babylon.mesh.ts 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229
  1. module BABYLON {
  2. export class Mesh extends Node {
  3. // Statics
  4. public static BILLBOARDMODE_NONE = 0;
  5. public static BILLBOARDMODE_X = 1;
  6. public static BILLBOARDMODE_Y = 2;
  7. public static BILLBOARDMODE_Z = 4;
  8. public static BILLBOARDMODE_ALL = 7;
  9. // Members
  10. public position = new BABYLON.Vector3(0, 0, 0);
  11. public rotation = new BABYLON.Vector3(0, 0, 0);
  12. public rotationQuaternion = null;
  13. public scaling = new BABYLON.Vector3(1, 1, 1);
  14. public delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE
  15. public material = null;
  16. public isVisible = true;
  17. public isPickable = true;
  18. public visibility = 1.0;
  19. public billboardMode = BABYLON.Mesh.BILLBOARDMODE_NONE;
  20. public checkCollisions = false;
  21. public receiveShadows = false;
  22. public _isDisposed = false;
  23. public onDispose = null;
  24. public skeleton = null;
  25. public renderingGroupId = 0;
  26. public infiniteDistance = false;
  27. public showBoundingBox = false;
  28. public subMeshes: SubMesh[];
  29. public delayLoadingFile: string;
  30. public actionManager: ActionManager;
  31. // Cache
  32. private _positions = null;
  33. private _localScaling = BABYLON.Matrix.Zero();
  34. private _localRotation = BABYLON.Matrix.Zero();
  35. private _localTranslation = BABYLON.Matrix.Zero();
  36. private _localBillboard = BABYLON.Matrix.Zero();
  37. private _localPivotScaling = BABYLON.Matrix.Zero();
  38. private _localPivotScalingRotation = BABYLON.Matrix.Zero();
  39. private _localWorld = BABYLON.Matrix.Zero();
  40. private _worldMatrix = BABYLON.Matrix.Zero();
  41. private _rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  42. private _collisionsTransformMatrix = BABYLON.Matrix.Zero();
  43. private _collisionsScalingMatrix = BABYLON.Matrix.Zero();
  44. private _absolutePosition = BABYLON.Vector3.Zero();
  45. // Physics
  46. public _physicImpostor = PhysicsEngine.NoImpostor;
  47. public _physicsMass: number;
  48. public _physicsFriction: number;
  49. public _physicRestitution: number;
  50. // Private
  51. private _boundingInfo: BoundingInfo;
  52. private _totalVertices = 0;
  53. private _pivotMatrix = BABYLON.Matrix.Identity();
  54. private _indices = [];
  55. private _renderId = 0;
  56. private _onBeforeRenderCallbacks = [];
  57. private _delayInfo; //ANY
  58. private _vertexStrideSize = 0;
  59. private _animationStarted = false;
  60. private _vertexBuffers;
  61. private _indexBuffer;
  62. private _delayLoadingFunction: (any, Mesh) => void;
  63. constructor(name: string, scene: Scene) {
  64. super(name, scene);
  65. scene.meshes.push(this);
  66. }
  67. public getBoundingInfo(): BoundingInfo {
  68. return this._boundingInfo;
  69. }
  70. public getWorldMatrix(): Matrix {
  71. if (this._currentRenderId !== this.getScene().getRenderId()) {
  72. this.computeWorldMatrix();
  73. }
  74. return this._worldMatrix;
  75. }
  76. public rotate(axis: Vector3, amount: number, space: Space): void {
  77. if (!this.rotationQuaternion) {
  78. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  79. this.rotation = BABYLON.Vector3.Zero();
  80. }
  81. if (!space || space == BABYLON.Space.LOCAL) {
  82. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  83. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  84. }
  85. else {
  86. if (this.parent) {
  87. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  88. invertParentWorldMatrix.invert();
  89. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  90. }
  91. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  92. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  93. }
  94. }
  95. public translate(axis: Vector3, distance: number, space: Space): void {
  96. var displacementVector = axis.scale(distance);
  97. if (!space || space == BABYLON.Space.LOCAL) {
  98. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  99. this.setPositionWithLocalVector(tempV3);
  100. }
  101. else {
  102. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  103. }
  104. }
  105. public getAbsolutePosition(): Vector3 {
  106. this.computeWorldMatrix();
  107. return this._absolutePosition;
  108. }
  109. public setAbsolutePosition(absolutePosition: Vector3): void {
  110. if (!absolutePosition) {
  111. return;
  112. }
  113. var absolutePositionX;
  114. var absolutePositionY;
  115. var absolutePositionZ;
  116. if (absolutePosition.x === undefined) {
  117. if (arguments.length < 3) {
  118. return;
  119. }
  120. absolutePositionX = arguments[0];
  121. absolutePositionY = arguments[1];
  122. absolutePositionZ = arguments[2];
  123. }
  124. else {
  125. absolutePositionX = absolutePosition.x;
  126. absolutePositionY = absolutePosition.y;
  127. absolutePositionZ = absolutePosition.z;
  128. }
  129. if (this.parent) {
  130. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  131. invertParentWorldMatrix.invert();
  132. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  133. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  134. } else {
  135. this.position.x = absolutePositionX;
  136. this.position.y = absolutePositionY;
  137. this.position.z = absolutePositionZ;
  138. }
  139. }
  140. public getTotalVertices(): number {
  141. return this._totalVertices;
  142. }
  143. public getVerticesData(kind): number[] {
  144. return this._vertexBuffers[kind].getData();
  145. }
  146. public getVertexBuffer(kind): VertexBuffer {
  147. return this._vertexBuffers[kind];
  148. }
  149. public isVerticesDataPresent(kind: string): boolean {
  150. if (!this._vertexBuffers) {
  151. if (this._delayInfo) {
  152. return this._delayInfo.indexOf(kind) !== -1;
  153. }
  154. return false;
  155. }
  156. return this._vertexBuffers[kind] !== undefined;
  157. }
  158. public getVerticesDataKinds(): string[] {
  159. var result = [];
  160. if (!this._vertexBuffers && this._delayInfo) {
  161. for (var kind in this._delayInfo) {
  162. result.push(kind);
  163. }
  164. } else {
  165. for (kind in this._vertexBuffers) {
  166. result.push(kind);
  167. }
  168. }
  169. return result;
  170. }
  171. public getTotalIndices(): number {
  172. return this._indices.length;
  173. }
  174. public getIndices(): number[] {
  175. return this._indices;
  176. }
  177. public getVertexStrideSize(): number {
  178. return this._vertexStrideSize;
  179. }
  180. public setPivotMatrix(matrix: Matrix): void {
  181. this._pivotMatrix = matrix;
  182. this._cache.pivotMatrixUpdated = true;
  183. }
  184. public getPivotMatrix(): Matrix {
  185. return this._pivotMatrix;
  186. }
  187. public _isSynchronized(): boolean {
  188. if (this.billboardMode !== Mesh.BILLBOARDMODE_NONE)
  189. return false;
  190. if (this._cache.pivotMatrixUpdated) {
  191. return false;
  192. }
  193. if (this.infiniteDistance) {
  194. return false;
  195. }
  196. if (!this._cache.position.equals(this.position))
  197. return false;
  198. if (this.rotationQuaternion) {
  199. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  200. return false;
  201. } else {
  202. if (!this._cache.rotation.equals(this.rotation))
  203. return false;
  204. }
  205. if (!this._cache.scaling.equals(this.scaling))
  206. return false;
  207. return true;
  208. }
  209. public isReady(): boolean {
  210. return this._isReady;
  211. }
  212. public isAnimated(): boolean {
  213. return this._animationStarted;
  214. }
  215. public isDisposed(): boolean {
  216. return this._isDisposed;
  217. }
  218. // Methods
  219. public _initCache() {
  220. super._initCache();
  221. this._cache.localMatrixUpdated = false;
  222. this._cache.position = BABYLON.Vector3.Zero();
  223. this._cache.scaling = BABYLON.Vector3.Zero();
  224. this._cache.rotation = BABYLON.Vector3.Zero();
  225. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  226. }
  227. public markAsDirty(property: string): void {
  228. if (property === "rotation") {
  229. this.rotationQuaternion = null;
  230. }
  231. this._currentRenderId = Number.MAX_VALUE;
  232. }
  233. public refreshBoundingInfo(): void {
  234. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  235. if (!data) {
  236. return;
  237. }
  238. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  239. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  240. for (var index = 0; index < this.subMeshes.length; index++) {
  241. this.subMeshes[index].refreshBoundingInfo();
  242. }
  243. this._updateBoundingInfo();
  244. }
  245. public _updateBoundingInfo(): void {
  246. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this._absolutePosition, this._absolutePosition);
  247. this._boundingInfo._update(this._worldMatrix);
  248. if (!this.subMeshes) {
  249. return;
  250. }
  251. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  252. var subMesh = this.subMeshes[subIndex];
  253. subMesh.updateBoundingInfo(this._worldMatrix);
  254. }
  255. }
  256. public computeWorldMatrix(force?: boolean): Matrix {
  257. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  258. return this._worldMatrix;
  259. }
  260. this._cache.position.copyFrom(this.position);
  261. this._cache.scaling.copyFrom(this.scaling);
  262. this._cache.pivotMatrixUpdated = false;
  263. this._currentRenderId = this.getScene().getRenderId();
  264. // Scaling
  265. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  266. // Rotation
  267. if (this.rotationQuaternion) {
  268. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  269. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  270. } else {
  271. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  272. this._cache.rotation.copyFrom(this.rotation);
  273. }
  274. // Translation
  275. if (this.infiniteDistance && !this.parent) {
  276. var camera = this.getScene().activeCamera;
  277. var cameraWorldMatrix = camera.getWorldMatrix();
  278. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  279. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  280. } else {
  281. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  282. }
  283. // Composing transformations
  284. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  285. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  286. // Billboarding
  287. if (this.billboardMode !== Mesh.BILLBOARDMODE_NONE) {
  288. var localPosition = this.position.clone();
  289. var zero = this.getScene().activeCamera.position.clone();
  290. if (this.parent && (<any>this.parent).position) {
  291. localPosition.addInPlace((<any>this.parent).position);
  292. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  293. }
  294. if ((this.billboardMode & Mesh.BILLBOARDMODE_ALL) === Mesh.BILLBOARDMODE_ALL) {
  295. zero = this.getScene().activeCamera.position;
  296. } else {
  297. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
  298. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  299. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
  300. zero.y = localPosition.y + 0.001;
  301. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
  302. zero.z = localPosition.z + 0.001;
  303. }
  304. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  305. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  306. this._localBillboard.invert();
  307. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  308. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  309. }
  310. // Local world
  311. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  312. // Parent
  313. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.Mesh.BILLBOARDMODE_NONE) {
  314. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  315. } else {
  316. this._worldMatrix.copyFrom(this._localWorld);
  317. }
  318. // Bounding info
  319. this._updateBoundingInfo();
  320. // Absolute position
  321. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  322. return this._worldMatrix;
  323. }
  324. public _createGlobalSubMesh(): SubMesh {
  325. if (!this._totalVertices || !this._indices) {
  326. return null;
  327. }
  328. this.subMeshes = [];
  329. return new BABYLON.SubMesh(0, 0, this._totalVertices, 0, this._indices.length, this);
  330. }
  331. public subdivide(count: number): void {
  332. if (count < 1) {
  333. return;
  334. }
  335. var subdivisionSize = this._indices.length / count;
  336. var offset = 0;
  337. this.subMeshes = [];
  338. for (var index = 0; index < count; index++) {
  339. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, this._indices.length - offset), this);
  340. offset += subdivisionSize;
  341. }
  342. }
  343. public setVerticesData(data: number[], kind: string, updatable?: boolean): void {
  344. if (!this._vertexBuffers) {
  345. this._vertexBuffers = {};
  346. }
  347. if (this._vertexBuffers[kind]) {
  348. this._vertexBuffers[kind].dispose();
  349. }
  350. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this, data, kind, updatable);
  351. if (kind === BABYLON.VertexBuffer.PositionKind) {
  352. this._resetPointsArrayCache();
  353. var stride = this._vertexBuffers[kind].getStrideSize();
  354. this._totalVertices = data.length / stride;
  355. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  356. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  357. this._createGlobalSubMesh();
  358. }
  359. }
  360. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean): void {
  361. if (this._vertexBuffers[kind]) {
  362. this._vertexBuffers[kind].update(data);
  363. if (kind === BABYLON.VertexBuffer.PositionKind) {
  364. this._resetPointsArrayCache();
  365. if (updateExtends) {
  366. var stride = this._vertexBuffers[kind].getStrideSize();
  367. this._totalVertices = data.length / stride;
  368. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  369. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  370. }
  371. }
  372. }
  373. }
  374. public setIndices(indices: number[]): void {
  375. if (this._indexBuffer) {
  376. this.getScene().getEngine()._releaseBuffer(this._indexBuffer);
  377. }
  378. this._indexBuffer = this.getScene().getEngine().createIndexBuffer(indices);
  379. this._indices = indices;
  380. this._createGlobalSubMesh();
  381. }
  382. // ANY
  383. public bindAndDraw(subMesh: SubMesh, effect, wireframe?: boolean): void {
  384. var engine = this.getScene().getEngine();
  385. // Wireframe
  386. var indexToBind = this._indexBuffer;
  387. var useTriangles = true;
  388. if (wireframe) {
  389. indexToBind = subMesh.getLinesIndexBuffer(this._indices, engine);
  390. useTriangles = false;
  391. }
  392. // VBOs
  393. engine.bindMultiBuffers(this._vertexBuffers, indexToBind, effect);
  394. // Draw order
  395. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  396. }
  397. public registerBeforeRender(func: () => void): void {
  398. this._onBeforeRenderCallbacks.push(func);
  399. }
  400. public unregisterBeforeRender(func: () => void): void {
  401. var index = this._onBeforeRenderCallbacks.indexOf(func);
  402. if (index > -1) {
  403. this._onBeforeRenderCallbacks.splice(index, 1);
  404. }
  405. }
  406. public render(subMesh: SubMesh): void {
  407. if (!this._vertexBuffers || !this._indexBuffer) {
  408. return;
  409. }
  410. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  411. this._onBeforeRenderCallbacks[callbackIndex]();
  412. }
  413. // World
  414. var world = this.getWorldMatrix();
  415. // Material
  416. var effectiveMaterial = subMesh.getMaterial();
  417. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  418. return;
  419. }
  420. effectiveMaterial._preBind();
  421. effectiveMaterial.bind(world, this);
  422. // Bind and draw
  423. var engine = this.getScene().getEngine();
  424. this.bindAndDraw(subMesh, effectiveMaterial.getEffect(), engine.forceWireframe || effectiveMaterial.wireframe);
  425. // Unbind
  426. effectiveMaterial.unbind();
  427. }
  428. public getEmittedParticleSystems(): ParticleSystem[] {
  429. var results = new Array<ParticleSystem>();
  430. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  431. var particleSystem = this.getScene().particleSystems[index];
  432. if (particleSystem.emitter === this) {
  433. results.push(particleSystem);
  434. }
  435. }
  436. return results;
  437. }
  438. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  439. var results = new Array<ParticleSystem>();
  440. var descendants = this.getDescendants();
  441. descendants.push(this);
  442. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  443. var particleSystem = this.getScene().particleSystems[index];
  444. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  445. results.push(particleSystem);
  446. }
  447. }
  448. return results;
  449. }
  450. public getChildren(): Node[] {
  451. var results = [];
  452. for (var index = 0; index < this.getScene().meshes.length; index++) {
  453. var mesh = this.getScene().meshes[index];
  454. if (mesh.parent == this) {
  455. results.push(mesh);
  456. }
  457. }
  458. return results;
  459. }
  460. public isInFrustum(frustumPlanes: Plane[]): boolean {
  461. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  462. return false;
  463. }
  464. var result = this._boundingInfo.isInFrustum(frustumPlanes);
  465. if (result && this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  466. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  467. this.getScene()._addPendingData(this);
  468. Tools.LoadFile(this.delayLoadingFile, data => {
  469. this._delayLoadingFunction(JSON.parse(data), this);
  470. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  471. this.getScene()._removePendingData(this);
  472. }, () => { }, this.getScene().database);
  473. }
  474. return result;
  475. }
  476. public setMaterialByID(id: string): void {
  477. var materials = this.getScene().materials;
  478. for (var index = 0; index < materials.length; index++) {
  479. if (materials[index].id == id) {
  480. this.material = materials[index];
  481. return;
  482. }
  483. }
  484. // Multi
  485. var multiMaterials = this.getScene().multiMaterials;
  486. for (index = 0; index < multiMaterials.length; index++) {
  487. if (multiMaterials[index].id == id) {
  488. this.material = multiMaterials[index];
  489. return;
  490. }
  491. }
  492. }
  493. public getAnimatables(): IAnimatable[] {
  494. var results = [];
  495. if (this.material) {
  496. results.push(this.material);
  497. }
  498. return results;
  499. }
  500. // Geometry
  501. public setPositionWithLocalVector(vector3: Vector3): void {
  502. this.computeWorldMatrix();
  503. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  504. }
  505. public getPositionExpressedInLocalSpace(): Vector3 {
  506. this.computeWorldMatrix();
  507. var invLocalWorldMatrix = this._localWorld.clone();
  508. invLocalWorldMatrix.invert();
  509. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  510. }
  511. public locallyTranslate(vector3: Vector3): void {
  512. this.computeWorldMatrix();
  513. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  514. }
  515. public bakeTransformIntoVertices(transform: Matrix): void {
  516. // Position
  517. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  518. return;
  519. }
  520. this._resetPointsArrayCache();
  521. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  522. var temp = [];
  523. for (var index = 0; index < data.length; index += 3) {
  524. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  525. }
  526. this.setVerticesData(temp, BABYLON.VertexBuffer.PositionKind, this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].isUpdatable());
  527. // Normals
  528. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  529. return;
  530. }
  531. data = this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].getData();
  532. for (index = 0; index < data.length; index += 3) {
  533. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  534. }
  535. this.setVerticesData(temp, BABYLON.VertexBuffer.NormalKind, this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].isUpdatable());
  536. }
  537. public lookAt(targetPoint: Vector3, yawCor: number, pitchCor: number, rollCor: number): void {
  538. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  539. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  540. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  541. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  542. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  543. /// <returns>Mesh oriented towards targetMesh</returns>
  544. yawCor = yawCor || 0; // default to zero if undefined
  545. pitchCor = pitchCor || 0;
  546. rollCor = rollCor || 0;
  547. var dv = targetPoint.subtract(this.position);
  548. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  549. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  550. var pitch = Math.atan2(dv.y, len);
  551. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  552. }
  553. // Cache
  554. public _resetPointsArrayCache(): void {
  555. this._positions = null;
  556. }
  557. public _generatePointsArray(): void {
  558. if (this._positions)
  559. return;
  560. this._positions = [];
  561. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  562. for (var index = 0; index < data.length; index += 3) {
  563. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  564. }
  565. }
  566. // Collisions
  567. public _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): void {
  568. this._generatePointsArray();
  569. // Transformation
  570. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  571. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  572. subMesh._lastColliderWorldVertices = [];
  573. subMesh._trianglePlanes = [];
  574. var start = subMesh.verticesStart;
  575. var end = (subMesh.verticesStart + subMesh.verticesCount);
  576. for (var i = start; i < end; i++) {
  577. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  578. }
  579. }
  580. // Collide
  581. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this._indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  582. }
  583. public _processCollisionsForSubModels(collider: Collider, transformMatrix: Matrix): void {
  584. for (var index = 0; index < this.subMeshes.length; index++) {
  585. var subMesh = this.subMeshes[index];
  586. // Bounding test
  587. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  588. continue;
  589. this._collideForSubMesh(subMesh, transformMatrix, collider);
  590. }
  591. }
  592. public _checkCollision(collider: Collider): void {
  593. // Bounding box test
  594. if (!this._boundingInfo._checkCollision(collider))
  595. return;
  596. // Transformation matrix
  597. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  598. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  599. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  600. }
  601. public intersectsMesh(mesh: Mesh, precise?: boolean): boolean {
  602. if (!this._boundingInfo || !mesh._boundingInfo) {
  603. return false;
  604. }
  605. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  606. }
  607. public intersectsPoint(point: Vector3): boolean {
  608. if (!this._boundingInfo) {
  609. return false;
  610. }
  611. return this._boundingInfo.intersectsPoint(point);
  612. }
  613. // Picking
  614. public intersects(ray: Ray, fastCheck?: boolean): PickingInfo {
  615. var pickingInfo = new BABYLON.PickingInfo();
  616. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  617. return pickingInfo;
  618. }
  619. this._generatePointsArray();
  620. var intersectInfo: IntersectionInfo = null;
  621. for (var index = 0; index < this.subMeshes.length; index++) {
  622. var subMesh = this.subMeshes[index];
  623. // Bounding test
  624. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  625. continue;
  626. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this._indices, fastCheck);
  627. if (currentIntersectInfo) {
  628. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  629. intersectInfo = currentIntersectInfo;
  630. if (fastCheck) {
  631. break;
  632. }
  633. }
  634. }
  635. }
  636. if (intersectInfo) {
  637. // Get picked point
  638. var world = this.getWorldMatrix();
  639. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  640. var direction = ray.direction.clone();
  641. direction.normalize();
  642. direction = direction.scale(intersectInfo.distance);
  643. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  644. var pickedPoint = worldOrigin.add(worldDirection);
  645. // Return result
  646. pickingInfo.hit = true;
  647. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  648. pickingInfo.pickedPoint = pickedPoint;
  649. pickingInfo.pickedMesh = this;
  650. pickingInfo.bu = intersectInfo.bu;
  651. pickingInfo.bv = intersectInfo.bv;
  652. pickingInfo.faceId = intersectInfo.faceId;
  653. return pickingInfo;
  654. }
  655. return pickingInfo;
  656. }
  657. // Clone
  658. public clone(name: string, newParent: Node, doNotCloneChildren?: boolean): Mesh {
  659. var result = new BABYLON.Mesh(name, this.getScene());
  660. // Buffers
  661. result._vertexBuffers = this._vertexBuffers;
  662. for (var kind in result._vertexBuffers) {
  663. result._vertexBuffers[kind]._buffer.references++;
  664. }
  665. result._indexBuffer = this._indexBuffer;
  666. this._indexBuffer.references++;
  667. // Deep copy
  668. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], ["_indices", "_totalVertices"]);
  669. // Bounding info
  670. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this._totalVertices);
  671. result._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  672. // Material
  673. result.material = this.material;
  674. // Parent
  675. if (newParent) {
  676. result.parent = newParent;
  677. }
  678. if (!doNotCloneChildren) {
  679. // Children
  680. for (var index = 0; index < this.getScene().meshes.length; index++) {
  681. var mesh = this.getScene().meshes[index];
  682. if (mesh.parent == this) {
  683. mesh.clone(mesh.name, result);
  684. }
  685. }
  686. }
  687. // Particles
  688. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  689. var system = this.getScene().particleSystems[index];
  690. if (system.emitter == this) {
  691. system.clone(system.name, result);
  692. }
  693. }
  694. result.computeWorldMatrix(true);
  695. return result;
  696. }
  697. // Dispose
  698. public dispose(doNotRecurse?: boolean): void {
  699. if (this._vertexBuffers) {
  700. for (var vbKind in this._vertexBuffers) {
  701. this._vertexBuffers[vbKind].dispose();
  702. }
  703. this._vertexBuffers = null;
  704. }
  705. if (this._indexBuffer) {
  706. this.getScene().getEngine()._releaseBuffer(this._indexBuffer);
  707. this._indexBuffer = null;
  708. }
  709. // Physics
  710. if (this.getPhysicsImpostor() != PhysicsEngine.NoImpostor) {
  711. this.setPhysicsState(PhysicsEngine.NoImpostor);
  712. }
  713. // Remove from scene
  714. var index = this.getScene().meshes.indexOf(this);
  715. this.getScene().meshes.splice(index, 1);
  716. if (!doNotRecurse) {
  717. // Particles
  718. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  719. if (this.getScene().particleSystems[index].emitter == this) {
  720. this.getScene().particleSystems[index].dispose();
  721. index--;
  722. }
  723. }
  724. // Children
  725. var objects = this.getScene().meshes.slice(0);
  726. for (index = 0; index < objects.length; index++) {
  727. if (objects[index].parent == this) {
  728. objects[index].dispose();
  729. }
  730. }
  731. } else {
  732. for (index = 0; index < this.getScene().meshes.length; index++) {
  733. var obj = this.getScene().meshes[index];
  734. if (obj.parent === this) {
  735. obj.parent = null;
  736. obj.computeWorldMatrix(true);
  737. }
  738. }
  739. }
  740. this._isDisposed = true;
  741. // Callback
  742. if (this.onDispose) {
  743. this.onDispose();
  744. }
  745. }
  746. // Physics
  747. public setPhysicsState(impostor?: any, options?: PhysicsBodyCreationOptions): void {
  748. var physicsEngine = this.getScene().getPhysicsEngine();
  749. if (!physicsEngine) {
  750. return;
  751. }
  752. if (impostor.impostor) {
  753. // Old API
  754. options = impostor;
  755. impostor = impostor.impostor;
  756. }
  757. impostor = impostor || PhysicsEngine.NoImpostor;
  758. options.mass = options.mass || 0;
  759. options.friction = options.friction || 0.2;
  760. options.restitution = options.restitution || 0.9;
  761. this._physicImpostor = impostor;
  762. this._physicsMass = options.mass;
  763. this._physicsFriction = options.friction;
  764. this._physicRestitution = options.restitution;
  765. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  766. physicsEngine._unregisterMesh(this);
  767. return;
  768. }
  769. physicsEngine._registerMesh(this, impostor, options);
  770. }
  771. public getPhysicsImpostor(): number {
  772. if (!this._physicImpostor) {
  773. return BABYLON.PhysicsEngine.NoImpostor;
  774. }
  775. return this._physicImpostor;
  776. }
  777. public getPhysicsMass(): number {
  778. if (!this._physicsMass) {
  779. return 0;
  780. }
  781. return this._physicsMass;
  782. }
  783. public getPhysicsFriction(): number {
  784. if (!this._physicsFriction) {
  785. return 0;
  786. }
  787. return this._physicsFriction;
  788. }
  789. public getPhysicsRestitution(): number {
  790. if (!this._physicRestitution) {
  791. return 0;
  792. }
  793. return this._physicRestitution;
  794. }
  795. public applyImpulse(force: Vector3, contactPoint: Vector3): void {
  796. if (!this._physicImpostor) {
  797. return;
  798. }
  799. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  800. }
  801. public setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3): void {
  802. if (!this._physicImpostor) {
  803. return;
  804. }
  805. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2);
  806. }
  807. // Geometric tools
  808. public convertToFlatShadedMesh(): void {
  809. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  810. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  811. var kinds = this.getVerticesDataKinds();
  812. var vbs = [];
  813. var data = [];
  814. var newdata = [];
  815. var updatableNormals = false;
  816. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  817. var kind = kinds[kindIndex];
  818. if (kind === BABYLON.VertexBuffer.NormalKind) {
  819. updatableNormals = this.getVertexBuffer(kind).isUpdatable();
  820. kinds.splice(kindIndex, 1);
  821. kindIndex--;
  822. continue;
  823. }
  824. vbs[kind] = this.getVertexBuffer(kind);
  825. data[kind] = vbs[kind].getData();
  826. newdata[kind] = [];
  827. }
  828. // Save previous submeshes
  829. var previousSubmeshes = this.subMeshes.slice(0);
  830. var indices = this.getIndices();
  831. // Generating unique vertices per face
  832. for (index = 0; index < indices.length; index++) {
  833. var vertexIndex = indices[index];
  834. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  835. kind = kinds[kindIndex];
  836. var stride = vbs[kind].getStrideSize();
  837. for (var offset = 0; offset < stride; offset++) {
  838. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  839. }
  840. }
  841. }
  842. // Updating faces & normal
  843. var normals = [];
  844. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  845. for (var index = 0; index < indices.length; index += 3) {
  846. indices[index] = index;
  847. indices[index + 1] = index + 1;
  848. indices[index + 2] = index + 2;
  849. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  850. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  851. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  852. var p1p2 = p1.subtract(p2);
  853. var p3p2 = p3.subtract(p2);
  854. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  855. // Store same normals for every vertex
  856. for (var localIndex = 0; localIndex < 3; localIndex++) {
  857. normals.push(normal.x);
  858. normals.push(normal.y);
  859. normals.push(normal.z);
  860. }
  861. }
  862. this.setIndices(indices);
  863. this.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatableNormals);
  864. // Updating vertex buffers
  865. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  866. kind = kinds[kindIndex];
  867. this.setVerticesData(newdata[kind], kind, vbs[kind].isUpdatable());
  868. }
  869. // Updating submeshes
  870. this.subMeshes = [];
  871. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  872. var previousOne = previousSubmeshes[submeshIndex];
  873. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  874. }
  875. }
  876. // Statics
  877. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  878. var box = new BABYLON.Mesh(name, scene);
  879. var vertexData = BABYLON.VertexData.CreateBox(size);
  880. vertexData.applyToMesh(box, updatable);
  881. return box;
  882. }
  883. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean): Mesh {
  884. var sphere = new BABYLON.Mesh(name, scene);
  885. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  886. vertexData.applyToMesh(sphere, updatable);
  887. return sphere;
  888. }
  889. // Cylinder and cone (Code inspired by SharpDX.org)
  890. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  891. var cylinder = new BABYLON.Mesh(name, scene);
  892. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation);
  893. vertexData.applyToMesh(cylinder, updatable);
  894. return cylinder;
  895. }
  896. // Torus (Code from SharpDX.org)
  897. public static CreateTorus(name: string, diameter, thickness: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  898. var torus = new BABYLON.Mesh(name, scene);
  899. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  900. vertexData.applyToMesh(torus, updatable);
  901. return torus;
  902. }
  903. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean): Mesh {
  904. var torusKnot = new BABYLON.Mesh(name, scene);
  905. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  906. vertexData.applyToMesh(torusKnot, updatable);
  907. return torusKnot;
  908. }
  909. // Plane & ground
  910. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  911. var plane = new BABYLON.Mesh(name, scene);
  912. var vertexData = BABYLON.VertexData.CreatePlane(size);
  913. vertexData.applyToMesh(plane, updatable);
  914. return plane;
  915. }
  916. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  917. var ground = new BABYLON.Mesh(name, scene);
  918. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  919. vertexData.applyToMesh(ground, updatable);
  920. return ground;
  921. }
  922. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean): Mesh {
  923. var ground = new BABYLON.Mesh(name, scene);
  924. var onload = img => {
  925. // Getting height map data
  926. var canvas = document.createElement("canvas");
  927. var context = canvas.getContext("2d");
  928. var heightMapWidth = img.width;
  929. var heightMapHeight = img.height;
  930. canvas.width = heightMapWidth;
  931. canvas.height = heightMapHeight;
  932. context.drawImage(img, 0, 0);
  933. // Create VertexData from map data
  934. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  935. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  936. vertexData.applyToMesh(ground, updatable);
  937. ground._isReady = true;
  938. };
  939. Tools.LoadImage(url, onload, () => {}, scene.database);
  940. ground._isReady = false;
  941. return ground;
  942. }
  943. // Tools
  944. public static MinMax(meshes: Mesh[]): {min: Vector3; max: Vector3} {
  945. var minVector = null;
  946. var maxVector = null;
  947. for (var i in meshes) {
  948. var mesh = meshes[i];
  949. var boundingBox = mesh.getBoundingInfo().boundingBox;
  950. if (!minVector) {
  951. minVector = boundingBox.minimumWorld;
  952. maxVector = boundingBox.maximumWorld;
  953. continue;
  954. }
  955. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  956. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  957. }
  958. return {
  959. min: minVector,
  960. max: maxVector
  961. };
  962. }
  963. public static Center(meshesOrMinMaxVector): Vector3 {
  964. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  965. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  966. }
  967. }
  968. }