[math] Add a rotation-level look-at so engine-math and Transform.lookAt share one implementation

Aperta
#3,116 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
48/100
Tipo di issue
Funzionalità
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
typescript

Direzione di ricerca

Read packages/math/src/Matrix.ts around Matrix.lookAt and packages/core/src/Transform.ts around Transform.lookAt to understand the existing conventions and basis construction. Add focused tests in tests/src/math/Quaternion.test.ts, comparing against the matrix path and checking the degenerate cases described in the issue. Done means the rotation-level API has documented semantics, the tests pass, and Transform.lookAt reuses the shared implementation.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Summary

engine-math has no rotation-level look-at: the only look-at in the math package is Matrix.lookAt (packages/math/src/Matrix.ts:483), which produces a view matrix. Consumers that can only depend on engine-math have to rebuild the basis → quaternion conversion themselves. engine-core does exactly that — Transform.lookAt (packages/core/src/Transform.ts:528) builds the basis by hand — so the family currently ships two implementations of the same math, and the Transform one silently no-ops on degenerate input.

Proposal: add a rotation-level look-at to engine-math with an explicit degenerate contract, and let Transform.lookAt reuse it.

Current state

  1. Matrix.lookAt(eye, target, up, out) is the only look-at in engine-math. Quaternion has rotationEuler / rotationYawPitchRoll / rotationAxisAngle / rotationX|Y|Z, but no look-at.
  2. Transform.lookAt(targetPosition, worldUp?) does not reuse it: it builds zAxis / xAxis / yAxis by hand and calls rotMat.getRotation(this._worldRotationQuaternion).
  3. Degenerate input is a silent no-op, and the source already carries the TODO:
if (axisLen <= MathUtil.zeroTolerance) {
  // The current position and the target position are almost the same.
  return;                                  // ① eye coincides with target
}
...
if (axisLen <= MathUtil.zeroTolerance) {
  // @todo:
  // 1.worldUp is(0,0,0)
  // 2.worldUp is parallel to zAxis
  return;                                  // ② zero up / up parallel to the view direction
}
  1. The worldUp-less fallback degenerates too: xAxis.set(zAxis.z, 0, -zAxis.x) is (0,0,0) whenever the view direction is ±Y, so a target directly above/below also lands in ②. Measured with the current pinned @galacean/[email protected]: zAxis = (0, ±1, 0) → fallback xAxis length 0.
  2. Transform.lookAt has no dedicated test — it is only called incidentally in tests/src/core/MeshRenderer.test.ts and tests/src/core/Trail.test.ts. Matrix.lookAt is covered in tests/src/math/Matrix.test.ts:157.

Why it matters

A public authoring tool cannot treat "silently keep the old rotation" as success. Editor's camera.lookAt (galacean/editor#3931) must work in headless/CLI, where no Engine instance exists (instantiation needs a canvas/WebGL context), and the domain layer may only depend on engine-math. It currently assembles Matrix.lookAt → Matrix.invert → Matrix.getRotation and adds its own degenerate handling; every engine-math-only consumer is in the same position.

Proposed API

/**
 * Calculate the rotation of an object at `eye` looking at `target`, with `up` as the world up.
 * Returns false when the direction is degenerate (eye coincides with target, `up` is zero,
 * or `up` is parallel to the view direction), leaving `out` untouched.
 */
static lookAt(eye: Vector3, target: Vector3, up: Vector3, out: Quaternion): boolean;
  • Same parameters as Matrix.lookAt, so consumers keep one coordinate convention; the result is the object's world rotation (its -Z faces target).
  • Matrix.decompose(...): boolean is the existing precedent for a boolean "degenerate" contract.
  • Alternative naming: Quaternion.lookRotation(forward, up, out) (Unity-style, forward = the direction the object's -Z should face). Either shape is fine — the point is that there is exactly one, with documented semantics.

Implementation notes

Reuse the basis flow already proven in Transform.lookAt (zAxis = normalize(eye - target); xAxis = normalize(cross(up, zAxis)); yAxis = cross(zAxis, xAxis); build the matrix; getRotation(out)), replacing both silent returns with return false. Internal temporaries should follow the Matrix._tempVec30..32 numbering convention (Quaternion currently only has _tempVector3 / _tempQuat1).

Compatibility

Pure addition; no behavior change unless Transform.lookAt starts delegating. Two decisions for that delegation:

  1. The worldUp-less fallback degenerates for vertical directions (point 4). Keep the current silent no-op, or replace the fallback with a documented default (up = (0,1,0)), which is a behavior change and needs its own evaluation.
  2. Transform.lookAt returns void today; delegating can keep that (ignore the boolean) or return boolean (API change).

Local verification (prototype, 20k random cases)

  • Quaternion.lookAt vs the existing Matrix.lookAt → invert → getRotation path: max angle difference 2.80e-2° (both are float32, different rounding order), unit-length error 2.88e-8.
  • Degenerate inputs (eye == target, up = 0, up ∥ view): all return false; today those paths leave the rotation unchanged.
  • Vertical view with up = (0,0,1): works. Non-orthogonal up (e.g. (0.3, 0.9, 0.1)): orthogonalized, identical to Matrix.lookAt.

Test plan

Extend tests/src/math/Quaternion.test.ts: equivalence with Matrix.lookAt (fixed cases plus randomized comparison with tolerance), the three degenerate inputs returning false with out untouched, non-orthogonal up, and unit-length output.

Downstream

After a release, galacean/editor can collapse its three-step conversion into a single call and delete the duplicated basis logic; its remaining domain-side responsibilities (hierarchy traversal, float32 representability checks) stay in the domain layer where they belong.

Lingua principale
TypeScript
Stelle
5.9k
Fork
413
Merge medio
16h 17m
PR unite (30g)
41

Preparare l'ambiente

  • Nessun Dockerfile né file Docker Compose
  • Ha un modello di pull request
  • Nessuna guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di galacean/engine

Tutte le issue di galacean/engine

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.