babylon.abstractMesh.ts 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  1. module BABYLON {
  2. export class AbstractMesh extends TransformNode implements IDisposable, ICullable, IGetSetVerticesData {
  3. public static OCCLUSION_TYPE_NONE = 0;
  4. public static OCCLUSION_TYPE_OPTIMISTIC = 1;
  5. public static OCCLUSION_TYPE_STRICT = 2;
  6. public static OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  7. public static OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  8. public static get BILLBOARDMODE_NONE(): number {
  9. return TransformNode.BILLBOARDMODE_NONE;
  10. }
  11. public static get BILLBOARDMODE_X(): number {
  12. return TransformNode.BILLBOARDMODE_X;
  13. }
  14. public static get BILLBOARDMODE_Y(): number {
  15. return TransformNode.BILLBOARDMODE_Y;
  16. }
  17. public static get BILLBOARDMODE_Z(): number {
  18. return TransformNode.BILLBOARDMODE_Z;
  19. }
  20. public static get BILLBOARDMODE_ALL(): number {
  21. return TransformNode.BILLBOARDMODE_ALL;
  22. }
  23. // facetData private properties
  24. private _facetPositions: Vector3[]; // facet local positions
  25. private _facetNormals: Vector3[]; // facet local normals
  26. private _facetPartitioning: number[][]; // partitioning array of facet index arrays
  27. private _facetNb: number = 0; // facet number
  28. private _partitioningSubdivisions: number = 10; // number of subdivisions per axis in the partioning space
  29. private _partitioningBBoxRatio: number = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  30. private _facetDataEnabled: boolean = false; // is the facet data feature enabled on this mesh ?
  31. private _facetParameters: any = {}; // keep a reference to the object parameters to avoid memory re-allocation
  32. private _bbSize: Vector3 = Vector3.Zero(); // bbox size approximated for facet data
  33. private _subDiv = { // actual number of subdivisions per axis for ComputeNormals()
  34. max: 1,
  35. X: 1,
  36. Y: 1,
  37. Z: 1
  38. };
  39. private _facetDepthSort: boolean = false; // is the facet depth sort to be computed
  40. private _facetDepthSortEnabled: boolean = false; // is the facet depth sort initialized
  41. private _depthSortedIndices: IndicesArray; // copy of the indices array to store them once sorted
  42. private _depthSortedFacets: { ind: number, sqDistance: number }[]; // array of depth sorted facets
  43. private _facetDepthSortFunction: (f1: { ind: number, sqDistance: number }, f2: { ind: number, sqDistance: number }) => number; // facet depth sort function
  44. private _facetDepthSortFrom: Vector3; // location where to depth sort from
  45. private _facetDepthSortOrigin: Vector3; // same as facetDepthSortFrom but expressed in the mesh local space
  46. private _invertedMatrix: Matrix; // Mesh inverted World Matrix
  47. /**
  48. * Read-only : the number of facets in the mesh
  49. */
  50. public get facetNb(): number {
  51. return this._facetNb;
  52. }
  53. /**
  54. * The number (integer) of subdivisions per axis in the partioning space
  55. */
  56. public get partitioningSubdivisions(): number {
  57. return this._partitioningSubdivisions;
  58. }
  59. public set partitioningSubdivisions(nb: number) {
  60. this._partitioningSubdivisions = nb;
  61. }
  62. /**
  63. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  64. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  65. */
  66. public get partitioningBBoxRatio(): number {
  67. return this._partitioningBBoxRatio;
  68. }
  69. public set partitioningBBoxRatio(ratio: number) {
  70. this._partitioningBBoxRatio = ratio;
  71. }
  72. /**
  73. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  74. * Works only for updatable meshes.
  75. * Doesn't work with multi-materials.
  76. */
  77. public get mustDepthSortFacets(): boolean {
  78. return this._facetDepthSort;
  79. }
  80. public set mustDepthSortFacets(sort: boolean) {
  81. this._facetDepthSort = sort;
  82. }
  83. /**
  84. * The location (Vector3) where the facet depth sort must be computed from.
  85. * By default, the active camera position.
  86. * Used only when facet depth sort is enabled.
  87. */
  88. public get facetDepthSortFrom(): Vector3 {
  89. return this._facetDepthSortFrom;
  90. }
  91. public set facetDepthSortFrom(location: Vector3) {
  92. this._facetDepthSortFrom = location;
  93. }
  94. /**
  95. * Read-only boolean : is the feature facetData enabled ?
  96. */
  97. public get isFacetDataEnabled(): boolean {
  98. return this._facetDataEnabled;
  99. }
  100. public _updateNonUniformScalingState(value: boolean): boolean {
  101. if (!super._updateNonUniformScalingState(value)) {
  102. return false;
  103. }
  104. this._markSubMeshesAsMiscDirty();
  105. return true;
  106. }
  107. // Events
  108. /**
  109. * An event triggered when this mesh collides with another one
  110. * @type {BABYLON.Observable}
  111. */
  112. public onCollideObservable = new Observable<AbstractMesh>();
  113. private _onCollideObserver: Nullable<Observer<AbstractMesh>>;
  114. public set onCollide(callback: () => void) {
  115. if (this._onCollideObserver) {
  116. this.onCollideObservable.remove(this._onCollideObserver);
  117. }
  118. this._onCollideObserver = this.onCollideObservable.add(callback);
  119. }
  120. /**
  121. * An event triggered when the collision's position changes
  122. * @type {BABYLON.Observable}
  123. */
  124. public onCollisionPositionChangeObservable = new Observable<Vector3>();
  125. private _onCollisionPositionChangeObserver: Nullable<Observer<Vector3>>;
  126. public set onCollisionPositionChange(callback: () => void) {
  127. if (this._onCollisionPositionChangeObserver) {
  128. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  129. }
  130. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  131. }
  132. /**
  133. * An event triggered when material is changed
  134. * @type {BABYLON.Observable}
  135. */
  136. public onMaterialChangedObservable = new Observable<AbstractMesh>();
  137. // Properties
  138. public definedFacingForward = true; // orientation for POV movement & rotation
  139. /**
  140. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  141. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  142. * or
  143. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  144. * for more info check WebGl documentations
  145. */
  146. public occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  147. /**
  148. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  149. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  150. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  151. * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  152. */
  153. public occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  154. /**
  155. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  156. * The default value is -1 which means don't break the query and wait till the result.
  157. */
  158. public occlusionRetryCount = -1;
  159. private _occlusionInternalRetryCounter = 0;
  160. protected _isOccluded = false;
  161. /**
  162. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  163. */
  164. public get isOccluded(): boolean {
  165. return this._isOccluded;
  166. }
  167. public set isOccluded(value: boolean) {
  168. this._isOccluded = value;
  169. }
  170. private _isOcclusionQueryInProgress = false;
  171. /**
  172. * Flag to check the progress status of the query
  173. */
  174. public get isOcclusionQueryInProgress(): boolean {
  175. return this._isOcclusionQueryInProgress;
  176. }
  177. private _occlusionQuery: Nullable<WebGLQuery>;
  178. private _visibility = 1.0;
  179. /**
  180. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  181. */
  182. public get visibility(): number {
  183. return this._visibility;
  184. }
  185. /**
  186. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  187. */
  188. public set visibility(value: number) {
  189. if (this._visibility === value) {
  190. return;
  191. }
  192. this._visibility = value;
  193. this._markSubMeshesAsMiscDirty();
  194. }
  195. public alphaIndex = Number.MAX_VALUE;
  196. public isVisible = true;
  197. public isPickable = true;
  198. public showBoundingBox = false;
  199. public showSubMeshesBoundingBox = false;
  200. public isBlocker = false;
  201. public enablePointerMoveEvents = false;
  202. public renderingGroupId = 0;
  203. private _material: Nullable<Material>
  204. public get material(): Nullable<Material> {
  205. return this._material;
  206. }
  207. public set material(value: Nullable<Material>) {
  208. if (this._material === value) {
  209. return;
  210. }
  211. this._material = value;
  212. if (this.onMaterialChangedObservable.hasObservers) {
  213. this.onMaterialChangedObservable.notifyObservers(this);
  214. }
  215. if (!this.subMeshes) {
  216. return;
  217. }
  218. for (var subMesh of this.subMeshes) {
  219. subMesh.setEffect(null);
  220. }
  221. }
  222. private _receiveShadows = false;
  223. public get receiveShadows(): boolean {
  224. return this._receiveShadows;
  225. }
  226. public set receiveShadows(value: boolean) {
  227. if (this._receiveShadows === value) {
  228. return;
  229. }
  230. this._receiveShadows = value;
  231. this._markSubMeshesAsLightDirty();
  232. }
  233. public renderOutline = false;
  234. public outlineColor = Color3.Red();
  235. public outlineWidth = 0.02;
  236. public renderOverlay = false;
  237. public overlayColor = Color3.Red();
  238. public overlayAlpha = 0.5;
  239. private _hasVertexAlpha = false;
  240. public get hasVertexAlpha(): boolean {
  241. return this._hasVertexAlpha;
  242. }
  243. public set hasVertexAlpha(value: boolean) {
  244. if (this._hasVertexAlpha === value) {
  245. return;
  246. }
  247. this._hasVertexAlpha = value;
  248. this._markSubMeshesAsAttributesDirty();
  249. this._markSubMeshesAsMiscDirty();
  250. }
  251. private _useVertexColors = true;
  252. public get useVertexColors(): boolean {
  253. return this._useVertexColors;
  254. }
  255. public set useVertexColors(value: boolean) {
  256. if (this._useVertexColors === value) {
  257. return;
  258. }
  259. this._useVertexColors = value;
  260. this._markSubMeshesAsAttributesDirty();
  261. }
  262. private _computeBonesUsingShaders = true;
  263. public get computeBonesUsingShaders(): boolean {
  264. return this._computeBonesUsingShaders;
  265. }
  266. public set computeBonesUsingShaders(value: boolean) {
  267. if (this._computeBonesUsingShaders === value) {
  268. return;
  269. }
  270. this._computeBonesUsingShaders = value;
  271. this._markSubMeshesAsAttributesDirty();
  272. }
  273. private _numBoneInfluencers = 4;
  274. public get numBoneInfluencers(): number {
  275. return this._numBoneInfluencers;
  276. }
  277. public set numBoneInfluencers(value: number) {
  278. if (this._numBoneInfluencers === value) {
  279. return;
  280. }
  281. this._numBoneInfluencers = value;
  282. this._markSubMeshesAsAttributesDirty();
  283. }
  284. private _applyFog = true;
  285. public get applyFog(): boolean {
  286. return this._applyFog;
  287. }
  288. public set applyFog(value: boolean) {
  289. if (this._applyFog === value) {
  290. return;
  291. }
  292. this._applyFog = value;
  293. this._markSubMeshesAsMiscDirty();
  294. }
  295. public useOctreeForRenderingSelection = true;
  296. public useOctreeForPicking = true;
  297. public useOctreeForCollisions = true;
  298. private _layerMask: number = 0x0FFFFFFF;
  299. public get layerMask(): number {
  300. return this._layerMask;
  301. }
  302. public set layerMask(value: number) {
  303. if (value === this._layerMask) {
  304. return;
  305. }
  306. this._layerMask = value;
  307. this._resyncLightSources();
  308. }
  309. /**
  310. * True if the mesh must be rendered in any case.
  311. */
  312. public alwaysSelectAsActiveMesh = false;
  313. /**
  314. * This scene's action manager
  315. * @type {BABYLON.ActionManager}
  316. */
  317. public actionManager: Nullable<ActionManager> = null;
  318. // Physics
  319. public physicsImpostor: Nullable<PhysicsImpostor> = null;
  320. // Collisions
  321. private _checkCollisions = false;
  322. private _collisionMask = -1;
  323. private _collisionGroup = -1;
  324. public ellipsoid = new Vector3(0.5, 1, 0.5);
  325. public ellipsoidOffset = new Vector3(0, 0, 0);
  326. private _collider: Collider;
  327. private _oldPositionForCollisions = new Vector3(0, 0, 0);
  328. private _diffPositionForCollisions = new Vector3(0, 0, 0);
  329. public get collisionMask(): number {
  330. return this._collisionMask;
  331. }
  332. public set collisionMask(mask: number) {
  333. this._collisionMask = !isNaN(mask) ? mask : -1;
  334. }
  335. public get collisionGroup(): number {
  336. return this._collisionGroup;
  337. }
  338. public set collisionGroup(mask: number) {
  339. this._collisionGroup = !isNaN(mask) ? mask : -1;
  340. }
  341. // Edges
  342. public edgesWidth = 1;
  343. public edgesColor = new Color4(1, 0, 0, 1);
  344. public _edgesRenderer: Nullable<EdgesRenderer>;
  345. // Cache
  346. private _collisionsTransformMatrix = Matrix.Zero();
  347. private _collisionsScalingMatrix = Matrix.Zero();
  348. public _masterMesh: Nullable<AbstractMesh>;
  349. public _boundingInfo: Nullable<BoundingInfo>;
  350. public _renderId = 0;
  351. public subMeshes: SubMesh[];
  352. public _submeshesOctree: Octree<SubMesh>;
  353. public _intersectionsInProgress = new Array<AbstractMesh>();
  354. public _unIndexed = false;
  355. public _lightSources = new Array<Light>();
  356. public get _positions(): Nullable<Vector3[]> {
  357. return null;
  358. }
  359. // Loading properties
  360. public _waitingActions: any;
  361. public _waitingFreezeWorldMatrix: Nullable<boolean>;
  362. // Skeleton
  363. private _skeleton: Nullable<Skeleton>;
  364. public _bonesTransformMatrices: Nullable<Float32Array>;
  365. public set skeleton(value: Nullable<Skeleton>) {
  366. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  367. this._skeleton._unregisterMeshWithPoseMatrix(this);
  368. }
  369. if (value && value.needInitialSkinMatrix) {
  370. value._registerMeshWithPoseMatrix(this);
  371. }
  372. this._skeleton = value;
  373. if (!this._skeleton) {
  374. this._bonesTransformMatrices = null;
  375. }
  376. this._markSubMeshesAsAttributesDirty();
  377. }
  378. public get skeleton(): Nullable<Skeleton> {
  379. return this._skeleton;
  380. }
  381. // Constructor
  382. constructor(name: string, scene: Nullable<Scene> = null) {
  383. super(name, scene, false);
  384. this.getScene().addMesh(this);
  385. this._resyncLightSources();
  386. }
  387. /**
  388. * Returns the string "AbstractMesh"
  389. */
  390. public getClassName(): string {
  391. return "AbstractMesh";
  392. }
  393. /**
  394. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  395. */
  396. public toString(fullDetails?: boolean): string {
  397. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof InstancedMesh ? "YES" : "NO");
  398. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  399. if (this._skeleton) {
  400. ret += ", skeleton: " + this._skeleton.name;
  401. }
  402. if (fullDetails) {
  403. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  404. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  405. }
  406. return ret;
  407. }
  408. public _rebuild(): void {
  409. if (this._occlusionQuery) {
  410. this._occlusionQuery = null;
  411. }
  412. if (this._edgesRenderer) {
  413. this._edgesRenderer._rebuild();
  414. }
  415. if (!this.subMeshes) {
  416. return;
  417. }
  418. for (var subMesh of this.subMeshes) {
  419. subMesh._rebuild();
  420. }
  421. }
  422. public _resyncLightSources(): void {
  423. this._lightSources.length = 0;
  424. for (var light of this.getScene().lights) {
  425. if (!light.isEnabled()) {
  426. continue;
  427. }
  428. if (light.canAffectMesh(this)) {
  429. this._lightSources.push(light);
  430. }
  431. }
  432. this._markSubMeshesAsLightDirty();
  433. }
  434. public _resyncLighSource(light: Light): void {
  435. var isIn = light.isEnabled() && light.canAffectMesh(this);
  436. var index = this._lightSources.indexOf(light);
  437. if (index === -1) {
  438. if (!isIn) {
  439. return;
  440. }
  441. this._lightSources.push(light);
  442. } else {
  443. if (isIn) {
  444. return;
  445. }
  446. this._lightSources.splice(index, 1);
  447. }
  448. this._markSubMeshesAsLightDirty();
  449. }
  450. public _removeLightSource(light: Light): void {
  451. var index = this._lightSources.indexOf(light);
  452. if (index === -1) {
  453. return;
  454. }
  455. this._lightSources.splice(index, 1);
  456. this._markSubMeshesAsLightDirty();
  457. }
  458. private _markSubMeshesAsDirty(func: (defines: MaterialDefines) => void) {
  459. if (!this.subMeshes) {
  460. return;
  461. }
  462. for (var subMesh of this.subMeshes) {
  463. if (subMesh._materialDefines) {
  464. func(subMesh._materialDefines);
  465. }
  466. }
  467. }
  468. public _markSubMeshesAsLightDirty() {
  469. this._markSubMeshesAsDirty(defines => defines.markAsLightDirty());
  470. }
  471. public _markSubMeshesAsAttributesDirty() {
  472. this._markSubMeshesAsDirty(defines => defines.markAsAttributesDirty());
  473. }
  474. public _markSubMeshesAsMiscDirty() {
  475. if (!this.subMeshes) {
  476. return;
  477. }
  478. for (var subMesh of this.subMeshes) {
  479. var material = subMesh.getMaterial();
  480. if (material) {
  481. material.markAsDirty(Material.MiscDirtyFlag);
  482. }
  483. }
  484. }
  485. /**
  486. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  487. * Default : (1.0, 1.0, 1.0)
  488. */
  489. public get scaling(): Vector3 {
  490. return this._scaling;
  491. }
  492. /**
  493. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  494. * Default : (1.0, 1.0, 1.0)
  495. */
  496. public set scaling(newScaling: Vector3) {
  497. this._scaling = newScaling;
  498. if (this.physicsImpostor) {
  499. this.physicsImpostor.forceUpdate();
  500. }
  501. }
  502. // Methods
  503. /**
  504. * Disables the mesh edger rendering mode.
  505. * Returns the AbstractMesh.
  506. */
  507. public disableEdgesRendering(): AbstractMesh {
  508. if (this._edgesRenderer) {
  509. this._edgesRenderer.dispose();
  510. this._edgesRenderer = null;
  511. }
  512. return this;
  513. }
  514. /**
  515. * Enables the edge rendering mode on the mesh.
  516. * This mode makes the mesh edges visible.
  517. * Returns the AbstractMesh.
  518. */
  519. public enableEdgesRendering(epsilon = 0.95, checkVerticesInsteadOfIndices = false): AbstractMesh {
  520. this.disableEdgesRendering();
  521. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  522. return this;
  523. }
  524. /**
  525. * Returns true if the mesh is blocked. Used by the class Mesh.
  526. * Returns the boolean `false` by default.
  527. */
  528. public get isBlocked(): boolean {
  529. return false;
  530. }
  531. /**
  532. * Returns the mesh itself by default, used by the class Mesh.
  533. * Returned type : AbstractMesh
  534. */
  535. public getLOD(camera: Camera): AbstractMesh {
  536. return this;
  537. }
  538. /**
  539. * Returns 0 by default, used by the class Mesh.
  540. * Returns an integer.
  541. */
  542. public getTotalVertices(): number {
  543. return 0;
  544. }
  545. /**
  546. * Returns null by default, used by the class Mesh.
  547. * Returned type : integer array
  548. */
  549. public getIndices(): Nullable<IndicesArray> {
  550. return null;
  551. }
  552. /**
  553. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  554. * Returned type : float array or Float32Array
  555. */
  556. public getVerticesData(kind: string): Nullable<FloatArray> {
  557. return null;
  558. }
  559. /**
  560. * Sets the vertex data of the mesh geometry for the requested `kind`.
  561. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  562. * The `data` are either a numeric array either a Float32Array.
  563. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  564. * 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).
  565. * Note that a new underlying VertexBuffer object is created each call.
  566. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  567. *
  568. * Possible `kind` values :
  569. * - BABYLON.VertexBuffer.PositionKind
  570. * - BABYLON.VertexBuffer.UVKind
  571. * - BABYLON.VertexBuffer.UV2Kind
  572. * - BABYLON.VertexBuffer.UV3Kind
  573. * - BABYLON.VertexBuffer.UV4Kind
  574. * - BABYLON.VertexBuffer.UV5Kind
  575. * - BABYLON.VertexBuffer.UV6Kind
  576. * - BABYLON.VertexBuffer.ColorKind
  577. * - BABYLON.VertexBuffer.MatricesIndicesKind
  578. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  579. * - BABYLON.VertexBuffer.MatricesWeightsKind
  580. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  581. *
  582. * Returns the Mesh.
  583. */
  584. public setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): AbstractMesh {
  585. return this;
  586. }
  587. /**
  588. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  589. * If the mesh has no geometry, it is simply returned as it is.
  590. * The `data` are either a numeric array either a Float32Array.
  591. * No new underlying VertexBuffer object is created.
  592. * 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.
  593. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  594. *
  595. * Possible `kind` values :
  596. * - BABYLON.VertexBuffer.PositionKind
  597. * - BABYLON.VertexBuffer.UVKind
  598. * - BABYLON.VertexBuffer.UV2Kind
  599. * - BABYLON.VertexBuffer.UV3Kind
  600. * - BABYLON.VertexBuffer.UV4Kind
  601. * - BABYLON.VertexBuffer.UV5Kind
  602. * - BABYLON.VertexBuffer.UV6Kind
  603. * - BABYLON.VertexBuffer.ColorKind
  604. * - BABYLON.VertexBuffer.MatricesIndicesKind
  605. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  606. * - BABYLON.VertexBuffer.MatricesWeightsKind
  607. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  608. *
  609. * Returns the Mesh.
  610. */
  611. public updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): AbstractMesh {
  612. return this;
  613. }
  614. /**
  615. * Sets the mesh indices.
  616. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  617. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  618. * This method creates a new index buffer each call.
  619. * Returns the Mesh.
  620. */
  621. public setIndices(indices: IndicesArray, totalVertices: Nullable<number>): AbstractMesh {
  622. return this;
  623. }
  624. /** Returns false by default, used by the class Mesh.
  625. * Returns a boolean
  626. */
  627. public isVerticesDataPresent(kind: string): boolean {
  628. return false;
  629. }
  630. /**
  631. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  632. * Returns a BoundingInfo
  633. */
  634. public getBoundingInfo(): BoundingInfo {
  635. if (this._masterMesh) {
  636. return this._masterMesh.getBoundingInfo();
  637. }
  638. if (!this._boundingInfo) {
  639. // this._boundingInfo is being created here
  640. this._updateBoundingInfo();
  641. }
  642. // cannot be null.
  643. return this._boundingInfo!;
  644. }
  645. /**
  646. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  647. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  648. */
  649. public normalizeToUnitCube(includeDescendants = true): AbstractMesh {
  650. let boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  651. let sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  652. let maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  653. if (maxDimension === 0) {
  654. return this;
  655. }
  656. let scale = 1 / maxDimension;
  657. this.scaling.scaleInPlace(scale);
  658. return this;
  659. }
  660. /**
  661. * Sets a mesh new object BoundingInfo.
  662. * Returns the AbstractMesh.
  663. */
  664. public setBoundingInfo(boundingInfo: BoundingInfo): AbstractMesh {
  665. this._boundingInfo = boundingInfo;
  666. return this;
  667. }
  668. public get useBones(): boolean {
  669. return (<boolean>(this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(VertexBuffer.MatricesWeightsKind)));
  670. }
  671. public _preActivate(): void {
  672. }
  673. public _preActivateForIntermediateRendering(renderId: number): void {
  674. }
  675. public _activate(renderId: number): void {
  676. this._renderId = renderId;
  677. }
  678. /**
  679. * Returns the latest update of the World matrix
  680. * Returns a Matrix.
  681. */
  682. public getWorldMatrix(): Matrix {
  683. if (this._masterMesh) {
  684. return this._masterMesh.getWorldMatrix();
  685. }
  686. return super.getWorldMatrix();
  687. }
  688. /**
  689. * Returns the latest update of the World matrix determinant.
  690. */
  691. protected _getWorldMatrixDeterminant(): number {
  692. if (this._masterMesh) {
  693. return this._masterMesh._getWorldMatrixDeterminant();
  694. }
  695. return super._getWorldMatrixDeterminant();
  696. }
  697. // ================================== Point of View Movement =================================
  698. /**
  699. * Perform relative position change from the point of view of behind the front of the mesh.
  700. * This is performed taking into account the meshes current rotation, so you do not have to care.
  701. * Supports definition of mesh facing forward or backward.
  702. * @param {number} amountRight
  703. * @param {number} amountUp
  704. * @param {number} amountForward
  705. *
  706. * Returns the AbstractMesh.
  707. */
  708. public movePOV(amountRight: number, amountUp: number, amountForward: number): AbstractMesh {
  709. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  710. return this;
  711. }
  712. /**
  713. * Calculate relative position change from the point of view of behind the front of the mesh.
  714. * This is performed taking into account the meshes current rotation, so you do not have to care.
  715. * Supports definition of mesh facing forward or backward.
  716. * @param {number} amountRight
  717. * @param {number} amountUp
  718. * @param {number} amountForward
  719. *
  720. * Returns a new Vector3.
  721. */
  722. public calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3 {
  723. var rotMatrix = new Matrix();
  724. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  725. rotQuaternion.toRotationMatrix(rotMatrix);
  726. var translationDelta = Vector3.Zero();
  727. var defForwardMult = this.definedFacingForward ? -1 : 1;
  728. Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  729. return translationDelta;
  730. }
  731. // ================================== Point of View Rotation =================================
  732. /**
  733. * Perform relative rotation change from the point of view of behind the front of the mesh.
  734. * Supports definition of mesh facing forward or backward.
  735. * @param {number} flipBack
  736. * @param {number} twirlClockwise
  737. * @param {number} tiltRight
  738. *
  739. * Returns the AbstractMesh.
  740. */
  741. public rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): AbstractMesh {
  742. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  743. return this;
  744. }
  745. /**
  746. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  747. * Supports definition of mesh facing forward or backward.
  748. * @param {number} flipBack
  749. * @param {number} twirlClockwise
  750. * @param {number} tiltRight
  751. *
  752. * Returns a new Vector3.
  753. */
  754. public calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3 {
  755. var defForwardMult = this.definedFacingForward ? 1 : -1;
  756. return new Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  757. }
  758. /**
  759. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  760. * @param includeDescendants Include bounding info from descendants as well (true by default).
  761. */
  762. public getHierarchyBoundingVectors(includeDescendants = true): { min: Vector3, max: Vector3 } {
  763. this.computeWorldMatrix(true);
  764. let min: Vector3;
  765. let max: Vector3;
  766. let boundingInfo = this.getBoundingInfo();
  767. if (!this.subMeshes) {
  768. min = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  769. max = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  770. } else {
  771. min = boundingInfo.boundingBox.minimumWorld;
  772. max = boundingInfo.boundingBox.maximumWorld;
  773. }
  774. if (includeDescendants) {
  775. let descendants = this.getDescendants(false);
  776. for (var descendant of descendants) {
  777. let childMesh = <AbstractMesh>descendant;
  778. childMesh.computeWorldMatrix(true);
  779. //make sure we have the needed params to get mix and max
  780. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  781. continue;
  782. }
  783. let childBoundingInfo = childMesh.getBoundingInfo();
  784. let boundingBox = childBoundingInfo.boundingBox;
  785. var minBox = boundingBox.minimumWorld;
  786. var maxBox = boundingBox.maximumWorld;
  787. Tools.CheckExtends(minBox, min, max);
  788. Tools.CheckExtends(maxBox, min, max);
  789. }
  790. }
  791. return {
  792. min: min,
  793. max: max
  794. }
  795. }
  796. /**
  797. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  798. * Returns the AbstractMesh.
  799. */
  800. public _updateBoundingInfo(): AbstractMesh {
  801. this._boundingInfo = this._boundingInfo || new BoundingInfo(this.absolutePosition, this.absolutePosition);
  802. this._boundingInfo.update(this.worldMatrixFromCache);
  803. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  804. return this;
  805. }
  806. /**
  807. * Update a mesh's children BoundingInfo objects only.
  808. * Returns the AbstractMesh.
  809. */
  810. public _updateSubMeshesBoundingInfo(matrix: Matrix): AbstractMesh {
  811. if (!this.subMeshes) {
  812. return this;
  813. }
  814. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  815. var subMesh = this.subMeshes[subIndex];
  816. if (!subMesh.IsGlobal) {
  817. subMesh.updateBoundingInfo(matrix);
  818. }
  819. }
  820. return this;
  821. }
  822. protected _afterComputeWorldMatrix(): void {
  823. // Bounding info
  824. this._updateBoundingInfo();
  825. }
  826. /**
  827. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  828. * A mesh is in the frustum if its bounding box intersects the frustum.
  829. * Boolean returned.
  830. */
  831. public isInFrustum(frustumPlanes: Plane[]): boolean {
  832. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  833. }
  834. /**
  835. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  836. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  837. * Boolean returned.
  838. */
  839. public isCompletelyInFrustum(frustumPlanes: Plane[]): boolean {
  840. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);;
  841. }
  842. /**
  843. * True if the mesh intersects another mesh or a SolidParticle object.
  844. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  845. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  846. * Returns a boolean.
  847. */
  848. public intersectsMesh(mesh: AbstractMesh | SolidParticle, precise: boolean = false, includeDescendants?: boolean): boolean {
  849. if (!this._boundingInfo || !mesh._boundingInfo) {
  850. return false;
  851. }
  852. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  853. return true;
  854. }
  855. if (includeDescendants) {
  856. for (var child of this.getChildMeshes()) {
  857. if (child.intersectsMesh(mesh, precise, true)) {
  858. return true;
  859. }
  860. }
  861. }
  862. return false;
  863. }
  864. /**
  865. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  866. * Returns a boolean.
  867. */
  868. public intersectsPoint(point: Vector3): boolean {
  869. if (!this._boundingInfo) {
  870. return false;
  871. }
  872. return this._boundingInfo.intersectsPoint(point);
  873. }
  874. public getPhysicsImpostor(): Nullable<PhysicsImpostor> {
  875. return this.physicsImpostor;
  876. }
  877. public getPositionInCameraSpace(camera: Nullable<Camera> = null): Vector3 {
  878. if (!camera) {
  879. camera = (<Camera>this.getScene().activeCamera);
  880. }
  881. return Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  882. }
  883. /**
  884. * Returns the distance from the mesh to the active camera.
  885. * Returns a float.
  886. */
  887. public getDistanceToCamera(camera: Nullable<Camera> = null): number {
  888. if (!camera) {
  889. camera = (<Camera>this.getScene().activeCamera);
  890. }
  891. return this.absolutePosition.subtract(camera.position).length();
  892. }
  893. public applyImpulse(force: Vector3, contactPoint: Vector3): AbstractMesh {
  894. if (!this.physicsImpostor) {
  895. return this;
  896. }
  897. this.physicsImpostor.applyImpulse(force, contactPoint);
  898. return this;
  899. }
  900. public setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): AbstractMesh {
  901. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  902. return this;
  903. }
  904. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, PhysicsJoint.HingeJoint, {
  905. mainPivot: pivot1,
  906. connectedPivot: pivot2,
  907. nativeParams: options
  908. });
  909. return this;
  910. }
  911. // Collisions
  912. /**
  913. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  914. * Default `false`.
  915. */
  916. public get checkCollisions(): boolean {
  917. return this._checkCollisions;
  918. }
  919. public set checkCollisions(collisionEnabled: boolean) {
  920. this._checkCollisions = collisionEnabled;
  921. if (this.getScene().workerCollisions) {
  922. this.getScene().collisionCoordinator.onMeshUpdated(this);
  923. }
  924. }
  925. /**
  926. * Gets Collider object used to compute collisions (not physics)
  927. */
  928. public get collider(): Collider {
  929. return this._collider;
  930. }
  931. public moveWithCollisions(displacement: Vector3): AbstractMesh {
  932. var globalPosition = this.getAbsolutePosition();
  933. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  934. if (!this._collider) {
  935. this._collider = new Collider();
  936. }
  937. this._collider._radius = this.ellipsoid;
  938. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  939. return this;
  940. }
  941. private _onCollisionPositionChange = (collisionId: number, newPosition: Vector3, collidedMesh: Nullable<AbstractMesh> = null) => {
  942. //TODO move this to the collision coordinator!
  943. if (this.getScene().workerCollisions)
  944. newPosition.multiplyInPlace(this._collider._radius);
  945. newPosition.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  946. if (this._diffPositionForCollisions.length() > Engine.CollisionsEpsilon) {
  947. this.position.addInPlace(this._diffPositionForCollisions);
  948. }
  949. if (collidedMesh) {
  950. this.onCollideObservable.notifyObservers(collidedMesh);
  951. }
  952. this.onCollisionPositionChangeObservable.notifyObservers(this.position);
  953. }
  954. // Submeshes octree
  955. /**
  956. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  957. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  958. * Returns an Octree of submeshes.
  959. */
  960. public createOrUpdateSubmeshesOctree(maxCapacity = 64, maxDepth = 2): Octree<SubMesh> {
  961. if (!this._submeshesOctree) {
  962. this._submeshesOctree = new Octree<SubMesh>(Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  963. }
  964. this.computeWorldMatrix(true);
  965. let boundingInfo = this.getBoundingInfo();
  966. // Update octree
  967. var bbox = boundingInfo.boundingBox;
  968. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  969. return this._submeshesOctree;
  970. }
  971. // Collisions
  972. public _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): AbstractMesh {
  973. this._generatePointsArray();
  974. if (!this._positions) {
  975. return this;
  976. }
  977. // Transformation
  978. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  979. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  980. subMesh._lastColliderWorldVertices = [];
  981. subMesh._trianglePlanes = [];
  982. var start = subMesh.verticesStart;
  983. var end = (subMesh.verticesStart + subMesh.verticesCount);
  984. for (var i = start; i < end; i++) {
  985. subMesh._lastColliderWorldVertices.push(Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  986. }
  987. }
  988. // Collide
  989. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, (<IndicesArray>this.getIndices()), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  990. if (collider.collisionFound) {
  991. collider.collidedMesh = this;
  992. }
  993. return this;
  994. }
  995. public _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): AbstractMesh {
  996. var subMeshes: SubMesh[];
  997. var len: number;
  998. // Octrees
  999. if (this._submeshesOctree && this.useOctreeForCollisions) {
  1000. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  1001. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  1002. len = intersections.length;
  1003. subMeshes = intersections.data;
  1004. } else {
  1005. subMeshes = this.subMeshes;
  1006. len = subMeshes.length;
  1007. }
  1008. for (var index = 0; index < len; index++) {
  1009. var subMesh = subMeshes[index];
  1010. // Bounding test
  1011. if (len > 1 && !subMesh._checkCollision(collider))
  1012. continue;
  1013. this._collideForSubMesh(subMesh, transformMatrix, collider);
  1014. }
  1015. return this;
  1016. }
  1017. public _checkCollision(collider: Collider): AbstractMesh {
  1018. // Bounding box test
  1019. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  1020. return this;
  1021. // Transformation matrix
  1022. Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  1023. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  1024. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  1025. return this;
  1026. }
  1027. // Picking
  1028. public _generatePointsArray(): boolean {
  1029. return false;
  1030. }
  1031. /**
  1032. * Checks if the passed Ray intersects with the mesh.
  1033. * Returns an object PickingInfo.
  1034. */
  1035. public intersects(ray: Ray, fastCheck?: boolean): PickingInfo {
  1036. var pickingInfo = new PickingInfo();
  1037. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  1038. return pickingInfo;
  1039. }
  1040. if (!this._generatePointsArray()) {
  1041. return pickingInfo;
  1042. }
  1043. var intersectInfo: Nullable<IntersectionInfo> = null;
  1044. // Octrees
  1045. var subMeshes: SubMesh[];
  1046. var len: number;
  1047. if (this._submeshesOctree && this.useOctreeForPicking) {
  1048. var worldRay = Ray.Transform(ray, this.getWorldMatrix());
  1049. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  1050. len = intersections.length;
  1051. subMeshes = intersections.data;
  1052. } else {
  1053. subMeshes = this.subMeshes;
  1054. len = subMeshes.length;
  1055. }
  1056. for (var index = 0; index < len; index++) {
  1057. var subMesh = subMeshes[index];
  1058. // Bounding test
  1059. if (len > 1 && !subMesh.canIntersects(ray))
  1060. continue;
  1061. var currentIntersectInfo = subMesh.intersects(ray, (<Vector3[]>this._positions), (<IndicesArray>this.getIndices()), fastCheck);
  1062. if (currentIntersectInfo) {
  1063. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  1064. intersectInfo = currentIntersectInfo;
  1065. intersectInfo.subMeshId = index;
  1066. if (fastCheck) {
  1067. break;
  1068. }
  1069. }
  1070. }
  1071. }
  1072. if (intersectInfo) {
  1073. // Get picked point
  1074. var world = this.getWorldMatrix();
  1075. var worldOrigin = Vector3.TransformCoordinates(ray.origin, world);
  1076. var direction = ray.direction.clone();
  1077. direction = direction.scale(intersectInfo.distance);
  1078. var worldDirection = Vector3.TransformNormal(direction, world);
  1079. var pickedPoint = worldOrigin.add(worldDirection);
  1080. // Return result
  1081. pickingInfo.hit = true;
  1082. pickingInfo.distance = Vector3.Distance(worldOrigin, pickedPoint);
  1083. pickingInfo.pickedPoint = pickedPoint;
  1084. pickingInfo.pickedMesh = this;
  1085. pickingInfo.bu = intersectInfo.bu || 0;
  1086. pickingInfo.bv = intersectInfo.bv || 0;
  1087. pickingInfo.faceId = intersectInfo.faceId;
  1088. pickingInfo.subMeshId = intersectInfo.subMeshId;
  1089. return pickingInfo;
  1090. }
  1091. return pickingInfo;
  1092. }
  1093. /**
  1094. * Clones the mesh, used by the class Mesh.
  1095. * Just returns `null` for an AbstractMesh.
  1096. */
  1097. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Nullable<AbstractMesh> {
  1098. return null;
  1099. }
  1100. /**
  1101. * Disposes all the mesh submeshes.
  1102. * Returns the AbstractMesh.
  1103. */
  1104. public releaseSubMeshes(): AbstractMesh {
  1105. if (this.subMeshes) {
  1106. while (this.subMeshes.length) {
  1107. this.subMeshes[0].dispose();
  1108. }
  1109. } else {
  1110. this.subMeshes = new Array<SubMesh>();
  1111. }
  1112. return this;
  1113. }
  1114. /**
  1115. * Releases resources associated with this abstract mesh.
  1116. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  1117. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  1118. */
  1119. public dispose(doNotRecurse?: boolean, disposeMaterialAndTextures = false): void {
  1120. var index: number;
  1121. // Action manager
  1122. if (this.actionManager !== undefined && this.actionManager !== null) {
  1123. this.actionManager.dispose();
  1124. this.actionManager = null;
  1125. }
  1126. // Skeleton
  1127. this.skeleton = null;
  1128. // Physics
  1129. if (this.physicsImpostor) {
  1130. this.physicsImpostor.dispose(/*!doNotRecurse*/);
  1131. }
  1132. // Intersections in progress
  1133. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  1134. var other = this._intersectionsInProgress[index];
  1135. var pos = other._intersectionsInProgress.indexOf(this);
  1136. other._intersectionsInProgress.splice(pos, 1);
  1137. }
  1138. this._intersectionsInProgress = [];
  1139. // Lights
  1140. var lights = this.getScene().lights;
  1141. lights.forEach((light: Light) => {
  1142. var meshIndex = light.includedOnlyMeshes.indexOf(this);
  1143. if (meshIndex !== -1) {
  1144. light.includedOnlyMeshes.splice(meshIndex, 1);
  1145. }
  1146. meshIndex = light.excludedMeshes.indexOf(this);
  1147. if (meshIndex !== -1) {
  1148. light.excludedMeshes.splice(meshIndex, 1);
  1149. }
  1150. // Shadow generators
  1151. var generator = light.getShadowGenerator();
  1152. if (generator) {
  1153. var shadowMap = generator.getShadowMap();
  1154. if (shadowMap && shadowMap.renderList) {
  1155. meshIndex = shadowMap.renderList.indexOf(this);
  1156. if (meshIndex !== -1) {
  1157. shadowMap.renderList.splice(meshIndex, 1);
  1158. }
  1159. }
  1160. }
  1161. });
  1162. // Edges
  1163. if (this._edgesRenderer) {
  1164. this._edgesRenderer.dispose();
  1165. this._edgesRenderer = null;
  1166. }
  1167. // SubMeshes
  1168. if (this.getClassName() !== "InstancedMesh") {
  1169. this.releaseSubMeshes();
  1170. }
  1171. // Octree
  1172. const sceneOctree = this.getScene().selectionOctree;
  1173. if (sceneOctree !== undefined && sceneOctree !== null) {
  1174. var index = sceneOctree.dynamicContent.indexOf(this);
  1175. if (index !== -1) {
  1176. sceneOctree.dynamicContent.splice(index, 1);
  1177. }
  1178. }
  1179. // Query
  1180. let engine = this.getScene().getEngine();
  1181. if (this._occlusionQuery) {
  1182. this._isOcclusionQueryInProgress = false;
  1183. engine.deleteQuery(this._occlusionQuery);
  1184. this._occlusionQuery = null;
  1185. }
  1186. // Engine
  1187. engine.wipeCaches();
  1188. // Remove from scene
  1189. this.getScene().removeMesh(this);
  1190. if (disposeMaterialAndTextures) {
  1191. if (this.material) {
  1192. this.material.dispose(false, true);
  1193. }
  1194. }
  1195. if (!doNotRecurse) {
  1196. // Particles
  1197. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  1198. if (this.getScene().particleSystems[index].emitter === this) {
  1199. this.getScene().particleSystems[index].dispose();
  1200. index--;
  1201. }
  1202. }
  1203. }
  1204. // facet data
  1205. if (this._facetDataEnabled) {
  1206. this.disableFacetData();
  1207. }
  1208. this.onAfterWorldMatrixUpdateObservable.clear();
  1209. this.onCollideObservable.clear();
  1210. this.onCollisionPositionChangeObservable.clear();
  1211. super.dispose(doNotRecurse, disposeMaterialAndTextures);
  1212. }
  1213. /**
  1214. * Adds the passed mesh as a child to the current mesh.
  1215. * Returns the AbstractMesh.
  1216. */
  1217. public addChild(mesh: AbstractMesh): AbstractMesh {
  1218. mesh.setParent(this);
  1219. return this;
  1220. }
  1221. /**
  1222. * Removes the passed mesh from the current mesh children list.
  1223. * Returns the AbstractMesh.
  1224. */
  1225. public removeChild(mesh: AbstractMesh): AbstractMesh {
  1226. mesh.setParent(null);
  1227. return this;
  1228. }
  1229. // Facet data
  1230. /**
  1231. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  1232. * Returns the AbstractMesh.
  1233. */
  1234. private _initFacetData(): AbstractMesh {
  1235. if (!this._facetNormals) {
  1236. this._facetNormals = new Array<Vector3>();
  1237. }
  1238. if (!this._facetPositions) {
  1239. this._facetPositions = new Array<Vector3>();
  1240. }
  1241. if (!this._facetPartitioning) {
  1242. this._facetPartitioning = new Array<number[]>();
  1243. }
  1244. this._facetNb = ((<IndicesArray>this.getIndices()).length / 3) | 0;
  1245. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  1246. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  1247. for (var f = 0; f < this._facetNb; f++) {
  1248. this._facetNormals[f] = Vector3.Zero();
  1249. this._facetPositions[f] = Vector3.Zero();
  1250. }
  1251. this._facetDataEnabled = true;
  1252. return this;
  1253. }
  1254. /**
  1255. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  1256. * This method can be called within the render loop.
  1257. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  1258. * Returns the AbstractMesh.
  1259. */
  1260. public updateFacetData(): AbstractMesh {
  1261. if (!this._facetDataEnabled) {
  1262. this._initFacetData();
  1263. }
  1264. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1265. var indices = this.getIndices();
  1266. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  1267. var bInfo = this.getBoundingInfo();
  1268. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  1269. // init arrays, matrix and sort function on first call
  1270. this._facetDepthSortEnabled = true;
  1271. if (indices instanceof Uint16Array) {
  1272. this._depthSortedIndices = new Uint16Array(indices!);
  1273. }
  1274. else if (indices instanceof Uint32Array) {
  1275. this._depthSortedIndices = new Uint32Array(indices!);
  1276. }
  1277. else {
  1278. var needs32bits = false;
  1279. for (var i = 0; i < indices!.length; i++) {
  1280. if (indices![i] > 65535) {
  1281. needs32bits = true;
  1282. break;
  1283. }
  1284. }
  1285. if (needs32bits) {
  1286. this._depthSortedIndices = new Uint32Array(indices!);
  1287. }
  1288. else {
  1289. this._depthSortedIndices = new Uint16Array(indices!);
  1290. }
  1291. }
  1292. this._facetDepthSortFunction = function (f1, f2) {
  1293. return (f2.sqDistance - f1.sqDistance);
  1294. };
  1295. if (!this._facetDepthSortFrom) {
  1296. var camera = this.getScene().activeCamera;
  1297. this._facetDepthSortFrom = (camera) ? camera.position : Vector3.Zero();
  1298. }
  1299. this._depthSortedFacets = [];
  1300. for (var f = 0; f < this._facetNb; f++) {
  1301. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  1302. this._depthSortedFacets.push(depthSortedFacet);
  1303. }
  1304. this._invertedMatrix = Matrix.Identity();
  1305. this._facetDepthSortOrigin = Vector3.Zero();
  1306. }
  1307. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : Epsilon;
  1308. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : Epsilon;
  1309. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : Epsilon;
  1310. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  1311. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  1312. this._subDiv.max = this._partitioningSubdivisions;
  1313. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  1314. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  1315. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  1316. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  1317. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  1318. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  1319. // set the parameters for ComputeNormals()
  1320. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  1321. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  1322. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  1323. this._facetParameters.bInfo = bInfo;
  1324. this._facetParameters.bbSize = this._bbSize;
  1325. this._facetParameters.subDiv = this._subDiv;
  1326. this._facetParameters.ratio = this.partitioningBBoxRatio;
  1327. this._facetParameters.depthSort = this._facetDepthSort;
  1328. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  1329. this.computeWorldMatrix(true);
  1330. this._worldMatrix.invertToRef(this._invertedMatrix);
  1331. Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  1332. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  1333. }
  1334. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  1335. VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  1336. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  1337. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  1338. var l = (this._depthSortedIndices.length / 3) | 0;
  1339. for (var f = 0; f < l; f++) {
  1340. var sind = this._depthSortedFacets[f].ind;
  1341. this._depthSortedIndices[f * 3] = indices![sind];
  1342. this._depthSortedIndices[f * 3 + 1] = indices![sind + 1];
  1343. this._depthSortedIndices[f * 3 + 2] = indices![sind + 2];
  1344. }
  1345. this.updateIndices(this._depthSortedIndices);
  1346. }
  1347. return this;
  1348. }
  1349. /**
  1350. * Returns the facetLocalNormals array.
  1351. * The normals are expressed in the mesh local space.
  1352. */
  1353. public getFacetLocalNormals(): Vector3[] {
  1354. if (!this._facetNormals) {
  1355. this.updateFacetData();
  1356. }
  1357. return this._facetNormals;
  1358. }
  1359. /**
  1360. * Returns the facetLocalPositions array.
  1361. * The facet positions are expressed in the mesh local space.
  1362. */
  1363. public getFacetLocalPositions(): Vector3[] {
  1364. if (!this._facetPositions) {
  1365. this.updateFacetData();
  1366. }
  1367. return this._facetPositions;
  1368. }
  1369. /**
  1370. * Returns the facetLocalPartioning array.
  1371. */
  1372. public getFacetLocalPartitioning(): number[][] {
  1373. if (!this._facetPartitioning) {
  1374. this.updateFacetData();
  1375. }
  1376. return this._facetPartitioning;
  1377. }
  1378. /**
  1379. * Returns the i-th facet position in the world system.
  1380. * This method allocates a new Vector3 per call.
  1381. */
  1382. public getFacetPosition(i: number): Vector3 {
  1383. var pos = Vector3.Zero();
  1384. this.getFacetPositionToRef(i, pos);
  1385. return pos;
  1386. }
  1387. /**
  1388. * Sets the reference Vector3 with the i-th facet position in the world system.
  1389. * Returns the AbstractMesh.
  1390. */
  1391. public getFacetPositionToRef(i: number, ref: Vector3): AbstractMesh {
  1392. var localPos = (this.getFacetLocalPositions())[i];
  1393. var world = this.getWorldMatrix();
  1394. Vector3.TransformCoordinatesToRef(localPos, world, ref);
  1395. return this;
  1396. }
  1397. /**
  1398. * Returns the i-th facet normal in the world system.
  1399. * This method allocates a new Vector3 per call.
  1400. */
  1401. public getFacetNormal(i: number): Vector3 {
  1402. var norm = Vector3.Zero();
  1403. this.getFacetNormalToRef(i, norm);
  1404. return norm;
  1405. }
  1406. /**
  1407. * Sets the reference Vector3 with the i-th facet normal in the world system.
  1408. * Returns the AbstractMesh.
  1409. */
  1410. public getFacetNormalToRef(i: number, ref: Vector3) {
  1411. var localNorm = (this.getFacetLocalNormals())[i];
  1412. Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  1413. return this;
  1414. }
  1415. /**
  1416. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  1417. */
  1418. public getFacetsAtLocalCoordinates(x: number, y: number, z: number): Nullable<number[]> {
  1419. var bInfo = this.getBoundingInfo();
  1420. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  1421. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  1422. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  1423. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  1424. return null;
  1425. }
  1426. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  1427. }
  1428. /**
  1429. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  1430. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  1431. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  1432. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  1433. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  1434. */
  1435. public getClosestFacetAtCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): Nullable<number> {
  1436. var world = this.getWorldMatrix();
  1437. var invMat = Tmp.Matrix[5];
  1438. world.invertToRef(invMat);
  1439. var invVect = Tmp.Vector3[8];
  1440. Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  1441. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  1442. if (projected) {
  1443. // tranform the local computed projected vector to world coordinates
  1444. Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  1445. }
  1446. return closest;
  1447. }
  1448. /**
  1449. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  1450. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  1451. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  1452. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  1453. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  1454. */
  1455. public getClosestFacetAtLocalCoordinates(x: number, y: number, z: number, projected?: Vector3, checkFace: boolean = false, facing: boolean = true): Nullable<number> {
  1456. var closest = null;
  1457. var tmpx = 0.0;
  1458. var tmpy = 0.0;
  1459. var tmpz = 0.0;
  1460. var d = 0.0; // tmp dot facet normal * facet position
  1461. var t0 = 0.0;
  1462. var projx = 0.0;
  1463. var projy = 0.0;
  1464. var projz = 0.0;
  1465. // Get all the facets in the same partitioning block than (x, y, z)
  1466. var facetPositions = this.getFacetLocalPositions();
  1467. var facetNormals = this.getFacetLocalNormals();
  1468. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  1469. if (!facetsInBlock) {
  1470. return null;
  1471. }
  1472. // Get the closest facet to (x, y, z)
  1473. var shortest = Number.MAX_VALUE; // init distance vars
  1474. var tmpDistance = shortest;
  1475. var fib; // current facet in the block
  1476. var norm; // current facet normal
  1477. var p0; // current facet barycenter position
  1478. // loop on all the facets in the current partitioning block
  1479. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  1480. fib = facetsInBlock[idx];
  1481. norm = facetNormals[fib];
  1482. p0 = facetPositions[fib];
  1483. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  1484. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  1485. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  1486. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  1487. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  1488. projx = x + norm.x * t0;
  1489. projy = y + norm.y * t0;
  1490. projz = z + norm.z * t0;
  1491. tmpx = projx - x;
  1492. tmpy = projy - y;
  1493. tmpz = projz - z;
  1494. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  1495. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  1496. shortest = tmpDistance;
  1497. closest = fib;
  1498. if (projected) {
  1499. projected.x = projx;
  1500. projected.y = projy;
  1501. projected.z = projz;
  1502. }
  1503. }
  1504. }
  1505. }
  1506. return closest;
  1507. }
  1508. /**
  1509. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  1510. */
  1511. public getFacetDataParameters(): any {
  1512. return this._facetParameters;
  1513. }
  1514. /**
  1515. * Disables the feature FacetData and frees the related memory.
  1516. * Returns the AbstractMesh.
  1517. */
  1518. public disableFacetData(): AbstractMesh {
  1519. if (this._facetDataEnabled) {
  1520. this._facetDataEnabled = false;
  1521. this._facetPositions = new Array<Vector3>();
  1522. this._facetNormals = new Array<Vector3>();
  1523. this._facetPartitioning = new Array<number[]>();
  1524. this._facetParameters = null;
  1525. this._depthSortedIndices = new Uint32Array(0);
  1526. }
  1527. return this;
  1528. }
  1529. /**
  1530. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  1531. * Returns the mesh.
  1532. */
  1533. public updateIndices(indices: IndicesArray): AbstractMesh {
  1534. return this;
  1535. }
  1536. /**
  1537. * The mesh Geometry. Actually used by the Mesh object.
  1538. * Returns a blank geometry object.
  1539. */
  1540. /**
  1541. * Creates new normals data for the mesh.
  1542. * @param updatable.
  1543. */
  1544. public createNormals(updatable: boolean) {
  1545. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  1546. var indices = this.getIndices();
  1547. var normals: FloatArray;
  1548. if (this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  1549. normals = (<FloatArray>this.getVerticesData(VertexBuffer.NormalKind));
  1550. } else {
  1551. normals = [];
  1552. }
  1553. VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  1554. this.setVerticesData(VertexBuffer.NormalKind, normals, updatable);
  1555. }
  1556. /**
  1557. * Align the mesh with a normal.
  1558. * Returns the mesh.
  1559. */
  1560. public alignWithNormal(normal: Vector3, upDirection?: Vector3): AbstractMesh {
  1561. if (!upDirection) {
  1562. upDirection = Axis.Y;
  1563. }
  1564. var axisX = Tmp.Vector3[0];
  1565. var axisZ = Tmp.Vector3[1];
  1566. Vector3.CrossToRef(upDirection, normal, axisZ);
  1567. Vector3.CrossToRef(normal, axisZ, axisX);
  1568. if (this.rotationQuaternion) {
  1569. Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  1570. } else {
  1571. Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  1572. }
  1573. return this;
  1574. }
  1575. protected checkOcclusionQuery() {
  1576. var engine = this.getEngine();
  1577. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  1578. this._isOccluded = false;
  1579. return;
  1580. }
  1581. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  1582. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  1583. if (isOcclusionQueryAvailable) {
  1584. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  1585. this._isOcclusionQueryInProgress = false;
  1586. this._occlusionInternalRetryCounter = 0;
  1587. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  1588. }
  1589. else {
  1590. this._occlusionInternalRetryCounter++;
  1591. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  1592. this._isOcclusionQueryInProgress = false;
  1593. this._occlusionInternalRetryCounter = 0;
  1594. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  1595. // if strict continue the last state of the object.
  1596. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  1597. }
  1598. else {
  1599. return;
  1600. }
  1601. }
  1602. }
  1603. var scene = this.getScene();
  1604. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  1605. if (!this._occlusionQuery) {
  1606. this._occlusionQuery = engine.createQuery();
  1607. }
  1608. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  1609. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  1610. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  1611. this._isOcclusionQueryInProgress = true;
  1612. }
  1613. }
  1614. }