babylon.solidParticleSystem.ts 45 KB

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