paavohtl Claude Opus 4.6 (1M context) commited on
Commit
a553079
·
1 Parent(s): 323dedb

refactor: extract game logic from wormkit/replacements to openwa-core

Browse files

Move ~2,760 lines of pure game logic from wormkit hook files into
openwa-core, leaving wormkit as thin shims (trampolines + install).

New core modules:
- engine/team_ops.rs: 8 team/worm state accessor functions
- audio/sound_ops.rs: sound queue, worm sound, dispatch + streaming bridges
- game/weapon_fire.rs: ammo management, fire dispatch, 20+ weapon handlers
- game/weapon_release.rs: weapon release orchestration, spawn effect

Expanded core modules:
- task/cloud.rs: cloud_handle_message (wind, parallax, render)
- task/filter.rs: filter_handle_message (subscription table gate)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

crates/openwa-core/src/audio/mod.rs CHANGED
@@ -2,6 +2,7 @@ pub mod active_sound;
2
  pub mod dssound;
3
  pub mod music;
4
  pub mod sound;
 
5
  pub mod speech;
6
  pub mod streaming;
7
 
 
2
  pub mod dssound;
3
  pub mod music;
4
  pub mod sound;
5
+ pub mod sound_ops;
6
  pub mod speech;
7
  pub mod streaming;
8
 
crates/openwa-core/src/audio/sound_ops.rs ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Sound playback operations.
2
+ //!
3
+ //! Pure Rust reimplementations of WA.exe sound functions. Called from
4
+ //! wormkit hook trampolines and from other core game logic (weapon fire, etc.).
5
+ //!
6
+ //! Original WA functions:
7
+ //! - PlaySoundGlobal queue insertion (0x546E20)
8
+ //! - PlaySoundLocal (0x4FDFE0)
9
+ //! - StopWormSound (FUN_00515180)
10
+ //! - PlayWormSound (FUN_005150D0)
11
+ //! - PlayWormSound2 (FUN_00515020)
12
+ //! - IsSoundSuppressed (0x5261E0)
13
+ //! - DispatchGlobalSound (0x526270)
14
+ //! - PlaySoundPooled_Direct (0x546B50)
15
+
16
+ use core::sync::atomic::{AtomicU32, Ordering};
17
+
18
+ use crate::audio::{play_sound, play_sound_pooled, SoundId, SoundSlot};
19
+ use crate::engine::{DDGame, DDGameWrapper, SoundQueueEntry};
20
+ use crate::fixed::Fixed;
21
+ use crate::task::worm::CTaskWorm;
22
+ use crate::task::{CGameTask, CTask};
23
+
24
+ // ============================================================
25
+ // Sound queue insertion
26
+ // ============================================================
27
+
28
+ /// Insert a sound into DDGame's 16-slot queue.
29
+ ///
30
+ /// Returns a pointer to the new entry, or None if the queue is full
31
+ /// or sound is disabled.
32
+ pub unsafe fn queue_sound(
33
+ ddgame: *mut DDGame,
34
+ sound_id: SoundId,
35
+ flags: u32,
36
+ volume: Fixed,
37
+ pitch: Fixed,
38
+ ) -> Option<*mut SoundQueueEntry> {
39
+ let g = &mut *ddgame;
40
+ if g.sound_queue_count >= 16 || g.sound.is_null() {
41
+ return None;
42
+ }
43
+ let entry = &mut g.sound_queue[g.sound_queue_count as usize];
44
+ *entry = SoundQueueEntry {
45
+ sound_id: sound_id.0,
46
+ flags,
47
+ volume: volume.0 as u32,
48
+ pitch: pitch.0 as u32,
49
+ reserved: 0,
50
+ is_local: 0,
51
+ _pad: [0; 3],
52
+ pos_x: 0,
53
+ pos_y: 0,
54
+ secondary_vtable: 0,
55
+ };
56
+ g.sound_queue_count += 1;
57
+ Some(entry)
58
+ }
59
+
60
+ // ============================================================
61
+ // PlaySoundLocal — Rust-callable version
62
+ // ============================================================
63
+
64
+ /// Play a local sound on a task — port of PlaySoundLocal (0x4FDFE0).
65
+ ///
66
+ /// Queues the sound, marks it as local, records the emitter position, and
67
+ /// increments the task's local sound count. Returns true on success.
68
+ pub unsafe fn play_sound_local(
69
+ task: *mut CGameTask,
70
+ sound_id: impl Into<SoundId>,
71
+ flags: u32,
72
+ volume: Fixed,
73
+ pitch: Fixed,
74
+ ) -> bool {
75
+ let gt = &*task;
76
+ let ddgame = gt.base.ddgame;
77
+ let entry = match queue_sound(ddgame, sound_id.into(), flags, volume, pitch) {
78
+ Some(e) => e,
79
+ None => return false,
80
+ };
81
+
82
+ (*entry).is_local = 1;
83
+
84
+ let emitter = &gt.sound_emitter;
85
+ (*entry).secondary_vtable = emitter as *const _ as u32;
86
+ ((*emitter.vtable).get_position)(emitter, &mut (*entry).pos_x, &mut (*entry).pos_y);
87
+
88
+ (*task).sound_emitter.local_sound_count += 1;
89
+ true
90
+ }
91
+
92
+ // ============================================================
93
+ // Worm sound functions (streaming sound handle at CTaskWorm+0x3B0)
94
+ // ============================================================
95
+
96
+ /// Stop the worm's active streaming sound. Port of FUN_00515180.
97
+ ///
98
+ /// Reads the sound handle from `worm.sound_handle`, dispatches to either
99
+ /// DSSound::stop_channel (regular) or ActiveSoundTable::stop_sound (streaming,
100
+ /// handle has bit 30 set), then clears the handle.
101
+ pub unsafe fn stop_worm_sound(worm: *mut CTaskWorm) {
102
+ let handle = (*worm).sound_handle;
103
+ if handle != 0 {
104
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
105
+ let sound = (*ddgame).sound;
106
+ if !sound.is_null() && (handle as i32) >= 0 {
107
+ if handle & 0x40000000 != 0 {
108
+ // Streaming sound — stop via ActiveSoundTable
109
+ if !(*ddgame).active_sounds.is_null() {
110
+ (*(*ddgame).active_sounds).stop_sound(handle & !0x40000000);
111
+ }
112
+ } else {
113
+ // Regular DSSound channel
114
+ ((*(*sound).vtable).stop_channel)(sound, handle as i32);
115
+ }
116
+ }
117
+ }
118
+ (*worm).sound_handle = 0;
119
+ }
120
+
121
+ /// Stop current worm sound, then start a new streaming sound.
122
+ /// Port of FUN_005150D0.
123
+ ///
124
+ /// Stops the current sound (same logic as [`stop_worm_sound`] but with
125
+ /// reversed condition order matching the original), then calls the WA
126
+ /// streaming load-and-play function (FUN_00546c20) and stores the new handle.
127
+ pub unsafe fn play_worm_sound(worm: *mut CTaskWorm, sound_id: SoundId, volume: Fixed) {
128
+ let handle = (*worm).sound_handle;
129
+ if handle != 0 {
130
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
131
+ let sound = (*ddgame).sound;
132
+ if !sound.is_null() && (handle as i32) >= 0 {
133
+ if handle & 0x40000000 == 0 {
134
+ // Regular DSSound channel — stop via vtable
135
+ ((*(*sound).vtable).stop_channel)(sound, handle as i32);
136
+ } else {
137
+ // Streaming sound — stop via ActiveSoundTable
138
+ if !(*ddgame).active_sounds.is_null() {
139
+ (*(*ddgame).active_sounds).stop_sound(handle & !0x40000000);
140
+ }
141
+ }
142
+ }
143
+ }
144
+ // Start new streaming sound via WA function (FUN_00546c20)
145
+ // FUN_005150D0 hardcodes flags=3
146
+ let new_handle = call_load_and_play_streaming(worm, sound_id.0, 3, volume.0 as u32);
147
+ (*worm).sound_handle = new_handle;
148
+ }
149
+
150
+ /// Stop+play on the secondary sound handle (CTaskWorm+0x3B4).
151
+ /// Port of FUN_00515020 (23 callers in WA).
152
+ ///
153
+ /// Stops any active sound on `sound_handle_2`, then plays a new streaming
154
+ /// sound. Has a special case for sound 0x36 (Teleport) when the worm's Y
155
+ /// position is extremely high — plays at weapon target position instead.
156
+ pub unsafe fn play_worm_sound_2(
157
+ worm: *mut CTaskWorm,
158
+ sound_id: SoundId,
159
+ volume: Fixed,
160
+ flags: u32,
161
+ ) {
162
+ // 1. Stop current sound on handle_2
163
+ let handle = (*worm).sound_handle_2;
164
+ if handle != 0 {
165
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
166
+ let sound = (*ddgame).sound;
167
+ if !sound.is_null() && (handle as i32) >= 0 {
168
+ if handle & 0x40000000 == 0 {
169
+ ((*(*sound).vtable).stop_channel)(sound, handle as i32);
170
+ } else if !(*ddgame).active_sounds.is_null() {
171
+ (*(*ddgame).active_sounds).stop_sound(handle & !0x40000000);
172
+ }
173
+ }
174
+ }
175
+
176
+ // 2. Start new sound
177
+ // CGameTask+0x88 = Y position (fixed-point). Check if worm is extremely high.
178
+ let worm_y = *((worm as *const u8).add(0x88) as *const i32);
179
+ let new_handle = if worm_y < -0x270F_FFFF && sound_id.0 == 0x36 {
180
+ // Special teleport case: play at weapon target position
181
+ call_load_and_play_streaming_positional(
182
+ worm,
183
+ sound_id.0,
184
+ flags,
185
+ volume.0 as u32,
186
+ (*worm).weapon_param_1 as u32,
187
+ (*worm).weapon_param_2 as u32,
188
+ )
189
+ } else {
190
+ // Normal case: play streaming sound
191
+ call_load_and_play_streaming(worm, sound_id.0, flags, volume.0 as u32)
192
+ };
193
+
194
+ (*worm).sound_handle_2 = new_handle;
195
+ }
196
+
197
+ // ============================================================
198
+ // Sound dispatch helpers
199
+ // ============================================================
200
+
201
+ /// Check if sound playback is suppressed — port of IsSoundSuppressed (0x5261E0).
202
+ ///
203
+ /// Returns true if sound is muted or current frame is before sound start.
204
+ pub unsafe fn is_sound_suppressed(ddgame: *const DDGame) -> bool {
205
+ let g = &*ddgame;
206
+ let gi = &*g.game_info;
207
+ gi.sound_mute != 0 || g.frame_counter < gi.sound_start_frame
208
+ }
209
+
210
+ /// Dispatch a global sound to DSSound — port of DispatchGlobalSound (0x526270).
211
+ ///
212
+ /// Checks sound suppression, then calls DSSound play_sound.
213
+ /// Returns 0xFFFFFFFF if suppressed, 0 if no DSSound, otherwise the channel handle.
214
+ pub unsafe fn dispatch_global_sound(
215
+ ddgame_wrapper: *const DDGameWrapper,
216
+ sound_id: u32,
217
+ flags: u32,
218
+ volume: u32,
219
+ pitch: u32,
220
+ ) -> u32 {
221
+ let g = &*(*ddgame_wrapper).ddgame;
222
+ let gi = &*g.game_info;
223
+
224
+ if gi.sound_mute != 0 || g.frame_counter < gi.sound_start_frame {
225
+ return 0xFFFF_FFFF;
226
+ }
227
+
228
+ let dssound = g.sound;
229
+ if dssound.is_null() {
230
+ return 0;
231
+ }
232
+
233
+ play_sound(
234
+ dssound,
235
+ SoundSlot(sound_id),
236
+ flags as i32,
237
+ Fixed(volume as i32),
238
+ Fixed(pitch as i32),
239
+ Fixed(0),
240
+ ) as u32
241
+ }
242
+
243
+ /// Direct pooled sound playback — port of PlaySoundPooled_Direct (0x546B50).
244
+ ///
245
+ /// Bypasses queue, checks suppression + fast-forward, calls DSSound play_sound_pooled.
246
+ pub unsafe fn play_sound_pooled_direct(
247
+ task: *const CTask,
248
+ param1: SoundSlot,
249
+ param2: i32,
250
+ param3: Fixed,
251
+ ) -> i32 {
252
+ let g = &*(*task).ddgame;
253
+ let gi = &*g.game_info;
254
+
255
+ if gi.sound_mute != 0 || g.frame_counter < gi.sound_start_frame {
256
+ return -1;
257
+ }
258
+
259
+ if g.fast_forward_active != 0 {
260
+ return -1;
261
+ }
262
+
263
+ let dssound = g.sound;
264
+ if dssound.is_null() {
265
+ return 0;
266
+ }
267
+
268
+ play_sound_pooled(dssound, param1, param2, Fixed::ONE, param3, Fixed::ZERO)
269
+ }
270
+
271
+ // ============================================================
272
+ // Streaming sound bridges (naked asm — WA usercall conventions)
273
+ // ============================================================
274
+
275
+ /// Rebased address for FUN_00546c20 (LoadAndPlayStreaming).
276
+ /// Initialized by wormkit's sound::install().
277
+ pub static LOAD_AND_PLAY_STREAMING_ADDR: AtomicU32 = AtomicU32::new(0);
278
+
279
+ /// Bridge to FUN_00546c20 — load and play a streaming sound.
280
+ /// usercall(EAX=worm, ESI=&worm.sound_emitter) + stdcall(sound_id, flags, volume), plain RET.
281
+ /// Returns new sound handle (with bit 30 set for streaming, 0 on failure, -1 if suppressed).
282
+ pub unsafe fn call_load_and_play_streaming(
283
+ worm: *mut CTaskWorm,
284
+ sound_id: u32,
285
+ flags: u32,
286
+ volume: u32,
287
+ ) -> u32 {
288
+ let addr = LOAD_AND_PLAY_STREAMING_ADDR.load(Ordering::Relaxed);
289
+ call_load_and_play_streaming_bridge(worm, sound_id, flags, volume, addr)
290
+ }
291
+
292
+ #[unsafe(naked)]
293
+ unsafe extern "C" fn call_load_and_play_streaming_bridge(
294
+ _worm: *mut CTaskWorm,
295
+ _sound_id: u32,
296
+ _flags: u32,
297
+ _volume: u32,
298
+ _addr: u32,
299
+ ) -> u32 {
300
+ core::arch::naked_asm!(
301
+ "push esi",
302
+ "push ebx",
303
+ // Stack: 2 saves(8) + ret(4) = 12 to first arg
304
+ "mov eax, [esp+12]", // worm → EAX
305
+ "lea esi, [eax+0xE8]", // &worm.sound_emitter → ESI
306
+ "mov ebx, [esp+28]", // addr (12 + 4*4 = 28)
307
+ "push [esp+24]", // volume (12+12=24)
308
+ "push [esp+20]", // flags (12+8=20, shifted+4=24)
309
+ "push [esp+24]", // sound_id (12+4=16, shifted+8=24)
310
+ "call ebx",
311
+ "pop ebx",
312
+ "pop esi",
313
+ "ret",
314
+ );
315
+ }
316
+
317
+ /// Bridge to FUN_00546bb0 — load and play a positional streaming sound.
318
+ /// usercall(EAX=worm, ESI=&worm.sound_emitter) + stdcall(sound_id, flags, volume, x, y).
319
+ /// Returns handle | 0x40000000 on success, 0 on failure, -1 if suppressed.
320
+ pub unsafe fn call_load_and_play_streaming_positional(
321
+ worm: *mut CTaskWorm,
322
+ sound_id: u32,
323
+ flags: u32,
324
+ volume: u32,
325
+ x: u32,
326
+ y: u32,
327
+ ) -> u32 {
328
+ let addr = crate::rebase::rb(0x546BB0u32);
329
+ call_load_and_play_streaming_positional_bridge(worm, sound_id, flags, volume, x, y, addr)
330
+ }
331
+
332
+ #[unsafe(naked)]
333
+ unsafe extern "C" fn call_load_and_play_streaming_positional_bridge(
334
+ _worm: *mut CTaskWorm,
335
+ _sound_id: u32,
336
+ _flags: u32,
337
+ _volume: u32,
338
+ _x: u32,
339
+ _y: u32,
340
+ _addr: u32,
341
+ ) -> u32 {
342
+ core::arch::naked_asm!(
343
+ "push esi",
344
+ "push ebx",
345
+ // Stack after saves: [ESP+12]=worm [+16]=sound_id [+20]=flags
346
+ // [+24]=volume [+28]=x [+32]=y [+36]=addr
347
+ "mov eax, [esp+12]", // worm → EAX
348
+ "lea esi, [eax+0xE8]", // &worm.sound_emitter → ESI
349
+ "mov ebx, [esp+36]", // addr
350
+ // Push 5 stdcall params right-to-left: y, x, volume, flags, sound_id.
351
+ "push [esp+32]", // y
352
+ "push [esp+32]", // x (was +28, shifted +4)
353
+ "push [esp+32]", // volume (was +24, shifted +8)
354
+ "push [esp+32]", // flags (was +20, shifted +12)
355
+ "push [esp+32]", // sound_id (was +16, shifted +16)
356
+ "call ebx",
357
+ "pop ebx",
358
+ "pop esi",
359
+ "ret",
360
+ );
361
+ }
crates/openwa-core/src/engine/mod.rs CHANGED
@@ -9,6 +9,7 @@ pub mod net_bridge;
9
  pub mod net_wrapper;
10
  pub mod replay;
11
  pub mod team_arena;
 
12
 
13
  pub use ddgame::DDGame;
14
  pub use ddgame_constructor::{
 
9
  pub mod net_wrapper;
10
  pub mod replay;
11
  pub mod team_arena;
12
+ pub mod team_ops;
13
 
14
  pub use ddgame::DDGame;
15
  pub use ddgame_constructor::{
crates/openwa-core/src/engine/team_ops.rs ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Team and worm state accessor functions.
2
+ //!
3
+ //! Pure Rust reimplementations of WA.exe functions that access the TeamArenaState
4
+ //! area (DDGame + 0x4628). These are called from wormkit hook trampolines.
5
+ //!
6
+ //! Original WA functions:
7
+ //! - CountTeamsByAlliance (0x522030)
8
+ //! - GetTeamTotalHealth (0x5224D0)
9
+ //! - IsWormInSpecialState (0x5226B0)
10
+ //! - GetWormPosition (0x522700)
11
+ //! - CheckWormState0x64 (0x5228D0)
12
+ //! - CheckTeamWormState0x64 (0x522930)
13
+ //! - CheckAnyWormState0x8b (0x522970)
14
+ //! - SetActiveWorm_Maybe (0x522500)
15
+
16
+ use super::ddgame::{self, TeamArenaRef};
17
+
18
+ /// Count teams by alliance membership — port of 0x522030.
19
+ ///
20
+ /// Updates `state.active_team_count`, `same_alliance_count`, `enemy_team_count`.
21
+ /// Uses Pattern B header fields (+0x70/+0x74) for alliance and active_worm.
22
+ pub unsafe fn count_teams_by_alliance(arena: TeamArenaRef, alliance_id: i32) {
23
+ let state = arena.state_mut();
24
+ state.current_alliance = alliance_id;
25
+ state.active_team_count = 0;
26
+ state.same_alliance_count = 0;
27
+ state.enemy_team_count = 0;
28
+
29
+ for i in 0..state.team_count as usize {
30
+ let header = arena.team_header_b(i);
31
+ let team_alliance = header.alliance;
32
+ let active_worm = header.active_worm;
33
+ if active_worm != 0 && team_alliance >= 0 {
34
+ state.active_team_count += 1;
35
+ if team_alliance == alliance_id {
36
+ state.same_alliance_count += 1;
37
+ } else {
38
+ state.enemy_team_count += 1;
39
+ }
40
+ }
41
+ }
42
+ }
43
+
44
+ /// Sum worm health for a team — port of 0x5224D0.
45
+ ///
46
+ /// Returns 0 if the team is eliminated.
47
+ pub unsafe fn get_team_total_health(team_index: u32, arena: TeamArenaRef) -> i32 {
48
+ let header = arena.team_header(team_index as usize);
49
+
50
+ if header.eliminated != 0 {
51
+ return 0;
52
+ }
53
+
54
+ let worm_count = header.worm_count;
55
+ let mut total = 0i32;
56
+ for w in 1..=worm_count as usize {
57
+ total += arena.team_worm(team_index as usize, w).health;
58
+ }
59
+ total
60
+ }
61
+
62
+ /// Check worm state flag — port of 0x5226B0.
63
+ ///
64
+ /// Returns 1 if the worm is in a "special" state, 0 otherwise.
65
+ pub unsafe fn is_worm_in_special_state(
66
+ team_index: u32,
67
+ worm_index: u32,
68
+ arena: TeamArenaRef,
69
+ ) -> u32 {
70
+ if ddgame::worm::is_special_state(
71
+ arena
72
+ .team_worm(team_index as usize, worm_index as usize)
73
+ .state,
74
+ ) {
75
+ 1
76
+ } else {
77
+ 0
78
+ }
79
+ }
80
+
81
+ /// Read worm X,Y coordinates — port of 0x522700.
82
+ ///
83
+ /// Reads pos_x/pos_y from WormEntry._unknown_90[0..4] / [4..8].
84
+ /// These values appear transient — actual worm positions live in CGameTask objects.
85
+ pub unsafe fn get_worm_position(
86
+ team_index: u32,
87
+ worm_index: u32,
88
+ arena: TeamArenaRef,
89
+ out_x: *mut i32,
90
+ out_y: *mut i32,
91
+ ) {
92
+ let worm = arena.team_worm(team_index as usize, worm_index as usize);
93
+ *out_x = *(worm._unknown_90.as_ptr() as *const i32);
94
+ *out_y = *(worm._unknown_90.as_ptr().add(4) as *const i32);
95
+ }
96
+
97
+ /// Check if any worm on any team has state 0x64 — port of 0x5228D0.
98
+ ///
99
+ /// Iterates real teams (1-indexed). 11 xrefs in gameplay code.
100
+ pub unsafe fn check_worm_state_0x64(arena: TeamArenaRef) -> u32 {
101
+ let state = arena.state();
102
+
103
+ for i in 1..=state.team_count as usize {
104
+ let header = arena.team_header(i);
105
+ if header.eliminated != 0 {
106
+ continue;
107
+ }
108
+ let worm_count = header.worm_count;
109
+ for w in 1..=worm_count as usize {
110
+ if arena.team_worm(i, w).state == 0x64 {
111
+ return 1;
112
+ }
113
+ }
114
+ }
115
+ 0
116
+ }
117
+
118
+ /// Check if any worm on a specific team has state 0x64 — port of 0x522930.
119
+ ///
120
+ /// Per-team version. 1 xref (FUN_00556ad0).
121
+ pub unsafe fn check_team_worm_state_0x64(arena: TeamArenaRef, team_idx: u32) -> u32 {
122
+ let header = arena.team_header(team_idx as usize);
123
+
124
+ if header.eliminated != 0 {
125
+ return 0;
126
+ }
127
+
128
+ let worm_count = header.worm_count;
129
+ for w in 1..=worm_count as usize {
130
+ if arena.team_worm(team_idx as usize, w).state == 0x64 {
131
+ return 1;
132
+ }
133
+ }
134
+ 0
135
+ }
136
+
137
+ /// Scan all teams for state 0x8b — port of 0x522970.
138
+ ///
139
+ /// 1 xref (FUN_00557310).
140
+ pub unsafe fn check_any_worm_state_0x8b(arena: TeamArenaRef) -> u32 {
141
+ let state = arena.state();
142
+
143
+ for i in 1..=state.team_count as usize {
144
+ let header = arena.team_header(i);
145
+ if header.eliminated != 0 {
146
+ continue;
147
+ }
148
+ let worm_count = header.worm_count;
149
+ for w in 1..=worm_count as usize {
150
+ if arena.team_worm(i, w).state == 0x8b {
151
+ return 1;
152
+ }
153
+ }
154
+ }
155
+ 0
156
+ }
157
+
158
+ /// Set the active worm for a team — port of 0x522500.
159
+ ///
160
+ /// `worm_index=0` deactivates the team. `worm_index=N` sets worm N as active.
161
+ /// Called on turn transitions and worm selection (Tab).
162
+ /// Updates active counters and records last_active_team/alliance.
163
+ /// Uses Pattern B headers (0-indexed from `team_idx - 1`).
164
+ pub unsafe fn set_active_worm(arena: TeamArenaRef, team_idx: u32, worm_index: i32) {
165
+ let state = arena.state_mut();
166
+
167
+ // Pattern B header: team_idx is 1-indexed, team_header_b is 0-indexed
168
+ // team_idx=1 → team_header_b(0) → blocks[2].header
169
+ let header = arena.team_header_b(team_idx as usize - 1);
170
+
171
+ if worm_index == 0 {
172
+ // Deactivate team
173
+ if header.active_worm != 0 {
174
+ state.active_worm_count -= 1;
175
+ let alliance = header.alliance;
176
+ if alliance >= 0 {
177
+ state.active_team_count -= 1;
178
+ if alliance == state.current_alliance {
179
+ state.same_alliance_count -= 1;
180
+ } else {
181
+ state.enemy_team_count -= 1;
182
+ }
183
+ }
184
+ arena.team_header_b_mut(team_idx as usize - 1).active_worm = 0;
185
+ }
186
+ } else {
187
+ // Activate team — only update counters if not already active
188
+ if header.active_worm == 0 {
189
+ state.active_worm_count += 1;
190
+ state.last_active_team = team_idx as i32;
191
+ let alliance = header.alliance;
192
+ state.last_active_alliance = alliance;
193
+ if alliance >= 0 {
194
+ state.active_team_count += 1;
195
+ if alliance == state.current_alliance {
196
+ state.same_alliance_count += 1;
197
+ } else {
198
+ state.enemy_team_count += 1;
199
+ }
200
+ }
201
+ }
202
+ // Always write worm_index (original writes ESI unconditionally)
203
+ arena.team_header_b_mut(team_idx as usize - 1).active_worm = worm_index;
204
+ }
205
+ }
crates/openwa-core/src/game/mod.rs CHANGED
@@ -3,6 +3,8 @@ pub mod frontend;
3
  pub mod message;
4
  pub mod scheme;
5
  pub mod weapon;
 
 
6
 
7
  pub use class_type::ClassType;
8
  pub use frontend::ScreenId;
 
3
  pub mod message;
4
  pub mod scheme;
5
  pub mod weapon;
6
+ pub mod weapon_fire;
7
+ pub mod weapon_release;
8
 
9
  pub use class_type::ClassType;
10
  pub use frontend::ScreenId;
crates/openwa-core/src/game/weapon_fire.rs ADDED
@@ -0,0 +1,1439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! Weapon fire dispatch, ammo management, and object creation.
2
+ //!
3
+ //! Pure Rust reimplementations of WA.exe weapon functions. Called from
4
+ //! wormkit hook trampolines.
5
+ //!
6
+ //! Original WA functions:
7
+ //! - AddAmmo (0x522640), SubtractAmmo (0x522680), GetAmmo (0x5225E0)
8
+ //! - CountAliveWorms (0x5225A0)
9
+ //! - FireWeapon (0x51EE60): full dispatch
10
+ //! - CreateWeaponProjectile (0x51E0F0), ProjectileFire (0x51DFB0), CreateArrow (0x51ED90)
11
+
12
+ use crate::address::va;
13
+ use crate::audio::{KnownSoundId, SoundId};
14
+ use crate::engine::ddgame::{self, TeamArenaRef};
15
+ use crate::fixed::Fixed;
16
+ use crate::game::weapon::{WeaponEntry, WeaponFireParams, WeaponSpawnData};
17
+ use crate::game::Weapon;
18
+ use crate::log::log_line;
19
+ use crate::task::turn_game::CTaskTurnGame;
20
+ use crate::task::worm::{CTaskWorm, WormState};
21
+ use crate::task::CTask;
22
+
23
+ // ── WeaponReleaseContext ────────────────────────────────────
24
+
25
+ /// The 0x2C-byte stack-local struct populated by WeaponRelease and passed to
26
+ /// FireWeapon as the `local_struct` (ECX) parameter.
27
+ #[repr(C)]
28
+ #[derive(Clone, Copy)]
29
+ pub struct WeaponReleaseContext {
30
+ pub team_id: u32,
31
+ pub worm_id: u32,
32
+ pub spawn_x: u32,
33
+ pub spawn_y: u32,
34
+ pub spawn_offset_x: i32,
35
+ pub spawn_offset_y: i32,
36
+ pub ammo_per_turn: u32,
37
+ pub ammo_per_slot: u32,
38
+ pub _zero: u32,
39
+ pub delay: u32,
40
+ pub network_delay: i32,
41
+ }
42
+
43
+ const _: () = assert!(core::mem::size_of::<WeaponReleaseContext>() == 0x2C);
44
+
45
+ // ============================================================
46
+ // AddAmmo replacement (0x522640)
47
+ // ============================================================
48
+ // __usercall: EAX = team_index, EDX = amount, [ESP+4] = team_info_base, [ESP+8] = weapon_id
49
+ // RET 0x8
50
+
51
+ pub unsafe fn add_ammo(
52
+ team_index: u32,
53
+ amount: i32,
54
+ arena: TeamArenaRef,
55
+ weapon_id: u32,
56
+ ) {
57
+ let (alliance, wid) = arena.weapon_slot_key(team_index as usize, weapon_id);
58
+ let state = arena.state_mut();
59
+ let ammo = state.get_ammo(alliance, wid);
60
+ if ammo >= 0 {
61
+ if amount < 0 {
62
+ *state.ammo_mut(alliance, wid) = -1;
63
+ } else {
64
+ *state.ammo_mut(alliance, wid) = ammo + amount;
65
+ }
66
+ }
67
+ }
68
+
69
+ // ============================================================
70
+ // SubtractAmmo replacement (0x522680)
71
+ // ============================================================
72
+ // __usercall: EAX = team_index, ECX = team_info_base, [ESP+4] = weapon_id
73
+ // RET 0x4
74
+
75
+ pub unsafe fn subtract_ammo(team_index: u32, arena: TeamArenaRef, weapon_id: u32) {
76
+ let (alliance, wid) = arena.weapon_slot_key(team_index as usize, weapon_id);
77
+ let state = arena.state_mut();
78
+ let ammo = state.get_ammo(alliance, wid);
79
+ if ammo > 0 {
80
+ *state.ammo_mut(alliance, wid) = ammo - 1;
81
+ }
82
+ }
83
+
84
+ // ============================================================
85
+ // GetAmmo replacement (0x5225E0)
86
+ // ============================================================
87
+ // __usercall: EAX = team_index, ESI = team_info_base, EDX = weapon_id
88
+ // plain RET, returns EAX = ammo count
89
+
90
+ pub unsafe fn get_ammo(
91
+ team_index: u32,
92
+ arena: TeamArenaRef,
93
+ weapon_id: u32,
94
+ ) -> u32 {
95
+ let (alliance, wid) = arena.weapon_slot_key(team_index as usize, weapon_id);
96
+ let state = arena.state();
97
+
98
+ // Check weapon delay
99
+ if state.get_delay(alliance, wid) != 0 {
100
+ if state.game_mode_flag == 0 {
101
+ return 0;
102
+ }
103
+ // In sudden death (phase >= 484), delayed weapons return 0
104
+ // unless it's Teleport (weapon 0x28)
105
+ if state.game_phase >= ddgame::GAME_PHASE_SUDDEN_DEATH
106
+ && weapon_id != Weapon::Teleport as u32
107
+ {
108
+ return 0;
109
+ }
110
+ }
111
+
112
+ // SelectWorm (0x3B) requires >1 alive worm on the team
113
+ if state.game_phase >= ddgame::GAME_PHASE_NORMAL_MIN
114
+ && weapon_id == Weapon::SelectWorm as u32
115
+ && count_alive_worms(team_index, arena) == 0
116
+ {
117
+ return 0;
118
+ }
119
+
120
+ state.get_ammo(alliance, wid) as u32
121
+ }
122
+
123
+ // ============================================================
124
+ // CountAliveWorms replacement (0x5225A0)
125
+ // ============================================================
126
+ // __usercall: EAX = team_index, ECX = base
127
+ // plain RET, returns EAX = bool (1 if >1 worm alive on team)
128
+
129
+ pub unsafe fn count_alive_worms(team_index: u32, arena: TeamArenaRef) -> u32 {
130
+ let header = arena.team_header(team_index as usize);
131
+ let worm_count = header.worm_count;
132
+ let mut alive = 0i32;
133
+ for w in 1..=worm_count as usize {
134
+ if arena.team_worm(team_index as usize, w).health > 0 {
135
+ alive += 1;
136
+ }
137
+ }
138
+ if alive > 1 {
139
+ 1
140
+ } else {
141
+ 0
142
+ }
143
+ }
144
+
145
+ // ============================================================
146
+ // FireWeapon (0x51EE60) — trapped, called directly from weapon_release
147
+ // ============================================================
148
+
149
+ /// FireWeapon dispatch — called directly by `weapon_release_impl`.
150
+ ///
151
+ /// The WA function at 0x51EE60 is trapped via `install_trap!`; its only
152
+ /// caller (WeaponRelease) is ported and invokes this Rust function instead.
153
+ ///
154
+ /// Dispatches to type-specific fire sub-functions based on `entry.fire_type`
155
+ /// and `entry.fire_method` / `entry.special_subtype`.
156
+ /// Sets the completion flag at worm+0x3C before and after dispatch.
157
+ pub unsafe fn fire_weapon(
158
+ entry: *const WeaponEntry,
159
+ ctx: *const WeaponReleaseContext,
160
+ worm: *mut CTaskWorm,
161
+ ) {
162
+ use crate::rebase::rb;
163
+
164
+ let fire_type = (*entry).fire_type;
165
+ let fire_method = (*entry).fire_method;
166
+ let fire_params = &raw const (*entry).fire_params;
167
+ // Log weapon fire
168
+ let weapon = (*worm).selected_weapon;
169
+ let _ = log_line(&format!(
170
+ "[Weapon] FireWeapon: {:?} (id={}) type={} sub34={} sub38={}",
171
+ weapon,
172
+ weapon as u32,
173
+ fire_type,
174
+ (*entry).special_subtype,
175
+ fire_method
176
+ ));
177
+
178
+ CTaskWorm::set_fire_complete_raw(worm, 0);
179
+
180
+ use crate::game::weapon::{FireMethod, FireType};
181
+ match FireType::try_from(fire_type) {
182
+ Ok(FireType::Projectile) => match FireMethod::try_from(fire_method) {
183
+ Ok(FireMethod::PlacedExplosive) => {
184
+ call_fire_placed_explosive(worm, fire_params, ctx, rb(0x51EC80))
185
+ }
186
+ Ok(FireMethod::ProjectileFire) => {
187
+ call_fire_stdcall3(worm, fire_params, ctx, rb(0x51DFB0))
188
+ }
189
+ Ok(FireMethod::CreateWeaponProjectile) => {
190
+ call_fire_thiscall2(worm, fire_params, ctx, rb(0x51E0F0))
191
+ }
192
+ Ok(FireMethod::CreateArrow) => {
193
+ call_fire_thiscall2(worm, fire_params, ctx, rb(0x51ED90))
194
+ }
195
+ _ => {}
196
+ },
197
+ Ok(FireType::Rope) => match FireMethod::try_from(fire_method) {
198
+ Ok(FireMethod::PlacedExplosive) => {
199
+ call_fire_stdcall3(worm, fire_params, ctx, rb(0x51E1C0))
200
+ } // RopeType1
201
+ Ok(FireMethod::ProjectileFire) => {
202
+ call_fire_thiscall2(worm, fire_params, ctx, rb(0x51E0F0))
203
+ }
204
+ Ok(FireMethod::CreateWeaponProjectile) => {
205
+ call_fire_stdcall3(worm, fire_params, ctx, rb(0x51E240))
206
+ } // RopeType3
207
+ _ => {}
208
+ },
209
+ Ok(FireType::Strike) => {
210
+ // StrikeFire takes a pointer to the subtype_34 field (reinterpreted as fire params)
211
+ let subtype_34_ptr = &raw const (*entry).special_subtype as *const WeaponFireParams;
212
+ call_fire_stdcall3(worm, subtype_34_ptr, ctx, rb(0x51E2C0));
213
+ }
214
+ Ok(FireType::Special) => {
215
+ fire_weapon_special((*entry).special_subtype, entry, worm, ctx);
216
+ }
217
+ _ => {}
218
+ }
219
+
220
+ CTaskWorm::set_fire_complete_raw(worm, 1);
221
+ }
222
+
223
+ // ── Sub-function bridges ────────────────────────────────────
224
+ // All bridges save/restore ESI+EDI, set ESI=EDI=worm, then call.
225
+ // This preserves LLVM's callee-saved registers while providing
226
+ // the usercall context that sub-functions expect.
227
+
228
+ /// Bridge: PlacedExplosive — usercall(ECX=local_struct, EDX=worm, [ESP+4]=fire_params), RET 0x4.
229
+ /// Args: (worm, fire_params, ctx, addr).
230
+ #[unsafe(naked)]
231
+ unsafe extern "C" fn call_fire_placed_explosive(
232
+ _worm: *mut CTaskWorm,
233
+ _fire_params: *const WeaponFireParams,
234
+ _ctx: *const WeaponReleaseContext,
235
+ _addr: u32,
236
+ ) {
237
+ core::arch::naked_asm!(
238
+ "push ebx",
239
+ "push esi",
240
+ "push edi",
241
+ // Set up usercall registers
242
+ // Stack: 3 saves(12) + ret(4) = 16 to first arg
243
+ "mov edx, [esp+16]", // EDX = worm
244
+ "mov ecx, [esp+24]", // ECX = local_struct
245
+ "mov ebx, [esp+28]", // addr
246
+ "push [esp+20]", // fire_params (stack param)
247
+ "call ebx",
248
+ "pop edi",
249
+ "pop esi",
250
+ "pop ebx",
251
+ "ret",
252
+ );
253
+ }
254
+
255
+ /// Bridge: Projectile/Rope/Grenade — stdcall(worm, fire_params, local_struct), RET 0xC.
256
+ #[unsafe(naked)]
257
+ unsafe extern "C" fn call_fire_stdcall3(
258
+ _worm: *mut CTaskWorm,
259
+ _fire_params: *const WeaponFireParams,
260
+ _ctx: *const WeaponReleaseContext,
261
+ _addr: u32,
262
+ ) {
263
+ core::arch::naked_asm!(
264
+ "push ebx",
265
+ "push esi",
266
+ "push edi",
267
+ "mov esi, [esp+16]", // worm (3 saves=12 + ret=4 = 16)
268
+ "mov edi, [esp+16]",
269
+ "mov ebx, [esp+28]", // addr (saves=12 + ret=4 + 3 args=12 = 28)
270
+ "push [esp+24]", // local_struct
271
+ "push [esp+24]", // params (shifted +4)
272
+ "push [esp+24]", // worm (shifted +8)
273
+ "call ebx",
274
+ "pop edi",
275
+ "pop esi",
276
+ "pop ebx",
277
+ "ret",
278
+ );
279
+ }
280
+
281
+ /// Bridge: CreateWeaponProjectile — thiscall(ECX=worm, fire_params, local_struct), RET 0x8.
282
+ #[unsafe(naked)]
283
+ unsafe extern "C" fn call_fire_thiscall2(
284
+ _worm: *mut CTaskWorm,
285
+ _fire_params: *const WeaponFireParams,
286
+ _ctx: *const WeaponReleaseContext,
287
+ _addr: u32,
288
+ ) {
289
+ core::arch::naked_asm!(
290
+ "push ebx",
291
+ "push esi",
292
+ "push edi",
293
+ "mov esi, [esp+16]", // worm
294
+ "mov edi, [esp+16]",
295
+ "mov ecx, [esp+16]", // ECX = worm (this)
296
+ "mov ebx, [esp+28]", // addr
297
+ "push [esp+24]", // local_struct
298
+ "push [esp+24]", // params (shifted +4)
299
+ "call ebx",
300
+ "pop edi",
301
+ "pop esi",
302
+ "pop ebx",
303
+ "ret",
304
+ );
305
+ }
306
+
307
+ /// Bridge: stdcall(fire_params, local_struct), RET 0x8.
308
+ /// Currently unused — was incorrectly used for Shotgun/Longbow (which are thiscall).
309
+ #[unsafe(naked)]
310
+ #[allow(dead_code)]
311
+ unsafe extern "C" fn call_fire_stdcall2(
312
+ _worm: *mut CTaskWorm,
313
+ _fire_params: *const WeaponFireParams,
314
+ _ctx: *const WeaponReleaseContext,
315
+ _addr: u32,
316
+ ) {
317
+ core::arch::naked_asm!(
318
+ "push ebx",
319
+ "push esi",
320
+ "push edi",
321
+ "mov esi, [esp+16]", // worm
322
+ "mov edi, [esp+16]",
323
+ "mov ebx, [esp+28]", // addr
324
+ "push [esp+24]", // local_struct
325
+ "push [esp+24]", // params (shifted +4)
326
+ "call ebx",
327
+ "pop edi",
328
+ "pop esi",
329
+ "pop ebx",
330
+ "ret",
331
+ );
332
+ }
333
+
334
+ /// Type 4 (special) weapon dispatch.
335
+ ///
336
+ /// EAX at entry = weapon entry pointer (unchanged from type-4 switch).
337
+ /// Some handlers explicitly set EAX=worm or EAX=*(worm+0x44).
338
+ /// Handlers without explicit MOV EAX inherit the entry pointer.
339
+ pub unsafe fn fire_weapon_special(
340
+ subtype: i32,
341
+ entry: *const WeaponEntry,
342
+ worm: *mut CTaskWorm,
343
+ ctx: *const WeaponReleaseContext,
344
+ ) {
345
+ use crate::game::weapon::SpecialFireSubtype as S;
346
+
347
+ // Pointer to fire_method field, reinterpreted as fire params pointer for Girder
348
+ let params_38_ptr = &raw const (*entry).fire_method as *const WeaponFireParams;
349
+
350
+ match S::try_from(subtype) {
351
+ Ok(S::FirePunch) => CTaskWorm::set_state_raw(worm, WormState::FirePunch),
352
+ Ok(S::BaseballBat) => fire_drill(worm, ctx as *const u8),
353
+ Ok(S::DragonBall) => fire_dragon_ball(worm, params_38_ptr, ctx as *const u8),
354
+ Ok(S::Kamikaze) => CTaskWorm::set_state_raw(worm, WormState::Kamikaze),
355
+ Ok(S::SuicideBomber) => CTaskWorm::set_state_raw(worm, WormState::SuicideBomber),
356
+ Ok(S::Unknown6) => CTaskWorm::set_state_raw(worm, WormState::Unknown_0x70),
357
+ Ok(S::PneumaticDrill) => CTaskWorm::set_state_raw(worm, WormState::PneumaticDrill),
358
+ Ok(S::Prod) => fire_prod(worm, ctx as *const u8),
359
+ Ok(S::Teleport) => fire_teleport(worm),
360
+ Ok(S::Blowtorch) => CTaskWorm::set_state_raw(worm, WormState::Blowtorch),
361
+ Ok(S::Parachute) => {} // TODO: parachute handler
362
+ Ok(S::Surrender) => fire_surrender(worm),
363
+ Ok(S::MailMineMole) => fire_mail_mine_mole(worm),
364
+ Ok(S::NuclearTest) => {
365
+ if can_fire_subtype16((*worm).state()) {
366
+ fire_nuclear_test(worm);
367
+ } else {
368
+ CTaskWorm::set_state_raw(worm, WormState::TeleportCancelled_Maybe);
369
+ }
370
+ }
371
+ Ok(S::Girder) => fire_girder(worm),
372
+ Ok(S::Unknown18) => CTaskWorm::set_state_raw(worm, WormState::Unknown_0x72),
373
+ Ok(S::SkipGo) => fire_skip_go(worm, entry),
374
+ Ok(S::Freeze) => fire_freeze(worm),
375
+ Ok(S::SelectWorm) => fire_select_worm(worm),
376
+ Ok(S::ScalesOfJustice) => fire_scales_of_justice(worm),
377
+ Ok(S::JetPack) => CTaskWorm::set_state_raw(worm, WormState::WeaponAimed_Maybe),
378
+ Ok(S::Armageddon) => fire_armageddon(worm),
379
+ _ => {}
380
+ }
381
+ }
382
+
383
+ /// Worm state validity check for subtype 16 — pure Rust port of 0x516930.
384
+ /// Used by Nuclear Test to gate firing.
385
+ pub fn can_fire_subtype16(state: u32) -> bool {
386
+ state == WormState::WeaponAimed_Maybe as u32
387
+ || (WormState::AimingAngle_Maybe as u32..=WormState::PreFire_Maybe as u32).contains(&state)
388
+ }
389
+
390
+ // ── Pure Rust fire handlers (no bridge needed) ──────────────
391
+
392
+ /// Look up the CTaskTurnGame entity for a worm via SharedData.
393
+ ///
394
+ /// The entity at key (0, 0x14) is a CTaskTurnGame (inherits CTaskTeam).
395
+ /// Returns null if not found.
396
+ pub unsafe fn lookup_turn_game(
397
+ worm: *const CTaskWorm,
398
+ ) -> *mut crate::task::CTaskTurnGame {
399
+ use crate::task::SharedDataTable;
400
+
401
+ let table = SharedDataTable::from_task(worm as *const CTask);
402
+ table.lookup(0, 0x14) as *mut crate::task::CTaskTurnGame
403
+ }
404
+
405
+ /// Surrender (subtype 13) — sends message 0x2B (TaskMessage::Surrender) to
406
+ /// CTaskTurnGame via vtable dispatch.
407
+ ///
408
+ /// TurnGame::HandleMessage (0x55DC00) delegates to CTaskTeam (0x557310) for
409
+ /// the broadcast, then handles end-turn logic and surrender sound.
410
+ #[inline(never)]
411
+ unsafe fn fire_surrender(worm: *mut CTaskWorm) {
412
+ let team = lookup_turn_game(worm);
413
+ if team.is_null() {
414
+ return;
415
+ }
416
+
417
+ let mut buf = [0u8; 0x40C];
418
+ buf[0..4].copy_from_slice(&(*worm).team_index.to_ne_bytes());
419
+
420
+ // Dispatch through vtable — hits CTaskTurnGame::HandleMessage (0x55DC00)
421
+ // which delegates to CTaskTeam (0x557310) and handles end-turn/sound.
422
+ CTaskTurnGame::handle_message_raw(
423
+ team,
424
+ worm as *mut crate::task::CTask,
425
+ 0x2B,
426
+ 4,
427
+ buf.as_ptr(),
428
+ );
429
+ }
430
+
431
+ /// Send a message to CTaskTurnGame via SharedData lookup + vtable dispatch.
432
+ ///
433
+ /// Shared pattern: look up CTaskTurnGame at key (0, 0x14), write team_index
434
+ /// into a 0x40C-byte buffer, and call HandleMessage (vtable slot 2).
435
+ ///
436
+ /// The 0x40C-byte local buffer is passed as data pointer; team_index is written
437
+ /// at buf+0x00 to identify which team fired.
438
+ unsafe fn fire_send_team_message(worm: *mut CTaskWorm, msg_type: u32) {
439
+ let team = lookup_turn_game(worm);
440
+ if team.is_null() {
441
+ return;
442
+ }
443
+
444
+ let mut buf = [0u8; 0x40C];
445
+ let team_index = (*worm).team_index;
446
+ buf[0..4].copy_from_slice(&team_index.to_ne_bytes());
447
+
448
+ CTaskTurnGame::handle_message_raw(
449
+ team,
450
+ worm as *mut crate::task::CTask,
451
+ msg_type,
452
+ 4,
453
+ buf.as_ptr(),
454
+ );
455
+ }
456
+
457
+ /// Select Worm (subtype 21) — pure Rust replacement for 0x51EBE0.
458
+ ///
459
+ /// Sends message 0x5D to CTaskTurnGame with buf = [8, team_index, ...].
460
+ unsafe fn fire_select_worm(worm: *mut CTaskWorm) {
461
+ let team = lookup_turn_game(worm);
462
+ if team.is_null() {
463
+ return;
464
+ }
465
+
466
+ let mut buf = [0u8; 0x40C];
467
+ buf[0..4].copy_from_slice(&8u32.to_ne_bytes());
468
+ buf[4..8].copy_from_slice(&(*worm).team_index.to_ne_bytes());
469
+
470
+ CTaskTurnGame::handle_message_raw(
471
+ team,
472
+ worm as *mut crate::task::CTask,
473
+ 0x5D,
474
+ 0x408,
475
+ buf.as_ptr(),
476
+ );
477
+ }
478
+
479
+ /// Skip Go (subtype 19) — pure Rust replacement for 0x51E8C0.
480
+ ///
481
+ /// Toggles a bit in the team's `TeamHeader.turn_action_flags` (+0x7C).
482
+ /// Bit position comes from weapon entry's fire_params.
483
+ /// In game_version > 0x1C: toggles (set/clear). Otherwise: always sets.
484
+ unsafe fn fire_skip_go(worm: *const CTaskWorm, entry: *const WeaponEntry) {
485
+ use crate::engine::ddgame::TeamArenaRef;
486
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
487
+ let game_version = (*(*ddgame).game_info).game_version;
488
+ let team_index = (*worm).team_index as usize;
489
+
490
+ let bit_index = ((*entry).fire_params.shot_count & 0x1F) as u32;
491
+ let bit = 1u32 << bit_index;
492
+
493
+ let arena = TeamArenaRef::from_ptr(&raw mut (*ddgame).team_arena);
494
+ let header = arena.team_header_mut(team_index);
495
+ let flags = header.turn_action_flags;
496
+
497
+ if game_version > 0x1C && (flags & bit) != 0 {
498
+ header.turn_action_flags = flags & !bit;
499
+ } else {
500
+ header.turn_action_flags = flags | bit;
501
+ }
502
+ }
503
+
504
+ /// Freeze weapon (subtype 20) — pure Rust replacement for 0x51E600.
505
+ ///
506
+ /// Sends message 0x29 (TaskMessage::Freeze) to CTaskTurnGame, then increments
507
+ /// WormEntry.turn_action_counter_Maybe by 14 (0x0E).
508
+ unsafe fn fire_freeze(worm: *mut CTaskWorm) {
509
+ use crate::engine::ddgame::TeamArenaRef;
510
+
511
+ fire_send_team_message(worm, 0x29);
512
+
513
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
514
+ let arena = TeamArenaRef::from_ptr(&raw mut (*ddgame).team_arena);
515
+ let team_index = (*worm).team_index as usize;
516
+ let worm_index = (*worm).worm_index as usize;
517
+ let entry = arena.team_worm_mut(team_index, worm_index);
518
+ entry.turn_action_counter_Maybe += 14;
519
+ }
520
+
521
+ /// Mail/Mine/Mole (subtype 14) — pure Rust replacement for 0x51E670.
522
+ ///
523
+ /// Conditionally calls worm->vtable[0xE](0x65) based on game version and worm state,
524
+ /// then sends message 0x28 to CTaskTurnGame, then increments
525
+ /// WormEntry.turn_action_counter_Maybe by 7.
526
+ ///
527
+ /// Version check logic (from disassembly at 0x51E670):
528
+ /// - version < 2: call vtable[0xE](0x65)
529
+ /// - 2 <= version < 5: skip vtable call
530
+ /// - version >= 5 && worm state == 0x7D: call vtable
531
+ /// - version >= 5 && worm state == 0x78 && version < 8: call vtable
532
+ /// - otherwise: skip
533
+ unsafe fn fire_mail_mine_mole(worm: *mut CTaskWorm) {
534
+ use crate::engine::ddgame::TeamArenaRef;
535
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
536
+ let version = (*ddgame).version_flag_4;
537
+ let worm_state = (*worm).state();
538
+
539
+ let should_call_vtable = version < 2
540
+ || (version >= 5
541
+ && (worm_state == WormState::PreFire_Maybe as u32
542
+ || (worm_state == WormState::WeaponAimed_Maybe as u32 && version < 8)));
543
+
544
+ if should_call_vtable {
545
+ CTaskWorm::set_state_raw(worm, WormState::Idle);
546
+ }
547
+
548
+ fire_send_team_message(worm, 0x28);
549
+
550
+ let arena = TeamArenaRef::from_ptr(&raw mut (*ddgame).team_arena);
551
+ let team_index = (*worm).team_index as usize;
552
+ let worm_index = (*worm).worm_index as usize;
553
+ let entry = arena.team_worm_mut(team_index, worm_index);
554
+ entry.turn_action_counter_Maybe += 7;
555
+ }
556
+
557
+ /// Teleport (subtype 10) — pure Rust port of 0x51E710.
558
+ ///
559
+ /// If CTaskWorm+0x208 == 0: set state to AirStrikePending_Maybe.
560
+ /// Otherwise: play teleport sound (via play_worm_sound_2), spawn visual
561
+ /// effect, update position, compute new state, clear action fields.
562
+ ///
563
+ /// Convention: usercall(EAX=worm, ESI=worm, EDI=worm), plain RET.
564
+ unsafe fn fire_teleport(worm: *mut CTaskWorm) {
565
+ use crate::audio::sound_ops as sound;
566
+ use crate::rebase::rb;
567
+
568
+ if (*worm)._unknown_208 == 0 {
569
+ CTaskWorm::set_state_raw(worm, WormState::AirStrikePending_Maybe);
570
+ return;
571
+ }
572
+
573
+ // Play teleport sound (0x36) on secondary sound handle
574
+ sound::play_worm_sound_2(worm, SoundId(0x36), Fixed::ONE, 3);
575
+
576
+ // Spawn visual effect: usercall(EAX=0x80000, ECX=x) + stdcall(y, 0, 0, 0, 600, 0x10000, 0x1999)
577
+ let fire_x = (*worm).weapon_param_1;
578
+ let fire_y = (*worm).weapon_param_2;
579
+ call_spawn_effect(fire_x, fire_y, rb(0x547C30));
580
+
581
+ // Temporarily swap worm+0x34 with worm+0x190, call position update, restore
582
+ let worm_raw = worm as *mut u8;
583
+ let saved_34 = *(worm_raw.add(0x34) as *const i32);
584
+ *(worm_raw.add(0x34) as *mut i32) = (*worm)._unknown_190;
585
+ call_position_update(worm, fire_x, fire_y, rb(0x4FE070));
586
+ *(worm_raw.add(0x34) as *mut i32) = saved_34;
587
+
588
+ // Compute new state: version < 455 → Idle (0x65), else → 0x8B
589
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
590
+ let game_version = (*(*ddgame).game_info).game_version;
591
+ let new_state = if game_version < 0x1C7 {
592
+ WormState::Idle
593
+ } else {
594
+ WormState::Unknown_0x8B
595
+ };
596
+ CTaskWorm::set_state_raw(worm, new_state);
597
+
598
+ // Clear action fields
599
+ *(worm_raw.add(0x48) as *mut i32) = 0;
600
+ (*worm)._unknown_208 = 0;
601
+ (*worm)._unknown_198 = 0;
602
+ (*worm)._unknown_19c = 0;
603
+ (*worm).facing_direction_inv = 0;
604
+
605
+ // FUN_0050D450: usercall(ESI=worm), cleanup/landing check
606
+ call_worm_landing_check(worm, rb(0x50D450));
607
+
608
+ // Debug log block (ddgame+0x8144) omitted — only writes to debug file
609
+ }
610
+
611
+ /// Nuclear Test (subtype 16) — pure Rust port of 0x51EB00.
612
+ ///
613
+ /// Sends three messages to CTaskTurnGame: RaiseWater (0x59), NukeBlast (0x5A),
614
+ /// PoisonWorm (0x51), and plays two sounds. Gated by can_fire_subtype16.
615
+ ///
616
+ /// Convention: usercall(EAX=worm_state, ESI=worm, EDI=worm), plain RET.
617
+ unsafe fn fire_nuclear_test(worm: *mut CTaskWorm) {
618
+ use crate::audio::sound_ops as sound;
619
+
620
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
621
+ let entry = &*(*worm).active_weapon_entry;
622
+ let team = lookup_turn_game(worm);
623
+
624
+ // Message 0x59 (RaiseWater): buf[0]=fire_method, buf[4]=8
625
+ if !team.is_null() {
626
+ let mut buf = [0u8; 0x40C];
627
+ buf[0..4].copy_from_slice(&entry.fire_method.to_ne_bytes());
628
+ buf[4..8].copy_from_slice(&8i32.to_ne_bytes());
629
+ CTaskTurnGame::handle_message_raw(
630
+ team,
631
+ worm as *mut crate::task::CTask,
632
+ 0x59,
633
+ 0x408,
634
+ buf.as_ptr(),
635
+ );
636
+ }
637
+
638
+ // Message 0x5A (NukeBlast): buf[0]=8
639
+ let team = lookup_turn_game(worm);
640
+ if !team.is_null() {
641
+ let mut buf = [0u8; 0x40C];
642
+ buf[0..4].copy_from_slice(&8i32.to_ne_bytes());
643
+ CTaskTurnGame::handle_message_raw(
644
+ team,
645
+ worm as *mut crate::task::CTask,
646
+ 0x5A,
647
+ 0x408,
648
+ buf.as_ptr(),
649
+ );
650
+ }
651
+
652
+ // PlaySoundGlobal(IndianAnthem, 8, 0x10000, 0x10000)
653
+ sound::queue_sound(
654
+ ddgame,
655
+ KnownSoundId::IndianAnthem.into(),
656
+ 8,
657
+ Fixed::ONE,
658
+ Fixed::ONE,
659
+ );
660
+
661
+ // Message 0x51 (PoisonWorm): buf[0]=shot_count, buf[4]=2, buf[8]=team_index
662
+ let team = lookup_turn_game(worm);
663
+ if !team.is_null() {
664
+ let mut buf = [0u8; 0x40C];
665
+ buf[0..4].copy_from_slice(&entry.fire_params.shot_count.to_ne_bytes());
666
+ buf[4..8].copy_from_slice(&2i32.to_ne_bytes());
667
+ buf[8..12].copy_from_slice(&(*worm).team_index.to_ne_bytes());
668
+ CTaskTurnGame::handle_message_raw(
669
+ team,
670
+ worm as *mut crate::task::CTask,
671
+ 0x51,
672
+ 0x408,
673
+ buf.as_ptr(),
674
+ );
675
+ }
676
+
677
+ // PlaySoundGlobal(NukeFlash, 5, 0x10000, 0x10000)
678
+ sound::queue_sound(
679
+ ddgame,
680
+ KnownSoundId::NukeFlash.into(),
681
+ 5,
682
+ Fixed::ONE,
683
+ Fixed::ONE,
684
+ );
685
+ }
686
+
687
+ /// Bridge: FUN_00547C30 — usercall(EAX=0x80000, ECX=x) + stdcall(y, 0,0,0, 600, 0x10000, 0x1999).
688
+ #[unsafe(naked)]
689
+ unsafe extern "C" fn call_spawn_effect(_x: i32, _y: i32, _addr: u32) {
690
+ core::arch::naked_asm!(
691
+ "push ebx",
692
+ // Stack: 1 save(4) + ret(4) = 8 to first arg
693
+ "mov ecx, [esp+8]", // x
694
+ "mov ebx, [esp+16]", // addr
695
+ "push 0x1999",
696
+ "push 0x10000",
697
+ "push 0x258", // 600
698
+ "push 0",
699
+ "push 0",
700
+ "push 0",
701
+ "push [esp+36]", // y (8 + 4 + 6*4 = 36)
702
+ "mov eax, 0x80000",
703
+ "call ebx",
704
+ "pop ebx",
705
+ "ret",
706
+ );
707
+ }
708
+
709
+ /// Bridge: FUN_004FE070 — usercall(ESI=worm, EDI=y) + stdcall(x). Plain RET.
710
+ #[unsafe(naked)]
711
+ unsafe extern "C" fn call_position_update(_worm: *mut CTaskWorm, _x: i32, _y: i32, _addr: u32) {
712
+ core::arch::naked_asm!(
713
+ "push ebx",
714
+ "push esi",
715
+ "push edi",
716
+ // Stack: 3 saves(12) + ret(4) = 16 to first arg
717
+ "mov esi, [esp+16]", // worm
718
+ "mov edi, [esp+24]", // y
719
+ "mov ebx, [esp+28]", // addr
720
+ "push [esp+20]", // x
721
+ "call ebx",
722
+ "pop edi",
723
+ "pop esi",
724
+ "pop ebx",
725
+ "ret",
726
+ );
727
+ }
728
+
729
+ /// Bridge: FUN_0050D450 — usercall(ESI=worm). Plain RET.
730
+ #[unsafe(naked)]
731
+ unsafe extern "C" fn call_worm_landing_check(_worm: *mut CTaskWorm, _addr: u32) {
732
+ core::arch::naked_asm!(
733
+ "push esi",
734
+ "mov esi, [esp+8]", // worm (1 save + ret = 8)
735
+ "call [esp+12]", // addr (8 + 4 = 12)
736
+ "pop esi",
737
+ "ret",
738
+ );
739
+ }
740
+
741
+ /// Scales of Justice (subtype 22) — pure Rust port of 0x51EC30.
742
+ ///
743
+ /// Sends message 0x5E to CTaskTurnGame, then plays a sound.
744
+ /// Convention: usercall(EAX=entry, ESI=worm, EDI=worm), plain RET.
745
+ unsafe fn fire_scales_of_justice(worm: *mut CTaskWorm) {
746
+ use crate::rebase::rb;
747
+
748
+ // Send message 0x5E to CTaskTurnGame
749
+ let team = lookup_turn_game(worm);
750
+ if !team.is_null() {
751
+ CTaskTurnGame::handle_message_raw(
752
+ team,
753
+ worm as *mut crate::task::CTask,
754
+ 0x5E,
755
+ 0,
756
+ core::ptr::null(),
757
+ );
758
+ }
759
+
760
+ // Play jet pack sound:
761
+ // FUN_0053EC70: usercall(EDI=0x6CB) + stdcall(timer_obj)
762
+ // FUN_005480F0: usercall(EAX=-21) + stdcall(worm, result, 0x17, &worm_name)
763
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
764
+ let sound_val = call_get_sound_val((*ddgame).timer_obj, rb(0x53EC70));
765
+ call_play_sound_usercall(
766
+ worm,
767
+ sound_val,
768
+ 0x17,
769
+ (*worm).worm_name.as_ptr(),
770
+ rb(0x5480F0),
771
+ );
772
+ }
773
+
774
+ /// Bridge: FUN_0053EC70 — usercall(EDI=0x6CB) + stdcall(timer_obj). Returns EAX.
775
+ #[unsafe(naked)]
776
+ unsafe extern "C" fn call_get_sound_val(_timer_obj: *mut u8, _addr: u32) -> u32 {
777
+ core::arch::naked_asm!(
778
+ "push ebx",
779
+ "push edi",
780
+ // Stack: 2 saves(8) + ret(4) = 12 to first arg
781
+ "mov edi, 0x6CB",
782
+ "mov ebx, [esp+16]", // addr
783
+ "push [esp+12]", // timer_obj
784
+ "call ebx",
785
+ "pop edi",
786
+ "pop ebx",
787
+ "ret",
788
+ );
789
+ }
790
+
791
+ /// Bridge: usercall(EAX=-21) + stdcall(4 params). Plain RET (callee doesn't clean).
792
+ #[unsafe(naked)]
793
+ unsafe extern "C" fn call_play_sound_usercall(
794
+ _worm: *mut CTaskWorm,
795
+ _sound_val: u32,
796
+ _param3: u32,
797
+ _name: *const u8,
798
+ _addr: u32,
799
+ ) {
800
+ core::arch::naked_asm!(
801
+ "push ebx",
802
+ // Stack: 1 save(4) + ret(4) = 8 to first arg
803
+ "mov ebx, [esp+24]", // addr (8 + 4*4 = 24)
804
+ "push [esp+20]", // name
805
+ "push [esp+20]", // param3 (shifted +4)
806
+ "push [esp+20]", // sound_val (shifted +8)
807
+ "push [esp+20]", // worm (shifted +12)
808
+ "mov eax, 0xFFFFFFEB", // EAX = -21 (usercall param)
809
+ "call ebx",
810
+ "pop ebx",
811
+ "ret",
812
+ );
813
+ }
814
+
815
+ /// Armageddon (subtype 24) — pure Rust port of 0x51EA60.
816
+ ///
817
+ /// Sends message 0x5B to CTaskTurnGame with weapon/team info, then conditionally
818
+ /// sets a gravity center point via FUN_00547E70.
819
+ /// Convention: usercall(EAX=entry, ESI=worm, EDI=worm), plain RET.
820
+ ///
821
+ unsafe fn fire_armageddon(worm: *mut CTaskWorm) {
822
+ use crate::rebase::rb;
823
+
824
+ // Send message 0x5B (Armageddon) to CTaskTurnGame with weapon info buffer.
825
+ //
826
+ // The original allocates a 0x410-byte stack buffer, writes fields at offsets
827
+ // 0x04/0x08/0x0C/0x10 from the buffer base, then passes (buffer_base + 4)
828
+ // as the data pointer to HandleMessage (LEA ECX,[ESP+0x8] after one PUSH
829
+ // was cleaned by the SharedData lookup). So HandleMessage sees:
830
+ // data[0x00] = 100 (0x64), data[0x04] = 166 (0xA6),
831
+ // data[0x08] = weapon_id, data[0x0C] = team_index
832
+ let team = lookup_turn_game(worm);
833
+ if !team.is_null() {
834
+ let mut buf = [0u8; 0x410];
835
+ buf[0x00..0x04].copy_from_slice(&100i32.to_ne_bytes());
836
+ buf[0x04..0x08].copy_from_slice(&166i32.to_ne_bytes());
837
+ buf[0x08..0x0C].copy_from_slice(&((*worm).selected_weapon as u32).to_ne_bytes());
838
+ buf[0x0C..0x10].copy_from_slice(&(*worm).team_index.to_ne_bytes());
839
+
840
+ CTaskTurnGame::handle_message_raw(
841
+ team,
842
+ worm as *mut crate::task::CTask,
843
+ 0x5B,
844
+ 0x408,
845
+ buf.as_ptr(),
846
+ );
847
+ }
848
+
849
+ // Re-read DDGame AFTER HandleMessage — the original does this (MOV EAX,[ESI+0x2C]
850
+ // at 0x51EAB0 is after the CALL), and HandleMessage may modify game state.
851
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
852
+ let game_version = (*(*ddgame).game_info).game_version;
853
+
854
+ // If old game version or worm state 0x69, set gravity center
855
+ if game_version < 0x50 || (*worm).is_in_state(WormState::Unknown_0x69) {
856
+ let ddgame_raw = ddgame as *const u8;
857
+ let level_w = *(ddgame_raw.add(0x77C0) as *const i32);
858
+ let level_h = *(ddgame_raw.add(0x77C4) as *const i32);
859
+ // SHL 16; CDQ; SUB EAX,EDX; SAR 1 — round-toward-zero divide by 2
860
+ let half_x = ((level_w << 16) + (if level_w < 0 { 1 } else { 0 })) >> 1;
861
+ let half_y = ((level_h << 16) + (if level_h < 0 { 1 } else { 0 })) >> 1;
862
+
863
+ call_set_gravity_center(worm, half_x, half_y, rb(0x547E70));
864
+ }
865
+ }
866
+
867
+ /// Bridge: usercall(ECX=half_x, EDX=half_y) + stdcall(worm), RET 0x4.
868
+ #[unsafe(naked)]
869
+ unsafe extern "C" fn call_set_gravity_center(
870
+ _worm: *mut CTaskWorm,
871
+ _half_x: i32,
872
+ _half_y: i32,
873
+ _addr: u32,
874
+ ) {
875
+ core::arch::naked_asm!(
876
+ "push ebx",
877
+ // Stack: 1 save(4) + ret(4) = 8 to first arg
878
+ "mov ecx, [esp+12]", // half_x
879
+ "mov edx, [esp+16]", // half_y
880
+ "mov ebx, [esp+20]", // addr
881
+ "push [esp+8]", // worm (shifted by 0 extra pushes before this)
882
+ "call ebx", // RET 0x4 cleans worm
883
+ "pop ebx",
884
+ "ret",
885
+ );
886
+ }
887
+
888
+ /// DragonBall (type 4 subtype 3) — pure Rust port of 0x51E350.
889
+ ///
890
+ /// Allocates a CTaskGirder (0xA4 bytes), copies 7 DWORDs from fire_params
891
+ /// as constructor arguments, and calls the constructor. The constructor handles
892
+ /// actually placing the girder on the landscape.
893
+ ///
894
+ /// Convention: stdcall(worm, fire_params, local_struct), RET 0xC.
895
+ unsafe fn fire_dragon_ball(
896
+ worm: *mut CTaskWorm,
897
+ fire_params: *const WeaponFireParams,
898
+ local_struct: *const u8,
899
+ ) {
900
+ use crate::rebase::rb;
901
+ use crate::task::SharedDataTable;
902
+ use crate::wa_alloc::wa_malloc;
903
+
904
+ // Look up parent task via SharedData (same key as CreateWeaponProjectile)
905
+ let table = SharedDataTable::from_task(worm as *const CTask);
906
+ let parent = table.lookup(0, 0x19);
907
+
908
+ // Allocate CTaskGirder (0xA4 bytes), zero first 0x84
909
+ let buffer = wa_malloc(0xA4);
910
+ if buffer.is_null() {
911
+ return;
912
+ }
913
+ core::ptr::write_bytes(buffer, 0, 0x84);
914
+
915
+ // CTaskGirder::Constructor — usercall(EAX=parent) +
916
+ // stdcall(this, 7×fire_param DWORDs, local_struct), RET 0x24.
917
+ // Copy 7 DWORDs from fire_params onto the stack via the naked bridge.
918
+ call_girder_ctor(
919
+ buffer,
920
+ parent as *mut u8,
921
+ fire_params,
922
+ local_struct,
923
+ rb(0x550890),
924
+ );
925
+ }
926
+
927
+ /// Bridge: CTaskGirder::Constructor — usercall(EAX=parent) +
928
+ /// stdcall(this, 7 DWORDs from fire_params, local_struct), RET 0x24.
929
+ ///
930
+ /// The original copies 7 DWORDs from fire_params onto the stack via REP MOVSD.
931
+ /// We replicate this by pushing them individually in reverse order.
932
+ #[unsafe(naked)]
933
+ unsafe extern "C" fn call_girder_ctor(
934
+ _this: *mut u8,
935
+ _parent: *mut u8,
936
+ _fire_params: *const WeaponFireParams,
937
+ _local_struct: *const u8,
938
+ _addr: u32,
939
+ ) {
940
+ core::arch::naked_asm!(
941
+ "push ebx",
942
+ "push esi",
943
+ "push edi",
944
+ // Stack: 3 saves(12) + ret(4) = 16 to first arg
945
+ // Args: this=+16, parent=+20, fire_params=+24, local_struct=+28, addr=+32
946
+ "mov esi, [esp+24]", // ESI = fire_params
947
+ "mov eax, [esp+20]", // EAX = parent (usercall)
948
+ "mov ebx, [esp+32]", // EBX = ctor address
949
+ // Push constructor args in reverse: local_struct, 7 DWORDs, this
950
+ "push [esp+28]", // local_struct (B+28 → stack pos 1)
951
+ "push [esi+24]", // fire_params[6]
952
+ "push [esi+20]", // fire_params[5]
953
+ "push [esi+16]", // fire_params[4]
954
+ "push [esi+12]", // fire_params[3]
955
+ "push [esi+8]", // fire_params[2]
956
+ "push [esi+4]", // fire_params[1]
957
+ "push [esi]", // fire_params[0] (B-28 → stack pos 8)
958
+ "push [esp+48]", // this: B-32+48 = B+16 ✓
959
+ "call ebx", // RET 0x24 cleans 9 params
960
+ "pop edi",
961
+ "pop esi",
962
+ "pop ebx",
963
+ "ret",
964
+ );
965
+ }
966
+
967
+ /// Girder/GirderPack (subtype 17) — pure Rust port of 0x51E920.
968
+ ///
969
+ /// Plays a sound, optionally creates a visual overlay on the
970
+ /// landscape and increments worm counters. The visual/counter path only runs
971
+ /// when CTaskWorm+0x2EC (weapon_param_3) is nonzero.
972
+ ///
973
+ /// Convention: usercall(EAX=worm, ESI=worm, EDI=worm), plain RET.
974
+ unsafe fn fire_girder(worm: *mut CTaskWorm) {
975
+ use crate::audio::sound_ops as sound;
976
+
977
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
978
+ let game_version = (*(*ddgame).game_info).game_version;
979
+
980
+ // Read girder position and sprite index from CTaskWorm fields
981
+ let girder_x = (*worm).weapon_param_1;
982
+ let girder_y = (*worm).weapon_param_2;
983
+ let girder_sprite = (*worm).weapon_param_3;
984
+
985
+ // Choose sound: 0x70 if girder has sprite or old version, else 0x73
986
+ let sound_id: u32 = if girder_sprite != 0 || game_version < 0x21 {
987
+ 0x70
988
+ } else {
989
+ 0x73
990
+ };
991
+
992
+ // Queue sound and set position to the girder location (local sound)
993
+ if let Some(entry) = sound::queue_sound(ddgame, SoundId(sound_id), 3, Fixed::ONE, Fixed::ONE) {
994
+ (*entry).is_local = 1;
995
+ (*entry).pos_x = girder_x as u32;
996
+ (*entry).pos_y = girder_y as u32;
997
+ }
998
+
999
+ // If girder has a sprite, apply the visual overlay and update counters
1000
+ if girder_sprite != 0 {
1001
+ // Call PCLandscape vtable[5] to create girder overlay
1002
+ let landscape = (*ddgame).landscape as *mut u8;
1003
+ let landscape_vt = *(landscape as *const *const usize);
1004
+ let girder_visual: unsafe extern "thiscall" fn(*mut u8, i32, i32, *mut u8, *mut u8) =
1005
+ core::mem::transmute(*landscape_vt.add(5));
1006
+ let sprite1 = (*ddgame).sprite_cache_2[girder_sprite as usize];
1007
+ let sprite2 = (*ddgame).sprite_cache_2[19 + girder_sprite as usize];
1008
+ girder_visual(landscape, girder_x >> 16, girder_y >> 16, sprite1, sprite2);
1009
+
1010
+ // Increment WormEntry counters
1011
+ let arena =
1012
+ crate::engine::ddgame::TeamArenaRef::from_ptr(&raw mut (*ddgame).team_arena);
1013
+ let team_index = (*worm).team_index as usize;
1014
+ let worm_index = (*worm).worm_index as usize;
1015
+ let entry = arena.team_worm_mut(team_index, worm_index);
1016
+ entry.turn_action_counter_Maybe += 3;
1017
+ entry.effect_counter_04_Maybe += 10;
1018
+ }
1019
+ }
1020
+
1021
+ // ── SpecialImpact wrapper ─────────────────────────────────
1022
+
1023
+ /// Typed wrapper for SpecialImpact (0x5193D0).
1024
+ /// Convention: stdcall with 13 params (RET 0x34 = 52 bytes).
1025
+ ///
1026
+ /// Used by Drill, Prod, and other melee/impact weapons. Applies damage in
1027
+ /// a directional area from the worm's position.
1028
+ #[allow(clippy::too_many_arguments)]
1029
+ unsafe fn call_special_impact(
1030
+ worm: *mut CTaskWorm,
1031
+ x: i32,
1032
+ y: i32,
1033
+ radius_x: i32,
1034
+ radius_y: i32,
1035
+ weapon_type: i32,
1036
+ dx: i32,
1037
+ dy: i32,
1038
+ p8: i32,
1039
+ p9: i32,
1040
+ p10: i32,
1041
+ flags: u32,
1042
+ p12: i32,
1043
+ ) {
1044
+ use crate::rebase::rb;
1045
+ type SpecialImpactFn = unsafe extern "stdcall" fn(
1046
+ *mut CTaskWorm,
1047
+ i32,
1048
+ i32,
1049
+ i32,
1050
+ i32,
1051
+ i32,
1052
+ i32,
1053
+ i32,
1054
+ i32,
1055
+ i32,
1056
+ i32,
1057
+ u32,
1058
+ i32,
1059
+ );
1060
+ let func: SpecialImpactFn = core::mem::transmute(rb(va::SPECIAL_IMPACT));
1061
+ func(
1062
+ worm,
1063
+ x,
1064
+ y,
1065
+ radius_x,
1066
+ radius_y,
1067
+ weapon_type,
1068
+ dx,
1069
+ dy,
1070
+ p8,
1071
+ p9,
1072
+ p10,
1073
+ flags,
1074
+ p12,
1075
+ );
1076
+ }
1077
+
1078
+ /// Compute version-dependent flags for SpecialImpact.
1079
+ ///
1080
+ /// Pattern shared by Drill and Prod:
1081
+ /// - Base flags OR 0x20 if version >= 2
1082
+ /// - Base flags OR 0x10 if version >= 8
1083
+ fn special_impact_version_flags(base: u32, version: u8) -> u32 {
1084
+ let mut flags = base;
1085
+ if version >= 2 {
1086
+ flags |= 0x20;
1087
+ }
1088
+ if version >= 8 {
1089
+ flags |= 0x10;
1090
+ }
1091
+ flags
1092
+ }
1093
+
1094
+ /// BaseballBat (subtype 2) — pure Rust port of 0x51E3E0.
1095
+ ///
1096
+ /// Calls SpecialImpact with facing-offset position and scaled direction.
1097
+ /// The original is usercall(ECX=local_struct, ESI=worm) — the old bridge
1098
+ /// did not set ECX, so this port also fixes a latent bug.
1099
+ unsafe fn fire_drill(worm: *mut CTaskWorm, local_struct: *const u8) {
1100
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
1101
+ let version = (*ddgame).version_flag_4;
1102
+ let entry = &*(*worm).active_weapon_entry;
1103
+ let shot_count = entry.fire_params.shot_count;
1104
+ let weapon_type = entry.fire_method;
1105
+ let facing = (*worm).facing_direction_2;
1106
+
1107
+ // Cast local_struct to WeaponSpawnData for field access (offsets match)
1108
+ let spawn = &*(local_struct as *const WeaponSpawnData);
1109
+
1110
+ let x = facing * 0x1A_0000 + spawn.spawn_x.0;
1111
+ let y = spawn.spawn_y.0;
1112
+ let dx = (spawn.initial_speed_x.0 * shot_count) / 10;
1113
+ let dy = (spawn.initial_speed_y.0 * shot_count) / 10;
1114
+ let flags = special_impact_version_flags(0x21C4C, version);
1115
+
1116
+ call_special_impact(
1117
+ worm,
1118
+ x,
1119
+ y,
1120
+ 0x1A_0000,
1121
+ 0x1E_0000,
1122
+ weapon_type,
1123
+ dx,
1124
+ dy,
1125
+ 6,
1126
+ 0x61,
1127
+ 0x51,
1128
+ flags,
1129
+ 1,
1130
+ );
1131
+ }
1132
+
1133
+ /// Prod (subtype 9) — pure Rust port of 0x51E480.
1134
+ ///
1135
+ /// Like Drill but with trig interpolation on the spread angle.
1136
+ /// Convention: usercall(EDI=worm) + 1 stack param (local_struct), RET 0x4.
1137
+ unsafe fn fire_prod(worm: *mut CTaskWorm, local_struct: *const u8) {
1138
+ use crate::rebase::rb;
1139
+
1140
+ let ddgame = CTask::ddgame_raw(worm as *const CTask);
1141
+ let version = (*ddgame).version_flag_4;
1142
+ let entry = &*(*worm).active_weapon_entry;
1143
+ let shot_count = entry.fire_params.shot_count;
1144
+ let spread = entry.fire_params.spread;
1145
+ let weapon_type = entry.fire_method;
1146
+ let facing = (*worm).facing_direction_2;
1147
+
1148
+ let spawn = &*(local_struct as *const WeaponSpawnData);
1149
+
1150
+ // Convert spread (degrees) to engine angle units: (spread << 16) / 360
1151
+ let angle = ((spread as u32) << 16) / 0x168;
1152
+
1153
+ // Interpolated sin/cos lookup (same pattern as projectile_fire)
1154
+ let sin_table = rb(va::SIN_TABLE) as *const i32;
1155
+ let cos_table = sin_table.add(256);
1156
+
1157
+ let table_index = ((angle >> 6) & 0x3FF) as usize;
1158
+ let frac = ((angle & 0x3F) << 10) as i32;
1159
+
1160
+ let cos_base = *cos_table.add(table_index);
1161
+ let cos_next = *cos_table.add(table_index + 1);
1162
+ let cos_val = cos_base + fixed_mul(cos_next - cos_base, frac);
1163
+
1164
+ let sin_base = *sin_table.add(table_index);
1165
+ let sin_next = *sin_table.add(table_index + 1);
1166
+ let sin_val = sin_base + fixed_mul(sin_next - sin_base, frac);
1167
+
1168
+ // Scale trig results by shot_count and divide by 10.
1169
+ // In WA's coordinate system (Y increases downward), the vertical component is negated.
1170
+ // Original asm uses IMUL 0x99999999 (= -0x66666667) for dy, which negates the result.
1171
+ // dx = (sin_val * shot_count) / 10 * facing
1172
+ // dy = -(cos_val * shot_count) / 10
1173
+ let dx = ((sin_val * shot_count) / 10) * facing;
1174
+ let dy = -((cos_val * shot_count) / 10);
1175
+
1176
+ let x = facing * 0x6_0000 + spawn.spawn_x.0;
1177
+ let y = spawn.spawn_y.0;
1178
+ let flags = special_impact_version_flags(0xC4C, version);
1179
+
1180
+ call_special_impact(
1181
+ worm,
1182
+ x,
1183
+ y,
1184
+ 0xC_0000,
1185
+ 0xC_0000,
1186
+ weapon_type,
1187
+ dx,
1188
+ dy,
1189
+ 0,
1190
+ 0,
1191
+ 0,
1192
+ flags,
1193
+ 1,
1194
+ );
1195
+ }
1196
+
1197
+ // ── Naked asm bridges ───────────────────────────────────────
1198
+
1199
+ /// Bridge: ProjectileFire_Single — usercall(EDI=spawn_data, stack=[worm, fire_params]), RET 0x8.
1200
+ /// Args: (spawn_data, worm, fire_params, addr).
1201
+ #[unsafe(naked)]
1202
+ unsafe extern "C" fn call_projectile_fire_single(
1203
+ _spawn_data: *const WeaponSpawnData,
1204
+ _worm: *mut CTaskWorm,
1205
+ _fire_params: *const WeaponFireParams,
1206
+ _addr: u32,
1207
+ ) {
1208
+ core::arch::naked_asm!(
1209
+ "push ebx",
1210
+ "push esi",
1211
+ "push edi",
1212
+ // Stack: 3 saves(12) + ret(4) = 16 to first arg
1213
+ "mov edi, [esp+16]", // EDI = spawn_data
1214
+ "mov ebx, [esp+28]", // addr
1215
+ "push [esp+24]", // fire_params
1216
+ "push [esp+24]", // worm (shifted +4)
1217
+ "call ebx", // RET 0x8 cleans 2 params
1218
+ "pop edi",
1219
+ "pop esi",
1220
+ "pop ebx",
1221
+ "ret",
1222
+ );
1223
+ }
1224
+
1225
+ /// Bridge: CTaskMissile::Constructor — thiscall(ECX=this, parent, fire_params, spawn_data), RET 0xC.
1226
+ /// Args: (this, parent, fire_params, spawn_data, ctor_addr).
1227
+ #[unsafe(naked)]
1228
+ unsafe extern "C" fn call_missile_ctor(
1229
+ _this: *mut u8,
1230
+ _parent: *mut u8,
1231
+ _fire_params: *const WeaponFireParams,
1232
+ _spawn_data: *const u8,
1233
+ _addr: u32,
1234
+ ) {
1235
+ core::arch::naked_asm!(
1236
+ "push ebx",
1237
+ "push esi",
1238
+ "push edi",
1239
+ // Stack: 3 saves(12) + ret(4) = 16 to first arg
1240
+ "mov ecx, [esp+16]", // ECX = this (buffer)
1241
+ "mov ebx, [esp+32]", // addr (16 + 4*4 args = 32)
1242
+ "push [esp+28]", // spawn_data
1243
+ "push [esp+28]", // fire_params (shifted +4)
1244
+ "push [esp+28]", // parent (shifted +8)
1245
+ "call ebx", // thiscall: RET 0xC cleans 3 params
1246
+ "pop edi",
1247
+ "pop esi",
1248
+ "pop ebx",
1249
+ "ret",
1250
+ );
1251
+ }
1252
+
1253
+ // ── Object creation functions ───────────────────────────────
1254
+
1255
+ /// Rust implementation of CreateWeaponProjectile.
1256
+ ///
1257
+ /// Original: 0x51E0F0. Allocates CTaskMissile (0x40C bytes), looks up
1258
+ /// parent CTaskTurnGame via SharedData, calls the original constructor.
1259
+ pub unsafe fn create_weapon_projectile(
1260
+ worm: *mut CTaskWorm,
1261
+ fire_params: *const WeaponFireParams,
1262
+ local_struct: *const u8,
1263
+ ) {
1264
+ use crate::rebase::rb;
1265
+ use crate::task::SharedDataTable;
1266
+ use crate::wa_alloc::wa_malloc;
1267
+
1268
+ let ddgame = &mut *CTask::ddgame_raw(worm as *const CTask);
1269
+
1270
+ // Pool capacity check: pool_count + 7 must be <= 700
1271
+ if ddgame.object_pool_count + 7 > 700 {
1272
+ ddgame.show_pool_overflow_warning();
1273
+ return;
1274
+ }
1275
+
1276
+ // Look up parent CTaskTurnGame via SharedData (key_esi=0, key_edi=0x19)
1277
+ let table = SharedDataTable::from_task(worm as *const CTask);
1278
+ let parent = table.lookup(0, 0x19);
1279
+
1280
+ // Allocate CTaskMissile (0x40C bytes)
1281
+ let buffer = wa_malloc(0x40C);
1282
+ if buffer.is_null() {
1283
+ return;
1284
+ }
1285
+
1286
+ // Zero bytes 0x00..0x3EC (the original only zeros 0x3EC of 0x40C)
1287
+ core::ptr::write_bytes(buffer, 0, 0x3EC);
1288
+
1289
+ // Call original CTaskMissile::Constructor
1290
+ // thiscall(ECX=buffer, parent, fire_params, local_struct), RET 0xC
1291
+ call_missile_ctor(
1292
+ buffer,
1293
+ parent as *mut u8,
1294
+ fire_params,
1295
+ local_struct,
1296
+ rb(va::CTASK_MISSILE_CTOR),
1297
+ );
1298
+
1299
+ let _ = log_line(&format!(
1300
+ "[Weapon] CreateWeaponProjectile: worm=0x{:08X} missile=0x{:08X}",
1301
+ worm as u32, buffer as u32,
1302
+ ));
1303
+ }
1304
+
1305
+ /// Rust implementation of ProjectileFire.
1306
+ ///
1307
+ /// Algorithm (from disasm at 0x51DFB0):
1308
+ /// 1. Copy 11 DWORDs from local_struct (spawn template) to local buffer
1309
+ /// 2. Loop fire_params+0xC times:
1310
+ /// a. Advance game RNG
1311
+ /// b. Random spread angle from RNG × fire_params+0x10 / 360
1312
+ /// c. Cos/sin table lookup with linear interpolation
1313
+ /// d. 2D rotation matrix on template velocity
1314
+ /// e. Write rotated velocity into local spawn data
1315
+ /// f. Call ProjectileFire_Single(loop_counter, fire_params) with EDI=spawn_data
1316
+ pub unsafe fn projectile_fire(
1317
+ worm: *mut CTaskWorm,
1318
+ fire_params: *const WeaponFireParams,
1319
+ local_struct: *const WeaponSpawnData,
1320
+ ) {
1321
+ use crate::rebase::rb;
1322
+
1323
+ let params = &*fire_params;
1324
+ // collision_radius field is polymorphic — for ProjectileFire it holds the shot count
1325
+ let shot_count = params.collision_radius.0;
1326
+ if shot_count <= 0 {
1327
+ return;
1328
+ }
1329
+
1330
+ // Copy spawn template from caller's stack buffer
1331
+ let mut spawn_data = *local_struct;
1332
+
1333
+ // Read template velocity (will be rotated per-shot)
1334
+ let template_speed_x = spawn_data.initial_speed_x.0;
1335
+ let template_speed_y = spawn_data.initial_speed_y.0;
1336
+
1337
+ // Trig table: sin at SIN_TABLE, cos at SIN_TABLE + 256*4
1338
+ let sin_table = rb(va::SIN_TABLE) as *const i32;
1339
+ let cos_table = sin_table.add(256); // cos = sin offset by 256 entries (quarter turn)
1340
+
1341
+ let ddgame = &mut *CTask::ddgame_raw(worm as *const CTask);
1342
+
1343
+ for _i in 0..shot_count {
1344
+ // Advance game RNG (same LCG as ADVANCE_GAME_RNG at 0x53F320)
1345
+ let rng = ddgame.advance_rng();
1346
+
1347
+ // Compute spread angle: ((rng_low16 - 0x8000) * spread_param) / 360
1348
+ // _fp_04 field is polymorphic — for ProjectileFire it holds spread angle
1349
+ let rng_centered = (rng & 0xFFFF) as i32 - 0x8000;
1350
+ let spread_param = params._fp_04;
1351
+ let angle = (rng_centered * spread_param) / 360;
1352
+
1353
+ // Cos/sin table lookup with linear interpolation
1354
+ // Table index = (angle >> 6) & 0x3FF (1024 entries)
1355
+ // Fractional = (angle & 0x3F) << 10
1356
+ let table_index = ((angle >> 6) & 0x3FF) as usize;
1357
+ let frac = ((angle & 0x3F) << 10) as i32;
1358
+
1359
+ let cos_base = *cos_table.add(table_index);
1360
+ let cos_next = *cos_table.add(table_index + 1);
1361
+ let cos_val = cos_base + fixed_mul(cos_next - cos_base, frac);
1362
+
1363
+ let sin_base = *sin_table.add(table_index);
1364
+ let sin_next = *sin_table.add(table_index + 1);
1365
+ let sin_val = sin_base + fixed_mul(sin_next - sin_base, frac);
1366
+
1367
+ // 2D rotation matrix:
1368
+ // speed_x = cos * template_x + sin * template_y
1369
+ // speed_y = -sin * template_x + cos * template_y
1370
+ let speed_x = fixed_mul(cos_val, template_speed_x) + fixed_mul(sin_val, template_speed_y);
1371
+ let speed_y = fixed_mul(-sin_val, template_speed_x) + fixed_mul(cos_val, template_speed_y);
1372
+
1373
+ // Write rotated velocity into spawn data
1374
+ spawn_data.initial_speed_x = Fixed(speed_x);
1375
+ spawn_data.initial_speed_y = Fixed(speed_y);
1376
+
1377
+ // Call ProjectileFire_Single(worm, fire_params) with EDI=&spawn_data
1378
+ call_projectile_fire_single(
1379
+ &raw const spawn_data,
1380
+ worm,
1381
+ fire_params,
1382
+ rb(va::PROJECTILE_FIRE_SINGLE),
1383
+ );
1384
+ }
1385
+
1386
+ let _ = log_line(&format!(
1387
+ "[Weapon] ProjectileFire: worm=0x{:08X} shots={}",
1388
+ worm as u32, shot_count,
1389
+ ));
1390
+ }
1391
+
1392
+ /// Fixed-point 16.16 multiply: (a * b) >> 16, using full 64-bit intermediate.
1393
+ #[inline(always)]
1394
+ fn fixed_mul(a: i32, b: i32) -> i32 {
1395
+ ((a as i64 * b as i64) >> 16) as i32
1396
+ }
1397
+
1398
+ /// Rust implementation of CreateArrow (0x51ED90).
1399
+ ///
1400
+ /// Allocates a CTaskArrow (0x168 bytes), calls the original stdcall constructor.
1401
+ /// Used by Shotgun and Longbow.
1402
+ pub unsafe fn create_arrow(
1403
+ worm: *mut CTaskWorm,
1404
+ fire_params: *const WeaponFireParams,
1405
+ local_struct: *const u8,
1406
+ ) {
1407
+ use crate::rebase::rb;
1408
+ use crate::task::SharedDataTable;
1409
+ use crate::wa_alloc::wa_malloc;
1410
+
1411
+ let ddgame = &mut *CTask::ddgame_raw(worm as *const CTask);
1412
+
1413
+ // Pool capacity check: pool_count + 2 must be <= 700
1414
+ if ddgame.object_pool_count + 2 > 700 {
1415
+ ddgame.show_pool_overflow_warning();
1416
+ return;
1417
+ }
1418
+
1419
+ // Look up parent CTaskTurnGame via SharedData (key 0, 0x19)
1420
+ let table = SharedDataTable::from_task(worm as *const CTask);
1421
+ let parent = table.lookup(0, 0x19);
1422
+
1423
+ // Allocate CTaskArrow (0x168 bytes)
1424
+ let buffer = wa_malloc(0x168);
1425
+ if buffer.is_null() {
1426
+ return;
1427
+ }
1428
+ core::ptr::write_bytes(buffer, 0, 0x148);
1429
+
1430
+ // CTaskArrow::Constructor — stdcall(this, parent, fire_params, local_struct), RET 0x10
1431
+ let ctor: unsafe extern "stdcall" fn(*mut u8, *mut u8, *const WeaponFireParams, *const u8) =
1432
+ core::mem::transmute(rb(va::CTASK_ARROW_CTOR));
1433
+ ctor(buffer, parent as *mut u8, fire_params, local_struct);
1434
+
1435
+ let _ = log_line(&format!(
1436
+ "[Weapon] CreateArrow: worm=0x{:08X} arrow=0x{:08X}",
1437
+ worm as u32, buffer as u32,
1438
+ ));
1439
+ }
crates/openwa-core/src/game/weapon_release.rs ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ //! WeaponRelease orchestration and spawn effect.
2
+ //!
3
+ //! Pure Rust reimplementation of WA.exe WeaponRelease (0x51C3D0) and
4
+ //! SpawnEffect (0x547C30). Called from wormkit hook trampolines.
5
+
6
+ use crate::audio::{KnownSoundId, SoundId};
7
+ use crate::fixed::Fixed;
8
+ use crate::game::Weapon;
9
+ use crate::log::log_line;
10
+ use crate::task::turn_game::CTaskTurnGame;
11
+ use crate::task::worm::{CTaskWorm, WormState};
12
+ use crate::task::{CGameTask, CTask, SharedDataTable, Task};
13
+
14
+ use crate::audio::sound_ops as sound;
15
+ use crate::game::weapon_fire::{self, WeaponReleaseContext};
16
+
17
+ // ── Weapon category classifiers (pure Rust) ─────────────────
18
+
19
+ /// IsSuperWeapon (0x565960): returns true for "super weapon" IDs.
20
+ /// For SelectWorm, returns the DDGame+0x7E3F version flag (mode-dependent).
21
+ pub fn is_super_weapon(weapon: Weapon, ddgame_7e3f: u8) -> bool {
22
+ use Weapon::*;
23
+ matches!(
24
+ weapon,
25
+ Earthquake
26
+ | SuicideBomber
27
+ | MailStrike
28
+ | MineStrike
29
+ | MoleSquadron
30
+ | GirderPack
31
+ | ScalesOfJustice
32
+ | SuperBanana
33
+ | SalvationArmy
34
+ | MbBomb
35
+ | MingVase
36
+ | SheepStrike
37
+ | CarpetBomb
38
+ | Donkey
39
+ | NuclearTest
40
+ | Armageddon
41
+ | Freeze
42
+ | MagicBullet
43
+ ) || (weapon == Weapon::SelectWorm && ddgame_7e3f != 0)
44
+ }
45
+
46
+ /// FUN_005658C0: weapon category A — homing/animal/special projectile weapons.
47
+ pub fn is_weapon_category_a(weapon: Weapon) -> bool {
48
+ use Weapon::*;
49
+ matches!(
50
+ weapon,
51
+ HomingPigeon
52
+ | SheepLauncher
53
+ | Sheep
54
+ | SuperSheep
55
+ | AquaSheep
56
+ | MoleBomb
57
+ | MoleSquadron
58
+ | SalvationArmy
59
+ | MbBomb
60
+ | Skunk
61
+ | SheepStrike
62
+ | MadCow
63
+ | OldWoman
64
+ | Donkey
65
+ )
66
+ }
67
+
68
+ /// FUN_00565920: weapon category B — fire/napalm weapons.
69
+ pub fn is_weapon_category_b(weapon: Weapon) -> bool {
70
+ use Weapon::*;
71
+ matches!(
72
+ weapon,
73
+ NapalmStrike | FlameThrower | PetrolBomb | SheepStrike
74
+ )
75
+ }
76
+
77
+ // ── Main implementation ─────────────────────────────────────
78
+
79
+ pub unsafe fn weapon_release(
80
+ worm: *mut CTaskWorm,
81
+ spawn_x: u32,
82
+ spawn_y: u32,
83
+ aim_dir_x: Fixed,
84
+ aim_dir_y: Fixed,
85
+ ) {
86
+ let w = &*worm;
87
+
88
+ // Initialize context struct to zero
89
+ let mut ctx = WeaponReleaseContext {
90
+ team_id: 0,
91
+ worm_id: 0,
92
+ spawn_x: 0,
93
+ spawn_y: 0,
94
+ spawn_offset_x: 0,
95
+ spawn_offset_y: 0,
96
+ ammo_per_turn: 0,
97
+ ammo_per_slot: 0,
98
+ _zero: 0,
99
+ delay: 0,
100
+ network_delay: 0,
101
+ };
102
+
103
+ // ── 1. Sync check ───────────────────────────────────────
104
+ if w.fire_sync_frame_1 == w.fire_sync_frame_2 {
105
+ let g = &mut *w.ddgame();
106
+ g.render_slot_count = 0x0E;
107
+ for entry in &mut g.render_entries {
108
+ entry.active = 0;
109
+ }
110
+ g.render_state_flag = 0;
111
+ }
112
+
113
+ // ── 2. Populate context fields ──────────────────────────
114
+ let speed_x = w.base.pos_x;
115
+ let speed_y = w.base.pos_y;
116
+ ctx.team_id = w.team_index;
117
+ ctx.worm_id = w.worm_index;
118
+ ctx.ammo_per_turn = w.weapon_param_1 as u32;
119
+ ctx.spawn_x = spawn_x;
120
+ ctx.spawn_y = spawn_y;
121
+ ctx.ammo_per_slot = w.weapon_param_2 as u32;
122
+
123
+ let entry = w.active_weapon_entry;
124
+ let fire_type = (*entry).fire_type;
125
+ let special_subtype = (*entry).special_subtype;
126
+ let fire_method = (*entry).fire_method;
127
+
128
+ use crate::game::weapon::{FireMethod, FireType};
129
+
130
+ // ── 3. Spawn offset calculation ─────────────────────────
131
+ let scale = w.landscape_scale;
132
+
133
+ let (mut offset_x, mut offset_y) = (Fixed::ZERO, Fixed::ZERO);
134
+ match FireType::try_from(fire_type) {
135
+ Ok(FireType::Projectile) => match FireMethod::try_from(fire_method) {
136
+ Ok(FireMethod::PlacedExplosive) => {
137
+ offset_x = aim_dir_x * 24;
138
+ offset_y = aim_dir_y * 24;
139
+ }
140
+ Ok(FireMethod::ProjectileFire) => {
141
+ // Falls through to Strike (passthrough)
142
+ offset_x = aim_dir_x;
143
+ offset_y = aim_dir_y;
144
+ }
145
+ Ok(FireMethod::CreateWeaponProjectile) => {
146
+ offset_x = aim_dir_x * scale * 24;
147
+ offset_y = aim_dir_y * scale * 24;
148
+ }
149
+ Ok(FireMethod::CreateArrow) => {
150
+ offset_x = aim_dir_x * 20;
151
+ offset_y = aim_dir_y * 20;
152
+ }
153
+ _ => {}
154
+ },
155
+ Ok(FireType::Rope) => {
156
+ offset_x = aim_dir_x * scale * 24;
157
+ offset_y = aim_dir_y * scale * 24;
158
+ // Special Y adjustment for state 0x79
159
+ if w.is_in_state(WormState::Unknown_0x79) {
160
+ offset_y += w.base.speed_y;
161
+ }
162
+ }
163
+ Ok(FireType::Strike) => {
164
+ offset_x = aim_dir_x;
165
+ offset_y = aim_dir_y;
166
+ }
167
+ Ok(FireType::Special) => {
168
+ if (special_subtype as u32).wrapping_sub(1) < 0x18 {
169
+ offset_x = aim_dir_x;
170
+ offset_y = aim_dir_y;
171
+ }
172
+ }
173
+ _ => {}
174
+ }
175
+ ctx.spawn_offset_x = offset_x.0;
176
+ ctx.spawn_offset_y = offset_y.0;
177
+
178
+ // ── 4. Delay ────────────────────────────────────────────
179
+ if w.difficulty_level == 0 {
180
+ ctx.delay = 0x1E;
181
+ } else if w.difficulty_level == 1 {
182
+ ctx.delay = 0x3C;
183
+ }
184
+
185
+ // ── 5. Network timing ───────────────────────────────────
186
+ let game_info = (*w.ddgame()).game_info as *const u8;
187
+ let is_network = *game_info.add(0xD9D0);
188
+ let fe_version = *game_info.add(0xD9B1);
189
+
190
+ let mut adjust = 0i32;
191
+ let max_clients = if is_network == 0 {
192
+ 5
193
+ } else if fe_version < 0x1B {
194
+ 10
195
+ } else {
196
+ adjust = -1;
197
+ 10
198
+ };
199
+
200
+ let client_idx = w.network_client_index;
201
+ if ((client_idx - adjust) as u32) < ((max_clients - adjust) as u32) {
202
+ ctx.network_delay = (client_idx + 1) * 1000;
203
+ }
204
+
205
+ // ── 6. Girder/GirderPack special ────────────────────────
206
+ let weapon = w.selected_weapon;
207
+ if matches!(weapon, Weapon::Girder | Weapon::GirderPack) && w.weapon_param_3 == 0 {
208
+ (*worm).shot_data_1 = w.shot_data_2;
209
+ }
210
+
211
+ // ── 7. SharedData HandleMessage (msg 0x49) ──────────────
212
+ let mut msg_buf = [0u8; 0x408];
213
+ write_u32(&mut msg_buf, 0x00, w.team_index);
214
+ write_u32(&mut msg_buf, 0x04, w.worm_index);
215
+ write_u32(&mut msg_buf, 0x08, w.shot_data_1);
216
+ write_u32(&mut msg_buf, 0x0C, w.shot_data_2);
217
+ write_u32(&mut msg_buf, 0x10, w.fire_sync_frame_1 as u32);
218
+ write_u32(&mut msg_buf, 0x14, w.fire_sync_frame_2 as u32);
219
+ write_u32(&mut msg_buf, 0x18, if w._unknown_2cc != 0 { 1 } else { 0 });
220
+ write_u32(&mut msg_buf, 0x1C, weapon as u32);
221
+
222
+ let team = weapon_fire::lookup_turn_game(worm);
223
+ if !team.is_null() {
224
+ CTaskTurnGame::handle_message_raw(
225
+ team,
226
+ worm as *mut crate::task::CTask,
227
+ 0x49,
228
+ 0x408,
229
+ msg_buf.as_ptr(),
230
+ );
231
+ }
232
+
233
+ // ── 8. Weapon stat counters ─────────────────────────────
234
+ let g = &mut *CTask::ddgame_raw(worm as *const CTask);
235
+ let team_id = (*worm).team_index;
236
+ let worm_id = (*worm).worm_index;
237
+
238
+ if is_super_weapon(weapon, g.version_flag_3) {
239
+ *g.weapon_stat_counter(team_id, worm_id, 0x40D8) += 1;
240
+ }
241
+
242
+ // Powerup/utility weapons (JetPack..=CrateShower)
243
+ if (Weapon::JetPack..=Weapon::CrateShower).contains(&weapon) {
244
+ *g.weapon_stat_counter(team_id, worm_id, 0x40D4) += 1;
245
+ }
246
+
247
+ if is_weapon_category_a(weapon) {
248
+ *g.weapon_stat_counter(team_id, worm_id, 0x40D0) += 1;
249
+ }
250
+
251
+ if is_weapon_category_b(weapon) {
252
+ *g.weapon_stat_counter(team_id, worm_id, 0x40CC) += 1;
253
+ }
254
+
255
+ // ── 9. Sound dispatch + 10. Visual effect ───────────────
256
+ let task = worm as *mut CGameTask;
257
+ let mut do_effect = false;
258
+ let mut effect_state: u32 = 0x73;
259
+
260
+ let w = &*worm; // re-borrow after mutation above
261
+ let entry = w.active_weapon_entry;
262
+
263
+ match FireType::try_from((*entry).fire_type) {
264
+ Ok(FireType::Projectile) => match (*entry).special_subtype {
265
+ 1 => {
266
+ if w.sound_handle == 0 {
267
+ sound::play_worm_sound(worm, SoundId(0x1004E), Fixed::ONE);
268
+ }
269
+ do_effect = true;
270
+ effect_state = 0x73;
271
+ }
272
+ 2 => {
273
+ sound::play_sound_local(
274
+ task,
275
+ KnownSoundId::ThrowRelease,
276
+ 3,
277
+ Fixed::ONE,
278
+ Fixed::ONE,
279
+ );
280
+ sound::stop_worm_sound(worm);
281
+ }
282
+ 3 | 7 | 0xB | 0xC => {
283
+ sound::play_sound_local(
284
+ task,
285
+ KnownSoundId::RocketRelease,
286
+ 3,
287
+ Fixed::ONE,
288
+ Fixed::ONE,
289
+ );
290
+ sound::stop_worm_sound(worm);
291
+ }
292
+ 4 => {
293
+ if w.sound_handle == 0 {
294
+ sound::play_worm_sound(worm, SoundId(0x1004F), Fixed::ONE);
295
+ }
296
+ do_effect = true;
297
+ effect_state = 0x73;
298
+ }
299
+ 5 => {
300
+ sound::play_sound_local(task, KnownSoundId::ShotgunFire, 3, Fixed::ONE, Fixed::ONE);
301
+ do_effect = true;
302
+ effect_state = 0x75;
303
+ }
304
+ 6 => {
305
+ sound::play_sound_local(task, KnownSoundId::HandgunFire, 3, Fixed::ONE, Fixed::ONE);
306
+ do_effect = true;
307
+ effect_state = 0x73;
308
+ }
309
+ 10 => {
310
+ sound::play_sound_local(
311
+ task,
312
+ KnownSoundId::LongbowRelease,
313
+ 3,
314
+ Fixed::ONE,
315
+ Fixed::ONE,
316
+ );
317
+ sound::stop_worm_sound(worm);
318
+ }
319
+ _ => {}
320
+ },
321
+ Ok(FireType::Rope) => {
322
+ if w._unknown_2cc == 0 || w._unknown_2c8 == 1 {
323
+ let team_sound_raw = (*w.ddgame()).team_sound_id(team_id);
324
+ sound::play_sound_local(task, SoundId(team_sound_raw), 3, Fixed::ONE, Fixed::ONE);
325
+ }
326
+ }
327
+ // Type 3 (Strike): no sound
328
+ Ok(FireType::Special) => {
329
+ use crate::game::weapon::SpecialFireSubtype as S;
330
+ match S::try_from((*entry).special_subtype) {
331
+ Ok(S::BaseballBat) => {
332
+ sound::play_sound_local(
333
+ task,
334
+ KnownSoundId::BaseballBatRelease,
335
+ 3,
336
+ Fixed::ONE,
337
+ Fixed::ONE,
338
+ );
339
+ }
340
+ Ok(S::DragonBall) => {
341
+ sound::play_sound_local(
342
+ task,
343
+ SoundId((*entry).fire_method as u32),
344
+ 3,
345
+ Fixed::ONE,
346
+ Fixed::ONE,
347
+ );
348
+ }
349
+ Ok(S::Kamikaze) => {
350
+ // Sound ID from fire_params.spread (polymorphic use of field)
351
+ sound::play_sound_local(
352
+ task,
353
+ SoundId((*entry).fire_params.spread as u32),
354
+ 3,
355
+ Fixed::ONE,
356
+ Fixed::ONE,
357
+ );
358
+ }
359
+ Ok(S::Teleport) => {
360
+ if w._unknown_208 == 0 {
361
+ sound::play_sound_local(
362
+ task,
363
+ KnownSoundId::Teleport,
364
+ 3,
365
+ Fixed::ONE,
366
+ Fixed::ONE,
367
+ );
368
+ }
369
+ }
370
+ Ok(S::Blowtorch) => {
371
+ if w.sound_handle == 0 {
372
+ sound::play_worm_sound(worm, SoundId(0x10035), Fixed::ONE);
373
+ }
374
+ }
375
+ _ => {}
376
+ }
377
+ }
378
+ _ => {}
379
+ }
380
+
381
+ // ── 10. Visual effect (if triggered by sound dispatch) ──
382
+ if do_effect {
383
+ let ddgame = &mut *CTask::ddgame_raw(worm as *const CTask);
384
+ let gfx_handler = ddgame.game_state_stream as *const u8;
385
+ let palette = *(gfx_handler.add(0x22C) as *const u32);
386
+
387
+ let rng1 = ddgame.advance_effect_rng();
388
+ let rng2 = ddgame.advance_effect_rng();
389
+
390
+ let rng2_offset = (rng2 & 0xFFFF) as i32 - 0x18000;
391
+ let facing = (*worm).facing_direction_2;
392
+ let rng_scaled = rng2_offset * facing;
393
+
394
+ let rng1_offset = (rng1 & 0xFFFF) as i32 - 0x18000;
395
+
396
+ let facing_flag: u32 = if facing < 1 { 0x40000 } else { 0 };
397
+ let state_flag = facing_flag + effect_state;
398
+
399
+ spawn_effect(
400
+ worm,
401
+ 0x80000,
402
+ speed_x,
403
+ speed_y,
404
+ rng_scaled,
405
+ rng1_offset,
406
+ palette,
407
+ state_flag,
408
+ Fixed(0xA0000),
409
+ Fixed(0x1999),
410
+ );
411
+ }
412
+
413
+ // ── 11. Call FireWeapon ──────────────────────────────────
414
+ let entry = (*worm).active_weapon_entry;
415
+ weapon_fire::fire_weapon(entry, &ctx, worm);
416
+
417
+ let _ = log_line(&format!(
418
+ "[WeaponRelease] worm=0x{:08X} weapon={:?} type={} sub34={} sub38={}",
419
+ worm as u32, weapon, fire_type, special_subtype, fire_method,
420
+ ));
421
+ }
422
+
423
+ // ── Helper ──────────────────────────────────────────────────
424
+
425
+ #[inline(always)]
426
+ fn write_u32(buf: &mut [u8], offset: usize, value: u32) {
427
+ buf[offset..offset + 4].copy_from_slice(&value.to_ne_bytes());
428
+ }
429
+
430
+ // ── SpawnEffect (0x547C30) ──────────────────────────────────
431
+
432
+ /// Spawn a visual effect on the sprite anim entity. Pure Rust port of FUN_00547C30.
433
+ ///
434
+ /// Builds a 0x408-byte message buffer from the params, looks up CTaskSpriteAnim
435
+ /// via SharedData (entity type 0x1A), and sends HandleMessage(0x56).
436
+ ///
437
+ /// Called directly from `weapon_release` and via the hook trampoline
438
+ /// for all other WA callers (17 call sites).
439
+ pub unsafe fn spawn_effect(
440
+ worm: *mut CTaskWorm,
441
+ constant: u32,
442
+ speed_x: Fixed,
443
+ speed_y: Fixed,
444
+ rng_scaled: i32,
445
+ rng_offset: i32,
446
+ palette: u32,
447
+ state_flag: u32,
448
+ size: Fixed,
449
+ scale: Fixed,
450
+ ) {
451
+ // Build the message buffer matching the original stack layout.
452
+ // The original pushes ESI (worm ptr) then uses LEA to include it at offset 0.
453
+ let mut buf = [0u8; 0x408];
454
+ write_u32(&mut buf, 0x00, worm as u32);
455
+ write_u32(&mut buf, 0x04, constant);
456
+ write_u32(&mut buf, 0x08, speed_x.0 as u32);
457
+ write_u32(&mut buf, 0x0C, speed_y.0 as u32);
458
+ write_u32(&mut buf, 0x10, rng_scaled as u32);
459
+ write_u32(&mut buf, 0x14, rng_offset as u32);
460
+ // [0x18] = 0 (already zeroed)
461
+ write_u32(&mut buf, 0x1C, palette);
462
+ write_u32(&mut buf, 0x20, state_flag);
463
+ // [0x24] = 0 (already zeroed)
464
+ write_u32(&mut buf, 0x28, size.0 as u32);
465
+ write_u32(&mut buf, 0x2C, scale.0 as u32);
466
+
467
+ // SharedData lookup for entity type 0x1A (CTaskSpriteAnim)
468
+ let table = SharedDataTable::from_task(worm as *const CTask);
469
+ let entity = table.lookup(0, 0x1A);
470
+ if !entity.is_null() {
471
+ let vtable = *(entity as *const *const usize);
472
+ let handle_msg: unsafe extern "thiscall" fn(*mut u8, *mut u8, u32, u32, *const u8) =
473
+ core::mem::transmute(*vtable.add(2));
474
+ handle_msg(
475
+ entity as *mut u8,
476
+ worm as *mut u8,
477
+ 0x56,
478
+ 0x408,
479
+ buf.as_ptr(),
480
+ );
481
+ }
482
+ }
crates/openwa-core/src/task/cloud.rs CHANGED
@@ -74,3 +74,95 @@ const _: () = assert!(core::mem::size_of::<CTaskCloud>() == 0x74);
74
 
75
  // Generate typed vtable method wrappers: handle_message(), process_frame().
76
  bind_CTaskCloudVTable!(CTaskCloud, base.vtable);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  // Generate typed vtable method wrappers: handle_message(), process_frame().
76
  bind_CTaskCloudVTable!(CTaskCloud, base.vtable);
77
+
78
+ use crate::game::TaskMessage;
79
+ use crate::render::queue::{command_type, DrawSpriteCmd};
80
+
81
+ /// CTaskCloud::HandleMessage replacement — pure game logic.
82
+ ///
83
+ /// Handles three message types:
84
+ /// - FrameFinish: per-frame position update (parallax scroll with wind drift)
85
+ /// - RenderScene: draw sprite at computed position
86
+ /// - SetWind: set wind target from message data
87
+ ///
88
+ /// Always calls base CTask::HandleMessage at the end (broadcast to children).
89
+ pub unsafe extern "thiscall" fn cloud_handle_message(
90
+ this: *mut CTaskCloud,
91
+ sender: *mut CTask,
92
+ msg_type: u32,
93
+ size: u32,
94
+ data: *const u8,
95
+ ) {
96
+ let msg = TaskMessage::try_from(msg_type);
97
+
98
+ match msg {
99
+ Ok(TaskMessage::FrameFinish) => {
100
+ // Advance Y position
101
+ (*this).pos_y = Fixed((*this).pos_y.0 + (*this).vel_y.0);
102
+
103
+ // Advance X position: base velocity + wind * 10
104
+ let wind = (*this).wind_accel.0;
105
+ (*this).pos_x = Fixed((*this).pos_x.0 + (*this).vel_x.0 + wind * 10);
106
+
107
+ // Wrap X at landscape bounds (with 128.0 Fixed padding)
108
+ let ddgame = CTask::ddgame_raw(this as *const CTask);
109
+ let padding = Fixed::from_int(128);
110
+ let level_left = (*ddgame).level_bound_min_x - padding;
111
+ let level_right = (*ddgame).level_bound_max_x + padding;
112
+
113
+ if (*this).pos_x < level_left {
114
+ (*this).pos_x = level_right;
115
+ } else if (*this).pos_x > level_right {
116
+ (*this).pos_x = level_left;
117
+ }
118
+
119
+ // Converge wind_accel toward wind_target (clamp step to ±0x147)
120
+ let target = (*this).wind_target.0;
121
+ let current = (*this).wind_accel.0;
122
+ let diff = target - current;
123
+ if diff.abs() < 0x147 {
124
+ (*this).wind_accel = Fixed(target);
125
+ } else if current < target {
126
+ (*this).wind_accel = Fixed(current + 0x147);
127
+ } else {
128
+ (*this).wind_accel = Fixed(current - 0x147);
129
+ }
130
+ }
131
+
132
+ Ok(TaskMessage::RenderScene) => {
133
+ let ddgame = CTask::ddgame_raw(this as *const CTask);
134
+
135
+ // Only render when rendering phase == 5 (in-game rendering active)
136
+ if (*ddgame).render_phase == 5 {
137
+ // Compute parallax X offset: (vel_x + wind * 10) * parallax_scale
138
+ let scroll_speed = (*this).vel_x.0 + (*this).wind_accel.0 * 10;
139
+ let parallax_x =
140
+ ((scroll_speed as i64 * (*ddgame).parallax_scale as i64) >> 16) as i32;
141
+ let x = parallax_x + (*this).pos_x.0;
142
+
143
+ let rq = &mut *(*ddgame).render_queue;
144
+ if let Some(entry) = rq.alloc::<DrawSpriteCmd>() {
145
+ *entry = DrawSpriteCmd {
146
+ command_type: command_type::DRAW_SPRITE_LOCAL,
147
+ layer: (*this).layer_depth.0 as u32,
148
+ x_pos: x as u32 & 0xFFFF0000,
149
+ y_pos: (*this).pos_y.0 as u32 & 0xFFFF0000,
150
+ sprite_id: (*this).sprite_id,
151
+ frame: 0,
152
+ };
153
+ }
154
+ }
155
+ }
156
+
157
+ Ok(TaskMessage::SetWind) => {
158
+ if !data.is_null() {
159
+ (*this).wind_target = Fixed(*(data as *const i32));
160
+ }
161
+ }
162
+
163
+ _ => {}
164
+ }
165
+
166
+ // Broadcast to children — raw-pointer version avoids noalias UB
167
+ CTask::broadcast_message_raw(this as *mut CTask, sender, msg_type, size, data);
168
+ }
crates/openwa-core/src/task/filter.rs CHANGED
@@ -81,3 +81,25 @@ const _: () = assert!(core::mem::size_of::<CTaskFilter>() == 0xB4);
81
 
82
  // Generate typed vtable method wrappers: handle_message(), process_frame().
83
  bind_CTaskFilterVTable!(CTaskFilter, base.vtable);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
82
  // Generate typed vtable method wrappers: handle_message(), process_frame().
83
  bind_CTaskFilterVTable!(CTaskFilter, base.vtable);
84
+
85
+ /// CTaskFilter::HandleMessage replacement — pure game logic.
86
+ ///
87
+ /// Messages with `msg_type < 98` are only forwarded if
88
+ /// `subscription_table[msg_type] != 0`. Messages >= 98 always pass through.
89
+ /// Forwarding calls `broadcast_message` which propagates down to child tasks.
90
+ pub unsafe extern "thiscall" fn filter_handle_message(
91
+ this: *mut CTaskFilter,
92
+ sender: *mut CTask,
93
+ msg_type: u32,
94
+ size: u32,
95
+ data: *const u8,
96
+ ) {
97
+ // Check subscription table — messages >= 98 always pass through
98
+ let table = &(*this).subscription_table;
99
+ if (msg_type as usize) < table.len() && table[msg_type as usize] == 0 {
100
+ return; // message not subscribed — drop silently
101
+ }
102
+
103
+ // Broadcast to children — raw-pointer version avoids noalias UB
104
+ CTask::broadcast_message_raw(this as *mut CTask, sender, msg_type, size, data);
105
+ }
crates/openwa-wormkit/src/replacements/sound.rs CHANGED
@@ -1,17 +1,22 @@
1
- //! Sound playback replacements.
2
  //!
3
- //! Full Rust reimplementations of the two sound queue functions.
4
- //! Enable logging with `OPENWA_SOUND_LOG=1` environment variable.
5
  //!
6
  //! Hooks:
7
  //! - PlaySoundGlobal (0x546E20): __thiscall, ECX=CTask*, 4 stack params, RET 0x10
8
  //! - PlaySoundLocal (0x4FDFE0): __usercall, EAX+ECX+EDI + 2 stack params, RET 0x8
 
 
 
 
9
 
10
  use std::sync::atomic::Ordering;
11
 
12
  use openwa_core::address::va;
13
- use openwa_core::audio::{play_sound, play_sound_pooled, KnownSoundId, SoundId, SoundSlot};
14
- use openwa_core::engine::{DDGame, DDGameWrapper, SoundQueueEntry};
 
15
  use openwa_core::fixed::Fixed;
16
  use openwa_core::task::worm::CTaskWorm;
17
  use openwa_core::task::{CGameTask, CTask};
@@ -22,46 +27,7 @@ use crate::log_line;
22
  /// Whether sound logging is enabled (checked once at init).
23
  static SOUND_LOG_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
24
 
25
- // ============================================================
26
- // Core: sound queue insertion
27
- // ============================================================
28
-
29
- /// Insert a sound into DDGame's 16-slot queue.
30
- ///
31
- /// Returns a pointer to the new entry, or None if the queue is full
32
- /// or sound is disabled.
33
- pub unsafe fn queue_sound(
34
- ddgame: *mut DDGame,
35
- sound_id: SoundId,
36
- flags: u32,
37
- volume: Fixed,
38
- pitch: Fixed,
39
- ) -> Option<*mut SoundQueueEntry> {
40
- let g = &mut *ddgame;
41
- if g.sound_queue_count >= 16 || g.sound.is_null() {
42
- return None;
43
- }
44
- let entry = &mut g.sound_queue[g.sound_queue_count as usize];
45
- *entry = SoundQueueEntry {
46
- sound_id: sound_id.0,
47
- flags,
48
- volume: volume.0 as u32,
49
- pitch: pitch.0 as u32,
50
- reserved: 0,
51
- is_local: 0,
52
- _pad: [0; 3],
53
- pos_x: 0,
54
- pos_y: 0,
55
- secondary_vtable: 0,
56
- };
57
- g.sound_queue_count += 1;
58
- Some(entry)
59
- }
60
-
61
- // ============================================================
62
- // PlaySoundGlobal (0x546E20)
63
- // ============================================================
64
- // __thiscall: ECX = CTask* this, 4 stack params, RET 0x10
65
 
66
  unsafe extern "thiscall" fn hook_play_sound_global(
67
  this: *const CGameTask,
@@ -80,14 +46,11 @@ unsafe extern "thiscall" fn hook_play_sound_global(
80
  ));
81
  }
82
 
83
- queue_sound((*this).base.ddgame, SoundId(sound_id), flags, volume, pitch).is_some() as u32
 
84
  }
85
 
86
- // ============================================================
87
- // PlaySoundLocal (0x4FDFE0)
88
- // ============================================================
89
- // __usercall: EAX=pitch, ECX=volume, EDI=task, stack[0]=sound_id, stack[1]=flags
90
- // RET 0x8
91
 
92
  hook::usercall_trampoline!(fn trampoline_play_sound_local; impl_fn = play_sound_local_impl;
93
  regs = [eax, ecx, edi]; stack_params = 2; ret_bytes = "0x8");
@@ -109,175 +72,14 @@ unsafe extern "cdecl" fn play_sound_local_impl(
109
  ));
110
  }
111
 
112
- let gt = &*task;
113
- let ddgame = gt.base.ddgame;
114
- let entry = match queue_sound(ddgame, SoundId(sound_id), flags, volume, pitch) {
115
- Some(e) => e,
116
- None => return 0,
117
- };
118
-
119
- // Mark as local sound
120
- (*entry).is_local = 1;
121
-
122
- // Store pointer to task's sound emitter sub-object (CGameTask+0xE8)
123
- let emitter = &gt.sound_emitter;
124
- (*entry).secondary_vtable = emitter as *const _ as u32;
125
-
126
- // Call GetPosition(this, &pos_x, &pos_y) via typed vtable
127
- ((*emitter.vtable).get_position)(emitter, &mut (*entry).pos_x, &mut (*entry).pos_y);
128
-
129
- // Increment local sound count
130
- (*task).sound_emitter.local_sound_count += 1;
131
-
132
- 1
133
- }
134
-
135
- /// Play a local sound on a task — Rust-callable version of PlaySoundLocal (0x4FDFE0).
136
- ///
137
- /// Queues the sound, marks it as local, records the emitter position, and
138
- /// increments the task's local sound count. Returns true on success.
139
- pub(crate) unsafe fn play_sound_local(
140
- task: *mut CGameTask,
141
- sound_id: impl Into<SoundId>,
142
- flags: u32,
143
- volume: Fixed,
144
- pitch: Fixed,
145
- ) -> bool {
146
- let gt = &*task;
147
- let ddgame = gt.base.ddgame;
148
- let entry = match queue_sound(ddgame, sound_id.into(), flags, volume, pitch) {
149
- Some(e) => e,
150
- None => return false,
151
- };
152
-
153
- (*entry).is_local = 1;
154
-
155
- let emitter = &gt.sound_emitter;
156
- (*entry).secondary_vtable = emitter as *const _ as u32;
157
- ((*emitter.vtable).get_position)(emitter, &mut (*entry).pos_x, &mut (*entry).pos_y);
158
-
159
- (*task).sound_emitter.local_sound_count += 1;
160
- true
161
- }
162
-
163
- // ============================================================
164
- // Worm sound functions (streaming sound handle at CTaskWorm+0x3B0)
165
- // ============================================================
166
-
167
- /// Stop the worm's active streaming sound. Port of FUN_00515180.
168
- ///
169
- /// Reads the sound handle from `worm.sound_handle`, dispatches to either
170
- /// DSSound::stop_channel (regular) or ActiveSoundTable::stop_sound (streaming,
171
- /// handle has bit 30 set), then clears the handle.
172
- pub(crate) unsafe fn stop_worm_sound(worm: *mut CTaskWorm) {
173
- let handle = (*worm).sound_handle;
174
- if handle != 0 {
175
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
176
- let sound = (*ddgame).sound;
177
- if !sound.is_null() && (handle as i32) >= 0 {
178
- if handle & 0x40000000 != 0 {
179
- // Streaming sound — stop via ActiveSoundTable
180
- if !(*ddgame).active_sounds.is_null() {
181
- (*(*ddgame).active_sounds).stop_sound(handle & !0x40000000);
182
- }
183
- } else {
184
- // Regular DSSound channel
185
- ((*(*sound).vtable).stop_channel)(sound, handle as i32);
186
- }
187
- }
188
- }
189
- (*worm).sound_handle = 0;
190
- }
191
-
192
- /// Stop current worm sound, then start a new streaming sound.
193
- /// Port of FUN_005150D0.
194
- ///
195
- /// Stops the current sound (same logic as [`stop_worm_sound`] but with
196
- /// reversed condition order matching the original), then calls the WA
197
- /// streaming load-and-play function (FUN_00546c20) and stores the new handle.
198
- pub(crate) unsafe fn play_worm_sound(worm: *mut CTaskWorm, sound_id: SoundId, volume: Fixed) {
199
- let handle = (*worm).sound_handle;
200
- if handle != 0 {
201
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
202
- let sound = (*ddgame).sound;
203
- if !sound.is_null() && (handle as i32) >= 0 {
204
- if handle & 0x40000000 == 0 {
205
- // Regular DSSound channel — stop via vtable
206
- ((*(*sound).vtable).stop_channel)(sound, handle as i32);
207
- } else {
208
- // Streaming sound — stop via ActiveSoundTable
209
- if !(*ddgame).active_sounds.is_null() {
210
- (*(*ddgame).active_sounds).stop_sound(handle & !0x40000000);
211
- }
212
- }
213
- }
214
- }
215
- // Start new streaming sound via WA function (FUN_00546c20)
216
- // FUN_005150D0 hardcodes flags=3
217
- let new_handle = call_load_and_play_streaming(worm, sound_id.0, 3, volume.0 as u32);
218
- (*worm).sound_handle = new_handle;
219
  }
220
 
221
- /// Stop+play on the secondary sound handle (CTaskWorm+0x3B4).
222
- /// Port of FUN_00515020 (23 callers in WA).
223
- ///
224
- /// Stops any active sound on `sound_handle_2`, then plays a new streaming
225
- /// sound. Has a special case for sound 0x36 (Teleport) when the worm's Y
226
- /// position is extremely high — plays at weapon target position instead.
227
- ///
228
- /// Parameters match the WA usercall convention:
229
- /// EDI=worm, stdcall(sound_id, volume, flags)
230
- pub(crate) unsafe fn play_worm_sound_2(
231
- worm: *mut CTaskWorm,
232
- sound_id: SoundId,
233
- volume: Fixed,
234
- flags: u32,
235
- ) {
236
- // 1. Stop current sound on handle_2
237
- let handle = (*worm).sound_handle_2;
238
- if handle != 0 {
239
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
240
- let sound = (*ddgame).sound;
241
- if !sound.is_null() && (handle as i32) >= 0 {
242
- if handle & 0x40000000 == 0 {
243
- ((*(*sound).vtable).stop_channel)(sound, handle as i32);
244
- } else if !(*ddgame).active_sounds.is_null() {
245
- (*(*ddgame).active_sounds).stop_sound(handle & !0x40000000);
246
- }
247
- }
248
- }
249
-
250
- // 2. Start new sound
251
- // CGameTask+0x88 = Y position (fixed-point). Check if worm is extremely high.
252
- let worm_y = *((worm as *const u8).add(0x88) as *const i32);
253
- let new_handle = if worm_y < -0x270F_FFFF && sound_id.0 == 0x36 {
254
- // Special teleport case: play at weapon target position
255
- call_load_and_play_streaming_positional(
256
- worm,
257
- sound_id.0,
258
- flags,
259
- volume.0 as u32,
260
- (*worm).weapon_param_1 as u32,
261
- (*worm).weapon_param_2 as u32,
262
- )
263
- } else {
264
- // Normal case: play streaming sound
265
- call_load_and_play_streaming(worm, sound_id.0, flags, volume.0 as u32)
266
- };
267
 
268
- (*worm).sound_handle_2 = new_handle;
269
- }
270
-
271
- /// Trampoline for hooking FUN_00515020 (CTaskWorm::PlaySound2).
272
- ///
273
- /// WA convention: usercall(EDI=worm) + stdcall(sound_id, volume, flags), RET 0xC.
274
- /// Extracts EDI and stack params, calls play_worm_sound_2, then returns
275
- /// with RET 0xC to clean the 3 stdcall params.
276
  #[unsafe(naked)]
277
  unsafe extern "C" fn trampoline_worm_play_sound_2() {
278
  core::arch::naked_asm!(
279
- // On entry: EDI=worm, [ESP+4]=sound_id, [ESP+8]=volume, [ESP+12]=flags
280
- // Call play_worm_sound_2(worm, sound_id, volume, flags) as cdecl
281
  "push [esp+12]", // flags
282
  "push [esp+12]", // volume (was +8, shifted +4)
283
  "push [esp+12]", // sound_id (was +4, shifted +8)
@@ -289,124 +91,23 @@ unsafe extern "C" fn trampoline_worm_play_sound_2() {
289
  );
290
  }
291
 
292
- /// Cdecl wrapper for play_worm_sound_2 — called from the trampoline.
293
  unsafe extern "cdecl" fn play_worm_sound_2_cdecl(
294
  worm: *mut CTaskWorm,
295
  sound_id: u32,
296
  volume: u32,
297
  flags: u32,
298
  ) {
299
- play_worm_sound_2(worm, SoundId(sound_id), Fixed(volume as i32), flags);
300
  }
301
 
302
- /// Bridge to FUN_00546bb0 — load and play a positional streaming sound.
303
- /// usercall(EAX=worm, ESI=&worm.sound_emitter) + stdcall(sound_id, flags, volume, x, y).
304
- /// Returns handle | 0x40000000 on success, 0 on failure, -1 if suppressed.
305
- unsafe fn call_load_and_play_streaming_positional(
306
- worm: *mut CTaskWorm,
307
- sound_id: u32,
308
- flags: u32,
309
- volume: u32,
310
- x: u32,
311
- y: u32,
312
- ) -> u32 {
313
- let addr = openwa_core::rebase::rb(0x546BB0u32);
314
- call_load_and_play_streaming_positional_bridge(worm, sound_id, flags, volume, x, y, addr)
315
- }
316
-
317
- #[unsafe(naked)]
318
- unsafe extern "C" fn call_load_and_play_streaming_positional_bridge(
319
- _worm: *mut CTaskWorm,
320
- _sound_id: u32,
321
- _flags: u32,
322
- _volume: u32,
323
- _x: u32,
324
- _y: u32,
325
- _addr: u32,
326
- ) -> u32 {
327
- core::arch::naked_asm!(
328
- "push esi",
329
- "push ebx",
330
- // Stack after saves: [ESP+12]=worm [+16]=sound_id [+20]=flags
331
- // [+24]=volume [+28]=x [+32]=y [+36]=addr
332
- "mov eax, [esp+12]", // worm → EAX
333
- "lea esi, [eax+0xE8]", // &worm.sound_emitter → ESI
334
- "mov ebx, [esp+36]", // addr
335
- // Push 5 stdcall params right-to-left: y, x, volume, flags, sound_id.
336
- // Each push shifts ESP by 4, so the next original param lands at ESP+32.
337
- "push [esp+32]", // y
338
- "push [esp+32]", // x (was +28, shifted +4)
339
- "push [esp+32]", // volume (was +24, shifted +8)
340
- "push [esp+32]", // flags (was +20, shifted +12)
341
- "push [esp+32]", // sound_id (was +16, shifted +16)
342
- "call ebx",
343
- "pop ebx",
344
- "pop esi",
345
- "ret",
346
- );
347
- }
348
-
349
- /// Bridge to FUN_00546c20 — load and play a streaming sound.
350
- /// usercall(EAX=worm, ESI=&worm.sound_emitter) + stdcall(sound_id, flags, volume), plain RET.
351
- /// Returns new sound handle (with bit 30 set for streaming, 0 on failure, -1 if suppressed).
352
- unsafe fn call_load_and_play_streaming(
353
- worm: *mut CTaskWorm,
354
- sound_id: u32,
355
- flags: u32,
356
- volume: u32,
357
- ) -> u32 {
358
- let addr = LOAD_AND_PLAY_STREAMING_ADDR.load(core::sync::atomic::Ordering::Relaxed);
359
- call_load_and_play_streaming_bridge(worm, sound_id, flags, volume, addr)
360
- }
361
-
362
- static LOAD_AND_PLAY_STREAMING_ADDR: core::sync::atomic::AtomicU32 =
363
- core::sync::atomic::AtomicU32::new(0);
364
-
365
- #[unsafe(naked)]
366
- unsafe extern "C" fn call_load_and_play_streaming_bridge(
367
- _worm: *mut CTaskWorm,
368
- _sound_id: u32,
369
- _flags: u32,
370
- _volume: u32,
371
- _addr: u32,
372
- ) -> u32 {
373
- core::arch::naked_asm!(
374
- "push esi",
375
- "push ebx",
376
- // Stack: 2 saves(8) + ret(4) = 12 to first arg
377
- "mov eax, [esp+12]", // worm → EAX
378
- "lea esi, [eax+0xE8]", // &worm.sound_emitter → ESI
379
- "mov ebx, [esp+28]", // addr (12 + 4*4 = 28)
380
- "push [esp+24]", // volume (12+12=24)
381
- "push [esp+20]", // flags (12+8=20, shifted+4=24)
382
- "push [esp+24]", // sound_id (12+4=16, shifted+8=24)
383
- "call ebx",
384
- "pop ebx",
385
- "pop esi",
386
- "ret",
387
- );
388
- }
389
 
390
- // ============================================================
391
- // Sound dispatch helpers (bridge: queue → DSSound)
392
- // ============================================================
393
-
394
- /// IsSoundSuppressed (0x5261E0) — thiscall(ECX=DDGame*), plain RET.
395
- /// Returns 0 if sound playback is allowed, 1 if suppressed.
396
  unsafe extern "thiscall" fn hook_is_sound_suppressed(ddgame: *mut DDGame) -> u32 {
397
- let g = &*ddgame;
398
- let gi = &*g.game_info;
399
- if gi.sound_mute != 0 {
400
- return 1;
401
- }
402
- if g.frame_counter < gi.sound_start_frame {
403
- return 1;
404
- }
405
- 0
406
  }
407
 
408
- /// DispatchGlobalSound (0x526270) — fastcall(ECX=unused, EDX=ddgame_wrapper) + 4 stack, RET 0x10.
409
- /// Checks sound suppression, then calls DSSound vtable slot 3 (play_sound).
410
  unsafe extern "fastcall" fn hook_dispatch_global_sound(
411
  _ecx: u32,
412
  ddgame_wrapper: *const DDGameWrapper,
@@ -415,31 +116,11 @@ unsafe extern "fastcall" fn hook_dispatch_global_sound(
415
  volume: u32,
416
  pitch: u32,
417
  ) -> u32 {
418
- let g = &*(*ddgame_wrapper).ddgame;
419
- let gi = &*g.game_info;
420
-
421
- // Suppression check — returns -1 if muted or before sound start frame
422
- if gi.sound_mute != 0 || g.frame_counter < gi.sound_start_frame {
423
- return 0xFFFF_FFFF;
424
- }
425
-
426
- let dssound = g.sound;
427
- if dssound.is_null() {
428
- return 0;
429
- }
430
-
431
- play_sound(
432
- dssound,
433
- SoundSlot(sound_id),
434
- flags as i32,
435
- Fixed(volume as i32),
436
- Fixed(pitch as i32),
437
- Fixed(0),
438
- ) as u32
439
  }
440
 
441
- /// PlaySoundPooled_Direct (0x546B50) — fastcall(ECX=unused, EDX=task) + 3 stack, RET 0xC.
442
- /// Bypasses queue, checks suppression + fast-forward, calls DSSound vtable slot 4 directly.
443
  unsafe extern "fastcall" fn hook_play_sound_pooled_direct(
444
  _ecx: u32,
445
  task: *const CTask,
@@ -447,30 +128,10 @@ unsafe extern "fastcall" fn hook_play_sound_pooled_direct(
447
  param2: i32,
448
  param3: Fixed,
449
  ) -> i32 {
450
- let g = &*(*task).ddgame;
451
- let gi = &*g.game_info;
452
-
453
- // Suppression check
454
- if gi.sound_mute != 0 || g.frame_counter < gi.sound_start_frame {
455
- return -1;
456
- }
457
-
458
- // Fast-forward check (unique to this function)
459
- if g.fast_forward_active != 0 {
460
- return -1;
461
- }
462
-
463
- let dssound = g.sound;
464
- if dssound.is_null() {
465
- return 0;
466
- }
467
-
468
- play_sound_pooled(dssound, param1, param2, Fixed::ONE, param3, Fixed::ZERO)
469
  }
470
 
471
- // ============================================================
472
- // Hook installation
473
- // ============================================================
474
 
475
  pub fn install() -> Result<(), String> {
476
  if std::env::var("OPENWA_SOUND_LOG").is_ok() {
@@ -484,26 +145,21 @@ pub fn install() -> Result<(), String> {
484
  va::PLAY_SOUND_GLOBAL,
485
  hook_play_sound_global as *const (),
486
  )?;
487
-
488
  let _ = hook::install(
489
  "PlaySoundLocal",
490
  va::PLAY_SOUND_LOCAL,
491
  trampoline_play_sound_local as *const (),
492
  )?;
493
-
494
- // Sound dispatch helpers (bridge: queue → DSSound)
495
  let _ = hook::install(
496
  "IsSoundSuppressed",
497
  va::IS_SOUND_SUPPRESSED,
498
  hook_is_sound_suppressed as *const (),
499
  )?;
500
-
501
  let _ = hook::install(
502
  "DispatchGlobalSound",
503
  va::DISPATCH_GLOBAL_SOUND,
504
  hook_dispatch_global_sound as *const (),
505
  )?;
506
-
507
  let _ = hook::install(
508
  "PlaySoundPooled_Direct",
509
  va::PLAY_SOUND_POOLED_DIRECT,
@@ -520,8 +176,8 @@ pub fn install() -> Result<(), String> {
520
  trampoline_worm_play_sound_2 as *const (),
521
  )?;
522
 
523
- // Initialize bridge addresses for worm sound functions
524
- LOAD_AND_PLAY_STREAMING_ADDR.store(
525
  openwa_core::rebase::rb(va::LOAD_AND_PLAY_STREAMING),
526
  core::sync::atomic::Ordering::Relaxed,
527
  );
 
1
+ //! Sound playback hooks.
2
  //!
3
+ //! Thin wormkit shim — game logic lives in `openwa_core::audio::sound_ops`.
4
+ //! This file contains hook entry points, trampolines, and installation.
5
  //!
6
  //! Hooks:
7
  //! - PlaySoundGlobal (0x546E20): __thiscall, ECX=CTask*, 4 stack params, RET 0x10
8
  //! - PlaySoundLocal (0x4FDFE0): __usercall, EAX+ECX+EDI + 2 stack params, RET 0x8
9
+ //! - IsSoundSuppressed (0x5261E0): __thiscall, ECX=DDGame*
10
+ //! - DispatchGlobalSound (0x526270): __fastcall + 4 stack, RET 0x10
11
+ //! - PlaySoundPooled_Direct (0x546B50): __fastcall + 3 stack, RET 0xC
12
+ //! - WormPlaySound2 (0x515020): __usercall(EDI=worm) + 3 stack, RET 0xC
13
 
14
  use std::sync::atomic::Ordering;
15
 
16
  use openwa_core::address::va;
17
+ use openwa_core::audio::sound_ops;
18
+ use openwa_core::audio::{KnownSoundId, SoundId, SoundSlot};
19
+ use openwa_core::engine::{DDGame, DDGameWrapper};
20
  use openwa_core::fixed::Fixed;
21
  use openwa_core::task::worm::CTaskWorm;
22
  use openwa_core::task::{CGameTask, CTask};
 
27
  /// Whether sound logging is enabled (checked once at init).
28
  static SOUND_LOG_ENABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
29
 
30
+ // ── PlaySoundGlobal (0x546E20): thiscall(ECX=CTask*, 4 stack, RET 0x10) ──
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
  unsafe extern "thiscall" fn hook_play_sound_global(
33
  this: *const CGameTask,
 
46
  ));
47
  }
48
 
49
+ sound_ops::queue_sound((*this).base.ddgame, SoundId(sound_id), flags, volume, pitch).is_some()
50
+ as u32
51
  }
52
 
53
+ // ── PlaySoundLocal (0x4FDFE0): usercall(EAX=pitch, ECX=volume, EDI=task, stack) ──
 
 
 
 
54
 
55
  hook::usercall_trampoline!(fn trampoline_play_sound_local; impl_fn = play_sound_local_impl;
56
  regs = [eax, ecx, edi]; stack_params = 2; ret_bytes = "0x8");
 
72
  ));
73
  }
74
 
75
+ sound_ops::play_sound_local(task, SoundId(sound_id), flags, volume, pitch) as u32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  }
77
 
78
+ // ── WormPlaySound2 (0x515020): usercall(EDI=worm) + stdcall(sound_id, volume, flags) ──
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
 
 
 
 
 
 
 
 
80
  #[unsafe(naked)]
81
  unsafe extern "C" fn trampoline_worm_play_sound_2() {
82
  core::arch::naked_asm!(
 
 
83
  "push [esp+12]", // flags
84
  "push [esp+12]", // volume (was +8, shifted +4)
85
  "push [esp+12]", // sound_id (was +4, shifted +8)
 
91
  );
92
  }
93
 
 
94
  unsafe extern "cdecl" fn play_worm_sound_2_cdecl(
95
  worm: *mut CTaskWorm,
96
  sound_id: u32,
97
  volume: u32,
98
  flags: u32,
99
  ) {
100
+ sound_ops::play_worm_sound_2(worm, SoundId(sound_id), Fixed(volume as i32), flags);
101
  }
102
 
103
+ // ── IsSoundSuppressed (0x5261E0): thiscall(ECX=DDGame*) ──
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
 
 
 
 
 
 
105
  unsafe extern "thiscall" fn hook_is_sound_suppressed(ddgame: *mut DDGame) -> u32 {
106
+ sound_ops::is_sound_suppressed(ddgame) as u32
 
 
 
 
 
 
 
 
107
  }
108
 
109
+ // ── DispatchGlobalSound (0x526270): fastcall(ECX=unused, EDX=wrapper) + 4 stack ──
110
+
111
  unsafe extern "fastcall" fn hook_dispatch_global_sound(
112
  _ecx: u32,
113
  ddgame_wrapper: *const DDGameWrapper,
 
116
  volume: u32,
117
  pitch: u32,
118
  ) -> u32 {
119
+ sound_ops::dispatch_global_sound(ddgame_wrapper, sound_id, flags, volume, pitch)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  }
121
 
122
+ // ── PlaySoundPooled_Direct (0x546B50): fastcall(ECX=unused, EDX=task) + 3 stack ──
123
+
124
  unsafe extern "fastcall" fn hook_play_sound_pooled_direct(
125
  _ecx: u32,
126
  task: *const CTask,
 
128
  param2: i32,
129
  param3: Fixed,
130
  ) -> i32 {
131
+ sound_ops::play_sound_pooled_direct(task, param1, param2, param3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  }
133
 
134
+ // ── Hook installation ──
 
 
135
 
136
  pub fn install() -> Result<(), String> {
137
  if std::env::var("OPENWA_SOUND_LOG").is_ok() {
 
145
  va::PLAY_SOUND_GLOBAL,
146
  hook_play_sound_global as *const (),
147
  )?;
 
148
  let _ = hook::install(
149
  "PlaySoundLocal",
150
  va::PLAY_SOUND_LOCAL,
151
  trampoline_play_sound_local as *const (),
152
  )?;
 
 
153
  let _ = hook::install(
154
  "IsSoundSuppressed",
155
  va::IS_SOUND_SUPPRESSED,
156
  hook_is_sound_suppressed as *const (),
157
  )?;
 
158
  let _ = hook::install(
159
  "DispatchGlobalSound",
160
  va::DISPATCH_GLOBAL_SOUND,
161
  hook_dispatch_global_sound as *const (),
162
  )?;
 
163
  let _ = hook::install(
164
  "PlaySoundPooled_Direct",
165
  va::PLAY_SOUND_POOLED_DIRECT,
 
176
  trampoline_worm_play_sound_2 as *const (),
177
  )?;
178
 
179
+ // Initialize bridge address for streaming sound functions
180
+ sound_ops::LOAD_AND_PLAY_STREAMING_ADDR.store(
181
  openwa_core::rebase::rb(va::LOAD_AND_PLAY_STREAMING),
182
  core::sync::atomic::Ordering::Relaxed,
183
  );
crates/openwa-wormkit/src/replacements/task/cloud.rs CHANGED
@@ -1,110 +1,16 @@
1
  //! CTaskCloud vtable hooks.
2
  //!
3
- //! Replaces CTaskCloud::HandleMessage (vtable slot 2).
4
- //! Handles cloud position updates (wind parallax), rendering, and wind changes.
5
 
6
  use openwa_core::address::va;
7
- use openwa_core::fixed::Fixed;
8
- use openwa_core::game::TaskMessage;
9
  use openwa_core::log::log_line;
10
- use openwa_core::render::queue::{command_type, DrawSpriteCmd};
11
- use openwa_core::task::cloud::CTaskCloud;
12
- use openwa_core::task::CTask;
13
-
14
- /// CTaskCloud::HandleMessage replacement.
15
- ///
16
- /// Handles three message types:
17
- /// - FrameFinish: per-frame position update (parallax scroll with wind drift)
18
- /// - RenderScene: draw sprite at computed position — delegates to original
19
- /// - SetWind: set wind target from message data
20
- ///
21
- /// Always calls base CTask::HandleMessage at the end (0x562F30).
22
- unsafe extern "thiscall" fn cloud_handle_message(
23
- this: *mut CTaskCloud,
24
- sender: *mut CTask,
25
- msg_type: u32,
26
- size: u32,
27
- data: *const u8,
28
- ) {
29
- let msg = TaskMessage::try_from(msg_type);
30
-
31
- match msg {
32
- Ok(TaskMessage::FrameFinish) => {
33
- // Advance Y position
34
- (*this).pos_y = Fixed((*this).pos_y.0 + (*this).vel_y.0);
35
-
36
- // Advance X position: base velocity + wind * 10
37
- let wind = (*this).wind_accel.0;
38
- (*this).pos_x = Fixed((*this).pos_x.0 + (*this).vel_x.0 + wind * 10);
39
-
40
- // Wrap X at landscape bounds (with 128.0 Fixed padding)
41
- let ddgame = CTask::ddgame_raw(this as *const CTask);
42
- let padding = Fixed::from_int(128);
43
- let level_left = (*ddgame).level_bound_min_x - padding;
44
- let level_right = (*ddgame).level_bound_max_x + padding;
45
-
46
- if (*this).pos_x < level_left {
47
- (*this).pos_x = level_right;
48
- } else if (*this).pos_x > level_right {
49
- (*this).pos_x = level_left;
50
- }
51
-
52
- // Converge wind_accel toward wind_target (clamp step to ±0x147)
53
- let target = (*this).wind_target.0;
54
- let current = (*this).wind_accel.0;
55
- let diff = target - current;
56
- if diff.abs() < 0x147 {
57
- (*this).wind_accel = Fixed(target);
58
- } else if current < target {
59
- (*this).wind_accel = Fixed(current + 0x147);
60
- } else {
61
- (*this).wind_accel = Fixed(current - 0x147);
62
- }
63
- }
64
-
65
- Ok(TaskMessage::RenderScene) => {
66
- let ddgame = CTask::ddgame_raw(this as *const CTask);
67
-
68
- // Only render when rendering phase == 5 (in-game rendering active)
69
- if (*ddgame).render_phase == 5 {
70
- // Compute parallax X offset: (vel_x + wind * 10) * parallax_scale
71
- let scroll_speed = (*this).vel_x.0 + (*this).wind_accel.0 * 10;
72
- let parallax_x =
73
- ((scroll_speed as i64 * (*ddgame).parallax_scale as i64) >> 16) as i32;
74
- let x = parallax_x + (*this).pos_x.0;
75
-
76
- let rq = &mut *(*ddgame).render_queue;
77
- if let Some(entry) = rq.alloc::<DrawSpriteCmd>() {
78
- *entry = DrawSpriteCmd {
79
- command_type: command_type::DRAW_SPRITE_LOCAL,
80
- layer: (*this).layer_depth.0 as u32,
81
- x_pos: x as u32 & 0xFFFF0000,
82
- y_pos: (*this).pos_y.0 as u32 & 0xFFFF0000,
83
- sprite_id: (*this).sprite_id,
84
- frame: 0,
85
- };
86
- }
87
- }
88
- }
89
-
90
- Ok(TaskMessage::SetWind) => {
91
- if !data.is_null() {
92
- (*this).wind_target = Fixed(*(data as *const i32));
93
- }
94
- }
95
-
96
- _ => {}
97
- }
98
-
99
- // Broadcast to children — raw-pointer version avoids noalias UB
100
- CTask::broadcast_message_raw(this as *mut CTask, sender, msg_type, size, data);
101
- }
102
 
103
  pub fn install() -> Result<(), String> {
104
  use openwa_core::vtable_replace;
105
 
106
- vtable_replace!(openwa_core::task::cloud::CTaskCloudVTable, va::CTASK_CLOUD_VTABLE, {
107
- handle_message => cloud_handle_message,
108
  })?;
109
 
110
  let _ = log_line("[Cloud] HandleMessage hooked via vtable_replace");
 
1
  //! CTaskCloud vtable hooks.
2
  //!
3
+ //! Thin wormkit shim — game logic lives in `openwa_core::task::cloud::cloud_handle_message`.
 
4
 
5
  use openwa_core::address::va;
 
 
6
  use openwa_core::log::log_line;
7
+ use openwa_core::task::cloud;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  pub fn install() -> Result<(), String> {
10
  use openwa_core::vtable_replace;
11
 
12
+ vtable_replace!(cloud::CTaskCloudVTable, va::CTASK_CLOUD_VTABLE, {
13
+ handle_message => cloud::cloud_handle_message,
14
  })?;
15
 
16
  let _ = log_line("[Cloud] HandleMessage hooked via vtable_replace");
crates/openwa-wormkit/src/replacements/task/filter.rs CHANGED
@@ -1,40 +1,16 @@
1
  //! CTaskFilter vtable hooks.
2
  //!
3
- //! Replaces CTaskFilter::HandleMessage (vtable slot 2).
4
- //! Gate-keeps message propagation via a per-instance subscription table.
5
 
6
  use openwa_core::address::va;
7
  use openwa_core::log::log_line;
8
- use openwa_core::task::filter::CTaskFilter;
9
- use openwa_core::task::CTask;
10
-
11
- /// CTaskFilter::HandleMessage replacement.
12
- ///
13
- /// Messages with `msg_type < 98` are only forwarded if
14
- /// `subscription_table[msg_type] != 0`. Messages >= 98 always pass through.
15
- /// Forwarding calls `broadcast_message` which propagates down to child tasks.
16
- unsafe extern "thiscall" fn filter_handle_message(
17
- this: *mut CTaskFilter,
18
- sender: *mut CTask,
19
- msg_type: u32,
20
- size: u32,
21
- data: *const u8,
22
- ) {
23
- // Check subscription table — messages >= 98 always pass through
24
- let table = &(*this).subscription_table;
25
- if (msg_type as usize) < table.len() && table[msg_type as usize] == 0 {
26
- return; // message not subscribed — drop silently
27
- }
28
-
29
- // Broadcast to children — raw-pointer version avoids noalias UB
30
- CTask::broadcast_message_raw(this as *mut CTask, sender, msg_type, size, data);
31
- }
32
 
33
  pub fn install() -> Result<(), String> {
34
  use openwa_core::vtable_replace;
35
 
36
- vtable_replace!(openwa_core::task::filter::CTaskFilterVTable, va::CTASK_FILTER_VTABLE, {
37
- handle_message => filter_handle_message,
38
  })?;
39
 
40
  let _ = log_line("[Filter] HandleMessage hooked via vtable_replace");
 
1
  //! CTaskFilter vtable hooks.
2
  //!
3
+ //! Thin wormkit shim — game logic lives in `openwa_core::task::filter::filter_handle_message`.
 
4
 
5
  use openwa_core::address::va;
6
  use openwa_core::log::log_line;
7
+ use openwa_core::task::filter;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  pub fn install() -> Result<(), String> {
10
  use openwa_core::vtable_replace;
11
 
12
+ vtable_replace!(filter::CTaskFilterVTable, va::CTASK_FILTER_VTABLE, {
13
+ handle_message => filter::filter_handle_message,
14
  })?;
15
 
16
  let _ = log_line("[Filter] HandleMessage hooked via vtable_replace");
crates/openwa-wormkit/src/replacements/team.rs CHANGED
@@ -1,112 +1,46 @@
1
  //! Team and worm state accessor hooks.
2
  //!
3
- //! Replaces WA.exe functions that access the TeamArenaState area (DDGame + 0x4628):
4
- //! - CountTeamsByAlliance (0x522030): count teams by alliance membership
5
- //! - GetTeamTotalHealth (0x5224D0): sum worm health for a team
6
- //! - IsWormInSpecialState (0x5226B0): check worm state flag
7
- //! - GetWormPosition (0x522700): read worm X,Y coordinates
8
- //! - CheckWormState0x64 (0x5228D0): check if any worm has state 0x64
9
- //! - CheckTeamWormState0x64 (0x522930): per-team version of above
10
- //! - CheckAnyWormState0x8b (0x522970): scan all teams for state 0x8b
11
- //! - SetActiveWorm_Maybe (0x522500): update team active state and counters
12
 
13
  use openwa_core::address::va;
14
- use openwa_core::engine::ddgame::{self, TeamArenaRef};
 
15
 
16
  use crate::hook::{self, usercall_trampoline};
17
 
18
- // ============================================================
19
- // CountTeamsByAlliance replacement (0x522030)
20
- // ============================================================
21
- // __usercall: EAX = base, EDI = alliance_id
22
- // plain RET
23
- //
24
- // NOTE: This function uses Pattern B header fields (+0x70/+0x74) for
25
- // alliance and active_worm, accessed via team_header_b().
26
 
27
  unsafe extern "cdecl" fn count_teams_by_alliance_impl(arena: TeamArenaRef, alliance_id: i32) {
28
- let state = arena.state_mut();
29
- state.current_alliance = alliance_id;
30
- state.active_team_count = 0;
31
- state.same_alliance_count = 0;
32
- state.enemy_team_count = 0;
33
-
34
- for i in 0..state.team_count as usize {
35
- let header = arena.team_header_b(i);
36
- let team_alliance = header.alliance;
37
- let active_worm = header.active_worm;
38
- if active_worm != 0 && team_alliance >= 0 {
39
- state.active_team_count += 1;
40
- if team_alliance == alliance_id {
41
- state.same_alliance_count += 1;
42
- } else {
43
- state.enemy_team_count += 1;
44
- }
45
- }
46
- }
47
  }
48
 
49
  usercall_trampoline!(fn trampoline_count_teams_by_alliance; impl_fn = count_teams_by_alliance_impl;
50
  regs = [eax, edi]);
51
 
52
- // ============================================================
53
- // GetTeamTotalHealth replacement (0x5224D0)
54
- // ============================================================
55
- // __fastcall: ECX = team_index, EDX = base
56
- // plain RET, returns EAX = total health
57
 
58
  unsafe extern "cdecl" fn get_team_total_health_impl(team_index: u32, arena: TeamArenaRef) -> i32 {
59
- let header = arena.team_header(team_index as usize);
60
-
61
- if header.eliminated != 0 {
62
- return 0;
63
- }
64
-
65
- let worm_count = header.worm_count;
66
- let mut total = 0i32;
67
- for w in 1..=worm_count as usize {
68
- total += arena.team_worm(team_index as usize, w).health;
69
- }
70
- total
71
  }
72
 
73
  usercall_trampoline!(fn trampoline_get_team_total_health; impl_fn = get_team_total_health_impl;
74
  regs = [ecx, edx]);
75
 
76
- // ============================================================
77
- // IsWormInSpecialState replacement (0x5226B0)
78
- // ============================================================
79
- // __usercall: EAX = team_index, ECX = worm_index, [ESP+4] = base
80
- // RET 0x4, returns EAX = bool (1 if special state)
81
 
82
  unsafe extern "cdecl" fn is_worm_in_special_state_impl(
83
  team_index: u32,
84
  worm_index: u32,
85
  arena: TeamArenaRef,
86
  ) -> u32 {
87
- if ddgame::worm::is_special_state(
88
- arena
89
- .team_worm(team_index as usize, worm_index as usize)
90
- .state,
91
- ) {
92
- 1
93
- } else {
94
- 0
95
- }
96
  }
97
 
98
  usercall_trampoline!(fn trampoline_is_worm_in_special_state; impl_fn = is_worm_in_special_state_impl;
99
  regs = [eax, ecx]; stack_params = 1; ret_bytes = "0x4");
100
 
101
- // ============================================================
102
- // GetWormPosition replacement (0x522700)
103
- // ============================================================
104
- // __usercall: EAX = team_index, ECX = worm_index,
105
- // [ESP+4] = base, [ESP+8] = out_x, [ESP+C] = out_y
106
- // RET 0xC
107
- //
108
- // Reads pos_x/pos_y from WormEntry._unknown_90[0..4] / [4..8].
109
- // These values appear transient — actual worm positions live in CGameTask objects.
110
 
111
  unsafe extern "cdecl" fn get_worm_position_impl(
112
  team_index: u32,
@@ -115,165 +49,52 @@ unsafe extern "cdecl" fn get_worm_position_impl(
115
  out_x: *mut i32,
116
  out_y: *mut i32,
117
  ) {
118
- let worm = arena.team_worm(team_index as usize, worm_index as usize);
119
- *out_x = *(worm._unknown_90.as_ptr() as *const i32);
120
- *out_y = *(worm._unknown_90.as_ptr().add(4) as *const i32);
121
  }
122
 
123
  usercall_trampoline!(fn trampoline_get_worm_position; impl_fn = get_worm_position_impl;
124
  regs = [eax, ecx]; stack_params = 3; ret_bytes = "0xC");
125
 
126
- // ============================================================
127
- // CheckWormState0x64 replacement (0x5228D0)
128
- // ============================================================
129
- // __usercall: EAX = base
130
- // plain RET, returns EAX = bool (1 if any worm has state 0x64)
131
- //
132
- // Previously named "HasFullHealthWorm" but Ghidra disassembly confirms it
133
- // reads worms[].state (offset +0x00), NOT worms[].health (offset +0x5C).
134
- // It compares to 0x64 (100 decimal). State 0x64 is likely a transitional
135
- // state distinct from 0x65 (idle). 11 xrefs in gameplay code.
136
 
137
  unsafe extern "cdecl" fn check_worm_state_0x64_impl(arena: TeamArenaRef) -> u32 {
138
- let state = arena.state();
139
-
140
- // Iterate real teams (1-indexed: team 1..=team_count)
141
- for i in 1..=state.team_count as usize {
142
- let header = arena.team_header(i);
143
- if header.eliminated != 0 {
144
- continue;
145
- }
146
- let worm_count = header.worm_count;
147
- for w in 1..=worm_count as usize {
148
- if arena.team_worm(i, w).state == 0x64 {
149
- return 1;
150
- }
151
- }
152
- }
153
- 0
154
  }
155
 
156
  usercall_trampoline!(fn trampoline_check_worm_state_0x64; impl_fn = check_worm_state_0x64_impl;
157
  reg = eax);
158
 
159
- // ============================================================
160
- // CheckTeamWormState0x64 replacement (0x522930)
161
- // ============================================================
162
- // __usercall: ECX = base, EAX = team_idx
163
- // plain RET, returns EAX = bool (1 if any worm on team has state 0x64)
164
- //
165
- // Per-team version of CheckWormState0x64. 1 xref (FUN_00556ad0).
166
 
167
  unsafe extern "cdecl" fn check_team_worm_state_0x64_impl(
168
  arena: TeamArenaRef,
169
  team_idx: u32,
170
  ) -> u32 {
171
- let header = arena.team_header(team_idx as usize);
172
-
173
- if header.eliminated != 0 {
174
- return 0;
175
- }
176
-
177
- let worm_count = header.worm_count;
178
- for w in 1..=worm_count as usize {
179
- if arena.team_worm(team_idx as usize, w).state == 0x64 {
180
- return 1;
181
- }
182
- }
183
- 0
184
  }
185
 
186
  usercall_trampoline!(fn trampoline_check_team_worm_state_0x64; impl_fn = check_team_worm_state_0x64_impl;
187
  regs = [ecx, eax]);
188
 
189
- // ============================================================
190
- // CheckAnyWormState0x8b replacement (0x522970)
191
- // ============================================================
192
- // __usercall: EAX = base
193
- // plain RET, returns EAX = bool (1 if any worm on any team has state 0x8b)
194
- //
195
- // Scans all teams. 1 xref (FUN_00557310).
196
 
197
  unsafe extern "cdecl" fn check_any_worm_state_0x8b_impl(arena: TeamArenaRef) -> u32 {
198
- let state = arena.state();
199
-
200
- for i in 1..=state.team_count as usize {
201
- let header = arena.team_header(i);
202
- if header.eliminated != 0 {
203
- continue;
204
- }
205
- let worm_count = header.worm_count;
206
- for w in 1..=worm_count as usize {
207
- if arena.team_worm(i, w).state == 0x8b {
208
- return 1;
209
- }
210
- }
211
- }
212
- 0
213
  }
214
 
215
  usercall_trampoline!(fn trampoline_check_any_worm_state_0x8b; impl_fn = check_any_worm_state_0x8b_impl;
216
  reg = eax);
217
 
218
- // ============================================================
219
- // SetActiveWorm_Maybe replacement (0x522500)
220
- // ============================================================
221
- // __usercall: EAX = base, EDX = team_idx (1-indexed), ESI = worm_index
222
- // plain RET (4 RET sites in original)
223
- //
224
- // Sets the active worm for a team. worm_index=0 deactivates, worm_index=N
225
- // sets worm N as active. Called on turn transitions and worm selection (Tab).
226
- // Updates active counters and records last_active_team/alliance. 3 xrefs.
227
 
228
  unsafe extern "cdecl" fn set_active_worm_impl(arena: TeamArenaRef, team_idx: u32, worm_index: i32) {
229
- let state = arena.state_mut();
230
-
231
- // Pattern B header: team_idx is 1-indexed, team_header_b is 0-indexed
232
- // team_idx=1 → team_header_b(0) → blocks[2].header
233
- let header = arena.team_header_b(team_idx as usize - 1);
234
-
235
- if worm_index == 0 {
236
- // Deactivate team
237
- if header.active_worm != 0 {
238
- state.active_worm_count -= 1;
239
- let alliance = header.alliance;
240
- if alliance >= 0 {
241
- state.active_team_count -= 1;
242
- if alliance == state.current_alliance {
243
- state.same_alliance_count -= 1;
244
- } else {
245
- state.enemy_team_count -= 1;
246
- }
247
- }
248
- arena.team_header_b_mut(team_idx as usize - 1).active_worm = 0;
249
- }
250
- } else {
251
- // Activate team — only update counters if not already active
252
- if header.active_worm == 0 {
253
- state.active_worm_count += 1;
254
- state.last_active_team = team_idx as i32;
255
- let alliance = header.alliance;
256
- state.last_active_alliance = alliance;
257
- if alliance >= 0 {
258
- state.active_team_count += 1;
259
- if alliance == state.current_alliance {
260
- state.same_alliance_count += 1;
261
- } else {
262
- state.enemy_team_count += 1;
263
- }
264
- }
265
- }
266
- // Always write worm_index (original writes ESI unconditionally)
267
- arena.team_header_b_mut(team_idx as usize - 1).active_worm = worm_index;
268
- }
269
  }
270
 
271
  usercall_trampoline!(fn trampoline_set_active_worm; impl_fn = set_active_worm_impl;
272
  regs = [eax, edx, esi]);
273
 
274
- // ============================================================
275
- // Hook installation
276
- // ============================================================
277
 
278
  pub fn install() -> Result<(), String> {
279
  unsafe {
@@ -282,49 +103,41 @@ pub fn install() -> Result<(), String> {
282
  va::COUNT_TEAMS_BY_ALLIANCE,
283
  trampoline_count_teams_by_alliance as *const (),
284
  )?;
285
-
286
  let _ = hook::install(
287
  "GetTeamTotalHealth",
288
  va::GET_TEAM_TOTAL_HEALTH,
289
  trampoline_get_team_total_health as *const (),
290
  )?;
291
-
292
  let _ = hook::install(
293
  "IsWormInSpecialState",
294
  va::IS_WORM_IN_SPECIAL_STATE,
295
  trampoline_is_worm_in_special_state as *const (),
296
  )?;
297
-
298
  let _ = hook::install(
299
  "GetWormPosition",
300
  va::GET_WORM_POSITION,
301
  trampoline_get_worm_position as *const (),
302
  )?;
303
-
304
  let _ = hook::install(
305
  "CheckWormState0x64",
306
  va::CHECK_WORM_STATE_0X64,
307
  trampoline_check_worm_state_0x64 as *const (),
308
  )?;
309
-
310
  let _ = hook::install(
311
  "CheckTeamWormState0x64",
312
  va::CHECK_TEAM_WORM_STATE_0X64,
313
  trampoline_check_team_worm_state_0x64 as *const (),
314
  )?;
315
-
316
  let _ = hook::install(
317
  "CheckAnyWormState0x8b",
318
  va::CHECK_ANY_WORM_STATE_0X8B,
319
  trampoline_check_any_worm_state_0x8b as *const (),
320
  )?;
321
-
322
  let _ = hook::install(
323
  "SetActiveWorm_Maybe",
324
  va::SET_ACTIVE_WORM_MAYBE,
325
  trampoline_set_active_worm as *const (),
326
  )?;
327
  }
328
-
329
  Ok(())
330
  }
 
1
  //! Team and worm state accessor hooks.
2
  //!
3
+ //! Thin wormkit shim — all game logic lives in `openwa_core::engine::team_ops`.
4
+ //! This file contains only usercall trampolines and hook installation.
 
 
 
 
 
 
 
5
 
6
  use openwa_core::address::va;
7
+ use openwa_core::engine::ddgame::TeamArenaRef;
8
+ use openwa_core::engine::team_ops;
9
 
10
  use crate::hook::{self, usercall_trampoline};
11
 
12
+ // ── CountTeamsByAlliance (0x522030): usercall(EAX=base, EDI=alliance_id) ──
 
 
 
 
 
 
 
13
 
14
  unsafe extern "cdecl" fn count_teams_by_alliance_impl(arena: TeamArenaRef, alliance_id: i32) {
15
+ team_ops::count_teams_by_alliance(arena, alliance_id);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  }
17
 
18
  usercall_trampoline!(fn trampoline_count_teams_by_alliance; impl_fn = count_teams_by_alliance_impl;
19
  regs = [eax, edi]);
20
 
21
+ // ── GetTeamTotalHealth (0x5224D0): fastcall(ECX=team_index, EDX=base) ──
 
 
 
 
22
 
23
  unsafe extern "cdecl" fn get_team_total_health_impl(team_index: u32, arena: TeamArenaRef) -> i32 {
24
+ team_ops::get_team_total_health(team_index, arena)
 
 
 
 
 
 
 
 
 
 
 
25
  }
26
 
27
  usercall_trampoline!(fn trampoline_get_team_total_health; impl_fn = get_team_total_health_impl;
28
  regs = [ecx, edx]);
29
 
30
+ // ── IsWormInSpecialState (0x5226B0): usercall(EAX=team, ECX=worm, [ESP+4]=base) ──
 
 
 
 
31
 
32
  unsafe extern "cdecl" fn is_worm_in_special_state_impl(
33
  team_index: u32,
34
  worm_index: u32,
35
  arena: TeamArenaRef,
36
  ) -> u32 {
37
+ team_ops::is_worm_in_special_state(team_index, worm_index, arena)
 
 
 
 
 
 
 
 
38
  }
39
 
40
  usercall_trampoline!(fn trampoline_is_worm_in_special_state; impl_fn = is_worm_in_special_state_impl;
41
  regs = [eax, ecx]; stack_params = 1; ret_bytes = "0x4");
42
 
43
+ // ── GetWormPosition (0x522700): usercall(EAX=team, ECX=worm, stack=base,x,y) ──
 
 
 
 
 
 
 
 
44
 
45
  unsafe extern "cdecl" fn get_worm_position_impl(
46
  team_index: u32,
 
49
  out_x: *mut i32,
50
  out_y: *mut i32,
51
  ) {
52
+ team_ops::get_worm_position(team_index, worm_index, arena, out_x, out_y);
 
 
53
  }
54
 
55
  usercall_trampoline!(fn trampoline_get_worm_position; impl_fn = get_worm_position_impl;
56
  regs = [eax, ecx]; stack_params = 3; ret_bytes = "0xC");
57
 
58
+ // ── CheckWormState0x64 (0x5228D0): usercall(EAX=base) ──
 
 
 
 
 
 
 
 
 
59
 
60
  unsafe extern "cdecl" fn check_worm_state_0x64_impl(arena: TeamArenaRef) -> u32 {
61
+ team_ops::check_worm_state_0x64(arena)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  }
63
 
64
  usercall_trampoline!(fn trampoline_check_worm_state_0x64; impl_fn = check_worm_state_0x64_impl;
65
  reg = eax);
66
 
67
+ // ── CheckTeamWormState0x64 (0x522930): usercall(ECX=base, EAX=team_idx) ──
 
 
 
 
 
 
68
 
69
  unsafe extern "cdecl" fn check_team_worm_state_0x64_impl(
70
  arena: TeamArenaRef,
71
  team_idx: u32,
72
  ) -> u32 {
73
+ team_ops::check_team_worm_state_0x64(arena, team_idx)
 
 
 
 
 
 
 
 
 
 
 
 
74
  }
75
 
76
  usercall_trampoline!(fn trampoline_check_team_worm_state_0x64; impl_fn = check_team_worm_state_0x64_impl;
77
  regs = [ecx, eax]);
78
 
79
+ // ── CheckAnyWormState0x8b (0x522970): usercall(EAX=base) ──
 
 
 
 
 
 
80
 
81
  unsafe extern "cdecl" fn check_any_worm_state_0x8b_impl(arena: TeamArenaRef) -> u32 {
82
+ team_ops::check_any_worm_state_0x8b(arena)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  }
84
 
85
  usercall_trampoline!(fn trampoline_check_any_worm_state_0x8b; impl_fn = check_any_worm_state_0x8b_impl;
86
  reg = eax);
87
 
88
+ // ── SetActiveWorm_Maybe (0x522500): usercall(EAX=base, EDX=team_idx, ESI=worm) ──
 
 
 
 
 
 
 
 
89
 
90
  unsafe extern "cdecl" fn set_active_worm_impl(arena: TeamArenaRef, team_idx: u32, worm_index: i32) {
91
+ team_ops::set_active_worm(arena, team_idx, worm_index);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  }
93
 
94
  usercall_trampoline!(fn trampoline_set_active_worm; impl_fn = set_active_worm_impl;
95
  regs = [eax, edx, esi]);
96
 
97
+ // ── Hook installation ──
 
 
98
 
99
  pub fn install() -> Result<(), String> {
100
  unsafe {
 
103
  va::COUNT_TEAMS_BY_ALLIANCE,
104
  trampoline_count_teams_by_alliance as *const (),
105
  )?;
 
106
  let _ = hook::install(
107
  "GetTeamTotalHealth",
108
  va::GET_TEAM_TOTAL_HEALTH,
109
  trampoline_get_team_total_health as *const (),
110
  )?;
 
111
  let _ = hook::install(
112
  "IsWormInSpecialState",
113
  va::IS_WORM_IN_SPECIAL_STATE,
114
  trampoline_is_worm_in_special_state as *const (),
115
  )?;
 
116
  let _ = hook::install(
117
  "GetWormPosition",
118
  va::GET_WORM_POSITION,
119
  trampoline_get_worm_position as *const (),
120
  )?;
 
121
  let _ = hook::install(
122
  "CheckWormState0x64",
123
  va::CHECK_WORM_STATE_0X64,
124
  trampoline_check_worm_state_0x64 as *const (),
125
  )?;
 
126
  let _ = hook::install(
127
  "CheckTeamWormState0x64",
128
  va::CHECK_TEAM_WORM_STATE_0X64,
129
  trampoline_check_team_worm_state_0x64 as *const (),
130
  )?;
 
131
  let _ = hook::install(
132
  "CheckAnyWormState0x8b",
133
  va::CHECK_ANY_WORM_STATE_0X8B,
134
  trampoline_check_any_worm_state_0x8b as *const (),
135
  )?;
 
136
  let _ = hook::install(
137
  "SetActiveWorm_Maybe",
138
  va::SET_ACTIVE_WORM_MAYBE,
139
  trampoline_set_active_worm as *const (),
140
  )?;
141
  }
 
142
  Ok(())
143
  }
crates/openwa-wormkit/src/replacements/weapon.rs CHANGED
@@ -1,39 +1,27 @@
1
  //! Weapon hooks.
2
  //!
3
- //! Replaces WA.exe functions that manage weapon ammo in the TeamArenaState area (DDGame + 0x4628):
4
- //! - GetAmmo (0x5225E0): query ammo count with delay/phase checks
5
- //! - AddAmmo (0x522640): add ammo to a weapon slot
6
- //! - SubtractAmmo (0x522680): decrement ammo count
7
- //! - CountAliveWorms (0x5225A0): check if >1 worm alive on team
8
- //! - FireWeapon (0x51EE60): full Rust dispatch
9
  //!
10
- //! Passthrough hooks on fire sub-functions (log params, call original):
11
- //! - CreateWeaponProjectile (0x51E0F0): thiscall(ECX=worm, fire_params, local_struct)
12
- //! - ProjectileFire (0x51DFB0): stdcall(worm, fire_params, local_struct)
13
- //! - StrikeFire (0x51E2C0): stdcall(worm, &subtype_34, local_struct) — AirStrike/NapalmStrike etc.
14
- //! - PlacedExplosive (0x51EC80): usercall(ECX=local_struct, EDX=worm, fire_params)
 
15
 
16
  use core::sync::atomic::{AtomicU32, Ordering};
17
 
18
  use openwa_core::address::va;
19
- use openwa_core::audio::{KnownSoundId, SoundId};
20
- use openwa_core::engine::ddgame::{self, TeamArenaRef};
21
- use openwa_core::fixed::Fixed;
22
- use openwa_core::game::weapon::{WeaponEntry, WeaponFireParams, WeaponSpawnData};
23
- use openwa_core::game::Weapon;
24
  use openwa_core::log::log_line;
25
- use openwa_core::task::turn_game::CTaskTurnGame;
26
- use openwa_core::task::worm::{CTaskWorm, WormState};
27
- use openwa_core::task::CTask;
28
 
29
  use crate::hook::{self, usercall_trampoline};
30
- use crate::replacements::weapon_release::WeaponReleaseContext;
31
 
32
- // ============================================================
33
- // AddAmmo replacement (0x522640)
34
- // ============================================================
35
- // __usercall: EAX = team_index, EDX = amount, [ESP+4] = team_info_base, [ESP+8] = weapon_id
36
- // RET 0x8
37
 
38
  unsafe extern "cdecl" fn add_ammo_impl(
39
  team_index: u32,
@@ -41,1412 +29,100 @@ unsafe extern "cdecl" fn add_ammo_impl(
41
  arena: TeamArenaRef,
42
  weapon_id: u32,
43
  ) {
44
- let (alliance, wid) = arena.weapon_slot_key(team_index as usize, weapon_id);
45
- let state = arena.state_mut();
46
- let ammo = state.get_ammo(alliance, wid);
47
- if ammo >= 0 {
48
- if amount < 0 {
49
- *state.ammo_mut(alliance, wid) = -1;
50
- } else {
51
- *state.ammo_mut(alliance, wid) = ammo + amount;
52
- }
53
- }
54
  }
55
 
56
  usercall_trampoline!(fn trampoline_add_ammo; impl_fn = add_ammo_impl;
57
  regs = [eax, edx]; stack_params = 2; ret_bytes = "0x8");
58
 
59
- // ============================================================
60
- // SubtractAmmo replacement (0x522680)
61
- // ============================================================
62
- // __usercall: EAX = team_index, ECX = team_info_base, [ESP+4] = weapon_id
63
- // RET 0x4
64
 
65
  unsafe extern "cdecl" fn subtract_ammo_impl(team_index: u32, arena: TeamArenaRef, weapon_id: u32) {
66
- let (alliance, wid) = arena.weapon_slot_key(team_index as usize, weapon_id);
67
- let state = arena.state_mut();
68
- let ammo = state.get_ammo(alliance, wid);
69
- if ammo > 0 {
70
- *state.ammo_mut(alliance, wid) = ammo - 1;
71
- }
72
  }
73
 
74
  usercall_trampoline!(fn trampoline_subtract_ammo; impl_fn = subtract_ammo_impl;
75
  regs = [eax, ecx]; stack_params = 1; ret_bytes = "0x4");
76
 
77
- // ============================================================
78
- // GetAmmo replacement (0x5225E0)
79
- // ============================================================
80
- // __usercall: EAX = team_index, ESI = team_info_base, EDX = weapon_id
81
- // plain RET, returns EAX = ammo count
82
 
83
  unsafe extern "cdecl" fn get_ammo_impl(
84
  team_index: u32,
85
  arena: TeamArenaRef,
86
  weapon_id: u32,
87
  ) -> u32 {
88
- let (alliance, wid) = arena.weapon_slot_key(team_index as usize, weapon_id);
89
- let state = arena.state();
90
-
91
- // Check weapon delay
92
- if state.get_delay(alliance, wid) != 0 {
93
- if state.game_mode_flag == 0 {
94
- return 0;
95
- }
96
- // In sudden death (phase >= 484), delayed weapons return 0
97
- // unless it's Teleport (weapon 0x28)
98
- if state.game_phase >= ddgame::GAME_PHASE_SUDDEN_DEATH
99
- && weapon_id != Weapon::Teleport as u32
100
- {
101
- return 0;
102
- }
103
- }
104
-
105
- // SelectWorm (0x3B) requires >1 alive worm on the team
106
- if state.game_phase >= ddgame::GAME_PHASE_NORMAL_MIN
107
- && weapon_id == Weapon::SelectWorm as u32
108
- && count_alive_worms_impl(team_index, arena) == 0
109
- {
110
- return 0;
111
- }
112
-
113
- state.get_ammo(alliance, wid) as u32
114
  }
115
 
116
  usercall_trampoline!(fn trampoline_get_ammo; impl_fn = get_ammo_impl;
117
  regs = [eax, esi, edx]);
118
 
119
- // ============================================================
120
- // CountAliveWorms replacement (0x5225A0)
121
- // ============================================================
122
- // __usercall: EAX = team_index, ECX = base
123
- // plain RET, returns EAX = bool (1 if >1 worm alive on team)
124
 
125
  unsafe extern "cdecl" fn count_alive_worms_impl(team_index: u32, arena: TeamArenaRef) -> u32 {
126
- let header = arena.team_header(team_index as usize);
127
- let worm_count = header.worm_count;
128
- let mut alive = 0i32;
129
- for w in 1..=worm_count as usize {
130
- if arena.team_worm(team_index as usize, w).health > 0 {
131
- alive += 1;
132
- }
133
- }
134
- if alive > 1 {
135
- 1
136
- } else {
137
- 0
138
- }
139
  }
140
 
141
  usercall_trampoline!(fn trampoline_count_alive_worms; impl_fn = count_alive_worms_impl;
142
  regs = [eax, ecx]);
143
 
144
- // ============================================================
145
- // FireWeapon (0x51EE60) — trapped, called directly from weapon_release
146
- // ============================================================
147
-
148
- /// FireWeapon dispatch — called directly by `weapon_release_impl`.
149
- ///
150
- /// The WA function at 0x51EE60 is trapped via `install_trap!`; its only
151
- /// caller (WeaponRelease) is ported and invokes this Rust function instead.
152
- ///
153
- /// Dispatches to type-specific fire sub-functions based on `entry.fire_type`
154
- /// and `entry.fire_method` / `entry.special_subtype`.
155
- /// Sets the completion flag at worm+0x3C before and after dispatch.
156
- pub(crate) unsafe fn fire_weapon(
157
- entry: *const WeaponEntry,
158
- ctx: *const WeaponReleaseContext,
159
- worm: *mut CTaskWorm,
160
- ) {
161
- use openwa_core::rebase::rb;
162
-
163
- let fire_type = (*entry).fire_type;
164
- let fire_method = (*entry).fire_method;
165
- let fire_params = &raw const (*entry).fire_params;
166
- // Log weapon fire
167
- let weapon = (*worm).selected_weapon;
168
- let _ = log_line(&format!(
169
- "[Weapon] FireWeapon: {:?} (id={}) type={} sub34={} sub38={}",
170
- weapon,
171
- weapon as u32,
172
- fire_type,
173
- (*entry).special_subtype,
174
- fire_method
175
- ));
176
-
177
- CTaskWorm::set_fire_complete_raw(worm, 0);
178
-
179
- use openwa_core::game::weapon::{FireMethod, FireType};
180
- match FireType::try_from(fire_type) {
181
- Ok(FireType::Projectile) => match FireMethod::try_from(fire_method) {
182
- Ok(FireMethod::PlacedExplosive) => {
183
- call_fire_placed_explosive(worm, fire_params, ctx, rb(0x51EC80))
184
- }
185
- Ok(FireMethod::ProjectileFire) => {
186
- call_fire_stdcall3(worm, fire_params, ctx, rb(0x51DFB0))
187
- }
188
- Ok(FireMethod::CreateWeaponProjectile) => {
189
- call_fire_thiscall2(worm, fire_params, ctx, rb(0x51E0F0))
190
- }
191
- Ok(FireMethod::CreateArrow) => {
192
- call_fire_thiscall2(worm, fire_params, ctx, rb(0x51ED90))
193
- }
194
- _ => {}
195
- },
196
- Ok(FireType::Rope) => match FireMethod::try_from(fire_method) {
197
- Ok(FireMethod::PlacedExplosive) => {
198
- call_fire_stdcall3(worm, fire_params, ctx, rb(0x51E1C0))
199
- } // RopeType1
200
- Ok(FireMethod::ProjectileFire) => {
201
- call_fire_thiscall2(worm, fire_params, ctx, rb(0x51E0F0))
202
- }
203
- Ok(FireMethod::CreateWeaponProjectile) => {
204
- call_fire_stdcall3(worm, fire_params, ctx, rb(0x51E240))
205
- } // RopeType3
206
- _ => {}
207
- },
208
- Ok(FireType::Strike) => {
209
- // StrikeFire takes a pointer to the subtype_34 field (reinterpreted as fire params)
210
- let subtype_34_ptr = &raw const (*entry).special_subtype as *const WeaponFireParams;
211
- call_fire_stdcall3(worm, subtype_34_ptr, ctx, rb(0x51E2C0));
212
- }
213
- Ok(FireType::Special) => {
214
- fire_weapon_special((*entry).special_subtype, entry, worm, ctx);
215
- }
216
- _ => {}
217
- }
218
-
219
- CTaskWorm::set_fire_complete_raw(worm, 1);
220
- }
221
-
222
- // ── Sub-function bridges ────────────────────────────────────
223
- // All bridges save/restore ESI+EDI, set ESI=EDI=worm, then call.
224
- // This preserves LLVM's callee-saved registers while providing
225
- // the usercall context that sub-functions expect.
226
-
227
- /// Bridge: PlacedExplosive — usercall(ECX=local_struct, EDX=worm, [ESP+4]=fire_params), RET 0x4.
228
- /// Args: (worm, fire_params, ctx, addr).
229
- #[unsafe(naked)]
230
- unsafe extern "C" fn call_fire_placed_explosive(
231
- _worm: *mut CTaskWorm,
232
- _fire_params: *const WeaponFireParams,
233
- _ctx: *const WeaponReleaseContext,
234
- _addr: u32,
235
- ) {
236
- core::arch::naked_asm!(
237
- "push ebx",
238
- "push esi",
239
- "push edi",
240
- // Set up usercall registers
241
- // Stack: 3 saves(12) + ret(4) = 16 to first arg
242
- "mov edx, [esp+16]", // EDX = worm
243
- "mov ecx, [esp+24]", // ECX = local_struct
244
- "mov ebx, [esp+28]", // addr
245
- "push [esp+20]", // fire_params (stack param)
246
- "call ebx",
247
- "pop edi",
248
- "pop esi",
249
- "pop ebx",
250
- "ret",
251
- );
252
- }
253
-
254
- /// Bridge: Projectile/Rope/Grenade — stdcall(worm, fire_params, local_struct), RET 0xC.
255
- #[unsafe(naked)]
256
- unsafe extern "C" fn call_fire_stdcall3(
257
- _worm: *mut CTaskWorm,
258
- _fire_params: *const WeaponFireParams,
259
- _ctx: *const WeaponReleaseContext,
260
- _addr: u32,
261
- ) {
262
- core::arch::naked_asm!(
263
- "push ebx",
264
- "push esi",
265
- "push edi",
266
- "mov esi, [esp+16]", // worm (3 saves=12 + ret=4 = 16)
267
- "mov edi, [esp+16]",
268
- "mov ebx, [esp+28]", // addr (saves=12 + ret=4 + 3 args=12 = 28)
269
- "push [esp+24]", // local_struct
270
- "push [esp+24]", // params (shifted +4)
271
- "push [esp+24]", // worm (shifted +8)
272
- "call ebx",
273
- "pop edi",
274
- "pop esi",
275
- "pop ebx",
276
- "ret",
277
- );
278
- }
279
-
280
- /// Bridge: CreateWeaponProjectile — thiscall(ECX=worm, fire_params, local_struct), RET 0x8.
281
- #[unsafe(naked)]
282
- unsafe extern "C" fn call_fire_thiscall2(
283
- _worm: *mut CTaskWorm,
284
- _fire_params: *const WeaponFireParams,
285
- _ctx: *const WeaponReleaseContext,
286
- _addr: u32,
287
- ) {
288
- core::arch::naked_asm!(
289
- "push ebx",
290
- "push esi",
291
- "push edi",
292
- "mov esi, [esp+16]", // worm
293
- "mov edi, [esp+16]",
294
- "mov ecx, [esp+16]", // ECX = worm (this)
295
- "mov ebx, [esp+28]", // addr
296
- "push [esp+24]", // local_struct
297
- "push [esp+24]", // params (shifted +4)
298
- "call ebx",
299
- "pop edi",
300
- "pop esi",
301
- "pop ebx",
302
- "ret",
303
- );
304
- }
305
-
306
- /// Bridge: stdcall(fire_params, local_struct), RET 0x8.
307
- /// Currently unused — was incorrectly used for Shotgun/Longbow (which are thiscall).
308
- #[unsafe(naked)]
309
- #[allow(dead_code)]
310
- unsafe extern "C" fn call_fire_stdcall2(
311
- _worm: *mut CTaskWorm,
312
- _fire_params: *const WeaponFireParams,
313
- _ctx: *const WeaponReleaseContext,
314
- _addr: u32,
315
- ) {
316
- core::arch::naked_asm!(
317
- "push ebx",
318
- "push esi",
319
- "push edi",
320
- "mov esi, [esp+16]", // worm
321
- "mov edi, [esp+16]",
322
- "mov ebx, [esp+28]", // addr
323
- "push [esp+24]", // local_struct
324
- "push [esp+24]", // params (shifted +4)
325
- "call ebx",
326
- "pop edi",
327
- "pop esi",
328
- "pop ebx",
329
- "ret",
330
- );
331
- }
332
-
333
- /// Type 4 (special) weapon dispatch.
334
- ///
335
- /// EAX at entry = weapon entry pointer (unchanged from type-4 switch).
336
- /// Some handlers explicitly set EAX=worm or EAX=*(worm+0x44).
337
- /// Handlers without explicit MOV EAX inherit the entry pointer.
338
- unsafe fn fire_weapon_special(
339
- subtype: i32,
340
- entry: *const WeaponEntry,
341
- worm: *mut CTaskWorm,
342
- ctx: *const WeaponReleaseContext,
343
- ) {
344
- use openwa_core::game::weapon::SpecialFireSubtype as S;
345
-
346
- // Pointer to fire_method field, reinterpreted as fire params pointer for Girder
347
- let params_38_ptr = &raw const (*entry).fire_method as *const WeaponFireParams;
348
-
349
- match S::try_from(subtype) {
350
- Ok(S::FirePunch) => CTaskWorm::set_state_raw(worm, WormState::FirePunch),
351
- Ok(S::BaseballBat) => fire_drill(worm, ctx as *const u8),
352
- Ok(S::DragonBall) => fire_dragon_ball(worm, params_38_ptr, ctx as *const u8),
353
- Ok(S::Kamikaze) => CTaskWorm::set_state_raw(worm, WormState::Kamikaze),
354
- Ok(S::SuicideBomber) => CTaskWorm::set_state_raw(worm, WormState::SuicideBomber),
355
- Ok(S::Unknown6) => CTaskWorm::set_state_raw(worm, WormState::Unknown_0x70),
356
- Ok(S::PneumaticDrill) => CTaskWorm::set_state_raw(worm, WormState::PneumaticDrill),
357
- Ok(S::Prod) => fire_prod(worm, ctx as *const u8),
358
- Ok(S::Teleport) => fire_teleport(worm),
359
- Ok(S::Blowtorch) => CTaskWorm::set_state_raw(worm, WormState::Blowtorch),
360
- Ok(S::Parachute) => {} // TODO: parachute handler
361
- Ok(S::Surrender) => fire_surrender(worm),
362
- Ok(S::MailMineMole) => fire_mail_mine_mole(worm),
363
- Ok(S::NuclearTest) => {
364
- if can_fire_subtype16((*worm).state()) {
365
- fire_nuclear_test(worm);
366
- } else {
367
- CTaskWorm::set_state_raw(worm, WormState::TeleportCancelled_Maybe);
368
- }
369
- }
370
- Ok(S::Girder) => fire_girder(worm),
371
- Ok(S::Unknown18) => CTaskWorm::set_state_raw(worm, WormState::Unknown_0x72),
372
- Ok(S::SkipGo) => fire_skip_go(worm, entry),
373
- Ok(S::Freeze) => fire_freeze(worm),
374
- Ok(S::SelectWorm) => fire_select_worm(worm),
375
- Ok(S::ScalesOfJustice) => fire_scales_of_justice(worm),
376
- Ok(S::JetPack) => CTaskWorm::set_state_raw(worm, WormState::WeaponAimed_Maybe),
377
- Ok(S::Armageddon) => fire_armageddon(worm),
378
- _ => {}
379
- }
380
- }
381
-
382
- /// Worm state validity check for subtype 16 — pure Rust port of 0x516930.
383
- /// Used by Nuclear Test to gate firing.
384
- fn can_fire_subtype16(state: u32) -> bool {
385
- state == WormState::WeaponAimed_Maybe as u32
386
- || (WormState::AimingAngle_Maybe as u32..=WormState::PreFire_Maybe as u32).contains(&state)
387
- }
388
-
389
- // ── Pure Rust fire handlers (no bridge needed) ──────────────
390
-
391
- /// Look up the CTaskTurnGame entity for a worm via SharedData.
392
- ///
393
- /// The entity at key (0, 0x14) is a CTaskTurnGame (inherits CTaskTeam).
394
- /// Returns null if not found.
395
- pub(crate) unsafe fn lookup_turn_game(
396
- worm: *const CTaskWorm,
397
- ) -> *mut openwa_core::task::CTaskTurnGame {
398
- use openwa_core::task::SharedDataTable;
399
-
400
- let table = SharedDataTable::from_task(worm as *const CTask);
401
- table.lookup(0, 0x14) as *mut openwa_core::task::CTaskTurnGame
402
- }
403
-
404
- /// Surrender (subtype 13) — sends message 0x2B (TaskMessage::Surrender) to
405
- /// CTaskTurnGame via vtable dispatch.
406
- ///
407
- /// TurnGame::HandleMessage (0x55DC00) delegates to CTaskTeam (0x557310) for
408
- /// the broadcast, then handles end-turn logic and surrender sound.
409
- #[inline(never)]
410
- unsafe fn fire_surrender(worm: *mut CTaskWorm) {
411
- let team = lookup_turn_game(worm);
412
- if team.is_null() {
413
- return;
414
- }
415
-
416
- let mut buf = [0u8; 0x40C];
417
- buf[0..4].copy_from_slice(&(*worm).team_index.to_ne_bytes());
418
-
419
- // Dispatch through vtable — hits CTaskTurnGame::HandleMessage (0x55DC00)
420
- // which delegates to CTaskTeam (0x557310) and handles end-turn/sound.
421
- CTaskTurnGame::handle_message_raw(
422
- team,
423
- worm as *mut openwa_core::task::CTask,
424
- 0x2B,
425
- 4,
426
- buf.as_ptr(),
427
- );
428
- }
429
-
430
- /// Send a message to CTaskTurnGame via SharedData lookup + vtable dispatch.
431
- ///
432
- /// Shared pattern: look up CTaskTurnGame at key (0, 0x14), write team_index
433
- /// into a 0x40C-byte buffer, and call HandleMessage (vtable slot 2).
434
- ///
435
- /// The 0x40C-byte local buffer is passed as data pointer; team_index is written
436
- /// at buf+0x00 to identify which team fired.
437
- unsafe fn fire_send_team_message(worm: *mut CTaskWorm, msg_type: u32) {
438
- let team = lookup_turn_game(worm);
439
- if team.is_null() {
440
- return;
441
- }
442
-
443
- let mut buf = [0u8; 0x40C];
444
- let team_index = (*worm).team_index;
445
- buf[0..4].copy_from_slice(&team_index.to_ne_bytes());
446
-
447
- CTaskTurnGame::handle_message_raw(
448
- team,
449
- worm as *mut openwa_core::task::CTask,
450
- msg_type,
451
- 4,
452
- buf.as_ptr(),
453
- );
454
- }
455
-
456
- /// Select Worm (subtype 21) — pure Rust replacement for 0x51EBE0.
457
- ///
458
- /// Sends message 0x5D to CTaskTurnGame with buf = [8, team_index, ...].
459
- unsafe fn fire_select_worm(worm: *mut CTaskWorm) {
460
- let team = lookup_turn_game(worm);
461
- if team.is_null() {
462
- return;
463
- }
464
-
465
- let mut buf = [0u8; 0x40C];
466
- buf[0..4].copy_from_slice(&8u32.to_ne_bytes());
467
- buf[4..8].copy_from_slice(&(*worm).team_index.to_ne_bytes());
468
-
469
- CTaskTurnGame::handle_message_raw(
470
- team,
471
- worm as *mut openwa_core::task::CTask,
472
- 0x5D,
473
- 0x408,
474
- buf.as_ptr(),
475
- );
476
- }
477
-
478
- /// Skip Go (subtype 19) — pure Rust replacement for 0x51E8C0.
479
- ///
480
- /// Toggles a bit in the team's `TeamHeader.turn_action_flags` (+0x7C).
481
- /// Bit position comes from weapon entry's fire_params.
482
- /// In game_version > 0x1C: toggles (set/clear). Otherwise: always sets.
483
- unsafe fn fire_skip_go(worm: *const CTaskWorm, entry: *const WeaponEntry) {
484
- use openwa_core::engine::ddgame::TeamArenaRef;
485
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
486
- let game_version = (*(*ddgame).game_info).game_version;
487
- let team_index = (*worm).team_index as usize;
488
-
489
- let bit_index = ((*entry).fire_params.shot_count & 0x1F) as u32;
490
- let bit = 1u32 << bit_index;
491
-
492
- let arena = TeamArenaRef::from_ptr(&raw mut (*ddgame).team_arena);
493
- let header = arena.team_header_mut(team_index);
494
- let flags = header.turn_action_flags;
495
-
496
- if game_version > 0x1C && (flags & bit) != 0 {
497
- header.turn_action_flags = flags & !bit;
498
- } else {
499
- header.turn_action_flags = flags | bit;
500
- }
501
- }
502
-
503
- /// Freeze weapon (subtype 20) — pure Rust replacement for 0x51E600.
504
- ///
505
- /// Sends message 0x29 (TaskMessage::Freeze) to CTaskTurnGame, then increments
506
- /// WormEntry.turn_action_counter_Maybe by 14 (0x0E).
507
- unsafe fn fire_freeze(worm: *mut CTaskWorm) {
508
- use openwa_core::engine::ddgame::TeamArenaRef;
509
-
510
- fire_send_team_message(worm, 0x29);
511
-
512
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
513
- let arena = TeamArenaRef::from_ptr(&raw mut (*ddgame).team_arena);
514
- let team_index = (*worm).team_index as usize;
515
- let worm_index = (*worm).worm_index as usize;
516
- let entry = arena.team_worm_mut(team_index, worm_index);
517
- entry.turn_action_counter_Maybe += 14;
518
- }
519
-
520
- /// Mail/Mine/Mole (subtype 14) — pure Rust replacement for 0x51E670.
521
- ///
522
- /// Conditionally calls worm->vtable[0xE](0x65) based on game version and worm state,
523
- /// then sends message 0x28 to CTaskTurnGame, then increments
524
- /// WormEntry.turn_action_counter_Maybe by 7.
525
- ///
526
- /// Version check logic (from disassembly at 0x51E670):
527
- /// - version < 2: call vtable[0xE](0x65)
528
- /// - 2 <= version < 5: skip vtable call
529
- /// - version >= 5 && worm state == 0x7D: call vtable
530
- /// - version >= 5 && worm state == 0x78 && version < 8: call vtable
531
- /// - otherwise: skip
532
- unsafe fn fire_mail_mine_mole(worm: *mut CTaskWorm) {
533
- use openwa_core::engine::ddgame::TeamArenaRef;
534
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
535
- let version = (*ddgame).version_flag_4;
536
- let worm_state = (*worm).state();
537
-
538
- let should_call_vtable = version < 2
539
- || (version >= 5
540
- && (worm_state == WormState::PreFire_Maybe as u32
541
- || (worm_state == WormState::WeaponAimed_Maybe as u32 && version < 8)));
542
-
543
- if should_call_vtable {
544
- CTaskWorm::set_state_raw(worm, WormState::Idle);
545
- }
546
-
547
- fire_send_team_message(worm, 0x28);
548
-
549
- let arena = TeamArenaRef::from_ptr(&raw mut (*ddgame).team_arena);
550
- let team_index = (*worm).team_index as usize;
551
- let worm_index = (*worm).worm_index as usize;
552
- let entry = arena.team_worm_mut(team_index, worm_index);
553
- entry.turn_action_counter_Maybe += 7;
554
- }
555
 
556
- /// Teleport (subtype 10) — pure Rust port of 0x51E710.
557
- ///
558
- /// If CTaskWorm+0x208 == 0: set state to AirStrikePending_Maybe.
559
- /// Otherwise: play teleport sound (via play_worm_sound_2), spawn visual
560
- /// effect, update position, compute new state, clear action fields.
561
- ///
562
- /// Convention: usercall(EAX=worm, ESI=worm, EDI=worm), plain RET.
563
- unsafe fn fire_teleport(worm: *mut CTaskWorm) {
564
- use crate::replacements::sound;
565
- use openwa_core::rebase::rb;
566
-
567
- if (*worm)._unknown_208 == 0 {
568
- CTaskWorm::set_state_raw(worm, WormState::AirStrikePending_Maybe);
569
- return;
570
- }
571
-
572
- // Play teleport sound (0x36) on secondary sound handle
573
- sound::play_worm_sound_2(worm, SoundId(0x36), Fixed::ONE, 3);
574
-
575
- // Spawn visual effect: usercall(EAX=0x80000, ECX=x) + stdcall(y, 0, 0, 0, 600, 0x10000, 0x1999)
576
- let fire_x = (*worm).weapon_param_1;
577
- let fire_y = (*worm).weapon_param_2;
578
- call_spawn_effect(fire_x, fire_y, rb(0x547C30));
579
-
580
- // Temporarily swap worm+0x34 with worm+0x190, call position update, restore
581
- let worm_raw = worm as *mut u8;
582
- let saved_34 = *(worm_raw.add(0x34) as *const i32);
583
- *(worm_raw.add(0x34) as *mut i32) = (*worm)._unknown_190;
584
- call_position_update(worm, fire_x, fire_y, rb(0x4FE070));
585
- *(worm_raw.add(0x34) as *mut i32) = saved_34;
586
-
587
- // Compute new state: version < 455 → Idle (0x65), else → 0x8B
588
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
589
- let game_version = (*(*ddgame).game_info).game_version;
590
- let new_state = if game_version < 0x1C7 {
591
- WormState::Idle
592
- } else {
593
- WormState::Unknown_0x8B
594
- };
595
- CTaskWorm::set_state_raw(worm, new_state);
596
-
597
- // Clear action fields
598
- *(worm_raw.add(0x48) as *mut i32) = 0;
599
- (*worm)._unknown_208 = 0;
600
- (*worm)._unknown_198 = 0;
601
- (*worm)._unknown_19c = 0;
602
- (*worm).facing_direction_inv = 0;
603
-
604
- // FUN_0050D450: usercall(ESI=worm), cleanup/landing check
605
- call_worm_landing_check(worm, rb(0x50D450));
606
-
607
- // Debug log block (ddgame+0x8144) omitted — only writes to debug file
608
- }
609
-
610
- /// Nuclear Test (subtype 16) — pure Rust port of 0x51EB00.
611
- ///
612
- /// Sends three messages to CTaskTurnGame: RaiseWater (0x59), NukeBlast (0x5A),
613
- /// PoisonWorm (0x51), and plays two sounds. Gated by can_fire_subtype16.
614
- ///
615
- /// Convention: usercall(EAX=worm_state, ESI=worm, EDI=worm), plain RET.
616
- unsafe fn fire_nuclear_test(worm: *mut CTaskWorm) {
617
- use crate::replacements::sound;
618
-
619
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
620
- let entry = &*(*worm).active_weapon_entry;
621
- let team = lookup_turn_game(worm);
622
-
623
- // Message 0x59 (RaiseWater): buf[0]=fire_method, buf[4]=8
624
- if !team.is_null() {
625
- let mut buf = [0u8; 0x40C];
626
- buf[0..4].copy_from_slice(&entry.fire_method.to_ne_bytes());
627
- buf[4..8].copy_from_slice(&8i32.to_ne_bytes());
628
- CTaskTurnGame::handle_message_raw(
629
- team,
630
- worm as *mut openwa_core::task::CTask,
631
- 0x59,
632
- 0x408,
633
- buf.as_ptr(),
634
- );
635
- }
636
-
637
- // Message 0x5A (NukeBlast): buf[0]=8
638
- let team = lookup_turn_game(worm);
639
- if !team.is_null() {
640
- let mut buf = [0u8; 0x40C];
641
- buf[0..4].copy_from_slice(&8i32.to_ne_bytes());
642
- CTaskTurnGame::handle_message_raw(
643
- team,
644
- worm as *mut openwa_core::task::CTask,
645
- 0x5A,
646
- 0x408,
647
- buf.as_ptr(),
648
- );
649
- }
650
-
651
- // PlaySoundGlobal(IndianAnthem, 8, 0x10000, 0x10000)
652
- sound::queue_sound(
653
- ddgame,
654
- KnownSoundId::IndianAnthem.into(),
655
- 8,
656
- Fixed::ONE,
657
- Fixed::ONE,
658
- );
659
-
660
- // Message 0x51 (PoisonWorm): buf[0]=shot_count, buf[4]=2, buf[8]=team_index
661
- let team = lookup_turn_game(worm);
662
- if !team.is_null() {
663
- let mut buf = [0u8; 0x40C];
664
- buf[0..4].copy_from_slice(&entry.fire_params.shot_count.to_ne_bytes());
665
- buf[4..8].copy_from_slice(&2i32.to_ne_bytes());
666
- buf[8..12].copy_from_slice(&(*worm).team_index.to_ne_bytes());
667
- CTaskTurnGame::handle_message_raw(
668
- team,
669
- worm as *mut openwa_core::task::CTask,
670
- 0x51,
671
- 0x408,
672
- buf.as_ptr(),
673
- );
674
- }
675
-
676
- // PlaySoundGlobal(NukeFlash, 5, 0x10000, 0x10000)
677
- sound::queue_sound(
678
- ddgame,
679
- KnownSoundId::NukeFlash.into(),
680
- 5,
681
- Fixed::ONE,
682
- Fixed::ONE,
683
- );
684
- }
685
-
686
- /// Bridge: FUN_00547C30 — usercall(EAX=0x80000, ECX=x) + stdcall(y, 0,0,0, 600, 0x10000, 0x1999).
687
- #[unsafe(naked)]
688
- unsafe extern "C" fn call_spawn_effect(_x: i32, _y: i32, _addr: u32) {
689
- core::arch::naked_asm!(
690
- "push ebx",
691
- // Stack: 1 save(4) + ret(4) = 8 to first arg
692
- "mov ecx, [esp+8]", // x
693
- "mov ebx, [esp+16]", // addr
694
- "push 0x1999",
695
- "push 0x10000",
696
- "push 0x258", // 600
697
- "push 0",
698
- "push 0",
699
- "push 0",
700
- "push [esp+36]", // y (8 + 4 + 6*4 = 36)
701
- "mov eax, 0x80000",
702
- "call ebx",
703
- "pop ebx",
704
- "ret",
705
- );
706
- }
707
-
708
- /// Bridge: FUN_004FE070 — usercall(ESI=worm, EDI=y) + stdcall(x). Plain RET.
709
- #[unsafe(naked)]
710
- unsafe extern "C" fn call_position_update(_worm: *mut CTaskWorm, _x: i32, _y: i32, _addr: u32) {
711
- core::arch::naked_asm!(
712
- "push ebx",
713
- "push esi",
714
- "push edi",
715
- // Stack: 3 saves(12) + ret(4) = 16 to first arg
716
- "mov esi, [esp+16]", // worm
717
- "mov edi, [esp+24]", // y
718
- "mov ebx, [esp+28]", // addr
719
- "push [esp+20]", // x
720
- "call ebx",
721
- "pop edi",
722
- "pop esi",
723
- "pop ebx",
724
- "ret",
725
- );
726
- }
727
-
728
- /// Bridge: FUN_0050D450 — usercall(ESI=worm). Plain RET.
729
- #[unsafe(naked)]
730
- unsafe extern "C" fn call_worm_landing_check(_worm: *mut CTaskWorm, _addr: u32) {
731
- core::arch::naked_asm!(
732
- "push esi",
733
- "mov esi, [esp+8]", // worm (1 save + ret = 8)
734
- "call [esp+12]", // addr (8 + 4 = 12)
735
- "pop esi",
736
- "ret",
737
- );
738
- }
739
-
740
- /// Scales of Justice (subtype 22) — pure Rust port of 0x51EC30.
741
- ///
742
- /// Sends message 0x5E to CTaskTurnGame, then plays a sound.
743
- /// Convention: usercall(EAX=entry, ESI=worm, EDI=worm), plain RET.
744
- unsafe fn fire_scales_of_justice(worm: *mut CTaskWorm) {
745
- use openwa_core::rebase::rb;
746
-
747
- // Send message 0x5E to CTaskTurnGame
748
- let team = lookup_turn_game(worm);
749
- if !team.is_null() {
750
- CTaskTurnGame::handle_message_raw(
751
- team,
752
- worm as *mut openwa_core::task::CTask,
753
- 0x5E,
754
- 0,
755
- core::ptr::null(),
756
- );
757
- }
758
-
759
- // Play jet pack sound:
760
- // FUN_0053EC70: usercall(EDI=0x6CB) + stdcall(timer_obj)
761
- // FUN_005480F0: usercall(EAX=-21) + stdcall(worm, result, 0x17, &worm_name)
762
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
763
- let sound_val = call_get_sound_val((*ddgame).timer_obj, rb(0x53EC70));
764
- call_play_sound_usercall(
765
- worm,
766
- sound_val,
767
- 0x17,
768
- (*worm).worm_name.as_ptr(),
769
- rb(0x5480F0),
770
- );
771
- }
772
-
773
- /// Bridge: FUN_0053EC70 — usercall(EDI=0x6CB) + stdcall(timer_obj). Returns EAX.
774
- #[unsafe(naked)]
775
- unsafe extern "C" fn call_get_sound_val(_timer_obj: *mut u8, _addr: u32) -> u32 {
776
- core::arch::naked_asm!(
777
- "push ebx",
778
- "push edi",
779
- // Stack: 2 saves(8) + ret(4) = 12 to first arg
780
- "mov edi, 0x6CB",
781
- "mov ebx, [esp+16]", // addr
782
- "push [esp+12]", // timer_obj
783
- "call ebx",
784
- "pop edi",
785
- "pop ebx",
786
- "ret",
787
- );
788
- }
789
-
790
- /// Bridge: usercall(EAX=-21) + stdcall(4 params). Plain RET (callee doesn't clean).
791
- #[unsafe(naked)]
792
- unsafe extern "C" fn call_play_sound_usercall(
793
- _worm: *mut CTaskWorm,
794
- _sound_val: u32,
795
- _param3: u32,
796
- _name: *const u8,
797
- _addr: u32,
798
- ) {
799
- core::arch::naked_asm!(
800
- "push ebx",
801
- // Stack: 1 save(4) + ret(4) = 8 to first arg
802
- "mov ebx, [esp+24]", // addr (8 + 4*4 = 24)
803
- "push [esp+20]", // name
804
- "push [esp+20]", // param3 (shifted +4)
805
- "push [esp+20]", // sound_val (shifted +8)
806
- "push [esp+20]", // worm (shifted +12)
807
- "mov eax, 0xFFFFFFEB", // EAX = -21 (usercall param)
808
- "call ebx",
809
- "pop ebx",
810
- "ret",
811
- );
812
- }
813
-
814
- /// Armageddon (subtype 24) — pure Rust port of 0x51EA60.
815
- ///
816
- /// Sends message 0x5B to CTaskTurnGame with weapon/team info, then conditionally
817
- /// sets a gravity center point via FUN_00547E70.
818
- /// Convention: usercall(EAX=entry, ESI=worm, EDI=worm), plain RET.
819
- ///
820
- unsafe fn fire_armageddon(worm: *mut CTaskWorm) {
821
- use openwa_core::rebase::rb;
822
-
823
- // Send message 0x5B (Armageddon) to CTaskTurnGame with weapon info buffer.
824
- //
825
- // The original allocates a 0x410-byte stack buffer, writes fields at offsets
826
- // 0x04/0x08/0x0C/0x10 from the buffer base, then passes (buffer_base + 4)
827
- // as the data pointer to HandleMessage (LEA ECX,[ESP+0x8] after one PUSH
828
- // was cleaned by the SharedData lookup). So HandleMessage sees:
829
- // data[0x00] = 100 (0x64), data[0x04] = 166 (0xA6),
830
- // data[0x08] = weapon_id, data[0x0C] = team_index
831
- let team = lookup_turn_game(worm);
832
- if !team.is_null() {
833
- let mut buf = [0u8; 0x410];
834
- buf[0x00..0x04].copy_from_slice(&100i32.to_ne_bytes());
835
- buf[0x04..0x08].copy_from_slice(&166i32.to_ne_bytes());
836
- buf[0x08..0x0C].copy_from_slice(&((*worm).selected_weapon as u32).to_ne_bytes());
837
- buf[0x0C..0x10].copy_from_slice(&(*worm).team_index.to_ne_bytes());
838
-
839
- CTaskTurnGame::handle_message_raw(
840
- team,
841
- worm as *mut openwa_core::task::CTask,
842
- 0x5B,
843
- 0x408,
844
- buf.as_ptr(),
845
- );
846
- }
847
-
848
- // Re-read DDGame AFTER HandleMessage — the original does this (MOV EAX,[ESI+0x2C]
849
- // at 0x51EAB0 is after the CALL), and HandleMessage may modify game state.
850
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
851
- let game_version = (*(*ddgame).game_info).game_version;
852
-
853
- // If old game version or worm state 0x69, set gravity center
854
- if game_version < 0x50 || (*worm).is_in_state(WormState::Unknown_0x69) {
855
- let ddgame_raw = ddgame as *const u8;
856
- let level_w = *(ddgame_raw.add(0x77C0) as *const i32);
857
- let level_h = *(ddgame_raw.add(0x77C4) as *const i32);
858
- // SHL 16; CDQ; SUB EAX,EDX; SAR 1 — round-toward-zero divide by 2
859
- let half_x = ((level_w << 16) + (if level_w < 0 { 1 } else { 0 })) >> 1;
860
- let half_y = ((level_h << 16) + (if level_h < 0 { 1 } else { 0 })) >> 1;
861
-
862
- call_set_gravity_center(worm, half_x, half_y, rb(0x547E70));
863
- }
864
- }
865
-
866
- /// Bridge: usercall(ECX=half_x, EDX=half_y) + stdcall(worm), RET 0x4.
867
- #[unsafe(naked)]
868
- unsafe extern "C" fn call_set_gravity_center(
869
- _worm: *mut CTaskWorm,
870
- _half_x: i32,
871
- _half_y: i32,
872
- _addr: u32,
873
- ) {
874
- core::arch::naked_asm!(
875
- "push ebx",
876
- // Stack: 1 save(4) + ret(4) = 8 to first arg
877
- "mov ecx, [esp+12]", // half_x
878
- "mov edx, [esp+16]", // half_y
879
- "mov ebx, [esp+20]", // addr
880
- "push [esp+8]", // worm (shifted by 0 extra pushes before this)
881
- "call ebx", // RET 0x4 cleans worm
882
- "pop ebx",
883
- "ret",
884
- );
885
- }
886
-
887
- /// DragonBall (type 4 subtype 3) — pure Rust port of 0x51E350.
888
- ///
889
- /// Allocates a CTaskGirder (0xA4 bytes), copies 7 DWORDs from fire_params
890
- /// as constructor arguments, and calls the constructor. The constructor handles
891
- /// actually placing the girder on the landscape.
892
- ///
893
- /// Convention: stdcall(worm, fire_params, local_struct), RET 0xC.
894
- unsafe fn fire_dragon_ball(
895
- worm: *mut CTaskWorm,
896
- fire_params: *const WeaponFireParams,
897
- local_struct: *const u8,
898
- ) {
899
- use openwa_core::rebase::rb;
900
- use openwa_core::task::SharedDataTable;
901
- use openwa_core::wa_alloc::wa_malloc;
902
-
903
- // Look up parent task via SharedData (same key as CreateWeaponProjectile)
904
- let table = SharedDataTable::from_task(worm as *const CTask);
905
- let parent = table.lookup(0, 0x19);
906
-
907
- // Allocate CTaskGirder (0xA4 bytes), zero first 0x84
908
- let buffer = wa_malloc(0xA4);
909
- if buffer.is_null() {
910
- return;
911
- }
912
- core::ptr::write_bytes(buffer, 0, 0x84);
913
-
914
- // CTaskGirder::Constructor — usercall(EAX=parent) +
915
- // stdcall(this, 7×fire_param DWORDs, local_struct), RET 0x24.
916
- // Copy 7 DWORDs from fire_params onto the stack via the naked bridge.
917
- call_girder_ctor(
918
- buffer,
919
- parent as *mut u8,
920
- fire_params,
921
- local_struct,
922
- rb(0x550890),
923
- );
924
- }
925
-
926
- /// Bridge: CTaskGirder::Constructor — usercall(EAX=parent) +
927
- /// stdcall(this, 7 DWORDs from fire_params, local_struct), RET 0x24.
928
- ///
929
- /// The original copies 7 DWORDs from fire_params onto the stack via REP MOVSD.
930
- /// We replicate this by pushing them individually in reverse order.
931
- #[unsafe(naked)]
932
- unsafe extern "C" fn call_girder_ctor(
933
- _this: *mut u8,
934
- _parent: *mut u8,
935
- _fire_params: *const WeaponFireParams,
936
- _local_struct: *const u8,
937
- _addr: u32,
938
- ) {
939
- core::arch::naked_asm!(
940
- "push ebx",
941
- "push esi",
942
- "push edi",
943
- // Stack: 3 saves(12) + ret(4) = 16 to first arg
944
- // Args: this=+16, parent=+20, fire_params=+24, local_struct=+28, addr=+32
945
- "mov esi, [esp+24]", // ESI = fire_params
946
- "mov eax, [esp+20]", // EAX = parent (usercall)
947
- "mov ebx, [esp+32]", // EBX = ctor address
948
- // Push constructor args in reverse: local_struct, 7 DWORDs, this
949
- "push [esp+28]", // local_struct (B+28 → stack pos 1)
950
- "push [esi+24]", // fire_params[6]
951
- "push [esi+20]", // fire_params[5]
952
- "push [esi+16]", // fire_params[4]
953
- "push [esi+12]", // fire_params[3]
954
- "push [esi+8]", // fire_params[2]
955
- "push [esi+4]", // fire_params[1]
956
- "push [esi]", // fire_params[0] (B-28 → stack pos 8)
957
- "push [esp+48]", // this: B-32+48 = B+16 ✓
958
- "call ebx", // RET 0x24 cleans 9 params
959
- "pop edi",
960
- "pop esi",
961
- "pop ebx",
962
- "ret",
963
- );
964
- }
965
-
966
- /// Girder/GirderPack (subtype 17) — pure Rust port of 0x51E920.
967
- ///
968
- /// Plays a sound, optionally creates a visual overlay on the
969
- /// landscape and increments worm counters. The visual/counter path only runs
970
- /// when CTaskWorm+0x2EC (weapon_param_3) is nonzero.
971
- ///
972
- /// Convention: usercall(EAX=worm, ESI=worm, EDI=worm), plain RET.
973
- unsafe fn fire_girder(worm: *mut CTaskWorm) {
974
- use crate::replacements::sound;
975
-
976
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
977
- let game_version = (*(*ddgame).game_info).game_version;
978
-
979
- // Read girder position and sprite index from CTaskWorm fields
980
- let girder_x = (*worm).weapon_param_1;
981
- let girder_y = (*worm).weapon_param_2;
982
- let girder_sprite = (*worm).weapon_param_3;
983
-
984
- // Choose sound: 0x70 if girder has sprite or old version, else 0x73
985
- let sound_id: u32 = if girder_sprite != 0 || game_version < 0x21 {
986
- 0x70
987
- } else {
988
- 0x73
989
- };
990
-
991
- // Queue sound and set position to the girder location (local sound)
992
- if let Some(entry) = sound::queue_sound(ddgame, SoundId(sound_id), 3, Fixed::ONE, Fixed::ONE) {
993
- (*entry).is_local = 1;
994
- (*entry).pos_x = girder_x as u32;
995
- (*entry).pos_y = girder_y as u32;
996
- }
997
-
998
- // If girder has a sprite, apply the visual overlay and update counters
999
- if girder_sprite != 0 {
1000
- // Call PCLandscape vtable[5] to create girder overlay
1001
- let landscape = (*ddgame).landscape as *mut u8;
1002
- let landscape_vt = *(landscape as *const *const usize);
1003
- let girder_visual: unsafe extern "thiscall" fn(*mut u8, i32, i32, *mut u8, *mut u8) =
1004
- core::mem::transmute(*landscape_vt.add(5));
1005
- let sprite1 = (*ddgame).sprite_cache_2[girder_sprite as usize];
1006
- let sprite2 = (*ddgame).sprite_cache_2[19 + girder_sprite as usize];
1007
- girder_visual(landscape, girder_x >> 16, girder_y >> 16, sprite1, sprite2);
1008
-
1009
- // Increment WormEntry counters
1010
- let arena =
1011
- openwa_core::engine::ddgame::TeamArenaRef::from_ptr(&raw mut (*ddgame).team_arena);
1012
- let team_index = (*worm).team_index as usize;
1013
- let worm_index = (*worm).worm_index as usize;
1014
- let entry = arena.team_worm_mut(team_index, worm_index);
1015
- entry.turn_action_counter_Maybe += 3;
1016
- entry.effect_counter_04_Maybe += 10;
1017
- }
1018
- }
1019
-
1020
- // ── SpecialImpact wrapper ─────────────────────────────────
1021
-
1022
- /// Typed wrapper for SpecialImpact (0x5193D0).
1023
- /// Convention: stdcall with 13 params (RET 0x34 = 52 bytes).
1024
- ///
1025
- /// Used by Drill, Prod, and other melee/impact weapons. Applies damage in
1026
- /// a directional area from the worm's position.
1027
- #[allow(clippy::too_many_arguments)]
1028
- unsafe fn call_special_impact(
1029
- worm: *mut CTaskWorm,
1030
- x: i32,
1031
- y: i32,
1032
- radius_x: i32,
1033
- radius_y: i32,
1034
- weapon_type: i32,
1035
- dx: i32,
1036
- dy: i32,
1037
- p8: i32,
1038
- p9: i32,
1039
- p10: i32,
1040
- flags: u32,
1041
- p12: i32,
1042
- ) {
1043
- use openwa_core::rebase::rb;
1044
- type SpecialImpactFn = unsafe extern "stdcall" fn(
1045
- *mut CTaskWorm,
1046
- i32,
1047
- i32,
1048
- i32,
1049
- i32,
1050
- i32,
1051
- i32,
1052
- i32,
1053
- i32,
1054
- i32,
1055
- i32,
1056
- u32,
1057
- i32,
1058
- );
1059
- let func: SpecialImpactFn = core::mem::transmute(rb(va::SPECIAL_IMPACT));
1060
- func(
1061
- worm,
1062
- x,
1063
- y,
1064
- radius_x,
1065
- radius_y,
1066
- weapon_type,
1067
- dx,
1068
- dy,
1069
- p8,
1070
- p9,
1071
- p10,
1072
- flags,
1073
- p12,
1074
- );
1075
- }
1076
-
1077
- /// Compute version-dependent flags for SpecialImpact.
1078
- ///
1079
- /// Pattern shared by Drill and Prod:
1080
- /// - Base flags OR 0x20 if version >= 2
1081
- /// - Base flags OR 0x10 if version >= 8
1082
- fn special_impact_version_flags(base: u32, version: u8) -> u32 {
1083
- let mut flags = base;
1084
- if version >= 2 {
1085
- flags |= 0x20;
1086
- }
1087
- if version >= 8 {
1088
- flags |= 0x10;
1089
- }
1090
- flags
1091
- }
1092
-
1093
- /// BaseballBat (subtype 2) — pure Rust port of 0x51E3E0.
1094
- ///
1095
- /// Calls SpecialImpact with facing-offset position and scaled direction.
1096
- /// The original is usercall(ECX=local_struct, ESI=worm) — the old bridge
1097
- /// did not set ECX, so this port also fixes a latent bug.
1098
- unsafe fn fire_drill(worm: *mut CTaskWorm, local_struct: *const u8) {
1099
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
1100
- let version = (*ddgame).version_flag_4;
1101
- let entry = &*(*worm).active_weapon_entry;
1102
- let shot_count = entry.fire_params.shot_count;
1103
- let weapon_type = entry.fire_method;
1104
- let facing = (*worm).facing_direction_2;
1105
-
1106
- // Cast local_struct to WeaponSpawnData for field access (offsets match)
1107
- let spawn = &*(local_struct as *const WeaponSpawnData);
1108
-
1109
- let x = facing * 0x1A_0000 + spawn.spawn_x.0;
1110
- let y = spawn.spawn_y.0;
1111
- let dx = (spawn.initial_speed_x.0 * shot_count) / 10;
1112
- let dy = (spawn.initial_speed_y.0 * shot_count) / 10;
1113
- let flags = special_impact_version_flags(0x21C4C, version);
1114
-
1115
- call_special_impact(
1116
- worm,
1117
- x,
1118
- y,
1119
- 0x1A_0000,
1120
- 0x1E_0000,
1121
- weapon_type,
1122
- dx,
1123
- dy,
1124
- 6,
1125
- 0x61,
1126
- 0x51,
1127
- flags,
1128
- 1,
1129
- );
1130
- }
1131
-
1132
- /// Prod (subtype 9) — pure Rust port of 0x51E480.
1133
- ///
1134
- /// Like Drill but with trig interpolation on the spread angle.
1135
- /// Convention: usercall(EDI=worm) + 1 stack param (local_struct), RET 0x4.
1136
- unsafe fn fire_prod(worm: *mut CTaskWorm, local_struct: *const u8) {
1137
- use openwa_core::rebase::rb;
1138
-
1139
- let ddgame = CTask::ddgame_raw(worm as *const CTask);
1140
- let version = (*ddgame).version_flag_4;
1141
- let entry = &*(*worm).active_weapon_entry;
1142
- let shot_count = entry.fire_params.shot_count;
1143
- let spread = entry.fire_params.spread;
1144
- let weapon_type = entry.fire_method;
1145
- let facing = (*worm).facing_direction_2;
1146
-
1147
- let spawn = &*(local_struct as *const WeaponSpawnData);
1148
-
1149
- // Convert spread (degrees) to engine angle units: (spread << 16) / 360
1150
- let angle = ((spread as u32) << 16) / 0x168;
1151
-
1152
- // Interpolated sin/cos lookup (same pattern as projectile_fire_impl)
1153
- let sin_table = rb(va::SIN_TABLE) as *const i32;
1154
- let cos_table = sin_table.add(256);
1155
-
1156
- let table_index = ((angle >> 6) & 0x3FF) as usize;
1157
- let frac = ((angle & 0x3F) << 10) as i32;
1158
-
1159
- let cos_base = *cos_table.add(table_index);
1160
- let cos_next = *cos_table.add(table_index + 1);
1161
- let cos_val = cos_base + fixed_mul(cos_next - cos_base, frac);
1162
-
1163
- let sin_base = *sin_table.add(table_index);
1164
- let sin_next = *sin_table.add(table_index + 1);
1165
- let sin_val = sin_base + fixed_mul(sin_next - sin_base, frac);
1166
-
1167
- // Scale trig results by shot_count and divide by 10.
1168
- // In WA's coordinate system (Y increases downward), the vertical component is negated.
1169
- // Original asm uses IMUL 0x99999999 (= -0x66666667) for dy, which negates the result.
1170
- // dx = (sin_val * shot_count) / 10 * facing
1171
- // dy = -(cos_val * shot_count) / 10
1172
- let dx = ((sin_val * shot_count) / 10) * facing;
1173
- let dy = -((cos_val * shot_count) / 10);
1174
-
1175
- let x = facing * 0x6_0000 + spawn.spawn_x.0;
1176
- let y = spawn.spawn_y.0;
1177
- let flags = special_impact_version_flags(0xC4C, version);
1178
-
1179
- call_special_impact(
1180
- worm,
1181
- x,
1182
- y,
1183
- 0xC_0000,
1184
- 0xC_0000,
1185
- weapon_type,
1186
- dx,
1187
- dy,
1188
- 0,
1189
- 0,
1190
- 0,
1191
- flags,
1192
- 1,
1193
- );
1194
- }
1195
-
1196
- // ── Naked asm bridges ───────────────────────────────────────
1197
-
1198
- /// Bridge: ProjectileFire_Single — usercall(EDI=spawn_data, stack=[worm, fire_params]), RET 0x8.
1199
- /// Args: (spawn_data, worm, fire_params, addr).
1200
- #[unsafe(naked)]
1201
- unsafe extern "C" fn call_projectile_fire_single(
1202
- _spawn_data: *const WeaponSpawnData,
1203
- _worm: *mut CTaskWorm,
1204
- _fire_params: *const WeaponFireParams,
1205
- _addr: u32,
1206
- ) {
1207
- core::arch::naked_asm!(
1208
- "push ebx",
1209
- "push esi",
1210
- "push edi",
1211
- // Stack: 3 saves(12) + ret(4) = 16 to first arg
1212
- "mov edi, [esp+16]", // EDI = spawn_data
1213
- "mov ebx, [esp+28]", // addr
1214
- "push [esp+24]", // fire_params
1215
- "push [esp+24]", // worm (shifted +4)
1216
- "call ebx", // RET 0x8 cleans 2 params
1217
- "pop edi",
1218
- "pop esi",
1219
- "pop ebx",
1220
- "ret",
1221
- );
1222
- }
1223
-
1224
- /// Bridge: CTaskMissile::Constructor — thiscall(ECX=this, parent, fire_params, spawn_data), RET 0xC.
1225
- /// Args: (this, parent, fire_params, spawn_data, ctor_addr).
1226
- #[unsafe(naked)]
1227
- unsafe extern "C" fn call_missile_ctor(
1228
- _this: *mut u8,
1229
- _parent: *mut u8,
1230
- _fire_params: *const WeaponFireParams,
1231
- _spawn_data: *const u8,
1232
- _addr: u32,
1233
- ) {
1234
- core::arch::naked_asm!(
1235
- "push ebx",
1236
- "push esi",
1237
- "push edi",
1238
- // Stack: 3 saves(12) + ret(4) = 16 to first arg
1239
- "mov ecx, [esp+16]", // ECX = this (buffer)
1240
- "mov ebx, [esp+32]", // addr (16 + 4*4 args = 32)
1241
- "push [esp+28]", // spawn_data
1242
- "push [esp+28]", // fire_params (shifted +4)
1243
- "push [esp+28]", // parent (shifted +8)
1244
- "call ebx", // thiscall: RET 0xC cleans 3 params
1245
- "pop edi",
1246
- "pop esi",
1247
- "pop ebx",
1248
- "ret",
1249
- );
1250
- }
1251
-
1252
- // ============================================================
1253
- // Passthrough hooks — fire sub-functions
1254
- // ============================================================
1255
- // These hooks log parameters, then call the original WA function.
1256
- // They exist for RE discovery and validation — no behavior change.
1257
-
1258
- static ORIG_CREATE_WEAPON_PROJECTILE: AtomicU32 = AtomicU32::new(0);
1259
- static ORIG_PROJECTILE_FIRE: AtomicU32 = AtomicU32::new(0);
1260
  static ORIG_STRIKE_FIRE: AtomicU32 = AtomicU32::new(0);
1261
  static ORIG_PLACED_EXPLOSIVE: AtomicU32 = AtomicU32::new(0);
1262
 
1263
- /// Full replacement for CreateWeaponProjectile (0x51E0F0).
1264
- /// Convention: thiscall(ECX=worm, fire_params, local_struct), RET 0x8.
1265
- ///
1266
- /// Allocates a CTaskMissile, calls the original constructor, and returns.
1267
- /// The constructor handles SharedData registration and pool management.
1268
  #[unsafe(naked)]
1269
  unsafe extern "C" fn trampoline_create_weapon_projectile() {
1270
  core::arch::naked_asm!(
1271
- // thiscall: ECX=worm, stack=[ret, fire_params, local_struct]
1272
- // Push cdecl args for Rust impl
1273
- "push dword ptr [esp+8]", // local_struct (ret=4 + param1=4 = 8)
1274
- "push dword ptr [esp+8]", // fire_params (shifted +4)
1275
- "push ecx", // worm (this)
1276
  "call {impl_fn}",
1277
  "add esp, 12",
1278
- "ret 0x8", // clean 2 stack params
1279
- impl_fn = sym create_weapon_projectile_impl,
1280
  );
1281
  }
1282
 
1283
- /// Rust implementation of CreateWeaponProjectile.
1284
- ///
1285
- /// Original: 0x51E0F0. Allocates CTaskMissile (0x40C bytes), looks up
1286
- /// parent CTaskTurnGame via SharedData, calls the original constructor.
1287
- unsafe extern "cdecl" fn create_weapon_projectile_impl(
1288
  worm: *mut CTaskWorm,
1289
  fire_params: *const WeaponFireParams,
1290
  local_struct: *const u8,
1291
  ) {
1292
- use openwa_core::rebase::rb;
1293
- use openwa_core::task::SharedDataTable;
1294
- use openwa_core::wa_alloc::wa_malloc;
1295
-
1296
- let ddgame = &mut *CTask::ddgame_raw(worm as *const CTask);
1297
-
1298
- // Pool capacity check: pool_count + 7 must be <= 700
1299
- if ddgame.object_pool_count + 7 > 700 {
1300
- ddgame.show_pool_overflow_warning();
1301
- return;
1302
- }
1303
-
1304
- // Look up parent CTaskTurnGame via SharedData (key_esi=0, key_edi=0x19)
1305
- let table = SharedDataTable::from_task(worm as *const CTask);
1306
- let parent = table.lookup(0, 0x19);
1307
-
1308
- // Allocate CTaskMissile (0x40C bytes)
1309
- let buffer = wa_malloc(0x40C);
1310
- if buffer.is_null() {
1311
- return;
1312
- }
1313
-
1314
- // Zero bytes 0x00..0x3EC (the original only zeros 0x3EC of 0x40C)
1315
- core::ptr::write_bytes(buffer, 0, 0x3EC);
1316
-
1317
- // Call original CTaskMissile::Constructor
1318
- // thiscall(ECX=buffer, parent, fire_params, local_struct), RET 0xC
1319
- call_missile_ctor(
1320
- buffer,
1321
- parent as *mut u8,
1322
- fire_params,
1323
- local_struct,
1324
- rb(va::CTASK_MISSILE_CTOR),
1325
- );
1326
-
1327
- let _ = log_line(&format!(
1328
- "[Weapon] CreateWeaponProjectile: worm=0x{:08X} missile=0x{:08X}",
1329
- worm as u32, buffer as u32,
1330
- ));
1331
  }
1332
 
1333
- /// Full replacement for ProjectileFire (0x51DFB0).
1334
- /// Convention: stdcall(worm, fire_params, local_struct), RET 0xC.
1335
- ///
1336
- /// Builds spawn data with RNG-randomized spread, then calls
1337
- /// ProjectileFire_Single per projectile. Used by Uzi, Handgun, Minigun.
1338
  #[unsafe(naked)]
1339
  unsafe extern "C" fn trampoline_projectile_fire() {
1340
  core::arch::naked_asm!(
1341
- // stdcall: stack=[ret, worm, fire_params, local_struct]
1342
- "push dword ptr [esp+12]", // local_struct
1343
- "push dword ptr [esp+12]", // fire_params (shifted +4)
1344
- "push dword ptr [esp+12]", // worm (shifted +8)
1345
  "call {impl_fn}",
1346
  "add esp, 12",
1347
- "ret 0xC", // clean 3 stack params
1348
- impl_fn = sym projectile_fire_impl,
1349
  );
1350
  }
1351
 
1352
- /// Rust implementation of ProjectileFire.
1353
- ///
1354
- /// Algorithm (from disasm at 0x51DFB0):
1355
- /// 1. Copy 11 DWORDs from local_struct (spawn template) to local buffer
1356
- /// 2. Loop fire_params+0xC times:
1357
- /// a. Advance game RNG
1358
- /// b. Random spread angle from RNG × fire_params+0x10 / 360
1359
- /// c. Cos/sin table lookup with linear interpolation
1360
- /// d. 2D rotation matrix on template velocity
1361
- /// e. Write rotated velocity into local spawn data
1362
- /// f. Call ProjectileFire_Single(loop_counter, fire_params) with EDI=spawn_data
1363
- unsafe extern "cdecl" fn projectile_fire_impl(
1364
  worm: *mut CTaskWorm,
1365
  fire_params: *const WeaponFireParams,
1366
- local_struct: *const WeaponSpawnData,
1367
  ) {
1368
- use openwa_core::rebase::rb;
1369
-
1370
- let params = &*fire_params;
1371
- // collision_radius field is polymorphic — for ProjectileFire it holds the shot count
1372
- let shot_count = params.collision_radius.0;
1373
- if shot_count <= 0 {
1374
- return;
1375
- }
1376
-
1377
- // Copy spawn template from caller's stack buffer
1378
- let mut spawn_data = *local_struct;
1379
-
1380
- // Read template velocity (will be rotated per-shot)
1381
- let template_speed_x = spawn_data.initial_speed_x.0;
1382
- let template_speed_y = spawn_data.initial_speed_y.0;
1383
-
1384
- // Trig table: sin at SIN_TABLE, cos at SIN_TABLE + 256*4
1385
- let sin_table = rb(va::SIN_TABLE) as *const i32;
1386
- let cos_table = sin_table.add(256); // cos = sin offset by 256 entries (quarter turn)
1387
-
1388
- let ddgame = &mut *CTask::ddgame_raw(worm as *const CTask);
1389
-
1390
- for _i in 0..shot_count {
1391
- // Advance game RNG (same LCG as ADVANCE_GAME_RNG at 0x53F320)
1392
- let rng = ddgame.advance_rng();
1393
-
1394
- // Compute spread angle: ((rng_low16 - 0x8000) * spread_param) / 360
1395
- // _fp_04 field is polymorphic — for ProjectileFire it holds spread angle
1396
- let rng_centered = (rng & 0xFFFF) as i32 - 0x8000;
1397
- let spread_param = params._fp_04;
1398
- let angle = (rng_centered * spread_param) / 360;
1399
-
1400
- // Cos/sin table lookup with linear interpolation
1401
- // Table index = (angle >> 6) & 0x3FF (1024 entries)
1402
- // Fractional = (angle & 0x3F) << 10
1403
- let table_index = ((angle >> 6) & 0x3FF) as usize;
1404
- let frac = ((angle & 0x3F) << 10) as i32;
1405
-
1406
- let cos_base = *cos_table.add(table_index);
1407
- let cos_next = *cos_table.add(table_index + 1);
1408
- let cos_val = cos_base + fixed_mul(cos_next - cos_base, frac);
1409
-
1410
- let sin_base = *sin_table.add(table_index);
1411
- let sin_next = *sin_table.add(table_index + 1);
1412
- let sin_val = sin_base + fixed_mul(sin_next - sin_base, frac);
1413
-
1414
- // 2D rotation matrix:
1415
- // speed_x = cos * template_x + sin * template_y
1416
- // speed_y = -sin * template_x + cos * template_y
1417
- let speed_x = fixed_mul(cos_val, template_speed_x) + fixed_mul(sin_val, template_speed_y);
1418
- let speed_y = fixed_mul(-sin_val, template_speed_x) + fixed_mul(cos_val, template_speed_y);
1419
-
1420
- // Write rotated velocity into spawn data
1421
- spawn_data.initial_speed_x = Fixed(speed_x);
1422
- spawn_data.initial_speed_y = Fixed(speed_y);
1423
-
1424
- // Call ProjectileFire_Single(worm, fire_params) with EDI=&spawn_data
1425
- call_projectile_fire_single(
1426
- &raw const spawn_data,
1427
- worm,
1428
- fire_params,
1429
- rb(va::PROJECTILE_FIRE_SINGLE),
1430
- );
1431
- }
1432
-
1433
- let _ = log_line(&format!(
1434
- "[Weapon] ProjectileFire: worm=0x{:08X} shots={}",
1435
- worm as u32, shot_count,
1436
- ));
1437
  }
1438
 
1439
- /// Fixed-point 16.16 multiply: (a * b) >> 16, using full 64-bit intermediate.
1440
- #[inline(always)]
1441
- fn fixed_mul(a: i32, b: i32) -> i32 {
1442
- ((a as i64 * b as i64) >> 16) as i32
1443
- }
1444
 
1445
- /// Full replacement for CreateArrow (0x51ED90).
1446
- /// Convention: thiscall(ECX=worm, fire_params, local_struct), RET 0x8.
1447
- ///
1448
- /// Allocates a CTaskArrow (0x168 bytes), calls the original stdcall constructor.
1449
- /// Used by Shotgun and Longbow.
1450
  #[unsafe(naked)]
1451
  unsafe extern "C" fn trampoline_create_arrow() {
1452
  core::arch::naked_asm!(
@@ -1456,60 +132,29 @@ unsafe extern "C" fn trampoline_create_arrow() {
1456
  "call {impl_fn}",
1457
  "add esp, 12",
1458
  "ret 0x8",
1459
- impl_fn = sym create_arrow_impl,
1460
  );
1461
  }
1462
 
1463
- unsafe extern "cdecl" fn create_arrow_impl(
1464
  worm: *mut CTaskWorm,
1465
  fire_params: *const WeaponFireParams,
1466
  local_struct: *const u8,
1467
  ) {
1468
- use openwa_core::rebase::rb;
1469
- use openwa_core::task::SharedDataTable;
1470
- use openwa_core::wa_alloc::wa_malloc;
1471
-
1472
- let ddgame = &mut *CTask::ddgame_raw(worm as *const CTask);
1473
-
1474
- // Pool capacity check: pool_count + 2 must be <= 700
1475
- if ddgame.object_pool_count + 2 > 700 {
1476
- ddgame.show_pool_overflow_warning();
1477
- return;
1478
- }
1479
-
1480
- // Look up parent CTaskTurnGame via SharedData (key 0, 0x19)
1481
- let table = SharedDataTable::from_task(worm as *const CTask);
1482
- let parent = table.lookup(0, 0x19);
1483
-
1484
- // Allocate CTaskArrow (0x168 bytes)
1485
- let buffer = wa_malloc(0x168);
1486
- if buffer.is_null() {
1487
- return;
1488
- }
1489
- core::ptr::write_bytes(buffer, 0, 0x148);
1490
-
1491
- // CTaskArrow::Constructor — stdcall(this, parent, fire_params, local_struct), RET 0x10
1492
- let ctor: unsafe extern "stdcall" fn(*mut u8, *mut u8, *const WeaponFireParams, *const u8) =
1493
- core::mem::transmute(rb(va::CTASK_ARROW_CTOR));
1494
- ctor(buffer, parent as *mut u8, fire_params, local_struct);
1495
-
1496
- let _ = log_line(&format!(
1497
- "[Weapon] CreateArrow: worm=0x{:08X} arrow=0x{:08X}",
1498
- worm as u32, buffer as u32,
1499
- ));
1500
  }
1501
 
1502
- /// Passthrough hook for StrikeFire (0x51E2C0).
1503
- /// Convention: stdcall(worm, &subtype_34, local_struct), RET 0xC.
1504
  #[unsafe(naked)]
1505
  unsafe extern "C" fn trampoline_strike_fire() {
1506
  core::arch::naked_asm!(
1507
  "push eax",
1508
  "push ecx",
1509
  "push edx",
1510
- "push dword ptr [esp+24]", // local_struct
1511
- "push dword ptr [esp+24]", // subtype_34_ptr
1512
- "push dword ptr [esp+24]", // worm
1513
  "call {log_fn}",
1514
  "add esp, 12",
1515
  "pop edx",
@@ -1528,12 +173,11 @@ unsafe extern "cdecl" fn log_strike_fire(worm: u32, subtype_34_ptr: u32, local_s
1528
  ));
1529
  }
1530
 
1531
- /// Passthrough hook for PlacedExplosive (0x51EC80).
1532
- /// Convention: usercall(ECX=local_struct, EDX=worm, [ESP+4]=fire_params), RET 0x4.
1533
  #[unsafe(naked)]
1534
  unsafe extern "C" fn trampoline_placed_explosive() {
1535
  core::arch::naked_asm!(
1536
- // Save ALL registers — ECX and EDX are usercall params!
1537
  "push eax",
1538
  "push ecx",
1539
  "push edx",
@@ -1541,13 +185,11 @@ unsafe extern "C" fn trampoline_placed_explosive() {
1541
  "push esi",
1542
  "push edi",
1543
  "push ebp",
1544
- // Log: push cdecl args
1545
- "push dword ptr [esp+32]", // fire_params (7 saves=28 + ret=4 = 32)
1546
- "push edx", // worm (still valid, saved above)
1547
- "push ecx", // local_struct (still valid)
1548
  "call {log_fn}",
1549
  "add esp, 12",
1550
- // Restore ALL (ECX and EDX restored for usercall!)
1551
  "pop ebp",
1552
  "pop edi",
1553
  "pop esi",
@@ -1555,7 +197,6 @@ unsafe extern "C" fn trampoline_placed_explosive() {
1555
  "pop edx",
1556
  "pop ecx",
1557
  "pop eax",
1558
- // Call original (usercall — ECX, EDX, stack all intact)
1559
  "jmp [{orig}]",
1560
  log_fn = sym log_placed_explosive,
1561
  orig = sym ORIG_PLACED_EXPLOSIVE,
@@ -1569,9 +210,7 @@ unsafe extern "cdecl" fn log_placed_explosive(local_struct: u32, worm: u32, fire
1569
  ));
1570
  }
1571
 
1572
- // ============================================================
1573
- // Hook installation
1574
- // ============================================================
1575
 
1576
  pub fn install() -> Result<(), String> {
1577
  unsafe {
@@ -1589,19 +228,24 @@ pub fn install() -> Result<(), String> {
1589
  )?;
1590
  hook::install_trap!("FireWeapon", va::FIRE_WEAPON);
1591
 
1592
- // Passthrough hooks on fire sub-functions (log + call original)
1593
- let t = hook::install(
1594
  "CreateWeaponProjectile",
1595
  va::CREATE_WEAPON_PROJECTILE,
1596
  trampoline_create_weapon_projectile as *const (),
1597
  )?;
1598
- ORIG_CREATE_WEAPON_PROJECTILE.store(t as u32, Ordering::Relaxed);
1599
- let t = hook::install(
1600
  "ProjectileFire",
1601
  va::PROJECTILE_FIRE,
1602
  trampoline_projectile_fire as *const (),
1603
  )?;
1604
- ORIG_PROJECTILE_FIRE.store(t as u32, Ordering::Relaxed);
 
 
 
 
 
 
1605
  let t = hook::install(
1606
  "StrikeFire",
1607
  va::STRIKE_FIRE,
@@ -1614,11 +258,6 @@ pub fn install() -> Result<(), String> {
1614
  trampoline_placed_explosive as *const (),
1615
  )?;
1616
  ORIG_PLACED_EXPLOSIVE.store(t as u32, Ordering::Relaxed);
1617
- let _ = hook::install(
1618
- "CreateArrow",
1619
- va::CREATE_ARROW,
1620
- trampoline_create_arrow as *const (),
1621
- )?;
1622
  }
1623
 
1624
  Ok(())
 
1
  //! Weapon hooks.
2
  //!
3
+ //! Thin wormkit shim — all game logic lives in `openwa_core::game::weapon_fire`.
4
+ //! This file contains usercall trampolines, passthrough hooks, and installation.
 
 
 
 
5
  //!
6
+ //! Hooks:
7
+ //! - AddAmmo (0x522640), SubtractAmmo (0x522680), GetAmmo (0x5225E0)
8
+ //! - CountAliveWorms (0x5225A0)
9
+ //! - FireWeapon (0x51EE60): trapped (called directly from weapon_release)
10
+ //! - CreateWeaponProjectile (0x51E0F0), ProjectileFire (0x51DFB0), CreateArrow (0x51ED90)
11
+ //! - StrikeFire (0x51E2C0), PlacedExplosive (0x51EC80): passthrough (log + call original)
12
 
13
  use core::sync::atomic::{AtomicU32, Ordering};
14
 
15
  use openwa_core::address::va;
16
+ use openwa_core::engine::ddgame::TeamArenaRef;
17
+ use openwa_core::game::weapon::WeaponFireParams;
18
+ use openwa_core::game::weapon_fire;
 
 
19
  use openwa_core::log::log_line;
20
+ use openwa_core::task::worm::CTaskWorm;
 
 
21
 
22
  use crate::hook::{self, usercall_trampoline};
 
23
 
24
+ // ── AddAmmo (0x522640): usercall(EAX=team, EDX=amount, stack=arena,weapon_id) ──
 
 
 
 
25
 
26
  unsafe extern "cdecl" fn add_ammo_impl(
27
  team_index: u32,
 
29
  arena: TeamArenaRef,
30
  weapon_id: u32,
31
  ) {
32
+ weapon_fire::add_ammo(team_index, amount, arena, weapon_id);
 
 
 
 
 
 
 
 
 
33
  }
34
 
35
  usercall_trampoline!(fn trampoline_add_ammo; impl_fn = add_ammo_impl;
36
  regs = [eax, edx]; stack_params = 2; ret_bytes = "0x8");
37
 
38
+ // ── SubtractAmmo (0x522680): usercall(EAX=team, ECX=arena, stack=weapon_id) ──
 
 
 
 
39
 
40
  unsafe extern "cdecl" fn subtract_ammo_impl(team_index: u32, arena: TeamArenaRef, weapon_id: u32) {
41
+ weapon_fire::subtract_ammo(team_index, arena, weapon_id);
 
 
 
 
 
42
  }
43
 
44
  usercall_trampoline!(fn trampoline_subtract_ammo; impl_fn = subtract_ammo_impl;
45
  regs = [eax, ecx]; stack_params = 1; ret_bytes = "0x4");
46
 
47
+ // ── GetAmmo (0x5225E0): usercall(EAX=team, ESI=arena, EDX=weapon_id) ──
 
 
 
 
48
 
49
  unsafe extern "cdecl" fn get_ammo_impl(
50
  team_index: u32,
51
  arena: TeamArenaRef,
52
  weapon_id: u32,
53
  ) -> u32 {
54
+ weapon_fire::get_ammo(team_index, arena, weapon_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  }
56
 
57
  usercall_trampoline!(fn trampoline_get_ammo; impl_fn = get_ammo_impl;
58
  regs = [eax, esi, edx]);
59
 
60
+ // ── CountAliveWorms (0x5225A0): usercall(EAX=team, ECX=arena) ──
 
 
 
 
61
 
62
  unsafe extern "cdecl" fn count_alive_worms_impl(team_index: u32, arena: TeamArenaRef) -> u32 {
63
+ weapon_fire::count_alive_worms(team_index, arena)
 
 
 
 
 
 
 
 
 
 
 
 
64
  }
65
 
66
  usercall_trampoline!(fn trampoline_count_alive_worms; impl_fn = count_alive_worms_impl;
67
  regs = [eax, ecx]);
68
 
69
+ // ── Passthrough hooks (log + call original) ──
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  static ORIG_STRIKE_FIRE: AtomicU32 = AtomicU32::new(0);
72
  static ORIG_PLACED_EXPLOSIVE: AtomicU32 = AtomicU32::new(0);
73
 
74
+ // ── CreateWeaponProjectile (0x51E0F0): thiscall(ECX=worm, fire_params, local_struct) ──
75
+
 
 
 
76
  #[unsafe(naked)]
77
  unsafe extern "C" fn trampoline_create_weapon_projectile() {
78
  core::arch::naked_asm!(
79
+ "push dword ptr [esp+8]",
80
+ "push dword ptr [esp+8]",
81
+ "push ecx",
 
 
82
  "call {impl_fn}",
83
  "add esp, 12",
84
+ "ret 0x8",
85
+ impl_fn = sym create_weapon_projectile_wrapper,
86
  );
87
  }
88
 
89
+ unsafe extern "cdecl" fn create_weapon_projectile_wrapper(
 
 
 
 
90
  worm: *mut CTaskWorm,
91
  fire_params: *const WeaponFireParams,
92
  local_struct: *const u8,
93
  ) {
94
+ weapon_fire::create_weapon_projectile(worm, fire_params, local_struct);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  }
96
 
97
+ // ── ProjectileFire (0x51DFB0): stdcall(worm, fire_params, local_struct) ──
98
+
 
 
 
99
  #[unsafe(naked)]
100
  unsafe extern "C" fn trampoline_projectile_fire() {
101
  core::arch::naked_asm!(
102
+ "push dword ptr [esp+12]",
103
+ "push dword ptr [esp+12]",
104
+ "push dword ptr [esp+12]",
 
105
  "call {impl_fn}",
106
  "add esp, 12",
107
+ "ret 0xC",
108
+ impl_fn = sym projectile_fire_wrapper,
109
  );
110
  }
111
 
112
+ unsafe extern "cdecl" fn projectile_fire_wrapper(
 
 
 
 
 
 
 
 
 
 
 
113
  worm: *mut CTaskWorm,
114
  fire_params: *const WeaponFireParams,
115
+ local_struct: *const u8,
116
  ) {
117
+ weapon_fire::projectile_fire(
118
+ worm,
119
+ fire_params,
120
+ local_struct as *const openwa_core::game::weapon::WeaponSpawnData,
121
+ );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  }
123
 
124
+ // ── CreateArrow (0x51ED90): thiscall(ECX=worm, fire_params, local_struct) ──
 
 
 
 
125
 
 
 
 
 
 
126
  #[unsafe(naked)]
127
  unsafe extern "C" fn trampoline_create_arrow() {
128
  core::arch::naked_asm!(
 
132
  "call {impl_fn}",
133
  "add esp, 12",
134
  "ret 0x8",
135
+ impl_fn = sym create_arrow_wrapper,
136
  );
137
  }
138
 
139
+ unsafe extern "cdecl" fn create_arrow_wrapper(
140
  worm: *mut CTaskWorm,
141
  fire_params: *const WeaponFireParams,
142
  local_struct: *const u8,
143
  ) {
144
+ weapon_fire::create_arrow(worm, fire_params, local_struct);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  }
146
 
147
+ // ── StrikeFire (0x51E2C0): passthrough (log + call original) ──
148
+
149
  #[unsafe(naked)]
150
  unsafe extern "C" fn trampoline_strike_fire() {
151
  core::arch::naked_asm!(
152
  "push eax",
153
  "push ecx",
154
  "push edx",
155
+ "push dword ptr [esp+24]",
156
+ "push dword ptr [esp+24]",
157
+ "push dword ptr [esp+24]",
158
  "call {log_fn}",
159
  "add esp, 12",
160
  "pop edx",
 
173
  ));
174
  }
175
 
176
+ // ── PlacedExplosive (0x51EC80): passthrough (log + call original) ──
177
+
178
  #[unsafe(naked)]
179
  unsafe extern "C" fn trampoline_placed_explosive() {
180
  core::arch::naked_asm!(
 
181
  "push eax",
182
  "push ecx",
183
  "push edx",
 
185
  "push esi",
186
  "push edi",
187
  "push ebp",
188
+ "push dword ptr [esp+32]",
189
+ "push edx",
190
+ "push ecx",
 
191
  "call {log_fn}",
192
  "add esp, 12",
 
193
  "pop ebp",
194
  "pop edi",
195
  "pop esi",
 
197
  "pop edx",
198
  "pop ecx",
199
  "pop eax",
 
200
  "jmp [{orig}]",
201
  log_fn = sym log_placed_explosive,
202
  orig = sym ORIG_PLACED_EXPLOSIVE,
 
210
  ));
211
  }
212
 
213
+ // ── Hook installation ──
 
 
214
 
215
  pub fn install() -> Result<(), String> {
216
  unsafe {
 
228
  )?;
229
  hook::install_trap!("FireWeapon", va::FIRE_WEAPON);
230
 
231
+ // Full replacements for fire sub-functions
232
+ let _ = hook::install(
233
  "CreateWeaponProjectile",
234
  va::CREATE_WEAPON_PROJECTILE,
235
  trampoline_create_weapon_projectile as *const (),
236
  )?;
237
+ let _ = hook::install(
 
238
  "ProjectileFire",
239
  va::PROJECTILE_FIRE,
240
  trampoline_projectile_fire as *const (),
241
  )?;
242
+ let _ = hook::install(
243
+ "CreateArrow",
244
+ va::CREATE_ARROW,
245
+ trampoline_create_arrow as *const (),
246
+ )?;
247
+
248
+ // Passthrough hooks (log + call original)
249
  let t = hook::install(
250
  "StrikeFire",
251
  va::STRIKE_FIRE,
 
258
  trampoline_placed_explosive as *const (),
259
  )?;
260
  ORIG_PLACED_EXPLOSIVE.store(t as u32, Ordering::Relaxed);
 
 
 
 
 
261
  }
262
 
263
  Ok(())
crates/openwa-wormkit/src/replacements/weapon_release.rs CHANGED
@@ -1,111 +1,20 @@
1
- //! WeaponRelease hook (0x51C3D0).
2
  //!
3
- //! Orchestrates weapon firing: ammo sync, spawn offset calculation, network timing,
4
- //! weapon stat counters, sound/visual effects, then delegates to FireWeapon (in weapon.rs).
5
- //!
6
- //! Convention: usercall(EAX=CTaskWorm*) + 4 stack params, RET 0x10.
7
 
8
  use openwa_core::address::va;
9
- use openwa_core::audio::{KnownSoundId, SoundId};
10
  use openwa_core::fixed::Fixed;
11
- use openwa_core::game::Weapon;
12
- use openwa_core::log::log_line;
13
- use openwa_core::task::turn_game::CTaskTurnGame;
14
- use openwa_core::task::worm::{CTaskWorm, WormState};
15
- use openwa_core::task::{CGameTask, CTask, SharedDataTable, Task};
16
 
17
  use crate::hook::{self, usercall_trampoline};
18
- use crate::replacements::{sound, weapon};
19
 
20
- // ── Trampoline ──────────────────────────────────────────────
21
 
22
  usercall_trampoline!(fn trampoline_weapon_release; impl_fn = weapon_release_impl;
23
  reg = eax; stack_params = 4; ret_bytes = "0x10");
24
 
25
- // ── WeaponReleaseContext ────────────────────────────────────
26
-
27
- /// The 0x2C-byte stack-local struct populated by WeaponRelease and passed to
28
- /// FireWeapon as the `local_struct` (ECX) parameter.
29
- #[repr(C)]
30
- #[derive(Clone, Copy)]
31
- pub(crate) struct WeaponReleaseContext {
32
- team_id: u32,
33
- worm_id: u32,
34
- spawn_x: u32,
35
- spawn_y: u32,
36
- spawn_offset_x: i32,
37
- spawn_offset_y: i32,
38
- ammo_per_turn: u32,
39
- ammo_per_slot: u32,
40
- _zero: u32,
41
- delay: u32,
42
- network_delay: i32,
43
- }
44
-
45
- const _: () = assert!(core::mem::size_of::<WeaponReleaseContext>() == 0x2C);
46
-
47
- // ── Weapon category classifiers (pure Rust) ─────────────────
48
-
49
- /// IsSuperWeapon (0x565960): returns true for "super weapon" IDs.
50
- /// For SelectWorm, returns the DDGame+0x7E3F version flag (mode-dependent).
51
- fn is_super_weapon(weapon: Weapon, ddgame_7e3f: u8) -> bool {
52
- use Weapon::*;
53
- matches!(
54
- weapon,
55
- Earthquake
56
- | SuicideBomber
57
- | MailStrike
58
- | MineStrike
59
- | MoleSquadron
60
- | GirderPack
61
- | ScalesOfJustice
62
- | SuperBanana
63
- | SalvationArmy
64
- | MbBomb
65
- | MingVase
66
- | SheepStrike
67
- | CarpetBomb
68
- | Donkey
69
- | NuclearTest
70
- | Armageddon
71
- | Freeze
72
- | MagicBullet
73
- ) || (weapon == Weapon::SelectWorm && ddgame_7e3f != 0)
74
- }
75
-
76
- /// FUN_005658C0: weapon category A — homing/animal/special projectile weapons.
77
- fn is_weapon_category_a(weapon: Weapon) -> bool {
78
- use Weapon::*;
79
- matches!(
80
- weapon,
81
- HomingPigeon
82
- | SheepLauncher
83
- | Sheep
84
- | SuperSheep
85
- | AquaSheep
86
- | MoleBomb
87
- | MoleSquadron
88
- | SalvationArmy
89
- | MbBomb
90
- | Skunk
91
- | SheepStrike
92
- | MadCow
93
- | OldWoman
94
- | Donkey
95
- )
96
- }
97
-
98
- /// FUN_00565920: weapon category B — fire/napalm weapons.
99
- fn is_weapon_category_b(weapon: Weapon) -> bool {
100
- use Weapon::*;
101
- matches!(
102
- weapon,
103
- NapalmStrike | FlameThrower | PetrolBomb | SheepStrike
104
- )
105
- }
106
-
107
- // ── Main implementation ─────────────────────────────────────
108
-
109
  unsafe extern "cdecl" fn weapon_release_impl(
110
  worm: *mut CTaskWorm,
111
  spawn_x: u32,
@@ -113,421 +22,20 @@ unsafe extern "cdecl" fn weapon_release_impl(
113
  aim_dir_x: Fixed,
114
  aim_dir_y: Fixed,
115
  ) {
116
- let w = &*worm;
117
-
118
- // Initialize context struct to zero
119
- let mut ctx = WeaponReleaseContext {
120
- team_id: 0,
121
- worm_id: 0,
122
- spawn_x: 0,
123
- spawn_y: 0,
124
- spawn_offset_x: 0,
125
- spawn_offset_y: 0,
126
- ammo_per_turn: 0,
127
- ammo_per_slot: 0,
128
- _zero: 0,
129
- delay: 0,
130
- network_delay: 0,
131
- };
132
-
133
- // ── 1. Sync check ───────────────────────────────────────
134
- if w.fire_sync_frame_1 == w.fire_sync_frame_2 {
135
- let g = &mut *w.ddgame();
136
- g.render_slot_count = 0x0E;
137
- for entry in &mut g.render_entries {
138
- entry.active = 0;
139
- }
140
- g.render_state_flag = 0;
141
- }
142
-
143
- // ── 2. Populate context fields ──────────────────────────
144
- let speed_x = w.base.pos_x;
145
- let speed_y = w.base.pos_y;
146
- ctx.team_id = w.team_index;
147
- ctx.worm_id = w.worm_index;
148
- ctx.ammo_per_turn = w.weapon_param_1 as u32;
149
- ctx.spawn_x = spawn_x;
150
- ctx.spawn_y = spawn_y;
151
- ctx.ammo_per_slot = w.weapon_param_2 as u32;
152
-
153
- let entry = w.active_weapon_entry;
154
- let fire_type = (*entry).fire_type;
155
- let special_subtype = (*entry).special_subtype;
156
- let fire_method = (*entry).fire_method;
157
-
158
- use openwa_core::game::weapon::{FireMethod, FireType};
159
-
160
- // ── 3. Spawn offset calculation ─────────────────────────
161
- let scale = w.landscape_scale;
162
-
163
- let (mut offset_x, mut offset_y) = (Fixed::ZERO, Fixed::ZERO);
164
- match FireType::try_from(fire_type) {
165
- Ok(FireType::Projectile) => match FireMethod::try_from(fire_method) {
166
- Ok(FireMethod::PlacedExplosive) => {
167
- offset_x = aim_dir_x * 24;
168
- offset_y = aim_dir_y * 24;
169
- }
170
- Ok(FireMethod::ProjectileFire) => {
171
- // Falls through to Strike (passthrough)
172
- offset_x = aim_dir_x;
173
- offset_y = aim_dir_y;
174
- }
175
- Ok(FireMethod::CreateWeaponProjectile) => {
176
- offset_x = aim_dir_x * scale * 24;
177
- offset_y = aim_dir_y * scale * 24;
178
- }
179
- Ok(FireMethod::CreateArrow) => {
180
- offset_x = aim_dir_x * 20;
181
- offset_y = aim_dir_y * 20;
182
- }
183
- _ => {}
184
- },
185
- Ok(FireType::Rope) => {
186
- offset_x = aim_dir_x * scale * 24;
187
- offset_y = aim_dir_y * scale * 24;
188
- // Special Y adjustment for state 0x79
189
- if w.is_in_state(WormState::Unknown_0x79) {
190
- offset_y += w.base.speed_y;
191
- }
192
- }
193
- Ok(FireType::Strike) => {
194
- offset_x = aim_dir_x;
195
- offset_y = aim_dir_y;
196
- }
197
- Ok(FireType::Special) => {
198
- if (special_subtype as u32).wrapping_sub(1) < 0x18 {
199
- offset_x = aim_dir_x;
200
- offset_y = aim_dir_y;
201
- }
202
- }
203
- _ => {}
204
- }
205
- ctx.spawn_offset_x = offset_x.0;
206
- ctx.spawn_offset_y = offset_y.0;
207
-
208
- // ── 4. Delay ────────────────────────────────────────────
209
- if w.difficulty_level == 0 {
210
- ctx.delay = 0x1E;
211
- } else if w.difficulty_level == 1 {
212
- ctx.delay = 0x3C;
213
- }
214
-
215
- // ── 5. Network timing ───────────────────────────────────
216
- let game_info = (*w.ddgame()).game_info as *const u8;
217
- let is_network = *game_info.add(0xD9D0);
218
- let fe_version = *game_info.add(0xD9B1);
219
-
220
- let mut adjust = 0i32;
221
- let max_clients = if is_network == 0 {
222
- 5
223
- } else if fe_version < 0x1B {
224
- 10
225
- } else {
226
- adjust = -1;
227
- 10
228
- };
229
-
230
- let client_idx = w.network_client_index;
231
- if ((client_idx - adjust) as u32) < ((max_clients - adjust) as u32) {
232
- ctx.network_delay = (client_idx + 1) * 1000;
233
- }
234
-
235
- // ── 6. Girder/GirderPack special ────────────────────────
236
- let weapon = w.selected_weapon;
237
- if matches!(weapon, Weapon::Girder | Weapon::GirderPack) && w.weapon_param_3 == 0 {
238
- (*worm).shot_data_1 = w.shot_data_2;
239
- }
240
-
241
- // ── 7. SharedData HandleMessage (msg 0x49) ──────────────
242
- let mut msg_buf = [0u8; 0x408];
243
- write_u32(&mut msg_buf, 0x00, w.team_index);
244
- write_u32(&mut msg_buf, 0x04, w.worm_index);
245
- write_u32(&mut msg_buf, 0x08, w.shot_data_1);
246
- write_u32(&mut msg_buf, 0x0C, w.shot_data_2);
247
- write_u32(&mut msg_buf, 0x10, w.fire_sync_frame_1 as u32);
248
- write_u32(&mut msg_buf, 0x14, w.fire_sync_frame_2 as u32);
249
- write_u32(&mut msg_buf, 0x18, if w._unknown_2cc != 0 { 1 } else { 0 });
250
- write_u32(&mut msg_buf, 0x1C, weapon as u32);
251
-
252
- let team = weapon::lookup_turn_game(worm);
253
- if !team.is_null() {
254
- CTaskTurnGame::handle_message_raw(
255
- team,
256
- worm as *mut openwa_core::task::CTask,
257
- 0x49,
258
- 0x408,
259
- msg_buf.as_ptr(),
260
- );
261
- }
262
-
263
- // ── 8. Weapon stat counters ─────────────────────────────
264
- let g = &mut *CTask::ddgame_raw(worm as *const CTask);
265
- let team_id = (*worm).team_index;
266
- let worm_id = (*worm).worm_index;
267
-
268
- if is_super_weapon(weapon, g.version_flag_3) {
269
- *g.weapon_stat_counter(team_id, worm_id, 0x40D8) += 1;
270
- }
271
-
272
- // Powerup/utility weapons (JetPack..=CrateShower)
273
- if (Weapon::JetPack..=Weapon::CrateShower).contains(&weapon) {
274
- *g.weapon_stat_counter(team_id, worm_id, 0x40D4) += 1;
275
- }
276
-
277
- if is_weapon_category_a(weapon) {
278
- *g.weapon_stat_counter(team_id, worm_id, 0x40D0) += 1;
279
- }
280
-
281
- if is_weapon_category_b(weapon) {
282
- *g.weapon_stat_counter(team_id, worm_id, 0x40CC) += 1;
283
- }
284
-
285
- // ── 9. Sound dispatch + 10. Visual effect ───────────────
286
- let task = worm as *mut CGameTask;
287
- let mut do_effect = false;
288
- let mut effect_state: u32 = 0x73;
289
-
290
- let w = &*worm; // re-borrow after mutation above
291
- let entry = w.active_weapon_entry;
292
-
293
- match FireType::try_from((*entry).fire_type) {
294
- Ok(FireType::Projectile) => match (*entry).special_subtype {
295
- 1 => {
296
- if w.sound_handle == 0 {
297
- sound::play_worm_sound(worm, SoundId(0x1004E), Fixed::ONE);
298
- }
299
- do_effect = true;
300
- effect_state = 0x73;
301
- }
302
- 2 => {
303
- sound::play_sound_local(
304
- task,
305
- KnownSoundId::ThrowRelease,
306
- 3,
307
- Fixed::ONE,
308
- Fixed::ONE,
309
- );
310
- sound::stop_worm_sound(worm);
311
- }
312
- 3 | 7 | 0xB | 0xC => {
313
- sound::play_sound_local(
314
- task,
315
- KnownSoundId::RocketRelease,
316
- 3,
317
- Fixed::ONE,
318
- Fixed::ONE,
319
- );
320
- sound::stop_worm_sound(worm);
321
- }
322
- 4 => {
323
- if w.sound_handle == 0 {
324
- sound::play_worm_sound(worm, SoundId(0x1004F), Fixed::ONE);
325
- }
326
- do_effect = true;
327
- effect_state = 0x73;
328
- }
329
- 5 => {
330
- sound::play_sound_local(task, KnownSoundId::ShotgunFire, 3, Fixed::ONE, Fixed::ONE);
331
- do_effect = true;
332
- effect_state = 0x75;
333
- }
334
- 6 => {
335
- sound::play_sound_local(task, KnownSoundId::HandgunFire, 3, Fixed::ONE, Fixed::ONE);
336
- do_effect = true;
337
- effect_state = 0x73;
338
- }
339
- 10 => {
340
- sound::play_sound_local(
341
- task,
342
- KnownSoundId::LongbowRelease,
343
- 3,
344
- Fixed::ONE,
345
- Fixed::ONE,
346
- );
347
- sound::stop_worm_sound(worm);
348
- }
349
- _ => {}
350
- },
351
- Ok(FireType::Rope) => {
352
- if w._unknown_2cc == 0 || w._unknown_2c8 == 1 {
353
- let team_sound_raw = (*w.ddgame()).team_sound_id(team_id);
354
- sound::play_sound_local(task, SoundId(team_sound_raw), 3, Fixed::ONE, Fixed::ONE);
355
- }
356
- }
357
- // Type 3 (Strike): no sound
358
- Ok(FireType::Special) => {
359
- use openwa_core::game::weapon::SpecialFireSubtype as S;
360
- match S::try_from((*entry).special_subtype) {
361
- Ok(S::BaseballBat) => {
362
- sound::play_sound_local(
363
- task,
364
- KnownSoundId::BaseballBatRelease,
365
- 3,
366
- Fixed::ONE,
367
- Fixed::ONE,
368
- );
369
- }
370
- Ok(S::DragonBall) => {
371
- sound::play_sound_local(
372
- task,
373
- SoundId((*entry).fire_method as u32),
374
- 3,
375
- Fixed::ONE,
376
- Fixed::ONE,
377
- );
378
- }
379
- Ok(S::Kamikaze) => {
380
- // Sound ID from fire_params.spread (polymorphic use of field)
381
- sound::play_sound_local(
382
- task,
383
- SoundId((*entry).fire_params.spread as u32),
384
- 3,
385
- Fixed::ONE,
386
- Fixed::ONE,
387
- );
388
- }
389
- Ok(S::Teleport) => {
390
- if w._unknown_208 == 0 {
391
- sound::play_sound_local(
392
- task,
393
- KnownSoundId::Teleport,
394
- 3,
395
- Fixed::ONE,
396
- Fixed::ONE,
397
- );
398
- }
399
- }
400
- Ok(S::Blowtorch) => {
401
- if w.sound_handle == 0 {
402
- sound::play_worm_sound(worm, SoundId(0x10035), Fixed::ONE);
403
- }
404
- }
405
- _ => {}
406
- }
407
- }
408
- _ => {}
409
- }
410
-
411
- // ── 10. Visual effect (if triggered by sound dispatch) ──
412
- if do_effect {
413
- let ddgame = &mut *CTask::ddgame_raw(worm as *const CTask);
414
- let gfx_handler = ddgame.game_state_stream as *const u8;
415
- let palette = *(gfx_handler.add(0x22C) as *const u32);
416
-
417
- let rng1 = ddgame.advance_effect_rng();
418
- let rng2 = ddgame.advance_effect_rng();
419
-
420
- let rng2_offset = (rng2 & 0xFFFF) as i32 - 0x18000;
421
- let facing = (*worm).facing_direction_2;
422
- let rng_scaled = rng2_offset * facing;
423
-
424
- let rng1_offset = (rng1 & 0xFFFF) as i32 - 0x18000;
425
-
426
- let facing_flag: u32 = if facing < 1 { 0x40000 } else { 0 };
427
- let state_flag = facing_flag + effect_state;
428
-
429
- spawn_effect(
430
- worm,
431
- 0x80000,
432
- speed_x,
433
- speed_y,
434
- rng_scaled,
435
- rng1_offset,
436
- palette,
437
- state_flag,
438
- Fixed(0xA0000),
439
- Fixed(0x1999),
440
- );
441
- }
442
-
443
- // ── 11. Call FireWeapon ──────────────────────────────────
444
- let entry = (*worm).active_weapon_entry;
445
- weapon::fire_weapon(entry, &ctx, worm);
446
-
447
- let _ = log_line(&format!(
448
- "[WeaponRelease] worm=0x{:08X} weapon={:?} type={} sub34={} sub38={}",
449
- worm as u32, weapon, fire_type, special_subtype, fire_method,
450
- ));
451
  }
452
 
453
- // ── Helper ──────────────────────────────────────────────────
454
 
455
- #[inline(always)]
456
- fn write_u32(buf: &mut [u8], offset: usize, value: u32) {
457
- buf[offset..offset + 4].copy_from_slice(&value.to_ne_bytes());
458
- }
459
-
460
- // ── SpawnEffect (0x547C30) — hooked, also called directly ───
461
-
462
- /// Spawn a visual effect on the sprite anim entity. Pure Rust port of FUN_00547C30.
463
- ///
464
- /// Builds a 0x408-byte message buffer from the params, looks up CTaskSpriteAnim
465
- /// via SharedData (entity type 0x1A), and sends HandleMessage(0x56).
466
- ///
467
- /// Called directly from `weapon_release_impl` and via the hook trampoline
468
- /// for all other WA callers (17 call sites).
469
- pub(crate) unsafe fn spawn_effect(
470
- worm: *mut CTaskWorm,
471
- constant: u32,
472
- speed_x: Fixed,
473
- speed_y: Fixed,
474
- rng_scaled: i32,
475
- rng_offset: i32,
476
- palette: u32,
477
- state_flag: u32,
478
- size: Fixed,
479
- scale: Fixed,
480
- ) {
481
- // Build the message buffer matching the original stack layout.
482
- // The original pushes ESI (worm ptr) then uses LEA to include it at offset 0.
483
- let mut buf = [0u8; 0x408];
484
- write_u32(&mut buf, 0x00, worm as u32);
485
- write_u32(&mut buf, 0x04, constant);
486
- write_u32(&mut buf, 0x08, speed_x.0 as u32);
487
- write_u32(&mut buf, 0x0C, speed_y.0 as u32);
488
- write_u32(&mut buf, 0x10, rng_scaled as u32);
489
- write_u32(&mut buf, 0x14, rng_offset as u32);
490
- // [0x18] = 0 (already zeroed)
491
- write_u32(&mut buf, 0x1C, palette);
492
- write_u32(&mut buf, 0x20, state_flag);
493
- // [0x24] = 0 (already zeroed)
494
- write_u32(&mut buf, 0x28, size.0 as u32);
495
- write_u32(&mut buf, 0x2C, scale.0 as u32);
496
-
497
- // SharedData lookup for entity type 0x1A (CTaskSpriteAnim)
498
- let table = SharedDataTable::from_task(worm as *const CTask);
499
- let entity = table.lookup(0, 0x1A);
500
- if !entity.is_null() {
501
- let vtable = *(entity as *const *const usize);
502
- let handle_msg: unsafe extern "thiscall" fn(*mut u8, *mut u8, u32, u32, *const u8) =
503
- core::mem::transmute(*vtable.add(2));
504
- handle_msg(
505
- entity as *mut u8,
506
- worm as *mut u8,
507
- 0x56,
508
- 0x408,
509
- buf.as_ptr(),
510
- );
511
- }
512
- }
513
-
514
- /// Naked trampoline for SpawnEffect (0x547C30).
515
- ///
516
- /// Original convention: usercall(EAX=constant, ECX=speed_x, ESI=worm)
517
- /// + 7 stack params (speed_y, rng_scaled, rng_offset, palette, state_flag, size, scale)
518
- /// RET 0x1C.
519
  #[unsafe(naked)]
520
  unsafe extern "C" fn trampoline_spawn_effect() {
521
  core::arch::naked_asm!(
522
- // Save callee-saved registers
523
  "push ebx",
524
  "push ebp",
525
  "push edi",
526
- // ESI = worm, EAX = constant, ECX = speed_x
527
- // Stack after 3 saves(12) + ret(4) = 16; original stack params start at +16
528
- // Push cdecl args in reverse: scale, size, state_flag, palette, rng_offset,
529
- // rng_scaled, speed_y, 0(rng_offset placeholder), speed_x(ECX), constant(EAX), worm(ESI)
530
- "push [esp+40]", // scale (16+24=40)
531
  "push [esp+40]", // size
532
  "push [esp+40]", // state_flag
533
  "push [esp+40]", // palette
@@ -543,11 +51,37 @@ unsafe extern "C" fn trampoline_spawn_effect() {
543
  "pop ebp",
544
  "pop ebx",
545
  "ret 0x1C", // clean 7 original stack params
546
- impl_fn = sym spawn_effect,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547
  );
548
  }
549
 
550
- // ── Hook installation ───────────────────────────────────────
551
 
552
  pub fn install() -> Result<(), String> {
553
  unsafe {
@@ -556,7 +90,6 @@ pub fn install() -> Result<(), String> {
556
  va::SPAWN_EFFECT,
557
  trampoline_spawn_effect as *const (),
558
  )?;
559
-
560
  hook::install(
561
  "WeaponRelease",
562
  va::WEAPON_RELEASE,
 
1
+ //! WeaponRelease hook (0x51C3D0) and SpawnEffect (0x547C30).
2
  //!
3
+ //! Thin wormkit shim — game logic lives in `openwa_core::game::weapon_release`.
4
+ //! This file contains usercall trampolines and hook installation.
 
 
5
 
6
  use openwa_core::address::va;
 
7
  use openwa_core::fixed::Fixed;
8
+ use openwa_core::game::weapon_release as wr;
9
+ use openwa_core::task::worm::CTaskWorm;
 
 
 
10
 
11
  use crate::hook::{self, usercall_trampoline};
 
12
 
13
+ // ── WeaponRelease (0x51C3D0): usercall(EAX=worm) + 4 stack, RET 0x10 ──
14
 
15
  usercall_trampoline!(fn trampoline_weapon_release; impl_fn = weapon_release_impl;
16
  reg = eax; stack_params = 4; ret_bytes = "0x10");
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  unsafe extern "cdecl" fn weapon_release_impl(
19
  worm: *mut CTaskWorm,
20
  spawn_x: u32,
 
22
  aim_dir_x: Fixed,
23
  aim_dir_y: Fixed,
24
  ) {
25
+ wr::weapon_release(worm, spawn_x, spawn_y, aim_dir_x, aim_dir_y);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  }
27
 
28
+ // ── SpawnEffect (0x547C30): usercall(EAX=const, ECX=speed_x, ESI=worm) + 7 stack ──
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  #[unsafe(naked)]
31
  unsafe extern "C" fn trampoline_spawn_effect() {
32
  core::arch::naked_asm!(
 
33
  "push ebx",
34
  "push ebp",
35
  "push edi",
36
+ // ESI=worm, EAX=constant, ECX=speed_x
37
+ // Stack: 3 saves(12) + ret(4) = 16; original stack params at +16
38
+ "push [esp+40]", // scale
 
 
39
  "push [esp+40]", // size
40
  "push [esp+40]", // state_flag
41
  "push [esp+40]", // palette
 
51
  "pop ebp",
52
  "pop ebx",
53
  "ret 0x1C", // clean 7 original stack params
54
+ impl_fn = sym spawn_effect_cdecl,
55
+ );
56
+ }
57
+
58
+ unsafe extern "cdecl" fn spawn_effect_cdecl(
59
+ worm: *mut CTaskWorm,
60
+ constant: u32,
61
+ speed_x: Fixed,
62
+ speed_y: Fixed,
63
+ rng_scaled: i32,
64
+ rng_offset: i32,
65
+ palette: u32,
66
+ state_flag: u32,
67
+ size: Fixed,
68
+ scale: Fixed,
69
+ ) {
70
+ wr::spawn_effect(
71
+ worm,
72
+ constant,
73
+ speed_x,
74
+ speed_y,
75
+ rng_scaled,
76
+ rng_offset,
77
+ palette,
78
+ state_flag,
79
+ size,
80
+ scale,
81
  );
82
  }
83
 
84
+ // ── Hook installation ──
85
 
86
  pub fn install() -> Result<(), String> {
87
  unsafe {
 
90
  va::SPAWN_EFFECT,
91
  trampoline_spawn_effect as *const (),
92
  )?;
 
93
  hook::install(
94
  "WeaponRelease",
95
  va::WEAPON_RELEASE,