babylon.mesh.ts 154 KB

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