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 names() -> impl Iterator<Item = &'static str> {
352    TRIGGERS
353        .iter()
354        .map(|trigger| trigger.name)
355        .chain(NAME_KEYED_TRIGGERS.iter().copied())
356        .chain(EXTENDED_TRIGGERS.iter().copied())
357}
358
359pub fn byte(name: &str) -> Option<u8> {
360    lookup(name).map(|t| t.byte)
361}
362
363pub fn subject_type(name: &str) -> Option<Type> {
364    lookup(name).and_then(|t| t.subject_type)
365}
366
367pub fn validates_subject(name: &str) -> bool {
368    lookup(name).map(|t| t.validates_subject).unwrap_or(false)
369}
370
371pub fn is_button(name: &str) -> bool {
372    lookup(name).map(|t| t.is_button).unwrap_or(false)
373}
374
375pub fn is_valid_trigger(name: &str) -> bool {
376    lookup(name).is_some()
377        || NAME_KEYED_TRIGGERS.contains(&name)
378        || EXTENDED_TRIGGERS.contains(&name)
379}
380
381pub fn allows_returns(name: &str) -> bool {
382    matches!(name, "proc" | "clientscript" | "command" | "logout")
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388
389    #[test]
390    fn no_duplicate_trigger_names() {
391        let mut seen = std::collections::HashSet::new();
392        for t in TRIGGERS {
393            assert!(seen.insert(t.name), "duplicate trigger name: {}", t.name);
394        }
395    }
396
397    #[test]
398    fn button_triggers_match_legacy_set() {
399        // Locks in pointer_checker's old hand-maintained list.
400        let expected = [
401            "if_button",
402            "if_button1",
403            "if_button2",
404            "if_button3",
405            "if_button4",
406            "if_button5",
407            "if_button6",
408            "if_button7",
409            "if_button8",
410            "if_button9",
411            "if_button10",
412            "if_buttond",
413            "inv_button1",
414            "inv_button2",
415            "inv_button3",
416            "inv_button4",
417            "inv_button5",
418            "inv_buttond",
419        ];
420        for name in expected {
421            assert!(is_button(name), "{} should be a button trigger", name);
422        }
423        // Spot-check that non-buttons aren't flagged.
424        assert!(!is_button("if_close"));
425        assert!(!is_button("opnpc1"));
426        assert!(!is_button("login"));
427    }
428
429    #[test]
430    fn known_byte_values() {
431        // Anchors against the RuneScriptTS ServerTriggerType.ts byte
432        // discriminants. If any of these change, the engine's dispatch
433        // will silently desync.
434        assert_eq!(byte("opnpc1"), Some(10));
435        assert_eq!(byte("opheld1"), Some(140));
436        assert_eq!(byte("if_button"), Some(147));
437        assert_eq!(byte("if_button1"), Some(149));
438        assert_eq!(byte("inv_button1"), Some(149));
439        assert_eq!(byte("login"), Some(157));
440        assert_eq!(byte("ai_despawn"), Some(167));
441        assert_eq!(byte("totally_unknown_trigger"), None);
442    }
443
444    #[test]
445    fn subject_type_routing() {
446        assert_eq!(subject_type("opnpc1"), Some(Type::Npc));
447        assert_eq!(subject_type("opobj1"), Some(Type::Obj));
448        assert_eq!(subject_type("oploc1"), Some(Type::Loc));
449        assert_eq!(subject_type("opheld1"), Some(Type::Obj));
450        assert_eq!(subject_type("if_button"), Some(Type::Interface));
451        assert_eq!(subject_type("inv_button1"), Some(Type::Component));
452        assert_eq!(subject_type("login"), None);
453        assert_eq!(subject_type("opplayer1"), None); // flat lookup
454        // advancestat/changestat take a stat subject. Without this routing,
455        // `[advancestat,ranged]` flat-resolves `ranged` to whatever type was
456        // registered last under that name (e.g. a hunt) instead of the stat.
457        assert_eq!(subject_type("advancestat"), Some(Type::Stat));
458        assert_eq!(subject_type("changestat"), Some(Type::Stat));
459    }
460
461    /// Every npc AI trigger's subject is the acting npc, whatever it targets
462    /// (RuneScriptTS: SubjectMode.Type(NPC); the engine keys them by npc type).
463    #[test]
464    fn npc_ai_triggers_take_an_npc_subject() {
465        let mut names: Vec<String> = Vec::new();
466        for target in ["player", "loc", "obj", "npc"] {
467            for op in ["ap", "op"] {
468                for i in 1..=5 {
469                    names.push(format!("ai_{op}{target}{i}"));
470                }
471            }
472        }
473        for i in 1..=20 {
474            names.push(format!("ai_queue{i}"));
475        }
476        names.extend(["ai_timer", "ai_spawn", "ai_despawn"].map(String::from));
477        for name in &names {
478            assert_eq!(subject_type(name), Some(Type::Npc), "{name}");
479        }
480    }
481
482    #[test]
483    fn validation_skip_list() {
484        // Triggers historically excluded from subject validation.
485        assert!(!validates_subject("login"));
486        assert!(!validates_subject("logout"));
487        assert!(!validates_subject("zone"));
488        assert!(!validates_subject("zoneexit"));
489        assert!(!validates_subject("mapzone"));
490        assert!(!validates_subject("mapzoneexit"));
491        assert!(!validates_subject("ai_queue1"));
492        assert!(!validates_subject("ai_timer"));
493        // …but the rest of the byte-keyed triggers do validate.
494        assert!(validates_subject("if_button"));
495        assert!(validates_subject("opnpc1"));
496        assert!(validates_subject("opheld1"));
497        assert!(validates_subject("tutorial"));
498    }
499
500    #[test]
501    fn is_valid_trigger_byte_keyed() {
502        assert!(is_valid_trigger("opnpc1"));
503        assert!(is_valid_trigger("opheld1"));
504        assert!(is_valid_trigger("if_button"));
505        assert!(is_valid_trigger("login"));
506        assert!(is_valid_trigger("ai_queue1"));
507        assert!(is_valid_trigger("ai_despawn"));
508    }
509
510    #[test]
511    fn is_valid_trigger_name_keyed() {
512        assert!(is_valid_trigger("proc"));
513        assert!(is_valid_trigger("label"));
514        assert!(is_valid_trigger("debugproc"));
515        assert!(is_valid_trigger("command"));
516        assert!(is_valid_trigger("clientscript"));
517        assert!(is_valid_trigger("walktrigger"));
518        assert!(is_valid_trigger("queue"));
519        assert!(is_valid_trigger("timer"));
520        assert!(is_valid_trigger("softtimer"));
521    }
522
523    #[test]
524    fn is_valid_trigger_extended() {
525        assert!(is_valid_trigger("switch_window_mode"));
526    }
527
528    #[test]
529    fn opheld_only_goes_to_five() {
530        // Rev-647 (and OSRS) have no opheld beyond 5. Inventory item ops 6-10
531        // route through if_button6-10 + the p_opheld content command instead.
532        assert!(is_valid_trigger("opheld5"));
533        assert!(!is_valid_trigger("opheld6"));
534        assert!(!is_valid_trigger("opheld7"));
535        assert!(!is_valid_trigger("opheld10"));
536    }
537
538    #[test]
539    fn if_button_extended_to_ten() {
540        // Bytes 173-177 must stay in sync with the engine's ServerTriggerType
541        // InvButton6-10.
542        assert!(is_valid_trigger("if_button6"));
543        assert!(is_valid_trigger("if_button10"));
544        assert_eq!(byte("if_button6"), Some(173));
545        assert_eq!(byte("if_button10"), Some(177));
546    }
547
548    #[test]
549    fn inv_button_caps_at_five() {
550        // inv_button is the 225-era spelling with ops 1-5 (+ d). 647 content
551        // uses if_button, which extends to 6-10. Both 225 and 647 content
552        // compile here, so inv_button1-5/inv_buttond stay valid while
553        // inv_button6-10 must not exist.
554        for n in ["inv_button1", "inv_button5", "inv_buttond"] {
555            assert!(is_valid_trigger(n), "{n} should still be a trigger");
556        }
557        for n in ["inv_button6", "inv_button7", "inv_button10"] {
558            assert!(
559                !is_valid_trigger(n),
560                "{n} must not exist (inv_button caps at 5)"
561            );
562            assert_eq!(byte(n), None);
563        }
564    }
565
566    #[test]
567    fn is_valid_trigger_unknown_rejected() {
568        assert!(!is_valid_trigger("not_a_real_trigger"));
569        assert!(!is_valid_trigger(""));
570        assert!(!is_valid_trigger("procc"));
571    }
572
573    #[test]
574    fn allows_returns_matches_lib_set() {
575        assert!(allows_returns("proc"));
576        assert!(allows_returns("clientscript"));
577        assert!(allows_returns("command"));
578        assert!(allows_returns("logout"));
579        assert!(!allows_returns("label"));
580        assert!(!allows_returns("debugproc"));
581        assert!(!allows_returns("queue"));
582        assert!(!allows_returns("timer"));
583        assert!(!allows_returns("softtimer"));
584        assert!(!allows_returns("walktrigger"));
585        assert!(!allows_returns("login"));
586        assert!(!allows_returns("opnpc1"));
587    }
588
589    #[test]
590    fn name_keyed_triggers_have_no_byte() {
591        assert_eq!(byte("proc"), None);
592        assert_eq!(byte("label"), None);
593        assert_eq!(byte("command"), None);
594        assert_eq!(byte("walktrigger"), None);
595    }
596}