Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ docs/ 詳細な文書
| [docs/architecture.md](docs/architecture.md) | 描画パイプライン、各モジュールの役割、設計上の判断 |
| [docs/operations.md](docs/operations.md) | セットアップ、マップ設定、全体ジョブ、常駐更新、プレイヤー位置の WebSocket、本番運用の安全策 |
| [docs/commands.md](docs/commands.md) | コマンドごとのオプション一覧 |
| [docs/render-api.md](docs/render-api.md) | 透視カメラの静止画と、watch が待ち受ける描画要求 API(英語) |
| [docs/igpu-report.md](docs/igpu-report.md) | 内蔵 GPU の調査と計測の報告(英語、2026-11-04 時点) |

## 既知の差異
Expand Down
2 changes: 1 addition & 1 deletion docker/maps.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"db": { "host": "tidb", "port": 4000, "user": "renderer", "password_file": "/run/secrets/db_password", "database": "dynmap" },
"live": "wss://map.example.net/up/ws",
"maps": [
{ "id": 1, "region": "/worlds/overworld/region", "persp": "iso_SE_30_hires", "zoom_max": 12 },
{ "id": 1, "name": "overworld", "region": "/worlds/overworld/region", "persp": "iso_SE_30_hires", "zoom_max": 12 },
{ "id": 2, "region": "/worlds/overworld/region", "persp": "iso_S_90_lowres", "zoom_max": 12 },
{ "id": 30001, "region": "/worlds/flat/region", "persp": "iso_S_90_lowres", "zoom_max": 7 },
{ "id": 30002, "region": "/worlds/flat/region", "persp": "iso_SE_30_hires", "zoom_max": 7 }
Expand Down
24 changes: 24 additions & 0 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ godot --path . -s scripts/main.gd -- <コマンド> [--オプション 値] [--
| `--dirty-port N` | 0 | ゲームサーバー(TORO-Core の map-dirty)からのブロック変更イベントを受ける WebSocket のポート。0 で無効 |
| `--dirty-token-file F` | | イベントの token を読むファイル(環境変数 `TORO_DIRTY_TOKEN` が優先)。`--dirty-port` と token の両方がそろったときだけ受ける |
| `--once` | | 1 回見て、最大 1 バッチだけ処理して終了(試験用) |
| `--api-port N` | | 描画要求 API(`docs/render-api.md`)をこのポートで待ち受ける。データベースに届かなくても API は動き続ける |

イベントは待ち行列に合流し、すでに入っているメガタイルは最初に入った時刻のままになる。繰り返し変わるメガタイルは
「熱い」と数えて順位を下げ、1 バッチに入る数も半分(最低 1)までに抑える。どのバッチでも最古の 1 件は必ず席を得る。
Expand All @@ -95,12 +96,35 @@ godot --path . -s scripts/main.gd -- <コマンド> [--オプション 値] [--
`zoom --map-id N --zoom-max Z (--all | --seed FILE)`: 描かずに zoom-out を再構築する。`FILE` は 1 行に 1 タイル
(`x y`、zoom 0)。

## `shot`

`shot --region-dir DIR --out FILE.png [オプション]`: 透視カメラで 1 枚の静止画を描き、PNG と変換情報の
JSON(`<ファイル名>.json`)を出す。カメラと API の仕様は `docs/render-api.md`。

| オプション | 既定 | 内容 |
| --- | --- | --- |
| `--out FILE` | | 出力する PNG(必須)。変換情報は同じ場所へ `.json` で出す |
| `--map NAME`, `--map-id N` | | `--config` のマップを名前か ID で選ぶ |
| `--region-dir DIR` | マップの設定 | ワールドの region ディレクトリ(マップより優先) |
| `--target x,y,z` | 0,70,0 | 注視点(軌道カメラ) |
| `--distance N` | 120 | 注視点からカメラまでの距離 |
| `--rotation N` | 0 | 方位(ラジアン) |
| `--angle N` | 0.75 | 見下ろし角(ラジアン。0 が真下) |
| `--fov N` | 75 | 垂直の画角(度) |
| `--eye x,y,z`, `--look-at x,y,z` | | 軌道カメラの代わりにカメラ位置と注視点を直接指定 |
| `--size WxH` | 1280x720 | 画像の大きさ |
| `--no-adjust-height` | | 注視点の高さの自動調整(BlueMap と同じ規則)をしない |
| `--background r,g,b[,a]` | 透明 | 何も描かれなかった所の色(0-255) |
| `--min-y`, `--max-y` | マップの設定 | 描画する高さの範囲 |
| `--data-dir DIR` | `res://data` | `build-data` の出力 |

## `build-data`

`build-data --jar FILE [--reports FILE] [--out DIR]`: クライアント jar から次を作る(`--out` の既定は `res://data`)。

- `blocks.json`, `atlas.bin`, `atlas.json`, `biomes.json`: 列単位の表(`BlockTable`)
- `assets/blockstates/*.json`, `assets/models/block/**.json`, `textures.bin`, `textures.json`: ブロックモデル(`StateRegistry`)
- `entity_textures.json`: ブロックエンティティ(チェスト、旗、頭、シュルカーボックス)のテクスチャシートの大きさ。シートのタイルも `textures.bin` / `textures.json` へ入る
- `block_defaults.json`: ブロックの既定プロパティ(`--reports` が要る)

## `dev`
Expand Down
143 changes: 143 additions & 0 deletions docs/render-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
# Still images and the render API

Besides map tiles, the renderer can draw a single still image ("shot") of a map area from a
perspective camera, and the resident `watch` process serves those renders over HTTP. Shots are a
general capability: a caller names a map, a camera and an image size, and receives a PNG plus the
camera transform, so any overlay or annotation can be computed on the caller's side. Nothing in
this design is specific to one caller; known callers are evidence capture (a caller that needs a
picture of one damaged spot, promptly) and background-video generation for a website (a caller
that needs many frames of a slow camera orbit, in batches).

## The camera

The shot camera uses the same terms as BlueMap's perspective view, so a view that exists as a
BlueMap link or a BlueMap screenshot can be reproduced exactly:

- `target`: the world position the camera looks at (`x`, `y`, `z`).
- `distance`: distance from the target to the camera, in blocks.
- `rotation`: azimuth in radians; 0 looks towards north, increasing values turn the view
clockwise seen from above.
- `angle`: tilt in radians; 0 is straight down from above, π/2 is horizontal.
- `fov`: vertical field of view in degrees (75 when omitted, BlueMap's value).

The camera position is `target + distance * (-sin(rotation) * sin(angle), cos(angle),
cos(rotation) * sin(angle))`, looking at the target with the world up vector. The projection is
the perspective projection with that field of view and the image's aspect ratio; near and far
planes follow BlueMap's rule for the distance (`near = clamp(distance / 1000, 0.01, 1)`,
`far = clamp(2 * distance, max(near + 1, 2000), distance + 5000)`).

### The effective target height

BlueMap does not use the given target height as-is: its map controls raise the target to a
suggested height derived from the terrain, every frame, and a settled screenshot therefore shows
that adjusted target. The shot camera reproduces the same rule, computed from the world data
itself (the terrain height is the top surface at the column, found by the same downward ray the
web app casts):

```
terrain = top surface height at (target.x, target.z)
targetHeight = terrain + 3
byDistance = lerp(targetHeight, 0, min(distance / 500, 1))
maxAngle = clamp((1 - sqrt(max(distance - 5, 0.001) * 0.0005)) * π/2, 0, π/2)
cameraHeight = top surface height at the camera's (x, z)
minCamera = cameraHeight - cos(maxAngle) * distance + 1 (0 when maxAngle < 0.1)
target.y = max(byDistance, minCamera)
```

Callers that already know the height they want (for example a caller that computed its target
from the thing it wants to show) can pass `adjust_height: false` to use the given target
unchanged. The transform in the response always describes the camera that was actually used.

## What a shot draws

A shot draws the same world the tiles draw — the region files, read directly — with the full
block models at their native 16-pixel textures:

- **Perspective projection** (above), at any image size, for example 1280×720 or 1920×1080.
- **Block-entity blocks.** Blocks whose shape the client draws from code rather than from a
block model — chests, banners, skulls and heads, shulker boxes — are baked from built-in
models that mirror the client's own geometry and entity textures, so they appear in shots
(and in tiles) like they do in the game. Sign and bed shapes come from their block models as
usual; sign *text* is not drawn (in the game it is a per-block label, and callers that
photograph signs for evidence suppress it there as well).
- **`uvlock`.** Block-state variants with `uvlock: true` keep their texture fixed to the world
while the model rotates, as the client does.

Lighting and shading are the renderer's own (the same model the tiles use), which is not the
web app's sun/ambient model; geometry, textures and the camera match, tones can differ slightly.

## The HTTP API

The `watch` process serves the API when started with `--api-port` (the port is a deployment
setting; nothing about it is baked into the program). Requests are JSON:

`POST /v1/render`

```json
{
"map": "overworld",
"camera": {"target": [100, 70, -40], "distance": 120, "rotation": -0.6, "angle": 0.75},
"width": 1280,
"height": 720,
"priority": "high"
}
```

- `map` is the map's name from the watch configuration. Instead of an orbit camera, a request
may give an explicit camera: `"camera": {"eye": [...], "look_at": [...], "up": [0, 1, 0],
"fov": 75}`.
- `priority` is `"high"` or `"normal"` (default). The watch loop serves the render queue
about once a second between tile batches: every high-priority request in that step, and a
few normal-priority ones, so a long batch sequence cannot starve an urgent single shot;
tile updates keep their own queue and are not starved either, because a shot takes about
a second.
- `background` (optional) is `[r, g, b]` or `[r, g, b, a]` with values 0-255: the colour the
picture starts from, i.e. what shows where no block was drawn. The default is transparent
black. A caller that composites the PNG over its own backdrop, or that matches another
renderer's void colour, sets it explicitly.
- The response is JSON: `image` (the PNG, base64), `width`, `height`, `view` and `projection`
(the camera matrices, 16 numbers each, in the column-major order three.js uses for
`Matrix4.elements`, over world coordinates), `eye` and `target` (the effective camera), and
`render_ms`.

Batch use (for example one video frame after another) is ordinary repeated requests; identical
requests are answered from a small in-memory cache, and the chunk and mesh caches stay warm
between frames of a sequence, so a slow orbit costs one render per frame, not one world load.

`GET /v1/maps` lists the served maps. `GET /v1/health` answers 204.

The same render is available without the server as a one-off command, which is what batch jobs
and tests use:

```
godot --path . -s scripts/main.gd -- shot --region-dir /worlds/overworld/region \
--target 100,70,-40 --distance 120 --rotation -0.6 --angle 0.75 \
--size 1280x720 --out shot.png
```

It writes the PNG and a `<name>.json` with the same fields as the API response.

## Verification

Equivalence with the BlueMap screenshot path was measured on a synthetic test world (built
for this purpose, containing the block-entity blocks listed above, uvlock variants and a
damaged area) drawn two ways with the same camera: once by BlueMap itself (Paper + BlueMap,
screen-captured in a browser) and once by the shot renderer, at 1280×720. The renderer's
transparent void was composited over black, the void colour of the comparison capture.

- Damage view (distance 70, rotation -0.6, angle 0.75): the two pictures agree on which
pixels show world (rather than void) for 94.9% of the pixels either one shows as world;
88.9% of all pixels are within ±12 per channel and 97.0% within ±30; the mean
maximum-channel difference over all pixels is 4.4 (of 255).
- Close-up view (distance 45, angle 0.9): world agreement 93.1%; 80.7% of pixels within ±12
and 93.6% within ±30; mean maximum-channel difference 8.2.

The remaining differences are the shading and texture filtering of two independent
renderers, not the geometry or the camera: chests (single and double), the ender and trapped
chests, banners, skulls and heads, shulker boxes and the uvlock variants are present and
identifiable in both pictures at the same positions.

Rendering speed on the same machine (RTX 3060): a 1280×720 evidence view renders in about
0.4-0.9 s; a 1920×1080 background view at distance 420 renders in about 0.6-0.9 s. The API
answers a high-priority request in about 1.5 s end to end while the watch process is
otherwise idle.
52 changes: 52 additions & 0 deletions scripts/cmd/build_data.gd
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ func _build(jar: String, out: String, reports: String) -> int:
continue
tex_names.append(n.substr("assets/minecraft/textures/".length(), n.length() - "assets/minecraft/textures/".length() - 4))
data.append_array(t)
_extract_entity_sheets(out, data, tex_names)
_write(out.path_join("textures.bin"), data)
_write_json(out.path_join("textures.json"), tex_names)
var defaults := {}
Expand Down Expand Up @@ -395,3 +396,54 @@ static func _parse_color(v: Variant) -> Variant:
if v is String:
return ("0x" + v.lstrip("#")).hex_to_int()
return null


# --- entity sheets ------------------------------------------------------------------------------------------------

## Sheets the client uses for block entities (chests, banners, shulker boxes, heads). They live
## outside textures/block, so they are cut into 16x16 tiles here and appended to the texture
## table as "entity/<sheet>#<tx>,<ty>"; entity_textures.json records each sheet's size in tiles
## for the state registry's block-entity baker.
const ENTITY_SHEETS := [
"entity/chest/normal", "entity/chest/normal_left", "entity/chest/normal_right",
"entity/chest/trapped", "entity/chest/trapped_left", "entity/chest/trapped_right",
"entity/chest/ender",
"entity/chest/copper", "entity/chest/copper_left", "entity/chest/copper_right",
"entity/chest/copper_exposed", "entity/chest/copper_exposed_left", "entity/chest/copper_exposed_right",
"entity/chest/copper_weathered", "entity/chest/copper_weathered_left", "entity/chest/copper_weathered_right",
"entity/chest/copper_oxidized", "entity/chest/copper_oxidized_left", "entity/chest/copper_oxidized_right",
"entity/banner/banner_base",
"entity/shulker/shulker",
"entity/shulker/shulker_white", "entity/shulker/shulker_light_gray", "entity/shulker/shulker_gray",
"entity/shulker/shulker_black", "entity/shulker/shulker_brown", "entity/shulker/shulker_red",
"entity/shulker/shulker_orange", "entity/shulker/shulker_yellow", "entity/shulker/shulker_lime",
"entity/shulker/shulker_green", "entity/shulker/shulker_cyan", "entity/shulker/shulker_light_blue",
"entity/shulker/shulker_blue", "entity/shulker/shulker_purple", "entity/shulker/shulker_magenta",
"entity/shulker/shulker_pink",
"entity/skeleton/skeleton", "entity/skeleton/wither_skeleton",
"entity/zombie/zombie", "entity/creeper/creeper", "entity/piglin/piglin",
"entity/enderdragon/dragon", "entity/player/wide/steve",
]


func _extract_entity_sheets(out_dir: String, data: PackedByteArray, tex_names: Array) -> void:
var manifest := {}
var skipped := 0
for sheet in ENTITY_SHEETS:
var path: String = "assets/minecraft/textures/" + sheet + ".png"
if not _jar.has(path):
skipped += 1
continue
var img := _load_rgba(_jar.read(path))
if img.get_width() == 0 or img.get_width() % 16 != 0 or img.get_height() % 16 != 0:
skipped += 1
continue
var txs := img.get_width() / 16
var tys := img.get_height() / 16
for ty in tys:
for tx in txs:
tex_names.append("%s#%d,%d" % [sheet, tx, ty])
data.append_array(img.get_region(Rect2i(tx * 16, ty * 16, 16, 16)).get_data())
manifest[sheet] = [txs, tys]
_write_json(out_dir.path_join("entity_textures.json"), manifest)
print("entity sheets %d (skipped %d)" % [manifest.size(), skipped])
17 changes: 15 additions & 2 deletions scripts/cmd/jobs.gd
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ static func run(args: Args) -> int:


## `watch --config maps.json [--map-id N,...] [--interval S] [--max-megas N] [--max-load L] [--stale-after S] [--once]`
## [--mega-cooldown S] [--bbox-threshold N] [--dirty-port N] [--dirty-token-file F]`
## [--mega-cooldown S] [--bbox-threshold N] [--dirty-port N] [--dirty-token-file F] [--api-port N]`
## Resident updater for every map of the config. The dirty feed (block-change events from the game server)
## listens only when both a port and a token are set: the token comes from TORO_DIRTY_TOKEN or the file.
static func watch(args: Args) -> int:
Expand Down Expand Up @@ -83,14 +83,27 @@ static func watch(args: Args) -> int:
var dirty := DirtyFeed.new()
if dirty.start(dirty_port, token):
job.dirty_feed = dirty
var api_port := args.integer("api-port", 0)
if api_port > 0:
var api := ShotApi.new()
api.pool = pool
if not api.start(api_port):
return 1
job.api = api

var state_dir := args.text("state-dir", "/state")
for e in ctx.cfg["maps"]:
var map := MapDef.from_entry(e)
if not wanted.is_empty() and not wanted.has(map.id):
continue
if job.api != null:
job.api.register(map)
if not ctx.store.ensure_connected():
Term.say("database unreachable: " + ctx.store.error)
return 1
if job.api == null:
return 1
# with the render API on, the map is still served; only its tile updates wait
continue
ctx.store.map_id = map.id
map.world = ctx.store.world_name()
if ctx.feed != null:
Expand Down
Loading
Loading