babylon.mesh.ts 87 KB

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