nmarshall commited on
Commit
3a736df
·
1 Parent(s): 3fe958b

gameplay: compose allocated defuse callback

Browse files
crates/urt-gameplay/src/bin/support/entity_pool.rs ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use urt_gameplay::location_feedback::{AllocationOutcome, EntityPool, EntitySlot};
2
+
3
+ fn list(v: &[u32]) -> String {
4
+ format!(
5
+ "[{}]",
6
+ v.iter()
7
+ .map(|v| v.to_string())
8
+ .collect::<Vec<_>>()
9
+ .join(",")
10
+ )
11
+ }
12
+ fn optional(v: Option<usize>) -> String {
13
+ v.map(|v| v.to_string()).unwrap_or("null".into())
14
+ }
15
+ pub fn decode_pool(w: &[u32]) -> (EntityPool, u32, u32) {
16
+ assert!(w.len() >= 4);
17
+ let mut p = EntityPool {
18
+ count: w[0],
19
+ slots: vec![
20
+ EntitySlot {
21
+ words: [0x12345678; 220]
22
+ };
23
+ 1024
24
+ ],
25
+ };
26
+ for j in 64..(w[0] as usize).max(65) {
27
+ p.slots[j].words[532 / 4] = 1;
28
+ p.slots[j].words[564 / 4] = 0;
29
+ }
30
+ assert_eq!(w.len(), 4 + 3 * w[3] as usize);
31
+ for s in w[4..].chunks_exact(3) {
32
+ p.slots[s[0] as usize].words[532 / 4] = s[1];
33
+ p.slots[s[0] as usize].words[564 / 4] = s[2];
34
+ }
35
+ (p, w[1], w[2])
36
+ }
37
+ pub fn record(words: &[u32], fields: &[usize]) -> String {
38
+ format!(
39
+ "{{{}}}",
40
+ fields
41
+ .iter()
42
+ .map(|o| format!("\"{o}\":{}", words[o / 4]))
43
+ .collect::<Vec<_>>()
44
+ .join(",")
45
+ )
46
+ }
47
+ pub fn allocation_fields(pool: &EntityPool, o: &AllocationOutcome) -> String {
48
+ let fields = [0, 512, 532, 536, 540, 564, 424, 84, 140];
49
+ let r = o
50
+ .selected
51
+ .map(|i| record(&pool.slots[i].words, &fields))
52
+ .unwrap_or("null".into());
53
+ format!(
54
+ r#""selected":{},"count":{},"retry":{},"scan_index":{},"status":"{}","registrations":{},"record":{}"#,
55
+ optional(o.selected),
56
+ o.count,
57
+ o.retry,
58
+ o.scan_index,
59
+ o.status,
60
+ list(&o.registrations),
61
+ r
62
+ )
63
+ }
crates/urt-gameplay/src/bin/urt-defuse.rs CHANGED
@@ -1,4 +1,9 @@
 
 
 
 
1
  use urt_gameplay::defuse::*;
 
2
  fn list(v: &[u32]) -> String {
3
  format!(
4
  "[{}]",
@@ -50,9 +55,11 @@ fn decode(w: &[u32]) -> (DefuseState, DefuseInput) {
50
  },
51
  )
52
  }
53
- fn fields(s: DefuseState, e: &[DefuseEffect]) -> String {
 
 
54
  format!(
55
- r#""flags":{},"flags104":{},"busy":{},"clock":{},"complete":{},"animation":{},"weapon":{},"event":{},"guards":[2864434397,287454020],"events":[{}]"#,
56
  s.flags,
57
  s.flags104,
58
  s.busy,
@@ -61,6 +68,7 @@ fn fields(s: DefuseState, e: &[DefuseEffect]) -> String {
61
  s.animation,
62
  s.weapon,
63
  list(&s.event),
 
64
  events(e)
65
  )
66
  }
@@ -72,19 +80,20 @@ fn main() {
72
  "begin" => {
73
  let (mut s, i) = decode(&w);
74
  let e = begin_defuse(&mut s, i).unwrap();
75
- println!("{{{}}}", fields(s, &e));
76
  }
77
  "cancel" => {
78
  let (mut s, i) = decode(&w);
79
  let e = cancel_defuse(&mut s, i).unwrap();
80
- println!("{{{}}}", fields(s, &e));
81
  }
82
  "finish" => {
83
  let (mut s, i) = decode(&w);
84
  let e = finish_defuse(&mut s, i).unwrap();
85
- println!("{{{}}}", fields(s, &e));
86
  }
87
  "full" => println!("{}", full(&w)),
 
88
  "sequence" => println!("{}", sequence(&w)),
89
  _ => panic!("unknown policy"),
90
  }
@@ -163,10 +172,10 @@ fn decode_full(w: &[u32]) -> (DefuseWorld, FullDefuseInput) {
163
  },
164
  )
165
  }
166
- fn full_fields(s: DefuseState, o: &DefuseOutcome) -> String {
167
  format!(
168
  r#"{},"lookups":[{}],"distances":{},"missing":{}"#,
169
- fields(s, &o.effects),
170
  o.lookups
171
  .iter()
172
  .map(|v| v.map(|i| i.to_string()).unwrap_or("null".into()))
@@ -179,7 +188,7 @@ fn full_fields(s: DefuseState, o: &DefuseOutcome) -> String {
179
  fn full(w: &[u32]) -> String {
180
  let (mut world, i) = decode_full(w);
181
  let o = process_defuse(&mut world, i).unwrap();
182
- format!("{{{}}}", full_fields(world.state, &o))
183
  }
184
 
185
  fn sequence(w: &[u32]) -> String {
@@ -209,8 +218,51 @@ fn sequence(w: &[u32]) -> String {
209
  r#"{{"frames":[{}]}}"#,
210
  frames
211
  .iter()
212
- .map(|f| format!("{{{}}}", full_fields(f.world.state, &f.outcome)))
 
 
 
213
  .collect::<Vec<_>>()
214
  .join(",")
215
  )
216
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #[path = "support/entity_pool.rs"]
2
+ mod entity_pool;
3
+
4
+ use entity_pool::{allocation_fields, decode_pool, record};
5
  use urt_gameplay::defuse::*;
6
+ use urt_gameplay::location_feedback::process_allocated_defuse;
7
  fn list(v: &[u32]) -> String {
8
  format!(
9
  "[{}]",
 
55
  },
56
  )
57
  }
58
+ const FIXTURE_GUARDS: [u32; 2] = [0xaabbccdd, 0x11223344];
59
+
60
+ fn fields(s: DefuseState, e: &[DefuseEffect], guards: [u32; 2]) -> String {
61
  format!(
62
+ r#""flags":{},"flags104":{},"busy":{},"clock":{},"complete":{},"animation":{},"weapon":{},"event":{},"guards":{},"events":[{}]"#,
63
  s.flags,
64
  s.flags104,
65
  s.busy,
 
68
  s.animation,
69
  s.weapon,
70
  list(&s.event),
71
+ list(&guards),
72
  events(e)
73
  )
74
  }
 
80
  "begin" => {
81
  let (mut s, i) = decode(&w);
82
  let e = begin_defuse(&mut s, i).unwrap();
83
+ println!("{{{}}}", fields(s, &e, FIXTURE_GUARDS));
84
  }
85
  "cancel" => {
86
  let (mut s, i) = decode(&w);
87
  let e = cancel_defuse(&mut s, i).unwrap();
88
+ println!("{{{}}}", fields(s, &e, FIXTURE_GUARDS));
89
  }
90
  "finish" => {
91
  let (mut s, i) = decode(&w);
92
  let e = finish_defuse(&mut s, i).unwrap();
93
+ println!("{{{}}}", fields(s, &e, FIXTURE_GUARDS));
94
  }
95
  "full" => println!("{}", full(&w)),
96
+ "allocated-full" => println!("{}", allocated_full(&w)),
97
  "sequence" => println!("{}", sequence(&w)),
98
  _ => panic!("unknown policy"),
99
  }
 
172
  },
173
  )
174
  }
175
+ fn full_fields(s: DefuseState, o: &DefuseOutcome, guards: [u32; 2]) -> String {
176
  format!(
177
  r#"{},"lookups":[{}],"distances":{},"missing":{}"#,
178
+ fields(s, &o.effects, guards),
179
  o.lookups
180
  .iter()
181
  .map(|v| v.map(|i| i.to_string()).unwrap_or("null".into()))
 
188
  fn full(w: &[u32]) -> String {
189
  let (mut world, i) = decode_full(w);
190
  let o = process_defuse(&mut world, i).unwrap();
191
+ format!("{{{}}}", full_fields(world.state, &o, FIXTURE_GUARDS))
192
  }
193
 
194
  fn sequence(w: &[u32]) -> String {
 
218
  r#"{{"frames":[{}]}}"#,
219
  frames
220
  .iter()
221
+ .map(|f| format!(
222
+ "{{{}}}",
223
+ full_fields(f.world.state, &f.outcome, FIXTURE_GUARDS)
224
+ ))
225
  .collect::<Vec<_>>()
226
  .join(",")
227
  )
228
  }
229
+
230
+ fn allocated_full(w: &[u32]) -> String {
231
+ let (mut world, input) = decode_full(&w[..31]);
232
+ let (mut pool, _, start) = decode_pool(&w[32..]);
233
+ for index in [64, 65, 66] {
234
+ pool.slots[index].words[424 / 4] = w[31];
235
+ }
236
+ let (mut routing, allocated) =
237
+ process_allocated_defuse(&mut world, &mut pool, input, start).unwrap();
238
+ let Some(allocated) = allocated else {
239
+ return format!(
240
+ r#"{{{},"allocation":null,"record":null,"links":[]}}"#,
241
+ full_fields(world.state, &routing, FIXTURE_GUARDS)
242
+ );
243
+ };
244
+ let link = allocated.link.unwrap();
245
+ let slot = link.slot;
246
+ let final_record = &pool.slots[slot].words;
247
+ let fields = [
248
+ 0, 4, 12, 16, 20, 24, 28, 32, 36, 40, 44, 84, 140, 180, 184, 188, 400, 424, 488, 492, 496,
249
+ 512, 532, 536, 540, 564, 568, 572,
250
+ ];
251
+ routing.effects = allocated.before_allocation;
252
+ routing.effects.push(DefuseEffect::Allocate {
253
+ event: allocated.event_kind,
254
+ });
255
+ routing.effects.extend(allocated.after_allocation);
256
+ let final_fields = record(final_record, &fields);
257
+ let guards = [final_record[180 / 4], final_record[188 / 4]];
258
+ pool.slots[slot] = allocated.initialized.unwrap();
259
+ format!(
260
+ r#"{{{},"allocation":{{{}}},"record":{},"links":[{{"slot":{},"payload":{},"flags":{}}}]}}"#,
261
+ full_fields(world.state, &routing, guards),
262
+ allocation_fields(&pool, &allocated.allocation),
263
+ final_fields,
264
+ slot,
265
+ link.record.words[184 / 4],
266
+ link.record.words[424 / 4]
267
+ )
268
+ }
crates/urt-gameplay/src/bin/urt-location-feedback.rs CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  use urt_gameplay::location_feedback::*;
2
  fn list(v: &[u32]) -> String {
3
  format!(
@@ -221,55 +224,6 @@ fn radio(w: &[u32]) -> String {
221
  out.warnings
222
  )
223
  }
224
- fn decode_pool(w: &[u32]) -> (EntityPool, u32, u32) {
225
- assert!(w.len() >= 4);
226
- let mut p = EntityPool {
227
- count: w[0],
228
- slots: vec![
229
- EntitySlot {
230
- words: [0x12345678; 220]
231
- };
232
- 1024
233
- ],
234
- };
235
- for j in 64..(w[0] as usize).max(65) {
236
- p.slots[j].words[532 / 4] = 1;
237
- p.slots[j].words[564 / 4] = 0;
238
- }
239
- assert_eq!(w.len(), 4 + 3 * w[3] as usize);
240
- for s in w[4..].chunks_exact(3) {
241
- p.slots[s[0] as usize].words[532 / 4] = s[1];
242
- p.slots[s[0] as usize].words[564 / 4] = s[2];
243
- }
244
- (p, w[1], w[2])
245
- }
246
- fn record(words: &[u32], fields: &[usize]) -> String {
247
- format!(
248
- "{{{}}}",
249
- fields
250
- .iter()
251
- .map(|o| format!("\"{o}\":{}", words[o / 4]))
252
- .collect::<Vec<_>>()
253
- .join(",")
254
- )
255
- }
256
- fn allocation_fields(pool: &EntityPool, o: &AllocationOutcome) -> String {
257
- let fields = [0, 512, 532, 536, 540, 564, 424, 84, 140];
258
- let r = o
259
- .selected
260
- .map(|i| record(&pool.slots[i].words, &fields))
261
- .unwrap_or("null".into());
262
- format!(
263
- r#""selected":{},"count":{},"retry":{},"scan_index":{},"status":"{}","registrations":{},"record":{}"#,
264
- optional(o.selected),
265
- o.count,
266
- o.retry,
267
- o.scan_index,
268
- o.status,
269
- list(&o.registrations),
270
- r
271
- )
272
- }
273
  fn allocation(w: &[u32]) -> String {
274
  let (mut pool, tick, start) = decode_pool(w);
275
  let out = allocate_entity(&mut pool, tick, start).unwrap();
@@ -359,7 +313,7 @@ fn defuse_terminal(w: &[u32]) -> String {
359
  .expect("expected an allocation attempt");
360
  assert_eq!(pool.slots, before_slots);
361
  assert!(outcome.initialized.is_none());
362
- assert!(outcome.links.is_empty());
363
  assert!(outcome.after_allocation.is_empty());
364
  let effects = outcome
365
  .before_allocation
 
1
+ #[path = "support/entity_pool.rs"]
2
+ mod entity_pool;
3
+ use entity_pool::{allocation_fields, decode_pool, record};
4
  use urt_gameplay::location_feedback::*;
5
  fn list(v: &[u32]) -> String {
6
  format!(
 
224
  out.warnings
225
  )
226
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  fn allocation(w: &[u32]) -> String {
228
  let (mut pool, tick, start) = decode_pool(w);
229
  let out = allocate_entity(&mut pool, tick, start).unwrap();
 
313
  .expect("expected an allocation attempt");
314
  assert_eq!(pool.slots, before_slots);
315
  assert!(outcome.initialized.is_none());
316
+ assert!(outcome.link.is_none());
317
  assert!(outcome.after_allocation.is_empty());
318
  let effects = outcome
319
  .before_allocation
crates/urt-gameplay/src/defuse.rs CHANGED
@@ -401,6 +401,22 @@ pub fn process_defuse(
401
  world: &mut DefuseWorld,
402
  input: FullDefuseInput,
403
  ) -> Result<DefuseOutcome, Error> {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  use crate::move_callbacks::{Mode8EligibilityInput, mode8_eligible};
405
  let mut out = DefuseOutcome::default();
406
  let mut clients = world.clients.clone();
@@ -423,7 +439,7 @@ pub fn process_defuse(
423
  count: input.count,
424
  },
425
  )? {
426
- return Ok(out);
427
  }
428
  let bomb = world
429
  .bombs
@@ -432,20 +448,17 @@ pub fn process_defuse(
432
  out.lookups.push(bomb);
433
  let Some(index) = bomb else {
434
  out.missing = true;
435
- return Ok(out);
436
  };
437
  let d = distance(world.actor_point, world.bombs[index].point)?;
438
  out.distances.push(d.to_bits());
439
  let mut next = world.state;
440
- out.effects = if d >= 75. || next.flags & 32768 == 0 {
441
- cancel_defuse(&mut next, input.base)?
442
- } else {
443
- finish_defuse(&mut next, input.base)?
444
- };
445
  clients[input.base.slot as usize].busy = next.busy;
446
  world.clients = clients;
447
  world.state = next;
448
- Ok(out)
449
  }
450
  #[cfg(test)]
451
  mod full_tests {
 
401
  world: &mut DefuseWorld,
402
  input: FullDefuseInput,
403
  ) -> Result<DefuseOutcome, Error> {
404
+ let (mut out, effects) = process_defuse_with(world, input, |state, input, cancel, _| {
405
+ if cancel {
406
+ cancel_defuse(state, input)
407
+ } else {
408
+ finish_defuse(state, input)
409
+ }
410
+ })?;
411
+ out.effects = effects;
412
+ Ok(out)
413
+ }
414
+
415
+ pub(crate) fn process_defuse_with<T: Default>(
416
+ world: &mut DefuseWorld,
417
+ input: FullDefuseInput,
418
+ apply: impl FnOnce(&mut DefuseState, DefuseInput, bool, [u32; 3]) -> Result<T, Error>,
419
+ ) -> Result<(DefuseOutcome, T), Error> {
420
  use crate::move_callbacks::{Mode8EligibilityInput, mode8_eligible};
421
  let mut out = DefuseOutcome::default();
422
  let mut clients = world.clients.clone();
 
439
  count: input.count,
440
  },
441
  )? {
442
+ return Ok((out, T::default()));
443
  }
444
  let bomb = world
445
  .bombs
 
448
  out.lookups.push(bomb);
449
  let Some(index) = bomb else {
450
  out.missing = true;
451
+ return Ok((out, T::default()));
452
  };
453
  let d = distance(world.actor_point, world.bombs[index].point)?;
454
  out.distances.push(d.to_bits());
455
  let mut next = world.state;
456
+ let cancel = d >= 75. || next.flags & 32768 == 0;
457
+ let result = apply(&mut next, input.base, cancel, world.bombs[index].point)?;
 
 
 
458
  clients[input.base.slot as usize].busy = next.busy;
459
  world.clients = clients;
460
  world.state = next;
461
+ Ok((out, result))
462
  }
463
  #[cfg(test)]
464
  mod full_tests {
crates/urt-gameplay/src/location_feedback.rs CHANGED
@@ -570,11 +570,37 @@ pub struct DefuseAllocation {
570
  pub event_kind: u32,
571
  pub allocation: AllocationOutcome,
572
  pub initialized: Option<EntitySlot>,
573
- pub links: Vec<usize>,
574
  pub before_allocation: Vec<crate::defuse::DefuseEffect>,
575
  pub after_allocation: Vec<crate::defuse::DefuseEffect>,
576
  }
577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
578
  /// Resolve event allocation for a reached defuse branch. Pending diagnostic
579
  /// and fatal outcomes commit the observed caller and allocator prefix. Typed
580
  /// errors leave the supplied state untouched. Native effects remain plans.
@@ -612,14 +638,20 @@ pub fn allocate_defuse_branch(
612
  caller.event = state.event;
613
  let mut next_pool = pool.clone();
614
  let allocation = allocate_entity(&mut next_pool, input.tick, start)?;
615
- let (initialized, links) = if let Some(index) = allocation.selected {
616
  let record = &mut next_pool.slots[index];
617
- let initialized = construct_defuse_event(record, origin, event_kind, input.tick, payload)?;
 
 
 
 
 
 
618
  caller.event = [payload, record.words[424 / 4]];
619
- (Some(initialized), vec![index])
620
  } else {
621
  after_allocation.clear();
622
- (None, vec![])
623
  };
624
  *state = caller;
625
  *pool = next_pool;
@@ -627,27 +659,28 @@ pub fn allocate_defuse_branch(
627
  event_kind,
628
  allocation,
629
  initialized,
630
- links,
631
  before_allocation: effects,
632
  after_allocation,
633
  }))
634
  }
635
 
636
- fn construct_defuse_event(
637
  record: &mut EntitySlot,
638
  origin: [u32; 3],
639
  kind: u32,
640
  tick: u32,
641
- payload: u32,
642
- ) -> Result<EntitySlot, Error> {
643
- let initialized = record.clone();
644
- let mut event = slot_event(&initialized);
645
  crate::transition::temporary_event(&mut event, origin, kind, tick as i32)
646
  .map_err(|_| Error::InvalidInput)?;
647
  store_event(record, &event);
 
 
 
 
648
  record.words[184 / 4] = payload;
649
  record.words[424 / 4] |= 32;
650
- Ok(initialized)
651
  }
652
 
653
  /// Original153774 through153917, stopping before radio. Successful allocation
@@ -665,8 +698,10 @@ pub fn allocated_defuse_start(
665
  crate::defuse::begin_defuse(&mut next, input)?;
666
  let allocation = allocate_entity(&mut p, input.tick, start)?;
667
  let index = allocation.selected.ok_or(Error::InvalidInput)?;
668
- let initialized =
669
- construct_defuse_event(&mut p.slots[index], origin, 83, input.tick, input.duration)?;
 
 
670
  next.event = [input.duration, p.slots[index].words[424 / 4]];
671
  *state = next;
672
  *pool = p;
 
570
  pub event_kind: u32,
571
  pub allocation: AllocationOutcome,
572
  pub initialized: Option<EntitySlot>,
573
+ pub link: Option<DefuseEventLink>,
574
  pub before_allocation: Vec<crate::defuse::DefuseEffect>,
575
  pub after_allocation: Vec<crate::defuse::DefuseEffect>,
576
  }
577
 
578
+ /// Snapshot presented to native link −31 before the caller updates the event.
579
+ #[derive(Clone, Debug, PartialEq, Eq)]
580
+ pub struct DefuseEventLink {
581
+ pub slot: usize,
582
+ pub record: EntitySlot,
583
+ }
584
+
585
+ /// Apply the complete defuse routing to a world and its caller-supplied pool.
586
+ /// Routing observations carry lookup and distance data; caller effect plans
587
+ /// are ordered around allocation in the optional event result.
588
+ pub fn process_allocated_defuse(
589
+ world: &mut crate::defuse::DefuseWorld,
590
+ pool: &mut EntityPool,
591
+ input: crate::defuse::FullDefuseInput,
592
+ level_start: u32,
593
+ ) -> Result<(crate::defuse::DefuseOutcome, Option<DefuseAllocation>), Error> {
594
+ crate::defuse::process_defuse_with(world, input, |state, base, cancel, origin| {
595
+ let branch = if cancel {
596
+ DefuseBranch::Cancel
597
+ } else {
598
+ DefuseBranch::Finish
599
+ };
600
+ allocate_defuse_branch(state, pool, base, branch, level_start, origin)
601
+ })
602
+ }
603
+
604
  /// Resolve event allocation for a reached defuse branch. Pending diagnostic
605
  /// and fatal outcomes commit the observed caller and allocator prefix. Typed
606
  /// errors leave the supplied state untouched. Native effects remain plans.
 
638
  caller.event = state.event;
639
  let mut next_pool = pool.clone();
640
  let allocation = allocate_entity(&mut next_pool, input.tick, start)?;
641
+ let (initialized, link) = if let Some(index) = allocation.selected {
642
  let record = &mut next_pool.slots[index];
643
+ let initialized = record.clone();
644
+ construct_event(record, origin, event_kind, input.tick)?;
645
+ let link = DefuseEventLink {
646
+ slot: index,
647
+ record: record.clone(),
648
+ };
649
+ write_defuse_payload(record, payload);
650
  caller.event = [payload, record.words[424 / 4]];
651
+ (Some(initialized), Some(link))
652
  } else {
653
  after_allocation.clear();
654
+ (None, None)
655
  };
656
  *state = caller;
657
  *pool = next_pool;
 
659
  event_kind,
660
  allocation,
661
  initialized,
662
+ link,
663
  before_allocation: effects,
664
  after_allocation,
665
  }))
666
  }
667
 
668
+ fn construct_event(
669
  record: &mut EntitySlot,
670
  origin: [u32; 3],
671
  kind: u32,
672
  tick: u32,
673
+ ) -> Result<(), Error> {
674
+ let mut event = slot_event(record);
 
 
675
  crate::transition::temporary_event(&mut event, origin, kind, tick as i32)
676
  .map_err(|_| Error::InvalidInput)?;
677
  store_event(record, &event);
678
+ Ok(())
679
+ }
680
+
681
+ fn write_defuse_payload(record: &mut EntitySlot, payload: u32) {
682
  record.words[184 / 4] = payload;
683
  record.words[424 / 4] |= 32;
 
684
  }
685
 
686
  /// Original153774 through153917, stopping before radio. Successful allocation
 
698
  crate::defuse::begin_defuse(&mut next, input)?;
699
  let allocation = allocate_entity(&mut p, input.tick, start)?;
700
  let index = allocation.selected.ok_or(Error::InvalidInput)?;
701
+ let record = &mut p.slots[index];
702
+ let initialized = record.clone();
703
+ construct_event(record, origin, 83, input.tick)?;
704
+ write_defuse_payload(record, input.duration);
705
  next.event = [input.duration, p.slots[index].words[424 / 4]];
706
  *state = next;
707
  *pool = p;
docs/FINDINGS.md CHANGED
@@ -2037,3 +2037,5 @@ RE-1034–1043 batch validation passed:2,018 Python tests,339 Rust tests,146 det
2037
  - The Rust defuse adapter preserves allocator-terminal caller writes and the completion log plan. [Rust terminal parity](research/RUST_DEFUSE_ALLOCATION_TERMINAL.md).
2038
 
2039
  - Defuse event linking precedes the caller's payload and flag writes for start, cancellation and completion. [Full QVM callback evidence](research/QVM_DEFUSE_ALLOCATED_CALLBACK.md).
 
 
 
2037
  - The Rust defuse adapter preserves allocator-terminal caller writes and the completion log plan. [Rust terminal parity](research/RUST_DEFUSE_ALLOCATION_TERMINAL.md).
2038
 
2039
  - Defuse event linking precedes the caller's payload and flag writes for start, cancellation and completion. [Full QVM callback evidence](research/QVM_DEFUSE_ALLOCATED_CALLBACK.md).
2040
+
2041
+ - The Rust callback exposes a link-time record snapshot and retains the final event in the pool. [Allocated defuse parity](research/RUST_DEFUSE_ALLOCATED_CALLBACK.md).
docs/PROVISIONAL_TODO.md CHANGED
@@ -2099,3 +2099,5 @@ RE-974–983 completed routing, command rewrite, inactivity, movement-parameter
2099
  - [x] RE-1045 Preserve defuse caller state across allocator terminals in Rust ([evidence](research/RUST_DEFUSE_ALLOCATION_TERMINAL.md)).
2100
 
2101
  - [x] RE-1046 Trace the complete defuse callback through returned event allocations ([evidence](research/QVM_DEFUSE_ALLOCATED_CALLBACK.md)).
 
 
 
2099
  - [x] RE-1045 Preserve defuse caller state across allocator terminals in Rust ([evidence](research/RUST_DEFUSE_ALLOCATION_TERMINAL.md)).
2100
 
2101
  - [x] RE-1046 Trace the complete defuse callback through returned event allocations ([evidence](research/QVM_DEFUSE_ALLOCATED_CALLBACK.md)).
2102
+
2103
+ - [x] RE-1047 Port the full allocated defuse callback and its link-time snapshot ([evidence](research/RUST_DEFUSE_ALLOCATED_CALLBACK.md)).
docs/RESEARCH_LEDGER.md CHANGED
@@ -2859,3 +2859,7 @@ Rust matches the caller state, earlier log and allocator results in sixteen trac
2859
  ## 2026-11-21 — RE-1046 Trace the complete defuse callback through returned event allocations
2860
 
2861
  Thirty-nine source cases combine eligibility, bomb search, distance routing and real event construction. Both cancellation branches write payload zero and completion writes one, after the native link request. See [full callback findings](research/QVM_DEFUSE_ALLOCATED_CALLBACK.md).
 
 
 
 
 
2859
  ## 2026-11-21 — RE-1046 Trace the complete defuse callback through returned event allocations
2860
 
2861
  Thirty-nine source cases combine eligibility, bomb search, distance routing and real event construction. Both cancellation branches write payload zero and completion writes one, after the native link request. See [full callback findings](research/QVM_DEFUSE_ALLOCATED_CALLBACK.md).
2862
+
2863
+ ## 2026-11-21 — RE-1047 Port the full allocated defuse callback and its link-time snapshot
2864
+
2865
+ Rust shares existing callback routing and matches all 39 source cases with actual pool allocations. The link plan retains the event record before payload and flag mutation. See [allocated callback parity](research/RUST_DEFUSE_ALLOCATED_CALLBACK.md).
docs/research/QVM_LOCATION_ALLOCATION_BATCH.md CHANGED
@@ -73,3 +73,5 @@ RE-1044 traces the caller and constructor prefixes before diagnostic/fatal alloc
73
  RE-1045 matches all sixteen prefixes in [the Rust adapter](RUST_DEFUSE_ALLOCATION_TERMINAL.md). The adapter commits the earlier writes at a terminal outcome and exposes the completion log separately from later effects.
74
 
75
  RE-1046 combines successful allocation and event construction with [the full source callback](QVM_DEFUSE_ALLOCATED_CALLBACK.md). Link-time and final event fields are captured separately for starts, cancellations and completions.
 
 
 
73
  RE-1045 matches all sixteen prefixes in [the Rust adapter](RUST_DEFUSE_ALLOCATION_TERMINAL.md). The adapter commits the earlier writes at a terminal outcome and exposes the completion log separately from later effects.
74
 
75
  RE-1046 combines successful allocation and event construction with [the full source callback](QVM_DEFUSE_ALLOCATED_CALLBACK.md). Link-time and final event fields are captured separately for starts, cancellations and completions.
76
+
77
+ RE-1047 matches the 39 source fixtures in [the full Rust callback](RUST_DEFUSE_ALLOCATED_CALLBACK.md). Native link adapters can now consume the record snapshot separately from the final pool contents.
docs/research/README.md CHANGED
@@ -1665,3 +1665,5 @@ The extension collector adds five focused tests for native tail calls, command-r
1665
  - [Defuse allocation terminals in Rust](RUST_DEFUSE_ALLOCATION_TERMINAL.md)
1666
 
1667
  - [Full defuse callback with allocated events](QVM_DEFUSE_ALLOCATED_CALLBACK.md)
 
 
 
1665
  - [Defuse allocation terminals in Rust](RUST_DEFUSE_ALLOCATION_TERMINAL.md)
1666
 
1667
  - [Full defuse callback with allocated events](QVM_DEFUSE_ALLOCATED_CALLBACK.md)
1668
+
1669
+ - [Allocated defuse callback in Rust](RUST_DEFUSE_ALLOCATED_CALLBACK.md)
docs/research/RUST_DEFUSE_ALLOCATED_CALLBACK.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Allocated defuse callback in Rust
2
+
3
+ `process_allocated_defuse` shares eligibility, bomb selection and distance routing with the existing defuse callback. It passes the selected bomb's origin to the allocator and event constructor. The link plan holds the event record as it appeared when the original requested linking, before the caller sets word 184 and bit 32 of word 424. The pool stores the final record.
4
+
5
+ The [parity report](rust-defuse-allocated-callback.json) compares all 39 traced cases, including both cancellation paths, log and completion plans, alternate bomb selection and states that produce no allocation. The focused check reruns the original callback and terminal-allocation parity. The allocator and bomb lookup still receive caller-supplied views of the world. Native linking, registration, radio and other feedback dispatch remain external.
docs/research/rust-defuse-allocated-callback.json ADDED
The diff for this file is too large to render. See raw diff
 
scripts/analyze_rust_defuse_allocated_callback.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compare the allocated Rust defuse callback with its full source traces."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ from analyze_qvm import write_json
9
+ from analyze_rust_defuse_complete import encode as encode_callback
10
+ from analyze_rust_location_allocation import encode as encode_pool
11
+ from rust_lifecycle_support import result
12
+
13
+
14
+ def main():
15
+ subprocess.run(['cargo', 'build', '--offline', '--package', 'urt-gameplay',
16
+ '--bin', 'urt-defuse'], check=True)
17
+ binary = Path(os.environ.get('CARGO_TARGET_DIR', 'target')) / 'debug' / 'urt-defuse'
18
+ path = Path('docs/research/qvm-defuse-allocated-callback.json')
19
+ data = path.read_bytes()
20
+ probes = []
21
+ for row in json.loads(data)['probes']:
22
+ a = row['input']
23
+ expected = {key: value for key, value in row.items() if key not in ('input', 'execution')}
24
+ args = [*encode_callback(a), a['event_flags'], *encode_pool(a['allocation'])]
25
+ probes.append(dict(input=a, source=expected, rust=result(binary, 'allocated-full', args)))
26
+ write_json(Path('docs/research/rust-defuse-allocated-callback.json'), {
27
+ 'source_report': str(path), 'source_report_sha256': hashlib.sha256(data).hexdigest(),
28
+ 'probes': probes, 'limits': 'Fixed-pool callback and link snapshot parity. Native effects remain plans.',
29
+ })
30
+
31
+
32
+ if __name__ == '__main__':
33
+ main()
scripts/test_rust_defuse_allocated_callback.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import json
3
+ import unittest
4
+ from pathlib import Path
5
+
6
+
7
+ class DefuseAllocatedCallbackParity(unittest.TestCase):
8
+ def test_allocated_callback(self):
9
+ report = json.loads(Path('docs/research/rust-defuse-allocated-callback.json').read_text())
10
+ digest = hashlib.sha256(Path(report['source_report']).read_bytes()).hexdigest()
11
+ self.assertEqual(report['source_report_sha256'], digest)
12
+ self.assertEqual(len(report['probes']), 39)
13
+ for row in report['probes']:
14
+ with self.subTest(input=row['input']):
15
+ self.assertEqual(row['source'], row['rust'])
16
+
17
+
18
+ if __name__ == '__main__':
19
+ unittest.main()
xtask/checks.tsv CHANGED
@@ -4762,3 +4762,20 @@ edge docs/research/qvm-defuse-allocated-callback.json scripts/test_qvm_defuse_al
4762
  group qvm-defuse-allocated-callback scripts/analyze_qvm_defuse_allocated_callback.py
4763
  group qvm-defuse-allocated-callback scripts/analyze_qvm_location_allocated_defuse.py
4764
  edge scripts/analyze_qvm_defuse_allocated_callback.py scripts/analyze_qvm_resumer_audit.py
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4762
  group qvm-defuse-allocated-callback scripts/analyze_qvm_defuse_allocated_callback.py
4763
  group qvm-defuse-allocated-callback scripts/analyze_qvm_location_allocated_defuse.py
4764
  edge scripts/analyze_qvm_defuse_allocated_callback.py scripts/analyze_qvm_resumer_audit.py
4765
+ report scripts/analyze_rust_defuse_allocated_callback.py docs/research/rust-defuse-allocated-callback.json
4766
+ edge docs/research/rust-defuse-allocated-callback.json scripts/test_rust_defuse_allocated_callback.py
4767
+ group rust-defuse-allocated-callback scripts/analyze_rust_defuse_allocated_callback.py
4768
+ group rust-defuse-allocated-callback scripts/analyze_rust_defuse_complete.py
4769
+ group rust-defuse-allocated-callback scripts/analyze_rust_defuse_allocation_terminal.py
4770
+ group gameplay scripts/analyze_rust_defuse_allocated_callback.py
4771
+ edge docs/research/qvm-defuse-allocated-callback.json scripts/analyze_rust_defuse_allocated_callback.py
4772
+ edge crates/urt-gameplay/src/defuse.rs scripts/analyze_rust_defuse_allocated_callback.py
4773
+ edge crates/urt-gameplay/src/location_feedback.rs scripts/analyze_rust_defuse_allocated_callback.py
4774
+ edge crates/urt-gameplay/src/move_callbacks.rs scripts/analyze_rust_defuse_allocated_callback.py
4775
+ edge crates/urt-gameplay/src/transition.rs scripts/analyze_rust_defuse_allocated_callback.py
4776
+ edge crates/urt-gameplay/src/bin/urt-defuse.rs scripts/analyze_rust_defuse_allocated_callback.py
4777
+ edge crates/urt-gameplay/src/bin/support/entity_pool.rs scripts/analyze_rust_defuse_allocated_callback.py
4778
+ edge crates/urt-gameplay/src/bin/support/entity_pool.rs scripts/analyze_rust_defuse_allocation_terminal.py
4779
+ edge crates/urt-gameplay/src/bin/support/entity_pool.rs scripts/analyze_rust_location_allocation.py
4780
+ edge crates/urt-gameplay/src/bin/support/entity_pool.rs scripts/analyze_rust_location_allocated_defuse.py
4781
+ edge crates/urt-gameplay/src/bin/support/entity_pool.rs scripts/analyze_rust_health_impulse.py