babylon.mesh.ts 96 KB

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