solidParticleSystem.ts 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  1. import { Nullable, IndicesArray, FloatArray } from "../types";
  2. import { Vector3, Matrix, TmpVectors, Quaternion } from "../Maths/math.vector";
  3. import { Color4 } from '../Maths/math.color';
  4. import { VertexBuffer } from "../Meshes/buffer";
  5. import { VertexData } from "../Meshes/mesh.vertexData";
  6. import { Mesh } from "../Meshes/mesh";
  7. import { DiscBuilder } from "../Meshes/Builders/discBuilder";
  8. import { EngineStore } from "../Engines/engineStore";
  9. import { Scene, IDisposable } from "../scene";
  10. import { DepthSortedParticle, SolidParticle, ModelShape } from "./solidParticle";
  11. import { TargetCamera } from "../Cameras/targetCamera";
  12. import { BoundingInfo } from "../Culling/boundingInfo";
  13. import { Axis } from '../Maths/math.axis';
  14. import { SubMesh } from '../Meshes/subMesh';
  15. import { Material } from '../Materials/material';
  16. import { StandardMaterial } from '../Materials/standardMaterial';
  17. import { MultiMaterial } from '../Materials/multiMaterial';
  18. /**
  19. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  20. *As it is just a mesh, the SPS has all the same properties than any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  21. * The SPS is also a particle system. It provides some methods to manage the particles.
  22. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  23. *
  24. * Full documentation here : http://doc.babylonjs.com/how_to/Solid_Particle_System
  25. */
  26. export class SolidParticleSystem implements IDisposable {
  27. /**
  28. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  29. * Example : var p = SPS.particles[i];
  30. */
  31. public particles: SolidParticle[] = new Array<SolidParticle>();
  32. /**
  33. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  34. */
  35. public nbParticles: number = 0;
  36. /**
  37. * If the particles must ever face the camera (default false). Useful for planar particles.
  38. */
  39. public billboard: boolean = false;
  40. /**
  41. * Recompute normals when adding a shape
  42. */
  43. public recomputeNormals: boolean = false;
  44. /**
  45. * This a counter ofr your own usage. It's not set by any SPS functions.
  46. */
  47. public counter: number = 0;
  48. /**
  49. * The SPS name. This name is also given to the underlying mesh.
  50. */
  51. public name: string;
  52. /**
  53. * The SPS mesh. It's a standard BJS Mesh, so all the methods from the Mesh class are avalaible.
  54. */
  55. public mesh: Mesh;
  56. /**
  57. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58. * Please read : http://doc.babylonjs.com/how_to/Solid_Particle_System#garbage-collector-concerns
  59. */
  60. public vars: any = {};
  61. /**
  62. * This array is populated when the SPS is set as 'pickable'.
  63. * Each key of this array is a `faceId` value that you can get from a pickResult object.
  64. * Each element of this array is an object `{idx: int, faceId: int}`.
  65. * `idx` is the picked particle index in the `SPS.particles` array
  66. * `faceId` is the picked face index counted within this particle.
  67. * Please read : http://doc.babylonjs.com/how_to/Solid_Particle_System#pickable-particles
  68. */
  69. public pickedParticles: { idx: number; faceId: number }[];
  70. /**
  71. * This array is populated when `enableDepthSort` is set to true.
  72. * Each element of this array is an instance of the class DepthSortedParticle.
  73. */
  74. public depthSortedParticles: DepthSortedParticle[];
  75. /**
  76. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  77. * @hidden
  78. */
  79. public _bSphereOnly: boolean = false;
  80. /**
  81. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  82. * @hidden
  83. */
  84. public _bSphereRadiusFactor: number = 1.0;
  85. private _scene: Scene;
  86. private _positions: number[] = new Array<number>();
  87. private _indices: number[] = new Array<number>();
  88. private _normals: number[] = new Array<number>();
  89. private _colors: number[] = new Array<number>();
  90. private _uvs: number[] = new Array<number>();
  91. private _indices32: IndicesArray; // used as depth sorted array if depth sort enabled, else used as typed indices
  92. private _positions32: Float32Array; // updated positions for the VBO
  93. private _normals32: Float32Array; // updated normals for the VBO
  94. private _fixedNormal32: Float32Array; // initial normal references
  95. private _colors32: Float32Array;
  96. private _uvs32: Float32Array;
  97. private _index: number = 0; // indices index
  98. private _updatable: boolean = true;
  99. private _pickable: boolean = false;
  100. private _isVisibilityBoxLocked = false;
  101. private _alwaysVisible: boolean = false;
  102. private _depthSort: boolean = false;
  103. private _expandable: boolean = false;
  104. private _shapeCounter: number = 0;
  105. private _copy: SolidParticle = new SolidParticle(0, 0, 0, 0, null, 0, 0, this);
  106. private _color: Color4 = new Color4(0, 0, 0, 0);
  107. private _computeParticleColor: boolean = true;
  108. private _computeParticleTexture: boolean = true;
  109. private _computeParticleRotation: boolean = true;
  110. private _computeParticleVertex: boolean = false;
  111. private _computeBoundingBox: boolean = false;
  112. private _depthSortParticles: boolean = true;
  113. private _camera: TargetCamera;
  114. private _mustUnrotateFixedNormals = false;
  115. private _particlesIntersect: boolean = false;
  116. private _needs32Bits: boolean = false;
  117. private _isNotBuilt: boolean = true;
  118. private _lastParticleId: number = 0;
  119. private _idxOfId: number[] = []; // array : key = particle.id / value = particle.idx
  120. private _multimaterialEnabled: boolean = false;
  121. private _useModelMaterial: boolean = false;
  122. private _indicesByMaterial: number[];
  123. private _materialIndexes: number[];
  124. private _depthSortFunction = (p1: DepthSortedParticle, p2: DepthSortedParticle) => p2.sqDistance - p1.sqDistance;
  125. private _materialSortFunction = (p1: DepthSortedParticle, p2: DepthSortedParticle) => p1.materialIndex - p2.materialIndex;
  126. private _materials: Material[];
  127. private _multimaterial: MultiMaterial;
  128. private _materialIndexesById: any;
  129. private _defaultMaterial: Material;
  130. /**
  131. * Creates a SPS (Solid Particle System) object.
  132. * @param name (String) is the SPS name, this will be the underlying mesh name.
  133. * @param scene (Scene) is the scene in which the SPS is added.
  134. * @param options defines the options of the sps e.g.
  135. * * updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  136. * * isPickable (optional boolean, default false) : if the solid particles must be pickable.
  137. * * enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  138. * * useModelMaterial (optional boolean, defaut false) : if the model materials must be used to create the SPS multimaterial. This enables the multimaterial supports of the SPS.
  139. * * enableMultiMaterial (optional boolean, default false) : if the solid particles can be given different materials.
  140. * * expandable (optional boolean, default false) : if particles can still be added after the initial SPS mesh creation.
  141. * * particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  142. * * boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  143. * * bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  144. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  145. */
  146. constructor(name: string, scene: Scene, options?: { updatable?: boolean; isPickable?: boolean; enableDepthSort?: boolean; particleIntersection?: boolean; boundingSphereOnly?: boolean; bSphereRadiusFactor?: number; expandable?: boolean; useModelMaterial?: boolean; enableMultiMaterial?: boolean; }) {
  147. this.name = name;
  148. this._scene = scene || EngineStore.LastCreatedScene;
  149. this._camera = <TargetCamera>scene.activeCamera;
  150. this._pickable = options ? <boolean>options.isPickable : false;
  151. this._depthSort = options ? <boolean>options.enableDepthSort : false;
  152. this._multimaterialEnabled = options ? <boolean>options.enableMultiMaterial : false;
  153. this._useModelMaterial = options ? <boolean>options.useModelMaterial : false;
  154. this._multimaterialEnabled = (this._useModelMaterial) ? true : this._multimaterialEnabled;
  155. this._expandable = options ? <boolean>options.expandable : false;
  156. this._particlesIntersect = options ? <boolean>options.particleIntersection : false;
  157. this._bSphereOnly = options ? <boolean>options.boundingSphereOnly : false;
  158. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  159. if (options && options.updatable !== undefined) {
  160. this._updatable = options.updatable;
  161. } else {
  162. this._updatable = true;
  163. }
  164. if (this._pickable) {
  165. this.pickedParticles = [];
  166. }
  167. if (this._depthSort || this._multimaterialEnabled) {
  168. this.depthSortedParticles = [];
  169. }
  170. if (this._multimaterialEnabled) {
  171. this._multimaterial = new MultiMaterial(this.name + "MultiMaterial", this._scene);
  172. this._materials = [];
  173. this._materialIndexesById = {};
  174. }
  175. }
  176. /**
  177. * Builds the SPS underlying mesh. Returns a standard Mesh.
  178. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  179. * @returns the created mesh
  180. */
  181. public buildMesh(): Mesh {
  182. if (!this._isNotBuilt && this.mesh) {
  183. return this.mesh;
  184. }
  185. if (this.nbParticles === 0 && !this.mesh) {
  186. var triangle = DiscBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  187. this.addShape(triangle, 1);
  188. triangle.dispose();
  189. }
  190. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  191. this._positions32 = new Float32Array(this._positions);
  192. this._uvs32 = new Float32Array(this._uvs);
  193. this._colors32 = new Float32Array(this._colors);
  194. if (!this.mesh) { // in case it's already expanded
  195. var mesh = new Mesh(this.name, this._scene);
  196. this.mesh = mesh;
  197. }
  198. if (!this._updatable && this._multimaterialEnabled) {
  199. this._sortParticlesByMaterial(); // this may reorder the indices32
  200. }
  201. if (this.recomputeNormals) {
  202. VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  203. }
  204. this._normals32 = new Float32Array(this._normals);
  205. this._fixedNormal32 = new Float32Array(this._normals);
  206. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  207. this._unrotateFixedNormals();
  208. }
  209. var vertexData = new VertexData();
  210. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  211. vertexData.set(this._positions32, VertexBuffer.PositionKind);
  212. vertexData.set(this._normals32, VertexBuffer.NormalKind);
  213. if (this._uvs32.length > 0) {
  214. vertexData.set(this._uvs32, VertexBuffer.UVKind);
  215. }
  216. if (this._colors32.length > 0) {
  217. vertexData.set(this._colors32, VertexBuffer.ColorKind);
  218. }
  219. vertexData.applyToMesh(this.mesh, this._updatable);
  220. this.mesh.isPickable = this._pickable;
  221. if (this._multimaterialEnabled) {
  222. this.setMultiMaterial(this._materials);
  223. }
  224. if (!this._expandable) {
  225. // free memory
  226. if (!this._depthSort && !this._multimaterialEnabled) {
  227. (<any>this._indices) = null;
  228. }
  229. (<any>this._positions) = null;
  230. (<any>this._normals) = null;
  231. (<any>this._uvs) = null;
  232. (<any>this._colors) = null;
  233. if (!this._updatable) {
  234. this.particles.length = 0;
  235. }
  236. }
  237. this._isNotBuilt = false;
  238. this.recomputeNormals = false;
  239. return this.mesh;
  240. }
  241. /**
  242. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  243. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  244. * Thus the particles generated from `digest()` have their property `position` set yet.
  245. * @param mesh ( Mesh ) is the mesh to be digested
  246. * @param options {facetNb} (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  247. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  248. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  249. * {storage} (optional existing array) is an array where the particles will be stored for a further use instead of being inserted in the SPS.
  250. * @returns the current SPS
  251. */
  252. public digest(mesh: Mesh, options?: { facetNb?: number; number?: number; delta?: number; storage?: [] }): SolidParticleSystem {
  253. var size: number = (options && options.facetNb) || 1;
  254. var number: number = (options && options.number) || 0;
  255. var delta: number = (options && options.delta) || 0;
  256. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  257. var meshInd = <IndicesArray>mesh.getIndices();
  258. var meshUV = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  259. var meshCol = <FloatArray>mesh.getVerticesData(VertexBuffer.ColorKind);
  260. var meshNor = <FloatArray>mesh.getVerticesData(VertexBuffer.NormalKind);
  261. var storage = (options && options.storage) ? options.storage : null;
  262. var f: number = 0; // facet counter
  263. var totalFacets: number = meshInd.length / 3; // a facet is a triangle, so 3 indices
  264. // compute size from number
  265. if (number) {
  266. number = (number > totalFacets) ? totalFacets : number;
  267. size = Math.round(totalFacets / number);
  268. delta = 0;
  269. } else {
  270. size = (size > totalFacets) ? totalFacets : size;
  271. }
  272. var facetPos: number[] = []; // submesh positions
  273. var facetNor: number[] = [];
  274. var facetInd: number[] = []; // submesh indices
  275. var facetUV: number[] = []; // submesh UV
  276. var facetCol: number[] = []; // submesh colors
  277. var barycenter: Vector3 = Vector3.Zero();
  278. var sizeO: number = size;
  279. while (f < totalFacets) {
  280. size = sizeO + Math.floor((1 + delta) * Math.random());
  281. if (f > totalFacets - size) {
  282. size = totalFacets - f;
  283. }
  284. // reset temp arrays
  285. facetPos.length = 0;
  286. facetNor.length = 0;
  287. facetInd.length = 0;
  288. facetUV.length = 0;
  289. facetCol.length = 0;
  290. // iterate over "size" facets
  291. var fi: number = 0;
  292. for (var j = f * 3; j < (f + size) * 3; j++) {
  293. facetInd.push(fi);
  294. var i: number = meshInd[j];
  295. var i3: number = i * 3;
  296. facetPos.push(meshPos[i3], meshPos[i3 + 1], meshPos[i3 + 2]);
  297. facetNor.push(meshNor[i3], meshNor[i3 + 1], meshNor[i3 + 2]);
  298. if (meshUV) {
  299. var i2: number = i * 2;
  300. facetUV.push(meshUV[i2], meshUV[i2 + 1]);
  301. }
  302. if (meshCol) {
  303. var i4: number = i * 4;
  304. facetCol.push(meshCol[i4], meshCol[i4 + 1], meshCol[i4 + 2], meshCol[i4 + 3]);
  305. }
  306. fi++;
  307. }
  308. // create a model shape for each single particle
  309. var idx: number = this.nbParticles;
  310. var shape: Vector3[] = this._posToShape(facetPos);
  311. var shapeUV: number[] = this._uvsToShapeUV(facetUV);
  312. var shapeInd = Array.from(facetInd);
  313. var shapeCol = Array.from(facetCol);
  314. var shapeNor = Array.from(facetNor);
  315. // compute the barycenter of the shape
  316. barycenter.copyFromFloats(0, 0, 0);
  317. var v: number;
  318. for (v = 0; v < shape.length; v++) {
  319. barycenter.addInPlace(shape[v]);
  320. }
  321. barycenter.scaleInPlace(1 / shape.length);
  322. // shift the shape from its barycenter to the origin
  323. // and compute the BBox required for intersection.
  324. var minimum: Vector3 = new Vector3(Infinity, Infinity, Infinity);
  325. var maximum: Vector3 = new Vector3(-Infinity, -Infinity, -Infinity);
  326. for (v = 0; v < shape.length; v++) {
  327. shape[v].subtractInPlace(barycenter);
  328. minimum.minimizeInPlaceFromFloats(shape[v].x, shape[v].y, shape[v].z);
  329. maximum.maximizeInPlaceFromFloats(shape[v].x, shape[v].y, shape[v].z);
  330. }
  331. var bInfo;
  332. if (this._particlesIntersect) {
  333. bInfo = new BoundingInfo(minimum, maximum);
  334. }
  335. var material = null;
  336. if (this._useModelMaterial) {
  337. material = (mesh.material) ? mesh.material : this._setDefaultMaterial();
  338. }
  339. var modelShape = new ModelShape(this._shapeCounter, shape, shapeInd, shapeNor, shapeCol, shapeUV, null, null, material);
  340. // add the particle in the SPS
  341. var currentPos = this._positions.length;
  342. var currentInd = this._indices.length;
  343. this._meshBuilder(this._index, currentInd, shape, this._positions, shapeInd, this._indices, facetUV, this._uvs, shapeCol, this._colors, shapeNor, this._normals, idx, 0, null, modelShape);
  344. this._addParticle(idx, this._lastParticleId, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo, storage);
  345. // initialize the particle position
  346. this.particles[this.nbParticles].position.addInPlace(barycenter);
  347. if (!storage) {
  348. this._index += shape.length;
  349. idx++;
  350. this.nbParticles++;
  351. this._lastParticleId++;
  352. }
  353. this._shapeCounter++;
  354. f += size;
  355. }
  356. this._isNotBuilt = true; // buildMesh() is now expected for setParticles() to work
  357. return this;
  358. }
  359. /**
  360. * Unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  361. * @hidden
  362. */
  363. private _unrotateFixedNormals() {
  364. var index = 0;
  365. var idx = 0;
  366. const tmpNormal = TmpVectors.Vector3[0];
  367. const quaternion = TmpVectors.Quaternion[0];
  368. const invertedRotMatrix = TmpVectors.Matrix[0];
  369. for (var p = 0; p < this.particles.length; p++) {
  370. const particle = this.particles[p];
  371. const shape = particle._model._shape;
  372. // computing the inverse of the rotation matrix from the quaternion
  373. // is equivalent to computing the matrix of the inverse quaternion, i.e of the conjugate quaternion
  374. if (particle.rotationQuaternion) {
  375. particle.rotationQuaternion.conjugateToRef(quaternion);
  376. }
  377. else {
  378. const rotation = particle.rotation;
  379. Quaternion.RotationYawPitchRollToRef(rotation.y, rotation.x, rotation.z, quaternion);
  380. quaternion.conjugateInPlace();
  381. }
  382. quaternion.toRotationMatrix(invertedRotMatrix);
  383. for (var pt = 0; pt < shape.length; pt++) {
  384. idx = index + pt * 3;
  385. Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], invertedRotMatrix, tmpNormal);
  386. tmpNormal.toArray(this._fixedNormal32, idx);
  387. }
  388. index = idx + 3;
  389. }
  390. }
  391. /**
  392. * Resets the temporary working copy particle
  393. * @hidden
  394. */
  395. private _resetCopy() {
  396. const copy = this._copy;
  397. copy.position.setAll(0);
  398. copy.rotation.setAll(0);
  399. copy.rotationQuaternion = null;
  400. copy.scaling.setAll(1);
  401. copy.uvs.copyFromFloats(0.0, 0.0, 1.0, 1.0);
  402. copy.color = null;
  403. copy.translateFromPivot = false;
  404. copy.materialIndex = null;
  405. }
  406. /**
  407. * Inserts the shape model geometry in the global SPS mesh by updating the positions, indices, normals, colors, uvs arrays
  408. * @param p the current index in the positions array to be updated
  409. * @param ind the current index in the indices array
  410. * @param shape a Vector3 array, the shape geometry
  411. * @param positions the positions array to be updated
  412. * @param meshInd the shape indices array
  413. * @param indices the indices array to be updated
  414. * @param meshUV the shape uv array
  415. * @param uvs the uv array to be updated
  416. * @param meshCol the shape color array
  417. * @param colors the color array to be updated
  418. * @param meshNor the shape normals array
  419. * @param normals the normals array to be updated
  420. * @param idx the particle index
  421. * @param idxInShape the particle index in its shape
  422. * @param options the addShape() method passed options
  423. * @model the particle model
  424. * @hidden
  425. */
  426. private _meshBuilder(p: number, ind: 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, model: ModelShape): SolidParticle {
  427. var i;
  428. var u = 0;
  429. var c = 0;
  430. var n = 0;
  431. this._resetCopy();
  432. const copy = this._copy;
  433. const storeApart = (options && options.storage) ? true : false;
  434. copy.idx = idx;
  435. copy.idxInShape = idxInShape;
  436. if (this._useModelMaterial) {
  437. var materialId = model._material!.uniqueId;
  438. const materialIndexesById = this._materialIndexesById;
  439. if (!materialIndexesById.hasOwnProperty(materialId)) {
  440. materialIndexesById[materialId] = this._materials.length;
  441. this._materials.push(model._material!);
  442. }
  443. var matIdx = materialIndexesById[materialId];
  444. copy.materialIndex = matIdx;
  445. }
  446. if (options && options.positionFunction) { // call to custom positionFunction
  447. options.positionFunction(copy, idx, idxInShape);
  448. this._mustUnrotateFixedNormals = true;
  449. }
  450. // in case the particle geometry must NOT be inserted in the SPS mesh geometry
  451. if (storeApart) {
  452. return copy;
  453. }
  454. const rotMatrix = TmpVectors.Matrix[0];
  455. const tmpVertex = TmpVectors.Vector3[0];
  456. const tmpRotated = TmpVectors.Vector3[1];
  457. const pivotBackTranslation = TmpVectors.Vector3[2];
  458. const scaledPivot = TmpVectors.Vector3[3];
  459. Matrix.IdentityToRef(rotMatrix);
  460. copy.getRotationMatrix(rotMatrix);
  461. copy.pivot.multiplyToRef(copy.scaling, scaledPivot);
  462. if (copy.translateFromPivot) {
  463. pivotBackTranslation.setAll(0.0);
  464. }
  465. else {
  466. pivotBackTranslation.copyFrom(scaledPivot);
  467. }
  468. var someVertexFunction = (options && options.vertexFunction);
  469. for (i = 0; i < shape.length; i++) {
  470. tmpVertex.copyFrom(shape[i]);
  471. if (someVertexFunction) {
  472. options.vertexFunction(copy, tmpVertex, i);
  473. }
  474. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  475. Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  476. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position);
  477. positions.push(tmpRotated.x, tmpRotated.y, tmpRotated.z);
  478. if (meshUV) {
  479. const copyUvs = copy.uvs;
  480. uvs.push((copyUvs.z - copyUvs.x) * meshUV[u] + copyUvs.x, (copyUvs.w - copyUvs.y) * meshUV[u + 1] + copyUvs.y);
  481. u += 2;
  482. }
  483. if (copy.color) {
  484. this._color = copy.color;
  485. } else {
  486. const color = this._color;
  487. if (meshCol && meshCol[c] !== undefined) {
  488. color.r = meshCol[c];
  489. color.g = meshCol[c + 1];
  490. color.b = meshCol[c + 2];
  491. color.a = meshCol[c + 3];
  492. } else {
  493. color.r = 1.0;
  494. color.g = 1.0;
  495. color.b = 1.0;
  496. color.a = 1.0;
  497. }
  498. }
  499. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  500. c += 4;
  501. if (!this.recomputeNormals && meshNor) {
  502. Vector3.TransformNormalFromFloatsToRef(meshNor[n], meshNor[n + 1], meshNor[n + 2], rotMatrix, tmpVertex);
  503. normals.push(tmpVertex.x, tmpVertex.y, tmpVertex.z);
  504. n += 3;
  505. }
  506. }
  507. for (i = 0; i < meshInd.length; i++) {
  508. var current_ind = p + meshInd[i];
  509. indices.push(current_ind);
  510. if (current_ind > 65535) {
  511. this._needs32Bits = true;
  512. }
  513. }
  514. if (this._pickable) {
  515. var nbfaces = meshInd.length / 3;
  516. for (i = 0; i < nbfaces; i++) {
  517. this.pickedParticles.push({ idx: idx, faceId: i });
  518. }
  519. }
  520. if (this._depthSort || this._multimaterialEnabled) {
  521. var matIndex = (copy.materialIndex !== null) ? copy.materialIndex : 0;
  522. this.depthSortedParticles.push(new DepthSortedParticle(ind, meshInd.length, matIndex));
  523. }
  524. return copy;
  525. }
  526. /**
  527. * Returns a shape Vector3 array from positions float array
  528. * @param positions float array
  529. * @returns a vector3 array
  530. * @hidden
  531. */
  532. private _posToShape(positions: number[] | Float32Array): Vector3[] {
  533. var shape = [];
  534. for (var i = 0; i < positions.length; i += 3) {
  535. shape.push(Vector3.FromArray(positions, i));
  536. }
  537. return shape;
  538. }
  539. /**
  540. * Returns a shapeUV array from a float uvs (array deep copy)
  541. * @param uvs as a float array
  542. * @returns a shapeUV array
  543. * @hidden
  544. */
  545. private _uvsToShapeUV(uvs: number[] | Float32Array): number[] {
  546. var shapeUV = [];
  547. if (uvs) {
  548. for (var i = 0; i < uvs.length; i++) {
  549. shapeUV.push(uvs[i]);
  550. }
  551. }
  552. return shapeUV;
  553. }
  554. /**
  555. * Adds a new particle object in the particles array
  556. * @param idx particle index in particles array
  557. * @param id particle id
  558. * @param idxpos positionIndex : the starting index of the particle vertices in the SPS "positions" array
  559. * @param idxind indiceIndex : he starting index of the particle indices in the SPS "indices" array
  560. * @param model particle ModelShape object
  561. * @param shapeId model shape identifier
  562. * @param idxInShape index of the particle in the current model
  563. * @param bInfo model bounding info object
  564. * @param storage target storage array, if any
  565. * @hidden
  566. */
  567. private _addParticle(idx: number, id: number, idxpos: number, idxind: number, model: ModelShape, shapeId: number, idxInShape: number, bInfo: Nullable<BoundingInfo> = null, storage: Nullable<[]> = null): SolidParticle {
  568. var sp = new SolidParticle(idx, id, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  569. var target = (storage) ? storage : this.particles;
  570. target.push(sp);
  571. return sp;
  572. }
  573. /**
  574. * Adds some particles to the SPS from the model shape. Returns the shape id.
  575. * Please read the doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#create-an-immutable-sps
  576. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  577. * @param nb (positive integer) the number of particles to be created from this model
  578. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  579. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  580. * {storage} (optional existing array) is an array where the particles will be stored for a further use instead of being inserted in the SPS.
  581. * @returns the number of shapes in the system
  582. */
  583. public addShape(mesh: Mesh, nb: number, options?: { positionFunction?: any; vertexFunction?: any; storage?: [] }): number {
  584. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  585. var meshInd = <IndicesArray>mesh.getIndices();
  586. var meshUV = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  587. var meshCol = <FloatArray>mesh.getVerticesData(VertexBuffer.ColorKind);
  588. var meshNor = <FloatArray>mesh.getVerticesData(VertexBuffer.NormalKind);
  589. this.recomputeNormals = (meshNor) ? false : true;
  590. var indices = Array.from(meshInd);
  591. var shapeNormals = Array.from(meshNor);
  592. var shapeColors = (meshCol) ? Array.from(meshCol) : [];
  593. var storage = (options && options.storage) ? options.storage : null;
  594. var bbInfo: Nullable<BoundingInfo> = null;
  595. if (this._particlesIntersect) {
  596. bbInfo = mesh.getBoundingInfo();
  597. }
  598. var shape = this._posToShape(meshPos);
  599. var shapeUV = this._uvsToShapeUV(meshUV);
  600. var posfunc = options ? options.positionFunction : null;
  601. var vtxfunc = options ? options.vertexFunction : null;
  602. var material = null;
  603. if (this._useModelMaterial) {
  604. material = (mesh.material) ? mesh.material : this._setDefaultMaterial();
  605. }
  606. var modelShape = new ModelShape(this._shapeCounter, shape, indices, shapeNormals, shapeColors, shapeUV, posfunc, vtxfunc, material);
  607. // particles
  608. var idx = this.nbParticles;
  609. for (var i = 0; i < nb; i++) {
  610. this._insertNewParticle(idx, i, modelShape, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, storage, options);
  611. }
  612. this._shapeCounter++;
  613. this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work
  614. return this._shapeCounter - 1;
  615. }
  616. /**
  617. * Rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  618. * @hidden
  619. */
  620. private _rebuildParticle(particle: SolidParticle, reset: boolean = false): void {
  621. this._resetCopy();
  622. const copy = this._copy;
  623. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  624. particle._model._positionFunction(copy, particle.idx, particle.idxInShape);
  625. }
  626. const rotMatrix = TmpVectors.Matrix[0];
  627. const tmpVertex = TmpVectors.Vector3[0];
  628. const tmpRotated = TmpVectors.Vector3[1];
  629. const pivotBackTranslation = TmpVectors.Vector3[2];
  630. const scaledPivot = TmpVectors.Vector3[3];
  631. copy.getRotationMatrix(rotMatrix);
  632. particle.pivot.multiplyToRef(particle.scaling, scaledPivot);
  633. if (copy.translateFromPivot) {
  634. pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  635. }
  636. else {
  637. pivotBackTranslation.copyFrom(scaledPivot);
  638. }
  639. const shape = particle._model._shape;
  640. for (var pt = 0; pt < shape.length; pt++) {
  641. tmpVertex.copyFrom(shape[pt]);
  642. if (particle._model._vertexFunction) {
  643. particle._model._vertexFunction(copy, tmpVertex, pt); // recall to stored vertexFunction
  644. }
  645. tmpVertex.multiplyInPlace(copy.scaling).subtractInPlace(scaledPivot);
  646. Vector3.TransformCoordinatesToRef(tmpVertex, rotMatrix, tmpRotated);
  647. tmpRotated.addInPlace(pivotBackTranslation).addInPlace(copy.position).toArray(this._positions32, particle._pos + pt * 3);
  648. }
  649. if (reset) {
  650. particle.position.setAll(0.0);
  651. particle.rotation.setAll(0.0);
  652. particle.rotationQuaternion = null;
  653. particle.scaling.setAll(1.0);
  654. particle.uvs.setAll(0.0);
  655. particle.pivot.setAll(0.0);
  656. particle.translateFromPivot = false;
  657. particle.parentId = null;
  658. }
  659. }
  660. /**
  661. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  662. * @param reset boolean, default false : if the particles must be reset at position and rotation zero, scaling 1, color white, initial UVs and not parented.
  663. * @returns the SPS.
  664. */
  665. public rebuildMesh(reset: boolean = false): SolidParticleSystem {
  666. for (var p = 0; p < this.particles.length; p++) {
  667. this._rebuildParticle(this.particles[p], reset);
  668. }
  669. this.mesh.updateVerticesData(VertexBuffer.PositionKind, this._positions32, false, false);
  670. return this;
  671. }
  672. /** Removes the particles from the start-th to the end-th included from an expandable SPS (required).
  673. * Returns an array with the removed particles.
  674. * If the number of particles to remove is lower than zero or greater than the global remaining particle number, then an empty array is returned.
  675. * The SPS can't be empty so at least one particle needs to remain in place.
  676. * Under the hood, the VertexData array, so the VBO buffer, is recreated each call.
  677. * @param start index of the first particle to remove
  678. * @param end index of the last particle to remove (included)
  679. * @returns an array populated with the removed particles
  680. */
  681. public removeParticles(start: number, end: number): SolidParticle[] {
  682. var nb = end - start + 1;
  683. if (!this._expandable || nb <= 0 || nb >= this.nbParticles || !this._updatable) {
  684. return [];
  685. }
  686. const particles = this.particles;
  687. const currentNb = this.nbParticles;
  688. if (end < currentNb - 1) { // update the particle indexes in the positions array in case they're remaining particles after the last removed
  689. var firstRemaining = end + 1;
  690. var shiftPos = particles[firstRemaining]._pos - particles[start]._pos;
  691. var shifInd = particles[firstRemaining]._ind - particles[start]._ind;
  692. for (var i = firstRemaining; i < currentNb; i++) {
  693. var part = particles[i];
  694. part._pos -= shiftPos;
  695. part._ind -= shifInd;
  696. }
  697. }
  698. var removed = particles.splice(start, nb);
  699. this._positions.length = 0;
  700. this._indices.length = 0;
  701. this._colors.length = 0;
  702. this._uvs.length = 0;
  703. this._normals.length = 0;
  704. this._index = 0;
  705. this._idxOfId.length = 0;
  706. if (this._depthSort || this._multimaterialEnabled) {
  707. this.depthSortedParticles = [];
  708. }
  709. var ind = 0;
  710. const particlesLength = particles.length;
  711. for (var p = 0; p < particlesLength; p++) {
  712. var particle = particles[p];
  713. var model = particle._model;
  714. var shape = model._shape;
  715. var modelIndices = model._indices;
  716. var modelNormals = model._normals;
  717. var modelColors = model._shapeColors;
  718. var modelUVs = model._shapeUV;
  719. particle.idx = p;
  720. this._idxOfId[particle.id] = p;
  721. this._meshBuilder(this._index, ind, shape, this._positions, modelIndices, this._indices, modelUVs, this._uvs, modelColors, this._colors, modelNormals, this._normals, particle.idx, particle.idxInShape, null, model);
  722. this._index += shape.length;
  723. ind += modelIndices.length;
  724. }
  725. this.nbParticles -= nb;
  726. this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work
  727. return removed;
  728. }
  729. /**
  730. * Inserts some pre-created particles in the solid particle system so that they can be managed by setParticles().
  731. * @param solidParticleArray an array populated with Solid Particles objects
  732. * @returns the SPS
  733. */
  734. public insertParticlesFromArray(solidParticleArray: SolidParticle[]): SolidParticleSystem {
  735. if (!this._expandable) {
  736. return this;
  737. }
  738. var idxInShape = 0;
  739. var currentShapeId = solidParticleArray[0].shapeId;
  740. const nb = solidParticleArray.length;
  741. for (var i = 0; i < nb; i++) {
  742. var sp = solidParticleArray[i];
  743. var model = sp._model;
  744. var shape = model._shape;
  745. var meshInd = model._indices;
  746. var meshUV = model._shapeUV;
  747. var meshCol = model._shapeColors;
  748. var meshNor = model._normals;
  749. var noNor = (meshNor) ? false : true;
  750. this.recomputeNormals = (noNor || this.recomputeNormals);
  751. var bbInfo = sp._boundingInfo;
  752. var newPart = this._insertNewParticle(this.nbParticles, idxInShape, model, shape, meshInd, meshUV, meshCol, meshNor, bbInfo, null, null);
  753. sp.copyToRef(newPart!);
  754. idxInShape++;
  755. if (currentShapeId != sp.shapeId) {
  756. currentShapeId = sp.shapeId;
  757. idxInShape = 0;
  758. }
  759. }
  760. this._isNotBuilt = true; // buildMesh() call is now expected for setParticles() to work
  761. return this;
  762. }
  763. /**
  764. * Creates a new particle and modifies the SPS mesh geometry :
  765. * - calls _meshBuilder() to increase the SPS mesh geometry step by step
  766. * - calls _addParticle() to populate the particle array
  767. * factorized code from addShape() and insertParticlesFromArray()
  768. * @param idx particle index in the particles array
  769. * @param i particle index in its shape
  770. * @param modelShape particle ModelShape object
  771. * @param shape shape vertex array
  772. * @param meshInd shape indices array
  773. * @param meshUV shape uv array
  774. * @param meshCol shape color array
  775. * @param meshNor shape normals array
  776. * @param bbInfo shape bounding info
  777. * @param storage target particle storage
  778. * @options addShape() passed options
  779. * @hidden
  780. */
  781. private _insertNewParticle(idx: number, i: number, modelShape: ModelShape, shape: Vector3[], meshInd: IndicesArray, meshUV: number[] | Float32Array, meshCol: number[] | Float32Array, meshNor: number[] | Float32Array, bbInfo: Nullable<BoundingInfo>, storage: Nullable<[]> , options: any): Nullable<SolidParticle> {
  782. var currentPos = this._positions.length;
  783. var currentInd = this._indices.length;
  784. var currentCopy = this._meshBuilder(this._index, currentInd, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options, modelShape);
  785. var sp: Nullable<SolidParticle> = null;
  786. if (this._updatable) {
  787. sp = this._addParticle(this.nbParticles, this._lastParticleId, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo, storage);
  788. sp.position.copyFrom(currentCopy.position);
  789. sp.rotation.copyFrom(currentCopy.rotation);
  790. if (currentCopy.rotationQuaternion) {
  791. if (sp.rotationQuaternion) {
  792. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  793. }
  794. else {
  795. sp.rotationQuaternion = currentCopy.rotationQuaternion.clone();
  796. }
  797. }
  798. if (currentCopy.color) {
  799. if (sp.color) {
  800. sp.color.copyFrom(currentCopy.color);
  801. }
  802. else {
  803. sp.color = currentCopy.color.clone();
  804. }
  805. }
  806. sp.scaling.copyFrom(currentCopy.scaling);
  807. sp.uvs.copyFrom(currentCopy.uvs);
  808. if (currentCopy.materialIndex !== null) {
  809. sp.materialIndex = currentCopy.materialIndex;
  810. }
  811. if (this.expandable) {
  812. this._idxOfId[sp.id] = sp.idx;
  813. }
  814. }
  815. if (!storage) {
  816. this._index += shape.length;
  817. this.nbParticles++;
  818. this._lastParticleId++;
  819. }
  820. return sp;
  821. }
  822. /**
  823. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  824. * This method calls `updateParticle()` for each particle of the SPS.
  825. * For an animated SPS, it is usually called within the render loop.
  826. * This methods does nothing if called on a non updatable or not yet built SPS. Example : buildMesh() not called after having added or removed particles from an expandable SPS.
  827. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  828. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  829. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  830. * @returns the SPS.
  831. */
  832. public setParticles(start: number = 0, end: number = this.nbParticles - 1, update: boolean = true): SolidParticleSystem {
  833. if (!this._updatable || this._isNotBuilt) {
  834. return this;
  835. }
  836. // custom beforeUpdate
  837. this.beforeUpdateParticles(start, end, update);
  838. const rotMatrix = TmpVectors.Matrix[0];
  839. const invertedMatrix = TmpVectors.Matrix[1];
  840. const mesh = this.mesh;
  841. const colors32 = this._colors32;
  842. const positions32 = this._positions32;
  843. const normals32 = this._normals32;
  844. const uvs32 = this._uvs32;
  845. const indices32 = this._indices32;
  846. const indices = this._indices;
  847. const fixedNormal32 = this._fixedNormal32;
  848. const tempVectors = TmpVectors.Vector3;
  849. const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  850. const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  851. const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  852. const minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  853. const maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  854. const camInvertedPosition = tempVectors[10].setAll(0);
  855. // cases when the World Matrix is to be computed first
  856. if (this.billboard || this._depthSort) {
  857. this.mesh.computeWorldMatrix(true);
  858. this.mesh._worldMatrix.invertToRef(invertedMatrix);
  859. }
  860. // if the particles will always face the camera
  861. if (this.billboard) {
  862. // compute the camera position and un-rotate it by the current mesh rotation
  863. const tmpVertex = tempVectors[0];
  864. this._camera.getDirectionToRef(Axis.Z, tmpVertex);
  865. Vector3.TransformNormalToRef(tmpVertex, invertedMatrix, camAxisZ);
  866. camAxisZ.normalize();
  867. // same for camera up vector extracted from the cam view matrix
  868. var view = this._camera.getViewMatrix(true);
  869. Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], invertedMatrix, camAxisY);
  870. Vector3.CrossToRef(camAxisY, camAxisZ, camAxisX);
  871. camAxisY.normalize();
  872. camAxisX.normalize();
  873. }
  874. // if depthSort, compute the camera global position in the mesh local system
  875. if (this._depthSort) {
  876. Vector3.TransformCoordinatesToRef(this._camera.globalPosition, invertedMatrix, camInvertedPosition); // then un-rotate the camera
  877. }
  878. Matrix.IdentityToRef(rotMatrix);
  879. var idx = 0; // current position index in the global array positions32
  880. var index = 0; // position start index in the global array positions32 of the current particle
  881. var colidx = 0; // current color index in the global array colors32
  882. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  883. var uvidx = 0; // current uv index in the global array uvs32
  884. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  885. var pt = 0; // current index in the particle model shape
  886. if (this.mesh.isFacetDataEnabled) {
  887. this._computeBoundingBox = true;
  888. }
  889. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  890. if (this._computeBoundingBox) {
  891. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  892. const boundingInfo = this.mesh._boundingInfo;
  893. if (boundingInfo) {
  894. minimum.copyFrom(boundingInfo.minimum);
  895. maximum.copyFrom(boundingInfo.maximum);
  896. }
  897. }
  898. }
  899. // particle loop
  900. index = this.particles[start]._pos;
  901. const vpos = (index / 3) | 0;
  902. colorIndex = vpos * 4;
  903. uvIndex = vpos * 2;
  904. for (var p = start; p <= end; p++) {
  905. const particle = this.particles[p];
  906. // call to custom user function to update the particle properties
  907. this.updateParticle(particle);
  908. const shape = particle._model._shape;
  909. const shapeUV = particle._model._shapeUV;
  910. const particleRotationMatrix = particle._rotationMatrix;
  911. const particlePosition = particle.position;
  912. const particleRotation = particle.rotation;
  913. const particleScaling = particle.scaling;
  914. const particleGlobalPosition = particle._globalPosition;
  915. // camera-particle distance for depth sorting
  916. if (this._depthSort && this._depthSortParticles) {
  917. var dsp = this.depthSortedParticles[p];
  918. dsp.ind = particle._ind;
  919. dsp.indicesLength = particle._model._indicesLength;
  920. dsp.sqDistance = Vector3.DistanceSquared(particle.position, camInvertedPosition);
  921. }
  922. // skip the computations for inactive or already invisible particles
  923. if (!particle.alive || (particle._stillInvisible && !particle.isVisible)) {
  924. // increment indexes for the next particle
  925. pt = shape.length;
  926. index += pt * 3;
  927. colorIndex += pt * 4;
  928. uvIndex += pt * 2;
  929. continue;
  930. }
  931. if (particle.isVisible) {
  932. particle._stillInvisible = false; // un-mark permanent invisibility
  933. const scaledPivot = tempVectors[12];
  934. particle.pivot.multiplyToRef(particleScaling, scaledPivot);
  935. // particle rotation matrix
  936. if (this.billboard) {
  937. particleRotation.x = 0.0;
  938. particleRotation.y = 0.0;
  939. }
  940. if (this._computeParticleRotation || this.billboard) {
  941. particle.getRotationMatrix(rotMatrix);
  942. }
  943. const particleHasParent = (particle.parentId !== null);
  944. if (particleHasParent) {
  945. const parent = this.getParticleById(particle.parentId!);
  946. if (parent) {
  947. const parentRotationMatrix = parent._rotationMatrix;
  948. const parentGlobalPosition = parent._globalPosition;
  949. const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  950. const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  951. const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  952. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  953. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  954. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  955. if (this._computeParticleRotation || this.billboard) {
  956. const rotMatrixValues = rotMatrix.m;
  957. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  958. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  959. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  960. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  961. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  962. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  963. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  964. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  965. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  966. }
  967. }
  968. else { // in case the parent were removed at some moment
  969. particle.parentId = null;
  970. }
  971. }
  972. else {
  973. particleGlobalPosition.x = particlePosition.x;
  974. particleGlobalPosition.y = particlePosition.y;
  975. particleGlobalPosition.z = particlePosition.z;
  976. if (this._computeParticleRotation || this.billboard) {
  977. const rotMatrixValues = rotMatrix.m;
  978. particleRotationMatrix[0] = rotMatrixValues[0];
  979. particleRotationMatrix[1] = rotMatrixValues[1];
  980. particleRotationMatrix[2] = rotMatrixValues[2];
  981. particleRotationMatrix[3] = rotMatrixValues[4];
  982. particleRotationMatrix[4] = rotMatrixValues[5];
  983. particleRotationMatrix[5] = rotMatrixValues[6];
  984. particleRotationMatrix[6] = rotMatrixValues[8];
  985. particleRotationMatrix[7] = rotMatrixValues[9];
  986. particleRotationMatrix[8] = rotMatrixValues[10];
  987. }
  988. }
  989. const pivotBackTranslation = tempVectors[11];
  990. if (particle.translateFromPivot) {
  991. pivotBackTranslation.setAll(0.0);
  992. }
  993. else {
  994. pivotBackTranslation.copyFrom(scaledPivot);
  995. }
  996. // particle vertex loop
  997. for (pt = 0; pt < shape.length; pt++) {
  998. idx = index + pt * 3;
  999. colidx = colorIndex + pt * 4;
  1000. uvidx = uvIndex + pt * 2;
  1001. const tmpVertex = tempVectors[0];
  1002. tmpVertex.copyFrom(shape[pt]);
  1003. if (this._computeParticleVertex) {
  1004. this.updateParticleVertex(particle, tmpVertex, pt);
  1005. }
  1006. // positions
  1007. const vertexX = tmpVertex.x * particleScaling.x - scaledPivot.x;
  1008. const vertexY = tmpVertex.y * particleScaling.y - scaledPivot.y;
  1009. const vertexZ = tmpVertex.z * particleScaling.z - scaledPivot.z;
  1010. let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  1011. let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  1012. let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  1013. rotatedX += pivotBackTranslation.x;
  1014. rotatedY += pivotBackTranslation.y;
  1015. rotatedZ += pivotBackTranslation.z;
  1016. const px = positions32[idx] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  1017. const py = positions32[idx + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  1018. const pz = positions32[idx + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  1019. if (this._computeBoundingBox) {
  1020. minimum.minimizeInPlaceFromFloats(px, py, pz);
  1021. maximum.maximizeInPlaceFromFloats(px, py, pz);
  1022. }
  1023. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  1024. if (!this._computeParticleVertex) {
  1025. const normalx = fixedNormal32[idx];
  1026. const normaly = fixedNormal32[idx + 1];
  1027. const normalz = fixedNormal32[idx + 2];
  1028. const rotatedx = normalx * particleRotationMatrix[0] + normaly * particleRotationMatrix[3] + normalz * particleRotationMatrix[6];
  1029. const rotatedy = normalx * particleRotationMatrix[1] + normaly * particleRotationMatrix[4] + normalz * particleRotationMatrix[7];
  1030. const rotatedz = normalx * particleRotationMatrix[2] + normaly * particleRotationMatrix[5] + normalz * particleRotationMatrix[8];
  1031. normals32[idx] = camAxisX.x * rotatedx + camAxisY.x * rotatedy + camAxisZ.x * rotatedz;
  1032. normals32[idx + 1] = camAxisX.y * rotatedx + camAxisY.y * rotatedy + camAxisZ.y * rotatedz;
  1033. normals32[idx + 2] = camAxisX.z * rotatedx + camAxisY.z * rotatedy + camAxisZ.z * rotatedz;
  1034. }
  1035. if (this._computeParticleColor && particle.color) {
  1036. const color = particle.color;
  1037. const colors32 = this._colors32;
  1038. colors32[colidx] = color.r;
  1039. colors32[colidx + 1] = color.g;
  1040. colors32[colidx + 2] = color.b;
  1041. colors32[colidx + 3] = color.a;
  1042. }
  1043. if (this._computeParticleTexture) {
  1044. const uvs = particle.uvs;
  1045. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  1046. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  1047. }
  1048. }
  1049. }
  1050. // particle just set invisible : scaled to zero and positioned at the origin
  1051. else {
  1052. particle._stillInvisible = true; // mark the particle as invisible
  1053. for (pt = 0; pt < shape.length; pt++) {
  1054. idx = index + pt * 3;
  1055. colidx = colorIndex + pt * 4;
  1056. uvidx = uvIndex + pt * 2;
  1057. positions32[idx] = positions32[idx + 1] = positions32[idx + 2] = 0;
  1058. normals32[idx] = normals32[idx + 1] = normals32[idx + 2] = 0;
  1059. if (this._computeParticleColor && particle.color) {
  1060. const color = particle.color;
  1061. colors32[colidx] = color.r;
  1062. colors32[colidx + 1] = color.g;
  1063. colors32[colidx + 2] = color.b;
  1064. colors32[colidx + 3] = color.a;
  1065. }
  1066. if (this._computeParticleTexture) {
  1067. const uvs = particle.uvs;
  1068. uvs32[uvidx] = shapeUV[pt * 2] * (uvs.z - uvs.x) + uvs.x;
  1069. uvs32[uvidx + 1] = shapeUV[pt * 2 + 1] * (uvs.w - uvs.y) + uvs.y;
  1070. }
  1071. }
  1072. }
  1073. // if the particle intersections must be computed : update the bbInfo
  1074. if (this._particlesIntersect) {
  1075. const bInfo = particle._boundingInfo;
  1076. const bBox = bInfo.boundingBox;
  1077. const bSphere = bInfo.boundingSphere;
  1078. const modelBoundingInfo = particle._modelBoundingInfo;
  1079. if (!this._bSphereOnly) {
  1080. // place, scale and rotate the particle bbox within the SPS local system, then update it
  1081. const modelBoundingInfoVectors = modelBoundingInfo.boundingBox.vectors;
  1082. const tempMin = tempVectors[1];
  1083. const tempMax = tempVectors[2];
  1084. tempMin.setAll(Number.MAX_VALUE);
  1085. tempMax.setAll(-Number.MAX_VALUE);
  1086. for (var b = 0; b < 8; b++) {
  1087. const scaledX = modelBoundingInfoVectors[b].x * particleScaling.x;
  1088. const scaledY = modelBoundingInfoVectors[b].y * particleScaling.y;
  1089. const scaledZ = modelBoundingInfoVectors[b].z * particleScaling.z;
  1090. const rotatedX = scaledX * particleRotationMatrix[0] + scaledY * particleRotationMatrix[3] + scaledZ * particleRotationMatrix[6];
  1091. const rotatedY = scaledX * particleRotationMatrix[1] + scaledY * particleRotationMatrix[4] + scaledZ * particleRotationMatrix[7];
  1092. const rotatedZ = scaledX * particleRotationMatrix[2] + scaledY * particleRotationMatrix[5] + scaledZ * particleRotationMatrix[8];
  1093. const x = particlePosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  1094. const y = particlePosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  1095. const z = particlePosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  1096. tempMin.minimizeInPlaceFromFloats(x, y, z);
  1097. tempMax.maximizeInPlaceFromFloats(x, y, z);
  1098. }
  1099. bBox.reConstruct(tempMin, tempMax, mesh._worldMatrix);
  1100. }
  1101. // place and scale the particle bouding sphere in the SPS local system, then update it
  1102. const minBbox = modelBoundingInfo.minimum.multiplyToRef(particleScaling, tempVectors[1]);
  1103. const maxBbox = modelBoundingInfo.maximum.multiplyToRef(particleScaling, tempVectors[2]);
  1104. const bSphereCenter = maxBbox.addToRef(minBbox, tempVectors[3]).scaleInPlace(0.5).addInPlace(particleGlobalPosition);
  1105. const halfDiag = maxBbox.subtractToRef(minBbox, tempVectors[4]).scaleInPlace(0.5 * this._bSphereRadiusFactor);
  1106. const bSphereMinBbox = bSphereCenter.subtractToRef(halfDiag, tempVectors[1]);
  1107. const bSphereMaxBbox = bSphereCenter.addToRef(halfDiag, tempVectors[2]);
  1108. bSphere.reConstruct(bSphereMinBbox, bSphereMaxBbox, mesh._worldMatrix);
  1109. }
  1110. // increment indexes for the next particle
  1111. index = idx + 3;
  1112. colorIndex = colidx + 4;
  1113. uvIndex = uvidx + 2;
  1114. }
  1115. // if the VBO must be updated
  1116. if (update) {
  1117. if (this._computeParticleColor) {
  1118. mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false);
  1119. }
  1120. if (this._computeParticleTexture) {
  1121. mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false);
  1122. }
  1123. mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false);
  1124. if (!mesh.areNormalsFrozen || mesh.isFacetDataEnabled) {
  1125. if (this._computeParticleVertex || mesh.isFacetDataEnabled) {
  1126. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  1127. var params = mesh.isFacetDataEnabled ? mesh.getFacetDataParameters() : null;
  1128. VertexData.ComputeNormals(positions32, indices32, normals32, params);
  1129. for (var i = 0; i < normals32.length; i++) {
  1130. fixedNormal32[i] = normals32[i];
  1131. }
  1132. }
  1133. if (!mesh.areNormalsFrozen) {
  1134. mesh.updateVerticesData(VertexBuffer.NormalKind, normals32, false, false);
  1135. }
  1136. }
  1137. if (this._depthSort && this._depthSortParticles) {
  1138. const depthSortedParticles = this.depthSortedParticles;
  1139. depthSortedParticles.sort(this._depthSortFunction);
  1140. const dspl = depthSortedParticles.length;
  1141. let sid = 0;
  1142. for (let sorted = 0; sorted < dspl; sorted++) {
  1143. const lind = depthSortedParticles[sorted].indicesLength;
  1144. const sind = depthSortedParticles[sorted].ind;
  1145. for (var i = 0; i < lind; i++) {
  1146. indices32[sid] = indices[sind + i];
  1147. sid++;
  1148. }
  1149. }
  1150. mesh.updateIndices(indices32);
  1151. }
  1152. }
  1153. if (this._computeBoundingBox) {
  1154. if (mesh._boundingInfo) {
  1155. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  1156. }
  1157. else {
  1158. mesh._boundingInfo = new BoundingInfo(minimum, maximum, mesh._worldMatrix);
  1159. }
  1160. }
  1161. this.afterUpdateParticles(start, end, update);
  1162. return this;
  1163. }
  1164. /**
  1165. * Disposes the SPS.
  1166. */
  1167. public dispose(): void {
  1168. this.mesh.dispose();
  1169. this.vars = null;
  1170. // drop references to internal big arrays for the GC
  1171. (<any>this._positions) = null;
  1172. (<any>this._indices) = null;
  1173. (<any>this._normals) = null;
  1174. (<any>this._uvs) = null;
  1175. (<any>this._colors) = null;
  1176. (<any>this._indices32) = null;
  1177. (<any>this._positions32) = null;
  1178. (<any>this._normals32) = null;
  1179. (<any>this._fixedNormal32) = null;
  1180. (<any>this._uvs32) = null;
  1181. (<any>this._colors32) = null;
  1182. (<any>this.pickedParticles) = null;
  1183. }
  1184. /**
  1185. * Returns a SolidParticle object from its identifier : particle.id
  1186. * @param id (integer) the particle Id
  1187. * @returns the searched particle or null if not found in the SPS.
  1188. */
  1189. public getParticleById(id: number): Nullable<SolidParticle> {
  1190. const p = this.particles[id];
  1191. if (p && p.id == id) {
  1192. return p;
  1193. }
  1194. const particles = this.particles;
  1195. const idx = this._idxOfId[id];
  1196. if (idx !== undefined) {
  1197. return particles[idx];
  1198. }
  1199. var i = 0;
  1200. const nb = this.nbParticles;
  1201. while (i < nb) {
  1202. var particle = particles[i];
  1203. if (particle.id == id) {
  1204. return particle;
  1205. }
  1206. i++;
  1207. }
  1208. return null;
  1209. }
  1210. /**
  1211. * Returns a new array populated with the particles having the passed shapeId.
  1212. * @param shapeId (integer) the shape identifier
  1213. * @returns a new solid particle array
  1214. */
  1215. public getParticlesByShapeId(shapeId: number): SolidParticle[] {
  1216. var ref: SolidParticle[] = [];
  1217. this.getParticlesByShapeIdToRef(shapeId, ref);
  1218. return ref;
  1219. }
  1220. /**
  1221. * Populates the passed array "ref" with the particles having the passed shapeId.
  1222. * @param shapeId the shape identifier
  1223. * @returns the SPS
  1224. * @param ref
  1225. */
  1226. public getParticlesByShapeIdToRef(shapeId: number, ref: SolidParticle[]): SolidParticleSystem {
  1227. ref.length = 0;
  1228. for (var i = 0; i < this.nbParticles; i++) {
  1229. var p = this.particles[i];
  1230. if (p.shapeId == shapeId) {
  1231. ref.push(p);
  1232. }
  1233. }
  1234. return this;
  1235. }
  1236. /**
  1237. * Computes the required SubMeshes according the materials assigned to the particles.
  1238. * @returns the solid particle system.
  1239. * Does nothing if called before the SPS mesh is built.
  1240. */
  1241. public computeSubMeshes(): SolidParticleSystem {
  1242. if (!this.mesh || !this._multimaterialEnabled) {
  1243. return this;
  1244. }
  1245. const depthSortedParticles = this.depthSortedParticles;
  1246. if (this.particles.length > 0) {
  1247. for (let p = 0; p < this.particles.length; p++) {
  1248. let part = this.particles[p];
  1249. if (!part.materialIndex) {
  1250. part.materialIndex = 0;
  1251. }
  1252. let sortedPart = depthSortedParticles[p];
  1253. sortedPart.materialIndex = part.materialIndex;
  1254. sortedPart.ind = part._ind;
  1255. sortedPart.indicesLength = part._model._indicesLength;
  1256. }
  1257. }
  1258. this._sortParticlesByMaterial();
  1259. const indicesByMaterial = this._indicesByMaterial;
  1260. const materialIndexes = this._materialIndexes;
  1261. const mesh = this.mesh;
  1262. mesh.subMeshes = [];
  1263. const vcount = mesh.getTotalVertices();
  1264. for (let m = 0; m < materialIndexes.length; m++) {
  1265. let start = indicesByMaterial[m];
  1266. let count = indicesByMaterial[m + 1] - start;
  1267. let matIndex = materialIndexes[m];
  1268. new SubMesh(matIndex, 0, vcount, start, count, mesh);
  1269. }
  1270. return this;
  1271. }
  1272. /**
  1273. * Sorts the solid particles by material when MultiMaterial is enabled.
  1274. * Updates the indices32 array.
  1275. * Updates the indicesByMaterial array.
  1276. * Updates the mesh indices array.
  1277. * @returns the SPS
  1278. * @hidden
  1279. */
  1280. private _sortParticlesByMaterial(): SolidParticleSystem {
  1281. const indicesByMaterial = [0];
  1282. this._indicesByMaterial = indicesByMaterial;
  1283. const materialIndexes: number[] = [];
  1284. this._materialIndexes = materialIndexes;
  1285. const depthSortedParticles = this.depthSortedParticles;
  1286. depthSortedParticles.sort(this._materialSortFunction);
  1287. const length = depthSortedParticles.length;
  1288. const indices32 = this._indices32;
  1289. const indices = this._indices;
  1290. let sid = 0;
  1291. let lastMatIndex = depthSortedParticles[0].materialIndex;
  1292. materialIndexes.push(lastMatIndex);
  1293. for (let sorted = 0; sorted < length; sorted++) {
  1294. let sortedPart = depthSortedParticles[sorted];
  1295. let lind = sortedPart.indicesLength;
  1296. let sind = sortedPart.ind;
  1297. if (sortedPart.materialIndex !== lastMatIndex) {
  1298. lastMatIndex = sortedPart.materialIndex;
  1299. indicesByMaterial.push(sid);
  1300. materialIndexes.push(lastMatIndex);
  1301. }
  1302. for (let i = 0; i < lind; i++) {
  1303. indices32[sid] = indices[sind + i];
  1304. sid++;
  1305. }
  1306. }
  1307. indicesByMaterial.push(indices32.length); // add the last number to ease the indices start/count values for subMeshes creation
  1308. if (this._updatable) {
  1309. this.mesh.updateIndices(indices32);
  1310. }
  1311. return this;
  1312. }
  1313. /**
  1314. * Sets the material indexes by id materialIndexesById[id] = materialIndex
  1315. * @hidden
  1316. */
  1317. private _setMaterialIndexesById() {
  1318. this._materialIndexesById = {};
  1319. for (var i = 0; i < this._materials.length; i++) {
  1320. var id = this._materials[i].uniqueId;
  1321. this._materialIndexesById[id] = i;
  1322. }
  1323. }
  1324. /**
  1325. * Returns an array with unique values of Materials from the passed array
  1326. * @param array the material array to be checked and filtered
  1327. * @hidden
  1328. */
  1329. private _filterUniqueMaterialId(array: Material[]): Material[] {
  1330. var filtered = array.filter(function(value, index, self) {
  1331. return self.indexOf(value) === index;
  1332. });
  1333. return filtered;
  1334. }
  1335. /**
  1336. * Sets a new Standard Material as _defaultMaterial if not already set.
  1337. * @hidden
  1338. */
  1339. private _setDefaultMaterial(): Material {
  1340. if (!this._defaultMaterial) {
  1341. this._defaultMaterial = new StandardMaterial(this.name + "DefaultMaterial", this._scene);
  1342. }
  1343. return this._defaultMaterial;
  1344. }
  1345. /**
  1346. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  1347. * doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1348. * @returns the SPS.
  1349. */
  1350. public refreshVisibleSize(): SolidParticleSystem {
  1351. if (!this._isVisibilityBoxLocked) {
  1352. this.mesh.refreshBoundingInfo();
  1353. }
  1354. return this;
  1355. }
  1356. /**
  1357. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  1358. * @param size the size (float) of the visibility box
  1359. * note : this doesn't lock the SPS mesh bounding box.
  1360. * doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1361. */
  1362. public setVisibilityBox(size: number): void {
  1363. var vis = size / 2;
  1364. this.mesh._boundingInfo = new BoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));
  1365. }
  1366. /**
  1367. * Gets whether the SPS as always visible or not
  1368. * doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1369. */
  1370. public get isAlwaysVisible(): boolean {
  1371. return this._alwaysVisible;
  1372. }
  1373. /**
  1374. * Sets the SPS as always visible or not
  1375. * doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1376. */
  1377. public set isAlwaysVisible(val: boolean) {
  1378. this._alwaysVisible = val;
  1379. this.mesh.alwaysSelectAsActiveMesh = val;
  1380. }
  1381. /**
  1382. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  1383. * doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1384. */
  1385. public set isVisibilityBoxLocked(val: boolean) {
  1386. this._isVisibilityBoxLocked = val;
  1387. let boundingInfo = this.mesh.getBoundingInfo();
  1388. boundingInfo.isLocked = val;
  1389. }
  1390. /**
  1391. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  1392. * doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#sps-visibility
  1393. */
  1394. public get isVisibilityBoxLocked(): boolean {
  1395. return this._isVisibilityBoxLocked;
  1396. }
  1397. /**
  1398. * Tells to `setParticles()` to compute the particle rotations or not.
  1399. * Default value : true. The SPS is faster when it's set to false.
  1400. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  1401. */
  1402. public set computeParticleRotation(val: boolean) {
  1403. this._computeParticleRotation = val;
  1404. }
  1405. /**
  1406. * Tells to `setParticles()` to compute the particle colors or not.
  1407. * Default value : true. The SPS is faster when it's set to false.
  1408. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  1409. */
  1410. public set computeParticleColor(val: boolean) {
  1411. this._computeParticleColor = val;
  1412. }
  1413. public set computeParticleTexture(val: boolean) {
  1414. this._computeParticleTexture = val;
  1415. }
  1416. /**
  1417. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  1418. * Default value : false. The SPS is faster when it's set to false.
  1419. * Note : the particle custom vertex positions aren't stored values.
  1420. */
  1421. public set computeParticleVertex(val: boolean) {
  1422. this._computeParticleVertex = val;
  1423. }
  1424. /**
  1425. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  1426. */
  1427. public set computeBoundingBox(val: boolean) {
  1428. this._computeBoundingBox = val;
  1429. }
  1430. /**
  1431. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  1432. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  1433. * Default : `true`
  1434. */
  1435. public set depthSortParticles(val: boolean) {
  1436. this._depthSortParticles = val;
  1437. }
  1438. /**
  1439. * Gets if `setParticles()` computes the particle rotations or not.
  1440. * Default value : true. The SPS is faster when it's set to false.
  1441. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  1442. */
  1443. public get computeParticleRotation(): boolean {
  1444. return this._computeParticleRotation;
  1445. }
  1446. /**
  1447. * Gets if `setParticles()` computes the particle colors or not.
  1448. * Default value : true. The SPS is faster when it's set to false.
  1449. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  1450. */
  1451. public get computeParticleColor(): boolean {
  1452. return this._computeParticleColor;
  1453. }
  1454. /**
  1455. * Gets if `setParticles()` computes the particle textures or not.
  1456. * Default value : true. The SPS is faster when it's set to false.
  1457. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  1458. */
  1459. public get computeParticleTexture(): boolean {
  1460. return this._computeParticleTexture;
  1461. }
  1462. /**
  1463. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  1464. * Default value : false. The SPS is faster when it's set to false.
  1465. * Note : the particle custom vertex positions aren't stored values.
  1466. */
  1467. public get computeParticleVertex(): boolean {
  1468. return this._computeParticleVertex;
  1469. }
  1470. /**
  1471. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  1472. */
  1473. public get computeBoundingBox(): boolean {
  1474. return this._computeBoundingBox;
  1475. }
  1476. /**
  1477. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  1478. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  1479. * Default : `true`
  1480. */
  1481. public get depthSortParticles(): boolean {
  1482. return this._depthSortParticles;
  1483. }
  1484. /**
  1485. * Gets if the SPS is created as expandable at construction time.
  1486. * Default : `false`
  1487. */
  1488. public get expandable(): boolean {
  1489. return this._expandable;
  1490. }
  1491. /**
  1492. * Gets if the SPS supports the Multi Materials
  1493. */
  1494. public get multimaterialEnabled(): boolean {
  1495. return this._multimaterialEnabled;
  1496. }
  1497. /**
  1498. * Gets if the SPS uses the model materials for its own multimaterial.
  1499. */
  1500. public get useModelMaterial(): boolean {
  1501. return this._useModelMaterial;
  1502. }
  1503. /**
  1504. * The SPS used material array.
  1505. */
  1506. public get materials(): Material[] {
  1507. return this._materials;
  1508. }
  1509. /**
  1510. * Sets the SPS MultiMaterial from the passed materials.
  1511. * Note : the passed array is internally copied and not used then by reference.
  1512. * @param materials an array of material objects. This array indexes are the materialIndex values of the particles.
  1513. */
  1514. public setMultiMaterial(materials: Material[]) {
  1515. this._materials = this._filterUniqueMaterialId(materials);
  1516. this._setMaterialIndexesById();
  1517. if (this._multimaterial) {
  1518. this._multimaterial.dispose();
  1519. }
  1520. this._multimaterial = new MultiMaterial(this.name + "MultiMaterial", this._scene);
  1521. for (var m = 0; m < this._materials.length; m++) {
  1522. this._multimaterial.subMaterials.push(this._materials[m]);
  1523. }
  1524. this.computeSubMeshes();
  1525. this.mesh.material = this._multimaterial;
  1526. }
  1527. /**
  1528. * The SPS computed multimaterial object
  1529. */
  1530. public get multimaterial(): MultiMaterial {
  1531. return this._multimaterial;
  1532. }
  1533. public set multimaterial(mm) {
  1534. this._multimaterial = mm;
  1535. }
  1536. // =======================================================================
  1537. // Particle behavior logic
  1538. // these following methods may be overwritten by the user to fit his needs
  1539. /**
  1540. * This function does nothing. It may be overwritten to set all the particle first values.
  1541. * The SPS doesn't call this function, you may have to call it by your own.
  1542. * doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#particle-management
  1543. */
  1544. public initParticles(): void {
  1545. }
  1546. /**
  1547. * This function does nothing. It may be overwritten to recycle a particle.
  1548. * The SPS doesn't call this function, you may have to call it by your own.
  1549. * doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#particle-management
  1550. * @param particle The particle to recycle
  1551. * @returns the recycled particle
  1552. */
  1553. public recycleParticle(particle: SolidParticle): SolidParticle {
  1554. return particle;
  1555. }
  1556. /**
  1557. * Updates a particle : this function should be overwritten by the user.
  1558. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  1559. * doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#particle-management
  1560. * @example : just set a particle position or velocity and recycle conditions
  1561. * @param particle The particle to update
  1562. * @returns the updated particle
  1563. */
  1564. public updateParticle(particle: SolidParticle): SolidParticle {
  1565. return particle;
  1566. }
  1567. /**
  1568. * Updates a vertex of a particle : it can be overwritten by the user.
  1569. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  1570. * @param particle the current particle
  1571. * @param vertex the current index of the current particle
  1572. * @param pt the index of the current vertex in the particle shape
  1573. * doc : http://doc.babylonjs.com/how_to/Solid_Particle_System#update-each-particle-shape
  1574. * @example : just set a vertex particle position
  1575. * @returns the updated vertex
  1576. */
  1577. public updateParticleVertex(particle: SolidParticle, vertex: Vector3, pt: number): Vector3 {
  1578. return vertex;
  1579. }
  1580. /**
  1581. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  1582. * This does nothing and may be overwritten by the user.
  1583. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1584. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1585. * @param update the boolean update value actually passed to setParticles()
  1586. */
  1587. public beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  1588. }
  1589. /**
  1590. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  1591. * This will be passed three parameters.
  1592. * This does nothing and may be overwritten by the user.
  1593. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1594. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  1595. * @param update the boolean update value actually passed to setParticles()
  1596. */
  1597. public afterUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  1598. }
  1599. }