babylon.mesh.ts 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895
  1. module BABYLON {
  2. export class _InstancesBatch {
  3. public mustReturn = false;
  4. public visibleInstances = new Array<Array<InstancedMesh>>();
  5. public renderSelf = new Array<boolean>();
  6. }
  7. export class Mesh extends AbstractMesh implements IGetSetVerticesData {
  8. // Consts
  9. public static _FRONTSIDE: number = 0;
  10. public static _BACKSIDE: number = 1;
  11. public static _DOUBLESIDE: number = 2;
  12. public static _DEFAULTSIDE: number = 0;
  13. public static _NO_CAP = 0;
  14. public static _CAP_START = 1;
  15. public static _CAP_END = 2;
  16. public static _CAP_ALL = 3;
  17. public static get FRONTSIDE(): number {
  18. return Mesh._FRONTSIDE;
  19. }
  20. public static get BACKSIDE(): number {
  21. return Mesh._BACKSIDE;
  22. }
  23. public static get DOUBLESIDE(): number {
  24. return Mesh._DOUBLESIDE;
  25. }
  26. public static get DEFAULTSIDE(): number {
  27. return Mesh._DEFAULTSIDE;
  28. }
  29. public static get NO_CAP(): number {
  30. return Mesh._NO_CAP;
  31. }
  32. public static get CAP_START(): number {
  33. return Mesh._CAP_START;
  34. }
  35. public static get CAP_END(): number {
  36. return Mesh._CAP_END;
  37. }
  38. public static get CAP_ALL(): number {
  39. return Mesh._CAP_ALL;
  40. }
  41. // Members
  42. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  43. public instances = new Array<InstancedMesh>();
  44. public delayLoadingFile: string;
  45. public _binaryInfo: any;
  46. private _LODLevels = new Array<Internals.MeshLODLevel>();
  47. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void;
  48. // Private
  49. public _geometry: Geometry;
  50. private _onBeforeRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  51. private _onAfterRenderCallbacks = new Array<(mesh: AbstractMesh) => void>();
  52. public _delayInfo; //ANY
  53. public _delayLoadingFunction: (any, Mesh) => void;
  54. public _visibleInstances: any = {};
  55. private _renderIdForInstances = new Array<number>();
  56. private _batchCache = new _InstancesBatch();
  57. private _worldMatricesInstancesBuffer: WebGLBuffer;
  58. private _worldMatricesInstancesArray: Float32Array;
  59. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  60. public _shouldGenerateFlatShading: boolean;
  61. private _preActivateId: number;
  62. private _sideOrientation: number = Mesh._DEFAULTSIDE;
  63. private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
  64. /**
  65. * @constructor
  66. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  67. * @param {Scene} scene - The scene to add this mesh to.
  68. * @param {Node} parent - The parent of this mesh, if it has one
  69. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  70. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  71. * When false, achieved by calling a clone(), also passing False.
  72. * This will make creation of children, recursive.
  73. */
  74. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
  75. super(name, scene);
  76. if (source) {
  77. // Geometry
  78. if (source._geometry) {
  79. source._geometry.applyToMesh(this);
  80. }
  81. // Deep copy
  82. Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  83. // Material
  84. this.material = source.material;
  85. if (!doNotCloneChildren) {
  86. // Children
  87. for (var index = 0; index < scene.meshes.length; index++) {
  88. var mesh = scene.meshes[index];
  89. if (mesh.parent === source) {
  90. // doNotCloneChildren is always going to be False
  91. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  92. }
  93. }
  94. }
  95. // Particles
  96. for (index = 0; index < scene.particleSystems.length; index++) {
  97. var system = scene.particleSystems[index];
  98. if (system.emitter === source) {
  99. system.clone(system.name, this);
  100. }
  101. }
  102. this.computeWorldMatrix(true);
  103. }
  104. // Parent
  105. if (parent !== null) {
  106. this.parent = parent;
  107. }
  108. }
  109. // Methods
  110. public get hasLODLevels(): boolean {
  111. return this._LODLevels.length > 0;
  112. }
  113. private _sortLODLevels(): void {
  114. this._LODLevels.sort((a, b) => {
  115. if (a.distance < b.distance) {
  116. return 1;
  117. }
  118. if (a.distance > b.distance) {
  119. return -1;
  120. }
  121. return 0;
  122. });
  123. }
  124. /**
  125. * Add a mesh as LOD level triggered at the given distance.
  126. * @param {number} distance - the distance from the center of the object to show this level
  127. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  128. * @return {BABYLON.Mesh} this mesh (for chaining)
  129. */
  130. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  131. if (mesh && mesh._masterMesh) {
  132. Tools.Warn("You cannot use a mesh as LOD level twice");
  133. return this;
  134. }
  135. var level = new Internals.MeshLODLevel(distance, mesh);
  136. this._LODLevels.push(level);
  137. if (mesh) {
  138. mesh._masterMesh = this;
  139. }
  140. this._sortLODLevels();
  141. return this;
  142. }
  143. public getLODLevelAtDistance(distance: number): Mesh {
  144. for (var index = 0; index < this._LODLevels.length; index++) {
  145. var level = this._LODLevels[index];
  146. if (level.distance === distance) {
  147. return level.mesh;
  148. }
  149. }
  150. return null;
  151. }
  152. /**
  153. * Remove a mesh from the LOD array
  154. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  155. * @return {BABYLON.Mesh} this mesh (for chaining)
  156. */
  157. public removeLODLevel(mesh: Mesh): Mesh {
  158. for (var index = 0; index < this._LODLevels.length; index++) {
  159. if (this._LODLevels[index].mesh === mesh) {
  160. this._LODLevels.splice(index, 1);
  161. if (mesh) {
  162. mesh._masterMesh = null;
  163. }
  164. }
  165. }
  166. this._sortLODLevels();
  167. return this;
  168. }
  169. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  170. if (!this._LODLevels || this._LODLevels.length === 0) {
  171. return this;
  172. }
  173. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  174. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  175. if (this.onLODLevelSelection) {
  176. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  177. }
  178. return this;
  179. }
  180. for (var index = 0; index < this._LODLevels.length; index++) {
  181. var level = this._LODLevels[index];
  182. if (level.distance < distanceToCamera) {
  183. if (level.mesh) {
  184. level.mesh._preActivate();
  185. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  186. }
  187. if (this.onLODLevelSelection) {
  188. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  189. }
  190. return level.mesh;
  191. }
  192. }
  193. if (this.onLODLevelSelection) {
  194. this.onLODLevelSelection(distanceToCamera, this, this);
  195. }
  196. return this;
  197. }
  198. public get geometry(): Geometry {
  199. return this._geometry;
  200. }
  201. public getTotalVertices(): number {
  202. if (!this._geometry) {
  203. return 0;
  204. }
  205. return this._geometry.getTotalVertices();
  206. }
  207. public getVerticesData(kind: string, copyWhenShared?: boolean): number[] {
  208. if (!this._geometry) {
  209. return null;
  210. }
  211. return this._geometry.getVerticesData(kind, copyWhenShared);
  212. }
  213. public getVertexBuffer(kind): VertexBuffer {
  214. if (!this._geometry) {
  215. return undefined;
  216. }
  217. return this._geometry.getVertexBuffer(kind);
  218. }
  219. public isVerticesDataPresent(kind: string): boolean {
  220. if (!this._geometry) {
  221. if (this._delayInfo) {
  222. return this._delayInfo.indexOf(kind) !== -1;
  223. }
  224. return false;
  225. }
  226. return this._geometry.isVerticesDataPresent(kind);
  227. }
  228. public getVerticesDataKinds(): string[] {
  229. if (!this._geometry) {
  230. var result = [];
  231. if (this._delayInfo) {
  232. for (var kind in this._delayInfo) {
  233. result.push(kind);
  234. }
  235. }
  236. return result;
  237. }
  238. return this._geometry.getVerticesDataKinds();
  239. }
  240. public getTotalIndices(): number {
  241. if (!this._geometry) {
  242. return 0;
  243. }
  244. return this._geometry.getTotalIndices();
  245. }
  246. public getIndices(copyWhenShared?: boolean): number[] {
  247. if (!this._geometry) {
  248. return [];
  249. }
  250. return this._geometry.getIndices(copyWhenShared);
  251. }
  252. public get isBlocked(): boolean {
  253. return this._masterMesh !== null && this._masterMesh !== undefined;
  254. }
  255. public isReady(): boolean {
  256. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  257. return false;
  258. }
  259. return super.isReady();
  260. }
  261. public isDisposed(): boolean {
  262. return this._isDisposed;
  263. }
  264. public get sideOrientation(): number {
  265. return this._sideOrientation;
  266. }
  267. public set sideOrientation(sideO: number) {
  268. this._sideOrientation = sideO;
  269. }
  270. public get areNormalsFrozen(): boolean {
  271. return this._areNormalsFrozen;
  272. }
  273. public freezeNormals(): void {
  274. this._areNormalsFrozen = true;
  275. }
  276. public unfreezeNormals(): void {
  277. this._areNormalsFrozen = false;
  278. }
  279. // Methods
  280. public _preActivate(): void {
  281. var sceneRenderId = this.getScene().getRenderId();
  282. if (this._preActivateId === sceneRenderId) {
  283. return;
  284. }
  285. this._preActivateId = sceneRenderId;
  286. this._visibleInstances = null;
  287. }
  288. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  289. if (!this._visibleInstances) {
  290. this._visibleInstances = {};
  291. this._visibleInstances.defaultRenderId = renderId;
  292. this._visibleInstances.selfDefaultRenderId = this._renderId;
  293. }
  294. if (!this._visibleInstances[renderId]) {
  295. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  296. }
  297. this._visibleInstances[renderId].push(instance);
  298. }
  299. public refreshBoundingInfo(): void {
  300. var data = this.getVerticesData(VertexBuffer.PositionKind);
  301. if (data) {
  302. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  303. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  304. }
  305. if (this.subMeshes) {
  306. for (var index = 0; index < this.subMeshes.length; index++) {
  307. this.subMeshes[index].refreshBoundingInfo();
  308. }
  309. }
  310. this._updateBoundingInfo();
  311. }
  312. public _createGlobalSubMesh(): SubMesh {
  313. var totalVertices = this.getTotalVertices();
  314. if (!totalVertices || !this.getIndices()) {
  315. return null;
  316. }
  317. this.releaseSubMeshes();
  318. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  319. }
  320. public subdivide(count: number): void {
  321. if (count < 1) {
  322. return;
  323. }
  324. var totalIndices = this.getTotalIndices();
  325. var subdivisionSize = (totalIndices / count) | 0;
  326. var offset = 0;
  327. // Ensure that subdivisionSize is a multiple of 3
  328. while (subdivisionSize % 3 !== 0) {
  329. subdivisionSize++;
  330. }
  331. this.releaseSubMeshes();
  332. for (var index = 0; index < count; index++) {
  333. if (offset >= totalIndices) {
  334. break;
  335. }
  336. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  337. offset += subdivisionSize;
  338. }
  339. this.synchronizeInstances();
  340. }
  341. public setVerticesData(kind: any, data: any, updatable?: boolean, stride?: number): void {
  342. if (kind instanceof Array) {
  343. var temp = data;
  344. data = kind;
  345. kind = temp;
  346. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  347. }
  348. if (!this._geometry) {
  349. var vertexData = new VertexData();
  350. vertexData.set(data, kind);
  351. var scene = this.getScene();
  352. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  353. }
  354. else {
  355. this._geometry.setVerticesData(kind, data, updatable, stride);
  356. }
  357. }
  358. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  359. if (!this._geometry) {
  360. return;
  361. }
  362. if (!makeItUnique) {
  363. this._geometry.updateVerticesData(kind, data, updateExtends);
  364. }
  365. else {
  366. this.makeGeometryUnique();
  367. this.updateVerticesData(kind, data, updateExtends, false);
  368. }
  369. }
  370. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  371. if (!this._geometry) {
  372. return;
  373. }
  374. if (!makeItUnique) {
  375. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  376. }
  377. else {
  378. this.makeGeometryUnique();
  379. this.updateVerticesDataDirectly(kind, data, offset, false);
  380. }
  381. }
  382. // Mesh positions update function :
  383. // updates the mesh positions according to the positionFunction returned values.
  384. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  385. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  386. public updateMeshPositions(positionFunction, computeNormals: boolean = true): void {
  387. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  388. positionFunction(positions);
  389. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  390. if (computeNormals) {
  391. var indices = this.getIndices();
  392. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  393. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  394. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  395. }
  396. }
  397. public makeGeometryUnique() {
  398. if (!this._geometry) {
  399. return;
  400. }
  401. var geometry = this._geometry.copy(Geometry.RandomId());
  402. geometry.applyToMesh(this);
  403. }
  404. public setIndices(indices: number[], totalVertices?: number): void {
  405. if (!this._geometry) {
  406. var vertexData = new VertexData();
  407. vertexData.indices = indices;
  408. var scene = this.getScene();
  409. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  410. }
  411. else {
  412. this._geometry.setIndices(indices, totalVertices);
  413. }
  414. }
  415. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  416. var engine = this.getScene().getEngine();
  417. // Wireframe
  418. var indexToBind;
  419. switch (fillMode) {
  420. case Material.PointFillMode:
  421. indexToBind = null;
  422. break;
  423. case Material.WireFrameFillMode:
  424. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  425. break;
  426. default:
  427. case Material.TriangleFillMode:
  428. indexToBind = this._geometry.getIndexBuffer();
  429. break;
  430. }
  431. // VBOs
  432. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  433. }
  434. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  435. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  436. return;
  437. }
  438. var engine = this.getScene().getEngine();
  439. // Draw order
  440. switch (fillMode) {
  441. case Material.PointFillMode:
  442. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  443. break;
  444. case Material.WireFrameFillMode:
  445. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  446. break;
  447. default:
  448. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  449. }
  450. }
  451. public registerBeforeRender(func: (mesh: AbstractMesh) => void): void {
  452. this._onBeforeRenderCallbacks.push(func);
  453. }
  454. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void {
  455. var index = this._onBeforeRenderCallbacks.indexOf(func);
  456. if (index > -1) {
  457. this._onBeforeRenderCallbacks.splice(index, 1);
  458. }
  459. }
  460. public registerAfterRender(func: (mesh: AbstractMesh) => void): void {
  461. this._onAfterRenderCallbacks.push(func);
  462. }
  463. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): void {
  464. var index = this._onAfterRenderCallbacks.indexOf(func);
  465. if (index > -1) {
  466. this._onAfterRenderCallbacks.splice(index, 1);
  467. }
  468. }
  469. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  470. var scene = this.getScene();
  471. this._batchCache.mustReturn = false;
  472. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  473. this._batchCache.visibleInstances[subMeshId] = null;
  474. if (this._visibleInstances) {
  475. var currentRenderId = scene.getRenderId();
  476. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  477. var selfRenderId = this._renderId;
  478. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  479. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  480. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  481. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  482. }
  483. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  484. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  485. this._batchCache.mustReturn = true;
  486. return this._batchCache;
  487. }
  488. if (currentRenderId !== selfRenderId) {
  489. this._batchCache.renderSelf[subMeshId] = false;
  490. }
  491. }
  492. this._renderIdForInstances[subMeshId] = currentRenderId;
  493. }
  494. return this._batchCache;
  495. }
  496. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  497. var visibleInstances = batch.visibleInstances[subMesh._id];
  498. var matricesCount = visibleInstances.length + 1;
  499. var bufferSize = matricesCount * 16 * 4;
  500. while (this._instancesBufferSize < bufferSize) {
  501. this._instancesBufferSize *= 2;
  502. }
  503. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  504. if (this._worldMatricesInstancesBuffer) {
  505. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  506. }
  507. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  508. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  509. }
  510. var offset = 0;
  511. var instancesCount = 0;
  512. var world = this.getWorldMatrix();
  513. if (batch.renderSelf[subMesh._id]) {
  514. world.copyToArray(this._worldMatricesInstancesArray, offset);
  515. offset += 16;
  516. instancesCount++;
  517. }
  518. if (visibleInstances) {
  519. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  520. var instance = visibleInstances[instanceIndex];
  521. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  522. offset += 16;
  523. instancesCount++;
  524. }
  525. }
  526. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  527. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  528. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  529. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  530. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  531. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  532. this._draw(subMesh, fillMode, instancesCount);
  533. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  534. }
  535. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  536. onBeforeDraw: (isInstance: boolean, world: Matrix) => void) {
  537. var scene = this.getScene();
  538. var engine = scene.getEngine();
  539. if (hardwareInstancedRendering) {
  540. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  541. } else {
  542. if (batch.renderSelf[subMesh._id]) {
  543. // Draw
  544. if (onBeforeDraw) {
  545. onBeforeDraw(false, this.getWorldMatrix());
  546. }
  547. this._draw(subMesh, fillMode);
  548. }
  549. if (batch.visibleInstances[subMesh._id]) {
  550. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  551. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  552. // World
  553. var world = instance.getWorldMatrix();
  554. if (onBeforeDraw) {
  555. onBeforeDraw(true, world);
  556. }
  557. // Draw
  558. this._draw(subMesh, fillMode);
  559. }
  560. }
  561. }
  562. }
  563. public render(subMesh: SubMesh): void {
  564. var scene = this.getScene();
  565. // Managing instances
  566. var batch = this._getInstancesRenderList(subMesh._id);
  567. if (batch.mustReturn) {
  568. return;
  569. }
  570. // Checking geometry state
  571. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  572. return;
  573. }
  574. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  575. this._onBeforeRenderCallbacks[callbackIndex](this);
  576. }
  577. var engine = scene.getEngine();
  578. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  579. // Material
  580. var effectiveMaterial = subMesh.getMaterial();
  581. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  582. return;
  583. }
  584. // Outline - step 1
  585. var savedDepthWrite = engine.getDepthWrite();
  586. if (this.renderOutline) {
  587. engine.setDepthWrite(false);
  588. scene.getOutlineRenderer().render(subMesh, batch);
  589. engine.setDepthWrite(savedDepthWrite);
  590. }
  591. effectiveMaterial._preBind();
  592. var effect = effectiveMaterial.getEffect();
  593. // Bind
  594. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  595. this._bind(subMesh, effect, fillMode);
  596. var world = this.getWorldMatrix();
  597. effectiveMaterial.bind(world, this);
  598. // Draw
  599. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering,
  600. (isInstance, world) => {
  601. if (isInstance) {
  602. effectiveMaterial.bindOnlyWorldMatrix(world);
  603. }
  604. });
  605. // Unbind
  606. effectiveMaterial.unbind();
  607. // Outline - step 2
  608. if (this.renderOutline && savedDepthWrite) {
  609. engine.setDepthWrite(true);
  610. engine.setColorWrite(false);
  611. scene.getOutlineRenderer().render(subMesh, batch);
  612. engine.setColorWrite(true);
  613. }
  614. // Overlay
  615. if (this.renderOverlay) {
  616. var currentMode = engine.getAlphaMode();
  617. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  618. scene.getOutlineRenderer().render(subMesh, batch, true);
  619. engine.setAlphaMode(currentMode);
  620. }
  621. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  622. this._onAfterRenderCallbacks[callbackIndex](this);
  623. }
  624. }
  625. public getEmittedParticleSystems(): ParticleSystem[] {
  626. var results = new Array<ParticleSystem>();
  627. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  628. var particleSystem = this.getScene().particleSystems[index];
  629. if (particleSystem.emitter === this) {
  630. results.push(particleSystem);
  631. }
  632. }
  633. return results;
  634. }
  635. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  636. var results = new Array<ParticleSystem>();
  637. var descendants = this.getDescendants();
  638. descendants.push(this);
  639. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  640. var particleSystem = this.getScene().particleSystems[index];
  641. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  642. results.push(particleSystem);
  643. }
  644. }
  645. return results;
  646. }
  647. public getChildren(): Node[] {
  648. var results = [];
  649. for (var index = 0; index < this.getScene().meshes.length; index++) {
  650. var mesh = this.getScene().meshes[index];
  651. if (mesh.parent === this) {
  652. results.push(mesh);
  653. }
  654. }
  655. return results;
  656. }
  657. public _checkDelayState(): void {
  658. var that = this;
  659. var scene = this.getScene();
  660. if (this._geometry) {
  661. this._geometry.load(scene);
  662. }
  663. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  664. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  665. scene._addPendingData(that);
  666. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  667. Tools.LoadFile(this.delayLoadingFile, data => {
  668. if (data instanceof ArrayBuffer) {
  669. this._delayLoadingFunction(data, this);
  670. }
  671. else {
  672. this._delayLoadingFunction(JSON.parse(data), this);
  673. }
  674. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  675. scene._removePendingData(this);
  676. },() => { }, scene.database, getBinaryData);
  677. }
  678. }
  679. public isInFrustum(frustumPlanes: Plane[]): boolean {
  680. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  681. return false;
  682. }
  683. if (!super.isInFrustum(frustumPlanes)) {
  684. return false;
  685. }
  686. this._checkDelayState();
  687. return true;
  688. }
  689. public setMaterialByID(id: string): void {
  690. var materials = this.getScene().materials;
  691. for (var index = 0; index < materials.length; index++) {
  692. if (materials[index].id === id) {
  693. this.material = materials[index];
  694. return;
  695. }
  696. }
  697. // Multi
  698. var multiMaterials = this.getScene().multiMaterials;
  699. for (index = 0; index < multiMaterials.length; index++) {
  700. if (multiMaterials[index].id === id) {
  701. this.material = multiMaterials[index];
  702. return;
  703. }
  704. }
  705. }
  706. public getAnimatables(): IAnimatable[] {
  707. var results = [];
  708. if (this.material) {
  709. results.push(this.material);
  710. }
  711. if (this.skeleton) {
  712. results.push(this.skeleton);
  713. }
  714. return results;
  715. }
  716. // Geometry
  717. public bakeTransformIntoVertices(transform: Matrix): void {
  718. // Position
  719. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  720. return;
  721. }
  722. this._resetPointsArrayCache();
  723. var data = this.getVerticesData(VertexBuffer.PositionKind);
  724. var temp = [];
  725. for (var index = 0; index < data.length; index += 3) {
  726. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  727. }
  728. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  729. // Normals
  730. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  731. return;
  732. }
  733. data = this.getVerticesData(VertexBuffer.NormalKind);
  734. temp = [];
  735. for (index = 0; index < data.length; index += 3) {
  736. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).toArray(temp, index);
  737. }
  738. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  739. }
  740. // Cache
  741. public _resetPointsArrayCache(): void {
  742. this._positions = null;
  743. }
  744. public _generatePointsArray(): boolean {
  745. if (this._positions)
  746. return true;
  747. this._positions = [];
  748. var data = this.getVerticesData(VertexBuffer.PositionKind);
  749. if (!data) {
  750. return false;
  751. }
  752. for (var index = 0; index < data.length; index += 3) {
  753. this._positions.push(Vector3.FromArray(data, index));
  754. }
  755. return true;
  756. }
  757. // Clone
  758. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh {
  759. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  760. }
  761. // Dispose
  762. public dispose(doNotRecurse?: boolean): void {
  763. if (this._geometry) {
  764. this._geometry.releaseForMesh(this, true);
  765. }
  766. // Instances
  767. if (this._worldMatricesInstancesBuffer) {
  768. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  769. this._worldMatricesInstancesBuffer = null;
  770. }
  771. while (this.instances.length) {
  772. this.instances[0].dispose();
  773. }
  774. super.dispose(doNotRecurse);
  775. }
  776. // Geometric tools
  777. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  778. var scene = this.getScene();
  779. var onload = img => {
  780. // Getting height map data
  781. var canvas = document.createElement("canvas");
  782. var context = canvas.getContext("2d");
  783. var heightMapWidth = img.width;
  784. var heightMapHeight = img.height;
  785. canvas.width = heightMapWidth;
  786. canvas.height = heightMapHeight;
  787. context.drawImage(img, 0, 0);
  788. // Create VertexData from map data
  789. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  790. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  791. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  792. //execute success callback, if set
  793. if (onSuccess) {
  794. onSuccess(this);
  795. }
  796. };
  797. Tools.LoadImage(url, onload,() => { }, scene.database);
  798. }
  799. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  800. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  801. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  802. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  803. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  804. return;
  805. }
  806. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  807. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  808. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  809. var position = Vector3.Zero();
  810. var normal = Vector3.Zero();
  811. var uv = Vector2.Zero();
  812. for (var index = 0; index < positions.length; index += 3) {
  813. Vector3.FromArrayToRef(positions, index, position);
  814. Vector3.FromArrayToRef(normals, index, normal);
  815. Vector2.FromArrayToRef(uvs,(index / 3) * 2, uv);
  816. // Compute height
  817. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  818. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  819. var pos = (u + v * heightMapWidth) * 4;
  820. var r = buffer[pos] / 255.0;
  821. var g = buffer[pos + 1] / 255.0;
  822. var b = buffer[pos + 2] / 255.0;
  823. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  824. normal.normalize();
  825. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  826. position = position.add(normal);
  827. position.toArray(positions, index);
  828. }
  829. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  830. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  831. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  832. }
  833. public convertToFlatShadedMesh(): void {
  834. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  835. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  836. var kinds = this.getVerticesDataKinds();
  837. var vbs = [];
  838. var data = [];
  839. var newdata = [];
  840. var updatableNormals = false;
  841. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  842. var kind = kinds[kindIndex];
  843. var vertexBuffer = this.getVertexBuffer(kind);
  844. if (kind === VertexBuffer.NormalKind) {
  845. updatableNormals = vertexBuffer.isUpdatable();
  846. kinds.splice(kindIndex, 1);
  847. kindIndex--;
  848. continue;
  849. }
  850. vbs[kind] = vertexBuffer;
  851. data[kind] = vbs[kind].getData();
  852. newdata[kind] = [];
  853. }
  854. // Save previous submeshes
  855. var previousSubmeshes = this.subMeshes.slice(0);
  856. var indices = this.getIndices();
  857. var totalIndices = this.getTotalIndices();
  858. // Generating unique vertices per face
  859. for (var index = 0; index < totalIndices; index++) {
  860. var vertexIndex = indices[index];
  861. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  862. kind = kinds[kindIndex];
  863. var stride = vbs[kind].getStrideSize();
  864. for (var offset = 0; offset < stride; offset++) {
  865. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  866. }
  867. }
  868. }
  869. // Updating faces & normal
  870. var normals = [];
  871. var positions = newdata[VertexBuffer.PositionKind];
  872. for (index = 0; index < totalIndices; index += 3) {
  873. indices[index] = index;
  874. indices[index + 1] = index + 1;
  875. indices[index + 2] = index + 2;
  876. var p1 = Vector3.FromArray(positions, index * 3);
  877. var p2 = Vector3.FromArray(positions,(index + 1) * 3);
  878. var p3 = Vector3.FromArray(positions,(index + 2) * 3);
  879. var p1p2 = p1.subtract(p2);
  880. var p3p2 = p3.subtract(p2);
  881. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  882. // Store same normals for every vertex
  883. for (var localIndex = 0; localIndex < 3; localIndex++) {
  884. normals.push(normal.x);
  885. normals.push(normal.y);
  886. normals.push(normal.z);
  887. }
  888. }
  889. this.setIndices(indices);
  890. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  891. // Updating vertex buffers
  892. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  893. kind = kinds[kindIndex];
  894. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  895. }
  896. // Updating submeshes
  897. this.releaseSubMeshes();
  898. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  899. var previousOne = previousSubmeshes[submeshIndex];
  900. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  901. }
  902. this.synchronizeInstances();
  903. }
  904. // Instances
  905. public createInstance(name: string): InstancedMesh {
  906. return new InstancedMesh(name, this);
  907. }
  908. public synchronizeInstances(): void {
  909. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  910. var instance = this.instances[instanceIndex];
  911. instance._syncSubMeshes();
  912. }
  913. }
  914. /**
  915. * Simplify the mesh according to the given array of settings.
  916. * Function will return immediately and will simplify async.
  917. * @param settings a collection of simplification settings.
  918. * @param parallelProcessing should all levels calculate parallel or one after the other.
  919. * @param type the type of simplification to run.
  920. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  921. */
  922. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void) {
  923. this.getScene().simplificationQueue.addTask({
  924. settings: settings,
  925. parallelProcessing: parallelProcessing,
  926. mesh: this,
  927. simplificationType: simplificationType,
  928. successCallback: successCallback
  929. });
  930. }
  931. /**
  932. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  933. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  934. * This should be used together with the simplification to avoid disappearing triangles.
  935. * @param successCallback an optional success callback to be called after the optimization finished.
  936. */
  937. public optimizeIndices(successCallback?: (mesh?: Mesh) => void) {
  938. var indices = this.getIndices();
  939. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  940. var vectorPositions = [];
  941. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  942. vectorPositions.push(Vector3.FromArray(positions, pos));
  943. }
  944. var dupes = [];
  945. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40,(iteration) => {
  946. var realPos = vectorPositions.length - 1 - iteration;
  947. var testedPosition = vectorPositions[realPos];
  948. for (var j = 0; j < realPos; ++j) {
  949. var againstPosition = vectorPositions[j];
  950. if (testedPosition.equals(againstPosition)) {
  951. dupes[realPos] = j;
  952. break;
  953. }
  954. }
  955. },() => {
  956. for (var i = 0; i < indices.length; ++i) {
  957. indices[i] = dupes[indices[i]] || indices[i];
  958. }
  959. //indices are now reordered
  960. var originalSubMeshes = this.subMeshes.slice(0);
  961. this.setIndices(indices);
  962. this.subMeshes = originalSubMeshes;
  963. if (successCallback) {
  964. successCallback(this);
  965. }
  966. });
  967. }
  968. // Statics
  969. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, ribbonInstance: Mesh = null): Mesh {
  970. if (ribbonInstance) { // existing ribbon instance update
  971. // positionFunction : ribbon case
  972. // only pathArray and sideOrientation parameters are taken into account for positions update
  973. var positionsOfRibbon = function (pathArray, sideOrientation) {
  974. var positionFunction = function (positions) {
  975. var minlg = pathArray[0].length;
  976. var i = 0;
  977. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  978. for (var si = 1; si <= ns; si++) {
  979. for (var p = 0; p < pathArray.length; p++) {
  980. var path = pathArray[p];
  981. var l = path.length;
  982. minlg = (minlg < l) ? minlg : l;
  983. var j = 0;
  984. while (j < minlg) {
  985. positions[i] = path[j].x;
  986. positions[i + 1] = path[j].y;
  987. positions[i + 2] = path[j].z;
  988. j++;
  989. i += 3;
  990. }
  991. }
  992. }
  993. };
  994. return positionFunction;
  995. };
  996. var sideOrientation = ribbonInstance.sideOrientation;
  997. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  998. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  999. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  1000. return ribbonInstance;
  1001. }
  1002. else { // new ribbon creation
  1003. var ribbon = new Mesh(name, scene);
  1004. ribbon.sideOrientation = sideOrientation;
  1005. var vertexData = VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  1006. vertexData.applyToMesh(ribbon, updatable);
  1007. return ribbon;
  1008. }
  1009. }
  1010. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1011. var disc = new Mesh(name, scene);
  1012. var vertexData = VertexData.CreateDisc(radius, tessellation, sideOrientation);
  1013. vertexData.applyToMesh(disc, updatable);
  1014. return disc;
  1015. }
  1016. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1017. var box = new Mesh(name, scene);
  1018. var vertexData = VertexData.CreateBox(size, sideOrientation);
  1019. vertexData.applyToMesh(box, updatable);
  1020. return box;
  1021. }
  1022. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1023. var sphere = new Mesh(name, scene);
  1024. var vertexData = VertexData.CreateSphere(segments, diameter, sideOrientation);
  1025. vertexData.applyToMesh(sphere, updatable);
  1026. return sphere;
  1027. }
  1028. // Cylinder and cone (Code inspired by SharpDX.org)
  1029. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1030. // subdivisions is a new parameter, we need to support old signature
  1031. if (scene === undefined || !(scene instanceof Scene)) {
  1032. if (scene !== undefined) {
  1033. updatable = scene;
  1034. }
  1035. scene = <Scene>subdivisions;
  1036. subdivisions = 1;
  1037. }
  1038. var cylinder = new Mesh(name, scene);
  1039. var vertexData = VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  1040. vertexData.applyToMesh(cylinder, updatable);
  1041. return cylinder;
  1042. }
  1043. // Torus (Code from SharpDX.org)
  1044. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1045. var torus = new Mesh(name, scene);
  1046. var vertexData = VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  1047. vertexData.applyToMesh(torus, updatable);
  1048. return torus;
  1049. }
  1050. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1051. var torusKnot = new Mesh(name, scene);
  1052. var vertexData = VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  1053. vertexData.applyToMesh(torusKnot, updatable);
  1054. return torusKnot;
  1055. }
  1056. // Lines
  1057. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, linesInstance: LinesMesh = null): LinesMesh {
  1058. if (linesInstance) { // lines update
  1059. var positionsOfLines = function (points) {
  1060. var positionFunction = function (positions) {
  1061. var i = 0;
  1062. for (var p = 0; p < points.length; p++) {
  1063. positions[i] = points[p].x;
  1064. positions[i + 1] = points[p].y;
  1065. positions[i + 2] = points[p].z;
  1066. i += 3;
  1067. }
  1068. };
  1069. return positionFunction;
  1070. };
  1071. var positionFunction = positionsOfLines(points);
  1072. linesInstance.updateMeshPositions(positionFunction, false);
  1073. return linesInstance;
  1074. }
  1075. // lines creation
  1076. var lines = new LinesMesh(name, scene, updatable);
  1077. var vertexData = VertexData.CreateLines(points);
  1078. vertexData.applyToMesh(lines, updatable);
  1079. return lines;
  1080. }
  1081. // Extrusion
  1082. public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, extrudedInstance: Mesh = null): Mesh {
  1083. scale = scale || 1;
  1084. rotation = rotation || 0;
  1085. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  1086. return extruded;
  1087. }
  1088. public static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction, rotationFunction, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, extrudedInstance: Mesh = null): Mesh {
  1089. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  1090. return extrudedCustom;
  1091. }
  1092. private static _ExtrudeShapeGeneric(name: string, shape: Vector3[], curve: Vector3[], scale: number, rotation: number, scaleFunction: { (i: number, distance: number): number; }, rotateFunction: { (i: number, distance: number): number; }, rbCA: boolean, rbCP: boolean, cap: number, custom: boolean, scene: Scene, updtbl: boolean, side: number, instance: Mesh): Mesh {
  1093. // extrusion geometry
  1094. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  1095. var tangents = path3D.getTangents();
  1096. var normals = path3D.getNormals();
  1097. var binormals = path3D.getBinormals();
  1098. var distances = path3D.getDistances();
  1099. var angle = 0;
  1100. var returnScale: { (i: number, distance: number): number; } = (i, distance) => { return scale; };
  1101. var returnRotation: { (i: number, distance: number): number; } = (i, distance) => { return rotation; };
  1102. var rotate: { (i: number, distance: number): number; } = custom ? rotateFunction : returnRotation;
  1103. var scl: { (i: number, distance: number): number; } = custom ? scaleFunction : returnScale;
  1104. var index = 0;
  1105. for (var i = 0; i < curve.length; i++) {
  1106. var shapePath = new Array<Vector3>();
  1107. var angleStep = rotate(i, distances[i]);
  1108. var scaleRatio = scl(i, distances[i]);
  1109. for (var p = 0; p < shape.length; p++) {
  1110. var rotationMatrix = Matrix.RotationAxis(tangents[i], angle);
  1111. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  1112. var rotated = Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  1113. shapePath.push(rotated);
  1114. }
  1115. shapePaths[index] = shapePath;
  1116. angle += angleStep;
  1117. index++;
  1118. }
  1119. // cap
  1120. var capPath = function (shapePath) {
  1121. var pointCap = Array<Vector3>();
  1122. var barycenter = Vector3.Zero();
  1123. var i: number;
  1124. for (i = 0; i < shapePath.length; i++) {
  1125. barycenter.addInPlace(shapePath[i]);
  1126. }
  1127. barycenter.scaleInPlace(1 / shapePath.length);
  1128. for (i = 0; i < shapePath.length; i++) {
  1129. pointCap.push(barycenter);
  1130. }
  1131. return pointCap;
  1132. };
  1133. switch (cap) {
  1134. case BABYLON.Mesh.NO_CAP:
  1135. break;
  1136. case BABYLON.Mesh.CAP_START:
  1137. shapePaths.unshift(capPath(shapePaths[0]));
  1138. break;
  1139. case BABYLON.Mesh.CAP_END:
  1140. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1141. break;
  1142. case BABYLON.Mesh.CAP_ALL:
  1143. shapePaths.unshift(capPath(shapePaths[0]));
  1144. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  1145. break;
  1146. default:
  1147. break;
  1148. }
  1149. return shapePaths;
  1150. };
  1151. if (instance) { // instance update
  1152. var path3D = ((<any>instance).path3D).update(curve);
  1153. var pathArray = extrusionPathArray(shape, curve,(<any>instance).path3D,(<any>instance).pathArray, scale, rotation, scaleFunction, rotateFunction,(<any>instance).cap, custom);
  1154. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  1155. return instance;
  1156. }
  1157. // extruded shape creation
  1158. var path3D = <any>new Path3D(curve);
  1159. var newShapePaths = new Array<Array<Vector3>>();
  1160. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1161. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  1162. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  1163. (<any>extrudedGeneric).pathArray = pathArray;
  1164. (<any>extrudedGeneric).path3D = path3D;
  1165. (<any>extrudedGeneric).cap = cap;
  1166. return extrudedGeneric;
  1167. }
  1168. // Plane & ground
  1169. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE): Mesh {
  1170. var plane = new Mesh(name, scene);
  1171. var vertexData = VertexData.CreatePlane(size, sideOrientation);
  1172. vertexData.applyToMesh(plane, updatable);
  1173. return plane;
  1174. }
  1175. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  1176. var ground = new GroundMesh(name, scene);
  1177. ground._setReady(false);
  1178. ground._subdivisions = subdivisions;
  1179. var vertexData = VertexData.CreateGround(width, height, subdivisions);
  1180. vertexData.applyToMesh(ground, updatable);
  1181. ground._setReady(true);
  1182. return ground;
  1183. }
  1184. public static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { w: number; h: number; }, precision: { w: number; h: number; }, scene: Scene, updatable?: boolean): Mesh {
  1185. var tiledGround = new Mesh(name, scene);
  1186. var vertexData = VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  1187. vertexData.applyToMesh(tiledGround, updatable);
  1188. return tiledGround;
  1189. }
  1190. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh {
  1191. var ground = new GroundMesh(name, scene);
  1192. ground._subdivisions = subdivisions;
  1193. ground._setReady(false);
  1194. var onload = img => {
  1195. // Getting height map data
  1196. var canvas = document.createElement("canvas");
  1197. var context = canvas.getContext("2d");
  1198. var heightMapWidth = img.width;
  1199. var heightMapHeight = img.height;
  1200. canvas.width = heightMapWidth;
  1201. canvas.height = heightMapHeight;
  1202. context.drawImage(img, 0, 0);
  1203. // Create VertexData from map data
  1204. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1205. var buffer = <Uint8Array> (<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1206. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  1207. vertexData.applyToMesh(ground, updatable);
  1208. ground._setReady(true);
  1209. //execute ready callback, if set
  1210. if (onReady) {
  1211. onReady(ground);
  1212. }
  1213. };
  1214. Tools.LoadImage(url, onload,() => { }, scene.database);
  1215. return ground;
  1216. }
  1217. public static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { (i: number, distance: number): number; }, cap: number, scene: Scene, updatable?: boolean, sideOrientation: number = Mesh.DEFAULTSIDE, tubeInstance: Mesh = null): Mesh {
  1218. // tube geometry
  1219. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  1220. var tangents = path3D.getTangents();
  1221. var normals = path3D.getNormals();
  1222. var distances = path3D.getDistances();
  1223. var pi2 = Math.PI * 2;
  1224. var step = pi2 / tessellation;
  1225. var returnRadius: { (i: number, distance: number): number; } = (i, distance) => radius;
  1226. var radiusFunctionFinal: { (i: number, distance: number): number; } = radiusFunction || returnRadius;
  1227. var circlePath: Vector3[];
  1228. var rad: number;
  1229. var normal: Vector3;
  1230. var rotated: Vector3;
  1231. var rotationMatrix: Matrix;
  1232. var index = 0;
  1233. for (var i = 0; i < path.length; i++) {
  1234. rad = radiusFunctionFinal(i, distances[i]); // current radius
  1235. circlePath = Array<Vector3>(); // current circle array
  1236. normal = normals[i]; // current normal
  1237. for (var t = 0; t < tessellation; t++) {
  1238. rotationMatrix = Matrix.RotationAxis(tangents[i], step * t);
  1239. rotated = Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  1240. circlePath.push(rotated);
  1241. }
  1242. circlePath.push(circlePath[0]);
  1243. circlePaths[index] = circlePath;
  1244. index++;
  1245. }
  1246. // cap
  1247. var capPath = function (nbPoints, pathIndex) {
  1248. var pointCap = Array<Vector3>();
  1249. for (var i = 0; i < nbPoints; i++) {
  1250. pointCap.push(path[pathIndex]);
  1251. }
  1252. return pointCap;
  1253. };
  1254. switch (cap) {
  1255. case BABYLON.Mesh.NO_CAP:
  1256. break;
  1257. case BABYLON.Mesh.CAP_START:
  1258. circlePaths.unshift(capPath(tessellation + 1, 0));
  1259. break;
  1260. case BABYLON.Mesh.CAP_END:
  1261. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1262. break;
  1263. case BABYLON.Mesh.CAP_ALL:
  1264. circlePaths.unshift(capPath(tessellation + 1, 0));
  1265. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  1266. break;
  1267. default:
  1268. break;
  1269. }
  1270. return circlePaths;
  1271. };
  1272. if (tubeInstance) { // tube update
  1273. var path3D = ((<any>tubeInstance).path3D).update(path);
  1274. var pathArray = tubePathArray(path, path3D,(<any>tubeInstance).pathArray, radius,(<any>tubeInstance).tessellation, radiusFunction,(<any>tubeInstance).cap);
  1275. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  1276. return tubeInstance;
  1277. }
  1278. // tube creation
  1279. var path3D = <any>new Path3D(path);
  1280. var newPathArray = new Array<Array<Vector3>>();
  1281. cap = (cap < 0 || cap > 3) ? 0 : cap;
  1282. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  1283. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  1284. (<any>tube).pathArray = pathArray;
  1285. (<any>tube).path3D = path3D;
  1286. (<any>tube).tessellation = tessellation;
  1287. (<any>tube).cap = cap;
  1288. return tube;
  1289. }
  1290. // Decals
  1291. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number = 0) {
  1292. var indices = sourceMesh.getIndices();
  1293. var positions = sourceMesh.getVerticesData(VertexBuffer.PositionKind);
  1294. var normals = sourceMesh.getVerticesData(VertexBuffer.NormalKind);
  1295. // Getting correct rotation
  1296. if (!normal) {
  1297. var target = new Vector3(0, 0, 1);
  1298. var camera = sourceMesh.getScene().activeCamera;
  1299. var cameraWorldTarget = Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  1300. normal = camera.globalPosition.subtract(cameraWorldTarget);
  1301. }
  1302. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  1303. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  1304. var pitch = Math.atan2(normal.y, len);
  1305. // Matrix
  1306. var decalWorldMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(Matrix.Translation(position.x, position.y, position.z));
  1307. var inverseDecalWorldMatrix = Matrix.Invert(decalWorldMatrix);
  1308. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  1309. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  1310. var vertexData = new VertexData();
  1311. vertexData.indices = [];
  1312. vertexData.positions = [];
  1313. vertexData.normals = [];
  1314. vertexData.uvs = [];
  1315. var currentVertexDataIndex = 0;
  1316. var extractDecalVector3 = (indexId: number): PositionNormalVertex => {
  1317. var vertexId = indices[indexId];
  1318. var result = new PositionNormalVertex();
  1319. result.position = new Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  1320. // Send vector to decal local world
  1321. result.position = Vector3.TransformCoordinates(result.position, transformMatrix);
  1322. // Get normal
  1323. result.normal = new Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  1324. return result;
  1325. }
  1326. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  1327. var clip = (vertices: PositionNormalVertex[], axis: Vector3): PositionNormalVertex[]=> {
  1328. if (vertices.length === 0) {
  1329. return vertices;
  1330. }
  1331. var clipSize = 0.5 * Math.abs(Vector3.Dot(size, axis));
  1332. var clipVertices = (v0: PositionNormalVertex, v1: PositionNormalVertex): PositionNormalVertex => {
  1333. var clipFactor = Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  1334. return new PositionNormalVertex(
  1335. Vector3.Lerp(v0.position, v1.position, clipFactor),
  1336. Vector3.Lerp(v0.normal, v1.normal, clipFactor)
  1337. );
  1338. }
  1339. var result = new Array<PositionNormalVertex>();
  1340. for (var index = 0; index < vertices.length; index += 3) {
  1341. var v1Out: boolean;
  1342. var v2Out: boolean;
  1343. var v3Out: boolean;
  1344. var total = 0;
  1345. var nV1: PositionNormalVertex, nV2: PositionNormalVertex, nV3: PositionNormalVertex, nV4: PositionNormalVertex;
  1346. var d1 = Vector3.Dot(vertices[index].position, axis) - clipSize;
  1347. var d2 = Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  1348. var d3 = Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  1349. v1Out = d1 > 0;
  1350. v2Out = d2 > 0;
  1351. v3Out = d3 > 0;
  1352. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  1353. switch (total) {
  1354. case 0:
  1355. result.push(vertices[index]);
  1356. result.push(vertices[index + 1]);
  1357. result.push(vertices[index + 2]);
  1358. break;
  1359. case 1:
  1360. if (v1Out) {
  1361. nV1 = vertices[index + 1];
  1362. nV2 = vertices[index + 2];
  1363. nV3 = clipVertices(vertices[index], nV1);
  1364. nV4 = clipVertices(vertices[index], nV2);
  1365. }
  1366. if (v2Out) {
  1367. nV1 = vertices[index];
  1368. nV2 = vertices[index + 2];
  1369. nV3 = clipVertices(vertices[index + 1], nV1);
  1370. nV4 = clipVertices(vertices[index + 1], nV2);
  1371. result.push(nV3);
  1372. result.push(nV2.clone());
  1373. result.push(nV1.clone());
  1374. result.push(nV2.clone());
  1375. result.push(nV3.clone());
  1376. result.push(nV4);
  1377. break;
  1378. }
  1379. if (v3Out) {
  1380. nV1 = vertices[index];
  1381. nV2 = vertices[index + 1];
  1382. nV3 = clipVertices(vertices[index + 2], nV1);
  1383. nV4 = clipVertices(vertices[index + 2], nV2);
  1384. }
  1385. result.push(nV1.clone());
  1386. result.push(nV2.clone());
  1387. result.push(nV3);
  1388. result.push(nV4);
  1389. result.push(nV3.clone());
  1390. result.push(nV2.clone());
  1391. break;
  1392. case 2:
  1393. if (!v1Out) {
  1394. nV1 = vertices[index].clone();
  1395. nV2 = clipVertices(nV1, vertices[index + 1]);
  1396. nV3 = clipVertices(nV1, vertices[index + 2]);
  1397. result.push(nV1);
  1398. result.push(nV2);
  1399. result.push(nV3);
  1400. }
  1401. if (!v2Out) {
  1402. nV1 = vertices[index + 1].clone();
  1403. nV2 = clipVertices(nV1, vertices[index + 2]);
  1404. nV3 = clipVertices(nV1, vertices[index]);
  1405. result.push(nV1);
  1406. result.push(nV2);
  1407. result.push(nV3);
  1408. }
  1409. if (!v3Out) {
  1410. nV1 = vertices[index + 2].clone();
  1411. nV2 = clipVertices(nV1, vertices[index]);
  1412. nV3 = clipVertices(nV1, vertices[index + 1]);
  1413. result.push(nV1);
  1414. result.push(nV2);
  1415. result.push(nV3);
  1416. }
  1417. break;
  1418. case 3:
  1419. break;
  1420. }
  1421. }
  1422. return result;
  1423. }
  1424. for (var index = 0; index < indices.length; index += 3) {
  1425. var faceVertices = new Array<PositionNormalVertex>();
  1426. faceVertices.push(extractDecalVector3(index));
  1427. faceVertices.push(extractDecalVector3(index + 1));
  1428. faceVertices.push(extractDecalVector3(index + 2));
  1429. // Clip
  1430. faceVertices = clip(faceVertices, new Vector3(1, 0, 0));
  1431. faceVertices = clip(faceVertices, new Vector3(-1, 0, 0));
  1432. faceVertices = clip(faceVertices, new Vector3(0, 1, 0));
  1433. faceVertices = clip(faceVertices, new Vector3(0, -1, 0));
  1434. faceVertices = clip(faceVertices, new Vector3(0, 0, 1));
  1435. faceVertices = clip(faceVertices, new Vector3(0, 0, -1));
  1436. if (faceVertices.length === 0) {
  1437. continue;
  1438. }
  1439. // Add UVs and get back to world
  1440. var localRotationMatrix = Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  1441. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  1442. var vertex = faceVertices[vIndex];
  1443. vertexData.indices.push(currentVertexDataIndex);
  1444. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  1445. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  1446. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  1447. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  1448. currentVertexDataIndex++;
  1449. }
  1450. }
  1451. // Return mesh
  1452. var decal = new Mesh(name, sourceMesh.getScene());
  1453. vertexData.applyToMesh(decal);
  1454. decal.position = position.clone();
  1455. decal.rotation = new Vector3(pitch, yaw, angle);
  1456. return decal;
  1457. }
  1458. // Tools
  1459. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  1460. var minVector: Vector3 = null;
  1461. var maxVector: Vector3 = null;
  1462. for (var i in meshes) {
  1463. var mesh = meshes[i];
  1464. var boundingBox = mesh.getBoundingInfo().boundingBox;
  1465. if (!minVector) {
  1466. minVector = boundingBox.minimumWorld;
  1467. maxVector = boundingBox.maximumWorld;
  1468. continue;
  1469. }
  1470. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  1471. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  1472. }
  1473. return {
  1474. min: minVector,
  1475. max: maxVector
  1476. };
  1477. }
  1478. public static Center(meshesOrMinMaxVector): Vector3 {
  1479. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  1480. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  1481. }
  1482. /**
  1483. * Merge the array of meshes into a single mesh for performance reasons.
  1484. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  1485. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  1486. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  1487. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  1488. */
  1489. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh {
  1490. if (!allow32BitsIndices) {
  1491. var totalVertices = 0;
  1492. // Counting vertices
  1493. for (var index = 0; index < meshes.length; index++) {
  1494. if (meshes[index]) {
  1495. totalVertices += meshes[index].getTotalVertices();
  1496. if (totalVertices > 65536) {
  1497. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  1498. return null;
  1499. }
  1500. }
  1501. }
  1502. }
  1503. // Merge
  1504. var vertexData: VertexData;
  1505. var otherVertexData: VertexData;
  1506. var source: Mesh;
  1507. for (index = 0; index < meshes.length; index++) {
  1508. if (meshes[index]) {
  1509. otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
  1510. otherVertexData.transform(meshes[index].getWorldMatrix());
  1511. if (vertexData) {
  1512. vertexData.merge(otherVertexData);
  1513. } else {
  1514. vertexData = otherVertexData;
  1515. source = meshes[index];
  1516. }
  1517. }
  1518. }
  1519. if (!meshSubclass) {
  1520. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  1521. }
  1522. vertexData.applyToMesh(meshSubclass);
  1523. // Setting properties
  1524. meshSubclass.material = source.material;
  1525. meshSubclass.checkCollisions = source.checkCollisions;
  1526. // Cleaning
  1527. if (disposeSource) {
  1528. for (index = 0; index < meshes.length; index++) {
  1529. if (meshes[index]) {
  1530. meshes[index].dispose();
  1531. }
  1532. }
  1533. }
  1534. return meshSubclass;
  1535. }
  1536. }
  1537. }