pointsCloudSystem.ts 46 KB

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