mesh.ts 192 KB

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