babylon.mesh.ts 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  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. // Members
  9. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  10. public instances = new Array<InstancedMesh>();
  11. public delayLoadingFile: string;
  12. public _binaryInfo: any;
  13. private _LODLevels = new Array<Internals.MeshLODLevel>();
  14. // Private
  15. public _geometry: Geometry;
  16. private _onBeforeRenderCallbacks = new Array<() => void>();
  17. private _onAfterRenderCallbacks = new Array<() => void>();
  18. public _delayInfo; //ANY
  19. public _delayLoadingFunction: (any, Mesh) => void;
  20. public _visibleInstances: any = {};
  21. private _renderIdForInstances = new Array<number>();
  22. private _batchCache = new _InstancesBatch();
  23. private _worldMatricesInstancesBuffer: WebGLBuffer;
  24. private _worldMatricesInstancesArray: Float32Array;
  25. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26. public _shouldGenerateFlatShading: boolean;
  27. private _preActivateId: number;
  28. /**
  29. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  30. * @param {Scene} scene - The scene to add this mesh to.
  31. * @param {Node} parent - The parent of this mesh, if it has one
  32. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  33. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  34. * When false, achieved by calling a clone(), also passing False.
  35. * This will make creation of children, recursive.
  36. */
  37. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
  38. super(name, scene);
  39. if (source) {
  40. // Geometry
  41. if (source._geometry) {
  42. source._geometry.applyToMesh(this);
  43. }
  44. // Deep copy
  45. Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  46. // Material
  47. this.material = source.material;
  48. if (!doNotCloneChildren) {
  49. // Children
  50. for (var index = 0; index < scene.meshes.length; index++) {
  51. var mesh = scene.meshes[index];
  52. if (mesh.parent === source) {
  53. // doNotCloneChildren is always going to be False
  54. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  55. }
  56. }
  57. }
  58. // Particles
  59. for (index = 0; index < scene.particleSystems.length; index++) {
  60. var system = scene.particleSystems[index];
  61. if (system.emitter === source) {
  62. system.clone(system.name, this);
  63. }
  64. }
  65. this.computeWorldMatrix(true);
  66. }
  67. // Parent
  68. if (parent !== null) {
  69. this.parent = parent;
  70. }
  71. }
  72. private _clone() {
  73. }
  74. // Methods
  75. public get hasLODLevels(): boolean {
  76. return this._LODLevels.length > 0;
  77. }
  78. private _sortLODLevels(): void {
  79. this._LODLevels.sort((a, b) => {
  80. if (a.distance < b.distance) {
  81. return 1;
  82. }
  83. if (a.distance > b.distance) {
  84. return -1;
  85. }
  86. return 0;
  87. });
  88. }
  89. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  90. if (mesh && mesh._masterMesh) {
  91. Tools.Warn("You cannot use a mesh as LOD level twice");
  92. return this;
  93. }
  94. var level = new Internals.MeshLODLevel(distance, mesh);
  95. this._LODLevels.push(level);
  96. if (mesh) {
  97. mesh._masterMesh = this;
  98. }
  99. this._sortLODLevels();
  100. return this;
  101. }
  102. public removeLODLevel(mesh: Mesh): Mesh {
  103. for (var index = 0; index < this._LODLevels.length; index++) {
  104. if (this._LODLevels[index].mesh === mesh) {
  105. this._LODLevels.splice(index, 1);
  106. if (mesh) {
  107. mesh._masterMesh = null;
  108. }
  109. }
  110. }
  111. this._sortLODLevels();
  112. return this;
  113. }
  114. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  115. if (!this._LODLevels || this._LODLevels.length === 0) {
  116. return this;
  117. }
  118. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  119. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  120. return this;
  121. }
  122. for (var index = 0; index < this._LODLevels.length; index++) {
  123. var level = this._LODLevels[index];
  124. if (level.distance < distanceToCamera) {
  125. if (level.mesh) {
  126. level.mesh._preActivate();
  127. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  128. }
  129. return level.mesh;
  130. }
  131. }
  132. return this;
  133. }
  134. public get geometry(): Geometry {
  135. return this._geometry;
  136. }
  137. public getTotalVertices(): number {
  138. if (!this._geometry) {
  139. return 0;
  140. }
  141. return this._geometry.getTotalVertices();
  142. }
  143. public getVerticesData(kind: string): number[] {
  144. if (!this._geometry) {
  145. return null;
  146. }
  147. return this._geometry.getVerticesData(kind);
  148. }
  149. public getVertexBuffer(kind): VertexBuffer {
  150. if (!this._geometry) {
  151. return undefined;
  152. }
  153. return this._geometry.getVertexBuffer(kind);
  154. }
  155. public isVerticesDataPresent(kind: string): boolean {
  156. if (!this._geometry) {
  157. if (this._delayInfo) {
  158. return this._delayInfo.indexOf(kind) !== -1;
  159. }
  160. return false;
  161. }
  162. return this._geometry.isVerticesDataPresent(kind);
  163. }
  164. public getVerticesDataKinds(): string[] {
  165. if (!this._geometry) {
  166. var result = [];
  167. if (this._delayInfo) {
  168. for (var kind in this._delayInfo) {
  169. result.push(kind);
  170. }
  171. }
  172. return result;
  173. }
  174. return this._geometry.getVerticesDataKinds();
  175. }
  176. public getTotalIndices(): number {
  177. if (!this._geometry) {
  178. return 0;
  179. }
  180. return this._geometry.getTotalIndices();
  181. }
  182. public getIndices(): number[] {
  183. if (!this._geometry) {
  184. return [];
  185. }
  186. return this._geometry.getIndices();
  187. }
  188. public get isBlocked(): boolean {
  189. return this._masterMesh !== null && this._masterMesh !== undefined;
  190. }
  191. public isReady(): boolean {
  192. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  193. return false;
  194. }
  195. return super.isReady();
  196. }
  197. public isDisposed(): boolean {
  198. return this._isDisposed;
  199. }
  200. // Methods
  201. public _preActivate(): void {
  202. var sceneRenderId = this.getScene().getRenderId();
  203. if (this._preActivateId == sceneRenderId) {
  204. return;
  205. }
  206. this._preActivateId = sceneRenderId;
  207. this._visibleInstances = null;
  208. }
  209. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  210. if (!this._visibleInstances) {
  211. this._visibleInstances = {};
  212. this._visibleInstances.defaultRenderId = renderId;
  213. this._visibleInstances.selfDefaultRenderId = this._renderId;
  214. }
  215. if (!this._visibleInstances[renderId]) {
  216. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  217. }
  218. this._visibleInstances[renderId].push(instance);
  219. }
  220. public refreshBoundingInfo(): void {
  221. var data = this.getVerticesData(VertexBuffer.PositionKind);
  222. if (data) {
  223. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  224. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  225. }
  226. if (this.subMeshes) {
  227. for (var index = 0; index < this.subMeshes.length; index++) {
  228. this.subMeshes[index].refreshBoundingInfo();
  229. }
  230. }
  231. this._updateBoundingInfo();
  232. }
  233. public _createGlobalSubMesh(): SubMesh {
  234. var totalVertices = this.getTotalVertices();
  235. if (!totalVertices || !this.getIndices()) {
  236. return null;
  237. }
  238. this.releaseSubMeshes();
  239. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  240. }
  241. public subdivide(count: number): void {
  242. if (count < 1) {
  243. return;
  244. }
  245. var totalIndices = this.getTotalIndices();
  246. var subdivisionSize = (totalIndices / count) | 0;
  247. var offset = 0;
  248. // Ensure that subdivisionSize is a multiple of 3
  249. while (subdivisionSize % 3 != 0) {
  250. subdivisionSize++;
  251. }
  252. this.releaseSubMeshes();
  253. for (var index = 0; index < count; index++) {
  254. if (offset >= totalIndices) {
  255. break;
  256. }
  257. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  258. offset += subdivisionSize;
  259. }
  260. this.synchronizeInstances();
  261. }
  262. public setVerticesData(kind: any, data: any, updatable?: boolean, stride?: number): void {
  263. if (kind instanceof Array) {
  264. var temp = data;
  265. data = kind;
  266. kind = temp;
  267. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  268. }
  269. if (!this._geometry) {
  270. var vertexData = new VertexData();
  271. vertexData.set(data, kind);
  272. var scene = this.getScene();
  273. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  274. }
  275. else {
  276. this._geometry.setVerticesData(kind, data, updatable, stride);
  277. }
  278. }
  279. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  280. if (!this._geometry) {
  281. return;
  282. }
  283. if (!makeItUnique) {
  284. this._geometry.updateVerticesData(kind, data, updateExtends);
  285. }
  286. else {
  287. this.makeGeometryUnique();
  288. this.updateVerticesData(kind, data, updateExtends, false);
  289. }
  290. }
  291. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  292. if (!this._geometry) {
  293. return;
  294. }
  295. if (!makeItUnique) {
  296. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  297. }
  298. else {
  299. this.makeGeometryUnique();
  300. this.updateVerticesDataDirectly(kind, data, offset, false);
  301. }
  302. }
  303. public makeGeometryUnique() {
  304. if (!this._geometry) {
  305. return;
  306. }
  307. var geometry = this._geometry.copy(Geometry.RandomId());
  308. geometry.applyToMesh(this);
  309. }
  310. public setIndices(indices: number[], totalVertices?: number): void {
  311. if (!this._geometry) {
  312. var vertexData = new VertexData();
  313. vertexData.indices = indices;
  314. var scene = this.getScene();
  315. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  316. }
  317. else {
  318. this._geometry.setIndices(indices, totalVertices);
  319. }
  320. }
  321. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  322. var engine = this.getScene().getEngine();
  323. // Wireframe
  324. var indexToBind;
  325. switch (fillMode) {
  326. case Material.PointFillMode:
  327. indexToBind = null;
  328. break;
  329. case Material.WireFrameFillMode:
  330. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  331. break;
  332. default:
  333. case Material.TriangleFillMode:
  334. indexToBind = this._geometry.getIndexBuffer();
  335. break;
  336. }
  337. // VBOs
  338. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  339. }
  340. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  341. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  342. return;
  343. }
  344. var engine = this.getScene().getEngine();
  345. // Draw order
  346. switch (fillMode) {
  347. case Material.PointFillMode:
  348. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  349. break;
  350. case Material.WireFrameFillMode:
  351. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  352. break;
  353. default:
  354. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  355. }
  356. }
  357. public registerBeforeRender(func: () => void): void {
  358. this._onBeforeRenderCallbacks.push(func);
  359. }
  360. public unregisterBeforeRender(func: () => void): void {
  361. var index = this._onBeforeRenderCallbacks.indexOf(func);
  362. if (index > -1) {
  363. this._onBeforeRenderCallbacks.splice(index, 1);
  364. }
  365. }
  366. public registerAfterRender(func: () => void): void {
  367. this._onAfterRenderCallbacks.push(func);
  368. }
  369. public unregisterAfterRender(func: () => void): void {
  370. var index = this._onAfterRenderCallbacks.indexOf(func);
  371. if (index > -1) {
  372. this._onAfterRenderCallbacks.splice(index, 1);
  373. }
  374. }
  375. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  376. var scene = this.getScene();
  377. this._batchCache.mustReturn = false;
  378. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  379. this._batchCache.visibleInstances[subMeshId] = null;
  380. if (this._visibleInstances) {
  381. var currentRenderId = scene.getRenderId();
  382. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  383. var selfRenderId = this._renderId;
  384. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  385. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  386. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  387. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  388. }
  389. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  390. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  391. this._batchCache.mustReturn = true;
  392. return this._batchCache;
  393. }
  394. if (currentRenderId !== selfRenderId) {
  395. this._batchCache.renderSelf[subMeshId] = false;
  396. }
  397. }
  398. this._renderIdForInstances[subMeshId] = currentRenderId;
  399. }
  400. return this._batchCache;
  401. }
  402. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  403. var visibleInstances = batch.visibleInstances[subMesh._id];
  404. var matricesCount = visibleInstances.length + 1;
  405. var bufferSize = matricesCount * 16 * 4;
  406. while (this._instancesBufferSize < bufferSize) {
  407. this._instancesBufferSize *= 2;
  408. }
  409. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  410. if (this._worldMatricesInstancesBuffer) {
  411. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  412. }
  413. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  414. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  415. }
  416. var offset = 0;
  417. var instancesCount = 0;
  418. var world = this.getWorldMatrix();
  419. if (batch.renderSelf[subMesh._id]) {
  420. world.copyToArray(this._worldMatricesInstancesArray, offset);
  421. offset += 16;
  422. instancesCount++;
  423. }
  424. if (visibleInstances) {
  425. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  426. var instance = visibleInstances[instanceIndex];
  427. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  428. offset += 16;
  429. instancesCount++;
  430. }
  431. }
  432. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  433. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  434. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  435. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  436. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  437. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  438. this._draw(subMesh, fillMode, instancesCount);
  439. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  440. }
  441. public render(subMesh: SubMesh): void {
  442. var scene = this.getScene();
  443. // Managing instances
  444. var batch = this._getInstancesRenderList(subMesh._id);
  445. if (batch.mustReturn) {
  446. return;
  447. }
  448. // Checking geometry state
  449. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  450. return;
  451. }
  452. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  453. this._onBeforeRenderCallbacks[callbackIndex]();
  454. }
  455. var engine = scene.getEngine();
  456. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  457. // Material
  458. var effectiveMaterial = subMesh.getMaterial();
  459. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  460. return;
  461. }
  462. // Outline - step 1
  463. var savedDepthWrite = engine.getDepthWrite();
  464. if (this.renderOutline) {
  465. engine.setDepthWrite(false);
  466. scene.getOutlineRenderer().render(subMesh, batch);
  467. engine.setDepthWrite(savedDepthWrite);
  468. }
  469. effectiveMaterial._preBind();
  470. var effect = effectiveMaterial.getEffect();
  471. // Bind
  472. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  473. this._bind(subMesh, effect, fillMode);
  474. var world = this.getWorldMatrix();
  475. effectiveMaterial.bind(world, this);
  476. // Instances rendering
  477. if (hardwareInstancedRendering) {
  478. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  479. } else {
  480. if (batch.renderSelf[subMesh._id]) {
  481. // Draw
  482. this._draw(subMesh, fillMode);
  483. }
  484. if (batch.visibleInstances[subMesh._id]) {
  485. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  486. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  487. // World
  488. world = instance.getWorldMatrix();
  489. effectiveMaterial.bindOnlyWorldMatrix(world);
  490. // Draw
  491. this._draw(subMesh, fillMode);
  492. }
  493. }
  494. }
  495. // Unbind
  496. effectiveMaterial.unbind();
  497. // Outline - step 2
  498. if (this.renderOutline && savedDepthWrite) {
  499. engine.setDepthWrite(true);
  500. engine.setColorWrite(false);
  501. scene.getOutlineRenderer().render(subMesh, batch);
  502. engine.setColorWrite(true);
  503. }
  504. // Overlay
  505. if (this.renderOverlay) {
  506. var currentMode = engine.getAlphaMode();
  507. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  508. scene.getOutlineRenderer().render(subMesh, batch, true);
  509. engine.setAlphaMode(currentMode);
  510. }
  511. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  512. this._onAfterRenderCallbacks[callbackIndex]();
  513. }
  514. }
  515. public getEmittedParticleSystems(): ParticleSystem[] {
  516. var results = new Array<ParticleSystem>();
  517. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  518. var particleSystem = this.getScene().particleSystems[index];
  519. if (particleSystem.emitter === this) {
  520. results.push(particleSystem);
  521. }
  522. }
  523. return results;
  524. }
  525. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  526. var results = new Array<ParticleSystem>();
  527. var descendants = this.getDescendants();
  528. descendants.push(this);
  529. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  530. var particleSystem = this.getScene().particleSystems[index];
  531. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  532. results.push(particleSystem);
  533. }
  534. }
  535. return results;
  536. }
  537. public getChildren(): Node[] {
  538. var results = [];
  539. for (var index = 0; index < this.getScene().meshes.length; index++) {
  540. var mesh = this.getScene().meshes[index];
  541. if (mesh.parent == this) {
  542. results.push(mesh);
  543. }
  544. }
  545. return results;
  546. }
  547. public _checkDelayState(): void {
  548. var that = this;
  549. var scene = this.getScene();
  550. if (this._geometry) {
  551. this._geometry.load(scene);
  552. }
  553. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  554. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  555. scene._addPendingData(that);
  556. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  557. Tools.LoadFile(this.delayLoadingFile, data => {
  558. if (data instanceof ArrayBuffer) {
  559. this._delayLoadingFunction(data, this);
  560. }
  561. else {
  562. this._delayLoadingFunction(JSON.parse(data), this);
  563. }
  564. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  565. scene._removePendingData(this);
  566. },() => { }, scene.database, getBinaryData);
  567. }
  568. }
  569. public isInFrustum(frustumPlanes: Plane[]): boolean {
  570. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  571. return false;
  572. }
  573. if (!super.isInFrustum(frustumPlanes)) {
  574. return false;
  575. }
  576. this._checkDelayState();
  577. return true;
  578. }
  579. public setMaterialByID(id: string): void {
  580. var materials = this.getScene().materials;
  581. for (var index = 0; index < materials.length; index++) {
  582. if (materials[index].id == id) {
  583. this.material = materials[index];
  584. return;
  585. }
  586. }
  587. // Multi
  588. var multiMaterials = this.getScene().multiMaterials;
  589. for (index = 0; index < multiMaterials.length; index++) {
  590. if (multiMaterials[index].id == id) {
  591. this.material = multiMaterials[index];
  592. return;
  593. }
  594. }
  595. }
  596. public getAnimatables(): IAnimatable[] {
  597. var results = [];
  598. if (this.material) {
  599. results.push(this.material);
  600. }
  601. if (this.skeleton) {
  602. results.push(this.skeleton);
  603. }
  604. return results;
  605. }
  606. // Geometry
  607. public bakeTransformIntoVertices(transform: Matrix): void {
  608. // Position
  609. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  610. return;
  611. }
  612. this._resetPointsArrayCache();
  613. var data = this.getVerticesData(VertexBuffer.PositionKind);
  614. var temp = [];
  615. for (var index = 0; index < data.length; index += 3) {
  616. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  617. }
  618. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  619. // Normals
  620. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  621. return;
  622. }
  623. data = this.getVerticesData(VertexBuffer.NormalKind);
  624. for (index = 0; index < data.length; index += 3) {
  625. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).toArray(temp, index);
  626. }
  627. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  628. }
  629. // Cache
  630. public _resetPointsArrayCache(): void {
  631. this._positions = null;
  632. }
  633. public _generatePointsArray(): boolean {
  634. if (this._positions)
  635. return true;
  636. this._positions = [];
  637. var data = this.getVerticesData(VertexBuffer.PositionKind);
  638. if (!data) {
  639. return false;
  640. }
  641. for (var index = 0; index < data.length; index += 3) {
  642. this._positions.push(Vector3.FromArray(data, index));
  643. }
  644. return true;
  645. }
  646. // Clone
  647. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Mesh {
  648. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  649. }
  650. // Dispose
  651. public dispose(doNotRecurse?: boolean): void {
  652. if (this._geometry) {
  653. this._geometry.releaseForMesh(this, true);
  654. }
  655. // Instances
  656. if (this._worldMatricesInstancesBuffer) {
  657. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  658. this._worldMatricesInstancesBuffer = null;
  659. }
  660. while (this.instances.length) {
  661. this.instances[0].dispose();
  662. }
  663. super.dispose(doNotRecurse);
  664. }
  665. // Geometric tools
  666. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number): void {
  667. var scene = this.getScene();
  668. var onload = img => {
  669. // Getting height map data
  670. var canvas = document.createElement("canvas");
  671. var context = canvas.getContext("2d");
  672. var heightMapWidth = img.width;
  673. var heightMapHeight = img.height;
  674. canvas.width = heightMapWidth;
  675. canvas.height = heightMapHeight;
  676. context.drawImage(img, 0, 0);
  677. // Create VertexData from map data
  678. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  679. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  680. };
  681. Tools.LoadImage(url, onload,() => { }, scene.database);
  682. }
  683. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  684. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  685. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  686. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  687. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  688. return;
  689. }
  690. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  691. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  692. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  693. var position = Vector3.Zero();
  694. var normal = Vector3.Zero();
  695. var uv = Vector2.Zero();
  696. for (var index = 0; index < positions.length; index += 3) {
  697. Vector3.FromArrayToRef(positions, index, position);
  698. Vector3.FromArrayToRef(normals, index, normal);
  699. Vector2.FromArrayToRef(uvs,(index / 3) * 2, uv);
  700. // Compute height
  701. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  702. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  703. var pos = (u + v * heightMapWidth) * 4;
  704. var r = buffer[pos] / 255.0;
  705. var g = buffer[pos + 1] / 255.0;
  706. var b = buffer[pos + 2] / 255.0;
  707. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  708. normal.normalize();
  709. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  710. position = position.add(normal);
  711. position.toArray(positions, index);
  712. }
  713. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  714. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  715. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  716. }
  717. public convertToFlatShadedMesh(): void {
  718. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  719. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  720. var kinds = this.getVerticesDataKinds();
  721. var vbs = [];
  722. var data = [];
  723. var newdata = [];
  724. var updatableNormals = false;
  725. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  726. var kind = kinds[kindIndex];
  727. var vertexBuffer = this.getVertexBuffer(kind);
  728. if (kind === VertexBuffer.NormalKind) {
  729. updatableNormals = vertexBuffer.isUpdatable();
  730. kinds.splice(kindIndex, 1);
  731. kindIndex--;
  732. continue;
  733. }
  734. vbs[kind] = vertexBuffer;
  735. data[kind] = vbs[kind].getData();
  736. newdata[kind] = [];
  737. }
  738. // Save previous submeshes
  739. var previousSubmeshes = this.subMeshes.slice(0);
  740. var indices = this.getIndices();
  741. var totalIndices = this.getTotalIndices();
  742. // Generating unique vertices per face
  743. for (var index = 0; index < totalIndices; index++) {
  744. var vertexIndex = indices[index];
  745. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  746. kind = kinds[kindIndex];
  747. var stride = vbs[kind].getStrideSize();
  748. for (var offset = 0; offset < stride; offset++) {
  749. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  750. }
  751. }
  752. }
  753. // Updating faces & normal
  754. var normals = [];
  755. var positions = newdata[VertexBuffer.PositionKind];
  756. for (index = 0; index < totalIndices; index += 3) {
  757. indices[index] = index;
  758. indices[index + 1] = index + 1;
  759. indices[index + 2] = index + 2;
  760. var p1 = Vector3.FromArray(positions, index * 3);
  761. var p2 = Vector3.FromArray(positions,(index + 1) * 3);
  762. var p3 = Vector3.FromArray(positions,(index + 2) * 3);
  763. var p1p2 = p1.subtract(p2);
  764. var p3p2 = p3.subtract(p2);
  765. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  766. // Store same normals for every vertex
  767. for (var localIndex = 0; localIndex < 3; localIndex++) {
  768. normals.push(normal.x);
  769. normals.push(normal.y);
  770. normals.push(normal.z);
  771. }
  772. }
  773. this.setIndices(indices);
  774. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  775. // Updating vertex buffers
  776. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  777. kind = kinds[kindIndex];
  778. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  779. }
  780. // Updating submeshes
  781. this.releaseSubMeshes();
  782. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  783. var previousOne = previousSubmeshes[submeshIndex];
  784. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  785. }
  786. this.synchronizeInstances();
  787. }
  788. // Instances
  789. public createInstance(name: string): InstancedMesh {
  790. return new InstancedMesh(name, this);
  791. }
  792. public synchronizeInstances(): void {
  793. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  794. var instance = this.instances[instanceIndex];
  795. instance._syncSubMeshes();
  796. }
  797. }
  798. /**
  799. * Simplify the mesh according to the given array of settings.
  800. * Function will return immediately and will simplify async.
  801. * @param settings a collection of simplification settings.
  802. * @param parallelProcessing should all levels calculate parallel or one after the other.
  803. * @param type the type of simplification to run.
  804. * successCallback optional success callback to be called after the simplification finished processing all settings.
  805. */
  806. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, type: SimplificationType = SimplificationType.QUADRATIC, successCallback?: () => void) {
  807. var getSimplifier = (): ISimplifier => {
  808. switch (type) {
  809. case SimplificationType.QUADRATIC:
  810. default:
  811. return new QuadraticErrorSimplification(this);
  812. }
  813. }
  814. if (parallelProcessing) {
  815. //parallel simplifier
  816. settings.forEach((setting) => {
  817. var simplifier = getSimplifier();
  818. simplifier.simplify(setting,(newMesh) => {
  819. this.addLODLevel(setting.distance, newMesh);
  820. //check if it is the last
  821. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  822. //all done, run the success callback.
  823. successCallback();
  824. }
  825. });
  826. });
  827. } else {
  828. //single simplifier.
  829. var simplifier = getSimplifier();
  830. var runDecimation = (setting: ISimplificationSettings, callback: () => void) => {
  831. simplifier.simplify(setting,(newMesh) => {
  832. this.addLODLevel(setting.distance, newMesh);
  833. //run the next quality level
  834. callback();
  835. });
  836. }
  837. AsyncLoop.Run(settings.length,(loop: AsyncLoop) => {
  838. runDecimation(settings[loop.index],() => {
  839. loop.executeNext();
  840. });
  841. },() => {
  842. //execution ended, run the success callback.
  843. if (successCallback) {
  844. successCallback();
  845. }
  846. });
  847. }
  848. }
  849. // Statics
  850. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  851. var box = new Mesh(name, scene);
  852. var vertexData = VertexData.CreateBox(size);
  853. vertexData.applyToMesh(box, updatable);
  854. return box;
  855. }
  856. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean): Mesh {
  857. var sphere = new Mesh(name, scene);
  858. var vertexData = VertexData.CreateSphere(segments, diameter);
  859. vertexData.applyToMesh(sphere, updatable);
  860. return sphere;
  861. }
  862. // Cylinder and cone (Code inspired by SharpDX.org)
  863. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any): Mesh {
  864. // subdivisions is a new parameter, we need to support old signature
  865. if (scene === undefined || !(scene instanceof Scene)) {
  866. if (scene !== undefined) {
  867. updatable = scene;
  868. }
  869. scene = <Scene>subdivisions;
  870. subdivisions = 1;
  871. }
  872. var cylinder = new Mesh(name, scene);
  873. var vertexData = VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  874. vertexData.applyToMesh(cylinder, updatable);
  875. return cylinder;
  876. }
  877. // Torus (Code from SharpDX.org)
  878. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  879. var torus = new Mesh(name, scene);
  880. var vertexData = VertexData.CreateTorus(diameter, thickness, tessellation);
  881. vertexData.applyToMesh(torus, updatable);
  882. return torus;
  883. }
  884. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean): Mesh {
  885. var torusKnot = new Mesh(name, scene);
  886. var vertexData = VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  887. vertexData.applyToMesh(torusKnot, updatable);
  888. return torusKnot;
  889. }
  890. // Lines
  891. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean): LinesMesh {
  892. var lines = new LinesMesh(name, scene, updatable);
  893. var vertexData = VertexData.CreateLines(points);
  894. vertexData.applyToMesh(lines, updatable);
  895. return lines;
  896. }
  897. // Plane & ground
  898. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  899. var plane = new Mesh(name, scene);
  900. var vertexData = VertexData.CreatePlane(size);
  901. vertexData.applyToMesh(plane, updatable);
  902. return plane;
  903. }
  904. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  905. var ground = new GroundMesh(name, scene);
  906. ground._setReady(false);
  907. ground._subdivisions = subdivisions;
  908. var vertexData = VertexData.CreateGround(width, height, subdivisions);
  909. vertexData.applyToMesh(ground, updatable);
  910. ground._setReady(true);
  911. return ground;
  912. }
  913. 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 {
  914. var tiledGround = new Mesh(name, scene);
  915. var vertexData = VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  916. vertexData.applyToMesh(tiledGround, updatable);
  917. return tiledGround;
  918. }
  919. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean): GroundMesh {
  920. var ground = new GroundMesh(name, scene);
  921. ground._subdivisions = subdivisions;
  922. ground._setReady(false);
  923. var onload = img => {
  924. // Getting height map data
  925. var canvas = document.createElement("canvas");
  926. var context = canvas.getContext("2d");
  927. var heightMapWidth = img.width;
  928. var heightMapHeight = img.height;
  929. canvas.width = heightMapWidth;
  930. canvas.height = heightMapHeight;
  931. context.drawImage(img, 0, 0);
  932. // Create VertexData from map data
  933. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  934. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  935. vertexData.applyToMesh(ground, updatable);
  936. ground._setReady(true);
  937. };
  938. Tools.LoadImage(url, onload,() => { }, scene.database);
  939. return ground;
  940. }
  941. // Tools
  942. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  943. var minVector = null;
  944. var maxVector = null;
  945. for (var i in meshes) {
  946. var mesh = meshes[i];
  947. var boundingBox = mesh.getBoundingInfo().boundingBox;
  948. if (!minVector) {
  949. minVector = boundingBox.minimumWorld;
  950. maxVector = boundingBox.maximumWorld;
  951. continue;
  952. }
  953. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  954. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  955. }
  956. return {
  957. min: minVector,
  958. max: maxVector
  959. };
  960. }
  961. public static Center(meshesOrMinMaxVector): Vector3 {
  962. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  963. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  964. }
  965. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean): Mesh {
  966. var source = meshes[0];
  967. var material = source.material;
  968. var scene = source.getScene();
  969. if (!allow32BitsIndices) {
  970. var totalVertices = 0;
  971. // Counting vertices
  972. for (var index = 0; index < meshes.length; index++) {
  973. totalVertices += meshes[index].getTotalVertices();
  974. if (totalVertices > 65536) {
  975. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  976. return null;
  977. }
  978. }
  979. }
  980. // Merge
  981. var vertexData = VertexData.ExtractFromMesh(source);
  982. vertexData.transform(source.getWorldMatrix());
  983. for (index = 1; index < meshes.length; index++) {
  984. var otherVertexData = VertexData.ExtractFromMesh(meshes[index]);
  985. otherVertexData.transform(meshes[index].getWorldMatrix());
  986. vertexData.merge(otherVertexData);
  987. }
  988. var newMesh = new Mesh(source.name + "_merged", scene);
  989. vertexData.applyToMesh(newMesh);
  990. // Setting properties
  991. newMesh.material = material;
  992. newMesh.checkCollisions = source.checkCollisions;
  993. // Cleaning
  994. if (disposeSource) {
  995. for (index = 0; index < meshes.length; index++) {
  996. meshes[index].dispose();
  997. }
  998. }
  999. return newMesh;
  1000. }
  1001. }
  1002. }