babylon.collisionWorker.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. for (var uniqueId in meshes) {
  43. if (meshes.hasOwnProperty(uniqueId) && parseInt(uniqueId) != excludedMeshUniqueId) {
  44. var mesh: SerializedMesh = meshes[uniqueId];
  45. if (mesh.checkCollisions)
  46. this.checkCollision(mesh);
  47. }
  48. }
  49. if (!this.collider.collisionFound) {
  50. position.addToRef(velocity, this.finalPosition);
  51. return;
  52. }
  53. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54. this.collider._getResponse(position, velocity);
  55. }
  56. if (velocity.length() <= closeDistance) {
  57. this.finalPosition.copyFrom(position);
  58. return;
  59. }
  60. this.collider.retry++;
  61. this.collideWithWorld(position, velocity, maximumRetry, excludedMeshUniqueId);
  62. }
  63. private checkCollision(mesh: SerializedMesh) {
  64. if (!this.collider._canDoCollision(BABYLON.Vector3.FromArray(mesh.sphereCenter), mesh.sphereRadius, BABYLON.Vector3.FromArray(mesh.boxMinimum), BABYLON.Vector3.FromArray(mesh.boxMaximum))) {
  65. return;
  66. };
  67. // Transformation matrix
  68. BABYLON.Matrix.ScalingToRef(1.0 / this.collider.radius.x, 1.0 / this.collider.radius.y, 1.0 / this.collider.radius.z, this.collisionsScalingMatrix);
  69. var worldFromCache = BABYLON.Matrix.FromArray(mesh.worldMatrixFromCache);
  70. worldFromCache.multiplyToRef(this.collisionsScalingMatrix, this.collisionTranformationMatrix);
  71. this.processCollisionsForSubMeshes(this.collisionTranformationMatrix, mesh);
  72. //return colTransMat;
  73. }
  74. private processCollisionsForSubMeshes(transformMatrix: BABYLON.Matrix, mesh: SerializedMesh): void {
  75. var len: number;
  76. var subMeshes;
  77. // No Octrees for now
  78. //if (this._submeshesOctree && this.useOctreeForCollisions) {
  79. // var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  80. // var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  81. // len = intersections.length;
  82. // subMeshes = intersections.data;
  83. //} else {
  84. subMeshes = mesh.subMeshes;
  85. len = subMeshes.length;
  86. //}
  87. if (!mesh.geometryId) {
  88. console.log("no mesh geometry id");
  89. return;
  90. }
  91. var meshGeometry = this._collisionCache.getGeometry(mesh.geometryId);
  92. if (!meshGeometry) {
  93. console.log("couldn't find geometry", mesh.geometryId);
  94. return;
  95. }
  96. for (var index = 0; index < len; index++) {
  97. var subMesh = subMeshes[index];
  98. // Bounding test
  99. if (len > 1 && !this.checkSubmeshCollision(subMesh))
  100. continue;
  101. //Unneeded
  102. //subMesh['getMesh'] = function () {
  103. // return mesh.uniqueId;
  104. //}
  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; i < meshGeometry.positions.length; 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. subMesh['_lastColliderTransformMatrix'] = transformMatrix.clone();
  115. //The following two arrays should be initialized CORRECTLY to save some calculation time.
  116. subMesh['_lastColliderWorldVertices'] = [];
  117. subMesh['_trianglePlanes'] = [];
  118. var start = subMesh.verticesStart;
  119. var end = (subMesh.verticesStart + subMesh.verticesCount);
  120. for (var i = start; i < end; i++) {
  121. subMesh['_lastColliderWorldVertices'].push(BABYLON.Vector3.TransformCoordinates(positionsArray[i], transformMatrix));
  122. }
  123. //}
  124. // Collide
  125. this.collider._collide(subMesh['_trianglePlanes'] = [], subMesh['_lastColliderWorldVertices'], <any> meshGeometry.indices, subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, subMesh.hasMaterial);
  126. }
  127. //TODO - this! :-)
  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. }