rustraight 0.5.2

A simple 2D game library for Rust, inspired by DXLib
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
// gamepad.rs — ゲームパッド入力管理。XInput(Xbox系)と DirectInput(それ以外の
// USB コントローラー)の2バックエンドを束ね、pad_id 0-3 の仮想スロットとして公開する。

const MAX_XINPUT: usize = 4;
const MAX_DINPUT: usize = 4;
const BTN_COUNT:  usize = 16;
const AXIS_COUNT: usize = 6;
/// DirectInput デバイスの再列挙インターバル(フレーム数)
const DINPUT_REENUM_FRAMES: u32 = 300;

/// ゲームパッドのボタン(XInput/DirectInput 双方の物理配置を共通名で抽象化)。
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum PadButton {
    South, East, West, North,
    LBumper, RBumper,
    LTrigger, RTrigger,
    Select, Start,
    LThumb, RThumb,
    DPadUp, DPadDown, DPadLeft, DPadRight,
}

impl PadButton {
    fn index(self) -> usize { self as usize }
}

/// ゲームパッドのアナログ軸(スティック・トリガー)。値は -1.0〜1.0 に正規化される。
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum PadAxis {
    LeftStickX, LeftStickY,
    RightStickX, RightStickY,
    LeftTrigger, RightTrigger,
}

impl PadAxis {
    fn index(self) -> usize { self as usize }
}

// ── 内部ステート ────────────────────────────────────────────────────────────────

/// 1台分のゲームパッドの状態(ボタン押下・前フレームとの比較用スナップショット・軸の値)。
struct PadState {
    connected: bool,
    previous:  [bool; BTN_COUNT], // 前フレームのボタン状態(is_just_pressed 判定用)
    current:   [bool; BTN_COUNT],
    axes:      [f32;  AXIS_COUNT],
}

impl PadState {
    fn new() -> Self {
        Self { connected: false, previous: [false; BTN_COUNT], current: [false; BTN_COUNT], axes: [0.0; AXIS_COUNT] }
    }
    /// 現在の状態を「前フレーム」としてコピーする(毎フレーム末に呼ぶ)。
    fn commit(&mut self) { self.previous = self.current; }
}

// ── 仮想パッド参照 (内部用) ─────────────────────────────────────────────────────

/// virtual_pads[外部pad_id] がどのバックエンドのどのスロットを指すか。
#[derive(Copy, Clone)]
enum VPad {
    XInput(usize),
    #[cfg(target_os = "windows")]
    DInput(usize),
}

// ── DirectInput コンテキスト ────────────────────────────────────────────────────

/// DirectInput で認識した1台のデバイス。
#[cfg(target_os = "windows")]
struct DInputDev {
    guid:   windows::core::GUID, // 既知デバイスの重複検出に使う
    name:   String,
    device: windows::Win32::Devices::HumanInterfaceDevice::IDirectInputDevice8W,
    state:  PadState,
}

#[cfg(target_os = "windows")]
unsafe impl Send for DInputDev {}

/// DirectInput 全体を管理する(デバイス列挙・保持)。
#[cfg(target_os = "windows")]
struct DInputMgr {
    dinput:  windows::Win32::Devices::HumanInterfaceDevice::IDirectInput8W,
    hwnd:    isize,
    devices: Vec<DInputDev>,
    counter: u32, // reenum_dinput までのフレームカウンタ
}

#[cfg(target_os = "windows")]
unsafe impl Send for DInputMgr {}

// ── GamepadManager ──────────────────────────────────────────────────────────────

/// XInput / DirectInput 両バックエンドを統括し、pad_id 0-3 の仮想スロットとして公開する。
pub struct GamepadManager {
    xinput_states: [PadState; MAX_XINPUT],
    #[cfg(target_os = "windows")]
    dinput_mgr:    Option<DInputMgr>,
    /// pad_id 0-3 の割り当てテーブル。
    /// 全スロットが切断されるとリセットされ、次の接続から 0 番に詰め直される。
    slots: [Option<VPad>; 4],
}

impl GamepadManager {
    /// GamepadManager を初期化する。`hwnd` は DirectInput の協調レベル設定に使うウィンドウハンドル。
    pub fn try_new(hwnd: isize) -> Option<Self> {
        #[cfg(target_os = "windows")]
        let dinput_mgr = unsafe { init_dinput_mgr(hwnd) };

        Some(Self {
            xinput_states: std::array::from_fn(|_| PadState::new()),
            #[cfg(target_os = "windows")]
            dinput_mgr,
            slots: [None; 4],
        })
    }

    /// 毎フレーム末に呼び、全デバイスの「前フレーム」スナップショットを更新する。
    pub fn commit(&mut self) {
        for s in &mut self.xinput_states { s.commit(); }
        #[cfg(target_os = "windows")]
        if let Some(mgr) = &mut self.dinput_mgr {
            for dev in &mut mgr.devices { dev.state.commit(); }
        }
    }

    /// 毎フレーム呼び、全デバイスの状態をポーリングし、新規接続デバイスへスロットを割り当てる。
    pub fn poll(&mut self) {
        // ── XInput スロット 0-3 ────────────────────────────────────────────
        #[cfg(target_os = "windows")]
        for i in 0..MAX_XINPUT {
            let (conn, btns, axes) = poll_xinput(i as u32);
            let s = &mut self.xinput_states[i];
            s.connected = conn;
            s.current   = if conn { btns } else { [false; BTN_COUNT] };
            s.axes      = if conn { axes  } else { [0.0;  AXIS_COUNT] };
        }

        // ── DirectInput デバイス ───────────────────────────────────────────
        #[cfg(target_os = "windows")]
        if let Some(mgr) = &mut self.dinput_mgr {
            // 定期的に新デバイスを列挙
            mgr.counter += 1;
            if mgr.counter >= DINPUT_REENUM_FRAMES {
                mgr.counter = 0;
                unsafe { reenum_dinput(mgr); }
            }
            // 各デバイスをポール
            for dev in &mut mgr.devices {
                unsafe { poll_dinput_dev(dev); }
            }
        }

        // ── 新規接続デバイスに pad_id を割り当て(既存割り当ては変更しない)
        self.assign_new_pads();
    }

    /// 割り当て済みスロットが全て切断状態かを返す(未割り当て None は無視)。
    fn all_assigned_disconnected(&self) -> bool {
        let mut has_assigned = false;
        for slot in &self.slots {
            let connected = match slot {
                None => continue,
                Some(VPad::XInput(i)) => self.xinput_states[*i].connected,
                #[cfg(target_os = "windows")]
                Some(VPad::DInput(i)) => self.dinput_mgr.as_ref()
                    .map(|m| m.devices[*i].state.connected)
                    .unwrap_or(false),
            };
            has_assigned = true;
            if connected { return false; }
        }
        has_assigned // 1 台以上が割り当て済み かつ 全て切断
    }

    /// 未割り当ての接続済みデバイスを空きスロットに前詰めする。
    /// 割り当て済みスロットが全て切断になった場合はリセットして再割り当て。
    fn assign_new_pads(&mut self) {
        if self.all_assigned_disconnected() {
            self.slots = [None; 4];
        }

        // XInput (スロット番号順)
        'xi: for i in 0..MAX_XINPUT {
            if !self.xinput_states[i].connected { continue; }
            // 既に割り当て済みならスキップ
            if self.slots.iter().any(|s| matches!(s, Some(VPad::XInput(j)) if *j == i)) { continue; }
            // 空きスロットに割り当て
            for slot in &mut self.slots {
                if slot.is_none() { *slot = Some(VPad::XInput(i)); continue 'xi; }
            }
        }

        // DirectInput (デバイスインデックス順)
        #[cfg(target_os = "windows")]
        {
            let n = self.dinput_mgr.as_ref().map(|m| m.devices.len()).unwrap_or(0);
            'd: for i in 0..n {
                let conn = self.dinput_mgr.as_ref()
                    .map(|m| m.devices[i].state.connected)
                    .unwrap_or(false);
                if !conn { continue; }
                if self.slots.iter().any(|s| matches!(s, Some(VPad::DInput(j)) if *j == i)) { continue; }
                for slot in &mut self.slots {
                    if slot.is_none() { *slot = Some(VPad::DInput(i)); continue 'd; }
                }
            }
        }
    }

    /// pad_id が指す接続中デバイスの状態を取得する(未割り当て/切断中は None)。
    fn get_state(&self, pad_id: usize) -> Option<&PadState> {
        if pad_id >= 4 { return None; }
        let s = match self.slots[pad_id].as_ref()? {
            VPad::XInput(i) => &self.xinput_states[*i],
            #[cfg(target_os = "windows")]
            VPad::DInput(i) => &self.dinput_mgr.as_ref()?.devices[*i].state,
        };
        if s.connected { Some(s) } else { None }
    }

    /// 指定ボタンが現在押されているかどうかを返す。
    pub fn is_pressed(&self, pad_id: usize, btn: PadButton) -> bool {
        self.get_state(pad_id).map(|s| s.current[btn.index()]).unwrap_or(false)
    }

    /// 指定ボタンがこのフレームで押された瞬間かどうかを返す。
    pub fn is_just_pressed(&self, pad_id: usize, btn: PadButton) -> bool {
        self.get_state(pad_id)
            .map(|s| s.current[btn.index()] && !s.previous[btn.index()])
            .unwrap_or(false)
    }

    /// 指定ボタンがこのフレームで離された瞬間かどうかを返す。
    pub fn is_released(&self, pad_id: usize, btn: PadButton) -> bool {
        self.get_state(pad_id)
            .map(|s| !s.current[btn.index()] && s.previous[btn.index()])
            .unwrap_or(false)
    }

    /// 指定軸の値(-1.0〜1.0)を返す。
    pub fn axis(&self, pad_id: usize, axis: PadAxis) -> f32 {
        self.get_state(pad_id).map(|s| s.axes[axis.index()]).unwrap_or(0.0)
    }

    /// 指定 pad_id が現在接続中かどうかを返す。
    pub fn is_connected(&self, pad_id: usize) -> bool {
        if pad_id >= 4 { return false; }
        match self.slots[pad_id].as_ref() {
            None => false,
            Some(VPad::XInput(i)) => self.xinput_states[*i].connected,
            #[cfg(target_os = "windows")]
            Some(VPad::DInput(i)) => self.dinput_mgr.as_ref()
                .map(|m| m.devices[*i].state.connected)
                .unwrap_or(false),
        }
    }

    /// 現在接続中のコントローラー数(スロット 0-3 の中で接続中のもの)。
    pub fn count(&self) -> usize {
        (0..4).filter(|&id| self.is_connected(id)).count()
    }
}

// ── グローバル状態 ────────────────────────────────────────────────────────────
// input.rs / time.rs と同じ「独立 thread_local + 公開関数」パターンに合わせる。
// DirectInput の協調レベル設定にメインウィンドウの hwnd が必要なため、
// input.rs と異なり明示的な init(hwnd) 呼び出しが必要。

thread_local! {
    static GAMEPAD: std::cell::RefCell<Option<GamepadManager>> = std::cell::RefCell::new(None);
}

/// window::init() から呼ばれ、GamepadManager を初期化してグローバル状態にセットする。
pub(crate) fn init(hwnd: isize) {
    GAMEPAD.with(|g| *g.borrow_mut() = GamepadManager::try_new(hwnd));
}

/// 毎フレーム末に呼び、「前フレーム」のスナップショットを更新する。
pub(crate) fn commit() {
    GAMEPAD.with(|g| if let Some(gm) = g.borrow_mut().as_mut() { gm.commit(); });
}

/// 毎フレーム呼び、全デバイスをポーリングする。
pub(crate) fn poll() {
    GAMEPAD.with(|g| if let Some(gm) = g.borrow_mut().as_mut() { gm.poll(); });
}

/// 指定ボタンが現在押されているかどうかを返す。
pub fn is_pad_pressed(pad_id: usize, btn: PadButton) -> bool {
    GAMEPAD.with(|g| g.borrow().as_ref().map(|gm| gm.is_pressed(pad_id, btn)).unwrap_or(false))
}

/// 指定ボタンがこのフレームで押された瞬間かどうかを返す。
pub fn is_pad_just_pressed(pad_id: usize, btn: PadButton) -> bool {
    GAMEPAD.with(|g| g.borrow().as_ref().map(|gm| gm.is_just_pressed(pad_id, btn)).unwrap_or(false))
}

/// 指定ボタンがこのフレームで離された瞬間かどうかを返す。
pub fn is_pad_released(pad_id: usize, btn: PadButton) -> bool {
    GAMEPAD.with(|g| g.borrow().as_ref().map(|gm| gm.is_released(pad_id, btn)).unwrap_or(false))
}

/// 指定軸の値(-1.0〜1.0)を返す。
pub fn pad_axis(pad_id: usize, axis: PadAxis) -> f32 {
    GAMEPAD.with(|g| g.borrow().as_ref().map(|gm| gm.axis(pad_id, axis)).unwrap_or(0.0))
}

/// 指定 pad_id が現在接続中かどうかを返す。
pub fn is_pad_connected(pad_id: usize) -> bool {
    GAMEPAD.with(|g| g.borrow().as_ref().map(|gm| gm.is_connected(pad_id)).unwrap_or(false))
}

/// 現在接続中のコントローラー数を返す。
pub fn pad_count() -> usize {
    GAMEPAD.with(|g| g.borrow().as_ref().map(|gm| gm.count()).unwrap_or(0))
}

// ── XInput ポール ───────────────────────────────────────────────────────────────

/// XInput スロット `index`(0-3)をポーリングし、(接続中か, ボタン状態, 軸の値) を返す。
#[cfg(target_os = "windows")]
fn poll_xinput(index: u32) -> (bool, [bool; BTN_COUNT], [f32; AXIS_COUNT]) {
    use windows_sys::Win32::UI::Input::XboxController::*;
    unsafe {
        let mut state = std::mem::zeroed::<XINPUT_STATE>();
        if XInputGetState(index, &mut state) != 0 {
            return (false, [false; BTN_COUNT], [0.0; AXIS_COUNT]);
        }
        let g = state.Gamepad;
        let w = g.wButtons;
        let mut btns = [false; BTN_COUNT];
        btns[PadButton::South     as usize] = w & XINPUT_GAMEPAD_A              != 0;
        btns[PadButton::East      as usize] = w & XINPUT_GAMEPAD_B              != 0;
        btns[PadButton::West      as usize] = w & XINPUT_GAMEPAD_X              != 0;
        btns[PadButton::North     as usize] = w & XINPUT_GAMEPAD_Y              != 0;
        btns[PadButton::LBumper   as usize] = w & XINPUT_GAMEPAD_LEFT_SHOULDER  != 0;
        btns[PadButton::RBumper   as usize] = w & XINPUT_GAMEPAD_RIGHT_SHOULDER != 0;
        btns[PadButton::LTrigger  as usize] = g.bLeftTrigger  > 30;
        btns[PadButton::RTrigger  as usize] = g.bRightTrigger > 30;
        btns[PadButton::Select    as usize] = w & XINPUT_GAMEPAD_BACK           != 0;
        btns[PadButton::Start     as usize] = w & XINPUT_GAMEPAD_START          != 0;
        btns[PadButton::LThumb    as usize] = w & XINPUT_GAMEPAD_LEFT_THUMB     != 0;
        btns[PadButton::RThumb    as usize] = w & XINPUT_GAMEPAD_RIGHT_THUMB    != 0;
        btns[PadButton::DPadUp    as usize] = w & XINPUT_GAMEPAD_DPAD_UP        != 0;
        btns[PadButton::DPadDown  as usize] = w & XINPUT_GAMEPAD_DPAD_DOWN      != 0;
        btns[PadButton::DPadLeft  as usize] = w & XINPUT_GAMEPAD_DPAD_LEFT      != 0;
        btns[PadButton::DPadRight as usize] = w & XINPUT_GAMEPAD_DPAD_RIGHT     != 0;
        let mut axes = [0.0f32; AXIS_COUNT];
        axes[PadAxis::LeftStickX   as usize] = g.sThumbLX     as f32 / 32767.0;
        axes[PadAxis::LeftStickY   as usize] = g.sThumbLY     as f32 / 32767.0;
        axes[PadAxis::RightStickX  as usize] = g.sThumbRX     as f32 / 32767.0;
        axes[PadAxis::RightStickY  as usize] = g.sThumbRY     as f32 / 32767.0;
        axes[PadAxis::LeftTrigger  as usize] = g.bLeftTrigger  as f32 / 255.0;
        axes[PadAxis::RightTrigger as usize] = g.bRightTrigger as f32 / 255.0;
        (true, btns, axes)
    }
}

// ── DirectInput 定数・型 ────────────────────────────────────────────────────────

#[cfg(target_os = "windows")]
const DIDFT_AXIS_OPT: u32   = 0x80FFFF03;
#[cfg(target_os = "windows")]
const DIDFT_POV_OPT: u32    = 0x80FFFF10;
#[cfg(target_os = "windows")]
const DIDFT_BUTTON_OPT: u32 = 0x80FFFF0C;
#[cfg(target_os = "windows")]
const DIPROP_RANGE_PTR: *const windows::core::GUID = 4 as *const windows::core::GUID;

/// DirectInput から読み取るジョイスティック状態 (DIJOYSTATE 相当、80 バイト)。
#[repr(C)]
#[cfg(target_os = "windows")]
#[allow(non_snake_case)]
struct JoyState {
    lX:         i32,
    lY:         i32,
    lZ:         i32,
    lRx:        i32,
    lRy:        i32,
    lRz:        i32,
    rglSlider:  [i32; 2],
    rgdwPOV:    [u32; 4],
    rgbButtons: [u8; 32],
}

// ── DirectInput データフォーマット構築 ─────────────────────────────────────────

/// DirectInput のデータフォーマット定義(6軸 + 4 POVハット + 32ボタン = JoyState と対応)を構築する。
#[cfg(target_os = "windows")]
fn build_joystick_odfs() -> Vec<windows::Win32::Devices::HumanInterfaceDevice::DIOBJECTDATAFORMAT> {
    use windows::Win32::Devices::HumanInterfaceDevice::DIOBJECTDATAFORMAT;
    let null = core::ptr::null::<windows::core::GUID>();
    let mut v = Vec::with_capacity(44);
    for off in [0u32, 4, 8, 12, 16, 20] {
        v.push(DIOBJECTDATAFORMAT { pguid: null, dwOfs: off, dwType: DIDFT_AXIS_OPT, dwFlags: 0 });
    }
    for off in [24u32, 28] {
        v.push(DIOBJECTDATAFORMAT { pguid: null, dwOfs: off, dwType: DIDFT_AXIS_OPT, dwFlags: 0 });
    }
    for off in [32u32, 36, 40, 44] {
        v.push(DIOBJECTDATAFORMAT { pguid: null, dwOfs: off, dwType: DIDFT_POV_OPT, dwFlags: 0 });
    }
    for i in 0u32..32 {
        v.push(DIOBJECTDATAFORMAT { pguid: null, dwOfs: 48 + i, dwType: DIDFT_BUTTON_OPT, dwFlags: 0 });
    }
    v
}

// ── DirectInput 初期化 ──────────────────────────────────────────────────────────

/// DirectInput8 オブジェクトを作成し、接続中デバイスを列挙して DInputMgr を構築する。
#[cfg(target_os = "windows")]
unsafe fn init_dinput_mgr(hwnd: isize) -> Option<DInputMgr> {
    use windows::{core::Interface, Win32::Devices::HumanInterfaceDevice::*, Win32::Foundation::*};

    let hinstance = unsafe {
        windows_sys::Win32::System::LibraryLoader::GetModuleHandleW(std::ptr::null())
    };
    let mut punk = std::ptr::null_mut::<core::ffi::c_void>();
    let hr = unsafe {
        DirectInput8Create(
            HINSTANCE(hinstance as *mut _),
            0x0800,
            &IDirectInput8W::IID,
            &mut punk,
            None,
        )
    };
    if hr.is_err() || punk.is_null() {
        crate::log_error!("DirectInput8Create に失敗しました: {hr:?}");
        return None;
    }
    let dinput: IDirectInput8W = unsafe { std::mem::transmute(punk) };
    let mut mgr = DInputMgr { dinput, hwnd, devices: Vec::new(), counter: 0 };
    unsafe { reenum_dinput(&mut mgr); }
    Some(mgr)
}

/// EnumDevices に渡すコールバック。見つかったデバイスを `pv` が指す Vec に積む。
#[cfg(target_os = "windows")]
unsafe extern "system" fn enum_devices_cb(
    inst: *mut windows::Win32::Devices::HumanInterfaceDevice::DIDEVICEINSTANCEW,
    pv:   *mut core::ffi::c_void,
) -> windows::Win32::Foundation::BOOL {
    unsafe {
        let vec = &mut *(pv as *mut Vec<windows::Win32::Devices::HumanInterfaceDevice::DIDEVICEINSTANCEW>);
        vec.push(*inst);
    }
    windows::Win32::Foundation::BOOL(1)
}

/// 新しく接続されたデバイスを mgr.devices に追加する。既知の GUID はスキップ。
#[cfg(target_os = "windows")]
unsafe fn reenum_dinput(mgr: &mut DInputMgr) {
    use windows::Win32::Devices::HumanInterfaceDevice::*;
    use windows::Win32::Foundation::HWND;

    let mut instances: Vec<DIDEVICEINSTANCEW> = Vec::new();
    let _ = unsafe {
        mgr.dinput.EnumDevices(
            4, // DI8DEVCLASS_GAMECTRL
            Some(enum_devices_cb),
            &mut instances as *mut Vec<DIDEVICEINSTANCEW> as *mut _,
            1, // DIEDFL_ATTACHEDONLY
        )
    };

    for inst in &instances {
        if mgr.devices.iter().any(|d| d.guid == inst.guidInstance) {
            continue;
        }
        if mgr.devices.len() >= MAX_DINPUT { break; }
        let hwnd_w = HWND(mgr.hwnd as *mut _);
        match unsafe { create_dinput_dev(&mgr.dinput, inst, hwnd_w) } {
            Ok(dev) => {
                crate::log_info!("ゲームパッドを認識しました: {}", dev.name);
                mgr.devices.push(dev);
            }
            Err(e) => crate::log_warn!("ゲームパッドデバイスの作成に失敗しました: {e:?}"),
        }
    }
}

/// 列挙されたデバイスインスタンスから IDirectInputDevice8W を作成し、データフォーマット・
/// 協調レベル・軸レンジを設定して Acquire するところまで行う。
#[cfg(target_os = "windows")]
unsafe fn create_dinput_dev(
    dinput: &windows::Win32::Devices::HumanInterfaceDevice::IDirectInput8W,
    inst:   &windows::Win32::Devices::HumanInterfaceDevice::DIDEVICEINSTANCEW,
    hwnd:   windows::Win32::Foundation::HWND,
) -> windows::core::Result<DInputDev> {
    use windows::Win32::Devices::HumanInterfaceDevice::*;

    let mut opt: Option<IDirectInputDevice8W> = None;
    unsafe {
        dinput.CreateDevice(&inst.guidInstance, &mut opt, None::<&windows::core::IUnknown>)?;
    }
    let device = opt.ok_or_else(|| windows::core::Error::from_win32())?;

    let odfs = build_joystick_odfs();
    let mut fmt = DIDATAFORMAT {
        dwSize:    std::mem::size_of::<DIDATAFORMAT>() as u32,
        dwObjSize: std::mem::size_of::<DIOBJECTDATAFORMAT>() as u32,
        dwFlags:   1, // DIDF_ABSAXIS
        dwDataSize: std::mem::size_of::<JoyState>() as u32,
        dwNumObjs: odfs.len() as u32,
        rgodf:     odfs.as_ptr() as *mut _,
    };
    unsafe {
        device.SetDataFormat(&mut fmt as *mut _)?;
        device.SetCooperativeLevel(hwnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)?;
        let mut range = DIPROPRANGE {
            diph: DIPROPHEADER {
                dwSize:       std::mem::size_of::<DIPROPRANGE>() as u32,
                dwHeaderSize: std::mem::size_of::<DIPROPHEADER>() as u32,
                dwObj: 0,
                dwHow: 0, // DIPH_DEVICE
            },
            lMin: -32767,
            lMax:  32767,
        };
        let _ = device.SetProperty(DIPROP_RANGE_PTR, &mut range.diph as *mut _);
        device.Acquire()?;
    }

    let name = String::from_utf16_lossy(
        inst.tszInstanceName.split(|&c| c == 0).next().unwrap_or(&[])
    );
    Ok(DInputDev { guid: inst.guidInstance, name, device, state: PadState::new() })
}

// ── DirectInput ポール ──────────────────────────────────────────────────────────

/// DirectInput デバイス1台をポーリングし、状態を PadState に反映する。
/// 取得に失敗した場合は切断とみなし、再アクワイアを試みる。
#[cfg(target_os = "windows")]
unsafe fn poll_dinput_dev(dev: &mut DInputDev) {
    unsafe {
        let _ = dev.device.Poll();
        let mut js: JoyState = std::mem::zeroed();
        let result = dev.device.GetDeviceState(
            std::mem::size_of::<JoyState>() as u32,
            &mut js as *mut _ as *mut _,
        );
        match result {
            Ok(_) => {
                dev.state.connected = true;
                apply_joystate(&mut dev.state, &js);
            }
            Err(_) => {
                // 切断時は再アクワイアを試みる (再接続後に自動復帰)
                let _ = dev.device.Acquire();
                dev.state.connected = false;
                dev.state.current   = [false; BTN_COUNT];
                dev.state.axes      = [0.0;  AXIS_COUNT];
            }
        }
    }
}

/// DirectInput から取得した生の JoyState を PadButton/PadAxis の共通表現に変換する。
#[cfg(target_os = "windows")]
fn apply_joystate(state: &mut PadState, js: &JoyState) {
    let b = &js.rgbButtons;
    state.current[PadButton::South    as usize] = b[0]  & 0x80 != 0;
    state.current[PadButton::East     as usize] = b[1]  & 0x80 != 0;
    state.current[PadButton::West     as usize] = b[2]  & 0x80 != 0;
    state.current[PadButton::North    as usize] = b[3]  & 0x80 != 0;
    state.current[PadButton::LBumper  as usize] = b[4]  & 0x80 != 0;
    state.current[PadButton::RBumper  as usize] = b[5]  & 0x80 != 0;
    state.current[PadButton::LTrigger as usize] = b[6]  & 0x80 != 0;
    state.current[PadButton::RTrigger as usize] = b[7]  & 0x80 != 0;
    state.current[PadButton::Select   as usize] = b[8]  & 0x80 != 0;
    state.current[PadButton::Start    as usize] = b[9]  & 0x80 != 0;
    state.current[PadButton::LThumb   as usize] = b[10] & 0x80 != 0;
    state.current[PadButton::RThumb   as usize] = b[11] & 0x80 != 0;

    // POV ハット → D-pad (1/100 度単位)
    let pov = js.rgdwPOV[0];
    let valid = pov != 0xFFFF_FFFF;
    state.current[PadButton::DPadUp    as usize] = valid && (pov <= 4500 || pov >= 31500);
    state.current[PadButton::DPadRight as usize] = valid && (4500..=13500).contains(&pov);
    state.current[PadButton::DPadDown  as usize] = valid && (13500..=22500).contains(&pov);
    state.current[PadButton::DPadLeft  as usize] = valid && (22500..=31500).contains(&pov);

    let norm = |v: i32| (v as f32 / 32767.0).clamp(-1.0, 1.0);
    state.axes[PadAxis::LeftStickX   as usize] = norm(js.lX);
    state.axes[PadAxis::LeftStickY   as usize] = norm(js.lY);
    state.axes[PadAxis::RightStickX  as usize] = norm(js.lRx);
    state.axes[PadAxis::RightStickY  as usize] = norm(js.lRy);
    state.axes[PadAxis::LeftTrigger  as usize] = norm(js.lZ);
    state.axes[PadAxis::RightTrigger as usize] = norm(js.lRz);
}