Create separate rendering functions

This commit is contained in:
Dendy 2022-07-22 17:57:51 +02:00
parent d0f444fa13
commit 1d24389a0a
2 changed files with 43 additions and 24 deletions

View File

@ -7,6 +7,7 @@ window: sdl.Window,
context: sdl.gl.Context, context: sdl.gl.Context,
color_loc: u32, color_loc: u32,
buffer: gl.Buffer, buffer: gl.Buffer,
color: [4]f32,
pub fn init() !Self { pub fn init() !Self {
try sdl.init(.{ .video = true, .audio = true, .events = true }); try sdl.init(.{ .video = true, .audio = true, .events = true });
@ -49,18 +50,8 @@ pub fn init() !Self {
var vertex_array = gl.VertexArray.gen(); var vertex_array = gl.VertexArray.gen();
vertex_array.bind(); vertex_array.bind();
const vertex_buffer = [_]f32{
-1.0, -1.0, 0.0,
-1.0, 1.0, 0.0,
0.0, 1.0, 0.0,
1.0, 1.0, 0.0,
0.0, -1.0, 0.0,
1.0, -1.0, 0.0,
};
const buf = gl.Buffer.gen(); const buf = gl.Buffer.gen();
buf.bind(.array_buffer); buf.bind(.array_buffer);
buf.data(f32, &vertex_buffer, .static_draw);
gl.clearColor(0.91, 0.97, 1.00, 1.00); gl.clearColor(0.91, 0.97, 1.00, 1.00);
@ -69,25 +60,14 @@ pub fn init() !Self {
.context = ctx, .context = ctx,
.color_loc = color_loc, .color_loc = color_loc,
.buffer = buf, .buffer = buf,
.color = .{0,0,0,0}
}; };
} }
pub fn render(self: Self) void { pub fn render(self: Self) void {
gl.clear(.{ .color = true });
gl.enableVertexAttribArray(0);
self.buffer.bind(.array_buffer);
gl.vertexAttribPointer(0, 3, .float, false, 0, 0);
gl.uniform4f(self.color_loc, 0.45, 0.21, 0.70, 1);
gl.drawArrays(.triangles, 0, 3);
gl.uniform4f(self.color_loc, 0.2, 0.5, 1.0, 1);
gl.drawArrays(.triangles, 3, 3);
gl.disableVertexAttribArray(0);
sdl.gl.swapWindow(self.window); sdl.gl.swapWindow(self.window);
gl.clear(.{ .color = true });
} }
pub fn deinit(self: Self) void { pub fn deinit(self: Self) void {
@ -95,3 +75,39 @@ pub fn deinit(self: Self) void {
self.window.destroy(); self.window.destroy();
sdl.gl.deleteContext(self.context); sdl.gl.deleteContext(self.context);
} }
pub fn setColor(self: *Self, r: u8, g: u32, b: u32, a: u32) void {
self.*.color = .{
@intToFloat(f32, r)/255.0,
@intToFloat(f32, g)/255.0,
@intToFloat(f32, b)/255.0,
@intToFloat(f32, a)/255.0,
};
}
pub fn drawRectangle(self: *Self, x: u32, y: u32, w: u32, h: u32) void {
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 3, .float, false, 0, 0);
const vertex_buffer = [_]f32{
-1.0, -1.0, 0.0,
-1.0, 1.0, 0.0,
0.0, 1.0, 0.0,
1.0, 1.0, 0.0,
0.0, -1.0, 0.0,
1.0, -1.0, 0.0,
};
self.buffer.data(f32, &vertex_buffer, .static_draw);
gl.uniform4fv(self.color_loc, &.{ self.color });
gl.drawArrays(.triangles, 0, 3);
gl.drawArrays(.triangles, 3, 3);
gl.disableVertexAttribArray(0);
_ = self;
_ = x;
_ = y;
_ = w;
_ = h;
}

View File

@ -26,6 +26,9 @@ pub fn main() !void {
} }
} }
renderer.setColor(255, 127, 0, 255);
renderer.drawRectangle(20, 20, 20, 20);
renderer.render(); renderer.render();
//current_state = switch (current_state) { //current_state = switch (current_state) {