babylon.mesh.js 47 KB

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