main.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. import * as THREE from 'https://cdn.skypack.dev/[email protected]';
  2. import {FirstPersonControls} from 'https://cdn.skypack.dev/[email protected]/examples/jsm/controls/FirstPersonControls.js';
  3. const KEYS = {
  4. 'a': 65,
  5. 's': 83,
  6. 'w': 87,
  7. 'd': 68,
  8. };
  9. function clamp(x, a, b) {
  10. return Math.min(Math.max(x, a), b);
  11. }
  12. class InputController {
  13. constructor(target) {
  14. this.target_ = target || document;
  15. this.initialize_();
  16. }
  17. initialize_() {
  18. this.current_ = {
  19. leftButton: false,
  20. rightButton: false,
  21. mouseXDelta: 0,
  22. mouseYDelta: 0,
  23. mouseX: 0,
  24. mouseY: 0,
  25. };
  26. this.previous_ = null;
  27. this.keys_ = {};
  28. this.previousKeys_ = {};
  29. this.target_.addEventListener('mousedown', (e) => this.onMouseDown_(e), false);
  30. this.target_.addEventListener('mousemove', (e) => this.onMouseMove_(e), false);
  31. this.target_.addEventListener('mouseup', (e) => this.onMouseUp_(e), false);
  32. this.target_.addEventListener('keydown', (e) => this.onKeyDown_(e), false);
  33. this.target_.addEventListener('keyup', (e) => this.onKeyUp_(e), false);
  34. }
  35. onMouseMove_(e) {
  36. this.current_.mouseX = e.pageX - window.innerWidth / 2;
  37. this.current_.mouseY = e.pageY - window.innerHeight / 2;
  38. if (this.previous_ === null) {
  39. this.previous_ = {...this.current_};
  40. }
  41. this.current_.mouseXDelta = this.current_.mouseX - this.previous_.mouseX;
  42. this.current_.mouseYDelta = this.current_.mouseY - this.previous_.mouseY;
  43. }
  44. onMouseDown_(e) {
  45. this.onMouseMove_(e);
  46. switch (e.button) {
  47. case 0: {
  48. this.current_.leftButton = true;
  49. break;
  50. }
  51. case 2: {
  52. this.current_.rightButton = true;
  53. break;
  54. }
  55. }
  56. }
  57. onMouseUp_(e) {
  58. this.onMouseMove_(e);
  59. switch (e.button) {
  60. case 0: {
  61. this.current_.leftButton = false;
  62. break;
  63. }
  64. case 2: {
  65. this.current_.rightButton = false;
  66. break;
  67. }
  68. }
  69. }
  70. onKeyDown_(e) {
  71. this.keys_[e.keyCode] = true;
  72. }
  73. onKeyUp_(e) {
  74. this.keys_[e.keyCode] = false;
  75. }
  76. key(keyCode) {
  77. return !!this.keys_[keyCode];
  78. }
  79. isReady() {
  80. return this.previous_ !== null;
  81. }
  82. update(_) {
  83. if (this.previous_ !== null) {
  84. this.current_.mouseXDelta = this.current_.mouseX - this.previous_.mouseX;
  85. this.current_.mouseYDelta = this.current_.mouseY - this.previous_.mouseY;
  86. this.previous_ = {...this.current_};
  87. }
  88. }
  89. };
  90. class FirstPersonCamera {
  91. constructor(camera, objects) {
  92. this.camera_ = camera;
  93. this.input_ = new InputController();
  94. this.rotation_ = new THREE.Quaternion();
  95. this.translation_ = new THREE.Vector3(0, 2, 0);
  96. this.phi_ = 0;
  97. this.phiSpeed_ = 8;
  98. this.theta_ = 0;
  99. this.thetaSpeed_ = 5;
  100. this.headBobActive_ = false;
  101. this.headBobTimer_ = 0;
  102. this.objects_ = objects;
  103. }
  104. update(timeElapsedS) {
  105. this.updateRotation_(timeElapsedS);
  106. this.updateCamera_(timeElapsedS);
  107. this.updateTranslation_(timeElapsedS);
  108. this.updateHeadBob_(timeElapsedS);
  109. this.input_.update(timeElapsedS);
  110. }
  111. updateCamera_(_) {
  112. this.camera_.quaternion.copy(this.rotation_);
  113. this.camera_.position.copy(this.translation_);
  114. this.camera_.position.y += Math.sin(this.headBobTimer_ * 10) * 1.5;
  115. const forward = new THREE.Vector3(0, 0, -1);
  116. forward.applyQuaternion(this.rotation_);
  117. const dir = forward.clone();
  118. forward.multiplyScalar(100);
  119. forward.add(this.translation_);
  120. let closest = forward;
  121. const result = new THREE.Vector3();
  122. const ray = new THREE.Ray(this.translation_, dir);
  123. for (let i = 0; i < this.objects_.length; ++i) {
  124. if (ray.intersectBox(this.objects_[i], result)) {
  125. if (result.distanceTo(ray.origin) < closest.distanceTo(ray.origin)) {
  126. closest = result.clone();
  127. }
  128. }
  129. }
  130. this.camera_.lookAt(closest);
  131. }
  132. updateHeadBob_(timeElapsedS) {
  133. if (this.headBobActive_) {
  134. const wavelength = Math.PI;
  135. const nextStep = 1 + Math.floor(((this.headBobTimer_ + 0.000001) * 10) / wavelength);
  136. const nextStepTime = nextStep * wavelength / 10;
  137. this.headBobTimer_ = Math.min(this.headBobTimer_ + timeElapsedS, nextStepTime);
  138. if (this.headBobTimer_ == nextStepTime) {
  139. this.headBobActive_ = false;
  140. }
  141. }
  142. }
  143. updateTranslation_(timeElapsedS) {
  144. const forwardVelocity = (this.input_.key(KEYS.w) ? 1 : 0) + (this.input_.key(KEYS.s) ? -1 : 0)
  145. const strafeVelocity = (this.input_.key(KEYS.a) ? 1 : 0) + (this.input_.key(KEYS.d) ? -1 : 0)
  146. const qx = new THREE.Quaternion();
  147. qx.setFromAxisAngle(new THREE.Vector3(0, 1, 0), this.phi_);
  148. const forward = new THREE.Vector3(0, 0, -1);
  149. forward.applyQuaternion(qx);
  150. forward.multiplyScalar(forwardVelocity * timeElapsedS * 10);
  151. const left = new THREE.Vector3(-1, 0, 0);
  152. left.applyQuaternion(qx);
  153. left.multiplyScalar(strafeVelocity * timeElapsedS * 10);
  154. this.translation_.add(forward);
  155. this.translation_.add(left);
  156. if (forwardVelocity != 0 || strafeVelocity != 0) {
  157. this.headBobActive_ = true;
  158. }
  159. }
  160. updateRotation_(timeElapsedS) {
  161. const xh = this.input_.current_.mouseXDelta / window.innerWidth;
  162. const yh = this.input_.current_.mouseYDelta / window.innerHeight;
  163. this.phi_ += -xh * this.phiSpeed_;
  164. this.theta_ = clamp(this.theta_ + -yh * this.thetaSpeed_, -Math.PI / 3, Math.PI / 3);
  165. const qx = new THREE.Quaternion();
  166. qx.setFromAxisAngle(new THREE.Vector3(0, 1, 0), this.phi_);
  167. const qz = new THREE.Quaternion();
  168. qz.setFromAxisAngle(new THREE.Vector3(1, 0, 0), this.theta_);
  169. const q = new THREE.Quaternion();
  170. q.multiply(qx);
  171. q.multiply(qz);
  172. this.rotation_.copy(q);
  173. }
  174. }
  175. class FirstPersonCameraDemo {
  176. constructor() {
  177. this.initialize_();
  178. }
  179. initialize_() {
  180. this.initializeRenderer_();
  181. this.initializeLights_();
  182. this.initializeScene_();
  183. this.initializePostFX_();
  184. this.initializeDemo_();
  185. this.previousRAF_ = null;
  186. this.raf_();
  187. this.onWindowResize_();
  188. }
  189. initializeDemo_() {
  190. // this.controls_ = new FirstPersonControls(
  191. // this.camera_, this.threejs_.domElement);
  192. // this.controls_.lookSpeed = 0.8;
  193. // this.controls_.movementSpeed = 5;
  194. this.fpsCamera_ = new FirstPersonCamera(this.camera_, this.objects_);
  195. }
  196. initializeRenderer_() {
  197. this.threejs_ = new THREE.WebGLRenderer({
  198. antialias: false,
  199. });
  200. this.threejs_.shadowMap.enabled = true;
  201. this.threejs_.shadowMap.type = THREE.PCFSoftShadowMap;
  202. this.threejs_.setPixelRatio(window.devicePixelRatio);
  203. this.threejs_.setSize(window.innerWidth, window.innerHeight);
  204. this.threejs_.physicallyCorrectLights = true;
  205. this.threejs_.outputEncoding = THREE.sRGBEncoding;
  206. document.body.appendChild(this.threejs_.domElement);
  207. window.addEventListener('resize', () => {
  208. this.onWindowResize_();
  209. }, false);
  210. const fov = 60;
  211. const aspect = 1920 / 1080;
  212. const near = 1.0;
  213. const far = 1000.0;
  214. this.camera_ = new THREE.PerspectiveCamera(fov, aspect, near, far);
  215. this.camera_.position.set(0, 2, 0);
  216. this.scene_ = new THREE.Scene();
  217. this.uiCamera_ = new THREE.OrthographicCamera(
  218. -1, 1, 1 * aspect, -1 * aspect, 1, 1000);
  219. this.uiScene_ = new THREE.Scene();
  220. }
  221. initializeScene_() {
  222. const loader = new THREE.CubeTextureLoader();
  223. const texture = loader.load([
  224. './resources/skybox/posx.jpg',
  225. './resources/skybox/negx.jpg',
  226. './resources/skybox/posy.jpg',
  227. './resources/skybox/negy.jpg',
  228. './resources/skybox/posz.jpg',
  229. './resources/skybox/negz.jpg',
  230. ]);
  231. texture.encoding = THREE.sRGBEncoding;
  232. this.scene_.background = texture;
  233. const mapLoader = new THREE.TextureLoader();
  234. const maxAnisotropy = this.threejs_.capabilities.getMaxAnisotropy();
  235. const checkerboard = mapLoader.load('resources/checkerboard.png');
  236. checkerboard.anisotropy = maxAnisotropy;
  237. checkerboard.wrapS = THREE.RepeatWrapping;
  238. checkerboard.wrapT = THREE.RepeatWrapping;
  239. checkerboard.repeat.set(32, 32);
  240. checkerboard.encoding = THREE.sRGBEncoding;
  241. const plane = new THREE.Mesh(
  242. new THREE.PlaneGeometry(100, 100, 10, 10),
  243. new THREE.MeshStandardMaterial({map: checkerboard}));
  244. plane.castShadow = false;
  245. plane.receiveShadow = true;
  246. plane.rotation.x = -Math.PI / 2;
  247. this.scene_.add(plane);
  248. const box = new THREE.Mesh(
  249. new THREE.BoxGeometry(4, 4, 4),
  250. this.loadMaterial_('vintage-tile1_', 0.2));
  251. box.position.set(10, 2, 0);
  252. box.castShadow = true;
  253. box.receiveShadow = true;
  254. this.scene_.add(box);
  255. const concreteMaterial = this.loadMaterial_('concrete3-', 4);
  256. const wall1 = new THREE.Mesh(
  257. new THREE.BoxGeometry(100, 100, 4),
  258. concreteMaterial);
  259. wall1.position.set(0, -40, -50);
  260. wall1.castShadow = true;
  261. wall1.receiveShadow = true;
  262. this.scene_.add(wall1);
  263. const wall2 = new THREE.Mesh(
  264. new THREE.BoxGeometry(100, 100, 4),
  265. concreteMaterial);
  266. wall2.position.set(0, -40, 50);
  267. wall2.castShadow = true;
  268. wall2.receiveShadow = true;
  269. this.scene_.add(wall2);
  270. const wall3 = new THREE.Mesh(
  271. new THREE.BoxGeometry(4, 100, 100),
  272. concreteMaterial);
  273. wall3.position.set(50, -40, 0);
  274. wall3.castShadow = true;
  275. wall3.receiveShadow = true;
  276. this.scene_.add(wall3);
  277. const wall4 = new THREE.Mesh(
  278. new THREE.BoxGeometry(4, 100, 100),
  279. concreteMaterial);
  280. wall4.position.set(-50, -40, 0);
  281. wall4.castShadow = true;
  282. wall4.receiveShadow = true;
  283. this.scene_.add(wall4);
  284. // Create Box3 for each mesh in the scene so that we can
  285. // do some easy intersection tests.
  286. const meshes = [
  287. plane, box, wall1, wall2, wall3, wall4];
  288. this.objects_ = [];
  289. for (let i = 0; i < meshes.length; ++i) {
  290. const b = new THREE.Box3();
  291. b.setFromObject(meshes[i]);
  292. this.objects_.push(b);
  293. }
  294. // Crosshair
  295. const crosshair = mapLoader.load('resources/crosshair.png');
  296. crosshair.anisotropy = maxAnisotropy;
  297. this.sprite_ = new THREE.Sprite(
  298. new THREE.SpriteMaterial({map: crosshair, color: 0xffffff, fog: false, depthTest: false, depthWrite: false}));
  299. this.sprite_.scale.set(0.15, 0.15 * this.camera_.aspect, 1)
  300. this.sprite_.position.set(0, 0, -10);
  301. this.uiScene_.add(this.sprite_);
  302. }
  303. initializeLights_() {
  304. const distance = 50.0;
  305. const angle = Math.PI / 4.0;
  306. const penumbra = 0.5;
  307. const decay = 1.0;
  308. let light = new THREE.SpotLight(
  309. 0xFFFFFF, 100.0, distance, angle, penumbra, decay);
  310. light.castShadow = true;
  311. light.shadow.bias = -0.00001;
  312. light.shadow.mapSize.width = 4096;
  313. light.shadow.mapSize.height = 4096;
  314. light.shadow.camera.near = 1;
  315. light.shadow.camera.far = 100;
  316. light.position.set(25, 25, 0);
  317. light.lookAt(0, 0, 0);
  318. this.scene_.add(light);
  319. const upColour = 0xFFFF80;
  320. const downColour = 0x808080;
  321. light = new THREE.HemisphereLight(upColour, downColour, 0.5);
  322. light.color.setHSL( 0.6, 1, 0.6 );
  323. light.groundColor.setHSL( 0.095, 1, 0.75 );
  324. light.position.set(0, 4, 0);
  325. this.scene_.add(light);
  326. }
  327. loadMaterial_(name, tiling) {
  328. const mapLoader = new THREE.TextureLoader();
  329. const maxAnisotropy = this.threejs_.capabilities.getMaxAnisotropy();
  330. const metalMap = mapLoader.load('resources/freepbr/' + name + 'metallic.png');
  331. metalMap.anisotropy = maxAnisotropy;
  332. metalMap.wrapS = THREE.RepeatWrapping;
  333. metalMap.wrapT = THREE.RepeatWrapping;
  334. metalMap.repeat.set(tiling, tiling);
  335. const albedo = mapLoader.load('resources/freepbr/' + name + 'albedo.png');
  336. albedo.anisotropy = maxAnisotropy;
  337. albedo.wrapS = THREE.RepeatWrapping;
  338. albedo.wrapT = THREE.RepeatWrapping;
  339. albedo.repeat.set(tiling, tiling);
  340. albedo.encoding = THREE.sRGBEncoding;
  341. const normalMap = mapLoader.load('resources/freepbr/' + name + 'normal.png');
  342. normalMap.anisotropy = maxAnisotropy;
  343. normalMap.wrapS = THREE.RepeatWrapping;
  344. normalMap.wrapT = THREE.RepeatWrapping;
  345. normalMap.repeat.set(tiling, tiling);
  346. const roughnessMap = mapLoader.load('resources/freepbr/' + name + 'roughness.png');
  347. roughnessMap.anisotropy = maxAnisotropy;
  348. roughnessMap.wrapS = THREE.RepeatWrapping;
  349. roughnessMap.wrapT = THREE.RepeatWrapping;
  350. roughnessMap.repeat.set(tiling, tiling);
  351. const material = new THREE.MeshStandardMaterial({
  352. metalnessMap: metalMap,
  353. map: albedo,
  354. normalMap: normalMap,
  355. roughnessMap: roughnessMap,
  356. });
  357. return material;
  358. }
  359. initializePostFX_() {
  360. }
  361. onWindowResize_() {
  362. this.camera_.aspect = window.innerWidth / window.innerHeight;
  363. this.camera_.updateProjectionMatrix();
  364. this.uiCamera_.left = -this.camera_.aspect;
  365. this.uiCamera_.right = this.camera_.aspect;
  366. this.uiCamera_.updateProjectionMatrix();
  367. this.threejs_.setSize(window.innerWidth, window.innerHeight);
  368. }
  369. raf_() {
  370. requestAnimationFrame((t) => {
  371. if (this.previousRAF_ === null) {
  372. this.previousRAF_ = t;
  373. }
  374. this.step_(t - this.previousRAF_);
  375. this.threejs_.autoClear = true;
  376. this.threejs_.render(this.scene_, this.camera_);
  377. this.threejs_.autoClear = false;
  378. this.threejs_.render(this.uiScene_, this.uiCamera_);
  379. this.previousRAF_ = t;
  380. this.raf_();
  381. });
  382. }
  383. step_(timeElapsed) {
  384. const timeElapsedS = timeElapsed * 0.001;
  385. // this.controls_.update(timeElapsedS);
  386. this.fpsCamera_.update(timeElapsedS);
  387. }
  388. }
  389. let _APP = null;
  390. window.addEventListener('DOMContentLoaded', () => {
  391. _APP = new FirstPersonCameraDemo();
  392. });