babylon.mesh.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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. {
  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.render = function (subMesh) {
  224. if (!this._vertexBuffer || !this._indexBuffer) {
  225. return;
  226. }
  227. var engine = this._scene.getEngine();
  228. // World
  229. var world = this.getWorldMatrix();
  230. // Material
  231. var effectiveMaterial = subMesh.getMaterial();
  232. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  233. return;
  234. }
  235. effectiveMaterial._preBind();
  236. effectiveMaterial.bind(world, this);
  237. // Wireframe
  238. var indexToBind = this._indexBuffer;
  239. var useTriangles = true;
  240. if (engine.forceWireframe || effectiveMaterial.wireframe) {
  241. indexToBind = subMesh.getLinesIndexBuffer(this._indices, engine);
  242. useTriangles = false;
  243. }
  244. // VBOs
  245. engine.bindBuffers(this._vertexBuffer, indexToBind, this._vertexDeclaration, this._vertexStrideSize, effectiveMaterial.getEffect());
  246. // Draw order
  247. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  248. // Unbind
  249. effectiveMaterial.unbind();
  250. };
  251. BABYLON.Mesh.prototype.isDescendantOf = function (ancestor) {
  252. if (this.parent) {
  253. if (this.parent === ancestor) {
  254. return true;
  255. }
  256. return this.parent.isDescendantOf(ancestor);
  257. }
  258. return false;
  259. };
  260. BABYLON.Mesh.prototype.getDescendants = function () {
  261. var results = [];
  262. for (var index = 0; index < this._scene.meshes.length; index++) {
  263. var mesh = this._scene.meshes[index];
  264. if (mesh.isDescendantOf(this)) {
  265. results.push(mesh);
  266. }
  267. }
  268. return results;
  269. };
  270. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  271. var results = [];
  272. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  273. var particleSystem = this._scene.particleSystems[index];
  274. if (particleSystem.emitter === this) {
  275. results.push(particleSystem);
  276. }
  277. }
  278. return results;
  279. };
  280. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  281. var results = [];
  282. var descendants = this.getDescendants();
  283. descendants.push(this);
  284. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  285. var particleSystem = this._scene.particleSystems[index];
  286. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  287. results.push(particleSystem);
  288. }
  289. }
  290. return results;
  291. };
  292. BABYLON.Mesh.prototype.getChildren = function () {
  293. var results = [];
  294. for (var index = 0; index < this._scene.meshes.length; index++) {
  295. var mesh = this._scene.meshes[index];
  296. if (mesh.parent == this) {
  297. results.push(mesh);
  298. }
  299. }
  300. return results;
  301. };
  302. BABYLON.Mesh.prototype.isInFrustrum = function (frustumPlanes) {
  303. return this._boundingInfo.isInFrustrum(frustumPlanes);
  304. };
  305. BABYLON.Mesh.prototype.setMaterialByID = function (id) {
  306. var materials = this._scene.materials;
  307. for (var index = 0; index < materials.length; index++) {
  308. if (materials[index].id == id) {
  309. this.material = materials[index];
  310. return;
  311. }
  312. }
  313. // Multi
  314. var multiMaterials = this._scene.multiMaterials;
  315. for (var index = 0; index < multiMaterials.length; index++) {
  316. if (multiMaterials[index].id == id) {
  317. this.material = multiMaterials[index];
  318. return;
  319. }
  320. }
  321. };
  322. BABYLON.Mesh.prototype.getAnimatables = function () {
  323. var results = [];
  324. if (this.material) {
  325. results.push(this.material);
  326. }
  327. return results;
  328. };
  329. // Cache
  330. BABYLON.Mesh.prototype._generatePointsArray = function () {
  331. if (this._positions)
  332. return;
  333. this._positions = [];
  334. var stride = this.getFloatVertexStrideSize();
  335. for (var index = 0; index < this._vertices.length; index += stride) {
  336. this._positions.push(BABYLON.Vector3.FromArray(this._vertices, index));
  337. }
  338. };
  339. // Collisions
  340. BABYLON.Mesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  341. this._generatePointsArray();
  342. // Transformation
  343. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  344. subMesh._lastColliderTransformMatrix = transformMatrix;
  345. subMesh._lastColliderWorldVertices = [];
  346. var start = subMesh.verticesStart;
  347. var end = (subMesh.verticesStart + subMesh.verticesCount);
  348. for (var i = start; i < end; i++) {
  349. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  350. }
  351. }
  352. // Collide
  353. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this._indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  354. };
  355. BABYLON.Mesh.prototype._processCollisionsForSubModels = function (collider, transformMatrix) {
  356. for (var index = 0; index < this.subMeshes.length; index++) {
  357. var subMesh = this.subMeshes[index];
  358. // Bounding test
  359. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  360. continue;
  361. this._collideForSubMesh(subMesh, transformMatrix, collider);
  362. }
  363. };
  364. BABYLON.Mesh.prototype._checkCollision = function (collider) {
  365. // Bounding box test
  366. if (!this._boundingInfo._checkCollision(collider))
  367. return;
  368. // Transformation matrix
  369. var transformMatrix = this._worldMatrix.multiply(BABYLON.Matrix.Scaling(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z));
  370. this._processCollisionsForSubModels(collider, transformMatrix);
  371. };
  372. BABYLON.Mesh.prototype.intersectsMesh = function (mesh, precise) {
  373. if (!this._boundingInfo || !mesh._boundingInfo) {
  374. return false;
  375. }
  376. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  377. };
  378. BABYLON.Mesh.prototype.intersectsPoint = function (point) {
  379. if (!this._boundingInfo) {
  380. return false;
  381. }
  382. return this._boundingInfo.intersectsPoint(point);
  383. };
  384. // Picking
  385. BABYLON.Mesh.prototype.intersects = function (ray) {
  386. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere)) {
  387. return { hit: false, distance: 0 };
  388. }
  389. this._generatePointsArray();
  390. var distance = Number.MAX_VALUE;
  391. for (var index = 0; index < this.subMeshes.length; index++) {
  392. var subMesh = this.subMeshes[index];
  393. // Bounding test
  394. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  395. continue;
  396. var result = subMesh.intersects(ray, this._positions, this._indices);
  397. if (result.hit) {
  398. if (result.distance < distance && result.distance >= 0) {
  399. distance = result.distance;
  400. }
  401. }
  402. }
  403. if (distance >= 0)
  404. return { hit: true, distance: distance };
  405. return { hit: false, distance: 0 };
  406. };
  407. // Clone
  408. BABYLON.Mesh.prototype.clone = function (name, newParent) {
  409. var result = new BABYLON.Mesh(name, this._vertexDeclaration, this._scene);
  410. BABYLON.Tools.DeepCopy(this, result, ["name", "material"], ["_uvCount", "_vertices", "_indices", "_totalVertices"]);
  411. // Bounding info
  412. result._boundingInfo = new BABYLON.BoundingInfo(result._vertices, result.getFloatVertexStrideSize(), 0, result._vertices.length);
  413. // Material
  414. result.material = this.material;
  415. // Buffers
  416. result._vertexBuffer = this._vertexBuffer;
  417. this._vertexBuffer.references++;
  418. result._indexBuffer = this._indexBuffer;
  419. this._indexBuffer.references++;
  420. // Parent
  421. if (newParent) {
  422. result.parent = newParent;
  423. }
  424. // Children
  425. for (var index = 0; index < this._scene.meshes.length; index++) {
  426. var mesh = this._scene.meshes[index];
  427. if (mesh.parent == this) {
  428. mesh.clone(mesh.name, result);
  429. }
  430. }
  431. // Particles
  432. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  433. var system = this._scene.particleSystems[index];
  434. if (system.emitter == this) {
  435. system.clone(system.name, result);
  436. }
  437. }
  438. return result;
  439. };
  440. // Dispose
  441. BABYLON.Mesh.prototype.dispose = function (doNotRecurse) {
  442. if (this._vertexBuffer) {
  443. //this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  444. this._vertexBuffer = null;
  445. }
  446. if (this._indexBuffer) {
  447. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  448. this._indexBuffer = null;
  449. }
  450. // Remove from scene
  451. var index = this._scene.meshes.indexOf(this);
  452. this._scene.meshes.splice(index, 1);
  453. if (doNotRecurse) {
  454. return;
  455. }
  456. // Particles
  457. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  458. if (this._scene.particleSystems[index].emitter == this) {
  459. this._scene.particleSystems[index].dispose();
  460. index--;
  461. }
  462. }
  463. // Children
  464. var objects = this._scene.meshes.slice(0);
  465. for (var index = 0; index < objects.length; index++) {
  466. if (objects[index].parent == this) {
  467. objects[index].dispose();
  468. }
  469. }
  470. // Callback
  471. if (this.onDispose) {
  472. this.onDispose();
  473. }
  474. };
  475. // Statics
  476. BABYLON.Mesh.CreateBox = function (name, size, scene, updatable) {
  477. var box = new BABYLON.Mesh(name, [3, 3, 2], scene);
  478. var normals = [
  479. new BABYLON.Vector3(0, 0, 1),
  480. new BABYLON.Vector3(0, 0, -1),
  481. new BABYLON.Vector3(1, 0, 0),
  482. new BABYLON.Vector3(-1, 0, 0),
  483. new BABYLON.Vector3(0, 1, 0),
  484. new BABYLON.Vector3(0, -1, 0)
  485. ];
  486. var indices = [];
  487. var vertices = [];
  488. // Create each face in turn.
  489. for (var index = 0; index < normals.length; index++) {
  490. var normal = normals[index];
  491. // Get two vectors perpendicular to the face normal and to each other.
  492. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  493. var side2 = BABYLON.Vector3.Cross(normal, side1);
  494. // Six indices (two triangles) per face.
  495. var verticesLength = vertices.length / 8;
  496. indices.push(verticesLength);
  497. indices.push(verticesLength + 1);
  498. indices.push(verticesLength + 2);
  499. indices.push(verticesLength);
  500. indices.push(verticesLength + 2);
  501. indices.push(verticesLength + 3);
  502. // Four vertices per face.
  503. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  504. vertices.push(vertex.x, vertex.y, vertex.z, normal.x, normal.y, normal.z, 1.0, 1.0);
  505. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  506. vertices.push(vertex.x, vertex.y, vertex.z, normal.x, normal.y, normal.z, 0.0, 1.0);
  507. vertex = normal.add(side1).add(side2).scale(size / 2);
  508. vertices.push(vertex.x, vertex.y, vertex.z, normal.x, normal.y, normal.z, 0.0, 0.0);
  509. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  510. vertices.push(vertex.x, vertex.y, vertex.z, normal.x, normal.y, normal.z, 1.0, 0.0);
  511. }
  512. box.setVertices(vertices, 1, updatable);
  513. box.setIndices(indices);
  514. return box;
  515. };
  516. BABYLON.Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  517. var sphere = new BABYLON.Mesh(name, [3, 3, 2], scene);
  518. var radius = diameter / 2;
  519. var totalZRotationSteps = 2 + segments;
  520. var totalYRotationSteps = 2 * totalZRotationSteps;
  521. var indices = [];
  522. var vertices = [];
  523. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  524. var normalizedZ = zRotationStep / totalZRotationSteps;
  525. var angleZ = (normalizedZ * Math.PI);
  526. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  527. var normalizedY = yRotationStep / totalYRotationSteps;
  528. var angleY = normalizedY * Math.PI * 2;
  529. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  530. var rotationY = BABYLON.Matrix.RotationY(angleY);
  531. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  532. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  533. var vertex = complete.scale(radius);
  534. var normal = BABYLON.Vector3.Normalize(vertex);
  535. vertices.push(vertex.x, vertex.y, vertex.z, normal.x, normal.y, normal.z, normalizedZ, normalizedY);
  536. }
  537. if (zRotationStep > 0) {
  538. var verticesCount = vertices.length / 8;
  539. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1) ; (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  540. indices.push((firstIndex));
  541. indices.push((firstIndex + 1));
  542. indices.push(firstIndex + totalYRotationSteps + 1);
  543. indices.push((firstIndex + totalYRotationSteps + 1));
  544. indices.push((firstIndex + 1));
  545. indices.push((firstIndex + totalYRotationSteps + 2));
  546. }
  547. }
  548. }
  549. sphere.setVertices(vertices, 1, updatable);
  550. sphere.setIndices(indices);
  551. return sphere;
  552. };
  553. // Plane
  554. BABYLON.Mesh.CreatePlane = function (name, size, scene, updatable) {
  555. var plane = new BABYLON.Mesh(name, [3, 3, 2], scene);
  556. var indices = [];
  557. var vertices = [];
  558. // Vertices
  559. var halfSize = size / 2.0;
  560. vertices.push(-halfSize, -halfSize, 0, 0, 0, -1.0, 0.0, 0.0);
  561. vertices.push(halfSize, -halfSize, 0, 0, 0, -1.0, 1.0, 0.0);
  562. vertices.push(halfSize, halfSize, 0, 0, 0, -1.0, 1.0, 1.0);
  563. vertices.push(-halfSize, halfSize, 0, 0, 0, -1.0, 0.0, 1.0);
  564. // Indices
  565. indices.push(0);
  566. indices.push(1);
  567. indices.push(2);
  568. indices.push(0);
  569. indices.push(2);
  570. indices.push(3);
  571. plane.setVertices(vertices, 1, updatable);
  572. plane.setIndices(indices);
  573. return plane;
  574. };
  575. BABYLON.Mesh.CreateGround = function(name, width, height, subdivisions, scene, updatable) {
  576. var ground = new BABYLON.Mesh(name, [3, 3, 2], scene);
  577. var indices = [];
  578. var vertices = [];
  579. var row, col;
  580. for (row = 0; row <= subdivisions; row++) {
  581. for (col = 0; col <= subdivisions; col++) {
  582. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  583. var normal = new BABYLON.Vector3(0, 1.0, 0);
  584. vertices.push(position.x, position.y, position.z,
  585. normal.x, normal.y, normal.z,
  586. col / subdivisions, row / subdivisions);
  587. }
  588. }
  589. for (row = 0; row < subdivisions; row++) {
  590. for (col = 0; col < subdivisions; col++) {
  591. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  592. indices.push(col + 1 + row * (subdivisions + 1));
  593. indices.push(col + row * (subdivisions + 1));
  594. indices.push(col + (row + 1) * (subdivisions + 1));
  595. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  596. indices.push(col + row * (subdivisions + 1));
  597. }
  598. }
  599. ground.setVertices(vertices, 1, updatable);
  600. ground.setIndices(indices);
  601. return ground;
  602. };
  603. BABYLON.Mesh.CreateGroundFromHeightMap = function(name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  604. var ground = new BABYLON.Mesh(name, [3, 3, 2], scene);
  605. var img = new Image();
  606. img.onload = function() {
  607. var indices = [];
  608. var vertices = [];
  609. var row, col;
  610. // Getting height map data
  611. var canvas = document.createElement("canvas");
  612. var context = canvas.getContext("2d");
  613. var heightMapWidth = img.width;
  614. var heightMapHeight = img.height;
  615. canvas.width = heightMapWidth;
  616. canvas.height = heightMapHeight;
  617. context.drawImage(img, 0, 0);
  618. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  619. // Vertices
  620. for (row = 0; row <= subdivisions; row++) {
  621. for (col = 0; col <= subdivisions; col++) {
  622. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  623. // Compute height
  624. var heightMapX = (((position.x + width / 2) / width) * (heightMapWidth - 1)) | 0;
  625. var heightMapY = (((position.z + height / 2) / height) * (heightMapHeight - 1)) | 0;
  626. var pos = (heightMapX + heightMapY * heightMapWidth) * 4;
  627. var r = buffer[pos] / 255.0;
  628. var g = buffer[pos + 1] / 255.0;
  629. var b = buffer[pos + 2] / 255.0;
  630. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  631. position.y = minHeight + (maxHeight - minHeight) * gradient;
  632. // Add vertex
  633. vertices.push(position.x, position.y, position.z,
  634. 0, 0, 0,
  635. col / subdivisions, row / subdivisions);
  636. }
  637. }
  638. // Indices
  639. for (row = 0; row < subdivisions; row++) {
  640. for (col = 0; col < subdivisions; col++) {
  641. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  642. indices.push(col + 1 + row * (subdivisions + 1));
  643. indices.push(col + row * (subdivisions + 1));
  644. indices.push(col + (row + 1) * (subdivisions + 1));
  645. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  646. indices.push(col + row * (subdivisions + 1));
  647. }
  648. }
  649. // Normals
  650. BABYLON.Mesh.ComputeNormal(vertices, indices, ground.getFloatVertexStrideSize());
  651. // Transfer
  652. ground.setVertices(vertices, 1, updatable);
  653. ground.setIndices(indices);
  654. ground._isReady = true;
  655. };
  656. img.src = url;
  657. ground._isReady = false;
  658. return ground;
  659. };
  660. // Tools
  661. BABYLON.Mesh.ComputeNormal = function(vertices, indices, stride, normalOffset) {
  662. var positions = [];
  663. var facesOfVertices = [];
  664. var index;
  665. if (normalOffset === undefined) {
  666. normalOffset = 3;
  667. }
  668. for (index = 0; index < vertices.length; index += stride) {
  669. var position = new BABYLON.Vector3(vertices[index], vertices[index + 1], vertices[index + 2]);
  670. positions.push(position);
  671. facesOfVertices.push([]);
  672. }
  673. // Compute normals
  674. var facesNormals = [];
  675. for (index = 0; index < indices.length / 3; index++) {
  676. var i1 = indices[index * 3];
  677. var i2 = indices[index * 3 + 1];
  678. var i3 = indices[index * 3 + 2];
  679. var p1 = positions[i1];
  680. var p2 = positions[i2];
  681. var p3 = positions[i3];
  682. var p1p2 = p1.subtract(p2);
  683. var p3p2 = p3.subtract(p2);
  684. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  685. facesOfVertices[i1].push(index);
  686. facesOfVertices[i2].push(index);
  687. facesOfVertices[i3].push(index);
  688. }
  689. for (index = 0; index < positions.length; index++) {
  690. var faces = facesOfVertices[index];
  691. var normal = BABYLON.Vector3.Zero();
  692. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  693. normal = normal.add(facesNormals[faces[faceIndex]]);
  694. }
  695. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  696. vertices[index * stride + normalOffset] = normal.x;
  697. vertices[index * stride + normalOffset + 1] = normal.y;
  698. vertices[index * stride + normalOffset + 2] = normal.z;
  699. }
  700. };
  701. })();