添加println!导致Rust OpenGL程序无法渲染三角形?
Rust OpenGL 彩色三角形程序抽象问题:
println!导致渲染失效 我用Rust开发了一个在屏幕上绘制彩色三角形的简单OpenGL程序,原本运行正常,三角形能按预期渲染:

之后我尝试对代码做抽象:把VAO、VBO和ShaderProgram封装成结构体,处理绑定、着色器附加等逻辑,这部分工作正常。但在抽象顶点属性时遇到了问题:
我给ShaderProgram结构体加了两个方法,目的是不用硬编码步长(stride)或属性起始指针就能启用顶点属性:
pub fn add_attribute(&mut self, name: &'a str, length: i32) { let mut props = VertexAttributeProps::new(name, length); self.attributes.push(props); } pub fn apply_attributes(&self) { const GL_FLOAT_SIZE: i32 = mem::size_of::<gl::types::GLfloat>() as i32; let stride = self .attributes .iter() .fold(0, |prev, attr| prev + attr.length) * GL_FLOAT_SIZE; let mut current_pos: i32 = 0; for attr_options in self.attributes.iter() { // println!("{:?}", current_pos); unsafe { let attribute = VertexAttribute::new( location, attr_options.length, gl::FLOAT, gl::FALSE, stride, (current_pos * GL_FLOAT_SIZE) as *const c_void, ); attribute.enable(); } current_pos = current_pos + attr_options.length; } }
我希望通过以下方式添加属性:
shader_program.add_attribute("position", 2); shader_program.add_attribute("color", 3); shader_program.apply_attributes();
替代原本冗长的代码块:
let posAttrib: GLuint; unsafe { posAttrib = gl::GetAttribLocation( shader_program.program_handle, "position".as_ptr() as *const i8, ) as u32; gl::EnableVertexAttribArray(posAttrib); gl::VertexAttribPointer( posAttrib, 2, gl::FLOAT, gl::FALSE, 5 * mem::size_of::<gl::types::GLfloat>() as i32, 0 as *const c_void, ) } let colAttrib: GLuint; unsafe { colAttrib = gl::GetAttribLocation(shader_program.program_handle, "color".as_ptr() as *const i8) as u32; gl::EnableVertexAttribArray(colAttrib); gl::VertexAttribPointer( colAttrib, 3, gl::FLOAT, gl::FALSE, 5 * mem::size_of::<gl::types::GLfloat>() as i32, (2 * mem::size_of::<gl::types::GLfloat>()) as *const c_void, ) }
但这种抽象方式无法正常工作。于是我尝试调试,在原本可行的冗长代码中添加了println!语句:
let posAttrib: GLuint; unsafe { posAttrib = gl::GetAttribLocation( shader_program.program_handle, "position".as_ptr() as *const i8, ) as u32; // ??????? println!("{}", posAttrib); // ??????? gl::EnableVertexAttribArray(posAttrib); gl::VertexAttribPointer( posAttrib, 2, gl::FLOAT, gl::FALSE, 5 * mem::size_of::<gl::types::GLfloat>() as i32, 0 as *const c_void, ) }
结果三角形停止渲染,移除该语句后三角形又能正常显示。为何一个简单的println!会导致这种问题?是时序问题导致程序异常吗?
内容的提问来源于stack exchange,提问作者DerAnonyme
相关产品推荐
相关产品推荐

