Skip to content

Commit

Permalink
feat: add to and from homogenous
Browse files Browse the repository at this point in the history
  • Loading branch information
eliassjogreen committed Feb 15, 2021
1 parent f37adb8 commit 78d8b4d
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/projection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Angle, Rad } from "./angle.ts";
import { Matrix4 } from "./matrix4.ts";
import { absDiffEq, absDiffNe } from "./util.ts";
import { absDiffEq } from "./util.ts";

export class Perspective {
left: number;
Expand Down
22 changes: 22 additions & 0 deletions src/vector3.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Vector } from "./vector.ts";
import { Vector2 } from "./vector2.ts";
import { Vector4 } from "./vector4.ts";

export class Vector3 extends Vector<Vector3> {
#internal = new Float32Array(3);
Expand Down Expand Up @@ -91,6 +93,10 @@ export class Vector3 extends Vector<Vector3> {
return new Vector3(0, 0, 1);
}

static fromHomogeneous(vector: Vector4): Vector3 {
return vector.trunc().mul(1 / vector.w)
}

constructor();
constructor(x: number);
constructor(x: number, y: number, z: number);
Expand Down Expand Up @@ -126,6 +132,18 @@ export class Vector3 extends Vector<Vector3> {
return this.div(this.mag());
}

truncN(n: 0 | 1 | 2): Vector2 {
switch(n) {
case 0: return new Vector2(this.y, this.z);
case 1: return new Vector2(this.x, this.z);
case 2: return new Vector2(this.x, this.y);
}
}

trunc(): Vector2 {
return new Vector2(this.x, this.y);
}

clamp(length: number): Vector3 {
return this.normal().mul(length);
}
Expand Down Expand Up @@ -200,6 +218,10 @@ export class Vector3 extends Vector<Vector3> {
return isFinite(this.x) && isFinite(this.y) && isFinite(this.z);
}

toHomogeneous(): Vector4 {
return new Vector4(this.x, this.y, this.z, 1);
}

toString(): string {
return `Vector3 { x: ${this[0]}, y: ${this[1]}, z: ${this[2]} }`;
}
Expand Down
14 changes: 14 additions & 0 deletions src/vector4.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Vector } from "./vector.ts";
import { Vector3 } from "./vector3.ts";

export class Vector4 extends Vector<Vector4> {
#internal = new Float32Array(4);
Expand Down Expand Up @@ -113,6 +114,19 @@ export class Vector4 extends Vector<Vector4> {
return this.div(this.mag());
}

truncN(n: 0 | 1 | 2 | 3): Vector3 {
switch(n) {
case 0: return new Vector3(this.y, this.z, this.w);
case 1: return new Vector3(this.x, this.z, this.w);
case 2: return new Vector3(this.x, this.y, this.w);
case 3: return new Vector3(this.x, this.y, this.z);
}
}

trunc(): Vector3 {
return new Vector3(this.x, this.y, this.z);
}

clamp(length: number): Vector4 {
return this.normal().mul(length);
}
Expand Down

0 comments on commit 78d8b4d

Please sign in to comment.