babylon.collisionWorker.ts 11 KB

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