babylon.mesh.js 47 KB

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