import mujoco, json, numpy as np, sys, os
from PIL import Image
sys.path.insert(0, os.path.dirname(__file__)); import harness as h
SH = "/workspace/asimov-guide/costdown/cad/out/shells"; IMG = "/workspace/asimov-guide/costdown/img"
pl = json.load(open(f"{SH}/shells.json"))["place"]
def model(shells=True, hide_orig=False):
    spec = mujoco.MjSpec.from_file(h.XML)
    for t in spec.textures:
        if t.type == mujoco.mjtTexture.mjTEXTURE_SKYBOX: t.builtin = mujoco.mjtBuiltin.mjBUILTIN_FLAT; t.rgb1 = [0.02,0.02,0.03]; t.rgb2 = [0.02,0.02,0.03]
        else: t.rgb1 = [0.06,0.07,0.06]; t.rgb2 = [0.09,0.10,0.09]; t.mark = mujoco.mjtMark.mjMARK_EDGE; t.markrgb = [0.784*0.5,0.961*0.5,0.259*0.5]
    for mm in spec.materials:
        if mm.name == 'groundplane': mm.reflectance = 0.05
    if hide_orig:
        for g in spec.geoms:
            if g.type == mujoco.mjtGeom.mjGEOM_MESH: g.rgba = [0.35, 0.37, 0.4, 1]
    if shells:
        mat_s = spec.add_material(); mat_s.name = "shell"; mat_s.rgba = [0.10, 0.11, 0.12, 1]; mat_s.specular = 0.4; mat_s.shininess = 0.6
        mat_v = spec.add_material(); mat_v.name = "visor"; mat_v.rgba = [0.784, 0.961, 0.259, 1]; mat_v.emission = 0.4
        for k, p in pl.items():
            if k.startswith("leg_"): continue
            for side in (("left", "right") if p["mirror_right"] else (None,)):
                m = spec.add_mesh(); m.name = f"{k}_{side}"; m.file = f"{SH}/{k}.stl"
                m.scale = [0.001, -0.001 if side == "right" else 0.001, 0.001]
                body = p["body"] if side in (None, "left") else p["body"].replace("left_", "right_")
                g = spec.body(body).add_geom(); g.type = mujoco.mjtGeom.mjGEOM_MESH; g.meshname = m.name
                pos = list(p["pos"]); 
                if side == "right": pos[1] = -pos[1]
                g.pos = pos; g.quat = list(p["quat"]); g.material = "visor" if k == "visor" else "shell"
                g.contype = 0; g.conaffinity = 0; g.group = 1
    spec.visual.global_.offwidth = 1600; spec.visual.global_.offheight = 1600
    m = spec.compile(); return m
def shot(m, name, cam_az, cam_el=-12, dist=2.3, w=900, hgt=1100, q=None):
    d = mujoco.MjData(m)
    if q:
        for j, v in q.items(): d.qpos[m.jnt_qposadr[m.joint(j).id]] = v
    mujoco.mj_forward(m, d)
    zmin = min(d.geom_xpos[g][2]-m.geom_size[g][0] for g in range(m.ngeom) if 'foot' in (m.geom(g).name or ''))
    d.qpos[2] -= zmin - 0.0005; mujoco.mj_forward(m, d)
    r = mujoco.Renderer(m, hgt, w)
    cam = mujoco.MjvCamera(); cam.lookat[:] = [0, 0, 0.62]; cam.distance = dist; cam.azimuth = cam_az; cam.elevation = cam_el
    opt = mujoco.MjvOption(); 
    r.update_scene(d, cam, opt)
    img = r.render()
    # replace background with site black
    Image.fromarray(img).save(f"{IMG}/{name}.png"); return img
m = model(True)
q = h.pose(0, "stand"); q.update({"left_shoulder_roll_joint": -0.25, "right_shoulder_roll_joint": 0.25})
shot(m, "bobbot_cd_front", 160, q=q)
shot(m, "bobbot_cd_side", 110, q=q)
shot(m, "bobbot_cd_34", 200, cam_el=-8, q=q)
m0 = model(False)
shot(m0, "asimov_orig_front", 160, q=q)
print("ok")
