Legal docs draft and Client refactor
This commit is contained in:
@@ -0,0 +1,712 @@
|
||||
class_name UnitAnimator
|
||||
extends Node
|
||||
|
||||
## Handles animation orchestration, hitsplat display, and movement animation.
|
||||
##
|
||||
## Reads scene dictionaries from mesh_builder (unit_bodies, anim_players, etc.)
|
||||
## and from unit_registry (unit_def_ids) via mesh_builder.unit_registry.
|
||||
## Requires mesh_builder and camera to be set by the parent before any call.
|
||||
|
||||
# ── External dependencies (set by parent) ─────────────────────────────────────
|
||||
|
||||
var mesh_builder: UnitMeshBuilder = null
|
||||
var camera: Camera3D = null
|
||||
|
||||
# ── Hitsplat icons ────────────────────────────────────────────────────────────
|
||||
|
||||
const _HITSPLAT_SHIELD_ICON: Texture2D = preload("res://ui/icons/Shield_Overlay_Gradient.png")
|
||||
const _HITSPLAT_HEART_ICON: Texture2D = preload("res://ui/icons/Heart_Overlay_Gradient.png")
|
||||
|
||||
# ── Owned state ───────────────────────────────────────────────────────────────
|
||||
|
||||
var prev_unit_hp: Dictionary = {} # instanceId → int
|
||||
var prev_unit_def: Dictionary = {} # instanceId → int
|
||||
var prev_unit_pos: Dictionary = {} # instanceId → Vector2i
|
||||
var last_attack_source_iid: String = ""
|
||||
var last_attack_target_iid: String = ""
|
||||
var hitsplat_layer: Control = null
|
||||
var hitsplat_canvas_layer: CanvasLayer = null
|
||||
|
||||
# ── Hitsplat layer ────────────────────────────────────────────────────────────
|
||||
|
||||
func ensure_hitsplat_layer() -> Control:
|
||||
if is_instance_valid(hitsplat_layer):
|
||||
return hitsplat_layer
|
||||
# Own CanvasLayer (layer 15) so hitsplats always render above the HUD (10)
|
||||
# and all dynamic panels added to _hud, but below card popups (20).
|
||||
hitsplat_canvas_layer = CanvasLayer.new()
|
||||
hitsplat_canvas_layer.layer = 15
|
||||
hitsplat_canvas_layer.name = "HitsplatCanvas"
|
||||
get_parent().add_child(hitsplat_canvas_layer)
|
||||
hitsplat_layer = Control.new()
|
||||
hitsplat_layer.name = "HitsplatLayer"
|
||||
hitsplat_layer.mouse_filter = Control.MOUSE_FILTER_IGNORE
|
||||
hitsplat_canvas_layer.add_child(hitsplat_layer)
|
||||
hitsplat_layer.set_anchors_preset(Control.PRESET_FULL_RECT)
|
||||
return hitsplat_layer
|
||||
|
||||
|
||||
func hitsplat_screen_pos(iid: String) -> Vector2:
|
||||
var body: StaticBody3D = mesh_builder.unit_bodies.get(iid) as StaticBody3D
|
||||
if not is_instance_valid(body):
|
||||
return Vector2.ZERO
|
||||
var above_tile: float = float(body.get_meta("above_tile", 0.28))
|
||||
var world_pos: Vector3 = body.global_position + Vector3(0.0, above_tile + 0.9, 0.0)
|
||||
return camera.unproject_position(world_pos)
|
||||
|
||||
|
||||
func queue_hitsplats(iid: String, def_amount: int, hp_amount: int, delay: float = 0.0) -> void:
|
||||
if def_amount <= 0 and hp_amount <= 0:
|
||||
return
|
||||
if delay > 0.0:
|
||||
var queued_iid: String = iid
|
||||
var queued_def: int = def_amount
|
||||
var queued_hp: int = hp_amount
|
||||
var queued_anchor: Vector2 = hitsplat_screen_pos(iid)
|
||||
var t: Tween = create_tween()
|
||||
t.tween_callback(func() -> void:
|
||||
if queued_anchor == Vector2.ZERO:
|
||||
show_hitsplats(queued_iid, queued_def, queued_hp)
|
||||
else:
|
||||
show_hitsplats_at_anchor(queued_iid, queued_def, queued_hp, queued_anchor)
|
||||
).set_delay(delay)
|
||||
return
|
||||
show_hitsplats(iid, def_amount, hp_amount)
|
||||
|
||||
|
||||
func show_hitsplats_once(shown: Dictionary, iid: String, def_amount: int, hp_amount: int,
|
||||
delay: float = 0.0) -> void:
|
||||
if def_amount <= 0 and hp_amount <= 0:
|
||||
return
|
||||
if shown.has(iid):
|
||||
return
|
||||
shown[iid] = true
|
||||
queue_hitsplats(iid, def_amount, hp_amount, delay)
|
||||
|
||||
|
||||
func show_hitsplats(iid: String, def_amount: int, hp_amount: int) -> void:
|
||||
print("[HITSPLAT] show_hitsplats iid=%s def=%d hp=%d" % [iid.substr(0, 8), def_amount, hp_amount])
|
||||
if not mesh_builder.unit_bodies.has(iid):
|
||||
print("[HITSPLAT] skipped — iid not in unit_bodies")
|
||||
return
|
||||
var anchor: Vector2 = hitsplat_screen_pos(iid)
|
||||
if anchor == Vector2.ZERO:
|
||||
print("[HITSPLAT] skipped — anchor is Vector2.ZERO (body invalid or not yet placed)")
|
||||
return
|
||||
show_hitsplats_at_anchor(iid, def_amount, hp_amount, anchor)
|
||||
|
||||
|
||||
func show_hitsplats_at_anchor(iid: String, def_amount: int, hp_amount: int, anchor: Vector2) -> void:
|
||||
if def_amount > 0:
|
||||
spawn_hitsplat(iid, def_amount, "Shield", _HITSPLAT_SHIELD_ICON, Color(0.24, 0.58, 1.0), anchor)
|
||||
if hp_amount > 0:
|
||||
# When both fire, delay the heart so shield appears first.
|
||||
if def_amount > 0:
|
||||
var q_iid: String = iid
|
||||
var q_hp: int = hp_amount
|
||||
var q_anchor: Vector2 = anchor
|
||||
var t: Tween = create_tween()
|
||||
t.tween_callback(func() -> void:
|
||||
spawn_hitsplat(q_iid, q_hp, "Heart", _HITSPLAT_HEART_ICON, Color(0.92, 0.24, 0.24), q_anchor)
|
||||
).set_delay(0.2)
|
||||
else:
|
||||
spawn_hitsplat(iid, hp_amount, "Heart", _HITSPLAT_HEART_ICON, Color(0.92, 0.24, 0.24), anchor)
|
||||
|
||||
|
||||
func spawn_hitsplat(iid: String, amount: int, icon_label: String, icon: Texture2D, tint: Color, anchor: Vector2) -> void:
|
||||
print("[HITSPLAT] %s amount=%d iid=%s" % [icon_label, amount, iid.substr(0, 8)])
|
||||
if amount <= 0:
|
||||
print("[HITSPLAT] skipped — amount <= 0")
|
||||
return
|
||||
var layer: Control = ensure_hitsplat_layer()
|
||||
if not is_instance_valid(layer):
|
||||
print("[HITSPLAT] skipped — layer invalid")
|
||||
return
|
||||
print("[HITSPLAT] spawning at screen pos %s" % anchor)
|
||||
var root: Control = Control.new()
|
||||
root.mouse_filter = Control.MOUSE_FILTER_IGNORE
|
||||
root.size = Vector2(96.0, 40.0)
|
||||
root.pivot_offset = root.size * 0.5
|
||||
root.position = anchor - root.size * 0.5 + Vector2(0.0, -14.0)
|
||||
layer.add_child(root)
|
||||
|
||||
var icon_rect: TextureRect = TextureRect.new()
|
||||
icon_rect.texture = icon
|
||||
icon_rect.expand_mode = TextureRect.EXPAND_IGNORE_SIZE
|
||||
icon_rect.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
|
||||
icon_rect.position = Vector2(0.0, 2.0)
|
||||
icon_rect.size = Vector2(34.0, 34.0)
|
||||
icon_rect.modulate = tint
|
||||
root.add_child(icon_rect)
|
||||
|
||||
var lbl: Label = Label.new()
|
||||
lbl.text = str(amount)
|
||||
lbl.position = Vector2(28.0, 0.0)
|
||||
lbl.size = Vector2(68.0, 36.0)
|
||||
lbl.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
|
||||
lbl.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
|
||||
lbl.add_theme_font_size_override("font_size", 20)
|
||||
lbl.add_theme_color_override("font_color", Color.WHITE)
|
||||
root.add_child(lbl)
|
||||
|
||||
var tw: Tween = create_tween()
|
||||
tw.set_parallel(true)
|
||||
tw.tween_property(root, "position", root.position + Vector2(0.0, -GameConstants.HITSPLAT_RISE_PIXELS), GameConstants.HITSPLAT_LIFETIME)\
|
||||
.set_trans(Tween.TRANS_CUBIC).set_ease(Tween.EASE_OUT)
|
||||
tw.tween_property(root, "modulate:a", 0.0, GameConstants.HITSPLAT_LIFETIME)\
|
||||
.set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN)
|
||||
tw.finished.connect(func() -> void:
|
||||
if is_instance_valid(root):
|
||||
root.queue_free()
|
||||
)
|
||||
|
||||
# ── Animation playback ────────────────────────────────────────────────────────
|
||||
|
||||
## Play an animation on a unit by action name. Uses card's AnimationTrackName
|
||||
## override when set, then falls back to case-insensitive convention matching.
|
||||
## Pass loop=true for looping animations (e.g. idle, moving).
|
||||
## GLB convention: the first ANIM_TRANSITION_SECS of any animation are
|
||||
## "entry frames" that blend from idle into the action. For looping animations
|
||||
## those frames are played once on entry, then skipped on every subsequent loop.
|
||||
func play_unit_anim(iid: String, action: String, loop: bool = false) -> void:
|
||||
var ap: AnimationPlayer = mesh_builder.anim_players.get(iid, null) as AnimationPlayer
|
||||
if ap == null or not is_instance_valid(ap):
|
||||
return
|
||||
# Resolve via CardAnimationBinding override first.
|
||||
var def_id: String = mesh_builder.unit_registry.unit_def_ids.get(iid, "")
|
||||
var desired: String = action
|
||||
if not def_id.is_empty():
|
||||
var override: String = ContentCache.get_anim_track(def_id, action)
|
||||
if not override.is_empty():
|
||||
desired = override
|
||||
var track: String = mesh_builder.resolve_anim_track(ap, desired.to_lower())
|
||||
if track.is_empty():
|
||||
return
|
||||
var anim: Animation = ap.get_animation(track)
|
||||
if anim == null:
|
||||
return
|
||||
|
||||
# All animations are managed with LOOP_NONE; looping is handled manually
|
||||
# so we can seek past the transition frames on subsequent iterations.
|
||||
anim.loop_mode = Animation.LOOP_NONE
|
||||
|
||||
# Disconnect any stale idle loop callback that would restart idle unexpectedly.
|
||||
if mesh_builder.idle_callbacks.has(iid):
|
||||
var old_cb: Callable = mesh_builder.idle_callbacks[iid] as Callable
|
||||
if ap.animation_finished.is_connected(old_cb):
|
||||
ap.animation_finished.disconnect(old_cb)
|
||||
mesh_builder.idle_callbacks.erase(iid)
|
||||
|
||||
# Don't restart the same animation while it's already playing correctly.
|
||||
if ap.current_animation == track and ap.is_playing():
|
||||
return
|
||||
|
||||
# Starting a non-loop animation: reset entry-done so the NEXT idle play
|
||||
# uses the transition frames to blend back from the action pose.
|
||||
if not loop:
|
||||
mesh_builder.idle_entry_done.erase(iid)
|
||||
|
||||
ap.play(track)
|
||||
|
||||
if loop:
|
||||
# On subsequent loop iterations skip the GLB entry frames.
|
||||
if mesh_builder.idle_entry_done.get(iid, false):
|
||||
ap.seek(GameConstants.ANIM_TRANSITION_SECS, true)
|
||||
else:
|
||||
mesh_builder.idle_entry_done[iid] = true
|
||||
# Schedule the next loop iteration via animation_finished.
|
||||
var cb: Callable = func(_n: String) -> void: play_unit_anim(iid, action, true)
|
||||
ap.animation_finished.connect(cb, CONNECT_ONE_SHOT)
|
||||
mesh_builder.idle_callbacks[iid] = cb
|
||||
else:
|
||||
# For one-shot non-death animations: return to idle via animation_finished.
|
||||
var action_l: String = action.to_lower()
|
||||
var is_death: bool = action_l == "dying" or action_l == "death" or action_l == "die"
|
||||
if not is_death:
|
||||
# Disconnect any prior oneshot callback — allows play_damage_animations to
|
||||
# replace "return-to-idle" with "play-damaged-then-idle" on an attacking unit.
|
||||
if mesh_builder.oneshot_callbacks.has(iid):
|
||||
var old_os: Callable = mesh_builder.oneshot_callbacks[iid] as Callable
|
||||
if ap.animation_finished.is_connected(old_os):
|
||||
ap.animation_finished.disconnect(old_os)
|
||||
mesh_builder.oneshot_callbacks.erase(iid)
|
||||
var os_cb: Callable = func(_n: String) -> void: play_unit_anim(iid, "idle", true)
|
||||
ap.animation_finished.connect(os_cb, CONNECT_ONE_SHOT)
|
||||
mesh_builder.oneshot_callbacks[iid] = os_cb
|
||||
|
||||
|
||||
## Returns the duration of the named animation for iid, or fallback if unavailable.
|
||||
func unit_action_duration(iid: String, action: String, fallback: float = 0.35) -> float:
|
||||
var ap: AnimationPlayer = mesh_builder.anim_players.get(iid, null) as AnimationPlayer
|
||||
if ap == null or not is_instance_valid(ap):
|
||||
return fallback
|
||||
var def_id: String = mesh_builder.unit_registry.unit_def_ids.get(iid, "")
|
||||
var desired: String = action
|
||||
if not def_id.is_empty():
|
||||
var override: String = ContentCache.get_anim_track(def_id, action)
|
||||
if not override.is_empty():
|
||||
desired = override
|
||||
var track: String = mesh_builder.resolve_anim_track(ap, desired.to_lower())
|
||||
if track.is_empty():
|
||||
return fallback
|
||||
var anim: Animation = ap.get_animation(track)
|
||||
if anim == null:
|
||||
return fallback
|
||||
return maxf(fallback, float(anim.length))
|
||||
|
||||
|
||||
## Returns the SFX CDN URL for a given unit and sound key, or "" if none assigned.
|
||||
## sfx_key is the camelCase DTO field name, e.g. "attackSoundUrl".
|
||||
func sfx_for_unit(iid: String, sfx_key: String) -> String:
|
||||
var def_id: String = mesh_builder.unit_registry.unit_def_ids.get(iid, "")
|
||||
if def_id.is_empty():
|
||||
return ""
|
||||
var def: Dictionary = ContentCache.get_definition(def_id)
|
||||
return str(def.get(sfx_key, ""))
|
||||
|
||||
|
||||
## Prime SFX URLs for a unit definition so they are ready when needed.
|
||||
func prime_unit_sfx(def: Dictionary) -> void:
|
||||
if def.is_empty():
|
||||
return
|
||||
for sfx_key: String in GameConstants.UNIT_SFX_KEYS:
|
||||
var url: String = str(def.get(sfx_key, "")).strip_edges()
|
||||
if not url.is_empty():
|
||||
SFX.prime(url)
|
||||
|
||||
|
||||
## Returns true if the AnimationPlayer's current track is an "attack" animation.
|
||||
func is_attack_track(full_name: String) -> bool:
|
||||
var s: String = full_name.get_slice("/", full_name.get_slice_count("/") - 1)
|
||||
for alias: String in GameConstants.ANIM_ALIASES.get("attack", []):
|
||||
if s.to_lower() == alias:
|
||||
return true
|
||||
if "." in s and s.get_slice(".", s.get_slice_count(".") - 1).to_lower() == alias:
|
||||
return true
|
||||
if "_" in s and s.substr(s.find("_") + 1).to_lower() == alias:
|
||||
return true
|
||||
return false
|
||||
|
||||
|
||||
## Replaces the pending animation_finished one-shot callback for iid.
|
||||
## Disconnects the previous callback (stored in oneshot_callbacks) and
|
||||
## connects cb as a new CONNECT_ONE_SHOT handler.
|
||||
func override_oneshot(iid: String, cb: Callable) -> void:
|
||||
var ap: AnimationPlayer = mesh_builder.anim_players.get(iid, null) as AnimationPlayer
|
||||
if ap == null or not is_instance_valid(ap):
|
||||
return
|
||||
if mesh_builder.oneshot_callbacks.has(iid):
|
||||
var old_cb: Callable = mesh_builder.oneshot_callbacks[iid] as Callable
|
||||
if ap.animation_finished.is_connected(old_cb):
|
||||
ap.animation_finished.disconnect(old_cb)
|
||||
mesh_builder.oneshot_callbacks.erase(iid)
|
||||
ap.animation_finished.connect(cb, CONNECT_ONE_SHOT)
|
||||
mesh_builder.oneshot_callbacks[iid] = cb
|
||||
|
||||
# ── Counterattack helpers ─────────────────────────────────────────────────────
|
||||
|
||||
## Counterattack phase 2: defender plays "attack", then triggers attacker "damaged".
|
||||
func play_counter_attack(defender_iid: String, attacker_iid: String,
|
||||
attacker_def_loss: int, attacker_hp_loss: int, hitsplats_shown: Dictionary) -> void:
|
||||
if not mesh_builder.unit_bodies.has(defender_iid):
|
||||
return
|
||||
if not is_instance_valid(mesh_builder.unit_bodies.get(defender_iid) as Node):
|
||||
return
|
||||
play_unit_anim(defender_iid, "attack", false)
|
||||
SFX.play(sfx_for_unit(defender_iid, "attackSoundUrl"))
|
||||
var counter_time: float = unit_action_duration(defender_iid, "attack")
|
||||
var t: Tween = create_tween()
|
||||
t.tween_callback(func() -> void:
|
||||
play_unit_anim(defender_iid, "idle", true)
|
||||
if mesh_builder.unit_bodies.has(attacker_iid) and \
|
||||
is_instance_valid(mesh_builder.unit_bodies.get(attacker_iid) as Node):
|
||||
play_unit_anim(attacker_iid, "damaged", false)
|
||||
SFX.play(sfx_for_unit(attacker_iid, "damagedSoundUrl"))
|
||||
show_hitsplats_once(hitsplats_shown, attacker_iid, attacker_def_loss, attacker_hp_loss)
|
||||
).set_delay(counter_time)
|
||||
|
||||
|
||||
## Full counterattack chain (starts after delay seconds):
|
||||
## delay → defender "damaged" → defender "attack" → attacker "damaged" + defender "idle"
|
||||
func play_counter_chain(defender_iid: String, attacker_iid: String, delay: float,
|
||||
defender_def_loss: int, defender_hp_loss: int,
|
||||
attacker_def_loss: int, attacker_hp_loss: int,
|
||||
hitsplats_shown: Dictionary) -> void:
|
||||
var t: Tween = create_tween()
|
||||
t.tween_callback(func() -> void:
|
||||
if not mesh_builder.unit_bodies.has(defender_iid) or \
|
||||
not is_instance_valid(mesh_builder.unit_bodies.get(defender_iid) as Node):
|
||||
return
|
||||
play_unit_anim(defender_iid, "damaged", false)
|
||||
SFX.play(sfx_for_unit(defender_iid, "damagedSoundUrl"))
|
||||
show_hitsplats_once(hitsplats_shown, defender_iid, defender_def_loss, defender_hp_loss)
|
||||
var damaged_time: float = unit_action_duration(defender_iid, "damaged")
|
||||
var td: Tween = create_tween()
|
||||
td.tween_callback(func() -> void:
|
||||
play_counter_attack(defender_iid, attacker_iid, attacker_def_loss, attacker_hp_loss, hitsplats_shown)
|
||||
).set_delay(damaged_time)
|
||||
).set_delay(delay)
|
||||
|
||||
# ── Damage animations ─────────────────────────────────────────────────────────
|
||||
|
||||
## Detect HP decreases and unit deaths vs previous state, and fire animations.
|
||||
##
|
||||
## Counterattack scenario (attacker AND a second unit both took damage this update):
|
||||
## delay(attack_remaining) → defender "damaged" → defender "attack" → attacker "damaged"
|
||||
##
|
||||
## Simple damage scenario:
|
||||
## attacker mid-attack + took damage → queue "damaged" behind its attack
|
||||
## other unit, attack in progress → delay "damaged" by attack_remaining
|
||||
## no attack in progress → play "damaged" immediately
|
||||
##
|
||||
## Returns true if any animation was triggered (used to decide rebuild delay).
|
||||
func play_damage_animations(state: Dictionary) -> bool:
|
||||
if prev_unit_hp.is_empty():
|
||||
return false
|
||||
|
||||
# ── Find any currently-playing attack animation ──────────────────────────
|
||||
var attacker_iid: String = ""
|
||||
var attack_remaining: float = 0.0
|
||||
for iid: String in mesh_builder.anim_players:
|
||||
var ap2: AnimationPlayer = mesh_builder.anim_players[iid] as AnimationPlayer
|
||||
if ap2 == null or not is_instance_valid(ap2) or not ap2.is_playing():
|
||||
continue
|
||||
if is_attack_track(ap2.current_animation):
|
||||
attacker_iid = iid
|
||||
attack_remaining = maxf(0.0,
|
||||
ap2.current_animation_length - ap2.current_animation_position)
|
||||
break
|
||||
if attacker_iid.is_empty() and not last_attack_source_iid.is_empty() \
|
||||
and mesh_builder.unit_bodies.has(last_attack_source_iid):
|
||||
attacker_iid = last_attack_source_iid
|
||||
attack_remaining = unit_action_duration(attacker_iid, "attack")
|
||||
|
||||
# ── Collect who took damage / died ───────────────────────────────────────
|
||||
var damaged_iids: Dictionary = {}
|
||||
var defense_hits: Dictionary = {}
|
||||
var health_hits: Dictionary = {}
|
||||
var seen_iids: Dictionary = {}
|
||||
for player: Dictionary in state.get("players", []):
|
||||
var _arch_raw: Variant = player.get("archSpirit")
|
||||
var _arch_list: Array = [] if _arch_raw == null else [_arch_raw]
|
||||
for unit: Dictionary in (_arch_list + player.get("field", [])):
|
||||
if unit.is_empty():
|
||||
continue
|
||||
var iid: String = str(unit.get("instanceId", ""))
|
||||
var _hp_v: Variant = unit.get("currentHealth")
|
||||
var _def_v: Variant = unit.get("currentDefense")
|
||||
var new_hp: int = 0 if _hp_v == null else int(_hp_v)
|
||||
var new_def: int = 0 if _def_v == null else int(_def_v)
|
||||
var old_hp: int = prev_unit_hp.get(iid, new_hp)
|
||||
var old_def: int = prev_unit_def.get(iid, new_def)
|
||||
seen_iids[iid] = true
|
||||
if new_def < old_def:
|
||||
defense_hits[iid] = old_def - new_def
|
||||
if new_hp < old_hp:
|
||||
health_hits[iid] = old_hp - new_hp
|
||||
damaged_iids[iid] = true
|
||||
|
||||
var dying_iids: Dictionary = {}
|
||||
for iid: String in prev_unit_hp:
|
||||
if not seen_iids.has(iid):
|
||||
dying_iids[iid] = true
|
||||
var dying_old_hp: int = int(prev_unit_hp.get(iid, 0))
|
||||
if dying_old_hp > 0:
|
||||
health_hits[iid] = dying_old_hp
|
||||
|
||||
# Consume tracked target before any early return so it never bleeds into
|
||||
# the next state update (e.g. a fully-blocked hit with 0 HP change).
|
||||
var tracked_source: String = last_attack_source_iid
|
||||
var tracked_target: String = last_attack_target_iid
|
||||
last_attack_source_iid = ""
|
||||
last_attack_target_iid = ""
|
||||
if attacker_iid.is_empty() and not tracked_source.is_empty() and mesh_builder.unit_bodies.has(tracked_source):
|
||||
attacker_iid = tracked_source
|
||||
attack_remaining = unit_action_duration(attacker_iid, "attack")
|
||||
var hitsplats_shown: Dictionary = {}
|
||||
|
||||
if damaged_iids.is_empty() and defense_hits.is_empty() and dying_iids.is_empty():
|
||||
# Fully-blocked attack: attacker is mid-swing but the defender's defense
|
||||
# absorbed all damage → no HP change, but play the blocked SFX.
|
||||
if attacker_iid != "" and not tracked_target.is_empty() \
|
||||
and tracked_target != attacker_iid:
|
||||
var blocked_iid: String = tracked_target
|
||||
if attack_remaining > 0.0:
|
||||
var tb: Tween = create_tween()
|
||||
tb.tween_callback(func() -> void:
|
||||
SFX.play(sfx_for_unit(blocked_iid, "blockedSoundUrl"))
|
||||
).set_delay(attack_remaining)
|
||||
else:
|
||||
SFX.play(sfx_for_unit(blocked_iid, "blockedSoundUrl"))
|
||||
return false
|
||||
|
||||
if damaged_iids.is_empty() and not defense_hits.is_empty():
|
||||
for iid: String in defense_hits:
|
||||
show_hitsplats_once(hitsplats_shown, iid, int(defense_hits.get(iid, 0)), 0, attack_remaining)
|
||||
if attacker_iid != "" and not tracked_target.is_empty() \
|
||||
and tracked_target != attacker_iid:
|
||||
var blocked_iid: String = tracked_target
|
||||
if attack_remaining > 0.0:
|
||||
var tb2: Tween = create_tween()
|
||||
tb2.tween_callback(func() -> void:
|
||||
SFX.play(sfx_for_unit(blocked_iid, "blockedSoundUrl"))
|
||||
).set_delay(attack_remaining)
|
||||
else:
|
||||
SFX.play(sfx_for_unit(blocked_iid, "blockedSoundUrl"))
|
||||
return false
|
||||
|
||||
# ── Detect counterattack: attacker took damage while mid-attack ─────────
|
||||
# The defender may have blocked all HP damage (defense stat), so we can't
|
||||
# rely on them being in damaged_iids. Use the tracked target from the last
|
||||
# send_attack() call as the primary source, and fall back to any other
|
||||
# damaged unit if the tracked target isn't available.
|
||||
var is_counterattack: bool = false
|
||||
var defender_iid: String = ""
|
||||
if attacker_iid != "" and damaged_iids.has(attacker_iid):
|
||||
# Prefer the unit we explicitly attacked (works even when they took 0 damage).
|
||||
if tracked_target != "" and tracked_target != attacker_iid:
|
||||
defender_iid = tracked_target
|
||||
else:
|
||||
# Fallback: any other damaged unit (original behaviour).
|
||||
for iid: String in damaged_iids:
|
||||
if iid != attacker_iid:
|
||||
defender_iid = iid
|
||||
break
|
||||
is_counterattack = defender_iid != ""
|
||||
|
||||
var display_delay: float = attack_remaining if attacker_iid != "" else 0.0
|
||||
for iid: String in seen_iids:
|
||||
show_hitsplats_once(
|
||||
hitsplats_shown,
|
||||
iid,
|
||||
int(defense_hits.get(iid, 0)),
|
||||
int(health_hits.get(iid, 0)),
|
||||
display_delay)
|
||||
for iid: String in dying_iids:
|
||||
show_hitsplats_once(
|
||||
hitsplats_shown,
|
||||
iid,
|
||||
int(defense_hits.get(iid, 0)),
|
||||
int(health_hits.get(iid, 0)),
|
||||
display_delay)
|
||||
|
||||
# ── Schedule animations ───────────────────────────────────────────────────
|
||||
if is_counterattack:
|
||||
# Full chain handles the attacker and primary defender.
|
||||
play_counter_chain(
|
||||
defender_iid,
|
||||
attacker_iid,
|
||||
attack_remaining,
|
||||
int(defense_hits.get(defender_iid, 0)),
|
||||
int(health_hits.get(defender_iid, 0)),
|
||||
int(defense_hits.get(attacker_iid, 0)),
|
||||
int(health_hits.get(attacker_iid, 0)),
|
||||
hitsplats_shown)
|
||||
# Any other simultaneously-damaged units get a simple delay (uncommon).
|
||||
for iid: String in seen_iids:
|
||||
if iid == attacker_iid or iid == defender_iid:
|
||||
continue
|
||||
var def_loss: int = int(defense_hits.get(iid, 0))
|
||||
var hp_loss: int = int(health_hits.get(iid, 0))
|
||||
if def_loss <= 0 and hp_loss <= 0:
|
||||
continue
|
||||
var hit_iid: String = iid
|
||||
var hit_def: int = def_loss
|
||||
var hit_hp: int = hp_loss
|
||||
var t2: Tween = create_tween()
|
||||
t2.tween_callback(func() -> void:
|
||||
if mesh_builder.unit_bodies.has(hit_iid) and \
|
||||
is_instance_valid(mesh_builder.unit_bodies.get(hit_iid) as Node):
|
||||
if hit_hp > 0:
|
||||
play_unit_anim(hit_iid, "damaged")
|
||||
SFX.play(sfx_for_unit(hit_iid, "damagedSoundUrl"))
|
||||
show_hitsplats_once(hitsplats_shown, hit_iid, hit_def, hit_hp)
|
||||
).set_delay(attack_remaining)
|
||||
else:
|
||||
for iid: String in seen_iids:
|
||||
var def_loss: int = int(defense_hits.get(iid, 0))
|
||||
var hp_loss: int = int(health_hits.get(iid, 0))
|
||||
if def_loss <= 0 and hp_loss <= 0:
|
||||
continue
|
||||
var ap: AnimationPlayer = mesh_builder.anim_players.get(iid, null) as AnimationPlayer
|
||||
if hp_loss > 0 and ap != null and is_instance_valid(ap) and ap.is_playing() \
|
||||
and is_attack_track(ap.current_animation):
|
||||
# This unit is mid-attack and took damage (self-damage or similar).
|
||||
# Queue "damaged" to play right after the attack finishes.
|
||||
if mesh_builder.oneshot_callbacks.has(iid):
|
||||
var old_cb: Callable = mesh_builder.oneshot_callbacks[iid] as Callable
|
||||
if ap.animation_finished.is_connected(old_cb):
|
||||
ap.animation_finished.disconnect(old_cb)
|
||||
mesh_builder.oneshot_callbacks.erase(iid)
|
||||
var cap_iid: String = iid
|
||||
var cap_def: int = def_loss
|
||||
var cap_hp: int = hp_loss
|
||||
var dmg_cb: Callable = func(_n: String) -> void:
|
||||
play_unit_anim(cap_iid, "damaged", false)
|
||||
SFX.play(sfx_for_unit(cap_iid, "damagedSoundUrl"))
|
||||
show_hitsplats_once(hitsplats_shown, cap_iid, cap_def, cap_hp)
|
||||
ap.animation_finished.connect(dmg_cb, CONNECT_ONE_SHOT)
|
||||
mesh_builder.oneshot_callbacks[iid] = dmg_cb
|
||||
elif attack_remaining > 0.0:
|
||||
# Bystander — delay "damaged" until after the attack lands.
|
||||
var hit_iid: String = iid
|
||||
var hit_def: int = def_loss
|
||||
var hit_hp: int = hp_loss
|
||||
var t: Tween = create_tween()
|
||||
t.tween_callback(func() -> void:
|
||||
if mesh_builder.unit_bodies.has(hit_iid) and \
|
||||
is_instance_valid(mesh_builder.unit_bodies.get(hit_iid) as Node):
|
||||
if hit_hp > 0:
|
||||
play_unit_anim(hit_iid, "damaged")
|
||||
SFX.play(sfx_for_unit(hit_iid, "damagedSoundUrl"))
|
||||
show_hitsplats_once(hitsplats_shown, hit_iid, hit_def, hit_hp)
|
||||
).set_delay(attack_remaining)
|
||||
else:
|
||||
if hp_loss > 0:
|
||||
play_unit_anim(iid, "damaged")
|
||||
SFX.play(sfx_for_unit(iid, "damagedSoundUrl"))
|
||||
show_hitsplats_once(hitsplats_shown, iid, def_loss, hp_loss)
|
||||
|
||||
for iid: String in dying_iids:
|
||||
show_hitsplats_once(hitsplats_shown, iid, int(defense_hits.get(iid, 0)), int(health_hits.get(iid, 0)))
|
||||
play_unit_anim(iid, "dying")
|
||||
SFX.play(sfx_for_unit(iid, "deathSoundUrl"))
|
||||
|
||||
return true
|
||||
|
||||
|
||||
## Update prev_unit_hp, prev_unit_def, and prev_unit_pos from the given state snapshot.
|
||||
## Call immediately when a new state arrives so the next state update has
|
||||
## correct baselines, independent of when the delayed rebuild fires.
|
||||
func update_prev_state(state: Dictionary) -> void:
|
||||
prev_unit_hp.clear()
|
||||
prev_unit_def.clear()
|
||||
prev_unit_pos.clear()
|
||||
for player: Dictionary in state.get("players", []):
|
||||
var arch: Dictionary = mesh_builder.unit_registry.safe_arch(player)
|
||||
for unit: Dictionary in ([arch] + player.get("field", [])):
|
||||
if unit.is_empty():
|
||||
continue
|
||||
var iid: String = str(unit.get("instanceId", ""))
|
||||
if iid.is_empty():
|
||||
continue
|
||||
prev_unit_hp[iid] = int(unit.get("currentHealth") or 0)
|
||||
prev_unit_def[iid] = int(unit.get("currentDefense") or 0)
|
||||
var pd: Variant = unit.get("position")
|
||||
if pd is Dictionary and not (pd as Dictionary).is_empty():
|
||||
prev_unit_pos[iid] = Vector2i((pd as Dictionary).get("x", 0),
|
||||
(pd as Dictionary).get("y", 0))
|
||||
|
||||
# ── Movement animation ────────────────────────────────────────────────────────
|
||||
|
||||
## Animate a single unit moving along a BFS path from from_coord to to_coord.
|
||||
## tile_heights and tile_y_bases are passed explicitly so this method stays pure
|
||||
## (the mesh builder owns those dicts and provides them via the parent wiring).
|
||||
## pathfinder is used for coord_to_world conversion.
|
||||
## Returns the total tween duration in seconds.
|
||||
func animate_unit_move(iid: String, from_coord: Vector2i, to_coord: Vector2i,
|
||||
blocked: Dictionary, tile_heights: Dictionary, tile_y_bases: Dictionary,
|
||||
pathfinder: Pathfinder, tile_bodies: Dictionary) -> float:
|
||||
var body: StaticBody3D = mesh_builder.unit_bodies.get(iid) as StaticBody3D
|
||||
if not is_instance_valid(body):
|
||||
return 0.0
|
||||
var path: Array[Vector2i] = pathfinder.bfs_path(from_coord, to_coord, blocked, tile_bodies)
|
||||
if path.is_empty():
|
||||
return 0.0
|
||||
var duration: float = path.size() * GameConstants.MOVE_STEP_SECS
|
||||
# Cancel any existing move tween for this unit.
|
||||
if mesh_builder.move_anims.has(iid) and mesh_builder.move_anims[iid] != null:
|
||||
(mesh_builder.move_anims[iid] as Tween).kill()
|
||||
# Play the looping move animation and its SFX.
|
||||
play_unit_anim(iid, "moving", true)
|
||||
SFX.play(sfx_for_unit(iid, "moveSoundUrl"))
|
||||
# Pre-compute per-step facing angles so the closures capture the correct values.
|
||||
var base_angle: float = float(mesh_builder.model_base_angles.get(iid, 0.0))
|
||||
var prev_coord: Vector2i = from_coord
|
||||
var step_angles: Array[float] = []
|
||||
for step: Vector2i in path:
|
||||
var step_wp: Vector3 = pathfinder.coord_to_world(step.x, step.y)
|
||||
var prev_wp: Vector3 = pathfinder.coord_to_world(prev_coord.x, prev_coord.y)
|
||||
var dir: Vector3 = step_wp - prev_wp # XZ direction in world space
|
||||
step_angles.append(base_angle - atan2(dir.x, -dir.z))
|
||||
prev_coord = step
|
||||
# Tween the body through each grid step, rotating the model to face each direction.
|
||||
# Use the stored "above_tile" constant so rapid state updates cannot skew the
|
||||
# height by back-calculating from a mid-tween body position.
|
||||
var unit_above: float = body.get_meta("above_tile", 0.28)
|
||||
# Pre-compute per-step Y positions.
|
||||
var step_ys: Array[float] = []
|
||||
for step: Vector2i in path:
|
||||
var key: String = "%d,%d" % [step.x, step.y]
|
||||
step_ys.append(tile_y_bases.get(key, 0.0) + tile_heights.get(key, 1.0) + unit_above)
|
||||
var tween: Tween = create_tween()
|
||||
tween.set_ease(Tween.EASE_IN_OUT)
|
||||
tween.set_trans(Tween.TRANS_SINE)
|
||||
for i: int in path.size():
|
||||
var step: Vector2i = path[i]
|
||||
var wp: Vector3 = pathfinder.coord_to_world(step.x, step.y)
|
||||
var facing_angle: float = step_angles[i]
|
||||
var step_y: float = step_ys[i]
|
||||
# Snap model rotation to face the movement direction before each step.
|
||||
tween.tween_callback(func() -> void:
|
||||
var m: Node3D = mesh_builder.unit_meshes.get(iid) as Node3D
|
||||
if is_instance_valid(m):
|
||||
m.rotation.y = facing_angle)
|
||||
tween.tween_property(body, "position", Vector3(wp.x, step_y, wp.z), GameConstants.MOVE_STEP_SECS)
|
||||
# Return to idle rotation and idle animation once movement finishes.
|
||||
tween.tween_callback(func() -> void:
|
||||
mesh_builder.move_anims.erase(iid)
|
||||
var m: Node3D = mesh_builder.unit_meshes.get(iid) as Node3D
|
||||
if is_instance_valid(m):
|
||||
m.rotation.y = mesh_builder.idle_rotation(iid)
|
||||
play_unit_anim(iid, "idle", true))
|
||||
mesh_builder.move_anims[iid] = tween
|
||||
return duration
|
||||
|
||||
|
||||
## Detect position changes vs prev_unit_pos and start move animations.
|
||||
## Returns the maximum movement duration across all movers (seconds).
|
||||
func play_move_animations(state: Dictionary, tile_heights: Dictionary,
|
||||
tile_y_bases: Dictionary, pathfinder: Pathfinder, tile_bodies: Dictionary) -> float:
|
||||
if prev_unit_pos.is_empty():
|
||||
return 0.0
|
||||
# Build the set of blocked tiles from old unit positions.
|
||||
var blocked: Dictionary = {}
|
||||
for prev_iid: String in prev_unit_pos:
|
||||
blocked[prev_unit_pos[prev_iid]] = true
|
||||
var max_dur: float = 0.0
|
||||
for player: Dictionary in state.get("players", []):
|
||||
var arch: Dictionary = mesh_builder.unit_registry.safe_arch(player)
|
||||
for unit: Dictionary in ([arch] + player.get("field", [])):
|
||||
if unit.is_empty():
|
||||
continue
|
||||
var iid: String = str(unit.get("instanceId", ""))
|
||||
var pd: Variant = unit.get("position")
|
||||
if not (pd is Dictionary) or (pd as Dictionary).is_empty():
|
||||
continue
|
||||
var new_coord: Vector2i = Vector2i((pd as Dictionary).get("x", 0),
|
||||
(pd as Dictionary).get("y", 0))
|
||||
if not prev_unit_pos.has(iid):
|
||||
continue
|
||||
var old_coord: Vector2i = prev_unit_pos[iid]
|
||||
if old_coord == new_coord:
|
||||
continue
|
||||
# Mover has left its old tile — unblock it for BFS.
|
||||
blocked.erase(old_coord)
|
||||
var dur: float = animate_unit_move(iid, old_coord, new_coord, blocked,
|
||||
tile_heights, tile_y_bases, pathfinder, tile_bodies)
|
||||
max_dur = maxf(max_dur, dur)
|
||||
return max_dur
|
||||
|
||||
|
||||
## Schedule a delayed call to rebuild_units via the provided callback.
|
||||
## If delay <= 0 and a rebuild is already pending, just store the state
|
||||
## but DO NOT cancel the running tween — this prevents rapid echo state-updates
|
||||
## (phase changes, turn ticks) from killing an in-progress movement animation.
|
||||
## The callback signature: func(state: Dictionary) -> void
|
||||
## The schedule_callback signature: func(state: Dictionary, delay: float) -> void
|
||||
## game_screen wires this to its own _schedule_rebuild implementation.
|
||||
signal rebuild_scheduled(state: Dictionary, delay: float)
|
||||
|
||||
func schedule_rebuild(state: Dictionary, delay: float) -> void:
|
||||
rebuild_scheduled.emit(state, delay)
|
||||
@@ -0,0 +1 @@
|
||||
uid://bc0e70q4no7nd
|
||||
@@ -0,0 +1,514 @@
|
||||
class_name UnitMeshBuilder
|
||||
extends Node
|
||||
|
||||
## Owns all per-unit scene objects and handles incremental unit mesh placement.
|
||||
##
|
||||
## Call rebuild_units(state) on each state update.
|
||||
## Requires units_root, tile_heights, tile_y_bases, unit_registry, pathfinder,
|
||||
## and local_is_p1 to be set by the parent before any call.
|
||||
|
||||
# ── External dependencies (set by parent) ─────────────────────────────────────
|
||||
|
||||
var units_root: Node3D = null
|
||||
var tile_heights: Dictionary = {} # "x,y" → float
|
||||
var tile_y_bases: Dictionary = {} # "x,y" → float
|
||||
var unit_registry: UnitRegistry = null
|
||||
var pathfinder: Pathfinder = null
|
||||
var local_is_p1: bool = false
|
||||
|
||||
# ── Owned scene dictionaries ──────────────────────────────────────────────────
|
||||
|
||||
var unit_bodies: Dictionary = {} # instanceId → StaticBody3D
|
||||
var unit_meshes: Dictionary = {} # instanceId → Node3D (placeholder or real model)
|
||||
var anim_players: Dictionary = {} # instanceId → AnimationPlayer (null if none)
|
||||
var move_anims: Dictionary = {} # instanceId → Tween (active movement tweens)
|
||||
var idle_entry_done: Dictionary = {} # iid → true once first idle entry has played
|
||||
var idle_callbacks: Dictionary = {} # iid → Callable (active loop reconnect)
|
||||
var oneshot_callbacks: Dictionary = {} # iid → Callable (animation_finished → next action)
|
||||
var model_base_angles: Dictionary = {} # iid → float (base facing angle, radians)
|
||||
var needs_face_rot: Dictionary = {} # iid → bool (team-based 180° flip flag)
|
||||
var unit_model_retries: Dictionary = {} # iid → int (attempt number, 1-based, capped at 10)
|
||||
|
||||
# ── Incremental rebuild ───────────────────────────────────────────────────────
|
||||
|
||||
## Incremental diff: add/remove units without recreating unchanged ones.
|
||||
## Recreating a unit body interrupts its running animation (idle/move/attack),
|
||||
## causing a one-frame bind-pose flash on every state echo.
|
||||
func rebuild_units(state: Dictionary) -> void:
|
||||
# Kill any in-flight movement tweens.
|
||||
for iid: String in move_anims:
|
||||
var t: Tween = move_anims[iid] as Tween
|
||||
if t != null:
|
||||
t.kill()
|
||||
move_anims.clear()
|
||||
|
||||
# 1. Collect the desired unit set from the new state.
|
||||
var my_id: String = Auth.user_id
|
||||
var team_colors: Dictionary = state.get("teamColors", {})
|
||||
var desired: Dictionary = {} # iid → {unit, color, is_enemy}
|
||||
# Find my team index for ally detection.
|
||||
var my_team_idx: int = -1
|
||||
for player: Dictionary in state.get("players", []):
|
||||
if str(player.get("accountId", "")).to_lower() == my_id.to_lower():
|
||||
my_team_idx = int(player.get("teamIndex", -1))
|
||||
break
|
||||
for player: Dictionary in state.get("players", []):
|
||||
var pid: String = str(player.get("accountId", "")).to_lower()
|
||||
var is_mine: bool = pid == my_id.to_lower()
|
||||
var team_idx: int = int(player.get("teamIndex", -1))
|
||||
var is_ally: bool = (not is_mine) and (my_team_idx >= 0) and (team_idx == my_team_idx)
|
||||
var is_enemy: bool = not (is_mine or is_ally)
|
||||
# Use the team's palette color; fall back to blue (friendly) or red (enemy).
|
||||
var hex_str: String = str(team_colors.get(str(team_idx), ""))
|
||||
var color: Color
|
||||
if not hex_str.is_empty():
|
||||
color = Color.html("#" + hex_str)
|
||||
elif is_enemy:
|
||||
color = Color(1.0, 0.35, 0.35)
|
||||
else:
|
||||
color = Color(0.3, 0.5, 1.0)
|
||||
var arch: Dictionary = unit_registry.safe_arch(player)
|
||||
for unit: Dictionary in ([arch] + player.get("field", [])):
|
||||
if unit.is_empty() or unit.get("position") == null:
|
||||
continue
|
||||
var iid: String = str(unit.get("instanceId", ""))
|
||||
if iid.is_empty():
|
||||
continue
|
||||
desired[iid] = {"unit": unit, "color": color, "is_enemy": is_enemy}
|
||||
|
||||
# 2. Remove units that are no longer on the board.
|
||||
var to_remove: Array[String] = []
|
||||
for iid: String in unit_bodies:
|
||||
if not desired.has(iid):
|
||||
to_remove.append(iid)
|
||||
for iid: String in to_remove:
|
||||
var body: StaticBody3D = unit_bodies[iid] as StaticBody3D
|
||||
if is_instance_valid(body):
|
||||
body.queue_free()
|
||||
unit_bodies.erase(iid)
|
||||
unit_meshes.erase(iid)
|
||||
anim_players.erase(iid)
|
||||
unit_registry.unit_def_ids.erase(iid)
|
||||
idle_entry_done.erase(iid)
|
||||
idle_callbacks.erase(iid)
|
||||
oneshot_callbacks.erase(iid)
|
||||
model_base_angles.erase(iid)
|
||||
needs_face_rot.erase(iid)
|
||||
unit_registry.unit_team_idx.erase(iid)
|
||||
unit_model_retries.erase(iid)
|
||||
|
||||
# 3. Add units not yet present (newly played, or first render after connect).
|
||||
for iid: String in desired:
|
||||
if not unit_bodies.has(iid):
|
||||
var d: Dictionary = desired[iid] as Dictionary
|
||||
add_unit_mesh(d["unit"] as Dictionary, d["color"] as Color, d["is_enemy"] as bool)
|
||||
|
||||
# 4. Refresh idle rotation for all units — nearest enemy may have changed.
|
||||
for iid: String in unit_meshes:
|
||||
if move_anims.has(iid):
|
||||
continue # don't interrupt an in-progress move
|
||||
var m: Node3D = unit_meshes.get(iid) as Node3D
|
||||
if is_instance_valid(m):
|
||||
m.rotation.y = idle_rotation(iid)
|
||||
|
||||
|
||||
func add_unit_mesh(unit: Dictionary, team_color: Color, is_enemy: bool = false) -> void:
|
||||
var pd: Dictionary = unit.get("position", {})
|
||||
if pd.is_empty():
|
||||
return
|
||||
var px: int = pd.get("x", 0)
|
||||
var py: int = pd.get("y", 0)
|
||||
var wp: Vector3 = pathfinder.coord_to_world(px, py)
|
||||
var tile_h: float = tile_heights.get("%d,%d" % [px, py], 1.0)
|
||||
var tile_base: float = tile_y_bases.get("%d,%d" % [px, py], 0.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 = StaticBody3D.new()
|
||||
body.set_meta("unit_id", iid)
|
||||
|
||||
var shape: CollisionShape3D = CollisionShape3D.new()
|
||||
var mi: MeshInstance3D = MeshInstance3D.new()
|
||||
var mat: StandardMaterial3D = StandardMaterial3D.new()
|
||||
mat.roughness = 0.65
|
||||
|
||||
var above_tile: float # how far above the tile top the body centre sits
|
||||
match card_type:
|
||||
"ArchSpirit":
|
||||
var cyl: CylinderMesh = CylinderMesh.new()
|
||||
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
|
||||
mat.emission = team_color * 0.4
|
||||
var cs: CylinderShape3D = CylinderShape3D.new()
|
||||
cs.radius = 0.22; cs.height = 0.8
|
||||
shape.shape = cs
|
||||
above_tile = 0.4
|
||||
"Ruin":
|
||||
var bm: BoxMesh = BoxMesh.new()
|
||||
bm.size = Vector3(0.25, 1.0, 0.25)
|
||||
mi.mesh = bm
|
||||
mat.albedo_color = Color(0.35, 0.32, 0.30)
|
||||
var bs: BoxShape3D = BoxShape3D.new()
|
||||
bs.size = Vector3(0.25, 1.0, 0.25)
|
||||
shape.shape = bs
|
||||
above_tile = 0.5
|
||||
_:
|
||||
var sm: SphereMesh = SphereMesh.new()
|
||||
sm.radius = 0.28; sm.height = 0.28
|
||||
mi.mesh = sm
|
||||
mat.albedo_color = team_color
|
||||
var ss: SphereShape3D = SphereShape3D.new()
|
||||
ss.radius = 0.28
|
||||
shape.shape = ss
|
||||
above_tile = 0.28
|
||||
|
||||
mi.material_override = mat
|
||||
if exhausted:
|
||||
mat.albedo_color = mat.albedo_color.darkened(0.45)
|
||||
|
||||
body.add_child(shape)
|
||||
body.add_child(mi)
|
||||
body.set_meta("above_tile", above_tile)
|
||||
body.position = wp + Vector3(0, tile_base + tile_h + above_tile, 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 not def_id.is_empty():
|
||||
unit_registry.unit_def_ids[iid] = def_id
|
||||
if def_id.is_empty():
|
||||
return
|
||||
var def: Dictionary = ContentCache.get_definition(def_id)
|
||||
_prime_unit_sfx(def)
|
||||
var model_asset: Dictionary = find_model3d_asset(def)
|
||||
var model_url: String = str(model_asset.get("cdnUrl", ""))
|
||||
var model_etag: String = str(model_asset.get("contentETag", ""))
|
||||
if model_url.is_empty():
|
||||
return
|
||||
|
||||
# Asset-level config (model-file specific).
|
||||
var facing_dir: String = str(model_asset.get("modelFacingDirection", "south"))
|
||||
# Card-level config (visual identity of this card, not the shared mesh file).
|
||||
var model_scale: float = float(def.get("modelScale", 1.0))
|
||||
var tint_str: String = str(def.get("modelTintColor", ""))
|
||||
var model_tint: Color = Color.WHITE
|
||||
if not tint_str.is_empty() and tint_str != "null":
|
||||
model_tint = Color(tint_str)
|
||||
|
||||
# Team-based facing: P1 units face +Z (toward P2), P2 units face -Z (toward P1).
|
||||
# Rotate if: (local is P1 AND friendly) OR (local is P2 AND enemy).
|
||||
var needs_face_rotation: bool = local_is_p1 != is_enemy
|
||||
var base_angle: float = facing_to_base_angle(facing_dir)
|
||||
|
||||
# Pre-set facing config so schedule_model_retry can use it even if load fails.
|
||||
model_base_angles[iid] = base_angle
|
||||
needs_face_rot[iid] = needs_face_rotation
|
||||
|
||||
var body_ref: Variant = weakref(body)
|
||||
ModelCache.load_model(model_url, func(model_node: Node3D) -> void:
|
||||
# Guard: body may have been freed by a state rebuild before load finished.
|
||||
var b: StaticBody3D = body_ref.get_ref() as StaticBody3D
|
||||
if not is_instance_valid(b):
|
||||
if model_node != null:
|
||||
model_node.queue_free()
|
||||
return
|
||||
if model_node == null:
|
||||
# Download failed — schedule a background retry.
|
||||
schedule_model_retry(iid, model_url, 1, model_etag)
|
||||
return
|
||||
|
||||
# Remove the placeholder MeshInstance3D.
|
||||
for child in b.get_children():
|
||||
if child is MeshInstance3D:
|
||||
child.queue_free()
|
||||
|
||||
# Apply uniform scale if configured.
|
||||
if not is_equal_approx(model_scale, 1.0):
|
||||
model_node.scale = Vector3.ONE * model_scale
|
||||
|
||||
# Facing config was already stored above; no need to repeat.
|
||||
|
||||
# Apply idle/team rotation (facing toward opponent).
|
||||
model_node.rotation.y = idle_rotation(iid)
|
||||
|
||||
# Apply multiplicative tint to all StandardMaterial3D surfaces.
|
||||
apply_model_tint(model_node, model_tint)
|
||||
|
||||
# Restore the body to its correct world height. Skip if a move tween
|
||||
# is currently driving the body.
|
||||
if not move_anims.has(iid):
|
||||
b.position = wp + Vector3(0, tile_base + tile_h + above_tile, 0)
|
||||
b.add_child(model_node)
|
||||
# Seat the model's AABB bottom (feet) on the tile surface.
|
||||
# body-local Y=0 is the tile top; feet target = -above_tile.
|
||||
var m_aabb: AABB = model_local_aabb(model_node)
|
||||
if m_aabb.size != Vector3.ZERO:
|
||||
model_node.position.y = -above_tile - model_node.scale.y * m_aabb.position.y
|
||||
unit_meshes[iid] = model_node
|
||||
|
||||
# Find and store the AnimationPlayer, then start the Idle loop.
|
||||
var ap: AnimationPlayer = find_animation_player(model_node)
|
||||
anim_players[iid] = ap
|
||||
if ap != null:
|
||||
_request_play_anim(iid, "idle", true)
|
||||
, model_etag)
|
||||
|
||||
|
||||
## Schedule a retry to (re)download the real GLB model for a unit.
|
||||
## attempt is 1-based; retries stop after MAX_RETRIES.
|
||||
## Only schedules if no equal-or-later retry is already pending for this unit.
|
||||
func schedule_model_retry(iid: String, model_url: String, attempt: int, etag: String = "") -> void:
|
||||
const MAX_RETRIES: int = 10
|
||||
if attempt > MAX_RETRIES:
|
||||
return
|
||||
# Don't override a retry already queued at this or a higher attempt number.
|
||||
if unit_model_retries.get(iid, 0) >= attempt:
|
||||
return
|
||||
unit_model_retries[iid] = attempt
|
||||
print("[UnitMeshBuilder] Model retry %d/%d scheduled for %s in 60s" % [attempt, MAX_RETRIES, iid])
|
||||
get_tree().create_timer(60.0).timeout.connect(
|
||||
func() -> void: do_model_retry(iid, model_url, attempt, etag),
|
||||
CONNECT_ONE_SHOT)
|
||||
|
||||
|
||||
## Execute one model retry attempt. Evicts the URL so ModelCache re-downloads it.
|
||||
## If successful, swaps out the placeholder and starts idle animation.
|
||||
## If it fails again, schedules the next attempt.
|
||||
func do_model_retry(iid: String, model_url: String, attempt: int, etag: String = "") -> void:
|
||||
# Was this attempt superseded by a later scheduled retry?
|
||||
if unit_model_retries.get(iid, -1) != attempt:
|
||||
return
|
||||
# Unit may have left the board while we were waiting.
|
||||
if not unit_bodies.has(iid):
|
||||
unit_model_retries.erase(iid)
|
||||
return
|
||||
print("[UnitMeshBuilder] Model retry %d — downloading %s" % [attempt, model_url])
|
||||
ModelCache.evict(model_url, etag)
|
||||
ModelCache.load_model(model_url, func(model_node: Node3D) -> void:
|
||||
if model_node == null:
|
||||
# Still failing — try again later.
|
||||
unit_model_retries.erase(iid)
|
||||
schedule_model_retry(iid, model_url, attempt + 1, etag)
|
||||
return
|
||||
unit_model_retries.erase(iid)
|
||||
# Use the CURRENT body (may differ from when the retry was first scheduled).
|
||||
var body: StaticBody3D = unit_bodies.get(iid) as StaticBody3D
|
||||
if not is_instance_valid(body):
|
||||
model_node.queue_free()
|
||||
return
|
||||
# Remove placeholder mesh.
|
||||
for child in body.get_children():
|
||||
if child is MeshInstance3D:
|
||||
child.queue_free()
|
||||
# Re-read card config in case ContentCache was refreshed since placement.
|
||||
var def_id: String = unit_registry.unit_def_ids.get(iid, "")
|
||||
var def: Dictionary = ContentCache.get_definition(def_id)
|
||||
var model_scale: float = float(def.get("modelScale", 1.0))
|
||||
var tint_str: String = str(def.get("modelTintColor", ""))
|
||||
var model_tint: Color = Color.WHITE
|
||||
if not tint_str.is_empty() and tint_str != "null":
|
||||
model_tint = Color(tint_str)
|
||||
if not is_equal_approx(model_scale, 1.0):
|
||||
model_node.scale = Vector3.ONE * model_scale
|
||||
model_node.rotation.y = idle_rotation(iid)
|
||||
apply_model_tint(model_node, model_tint)
|
||||
var above_tile: float = body.get_meta("above_tile", 0.28)
|
||||
body.add_child(model_node)
|
||||
var m_aabb: AABB = model_local_aabb(model_node)
|
||||
if m_aabb.size != Vector3.ZERO:
|
||||
model_node.position.y = -above_tile - model_node.scale.y * m_aabb.position.y
|
||||
unit_meshes[iid] = model_node
|
||||
var ap: AnimationPlayer = find_animation_player(model_node)
|
||||
anim_players[iid] = ap
|
||||
if ap != null:
|
||||
_request_play_anim(iid, "idle", true)
|
||||
print("[UnitMeshBuilder] Model retry %d succeeded for %s" % [attempt, iid])
|
||||
, etag)
|
||||
|
||||
# ── Model helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
## Returns the first Model3D asset dict for a card definition, or {} if none.
|
||||
func find_model3d_asset(def: Dictionary) -> Dictionary:
|
||||
for asset: Variant in def.get("assets", []):
|
||||
var d: Dictionary = asset as Dictionary
|
||||
if d == null:
|
||||
continue
|
||||
if str(d.get("assetType", "")) == "Model3D":
|
||||
return d
|
||||
return {}
|
||||
|
||||
|
||||
## Apply a multiplicative colour tint to all StandardMaterial3D surfaces in a
|
||||
## model subtree. Materials are duplicated per-instance to avoid cross-unit bleed.
|
||||
## White (default) is a no-op.
|
||||
func apply_model_tint(model: Node3D, tint: Color) -> void:
|
||||
if tint.is_equal_approx(Color.WHITE):
|
||||
return
|
||||
var stack: Array = [model]
|
||||
while not stack.is_empty():
|
||||
var n: Variant = stack.pop_back()
|
||||
if n is MeshInstance3D:
|
||||
var mi: MeshInstance3D = n as MeshInstance3D
|
||||
if mi.mesh != null:
|
||||
for i: int in mi.mesh.get_surface_count():
|
||||
var mat: Material = mi.get_active_material(i)
|
||||
if mat is StandardMaterial3D:
|
||||
var dup: StandardMaterial3D = mat.duplicate() as StandardMaterial3D
|
||||
dup.albedo_color = dup.albedo_color * tint
|
||||
mi.set_surface_override_material(i, dup)
|
||||
for child: Variant in n.get_children():
|
||||
stack.append(child)
|
||||
|
||||
|
||||
## Recursively find the first AnimationPlayer in a model subtree.
|
||||
func find_animation_player(node: Node) -> AnimationPlayer:
|
||||
if node is AnimationPlayer:
|
||||
return node as AnimationPlayer
|
||||
for child: Node in node.get_children():
|
||||
var found: AnimationPlayer = find_animation_player(child)
|
||||
if found != null:
|
||||
return found
|
||||
return null
|
||||
|
||||
|
||||
## Case-insensitive track name resolver with fallback aliases.
|
||||
## Returns the exact track name in the AnimationPlayer, or "" if not found.
|
||||
## Handles multiple naming conventions exported from DCC tools:
|
||||
## "Idle" — bare name
|
||||
## "lib/Idle" — library-prefixed (GLTF named library)
|
||||
## "Merlock.Attack" — dot-prefixed model name (e.g. Blender action sets)
|
||||
## "Merlock_IDLE" — underscore-prefixed model name
|
||||
func resolve_anim_track(ap: AnimationPlayer, action_lower: String) -> String:
|
||||
# Try: canonical action name first, then aliases.
|
||||
var to_try: Array[String] = [action_lower]
|
||||
for alias: String in GameConstants.ANIM_ALIASES.get(action_lower, []):
|
||||
if alias != action_lower:
|
||||
to_try.append(alias)
|
||||
|
||||
for candidate: String in to_try:
|
||||
for full_name: String in ap.get_animation_list():
|
||||
# Strip library prefix (e.g. "lib/Idle" → "Idle").
|
||||
var s: String = full_name.get_slice("/", full_name.get_slice_count("/") - 1)
|
||||
# 1. Direct match after library strip.
|
||||
if s.to_lower() == candidate:
|
||||
return full_name
|
||||
# 2. Dot-prefix stripped (e.g. "Merlock.Attack" → "Attack" → "attack").
|
||||
if "." in s:
|
||||
if s.get_slice(".", s.get_slice_count(".") - 1).to_lower() == candidate:
|
||||
return full_name
|
||||
# 3. First-underscore-prefix stripped (e.g. "Merlock_IDLE" → "IDLE" → "idle").
|
||||
if "_" in s:
|
||||
if s.substr(s.find("_") + 1).to_lower() == candidate:
|
||||
return full_name
|
||||
return ""
|
||||
|
||||
|
||||
## Convert a model's exported facing direction string to a base angle in radians.
|
||||
## The angle represents atan2(dir.x, -dir.z) for the direction the model faces
|
||||
## when rotation.y == 0. All animations and movement share this offset.
|
||||
## GLB models exported from Blender arrive in Godot facing +Z (south) by default,
|
||||
## so "south" / unset / null all map to PI. Explicitly pass "north" for -Z models.
|
||||
func facing_to_base_angle(facing: String) -> float:
|
||||
match facing.to_lower():
|
||||
"north": return 0.0 # model faces -Z (Godot's natural forward)
|
||||
"east": return PI / 2.0
|
||||
"west": return -PI / 2.0
|
||||
_: return PI # "south" / default / null — model faces +Z (Blender GLB)
|
||||
|
||||
|
||||
## Returns the rotation.y (radians) that makes a unit's model face the nearest
|
||||
## enemy unit on the board. Falls back to the fixed north/south heuristic when
|
||||
## no enemy body is found (e.g. during initial placement before enemies exist).
|
||||
func idle_rotation(iid: String) -> float:
|
||||
var base: float = float(model_base_angles.get(iid, 0.0))
|
||||
var my_body: StaticBody3D = unit_bodies.get(iid) as StaticBody3D
|
||||
if is_instance_valid(my_body):
|
||||
var my_pos: Vector3 = my_body.global_position
|
||||
var best_sq: float = INF
|
||||
var best_dir: Vector3 = Vector3.ZERO
|
||||
# Build opponent list using team index when available (spectate-safe).
|
||||
# When spectating, all units land in enemy_unit_ids so friend/enemy split
|
||||
# is meaningless — instead find any unit whose team differs from ours.
|
||||
var my_team: int = int(unit_registry.unit_team_idx.get(iid, -1))
|
||||
var enemy_ids: Array
|
||||
if my_team >= 0:
|
||||
enemy_ids = []
|
||||
for eid: String in unit_bodies:
|
||||
if int(unit_registry.unit_team_idx.get(eid, -1)) != my_team:
|
||||
enemy_ids.append(eid)
|
||||
else:
|
||||
var is_enemy_unit: bool = unit_registry.is_enemy_unit(iid)
|
||||
enemy_ids = unit_registry.enemy_unit_ids.keys() if not is_enemy_unit \
|
||||
else unit_registry.friendly_unit_ids.keys()
|
||||
var found_bodies: int = 0
|
||||
for eid: Variant in enemy_ids:
|
||||
var eb: StaticBody3D = unit_bodies.get(eid) as StaticBody3D
|
||||
if not is_instance_valid(eb):
|
||||
continue
|
||||
found_bodies += 1
|
||||
var d: Vector3 = eb.global_position - my_pos
|
||||
var sq: float = d.x * d.x + d.z * d.z
|
||||
if sq < best_sq:
|
||||
best_sq = sq
|
||||
best_dir = d
|
||||
if best_sq < INF and (best_dir.x != 0.0 or best_dir.z != 0.0):
|
||||
var flat: Vector3 = Vector3(best_dir.x, 0.0, best_dir.z).normalized()
|
||||
return base - atan2(flat.x, -flat.z)
|
||||
# Log why closest-enemy failed.
|
||||
push_warning("[IdleRot] FALLBACK iid=%s team=%d enemy_ids=%d bodies_found=%d best_sq=%s dir_xz=(%s,%s)" \
|
||||
% [iid.substr(0,8), my_team, enemy_ids.size(), found_bodies,
|
||||
str(best_sq), str(best_dir.x), str(best_dir.z)])
|
||||
else:
|
||||
push_warning("[IdleRot] FALLBACK iid=%s — body not in unit_bodies (friendly=%d enemy=%d)" \
|
||||
% [iid.substr(0,8), unit_registry.friendly_unit_ids.size(), unit_registry.enemy_unit_ids.size()])
|
||||
# Fallback: fixed north/south heuristic.
|
||||
var flip: bool = bool(needs_face_rot.get(iid, false))
|
||||
var dir: Vector3 = Vector3(0, 0, 1) if flip else Vector3(0, 0, -1)
|
||||
return atan2(dir.x, -dir.z) - base
|
||||
|
||||
|
||||
## Returns the AABB of a model in its own local space, accounting for child transforms.
|
||||
func model_local_aabb(root: Node3D) -> AABB:
|
||||
var result: AABB = AABB()
|
||||
var first: bool = true
|
||||
var stack: Array = [root]
|
||||
while not stack.is_empty():
|
||||
var n: Variant = stack.pop_back()
|
||||
if n is MeshInstance3D:
|
||||
var mi: MeshInstance3D = n as MeshInstance3D
|
||||
if mi.mesh != null:
|
||||
var local_aabb: AABB = mi.get_transform() * mi.mesh.get_aabb()
|
||||
if first:
|
||||
result = local_aabb
|
||||
first = false
|
||||
else:
|
||||
result = result.merge(local_aabb)
|
||||
for child: Variant in n.get_children():
|
||||
stack.append(child)
|
||||
return result
|
||||
|
||||
# ── Internal helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
## Prime SFX URLs for a unit definition so they are ready when needed.
|
||||
func _prime_unit_sfx(def: Dictionary) -> void:
|
||||
if def.is_empty():
|
||||
return
|
||||
for sfx_key: String in GameConstants.UNIT_SFX_KEYS:
|
||||
var url: String = str(def.get(sfx_key, "")).strip_edges()
|
||||
if not url.is_empty():
|
||||
SFX.prime(url)
|
||||
|
||||
|
||||
## Internal: requests the animator (via signal or direct call) to play an animation.
|
||||
## This indirection is needed because the mesh builder loads models asynchronously
|
||||
## and needs to trigger idle immediately after a model loads, but does not own the
|
||||
## animator. The parent (game_screen) wires this after construction.
|
||||
signal play_anim_requested(iid: String, action: String, loop: bool)
|
||||
|
||||
func _request_play_anim(iid: String, action: String, loop: bool) -> void:
|
||||
play_anim_requested.emit(iid, action, loop)
|
||||
@@ -0,0 +1 @@
|
||||
uid://jr1obk6cn100
|
||||
@@ -0,0 +1,121 @@
|
||||
class_name UnitRegistry
|
||||
extends Node
|
||||
|
||||
## Owns unit ownership tracking and provides O(1) ownership queries.
|
||||
##
|
||||
## Call rebuild_ownership(state) on every state update to refresh the lookups.
|
||||
|
||||
# ── Ownership tables ──────────────────────────────────────────────────────────
|
||||
|
||||
var enemy_unit_ids: Dictionary = {} # instanceId → true
|
||||
var friendly_unit_ids: Dictionary = {} # instanceId → true
|
||||
var unit_team_idx: Dictionary = {} # instanceId → int (team index)
|
||||
|
||||
# ── Definition ID map (instanceId → card definition ID string) ────────────────
|
||||
# Populated by the mesh-builder layer; exposed here for cross-component access.
|
||||
var unit_def_ids: Dictionary = {}
|
||||
|
||||
# ── Ownership rebuild ─────────────────────────────────────────────────────────
|
||||
|
||||
## Rebuild enemy/friendly/team-index lookup tables from a full game state snapshot.
|
||||
func rebuild_ownership(state: Dictionary) -> void:
|
||||
enemy_unit_ids.clear()
|
||||
friendly_unit_ids.clear()
|
||||
unit_team_idx.clear()
|
||||
var my_id: String = Auth.user_id
|
||||
# Find my team index so allies are treated as friendly too.
|
||||
var my_team_idx: int = -1
|
||||
for p: Dictionary in state.get("players", []):
|
||||
if str(p.get("accountId", "")).to_lower() == my_id.to_lower():
|
||||
my_team_idx = int(p.get("teamIndex", -1))
|
||||
break
|
||||
for p: Dictionary in state.get("players", []):
|
||||
var pid: String = str(p.get("accountId", "")).to_lower()
|
||||
var is_mine: bool = pid == my_id.to_lower()
|
||||
var team_idx: int = int(p.get("teamIndex", -1))
|
||||
# In team games (teamIndex matches), treat allies as friendly.
|
||||
var is_ally: bool = (not is_mine) and (my_team_idx >= 0) and (team_idx == my_team_idx)
|
||||
var target: Dictionary = friendly_unit_ids if (is_mine or is_ally) else enemy_unit_ids
|
||||
for u: Dictionary in p.get("field", []):
|
||||
if is_ruin_unit(u):
|
||||
continue
|
||||
var iid: String = u.get("instanceId", "")
|
||||
if not iid.is_empty():
|
||||
target[iid] = true
|
||||
unit_team_idx[iid] = team_idx
|
||||
var arch: Dictionary = safe_arch(p)
|
||||
var aid: String = arch.get("instanceId", "")
|
||||
if not aid.is_empty():
|
||||
target[aid] = true
|
||||
unit_team_idx[aid] = team_idx
|
||||
|
||||
# ── Ownership queries ─────────────────────────────────────────────────────────
|
||||
|
||||
func is_enemy_unit(iid: String) -> bool:
|
||||
return enemy_unit_ids.has(iid)
|
||||
|
||||
|
||||
func is_friendly_unit(iid: String) -> bool:
|
||||
return friendly_unit_ids.has(iid)
|
||||
|
||||
# ── Ruin helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
## Returns true when the unit dictionary represents a Ruin card type.
|
||||
func is_ruin_unit(unit: Dictionary) -> bool:
|
||||
return str(unit.get("cardType", "")).to_lower() == "ruin"
|
||||
|
||||
|
||||
## Returns true when the given instance ID belongs to a Ruin unit.
|
||||
func is_ruin_instance(iid: String) -> bool:
|
||||
if iid.is_empty():
|
||||
return false
|
||||
var unit: Dictionary = Game.get_unit_by_id(iid)
|
||||
return not unit.is_empty() and is_ruin_unit(unit)
|
||||
|
||||
# ── Tile occupant helper ──────────────────────────────────────────────────────
|
||||
|
||||
## Returns true when the tile has an occupant that blocks movement (i.e. not a Ruin).
|
||||
func tile_has_blocking_occupant(tile: Dictionary) -> bool:
|
||||
var occupant_id: String = str(tile.get("occupantId", ""))
|
||||
if occupant_id.is_empty() or occupant_id == "null":
|
||||
print("[TileBlock] failing out")
|
||||
return false
|
||||
print("[TileBlock] returning this: ", not is_ruin_instance(occupant_id))
|
||||
return not is_ruin_instance(occupant_id)
|
||||
|
||||
# ── ArchSpirit helper ─────────────────────────────────────────────────────────
|
||||
|
||||
## Safe accessor for a player's archSpirit — returns {} when absent or wrong type.
|
||||
func safe_arch(player: Dictionary) -> Dictionary:
|
||||
var arch: Variant = player.get("archSpirit")
|
||||
return arch as Dictionary if arch is Dictionary else {}
|
||||
|
||||
# ── Board-unit enumeration ────────────────────────────────────────────────────
|
||||
|
||||
## Returns all non-Ruin units currently on the board (spirits + arch spirits).
|
||||
func all_board_units() -> Array:
|
||||
var units: Array = []
|
||||
for player: Dictionary in Game.state.get("players", []):
|
||||
for unit: Dictionary in player.get("field", []):
|
||||
if not is_ruin_unit(unit):
|
||||
units.append(unit)
|
||||
var arch: Dictionary = safe_arch(player)
|
||||
if not arch.is_empty():
|
||||
units.append(arch)
|
||||
return units
|
||||
|
||||
|
||||
## Returns a Dictionary[instanceId → true] of units whose active effects
|
||||
## mark them as obstructing the given movement type.
|
||||
func units_obstructing_movement_type(mov: String) -> Dictionary:
|
||||
var result: Dictionary = {}
|
||||
var want_label: String = "obstruct:%s" % mov.to_lower()
|
||||
var active_effects: Variant = Game.state.get("activeEffects")
|
||||
if not active_effects is Array:
|
||||
return result
|
||||
for effect: Dictionary in active_effects:
|
||||
if str(effect.get("label", "")).to_lower() == want_label:
|
||||
var target_ref: String = str(effect.get("targetRef", ""))
|
||||
if not target_ref.is_empty():
|
||||
result[target_ref] = true
|
||||
return result
|
||||
@@ -0,0 +1 @@
|
||||
uid://cdd7w27j5lpog
|
||||
Reference in New Issue
Block a user