babylon.mesh.ts 47 KB

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