init
[csRadar.git] / csrDraw.h
1 #include <time.h>
2
3 typedef struct csr_frag csr_frag;
4
5 struct csr_frag
6 {
7 u32 id; // Triangle index
8 float qa, qb; // Quantities
9
10 float depth; // 'depth testing'
11 };
12
13 void clear_depth( csr_frag fragments[], u32 x, u32 y )
14 {
15 for( u32 i = 0; i < x*y; i ++ )
16 {
17 fragments[ i ].depth = INFINITY;
18 }
19 }
20
21 void simple_raster( csr_frag fragments[], u32 x, u32 y, v4f cam_bounds, vmf_vert tri[3], int id )
22 {
23 // Very simplified tracing algorithm
24
25 v2f bmin = { 0.f, 0.f };
26 v2f bmax = { x, y };
27
28 v2_minv( tri[0].co, tri[1].co, bmin );
29 v2_minv( tri[2].co, bmin, bmin );
30
31 v2_maxv( tri[0].co, tri[1].co, bmax );
32 v2_maxv( tri[2].co, bmax, bmax );
33
34 float range_x = (cam_bounds[2]-cam_bounds[0])/(float)x;
35 float range_y = (cam_bounds[3]-cam_bounds[1])/(float)y;
36
37 int start_x = csr_max( 0, floorf( (bmin[0]-cam_bounds[0])/range_x));
38 int end_x = csr_min( x, floorf( (bmax[0]-cam_bounds[0])/range_x ));
39 int start_y = csr_max( 0, ceilf( (bmin[1]-cam_bounds[1])/range_y ));
40 int end_y = csr_min( y, ceilf( (bmax[1]-cam_bounds[1])/range_y ));
41
42 v3f trace_dir = { 0.f, 0.f, -1.f };
43 v3f trace_origin = { 0.f, 0.f, 16385.f };
44
45 for( u32 py = start_y; py < end_y; py ++ )
46 {
47 trace_origin[1] = csr_lerpf( cam_bounds[1], cam_bounds[3], (float)py/(float)y );
48
49 for( u32 px = start_x; px < end_x; px ++ )
50 {
51 trace_origin[0] = csr_lerpf( cam_bounds[0], cam_bounds[2], (float)px/(float)x );
52
53 csr_frag *frag = &fragments[ py*y + px ];
54
55 float tqa = 0.f, tqb = 0.f;
56 float tdepth = csr_ray_tri( trace_origin, trace_dir, tri[0].co, tri[1].co, tri[2].co, &tqa, &tqb );
57
58 if( tdepth < frag->depth )
59 {
60 frag->depth = tdepth;
61 frag->id = id;
62 frag->qa = tqa;
63 frag->qb = tqb;
64 }
65 }
66 }
67 }
68
69 // First pass 'fragmentize'
70 void draw_buffers( csr_frag fragments[], u32 x, u32 y, v4f cam_bounds, vmf_vert *triangles, u32 triangle_count )
71 {
72 clock_t t;
73 t = clock();
74 printf("Timer starts\n");
75
76 clear_depth( fragments, x, y );
77
78 for( u32 i = 0; i < triangle_count; i ++ )
79 {
80 vmf_vert *triangle = triangles + i*3;
81 simple_raster( fragments, x, y, cam_bounds, triangle, i );
82 }
83
84 printf("Timer ends \n");
85 t = clock() - t;
86 double time_taken = ((double)t)/CLOCKS_PER_SEC; // calculate the elapsed time
87 printf("Tracing took %f seconds to execute\n", time_taken);
88 }