babylon.mesh.ts 156 KB

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