Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Scene: Ray.applyMatrix4 keeps the direction unit length under scale, as three.js does (#128)

Kevin Rajan113403bf16e8
diff --git a/packages/scene/src/math.ts b/packages/scene/src/math.ts
index e50619f..297c521 100644
--- a/packages/scene/src/math.ts
+++ b/packages/scene/src/math.ts
@@ -814,9 +814,8 @@ export class Ray {
return target.set(this.origin.x + this.direction.x * t, this.origin.y + this.direction.y * t, this.origin.z + this.direction.z * t);
}
applyMatrix4(m: Matrix4): this {
- const end = this.at(1).applyMatrix4(m);
this.origin.applyMatrix4(m);
- this.direction.subVectors(end, this.origin);
+ this.direction.transformDirection(m);
return this;
}
/** The ray parameter where it enters `b` (0 inside), or null. */
diff --git a/packages/scene/test/three-compat-sphere-ray.test.ts b/packages/scene/test/three-compat-sphere-ray.test.ts
new file mode 100644
index 0000000..921eafe
--- /dev/null
+++ b/packages/scene/test/three-compat-sphere-ray.test.ts
@@ -0,0 +1,25 @@
+// Ray.applyMatrix4 preserves a unit direction after non-uniform scaling, as three.js r187 does.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("Ray.applyMatrix4: a non-uniform scale transforms the origin but not the direction length", () => {
+ const matrix = new THREE.Matrix4().compose(
+ new THREE.Vector3(10, -4, 3),
+ new THREE.Quaternion(),
+ new THREE.Vector3(2, 3, 4),
+ );
+ const ray = new THREE.Ray(new THREE.Vector3(1, 2, 3), new THREE.Vector3(1, 0, 0));
+
+ assert.equal(ray.applyMatrix4(matrix), ray);
+ assert.deepEqual(ray.origin.toArray(), [12, 2, 15]);
+ assert.deepEqual(ray.direction.toArray(), [1, 0, 0]);
+ assert.deepEqual(ray.at(3, new THREE.Vector3()).toArray(), [15, 2, 15]);
+
+ const diagonal = new THREE.Ray(
+ new THREE.Vector3(),
+ new THREE.Vector3(3 / 5, 4 / 5, 0),
+ ).applyMatrix4(matrix);
+ assert.ok(diagonal.direction.distanceTo(new THREE.Vector3(1, 2, 0).normalize()) < 1e-12);
+ assert.ok(Math.abs(diagonal.direction.length() - 1) < 1e-12);
+});