pointsCloudSystem.ts 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. import { IndicesArray, FloatArray } from "../types";
  2. import { Color4, Color3 } from "../Maths/math";
  3. import { Vector2, Vector3, Vector4, TmpVectors, Matrix } from "../Maths/math.vector";
  4. import { Logger } from "../Misc/logger";
  5. import { VertexBuffer } from "../Meshes/buffer";
  6. import { VertexData } from "../Meshes/mesh.vertexData";
  7. import { Mesh } from "../Meshes/mesh";
  8. import { EngineStore } from "../Engines/engineStore";
  9. import { Scene, IDisposable } from "../scene";
  10. import { CloudPoint, PointsGroup } from "./cloudPoint";
  11. import { BoundingInfo } from "../Culling/boundingInfo";
  12. import { Ray } from "../Culling/ray";
  13. import { PickingInfo } from "../Collisions/pickingInfo";
  14. import { StandardMaterial } from "../Materials/standardMaterial";
  15. import { BaseTexture } from "./../Materials/Textures/baseTexture";
  16. import { Scalar } from "../Maths/math.scalar";
  17. /** Defines the 4 color options */
  18. export enum PointColor {
  19. /** color value */
  20. Color = 2,
  21. /** uv value */
  22. UV = 1,
  23. /** random value */
  24. Random = 0,
  25. /** stated value */
  26. Stated = 3
  27. }
  28. /**
  29. * The PointCloudSystem (PCS) is a single updatable mesh. The points corresponding to the vertices of this big mesh.
  30. * As it is just a mesh, the PointCloudSystem has all the same properties as any other BJS mesh : not more, not less. It can be scaled, rotated, translated, enlighted, textured, moved, etc.
  31. * The PointCloudSytem is also a particle system, with each point being a particle. It provides some methods to manage the particles.
  32. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  33. *
  34. * Full documentation here : TO BE ENTERED
  35. */
  36. export class PointsCloudSystem implements IDisposable {
  37. /**
  38. * The PCS array of cloud point objects. Just access each particle as with any classic array.
  39. * Example : var p = SPS.particles[i];
  40. */
  41. public particles: CloudPoint[] = new Array<CloudPoint>();
  42. /**
  43. * The PCS total number of particles. Read only. Use PCS.counter instead if you need to set your own value.
  44. */
  45. public nbParticles: number = 0;
  46. /**
  47. * This a counter for your own usage. It's not set by any SPS functions.
  48. */
  49. public counter: number = 0;
  50. /**
  51. * The PCS name. This name is also given to the underlying mesh.
  52. */
  53. public name: string;
  54. /**
  55. * The PCS mesh. It's a standard BJS Mesh, so all the methods from the Mesh class are avalaible.
  56. */
  57. public mesh: Mesh;
  58. /**
  59. * This empty object is intended to store some PCS specific or temporary values in order to lower the Garbage Collector activity.
  60. * Please read :
  61. */
  62. public vars: any = {};
  63. /**
  64. * @hidden
  65. */
  66. public _size: number; //size of each point particle
  67. private _scene: Scene;
  68. private _promises: Array<Promise<any>> = [];
  69. private _positions: number[] = new Array<number>();
  70. private _indices: number[] = new Array<number>();
  71. private _normals: number[] = new Array<number>();
  72. private _colors: number[] = new Array<number>();
  73. private _uvs: number[] = new Array<number>();
  74. private _indices32: IndicesArray; // used as depth sorted array if depth sort enabled, else used as typed indices
  75. private _positions32: Float32Array; // updated positions for the VBO
  76. private _colors32: Float32Array;
  77. private _uvs32: Float32Array;
  78. private _updatable: boolean = true;
  79. private _isVisibilityBoxLocked = false;
  80. private _alwaysVisible: boolean = false;
  81. private _groups: number[] = new Array<number>(); //start indices for each group of particles
  82. private _groupCounter: number = 0;
  83. private _computeParticleColor: boolean = true;
  84. private _computeParticleTexture: boolean = true;
  85. private _computeParticleRotation: boolean = true;
  86. private _computeBoundingBox: boolean = false;
  87. private _isReady: boolean = false;
  88. /**
  89. * Creates a PCS (Points Cloud System) object
  90. * @param name (String) is the PCS name, this will be the underlying mesh name
  91. * @param pointSize (number) is the size for each point
  92. * @param scene (Scene) is the scene in which the PCS is added
  93. * @param options defines the options of the PCS e.g.
  94. * * updatable (optional boolean, default true) : if the PCS must be updatable or immutable
  95. */
  96. constructor(name: string, pointSize: number, scene: Scene, options?: { updatable?: boolean}) {
  97. this.name = name;
  98. this._size = pointSize;
  99. this._scene = scene || EngineStore.LastCreatedScene;
  100. if (options && options.updatable !== undefined) {
  101. this._updatable = options.updatable;
  102. } else {
  103. this._updatable = true;
  104. }
  105. }
  106. /**
  107. * Builds the PCS underlying mesh. Returns a standard Mesh.
  108. * If no points were added to the PCS, the returned mesh is just a single point.
  109. * @returns a promise for the created mesh
  110. */
  111. public buildMeshAsync(): Promise<Mesh> {
  112. return Promise.all(this._promises).then(() => {
  113. this._isReady = true;
  114. return this._buildMesh();
  115. });
  116. }
  117. /**
  118. * @hidden
  119. */
  120. private _buildMesh(): Promise<Mesh> {
  121. if (this.nbParticles === 0) {
  122. this.addPoints(1);
  123. }
  124. this._positions32 = new Float32Array(this._positions);
  125. this._uvs32 = new Float32Array(this._uvs);
  126. this._colors32 = new Float32Array(this._colors);
  127. var vertexData = new VertexData();
  128. vertexData.set(this._positions32, VertexBuffer.PositionKind);
  129. if (this._uvs32.length > 0) {
  130. vertexData.set(this._uvs32, VertexBuffer.UVKind);
  131. }
  132. var ec = 0; //emissive color value 0 for UVs, 1 for color
  133. if (this._colors32.length > 0) {
  134. ec = 1;
  135. vertexData.set(this._colors32, VertexBuffer.ColorKind);
  136. }
  137. var mesh = new Mesh(this.name, this._scene);
  138. vertexData.applyToMesh(mesh, this._updatable);
  139. this.mesh = mesh;
  140. // free memory
  141. (<any>this._positions) = null;
  142. (<any>this._uvs) = null;
  143. (<any>this._colors) = null;
  144. if (!this._updatable) {
  145. this.particles.length = 0;
  146. }
  147. var mat = new StandardMaterial("point cloud material", this._scene);
  148. mat.emissiveColor = new Color3(ec, ec, ec);
  149. mat.disableLighting = true;
  150. mat.pointsCloud = true;
  151. mat.pointSize = this._size;
  152. mesh.material = mat;
  153. return new Promise((resolve) => resolve(mesh));
  154. }
  155. // adds a new particle object in the particles array
  156. private _addParticle(idx: number, group: PointsGroup, groupId: number, idxInGroup: number): CloudPoint {
  157. var cp = new CloudPoint(idx, group, groupId, idxInGroup, this);
  158. this.particles.push(cp);
  159. return cp;
  160. }
  161. private _randomUnitVector(particle: CloudPoint): void {
  162. particle.position = new Vector3(Math.random(), Math.random(), Math.random());
  163. particle.color = new Color4(1, 1, 1, 1);
  164. }
  165. private _getColorIndicesForCoord(pointsGroup: PointsGroup, x: number, y: number, width: number): Color4 {
  166. var imageData = <Uint8Array>pointsGroup._groupImageData;
  167. var color = y * (width * 4) + x * 4;
  168. var colorIndices = [color, color + 1, color + 2, color + 3];
  169. var redIndex = colorIndices[0];
  170. var greenIndex = colorIndices[1];
  171. var blueIndex = colorIndices[2];
  172. var alphaIndex = colorIndices[3];
  173. var redForCoord = imageData[redIndex];
  174. var greenForCoord = imageData[greenIndex];
  175. var blueForCoord = imageData[blueIndex];
  176. var alphaForCoord = imageData[alphaIndex];
  177. return new Color4(redForCoord / 255, greenForCoord / 255, blueForCoord / 255, alphaForCoord);
  178. }
  179. private _setPointsColorOrUV(mesh: Mesh, pointsGroup: PointsGroup, isVolume: boolean, colorFromTexture?: boolean, hasTexture?: boolean, color?: Color4, range?: number) {
  180. if (isVolume) {
  181. mesh.updateFacetData();
  182. }
  183. var boundInfo = mesh.getBoundingInfo();
  184. var diameter = 2 * boundInfo.boundingSphere.radius;
  185. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  186. var meshInd = <IndicesArray>mesh.getIndices();
  187. var meshUV = <FloatArray>mesh.getVerticesData(VertexBuffer.UVKind);
  188. var meshCol = <FloatArray>mesh.getVerticesData(VertexBuffer.ColorKind);
  189. var place = Vector3.Zero();
  190. mesh.computeWorldMatrix();
  191. var meshMatrix: Matrix = mesh.getWorldMatrix();
  192. if (!meshMatrix.isIdentity()) {
  193. for (var p = 0; p < meshPos.length / 3; p++) {
  194. Vector3.TransformCoordinatesFromFloatsToRef(meshPos[3 * p], meshPos[3 * p + 1], meshPos[3 * p + 2], meshMatrix, place);
  195. meshPos[3 * p] = place.x;
  196. meshPos[3 * p + 1] = place.y;
  197. meshPos[3 * p + 2] = place.z;
  198. }
  199. }
  200. var idxPoints: number = 0;
  201. var index: number = 0;
  202. var id0: number = 0;
  203. var id1: number = 0;
  204. var id2: number = 0;
  205. var v0X: number = 0;
  206. var v0Y: number = 0;
  207. var v0Z: number = 0;
  208. var v1X: number = 0;
  209. var v1Y: number = 0;
  210. var v1Z: number = 0;
  211. var v2X: number = 0;
  212. var v2Y: number = 0;
  213. var v2Z: number = 0;
  214. var vertex0 = Vector3.Zero();
  215. var vertex1 = Vector3.Zero();
  216. var vertex2 = Vector3.Zero();
  217. var vec0 = Vector3.Zero();
  218. var vec1 = Vector3.Zero();
  219. var uv0X: number = 0;
  220. var uv0Y: number = 0;
  221. var uv1X: number = 0;
  222. var uv1Y: number = 0;
  223. var uv2X: number = 0;
  224. var uv2Y: number = 0;
  225. var uv0 = Vector2.Zero();
  226. var uv1 = Vector2.Zero();
  227. var uv2 = Vector2.Zero();
  228. var uvec0 = Vector2.Zero();
  229. var uvec1 = Vector2.Zero();
  230. var col0X: number = 0;
  231. var col0Y: number = 0;
  232. var col0Z: number = 0;
  233. var col0A: number = 0;
  234. var col1X: number = 0;
  235. var col1Y: number = 0;
  236. var col1Z: number = 0;
  237. var col1A: number = 0;
  238. var col2X: number = 0;
  239. var col2Y: number = 0;
  240. var col2Z: number = 0;
  241. var col2A: number = 0;
  242. var col0 = Vector4.Zero();
  243. var col1 = Vector4.Zero();
  244. var col2 = Vector4.Zero();
  245. var colvec0 = Vector4.Zero();
  246. var colvec1 = Vector4.Zero();
  247. var lamda: number = 0;
  248. var mu: number = 0;
  249. range = range ? range : 0;
  250. var facetPoint: Vector3;
  251. var uvPoint: Vector2;
  252. var colPoint: Vector4 = new Vector4(0, 0, 0, 0);
  253. var norm = Vector3.Zero();
  254. var tang = Vector3.Zero();
  255. var biNorm = Vector3.Zero();
  256. var angle = 0;
  257. var facetPlaneVec = Vector3.Zero();
  258. var gap = 0;
  259. var distance = 0;
  260. var ray = new Ray(Vector3.Zero(), new Vector3(1, 0, 0));
  261. var pickInfo: PickingInfo;
  262. var direction = Vector3.Zero();
  263. for (var index = 0; index < meshInd.length / 3; index++) {
  264. id0 = meshInd[3 * index];
  265. id1 = meshInd[3 * index + 1];
  266. id2 = meshInd[3 * index + 2];
  267. v0X = meshPos[3 * id0];
  268. v0Y = meshPos[3 * id0 + 1];
  269. v0Z = meshPos[3 * id0 + 2];
  270. v1X = meshPos[3 * id1];
  271. v1Y = meshPos[3 * id1 + 1];
  272. v1Z = meshPos[3 * id1 + 2];
  273. v2X = meshPos[3 * id2];
  274. v2Y = meshPos[3 * id2 + 1];
  275. v2Z = meshPos[3 * id2 + 2];
  276. vertex0.set(v0X, v0Y, v0Z);
  277. vertex1.set(v1X, v1Y, v1Z);
  278. vertex2.set(v2X, v2Y, v2Z);
  279. vertex1.subtractToRef(vertex0, vec0);
  280. vertex2.subtractToRef(vertex1, vec1);
  281. if (meshUV) {
  282. uv0X = meshUV[2 * id0];
  283. uv0Y = meshUV[2 * id0 + 1];
  284. uv1X = meshUV[2 * id1];
  285. uv1Y = meshUV[2 * id1 + 1];
  286. uv2X = meshUV[2 * id2];
  287. uv2Y = meshUV[2 * id2 + 1];
  288. uv0.set(uv0X, uv0Y);
  289. uv1.set(uv1X, uv1Y);
  290. uv2.set(uv2X, uv2Y);
  291. uv1.subtractToRef(uv0, uvec0);
  292. uv2.subtractToRef(uv1, uvec1);
  293. }
  294. if (meshCol && colorFromTexture) {
  295. col0X = meshCol[4 * id0];
  296. col0Y = meshCol[4 * id0 + 1];
  297. col0Z = meshCol[4 * id0 + 2];
  298. col0A = meshCol[4 * id0 + 3];
  299. col1X = meshCol[4 * id1];
  300. col1Y = meshCol[4 * id1 + 1];
  301. col1Z = meshCol[4 * id1 + 2];
  302. col1A = meshCol[4 * id1 + 3];
  303. col2X = meshCol[4 * id2];
  304. col2Y = meshCol[4 * id2 + 1];
  305. col2Z = meshCol[4 * id2 + 2];
  306. col2A = meshCol[4 * id2 + 3];
  307. col0.set(col0X, col0Y, col0Z, col0A);
  308. col1.set(col1X, col1Y, col1Z, col1A);
  309. col2.set(col2X, col2Y, col2Z, col2A);
  310. col1.subtractToRef(col0, colvec0);
  311. col2.subtractToRef(col1, colvec1);
  312. }
  313. var width: number;
  314. var height: number;
  315. var deltaS: number;
  316. var deltaV: number;
  317. var h: number;
  318. var s: number;
  319. var v: number;
  320. var hsvCol: Color3;
  321. var statedColor: Color3 = new Color3(0, 0, 0);
  322. var colPoint3: Color3 = new Color3(0, 0, 0);
  323. var pointColors: Color4;
  324. var particle: CloudPoint;
  325. for (var i = 0; i < pointsGroup._groupDensity[index]; i++) {
  326. idxPoints = this.particles.length;
  327. this._addParticle(idxPoints, pointsGroup, this._groupCounter, index + i);
  328. particle = this.particles[idxPoints];
  329. //form a point inside the facet v0, v1, v2;
  330. lamda = Scalar.RandomRange(0, 1);
  331. mu = Scalar.RandomRange(0, 1);
  332. facetPoint = vertex0.add(vec0.scale(lamda)).add(vec1.scale(lamda * mu));
  333. if (isVolume) {
  334. norm = mesh.getFacetNormal(index).normalize().scale(-1);
  335. tang = vec0.clone().normalize();
  336. biNorm = Vector3.Cross(norm, tang);
  337. angle = Scalar.RandomRange(0, 2 * Math.PI);
  338. facetPlaneVec = tang.scale(Math.cos(angle)).add(biNorm.scale(Math.sin(angle)));
  339. angle = Scalar.RandomRange(0.1, Math.PI / 2);
  340. direction = facetPlaneVec.scale(Math.cos(angle)).add(norm.scale(Math.sin(angle)));
  341. ray.origin = facetPoint.add(direction.scale(0.00001));
  342. ray.direction = direction;
  343. ray.length = diameter;
  344. pickInfo = ray.intersectsMesh(mesh);
  345. if (pickInfo.hit) {
  346. distance = pickInfo.pickedPoint!.subtract(facetPoint).length();
  347. gap = Scalar.RandomRange(0, 1) * distance;
  348. facetPoint.addInPlace(direction.scale(gap));
  349. }
  350. }
  351. particle.position = facetPoint.clone();
  352. this._positions.push(particle.position.x, particle.position.y, particle.position.z);
  353. if (colorFromTexture !== undefined) {
  354. if (meshUV) {
  355. uvPoint = uv0.add(uvec0.scale(lamda)).add(uvec1.scale(lamda * mu));
  356. if (colorFromTexture) { //Set particle color to texture color
  357. if (hasTexture && pointsGroup._groupImageData !== null) {
  358. width = pointsGroup._groupImgWidth;
  359. height = pointsGroup._groupImgHeight;
  360. pointColors = this._getColorIndicesForCoord(pointsGroup, Math.round(uvPoint.x * width), Math.round(uvPoint.y * height), width);
  361. particle.color = pointColors;
  362. this._colors.push(pointColors.r, pointColors.g, pointColors.b, pointColors.a);
  363. }
  364. else {
  365. if (meshCol) { //failure in texture and colors available
  366. colPoint = col0.add(colvec0.scale(lamda)).add(colvec1.scale(lamda * mu));
  367. particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  368. this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  369. }
  370. else {
  371. colPoint = col0.set(Math.random(), Math.random(), Math.random(), 1);
  372. particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  373. this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  374. }
  375. }
  376. }
  377. else { //Set particle uv based on a mesh uv
  378. particle.uv = uvPoint.clone();
  379. this._uvs.push(particle.uv.x, particle.uv.y);
  380. }
  381. }
  382. }
  383. else {
  384. if (color) {
  385. statedColor.set(color.r, color.g, color.b);
  386. deltaS = Scalar.RandomRange(-range, range);
  387. deltaV = Scalar.RandomRange(-range, range);
  388. hsvCol = statedColor.toHSV();
  389. h = hsvCol.r;
  390. s = hsvCol.g + deltaS;
  391. v = hsvCol.b + deltaV;
  392. if (s < 0) {
  393. s = 0;
  394. }
  395. if (s > 1) {
  396. s = 1;
  397. }
  398. if (v < 0) {
  399. v = 0;
  400. }
  401. if (v > 1) {
  402. v = 1;
  403. }
  404. Color3.HSVtoRGBToRef(h, s, v, colPoint3);
  405. colPoint.set(colPoint3.r, colPoint3.g, colPoint3.b, 1);
  406. }
  407. else {
  408. colPoint = col0.set(Math.random(), Math.random(), Math.random(), 1);
  409. }
  410. particle.color = new Color4(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  411. this._colors.push(colPoint.x, colPoint.y, colPoint.z, colPoint.w);
  412. }
  413. }
  414. }
  415. }
  416. // stores mesh texture in dynamic texture for color pixel retrieval
  417. // when pointColor type is color for surface points
  418. private _colorFromTexture(mesh: Mesh, pointsGroup: PointsGroup, isVolume: boolean): void {
  419. if (mesh.material === null) {
  420. Logger.Warn(mesh.name + "has no material.");
  421. pointsGroup._groupImageData = null;
  422. this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false);
  423. return;
  424. }
  425. var mat = mesh.material;
  426. let textureList: BaseTexture[] = mat.getActiveTextures();
  427. if (textureList.length === 0) {
  428. Logger.Warn(mesh.name + "has no useable texture.");
  429. pointsGroup._groupImageData = null;
  430. this._setPointsColorOrUV(mesh, pointsGroup, isVolume, true, false);
  431. return;
  432. }
  433. var clone = <Mesh>mesh.clone();
  434. clone.setEnabled(false);
  435. this._promises.push(new Promise((resolve) => {
  436. BaseTexture.WhenAllReady(textureList, () => {
  437. let n = pointsGroup._textureNb;
  438. pointsGroup._groupImageData = textureList[n].readPixels();
  439. pointsGroup._groupImgWidth = textureList[n].getSize().width;
  440. pointsGroup._groupImgHeight = textureList[this.nbParticles].getSize().height;
  441. this._setPointsColorOrUV(clone, pointsGroup, isVolume, true, true);
  442. clone.dispose();
  443. return resolve();
  444. });
  445. }));
  446. }
  447. // calculates the point density per facet of a mesh for surface points
  448. private _calculateDensity(nbPoints: number, positions: FloatArray, indices: FloatArray): number[] {
  449. var density: number[] = new Array<number>();
  450. var index: number;
  451. var id0: number;
  452. var id1: number;
  453. var id2: number;
  454. var v0X: number;
  455. var v0Y: number;
  456. var v0Z: number;
  457. var v1X: number;
  458. var v1Y: number;
  459. var v1Z: number;
  460. var v2X: number;
  461. var v2Y: number;
  462. var v2Z: number;
  463. var vertex0 = Vector3.Zero();
  464. var vertex1 = Vector3.Zero();
  465. var vertex2 = Vector3.Zero();
  466. var vec0 = Vector3.Zero();
  467. var vec1 = Vector3.Zero();
  468. var vec2 = Vector3.Zero();
  469. var a: number; //length of side of triangle
  470. var b: number; //length of side of triangle
  471. var c: number; //length of side of triangle
  472. var p: number; //perimeter of triangle
  473. var area: number;
  474. var areas: number[] = new Array<number>();
  475. var surfaceArea: number = 0;
  476. var nbFacets = indices.length / 3;
  477. //surface area
  478. for (var index = 0; index < nbFacets; index++) {
  479. id0 = indices[3 * index];
  480. id1 = indices[3 * index + 1];
  481. id2 = indices[3 * index + 2];
  482. v0X = positions[3 * id0];
  483. v0Y = positions[3 * id0 + 1];
  484. v0Z = positions[3 * id0 + 2];
  485. v1X = positions[3 * id1];
  486. v1Y = positions[3 * id1 + 1];
  487. v1Z = positions[3 * id1 + 2];
  488. v2X = positions[3 * id2];
  489. v2Y = positions[3 * id2 + 1];
  490. v2Z = positions[3 * id2 + 2];
  491. vertex0.set(v0X, v0Y, v0Z);
  492. vertex1.set(v1X, v1Y, v1Z);
  493. vertex2.set(v2X, v2Y, v2Z);
  494. vertex1.subtractToRef(vertex0, vec0);
  495. vertex2.subtractToRef(vertex1, vec1);
  496. vertex2.subtractToRef(vertex0, vec2);
  497. a = vec0.length();
  498. b = vec1.length();
  499. c = vec2.length();
  500. p = (a + b + c) / 2;
  501. area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
  502. surfaceArea += area;
  503. areas[index] = area;
  504. }
  505. var pointCount: number = 0;
  506. for (var index = 0; index < nbFacets; index++) {
  507. density[index] = Math.floor(nbPoints * areas[index] / surfaceArea);
  508. pointCount += density[index];
  509. }
  510. var diff: number = nbPoints - pointCount;
  511. var pointsPerFacet: number = Math.floor(diff / nbFacets);
  512. var extraPoints: number = diff % nbFacets;
  513. if (pointsPerFacet > 0) {
  514. density = density.map((x) => x + pointsPerFacet);
  515. }
  516. for (var index = 0; index < extraPoints; index++) {
  517. density[index] += 1;
  518. }
  519. return density;
  520. }
  521. /**
  522. * Adds points to the PCS in random positions within a unit sphere
  523. * @param nb (positive integer) the number of particles to be created from this model
  524. * @param pointFunction is an optional javascript function to be called for each particle on PCS creation
  525. * @returns the number of groups in the system
  526. */
  527. public addPoints(nb: number, pointFunction: any = this._randomUnitVector): number {
  528. var pointsGroup = new PointsGroup(this._groupCounter, pointFunction);
  529. var cp: CloudPoint;
  530. // particles
  531. var idx = this.nbParticles;
  532. for (var i = 0; i < nb; i++) {
  533. cp = this._addParticle(idx, pointsGroup, this._groupCounter, i);
  534. if (pointsGroup && pointsGroup._positionFunction) {
  535. pointsGroup._positionFunction(cp, idx, i);
  536. }
  537. this._positions.push(cp.position.x, cp.position.y, cp.position.z);
  538. if (cp.color) {
  539. this._colors.push(cp.color.r, cp.color.g, cp.color.b, cp.color.a);
  540. }
  541. if (cp.uv) {
  542. this._uvs.push(cp.uv.x, cp.uv.y);
  543. }
  544. idx++;
  545. }
  546. this.nbParticles += nb;
  547. this._groupCounter++;
  548. return this._groupCounter;
  549. }
  550. /**
  551. * Adds points to the PCS from the surface of the model shape
  552. * @param mesh is any Mesh object that will be used as a surface model for the points
  553. * @param nb (positive integer) the number of particles to be created from this model
  554. * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible)
  555. * @param color (color3) to be used when colorWith is stated
  556. * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color
  557. * @returns the number of groups in the system
  558. */
  559. public addSurfacePoints(mesh: Mesh, nb: number, colorWith?: number, color?: Color4 | number, range?: number): number {
  560. var colored = colorWith ? colorWith : PointColor.Random;
  561. if (isNaN(colored) || colored < 0 || colored > 3) {
  562. colored = PointColor.Random ;
  563. }
  564. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  565. var meshInd = <IndicesArray>mesh.getIndices();
  566. this._groups.push(this._groupCounter);
  567. var pointsGroup = new PointsGroup(this._groupCounter, null);
  568. pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd);
  569. if (colored === PointColor.Color) {
  570. pointsGroup._textureNb = <number>color ? <number>color : 0;
  571. }
  572. else {
  573. color = <Color4>color ? <Color4>color : new Color4(1, 1, 1, 1);
  574. }
  575. switch (colored) {
  576. case PointColor.Color:
  577. this._colorFromTexture(mesh, pointsGroup, false);
  578. break;
  579. case PointColor.UV:
  580. this._setPointsColorOrUV(mesh, pointsGroup, false, false, false);
  581. break;
  582. case PointColor.Random:
  583. this._setPointsColorOrUV(mesh, pointsGroup, false);
  584. break;
  585. case PointColor.Stated:
  586. this._setPointsColorOrUV(mesh, pointsGroup, false, undefined, undefined, <Color4>color, range);
  587. break;
  588. }
  589. this.nbParticles += nb;
  590. this._groupCounter++;
  591. return this._groupCounter - 1;
  592. }
  593. /**
  594. * Adds points to the PCS inside the model shape
  595. * @param mesh is any Mesh object that will be used as a surface model for the points
  596. * @param nb (positive integer) the number of particles to be created from this model
  597. * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible),
  598. * @param color (color4) to be used when colorWith is stated
  599. * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color
  600. * @returns the number of groups in the system
  601. */
  602. public addVolumePoints(mesh: Mesh, nb: number, colorWith?: number, color?: Color4, range?: number): number {
  603. var colored = colorWith ? colorWith : PointColor.Random;
  604. if (isNaN(colored) || colored < 0 || colored > 3) {
  605. colored = PointColor.Random;
  606. }
  607. color = color ? color : new Color4(1, 1, 1, 1);
  608. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  609. var meshInd = <IndicesArray>mesh.getIndices();
  610. this._groups.push(this._groupCounter);
  611. var pointsGroup = new PointsGroup(this._groupCounter, null);
  612. pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd);
  613. switch (colored) {
  614. case PointColor.Color:
  615. this._colorFromTexture(mesh, pointsGroup, true);
  616. break;
  617. case PointColor.UV:
  618. this._setPointsColorOrUV(mesh, pointsGroup, true, false, false);
  619. break;
  620. case PointColor.Random:
  621. this._setPointsColorOrUV(mesh, pointsGroup, true);
  622. break;
  623. case PointColor.Stated:
  624. this._setPointsColorOrUV(mesh, pointsGroup, true, undefined, undefined, color, range);
  625. break;
  626. }
  627. this.nbParticles += nb;
  628. this._groupCounter++;
  629. return this._groupCounter - 1;
  630. }
  631. /**
  632. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  633. * This method calls `updateParticle()` for each particle of the SPS.
  634. * For an animated SPS, it is usually called within the render loop.
  635. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  636. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  637. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  638. * @returns the PCS.
  639. */
  640. public setParticles(start: number = 0, end: number = this.nbParticles - 1, update: boolean = true): PointsCloudSystem {
  641. if (!this._updatable || !this._isReady) {
  642. return this;
  643. }
  644. // custom beforeUpdate
  645. this.beforeUpdateParticles(start, end, update);
  646. const rotMatrix = TmpVectors.Matrix[0];
  647. const mesh = this.mesh;
  648. const colors32 = this._colors32;
  649. const positions32 = this._positions32;
  650. const uvs32 = this._uvs32;
  651. const tempVectors = TmpVectors.Vector3;
  652. const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  653. const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  654. const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  655. const minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  656. const maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  657. Matrix.IdentityToRef(rotMatrix);
  658. var idx = 0; // current index of the particle
  659. if (this.mesh.isFacetDataEnabled) {
  660. this._computeBoundingBox = true;
  661. }
  662. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  663. if (this._computeBoundingBox) {
  664. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  665. const boundingInfo = this.mesh._boundingInfo;
  666. if (boundingInfo) {
  667. minimum.copyFrom(boundingInfo.minimum);
  668. maximum.copyFrom(boundingInfo.maximum);
  669. }
  670. }
  671. }
  672. var idx = 0; // particle index
  673. var pindex = 0; //index in positions array
  674. var cindex = 0; //index in color array
  675. var uindex = 0; //index in uv array
  676. // particle loop
  677. for (var p = start; p <= end; p++) {
  678. const particle = this.particles[p];
  679. idx = particle.idx;
  680. pindex = 3 * idx;
  681. cindex = 4 * idx;
  682. uindex = 2 * idx;
  683. // call to custom user function to update the particle properties
  684. this.updateParticle(particle);
  685. const particleRotationMatrix = particle._rotationMatrix;
  686. const particlePosition = particle.position;
  687. const particleGlobalPosition = particle._globalPosition;
  688. if (this._computeParticleRotation) {
  689. particle.getRotationMatrix(rotMatrix);
  690. }
  691. const particleHasParent = (particle.parentId !== null);
  692. if (particleHasParent) {
  693. const parent = this.particles[particle.parentId!];
  694. const parentRotationMatrix = parent._rotationMatrix;
  695. const parentGlobalPosition = parent._globalPosition;
  696. const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  697. const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  698. const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  699. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  700. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  701. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  702. if (this._computeParticleRotation) {
  703. const rotMatrixValues = rotMatrix.m;
  704. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  705. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  706. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  707. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  708. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  709. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  710. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  711. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  712. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  713. }
  714. }
  715. else {
  716. particleGlobalPosition.x = 0;
  717. particleGlobalPosition.y = 0;
  718. particleGlobalPosition.z = 0;
  719. if (this._computeParticleRotation) {
  720. const rotMatrixValues = rotMatrix.m;
  721. particleRotationMatrix[0] = rotMatrixValues[0];
  722. particleRotationMatrix[1] = rotMatrixValues[1];
  723. particleRotationMatrix[2] = rotMatrixValues[2];
  724. particleRotationMatrix[3] = rotMatrixValues[4];
  725. particleRotationMatrix[4] = rotMatrixValues[5];
  726. particleRotationMatrix[5] = rotMatrixValues[6];
  727. particleRotationMatrix[6] = rotMatrixValues[8];
  728. particleRotationMatrix[7] = rotMatrixValues[9];
  729. particleRotationMatrix[8] = rotMatrixValues[10];
  730. }
  731. }
  732. const pivotBackTranslation = tempVectors[11];
  733. if (particle.translateFromPivot) {
  734. pivotBackTranslation.setAll(0.0);
  735. }
  736. else {
  737. pivotBackTranslation.copyFrom(particle.pivot);
  738. }
  739. // positions
  740. const tmpVertex = tempVectors[0];
  741. tmpVertex.copyFrom(particle.position);
  742. const vertexX = tmpVertex.x - particle.pivot.x;
  743. const vertexY = tmpVertex.y - particle.pivot.y;
  744. const vertexZ = tmpVertex.z - particle.pivot.z;
  745. let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  746. let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  747. let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  748. rotatedX += pivotBackTranslation.x;
  749. rotatedY += pivotBackTranslation.y;
  750. rotatedZ += pivotBackTranslation.z;
  751. const px = positions32[pindex] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  752. const py = positions32[pindex + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  753. const pz = positions32[pindex + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  754. if (this._computeBoundingBox) {
  755. minimum.minimizeInPlaceFromFloats(px, py, pz);
  756. maximum.maximizeInPlaceFromFloats(px, py, pz);
  757. }
  758. if (this._computeParticleColor && particle.color) {
  759. const color = particle.color;
  760. const colors32 = this._colors32;
  761. colors32[cindex] = color.r;
  762. colors32[cindex + 1] = color.g;
  763. colors32[cindex + 2] = color.b;
  764. colors32[cindex + 3] = color.a;
  765. }
  766. if (this._computeParticleTexture && particle.uv) {
  767. const uv = particle.uv;
  768. const uvs32 = this._uvs32;
  769. uvs32[uindex] = uv.x;
  770. uvs32[uindex + 1] = uv.y;
  771. }
  772. }
  773. // if the VBO must be updated
  774. if (update) {
  775. if (this._computeParticleColor) {
  776. mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false);
  777. }
  778. if (this._computeParticleTexture) {
  779. mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false);
  780. }
  781. mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false);
  782. }
  783. if (this._computeBoundingBox) {
  784. if (mesh._boundingInfo) {
  785. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  786. }
  787. else {
  788. mesh._boundingInfo = new BoundingInfo(minimum, maximum, mesh._worldMatrix);
  789. }
  790. }
  791. this.afterUpdateParticles(start, end, update);
  792. return this;
  793. }
  794. /**
  795. * Disposes the PCS.
  796. */
  797. public dispose(): void {
  798. this.mesh.dispose();
  799. this.vars = null;
  800. // drop references to internal big arrays for the GC
  801. (<any>this._positions) = null;
  802. (<any>this._indices) = null;
  803. (<any>this._normals) = null;
  804. (<any>this._uvs) = null;
  805. (<any>this._colors) = null;
  806. (<any>this._indices32) = null;
  807. (<any>this._positions32) = null;
  808. (<any>this._uvs32) = null;
  809. (<any>this._colors32) = null;
  810. }
  811. /**
  812. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  813. * doc :
  814. * @returns the PCS.
  815. */
  816. public refreshVisibleSize(): PointsCloudSystem {
  817. if (!this._isVisibilityBoxLocked) {
  818. this.mesh.refreshBoundingInfo();
  819. }
  820. return this;
  821. }
  822. /**
  823. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  824. * @param size the size (float) of the visibility box
  825. * note : this doesn't lock the PCS mesh bounding box.
  826. * doc :
  827. */
  828. public setVisibilityBox(size: number): void {
  829. var vis = size / 2;
  830. this.mesh._boundingInfo = new BoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));
  831. }
  832. /**
  833. * Gets whether the PCS is always visible or not
  834. * doc :
  835. */
  836. public get isAlwaysVisible(): boolean {
  837. return this._alwaysVisible;
  838. }
  839. /**
  840. * Sets the PCS as always visible or not
  841. * doc :
  842. */
  843. public set isAlwaysVisible(val: boolean) {
  844. this._alwaysVisible = val;
  845. this.mesh.alwaysSelectAsActiveMesh = val;
  846. }
  847. /**
  848. * Tells to `setParticles()` to compute the particle rotations or not
  849. * Default value : false. The PCS is faster when it's set to false
  850. * Note : particle rotations are only applied to parent particles
  851. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate
  852. */
  853. public set computeParticleRotation(val: boolean) {
  854. this._computeParticleRotation = val;
  855. }
  856. /**
  857. * Tells to `setParticles()` to compute the particle colors or not.
  858. * Default value : true. The PCS is faster when it's set to false.
  859. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  860. */
  861. public set computeParticleColor(val: boolean) {
  862. this._computeParticleColor = val;
  863. }
  864. public set computeParticleTexture(val: boolean) {
  865. this._computeParticleTexture = val;
  866. }
  867. /**
  868. * Gets if `setParticles()` computes the particle colors or not.
  869. * Default value : false. The PCS is faster when it's set to false.
  870. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  871. */
  872. public get computeParticleColor(): boolean {
  873. return this._computeParticleColor;
  874. }
  875. /**
  876. * Gets if `setParticles()` computes the particle textures or not.
  877. * Default value : false. The PCS is faster when it's set to false.
  878. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  879. */
  880. public get computeParticleTexture(): boolean {
  881. return this._computeParticleTexture;
  882. }
  883. /**
  884. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  885. */
  886. public set computeBoundingBox(val: boolean) {
  887. this._computeBoundingBox = val;
  888. }
  889. /**
  890. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  891. */
  892. public get computeBoundingBox(): boolean {
  893. return this._computeBoundingBox;
  894. }
  895. // =======================================================================
  896. // Particle behavior logic
  897. // these following methods may be overwritten by users to fit their needs
  898. /**
  899. * This function does nothing. It may be overwritten to set all the particle first values.
  900. * The PCS doesn't call this function, you may have to call it by your own.
  901. * doc :
  902. */
  903. public initParticles(): void {
  904. }
  905. /**
  906. * This function does nothing. It may be overwritten to recycle a particle
  907. * The PCS doesn't call this function, you can to call it
  908. * doc :
  909. * @param particle The particle to recycle
  910. * @returns the recycled particle
  911. */
  912. public recycleParticle(particle: CloudPoint): CloudPoint {
  913. return particle;
  914. }
  915. /**
  916. * Updates a particle : this function should be overwritten by the user.
  917. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  918. * doc :
  919. * @example : just set a particle position or velocity and recycle conditions
  920. * @param particle The particle to update
  921. * @returns the updated particle
  922. */
  923. public updateParticle(particle: CloudPoint): CloudPoint {
  924. return particle;
  925. }
  926. /**
  927. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  928. * This does nothing and may be overwritten by the user.
  929. * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle()
  930. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  931. * @param update the boolean update value actually passed to setParticles()
  932. */
  933. public beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  934. }
  935. /**
  936. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  937. * This will be passed three parameters.
  938. * This does nothing and may be overwritten by the user.
  939. * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle()
  940. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  941. * @param update the boolean update value actually passed to setParticles()
  942. */
  943. public afterUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  944. }
  945. }