OffAxisProjection.fromMatrix constructor

OffAxisProjection.fromMatrix(
  1. Matrix4 matrix, {
  2. double? near,
  3. double? far,
})

Reads the edges and clip planes back out of a perspective matrix.

Accepts the engine's own convention (clip w is the view depth, depth 0..1) and OpenGL's (clip w is -z, depth -1..1, what WebXR's XRView.projectionMatrix and ARKit's projectionMatrix produce), told apart by the sign of the w row. A matrix with an infinite far plane decodes far as double.infinity. near and far replace the decoded planes when given, for a matrix whose depth mapping is not one of those two. Jitter or any other skew in the matrix is not recovered.

Implementation

factory OffAxisProjection.fromMatrix(
  Matrix4 matrix, {
  double? near,
  double? far,
}) {
  final m00 = matrix.entry(0, 0);
  final m11 = matrix.entry(1, 1);
  final m20 = matrix.entry(0, 2);
  final m21 = matrix.entry(1, 2);
  final m22 = matrix.entry(2, 2);
  final m32 = matrix.entry(2, 3);
  final w = matrix.entry(3, 2);
  if (m00 == 0.0 || m11 == 0.0 || w == 0.0) {
    throw ArgumentError(
      'OffAxisProjection.fromMatrix needs a perspective matrix (nonzero '
      'x and y scales and a w row that reads view depth).',
    );
  }
  final double tanLeft, tanRight, tanDown, tanUp, decodedNear, decodedFar;
  if (w < 0.0) {
    // OpenGL: x_ndc = m00 * (x / -z) - m20, depth -1 at near and 1 at far.
    tanRight = (1.0 + m20) / m00;
    tanLeft = (m20 - 1.0) / m00;
    tanUp = (1.0 + m21) / m11;
    tanDown = (m21 - 1.0) / m11;
    decodedNear = m32 / (m22 - 1.0);
    decodedFar = m22 == -1.0 ? double.infinity : m32 / (m22 + 1.0);
  } else {
    // Engine: x_ndc = m00 * (x / z) + m20, depth 0 at near and 1 at far.
    tanRight = (1.0 - m20) / m00;
    tanLeft = (-1.0 - m20) / m00;
    tanUp = (1.0 - m21) / m11;
    tanDown = (-1.0 - m21) / m11;
    decodedNear = m22 == 0.0 ? 0.0 : -m32 / m22;
    decodedFar = m22 == 1.0 ? double.infinity : m32 / (1.0 - m22);
  }
  return OffAxisProjection(
    tanLeft: tanLeft,
    tanRight: tanRight,
    tanDown: tanDown,
    tanUp: tanUp,
    near: near ?? decodedNear,
    far: far ?? decodedFar,
  );
}