diff --git a/README.md b/README.md index 3b2afc1..02d1a50 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,8 @@ - [x] FPS Camera - [ ] Quarternions for rotations - [x] Reading OBJ models +- [x] Dumping raw obj files +- [x] Loading raw obj files, big startup speedup! - [ ] Reading more OBJ formats - [x] Reading OBJ .mtl files - [x] Loading materials @@ -41,7 +43,7 @@ - [ ] Outlines - [ ] Lightning - [ ] Proper normal interpolation - * https://hero.handmade.network/episode/code/day101/#105 + * `https://hero.handmade.network/episode/code/day101/#105 - [ ] Phong - [x] diffuse - [x] ambient @@ -76,6 +78,12 @@ - [x] Simple scatter plot +### Urgent: + +- [ ] Simplify the code, especially for the 2d routines +- [x] Asset processor as second program + + ## Clipping There are 3 clipping stages, 2 clipping stages in 3D space against zfar and znear and 1 clipping diff --git a/assets.cpp b/assets.cpp index 7f0a86e..72f8d71 100644 --- a/assets.cpp +++ b/assets.cpp @@ -21,11 +21,11 @@ struct Obj_Token { }; }; -function Bitmap +function Bitmap load_image(String path) { Scratch scratch; String file = os_read_file(scratch, path); - + int x, y, n; unsigned char* data = stbi_load_from_memory(file.str, file.len, &x, &y, &n, 4); Bitmap result = { (U32*)data, x, y }; @@ -40,7 +40,7 @@ load_image(String path) { color.b *= color.a; *p++ = vec4_to_u32abgr(color); } - } + } } #endif return result; @@ -50,7 +50,7 @@ function Obj_Token next_token_raw(char** data) { Obj_Token result = {}; result.s = *data; *data += 1; - + if (is_alphabetic(*result.s)) { result.type = Obj_Token_Type::word; while (!is_whitespace(**data)) { @@ -81,7 +81,7 @@ function Obj_Token next_token_raw(char** data) { else if (*result.s >= '!') { result.type = (Obj_Token_Type)*result.s; } - + return result; } @@ -110,12 +110,12 @@ function void debug_expect_raw(char** data, Obj_Token_Type type) { assert(t.type == type); } -function void +function void parse_mtl(Obj* obj, String path_obj_folder, String mtl_file) { Scratch scratch; char *data = (char *)mtl_file.str; Obj_Material *m = 0; - + for (;;) { Obj_Token token = next_token(&data); if (token.type == Obj_Token_Type::end) break; @@ -126,11 +126,11 @@ parse_mtl(Obj* obj, String path_obj_folder, String mtl_file) { m->name_len = clamp_top(token.len, 64); memory_copy(m->name, token.s8.str, m->name_len); } - + else if (string_compare(token.s8, "Ns"_s)) { m->shininess = expect_number(&data); } - + else if (string_compare(token.s8, "Ka"_s)) { m->ambient_color.x = expect_number(&data); m->ambient_color.y = expect_number(&data); @@ -141,7 +141,7 @@ parse_mtl(Obj* obj, String path_obj_folder, String mtl_file) { m->diffuse_color.y = expect_number(&data); m->diffuse_color.z = expect_number(&data); } - + else if (string_compare(token.s8, "Ks"_s)) { m->specular_color.x = expect_number(&data); m->specular_color.y = expect_number(&data); @@ -150,32 +150,32 @@ parse_mtl(Obj* obj, String path_obj_folder, String mtl_file) { else if (string_compare(token.s8, "Ni"_s)) { m->optical_density = expect_number(&data); } - + else if (string_compare(token.s8, "d"_s)) { m->non_transparency = expect_number(&data); } else if (string_compare(token.s8, "illum"_s)) { m->illumination_model = (S32)expect_number(&data); } - + else if (string_compare(token.s8, "map_Kd"_s)) { Obj_Token t = next_token(&data); String path = string_fmt(scratch, "%Q/%Q\0", path_obj_folder, t.s8); m->texture_diffuse = load_image(path); } - + else if (string_compare(token.s8, "map_Ka"_s)) { Obj_Token t = next_token(&data); String path = string_fmt(scratch, "%Q/%Q\0", path_obj_folder, t.s8); m->texture_ambient = load_image(path); } - + else if (string_compare(token.s8, "map_d"_s)) { Obj_Token t = next_token(&data); String path = string_fmt(scratch, "%Q/%Q\0", path_obj_folder, t.s8); m->texture_dissolve = load_image(path); } - + else if (string_compare(token.s8, "map_Disp"_s)) { Obj_Token t = next_token(&data); String path = string_fmt(scratch, "%Q/%Q\0", path_obj_folder, t.s8); @@ -185,7 +185,7 @@ parse_mtl(Obj* obj, String path_obj_folder, String mtl_file) { } } -function Obj +function Obj parse(Allocator *allocator, char* data, String path_obj_folder) { Set_Allocator(allocator); Scratch mtl_scratch; @@ -196,11 +196,11 @@ parse(Allocator *allocator, char* data, String path_obj_folder) { //result.mesh.init(allocator, 64); //result.materials.init(allocator, 64); int smoothing = 0; - + Obj_Mesh *mesh = result.mesh.push_empty_zero(); //mesh->indices.init(allocator); int material_id = -1; - + S64 debug_i = 0; for (;;debug_i++){ Obj_Token token = next_token(&data); @@ -213,14 +213,14 @@ parse(Allocator *allocator, char* data, String path_obj_folder) { vertex->z = (float)expect_number(&data); debug_expect_raw(&data, Obj_Token_Type::whitespace); } - + else if (string_compare(token.s8, "vt"_s)) { Vec2 *tex = result.texture_coordinates.push_empty_zero(); tex->x = (float)expect_number(&data); tex->y = (float)expect_number(&data); debug_expect_raw(&data, Obj_Token_Type::whitespace); } - + else if (string_compare(token.s8, "vn"_s)) { Vec3 *norm = result.normals.push_empty_zero(); norm->x = (float)expect_number(&data); @@ -228,16 +228,16 @@ parse(Allocator *allocator, char* data, String path_obj_folder) { norm->z = (float)expect_number(&data); debug_expect_raw(&data, Obj_Token_Type::whitespace); } - + else if (string_compare(token.s8, "mtllib"_s)) { Obj_Token t = next_token(&data); String path = string_fmt(mtl_scratch, "%Q/%Q", path_obj_folder, t.s8); String mtl_file = os_read_file(mtl_scratch, path); if(mtl_file.str) { - parse_mtl(&result, path_obj_folder, mtl_file); + parse_mtl(&result, path_obj_folder, mtl_file); } } - + else if (string_compare(token.s8, "usemtl"_s)) { Obj_Token t = next_token(&data); assert(t.type == Obj_Token_Type::word); @@ -249,7 +249,7 @@ parse(Allocator *allocator, char* data, String path_obj_folder) { } } } - + else if (string_compare(token.s8, "o"_s)) { Obj_Token t = next_token(&data); assert(t.type == Obj_Token_Type::word); @@ -261,7 +261,7 @@ parse(Allocator *allocator, char* data, String path_obj_folder) { memory_copy(mesh->name, t.s, len); } } - + else if (string_compare(token.s8, "s"_s)) { Obj_Token t = next_token(&data); if (t.type == Obj_Token_Type::number) { @@ -277,14 +277,14 @@ parse(Allocator *allocator, char* data, String path_obj_folder) { } else invalid_codepath; } - + } - + else if (string_compare(token.s8, "g"_s)) { Obj_Token t = next_token(&data); assert(t.type == Obj_Token_Type::word); } - + else if (string_compare(token.s8, "f"_s)) { Obj_Index *i = mesh->indices.push_empty_zero(); i->smoothing_group_id = smoothing; @@ -294,13 +294,13 @@ parse(Allocator *allocator, char* data, String path_obj_folder) { i->tex[0] = (int)expect_number(&data); expect_token(&data, '/'); i->normal[0] = (int)expect_number(&data); - + i->vertex[1] = (int)expect_number(&data); expect_token(&data, '/'); i->tex[1] = (int)expect_number(&data); expect_token(&data, '/'); i->normal[1] = (int)expect_number(&data); - + i->vertex[2] = (int)expect_number(&data); expect_token(&data, '/'); i->tex[2] = (int)expect_number(&data); @@ -313,19 +313,19 @@ parse(Allocator *allocator, char* data, String path_obj_folder) { return result; } -function Obj +function Obj load_obj(Allocator *arena, String file) { Scratch scratch; String data = os_read_file(scratch, file); assert(data.str); - + String path = string_chop_last_slash(file); Obj result = parse(arena, (char *)data.str, path); result.name = file; return result; } -template void +template void dump_array(String_Builder *sb, Array *arr){ sb->append_data(arr, sizeof(*arr)); sb->append_data(arr->data, sizeof(T)*arr->len); @@ -336,6 +336,7 @@ dump_bitmap_image(String_Builder *sb, Bitmap *bm){ sb->append_data(bm->pixels, sizeof(U32)*bm->x*bm->y); } + function B32 _os_write_file(String file, String data, B32 append = false) { B32 result = false; @@ -345,7 +346,7 @@ _os_write_file(String file, String data, B32 append = false) { access = FILE_APPEND_DATA; creation_disposition = OPEN_ALWAYS; } - + // @Todo(Krzosa): Unicode HANDLE handle = CreateFileA((const char *)file.str, access, 0, NULL, creation_disposition, FILE_ATTRIBUTE_NORMAL, NULL); if (handle != INVALID_HANDLE_VALUE) { @@ -359,19 +360,19 @@ _os_write_file(String file, String data, B32 append = false) { else result = true; } CloseHandle(handle); - } + } else { log_error("File not found when trying to write: %Q", file); } - + return result; } -function B32 -os_write_file(String file, String data) { +function B32 +os_write_file2(String file, String data) { return _os_write_file(file, data, false); } -function B32 +function B32 os_append_file(String file, String data) { return _os_write_file(file, data, true); } @@ -380,24 +381,24 @@ function void dump_obj_to_file(Obj *obj, String out_name){ obj->vertices.allocator = 0; obj->vertices.cap = obj->vertices.len; - + obj->texture_coordinates.allocator = 0; obj->texture_coordinates.cap = obj->texture_coordinates.len; - + obj->normals.allocator = 0; obj->normals.cap = obj->normals.len; - + obj->mesh.allocator = 0; obj->mesh.cap = obj->mesh.len; - + obj->materials.allocator = 0; obj->materials.cap = obj->materials.len; - - Iter(obj->mesh){ - it->indices.allocator = 0; - it->indices.cap = it->indices.len; + + For(obj->mesh){ + it.indices.allocator = 0; + it.indices.cap = it.indices.len; } - + Scratch arena; String_Builder sb = string_builder_make(arena, mib(4)); sb.append_data(obj, sizeof(Obj)); @@ -407,21 +408,21 @@ dump_obj_to_file(Obj *obj, String out_name){ sb.append_data(obj->normals.data, obj->normals.len*sizeof(Vec3)); sb.append_data(obj->mesh.data, obj->mesh.len*sizeof(Obj_Mesh)); sb.append_data(obj->materials.data, obj->materials.len*sizeof(Obj_Material)); - - Iter(obj->mesh){ - sb.append_data(it->indices.data, sizeof(Obj_Index)*it->indices.len); + + For(obj->mesh){ + sb.append_data(it.indices.data, sizeof(Obj_Index)*it.indices.len); } - - Iter(obj->materials){ - sb.append_data(it, sizeof(Obj_Material)); - dump_bitmap_image(&sb, &it->texture_ambient); - dump_bitmap_image(&sb, &it->texture_diffuse); - dump_bitmap_image(&sb, &it->texture_dissolve); - dump_bitmap_image(&sb, &it->texture_displacement); + + For(obj->materials){ + sb.append_data(&it, sizeof(Obj_Material)); + dump_bitmap_image(&sb, &it.texture_ambient); + dump_bitmap_image(&sb, &it.texture_diffuse); + dump_bitmap_image(&sb, &it.texture_dissolve); + dump_bitmap_image(&sb, &it.texture_displacement); } - + String result = string_flatten(arena, &sb); - os_write_file(out_name, result); + os_write_file2(out_name, result); } global FILE *output_file; @@ -429,21 +430,21 @@ global FILE *output_file; function void asset_log(Log_Kind kind, String string, char *file, int line){ if(!output_file) { - + } fprintf(output_file, "%.*s", string_expand(string)); } -int +int main(int argc, char **argv){ output_file = fopen("asset.log.txt", "a"); thread_ctx.log_proc = asset_log; - + Obj sponza_obj = load_obj(&os_process_heap, "assets/sponza/sponza.obj"_s); dump_obj_to_file(&sponza_obj, "sponza.bin"_s); - + Obj plane_obj = load_obj(&pernament_arena, "assets/f22.obj"_s); - + // Add brick texture as main texture Scratch scratch; Set_Allocator(scratch); @@ -451,11 +452,11 @@ main(int argc, char **argv){ material.texture_ambient = load_image("assets/bricksx64.png"_s); plane_obj.materials.add(material); For(plane_obj.mesh){ - IFor(it->indices, jt, j){ - jt->material_id = 0; + For_Named(it.indices, jt){ + jt.material_id = 0; } } - + dump_obj_to_file(&plane_obj, "plane.bin"_s); fclose(output_file); } \ No newline at end of file diff --git a/build.bat b/build.bat index 45ca401..7cde64f 100644 --- a/build.bat +++ b/build.bat @@ -1,8 +1,7 @@ @echo off -rem clang assets.cpp -Wall -Wno-unused-function -Wno-missing-braces -fno-exceptions -fdiagnostics-absolute-paths -g -I".." -o assets.exe -Wl,user32.lib - -rem assets.exe +clang assets.cpp -Wall -Wno-unused-function -Wno-missing-braces -fno-exceptions -fdiagnostics-absolute-paths -g -I".." -o assets.exe -Wl,user32.lib +assets.exe clang main.cpp -Wall -Wno-unused-function -Wno-missing-braces -fno-exceptions -fdiagnostics-absolute-paths -g -I".." -o main.exe -Wl,user32.lib \ No newline at end of file diff --git a/main.cpp b/main.cpp index 1be6f92..d2337e8 100644 --- a/main.cpp +++ b/main.cpp @@ -1,7 +1,7 @@ ///////////////////////////////////////////////////////////////////////////////////// -/// +/// /// ### Things to do: -/// +/// /// - [x] Drawing triangles /// - [x] Drawing cubes and lines for testing /// - [x] Y up coordinate system, left handed @@ -14,7 +14,7 @@ /// - [x] Fix the gaps between triangles (it also improved look of triangle edges) /// - [ ] Perspective matrix vs simple perspective /// - [x] Perspective correct interpolation -/// - [x] Depth buffer +/// - [x] Depth buffer /// - [x] Gamma correct blending - converting to almost linear space /// - [x] Alpha blending /// - [x] Premultiplied alpha @@ -25,7 +25,7 @@ /// - [x] FPS Camera /// - [ ] Quarternions for rotations /// - [x] Reading OBJ models -/// - [x] Dumping raw obj files +/// - [x] Dumping raw obj files /// - [x] Loading raw obj files, big startup speedup! /// - [ ] Reading more OBJ formats /// - [x] Reading OBJ .mtl files @@ -35,7 +35,7 @@ /// - [x] Fix sponza uv coordinates - the issue was uv > 1 and uv < 0 /// - [x] Clipping /// - [x] Triagnle rectangle bound clipping -/// - [x] A way of culling Z out triangles +/// - [x] A way of culling Z out triangles /// - [x] Simple test z clipping /// - [x] Maybe should clip a triangle on znear zfar plane? /// - [x] Maybe should clip out triangles that are fully z out before draw_triangle @@ -76,10 +76,10 @@ /// - [x] Gamma correct alpha blending for rectangles and bitmaps /// - [ ] Plotting of profile data /// - [x] Simple scatter plot -/// -/// -/// ### Urgent: -/// +/// +/// +/// ### Urgent: +/// /// - [ ] Simplify the code, especially for the 2d routines /// - [x] Asset processor as second program /// @@ -100,7 +100,7 @@ struct Render { Mat4 camera; Mat4 projection; Mat4 transform; - + Vec3 camera_pos; Vec3 camera_direction; Vec3 camera_forward_velocity; @@ -150,12 +150,12 @@ void draw_rect(Bitmap* dst, F32 X, F32 Y, F32 w, F32 h, Vec4 color) { int max_y = (int)(min(Y + h, (F32)dst->y) + 0.5f); int min_x = (int)(max(0.f, X) + 0.5f); int min_y = (int)(max(0.f, Y) + 0.5f); - + color.rgb *= color.a; color = srgb_to_almost_linear(color); for (int y = min_y; y < max_y; y++) { for (int x = min_x; x < max_x; x++) { - U32 *dst_pixel = dst->pixels + (x + y * dst->x); + U32 *dst_pixel = dst->pixels + (x + y * dst->x); Vec4 dstc = srgb_to_almost_linear(vec4abgr(*dst_pixel)); dstc = premultiplied_alpha(dstc, color); U32 color32 = vec4_to_u32abgr(almost_linear_to_srgb(dstc)); @@ -164,79 +164,80 @@ void draw_rect(Bitmap* dst, F32 X, F32 Y, F32 w, F32 h, Vec4 color) { } } -function -void draw_bitmap(Bitmap* dst, Bitmap* src, Vec2 pos, Vec2 size=vec2(F32MAX, F32MAX)) { +function void +draw_bitmap(Bitmap *dst, Bitmap *src, Vec2 pos){ S64 minx = (S64)(pos.x + 0.5); S64 miny = (S64)(pos.y + 0.5); - - if (size.x == F32MAX || size.y == F32MAX) { - S64 maxx = minx + src->x; - S64 maxy = miny + src->y; - S64 offsetx = 0; - S64 offsety = 0; - - if (maxx > dst->x) { - maxx = dst->x; - } - if (maxy > dst->y) { - maxy = dst->y; - } - if (minx < 0) { - offsetx = -minx; - minx = 0; - } - if (miny < 0) { - offsety = -miny; - miny = 0; - } - for (S64 y = miny; y < maxy; y++) { - for (S64 x = minx; x < maxx; x++) { - S64 tx = x - minx + offsetx; - S64 ty = y - miny + offsety; - U32 *dst_pixel = dst->pixels + (x + y * dst->x); - U32 *pixel = src->pixels + (tx + ty * src->x); - Vec4 result_color = srgb_to_almost_linear(vec4abgr(*pixel)); - Vec4 dst_color = srgb_to_almost_linear(vec4abgr(*dst_pixel)); - result_color = premultiplied_alpha(dst_color, result_color); - result_color = almost_linear_to_srgb(result_color); - U32 color32 = vec4_to_u32abgr(result_color); - *dst_pixel = color32; - } + S64 maxx = minx + src->x; + S64 maxy = miny + src->y; + S64 offsetx = 0; + S64 offsety = 0; + + if (maxx > dst->x) { + maxx = dst->x; + } + if (maxy > dst->y) { + maxy = dst->y; + } + if (minx < 0) { + offsetx = -minx; + minx = 0; + } + if (miny < 0) { + offsety = -miny; + miny = 0; + } + for (S64 y = miny; y < maxy; y++) { + for (S64 x = minx; x < maxx; x++) { + S64 tx = x - minx + offsetx; + S64 ty = y - miny + offsety; + U32 *dst_pixel = dst->pixels + (x + y * dst->x); + U32 *pixel = src->pixels + (tx + ty * src->x); + Vec4 result_color = srgb_to_almost_linear(vec4abgr(*pixel)); + Vec4 dst_color = srgb_to_almost_linear(vec4abgr(*dst_pixel)); + result_color = premultiplied_alpha(dst_color, result_color); + result_color = almost_linear_to_srgb(result_color); + U32 color32 = vec4_to_u32abgr(result_color); + *dst_pixel = color32; } } - else { - S64 maxx = minx + (S64)(size.x + 0.5f); - S64 maxy = miny + (S64)(size.y + 0.5f); - S64 offsetx = 0; - S64 offsety = 0; - maxx = clamp_top(maxx, (S64)dst->x); - maxy = clamp_top(maxy, (S64)dst->y); - if (minx < 0) { - offsetx = -minx; - minx = 0; - } - if (miny < 0) { - offsety = -miny; - miny = 0; - } - - F32 distx = (F32)(maxx - minx); - F32 disty = (F32)(maxy - miny); - for (S64 y = miny; y < maxy; y++) { - for (S64 x = minx; x < maxx; x++) { - F32 u = (F32)(x - minx) / distx; - F32 v = (F32)(y - miny) / disty; - S64 tx = (S64)(u * src->x + 0.5f); - S64 ty = (S64)(v * src->y + 0.5f); - U32 *dst_pixel = dst->pixels + (x + y * dst->x); - U32 *pixel = src->pixels + (tx + ty * src->x); - Vec4 result_color = srgb_to_almost_linear(vec4abgr(*pixel)); - Vec4 dst_color = srgb_to_almost_linear(vec4abgr(*dst_pixel)); - result_color = premultiplied_alpha(dst_color, result_color); - result_color = almost_linear_to_srgb(result_color); - U32 color32 = vec4_to_u32abgr(result_color); - *dst_pixel = color32; - } +} + +function +void draw_bitmap(Bitmap* dst, Bitmap* src, Vec2 pos, Vec2 size) { + S64 minx = (S64)(pos.x + 0.5); + S64 miny = (S64)(pos.y + 0.5); + S64 maxx = minx + (S64)(size.x + 0.5f); + S64 maxy = miny + (S64)(size.y + 0.5f); + S64 offsetx = 0; + S64 offsety = 0; + maxx = clamp_top(maxx, (S64)dst->x); + maxy = clamp_top(maxy, (S64)dst->y); + if (minx < 0) { + offsetx = -minx; + minx = 0; + } + if (miny < 0) { + offsety = -miny; + miny = 0; + } + + F32 distx = (F32)(maxx - minx); + F32 disty = (F32)(maxy - miny); + for (S64 y = miny; y < maxy; y++) { + for (S64 x = minx; x < maxx; x++) { + F32 u = (F32)(x - minx) / distx; + F32 v = (F32)(y - miny) / disty; + S64 tx = (S64)(u * src->x + 0.5f); + S64 ty = (S64)(v * src->y + 0.5f); + U32 *dst_pixel = dst->pixels + (x + y * dst->x); + U32 *pixel = src->pixels + (tx + ty * src->x); + Vec4 result_color = srgb_to_almost_linear(vec4abgr(*pixel)); + Vec4 dst_color = srgb_to_almost_linear(vec4abgr(*dst_pixel)); + result_color = premultiplied_alpha(dst_color, result_color); + result_color = almost_linear_to_srgb(result_color); + U32 color32 = vec4_to_u32abgr(result_color); + *dst_pixel = color32; } } } @@ -282,7 +283,7 @@ F32 edge_function(Vec4 vecp0, Vec4 vecp1, Vec4 p) { return result; } -function +function void draw_triangle_nearest(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 light_direction, Vec4 p0, Vec4 p1, Vec4 p2, Vec2 tex0, Vec2 tex1, Vec2 tex2, @@ -296,23 +297,23 @@ void draw_triangle_nearest(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 lig S64 min_y = (S64)max(0.f, floor(min_y1)); S64 max_x = (S64)min((F32)dst->x, ceil(max_x1)); S64 max_y = (S64)min((F32)dst->y, ceil(max_y1)); - + F32 dy10 = (p1.y - p0.y); F32 dy21 = (p2.y - p1.y); F32 dy02 = (p0.y - p2.y); - + F32 dx10 = (p1.x - p0.x); F32 dx21 = (p2.x - p1.x); F32 dx02 = (p0.x - p2.x); - + F32 C0 = dy10 * (p0.x) - dx10 * (p0.y); F32 C1 = dy21 * (p1.x) - dx21 * (p1.y); F32 C2 = dy02 * (p2.x) - dx02 * (p2.y); - + F32 Cy0 = dy10 * min_x - dx10 * min_y - C0; F32 Cy1 = dy21 * min_x - dx21 * min_y - C1; F32 Cy2 = dy02 * min_x - dx02 * min_y - C2; - + U32 *destination = dst->pixels + dst->x*min_y; F32 area = (p1.y - p0.y) * (p2.x - p0.x) - (p1.x - p0.x) * (p2.y - p0.y); for (S64 y = min_y; y < max_y; y++) { @@ -324,7 +325,7 @@ void draw_triangle_nearest(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 lig F32 w1 = Cx1 / area; F32 w2 = Cx2 / area; F32 w3 = Cx0 / area; - + // @Note: We could do: interpolated_w = 1.f / interpolated_w to get proper depth // but why waste an instruction, the smaller the depth value the farther the object F32 interpolated_w = (1.f / p0.w) * w1 + (1.f / p1.w) * w2 + (1.f / p2.w) * w3; @@ -334,7 +335,7 @@ void draw_triangle_nearest(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 lig F32 invw0 = (w1 / p0.w); F32 invw1 = (w2 / p1.w); F32 invw2 = (w3 / p2.w); - + Vec3 norm = (norm0 * invw0 + norm1 * invw1 + norm2 * invw2) / interpolated_w; F32 u = tex0.x * invw0 + tex1.x * invw1 + tex2.x * invw2; F32 v = tex0.y * invw0 + tex1.y * invw1 + tex2.y * invw2; @@ -353,7 +354,7 @@ void draw_triangle_nearest(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 lig // Origin UV (0,0) is in bottom left U32 *dst_pixel = destination + x; U32 *pixel = src->pixels + (ui + (src->y - 1ll - vi) * src->x); - + #if PREMULTIPLIED_ALPHA_BLENDING Vec4 result_color; { U32 c = *pixel; @@ -364,9 +365,9 @@ void draw_triangle_nearest(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 lig r*=r; g*=g; b*=b; - result_color = { r,g,b,a }; + result_color = { r,g,b,a }; } - + Vec4 dst_color; { U32 c = *dst_pixel; F32 a = ((c & 0xff000000) >> 24) / 255.f; @@ -374,24 +375,24 @@ void draw_triangle_nearest(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 lig F32 g = ((c & 0x0000ff00) >> 8) / 255.f; F32 r = ((c & 0x000000ff) >> 0) / 255.f; r*=r; g*=g; b*=b; - dst_color = { r,g,b,a }; + dst_color = { r,g,b,a }; } - + Vec3 light_color = vec3(0.8,0.8,1); constexpr F32 ambient_strength = 0.1f; { Vec3 ambient = ambient_strength * light_color; Vec3 diffuse = clamp_bot(0.f, -dot(norm, light_direction)) * light_color; result_color.rgb *= (ambient+diffuse); } - - + + result_color = premultiplied_alpha(dst_color, result_color); result_color = almost_linear_to_srgb(result_color); U32 color32 = vec4_to_u32abgr(result_color); #else U32 color32 = *pixel; #endif - + *dst_pixel = color32; } } @@ -404,38 +405,38 @@ void draw_triangle_nearest(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 lig Cy2 -= dx02; destination += dst->x; } - + if(os.frame > 60) PROFILE_END(draw_triangle); } -function +function void draw_triangle_bilinear(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 light_direction, Vec4 p0, Vec4 p1, Vec4 p2, - Vec2 tex0, Vec2 tex1, Vec2 tex2, + Vec2 tex0, Vec2 tex1, Vec2 tex2, Vec3 norm0, Vec3 norm1, Vec3 norm2) { F32 min_x1 = (F32)(min(p0.x, min(p1.x, p2.x))); F32 min_y1 = (F32)(min(p0.y, min(p1.y, p2.y))); F32 max_x1 = (F32)(max(p0.x, max(p1.x, p2.x))); F32 max_y1 = (F32)(max(p0.y, max(p1.y, p2.y))); - + S64 min_x = (S64)clamp_bot(0.f, floor(min_x1)); S64 min_y = (S64)clamp_bot(0.f, floor(min_y1)); S64 max_x = (S64)clamp_top((F32)dst->x, ceil(max_x1)); S64 max_y = (S64)clamp_top((F32)dst->y, ceil(max_y1)); - + F32 area = edge_function(p0, p1, p2); for (S64 y = min_y; y < max_y; y++) { for (S64 x = min_x; x < max_x; x++) { F32 edge0 = edge_function(p0, p1, { (F32)x,(F32)y }); F32 edge1 = edge_function(p1, p2, { (F32)x,(F32)y }); F32 edge2 = edge_function(p2, p0, { (F32)x,(F32)y }); - + if (edge0 >= 0 && edge1 >= 0 && edge2 >= 0) { F32 w1 = edge1 / area; F32 w2 = edge2 / area; F32 w3 = edge0 / area; F32 interpolated_w = (1.f / p0.w) * w1 + (1.f / p1.w) * w2 + (1.f / p2.w) * w3; - + // @Note: We could do: interpolated_w = 1.f / interpolated_w to get proper depth // but why waste an instruction, the smaller the depth value the farther the object F32* depth = depth_buffer + (x + y * dst->x); @@ -444,7 +445,7 @@ void draw_triangle_bilinear(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 li F32 invw0 = (w1 / p0.w); F32 invw1 = (w2 / p1.w); F32 invw2 = (w3 / p2.w); - + Vec3 norm = (norm0 * invw0 + norm1 * invw1 + norm2 * invw2) / interpolated_w; F32 u = tex0.x * invw0 + tex1.x * invw1 + tex2.x * invw2; F32 v = tex0.y * invw0 + tex1.y * invw1 + tex2.y * invw2; @@ -456,7 +457,7 @@ void draw_triangle_bilinear(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 li u = u * (src->x - 1); v = v * (src->y - 1); } - + S64 ui = (S64)(u); S64 vi = (S64)(v); F32 udiff = u - (F32)ui; @@ -464,7 +465,10 @@ void draw_triangle_bilinear(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 li // Origin UV (0,0) is in bottom left U32 *pixel = src->pixels + (ui + (src->y - 1ll - vi) * src->x); U32 *dst_pixel = dst->pixels + (x + y * dst->x); - + +#if 0 + Vec4 result_color = vec4abgr(*pixel); +#else Vec4 pixelx1y1 = vec4abgr(*pixel); Vec4 pixelx2y1 = vec4abgr(*(pixel + 1)); Vec4 pixelx1y2 = vec4abgr(*(pixel - src->x)); @@ -476,20 +480,21 @@ void draw_triangle_bilinear(Bitmap* dst, F32 *depth_buffer, Bitmap *src, Vec3 li Vec4 blendx1 = lerp(pixelx1y1, pixelx2y1, udiff); Vec4 blendx2 = lerp(pixelx1y2, pixelx2y2, udiff); Vec4 result_color = lerp(blendx1, blendx2, vdiff); - +#endif + Vec3 light_color = vec3(0.8,0.8,1); constexpr F32 ambient_strength = 0.1f; { Vec3 ambient = ambient_strength * light_color; Vec3 diffuse = clamp_bot(0.f, -dot(norm, light_direction)) * light_color; result_color.rgb *= (ambient+diffuse); } - + Vec4 dst_color = vec4abgr(*dst_pixel); dst_color = srgb_to_almost_linear(dst_color); result_color = premultiplied_alpha(dst_color, result_color); result_color = almost_linear_to_srgb(result_color); U32 color32 = vec4_to_u32abgr(result_color); - + *dst_pixel = color32; } } @@ -508,9 +513,9 @@ void draw_mesh(Render *r, String scene_name, Obj_Material *materials, Obj_Mesh * // Need to figure out how to accomodate multiple possible formats of input etc. if(material->texture_ambient.pixels) { image = &material->texture_ambient; - } + } } - Vertex vert[] = { + Vertex vert[] = { { vertices[index->vertex[0] - 1], tex_coords[index->tex[0] - 1], @@ -527,26 +532,26 @@ void draw_mesh(Render *r, String scene_name, Obj_Material *materials, Obj_Mesh * normals[index->normal[2] - 1], }, }; - + //@Note: Transform for (int j = 0; j < 3; j++) { vert[j].pos = r->transform * vert[j].pos; } - - + + Vec3 p0_to_camera = r->camera_pos - vert[0].pos; Vec3 p0_to_p1 = vert[1].pos - vert[0].pos; Vec3 p0_to_p2 = vert[2].pos - vert[0].pos; Vec3 normal = normalize(cross(p0_to_p1, p0_to_p2)); Vec3 light_direction = mat4_rotation_x(light_rotation) * vec3(0, 0, 1); - + if (dot(normal, p0_to_camera) > 0) { //@Note: Backface culling - /// ## Clipping - /// - /// There are 3 clipping stages, 2 clipping stages in 3D space against zfar and znear and 1 clipping - /// stage in 2D against left, bottom, right, top(2D image bounds). + /// ## Clipping /// - /// First the triangles get clipped against the zfar plane, + /// There are 3 clipping stages, 2 clipping stages in 3D space against zfar and znear and 1 clipping + /// stage in 2D against left, bottom, right, top(2D image bounds). + /// + /// First the triangles get clipped against the zfar plane, /// if a triangle has even one vertex outside the clipping region, the entire triangle gets cut. /// So far I didn't have problems with that. It simplifies the computations and splitting triangles /// on zfar seems like a waste of power. @@ -554,12 +559,12 @@ void draw_mesh(Render *r, String scene_name, Obj_Material *materials, Obj_Mesh * /// The second clipping stage is znear plane. Triangles get fully and nicely clipped against znear. /// Every time a triangle gets partially outside the clipping region it gets cut to the znear and /// either one or two new triangles get derived from the old one. - /// - /// Last clipping stage is performed in the 2D image space. Every triangle has a corresponding AABB + /// + /// Last clipping stage is performed in the 2D image space. Every triangle has a corresponding AABB /// box. In this box every pixel gets tested to see if it's in the triangle. In this clipping stage /// the box is clipped to the image metrics - 0, 0, width, height. - /// - /// + /// + /// // @Note: Zfar B32 vertex_is_outside = false; Vec3 zfar_normal = vec3(0, 0, -1); @@ -568,27 +573,27 @@ void draw_mesh(Render *r, String scene_name, Obj_Material *materials, Obj_Mesh * // @Note: Camera vert[j].pos = r->camera * vert[j].pos; // @Note: Skip triangle if even one vertex gets outside the clipping plane - if ((dot(zfar_normal, vert[j].pos - zfar_pos) < 0)) { + if ((dot(zfar_normal, vert[j].pos - zfar_pos) < 0)) { vertex_is_outside = true; break; } } - + if (vertex_is_outside) { continue; } - + // @Note: Znear, clip triangles to the near clipping plane Vec3 znear_normal = vec3(0, 0, 1); Vec3 znear_pos = vec3(0, 0, 1.f); - + struct _Vertex { Vec4 pos; Vec2 tex; Vec3 norm; } in[4]; S32 in_count = 0; - + Vertex *prev = vert + 2; Vertex *curr = vert; F32 prev_dot = dot(znear_normal, prev->pos - znear_pos); @@ -609,39 +614,34 @@ void draw_mesh(Render *r, String scene_name, Obj_Material *materials, Obj_Mesh * prev = curr++; prev_dot = curr_dot; } - + if (in_count == 0) { continue; } - + for(S64 j = 0; j < in_count; j++) { //@Note: Perspective in[j].pos = r->projection * in[j].pos; in[j].pos.x = in[j].pos.x / in[j].pos.w; in[j].pos.y = in[j].pos.y / in[j].pos.w; // in[j].pos.z = in[j].pos.z / in[j].pos.w; - + //@Note: To pixel space in[j].pos.x *= r->screen320.x / 2; in[j].pos.y *= r->screen320.y / 2; in[j].pos.x += r->screen320.x / 2; in[j].pos.y += r->screen320.y / 2; } - - - draw_triangle_bilinear(&r->screen320, r->depth320, image, light_direction, in[0].pos, in[1].pos, in[2].pos, in[0].tex, in[1].tex, in[2].tex, in[0].norm, in[1].norm, in[2].norm); + + + draw_triangle_nearest(&r->screen320, r->depth320, image, light_direction, in[0].pos, in[1].pos, in[2].pos, in[0].tex, in[1].tex, in[2].tex, in[0].norm, in[1].norm, in[2].norm); if (in_count > 3) { - draw_triangle_bilinear(&r->screen320, r->depth320, image, light_direction, in[0].pos, in[2].pos, in[3].pos, in[0].tex, in[2].tex, in[3].tex, in[0].norm, in[2].norm, in[3].norm); + draw_triangle_nearest(&r->screen320, r->depth320, image, light_direction, in[0].pos, in[2].pos, in[3].pos, in[0].tex, in[2].tex, in[3].tex, in[0].norm, in[2].norm, in[3].norm); } - -#if 0 - ProfileScope *scope = profile_scopes + ProfileScopeName_draw_triangle; - LOCAL_PERSIST B32 profile_flag; - if (!profile_flag && scope->i > 2000) { - profile_flag = 1; - save_profile_data(scope, scene_name, LIT("draw_triangle")); - } -#endif + + + + } } } @@ -679,7 +679,7 @@ windows_log(Log_Kind kind, String string, char *file, int line){ OutputDebugStringA((char *)string.str); } -int +int main(int argc, char **argv) { thread_ctx.log_proc = windows_log; os.window_size.x = 1280; @@ -687,18 +687,18 @@ main(int argc, char **argv) { os.window_resizable = 1; assert(os_init()); Font font = os_load_font(os.perm_arena, 72, "Arial", 0); - + f22 = load_obj_dump(os.perm_arena, "plane.bin"_s); sponza = load_obj_dump(os.perm_arena, "sponza.bin"_s); scene_callback(); - - int screen_x = 320; - int screen_y = 180; - + + int screen_x = 1280; + int screen_y = 720; + r.camera_pos = {0,0,-2}; r.screen320 = {(U32 *)arena_push_size(os.perm_arena, screen_x*screen_y*sizeof(U32)), screen_x, screen_y}; r.depth320 = (F32 *)arena_push_size(os.perm_arena, sizeof(F32) * screen_x * screen_y); - + String frame_data = {}; UISetup setup[] = { UI_SIGNAL("Change scene"_s, scene_callback), @@ -706,8 +706,8 @@ main(int argc, char **argv) { UI_LABEL(&os.text), }; UI ui = ui_make(setup, buff_cap(setup)); - B32 ui_mouse_lock = true; - + B32 ui_mouse_lock = true; + while (os_game_loop()) { if (ui_mouse_lock == false) { r.camera_yaw.x += os.delta_mouse_pos.x * 0.01f; @@ -744,8 +744,8 @@ main(int argc, char **argv) { *dp++ = -F32MAX; } } - - + + Mat4 camera_rotation = mat4_rotation_y(r.camera_yaw.x) * mat4_rotation_x(r.camera_yaw.y); r.camera_direction = (camera_rotation * vec4(0,0,1,1)).xyz; Vec3 target = r.camera_pos + r.camera_direction; @@ -760,8 +760,8 @@ main(int argc, char **argv) { Vec3* vertices = (Vec3 *)obj->vertices.data; draw_mesh(&r, obj->name, obj->materials.data, mesh+i, vertices, tex_coords, normals); } - - + + // @Note: Draw 320screen to OS screen U32* ptr = os.screen->pixels; for (int y = 0; y < os.screen->y; y++) { @@ -780,7 +780,7 @@ main(int argc, char **argv) { ///////////////////////////////////////////////////////////////////////////////////// /// ### Resources that helped me build the rasterizer (Might be helpful to you too): -/// +/// /// * Algorithm I used for triangle rasterization by Juan Pineda is described in paper called "A Parallel Algorithm for Polygon Rasterization" /// * Casey Muratori's series on making a game from scratch(including a 2D software rasterizer(episode ~82) and 3d gpu renderer): https://hero.handmade.network/episode/code# /// * Fabian Giessen's "Optimizing Software Occlusion Culling": https://fgiesen.wordpress.com/2013/02/17/optimizing-sw-occlusion-culling-index/ diff --git a/obj.cpp b/obj.cpp index 8870ff4..ca1d47b 100644 --- a/obj.cpp +++ b/obj.cpp @@ -27,7 +27,7 @@ struct Obj_Material { F32 transparency; // Tr F32 optical_density; // Ni F32 shininess; // Ns - S32 illumination_model; // illum + S32 illumination_model; // illum Vec3 ambient_color; // Ka Vec3 diffuse_color; // Kd Vec3 specular_color; // Ks @@ -60,27 +60,27 @@ stream_read(Stream *s, SizeU size){ function Obj * load_obj_dump(Allocator *allocator, String filename){ String string = os_read_file(allocator, filename); - - Obj *obj = (Obj *)string.str; - Stream stream = {(U8 *)(obj+1), string.str + string.len}; + + Stream stream = {string.str, string.str + string.len}; + Obj *obj = stream_read_struct(&stream, Obj); obj->name.str = stream_read_array(&stream, U8, obj->name.len); obj->vertices.data = stream_read_array(&stream, Vec3, obj->vertices.len); obj->texture_coordinates.data = stream_read_array(&stream, Vec2, obj->texture_coordinates.len); obj->normals.data = stream_read_array(&stream, Vec3, obj->normals.len); obj->mesh.data = stream_read_array(&stream, Obj_Mesh, obj->mesh.len); obj->materials.data = stream_read_array(&stream, Obj_Material, obj->materials.len); - - Iter(obj->mesh){ - it->indices.data = stream_read_array(&stream, Obj_Index, it->indices.len); + + For(obj->mesh){ + it.indices.data = stream_read_array(&stream, Obj_Index, it.indices.len); } - - Iter(obj->materials){ - it->texture_ambient.pixels = stream_read_array(&stream, U32, it->texture_ambient.x*it->texture_ambient.y); - it->texture_diffuse.pixels = stream_read_array(&stream, U32, it->texture_diffuse.x*it->texture_diffuse.y); - it->texture_dissolve.pixels = stream_read_array(&stream, U32, it->texture_dissolve.x*it->texture_dissolve.y); - it->texture_displacement.pixels = stream_read_array(&stream, U32, it->texture_displacement.x*it->texture_displacement.y); + + For(obj->materials){ + it.texture_ambient.pixels = stream_read_array(&stream, U32, it.texture_ambient.x*it.texture_ambient.y); + it.texture_diffuse.pixels = stream_read_array(&stream, U32, it.texture_diffuse.x*it.texture_diffuse.y); + it.texture_dissolve.pixels = stream_read_array(&stream, U32, it.texture_dissolve.x*it.texture_dissolve.y); + it.texture_displacement.pixels = stream_read_array(&stream, U32, it.texture_displacement.x*it.texture_displacement.y); } - + return obj; } diff --git a/profile.cpp b/profile.cpp index 32b153d..bed7862 100644 --- a/profile.cpp +++ b/profile.cpp @@ -21,33 +21,3 @@ _profile_scope->samples[_profile_scope->i] = __rdtsc() - _profile_scope->samples _profile_scope->i = (_profile_scope->i + 1) % 5096; \ }while (0) - -function void save_profile_data(ProfileScope *scope, S8 scenario_name, S8 scope_name) { - /*for (S64 si = 1; si < scope->i; si++) { - for (S64 sj = 1; sj < scope->i; sj++) { - if (scope->samples[sj] < scope->samples[sj - 1]) { - F64 temp = scope->samples[sj]; - scope->samples[sj] = scope->samples[sj-1]; - scope->samples[sj-1] = temp; - } - } - }*/ - - /* - Scratch scratch; - scenario_name = string_chop_last_period(scenario_name); - scenario_name = string_skip_to_last_slash(scenario_name); - U8 *string_pointer = string_begin(scratch); - string_fmt(scratch, "%s %s\n", build_name, scenario_name); - S64 one_past_last = scope->i; - for (S64 si = 0; si < one_past_last; si++) { - string_fmt(scratch, "%u\n", scope->samples[si]); - } - - S8 data = string_end(scratch, string_pointer); - Date date = os_date(); - os_make_dir(LIT("stats")); - S8 name = string_fmt(scratch, "stats/%s_%s_%s_%u_%u_%u_%u_%u_%u.txt", scope_name, build_name, scenario_name, date.year, date.month, date.day, date.hour, date.minute, date.second); - os_append_file(name, data); - */ -} \ No newline at end of file diff --git a/ui.cpp b/ui.cpp index 07c2d4b..cfbea66 100644 --- a/ui.cpp +++ b/ui.cpp @@ -35,13 +35,13 @@ struct UIWidget { UIWidget *prev; UIWidget *first_child; UIWidget *last_child; - + String text; Vec2 size; S32 option_max; union { - Bitmap *image; - B32 *b32; + Bitmap *image; + B32 *b32; String *label; S32 *option; UISignalCallback *signal_callback; @@ -50,13 +50,13 @@ struct UIWidget { struct UI : UIWidget { Arena arena; - + UIWidget *hot; UIWidget *active; }; function UIWidget *ui_new_widget(Allocator *arena, UIWidgetKind kind) { - UIWidget *result = exp_alloc_type(arena, UIWidget); + UIWidget *result = exp_alloc_type(arena, UIWidget, AF_ZeroMemory); result->kind = kind; return result; } @@ -74,7 +74,7 @@ function UIWidget *ui_push_child(Arena *arena, UIWidget *widget, UIWidgetKind ki function UIWidget *ui_push_image(Arena *arena, UIWidget *widget, Bitmap *img) { UIWidget *result = ui_push_child(arena, widget, UIWidgetKind_Image); result->ptr.image = img; - + F32 ratio = (F32)result->ptr.image->x / (F32)result->ptr.image->y; result->size.y = 64; result->size.x = 64 * ratio; @@ -148,7 +148,7 @@ function B32 ui_mouse_test(UI *ui, UIWidget *w, Vec4 rect) { else if (w == ui->hot) { ui->hot = 0; } - + if (os.key[Key_MouseLeft].released) { if (ui->active == w) { if (ui->hot == w) @@ -156,7 +156,7 @@ function B32 ui_mouse_test(UI *ui, UIWidget *w, Vec4 rect) { ui->active = 0; } } - + return result; }