babylon.mesh.ts 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298
  1. module BABYLON {
  2. export class _InstancesBatch {
  3. public mustReturn = false;
  4. public visibleInstances = new Array<Nullable<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. /**
  18. * Mesh side orientation : usually the external or front surface
  19. */
  20. public static get FRONTSIDE(): number {
  21. return Mesh._FRONTSIDE;
  22. }
  23. /**
  24. * Mesh side orientation : usually the internal or back surface
  25. */
  26. public static get BACKSIDE(): number {
  27. return Mesh._BACKSIDE;
  28. }
  29. /**
  30. * Mesh side orientation : both internal and external or front and back surfaces
  31. */
  32. public static get DOUBLESIDE(): number {
  33. return Mesh._DOUBLESIDE;
  34. }
  35. /**
  36. * Mesh side orientation : by default, `FRONTSIDE`
  37. */
  38. public static get DEFAULTSIDE(): number {
  39. return Mesh._DEFAULTSIDE;
  40. }
  41. /**
  42. * Mesh cap setting : no cap
  43. */
  44. public static get NO_CAP(): number {
  45. return Mesh._NO_CAP;
  46. }
  47. /**
  48. * Mesh cap setting : one cap at the beginning of the mesh
  49. */
  50. public static get CAP_START(): number {
  51. return Mesh._CAP_START;
  52. }
  53. /**
  54. * Mesh cap setting : one cap at the end of the mesh
  55. */
  56. public static get CAP_END(): number {
  57. return Mesh._CAP_END;
  58. }
  59. /**
  60. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  61. */
  62. public static get CAP_ALL(): number {
  63. return Mesh._CAP_ALL;
  64. }
  65. // Events
  66. /**
  67. * An event triggered before rendering the mesh
  68. * @type {BABYLON.Observable}
  69. */
  70. public onBeforeRenderObservable = new Observable<Mesh>();
  71. /**
  72. * An event triggered after rendering the mesh
  73. * @type {BABYLON.Observable}
  74. */
  75. public onAfterRenderObservable = new Observable<Mesh>();
  76. /**
  77. * An event triggered before drawing the mesh
  78. * @type {BABYLON.Observable}
  79. */
  80. public onBeforeDrawObservable = new Observable<Mesh>();
  81. private _onBeforeDrawObserver: Nullable<Observer<Mesh>>;
  82. public set onBeforeDraw(callback: () => void) {
  83. if (this._onBeforeDrawObserver) {
  84. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  85. }
  86. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  87. }
  88. // Members
  89. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  90. public instances = new Array<InstancedMesh>();
  91. public delayLoadingFile: string;
  92. public _binaryInfo: any;
  93. private _LODLevels = new Array<Internals.MeshLODLevel>();
  94. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void;
  95. // Morph
  96. private _morphTargetManager: Nullable<MorphTargetManager>;
  97. public get morphTargetManager(): Nullable<MorphTargetManager> {
  98. return this._morphTargetManager;
  99. }
  100. public set morphTargetManager(value: Nullable<MorphTargetManager>) {
  101. if (this._morphTargetManager === value) {
  102. return;
  103. }
  104. this._morphTargetManager = value;
  105. this._syncGeometryWithMorphTargetManager();
  106. }
  107. // Private
  108. public _geometry: Nullable<Geometry>;
  109. public _delayInfo: Array<string>;
  110. public _delayLoadingFunction: (any: any, mesh: Mesh) => void;
  111. public _visibleInstances: any = {};
  112. private _renderIdForInstances = new Array<number>();
  113. private _batchCache = new _InstancesBatch();
  114. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  115. private _instancesBuffer: Nullable<Buffer>;
  116. private _instancesData: Float32Array;
  117. private _overridenInstanceCount: number;
  118. private _effectiveMaterial: Material;
  119. public _shouldGenerateFlatShading: boolean;
  120. private _preActivateId: number;
  121. // Use by builder only to know what orientation were the mesh build in.
  122. public _originalBuilderSideOrientation: number = Mesh._DEFAULTSIDE;
  123. public overrideMaterialSideOrientation: Nullable<number> = null;
  124. private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
  125. private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
  126. private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
  127. // Will be used to save a source mesh reference, If any
  128. private _source: Nullable<Mesh> = null;
  129. public get source(): Nullable<Mesh> {
  130. return this._source;
  131. }
  132. /**
  133. * @constructor
  134. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  135. * @param {Scene} scene The scene to add this mesh to.
  136. * @param {Node} parent The parent of this mesh, if it has one
  137. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  138. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  139. * When false, achieved by calling a clone(), also passing False.
  140. * This will make creation of children, recursive.
  141. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  142. */
  143. constructor(name: string, scene: Nullable<Scene> = null, parent: Nullable<Node> = null, source: Nullable<Mesh> = null, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true) {
  144. super(name, scene);
  145. scene = this.getScene();
  146. if (source) {
  147. // Source mesh
  148. this._source = source;
  149. // Geometry
  150. if (source._geometry) {
  151. source._geometry.applyToMesh(this);
  152. }
  153. // Deep copy
  154. Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  155. // Tags
  156. if (Tags.HasTags(source)) {
  157. Tags.AddTagsTo(this, Tags.GetTags(source, true));
  158. }
  159. this.metadata = source.metadata;
  160. // Parent
  161. this.parent = source.parent;
  162. // Pivot
  163. this.setPivotMatrix(source.getPivotMatrix());
  164. this.id = name + "." + source.id;
  165. // Material
  166. this.material = source.material;
  167. var index: number;
  168. if (!doNotCloneChildren) {
  169. // Children
  170. for (index = 0; index < scene.meshes.length; index++) {
  171. var mesh = scene.meshes[index];
  172. if (mesh.parent === source) {
  173. // doNotCloneChildren is always going to be False
  174. mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  175. }
  176. }
  177. }
  178. // Physics clone
  179. var physicsEngine = this.getScene().getPhysicsEngine();
  180. if (clonePhysicsImpostor && physicsEngine) {
  181. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  182. if (impostor) {
  183. this.physicsImpostor = impostor.clone(this);
  184. }
  185. }
  186. // Particles
  187. for (index = 0; index < scene.particleSystems.length; index++) {
  188. var system = scene.particleSystems[index];
  189. if (system.emitter === source) {
  190. system.clone(system.name, this);
  191. }
  192. }
  193. this.computeWorldMatrix(true);
  194. }
  195. // Parent
  196. if (parent !== null) {
  197. this.parent = parent;
  198. }
  199. }
  200. // Methods
  201. /**
  202. * Returns the string "Mesh".
  203. */
  204. public getClassName(): string {
  205. return "Mesh";
  206. }
  207. /**
  208. * Returns a string.
  209. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  210. */
  211. public toString(fullDetails?: boolean): string {
  212. var ret = super.toString(fullDetails);
  213. ret += ", n vertices: " + this.getTotalVertices();
  214. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  215. if (this.animations) {
  216. for (var i = 0; i < this.animations.length; i++) {
  217. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  218. }
  219. }
  220. if (fullDetails) {
  221. if (this._geometry) {
  222. let ib = this.getIndices();
  223. let vb = this.getVerticesData(VertexBuffer.PositionKind);
  224. if (vb && ib) {
  225. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  226. }
  227. } else {
  228. ret += ", flat shading: UNKNOWN";
  229. }
  230. }
  231. return ret;
  232. }
  233. /**
  234. * True if the mesh has some Levels Of Details (LOD).
  235. * Returns a boolean.
  236. */
  237. public get hasLODLevels(): boolean {
  238. return this._LODLevels.length > 0;
  239. }
  240. private _sortLODLevels(): void {
  241. this._LODLevels.sort((a, b) => {
  242. if (a.distance < b.distance) {
  243. return 1;
  244. }
  245. if (a.distance > b.distance) {
  246. return -1;
  247. }
  248. return 0;
  249. });
  250. }
  251. /**
  252. * Add a mesh as LOD level triggered at the given distance.
  253. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  254. * @param {number} distance The distance from the center of the object to show this level
  255. * @param {Mesh} mesh The mesh to be added as LOD level
  256. * @return {Mesh} This mesh (for chaining)
  257. */
  258. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  259. if (mesh && mesh._masterMesh) {
  260. Tools.Warn("You cannot use a mesh as LOD level twice");
  261. return this;
  262. }
  263. var level = new Internals.MeshLODLevel(distance, mesh);
  264. this._LODLevels.push(level);
  265. if (mesh) {
  266. mesh._masterMesh = this;
  267. }
  268. this._sortLODLevels();
  269. return this;
  270. }
  271. /**
  272. * Returns the LOD level mesh at the passed distance or null if not found.
  273. * It is related to the method `addLODLevel(distance, mesh)`.
  274. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  275. * Returns an object Mesh or `null`.
  276. */
  277. public getLODLevelAtDistance(distance: number): Nullable<Mesh> {
  278. for (var index = 0; index < this._LODLevels.length; index++) {
  279. var level = this._LODLevels[index];
  280. if (level.distance === distance) {
  281. return level.mesh;
  282. }
  283. }
  284. return null;
  285. }
  286. /**
  287. * Remove a mesh from the LOD array
  288. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  289. * @param {Mesh} mesh The mesh to be removed.
  290. * @return {Mesh} This mesh (for chaining)
  291. */
  292. public removeLODLevel(mesh: Mesh): Mesh {
  293. for (var index = 0; index < this._LODLevels.length; index++) {
  294. if (this._LODLevels[index].mesh === mesh) {
  295. this._LODLevels.splice(index, 1);
  296. if (mesh) {
  297. mesh._masterMesh = null;
  298. }
  299. }
  300. }
  301. this._sortLODLevels();
  302. return this;
  303. }
  304. /**
  305. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  306. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  307. */
  308. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  309. if (!this._LODLevels || this._LODLevels.length === 0) {
  310. return this;
  311. }
  312. let bSphere: BoundingSphere;
  313. if (boundingSphere) {
  314. bSphere = boundingSphere;
  315. } else {
  316. let boundingInfo = this.getBoundingInfo();
  317. bSphere = boundingInfo.boundingSphere;
  318. }
  319. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  320. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  321. if (this.onLODLevelSelection) {
  322. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  323. }
  324. return this;
  325. }
  326. for (var index = 0; index < this._LODLevels.length; index++) {
  327. var level = this._LODLevels[index];
  328. if (level.distance < distanceToCamera) {
  329. if (level.mesh) {
  330. level.mesh._preActivate();
  331. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  332. }
  333. if (this.onLODLevelSelection) {
  334. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  335. }
  336. return level.mesh;
  337. }
  338. }
  339. if (this.onLODLevelSelection) {
  340. this.onLODLevelSelection(distanceToCamera, this, this);
  341. }
  342. return this;
  343. }
  344. /**
  345. * Returns the mesh internal Geometry object.
  346. */
  347. public get geometry(): Nullable<Geometry> {
  348. return this._geometry;
  349. }
  350. /**
  351. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  352. */
  353. public getTotalVertices(): number {
  354. if (!this._geometry) {
  355. return 0;
  356. }
  357. return this._geometry.getTotalVertices();
  358. }
  359. /**
  360. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  361. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  362. * You can force the copy with forceCopy === true
  363. * Returns null if the mesh has no geometry or no vertex buffer.
  364. * Possible `kind` values :
  365. * - BABYLON.VertexBuffer.PositionKind
  366. * - BABYLON.VertexBuffer.UVKind
  367. * - BABYLON.VertexBuffer.UV2Kind
  368. * - BABYLON.VertexBuffer.UV3Kind
  369. * - BABYLON.VertexBuffer.UV4Kind
  370. * - BABYLON.VertexBuffer.UV5Kind
  371. * - BABYLON.VertexBuffer.UV6Kind
  372. * - BABYLON.VertexBuffer.ColorKind
  373. * - BABYLON.VertexBuffer.MatricesIndicesKind
  374. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  375. * - BABYLON.VertexBuffer.MatricesWeightsKind
  376. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  377. */
  378. public getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable<FloatArray> {
  379. if (!this._geometry) {
  380. return null;
  381. }
  382. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  383. }
  384. /**
  385. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  386. * Returns `null` if the mesh has no geometry.
  387. * Possible `kind` values :
  388. * - BABYLON.VertexBuffer.PositionKind
  389. * - BABYLON.VertexBuffer.UVKind
  390. * - BABYLON.VertexBuffer.UV2Kind
  391. * - BABYLON.VertexBuffer.UV3Kind
  392. * - BABYLON.VertexBuffer.UV4Kind
  393. * - BABYLON.VertexBuffer.UV5Kind
  394. * - BABYLON.VertexBuffer.UV6Kind
  395. * - BABYLON.VertexBuffer.ColorKind
  396. * - BABYLON.VertexBuffer.MatricesIndicesKind
  397. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  398. * - BABYLON.VertexBuffer.MatricesWeightsKind
  399. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  400. */
  401. public getVertexBuffer(kind: string): Nullable<VertexBuffer> {
  402. if (!this._geometry) {
  403. return null;
  404. }
  405. return this._geometry.getVertexBuffer(kind);
  406. }
  407. /**
  408. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  409. * Possible `kind` values :
  410. * - BABYLON.VertexBuffer.PositionKind
  411. * - BABYLON.VertexBuffer.UVKind
  412. * - BABYLON.VertexBuffer.UV2Kind
  413. * - BABYLON.VertexBuffer.UV3Kind
  414. * - BABYLON.VertexBuffer.UV4Kind
  415. * - BABYLON.VertexBuffer.UV5Kind
  416. * - BABYLON.VertexBuffer.UV6Kind
  417. * - BABYLON.VertexBuffer.ColorKind
  418. * - BABYLON.VertexBuffer.MatricesIndicesKind
  419. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  420. * - BABYLON.VertexBuffer.MatricesWeightsKind
  421. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  422. */
  423. public isVerticesDataPresent(kind: string): boolean {
  424. if (!this._geometry) {
  425. if (this._delayInfo) {
  426. return this._delayInfo.indexOf(kind) !== -1;
  427. }
  428. return false;
  429. }
  430. return this._geometry.isVerticesDataPresent(kind);
  431. }
  432. /**
  433. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  434. * Possible `kind` values :
  435. * - BABYLON.VertexBuffer.PositionKind
  436. * - BABYLON.VertexBuffer.UVKind
  437. * - BABYLON.VertexBuffer.UV2Kind
  438. * - BABYLON.VertexBuffer.UV3Kind
  439. * - BABYLON.VertexBuffer.UV4Kind
  440. * - BABYLON.VertexBuffer.UV5Kind
  441. * - BABYLON.VertexBuffer.UV6Kind
  442. * - BABYLON.VertexBuffer.ColorKind
  443. * - BABYLON.VertexBuffer.MatricesIndicesKind
  444. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  445. * - BABYLON.VertexBuffer.MatricesWeightsKind
  446. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  447. */
  448. public isVertexBufferUpdatable(kind: string): boolean {
  449. if (!this._geometry) {
  450. if (this._delayInfo) {
  451. return this._delayInfo.indexOf(kind) !== -1;
  452. }
  453. return false;
  454. }
  455. return this._geometry.isVertexBufferUpdatable(kind);
  456. }
  457. /**
  458. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  459. * Possible `kind` values :
  460. * - BABYLON.VertexBuffer.PositionKind
  461. * - BABYLON.VertexBuffer.UVKind
  462. * - BABYLON.VertexBuffer.UV2Kind
  463. * - BABYLON.VertexBuffer.UV3Kind
  464. * - BABYLON.VertexBuffer.UV4Kind
  465. * - BABYLON.VertexBuffer.UV5Kind
  466. * - BABYLON.VertexBuffer.UV6Kind
  467. * - BABYLON.VertexBuffer.ColorKind
  468. * - BABYLON.VertexBuffer.MatricesIndicesKind
  469. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  470. * - BABYLON.VertexBuffer.MatricesWeightsKind
  471. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  472. */
  473. public getVerticesDataKinds(): string[] {
  474. if (!this._geometry) {
  475. var result = new Array<string>();
  476. if (this._delayInfo) {
  477. this._delayInfo.forEach(function (kind, index, array) {
  478. result.push(kind);
  479. });
  480. }
  481. return result;
  482. }
  483. return this._geometry.getVerticesDataKinds();
  484. }
  485. /**
  486. * Returns a positive integer : the total number of indices in this mesh geometry.
  487. * Returns zero if the mesh has no geometry.
  488. */
  489. public getTotalIndices(): number {
  490. if (!this._geometry) {
  491. return 0;
  492. }
  493. return this._geometry.getTotalIndices();
  494. }
  495. /**
  496. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  497. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  498. * Returns an empty array if the mesh has no geometry.
  499. */
  500. public getIndices(copyWhenShared?: boolean): Nullable<IndicesArray> {
  501. if (!this._geometry) {
  502. return [];
  503. }
  504. return this._geometry.getIndices(copyWhenShared);
  505. }
  506. public get isBlocked(): boolean {
  507. return this._masterMesh !== null && this._masterMesh !== undefined;
  508. }
  509. /**
  510. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  511. */
  512. public isReady(): boolean {
  513. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  514. return false;
  515. }
  516. return super.isReady();
  517. }
  518. /**
  519. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  520. * This property is pertinent only for updatable parametric shapes.
  521. */
  522. public get areNormalsFrozen(): boolean {
  523. return this._areNormalsFrozen;
  524. }
  525. /**
  526. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  527. * It has no effect at all on other shapes.
  528. * It prevents the mesh normals from being recomputed on next `positions` array update.
  529. * Returns the Mesh.
  530. */
  531. public freezeNormals(): Mesh {
  532. this._areNormalsFrozen = true;
  533. return this;
  534. }
  535. /**
  536. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  537. * It has no effect at all on other shapes.
  538. * It reactivates the mesh normals computation if it was previously frozen.
  539. * Returns the Mesh.
  540. */
  541. public unfreezeNormals(): Mesh {
  542. this._areNormalsFrozen = false;
  543. return this;
  544. }
  545. /**
  546. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  547. */
  548. public set overridenInstanceCount(count: number) {
  549. this._overridenInstanceCount = count;
  550. }
  551. // Methods
  552. public _preActivate(): Mesh {
  553. var sceneRenderId = this.getScene().getRenderId();
  554. if (this._preActivateId === sceneRenderId) {
  555. return this;
  556. }
  557. this._preActivateId = sceneRenderId;
  558. this._visibleInstances = null;
  559. return this;
  560. }
  561. public _preActivateForIntermediateRendering(renderId: number): Mesh {
  562. if (this._visibleInstances) {
  563. this._visibleInstances.intermediateDefaultRenderId = renderId;
  564. }
  565. return this;
  566. }
  567. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number): Mesh {
  568. if (!this._visibleInstances) {
  569. this._visibleInstances = {};
  570. this._visibleInstances.defaultRenderId = renderId;
  571. this._visibleInstances.selfDefaultRenderId = this._renderId;
  572. }
  573. if (!this._visibleInstances[renderId]) {
  574. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  575. }
  576. this._visibleInstances[renderId].push(instance);
  577. return this;
  578. }
  579. /**
  580. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  581. * This means the mesh underlying bounding box and sphere are recomputed.
  582. * Returns the Mesh.
  583. */
  584. public refreshBoundingInfo(): Mesh {
  585. if (this._boundingInfo && this._boundingInfo.isLocked) {
  586. return this;
  587. }
  588. var data = this.getVerticesData(VertexBuffer.PositionKind);
  589. if (data) {
  590. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  591. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  592. }
  593. if (this.subMeshes) {
  594. for (var index = 0; index < this.subMeshes.length; index++) {
  595. this.subMeshes[index].refreshBoundingInfo();
  596. }
  597. }
  598. this._updateBoundingInfo();
  599. return this;
  600. }
  601. public _createGlobalSubMesh(force: boolean): Nullable<SubMesh> {
  602. var totalVertices = this.getTotalVertices();
  603. if (!totalVertices || !this.getIndices()) {
  604. return null;
  605. }
  606. // Check if we need to recreate the submeshes
  607. if (this.subMeshes && this.subMeshes.length > 0) {
  608. let ib = this.getIndices();
  609. if (!ib) {
  610. return null;
  611. }
  612. var totalIndices = ib.length;
  613. let needToRecreate = false;
  614. if (force) {
  615. needToRecreate = true;
  616. } else {
  617. for (var submesh of this.subMeshes) {
  618. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  619. needToRecreate = true;
  620. break;
  621. }
  622. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  623. needToRecreate = true;
  624. break;
  625. }
  626. }
  627. }
  628. if (!needToRecreate) {
  629. return this.subMeshes[0];
  630. }
  631. }
  632. this.releaseSubMeshes();
  633. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  634. }
  635. public subdivide(count: number): void {
  636. if (count < 1) {
  637. return;
  638. }
  639. var totalIndices = this.getTotalIndices();
  640. var subdivisionSize = (totalIndices / count) | 0;
  641. var offset = 0;
  642. // Ensure that subdivisionSize is a multiple of 3
  643. while (subdivisionSize % 3 !== 0) {
  644. subdivisionSize++;
  645. }
  646. this.releaseSubMeshes();
  647. for (var index = 0; index < count; index++) {
  648. if (offset >= totalIndices) {
  649. break;
  650. }
  651. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  652. offset += subdivisionSize;
  653. }
  654. this.synchronizeInstances();
  655. }
  656. /**
  657. * Sets the vertex data of the mesh geometry for the requested `kind`.
  658. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  659. * The `data` are either a numeric array either a Float32Array.
  660. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  661. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  662. * Note that a new underlying VertexBuffer object is created each call.
  663. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  664. *
  665. * Possible `kind` values :
  666. * - BABYLON.VertexBuffer.PositionKind
  667. * - BABYLON.VertexBuffer.UVKind
  668. * - BABYLON.VertexBuffer.UV2Kind
  669. * - BABYLON.VertexBuffer.UV3Kind
  670. * - BABYLON.VertexBuffer.UV4Kind
  671. * - BABYLON.VertexBuffer.UV5Kind
  672. * - BABYLON.VertexBuffer.UV6Kind
  673. * - BABYLON.VertexBuffer.ColorKind
  674. * - BABYLON.VertexBuffer.MatricesIndicesKind
  675. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  676. * - BABYLON.VertexBuffer.MatricesWeightsKind
  677. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  678. *
  679. * Returns the Mesh.
  680. */
  681. public setVerticesData(kind: string, data: FloatArray, updatable: boolean = false, stride?: number): Mesh {
  682. if (!this._geometry) {
  683. var vertexData = new VertexData();
  684. vertexData.set(data, kind);
  685. var scene = this.getScene();
  686. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  687. }
  688. else {
  689. this._geometry.setVerticesData(kind, data, updatable, stride);
  690. }
  691. return this;
  692. }
  693. public markVerticesDataAsUpdatable(kind: string, updatable = true) {
  694. let vb = this.getVertexBuffer(kind);
  695. if (!vb || vb.isUpdatable() === updatable) {
  696. return;
  697. }
  698. this.setVerticesData(kind, (<FloatArray>this.getVerticesData(kind)), updatable);
  699. }
  700. /**
  701. * Sets the mesh VertexBuffer.
  702. * Returns the Mesh.
  703. */
  704. public setVerticesBuffer(buffer: VertexBuffer): Mesh {
  705. if (!this._geometry) {
  706. this._geometry = Geometry.CreateGeometryForMesh(this);
  707. }
  708. this._geometry.setVerticesBuffer(buffer);
  709. return this;
  710. }
  711. /**
  712. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  713. * If the mesh has no geometry, it is simply returned as it is.
  714. * The `data` are either a numeric array either a Float32Array.
  715. * No new underlying VertexBuffer object is created.
  716. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  717. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  718. *
  719. * Possible `kind` values :
  720. * - BABYLON.VertexBuffer.PositionKind
  721. * - BABYLON.VertexBuffer.UVKind
  722. * - BABYLON.VertexBuffer.UV2Kind
  723. * - BABYLON.VertexBuffer.UV3Kind
  724. * - BABYLON.VertexBuffer.UV4Kind
  725. * - BABYLON.VertexBuffer.UV5Kind
  726. * - BABYLON.VertexBuffer.UV6Kind
  727. * - BABYLON.VertexBuffer.ColorKind
  728. * - BABYLON.VertexBuffer.MatricesIndicesKind
  729. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  730. * - BABYLON.VertexBuffer.MatricesWeightsKind
  731. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  732. *
  733. * Returns the Mesh.
  734. */
  735. public updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh {
  736. if (!this._geometry) {
  737. return this;
  738. }
  739. if (!makeItUnique) {
  740. this._geometry.updateVerticesData(kind, data, updateExtends);
  741. }
  742. else {
  743. this.makeGeometryUnique();
  744. this.updateVerticesData(kind, data, updateExtends, false);
  745. }
  746. return this;
  747. }
  748. /**
  749. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  750. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  751. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  752. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  753. * Returns the Mesh.
  754. */
  755. public updateMeshPositions(positionFunction: (data: FloatArray) => void, computeNormals: boolean = true): Mesh {
  756. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  757. if (!positions) {
  758. return this;
  759. }
  760. positionFunction(positions);
  761. this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  762. if (computeNormals) {
  763. var indices = this.getIndices();
  764. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  765. if (!normals) {
  766. return this;
  767. }
  768. VertexData.ComputeNormals(positions, indices, normals);
  769. this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  770. }
  771. return this;
  772. }
  773. /**
  774. * Creates a un-shared specific occurence of the geometry for the mesh.
  775. * Returns the Mesh.
  776. */
  777. public makeGeometryUnique(): Mesh {
  778. if (!this._geometry) {
  779. return this;
  780. }
  781. var oldGeometry = this._geometry;
  782. var geometry = this._geometry.copy(Geometry.RandomId());
  783. oldGeometry.releaseForMesh(this, true);
  784. geometry.applyToMesh(this);
  785. return this;
  786. }
  787. /**
  788. * Sets the mesh indices.
  789. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  790. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  791. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  792. * This method creates a new index buffer each call.
  793. * Returns the Mesh.
  794. */
  795. public setIndices(indices: IndicesArray, totalVertices: Nullable<number> = null, updatable: boolean = false): Mesh {
  796. if (!this._geometry) {
  797. var vertexData = new VertexData();
  798. vertexData.indices = indices;
  799. var scene = this.getScene();
  800. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  801. }
  802. else {
  803. this._geometry.setIndices(indices, totalVertices, updatable);
  804. }
  805. return this;
  806. }
  807. /**
  808. * Update the current index buffer
  809. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  810. * Returns the Mesh.
  811. */
  812. public updateIndices(indices: IndicesArray, offset?: number): Mesh {
  813. if (!this._geometry) {
  814. return this;
  815. }
  816. this._geometry.updateIndices(indices, offset);
  817. return this;
  818. }
  819. /**
  820. * Invert the geometry to move from a right handed system to a left handed one.
  821. * Returns the Mesh.
  822. */
  823. public toLeftHanded(): Mesh {
  824. if (!this._geometry) {
  825. return this;
  826. }
  827. this._geometry.toLeftHanded();
  828. return this;
  829. }
  830. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): Mesh {
  831. if (!this._geometry) {
  832. return this;
  833. }
  834. var engine = this.getScene().getEngine();
  835. // Wireframe
  836. var indexToBind;
  837. if (this._unIndexed) {
  838. indexToBind = null;
  839. } else {
  840. switch (fillMode) {
  841. case Material.PointFillMode:
  842. indexToBind = null;
  843. break;
  844. case Material.WireFrameFillMode:
  845. indexToBind = subMesh.getLinesIndexBuffer(<IndicesArray>this.getIndices(), engine);
  846. break;
  847. default:
  848. case Material.TriangleFillMode:
  849. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  850. break;
  851. }
  852. }
  853. // VBOs
  854. this._geometry._bind(effect, indexToBind);
  855. return this;
  856. }
  857. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number, alternate = false): Mesh {
  858. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  859. return this;
  860. }
  861. this.onBeforeDrawObservable.notifyObservers(this);
  862. let scene = this.getScene();
  863. let engine = scene.getEngine();
  864. // Draw order
  865. switch (fillMode) {
  866. case Material.PointFillMode:
  867. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  868. break;
  869. case Material.WireFrameFillMode:
  870. if (this._unIndexed) {
  871. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  872. } else {
  873. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  874. }
  875. break;
  876. default:
  877. if (this._unIndexed) {
  878. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  879. } else {
  880. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  881. }
  882. }
  883. if (scene._isAlternateRenderingEnabled && !alternate) {
  884. let effect = subMesh.effect || this._effectiveMaterial.getEffect();
  885. if (!effect || !scene.activeCamera) {
  886. return this;
  887. }
  888. scene._switchToAlternateCameraConfiguration(true);
  889. this._effectiveMaterial.bindView(effect);
  890. this._effectiveMaterial.bindViewProjection(effect);
  891. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  892. this._draw(subMesh, fillMode, instancesCount, true);
  893. engine.setViewport(scene.activeCamera.viewport);
  894. scene._switchToAlternateCameraConfiguration(false);
  895. this._effectiveMaterial.bindView(effect);
  896. this._effectiveMaterial.bindViewProjection(effect);
  897. }
  898. return this;
  899. }
  900. /**
  901. * Registers for this mesh a javascript function called just before the rendering process.
  902. * This function is passed the current mesh.
  903. * Return the Mesh.
  904. */
  905. public registerBeforeRender(func: (mesh: AbstractMesh) => void): Mesh {
  906. this.onBeforeRenderObservable.add(func);
  907. return this;
  908. }
  909. /**
  910. * Disposes a previously registered javascript function called before the rendering.
  911. * This function is passed the current mesh.
  912. * Returns the Mesh.
  913. */
  914. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): Mesh {
  915. this.onBeforeRenderObservable.removeCallback(func);
  916. return this;
  917. }
  918. /**
  919. * Registers for this mesh a javascript function called just after the rendering is complete.
  920. * This function is passed the current mesh.
  921. * Returns the Mesh.
  922. */
  923. public registerAfterRender(func: (mesh: AbstractMesh) => void): Mesh {
  924. this.onAfterRenderObservable.add(func);
  925. return this;
  926. }
  927. /**
  928. * Disposes a previously registered javascript function called after the rendering.
  929. * This function is passed the current mesh.
  930. * Return the Mesh.
  931. */
  932. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): Mesh {
  933. this.onAfterRenderObservable.removeCallback(func);
  934. return this;
  935. }
  936. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  937. var scene = this.getScene();
  938. this._batchCache.mustReturn = false;
  939. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  940. this._batchCache.visibleInstances[subMeshId] = null;
  941. if (this._visibleInstances) {
  942. var currentRenderId = scene.getRenderId();
  943. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  944. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  945. var selfRenderId = this._renderId;
  946. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  947. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  948. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  949. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  950. }
  951. let visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  952. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  953. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  954. this._batchCache.mustReturn = true;
  955. return this._batchCache;
  956. }
  957. if (currentRenderId !== selfRenderId) {
  958. this._batchCache.renderSelf[subMeshId] = false;
  959. }
  960. }
  961. this._renderIdForInstances[subMeshId] = currentRenderId;
  962. }
  963. return this._batchCache;
  964. }
  965. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): Mesh {
  966. var visibleInstances = batch.visibleInstances[subMesh._id];
  967. if (!visibleInstances) {
  968. return this;
  969. }
  970. var matricesCount = visibleInstances.length + 1;
  971. var bufferSize = matricesCount * 16 * 4;
  972. var currentInstancesBufferSize = this._instancesBufferSize;
  973. var instancesBuffer = this._instancesBuffer;
  974. while (this._instancesBufferSize < bufferSize) {
  975. this._instancesBufferSize *= 2;
  976. }
  977. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  978. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  979. }
  980. var offset = 0;
  981. var instancesCount = 0;
  982. var world = this.getWorldMatrix();
  983. if (batch.renderSelf[subMesh._id]) {
  984. world.copyToArray(this._instancesData, offset);
  985. offset += 16;
  986. instancesCount++;
  987. }
  988. if (visibleInstances) {
  989. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  990. var instance = visibleInstances[instanceIndex];
  991. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  992. offset += 16;
  993. instancesCount++;
  994. }
  995. }
  996. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  997. if (instancesBuffer) {
  998. instancesBuffer.dispose();
  999. }
  1000. instancesBuffer = new Buffer(engine, this._instancesData, true, 16, false, true);
  1001. this._instancesBuffer = instancesBuffer;
  1002. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  1003. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  1004. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  1005. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  1006. } else {
  1007. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  1008. }
  1009. this._bind(subMesh, effect, fillMode);
  1010. this._draw(subMesh, fillMode, instancesCount);
  1011. engine.unbindInstanceAttributes();
  1012. return this;
  1013. }
  1014. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  1015. onBeforeDraw: (isInstance: boolean, world: Matrix, effectiveMaterial?: Material) => void, effectiveMaterial?: Material): Mesh {
  1016. var scene = this.getScene();
  1017. var engine = scene.getEngine();
  1018. if (hardwareInstancedRendering) {
  1019. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  1020. } else {
  1021. if (batch.renderSelf[subMesh._id]) {
  1022. // Draw
  1023. if (onBeforeDraw) {
  1024. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  1025. }
  1026. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  1027. }
  1028. let visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  1029. if (visibleInstancesForSubMesh) {
  1030. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  1031. var instance = visibleInstancesForSubMesh[instanceIndex];
  1032. // World
  1033. var world = instance.getWorldMatrix();
  1034. if (onBeforeDraw) {
  1035. onBeforeDraw(true, world, effectiveMaterial);
  1036. }
  1037. // Draw
  1038. this._draw(subMesh, fillMode);
  1039. }
  1040. }
  1041. }
  1042. return this;
  1043. }
  1044. /**
  1045. * Triggers the draw call for the mesh.
  1046. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  1047. * Returns the Mesh.
  1048. */
  1049. public render(subMesh: SubMesh, enableAlphaMode: boolean): Mesh {
  1050. this.checkOcclusionQuery();
  1051. if (this._isOccluded) {
  1052. return this;
  1053. }
  1054. var scene = this.getScene();
  1055. // Managing instances
  1056. var batch = this._getInstancesRenderList(subMesh._id);
  1057. if (batch.mustReturn) {
  1058. return this;
  1059. }
  1060. // Checking geometry state
  1061. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  1062. return this;
  1063. }
  1064. this.onBeforeRenderObservable.notifyObservers(this);
  1065. var engine = scene.getEngine();
  1066. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  1067. // Material
  1068. let material = subMesh.getMaterial();
  1069. if (!material) {
  1070. return this;
  1071. }
  1072. this._effectiveMaterial = material
  1073. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  1074. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  1075. return this;
  1076. }
  1077. } else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  1078. return this;
  1079. }
  1080. // Alpha mode
  1081. if (enableAlphaMode) {
  1082. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  1083. }
  1084. // Outline - step 1
  1085. var savedDepthWrite = engine.getDepthWrite();
  1086. if (this.renderOutline) {
  1087. engine.setDepthWrite(false);
  1088. scene.getOutlineRenderer().render(subMesh, batch);
  1089. engine.setDepthWrite(savedDepthWrite);
  1090. }
  1091. var effect: Nullable<Effect>;
  1092. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  1093. effect = subMesh.effect;
  1094. } else {
  1095. effect = this._effectiveMaterial.getEffect();
  1096. }
  1097. if (!effect) {
  1098. return this;
  1099. }
  1100. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  1101. if (this._effectiveMaterial.forceDepthWrite) {
  1102. engine.setDepthWrite(true);
  1103. }
  1104. // Bind
  1105. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  1106. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  1107. this._bind(subMesh, effect, fillMode);
  1108. }
  1109. var world = this.getWorldMatrix();
  1110. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  1111. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  1112. } else {
  1113. this._effectiveMaterial.bind(world, this);
  1114. }
  1115. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  1116. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  1117. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  1118. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  1119. }
  1120. // Draw
  1121. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  1122. // Unbind
  1123. this._effectiveMaterial.unbind();
  1124. // Outline - step 2
  1125. if (this.renderOutline && savedDepthWrite) {
  1126. engine.setDepthWrite(true);
  1127. engine.setColorWrite(false);
  1128. scene.getOutlineRenderer().render(subMesh, batch);
  1129. engine.setColorWrite(true);
  1130. }
  1131. // Overlay
  1132. if (this.renderOverlay) {
  1133. var currentMode = engine.getAlphaMode();
  1134. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  1135. scene.getOutlineRenderer().render(subMesh, batch, true);
  1136. engine.setAlphaMode(currentMode);
  1137. }
  1138. this.onAfterRenderObservable.notifyObservers(this);
  1139. return this;
  1140. }
  1141. private _onBeforeDraw(isInstance: boolean, world: Matrix, effectiveMaterial: Material): Mesh {
  1142. if (isInstance) {
  1143. effectiveMaterial.bindOnlyWorldMatrix(world);
  1144. }
  1145. return this;
  1146. }
  1147. /**
  1148. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  1149. */
  1150. public getEmittedParticleSystems(): IParticleSystem[] {
  1151. var results = new Array<IParticleSystem>();
  1152. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  1153. var particleSystem = this.getScene().particleSystems[index];
  1154. if (particleSystem.emitter === this) {
  1155. results.push(particleSystem);
  1156. }
  1157. }
  1158. return results;
  1159. }
  1160. /**
  1161. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  1162. */
  1163. public getHierarchyEmittedParticleSystems(): IParticleSystem[] {
  1164. var results = new Array<IParticleSystem>();
  1165. var descendants = this.getDescendants();
  1166. descendants.push(this);
  1167. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  1168. var particleSystem = this.getScene().particleSystems[index];
  1169. let emitter: any = particleSystem.emitter;
  1170. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  1171. results.push(particleSystem);
  1172. }
  1173. }
  1174. return results;
  1175. }
  1176. public _checkDelayState(): Mesh {
  1177. var scene = this.getScene();
  1178. if (this._geometry) {
  1179. this._geometry.load(scene);
  1180. }
  1181. else if (this.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  1182. this.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  1183. this._queueLoad(this, scene);
  1184. }
  1185. return this;
  1186. }
  1187. private _queueLoad(mesh: Mesh, scene: Scene): Mesh {
  1188. scene._addPendingData(mesh);
  1189. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  1190. Tools.LoadFile(this.delayLoadingFile, data => {
  1191. if (data instanceof ArrayBuffer) {
  1192. this._delayLoadingFunction(data, this);
  1193. }
  1194. else {
  1195. this._delayLoadingFunction(JSON.parse(data), this);
  1196. }
  1197. this.instances.forEach(instance => {
  1198. instance._syncSubMeshes();
  1199. });
  1200. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  1201. scene._removePendingData(this);
  1202. }, () => { }, scene.database, getBinaryData);
  1203. return this;
  1204. }
  1205. /**
  1206. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  1207. */
  1208. public isInFrustum(frustumPlanes: Plane[]): boolean {
  1209. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  1210. return false;
  1211. }
  1212. if (!super.isInFrustum(frustumPlanes)) {
  1213. return false;
  1214. }
  1215. this._checkDelayState();
  1216. return true;
  1217. }
  1218. /**
  1219. * Sets the mesh material by the material or multiMaterial `id` property.
  1220. * The material `id` is a string identifying the material or the multiMaterial.
  1221. * This method returns the Mesh.
  1222. */
  1223. public setMaterialByID(id: string): Mesh {
  1224. var materials = this.getScene().materials;
  1225. var index: number;
  1226. for (index = materials.length - 1; index > -1; index--) {
  1227. if (materials[index].id === id) {
  1228. this.material = materials[index];
  1229. return this;
  1230. }
  1231. }
  1232. // Multi
  1233. var multiMaterials = this.getScene().multiMaterials;
  1234. for (index = multiMaterials.length - 1; index > -1; index--) {
  1235. if (multiMaterials[index].id === id) {
  1236. this.material = multiMaterials[index];
  1237. return this;
  1238. }
  1239. }
  1240. return this;
  1241. }
  1242. /**
  1243. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  1244. */
  1245. public getAnimatables(): IAnimatable[] {
  1246. var results = new Array<IAnimatable>();
  1247. if (this.material) {
  1248. results.push(this.material);
  1249. }
  1250. if (this.skeleton) {
  1251. results.push(this.skeleton);
  1252. }
  1253. return results;
  1254. }
  1255. /**
  1256. * Modifies the mesh geometry according to the passed transformation matrix.
  1257. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  1258. * The mesh normals are modified accordingly the same transformation.
  1259. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  1260. * Note that, under the hood, this method sets a new VertexBuffer each call.
  1261. * Returns the Mesh.
  1262. */
  1263. public bakeTransformIntoVertices(transform: Matrix): Mesh {
  1264. // Position
  1265. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  1266. return this;
  1267. }
  1268. var submeshes = this.subMeshes.splice(0);
  1269. this._resetPointsArrayCache();
  1270. var data = <FloatArray>this.getVerticesData(VertexBuffer.PositionKind);
  1271. var temp = new Array<number>();
  1272. var index: number;
  1273. for (index = 0; index < data.length; index += 3) {
  1274. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  1275. }
  1276. this.setVerticesData(VertexBuffer.PositionKind, temp, (<VertexBuffer>this.getVertexBuffer(VertexBuffer.PositionKind)).isUpdatable());
  1277. // Normals
  1278. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1279. return this;
  1280. }
  1281. data = <FloatArray>this.getVerticesData(VertexBuffer.NormalKind);
  1282. temp = [];
  1283. for (index = 0; index < data.length; index += 3) {
  1284. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  1285. }
  1286. this.setVerticesData(VertexBuffer.NormalKind, temp, (<VertexBuffer>this.getVertexBuffer(VertexBuffer.NormalKind)).isUpdatable());
  1287. // flip faces?
  1288. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
  1289. // Restore submeshes
  1290. this.releaseSubMeshes();
  1291. this.subMeshes = submeshes;
  1292. return this;
  1293. }
  1294. /**
  1295. * Modifies the mesh geometry according to its own current World Matrix.
  1296. * The mesh World Matrix is then reset.
  1297. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  1298. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  1299. * Note that, under the hood, this method sets a new VertexBuffer each call.
  1300. * Returns the Mesh.
  1301. */
  1302. public bakeCurrentTransformIntoVertices(): Mesh {
  1303. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  1304. this.scaling.copyFromFloats(1, 1, 1);
  1305. this.position.copyFromFloats(0, 0, 0);
  1306. this.rotation.copyFromFloats(0, 0, 0);
  1307. //only if quaternion is already set
  1308. if (this.rotationQuaternion) {
  1309. this.rotationQuaternion = Quaternion.Identity();
  1310. }
  1311. this._worldMatrix = Matrix.Identity();
  1312. return this;
  1313. }
  1314. // Cache
  1315. public get _positions(): Nullable<Vector3[]> {
  1316. if (this._geometry) {
  1317. return this._geometry._positions;
  1318. }
  1319. return null;
  1320. }
  1321. public _resetPointsArrayCache(): Mesh {
  1322. if (this._geometry) {
  1323. this._geometry._resetPointsArrayCache();
  1324. }
  1325. return this;
  1326. }
  1327. public _generatePointsArray(): boolean {
  1328. if (this._geometry) {
  1329. return this._geometry._generatePointsArray();
  1330. }
  1331. return false;
  1332. }
  1333. /**
  1334. * Returns a new Mesh object generated from the current mesh properties.
  1335. * This method must not get confused with createInstance().
  1336. * The parameter `name` is a string, the name given to the new mesh.
  1337. * The optional parameter `newParent` can be any Node object (default `null`).
  1338. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  1339. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  1340. */
  1341. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true): Mesh {
  1342. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  1343. }
  1344. /**
  1345. * Disposes the Mesh.
  1346. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  1347. * Returns nothing.
  1348. */
  1349. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures: boolean = false): void {
  1350. this.morphTargetManager = null;
  1351. if (this._geometry) {
  1352. this._geometry.releaseForMesh(this, true);
  1353. }
  1354. // Sources
  1355. var meshes = this.getScene().meshes;
  1356. meshes.forEach((mesh: Mesh) => {
  1357. if (mesh._source && mesh._source === this) {
  1358. mesh._source = null;
  1359. }
  1360. });
  1361. this._source = null;
  1362. // Instances
  1363. if (this._instancesBuffer) {
  1364. this._instancesBuffer.dispose();
  1365. this._instancesBuffer = null;
  1366. }
  1367. while (this.instances.length) {
  1368. this.instances[0].dispose();
  1369. }
  1370. // Highlight layers.
  1371. let highlightLayers = this.getScene().highlightLayers;
  1372. for (let i = 0; i < highlightLayers.length; i++) {
  1373. let highlightLayer = highlightLayers[i];
  1374. if (highlightLayer) {
  1375. highlightLayer.removeMesh(this);
  1376. highlightLayer.removeExcludedMesh(this);
  1377. }
  1378. }
  1379. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  1380. }
  1381. /**
  1382. * Modifies the mesh geometry according to a displacement map.
  1383. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  1384. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  1385. * This method returns nothing.
  1386. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  1387. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  1388. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  1389. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  1390. * The parameter `uvScale` is an optional vector2 used to scale UV.
  1391. *
  1392. * Returns the Mesh.
  1393. */
  1394. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void, uvOffset?: Vector2, uvScale?: Vector2): Mesh {
  1395. var scene = this.getScene();
  1396. var onload = (img: HTMLImageElement) => {
  1397. // Getting height map data
  1398. var canvas = document.createElement("canvas");
  1399. var context = <CanvasRenderingContext2D>canvas.getContext("2d");
  1400. var heightMapWidth = img.width;
  1401. var heightMapHeight = img.height;
  1402. canvas.width = heightMapWidth;
  1403. canvas.height = heightMapHeight;
  1404. context.drawImage(img, 0, 0);
  1405. // Create VertexData from map data
  1406. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1407. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1408. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  1409. //execute success callback, if set
  1410. if (onSuccess) {
  1411. onSuccess(this);
  1412. }
  1413. };
  1414. Tools.LoadImage(url, onload, () => { }, scene.database);
  1415. return this;
  1416. }
  1417. /**
  1418. * Modifies the mesh geometry according to a displacementMap buffer.
  1419. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  1420. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  1421. * This method returns nothing.
  1422. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  1423. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  1424. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  1425. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  1426. * The parameter `uvScale` is an optional vector2 used to scale UV.
  1427. *
  1428. * Returns the Mesh.
  1429. */
  1430. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number, uvOffset?: Vector2, uvScale?: Vector2): Mesh {
  1431. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  1432. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  1433. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  1434. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  1435. return this;
  1436. }
  1437. var positions = <FloatArray>this.getVerticesData(VertexBuffer.PositionKind);
  1438. var normals = <FloatArray>this.getVerticesData(VertexBuffer.NormalKind);
  1439. var uvs = <number[]>this.getVerticesData(VertexBuffer.UVKind);
  1440. var position = Vector3.Zero();
  1441. var normal = Vector3.Zero();
  1442. var uv = Vector2.Zero();
  1443. uvOffset = uvOffset || Vector2.Zero();
  1444. uvScale = uvScale || new Vector2(1, 1);
  1445. for (var index = 0; index < positions.length; index += 3) {
  1446. Vector3.FromArrayToRef(positions, index, position);
  1447. Vector3.FromArrayToRef(normals, index, normal);
  1448. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  1449. // Compute height
  1450. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  1451. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  1452. var pos = (u + v * heightMapWidth) * 4;
  1453. var r = buffer[pos] / 255.0;
  1454. var g = buffer[pos + 1] / 255.0;
  1455. var b = buffer[pos + 2] / 255.0;
  1456. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  1457. normal.normalize();
  1458. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  1459. position = position.add(normal);
  1460. position.toArray(positions, index);
  1461. }
  1462. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  1463. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  1464. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  1465. return this;
  1466. }
  1467. /**
  1468. * Modify the mesh to get a flat shading rendering.
  1469. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  1470. * This method returns the Mesh.
  1471. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  1472. */
  1473. public convertToFlatShadedMesh(): Mesh {
  1474. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  1475. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  1476. var kinds = this.getVerticesDataKinds();
  1477. var vbs: { [key: string]: VertexBuffer } = {};
  1478. var data: { [key: string]: FloatArray } = {};
  1479. var newdata: { [key: string]: Array<number> } = {};
  1480. var updatableNormals = false;
  1481. var kindIndex: number;
  1482. var kind: string;
  1483. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1484. kind = kinds[kindIndex];
  1485. var vertexBuffer = <VertexBuffer>this.getVertexBuffer(kind);
  1486. if (kind === VertexBuffer.NormalKind) {
  1487. updatableNormals = vertexBuffer.isUpdatable();
  1488. kinds.splice(kindIndex, 1);
  1489. kindIndex--;
  1490. continue;
  1491. }
  1492. vbs[kind] = vertexBuffer;
  1493. data[kind] = <FloatArray>vbs[kind].getData();
  1494. newdata[kind] = [];
  1495. }
  1496. // Save previous submeshes
  1497. var previousSubmeshes = this.subMeshes.slice(0);
  1498. var indices = <IndicesArray>this.getIndices();
  1499. var totalIndices = this.getTotalIndices();
  1500. // Generating unique vertices per face
  1501. var index: number;
  1502. for (index = 0; index < totalIndices; index++) {
  1503. var vertexIndex = indices[index];
  1504. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1505. kind = kinds[kindIndex];
  1506. var stride = vbs[kind].getStrideSize();
  1507. for (var offset = 0; offset < stride; offset++) {
  1508. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1509. }
  1510. }
  1511. }
  1512. // Updating faces & normal
  1513. var normals = [];
  1514. var positions = newdata[VertexBuffer.PositionKind];
  1515. for (index = 0; index < totalIndices; index += 3) {
  1516. indices[index] = index;
  1517. indices[index + 1] = index + 1;
  1518. indices[index + 2] = index + 2;
  1519. var p1 = Vector3.FromArray(positions, index * 3);
  1520. var p2 = Vector3.FromArray(positions, (index + 1) * 3);
  1521. var p3 = Vector3.FromArray(positions, (index + 2) * 3);
  1522. var p1p2 = p1.subtract(p2);
  1523. var p3p2 = p3.subtract(p2);
  1524. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  1525. // Store same normals for every vertex
  1526. for (var localIndex = 0; localIndex < 3; localIndex++) {
  1527. normals.push(normal.x);
  1528. normals.push(normal.y);
  1529. normals.push(normal.z);
  1530. }
  1531. }
  1532. this.setIndices(indices);
  1533. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  1534. // Updating vertex buffers
  1535. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1536. kind = kinds[kindIndex];
  1537. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1538. }
  1539. // Updating submeshes
  1540. this.releaseSubMeshes();
  1541. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1542. var previousOne = previousSubmeshes[submeshIndex];
  1543. SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1544. }
  1545. this.synchronizeInstances();
  1546. return this;
  1547. }
  1548. /**
  1549. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  1550. * In other words, more vertices, no more indices and a single bigger VBO.
  1551. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  1552. * Returns the Mesh.
  1553. */
  1554. public convertToUnIndexedMesh(): Mesh {
  1555. /// <summary>Remove indices by unfolding faces into buffers</summary>
  1556. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  1557. var kinds = this.getVerticesDataKinds();
  1558. var vbs: { [key: string]: VertexBuffer } = {};
  1559. var data: { [key: string]: FloatArray } = {};
  1560. var newdata: { [key: string]: Array<number> } = {};
  1561. var kindIndex: number;
  1562. var kind: string;
  1563. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1564. kind = kinds[kindIndex];
  1565. var vertexBuffer = <VertexBuffer>this.getVertexBuffer(kind);
  1566. vbs[kind] = vertexBuffer;
  1567. data[kind] = <FloatArray>vbs[kind].getData();
  1568. newdata[kind] = [];
  1569. }
  1570. // Save previous submeshes
  1571. var previousSubmeshes = this.subMeshes.slice(0);
  1572. var indices = <IndicesArray>this.getIndices();
  1573. var totalIndices = this.getTotalIndices();
  1574. // Generating unique vertices per face
  1575. var index: number;
  1576. for (index = 0; index < totalIndices; index++) {
  1577. var vertexIndex = indices[index];
  1578. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1579. kind = kinds[kindIndex];
  1580. var stride = vbs[kind].getStrideSize();
  1581. for (var offset = 0; offset < stride; offset++) {
  1582. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1583. }
  1584. }
  1585. }
  1586. // Updating indices
  1587. for (index = 0; index < totalIndices; index += 3) {
  1588. indices[index] = index;
  1589. indices[index + 1] = index + 1;
  1590. indices[index + 2] = index + 2;
  1591. }
  1592. this.setIndices(indices);
  1593. // Updating vertex buffers
  1594. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1595. kind = kinds[kindIndex];
  1596. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1597. }
  1598. // Updating submeshes
  1599. this.releaseSubMeshes();
  1600. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1601. var previousOne = previousSubmeshes[submeshIndex];
  1602. SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1603. }
  1604. this._unIndexed = true;
  1605. this.synchronizeInstances();
  1606. return this;
  1607. }
  1608. /**
  1609. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  1610. * This method returns the Mesh.
  1611. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  1612. */
  1613. public flipFaces(flipNormals: boolean = false): Mesh {
  1614. var vertex_data = VertexData.ExtractFromMesh(this);
  1615. var i: number;
  1616. if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind) && vertex_data.normals) {
  1617. for (i = 0; i < vertex_data.normals.length; i++) {
  1618. vertex_data.normals[i] *= -1;
  1619. }
  1620. }
  1621. if (vertex_data.indices) {
  1622. var temp;
  1623. for (i = 0; i < vertex_data.indices.length; i += 3) {
  1624. // reassign indices
  1625. temp = vertex_data.indices[i + 1];
  1626. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  1627. vertex_data.indices[i + 2] = temp;
  1628. }
  1629. }
  1630. vertex_data.applyToMesh(this);
  1631. return this;
  1632. }
  1633. // Instances
  1634. /**
  1635. * Creates a new InstancedMesh object from the mesh model.
  1636. * An instance shares the same properties and the same material than its model.
  1637. * Only these properties of each instance can then be set individually :
  1638. * - position
  1639. * - rotation
  1640. * - rotationQuaternion
  1641. * - setPivotMatrix
  1642. * - scaling
  1643. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  1644. * Warning : this method is not supported for Line mesh and LineSystem
  1645. */
  1646. public createInstance(name: string): InstancedMesh {
  1647. return new InstancedMesh(name, this);
  1648. }
  1649. /**
  1650. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  1651. * After this call, all the mesh instances have the same submeshes than the current mesh.
  1652. * This method returns the Mesh.
  1653. */
  1654. public synchronizeInstances(): Mesh {
  1655. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  1656. var instance = this.instances[instanceIndex];
  1657. instance._syncSubMeshes();
  1658. }
  1659. return this;
  1660. }
  1661. /**
  1662. * Simplify the mesh according to the given array of settings.
  1663. * Function will return immediately and will simplify async. It returns the Mesh.
  1664. * @param settings a collection of simplification settings.
  1665. * @param parallelProcessing should all levels calculate parallel or one after the other.
  1666. * @param type the type of simplification to run.
  1667. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  1668. */
  1669. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, simplificationType: SimplificationType = SimplificationType.QUADRATIC, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void): Mesh {
  1670. this.getScene().simplificationQueue.addTask({
  1671. settings: settings,
  1672. parallelProcessing: parallelProcessing,
  1673. mesh: this,
  1674. simplificationType: simplificationType,
  1675. successCallback: successCallback
  1676. });
  1677. return this;
  1678. }
  1679. /**
  1680. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  1681. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  1682. * This should be used together with the simplification to avoid disappearing triangles.
  1683. * Returns the Mesh.
  1684. * @param successCallback an optional success callback to be called after the optimization finished.
  1685. */
  1686. public optimizeIndices(successCallback?: (mesh?: Mesh) => void): Mesh {
  1687. var indices = <IndicesArray>this.getIndices();
  1688. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1689. if (!positions || !indices) {
  1690. return this;
  1691. }
  1692. var vectorPositions = new Array<Vector3>();
  1693. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  1694. vectorPositions.push(Vector3.FromArray(positions, pos));
  1695. }
  1696. var dupes = new Array<number>();
  1697. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
  1698. var realPos = vectorPositions.length - 1 - iteration;
  1699. var testedPosition = vectorPositions[realPos];
  1700. for (var j = 0; j < realPos; ++j) {
  1701. var againstPosition = vectorPositions[j];
  1702. if (testedPosition.equals(againstPosition)) {
  1703. dupes[realPos] = j;
  1704. break;
  1705. }
  1706. }
  1707. }, () => {
  1708. for (var i = 0; i < indices.length; ++i) {
  1709. indices[i] = dupes[indices[i]] || indices[i];
  1710. }
  1711. //indices are now reordered
  1712. var originalSubMeshes = this.subMeshes.slice(0);
  1713. this.setIndices(indices);
  1714. this.subMeshes = originalSubMeshes;
  1715. if (successCallback) {
  1716. successCallback(this);
  1717. }
  1718. });
  1719. return this;
  1720. }
  1721. public serialize(serializationObject: any): void {
  1722. serializationObject.name = this.name;
  1723. serializationObject.id = this.id;
  1724. serializationObject.type = this.getClassName();
  1725. if (Tags && Tags.HasTags(this)) {
  1726. serializationObject.tags = Tags.GetTags(this);
  1727. }
  1728. serializationObject.position = this.position.asArray();
  1729. if (this.rotationQuaternion) {
  1730. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  1731. } else if (this.rotation) {
  1732. serializationObject.rotation = this.rotation.asArray();
  1733. }
  1734. serializationObject.scaling = this.scaling.asArray();
  1735. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  1736. serializationObject.isEnabled = this.isEnabled();
  1737. serializationObject.isVisible = this.isVisible;
  1738. serializationObject.infiniteDistance = this.infiniteDistance;
  1739. serializationObject.pickable = this.isPickable;
  1740. serializationObject.receiveShadows = this.receiveShadows;
  1741. serializationObject.billboardMode = this.billboardMode;
  1742. serializationObject.visibility = this.visibility;
  1743. serializationObject.checkCollisions = this.checkCollisions;
  1744. serializationObject.isBlocker = this.isBlocker;
  1745. // Parent
  1746. if (this.parent) {
  1747. serializationObject.parentId = this.parent.id;
  1748. }
  1749. // Geometry
  1750. var geometry = this._geometry;
  1751. if (geometry) {
  1752. var geometryId = geometry.id;
  1753. serializationObject.geometryId = geometryId;
  1754. // SubMeshes
  1755. serializationObject.subMeshes = [];
  1756. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  1757. var subMesh = this.subMeshes[subIndex];
  1758. serializationObject.subMeshes.push({
  1759. materialIndex: subMesh.materialIndex,
  1760. verticesStart: subMesh.verticesStart,
  1761. verticesCount: subMesh.verticesCount,
  1762. indexStart: subMesh.indexStart,
  1763. indexCount: subMesh.indexCount
  1764. });
  1765. }
  1766. }
  1767. // Material
  1768. if (this.material) {
  1769. serializationObject.materialId = this.material.id;
  1770. } else {
  1771. this.material = null;
  1772. }
  1773. // Morph targets
  1774. if (this.morphTargetManager) {
  1775. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  1776. }
  1777. // Skeleton
  1778. if (this.skeleton) {
  1779. serializationObject.skeletonId = this.skeleton.id;
  1780. }
  1781. // Physics
  1782. //TODO implement correct serialization for physics impostors.
  1783. let impostor = this.getPhysicsImpostor();
  1784. if (impostor) {
  1785. serializationObject.physicsMass = impostor.getParam("mass");
  1786. serializationObject.physicsFriction = impostor.getParam("friction");
  1787. serializationObject.physicsRestitution = impostor.getParam("mass");
  1788. serializationObject.physicsImpostor = impostor.type;
  1789. }
  1790. // Metadata
  1791. if (this.metadata) {
  1792. serializationObject.metadata = this.metadata;
  1793. }
  1794. // Instances
  1795. serializationObject.instances = [];
  1796. for (var index = 0; index < this.instances.length; index++) {
  1797. var instance = this.instances[index];
  1798. var serializationInstance: any = {
  1799. name: instance.name,
  1800. position: instance.position.asArray(),
  1801. scaling: instance.scaling.asArray()
  1802. };
  1803. if (instance.rotationQuaternion) {
  1804. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  1805. } else if (instance.rotation) {
  1806. serializationInstance.rotation = instance.rotation.asArray();
  1807. }
  1808. serializationObject.instances.push(serializationInstance);
  1809. // Animations
  1810. Animation.AppendSerializedAnimations(instance, serializationInstance);
  1811. serializationInstance.ranges = instance.serializeAnimationRanges();
  1812. }
  1813. //
  1814. // Animations
  1815. Animation.AppendSerializedAnimations(this, serializationObject);
  1816. serializationObject.ranges = this.serializeAnimationRanges();
  1817. // Layer mask
  1818. serializationObject.layerMask = this.layerMask;
  1819. // Alpha
  1820. serializationObject.alphaIndex = this.alphaIndex;
  1821. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  1822. // Overlay
  1823. serializationObject.overlayAlpha = this.overlayAlpha;
  1824. serializationObject.overlayColor = this.overlayColor.asArray();
  1825. serializationObject.renderOverlay = this.renderOverlay;
  1826. // Fog
  1827. serializationObject.applyFog = this.applyFog;
  1828. // Action Manager
  1829. if (this.actionManager) {
  1830. serializationObject.actions = this.actionManager.serialize(this.name);
  1831. }
  1832. }
  1833. public _syncGeometryWithMorphTargetManager() {
  1834. if (!this.geometry) {
  1835. return;
  1836. }
  1837. this._markSubMeshesAsAttributesDirty();
  1838. let morphTargetManager = this._morphTargetManager;
  1839. if (morphTargetManager && morphTargetManager.vertexCount) {
  1840. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  1841. Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  1842. this.morphTargetManager = null;
  1843. return;
  1844. }
  1845. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  1846. var morphTarget = morphTargetManager.getActiveTarget(index);
  1847. const positions = morphTarget.getPositions();
  1848. if (!positions) {
  1849. Tools.Error("Invalid morph target. Target must have positions.");
  1850. return;
  1851. }
  1852. this.geometry.setVerticesData(VertexBuffer.PositionKind + index, positions, false, 3);
  1853. const normals = morphTarget.getNormals();
  1854. if (normals) {
  1855. this.geometry.setVerticesData(VertexBuffer.NormalKind + index, normals, false, 3);
  1856. }
  1857. const tangents = morphTarget.getTangents();
  1858. if (tangents) {
  1859. this.geometry.setVerticesData(VertexBuffer.TangentKind + index, tangents, false, 3);
  1860. }
  1861. }
  1862. } else {
  1863. var index = 0;
  1864. // Positions
  1865. while (this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind + index)) {
  1866. this.geometry.removeVerticesData(VertexBuffer.PositionKind + index);
  1867. if (this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind + index)) {
  1868. this.geometry.removeVerticesData(VertexBuffer.NormalKind + index);
  1869. }
  1870. if (this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind + index)) {
  1871. this.geometry.removeVerticesData(VertexBuffer.TangentKind + index);
  1872. }
  1873. index++;
  1874. }
  1875. }
  1876. }
  1877. // Statics
  1878. /**
  1879. * Returns a new Mesh object parsed from the source provided.
  1880. * The parameter `parsedMesh` is the source.
  1881. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  1882. */
  1883. public static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh {
  1884. var mesh: Mesh;
  1885. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  1886. mesh = GroundMesh.Parse(parsedMesh, scene);
  1887. } else {
  1888. mesh = new Mesh(parsedMesh.name, scene);
  1889. }
  1890. mesh.id = parsedMesh.id;
  1891. if (Tags) {
  1892. Tags.AddTagsTo(mesh, parsedMesh.tags);
  1893. }
  1894. mesh.position = Vector3.FromArray(parsedMesh.position);
  1895. if (parsedMesh.metadata !== undefined) {
  1896. mesh.metadata = parsedMesh.metadata;
  1897. }
  1898. if (parsedMesh.rotationQuaternion) {
  1899. mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion);
  1900. } else if (parsedMesh.rotation) {
  1901. mesh.rotation = Vector3.FromArray(parsedMesh.rotation);
  1902. }
  1903. mesh.scaling = Vector3.FromArray(parsedMesh.scaling);
  1904. if (parsedMesh.localMatrix) {
  1905. mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.localMatrix));
  1906. } else if (parsedMesh.pivotMatrix) {
  1907. mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix));
  1908. }
  1909. mesh.setEnabled(parsedMesh.isEnabled);
  1910. mesh.isVisible = parsedMesh.isVisible;
  1911. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  1912. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  1913. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  1914. if (parsedMesh.applyFog !== undefined) {
  1915. mesh.applyFog = parsedMesh.applyFog;
  1916. }
  1917. if (parsedMesh.pickable !== undefined) {
  1918. mesh.isPickable = parsedMesh.pickable;
  1919. }
  1920. if (parsedMesh.alphaIndex !== undefined) {
  1921. mesh.alphaIndex = parsedMesh.alphaIndex;
  1922. }
  1923. mesh.receiveShadows = parsedMesh.receiveShadows;
  1924. mesh.billboardMode = parsedMesh.billboardMode;
  1925. if (parsedMesh.visibility !== undefined) {
  1926. mesh.visibility = parsedMesh.visibility;
  1927. }
  1928. mesh.checkCollisions = parsedMesh.checkCollisions;
  1929. if (parsedMesh.isBlocker !== undefined) {
  1930. mesh.isBlocker = parsedMesh.isBlocker;
  1931. }
  1932. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  1933. // freezeWorldMatrix
  1934. if (parsedMesh.freezeWorldMatrix) {
  1935. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  1936. }
  1937. // Parent
  1938. if (parsedMesh.parentId) {
  1939. mesh._waitingParentId = parsedMesh.parentId;
  1940. }
  1941. // Actions
  1942. if (parsedMesh.actions !== undefined) {
  1943. mesh._waitingActions = parsedMesh.actions;
  1944. }
  1945. // Overlay
  1946. if (parsedMesh.overlayAlpha !== undefined) {
  1947. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  1948. }
  1949. if (parsedMesh.overlayColor !== undefined) {
  1950. mesh.overlayColor = Color3.FromArray(parsedMesh.overlayColor);
  1951. }
  1952. if (parsedMesh.renderOverlay !== undefined) {
  1953. mesh.renderOverlay = parsedMesh.renderOverlay;
  1954. }
  1955. // Geometry
  1956. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  1957. if (parsedMesh.delayLoadingFile) {
  1958. mesh.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
  1959. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  1960. mesh._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  1961. if (parsedMesh._binaryInfo) {
  1962. mesh._binaryInfo = parsedMesh._binaryInfo;
  1963. }
  1964. mesh._delayInfo = [];
  1965. if (parsedMesh.hasUVs) {
  1966. mesh._delayInfo.push(VertexBuffer.UVKind);
  1967. }
  1968. if (parsedMesh.hasUVs2) {
  1969. mesh._delayInfo.push(VertexBuffer.UV2Kind);
  1970. }
  1971. if (parsedMesh.hasUVs3) {
  1972. mesh._delayInfo.push(VertexBuffer.UV3Kind);
  1973. }
  1974. if (parsedMesh.hasUVs4) {
  1975. mesh._delayInfo.push(VertexBuffer.UV4Kind);
  1976. }
  1977. if (parsedMesh.hasUVs5) {
  1978. mesh._delayInfo.push(VertexBuffer.UV5Kind);
  1979. }
  1980. if (parsedMesh.hasUVs6) {
  1981. mesh._delayInfo.push(VertexBuffer.UV6Kind);
  1982. }
  1983. if (parsedMesh.hasColors) {
  1984. mesh._delayInfo.push(VertexBuffer.ColorKind);
  1985. }
  1986. if (parsedMesh.hasMatricesIndices) {
  1987. mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind);
  1988. }
  1989. if (parsedMesh.hasMatricesWeights) {
  1990. mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind);
  1991. }
  1992. mesh._delayLoadingFunction = Geometry.ImportGeometry;
  1993. if (SceneLoader.ForceFullSceneLoadingForIncremental) {
  1994. mesh._checkDelayState();
  1995. }
  1996. } else {
  1997. Geometry.ImportGeometry(parsedMesh, mesh);
  1998. }
  1999. // Material
  2000. if (parsedMesh.materialId) {
  2001. mesh.setMaterialByID(parsedMesh.materialId);
  2002. } else {
  2003. mesh.material = null;
  2004. }
  2005. // Morph targets
  2006. if (parsedMesh.morphTargetManagerId > -1) {
  2007. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  2008. }
  2009. // Skeleton
  2010. if (parsedMesh.skeletonId > -1) {
  2011. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  2012. if (parsedMesh.numBoneInfluencers) {
  2013. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  2014. }
  2015. }
  2016. // Animations
  2017. if (parsedMesh.animations) {
  2018. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  2019. var parsedAnimation = parsedMesh.animations[animationIndex];
  2020. mesh.animations.push(Animation.Parse(parsedAnimation));
  2021. }
  2022. Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  2023. }
  2024. if (parsedMesh.autoAnimate) {
  2025. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  2026. }
  2027. // Layer Mask
  2028. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  2029. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  2030. } else {
  2031. mesh.layerMask = 0x0FFFFFFF;
  2032. }
  2033. // Physics
  2034. if (parsedMesh.physicsImpostor) {
  2035. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  2036. mass: parsedMesh.physicsMass,
  2037. friction: parsedMesh.physicsFriction,
  2038. restitution: parsedMesh.physicsRestitution
  2039. }, scene);
  2040. }
  2041. // Instances
  2042. if (parsedMesh.instances) {
  2043. for (var index = 0; index < parsedMesh.instances.length; index++) {
  2044. var parsedInstance = parsedMesh.instances[index];
  2045. var instance = mesh.createInstance(parsedInstance.name);
  2046. if (Tags) {
  2047. Tags.AddTagsTo(instance, parsedInstance.tags);
  2048. }
  2049. instance.position = Vector3.FromArray(parsedInstance.position);
  2050. if (parsedInstance.parentId) {
  2051. instance._waitingParentId = parsedInstance.parentId;
  2052. }
  2053. if (parsedInstance.rotationQuaternion) {
  2054. instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion);
  2055. } else if (parsedInstance.rotation) {
  2056. instance.rotation = Vector3.FromArray(parsedInstance.rotation);
  2057. }
  2058. instance.scaling = Vector3.FromArray(parsedInstance.scaling);
  2059. instance.checkCollisions = mesh.checkCollisions;
  2060. if (parsedMesh.animations) {
  2061. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  2062. parsedAnimation = parsedMesh.animations[animationIndex];
  2063. instance.animations.push(Animation.Parse(parsedAnimation));
  2064. }
  2065. Node.ParseAnimationRanges(instance, parsedMesh, scene);
  2066. }
  2067. }
  2068. }
  2069. return mesh;
  2070. }
  2071. /**
  2072. * Creates a ribbon mesh.
  2073. * Please consider using the same method from the MeshBuilder class instead.
  2074. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  2075. *
  2076. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  2077. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  2078. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  2079. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  2080. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  2081. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  2082. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  2083. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2084. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2085. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2086. */
  2087. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean = false, closePath: boolean, offset: number, scene?: Scene, updatable: boolean = false, sideOrientation?: number, instance?: Mesh): Mesh {
  2088. return MeshBuilder.CreateRibbon(name, {
  2089. pathArray: pathArray,
  2090. closeArray: closeArray,
  2091. closePath: closePath,
  2092. offset: offset,
  2093. updatable: updatable,
  2094. sideOrientation: sideOrientation,
  2095. instance: instance
  2096. }, scene);
  2097. }
  2098. /**
  2099. * Creates a plane polygonal mesh. By default, this is a disc.
  2100. * Please consider using the same method from the MeshBuilder class instead.
  2101. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  2102. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  2103. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2104. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2105. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2106. */
  2107. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Nullable<Scene> = null, updatable?: boolean, sideOrientation?: number): Mesh {
  2108. var options = {
  2109. radius: radius,
  2110. tessellation: tessellation,
  2111. sideOrientation: sideOrientation,
  2112. updatable: updatable
  2113. }
  2114. return MeshBuilder.CreateDisc(name, options, scene);
  2115. }
  2116. /**
  2117. * Creates a box mesh.
  2118. * Please consider using the same method from the MeshBuilder class instead.
  2119. * The parameter `size` sets the size (float) of each box side (default 1).
  2120. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2121. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2122. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2123. */
  2124. public static CreateBox(name: string, size: number, scene: Nullable<Scene> = null, updatable?: boolean, sideOrientation?: number): Mesh {
  2125. var options = {
  2126. size: size,
  2127. sideOrientation: sideOrientation,
  2128. updatable: updatable
  2129. };
  2130. return MeshBuilder.CreateBox(name, options, scene);
  2131. }
  2132. /**
  2133. * Creates a sphere mesh.
  2134. * Please consider using the same method from the MeshBuilder class instead.
  2135. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  2136. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  2137. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2138. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2139. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2140. */
  2141. public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2142. var options = {
  2143. segments: segments,
  2144. diameterX: diameter,
  2145. diameterY: diameter,
  2146. diameterZ: diameter,
  2147. sideOrientation: sideOrientation,
  2148. updatable: updatable
  2149. }
  2150. return MeshBuilder.CreateSphere(name, options, scene);
  2151. }
  2152. /**
  2153. * Creates a cylinder or a cone mesh.
  2154. * Please consider using the same method from the MeshBuilder class instead.
  2155. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  2156. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  2157. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  2158. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  2159. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  2160. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2161. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2162. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2163. */
  2164. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene?: Scene, updatable?: any, sideOrientation?: number): Mesh {
  2165. if (scene === undefined || !(scene instanceof Scene)) {
  2166. if (scene !== undefined) {
  2167. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  2168. updatable = scene;
  2169. }
  2170. scene = <Scene>subdivisions;
  2171. subdivisions = 1;
  2172. }
  2173. var options = {
  2174. height: height,
  2175. diameterTop: diameterTop,
  2176. diameterBottom: diameterBottom,
  2177. tessellation: tessellation,
  2178. subdivisions: subdivisions,
  2179. sideOrientation: sideOrientation,
  2180. updatable: updatable
  2181. }
  2182. return MeshBuilder.CreateCylinder(name, options, scene);
  2183. }
  2184. // Torus (Code from SharpDX.org)
  2185. /**
  2186. * Creates a torus mesh.
  2187. * Please consider using the same method from the MeshBuilder class instead.
  2188. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  2189. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  2190. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  2191. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2192. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2193. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2194. */
  2195. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2196. var options = {
  2197. diameter: diameter,
  2198. thickness: thickness,
  2199. tessellation: tessellation,
  2200. sideOrientation: sideOrientation,
  2201. updatable: updatable
  2202. }
  2203. return MeshBuilder.CreateTorus(name, options, scene);
  2204. }
  2205. /**
  2206. * Creates a torus knot mesh.
  2207. * Please consider using the same method from the MeshBuilder class instead.
  2208. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  2209. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  2210. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  2211. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  2212. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2213. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2215. */
  2216. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2217. var options = {
  2218. radius: radius,
  2219. tube: tube,
  2220. radialSegments: radialSegments,
  2221. tubularSegments: tubularSegments,
  2222. p: p,
  2223. q: q,
  2224. sideOrientation: sideOrientation,
  2225. updatable: updatable
  2226. }
  2227. return MeshBuilder.CreateTorusKnot(name, options, scene);
  2228. }
  2229. /**
  2230. * Creates a line mesh.
  2231. * Please consider using the same method from the MeshBuilder class instead.
  2232. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  2233. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  2234. * The parameter `points` is an array successive Vector3.
  2235. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  2236. * When updating an instance, remember that only point positions can change, not the number of points.
  2237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2238. */
  2239. public static CreateLines(name: string, points: Vector3[], scene: Nullable<Scene> = null, updatable: boolean = false, instance: Nullable<LinesMesh> = null): LinesMesh {
  2240. var options = {
  2241. points: points,
  2242. updatable: updatable,
  2243. instance: instance
  2244. }
  2245. return MeshBuilder.CreateLines(name, options, scene);
  2246. }
  2247. /**
  2248. * Creates a dashed line mesh.
  2249. * Please consider using the same method from the MeshBuilder class instead.
  2250. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  2251. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  2252. * The parameter `points` is an array successive Vector3.
  2253. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  2254. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  2255. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  2256. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  2257. * When updating an instance, remember that only point positions can change, not the number of points.
  2258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2259. */
  2260. public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Nullable<Scene> = null, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  2261. var options = {
  2262. points: points,
  2263. dashSize: dashSize,
  2264. gapSize: gapSize,
  2265. dashNb: dashNb,
  2266. updatable: updatable,
  2267. instance: instance
  2268. }
  2269. return MeshBuilder.CreateDashedLines(name, options, scene);
  2270. }
  2271. /**
  2272. * Creates a polygon mesh.
  2273. * Please consider using the same method from the MeshBuilder class instead.
  2274. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  2275. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  2276. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2278. * Remember you can only change the shape positions, not their number when updating a polygon.
  2279. */
  2280. public static CreatePolygon(name: string, shape: Vector3[], scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh {
  2281. var options = {
  2282. shape: shape,
  2283. holes: holes,
  2284. updatable: updatable,
  2285. sideOrientation: sideOrientation
  2286. }
  2287. return MeshBuilder.CreatePolygon(name, options, scene);
  2288. }
  2289. /**
  2290. * Creates an extruded polygon mesh, with depth in the Y direction.
  2291. * Please consider using the same method from the MeshBuilder class instead.
  2292. */
  2293. public static ExtrudePolygon(name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number): Mesh {
  2294. var options = {
  2295. shape: shape,
  2296. holes: holes,
  2297. depth: depth,
  2298. updatable: updatable,
  2299. sideOrientation: sideOrientation
  2300. }
  2301. return MeshBuilder.ExtrudePolygon(name, options, scene);
  2302. }
  2303. /**
  2304. * Creates an extruded shape mesh.
  2305. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  2306. * Please consider using the same method from the MeshBuilder class instead.
  2307. *
  2308. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  2309. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  2310. * extruded along the Z axis.
  2311. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  2312. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  2313. * The parameter `scale` (float, default 1) is the value to scale the shape.
  2314. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  2315. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  2316. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  2317. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2318. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2319. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2320. */
  2321. public static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Nullable<Scene> = null, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  2322. var options = {
  2323. shape: shape,
  2324. path: path,
  2325. scale: scale,
  2326. rotation: rotation,
  2327. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  2328. sideOrientation: sideOrientation,
  2329. instance: instance,
  2330. updatable: updatable
  2331. }
  2332. return MeshBuilder.ExtrudeShape(name, options, scene);
  2333. }
  2334. /**
  2335. * Creates an custom extruded shape mesh.
  2336. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  2337. * Please consider using the same method from the MeshBuilder class instead.
  2338. *
  2339. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  2340. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  2341. * extruded along the Z axis.
  2342. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  2343. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  2344. * and the distance of this point from the begining of the path :
  2345. * ```javascript
  2346. * var rotationFunction = function(i, distance) {
  2347. * // do things
  2348. * return rotationValue; }
  2349. * ```
  2350. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  2351. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  2352. * and the distance of this point from the begining of the path :
  2353. * ```javascript
  2354. * var scaleFunction = function(i, distance) {
  2355. * // do things
  2356. * return scaleValue;}
  2357. * ```
  2358. * It must returns a float value that will be the scale value applied to the shape on each path point.
  2359. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  2360. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  2361. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  2362. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  2363. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  2364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2365. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2366. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2367. */
  2368. public static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: Function, rotationFunction: Function, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  2369. var options = {
  2370. shape: shape,
  2371. path: path,
  2372. scaleFunction: scaleFunction,
  2373. rotationFunction: rotationFunction,
  2374. ribbonCloseArray: ribbonCloseArray,
  2375. ribbonClosePath: ribbonClosePath,
  2376. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  2377. sideOrientation: sideOrientation,
  2378. instance: instance,
  2379. updatable: updatable
  2380. }
  2381. return MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  2382. }
  2383. /**
  2384. * Creates lathe mesh.
  2385. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  2386. * Please consider using the same method from the MeshBuilder class instead.
  2387. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  2388. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  2389. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  2390. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  2391. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2392. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2394. */
  2395. public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2396. var options = {
  2397. shape: shape,
  2398. radius: radius,
  2399. tessellation: tessellation,
  2400. sideOrientation: sideOrientation,
  2401. updatable: updatable
  2402. };
  2403. return MeshBuilder.CreateLathe(name, options, scene);
  2404. }
  2405. /**
  2406. * Creates a plane mesh.
  2407. * Please consider using the same method from the MeshBuilder class instead.
  2408. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  2409. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2410. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2411. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2412. */
  2413. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2414. var options = {
  2415. size: size,
  2416. width: size,
  2417. height: size,
  2418. sideOrientation: sideOrientation,
  2419. updatable: updatable
  2420. }
  2421. return MeshBuilder.CreatePlane(name, options, scene);
  2422. }
  2423. /**
  2424. * Creates a ground mesh.
  2425. * Please consider using the same method from the MeshBuilder class instead.
  2426. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  2427. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  2428. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2429. */
  2430. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene?: Scene, updatable?: boolean): Mesh {
  2431. var options = {
  2432. width: width,
  2433. height: height,
  2434. subdivisions: subdivisions,
  2435. updatable: updatable
  2436. }
  2437. return MeshBuilder.CreateGround(name, options, scene);
  2438. }
  2439. /**
  2440. * Creates a tiled ground mesh.
  2441. * Please consider using the same method from the MeshBuilder class instead.
  2442. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  2443. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  2444. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  2445. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  2446. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  2447. * numbers of subdivisions on the ground width and height of each tile.
  2448. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2449. */
  2450. 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 {
  2451. var options = {
  2452. xmin: xmin,
  2453. zmin: zmin,
  2454. xmax: xmax,
  2455. zmax: zmax,
  2456. subdivisions: subdivisions,
  2457. precision: precision,
  2458. updatable: updatable
  2459. }
  2460. return MeshBuilder.CreateTiledGround(name, options, scene);
  2461. }
  2462. /**
  2463. * Creates a ground mesh from a height map.
  2464. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  2465. * Please consider using the same method from the MeshBuilder class instead.
  2466. * The parameter `url` sets the URL of the height map image resource.
  2467. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  2468. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  2469. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  2470. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  2471. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  2472. * This function is passed the newly built mesh :
  2473. * ```javascript
  2474. * function(mesh) { // do things
  2475. * return; }
  2476. * ```
  2477. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2478. */
  2479. 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 {
  2480. var options = {
  2481. width: width,
  2482. height: height,
  2483. subdivisions: subdivisions,
  2484. minHeight: minHeight,
  2485. maxHeight: maxHeight,
  2486. updatable: updatable,
  2487. onReady: onReady
  2488. };
  2489. return MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  2490. }
  2491. /**
  2492. * Creates a tube mesh.
  2493. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  2494. * Please consider using the same method from the MeshBuilder class instead.
  2495. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  2496. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  2497. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  2498. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  2499. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  2500. * It must return a radius value (positive float) :
  2501. * ```javascript
  2502. * var radiusFunction = function(i, distance) {
  2503. * // do things
  2504. * return radius; }
  2505. * ```
  2506. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  2507. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  2508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2511. */
  2512. 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, instance?: Mesh): Mesh {
  2513. var options = {
  2514. path: path,
  2515. radius: radius,
  2516. tessellation: tessellation,
  2517. radiusFunction: radiusFunction,
  2518. arc: 1,
  2519. cap: cap,
  2520. updatable: updatable,
  2521. sideOrientation: sideOrientation,
  2522. instance: instance
  2523. }
  2524. return MeshBuilder.CreateTube(name, options, scene);
  2525. }
  2526. /**
  2527. * Creates a polyhedron mesh.
  2528. * Please consider using the same method from the MeshBuilder class instead.
  2529. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  2530. * to choose the wanted type.
  2531. * The parameter `size` (positive float, default 1) sets the polygon size.
  2532. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  2533. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  2534. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  2535. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  2536. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  2537. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  2538. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2539. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2541. */
  2542. public static CreatePolyhedron(name: string, options: { type?: number, size?: number, sizeX?: number, sizeY?: number, sizeZ?: number, custom?: any, faceUV?: Vector4[], faceColors?: Color4[], updatable?: boolean, sideOrientation?: number }, scene: Scene): Mesh {
  2543. return MeshBuilder.CreatePolyhedron(name, options, scene);
  2544. }
  2545. /**
  2546. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  2547. * Please consider using the same method from the MeshBuilder class instead.
  2548. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  2549. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  2550. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  2551. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  2552. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  2553. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  2554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2555. */
  2556. public static CreateIcoSphere(name: string, options: { radius?: number, flat?: boolean, subdivisions?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
  2557. return MeshBuilder.CreateIcoSphere(name, options, scene);
  2558. }
  2559. /**
  2560. * Creates a decal mesh.
  2561. * Please consider using the same method from the MeshBuilder class instead.
  2562. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  2563. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  2564. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  2565. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  2566. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  2567. */
  2568. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh {
  2569. var options = {
  2570. position: position,
  2571. normal: normal,
  2572. size: size,
  2573. angle: angle
  2574. }
  2575. return MeshBuilder.CreateDecal(name, sourceMesh, options);
  2576. }
  2577. // Skeletons
  2578. /**
  2579. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  2580. */
  2581. public setPositionsForCPUSkinning(): Float32Array {
  2582. if (!this._sourcePositions) {
  2583. let source = this.getVerticesData(VertexBuffer.PositionKind);
  2584. if (!source) {
  2585. return this._sourcePositions;
  2586. }
  2587. this._sourcePositions = new Float32Array(<any>source);
  2588. if (!this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
  2589. this.setVerticesData(VertexBuffer.PositionKind, source, true);
  2590. }
  2591. }
  2592. return this._sourcePositions;
  2593. }
  2594. /**
  2595. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  2596. */
  2597. public setNormalsForCPUSkinning(): Float32Array {
  2598. if (!this._sourceNormals) {
  2599. let source = this.getVerticesData(VertexBuffer.NormalKind);
  2600. if (!source) {
  2601. return this._sourceNormals;
  2602. }
  2603. this._sourceNormals = new Float32Array(<any>source);
  2604. if (!this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
  2605. this.setVerticesData(VertexBuffer.NormalKind, source, true);
  2606. }
  2607. }
  2608. return this._sourceNormals;
  2609. }
  2610. /**
  2611. * Updates the vertex buffer by applying transformation from the bones.
  2612. * Returns the Mesh.
  2613. *
  2614. * @param {skeleton} skeleton to apply
  2615. */
  2616. public applySkeleton(skeleton: Skeleton): Mesh {
  2617. if (!this.geometry) {
  2618. return this;
  2619. }
  2620. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  2621. return this;
  2622. }
  2623. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  2624. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  2625. return this;
  2626. }
  2627. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  2628. return this;
  2629. }
  2630. if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  2631. return this;
  2632. }
  2633. if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  2634. return this;
  2635. }
  2636. if (!this._sourcePositions) {
  2637. var submeshes = this.subMeshes.slice();
  2638. this.setPositionsForCPUSkinning();
  2639. this.subMeshes = submeshes;
  2640. }
  2641. if (!this._sourceNormals) {
  2642. this.setNormalsForCPUSkinning();
  2643. }
  2644. // positionsData checks for not being Float32Array will only pass at most once
  2645. var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
  2646. if (!positionsData) {
  2647. return this;
  2648. }
  2649. if (!(positionsData instanceof Float32Array)) {
  2650. positionsData = new Float32Array(positionsData);
  2651. }
  2652. // normalsData checks for not being Float32Array will only pass at most once
  2653. var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
  2654. if (!normalsData) {
  2655. return this;
  2656. }
  2657. if (!(normalsData instanceof Float32Array)) {
  2658. normalsData = new Float32Array(normalsData);
  2659. }
  2660. var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
  2661. var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
  2662. if (!matricesWeightsData || !matricesIndicesData) {
  2663. return this;
  2664. }
  2665. var needExtras = this.numBoneInfluencers > 4;
  2666. var matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
  2667. var matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
  2668. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  2669. return this;
  2670. }
  2671. var skeletonMatrices = skeleton.getTransformMatrices(this);
  2672. var tempVector3 = Vector3.Zero();
  2673. var finalMatrix = new Matrix();
  2674. var tempMatrix = new Matrix();
  2675. var matWeightIdx = 0;
  2676. var inf: number;
  2677. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  2678. var weight: number;
  2679. for (inf = 0; inf < 4; inf++) {
  2680. weight = matricesWeightsData[matWeightIdx + inf];
  2681. if (weight > 0) {
  2682. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  2683. finalMatrix.addToSelf(tempMatrix);
  2684. } else break;
  2685. }
  2686. if (needExtras) {
  2687. for (inf = 0; inf < 4; inf++) {
  2688. weight = matricesWeightsExtraData[matWeightIdx + inf];
  2689. if (weight > 0) {
  2690. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  2691. finalMatrix.addToSelf(tempMatrix);
  2692. } else break;
  2693. }
  2694. }
  2695. Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  2696. tempVector3.toArray(positionsData, index);
  2697. Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  2698. tempVector3.toArray(normalsData, index);
  2699. finalMatrix.reset();
  2700. }
  2701. this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
  2702. this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
  2703. return this;
  2704. }
  2705. // Tools
  2706. /**
  2707. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  2708. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  2709. */
  2710. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  2711. var minVector: Nullable<Vector3> = null;
  2712. var maxVector: Nullable<Vector3> = null;
  2713. meshes.forEach(function (mesh, index, array) {
  2714. let boundingInfo = mesh.getBoundingInfo();
  2715. let boundingBox = boundingInfo.boundingBox;
  2716. if (!minVector || !maxVector) {
  2717. minVector = boundingBox.minimumWorld;
  2718. maxVector = boundingBox.maximumWorld;
  2719. } else {
  2720. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  2721. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  2722. }
  2723. });
  2724. if (!minVector || !maxVector) {
  2725. return {
  2726. min: Vector3.Zero(),
  2727. max: Vector3.Zero()
  2728. }
  2729. }
  2730. return {
  2731. min: minVector,
  2732. max: maxVector
  2733. };
  2734. }
  2735. /**
  2736. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  2737. */
  2738. public static Center(meshesOrMinMaxVector: { min: Vector3; max: Vector3 } | AbstractMesh[]): Vector3 {
  2739. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  2740. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  2741. }
  2742. /**
  2743. * Merge the array of meshes into a single mesh for performance reasons.
  2744. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  2745. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  2746. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  2747. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  2748. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  2749. */
  2750. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh, subdivideWithSubMeshes?: boolean): Nullable<Mesh> {
  2751. var index: number;
  2752. if (!allow32BitsIndices) {
  2753. var totalVertices = 0;
  2754. // Counting vertices
  2755. for (index = 0; index < meshes.length; index++) {
  2756. if (meshes[index]) {
  2757. totalVertices += meshes[index].getTotalVertices();
  2758. if (totalVertices > 65536) {
  2759. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  2760. return null;
  2761. }
  2762. }
  2763. }
  2764. }
  2765. // Merge
  2766. var vertexData: Nullable<VertexData> = null;
  2767. var otherVertexData: VertexData;
  2768. var indiceArray: Array<number> = new Array<number>();
  2769. var source: Nullable<Mesh> = null;
  2770. for (index = 0; index < meshes.length; index++) {
  2771. if (meshes[index]) {
  2772. meshes[index].computeWorldMatrix(true);
  2773. otherVertexData = VertexData.ExtractFromMesh(meshes[index], true);
  2774. otherVertexData.transform(meshes[index].getWorldMatrix());
  2775. if (vertexData) {
  2776. vertexData.merge(otherVertexData);
  2777. } else {
  2778. vertexData = otherVertexData;
  2779. source = meshes[index];
  2780. }
  2781. if (subdivideWithSubMeshes) {
  2782. indiceArray.push(meshes[index].getTotalIndices());
  2783. }
  2784. }
  2785. }
  2786. source = <Mesh>source;
  2787. if (!meshSubclass) {
  2788. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  2789. }
  2790. (<VertexData>vertexData).applyToMesh(meshSubclass);
  2791. // Setting properties
  2792. meshSubclass.material = source.material;
  2793. meshSubclass.checkCollisions = source.checkCollisions;
  2794. // Cleaning
  2795. if (disposeSource) {
  2796. for (index = 0; index < meshes.length; index++) {
  2797. if (meshes[index]) {
  2798. meshes[index].dispose();
  2799. }
  2800. }
  2801. }
  2802. // Subdivide
  2803. if (subdivideWithSubMeshes) {
  2804. //-- Suppresions du submesh global
  2805. meshSubclass.releaseSubMeshes();
  2806. index = 0;
  2807. var offset = 0;
  2808. //-- aplique la subdivision en fonction du tableau d'indices
  2809. while (index < indiceArray.length) {
  2810. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  2811. offset += indiceArray[index];
  2812. index++;
  2813. }
  2814. }
  2815. return meshSubclass;
  2816. }
  2817. }
  2818. }