i forgo
[carveJwlIkooP6JGAAIwe30JlM.git] / scene.h
1 #ifndef SCENE_H
2 #define SCENE_H
3
4 #include "vg/vg.h"
5 #include "model.h"
6
7 typedef struct scene scene;
8 typedef struct bvh_node bvh_node;
9
10 struct scene
11 {
12 glmesh mesh;
13
14 model_vert *verts;
15 u32 *indices;
16
17 struct
18 {
19 bvh_node *nodes;
20 u32 node_count;
21 }
22 bvh;
23
24 u32 vertex_count,
25 indice_count,
26 vertex_cap,
27 indice_cap;
28
29 boxf bbx;
30
31 struct shadower
32 {
33 sdf_primative sdf;
34 esdf_type sdf_type;
35 }
36 *shadowers;
37
38 u32 shadower_count,
39 shadower_cap;
40
41 submodel submesh;
42 };
43
44 GLuint tex_dual_noise;
45
46 static void scene_init( scene *pscene )
47 {
48 pscene->verts = NULL;
49 pscene->indices = NULL;
50 pscene->vertex_count = 0;
51 pscene->indice_count = 0;
52 pscene->shadowers = NULL;
53 pscene->shadower_count = 0;
54 pscene->shadower_cap = 0;
55 pscene->submesh.indice_start = 0;
56 pscene->submesh.indice_count = 0;
57
58 v3_fill( pscene->bbx[0], 999999.9f );
59 v3_fill( pscene->bbx[1], -999999.9f );
60
61 static int noise_ready = 0;
62 if( !noise_ready )
63 {
64 noise_ready = 1;
65
66 u8 *buf = malloc( 256*256*2 );
67
68 for( int i=0; i<256*256; i++ )
69 {
70 u8 val = rand()&0xff;
71 buf[i*2] = val;
72 }
73
74 for( int y=0; y<256; y++ )
75 {
76 for( int x=0; x<256; x++ )
77 {
78 u8 *pr = &buf[(y*256+x)*2],
79 *pg = &buf[(((y+17)&0xff)*256+((x+37)&0xff))*2+1];
80 *pg = *pr;
81 }
82 }
83
84 /* TODO: This texture should be delted somewhere */
85 glGenTextures( 1, &tex_dual_noise );
86 glBindTexture( GL_TEXTURE_2D, tex_dual_noise );
87 glTexImage2D( GL_TEXTURE_2D, 0, GL_RG, 256, 256, 0, GL_RG,
88 GL_UNSIGNED_BYTE, buf );
89
90 vg_tex2d_linear();
91 vg_tex2d_repeat();
92
93 free( buf );
94 }
95 }
96
97 /* https://www.shadertoy.com/view/4sfGzS */
98 #define SHADER_VALUE_NOISE_3D \
99 "uniform sampler2D uTexNoise;" \
100 "" \
101 "float noise( vec3 x )" \
102 "{" \
103 "vec3 i = floor(x);" \
104 "vec3 f = fract(x);" \
105 "f = f*f*(3.0-2.0*f);" \
106 "vec2 uv = (i.xy+vec2(37.0,17.0)*i.z) + f.xy;" \
107 "vec2 rg = texture( uTexNoise, (uv+0.5)/256.0).yx;"\
108 "return mix( rg.x, rg.y, f.z );" \
109 "}" \
110 "" \
111 "const mat3 m = mat3( 0.00, 0.80, 0.60," \
112 "-0.80, 0.36, -0.48," \
113 "-0.60, -0.48, 0.64 );" \
114 "" \
115 "float fractalNoise( vec3 x )" \
116 "{" \
117 "vec3 q = 8.0*x;" \
118 "float f;" \
119 "f = 0.5000*noise( q ); q = m*q*2.01;" \
120 "f += 0.2500*noise( q ); q = m*q*2.02;" \
121 "f += 0.1250*noise( q ); q = m*q*2.03;" \
122 "f += 0.0625*noise( q ); q = m*q*2.01;" \
123 "return f;" \
124 "}"
125
126 SHADER_DEFINE( shader_debug_vcol,
127
128 /*Include*/ VERTEX_STANDARD_ATTRIBUTES
129
130 "uniform mat4 uPv;"
131 "uniform mat4x3 uMdl;"
132 "uniform float uTime;"
133 "uniform float uSwayAmt;"
134 ""
135 "out vec4 aColour;"
136 "out vec2 aUv;"
137 "out vec3 aNorm;"
138 "out vec3 aCo;"
139 ""
140 "vec3 compute_sway( vec3 pos )"
141 "{"
142 "vec4 sines = vec4( sin(uTime + pos.x)*1.0,"
143 "sin(uTime*1.2 + pos.z*2.0)*1.1,"
144 "sin(uTime*2.33)*0.5,"
145 "sin(uTime*0.6 + pos.x*0.3)*1.3 );"
146
147 "vec3 offset = vec3( sines.x+sines.y*sines.w, 0.0, sines.x+sines.z );"
148 "return pos + offset*a_colour.r*uSwayAmt;"
149 "}"
150 ""
151 "void main()"
152 "{"
153 "vec3 swaypos = compute_sway( a_co );"
154 "gl_Position = uPv * vec4(uMdl * vec4(swaypos,1.0), 1.0 );"
155 "aColour = a_colour;"
156 "aUv = a_uv;"
157 "aNorm = normalize(mat3(uMdl) * a_norm);"
158 "aCo = a_co;"
159 "}",
160 /* Fragment */
161 "out vec4 FragColor;"
162 ""
163 "uniform int uMode;"
164 "uniform sampler2D uTexMain;"
165 "uniform sampler2D uTexGradients;"
166 ""
167 /*Include*/ SHADER_VALUE_NOISE_3D
168 ""
169 "in vec4 aColour;"
170 "in vec2 aUv;"
171 "in vec3 aNorm;"
172 "in vec3 aCo;"
173 ""
174 "void main()"
175 "{"
176 "vec4 colour = vec4(1.0,0.0,0.5,1.0);"
177 "vec4 diffuse = texture( uTexMain, aUv );"
178
179 "if( uMode == 1 )"
180 "{"
181 "colour = vec4(aNorm * 0.5 + 0.5, 1.0);"
182 "}"
183 "if( uMode == 2 )"
184 "{"
185 "colour = aColour;"
186 "}"
187 "if( uMode == 3 )"
188 "{"
189 "float light = dot(aNorm, vec3(0.2,0.8,0.1));"
190 "vec3 grid3 = fract(aCo);"
191
192 "colour = vec4(vec3(light)*(1.0-grid3*0.3),1.0);"
193 "}"
194 "if( uMode == 4 )"
195 "{"
196 "colour = vec4( aUv, 0.0, 1.0 );"
197 "}"
198 "if( uMode == 5 )"
199 "{"
200 "if( diffuse.a < 0.45 ) discard;"
201 "colour = diffuse;"
202 "}"
203 "if( uMode == 6 )"
204 "{"
205 "float r1 = fractalNoise(aCo);"
206 "colour = vec4( vec3(r1), 1.0 );"
207 "}"
208 "if( uMode == 7 )"
209 "{"
210 "if( diffuse.a < 0.2 ) discard;"
211 "float lighting = 1.0 - aColour.g*0.8;"
212
213 "float light1 = max(0.0,dot(-vec3(0.5,-0.8,0.25), aNorm));"
214 "float light2 = max(0.0,dot(-vec3(-0.8,0.5,-0.25), aNorm));"
215 "vec3 lt = vec3(0.2,0.2,0.2 ) + "
216 "vec3(1.0,1.0,0.9)*light1 + "
217 "vec3(0.1,0.3,0.4 )*light2;"
218
219
220 "colour = vec4(vec3(pow(lighting,1.6)*(diffuse.r*0.7+0.5)),1.0);"
221 "colour = vec4(colour.rgb*lt,1.0);"
222
223 "vec2 gradUV = vec2(lighting*1.9,aColour.b*0.8);"
224 "vec4 gradient_sample = texture( uTexGradients, gradUV );"
225 "colour = colour*gradient_sample;"
226 "}"
227 "if( uMode == 8 )"
228 "{"
229 "if( diffuse.a < 0.45 ) discard;"
230 "float light = 1.0 - aColour.g;"
231 "light = pow(light,1.6)*(diffuse.r*0.7+0.5);"
232 "float r1 = fractalNoise(aCo*0.01);"
233
234 "vec2 gradUV = vec2(light*1.9,r1+aColour.b);"
235 "vec4 gradient_sample = texture( uTexGradients, gradUV );"
236 "colour = gradient_sample*light;"
237 "}"
238
239 "FragColor = colour;"
240 "}"
241 ,
242 UNIFORMS({ "uPv", "uMode", "uTexMain", "uTexGradients", "uTexNoise", \
243 "uTime", "uSwayAmt", "uMdl" })
244 )
245
246 SHADER_DEFINE( shader_standard_lit,
247
248 /*Include*/ VERTEX_STANDARD_ATTRIBUTES
249
250 "uniform mat4 uPv;"
251 "uniform mat4x3 uMdl;"
252 ""
253 "out vec4 aColour;"
254 "out vec2 aUv;"
255 "out vec3 aNorm;"
256 "out vec3 aCo;"
257 ""
258 "void main()"
259 "{"
260 "gl_Position = uPv * vec4( uMdl * vec4(a_co,1.0), 1.0 );"
261 "aColour = a_colour;"
262 "aUv = a_uv;"
263 "aNorm = mat3(uMdl) * a_norm;"
264 "aCo = a_co;"
265 "}",
266 /* Fragment */
267 "out vec4 FragColor;"
268 ""
269 "uniform sampler2D uTexMain;"
270 "uniform vec4 uColour;"
271 ""
272 "in vec4 aColour;"
273 "in vec2 aUv;"
274 "in vec3 aNorm;"
275 "in vec3 aCo;"
276 ""
277 "void main()"
278 "{"
279 "vec3 diffuse = texture( uTexMain, aUv ).rgb;"
280
281 "float light1 = max(0.0,dot(-vec3(0.5,-0.8,0.25), aNorm));"
282 "float light2 = max(0.0,dot(-vec3(-0.8,0.5,-0.25), aNorm));"
283 "diffuse += vec3(0.2,0.2,0.2) + "
284 "vec3(1.0,1.0,0.9)*light1 + "
285 "vec3(0.1,0.3,0.4)*light2;"
286
287 "FragColor = vec4(diffuse*uColour.rgb, aColour.a*uColour.a);"
288 "}"
289 ,
290 UNIFORMS({ "uColour","uTexMain","uPv","uMdl" })
291 )
292
293 SHADER_DEFINE( shader_unlit,
294
295 /*Include*/ VERTEX_STANDARD_ATTRIBUTES
296
297 "uniform mat4 uPv;"
298 "uniform mat4x3 uMdl;"
299 ""
300 "out vec4 aColour;"
301 "out vec2 aUv;"
302 "out vec3 aNorm;"
303 "out vec3 aCo;"
304 ""
305 "void main()"
306 "{"
307 "gl_Position = uPv * vec4(uMdl * vec4(a_co,1.0), 1.0);"
308 "aColour = a_colour;"
309 "aUv = a_uv;"
310 "aNorm = mat3(uMdl) * a_norm;"
311 "aCo = a_co;"
312 "}",
313 /* Fragment */
314 "out vec4 FragColor;"
315 ""
316 "uniform sampler2D uTexMain;"
317 "uniform vec4 uColour;"
318 ""
319 "in vec4 aColour;"
320 "in vec2 aUv;"
321 "in vec3 aNorm;"
322 "in vec3 aCo;"
323 ""
324 "void main()"
325 "{"
326 "vec3 diffuse = texture( uTexMain, aUv ).rgb;"
327 "FragColor = vec4(pow(diffuse,vec3(1.0)),1.0);"
328 "}"
329 ,
330 UNIFORMS({ "uTexMain", "uPv", "uMdl" })
331 )
332
333 static void *buffer_reserve( void *buffer, u32 count, u32 *cap, u32 amount,
334 size_t emsize )
335 {
336 if( count+amount > *cap )
337 {
338 *cap = VG_MAX( (*cap)*2, (*cap)+amount );
339
340 return realloc( buffer, (*cap) * emsize );
341 }
342
343 return buffer;
344 }
345
346 /*
347 * Append a model into the scene with a given transform
348 */
349 static void scene_add_model( scene *pscene, model *mdl, submodel *submodel,
350 v3f pos, float yaw, float scale )
351 {
352 pscene->verts = buffer_reserve( pscene->verts, pscene->vertex_count,
353 &pscene->vertex_cap, submodel->vertex_count, sizeof(model_vert) );
354 pscene->indices = buffer_reserve( pscene->indices, pscene->indice_count,
355 &pscene->indice_cap, submodel->indice_count, sizeof(u32) );
356
357 if( submodel->sdf_type )
358 {
359 pscene->shadowers = buffer_reserve( pscene->shadowers,
360 pscene->shadower_count, &pscene->shadower_cap, 1,
361 sizeof( struct shadower ));
362
363 struct shadower *shadower =
364 &pscene->shadowers[ pscene->shadower_count ++ ];
365
366 shadower->sdf = submodel->sdf;
367 shadower->sdf_type = submodel->sdf_type;
368
369 v2_muls( shadower->sdf.info, scale, shadower->sdf.info );
370 v3_muls( shadower->sdf.origin, scale, shadower->sdf.origin );
371 v3_add( pos, shadower->sdf.origin, shadower->sdf.origin );
372 }
373
374 /* Transform and place vertices */
375 model_vert *src_verts = submodel_vert_data( mdl, submodel );
376 u32 *src_indices = submodel_indice_data( mdl, submodel );
377
378 m4x3f mtx;
379 m4x3_identity( mtx );
380 m4x3_translate( mtx, pos );
381 m4x3_rotate_y( mtx, yaw );
382 m4x3_scale( mtx, scale );
383
384 boxf bbxnew;
385 box_copy( submodel->bbx, bbxnew );
386 m4x3_transform_aabb( mtx, bbxnew );
387 box_concat( pscene->bbx, bbxnew );
388
389 m3x3f rotation;
390 m4x3_to_3x3( mtx, rotation );
391
392 float rand_hue = vg_randf();
393
394 for( u32 i=0; i<submodel->vertex_count; i++ )
395 {
396 model_vert *pvert = &pscene->verts[ pscene->vertex_count+i ],
397 *src = &src_verts[ i ];
398
399 m4x3_mulv( mtx, src->co, pvert->co );
400 m3x3_mulv( rotation, src->norm, pvert->norm );
401
402 v4_copy( src->colour, pvert->colour );
403 v2_copy( src->uv, pvert->uv );
404
405 float rel_y = src->co[1] / submodel->bbx[1][1];
406 pvert->colour[0] = rel_y;
407 pvert->colour[2] = rand_hue;
408 }
409
410 for( u32 i=0; i<submodel->indice_count; i++ )
411 {
412 u32 *pidx = &pscene->indices[ pscene->indice_count+i ];
413 *pidx = src_indices[i] + pscene->vertex_count;
414 }
415
416 pscene->vertex_count += submodel->vertex_count;
417 pscene->indice_count += submodel->indice_count;
418 }
419
420 static void scene_copy_slice( scene *pscene, submodel *sm )
421 {
422 sm->indice_start = pscene->submesh.indice_start;
423 sm->indice_count = pscene->indice_count - sm->indice_start;
424
425 sm->vertex_start = pscene->submesh.vertex_start;
426 sm->vertex_count = pscene->vertex_count - sm->vertex_start;
427
428 pscene->submesh.indice_start = pscene->indice_count;
429 pscene->submesh.vertex_start = pscene->vertex_count;
430 }
431
432 static void scene_shadow_sphere( scene *pscene, v3f sphere,
433 v4f params, v3f lightdir )
434 {
435 for( int i=0; i<pscene->vertex_count; i++ )
436 {
437 model_vert *vert = &pscene->verts[i];
438
439 v3f delta;
440 v3_sub( sphere, vert->co, delta );
441
442 float d = v3_dot( lightdir, delta );
443 v3f closest;
444
445 v3_muls( lightdir, d, closest );
446 float dist = v3_dist( closest, delta ),
447 shading = vg_maxf( dist - params[0], 0.0f );
448
449 shading = vg_minf( shading * params[1], 1.0f );
450 vert->colour[1] *= shading;
451 }
452 }
453
454 static void scene_shadow_gradient( scene *pscene, int comp,
455 float start, float length )
456 {
457 float scale = 1.0f / length;
458
459 for( int i=0; i<pscene->vertex_count; i++ )
460 {
461 model_vert *vert = &pscene->verts[i];
462 float shading = start + vert->co[comp] * scale;
463
464 vert->colour[1] = shading;
465 }
466 }
467
468
469 /*
470 * Experimental SDF based shadows
471 *
472 * https://iquilezles.org/articles/distfunctions/
473 */
474 static float sd_cone( v3f co, sdf_primative *prim )
475 {
476 float bound = prim->info[1]*1.75f;
477 if( v3_dist2( prim->origin, co ) > bound*bound )
478 return 999999.9f;
479
480 v3f p;
481 v3_sub( co, prim->origin, p );
482
483 float h = prim->info[1];
484 v2f c = { prim->info[2], prim->info[3] };
485
486 v2f q, w, a, b;
487 v2_muls( (v2f){ c[0]/c[1], -1.0f }, h, q );
488
489 w[0] = v2_length( (v2f){ p[0], p[2] } );
490 w[1] = p[1];
491
492 v2_muladds( w, q, -vg_clampf( v2_dot(w,q)/v2_dot(q,q), 0.0f, 1.0f ), a );
493 v2_muladd( w, q, (v2f){ vg_clampf( w[0]/q[0], 0.0f, 1.0f ), 1.0f }, b );
494
495 float k = vg_signf( q[1] ),
496 d = vg_minf( v2_dot( a,a ), v2_dot( b,b ) ),
497 s = vg_maxf( k*(w[0]*q[1]-w[1]*q[0]), k*(w[1]-q[1]) );
498
499 return sqrtf(d)*vg_signf(s);
500 }
501
502 #define CACHE_AMBIENT_SHAPES
503
504 static float scene_ambient_sample( scene *pscene, v3f pos, v3f dir )
505 {
506 float accum = 0.0f;
507
508 #ifdef CACHE_AMBIENT_SHAPES
509 static struct shadower *local_shadowers[32];
510 static int local_shadower_count = 0;
511 static v3f local_shadower_last = { -99999.9f, -999999.9f, -9999999.9f };
512
513 if( v3_dist2( pos, local_shadower_last ) > 10.0f*10.0f )
514 {
515 local_shadower_count = 0;
516 v3_copy( pos, local_shadower_last );
517
518 for( int k=0; k<pscene->shadower_count; k++ )
519 {
520 struct shadower *shadower = &pscene->shadowers[k];
521
522 if( sd_cone( pos, &shadower->sdf ) <= 20.0f )
523 {
524 local_shadowers[ local_shadower_count ++ ] = shadower;
525 if( local_shadower_count == vg_list_size( local_shadowers ) )
526 break;
527 }
528 }
529 }
530 #endif
531
532 for( int j=0; j<5; j++ )
533 {
534 v3f tracepos;
535 v3_muladds( pos, dir, 1.5f*(float)j, tracepos );
536
537 float mindist = 99999.9f;
538
539 #ifndef CACHE_AMBIENT_SHAPES
540
541 for( int k=0; k<pscene->shadower_count; k++ ){
542 struct shadower *shadower = &pscene->shadowers[k];
543 #else
544
545 for( int k=0; k<local_shadower_count; k++ ){
546 struct shadower *shadower = local_shadowers[k];
547 #endif
548
549 float dist = vg_maxf( 0.0f, sd_cone( tracepos, &shadower->sdf ));
550 mindist = vg_minf( mindist, dist );
551 }
552
553
554 accum += vg_clampf( 1.0f - mindist, 0.0f, 1.0f )*0.2f;
555 }
556
557 return accum;
558 }
559
560 #define DYNAMIC_GRID
561 #define JUST_DO_EVERY_VERT
562
563 static void scene_compute_occlusion( scene *pscene )
564 {
565 v3f sundir = { 0.2f, 0.9f, 0.2f };
566 v3_normalize( sundir );
567
568 /* TODO: Make this sample grid be dynamically required.
569 *
570 * 1. Only resample the light grid (1x1x1), when a vertex is outside the
571 * current cube
572 *
573 * 2. Reorder all vertices so that each group of vertices that fit in a
574 * cube are next to eachother in the buffer. This will save cache
575 * misses.
576 *
577 * for the sorting algorithm, i think we can already assume that *most
578 * vertices will be quite close to eachother. so instead of doing an
579 * exhaustive search we can reorder 1k chunks at a time.
580 */
581
582 v3f sample_area;
583 v3_sub( pscene->bbx[1], pscene->bbx[0], sample_area );
584 v3_ceil( sample_area, sample_area );
585 int ax = sample_area[0],
586 ay = sample_area[1],
587 az = sample_area[2];
588
589 #ifndef DYNAMIC_GRID
590 float *samplegrid = malloc( ax*ay*az* sizeof(float) );
591
592 for( int x=0; x<ax; x++ ){
593 for( int y=0; y<ay; y++ ){
594 for( int z=0; z<az; z++ )
595 {
596 v3f sample_pos = { x,y,z };
597 v3_add( pscene->bbx[0], sample_pos, sample_pos );
598 float accum = scene_ambient_sample( pscene, sample_pos, sundir );
599
600 samplegrid[x + y*ax + z*ax*ay] = accum;
601 }}}
602 #else
603 v3i cube_pos = { -999999, -999999, -999999 };
604 int cube_resamples = 0, hits = 0, misses = 0;
605
606 float s0=0.0f,s1=0.0f,s2=0.0f,s3=0.0f,s4=0.0f,s5=0.0f,s6=0.0f,s7=0.0f;
607 #endif
608
609 for( int i=0; i<pscene->vertex_count; i++ )
610 {
611 model_vert *vert = &pscene->verts[i];
612 v3f rel, q;
613
614 #ifndef DYNAMIC_GRID
615 v3_sub( vert->co, pscene->bbx[0], q );
616 #else
617 v3_copy( vert->co, q );
618 #endif
619
620 v3_floor( q, rel );
621 v3_sub( q, rel, q );
622
623 int x=rel[0],
624 y=rel[1],
625 z=rel[2];
626
627 #ifndef JUST_DO_EVERY_VERT
628 #ifndef DYNAMIC_GRID
629 x = VG_MIN(x,ax-2);
630 y = VG_MIN(y,ay-2);
631 z = VG_MIN(z,az-2);
632 x = VG_MAX(x,0);
633 y = VG_MAX(y,0);
634 z = VG_MAX(z,0);
635
636 float
637 s0 = samplegrid[ x + y*ax + z*ax*ay],
638 s1 = samplegrid[(x+1) + y*ax + z*ax*ay],
639 s2 = samplegrid[ x + (y+1)*ax + z*ax*ay],
640 s3 = samplegrid[(x+1) + (y+1)*ax + z*ax*ay],
641 s4 = samplegrid[ x + y*ax + (z+1)*ax*ay],
642 s5 = samplegrid[(x+1) + y*ax + (z+1)*ax*ay],
643 s6 = samplegrid[ x + (y+1)*ax + (z+1)*ax*ay],
644 s7 = samplegrid[(x+1) + (y+1)*ax + (z+1)*ax*ay],
645 #else
646 if( x!=cube_pos[0] || y!=cube_pos[1] || z!=cube_pos[2] )
647 {
648 cube_pos[0] = x;
649 cube_pos[1] = y;
650 cube_pos[2] = z;
651
652 s0 = scene_ambient_sample( pscene, (v3f){ x,y,z }, sundir );
653 s1 = scene_ambient_sample( pscene, (v3f){ x+1,y,z }, sundir );
654 s2 = scene_ambient_sample( pscene, (v3f){ x,y+1,z }, sundir );
655 s3 = scene_ambient_sample( pscene, (v3f){ x+1,y+1,z }, sundir );
656 s4 = scene_ambient_sample( pscene, (v3f){ x,y,z+1 }, sundir );
657 s5 = scene_ambient_sample( pscene, (v3f){ x+1,y,z+1 }, sundir );
658 s6 = scene_ambient_sample( pscene, (v3f){ x,y+1,z+1 }, sundir );
659 s7 = scene_ambient_sample( pscene, (v3f){ x+1,y+1,z+1 }, sundir );
660
661 cube_resamples += 8;
662 misses ++;
663 }
664 else
665 hits ++;
666
667 float
668 #endif
669
670 s0_s1 = vg_lerpf( s0, s1, q[0] ),
671 s2_s3 = vg_lerpf( s2, s3, q[0] ),
672 s4_s5 = vg_lerpf( s4, s5, q[0] ),
673 s6_s7 = vg_lerpf( s6, s7, q[0] ),
674
675 s0s1_s2s3 = vg_lerpf( s0_s1, s2_s3, q[1] ),
676 s4s5_s6s7 = vg_lerpf( s4_s5, s6_s7, q[1] ),
677 s0s1s2s3_s4s5s6s7 = vg_lerpf( s0s1_s2s3, s4s5_s6s7, q[2] );
678
679 vert->colour[1] = s0s1s2s3_s4s5s6s7;
680 #else
681 vert->colour[1] = scene_ambient_sample( pscene, vert->co, sundir );
682 #endif
683 }
684
685 #ifndef DYNAMIC_GRID
686 int cube_resamples = -1, misses = 0, hits = 0;
687 #endif
688
689 int static_samples = ax*ay*az,
690 vertex_samples = pscene->vertex_count;
691
692 if( cube_resamples < static_samples )
693 vg_success( "Walking cube beat static grid (%d<%d. %d)!\n",
694 cube_resamples, static_samples, vertex_samples );
695 else
696 vg_warn( "Walking cube was worse than static grid (%d<%d. %d).\n",
697 cube_resamples, static_samples, vertex_samples );
698
699 vg_info( "Hits; %d, misses: %d\n", hits, misses );
700
701 #ifndef DYNAMIC_GRID
702 free( samplegrid );
703 #endif
704
705 return;
706
707 for( int i=0; i<pscene->vertex_count; i++ )
708 {
709 model_vert *vert = &pscene->verts[i];
710 float accum = 0.0f;
711
712 for( int j=0; j<5; j++ )
713 {
714 v3f tracepos;
715 v3_copy( vert->co, tracepos );
716 v3_muladds( tracepos, sundir, 1.5f*(float)j, tracepos );
717
718 float mindist = 99999.9f;
719
720 for( int k=0; k<pscene->shadower_count; k++ )
721 {
722 struct shadower *shadower = &pscene->shadowers[k];
723 float dist = vg_maxf( 0.0f, sd_cone( tracepos, &shadower->sdf ));
724 mindist = vg_minf( mindist, dist );
725 }
726
727 accum += vg_clampf( 1.0f - mindist, 0.0f, 1.0f )*0.2f;
728 }
729
730 vert->colour[1] = vg_minf( accum, 1.0f );
731 }
732 }
733
734 static void scene_upload( scene *pscene )
735 {
736 mesh_upload( &pscene->mesh,
737 pscene->verts, pscene->vertex_count,
738 pscene->indices, pscene->indice_count );
739
740 vg_info( "Scene upload\n" );
741 vg_info( " indices:%u\n", pscene->indice_count );
742 vg_info( " verts:%u\n", pscene->vertex_count );
743 }
744
745 float scene_tree_sway = 0.1f;
746
747 #if 0
748 static void scene_foliage_shader_use(void)
749 {
750 SHADER_USE( shader_debug_vcol );
751
752 glUniformMatrix4fv( SHADER_UNIFORM( shader_debug_vcol, "uPv" ),
753 1, GL_FALSE, (float *)vg_pv );
754
755 glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uMode" ), debugview );
756 glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uTexMain" ), 0 );
757
758 glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uTexGradients" ), 1 );
759 vg_tex2d_bind( &tex_gradients, 1 );
760
761 glUniform1i( SHADER_UNIFORM( shader_debug_vcol, "uTexNoise" ), 2 );
762 glActiveTexture( GL_TEXTURE2 );
763 glBindTexture( GL_TEXTURE_2D, tex_dual_noise );
764
765 glUniform1f( SHADER_UNIFORM( shader_debug_vcol, "uTime" ), vg_time );
766 glUniform1f( SHADER_UNIFORM( shader_debug_vcol, "uSwayAmt" ),
767 scene_tree_sway );
768 }
769 #endif
770
771 static void scene_bind( scene *pscene )
772 {
773 mesh_bind( &pscene->mesh );
774 }
775
776 static void scene_draw( scene *pscene )
777 {
778 mesh_drawn( 0, pscene->indice_count );
779 }
780
781 static void scene_debugsdf( scene *pscene )
782 {
783 for( int i=0; i<pscene->shadower_count; i++ )
784 {
785 struct shadower *shadower = &pscene->shadowers[i];
786
787 v3f base, side;
788 v3_copy( shadower->sdf.origin, base );
789 base[1] -= shadower->sdf.info[1];
790 v3_copy( base, side );
791 side[0] += shadower->sdf.info[0];
792
793 vg_line2( shadower->sdf.origin, base, 0xff00ff00, 0xff0000ff );
794 vg_line2( side, base, 0xff00ff00, 0xff0000ff );
795 vg_line( side, shadower->sdf.origin, 0xff00ff00 );
796 }
797
798 v3f p0 = { pscene->bbx[0][0], pscene->bbx[0][1], pscene->bbx[0][2] },
799 p1 = { pscene->bbx[0][0], pscene->bbx[1][1], pscene->bbx[0][2] },
800 p2 = { pscene->bbx[1][0], pscene->bbx[1][1], pscene->bbx[0][2] },
801 p3 = { pscene->bbx[1][0], pscene->bbx[0][1], pscene->bbx[0][2] },
802
803 p4 = { pscene->bbx[0][0], pscene->bbx[0][1], pscene->bbx[1][2] },
804 p5 = { pscene->bbx[0][0], pscene->bbx[1][1], pscene->bbx[1][2] },
805 p6 = { pscene->bbx[1][0], pscene->bbx[1][1], pscene->bbx[1][2] },
806 p7 = { pscene->bbx[1][0], pscene->bbx[0][1], pscene->bbx[1][2] };
807
808 u32 col = 0xffff00c8;
809 vg_line( p0, p1, col );
810 vg_line( p1, p2, col );
811 vg_line( p2, p3, col );
812 vg_line( p3, p0, col );
813
814 vg_line( p4, p5, col );
815 vg_line( p5, p6, col );
816 vg_line( p6, p7, col );
817 vg_line( p7, p4, col );
818
819 vg_line( p0, p4, col );
820 vg_line( p1, p5, col );
821 vg_line( p2, p6, col );
822 vg_line( p3, p7, col );
823 }
824
825 static void scene_register(void)
826 {
827 SHADER_INIT( shader_debug_vcol );
828 SHADER_INIT( shader_standard_lit );
829 SHADER_INIT( shader_unlit );
830 }
831
832
833 /* Physics segment */
834
835 static int triangle_raycast2d( v3f pA, v3f pB, v3f pC, v3f ray, float *height )
836 {
837 v2f v0, v1, v2, vp, vp2;
838 float d, bca = 0.f, bcb = 0.f, bcc = 0.f;
839
840 v0[0] = pB[0] - pA[0];
841 v0[1] = pB[2] - pA[2];
842 v1[0] = pC[0] - pA[0];
843 v1[1] = pC[2] - pA[2];
844 v2[0] = pB[0] - pC[0];
845 v2[1] = pB[2] - pC[2];
846
847 d = 1.f / (v0[0]*v1[1] - v1[0]*v0[1]);
848
849 #if 0
850 /* Backface culling */
851 if( v2_cross( v0, v1 ) > 0.f )
852 return;
853 #endif
854
855 vp[0] = ray[0] - pA[0];
856 vp[1] = ray[2] - pA[2];
857
858 if( v2_cross( v0, vp ) > 0.f ) return 0;
859 if( v2_cross( vp, v1 ) > 0.f ) return 0;
860
861 vp2[0] = ray[0] - pB[0];
862 vp2[1] = ray[2] - pB[2];
863
864 if( v2_cross( vp2, v2 ) > 0.f ) return 0;
865
866 bcb = (vp[0]*v1[1] - v1[0]*vp[1]) * d;
867 bcc = (v0[0]*vp[1] - vp[0]*v0[1]) * d;
868 bca = 1.f - bcb - bcc;
869
870 *height = pA[1]*bca + pB[1]*bcb + pC[1]*bcc;
871 return 1;
872 }
873
874 /* Temporary */
875 static int sample_scene_height( scene *pscene, v3f pos, v3f norm )
876 {
877 for( int i=0; i<pscene->indice_count/3; i++ )
878 {
879 u32 *tri = &pscene->indices[i*3];
880
881 float *pA = pscene->verts[tri[0]].co,
882 *pB = pscene->verts[tri[1]].co,
883 *pC = pscene->verts[tri[2]].co;
884
885 float height;
886 if( triangle_raycast2d( pA, pB, pC, pos, &height ))
887 {
888 pos[1] = height;
889
890 if( norm )
891 {
892 v3f v0, v1;
893 v3_sub( pA, pB, v0 );
894 v3_sub( pC, pB, v1 );
895 v3_cross( v1, v0, norm );
896 v3_normalize( norm );
897 }
898
899 return 1;
900 }
901 }
902 return 0;
903 }
904
905 static void sample_scene_normal( scene *pscene, v3f pos, v3f normal )
906 {
907 for( int i=0; i<pscene->indice_count/3; i++ )
908 {
909 u32 *tri = &pscene->indices[i*3];
910
911 float height;
912 if( triangle_raycast2d(
913 pscene->verts[ tri[0] ].co,
914 pscene->verts[ tri[1] ].co,
915 pscene->verts[ tri[2] ].co, pos, &height ))
916 {
917 v3f v0, v1;
918
919 v3_sub( pscene->verts[ tri[1] ].co,
920 pscene->verts[ tri[0] ].co,
921 v0 );
922
923 v3_sub( pscene->verts[ tri[2] ].co,
924 pscene->verts[ tri[0] ].co,
925 v1 );
926
927 v3_cross( v0, v1, normal );
928 v3_normalize( normal );
929 return;
930 }
931 }
932
933 normal[0] = 0.0f;
934 normal[1] = 1.0f;
935 normal[2] = 0.0f;
936 }
937
938 struct bvh_node
939 {
940 boxf bbx;
941
942 /* if il is 0, this is a leaf */
943 u32 il, count;
944 union{ u32 ir, start; };
945 };
946
947 static void bvh_update_bounds( scene *s, u32 inode )
948 {
949 bvh_node *node = &s->bvh.nodes[ inode ];
950
951 box_init_inf( node->bbx );
952 for( u32 i=0; i<node->count; i++ )
953 {
954 u32 idx = node->start+i;
955 model_vert *pa = &s->verts[ s->indices[idx*3+0] ],
956 *pb = &s->verts[ s->indices[idx*3+1] ],
957 *pc = &s->verts[ s->indices[idx*3+2] ];
958
959 box_addpt( node->bbx, pa->co );
960 box_addpt( node->bbx, pb->co );
961 box_addpt( node->bbx, pc->co );
962 }
963 }
964
965 static void bvh_subdiv( scene *s, u32 inode )
966 {
967 bvh_node *node = &s->bvh.nodes[ inode ];
968
969 v3f extent;
970 v3_sub( node->bbx[1], node->bbx[0], extent );
971
972 int axis = 0;
973 if( extent[1] > extent[0] ) axis = 1;
974 if( extent[2] > extent[axis] ) axis = 2;
975
976 float split = node->bbx[0][axis] + extent[axis]*0.5f;
977
978 /* To beat: 121,687 / 136,579
979 * 136,375
980 */
981
982 float avg = 0.0;
983 for( u32 t=0; t<node->count; t++ )
984 {
985 u32 *ti = &s->indices[(node->start+t)*3];
986 float a = s->verts[ti[0]].co[axis],
987 b = s->verts[ti[1]].co[axis],
988 c = s->verts[ti[2]].co[axis];
989 avg += (a+b+c)/3.0;
990 }
991 avg /= (float)node->count;
992
993 split = avg;
994
995 i32 i = node->start,
996 j = i + node->count-1;
997
998 while( i <= j )
999 {
1000 u32 *ti = &s->indices[i*3];
1001
1002 float a = s->verts[ti[0]].co[axis],
1003 b = s->verts[ti[1]].co[axis],
1004 c = s->verts[ti[2]].co[axis];
1005
1006 if( ((a+b+c) / 3.0f) < split )
1007 i ++;
1008 else
1009 {
1010 /* Swap triangle indices */
1011 u32 *tj = &s->indices[j*3];
1012 u32 temp[3];
1013 temp[0] = ti[0];
1014 temp[1] = ti[1];
1015 temp[2] = ti[2];
1016
1017 ti[0] = tj[0];
1018 ti[1] = tj[1];
1019 ti[2] = tj[2];
1020
1021 tj[0] = temp[0];
1022 tj[1] = temp[1];
1023 tj[2] = temp[2];
1024
1025 j --;
1026 }
1027 }
1028
1029 u32 left_count = i - node->start;
1030 if( left_count == 0 || left_count == node->count ) return;
1031
1032 u32 il = s->bvh.node_count ++,
1033 ir = s->bvh.node_count ++;
1034
1035 struct bvh_node *lnode = &s->bvh.nodes[il],
1036 *rnode = &s->bvh.nodes[ir];
1037
1038 lnode->start = node->start;
1039 lnode->count = left_count;
1040 rnode->start = i;
1041 rnode->count = node->count - left_count;
1042
1043 node->il = il;
1044 node->ir = ir;
1045 node->count = 0;
1046
1047 bvh_update_bounds( s, il );
1048 bvh_update_bounds( s, ir );
1049 bvh_subdiv( s, il );
1050 bvh_subdiv( s, ir );
1051 }
1052
1053 static void bvh_create( scene *s )
1054 {
1055 u32 triangle_count = s->indice_count / 3;
1056 s->bvh.nodes = malloc( sizeof(struct bvh_node) * (triangle_count*2-1) );
1057
1058 bvh_node *root = &s->bvh.nodes[0];
1059 s->bvh.node_count = 1;
1060
1061 root->il = 0;
1062 root->ir = 0;
1063 root->count = triangle_count;
1064 root->start = 0;
1065
1066 bvh_update_bounds( s, 0 );
1067 bvh_subdiv( s, 0 );
1068
1069 s->bvh.nodes =
1070 realloc( s->bvh.nodes, sizeof(struct bvh_node) * s->bvh.node_count );
1071
1072 vg_success( "BVH done, size: %u/%u\n", s->bvh.node_count,
1073 (triangle_count*2-1) );
1074 }
1075
1076 static void bvh_debug_node( scene *s, u32 inode, v3f pos, u32 colour )
1077 {
1078 struct bvh_node *node = &s->bvh.nodes[ inode ];
1079
1080 if( (pos[0] >= node->bbx[0][0] && pos[0] <= node->bbx[1][0]) &&
1081 (pos[2] >= node->bbx[0][2] && pos[2] <= node->bbx[1][2]) )
1082 {
1083 if( !node->count )
1084 {
1085 vg_line_boxf( node->bbx, colour );
1086
1087 bvh_debug_node( s, node->il, pos, colour );
1088 bvh_debug_node( s, node->ir, pos, colour );
1089 }
1090 else
1091 {
1092 vg_line_boxf( node->bbx, 0xff00ff00 );
1093 for( u32 i=0; i<node->count; i++ )
1094 {
1095 u32 idx = (node->start+i)*3;
1096
1097 model_vert *pa = &s->verts[ s->indices[ idx+0 ] ],
1098 *pb = &s->verts[ s->indices[ idx+1 ] ],
1099 *pc = &s->verts[ s->indices[ idx+2 ] ];
1100
1101 vg_line( pa->co, pb->co, 0xff0000ff );
1102 vg_line( pb->co, pc->co, 0xff0000ff );
1103 vg_line( pc->co, pa->co, 0xff0000ff );
1104 }
1105 }
1106 }
1107 }
1108
1109 static void bvh_debug( scene *s, v3f pos )
1110 {
1111 bvh_debug_node( s, 0, pos, 0x4000ffa8 );
1112 }
1113
1114 typedef struct ray_hit ray_hit;
1115 struct ray_hit
1116 {
1117 float dist;
1118 u32 *tri;
1119 v3f pos, normal;
1120 };
1121
1122 int ray_aabb( boxf box, v3f co, v3f dir, float dist )
1123 {
1124 v3f v0, v1;
1125 float tmin, tmax;
1126
1127 v3_sub( box[0], co, v0 );
1128 v3_sub( box[1], co, v1 );
1129 v3_div( v0, dir, v0 );
1130 v3_div( v1, dir, v1 );
1131
1132 tmin = vg_minf( v0[0], v1[0] );
1133 tmax = vg_maxf( v0[0], v1[0] );
1134 tmin = vg_maxf( tmin, vg_minf( v0[1], v1[1] ));
1135 tmax = vg_minf( tmax, vg_maxf( v0[1], v1[1] ));
1136 tmin = vg_maxf( tmin, vg_minf( v0[2], v1[2] ));
1137 tmax = vg_minf( tmax, vg_maxf( v0[2], v1[2] ));
1138
1139 return tmax >= tmin && tmin < dist && tmax > 0;
1140 }
1141
1142 static int bvh_ray_tri( scene *sc, u32 *tri, v3f co, v3f dir, ray_hit *hit )
1143 {
1144 float const kEpsilon = 0.00001f;
1145
1146 v3f v0, v1, h, s, q, n;
1147 float a,f,u,v,t;
1148
1149 float *pa = sc->verts[tri[0]].co,
1150 *pb = sc->verts[tri[1]].co,
1151 *pc = sc->verts[tri[2]].co;
1152
1153 v3_sub( pb, pa, v0 );
1154 v3_sub( pc, pa, v1 );
1155 v3_cross( dir, v1, h );
1156 v3_cross( v0, v1, n );
1157
1158 if( v3_dot( n, dir ) > 0.0f ) /* Backface culling */
1159 return 0;
1160
1161 /* Parralel */
1162 a = v3_dot( v0, h );
1163 if( a > -kEpsilon && a < kEpsilon )
1164 return 0;
1165
1166 f = 1.0f/a;
1167 v3_sub( co, pa, s );
1168
1169 u = f * v3_dot(s, h);
1170 if( u < 0.0f || u > 1.0f )
1171 return 0;
1172
1173 v3_cross( s, v0, q );
1174 v = f * v3_dot( dir, q );
1175 if( v < 0.0f || u+v > 1.0f )
1176 return 0;
1177
1178 t = f * v3_dot(v1, q);
1179 if( t > kEpsilon && t < hit->dist )
1180 {
1181 hit->dist = t;
1182 hit->tri = tri;
1183 return 1;
1184 }
1185 else return 0;
1186 }
1187
1188 static int bvh_ray( scene *s, u32 inode, v3f co, v3f dir, ray_hit *hit )
1189 {
1190 bvh_node *node = &s->bvh.nodes[ inode ];
1191
1192 if( !ray_aabb( node->bbx, co, dir, hit->dist ))
1193 return 0;
1194
1195 int count = 0;
1196
1197 if( node->count )
1198 {
1199 for( u32 i=0; i<node->count; i++ )
1200 {
1201 u32 *indices = &s->indices[ (node->start+i)*3 ];
1202 count += bvh_ray_tri( s, indices, co, dir, hit );
1203 }
1204 }
1205 else
1206 {
1207 count += bvh_ray( s, node->il, co, dir, hit );
1208 count += bvh_ray( s, node->ir, co, dir, hit );
1209 }
1210
1211 return count;
1212 }
1213
1214 static int bvh_raycast( scene *s, v3f co, v3f dir, ray_hit *hit )
1215 {
1216 v3f pb;
1217 v3_muladds( co, dir, hit->dist, pb );
1218
1219 int count = bvh_ray( s, 0, co, dir, hit );
1220
1221 if( count )
1222 {
1223 //vg_line( co, pb, 0xff00ffff );
1224
1225 v3f v0, v1;
1226
1227 float *pa = s->verts[hit->tri[0]].co,
1228 *pb = s->verts[hit->tri[1]].co,
1229 *pc = s->verts[hit->tri[2]].co;
1230
1231 v3_sub( pa, pb, v0 );
1232 v3_sub( pc, pb, v1 );
1233 v3_cross( v1, v0, hit->normal );
1234 v3_normalize( hit->normal );
1235 v3_muladds( co, dir, hit->dist, hit->pos );
1236 }
1237 else
1238 {
1239 //vg_line( co, pb, 0xff0000ff );
1240 }
1241
1242 return count;
1243 }
1244
1245 static int bvh_scene_sample_node_h( scene *s, u32 inode, v3f pos, v3f norm )
1246 {
1247 bvh_node *node = &s->bvh.nodes[ inode ];
1248
1249 if( (pos[0] >= node->bbx[0][0] && pos[0] <= node->bbx[1][0]) &&
1250 (pos[2] >= node->bbx[0][2] && pos[2] <= node->bbx[1][2]) )
1251 {
1252 if( !node->count )
1253 {
1254 if( bvh_scene_sample_node_h( s, node->il, pos, norm )) return 1;
1255 if( bvh_scene_sample_node_h( s, node->ir, pos, norm )) return 1;
1256 }
1257 else
1258 {
1259 for( u32 i=0; i<node->count; i++ )
1260 {
1261 u32 idx = (node->start+i)*3;
1262 model_vert *pa = &s->verts[ s->indices[ idx+0 ] ],
1263 *pb = &s->verts[ s->indices[ idx+1 ] ],
1264 *pc = &s->verts[ s->indices[ idx+2 ] ];
1265
1266 float height;
1267 if( triangle_raycast2d( pa->co, pb->co, pc->co, pos, &height ))
1268 {
1269 pos[1] = height;
1270
1271 if( norm )
1272 {
1273 v3f v0, v1;
1274 v3_sub( pa->co, pb->co, v0 );
1275 v3_sub( pc->co, pb->co, v1 );
1276 v3_cross( v1, v0, norm );
1277 v3_normalize( norm );
1278 }
1279
1280 return 1;
1281 }
1282 }
1283 }
1284 }
1285
1286 return 0;
1287 }
1288
1289 static int bvh_scene_sample_h( scene *s, v3f pos, v3f norm)
1290 {
1291 return bvh_scene_sample_node_h( s, 0, pos, norm );
1292 }
1293
1294 static int bvh_scene_sample( scene *s, v3f pos, ray_hit *hit )
1295 {
1296 hit->dist = INFINITY;
1297
1298 v3f ray_pos;
1299 v3_add( pos, (v3f){0.0f,4.0f,0.0f}, ray_pos );
1300
1301 if( bvh_raycast( s, ray_pos, (v3f){0.0f,-1.0f,0.0f}, hit ))
1302 {
1303 pos[1] = hit->pos[1];
1304 return 1;
1305 }
1306
1307 return 0;
1308 }
1309
1310 #endif