babylon.mesh.js 49 KB

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