babylon.mesh.js 46 KB

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