babylon.mesh.ts 81 KB

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