babylon.abstractMesh.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. var __extends = (this && this.__extends) || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5. };
  6. var BABYLON;
  7. (function (BABYLON) {
  8. var AbstractMesh = (function (_super) {
  9. __extends(AbstractMesh, _super);
  10. // Constructor
  11. function AbstractMesh(name, scene) {
  12. var _this = this;
  13. _super.call(this, name, scene);
  14. // Properties
  15. this.definedFacingForward = true; // orientation for POV movement & rotation
  16. this.position = new BABYLON.Vector3(0, 0, 0);
  17. this._rotation = new BABYLON.Vector3(0, 0, 0);
  18. this._scaling = new BABYLON.Vector3(1, 1, 1);
  19. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  20. this.visibility = 1.0;
  21. this.alphaIndex = Number.MAX_VALUE;
  22. this.infiniteDistance = false;
  23. this.isVisible = true;
  24. this.isPickable = true;
  25. this.showBoundingBox = false;
  26. this.showSubMeshesBoundingBox = false;
  27. this.onDispose = null;
  28. this.isBlocker = false;
  29. this.renderingGroupId = 0;
  30. this.receiveShadows = false;
  31. this.renderOutline = false;
  32. this.outlineColor = BABYLON.Color3.Red();
  33. this.outlineWidth = 0.02;
  34. this.renderOverlay = false;
  35. this.overlayColor = BABYLON.Color3.Red();
  36. this.overlayAlpha = 0.5;
  37. this.hasVertexAlpha = false;
  38. this.useVertexColors = true;
  39. this.applyFog = true;
  40. this.computeBonesUsingShaders = true;
  41. this.scalingDeterminant = 1;
  42. this.numBoneInfluencers = 4;
  43. this.useOctreeForRenderingSelection = true;
  44. this.useOctreeForPicking = true;
  45. this.useOctreeForCollisions = true;
  46. this.layerMask = 0x0FFFFFFF;
  47. this.alwaysSelectAsActiveMesh = false;
  48. // Collisions
  49. this._checkCollisions = false;
  50. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  51. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  52. this._collider = new BABYLON.Collider();
  53. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  54. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  55. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  56. // Edges
  57. this.edgesWidth = 1;
  58. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  59. // Cache
  60. this._localWorld = BABYLON.Matrix.Zero();
  61. this._worldMatrix = BABYLON.Matrix.Zero();
  62. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  63. this._absolutePosition = BABYLON.Vector3.Zero();
  64. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  65. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  66. this._isDirty = false;
  67. this._pivotMatrix = BABYLON.Matrix.Identity();
  68. this._isDisposed = false;
  69. this._renderId = 0;
  70. this._intersectionsInProgress = new Array();
  71. this._onAfterWorldMatrixUpdate = new Array();
  72. this._isWorldMatrixFrozen = false;
  73. this._unIndexed = false;
  74. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  75. if (collidedMesh === void 0) { collidedMesh = null; }
  76. //TODO move this to the collision coordinator!
  77. if (_this.getScene().workerCollisions)
  78. newPosition.multiplyInPlace(_this._collider.radius);
  79. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  80. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  81. _this.position.addInPlace(_this._diffPositionForCollisions);
  82. }
  83. if (_this.onCollide && collidedMesh) {
  84. _this.onCollide(collidedMesh);
  85. }
  86. if (_this.onCollisionPositionChange) {
  87. _this.onCollisionPositionChange(_this.position);
  88. }
  89. };
  90. scene.addMesh(this);
  91. }
  92. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  93. get: function () {
  94. return AbstractMesh._BILLBOARDMODE_NONE;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  100. get: function () {
  101. return AbstractMesh._BILLBOARDMODE_X;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  107. get: function () {
  108. return AbstractMesh._BILLBOARDMODE_Y;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  114. get: function () {
  115. return AbstractMesh._BILLBOARDMODE_Z;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  121. get: function () {
  122. return AbstractMesh._BILLBOARDMODE_ALL;
  123. },
  124. enumerable: true,
  125. configurable: true
  126. });
  127. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  128. get: function () {
  129. return this._skeleton;
  130. },
  131. set: function (value) {
  132. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  133. this._skeleton._unregisterMeshWithPoseMatrix(this);
  134. }
  135. if (value && value.needInitialSkinMatrix) {
  136. value._registerMeshWithPoseMatrix(this);
  137. }
  138. this._skeleton = value;
  139. if (!this._skeleton) {
  140. this._bonesTransformMatrices = null;
  141. }
  142. },
  143. enumerable: true,
  144. configurable: true
  145. });
  146. /**
  147. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  148. */
  149. AbstractMesh.prototype.toString = function (fullDetails) {
  150. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  151. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  152. if (this._skeleton) {
  153. ret += ", skeleton: " + this._skeleton.name;
  154. }
  155. if (fullDetails) {
  156. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  157. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  158. }
  159. return ret;
  160. };
  161. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  162. /**
  163. * Getting the rotation object.
  164. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  165. */
  166. get: function () {
  167. return this._rotation;
  168. },
  169. set: function (newRotation) {
  170. this._rotation = newRotation;
  171. },
  172. enumerable: true,
  173. configurable: true
  174. });
  175. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  176. get: function () {
  177. return this._scaling;
  178. },
  179. set: function (newScaling) {
  180. this._scaling = newScaling;
  181. if (this.physicsImpostor) {
  182. this.physicsImpostor.forceUpdate();
  183. }
  184. },
  185. enumerable: true,
  186. configurable: true
  187. });
  188. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  189. get: function () {
  190. return this._rotationQuaternion;
  191. },
  192. set: function (quaternion) {
  193. this._rotationQuaternion = quaternion;
  194. //reset the rotation vector.
  195. if (quaternion && this.rotation.length()) {
  196. this.rotation.copyFromFloats(0, 0, 0);
  197. }
  198. },
  199. enumerable: true,
  200. configurable: true
  201. });
  202. // Methods
  203. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  204. this._poseMatrix.copyFrom(matrix);
  205. };
  206. AbstractMesh.prototype.getPoseMatrix = function () {
  207. return this._poseMatrix;
  208. };
  209. AbstractMesh.prototype.disableEdgesRendering = function () {
  210. if (this._edgesRenderer !== undefined) {
  211. this._edgesRenderer.dispose();
  212. this._edgesRenderer = undefined;
  213. }
  214. };
  215. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  216. if (epsilon === void 0) { epsilon = 0.95; }
  217. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  218. this.disableEdgesRendering();
  219. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  220. };
  221. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  222. get: function () {
  223. return false;
  224. },
  225. enumerable: true,
  226. configurable: true
  227. });
  228. AbstractMesh.prototype.getLOD = function (camera) {
  229. return this;
  230. };
  231. AbstractMesh.prototype.getTotalVertices = function () {
  232. return 0;
  233. };
  234. AbstractMesh.prototype.getIndices = function () {
  235. return null;
  236. };
  237. AbstractMesh.prototype.getVerticesData = function (kind) {
  238. return null;
  239. };
  240. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  241. return false;
  242. };
  243. AbstractMesh.prototype.getBoundingInfo = function () {
  244. if (this._masterMesh) {
  245. return this._masterMesh.getBoundingInfo();
  246. }
  247. if (!this._boundingInfo) {
  248. this._updateBoundingInfo();
  249. }
  250. return this._boundingInfo;
  251. };
  252. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  253. get: function () {
  254. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  255. },
  256. enumerable: true,
  257. configurable: true
  258. });
  259. AbstractMesh.prototype._preActivate = function () {
  260. };
  261. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  262. };
  263. AbstractMesh.prototype._activate = function (renderId) {
  264. this._renderId = renderId;
  265. };
  266. AbstractMesh.prototype.getWorldMatrix = function () {
  267. if (this._masterMesh) {
  268. return this._masterMesh.getWorldMatrix();
  269. }
  270. if (this._currentRenderId !== this.getScene().getRenderId()) {
  271. this.computeWorldMatrix();
  272. }
  273. return this._worldMatrix;
  274. };
  275. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  276. get: function () {
  277. return this._worldMatrix;
  278. },
  279. enumerable: true,
  280. configurable: true
  281. });
  282. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  283. get: function () {
  284. return this._absolutePosition;
  285. },
  286. enumerable: true,
  287. configurable: true
  288. });
  289. AbstractMesh.prototype.freezeWorldMatrix = function () {
  290. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  291. this.computeWorldMatrix(true);
  292. this._isWorldMatrixFrozen = true;
  293. };
  294. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  295. this._isWorldMatrixFrozen = false;
  296. this.computeWorldMatrix(true);
  297. };
  298. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  299. get: function () {
  300. return this._isWorldMatrixFrozen;
  301. },
  302. enumerable: true,
  303. configurable: true
  304. });
  305. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  306. axis.normalize();
  307. if (!this.rotationQuaternion) {
  308. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  309. this.rotation = BABYLON.Vector3.Zero();
  310. }
  311. var rotationQuaternion;
  312. if (!space || space === BABYLON.Space.LOCAL) {
  313. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  314. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  315. }
  316. else {
  317. if (this.parent) {
  318. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  319. invertParentWorldMatrix.invert();
  320. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  321. }
  322. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  323. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  324. }
  325. };
  326. AbstractMesh.prototype.translate = function (axis, distance, space) {
  327. var displacementVector = axis.scale(distance);
  328. if (!space || space === BABYLON.Space.LOCAL) {
  329. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  330. this.setPositionWithLocalVector(tempV3);
  331. }
  332. else {
  333. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  334. }
  335. };
  336. AbstractMesh.prototype.getAbsolutePosition = function () {
  337. this.computeWorldMatrix();
  338. return this._absolutePosition;
  339. };
  340. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  341. if (!absolutePosition) {
  342. return;
  343. }
  344. var absolutePositionX;
  345. var absolutePositionY;
  346. var absolutePositionZ;
  347. if (absolutePosition.x === undefined) {
  348. if (arguments.length < 3) {
  349. return;
  350. }
  351. absolutePositionX = arguments[0];
  352. absolutePositionY = arguments[1];
  353. absolutePositionZ = arguments[2];
  354. }
  355. else {
  356. absolutePositionX = absolutePosition.x;
  357. absolutePositionY = absolutePosition.y;
  358. absolutePositionZ = absolutePosition.z;
  359. }
  360. if (this.parent) {
  361. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  362. invertParentWorldMatrix.invert();
  363. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  364. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  365. }
  366. else {
  367. this.position.x = absolutePositionX;
  368. this.position.y = absolutePositionY;
  369. this.position.z = absolutePositionZ;
  370. }
  371. };
  372. // ================================== Point of View Movement =================================
  373. /**
  374. * Perform relative position change from the point of view of behind the front of the mesh.
  375. * This is performed taking into account the meshes current rotation, so you do not have to care.
  376. * Supports definition of mesh facing forward or backward.
  377. * @param {number} amountRight
  378. * @param {number} amountUp
  379. * @param {number} amountForward
  380. */
  381. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  382. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  383. };
  384. /**
  385. * Calculate relative position change from the point of view of behind the front of the mesh.
  386. * This is performed taking into account the meshes current rotation, so you do not have to care.
  387. * Supports definition of mesh facing forward or backward.
  388. * @param {number} amountRight
  389. * @param {number} amountUp
  390. * @param {number} amountForward
  391. */
  392. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  393. var rotMatrix = new BABYLON.Matrix();
  394. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  395. rotQuaternion.toRotationMatrix(rotMatrix);
  396. var translationDelta = BABYLON.Vector3.Zero();
  397. var defForwardMult = this.definedFacingForward ? -1 : 1;
  398. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  399. return translationDelta;
  400. };
  401. // ================================== Point of View Rotation =================================
  402. /**
  403. * Perform relative rotation change from the point of view of behind the front of the mesh.
  404. * Supports definition of mesh facing forward or backward.
  405. * @param {number} flipBack
  406. * @param {number} twirlClockwise
  407. * @param {number} tiltRight
  408. */
  409. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  410. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  411. };
  412. /**
  413. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  414. * Supports definition of mesh facing forward or backward.
  415. * @param {number} flipBack
  416. * @param {number} twirlClockwise
  417. * @param {number} tiltRight
  418. */
  419. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  420. var defForwardMult = this.definedFacingForward ? 1 : -1;
  421. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  422. };
  423. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  424. this._pivotMatrix = matrix;
  425. this._cache.pivotMatrixUpdated = true;
  426. };
  427. AbstractMesh.prototype.getPivotMatrix = function () {
  428. return this._pivotMatrix;
  429. };
  430. AbstractMesh.prototype._isSynchronized = function () {
  431. if (this._isDirty) {
  432. return false;
  433. }
  434. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  435. return false;
  436. if (this._cache.pivotMatrixUpdated) {
  437. return false;
  438. }
  439. if (this.infiniteDistance) {
  440. return false;
  441. }
  442. if (!this._cache.position.equals(this.position))
  443. return false;
  444. if (this.rotationQuaternion) {
  445. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  446. return false;
  447. }
  448. else {
  449. if (!this._cache.rotation.equals(this.rotation))
  450. return false;
  451. }
  452. if (!this._cache.scaling.equals(this.scaling))
  453. return false;
  454. return true;
  455. };
  456. AbstractMesh.prototype._initCache = function () {
  457. _super.prototype._initCache.call(this);
  458. this._cache.localMatrixUpdated = false;
  459. this._cache.position = BABYLON.Vector3.Zero();
  460. this._cache.scaling = BABYLON.Vector3.Zero();
  461. this._cache.rotation = BABYLON.Vector3.Zero();
  462. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  463. this._cache.billboardMode = -1;
  464. };
  465. AbstractMesh.prototype.markAsDirty = function (property) {
  466. if (property === "rotation") {
  467. this.rotationQuaternion = null;
  468. }
  469. this._currentRenderId = Number.MAX_VALUE;
  470. this._isDirty = true;
  471. };
  472. AbstractMesh.prototype._updateBoundingInfo = function () {
  473. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  474. this._boundingInfo.update(this.worldMatrixFromCache);
  475. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  476. };
  477. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  478. if (!this.subMeshes) {
  479. return;
  480. }
  481. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  482. var subMesh = this.subMeshes[subIndex];
  483. if (!subMesh.IsGlobal) {
  484. subMesh.updateBoundingInfo(matrix);
  485. }
  486. }
  487. };
  488. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  489. if (this._isWorldMatrixFrozen) {
  490. return this._worldMatrix;
  491. }
  492. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  493. this._currentRenderId = this.getScene().getRenderId();
  494. return this._worldMatrix;
  495. }
  496. this._cache.position.copyFrom(this.position);
  497. this._cache.scaling.copyFrom(this.scaling);
  498. this._cache.pivotMatrixUpdated = false;
  499. this._cache.billboardMode = this.billboardMode;
  500. this._currentRenderId = this.getScene().getRenderId();
  501. this._isDirty = false;
  502. // Scaling
  503. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  504. // Rotation
  505. //rotate, if quaternion is set and rotation was used
  506. if (this.rotationQuaternion) {
  507. var len = this.rotation.length();
  508. if (len) {
  509. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  510. this.rotation.copyFromFloats(0, 0, 0);
  511. }
  512. }
  513. if (this.rotationQuaternion) {
  514. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  515. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  516. }
  517. else {
  518. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  519. this._cache.rotation.copyFrom(this.rotation);
  520. }
  521. // Translation
  522. if (this.infiniteDistance && !this.parent) {
  523. var camera = this.getScene().activeCamera;
  524. if (camera) {
  525. var cameraWorldMatrix = camera.getWorldMatrix();
  526. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  527. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  528. }
  529. }
  530. else {
  531. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  532. }
  533. // Composing transformations
  534. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  535. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  536. // Billboarding
  537. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  538. var localPosition = this.position.clone();
  539. var zero = this.getScene().activeCamera.globalPosition.clone();
  540. if (this.parent && this.parent.position) {
  541. localPosition.addInPlace(this.parent.position);
  542. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  543. }
  544. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  545. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  546. zero.x = localPosition.x + BABYLON.Epsilon;
  547. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  548. zero.y = localPosition.y + BABYLON.Epsilon;
  549. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  550. zero.z = localPosition.z + BABYLON.Epsilon;
  551. }
  552. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  553. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  554. BABYLON.Tmp.Matrix[3].invert();
  555. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  556. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  557. }
  558. // Local world
  559. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  560. // Parent
  561. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  562. this._markSyncedWithParent();
  563. if (this._meshToBoneReferal) {
  564. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  565. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  566. }
  567. else {
  568. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  569. }
  570. }
  571. else {
  572. this._worldMatrix.copyFrom(this._localWorld);
  573. }
  574. // Bounding info
  575. this._updateBoundingInfo();
  576. // Absolute position
  577. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  578. // Callbacks
  579. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  580. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  581. }
  582. if (!this._poseMatrix) {
  583. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  584. }
  585. return this._worldMatrix;
  586. };
  587. /**
  588. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  589. * @param func: callback function to add
  590. */
  591. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  592. this._onAfterWorldMatrixUpdate.push(func);
  593. };
  594. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  595. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  596. if (index > -1) {
  597. this._onAfterWorldMatrixUpdate.splice(index, 1);
  598. }
  599. };
  600. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  601. this.computeWorldMatrix();
  602. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  603. };
  604. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  605. this.computeWorldMatrix();
  606. var invLocalWorldMatrix = this._localWorld.clone();
  607. invLocalWorldMatrix.invert();
  608. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  609. };
  610. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  611. this.computeWorldMatrix(true);
  612. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  613. };
  614. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  615. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  616. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  617. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  618. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  619. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  620. /// <returns>Mesh oriented towards targetMesh</returns>
  621. yawCor = yawCor || 0; // default to zero if undefined
  622. pitchCor = pitchCor || 0;
  623. rollCor = rollCor || 0;
  624. var dv = targetPoint.subtract(this.position);
  625. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  626. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  627. var pitch = Math.atan2(dv.y, len);
  628. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  629. };
  630. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  631. this._meshToBoneReferal = affectedMesh;
  632. this.parent = bone;
  633. if (bone.getWorldMatrix().determinant() < 0) {
  634. this.scalingDeterminant *= -1;
  635. }
  636. };
  637. AbstractMesh.prototype.detachFromBone = function () {
  638. if (this.parent.getWorldMatrix().determinant() < 0) {
  639. this.scalingDeterminant *= -1;
  640. }
  641. this._meshToBoneReferal = null;
  642. this.parent = null;
  643. };
  644. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  645. return this._boundingInfo.isInFrustum(frustumPlanes);
  646. };
  647. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  648. if (!camera) {
  649. camera = this.getScene().activeCamera;
  650. }
  651. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  652. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  653. return false;
  654. }
  655. return true;
  656. };
  657. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  658. if (!this._boundingInfo || !mesh._boundingInfo) {
  659. return false;
  660. }
  661. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  662. };
  663. AbstractMesh.prototype.intersectsPoint = function (point) {
  664. if (!this._boundingInfo) {
  665. return false;
  666. }
  667. return this._boundingInfo.intersectsPoint(point);
  668. };
  669. // Physics
  670. /**
  671. * @Deprecated. Use new PhysicsImpostor instead.
  672. * */
  673. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  674. //legacy support
  675. if (impostor.impostor) {
  676. options = impostor;
  677. impostor = impostor.impostor;
  678. }
  679. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  680. return this.physicsImpostor.physicsBody;
  681. };
  682. AbstractMesh.prototype.getPhysicsImpostor = function () {
  683. return this.physicsImpostor;
  684. };
  685. /**
  686. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  687. */
  688. AbstractMesh.prototype.getPhysicsMass = function () {
  689. return this.physicsImpostor.getParam("mass");
  690. };
  691. /**
  692. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  693. */
  694. AbstractMesh.prototype.getPhysicsFriction = function () {
  695. return this.physicsImpostor.getParam("friction");
  696. };
  697. /**
  698. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  699. */
  700. AbstractMesh.prototype.getPhysicsRestitution = function () {
  701. return this.physicsImpostor.getParam("resitution");
  702. };
  703. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  704. if (!camera) {
  705. camera = this.getScene().activeCamera;
  706. }
  707. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  708. };
  709. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  710. if (!camera) {
  711. camera = this.getScene().activeCamera;
  712. }
  713. return this.absolutePosition.subtract(camera.position).length();
  714. };
  715. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  716. if (!this.physicsImpostor) {
  717. return;
  718. }
  719. this.physicsImpostor.applyImpulse(force, contactPoint);
  720. };
  721. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  722. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  723. return;
  724. }
  725. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  726. mainPivot: pivot1,
  727. connectedPivot: pivot2,
  728. nativeParams: options
  729. });
  730. };
  731. /**
  732. * @Deprecated
  733. */
  734. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  735. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  736. this.updatePhysicsBody();
  737. };
  738. /**
  739. * @Deprecated
  740. * Calling this function is not needed anymore.
  741. * The physics engine takes care of transofmration automatically.
  742. */
  743. AbstractMesh.prototype.updatePhysicsBody = function () {
  744. //Unneeded
  745. };
  746. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  747. // Collisions
  748. get: function () {
  749. return this._checkCollisions;
  750. },
  751. set: function (collisionEnabled) {
  752. this._checkCollisions = collisionEnabled;
  753. if (this.getScene().workerCollisions) {
  754. this.getScene().collisionCoordinator.onMeshUpdated(this);
  755. }
  756. },
  757. enumerable: true,
  758. configurable: true
  759. });
  760. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  761. var globalPosition = this.getAbsolutePosition();
  762. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  763. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  764. this._collider.radius = this.ellipsoid;
  765. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  766. };
  767. // Submeshes octree
  768. /**
  769. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  770. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  771. */
  772. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  773. if (maxCapacity === void 0) { maxCapacity = 64; }
  774. if (maxDepth === void 0) { maxDepth = 2; }
  775. if (!this._submeshesOctree) {
  776. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  777. }
  778. this.computeWorldMatrix(true);
  779. // Update octree
  780. var bbox = this.getBoundingInfo().boundingBox;
  781. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  782. return this._submeshesOctree;
  783. };
  784. // Collisions
  785. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  786. this._generatePointsArray();
  787. // Transformation
  788. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  789. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  790. subMesh._lastColliderWorldVertices = [];
  791. subMesh._trianglePlanes = [];
  792. var start = subMesh.verticesStart;
  793. var end = (subMesh.verticesStart + subMesh.verticesCount);
  794. for (var i = start; i < end; i++) {
  795. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  796. }
  797. }
  798. // Collide
  799. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  800. if (collider.collisionFound) {
  801. collider.collidedMesh = this;
  802. }
  803. };
  804. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  805. var subMeshes;
  806. var len;
  807. // Octrees
  808. if (this._submeshesOctree && this.useOctreeForCollisions) {
  809. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  810. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  811. len = intersections.length;
  812. subMeshes = intersections.data;
  813. }
  814. else {
  815. subMeshes = this.subMeshes;
  816. len = subMeshes.length;
  817. }
  818. for (var index = 0; index < len; index++) {
  819. var subMesh = subMeshes[index];
  820. // Bounding test
  821. if (len > 1 && !subMesh._checkCollision(collider))
  822. continue;
  823. this._collideForSubMesh(subMesh, transformMatrix, collider);
  824. }
  825. };
  826. AbstractMesh.prototype._checkCollision = function (collider) {
  827. // Bounding box test
  828. if (!this._boundingInfo._checkCollision(collider))
  829. return;
  830. // Transformation matrix
  831. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  832. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  833. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  834. };
  835. // Picking
  836. AbstractMesh.prototype._generatePointsArray = function () {
  837. return false;
  838. };
  839. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  840. var pickingInfo = new BABYLON.PickingInfo();
  841. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  842. return pickingInfo;
  843. }
  844. if (!this._generatePointsArray()) {
  845. return pickingInfo;
  846. }
  847. var intersectInfo = null;
  848. // Octrees
  849. var subMeshes;
  850. var len;
  851. if (this._submeshesOctree && this.useOctreeForPicking) {
  852. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  853. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  854. len = intersections.length;
  855. subMeshes = intersections.data;
  856. }
  857. else {
  858. subMeshes = this.subMeshes;
  859. len = subMeshes.length;
  860. }
  861. for (var index = 0; index < len; index++) {
  862. var subMesh = subMeshes[index];
  863. // Bounding test
  864. if (len > 1 && !subMesh.canIntersects(ray))
  865. continue;
  866. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  867. if (currentIntersectInfo) {
  868. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  869. intersectInfo = currentIntersectInfo;
  870. intersectInfo.subMeshId = index;
  871. if (fastCheck) {
  872. break;
  873. }
  874. }
  875. }
  876. }
  877. if (intersectInfo) {
  878. // Get picked point
  879. var world = this.getWorldMatrix();
  880. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  881. var direction = ray.direction.clone();
  882. direction = direction.scale(intersectInfo.distance);
  883. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  884. var pickedPoint = worldOrigin.add(worldDirection);
  885. // Return result
  886. pickingInfo.hit = true;
  887. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  888. pickingInfo.pickedPoint = pickedPoint;
  889. pickingInfo.pickedMesh = this;
  890. pickingInfo.bu = intersectInfo.bu;
  891. pickingInfo.bv = intersectInfo.bv;
  892. pickingInfo.faceId = intersectInfo.faceId;
  893. pickingInfo.subMeshId = intersectInfo.subMeshId;
  894. return pickingInfo;
  895. }
  896. return pickingInfo;
  897. };
  898. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  899. return null;
  900. };
  901. AbstractMesh.prototype.releaseSubMeshes = function () {
  902. if (this.subMeshes) {
  903. while (this.subMeshes.length) {
  904. this.subMeshes[0].dispose();
  905. }
  906. }
  907. else {
  908. this.subMeshes = new Array();
  909. }
  910. };
  911. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  912. var _this = this;
  913. var index;
  914. // Action manager
  915. if (this.actionManager) {
  916. this.actionManager.dispose();
  917. this.actionManager = null;
  918. }
  919. // Skeleton
  920. this.skeleton = null;
  921. // Animations
  922. this.getScene().stopAnimation(this);
  923. // Physics
  924. if (this.physicsImpostor) {
  925. this.physicsImpostor.dispose();
  926. }
  927. // Intersections in progress
  928. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  929. var other = this._intersectionsInProgress[index];
  930. var pos = other._intersectionsInProgress.indexOf(this);
  931. other._intersectionsInProgress.splice(pos, 1);
  932. }
  933. this._intersectionsInProgress = [];
  934. // Lights
  935. var lights = this.getScene().lights;
  936. lights.forEach(function (light) {
  937. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  938. if (meshIndex !== -1) {
  939. light.includedOnlyMeshes.splice(meshIndex, 1);
  940. }
  941. meshIndex = light.excludedMeshes.indexOf(_this);
  942. if (meshIndex !== -1) {
  943. light.excludedMeshes.splice(meshIndex, 1);
  944. }
  945. });
  946. // Edges
  947. if (this._edgesRenderer) {
  948. this._edgesRenderer.dispose();
  949. this._edgesRenderer = null;
  950. }
  951. // SubMeshes
  952. this.releaseSubMeshes();
  953. // Remove from scene
  954. this.getScene().removeMesh(this);
  955. if (!doNotRecurse) {
  956. // Particles
  957. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  958. if (this.getScene().particleSystems[index].emitter === this) {
  959. this.getScene().particleSystems[index].dispose();
  960. index--;
  961. }
  962. }
  963. // Children
  964. var objects = this.getDescendants(true);
  965. for (index = 0; index < objects.length; index++) {
  966. objects[index].dispose();
  967. }
  968. }
  969. else {
  970. var childMeshes = this.getChildMeshes(true);
  971. for (index = 0; childMeshes.length; index++) {
  972. var child = childMeshes[index];
  973. child.parent = null;
  974. child.computeWorldMatrix(true);
  975. }
  976. }
  977. _super.prototype.dispose.call(this);
  978. this._onAfterWorldMatrixUpdate = [];
  979. this._isDisposed = true;
  980. // Callback
  981. if (this.onDispose) {
  982. this.onDispose();
  983. }
  984. };
  985. // Statics
  986. AbstractMesh._BILLBOARDMODE_NONE = 0;
  987. AbstractMesh._BILLBOARDMODE_X = 1;
  988. AbstractMesh._BILLBOARDMODE_Y = 2;
  989. AbstractMesh._BILLBOARDMODE_Z = 4;
  990. AbstractMesh._BILLBOARDMODE_ALL = 7;
  991. return AbstractMesh;
  992. })(BABYLON.Node);
  993. BABYLON.AbstractMesh = AbstractMesh;
  994. })(BABYLON || (BABYLON = {}));