mesh.ts 168 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936
  1. import { Observer, Observable } from "../Misc/observable";
  2. import { Tools, IAnimatable, AsyncLoop } from "../Misc/tools";
  3. import { DeepCopier } from "../Misc/deepCopier";
  4. import { Tags } from "../Misc/tags";
  5. import { Nullable, FloatArray, IndicesArray } from "../types";
  6. import { Camera } from "../Cameras/camera";
  7. import { Scene } from "../scene";
  8. import { Quaternion, Matrix, Vector3, Vector2, Color3, Color4, Plane, Vector4, Path3D } from "../Maths/math";
  9. import { Engine } from "../Engines/engine";
  10. import { Node } from "../node";
  11. import { VertexBuffer } from "./buffer";
  12. import { VertexData, IGetSetVerticesData } from "./mesh.vertexData";
  13. import { Buffer } from "./buffer";
  14. import { Geometry } from "./geometry";
  15. import { AbstractMesh } from "./abstractMesh";
  16. import { SubMesh } from "./subMesh";
  17. import { BoundingInfo } from "../Culling/boundingInfo";
  18. import { BoundingSphere } from "../Culling/boundingSphere";
  19. import { Effect } from "../Materials/effect";
  20. import { Material } from "../Materials/material";
  21. import { MultiMaterial } from "../Materials/multiMaterial";
  22. import { SceneLoaderFlags } from "../Loading/sceneLoaderFlags";
  23. import { Skeleton } from "../Bones/skeleton";
  24. import { MorphTargetManager } from "../Morph/morphTargetManager";
  25. import { Constants } from "../Engines/constants";
  26. import { SerializationHelper } from "../Misc/decorators";
  27. import { Logger } from "../Misc/logger";
  28. import { _TypeStore } from '../Misc/typeStore';
  29. import { _DevTools } from '../Misc/devTools';
  30. declare type LinesMesh = import("./linesMesh").LinesMesh;
  31. declare type InstancedMesh = import("./instancedMesh").InstancedMesh;
  32. declare type GroundMesh = import("./groundMesh").GroundMesh;
  33. declare type IPhysicsEnabledObject = import("../Physics/physicsImpostor").IPhysicsEnabledObject;
  34. declare type PhysicsImpostor = import("../Physics/physicsImpostor").PhysicsImpostor;
  35. declare var earcut: any;
  36. /**
  37. * Class used to represent a specific level of detail of a mesh
  38. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  39. */
  40. export class MeshLODLevel {
  41. /**
  42. * Creates a new LOD level
  43. * @param distance defines the distance where this level should star being displayed
  44. * @param mesh defines the mesh to use to render this level
  45. */
  46. constructor(
  47. /** Defines the distance where this level should star being displayed */
  48. public distance: number,
  49. /** Defines the mesh to use to render this level */
  50. public mesh: Nullable<Mesh>) {
  51. }
  52. }
  53. /**
  54. * @hidden
  55. **/
  56. export class _CreationDataStorage {
  57. public closePath?: boolean;
  58. public closeArray?: boolean;
  59. public idx: number[];
  60. public dashSize: number;
  61. public gapSize: number;
  62. public path3D: Path3D;
  63. public pathArray: Vector3[][];
  64. public arc: number;
  65. public radius: number;
  66. public cap: number;
  67. public tessellation: number;
  68. }
  69. /**
  70. * @hidden
  71. **/
  72. class _InstanceDataStorage {
  73. public visibleInstances: any = {};
  74. public renderIdForInstances = new Array<number>();
  75. public batchCache = new _InstancesBatch();
  76. public instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  77. public instancesBuffer: Nullable<Buffer>;
  78. public instancesData: Float32Array;
  79. public overridenInstanceCount: number;
  80. }
  81. /**
  82. * @hidden
  83. **/
  84. export class _InstancesBatch {
  85. public mustReturn = false;
  86. public visibleInstances = new Array<Nullable<Array<InstancedMesh>>>();
  87. public renderSelf = new Array<boolean>();
  88. }
  89. /**
  90. * Class used to represent renderable models
  91. */
  92. export class Mesh extends AbstractMesh implements IGetSetVerticesData {
  93. // Consts
  94. /**
  95. * Mesh side orientation : usually the external or front surface
  96. */
  97. public static readonly FRONTSIDE = VertexData.FRONTSIDE;
  98. /**
  99. * Mesh side orientation : usually the internal or back surface
  100. */
  101. public static readonly BACKSIDE = VertexData.BACKSIDE;
  102. /**
  103. * Mesh side orientation : both internal and external or front and back surfaces
  104. */
  105. public static readonly DOUBLESIDE = VertexData.DOUBLESIDE;
  106. /**
  107. * Mesh side orientation : by default, `FRONTSIDE`
  108. */
  109. public static readonly DEFAULTSIDE = VertexData.DEFAULTSIDE;
  110. /**
  111. * Mesh cap setting : no cap
  112. */
  113. public static readonly NO_CAP = 0;
  114. /**
  115. * Mesh cap setting : one cap at the beginning of the mesh
  116. */
  117. public static readonly CAP_START = 1;
  118. /**
  119. * Mesh cap setting : one cap at the end of the mesh
  120. */
  121. public static readonly CAP_END = 2;
  122. /**
  123. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  124. */
  125. public static readonly CAP_ALL = 3;
  126. /**
  127. * Gets the default side orientation.
  128. * @param orientation the orientation to value to attempt to get
  129. * @returns the default orientation
  130. * @hidden
  131. */
  132. public static _GetDefaultSideOrientation(orientation?: number): number {
  133. return orientation || Mesh.FRONTSIDE; // works as Mesh.FRONTSIDE is 0
  134. }
  135. // Events
  136. private _onBeforeRenderObservable: Nullable<Observable<Mesh>>;
  137. private _onBeforeBindObservable: Nullable<Observable<Mesh>>;
  138. private _onAfterRenderObservable: Nullable<Observable<Mesh>>;
  139. private _onBeforeDrawObservable: Nullable<Observable<Mesh>>;
  140. /**
  141. * An event triggered before rendering the mesh
  142. */
  143. public get onBeforeRenderObservable(): Observable<Mesh> {
  144. if (!this._onBeforeRenderObservable) {
  145. this._onBeforeRenderObservable = new Observable<Mesh>();
  146. }
  147. return this._onBeforeRenderObservable;
  148. }
  149. /**
  150. * An event triggered before binding the mesh
  151. */
  152. public get onBeforeBindObservable(): Observable<Mesh> {
  153. if (!this._onBeforeBindObservable) {
  154. this._onBeforeBindObservable = new Observable<Mesh>();
  155. }
  156. return this._onBeforeBindObservable;
  157. }
  158. /**
  159. * An event triggered after rendering the mesh
  160. */
  161. public get onAfterRenderObservable(): Observable<Mesh> {
  162. if (!this._onAfterRenderObservable) {
  163. this._onAfterRenderObservable = new Observable<Mesh>();
  164. }
  165. return this._onAfterRenderObservable;
  166. }
  167. /**
  168. * An event triggered before drawing the mesh
  169. */
  170. public get onBeforeDrawObservable(): Observable<Mesh> {
  171. if (!this._onBeforeDrawObservable) {
  172. this._onBeforeDrawObservable = new Observable<Mesh>();
  173. }
  174. return this._onBeforeDrawObservable;
  175. }
  176. private _onBeforeDrawObserver: Nullable<Observer<Mesh>>;
  177. /**
  178. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  179. */
  180. public set onBeforeDraw(callback: () => void) {
  181. if (this._onBeforeDrawObserver) {
  182. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  183. }
  184. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  185. }
  186. // Members
  187. /**
  188. * Gets the delay loading state of the mesh (when delay loading is turned on)
  189. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  190. */
  191. public delayLoadState = Constants.DELAYLOADSTATE_NONE;
  192. /**
  193. * Gets the list of instances created from this mesh
  194. * it is not supposed to be modified manually.
  195. * Note also that the order of the InstancedMesh wihin the array is not significant and might change.
  196. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  197. */
  198. public instances = new Array<InstancedMesh>();
  199. /**
  200. * Gets the file containing delay loading data for this mesh
  201. */
  202. public delayLoadingFile: string;
  203. /** @hidden */
  204. public _binaryInfo: any;
  205. private _LODLevels = new Array<MeshLODLevel>();
  206. /**
  207. * User defined function used to change how LOD level selection is done
  208. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  209. */
  210. public onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Nullable<Mesh>) => void;
  211. // Morph
  212. private _morphTargetManager: Nullable<MorphTargetManager>;
  213. /**
  214. * Gets or sets the morph target manager
  215. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  216. */
  217. public get morphTargetManager(): Nullable<MorphTargetManager> {
  218. return this._morphTargetManager;
  219. }
  220. public set morphTargetManager(value: Nullable<MorphTargetManager>) {
  221. if (this._morphTargetManager === value) {
  222. return;
  223. }
  224. this._morphTargetManager = value;
  225. this._syncGeometryWithMorphTargetManager();
  226. }
  227. // Private
  228. /** @hidden */
  229. public _creationDataStorage: Nullable<_CreationDataStorage>;
  230. /** @hidden */
  231. public _geometry: Nullable<Geometry>;
  232. /** @hidden */
  233. public _delayInfo: Array<string>;
  234. /** @hidden */
  235. public _delayLoadingFunction: (any: any, mesh: Mesh) => void;
  236. /** @hidden */
  237. public _instanceDataStorage = new _InstanceDataStorage();
  238. private _effectiveMaterial: Material;
  239. /** @hidden */
  240. public _shouldGenerateFlatShading: boolean;
  241. private _preActivateId: number;
  242. // Use by builder only to know what orientation were the mesh build in.
  243. /** @hidden */
  244. public _originalBuilderSideOrientation: number = Mesh.DEFAULTSIDE;
  245. /**
  246. * Use this property to change the original side orientation defined at construction time
  247. */
  248. public overrideMaterialSideOrientation: Nullable<number> = null;
  249. private _areNormalsFrozen: boolean = false; // Will be used by ribbons mainly
  250. private _sourcePositions: Float32Array; // Will be used to save original positions when using software skinning
  251. private _sourceNormals: Float32Array; // Will be used to save original normals when using software skinning
  252. // Will be used to save a source mesh reference, If any
  253. private _source: Nullable<Mesh> = null;
  254. // Will be used to for fast cloned mesh lookup
  255. private meshMap: Nullable<{ [id: string]: Mesh | undefined }>;
  256. /**
  257. * Gets the source mesh (the one used to clone this one from)
  258. */
  259. public get source(): Nullable<Mesh> {
  260. return this._source;
  261. }
  262. /**
  263. * Gets or sets a boolean indicating that this mesh does not use index buffer
  264. */
  265. public get isUnIndexed(): boolean {
  266. return this._unIndexed;
  267. }
  268. public set isUnIndexed(value: boolean) {
  269. if (this._unIndexed !== value) {
  270. this._unIndexed = value;
  271. this._markSubMeshesAsAttributesDirty();
  272. }
  273. }
  274. /**
  275. * @constructor
  276. * @param name The value used by scene.getMeshByName() to do a lookup.
  277. * @param scene The scene to add this mesh to.
  278. * @param parent The parent of this mesh, if it has one
  279. * @param source An optional Mesh from which geometry is shared, cloned.
  280. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  281. * When false, achieved by calling a clone(), also passing False.
  282. * This will make creation of children, recursive.
  283. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  284. */
  285. constructor(name: string, scene: Nullable<Scene> = null, parent: Nullable<Node> = null, source: Nullable<Mesh> = null, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true) {
  286. super(name, scene);
  287. scene = this.getScene();
  288. if (source) {
  289. // Geometry
  290. if (source._geometry) {
  291. source._geometry.applyToMesh(this);
  292. }
  293. // Deep copy
  294. DeepCopier.DeepCopy(source, this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  295. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  296. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw",
  297. "onAfterWorldMatrixUpdateObservable", "onCollideObservable", "onCollisionPositionChangeObservable", "onRebuildObservable",
  298. "onDisposeObservable"
  299. ],
  300. ["_poseMatrix"]);
  301. // Source mesh
  302. this._source = source;
  303. if (scene.useClonedMeshhMap) {
  304. if (!source.meshMap) {
  305. source.meshMap = {};
  306. }
  307. source.meshMap[this.uniqueId] = this;
  308. }
  309. // Construction Params
  310. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  311. this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  312. this._creationDataStorage = source._creationDataStorage;
  313. // Animation ranges
  314. if (this._source._ranges) {
  315. const ranges = this._source._ranges;
  316. for (var name in ranges) {
  317. if (!ranges.hasOwnProperty(name)) {
  318. continue;
  319. }
  320. if (!ranges[name]) {
  321. continue;
  322. }
  323. this.createAnimationRange(name, ranges[name]!.from, ranges[name]!.to);
  324. }
  325. }
  326. // Metadata
  327. if (source.metadata && source.metadata.clone) {
  328. this.metadata = source.metadata.clone();
  329. } else {
  330. this.metadata = source.metadata;
  331. }
  332. // Tags
  333. if (Tags && Tags.HasTags(source)) {
  334. Tags.AddTagsTo(this, Tags.GetTags(source, true));
  335. }
  336. // Parent
  337. this.parent = source.parent;
  338. // Pivot
  339. this.setPivotMatrix(source.getPivotMatrix());
  340. this.id = name + "." + source.id;
  341. // Material
  342. this.material = source.material;
  343. var index: number;
  344. if (!doNotCloneChildren) {
  345. // Children
  346. let directDescendants = source.getDescendants(true);
  347. for (let index = 0; index < directDescendants.length; index++) {
  348. var child = directDescendants[index];
  349. if ((<any>child).clone) {
  350. (<any>child).clone(name + "." + child.name, this);
  351. }
  352. }
  353. }
  354. // Physics clone
  355. var physicsEngine = this.getScene().getPhysicsEngine();
  356. if (clonePhysicsImpostor && physicsEngine) {
  357. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  358. if (impostor) {
  359. this.physicsImpostor = impostor.clone(this);
  360. }
  361. }
  362. // Particles
  363. for (index = 0; index < scene.particleSystems.length; index++) {
  364. var system = scene.particleSystems[index];
  365. if (system.emitter === source) {
  366. system.clone(system.name, this);
  367. }
  368. }
  369. this.refreshBoundingInfo();
  370. this.computeWorldMatrix(true);
  371. }
  372. // Parent
  373. if (parent !== null) {
  374. this.parent = parent;
  375. }
  376. }
  377. // Methods
  378. /**
  379. * Gets the class name
  380. * @returns the string "Mesh".
  381. */
  382. public getClassName(): string {
  383. return "Mesh";
  384. }
  385. /** @hidden */
  386. public readonly _isMesh = true;
  387. /**
  388. * Returns a description of this mesh
  389. * @param fullDetails define if full details about this mesh must be used
  390. * @returns a descriptive string representing this mesh
  391. */
  392. public toString(fullDetails?: boolean): string {
  393. var ret = super.toString(fullDetails);
  394. ret += ", n vertices: " + this.getTotalVertices();
  395. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  396. if (this.animations) {
  397. for (var i = 0; i < this.animations.length; i++) {
  398. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  399. }
  400. }
  401. if (fullDetails) {
  402. if (this._geometry) {
  403. let ib = this.getIndices();
  404. let vb = this.getVerticesData(VertexBuffer.PositionKind);
  405. if (vb && ib) {
  406. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  407. }
  408. } else {
  409. ret += ", flat shading: UNKNOWN";
  410. }
  411. }
  412. return ret;
  413. }
  414. /** @hidden */
  415. public _unBindEffect() {
  416. super._unBindEffect();
  417. for (var instance of this.instances) {
  418. instance._unBindEffect();
  419. }
  420. }
  421. /**
  422. * Gets a boolean indicating if this mesh has LOD
  423. */
  424. public get hasLODLevels(): boolean {
  425. return this._LODLevels.length > 0;
  426. }
  427. /**
  428. * Gets the list of MeshLODLevel associated with the current mesh
  429. * @returns an array of MeshLODLevel
  430. */
  431. public getLODLevels(): MeshLODLevel[] {
  432. return this._LODLevels;
  433. }
  434. private _sortLODLevels(): void {
  435. this._LODLevels.sort((a, b) => {
  436. if (a.distance < b.distance) {
  437. return 1;
  438. }
  439. if (a.distance > b.distance) {
  440. return -1;
  441. }
  442. return 0;
  443. });
  444. }
  445. /**
  446. * Add a mesh as LOD level triggered at the given distance.
  447. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  448. * @param distance The distance from the center of the object to show this level
  449. * @param mesh The mesh to be added as LOD level (can be null)
  450. * @return This mesh (for chaining)
  451. */
  452. public addLODLevel(distance: number, mesh: Nullable<Mesh>): Mesh {
  453. if (mesh && mesh._masterMesh) {
  454. Logger.Warn("You cannot use a mesh as LOD level twice");
  455. return this;
  456. }
  457. var level = new MeshLODLevel(distance, mesh);
  458. this._LODLevels.push(level);
  459. if (mesh) {
  460. mesh._masterMesh = this;
  461. }
  462. this._sortLODLevels();
  463. return this;
  464. }
  465. /**
  466. * Returns the LOD level mesh at the passed distance or null if not found.
  467. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  468. * @param distance The distance from the center of the object to show this level
  469. * @returns a Mesh or `null`
  470. */
  471. public getLODLevelAtDistance(distance: number): Nullable<Mesh> {
  472. for (var index = 0; index < this._LODLevels.length; index++) {
  473. var level = this._LODLevels[index];
  474. if (level.distance === distance) {
  475. return level.mesh;
  476. }
  477. }
  478. return null;
  479. }
  480. /**
  481. * Remove a mesh from the LOD array
  482. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  483. * @param mesh defines the mesh to be removed
  484. * @return This mesh (for chaining)
  485. */
  486. public removeLODLevel(mesh: Mesh): Mesh {
  487. for (var index = 0; index < this._LODLevels.length; index++) {
  488. if (this._LODLevels[index].mesh === mesh) {
  489. this._LODLevels.splice(index, 1);
  490. if (mesh) {
  491. mesh._masterMesh = null;
  492. }
  493. }
  494. }
  495. this._sortLODLevels();
  496. return this;
  497. }
  498. /**
  499. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  500. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  501. * @param camera defines the camera to use to compute distance
  502. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  503. * @return This mesh (for chaining)
  504. */
  505. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): Nullable<AbstractMesh> {
  506. if (!this._LODLevels || this._LODLevels.length === 0) {
  507. return this;
  508. }
  509. let bSphere: BoundingSphere;
  510. if (boundingSphere) {
  511. bSphere = boundingSphere;
  512. } else {
  513. let boundingInfo = this.getBoundingInfo();
  514. bSphere = boundingInfo.boundingSphere;
  515. }
  516. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  517. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  518. if (this.onLODLevelSelection) {
  519. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  520. }
  521. return this;
  522. }
  523. for (var index = 0; index < this._LODLevels.length; index++) {
  524. var level = this._LODLevels[index];
  525. if (level.distance < distanceToCamera) {
  526. if (level.mesh) {
  527. level.mesh._preActivate();
  528. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  529. }
  530. if (this.onLODLevelSelection) {
  531. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  532. }
  533. return level.mesh;
  534. }
  535. }
  536. if (this.onLODLevelSelection) {
  537. this.onLODLevelSelection(distanceToCamera, this, this);
  538. }
  539. return this;
  540. }
  541. /**
  542. * Gets the mesh internal Geometry object
  543. */
  544. public get geometry(): Nullable<Geometry> {
  545. return this._geometry;
  546. }
  547. /**
  548. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  549. * @returns the total number of vertices
  550. */
  551. public getTotalVertices(): number {
  552. if (this._geometry === null || this._geometry === undefined) {
  553. return 0;
  554. }
  555. return this._geometry.getTotalVertices();
  556. }
  557. /**
  558. * Returns the content of an associated vertex buffer
  559. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  560. * - VertexBuffer.PositionKind
  561. * - VertexBuffer.UVKind
  562. * - VertexBuffer.UV2Kind
  563. * - VertexBuffer.UV3Kind
  564. * - VertexBuffer.UV4Kind
  565. * - VertexBuffer.UV5Kind
  566. * - VertexBuffer.UV6Kind
  567. * - VertexBuffer.ColorKind
  568. * - VertexBuffer.MatricesIndicesKind
  569. * - VertexBuffer.MatricesIndicesExtraKind
  570. * - VertexBuffer.MatricesWeightsKind
  571. * - VertexBuffer.MatricesWeightsExtraKind
  572. * @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
  573. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  574. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  575. */
  576. public getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable<FloatArray> {
  577. if (!this._geometry) {
  578. return null;
  579. }
  580. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  581. }
  582. /**
  583. * Returns the mesh VertexBuffer object from the requested `kind`
  584. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  585. * - VertexBuffer.PositionKind
  586. * - VertexBuffer.UVKind
  587. * - VertexBuffer.UV2Kind
  588. * - VertexBuffer.UV3Kind
  589. * - VertexBuffer.UV4Kind
  590. * - VertexBuffer.UV5Kind
  591. * - VertexBuffer.UV6Kind
  592. * - VertexBuffer.ColorKind
  593. * - VertexBuffer.MatricesIndicesKind
  594. * - VertexBuffer.MatricesIndicesExtraKind
  595. * - VertexBuffer.MatricesWeightsKind
  596. * - VertexBuffer.MatricesWeightsExtraKind
  597. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  598. */
  599. public getVertexBuffer(kind: string): Nullable<VertexBuffer> {
  600. if (!this._geometry) {
  601. return null;
  602. }
  603. return this._geometry.getVertexBuffer(kind);
  604. }
  605. /**
  606. * Tests if a specific vertex buffer is associated with this mesh
  607. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  608. * - VertexBuffer.PositionKind
  609. * - VertexBuffer.UVKind
  610. * - VertexBuffer.UV2Kind
  611. * - VertexBuffer.UV3Kind
  612. * - VertexBuffer.UV4Kind
  613. * - VertexBuffer.UV5Kind
  614. * - VertexBuffer.UV6Kind
  615. * - VertexBuffer.ColorKind
  616. * - VertexBuffer.MatricesIndicesKind
  617. * - VertexBuffer.MatricesIndicesExtraKind
  618. * - VertexBuffer.MatricesWeightsKind
  619. * - VertexBuffer.MatricesWeightsExtraKind
  620. * @returns a boolean
  621. */
  622. public isVerticesDataPresent(kind: string): boolean {
  623. if (!this._geometry) {
  624. if (this._delayInfo) {
  625. return this._delayInfo.indexOf(kind) !== -1;
  626. }
  627. return false;
  628. }
  629. return this._geometry.isVerticesDataPresent(kind);
  630. }
  631. /**
  632. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  633. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  634. * - VertexBuffer.PositionKind
  635. * - VertexBuffer.UVKind
  636. * - VertexBuffer.UV2Kind
  637. * - VertexBuffer.UV3Kind
  638. * - VertexBuffer.UV4Kind
  639. * - VertexBuffer.UV5Kind
  640. * - VertexBuffer.UV6Kind
  641. * - VertexBuffer.ColorKind
  642. * - VertexBuffer.MatricesIndicesKind
  643. * - VertexBuffer.MatricesIndicesExtraKind
  644. * - VertexBuffer.MatricesWeightsKind
  645. * - VertexBuffer.MatricesWeightsExtraKind
  646. * @returns a boolean
  647. */
  648. public isVertexBufferUpdatable(kind: string): boolean {
  649. if (!this._geometry) {
  650. if (this._delayInfo) {
  651. return this._delayInfo.indexOf(kind) !== -1;
  652. }
  653. return false;
  654. }
  655. return this._geometry.isVertexBufferUpdatable(kind);
  656. }
  657. /**
  658. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  659. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  660. * - VertexBuffer.PositionKind
  661. * - VertexBuffer.UVKind
  662. * - VertexBuffer.UV2Kind
  663. * - VertexBuffer.UV3Kind
  664. * - VertexBuffer.UV4Kind
  665. * - VertexBuffer.UV5Kind
  666. * - VertexBuffer.UV6Kind
  667. * - VertexBuffer.ColorKind
  668. * - VertexBuffer.MatricesIndicesKind
  669. * - VertexBuffer.MatricesIndicesExtraKind
  670. * - VertexBuffer.MatricesWeightsKind
  671. * - VertexBuffer.MatricesWeightsExtraKind
  672. * @returns an array of strings
  673. */
  674. public getVerticesDataKinds(): string[] {
  675. if (!this._geometry) {
  676. var result = new Array<string>();
  677. if (this._delayInfo) {
  678. this._delayInfo.forEach(function(kind) {
  679. result.push(kind);
  680. });
  681. }
  682. return result;
  683. }
  684. return this._geometry.getVerticesDataKinds();
  685. }
  686. /**
  687. * Returns a positive integer : the total number of indices in this mesh geometry.
  688. * @returns the numner of indices or zero if the mesh has no geometry.
  689. */
  690. public getTotalIndices(): number {
  691. if (!this._geometry) {
  692. return 0;
  693. }
  694. return this._geometry.getTotalIndices();
  695. }
  696. /**
  697. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  698. * @param copyWhenShared If 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.
  699. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  700. * @returns the indices array or an empty array if the mesh has no geometry
  701. */
  702. public getIndices(copyWhenShared?: boolean, forceCopy?: boolean): Nullable<IndicesArray> {
  703. if (!this._geometry) {
  704. return [];
  705. }
  706. return this._geometry.getIndices(copyWhenShared, forceCopy);
  707. }
  708. public get isBlocked(): boolean {
  709. return this._masterMesh !== null && this._masterMesh !== undefined;
  710. }
  711. /**
  712. * Determine if the current mesh is ready to be rendered
  713. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  714. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  715. * @returns true if all associated assets are ready (material, textures, shaders)
  716. */
  717. public isReady(completeCheck = false, forceInstanceSupport = false): boolean {
  718. if (this.delayLoadState === Constants.DELAYLOADSTATE_LOADING) {
  719. return false;
  720. }
  721. if (!super.isReady(completeCheck)) {
  722. return false;
  723. }
  724. if (!this.subMeshes || this.subMeshes.length === 0) {
  725. return true;
  726. }
  727. if (!completeCheck) {
  728. return true;
  729. }
  730. let engine = this.getEngine();
  731. let scene = this.getScene();
  732. let hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  733. this.computeWorldMatrix();
  734. let mat = this.material || scene.defaultMaterial;
  735. if (mat) {
  736. if (mat._storeEffectOnSubMeshes) {
  737. for (var subMesh of this.subMeshes) {
  738. let effectiveMaterial = subMesh.getMaterial();
  739. if (effectiveMaterial) {
  740. if (effectiveMaterial._storeEffectOnSubMeshes) {
  741. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  742. return false;
  743. }
  744. }
  745. else {
  746. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  747. return false;
  748. }
  749. }
  750. }
  751. }
  752. } else {
  753. if (!mat.isReady(this, hardwareInstancedRendering)) {
  754. return false;
  755. }
  756. }
  757. }
  758. // Shadows
  759. for (var light of this._lightSources) {
  760. let generator = light.getShadowGenerator();
  761. if (generator) {
  762. for (var subMesh of this.subMeshes) {
  763. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  764. return false;
  765. }
  766. }
  767. }
  768. }
  769. // LOD
  770. for (var lod of this._LODLevels) {
  771. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  772. return false;
  773. }
  774. }
  775. return true;
  776. }
  777. /**
  778. * Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
  779. */
  780. public get areNormalsFrozen(): boolean {
  781. return this._areNormalsFrozen;
  782. }
  783. /**
  784. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
  785. * @returns the current mesh
  786. */
  787. public freezeNormals(): Mesh {
  788. this._areNormalsFrozen = true;
  789. return this;
  790. }
  791. /**
  792. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
  793. * @returns the current mesh
  794. */
  795. public unfreezeNormals(): Mesh {
  796. this._areNormalsFrozen = false;
  797. return this;
  798. }
  799. /**
  800. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  801. */
  802. public set overridenInstanceCount(count: number) {
  803. this._instanceDataStorage.overridenInstanceCount = count;
  804. }
  805. // Methods
  806. /** @hidden */
  807. public _preActivate(): Mesh {
  808. var sceneRenderId = this.getScene().getRenderId();
  809. if (this._preActivateId === sceneRenderId) {
  810. return this;
  811. }
  812. this._preActivateId = sceneRenderId;
  813. this._instanceDataStorage.visibleInstances = null;
  814. return this;
  815. }
  816. /** @hidden */
  817. public _preActivateForIntermediateRendering(renderId: number): Mesh {
  818. if (this._instanceDataStorage.visibleInstances) {
  819. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  820. }
  821. return this;
  822. }
  823. /** @hidden */
  824. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number): Mesh {
  825. if (!this._instanceDataStorage.visibleInstances) {
  826. this._instanceDataStorage.visibleInstances = {
  827. defaultRenderId: renderId,
  828. selfDefaultRenderId: this._renderId
  829. };
  830. }
  831. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  832. this._instanceDataStorage.visibleInstances[renderId] = new Array<InstancedMesh>();
  833. }
  834. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  835. return this;
  836. }
  837. /**
  838. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  839. * This means the mesh underlying bounding box and sphere are recomputed.
  840. * @param applySkeleton defines whether to apply the skeleton before computing the bounding info
  841. * @returns the current mesh
  842. */
  843. public refreshBoundingInfo(applySkeleton: boolean = false): Mesh {
  844. if (this._boundingInfo && this._boundingInfo.isLocked) {
  845. return this;
  846. }
  847. const bias = this.geometry ? this.geometry.boundingBias : null;
  848. this._refreshBoundingInfo(this._getPositionData(applySkeleton), bias);
  849. return this;
  850. }
  851. /** @hidden */
  852. public _createGlobalSubMesh(force: boolean): Nullable<SubMesh> {
  853. var totalVertices = this.getTotalVertices();
  854. if (!totalVertices || !this.getIndices()) {
  855. return null;
  856. }
  857. // Check if we need to recreate the submeshes
  858. if (this.subMeshes && this.subMeshes.length > 0) {
  859. let ib = this.getIndices();
  860. if (!ib) {
  861. return null;
  862. }
  863. var totalIndices = ib.length;
  864. let needToRecreate = false;
  865. if (force) {
  866. needToRecreate = true;
  867. } else {
  868. for (var submesh of this.subMeshes) {
  869. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  870. needToRecreate = true;
  871. break;
  872. }
  873. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  874. needToRecreate = true;
  875. break;
  876. }
  877. }
  878. }
  879. if (!needToRecreate) {
  880. return this.subMeshes[0];
  881. }
  882. }
  883. this.releaseSubMeshes();
  884. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  885. }
  886. /**
  887. * This function will subdivide the mesh into multiple submeshes
  888. * @param count defines the expected number of submeshes
  889. */
  890. public subdivide(count: number): void {
  891. if (count < 1) {
  892. return;
  893. }
  894. var totalIndices = this.getTotalIndices();
  895. var subdivisionSize = (totalIndices / count) | 0;
  896. var offset = 0;
  897. // Ensure that subdivisionSize is a multiple of 3
  898. while (subdivisionSize % 3 !== 0) {
  899. subdivisionSize++;
  900. }
  901. this.releaseSubMeshes();
  902. for (var index = 0; index < count; index++) {
  903. if (offset >= totalIndices) {
  904. break;
  905. }
  906. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  907. offset += subdivisionSize;
  908. }
  909. this.synchronizeInstances();
  910. }
  911. /**
  912. * Copy a FloatArray into a specific associated vertex buffer
  913. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  914. * - VertexBuffer.PositionKind
  915. * - VertexBuffer.UVKind
  916. * - VertexBuffer.UV2Kind
  917. * - VertexBuffer.UV3Kind
  918. * - VertexBuffer.UV4Kind
  919. * - VertexBuffer.UV5Kind
  920. * - VertexBuffer.UV6Kind
  921. * - VertexBuffer.ColorKind
  922. * - VertexBuffer.MatricesIndicesKind
  923. * - VertexBuffer.MatricesIndicesExtraKind
  924. * - VertexBuffer.MatricesWeightsKind
  925. * - VertexBuffer.MatricesWeightsExtraKind
  926. * @param data defines the data source
  927. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  928. * @param stride defines the data stride size (can be null)
  929. * @returns the current mesh
  930. */
  931. public setVerticesData(kind: string, data: FloatArray, updatable: boolean = false, stride?: number): Mesh {
  932. if (!this._geometry) {
  933. var vertexData = new VertexData();
  934. vertexData.set(data, kind);
  935. var scene = this.getScene();
  936. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  937. }
  938. else {
  939. this._geometry.setVerticesData(kind, data, updatable, stride);
  940. }
  941. return this;
  942. }
  943. /**
  944. * Flags an associated vertex buffer as updatable
  945. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  946. * - VertexBuffer.PositionKind
  947. * - VertexBuffer.UVKind
  948. * - VertexBuffer.UV2Kind
  949. * - VertexBuffer.UV3Kind
  950. * - VertexBuffer.UV4Kind
  951. * - VertexBuffer.UV5Kind
  952. * - VertexBuffer.UV6Kind
  953. * - VertexBuffer.ColorKind
  954. * - VertexBuffer.MatricesIndicesKind
  955. * - VertexBuffer.MatricesIndicesExtraKind
  956. * - VertexBuffer.MatricesWeightsKind
  957. * - VertexBuffer.MatricesWeightsExtraKind
  958. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  959. */
  960. public markVerticesDataAsUpdatable(kind: string, updatable = true) {
  961. let vb = this.getVertexBuffer(kind);
  962. if (!vb || vb.isUpdatable() === updatable) {
  963. return;
  964. }
  965. this.setVerticesData(kind, (<FloatArray>this.getVerticesData(kind)), updatable);
  966. }
  967. /**
  968. * Sets the mesh global Vertex Buffer
  969. * @param buffer defines the buffer to use
  970. * @returns the current mesh
  971. */
  972. public setVerticesBuffer(buffer: VertexBuffer): Mesh {
  973. if (!this._geometry) {
  974. this._geometry = Geometry.CreateGeometryForMesh(this);
  975. }
  976. this._geometry.setVerticesBuffer(buffer);
  977. return this;
  978. }
  979. /**
  980. * Update a specific associated vertex buffer
  981. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  982. * - VertexBuffer.PositionKind
  983. * - VertexBuffer.UVKind
  984. * - VertexBuffer.UV2Kind
  985. * - VertexBuffer.UV3Kind
  986. * - VertexBuffer.UV4Kind
  987. * - VertexBuffer.UV5Kind
  988. * - VertexBuffer.UV6Kind
  989. * - VertexBuffer.ColorKind
  990. * - VertexBuffer.MatricesIndicesKind
  991. * - VertexBuffer.MatricesIndicesExtraKind
  992. * - VertexBuffer.MatricesWeightsKind
  993. * - VertexBuffer.MatricesWeightsExtraKind
  994. * @param data defines the data source
  995. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  996. * @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
  997. * @returns the current mesh
  998. */
  999. public updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh {
  1000. if (!this._geometry) {
  1001. return this;
  1002. }
  1003. if (!makeItUnique) {
  1004. this._geometry.updateVerticesData(kind, data, updateExtends);
  1005. }
  1006. else {
  1007. this.makeGeometryUnique();
  1008. this.updateVerticesData(kind, data, updateExtends, false);
  1009. }
  1010. return this;
  1011. }
  1012. /**
  1013. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  1014. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  1015. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  1016. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  1017. * @returns the current mesh
  1018. */
  1019. public updateMeshPositions(positionFunction: (data: FloatArray) => void, computeNormals: boolean = true): Mesh {
  1020. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1021. if (!positions) {
  1022. return this;
  1023. }
  1024. positionFunction(positions);
  1025. this.updateVerticesData(VertexBuffer.PositionKind, positions, false, false);
  1026. if (computeNormals) {
  1027. var indices = this.getIndices();
  1028. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1029. if (!normals) {
  1030. return this;
  1031. }
  1032. VertexData.ComputeNormals(positions, indices, normals);
  1033. this.updateVerticesData(VertexBuffer.NormalKind, normals, false, false);
  1034. }
  1035. return this;
  1036. }
  1037. /**
  1038. * Creates a un-shared specific occurence of the geometry for the mesh.
  1039. * @returns the current mesh
  1040. */
  1041. public makeGeometryUnique(): Mesh {
  1042. if (!this._geometry) {
  1043. return this;
  1044. }
  1045. var oldGeometry = this._geometry;
  1046. var geometry = this._geometry.copy(Geometry.RandomId());
  1047. oldGeometry.releaseForMesh(this, true);
  1048. geometry.applyToMesh(this);
  1049. return this;
  1050. }
  1051. /**
  1052. * Set the index buffer of this mesh
  1053. * @param indices defines the source data
  1054. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  1055. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  1056. * @returns the current mesh
  1057. */
  1058. public setIndices(indices: IndicesArray, totalVertices: Nullable<number> = null, updatable: boolean = false): Mesh {
  1059. if (!this._geometry) {
  1060. var vertexData = new VertexData();
  1061. vertexData.indices = indices;
  1062. var scene = this.getScene();
  1063. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  1064. }
  1065. else {
  1066. this._geometry.setIndices(indices, totalVertices, updatable);
  1067. }
  1068. return this;
  1069. }
  1070. /**
  1071. * Update the current index buffer
  1072. * @param indices defines the source data
  1073. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  1074. * @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)
  1075. * @returns the current mesh
  1076. */
  1077. public updateIndices(indices: IndicesArray, offset?: number, gpuMemoryOnly = false): Mesh {
  1078. if (!this._geometry) {
  1079. return this;
  1080. }
  1081. this._geometry.updateIndices(indices, offset, gpuMemoryOnly);
  1082. return this;
  1083. }
  1084. /**
  1085. * Invert the geometry to move from a right handed system to a left handed one.
  1086. * @returns the current mesh
  1087. */
  1088. public toLeftHanded(): Mesh {
  1089. if (!this._geometry) {
  1090. return this;
  1091. }
  1092. this._geometry.toLeftHanded();
  1093. return this;
  1094. }
  1095. /** @hidden */
  1096. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): Mesh {
  1097. if (!this._geometry) {
  1098. return this;
  1099. }
  1100. var engine = this.getScene().getEngine();
  1101. // Wireframe
  1102. var indexToBind;
  1103. if (this._unIndexed) {
  1104. indexToBind = null;
  1105. } else {
  1106. switch (fillMode) {
  1107. case Material.PointFillMode:
  1108. indexToBind = null;
  1109. break;
  1110. case Material.WireFrameFillMode:
  1111. indexToBind = subMesh._getLinesIndexBuffer(<IndicesArray>this.getIndices(), engine);
  1112. break;
  1113. default:
  1114. case Material.TriangleFillMode:
  1115. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  1116. break;
  1117. }
  1118. }
  1119. // VBOs
  1120. this._geometry._bind(effect, indexToBind);
  1121. return this;
  1122. }
  1123. /** @hidden */
  1124. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): Mesh {
  1125. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  1126. return this;
  1127. }
  1128. if (this._onBeforeDrawObservable) {
  1129. this._onBeforeDrawObservable.notifyObservers(this);
  1130. }
  1131. let scene = this.getScene();
  1132. let engine = scene.getEngine();
  1133. if (this._unIndexed || fillMode == Material.PointFillMode) {
  1134. // or triangles as points
  1135. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  1136. } else if (fillMode == Material.WireFrameFillMode) {
  1137. // Triangles as wireframe
  1138. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  1139. } else {
  1140. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  1141. }
  1142. return this;
  1143. }
  1144. /**
  1145. * Registers for this mesh a javascript function called just before the rendering process
  1146. * @param func defines the function to call before rendering this mesh
  1147. * @returns the current mesh
  1148. */
  1149. public registerBeforeRender(func: (mesh: AbstractMesh) => void): Mesh {
  1150. this.onBeforeRenderObservable.add(func);
  1151. return this;
  1152. }
  1153. /**
  1154. * Disposes a previously registered javascript function called before the rendering
  1155. * @param func defines the function to remove
  1156. * @returns the current mesh
  1157. */
  1158. public unregisterBeforeRender(func: (mesh: AbstractMesh) => void): Mesh {
  1159. this.onBeforeRenderObservable.removeCallback(func);
  1160. return this;
  1161. }
  1162. /**
  1163. * Registers for this mesh a javascript function called just after the rendering is complete
  1164. * @param func defines the function to call after rendering this mesh
  1165. * @returns the current mesh
  1166. */
  1167. public registerAfterRender(func: (mesh: AbstractMesh) => void): Mesh {
  1168. this.onAfterRenderObservable.add(func);
  1169. return this;
  1170. }
  1171. /**
  1172. * Disposes a previously registered javascript function called after the rendering.
  1173. * @param func defines the function to remove
  1174. * @returns the current mesh
  1175. */
  1176. public unregisterAfterRender(func: (mesh: AbstractMesh) => void): Mesh {
  1177. this.onAfterRenderObservable.removeCallback(func);
  1178. return this;
  1179. }
  1180. /** @hidden */
  1181. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  1182. var scene = this.getScene();
  1183. let batchCache = this._instanceDataStorage.batchCache;
  1184. batchCache.mustReturn = false;
  1185. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  1186. batchCache.visibleInstances[subMeshId] = null;
  1187. if (this._instanceDataStorage.visibleInstances) {
  1188. let visibleInstances = this._instanceDataStorage.visibleInstances;
  1189. var currentRenderId = scene.getRenderId();
  1190. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  1191. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  1192. var selfRenderId = this._renderId;
  1193. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  1194. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  1195. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  1196. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  1197. }
  1198. let visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  1199. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  1200. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  1201. batchCache.mustReturn = true;
  1202. return batchCache;
  1203. }
  1204. if (currentRenderId !== selfRenderId) {
  1205. batchCache.renderSelf[subMeshId] = false;
  1206. }
  1207. }
  1208. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  1209. }
  1210. return batchCache;
  1211. }
  1212. /** @hidden */
  1213. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): Mesh {
  1214. var visibleInstances = batch.visibleInstances[subMesh._id];
  1215. if (!visibleInstances) {
  1216. return this;
  1217. }
  1218. var matricesCount = visibleInstances.length + 1;
  1219. var bufferSize = matricesCount * 16 * 4;
  1220. let instanceStorage = this._instanceDataStorage;
  1221. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  1222. var instancesBuffer = instanceStorage.instancesBuffer;
  1223. while (instanceStorage.instancesBufferSize < bufferSize) {
  1224. instanceStorage.instancesBufferSize *= 2;
  1225. }
  1226. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  1227. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  1228. }
  1229. var offset = 0;
  1230. var instancesCount = 0;
  1231. var world = this._effectiveMesh.getWorldMatrix();
  1232. if (batch.renderSelf[subMesh._id]) {
  1233. world.copyToArray(instanceStorage.instancesData, offset);
  1234. offset += 16;
  1235. instancesCount++;
  1236. }
  1237. if (visibleInstances) {
  1238. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  1239. var instance = visibleInstances[instanceIndex];
  1240. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  1241. offset += 16;
  1242. instancesCount++;
  1243. }
  1244. }
  1245. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  1246. if (instancesBuffer) {
  1247. instancesBuffer.dispose();
  1248. }
  1249. instancesBuffer = new Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  1250. instanceStorage.instancesBuffer = instancesBuffer;
  1251. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  1252. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  1253. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  1254. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  1255. } else {
  1256. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  1257. }
  1258. this._bind(subMesh, effect, fillMode);
  1259. this._draw(subMesh, fillMode, instancesCount);
  1260. engine.unbindInstanceAttributes();
  1261. return this;
  1262. }
  1263. /** @hidden */
  1264. public _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean,
  1265. onBeforeDraw: (isInstance: boolean, world: Matrix, effectiveMaterial?: Material) => void, effectiveMaterial?: Material): Mesh {
  1266. var scene = this.getScene();
  1267. var engine = scene.getEngine();
  1268. if (hardwareInstancedRendering) {
  1269. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  1270. } else {
  1271. if (batch.renderSelf[subMesh._id]) {
  1272. // Draw
  1273. if (onBeforeDraw) {
  1274. onBeforeDraw(false, this._effectiveMesh.getWorldMatrix(), effectiveMaterial);
  1275. }
  1276. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  1277. }
  1278. let visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  1279. if (visibleInstancesForSubMesh) {
  1280. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  1281. var instance = visibleInstancesForSubMesh[instanceIndex];
  1282. // World
  1283. var world = instance.getWorldMatrix();
  1284. if (onBeforeDraw) {
  1285. onBeforeDraw(true, world, effectiveMaterial);
  1286. }
  1287. // Draw
  1288. this._draw(subMesh, fillMode);
  1289. }
  1290. }
  1291. }
  1292. return this;
  1293. }
  1294. /**
  1295. * Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
  1296. * @param subMesh defines the subMesh to render
  1297. * @param enableAlphaMode defines if alpha mode can be changed
  1298. * @returns the current mesh
  1299. */
  1300. public render(subMesh: SubMesh, enableAlphaMode: boolean): Mesh {
  1301. if (this._checkOcclusionQuery()) {
  1302. return this;
  1303. }
  1304. var scene = this.getScene();
  1305. // Managing instances
  1306. var batch = this._getInstancesRenderList(subMesh._id);
  1307. if (batch.mustReturn) {
  1308. return this;
  1309. }
  1310. // Checking geometry state
  1311. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  1312. return this;
  1313. }
  1314. if (this._onBeforeRenderObservable) {
  1315. this._onBeforeRenderObservable.notifyObservers(this);
  1316. }
  1317. var engine = scene.getEngine();
  1318. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  1319. // Material
  1320. let material = subMesh.getMaterial();
  1321. if (!material) {
  1322. return this;
  1323. }
  1324. this._effectiveMaterial = material;
  1325. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  1326. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  1327. return this;
  1328. }
  1329. } else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  1330. return this;
  1331. }
  1332. // Alpha mode
  1333. if (enableAlphaMode) {
  1334. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  1335. }
  1336. for (let step of scene._beforeRenderingMeshStage) {
  1337. step.action(this, subMesh, batch);
  1338. }
  1339. var effect: Nullable<Effect>;
  1340. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  1341. effect = subMesh.effect;
  1342. } else {
  1343. effect = this._effectiveMaterial.getEffect();
  1344. }
  1345. if (!effect) {
  1346. return this;
  1347. }
  1348. const effectiveMesh = this._effectiveMesh;
  1349. var sideOrientation = this.overrideMaterialSideOrientation;
  1350. if (sideOrientation == null) {
  1351. sideOrientation = this._effectiveMaterial.sideOrientation;
  1352. if (effectiveMesh._getWorldMatrixDeterminant() < 0) {
  1353. sideOrientation = (sideOrientation === Material.ClockWiseSideOrientation ? Material.CounterClockWiseSideOrientation : Material.ClockWiseSideOrientation);
  1354. }
  1355. }
  1356. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  1357. if (this._effectiveMaterial.forceDepthWrite) {
  1358. engine.setDepthWrite(true);
  1359. }
  1360. // Bind
  1361. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  1362. if (this._onBeforeBindObservable) {
  1363. this._onBeforeBindObservable.notifyObservers(this);
  1364. }
  1365. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  1366. this._bind(subMesh, effect, fillMode);
  1367. }
  1368. var world = effectiveMesh.getWorldMatrix();
  1369. if (this._effectiveMaterial._storeEffectOnSubMeshes) {
  1370. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  1371. } else {
  1372. this._effectiveMaterial.bind(world, this);
  1373. }
  1374. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  1375. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  1376. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  1377. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  1378. }
  1379. // Draw
  1380. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  1381. // Unbind
  1382. this._effectiveMaterial.unbind();
  1383. for (let step of scene._afterRenderingMeshStage) {
  1384. step.action(this, subMesh, batch);
  1385. }
  1386. if (this._onAfterRenderObservable) {
  1387. this._onAfterRenderObservable.notifyObservers(this);
  1388. }
  1389. return this;
  1390. }
  1391. private _onBeforeDraw(isInstance: boolean, world: Matrix, effectiveMaterial?: Material): void {
  1392. if (isInstance && effectiveMaterial) {
  1393. effectiveMaterial.bindOnlyWorldMatrix(world);
  1394. }
  1395. }
  1396. /**
  1397. * Renormalize the mesh and patch it up if there are no weights
  1398. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  1399. * However in the case of zero weights then we set just a single influence to 1.
  1400. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  1401. */
  1402. public cleanMatrixWeights(): void {
  1403. if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  1404. if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsExtraKind)) {
  1405. this.normalizeSkinWeightsAndExtra();
  1406. }
  1407. else {
  1408. this.normalizeSkinFourWeights();
  1409. }
  1410. }
  1411. }
  1412. // faster 4 weight version.
  1413. private normalizeSkinFourWeights(): void {
  1414. let matricesWeights = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsKind));
  1415. let numWeights = matricesWeights.length;
  1416. for (var a = 0; a < numWeights; a += 4) {
  1417. // accumulate weights
  1418. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  1419. // check for invalid weight and just set it to 1.
  1420. if (t === 0) { matricesWeights[a] = 1; }
  1421. else {
  1422. // renormalize so everything adds to 1 use reciprical
  1423. let recip = 1 / t;
  1424. matricesWeights[a] *= recip;
  1425. matricesWeights[a + 1] *= recip;
  1426. matricesWeights[a + 2] *= recip;
  1427. matricesWeights[a + 3] *= recip;
  1428. }
  1429. }
  1430. this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights);
  1431. }
  1432. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  1433. private normalizeSkinWeightsAndExtra(): void {
  1434. let matricesWeightsExtra = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind));
  1435. let matricesWeights = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsKind));
  1436. let numWeights = matricesWeights.length;
  1437. for (var a = 0; a < numWeights; a += 4) {
  1438. // accumulate weights
  1439. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  1440. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  1441. // check for invalid weight and just set it to 1.
  1442. if (t === 0) { matricesWeights[a] = 1; }
  1443. else {
  1444. // renormalize so everything adds to 1 use reciprical
  1445. let recip = 1 / t;
  1446. matricesWeights[a] *= recip;
  1447. matricesWeights[a + 1] *= recip;
  1448. matricesWeights[a + 2] *= recip;
  1449. matricesWeights[a + 3] *= recip;
  1450. // same goes for extras
  1451. matricesWeightsExtra[a] *= recip;
  1452. matricesWeightsExtra[a + 1] *= recip;
  1453. matricesWeightsExtra[a + 2] *= recip;
  1454. matricesWeightsExtra[a + 3] *= recip;
  1455. }
  1456. }
  1457. this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeights);
  1458. this.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  1459. }
  1460. /**
  1461. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  1462. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  1463. * the user know there was an issue with importing the mesh
  1464. * @returns a validation object with skinned, valid and report string
  1465. */
  1466. public validateSkinning(): { skinned: boolean, valid: boolean, report: string } {
  1467. let matricesWeightsExtra = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind));
  1468. let matricesWeights = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesWeightsKind));
  1469. if (matricesWeights === null || this.skeleton == null) {
  1470. return { skinned: false, valid: true, report: "not skinned" };
  1471. }
  1472. let numWeights = matricesWeights.length;
  1473. let numberNotSorted: number = 0;
  1474. let missingWeights: number = 0;
  1475. let maxUsedWeights: number = 0;
  1476. let numberNotNormalized: number = 0;
  1477. let numInfluences: number = matricesWeightsExtra === null ? 4 : 8;
  1478. var usedWeightCounts = new Array<number>();
  1479. for (var a = 0; a <= numInfluences; a++) {
  1480. usedWeightCounts[a] = 0;
  1481. }
  1482. const toleranceEpsilon: number = 0.001;
  1483. for (var a = 0; a < numWeights; a += 4) {
  1484. let lastWeight: number = matricesWeights[a];
  1485. var t = lastWeight;
  1486. let usedWeights: number = t === 0 ? 0 : 1;
  1487. for (var b = 1; b < numInfluences; b++) {
  1488. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  1489. if (d > lastWeight) { numberNotSorted++; }
  1490. if (d !== 0) { usedWeights++; }
  1491. t += d;
  1492. lastWeight = d;
  1493. }
  1494. // count the buffer weights usage
  1495. usedWeightCounts[usedWeights]++;
  1496. // max influences
  1497. if (usedWeights > maxUsedWeights) { maxUsedWeights = usedWeights; }
  1498. // check for invalid weight and just set it to 1.
  1499. if (t === 0) {
  1500. missingWeights++;
  1501. }
  1502. else {
  1503. // renormalize so everything adds to 1 use reciprical
  1504. let recip = 1 / t;
  1505. let tolerance = 0;
  1506. for (b = 0; b < numInfluences; b++) {
  1507. if (b < 4) {
  1508. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  1509. }
  1510. else {
  1511. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  1512. }
  1513. }
  1514. // arbitary epsilon value for dicdating not normalized
  1515. if (tolerance > toleranceEpsilon) { numberNotNormalized++; }
  1516. }
  1517. }
  1518. // validate bone indices are in range of the skeleton
  1519. let numBones: number = this.skeleton.bones.length;
  1520. let matricesIndices = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesIndicesKind));
  1521. let matricesIndicesExtra = (<FloatArray>this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind));
  1522. let numBadBoneIndices: number = 0;
  1523. for (var a = 0; a < numWeights; a++) {
  1524. for (var b = 0; b < numInfluences; b++) {
  1525. let index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  1526. if (index >= numBones || index < 0) { numBadBoneIndices++; }
  1527. }
  1528. }
  1529. // log mesh stats
  1530. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  1531. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  1532. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  1533. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  1534. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  1535. }
  1536. /** @hidden */
  1537. public _checkDelayState(): Mesh {
  1538. var scene = this.getScene();
  1539. if (this._geometry) {
  1540. this._geometry.load(scene);
  1541. }
  1542. else if (this.delayLoadState === Constants.DELAYLOADSTATE_NOTLOADED) {
  1543. this.delayLoadState = Constants.DELAYLOADSTATE_LOADING;
  1544. this._queueLoad(scene);
  1545. }
  1546. return this;
  1547. }
  1548. private _queueLoad(scene: Scene): Mesh {
  1549. scene._addPendingData(this);
  1550. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  1551. Tools.LoadFile(this.delayLoadingFile, (data) => {
  1552. if (data instanceof ArrayBuffer) {
  1553. this._delayLoadingFunction(data, this);
  1554. }
  1555. else {
  1556. this._delayLoadingFunction(JSON.parse(data), this);
  1557. }
  1558. this.instances.forEach((instance) => {
  1559. instance._syncSubMeshes();
  1560. });
  1561. this.delayLoadState = Constants.DELAYLOADSTATE_LOADED;
  1562. scene._removePendingData(this);
  1563. }, () => { }, scene.offlineProvider, getBinaryData);
  1564. return this;
  1565. }
  1566. /**
  1567. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  1568. * A mesh is in the frustum if its bounding box intersects the frustum
  1569. * @param frustumPlanes defines the frustum to test
  1570. * @returns true if the mesh is in the frustum planes
  1571. */
  1572. public isInFrustum(frustumPlanes: Plane[]): boolean {
  1573. if (this.delayLoadState === Constants.DELAYLOADSTATE_LOADING) {
  1574. return false;
  1575. }
  1576. if (!super.isInFrustum(frustumPlanes)) {
  1577. return false;
  1578. }
  1579. this._checkDelayState();
  1580. return true;
  1581. }
  1582. /**
  1583. * Sets the mesh material by the material or multiMaterial `id` property
  1584. * @param id is a string identifying the material or the multiMaterial
  1585. * @returns the current mesh
  1586. */
  1587. public setMaterialByID(id: string): Mesh {
  1588. var materials = this.getScene().materials;
  1589. var index: number;
  1590. for (index = materials.length - 1; index > -1; index--) {
  1591. if (materials[index].id === id) {
  1592. this.material = materials[index];
  1593. return this;
  1594. }
  1595. }
  1596. // Multi
  1597. var multiMaterials = this.getScene().multiMaterials;
  1598. for (index = multiMaterials.length - 1; index > -1; index--) {
  1599. if (multiMaterials[index].id === id) {
  1600. this.material = multiMaterials[index];
  1601. return this;
  1602. }
  1603. }
  1604. return this;
  1605. }
  1606. /**
  1607. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  1608. * @returns an array of IAnimatable
  1609. */
  1610. public getAnimatables(): IAnimatable[] {
  1611. var results = new Array<IAnimatable>();
  1612. if (this.material) {
  1613. results.push(this.material);
  1614. }
  1615. if (this.skeleton) {
  1616. results.push(this.skeleton);
  1617. }
  1618. return results;
  1619. }
  1620. /**
  1621. * Modifies the mesh geometry according to the passed transformation matrix.
  1622. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  1623. * The mesh normals are modified using the same transformation.
  1624. * Note that, under the hood, this method sets a new VertexBuffer each call.
  1625. * @param transform defines the transform matrix to use
  1626. * @see http://doc.babylonjs.com/resources/baking_transformations
  1627. * @returns the current mesh
  1628. */
  1629. public bakeTransformIntoVertices(transform: Matrix): Mesh {
  1630. // Position
  1631. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  1632. return this;
  1633. }
  1634. var submeshes = this.subMeshes.splice(0);
  1635. this._resetPointsArrayCache();
  1636. var data = <FloatArray>this.getVerticesData(VertexBuffer.PositionKind);
  1637. var temp = new Array<number>();
  1638. var index: number;
  1639. for (index = 0; index < data.length; index += 3) {
  1640. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  1641. }
  1642. this.setVerticesData(VertexBuffer.PositionKind, temp, (<VertexBuffer>this.getVertexBuffer(VertexBuffer.PositionKind)).isUpdatable());
  1643. // Normals
  1644. if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1645. data = <FloatArray>this.getVerticesData(VertexBuffer.NormalKind);
  1646. temp = [];
  1647. for (index = 0; index < data.length; index += 3) {
  1648. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  1649. }
  1650. this.setVerticesData(VertexBuffer.NormalKind, temp, (<VertexBuffer>this.getVertexBuffer(VertexBuffer.NormalKind)).isUpdatable());
  1651. }
  1652. // flip faces?
  1653. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) { this.flipFaces(); }
  1654. // Restore submeshes
  1655. this.releaseSubMeshes();
  1656. this.subMeshes = submeshes;
  1657. return this;
  1658. }
  1659. /**
  1660. * Modifies the mesh geometry according to its own current World Matrix.
  1661. * The mesh World Matrix is then reset.
  1662. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  1663. * Note that, under the hood, this method sets a new VertexBuffer each call.
  1664. * @see http://doc.babylonjs.com/resources/baking_transformations
  1665. * @returns the current mesh
  1666. */
  1667. public bakeCurrentTransformIntoVertices(): Mesh {
  1668. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  1669. this.scaling.copyFromFloats(1, 1, 1);
  1670. this.position.copyFromFloats(0, 0, 0);
  1671. this.rotation.copyFromFloats(0, 0, 0);
  1672. //only if quaternion is already set
  1673. if (this.rotationQuaternion) {
  1674. this.rotationQuaternion = Quaternion.Identity();
  1675. }
  1676. this._worldMatrix = Matrix.Identity();
  1677. return this;
  1678. }
  1679. // Cache
  1680. /** @hidden */
  1681. public get _positions(): Nullable<Vector3[]> {
  1682. if (this._geometry) {
  1683. return this._geometry._positions;
  1684. }
  1685. return null;
  1686. }
  1687. /** @hidden */
  1688. public _resetPointsArrayCache(): Mesh {
  1689. if (this._geometry) {
  1690. this._geometry._resetPointsArrayCache();
  1691. }
  1692. return this;
  1693. }
  1694. /** @hidden */
  1695. public _generatePointsArray(): boolean {
  1696. if (this._geometry) {
  1697. return this._geometry._generatePointsArray();
  1698. }
  1699. return false;
  1700. }
  1701. /**
  1702. * Returns a new Mesh object generated from the current mesh properties.
  1703. * This method must not get confused with createInstance()
  1704. * @param name is a string, the name given to the new mesh
  1705. * @param newParent can be any Node object (default `null`)
  1706. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  1707. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  1708. * @returns a new mesh
  1709. */
  1710. public clone(name: string = "", newParent?: Node, doNotCloneChildren?: boolean, clonePhysicsImpostor: boolean = true): Mesh {
  1711. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  1712. }
  1713. /**
  1714. * Releases resources associated with this mesh.
  1715. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  1716. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  1717. */
  1718. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  1719. this.morphTargetManager = null;
  1720. if (this._geometry) {
  1721. this._geometry.releaseForMesh(this, true);
  1722. }
  1723. if (this._onBeforeDrawObservable) {
  1724. this._onBeforeDrawObservable.clear();
  1725. }
  1726. if (this._onBeforeBindObservable) {
  1727. this._onBeforeBindObservable.clear();
  1728. }
  1729. if (this._onBeforeRenderObservable) {
  1730. this._onBeforeRenderObservable.clear();
  1731. }
  1732. if (this._onAfterRenderObservable) {
  1733. this._onAfterRenderObservable.clear();
  1734. }
  1735. // Sources
  1736. if (this._scene.useClonedMeshhMap) {
  1737. if (this.meshMap) {
  1738. for (const uniqueId in this.meshMap) {
  1739. const mesh = this.meshMap[uniqueId];
  1740. if (mesh) {
  1741. mesh._source = null;
  1742. this.meshMap[uniqueId] = undefined;
  1743. }
  1744. }
  1745. }
  1746. if (this._source && this._source.meshMap) {
  1747. this._source.meshMap[this.uniqueId] = undefined;
  1748. }
  1749. }
  1750. else {
  1751. var meshes = this.getScene().meshes;
  1752. for (const abstractMesh of meshes) {
  1753. let mesh = abstractMesh as Mesh;
  1754. if (mesh._source && mesh._source === this) {
  1755. mesh._source = null;
  1756. }
  1757. }
  1758. }
  1759. this._source = null;
  1760. // Instances
  1761. if (this._instanceDataStorage.instancesBuffer) {
  1762. this._instanceDataStorage.instancesBuffer.dispose();
  1763. this._instanceDataStorage.instancesBuffer = null;
  1764. }
  1765. while (this.instances.length) {
  1766. this.instances[0].dispose();
  1767. }
  1768. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  1769. }
  1770. /**
  1771. * Modifies the mesh geometry according to a displacement map.
  1772. * 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.
  1773. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  1774. * @param url is a string, the URL from the image file is to be downloaded.
  1775. * @param minHeight is the lower limit of the displacement.
  1776. * @param maxHeight is the upper limit of the displacement.
  1777. * @param 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.
  1778. * @param uvOffset is an optional vector2 used to offset UV.
  1779. * @param uvScale is an optional vector2 used to scale UV.
  1780. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance.
  1781. * @returns the Mesh.
  1782. */
  1783. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void, uvOffset?: Vector2, uvScale?: Vector2, forceUpdate = false): Mesh {
  1784. var scene = this.getScene();
  1785. var onload = (img: HTMLImageElement) => {
  1786. // Getting height map data
  1787. var canvas = document.createElement("canvas");
  1788. var context = <CanvasRenderingContext2D>canvas.getContext("2d");
  1789. var heightMapWidth = img.width;
  1790. var heightMapHeight = img.height;
  1791. canvas.width = heightMapWidth;
  1792. canvas.height = heightMapHeight;
  1793. context.drawImage(img, 0, 0);
  1794. // Create VertexData from map data
  1795. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  1796. var buffer = <Uint8Array>(<any>context.getImageData(0, 0, heightMapWidth, heightMapHeight).data);
  1797. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  1798. //execute success callback, if set
  1799. if (onSuccess) {
  1800. onSuccess(this);
  1801. }
  1802. };
  1803. Tools.LoadImage(url, onload, () => { }, scene.offlineProvider);
  1804. return this;
  1805. }
  1806. /**
  1807. * Modifies the mesh geometry according to a displacementMap buffer.
  1808. * 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.
  1809. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  1810. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  1811. * @param heightMapWidth is the width of the buffer image.
  1812. * @param heightMapHeight is the height of the buffer image.
  1813. * @param minHeight is the lower limit of the displacement.
  1814. * @param maxHeight is the upper limit of the displacement.
  1815. * @param 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.
  1816. * @param uvOffset is an optional vector2 used to offset UV.
  1817. * @param uvScale is an optional vector2 used to scale UV.
  1818. * @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance.
  1819. * @returns the Mesh.
  1820. */
  1821. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number, uvOffset?: Vector2, uvScale?: Vector2, forceUpdate = false): Mesh {
  1822. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  1823. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  1824. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  1825. Logger.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  1826. return this;
  1827. }
  1828. var positions = <FloatArray>this.getVerticesData(VertexBuffer.PositionKind, true, true);
  1829. var normals = <FloatArray>this.getVerticesData(VertexBuffer.NormalKind);
  1830. var uvs = <number[]>this.getVerticesData(VertexBuffer.UVKind);
  1831. var position = Vector3.Zero();
  1832. var normal = Vector3.Zero();
  1833. var uv = Vector2.Zero();
  1834. uvOffset = uvOffset || Vector2.Zero();
  1835. uvScale = uvScale || new Vector2(1, 1);
  1836. for (var index = 0; index < positions.length; index += 3) {
  1837. Vector3.FromArrayToRef(positions, index, position);
  1838. Vector3.FromArrayToRef(normals, index, normal);
  1839. Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  1840. // Compute height
  1841. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  1842. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  1843. var pos = (u + v * heightMapWidth) * 4;
  1844. var r = buffer[pos] / 255.0;
  1845. var g = buffer[pos + 1] / 255.0;
  1846. var b = buffer[pos + 2] / 255.0;
  1847. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  1848. normal.normalize();
  1849. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  1850. position = position.add(normal);
  1851. position.toArray(positions, index);
  1852. }
  1853. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  1854. if (forceUpdate) {
  1855. this.setVerticesData(VertexBuffer.PositionKind, positions);
  1856. this.setVerticesData(VertexBuffer.NormalKind, normals);
  1857. }
  1858. else {
  1859. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  1860. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  1861. }
  1862. return this;
  1863. }
  1864. /**
  1865. * Modify the mesh to get a flat shading rendering.
  1866. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  1867. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  1868. * @returns current mesh
  1869. */
  1870. public convertToFlatShadedMesh(): Mesh {
  1871. var kinds = this.getVerticesDataKinds();
  1872. var vbs: { [key: string]: VertexBuffer } = {};
  1873. var data: { [key: string]: FloatArray } = {};
  1874. var newdata: { [key: string]: Array<number> } = {};
  1875. var updatableNormals = false;
  1876. var kindIndex: number;
  1877. var kind: string;
  1878. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1879. kind = kinds[kindIndex];
  1880. var vertexBuffer = <VertexBuffer>this.getVertexBuffer(kind);
  1881. if (kind === VertexBuffer.NormalKind) {
  1882. updatableNormals = vertexBuffer.isUpdatable();
  1883. kinds.splice(kindIndex, 1);
  1884. kindIndex--;
  1885. continue;
  1886. }
  1887. vbs[kind] = vertexBuffer;
  1888. data[kind] = <FloatArray>vbs[kind].getData();
  1889. newdata[kind] = [];
  1890. }
  1891. // Save previous submeshes
  1892. var previousSubmeshes = this.subMeshes.slice(0);
  1893. var indices = <IndicesArray>this.getIndices();
  1894. var totalIndices = this.getTotalIndices();
  1895. // Generating unique vertices per face
  1896. var index: number;
  1897. for (index = 0; index < totalIndices; index++) {
  1898. var vertexIndex = indices[index];
  1899. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1900. kind = kinds[kindIndex];
  1901. var stride = vbs[kind].getStrideSize();
  1902. for (var offset = 0; offset < stride; offset++) {
  1903. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1904. }
  1905. }
  1906. }
  1907. // Updating faces & normal
  1908. var normals = [];
  1909. var positions = newdata[VertexBuffer.PositionKind];
  1910. for (index = 0; index < totalIndices; index += 3) {
  1911. indices[index] = index;
  1912. indices[index + 1] = index + 1;
  1913. indices[index + 2] = index + 2;
  1914. var p1 = Vector3.FromArray(positions, index * 3);
  1915. var p2 = Vector3.FromArray(positions, (index + 1) * 3);
  1916. var p3 = Vector3.FromArray(positions, (index + 2) * 3);
  1917. var p1p2 = p1.subtract(p2);
  1918. var p3p2 = p3.subtract(p2);
  1919. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  1920. // Store same normals for every vertex
  1921. for (var localIndex = 0; localIndex < 3; localIndex++) {
  1922. normals.push(normal.x);
  1923. normals.push(normal.y);
  1924. normals.push(normal.z);
  1925. }
  1926. }
  1927. this.setIndices(indices);
  1928. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  1929. // Updating vertex buffers
  1930. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1931. kind = kinds[kindIndex];
  1932. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1933. }
  1934. // Updating submeshes
  1935. this.releaseSubMeshes();
  1936. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1937. var previousOne = previousSubmeshes[submeshIndex];
  1938. SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1939. }
  1940. this.synchronizeInstances();
  1941. return this;
  1942. }
  1943. /**
  1944. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  1945. * In other words, more vertices, no more indices and a single bigger VBO.
  1946. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  1947. * @returns current mesh
  1948. */
  1949. public convertToUnIndexedMesh(): Mesh {
  1950. var kinds = this.getVerticesDataKinds();
  1951. var vbs: { [key: string]: VertexBuffer } = {};
  1952. var data: { [key: string]: FloatArray } = {};
  1953. var newdata: { [key: string]: Array<number> } = {};
  1954. var kindIndex: number;
  1955. var kind: string;
  1956. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1957. kind = kinds[kindIndex];
  1958. var vertexBuffer = <VertexBuffer>this.getVertexBuffer(kind);
  1959. vbs[kind] = vertexBuffer;
  1960. data[kind] = <FloatArray>vbs[kind].getData();
  1961. newdata[kind] = [];
  1962. }
  1963. // Save previous submeshes
  1964. var previousSubmeshes = this.subMeshes.slice(0);
  1965. var indices = <IndicesArray>this.getIndices();
  1966. var totalIndices = this.getTotalIndices();
  1967. // Generating unique vertices per face
  1968. var index: number;
  1969. for (index = 0; index < totalIndices; index++) {
  1970. var vertexIndex = indices[index];
  1971. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1972. kind = kinds[kindIndex];
  1973. var stride = vbs[kind].getStrideSize();
  1974. for (var offset = 0; offset < stride; offset++) {
  1975. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  1976. }
  1977. }
  1978. }
  1979. // Updating indices
  1980. for (index = 0; index < totalIndices; index += 3) {
  1981. indices[index] = index;
  1982. indices[index + 1] = index + 1;
  1983. indices[index + 2] = index + 2;
  1984. }
  1985. this.setIndices(indices);
  1986. // Updating vertex buffers
  1987. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  1988. kind = kinds[kindIndex];
  1989. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  1990. }
  1991. // Updating submeshes
  1992. this.releaseSubMeshes();
  1993. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  1994. var previousOne = previousSubmeshes[submeshIndex];
  1995. SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  1996. }
  1997. this._unIndexed = true;
  1998. this.synchronizeInstances();
  1999. return this;
  2000. }
  2001. /**
  2002. * Inverses facet orientations.
  2003. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  2004. * @param flipNormals will also inverts the normals
  2005. * @returns current mesh
  2006. */
  2007. public flipFaces(flipNormals: boolean = false): Mesh {
  2008. var vertex_data = VertexData.ExtractFromMesh(this);
  2009. var i: number;
  2010. if (flipNormals && this.isVerticesDataPresent(VertexBuffer.NormalKind) && vertex_data.normals) {
  2011. for (i = 0; i < vertex_data.normals.length; i++) {
  2012. vertex_data.normals[i] *= -1;
  2013. }
  2014. }
  2015. if (vertex_data.indices) {
  2016. var temp;
  2017. for (i = 0; i < vertex_data.indices.length; i += 3) {
  2018. // reassign indices
  2019. temp = vertex_data.indices[i + 1];
  2020. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  2021. vertex_data.indices[i + 2] = temp;
  2022. }
  2023. }
  2024. vertex_data.applyToMesh(this);
  2025. return this;
  2026. }
  2027. /**
  2028. * Increase the number of facets and hence vertices in a mesh
  2029. * Vertex normals are interpolated from existing vertex normals
  2030. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  2031. * @param numberPerEdge the number of new vertices to add to each edge of a facet, optional default 1
  2032. */
  2033. public increaseVertices(numberPerEdge: number): void {
  2034. var vertex_data = VertexData.ExtractFromMesh(this);
  2035. var uvs = vertex_data.uvs;
  2036. var currentIndices = vertex_data.indices;
  2037. var positions = vertex_data.positions;
  2038. var normals = vertex_data.normals;
  2039. if (currentIndices === null || positions === null || normals === null || uvs === null) {
  2040. Logger.Warn("VertexData contains null entries");
  2041. }
  2042. else {
  2043. var segments: number = numberPerEdge + 1; //segments per current facet edge, become sides of new facets
  2044. var tempIndices: Array<Array<number>> = new Array();
  2045. for (var i = 0; i < segments + 1; i++) {
  2046. tempIndices[i] = new Array();
  2047. }
  2048. var a: number; //vertex index of one end of a side
  2049. var b: number; //vertex index of other end of the side
  2050. var deltaPosition: Vector3 = new Vector3(0, 0, 0);
  2051. var deltaNormal: Vector3 = new Vector3(0, 0, 0);
  2052. var deltaUV: Vector2 = new Vector2(0, 0);
  2053. var indices: number[] = new Array();
  2054. var vertexIndex: number[] = new Array();
  2055. var side: Array<Array<Array<number>>> = new Array();
  2056. var len: number;
  2057. var positionPtr: number = positions.length;
  2058. var uvPtr: number = uvs.length;
  2059. for (var i = 0; i < currentIndices.length; i += 3) {
  2060. vertexIndex[0] = currentIndices[i];
  2061. vertexIndex[1] = currentIndices[i + 1];
  2062. vertexIndex[2] = currentIndices[i + 2];
  2063. for (var j = 0; j < 3; j++) {
  2064. a = vertexIndex[j];
  2065. b = vertexIndex[(j + 1) % 3];
  2066. if (side[a] === undefined && side[b] === undefined) {
  2067. side[a] = new Array();
  2068. side[b] = new Array();
  2069. }
  2070. else {
  2071. if (side[a] === undefined) {
  2072. side[a] = new Array();
  2073. }
  2074. if (side[b] === undefined) {
  2075. side[b] = new Array();
  2076. }
  2077. }
  2078. if (side[a][b] === undefined && side[b][a] === undefined) {
  2079. side[a][b] = [];
  2080. deltaPosition.x = (positions[3 * b] - positions[3 * a]) / segments;
  2081. deltaPosition.y = (positions[3 * b + 1] - positions[3 * a + 1]) / segments;
  2082. deltaPosition.z = (positions[3 * b + 2] - positions[3 * a + 2]) / segments;
  2083. deltaNormal.x = (normals[3 * b] - normals[3 * a]) / segments;
  2084. deltaNormal.y = (normals[3 * b + 1] - normals[3 * a + 1]) / segments;
  2085. deltaNormal.z = (normals[3 * b + 2] - normals[3 * a + 2]) / segments;
  2086. deltaUV.x = (uvs[2 * b] - uvs[2 * a]) / segments;
  2087. deltaUV.y = (uvs[2 * b + 1] - uvs[2 * a + 1]) / segments;
  2088. side[a][b].push(a);
  2089. for (var k = 1; k < segments; k++) {
  2090. side[a][b].push(positions.length / 3);
  2091. positions[positionPtr] = positions[3 * a] + k * deltaPosition.x;
  2092. normals[positionPtr++] = normals[3 * a] + k * deltaNormal.x;
  2093. positions[positionPtr] = positions[3 * a + 1] + k * deltaPosition.y;
  2094. normals[positionPtr++] = normals[3 * a + 1] + k * deltaNormal.y;
  2095. positions[positionPtr] = positions[3 * a + 2] + k * deltaPosition.z;
  2096. normals[positionPtr++] = normals[3 * a + 2] + k * deltaNormal.z;
  2097. uvs[uvPtr++] = uvs[2 * a] + k * deltaUV.x;
  2098. uvs[uvPtr++] = uvs[2 * a + 1] + k * deltaUV.y;
  2099. }
  2100. side[a][b].push(b);
  2101. side[b][a] = new Array();
  2102. len = side[a][b].length;
  2103. for (var idx = 0; idx < len; idx++) {
  2104. side[b][a][idx] = side[a][b][len - 1 - idx];
  2105. }
  2106. }
  2107. }
  2108. //Calculate positions, normals and uvs of new internal vertices
  2109. tempIndices[0][0] = currentIndices[i];
  2110. tempIndices[1][0] = side[currentIndices[i]][currentIndices[i + 1]][1];
  2111. tempIndices[1][1] = side[currentIndices[i]][currentIndices[i + 2]][1];
  2112. for (var k = 2; k < segments; k++) {
  2113. tempIndices[k][0] = side[currentIndices[i]][currentIndices[i + 1]][k];
  2114. tempIndices[k][k] = side[currentIndices[i]][currentIndices[i + 2]][k];
  2115. deltaPosition.x = (positions[3 * tempIndices[k][k]] - positions[3 * tempIndices[k][0]]) / k;
  2116. deltaPosition.y = (positions[3 * tempIndices[k][k] + 1] - positions[3 * tempIndices[k][0] + 1]) / k;
  2117. deltaPosition.z = (positions[3 * tempIndices[k][k] + 2] - positions[3 * tempIndices[k][0] + 2]) / k;
  2118. deltaNormal.x = (normals[3 * tempIndices[k][k]] - normals[3 * tempIndices[k][0]]) / k;
  2119. deltaNormal.y = (normals[3 * tempIndices[k][k] + 1] - normals[3 * tempIndices[k][0] + 1]) / k;
  2120. deltaNormal.z = (normals[3 * tempIndices[k][k] + 2] - normals[3 * tempIndices[k][0] + 2]) / k;
  2121. deltaUV.x = (uvs[2 * tempIndices[k][k]] - uvs[2 * tempIndices[k][0]]) / k;
  2122. deltaUV.y = (uvs[2 * tempIndices[k][k] + 1] - uvs[2 * tempIndices[k][0] + 1]) / k;
  2123. for (var j = 1; j < k; j++) {
  2124. tempIndices[k][j] = positions.length / 3;
  2125. positions[positionPtr] = positions[3 * tempIndices[k][0]] + j * deltaPosition.x;
  2126. normals[positionPtr++] = normals[3 * tempIndices[k][0]] + j * deltaNormal.x;
  2127. positions[positionPtr] = positions[3 * tempIndices[k][0] + 1] + j * deltaPosition.y;
  2128. normals[positionPtr++] = normals[3 * tempIndices[k][0] + 1] + j * deltaNormal.y;
  2129. positions[positionPtr] = positions[3 * tempIndices[k][0] + 2] + j * deltaPosition.z;
  2130. normals[positionPtr++] = normals[3 * tempIndices[k][0] + 2] + j * deltaNormal.z;
  2131. uvs[uvPtr++] = uvs[2 * tempIndices[k][0]] + j * deltaUV.x;
  2132. uvs[uvPtr++] = uvs[2 * tempIndices[k][0] + 1] + j * deltaUV.y;
  2133. }
  2134. }
  2135. tempIndices[segments] = side[currentIndices[i + 1]][currentIndices[i + 2]];
  2136. // reform indices
  2137. indices.push(tempIndices[0][0], tempIndices[1][0], tempIndices[1][1]);
  2138. for (var k = 1; k < segments; k++) {
  2139. for (var j = 0; j < k; j++) {
  2140. indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]);
  2141. indices.push(tempIndices[k][j], tempIndices[k + 1][j + 1], tempIndices[k][j + 1]);
  2142. }
  2143. indices.push(tempIndices[k][j], tempIndices[k + 1][j], tempIndices[k + 1][j + 1]);
  2144. }
  2145. }
  2146. vertex_data.indices = indices;
  2147. vertex_data.applyToMesh(this);
  2148. }
  2149. }
  2150. /**
  2151. * Force adjacent facets to share vertices and remove any facets that have all vertices in a line
  2152. * This will undo any application of covertToFlatShadedMesh
  2153. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  2154. */
  2155. public forceSharedVertices(): void {
  2156. var vertex_data = VertexData.ExtractFromMesh(this);
  2157. var currentUVs = vertex_data.uvs;
  2158. var currentIndices = vertex_data.indices;
  2159. var currentPositions = vertex_data.positions;
  2160. var currentNormals = vertex_data.normals;
  2161. if (currentIndices === null || currentPositions === null || currentNormals === null || currentUVs === null) {
  2162. Logger.Warn("VertexData contains null entries");
  2163. }
  2164. else {
  2165. var positions: Array<number> = new Array();
  2166. var indices: Array<number> = new Array();
  2167. var uvs: Array<number> = new Array();
  2168. var pstring: Array<string> = new Array(); //lists facet vertex positions (a,b,c) as string "a|b|c"
  2169. var indexPtr: number = 0; // pointer to next available index value
  2170. var uniquePositions: Array<string> = new Array(); // unique vertex positions
  2171. var ptr: number; // pointer to element in uniquePositions
  2172. var facet: Array<number>;
  2173. for (var i = 0; i < currentIndices.length; i += 3) {
  2174. facet = [currentIndices[i], currentIndices[i + 1], currentIndices[i + 2]]; //facet vertex indices
  2175. pstring = new Array();
  2176. for (var j = 0; j < 3; j++) {
  2177. pstring[j] = "";
  2178. for (var k = 0; k < 3; k++) {
  2179. //small values make 0
  2180. if (Math.abs(currentPositions[3 * facet[j] + k]) < 0.00000001) {
  2181. currentPositions[3 * facet[j] + k] = 0;
  2182. }
  2183. pstring[j] += currentPositions[3 * facet[j] + k] + "|";
  2184. }
  2185. pstring[j] = pstring[j].slice(0, -1);
  2186. }
  2187. //check facet vertices to see that none are repeated
  2188. // do not process any facet that has a repeated vertex, ie is a line
  2189. if (!(pstring[0] == pstring[1] || pstring[0] == pstring[2] || pstring[1] == pstring[2])) {
  2190. //for each facet position check if already listed in uniquePositions
  2191. // if not listed add to uniquePositions and set index pointer
  2192. // if listed use its index in uniquePositions and new index pointer
  2193. for (var j = 0; j < 3; j++) {
  2194. ptr = uniquePositions.indexOf(pstring[j]);
  2195. if (ptr < 0) {
  2196. uniquePositions.push(pstring[j]);
  2197. ptr = indexPtr++;
  2198. //not listed so add individual x, y, z coordinates to positions
  2199. for (var k = 0; k < 3; k++) {
  2200. positions.push(currentPositions[3 * facet[j] + k]);
  2201. }
  2202. for (var k = 0; k < 2; k++) {
  2203. uvs.push(currentUVs[2 * facet[j] + k]);
  2204. }
  2205. }
  2206. // add new index pointer to indices array
  2207. indices.push(ptr);
  2208. }
  2209. }
  2210. }
  2211. var normals: Array<number> = new Array();
  2212. VertexData.ComputeNormals(positions, indices, normals);
  2213. //create new vertex data object and update
  2214. vertex_data.positions = positions;
  2215. vertex_data.indices = indices;
  2216. vertex_data.normals = normals;
  2217. vertex_data.uvs = uvs;
  2218. vertex_data.applyToMesh(this);
  2219. }
  2220. }
  2221. // Instances
  2222. /** @hidden */
  2223. public static _instancedMeshFactory(name: string, mesh: Mesh): InstancedMesh {
  2224. throw _DevTools.WarnImport("InstancedMesh");
  2225. }
  2226. /** @hidden */
  2227. public static _PhysicsImpostorParser(scene: Scene, physicObject: IPhysicsEnabledObject, jsonObject: any): PhysicsImpostor {
  2228. throw _DevTools.WarnImport("PhysicsImpostor");
  2229. }
  2230. /**
  2231. * Creates a new InstancedMesh object from the mesh model.
  2232. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  2233. * @param name defines the name of the new instance
  2234. * @returns a new InstancedMesh
  2235. */
  2236. public createInstance(name: string): InstancedMesh {
  2237. return Mesh._instancedMeshFactory(name, this);
  2238. }
  2239. /**
  2240. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  2241. * After this call, all the mesh instances have the same submeshes than the current mesh.
  2242. * @returns the current mesh
  2243. */
  2244. public synchronizeInstances(): Mesh {
  2245. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  2246. var instance = this.instances[instanceIndex];
  2247. instance._syncSubMeshes();
  2248. }
  2249. return this;
  2250. }
  2251. /**
  2252. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  2253. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  2254. * This should be used together with the simplification to avoid disappearing triangles.
  2255. * @param successCallback an optional success callback to be called after the optimization finished.
  2256. * @returns the current mesh
  2257. */
  2258. public optimizeIndices(successCallback?: (mesh?: Mesh) => void): Mesh {
  2259. var indices = <IndicesArray>this.getIndices();
  2260. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  2261. if (!positions || !indices) {
  2262. return this;
  2263. }
  2264. var vectorPositions = new Array<Vector3>();
  2265. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  2266. vectorPositions.push(Vector3.FromArray(positions, pos));
  2267. }
  2268. var dupes = new Array<number>();
  2269. AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, (iteration) => {
  2270. var realPos = vectorPositions.length - 1 - iteration;
  2271. var testedPosition = vectorPositions[realPos];
  2272. for (var j = 0; j < realPos; ++j) {
  2273. var againstPosition = vectorPositions[j];
  2274. if (testedPosition.equals(againstPosition)) {
  2275. dupes[realPos] = j;
  2276. break;
  2277. }
  2278. }
  2279. }, () => {
  2280. for (var i = 0; i < indices.length; ++i) {
  2281. indices[i] = dupes[indices[i]] || indices[i];
  2282. }
  2283. //indices are now reordered
  2284. var originalSubMeshes = this.subMeshes.slice(0);
  2285. this.setIndices(indices);
  2286. this.subMeshes = originalSubMeshes;
  2287. if (successCallback) {
  2288. successCallback(this);
  2289. }
  2290. });
  2291. return this;
  2292. }
  2293. /**
  2294. * Serialize current mesh
  2295. * @param serializationObject defines the object which will receive the serialization data
  2296. */
  2297. public serialize(serializationObject: any): void {
  2298. serializationObject.name = this.name;
  2299. serializationObject.id = this.id;
  2300. serializationObject.type = this.getClassName();
  2301. if (Tags && Tags.HasTags(this)) {
  2302. serializationObject.tags = Tags.GetTags(this);
  2303. }
  2304. serializationObject.position = this.position.asArray();
  2305. if (this.rotationQuaternion) {
  2306. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  2307. } else if (this.rotation) {
  2308. serializationObject.rotation = this.rotation.asArray();
  2309. }
  2310. serializationObject.scaling = this.scaling.asArray();
  2311. if (this._postMultiplyPivotMatrix) {
  2312. serializationObject.pivotMatrix = this.getPivotMatrix().asArray();
  2313. } else {
  2314. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  2315. }
  2316. serializationObject.isEnabled = this.isEnabled(false);
  2317. serializationObject.isVisible = this.isVisible;
  2318. serializationObject.infiniteDistance = this.infiniteDistance;
  2319. serializationObject.pickable = this.isPickable;
  2320. serializationObject.receiveShadows = this.receiveShadows;
  2321. serializationObject.billboardMode = this.billboardMode;
  2322. serializationObject.visibility = this.visibility;
  2323. serializationObject.checkCollisions = this.checkCollisions;
  2324. serializationObject.isBlocker = this.isBlocker;
  2325. // Parent
  2326. if (this.parent) {
  2327. serializationObject.parentId = this.parent.id;
  2328. }
  2329. // Geometry
  2330. serializationObject.isUnIndexed = this.isUnIndexed;
  2331. var geometry = this._geometry;
  2332. if (geometry) {
  2333. var geometryId = geometry.id;
  2334. serializationObject.geometryId = geometryId;
  2335. // SubMeshes
  2336. serializationObject.subMeshes = [];
  2337. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  2338. var subMesh = this.subMeshes[subIndex];
  2339. serializationObject.subMeshes.push({
  2340. materialIndex: subMesh.materialIndex,
  2341. verticesStart: subMesh.verticesStart,
  2342. verticesCount: subMesh.verticesCount,
  2343. indexStart: subMesh.indexStart,
  2344. indexCount: subMesh.indexCount
  2345. });
  2346. }
  2347. }
  2348. // Material
  2349. if (this.material) {
  2350. serializationObject.materialId = this.material.id;
  2351. } else {
  2352. this.material = null;
  2353. }
  2354. // Morph targets
  2355. if (this.morphTargetManager) {
  2356. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  2357. }
  2358. // Skeleton
  2359. if (this.skeleton) {
  2360. serializationObject.skeletonId = this.skeleton.id;
  2361. }
  2362. // Physics
  2363. //TODO implement correct serialization for physics impostors.
  2364. let impostor = this.getPhysicsImpostor();
  2365. if (impostor) {
  2366. serializationObject.physicsMass = impostor.getParam("mass");
  2367. serializationObject.physicsFriction = impostor.getParam("friction");
  2368. serializationObject.physicsRestitution = impostor.getParam("mass");
  2369. serializationObject.physicsImpostor = impostor.type;
  2370. }
  2371. // Metadata
  2372. if (this.metadata) {
  2373. serializationObject.metadata = this.metadata;
  2374. }
  2375. // Instances
  2376. serializationObject.instances = [];
  2377. for (var index = 0; index < this.instances.length; index++) {
  2378. var instance = this.instances[index];
  2379. if (instance.doNotSerialize) {
  2380. continue;
  2381. }
  2382. var serializationInstance: any = {
  2383. name: instance.name,
  2384. id: instance.id,
  2385. position: instance.position.asArray(),
  2386. scaling: instance.scaling.asArray()
  2387. };
  2388. if (instance.parent) {
  2389. serializationInstance.parentId = instance.parent.id;
  2390. }
  2391. if (instance.rotationQuaternion) {
  2392. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  2393. } else if (instance.rotation) {
  2394. serializationInstance.rotation = instance.rotation.asArray();
  2395. }
  2396. serializationObject.instances.push(serializationInstance);
  2397. // Animations
  2398. SerializationHelper.AppendSerializedAnimations(instance, serializationInstance);
  2399. serializationInstance.ranges = instance.serializeAnimationRanges();
  2400. }
  2401. //
  2402. // Animations
  2403. SerializationHelper.AppendSerializedAnimations(this, serializationObject);
  2404. serializationObject.ranges = this.serializeAnimationRanges();
  2405. // Layer mask
  2406. serializationObject.layerMask = this.layerMask;
  2407. // Alpha
  2408. serializationObject.alphaIndex = this.alphaIndex;
  2409. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  2410. // Overlay
  2411. serializationObject.overlayAlpha = this.overlayAlpha;
  2412. serializationObject.overlayColor = this.overlayColor.asArray();
  2413. serializationObject.renderOverlay = this.renderOverlay;
  2414. // Fog
  2415. serializationObject.applyFog = this.applyFog;
  2416. // Action Manager
  2417. if (this.actionManager) {
  2418. serializationObject.actions = this.actionManager.serialize(this.name);
  2419. }
  2420. }
  2421. /** @hidden */
  2422. public _syncGeometryWithMorphTargetManager() {
  2423. if (!this.geometry) {
  2424. return;
  2425. }
  2426. this._markSubMeshesAsAttributesDirty();
  2427. let morphTargetManager = this._morphTargetManager;
  2428. if (morphTargetManager && morphTargetManager.vertexCount) {
  2429. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  2430. Logger.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  2431. this.morphTargetManager = null;
  2432. return;
  2433. }
  2434. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  2435. var morphTarget = morphTargetManager.getActiveTarget(index);
  2436. const positions = morphTarget.getPositions();
  2437. if (!positions) {
  2438. Logger.Error("Invalid morph target. Target must have positions.");
  2439. return;
  2440. }
  2441. this.geometry.setVerticesData(VertexBuffer.PositionKind + index, positions, false, 3);
  2442. const normals = morphTarget.getNormals();
  2443. if (normals) {
  2444. this.geometry.setVerticesData(VertexBuffer.NormalKind + index, normals, false, 3);
  2445. }
  2446. const tangents = morphTarget.getTangents();
  2447. if (tangents) {
  2448. this.geometry.setVerticesData(VertexBuffer.TangentKind + index, tangents, false, 3);
  2449. }
  2450. }
  2451. } else {
  2452. var index = 0;
  2453. // Positions
  2454. while (this.geometry.isVerticesDataPresent(VertexBuffer.PositionKind + index)) {
  2455. this.geometry.removeVerticesData(VertexBuffer.PositionKind + index);
  2456. if (this.geometry.isVerticesDataPresent(VertexBuffer.NormalKind + index)) {
  2457. this.geometry.removeVerticesData(VertexBuffer.NormalKind + index);
  2458. }
  2459. if (this.geometry.isVerticesDataPresent(VertexBuffer.TangentKind + index)) {
  2460. this.geometry.removeVerticesData(VertexBuffer.TangentKind + index);
  2461. }
  2462. index++;
  2463. }
  2464. }
  2465. }
  2466. // Statics
  2467. /** @hidden */
  2468. public static _GroundMeshParser = (parsedMesh: any, scene: Scene): Mesh => {
  2469. throw _DevTools.WarnImport("GroundMesh");
  2470. }
  2471. /**
  2472. * Returns a new Mesh object parsed from the source provided.
  2473. * @param parsedMesh is the source
  2474. * @param scene defines the hosting scene
  2475. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  2476. * @returns a new Mesh
  2477. */
  2478. public static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh {
  2479. var mesh: Mesh;
  2480. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  2481. mesh = Mesh._GroundMeshParser(parsedMesh, scene);
  2482. } else {
  2483. mesh = new Mesh(parsedMesh.name, scene);
  2484. }
  2485. mesh.id = parsedMesh.id;
  2486. if (Tags) {
  2487. Tags.AddTagsTo(mesh, parsedMesh.tags);
  2488. }
  2489. mesh.position = Vector3.FromArray(parsedMesh.position);
  2490. if (parsedMesh.metadata !== undefined) {
  2491. mesh.metadata = parsedMesh.metadata;
  2492. }
  2493. if (parsedMesh.rotationQuaternion) {
  2494. mesh.rotationQuaternion = Quaternion.FromArray(parsedMesh.rotationQuaternion);
  2495. } else if (parsedMesh.rotation) {
  2496. mesh.rotation = Vector3.FromArray(parsedMesh.rotation);
  2497. }
  2498. mesh.scaling = Vector3.FromArray(parsedMesh.scaling);
  2499. if (parsedMesh.localMatrix) {
  2500. mesh.setPreTransformMatrix(Matrix.FromArray(parsedMesh.localMatrix));
  2501. } else if (parsedMesh.pivotMatrix) {
  2502. mesh.setPivotMatrix(Matrix.FromArray(parsedMesh.pivotMatrix));
  2503. }
  2504. mesh.setEnabled(parsedMesh.isEnabled);
  2505. mesh.isVisible = parsedMesh.isVisible;
  2506. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  2507. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  2508. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  2509. if (parsedMesh.applyFog !== undefined) {
  2510. mesh.applyFog = parsedMesh.applyFog;
  2511. }
  2512. if (parsedMesh.pickable !== undefined) {
  2513. mesh.isPickable = parsedMesh.pickable;
  2514. }
  2515. if (parsedMesh.alphaIndex !== undefined) {
  2516. mesh.alphaIndex = parsedMesh.alphaIndex;
  2517. }
  2518. mesh.receiveShadows = parsedMesh.receiveShadows;
  2519. mesh.billboardMode = parsedMesh.billboardMode;
  2520. if (parsedMesh.visibility !== undefined) {
  2521. mesh.visibility = parsedMesh.visibility;
  2522. }
  2523. mesh.checkCollisions = parsedMesh.checkCollisions;
  2524. if (parsedMesh.isBlocker !== undefined) {
  2525. mesh.isBlocker = parsedMesh.isBlocker;
  2526. }
  2527. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  2528. // freezeWorldMatrix
  2529. if (parsedMesh.freezeWorldMatrix) {
  2530. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  2531. }
  2532. // Parent
  2533. if (parsedMesh.parentId) {
  2534. mesh._waitingParentId = parsedMesh.parentId;
  2535. }
  2536. // Actions
  2537. if (parsedMesh.actions !== undefined) {
  2538. mesh._waitingActions = parsedMesh.actions;
  2539. }
  2540. // Overlay
  2541. if (parsedMesh.overlayAlpha !== undefined) {
  2542. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  2543. }
  2544. if (parsedMesh.overlayColor !== undefined) {
  2545. mesh.overlayColor = Color3.FromArray(parsedMesh.overlayColor);
  2546. }
  2547. if (parsedMesh.renderOverlay !== undefined) {
  2548. mesh.renderOverlay = parsedMesh.renderOverlay;
  2549. }
  2550. // Geometry
  2551. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  2552. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  2553. if (parsedMesh.delayLoadingFile) {
  2554. mesh.delayLoadState = Constants.DELAYLOADSTATE_NOTLOADED;
  2555. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  2556. mesh._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedMesh.boundingBoxMinimum), Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  2557. if (parsedMesh._binaryInfo) {
  2558. mesh._binaryInfo = parsedMesh._binaryInfo;
  2559. }
  2560. mesh._delayInfo = [];
  2561. if (parsedMesh.hasUVs) {
  2562. mesh._delayInfo.push(VertexBuffer.UVKind);
  2563. }
  2564. if (parsedMesh.hasUVs2) {
  2565. mesh._delayInfo.push(VertexBuffer.UV2Kind);
  2566. }
  2567. if (parsedMesh.hasUVs3) {
  2568. mesh._delayInfo.push(VertexBuffer.UV3Kind);
  2569. }
  2570. if (parsedMesh.hasUVs4) {
  2571. mesh._delayInfo.push(VertexBuffer.UV4Kind);
  2572. }
  2573. if (parsedMesh.hasUVs5) {
  2574. mesh._delayInfo.push(VertexBuffer.UV5Kind);
  2575. }
  2576. if (parsedMesh.hasUVs6) {
  2577. mesh._delayInfo.push(VertexBuffer.UV6Kind);
  2578. }
  2579. if (parsedMesh.hasColors) {
  2580. mesh._delayInfo.push(VertexBuffer.ColorKind);
  2581. }
  2582. if (parsedMesh.hasMatricesIndices) {
  2583. mesh._delayInfo.push(VertexBuffer.MatricesIndicesKind);
  2584. }
  2585. if (parsedMesh.hasMatricesWeights) {
  2586. mesh._delayInfo.push(VertexBuffer.MatricesWeightsKind);
  2587. }
  2588. mesh._delayLoadingFunction = Geometry._ImportGeometry;
  2589. if (SceneLoaderFlags.ForceFullSceneLoadingForIncremental) {
  2590. mesh._checkDelayState();
  2591. }
  2592. } else {
  2593. Geometry._ImportGeometry(parsedMesh, mesh);
  2594. }
  2595. // Material
  2596. if (parsedMesh.materialId) {
  2597. mesh.setMaterialByID(parsedMesh.materialId);
  2598. } else {
  2599. mesh.material = null;
  2600. }
  2601. // Morph targets
  2602. if (parsedMesh.morphTargetManagerId > -1) {
  2603. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  2604. }
  2605. // Skeleton
  2606. if (parsedMesh.skeletonId > -1) {
  2607. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  2608. if (parsedMesh.numBoneInfluencers) {
  2609. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  2610. }
  2611. }
  2612. // Animations
  2613. if (parsedMesh.animations) {
  2614. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  2615. var parsedAnimation = parsedMesh.animations[animationIndex];
  2616. const internalClass = _TypeStore.GetClass("BABYLON.Animation");
  2617. if (internalClass) {
  2618. mesh.animations.push(internalClass.Parse(parsedAnimation));
  2619. }
  2620. }
  2621. Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  2622. }
  2623. if (parsedMesh.autoAnimate) {
  2624. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  2625. }
  2626. // Layer Mask
  2627. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  2628. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  2629. } else {
  2630. mesh.layerMask = 0x0FFFFFFF;
  2631. }
  2632. // Physics
  2633. if (parsedMesh.physicsImpostor) {
  2634. Mesh._PhysicsImpostorParser(scene, mesh, parsedMesh);
  2635. }
  2636. // Instances
  2637. if (parsedMesh.instances) {
  2638. for (var index = 0; index < parsedMesh.instances.length; index++) {
  2639. var parsedInstance = parsedMesh.instances[index];
  2640. var instance = mesh.createInstance(parsedInstance.name);
  2641. if (parsedInstance.id) {
  2642. instance.id = parsedInstance.id;
  2643. }
  2644. if (Tags) {
  2645. if (parsedInstance.tags) {
  2646. Tags.AddTagsTo(instance, parsedInstance.tags);
  2647. } else {
  2648. Tags.AddTagsTo(instance, parsedMesh.tags);
  2649. }
  2650. }
  2651. instance.position = Vector3.FromArray(parsedInstance.position);
  2652. if (parsedInstance.parentId) {
  2653. instance._waitingParentId = parsedInstance.parentId;
  2654. }
  2655. if (parsedInstance.rotationQuaternion) {
  2656. instance.rotationQuaternion = Quaternion.FromArray(parsedInstance.rotationQuaternion);
  2657. } else if (parsedInstance.rotation) {
  2658. instance.rotation = Vector3.FromArray(parsedInstance.rotation);
  2659. }
  2660. instance.scaling = Vector3.FromArray(parsedInstance.scaling);
  2661. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  2662. instance.checkCollisions = parsedInstance.checkCollisions;
  2663. }
  2664. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  2665. instance.isPickable = parsedInstance.pickable;
  2666. }
  2667. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  2668. instance.showBoundingBox = parsedInstance.showBoundingBox;
  2669. }
  2670. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  2671. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  2672. }
  2673. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  2674. instance.alphaIndex = parsedInstance.alphaIndex;
  2675. }
  2676. // Physics
  2677. if (parsedInstance.physicsImpostor) {
  2678. Mesh._PhysicsImpostorParser(scene, instance, parsedInstance);
  2679. }
  2680. // Animation
  2681. if (parsedInstance.animations) {
  2682. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  2683. parsedAnimation = parsedInstance.animations[animationIndex];
  2684. const internalClass = _TypeStore.GetClass("BABYLON.Animation");
  2685. if (internalClass) {
  2686. instance.animations.push(internalClass.Parse(parsedAnimation));
  2687. }
  2688. }
  2689. Node.ParseAnimationRanges(instance, parsedInstance, scene);
  2690. if (parsedInstance.autoAnimate) {
  2691. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  2692. }
  2693. }
  2694. }
  2695. }
  2696. return mesh;
  2697. }
  2698. /**
  2699. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  2700. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  2701. * @param name defines the name of the mesh to create
  2702. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  2703. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  2704. * @param closePath creates a seam between the first and the last points of each path of the path array
  2705. * @param offset is taken in account only if the `pathArray` is containing a single path
  2706. * @param scene defines the hosting scene
  2707. * @param updatable defines if the mesh must be flagged as updatable
  2708. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2709. * @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
  2710. * @returns a new Mesh
  2711. */
  2712. public static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene?: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh {
  2713. throw _DevTools.WarnImport("MeshBuilder");
  2714. }
  2715. /**
  2716. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  2717. * @param name defines the name of the mesh to create
  2718. * @param radius sets the radius size (float) of the polygon (default 0.5)
  2719. * @param 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
  2720. * @param scene defines the hosting scene
  2721. * @param updatable defines if the mesh must be flagged as updatable
  2722. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2723. * @returns a new Mesh
  2724. */
  2725. public static CreateDisc(name: string, radius: number, tessellation: number, scene: Nullable<Scene> = null, updatable?: boolean, sideOrientation?: number): Mesh {
  2726. throw _DevTools.WarnImport("MeshBuilder");
  2727. }
  2728. /**
  2729. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  2730. * @param name defines the name of the mesh to create
  2731. * @param size sets the size (float) of each box side (default 1)
  2732. * @param scene defines the hosting scene
  2733. * @param updatable defines if the mesh must be flagged as updatable
  2734. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2735. * @returns a new Mesh
  2736. */
  2737. public static CreateBox(name: string, size: number, scene: Nullable<Scene> = null, updatable?: boolean, sideOrientation?: number): Mesh {
  2738. throw _DevTools.WarnImport("MeshBuilder");
  2739. }
  2740. /**
  2741. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  2742. * @param name defines the name of the mesh to create
  2743. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  2744. * @param diameter sets the diameter size (float) of the sphere (default 1)
  2745. * @param scene defines the hosting scene
  2746. * @param updatable defines if the mesh must be flagged as updatable
  2747. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2748. * @returns a new Mesh
  2749. */
  2750. public static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2751. throw _DevTools.WarnImport("MeshBuilder");
  2752. }
  2753. /**
  2754. * Creates a hemisphere mesh. Please consider using the same method from the MeshBuilder class instead
  2755. * @param name defines the name of the mesh to create
  2756. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  2757. * @param diameter sets the diameter size (float) of the sphere (default 1)
  2758. * @param scene defines the hosting scene
  2759. * @returns a new Mesh
  2760. */
  2761. public static CreateHemisphere(name: string, segments: number, diameter: number, scene?: Scene): Mesh {
  2762. throw _DevTools.WarnImport("MeshBuilder");
  2763. }
  2764. /**
  2765. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  2766. * @param name defines the name of the mesh to create
  2767. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  2768. * @param diameterTop set the top cap diameter (floats, default 1)
  2769. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  2770. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  2771. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  2772. * @param scene defines the hosting scene
  2773. * @param updatable defines if the mesh must be flagged as updatable
  2774. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2775. * @returns a new Mesh
  2776. */
  2777. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene?: Scene, updatable?: any, sideOrientation?: number): Mesh {
  2778. throw _DevTools.WarnImport("MeshBuilder");
  2779. }
  2780. // Torus (Code from SharpDX.org)
  2781. /**
  2782. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  2783. * @param name defines the name of the mesh to create
  2784. * @param diameter sets the diameter size (float) of the torus (default 1)
  2785. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  2786. * @param tessellation sets the number of torus sides (postive integer, default 16)
  2787. * @param scene defines the hosting scene
  2788. * @param updatable defines if the mesh must be flagged as updatable
  2789. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2790. * @returns a new Mesh
  2791. */
  2792. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2793. throw _DevTools.WarnImport("MeshBuilder");
  2794. }
  2795. /**
  2796. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  2797. * @param name defines the name of the mesh to create
  2798. * @param radius sets the global radius size (float) of the torus knot (default 2)
  2799. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  2800. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  2801. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  2802. * @param p the number of windings on X axis (positive integers, default 2)
  2803. * @param q the number of windings on Y axis (positive integers, default 3)
  2804. * @param scene defines the hosting scene
  2805. * @param updatable defines if the mesh must be flagged as updatable
  2806. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2807. * @returns a new Mesh
  2808. */
  2809. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2810. throw _DevTools.WarnImport("MeshBuilder");
  2811. }
  2812. /**
  2813. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  2814. * @param name defines the name of the mesh to create
  2815. * @param points is an array successive Vector3
  2816. * @param scene defines the hosting scene
  2817. * @param updatable defines if the mesh must be flagged as updatable
  2818. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
  2819. * @returns a new Mesh
  2820. */
  2821. public static CreateLines(name: string, points: Vector3[], scene: Nullable<Scene> = null, updatable: boolean = false, instance: Nullable<LinesMesh> = null): LinesMesh {
  2822. throw _DevTools.WarnImport("MeshBuilder");
  2823. }
  2824. /**
  2825. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  2826. * @param name defines the name of the mesh to create
  2827. * @param points is an array successive Vector3
  2828. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  2829. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  2830. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  2831. * @param scene defines the hosting scene
  2832. * @param updatable defines if the mesh must be flagged as updatable
  2833. * @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
  2834. * @returns a new Mesh
  2835. */
  2836. public static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Nullable<Scene> = null, updatable?: boolean, instance?: LinesMesh): LinesMesh {
  2837. throw _DevTools.WarnImport("MeshBuilder");
  2838. }
  2839. /**
  2840. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  2841. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  2842. * 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.
  2843. * You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
  2844. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  2845. * Remember you can only change the shape positions, not their number when updating a polygon.
  2846. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  2847. * @param name defines the name of the mesh to create
  2848. * @param 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
  2849. * @param scene defines the hosting scene
  2850. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  2851. * @param updatable defines if the mesh must be flagged as updatable
  2852. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2853. * @param earcutInjection can be used to inject your own earcut reference
  2854. * @returns a new Mesh
  2855. */
  2856. public static CreatePolygon(name: string, shape: Vector3[], scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number, earcutInjection = earcut): Mesh {
  2857. throw _DevTools.WarnImport("MeshBuilder");
  2858. }
  2859. /**
  2860. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  2861. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  2862. * @param name defines the name of the mesh to create
  2863. * @param 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
  2864. * @param depth defines the height of extrusion
  2865. * @param scene defines the hosting scene
  2866. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  2867. * @param updatable defines if the mesh must be flagged as updatable
  2868. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2869. * @param earcutInjection can be used to inject your own earcut reference
  2870. * @returns a new Mesh
  2871. */
  2872. public static ExtrudePolygon(name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number, earcutInjection = earcut): Mesh {
  2873. throw _DevTools.WarnImport("MeshBuilder");
  2874. }
  2875. /**
  2876. * Creates an extruded shape mesh.
  2877. * The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
  2878. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  2879. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  2880. * @param name defines the name of the mesh to create
  2881. * @param 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 extruded along the Z axis
  2882. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  2883. * @param scale is the value to scale the shape
  2884. * @param rotation 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
  2885. * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
  2886. * @param scene defines the hosting scene
  2887. * @param updatable defines if the mesh must be flagged as updatable
  2888. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2889. * @param 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/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
  2890. * @returns a new Mesh
  2891. */
  2892. 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 {
  2893. throw _DevTools.WarnImport("MeshBuilder");
  2894. }
  2895. /**
  2896. * Creates an custom extruded shape mesh.
  2897. * The custom extrusion is a parametric shape.
  2898. * It has no predefined shape. Its final shape will depend on the input parameters.
  2899. * Please consider using the same method from the MeshBuilder class instead
  2900. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  2901. * @param name defines the name of the mesh to create
  2902. * @param 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 extruded along the Z axis
  2903. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  2904. * @param scaleFunction is a custom Javascript function called on each path point
  2905. * @param rotationFunction is a custom Javascript function called on each path point
  2906. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  2907. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  2908. * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
  2909. * @param scene defines the hosting scene
  2910. * @param updatable defines if the mesh must be flagged as updatable
  2911. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2912. * @param 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/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
  2913. * @returns a new Mesh
  2914. */
  2915. 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 {
  2916. throw _DevTools.WarnImport("MeshBuilder");
  2917. }
  2918. /**
  2919. * Creates lathe mesh.
  2920. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  2921. * Please consider using the same method from the MeshBuilder class instead
  2922. * @param name defines the name of the mesh to create
  2923. * @param 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 rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
  2924. * @param radius is the radius value of the lathe
  2925. * @param tessellation is the side number of the lathe.
  2926. * @param scene defines the hosting scene
  2927. * @param updatable defines if the mesh must be flagged as updatable
  2928. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2929. * @returns a new Mesh
  2930. */
  2931. public static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2932. throw _DevTools.WarnImport("MeshBuilder");
  2933. }
  2934. /**
  2935. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  2936. * @param name defines the name of the mesh to create
  2937. * @param size sets the size (float) of both sides of the plane at once (default 1)
  2938. * @param scene defines the hosting scene
  2939. * @param updatable defines if the mesh must be flagged as updatable
  2940. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  2941. * @returns a new Mesh
  2942. */
  2943. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh {
  2944. throw _DevTools.WarnImport("MeshBuilder");
  2945. }
  2946. /**
  2947. * Creates a ground mesh.
  2948. * Please consider using the same method from the MeshBuilder class instead
  2949. * @param name defines the name of the mesh to create
  2950. * @param width set the width of the ground
  2951. * @param height set the height of the ground
  2952. * @param subdivisions sets the number of subdivisions per side
  2953. * @param scene defines the hosting scene
  2954. * @param updatable defines if the mesh must be flagged as updatable
  2955. * @returns a new Mesh
  2956. */
  2957. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene?: Scene, updatable?: boolean): Mesh {
  2958. throw _DevTools.WarnImport("MeshBuilder");
  2959. }
  2960. /**
  2961. * Creates a tiled ground mesh.
  2962. * Please consider using the same method from the MeshBuilder class instead
  2963. * @param name defines the name of the mesh to create
  2964. * @param xmin set the ground minimum X coordinate
  2965. * @param zmin set the ground minimum Y coordinate
  2966. * @param xmax set the ground maximum X coordinate
  2967. * @param zmax set the ground maximum Z coordinate
  2968. * @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
  2969. * @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
  2970. * @param scene defines the hosting scene
  2971. * @param updatable defines if the mesh must be flagged as updatable
  2972. * @returns a new Mesh
  2973. */
  2974. 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 {
  2975. throw _DevTools.WarnImport("MeshBuilder");
  2976. }
  2977. /**
  2978. * Creates a ground mesh from a height map.
  2979. * Please consider using the same method from the MeshBuilder class instead
  2980. * @see http://doc.babylonjs.com/babylon101/height_map
  2981. * @param name defines the name of the mesh to create
  2982. * @param url sets the URL of the height map image resource
  2983. * @param width set the ground width size
  2984. * @param height set the ground height size
  2985. * @param subdivisions sets the number of subdivision per side
  2986. * @param minHeight is the minimum altitude on the ground
  2987. * @param maxHeight is the maximum altitude on the ground
  2988. * @param scene defines the hosting scene
  2989. * @param updatable defines if the mesh must be flagged as updatable
  2990. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  2991. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  2992. * @returns a new Mesh
  2993. */
  2994. 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, alphaFilter?: number): GroundMesh {
  2995. throw _DevTools.WarnImport("MeshBuilder");
  2996. }
  2997. /**
  2998. * Creates a tube mesh.
  2999. * The tube is a parametric shape.
  3000. * It has no predefined shape. Its final shape will depend on the input parameters.
  3001. * Please consider using the same method from the MeshBuilder class instead
  3002. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  3003. * @param name defines the name of the mesh to create
  3004. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  3005. * @param radius sets the tube radius size
  3006. * @param tessellation is the number of sides on the tubular surface
  3007. * @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. 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
  3008. * @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
  3009. * @param scene defines the hosting scene
  3010. * @param updatable defines if the mesh must be flagged as updatable
  3011. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  3012. * @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
  3013. * @returns a new Mesh
  3014. */
  3015. 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 {
  3016. throw _DevTools.WarnImport("MeshBuilder");
  3017. }
  3018. /**
  3019. * Creates a polyhedron mesh.
  3020. * Please consider using the same method from the MeshBuilder class instead.
  3021. * * 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 to choose the wanted type
  3022. * * The parameter `size` (positive float, default 1) sets the polygon size
  3023. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  3024. * * 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`
  3025. * * 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
  3026. * * 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)`)
  3027. * * 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 : https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors
  3028. * * 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
  3029. * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
  3030. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  3031. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  3032. * @param name defines the name of the mesh to create
  3033. * @param options defines the options used to create the mesh
  3034. * @param scene defines the hosting scene
  3035. * @returns a new Mesh
  3036. */
  3037. 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 {
  3038. throw _DevTools.WarnImport("MeshBuilder");
  3039. }
  3040. /**
  3041. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  3042. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  3043. * * 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`)
  3044. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  3045. * * 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
  3046. * * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
  3047. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  3048. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  3049. * @param name defines the name of the mesh
  3050. * @param options defines the options used to create the mesh
  3051. * @param scene defines the hosting scene
  3052. * @returns a new Mesh
  3053. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  3054. */
  3055. public static CreateIcoSphere(name: string, options: { radius?: number, flat?: boolean, subdivisions?: number, sideOrientation?: number, updatable?: boolean }, scene: Scene): Mesh {
  3056. throw _DevTools.WarnImport("MeshBuilder");
  3057. }
  3058. /**
  3059. * Creates a decal mesh.
  3060. * Please consider using the same method from the MeshBuilder class instead.
  3061. * A decal is a mesh usually applied as a model onto the surface of another mesh
  3062. * @param name defines the name of the mesh
  3063. * @param sourceMesh defines the mesh receiving the decal
  3064. * @param position sets the position of the decal in world coordinates
  3065. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  3066. * @param size sets the decal scaling
  3067. * @param angle sets the angle to rotate the decal
  3068. * @returns a new Mesh
  3069. */
  3070. public static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh {
  3071. throw _DevTools.WarnImport("MeshBuilder");
  3072. }
  3073. // Skeletons
  3074. /**
  3075. * Prepare internal position array for software CPU skinning
  3076. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  3077. */
  3078. public setPositionsForCPUSkinning(): Float32Array {
  3079. if (!this._sourcePositions) {
  3080. let source = this.getVerticesData(VertexBuffer.PositionKind);
  3081. if (!source) {
  3082. return this._sourcePositions;
  3083. }
  3084. this._sourcePositions = new Float32Array(<any>source);
  3085. if (!this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
  3086. this.setVerticesData(VertexBuffer.PositionKind, source, true);
  3087. }
  3088. }
  3089. return this._sourcePositions;
  3090. }
  3091. /**
  3092. * Prepare internal normal array for software CPU skinning
  3093. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  3094. */
  3095. public setNormalsForCPUSkinning(): Float32Array {
  3096. if (!this._sourceNormals) {
  3097. let source = this.getVerticesData(VertexBuffer.NormalKind);
  3098. if (!source) {
  3099. return this._sourceNormals;
  3100. }
  3101. this._sourceNormals = new Float32Array(<any>source);
  3102. if (!this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
  3103. this.setVerticesData(VertexBuffer.NormalKind, source, true);
  3104. }
  3105. }
  3106. return this._sourceNormals;
  3107. }
  3108. /**
  3109. * Updates the vertex buffer by applying transformation from the bones
  3110. * @param skeleton defines the skeleton to apply to current mesh
  3111. * @returns the current mesh
  3112. */
  3113. public applySkeleton(skeleton: Skeleton): Mesh {
  3114. if (!this.geometry) {
  3115. return this;
  3116. }
  3117. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  3118. return this;
  3119. }
  3120. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  3121. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  3122. return this;
  3123. }
  3124. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  3125. return this;
  3126. }
  3127. if (!this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  3128. return this;
  3129. }
  3130. if (!this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  3131. return this;
  3132. }
  3133. if (!this._sourcePositions) {
  3134. var submeshes = this.subMeshes.slice();
  3135. this.setPositionsForCPUSkinning();
  3136. this.subMeshes = submeshes;
  3137. }
  3138. if (!this._sourceNormals) {
  3139. this.setNormalsForCPUSkinning();
  3140. }
  3141. // positionsData checks for not being Float32Array will only pass at most once
  3142. var positionsData = this.getVerticesData(VertexBuffer.PositionKind);
  3143. if (!positionsData) {
  3144. return this;
  3145. }
  3146. if (!(positionsData instanceof Float32Array)) {
  3147. positionsData = new Float32Array(positionsData);
  3148. }
  3149. // normalsData checks for not being Float32Array will only pass at most once
  3150. var normalsData = this.getVerticesData(VertexBuffer.NormalKind);
  3151. if (!normalsData) {
  3152. return this;
  3153. }
  3154. if (!(normalsData instanceof Float32Array)) {
  3155. normalsData = new Float32Array(normalsData);
  3156. }
  3157. var matricesIndicesData = this.getVerticesData(VertexBuffer.MatricesIndicesKind);
  3158. var matricesWeightsData = this.getVerticesData(VertexBuffer.MatricesWeightsKind);
  3159. if (!matricesWeightsData || !matricesIndicesData) {
  3160. return this;
  3161. }
  3162. var needExtras = this.numBoneInfluencers > 4;
  3163. var matricesIndicesExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesIndicesExtraKind) : null;
  3164. var matricesWeightsExtraData = needExtras ? this.getVerticesData(VertexBuffer.MatricesWeightsExtraKind) : null;
  3165. var skeletonMatrices = skeleton.getTransformMatrices(this);
  3166. var tempVector3 = Vector3.Zero();
  3167. var finalMatrix = new Matrix();
  3168. var tempMatrix = new Matrix();
  3169. var matWeightIdx = 0;
  3170. var inf: number;
  3171. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  3172. var weight: number;
  3173. for (inf = 0; inf < 4; inf++) {
  3174. weight = matricesWeightsData[matWeightIdx + inf];
  3175. if (weight > 0) {
  3176. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  3177. finalMatrix.addToSelf(tempMatrix);
  3178. }
  3179. }
  3180. if (needExtras) {
  3181. for (inf = 0; inf < 4; inf++) {
  3182. weight = matricesWeightsExtraData![matWeightIdx + inf];
  3183. if (weight > 0) {
  3184. Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData![matWeightIdx + inf] * 16), weight, tempMatrix);
  3185. finalMatrix.addToSelf(tempMatrix);
  3186. }
  3187. }
  3188. }
  3189. Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  3190. tempVector3.toArray(positionsData, index);
  3191. Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  3192. tempVector3.toArray(normalsData, index);
  3193. finalMatrix.reset();
  3194. }
  3195. this.updateVerticesData(VertexBuffer.PositionKind, positionsData);
  3196. this.updateVerticesData(VertexBuffer.NormalKind, normalsData);
  3197. return this;
  3198. }
  3199. // Tools
  3200. /**
  3201. * Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
  3202. * @param meshes defines the list of meshes to scan
  3203. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  3204. */
  3205. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  3206. var minVector: Nullable<Vector3> = null;
  3207. var maxVector: Nullable<Vector3> = null;
  3208. meshes.forEach(function(mesh) {
  3209. let boundingInfo = mesh.getBoundingInfo();
  3210. let boundingBox = boundingInfo.boundingBox;
  3211. if (!minVector || !maxVector) {
  3212. minVector = boundingBox.minimumWorld;
  3213. maxVector = boundingBox.maximumWorld;
  3214. } else {
  3215. minVector.minimizeInPlace(boundingBox.minimumWorld);
  3216. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  3217. }
  3218. });
  3219. if (!minVector || !maxVector) {
  3220. return {
  3221. min: Vector3.Zero(),
  3222. max: Vector3.Zero()
  3223. };
  3224. }
  3225. return {
  3226. min: minVector,
  3227. max: maxVector
  3228. };
  3229. }
  3230. /**
  3231. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  3232. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  3233. * @returns a vector3
  3234. */
  3235. public static Center(meshesOrMinMaxVector: { min: Vector3; max: Vector3 } | AbstractMesh[]): Vector3 {
  3236. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  3237. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  3238. }
  3239. /**
  3240. * Merge the array of meshes into a single mesh for performance reasons.
  3241. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  3242. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  3243. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  3244. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  3245. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  3246. * @param multiMultiMaterials when true (false default), subdivide mesh and accept multiple multi materials, ignores subdivideWithSubMeshes.
  3247. * @returns a new mesh
  3248. */
  3249. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean, meshSubclass?: Mesh, subdivideWithSubMeshes?: boolean, multiMultiMaterials?: boolean): Nullable<Mesh> {
  3250. var index: number;
  3251. if (!allow32BitsIndices) {
  3252. var totalVertices = 0;
  3253. // Counting vertices
  3254. for (index = 0; index < meshes.length; index++) {
  3255. if (meshes[index]) {
  3256. totalVertices += meshes[index].getTotalVertices();
  3257. if (totalVertices > 65536) {
  3258. Logger.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  3259. return null;
  3260. }
  3261. }
  3262. }
  3263. }
  3264. if (multiMultiMaterials) {
  3265. var newMultiMaterial: Nullable<MultiMaterial> = null;
  3266. var subIndex: number;
  3267. var matIndex: number;
  3268. subdivideWithSubMeshes = false;
  3269. }
  3270. var materialArray: Array<Material> = new Array<Material>();
  3271. var materialIndexArray: Array<number> = new Array<number>();
  3272. // Merge
  3273. var vertexData: Nullable<VertexData> = null;
  3274. var otherVertexData: VertexData;
  3275. var indiceArray: Array<number> = new Array<number>();
  3276. var source: Nullable<Mesh> = null;
  3277. for (index = 0; index < meshes.length; index++) {
  3278. if (meshes[index]) {
  3279. var mesh = meshes[index];
  3280. const wm = mesh.computeWorldMatrix(true);
  3281. otherVertexData = VertexData.ExtractFromMesh(mesh, true, true);
  3282. otherVertexData.transform(wm);
  3283. if (vertexData) {
  3284. vertexData.merge(otherVertexData, allow32BitsIndices);
  3285. } else {
  3286. vertexData = otherVertexData;
  3287. source = mesh;
  3288. }
  3289. if (subdivideWithSubMeshes) {
  3290. indiceArray.push(mesh.getTotalIndices());
  3291. }
  3292. if (multiMultiMaterials) {
  3293. if (mesh.material) {
  3294. var material = mesh.material;
  3295. if (material instanceof MultiMaterial) {
  3296. for (matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  3297. if (materialArray.indexOf(<Material>material.subMaterials[matIndex]) < 0) {
  3298. materialArray.push(<Material>material.subMaterials[matIndex]);
  3299. }
  3300. }
  3301. for (subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  3302. materialIndexArray.push(materialArray.indexOf(<Material>material.subMaterials[mesh.subMeshes[subIndex].materialIndex]));
  3303. indiceArray.push(mesh.subMeshes[subIndex].indexCount);
  3304. }
  3305. } else {
  3306. if (materialArray.indexOf(<Material>material) < 0) {
  3307. materialArray.push(<Material>material);
  3308. }
  3309. for (subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  3310. materialIndexArray.push(materialArray.indexOf(<Material>material));
  3311. indiceArray.push(mesh.subMeshes[subIndex].indexCount);
  3312. }
  3313. }
  3314. } else {
  3315. for (subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  3316. materialIndexArray.push(0);
  3317. indiceArray.push(mesh.subMeshes[subIndex].indexCount);
  3318. }
  3319. }
  3320. }
  3321. }
  3322. }
  3323. source = <Mesh>source;
  3324. if (!meshSubclass) {
  3325. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  3326. }
  3327. (<VertexData>vertexData).applyToMesh(meshSubclass);
  3328. // Setting properties
  3329. meshSubclass.checkCollisions = source.checkCollisions;
  3330. // Cleaning
  3331. if (disposeSource) {
  3332. for (index = 0; index < meshes.length; index++) {
  3333. if (meshes[index]) {
  3334. meshes[index].dispose();
  3335. }
  3336. }
  3337. }
  3338. // Subdivide
  3339. if (subdivideWithSubMeshes || multiMultiMaterials) {
  3340. //-- removal of global submesh
  3341. meshSubclass.releaseSubMeshes();
  3342. index = 0;
  3343. var offset = 0;
  3344. //-- apply subdivision according to index table
  3345. while (index < indiceArray.length) {
  3346. SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  3347. offset += indiceArray[index];
  3348. index++;
  3349. }
  3350. }
  3351. if (multiMultiMaterials) {
  3352. newMultiMaterial = new MultiMaterial(source.name + "_merged", source.getScene());
  3353. newMultiMaterial.subMaterials = materialArray;
  3354. for (subIndex = 0; subIndex < meshSubclass.subMeshes.length; subIndex++) {
  3355. meshSubclass.subMeshes[subIndex].materialIndex = materialIndexArray[subIndex];
  3356. }
  3357. meshSubclass.material = newMultiMaterial;
  3358. } else {
  3359. meshSubclass.material = source.material;
  3360. }
  3361. return meshSubclass;
  3362. }
  3363. /** @hidden */
  3364. public addInstance(instance: InstancedMesh) {
  3365. instance._indexInSourceMeshInstanceArray = this.instances.length;
  3366. this.instances.push(instance);
  3367. }
  3368. /** @hidden */
  3369. public removeInstance(instance: InstancedMesh) {
  3370. // Remove from mesh
  3371. const index = instance._indexInSourceMeshInstanceArray;
  3372. if (index != -1) {
  3373. if (index !== this.instances.length - 1) {
  3374. const last = this.instances[this.instances.length - 1];
  3375. this.instances[index] = last;
  3376. last._indexInSourceMeshInstanceArray = index;
  3377. }
  3378. instance._indexInSourceMeshInstanceArray = -1;
  3379. this.instances.pop();
  3380. }
  3381. }
  3382. }