babylon.collisionCoordinator.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. module BABYLON {
  2. //WebWorker code will be inserted to this variable.
  3. export var CollisionWorker = "";
  4. export interface ICollisionCoordinator {
  5. getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: Nullable<AbstractMesh>, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable<AbstractMesh>) => void, collisionIndex: number): void;
  6. init(scene: Scene): void;
  7. destroy(): void;
  8. //Update meshes and geometries
  9. onMeshAdded(mesh: AbstractMesh): void;
  10. onMeshUpdated(mesh: AbstractMesh): void;
  11. onMeshRemoved(mesh: AbstractMesh): void;
  12. onGeometryAdded(geometry: Geometry): void;
  13. onGeometryUpdated(geometry: Geometry): void;
  14. onGeometryDeleted(geometry: Geometry): void;
  15. }
  16. export interface SerializedMesh {
  17. id: string;
  18. name: string;
  19. uniqueId: number;
  20. geometryId: Nullable<string>;
  21. sphereCenter: Array<number>;
  22. sphereRadius: number;
  23. boxMinimum: Array<number>;
  24. boxMaximum: Array<number>;
  25. worldMatrixFromCache: any;
  26. subMeshes: Array<SerializedSubMesh>;
  27. checkCollisions: boolean;
  28. }
  29. export interface SerializedSubMesh {
  30. position: number;
  31. verticesStart: number;
  32. verticesCount: number;
  33. indexStart: number;
  34. indexCount: number;
  35. hasMaterial: boolean;
  36. sphereCenter: Array<number>;
  37. sphereRadius: number;
  38. boxMinimum: Array<number>;
  39. boxMaximum: Array<number>;
  40. }
  41. export interface SerializedGeometry {
  42. id: string;
  43. positions: Float32Array;
  44. indices: Uint32Array;
  45. normals: Float32Array;
  46. //uvs?: Float32Array;
  47. }
  48. export interface BabylonMessage {
  49. taskType: WorkerTaskType;
  50. payload: InitPayload | CollidePayload | UpdatePayload /*any for TS under 1.4*/;
  51. }
  52. export interface SerializedColliderToWorker {
  53. position: Array<number>;
  54. velocity: Array<number>;
  55. radius: Array<number>;
  56. }
  57. export enum WorkerTaskType {
  58. INIT,
  59. UPDATE,
  60. COLLIDE
  61. }
  62. export interface WorkerReply {
  63. error: WorkerReplyType;
  64. taskType: WorkerTaskType;
  65. payload?: any;
  66. }
  67. export interface CollisionReplyPayload {
  68. newPosition: Array<number>;
  69. collisionId: number;
  70. collidedMeshUniqueId: number;
  71. }
  72. export interface InitPayload {
  73. }
  74. export interface CollidePayload {
  75. collisionId: number;
  76. collider: SerializedColliderToWorker;
  77. maximumRetry: number;
  78. excludedMeshUniqueId: Nullable<number>;
  79. }
  80. export interface UpdatePayload {
  81. updatedMeshes: { [n: number]: SerializedMesh; };
  82. updatedGeometries: { [s: string]: SerializedGeometry; };
  83. removedMeshes: Array<number>;
  84. removedGeometries: Array<string>;
  85. }
  86. export enum WorkerReplyType {
  87. SUCCESS,
  88. UNKNOWN_ERROR
  89. }
  90. export class CollisionCoordinatorWorker implements ICollisionCoordinator {
  91. private _scene: Scene;
  92. private _scaledPosition = Vector3.Zero();
  93. private _scaledVelocity = Vector3.Zero();
  94. private _collisionsCallbackArray: Array<Nullable<(collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable<AbstractMesh>) => void>>;
  95. private _init: boolean;
  96. private _runningUpdated: number;
  97. private _worker: Worker;
  98. private _addUpdateMeshesList: { [n: number]: SerializedMesh; }
  99. private _addUpdateGeometriesList: { [s: string]: SerializedGeometry; };
  100. private _toRemoveMeshesArray: Array<number>;
  101. private _toRemoveGeometryArray: Array<string>;
  102. constructor() {
  103. this._collisionsCallbackArray = [];
  104. this._init = false;
  105. this._runningUpdated = 0;
  106. this._addUpdateMeshesList = {};
  107. this._addUpdateGeometriesList = {};
  108. this._toRemoveGeometryArray = [];
  109. this._toRemoveMeshesArray = [];
  110. }
  111. public static SerializeMesh = function (mesh: AbstractMesh): SerializedMesh {
  112. var submeshes: Array<SerializedSubMesh> = [];
  113. if (mesh.subMeshes) {
  114. submeshes = mesh.subMeshes.map(function (sm, idx) {
  115. let boundingInfo = sm.getBoundingInfo();
  116. return {
  117. position: idx,
  118. verticesStart: sm.verticesStart,
  119. verticesCount: sm.verticesCount,
  120. indexStart: sm.indexStart,
  121. indexCount: sm.indexCount,
  122. hasMaterial: !!sm.getMaterial(),
  123. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  124. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  125. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  126. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  127. }
  128. });
  129. }
  130. var geometryId: Nullable<string> = null;
  131. if (mesh instanceof Mesh) {
  132. let geometry = (<Mesh>mesh).geometry;
  133. geometryId = geometry ? geometry.id : null;
  134. } else if (mesh instanceof InstancedMesh) {
  135. let geometry = (<InstancedMesh>mesh).sourceMesh.geometry;
  136. geometryId = geometry ? geometry.id : null;
  137. }
  138. let boundingInfo = mesh.getBoundingInfo();
  139. return {
  140. uniqueId: mesh.uniqueId,
  141. id: mesh.id,
  142. name: mesh.name,
  143. geometryId: geometryId,
  144. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  145. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  146. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  147. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  148. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  149. subMeshes: submeshes,
  150. checkCollisions: mesh.checkCollisions
  151. }
  152. }
  153. public static SerializeGeometry = function (geometry: Geometry): SerializedGeometry {
  154. return {
  155. id: geometry.id,
  156. positions: new Float32Array(geometry.getVerticesData(VertexBuffer.PositionKind) || []),
  157. normals: new Float32Array(geometry.getVerticesData(VertexBuffer.NormalKind) || []),
  158. indices: new Uint32Array(geometry.getIndices() || []),
  159. //uvs: new Float32Array(geometry.getVerticesData(VertexBuffer.UVKind) || [])
  160. }
  161. }
  162. public getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable<AbstractMesh>) => void, collisionIndex: number): void {
  163. if (!this._init) return;
  164. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000]) return;
  165. position.divideToRef(collider._radius, this._scaledPosition);
  166. displacement.divideToRef(collider._radius, this._scaledVelocity);
  167. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  168. var payload: CollidePayload = {
  169. collider: {
  170. position: this._scaledPosition.asArray(),
  171. velocity: this._scaledVelocity.asArray(),
  172. radius: collider._radius.asArray()
  173. },
  174. collisionId: collisionIndex,
  175. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  176. maximumRetry: maximumRetry
  177. };
  178. var message: BabylonMessage = {
  179. payload: payload,
  180. taskType: WorkerTaskType.COLLIDE
  181. }
  182. this._worker.postMessage(message);
  183. }
  184. public init(scene: Scene): void {
  185. this._scene = scene;
  186. this._scene.registerAfterRender(this._afterRender);
  187. var workerUrl = WorkerIncluded ? Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([CollisionWorker], { type: 'application/javascript' }));
  188. this._worker = new Worker(workerUrl);
  189. this._worker.onmessage = this._onMessageFromWorker;
  190. var message: BabylonMessage = {
  191. payload: {},
  192. taskType: WorkerTaskType.INIT
  193. }
  194. this._worker.postMessage(message);
  195. }
  196. public destroy(): void {
  197. this._scene.unregisterAfterRender(this._afterRender);
  198. this._worker.terminate();
  199. }
  200. public onMeshAdded(mesh: AbstractMesh) {
  201. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  202. this.onMeshUpdated(mesh);
  203. }
  204. public onMeshUpdated = (transformNode: TransformNode) => {
  205. this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode as AbstractMesh);
  206. }
  207. public onMeshRemoved(mesh: AbstractMesh) {
  208. this._toRemoveMeshesArray.push(mesh.uniqueId);
  209. }
  210. public onGeometryAdded(geometry: Geometry) {
  211. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  212. geometry.onGeometryUpdated = this.onGeometryUpdated;
  213. this.onGeometryUpdated(geometry);
  214. }
  215. public onGeometryUpdated = (geometry: Geometry) => {
  216. this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  217. }
  218. public onGeometryDeleted(geometry: Geometry) {
  219. this._toRemoveGeometryArray.push(geometry.id);
  220. }
  221. private _afterRender = () => {
  222. if (!this._init) return;
  223. if (this._toRemoveGeometryArray.length == 0 && this._toRemoveMeshesArray.length == 0 && Object.keys(this._addUpdateGeometriesList).length == 0 && Object.keys(this._addUpdateMeshesList).length == 0) {
  224. return;
  225. }
  226. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  227. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  228. if (this._runningUpdated > 4) {
  229. return;
  230. }
  231. ++this._runningUpdated;
  232. var payload: UpdatePayload = {
  233. updatedMeshes: this._addUpdateMeshesList,
  234. updatedGeometries: this._addUpdateGeometriesList,
  235. removedGeometries: this._toRemoveGeometryArray,
  236. removedMeshes: this._toRemoveMeshesArray
  237. };
  238. var message: BabylonMessage = {
  239. payload: payload,
  240. taskType: WorkerTaskType.UPDATE
  241. }
  242. var serializable = [];
  243. for (var id in payload.updatedGeometries) {
  244. if (payload.updatedGeometries.hasOwnProperty(id)) {
  245. //prepare transferables
  246. serializable.push((<UpdatePayload>message.payload).updatedGeometries[id].indices.buffer);
  247. serializable.push((<UpdatePayload>message.payload).updatedGeometries[id].normals.buffer);
  248. serializable.push((<UpdatePayload>message.payload).updatedGeometries[id].positions.buffer);
  249. }
  250. }
  251. this._worker.postMessage(message, serializable);
  252. this._addUpdateMeshesList = {};
  253. this._addUpdateGeometriesList = {};
  254. this._toRemoveGeometryArray = [];
  255. this._toRemoveMeshesArray = [];
  256. }
  257. private _onMessageFromWorker = (e: MessageEvent) => {
  258. var returnData = <WorkerReply>e.data;
  259. if (returnData.error != WorkerReplyType.SUCCESS) {
  260. //TODO what errors can be returned from the worker?
  261. Tools.Warn("error returned from worker!");
  262. return;
  263. }
  264. switch (returnData.taskType) {
  265. case WorkerTaskType.INIT:
  266. this._init = true;
  267. //Update the worked with ALL of the scene's current state
  268. this._scene.meshes.forEach((mesh) => {
  269. this.onMeshAdded(mesh);
  270. });
  271. this._scene.getGeometries().forEach((geometry) => {
  272. this.onGeometryAdded(geometry);
  273. });
  274. break;
  275. case WorkerTaskType.UPDATE:
  276. this._runningUpdated--;
  277. break;
  278. case WorkerTaskType.COLLIDE:
  279. var returnPayload: CollisionReplyPayload = returnData.payload;
  280. if (!this._collisionsCallbackArray[returnPayload.collisionId]) return;
  281. let callback = this._collisionsCallbackArray[returnPayload.collisionId];
  282. if (callback) {
  283. let mesh = this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  284. if (mesh) {
  285. callback(returnPayload.collisionId, Vector3.FromArray(returnPayload.newPosition), mesh);
  286. }
  287. }
  288. //cleanup
  289. this._collisionsCallbackArray[returnPayload.collisionId] = null;
  290. break;
  291. }
  292. }
  293. }
  294. export class CollisionCoordinatorLegacy implements ICollisionCoordinator {
  295. private _scene: Scene;
  296. private _scaledPosition = Vector3.Zero();
  297. private _scaledVelocity = Vector3.Zero();
  298. private _finalPosition = Vector3.Zero();
  299. public getNewPosition(position: Vector3, displacement: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh: Nullable<AbstractMesh>) => void, collisionIndex: number): void {
  300. position.divideToRef(collider._radius, this._scaledPosition);
  301. displacement.divideToRef(collider._radius, this._scaledVelocity);
  302. collider.collidedMesh = null;
  303. collider._retry = 0;
  304. collider._initialVelocity = this._scaledVelocity;
  305. collider._initialPosition = this._scaledPosition;
  306. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  307. this._finalPosition.multiplyInPlace(collider._radius);
  308. //run the callback
  309. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  310. }
  311. public init(scene: Scene): void {
  312. this._scene = scene;
  313. }
  314. public destroy(): void {
  315. //Legacy need no destruction method.
  316. }
  317. //No update in legacy mode
  318. public onMeshAdded(mesh: AbstractMesh) { }
  319. public onMeshUpdated(mesh: AbstractMesh) { }
  320. public onMeshRemoved(mesh: AbstractMesh) { }
  321. public onGeometryAdded(geometry: Geometry) { }
  322. public onGeometryUpdated(geometry: Geometry) { }
  323. public onGeometryDeleted(geometry: Geometry) { }
  324. private _collideWithWorld(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, finalPosition: Vector3, excludedMesh: Nullable<AbstractMesh> = null): void {
  325. var closeDistance = Engine.CollisionsEpsilon * 10.0;
  326. if (collider._retry >= maximumRetry) {
  327. finalPosition.copyFrom(position);
  328. return;
  329. }
  330. // Check if this is a mesh else camera or -1
  331. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  332. collider._initialize(position, velocity, closeDistance);
  333. // Check all meshes
  334. for (var index = 0; index < this._scene.meshes.length; index++) {
  335. var mesh = this._scene.meshes[index];
  336. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  337. mesh._checkCollision(collider);
  338. }
  339. }
  340. if (!collider.collisionFound) {
  341. position.addToRef(velocity, finalPosition);
  342. return;
  343. }
  344. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  345. collider._getResponse(position, velocity);
  346. }
  347. if (velocity.length() <= closeDistance) {
  348. finalPosition.copyFrom(position);
  349. return;
  350. }
  351. collider._retry++;
  352. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  353. }
  354. }
  355. }