debug.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
  2. import {GUI} from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/libs/dat.gui.module.js';
  3. import {game} from './game.js';
  4. import {graphics} from './graphics.js';
  5. import {math} from './math.js';
  6. import {visibility} from './visibility.js';
  7. let _APP = null;
  8. const _NUM_BOIDS = 30;
  9. const _BOID_SPEED = 5;
  10. const _BOID_ACCELERATION = _BOID_SPEED / 5.0;
  11. const _BOID_FORCE_MAX = _BOID_ACCELERATION / 10.0;
  12. const _BOID_FORCE_ALIGNMENT = 5;
  13. const _BOID_FORCE_SEPARATION = 8;
  14. const _BOID_FORCE_COHESION = 4;
  15. const _BOID_FORCE_WANDER = 5;
  16. class LineRenderer {
  17. constructor(game) {
  18. this._game = game;
  19. this._materials = {};
  20. this._group = new THREE.Group();
  21. this._game._graphics.Scene.add(this._group);
  22. }
  23. Reset() {
  24. this._lines = [];
  25. this._group.remove(...this._group.children);
  26. }
  27. Add(pt1, pt2, hexColour) {
  28. const geometry = new THREE.Geometry();
  29. geometry.vertices.push(pt1.clone());
  30. geometry.vertices.push(pt2.clone());
  31. let material = this._materials[hexColour];
  32. if (!material) {
  33. this._materials[hexColour] = new THREE.LineBasicMaterial(
  34. {color: hexColour});
  35. material = this._materials[hexColour];
  36. }
  37. const line = new THREE.Line(geometry, material);
  38. this._lines.push(line);
  39. this._group.add(line);
  40. }
  41. }
  42. class Boid {
  43. constructor(game, params) {
  44. this._mesh = new THREE.Mesh(
  45. params.geometry,
  46. new THREE.MeshStandardMaterial({color: params.colour}));
  47. this._mesh.castShadow = true;
  48. this._mesh.receiveShadow = false;
  49. this._group = new THREE.Group();
  50. this._group.add(this._mesh);
  51. this._group.position.set(
  52. math.rand_range(-50, 50),
  53. 0,
  54. math.rand_range(-50, 50));
  55. this._direction = new THREE.Vector3(
  56. math.rand_range(-1, 1),
  57. 0,
  58. math.rand_range(-1, 1));
  59. this._velocity = this._direction.clone();
  60. this._maxSteeringForce = params.maxSteeringForce;
  61. this._maxSpeed = params.speed;
  62. this._acceleration = params.acceleration;
  63. this._radius = 1.0;
  64. this._mesh.rotateX(-Math.PI / 2);
  65. this._game = game;
  66. game._graphics.Scene.add(this._group);
  67. this._visibilityIndex = game._visibilityGrid.UpdateItem(
  68. this._mesh.uuid, this);
  69. this._wanderAngle = 0;
  70. this._params = params;
  71. }
  72. DisplayDebug() {
  73. const geometry = new THREE.SphereGeometry(10, 64, 64);
  74. const material = new THREE.MeshBasicMaterial({
  75. color: 0xFF0000,
  76. transparent: true,
  77. opacity: 0.25,
  78. });
  79. const mesh = new THREE.Mesh(geometry, material);
  80. this._group.add(mesh);
  81. this._mesh.material.color.setHex(0xFF0000);
  82. this._displayDebug = true;
  83. this._lineRenderer = new LineRenderer(this._game);
  84. }
  85. _UpdateDebug(local) {
  86. this._lineRenderer.Reset();
  87. this._lineRenderer.Add(
  88. this.Position, this.Position.clone().add(this._velocity),
  89. 0xFFFFFF);
  90. for (const e of local) {
  91. this._lineRenderer.Add(this.Position, e.Position, 0x00FF00);
  92. this._lineRenderer.Add(
  93. e.Position, e.Position.clone().add(e._velocity),
  94. 0xFFFFFF);
  95. }
  96. }
  97. get Position() {
  98. return this._group.position;
  99. }
  100. get Velocity() {
  101. return this._velocity;
  102. }
  103. get Direction() {
  104. return this._direction;
  105. }
  106. get Radius() {
  107. return this._radius;
  108. }
  109. Step(timeInSeconds) {
  110. if (this._displayDebug) {
  111. let a = 0;
  112. }
  113. const local = this._game._visibilityGrid.GetLocalEntities(
  114. this.Position, 15);
  115. this._ApplySteering(timeInSeconds, local);
  116. const frameVelocity = this._velocity.clone();
  117. frameVelocity.multiplyScalar(timeInSeconds);
  118. this._group.position.add(frameVelocity);
  119. const direction = this.Direction;
  120. const m = new THREE.Matrix4();
  121. m.lookAt(
  122. new THREE.Vector3(0, 0, 0),
  123. direction,
  124. new THREE.Vector3(0, 1, 0));
  125. this._group.quaternion.setFromRotationMatrix(m);
  126. this._visibilityIndex = this._game._visibilityGrid.UpdateItem(
  127. this._mesh.uuid, this, this._visibilityIndex);
  128. if (this._displayDebug) {
  129. this._UpdateDebug(local);
  130. }
  131. }
  132. CheckBounds() {
  133. const pos = this._group.position;
  134. if (pos.x > 65) {
  135. pos.x = -65;
  136. } else if (pos.x < -65) {
  137. pos.x = 65;
  138. } else if (pos.z < -35) {
  139. pos.z = 35;
  140. } else if (pos.z > 35) {
  141. pos.z = -35;
  142. }
  143. this._visibilityIndex = this._game._visibilityGrid.UpdateItem(
  144. this._mesh.uuid, this, this._visibilityIndex);
  145. }
  146. _ApplySteering(timeInSeconds, local) {
  147. const forces = [
  148. this._ApplyWander(),
  149. ];
  150. if (this._params.guiParams.separationEnabled) {
  151. forces.push(this._ApplySeparation(local));
  152. }
  153. if (this._params.guiParams.alignmentEnabled) {
  154. forces.push(this._ApplyAlignment(local));
  155. }
  156. if (this._params.guiParams.cohesionEnabled) {
  157. forces.push(this._ApplyCohesion(local));
  158. }
  159. const steeringForce = new THREE.Vector3(0, 0, 0);
  160. for (const f of forces) {
  161. steeringForce.add(f);
  162. }
  163. steeringForce.multiplyScalar(this._acceleration * timeInSeconds);
  164. // Lock to xz dimension
  165. steeringForce.multiply(new THREE.Vector3(1, 0, 1));
  166. // Clamp the force applied
  167. steeringForce.normalize();
  168. steeringForce.multiplyScalar(this._maxSteeringForce);
  169. this._velocity.add(steeringForce);
  170. // Lock velocity for debug mode
  171. this._velocity.normalize();
  172. this._velocity.multiplyScalar(this._maxSpeed);
  173. this._direction = this._velocity.clone();
  174. this._direction.normalize();
  175. }
  176. _ApplyWander() {
  177. this._wanderAngle += 0.1 * math.rand_range(-2 * Math.PI, 2 * Math.PI);
  178. const randomPointOnCircle = new THREE.Vector3(
  179. Math.cos(this._wanderAngle),
  180. 0,
  181. Math.sin(this._wanderAngle));
  182. const pointAhead = this._direction.clone();
  183. pointAhead.multiplyScalar(2);
  184. pointAhead.add(randomPointOnCircle);
  185. pointAhead.normalize();
  186. return pointAhead.multiplyScalar(_BOID_FORCE_WANDER);
  187. }
  188. _CalculateSeparationForce() {
  189. totalForce = 0;
  190. for (every boid in the area) {
  191. totalForce += (ourPosition - theirPosition) / distanceBetween;
  192. }
  193. return totalForce;
  194. }
  195. _CalculateSeparationForce(local) {
  196. const forceVector = new THREE.Vector3(0, 0, 0);
  197. for (let e of local) {
  198. const distanceToEntity = Math.max(
  199. e.Position.distanceTo(this.Position) - (this.Radius + e.Radius),
  200. 0.001);
  201. const directionFromEntity = new THREE.Vector3().subVectors(
  202. this.Position, e.Position);
  203. directionFromEntity.normalize();
  204. const multiplier = _BOID_FORCE_SEPARATION * (
  205. (this.Radius + e.Radius) / distanceToEntity);
  206. forceVector.add(
  207. directionFromEntity.multiplyScalar(multiplier));
  208. }
  209. return forceVector;
  210. }
  211. _ApplyAlignment(local) {
  212. const forceVector = new THREE.Vector3(0, 0, 0);
  213. for (let e of local) {
  214. const entityDirection = e.Direction;
  215. forceVector.add(entityDirection);
  216. }
  217. forceVector.normalize();
  218. forceVector.multiplyScalar(_BOID_FORCE_ALIGNMENT);
  219. return forceVector;
  220. }
  221. _ApplyCohesion(local) {
  222. const forceVector = new THREE.Vector3(0, 0, 0);
  223. if (local.length == 0) {
  224. return forceVector;
  225. }
  226. const averagePosition = new THREE.Vector3(0, 0, 0);
  227. for (let e of local) {
  228. averagePosition.add(e.Position);
  229. }
  230. averagePosition.multiplyScalar(1.0 / local.length);
  231. const directionToAveragePosition = averagePosition.clone().sub(
  232. this.Position);
  233. directionToAveragePosition.normalize();
  234. directionToAveragePosition.multiplyScalar(_BOID_FORCE_COHESION);
  235. return directionToAveragePosition;
  236. }
  237. }
  238. class DebugDemo extends game.Game {
  239. constructor() {
  240. super();
  241. }
  242. _OnInitialize() {
  243. this._entities = [];
  244. this._guiParams = {
  245. separationEnabled: false,
  246. cohesionEnabled: false,
  247. alignmentEnabled: false,
  248. };
  249. this._gui = new GUI();
  250. this._gui.add(this._guiParams, "separationEnabled");
  251. this._gui.add(this._guiParams, "cohesionEnabled");
  252. this._gui.add(this._guiParams, "alignmentEnabled");
  253. this._gui.close();
  254. const geoLibrary = {
  255. cone: new THREE.ConeGeometry(1, 2, 32)
  256. };
  257. this._CreateEntities();
  258. this._CreateBoids(geoLibrary);
  259. }
  260. _CreateEntities() {
  261. const plane = new THREE.Mesh(
  262. new THREE.PlaneGeometry(400, 400, 32, 32),
  263. new THREE.MeshStandardMaterial({
  264. color: 0x808080,
  265. transparent: false,
  266. }));
  267. plane.position.set(0, -2, 0);
  268. plane.castShadow = false;
  269. plane.receiveShadow = false;
  270. plane.rotation.x = -Math.PI / 2;
  271. this._graphics.Scene.add(plane);
  272. this._visibilityGrid = new visibility.VisibilityGrid(
  273. [new THREE.Vector3(-500, 0, -500), new THREE.Vector3(500, 0, 500)],
  274. [100, 100]);
  275. this._graphics._camera.position.set(0, 50, 0);
  276. this._controls.target.set(0, 0, 0);
  277. this._controls.update();
  278. }
  279. _CreateBoids(geoLibrary) {
  280. let params = {
  281. geometry: geoLibrary.cone,
  282. speedMin: 1.0,
  283. speedMax: 1.0,
  284. speed: _BOID_SPEED,
  285. maxSteeringForce: _BOID_FORCE_MAX,
  286. acceleration: _BOID_ACCELERATION,
  287. colour: 0x80FF80,
  288. guiParams: this._guiParams
  289. };
  290. for (let i = 0; i < _NUM_BOIDS * 2; i++) {
  291. const e = new Boid(this, params);
  292. this._entities.push(e);
  293. }
  294. this._entities[0].DisplayDebug();
  295. }
  296. _OnStep(timeInSeconds) {
  297. timeInSeconds = Math.min(timeInSeconds, 1 / 10.0);
  298. if (this._entities.length == 0) {
  299. return;
  300. }
  301. for (let e of this._entities) {
  302. e.Step(timeInSeconds);
  303. }
  304. for (let e of this._entities) {
  305. // Teleport to other side if offscreen
  306. e.CheckBounds();
  307. }
  308. }
  309. }
  310. function _Main() {
  311. _APP = new DebugDemo();
  312. }
  313. _Main();