Feat: load 3D models from card definition assets on game board

Client:
- Added ModelCache autoload (autoloads/ModelCache.gd)
  - Downloads .glb files from CDN via HTTPRequest
  - Disk cache: user://remote_model_cache/<sha256>.glb
  - Memory cache: PackedScene per URL for instant re-instantiation
  - Concurrent requests for same URL queue and share one download
  - Loads via GLTFDocument.append_from_file + generate_scene
- game_screen.gd: _add_unit_mesh now looks up cardDefinitionId
  → ContentCache.get_definition() → finds Model3D asset URL
  → calls ModelCache.load_model() to async replace placeholder geometry
  - Placeholder (sphere/cylinder/box) shown immediately
  - Real model swaps in on download completion
  - Guards against body being freed before model arrives
  - Added _unit_bodies dict for O(1) body lookup
- project.godot: registered ModelCache autoload

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-03-09 12:37:25 -04:00
co-authored by Claude Happy
parent bb0f7dae91
commit e815dd708f
3 changed files with 173 additions and 14 deletions
@@ -0,0 +1,118 @@
extends Node
## ModelCache — downloads and caches .glb / .gltf 3D models from CDN.
##
## Usage:
## ModelCache.load_model(url, func(node: Node3D): ...)
##
## The callback receives a freshly-instantiated Node3D on success, or null on
## failure. Multiple callers requesting the same URL share a single download.
## Cached PackedScenes are kept in memory; raw bytes are written to
## user://remote_model_cache/<sha256>.glb
## so subsequent app launches skip the download.
const _CACHE_DIR := "user://remote_model_cache/"
# url (String) → PackedScene (null if load failed)
static var _mem: Dictionary = {}
# url (String) → Array[Callable] (callbacks waiting on an in-flight download)
static var _pending: Dictionary = {}
func _ready() -> void:
DirAccess.make_dir_recursive_absolute(_CACHE_DIR)
## Request a model by CDN URL.
## callback(node: Node3D) is called on the main thread; node may be null.
func load_model(url: String, callback: Callable) -> void:
# 1 — memory hit
if _mem.has(url):
var packed: PackedScene = _mem[url]
callback.call(packed.instantiate() if packed != null else null)
return
# 2 — disk hit
var disk := _disk_path(url)
if FileAccess.file_exists(disk):
var packed := _load_gltf(disk)
_mem[url] = packed
callback.call(packed.instantiate() if packed != null else null)
return
# 3 — already downloading → queue
if _pending.has(url):
_pending[url].append(callback)
return
# 4 — start download
_pending[url] = [callback]
_download(url, disk)
func _download(url: String, disk: String) -> void:
var http := HTTPRequest.new()
http.use_threads = true
add_child(http)
http.request_completed.connect(func(_result, code, _headers, body: PackedByteArray):
http.queue_free()
var callbacks: Array = _pending.get(url, [])
_pending.erase(url)
if code < 200 or code >= 300:
push_warning("ModelCache: download failed (%d) for %s" % [code, url])
for cb: Callable in callbacks:
cb.call(null)
return
# Write disk cache
var f := FileAccess.open(disk, FileAccess.WRITE)
if f:
f.store_buffer(body)
f.close()
else:
push_warning("ModelCache: could not write cache file %s" % disk)
var packed := _load_gltf(disk)
_mem[url] = packed
for cb: Callable in callbacks:
cb.call(packed.instantiate() if packed != null else null)
)
var err := http.request(url)
if err != OK:
push_warning("ModelCache: request() failed for %s (err %d)" % [url, err])
var callbacks: Array = _pending.get(url, [])
_pending.erase(url)
for cb: Callable in callbacks:
cb.call(null)
# Loads a .glb/.gltf from disk into a PackedScene for repeated instantiation.
func _load_gltf(path: String) -> PackedScene:
var doc := GLTFDocument.new()
var state := GLTFState.new()
var err := doc.append_from_file(path, state)
if err != OK:
push_warning("ModelCache: GLTFDocument error %d loading %s" % [err, path])
return null
var root := doc.generate_scene(state)
if root == null:
push_warning("ModelCache: generate_scene returned null for %s" % path)
return null
var packed := PackedScene.new()
var pack_err := packed.pack(root)
root.queue_free()
if pack_err != OK:
push_warning("ModelCache: PackedScene.pack() error %d for %s" % [pack_err, path])
return null
return packed
func _disk_path(url: String) -> String:
return _CACHE_DIR + url.sha256_text() + ".glb"
+1
View File
@@ -24,6 +24,7 @@ CollectionCache="*res://autoloads/CollectionCache.gd"
Chat="*res://autoloads/Chat.gd"
Settings="*res://autoloads/Settings.gd"
Game="*res://autoloads/Game.gd"
ModelCache="*res://autoloads/ModelCache.gd"
[display]
+54 -14
View File
@@ -143,7 +143,8 @@ var _friendly_unit_ids: Dictionary = {} # instanceId → true
# ── Scene refs ────────────────────────────────────────────────────────────────
var _tile_bodies : Dictionary = {} # "x,y" → StaticBody3D
var _unit_meshes : Dictionary = {} # instanceId → MeshInstance3D
var _unit_meshes : Dictionary = {} # instanceId → MeshInstance3D (placeholder)
var _unit_bodies : Dictionary = {} # instanceId → StaticBody3D
# ── Lifecycle ─────────────────────────────────────────────────────────────────
@@ -387,6 +388,7 @@ func _build_board(board: Dictionary) -> void:
for c in _hi_root.get_children(): c.queue_free()
_tile_bodies.clear()
_unit_meshes.clear()
_unit_bodies.clear()
for tile: Dictionary in board.get("tiles", []):
var coord : Dictionary = tile.get("coord", {})
_add_tile(coord.get("x", 0), coord.get("y", 0),
@@ -433,6 +435,7 @@ func _update_tile_affinity(x: int, y: int, affinity: String) -> void:
func _rebuild_units(state: Dictionary) -> void:
for c in _units_root.get_children(): c.queue_free()
_unit_meshes.clear()
_unit_bodies.clear()
var my_id := Auth.user_id
for player: Dictionary in state.get("players", []):
var is_mine : bool = str(player.get("accountId", "")).to_lower() == my_id.to_lower()
@@ -448,25 +451,24 @@ func _rebuild_units(state: Dictionary) -> void:
func _add_unit_mesh(unit: Dictionary, team_color: Color) -> void:
var pd : Dictionary = unit.get("position", {})
if pd.is_empty(): return
var wp := _coord_to_world(pd.get("x", 0), pd.get("y", 0))
var wp := _coord_to_world(pd.get("x", 0), pd.get("y", 0))
var card_type : String = unit.get("cardType", "Spirit")
var iid : String = unit.get("instanceId", "")
var exhausted : bool = unit.get("isExhausted", false)
var body := StaticBody3D.new()
var body := StaticBody3D.new()
body.set_meta("unit_id", iid)
var shape := CollisionShape3D.new()
var mi := MeshInstance3D.new()
var mat := StandardMaterial3D.new()
var shape := CollisionShape3D.new()
var mi := MeshInstance3D.new()
var mat := StandardMaterial3D.new()
mat.roughness = 0.65
var y_offset : float
match card_type:
"ArchSpirit":
var cyl := CylinderMesh.new()
cyl.top_radius = 0.22
cyl.bottom_radius = 0.22
cyl.height = 0.8
cyl.top_radius = 0.22; cyl.bottom_radius = 0.22; cyl.height = 0.8
mi.mesh = cyl
mat.albedo_color = team_color.lightened(0.25)
mat.emission_enabled = true
@@ -475,7 +477,6 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color) -> void:
cs.radius = 0.22; cs.height = 0.8
shape.shape = cs
y_offset = 0.5 + 0.4
"Ruin":
var bm := BoxMesh.new()
bm.size = Vector3(0.25, 1.0, 0.25)
@@ -485,11 +486,9 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color) -> void:
bs.size = Vector3(0.25, 1.0, 0.25)
shape.shape = bs
y_offset = 0.5 + 0.5
_:
var sm := SphereMesh.new()
sm.radius = 0.28
sm.height = 0.28
sm.radius = 0.28; sm.height = 0.28
mi.mesh = sm
mat.albedo_color = team_color
var ss := SphereShape3D.new()
@@ -498,7 +497,7 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color) -> void:
y_offset = 0.5 + 0.28
mi.material_override = mat
if unit.get("isExhausted", false):
if exhausted:
mat.albedo_color = mat.albedo_color.darkened(0.45)
body.add_child(shape)
@@ -506,6 +505,47 @@ func _add_unit_mesh(unit: Dictionary, team_color: Color) -> void:
body.position = wp + Vector3(0, y_offset, 0)
_units_root.add_child(body)
_unit_meshes[iid] = mi
_unit_bodies[iid] = body
# ── Try to load the real 3D model from the card definition ──────────────
var def_id : String = str(unit.get("cardDefinitionId", ""))
if def_id.is_empty():
return
var def := ContentCache.get_definition(def_id)
var model_url := _find_model3d_url(def)
if model_url.is_empty():
return
ModelCache.load_model(model_url, func(model_node: Node3D) -> void:
# Guard: body may have been freed by a state rebuild before load finished.
if not is_instance_valid(body):
if model_node != null:
model_node.queue_free()
return
if model_node == null:
return
# Remove the placeholder MeshInstance3D.
for child in body.get_children():
if child is MeshInstance3D:
child.queue_free()
# Position model so its local origin sits at the body's position.
# Models should be authored with their base (foot) at y = 0.
# Adjust the body back down so the model base lands on the tile surface.
body.position = wp + Vector3(0, 0.5, 0)
body.add_child(model_node)
_unit_meshes[iid] = model_node
)
func _find_model3d_url(def: Dictionary) -> String:
for asset: Variant in def.get("assets", []):
var d := asset as Dictionary
if d == null: continue
if str(d.get("assetType", "")) == "Model3D":
return str(d.get("cdnUrl", ""))
return ""
# ── Highlights ────────────────────────────────────────────────────────────────