babylon.mesh.ts 65 KB

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