Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(physics): a ring of more than eight points keeps its collider

yhhe494f34caf2b
diff --git a/sdk/src/physics/polygonDecompose2D.ts b/sdk/src/physics/polygonDecompose2D.ts
index 42e9e73d1..b8ce622f4 100644
--- a/sdk/src/physics/polygonDecompose2D.ts
+++ b/sdk/src/physics/polygonDecompose2D.ts
@@ -25,6 +25,9 @@ import { computePolygonHull, MAX_POLYGON_VERTICES, MIN_POLYGON_VERTICES } from '
/** Points nearer than this are one point, matching the hull's own welding. */
const WELD = 0.02;
+/** Box2D's linear slop; {@link WELD} is the 4x radius its hull welds within. */
+const SLOP = WELD / 4;
+
const cross = (ax: number, ay: number, bx: number, by: number): number => ax * by - ay * bx;
/** The turn at `b` walking a → b → c. Positive is a left turn, so convex in CCW. */
@@ -32,6 +35,21 @@ function turn(a: Vec2, b: Vec2, c: Vec2): number {
return cross(b.x - a.x, b.y - a.y, c.x - b.x, c.y - b.y);
}
+/**
+ * Whether the ring encloses more than slop. Area against PERIMETER, because area
+ * alone has no scale to be small against: a long thin sliver and a small honest
+ * triangle measure alike, and only one of them is a shape Box2D builds.
+ */
+function hasArea(ring: readonly Vec2[]): boolean {
+ let perimeter = 0;
+ for (let i = 0; i < ring.length; i++) {
+ const a = ring[i];
+ const b = ring[(i + 1) % ring.length];
+ perimeter += Math.hypot(b.x - a.x, b.y - a.y);
+ }
+ return Math.abs(signedArea2(ring)) > 2 * SLOP * perimeter;
+}
+
/** Twice the signed area of a ring: positive counter-clockwise. */
function signedArea2(ring: readonly Vec2[]): number {
let sum = 0;
@@ -84,11 +102,11 @@ function selfIntersects(ring: readonly Vec2[]): boolean {
return false;
}
-/** Strictly inside — a point ON an edge must not block the ear that owns it. */
+/** Inside or ON the boundary of a counter-clockwise triangle. */
function inTriangle(p: Vec2, a: Vec2, b: Vec2, c: Vec2): boolean {
- return cross(b.x - a.x, b.y - a.y, p.x - a.x, p.y - a.y) > 0
- && cross(c.x - b.x, c.y - b.y, p.x - b.x, p.y - b.y) > 0
- && cross(a.x - c.x, a.y - c.y, p.x - c.x, p.y - c.y) > 0;
+ return cross(b.x - a.x, b.y - a.y, p.x - a.x, p.y - a.y) >= 0
+ && cross(c.x - b.x, c.y - b.y, p.x - b.x, p.y - b.y) >= 0
+ && cross(a.x - c.x, a.y - c.y, p.x - c.x, p.y - c.y) >= 0;
}
/** The ring with consecutive duplicates removed, wound counter-clockwise. */
@@ -114,6 +132,9 @@ function normalize(vertices: readonly Vec2[]): Vec2[] {
function earClip(pts: readonly Vec2[]): number[][] | null {
const live = pts.map((_, i) => i);
const out: number[][] = [];
+ const turnAt = (i: number): number => turn(
+ pts[live[(i + live.length - 1) % live.length]], pts[live[i]], pts[live[(i + 1) % live.length]]);
+
while (live.length > 3) {
let clipped = -1;
for (let i = 0; i < live.length; i++) {
@@ -122,9 +143,14 @@ function earClip(pts: readonly Vec2[]): number[][] | null {
const c = live[(i + 1) % live.length];
if (turn(pts[a], pts[b], pts[c]) <= 0) continue;
let blocked = false;
- for (const k of live) {
+ for (let j = 0; j < live.length && !blocked; j++) {
+ const k = live[j];
if (k === a || k === b || k === c) continue;
- if (inTriangle(pts[k], pts[a], pts[b], pts[c])) { blocked = true; break; }
+ // Only a REFLEX vertex can invalidate an ear, and touching the
+ // triangle invalidates it as surely as sitting inside: a cut that
+ // grazes the boundary leaves a remainder with no ear at all.
+ if (turnAt(j) > 0) continue;
+ if (inTriangle(pts[k], pts[a], pts[b], pts[c])) blocked = true;
}
if (blocked) continue;
out.push([a, b, c]);
@@ -248,19 +274,25 @@ function partition(vertices: readonly Vec2[]): PolygonDecomposition {
const ring = normalize(vertices);
if (ring.length < MIN_POLYGON_VERTICES) return { pieces: [], degenerate: false };
- // The hull is the solver's own verdict on whether these points are a shape at
- // all — welded down to a line, or to fewer than three. Asking it here keeps
- // the fast path below from handing back a ring Box2D would refuse.
- const hull = computePolygonHull(ring);
- if (hull.length < MIN_POLYGON_VERTICES) return { pieces: [], degenerate: false };
+ // Crossing is asked FIRST. A symmetric bow tie encloses zero net area, so the
+ // area gate below would call it nothing at all — and "you crossed your own
+ // outline" is both the truer answer and the one an author can act on.
+ if (selfIntersects(ring)) return { pieces: [computePolygonHull(ring)], degenerate: true };
+
+ // Asked of the WHOLE ring. The hull models what b2ComputeHull does to an array,
+ // and that keeps only the first eight points — so as a shape gate it judges a
+ // long ring by eight of them, and loses the collider when those are collinear.
+ if (!hasArea(ring)) return { pieces: [], degenerate: false };
- if (selfIntersects(ring)) return { pieces: [hull], degenerate: true };
+ // Only now: a star traced as one stroke has no right turn either, so this test
+ // is a claim about convexity only once crossing has been ruled out. Normalizing
+ // already welded to Box2D's radius, so the points stay the ones an author placed.
if (ring.length <= MAX_POLYGON_VERTICES && isConvex(ring)) {
return { pieces: [ring], degenerate: false };
}
const triangles = earClip(ring);
- if (!triangles) return { pieces: [hull], degenerate: true };
+ if (!triangles) return { pieces: [computePolygonHull(ring)], degenerate: true };
// Each piece is finally what Box2D would make of it, so a sliver the solver
// refuses is dropped where it can be seen rather than at shape creation.
diff --git a/sdk/tests/concave-collider-smoke.mjs b/sdk/tests/concave-collider-smoke.mjs
index 070efc321..4832ea5e6 100644
--- a/sdk/tests/concave-collider-smoke.mjs
+++ b/sdk/tests/concave-collider-smoke.mjs
@@ -55,12 +55,12 @@ const CUP_RING = [
{ x: 1, y: 0 }, { x: -1, y: 0 }, { x: -1, y: 3 }, { x: -2, y: 3 },
];
-/** Drop a small box down the middle from `y`, and answer where it stops. */
-function dropInto(pieces, fromY) {
+/** Drop a small box from (`x`, `fromY`), and answer where it comes to rest. */
+function dropInto(pieces, fromY, x = 0) {
m._physics_init(0, -9.81, 1 / 60, 4, 30, 10, 3);
m._physics_createBody(CUP, STATIC, 0, 0, 0, 1, 0, 0, 0, 0);
for (const piece of pieces) addPiece(CUP, piece);
- m._physics_createBody(DROP, DYNAMIC, 0, fromY, 0, 1, 0, 0, 0, 0);
+ m._physics_createBody(DROP, DYNAMIC, x, fromY, 0, 1, 0, 0, 0, 0);
m._physics_addBoxShape(DROP, 0.2, 0.2, 0, 0, 0, 1, 0.3, 0, 0, 1, 0xffff);
for (let i = 0; i < 420; i++) m._physics_step(1 / 60);
const at = bodyPos(DROP);
@@ -90,5 +90,26 @@ check('the hull of the same ring seals it — the control', onLid && Math.abs(on
check('the two answers are far apart', landed && onLid && onLid.y - landed.y > 2.5,
`${landed?.y.toFixed(3)} vs ${onLid?.y.toFixed(3)}`);
+// Past the eight vertices one Box2D polygon holds: a comb with two teeth and a
+// slot between them, twelve points in one ring. The cap is a PIECE's, so this has
+// to behave like the geometry it is rather than like the hull of it.
+const COMB = [
+ { x: -3, y: -1 }, { x: 3, y: -1 }, { x: 3, y: 0 }, { x: 2, y: 0 },
+ { x: 2, y: 2 }, { x: 1, y: 2 }, { x: 1, y: 0 }, { x: 0, y: 0 },
+ { x: 0, y: 2 }, { x: -1, y: 2 }, { x: -1, y: 0 }, { x: -3, y: 0 },
+];
+const comb = decomposePolygon2D(COMB);
+check('a twelve-point ring partitions', !comb.degenerate && comb.pieces.length > 1,
+ `${COMB.length} points -> ${comb.pieces.length} piece(s): ${comb.pieces.map((q) => q.length).join('+')}`);
+check('and no piece exceeds what one polygon holds', comb.pieces.every((q) => q.length <= 8),
+ comb.pieces.map((q) => q.length).join('+'));
+
+const inSlot = dropInto(comb.pieces, 5, 0.5);
+check('a body drops down the slot between two teeth', inSlot && Math.abs(inSlot.y - 0.2) < 0.1,
+ `y=${inSlot?.y.toFixed(3)} (want \u22480.2, the slot floor)`);
+const onTooth = dropInto(comb.pieces, 5, 1.5);
+check('and rests on the tooth beside it', onTooth && Math.abs(onTooth.y - 2.2) < 0.1,
+ `y=${onTooth?.y.toFixed(3)} (want \u22482.2, the tooth top)`);
+
console.log(pass ? '\nconcave-collider-smoke: PASS' : '\nconcave-collider-smoke: FAIL');
process.exit(pass ? 0 : 1);
diff --git a/sdk/tests/polygon-decompose.test.ts b/sdk/tests/polygon-decompose.test.ts
index 335d7c79a..2e87b32ce 100644
--- a/sdk/tests/polygon-decompose.test.ts
+++ b/sdk/tests/polygon-decompose.test.ts
@@ -124,6 +124,38 @@ describe('decomposePolygon2D', () => {
expect(covered(p(1.35, 1.35), d.pieces)).toBe(false); // the gap between two
});
+ it('partitions a comb — several teeth, several slots, one ring', () => {
+ const comb = [
+ p(-3, -1), p(3, -1), p(3, 0), p(2, 0), p(2, 2), p(1, 2),
+ p(1, 0), p(0, 0), p(0, 2), p(-1, 2), p(-1, 0), p(-3, 0),
+ ];
+ const d = decomposePolygon2D(comb);
+ expect(d.degenerate).toBe(false);
+ expectWellFormed(d.pieces);
+ expect(covered(p(0.5, 1), d.pieces)).toBe(false); // the slot between the teeth
+ expect(covered(p(1.5, 1), d.pieces)).toBe(true); // a tooth
+ expect(covered(p(-0.5, 1), d.pieces)).toBe(true); // the other tooth
+ expect(covered(p(0.5, -0.5), d.pieces)).toBe(true); // the base under the slot
+ });
+
+ it('survives a ring whose first eight points are collinear', () => {
+ // What the editor's insert makes of one edge subdivided over and over. The
+ // hull only ever looks at eight points, so using it to ask "is this a shape"
+ // answered no here, and the collider vanished.
+ let ring = [p(-1, -1), p(1, -1), p(1, 1), p(-1, 1)];
+ for (let k = 0; k < 8; k++) {
+ const a = ring[0];
+ const b = ring[1];
+ ring = [a, p((a.x + b.x) / 2, (a.y + b.y) / 2), ...ring.slice(1)];
+ }
+ expect(ring.length).toBeGreaterThan(MAX_POLYGON_VERTICES);
+ const d = decomposePolygon2D(ring);
+ expect(d.degenerate).toBe(false);
+ expectWellFormed(d.pieces);
+ expect(covered(p(0, 0), d.pieces)).toBe(true); // still a solid square
+ expect(covered(p(0, 2), d.pieces)).toBe(false);
+ });
+
it('is deterministic — the same ring gives the same pieces every time', () => {
expect(decomposePolygon2D(C).pieces).toEqual(decomposePolygon2D(C).pieces);
});