babylon.collisionWorker.ts 12 KB

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