subMesh.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. import { Nullable, IndicesArray, DeepImmutable, FloatArray } from "../types";
  2. import { Matrix, Vector3 } from "../Maths/math.vector";
  3. import { Engine } from "../Engines/engine";
  4. import { VertexBuffer } from "./buffer";
  5. import { IntersectionInfo } from "../Collisions/intersectionInfo";
  6. import { ICullable, BoundingInfo } from "../Culling/boundingInfo";
  7. import { Effect } from "../Materials/effect";
  8. import { Constants } from "../Engines/constants";
  9. import { DataBuffer } from './dataBuffer';
  10. import { extractMinAndMaxIndexed } from '../Maths/math.functions';
  11. import { Plane } from '../Maths/math.plane';
  12. declare type Collider = import("../Collisions/collider").Collider;
  13. declare type Material = import("../Materials/material").Material;
  14. declare type MaterialDefines = import("../Materials/materialDefines").MaterialDefines;
  15. declare type MultiMaterial = import("../Materials/multiMaterial").MultiMaterial;
  16. declare type AbstractMesh = import("./abstractMesh").AbstractMesh;
  17. declare type Mesh = import("./mesh").Mesh;
  18. declare type Ray = import("../Culling/ray").Ray;
  19. declare type TrianglePickingPredicate = import("../Culling/ray").TrianglePickingPredicate;
  20. /**
  21. * Base class for submeshes
  22. */
  23. export class BaseSubMesh {
  24. /** @hidden */
  25. public _materialDefines: Nullable<MaterialDefines> = null;
  26. /** @hidden */
  27. public _materialEffect: Nullable<Effect> = null;
  28. /** @hidden */
  29. public _effectOverride: Nullable<Effect> = null;
  30. /**
  31. * Gets material defines used by the effect associated to the sub mesh
  32. */
  33. public get materialDefines(): Nullable<MaterialDefines> {
  34. return this._materialDefines;
  35. }
  36. /**
  37. * Sets material defines used by the effect associated to the sub mesh
  38. */
  39. public set materialDefines(defines: Nullable<MaterialDefines>) {
  40. this._materialDefines = defines;
  41. }
  42. /**
  43. * Gets associated effect
  44. */
  45. public get effect(): Nullable<Effect> {
  46. return this._effectOverride ?? this._materialEffect;
  47. }
  48. /**
  49. * Sets associated effect (effect used to render this submesh)
  50. * @param effect defines the effect to associate with
  51. * @param defines defines the set of defines used to compile this effect
  52. */
  53. public setEffect(effect: Nullable<Effect>, defines: Nullable<MaterialDefines> = null) {
  54. if (this._materialEffect === effect) {
  55. if (!effect) {
  56. this._materialDefines = null;
  57. }
  58. return;
  59. }
  60. this._materialDefines = defines;
  61. this._materialEffect = effect;
  62. }
  63. }
  64. /**
  65. * Defines a subdivision inside a mesh
  66. */
  67. export class SubMesh extends BaseSubMesh implements ICullable {
  68. /** @hidden */
  69. public _linesIndexCount: number = 0;
  70. private _mesh: AbstractMesh;
  71. private _renderingMesh: Mesh;
  72. private _boundingInfo: BoundingInfo;
  73. private _linesIndexBuffer: Nullable<DataBuffer> = null;
  74. /** @hidden */
  75. public _lastColliderWorldVertices: Nullable<Vector3[]> = null;
  76. /** @hidden */
  77. public _trianglePlanes: Plane[];
  78. /** @hidden */
  79. public _lastColliderTransformMatrix: Nullable<Matrix> = null;
  80. /** @hidden */
  81. public _renderId = 0;
  82. /** @hidden */
  83. public _alphaIndex: number = 0;
  84. /** @hidden */
  85. public _distanceToCamera: number = 0;
  86. /** @hidden */
  87. public _id: number;
  88. private _currentMaterial: Nullable<Material> = null;
  89. /**
  90. * Add a new submesh to a mesh
  91. * @param materialIndex defines the material index to use
  92. * @param verticesStart defines vertex index start
  93. * @param verticesCount defines vertices count
  94. * @param indexStart defines index start
  95. * @param indexCount defines indices count
  96. * @param mesh defines the parent mesh
  97. * @param renderingMesh defines an optional rendering mesh
  98. * @param createBoundingBox defines if bounding box should be created for this submesh
  99. * @returns the new submesh
  100. */
  101. public static AddToMesh(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox: boolean = true): SubMesh {
  102. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  103. }
  104. /**
  105. * Creates a new submesh
  106. * @param materialIndex defines the material index to use
  107. * @param verticesStart defines vertex index start
  108. * @param verticesCount defines vertices count
  109. * @param indexStart defines index start
  110. * @param indexCount defines indices count
  111. * @param mesh defines the parent mesh
  112. * @param renderingMesh defines an optional rendering mesh
  113. * @param createBoundingBox defines if bounding box should be created for this submesh
  114. */
  115. constructor(
  116. /** the material index to use */
  117. public materialIndex: number,
  118. /** vertex index start */
  119. public verticesStart: number,
  120. /** vertices count */
  121. public verticesCount: number,
  122. /** index start */
  123. public indexStart: number,
  124. /** indices count */
  125. public indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox: boolean = true) {
  126. super();
  127. this._mesh = mesh;
  128. this._renderingMesh = renderingMesh || <Mesh>mesh;
  129. mesh.subMeshes.push(this);
  130. this._trianglePlanes = [];
  131. this._id = mesh.subMeshes.length - 1;
  132. if (createBoundingBox) {
  133. this.refreshBoundingInfo();
  134. mesh.computeWorldMatrix(true);
  135. }
  136. }
  137. /**
  138. * Returns true if this submesh covers the entire parent mesh
  139. * @ignorenaming
  140. */
  141. public get IsGlobal(): boolean {
  142. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  143. }
  144. /**
  145. * Returns the submesh BoudingInfo object
  146. * @returns current bounding info (or mesh's one if the submesh is global)
  147. */
  148. public getBoundingInfo(): BoundingInfo {
  149. if (this.IsGlobal) {
  150. return this._mesh.getBoundingInfo();
  151. }
  152. return this._boundingInfo;
  153. }
  154. /**
  155. * Sets the submesh BoundingInfo
  156. * @param boundingInfo defines the new bounding info to use
  157. * @returns the SubMesh
  158. */
  159. public setBoundingInfo(boundingInfo: BoundingInfo): SubMesh {
  160. this._boundingInfo = boundingInfo;
  161. return this;
  162. }
  163. /**
  164. * Returns the mesh of the current submesh
  165. * @return the parent mesh
  166. */
  167. public getMesh(): AbstractMesh {
  168. return this._mesh;
  169. }
  170. /**
  171. * Returns the rendering mesh of the submesh
  172. * @returns the rendering mesh (could be different from parent mesh)
  173. */
  174. public getRenderingMesh(): Mesh {
  175. return this._renderingMesh;
  176. }
  177. /**
  178. * Returns the submesh material
  179. * @returns null or the current material
  180. */
  181. public getMaterial(): Nullable<Material> {
  182. var rootMaterial = this._renderingMesh.material;
  183. if (rootMaterial === null || rootMaterial === undefined) {
  184. return this._mesh.getScene().defaultMaterial;
  185. } else if ((<MultiMaterial>rootMaterial).getSubMaterial) {
  186. var multiMaterial = <MultiMaterial>rootMaterial;
  187. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  188. if (this._currentMaterial !== effectiveMaterial) {
  189. this._currentMaterial = effectiveMaterial;
  190. this._materialDefines = null;
  191. }
  192. return effectiveMaterial;
  193. }
  194. return rootMaterial;
  195. }
  196. // Methods
  197. /**
  198. * Sets a new updated BoundingInfo object to the submesh
  199. * @param data defines an optional position array to use to determine the bounding info
  200. * @returns the SubMesh
  201. */
  202. public refreshBoundingInfo(data: Nullable<FloatArray> = null): SubMesh {
  203. this._lastColliderWorldVertices = null;
  204. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  205. return this;
  206. }
  207. if (!data) {
  208. data = this._renderingMesh.getVerticesData(VertexBuffer.PositionKind);
  209. }
  210. if (!data) {
  211. this._boundingInfo = this._mesh.getBoundingInfo();
  212. return this;
  213. }
  214. var indices = <IndicesArray>this._renderingMesh.getIndices();
  215. var extend: { minimum: Vector3, maximum: Vector3 };
  216. //is this the only submesh?
  217. if (this.indexStart === 0 && this.indexCount === indices.length) {
  218. let boundingInfo = this._renderingMesh.getBoundingInfo();
  219. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  220. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  221. } else {
  222. extend = extractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  223. }
  224. if (this._boundingInfo) {
  225. this._boundingInfo.reConstruct(extend.minimum, extend.maximum);
  226. }
  227. else {
  228. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  229. }
  230. return this;
  231. }
  232. /** @hidden */
  233. public _checkCollision(collider: Collider): boolean {
  234. let boundingInfo = this.getBoundingInfo();
  235. return boundingInfo._checkCollision(collider);
  236. }
  237. /**
  238. * Updates the submesh BoundingInfo
  239. * @param world defines the world matrix to use to update the bounding info
  240. * @returns the submesh
  241. */
  242. public updateBoundingInfo(world: DeepImmutable<Matrix>): SubMesh {
  243. let boundingInfo = this.getBoundingInfo();
  244. if (!boundingInfo) {
  245. this.refreshBoundingInfo();
  246. boundingInfo = this.getBoundingInfo();
  247. }
  248. if (boundingInfo) {
  249. (<BoundingInfo>boundingInfo).update(world);
  250. }
  251. return this;
  252. }
  253. /**
  254. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  255. * @param frustumPlanes defines the frustum planes
  256. * @returns true if the submesh is intersecting with the frustum
  257. */
  258. public isInFrustum(frustumPlanes: Plane[]): boolean {
  259. let boundingInfo = this.getBoundingInfo();
  260. if (!boundingInfo) {
  261. return false;
  262. }
  263. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  264. }
  265. /**
  266. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  267. * @param frustumPlanes defines the frustum planes
  268. * @returns true if the submesh is inside the frustum
  269. */
  270. public isCompletelyInFrustum(frustumPlanes: Plane[]): boolean {
  271. let boundingInfo = this.getBoundingInfo();
  272. if (!boundingInfo) {
  273. return false;
  274. }
  275. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  276. }
  277. /**
  278. * Renders the submesh
  279. * @param enableAlphaMode defines if alpha needs to be used
  280. * @returns the submesh
  281. */
  282. public render(enableAlphaMode: boolean): SubMesh {
  283. this._renderingMesh.render(this, enableAlphaMode, this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh ? this._mesh : undefined);
  284. return this;
  285. }
  286. /**
  287. * @hidden
  288. */
  289. public _getLinesIndexBuffer(indices: IndicesArray, engine: Engine): DataBuffer {
  290. if (!this._linesIndexBuffer) {
  291. var linesIndices = [];
  292. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  293. linesIndices.push(indices[index], indices[index + 1],
  294. indices[index + 1], indices[index + 2],
  295. indices[index + 2], indices[index]);
  296. }
  297. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  298. this._linesIndexCount = linesIndices.length;
  299. }
  300. return this._linesIndexBuffer;
  301. }
  302. /**
  303. * Checks if the submesh intersects with a ray
  304. * @param ray defines the ray to test
  305. * @returns true is the passed ray intersects the submesh bounding box
  306. */
  307. public canIntersects(ray: Ray): boolean {
  308. let boundingInfo = this.getBoundingInfo();
  309. if (!boundingInfo) {
  310. return false;
  311. }
  312. return ray.intersectsBox(boundingInfo.boundingBox);
  313. }
  314. /**
  315. * Intersects current submesh with a ray
  316. * @param ray defines the ray to test
  317. * @param positions defines mesh's positions array
  318. * @param indices defines mesh's indices array
  319. * @param fastCheck defines if the first intersection will be used (and not the closest)
  320. * @param trianglePredicate defines an optional predicate used to select faces when a mesh intersection is detected
  321. * @returns intersection info or null if no intersection
  322. */
  323. public intersects(ray: Ray, positions: Vector3[], indices: IndicesArray,
  324. fastCheck?: boolean, trianglePredicate?: TrianglePickingPredicate): Nullable<IntersectionInfo> {
  325. const material = this.getMaterial();
  326. if (!material) {
  327. return null;
  328. }
  329. let step = 3;
  330. let checkStopper = false;
  331. switch (material.fillMode) {
  332. case Constants.MATERIAL_PointListDrawMode:
  333. case Constants.MATERIAL_LineListDrawMode:
  334. case Constants.MATERIAL_LineLoopDrawMode:
  335. case Constants.MATERIAL_LineStripDrawMode:
  336. case Constants.MATERIAL_TriangleFanDrawMode:
  337. return null;
  338. case Constants.MATERIAL_TriangleStripDrawMode:
  339. step = 1;
  340. checkStopper = true;
  341. break;
  342. default:
  343. break;
  344. }
  345. // LineMesh first as it's also a Mesh...
  346. if (this._mesh.getClassName() === "InstancedLinesMesh" || this._mesh.getClassName() === "LinesMesh") {
  347. // Check if mesh is unindexed
  348. if (!indices.length) {
  349. return this._intersectUnIndexedLines(ray, positions, indices, (this._mesh as any).intersectionThreshold, fastCheck);
  350. }
  351. return this._intersectLines(ray, positions, indices, (this._mesh as any).intersectionThreshold, fastCheck);
  352. }
  353. else {
  354. // Check if mesh is unindexed
  355. if (!indices.length && this._mesh._unIndexed) {
  356. return this._intersectUnIndexedTriangles(ray, positions, indices, fastCheck, trianglePredicate);
  357. }
  358. return this._intersectTriangles(ray, positions, indices, step, checkStopper, fastCheck, trianglePredicate);
  359. }
  360. }
  361. /** @hidden */
  362. private _intersectLines(ray: Ray, positions: Vector3[], indices: IndicesArray, intersectionThreshold: number, fastCheck?: boolean): Nullable<IntersectionInfo> {
  363. var intersectInfo: Nullable<IntersectionInfo> = null;
  364. // Line test
  365. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  366. var p0 = positions[indices[index]];
  367. var p1 = positions[indices[index + 1]];
  368. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  369. if (length < 0) {
  370. continue;
  371. }
  372. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  373. intersectInfo = new IntersectionInfo(null, null, length);
  374. intersectInfo.faceId = index / 2;
  375. if (fastCheck) {
  376. break;
  377. }
  378. }
  379. }
  380. return intersectInfo;
  381. }
  382. /** @hidden */
  383. private _intersectUnIndexedLines(ray: Ray, positions: Vector3[], indices: IndicesArray, intersectionThreshold: number, fastCheck?: boolean): Nullable<IntersectionInfo> {
  384. var intersectInfo: Nullable<IntersectionInfo> = null;
  385. // Line test
  386. for (var index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 2) {
  387. var p0 = positions[index];
  388. var p1 = positions[index + 1];
  389. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  390. if (length < 0) {
  391. continue;
  392. }
  393. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  394. intersectInfo = new IntersectionInfo(null, null, length);
  395. intersectInfo.faceId = index / 2;
  396. if (fastCheck) {
  397. break;
  398. }
  399. }
  400. }
  401. return intersectInfo;
  402. }
  403. /** @hidden */
  404. private _intersectTriangles(ray: Ray, positions: Vector3[], indices: IndicesArray,
  405. step: number, checkStopper: boolean,
  406. fastCheck?: boolean, trianglePredicate?: TrianglePickingPredicate): Nullable<IntersectionInfo> {
  407. var intersectInfo: Nullable<IntersectionInfo> = null;
  408. // Triangles test
  409. let faceID = -1;
  410. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += step) {
  411. faceID++;
  412. const indexA = indices[index];
  413. const indexB = indices[index + 1];
  414. const indexC = indices[index + 2];
  415. if (checkStopper && indexC === 0xFFFFFFFF) {
  416. index += 2;
  417. continue;
  418. }
  419. var p0 = positions[indexA];
  420. var p1 = positions[indexB];
  421. var p2 = positions[indexC];
  422. if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray)) {
  423. continue;
  424. }
  425. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  426. if (currentIntersectInfo) {
  427. if (currentIntersectInfo.distance < 0) {
  428. continue;
  429. }
  430. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  431. intersectInfo = currentIntersectInfo;
  432. intersectInfo.faceId = faceID;
  433. if (fastCheck) {
  434. break;
  435. }
  436. }
  437. }
  438. }
  439. return intersectInfo;
  440. }
  441. /** @hidden */
  442. private _intersectUnIndexedTriangles(ray: Ray, positions: Vector3[], indices: IndicesArray,
  443. fastCheck?: boolean, trianglePredicate?: TrianglePickingPredicate): Nullable<IntersectionInfo> {
  444. var intersectInfo: Nullable<IntersectionInfo> = null;
  445. // Triangles test
  446. for (var index = this.verticesStart; index < this.verticesStart + this.verticesCount; index += 3) {
  447. var p0 = positions[index];
  448. var p1 = positions[index + 1];
  449. var p2 = positions[index + 2];
  450. if (trianglePredicate && !trianglePredicate(p0, p1, p2, ray)) {
  451. continue;
  452. }
  453. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  454. if (currentIntersectInfo) {
  455. if (currentIntersectInfo.distance < 0) {
  456. continue;
  457. }
  458. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  459. intersectInfo = currentIntersectInfo;
  460. intersectInfo.faceId = index / 3;
  461. if (fastCheck) {
  462. break;
  463. }
  464. }
  465. }
  466. }
  467. return intersectInfo;
  468. }
  469. /** @hidden */
  470. public _rebuild(): void {
  471. if (this._linesIndexBuffer) {
  472. this._linesIndexBuffer = null;
  473. }
  474. }
  475. // Clone
  476. /**
  477. * Creates a new submesh from the passed mesh
  478. * @param newMesh defines the new hosting mesh
  479. * @param newRenderingMesh defines an optional rendering mesh
  480. * @returns the new submesh
  481. */
  482. public clone(newMesh: AbstractMesh, newRenderingMesh?: Mesh): SubMesh {
  483. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  484. if (!this.IsGlobal) {
  485. let boundingInfo = this.getBoundingInfo();
  486. if (!boundingInfo) {
  487. return result;
  488. }
  489. result._boundingInfo = new BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  490. }
  491. return result;
  492. }
  493. // Dispose
  494. /**
  495. * Release associated resources
  496. */
  497. public dispose(): void {
  498. if (this._linesIndexBuffer) {
  499. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  500. this._linesIndexBuffer = null;
  501. }
  502. // Remove from mesh
  503. var index = this._mesh.subMeshes.indexOf(this);
  504. this._mesh.subMeshes.splice(index, 1);
  505. }
  506. /**
  507. * Gets the class name
  508. * @returns the string "SubMesh".
  509. */
  510. public getClassName(): string {
  511. return "SubMesh";
  512. }
  513. // Statics
  514. /**
  515. * Creates a new submesh from indices data
  516. * @param materialIndex the index of the main mesh material
  517. * @param startIndex the index where to start the copy in the mesh indices array
  518. * @param indexCount the number of indices to copy then from the startIndex
  519. * @param mesh the main mesh to create the submesh from
  520. * @param renderingMesh the optional rendering mesh
  521. * @returns a new submesh
  522. */
  523. public static CreateFromIndices(materialIndex: number, startIndex: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh): SubMesh {
  524. var minVertexIndex = Number.MAX_VALUE;
  525. var maxVertexIndex = -Number.MAX_VALUE;
  526. const whatWillRender = (renderingMesh || mesh);
  527. var indices = whatWillRender!.getIndices()!;
  528. for (var index = startIndex; index < startIndex + indexCount; index++) {
  529. var vertexIndex = indices[index];
  530. if (vertexIndex < minVertexIndex) {
  531. minVertexIndex = vertexIndex;
  532. }
  533. if (vertexIndex > maxVertexIndex) {
  534. maxVertexIndex = vertexIndex;
  535. }
  536. }
  537. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  538. }
  539. }