Skip to content

Commit

Permalink
也许呢.png
Browse files Browse the repository at this point in the history
  • Loading branch information
shenjackyuanjie committed Jan 22, 2025
1 parent 1b2c726 commit 15b122a
Show file tree
Hide file tree
Showing 8 changed files with 145 additions and 63 deletions.
2 changes: 2 additions & 0 deletions mods/dr_game/Difficult_Rocket_rs/src/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
*/

mod dr_physics;
/// 平台相关的代码
pub mod platform;
/// Python 交互
mod python;
/// 也许是一些渲染的东西
Expand Down
2 changes: 2 additions & 0 deletions mods/dr_game/Difficult_Rocket_rs/src/src/platform/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#[cfg(windows)]
pub mod win;
28 changes: 28 additions & 0 deletions mods/dr_game/Difficult_Rocket_rs/src/src/platform/win/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use windows_sys::Win32::{
Foundation::HWND,
System::Threading::GetCurrentProcessId,
UI::WindowsAndMessaging::{EnumWindows, GetWindowThreadProcessId},
};

unsafe extern "system" fn enum_windows_proc(hwnd: HWND, lparam: isize) -> i32 {
let mut process_id = 0;
GetWindowThreadProcessId(hwnd, &mut process_id);
if process_id == GetCurrentProcessId() {
println!("找到当前的窗口: {:?}", hwnd);
*(lparam as *mut HWND) = hwnd;
return 0;
}
1
}

pub fn get_window_handler() -> Option<isize> {
let mut window: HWND = std::ptr::null_mut();

let result = unsafe { EnumWindows(Some(enum_windows_proc), &mut window as *mut _ as isize) };

if result != 0 {
return None;
}

Some(window as isize)
}
1 change: 1 addition & 0 deletions mods/dr_game/Difficult_Rocket_rs/src/src/python.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ pub mod console;
pub mod data;
#[allow(unused)]
pub mod editor;
pub mod renders;
19 changes: 19 additions & 0 deletions mods/dr_game/Difficult_Rocket_rs/src/src/python/renders.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use pyo3::prelude::*;

#[pyclass]
pub struct WgpuRenderPy {
#[cfg(windows)]
pub app: crate::renders::win_gpu::WgpuContext,
}

#[pymethods]
impl WgpuRenderPy {
pub fn on_draw(&mut self) {
#[cfg(windows)]
self.app.on_draw();
}
}

impl WgpuRenderPy {
pub fn new(app: crate::renders::win_gpu::WgpuContext) -> Self { Self { app } }
}
10 changes: 6 additions & 4 deletions mods/dr_game/Difficult_Rocket_rs/src/src/renders.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
#[cfg(windows)]
mod win;
pub mod win;
#[cfg(windows)]
mod win_gpu;
pub mod win_gpu;

use pyo3::pyfunction;

#[pyfunction]
pub fn render_hack() {
pub fn render_hack() -> Option<crate::python::renders::WgpuRenderPy> {
println!("render_hacking_start");
#[cfg(windows)]
win::render_main();
// let render = win::render_main();
let render = win_gpu::render_init();
#[cfg(not(windows))]
println!("对不起不支持非 Windows 捏");
println!("render_hacking_end");
render
}
29 changes: 7 additions & 22 deletions mods/dr_game/Difficult_Rocket_rs/src/src/renders/win.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ use winit::window::WindowAttributes;
use winit::{application::ApplicationHandler, event_loop::EventLoop, window::Window};

use windows_sys::Win32::Foundation::HWND;
use windows_sys::Win32::System::Threading::GetCurrentProcessId;
use windows_sys::Win32::UI::WindowsAndMessaging::{EnumWindows, GetWindowThreadProcessId};

use raw_window_handle::{RawWindowHandle, Win32WindowHandle};

Expand Down Expand Up @@ -82,17 +80,6 @@ impl App {
pub fn ref_window(&self) -> &Window { self.window.as_ref().unwrap() }
}

unsafe extern "system" fn enum_windows_proc(hwnd: HWND, lparam: isize) -> i32 {
let mut process_id = 0;
GetWindowThreadProcessId(hwnd, &mut process_id);
if process_id == GetCurrentProcessId() {
println!("找到当前的窗口: {:?}", hwnd);
*(lparam as *mut HWND) = hwnd;
return 0;
}
1
}

fn render_thread(handler: isize) -> anyhow::Result<()> {
let window = handler as HWND;
let win32_handle = Win32WindowHandle::new(NonZeroIsize::new(window as isize).unwrap());
Expand All @@ -108,15 +95,13 @@ fn render_thread(handler: isize) -> anyhow::Result<()> {
}

pub fn render_main() {
let mut window: HWND = std::ptr::null_mut();

let result = unsafe { EnumWindows(Some(enum_windows_proc), &mut window as *mut _ as isize) };

if result != 0 {
println!("Find window failed");
return;
}
println!("找到 pyglet 的窗口: {:?}", window);
let window = match crate::platform::win::get_window_handler() {
Some(window) => window,
None => {
println!("Failed to get window handler");
return;
}
};

// let window_ptr = window as isize;

Expand Down
117 changes: 80 additions & 37 deletions mods/dr_game/Difficult_Rocket_rs/src/src/renders/win_gpu.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use raw_window_handle::RawWindowHandle;
use winit::window::Window;
use wgpu::{Adapter, Device, Instance, Queue, Surface, SurfaceTargetUnsafe};
use std::num::NonZeroIsize;

use pollster::block_on;
use raw_window_handle::{RawWindowHandle, Win32WindowHandle};
use wgpu::{Adapter, Device, Gles3MinorVersion, Instance, InstanceDescriptor, Queue, Surface, SurfaceTargetUnsafe};

/// 定义一个结构体保存所有渲染上下文
#[derive(Debug)]
Expand All @@ -14,50 +15,41 @@ pub struct WgpuContext {
}

impl WgpuContext {
pub fn new(window_handle: &RawWindowHandle) -> anyhow::Result<Self> {
let unsafe_handle = SurfaceTargetUnsafe::RawHandle{
raw_window_handle: window_handle.to_owned(),
raw_display_handle: raw_window_handle::RawDisplayHandle::Windows(raw_window_handle::WindowsDisplayHandle::new())
};
pub fn new(unsafe_handle: SurfaceTargetUnsafe) -> anyhow::Result<Self> {
let mut descripter = InstanceDescriptor::default();
descripter.backends = wgpu::Backends::from_comma_list("vulkan,dx12");

let instance = Instance::default();
let surface = unsafe {
instance.create_surface_unsafe(unsafe_handle)
}?;
let instance = Instance::new(&descripter);
let surface = unsafe { instance.create_surface_unsafe(unsafe_handle) }?;

// 步骤2: 请求适配器(Adapter)
let adapter = block_on(
instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
force_fallback_adapter: false,
})
).expect("Failed to find合适的适配器");
let adapter = block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
force_fallback_adapter: false,
}))
.expect("没找到合适的适配器");

// 步骤3: 创建设备和队列(Device/Queue)
let (device, queue) = block_on(
adapter.request_device(
&wgpu::DeviceDescriptor {
label: None,
// 如果需要特定功能(如深度缓冲),在此处声明
required_features: wgpu::Features::empty(),
// 根据需求调整限制(如纹理大小)
required_limits: wgpu::Limits::downlevel_defaults(),
memory_hints: wgpu::MemoryHints::default(),
},
None, // 追踪路径(Trace Path)
)
)?;
let (device, queue) = block_on(adapter.request_device(
&wgpu::DeviceDescriptor {
label: Some("主设备"),
// 如果需要特定功能(如深度缓冲),在此处声明
required_features: wgpu::Features::empty(),
// 根据需求调整限制(如纹理大小)
required_limits: wgpu::Limits::downlevel_defaults(),
memory_hints: wgpu::MemoryHints::default(),
},
None, // 追踪路径(Trace Path)
))?;

// 步骤4: 配置Surface
let surface_caps = surface.get_capabilities(&adapter);
let surface_format = surface_caps.formats.iter()
.find(|f| f.is_srgb())
.unwrap_or(&surface_caps.formats[0]);
let surface_format = surface_caps.formats.iter().find(|f| f.is_srgb()).unwrap_or(&surface_caps.formats[0]);

let height = 100;
let width = 100;
// let size =
// let size =
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: *surface_format,
Expand All @@ -78,4 +70,55 @@ impl WgpuContext {
config,
})
}
}

pub fn on_draw(&mut self) {
// 步骤5: 渲染
// let frame = self.surface.get_current_frame().expect("Failed to acquire next swap chain texture").output;
// let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
// {
// let _render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
// color_attachments: &[
// wgpu::RenderPassColorAttachment {
// view: &frame.view,
// resolve_target: None,
// ops: wgpu::Operations {
// load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
// store: true,
// }
// }
// ],
// depth_stencil_attachment: None,
// });
// }
// self.queue.submit(std::iter::once(encoder.finish()));
}
}

pub fn render_init() -> Option<crate::python::renders::WgpuRenderPy> {
let handler = match crate::platform::win::get_window_handler() {
Some(handler) => handler,
None => {
println!("找不到 pyglet 创建的窗口");
return None;
}
};

let win32_handle = Win32WindowHandle::new(NonZeroIsize::new(handler).unwrap());
let raw_handle: RawWindowHandle = RawWindowHandle::Win32(win32_handle);
let unsafe_handle = SurfaceTargetUnsafe::RawHandle {
raw_window_handle: raw_handle,
raw_display_handle: raw_window_handle::RawDisplayHandle::Windows(raw_window_handle::WindowsDisplayHandle::new()),
};

let content = match WgpuContext::new(unsafe_handle) {
Ok(content) => content,
Err(e) => {
println!("Failed to create wgpu context: {:?}", e);
return None;
}
};

let py_warped = crate::python::renders::WgpuRenderPy::new(content);

Some(py_warped)
}

0 comments on commit 15b122a

Please sign in to comment.