pointsCloudSystem.ts 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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. if (n < 0) {
  439. n = 0;
  440. }
  441. if (n > textureList.length - 1) {
  442. n = textureList.length - 1;
  443. }
  444. const finalize = () => {
  445. pointsGroup._groupImgWidth = textureList[n].getSize().width;
  446. pointsGroup._groupImgHeight = textureList[n].getSize().height;
  447. this._setPointsColorOrUV(clone, pointsGroup, isVolume, true, true);
  448. clone.dispose();
  449. resolve();
  450. };
  451. pointsGroup._groupImageData = null;
  452. const dataPromise = textureList[n].readPixels();
  453. if (!dataPromise) {
  454. finalize();
  455. } else {
  456. dataPromise.then((data) => {
  457. pointsGroup._groupImageData = data;
  458. finalize();
  459. });
  460. }
  461. });
  462. }));
  463. }
  464. // calculates the point density per facet of a mesh for surface points
  465. private _calculateDensity(nbPoints: number, positions: FloatArray, indices: FloatArray): number[] {
  466. var density: number[] = new Array<number>();
  467. var index: number;
  468. var id0: number;
  469. var id1: number;
  470. var id2: number;
  471. var v0X: number;
  472. var v0Y: number;
  473. var v0Z: number;
  474. var v1X: number;
  475. var v1Y: number;
  476. var v1Z: number;
  477. var v2X: number;
  478. var v2Y: number;
  479. var v2Z: number;
  480. var vertex0 = Vector3.Zero();
  481. var vertex1 = Vector3.Zero();
  482. var vertex2 = Vector3.Zero();
  483. var vec0 = Vector3.Zero();
  484. var vec1 = Vector3.Zero();
  485. var vec2 = Vector3.Zero();
  486. var a: number; //length of side of triangle
  487. var b: number; //length of side of triangle
  488. var c: number; //length of side of triangle
  489. var p: number; //perimeter of triangle
  490. var area: number;
  491. var areas: number[] = new Array<number>();
  492. var surfaceArea: number = 0;
  493. var nbFacets = indices.length / 3;
  494. //surface area
  495. for (var index = 0; index < nbFacets; index++) {
  496. id0 = indices[3 * index];
  497. id1 = indices[3 * index + 1];
  498. id2 = indices[3 * index + 2];
  499. v0X = positions[3 * id0];
  500. v0Y = positions[3 * id0 + 1];
  501. v0Z = positions[3 * id0 + 2];
  502. v1X = positions[3 * id1];
  503. v1Y = positions[3 * id1 + 1];
  504. v1Z = positions[3 * id1 + 2];
  505. v2X = positions[3 * id2];
  506. v2Y = positions[3 * id2 + 1];
  507. v2Z = positions[3 * id2 + 2];
  508. vertex0.set(v0X, v0Y, v0Z);
  509. vertex1.set(v1X, v1Y, v1Z);
  510. vertex2.set(v2X, v2Y, v2Z);
  511. vertex1.subtractToRef(vertex0, vec0);
  512. vertex2.subtractToRef(vertex1, vec1);
  513. vertex2.subtractToRef(vertex0, vec2);
  514. a = vec0.length();
  515. b = vec1.length();
  516. c = vec2.length();
  517. p = (a + b + c) / 2;
  518. area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
  519. surfaceArea += area;
  520. areas[index] = area;
  521. }
  522. var pointCount: number = 0;
  523. for (var index = 0; index < nbFacets; index++) {
  524. density[index] = Math.floor(nbPoints * areas[index] / surfaceArea);
  525. pointCount += density[index];
  526. }
  527. var diff: number = nbPoints - pointCount;
  528. var pointsPerFacet: number = Math.floor(diff / nbFacets);
  529. var extraPoints: number = diff % nbFacets;
  530. if (pointsPerFacet > 0) {
  531. density = density.map((x) => x + pointsPerFacet);
  532. }
  533. for (var index = 0; index < extraPoints; index++) {
  534. density[index] += 1;
  535. }
  536. return density;
  537. }
  538. /**
  539. * Adds points to the PCS in random positions within a unit sphere
  540. * @param nb (positive integer) the number of particles to be created from this model
  541. * @param pointFunction is an optional javascript function to be called for each particle on PCS creation
  542. * @returns the number of groups in the system
  543. */
  544. public addPoints(nb: number, pointFunction: any = this._randomUnitVector): number {
  545. var pointsGroup = new PointsGroup(this._groupCounter, pointFunction);
  546. var cp: CloudPoint;
  547. // particles
  548. var idx = this.nbParticles;
  549. for (var i = 0; i < nb; i++) {
  550. cp = this._addParticle(idx, pointsGroup, this._groupCounter, i);
  551. if (pointsGroup && pointsGroup._positionFunction) {
  552. pointsGroup._positionFunction(cp, idx, i);
  553. }
  554. this._positions.push(cp.position.x, cp.position.y, cp.position.z);
  555. if (cp.color) {
  556. this._colors.push(cp.color.r, cp.color.g, cp.color.b, cp.color.a);
  557. }
  558. if (cp.uv) {
  559. this._uvs.push(cp.uv.x, cp.uv.y);
  560. }
  561. idx++;
  562. }
  563. this.nbParticles += nb;
  564. this._groupCounter++;
  565. return this._groupCounter;
  566. }
  567. /**
  568. * Adds points to the PCS from the surface of the model shape
  569. * @param mesh is any Mesh object that will be used as a surface model for the points
  570. * @param nb (positive integer) the number of particles to be created from this model
  571. * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible)
  572. * @param color (color4) to be used when colorWith is stated or color (number) when used to specify texture position
  573. * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color
  574. * @returns the number of groups in the system
  575. */
  576. public addSurfacePoints(mesh: Mesh, nb: number, colorWith?: number, color?: Color4 | number, range?: number): number {
  577. var colored = colorWith ? colorWith : PointColor.Random;
  578. if (isNaN(colored) || colored < 0 || colored > 3) {
  579. colored = PointColor.Random ;
  580. }
  581. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  582. var meshInd = <IndicesArray>mesh.getIndices();
  583. this._groups.push(this._groupCounter);
  584. var pointsGroup = new PointsGroup(this._groupCounter, null);
  585. pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd);
  586. if (colored === PointColor.Color) {
  587. pointsGroup._textureNb = <number>color ? <number>color : 0;
  588. }
  589. else {
  590. color = <Color4>color ? <Color4>color : new Color4(1, 1, 1, 1);
  591. }
  592. switch (colored) {
  593. case PointColor.Color:
  594. this._colorFromTexture(mesh, pointsGroup, false);
  595. break;
  596. case PointColor.UV:
  597. this._setPointsColorOrUV(mesh, pointsGroup, false, false, false);
  598. break;
  599. case PointColor.Random:
  600. this._setPointsColorOrUV(mesh, pointsGroup, false);
  601. break;
  602. case PointColor.Stated:
  603. this._setPointsColorOrUV(mesh, pointsGroup, false, undefined, undefined, <Color4>color, range);
  604. break;
  605. }
  606. this.nbParticles += nb;
  607. this._groupCounter++;
  608. return this._groupCounter - 1;
  609. }
  610. /**
  611. * Adds points to the PCS inside the model shape
  612. * @param mesh is any Mesh object that will be used as a surface model for the points
  613. * @param nb (positive integer) the number of particles to be created from this model
  614. * @param colorWith determines whether a point is colored using color (default), uv, random, stated or none (invisible)
  615. * @param color (color4) to be used when colorWith is stated or color (number) when used to specify texture position
  616. * @param range (number from 0 to 1) to determine the variation in shape and tone for a stated color
  617. * @returns the number of groups in the system
  618. */
  619. public addVolumePoints(mesh: Mesh, nb: number, colorWith?: number, color?: Color4 | number, range?: number): number {
  620. var colored = colorWith ? colorWith : PointColor.Random;
  621. if (isNaN(colored) || colored < 0 || colored > 3) {
  622. colored = PointColor.Random;
  623. }
  624. var meshPos = <FloatArray>mesh.getVerticesData(VertexBuffer.PositionKind);
  625. var meshInd = <IndicesArray>mesh.getIndices();
  626. this._groups.push(this._groupCounter);
  627. var pointsGroup = new PointsGroup(this._groupCounter, null);
  628. pointsGroup._groupDensity = this._calculateDensity(nb, meshPos, meshInd);
  629. if (colored === PointColor.Color) {
  630. pointsGroup._textureNb = <number>color ? <number>color : 0;
  631. }
  632. else {
  633. color = <Color4>color ? <Color4>color : new Color4(1, 1, 1, 1);
  634. }
  635. switch (colored) {
  636. case PointColor.Color:
  637. this._colorFromTexture(mesh, pointsGroup, true);
  638. break;
  639. case PointColor.UV:
  640. this._setPointsColorOrUV(mesh, pointsGroup, true, false, false);
  641. break;
  642. case PointColor.Random:
  643. this._setPointsColorOrUV(mesh, pointsGroup, true);
  644. break;
  645. case PointColor.Stated:
  646. this._setPointsColorOrUV(mesh, pointsGroup, true, undefined, undefined, <Color4>color, range);
  647. break;
  648. }
  649. this.nbParticles += nb;
  650. this._groupCounter++;
  651. return this._groupCounter - 1;
  652. }
  653. /**
  654. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  655. * This method calls `updateParticle()` for each particle of the SPS.
  656. * For an animated SPS, it is usually called within the render loop.
  657. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  658. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  659. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  660. * @returns the PCS.
  661. */
  662. public setParticles(start: number = 0, end: number = this.nbParticles - 1, update: boolean = true): PointsCloudSystem {
  663. if (!this._updatable || !this._isReady) {
  664. return this;
  665. }
  666. // custom beforeUpdate
  667. this.beforeUpdateParticles(start, end, update);
  668. const rotMatrix = TmpVectors.Matrix[0];
  669. const mesh = this.mesh;
  670. const colors32 = this._colors32;
  671. const positions32 = this._positions32;
  672. const uvs32 = this._uvs32;
  673. const tempVectors = TmpVectors.Vector3;
  674. const camAxisX = tempVectors[5].copyFromFloats(1.0, 0.0, 0.0);
  675. const camAxisY = tempVectors[6].copyFromFloats(0.0, 1.0, 0.0);
  676. const camAxisZ = tempVectors[7].copyFromFloats(0.0, 0.0, 1.0);
  677. const minimum = tempVectors[8].setAll(Number.MAX_VALUE);
  678. const maximum = tempVectors[9].setAll(-Number.MAX_VALUE);
  679. Matrix.IdentityToRef(rotMatrix);
  680. var idx = 0; // current index of the particle
  681. if (this.mesh.isFacetDataEnabled) {
  682. this._computeBoundingBox = true;
  683. }
  684. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  685. if (this._computeBoundingBox) {
  686. if (start != 0 || end != this.nbParticles - 1) { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  687. const boundingInfo = this.mesh._boundingInfo;
  688. if (boundingInfo) {
  689. minimum.copyFrom(boundingInfo.minimum);
  690. maximum.copyFrom(boundingInfo.maximum);
  691. }
  692. }
  693. }
  694. var idx = 0; // particle index
  695. var pindex = 0; //index in positions array
  696. var cindex = 0; //index in color array
  697. var uindex = 0; //index in uv array
  698. // particle loop
  699. for (var p = start; p <= end; p++) {
  700. const particle = this.particles[p];
  701. idx = particle.idx;
  702. pindex = 3 * idx;
  703. cindex = 4 * idx;
  704. uindex = 2 * idx;
  705. // call to custom user function to update the particle properties
  706. this.updateParticle(particle);
  707. const particleRotationMatrix = particle._rotationMatrix;
  708. const particlePosition = particle.position;
  709. const particleGlobalPosition = particle._globalPosition;
  710. if (this._computeParticleRotation) {
  711. particle.getRotationMatrix(rotMatrix);
  712. }
  713. const particleHasParent = (particle.parentId !== null);
  714. if (particleHasParent) {
  715. const parent = this.particles[particle.parentId!];
  716. const parentRotationMatrix = parent._rotationMatrix;
  717. const parentGlobalPosition = parent._globalPosition;
  718. const rotatedY = particlePosition.x * parentRotationMatrix[1] + particlePosition.y * parentRotationMatrix[4] + particlePosition.z * parentRotationMatrix[7];
  719. const rotatedX = particlePosition.x * parentRotationMatrix[0] + particlePosition.y * parentRotationMatrix[3] + particlePosition.z * parentRotationMatrix[6];
  720. const rotatedZ = particlePosition.x * parentRotationMatrix[2] + particlePosition.y * parentRotationMatrix[5] + particlePosition.z * parentRotationMatrix[8];
  721. particleGlobalPosition.x = parentGlobalPosition.x + rotatedX;
  722. particleGlobalPosition.y = parentGlobalPosition.y + rotatedY;
  723. particleGlobalPosition.z = parentGlobalPosition.z + rotatedZ;
  724. if (this._computeParticleRotation) {
  725. const rotMatrixValues = rotMatrix.m;
  726. particleRotationMatrix[0] = rotMatrixValues[0] * parentRotationMatrix[0] + rotMatrixValues[1] * parentRotationMatrix[3] + rotMatrixValues[2] * parentRotationMatrix[6];
  727. particleRotationMatrix[1] = rotMatrixValues[0] * parentRotationMatrix[1] + rotMatrixValues[1] * parentRotationMatrix[4] + rotMatrixValues[2] * parentRotationMatrix[7];
  728. particleRotationMatrix[2] = rotMatrixValues[0] * parentRotationMatrix[2] + rotMatrixValues[1] * parentRotationMatrix[5] + rotMatrixValues[2] * parentRotationMatrix[8];
  729. particleRotationMatrix[3] = rotMatrixValues[4] * parentRotationMatrix[0] + rotMatrixValues[5] * parentRotationMatrix[3] + rotMatrixValues[6] * parentRotationMatrix[6];
  730. particleRotationMatrix[4] = rotMatrixValues[4] * parentRotationMatrix[1] + rotMatrixValues[5] * parentRotationMatrix[4] + rotMatrixValues[6] * parentRotationMatrix[7];
  731. particleRotationMatrix[5] = rotMatrixValues[4] * parentRotationMatrix[2] + rotMatrixValues[5] * parentRotationMatrix[5] + rotMatrixValues[6] * parentRotationMatrix[8];
  732. particleRotationMatrix[6] = rotMatrixValues[8] * parentRotationMatrix[0] + rotMatrixValues[9] * parentRotationMatrix[3] + rotMatrixValues[10] * parentRotationMatrix[6];
  733. particleRotationMatrix[7] = rotMatrixValues[8] * parentRotationMatrix[1] + rotMatrixValues[9] * parentRotationMatrix[4] + rotMatrixValues[10] * parentRotationMatrix[7];
  734. particleRotationMatrix[8] = rotMatrixValues[8] * parentRotationMatrix[2] + rotMatrixValues[9] * parentRotationMatrix[5] + rotMatrixValues[10] * parentRotationMatrix[8];
  735. }
  736. }
  737. else {
  738. particleGlobalPosition.x = 0;
  739. particleGlobalPosition.y = 0;
  740. particleGlobalPosition.z = 0;
  741. if (this._computeParticleRotation) {
  742. const rotMatrixValues = rotMatrix.m;
  743. particleRotationMatrix[0] = rotMatrixValues[0];
  744. particleRotationMatrix[1] = rotMatrixValues[1];
  745. particleRotationMatrix[2] = rotMatrixValues[2];
  746. particleRotationMatrix[3] = rotMatrixValues[4];
  747. particleRotationMatrix[4] = rotMatrixValues[5];
  748. particleRotationMatrix[5] = rotMatrixValues[6];
  749. particleRotationMatrix[6] = rotMatrixValues[8];
  750. particleRotationMatrix[7] = rotMatrixValues[9];
  751. particleRotationMatrix[8] = rotMatrixValues[10];
  752. }
  753. }
  754. const pivotBackTranslation = tempVectors[11];
  755. if (particle.translateFromPivot) {
  756. pivotBackTranslation.setAll(0.0);
  757. }
  758. else {
  759. pivotBackTranslation.copyFrom(particle.pivot);
  760. }
  761. // positions
  762. const tmpVertex = tempVectors[0];
  763. tmpVertex.copyFrom(particle.position);
  764. const vertexX = tmpVertex.x - particle.pivot.x;
  765. const vertexY = tmpVertex.y - particle.pivot.y;
  766. const vertexZ = tmpVertex.z - particle.pivot.z;
  767. let rotatedX = vertexX * particleRotationMatrix[0] + vertexY * particleRotationMatrix[3] + vertexZ * particleRotationMatrix[6];
  768. let rotatedY = vertexX * particleRotationMatrix[1] + vertexY * particleRotationMatrix[4] + vertexZ * particleRotationMatrix[7];
  769. let rotatedZ = vertexX * particleRotationMatrix[2] + vertexY * particleRotationMatrix[5] + vertexZ * particleRotationMatrix[8];
  770. rotatedX += pivotBackTranslation.x;
  771. rotatedY += pivotBackTranslation.y;
  772. rotatedZ += pivotBackTranslation.z;
  773. const px = positions32[pindex] = particleGlobalPosition.x + camAxisX.x * rotatedX + camAxisY.x * rotatedY + camAxisZ.x * rotatedZ;
  774. const py = positions32[pindex + 1] = particleGlobalPosition.y + camAxisX.y * rotatedX + camAxisY.y * rotatedY + camAxisZ.y * rotatedZ;
  775. const pz = positions32[pindex + 2] = particleGlobalPosition.z + camAxisX.z * rotatedX + camAxisY.z * rotatedY + camAxisZ.z * rotatedZ;
  776. if (this._computeBoundingBox) {
  777. minimum.minimizeInPlaceFromFloats(px, py, pz);
  778. maximum.maximizeInPlaceFromFloats(px, py, pz);
  779. }
  780. if (this._computeParticleColor && particle.color) {
  781. const color = particle.color;
  782. const colors32 = this._colors32;
  783. colors32[cindex] = color.r;
  784. colors32[cindex + 1] = color.g;
  785. colors32[cindex + 2] = color.b;
  786. colors32[cindex + 3] = color.a;
  787. }
  788. if (this._computeParticleTexture && particle.uv) {
  789. const uv = particle.uv;
  790. const uvs32 = this._uvs32;
  791. uvs32[uindex] = uv.x;
  792. uvs32[uindex + 1] = uv.y;
  793. }
  794. }
  795. // if the VBO must be updated
  796. if (update) {
  797. if (this._computeParticleColor) {
  798. mesh.updateVerticesData(VertexBuffer.ColorKind, colors32, false, false);
  799. }
  800. if (this._computeParticleTexture) {
  801. mesh.updateVerticesData(VertexBuffer.UVKind, uvs32, false, false);
  802. }
  803. mesh.updateVerticesData(VertexBuffer.PositionKind, positions32, false, false);
  804. }
  805. if (this._computeBoundingBox) {
  806. if (mesh._boundingInfo) {
  807. mesh._boundingInfo.reConstruct(minimum, maximum, mesh._worldMatrix);
  808. }
  809. else {
  810. mesh._boundingInfo = new BoundingInfo(minimum, maximum, mesh._worldMatrix);
  811. }
  812. }
  813. this.afterUpdateParticles(start, end, update);
  814. return this;
  815. }
  816. /**
  817. * Disposes the PCS.
  818. */
  819. public dispose(): void {
  820. this.mesh.dispose();
  821. this.vars = null;
  822. // drop references to internal big arrays for the GC
  823. (<any>this._positions) = null;
  824. (<any>this._indices) = null;
  825. (<any>this._normals) = null;
  826. (<any>this._uvs) = null;
  827. (<any>this._colors) = null;
  828. (<any>this._indices32) = null;
  829. (<any>this._positions32) = null;
  830. (<any>this._uvs32) = null;
  831. (<any>this._colors32) = null;
  832. }
  833. /**
  834. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  835. * doc :
  836. * @returns the PCS.
  837. */
  838. public refreshVisibleSize(): PointsCloudSystem {
  839. if (!this._isVisibilityBoxLocked) {
  840. this.mesh.refreshBoundingInfo();
  841. }
  842. return this;
  843. }
  844. /**
  845. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  846. * @param size the size (float) of the visibility box
  847. * note : this doesn't lock the PCS mesh bounding box.
  848. * doc :
  849. */
  850. public setVisibilityBox(size: number): void {
  851. var vis = size / 2;
  852. this.mesh._boundingInfo = new BoundingInfo(new Vector3(-vis, -vis, -vis), new Vector3(vis, vis, vis));
  853. }
  854. /**
  855. * Gets whether the PCS is always visible or not
  856. * doc :
  857. */
  858. public get isAlwaysVisible(): boolean {
  859. return this._alwaysVisible;
  860. }
  861. /**
  862. * Sets the PCS as always visible or not
  863. * doc :
  864. */
  865. public set isAlwaysVisible(val: boolean) {
  866. this._alwaysVisible = val;
  867. this.mesh.alwaysSelectAsActiveMesh = val;
  868. }
  869. /**
  870. * Tells to `setParticles()` to compute the particle rotations or not
  871. * Default value : false. The PCS is faster when it's set to false
  872. * Note : particle rotations are only applied to parent particles
  873. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate
  874. */
  875. public set computeParticleRotation(val: boolean) {
  876. this._computeParticleRotation = val;
  877. }
  878. /**
  879. * Tells to `setParticles()` to compute the particle colors or not.
  880. * Default value : true. The PCS is faster when it's set to false.
  881. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  882. */
  883. public set computeParticleColor(val: boolean) {
  884. this._computeParticleColor = val;
  885. }
  886. public set computeParticleTexture(val: boolean) {
  887. this._computeParticleTexture = val;
  888. }
  889. /**
  890. * Gets if `setParticles()` computes the particle colors or not.
  891. * Default value : false. The PCS is faster when it's set to false.
  892. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  893. */
  894. public get computeParticleColor(): boolean {
  895. return this._computeParticleColor;
  896. }
  897. /**
  898. * Gets if `setParticles()` computes the particle textures or not.
  899. * Default value : false. The PCS is faster when it's set to false.
  900. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  901. */
  902. public get computeParticleTexture(): boolean {
  903. return this._computeParticleTexture;
  904. }
  905. /**
  906. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  907. */
  908. public set computeBoundingBox(val: boolean) {
  909. this._computeBoundingBox = val;
  910. }
  911. /**
  912. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  913. */
  914. public get computeBoundingBox(): boolean {
  915. return this._computeBoundingBox;
  916. }
  917. // =======================================================================
  918. // Particle behavior logic
  919. // these following methods may be overwritten by users to fit their needs
  920. /**
  921. * This function does nothing. It may be overwritten to set all the particle first values.
  922. * The PCS doesn't call this function, you may have to call it by your own.
  923. * doc :
  924. */
  925. public initParticles(): void {
  926. }
  927. /**
  928. * This function does nothing. It may be overwritten to recycle a particle
  929. * The PCS doesn't call this function, you can to call it
  930. * doc :
  931. * @param particle The particle to recycle
  932. * @returns the recycled particle
  933. */
  934. public recycleParticle(particle: CloudPoint): CloudPoint {
  935. return particle;
  936. }
  937. /**
  938. * Updates a particle : this function should be overwritten by the user.
  939. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  940. * doc :
  941. * @example : just set a particle position or velocity and recycle conditions
  942. * @param particle The particle to update
  943. * @returns the updated particle
  944. */
  945. public updateParticle(particle: CloudPoint): CloudPoint {
  946. return particle;
  947. }
  948. /**
  949. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  950. * This does nothing and may be overwritten by the user.
  951. * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle()
  952. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  953. * @param update the boolean update value actually passed to setParticles()
  954. */
  955. public beforeUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  956. }
  957. /**
  958. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  959. * This will be passed three parameters.
  960. * This does nothing and may be overwritten by the user.
  961. * @param start the particle index in the particle array where to start to iterate, same than the value passed to setParticle()
  962. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  963. * @param update the boolean update value actually passed to setParticles()
  964. */
  965. public afterUpdateParticles(start?: number, stop?: number, update?: boolean): void {
  966. }
  967. }