> ## 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 场景

> 根据提示词或 360° 全景图构建可探索的 3D 高斯泼溅场景（.spz），为其生成新视角并重建场景。

JST-2 能根据文字提示词或 360° 全景图构建可探索的 3D 场景，即 `.spz` 格式的高斯泼溅（Gaussian splat）。之后你可以从自己放置的相机渲染新视角，并用这些视角重建场景，补全首次构建时看不到的部分。可用于游戏关卡、虚拟布景，以及 [3D 角色](https://docs.viggle.ai/zh/v1/3d/characters.md)身后的背景。

> [!WARNING]
>
> **场景字段使用驼峰命名（camelCase）。** 与 V1 的其他接口不同，场景接口在请求和响应中使用 `sessionId`、`panoramaUri`、`referenceBatchIds`、`targetC2w` 等字段名。未知字段会以 `400` 拒绝，因此 `session_id` 无效。

## 场景的工作方式

* **会话（Session）。** 每个请求都要带上你自定义的 `sessionId`：1–128 个字母、数字、`_` 或 `-`，作用域为你的账号。一个会话包含一个场景及其图像批次。
* **同一时间只运行一个任务。** 一个会话同一时间只能运行一个任务。当已有任务处于 `queued` 或 `processing` 时再提交，会在扣费前返回 `409`，并在 `error.details.running_task_id` 中给出该任务的 ID。
* **批次（Batch）。** 一组带位姿的图像。创建场景会生成一个 `initial` 批次，每次调用 generate 会生成一个 `generated` 批次。generate 和 reconstruct 在 `referenceBatchIds` 中接收的就是这些批次的 `batchId`。
* **相机。** 位姿用 4×4 的相机到世界矩阵（`c2w`）表示。批次中的每个视角都带有自己的 `c2w`，因此最简单的新相机就是把已有相机移动一下。

所有调用都是异步的。请求会立即返回一个 `scn_` 任务，你需要用 `GET /v1/scenes/{task_id}` 轮询。

| 步骤 | 调用 | 主要输入 | 结果 |
| - | - | - | - |
| 根据提示词或全景图创建 | `POST /v1/scenes/pano` | `prompt`、`panoramaUri` 或 `panorama` 文件 | `.spz`、全景图、`initial` 批次 |
| 按你自己的位姿和尺度创建 | `POST /v1/scenes/custom-pano` | 全景图加 `panoramaC2w`、`metersPerUnit` | 与 pano 相同，相机位于你的世界坐标系中 |
| 生成新视角 | `POST /v1/scenes/generate` | `referenceBatchIds`、`targetC2w` 或 `targetPosition` | `generated` 批次 |
| 重建 | `POST /v1/scenes/reconstruct` | `referenceBatchIds` | 重建后的 `.spz` |

## 参数

发送 JSON（不超过 1 MiB）。`pano` 和 `custom-pano` 还接受 `multipart/form-data` 以上传文件。

| 参数 | 使用者 | 取值 |
| - | - | - |
| `sessionId` | 全部 | 必填。见上文 |
| `prompt` | pano | 1–1000 个字符。全景图可根据它、参考图或两者共同生成 |
| `referenceImages` 或 `referenceImageFiles` | pano，可带或不带 `prompt` | 最多 8 个图片 URL，或最多 8 个上传的 JPEG/PNG/WebP 文件，每个不超过 10 MiB |
| `quality` | pano，配合 `prompt` 或参考图 | `low`（默认）、`medium`、`high` |
| `panoramaUri` 或 `panorama` | pano、custom-pano | 你的 360° 全景图，可以是公开 URL，也可以上传不超过 50 MiB 的 JPEG/PNG/WebP。用于替代 `prompt` |
| `panoramaC2w`、`metersPerUnit` | custom-pano | 全景图在你的世界中的位置，以及尺度（默认 `1`） |
| `referenceBatchIds` | generate、reconstruct | 同一会话中的 1–35 个批次 ID |
| `targetC2w` 或 `targetPosition` | generate | 相机，可以是矩阵，也可以是 `{"position": [x, y, z], "yaw": deg, "pitch": deg}` |
| `projection` | generate | `perspective`（默认）或 `pano` |
| `fov`、`seed` | generate | 视场角 20–140 度；seed 用于获得可复现的输出 |

URL 必须是公开的 `http(s)` 地址。坐标系和全部校验规则详见 [API 参考](https://docs.viggle.ai/zh/v1/api-reference/scenes/create-a-scene.md)。

## 价格

模型每运行一次，每个视角收取 1 积分（\$0.01）。一张全景图计为 6 个视角。

| 调用 | 积分 |
| - | - |
| `pano`、`custom-pano` | 6 |
| `generate` | `perspective` 时每个新视角 1 积分（预扣 1，按实际生成的视角数结算）；`pano` 时 6 |
| `reconstruct` | 读取的批次中每个视角 1 积分。每个批次预扣 6，再按实际读取的视角数结算 |

下面的脚本创建一个场景（6 积分），生成一个透视视角（1 积分），再用两个批次重建（6 + 1 = 7，假设全景批次照常包含 6 个视角）：共 14 积分（\$0.14）。积分在提交时预扣，除非任务以 `ready` 结束，否则全额退款。任务的 `credits` 字段显示当前占用的积分。

如果余额不足，提交会返回 `402 INSUFFICIENT_CREDITS`，且不会进入排队。

## 构建、扩展并重建

该脚本根据提示词创建场景，保存 `scene.spz` 和 `panorama.png`，把第一个相机横向移动 0.3 个单位后生成一个视角，然后重建并保存 `scene-v2.spz`。不需要任何输入文件。

```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"])
```

如果要从你自己的全景图开始，把 `prompt` 和 `quality` 换成 `"panoramaUri": "https://example.com/courtyard-360.jpg"`，或者直接上传文件：

```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
```

## 获取结果

每次提交都会返回一个处于 `queued`（带 `queuePosition`）或已在 `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
}
```

每 5 秒轮询一次 `GET /v1/scenes/{task_id}`，直到 `status` 变为 `ready`、`failed` 或 `cancelled`。就绪时 `result` 包含：

| 操作 | `spz` | `panorama` | `outputBatch` |
| - | - | - | - |
| `pano`（及 `custom-pano`） | 有 | 有 | `initial` 批次 |
| `generate` | 无 | 无 | `generated` 批次 |
| `reconstruct` | 有 | 无 | 无 |

每个 `outputBatch.views[]` 条目包含图像 `url`、对应的 `c2w` 和 `intrinsic`。所有 URL 的签名有效期为 3 小时；需要新链接时重新读取任务即可，要保留的内容请在任务完成后尽快下载。场景归属于你的账号，因此该账号下的任何 API 密钥都能读取。

`.spz` 可在任何支持 SPZ 的高斯泼溅查看器中打开。Viggle Splat Engine 也能加载它：Web 包会把它放在角色身后，Unity 包会把它作为静态捕捉导入。

## 出错时的处理

* 提交时返回 `409`：会话正忙。等待 `error.details.running_task_id` 对应的任务结束后再提交。
* 提交时返回 `429 RATE_LIMITED`：积分预扣通道繁忙。请退避后重试。
* 任务以 `failed` 结束且错误为 `INVALID_REQUEST`：模型拒绝了输入，例如使用了其他会话的批次。请先修正输入。
* 任务以 `failed` 结束且错误为 `PROCESSING_FAILED`，或任务为 `cancelled`：重新提交相同的请求。失败和取消的任务会退款。
* 轮询时返回 `404`：ID 错误、任务属于其他账号，或已超过保留期。该接口对这种情况使用错误码 `INVALID_REQUEST`。

## 后续步骤

> [card] [3D 角色](https://docs.viggle.ai/zh/v1/3d/characters.md)
>
> 在场景中放入带骨骼的角色。

> [card] [限制与保留期](https://docs.viggle.ai/zh/v1/concepts/limits-and-retention.md)
>
> 结果和链接的有效时长。

> [card] [API 参考](https://docs.viggle.ai/zh/v1/api-reference/scenes/generate-scene-views.md)
>
> 相机、投影方式、视场角和 seed。


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