instancedMesh.ts 14 KB

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