harvest/game/scripts/build_mode.gd
2026-10-04 12:07:36 -04:00

208 lines
7.3 KiB
GDScript

class_name BuildMode
extends Node3D
## The scarecrow's build mode (build_mode: B / d-pad up toggles it):
## * Pick what to build with 1-4, or cycle with build_next (Tab / d-pad down).
## * A ghost follows the cursor, snapped to the 0.5 m grid: the ground point under the mouse,
## or GAMEPAD_REACH ahead along the right stick. rotate_left / rotate_right (Z / C, d-pad)
## turn it by 45 degrees.
## * The ghost is green where it can go and red where it can't, with the reason above it.
## * fire (LMB / RT) builds it (StructureSystem.validate, then place).
## * Over a built structure, cancel (RMB / B) dismantles it for its refund; anywhere else
## cancel leaves build mode.
## The scarecrow doesn't shoot, gather, or repair while building (FarmSim, Interactions).
## Co-op, on the partner's machine: placing and dismantling are sent to the host (place_request,
## dismantle_request), which checks them again and does them; the result comes back as a message.
signal message(text: String, color: Color)
signal toggled(on: bool)
## A placement was refused (the reason); a structure was taken down.
signal refused(reason: String)
signal dismantled(type: String)
const ACTIONS: Array[StringName] = [&"build_mode", &"build_next", &"build_1", &"build_2", &"build_3",
&"build_4", &"rotate_left", &"rotate_right", &"fire", &"cancel"]
const GAMEPAD_REACH := 3.0
var active := false
var selected: int = 0
var rot: int = 0
var cursor := Vector2.ZERO
## Built structure under the cursor (-1 = none) and why the ghost can't be placed ("" = it can).
var hover: int = -1
var reason := ""
var config: GameConfig
var campaign: CampaignController
var player: PlayerCharacter
var camera: Camera3D
var structures: StructureSystem
var combat: ScarecrowCombat
var kit: Scarecrow
## Co-op partner: ask the host instead (type, x, z, rot) / (structure id).
var place_request: Callable
var dismantle_request: Callable
var _edges := ActionEdges.new()
var _ghost: Node3D
var _ghost_key := ""
var _ok_mat: StandardMaterial3D
var _bad_mat: StandardMaterial3D
var _label: Label3D
var _stick_dir := Vector2(0.0, -1.0)
func setup(cfg: GameConfig, p_campaign: CampaignController, p_player: PlayerCharacter, p_camera: Camera3D,
p_structures: StructureSystem, p_combat: ScarecrowCombat, p_kit: Scarecrow) -> void:
config = cfg
campaign = p_campaign
player = p_player
camera = p_camera
structures = p_structures
combat = p_combat
kit = p_kit
_ok_mat = _ghost_material(Color(0.3, 1.0, 0.4, 0.45))
_bad_mat = _ghost_material(Color(1.0, 0.25, 0.2, 0.45))
_label = Label3D.new()
_label.billboard = BaseMaterial3D.BILLBOARD_ENABLED
_label.no_depth_test = true
_label.shaded = false
_label.font_size = 40
_label.outline_size = 10
_label.pixel_size = 0.0075
_label.top_level = true
_label.visible = false
_label.physics_interpolation_mode = Node.PHYSICS_INTERPOLATION_MODE_OFF
add_child(_label)
func type() -> String:
return StructureSystem.ORDER[selected]
func set_active(on: bool) -> void:
if on == active:
return
active = on
if _ghost != null:
_ghost.visible = on
_label.visible = on
toggled.emit(on)
## One physics tick. Every action is polled each tick so presses are seen exactly once.
func step(_dt: float) -> void:
var p := {}
for a in ACTIONS:
p[a] = _edges.pressed(a)
if not kit.alive:
set_active(false)
return
if p[&"build_mode"]:
set_active(not active)
if not active:
return
for k in 4:
if p[StringName("build_%d" % (k + 1))]:
selected = k
if p[&"build_next"]:
selected = (selected + 1) % StructureSystem.ORDER.size()
if p[&"rotate_left"]:
rot = (rot + 7) % 8
if p[&"rotate_right"]:
rot = (rot + 1) % 8
_update_cursor()
var me := Vector2(player.global_position.x, player.global_position.z)
hover = structures.structure_near(cursor, 0.3)
if hover >= 0:
reason = ""
if p[&"cancel"]:
if dismantle_request.is_valid():
dismantle_request.call(hover)
hover = -1
return
var e := campaign.state.structure(hover)
var back := structures.dismantle(hover)
dismantled.emit(String(e["type"]))
message.emit("Dismantled the %s%s" % [StructureSystem.NAMES[e["type"]].to_lower(),
(": %s back in the shed" % ResourceStore.describe(back)) if not back.is_empty() else ""], Color(0.85, 0.95, 1.0))
hover = -1
return
reason = structures.validate(type(), cursor.x, cursor.y, rot, me)
if p[&"fire"]:
if reason == "" and place_request.is_valid():
place_request.call(type(), cursor.x, cursor.y, rot)
elif reason == "":
structures.place(type(), cursor.x, cursor.y, rot)
message.emit("Built a %s" % StructureSystem.NAMES[type()].to_lower(), Color(0.6, 1.0, 0.55))
else:
message.emit(reason, Color(1.0, 0.8, 0.5))
refused.emit(reason)
elif p[&"cancel"]:
set_active(false)
func _unhandled_input(event: InputEvent) -> void:
_edges.note(event, ACTIONS)
func _update_cursor() -> void:
var at: Vector2
if combat.device == ScarecrowCombat.Device.GAMEPAD:
var b := camera.global_transform.basis
var fwd := Vector2(-b.z.x, -b.z.z).normalized()
var right := Vector2(b.x.x, b.x.z).normalized()
var stick := Input.get_vector("aim_left", "aim_right", "aim_down", "aim_up", config.aim_dead_zone)
if stick != Vector2.ZERO:
_stick_dir = (right * stick.x + fwd * stick.y).normalized()
at = Vector2(player.global_position.x, player.global_position.z) + _stick_dir * GAMEPAD_REACH
else:
var screen := camera.get_viewport().get_mouse_position()
var o := camera.project_ray_origin(screen)
var d := camera.project_ray_normal(screen)
var t := -o.y / d.y if absf(d.y) > 1e-5 else 0.0
at = Vector2(o.x + d.x * t, o.z + d.z * t)
cursor = StructureSystem.snap(at)
func _process(_delta: float) -> void:
if not active:
return
var key := "%s/%d" % [type(), rot]
if key != _ghost_key:
_ghost_key = key
if _ghost != null:
_ghost.queue_free()
_ghost = structures.make_ghost(type(), rot)
_ghost.top_level = true
add_child(_ghost)
var ok := reason == "" and hover < 0
for mi in _ghost.find_children("*", "MeshInstance3D", true, false):
(mi as MeshInstance3D).material_override = _ok_mat if ok else _bad_mat
_ghost.visible = hover < 0
_ghost.global_position = Vector3(cursor.x, structures._ground_y(cursor), cursor.y)
_label.global_position = Vector3(cursor.x, 2.4, cursor.y)
if hover >= 0:
var e := campaign.state.structure(hover)
var refund := {}
var cost: Dictionary = config.costs.get(e.get("type", ""), {})
for m in cost:
if floori(int(cost[m]) * config.dismantle_refund) > 0:
refund[m] = floori(int(cost[m]) * config.dismantle_refund)
_label.text = "%s %d/%d\n[RMB / B] Dismantle%s" % [StructureSystem.NAMES.get(e.get("type", ""), ""), int(e.get("hp", 0)),
structures.max_hp(e.get("type", "fence")), (" (+%s)" % ResourceStore.describe(refund)) if not refund.is_empty() else ""]
_label.modulate = Color(0.85, 0.95, 1.0)
elif ok:
_label.text = "%s %s\n[LMB / RT] Build" % [StructureSystem.NAMES[type()], ResourceStore.describe(config.costs.get(type(), {}))]
_label.modulate = Color(0.7, 1.0, 0.7)
else:
_label.text = "%s\n%s" % [StructureSystem.NAMES[type()], reason]
_label.modulate = Color(1.0, 0.7, 0.6)
func _ghost_material(color: Color) -> StandardMaterial3D:
var m := StandardMaterial3D.new()
m.shading_mode = BaseMaterial3D.SHADING_MODE_UNSHADED
m.transparency = BaseMaterial3D.TRANSPARENCY_ALPHA
m.albedo_color = color
m.no_depth_test = false
return m