triangle rust with ZEN style.

use rustgl::*;
use rustgl::GL::*;
use glfw::*;

unsafe fn read_file(path: &a/str) -> (int, *u8) {
    let s = io::read_whole_file(&path::Path(path));
    let mut bytes = result::unwrap(s);
    bytes.push(0u8);
    assert bytes.len() > 0;
    return (bytes.len() as int, vec::raw::to_ptr(bytes));
}

fn check_errors(errStr: &str) {
    let err = glGetError();
    if err != 0 {
        let s = if err == GL_INVALID_ENUM {
             ~"invalid enum"
        } else if err == GL_INVALID_VALUE {
             ~"invalid value"
        } else if err == GL_INVALID_OPERATION {
             ~"invalid operation"
        } else {
            fmt!("%?", err)
        };
        fail fmt!("opengl error code: %s in %s", s, errStr);
    }
}

fn main() {
    let aspect = 1.85f,
        height = 700,
        width = (aspect * (height as float)) as int;
    glfw::open_window(width, height, GLFW_WINDOW);
    glfw::center_window();
    glfw::set_window_title("Hello, World!");

    unsafe {
        unsafe fn create_shader(t: rustgl::GLenum, path: &str) -> GLuint {
            let id = glCreateShader(t);
            let (len, source) = read_file(path);
            glShaderSource(id, 1, ptr::addr_of(&source), ptr::addr_of(&len));
            glCompileShader(id);
            return id;
        }

        let id = glCreateProgram();
        glAttachShader(id, create_shader(GL_VERTEX_SHADER, "shaders/basic.glslv"));
        glAttachShader(id, create_shader(GL_FRAGMENT_SHADER, "shaders/basic.glslf"));
        glLinkProgram(id);
        glUseProgram(id);

        let mut id = 200,
            data = [mut 0f, ..6];
        let dataSize = (sys::size_of::<float>() * data.len());
        data[0] = 0f; data[1] = 0f;
        data[2] = 5f; data[3] = 0f;
        data[4] = 0f; data[5] = 5f;
        glGenBuffers(1, ptr::addr_of(&id));
        check_errors("GenBuffers");

        debug!("buffer id: %?", id);
        glBindBuffer(GL_ARRAY_BUFFER, id);
        assert glIsBuffer(id) == GL_TRUE;
        check_errors("BindBuffer");

        glBufferData(GL_ARRAY_BUFFER, dataSize as int,
            vec::raw::to_ptr(data) as *const GLvoid, GL_STATIC_DRAW);
        check_errors("BufferData");

        glEnableVertexAttribArray(0);
        glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0 as *uint);
    }

    while !glfw::get_key(GLFW_KEY_ESC) {
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

        glDrawArrays(GL_TRIANGLES, 0, 3);

        glfwSwapBuffers();
    }
    glfwTerminate();
}

Posted on 2012-10-12 15:55 with rust in 0.048 sec.