rust_pixel 2.4.0

2d pixel-art game engine & rapid prototype tools support terminal, wgpu and web...
Documentation
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
// RustPixel
// copyright zipxing@hotmail.com 2022~2026

//! # Winit + WGPU Adapter Implementation
//!
//! Modern cross-platform rendering adapter based on winit + wgpu technology stack.
//!
//! ## Technology Stack
//! - **winit**: Cross-platform window management and event handling
//! - **wgpu**: Modern GPU API abstraction layer (based on Vulkan, Metal, D3D12, WebGPU)
//!
//! ## Features
//! - Cross-platform window management (Windows, macOS, Linux)
//! - High DPI/Retina display support
//! - Custom mouse cursor
//! - Window drag functionality
//! - Keyboard and mouse event handling
//! - Modern GPU hardware-accelerated rendering
//! - Command buffer and asynchronous rendering

use crate::event::Event;
use crate::render::{
    adapter::{
        wgpu::{WgpuRenderCore, WgpuRenderCoreBuilder},
        winit_common::{
            apply_cursor_to_window, check_border_area, input_events_from_winit,
            load_custom_cursor, winit_init_common, winit_move_win, BorderArea, Drag,
            WindowInitParams,
        },
        Adapter, AdapterBase, RtComposite,
    },
    buffer::Buffer,
    graph::{UnifiedTransform, is_letterboxing_enabled, set_letterboxing_override},
    sprite::Layer,
};

use log::info;
use std::any::Any;
use std::sync::Arc;
use std::time::Duration;
use winit::platform::pump_events::{EventLoopExtPumpEvents, PumpStatus};
pub use winit::{
    application::ApplicationHandler,
    dpi::LogicalSize,
    event::{Event as WinitEvent, WindowEvent},
    event_loop::{ControlFlow, EventLoop},
    window::{Cursor, CustomCursor, Fullscreen, Window},
};

/// Winit + WGPU adapter main structure
///
/// Encapsulates all components of winit window management and the WGPU modern rendering backend.
pub struct WinitWgpuAdapter {
    /// Base adapter data
    pub base: AdapterBase,

    // Winit related objects
    /// Window instance
    pub window: Option<Arc<Window>>,
    /// Event loop
    pub event_loop: Option<EventLoop<()>>,
    /// Window initialization parameters (for creating window in resumed)
    pub window_init_params: Option<WindowInitParams>,

    // WGPU backend objects
    /// WGPU instance for creating devices and surfaces
    pub wgpu_instance: Option<wgpu::Instance>,
    /// Window surface for rendering
    pub wgpu_surface: Option<wgpu::Surface<'static>>,
    /// Surface configuration
    pub wgpu_surface_config: Option<wgpu::SurfaceConfiguration>,
    /// Shared render core (contains device, queue, pixel_renderer)
    pub render_core: Option<WgpuRenderCore>,

    /// Whether the program should exit
    pub should_exit: bool,

    /// Event handler (for pump_events mode)
    pub app_handler: Option<WinitWgpuAppHandler>,

    /// Custom mouse cursor
    pub custom_cursor: Option<CustomCursor>,

    /// Whether cursor has been set (delayed set flag)
    pub cursor_set: bool,

    /// Window drag data
    drag: Drag,

    /// Original ratio values (saved before maximize override)
    original_ratio_x: f32,
    original_ratio_y: f32,
    /// Whether ratio was overridden by maximize
    ratio_overridden: bool,

    /// Original logical pixel size (before fullscreen override)
    /// Used for letterboxing aspect ratio calculation
    logical_content_w: f32,
    logical_content_h: f32,
}

/// Winit + WGPU application event handler
///
/// Implements the winit ApplicationHandler trait, handling window events and user input.
pub struct WinitWgpuAppHandler {
    /// Pending pixel event queue
    pub pending_events: Vec<Event>,
    /// Current mouse position
    pub cursor_position: (f64, f64),
    /// X-axis scaling coefficient
    pub ratio_x: f32,
    /// Y-axis scaling coefficient
    pub ratio_y: f32,
    /// Whether to use TUI character height (32px) for mouse coordinate calculation
    pub use_tui_height: bool,
    /// Whether to exit
    pub should_exit: bool,

    /// Adapter reference (for drag handling)
    pub adapter_ref: *mut WinitWgpuAdapter,
}

impl ApplicationHandler for WinitWgpuAppHandler {
    fn resumed(&mut self, event_loop: &winit::event_loop::ActiveEventLoop) {
        if let Some(adapter) = unsafe { self.adapter_ref.as_mut() } {
            if adapter.window.is_none() {
                adapter.create_wgpu_window_and_resources(event_loop);
            }

            if !adapter.cursor_set {
                adapter.clear_screen_wgpu();
                adapter.set_mouse_cursor();
                adapter.cursor_set = true;
            }
        }
    }

    fn window_event(
        &mut self,
        event_loop: &winit::event_loop::ActiveEventLoop,
        _window_id: winit::window::WindowId,
        event: WindowEvent,
    ) {
        match event {
            WindowEvent::CloseRequested => {
                self.should_exit = true;
                event_loop.exit();
            }
            WindowEvent::KeyboardInput {
                event: key_event, ..
            } => {
                if key_event.state == winit::event::ElementState::Pressed {
                    if let winit::keyboard::PhysicalKey::Code(keycode) = key_event.physical_key {
                        if keycode == winit::keyboard::KeyCode::KeyQ {
                            self.should_exit = true;
                            event_loop.exit();
                            return;
                        }
                    }
                }

                let winit_event = WinitEvent::WindowEvent {
                    window_id: _window_id,
                    event: WindowEvent::KeyboardInput {
                        device_id: winit::event::DeviceId::dummy(),
                        event: key_event,
                        is_synthetic: false,
                    },
                };
                if let Some(pixel_event) = input_events_from_winit(
                    &winit_event,
                    self.ratio_x,
                    self.ratio_y,
                    self.use_tui_height,
                    &mut self.cursor_position,
                ) {
                    self.pending_events.push(pixel_event);
                }
            }
            WindowEvent::Resized(new_size) => {
                if new_size.width > 0 && new_size.height > 0 {
                    unsafe {
                        let adapter = &mut *self.adapter_ref;

                        let is_max = adapter.window.as_ref()
                            .map(|w| w.is_maximized()).unwrap_or(false);
                        let is_fullscreen = adapter.window.as_ref()
                            .and_then(|w| w.fullscreen()).is_some();

                        // Reconfigure surface to match new window size
                        if let (Some(surface), Some(config), Some(core)) = (
                            &adapter.wgpu_surface,
                            adapter.wgpu_surface_config.as_mut(),
                            &adapter.render_core,
                        ) {
                            config.width = new_size.width;
                            config.height = new_size.height;
                            surface.configure(&core.device, config);
                        }

                        // On maximize/fullscreen: force ratio=1.0, enable letterboxing,
                        // and rebuild render core for crisp rendering
                        // On restore: restore original ratio and disable letterboxing
                        let should_override = (is_max || is_fullscreen)
                            && !adapter.ratio_overridden
                            && adapter.base.gr.ratio_x > 1.0;

                        if should_override {
                            adapter.original_ratio_x = adapter.base.gr.ratio_x;
                            adapter.original_ratio_y = adapter.base.gr.ratio_y;
                            adapter.base.gr.ratio_x = 1.0;
                            adapter.base.gr.ratio_y = 1.0;
                            adapter.base.gr.set_pixel_size(
                                adapter.base.cell_w, adapter.base.cell_h,
                            );
                            set_letterboxing_override(true);
                            adapter.rebuild_render_core();
                            adapter.ratio_overridden = true;
                        } else if !is_max && !is_fullscreen && adapter.ratio_overridden {
                            adapter.base.gr.ratio_x = adapter.original_ratio_x;
                            adapter.base.gr.ratio_y = adapter.original_ratio_y;
                            adapter.base.gr.set_pixel_size(
                                adapter.base.cell_w, adapter.base.cell_h,
                            );
                            set_letterboxing_override(false);
                            adapter.rebuild_render_core();
                            adapter.ratio_overridden = false;
                        }
                    }
                }
            }
            WindowEvent::CursorMoved { position, .. } => {
                unsafe {
                    let adapter = &*self.adapter_ref;
                    if let Some(window) = &adapter.window {
                        let actual_size = window.inner_size();
                        let expected_w = adapter.base.gr.pixel_w as f64;
                        let expected_h = adapter.base.gr.pixel_h as f64;
                        let phys_w = actual_size.width as f64;
                        let phys_h = actual_size.height as f64;

                        if is_letterboxing_enabled() {
                            // Content is centered with black borders; adjust cursor mapping
                            let content_aspect = expected_w / expected_h;
                            let window_aspect = phys_w / phys_h;

                            if window_aspect > content_aspect {
                                // Black bars on left/right
                                let content_phys_w = phys_h * content_aspect;
                                let offset_x = (phys_w - content_phys_w) / 2.0;
                                self.cursor_position = (
                                    (position.x - offset_x) / content_phys_w * expected_w,
                                    position.y / phys_h * expected_h,
                                );
                            } else {
                                // Black bars on top/bottom
                                let content_phys_h = phys_w / content_aspect;
                                let offset_y = (phys_h - content_phys_h) / 2.0;
                                self.cursor_position = (
                                    position.x / phys_w * expected_w,
                                    (position.y - offset_y) / content_phys_h * expected_h,
                                );
                            }
                        } else {
                            // No letterboxing: content stretches to fill window
                            self.cursor_position = (
                                position.x / phys_w * expected_w,
                                position.y / phys_h * expected_h,
                            );
                        }
                    } else {
                        self.cursor_position = (position.x, position.y);
                    }
                }

                unsafe {
                    let adapter = &mut *self.adapter_ref;
                    if adapter.drag.draging {
                        adapter.drag.need = true;
                        adapter.drag.dx = position.x - adapter.drag.mouse_x;
                        adapter.drag.dy = position.y - adapter.drag.mouse_y;
                    }
                }

                let logical_position = winit::dpi::PhysicalPosition::new(
                    self.cursor_position.0,
                    self.cursor_position.1,
                );
                let winit_event = WinitEvent::WindowEvent {
                    window_id: _window_id,
                    event: WindowEvent::CursorMoved {
                        device_id: winit::event::DeviceId::dummy(),
                        position: logical_position,
                    },
                };

                unsafe {
                    let adapter = &*self.adapter_ref;
                    if !adapter.drag.draging {
                        if let Some(pixel_event) = input_events_from_winit(
                            &winit_event,
                            self.ratio_x,
                            self.ratio_y,
                            self.use_tui_height,
                            &mut self.cursor_position,
                        ) {
                            self.pending_events.push(pixel_event);
                        }
                    }
                }
            }
            WindowEvent::MouseInput { state, button, .. } => {
                match (state, button) {
                    (winit::event::ElementState::Pressed, winit::event::MouseButton::Left) |
                    (winit::event::ElementState::Released, winit::event::MouseButton::Left) => {
                        let winit_event = WinitEvent::WindowEvent {
                            window_id: _window_id,
                            event: WindowEvent::MouseInput {
                                device_id: winit::event::DeviceId::dummy(),
                                state,
                                button,
                            },
                        };
                        if let Some(pixel_event) = input_events_from_winit(
                            &winit_event,
                            self.ratio_x,
                            self.ratio_y,
                            self.use_tui_height,
                            &mut self.cursor_position,
                        ) {
                            self.pending_events.push(pixel_event);
                        }
                    }
                    _ => {
                        let winit_event = WinitEvent::WindowEvent {
                            window_id: _window_id,
                            event: WindowEvent::MouseInput {
                                device_id: winit::event::DeviceId::dummy(),
                                state,
                                button,
                            },
                        };
                        if let Some(pixel_event) = input_events_from_winit(
                            &winit_event,
                            self.ratio_x,
                            self.ratio_y,
                            self.use_tui_height,
                            &mut self.cursor_position,
                        ) {
                            self.pending_events.push(pixel_event);
                        }
                    }
                }
            }
            _ => {
                let winit_event = WinitEvent::WindowEvent {
                    window_id: _window_id,
                    event,
                };
                if let Some(pixel_event) = input_events_from_winit(
                    &winit_event,
                    self.ratio_x,
                    self.ratio_y,
                    self.use_tui_height,
                    &mut self.cursor_position,
                ) {
                    self.pending_events.push(pixel_event);
                }
            }
        }
    }
}

impl Default for WinitWgpuAdapter {
    fn default() -> Self {
        Self::new()
    }
}

impl WinitWgpuAdapter {
    pub fn new() -> Self {
        Self {
            base: AdapterBase::new(),
            window: None,
            event_loop: None,
            window_init_params: None,

            wgpu_instance: None,
            wgpu_surface: None,
            wgpu_surface_config: None,
            render_core: None,

            should_exit: false,
            app_handler: None,
            custom_cursor: None,
            cursor_set: false,
            drag: Default::default(),
            original_ratio_x: 1.0,
            original_ratio_y: 1.0,
            ratio_overridden: false,
            logical_content_w: 0.0,
            logical_content_h: 0.0,
        }
    }

    fn init_common(&mut self, w: u16, h: u16, rx: f32, ry: f32, title: String) -> String {
        let (event_loop, window_init_params, texture_path) =
            winit_init_common(self, w, h, rx, ry, title);

        self.event_loop = Some(event_loop);
        self.window_init_params = Some(window_init_params);

        self.app_handler = Some(WinitWgpuAppHandler {
            pending_events: Vec::new(),
            cursor_position: (0.0, 0.0),
            ratio_x: self.base.gr.ratio_x,
            ratio_y: self.base.gr.ratio_y,
            use_tui_height: self.base.gr.use_tui_height,
            should_exit: false,
            adapter_ref: self as *mut WinitWgpuAdapter,
        });

        texture_path
    }

    fn init_wgpu(&mut self, w: u16, h: u16, rx: f32, ry: f32, title: String) {
        info!("Initializing Winit adapter with WGPU backend...");
        let _texture_path = self.init_common(w, h, rx, ry, title);
    }

    fn create_wgpu_window_and_resources(
        &mut self,
        event_loop: &winit::event_loop::ActiveEventLoop,
    ) {
        let params = self.window_init_params.as_ref().unwrap().clone();

        info!("Creating WGPU window and resources...");

        let window_size = LogicalSize::new(self.base.gr.pixel_w, self.base.gr.pixel_h);

        // Check if fullscreen mode is requested from GameConfig
        let game_config = crate::get_game_config();
        let fullscreen = if game_config.fullscreen {
            Some(Fullscreen::Borderless(None))
        } else {
            None
        };

        // Start window hidden to avoid white flash from uninitialized GPU memory
        // Window will be shown after first clear_screen_wgpu() call
        let window_attributes = winit::window::Window::default_attributes()
            .with_title(&params.title)
            .with_inner_size(window_size)
            .with_decorations(true)
            .with_resizable(true)
            .with_fullscreen(fullscreen.clone())
            .with_visible(false);

        let window = Arc::new(
            event_loop
                .create_window(window_attributes)
                .expect("Failed to create window"),
        );

        let physical_size = window.inner_size();
        let scale_factor = window.scale_factor();

        info!(
            "Window created - Logical: {}x{}, Physical: {}x{}, Scale factor: {:.2}",
            self.base.gr.pixel_w, self.base.gr.pixel_h,
            physical_size.width, physical_size.height,
            scale_factor
        );

        // Save original logical pixel size before fullscreen override (for letterboxing)
        self.logical_content_w = self.base.gr.pixel_w as f32;
        self.logical_content_h = self.base.gr.pixel_h as f32;

        let logical_w = self.base.gr.pixel_w as f32;
        let logical_h = self.base.gr.pixel_h as f32;
        let phys_w = physical_size.width as f32;
        let phys_h = physical_size.height as f32;
        let orig_ratio_x = self.base.gr.ratio_x;
        let orig_ratio_y = self.base.gr.ratio_y;

        log::info!("=== Window/Display Size Debug ===");
        log::info!("  game_config.fullscreen = {}", game_config.fullscreen);
        log::info!("  game_config.fullscreen_fit = {}", game_config.fullscreen_fit);
        log::info!("  logical (pixel_w/h before override) = {}x{}", logical_w, logical_h);
        log::info!("  physical (window inner_size) = {}x{}", phys_w, phys_h);
        log::info!("  scale_factor = {:.2}", scale_factor);
        log::info!("  original ratio_x={:.4}, ratio_y={:.4}", orig_ratio_x, orig_ratio_y);
        log::info!("  logical_content saved = {}x{}", self.logical_content_w, self.logical_content_h);

        let (canvas_w, canvas_h, ratio_x, ratio_y, render_scale) = if game_config.fullscreen {
            if game_config.fullscreen_fit {
                // Fullscreen-fit mode: preserve aspect ratio (isotropic rendering).
                // Use a canvas that matches the game's aspect ratio at max resolution.
                // Letterboxing in the composition stage maps this to the physical screen.
                let logical_aspect = logical_w / logical_h;
                let phys_aspect = phys_w / phys_h;

                let (cw, ch) = if phys_aspect > logical_aspect {
                    // Screen is wider than game: fit to height, pillarbox sides
                    let ch = phys_h as u32;
                    let cw = (phys_h * logical_aspect) as u32;
                    (cw, ch)
                } else {
                    // Screen is taller than game: fit to width, letterbox top/bottom
                    let cw = phys_w as u32;
                    let ch = (phys_w / logical_aspect) as u32;
                    (cw, ch)
                };

                // Uniform ratio: same for both axes → isotropic rendering
                let uniform_ratio = logical_w / cw as f32;

                log::info!("  [Fullscreen-FIT] logical_aspect={:.4}, phys_aspect={:.4}", logical_aspect, phys_aspect);
                log::info!("  [Fullscreen-FIT] canvas={}x{}, uniform_ratio={:.6}", cw, ch, uniform_ratio);
                log::info!("  [Fullscreen-FIT] render_scale=1.0");

                self.base.gr.ratio_x = uniform_ratio;
                self.base.gr.ratio_y = uniform_ratio;
                self.base.gr.pixel_w = cw;
                self.base.gr.pixel_h = ch;

                if let Some(ref mut handler) = self.app_handler {
                    handler.ratio_x = uniform_ratio;
                    handler.ratio_y = uniform_ratio;
                }

                (cw, ch, uniform_ratio, uniform_ratio, 1.0)
            } else {
                // Fullscreen-stretch mode: fill entire screen (non-uniform ratio)
                let new_ratio_x = logical_w / phys_w;
                let new_ratio_y = logical_h / phys_h;

                log::info!("  [Fullscreen-STRETCH] ratio_x={:.6}, ratio_y={:.6}", new_ratio_x, new_ratio_y);
                log::info!("  [Fullscreen-STRETCH] canvas={}x{} (=physical)", physical_size.width, physical_size.height);
                log::info!("  [Fullscreen-STRETCH] render_scale=1.0");

                self.base.gr.ratio_x = new_ratio_x;
                self.base.gr.ratio_y = new_ratio_y;
                self.base.gr.pixel_w = physical_size.width;
                self.base.gr.pixel_h = physical_size.height;

                if let Some(ref mut handler) = self.app_handler {
                    handler.ratio_x = new_ratio_x;
                    handler.ratio_y = new_ratio_y;
                }

                (physical_size.width, physical_size.height, new_ratio_x, new_ratio_y, 1.0)
            }
        } else {
            // Windowed mode: use physical size for RT, keep ratio for layout
            // render_scale = physical / logical, used to scale render coordinates
            let render_scale = phys_h / logical_h;

            log::info!("  [Windowed] canvas={}x{} (=physical)", physical_size.width, physical_size.height);
            log::info!("  [Windowed] ratio_x={:.6}, ratio_y={:.6} (unchanged)", self.base.gr.ratio_x, self.base.gr.ratio_y);
            log::info!("  [Windowed] render_scale={:.4}", render_scale);

            (physical_size.width, physical_size.height, self.base.gr.ratio_x, self.base.gr.ratio_y, render_scale)
        };

        log::info!("  --- Final Settings ---");
        log::info!("  canvas (RT) = {}x{}", canvas_w, canvas_h);
        log::info!("  surface (physical) = {}x{}", physical_size.width, physical_size.height);
        log::info!("  ratio = ({:.6}, {:.6}), render_scale = {:.4}", ratio_x, ratio_y, render_scale);
        log::info!("  pixel_w/h (after override) = {}x{}", self.base.gr.pixel_w, self.base.gr.pixel_h);
        log::info!("  isotropic = {}", (ratio_x - ratio_y).abs() < 0.0001);
        log::info!("================================");

        let wgpu_instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends: wgpu::Backends::all(),
            ..Default::default()
        });

        self.window = Some(window.clone());

        let wgpu_surface = unsafe {
            wgpu_instance
                .create_surface_unsafe(
                    wgpu::SurfaceTargetUnsafe::from_window(&**self.window.as_ref().unwrap())
                        .unwrap(),
                )
                .expect("Failed to create surface")
        };

        let (device, queue, wgpu_surface_config) = pollster::block_on(async {
            let adapter = wgpu_instance
                .request_adapter(&wgpu::RequestAdapterOptions {
                    power_preference: wgpu::PowerPreference::default(),
                    compatible_surface: Some(&wgpu_surface),
                    force_fallback_adapter: false,
                })
                .await
                .expect("Failed to find suitable WGPU adapter");

            info!("WGPU adapter found: {:?}", adapter.get_info());

            let (device, queue) = adapter
                .request_device(
                    &wgpu::DeviceDescriptor {
                        label: Some("RustPixel WGPU Device"),
                        required_features: wgpu::Features::empty(),
                        required_limits: wgpu::Limits::default(),
                        memory_hints: wgpu::MemoryHints::Performance,
                        ..Default::default()
                    },
                )
                .await
                .expect("Failed to create WGPU device");

            let surface_caps = wgpu_surface.get_capabilities(&adapter);
            let surface_format = surface_caps
                .formats
                .iter()
                .copied()
                .find(|f| !f.is_srgb())
                .unwrap_or(surface_caps.formats[0]);

            let surface_config = wgpu::SurfaceConfiguration {
                usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                format: surface_format,
                width: physical_size.width,
                height: physical_size.height,
                present_mode: surface_caps.present_modes[0],
                alpha_mode: surface_caps.alpha_modes[0],
                view_formats: vec![],
                desired_maximum_frame_latency: 2,
            };

            wgpu_surface.configure(&device, &surface_config);

            info!(
                "WGPU surface configured: {}x{}, format: {:?}",
                surface_config.width, surface_config.height, surface_config.format
            );

            (device, queue, surface_config)
        });

        // Build render core (Texture2DArray mode)
        let builder = WgpuRenderCoreBuilder::new(
            canvas_w,
            canvas_h,
            wgpu_surface_config.format,
        )
        .with_ratio(ratio_x, ratio_y)
        .with_render_scale(render_scale);

        let layer_data = crate::get_pixel_layer_data()
            .expect("Layer data not loaded");
        let layer_refs: Vec<&[u8]> = layer_data.layers.iter().map(|v| v.as_slice()).collect();
        let render_core = builder
            .build_layered(device, queue, layer_data.layer_size, &layer_refs)
            .expect("Failed to build render core");

        self.wgpu_instance = Some(wgpu_instance);
        self.wgpu_surface = Some(wgpu_surface);
        self.wgpu_surface_config = Some(wgpu_surface_config);
        self.render_core = Some(render_core);
    }

    fn clear_screen_wgpu(&mut self) {
        let mut cleared = false;
        if let (Some(surface), Some(core)) = (&self.wgpu_surface, &self.render_core) {
            if let Ok(output) = surface.get_current_texture() {
                let view = output
                    .texture
                    .create_view(&wgpu::TextureViewDescriptor::default());

                let mut encoder = core.device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("Cursor Clear Screen Encoder"),
                });

                {
                    let _clear_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                        label: Some("Cursor Clear Screen Pass"),
                        color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                            view: &view,
                            resolve_target: None,
                            ops: wgpu::Operations {
                                load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
                                store: wgpu::StoreOp::Store,
                            },
                            depth_slice: None,
                        })],
                        depth_stencil_attachment: None,
                        occlusion_query_set: None,
                        timestamp_writes: None,
                    });
                }

                core.queue.submit(std::iter::once(encoder.finish()));
                output.present();
                cleared = true;
            }
        }

        // Show the window after clear (or even if clear failed, to avoid permanently hidden window)
        // This avoids the white flash from uninitialized GPU memory on Windows Vulkan
        if let Some(window) = &self.window {
            window.set_visible(true);
        }
        let _ = cleared; // suppress unused warning
    }

    fn set_mouse_cursor(&mut self) {
        if let (Some(window), Some(event_loop)) = (&self.window, &self.event_loop) {
            if let Some(cursor) = load_custom_cursor(event_loop) {
                self.custom_cursor = Some(cursor.clone());
                apply_cursor_to_window(window, &cursor);
            }
        }
    }

    /// Rebuild render core with current pixel_w/pixel_h and ratio settings.
    /// Extracts device/queue from old core, builds new core, reconfigures surface.
    fn rebuild_render_core(&mut self) {
        if let Some(old_core) = self.render_core.take() {
            let device = old_core.device;
            let queue = old_core.queue;
            let format = self.wgpu_surface_config.as_ref().unwrap().format;

            let builder = WgpuRenderCoreBuilder::new(
                self.base.gr.pixel_w,
                self.base.gr.pixel_h,
                format,
            )
            .with_ratio(self.base.gr.ratio_x, self.base.gr.ratio_y);

            let layer_data = crate::get_pixel_layer_data()
                .expect("Layer data not loaded");
            let layer_refs: Vec<&[u8]> = layer_data.layers.iter().map(|v| v.as_slice()).collect();
            let new_core = builder
                .build_layered(device, queue, layer_data.layer_size, &layer_refs)
                .expect("Failed to rebuild render core");

            info!(
                "Render core rebuilt: {}x{}, ratio: ({}, {})",
                self.base.gr.pixel_w, self.base.gr.pixel_h,
                self.base.gr.ratio_x, self.base.gr.ratio_y
            );

            self.render_core = Some(new_core);
        }
    }

    #[allow(dead_code)]
    fn in_border(&self, x: f64, y: f64) -> BorderArea {
        check_border_area(x, y, &self.base)
    }

    /// Present render textures to screen with letterboxing support
    fn draw_render_textures_to_screen_wgpu(&mut self) -> Result<(), String> {
        let (cw, ch) = if let Some(core) = &self.render_core {
            core.canvas_size()
        } else {
            return Err("render_core not initialized".to_string());
        };

        let (phys_w, phys_h) = if let Some(window) = &self.window {
            let size = window.inner_size();
            (size.width as f32, size.height as f32)
        } else {
            (cw as f32, ch as f32)
        };

        // For letterboxing, use original logical pixel size (before fullscreen override).
        // In fullscreen mode, canvas_size == physical_size so using it would give aspect=1.
        let (content_w, content_h) = if self.logical_content_w > 0.0 && self.logical_content_h > 0.0 {
            (self.logical_content_w, self.logical_content_h)
        } else {
            (cw as f32, ch as f32)
        };

        let letterboxing = is_letterboxing_enabled();
        let (scale_x, scale_y) = if letterboxing {
            let content_aspect = content_w / content_h;
            let window_aspect = phys_w / phys_h;

            if window_aspect > content_aspect {
                let scale = phys_h / content_h;
                let scaled_w = content_w * scale;
                (scaled_w / phys_w, 1.0)
            } else {
                let scale = phys_w / content_w;
                let scaled_h = content_h * scale;
                (1.0, scaled_h / phys_h)
            }
        } else {
            (1.0, 1.0)
        };

        // Log composition debug info (first frame only via static flag)
        use std::sync::atomic::{AtomicBool, Ordering};
        static LOGGED: AtomicBool = AtomicBool::new(false);
        if !LOGGED.swap(true, Ordering::Relaxed) {
            println!("=== Composition Debug (first frame) ===");
            println!("  canvas (RT) = {}x{}", cw, ch);
            println!("  physical (window) = {}x{}", phys_w, phys_h);
            println!("  content_w/h (for letterbox) = {}x{}", content_w, content_h);
            println!("  letterboxing = {}", letterboxing);
            println!("  composition scale = ({:.4}, {:.4})", scale_x, scale_y);
            println!("=======================================");
        }

        let mut rt2_transform = UnifiedTransform::new();
        rt2_transform.scale(scale_x, scale_y);

        // Only render RT2 (main content) to screen
        // RT3 is only used during transitions and is handled separately by blend_rts
        let composites = vec![
            RtComposite::fullscreen(2).transform(rt2_transform),
        ];

        self.present_wgpu(&composites)
    }

    fn present_wgpu(&mut self, composites: &[RtComposite]) -> Result<(), String> {
        if let (Some(surface), Some(core)) = (&self.wgpu_surface, &mut self.render_core) {
            let output = surface
                .get_current_texture()
                .map_err(|e| format!("Failed to acquire next swap chain texture: {}", e))?;

            let view = output
                .texture
                .create_view(&wgpu::TextureViewDescriptor::default());

            core.present(&view, composites);

            output.present();
        } else {
            return Err("WGPU components not initialized".to_string());
        }

        Ok(())
    }
}

/// Manual Drop implementation to ensure correct destruction order on Wayland/Vulkan.
///
/// The wgpu::Surface holds a Vulkan swapchain that references the Wayland display
/// connection (via the Window). If the Window is dropped before the Surface, the
/// Surface destructor tries to use a dead Wayland connection → SEGFAULT.
///
/// Required drop order: render_core → surface → instance → window → event_loop
impl Drop for WinitWgpuAdapter {
    fn drop(&mut self) {
        // Drop GPU resources before the surface they depend on
        self.render_core.take();
        self.wgpu_surface_config.take();
        // Drop surface before instance and window
        self.wgpu_surface.take();
        self.wgpu_instance.take();
        // Window and event_loop dropped last (via normal struct drop for remaining fields)
    }
}

impl Adapter for WinitWgpuAdapter {
    fn init(&mut self, w: u16, h: u16, rx: f32, ry: f32, title: String) {
        info!("Initializing WinitWgpu adapter with WGPU backend...");
        self.init_wgpu(w, h, rx, ry, title);
    }

    fn get_base(&mut self) -> &mut AdapterBase {
        &mut self.base
    }

    fn get_canvas_size(&self) -> (u32, u32) {
        if let Some(core) = &self.render_core {
            core.canvas_size()
        } else {
            (self.base.gr.pixel_w, self.base.gr.pixel_h)
        }
    }

    fn reset(&mut self) {}

    fn poll_event(&mut self, timeout: Duration, es: &mut Vec<Event>) -> bool {
        if let (Some(event_loop), Some(app_handler)) =
            (self.event_loop.as_mut(), self.app_handler.as_mut())
        {
            let pump_timeout = Some(timeout);
            let status = event_loop.pump_app_events(pump_timeout, app_handler);

            for event in app_handler.pending_events.drain(..) {
                if !self.drag.draging {
                    es.push(event);
                }
            }

            if app_handler.should_exit {
                return true;
            }

            if let PumpStatus::Exit(_) = status {
                return true;
            }
        } else {
            // Event loop not ready yet; avoid busy spin in early initialization stage.
            std::thread::sleep(timeout);
        }

        self.should_exit
    }

    fn draw_all(
        &mut self,
        current_buffer: &Buffer,
        previous_buffer: &Buffer,
        pixel_sprites: &mut Vec<Layer>,
        stage: u32,
    ) -> Result<(), String> {
        winit_move_win(
            &mut self.drag.need,
            self.window.as_deref(),
            self.drag.dx,
            self.drag.dy,
        );

        self.draw_all_graph(current_buffer, previous_buffer, pixel_sprites, stage);

        self.post_draw();
        Ok(())
    }

    fn post_draw(&mut self) {
        if let Some(window) = &self.window {
            window.as_ref().request_redraw();
        }
    }

    fn hide_cursor(&mut self) -> Result<(), String> {
        Ok(())
    }

    fn show_cursor(&mut self) -> Result<(), String> {
        if let Some(window) = &self.window {
            window.set_cursor_visible(true);
        }
        Ok(())
    }

    fn set_cursor(&mut self, _x: u16, _y: u16) -> Result<(), String> {
        Ok(())
    }

    fn get_cursor(&mut self) -> Result<(u16, u16), String> {
        Ok((0, 0))
    }

    fn as_any(&mut self) -> &mut dyn Any {
        self
    }

    fn rbuf2rt(
        &mut self,
        rbuf: &[crate::render::adapter::RenderCell],
        rtidx: usize,
        debug: bool,
    ) where
        Self: Sized,
    {
        // Compute viewport scale (physical window height / canvas height)
        // for accurate mipmap level selection on resize/fullscreen.
        let viewport_scale = if let (Some(window), Some(core)) = (&self.window, &self.render_core) {
            let phys_h = window.inner_size().height as f32;
            let (_, canvas_h) = core.canvas_size();
            if canvas_h > 0 { phys_h / canvas_h as f32 } else { 1.0 }
        } else {
            1.0
        };

        if let Some(core) = &mut self.render_core {
            core.set_viewport_scale(viewport_scale);
            core.rbuf2rt(rbuf, rtidx, debug);
        } else {
            eprintln!("WinitWgpuAdapter: render core not initialized");
        }
    }

    fn set_rt_visible(&mut self, texture_index: usize, visible: bool) {
        if let Some(core) = &mut self.render_core {
            core.set_rt_visible(texture_index, visible);
        }
    }

    fn blend_rts(
        &mut self,
        src_texture1: usize,
        src_texture2: usize,
        dst_texture: usize,
        effect_type: usize,
        progress: f32,
    ) {
        if let Some(core) = &mut self.render_core {
            core.blend_rts(src_texture1, src_texture2, dst_texture, effect_type, progress);
        }
    }

    fn setup_buffer_transition(&mut self, target_texture: usize) {
        if let Some(core) = &mut self.render_core {
            core.set_rt_visible(target_texture, false);
        }
    }

    fn copy_rt(&mut self, src_index: usize, dst_index: usize) {
        if let Some(core) = &mut self.render_core {
            core.copy_rt(src_index, dst_index);
        }
    }

    fn present(&mut self, composites: &[RtComposite]) {
        if let Err(e) = self.present_wgpu(composites) {
            eprintln!("WinitWgpuAdapter: Failed to present: {}", e);
        }
    }

    fn present_default(&mut self) {
        if let Err(e) = self.draw_render_textures_to_screen_wgpu() {
            eprintln!("WinitWgpuAdapter: Failed to present_default: {}", e);
        }
    }

    fn set_sharpness(&mut self, sharpness: f32) {
        if let Some(core) = &mut self.render_core {
            core.set_sharpness(sharpness);
        }
    }

    fn set_msdf_enabled(&mut self, _enabled: bool) {
        // MSDF removed — layered mode always uses bitmap rendering
    }
}