recastJSPlugin.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. import { INavigationEnginePlugin, ICrowd, IAgentParameters, INavMeshParameters } from "../../Navigation/INavigationEngine";
  2. import { Logger } from "../../Misc/logger";
  3. import { VertexData } from "../../Meshes/mesh.vertexData";
  4. import { Mesh } from "../../Meshes/mesh";
  5. import { Scene } from "../../scene";
  6. import { Vector3 } from '../../Maths/math';
  7. import { TransformNode } from "../../Meshes/transformNode";
  8. import { Observer } from "../../Misc/observable";
  9. import { Nullable } from "../../types";
  10. import { VertexBuffer } from "../../Meshes/buffer";
  11. declare var Recast: any;
  12. /**
  13. * RecastJS navigation plugin
  14. */
  15. export class RecastJSPlugin implements INavigationEnginePlugin {
  16. /**
  17. * Reference to the Recast library
  18. */
  19. public bjsRECAST: any = {};
  20. /**
  21. * plugin name
  22. */
  23. public name: string = "RecastJSPlugin";
  24. /**
  25. * the first navmesh created. We might extend this to support multiple navmeshes
  26. */
  27. public navMesh: any;
  28. /**
  29. * Initializes the recastJS plugin
  30. * @param recastInjection can be used to inject your own recast reference
  31. */
  32. public constructor(recastInjection: any = Recast) {
  33. if (typeof recastInjection === "function") {
  34. recastInjection(this.bjsRECAST);
  35. } else {
  36. this.bjsRECAST = recastInjection;
  37. }
  38. if (!this.isSupported()) {
  39. Logger.Error("RecastJS is not available. Please make sure you included the js file.");
  40. return;
  41. }
  42. }
  43. /**
  44. * Creates a navigation mesh
  45. * @param meshes array of all the geometry used to compute the navigatio mesh
  46. * @param parameters bunch of parameters used to filter geometry
  47. */
  48. createMavMesh(meshes: Array<Mesh>, parameters: INavMeshParameters): void {
  49. const rc = new this.bjsRECAST.rcConfig();
  50. rc.cs = parameters.cs;
  51. rc.ch = parameters.ch;
  52. rc.borderSize = 0;
  53. rc.tileSize = 0;
  54. rc.walkableSlopeAngle = parameters.walkableSlopeAngle;
  55. rc.walkableHeight = parameters.walkableHeight;
  56. rc.walkableClimb = parameters.walkableClimb;
  57. rc.walkableRadius = parameters.walkableRadius;
  58. rc.maxEdgeLen = parameters.maxEdgeLen;
  59. rc.maxSimplificationError = parameters.maxSimplificationError;
  60. rc.minRegionArea = parameters.minRegionArea;
  61. rc.mergeRegionArea = parameters.mergeRegionArea;
  62. rc.maxVertsPerPoly = parameters.maxVertsPerPoly;
  63. rc.detailSampleDist = parameters.detailSampleDist;
  64. rc.detailSampleMaxError = parameters.detailSampleMaxError;
  65. this.navMesh = new this.bjsRECAST.NavMesh();
  66. var index: number;
  67. var tri: number;
  68. var pt: number;
  69. var indices = [];
  70. var positions = [];
  71. var offset = 0;
  72. for (index = 0; index < meshes.length; index++) {
  73. if (meshes[index]) {
  74. var mesh = meshes[index];
  75. const meshIndices = mesh.getIndices();
  76. if (!meshIndices) {
  77. continue;
  78. }
  79. const meshPositions = mesh.getVerticesData(VertexBuffer.PositionKind, false, false);
  80. if (!meshPositions) {
  81. continue;
  82. }
  83. const wm = mesh.computeWorldMatrix(false);
  84. for (tri = 0; tri < meshIndices.length; tri++) {
  85. indices.push(meshIndices[tri] + offset);
  86. }
  87. var transformed = Vector3.Zero();
  88. var position = Vector3.Zero();
  89. for (pt = 0; pt < meshPositions.length; pt += 3) {
  90. Vector3.FromArrayToRef(meshPositions, pt, position);
  91. Vector3.TransformCoordinatesToRef(position, wm, transformed);
  92. positions.push(transformed.x, transformed.y, transformed.z);
  93. }
  94. offset += meshPositions.length / 3;
  95. }
  96. }
  97. this.navMesh.build(positions, offset, indices, indices.length, rc);
  98. }
  99. /**
  100. * Create a navigation mesh debug mesh
  101. * @param scene is where the mesh will be added
  102. * @returns debug display mesh
  103. */
  104. createDebugNavMesh(scene: Scene): Mesh {
  105. var tri: number;
  106. var pt: number;
  107. var debugNavMesh = this.navMesh.getDebugNavMesh();
  108. let triangleCount = debugNavMesh.getTriangleCount();
  109. var indices = [];
  110. var positions = [];
  111. for (tri = 0; tri < triangleCount * 3; tri++)
  112. {
  113. indices.push(tri);
  114. }
  115. for (tri = 0; tri < triangleCount; tri++)
  116. {
  117. for (pt = 0; pt < 3 ; pt++)
  118. {
  119. let point = debugNavMesh.getTriangle(tri).getPoint(pt);
  120. positions.push(point.x, point.y, point.z);
  121. }
  122. }
  123. var mesh = new Mesh("NavMeshDebug", scene);
  124. var vertexData = new VertexData();
  125. vertexData.indices = indices;
  126. vertexData.positions = positions;
  127. vertexData.applyToMesh(mesh, false);
  128. return mesh;
  129. }
  130. /**
  131. * Get a navigation mesh constrained position, closest to the parameter position
  132. * @param position world position
  133. * @returns the closest point to position constrained by the navigation mesh
  134. */
  135. getClosestPoint(position: Vector3) : Vector3
  136. {
  137. var p = new this.bjsRECAST.Vec3(position.x, position.y, position.z);
  138. var ret = this.navMesh.getClosestPoint(p);
  139. var pr = new Vector3(ret.x, ret.y, ret.z);
  140. return pr;
  141. }
  142. /**
  143. * Get a navigation mesh constrained position, within a particular radius
  144. * @param position world position
  145. * @param maxRadius the maximum distance to the constrained world position
  146. * @returns the closest point to position constrained by the navigation mesh
  147. */
  148. getRandomPointAround(position: Vector3, maxRadius: number): Vector3 {
  149. var p = new this.bjsRECAST.Vec3(position.x, position.y, position.z);
  150. var ret = this.navMesh.getRandomPointAround(p, maxRadius);
  151. var pr = new Vector3(ret.x, ret.y, ret.z);
  152. return pr;
  153. }
  154. /**
  155. * Compute the final position from a segment made of destination-position
  156. * @param position world position
  157. * @param destination world position
  158. * @returns the resulting point along the navmesh
  159. */
  160. moveAlong(position: Vector3, destination: Vector3): Vector3 {
  161. var p = new this.bjsRECAST.Vec3(position.x, position.y, position.z);
  162. var d = new this.bjsRECAST.Vec3(destination.x, destination.y, destination.z);
  163. var ret = this.navMesh.moveAlong(p, d);
  164. var pr = new Vector3(ret.x, ret.y, ret.z);
  165. return pr;
  166. }
  167. /**
  168. * Compute a navigation path from start to end. Returns an empty array if no path can be computed
  169. * @param start world position
  170. * @param end world position
  171. * @returns array containing world position composing the path
  172. */
  173. computePath(start: Vector3, end: Vector3): Vector3[]
  174. {
  175. var pt: number;
  176. let startPos = new this.bjsRECAST.Vec3(start.x, start.y, start.z);
  177. let endPos = new this.bjsRECAST.Vec3(end.x, end.y, end.z);
  178. let navPath = this.navMesh.computePath(startPos, endPos);
  179. let pointCount = navPath.getPointCount();
  180. var positions = [];
  181. for (pt = 0; pt < pointCount; pt++)
  182. {
  183. let p = navPath.getPoint(pt);
  184. positions.push(new Vector3(p.x, p.y, p.z));
  185. }
  186. return positions;
  187. }
  188. /**
  189. * Create a new Crowd so you can add agents
  190. * @param maxAgents the maximum agent count in the crowd
  191. * @param maxAgentRadius the maximum radius an agent can have
  192. * @param scene to attach the crowd to
  193. * @returns the crowd you can add agents to
  194. */
  195. createCrowd(maxAgents: number, maxAgentRadius: number, scene: Scene) : ICrowd
  196. {
  197. var crowd = new RecastJSCrowd(this, maxAgents, maxAgentRadius, scene);
  198. return crowd;
  199. }
  200. /**
  201. * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...)
  202. * The queries will try to find a solution within those bounds
  203. * default is (1,1,1)
  204. * @param extent x,y,z value that define the extent around the queries point of reference
  205. */
  206. setDefaultQueryExtent(extent: Vector3): void
  207. {
  208. let ext = new this.bjsRECAST.Vec3(extent.x, extent.y, extent.z);
  209. this.navMesh.setDefaultQueryExtent(ext);
  210. }
  211. /**
  212. * Get the Bounding box extent specified by setDefaultQueryExtent
  213. * @returns the box extent values
  214. */
  215. getDefaultQueryExtent(): Vector3
  216. {
  217. let p = this.navMesh.getDefaultQueryExtent();
  218. return new Vector3(p.x, p.y, p.z);
  219. }
  220. /**
  221. * Disposes
  222. */
  223. public dispose() {
  224. }
  225. /**
  226. * If this plugin is supported
  227. * @returns true if plugin is supported
  228. */
  229. public isSupported(): boolean {
  230. return this.bjsRECAST !== undefined;
  231. }
  232. }
  233. /**
  234. * Recast detour crowd implementation
  235. */
  236. export class RecastJSCrowd implements ICrowd {
  237. /**
  238. * Recast/detour plugin
  239. */
  240. public bjsRECASTPlugin: RecastJSPlugin;
  241. /**
  242. * Link to the detour crowd
  243. */
  244. public recastCrowd: any = {};
  245. /**
  246. * One transform per agent
  247. */
  248. public transforms: TransformNode[] = new Array<TransformNode>();
  249. /**
  250. * All agents created
  251. */
  252. public agents: number[] = new Array<number>();
  253. /**
  254. * Link to the scene is kept to unregister the crowd from the scene
  255. */
  256. private _scene: Scene;
  257. /**
  258. * Observer for crowd updates
  259. */
  260. private _onBeforeAnimationsObserver: Nullable<Observer<Scene>> = null;
  261. /**
  262. * Constructor
  263. * @param plugin recastJS plugin
  264. * @param maxAgents the maximum agent count in the crowd
  265. * @param maxAgentRadius the maximum radius an agent can have
  266. * @param scene to attach the crowd to
  267. * @returns the crowd you can add agents to
  268. */
  269. public constructor(plugin: RecastJSPlugin, maxAgents: number, maxAgentRadius: number, scene: Scene) {
  270. this.bjsRECASTPlugin = plugin;
  271. this.recastCrowd = new this.bjsRECASTPlugin.bjsRECAST.Crowd(maxAgents, maxAgentRadius, this.bjsRECASTPlugin.navMesh.getNavMesh());
  272. this._scene = scene;
  273. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(() => {
  274. this.update(scene.getEngine().getDeltaTime() * 0.001);
  275. });
  276. }
  277. /**
  278. * Add a new agent to the crowd with the specified parameter a corresponding transformNode.
  279. * You can attach anything to that node. The node position is updated in the scene update tick.
  280. * @param pos world position that will be constrained by the navigation mesh
  281. * @param parameters agent parameters
  282. * @param transform hooked to the agent that will be update by the scene
  283. * @returns agent index
  284. */
  285. addAgent(pos: Vector3, parameters: IAgentParameters, transform: TransformNode): number
  286. {
  287. var agentParams = new this.bjsRECASTPlugin.bjsRECAST.dtCrowdAgentParams();
  288. agentParams.radius = parameters.radius;
  289. agentParams.height = parameters.height;
  290. agentParams.maxAcceleration = parameters.maxAcceleration;
  291. agentParams.maxSpeed = parameters.maxSpeed;
  292. agentParams.collisionQueryRange = parameters.collisionQueryRange;
  293. agentParams.pathOptimizationRange = parameters.pathOptimizationRange;
  294. agentParams.separationWeight = parameters.separationWeight;
  295. agentParams.updateFlags = 7;
  296. agentParams.obstacleAvoidanceType = 0;
  297. agentParams.queryFilterType = 0;
  298. agentParams.userData = 0;
  299. var agentIndex = this.recastCrowd.addAgent(new this.bjsRECASTPlugin.bjsRECAST.Vec3(pos.x, pos.y, pos.z), agentParams);
  300. this.transforms.push(transform);
  301. this.agents.push(agentIndex);
  302. return agentIndex;
  303. }
  304. /**
  305. * Returns the agent position in world space
  306. * @param index agent index returned by addAgent
  307. * @returns world space position
  308. */
  309. getAgentPosition(index: number): Vector3 {
  310. var agentPos = this.recastCrowd.getAgentPosition(index);
  311. return new Vector3(agentPos.x, agentPos.y, agentPos.z);
  312. }
  313. /**
  314. * Returns the agent velocity in world space
  315. * @param index agent index returned by addAgent
  316. * @returns world space velocity
  317. */
  318. getAgentVelocity(index: number): Vector3 {
  319. var agentVel = this.recastCrowd.getAgentVelocity(index);
  320. return new Vector3(agentVel.x, agentVel.y, agentVel.z);
  321. }
  322. /**
  323. * Asks a particular agent to go to a destination. That destination is constrained by the navigation mesh
  324. * @param index agent index returned by addAgent
  325. * @param destination targeted world position
  326. */
  327. agentGoto(index: number, destination: Vector3): void {
  328. this.recastCrowd.agentGoto(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z));
  329. }
  330. /**
  331. * Teleport the agent to a new position
  332. * @param index agent index returned by addAgent
  333. * @param destination targeted world position
  334. */
  335. agentTeleport(index: number, destination: Vector3): void {
  336. this.recastCrowd.agentTeleport(index, new this.bjsRECASTPlugin.bjsRECAST.Vec3(destination.x, destination.y, destination.z));
  337. }
  338. /**
  339. * Update agent parameters
  340. * @param index agent index returned by addAgent
  341. * @param parameters agent parameters
  342. */
  343. updateAgentParameters(index: number, parameters: IAgentParameters): void {
  344. var agentParams = this.recastCrowd.getAgentParameters(index);
  345. if (parameters.radius !== undefined) {
  346. agentParams.radius = parameters.radius;
  347. }
  348. if (parameters.height !== undefined) {
  349. agentParams.height = parameters.height;
  350. }
  351. if (parameters.maxAcceleration !== undefined) {
  352. agentParams.maxAcceleration = parameters.maxAcceleration;
  353. }
  354. if (parameters.maxSpeed !== undefined) {
  355. agentParams.maxSpeed = parameters.maxSpeed;
  356. }
  357. if (parameters.collisionQueryRange !== undefined) {
  358. agentParams.collisionQueryRange = parameters.collisionQueryRange;
  359. }
  360. if (parameters.pathOptimizationRange !== undefined) {
  361. agentParams.pathOptimizationRange = parameters.pathOptimizationRange;
  362. }
  363. if (parameters.separationWeight !== undefined) {
  364. agentParams.separationWeight = parameters.separationWeight;
  365. }
  366. this.recastCrowd.setAgentParameters(index, agentParams);
  367. }
  368. /**
  369. * remove a particular agent previously created
  370. * @param index agent index returned by addAgent
  371. */
  372. removeAgent(index: number): void {
  373. this.recastCrowd.removeAgent(index);
  374. var item = this.agents.indexOf(index);
  375. if (item > -1) {
  376. this.agents.splice(item, 1);
  377. this.transforms.splice(item, 1);
  378. }
  379. }
  380. /**
  381. * get the list of all agents attached to this crowd
  382. * @returns list of agent indices
  383. */
  384. getAgents(): number[] {
  385. return this.agents;
  386. }
  387. /**
  388. * Tick update done by the Scene. Agent position/velocity/acceleration is updated by this function
  389. * @param deltaTime in seconds
  390. */
  391. update(deltaTime: number): void {
  392. // update crowd
  393. this.recastCrowd.update(deltaTime);
  394. // update transforms
  395. for (let index = 0; index < this.agents.length; index++)
  396. {
  397. this.transforms[index].position = this.getAgentPosition(this.agents[index]);
  398. }
  399. }
  400. /**
  401. * Set the Bounding box extent for doing spatial queries (getClosestPoint, getRandomPointAround, ...)
  402. * The queries will try to find a solution within those bounds
  403. * default is (1,1,1)
  404. * @param extent x,y,z value that define the extent around the queries point of reference
  405. */
  406. setDefaultQueryExtent(extent: Vector3): void
  407. {
  408. let ext = new this.bjsRECASTPlugin.bjsRECAST.Vec3(extent.x, extent.y, extent.z);
  409. this.recastCrowd.setDefaultQueryExtent(ext);
  410. }
  411. /**
  412. * Get the Bounding box extent specified by setDefaultQueryExtent
  413. * @returns the box extent values
  414. */
  415. getDefaultQueryExtent(): Vector3
  416. {
  417. let p = this.recastCrowd.getDefaultQueryExtent();
  418. return new Vector3(p.x, p.y, p.z);
  419. }
  420. /**
  421. * Release all resources
  422. */
  423. dispose() : void
  424. {
  425. this.recastCrowd.destroy();
  426. this._scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  427. this._onBeforeAnimationsObserver = null;
  428. }
  429. }