1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
use crate::interfaces::Interface;
use crate::processor::Processor;

use gl::types::{GLchar, GLfloat, GLint, GLsizei, GLuint};
use glfw::{Context, Glfw, GlfwReceiver, PWindow, WindowEvent};
use std::{array, ffi::CString, mem, os::raw::c_void, ptr};

pub struct OpenGlInterface {
    glfw: Glfw,
    events: GlfwReceiver<(f64, WindowEvent)>,
    window: PWindow,
    cbo: GLuint,
    input_states: [bool; 0x10],
}
const VERTEX_SHADER: &str = r#"
#version 330 core
layout (location = 0) in vec3 aPos;
out vec3 pos;
out vec3 vColor;
in vec3 color;

void main() {
    gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
    pos = aPos;
    vColor = color;
}
"#;

const FRAGMENT_SHADER: &str = r#"
#version 330 core
out vec4 color;
in vec3 vColor;

void main() {
    color = vec4(vColor, 1.0f);
}
"#;

/**
 * Interface that uses OpenGL to render the processor.
 */
impl OpenGlInterface {
    pub fn new() -> OpenGlInterface {
        // glfw: initialize and configure
        // ------------------------------
        let mut glfw = glfw::init(glfw::fail_on_errors).unwrap();
        glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3));
        glfw.window_hint(glfw::WindowHint::OpenGlProfile(
            glfw::OpenGlProfileHint::Core,
        ));
        #[cfg(target_os = "macos")]
        glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true));

        // glfw window creation
        // --------------------
        let (mut window, events) = glfw
            .create_window(800, 600, "CHIP-8", glfw::WindowMode::Windowed)
            .expect("Failed to create GLFW window");

        gl::load_with(|symbol| window.get_proc_address(symbol) as *const _);

        window.focus();
        window.make_current();
        window.set_key_polling(true);
        window.set_framebuffer_size_polling(true);

        // Load up vertexes
        // Define "window" boundaries
        const X_MIN: f32 = -1.0;
        const X_MAX: f32 = 1.0;
        const Y_MIN: f32 = -1.0;
        const Y_MAX: f32 = 1.0;
        // Generate 4 vertices for each pixel (2 triangles)
        let vertices: [f32; 3 * 4 * 64 * 32] = array::from_fn(|i| {
            const PIXEL: [[f32; 3]; 4] = [
                [0.0, 0.0, 0.0],
                [1.0, 0.0, 0.0],
                [1.0, 1.0, 0.0],
                [0.0, 1.0, 0.0],
            ];
            let x = (i / (3 * 4)) % 64;
            let y = (i / (3 * 4)) / 64;
            let pixel_i = i % 12;
            let vertex = PIXEL[pixel_i / 3];
            return match i % 3 {
                0 => X_MIN + (x as f32 + vertex[0]) / 64.0 * (X_MAX - X_MIN),
                1 => Y_MIN + (y as f32 + vertex[1]) / 32.0 * (Y_MAX - Y_MIN),
                2 => 0 as f32,
                _ => 0 as f32,
            };
        });

        // Generate indices linking those 4 vertices into 2 triangles
        let indices: [i32; 6 * 64 * 32] = array::from_fn(|i| {
            let pixel = i / 6;
            return ((4 * pixel) + [0, 1, 2, 0, 2, 3][i % 6]) as i32;
        });

        // Default color is just white
        let colors: [f32; 3 * 4 * 65 * 33] = array::from_fn(|_| {
            return 1.0 as f32;
        });

        let mut vao = 0;
        let mut vbo = 0;
        let mut ebo = 0;
        let mut cbo = 0;
        unsafe {
            let vertex_shader = compile_shader(VERTEX_SHADER, gl::VERTEX_SHADER);
            let fragment_shader = compile_shader(FRAGMENT_SHADER, gl::FRAGMENT_SHADER);

            let program = create_program(vec![vertex_shader, fragment_shader]);

            gl::DeleteShader(vertex_shader);
            gl::DeleteShader(fragment_shader);

            gl::GenVertexArrays(1, &mut vao);
            gl::GenBuffers(1, &mut vbo);
            gl::GenBuffers(1, &mut ebo);
            gl::GenBuffers(1, &mut cbo);

            gl::BindVertexArray(vao);

            gl::BindBuffer(gl::ARRAY_BUFFER, vbo);
            gl::BufferData(
                gl::ARRAY_BUFFER,
                (vertices.len() * mem::size_of::<GLfloat>()) as isize,
                &vertices[0] as *const f32 as *const c_void,
                gl::STATIC_DRAW,
            );

            gl::VertexAttribPointer(
                0,
                3,
                gl::FLOAT,
                gl::FALSE,
                3 * mem::size_of::<GLfloat>() as GLsizei,
                ptr::null(),
            );
            gl::EnableVertexAttribArray(0);
            gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ebo);
            gl::BufferData(
                gl::ELEMENT_ARRAY_BUFFER,
                (indices.len() * mem::size_of::<GLfloat>()) as isize,
                &indices[0] as *const i32 as *const c_void,
                gl::STATIC_DRAW,
            );

            gl::BindBuffer(gl::ARRAY_BUFFER, cbo);
            gl::BufferData(
                gl::ARRAY_BUFFER,
                (colors.len() * mem::size_of::<GLfloat>()) as isize,
                &colors[0] as *const f32 as *const c_void,
                gl::STATIC_DRAW,
            );
            let name = "color";
            let c_name = CString::new(name.as_bytes()).unwrap();
            let color_idx = gl::GetAttribLocation(program, c_name.as_ptr()) as u32;
            gl::EnableVertexAttribArray(color_idx);
            gl::VertexAttribPointer(color_idx, 3, gl::FLOAT, gl::FALSE, 0, ptr::null());

            gl::BindBuffer(gl::ARRAY_BUFFER, 0);
            gl::BindVertexArray(0);
            gl::UseProgram(program);
            gl::BindVertexArray(vao);

            gl::Disable(gl::DITHER);
            gl::Disable(gl::LINE_SMOOTH);
            gl::Disable(gl::POLYGON_SMOOTH);
            gl::Hint(gl::POLYGON_SMOOTH_HINT, gl::DONT_CARE);
            gl::Hint(gl::LINE_SMOOTH_HINT, gl::DONT_CARE);
        }

        OpenGlInterface {
            glfw,
            events,
            window,
            cbo: cbo,
            input_states: [false; 0x10],
        }
    }
}

impl Interface for OpenGlInterface {
    fn exit(&mut self) {}
    fn update(&mut self, p: &mut Processor) -> bool {
        let key_map = [
            glfw::Key::X,
            glfw::Key::Num1,
            glfw::Key::Num2,
            glfw::Key::Num3,
            glfw::Key::Q,
            glfw::Key::W,
            glfw::Key::E,
            glfw::Key::A,
            glfw::Key::S,
            glfw::Key::D,
            glfw::Key::Z,
            glfw::Key::C,
            glfw::Key::Num4,
            glfw::Key::R,
            glfw::Key::F,
            glfw::Key::V,
        ];
        // Check for events
        self.glfw.poll_events();
        for (_, event) in glfw::flush_messages(&self.events) {
            match event {
                glfw::WindowEvent::FramebufferSize(width, height) => {
                    // make sure the viewport matches the new window dimensions; note that width and
                    // height will be significantly larger than specified on retina displays.
                    unsafe { gl::Viewport(0, 0, width, height) }
                }
                glfw::WindowEvent::Key(glfw::Key::Escape, _, glfw::Action::Press, _) => {
                    self.window.set_should_close(true);
                }
                glfw::WindowEvent::Key(key, _, action, _) => {
                    match key_map.iter().position(|k| *k == key) {
                        Some(i) => {
                            self.input_states[i] = match action {
                                glfw::Action::Press => true,
                                glfw::Action::Release => false,
                                _ => self.input_states[i],
                            };
                            if action == glfw::Action::Release {
                                p.on_key_release(i as u8);
                            }
                        }
                        _ => {}
                    }
                }
                _ => {}
            }
        }
        p.update_inputs(self.input_states);
        return self.window.should_close();
    }
    fn render(&mut self, p: &Processor) {
        // render
        // ------
        unsafe {
            gl::ClearColor(0.2, 0.3, 0.3, 1.0);
            gl::Clear(gl::COLOR_BUFFER_BIT);

            // Calculate colors of each vertex
            // 3 floats per color * 4 colors/vertices per pixel
            let colors: [f32; 3 * 4 * 64 * 32] = array::from_fn(|i| {
                let x = (i / 3 / 4) % 64;
                let y = (i / 3 / 4) / 64;
                // Our screen starts at the top left
                return if p.get_pixel_at(x as u8, 64 - y as u8) {
                    1
                } else {
                    0
                } as f32;
            });

            // Refresh color buffer
            gl::BindBuffer(gl::ARRAY_BUFFER, self.cbo);
            gl::BufferData(
                gl::ARRAY_BUFFER,
                (colors.len() * mem::size_of::<GLfloat>()) as isize,
                &colors[0] as *const f32 as *const c_void,
                gl::STATIC_DRAW,
            );

            // Draw pixels
            gl::DrawElements(
                gl::TRIANGLES,
                2 * 3 * 64 * 32,
                gl::UNSIGNED_INT,
                ptr::null(),
            );
        }

        // Refresh page
        self.window.swap_buffers();
    }
}

unsafe fn compile_shader(shader_src: &str, shader_type: u32) -> u32 {
    let shader = gl::CreateShader(shader_type);
    let c_pointer = CString::new(shader_src.as_bytes()).unwrap();
    gl::ShaderSource(shader, 1, &c_pointer.as_ptr(), ptr::null());
    gl::CompileShader(shader);
    // Check for success
    let mut success = gl::FALSE as GLint;
    let mut info_log = Vec::with_capacity(512);
    info_log.set_len(512 - 1);
    gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut success);

    if success != gl::TRUE as GLint {
        gl::GetShaderInfoLog(
            shader,
            512,
            ptr::null_mut(),
            info_log.as_mut_ptr() as *mut GLchar,
        );
        panic!("Error compiling shader! {:?}", String::from_utf8(info_log));
    }

    return shader;
}

unsafe fn create_program(shaders: Vec<u32>) -> u32 {
    let program = gl::CreateProgram();
    gl::AttachShader(program, shaders[0]);
    gl::AttachShader(program, shaders[1]);
    // for shader in shaders {
    //     gl::AttachShader(program, shader);
    // }
    gl::LinkProgram(program);

    // Check for success
    let mut success = gl::FALSE as GLint;
    gl::GetProgramiv(program, gl::LINK_STATUS, &mut success);

    if success != gl::TRUE as GLint {
        let mut info_log = Vec::with_capacity(512);
        info_log.set_len(512 - 1);
        gl::GetProgramInfoLog(
            program,
            512,
            ptr::null_mut(),
            info_log.as_mut_ptr() as *mut GLchar,
        );
        panic!(
            "Error creating program! {}",
            String::from_utf8(info_log).unwrap()
        );
    }

    return program;
}