WoRld As a Program: Programmable Spatial Reasoning for Multimodal LLMs

WRAP logo showing objects in a room linked to code
Explore the project

Programmable 3D worlds from video

WRAP transforms videos into programmable 3D worlds, enabling multimodal large language models (MLLMs) to reason about and manipulate 3D scenes.

By grounding visual objects into persistent 3D variables, WRAP allows MLLMs to dynamically generate and execute programs for flexible geometric computations, supporting both video spatial reasoning and 3D scene editing.

Explore a 3D scene

Input video

1 / 291

Drag the timeline, or click the video and scroll to step through its frames.

Tagged Video & 3D object point clouds

Loading point clouds…

Objects

Tagged Video

    Drag to orbit, or focus the view and use the arrow keys. Check the objects you want to see together.

    Spatial Reasoning

    Prompt

    How far is the desk from the Sofa?

    Reasoning

    <think> The desk is OBJECT_3 and Sofa is OBJECT_5. I will write python code to calculate the closest-point distance. </think>

    <code>Python
    from scipy.spatial import cKDTree
    d, _ = cKDTree(OBJECT_3).query(OBJECT_5, k=1)
    print(f"Disntace {float(d.min())}")
    </code>

    Result

    Distance 1.2

    Scene Editing

    Prompt

    I want to swap the desk and chair with the Sofa and turn them around so they face the right way.

    Reasoning

    <think> The desk is OBJECT_3, the sofa is OBJECT_5, and the chair is OBJECT_13. Wait, I notice an accompanying object (OBJECT_26) near the desk. I need to move it together with the desk during the swap. I will swap their positions and rotate them by 180° around the Z axis. </think>

    <code>Python
    from pathlib import Path
    import ctypes, subprocess, sys
    import cv2
    import numpy as np
    from scipy.spatial import Delaunay
    
    root = Path('./demo')
    out = root / 'demo_complete_output'
    out.mkdir(exist_ok=True)
    # Process all RGB frames; filter this list if a subset is needed.
    frames = sorted((root/'color').glob('*.jpg'), key=lambda p: int(p.stem))
    ids = (3, 5, 13, 26)
    objects = {3: OBJECT_3, 5: OBJECT_5, 13: OBJECT_13, 26: OBJECT_26}
    group = np.concatenate([objects[i][:,:2] for i in (3,13,26)])
    sofa = objects[5][:,:2]
    group_center = (group.min(0).astype(np.float64)+group.max(0))/2
    sofa_center = (sofa.min(0).astype(np.float64)+sofa.max(0))/2
    moved = {}
    for i in ids:
        a = objects[i]; b = a.copy()
        source, target = (sofa_center, group_center) if i == 5 else (group_center, sofa_center)
        b[:,:2] = target - (a[:,:2].astype(np.float64)-source)
        moved[i] = b
    with (root/'scene.ply').open('rb') as f:
        n = None
        while True:
            line = f.readline().decode('ascii').strip()
            if line.startswith('element vertex '): n = int(line.split()[-1])
            if line == 'end_header': break
        vertices = np.fromfile(f, dtype=[('x','<f4'),('y','<f4'),('z','<f4'),('r','u1'),('g','u1'),('b','u1'),('a','u1')], count=n)
        faces = np.fromfile(f, dtype=[('n','u1'),('index','<i4',(3,))])
    if not np.all(faces['n']==3): raise ValueError('Expected triangular mesh')
    xyz = np.stack([vertices[k] for k in 'xyz'],axis=1)
    lookup = {tuple(x): i for i,x in enumerate(xyz)}
    geometry = []
    for i in ids:
        a = objects[i]; indices = np.array([lookup[tuple(x)] for x in a[:,:3]],np.int32)
        local = np.full(n,-1,np.int32); local[indices] = np.arange(len(indices))
        triangles = local[faces['index']]; triangles = triangles[np.all(triangles>=0,axis=1)]
        if i == 3:
            selected = np.flatnonzero((a[:,2]>=.73)&(a[:,2]<=.77))
            _, unique = np.unique(a[selected,:2],axis=0,return_index=True)
            selected = selected[unique]
            extra = selected[Delaunay(a[selected,:2]).simplices]
            xy = a[extra,:2]
            lengths = np.max(np.linalg.norm(xy-np.roll(xy,1,axis=1),axis=2),axis=1)
            triangles = np.concatenate([triangles, extra[lengths<.55]],axis=0)
        colors = np.clip(np.rint(a[:,3:6][:,::-1]),0,255).astype(np.uint8)
        geometry.append((np.ascontiguousarray(a[:,:3]),np.ascontiguousarray(moved[i][:,:3]),np.ascontiguousarray(colors),np.ascontiguousarray(triangles,dtype=np.int32)))
    
    cpp_source = r'''
    #include <cmath>
    #include <cstdint>
    #include <algorithm>
    #include <limits>
    extern "C" void raster(const float* xyz, const unsigned char* rgb, const int32_t* faces, int count, int w, int h, float fx,float fy,float cx,float cy, float* zbuf, unsigned char* out) {
     for(int f=0;f<count;f++) {
      const int32_t* t=faces+3*f; float X[3],Y[3],Z[3],u[3],v[3]; bool ok=true;
      for(int i=0;i<3;i++){ int j=t[i]; X[i]=xyz[j*3]; Y[i]=xyz[j*3+1]; Z[i]=xyz[j*3+2]; if(Z[i]<=0.05f||!std::isfinite(Z[i])){ok=false;break;} u[i]=fx*X[i]/Z[i]+cx;v[i]=fy*Y[i]/Z[i]+cy; }
      if(!ok) continue;
      float xmin=std::min({u[0],u[1],u[2]}),xmax=std::max({u[0],u[1],u[2]}); float ymin=std::min({v[0],v[1],v[2]}),ymax=std::max({v[0],v[1],v[2]});
      if(xmax<0||ymax<0||xmin>=w||ymin>=h)continue;
      int x0=std::max(0,(int)std::floor(xmin)), x1=std::min(w-1,(int)std::ceil(xmax)); int y0=std::max(0,(int)std::floor(ymin)),y1=std::min(h-1,(int)std::ceil(ymax));
      float den=(v[1]-v[2])*(u[0]-u[2])+(u[2]-u[1])*(v[0]-v[2]); if(std::abs(den)<1e-8f)continue;
      for(int y=y0;y<=y1;y++)for(int x=x0;x<=x1;x++){
       float a=((v[1]-v[2])*(x-u[2])+(u[2]-u[1])*(y-v[2]))/den;
       float b=((v[2]-v[0])*(x-u[2])+(u[0]-u[2])*(y-v[2]))/den; float c=1-a-b;
       if(a < -1e-5f||b < -1e-5f||c < -1e-5f) continue;
       float iz=a/Z[0]+b/Z[1]+c/Z[2]; if(iz<=0)continue;float depth=1/iz;int p=y*w+x; if(depth>=zbuf[p])continue; zbuf[p]=depth;
       float wa=(a/Z[0])*depth, wb=(b/Z[1])*depth, wc=(c/Z[2])*depth;
       for(int k=0;k<3;k++)out[p*3+k]=(unsigned char)std::clamp((int)std::lround(wa*rgb[3*t[0]+k]+wb*rgb[3*t[1]+k]+wc*rgb[3*t[2]+k]),0,255);
      }
     }
    }
    
    '''
    source = out/'raster.cpp'; library_path = out/'raster.dylib'
    source.write_text(cpp_source)
    subprocess.run(['clang++','-O3','-std=c++17','-shared','-fPIC',str(source),'-o',str(library_path)],check=True)
    lib = ctypes.CDLL(str(library_path)); raster = lib.raster
    raster.argtypes = [ctypes.c_void_p,ctypes.c_void_p,ctypes.c_void_p,ctypes.c_int,ctypes.c_int,ctypes.c_int,ctypes.c_float,ctypes.c_float,ctypes.c_float,ctypes.c_float,ctypes.c_void_p,ctypes.c_void_p]
    k = np.loadtxt(root/'intrinsic/intrinsic_color.txt'); kd = np.loadtxt(root/'intrinsic/intrinsic_depth.txt')
    cv2.setNumThreads(1)
    for number, path in enumerate(frames,1):
        name = path.stem
        image = cv2.imread(str(path)); depth = cv2.imread(str(root/'depth'/f'{name}.png'),-1)
        pose = np.loadtxt(root/'pose'/f'{name}.txt')
        if image is None or depth is None: raise ValueError(f'Missing frame {name}')
        if pose.shape!=(4,4) or not np.isfinite(pose).all() or abs(np.linalg.det(pose))<1e-10:
            cv2.imwrite(str(out/f'{name}.png'),image); continue
        h,w=image.shape[:2]; transform=np.linalg.inv(pose)
        u,v=np.meshgrid(np.arange(w,dtype=np.float32),np.arange(h,dtype=np.float32))
        mapx=((u-k[0,2])*(kd[0,0]/k[0,0])+kd[0,2]).astype(np.float32)
        mapy=((v-k[1,2])*(kd[1,1]/k[1,1])+kd[1,2]).astype(np.float32)
        dm=cv2.remap(depth,mapx,mapy,cv2.INTER_NEAREST,borderMode=cv2.BORDER_CONSTANT).astype(np.float32)*.001
        layers=[]
        for position in (0,1):
            z=np.full((h,w),np.inf,np.float32); rgb=np.zeros((h,w,3),np.uint8)
            for obj in geometry:
                camera=np.ascontiguousarray(obj[position]@transform[:3,:3].T+transform[:3,3],dtype=np.float32)
                color,triangles=obj[2],obj[3]
                raster(camera.ctypes.data,color.ctypes.data,triangles.ctypes.data,len(triangles),w,h,*map(float,(k[0,0],k[1,1],k[0,2],k[1,2])),z.ctypes.data,rgb.ctypes.data)
            layers.append((z,rgb))
        old_z=layers[0][0]; new_z,rgb=layers[1]
        mask=(np.isfinite(old_z)&((dm==0)|(old_z<=dm+.22))).astype(np.uint8)
        mask=cv2.dilate(mask,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))
        mask=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,cv2.getStructuringElement(cv2.MORPH_RECT,(151,151)))
        mask=cv2.dilate(mask,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(21,21)))
        if mask.any(): image=cv2.inpaint(image,mask*255,5,cv2.INPAINT_TELEA)
        valid=np.isfinite(new_z)&((dm==0)|(mask!=0)|(new_z<=dm+.05))
        if valid.any():
            closed=cv2.morphologyEx(valid.astype(np.uint8),cv2.MORPH_CLOSE,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(21,21)))
            holes=(closed!=0)&(~valid)
            if holes.any():
                _, labels=cv2.distanceTransformWithLabels((~valid).astype(np.uint8),cv2.DIST_L2,5,labelType=cv2.DIST_LABEL_PIXEL)
                yy,xx=np.nonzero(valid)
                color_table=np.zeros((int(labels.max())+1,3),np.uint8); color_table[labels[yy,xx]]=rgb[yy,xx]
                depth_table=np.zeros(len(color_table),np.float32); depth_table[labels[yy,xx]]=new_z[yy,xx]
                holes &= (dm==0)|(mask!=0)|(depth_table[labels]<=dm+.05)
                rgb[holes]=color_table[labels[holes]]; valid |= holes
        image[valid]=rgb[valid]
        if not cv2.imwrite(str(out/f'{name}.png'),image): raise RuntimeError(f'Cannot save {name}')
        print(f'{number}/{len(frames)} {name}',flush=True)
    </code>

    Result

    1 / 291

    Drag the timeline, or click the video and scroll to step through its frames.

    From video to executable 3D programs

    WRAP gives a multimodal language model a way to refer to objects it sees and compute directly on their 3D geometry.

    Visual-Geometric Entity Binding

    WRAP builds object point clouds from video and links them to persistent visual IDs. Each ID resolves to a Grounded Variable.

    Adaptive 3D Activation

    The model starts with untagged video and switches to tagged frames when it needs explicit 3D computation.

    3D Program Reasoning

    The model selects the relevant variables and writes a task-specific program. The executor runs it to answer the question or update the scene.

    Spatial reasoning and scene editing

    ReVSI

    66.1%

    Average score · WRAP 9B

    5.2 percentage points above Gemini 3 Pro in the reported comparison.

    VSI-Bench

    69.5%

    Average score · WRAP 9B

    Includes numerical and multiple-choice questions on video spatial reasoning.

    EditRoom-DB

    0.5889

    Edit-IoU · WRAP 9B

    Edit-IoU measures overlap on edited objects. The EditRoom baseline scores 0.3236.