mesh.ts 189 KB

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