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];
220
221// ── Constructor helpers ──────────────────────────────────────────────
222//
223// `const fn` so the static slice above stays trivially constructible.
224
225const fn npc(name: &'static str, byte: u8) -> TriggerInfo {
226    TriggerInfo {
227        name,
228        byte,
229        subject_type: Some(Type::Npc),
230        validates_subject: true,
231        is_button: false,
232    }
233}
234
235const fn npc_no_validate(name: &'static str, byte: u8) -> TriggerInfo {
236    TriggerInfo {
237        name,
238        byte,
239        subject_type: Some(Type::Npc),
240        validates_subject: false,
241        is_button: false,
242    }
243}
244
245const fn obj(name: &'static str, byte: u8) -> TriggerInfo {
246    TriggerInfo {
247        name,
248        byte,
249        subject_type: Some(Type::Obj),
250        validates_subject: true,
251        is_button: false,
252    }
253}
254
255const fn loc(name: &'static str, byte: u8) -> TriggerInfo {
256    TriggerInfo {
257        name,
258        byte,
259        subject_type: Some(Type::Loc),
260        validates_subject: true,
261        is_button: false,
262    }
263}
264
265const fn iface(name: &'static str, byte: u8, is_button: bool) -> TriggerInfo {
266    TriggerInfo {
267        name,
268        byte,
269        subject_type: Some(Type::Interface),
270        validates_subject: true,
271        is_button,
272    }
273}
274
275const fn component(name: &'static str, byte: u8) -> TriggerInfo {
276    TriggerInfo {
277        name,
278        byte,
279        subject_type: Some(Type::Component),
280        validates_subject: true,
281        is_button: true,
282    }
283}
284
285/// `[advancestat,stat]` / `[changestat,stat]` — subject is a player stat.
286/// Routes to `Type::Stat` so the subject resolves via the typed map instead
287/// of the flat entity-id map, where a same-named entity of another type
288/// (e.g. a `hunt` called `ranged`) would otherwise shadow the stat.
289const fn stat(name: &'static str, byte: u8) -> TriggerInfo {
290    TriggerInfo {
291        name,
292        byte,
293        subject_type: Some(Type::Stat),
294        validates_subject: true,
295        is_button: false,
296    }
297}
298
299const fn flat(name: &'static str, byte: u8) -> TriggerInfo {
300    TriggerInfo {
301        name,
302        byte,
303        subject_type: None,
304        validates_subject: true,
305        is_button: false,
306    }
307}
308
309const fn flat_no_validate(name: &'static str, byte: u8) -> TriggerInfo {
310    TriggerInfo {
311        name,
312        byte,
313        subject_type: None,
314        validates_subject: false,
315        is_button: false,
316    }
317}
318
319// ── Name-keyed triggers ─────────────────────────────────────────────
320//
321// Triggers dispatched by script name (no byte discriminant). These are
322// valid trigger keywords but don't participate in lookup-key hashing.
323
324const NAME_KEYED_TRIGGERS: &[&str] = &[
325    "proc",
326    "label",
327    "debugproc",
328    "command",
329    "clientscript",
330    "walktrigger",
331    "queue",
332    "timer",
333    "softtimer",
334];
335
336// Rev-647 extensions: valid triggers whose byte discriminants are not
337// yet standardized in the reference implementation.
338const EXTENDED_TRIGGERS: &[&str] = &["switch_window_mode"];
339
340// ── Public lookup API ────────────────────────────────────────────────
341
342fn table() -> &'static HashMap<&'static str, TriggerInfo> {
343    static TABLE: OnceLock<HashMap<&'static str, TriggerInfo>> = OnceLock::new();
344    TABLE.get_or_init(|| TRIGGERS.iter().map(|t| (t.name, *t)).collect())
345}
346
347pub fn lookup(name: &str) -> Option<TriggerInfo> {
348    table().get(name).copied()
349}
350
351pub fn byte(name: &str) -> Option<u8> {
352    lookup(name).map(|t| t.byte)
353}
354
355pub fn subject_type(name: &str) -> Option<Type> {
356    lookup(name).and_then(|t| t.subject_type)
357}
358
359pub fn validates_subject(name: &str) -> bool {
360    lookup(name).map(|t| t.validates_subject).unwrap_or(false)
361}
362
363pub fn is_button(name: &str) -> bool {
364    lookup(name).map(|t| t.is_button).unwrap_or(false)
365}
366
367pub fn is_valid_trigger(name: &str) -> bool {
368    lookup(name).is_some()
369        || NAME_KEYED_TRIGGERS.contains(&name)
370        || EXTENDED_TRIGGERS.contains(&name)
371}
372
373pub fn allows_returns(name: &str) -> bool {
374    matches!(name, "proc" | "clientscript" | "command" | "logout")
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    #[test]
382    fn no_duplicate_trigger_names() {
383        let mut seen = std::collections::HashSet::new();
384        for t in TRIGGERS {
385            assert!(seen.insert(t.name), "duplicate trigger name: {}", t.name);
386        }
387    }
388
389    #[test]
390    fn button_triggers_match_legacy_set() {
391        // Locks in pointer_checker's old hand-maintained list.
392        let expected = [
393            "if_button",
394            "if_button1",
395            "if_button2",
396            "if_button3",
397            "if_button4",
398            "if_button5",
399            "if_button6",
400            "if_button7",
401            "if_button8",
402            "if_button9",
403            "if_button10",
404            "if_buttond",
405            "inv_button1",
406            "inv_button2",
407            "inv_button3",
408            "inv_button4",
409            "inv_button5",
410            "inv_buttond",
411        ];
412        for name in expected {
413            assert!(is_button(name), "{} should be a button trigger", name);
414        }
415        // Spot-check that non-buttons aren't flagged.
416        assert!(!is_button("if_close"));
417        assert!(!is_button("opnpc1"));
418        assert!(!is_button("login"));
419    }
420
421    #[test]
422    fn known_byte_values() {
423        // Anchors against the RuneScriptTS ServerTriggerType.ts byte
424        // discriminants. If any of these change, the engine's dispatch
425        // will silently desync.
426        assert_eq!(byte("opnpc1"), Some(10));
427        assert_eq!(byte("opheld1"), Some(140));
428        assert_eq!(byte("if_button"), Some(147));
429        assert_eq!(byte("if_button1"), Some(149));
430        assert_eq!(byte("inv_button1"), Some(149));
431        assert_eq!(byte("login"), Some(157));
432        assert_eq!(byte("ai_despawn"), Some(167));
433        assert_eq!(byte("totally_unknown_trigger"), None);
434    }
435
436    #[test]
437    fn subject_type_routing() {
438        assert_eq!(subject_type("opnpc1"), Some(Type::Npc));
439        assert_eq!(subject_type("opobj1"), Some(Type::Obj));
440        assert_eq!(subject_type("oploc1"), Some(Type::Loc));
441        assert_eq!(subject_type("opheld1"), Some(Type::Obj));
442        assert_eq!(subject_type("if_button"), Some(Type::Interface));
443        assert_eq!(subject_type("inv_button1"), Some(Type::Component));
444        assert_eq!(subject_type("login"), None);
445        assert_eq!(subject_type("opplayer1"), None); // flat lookup
446        // advancestat/changestat take a stat subject. Without this routing,
447        // `[advancestat,ranged]` flat-resolves `ranged` to whatever type was
448        // registered last under that name (e.g. a hunt) instead of the stat.
449        assert_eq!(subject_type("advancestat"), Some(Type::Stat));
450        assert_eq!(subject_type("changestat"), Some(Type::Stat));
451    }
452
453    /// Every npc AI trigger's subject is the acting npc, whatever it targets
454    /// (RuneScriptTS: SubjectMode.Type(NPC); the engine keys them by npc type).
455    #[test]
456    fn npc_ai_triggers_take_an_npc_subject() {
457        let mut names: Vec<String> = Vec::new();
458        for target in ["player", "loc", "obj", "npc"] {
459            for op in ["ap", "op"] {
460                for i in 1..=5 {
461                    names.push(format!("ai_{op}{target}{i}"));
462                }
463            }
464        }
465        for i in 1..=20 {
466            names.push(format!("ai_queue{i}"));
467        }
468        names.extend(["ai_timer", "ai_spawn", "ai_despawn"].map(String::from));
469        for name in &names {
470            assert_eq!(subject_type(name), Some(Type::Npc), "{name}");
471        }
472    }
473
474    #[test]
475    fn validation_skip_list() {
476        // Triggers historically excluded from subject validation.
477        assert!(!validates_subject("login"));
478        assert!(!validates_subject("logout"));
479        assert!(!validates_subject("zone"));
480        assert!(!validates_subject("zoneexit"));
481        assert!(!validates_subject("mapzone"));
482        assert!(!validates_subject("mapzoneexit"));
483        assert!(!validates_subject("ai_queue1"));
484        assert!(!validates_subject("ai_timer"));
485        // …but the rest of the byte-keyed triggers do validate.
486        assert!(validates_subject("if_button"));
487        assert!(validates_subject("opnpc1"));
488        assert!(validates_subject("opheld1"));
489        assert!(validates_subject("tutorial"));
490    }
491
492    #[test]
493    fn is_valid_trigger_byte_keyed() {
494        assert!(is_valid_trigger("opnpc1"));
495        assert!(is_valid_trigger("opheld1"));
496        assert!(is_valid_trigger("if_button"));
497        assert!(is_valid_trigger("login"));
498        assert!(is_valid_trigger("ai_queue1"));
499        assert!(is_valid_trigger("ai_despawn"));
500    }
501
502    #[test]
503    fn is_valid_trigger_name_keyed() {
504        assert!(is_valid_trigger("proc"));
505        assert!(is_valid_trigger("label"));
506        assert!(is_valid_trigger("debugproc"));
507        assert!(is_valid_trigger("command"));
508        assert!(is_valid_trigger("clientscript"));
509        assert!(is_valid_trigger("walktrigger"));
510        assert!(is_valid_trigger("queue"));
511        assert!(is_valid_trigger("timer"));
512        assert!(is_valid_trigger("softtimer"));
513    }
514
515    #[test]
516    fn is_valid_trigger_extended() {
517        assert!(is_valid_trigger("switch_window_mode"));
518    }
519
520    #[test]
521    fn opheld_only_goes_to_five() {
522        // Rev-647 (and OSRS) have no opheld beyond 5. Inventory item ops 6-10
523        // route through if_button6-10 + the p_opheld content command instead.
524        assert!(is_valid_trigger("opheld5"));
525        assert!(!is_valid_trigger("opheld6"));
526        assert!(!is_valid_trigger("opheld7"));
527        assert!(!is_valid_trigger("opheld10"));
528    }
529
530    #[test]
531    fn if_button_extended_to_ten() {
532        // Bytes 173-177 must stay in sync with the engine's ServerTriggerType
533        // InvButton6-10.
534        assert!(is_valid_trigger("if_button6"));
535        assert!(is_valid_trigger("if_button10"));
536        assert_eq!(byte("if_button6"), Some(173));
537        assert_eq!(byte("if_button10"), Some(177));
538    }
539
540    #[test]
541    fn inv_button_caps_at_five() {
542        // inv_button is the 225-era spelling with ops 1-5 (+ d). 647 content
543        // uses if_button, which extends to 6-10. Both 225 and 647 content
544        // compile here, so inv_button1-5/inv_buttond stay valid while
545        // inv_button6-10 must not exist.
546        for n in ["inv_button1", "inv_button5", "inv_buttond"] {
547            assert!(is_valid_trigger(n), "{n} should still be a trigger");
548        }
549        for n in ["inv_button6", "inv_button7", "inv_button10"] {
550            assert!(
551                !is_valid_trigger(n),
552                "{n} must not exist (inv_button caps at 5)"
553            );
554            assert_eq!(byte(n), None);
555        }
556    }
557
558    #[test]
559    fn is_valid_trigger_unknown_rejected() {
560        assert!(!is_valid_trigger("not_a_real_trigger"));
561        assert!(!is_valid_trigger(""));
562        assert!(!is_valid_trigger("procc"));
563    }
564
565    #[test]
566    fn allows_returns_matches_lib_set() {
567        assert!(allows_returns("proc"));
568        assert!(allows_returns("clientscript"));
569        assert!(allows_returns("command"));
570        assert!(allows_returns("logout"));
571        assert!(!allows_returns("label"));
572        assert!(!allows_returns("debugproc"));
573        assert!(!allows_returns("queue"));
574        assert!(!allows_returns("timer"));
575        assert!(!allows_returns("softtimer"));
576        assert!(!allows_returns("walktrigger"));
577        assert!(!allows_returns("login"));
578        assert!(!allows_returns("opnpc1"));
579    }
580
581    #[test]
582    fn name_keyed_triggers_have_no_byte() {
583        assert_eq!(byte("proc"), None);
584        assert_eq!(byte("label"), None);
585        assert_eq!(byte("command"), None);
586        assert_eq!(byte("walktrigger"), None);
587    }
588}