1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
|
use crate::{BehaviorOreState, LoadedMissionState, MissionEventStop};
use fparkan_script::{
Handler2Record, Handler2RecordInput, Handler2RecordScheduler, ScriptDispatchSelector, VarSet,
VarSetDefault,
};
use fparkan_world::{identity_metadata, registration_sequence, OwnerId, World};
use std::collections::BTreeMap;
const STORAGE_CLASS: u32 = 0x8000_0008;
const RESOURCE_ORE: u32 = 0x0200_0100;
#[derive(Default)]
pub(super) struct ClanAiEvents {
next_ms: BTreeMap<usize, u32>,
stops: BTreeMap<(usize, usize, usize), (MissionEventStop, u64)>,
research_stubs: BTreeMap<(usize, u8), u64>,
problems: BTreeMap<usize, Handler2RecordScheduler>,
started: BTreeMap<(usize, u32), u64>,
}
impl LoadedMissionState {
pub(super) fn tick_clan_ai_events(&mut self, world: &World, now_ms: u32) {
let Some(varset) = &self.script_varset else {
return;
};
for bundle in self.script_bundles.iter().filter(|bundle| {
bundle.behavior_warm_start.is_some() && self.mission.clans[bundle.clan_index].mode == 2
}) {
let Some((event_index, event)) =
bundle.package.events.iter().enumerate().find(|(_, event)| {
event.name_raw == b"Problems0\0" && !event.instructions.is_empty()
})
else {
continue;
};
let clan = bundle.clan_index;
// shortcut: use the base interval until the separate native AI clock and RNG are wired.
if !self
.clan_ai_events
.due(clan, self.mission_events.start_ms, now_ms)
{
continue;
}
let Some(state) = self
.script_varset_states
.iter_mut()
.find(|state| state.clan_index == clan)
else {
continue;
};
let mut next = Some((event_index, event, None));
while let Some((event_index, event, problem)) = next.take() {
let mut solved = false;
let result = varset.declarations.execute_event_prefix(
event,
bundle.formula_table.as_ref(),
&mut state.values,
|instruction, values| match instruction.dispatch_selector() {
ScriptDispatchSelector::Handler(8) if problem.is_some() => {
if single_dword(&instruction.references, values) != Some(2) {
return Err("Handler(8) only supports ST_SOLVED".into());
}
solved = true;
Ok(None)
}
ScriptDispatchSelector::Handler(14) if problem.is_some() => {
let (mode, class) = instruction.dword_pair(values)
.ok_or("Handler(14) requires a unit mode and class")?;
if mode != 2 {
return Err("Handler(14) only supports UNIT_ANY_UNIT".into());
}
// shortcut: only unassigned placed objects until PBM owns roster slots.
let id = self.mission_events.first_available_placed_unit(
&self.mission, world, clan, class
);
Ok(Some(VarSetDefault::Dword(id.unwrap_or(u32::MAX))))
}
ScriptDispatchSelector::Handler(29) => {
let problem: &Handler2Record = problem.as_ref().ok_or("Handler(29) requires a current problem")?;
let bits = match single_dword(&instruction.references, values) {
Some(0) => problem.key.scalar_4_bits,
Some(1) => problem.key.scalar_5_bits,
Some(2) => problem.scalar_6.to_bits(),
_ => return Err("Handler(29) requires a problem argument index from 0 to 2".into()),
};
Ok(Some(VarSetDefault::Dword(problem_dword(bits).ok_or("Handler(29) argument is outside the supported DWORD range")?)))
}
ScriptDispatchSelector::Handler(0) if problem.is_some() && instruction.references.len() == 1 => Ok(Some(VarSetDefault::Dword(1))),
ScriptDispatchSelector::Handler(2) => {
let (name, input) = problem_operands(&varset.declarations, values, &instruction.references)
.ok_or("Handler(2) requires seven numeric problem operands")?;
let start = format!("{name}_Start\0");
let resume = format!("{name}_Continue\0");
if bundle.package.events.iter().any(|event| event.name_raw == start.as_bytes())
&& bundle.package.events.iter().any(|event| event.name_raw == resume.as_bytes())
{
let update = self.clan_ai_events.problems.entry(clan).or_default().submit(input);
if update.created {
eprintln!("sim_coverage script_problem_dispatch_stub=1 clan={clan} problem={name}");
}
}
Ok(None)
}
ScriptDispatchSelector::Handler(3) if instruction.references.is_empty() => {
let [available, _, _, demand, _] = bundle
.behavior_warm_start
.ok_or("Handler(3) requires live Behavior totals")?
.cleared_words
.map(f32::from_bits);
Ok(Some(VarSetDefault::FloatBits(
(available - demand).to_bits(),
)))
}
ScriptDispatchSelector::Handler(16)
if instruction.dword_pair(values) == Some((STORAGE_CLASS, RESOURCE_ORE)) =>
{
let remaining = storage_space(&self.behavior_ore_states, world, OwnerId(clan as u16));
Ok(Some(VarSetDefault::FloatBits(remaining.to_bits())))
}
ScriptDispatchSelector::Handler(17)
if instruction.dword_pair(values)
== Some((crate::mining::MINE_CLASS, 0x0afc_0900)) =>
{
let owner = OwnerId(clan as u16);
let remaining =
crate::mining::remaining_for_clan(&self.mine_sites, world, owner);
Ok(Some(VarSetDefault::FloatBits(remaining.to_bits())))
}
ScriptDispatchSelector::Handler(49) if instruction.references.is_empty() => {
let slots = self
.ai_startup_states
.iter()
.find(|state| state.clan_index == clan);
Ok(Some(VarSetDefault::Dword(
slots.map_or(0, |state| count_free_minds(&state.record_slots)),
)))
}
ScriptDispatchSelector::Handler(34) => {
let &[index] = instruction.references.as_slice() else {
return Err("Handler(34) requires one DWORD operand".to_owned());
};
let Some(&VarSetDefault::Dword(class)) = values.get(index as usize) else {
return Err("Handler(34) requires one DWORD operand".to_owned());
};
Ok(Some(VarSetDefault::Dword(
self.mission_events.count_clan_class(
world,
OwnerId(clan as u16),
class,
),
)))
}
ScriptDispatchSelector::Handler(handler @ (56 | 65)) if instruction.references.is_empty() => {
// shortcut: keep research disabled until the native policy flag and catalog are wired.
let count = self
.clan_ai_events
.research_stubs
.entry((clan, handler))
.or_default();
*count += 1;
if *count == 1 {
eprintln!(
"sim_coverage script_research_status_stub=1 clan={clan} handler={handler} script={}",
bundle.script_path
);
}
Ok(Some(VarSetDefault::Dword(0)))
}
selector => Err(format!("{selector:?}")),
},
);
if let Err((instruction_index, reason)) = result {
let (stop, count) = self
.clan_ai_events
.stops
.entry((clan, event_index, instruction_index))
.or_insert_with(|| {
(
MissionEventStop {
clan_index: clan,
script_path: bundle.script_path.clone(),
event_index,
instruction_index,
reason,
},
0,
)
});
*count += 1;
if *count == 1 {
eprintln!("sim_coverage script_clan_ai_unsupported=1 clan={clan} script={} event={event_index} instruction={instruction_index} reason={}", stop.script_path, stop.reason);
}
}
if let Some(problem) = problem {
if solved {
self.clan_ai_events
.problems
.entry(clan)
.or_default()
.remove(problem.key);
}
continue;
}
// shortcut: run one highest-priority Start per tick until ties, decay and Continue are wired.
let Some(problem) = self
.clan_ai_events
.problems
.get(&clan)
.and_then(|queue| highest_problem(queue.records()))
.cloned()
else {
continue;
};
let Some(kind) = varset.declarations.declarations.iter().find(|entry| {
entry.name.starts_with("PBM_")
&& entry.default_value == VarSetDefault::Dword(problem.key.word_0)
}) else {
continue;
};
let problem_id = problem.key.word_0;
let start = format!("{}_Start\0", kind.name);
next = bundle
.package
.events
.iter()
.enumerate()
.find(|(_, event)| {
event.name_raw == start.as_bytes() && !event.instructions.is_empty()
})
.map(|(index, event)| (index, event, Some(problem)));
if next.is_some() {
let count = self
.clan_ai_events
.started
.entry((clan, problem_id))
.or_default();
*count += 1;
if *count == 1 {
eprintln!(
"sim_coverage script_problem_start_approx=1 clan={clan} problem={}",
kind.name
);
}
}
}
}
}
}
fn highest_problem(problems: &[Handler2Record]) -> Option<&Handler2Record> {
problems
.iter()
.filter(|record| record.scalar_1 > 0.0)
.reduce(|best, record| {
if record.scalar_1 > best.scalar_1 {
record
} else {
best
}
})
}
fn single_dword(references: &[u32], values: &[VarSetDefault]) -> Option<u32> {
let &[index] = references else {
return None;
};
values.get(index as usize)?.as_dword()
}
fn problem_dword(bits: u32) -> Option<u32> {
let value = f64::from(f32::from_bits(bits));
let limit = 9_223_372_036_854_775_808.0;
(-limit..limit)
.contains(&value)
.then(|| value.trunc() as i64 as u32)
}
fn problem_operands<'a>(
varset: &'a VarSet,
values: &[VarSetDefault],
references: &[u32],
) -> Option<(&'a str, Handler2RecordInput)> {
let &[kind, priority, increment, sender, first, second, third] = references else {
return None;
};
let value = |index: u32| values.get(index as usize).copied();
let word = |index| match value(index)? {
VarSetDefault::Dword(value) => Some(value),
VarSetDefault::FloatBits(bits) => problem_dword(bits),
};
let scalar = |index| match value(index)? {
VarSetDefault::Dword(value) => Some(value as f32),
VarSetDefault::FloatBits(bits) => Some(f32::from_bits(bits)),
};
Some((
varset.declarations.get(kind as usize)?.name.as_str(),
Handler2RecordInput {
word_0: word(kind)?,
scalar_1: scalar(priority)?,
word_2: word(increment)?,
word_3: word(sender)?,
scalar_4: scalar(first)?,
scalar_5: scalar(second)?,
scalar_6: scalar(third)?,
},
))
}
fn count_free_minds(slots: &[u32]) -> u32 {
slots.iter().filter(|&&word| word == u32::MAX).count() as u32
}
fn storage_space(ores: &[BehaviorOreState], world: &World, clan: OwnerId) -> f32 {
ores.iter()
.filter(|ore| {
ore.class_flags == STORAGE_CLASS
&& registration_sequence(world, ore.handle).is_ok_and(|sequence| sequence.is_some())
&& identity_metadata(world, ore.handle)
.is_ok_and(|identity| identity.owner_id == Some(clan))
})
.fold(0.0, |space, ore| {
space + (f32::from_bits(ore.maximum_ore_bits) - f32::from_bits(ore.current_ore_bits))
})
}
impl ClanAiEvents {
fn due(&mut self, clan: usize, start_ms: u32, now_ms: u32) -> bool {
let next = self.next_ms.entry(clan).or_insert(7_000);
let elapsed = now_ms.wrapping_sub(start_ms);
if elapsed < *next {
return false;
}
*next = elapsed.saturating_add(7_000);
true
}
pub(super) fn stops(&self) -> impl Iterator<Item = (&MissionEventStop, u64)> {
self.stops.values().map(|(stop, count)| (stop, *count))
}
pub(super) fn research_status_stubs(&self) -> impl Iterator<Item = (usize, u8, u64)> + '_ {
self.research_stubs
.iter()
.map(|(&(clan, handler), &count)| (clan, handler, count))
}
pub(super) fn pending_problems(&self) -> impl Iterator<Item = (usize, u32)> + '_ {
self.problems.iter().flat_map(|(&clan, problems)| {
problems
.records()
.iter()
.map(move |record| (clan, record.key.word_0))
})
}
pub(super) fn started_problems(&self) -> impl Iterator<Item = (usize, u32, u64)> + '_ {
self.started
.iter()
.map(|(&(clan, kind), &count)| (clan, kind, count))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clans_have_independent_due_times_and_no_replay_after_a_late_tick() {
let mut ai = ClanAiEvents::default();
assert!(!ai.due(1, 100_000, 106_999));
assert!(ai.due(1, 100_000, 107_000));
assert!(ai.due(2, 100_000, 107_000));
assert!(!ai.due(1, 100_000, 113_999));
assert!(ai.due(1, 100_000, 120_000));
assert!(!ai.due(1, 100_000, 120_000));
}
#[test]
fn free_mind_count_uses_only_the_native_sentinel() {
assert_eq!(count_free_minds(&[]), 0);
assert_eq!(count_free_minds(&[u32::MAX, 0, u32::MAX, 1, 0xfffe]), 2);
}
#[test]
fn problem_operands_resolve_live_cells_and_numeric_types() {
let varset = fparkan_script::parse_varset(
b"VAR(DWORD, PBM_ROBOT_NEEDED, 6)\nVAR(float, priority, 0)\nVAR(DWORD, arg, 0)\n",
)
.unwrap();
let values = [
VarSetDefault::Dword(6),
VarSetDefault::FloatBits(5.75_f32.to_bits()),
VarSetDefault::Dword(12),
];
let (name, problem) = problem_operands(&varset, &values, &[0, 1, 1, 2, 2, 1, 0]).unwrap();
assert_eq!(name, "PBM_ROBOT_NEEDED");
assert_eq!(
problem,
Handler2RecordInput {
word_0: 6,
scalar_1: 5.75,
word_2: 5,
word_3: 12,
scalar_4: 12.0,
scalar_5: 5.75,
scalar_6: 6.0,
}
);
}
#[test]
fn problem_selection_requires_a_positive_priority_and_preserves_order_on_ties() {
let mut queue = Handler2RecordScheduler::default();
for (word_0, scalar_1) in [(1, 0.0), (2, -3.0), (3, 0.5), (4, 0.5)] {
queue.submit(Handler2RecordInput {
word_0,
scalar_1,
word_2: 0,
word_3: 0,
scalar_4: 0.0,
scalar_5: 0.0,
scalar_6: 0.0,
});
}
let first = highest_problem(queue.records()).unwrap().key;
assert_eq!(first.word_0, 3);
queue.remove(first);
assert_eq!(highest_problem(queue.records()).unwrap().key.word_0, 4);
}
#[test]
fn free_ore_space_follows_storage_ownership_and_lifecycle() {
use fparkan_world::{
construct_object, new, register_object, request_delete, set_owner, step, InputSnapshot,
ObjectDraft, OriginalObjectId, WorldConfig,
};
let mut world = new(WorldConfig);
let mut make = |id, class_flags, owner, ore: f32| {
let original_id = OriginalObjectId(id);
let handle = construct_object(
&mut world,
ObjectDraft {
original_id: Some(original_id),
},
)
.unwrap();
set_owner(&mut world, handle, Some(OwnerId(owner))).unwrap();
register_object(&mut world, handle).unwrap();
BehaviorOreState {
original_id,
handle,
class_flags,
current_ore_bits: ore.to_bits(),
maximum_ore_bits: 100.0_f32.to_bits(),
}
};
let ores = [
make(1, STORAGE_CLASS, 1, 15.0),
make(2, STORAGE_CLASS, 1, 40.0),
make(3, STORAGE_CLASS, 0, 10.0),
make(4, crate::mining::MINE_CLASS, 1, 20.0),
];
assert_eq!(storage_space(&ores, &world, OwnerId(1)), 145.0);
request_delete(&mut world, ores[0].handle).unwrap();
step(&mut world, &InputSnapshot).unwrap();
assert_eq!(storage_space(&ores, &world, OwnerId(1)), 60.0);
}
}
|