babylon.mesh.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. var BABYLON = BABYLON || {};
  2. (function () {
  3. BABYLON.Mesh = function (name, scene) {
  4. this.name = name;
  5. this.id = name;
  6. this._scene = scene;
  7. this._totalVertices = 0;
  8. this._worldMatrix = BABYLON.Matrix.Identity();
  9. scene.meshes.push(this);
  10. this.position = new BABYLON.Vector3(0, 0, 0);
  11. this.rotation = new BABYLON.Vector3(0, 0, 0);
  12. this.scaling = new BABYLON.Vector3(1, 1, 1);
  13. this._vertices = [];
  14. this._indices = [];
  15. this.subMeshes = [];
  16. this._renderId = 0;
  17. // Animations
  18. this.animations = [];
  19. // Cache
  20. this._positions = null;
  21. this._cache = {
  22. position: BABYLON.Vector3.Zero(),
  23. scaling: BABYLON.Vector3.Zero(),
  24. rotation: BABYLON.Vector3.Zero()
  25. };
  26. this._childrenFlag = false;
  27. this._localScaling = BABYLON.Matrix.Zero();
  28. this._localRotation = BABYLON.Matrix.Zero();
  29. this._localTranslation = BABYLON.Matrix.Zero();
  30. this._localBillboard = BABYLON.Matrix.Zero();
  31. this._localScalingRotation = BABYLON.Matrix.Zero();
  32. this._localWorld = BABYLON.Matrix.Zero();
  33. this._worldMatrix = BABYLON.Matrix.Zero();
  34. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  35. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  36. };
  37. // Constants
  38. BABYLON.Mesh.BILLBOARDMODE_NONE = 0;
  39. BABYLON.Mesh.BILLBOARDMODE_X = 1;
  40. BABYLON.Mesh.BILLBOARDMODE_Y = 2;
  41. BABYLON.Mesh.BILLBOARDMODE_Z = 4;
  42. BABYLON.Mesh.BILLBOARDMODE_ALL = 7;
  43. // Members
  44. BABYLON.Mesh.prototype.material = null;
  45. BABYLON.Mesh.prototype.parent = null;
  46. BABYLON.Mesh.prototype._isReady = true;
  47. BABYLON.Mesh.prototype._isEnabled = true;
  48. BABYLON.Mesh.prototype.isVisible = true;
  49. BABYLON.Mesh.prototype.isPickable = true;
  50. BABYLON.Mesh.prototype.visibility = 1.0;
  51. BABYLON.Mesh.prototype.billboardMode = BABYLON.Mesh.BILLBOARDMODE_NONE;
  52. BABYLON.Mesh.prototype.checkCollisions = false;
  53. BABYLON.Mesh.prototype.receiveShadows = false;
  54. BABYLON.Mesh.prototype._isDisposed = false;
  55. BABYLON.Mesh.prototype.onDispose = null;
  56. // Properties
  57. BABYLON.Mesh.prototype.getBoundingInfo = function () {
  58. return this._boundingInfo;
  59. };
  60. BABYLON.Mesh.prototype.getScene = function () {
  61. return this._scene;
  62. };
  63. BABYLON.Mesh.prototype.getWorldMatrix = function () {
  64. return this._worldMatrix;
  65. };
  66. BABYLON.Mesh.prototype.getTotalVertices = function () {
  67. return this._totalVertices;
  68. };
  69. BABYLON.Mesh.prototype.getVerticesData = function (kind) {
  70. return this._vertexBuffers[kind].getData();
  71. };
  72. BABYLON.Mesh.prototype.isVerticesDataPresent = function (kind) {
  73. return this._vertexBuffers[kind] !== undefined;
  74. };
  75. BABYLON.Mesh.prototype.getTotalIndices = function () {
  76. return this._indices.length;
  77. };
  78. BABYLON.Mesh.prototype.getIndices = function () {
  79. return this._indices;
  80. };
  81. BABYLON.Mesh.prototype.getVertexStrideSize = function () {
  82. return this._vertexStrideSize;
  83. };
  84. BABYLON.Mesh.prototype._needToSynchonizeChildren = function () {
  85. return this._childrenFlag;
  86. };
  87. BABYLON.Mesh.prototype.isSynchronized = function () {
  88. if (this.billboardMode !== BABYLON.Mesh.BILLBOARDMODE_NONE)
  89. return false;
  90. if (!this._cache.position || !this._cache.rotation || !this._cache.scaling) {
  91. return false;
  92. }
  93. if (!this._cache.position.equals(this.position))
  94. return false;
  95. if (!this._cache.rotation.equals(this.rotation))
  96. return false;
  97. if (!this._cache.scaling.equals(this.scaling))
  98. return false;
  99. if (this.parent)
  100. return !this.parent._needToSynchonizeChildren();
  101. return true;
  102. };
  103. BABYLON.Mesh.prototype.isReady = function () {
  104. return this._isReady;
  105. };
  106. BABYLON.Mesh.prototype.isEnabled = function () {
  107. if (!this.isReady() || !this._isEnabled) {
  108. return false;
  109. }
  110. if (this.parent) {
  111. return this.parent.isEnabled();
  112. }
  113. return true;
  114. };
  115. BABYLON.Mesh.prototype.setEnabled = function (value) {
  116. this._isEnabled = value;
  117. };
  118. BABYLON.Mesh.prototype.isAnimated = function () {
  119. return this._animationStarted;
  120. };
  121. BABYLON.Mesh.prototype.isDisposed = function () {
  122. return this._isDisposed;
  123. };
  124. // Methods
  125. BABYLON.Mesh.prototype.computeWorldMatrix = function () {
  126. if (this.isSynchronized()) {
  127. this._childrenFlag = false;
  128. return this._worldMatrix;
  129. }
  130. this._childrenFlag = true;
  131. this._cache.position.copyFrom(this.position);
  132. this._cache.rotation.copyFrom(this.rotation);
  133. this._cache.scaling.copyFrom(this.scaling);
  134. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  135. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  136. this._localScaling.multiplyToRef(this._localRotation, this._localScalingRotation);
  137. // Billboarding
  138. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  139. if (this.billboardMode !== BABYLON.Mesh.BILLBOARDMODE_NONE) {
  140. var localPosition = this.position.clone();
  141. var zero = this._scene.activeCamera.position.clone();
  142. if (this.parent) {
  143. localPosition.addInPlace(this.parent.position);
  144. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  145. }
  146. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_ALL === BABYLON.Mesh.BILLBOARDMODE_ALL) {
  147. zero = this._scene.activeCamera.position;
  148. } else {
  149. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
  150. zero.x = localPosition.x + BABYLON.Engine.epsilon;
  151. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
  152. zero.y = localPosition.y + BABYLON.Engine.epsilon;
  153. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
  154. zero.z = localPosition.z + BABYLON.Engine.epsilon;
  155. }
  156. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  157. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  158. this._localBillboard.invert();
  159. this._localScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  160. BABYLON.Matrix.RotationY(Math.PI).multiplyToRef(this._localWorld, this._localScalingRotation);
  161. }
  162. // Parent
  163. if (this.parent && this.billboardMode === BABYLON.Mesh.BILLBOARDMODE_NONE) {
  164. this._localScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  165. var parentWorld = this.parent.getWorldMatrix();
  166. this._localWorld.multiplyToRef(parentWorld, this._worldMatrix);
  167. } else {
  168. this._localScalingRotation.multiplyToRef(this._localTranslation, this._worldMatrix);
  169. }
  170. // Bounding info
  171. if (this._boundingInfo) {
  172. this._scaleFactor = Math.max(this.scaling.x, this.scaling.y);
  173. this._scaleFactor = Math.max(this._scaleFactor, this.scaling.z);
  174. if (this.parent)
  175. this._scaleFactor = this._scaleFactor * this.parent._scaleFactor;
  176. this._boundingInfo._update(this._worldMatrix, this._scaleFactor);
  177. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  178. var subMesh = this.subMeshes[subIndex];
  179. subMesh.updateBoundingInfo(this._worldMatrix, this._scaleFactor);
  180. }
  181. }
  182. return this._worldMatrix;
  183. };
  184. BABYLON.Mesh.prototype._createGlobalSubMesh = function () {
  185. if (!this._totalVertices || !this._indices) {
  186. return null;
  187. }
  188. this.subMeshes = [];
  189. return new BABYLON.SubMesh(0, 0, this._totalVertices, 0, this._indices.length, this);
  190. };
  191. BABYLON.Mesh.prototype.subdivide = function (count) {
  192. if (count < 1) {
  193. return;
  194. }
  195. var subdivisionSize = this._indices.length / count;
  196. var offset = 0;
  197. this.subMeshes = [];
  198. for (var index = 0; index < count; index++) {
  199. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, this._indices.length - offset), this);
  200. offset += subdivisionSize;
  201. }
  202. };
  203. BABYLON.Mesh.prototype.setVerticesData = function (data, kind, updatable) {
  204. if (!this._vertexBuffers) {
  205. this._vertexBuffers = {};
  206. }
  207. if (this._vertexBuffers[kind]) {
  208. this._vertexBuffers[kind].dispose();
  209. }
  210. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this, data, kind, updatable);
  211. if (kind === BABYLON.VertexBuffer.PositionKind) {
  212. var stride = this._vertexBuffers[kind].getStrideSize();
  213. this._totalVertices = data.length / stride;
  214. this._boundingInfo = new BABYLON.BoundingInfo(data, 0, this._totalVertices);
  215. this._createGlobalSubMesh();
  216. }
  217. };
  218. BABYLON.Mesh.prototype.updateVerticesData = function (kind, data) {
  219. if (this._vertexBuffers[kind]) {
  220. this._vertexBuffers[kind].update(data);
  221. }
  222. };
  223. BABYLON.Mesh.prototype.setIndices = function (indices) {
  224. if (this._indexBuffer) {
  225. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  226. }
  227. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  228. this._indices = indices;
  229. this._createGlobalSubMesh();
  230. };
  231. BABYLON.Mesh.prototype.bindAndDraw = function (subMesh, effect, wireframe) {
  232. var engine = this._scene.getEngine();
  233. // Wireframe
  234. var indexToBind = this._indexBuffer;
  235. var useTriangles = true;
  236. if (wireframe) {
  237. indexToBind = subMesh.getLinesIndexBuffer(this._indices, engine);
  238. useTriangles = false;
  239. }
  240. // VBOs
  241. engine.bindMultiBuffers(this._vertexBuffers, indexToBind, effect);
  242. // Draw order
  243. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  244. };
  245. BABYLON.Mesh.prototype.render = function (subMesh) {
  246. if (!this._vertexBuffers || !this._indexBuffer) {
  247. return;
  248. }
  249. // World
  250. var world = this.getWorldMatrix();
  251. // Material
  252. var effectiveMaterial = subMesh.getMaterial();
  253. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  254. return;
  255. }
  256. effectiveMaterial._preBind();
  257. effectiveMaterial.bind(world, this);
  258. // Bind and draw
  259. var engine = this._scene.getEngine();
  260. this.bindAndDraw(subMesh, effectiveMaterial.getEffect(), engine.forceWireframe || effectiveMaterial.wireframe);
  261. // Unbind
  262. effectiveMaterial.unbind();
  263. };
  264. BABYLON.Mesh.prototype.isDescendantOf = function (ancestor) {
  265. if (this.parent) {
  266. if (this.parent === ancestor) {
  267. return true;
  268. }
  269. return this.parent.isDescendantOf(ancestor);
  270. }
  271. return false;
  272. };
  273. BABYLON.Mesh.prototype.getDescendants = function () {
  274. var results = [];
  275. for (var index = 0; index < this._scene.meshes.length; index++) {
  276. var mesh = this._scene.meshes[index];
  277. if (mesh.isDescendantOf(this)) {
  278. results.push(mesh);
  279. }
  280. }
  281. return results;
  282. };
  283. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  284. var results = [];
  285. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  286. var particleSystem = this._scene.particleSystems[index];
  287. if (particleSystem.emitter === this) {
  288. results.push(particleSystem);
  289. }
  290. }
  291. return results;
  292. };
  293. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  294. var results = [];
  295. var descendants = this.getDescendants();
  296. descendants.push(this);
  297. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  298. var particleSystem = this._scene.particleSystems[index];
  299. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  300. results.push(particleSystem);
  301. }
  302. }
  303. return results;
  304. };
  305. BABYLON.Mesh.prototype.getChildren = function () {
  306. var results = [];
  307. for (var index = 0; index < this._scene.meshes.length; index++) {
  308. var mesh = this._scene.meshes[index];
  309. if (mesh.parent == this) {
  310. results.push(mesh);
  311. }
  312. }
  313. return results;
  314. };
  315. BABYLON.Mesh.prototype.isInFrustrum = function (frustumPlanes) {
  316. return this._boundingInfo.isInFrustrum(frustumPlanes);
  317. };
  318. BABYLON.Mesh.prototype.setMaterialByID = function (id) {
  319. var materials = this._scene.materials;
  320. for (var index = 0; index < materials.length; index++) {
  321. if (materials[index].id == id) {
  322. this.material = materials[index];
  323. return;
  324. }
  325. }
  326. // Multi
  327. var multiMaterials = this._scene.multiMaterials;
  328. for (var index = 0; index < multiMaterials.length; index++) {
  329. if (multiMaterials[index].id == id) {
  330. this.material = multiMaterials[index];
  331. return;
  332. }
  333. }
  334. };
  335. BABYLON.Mesh.prototype.getAnimatables = function () {
  336. var results = [];
  337. if (this.material) {
  338. results.push(this.material);
  339. }
  340. return results;
  341. };
  342. // Cache
  343. BABYLON.Mesh.prototype._resetPointsArrayCache = function () {
  344. this._positions = null;
  345. };
  346. BABYLON.Mesh.prototype._generatePointsArray = function () {
  347. if (this._positions)
  348. return;
  349. this._positions = [];
  350. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  351. for (var index = 0; index < data.length; index += 3) {
  352. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  353. }
  354. };
  355. // Collisions
  356. BABYLON.Mesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  357. this._generatePointsArray();
  358. // Transformation
  359. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  360. subMesh._lastColliderTransformMatrix = transformMatrix;
  361. subMesh._lastColliderWorldVertices = [];
  362. var start = subMesh.verticesStart;
  363. var end = (subMesh.verticesStart + subMesh.verticesCount);
  364. for (var i = start; i < end; i++) {
  365. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  366. }
  367. }
  368. // Collide
  369. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this._indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  370. };
  371. BABYLON.Mesh.prototype._processCollisionsForSubModels = function (collider, transformMatrix) {
  372. for (var index = 0; index < this.subMeshes.length; index++) {
  373. var subMesh = this.subMeshes[index];
  374. // Bounding test
  375. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  376. continue;
  377. this._collideForSubMesh(subMesh, transformMatrix, collider);
  378. }
  379. };
  380. BABYLON.Mesh.prototype._checkCollision = function (collider) {
  381. // Bounding box test
  382. if (!this._boundingInfo._checkCollision(collider))
  383. return;
  384. // Transformation matrix
  385. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  386. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  387. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  388. };
  389. BABYLON.Mesh.prototype.intersectsMesh = function (mesh, precise) {
  390. if (!this._boundingInfo || !mesh._boundingInfo) {
  391. return false;
  392. }
  393. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  394. };
  395. BABYLON.Mesh.prototype.intersectsPoint = function (point) {
  396. if (!this._boundingInfo) {
  397. return false;
  398. }
  399. return this._boundingInfo.intersectsPoint(point);
  400. };
  401. // Picking
  402. BABYLON.Mesh.prototype.intersects = function (ray) {
  403. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere)) {
  404. return { hit: false, distance: 0 };
  405. }
  406. this._generatePointsArray();
  407. var distance = Number.MAX_VALUE;
  408. for (var index = 0; index < this.subMeshes.length; index++) {
  409. var subMesh = this.subMeshes[index];
  410. // Bounding test
  411. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  412. continue;
  413. var result = subMesh.intersects(ray, this._positions, this._indices);
  414. if (result.hit) {
  415. if (result.distance < distance && result.distance >= 0) {
  416. distance = result.distance;
  417. }
  418. }
  419. }
  420. if (distance >= 0)
  421. return { hit: true, distance: distance };
  422. return { hit: false, distance: 0 };
  423. };
  424. // Clone
  425. BABYLON.Mesh.prototype.clone = function (name, newParent) {
  426. var result = new BABYLON.Mesh(name, this._scene);
  427. // Buffers
  428. result._vertexBuffers = this._vertexBuffers;
  429. this._vertexBuffers.references++;
  430. result._indexBuffer = this._indexBuffer;
  431. this._indexBuffer.references++;
  432. // Deep copy
  433. BABYLON.Tools.DeepCopy(this, result, ["name", "material"], ["_indices", "_totalVertices"]);
  434. // Bounding info
  435. result._boundingInfo = new BABYLON.BoundingInfo(this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData(), 0, this._totalVertices);
  436. // Material
  437. result.material = this.material;
  438. // Parent
  439. if (newParent) {
  440. result.parent = newParent;
  441. }
  442. // Children
  443. for (var index = 0; index < this._scene.meshes.length; index++) {
  444. var mesh = this._scene.meshes[index];
  445. if (mesh.parent == this) {
  446. mesh.clone(mesh.name, result);
  447. }
  448. }
  449. // Particles
  450. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  451. var system = this._scene.particleSystems[index];
  452. if (system.emitter == this) {
  453. system.clone(system.name, result);
  454. }
  455. }
  456. return result;
  457. };
  458. // Dispose
  459. BABYLON.Mesh.prototype.dispose = function (doNotRecurse) {
  460. if (this._vertexBuffers) {
  461. //this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  462. this._vertexBuffers = null;
  463. }
  464. if (this._indexBuffer) {
  465. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  466. this._indexBuffer = null;
  467. }
  468. // Remove from scene
  469. var index = this._scene.meshes.indexOf(this);
  470. this._scene.meshes.splice(index, 1);
  471. if (!doNotRecurse) {
  472. // Particles
  473. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  474. if (this._scene.particleSystems[index].emitter == this) {
  475. this._scene.particleSystems[index].dispose();
  476. index--;
  477. }
  478. }
  479. // Children
  480. var objects = this._scene.meshes.slice(0);
  481. for (var index = 0; index < objects.length; index++) {
  482. if (objects[index].parent == this) {
  483. objects[index].dispose();
  484. }
  485. }
  486. }
  487. this._isDisposed = true;
  488. // Callback
  489. if (this.onDispose) {
  490. this.onDispose();
  491. }
  492. };
  493. // Statics
  494. BABYLON.Mesh.CreateBox = function (name, size, scene, updatable) {
  495. var box = new BABYLON.Mesh(name, scene);
  496. var normalsSource = [
  497. new BABYLON.Vector3(0, 0, 1),
  498. new BABYLON.Vector3(0, 0, -1),
  499. new BABYLON.Vector3(1, 0, 0),
  500. new BABYLON.Vector3(-1, 0, 0),
  501. new BABYLON.Vector3(0, 1, 0),
  502. new BABYLON.Vector3(0, -1, 0)
  503. ];
  504. var indices = [];
  505. var positions = [];
  506. var normals = [];
  507. var uvs = [];
  508. // Create each face in turn.
  509. for (var index = 0; index < normalsSource.length; index++) {
  510. var normal = normalsSource[index];
  511. // Get two vectors perpendicular to the face normal and to each other.
  512. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  513. var side2 = BABYLON.Vector3.Cross(normal, side1);
  514. // Six indices (two triangles) per face.
  515. var verticesLength = positions.length / 3;
  516. indices.push(verticesLength);
  517. indices.push(verticesLength + 1);
  518. indices.push(verticesLength + 2);
  519. indices.push(verticesLength);
  520. indices.push(verticesLength + 2);
  521. indices.push(verticesLength + 3);
  522. // Four vertices per face.
  523. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  524. positions.push(vertex.x, vertex.y, vertex.z);
  525. normals.push(normal.x, normal.y, normal.z);
  526. uvs.push(1.0, 1.0);
  527. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  528. positions.push(vertex.x, vertex.y, vertex.z);
  529. normals.push(normal.x, normal.y, normal.z);
  530. uvs.push(0.0, 1.0);
  531. vertex = normal.add(side1).add(side2).scale(size / 2);
  532. positions.push(vertex.x, vertex.y, vertex.z);
  533. normals.push(normal.x, normal.y, normal.z);
  534. uvs.push(0.0, 0.0);
  535. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  536. positions.push(vertex.x, vertex.y, vertex.z);
  537. normals.push(normal.x, normal.y, normal.z);
  538. uvs.push(1.0, 0.0);
  539. }
  540. box.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  541. box.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  542. box.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  543. box.setIndices(indices);
  544. return box;
  545. };
  546. BABYLON.Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  547. var sphere = new BABYLON.Mesh(name, scene);
  548. var radius = diameter / 2;
  549. var totalZRotationSteps = 2 + segments;
  550. var totalYRotationSteps = 2 * totalZRotationSteps;
  551. var indices = [];
  552. var positions = [];
  553. var normals = [];
  554. var uvs = [];
  555. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  556. var normalizedZ = zRotationStep / totalZRotationSteps;
  557. var angleZ = (normalizedZ * Math.PI);
  558. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  559. var normalizedY = yRotationStep / totalYRotationSteps;
  560. var angleY = normalizedY * Math.PI * 2;
  561. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  562. var rotationY = BABYLON.Matrix.RotationY(angleY);
  563. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  564. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  565. var vertex = complete.scale(radius);
  566. var normal = BABYLON.Vector3.Normalize(vertex);
  567. positions.push(vertex.x, vertex.y, vertex.z);
  568. normals.push(normal.x, normal.y, normal.z);
  569. uvs.push(normalizedZ, normalizedY);
  570. }
  571. if (zRotationStep > 0) {
  572. var verticesCount = positions.length / 3;
  573. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1) ; (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  574. indices.push((firstIndex));
  575. indices.push((firstIndex + 1));
  576. indices.push(firstIndex + totalYRotationSteps + 1);
  577. indices.push((firstIndex + totalYRotationSteps + 1));
  578. indices.push((firstIndex + 1));
  579. indices.push((firstIndex + totalYRotationSteps + 2));
  580. }
  581. }
  582. }
  583. sphere.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  584. sphere.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  585. sphere.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  586. sphere.setIndices(indices);
  587. return sphere;
  588. };
  589. // Cylinder (Code from SharpDX.org)
  590. BABYLON.Mesh.CreateCylinder = function (name, height, diameter, tessellation, scene, updatable) {
  591. var radius = diameter / 2;
  592. var indices = [];
  593. var positions = [];
  594. var normals = [];
  595. var uvs = [];
  596. var cylinder = new BABYLON.Mesh(name, scene);
  597. var getCircleVector = function (i) {
  598. var angle = (i * 2.0 * Math.PI / tessellation);
  599. var dx = Math.sin(angle);
  600. var dz = Math.cos(angle);
  601. return new BABYLON.Vector3(dx, 0, dz);
  602. };
  603. var createCylinderCap = function (isTop) {
  604. // Create cap indices.
  605. for (var i = 0; i < tessellation - 2; i++) {
  606. var i1 = (i + 1) % tessellation;
  607. var i2 = (i + 2) % tessellation;
  608. if (isTop) {
  609. var tmp = i1;
  610. var i1 = i2;
  611. i2 = tmp;
  612. }
  613. var vbase = positions.length / 3;
  614. indices.push(vbase);
  615. indices.push(vbase + i1);
  616. indices.push(vbase + i2);
  617. }
  618. // Which end of the cylinder is this?
  619. var normal = new BABYLON.Vector3(0, 1, 0);
  620. var textureScale = new BABYLON.Vector2(-0.5, -0.5);
  621. if (!isTop) {
  622. normal = normal.scale(-1);
  623. textureScale.x = -textureScale.x;
  624. }
  625. // Create cap vertices.
  626. for (var i = 0; i < tessellation; i++) {
  627. var circleVector = getCircleVector(i);
  628. var position = circleVector.scale(radius).add(normal.scale(height));
  629. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  630. positions.push(position.x, position.y, position.z);
  631. normals.push(normal.x, normal.y, normal.z);
  632. uvs.push(textureCoordinate.x, textureCoordinate.y);
  633. }
  634. };
  635. height /= 2;
  636. var topOffset = new BABYLON.Vector3(0, 1, 0).scale(height);
  637. var stride = tessellation + 1;
  638. // Create a ring of triangles around the outside of the cylinder.
  639. for (var i = 0; i <= tessellation; i++) {
  640. var normal = getCircleVector(i);
  641. var sideOffset = normal.scale(radius);
  642. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  643. var position = sideOffset.add(topOffset);
  644. positions.push(position.x, position.y, position.z);
  645. normals.push(normal.x, normal.y, normal.z);
  646. uvs.push(textureCoordinate.x, textureCoordinate.y);
  647. position = sideOffset.subtract(topOffset);
  648. textureCoordinate.y += 1;
  649. positions.push(position.x, position.y, position.z);
  650. normals.push(normal.x, normal.y, normal.z);
  651. uvs.push(textureCoordinate.x, textureCoordinate.y);
  652. indices.push(i * 2);
  653. indices.push((i * 2 + 2) % (stride * 2));
  654. indices.push(i * 2 + 1);
  655. indices.push(i * 2 + 1);
  656. indices.push((i * 2 + 2) % (stride * 2));
  657. indices.push((i * 2 + 3) % (stride * 2));
  658. }
  659. // Create flat triangle fan caps to seal the top and bottom.
  660. createCylinderCap(true);
  661. createCylinderCap(false);
  662. cylinder.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  663. cylinder.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  664. cylinder.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  665. cylinder.setIndices(indices);
  666. return cylinder;
  667. };
  668. // Torus (Code from SharpDX.org)
  669. BABYLON.Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  670. var torus = new BABYLON.Mesh(name, scene);
  671. var indices = [];
  672. var positions = [];
  673. var normals = [];
  674. var uvs = [];
  675. var stride = tessellation + 1;
  676. for (var i = 0; i <= tessellation; i++) {
  677. var u = i / tessellation;
  678. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  679. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  680. for (var j = 0; j <= tessellation; j++) {
  681. var v = 1 - j / tessellation;
  682. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  683. var dx = Math.cos(innerAngle);
  684. var dy = Math.sin(innerAngle);
  685. // Create a vertex.
  686. var normal = new BABYLON.Vector3(dx, dy, 0);
  687. var position = normal.scale(thickness / 2);
  688. var textureCoordinate = new BABYLON.Vector2(u, v);
  689. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  690. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  691. positions.push(position.x, position.y, position.z);
  692. normals.push(normal.x, normal.y, normal.z);
  693. uvs.push(textureCoordinate.x, textureCoordinate.y);
  694. // And create indices for two triangles.
  695. var nextI = (i + 1) % stride;
  696. var nextJ = (j + 1) % stride;
  697. indices.push(i * stride + j);
  698. indices.push(i * stride + nextJ);
  699. indices.push(nextI * stride + j);
  700. indices.push(i * stride + nextJ);
  701. indices.push(nextI * stride + nextJ);
  702. indices.push(nextI * stride + j);
  703. }
  704. }
  705. torus.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  706. torus.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  707. torus.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  708. torus.setIndices(indices);
  709. return torus;
  710. };
  711. // Plane
  712. BABYLON.Mesh.CreatePlane = function (name, size, scene, updatable) {
  713. var plane = new BABYLON.Mesh(name, scene);
  714. var indices = [];
  715. var positions = [];
  716. var normals = [];
  717. var uvs = [];
  718. // Vertices
  719. var halfSize = size / 2.0;
  720. positions.push(-halfSize, -halfSize, 0);
  721. normals.push(0, 0, -1.0);
  722. uvs.push(0.0, 0.0);
  723. positions.push(halfSize, -halfSize, 0);
  724. normals.push(0, 0, -1.0);
  725. uvs.push(1.0, 0.0);
  726. positions.push(halfSize, halfSize, 0);
  727. normals.push(0, 0, -1.0);
  728. uvs.push(1.0, 1.0);
  729. positions.push(-halfSize, halfSize, 0);
  730. normals.push(0, 0, -1.0);
  731. uvs.push(0.0, 1.0);
  732. // Indices
  733. indices.push(0);
  734. indices.push(1);
  735. indices.push(2);
  736. indices.push(0);
  737. indices.push(2);
  738. indices.push(3);
  739. plane.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  740. plane.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  741. plane.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  742. plane.setIndices(indices);
  743. return plane;
  744. };
  745. BABYLON.Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  746. var ground = new BABYLON.Mesh(name, scene);
  747. var indices = [];
  748. var positions = [];
  749. var normals = [];
  750. var uvs = [];
  751. var row, col;
  752. for (row = 0; row <= subdivisions; row++) {
  753. for (col = 0; col <= subdivisions; col++) {
  754. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  755. var normal = new BABYLON.Vector3(0, 1.0, 0);
  756. positions.push(position.x, position.y, position.z);
  757. normals.push(normal.x, normal.y, normal.z);
  758. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  759. }
  760. }
  761. for (row = 0; row < subdivisions; row++) {
  762. for (col = 0; col < subdivisions; col++) {
  763. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  764. indices.push(col + 1 + row * (subdivisions + 1));
  765. indices.push(col + row * (subdivisions + 1));
  766. indices.push(col + (row + 1) * (subdivisions + 1));
  767. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  768. indices.push(col + row * (subdivisions + 1));
  769. }
  770. }
  771. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  772. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  773. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  774. ground.setIndices(indices);
  775. return ground;
  776. };
  777. BABYLON.Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  778. var ground = new BABYLON.Mesh(name, scene);
  779. var img = new Image();
  780. img.onload = function () {
  781. var indices = [];
  782. var positions = [];
  783. var normals = [];
  784. var uvs = [];
  785. var row, col;
  786. // Getting height map data
  787. var canvas = document.createElement("canvas");
  788. var context = canvas.getContext("2d");
  789. var heightMapWidth = img.width;
  790. var heightMapHeight = img.height;
  791. canvas.width = heightMapWidth;
  792. canvas.height = heightMapHeight;
  793. context.drawImage(img, 0, 0);
  794. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  795. // Vertices
  796. for (row = 0; row <= subdivisions; row++) {
  797. for (col = 0; col <= subdivisions; col++) {
  798. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  799. // Compute height
  800. var heightMapX = (((position.x + width / 2) / width) * (heightMapWidth - 1)) | 0;
  801. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (heightMapHeight - 1)) | 0;
  802. var pos = (heightMapX + heightMapY * heightMapWidth) * 4;
  803. var r = buffer[pos] / 255.0;
  804. var g = buffer[pos + 1] / 255.0;
  805. var b = buffer[pos + 2] / 255.0;
  806. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  807. position.y = minHeight + (maxHeight - minHeight) * gradient;
  808. // Add vertex
  809. positions.push(position.x, position.y, position.z);
  810. normals.push(0, 0, 0);
  811. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  812. }
  813. }
  814. // Indices
  815. for (row = 0; row < subdivisions; row++) {
  816. for (col = 0; col < subdivisions; col++) {
  817. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  818. indices.push(col + 1 + row * (subdivisions + 1));
  819. indices.push(col + row * (subdivisions + 1));
  820. indices.push(col + (row + 1) * (subdivisions + 1));
  821. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  822. indices.push(col + row * (subdivisions + 1));
  823. }
  824. }
  825. // Normals
  826. BABYLON.Mesh.ComputeNormal(positions, normals, indices);
  827. // Transfer
  828. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  829. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  830. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  831. ground.setIndices(indices);
  832. ground._isReady = true;
  833. };
  834. img.src = url;
  835. ground._isReady = false;
  836. return ground;
  837. };
  838. // Tools
  839. BABYLON.Mesh.ComputeNormal = function (positions, normals, indices) {
  840. var positionVectors = [];
  841. var facesOfVertices = [];
  842. var index;
  843. for (index = 0; index < positions.length; index += 3) {
  844. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  845. positionVectors.push(vector3);
  846. facesOfVertices.push([]);
  847. }
  848. // Compute normals
  849. var facesNormals = [];
  850. for (index = 0; index < indices.length / 3; index++) {
  851. var i1 = indices[index * 3];
  852. var i2 = indices[index * 3 + 1];
  853. var i3 = indices[index * 3 + 2];
  854. var p1 = positionVectors[i1];
  855. var p2 = positionVectors[i2];
  856. var p3 = positionVectors[i3];
  857. var p1p2 = p1.subtract(p2);
  858. var p3p2 = p3.subtract(p2);
  859. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  860. facesOfVertices[i1].push(index);
  861. facesOfVertices[i2].push(index);
  862. facesOfVertices[i3].push(index);
  863. }
  864. for (index = 0; index < positionVectors.length; index++) {
  865. var faces = facesOfVertices[index];
  866. var normal = BABYLON.Vector3.Zero();
  867. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  868. normal.addInPlace(facesNormals[faces[faceIndex]]);
  869. }
  870. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  871. normals[index * 3] = normal.x;
  872. normals[index * 3 + 1] = normal.y;
  873. normals[index * 3 + 2] = normal.z;
  874. }
  875. };
  876. })();