babylon.mesh.js 47 KB

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