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: Box3.intersect, as three.js has it (#139)

Kevin Rajan9b53324add30
diff --git a/packages/scene/src/math.ts b/packages/scene/src/math.ts
index 8f40520..9687218 100644
--- a/packages/scene/src/math.ts
+++ b/packages/scene/src/math.ts
@@ -750,6 +750,13 @@ export class Box3 {
union(b: Box3): this {
return this.expandByPoint(b.min).expandByPoint(b.max);
}
+ /** Narrows this box to its overlap with `b` (three.js). */
+ intersect(b: Box3): this {
+ this.min.set(Math.max(this.min.x, b.min.x), Math.max(this.min.y, b.min.y), Math.max(this.min.z, b.min.z));
+ this.max.set(Math.min(this.max.x, b.max.x), Math.min(this.max.y, b.max.y), Math.min(this.max.z, b.max.z));
+ if (this.isEmpty()) this.makeEmpty();
+ return this;
+ }
/** The box of the box transformed by `m` (its eight corners). */
applyMatrix4(m: Matrix4): this {
if (this.isEmpty()) return this;
diff --git a/packages/scene/test/three-compat-box3-ops.test.ts b/packages/scene/test/three-compat-box3-ops.test.ts
new file mode 100644
index 0000000..0c9eddd
--- /dev/null
+++ b/packages/scene/test/three-compat-box3-ops.test.ts
@@ -0,0 +1,29 @@
+// Box3 intersection parity with three.js r187.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import * as THREE from "../src/index.ts";
+
+test("Box3.intersect keeps the overlap and fully empties disjoint boxes", () => {
+ const box = new THREE.Box3(new THREE.Vector3(-2, 0, 1), new THREE.Vector3(4, 6, 8));
+ const overlap = new THREE.Box3(new THREE.Vector3(3, -5, 6), new THREE.Vector3(10, 2, 11));
+
+ assert.strictEqual(box.intersect(overlap), box);
+ assert.deepEqual(box.min.toArray(), [3, 0, 6]);
+ assert.deepEqual(box.max.toArray(), [4, 2, 8]);
+ assert.deepEqual(overlap.min.toArray(), [3, -5, 6]);
+ assert.deepEqual(overlap.max.toArray(), [10, 2, 11]);
+
+ const disjoint = new THREE.Box3(new THREE.Vector3(20, 0, 0), new THREE.Vector3(30, 1, 1));
+ assert.strictEqual(box.intersect(disjoint), box);
+ assert.equal(box.isEmpty(), true);
+ assert.deepEqual(box.min.toArray(), [Infinity, Infinity, Infinity]);
+ assert.deepEqual(box.max.toArray(), [-Infinity, -Infinity, -Infinity]);
+ assert.deepEqual(box.getCenter(new THREE.Vector3(9, 9, 9)).toArray(), [0, 0, 0]);
+ assert.deepEqual(box.getSize(new THREE.Vector3(9, 9, 9)).toArray(), [0, 0, 0]);
+
+ const touching = new THREE.Box3(new THREE.Vector3(0, 0, 0), new THREE.Vector3(1, 1, 1));
+ touching.intersect(new THREE.Box3(new THREE.Vector3(1, 1, 1), new THREE.Vector3(2, 2, 2)));
+ assert.equal(touching.isEmpty(), false);
+ assert.deepEqual(touching.min.toArray(), [1, 1, 1]);
+ assert.deepEqual(touching.max.toArray(), [1, 1, 1]);
+});