webgl_game/src/js/common.ts

97 lines
1.9 KiB
TypeScript

function initializeContext(canvasId: string): WebGL2RenderingContext | null {
const canvas = document.getElementById(canvasId) as HTMLCanvasElement;
const ctx = canvas.getContext("webgl2", {antialias: false});
return ctx;
}
type Color = [number, number, number, number]
class Vec2 {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
add(other: Vec2) {
this.x += other.x;
this.y += other.y;
}
addScalar(scalar: number) {
this.x += scalar;
this.y += scalar;
}
addNew(other: Vec2): Vec2 {
return new Vec2(this.x + other.x, this.y + other.y);
}
addScalarNew(scalar: number): Vec2 {
return new Vec2(this.x + scalar, this.y + scalar);
}
sub(other: Vec2) {
this.x -= other.x;
this.y -= other.y;
}
mult(scalar: number) {
this.x *= scalar;
this.y *= scalar;
}
multNew(scalar: number): Vec2 {
return new Vec2(this.x * scalar, this.y * scalar);
}
splatToArray(): Array<number> {
return [this.x, this.y];
}
static angle(angle: number): Vec2 {
const eps = 1e-6;
let x = Math.cos(angle);
let y = Math.sin(angle);
if ((x > 0 && x < eps)
|| (x < 0 && x > -eps))
x = 0;
if ((y > 0 && y < eps)
|| (y < 0 && y > -eps))
y = 0;
return new Vec2(x, y);
}
}
class Vec3 {
x: number;
y: number;
z: number;
constructor(x: number, y: number, z: number) {
this.x = x;
this.y = y;
this.z = z;
}
add(other: Vec3) {
this.x += other.x;
this.y += other.y;
this.z += other.z;
}
sub(other: Vec3) {
this.x -= other.x;
this.y -= other.y;
this.z -= other.z;
}
}
export { initializeContext, Vec2, Vec3, Color };