babylon.mesh.ts 157 KB

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