mesh.ts 190 KB

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