babylon.solidParticleSystem.ts 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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. // private members
  51. private _scene: Scene;
  52. private _positions: number[] = new Array<number>();
  53. private _indices: number[] = new Array<number>();
  54. private _normals: number[] = new Array<number>();
  55. private _colors: number[] = new Array<number>();
  56. private _uvs: number[] = new Array<number>();
  57. private _positions32: Float32Array;
  58. private _normals32: Float32Array; // updated normals for the VBO
  59. private _fixedNormal32: Float32Array; // initial normal references
  60. private _colors32: Float32Array;
  61. private _uvs32: Float32Array;
  62. private _index: number = 0; // indices index
  63. private _updatable: boolean = true;
  64. private _pickable: boolean = false;
  65. private _isVisibilityBoxLocked = false;
  66. private _alwaysVisible: boolean = false;
  67. private _shapeCounter: number = 0;
  68. private _copy: SolidParticle = new SolidParticle(null, null, null, null, null);
  69. private _shape: Vector3[];
  70. private _shapeUV: number[];
  71. private _color: Color4 = new Color4(0, 0, 0, 0);
  72. private _computeParticleColor: boolean = true;
  73. private _computeParticleTexture: boolean = true;
  74. private _computeParticleRotation: boolean = true;
  75. private _computeParticleVertex: boolean = false;
  76. private _computeBoundingBox: boolean = false;
  77. private _cam_axisZ: Vector3 = Vector3.Zero();
  78. private _cam_axisY: Vector3 = Vector3.Zero();
  79. private _cam_axisX: Vector3 = Vector3.Zero();
  80. private _axisX: Vector3 = Axis.X;
  81. private _axisY: Vector3 = Axis.Y;
  82. private _axisZ: Vector3 = Axis.Z;
  83. private _camera: TargetCamera;
  84. private _particle: SolidParticle;
  85. private _camDir: Vector3 = Vector3.Zero();
  86. private _rotMatrix: Matrix = new Matrix();
  87. private _invertMatrix: Matrix = new Matrix();
  88. private _rotated: Vector3 = Vector3.Zero();
  89. private _quaternion: Quaternion = new Quaternion();
  90. private _vertex: Vector3 = Vector3.Zero();
  91. private _normal: Vector3 = Vector3.Zero();
  92. private _yaw: number = 0.0;
  93. private _pitch: number = 0.0;
  94. private _roll: number = 0.0;
  95. private _halfroll: number = 0.0;
  96. private _halfpitch: number = 0.0;
  97. private _halfyaw: number = 0.0;
  98. private _sinRoll: number = 0.0;
  99. private _cosRoll: number = 0.0;
  100. private _sinPitch: number = 0.0;
  101. private _cosPitch: number = 0.0;
  102. private _sinYaw: number = 0.0;
  103. private _cosYaw: number = 0.0;
  104. private _w: number = 0.0;
  105. private _minimum: Vector3 = Tmp.Vector3[0];
  106. private _maximum: Vector3 = Tmp.Vector3[1];
  107. /**
  108. * Creates a SPS (Solid Particle System) object.
  109. * `name` (String) is the SPS name, this will be the underlying mesh name.
  110. * `scene` (Scene) is the scene in which the SPS is added.
  111. * `updatable` (default true) : if the SPS must be updatable or immutable.
  112. * `isPickable` (default false) : if the solid particles must be pickable.
  113. */
  114. constructor(name: string, scene: Scene, options?: { updatable?: boolean; isPickable?: boolean }) {
  115. this.name = name;
  116. this._scene = scene;
  117. this._camera = <TargetCamera>scene.activeCamera;
  118. this._pickable = options ? options.isPickable : false;
  119. if (options && options.updatable) {
  120. this._updatable = options.updatable;
  121. } else {
  122. this._updatable = true;
  123. }
  124. if (this._pickable) {
  125. this.pickedParticles = [];
  126. }
  127. }
  128. /**
  129. * Builds the SPS underlying mesh. Returns a standard Mesh.
  130. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  131. */
  132. public buildMesh(): Mesh {
  133. if (this.nbParticles === 0) {
  134. var triangle = MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  135. this.addShape(triangle, 1);
  136. triangle.dispose();
  137. }
  138. this._positions32 = new Float32Array(this._positions);
  139. this._uvs32 = new Float32Array(this._uvs);
  140. this._colors32 = new Float32Array(this._colors);
  141. if (this.recomputeNormals) {
  142. VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  143. }
  144. this._normals32 = new Float32Array(this._normals);
  145. this._fixedNormal32 = new Float32Array(this._normals);
  146. var vertexData = new VertexData();
  147. vertexData.set(this._positions32, VertexBuffer.PositionKind);
  148. vertexData.indices = this._indices;
  149. vertexData.set(this._normals32, VertexBuffer.NormalKind);
  150. if (this._uvs32) {
  151. vertexData.set(this._uvs32, VertexBuffer.UVKind);;
  152. }
  153. if (this._colors32) {
  154. vertexData.set(this._colors32, VertexBuffer.ColorKind);
  155. }
  156. var mesh = new Mesh(this.name, this._scene);
  157. vertexData.applyToMesh(mesh, this._updatable);
  158. this.mesh = mesh;
  159. this.mesh.isPickable = this._pickable;
  160. // free memory
  161. this._positions = null;
  162. this._normals = null;
  163. this._uvs = null;
  164. this._colors = null;
  165. if (!this._updatable) {
  166. this.particles.length = 0;
  167. }
  168. return mesh;
  169. }
  170. /**
  171. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  172. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  173. * Thus the particles generated from `digest()` have their property `position` set yet.
  174. * `mesh` ( Mesh ) is the mesh to be digested
  175. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  176. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  177. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  178. */
  179. public digest(mesh: Mesh, options?: { facetNb?: number; number?: number; delta?: number }): SolidParticleSystem {
  180. var size: number = (options && options.facetNb) || 1;
  181. var number: number = (options && options.number);
  182. var delta: number = (options && options.delta) || 0;
  183. var meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);
  184. var meshInd = mesh.getIndices();
  185. var meshUV = mesh.getVerticesData(VertexBuffer.UVKind);
  186. var meshCol = mesh.getVerticesData(VertexBuffer.ColorKind);
  187. var meshNor = mesh.getVerticesData(VertexBuffer.NormalKind);
  188. var f: number = 0; // facet counter
  189. var totalFacets: number = meshInd.length / 3; // a facet is a triangle, so 3 indices
  190. // compute size from number
  191. if (number) {
  192. number = (number > totalFacets) ? totalFacets : number;
  193. size = Math.round(totalFacets / number);
  194. delta = 0;
  195. } else {
  196. size = (size > totalFacets) ? totalFacets : size;
  197. }
  198. var facetPos: number[] = []; // submesh positions
  199. var facetInd: number[] = []; // submesh indices
  200. var facetUV: number[] = []; // submesh UV
  201. var facetCol: number[] = []; // submesh colors
  202. var barycenter: Vector3 = Tmp.Vector3[0];
  203. var rand: number;
  204. var sizeO: number = size;
  205. while (f < totalFacets) {
  206. size = sizeO + Math.floor((1 + delta) * Math.random());
  207. if (f > totalFacets - size) {
  208. size = totalFacets - f;
  209. }
  210. // reset temp arrays
  211. facetPos.length = 0;
  212. facetInd.length = 0;
  213. facetUV.length = 0;
  214. facetCol.length = 0;
  215. // iterate over "size" facets
  216. var fi: number = 0;
  217. for (var j = f * 3; j < (f + size) * 3; j++) {
  218. facetInd.push(fi);
  219. var i: number = meshInd[j];
  220. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  221. if (meshUV) {
  222. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  223. }
  224. if (meshCol) {
  225. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  226. }
  227. fi++;
  228. }
  229. // create a model shape for each single particle
  230. var idx: number = this.nbParticles;
  231. var shape: Vector3[] = this._posToShape(facetPos);
  232. var shapeUV: number[] = this._uvsToShapeUV(facetUV);
  233. // compute the barycenter of the shape
  234. var v: number;
  235. for (v = 0; v < shape.length; v++) {
  236. barycenter.addInPlace(shape[v]);
  237. }
  238. barycenter.scaleInPlace(1 / shape.length);
  239. // shift the shape from its barycenter to the origin
  240. for (v = 0; v < shape.length; v++) {
  241. shape[v].subtractInPlace(barycenter);
  242. }
  243. var modelShape = new ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  244. // add the particle in the SPS
  245. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  246. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  247. // initialize the particle position
  248. this.particles[this.nbParticles].position.addInPlace(barycenter);
  249. this._index += shape.length;
  250. idx++;
  251. this.nbParticles++;
  252. this._shapeCounter++;
  253. f += size;
  254. }
  255. return this;
  256. }
  257. //reset copy
  258. private _resetCopy() {
  259. this._copy.position.x = 0;
  260. this._copy.position.y = 0;
  261. this._copy.position.z = 0;
  262. this._copy.rotation.x = 0;
  263. this._copy.rotation.y = 0;
  264. this._copy.rotation.z = 0;
  265. this._copy.rotationQuaternion = null;
  266. this._copy.scaling.x = 1;
  267. this._copy.scaling.y = 1;
  268. this._copy.scaling.z = 1;
  269. this._copy.uvs.x = 0;
  270. this._copy.uvs.y = 0;
  271. this._copy.uvs.z = 1;
  272. this._copy.uvs.w = 1;
  273. this._copy.color = null;
  274. }
  275. // _meshBuilder : inserts the shape model in the global SPS mesh
  276. private _meshBuilder(p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options): void {
  277. var i;
  278. var u = 0;
  279. var c = 0;
  280. var n = 0;
  281. this._resetCopy();
  282. if (options && options.positionFunction) { // call to custom positionFunction
  283. options.positionFunction(this._copy, idx, idxInShape);
  284. }
  285. if (this._copy.rotationQuaternion) {
  286. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  287. } else {
  288. this._yaw = this._copy.rotation.y;
  289. this._pitch = this._copy.rotation.x;
  290. this._roll = this._copy.rotation.z;
  291. this._quaternionRotationYPR();
  292. }
  293. this._quaternionToRotationMatrix();
  294. for (i = 0; i < shape.length; i++) {
  295. this._vertex.x = shape[i].x;
  296. this._vertex.y = shape[i].y;
  297. this._vertex.z = shape[i].z;
  298. if (options && options.vertexFunction) {
  299. options.vertexFunction(this._copy, this._vertex, i);
  300. }
  301. this._vertex.x *= this._copy.scaling.x;
  302. this._vertex.y *= this._copy.scaling.y;
  303. this._vertex.z *= this._copy.scaling.z;
  304. Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  305. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  306. if (meshUV) {
  307. 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);
  308. u += 2;
  309. }
  310. if (this._copy.color) {
  311. this._color = this._copy.color;
  312. } else if (meshCol && meshCol[c] !== undefined) {
  313. this._color.r = meshCol[c];
  314. this._color.g = meshCol[c + 1];
  315. this._color.b = meshCol[c + 2];
  316. this._color.a = meshCol[c + 3];
  317. } else {
  318. this._color.r = 1;
  319. this._color.g = 1;
  320. this._color.b = 1;
  321. this._color.a = 1;
  322. }
  323. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  324. c += 4;
  325. if (!this.recomputeNormals && meshNor) {
  326. this._normal.x = meshNor[n];
  327. this._normal.y = meshNor[n + 1];
  328. this._normal.z = meshNor[n + 2];
  329. Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  330. normals.push(this._normal.x, this._normal.y, this._normal.z);
  331. n += 3;
  332. }
  333. }
  334. for (i = 0; i < meshInd.length; i++) {
  335. indices.push(p + meshInd[i]);
  336. }
  337. if (this._pickable) {
  338. var nbfaces = meshInd.length / 3;
  339. for (i = 0; i < nbfaces; i++) {
  340. this.pickedParticles.push({ idx: idx, faceId: i });
  341. }
  342. }
  343. }
  344. // returns a shape array from positions array
  345. private _posToShape(positions): Vector3[] {
  346. var shape = [];
  347. for (var i = 0; i < positions.length; i += 3) {
  348. shape.push(new Vector3(positions[i], positions[i + 1], positions[i + 2]));
  349. }
  350. return shape;
  351. }
  352. // returns a shapeUV array from a Vector4 uvs
  353. private _uvsToShapeUV(uvs): number[] {
  354. var shapeUV = [];
  355. if (uvs) {
  356. for (var i = 0; i < uvs.length; i++)
  357. shapeUV.push(uvs[i]);
  358. }
  359. return shapeUV;
  360. }
  361. // adds a new particle object in the particles array
  362. private _addParticle(idx: number, idxpos: number, model: ModelShape, shapeId: number, idxInShape: number): void {
  363. this.particles.push(new SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  364. }
  365. /**
  366. * Adds some particles to the SPS from the model shape. Returns the shape id.
  367. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  368. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  369. * `nb` (positive integer) the number of particles to be created from this model
  370. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  371. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  372. */
  373. public addShape(mesh: Mesh, nb: number, options?: { positionFunction?: any; vertexFunction?: any }): number {
  374. var meshPos = mesh.getVerticesData(VertexBuffer.PositionKind);
  375. var meshInd = mesh.getIndices();
  376. var meshUV = mesh.getVerticesData(VertexBuffer.UVKind);
  377. var meshCol = mesh.getVerticesData(VertexBuffer.ColorKind);
  378. var meshNor = mesh.getVerticesData(VertexBuffer.NormalKind);
  379. var shape = this._posToShape(meshPos);
  380. var shapeUV = this._uvsToShapeUV(meshUV);
  381. var posfunc = options ? options.positionFunction : null;
  382. var vtxfunc = options ? options.vertexFunction : null;
  383. var modelShape = new ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  384. // particles
  385. var idx = this.nbParticles;
  386. for (var i = 0; i < nb; i++) {
  387. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  388. if (this._updatable) {
  389. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  390. }
  391. this._index += shape.length;
  392. idx++;
  393. }
  394. this.nbParticles += nb;
  395. this._shapeCounter++;
  396. return this._shapeCounter - 1;
  397. }
  398. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  399. private _rebuildParticle(particle: SolidParticle): void {
  400. this._resetCopy();
  401. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  402. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  403. }
  404. if (this._copy.rotationQuaternion) {
  405. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  406. } else {
  407. this._yaw = this._copy.rotation.y;
  408. this._pitch = this._copy.rotation.x;
  409. this._roll = this._copy.rotation.z;
  410. this._quaternionRotationYPR();
  411. }
  412. this._quaternionToRotationMatrix();
  413. this._shape = particle._model._shape;
  414. for (var pt = 0; pt < this._shape.length; pt++) {
  415. this._vertex.x = this._shape[pt].x;
  416. this._vertex.y = this._shape[pt].y;
  417. this._vertex.z = this._shape[pt].z;
  418. if (particle._model._vertexFunction) {
  419. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  420. }
  421. this._vertex.x *= this._copy.scaling.x;
  422. this._vertex.y *= this._copy.scaling.y;
  423. this._vertex.z *= this._copy.scaling.z;
  424. Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  425. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  426. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  427. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  428. }
  429. particle.position.x = 0;
  430. particle.position.y = 0;
  431. particle.position.z = 0;
  432. particle.rotation.x = 0;
  433. particle.rotation.y = 0;
  434. particle.rotation.z = 0;
  435. particle.rotationQuaternion = null;
  436. particle.scaling.x = 1;
  437. particle.scaling.y = 1;
  438. particle.scaling.z = 1;
  439. }
  440. /**
  441. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  442. */
  443. public rebuildMesh(): void {
  444. for (var p = 0; p < this.particles.length; p++) {
  445. this._rebuildParticle(this.particles[p]);
  446. }
  447. this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);
  448. }
  449. /**
  450. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  451. * This method calls `updateParticle()` for each particle of the SPS.
  452. * For an animated SPS, it is usually called within the render loop.
  453. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  454. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  455. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  456. */
  457. public setParticles(start: number = 0, end: number = this.nbParticles - 1, update: boolean = true): void {
  458. if (!this._updatable) {
  459. return;
  460. }
  461. // custom beforeUpdate
  462. this.beforeUpdateParticles(start, end, update);
  463. this._cam_axisX.x = 1.0;
  464. this._cam_axisX.y = 0.0;
  465. this._cam_axisX.z = 0.0;
  466. this._cam_axisY.x = 0.0;
  467. this._cam_axisY.y = 1.0;
  468. this._cam_axisY.z = 0.0;
  469. this._cam_axisZ.x = 0.0;
  470. this._cam_axisZ.y = 0.0;
  471. this._cam_axisZ.z = 1.0;
  472. // if the particles will always face the camera
  473. if (this.billboard) {
  474. // compute the camera position and un-rotate it by the current mesh rotation
  475. this._yaw = this.mesh.rotation.y;
  476. this._pitch = this.mesh.rotation.x;
  477. this._roll = this.mesh.rotation.z;
  478. this._quaternionRotationYPR();
  479. this._quaternionToRotationMatrix();
  480. this._rotMatrix.invertToRef(this._invertMatrix);
  481. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  482. Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  483. this._cam_axisZ.normalize();
  484. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  485. Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  486. Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  487. this._cam_axisY.normalize();
  488. this._cam_axisX.normalize();
  489. }
  490. Matrix.IdentityToRef(this._rotMatrix);
  491. var idx = 0;
  492. var index = 0;
  493. var colidx = 0;
  494. var colorIndex = 0;
  495. var uvidx = 0;
  496. var uvIndex = 0;
  497. var pt = 0;
  498. if (this._computeBoundingBox) {
  499. Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  500. Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  501. }
  502. // particle loop
  503. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  504. for (var p = start; p <= end; p++) {
  505. this._particle = this.particles[p];
  506. this._shape = this._particle._model._shape;
  507. this._shapeUV = this._particle._model._shapeUV;
  508. // call to custom user function to update the particle properties
  509. this.updateParticle(this._particle);
  510. if (this._particle.isVisible) {
  511. // particle rotation matrix
  512. if (this.billboard) {
  513. this._particle.rotation.x = 0.0;
  514. this._particle.rotation.y = 0.0;
  515. }
  516. if (this._computeParticleRotation || this.billboard) {
  517. if (this._particle.rotationQuaternion) {
  518. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  519. } else {
  520. this._yaw = this._particle.rotation.y;
  521. this._pitch = this._particle.rotation.x;
  522. this._roll = this._particle.rotation.z;
  523. this._quaternionRotationYPR();
  524. }
  525. this._quaternionToRotationMatrix();
  526. }
  527. // particle vertex loop
  528. for (pt = 0; pt < this._shape.length; pt++) {
  529. idx = index + pt * 3;
  530. colidx = colorIndex + pt * 4;
  531. uvidx = uvIndex + pt * 2;
  532. this._vertex.x = this._shape[pt].x;
  533. this._vertex.y = this._shape[pt].y;
  534. this._vertex.z = this._shape[pt].z;
  535. if (this._computeParticleVertex) {
  536. this.updateParticleVertex(this._particle, this._vertex, pt);
  537. }
  538. // positions
  539. this._vertex.x *= this._particle.scaling.x;
  540. this._vertex.y *= this._particle.scaling.y;
  541. this._vertex.z *= this._particle.scaling.z;
  542. this._w = (this._vertex.x * this._rotMatrix.m[3]) + (this._vertex.y * this._rotMatrix.m[7]) + (this._vertex.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  543. this._rotated.x = ((this._vertex.x * this._rotMatrix.m[0]) + (this._vertex.y * this._rotMatrix.m[4]) + (this._vertex.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  544. this._rotated.y = ((this._vertex.x * this._rotMatrix.m[1]) + (this._vertex.y * this._rotMatrix.m[5]) + (this._vertex.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  545. this._rotated.z = ((this._vertex.x * this._rotMatrix.m[2]) + (this._vertex.y * this._rotMatrix.m[6]) + (this._vertex.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  546. 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;
  547. 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;
  548. 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;
  549. if (this._computeBoundingBox) {
  550. if (this._positions32[idx] < this._minimum.x) {
  551. this._minimum.x = this._positions32[idx];
  552. }
  553. if (this._positions32[idx] > this._maximum.x) {
  554. this._maximum.x = this._positions32[idx];
  555. }
  556. if (this._positions32[idx + 1] < this._minimum.y) {
  557. this._minimum.y = this._positions32[idx + 1];
  558. }
  559. if (this._positions32[idx + 1] > this._maximum.y) {
  560. this._maximum.y = this._positions32[idx + 1];
  561. }
  562. if (this._positions32[idx + 2] < this._minimum.z) {
  563. this._minimum.z = this._positions32[idx + 2];
  564. }
  565. if (this._positions32[idx + 2] > this._maximum.z) {
  566. this._maximum.z = this._positions32[idx + 2];
  567. }
  568. }
  569. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  570. if (!this._computeParticleVertex) {
  571. this._normal.x = this._fixedNormal32[idx];
  572. this._normal.y = this._fixedNormal32[idx + 1];
  573. this._normal.z = this._fixedNormal32[idx + 2];
  574. this._w = (this._normal.x * this._rotMatrix.m[3]) + (this._normal.y * this._rotMatrix.m[7]) + (this._normal.z * this._rotMatrix.m[11]) + this._rotMatrix.m[15];
  575. this._rotated.x = ((this._normal.x * this._rotMatrix.m[0]) + (this._normal.y * this._rotMatrix.m[4]) + (this._normal.z * this._rotMatrix.m[8]) + this._rotMatrix.m[12]) / this._w;
  576. this._rotated.y = ((this._normal.x * this._rotMatrix.m[1]) + (this._normal.y * this._rotMatrix.m[5]) + (this._normal.z * this._rotMatrix.m[9]) + this._rotMatrix.m[13]) / this._w;
  577. this._rotated.z = ((this._normal.x * this._rotMatrix.m[2]) + (this._normal.y * this._rotMatrix.m[6]) + (this._normal.z * this._rotMatrix.m[10]) + this._rotMatrix.m[14]) / this._w;
  578. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  579. 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;
  580. 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;
  581. }
  582. if (this._computeParticleColor) {
  583. this._colors32[colidx] = this._particle.color.r;
  584. this._colors32[colidx + 1] = this._particle.color.g;
  585. this._colors32[colidx + 2] = this._particle.color.b;
  586. this._colors32[colidx + 3] = this._particle.color.a;
  587. }
  588. if (this._computeParticleTexture) {
  589. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  590. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  591. }
  592. }
  593. }
  594. // particle not visible : scaled to zero and positioned to the camera position
  595. else {
  596. for (pt = 0; pt < this._shape.length; pt++) {
  597. idx = index + pt * 3;
  598. colidx = colorIndex + pt * 4;
  599. uvidx = uvIndex + pt * 2;
  600. this._positions32[idx] = this._camera.position.x;
  601. this._positions32[idx + 1] = this._camera.position.y;
  602. this._positions32[idx + 2] = this._camera.position.z;
  603. this._normals32[idx] = 0.0;
  604. this._normals32[idx + 1] = 0.0;
  605. this._normals32[idx + 2] = 0.0;
  606. if (this._computeParticleColor) {
  607. this._colors32[colidx] = this._particle.color.r;
  608. this._colors32[colidx + 1] = this._particle.color.g;
  609. this._colors32[colidx + 2] = this._particle.color.b;
  610. this._colors32[colidx + 3] = this._particle.color.a;
  611. }
  612. if (this._computeParticleTexture) {
  613. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  614. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  615. }
  616. }
  617. }
  618. // increment indexes for the next particle
  619. index = idx + 3;
  620. colorIndex = colidx + 4;
  621. uvIndex = uvidx + 2;
  622. }
  623. // if the VBO must be updated
  624. if (update) {
  625. if (this._computeParticleColor) {
  626. this.mesh.updateVerticesData(VertexBuffer.ColorKind, this._colors32, false, false);
  627. }
  628. if (this._computeParticleTexture) {
  629. this.mesh.updateVerticesData(VertexBuffer.UVKind, this._uvs32, false, false);
  630. }
  631. this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);
  632. if (!this.mesh.areNormalsFrozen) {
  633. if (this._computeParticleVertex) {
  634. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  635. VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  636. for (var i = 0; i < this._normals32.length; i++) {
  637. this._fixedNormal32[i] = this._normals32[i];
  638. }
  639. }
  640. this.mesh.updateVerticesData(VertexBuffer.NormalKind, this._normals32, false, false);
  641. }
  642. }
  643. if (this._computeBoundingBox) {
  644. this.mesh._boundingInfo = new BoundingInfo(this._minimum, this._maximum);
  645. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  646. }
  647. this.afterUpdateParticles(start, end, update);
  648. }
  649. private _quaternionRotationYPR(): void {
  650. this._halfroll = this._roll * 0.5;
  651. this._halfpitch = this._pitch * 0.5;
  652. this._halfyaw = this._yaw * 0.5;
  653. this._sinRoll = Math.sin(this._halfroll);
  654. this._cosRoll = Math.cos(this._halfroll);
  655. this._sinPitch = Math.sin(this._halfpitch);
  656. this._cosPitch = Math.cos(this._halfpitch);
  657. this._sinYaw = Math.sin(this._halfyaw);
  658. this._cosYaw = Math.cos(this._halfyaw);
  659. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  660. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  661. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  662. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  663. }
  664. private _quaternionToRotationMatrix(): void {
  665. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  666. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  667. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  668. this._rotMatrix.m[3] = 0;
  669. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  670. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  671. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  672. this._rotMatrix.m[7] = 0;
  673. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  674. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  675. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  676. this._rotMatrix.m[11] = 0;
  677. this._rotMatrix.m[12] = 0;
  678. this._rotMatrix.m[13] = 0;
  679. this._rotMatrix.m[14] = 0;
  680. this._rotMatrix.m[15] = 1.0;
  681. }
  682. /**
  683. * Disposes the SPS
  684. */
  685. public dispose(): void {
  686. this.mesh.dispose();
  687. this.vars = null;
  688. // drop references to internal big arrays for the GC
  689. this._positions = null;
  690. this._indices = null;
  691. this._normals = null;
  692. this._uvs = null;
  693. this._colors = null;
  694. this._positions32 = null;
  695. this._normals32 = null;
  696. this._fixedNormal32 = null;
  697. this._uvs32 = null;
  698. this._colors32 = null;
  699. this.pickedParticles = null;
  700. }
  701. /**
  702. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  703. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  704. */
  705. public refreshVisibleSize(): void {
  706. if (!this._isVisibilityBoxLocked) {
  707. this.mesh.refreshBoundingInfo();
  708. }
  709. }
  710. /**
  711. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  712. * @param size the size (float) of the visibility box
  713. * note : this doesn't lock the SPS mesh bounding box.
  714. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  715. */
  716. public setVisibilityBox(size: number): void {
  717. var vis = size / 2;
  718. this.mesh._boundingInfo = new BoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));
  719. }
  720. // getter and setter
  721. public get isAlwaysVisible(): boolean {
  722. return this._alwaysVisible;
  723. }
  724. /**
  725. * Sets the SPS as always visible or not
  726. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  727. */
  728. public set isAlwaysVisible(val: boolean) {
  729. this._alwaysVisible = val;
  730. this.mesh.alwaysSelectAsActiveMesh = val;
  731. }
  732. /**
  733. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  734. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  735. */
  736. public set isVisibilityBoxLocked(val: boolean) {
  737. this._isVisibilityBoxLocked = val;
  738. this.mesh.getBoundingInfo().isLocked = val;
  739. }
  740. public get isVisibilityBoxLocked(): boolean {
  741. return this._isVisibilityBoxLocked;
  742. }
  743. // Optimizer setters
  744. /**
  745. * Tells to `setParticles()` to compute the particle rotations or not.
  746. * Default value : true. The SPS is faster when it's set to false.
  747. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  748. */
  749. public set computeParticleRotation(val: boolean) {
  750. this._computeParticleRotation = val;
  751. }
  752. /**
  753. * Tells to `setParticles()` to compute the particle colors or not.
  754. * Default value : true. The SPS is faster when it's set to false.
  755. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  756. */
  757. public set computeParticleColor(val: boolean) {
  758. this._computeParticleColor = val;
  759. }
  760. /**
  761. * Tells to `setParticles()` to compute the particle textures or not.
  762. * Default value : true. The SPS is faster when it's set to false.
  763. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  764. */
  765. public set computeParticleTexture(val: boolean) {
  766. this._computeParticleTexture = val;
  767. }
  768. /**
  769. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  770. * Default value : false. The SPS is faster when it's set to false.
  771. * Note : the particle custom vertex positions aren't stored values.
  772. */
  773. public set computeParticleVertex(val: boolean) {
  774. this._computeParticleVertex = val;
  775. }
  776. /**
  777. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  778. */
  779. public set computeBoundingBox(val: boolean) {
  780. this._computeBoundingBox = val;
  781. }
  782. // getters
  783. public get computeParticleRotation(): boolean {
  784. return this._computeParticleRotation;
  785. }
  786. public get computeParticleColor(): boolean {
  787. return this._computeParticleColor;
  788. }
  789. public get computeParticleTexture(): boolean {
  790. return this._computeParticleTexture;
  791. }
  792. public get computeParticleVertex(): boolean {
  793. return this._computeParticleVertex;
  794. }
  795. public get computeBoundingBox(): boolean {
  796. return this._computeBoundingBox;
  797. }
  798. // =======================================================================
  799. // Particle behavior logic
  800. // these following methods may be overwritten by the user to fit his needs
  801. /**
  802. * This function does nothing. It may be overwritten to set all the particle first values.
  803. * The SPS doesn't call this function, you may have to call it by your own.
  804. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  805. */
  806. public initParticles(): void {
  807. }
  808. /**
  809. * This function does nothing. It may be overwritten to recycle a particle.
  810. * The SPS doesn't call this function, you may have to call it by your own.
  811. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  812. */
  813. public recycleParticle(particle: SolidParticle): SolidParticle {
  814. return particle;
  815. }
  816. /**
  817. * Updates a particle : this function should be overwritten by the user.
  818. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  819. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  820. * ex : just set a particle position or velocity and recycle conditions
  821. */
  822. public updateParticle(particle: SolidParticle): SolidParticle {
  823. return particle;
  824. }
  825. /**
  826. * Updates a vertex of a particle : it can be overwritten by the user.
  827. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  828. * @param particle the current particle
  829. * @param vertex the current index of the current particle
  830. * @param pt the index of the current vertex in the particle shape
  831. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  832. * ex : just set a vertex particle position
  833. */
  834. public updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3 {
  835. return vertex;
  836. }
  837. /**
  838. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  839. * This does nothing and may be overwritten by the user.
  840. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  841. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  842. * @param update the boolean update value actually passed to setParticles()
  843. */
  844. public beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  845. }
  846. /**
  847. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  848. * This will be passed three parameters.
  849. * This does nothing and may be overwritten by the user.
  850. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  851. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  852. * @param update the boolean update value actually passed to setParticles()
  853. */
  854. public afterUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  855. }
  856. }
  857. }