babylon.mesh.js 46 KB

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