space.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { view } from "./view";
  2. import { cx_ui } from "./cx-ui.js";
  3. import { selector } from "./selector.js";
  4. import { phrase } from "./phrase.js";
  5. import { space_scene } from "./space-scene.js";
  6. import { controler } from "./controler.js";
  7. export class space extends view {
  8. #canvas;
  9. #context;
  10. #scene;
  11. #on_resize;
  12. #mouse;
  13. get canvas() {
  14. return this.#canvas;
  15. }
  16. get mouse() {
  17. return this.#mouse;
  18. }
  19. get context() {
  20. return this.#context;
  21. }
  22. #init_canvas() {
  23. this.#context = this.canvas.getContext("webgl2");
  24. this.#context = this.#context || this.canvas.getContext("webgl");
  25. if (this.#context) {
  26. return;
  27. }
  28. throw new MediaError("WebGL is not supported by browser");
  29. }
  30. update_size() {
  31. this.#scene.update_size(window.innerWidth, window.innerHeight);
  32. }
  33. show() {
  34. const ui = cx_ui.div("ui");
  35. const render = cx_ui.div("render");
  36. const back = new phrase("selector.return");
  37. const return_button = cx_ui.push("return", back, () => {
  38. this.manager.view = selector;
  39. });
  40. this.#canvas = cx_ui.canvas("space-render");
  41. this.#mouse = new controler();
  42. ui.appendChild(return_button);
  43. render.appendChild(this.canvas);
  44. try {
  45. this.#init_canvas();
  46. this.#scene = new space_scene(this);
  47. this.update_size();
  48. this.#scene.start();
  49. } catch (fail) {
  50. const error = cx_ui.div("error");
  51. const code = cx_ui.p("code", new phrase("error.webgl-support"));
  52. error.appendChild(code);
  53. render.appendChild(error);
  54. this.canvas.remove();
  55. console.error(fail);
  56. }
  57. this.#on_resize = () => { this.update_size(); };
  58. this.#mouse.enable();
  59. window.addEventListener("resize", this.#on_resize);
  60. return cx_ui.div("container", null, (container) => {
  61. container.appendChild(render);
  62. container.appendChild(ui);
  63. });
  64. }
  65. destroy() {
  66. this.#scene.stop();
  67. this.#mouse.clean();
  68. window.removeEventListener("resize", this.#on_resize);
  69. }
  70. }