shader-web-test/main.mjs
2024-12-26 04:15:00 +00:00

99 lines
2.4 KiB
JavaScript

import "https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/3.4.2/gl-matrix-min.js";
import { initShader } from "./shader.mjs";
import { calcRotationMatrix } from "./algebra.mjs";
const CANVAS_WIDTH = 800;
const CANVAS_HEIGHT = 800;
let TIME = 0;
let camera_pos = [0, 0, 0];
let mouse_pos = [0, 0];
// Update the Camera position
function updateCamera(gl, program) {
if (document.pointerLockElement) {
if (keymap.get("w")) {
camera_pos[2] += 0.1;
}
if (keymap.get("a")) {
camera_pos[0] += -0.1;
}
if (keymap.get("s")) {
camera_pos[2] += -0.1;
}
if (keymap.get("d")) {
camera_pos[0] += 0.1;
}
if (keymap.get("e")) {
camera_pos[1] += 0.1;
}
if (keymap.get("q")) {
camera_pos[1] += -0.1;
}
}
// Position
const pos = gl.getUniformLocation(program, "camera_pos");
gl.uniform3fv(pos, camera_pos);
// Rotation
const rot = gl.getUniformLocation(program, "camera_rot");
let M1 = calcRotationMatrix([0, -1, 0], mouse_pos[0]);
let M2 = calcRotationMatrix([-1, 0, 0], mouse_pos[1]);
let rot_mat = glMatrix.mat3.create();
glMatrix.mat3.mul(rot_mat, M1, M2);
gl.uniform3fv(rot, rot_mat);
}
// update the canvas
function draw(gl, program) {
// Create uniform
const loc = gl.getUniformLocation(program, "time");
TIME += 1 / 60;
gl.uniform1f(loc, TIME);
updateCamera(gl, program);
// Draw the frame recursively on next frame
gl.drawArrays(gl.TRIANGLES, 0, 6);
requestAnimationFrame(() => draw(gl, program));
}
const button = document.getElementById("reset_button");
button.addEventListener("click", reset_transform);
function reset_transform() {
camera_pos = [0, 0, 0];
mouse_pos = [0, 0];
}
//** MAIN PROGRAM **//
// Initialize the shader
const [gl, program, canvas] = await initShader(CANVAS_WIDTH, CANVAS_HEIGHT);
// Key Presses
let keymap = new Map();
document.addEventListener("keydown", function (event) {
keymap.set(event.key, true);
});
document.addEventListener("keyup", function (event) {
keymap.set(event.key, false);
});
// Mouse movement
document.addEventListener("mousemove", function (event) {
if (document.pointerLockElement) {
mouse_pos[0] += event.movementX / 800;
mouse_pos[1] += event.movementY / 800;
}
});
// Request pointer Lock
canvas.addEventListener("click", async () => {
await canvas.requestPointerLock();
});
// Update loop
draw(gl, program);