# Camera pose back-solve from a policy probe

Goal: recover the REAL camera pose so sim renders match the real view, using the
gripper as a calibration target. Verified on this rig (RMS 2.93 px @128).

## The idea

The policy probe gives you, at several timesteps, both:
- `TCP_world` — the gripper TCP in world coords, from sim forward kinematics
  (valid because the sim<->real joint calibration makes sim FK match reality), and
- `gripper_pixel` — where the gripper actually appears in the real camera frame
  (read off the frame by eye / vision).

These are 3D->2D correspondences. Solve the camera extrinsic+intrinsic that
projects TCP_world onto gripper_pixel by nonlinear least squares.

## SAPIEN camera model (reverse-engineered)

For camera position `P`, view forward direction `fw` (unit), up `UP=[0,0,1]`, fov:
```
zc = fw / |fw|
xc = cross(zc, UP); xc /= |xc|
yc = cross(zc, xc)
R  = stack([xc, yc, zc])         # world->camera rotation (rows)
t  = -R @ P
Xc = R @ X + t                   # world point -> camera coords
f  = 64 / tan(fov/2)             # fx=fy for a 128x128 view
u  = f*Xc[0]/Xc[2] + 64          # cx=cy=64
v  = f*Xc[1]/Xc[2] + 64
```
This matches `cam.get_params()["extrinsic_cv"]` / `["intrinsic_cv"]` from a
ManiSkill sensor (see `outputs/cam_backsolve/scripts/camproj.py`).

## Real 640x480 <-> 128 policy view

The policy sees a 128x128 center-crop of the 640x480 real frame:
```
to128(p)   = [(p[0]-80)*128/480, p[1]*128/480]      # real640 -> sim128
to640(p128)= [p128[0]*480/128 + 80, p128[1]*480/128]
```
Do the solve in 128-space (crop x by 80, scale 128/480).

## CRITICAL: parameterize orientation by view az/el, NOT target point

The camera looks from a FIXED platform position `P` (known). The free parameters
are the view direction (azimuth `th`, elevation `ph`) and `fov`:
```
fw(th,ph) = [cos(ph)cos(th), cos(ph)sin(th), sin(ph)]
```
Do NOT solve for a `target` point directly: the target DISTANCE along the view
ray is a redundant DOF (only the direction matters for projection). Optimizing
target xyz makes that distance diverge to ~1e10. Solve `(th, ph, fov)` (+ optional
roll), then report `target = P + fw*0.35` only for the config file.

## Solver: Levenberg-damped Gauss-Newton with backslash

```
resid(x) = concat over pts of (project(P, fw(th,ph), fov, roll, X) - p)
J[:,j]   = (resid(x+h e_j) - resid(x)) / h        # numeric Jacobian, h=1e-6
A = J.T@J + lam*I ;  b = -J.T@r
dx = np.linalg.lstsq(A, b, rcond=None)[0]         # the "" solve
x += dx ; clip fov to [0.3, 1.6]
accept if |resid| decreased (lam*=0.5) else lam*=3
```
Init from the gitold camera direction; ~60 iters. Solve roll=0 first, then with
roll if needed. See `outputs/cam_backsolve/scripts/backsolve_cam.py`.

## Result (this rig)

pos `[-0.0126,-0.1788,0.4482]` (fixed), target `[0.1773,-0.107,0.1631]`,
fov `0.7567` (elevation -58.6deg -> -54.5deg, +4deg vs gitold). RMS 2.93 px@128
(within pixel-read noise). Stored in `env_config_solved.json` /
`outputs/cam_backsolve/data/cam_solve_roll0.json`.

## Learnability constraint

The solved camera is a SMALL perturbation of the learnable gitold camera, so a
policy fine-tuned from ckpt_1551 stays learnable. A large camera jump
(newcam / joint_refined) is UNLEARNABLE (0% sim success) — don't chase a perfect
geometric fit at the cost of learnability. Validate visually: render the sim at
the probe qpos and overlay on the real frame; the gripper should align at the
reach poses (`outputs/cam_backsolve/frames/val_sbs_t*.png`).

## Iterate on residual

After fine-tuning + real eval, if the TCP still misses the cube, collect fresh
(TCP_world, gripper_pixel) pairs from the new run and re-solve the residual. The
camera is the main sim2real gap; the joint calibration is already validated.
