LOTS of unsafe later... got my black triangle.

main
_ 2020-01-07 05:50:20 +00:00
parent bfeb111b14
commit 05eca4840f
1 changed files with 70 additions and 6 deletions

View File

@ -1,8 +1,9 @@
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use std::collections::HashMap;
use std::convert::TryInto;
use std::ffi::{CStr, CString};
use std::ffi::{c_void, CStr, CString};
use std::time::Duration;
const VERT_SHADER_SRC: &str =
@ -164,6 +165,13 @@ impl ShaderProgram {
gl::GetUniformLocation (self.id, name.as_ptr ())
}
}
pub fn get_attribute_location (&self, name: &CStr) -> i32 {
unsafe {
gl::UseProgram (self.id);
gl::GetAttribLocation (self.id, name.as_ptr ())
}
}
}
impl Drop for ShaderProgram {
@ -210,11 +218,66 @@ fn main () {
let shader_program = ShaderProgram::new (&vert_shader, &frag_shader).unwrap ();
let uni_model = shader_program.get_uniform_location (&CString::new ("uni_model").unwrap ());
let uni_viewproj = shader_program.get_uniform_location (CStr::from_bytes_with_nul (b"uni_viewproj\0").unwrap ());
let unis: HashMap <_, _> = vec! [
"model",
"viewproj",
].iter ()
.map (|name| {
let mut s = String::from ("uni_");
s.push_str (name);
let c_str = CString::new (s.as_bytes ()).unwrap ();
(String::from (*name), shader_program.get_uniform_location (&c_str))
})
.collect ();
println! ("uni_model: {}", uni_model);
println! ("uni_viewproj: {}", uni_viewproj);
println! ("uni_model: {}", unis ["model"]);
println! ("uni_viewproj: {}", unis ["viewproj"]);
let attrs: HashMap <_, u32> = vec! [
"pos",
"uv",
//"normal",
].iter ()
.map (|name| {
let mut s = String::from ("attr_");
s.push_str (name);
let c_str = CString::new (s.as_bytes ()).unwrap ();
let loc = shader_program.get_attribute_location (&c_str);
(String::from (*name), loc.try_into ().unwrap ())
})
.collect ();
println! ("attr_pos: {}", attrs ["pos"]);
let tri_mesh: Vec <f32> = vec! [
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
];
let id_mat: Vec <f32> = vec! [
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
];
let indexes: Vec <u16> = vec! [0, 1, 2];
const FALSE_U8: u8 = 0;
unsafe {
gl::EnableVertexAttribArray (attrs ["pos"]);
let stride = 4 * 2;
gl::VertexAttribPointer (attrs ["pos"], 2, gl::FLOAT, FALSE_U8, stride, &tri_mesh [0] as *const f32 as *const c_void);
gl::UniformMatrix4fv (unis ["viewproj"], 1, FALSE_U8, &id_mat [0]);
gl::UniformMatrix4fv (unis ["model"], 1, FALSE_U8, &id_mat [0]);
}
let mut event_pump = sdl_context.event_pump ().unwrap ();
'running: loop {
@ -235,6 +298,8 @@ fn main () {
unsafe {
gl::ClearColor (1.0f32, 0.0f32, 1.0f32, 1.0f32);
gl::Clear (gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
gl::DrawElements (gl::TRIANGLES, 3, gl::UNSIGNED_SHORT, &indexes [0] as *const u16 as *const c_void);
}
window.gl_swap_window ();
@ -242,4 +307,3 @@ fn main () {
::std::thread::sleep (Duration::from_millis (15));
}
}