instancedMesh.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. import { Nullable, FloatArray, IndicesArray } from "../types";
  2. import { Vector3, Matrix, Tmp } from "../Maths/math";
  3. import { Logger } from "../Misc/logger";
  4. import { Camera } from "../Cameras/camera";
  5. import { Node } from "../node";
  6. import { AbstractMesh } from "../Meshes/abstractMesh";
  7. import { Mesh } from "../Meshes/mesh";
  8. import { Material } from "../Materials/material";
  9. import { Skeleton } from "../Bones/skeleton";
  10. import { DeepCopier } from "../Misc/deepCopier";
  11. import { TransformNode } from './transformNode';
  12. import { Light } from '../Lights/light';
  13. Mesh._instancedMeshFactory = (name: string, mesh: Mesh): InstancedMesh => {
  14. return new InstancedMesh(name, mesh);
  15. };
  16. /**
  17. * Creates an instance based on a source mesh.
  18. */
  19. export class InstancedMesh extends AbstractMesh {
  20. private _sourceMesh: Mesh;
  21. private _currentLOD: Mesh;
  22. /** @hidden */
  23. public _indexInSourceMeshInstanceArray = -1;
  24. constructor(name: string, source: Mesh) {
  25. super(name, source.getScene());
  26. source.addInstance(this);
  27. this._sourceMesh = source;
  28. this._unIndexed = source._unIndexed;
  29. this.position.copyFrom(source.position);
  30. this.rotation.copyFrom(source.rotation);
  31. this.scaling.copyFrom(source.scaling);
  32. if (source.rotationQuaternion) {
  33. this.rotationQuaternion = source.rotationQuaternion.clone();
  34. }
  35. this.infiniteDistance = source.infiniteDistance;
  36. this.setPivotMatrix(source.getPivotMatrix());
  37. this.refreshBoundingInfo();
  38. if (!this._sourceMesh.subMeshes) {
  39. Logger.Warn("Instances should only be created for meshes with Geometry.");
  40. }
  41. this._syncSubMeshes();
  42. }
  43. /**
  44. * Returns the string "InstancedMesh".
  45. */
  46. public getClassName(): string {
  47. return "InstancedMesh";
  48. }
  49. /** Gets the list of lights affecting that mesh */
  50. public get lightSources(): Light[] {
  51. return this._sourceMesh._lightSources;
  52. }
  53. public _resyncLightSources(): void {
  54. // Do nothing as all the work will be done by source mesh
  55. }
  56. public _resyncLighSource(light: Light): void {
  57. // Do nothing as all the work will be done by source mesh
  58. }
  59. public _removeLightSource(light: Light): void {
  60. // Do nothing as all the work will be done by source mesh
  61. }
  62. // Methods
  63. /**
  64. * If the source mesh receives shadows
  65. */
  66. public get receiveShadows(): boolean {
  67. return this._sourceMesh.receiveShadows;
  68. }
  69. /**
  70. * The material of the source mesh
  71. */
  72. public get material(): Nullable<Material> {
  73. return this._sourceMesh.material;
  74. }
  75. /**
  76. * Visibility of the source mesh
  77. */
  78. public get visibility(): number {
  79. return this._sourceMesh.visibility;
  80. }
  81. /**
  82. * Skeleton of the source mesh
  83. */
  84. public get skeleton(): Nullable<Skeleton> {
  85. return this._sourceMesh.skeleton;
  86. }
  87. /**
  88. * Rendering ground id of the source mesh
  89. */
  90. public get renderingGroupId(): number {
  91. return this._sourceMesh.renderingGroupId;
  92. }
  93. public set renderingGroupId(value: number) {
  94. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  95. return;
  96. }
  97. //no-op with warning
  98. Logger.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  99. }
  100. /**
  101. * Returns the total number of vertices (integer).
  102. */
  103. public getTotalVertices(): number {
  104. return this._sourceMesh ? this._sourceMesh.getTotalVertices() : 0;
  105. }
  106. /**
  107. * Returns a positive integer : the total number of indices in this mesh geometry.
  108. * @returns the numner of indices or zero if the mesh has no geometry.
  109. */
  110. public getTotalIndices(): number {
  111. return this._sourceMesh.getTotalIndices();
  112. }
  113. /**
  114. * The source mesh of the instance
  115. */
  116. public get sourceMesh(): Mesh {
  117. return this._sourceMesh;
  118. }
  119. /**
  120. * Is this node ready to be used/rendered
  121. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  122. * @return {boolean} is it ready
  123. */
  124. public isReady(completeCheck = false): boolean {
  125. return this._sourceMesh.isReady(completeCheck, true);
  126. }
  127. /**
  128. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  129. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  130. * @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  131. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  132. */
  133. public getVerticesData(kind: string, copyWhenShared?: boolean): Nullable<FloatArray> {
  134. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  135. }
  136. /**
  137. * Sets the vertex data of the mesh geometry for the requested `kind`.
  138. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  139. * The `data` are either a numeric array either a Float32Array.
  140. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  141. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  142. * Note that a new underlying VertexBuffer object is created each call.
  143. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  144. *
  145. * Possible `kind` values :
  146. * - VertexBuffer.PositionKind
  147. * - VertexBuffer.UVKind
  148. * - VertexBuffer.UV2Kind
  149. * - VertexBuffer.UV3Kind
  150. * - VertexBuffer.UV4Kind
  151. * - VertexBuffer.UV5Kind
  152. * - VertexBuffer.UV6Kind
  153. * - VertexBuffer.ColorKind
  154. * - VertexBuffer.MatricesIndicesKind
  155. * - VertexBuffer.MatricesIndicesExtraKind
  156. * - VertexBuffer.MatricesWeightsKind
  157. * - VertexBuffer.MatricesWeightsExtraKind
  158. *
  159. * Returns the Mesh.
  160. */
  161. public setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): Mesh {
  162. if (this.sourceMesh) {
  163. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  164. }
  165. return this.sourceMesh;
  166. }
  167. /**
  168. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  169. * If the mesh has no geometry, it is simply returned as it is.
  170. * The `data` are either a numeric array either a Float32Array.
  171. * No new underlying VertexBuffer object is created.
  172. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  173. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  174. *
  175. * Possible `kind` values :
  176. * - VertexBuffer.PositionKind
  177. * - VertexBuffer.UVKind
  178. * - VertexBuffer.UV2Kind
  179. * - VertexBuffer.UV3Kind
  180. * - VertexBuffer.UV4Kind
  181. * - VertexBuffer.UV5Kind
  182. * - VertexBuffer.UV6Kind
  183. * - VertexBuffer.ColorKind
  184. * - VertexBuffer.MatricesIndicesKind
  185. * - VertexBuffer.MatricesIndicesExtraKind
  186. * - VertexBuffer.MatricesWeightsKind
  187. * - VertexBuffer.MatricesWeightsExtraKind
  188. *
  189. * Returns the Mesh.
  190. */
  191. public updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): Mesh {
  192. if (this.sourceMesh) {
  193. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  194. }
  195. return this.sourceMesh;
  196. }
  197. /**
  198. * Sets the mesh indices.
  199. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  200. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  201. * This method creates a new index buffer each call.
  202. * Returns the Mesh.
  203. */
  204. public setIndices(indices: IndicesArray, totalVertices: Nullable<number> = null): Mesh {
  205. if (this.sourceMesh) {
  206. this.sourceMesh.setIndices(indices, totalVertices);
  207. }
  208. return this.sourceMesh;
  209. }
  210. /**
  211. * Boolean : True if the mesh owns the requested kind of data.
  212. */
  213. public isVerticesDataPresent(kind: string): boolean {
  214. return this._sourceMesh.isVerticesDataPresent(kind);
  215. }
  216. /**
  217. * Returns an array of indices (IndicesArray).
  218. */
  219. public getIndices(): Nullable<IndicesArray> {
  220. return this._sourceMesh.getIndices();
  221. }
  222. public get _positions(): Nullable<Vector3[]> {
  223. return this._sourceMesh._positions;
  224. }
  225. /**
  226. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  227. * This means the mesh underlying bounding box and sphere are recomputed.
  228. * @param applySkeleton defines whether to apply the skeleton before computing the bounding info
  229. * @returns the current mesh
  230. */
  231. public refreshBoundingInfo(applySkeleton: boolean = false): InstancedMesh {
  232. if (this._boundingInfo && this._boundingInfo.isLocked) {
  233. return this;
  234. }
  235. const bias = this._sourceMesh.geometry ? this._sourceMesh.geometry.boundingBias : null;
  236. this._refreshBoundingInfo(this._sourceMesh._getPositionData(applySkeleton), bias);
  237. return this;
  238. }
  239. /** @hidden */
  240. public _preActivate(): InstancedMesh {
  241. if (this._currentLOD) {
  242. this._currentLOD._preActivate();
  243. }
  244. return this;
  245. }
  246. /** @hidden */
  247. public _activate(renderId: number, intermediateRendering: boolean): boolean {
  248. if (this._currentLOD) {
  249. this._currentLOD._registerInstanceForRenderId(this, renderId);
  250. if (intermediateRendering) {
  251. if (!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate) {
  252. this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate = true;
  253. return true;
  254. }
  255. } else {
  256. if (!this._currentLOD._internalAbstractMeshDataInfo._isActive) {
  257. this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances = true;
  258. return true;
  259. }
  260. }
  261. }
  262. return false;
  263. }
  264. /** @hidden */
  265. public _postActivate(): void {
  266. if (this._edgesRenderer && this._edgesRenderer.isEnabled && this._sourceMesh._renderingGroup) {
  267. this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer);
  268. }
  269. }
  270. public getWorldMatrix(): Matrix {
  271. if (this._currentLOD && this._currentLOD.billboardMode !== TransformNode.BILLBOARDMODE_NONE && this._currentLOD._masterMesh !== this) {
  272. let tempMaster = this._currentLOD._masterMesh;
  273. this._currentLOD._masterMesh = this;
  274. Tmp.Matrix[0].copyFrom(this._currentLOD.computeWorldMatrix(true));
  275. this._currentLOD._masterMesh = tempMaster;
  276. return Tmp.Matrix[0];
  277. }
  278. return super.getWorldMatrix();
  279. }
  280. public get isAnInstance(): boolean {
  281. return true;
  282. }
  283. /**
  284. * Returns the current associated LOD AbstractMesh.
  285. */
  286. public getLOD(camera: Camera): AbstractMesh {
  287. if (!camera) {
  288. return this;
  289. }
  290. let boundingInfo = this.getBoundingInfo();
  291. this._currentLOD = <Mesh>this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  292. if (this._currentLOD === this.sourceMesh) {
  293. return this.sourceMesh;
  294. }
  295. return this._currentLOD;
  296. }
  297. /** @hidden */
  298. public _syncSubMeshes(): InstancedMesh {
  299. this.releaseSubMeshes();
  300. if (this._sourceMesh.subMeshes) {
  301. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  302. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  303. }
  304. }
  305. return this;
  306. }
  307. /** @hidden */
  308. public _generatePointsArray(): boolean {
  309. return this._sourceMesh._generatePointsArray();
  310. }
  311. /**
  312. * Creates a new InstancedMesh from the current mesh.
  313. * - name (string) : the cloned mesh name
  314. * - newParent (optional Node) : the optional Node to parent the clone to.
  315. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  316. *
  317. * Returns the clone.
  318. */
  319. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): InstancedMesh {
  320. var result = this._sourceMesh.createInstance(name);
  321. // Deep copy
  322. DeepCopier.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  323. // Bounding info
  324. this.refreshBoundingInfo();
  325. // Parent
  326. if (newParent) {
  327. result.parent = newParent;
  328. }
  329. if (!doNotCloneChildren) {
  330. // Children
  331. for (var index = 0; index < this.getScene().meshes.length; index++) {
  332. var mesh = this.getScene().meshes[index];
  333. if (mesh.parent === this) {
  334. mesh.clone(mesh.name, result);
  335. }
  336. }
  337. }
  338. result.computeWorldMatrix(true);
  339. return result;
  340. }
  341. /**
  342. * Disposes the InstancedMesh.
  343. * Returns nothing.
  344. */
  345. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  346. // Remove from mesh
  347. this._sourceMesh.removeInstance(this);
  348. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  349. }
  350. }