babylon.mesh.js 37 KB

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