geometry.ts 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  1. import { Tools, Tags } from "Tools";
  2. import { Nullable, FloatArray, DataArray, IndicesArray } from "types";
  3. import { Scene } from "scene";
  4. import { Vector3, Vector2, Color4 } from "Math";
  5. import { Engine } from "Engine";
  6. import { Mesh, AbstractMesh, VertexBuffer, SubMesh, IGetSetVerticesData, VertexData } from "Mesh";
  7. import { Effect } from "Materials";
  8. import { SceneLoader } from "Loading";
  9. import { BoundingInfo } from "index";
  10. /**
  11. * Class used to store geometry data (vertex buffers + index buffer)
  12. */
  13. export class Geometry implements IGetSetVerticesData {
  14. // Members
  15. /**
  16. * Gets or sets the unique ID of the geometry
  17. */
  18. public id: string;
  19. /**
  20. * Gets the delay loading state of the geometry (none by default which means not delayed)
  21. */
  22. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  23. /**
  24. * Gets the file containing the data to load when running in delay load state
  25. */
  26. public delayLoadingFile: Nullable<string>;
  27. /**
  28. * Callback called when the geometry is updated
  29. */
  30. public onGeometryUpdated: (geometry: Geometry, kind?: string) => void;
  31. // Private
  32. private _scene: Scene;
  33. private _engine: Engine;
  34. private _meshes: Mesh[];
  35. private _totalVertices = 0;
  36. /** @hidden */
  37. public _indices: IndicesArray;
  38. /** @hidden */
  39. public _vertexBuffers: { [key: string]: VertexBuffer; };
  40. private _isDisposed = false;
  41. private _extend: { minimum: Vector3, maximum: Vector3 };
  42. private _boundingBias: Vector2;
  43. /** @hidden */
  44. public _delayInfo: Array<string>;
  45. private _indexBuffer: Nullable<WebGLBuffer>;
  46. private _indexBufferIsUpdatable = false;
  47. /** @hidden */
  48. public _boundingInfo: Nullable<BoundingInfo>;
  49. /** @hidden */
  50. public _delayLoadingFunction: Nullable<(any: any, geometry: Geometry) => void>;
  51. /** @hidden */
  52. public _softwareSkinningFrameId: number;
  53. private _vertexArrayObjects: { [key: string]: WebGLVertexArrayObject; };
  54. private _updatable: boolean;
  55. // Cache
  56. /** @hidden */
  57. public _positions: Nullable<Vector3[]>;
  58. /**
  59. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  60. */
  61. public get boundingBias(): Vector2 {
  62. return this._boundingBias;
  63. }
  64. /**
  65. * Gets or sets the Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  66. */
  67. public set boundingBias(value: Vector2) {
  68. if (this._boundingBias) {
  69. this._boundingBias.copyFrom(value);
  70. }
  71. else {
  72. this._boundingBias = value.clone();
  73. }
  74. this._updateBoundingInfo(true, null);
  75. }
  76. /**
  77. * Static function used to attach a new empty geometry to a mesh
  78. * @param mesh defines the mesh to attach the geometry to
  79. * @returns the new Geometry
  80. */
  81. public static CreateGeometryForMesh(mesh: Mesh): Geometry {
  82. let geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  83. geometry.applyToMesh(mesh);
  84. return geometry;
  85. }
  86. /**
  87. * Creates a new geometry
  88. * @param id defines the unique ID
  89. * @param scene defines the hosting scene
  90. * @param vertexData defines the VertexData used to get geometry data
  91. * @param updatable defines if geometry must be updatable (false by default)
  92. * @param mesh defines the mesh that will be associated with the geometry
  93. */
  94. constructor(id: string, scene: Scene, vertexData?: VertexData, updatable: boolean = false, mesh: Nullable<Mesh> = null) {
  95. this.id = id;
  96. this._engine = scene.getEngine();
  97. this._meshes = [];
  98. this._scene = scene;
  99. //Init vertex buffer cache
  100. this._vertexBuffers = {};
  101. this._indices = [];
  102. this._updatable = updatable;
  103. // vertexData
  104. if (vertexData) {
  105. this.setAllVerticesData(vertexData, updatable);
  106. }
  107. else {
  108. this._totalVertices = 0;
  109. this._indices = [];
  110. }
  111. if (this._engine.getCaps().vertexArrayObject) {
  112. this._vertexArrayObjects = {};
  113. }
  114. // applyToMesh
  115. if (mesh) {
  116. this.applyToMesh(mesh);
  117. mesh.computeWorldMatrix(true);
  118. }
  119. }
  120. /**
  121. * Gets the current extend of the geometry
  122. */
  123. public get extend(): { minimum: Vector3, maximum: Vector3 } {
  124. return this._extend;
  125. }
  126. /**
  127. * Gets the hosting scene
  128. * @returns the hosting Scene
  129. */
  130. public getScene(): Scene {
  131. return this._scene;
  132. }
  133. /**
  134. * Gets the hosting engine
  135. * @returns the hosting Engine
  136. */
  137. public getEngine(): Engine {
  138. return this._engine;
  139. }
  140. /**
  141. * Defines if the geometry is ready to use
  142. * @returns true if the geometry is ready to be used
  143. */
  144. public isReady(): boolean {
  145. return this.delayLoadState === Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === Engine.DELAYLOADSTATE_NONE;
  146. }
  147. /**
  148. * Gets a value indicating that the geometry should not be serialized
  149. */
  150. public get doNotSerialize(): boolean {
  151. for (var index = 0; index < this._meshes.length; index++) {
  152. if (!this._meshes[index].doNotSerialize) {
  153. return false;
  154. }
  155. }
  156. return true;
  157. }
  158. /** @hidden */
  159. public _rebuild(): void {
  160. if (this._vertexArrayObjects) {
  161. this._vertexArrayObjects = {};
  162. }
  163. // Index buffer
  164. if (this._meshes.length !== 0 && this._indices) {
  165. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  166. }
  167. // Vertex buffers
  168. for (var key in this._vertexBuffers) {
  169. let vertexBuffer = <VertexBuffer>this._vertexBuffers[key];
  170. vertexBuffer._rebuild();
  171. }
  172. }
  173. /**
  174. * Affects all geometry data in one call
  175. * @param vertexData defines the geometry data
  176. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  177. */
  178. public setAllVerticesData(vertexData: VertexData, updatable?: boolean): void {
  179. vertexData.applyToGeometry(this, updatable);
  180. this.notifyUpdate();
  181. }
  182. /**
  183. * Set specific vertex data
  184. * @param kind defines the data kind (Position, normal, etc...)
  185. * @param data defines the vertex data to use
  186. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  187. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  188. */
  189. public setVerticesData(kind: string, data: FloatArray, updatable: boolean = false, stride?: number): void {
  190. var buffer = new VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  191. this.setVerticesBuffer(buffer);
  192. }
  193. /**
  194. * Removes a specific vertex data
  195. * @param kind defines the data kind (Position, normal, etc...)
  196. */
  197. public removeVerticesData(kind: string) {
  198. if (this._vertexBuffers[kind]) {
  199. this._vertexBuffers[kind].dispose();
  200. delete this._vertexBuffers[kind];
  201. }
  202. }
  203. /**
  204. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  205. * @param buffer defines the vertex buffer to use
  206. * @param totalVertices defines the total number of vertices for position kind (could be null)
  207. */
  208. public setVerticesBuffer(buffer: VertexBuffer, totalVertices: Nullable<number> = null): void {
  209. var kind = buffer.getKind();
  210. if (this._vertexBuffers[kind]) {
  211. this._vertexBuffers[kind].dispose();
  212. }
  213. this._vertexBuffers[kind] = buffer;
  214. if (kind === VertexBuffer.PositionKind) {
  215. var data = <FloatArray>buffer.getData();
  216. if (totalVertices != null) {
  217. this._totalVertices = totalVertices;
  218. } else {
  219. if (data != null) {
  220. this._totalVertices = data.length / (buffer.byteStride / 4);
  221. }
  222. }
  223. this._updateExtend(data);
  224. this._resetPointsArrayCache();
  225. var meshes = this._meshes;
  226. var numOfMeshes = meshes.length;
  227. for (var index = 0; index < numOfMeshes; index++) {
  228. var mesh = meshes[index];
  229. mesh._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  230. mesh._createGlobalSubMesh(false);
  231. mesh.computeWorldMatrix(true);
  232. }
  233. }
  234. this.notifyUpdate(kind);
  235. if (this._vertexArrayObjects) {
  236. this._disposeVertexArrayObjects();
  237. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  238. }
  239. }
  240. /**
  241. * Update a specific vertex buffer
  242. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  243. * It will do nothing if the buffer is not updatable
  244. * @param kind defines the data kind (Position, normal, etc...)
  245. * @param data defines the data to use
  246. * @param offset defines the offset in the target buffer where to store the data
  247. * @param useBytes set to true if the offset is in bytes
  248. */
  249. public updateVerticesDataDirectly(kind: string, data: DataArray, offset: number, useBytes: boolean = false): void {
  250. var vertexBuffer = this.getVertexBuffer(kind);
  251. if (!vertexBuffer) {
  252. return;
  253. }
  254. vertexBuffer.updateDirectly(data, offset, useBytes);
  255. this.notifyUpdate(kind);
  256. }
  257. /**
  258. * Update a specific vertex buffer
  259. * This function will create a new buffer if the current one is not updatable
  260. * @param kind defines the data kind (Position, normal, etc...)
  261. * @param data defines the data to use
  262. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  263. */
  264. public updateVerticesData(kind: string, data: FloatArray, updateExtends: boolean = false): void {
  265. var vertexBuffer = this.getVertexBuffer(kind);
  266. if (!vertexBuffer) {
  267. return;
  268. }
  269. vertexBuffer.update(data);
  270. if (kind === VertexBuffer.PositionKind) {
  271. this._updateBoundingInfo(updateExtends, data);
  272. }
  273. this.notifyUpdate(kind);
  274. }
  275. private _updateBoundingInfo(updateExtends: boolean, data: Nullable<FloatArray>) {
  276. if (updateExtends) {
  277. this._updateExtend(data);
  278. }
  279. this._resetPointsArrayCache();
  280. if (updateExtends) {
  281. var meshes = this._meshes;
  282. for (const mesh of meshes) {
  283. if (mesh._boundingInfo) {
  284. mesh._boundingInfo.reConstruct(this._extend.minimum, this._extend.maximum);
  285. }
  286. else {
  287. mesh._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  288. }
  289. const subMeshes = mesh.subMeshes;
  290. for (const subMesh of subMeshes) {
  291. subMesh.refreshBoundingInfo();
  292. }
  293. }
  294. }
  295. }
  296. /** @hidden */
  297. public _bind(effect: Nullable<Effect>, indexToBind?: Nullable<WebGLBuffer>): void {
  298. if (!effect) {
  299. return;
  300. }
  301. if (indexToBind === undefined) {
  302. indexToBind = this._indexBuffer;
  303. }
  304. let vbs = this.getVertexBuffers();
  305. if (!vbs) {
  306. return;
  307. }
  308. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  309. this._engine.bindBuffers(vbs, indexToBind, effect);
  310. return;
  311. }
  312. // Using VAO
  313. if (!this._vertexArrayObjects[effect.key]) {
  314. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  315. }
  316. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  317. }
  318. /**
  319. * Gets total number of vertices
  320. * @returns the total number of vertices
  321. */
  322. public getTotalVertices(): number {
  323. if (!this.isReady()) {
  324. return 0;
  325. }
  326. return this._totalVertices;
  327. }
  328. /**
  329. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  330. * @param kind defines the data kind (Position, normal, etc...)
  331. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  332. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  333. * @returns a float array containing vertex data
  334. */
  335. public getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable<FloatArray> {
  336. const vertexBuffer = this.getVertexBuffer(kind);
  337. if (!vertexBuffer) {
  338. return null;
  339. }
  340. let data = vertexBuffer.getData();
  341. if (!data) {
  342. return null;
  343. }
  344. const tightlyPackedByteStride = vertexBuffer.getSize() * VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  345. const count = this._totalVertices * vertexBuffer.getSize();
  346. if (vertexBuffer.type !== VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  347. const copy : number[] = [];
  348. vertexBuffer.forEach(count, (value) => copy.push(value));
  349. return copy;
  350. }
  351. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  352. if (data instanceof Array) {
  353. const offset = vertexBuffer.byteOffset / 4;
  354. return Tools.Slice(data, offset, offset + count);
  355. }
  356. else if (data instanceof ArrayBuffer) {
  357. return new Float32Array(data, vertexBuffer.byteOffset, count);
  358. }
  359. else {
  360. const offset = data.byteOffset + vertexBuffer.byteOffset;
  361. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  362. let result = new Float32Array(count);
  363. let source = new Float32Array(data.buffer, offset, count);
  364. result.set(source);
  365. return result;
  366. }
  367. return new Float32Array(data.buffer, offset, count);
  368. }
  369. }
  370. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  371. return Tools.Slice(data);
  372. }
  373. return data;
  374. }
  375. /**
  376. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  377. * @param kind defines the data kind (Position, normal, etc...)
  378. * @returns true if the vertex buffer with the specified kind is updatable
  379. */
  380. public isVertexBufferUpdatable(kind: string): boolean {
  381. let vb = this._vertexBuffers[kind];
  382. if (!vb) {
  383. return false;
  384. }
  385. return vb.isUpdatable();
  386. }
  387. /**
  388. * Gets a specific vertex buffer
  389. * @param kind defines the data kind (Position, normal, etc...)
  390. * @returns a VertexBuffer
  391. */
  392. public getVertexBuffer(kind: string): Nullable<VertexBuffer> {
  393. if (!this.isReady()) {
  394. return null;
  395. }
  396. return this._vertexBuffers[kind];
  397. }
  398. /**
  399. * Returns all vertex buffers
  400. * @return an object holding all vertex buffers indexed by kind
  401. */
  402. public getVertexBuffers(): Nullable<{ [key: string]: VertexBuffer; }> {
  403. if (!this.isReady()) {
  404. return null;
  405. }
  406. return this._vertexBuffers;
  407. }
  408. /**
  409. * Gets a boolean indicating if specific vertex buffer is present
  410. * @param kind defines the data kind (Position, normal, etc...)
  411. * @returns true if data is present
  412. */
  413. public isVerticesDataPresent(kind: string): boolean {
  414. if (!this._vertexBuffers) {
  415. if (this._delayInfo) {
  416. return this._delayInfo.indexOf(kind) !== -1;
  417. }
  418. return false;
  419. }
  420. return this._vertexBuffers[kind] !== undefined;
  421. }
  422. /**
  423. * Gets a list of all attached data kinds (Position, normal, etc...)
  424. * @returns a list of string containing all kinds
  425. */
  426. public getVerticesDataKinds(): string[] {
  427. var result = [];
  428. var kind;
  429. if (!this._vertexBuffers && this._delayInfo) {
  430. for (kind in this._delayInfo) {
  431. result.push(kind);
  432. }
  433. } else {
  434. for (kind in this._vertexBuffers) {
  435. result.push(kind);
  436. }
  437. }
  438. return result;
  439. }
  440. /**
  441. * Update index buffer
  442. * @param indices defines the indices to store in the index buffer
  443. * @param offset defines the offset in the target buffer where to store the data
  444. */
  445. public updateIndices(indices: IndicesArray, offset?: number): void {
  446. if (!this._indexBuffer) {
  447. return;
  448. }
  449. if (!this._indexBufferIsUpdatable) {
  450. this.setIndices(indices, null, true);
  451. } else {
  452. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  453. }
  454. }
  455. /**
  456. * Creates a new index buffer
  457. * @param indices defines the indices to store in the index buffer
  458. * @param totalVertices defines the total number of vertices (could be null)
  459. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  460. */
  461. public setIndices(indices: IndicesArray, totalVertices: Nullable<number> = null, updatable: boolean = false): void {
  462. if (this._indexBuffer) {
  463. this._engine._releaseBuffer(this._indexBuffer);
  464. }
  465. this._disposeVertexArrayObjects();
  466. this._indices = indices;
  467. this._indexBufferIsUpdatable = updatable;
  468. if (this._meshes.length !== 0 && this._indices) {
  469. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  470. }
  471. if (totalVertices != undefined) { // including null and undefined
  472. this._totalVertices = totalVertices;
  473. }
  474. var meshes = this._meshes;
  475. var numOfMeshes = meshes.length;
  476. for (var index = 0; index < numOfMeshes; index++) {
  477. meshes[index]._createGlobalSubMesh(true);
  478. }
  479. this.notifyUpdate();
  480. }
  481. /**
  482. * Return the total number of indices
  483. * @returns the total number of indices
  484. */
  485. public getTotalIndices(): number {
  486. if (!this.isReady()) {
  487. return 0;
  488. }
  489. return this._indices.length;
  490. }
  491. /**
  492. * Gets the index buffer array
  493. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  494. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  495. * @returns the index buffer array
  496. */
  497. public getIndices(copyWhenShared?: boolean, forceCopy?: boolean): Nullable<IndicesArray> {
  498. if (!this.isReady()) {
  499. return null;
  500. }
  501. var orig = this._indices;
  502. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  503. return orig;
  504. } else {
  505. var len = orig.length;
  506. var copy = [];
  507. for (var i = 0; i < len; i++) {
  508. copy.push(orig[i]);
  509. }
  510. return copy;
  511. }
  512. }
  513. /**
  514. * Gets the index buffer
  515. * @return the index buffer
  516. */
  517. public getIndexBuffer(): Nullable<WebGLBuffer> {
  518. if (!this.isReady()) {
  519. return null;
  520. }
  521. return this._indexBuffer;
  522. }
  523. /** @hidden */
  524. public _releaseVertexArrayObject(effect: Nullable<Effect> = null) {
  525. if (!effect || !this._vertexArrayObjects) {
  526. return;
  527. }
  528. if (this._vertexArrayObjects[effect.key]) {
  529. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  530. delete this._vertexArrayObjects[effect.key];
  531. }
  532. }
  533. /**
  534. * Release the associated resources for a specific mesh
  535. * @param mesh defines the source mesh
  536. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  537. */
  538. public releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void {
  539. var meshes = this._meshes;
  540. var index = meshes.indexOf(mesh);
  541. if (index === -1) {
  542. return;
  543. }
  544. meshes.splice(index, 1);
  545. mesh._geometry = null;
  546. if (meshes.length === 0 && shouldDispose) {
  547. this.dispose();
  548. }
  549. }
  550. /**
  551. * Apply current geometry to a given mesh
  552. * @param mesh defines the mesh to apply geometry to
  553. */
  554. public applyToMesh(mesh: Mesh): void {
  555. if (mesh._geometry === this) {
  556. return;
  557. }
  558. var previousGeometry = mesh._geometry;
  559. if (previousGeometry) {
  560. previousGeometry.releaseForMesh(mesh);
  561. }
  562. var meshes = this._meshes;
  563. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  564. mesh._geometry = this;
  565. this._scene.pushGeometry(this);
  566. meshes.push(mesh);
  567. if (this.isReady()) {
  568. this._applyToMesh(mesh);
  569. }
  570. else {
  571. mesh._boundingInfo = this._boundingInfo;
  572. }
  573. }
  574. private _updateExtend(data: Nullable<FloatArray> = null) {
  575. if (!data) {
  576. data = this.getVerticesData(VertexBuffer.PositionKind)!;
  577. }
  578. this._extend = Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  579. }
  580. private _applyToMesh(mesh: Mesh): void {
  581. var numOfMeshes = this._meshes.length;
  582. // vertexBuffers
  583. for (var kind in this._vertexBuffers) {
  584. if (numOfMeshes === 1) {
  585. this._vertexBuffers[kind].create();
  586. }
  587. var buffer = this._vertexBuffers[kind].getBuffer();
  588. if (buffer) {
  589. buffer.references = numOfMeshes;
  590. }
  591. if (kind === VertexBuffer.PositionKind) {
  592. if (!this._extend) {
  593. this._updateExtend();
  594. }
  595. mesh._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  596. mesh._createGlobalSubMesh(false);
  597. //bounding info was just created again, world matrix should be applied again.
  598. mesh._updateBoundingInfo();
  599. }
  600. }
  601. // indexBuffer
  602. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  603. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  604. }
  605. if (this._indexBuffer) {
  606. this._indexBuffer.references = numOfMeshes;
  607. }
  608. // morphTargets
  609. mesh._syncGeometryWithMorphTargetManager();
  610. // instances
  611. mesh.synchronizeInstances();
  612. }
  613. private notifyUpdate(kind?: string) {
  614. if (this.onGeometryUpdated) {
  615. this.onGeometryUpdated(this, kind);
  616. }
  617. for (var mesh of this._meshes) {
  618. mesh._markSubMeshesAsAttributesDirty();
  619. }
  620. }
  621. /**
  622. * Load the geometry if it was flagged as delay loaded
  623. * @param scene defines the hosting scene
  624. * @param onLoaded defines a callback called when the geometry is loaded
  625. */
  626. public load(scene: Scene, onLoaded?: () => void): void {
  627. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  628. return;
  629. }
  630. if (this.isReady()) {
  631. if (onLoaded) {
  632. onLoaded();
  633. }
  634. return;
  635. }
  636. this.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  637. this._queueLoad(scene, onLoaded);
  638. }
  639. private _queueLoad(scene: Scene, onLoaded?: () => void): void {
  640. if (!this.delayLoadingFile) {
  641. return;
  642. }
  643. scene._addPendingData(this);
  644. scene._loadFile(this.delayLoadingFile, (data) => {
  645. if (!this._delayLoadingFunction) {
  646. return;
  647. }
  648. this._delayLoadingFunction(JSON.parse(data as string), this);
  649. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  650. this._delayInfo = [];
  651. scene._removePendingData(this);
  652. var meshes = this._meshes;
  653. var numOfMeshes = meshes.length;
  654. for (var index = 0; index < numOfMeshes; index++) {
  655. this._applyToMesh(meshes[index]);
  656. }
  657. if (onLoaded) {
  658. onLoaded();
  659. }
  660. }, undefined, true);
  661. }
  662. /**
  663. * Invert the geometry to move from a right handed system to a left handed one.
  664. */
  665. public toLeftHanded(): void {
  666. // Flip faces
  667. let tIndices = this.getIndices(false);
  668. if (tIndices != null && tIndices.length > 0) {
  669. for (let i = 0; i < tIndices.length; i += 3) {
  670. let tTemp = tIndices[i + 0];
  671. tIndices[i + 0] = tIndices[i + 2];
  672. tIndices[i + 2] = tTemp;
  673. }
  674. this.setIndices(tIndices);
  675. }
  676. // Negate position.z
  677. let tPositions = this.getVerticesData(VertexBuffer.PositionKind, false);
  678. if (tPositions != null && tPositions.length > 0) {
  679. for (let i = 0; i < tPositions.length; i += 3) {
  680. tPositions[i + 2] = -tPositions[i + 2];
  681. }
  682. this.setVerticesData(VertexBuffer.PositionKind, tPositions, false);
  683. }
  684. // Negate normal.z
  685. let tNormals = this.getVerticesData(VertexBuffer.NormalKind, false);
  686. if (tNormals != null && tNormals.length > 0) {
  687. for (let i = 0; i < tNormals.length; i += 3) {
  688. tNormals[i + 2] = -tNormals[i + 2];
  689. }
  690. this.setVerticesData(VertexBuffer.NormalKind, tNormals, false);
  691. }
  692. }
  693. // Cache
  694. /** @hidden */
  695. public _resetPointsArrayCache(): void {
  696. this._positions = null;
  697. }
  698. /** @hidden */
  699. public _generatePointsArray(): boolean {
  700. if (this._positions) {
  701. return true;
  702. }
  703. var data = this.getVerticesData(VertexBuffer.PositionKind);
  704. if (!data || data.length === 0) {
  705. return false;
  706. }
  707. this._positions = [];
  708. for (var index = 0; index < data.length; index += 3) {
  709. this._positions.push(Vector3.FromArray(data, index));
  710. }
  711. return true;
  712. }
  713. /**
  714. * Gets a value indicating if the geometry is disposed
  715. * @returns true if the geometry was disposed
  716. */
  717. public isDisposed(): boolean {
  718. return this._isDisposed;
  719. }
  720. private _disposeVertexArrayObjects(): void {
  721. if (this._vertexArrayObjects) {
  722. for (var kind in this._vertexArrayObjects) {
  723. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  724. }
  725. this._vertexArrayObjects = {};
  726. }
  727. }
  728. /**
  729. * Free all associated resources
  730. */
  731. public dispose(): void {
  732. var meshes = this._meshes;
  733. var numOfMeshes = meshes.length;
  734. var index: number;
  735. for (index = 0; index < numOfMeshes; index++) {
  736. this.releaseForMesh(meshes[index]);
  737. }
  738. this._meshes = [];
  739. this._disposeVertexArrayObjects();
  740. for (var kind in this._vertexBuffers) {
  741. this._vertexBuffers[kind].dispose();
  742. }
  743. this._vertexBuffers = {};
  744. this._totalVertices = 0;
  745. if (this._indexBuffer) {
  746. this._engine._releaseBuffer(this._indexBuffer);
  747. }
  748. this._indexBuffer = null;
  749. this._indices = [];
  750. this.delayLoadState = Engine.DELAYLOADSTATE_NONE;
  751. this.delayLoadingFile = null;
  752. this._delayLoadingFunction = null;
  753. this._delayInfo = [];
  754. this._boundingInfo = null;
  755. this._scene.removeGeometry(this);
  756. this._isDisposed = true;
  757. }
  758. /**
  759. * Clone the current geometry into a new geometry
  760. * @param id defines the unique ID of the new geometry
  761. * @returns a new geometry object
  762. */
  763. public copy(id: string): Geometry {
  764. var vertexData = new VertexData();
  765. vertexData.indices = [];
  766. var indices = this.getIndices();
  767. if (indices) {
  768. for (var index = 0; index < indices.length; index++) {
  769. (<number[]>vertexData.indices).push(indices[index]);
  770. }
  771. }
  772. var updatable = false;
  773. var stopChecking = false;
  774. var kind;
  775. for (kind in this._vertexBuffers) {
  776. // using slice() to make a copy of the array and not just reference it
  777. var data = this.getVerticesData(kind);
  778. if (data instanceof Float32Array) {
  779. vertexData.set(new Float32Array(<Float32Array>data), kind);
  780. } else {
  781. vertexData.set((<number[]>data).slice(0), kind);
  782. }
  783. if (!stopChecking) {
  784. let vb = this.getVertexBuffer(kind);
  785. if (vb) {
  786. updatable = vb.isUpdatable();
  787. stopChecking = !updatable;
  788. }
  789. }
  790. }
  791. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  792. geometry.delayLoadState = this.delayLoadState;
  793. geometry.delayLoadingFile = this.delayLoadingFile;
  794. geometry._delayLoadingFunction = this._delayLoadingFunction;
  795. for (kind in this._delayInfo) {
  796. geometry._delayInfo = geometry._delayInfo || [];
  797. geometry._delayInfo.push(kind);
  798. }
  799. // Bounding info
  800. geometry._boundingInfo = new BoundingInfo(this._extend.minimum, this._extend.maximum);
  801. return geometry;
  802. }
  803. /**
  804. * Serialize the current geometry info (and not the vertices data) into a JSON object
  805. * @return a JSON representation of the current geometry data (without the vertices data)
  806. */
  807. public serialize(): any {
  808. var serializationObject: any = {};
  809. serializationObject.id = this.id;
  810. serializationObject.updatable = this._updatable;
  811. if (Tags && Tags.HasTags(this)) {
  812. serializationObject.tags = Tags.GetTags(this);
  813. }
  814. return serializationObject;
  815. }
  816. private toNumberArray(origin: Nullable<Float32Array | IndicesArray>): number[] {
  817. if (Array.isArray(origin)) {
  818. return origin;
  819. } else {
  820. return Array.prototype.slice.call(origin);
  821. }
  822. }
  823. /**
  824. * Serialize all vertices data into a JSON oject
  825. * @returns a JSON representation of the current geometry data
  826. */
  827. public serializeVerticeData(): any {
  828. var serializationObject = this.serialize();
  829. if (this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  830. serializationObject.positions = this.toNumberArray(this.getVerticesData(VertexBuffer.PositionKind));
  831. if (this.isVertexBufferUpdatable(VertexBuffer.PositionKind)) {
  832. serializationObject.positions._updatable = true;
  833. }
  834. }
  835. if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  836. serializationObject.normals = this.toNumberArray(this.getVerticesData(VertexBuffer.NormalKind));
  837. if (this.isVertexBufferUpdatable(VertexBuffer.NormalKind)) {
  838. serializationObject.normals._updatable = true;
  839. }
  840. }
  841. if (this.isVerticesDataPresent(VertexBuffer.TangentKind)) {
  842. serializationObject.tangets = this.toNumberArray(this.getVerticesData(VertexBuffer.TangentKind));
  843. if (this.isVertexBufferUpdatable(VertexBuffer.TangentKind)) {
  844. serializationObject.tangets._updatable = true;
  845. }
  846. }
  847. if (this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  848. serializationObject.uvs = this.toNumberArray(this.getVerticesData(VertexBuffer.UVKind));
  849. if (this.isVertexBufferUpdatable(VertexBuffer.UVKind)) {
  850. serializationObject.uvs._updatable = true;
  851. }
  852. }
  853. if (this.isVerticesDataPresent(VertexBuffer.UV2Kind)) {
  854. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV2Kind));
  855. if (this.isVertexBufferUpdatable(VertexBuffer.UV2Kind)) {
  856. serializationObject.uv2s._updatable = true;
  857. }
  858. }
  859. if (this.isVerticesDataPresent(VertexBuffer.UV3Kind)) {
  860. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV3Kind));
  861. if (this.isVertexBufferUpdatable(VertexBuffer.UV3Kind)) {
  862. serializationObject.uv3s._updatable = true;
  863. }
  864. }
  865. if (this.isVerticesDataPresent(VertexBuffer.UV4Kind)) {
  866. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV4Kind));
  867. if (this.isVertexBufferUpdatable(VertexBuffer.UV4Kind)) {
  868. serializationObject.uv4s._updatable = true;
  869. }
  870. }
  871. if (this.isVerticesDataPresent(VertexBuffer.UV5Kind)) {
  872. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV5Kind));
  873. if (this.isVertexBufferUpdatable(VertexBuffer.UV5Kind)) {
  874. serializationObject.uv5s._updatable = true;
  875. }
  876. }
  877. if (this.isVerticesDataPresent(VertexBuffer.UV6Kind)) {
  878. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(VertexBuffer.UV6Kind));
  879. if (this.isVertexBufferUpdatable(VertexBuffer.UV6Kind)) {
  880. serializationObject.uv6s._updatable = true;
  881. }
  882. }
  883. if (this.isVerticesDataPresent(VertexBuffer.ColorKind)) {
  884. serializationObject.colors = this.toNumberArray(this.getVerticesData(VertexBuffer.ColorKind));
  885. if (this.isVertexBufferUpdatable(VertexBuffer.ColorKind)) {
  886. serializationObject.colors._updatable = true;
  887. }
  888. }
  889. if (this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind)) {
  890. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(VertexBuffer.MatricesIndicesKind));
  891. serializationObject.matricesIndices._isExpanded = true;
  892. if (this.isVertexBufferUpdatable(VertexBuffer.MatricesIndicesKind)) {
  893. serializationObject.matricesIndices._updatable = true;
  894. }
  895. }
  896. if (this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)) {
  897. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(VertexBuffer.MatricesWeightsKind));
  898. if (this.isVertexBufferUpdatable(VertexBuffer.MatricesWeightsKind)) {
  899. serializationObject.matricesWeights._updatable = true;
  900. }
  901. }
  902. serializationObject.indices = this.toNumberArray(this.getIndices());
  903. return serializationObject;
  904. }
  905. // Statics
  906. /**
  907. * Extracts a clone of a mesh geometry
  908. * @param mesh defines the source mesh
  909. * @param id defines the unique ID of the new geometry object
  910. * @returns the new geometry object
  911. */
  912. public static ExtractFromMesh(mesh: Mesh, id: string): Nullable<Geometry> {
  913. var geometry = mesh._geometry;
  914. if (!geometry) {
  915. return null;
  916. }
  917. return geometry.copy(id);
  918. }
  919. /**
  920. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  921. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  922. * Be aware Math.random() could cause collisions, but:
  923. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  924. * @returns a string containing a new GUID
  925. */
  926. public static RandomId(): string {
  927. return Tools.RandomId();
  928. }
  929. /** @hidden */
  930. public static _ImportGeometry(parsedGeometry: any, mesh: Mesh): void {
  931. var scene = mesh.getScene();
  932. // Geometry
  933. var geometryId = parsedGeometry.geometryId;
  934. if (geometryId) {
  935. var geometry = scene.getGeometryByID(geometryId);
  936. if (geometry) {
  937. geometry.applyToMesh(mesh);
  938. }
  939. } else if (parsedGeometry instanceof ArrayBuffer) {
  940. var binaryInfo = mesh._binaryInfo;
  941. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  942. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  943. mesh.setVerticesData(VertexBuffer.PositionKind, positionsData, false);
  944. }
  945. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  946. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  947. mesh.setVerticesData(VertexBuffer.NormalKind, normalsData, false);
  948. }
  949. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  950. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  951. mesh.setVerticesData(VertexBuffer.TangentKind, tangentsData, false);
  952. }
  953. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  954. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  955. mesh.setVerticesData(VertexBuffer.UVKind, uvsData, false);
  956. }
  957. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  958. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  959. mesh.setVerticesData(VertexBuffer.UV2Kind, uvs2Data, false);
  960. }
  961. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  962. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  963. mesh.setVerticesData(VertexBuffer.UV3Kind, uvs3Data, false);
  964. }
  965. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  966. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  967. mesh.setVerticesData(VertexBuffer.UV4Kind, uvs4Data, false);
  968. }
  969. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  970. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  971. mesh.setVerticesData(VertexBuffer.UV5Kind, uvs5Data, false);
  972. }
  973. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  974. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  975. mesh.setVerticesData(VertexBuffer.UV6Kind, uvs6Data, false);
  976. }
  977. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  978. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  979. mesh.setVerticesData(VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  980. }
  981. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  982. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  983. var floatIndices = [];
  984. for (var i = 0; i < matricesIndicesData.length; i++) {
  985. var index = matricesIndicesData[i];
  986. floatIndices.push(index & 0x000000FF);
  987. floatIndices.push((index & 0x0000FF00) >> 8);
  988. floatIndices.push((index & 0x00FF0000) >> 16);
  989. floatIndices.push(index >> 24);
  990. }
  991. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, false);
  992. }
  993. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  994. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  995. mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  996. }
  997. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  998. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  999. mesh.setIndices(indicesData, null);
  1000. }
  1001. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  1002. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  1003. mesh.subMeshes = [];
  1004. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  1005. var materialIndex = subMeshesData[(i * 5) + 0];
  1006. var verticesStart = subMeshesData[(i * 5) + 1];
  1007. var verticesCount = subMeshesData[(i * 5) + 2];
  1008. var indexStart = subMeshesData[(i * 5) + 3];
  1009. var indexCount = subMeshesData[(i * 5) + 4];
  1010. SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, <AbstractMesh>mesh);
  1011. }
  1012. }
  1013. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  1014. mesh.setVerticesData(VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  1015. mesh.setVerticesData(VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  1016. if (parsedGeometry.tangents) {
  1017. mesh.setVerticesData(VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  1018. }
  1019. if (parsedGeometry.uvs) {
  1020. mesh.setVerticesData(VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  1021. }
  1022. if (parsedGeometry.uvs2) {
  1023. mesh.setVerticesData(VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  1024. }
  1025. if (parsedGeometry.uvs3) {
  1026. mesh.setVerticesData(VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  1027. }
  1028. if (parsedGeometry.uvs4) {
  1029. mesh.setVerticesData(VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  1030. }
  1031. if (parsedGeometry.uvs5) {
  1032. mesh.setVerticesData(VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  1033. }
  1034. if (parsedGeometry.uvs6) {
  1035. mesh.setVerticesData(VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  1036. }
  1037. if (parsedGeometry.colors) {
  1038. mesh.setVerticesData(VertexBuffer.ColorKind, Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  1039. }
  1040. if (parsedGeometry.matricesIndices) {
  1041. if (!parsedGeometry.matricesIndices._isExpanded) {
  1042. var floatIndices = [];
  1043. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  1044. var matricesIndex = parsedGeometry.matricesIndices[i];
  1045. floatIndices.push(matricesIndex & 0x000000FF);
  1046. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  1047. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  1048. floatIndices.push(matricesIndex >> 24);
  1049. }
  1050. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  1051. } else {
  1052. delete parsedGeometry.matricesIndices._isExpanded;
  1053. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  1054. }
  1055. }
  1056. if (parsedGeometry.matricesIndicesExtra) {
  1057. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  1058. var floatIndices = [];
  1059. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  1060. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  1061. floatIndices.push(matricesIndex & 0x000000FF);
  1062. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  1063. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  1064. floatIndices.push(matricesIndex >> 24);
  1065. }
  1066. mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  1067. } else {
  1068. delete parsedGeometry.matricesIndices._isExpanded;
  1069. mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  1070. }
  1071. }
  1072. if (parsedGeometry.matricesWeights) {
  1073. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  1074. mesh.setVerticesData(VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  1075. }
  1076. if (parsedGeometry.matricesWeightsExtra) {
  1077. mesh.setVerticesData(VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  1078. }
  1079. mesh.setIndices(parsedGeometry.indices, null);
  1080. }
  1081. // SubMeshes
  1082. if (parsedGeometry.subMeshes) {
  1083. mesh.subMeshes = [];
  1084. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  1085. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  1086. SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, <AbstractMesh>mesh);
  1087. }
  1088. }
  1089. // Flat shading
  1090. if (mesh._shouldGenerateFlatShading) {
  1091. mesh.convertToFlatShadedMesh();
  1092. delete mesh._shouldGenerateFlatShading;
  1093. }
  1094. // Update
  1095. mesh.computeWorldMatrix(true);
  1096. scene.onMeshImportedObservable.notifyObservers(<AbstractMesh>mesh);
  1097. }
  1098. private static _CleanMatricesWeights(parsedGeometry: any, mesh: Mesh): void {
  1099. const epsilon: number = 1e-3;
  1100. if (!SceneLoader.CleanBoneMatrixWeights) {
  1101. return;
  1102. }
  1103. let noInfluenceBoneIndex = 0.0;
  1104. if (parsedGeometry.skeletonId > -1) {
  1105. let skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  1106. if (!skeleton) {
  1107. return;
  1108. }
  1109. noInfluenceBoneIndex = skeleton.bones.length;
  1110. } else {
  1111. return;
  1112. }
  1113. let matricesIndices = (<FloatArray>mesh.getVerticesData(VertexBuffer.MatricesIndicesKind));
  1114. let matricesIndicesExtra = (<FloatArray>mesh.getVerticesData(VertexBuffer.MatricesIndicesExtraKind));
  1115. let matricesWeights = parsedGeometry.matricesWeights;
  1116. let matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  1117. let influencers = parsedGeometry.numBoneInfluencer;
  1118. let size = matricesWeights.length;
  1119. for (var i = 0; i < size; i += 4) {
  1120. let weight = 0.0;
  1121. let firstZeroWeight = -1;
  1122. for (var j = 0; j < 4; j++) {
  1123. let w = matricesWeights[i + j];
  1124. weight += w;
  1125. if (w < epsilon && firstZeroWeight < 0) {
  1126. firstZeroWeight = j;
  1127. }
  1128. }
  1129. if (matricesWeightsExtra) {
  1130. for (var j = 0; j < 4; j++) {
  1131. let w = matricesWeightsExtra[i + j];
  1132. weight += w;
  1133. if (w < epsilon && firstZeroWeight < 0) {
  1134. firstZeroWeight = j + 4;
  1135. }
  1136. }
  1137. }
  1138. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  1139. firstZeroWeight = influencers - 1;
  1140. }
  1141. if (weight > epsilon) {
  1142. let mweight = 1.0 / weight;
  1143. for (var j = 0; j < 4; j++) {
  1144. matricesWeights[i + j] *= mweight;
  1145. }
  1146. if (matricesWeightsExtra) {
  1147. for (var j = 0; j < 4; j++) {
  1148. matricesWeightsExtra[i + j] *= mweight;
  1149. }
  1150. }
  1151. } else {
  1152. if (firstZeroWeight >= 4) {
  1153. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  1154. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  1155. } else {
  1156. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  1157. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  1158. }
  1159. }
  1160. }
  1161. mesh.setVerticesData(VertexBuffer.MatricesIndicesKind, matricesIndices);
  1162. if (parsedGeometry.matricesWeightsExtra) {
  1163. mesh.setVerticesData(VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  1164. }
  1165. }
  1166. /**
  1167. * Create a new geometry from persisted data (Using .babylon file format)
  1168. * @param parsedVertexData defines the persisted data
  1169. * @param scene defines the hosting scene
  1170. * @param rootUrl defines the root url to use to load assets (like delayed data)
  1171. * @returns the new geometry object
  1172. */
  1173. public static Parse(parsedVertexData: any, scene: Scene, rootUrl: string): Nullable<Geometry> {
  1174. if (scene.getGeometryByID(parsedVertexData.id)) {
  1175. return null; // null since geometry could be something else than a box...
  1176. }
  1177. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  1178. if (Tags) {
  1179. Tags.AddTagsTo(geometry, parsedVertexData.tags);
  1180. }
  1181. if (parsedVertexData.delayLoadingFile) {
  1182. geometry.delayLoadState = Engine.DELAYLOADSTATE_NOTLOADED;
  1183. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  1184. geometry._boundingInfo = new BoundingInfo(Vector3.FromArray(parsedVertexData.boundingBoxMinimum), Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  1185. geometry._delayInfo = [];
  1186. if (parsedVertexData.hasUVs) {
  1187. geometry._delayInfo.push(VertexBuffer.UVKind);
  1188. }
  1189. if (parsedVertexData.hasUVs2) {
  1190. geometry._delayInfo.push(VertexBuffer.UV2Kind);
  1191. }
  1192. if (parsedVertexData.hasUVs3) {
  1193. geometry._delayInfo.push(VertexBuffer.UV3Kind);
  1194. }
  1195. if (parsedVertexData.hasUVs4) {
  1196. geometry._delayInfo.push(VertexBuffer.UV4Kind);
  1197. }
  1198. if (parsedVertexData.hasUVs5) {
  1199. geometry._delayInfo.push(VertexBuffer.UV5Kind);
  1200. }
  1201. if (parsedVertexData.hasUVs6) {
  1202. geometry._delayInfo.push(VertexBuffer.UV6Kind);
  1203. }
  1204. if (parsedVertexData.hasColors) {
  1205. geometry._delayInfo.push(VertexBuffer.ColorKind);
  1206. }
  1207. if (parsedVertexData.hasMatricesIndices) {
  1208. geometry._delayInfo.push(VertexBuffer.MatricesIndicesKind);
  1209. }
  1210. if (parsedVertexData.hasMatricesWeights) {
  1211. geometry._delayInfo.push(VertexBuffer.MatricesWeightsKind);
  1212. }
  1213. geometry._delayLoadingFunction = VertexData.ImportVertexData;
  1214. } else {
  1215. VertexData.ImportVertexData(parsedVertexData, geometry);
  1216. }
  1217. scene.pushGeometry(geometry, true);
  1218. return geometry;
  1219. }
  1220. }
  1221. // Primitives
  1222. /// Abstract class
  1223. /**
  1224. * Abstract class used to provide common services for all typed geometries
  1225. * @hidden
  1226. */
  1227. export class _PrimitiveGeometry extends Geometry {
  1228. private _beingRegenerated: boolean;
  1229. /**
  1230. * Creates a new typed geometry
  1231. * @param id defines the unique ID of the geometry
  1232. * @param scene defines the hosting scene
  1233. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1234. * @param mesh defines the hosting mesh (can be null)
  1235. */
  1236. constructor(id: string, scene: Scene, private _canBeRegenerated: boolean = false, mesh: Nullable<Mesh> = null) {
  1237. super(id, scene, undefined, false, mesh); // updatable = false to be sure not to update vertices
  1238. this._beingRegenerated = true;
  1239. this.regenerate();
  1240. this._beingRegenerated = false;
  1241. }
  1242. /**
  1243. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  1244. * @returns true if the geometry can be regenerated
  1245. */
  1246. public canBeRegenerated(): boolean {
  1247. return this._canBeRegenerated;
  1248. }
  1249. /**
  1250. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  1251. */
  1252. public regenerate(): void {
  1253. if (!this._canBeRegenerated) {
  1254. return;
  1255. }
  1256. this._beingRegenerated = true;
  1257. this.setAllVerticesData(this._regenerateVertexData(), false);
  1258. this._beingRegenerated = false;
  1259. }
  1260. /**
  1261. * Clone the geometry
  1262. * @param id defines the unique ID of the new geometry
  1263. * @returns the new geometry
  1264. */
  1265. public asNewGeometry(id: string): Geometry {
  1266. return super.copy(id);
  1267. }
  1268. // overrides
  1269. public setAllVerticesData(vertexData: VertexData, updatable?: boolean): void {
  1270. if (!this._beingRegenerated) {
  1271. return;
  1272. }
  1273. super.setAllVerticesData(vertexData, false);
  1274. }
  1275. public setVerticesData(kind: string, data: FloatArray, updatable?: boolean): void {
  1276. if (!this._beingRegenerated) {
  1277. return;
  1278. }
  1279. super.setVerticesData(kind, data, false);
  1280. }
  1281. // to override
  1282. /** @hidden */
  1283. public _regenerateVertexData(): VertexData {
  1284. throw new Error("Abstract method");
  1285. }
  1286. public copy(id: string): Geometry {
  1287. throw new Error("Must be overriden in sub-classes.");
  1288. }
  1289. public serialize(): any {
  1290. var serializationObject = super.serialize();
  1291. serializationObject.canBeRegenerated = this.canBeRegenerated();
  1292. return serializationObject;
  1293. }
  1294. }
  1295. /**
  1296. * Creates a ribbon geometry
  1297. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  1298. */
  1299. export class RibbonGeometry extends _PrimitiveGeometry {
  1300. /**
  1301. * Creates a ribbon geometry
  1302. * @param id defines the unique ID of the geometry
  1303. * @param scene defines the hosting scene
  1304. * @param pathArray defines the array of paths to use
  1305. * @param closeArray defines if the last path and the first path must be joined
  1306. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  1307. * @param offset defines the offset between points
  1308. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1309. * @param mesh defines the hosting mesh (can be null)
  1310. * @param side defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1311. */
  1312. constructor(
  1313. id: string, scene: Scene,
  1314. /**
  1315. * Defines the array of paths to use
  1316. */
  1317. public pathArray: Vector3[][],
  1318. /**
  1319. * Defines if the last and first points of each path in your pathArray must be joined
  1320. */
  1321. public closeArray: boolean,
  1322. /**
  1323. * Defines if the last and first points of each path in your pathArray must be joined
  1324. */
  1325. public closePath: boolean,
  1326. /**
  1327. * Defines the offset between points
  1328. */
  1329. public offset: number,
  1330. canBeRegenerated?: boolean,
  1331. mesh?: Mesh,
  1332. /**
  1333. * Defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1334. */
  1335. public side: number = Mesh.DEFAULTSIDE) {
  1336. super(id, scene, canBeRegenerated, mesh);
  1337. }
  1338. /** @hidden */
  1339. public _regenerateVertexData(): VertexData {
  1340. return VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  1341. }
  1342. public copy(id: string): Geometry {
  1343. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  1344. }
  1345. }
  1346. /**
  1347. * Creates a box geometry
  1348. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  1349. */
  1350. export class BoxGeometry extends _PrimitiveGeometry {
  1351. /**
  1352. * Creates a box geometry
  1353. * @param id defines the unique ID of the geometry
  1354. * @param scene defines the hosting scene
  1355. * @param size defines the zise of the box (width, height and depth are the same)
  1356. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1357. * @param mesh defines the hosting mesh (can be null)
  1358. * @param side defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1359. */
  1360. constructor(
  1361. id: string, scene: Scene,
  1362. /**
  1363. * Defines the zise of the box (width, height and depth are the same)
  1364. */
  1365. public size: number,
  1366. canBeRegenerated?: boolean,
  1367. mesh: Nullable<Mesh> = null,
  1368. /**
  1369. * Defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1370. */
  1371. public side: number = Mesh.DEFAULTSIDE) {
  1372. super(id, scene, canBeRegenerated, mesh);
  1373. }
  1374. /** @hidden */
  1375. public _regenerateVertexData(): VertexData {
  1376. return VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  1377. }
  1378. public copy(id: string): Geometry {
  1379. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  1380. }
  1381. public serialize(): any {
  1382. var serializationObject = super.serialize();
  1383. serializationObject.size = this.size;
  1384. return serializationObject;
  1385. }
  1386. public static Parse(parsedBox: any, scene: Scene): Nullable<BoxGeometry> {
  1387. if (scene.getGeometryByID(parsedBox.id)) {
  1388. return null; // null since geometry could be something else than a box...
  1389. }
  1390. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  1391. if (Tags) {
  1392. Tags.AddTagsTo(box, parsedBox.tags);
  1393. }
  1394. scene.pushGeometry(box, true);
  1395. return box;
  1396. }
  1397. }
  1398. /**
  1399. * Creates a sphere geometry
  1400. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  1401. */
  1402. export class SphereGeometry extends _PrimitiveGeometry {
  1403. /**
  1404. * Create a new sphere geometry
  1405. * @param id defines the unique ID of the geometry
  1406. * @param scene defines the hosting scene
  1407. * @param segments defines the number of segments to use to create the sphere
  1408. * @param diameter defines the diameter of the sphere
  1409. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1410. * @param mesh defines the hosting mesh (can be null)
  1411. * @param side defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1412. */
  1413. constructor(
  1414. id: string, scene: Scene,
  1415. /**
  1416. * Defines the number of segments to use to create the sphere
  1417. */
  1418. public segments: number,
  1419. /**
  1420. * Defines the diameter of the sphere
  1421. */
  1422. public diameter: number,
  1423. canBeRegenerated?: boolean,
  1424. mesh: Nullable<Mesh> = null,
  1425. /**
  1426. * Defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1427. */
  1428. public side: number = Mesh.DEFAULTSIDE) {
  1429. super(id, scene, canBeRegenerated, mesh);
  1430. }
  1431. /** @hidden */
  1432. public _regenerateVertexData(): VertexData {
  1433. return VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  1434. }
  1435. public copy(id: string): Geometry {
  1436. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  1437. }
  1438. public serialize(): any {
  1439. var serializationObject = super.serialize();
  1440. serializationObject.segments = this.segments;
  1441. serializationObject.diameter = this.diameter;
  1442. return serializationObject;
  1443. }
  1444. public static Parse(parsedSphere: any, scene: Scene): Nullable<SphereGeometry> {
  1445. if (scene.getGeometryByID(parsedSphere.id)) {
  1446. return null; // null since geometry could be something else than a sphere...
  1447. }
  1448. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  1449. if (Tags) {
  1450. Tags.AddTagsTo(sphere, parsedSphere.tags);
  1451. }
  1452. scene.pushGeometry(sphere, true);
  1453. return sphere;
  1454. }
  1455. }
  1456. /**
  1457. * Creates a disc geometry
  1458. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  1459. */
  1460. export class DiscGeometry extends _PrimitiveGeometry {
  1461. /**
  1462. * Creates a new disc geometry
  1463. * @param id defines the unique ID of the geometry
  1464. * @param scene defines the hosting scene
  1465. * @param radius defines the radius of the disc
  1466. * @param tessellation defines the tesselation factor to apply to the disc
  1467. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1468. * @param mesh defines the hosting mesh (can be null)
  1469. * @param side defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1470. */
  1471. constructor(
  1472. id: string, scene: Scene,
  1473. /**
  1474. * Defines the radius of the disc
  1475. */
  1476. public radius: number,
  1477. /**
  1478. * Defines the tesselation factor to apply to the disc
  1479. */
  1480. public tessellation: number,
  1481. canBeRegenerated?: boolean,
  1482. mesh: Nullable<Mesh> = null,
  1483. /**
  1484. * Defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1485. */
  1486. public side: number = Mesh.DEFAULTSIDE) {
  1487. super(id, scene, canBeRegenerated, mesh);
  1488. }
  1489. /** @hidden */
  1490. public _regenerateVertexData(): VertexData {
  1491. return VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  1492. }
  1493. public copy(id: string): Geometry {
  1494. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  1495. }
  1496. }
  1497. /**
  1498. * Creates a new cylinder geometry
  1499. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  1500. */
  1501. export class CylinderGeometry extends _PrimitiveGeometry {
  1502. /**
  1503. * Creates a new cylinder geometry
  1504. * @param id defines the unique ID of the geometry
  1505. * @param scene defines the hosting scene
  1506. * @param height defines the height of the cylinder
  1507. * @param diameterTop defines the diameter of the cylinder's top cap
  1508. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  1509. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  1510. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  1511. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1512. * @param mesh defines the hosting mesh (can be null)
  1513. * @param side defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1514. */
  1515. constructor(
  1516. id: string, scene: Scene,
  1517. /**
  1518. * Defines the height of the cylinder
  1519. */
  1520. public height: number,
  1521. /**
  1522. * Defines the diameter of the cylinder's top cap
  1523. */
  1524. public diameterTop: number,
  1525. /**
  1526. * Defines the diameter of the cylinder's bottom cap
  1527. */
  1528. public diameterBottom: number,
  1529. /**
  1530. * Defines the tessellation factor to apply to the cylinder
  1531. */
  1532. public tessellation: number,
  1533. /**
  1534. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  1535. */
  1536. public subdivisions: number = 1,
  1537. canBeRegenerated?: boolean, mesh:
  1538. Nullable<Mesh> = null,
  1539. /**
  1540. * Defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1541. */
  1542. public side: number = Mesh.DEFAULTSIDE) {
  1543. super(id, scene, canBeRegenerated, mesh);
  1544. }
  1545. /** @hidden */
  1546. public _regenerateVertexData(): VertexData {
  1547. return VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  1548. }
  1549. public copy(id: string): Geometry {
  1550. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  1551. }
  1552. public serialize(): any {
  1553. var serializationObject = super.serialize();
  1554. serializationObject.height = this.height;
  1555. serializationObject.diameterTop = this.diameterTop;
  1556. serializationObject.diameterBottom = this.diameterBottom;
  1557. serializationObject.tessellation = this.tessellation;
  1558. return serializationObject;
  1559. }
  1560. public static Parse(parsedCylinder: any, scene: Scene): Nullable<CylinderGeometry> {
  1561. if (scene.getGeometryByID(parsedCylinder.id)) {
  1562. return null; // null since geometry could be something else than a cylinder...
  1563. }
  1564. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  1565. if (Tags) {
  1566. Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  1567. }
  1568. scene.pushGeometry(cylinder, true);
  1569. return cylinder;
  1570. }
  1571. }
  1572. /**
  1573. * Creates a new torus geometry
  1574. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  1575. */
  1576. export class TorusGeometry extends _PrimitiveGeometry {
  1577. /**
  1578. * Creates a new torus geometry
  1579. * @param id defines the unique ID of the geometry
  1580. * @param scene defines the hosting scene
  1581. * @param diameter defines the diameter of the torus
  1582. * @param thickness defines the thickness of the torus (ie. internal diameter)
  1583. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  1584. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1585. * @param mesh defines the hosting mesh (can be null)
  1586. * @param side defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1587. */
  1588. constructor(
  1589. id: string, scene: Scene,
  1590. /**
  1591. * Defines the diameter of the torus
  1592. */
  1593. public diameter: number,
  1594. /**
  1595. * Defines the thickness of the torus (ie. internal diameter)
  1596. */
  1597. public thickness: number,
  1598. /**
  1599. * Defines the tesselation factor to apply to the torus
  1600. */
  1601. public tessellation: number,
  1602. canBeRegenerated?: boolean,
  1603. mesh: Nullable<Mesh> = null,
  1604. /**
  1605. * Defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1606. */
  1607. public side: number = Mesh.DEFAULTSIDE) {
  1608. super(id, scene, canBeRegenerated, mesh);
  1609. }
  1610. /** @hidden */
  1611. public _regenerateVertexData(): VertexData {
  1612. return VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  1613. }
  1614. public copy(id: string): Geometry {
  1615. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  1616. }
  1617. public serialize(): any {
  1618. var serializationObject = super.serialize();
  1619. serializationObject.diameter = this.diameter;
  1620. serializationObject.thickness = this.thickness;
  1621. serializationObject.tessellation = this.tessellation;
  1622. return serializationObject;
  1623. }
  1624. public static Parse(parsedTorus: any, scene: Scene): Nullable<TorusGeometry> {
  1625. if (scene.getGeometryByID(parsedTorus.id)) {
  1626. return null; // null since geometry could be something else than a torus...
  1627. }
  1628. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  1629. if (Tags) {
  1630. Tags.AddTagsTo(torus, parsedTorus.tags);
  1631. }
  1632. scene.pushGeometry(torus, true);
  1633. return torus;
  1634. }
  1635. }
  1636. /**
  1637. * Creates a new ground geometry
  1638. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  1639. */
  1640. export class GroundGeometry extends _PrimitiveGeometry {
  1641. /**
  1642. * Creates a new ground geometry
  1643. * @param id defines the unique ID of the geometry
  1644. * @param scene defines the hosting scene
  1645. * @param width defines the width of the ground
  1646. * @param height defines the height of the ground
  1647. * @param subdivisions defines the subdivisions to apply to the ground
  1648. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1649. * @param mesh defines the hosting mesh (can be null)
  1650. */
  1651. constructor(
  1652. id: string, scene: Scene,
  1653. /**
  1654. * Defines the width of the ground
  1655. */
  1656. public width: number,
  1657. /**
  1658. * Defines the height of the ground
  1659. */
  1660. public height: number,
  1661. /**
  1662. * Defines the subdivisions to apply to the ground
  1663. */
  1664. public subdivisions: number,
  1665. canBeRegenerated?: boolean,
  1666. mesh: Nullable<Mesh> = null) {
  1667. super(id, scene, canBeRegenerated, mesh);
  1668. }
  1669. /** @hidden */
  1670. public _regenerateVertexData(): VertexData {
  1671. return VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  1672. }
  1673. public copy(id: string): Geometry {
  1674. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  1675. }
  1676. public serialize(): any {
  1677. var serializationObject = super.serialize();
  1678. serializationObject.width = this.width;
  1679. serializationObject.height = this.height;
  1680. serializationObject.subdivisions = this.subdivisions;
  1681. return serializationObject;
  1682. }
  1683. public static Parse(parsedGround: any, scene: Scene): Nullable<GroundGeometry> {
  1684. if (scene.getGeometryByID(parsedGround.id)) {
  1685. return null; // null since geometry could be something else than a ground...
  1686. }
  1687. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  1688. if (Tags) {
  1689. Tags.AddTagsTo(ground, parsedGround.tags);
  1690. }
  1691. scene.pushGeometry(ground, true);
  1692. return ground;
  1693. }
  1694. }
  1695. /**
  1696. * Creates a tiled ground geometry
  1697. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  1698. */
  1699. export class TiledGroundGeometry extends _PrimitiveGeometry {
  1700. /**
  1701. * Creates a tiled ground geometry
  1702. * @param id defines the unique ID of the geometry
  1703. * @param scene defines the hosting scene
  1704. * @param xmin defines the minimum value on X axis
  1705. * @param zmin defines the minimum value on Z axis
  1706. * @param xmax defines the maximum value on X axis
  1707. * @param zmax defines the maximum value on Z axis
  1708. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  1709. * @param precision defines the precision to use when computing the tiles
  1710. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1711. * @param mesh defines the hosting mesh (can be null)
  1712. */
  1713. constructor(
  1714. id: string, scene: Scene,
  1715. /**
  1716. * Defines the minimum value on X axis
  1717. */
  1718. public xmin: number,
  1719. /**
  1720. * Defines the minimum value on Z axis
  1721. */
  1722. public zmin: number,
  1723. /**
  1724. * Defines the maximum value on X axis
  1725. */
  1726. public xmax: number,
  1727. /**
  1728. * Defines the maximum value on Z axis
  1729. */
  1730. public zmax: number,
  1731. /**
  1732. * Defines the subdivisions to apply to the ground
  1733. */
  1734. public subdivisions: { w: number; h: number; },
  1735. /**
  1736. * Defines the precision to use when computing the tiles
  1737. */
  1738. public precision: { w: number; h: number; },
  1739. canBeRegenerated?: boolean,
  1740. mesh: Nullable<Mesh> = null) {
  1741. super(id, scene, canBeRegenerated, mesh);
  1742. }
  1743. /** @hidden */
  1744. public _regenerateVertexData(): VertexData {
  1745. return VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  1746. }
  1747. public copy(id: string): Geometry {
  1748. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  1749. }
  1750. }
  1751. /**
  1752. * Creates a plane geometry
  1753. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  1754. */
  1755. export class PlaneGeometry extends _PrimitiveGeometry {
  1756. /**
  1757. * Creates a plane geometry
  1758. * @param id defines the unique ID of the geometry
  1759. * @param scene defines the hosting scene
  1760. * @param size defines the size of the plane (width === height)
  1761. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1762. * @param mesh defines the hosting mesh (can be null)
  1763. * @param side defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1764. */
  1765. constructor(
  1766. id: string, scene: Scene,
  1767. /**
  1768. * Defines the size of the plane (width === height)
  1769. */
  1770. public size: number,
  1771. canBeRegenerated?: boolean,
  1772. mesh: Nullable<Mesh> = null,
  1773. /**
  1774. * Defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1775. */
  1776. public side: number = Mesh.DEFAULTSIDE) {
  1777. super(id, scene, canBeRegenerated, mesh);
  1778. }
  1779. /** @hidden */
  1780. public _regenerateVertexData(): VertexData {
  1781. return VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  1782. }
  1783. public copy(id: string): Geometry {
  1784. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  1785. }
  1786. public serialize(): any {
  1787. var serializationObject = super.serialize();
  1788. serializationObject.size = this.size;
  1789. return serializationObject;
  1790. }
  1791. public static Parse(parsedPlane: any, scene: Scene): Nullable<PlaneGeometry> {
  1792. if (scene.getGeometryByID(parsedPlane.id)) {
  1793. return null; // null since geometry could be something else than a ground...
  1794. }
  1795. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  1796. if (Tags) {
  1797. Tags.AddTagsTo(plane, parsedPlane.tags);
  1798. }
  1799. scene.pushGeometry(plane, true);
  1800. return plane;
  1801. }
  1802. }
  1803. /**
  1804. * Creates a torus knot geometry
  1805. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  1806. */
  1807. export class TorusKnotGeometry extends _PrimitiveGeometry {
  1808. /**
  1809. * Creates a torus knot geometry
  1810. * @param id defines the unique ID of the geometry
  1811. * @param scene defines the hosting scene
  1812. * @param radius defines the radius of the torus knot
  1813. * @param tube defines the thickness of the torus knot tube
  1814. * @param radialSegments defines the number of radial segments
  1815. * @param tubularSegments defines the number of tubular segments
  1816. * @param p defines the first number of windings
  1817. * @param q defines the second number of windings
  1818. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  1819. * @param mesh defines the hosting mesh (can be null)
  1820. * @param side defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1821. */
  1822. constructor(
  1823. id: string, scene: Scene,
  1824. /**
  1825. * Defines the radius of the torus knot
  1826. */
  1827. public radius: number,
  1828. /**
  1829. * Defines the thickness of the torus knot tube
  1830. */
  1831. public tube: number,
  1832. /**
  1833. * Defines the number of radial segments
  1834. */
  1835. public radialSegments: number,
  1836. /**
  1837. * Defines the number of tubular segments
  1838. */
  1839. public tubularSegments: number,
  1840. /**
  1841. * Defines the first number of windings
  1842. */
  1843. public p: number,
  1844. /**
  1845. * Defines the second number of windings
  1846. */
  1847. public q: number,
  1848. canBeRegenerated?: boolean,
  1849. mesh: Nullable<Mesh> = null,
  1850. /**
  1851. * Defines if the created geometry is double sided or not (default is Mesh.DEFAULTSIDE)
  1852. */
  1853. public side: number = Mesh.DEFAULTSIDE) {
  1854. super(id, scene, canBeRegenerated, mesh);
  1855. }
  1856. /** @hidden */
  1857. public _regenerateVertexData(): VertexData {
  1858. return VertexData.CreateTorusKnot({ radius: this.radius, tube: this.tube, radialSegments: this.radialSegments, tubularSegments: this.tubularSegments, p: this.p, q: this.q, sideOrientation: this.side });
  1859. }
  1860. public copy(id: string): Geometry {
  1861. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  1862. }
  1863. public serialize(): any {
  1864. var serializationObject = super.serialize();
  1865. serializationObject.radius = this.radius;
  1866. serializationObject.tube = this.tube;
  1867. serializationObject.radialSegments = this.radialSegments;
  1868. serializationObject.tubularSegments = this.tubularSegments;
  1869. serializationObject.p = this.p;
  1870. serializationObject.q = this.q;
  1871. return serializationObject;
  1872. }
  1873. public static Parse(parsedTorusKnot: any, scene: Scene): Nullable<TorusKnotGeometry> {
  1874. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  1875. return null; // null since geometry could be something else than a ground...
  1876. }
  1877. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  1878. if (Tags) {
  1879. Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  1880. }
  1881. scene.pushGeometry(torusKnot, true);
  1882. return torusKnot;
  1883. }
  1884. }
  1885. //}