class_name AlertManager extends Control ## What's going wrong on the farm, as labeled arrows at the screen edge for whatever is off ## screen (on-screen threats already have their world markers). Every frame it collects alerts: ## ESCAPE a carrier making off with loot. It escalates as the carrier nears its exit (the ## farm's nearest edge, on foot or flying): the arrow grows, pulses faster, and ## turns from orange to red, and the label ends in "!". ## BREACH a barrier being smashed, or one just broken (for BREACH_TIME) ## THEFT loot being taken, or an enemy on its way to it ## LOOSE an animal loose on the farm, or loot lying dropped ## Alerts of the same kind, enemy type, and loot category in the same zone are grouped into one ## ("3 crows — Crop Field"). They're ordered by priority (kind, then escalation, then distance to ## the scarecrow), and at most MAX_SHOWN arrows are drawn at once. enum Kind { ESCAPE, BREACH, THEFT, LOOSE } const PRIORITY := {Kind.ESCAPE: 100.0, Kind.BREACH: 70.0, Kind.THEFT: 60.0, Kind.LOOSE: 45.0} const FILL := { Kind.ESCAPE: Color(1.0, 0.22, 0.15), Kind.BREACH: Color(1.0, 0.45, 0.2), Kind.THEFT: Color(1.0, 0.6, 0.1), Kind.LOOSE: Color(1.0, 0.9, 0.25), } const MAX_SHOWN := 5 const MARGIN := 46.0 const BREACH_TIME := 6.0 ## Escape alerts start escalating this far from the exit. const ESCALATE_FROM := 20.0 var loot: LootSystem var waves: WaveDirector var enemies: EnemySystem var structures: StructureSystem var zones: FarmZones var player: Node3D ## Set by FarmSim: the field to the farm's edge (how far a carrier on foot has left to go). var sim: FarmSim ## Alerts drawn last frame (tests and debugging). var last_shown: Array[Dictionary] = [] var _breaches: Array = [] # [seconds left, position, type name] var _time: float = 0.0 var _font: Font func setup(p_sim: FarmSim) -> void: sim = p_sim loot = sim.loot waves = sim.waves enemies = sim.enemies structures = sim.structures zones = sim.zones player = sim.player structures.destroyed.connect(func(_id: int, t: String, at: Vector3) -> void: _breaches.append([BREACH_TIME, at, t])) sim.campaign.phase_changed.connect(func(phase: CampaignController.Phase, _p: CampaignController.Phase) -> void: if phase == CampaignController.Phase.MORNING: _breaches.clear()) func _ready() -> void: set_anchors_preset(Control.PRESET_FULL_RECT) mouse_filter = Control.MOUSE_FILTER_IGNORE _font = ThemeDB.fallback_font func _process(delta: float) -> void: _time += delta for b in _breaches: b[0] = float(b[0]) - delta _breaches = _breaches.filter(func(b: Array) -> bool: return float(b[0]) > 0.0) queue_redraw() ## Every alert right now, grouped and sorted by priority (highest first). Each is a dictionary: ## kind, type (EnemySystem type or -1), category (LootSystem.Category or -1), zone (name or ""), ## position (Vector3, the group's center), count, escalation (0..1), priority, label. func collect() -> Array[Dictionary]: var raw: Array[Dictionary] = [] if loot != null: for id in range(1, loot.item_count + 1): match loot.status[id]: LootSystem.Status.CARRIED: var d := enemies.resolve_handle(loot.holder[id]) if d < 0: continue var p := Vector2(enemies.pos_x[d], enemies.pos_z[d]) raw.append(_alert(Kind.ESCAPE, enemies.type[d], loot.category[id], p, _escalation(d, p))) LootSystem.Status.HOME: var d := enemies.resolve_handle(loot.holder[id]) if loot.holder[id] >= 0 else -1 if d >= 0: raw.append(_alert(Kind.THEFT, enemies.type[d], loot.category[id], loot.position_of(id), 0.0)) LootSystem.Status.DROPPED: raw.append(_alert(Kind.LOOSE, -1, loot.category[id], loot.position_of(id), 0.0)) if enemies != null and structures != null: for d in enemies.active_count: if enemies.alive[d] == 1 and enemies.state[d] == ThiefBehavior.State.BREAK: var e := structures.campaign.state.structure(enemies.barrier[d]) if not e.is_empty(): raw.append(_alert(Kind.BREACH, enemies.type[d], -1, Vector2(e["x"], e["z"]), 0.0)) for b in _breaches: var at: Vector3 = b[1] raw.append(_alert(Kind.BREACH, -1, -1, Vector2(at.x, at.z), 1.0)) return sort_alerts(group_alerts(raw)) ## Merges alerts of the same kind, type, category, and zone. static func group_alerts(raw: Array[Dictionary]) -> Array[Dictionary]: var groups := {} var order: Array[String] = [] for a in raw: var key := "%d|%d|%d|%s" % [a["kind"], a["type"], a["category"], a["zone"]] if not groups.has(key): groups[key] = a.duplicate() groups[key]["sum"] = a["position"] order.append(key) else: var g: Dictionary = groups[key] g["count"] = int(g["count"]) + 1 g["sum"] = (g["sum"] as Vector3) + (a["position"] as Vector3) g["escalation"] = maxf(float(g["escalation"]), float(a["escalation"])) var out: Array[Dictionary] = [] for key in order: var g: Dictionary = groups[key] g["position"] = (g["sum"] as Vector3) / float(g["count"]) g.erase("sum") g["priority"] = float(PRIORITY[g["kind"]]) + 20.0 * float(g["escalation"]) + minf(float(g["count"]) - 1.0, 5.0) g["label"] = label_for(g) out.append(g) return out static func sort_alerts(list: Array[Dictionary]) -> Array[Dictionary]: list.sort_custom(func(a: Dictionary, b: Dictionary) -> bool: if not is_equal_approx(float(a["priority"]), float(b["priority"])): return float(a["priority"]) > float(b["priority"]) return float(a.get("distance", 0.0)) < float(b.get("distance", 0.0))) return list ## The first `cap` alerts that pass the filter (on the HUD: those off screen). static func cap(list: Array[Dictionary], limit: int, keep: Callable = Callable()) -> Array[Dictionary]: var out: Array[Dictionary] = [] for a in list: if out.size() >= limit: break if not keep.is_valid() or keep.call(a): out.append(a) return out ## "3 crows — Crop Field", "Crow escaping with a crop!", "Breach! — Animal Pen". static func label_for(a: Dictionary) -> String: var n := int(a["count"]) var t := int(a["type"]) var who := "" if t >= 0: who = "%d %s" % [n, EnemySystem.PLURALS[t]] if n > 1 else EnemySystem.NAMES[t].capitalize() var what := "" var c := int(a["category"]) if c >= 0: what = ["crop", "animal", "supplies"][c] if n > 1 and c != LootSystem.Category.SUPPLY: what += "s" var text := "" match int(a["kind"]): Kind.ESCAPE: var article := ("an " if what.begins_with("a") else "a ") if n == 1 and c != LootSystem.Category.SUPPLY else "" text = "%s escaping with %s%s" % [who, article, what] if float(a["escalation"]) >= 0.7: text += "!" Kind.BREACH: text = "Breach!" if t < 0 else "%s smashing a barrier" % who Kind.THEFT: text = who Kind.LOOSE: text = ("%d loose animals" % n if n > 1 else "Loose animal") if c == LootSystem.Category.ANIMAL \ else ("%d dropped %s" % [n, what] if n > 1 else "Dropped %s" % what) return "%s — %s" % [text, a["zone"]] if String(a["zone"]) != "" else text func _alert(kind: Kind, type: int, category: int, p: Vector2, escalation: float) -> Dictionary: var zone := zones.zone_at(Vector3(p.x, 0.0, p.y)) if zones != null else null var me := Vector2(player.global_position.x, player.global_position.z) if player != null else p return {"kind": kind, "type": type, "category": category, "zone": zone.display_name if zone != null else "", "position": Vector3(p.x, 1.0, p.y), "count": 1, "escalation": escalation, "distance": p.distance_to(me)} ## How close a carrier is to getting away (0 far .. 1 at the exit): on foot by the escape field, ## a flyer by its distance to the fence. func _escalation(d: int, p: Vector2) -> float: var left := ESCALATE_FROM if enemies.t_flying[enemies.type[d]] == 1: var r := zones.playable left = maxf(minf(minf(p.x - r.position.x, r.end.x - p.x), minf(p.y - r.position.y, r.end.y - p.y)), 0.0) elif sim != null and not sim.escape_field.is_empty(): left = sim.nav.meters(sim.escape_field[sim.nav.cell_of(p.x, p.y)]) return clampf(1.0 - left / ESCALATE_FROM, 0.0, 1.0) func _draw() -> void: var cam := get_viewport().get_camera_3d() if cam == null or loot == null: return var view := get_viewport_rect() var inner := view.grow(-MARGIN) var center := inner.get_center() var to_canvas := get_viewport().get_screen_transform().affine_inverse() var offscreen := func(a: Dictionary) -> bool: var world: Vector3 = a["position"] return cam.is_position_behind(world) or not view.has_point(to_canvas * cam.unproject_position(world)) last_shown = cap(collect(), MAX_SHOWN, offscreen) var labels: Array[Rect2] = [] for a in last_shown: var world: Vector3 = a["position"] var behind := cam.is_position_behind(world) var p := to_canvas * cam.unproject_position(world) var dir := (p - center) * (-1.0 if behind else 1.0) dir = dir.normalized() if dir.length_squared() > 1.0 else Vector2.DOWN var t := INF if absf(dir.x) > 1e-4: t = minf(t, inner.size.x * 0.5 / absf(dir.x)) if absf(dir.y) > 1e-4: t = minf(t, inner.size.y * 0.5 / absf(dir.y)) _arrow(_clear_of_hud(center + dir * t, inner), dir, a, labels) ## The HUD's corner panels (phase, materials, scarecrow), which arrows and labels keep out of. func _hud_rects() -> Array[Rect2]: var v := size_px() return [Rect2(0.0, 0.0, 600.0, 140.0), Rect2(v.x - 540.0, 0.0, 540.0, 130.0), Rect2(0.0, v.y - 180.0, 370.0, 180.0)] ## Slides a point on the arrow border along that border, out of any HUD panel. func _clear_of_hud(p: Vector2, inner: Rect2) -> Vector2: for r in _hud_rects(): var g := r.grow(24.0) if not g.has_point(p): continue var on_side := absf(p.x - inner.position.x) < 1.0 or absf(p.x - inner.end.x) < 1.0 if on_side: p.y = g.end.y if g.position.y <= 0.0 else g.position.y else: p.x = g.end.x if g.position.x <= 0.0 else g.position.x return p func _arrow(at: Vector2, dir: Vector2, a: Dictionary, labels: Array[Rect2]) -> void: var e := float(a["escalation"]) var color: Color = FILL[a["kind"]] if int(a["kind"]) == Kind.ESCAPE: color = Color(1.0, 0.6, 0.15).lerp(Color(1.0, 0.1, 0.08), e) var pulse := 0.5 + 0.5 * sin(_time * (5.0 + 10.0 * e)) var size := 1.0 + 0.45 * e * pulse var side := Vector2(-dir.y, dir.x) var tip := at + dir * 28.0 * size var back := at - dir * 16.0 * size var points := PackedVector2Array([tip, back + side * 22.0 * size, back - side * 22.0 * size]) draw_colored_polygon(points, color) points.append(tip) var rim: Color = LootSystem.CATEGORY_COLORS[a["category"]] if int(a["category"]) >= 0 else Color(0.05, 0.03, 0.0) draw_polyline(points, rim, 5.0, true) draw_polyline(points, Color(0.05, 0.03, 0.0), 1.5, true) var text := String(a["label"]) var fs := 20 var w := _font.get_string_size(text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs).x var anchor := at - dir * 44.0 - Vector2(w * 0.5, -fs * 0.35) anchor.x = clampf(anchor.x, 8.0, size_px().x - w - 8.0) anchor.y = clampf(anchor.y, fs + 4.0, size_px().y - 8.0) # Stack labels instead of overlapping them (moving toward the middle of the screen). var step := Vector2(0.0, -26.0 if anchor.y > size_px().y * 0.5 else 26.0) var box := Rect2(anchor + Vector2(-6.0, -fs - 2.0), Vector2(w + 12.0, fs + 10.0)) for k in 6: var hit := false for other in labels: if other.intersects(box): hit = true break if not hit: break anchor += step box.position += step labels.append(box) draw_rect(box, Color(0.0, 0.0, 0.0, 0.45)) draw_string_outline(_font, anchor, text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, 6, Color.BLACK) draw_string(_font, anchor, text, HORIZONTAL_ALIGNMENT_LEFT, -1, fs, color.lerp(Color.WHITE, 0.35)) func size_px() -> Vector2: return get_viewport_rect().size