> ## Documentation Index
> Fetch the complete documentation index at: https://docs.viggle.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 3D scenes

> Build an explorable 3D Gaussian-splat scene (.spz) from a prompt or a 360° panorama, generate new views of it and reconstruct it.

JST-2 builds an explorable 3D scene, a Gaussian splat in `.spz` format, from a text prompt or a 360° panorama. You can then render new views from cameras you place and rebuild the scene from them to fill in what the first pass could not see. Use it for game levels, virtual sets and backgrounds behind your [3D characters](https://docs.viggle.ai/v1/3d/characters.md).

> [!WARNING]
>
> **Scene fields are camelCase.** Unlike the rest of V1, the scene endpoints use `sessionId`, `panoramaUri`, `referenceBatchIds`, `targetC2w` and so on, in requests and responses. Unknown fields are rejected with `400`, so `session_id` will not work.

## How scenes work

* **Session.** Every request carries a `sessionId` you choose: 1–128 letters, digits, `_` or `-`, scoped to your account. A session holds one scene and its image batches.
* **One task at a time.** A session runs one task at a time. Submitting while one is `queued` or `processing` answers `409`, before anything is charged, with that task's ID in `error.details.running_task_id`.
* **Batch.** A set of posed images. Creating a scene makes an `initial` batch, each generate call makes a `generated` batch. Their `batchId`s are what generate and reconstruct take in `referenceBatchIds`.
* **Camera.** Poses are 4×4 camera-to-world matrices (`c2w`). Every view in a batch comes with its `c2w`, so the easiest new camera is an existing one, moved.

Every call is asynchronous. It answers right away with a `scn_` task, which you poll with `GET /v1/scenes/{task_id}`.

| Step | Call | Main inputs | Result |
| - | - | - | - |
| Create from a prompt or panorama | `POST /v1/scenes/pano` | `prompt`, `panoramaUri` or a `panorama` file | `.spz`, panorama, `initial` batch |
| Create at your own pose and scale | `POST /v1/scenes/custom-pano` | panorama plus `panoramaC2w`, `metersPerUnit` | Same as pano, cameras in your world frame |
| Generate new views | `POST /v1/scenes/generate` | `referenceBatchIds`, `targetC2w` or `targetPosition` | `generated` batch |
| Reconstruct | `POST /v1/scenes/reconstruct` | `referenceBatchIds` | Rebuilt `.spz` |

## Parameters

Send JSON (up to 1 MiB). `pano` and `custom-pano` also accept `multipart/form-data` to upload files.

| Parameter | Used by | Values |
| - | - | - |
| `sessionId` | All | Required. See above |
| `prompt` | pano | 1–1000 characters. The panorama is generated from it, from reference images, or from both |
| `referenceImages` or `referenceImageFiles` | pano, with or without `prompt` | Up to 8 image URLs, or up to 8 uploaded JPEG/PNG/WebP files of 10 MiB each |
| `quality` | pano, with `prompt` or reference images | `low` (default), `medium`, `high` |
| `panoramaUri` or `panorama` | pano, custom-pano | Your 360° panorama as a public URL, or an uploaded JPEG/PNG/WebP up to 50 MiB. Instead of `prompt` |
| `panoramaC2w`, `metersPerUnit` | custom-pano | Where the panorama sits in your world, and the scale (default `1`) |
| `referenceBatchIds` | generate, reconstruct | 1–35 batch IDs from the same session |
| `targetC2w` or `targetPosition` | generate | The camera, as a matrix or as `{"position": [x, y, z], "yaw": deg, "pitch": deg}` |
| `projection` | generate | `perspective` (default) or `pano` |
| `fov`, `seed` | generate | Field of view 20–140 degrees; seed for repeatable output |

URLs must be public `http(s)` addresses. The [API reference](https://docs.viggle.ai/v1/api-reference/scenes/create-a-scene.md) covers coordinate frames and every validation rule.

## Price

You pay 1 credit (\$0.01) per view, each time the model runs. A panorama counts as 6 views.

| Call | Credits |
| - | - |
| `pano`, `custom-pano` | 6 |
| `generate` | 1 per new view with `perspective` (1 reserved, settled to the views made); 6 with `pano` |
| `reconstruct` | 1 per view in the batches it reads. It reserves 6 per batch, then settles to the views it read |

The script below creates a scene (6 credits), generates one perspective view (1) and reconstructs from both batches (6 + 1 = 7, assuming the panorama batch holds its usual 6 views): 14 credits (\$0.14) in all. Credits are reserved at submit and refunded in full unless the task finishes `ready`. The task's `credits` field shows what it holds.

If your balance is short, the submit answers `402 INSUFFICIENT_CREDITS` and nothing is queued.

## Build, extend and reconstruct

The script creates a scene from a prompt, saves `scene.spz` and `panorama.png`, generates a view from the first camera moved 0.3 units sideways, then reconstructs and saves `scene-v2.spz`. It needs no input files.

```bash cURL theme={null}
#!/usr/bin/env bash
set -euo pipefail
base="https://apis.viggle.ai/v1/scenes"
auth="Authorization: Bearer $VIGGLE_API_KEY"
session="quickstart-$(date +%s)"

submit() { # operation, JSON body -> task ID
  curl -sf -X POST "$base/$1" -H "$auth" -H "Content-Type: application/json" -d "$2" | jq -r '.id'
}

wait_ready() { # task ID -> ready task JSON
  while true; do
    task=$(curl -sf "$base/$1" -H "$auth")
    case "$(echo "$task" | jq -r '.status')" in
      ready) echo "$task"; return 0 ;;
      failed|cancelled) echo "Task $1 ended: $(echo "$task" | jq -c '.error')" >&2; return 1 ;;
    esac
    sleep 5
  done
}

# 1. Create the scene from a prompt.
task_id=$(submit pano "$(jq -n --arg s "$session" '{
  sessionId: $s,
  prompt: "A sunlit Scandinavian living room with a grey sofa and large windows",
  quality: "low"
}')")
pano=$(wait_ready "$task_id")
curl -sf -o scene.spz "$(echo "$pano" | jq -r '.result.spz.url')"
curl -sf -o panorama.png "$(echo "$pano" | jq -r '.result.panorama.url')"
initial=$(echo "$pano" | jq -r '.result.outputBatch.batchId')
echo "saved scene.spz and panorama.png; initial batch $initial"

# 2. Generate a view from the first camera, moved 0.3 units along its x axis.
target=$(echo "$pano" | jq -c '.result.outputBatch.views[0].c2w | .[0][3] += 0.3')
task_id=$(submit generate "$(jq -n --arg s "$session" --arg b "$initial" --argjson c "$target" '{
  sessionId: $s, referenceBatchIds: [$b], targetC2w: $c
}')")
generated=$(wait_ready "$task_id" | jq -r '.result.outputBatch.batchId')
echo "generated batch $generated"

# 3. Reconstruct from both batches.
task_id=$(submit reconstruct "$(jq -n --arg s "$session" --arg a "$initial" --arg b "$generated" '{
  sessionId: $s, referenceBatchIds: [$a, $b]
}')")
url=$(wait_ready "$task_id" | jq -r '.result.spz.url')
curl -sf -o scene-v2.spz "$url"
echo "saved scene-v2.spz from $url"
```

```javascript Node.js theme={null}
import { writeFile } from "node:fs/promises";

const base = "https://apis.viggle.ai/v1/scenes";
const headers = {
  Authorization: `Bearer ${process.env.VIGGLE_API_KEY}`,
  "Content-Type": "application/json",
};
const sessionId = `quickstart-${Date.now()}`;

async function api(path, body) {
  const res = await fetch(`${base}${path}`, {
    method: body ? "POST" : "GET",
    headers,
    body: body && JSON.stringify(body),
  });
  const json = await res.json();
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${JSON.stringify(json.error)}`);
  return json;
}

async function waitReady(task) {
  while (task.status === "queued" || task.status === "processing") {
    await new Promise((r) => setTimeout(r, 5000));
    task = await api(`/${task.id}`);
  }
  if (task.status !== "ready") {
    throw new Error(`Task ${task.id} ended ${task.status}: ${JSON.stringify(task.error)}`);
  }
  return task.result;
}

async function download(url, path) {
  const res = await fetch(url);
  await writeFile(path, Buffer.from(await res.arrayBuffer()));
  console.log(`saved ${path}`);
}

// 1. Create the scene from a prompt.
const pano = await waitReady(await api("/pano", {
  sessionId,
  prompt: "A sunlit Scandinavian living room with a grey sofa and large windows",
  quality: "low",
}));
await download(pano.spz.url, "scene.spz");
await download(pano.panorama.url, "panorama.png");
const initial = pano.outputBatch.batchId;

// 2. Generate a view from the first camera, moved 0.3 units along its x axis.
const targetC2w = structuredClone(pano.outputBatch.views[0].c2w);
targetC2w[0][3] += 0.3;
const generated = await waitReady(await api("/generate", {
  sessionId,
  referenceBatchIds: [initial],
  targetC2w,
}));
console.log(`generated ${generated.newViewCount} views in batch ${generated.outputBatch.batchId}`);

// 3. Reconstruct from both batches.
const rebuilt = await waitReady(await api("/reconstruct", {
  sessionId,
  referenceBatchIds: [initial, generated.outputBatch.batchId],
}));
await download(rebuilt.spz.url, "scene-v2.spz");
console.log(rebuilt.spz.url);
```

```python Python theme={null}
import copy
import os
import time
import requests

base = "https://apis.viggle.ai/v1/scenes"
headers = {"Authorization": f"Bearer {os.environ['VIGGLE_API_KEY']}"}
session_id = f"quickstart-{int(time.time())}"


def submit(operation, body):
    res = requests.post(f"{base}/{operation}", headers=headers, json=body)
    res.raise_for_status()
    return res.json()


def wait_ready(task):
    while task["status"] in ("queued", "processing"):
        time.sleep(5)
        res = requests.get(f"{base}/{task['id']}", headers=headers)
        res.raise_for_status()
        task = res.json()
    if task["status"] != "ready":
        raise RuntimeError(f"Task {task['id']} ended {task['status']}: {task.get('error')}")
    return task["result"]


def download(url, path):
    res = requests.get(url)
    res.raise_for_status()
    with open(path, "wb") as f:
        f.write(res.content)
    print(f"saved {path}")


# 1. Create the scene from a prompt.
pano = wait_ready(submit("pano", {
    "sessionId": session_id,
    "prompt": "A sunlit Scandinavian living room with a grey sofa and large windows",
    "quality": "low",
}))
download(pano["spz"]["url"], "scene.spz")
download(pano["panorama"]["url"], "panorama.png")
initial = pano["outputBatch"]["batchId"]

# 2. Generate a view from the first camera, moved 0.3 units along its x axis.
target_c2w = copy.deepcopy(pano["outputBatch"]["views"][0]["c2w"])
target_c2w[0][3] += 0.3
generated = wait_ready(submit("generate", {
    "sessionId": session_id,
    "referenceBatchIds": [initial],
    "targetC2w": target_c2w,
}))
print(f"generated {generated['newViewCount']} views in batch {generated['outputBatch']['batchId']}")

# 3. Reconstruct from both batches.
rebuilt = wait_ready(submit("reconstruct", {
    "sessionId": session_id,
    "referenceBatchIds": [initial, generated["outputBatch"]["batchId"]],
}))
download(rebuilt["spz"]["url"], "scene-v2.spz")
print(rebuilt["spz"]["url"])
```

To start from your own panorama, replace `prompt` and `quality` with `"panoramaUri": "https://example.com/courtyard-360.jpg"`, or upload the file:

```bash theme={null}
curl -X POST https://apis.viggle.ai/v1/scenes/pano \
  -H "Authorization: Bearer $VIGGLE_API_KEY" \
  -F sessionId=courtyard-01 \
  -F panorama=@courtyard-360.jpg
```

## Get the result

Each submit answers with a task in `queued` (with `queuePosition`) or already `processing`:

```json theme={null}
{
  "id": "scn_0199f0c2-6a1e-7c3d-9b2a-4f5e6d7c8b9a.living-room-01",
  "sessionId": "living-room-01",
  "operation": "pano",
  "status": "queued",
  "credits": 6,
  "queuePosition": 0,
  "createdAt": 1791856740000,
  "completedAt": null,
  "result": null,
  "error": null
}
```

Poll `GET /v1/scenes/{task_id}` every 5 seconds until `status` is `ready`, `failed` or `cancelled`. A ready `result` holds:

| Operation | `spz` | `panorama` | `outputBatch` |
| - | - | - | - |
| `pano` (and `custom-pano`) | Yes | Yes | `initial` batch |
| `generate` | No | No | `generated` batch |
| `reconstruct` | Yes | No | No |

Each `outputBatch.views[]` entry has the image `url`, its `c2w` and `intrinsic`. Every URL is signed for 3 hours; read the task again for fresh ones, and download what you keep soon after the task finishes. Scenes belong to your account, so any of its API keys can read them.

The `.spz` opens in any SPZ Gaussian-splat viewer. The Viggle Splat Engine also loads it: the web package places it behind a character, and the Unity package imports it as a static capture.

## If something fails

* `409` on submit: the session is busy. Wait for `error.details.running_task_id`, then submit again.
* `429 RATE_LIMITED` on submit: the credit reservation gate is busy. Retry with backoff.
* Task `failed` with `INVALID_REQUEST`: the model rejected the input, for example a batch from another session. Fix it first.
* Task `failed` with `PROCESSING_FAILED`, or `cancelled`: submit the same request again. Failed and cancelled tasks are refunded.
* `404` on poll: wrong ID, a task from another account, or past retention. This endpoint uses the code `INVALID_REQUEST` for it.

## Next steps

> [card] [3D characters](https://docs.viggle.ai/v1/3d/characters.md)
>
> Put a rigged character in the scene.

> [card] [Limits and retention](https://docs.viggle.ai/v1/concepts/limits-and-retention.md)
>
> How long results and links last.

> [card] [API reference](https://docs.viggle.ai/v1/api-reference/scenes/generate-scene-views.md)
>
> Cameras, projection, field of view and seed.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.