Skip to main content

delvewright_dsl/
actor.rs

1//! Stage 5 — scripted actors (DSL v0.6, spec-0014): bodies the story moves.
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6use crate::serde_fields::{is_false, is_zero3};
7use crate::{
8    ActorId, AnchorId, BodyTraversal, EncounterTier, MobAttributes, MobDrop, MobEquipment, NpcSkin,
9    OnKill, QuestEffect,
10};
11
12#[cfg(doc)]
13use crate::{Mark, Npc, Wave};
14
15/// A scripted stage actor (DSL v0.6, spec-0014): a NoAI/Silent/no-loot puppet,
16/// distinct from a stage-2 [`Npc`] (no dialogue, any mob type). Emitted with tag
17/// `dw_actor_<id>`, `Invulnerable` unless `vulnerable` (a damageable puppet stays
18/// knockback-immune — the tower-defense creep). `skin` re-dresses it as a
19/// `minecraft:mannequin`, exactly as a stage-2 NPC skin. The puppet is summoned by
20/// a `spawn-actor` effect (not at load), moved by `move-actor`, and can be replaced
21/// by a real-AI twin with `unleash-actor`.
22#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
23#[serde(deny_unknown_fields)]
24pub struct Actor {
25    /// Unique actor id (`actor/<kebab>`).
26    pub id: ActorId,
27    /// The vanilla entity to puppet, e.g. `minecraft:warden`. Validated against the
28    /// pinned 1.21.11 entity registry (`DW0173`).
29    pub entity: String,
30    /// Optional custom name shown above the puppet.
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub name: Option<String>,
33    /// Optional player-model skin (mannequin), as a stage-2 NPC (`DW0190`).
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub skin: Option<NpcSkin>,
36    /// The anchor the puppet is summoned on (resolved across areas, like an
37    /// `open-gate` / `move-npc` destination).
38    pub anchor: AnchorId,
39    /// Integer `[x, y, z]` block offset from `anchor` (spec-0066, default
40    /// `[0, 0, 0]`): the puppet stands at the [`Mark`] the two fields spell, so
41    /// a rank of bodies is one anchor and an offset apiece.
42    #[serde(default, skip_serializing_if = "is_zero3")]
43    pub offset: [i32; 3],
44    /// Initial facing (default `south`). The puppet spawns yawed this way.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub facing: Option<Facing>,
47    /// If `true`, the puppet is damageable (a tower-defense creep) but stays
48    /// knockback-immune; default `false` (fully `Invulnerable`).
49    #[serde(default, skip_serializing_if = "is_false")]
50    pub vulnerable: bool,
51    /// Gear the actor wears and holds, in the same shape a wave mob uses
52    /// ([`MobEquipment`]). Emitted into BOTH the staged puppet and the
53    /// unleashed twin, so the dormant elite the player has been circling is
54    /// visibly the same armoured thing that stands up. Drop chances are zero —
55    /// wave gear and actor gear are never farmable (no-grind constitution).
56    #[serde(default, skip_serializing_if = "Option::is_none")]
57    pub equipment: Option<MobEquipment>,
58    /// Attribute overrides, in the same shape a wave mob uses ([`MobAttributes`],
59    /// the v0.4 surface — one type, one rule set, so the two surfaces cannot
60    /// drift). Emitted into BOTH the staged puppet and the unleashed twin, so the
61    /// elite the party fights is the elite the author tuned; without it an actor
62    /// was stuck at vanilla base values while every wave mob could be tuned,
63    /// which is what blocked elite authoring. A `vulnerable` actor's
64    /// knockback-immunity is emitted first and is not authorable.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub attributes: Option<MobAttributes>,
67    /// How hard this actor's fight is *meant* to be (DSL v0.8, spec-0023) — the
68    /// same [`EncounterTier`] vocabulary a [`Wave`] declares. Absent =
69    /// [`EncounterTier::Ordinary`], byte-identical to every pre-0.8 campaign.
70    ///
71    /// A wave is not the only shape an elite takes. The set-piece souls fight —
72    /// the armoured thing kneeling among the graves that stands up when you hit
73    /// it — is an **actor**: staged by `spawn-actor`, given AI by
74    /// `unleash-actor`, killed by hand rather than by a `kill` objective. Before
75    /// this field nothing anywhere stated what such a fight was billed as.
76    ///
77    /// Like the wave field this is a **declaration, not a knob**: the compiler
78    /// never scales an actor from it, and emission is unchanged whichever tier is
79    /// declared. Its readers are the health-bar advisory (`DW0912`) and the drop
80    /// rule — only a billed fight leaves anything behind.
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub tier: Option<EncounterTier>,
83    /// A health bar over this actor's fight (DSL v0.31, spec-0073) — the same
84    /// [`HealthBar`](crate::healthbar::HealthBar) a [`Wave`] declares. It reads the
85    /// bodies whose health can move: the unleashed twin, or the puppet itself when
86    /// the actor is `vulnerable`. A bar on an actor that is neither is `DW0909`.
87    /// Absent = no bar, byte-identical.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub health_bar: Option<crate::healthbar::HealthBar>,
90    /// What this actor leaves behind when a player kills it. Only an
91    /// `elite`/`boss` actor may
92    /// declare it (`DW0491`). Emitted into BOTH the staged puppet and the
93    /// unleashed twin, exactly as `equipment` is — the drop belongs to the body,
94    /// not to one of its two lifecycles. A `despawn-actor` strips the
95    /// declaration off the body before removing it, so re-caging an elite (a
96    /// souls re-seat) never scatters its axe.
97    #[serde(default, skip_serializing_if = "Vec::is_empty")]
98    pub drops: Vec<MobDrop>,
99    /// What this body can do when it moves (DSL v0.11, spec-0034) — the same
100    /// [`BodyTraversal`] a stage-2 [`Npc`] carries, because traversal belongs to
101    /// the body and not to the stage that declares it. Absent = the class the
102    /// compiler derives from `entity` (or from `minecraft:mannequin` when `skin`
103    /// is set).
104    #[serde(default, skip_serializing_if = "Option::is_none")]
105    pub traversal: Option<BodyTraversal>,
106    /// What happens each time a player is credited with killing this actor's
107    /// body (spec-0074) — effect root R9, the same [`OnKill`] a
108    /// wave declares. Absent = no bundle, and the actor's emission is
109    /// byte-identical.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub on_kill: Option<OnKill>,
112}
113
114/// A cardinal facing keyword (DSL v0.6). Emitted as the puppet's spawn yaw
115/// (MC: yaw 0 = +z/south).
116#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
117#[serde(rename_all = "kebab-case")]
118pub enum Facing {
119    /// Facing +z (yaw 0) — the default.
120    South,
121    /// Facing -z (yaw 180).
122    North,
123    /// Facing -x (yaw 90).
124    West,
125    /// Facing +x (yaw 270).
126    East,
127}
128
129impl Facing {
130    /// The kebab token (`south` / `north` / `west` / `east`).
131    pub fn token(self) -> &'static str {
132        match self {
133            Facing::South => "south",
134            Facing::North => "north",
135            Facing::West => "west",
136            Facing::East => "east",
137        }
138    }
139}
140
141/// How a `despawn-actor` removes its puppet (DSL v0.6).
142#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
143#[serde(rename_all = "kebab-case")]
144pub enum DespawnStyle {
145    /// The body leaves unseen: no death animation, red flash or death particles
146    /// where it stood. It is moved under the world and removed there.
147    Vanish,
148    /// The body dies where it stands, with the vanilla death animation (a death
149    /// the player is meant to watch).
150    Kill,
151}
152
153impl DespawnStyle {
154    /// The kebab token (`vanish` / `kill`).
155    pub fn token(self) -> &'static str {
156        match self {
157            DespawnStyle::Vanish => "vanish",
158            DespawnStyle::Kill => "kill",
159        }
160    }
161}
162
163/// One step of a [`Verb::Sequence`] (DSL v0.6): a group of effects fired at
164/// an exact tick offset from the sequence's start.
165#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
166#[serde(deny_unknown_fields)]
167pub struct SequenceStep {
168    /// Tick offset from the sequence start at which `effects` fire.
169    pub at_ticks: u32,
170    /// The effects fired at `at_ticks`. Any stage-5 effect except a nested
171    /// `sequence` (rejected with `DW0329`).
172    pub effects: Vec<QuestEffect>,
173}
174
175// ---------------------------------------------------------------------------
176// Validation — the checks `dsl::validate` runs over this object (ADR-0031)
177// ---------------------------------------------------------------------------
178
179use crate::Verb;
180use crate::diagnostic::{Diagnostic, codes};
181use crate::envelope::Campaign;
182use crate::ids::is_kebab;
183use crate::quest::check::check_no_nested_sequence;
184use crate::registry::{AnchorRegistry, EntityRegistry, ItemRegistry};
185use crate::validate::{AnchorProviders, station_kind_diag};
186use crate::wave::check_equipment;
187use std::collections::BTreeSet;
188
189/// Recursively visit every effect in `effs`, descending into every nested effect
190/// list ([`QuestEffect::nested_effect_lists`]: `sequence` steps, `set-checkpoint`
191/// `on_respawn`, `begin-stealth` `on_caught`, `move-actor` / `move-npc`
192/// `on_arrive`).
193fn walk_effects_deep(effs: &[QuestEffect], f: &mut dyn FnMut(&QuestEffect)) {
194    for e in effs {
195        e.visit_deep(f);
196    }
197}
198
199/// Actor declarations (spec-0014): a known entity id, a well-formed and distinct
200/// skin, a spawn anchor some area provides — and every actor staging effect's
201/// reference (`DW0112`), every `move-actor` destination anchor (`DW0142`) and the
202/// no-nested-`sequence` rule (`DW0329`) at every depth of a quest's or a
203/// trigger's bundles.
204pub(crate) fn actor_checks(
205    c: &Campaign,
206    anchors: &dyn AnchorRegistry,
207    entities: &dyn EntityRegistry,
208    d: &mut Vec<Diagnostic>,
209) {
210    let quests = &c.quests.content;
211    let declared: BTreeSet<&str> = quests.actors.iter().map(|a| a.id.as_str()).collect();
212
213    // Anchor names provided by single-prefab areas (pool areas resolve anchors in
214    // the compiler, so their presence defers the check — mirroring `DW0142`'s
215    // single-prefab-only scope; never a false positive).
216    let providers = AnchorProviders::build(c, anchors);
217
218    // Actor declarations: entity id, skin, spawn anchor.
219    let mut seen_skins: BTreeSet<&str> = BTreeSet::new();
220    for (i, a) in quests.actors.iter().enumerate() {
221        if !entities.contains(&a.entity) {
222            d.push(Diagnostic::error(
223                codes::ENTITY_UNKNOWN,
224                "quests",
225                format!("/content/actors/{i}/entity"),
226                format!(
227                    "actor entity `{}` is not a known 1.21.11 entity id — use a valid namespaced \
228                     entity id (e.g. `minecraft:warden`)",
229                    a.entity
230                ),
231            ));
232        }
233        if let Some(skin) = &a.skin {
234            if !is_kebab(&skin.texture_id) {
235                d.push(Diagnostic::error(
236                    codes::SKIN_INVALID,
237                    "quests",
238                    format!("/content/actors/{i}/skin/texture_id"),
239                    format!(
240                        "actor skin `texture_id` `{}` is malformed — it must be a bare kebab token \
241                         (e.g. `giant-idle`), matching the `skins/<texture_id>.png` filename",
242                        skin.texture_id
243                    ),
244                ));
245            } else if !seen_skins.insert(skin.texture_id.as_str()) {
246                d.push(Diagnostic::error(
247                    codes::SKIN_INVALID,
248                    "quests",
249                    format!("/content/actors/{i}/skin/texture_id"),
250                    format!(
251                        "duplicate actor skin `texture_id` `{}` — each mannequin needs a distinct \
252                         texture; rename one (and its `skins/<id>.png`)",
253                        skin.texture_id
254                    ),
255                ));
256            }
257        }
258        if let Some(f) = station_kind_diag(
259            &providers,
260            a.anchor.as_str(),
261            crate::layout::StationKind::Point,
262            "an actor's station",
263            "quests",
264            format!("/content/actors/{i}/anchor"),
265        ) {
266            d.push(f);
267        }
268        if !providers.resolvable(a.anchor.as_str()) {
269            d.push(Diagnostic::error(
270                codes::ANCHOR_UNRESOLVED,
271                "quests",
272                format!("/content/actors/{i}/anchor"),
273                format!(
274                    "actor anchor `{}` is not provided by any area's prefab — {}",
275                    a.anchor,
276                    providers.anchor_remedy(
277                        "use an anchor a prefab exposes, or bind a prefab/pool that carries it"
278                    ),
279                ),
280            ));
281        }
282    }
283
284    // Effect-level: actor references (DW0112), move-actor destination anchors
285    // (DW0142), and the no-nested-sequence rule (DW0329). Deep-walk so effects
286    // nested in a `sequence` / `move-actor` `on_arrive` are covered.
287    let mut groups: Vec<(String, &[QuestEffect])> = Vec::new();
288    for (i, q) in quests.quests.iter().enumerate() {
289        for (key, effs) in &q.on_objective_complete {
290            groups.push((
291                format!("/content/quests/{i}/on_objective_complete/{key}"),
292                effs.as_slice(),
293            ));
294        }
295        groups.push((
296            format!("/content/quests/{i}/on_complete"),
297            q.on_complete.as_slice(),
298        ));
299    }
300    for (i, t) in quests.triggers.iter().enumerate() {
301        groups.push((
302            format!("/content/triggers/{i}/effects"),
303            t.effects.as_slice(),
304        ));
305    }
306    for (path, effs) in &groups {
307        let mut visit = |e: &QuestEffect| {
308            if let Some(actor) = e.actor_ref()
309                && !declared.contains(actor.as_str())
310            {
311                d.push(Diagnostic::error(
312                    codes::DANGLING_REF,
313                    "quests",
314                    path.clone(),
315                    format!(
316                        "actor staging effect references unknown actor `{actor}` — declare it in \
317                         the stage-5 `actors` list, or fix the reference"
318                    ),
319                ));
320            }
321            if let Verb::MoveActor { to, .. } = &e.verb
322                && let Some(f) = station_kind_diag(
323                    &providers,
324                    to.anchor.as_str(),
325                    crate::layout::StationKind::Point,
326                    "a `move-actor` destination",
327                    "quests",
328                    path.clone(),
329                )
330            {
331                d.push(f);
332            } else if let Verb::MoveActor { to, .. } = &e.verb
333                && !providers.resolvable(to.anchor.as_str())
334            {
335                d.push(Diagnostic::error(
336                    codes::ANCHOR_UNRESOLVED,
337                    "quests",
338                    path.clone(),
339                    format!(
340                        "move-actor destination anchor `{}` is not provided by any \
341                         area's prefab — {}",
342                        to.anchor,
343                        providers.anchor_remedy("use an anchor a prefab exposes"),
344                    ),
345                ));
346            }
347        };
348        walk_effects_deep(effs, &mut visit);
349        check_no_nested_sequence(effs, path, d);
350    }
351}
352
353/// Actor `equipment` (spec-0021): item ids and enchantments, by the wave mob's
354/// rule ([`crate::wave::check_equipment`]).
355pub(crate) fn actor_equipment_checks(
356    c: &Campaign,
357    items: &dyn ItemRegistry,
358    d: &mut Vec<Diagnostic>,
359) {
360    let quests = &c.quests.content;
361    // Actor `equipment` (spec-0021): the same shape, the same registries, the
362    // same diagnostics as a wave mob's — one surface, one rule set.
363    for (i, a) in quests.actors.iter().enumerate() {
364        let Some(eq) = &a.equipment else { continue };
365        check_equipment(
366            eq,
367            "actor",
368            &format!("/content/actors/{i}/equipment"),
369            items,
370            d,
371        );
372    }
373}
374
375/// `DW0110` over the scripted-actor ids.
376pub(crate) fn actor_id_syntax(c: &Campaign, d: &mut Vec<Diagnostic>) {
377    for (i, a) in c.quests.content.actors.iter().enumerate() {
378        crate::ids::id_syntax!(d, a.id, "quests", format!("/content/actors/{i}/id"));
379    }
380}
381
382/// `DW0111` over the scripted-actor ids: unique within the stage-5 actors
383/// namespace (DSL v0.6).
384pub(crate) fn actor_id_uniqueness(c: &Campaign, d: &mut Vec<Diagnostic>) {
385    crate::ids::dup_check(
386        c.quests
387            .content
388            .actors
389            .iter()
390            .enumerate()
391            .map(|(i, a)| (a.id.as_str(), format!("/content/actors/{i}/id"))),
392        "quests",
393        "actor",
394        d,
395    );
396}