Rust 的wgpu 跟winit最乾淨程式碼
- User
Rust 的wgpu 跟winit最乾淨程式碼
- Assistant
- User
wgpu = "25.0.2"用這個版本
- Assistant
- User
- Assistant
- User
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\wgpu-25.0.2\src\api\instance.rs:282:22 | 280 | pub fn create_surface<'window>( | -------------- required by a bound in this associated function 281 | &self, 282 | target: impl Into<SurfaceTarget<'window>>, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in
Instance::create_surfaceerror[E0308]: mismatched types --> src\main.rs:37:20 | 37 | trace: None, | ^^^^ expected , found | = note: expected enum found enum
- Assistant
- User
完整程式碼
- Assistant
- User
用wgpu = "0.16",winit = "0.28",pollster = "0.3" 的錯誤訊息 error[E0599]: no method named
get_supported_formatsfound for structSurfacein the current scope --> src\main.rs:51:29 | 51 | format: surface.get_supported_formats(&adapter)[0], | ^^^^^^^^^^^^^^^^^^^^^ method not found inSurfaceFor more information about this error, try
rustc --explain E0599. error: could not compilemy_project(bin "my_project") due to 1 previous error - Assistant
你在使用
wgpu = "0.16"版本搭配winit = "0.28"時,遇到的錯誤是:error[E0599]: no method named `get_supported_formats` found for struct `Surface` in the current scope這是因為在
wgpu 0.16這個版本中,Surface沒有get_supported_formats這個方法,該 API 是在後期版本才加入的。
解決方案
在
wgpu 0.16你必須用 surface 的get_capabilities方法來取得 surface 支援的格式,回傳的 struct 中會有formats欄位。以下是常見的寫法:
let surface_caps = surface.get_capabilities(&adapter); let surface_format = surface_caps.formats[0]; // 直接取第一個支援格式或者你可以遍歷
surface_caps.formats,選擇你喜歡的格式。
修改範例
把你原本用
surface.get_supported_formats(&adapter)[0]換成:let surface_caps = surface.get_capabilities(&adapter); let surface_format = surface_caps.formats[0]; - User
完整程式碼
- Assistant
- User
Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project) error[E0308]: mismatched types --> src\main.rs:23:44 | 23 | let instance = wgpu::Instance::new(wgpu::Backends::all()); | ------------------- ^^^^^^^^^^^^^^^^^^^^^ expected
InstanceDescriptor, foundBackends| | | arguments to this function are incorrect | note: associated function defined here --> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\wgpu-0.16.3\src\lib.rs:1331:12 | 1331 | pub fn new(instance_desc: InstanceDescriptor) -> Self { | ^^^error[E0063]: missing field
view_formatsin initializer ofwgpu_types::SurfaceConfiguration<Vec<TextureFormat>>--> src\main.rs:56:22 | 56 | let config = wgpu::SurfaceConfiguration { | ^^^^^^^^^^^^^^^^^^^^^^^^^^ missingview_formatsSome errors have detailed explanations: E0063, E0308. For more information about an error, try
rustc --explain E0063. - Assistant
- User
Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project) error[E0614]: type
PhysicalSize<u32>cannot be dereferenced --> src\main.rs:148:68 | 148 | WindowEvent::Resized(size) => state.resize(*size), | ^^^^^ can't be dereferenced error[E0614]: typePhysicalSize<u32>cannot be dereferenced --> src\main.rs:150:42 | 150 | ... state.resize(**new_inner_size) | ^^^^^^^^^^^^^^^^ can't be dereferencedFor more information about this error, try
rustc --explain E0614. error: could not compilemy_project(bin "my_project") due to 2 previous errors - Assistant
你遇到的錯誤是因為嘗試對
PhysicalSize<u32>這個型別解引用(*size、**new_inner_size),但PhysicalSize本身是結構體,不能用*解引用。
錯誤行
WindowEvent::Resized(size) => state.resize(*size), WindowEvent::ScaleFactorChanged { new_inner_size, .. } => state.resize(**new_inner_size)
改法:去掉
*解引用,直接傳參即可改成:
WindowEvent::Resized(size) => state.resize(*size), // 錯誤,不用 * WindowEvent::Resized(size) => state.resize(size), // 正確 WindowEvent::ScaleFactorChanged { new_inner_size, .. } => state.resize(**new_inner_size), // 錯誤,不用 ** WindowEvent::ScaleFactorChanged { new_inner_size, .. } => state.resize(*new_inner_size), // 正確
可能的解釋:
WindowEvent::Resized(size)中的size是 ,直接使用該值(是 Copy 類型)即可,不需要對它解引用。 - User
完整程式碼
- Assistant
- User
中間有一個三角形有厚度在旋轉
- Assistant
- User
- Assistant
你的錯誤訊息是說找不到
cgmath跟bytemuck這兩個 crate,也就是你還沒在你的專案Cargo.toml裡加入這兩個依賴。請打開你專案根目錄下的
Cargo.toml,在[dependencies]區段加入以下:cgmath = "0.18" bytemuck = { version = "1.7", features = ["derive"] }例如,你的
Cargo.toml會像這樣:[package] name = "my_project" version = "0.1.0" edition = "2021" [dependencies] wgpu = "0.16" winit = "0.28" pollster = "0.3" cgmath = "0.18" bytemuck = { version = "1.7", features = ["derive"] }
或者你也可以在命令列執行(有
cargo-edit工具時):cargo add cgmath cargo add bytemuck --features derive安裝完後,重新
cargo build就能找到這些 crate,錯誤也會消失。
補充:
cgmath是幫忙處理矩陣、向量和數學運算的 crate。bytemuck是用來提供安全的 memory cast,方便把 struct 轉成 byte slice 傳給 GPU buffer。features = ["derive"]是讓它支援#[derive(bytemuck::Pod, bytemuck::Zeroable)]這樣的宏。
如有需要,我可以幫你確認整個範例的
Cargo.toml配置也一起給你。 - User
wgpu error: Validation Error
Caused by: In Device::create_shader_module note: label =
ShaderShader 'Shader' parsing error: expected global item ('struct', 'const', 'var', 'alias', ';', 'fn') or the end of the file, found '[' ┌─ wgsl:1:1 │ 1 │ [[block]] │ ^ expected global item ('struct', 'const', 'var', 'alias', ';', 'fn') or the end of the file
expected global item ('struct', 'const', 'var', 'alias', ';', 'fn') or the end of the file, found '['note: run with
RUST_BACKTRACE=1environment variable to display a backtrace error: process didn't exit successfully:target\debug\my_project.exe(exit code: 101) - Assistant
你的 WGSL 着色器語法錯誤,是因為你使用了舊版 WGSL 語法(
[[block]]、[[group(0), binding(0)]]、[[location(0)]]等雙中括號屬性),而目前 wgpu 及 Vulkan WGSL 實作已改為 Rust-style 的@屬性標註。
語法差異
- 舊版 WGSL (已過時,wgpu 0.16 應該不適用):
[[block]] struct Uniforms { ... }; [[group(0), binding(0)]] var<uniform> uniforms: Uniforms; [[stage(vertex)]] fn vs_main() -> { ... }- 新版 WGSL (目前符合 wgpu 官方要求):
struct Uniforms { @size(64) // 可選 ... }; @group(0) @binding(0) var<uniform> uniforms: Uniforms; @vertex fn vs_main() -> ... { ... } - User
Caused by: In Device::create_shader_module note: label =
ShaderShader 'Shader' parsing error: expected global item ('struct', 'const', 'var', 'alias', ';', 'fn') or the end of the file, found 'let' ┌─ wgsl:1:1 │ 1 │ let shader_source = wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(r#" │ ^^^ expected global item ('struct', 'const', 'var', 'alias', ';', 'fn') or the end of the file
expected global item ('struct', 'const', 'var', 'alias', ';', 'fn') or the end of the file, found 'let'note: run with
RUST_BACKTRACE=1environment variable to display a backtrace error: process didn't exit successfully:target\debug\my_project.exe(exit code: 101) - Assistant
你把 Rust 變數宣告 (
let shader_source = ...) 的程式碼直接貼到 WGSL Shader 檔案或是傳給create_shader_module的字串裡了。
核心問題
wgpu::Device::create_shader_module接受的是 WGSL 語言的字串,不是 Rust 程式碼,不能包含 Rust 的let或其他語法。
正確做法示範:
// 這是 Rust 程式碼裡面定義 shader 字串內容 let shader_source = wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(r#" struct Uniforms { mvp: mat4x4<f32>; }; @group(0) @binding(0) var<uniform> uniforms: Uniforms; struct VertexInput { @location(0) position: vec3<f32>; }; struct VertexOutput { @builtin(position) position: vec4<f32>; }; @vertex fn vs_main(input: VertexInput) -> VertexOutput { var output: VertexOutput; output.position = uniforms.mvp * vec4<f32>(input.position, 1.0); return output; } @fragment fn fs_main() -> @location(0) vec4<f32> { return vec4<f32>(1.0, 1.0, 1.0, 1.0); } "#)); - User
一個3d立體三角形旋轉,有厚度
- Assistant
- User
Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project) error[E0308]: mismatched types --> src\main.rs:185:50 | 185 | let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { | _____________________--------------------^ | | | | | arguments to this method are incorrect 186 | | label: Some("Shader"), 187 | | source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()), 188 | | }); | |^ expected
ShaderModuleDescriptor<'_>, found&ShaderModuleDescriptor<'_>
| note: method defined here --> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\wgpu-0.16.3\src\lib.rs:1936:12 | 1936 | pub fn create_shader_module(&self, desc: ShaderModuleDescriptor) -> ShaderModule {
| ^^^^^^^^^^^^^^^^^^^^ help: consider removing the borrow | 185 - let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { 185 + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |For more information about this error, try
rustc --explain E0308. error: could not compilemy_project(bin "my_project") due to 1 previous error - Assistant
這個錯誤是因為
wgpu 0.16版本中,device.create_shader_module需要直接取得ShaderModuleDescriptor實例(值),而非借用(&ShaderModuleDescriptor)。
修正方式
把這行:
let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { label: Some("Shader"), source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()), });改成:
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Shader"), source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()), });刪除
&,直接傳入擁有所有權的值。
解釋
-
.create_shader_module()的函式簽名是pub fn create_shader_module(&self, desc: ShaderModuleDescriptor) -> ShaderModule因此
desc是傳入值,而非引用。
最後提醒
wgpu API 在不同版本有變動,請參考你當時使用的版本文件。
有任何其他錯誤都歡迎繼續問我!
-
- User
完整的程式碼
- Assistant
- User
視窗中間一個旋轉三角形,有厚度,
- Assistant
- User
這個三角形看不到厚度,很像兩個三角形爾以
- Assistant
你說得對,上面範例是標準三角錐模型,它是由4個頂點、4個三角形面組成,的確是個**「中空」的三角錐**,沒有實際的「實心厚度」(mesh厚實的體積)。所以看起來其實就像「多個靠攏的三角形面片」,沒有變成實心或有體積感。
如何讓三角形「有厚度」?
幾種方式:
1. 幾何學上的「挤出」(Extrude)成為三維實心物件
- 將你的三角形從平面抽出厚度,變成類似三角柱(Prism)而不是三角錐。
- 也就是你要在Z軸(或其他軸)複製三角形頂點一組,兩組頂點用矩形面連接,變成立體厚度。
2. 模型建築軟體(Blender / Maya)做好模型
- 直接設計有厚度的三角柱模型,匯出為 glTF 或其他格式,用 Rust/
wgpu做讀入渲染。
這邊我示範如何用程式碼「挤出」三角形成三角柱(有厚度),就是:
- 底層三角形頂點一組(Z=0)
- 頂層三角形頂點一組(Z=厚度,比方說Z=0.2)
- 三角柱側面由4個矩形面(三角形3個邊各對應一個矩形)組成,每個矩形用兩個三角形面表示。
語意
- 共有 6 個頂點(底三角形3個+頂三角形3個)
- 底面三角形1個,頂面三角形1個
- 側面3個矩形=6個三角形面(三角柱邊厚度)
程式示範(用
wgpu 0.16)main.rs頂點定義:// 底面三角形(Z=0) Vertex { position: [ 0.0, 0.5, 0.0], color: RED }, // 0 Vertex { position: [-0.5,-0.5, 0.0], color: GREEN }, // 1 Vertex { position: [ 0.5,-0.5, 0.0], color: BLUE }, // 2 // 頂面三角形(Z=厚度=0.2) Vertex { position: [ 0.0, 0.5, 0.2], color: RED }, // 3 Vertex { position: [-0.5,-0.5, 0.2], color: GREEN }, // 4 Vertex { position: [ 0.5,-0.5, 0.2], color: BLUE }, // 5 - User
完整範例分段提供
- Assistant