babylon.mesh.ts 157 KB

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