babylon.solidParticleSystem.ts 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. module BABYLON {
  2. /**
  3. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  4. */
  5. export class SolidParticleSystem implements IDisposable {
  6. // public members
  7. /**
  8. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  9. * Example : var p = SPS.particles[i];
  10. */
  11. public particles: SolidParticle[] = new Array<SolidParticle>();
  12. /**
  13. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  14. */
  15. public nbParticles: number = 0;
  16. /**
  17. * If the particles must ever face the camera (default false). Useful for planar particles.
  18. */
  19. public billboard: boolean = false;
  20. /**
  21. * Recompute normals when adding a shape
  22. */
  23. public recomputeNormals: boolean = true;
  24. /**
  25. * This a counter ofr your own usage. It's not set by any SPS functions.
  26. */
  27. public counter: number = 0;
  28. /**
  29. * The SPS name. This name is also given to the underlying mesh.
  30. */
  31. public name: string;
  32. /**
  33. * The SPS mesh. It's a standard BJS Mesh, so all the methods from the Mesh class are avalaible.
  34. */
  35. public mesh: Mesh;
  36. /**
  37. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  38. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  39. */
  40. public vars: any = {};
  41. /**
  42. * This array is populated when the SPS is set as 'pickable'.
  43. * Each key of this array is a `faceId` value that you can get from a pickResult object.
  44. * Each element of this array is an object `{idx: int, faceId: int}`.
  45. * `idx` is the picked particle index in the `SPS.particles` array
  46. * `faceId` is the picked face index counted within this particle.
  47. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#pickable-particles
  48. */
  49. public pickedParticles: { idx: number; faceId: number }[];
  50. /**
  51. * This array is populated when `enableDepthSort` is set to true.
  52. * Each element of this array is an instance of the class DepthSortedParticle.
  53. */
  54. public depthSortedParticles: DepthSortedParticle[];
  55. // private members
  56. private _scene: Scene;
  57. private _positions: number[] = new Array<number>();
  58. private _indices: number[] = new Array<number>();
  59. private _normals: number[] = new Array<number>();
  60. private _colors: number[] = new Array<number>();
  61. private _uvs: number[] = new Array<number>();
  62. private _indices32: IndicesArray; // used as depth sorted array if depth sort enabled, else used as typed indices
  63. private _positions32: Float32Array; // updated positions for the VBO
  64. private _normals32: Float32Array; // updated normals for the VBO
  65. private _fixedNormal32: Float32Array; // initial normal references
  66. private _colors32: Float32Array;
  67. private _uvs32: Float32Array;
  68. private _index: number = 0; // indices index
  69. private _updatable: boolean = true;
  70. private _pickable: boolean = false;
  71. private _isVisibilityBoxLocked = false;
  72. private _alwaysVisible: boolean = false;
  73. private _depthSort: boolean = false;
  74. private _shapeCounter: number = 0;
  75. private _copy: SolidParticle = new SolidParticle(0, 0, 0, null, 0, 0, this);
  76. private _shape: Vector3[];
  77. private _shapeUV: number[];
  78. private _color: Color4 = new Color4(0, 0, 0, 0);
  79. private _computeParticleColor: boolean = true;
  80. private _computeParticleTexture: boolean = true;
  81. private _computeParticleRotation: boolean = true;
  82. private _computeParticleVertex: boolean = false;
  83. private _computeBoundingBox: boolean = false;
  84. private _depthSortParticles: boolean = true;
  85. private _cam_axisZ: Vector3 = Vector3.Zero();
  86. private _cam_axisY: Vector3 = Vector3.Zero();
  87. private _cam_axisX: Vector3 = Vector3.Zero();
  88. private _axisZ: Vector3 = Axis.Z;
  89. private _camera: TargetCamera;
  90. private _particle: SolidParticle;
  91. private _camDir: Vector3 = Vector3.Zero();
  92. private _camInvertedPosition: Vector3 = Vector3.Zero();
  93. private _rotMatrix: Matrix = new Matrix();
  94. private _invertMatrix: Matrix = new Matrix();
  95. private _rotated: Vector3 = Vector3.Zero();
  96. private _quaternion: Quaternion = new Quaternion();
  97. private _vertex: Vector3 = Vector3.Zero();
  98. private _normal: Vector3 = Vector3.Zero();
  99. private _yaw: number = 0.0;
  100. private _pitch: number = 0.0;
  101. private _roll: number = 0.0;
  102. private _halfroll: number = 0.0;
  103. private _halfpitch: number = 0.0;
  104. private _halfyaw: number = 0.0;
  105. private _sinRoll: number = 0.0;
  106. private _cosRoll: number = 0.0;
  107. private _sinPitch: number = 0.0;
  108. private _cosPitch: number = 0.0;
  109. private _sinYaw: number = 0.0;
  110. private _cosYaw: number = 0.0;
  111. private _mustUnrotateFixedNormals = false;
  112. private _minimum: Vector3 = Tmp.Vector3[0];
  113. private _maximum: Vector3 = Tmp.Vector3[1];
  114. private _minBbox: Vector3 = Tmp.Vector3[4];
  115. private _maxBbox: Vector3 = Tmp.Vector3[5];
  116. private _particlesIntersect: boolean = false;
  117. private _depthSortFunction: (p1: DepthSortedParticle, p2: DepthSortedParticle) => number =
  118. function(p1, p2) {
  119. return (p2.sqDistance - p1.sqDistance);
  120. };
  121. private _needs32Bits: boolean = false;
  122. public _bSphereOnly: boolean = false;
  123. public _bSphereRadiusFactor: number = 1.0;
  124. /**
  125. * Creates a SPS (Solid Particle System) object.
  126. * `name` (String) is the SPS name, this will be the underlying mesh name.
  127. * `scene` (Scene) is the scene in which the SPS is added.
  128. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  129. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  130. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  131. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  132. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  133. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  134. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  135. */
  136. constructor(name: string, scene: Scene, options?: { updatable?: boolean; isPickable?: boolean; enableDepthSort?: boolean; particleIntersection?: boolean; boundingSphereOnly?: boolean; bSphereRadiusFactor?: number }) {
  137. this.name = name;
  138. this._scene = scene || Engine.LastCreatedScene;
  139. this._camera = <TargetCamera>scene.activeCamera;
  140. this._pickable = options ? <boolean>options.isPickable : false;
  141. this._depthSort = options ? <boolean>options.enableDepthSort : false;
  142. this._particlesIntersect = options ? <boolean>options.particleIntersection : false;
  143. this._bSphereOnly= options ? <boolean>options.boundingSphereOnly : false;
  144. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  145. if (options && options.updatable) {
  146. this._updatable = options.updatable;
  147. } else {
  148. this._updatable = true;
  149. }
  150. if (this._pickable) {
  151. this.pickedParticles = [];
  152. }
  153. if (this._depthSort) {
  154. this.depthSortedParticles = [];
  155. }
  156. }
  157. /**
  158. * Builds the SPS underlying mesh. Returns a standard Mesh.
  159. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  160. */
  161. public buildMesh(): Mesh {
  162. if (this.nbParticles === 0) {
  163. var triangle = MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  164. this.addShape(triangle, 1);
  165. triangle.dispose();
  166. }
  167. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  168. this._positions32 = new Float32Array(this._positions);
  169. this._uvs32 = new Float32Array(this._uvs);
  170. this._colors32 = new Float32Array(this._colors);
  171. if (this.recomputeNormals) {
  172. VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  173. }
  174. this._normals32 = new Float32Array(this._normals);
  175. this._fixedNormal32 = new Float32Array(this._normals);
  176. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  177. this._unrotateFixedNormals();
  178. }
  179. var vertexData = new VertexData();
  180. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  181. vertexData.set(this._positions32, VertexBuffer.PositionKind);
  182. vertexData.set(this._normals32, VertexBuffer.NormalKind);
  183. if (this._uvs32) {
  184. vertexData.set(this._uvs32, VertexBuffer.UVKind);;
  185. }
  186. if (this._colors32) {
  187. vertexData.set(this._colors32, VertexBuffer.ColorKind);
  188. }
  189. var mesh = new Mesh(this.name, this._scene);
  190. vertexData.applyToMesh(mesh, this._updatable);
  191. this.mesh = mesh;
  192. this.mesh.isPickable = this._pickable;
  193. // free memory
  194. if (!this._depthSort) {
  195. (<any>this._indices) = null;
  196. }
  197. (<any>this._positions) = null;
  198. (<any>this._normals) = null;
  199. (<any>this._uvs) = null;
  200. (<any>this._colors) = null;
  201. if (!this._updatable) {
  202. this.particles.length = 0;
  203. }
  204. return mesh;
  205. }
  206. /**
  207. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  208. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  209. * Thus the particles generated from `digest()` have their property `position` set yet.
  210. * `mesh` ( Mesh ) is the mesh to be digested
  211. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  212. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  213. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  214. */
  215. public digest(mesh: Mesh, options?: { facetNb?: number; number?: number; delta?: number }): SolidParticleSystem {
  216. var size: number = (options && options.facetNb) || 1;
  217. var number: number = (options && options.number) || 0;
  218. var delta: number = (options && options.delta) || 0;
  219. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  220. var meshInd = <IndicesArray>mesh.getIndices();
  221. var meshUV = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  222. var meshCol = <FloatArray>mesh.getVerticesData(VertexBuffer.ColorKind);
  223. var meshNor = <FloatArray>mesh.getVerticesData(VertexBuffer.NormalKind);
  224. var f: number = 0; // facet counter
  225. var totalFacets: number = meshInd.length / 3; // a facet is a triangle, so 3 indices
  226. // compute size from number
  227. if (number) {
  228. number = (number > totalFacets) ? totalFacets : number;
  229. size = Math.round(totalFacets / number);
  230. delta = 0;
  231. } else {
  232. size = (size > totalFacets) ? totalFacets : size;
  233. }
  234. var facetPos: number[] = []; // submesh positions
  235. var facetInd: number[] = []; // submesh indices
  236. var facetUV: number[] = []; // submesh UV
  237. var facetCol: number[] = []; // submesh colors
  238. var barycenter: Vector3 = Tmp.Vector3[0];
  239. var sizeO: number = size;
  240. while (f < totalFacets) {
  241. size = sizeO + Math.floor((1 + delta) * Math.random());
  242. if (f > totalFacets - size) {
  243. size = totalFacets - f;
  244. }
  245. // reset temp arrays
  246. facetPos.length = 0;
  247. facetInd.length = 0;
  248. facetUV.length = 0;
  249. facetCol.length = 0;
  250. // iterate over "size" facets
  251. var fi: number = 0;
  252. for (var j = f * 3; j < (f + size) * 3; j++) {
  253. facetInd.push(fi);
  254. var i: number = meshInd[j];
  255. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  256. if (meshUV) {
  257. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  258. }
  259. if (meshCol) {
  260. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  261. }
  262. fi++;
  263. }
  264. // create a model shape for each single particle
  265. var idx: number = this.nbParticles;
  266. var shape: Vector3[] = this._posToShape(facetPos);
  267. var shapeUV: number[] = this._uvsToShapeUV(facetUV);
  268. // compute the barycenter of the shape
  269. var v: number;
  270. for (v = 0; v < shape.length; v++) {
  271. barycenter.addInPlace(shape[v]);
  272. }
  273. barycenter.scaleInPlace(1 / shape.length);
  274. // shift the shape from its barycenter to the origin
  275. for (v = 0; v < shape.length; v++) {
  276. shape[v].subtractInPlace(barycenter);
  277. }
  278. var bInfo;
  279. if (this._particlesIntersect) {
  280. bInfo = new BoundingInfo(barycenter, barycenter);
  281. }
  282. var modelShape = new ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  283. // add the particle in the SPS
  284. var currentPos = this._positions.length;
  285. var currentInd = this._indices.length;
  286. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  287. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  288. // initialize the particle position
  289. this.particles[this.nbParticles].position.addInPlace(barycenter);
  290. this._index += shape.length;
  291. idx++;
  292. this.nbParticles++;
  293. this._shapeCounter++;
  294. f += size;
  295. }
  296. return this;
  297. }
  298. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  299. private _unrotateFixedNormals() {
  300. var index = 0;
  301. var idx = 0;
  302. for (var p = 0; p < this.particles.length; p++) {
  303. this._particle = this.particles[p];
  304. this._shape = this._particle._model._shape;
  305. if (this._particle.rotationQuaternion) {
  306. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  307. }
  308. else {
  309. this._yaw = this._particle.rotation.y;
  310. this._pitch = this._particle.rotation.x;
  311. this._roll = this._particle.rotation.z;
  312. this._quaternionRotationYPR();
  313. }
  314. this._quaternionToRotationMatrix();
  315. this._rotMatrix.invertToRef(this._invertMatrix);
  316. for (var pt = 0; pt < this._shape.length; pt++) {
  317. idx = index + pt * 3;
  318. Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  319. this._fixedNormal32[idx] = this._normal.x;
  320. this._fixedNormal32[idx + 1] = this._normal.y;
  321. this._fixedNormal32[idx + 2] = this._normal.z;
  322. }
  323. index = idx + 3;
  324. }
  325. }
  326. //reset copy
  327. private _resetCopy() {
  328. this._copy.position.x = 0;
  329. this._copy.position.y = 0;
  330. this._copy.position.z = 0;
  331. this._copy.rotation.x = 0;
  332. this._copy.rotation.y = 0;
  333. this._copy.rotation.z = 0;
  334. this._copy.rotationQuaternion = null;
  335. this._copy.scaling.x = 1.0;
  336. this._copy.scaling.y = 1.0;
  337. this._copy.scaling.z = 1.0;
  338. this._copy.uvs.x = 0;
  339. this._copy.uvs.y = 0;
  340. this._copy.uvs.z = 1.0;
  341. this._copy.uvs.w = 1.0;
  342. this._copy.color = null;
  343. }
  344. // _meshBuilder : inserts the shape model in the global SPS mesh
  345. private _meshBuilder(p: number, shape: Vector3[], positions: number[], meshInd: IndicesArray, indices: number[], meshUV: number[]|Float32Array, uvs: number[], meshCol: number[]|Float32Array, colors: number[], meshNor: number[]|Float32Array, normals: number[], idx: number, idxInShape: number, options: any): SolidParticle {
  346. var i;
  347. var u = 0;
  348. var c = 0;
  349. var n = 0;
  350. this._resetCopy();
  351. if (options && options.positionFunction) { // call to custom positionFunction
  352. options.positionFunction(this._copy, idx, idxInShape);
  353. this._mustUnrotateFixedNormals = true;
  354. }
  355. if (this._copy.rotationQuaternion) {
  356. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  357. } else {
  358. this._yaw = this._copy.rotation.y;
  359. this._pitch = this._copy.rotation.x;
  360. this._roll = this._copy.rotation.z;
  361. this._quaternionRotationYPR();
  362. }
  363. this._quaternionToRotationMatrix();
  364. for (i = 0; i < shape.length; i++) {
  365. this._vertex.x = shape[i].x;
  366. this._vertex.y = shape[i].y;
  367. this._vertex.z = shape[i].z;
  368. if (options && options.vertexFunction) {
  369. options.vertexFunction(this._copy, this._vertex, i);
  370. }
  371. this._vertex.x *= this._copy.scaling.x;
  372. this._vertex.y *= this._copy.scaling.y;
  373. this._vertex.z *= this._copy.scaling.z;
  374. this._vertex.x += this._copy.pivot.x;
  375. this._vertex.y += this._copy.pivot.y;
  376. this._vertex.z += this._copy.pivot.z;
  377. Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  378. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  379. if (meshUV) {
  380. uvs.push((this._copy.uvs.z - this._copy.uvs.x) * meshUV[u] + this._copy.uvs.x, (this._copy.uvs.w - this._copy.uvs.y) * meshUV[u + 1] + this._copy.uvs.y);
  381. u += 2;
  382. }
  383. if (this._copy.color) {
  384. this._color = this._copy.color;
  385. } else if (meshCol && meshCol[c] !== undefined) {
  386. this._color.r = meshCol[c];
  387. this._color.g = meshCol[c + 1];
  388. this._color.b = meshCol[c + 2];
  389. this._color.a = meshCol[c + 3];
  390. } else {
  391. this._color.r = 1.0;
  392. this._color.g = 1.0;
  393. this._color.b = 1.0;
  394. this._color.a = 1.0;
  395. }
  396. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  397. c += 4;
  398. if (!this.recomputeNormals && meshNor) {
  399. this._normal.x = meshNor[n];
  400. this._normal.y = meshNor[n + 1];
  401. this._normal.z = meshNor[n + 2];
  402. Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  403. normals.push(this._normal.x, this._normal.y, this._normal.z);
  404. n += 3;
  405. }
  406. }
  407. for (i = 0; i < meshInd.length; i++) {
  408. var current_ind = p + meshInd[i];
  409. indices.push(current_ind);
  410. if (current_ind > 65535) {
  411. this._needs32Bits = true;
  412. }
  413. }
  414. if (this._pickable) {
  415. var nbfaces = meshInd.length / 3;
  416. for (i = 0; i < nbfaces; i++) {
  417. this.pickedParticles.push({ idx: idx, faceId: i });
  418. }
  419. }
  420. if (this._depthSort) {
  421. this.depthSortedParticles.push(new DepthSortedParticle());
  422. }
  423. return this._copy;
  424. }
  425. // returns a shape array from positions array
  426. private _posToShape(positions: number[]|Float32Array): Vector3[] {
  427. var shape = [];
  428. for (var i = 0; i < positions.length; i += 3) {
  429. shape.push(new Vector3(positions[i], positions[i + 1], positions[i + 2]));
  430. }
  431. return shape;
  432. }
  433. // returns a shapeUV array from a Vector4 uvs
  434. private _uvsToShapeUV(uvs: number[]|Float32Array): number[] {
  435. var shapeUV = [];
  436. if (uvs) {
  437. for (var i = 0; i < uvs.length; i++)
  438. shapeUV.push(uvs[i]);
  439. }
  440. return shapeUV;
  441. }
  442. // adds a new particle object in the particles array
  443. private _addParticle(idx: number, idxpos: number, idxind: number, model: ModelShape, shapeId: number, idxInShape: number, bInfo: Nullable<BoundingInfo> = null): SolidParticle {
  444. var sp = new SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  445. this.particles.push(sp);
  446. return sp;
  447. }
  448. /**
  449. * Adds some particles to the SPS from the model shape. Returns the shape id.
  450. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  451. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  452. * `nb` (positive integer) the number of particles to be created from this model
  453. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  454. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  455. */
  456. public addShape(mesh: Mesh, nb: number, options?: { positionFunction?: any; vertexFunction?: any }): number {
  457. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  458. var meshInd = <IndicesArray>mesh.getIndices();
  459. var meshUV = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  460. var meshCol = <FloatArray>mesh.getVerticesData(VertexBuffer.ColorKind);
  461. var meshNor = <FloatArray>mesh.getVerticesData(VertexBuffer.NormalKind);
  462. var bbInfo;
  463. if (this._particlesIntersect) {
  464. bbInfo = mesh.getBoundingInfo();
  465. }
  466. var shape = this._posToShape(meshPos);
  467. var shapeUV = this._uvsToShapeUV(meshUV);
  468. var posfunc = options ? options.positionFunction : null;
  469. var vtxfunc = options ? options.vertexFunction : null;
  470. var modelShape = new ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  471. // particles
  472. var sp;
  473. var currentCopy;
  474. var idx = this.nbParticles;
  475. for (var i = 0; i < nb; i++) {
  476. var currentPos = this._positions.length;
  477. var currentInd = this._indices.length;
  478. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  479. if (this._updatable) {
  480. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  481. sp.position.copyFrom(currentCopy.position);
  482. sp.rotation.copyFrom(currentCopy.rotation);
  483. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  484. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  485. }
  486. if (currentCopy.color && sp.color) {
  487. sp.color.copyFrom(currentCopy.color);
  488. }
  489. sp.scaling.copyFrom(currentCopy.scaling);
  490. sp.uvs.copyFrom(currentCopy.uvs);
  491. }
  492. this._index += shape.length;
  493. idx++;
  494. }
  495. this.nbParticles += nb;
  496. this._shapeCounter++;
  497. return this._shapeCounter - 1;
  498. }
  499. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  500. private _rebuildParticle(particle: SolidParticle): void {
  501. this._resetCopy();
  502. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  503. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  504. }
  505. if (this._copy.rotationQuaternion) {
  506. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  507. } else {
  508. this._yaw = this._copy.rotation.y;
  509. this._pitch = this._copy.rotation.x;
  510. this._roll = this._copy.rotation.z;
  511. this._quaternionRotationYPR();
  512. }
  513. this._quaternionToRotationMatrix();
  514. this._shape = particle._model._shape;
  515. for (var pt = 0; pt < this._shape.length; pt++) {
  516. this._vertex.x = this._shape[pt].x;
  517. this._vertex.y = this._shape[pt].y;
  518. this._vertex.z = this._shape[pt].z;
  519. if (particle._model._vertexFunction) {
  520. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  521. }
  522. this._vertex.x *= this._copy.scaling.x;
  523. this._vertex.y *= this._copy.scaling.y;
  524. this._vertex.z *= this._copy.scaling.z;
  525. this._vertex.x += this._copy.pivot.x;
  526. this._vertex.y += this._copy.pivot.y;
  527. this._vertex.z += this._copy.pivot.z;
  528. Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  529. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  530. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  531. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  532. }
  533. particle.position.x = 0.0;
  534. particle.position.y = 0.0;
  535. particle.position.z = 0.0;
  536. particle.rotation.x = 0.0;
  537. particle.rotation.y = 0.0;
  538. particle.rotation.z = 0.0;
  539. particle.rotationQuaternion = null;
  540. particle.scaling.x = 1.0;
  541. particle.scaling.y = 1.0;
  542. particle.scaling.z = 1.0;
  543. }
  544. /**
  545. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  546. * Returns the SPS.
  547. */
  548. public rebuildMesh(): SolidParticleSystem {
  549. for (var p = 0; p < this.particles.length; p++) {
  550. this._rebuildParticle(this.particles[p]);
  551. }
  552. this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);
  553. return this;
  554. }
  555. /**
  556. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  557. * This method calls `updateParticle()` for each particle of the SPS.
  558. * For an animated SPS, it is usually called within the render loop.
  559. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  560. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  561. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  562. * Returns the SPS.
  563. */
  564. public setParticles(start: number = 0, end: number = this.nbParticles - 1, update: boolean = true): SolidParticleSystem {
  565. if (!this._updatable) {
  566. return this;
  567. }
  568. // custom beforeUpdate
  569. this.beforeUpdateParticles(start, end, update);
  570. this._cam_axisX.x = 1.0;
  571. this._cam_axisX.y = 0.0;
  572. this._cam_axisX.z = 0.0;
  573. this._cam_axisY.x = 0.0;
  574. this._cam_axisY.y = 1.0;
  575. this._cam_axisY.z = 0.0;
  576. this._cam_axisZ.x = 0.0;
  577. this._cam_axisZ.y = 0.0;
  578. this._cam_axisZ.z = 1.0;
  579. // cases when the World Matrix is to be computed first
  580. if (this.billboard || this._depthSort) {
  581. this.mesh.computeWorldMatrix(true);
  582. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  583. }
  584. // if the particles will always face the camera
  585. if (this.billboard) {
  586. // compute the camera position and un-rotate it by the current mesh rotation
  587. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  588. Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  589. this._cam_axisZ.normalize();
  590. // same for camera up vector extracted from the cam view matrix
  591. var view = this._camera.getViewMatrix(true);
  592. Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  593. Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  594. this._cam_axisY.normalize();
  595. this._cam_axisX.normalize();
  596. }
  597. // if depthSort, compute the camera global position in the mesh local system
  598. if (this._depthSort) {
  599. Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  600. }
  601. Matrix.IdentityToRef(this._rotMatrix);
  602. var idx = 0; // current position index in the global array positions32
  603. var index = 0; // position start index in the global array positions32 of the current particle
  604. var colidx = 0; // current color index in the global array colors32
  605. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  606. var uvidx = 0; // current uv index in the global array uvs32
  607. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  608. var pt = 0; // current index in the particle model shape
  609. if (this.mesh.isFacetDataEnabled) {
  610. this._computeBoundingBox = true;
  611. }
  612. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  613. if (this._computeBoundingBox) {
  614. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  615. Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  616. Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  617. }
  618. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  619. if (this.mesh._boundingInfo) {
  620. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  621. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  622. }
  623. }
  624. }
  625. // particle loop
  626. index = this.particles[start]._pos;
  627. var vpos = (index / 3)|0;
  628. colorIndex = vpos * 4;
  629. uvIndex = vpos * 2;
  630. for (var p = start; p <= end; p++) {
  631. this._particle = this.particles[p];
  632. this._shape = this._particle._model._shape;
  633. this._shapeUV = this._particle._model._shapeUV;
  634. // call to custom user function to update the particle properties
  635. this.updateParticle(this._particle);
  636. // camera-particle distance for depth sorting
  637. if (this._depthSort && this._depthSortParticles) {
  638. var dsp = this.depthSortedParticles[p];
  639. dsp.ind = this._particle._ind;
  640. dsp.indicesLength = this._particle._model._indicesLength;
  641. dsp.sqDistance = Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  642. }
  643. // skip the computations for inactive or already invisible particles
  644. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  645. // increment indexes for the next particle
  646. pt = this._shape.length;
  647. index += pt * 3;
  648. colorIndex += pt * 4;
  649. uvIndex += pt * 2;
  650. continue;
  651. }
  652. if (this._particle.isVisible) {
  653. this._particle._stillInvisible = false; // un-mark permanent invisibility
  654. // particle rotation matrix
  655. if (this.billboard) {
  656. this._particle.rotation.x = 0.0;
  657. this._particle.rotation.y = 0.0;
  658. }
  659. if (this._computeParticleRotation || this.billboard) {
  660. if (this._particle.rotationQuaternion) {
  661. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  662. } else {
  663. this._yaw = this._particle.rotation.y;
  664. this._pitch = this._particle.rotation.x;
  665. this._roll = this._particle.rotation.z;
  666. this._quaternionRotationYPR();
  667. }
  668. this._quaternionToRotationMatrix();
  669. }
  670. // particle vertex loop
  671. for (pt = 0; pt < this._shape.length; pt++) {
  672. idx = index + pt * 3;
  673. colidx = colorIndex + pt * 4;
  674. uvidx = uvIndex + pt * 2;
  675. this._vertex.x = this._shape[pt].x;
  676. this._vertex.y = this._shape[pt].y;
  677. this._vertex.z = this._shape[pt].z;
  678. if (this._computeParticleVertex) {
  679. this.updateParticleVertex(this._particle, this._vertex, pt);
  680. }
  681. // positions
  682. this._vertex.x *= this._particle.scaling.x;
  683. this._vertex.y *= this._particle.scaling.y;
  684. this._vertex.z *= this._particle.scaling.z;
  685. this._vertex.x += this._particle.pivot.x;
  686. this._vertex.y += this._particle.pivot.y;
  687. this._vertex.z += this._particle.pivot.z;
  688. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  689. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  690. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  691. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  692. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  693. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  694. if (this._computeBoundingBox) {
  695. if (this._positions32[idx] < this._minimum.x) {
  696. this._minimum.x = this._positions32[idx];
  697. }
  698. if (this._positions32[idx] > this._maximum.x) {
  699. this._maximum.x = this._positions32[idx];
  700. }
  701. if (this._positions32[idx + 1] < this._minimum.y) {
  702. this._minimum.y = this._positions32[idx + 1];
  703. }
  704. if (this._positions32[idx + 1] > this._maximum.y) {
  705. this._maximum.y = this._positions32[idx + 1];
  706. }
  707. if (this._positions32[idx + 2] < this._minimum.z) {
  708. this._minimum.z = this._positions32[idx + 2];
  709. }
  710. if (this._positions32[idx + 2] > this._maximum.z) {
  711. this._maximum.z = this._positions32[idx + 2];
  712. }
  713. }
  714. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  715. if (!this._computeParticleVertex) {
  716. this._normal.x = this._fixedNormal32[idx];
  717. this._normal.y = this._fixedNormal32[idx + 1];
  718. this._normal.z = this._fixedNormal32[idx + 2];
  719. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  720. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  721. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  722. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  723. this._normals32[idx + 1] = this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  724. this._normals32[idx + 2] = this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  725. }
  726. if (this._computeParticleColor && this._particle.color) {
  727. this._colors32[colidx] = this._particle.color.r;
  728. this._colors32[colidx + 1] = this._particle.color.g;
  729. this._colors32[colidx + 2] = this._particle.color.b;
  730. this._colors32[colidx + 3] = this._particle.color.a;
  731. }
  732. if (this._computeParticleTexture) {
  733. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  734. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  735. }
  736. }
  737. }
  738. // particle just set invisible : scaled to zero and positioned at the origin
  739. else {
  740. this._particle._stillInvisible = true; // mark the particle as invisible
  741. for (pt = 0; pt < this._shape.length; pt++) {
  742. idx = index + pt * 3;
  743. colidx = colorIndex + pt * 4;
  744. uvidx = uvIndex + pt * 2;
  745. this._positions32[idx] = 0.0;
  746. this._positions32[idx + 1] = 0.0;
  747. this._positions32[idx + 2] = 0.0;
  748. this._normals32[idx] = 0.0;
  749. this._normals32[idx + 1] = 0.0;
  750. this._normals32[idx + 2] = 0.0;
  751. if (this._computeParticleColor && this._particle.color) {
  752. this._colors32[colidx] = this._particle.color.r;
  753. this._colors32[colidx + 1] = this._particle.color.g;
  754. this._colors32[colidx + 2] = this._particle.color.b;
  755. this._colors32[colidx + 3] = this._particle.color.a;
  756. }
  757. if (this._computeParticleTexture) {
  758. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  759. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  760. }
  761. }
  762. }
  763. // if the particle intersections must be computed : update the bbInfo
  764. if (this._particlesIntersect) {
  765. var bInfo = this._particle._boundingInfo;
  766. var bBox = bInfo.boundingBox;
  767. var bSphere = bInfo.boundingSphere;
  768. if (!this._bSphereOnly) {
  769. // place, scale and rotate the particle bbox within the SPS local system, then update it
  770. for (var b = 0; b < bBox.vectors.length; b++) {
  771. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  772. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  773. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  774. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  775. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  776. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  777. bBox.vectors[b].x = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  778. bBox.vectors[b].y = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  779. bBox.vectors[b].z = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  780. }
  781. bBox._update(this.mesh._worldMatrix);
  782. }
  783. // place and scale the particle bouding sphere in the SPS local system, then update it
  784. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  785. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  786. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  787. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  788. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  789. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  790. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  791. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  792. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  793. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  794. bSphere._update(this.mesh._worldMatrix);
  795. }
  796. // increment indexes for the next particle
  797. index = idx + 3;
  798. colorIndex = colidx + 4;
  799. uvIndex = uvidx + 2;
  800. }
  801. // if the VBO must be updated
  802. if (update) {
  803. if (this._computeParticleColor) {
  804. this.mesh.updateVerticesData(VertexBuffer.ColorKind, this._colors32, false, false);
  805. }
  806. if (this._computeParticleTexture) {
  807. this.mesh.updateVerticesData(VertexBuffer.UVKind, this._uvs32, false, false);
  808. }
  809. this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);
  810. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  811. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  812. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  813. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  814. VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  815. for (var i = 0; i < this._normals32.length; i++) {
  816. this._fixedNormal32[i] = this._normals32[i];
  817. }
  818. }
  819. if (!this.mesh.areNormalsFrozen) {
  820. this.mesh.updateVerticesData(VertexBuffer.NormalKind, this._normals32, false, false);
  821. }
  822. }
  823. if (this._depthSort && this._depthSortParticles) {
  824. this.depthSortedParticles.sort(this._depthSortFunction);
  825. var dspl = this.depthSortedParticles.length;
  826. var sorted = 0;
  827. var lind = 0;
  828. var sind = 0;
  829. var sid = 0;
  830. for (sorted = 0; sorted < dspl; sorted++) {
  831. lind = this.depthSortedParticles[sorted].indicesLength;
  832. sind = this.depthSortedParticles[sorted].ind;
  833. for (var i = 0; i < lind; i++) {
  834. this._indices32[sid] = this._indices[sind + i];
  835. sid++;
  836. }
  837. }
  838. this.mesh.updateIndices(this._indices32);
  839. }
  840. }
  841. if (this._computeBoundingBox) {
  842. this.mesh._boundingInfo = new BoundingInfo(this._minimum, this._maximum);
  843. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  844. }
  845. this.afterUpdateParticles(start, end, update);
  846. return this;
  847. }
  848. private _quaternionRotationYPR(): void {
  849. this._halfroll = this._roll * 0.5;
  850. this._halfpitch = this._pitch * 0.5;
  851. this._halfyaw = this._yaw * 0.5;
  852. this._sinRoll = Math.sin(this._halfroll);
  853. this._cosRoll = Math.cos(this._halfroll);
  854. this._sinPitch = Math.sin(this._halfpitch);
  855. this._cosPitch = Math.cos(this._halfpitch);
  856. this._sinYaw = Math.sin(this._halfyaw);
  857. this._cosYaw = Math.cos(this._halfyaw);
  858. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  859. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  860. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  861. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  862. }
  863. private _quaternionToRotationMatrix(): void {
  864. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  865. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  866. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  867. this._rotMatrix.m[3] = 0;
  868. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  869. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  870. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  871. this._rotMatrix.m[7] = 0;
  872. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  873. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  874. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  875. this._rotMatrix.m[11] = 0;
  876. this._rotMatrix.m[12] = 0;
  877. this._rotMatrix.m[13] = 0;
  878. this._rotMatrix.m[14] = 0;
  879. this._rotMatrix.m[15] = 1.0;
  880. }
  881. /**
  882. * Disposes the SPS.
  883. * Returns nothing.
  884. */
  885. public dispose(): void {
  886. this.mesh.dispose();
  887. this.vars = null;
  888. // drop references to internal big arrays for the GC
  889. (<any>this._positions) = null;
  890. (<any>this._indices) = null;
  891. (<any>this._normals) = null;
  892. (<any>this._uvs) = null;
  893. (<any>this._colors) = null;
  894. (<any>this._indices32) = null;
  895. (<any>this._positions32) = null;
  896. (<any>this._normals32) = null;
  897. (<any>this._fixedNormal32) = null;
  898. (<any>this._uvs32) = null;
  899. (<any>this._colors32) = null;
  900. (<any>this.pickedParticles) = null;
  901. }
  902. /**
  903. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  904. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  905. * Returns the SPS.
  906. */
  907. public refreshVisibleSize(): SolidParticleSystem {
  908. if (!this._isVisibilityBoxLocked) {
  909. this.mesh.refreshBoundingInfo();
  910. }
  911. return this;
  912. }
  913. /**
  914. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  915. * @param size the size (float) of the visibility box
  916. * note : this doesn't lock the SPS mesh bounding box.
  917. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  918. */
  919. public setVisibilityBox(size: number): void {
  920. var vis = size / 2;
  921. this.mesh._boundingInfo = new BoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));
  922. }
  923. // getter and setter
  924. public get isAlwaysVisible(): boolean {
  925. return this._alwaysVisible;
  926. }
  927. /**
  928. * Sets the SPS as always visible or not
  929. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  930. */
  931. public set isAlwaysVisible(val: boolean) {
  932. this._alwaysVisible = val;
  933. this.mesh.alwaysSelectAsActiveMesh = val;
  934. }
  935. /**
  936. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  937. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  938. */
  939. public set isVisibilityBoxLocked(val: boolean) {
  940. this._isVisibilityBoxLocked = val;
  941. let boundingInfo = this.mesh.getBoundingInfo();
  942. boundingInfo.isLocked = val;
  943. }
  944. public get isVisibilityBoxLocked(): boolean {
  945. return this._isVisibilityBoxLocked;
  946. }
  947. // Optimizer setters
  948. /**
  949. * Tells to `setParticles()` to compute the particle rotations or not.
  950. * Default value : true. The SPS is faster when it's set to false.
  951. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  952. */
  953. public set computeParticleRotation(val: boolean) {
  954. this._computeParticleRotation = val;
  955. }
  956. /**
  957. * Tells to `setParticles()` to compute the particle colors or not.
  958. * Default value : true. The SPS is faster when it's set to false.
  959. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  960. */
  961. public set computeParticleColor(val: boolean) {
  962. this._computeParticleColor = val;
  963. }
  964. /**
  965. * Tells to `setParticles()` to compute the particle textures or not.
  966. * Default value : true. The SPS is faster when it's set to false.
  967. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  968. */
  969. public set computeParticleTexture(val: boolean) {
  970. this._computeParticleTexture = val;
  971. }
  972. /**
  973. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  974. * Default value : false. The SPS is faster when it's set to false.
  975. * Note : the particle custom vertex positions aren't stored values.
  976. */
  977. public set computeParticleVertex(val: boolean) {
  978. this._computeParticleVertex = val;
  979. }
  980. /**
  981. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  982. */
  983. public set computeBoundingBox(val: boolean) {
  984. this._computeBoundingBox = val;
  985. }
  986. /**
  987. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  988. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  989. * Default : `true`
  990. */
  991. public set depthSortParticles(val: boolean) {
  992. this._depthSortParticles = val;
  993. }
  994. // getters
  995. public get computeParticleRotation(): boolean {
  996. return this._computeParticleRotation;
  997. }
  998. public get computeParticleColor(): boolean {
  999. return this._computeParticleColor;
  1000. }
  1001. public get computeParticleTexture(): boolean {
  1002. return this._computeParticleTexture;
  1003. }
  1004. public get computeParticleVertex(): boolean {
  1005. return this._computeParticleVertex;
  1006. }
  1007. public get computeBoundingBox(): boolean {
  1008. return this._computeBoundingBox;
  1009. }
  1010. public get depthSortParticles(): boolean {
  1011. return this._depthSortParticles;
  1012. }
  1013. // =======================================================================
  1014. // Particle behavior logic
  1015. // these following methods may be overwritten by the user to fit his needs
  1016. /**
  1017. * This function does nothing. It may be overwritten to set all the particle first values.
  1018. * The SPS doesn't call this function, you may have to call it by your own.
  1019. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  1020. */
  1021. public initParticles(): void {
  1022. }
  1023. /**
  1024. * This function does nothing. It may be overwritten to recycle a particle.
  1025. * The SPS doesn't call this function, you may have to call it by your own.
  1026. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  1027. */
  1028. public recycleParticle(particle: SolidParticle): SolidParticle {
  1029. return particle;
  1030. }
  1031. /**
  1032. * Updates a particle : this function should be overwritten by the user.
  1033. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  1034. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  1035. * ex : just set a particle position or velocity and recycle conditions
  1036. */
  1037. public updateParticle(particle: SolidParticle): SolidParticle {
  1038. return particle;
  1039. }
  1040. /**
  1041. * Updates a vertex of a particle : it can be overwritten by the user.
  1042. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  1043. * @param particle the current particle
  1044. * @param vertex the current index of the current particle
  1045. * @param pt the index of the current vertex in the particle shape
  1046. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  1047. * ex : just set a vertex particle position
  1048. */
  1049. public updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3 {
  1050. return vertex;
  1051. }
  1052. /**
  1053. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  1054. * This does nothing and may be overwritten by the user.
  1055. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1056. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1057. * @param update the boolean update value actually passed to setParticles()
  1058. */
  1059. public beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  1060. }
  1061. /**
  1062. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  1063. * This will be passed three parameters.
  1064. * This does nothing and may be overwritten by the user.
  1065. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1066. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1067. * @param update the boolean update value actually passed to setParticles()
  1068. */
  1069. public afterUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  1070. }
  1071. }
  1072. }