- TileBottomModel gains a Shape column (Square/Hex, default Square) so admins can manage separate stalagmite pools per tile grid type - EF migration 20260407153312_AddTileBottomModelShape adds the column with a default of 'Square' to preserve existing data - Admin UI splits the Tile Bottom Models section into Square and Hex cards, each with their own Add/toggle/delete controls - content.tile_bottoms response now returns squareUrls and hexUrls separately; handler queries each shape independently - ContentCache splits into _tile_bottom_urls_square / _hex and get_random_tile_bottom_url() now takes a shape parameter - game_screen: hex tiles with no 3D model now receive a hex stalagmite instead of silently skipping; 3D-model path passes shape_key through 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>
435 lines
15 KiB
GDScript
435 lines
15 KiB
GDScript
extends Node
|
|
## Local card-definition cache.
|
|
##
|
|
## Syncs all published card definitions from the server using the
|
|
## content.sync message (cursor-based, incremental). Definitions are text
|
|
## only (stats, CDN URLs for art/models) — no binary assets are stored here.
|
|
##
|
|
## Also caches tile model bindings fetched via content.tile_models.
|
|
##
|
|
## Storage layout:
|
|
## user://content/defs.json — { "version": int, "defs": { id: dto } }
|
|
## user://content/tile_models.json — { "Forest_Square": "https://...", ... }
|
|
##
|
|
## Usage:
|
|
## ContentCache.start_sync()
|
|
## ContentCache.get_definition("some-guid") → Dictionary or {}
|
|
## ContentCache.get_tile_model_url("Forest", "Square") → String or ""
|
|
## ContentCache.sync_complete.connect(...)
|
|
|
|
const CACHE_DIR := "user://content"
|
|
const CACHE_PATH := "user://content/defs.json"
|
|
const TILE_MODELS_PATH := "user://content/tile_models.json"
|
|
const TILE_BOTTOMS_PATH := "user://content/tile_bottoms_v2.json"
|
|
const SKYBOXES_PATH := "user://content/skyboxes.json"
|
|
const PAGE_SIZE := 200
|
|
const REFRESH_INTERVAL_SECS := 300.0 # re-sync every 5 minutes during live play
|
|
|
|
signal sync_progress(fetched_total: int) ## Running count of total definitions in memory.
|
|
signal sync_complete(total: int) ## Emitted once sync finishes.
|
|
signal sync_failed(error: String) ## Emitted if sync cannot complete.
|
|
signal tile_models_ready ## Emitted when tile model bindings are loaded.
|
|
|
|
var _defs: Dictionary = {} ## definitionId (String) → definition Dictionary
|
|
var _sync_version: int = 0 ## Stored DefinitionVersion cursor.
|
|
var _is_syncing: bool = false
|
|
|
|
## "Affinity_Shape" (e.g. "Forest_Square") → CDN model URL string
|
|
var _tile_models: Dictionary = {}
|
|
|
|
## "Affinity_Shape" → CDN texture URL string (2D texture for placeholder tiles)
|
|
var _tile_textures: Dictionary = {}
|
|
|
|
## CDN URL strings for tile bottom (stalagmite) models, split by tile shape.
|
|
var _tile_bottom_urls_square: Array = []
|
|
var _tile_bottom_urls_hex: Array = []
|
|
|
|
## Array of Dictionary (SkyboxDefinitionDto) for all active skyboxes.
|
|
var _skyboxes: Array = []
|
|
|
|
# ── Lifecycle ─────────────────────────────────────────────────────────────────
|
|
|
|
func _ready() -> void:
|
|
_load_from_disk()
|
|
_load_tile_models_from_disk()
|
|
_load_tile_bottoms_from_disk()
|
|
_load_skyboxes_from_disk()
|
|
|
|
# ── Public API ────────────────────────────────────────────────────────────────
|
|
|
|
## Return the cached definition dictionary, or {} if not found.
|
|
func get_definition(id: String) -> Dictionary:
|
|
return _defs.get(id, {})
|
|
|
|
|
|
## True if the definition is cached.
|
|
func has_definition(id: String) -> bool:
|
|
return _defs.has(id)
|
|
|
|
|
|
## Returns all cached definition IDs.
|
|
func get_all_definition_ids() -> Array:
|
|
return _defs.keys()
|
|
|
|
|
|
## The current sync-version cursor (0 = never synced).
|
|
func get_sync_version() -> int:
|
|
return _sync_version
|
|
|
|
|
|
## Total number of definitions currently in memory.
|
|
func definition_count() -> int:
|
|
return _defs.size()
|
|
|
|
|
|
## True while a sync is in progress.
|
|
func is_syncing() -> bool:
|
|
return _is_syncing
|
|
|
|
|
|
## Start (or resume) the incremental sync.
|
|
## Emits sync_progress during, sync_complete or sync_failed when done.
|
|
## Also triggers a fresh fetch of tile model bindings and bottom models.
|
|
func start_sync() -> void:
|
|
if _is_syncing:
|
|
return
|
|
_is_syncing = true
|
|
_fetch_page(_sync_version)
|
|
fetch_tile_models()
|
|
fetch_tile_bottoms()
|
|
fetch_skyboxes()
|
|
|
|
|
|
## Return the GLB animation track name for a card action.
|
|
##
|
|
## Looks for an animationBinding with the given action_name (case-insensitive).
|
|
## If found and the binding has a non-empty animationTrackName, returns that.
|
|
## Otherwise returns the action_name itself so the caller can do its own
|
|
## case-insensitive fuzzy match against the AnimationPlayer's track list.
|
|
##
|
|
## card_def_id: card definition GUID string
|
|
## action_name: e.g. "attack", "idle", "death", "move"
|
|
func get_anim_track(card_def_id: String, action_name: String) -> String:
|
|
var def := get_definition(card_def_id)
|
|
var action_lower := action_name.to_lower()
|
|
for binding: Dictionary in def.get("animationBindings", []):
|
|
if str(binding.get("actionName", "")).to_lower() == action_lower:
|
|
var track := str(binding.get("animationTrackName", ""))
|
|
return track if not track.is_empty() else action_name
|
|
return action_name
|
|
|
|
|
|
## Return the CDN URL for a tile's 3D model, or "" if not assigned.
|
|
## affinity: e.g. "Forest" shape: "Square" or "Hex"
|
|
func get_tile_model_url(affinity: String, shape: String) -> String:
|
|
return _tile_models.get(affinity + "_" + shape, "")
|
|
|
|
|
|
## Return the CDN URL for a tile's 2D placeholder texture, or "" if not assigned.
|
|
func get_tile_texture_url(affinity: String, shape: String) -> String:
|
|
return _tile_textures.get(affinity + "_" + shape, "")
|
|
|
|
|
|
## Returns a random active tile bottom (stalagmite) CDN URL for the given shape,
|
|
## or "" if none are configured. shape should be "Square" or "Hex".
|
|
func get_random_tile_bottom_url(shape: String) -> String:
|
|
var pool := _tile_bottom_urls_hex if shape == "Hex" else _tile_bottom_urls_square
|
|
if pool.is_empty():
|
|
return ""
|
|
return pool[randi() % pool.size()] as String
|
|
|
|
|
|
## Fetch tile bottom model URLs from the server and update the local cache.
|
|
func fetch_tile_bottoms() -> void:
|
|
Network.request(
|
|
"content.tile_bottoms",
|
|
{},
|
|
func(_type: String, p: Variant): _on_tile_bottoms(p),
|
|
func(code: String, msg: String):
|
|
push_warning("ContentCache: tile_bottoms fetch failed — %s %s" % [code, msg])
|
|
)
|
|
|
|
|
|
## Fetch active skybox definitions from the server and update the local cache.
|
|
func fetch_skyboxes() -> void:
|
|
Network.request(
|
|
"content.get_skybox_config",
|
|
{},
|
|
func(_type: String, p: Variant): _on_skyboxes(p),
|
|
func(code: String, msg: String):
|
|
push_warning("ContentCache: skyboxes fetch failed — %s %s" % [code, msg])
|
|
)
|
|
|
|
|
|
## Returns a random active skybox Dictionary, or {} if none are cached.
|
|
func get_random_skybox() -> Dictionary:
|
|
if _skyboxes.is_empty():
|
|
return {}
|
|
return _skyboxes[randi() % _skyboxes.size()] as Dictionary
|
|
|
|
|
|
## Returns the best URL to use as a flat 2D background from this skybox dict.
|
|
## For Cubemap: returns the +Z (Front) face URL.
|
|
## For Panoramic/AnimatedPanorama: returns the cdnPath.
|
|
func get_skybox_bg_url(skybox: Dictionary) -> String:
|
|
var sky_type := str(skybox.get("type", "Panoramic"))
|
|
if sky_type == "Cubemap":
|
|
return str(skybox.get("cubePzUrl", ""))
|
|
return str(skybox.get("cdnPath", ""))
|
|
|
|
|
|
## Downloads an image from url and calls callback(Texture2D).
|
|
## Adds a temporary HTTPRequest child; frees itself on completion.
|
|
func load_texture_async(url: String, callback: Callable) -> void:
|
|
var http := HTTPRequest.new()
|
|
add_child(http)
|
|
http.request_completed.connect(func(result: int, code: int, _hdrs: PackedStringArray, body: PackedByteArray):
|
|
http.queue_free()
|
|
if result != HTTPRequest.RESULT_SUCCESS or code != 200:
|
|
callback.call(null)
|
|
return
|
|
var img := Image.new()
|
|
var ext := url.split("?")[0].get_extension().to_lower()
|
|
var err: Error
|
|
if ext in ["jpg", "jpeg"]:
|
|
err = img.load_jpg_from_buffer(body)
|
|
elif ext == "webp":
|
|
err = img.load_webp_from_buffer(body)
|
|
else:
|
|
err = img.load_png_from_buffer(body)
|
|
if err != OK:
|
|
callback.call(null)
|
|
return
|
|
callback.call(ImageTexture.create_from_image(img)))
|
|
http.request(url)
|
|
|
|
|
|
## Hides the first direct-child ColorRect of `parent` and injects a full-rect
|
|
## TextureRect (from a random active skybox) as the new first child.
|
|
## The texture slowly scrolls horizontally to match the 3D sky rotation feel.
|
|
## Call from _ready() in any 2D scene that has a solid-color background.
|
|
func apply_scene_background(parent: Control) -> void:
|
|
var skybox := get_random_skybox()
|
|
if skybox.is_empty():
|
|
return
|
|
var url := get_skybox_bg_url(skybox)
|
|
if url.is_empty():
|
|
return
|
|
load_texture_async(url, func(tex: Texture2D):
|
|
if not is_instance_valid(parent) or tex == null:
|
|
return
|
|
for child in parent.get_children():
|
|
if child is ColorRect:
|
|
child.visible = false
|
|
break
|
|
var tr := TextureRect.new()
|
|
tr.texture = tex
|
|
tr.expand_mode = TextureRect.EXPAND_IGNORE_SIZE
|
|
tr.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_COVERED
|
|
tr.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
|
|
tr.mouse_filter = Control.MOUSE_FILTER_IGNORE
|
|
# Slowly scroll UV horizontally — same ~4-min revolution as the 3D sky rotation.
|
|
var shader := Shader.new()
|
|
shader.code = "shader_type canvas_item;\nvoid fragment() {\n\tvec2 uv = UV;\n\tuv.x = fract(uv.x + TIME * 0.004);\n\tCOLOR = texture(TEXTURE, uv);\n}\n"
|
|
var mat := ShaderMaterial.new()
|
|
mat.shader = shader
|
|
tr.material = mat
|
|
parent.add_child(tr)
|
|
parent.move_child(tr, 0))
|
|
|
|
|
|
## Fetch tile model bindings from the server and update the local cache.
|
|
## Emits tile_models_ready when done (even on error, using cached data).
|
|
func fetch_tile_models() -> void:
|
|
Network.request(
|
|
"content.tile_models",
|
|
{},
|
|
func(_type: String, p: Variant): _on_tile_models(p),
|
|
func(code: String, msg: String):
|
|
push_warning("ContentCache: tile_models fetch failed — %s %s" % [code, msg])
|
|
tile_models_ready.emit()
|
|
)
|
|
|
|
# ── Sync loop ─────────────────────────────────────────────────────────────────
|
|
|
|
func _fetch_page(since_version: int) -> void:
|
|
Network.request(
|
|
"content.sync",
|
|
{ "sinceVersion": since_version, "pageSize": PAGE_SIZE },
|
|
func(_type: String, p: Variant): _on_page(p),
|
|
func(code: String, msg: String): _on_error(code, msg)
|
|
)
|
|
|
|
|
|
func _on_page(payload: Variant) -> void:
|
|
var p := payload as Dictionary
|
|
var cards : Array = p.get("cards", [])
|
|
var next_ver : int = p.get("currentVersion", _sync_version)
|
|
var has_more : bool = p.get("hasMore", false)
|
|
|
|
for card in cards:
|
|
var id: String = str(card.get("id", ""))
|
|
if not id.is_empty():
|
|
_defs[id] = card
|
|
|
|
_sync_version = next_ver
|
|
sync_progress.emit(_defs.size())
|
|
|
|
if has_more:
|
|
_fetch_page(next_ver)
|
|
else:
|
|
_is_syncing = false
|
|
_save_to_disk()
|
|
sync_complete.emit(_defs.size())
|
|
# Schedule next background refresh so live content patches are picked up
|
|
# without restarting the client.
|
|
get_tree().create_timer(REFRESH_INTERVAL_SECS).timeout.connect(
|
|
func() -> void: start_sync(), CONNECT_ONE_SHOT)
|
|
|
|
|
|
func _on_error(code: String, msg: String) -> void:
|
|
_is_syncing = false
|
|
var detail := msg if not msg.is_empty() else code
|
|
push_warning("ContentCache: sync failed — %s" % detail)
|
|
sync_failed.emit(detail)
|
|
|
|
|
|
func _on_tile_models(payload: Variant) -> void:
|
|
var p := payload as Dictionary
|
|
var bindings : Array = p.get("bindings", [])
|
|
_tile_models.clear()
|
|
_tile_textures.clear()
|
|
for item in bindings:
|
|
var d := item as Dictionary
|
|
if d == null: continue
|
|
var key := str(d.get("affinity", "")) + "_" + str(d.get("shape", ""))
|
|
if key.is_empty(): continue
|
|
var model_url := str(d.get("modelPublicUrl", ""))
|
|
if not model_url.is_empty():
|
|
_tile_models[key] = model_url
|
|
var tex_url := str(d.get("texturePublicUrl", ""))
|
|
if not tex_url.is_empty() and tex_url != "null":
|
|
_tile_textures[key] = tex_url
|
|
_save_tile_models_to_disk()
|
|
tile_models_ready.emit()
|
|
|
|
|
|
func _on_tile_bottoms(payload: Variant) -> void:
|
|
var p := payload as Dictionary
|
|
_tile_bottom_urls_square.clear()
|
|
_tile_bottom_urls_hex.clear()
|
|
for u in p.get("squareUrls", []):
|
|
if typeof(u) == TYPE_STRING and not (u as String).is_empty():
|
|
_tile_bottom_urls_square.append(u as String)
|
|
for u in p.get("hexUrls", []):
|
|
if typeof(u) == TYPE_STRING and not (u as String).is_empty():
|
|
_tile_bottom_urls_hex.append(u as String)
|
|
_save_tile_bottoms_to_disk()
|
|
|
|
|
|
func _on_skyboxes(payload: Variant) -> void:
|
|
var p := payload as Dictionary
|
|
_skyboxes.clear()
|
|
for item in p.get("skyboxes", []):
|
|
if typeof(item) == TYPE_DICTIONARY:
|
|
_skyboxes.append(item as Dictionary)
|
|
_save_skyboxes_to_disk()
|
|
|
|
# ── Persistence ───────────────────────────────────────────────────────────────
|
|
|
|
func _load_from_disk() -> void:
|
|
if not FileAccess.file_exists(CACHE_PATH):
|
|
return
|
|
var file := FileAccess.open(CACHE_PATH, FileAccess.READ)
|
|
if not file:
|
|
push_warning("ContentCache: could not open cache file")
|
|
return
|
|
var text := file.get_as_text()
|
|
file.close()
|
|
var parsed: Variant = JSON.parse_string(text)
|
|
if typeof(parsed) != TYPE_DICTIONARY:
|
|
push_warning("ContentCache: cache file is malformed — starting fresh")
|
|
return
|
|
var root := parsed as Dictionary
|
|
_sync_version = int(root.get("version", 0))
|
|
var defs: Variant = root.get("defs", {})
|
|
if typeof(defs) == TYPE_DICTIONARY:
|
|
_defs = defs as Dictionary
|
|
|
|
|
|
func _save_to_disk() -> void:
|
|
DirAccess.make_dir_recursive_absolute(CACHE_DIR)
|
|
var file := FileAccess.open(CACHE_PATH, FileAccess.WRITE)
|
|
if not file:
|
|
push_warning("ContentCache: could not write cache file")
|
|
return
|
|
file.store_string(JSON.stringify({ "version": _sync_version, "defs": _defs }))
|
|
file.close()
|
|
|
|
|
|
func _load_tile_models_from_disk() -> void:
|
|
if not FileAccess.file_exists(TILE_MODELS_PATH):
|
|
return
|
|
var file := FileAccess.open(TILE_MODELS_PATH, FileAccess.READ)
|
|
if not file:
|
|
return
|
|
var parsed: Variant = JSON.parse_string(file.get_as_text())
|
|
file.close()
|
|
if typeof(parsed) == TYPE_DICTIONARY:
|
|
_tile_models = parsed as Dictionary
|
|
|
|
|
|
func _save_tile_models_to_disk() -> void:
|
|
DirAccess.make_dir_recursive_absolute(CACHE_DIR)
|
|
var file := FileAccess.open(TILE_MODELS_PATH, FileAccess.WRITE)
|
|
if not file:
|
|
return
|
|
file.store_string(JSON.stringify(_tile_models))
|
|
file.close()
|
|
|
|
|
|
func _load_tile_bottoms_from_disk() -> void:
|
|
if not FileAccess.file_exists(TILE_BOTTOMS_PATH):
|
|
return
|
|
var file := FileAccess.open(TILE_BOTTOMS_PATH, FileAccess.READ)
|
|
if not file:
|
|
return
|
|
var parsed: Variant = JSON.parse_string(file.get_as_text())
|
|
file.close()
|
|
if typeof(parsed) == TYPE_DICTIONARY:
|
|
var d := parsed as Dictionary
|
|
if typeof(d.get("square")) == TYPE_ARRAY:
|
|
_tile_bottom_urls_square = d["square"] as Array
|
|
if typeof(d.get("hex")) == TYPE_ARRAY:
|
|
_tile_bottom_urls_hex = d["hex"] as Array
|
|
|
|
|
|
func _save_tile_bottoms_to_disk() -> void:
|
|
DirAccess.make_dir_recursive_absolute(CACHE_DIR)
|
|
var file := FileAccess.open(TILE_BOTTOMS_PATH, FileAccess.WRITE)
|
|
if not file:
|
|
return
|
|
file.store_string(JSON.stringify({ "square": _tile_bottom_urls_square, "hex": _tile_bottom_urls_hex }))
|
|
file.close()
|
|
|
|
|
|
func _load_skyboxes_from_disk() -> void:
|
|
if not FileAccess.file_exists(SKYBOXES_PATH):
|
|
return
|
|
var file := FileAccess.open(SKYBOXES_PATH, FileAccess.READ)
|
|
if not file:
|
|
return
|
|
var parsed: Variant = JSON.parse_string(file.get_as_text())
|
|
file.close()
|
|
if typeof(parsed) == TYPE_ARRAY:
|
|
_skyboxes = parsed as Array
|
|
|
|
|
|
func _save_skyboxes_to_disk() -> void:
|
|
DirAccess.make_dir_recursive_absolute(CACHE_DIR)
|
|
var file := FileAccess.open(SKYBOXES_PATH, FileAccess.WRITE)
|
|
if not file:
|
|
return
|
|
file.store_string(JSON.stringify(_skyboxes))
|
|
file.close()
|