babylon.mesh.js 58 KB

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