babylon.mesh.js 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  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 == 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 == 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. if (this._boundingInfo) {
  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. };
  253. BABYLON.Mesh.prototype.computeWorldMatrix = function (force) {
  254. if (!force && (this._currentRenderId == this._scene.getRenderId() || this.isSynchronized(true))) {
  255. this._currentRenderId = this._scene.getRenderId();
  256. return this._worldMatrix;
  257. }
  258. this._cache.position.copyFrom(this.position);
  259. this._cache.scaling.copyFrom(this.scaling);
  260. this._cache.pivotMatrixUpdated = false;
  261. this._currentRenderId = this._scene.getRenderId();
  262. // Scaling
  263. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  264. // Rotation
  265. if (this.rotationQuaternion) {
  266. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  267. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  268. } else {
  269. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  270. this._cache.rotation.copyFrom(this.rotation);
  271. }
  272. // Translation
  273. if (this.infiniteDistance && !this.parent) {
  274. var camera = this._scene.activeCamera;
  275. var cameraWorldMatrix = camera.getWorldMatrix();
  276. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  277. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  278. } else {
  279. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  280. }
  281. // Composing transformations
  282. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  283. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  284. // Billboarding
  285. if (this.billboardMode !== BABYLON.Mesh.BILLBOARDMODE_NONE) {
  286. var localPosition = this.position.clone();
  287. var zero = this._scene.activeCamera.position.clone();
  288. if (this.parent && this.parent.position) {
  289. localPosition.addInPlace(this.parent.position);
  290. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  291. }
  292. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_ALL === BABYLON.Mesh.BILLBOARDMODE_ALL) {
  293. zero = this._scene.activeCamera.position;
  294. } else {
  295. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_X)
  296. zero.x = localPosition.x + BABYLON.Engine.epsilon;
  297. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Y)
  298. zero.y = localPosition.y + BABYLON.Engine.epsilon;
  299. if (this.billboardMode & BABYLON.Mesh.BILLBOARDMODE_Z)
  300. zero.z = localPosition.z + BABYLON.Engine.epsilon;
  301. }
  302. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  303. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  304. this._localBillboard.invert();
  305. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  306. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  307. }
  308. // Local world
  309. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  310. // Parent
  311. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.Mesh.BILLBOARDMODE_NONE) {
  312. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  313. } else {
  314. this._worldMatrix.copyFrom(this._localWorld);
  315. }
  316. // Bounding info
  317. this._updateBoundingInfo();
  318. // Absolute position
  319. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  320. return this._worldMatrix;
  321. };
  322. BABYLON.Mesh.prototype._createGlobalSubMesh = function () {
  323. if (!this._totalVertices || !this._indices) {
  324. return null;
  325. }
  326. this.subMeshes = [];
  327. return new BABYLON.SubMesh(0, 0, this._totalVertices, 0, this._indices.length, this);
  328. };
  329. BABYLON.Mesh.prototype.subdivide = function (count) {
  330. if (count < 1) {
  331. return;
  332. }
  333. var subdivisionSize = this._indices.length / count;
  334. var offset = 0;
  335. this.subMeshes = [];
  336. for (var index = 0; index < count; index++) {
  337. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, this._indices.length - offset), this);
  338. offset += subdivisionSize;
  339. }
  340. };
  341. BABYLON.Mesh.prototype.setVerticesData = function (data, kind, updatable) {
  342. if (!this._vertexBuffers) {
  343. this._vertexBuffers = {};
  344. }
  345. if (this._vertexBuffers[kind]) {
  346. this._vertexBuffers[kind].dispose();
  347. }
  348. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this, data, kind, updatable);
  349. if (kind === BABYLON.VertexBuffer.PositionKind) {
  350. var stride = this._vertexBuffers[kind].getStrideSize();
  351. this._totalVertices = data.length / stride;
  352. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  353. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  354. this._createGlobalSubMesh();
  355. }
  356. };
  357. BABYLON.Mesh.prototype.updateVerticesData = function (kind, data) {
  358. if (this._vertexBuffers[kind]) {
  359. this._vertexBuffers[kind].update(data);
  360. }
  361. };
  362. BABYLON.Mesh.prototype.setIndices = function (indices) {
  363. if (this._indexBuffer) {
  364. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  365. }
  366. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  367. this._indices = indices;
  368. this._createGlobalSubMesh();
  369. };
  370. BABYLON.Mesh.prototype.bindAndDraw = function (subMesh, effect, wireframe) {
  371. var engine = this._scene.getEngine();
  372. // Wireframe
  373. var indexToBind = this._indexBuffer;
  374. var useTriangles = true;
  375. if (wireframe) {
  376. indexToBind = subMesh.getLinesIndexBuffer(this._indices, engine);
  377. useTriangles = false;
  378. }
  379. // VBOs
  380. engine.bindMultiBuffers(this._vertexBuffers, indexToBind, effect);
  381. // Draw order
  382. engine.draw(useTriangles, useTriangles ? subMesh.indexStart : 0, useTriangles ? subMesh.indexCount : subMesh.linesIndexCount);
  383. };
  384. BABYLON.Mesh.prototype.registerBeforeRender = function (func) {
  385. this._onBeforeRenderCallbacks.push(func);
  386. };
  387. BABYLON.Mesh.prototype.unregisterBeforeRender = function (func) {
  388. var index = this._onBeforeRenderCallbacks.indexOf(func);
  389. if (index > -1) {
  390. this._onBeforeRenderCallbacks.splice(index, 1);
  391. }
  392. };
  393. BABYLON.Mesh.prototype.render = function (subMesh) {
  394. if (!this._vertexBuffers || !this._indexBuffer) {
  395. return;
  396. }
  397. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  398. this._onBeforeRenderCallbacks[callbackIndex]();
  399. }
  400. // World
  401. var world = this.getWorldMatrix();
  402. // Material
  403. var effectiveMaterial = subMesh.getMaterial();
  404. if (!effectiveMaterial || !effectiveMaterial.isReady(this)) {
  405. return;
  406. }
  407. effectiveMaterial._preBind();
  408. effectiveMaterial.bind(world, this);
  409. // Bind and draw
  410. var engine = this._scene.getEngine();
  411. this.bindAndDraw(subMesh, effectiveMaterial.getEffect(), engine.forceWireframe || effectiveMaterial.wireframe);
  412. // Unbind
  413. effectiveMaterial.unbind();
  414. };
  415. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  416. var results = [];
  417. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  418. var particleSystem = this._scene.particleSystems[index];
  419. if (particleSystem.emitter === this) {
  420. results.push(particleSystem);
  421. }
  422. }
  423. return results;
  424. };
  425. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  426. var results = [];
  427. var descendants = this.getDescendants();
  428. descendants.push(this);
  429. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  430. var particleSystem = this._scene.particleSystems[index];
  431. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  432. results.push(particleSystem);
  433. }
  434. }
  435. return results;
  436. };
  437. BABYLON.Mesh.prototype.getChildren = function () {
  438. var results = [];
  439. for (var index = 0; index < this._scene.meshes.length; index++) {
  440. var mesh = this._scene.meshes[index];
  441. if (mesh.parent == this) {
  442. results.push(mesh);
  443. }
  444. }
  445. return results;
  446. };
  447. BABYLON.Mesh.prototype.isInFrustum = function (frustumPlanes) {
  448. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  449. return false;
  450. }
  451. var result = this._boundingInfo.isInFrustum(frustumPlanes);
  452. if (result && this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  453. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  454. var that = this;
  455. this._scene._addPendingData(this);
  456. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  457. that._delayLoadingFunction(JSON.parse(data), that);
  458. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  459. that._scene._removePendingData(that);
  460. }, function () { }, this._scene.database);
  461. }
  462. return result;
  463. };
  464. BABYLON.Mesh.prototype.setMaterialByID = function (id) {
  465. var materials = this._scene.materials;
  466. for (var index = 0; index < materials.length; index++) {
  467. if (materials[index].id == id) {
  468. this.material = materials[index];
  469. return;
  470. }
  471. }
  472. // Multi
  473. var multiMaterials = this._scene.multiMaterials;
  474. for (var index = 0; index < multiMaterials.length; index++) {
  475. if (multiMaterials[index].id == id) {
  476. this.material = multiMaterials[index];
  477. return;
  478. }
  479. }
  480. };
  481. BABYLON.Mesh.prototype.getAnimatables = function () {
  482. var results = [];
  483. if (this.material) {
  484. results.push(this.material);
  485. }
  486. return results;
  487. };
  488. // Geometry
  489. BABYLON.Mesh.prototype.setPositionWithLocalVector = function (vector3) {
  490. this.computeWorldMatrix();
  491. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  492. };
  493. BABYLON.Mesh.prototype.getPositionExpressedInLocalSpace = function () {
  494. this.computeWorldMatrix();
  495. var invLocalWorldMatrix = this._localWorld.clone();
  496. invLocalWorldMatrix.invert();
  497. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  498. };
  499. BABYLON.Mesh.prototype.locallyTranslate = function (vector3) {
  500. this.computeWorldMatrix();
  501. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  502. };
  503. BABYLON.Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  504. // Position
  505. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  506. return;
  507. }
  508. this._resetPointsArrayCache();
  509. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  510. var temp = new BABYLON.MatrixType(data.length);
  511. for (var index = 0; index < data.length; index += 3) {
  512. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  513. }
  514. this.setVerticesData(temp, BABYLON.VertexBuffer.PositionKind, this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].isUpdatable());
  515. // Normals
  516. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  517. return;
  518. }
  519. data = this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].getData();
  520. for (var index = 0; index < data.length; index += 3) {
  521. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  522. }
  523. this.setVerticesData(temp, BABYLON.VertexBuffer.NormalKind, this._vertexBuffers[BABYLON.VertexBuffer.NormalKind].isUpdatable());
  524. };
  525. BABYLON.Mesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  526. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  527. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  528. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  529. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  530. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  531. /// <returns>Mesh oriented towards targetMesh</returns>
  532. yawCor = yawCor || 0; // default to zero if undefined
  533. pitchCor = pitchCor || 0;
  534. rollCor = rollCor || 0;
  535. var dv = targetPoint.subtract(this.position);
  536. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  537. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  538. var pitch = Math.atan2(dv.y, len);
  539. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  540. };
  541. // Cache
  542. BABYLON.Mesh.prototype._resetPointsArrayCache = function () {
  543. this._positions = null;
  544. };
  545. BABYLON.Mesh.prototype._generatePointsArray = function () {
  546. if (this._positions)
  547. return;
  548. this._positions = [];
  549. var data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  550. for (var index = 0; index < data.length; index += 3) {
  551. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  552. }
  553. };
  554. // Collisions
  555. BABYLON.Mesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  556. this._generatePointsArray();
  557. // Transformation
  558. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  559. subMesh._lastColliderTransformMatrix = transformMatrix;
  560. subMesh._lastColliderWorldVertices = [];
  561. var start = subMesh.verticesStart;
  562. var end = (subMesh.verticesStart + subMesh.verticesCount);
  563. for (var i = start; i < end; i++) {
  564. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  565. }
  566. }
  567. // Collide
  568. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this._indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  569. };
  570. BABYLON.Mesh.prototype._processCollisionsForSubModels = function (collider, transformMatrix) {
  571. for (var index = 0; index < this.subMeshes.length; index++) {
  572. var subMesh = this.subMeshes[index];
  573. // Bounding test
  574. if (this.subMeshes.length > 1 && !subMesh._checkCollision(collider))
  575. continue;
  576. this._collideForSubMesh(subMesh, transformMatrix, collider);
  577. }
  578. };
  579. BABYLON.Mesh.prototype._checkCollision = function (collider) {
  580. // Bounding box test
  581. if (!this._boundingInfo._checkCollision(collider))
  582. return;
  583. // Transformation matrix
  584. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  585. this._worldMatrix.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  586. this._processCollisionsForSubModels(collider, this._collisionsTransformMatrix);
  587. };
  588. BABYLON.Mesh.prototype.intersectsMesh = function (mesh, precise) {
  589. if (!this._boundingInfo || !mesh._boundingInfo) {
  590. return false;
  591. }
  592. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  593. };
  594. BABYLON.Mesh.prototype.intersectsPoint = function (point) {
  595. if (!this._boundingInfo) {
  596. return false;
  597. }
  598. return this._boundingInfo.intersectsPoint(point);
  599. };
  600. // Picking
  601. BABYLON.Mesh.prototype.intersects = function (ray, fastCheck) {
  602. var pickingInfo = new BABYLON.PickingInfo();
  603. if (!this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  604. return pickingInfo;
  605. }
  606. this._generatePointsArray();
  607. var intersectInfo = null;
  608. for (var index = 0; index < this.subMeshes.length; index++) {
  609. var subMesh = this.subMeshes[index];
  610. // Bounding test
  611. if (this.subMeshes.length > 1 && !subMesh.canIntersects(ray))
  612. continue;
  613. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this._indices, fastCheck);
  614. if (currentIntersectInfo) {
  615. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  616. intersectInfo = currentIntersectInfo;
  617. if (fastCheck) {
  618. break;
  619. }
  620. }
  621. }
  622. }
  623. if (intersectInfo) {
  624. // Get picked point
  625. var world = this.getWorldMatrix();
  626. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  627. var direction = ray.direction.clone();
  628. direction.normalize();
  629. direction = direction.scale(intersectInfo.distance);
  630. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  631. var pickedPoint = worldOrigin.add(worldDirection);
  632. // Return result
  633. pickingInfo.hit = true;
  634. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  635. pickingInfo.pickedPoint = pickedPoint;
  636. pickingInfo.pickedMesh = this;
  637. pickingInfo.bu = intersectInfo.bu;
  638. pickingInfo.bv = intersectInfo.bv;
  639. pickingInfo.faceId = intersectInfo.faceId;
  640. return pickingInfo;
  641. }
  642. return pickingInfo;
  643. };
  644. // Clone
  645. BABYLON.Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  646. var result = new BABYLON.Mesh(name, this._scene);
  647. // Buffers
  648. result._vertexBuffers = this._vertexBuffers;
  649. for (var kind in result._vertexBuffers) {
  650. result._vertexBuffers[kind].references++;
  651. }
  652. result._indexBuffer = this._indexBuffer;
  653. this._indexBuffer.references++;
  654. // Deep copy
  655. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], ["_indices", "_totalVertices"]);
  656. // Bounding info
  657. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this._totalVertices);
  658. result._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  659. // Material
  660. result.material = this.material;
  661. // Parent
  662. if (newParent) {
  663. result.parent = newParent;
  664. }
  665. if (!doNotCloneChildren) {
  666. // Children
  667. for (var index = 0; index < this._scene.meshes.length; index++) {
  668. var mesh = this._scene.meshes[index];
  669. if (mesh.parent == this) {
  670. mesh.clone(mesh.name, result);
  671. }
  672. }
  673. }
  674. // Particles
  675. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  676. var system = this._scene.particleSystems[index];
  677. if (system.emitter == this) {
  678. system.clone(system.name, result);
  679. }
  680. }
  681. result.computeWorldMatrix(true);
  682. return result;
  683. };
  684. // Dispose
  685. BABYLON.Mesh.prototype.dispose = function (doNotRecurse) {
  686. if (this._vertexBuffers) {
  687. for (var vbKind in this._vertexBuffers) {
  688. this._vertexBuffers[vbKind].dispose();
  689. }
  690. this._vertexBuffers = null;
  691. }
  692. if (this._indexBuffer) {
  693. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  694. this._indexBuffer = null;
  695. }
  696. // Remove from scene
  697. var index = this._scene.meshes.indexOf(this);
  698. this._scene.meshes.splice(index, 1);
  699. if (!doNotRecurse) {
  700. // Particles
  701. for (var index = 0; index < this._scene.particleSystems.length; index++) {
  702. if (this._scene.particleSystems[index].emitter == this) {
  703. this._scene.particleSystems[index].dispose();
  704. index--;
  705. }
  706. }
  707. // Children
  708. var objects = this._scene.meshes.slice(0);
  709. for (var index = 0; index < objects.length; index++) {
  710. if (objects[index].parent == this) {
  711. objects[index].dispose();
  712. }
  713. }
  714. } else {
  715. for (var index = 0; index < this._scene.meshes.length; index++) {
  716. var obj = this._scene.meshes[index];
  717. if (obj.parent === this) {
  718. obj.parent = null;
  719. obj.computeWorldMatrix(true);
  720. }
  721. }
  722. }
  723. this._isDisposed = true;
  724. // Callback
  725. if (this.onDispose) {
  726. this.onDispose();
  727. }
  728. };
  729. // Physics
  730. BABYLON.Mesh.prototype.setPhysicsState = function (options) {
  731. if (!this._scene._physicsEngine) {
  732. return;
  733. }
  734. options.impostor = options.impostor || BABYLON.PhysicsEngine.NoImpostor;
  735. options.mass = options.mass || 0;
  736. options.friction = options.friction || 0.2;
  737. options.restitution = options.restitution || 0.9;
  738. this._physicImpostor = options.impostor;
  739. this._physicsMass = options.mass;
  740. this._physicsFriction = options.friction;
  741. this._physicRestitution = options.restitution;
  742. if (options.impostor === BABYLON.PhysicsEngine.NoImpostor) {
  743. this._scene._physicsEngine._unregisterMesh(this);
  744. return;
  745. }
  746. this._scene._physicsEngine._registerMesh(this, options);
  747. };
  748. BABYLON.Mesh.prototype.getPhysicsImpostor = function () {
  749. if (!this._physicImpostor) {
  750. return BABYLON.PhysicsEngine.NoImpostor;
  751. }
  752. return this._physicImpostor;
  753. };
  754. BABYLON.Mesh.prototype.getPhysicsMass = function () {
  755. if (!this._physicsMass) {
  756. return 0;
  757. }
  758. return this._physicsMass;
  759. };
  760. BABYLON.Mesh.prototype.getPhysicsFriction = function () {
  761. if (!this._physicsFriction) {
  762. return 0;
  763. }
  764. return this._physicsFriction;
  765. };
  766. BABYLON.Mesh.prototype.getPhysicsRestitution = function () {
  767. if (!this._physicRestitution) {
  768. return 0;
  769. }
  770. return this._physicRestitution;
  771. };
  772. BABYLON.Mesh.prototype.applyImpulse = function (force, contactPoint) {
  773. if (!this._physicImpostor) {
  774. return;
  775. }
  776. this._scene._physicsEngine._applyImpulse(this, force, contactPoint);
  777. };
  778. BABYLON.Mesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2) {
  779. if (!this._physicImpostor) {
  780. return;
  781. }
  782. this._scene._physicsEngine._createLink(this, otherMesh, pivot1, pivot2);
  783. };
  784. // Geometric tools
  785. BABYLON.Mesh.prototype.convertToFlatShadedMesh = function () {
  786. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  787. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  788. var kinds = this.getVerticesDataKinds();
  789. var vbs = [];
  790. var data = [];
  791. var newdata = [];
  792. var updatableNormals = false;
  793. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  794. var kind = kinds[kindIndex];
  795. if (kind === BABYLON.VertexBuffer.NormalKind) {
  796. updatableNormals = this.getVertexBuffer(kind).isUpdatable();
  797. kinds.splice(kindIndex, 1);
  798. kindIndex--;
  799. continue;
  800. }
  801. vbs[kind] = this.getVertexBuffer(kind);
  802. data[kind] = vbs[kind].getData();
  803. newdata[kind] = [];
  804. }
  805. // Save previous submeshes
  806. var previousSubmeshes = this.subMeshes.slice(0);
  807. var indices = this.getIndices();
  808. // Generating unique vertices per face
  809. for (var index = 0; index < indices.length; index++) {
  810. var vertexIndex = indices[index];
  811. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  812. var kind = kinds[kindIndex];
  813. var stride = vbs[kind].getStrideSize();
  814. for (var offset = 0; offset < stride; offset++) {
  815. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  816. }
  817. }
  818. }
  819. // Updating faces & normal
  820. var normals = [];
  821. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  822. for (var index = 0; index < indices.length; index += 3) {
  823. indices[index] = index;
  824. indices[index + 1] = index + 1;
  825. indices[index + 2] = index + 2;
  826. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  827. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  828. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  829. var p1p2 = p1.subtract(p2);
  830. var p3p2 = p3.subtract(p2);
  831. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  832. // Store same normals for every vertex
  833. for (var localIndex = 0; localIndex < 3; localIndex++) {
  834. normals.push(normal.x);
  835. normals.push(normal.y);
  836. normals.push(normal.z);
  837. }
  838. }
  839. this.setIndices(indices);
  840. this.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatableNormals);
  841. // Updating vertex buffers
  842. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  843. var kind = kinds[kindIndex];
  844. this.setVerticesData(newdata[kind], kind, vbs[kind].isUpdatable());
  845. }
  846. // Updating submeshes
  847. this.subMeshes = [];
  848. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  849. var previousOne = previousSubmeshes[submeshIndex];
  850. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  851. }
  852. };
  853. // Statics
  854. BABYLON.Mesh.CreateBox = function (name, size, scene, updatable) {
  855. var box = new BABYLON.Mesh(name, scene);
  856. var normalsSource = [
  857. new BABYLON.Vector3(0, 0, 1),
  858. new BABYLON.Vector3(0, 0, -1),
  859. new BABYLON.Vector3(1, 0, 0),
  860. new BABYLON.Vector3(-1, 0, 0),
  861. new BABYLON.Vector3(0, 1, 0),
  862. new BABYLON.Vector3(0, -1, 0)
  863. ];
  864. var indices = [];
  865. var positions = [];
  866. var normals = [];
  867. var uvs = [];
  868. // Create each face in turn.
  869. for (var index = 0; index < normalsSource.length; index++) {
  870. var normal = normalsSource[index];
  871. // Get two vectors perpendicular to the face normal and to each other.
  872. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  873. var side2 = BABYLON.Vector3.Cross(normal, side1);
  874. // Six indices (two triangles) per face.
  875. var verticesLength = positions.length / 3;
  876. indices.push(verticesLength);
  877. indices.push(verticesLength + 1);
  878. indices.push(verticesLength + 2);
  879. indices.push(verticesLength);
  880. indices.push(verticesLength + 2);
  881. indices.push(verticesLength + 3);
  882. // Four vertices per face.
  883. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  884. positions.push(vertex.x, vertex.y, vertex.z);
  885. normals.push(normal.x, normal.y, normal.z);
  886. uvs.push(1.0, 1.0);
  887. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  888. positions.push(vertex.x, vertex.y, vertex.z);
  889. normals.push(normal.x, normal.y, normal.z);
  890. uvs.push(0.0, 1.0);
  891. vertex = normal.add(side1).add(side2).scale(size / 2);
  892. positions.push(vertex.x, vertex.y, vertex.z);
  893. normals.push(normal.x, normal.y, normal.z);
  894. uvs.push(0.0, 0.0);
  895. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  896. positions.push(vertex.x, vertex.y, vertex.z);
  897. normals.push(normal.x, normal.y, normal.z);
  898. uvs.push(1.0, 0.0);
  899. }
  900. box.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  901. box.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  902. box.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  903. box.setIndices(indices);
  904. return box;
  905. };
  906. BABYLON.Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  907. var sphere = new BABYLON.Mesh(name, scene);
  908. var radius = diameter / 2;
  909. var totalZRotationSteps = 2 + segments;
  910. var totalYRotationSteps = 2 * totalZRotationSteps;
  911. var indices = [];
  912. var positions = [];
  913. var normals = [];
  914. var uvs = [];
  915. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  916. var normalizedZ = zRotationStep / totalZRotationSteps;
  917. var angleZ = (normalizedZ * Math.PI);
  918. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  919. var normalizedY = yRotationStep / totalYRotationSteps;
  920. var angleY = normalizedY * Math.PI * 2;
  921. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  922. var rotationY = BABYLON.Matrix.RotationY(angleY);
  923. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  924. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  925. var vertex = complete.scale(radius);
  926. var normal = BABYLON.Vector3.Normalize(vertex);
  927. positions.push(vertex.x, vertex.y, vertex.z);
  928. normals.push(normal.x, normal.y, normal.z);
  929. uvs.push(normalizedZ, normalizedY);
  930. }
  931. if (zRotationStep > 0) {
  932. var verticesCount = positions.length / 3;
  933. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1) ; (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  934. indices.push((firstIndex));
  935. indices.push((firstIndex + 1));
  936. indices.push(firstIndex + totalYRotationSteps + 1);
  937. indices.push((firstIndex + totalYRotationSteps + 1));
  938. indices.push((firstIndex + 1));
  939. indices.push((firstIndex + totalYRotationSteps + 2));
  940. }
  941. }
  942. }
  943. sphere.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  944. sphere.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  945. sphere.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  946. sphere.setIndices(indices);
  947. return sphere;
  948. };
  949. // Cylinder and cone (Code inspired by SharpDX.org)
  950. BABYLON.Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, scene, updatable) {
  951. var radiusTop = diameterTop / 2;
  952. var radiusBottom = diameterBottom / 2;
  953. var indices = [];
  954. var positions = [];
  955. var normals = [];
  956. var uvs = [];
  957. var cylinder = new BABYLON.Mesh(name, scene);
  958. var getCircleVector = function (i) {
  959. var angle = (i * 2.0 * Math.PI / tessellation);
  960. var dx = Math.sin(angle);
  961. var dz = Math.cos(angle);
  962. return new BABYLON.Vector3(dx, 0, dz);
  963. };
  964. var createCylinderCap = function (isTop) {
  965. var radius = isTop ? radiusTop : radiusBottom;
  966. if (radius == 0) {
  967. return;
  968. }
  969. // Create cap indices.
  970. for (var i = 0; i < tessellation - 2; i++) {
  971. var i1 = (i + 1) % tessellation;
  972. var i2 = (i + 2) % tessellation;
  973. if (!isTop) {
  974. var tmp = i1;
  975. var i1 = i2;
  976. i2 = tmp;
  977. }
  978. var vbase = positions.length / 3;
  979. indices.push(vbase);
  980. indices.push(vbase + i1);
  981. indices.push(vbase + i2);
  982. }
  983. // Which end of the cylinder is this?
  984. var normal = new BABYLON.Vector3(0, -1, 0);
  985. var textureScale = new BABYLON.Vector2(-0.5, -0.5);
  986. if (!isTop) {
  987. normal = normal.scale(-1);
  988. textureScale.x = -textureScale.x;
  989. }
  990. // Create cap vertices.
  991. for (var i = 0; i < tessellation; i++) {
  992. var circleVector = getCircleVector(i);
  993. var position = circleVector.scale(radius).add(normal.scale(height));
  994. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  995. positions.push(position.x, position.y, position.z);
  996. normals.push(normal.x, normal.y, normal.z);
  997. uvs.push(textureCoordinate.x, textureCoordinate.y);
  998. }
  999. };
  1000. height /= 2;
  1001. var topOffset = new BABYLON.Vector3(0, 1, 0).scale(height);
  1002. var stride = tessellation + 1;
  1003. // Create a ring of triangles around the outside of the cylinder.
  1004. for (var i = 0; i <= tessellation; i++) {
  1005. var normal = getCircleVector(i);
  1006. var sideOffsetBottom = normal.scale(radiusBottom);
  1007. var sideOffsetTop = normal.scale(radiusTop);
  1008. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  1009. var position = sideOffsetBottom.add(topOffset);
  1010. positions.push(position.x, position.y, position.z);
  1011. normals.push(normal.x, normal.y, normal.z);
  1012. uvs.push(textureCoordinate.x, textureCoordinate.y);
  1013. position = sideOffsetTop.subtract(topOffset);
  1014. textureCoordinate.y += 1;
  1015. positions.push(position.x, position.y, position.z);
  1016. normals.push(normal.x, normal.y, normal.z);
  1017. uvs.push(textureCoordinate.x, textureCoordinate.y);
  1018. indices.push(i * 2);
  1019. indices.push((i * 2 + 2) % (stride * 2));
  1020. indices.push(i * 2 + 1);
  1021. indices.push(i * 2 + 1);
  1022. indices.push((i * 2 + 2) % (stride * 2));
  1023. indices.push((i * 2 + 3) % (stride * 2));
  1024. }
  1025. // Create flat triangle fan caps to seal the top and bottom.
  1026. createCylinderCap(true);
  1027. createCylinderCap(false);
  1028. cylinder.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1029. cylinder.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1030. cylinder.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1031. cylinder.setIndices(indices);
  1032. return cylinder;
  1033. };
  1034. // Torus (Code from SharpDX.org)
  1035. BABYLON.Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  1036. var torus = new BABYLON.Mesh(name, scene);
  1037. var indices = [];
  1038. var positions = [];
  1039. var normals = [];
  1040. var uvs = [];
  1041. var stride = tessellation + 1;
  1042. for (var i = 0; i <= tessellation; i++) {
  1043. var u = i / tessellation;
  1044. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  1045. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  1046. for (var j = 0; j <= tessellation; j++) {
  1047. var v = 1 - j / tessellation;
  1048. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  1049. var dx = Math.cos(innerAngle);
  1050. var dy = Math.sin(innerAngle);
  1051. // Create a vertex.
  1052. var normal = new BABYLON.Vector3(dx, dy, 0);
  1053. var position = normal.scale(thickness / 2);
  1054. var textureCoordinate = new BABYLON.Vector2(u, v);
  1055. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  1056. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  1057. positions.push(position.x, position.y, position.z);
  1058. normals.push(normal.x, normal.y, normal.z);
  1059. uvs.push(textureCoordinate.x, textureCoordinate.y);
  1060. // And create indices for two triangles.
  1061. var nextI = (i + 1) % stride;
  1062. var nextJ = (j + 1) % stride;
  1063. indices.push(i * stride + j);
  1064. indices.push(i * stride + nextJ);
  1065. indices.push(nextI * stride + j);
  1066. indices.push(i * stride + nextJ);
  1067. indices.push(nextI * stride + nextJ);
  1068. indices.push(nextI * stride + j);
  1069. }
  1070. }
  1071. torus.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1072. torus.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1073. torus.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1074. torus.setIndices(indices);
  1075. return torus;
  1076. };
  1077. // Plane
  1078. BABYLON.Mesh.CreatePlane = function (name, size, scene, updatable) {
  1079. var plane = new BABYLON.Mesh(name, scene);
  1080. var indices = [];
  1081. var positions = [];
  1082. var normals = [];
  1083. var uvs = [];
  1084. // Vertices
  1085. var halfSize = size / 2.0;
  1086. positions.push(-halfSize, -halfSize, 0);
  1087. normals.push(0, 0, -1.0);
  1088. uvs.push(0.0, 0.0);
  1089. positions.push(halfSize, -halfSize, 0);
  1090. normals.push(0, 0, -1.0);
  1091. uvs.push(1.0, 0.0);
  1092. positions.push(halfSize, halfSize, 0);
  1093. normals.push(0, 0, -1.0);
  1094. uvs.push(1.0, 1.0);
  1095. positions.push(-halfSize, halfSize, 0);
  1096. normals.push(0, 0, -1.0);
  1097. uvs.push(0.0, 1.0);
  1098. // Indices
  1099. indices.push(0);
  1100. indices.push(1);
  1101. indices.push(2);
  1102. indices.push(0);
  1103. indices.push(2);
  1104. indices.push(3);
  1105. plane.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1106. plane.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1107. plane.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1108. plane.setIndices(indices);
  1109. return plane;
  1110. };
  1111. BABYLON.Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  1112. var ground = new BABYLON.Mesh(name, scene);
  1113. var indices = [];
  1114. var positions = [];
  1115. var normals = [];
  1116. var uvs = [];
  1117. var row, col;
  1118. for (row = 0; row <= subdivisions; row++) {
  1119. for (col = 0; col <= subdivisions; col++) {
  1120. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  1121. var normal = new BABYLON.Vector3(0, 1.0, 0);
  1122. positions.push(position.x, position.y, position.z);
  1123. normals.push(normal.x, normal.y, normal.z);
  1124. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  1125. }
  1126. }
  1127. for (row = 0; row < subdivisions; row++) {
  1128. for (col = 0; col < subdivisions; col++) {
  1129. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1130. indices.push(col + 1 + row * (subdivisions + 1));
  1131. indices.push(col + row * (subdivisions + 1));
  1132. indices.push(col + (row + 1) * (subdivisions + 1));
  1133. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1134. indices.push(col + row * (subdivisions + 1));
  1135. }
  1136. }
  1137. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1138. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1139. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1140. ground.setIndices(indices);
  1141. return ground;
  1142. };
  1143. BABYLON.Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  1144. var ground = new BABYLON.Mesh(name, scene);
  1145. var onload = function (img) {
  1146. var indices = [];
  1147. var positions = [];
  1148. var normals = [];
  1149. var uvs = [];
  1150. var row, col;
  1151. // Getting height map data
  1152. var canvas = document.createElement("canvas");
  1153. var context = canvas.getContext("2d");
  1154. var heightMapWidth = img.width;
  1155. var heightMapHeight = img.height;
  1156. canvas.width = heightMapWidth;
  1157. canvas.height = heightMapHeight;
  1158. context.drawImage(img, 0, 0);
  1159. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  1160. // Vertices
  1161. for (row = 0; row <= subdivisions; row++) {
  1162. for (col = 0; col <= subdivisions; col++) {
  1163. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  1164. // Compute height
  1165. var heightMapX = (((position.x + width / 2) / width) * (heightMapWidth - 1)) | 0;
  1166. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (heightMapHeight - 1)) | 0;
  1167. var pos = (heightMapX + heightMapY * heightMapWidth) * 4;
  1168. var r = buffer[pos] / 255.0;
  1169. var g = buffer[pos + 1] / 255.0;
  1170. var b = buffer[pos + 2] / 255.0;
  1171. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  1172. position.y = minHeight + (maxHeight - minHeight) * gradient;
  1173. // Add vertex
  1174. positions.push(position.x, position.y, position.z);
  1175. normals.push(0, 0, 0);
  1176. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  1177. }
  1178. }
  1179. // Indices
  1180. for (row = 0; row < subdivisions; row++) {
  1181. for (col = 0; col < subdivisions; col++) {
  1182. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1183. indices.push(col + 1 + row * (subdivisions + 1));
  1184. indices.push(col + row * (subdivisions + 1));
  1185. indices.push(col + (row + 1) * (subdivisions + 1));
  1186. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  1187. indices.push(col + row * (subdivisions + 1));
  1188. }
  1189. }
  1190. // Normals
  1191. BABYLON.Mesh.ComputeNormal(positions, normals, indices);
  1192. // Transfer
  1193. ground.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  1194. ground.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  1195. ground.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  1196. ground.setIndices(indices);
  1197. ground._isReady = true;
  1198. };
  1199. BABYLON.Tools.LoadImage(url, onload, scene.database);
  1200. ground._isReady = false;
  1201. return ground;
  1202. };
  1203. // Tools
  1204. BABYLON.Mesh.ComputeNormal = function (positions, normals, indices) {
  1205. var positionVectors = [];
  1206. var facesOfVertices = [];
  1207. var index;
  1208. for (index = 0; index < positions.length; index += 3) {
  1209. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  1210. positionVectors.push(vector3);
  1211. facesOfVertices.push([]);
  1212. }
  1213. // Compute normals
  1214. var facesNormals = [];
  1215. for (index = 0; index < indices.length / 3; index++) {
  1216. var i1 = indices[index * 3];
  1217. var i2 = indices[index * 3 + 1];
  1218. var i3 = indices[index * 3 + 2];
  1219. var p1 = positionVectors[i1];
  1220. var p2 = positionVectors[i2];
  1221. var p3 = positionVectors[i3];
  1222. var p1p2 = p1.subtract(p2);
  1223. var p3p2 = p3.subtract(p2);
  1224. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  1225. facesOfVertices[i1].push(index);
  1226. facesOfVertices[i2].push(index);
  1227. facesOfVertices[i3].push(index);
  1228. }
  1229. for (index = 0; index < positionVectors.length; index++) {
  1230. var faces = facesOfVertices[index];
  1231. var normal = BABYLON.Vector3.Zero();
  1232. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  1233. normal.addInPlace(facesNormals[faces[faceIndex]]);
  1234. }
  1235. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  1236. normals[index * 3] = normal.x;
  1237. normals[index * 3 + 1] = normal.y;
  1238. normals[index * 3 + 2] = normal.z;
  1239. }
  1240. };
  1241. })();