babylon.mesh.js 47 KB

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