babylon.mesh.js 37 KB

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