babylon.collisionWorker.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. var BABYLON;
  2. (function (BABYLON) {
  3. //If this file is included in the main thread, this will be initialized.
  4. BABYLON.WorkerIncluded = true;
  5. var CollisionCache = (function () {
  6. function CollisionCache() {
  7. this._meshes = {};
  8. this._geometries = {};
  9. }
  10. CollisionCache.prototype.getMeshes = function () {
  11. return this._meshes;
  12. };
  13. CollisionCache.prototype.getGeometries = function () {
  14. return this._geometries;
  15. };
  16. CollisionCache.prototype.getMesh = function (id) {
  17. return this._meshes[id];
  18. };
  19. CollisionCache.prototype.addMesh = function (mesh) {
  20. this._meshes[mesh.uniqueId] = mesh;
  21. };
  22. CollisionCache.prototype.getGeometry = function (id) {
  23. return this._geometries[id];
  24. };
  25. CollisionCache.prototype.addGeometry = function (geometry) {
  26. this._geometries[geometry.id] = geometry;
  27. };
  28. return CollisionCache;
  29. })();
  30. BABYLON.CollisionCache = CollisionCache;
  31. var CollideWorker = (function () {
  32. function CollideWorker(collider, _collisionCache, finalPosition) {
  33. this.collider = collider;
  34. this._collisionCache = _collisionCache;
  35. this.finalPosition = finalPosition;
  36. this.collisionsScalingMatrix = BABYLON.Matrix.Zero();
  37. this.collisionTranformationMatrix = BABYLON.Matrix.Zero();
  38. }
  39. CollideWorker.prototype.collideWithWorld = function (position, velocity, maximumRetry, excludedMeshUniqueId) {
  40. //TODO CollisionsEpsilon should be defined here and not in the engine.
  41. var closeDistance = 0.01;
  42. //is initializing here correct? A quick look - looks like it is fine.
  43. if (this.collider.retry >= maximumRetry) {
  44. this.finalPosition.copyFrom(position);
  45. return;
  46. }
  47. this.collider._initialize(position, velocity, closeDistance);
  48. // Check all meshes
  49. var meshes = this._collisionCache.getMeshes();
  50. var keys = Object.keys(meshes);
  51. var len = keys.length;
  52. var uniqueId;
  53. for (var i = 0; i < len; ++i) {
  54. uniqueId = keys[i];
  55. if (parseInt(uniqueId) != excludedMeshUniqueId) {
  56. var mesh = meshes[uniqueId];
  57. if (mesh.checkCollisions)
  58. this.checkCollision(mesh);
  59. }
  60. }
  61. if (!this.collider.collisionFound) {
  62. position.addToRef(velocity, this.finalPosition);
  63. return;
  64. }
  65. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  66. this.collider._getResponse(position, velocity);
  67. }
  68. if (velocity.length() <= closeDistance) {
  69. this.finalPosition.copyFrom(position);
  70. return;
  71. }
  72. this.collider.retry++;
  73. this.collideWithWorld(position, velocity, maximumRetry, excludedMeshUniqueId);
  74. };
  75. CollideWorker.prototype.checkCollision = function (mesh) {
  76. if (!this.collider._canDoCollision(BABYLON.Vector3.FromArray(mesh.sphereCenter), mesh.sphereRadius, BABYLON.Vector3.FromArray(mesh.boxMinimum), BABYLON.Vector3.FromArray(mesh.boxMaximum))) {
  77. return;
  78. }
  79. ;
  80. // Transformation matrix
  81. BABYLON.Matrix.ScalingToRef(1.0 / this.collider.radius.x, 1.0 / this.collider.radius.y, 1.0 / this.collider.radius.z, this.collisionsScalingMatrix);
  82. var worldFromCache = BABYLON.Matrix.FromArray(mesh.worldMatrixFromCache);
  83. worldFromCache.multiplyToRef(this.collisionsScalingMatrix, this.collisionTranformationMatrix);
  84. this.processCollisionsForSubMeshes(this.collisionTranformationMatrix, mesh);
  85. //return colTransMat;
  86. };
  87. CollideWorker.prototype.processCollisionsForSubMeshes = function (transformMatrix, mesh) {
  88. var len;
  89. var subMeshes;
  90. // No Octrees for now
  91. //if (this._submeshesOctree && this.useOctreeForCollisions) {
  92. // var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  93. // var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  94. // len = intersections.length;
  95. // subMeshes = intersections.data;
  96. //} else {
  97. subMeshes = mesh.subMeshes;
  98. len = subMeshes.length;
  99. //}
  100. if (!mesh.geometryId) {
  101. console.log("no mesh geometry id");
  102. return;
  103. }
  104. var meshGeometry = this._collisionCache.getGeometry(mesh.geometryId);
  105. if (!meshGeometry) {
  106. console.log("couldn't find geometry", mesh.geometryId);
  107. return;
  108. }
  109. for (var index = 0; index < len; index++) {
  110. var subMesh = subMeshes[index];
  111. // Bounding test
  112. if (len > 1 && !this.checkSubmeshCollision(subMesh))
  113. continue;
  114. this.collideForSubMesh(subMesh, transformMatrix, meshGeometry);
  115. }
  116. };
  117. CollideWorker.prototype.collideForSubMesh = function (subMesh, transformMatrix, meshGeometry) {
  118. var positionsArray = [];
  119. for (var i = 0, len = meshGeometry.positions.length; i < len; i = i + 3) {
  120. var p = BABYLON.Vector3.FromArray([meshGeometry.positions[i], meshGeometry.positions[i + 1], meshGeometry.positions[i + 2]]);
  121. positionsArray.push(p);
  122. }
  123. if (!subMesh['_lastColliderWorldVertices'] || !subMesh['_lastColliderTransformMatrix'].equals(transformMatrix)) {
  124. subMesh['_lastColliderTransformMatrix'] = transformMatrix.clone();
  125. //The following two arrays should be initialized CORRECTLY to save some calculation time.
  126. subMesh['_lastColliderWorldVertices'] = [];
  127. subMesh['_trianglePlanes'] = [];
  128. var start = subMesh.verticesStart;
  129. var end = (subMesh.verticesStart + subMesh.verticesCount);
  130. for (var i = start; i < end; i++) {
  131. subMesh['_lastColliderWorldVertices'].push(BABYLON.Vector3.TransformCoordinates(positionsArray[i], transformMatrix));
  132. }
  133. }
  134. // Collide
  135. this.collider._collide(subMesh['_trianglePlanes'], subMesh['_lastColliderWorldVertices'], meshGeometry.indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, subMesh.hasMaterial);
  136. };
  137. CollideWorker.prototype.checkSubmeshCollision = function (subMesh) {
  138. return this.collider._canDoCollision(BABYLON.Vector3.FromArray(subMesh.sphereCenter), subMesh.sphereRadius, BABYLON.Vector3.FromArray(subMesh.boxMinimum), BABYLON.Vector3.FromArray(subMesh.boxMaximum));
  139. };
  140. return CollideWorker;
  141. })();
  142. BABYLON.CollideWorker = CollideWorker;
  143. var CollisionDetectorTransferable = (function () {
  144. function CollisionDetectorTransferable() {
  145. }
  146. CollisionDetectorTransferable.prototype.onInit = function (payload) {
  147. this._collisionCache = new CollisionCache();
  148. var reply = {
  149. error: BABYLON.WorkerReplyType.SUCCESS,
  150. taskType: BABYLON.WorkerTaskType.INIT
  151. };
  152. postMessage(reply, undefined);
  153. };
  154. CollisionDetectorTransferable.prototype.onUpdate = function (payload) {
  155. for (var id in payload.updatedGeometries) {
  156. if (payload.updatedGeometries.hasOwnProperty(id)) {
  157. this._collisionCache.addGeometry(payload.updatedGeometries[id]);
  158. }
  159. }
  160. for (var uniqueId in payload.updatedMeshes) {
  161. if (payload.updatedMeshes.hasOwnProperty(uniqueId)) {
  162. this._collisionCache.addMesh(payload.updatedMeshes[uniqueId]);
  163. }
  164. }
  165. var replay = {
  166. error: BABYLON.WorkerReplyType.SUCCESS,
  167. taskType: BABYLON.WorkerTaskType.UPDATE
  168. };
  169. postMessage(replay, undefined);
  170. };
  171. CollisionDetectorTransferable.prototype.onCollision = function (payload) {
  172. var finalPosition = BABYLON.Vector3.Zero();
  173. //create a new collider
  174. var collider = new BABYLON.Collider();
  175. collider.radius = BABYLON.Vector3.FromArray(payload.collider.radius);
  176. var colliderWorker = new CollideWorker(collider, this._collisionCache, finalPosition);
  177. colliderWorker.collideWithWorld(BABYLON.Vector3.FromArray(payload.collider.position), BABYLON.Vector3.FromArray(payload.collider.velocity), payload.maximumRetry, payload.excludedMeshUniqueId);
  178. var replyPayload = {
  179. collidedMeshUniqueId: collider.collidedMesh,
  180. collisionId: payload.collisionId,
  181. newPosition: finalPosition.asArray()
  182. };
  183. var reply = {
  184. error: BABYLON.WorkerReplyType.SUCCESS,
  185. taskType: BABYLON.WorkerTaskType.COLLIDE,
  186. payload: replyPayload
  187. };
  188. postMessage(reply, undefined);
  189. };
  190. return CollisionDetectorTransferable;
  191. })();
  192. BABYLON.CollisionDetectorTransferable = CollisionDetectorTransferable;
  193. try {
  194. if (self && self instanceof WorkerGlobalScope) {
  195. //Window hack to allow including babylonjs native code. the <any> is for typescript.
  196. window = {};
  197. //scripts were not included, standalone worker
  198. if (!BABYLON.Collider) {
  199. importScripts("./babylon.collisionCoordinator.js");
  200. importScripts("./babylon.collider.js");
  201. importScripts("../Math/babylon.math.js");
  202. }
  203. var collisionDetector = new CollisionDetectorTransferable();
  204. var onNewMessage = function (event) {
  205. var message = event.data;
  206. switch (message.taskType) {
  207. case BABYLON.WorkerTaskType.INIT:
  208. collisionDetector.onInit(message.payload);
  209. break;
  210. case BABYLON.WorkerTaskType.COLLIDE:
  211. collisionDetector.onCollision(message.payload);
  212. break;
  213. case BABYLON.WorkerTaskType.UPDATE:
  214. collisionDetector.onUpdate(message.payload);
  215. break;
  216. }
  217. };
  218. self.onmessage = onNewMessage;
  219. }
  220. }
  221. catch (e) {
  222. console.log("single worker init");
  223. }
  224. })(BABYLON || (BABYLON = {}));
  225. //# sourceMappingURL=babylon.collisionWorker.js.map