babylon.mesh.js 46 KB

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