Skip to main content

runec/
trigger_table.rs

1//! Single source of truth for RuneScript trigger metadata.
2//!
3//! Every trigger keyword (`[opnpc1,…]`, `[if_button,…]`, `[login,_]`, …)
4//! has the same shape of metadata: a byte discriminant for lookup-key
5//! dispatch, an optional preferred subject type for entity resolution,
6//! whether its subject should be validated to resolve, and whether it's a
7//! button trigger that participates in pointer-grant logic.
8//!
9//! Before this module existed, that metadata was scattered across three
10//! separate matches in `compiler.rs` (the byte table, the
11//! `is_byte_keyed_trigger` whitelist, and the `preferred_type` selector)
12//! plus a 13-arm match in `pointer_checker.rs`. Adding a trigger meant
13//! editing four places, and one of them was the bug shape that silently
14//! produced unreachable scripts.
15
16use crate::types::Type;
17use std::collections::HashMap;
18use std::sync::OnceLock;
19
20#[derive(Debug, Clone, Copy)]
21pub struct TriggerInfo {
22    pub name: &'static str,
23    pub byte: u8,
24    /// Preferred entity type for `lookup_entity_id_typed`. `None` falls
25    /// through to the flat entity-id lookup.
26    pub subject_type: Option<Type>,
27    /// True if a `[trigger,name]` script with a non-`_`, non-`_category`,
28    /// non-coord subject should resolve to a real entity. Drives the
29    /// "subject did not resolve" warning. False for triggers that:
30    ///   - have no entity subject (login, logout)
31    ///   - take coord-shaped subjects (zone, zoneexit, mapzone, mapzoneexit)
32    ///   - intentionally don't validate (ai_queue, ai_timer — preserved
33    ///     from the original `is_byte_keyed_trigger` whitelist; widening
34    ///     this would change emitted warnings)
35    pub validates_subject: bool,
36    /// True for if_button/if_button1-10/if_buttond and inv_button1-5/inv_buttond.
37    /// Used by pointer_checker to grant p_active_player on non-overlay
38    /// interfaces, mirroring ServerPointerChecker.setsPointerTrigger().
39    pub is_button: bool,
40}
41
42const TRIGGERS: &[TriggerInfo] = &[
43    // ── NPC triggers ─────────────────────────────────────────────────
44    npc("apnpc1", 3),
45    npc("apnpc2", 4),
46    npc("apnpc3", 5),
47    npc("apnpc4", 6),
48    npc("apnpc5", 7),
49    npc("apnpcu", 8),
50    npc("apnpct", 9),
51    npc("opnpc1", 10),
52    npc("opnpc2", 11),
53    npc("opnpc3", 12),
54    npc("opnpc4", 13),
55    npc("opnpc5", 14),
56    npc("opnpcu", 15),
57    npc("opnpct", 16),
58    npc("ai_apnpc1", 17),
59    npc("ai_apnpc2", 18),
60    npc("ai_apnpc3", 19),
61    npc("ai_apnpc4", 20),
62    npc("ai_apnpc5", 21),
63    npc("ai_opnpc1", 24),
64    npc("ai_opnpc2", 25),
65    npc("ai_opnpc3", 26),
66    npc("ai_opnpc4", 27),
67    npc("ai_opnpc5", 28),
68    // ── Ground obj triggers ──────────────────────────────────────────
69    obj("apobj1", 31),
70    obj("apobj2", 32),
71    obj("apobj3", 33),
72    obj("apobj4", 34),
73    obj("apobj5", 35),
74    obj("apobju", 36),
75    obj("apobjt", 37),
76    obj("opobj1", 38),
77    obj("opobj2", 39),
78    obj("opobj3", 40),
79    obj("opobj4", 41),
80    obj("opobj5", 42),
81    obj("opobju", 43),
82    obj("opobjt", 44),
83    // An npc's AI triggers name the npc (or `_category`) whatever its target:
84    // the engine keys them by the acting npc's type, and RuneScriptTS gives them
85    // SubjectMode.Type(NPC).
86    npc("ai_apobj1", 45),
87    npc("ai_apobj2", 46),
88    npc("ai_apobj3", 47),
89    npc("ai_apobj4", 48),
90    npc("ai_apobj5", 49),
91    npc("ai_opobj1", 52),
92    npc("ai_opobj2", 53),
93    npc("ai_opobj3", 54),
94    npc("ai_opobj4", 55),
95    npc("ai_opobj5", 56),
96    // ── Loc triggers ─────────────────────────────────────────────────
97    loc("aploc1", 59),
98    loc("aploc2", 60),
99    loc("aploc3", 61),
100    loc("aploc4", 62),
101    loc("aploc5", 63),
102    loc("aplocu", 64),
103    loc("aploct", 65),
104    loc("oploc1", 66),
105    loc("oploc2", 67),
106    loc("oploc3", 68),
107    loc("oploc4", 69),
108    loc("oploc5", 70),
109    loc("oplocu", 71),
110    loc("oploct", 72),
111    // An npc's AI triggers name the npc (or `_category`) whatever its target:
112    // the engine keys them by the acting npc's type, and RuneScriptTS gives them
113    // SubjectMode.Type(NPC).
114    npc("ai_aploc1", 73),
115    npc("ai_aploc2", 74),
116    npc("ai_aploc3", 75),
117    npc("ai_aploc4", 76),
118    npc("ai_aploc5", 77),
119    npc("ai_oploc1", 80),
120    npc("ai_oploc2", 81),
121    npc("ai_oploc3", 82),
122    npc("ai_oploc4", 83),
123    npc("ai_oploc5", 84),
124    // ── Player triggers (no preferred type — fall through to flat lookup) ──
125    flat("applayer1", 87),
126    flat("applayer2", 88),
127    flat("applayer3", 89),
128    flat("applayer4", 90),
129    flat("applayer5", 91),
130    flat("applayeru", 92),
131    flat("applayert", 93),
132    flat("opplayer1", 94),
133    flat("opplayer2", 95),
134    flat("opplayer3", 96),
135    flat("opplayer4", 97),
136    flat("opplayer5", 98),
137    flat("opplayeru", 99),
138    flat("opplayert", 100),
139    // An npc's AI triggers name the npc (or `_category`) whatever its target:
140    // the engine keys them by the acting npc's type, and RuneScriptTS gives them
141    // SubjectMode.Type(NPC).
142    npc("ai_applayer1", 101),
143    npc("ai_applayer2", 102),
144    npc("ai_applayer3", 103),
145    npc("ai_applayer4", 104),
146    npc("ai_applayer5", 105),
147    npc("ai_opplayer1", 108),
148    npc("ai_opplayer2", 109),
149    npc("ai_opplayer3", 110),
150    npc("ai_opplayer4", 111),
151    npc("ai_opplayer5", 112),
152    // ── AI queue / timer (NPC-keyed, but historically not validated) ──
153    npc_no_validate("ai_queue1", 117),
154    npc_no_validate("ai_queue2", 118),
155    npc_no_validate("ai_queue3", 119),
156    npc_no_validate("ai_queue4", 120),
157    npc_no_validate("ai_queue5", 121),
158    npc_no_validate("ai_queue6", 122),
159    npc_no_validate("ai_queue7", 123),
160    npc_no_validate("ai_queue8", 124),
161    npc_no_validate("ai_queue9", 125),
162    npc_no_validate("ai_queue10", 126),
163    npc_no_validate("ai_queue11", 127),
164    npc_no_validate("ai_queue12", 128),
165    npc_no_validate("ai_queue13", 129),
166    npc_no_validate("ai_queue14", 130),
167    npc_no_validate("ai_queue15", 131),
168    npc_no_validate("ai_queue16", 132),
169    npc_no_validate("ai_queue17", 133),
170    npc_no_validate("ai_queue18", 134),
171    npc_no_validate("ai_queue19", 135),
172    npc_no_validate("ai_queue20", 136),
173    npc_no_validate("ai_timer", 139),
174    // ── Held / inventory item triggers ───────────────────────────────
175    obj("opheld1", 140),
176    obj("opheld2", 141),
177    obj("opheld3", 142),
178    obj("opheld4", 143),
179    obj("opheld5", 144),
180    obj("opheldu", 145),
181    obj("opheldt", 146),
182    // ── Interface / button triggers ──────────────────────────────────
183    iface("if_button", 147, true),
184    iface("if_close", 148, false),
185    iface("if_button1", 149, true),
186    iface("if_button2", 150, true),
187    iface("if_button3", 151, true),
188    iface("if_button4", 152, true),
189    iface("if_button5", 153, true),
190    iface("if_buttond", 154, true),
191    // Rev-647: client merged OpHeld/InvButton into IfButton1-10. Inventory
192    // item ops 6-10 (e.g. Drop=op8) are handled in content via
193    // `[if_button6..10,inv:component]` + `p_opheld(op, inv, slot)`.
194    // Bytes 173-177 must match the engine's ServerTriggerType InvButton6-10.
195    iface("if_button6", 173, true),
196    iface("if_button7", 174, true),
197    iface("if_button8", 175, true),
198    iface("if_button9", 176, true),
199    iface("if_button10", 177, true),
200    component("inv_button1", 149),
201    component("inv_button2", 150),
202    component("inv_button3", 151),
203    component("inv_button4", 152),
204    component("inv_button5", 153),
205    component("inv_buttond", 154),
206    // ── Player lifecycle / coord / stat triggers ─────────────────────
207    flat_no_validate("login", 157),
208    flat_no_validate("logout", 158),
209    flat("tutorial", 159),
210    stat("advancestat", 160),
211    flat_no_validate("mapzone", 161),
212    flat_no_validate("mapzoneexit", 162),
213    flat_no_validate("zone", 163),
214    flat_no_validate("zoneexit", 164),
215    stat("changestat", 165),
216    // An npc's spawn and despawn name the npc, as its other AI triggers do.
217    npc("ai_spawn", 166),
218    npc("ai_despawn", 167),
219    // A player entering or leaving an area painted on the map. 168-172 stay
220    // unused: they were opheld6-10.
221    area("area", 178),
222    area("areaexit", 179),
223];
224
225// ── Constructor helpers ──────────────────────────────────────────────
226//
227// `const fn` so the static slice above stays trivially constructible.
228
229const fn npc(name: &'static str, byte: u8) -> TriggerInfo {
230    TriggerInfo {
231        name,
232        byte,
233        subject_type: Some(Type::Npc),
234        validates_subject: true,
235        is_button: false,
236    }
237}
238
239const fn npc_no_validate(name: &'static str, byte: u8) -> TriggerInfo {
240    TriggerInfo {
241        name,
242        byte,
243        subject_type: Some(Type::Npc),
244        validates_subject: false,
245        is_button: false,
246    }
247}
248
249const fn obj(name: &'static str, byte: u8) -> TriggerInfo {
250    TriggerInfo {
251        name,
252        byte,
253        subject_type: Some(Type::Obj),
254        validates_subject: true,
255        is_button: false,
256    }
257}
258
259const fn loc(name: &'static str, byte: u8) -> TriggerInfo {
260    TriggerInfo {
261        name,
262        byte,
263        subject_type: Some(Type::Loc),
264        validates_subject: true,
265        is_button: false,
266    }
267}
268
269const fn iface(name: &'static str, byte: u8, is_button: bool) -> TriggerInfo {
270    TriggerInfo {
271        name,
272        byte,
273        subject_type: Some(Type::Interface),
274        validates_subject: true,
275        is_button,
276    }
277}
278
279const fn component(name: &'static str, byte: u8) -> TriggerInfo {
280    TriggerInfo {
281        name,
282        byte,
283        subject_type: Some(Type::Component),
284        validates_subject: true,
285        is_button: true,
286    }
287}
288
289const fn area(name: &'static str, byte: u8) -> TriggerInfo {
290    TriggerInfo {
291        name,
292        byte,
293        subject_type: Some(Type::Area),
294        validates_subject: true,
295        is_button: false,
296    }
297}
298
299/// `[advancestat,stat]` / `[changestat,stat]` — subject is a player stat.
300/// Routes to `Type::Stat` so the subject resolves via the typed map instead
301/// of the flat entity-id map, where a same-named entity of another type
302/// (e.g. a `hunt` called `ranged`) would otherwise shadow the stat.
303const fn stat(name: &'static str, byte: u8) -> TriggerInfo {
304    TriggerInfo {
305        name,
306        byte,
307        subject_type: Some(Type::Stat),
308        validates_subject: true,
309        is_button: false,
310    }
311}
312
313const fn flat(name: &'static str, byte: u8) -> TriggerInfo {
314    TriggerInfo {
315        name,
316        byte,
317        subject_type: None,
318        validates_subject: true,
319        is_button: false,
320    }
321}
322
323const fn flat_no_validate(name: &'static str, byte: u8) -> TriggerInfo {
324    TriggerInfo {
325        name,
326        byte,
327        subject_type: None,
328        validates_subject: false,
329        is_button: false,
330    }
331}
332
333// ── Name-keyed triggers ─────────────────────────────────────────────
334//
335// Triggers dispatched by script name (no byte discriminant). These are
336// valid trigger keywords but don't participate in lookup-key hashing.
337
338const NAME_KEYED_TRIGGERS: &[&str] = &[
339    "proc",
340    "label",
341    "debugproc",
342    "command",
343    "clientscript",
344    "walktrigger",
345    "queue",
346    "timer",
347    "softtimer",
348];
349
350// Rev-647 extensions: valid triggers whose byte discriminants are not
351// yet standardized in the reference implementation.
352const EXTENDED_TRIGGERS: &[&str] = &["switch_window_mode"];
353
354// ── Public lookup API ────────────────────────────────────────────────
355
356fn table() -> &'static HashMap<&'static str, TriggerInfo> {
357    static TABLE: OnceLock<HashMap<&'static str, TriggerInfo>> = OnceLock::new();
358    TABLE.get_or_init(|| TRIGGERS.iter().map(|t| (t.name, *t)).collect())
359}
360
361pub fn lookup(name: &str) -> Option<TriggerInfo> {
362    table().get(name).copied()
363}
364
365pub fn names() -> impl Iterator<Item = &'static str> {
366    TRIGGERS
367        .iter()
368        .map(|trigger| trigger.name)
369        .chain(NAME_KEYED_TRIGGERS.iter().copied())
370        .chain(EXTENDED_TRIGGERS.iter().copied())
371}
372
373pub fn byte(name: &str) -> Option<u8> {
374    lookup(name).map(|t| t.byte)
375}
376
377pub fn subject_type(name: &str) -> Option<Type> {
378    lookup(name).and_then(|t| t.subject_type)
379}
380
381pub fn validates_subject(name: &str) -> bool {
382    lookup(name).map(|t| t.validates_subject).unwrap_or(false)
383}
384
385pub fn is_button(name: &str) -> bool {
386    lookup(name).map(|t| t.is_button).unwrap_or(false)
387}
388
389pub fn is_valid_trigger(name: &str) -> bool {
390    lookup(name).is_some()
391        || NAME_KEYED_TRIGGERS.contains(&name)
392        || EXTENDED_TRIGGERS.contains(&name)
393}
394
395pub fn allows_returns(name: &str) -> bool {
396    matches!(name, "proc" | "clientscript" | "command" | "logout")
397}
398
399#[cfg(test)]
400mod tests {
401    use super::*;
402
403    #[test]
404    fn no_duplicate_trigger_names() {
405        let mut seen = std::collections::HashSet::new();
406        for t in TRIGGERS {
407            assert!(seen.insert(t.name), "duplicate trigger name: {}", t.name);
408        }
409    }
410
411    #[test]
412    fn button_triggers_match_legacy_set() {
413        // Locks in pointer_checker's old hand-maintained list.
414        let expected = [
415            "if_button",
416            "if_button1",
417            "if_button2",
418            "if_button3",
419            "if_button4",
420            "if_button5",
421            "if_button6",
422            "if_button7",
423            "if_button8",
424            "if_button9",
425            "if_button10",
426            "if_buttond",
427            "inv_button1",
428            "inv_button2",
429            "inv_button3",
430            "inv_button4",
431            "inv_button5",
432            "inv_buttond",
433        ];
434        for name in expected {
435            assert!(is_button(name), "{} should be a button trigger", name);
436        }
437        // Spot-check that non-buttons aren't flagged.
438        assert!(!is_button("if_close"));
439        assert!(!is_button("opnpc1"));
440        assert!(!is_button("login"));
441    }
442
443    #[test]
444    fn known_byte_values() {
445        // Anchors against the RuneScriptTS ServerTriggerType.ts byte
446        // discriminants. If any of these change, the engine's dispatch
447        // will silently desync.
448        assert_eq!(byte("opnpc1"), Some(10));
449        assert_eq!(byte("opheld1"), Some(140));
450        assert_eq!(byte("if_button"), Some(147));
451        assert_eq!(byte("if_button1"), Some(149));
452        assert_eq!(byte("inv_button1"), Some(149));
453        assert_eq!(byte("login"), Some(157));
454        assert_eq!(byte("ai_despawn"), Some(167));
455        assert_eq!(byte("totally_unknown_trigger"), None);
456    }
457
458    #[test]
459    fn subject_type_routing() {
460        assert_eq!(subject_type("opnpc1"), Some(Type::Npc));
461        assert_eq!(subject_type("opobj1"), Some(Type::Obj));
462        assert_eq!(subject_type("oploc1"), Some(Type::Loc));
463        assert_eq!(subject_type("opheld1"), Some(Type::Obj));
464        assert_eq!(subject_type("if_button"), Some(Type::Interface));
465        assert_eq!(subject_type("inv_button1"), Some(Type::Component));
466        assert_eq!(subject_type("login"), None);
467        assert_eq!(subject_type("opplayer1"), None); // flat lookup
468        // advancestat/changestat take a stat subject. Without this routing,
469        // `[advancestat,ranged]` flat-resolves `ranged` to whatever type was
470        // registered last under that name (e.g. a hunt) instead of the stat.
471        assert_eq!(subject_type("advancestat"), Some(Type::Stat));
472        assert_eq!(subject_type("changestat"), Some(Type::Stat));
473    }
474
475    /// Every npc AI trigger's subject is the acting npc, whatever it targets
476    /// (RuneScriptTS: SubjectMode.Type(NPC); the engine keys them by npc type).
477    #[test]
478    fn npc_ai_triggers_take_an_npc_subject() {
479        let mut names: Vec<String> = Vec::new();
480        for target in ["player", "loc", "obj", "npc"] {
481            for op in ["ap", "op"] {
482                for i in 1..=5 {
483                    names.push(format!("ai_{op}{target}{i}"));
484                }
485            }
486        }
487        for i in 1..=20 {
488            names.push(format!("ai_queue{i}"));
489        }
490        names.extend(["ai_timer", "ai_spawn", "ai_despawn"].map(String::from));
491        for name in &names {
492            assert_eq!(subject_type(name), Some(Type::Npc), "{name}");
493        }
494    }
495
496    #[test]
497    fn validation_skip_list() {
498        // Triggers historically excluded from subject validation.
499        assert!(!validates_subject("login"));
500        assert!(!validates_subject("logout"));
501        assert!(!validates_subject("zone"));
502        assert!(!validates_subject("zoneexit"));
503        assert!(!validates_subject("mapzone"));
504        assert!(!validates_subject("mapzoneexit"));
505        assert!(!validates_subject("ai_queue1"));
506        assert!(!validates_subject("ai_timer"));
507        // …but the rest of the byte-keyed triggers do validate.
508        assert!(validates_subject("if_button"));
509        assert!(validates_subject("opnpc1"));
510        assert!(validates_subject("opheld1"));
511        assert!(validates_subject("tutorial"));
512    }
513
514    #[test]
515    fn is_valid_trigger_byte_keyed() {
516        assert!(is_valid_trigger("opnpc1"));
517        assert!(is_valid_trigger("opheld1"));
518        assert!(is_valid_trigger("if_button"));
519        assert!(is_valid_trigger("login"));
520        assert!(is_valid_trigger("ai_queue1"));
521        assert!(is_valid_trigger("ai_despawn"));
522    }
523
524    #[test]
525    fn is_valid_trigger_name_keyed() {
526        assert!(is_valid_trigger("proc"));
527        assert!(is_valid_trigger("label"));
528        assert!(is_valid_trigger("debugproc"));
529        assert!(is_valid_trigger("command"));
530        assert!(is_valid_trigger("clientscript"));
531        assert!(is_valid_trigger("walktrigger"));
532        assert!(is_valid_trigger("queue"));
533        assert!(is_valid_trigger("timer"));
534        assert!(is_valid_trigger("softtimer"));
535    }
536
537    #[test]
538    fn is_valid_trigger_extended() {
539        assert!(is_valid_trigger("switch_window_mode"));
540    }
541
542    #[test]
543    fn opheld_only_goes_to_five() {
544        // Rev-647 (and OSRS) have no opheld beyond 5. Inventory item ops 6-10
545        // route through if_button6-10 + the p_opheld content command instead.
546        assert!(is_valid_trigger("opheld5"));
547        assert!(!is_valid_trigger("opheld6"));
548        assert!(!is_valid_trigger("opheld7"));
549        assert!(!is_valid_trigger("opheld10"));
550    }
551
552    #[test]
553    fn if_button_extended_to_ten() {
554        // Bytes 173-177 must stay in sync with the engine's ServerTriggerType
555        // InvButton6-10.
556        assert!(is_valid_trigger("if_button6"));
557        assert!(is_valid_trigger("if_button10"));
558        assert_eq!(byte("if_button6"), Some(173));
559        assert_eq!(byte("if_button10"), Some(177));
560    }
561
562    #[test]
563    fn inv_button_caps_at_five() {
564        // inv_button is the 225-era spelling with ops 1-5 (+ d). 647 content
565        // uses if_button, which extends to 6-10. Both 225 and 647 content
566        // compile here, so inv_button1-5/inv_buttond stay valid while
567        // inv_button6-10 must not exist.
568        for n in ["inv_button1", "inv_button5", "inv_buttond"] {
569            assert!(is_valid_trigger(n), "{n} should still be a trigger");
570        }
571        for n in ["inv_button6", "inv_button7", "inv_button10"] {
572            assert!(
573                !is_valid_trigger(n),
574                "{n} must not exist (inv_button caps at 5)"
575            );
576            assert_eq!(byte(n), None);
577        }
578    }
579
580    #[test]
581    fn is_valid_trigger_unknown_rejected() {
582        assert!(!is_valid_trigger("not_a_real_trigger"));
583        assert!(!is_valid_trigger(""));
584        assert!(!is_valid_trigger("procc"));
585    }
586
587    #[test]
588    fn allows_returns_matches_lib_set() {
589        assert!(allows_returns("proc"));
590        assert!(allows_returns("clientscript"));
591        assert!(allows_returns("command"));
592        assert!(allows_returns("logout"));
593        assert!(!allows_returns("label"));
594        assert!(!allows_returns("debugproc"));
595        assert!(!allows_returns("queue"));
596        assert!(!allows_returns("timer"));
597        assert!(!allows_returns("softtimer"));
598        assert!(!allows_returns("walktrigger"));
599        assert!(!allows_returns("login"));
600        assert!(!allows_returns("opnpc1"));
601    }
602
603    #[test]
604    fn name_keyed_triggers_have_no_byte() {
605        assert_eq!(byte("proc"), None);
606        assert_eq!(byte("label"), None);
607        assert_eq!(byte("command"), None);
608        assert_eq!(byte("walktrigger"), None);
609    }
610}