Clipping donegit status! loading and showing sponza mini

This commit is contained in:
Krzosa Karol
2022-02-25 21:16:25 +01:00
parent fd8ce7d1a9
commit 372e4fd16b
10 changed files with 885 additions and 433 deletions

2
.gitignore vendored
View File

@@ -1,5 +1,7 @@
.vs/
x64/
assets/
*.sln
*.vcxproj*
*.rdbg

70
README.md Normal file
View File

@@ -0,0 +1,70 @@
# Things to do:
- [x] Drawing triangles
- [x] Drawing cubes and lines for testing
- [x] Y up coordinate system, left handed
- [x] Drawing a cube with perspective
- [x] Culling triangles facing away from camera
- [x] Texture mapping
- [x] Basic linear transformations - rotation, translation, scaling
- [x] Bilinear filtering of textures / subpixel precison
- [x] Nearest filtering
- [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] Gamma correct blending - converting to almost linear space
- [x] Alpha blending??
- [x] Premultiplied alpha???
- [x] Merge with base
- [ ] Lightning
- [x] GLOBAL Ilumination
- [x] LookAt Camera
- [ ] FPS Camera
- [x] Reading OBJ models
- [ ] Reading OBJ .mtl files
- [ ] Reading complex obj models (sponza)
- [ ] Reading PMX files
- [ ] Rendering multiple objects, queue renderer
- [x] Clipping
- [x] Triagnle rectangle bound clipping
- [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
- [ ] Subpixel precision of triangle edges
- [x] Simple profiling tooling
- [ ] Statistics based on profiler data, distribution information
- [x] Find cool profilers - ExtraSleepy, Vtune
- [ ] Optimizations
- [ ] Inline edge function
- [ ] Edge function to integer
- [ ] Use integer bit operations to figure out if plus. (edge1|edge2|edge3)>=0
- [ ] SIMD
- [ ] Multithreading
- [ ]
- [ ] Text rendering
- [ ] Basic UI
- [ ] Gamma correct and alpha blending
# Resources that helped me build the rasterizer (Might be helpful to you too):
* Algorithm I used for triangle rasterization by Juan Pineda: https://www.cs.drexel.edu/~david/Classes/Papers/comp175-06-pineda.pdf
* Fabian Giessen's "Optimizing Software Occlusion Culling": https://fgiesen.wordpress.com/2013/02/17/optimizing-sw-occlusion-culling-index/
* Fabian Giessen's optimized software renderer: https://github.com/rygorous/intel_occlusion_cull/tree/blog/SoftwareOcclusionCulling
* Fabian Giessen's javascript triangle rasterizer: https://gist.github.com/rygorous/2486101
* Fabian Giessen's C++ triangle rasterizer: https://github.com/rygorous/trirast/blob/master/main.cpp
* Joy's Kenneth lectures about computer graphics: https://www.youtube.com/playlist?list=PL_w_qWAQZtAZhtzPI5pkAtcUVgmzdAP8g
* Joy's Kenneth article on clipping: https://import.cdn.thinkific.com/167815/JoyKennethClipping-200905-175314.pdf
* A bunch of helpful notes and links to resources: https://nlguillemot.wordpress.com/2016/07/10/rasterizer-notes/
* Very nice paid course on making a software rasterizer using a scanline method: https://pikuma.com/courses/learn-3d-computer-graphics-programming
* Reference for obj loader: https://github.com/tinyobjloader/tinyobjloader/blob/master/tiny_obj_loader.h
*
*
*
## To read
* http://ce-publications.et.tudelft.nl/publications/1362_hardware_algorithms_for_tilebased_realtime_rendering.pdf

120
data.txt Normal file
View File

@@ -0,0 +1,120 @@
avg:0.000007
avg:0.000009
avg:0.000009
avg:0.000009
avg:0.000009
avg:0.000009
avg:0.000009
avg:0.000009
avg:0.000009
avg:0.000009
avg:0.000007
avg:0.000007
avg:0.000126
avg:0.000007
avg:0.000003
avg:0.000005
avg:0.000002
avg:0.000008
avg:0.000009
avg:0.000009
avg:0.000009
avg:0.000006
avg:0.000002
avg:0.000000
avg:0.000008
avg:0.000009
avg:0.000009
avg:0.000001
avg:0.000009
avg:0.000007
avg:0.000007
avg:0.000009
avg:0.000009
avg:0.000009
avg:0.000009
avg:0.000011
avg:0.000008
avg:0.000000
avg:0.000009
avg:0.000023
avg:0.000023
avg:0.000011
avg:0.000014
avg:0.000008
avg:0.000014
avg:0.000095
avg:0.000070
avg:0.000073
avg:0.000070
avg:0.000075
avg:0.000069
avg:0.000071
avg:0.000074
avg:0.000071
avg:0.000095
avg:0.000075
avg:0.000098
avg:0.000098
avg:0.000074
avg:0.000096
avg:0.000070
avg:0.000079
avg:0.000097
avg:0.000069
avg:0.000094
avg:0.000089
avg:0.000084
avg:0.000077
avg:0.000071
avg:0.000083
avg:0.000103
avg:0.000185
avg:0.000182
avg:0.000121
avg:0.000069
avg:0.000073
avg:0.000083
avg:0.000072
avg:0.000071
avg:0.000122
avg:0.000096
avg:0.000159
avg:0.000144
avg:0.000187
avg:0.000138
avg:0.000173
avg:0.000153
avg:0.000196
avg:0.000221
avg:0.000128
avg:0.000189
avg:0.000143
avg:0.000133
avg:0.000159
avg:0.000109
avg:0.000154
avg:0.000147
avg:0.000210
avg:0.000156
avg:0.000807
avg:0.000145
avg:0.000128
avg:0.000315
avg:0.000457
avg:0.000335
avg:0.000247
avg:0.000383
avg:0.000112
avg:0.000104
avg:0.000081
avg:0.000056
avg:0.000019
avg:0.000050
avg:0.000029
avg:0.000023
avg:0.000039
avg:0.000097
avg:0.000098
avg:0.000097
avg:0.000002

Binary file not shown.

595
main.cpp
View File

@@ -1,57 +1,104 @@
/* Things to do:
OK Drawing triangles
OK Drawing cubes and lines for testing
OK Y up coordinate system, left handed
OK Drawing a cube with perspective
OK Culling triangles facing away from camera
OK Texture mapping
? Basic math operations on Vec4 Mat4 - Muls, dot, cross etc.
OK Basic linear transformations - rotation, translation, scaling
OK Bilinear filtering of textures / subpixel precison
OK Fix the gaps between triangles (it also improved look of triangle edges)
* Perspective matrix vs simple perspective
OK Perspective correct interpolation
OK Depth buffer
KINDA_OK Gamma correct blending
OK Alpha blending??
OK Premultiplied alpha???
OK Merge with base
* Lightning
OK GLOBAL Ilumination
* LookAt Camera
* FPS Camera
OK Reading OBJ files
* Reading PMX files
* Rendering multiple objects, queue renderer
* Clipping
* Optimizations
* SIMD
* Multithreading
*
* Text rendering
* Basic UI
* Gamma correct and alpha blending
*/
/////////////////////////////////////////////////////////////////////////////////////
///
/// ### Things to do:
///
/// - [x] Drawing triangles
/// - [x] Drawing cubes and lines for testing
/// - [x] Y up coordinate system, left handed
/// - [x] Drawing a cube with perspective
/// - [x] Culling triangles facing away from camera
/// - [x] Texture mapping
/// - [x] Basic linear transformations - rotation, translation, scaling
/// - [x] Bilinear filtering of textures / subpixel precison
/// - [x] Nearest filtering
/// - [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] Gamma correct blending - converting to almost linear space
/// - [x] Alpha blending??
/// - [x] Premultiplied alpha???
/// - [x] Merge with base
/// - [ ] Lightning
/// - [x] GLOBAL Ilumination
/// - [x] LookAt Camera
/// - [ ] FPS Camera
/// - [x] Reading OBJ models
/// - [ ] Reading OBJ .mtl files
/// - [ ] Reading complex obj models (sponza)
/// - [ ] Reading PMX files
/// - [ ] Rendering multiple objects, queue renderer
/// - [x] Clipping
/// - [x] Triagnle rectangle bound clipping
/// - [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
/// - [ ] Subpixel precision of triangle edges
/// - [x] Simple profiling tooling
/// - [ ] Statistics based on profiler data, distribution information
/// - [x] Find cool profilers - ExtraSleepy, Vtune
/// - [ ] Optimizations
/// - [ ] Inline edge function
/// - [ ] Edge function to integer
/// - [ ] Use integer bit operations to figure out if plus. (edge1|edge2|edge3)>=0
/// - [ ] SIMD
/// - [ ] Multithreading
/// - [ ]
/// - [ ] Text rendering
/// - [ ] Basic UI
/// - [ ] Gamma correct and alpha blending
///
/// ### Resources that helped me build the rasterizer (Might be helpful to you too):
///
/// * Algorithm I used for triangle rasterization by Juan Pineda: https://www.cs.drexel.edu/~david/Classes/Papers/comp175-06-pineda.pdf
/// * Fabian Giessen's "Optimizing Software Occlusion Culling": https://fgiesen.wordpress.com/2013/02/17/optimizing-sw-occlusion-culling-index/
/// * Fabian Giessen's optimized software renderer: https://github.com/rygorous/intel_occlusion_cull/tree/blog/SoftwareOcclusionCulling
/// * Fabian Giessen's javascript triangle rasterizer: https://gist.github.com/rygorous/2486101
/// * Fabian Giessen's C++ triangle rasterizer: https://github.com/rygorous/trirast/blob/master/main.cpp
/// * Joy's Kenneth lectures about computer graphics: https://www.youtube.com/playlist?list=PL_w_qWAQZtAZhtzPI5pkAtcUVgmzdAP8g
/// * Joy's Kenneth article on clipping: https://import.cdn.thinkific.com/167815/JoyKennethClipping-200905-175314.pdf
/// * A bunch of helpful notes and links to resources: https://nlguillemot.wordpress.com/2016/07/10/rasterizer-notes/
/// * Very nice paid course on making a software rasterizer using a scanline method: https://pikuma.com/courses/learn-3d-computer-graphics-programming
/// * Reference for obj loader: https://github.com/tinyobjloader/tinyobjloader/blob/master/tiny_obj_loader.h
/// *
/// *
/// *
///
/// ### To read
///
/// * http://ce-publications.et.tudelft.nl/publications/1362_hardware_algorithms_for_tilebased_realtime_rendering.pdf
#define OS_WINDOWS 1
#define PERSPECTIVE_CORRECT_INTERPOLATION 1
#define BILINEAR_BLEND 1
#define GAMMA_CORRECT_BLENDING 1
#define _CRT_SECURE_NO_WARNINGS
#define PREMULTIPLIED_ALPHA_BLENDING 1
#define PLATFORM
#include "base.h"
#include "kpl.h"
#include "profile.cpp"
#include "math.h"
struct R_Vertex {
Vec3 pos;
Vec2 tex;
Vec3 norm;
};
struct R_Render {
Mat4 camera;
Mat4 projection;
};
#include "obj_parser.cpp"
#include "stb_image.h"
#include "objparser.h"
#include <float.h>
//GLOBAL OS os = {};
GLOBAL bool draw_rects = 0;
GLOBAL bool draw_wireframe = 0;
FUNCTION
void draw_rect(Bitmap* dst, float X, float Y, float w, float h, U32 color) {
void draw_rect(Bitmap* dst, F32 X, F32 Y, F32 w, F32 h, U32 color) {
int max_x = (int)(MIN(X + w, dst->x) + 0.5f);
int max_y = (int)(MIN(Y + h, dst->y) + 0.5f);
int min_x = (int)(MAX(0, X) + 0.5f);
@@ -65,8 +112,8 @@ void draw_rect(Bitmap* dst, float X, float Y, float w, float h, U32 color) {
}
FUNCTION
float edge_function(Vec4 vecp0, Vec4 vecp1, Vec4 p) {
float result = (vecp1.y - vecp0.y) * (p.x - vecp0.x) - (vecp1.x - vecp0.x) * (p.y - vecp0.y);
F32 edge_function(Vec4 vecp0, Vec4 vecp1, Vec4 p) {
F32 result = (vecp1.y - vecp0.y) * (p.x - vecp0.x) - (vecp1.x - vecp0.x) * (p.y - vecp0.y);
return result;
}
@@ -126,96 +173,65 @@ FUNCTION
}
FUNCTION
void draw_triangle(Bitmap* dst, float *depth_buffer, Bitmap *src, float light,
void draw_triangle_nearest(Bitmap* dst, F32 *depth_buffer, Bitmap *src, F32 light,
Vec4 p0, Vec4 p1, Vec4 p2,
Vec2 tex0, Vec2 tex1, Vec2 tex2) {
float min_x1 = (float)(MIN(p0.x, MIN(p1.x, p2.x)));
float min_y1 = (float)(MIN(p0.y, MIN(p1.y, p2.y)));
float max_x1 = (float)(MAX(p0.x, MAX(p1.x, p2.x)));
float max_y1 = (float)(MAX(p0.y, MAX(p1.y, p2.y)));
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)));
I64 min_x = (I64)MAX(0, floor(min_x1));
I64 min_y = (I64)MAX(0, floor(min_y1));
I64 max_x = (I64)MIN(dst->x, ceil(max_x1));
I64 max_y = (I64)MIN(dst->y, ceil(max_y1));
float area = edge_function(p0, p1, p2);
F32 area = edge_function(p0, p1, p2);
for (I64 y = min_y; y < max_y; y++) {
for (I64 x = min_x; x < max_x; x++) {
float edge1 = edge_function(p0, p1, { (float)x,(float)y });
float edge2 = edge_function(p1, p2, { (float)x,(float)y });
float edge3 = edge_function(p2, p0, { (float)x,(float)y });
F32 edge1 = edge_function(p0, p1, { (F32)x,(F32)y });
F32 edge2 = edge_function(p1, p2, { (F32)x,(F32)y });
F32 edge3 = edge_function(p2, p0, { (F32)x,(F32)y });
if (edge1 >= 0 && edge2 >= 0 && edge3 >= 0) {
float w1 = edge2 / area;
float w2 = edge3 / area;
float w3 = edge1 / area;
float interpolated_z = (1.f / p0.w) * w1 + (1.f / p1.w) * w2 + (1.f / p2.w) * w3;
#if PERSPECTIVE_CORRECT_INTERPOLATION
float u = tex0.x * (w1 / p0.w) + tex1.x * (w2 / p1.w) + tex2.x * (w3 / p2.w);
float v = tex0.y * (w1 / p0.w) + tex1.y * (w2 / p1.w) + tex2.y * (w3 / p2.w);
u /= interpolated_z;
v /= interpolated_z;
#else
float u = tex0.x * w1 + tex1.x * w2 + tex2.x * w3;
float v = tex0.y * w1 + tex1.y * w2 + tex2.y * w3;
#endif
// @Note: We could do: interpolated_z = 1.f / interpolated_z to get proper depth
F32 w1 = edge2 / area;
F32 w2 = edge3 / area;
F32 w3 = edge1 / area;
F32 interpolated_w = (1.f / p0.w) * w1 + (1.f / p1.w) * w2 + (1.f / p2.w) * w3;
F32 u = tex0.x * (w1 / p0.w) + tex1.x * (w2 / p1.w) + tex2.x * (w3 / p2.w);
F32 v = tex0.y * (w1 / p0.w) + tex1.y * (w2 / p1.w) + tex2.y * (w3 / p2.w);
u /= interpolated_w;
v /= interpolated_w;
// @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
float* depth = depth_buffer + (x + y * dst->x);
if (*depth < interpolated_z) {
*depth = interpolated_z;
F32* depth = depth_buffer + (x + y * dst->x);
if (*depth < interpolated_w) {
*depth = interpolated_w;
u = u * (src->x - 2);
v = v * (src->y - 2);
I64 ui = (I64)(u);
I64 vi = (I64)(v);
float udiff = u - (float)ui;
float vdiff = v - (float)vi;
F32 udiff = u - (F32)ui;
F32 vdiff = v - (F32)vi;
// 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);
U32 *pixel = src->pixels + (ui + (src->y - 1ll - vi) * src->x);
#if BILINEAR_BLEND
Vec4 pixelx1y1 = vec4abgr(*pixel);
Vec4 pixelx2y1 = vec4abgr(*(pixel + 1));
Vec4 pixelx1y2 = vec4abgr(*(pixel - src->x));
Vec4 pixelx2y2 = vec4abgr(*(pixel + 1 - src->x));
#if GAMMA_CORRECT_BLENDING
pixelx1y1 = srgb_to_almost_linear(pixelx1y1);
pixelx2y1 = srgb_to_almost_linear(pixelx2y1);
pixelx1y2 = srgb_to_almost_linear(pixelx1y2);
pixelx2y2 = srgb_to_almost_linear(pixelx2y2);
#endif // GAMMA_CORRECT_BLENDING
Vec4 blendx1 = lerp(pixelx1y1, pixelx2y1, udiff);
Vec4 blendx2 = lerp(pixelx1y2, pixelx2y2, udiff);
Vec4 result_color = lerp(blendx1, blendx2, vdiff);
#if PREMULTIPLIED_ALPHA_BLENDING
Vec4 result_color = srgb_to_almost_linear(vec4abgr(*pixel));
Vec4 dst_color = srgb_to_almost_linear(vec4abgr(*dst_pixel));
result_color.r *= light;
result_color.g *= light;
result_color.b *= light;
#if PREMULTIPLIED_ALPHA_BLENDING
Vec4 dst_color = vec4abgr(*dst_pixel);
#if GAMMA_CORRECT_BLENDING
dst_color = srgb_to_almost_linear(dst_color);
result_color.r = result_color.r + (1-result_color.a) * dst_color.r;
result_color.g = result_color.g + (1-result_color.a) * dst_color.g;
result_color.b = result_color.b + (1-result_color.a) * dst_color.b;
result_color.a = result_color.a + dst_color.a - result_color.a*dst_color.a;
result_color = almost_linear_to_srgb(result_color);
U32 color32 = vec4_to_u32abgr(result_color);
#else
U32 color32 = *pixel;
#endif
result_color.r = result_color.r + (1-result_color.a) * dst_color.r;
result_color.g = result_color.g + (1-result_color.a) * dst_color.g;
result_color.b = result_color.b + (1-result_color.a) * dst_color.b;
result_color.a = result_color.a + dst_color.a - result_color.a*dst_color.a;
#endif // PREMULTIPLIED_ALPHA_BLENDING
#if GAMMA_CORRECT_BLENDING
result_color = almost_linear_to_srgb(result_color);
//ASSERT(result_color.r <= 1 && result_color.g <= 1 && result_color.b <= 1);
#endif // GAMMA_CORRECT_BLENDING
U32 color32 = vec4_to_u32abgr(result_color);
#else // BILINEAR_BLEND
Vec4 result_color = srgb_to_almost_linear(vec4abgr(*pixel));
Vec4 dst_color = srgb_to_almost_linear(vec4abgr(*dst_pixel));
result_color.r = result_color.r + (1-result_color.a) * dst_color.r;
result_color.g = result_color.g + (1-result_color.a) * dst_color.g;
result_color.b = result_color.b + (1-result_color.a) * dst_color.b;
result_color.a = result_color.a + dst_color.a - result_color.a*dst_color.a;
result_color = almost_linear_to_srgb(result_color);
U32 color32 = vec4_to_u32abgr(result_color);
#endif // BILINEAR_BLEND
*dst_pixel = color32;
}
@@ -230,14 +246,96 @@ void draw_triangle(Bitmap* dst, float *depth_buffer, Bitmap *src, float light,
}
FUNCTION
void draw_line(Bitmap *dst, float x0, float y0, float x1, float y1) {
float delta_x = (x1 - x0);
float delta_y = (y1 - y0);
float longest_side_length = (ABS(delta_x) >= ABS(delta_y)) ? ABS(delta_x) : ABS(delta_y);
float x_inc = delta_x / (float)longest_side_length;
float y_inc = delta_y / (float)longest_side_length;
float current_x = (float)x0;
float current_y = (float)y0;
void draw_triangle_subpixel(Bitmap* dst, F32 *depth_buffer, Bitmap *src, F32 light,
Vec4 p0, Vec4 p1, Vec4 p2,
Vec2 tex0, Vec2 tex1, Vec2 tex2) {
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)));
I64 min_x = (I64)MAX(0, floor(min_x1));
I64 min_y = (I64)MAX(0, floor(min_y1));
I64 max_x = (I64)MIN(dst->x, ceil(max_x1));
I64 max_y = (I64)MIN(dst->y, ceil(max_y1));
F32 area = edge_function(p0, p1, p2);
for (I64 y = min_y; y < max_y; y++) {
for (I64 x = min_x; x < max_x; x++) {
F32 edge1 = edge_function(p0, p1, { (F32)x,(F32)y });
F32 edge2 = edge_function(p1, p2, { (F32)x,(F32)y });
F32 edge3 = edge_function(p2, p0, { (F32)x,(F32)y });
if (edge1 >= 0 && edge2 >= 0 && edge3 >= 0) {
F32 w1 = edge2 / area;
F32 w2 = edge3 / area;
F32 w3 = edge1 / area;
F32 interpolated_w = (1.f / p0.w) * w1 + (1.f / p1.w) * w2 + (1.f / p2.w) * w3;
F32 u = tex0.x * (w1 / p0.w) + tex1.x * (w2 / p1.w) + tex2.x * (w3 / p2.w);
F32 v = tex0.y * (w1 / p0.w) + tex1.y * (w2 / p1.w) + tex2.y * (w3 / p2.w);
u /= interpolated_w;
v /= interpolated_w;
// @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);
if (*depth < interpolated_w && interpolated_w > 0.1f) {
*depth = interpolated_w;
u = u * (src->x - 2);
v = v * (src->y - 2);
I64 ui = (I64)(u);
I64 vi = (I64)(v);
F32 udiff = u - (F32)ui;
F32 vdiff = v - (F32)vi;
// 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);
Vec4 pixelx1y1 = vec4abgr(*pixel);
Vec4 pixelx2y1 = vec4abgr(*(pixel + 1));
Vec4 pixelx1y2 = vec4abgr(*(pixel - src->x));
Vec4 pixelx2y2 = vec4abgr(*(pixel + 1 - src->x));
pixelx1y1 = srgb_to_almost_linear(pixelx1y1);
pixelx2y1 = srgb_to_almost_linear(pixelx2y1);
pixelx1y2 = srgb_to_almost_linear(pixelx1y2);
pixelx2y2 = srgb_to_almost_linear(pixelx2y2);
Vec4 blendx1 = lerp(pixelx1y1, pixelx2y1, udiff);
Vec4 blendx2 = lerp(pixelx1y2, pixelx2y2, udiff);
Vec4 result_color = lerp(blendx1, blendx2, vdiff);
result_color.r *= light;
result_color.g *= light;
result_color.b *= light;
#if PREMULTIPLIED_ALPHA_BLENDING
Vec4 dst_color = vec4abgr(*dst_pixel);
dst_color = srgb_to_almost_linear(dst_color);
result_color.r = result_color.r + (1-result_color.a) * dst_color.r;
result_color.g = result_color.g + (1-result_color.a) * dst_color.g;
result_color.b = result_color.b + (1-result_color.a) * dst_color.b;
result_color.a = result_color.a + dst_color.a - result_color.a*dst_color.a;
#endif // PREMULTIPLIED_ALPHA_BLENDING
result_color = almost_linear_to_srgb(result_color);
U32 color32 = vec4_to_u32abgr(result_color);
*dst_pixel = color32;
}
}
}
}
if (draw_rects) {
draw_rect(dst, p0.x-4, p0.y-4, 8,8, 0x00ff0000);
draw_rect(dst, p1.x-4, p1.y-4, 8,8, 0x0000ff00);
draw_rect(dst, p2.x-4, p2.y-4, 8,8, 0x000000ff);
}
}
FUNCTION
void draw_line(Bitmap *dst, F32 x0, F32 y0, F32 x1, F32 y1) {
F32 delta_x = (x1 - x0);
F32 delta_y = (y1 - y0);
F32 longest_side_length = (ABS(delta_x) >= ABS(delta_y)) ? ABS(delta_x) : ABS(delta_y);
F32 x_inc = delta_x / (F32)longest_side_length;
F32 y_inc = delta_y / (F32)longest_side_length;
F32 current_x = (F32)x0;
F32 current_y = (F32)y0;
for (int i = 0; i <= longest_side_length; i++) {
int x = (int)(current_x + 0.5f);
int y = (int)(current_y + 0.5f);
@@ -247,26 +345,6 @@ void draw_line(Bitmap *dst, float x0, float y0, float x1, float y1) {
}
}
struct FaceA {
int vertex[3];
int tex[3];
int normal[3];
};
FN void null_terminate(Arena *arena) {
PUSH_SIZE(arena, 1);
}
FUNCTION
Obj load_obj(S8 file) {
Scratch scratch;
S8 data = os_read_file(scratch, file).error_is_fatal();
null_terminate(scratch);
char* memory = (char*)malloc(100000);
Obj result = obj::parse(memory, 100000, (char *)data.str);
return result;
}
FUNCTION
Bitmap load_image(const char* path) {
int x, y, n;
@@ -287,115 +365,212 @@ Bitmap load_image(const char* path) {
return result;
}
FN void r_draw_mesh(ObjMesh *mesh) {
}
int main() {
obj::test();
os.window_size.x = 1280;
os.window_size.y = 720;
os_init();
os_init_software_render();
os.window_size.x = 1920;
os.window_size.y = 1080;
os.window_resizable = 1;
os_init().error_is_fatal();
S8List list = {};
string_push(os.frame_arena, &list, LIT("main.cpp"));
generate_documentation(list, LIT("README.md"));
float rotation = 0;
Vec3 camera_pos = {0,0,-5};
Obj obj = load_obj(LIT("assets/sponza/sponza_mini.obj"));
Obj obj = load_obj(LIT("assets/f22.obj"));
Vec3* vertices = (Vec3 *)obj.vertices;
Vec2* tex_coords = (Vec2*)obj.texture;
Vec3 *normals = (Vec3 *)obj.normals;
FaceA* faces = (FaceA*)obj.indices;
I64 face_count = obj.indices_count;
//Obj obj = load_obj(LIT("assets/f22.obj"));
ObjMesh *mesh = obj.mesh.e + 1;
F32 speed = 0.01f;
F32 rotation = 405;
Vec3 camera_pos = {0,0,-2};
//Vec3 camera_target = { 300, 200, 0 };
Vec3 camera_target = { 0, 0, 0 };
bool lock_camera_flag = 1;
Vec3* vertices = (Vec3 *)obj.vertices.e;
Vec2* tex_coords = (Vec2*)obj.texture_coordinates.e;
Vec3 *normals = (Vec3 *)obj.normals.e;
Bitmap img = load_image("assets/bricksx64.png");
int screen_x = 320;
int screen_y = 180;
Bitmap screen320 = {(U32 *)malloc(screen_x*screen_y*sizeof(U32)), screen_x, screen_y};
float* depth320 = (float *)malloc(sizeof(float) * screen_x * screen_y);
Bitmap screen320 = {(U32 *)PUSH_SIZE(os.perm_arena, screen_x*screen_y*sizeof(U32)), screen_x, screen_y};
F32* depth320 = (F32 *)PUSH_SIZE(os.perm_arena, sizeof(F32) * screen_x * screen_y);
while (os_game_loop()) {
Mat4 perspective = make_matrix_perspective(60.f, (float)screen->x, (float)screen->y, 0.1f, 100.f);
Mat4 perspective = mat4_perspective(60.f, (F32)os.screen->x, (F32)os.screen->y, 0.1f, 1000.f);
Mat4 camera = mat4_look_at(camera_pos, camera_target, vec3(0, 1, 0));
U32* p = screen320.pixels;
for (int y = 0; y < screen320.y; y++) {
for (int x = 0; x < screen320.x; x++) {
*p++ = 0x33333333;
}
}
float* dp = depth320;
F32* dp = depth320;
for (int y = 0; y < screen320.y; y++) {
for (int x = 0; x < screen320.x; x++) {
*dp++ = -FLT_MAX;
}
}
Mat4 transform = make_matrix_rotation_z(rotation);
transform = transform * make_matrix_rotation_x(rotation);
if (os.key[Key_Escape].pressed) os.quit = true;
Mat4 transform = mat4_rotation_z(rotation);
transform = transform * mat4_rotation_y(rotation);
if (os.key[Key_Escape].pressed) os_quit();
if (os.key[Key_O].down) rotation += 0.05f;
if (os.key[Key_P].down) rotation -= 0.05f;
if (os.key[Key_F1].pressed) draw_rects = !draw_rects;
if (os.key[Key_F2].pressed) draw_wireframe = !draw_wireframe;
for (int i = 0; i < face_count; i++) {
FaceA* face = faces + i;
Vec4 pos[3] = {
vec4(vertices[face->vertex[0] - 1], 1),
vec4(vertices[face->vertex[1] - 1], 1),
vec4(vertices[face->vertex[2] - 1], 1),
};
Vec2 tex[3] = {
tex_coords[face->tex[0] - 1],
tex_coords[face->tex[1] - 1],
tex_coords[face->tex[2] - 1],
};
Vec3 norm[3] = {
normals[face->normal[0] - 1],
normals[face->normal[1] - 1],
normals[face->normal[2] - 1],
if (os.key[Key_A].down) camera_target.x -= speed;
if (os.key[Key_D].down) camera_target.x += speed;
if (os.key[Key_W].down) camera_target.y += speed;
if (os.key[Key_S].down) camera_target.y -= speed;
if (os.key[Key_R].down) camera_pos.z += speed;
if (os.key[Key_F].down) camera_pos.z -= speed;
for (int i = 0; i < mesh->indices.len; i++) {
ObjIndex *index = mesh->indices.e + i;
R_Vertex vert[] = {
{
vertices[index->vertex[0] - 1],
tex_coords[index->tex[0] - 1],
normals[index->normal[0] - 1],
},
{
vertices[index->vertex[1] - 1],
tex_coords[index->tex[1] - 1],
normals[index->normal[1] - 1],
},
{
vertices[index->vertex[2] - 1],
tex_coords[index->tex[2] - 1],
normals[index->normal[2] - 1],
},
};
if (lock_camera_flag) {
camera_pos = vert[0].pos - vec3(0,-100,130);
camera_target = vert[0].pos;
camera = mat4_look_at(camera_pos, camera_target, vec3(0, 1, 0));
lock_camera_flag = 0;
}
//@Note: Transform
for (int j = 0; j < 3; j++) {
pos[j] = transform * pos[j];
}
//@Note: Cull
Vec3 p0_to_camera = camera_pos - pos[0].xyz;
Vec3 p0_to_p1 = pos[1].xyz - pos[0].xyz;
Vec3 p0_to_p2 = pos[2].xyz - pos[0].xyz;
Vec3 normal = normalize(cross(p0_to_p1, p0_to_p2));
float light = -dot(normal, vec3(0,1,0));
light = CLAMP(0.05f, light, 1.f);
if (dot(normal, p0_to_camera) > 0) {
for (int j = 0; j < 3; j++) {
//@Note: Camera
pos[j].xyz = pos[j].xyz - camera_pos;
//@Note: Perspective
pos[j] = perspective * pos[j];
pos[j].x = pos[j].x / pos[j].w;
pos[j].y = pos[j].y / pos[j].w;
pos[j].z = pos[j].z / pos[j].w;
//@Note: To pixel space
pos[j].x *= screen320.x / 2;
pos[j].y *= screen320.y / 2;
pos[j].x += screen320.x / 2;
pos[j].y += screen320.y / 2;
vert[j].pos = transform * vert[j].pos;
}
draw_triangle(&screen320, depth320, &img, light, pos[0], pos[1], pos[2], tex[0], tex[1], tex[2]);
Vec3 p0_to_camera = 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_y(45) * vec3(0, 0, 1);
F32 light = -dot(normal, light_direction);
light = CLAMP(0.05f, light, 1.f);
if (dot(normal, p0_to_camera) > 0) { //@Note: Backface culling
// @Note: Zfar
B32 vertex_is_outside = false;
Vec3 zfar_normal = vec3(0, 0, -1);
Vec3 zfar_pos = vec3(0, 0, 1000.f);
for (I32 j = 0; j < 3; j++) {
// @Note: Camera
vert[j].pos = 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)) {
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 _R_Vertex {
Vec4 pos;
Vec2 tex;
} in[4];
I32 in_count = 0;
R_Vertex *prev = vert + 2;
R_Vertex *curr = vert;
F32 prev_dot = dot(znear_normal, prev->pos - znear_pos);
F32 curr_dot = 0;
for (int j = 0; j < 3; j++) {
pos[j].x += screen320.x / 8;
pos[j].y += screen320.y / 8;
curr_dot = dot(znear_normal, curr->pos - znear_pos);
if (curr_dot * prev_dot < 0) {
F32 t = prev_dot / (prev_dot - curr_dot);
in[in_count].pos = vec4(lerp(prev->pos, curr->pos, t), 1);
in[in_count++].tex = lerp(prev->tex, curr->tex, t);
}
draw_triangle(&screen320, depth320, &img, light, pos[0], pos[1], pos[2], tex[0], tex[1], tex[2]);
if (curr_dot > 0) {
in[in_count].pos = vec4(vert[j].pos, 1);
in[in_count++].tex = vert[j].tex;
}
prev = curr++;
prev_dot = curr_dot;
}
if (in_count == 0) {
continue;
}
for(I64 j = 0; j < in_count; j++) {
//@Note: Perspective
in[j].pos = perspective * 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 *= screen320.x / 2;
in[j].pos.y *= screen320.y / 2;
in[j].pos.x += screen320.x / 2;
in[j].pos.y += screen320.y / 2;
}
if(os.frame > 60) PROFILE_BEGIN(draw_triangle);
draw_triangle_nearest(&screen320, depth320, &img, light, in[0].pos, in[1].pos, in[2].pos, in[0].tex, in[1].tex, in[2].tex);
if(os.frame > 60) PROFILE_END(draw_triangle);
if (in_count > 3) {
if(os.frame > 60) PROFILE_BEGIN(draw_triangle);
draw_triangle_nearest(&screen320, depth320, &img, light, in[0].pos, in[2].pos, in[3].pos, in[0].tex, in[2].tex, in[3].tex);
if(os.frame > 60) PROFILE_END(draw_triangle);
}
#if 1
ProfileScope *scope = profile_scopes + ProfileScopeName_draw_triangle;
LOCAL_PERSIST B32 profile_flag;
if (!profile_flag && scope->i > 2000) {
profile_flag = 1;
F64 sum = 0;
for (I64 i = 0; i < profile_scopes[ProfileScopeName_draw_triangle].i; i++) {
sum += scope->samples[i];
}
F64 avg = sum / scope->i;
S8 data = string_format(os.frame_arena, "avg:%f\n", avg);
os_append_file(LIT("data.txt"), data);
}
#endif
if (draw_wireframe) {
draw_line(&screen320, pos[0].x, pos[0].y, pos[1].x, pos[1].y);
draw_line(&screen320, pos[1].x, pos[1].y, pos[2].x, pos[2].y);
draw_line(&screen320, pos[2].x, pos[2].y, pos[0].x, pos[0].y);
draw_line(&screen320, vert[0].pos.x, vert[0].pos.y, vert[1].pos.x, vert[1].pos.y);
draw_line(&screen320, vert[1].pos.x, vert[1].pos.y, vert[2].pos.x, vert[2].pos.y);
draw_line(&screen320, vert[2].pos.x, vert[2].pos.y, vert[0].pos.x, vert[0].pos.y);
}
}
}
// @Note: Draw 320screen to OS screen
U32* ptr = screen->pixels;
for (int y = 0; y < screen->y; y++) {
for (int x = 0; x < screen->x; x++) {
float u = (float)x / (float)screen->x;
float v = (float)y / (float)screen->y;
U32* ptr = os.screen->pixels;
for (int y = 0; y < os.screen->y; y++) {
for (int x = 0; x < os.screen->x; x++) {
F32 u = (F32)x / (F32)os.screen->x;
F32 v = (F32)y / (F32)os.screen->y;
int tx = (int)(u * screen320.x );
int ty = (int)(v * screen320.y );
*ptr++ = screen320.pixels[tx + ty * (screen320.x)];

56
math.h
View File

@@ -1,6 +1,35 @@
FUNCTION
Mat4 mat4_identity() {
return {
1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1,
};
}
FUNCTION
Mat4 make_matrix_rotation_x(float rotation) {
Mat4 mat4_scale(Vec3 a) {
return {
a.x, 0, 0, 0,
0, a.y, 0, 0,
0, 0, a.z, 0,
0, 0, 0, 1
};
}
FUNCTION
Mat4 mat4_translation(Vec3 a) {
return {
1, 0, 0, a.x,
0, 1, 0, a.y,
0, 0, 1, a.z,
0, 0, 0, 1
};
}
FUNCTION
Mat4 mat4_rotation_z(float rotation) {
float s = sinf(rotation);
float c = cosf(rotation);
Mat4 result = {
@@ -13,7 +42,7 @@ Mat4 make_matrix_rotation_x(float rotation) {
}
FUNCTION
Mat4 make_matrix_rotation_y(float rotation) {
Mat4 mat4_rotation_y(float rotation) {
float s = sinf(rotation);
float c = cosf(rotation);
Mat4 result = {
@@ -26,7 +55,7 @@ Mat4 make_matrix_rotation_y(float rotation) {
}
FUNCTION
Mat4 make_matrix_rotation_z(float rotation) {
Mat4 mat4_rotation_x(float rotation) {
float s = sinf(rotation);
float c = cosf(rotation);
Mat4 result = {
@@ -39,9 +68,9 @@ Mat4 make_matrix_rotation_z(float rotation) {
}
FUNCTION
Mat4 make_matrix_perspective(float fov, float window_x, float window_y, float znear, float zfar) {
Mat4 mat4_perspective(float fov, float window_x, float window_y, float znear, float zfar) {
float aspect_ratio = window_y / window_x;
float f = (1.f / tanf((fov/2.f)*(180.f/PI32)));
float f = (1.f / tanf((fov/2.f)*deg2rad));
Mat4 result = {
aspect_ratio*f, 0, 0, 0,
0, f, 0, 0,
@@ -51,8 +80,21 @@ Mat4 make_matrix_perspective(float fov, float window_x, float window_y, float zn
return result;
}
FN Mat4 mat4_look_at(Vec3 pos, Vec3 target, Vec3 up) {
Vec3 z = normalize(target - pos);
Vec3 x = normalize(cross(up, z));
Vec3 y = cross(z, x);
Mat4 result = {
x.x,x.y,x.z,-dot(x,pos),
y.x,y.y,y.z,-dot(y,pos),
z.x,z.y,z.z,-dot(z,pos),
0,0,0, 1,
};
return result;
}
FUNCTION
Mat4 transpose(Mat4 a) {
Mat4 mat4_transpose(Mat4 a) {
Mat4 result = a;
result.p[0][1] = result.p[1][0];
result.p[0][2] = result.p[2][0];
@@ -64,7 +106,7 @@ Mat4 transpose(Mat4 a) {
}
FUNCTION
Mat4 translate(Mat4 a, Vec3 translation) {
Mat4 mat4_translate(Mat4 a, Vec3 translation) {
a.p[0][0] += translation.x;
a.p[0][1] += translation.y;
a.p[0][2] += translation.z;

254
obj_parser.cpp Normal file
View File

@@ -0,0 +1,254 @@
template<class T>
struct DynamicArray {
T *e;
U64 cap, len;
T *push_empty(int element_count = 1) {
if (cap == 0) {
cap = 8;
e = (T*)malloc(sizeof(T)*cap);
}
else if (len + element_count > cap) {
U64 new_size = (len + element_count) * 2;
void *ptr = realloc(e, new_size*sizeof(T));
if (!ptr) FATAL_ERROR("Ran out of memory! Cant allocate more.");
e = (T *)ptr;
cap = new_size;
}
T *result = e + len;
len += element_count;
return result;
}
void push(T element) {
T *result = push_empty();
*result = element;
}
};
struct ObjIndex {
int vertex[3];
int tex[3];
int normal[3];
I32 material_id;
I32 smoothing_group_id;
};
struct ObjMesh {
char name[64];
DynamicArray<ObjIndex> indices;
};
struct Obj {
DynamicArray<Vec3> vertices;
DynamicArray<Vec2> texture_coordinates;
DynamicArray<Vec3> normals;
DynamicArray<ObjMesh> mesh;
};
namespace obj {
enum class TokenType {
none, word, number, whitespace, end
};
struct Token {
TokenType type;
double number;
union {
struct {
char* s;
int len;
};
S8 s8;
};
};
FN Token next_token_raw(char** data) {
Token result = {};
result.s = *data;
*data += 1;
if (is_alphabetic(*result.s)) {
result.type = TokenType::word;
while (!is_whitespace(**data)) {
*data += 1;
}
result.len = (int)(*data - result.s);
}
else if (is_number(*result.s) || *result.s == '-') {
result.type = TokenType::number;
while (is_number(**data) || **data == '.') {
*data += 1;
}
result.number = atof(result.s);
result.len = (int)(*data - result.s);
}
else if (*result.s == '#') {
while (**data != '\n') *data += 1;
result = next_token_raw(data);
}
else if (is_whitespace(*result.s)) {
result.type = TokenType::whitespace;
while (is_whitespace(**data)) *data += 1;
result.len = (int)(*data - result.s);
}
else if (*result.s == 0) {
result.type = TokenType::end;
}
else if (*result.s >= '!') {
result.type = (TokenType)*result.s;
}
return result;
}
FN Token next_token(char** data) {
Token result;
do {
result = next_token_raw(data);
} while (result.type == TokenType::whitespace);
return result;
}
FN double expect_number(char** data) {
Token t = next_token(data);
TASSERT(t.type == TokenType::number); // @Todo: Error handling, error flag
return t.number;
}
FN void expect_token(char** data, char token) {
Token t = next_token(data);
TASSERT(t.type == (TokenType)token); // @Todo: Error handling, error flag
}
FN void debug_expect_raw(char** data, TokenType type) {
char* data_temp = *data;
TASSERT(next_token_raw(&data_temp).type == type);
}
// Each face needs to have own material_id, group_id, smoothing ..
Obj parse(char* data) {
Obj result = {};
int smoothing = 0;
ObjMesh *mesh = 0;
int material_id = -1;
for (;; ) {
Token token = next_token(&data);
if (token.type == TokenType::end) break;
else if (token.type == TokenType::word) {
if (string_compare(token.s8, LIT("v"))) {
Vec3 *vertex = result.vertices.push_empty();
vertex->x = (float)expect_number(&data);
vertex->y = (float)expect_number(&data);
vertex->z = (float)expect_number(&data);
debug_expect_raw(&data, TokenType::whitespace);
}
else if (string_compare(token.s8, LIT("vt"))) {
Vec2 *tex = result.texture_coordinates.push_empty();
tex->x = (float)expect_number(&data);
tex->y = (float)expect_number(&data);
debug_expect_raw(&data, TokenType::whitespace);
}
else if (string_compare(token.s8, LIT("vn"))) {
Vec3 *norm = result.normals.push_empty();
norm->x = (float)expect_number(&data);
norm->y = (float)expect_number(&data);
norm->z = (float)expect_number(&data);
debug_expect_raw(&data, TokenType::whitespace);
}
else if (string_compare(token.s8, LIT("mtlib"))) {
Token t = next_token(&data);
TASSERT(t.type == TokenType::word);
}
else if (string_compare(token.s8, LIT("usemtl"))) {
Token t = next_token(&data);
TASSERT(t.type == TokenType::word);
}
else if (string_compare(token.s8, LIT("o"))) {
Token t = next_token(&data);
TASSERT(t.type == TokenType::word);
mesh = result.mesh.push_empty();
ZERO_STRUCT(mesh);
U64 len = CLAMP_TOP(t.len, 64);
memory_copy(t.s, mesh->name, len);
}
else if (string_compare(token.s8, LIT("s"))) {
Token t = next_token(&data);
if (t.type == TokenType::number) {
smoothing = (int)t.number;
}
else {
TASSERT(t.type == TokenType::word);
if (string_compare(t.s8, LIT("on"))) {
smoothing = 1;
}
else if (string_compare(t.s8, LIT("off"))) {
smoothing = 0;
}
else INVALID_CODEPATH;
}
}
else if (string_compare(token.s8, LIT("g"))) {
Token t = next_token(&data);
TASSERT(t.type == TokenType::word);
}
else if (string_compare(token.s8, LIT("f"))) {
ObjIndex *i = mesh->indices.push_empty();
i->smoothing_group_id = smoothing;
i->material_id = material_id;
i->vertex[0] = (int)expect_number(&data);
expect_token(&data, '/');
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);
expect_token(&data, '/');
i->normal[2] = (int)expect_number(&data);
//debug_expect_raw(&data, TokenType::whitespace);
}
}
}
return result;
}
FN void test_lex() {
const char* d = "v 0.885739 0.001910 -0.380334";
char* dd = (char *)d;
TASSERT(next_token(&dd).type == TokenType::word);
Token t = next_token(&dd); TASSERT(t.type == TokenType::number && t.number > 0.8857);
t = next_token(&dd); TASSERT(t.type == TokenType::number && t.number > 0.0019);
t = next_token(&dd); TASSERT(t.type == TokenType::number && t.number < -0.38);
d = "# Blender v2.79 (sub 0) OBJ File: 'fighters_0.blend'\n"
"# www.blender.org\n"
"mtllib f-22.mtl\n"
"o F-22\n";
dd = (char *)d;
t = next_token(&dd); TASSERT(t.type == TokenType::word && string_compare(t.s8, LIT("mtllib")));
t = next_token(&dd); TASSERT(t.type == TokenType::word && string_compare(t.s8, LIT("f-22.mtl")));
t = next_token(&dd); TASSERT(t.type == TokenType::word && string_compare(t.s8, LIT("o")));
t = next_token(&dd); TASSERT(t.type == TokenType::word && string_compare(t.s8, LIT("F-22")));
}
void test() {
test_lex();
}
}
FUNCTION
Obj load_obj(S8 file) {
Scratch scratch;
S8 data = os_read_file(scratch, file).error_is_fatal();
PUSH_SIZE(scratch, 1);
Obj result = obj::parse((char *)data.str);
return result;
}

View File

@@ -1,217 +0,0 @@
#include "objparser.h"
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#define FUNCTION static
enum class TokenType {
none, word, number, whitespace, end
};
struct Token {
TokenType type;
union {
struct {
char* s;
int len;
};
double number;
};
};
struct Obj_Arena {
char* base;
size_t size;
size_t p;
};
namespace obj {
FUNCTION bool is_alphabetic(char w) {
bool result = (w >= 'a' && w <= 'z') || (w >= 'A' && w <= 'Z');
return result;
}
FUNCTION bool is_number(char w) {
bool result = w >= '0' && w <= '9';
return result;
}
FUNCTION bool is_whitespace(char w) {
bool result = w == '\n' || w == ' ' || w == '\t' || w == '\v' || w == '\r';
return result;
}
FUNCTION int string_len(char* a) {
int result = 0;
while (*a++ != 0) result++;
return result;
}
FUNCTION bool equals(Token a, const char* b) {
int len = string_len((char*)b);
if (a.type != TokenType::word) return false;
if (a.len != len) return false;
for (int i = 0; i < len; i++) {
if (a.s[i] != b[i]) return false;
}
return true;
}
FUNCTION Token next_token_raw(char** data) {
Token result = {};
result.s = *data;
*data += 1;
if (is_alphabetic(*result.s)) {
result.type = TokenType::word;
while (!is_whitespace(**data)) {
*data += 1;
}
result.len = (int)(*data - result.s);
}
else if (is_number(*result.s) || *result.s == '-') {
result.type = TokenType::number;
while (is_number(**data) || **data == '.') {
*data += 1;
}
result.number = atof(result.s);
}
else if (*result.s == '#') {
while (**data != '\n') *data += 1;
result = next_token_raw(data);
}
else if (is_whitespace(*result.s)) {
result.type = TokenType::whitespace;
while (is_whitespace(**data)) *data += 1;
result.len = (int)(*data - result.s);
}
else if (*result.s == 0) {
result.type = TokenType::end;
}
else if (*result.s >= '!') {
result.type = (TokenType)*result.s;
}
return result;
}
FUNCTION Token next_token(char** data) {
Token result;
do {
result = next_token_raw(data);
} while (result.type == TokenType::whitespace);
return result;
}
FUNCTION double expect_number(char** data) {
Token t = next_token(data);
assert(t.type == TokenType::number); // @Todo: Error handling, error flag
return t.number;
}
FUNCTION void expect_token(char** data, char token) {
Token t = next_token(data);
assert(t.type == (TokenType)token); // @Todo: Error handling, error flag
}
FUNCTION void debug_expect_raw(char** data, TokenType type) {
char* data_temp = *data;
assert(next_token_raw(&data_temp).type == type);
}
FUNCTION char* push(Obj_Arena *a, size_t size) {
char* ptr = a->base;
if (a->p + size < a->size) {
ptr += a->p;
a->p += size;
}
else {
assert(!"Buffer is too small to hold the data!");
}
return ptr;
}
Obj parse(char* memory, size_t memory_size, char* data) {
Obj_Arena arena = { memory, memory_size };
Obj result = {};
for (; ; ) {
Token token = next_token(&data);
if (token.type == TokenType::end) break;
else if (token.type == TokenType::word) {
if (equals(token, "v")) {
float* ptr = (float*)push(&arena, sizeof(float) * 3);
ptr[0] = (float)expect_number(&data);
ptr[1] = (float)expect_number(&data);
ptr[2] = (float)expect_number(&data);
if (result.vertices == 0) result.vertices = ptr;
result.vertices_count++;
debug_expect_raw(&data, TokenType::whitespace);
}
else if (equals(token, "vt")) {
float* ptr = (float*)push(&arena, sizeof(float) * 2);
ptr[0] = (float)expect_number(&data);
ptr[1] = (float)expect_number(&data);
if (result.texture == 0) result.texture = ptr;
debug_expect_raw(&data, TokenType::whitespace);
}
else if (equals(token, "vn")) {
float* ptr = (float*)push(&arena, sizeof(float) * 3);
ptr[0] = (float)expect_number(&data);
ptr[1] = (float)expect_number(&data);
ptr[2] = (float)expect_number(&data);
if (result.normals == 0) result.normals = ptr;
debug_expect_raw(&data, TokenType::whitespace);
}
else if (equals(token, "f")) {
int* ptr = (int*)push(&arena, sizeof(int) * 9);
ptr[0] = (int)expect_number(&data);
expect_token(&data, '/');
ptr[3] = (int)expect_number(&data);
expect_token(&data, '/');
ptr[6] = (int)expect_number(&data);
ptr[1] = (int)expect_number(&data);
expect_token(&data, '/');
ptr[4] = (int)expect_number(&data);
expect_token(&data, '/');
ptr[7] = (int)expect_number(&data);
ptr[2] = (int)expect_number(&data);
expect_token(&data, '/');
ptr[5] = (int)expect_number(&data);
expect_token(&data, '/');
ptr[8] = (int)expect_number(&data);
if (result.indices == 0) result.indices = ptr;
result.indices_count += 1;
debug_expect_raw(&data, TokenType::whitespace);
}
}
}
result.memory_taken = arena.p;
return result;
}
FUNCTION void test_lex() {
const char* d = "v 0.885739 0.001910 -0.380334";
char* dd = (char *)d;
assert(next_token(&dd).type == TokenType::word);
Token t = next_token(&dd); assert(t.type == TokenType::number && t.number > 0.8857);
t = next_token(&dd); assert(t.type == TokenType::number && t.number > 0.0019);
t = next_token(&dd); assert(t.type == TokenType::number && t.number < -0.38);
d = "# Blender v2.79 (sub 0) OBJ File: 'fighters_0.blend'\n"
"# www.blender.org\n"
"mtllib f-22.mtl\n"
"o F-22\n";
dd = (char *)d;
t = next_token(&dd); assert(t.type == TokenType::word && equals(t, (char*)"mtllib"));
t = next_token(&dd); assert(t.type == TokenType::word && equals(t, (char*)"f-22.mtl"));
t = next_token(&dd); assert(t.type == TokenType::word && equals(t, (char*)"o"));
t = next_token(&dd); assert(t.type == TokenType::word && equals(t, (char*)"F-22"));
}
void test() {
test_lex();
}
}

View File

@@ -1,16 +0,0 @@
#pragma once
struct Obj {
float* vertices; // sets of 3 floats
float* texture; // sets of 2 floats
float* normals; // sets of 3 floats
int vertices_count; // count of sets(vertices, textures, normals)
int* indices; // layout: vvv/ttt/nnn
int indices_count; // 1 count == 1 full face == 3vertex indices, 3 texture coordinate indices, 3 normal indices
size_t memory_taken;
};
namespace obj {
Obj parse(char* memory, size_t memory_size, char* data);
void test();
}

22
profile.cpp Normal file
View File

@@ -0,0 +1,22 @@
enum ProfileScopeName {
ProfileScopeName_draw_triangle,
ProfileScopeName_Count,
};
struct ProfileScope {
F64 samples[5096];
I64 i;
};
GLOBAL ProfileScope profile_scopes[ProfileScopeName_Count];
#define PROFILE_BEGIN(name) do { \
ProfileScope *__profile_scope = profile_scopes + ProfileScopeName_##name; \
__profile_scope->samples[__profile_scope->i] = os_time(); \
} while (0)
#define PROFILE_END(name) do { \
ProfileScope *_profile_scope = profile_scopes + ProfileScopeName_##name; \
_profile_scope->samples[_profile_scope->i] = os_time() - _profile_scope->samples[_profile_scope->i]; \
_profile_scope->i = (_profile_scope->i + 1) % 5096; \
}while (0)