Initial project import
This commit is contained in:
commit
23f2d29e32
11957 files changed
+1754577
No files matched your search
@@ -0,0 +1,6 @@
|
||||
02_cubes_glsl/cube_glsl.h
|
||||
03_march_tracing_glsl/rt_glsl.h
|
||||
04_multi_shader_glsl/rt_glsl_march.h
|
||||
04_multi_shader_glsl/rt_glsl_puppy.h
|
||||
05_instancing_glsl/rt_glsl_instancing.h
|
||||
06_obj_viewer/gouraud.h
|
||||
@@ -0,0 +1,379 @@
|
||||
/**********************************************************************
|
||||
* Sokol 3d cube demo
|
||||
* Copyright (c) 2021 Dario Deledda. All rights reserved.
|
||||
* Use of this source code is governed by an MIT license
|
||||
* that can be found in the LICENSE file.
|
||||
* TODO:
|
||||
* - add instancing
|
||||
* - add an example with shaders
|
||||
**********************************************************************/
|
||||
import gg
|
||||
import math
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
import sokol.sgl
|
||||
|
||||
const win_width = 800
|
||||
const win_height = 800
|
||||
const bg_color = gg.white
|
||||
|
||||
struct App {
|
||||
mut:
|
||||
gg &gg.Context = unsafe { nil }
|
||||
pip_3d sgl.Pipeline
|
||||
texture gfx.Image
|
||||
sampler gfx.Sampler
|
||||
init_flag bool
|
||||
frame_count int
|
||||
mouse_x int = -1
|
||||
mouse_y int = -1
|
||||
}
|
||||
|
||||
fn create_texture(w int, h int, buf &u8) (gfx.Image, gfx.Sampler) {
|
||||
sz := w * h * 4
|
||||
mut img_desc := gfx.ImageDesc{
|
||||
width: w
|
||||
height: h
|
||||
num_mipmaps: 0
|
||||
// usage: .dynamic
|
||||
label: &char(unsafe { nil })
|
||||
d3d11_texture: 0
|
||||
}
|
||||
// comment, if .dynamic is enabled
|
||||
img_desc.data.subimage[0][0] = gfx.Range{
|
||||
ptr: buf
|
||||
size: usize(sz)
|
||||
}
|
||||
|
||||
sg_img := gfx.make_image(&img_desc)
|
||||
|
||||
mut smp_desc := gfx.SamplerDesc{
|
||||
min_filter: .linear
|
||||
mag_filter: .linear
|
||||
wrap_u: .clamp_to_edge
|
||||
wrap_v: .clamp_to_edge
|
||||
}
|
||||
|
||||
sg_smp := gfx.make_sampler(&smp_desc)
|
||||
return sg_img, sg_smp
|
||||
}
|
||||
|
||||
fn draw_triangle() {
|
||||
sgl.defaults()
|
||||
sgl.begin_triangles()
|
||||
sgl.v2f_c3b(0.0, 0.5, 255, 0, 0)
|
||||
sgl.v2f_c3b(-0.5, -0.5, 0, 0, 255)
|
||||
sgl.v2f_c3b(0.5, -0.5, 0, 255, 0)
|
||||
sgl.end()
|
||||
}
|
||||
|
||||
// vertex specification for a cube with colored sides and texture coords
|
||||
fn cube() {
|
||||
sgl.begin_quads()
|
||||
// edge color
|
||||
sgl.c3f(1.0, 0.0, 0.0)
|
||||
// edge coord
|
||||
// x,y,z, texture cord: u,v
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f(1.0, 1.0, -1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f(1.0, -1.0, -1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, -1.0, -1.0)
|
||||
sgl.c3f(0.0, 1.0, 0.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f(1.0, -1.0, 1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f(1.0, 1.0, 1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, -1.0, -1.0)
|
||||
sgl.c3f(0.0, 0.0, 1.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, -1.0, -1.0)
|
||||
sgl.c3f(1.0, 0.5, 0.0)
|
||||
sgl.v3f_t2f(1.0, -1.0, 1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f(1.0, -1.0, -1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f(1.0, 1.0, -1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(1.0, 1.0, 1.0, -1.0, -1.0)
|
||||
sgl.c3f(0.0, 0.5, 1.0)
|
||||
sgl.v3f_t2f(1.0, -1.0, -1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f(1.0, -1.0, 1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, -1.0, -1.0)
|
||||
sgl.c3f(1.0, 0.0, 0.5)
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f(1.0, 1.0, 1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(1.0, 1.0, -1.0, -1.0, -1.0)
|
||||
sgl.end()
|
||||
}
|
||||
|
||||
fn draw_cubes(app App) {
|
||||
rot := [f32(1.0) * (app.frame_count % 360), 0.5 * f32(app.frame_count % 360)]
|
||||
|
||||
sgl.defaults()
|
||||
sgl.load_pipeline(app.pip_3d)
|
||||
|
||||
sgl.matrix_mode_projection()
|
||||
sgl.perspective(sgl.rad(45.0), 1.0, 0.1, 100.0)
|
||||
|
||||
sgl.matrix_mode_modelview()
|
||||
sgl.translate(0.0, 0.0, -12.0)
|
||||
sgl.rotate(sgl.rad(rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate(sgl.rad(rot[1]), 0.0, 1.0, 0.0)
|
||||
cube()
|
||||
sgl.push_matrix()
|
||||
sgl.translate(0.0, 0.0, 3.0)
|
||||
sgl.scale(0.5, 0.5, 0.5)
|
||||
sgl.rotate(-2.0 * sgl.rad(rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate(-2.0 * sgl.rad(rot[1]), 0.0, 1.0, 0.0)
|
||||
cube()
|
||||
sgl.push_matrix()
|
||||
sgl.translate(0.0, 0.0, 3.0)
|
||||
sgl.scale(0.5, 0.5, 0.5)
|
||||
sgl.rotate(-3.0 * sgl.rad(2 * rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate(3.0 * sgl.rad(2 * rot[1]), 0.0, 0.0, 1.0)
|
||||
cube()
|
||||
sgl.pop_matrix()
|
||||
sgl.pop_matrix()
|
||||
}
|
||||
|
||||
fn cube_t(r f32, g f32, b f32) {
|
||||
sgl.begin_quads()
|
||||
// edge color
|
||||
sgl.c3f(r, g, b)
|
||||
// edge coord
|
||||
// x,y,z, texture cord: u,v
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, 0.0, 0.25)
|
||||
sgl.v3f_t2f(1.0, 1.0, -1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f(1.0, -1.0, -1.0, 0.25, 0.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, 0.0, 0.0)
|
||||
sgl.c3f(r, g, b)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, 0.0, 0.25)
|
||||
sgl.v3f_t2f(1.0, -1.0, 1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f(1.0, 1.0, 1.0, 0.25, 0.0)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, 0.0, 0.0)
|
||||
sgl.c3f(r, g, b)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, 0.0, 0.25)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, 0.25, 0.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, 0.0, 0.0)
|
||||
sgl.c3f(r, g, b)
|
||||
sgl.v3f_t2f(1.0, -1.0, 1.0, 0.0, 0.25)
|
||||
sgl.v3f_t2f(1.0, -1.0, -1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f(1.0, 1.0, -1.0, 0.25, 0.0)
|
||||
sgl.v3f_t2f(1.0, 1.0, 1.0, 0.0, 0.0)
|
||||
sgl.c3f(r, g, b)
|
||||
sgl.v3f_t2f(1.0, -1.0, -1.0, 0.0, 0.25)
|
||||
sgl.v3f_t2f(1.0, -1.0, 1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, 0.25, 0.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, 0.0, 0.0)
|
||||
sgl.c3f(r, g, b)
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, 0.0, 0.25)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f(1.0, 1.0, 1.0, 0.25, 0.0)
|
||||
sgl.v3f_t2f(1.0, 1.0, -1.0, 0.0, 0.0)
|
||||
sgl.end()
|
||||
}
|
||||
|
||||
fn draw_texture_cubes(app App) {
|
||||
rot := [f32(app.mouse_x), f32(app.mouse_y)]
|
||||
sgl.defaults()
|
||||
sgl.load_pipeline(app.pip_3d)
|
||||
|
||||
sgl.enable_texture()
|
||||
sgl.texture(app.texture, app.sampler)
|
||||
|
||||
sgl.matrix_mode_projection()
|
||||
sgl.perspective(sgl.rad(45.0), 1.0, 0.1, 100.0)
|
||||
|
||||
sgl.matrix_mode_modelview()
|
||||
sgl.translate(0.0, 0.0, -12.0)
|
||||
sgl.rotate(sgl.rad(rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate(sgl.rad(rot[1]), 0.0, 1.0, 0.0)
|
||||
cube_t(1, 1, 1)
|
||||
sgl.push_matrix()
|
||||
sgl.translate(0.0, 0.0, 3.0)
|
||||
sgl.scale(0.5, 0.5, 0.5)
|
||||
sgl.rotate(-2.0 * sgl.rad(rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate(-2.0 * sgl.rad(rot[1]), 0.0, 1.0, 0.0)
|
||||
cube_t(1, 1, 1)
|
||||
sgl.push_matrix()
|
||||
sgl.translate(0.0, 0.0, 3.0)
|
||||
sgl.scale(0.5, 0.5, 0.5)
|
||||
sgl.rotate(-3.0 * sgl.rad(2 * rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate(3.0 * sgl.rad(2 * rot[1]), 0.0, 0.0, 1.0)
|
||||
cube_t(1, 1, 1)
|
||||
sgl.pop_matrix()
|
||||
sgl.pop_matrix()
|
||||
|
||||
sgl.disable_texture()
|
||||
}
|
||||
|
||||
fn cube_field(app App) {
|
||||
rot := [f32(app.mouse_x), f32(app.mouse_y)]
|
||||
xyz_sz := f32(2.0)
|
||||
field_size := 20
|
||||
|
||||
sgl.defaults()
|
||||
sgl.load_pipeline(app.pip_3d)
|
||||
|
||||
sgl.enable_texture()
|
||||
sgl.texture(app.texture, app.sampler)
|
||||
|
||||
sgl.matrix_mode_projection()
|
||||
sgl.perspective(sgl.rad(45.0), 1.0, 0.1, 200.0)
|
||||
|
||||
sgl.matrix_mode_modelview()
|
||||
|
||||
sgl.translate(field_size, 0.0, -120.0)
|
||||
sgl.rotate(sgl.rad(rot[0]), 0.0, 1.0, 0.0)
|
||||
sgl.rotate(sgl.rad(rot[1]), 1.0, 0.0, 0.0)
|
||||
|
||||
// draw field_size*field_size cubes
|
||||
for y in 0 .. field_size {
|
||||
for x in 0 .. field_size {
|
||||
sgl.push_matrix()
|
||||
z := f32(math.cos(f32(x * 2) / field_size) * math.sin(f32(y * 2) / field_size) * xyz_sz) * (xyz_sz * 5)
|
||||
sgl.translate(x * xyz_sz, z, y * xyz_sz)
|
||||
cube_t(f32(f32(x) / field_size), f32(f32(y) / field_size), 1)
|
||||
sgl.pop_matrix()
|
||||
}
|
||||
}
|
||||
sgl.disable_texture()
|
||||
}
|
||||
|
||||
fn frame(mut app App) {
|
||||
ws := gg.window_size_real_pixels()
|
||||
ratio := f32(ws.width) / ws.height
|
||||
dw := ws.width
|
||||
dh := ws.height
|
||||
ww := int(dh / 3) // not a bug
|
||||
hh := int(dh / 3)
|
||||
x0 := int(f32(dw) * 0.05)
|
||||
// x1 := dw/2
|
||||
y0 := 0
|
||||
y1 := int(f32(dh) * 0.5)
|
||||
|
||||
app.gg.begin()
|
||||
// sgl.defaults()
|
||||
|
||||
// 2d triangle
|
||||
sgl.viewport(x0, y0, ww, hh, true)
|
||||
draw_triangle()
|
||||
|
||||
// colored cubes with viewport
|
||||
sgl.viewport(x0, y1, ww, hh, true)
|
||||
draw_cubes(app)
|
||||
|
||||
// textured cubed with viewport
|
||||
sgl.viewport(0, int(dh / 5), dw, int(dh * ratio), true)
|
||||
draw_texture_cubes(app)
|
||||
|
||||
// textured field of cubes with viewport
|
||||
sgl.viewport(0, int(dh / 5), dw, int(dh * ratio), true)
|
||||
cube_field(app)
|
||||
|
||||
app.frame_count++
|
||||
|
||||
app.gg.end()
|
||||
}
|
||||
|
||||
fn my_init(mut app App) {
|
||||
app.init_flag = true
|
||||
|
||||
// set max vertices,
|
||||
// for a large number of the same type of object it is better use the instances!!
|
||||
desc := sapp.create_desc()
|
||||
gfx.setup(&desc)
|
||||
sgl_desc := sgl.Desc{
|
||||
max_vertices: 50 * 65536
|
||||
}
|
||||
sgl.setup(&sgl_desc)
|
||||
|
||||
// 3d pipeline
|
||||
mut pipdesc := gfx.PipelineDesc{}
|
||||
unsafe { vmemset(&pipdesc, 0, int(sizeof(pipdesc))) }
|
||||
|
||||
color_state := gfx.ColorTargetState{
|
||||
blend: gfx.BlendState{
|
||||
enabled: true
|
||||
src_factor_rgb: .src_alpha
|
||||
dst_factor_rgb: .one_minus_src_alpha
|
||||
}
|
||||
}
|
||||
pipdesc.colors[0] = color_state
|
||||
|
||||
pipdesc.depth = gfx.DepthState{
|
||||
write_enabled: true
|
||||
compare: .less_equal
|
||||
}
|
||||
pipdesc.cull_mode = .back
|
||||
app.pip_3d = sgl.make_pipeline(&pipdesc)
|
||||
|
||||
// create chessboard texture 256*256 RGBA
|
||||
w := 256
|
||||
h := 256
|
||||
sz := w * h * 4
|
||||
tmp_txt := unsafe { malloc(sz) }
|
||||
mut i := 0
|
||||
for i < sz {
|
||||
unsafe {
|
||||
y := (i >> 0x8) >> 5 // 8 cell
|
||||
x := (i & 0xFF) >> 5 // 8 cell
|
||||
// upper left corner
|
||||
if x == 0 && y == 0 {
|
||||
tmp_txt[i] = u8(0xFF)
|
||||
tmp_txt[i + 1] = u8(0)
|
||||
tmp_txt[i + 2] = u8(0)
|
||||
tmp_txt[i + 3] = u8(0xFF)
|
||||
}
|
||||
// low right corner
|
||||
else if x == 7 && y == 7 {
|
||||
tmp_txt[i] = u8(0)
|
||||
tmp_txt[i + 1] = u8(0xFF)
|
||||
tmp_txt[i + 2] = u8(0)
|
||||
tmp_txt[i + 3] = u8(0xFF)
|
||||
} else {
|
||||
col := if ((x + y) & 1) == 1 { 0xFF } else { 0 }
|
||||
tmp_txt[i] = u8(col) // red
|
||||
tmp_txt[i + 1] = u8(col) // green
|
||||
tmp_txt[i + 2] = u8(col) // blue
|
||||
tmp_txt[i + 3] = u8(0xFF) // alpha
|
||||
}
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
app.texture, app.sampler = create_texture(w, h, tmp_txt)
|
||||
free(tmp_txt)
|
||||
}
|
||||
}
|
||||
|
||||
fn my_event_manager(mut ev gg.Event, mut app App) {
|
||||
if ev.typ == .mouse_move {
|
||||
app.mouse_x = int(ev.mouse_x)
|
||||
app.mouse_y = int(ev.mouse_y)
|
||||
}
|
||||
if ev.typ == .touches_began || ev.typ == .touches_moved {
|
||||
if ev.num_touches > 0 {
|
||||
touch_point := ev.touches[0]
|
||||
app.mouse_x = int(touch_point.pos_x)
|
||||
app.mouse_y = int(touch_point.pos_y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
mut app := &App{}
|
||||
app.gg = gg.new_context(
|
||||
width: win_width
|
||||
height: win_height
|
||||
create_window: true
|
||||
window_title: '3D Cube Demo'
|
||||
user_data: app
|
||||
bg_color: bg_color
|
||||
frame_fn: frame
|
||||
init_fn: my_init
|
||||
event_fn: my_event_manager
|
||||
)
|
||||
app.gg.run()
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// Shader code for texcube-sapp sample.
|
||||
//
|
||||
// NOTE: This source file also uses the '#pragma sokol' form of the
|
||||
// custom tags.
|
||||
//------------------------------------------------------------------------------
|
||||
//#pragma sokol @ctype mat4 my_mat4
|
||||
|
||||
#pragma sokol @vs vs
|
||||
uniform vs_params {
|
||||
mat4 mvp;
|
||||
};
|
||||
|
||||
in vec4 pos;
|
||||
in vec4 color0;
|
||||
in vec2 texcoord0;
|
||||
|
||||
out vec4 color;
|
||||
out vec2 uv;
|
||||
|
||||
void main() {
|
||||
gl_Position = mvp * pos;
|
||||
color = color0;
|
||||
uv = texcoord0;
|
||||
}
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @fs fs
|
||||
|
||||
uniform texture2D tex;
|
||||
uniform sampler smp;
|
||||
|
||||
uniform fs_params {
|
||||
vec2 text_res;
|
||||
float iTime;
|
||||
};
|
||||
|
||||
in vec4 color;
|
||||
in vec2 uv;
|
||||
out vec4 frag_color;
|
||||
|
||||
//*********************************************************
|
||||
// RAY TRACE
|
||||
// original code from: https://www.shadertoy.com/view/ldS3DW
|
||||
//*********************************************************
|
||||
float sphere(vec3 ray, vec3 dir, vec3 center, float radius)
|
||||
{
|
||||
vec3 rc = ray-center;
|
||||
float c = dot(rc, rc) - (radius*radius);
|
||||
float b = dot(dir, rc);
|
||||
float d = b*b - c;
|
||||
float t = -b - sqrt(abs(d));
|
||||
float st = step(0.0, min(t,d));
|
||||
return mix(-1.0, t, st);
|
||||
}
|
||||
|
||||
vec3 background(float t, vec3 rd)
|
||||
{
|
||||
vec3 light = normalize(vec3(sin(t), 0.6, cos(t)));
|
||||
float sun = max(0.0, dot(rd, light));
|
||||
float sky = max(0.0, dot(rd, vec3(0.0, 1.0, 0.0)));
|
||||
float ground = max(0.0, -dot(rd, vec3(0.0, 1.0, 0.0)));
|
||||
return (pow(sun, 256.0)+0.2*pow(sun, 2.0))*vec3(2.0, 1.6, 1.0) +
|
||||
pow(ground, 0.5)*vec3(0.4, 0.3, 0.2) +
|
||||
pow(sky, 1.0)*vec3(0.5, 0.6, 0.7);
|
||||
}
|
||||
|
||||
vec4 mainImage(vec2 fragCoord)
|
||||
{
|
||||
vec2 uv = (fragCoord-vec2(0.4,0.4))*2.0;
|
||||
|
||||
//vec2 uv = (-1.0 + 2.0*fc.xy / text_res.xy) * vec2(text_res.x/text_res.y, 1.0);
|
||||
vec3 ro = vec3(0.0, 0.0, -3.0);
|
||||
vec3 rd = normalize(vec3(uv, 1.0));
|
||||
vec3 p = vec3(0.0, 0.0, 0.0);
|
||||
float t = sphere(ro, rd, p, 1.0);
|
||||
vec3 nml = normalize(p - (ro+rd*t));
|
||||
vec3 bgCol = background(iTime, rd);
|
||||
rd = reflect(rd, nml);
|
||||
vec3 col = background(iTime, rd) * vec3(0.9, 0.8, 1.0);
|
||||
vec4 fragColor = vec4( mix(bgCol, col, step(0.0, t)), 1.0 );
|
||||
return fragColor;
|
||||
}
|
||||
//*********************************************************
|
||||
//*********************************************************
|
||||
|
||||
void main() {
|
||||
vec4 c = color;
|
||||
vec4 txt = texture(sampler2D(tex, smp), uv/4.0);
|
||||
c = txt * c;
|
||||
vec4 col_ray = mainImage(uv);
|
||||
float txt_mix = mod(iTime,5);
|
||||
frag_color = c*txt_mix*0.1 + col_ray ;
|
||||
}
|
||||
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @program cube vs fs
|
||||
@@ -0,0 +1,626 @@
|
||||
// vtest build: misc-tooling // needs .h files that are produced by `v shader`
|
||||
/**********************************************************************
|
||||
*
|
||||
* Sokol 3d cube demo
|
||||
*
|
||||
* Copyright (c) 2021 Dario Deledda. All rights reserved.
|
||||
* Use of this source code is governed by an MIT license
|
||||
* that can be found in the LICENSE file.
|
||||
*
|
||||
* HOW TO COMPILE SHADERS:
|
||||
* Run `v shader .` in this directory to compile the shaders.
|
||||
* For more info and help with shader compilation see `docs.md` and `v help shader`.
|
||||
*
|
||||
* TODO:
|
||||
* - add instancing
|
||||
**********************************************************************/
|
||||
import gg
|
||||
// import math
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
import sokol.sgl
|
||||
import time
|
||||
import gg.m4
|
||||
|
||||
// GLSL Include and functions
|
||||
#include "@VMODROOT/cube_glsl.h" # It should be generated with `v shader .` (see the instructions at the top of this file)
|
||||
|
||||
fn C.cube_shader_desc(gfx.Backend) &gfx.ShaderDesc
|
||||
|
||||
const win_width = 800
|
||||
const win_height = 800
|
||||
const bg_color = gg.white
|
||||
|
||||
struct App {
|
||||
mut:
|
||||
gg &gg.Context = unsafe { nil }
|
||||
pip_3d sgl.Pipeline
|
||||
texture gfx.Image
|
||||
sampler gfx.Sampler
|
||||
init_flag bool
|
||||
frame_count int
|
||||
mouse_x int = -1
|
||||
mouse_y int = -1
|
||||
// glsl
|
||||
cube_pip_glsl gfx.Pipeline
|
||||
cube_bind gfx.Bindings
|
||||
// time
|
||||
ticks i64
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
*
|
||||
* Texture functions
|
||||
*
|
||||
******************************************************************************/
|
||||
fn create_texture(w int, h int, buf &u8) (gfx.Image, gfx.Sampler) {
|
||||
sz := w * h * 4
|
||||
mut img_desc := gfx.ImageDesc{
|
||||
width: w
|
||||
height: h
|
||||
num_mipmaps: 0
|
||||
// usage: .dynamic
|
||||
label: &char(unsafe { nil })
|
||||
d3d11_texture: 0
|
||||
}
|
||||
// comment if .dynamic is enabled
|
||||
img_desc.data.subimage[0][0] = gfx.Range{
|
||||
ptr: buf
|
||||
size: usize(sz)
|
||||
}
|
||||
|
||||
sg_img := gfx.make_image(&img_desc)
|
||||
|
||||
mut smp_desc := gfx.SamplerDesc{
|
||||
min_filter: .linear
|
||||
mag_filter: .linear
|
||||
wrap_u: .clamp_to_edge
|
||||
wrap_v: .clamp_to_edge
|
||||
}
|
||||
|
||||
sg_smp := gfx.make_sampler(&smp_desc)
|
||||
return sg_img, sg_smp
|
||||
}
|
||||
|
||||
fn destroy_texture(sg_img gfx.Image) {
|
||||
gfx.destroy_image(sg_img)
|
||||
}
|
||||
|
||||
// Use only if usage: .dynamic is enabled
|
||||
fn update_text_texture(sg_img gfx.Image, w int, h int, buf &u8) {
|
||||
sz := w * h * 4
|
||||
mut tmp_sbc := gfx.ImageData{}
|
||||
tmp_sbc.subimage[0][0] = gfx.Range{
|
||||
ptr: buf
|
||||
size: usize(sz)
|
||||
}
|
||||
gfx.update_image(sg_img, &tmp_sbc)
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
*
|
||||
* Draw functions
|
||||
*
|
||||
******************************************************************************/
|
||||
fn draw_triangle() {
|
||||
sgl.defaults()
|
||||
sgl.begin_triangles()
|
||||
{
|
||||
// vfmt off
|
||||
sgl.v2f_c3b( 0.0, 0.5, 255, 0 , 0 )
|
||||
sgl.v2f_c3b(-0.5, -0.5, 0, 0 , 255)
|
||||
sgl.v2f_c3b( 0.5, -0.5, 0, 255, 0 )
|
||||
// vfmt on
|
||||
}
|
||||
sgl.end()
|
||||
}
|
||||
|
||||
// vertex specification for a cube with colored sides and texture coords
|
||||
fn cube() {
|
||||
sgl.begin_quads()
|
||||
{
|
||||
// vfmt off
|
||||
sgl.c3f(1.0, 0.0, 0.0) // edge color
|
||||
// edge coordinates
|
||||
// x,y,z, texture cord: u,v
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f( 1.0, 1.0, -1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f( 1.0, -1.0, -1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, -1.0, -1.0)
|
||||
sgl.c3f(0.0, 1.0, 0.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f( 1.0, -1.0, 1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f( 1.0, 1.0, 1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, -1.0, -1.0)
|
||||
sgl.c3f(0.0, 0.0, 1.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, -1.0, -1.0)
|
||||
sgl.c3f(1.0, 0.5, 0.0)
|
||||
sgl.v3f_t2f(1.0, -1.0, 1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f(1.0, -1.0, -1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f(1.0, 1.0, -1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(1.0, 1.0, 1.0, -1.0, -1.0)
|
||||
sgl.c3f(0.0, 0.5, 1.0)
|
||||
sgl.v3f_t2f( 1.0, -1.0, -1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f( 1.0, -1.0, 1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, -1.0, -1.0)
|
||||
sgl.c3f(1.0, 0.0, 0.5)
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, -1.0, 1.0)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, 1.0, 1.0)
|
||||
sgl.v3f_t2f( 1.0, 1.0, 1.0, 1.0, -1.0)
|
||||
sgl.v3f_t2f( 1.0, 1.0, -1.0, -1.0, -1.0)
|
||||
// vfmt on
|
||||
}
|
||||
sgl.end()
|
||||
}
|
||||
|
||||
fn draw_cubes(app App) {
|
||||
rot := [f32(1.0) * (app.frame_count % 360), 0.5 * f32(app.frame_count % 360)]
|
||||
// rot := [f32(app.mouse_x), f32(app.mouse_y)]
|
||||
|
||||
sgl.defaults()
|
||||
sgl.load_pipeline(app.pip_3d)
|
||||
|
||||
sgl.matrix_mode_projection()
|
||||
sgl.perspective(sgl.rad(45.0), 1.0, 0.1, 100.0)
|
||||
|
||||
sgl.matrix_mode_modelview()
|
||||
sgl.translate(0.0, 0.0, -12.0)
|
||||
sgl.rotate(sgl.rad(rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate(sgl.rad(rot[1]), 0.0, 1.0, 0.0)
|
||||
cube()
|
||||
sgl.push_matrix()
|
||||
{
|
||||
sgl.translate(0.0, 0.0, 3.0)
|
||||
sgl.scale(0.5, 0.5, 0.5)
|
||||
sgl.rotate(-2.0 * sgl.rad(rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate(-2.0 * sgl.rad(rot[1]), 0.0, 1.0, 0.0)
|
||||
cube()
|
||||
sgl.push_matrix()
|
||||
{
|
||||
sgl.translate(0.0, 0.0, 3.0)
|
||||
sgl.scale(0.5, 0.5, 0.5)
|
||||
// vfmt off
|
||||
sgl.rotate(-3.0 * sgl.rad(2 * rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate( 3.0 * sgl.rad(2 * rot[1]), 0.0, 0.0, 1.0)
|
||||
// vfmt on
|
||||
cube()
|
||||
}
|
||||
sgl.pop_matrix()
|
||||
}
|
||||
sgl.pop_matrix()
|
||||
}
|
||||
|
||||
fn cube_texture(r f32, g f32, b f32) {
|
||||
sgl.begin_quads()
|
||||
{
|
||||
sgl.c3f(r, g, b) // edge color
|
||||
// edge coord
|
||||
// x,y,z, texture cord: u,v
|
||||
// vfmt off
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, 0.0 , 0.25)
|
||||
sgl.v3f_t2f( 1.0, 1.0, -1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f( 1.0, -1.0, -1.0, 0.25, 0.0 )
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, 0.0 , 0.0 )
|
||||
sgl.c3f(r, g, b)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, 0.0 , 0.25)
|
||||
sgl.v3f_t2f( 1.0, -1.0, 1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f( 1.0, 1.0, 1.0, 0.25, 0.0 )
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, 0.0 , 0.0 )
|
||||
sgl.c3f(r, g, b)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, 0.0 , 0.25)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, 0.25, 0.0 )
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, 0.0 , 0.0 )
|
||||
sgl.c3f(r, g, b)
|
||||
sgl.v3f_t2f(1.0, -1.0, 1.0, 0.0 , 0.25)
|
||||
sgl.v3f_t2f(1.0, -1.0, -1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f(1.0, 1.0, -1.0, 0.25, 0.0 )
|
||||
sgl.v3f_t2f(1.0, 1.0, 1.0, 0.0 , 0.0 )
|
||||
sgl.c3f(r, g, b)
|
||||
sgl.v3f_t2f( 1.0, -1.0, -1.0, 0.0 , 0.25)
|
||||
sgl.v3f_t2f( 1.0, -1.0, 1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f(-1.0, -1.0, 1.0, 0.25, 0.0 )
|
||||
sgl.v3f_t2f(-1.0, -1.0, -1.0, 0.0 , 0.0 )
|
||||
sgl.c3f(r, g, b)
|
||||
sgl.v3f_t2f(-1.0, 1.0, -1.0, 0.0 , 0.25)
|
||||
sgl.v3f_t2f(-1.0, 1.0, 1.0, 0.25, 0.25)
|
||||
sgl.v3f_t2f( 1.0, 1.0, 1.0, 0.25, 0.0 )
|
||||
sgl.v3f_t2f( 1.0, 1.0, -1.0, 0.0 , 0.0 )
|
||||
// vfmt on
|
||||
}
|
||||
sgl.end()
|
||||
}
|
||||
|
||||
/*
|
||||
Cube vertex buffer with packed vertex formats for color and texture coords.
|
||||
Note that a vertex format which must be portable across all
|
||||
backends must only use the normalized integer formats
|
||||
(BYTE4N, UBYTE4N, SHORT2N, SHORT4N), which can be converted
|
||||
to floating point formats in the vertex shader inputs.
|
||||
The reason is that D3D11 cannot convert from non-normalized
|
||||
formats to floating point inputs (only to integer inputs),
|
||||
and WebGL2 / GLES2 don't support integer vertex shader inputs.
|
||||
*/
|
||||
|
||||
struct Vertex_t {
|
||||
x f32
|
||||
y f32
|
||||
z f32
|
||||
color u32
|
||||
// u u16
|
||||
// v u16
|
||||
u f32
|
||||
v f32
|
||||
}
|
||||
|
||||
fn init_cube_glsl(mut app App) {
|
||||
// cube vertex buffer
|
||||
// d := u16(32767/8) // for compatibility with D3D11, 32767 stand for 1
|
||||
d := f32(1.0) // 0.05)
|
||||
c := u32(0xFFFFFF_FF) // color RGBA8
|
||||
// vfmt off
|
||||
vertices := [
|
||||
// Face 0
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{ 1.0, -1.0, -1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, -1.0, c, d, d},
|
||||
Vertex_t{-1.0, 1.0, -1.0, c, 0, d},
|
||||
// Face 1
|
||||
Vertex_t{-1.0, -1.0, 1.0, c, 0, 0},
|
||||
Vertex_t{ 1.0, -1.0, 1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{-1.0, 1.0, 1.0, c, 0, d},
|
||||
// Face 2
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{-1.0, 1.0, -1.0, c, d, 0},
|
||||
Vertex_t{-1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{-1.0, -1.0, 1.0, c, 0, d},
|
||||
// Face 3
|
||||
Vertex_t{ 1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{ 1.0, 1.0, -1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{ 1.0, -1.0, 1.0, c, 0, d},
|
||||
// Face 4
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{-1.0, -1.0, 1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, -1.0, 1.0, c, d, d},
|
||||
Vertex_t{ 1.0, -1.0, -1.0, c, 0, d},
|
||||
// Face 5
|
||||
Vertex_t{-1.0, 1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{-1.0, 1.0, 1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{ 1.0, 1.0, -1.0, c, 0, d},
|
||||
]
|
||||
// vfmt on
|
||||
|
||||
mut vert_buffer_desc := gfx.BufferDesc{
|
||||
label: c'cube-vertices'
|
||||
}
|
||||
unsafe { vmemset(&vert_buffer_desc, 0, int(sizeof(vert_buffer_desc))) }
|
||||
|
||||
vert_buffer_desc.size = usize(vertices.len * int(sizeof(Vertex_t)))
|
||||
vert_buffer_desc.data = gfx.Range{
|
||||
ptr: vertices.data
|
||||
size: usize(vertices.len * int(sizeof(Vertex_t)))
|
||||
}
|
||||
|
||||
vert_buffer_desc.type = .vertexbuffer
|
||||
// vert_buffer_desc.usage = .immutable
|
||||
vbuf := gfx.make_buffer(&vert_buffer_desc)
|
||||
|
||||
// create an index buffer for the cube
|
||||
// vfmt off
|
||||
indices := [
|
||||
u16(0), 1, 2, 0, 2, 3,
|
||||
6, 5, 4, 7, 6, 4,
|
||||
8, 9, 10, 8, 10, 11,
|
||||
14, 13, 12, 15, 14, 12,
|
||||
16, 17, 18, 16, 18, 19,
|
||||
22, 21, 20, 23, 22, 20,
|
||||
]
|
||||
// vfmt on
|
||||
|
||||
mut index_buffer_desc := gfx.BufferDesc{
|
||||
label: c'cube-indices'
|
||||
}
|
||||
unsafe { vmemset(&index_buffer_desc, 0, int(sizeof(index_buffer_desc))) }
|
||||
|
||||
index_buffer_desc.size = usize(indices.len * int(sizeof(u16)))
|
||||
index_buffer_desc.data = gfx.Range{
|
||||
ptr: indices.data
|
||||
size: usize(indices.len * int(sizeof(u16)))
|
||||
}
|
||||
|
||||
index_buffer_desc.type = .indexbuffer
|
||||
ibuf := gfx.make_buffer(&index_buffer_desc)
|
||||
|
||||
// create shader
|
||||
shader := gfx.make_shader(voidptr(C.cube_shader_desc(C.sg_query_backend())))
|
||||
|
||||
mut pipdesc := gfx.PipelineDesc{}
|
||||
unsafe { vmemset(&pipdesc, 0, int(sizeof(pipdesc))) }
|
||||
|
||||
pipdesc.layout.buffers[0].stride = int(sizeof(Vertex_t))
|
||||
// the constants [C.ATTR_vs_pos, C.ATTR_vs_color0, C.ATTR_vs_texcoord0] are generated bysokol-shdc
|
||||
pipdesc.layout.attrs[C.ATTR_vs_pos].format = .float3 // x,y,z as f32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_color0].format = .ubyte4n // color as u32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_texcoord0].format = .float2 // u,v as f32
|
||||
// pipdesc.layout.attrs[C.ATTR_vs_texcoord0].format = .short2n // u,v as u16
|
||||
|
||||
pipdesc.shader = shader
|
||||
pipdesc.index_type = .uint16
|
||||
|
||||
pipdesc.depth = gfx.DepthState{
|
||||
write_enabled: true
|
||||
compare: .less_equal
|
||||
}
|
||||
pipdesc.cull_mode = .back
|
||||
|
||||
pipdesc.label = c'glsl_shader pipeline'
|
||||
|
||||
app.cube_bind.vertex_buffers[0] = vbuf
|
||||
app.cube_bind.index_buffer = ibuf
|
||||
app.cube_bind.fs.images[C.SLOT_tex] = app.texture
|
||||
app.cube_bind.fs.samplers[C.SLOT_smp] = app.sampler
|
||||
app.cube_pip_glsl = gfx.make_pipeline(&pipdesc)
|
||||
println('GLSL init DONE!')
|
||||
}
|
||||
|
||||
fn draw_cube_glsl(app App) {
|
||||
if app.init_flag == false {
|
||||
return
|
||||
}
|
||||
|
||||
// clear
|
||||
ws := gg.window_size_real_pixels()
|
||||
mut color_action := gfx.ColorAttachmentAction{
|
||||
load_action: unsafe { gfx.LoadAction(C.SG_LOADACTION_DONTCARE) } // C.SG_ACTION_CLEAR)
|
||||
clear_value: gfx.Color{
|
||||
r: 1.0
|
||||
g: 1.0
|
||||
b: 1.0
|
||||
a: 1.0
|
||||
}
|
||||
}
|
||||
mut pass_action := gfx.PassAction{}
|
||||
pass_action.colors[0] = color_action
|
||||
pass := sapp.create_default_pass(pass_action)
|
||||
gfx.begin_pass(&pass)
|
||||
{
|
||||
rot := [f32(app.mouse_y), f32(app.mouse_x)]
|
||||
// ratio := f32(ws.width)/ws.height
|
||||
dw := f32(ws.width / 2)
|
||||
dh := f32(ws.height / 2)
|
||||
|
||||
tr_matrix := m4.calc_tr_matrices(dw, dh, rot[0], rot[1], 2.0)
|
||||
gfx.apply_viewport(ws.width / 2, 0, ws.width / 2, ws.height / 2, true)
|
||||
|
||||
// apply the pipeline and bindings
|
||||
gfx.apply_pipeline(app.cube_pip_glsl)
|
||||
gfx.apply_bindings(app.cube_bind)
|
||||
|
||||
// Uniforms:
|
||||
// passing the view matrix as uniform
|
||||
// res is a 4x4 matrix of f32 thus: 4*16 byte of size
|
||||
vs_uniforms_range := gfx.Range{
|
||||
ptr: &tr_matrix
|
||||
size: usize(4 * 16)
|
||||
}
|
||||
gfx.apply_uniforms(.vs, C.SLOT_vs_params, &vs_uniforms_range)
|
||||
|
||||
// fs uniforms
|
||||
time_ticks := f32(time.ticks() - app.ticks) / 1000
|
||||
mut text_res := [
|
||||
f32(512),
|
||||
512, // x,y resolution to pass to FS
|
||||
time_ticks, // time as f32
|
||||
0, // padding 4 Bytes == 1 f32
|
||||
]!
|
||||
fs_uniforms_range := gfx.Range{
|
||||
ptr: unsafe { &text_res }
|
||||
size: usize(4 * 4)
|
||||
}
|
||||
gfx.apply_uniforms(.fs, C.SLOT_fs_params, &fs_uniforms_range)
|
||||
|
||||
gfx.draw(0, (3 * 2) * 6, 1)
|
||||
}
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
|
||||
fn draw_texture_cubes(app App) {
|
||||
rot := [f32(app.mouse_x), f32(app.mouse_y)]
|
||||
sgl.defaults()
|
||||
sgl.load_pipeline(app.pip_3d)
|
||||
|
||||
sgl.enable_texture()
|
||||
sgl.texture(app.texture, app.sampler)
|
||||
|
||||
sgl.matrix_mode_projection()
|
||||
sgl.perspective(sgl.rad(45.0), 1.0, 0.1, 100.0)
|
||||
|
||||
sgl.matrix_mode_modelview()
|
||||
sgl.translate(0.0, 0.0, -12.0)
|
||||
sgl.rotate(sgl.rad(rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate(sgl.rad(rot[1]), 0.0, 1.0, 0.0)
|
||||
cube_texture(1, 1, 1)
|
||||
|
||||
sgl.push_matrix()
|
||||
{
|
||||
sgl.translate(0.0, 0.0, 3.0)
|
||||
sgl.scale(0.5, 0.5, 0.5)
|
||||
sgl.rotate(-2.0 * sgl.rad(rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate(-2.0 * sgl.rad(rot[1]), 0.0, 1.0, 0.0)
|
||||
cube_texture(1, 1, 1)
|
||||
sgl.push_matrix()
|
||||
{
|
||||
sgl.translate(0.0, 0.0, 3.0)
|
||||
sgl.scale(0.5, 0.5, 0.5)
|
||||
// vfmt off
|
||||
sgl.rotate(-3.0 * sgl.rad(2 * rot[0]), 1.0, 0.0, 0.0)
|
||||
sgl.rotate( 3.0 * sgl.rad(2 * rot[1]), 0.0, 0.0, 1.0)
|
||||
// vfmt on
|
||||
cube_texture(1, 1, 1)
|
||||
}
|
||||
sgl.pop_matrix()
|
||||
}
|
||||
sgl.pop_matrix()
|
||||
|
||||
sgl.disable_texture()
|
||||
}
|
||||
|
||||
fn frame(mut app App) {
|
||||
ws := gg.window_size_real_pixels()
|
||||
ratio := f32(ws.width) / ws.height
|
||||
dw := ws.width
|
||||
dh := ws.height
|
||||
ww := int(dh / 3) // not a bug
|
||||
hh := int(dh / 3)
|
||||
x0 := int(f32(dw) * 0.05)
|
||||
// x1 := dw/2
|
||||
y0 := 0
|
||||
y1 := int(f32(dh) * 0.5)
|
||||
|
||||
app.gg.begin()
|
||||
{
|
||||
sgl.defaults()
|
||||
|
||||
// 2d triangle
|
||||
sgl.viewport(x0, y0, ww, hh, true)
|
||||
draw_triangle()
|
||||
|
||||
// colored cubes with viewport
|
||||
sgl.viewport(x0, y1, ww, hh, true)
|
||||
draw_cubes(app)
|
||||
|
||||
// textured cubed with viewport
|
||||
sgl.viewport(0, int(dh / 5), dw, int(dh * ratio), true)
|
||||
draw_texture_cubes(app)
|
||||
}
|
||||
app.gg.end()
|
||||
|
||||
// glsl cube
|
||||
draw_cube_glsl(app)
|
||||
|
||||
app.frame_count++
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Init / Cleanup
|
||||
******************************************************************************/
|
||||
fn my_init(mut app App) {
|
||||
// set max vertices,
|
||||
// for a large number of the same type of object it is better use the instances!!
|
||||
desc := sapp.create_desc()
|
||||
gfx.setup(&desc)
|
||||
sgl_desc := sgl.Desc{
|
||||
max_vertices: 50 * 65536
|
||||
}
|
||||
sgl.setup(&sgl_desc)
|
||||
|
||||
// 3d pipeline
|
||||
mut pipdesc := gfx.PipelineDesc{}
|
||||
unsafe { vmemset(&pipdesc, 0, int(sizeof(pipdesc))) }
|
||||
|
||||
color_state := gfx.ColorTargetState{
|
||||
blend: gfx.BlendState{
|
||||
enabled: true
|
||||
src_factor_rgb: .src_alpha
|
||||
dst_factor_rgb: .one_minus_src_alpha
|
||||
}
|
||||
}
|
||||
pipdesc.colors[0] = color_state
|
||||
|
||||
pipdesc.depth = gfx.DepthState{
|
||||
write_enabled: true
|
||||
compare: .less_equal
|
||||
}
|
||||
pipdesc.cull_mode = .back
|
||||
|
||||
app.pip_3d = sgl.make_pipeline(&pipdesc)
|
||||
|
||||
// create chessboard texture 256*256 RGBA
|
||||
w := 256
|
||||
h := 256
|
||||
sz := w * h * 4
|
||||
tmp_txt := unsafe { malloc(sz) }
|
||||
mut i := 0
|
||||
for i < sz {
|
||||
unsafe {
|
||||
y := (i >> 0x8) >> 5 // 8 cell
|
||||
x := (i & 0xFF) >> 5 // 8 cell
|
||||
// upper left corner
|
||||
if x == 0 && y == 0 {
|
||||
tmp_txt[i] = u8(0xFF)
|
||||
tmp_txt[i + 1] = u8(0)
|
||||
tmp_txt[i + 2] = u8(0)
|
||||
tmp_txt[i + 3] = u8(0xFF)
|
||||
}
|
||||
// low right corner
|
||||
else if x == 7 && y == 7 {
|
||||
tmp_txt[i + 0] = u8(0)
|
||||
tmp_txt[i + 1] = u8(0xFF)
|
||||
tmp_txt[i + 2] = u8(0)
|
||||
tmp_txt[i + 3] = u8(0xFF)
|
||||
} else {
|
||||
col := if ((x + y) & 1) == 1 { 0xFF } else { 128 }
|
||||
tmp_txt[i + 0] = u8(col) // red
|
||||
tmp_txt[i + 1] = u8(col) // green
|
||||
tmp_txt[i + 2] = u8(col) // blue
|
||||
tmp_txt[i + 3] = u8(0xFF) // alpha
|
||||
}
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
app.texture, app.sampler = create_texture(w, h, tmp_txt)
|
||||
unsafe { free(tmp_txt) }
|
||||
|
||||
// glsl
|
||||
init_cube_glsl(mut app)
|
||||
app.init_flag = true
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* event
|
||||
******************************************************************************/
|
||||
fn my_event_manager(mut ev gg.Event, mut app App) {
|
||||
if ev.typ == .mouse_move {
|
||||
app.mouse_x = int(ev.mouse_x)
|
||||
app.mouse_y = int(ev.mouse_y)
|
||||
}
|
||||
if ev.typ == .touches_began || ev.typ == .touches_moved {
|
||||
if ev.num_touches > 0 {
|
||||
touch_point := ev.touches[0]
|
||||
app.mouse_x = int(touch_point.pos_x)
|
||||
app.mouse_y = int(touch_point.pos_y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// App init
|
||||
mut app := &App{}
|
||||
|
||||
mut a := [5]int{}
|
||||
a[0] = 2
|
||||
println(a)
|
||||
|
||||
app.gg = gg.new_context(
|
||||
width: win_width
|
||||
height: win_height
|
||||
create_window: true
|
||||
window_title: '3D Cube Demo'
|
||||
user_data: app
|
||||
bg_color: bg_color
|
||||
frame_fn: frame
|
||||
init_fn: my_init
|
||||
event_fn: my_event_manager
|
||||
)
|
||||
|
||||
app.ticks = time.ticks()
|
||||
app.gg.run()
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,696 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// Shader code for texcube-sapp sample.
|
||||
//
|
||||
// NOTE: This source file also uses the '#pragma sokol' form of the
|
||||
// custom tags.
|
||||
//------------------------------------------------------------------------------
|
||||
//#pragma sokol @ctype mat4 hmm_mat4
|
||||
|
||||
#pragma sokol @vs vs
|
||||
uniform vs_params {
|
||||
mat4 mvp;
|
||||
};
|
||||
|
||||
in vec4 pos;
|
||||
in vec4 color0;
|
||||
in vec2 texcoord0;
|
||||
|
||||
out vec4 color;
|
||||
out vec2 uv;
|
||||
|
||||
void main() {
|
||||
gl_Position = mvp * pos;
|
||||
color = color0;
|
||||
uv = texcoord0;
|
||||
}
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @fs fs
|
||||
uniform texture2D tex;
|
||||
uniform sampler smp;
|
||||
uniform fs_params {
|
||||
vec2 iResolution;
|
||||
vec2 iMouse;
|
||||
float iTime;
|
||||
float iFrame;
|
||||
};
|
||||
|
||||
in vec4 color;
|
||||
in vec2 uv;
|
||||
out vec4 frag_color;
|
||||
|
||||
// change to 0 to 4 to increment the AntiAliasing,
|
||||
// increase AA will SLOW the rendering!!
|
||||
#define AA 1
|
||||
|
||||
//*********************************************************
|
||||
// Ray Marching
|
||||
// original code from: https://www.shadertoy.com/view/Xds3zN
|
||||
//*********************************************************
|
||||
// The MIT License
|
||||
// Copyright © 2013 Inigo Quilez
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
// A list of useful distance function to simple primitives. All
|
||||
// these functions (except for ellipsoid) return an exact
|
||||
// euclidean distance, meaning they produce a better SDF than
|
||||
// what you'd get if you were constructing them from boolean
|
||||
// operations.
|
||||
//
|
||||
// More info here:
|
||||
//
|
||||
// https://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
|
||||
|
||||
//------------------------------------------------------------------
|
||||
float dot2( in vec2 v ) { return dot(v,v); }
|
||||
float dot2( in vec3 v ) { return dot(v,v); }
|
||||
float ndot( in vec2 a, in vec2 b ) { return a.x*b.x - a.y*b.y; }
|
||||
|
||||
float sdPlane( vec3 p )
|
||||
{
|
||||
return p.y;
|
||||
}
|
||||
|
||||
float sdSphere( vec3 p, float s )
|
||||
{
|
||||
return length(p)-s;
|
||||
}
|
||||
|
||||
float sdBox( vec3 p, vec3 b )
|
||||
{
|
||||
vec3 d = abs(p) - b;
|
||||
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
|
||||
}
|
||||
|
||||
float sdBoundingBox( vec3 p, vec3 b, float e )
|
||||
{
|
||||
p = abs(p )-b;
|
||||
vec3 q = abs(p+e)-e;
|
||||
|
||||
return min(min(
|
||||
length(max(vec3(p.x,q.y,q.z),0.0))+min(max(p.x,max(q.y,q.z)),0.0),
|
||||
length(max(vec3(q.x,p.y,q.z),0.0))+min(max(q.x,max(p.y,q.z)),0.0)),
|
||||
length(max(vec3(q.x,q.y,p.z),0.0))+min(max(q.x,max(q.y,p.z)),0.0));
|
||||
}
|
||||
float sdEllipsoid( in vec3 p, in vec3 r ) // approximated
|
||||
{
|
||||
float k0 = length(p/r);
|
||||
float k1 = length(p/(r*r));
|
||||
return k0*(k0-1.0)/k1;
|
||||
}
|
||||
|
||||
float sdTorus( vec3 p, vec2 t )
|
||||
{
|
||||
return length( vec2(length(p.xz)-t.x,p.y) )-t.y;
|
||||
}
|
||||
|
||||
float sdCappedTorus(in vec3 p, in vec2 sc, in float ra, in float rb)
|
||||
{
|
||||
p.x = abs(p.x);
|
||||
float k = (sc.y*p.x>sc.x*p.y) ? dot(p.xy,sc) : length(p.xy);
|
||||
return sqrt( dot(p,p) + ra*ra - 2.0*ra*k ) - rb;
|
||||
}
|
||||
|
||||
float sdHexPrism( vec3 p, vec2 h )
|
||||
{
|
||||
vec3 q = abs(p);
|
||||
|
||||
const vec3 k = vec3(-0.8660254, 0.5, 0.57735);
|
||||
p = abs(p);
|
||||
p.xy -= 2.0*min(dot(k.xy, p.xy), 0.0)*k.xy;
|
||||
vec2 d = vec2(
|
||||
length(p.xy - vec2(clamp(p.x, -k.z*h.x, k.z*h.x), h.x))*sign(p.y - h.x),
|
||||
p.z-h.y );
|
||||
return min(max(d.x,d.y),0.0) + length(max(d,0.0));
|
||||
}
|
||||
|
||||
float sdOctogonPrism( in vec3 p, in float r, float h )
|
||||
{
|
||||
const vec3 k = vec3(-0.9238795325, // sqrt(2+sqrt(2))/2
|
||||
0.3826834323, // sqrt(2-sqrt(2))/2
|
||||
0.4142135623 ); // sqrt(2)-1
|
||||
// reflections
|
||||
p = abs(p);
|
||||
p.xy -= 2.0*min(dot(vec2( k.x,k.y),p.xy),0.0)*vec2( k.x,k.y);
|
||||
p.xy -= 2.0*min(dot(vec2(-k.x,k.y),p.xy),0.0)*vec2(-k.x,k.y);
|
||||
// polygon side
|
||||
p.xy -= vec2(clamp(p.x, -k.z*r, k.z*r), r);
|
||||
vec2 d = vec2( length(p.xy)*sign(p.y), p.z-h );
|
||||
return min(max(d.x,d.y),0.0) + length(max(d,0.0));
|
||||
}
|
||||
|
||||
float sdCapsule( vec3 p, vec3 a, vec3 b, float r )
|
||||
{
|
||||
vec3 pa = p-a, ba = b-a;
|
||||
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
|
||||
return length( pa - ba*h ) - r;
|
||||
}
|
||||
|
||||
float sdRoundCone( in vec3 p, in float r1, float r2, float h )
|
||||
{
|
||||
vec2 q = vec2( length(p.xz), p.y );
|
||||
|
||||
float b = (r1-r2)/h;
|
||||
float a = sqrt(1.0-b*b);
|
||||
float k = dot(q,vec2(-b,a));
|
||||
|
||||
if( k < 0.0 ) return length(q) - r1;
|
||||
if( k > a*h ) return length(q-vec2(0.0,h)) - r2;
|
||||
|
||||
return dot(q, vec2(a,b) ) - r1;
|
||||
}
|
||||
|
||||
float sdRoundCone(vec3 p, vec3 a, vec3 b, float r1, float r2)
|
||||
{
|
||||
// sampling independent computations (only depend on shape)
|
||||
vec3 ba = b - a;
|
||||
float l2 = dot(ba,ba);
|
||||
float rr = r1 - r2;
|
||||
float a2 = l2 - rr*rr;
|
||||
float il2 = 1.0/l2;
|
||||
|
||||
// sampling dependent computations
|
||||
vec3 pa = p - a;
|
||||
float y = dot(pa,ba);
|
||||
float z = y - l2;
|
||||
float x2 = dot2( pa*l2 - ba*y );
|
||||
float y2 = y*y*l2;
|
||||
float z2 = z*z*l2;
|
||||
|
||||
// single square root!
|
||||
float k = sign(rr)*rr*rr*x2;
|
||||
if( sign(z)*a2*z2 > k ) return sqrt(x2 + z2) *il2 - r2;
|
||||
if( sign(y)*a2*y2 < k ) return sqrt(x2 + y2) *il2 - r1;
|
||||
return (sqrt(x2*a2*il2)+y*rr)*il2 - r1;
|
||||
}
|
||||
|
||||
float sdTriPrism( vec3 p, vec2 h )
|
||||
{
|
||||
const float k = sqrt(3.0);
|
||||
h.x *= 0.5*k;
|
||||
p.xy /= h.x;
|
||||
p.x = abs(p.x) - 1.0;
|
||||
p.y = p.y + 1.0/k;
|
||||
if( p.x+k*p.y>0.0 ) p.xy=vec2(p.x-k*p.y,-k*p.x-p.y)/2.0;
|
||||
p.x -= clamp( p.x, -2.0, 0.0 );
|
||||
float d1 = length(p.xy)*sign(-p.y)*h.x;
|
||||
float d2 = abs(p.z)-h.y;
|
||||
return length(max(vec2(d1,d2),0.0)) + min(max(d1,d2), 0.);
|
||||
}
|
||||
|
||||
// vertical
|
||||
float sdCylinder( vec3 p, vec2 h )
|
||||
{
|
||||
vec2 d = abs(vec2(length(p.xz),p.y)) - h;
|
||||
return min(max(d.x,d.y),0.0) + length(max(d,0.0));
|
||||
}
|
||||
|
||||
// arbitrary orientation
|
||||
float sdCylinder(vec3 p, vec3 a, vec3 b, float r)
|
||||
{
|
||||
vec3 pa = p - a;
|
||||
vec3 ba = b - a;
|
||||
float baba = dot(ba,ba);
|
||||
float paba = dot(pa,ba);
|
||||
|
||||
float x = length(pa*baba-ba*paba) - r*baba;
|
||||
float y = abs(paba-baba*0.5)-baba*0.5;
|
||||
float x2 = x*x;
|
||||
float y2 = y*y*baba;
|
||||
float d = (max(x,y)<0.0)?-min(x2,y2):(((x>0.0)?x2:0.0)+((y>0.0)?y2:0.0));
|
||||
return sign(d)*sqrt(abs(d))/baba;
|
||||
}
|
||||
|
||||
// vertical
|
||||
float sdCone( in vec3 p, in vec2 c, float h )
|
||||
{
|
||||
vec2 q = h*vec2(c.x,-c.y)/c.y;
|
||||
vec2 w = vec2( length(p.xz), p.y );
|
||||
|
||||
vec2 a = w - q*clamp( dot(w,q)/dot(q,q), 0.0, 1.0 );
|
||||
vec2 b = w - q*vec2( clamp( w.x/q.x, 0.0, 1.0 ), 1.0 );
|
||||
float k = sign( q.y );
|
||||
float d = min(dot( a, a ),dot(b, b));
|
||||
float s = max( k*(w.x*q.y-w.y*q.x),k*(w.y-q.y) );
|
||||
return sqrt(d)*sign(s);
|
||||
}
|
||||
|
||||
float sdCappedCone( in vec3 p, in float h, in float r1, in float r2 )
|
||||
{
|
||||
vec2 q = vec2( length(p.xz), p.y );
|
||||
|
||||
vec2 k1 = vec2(r2,h);
|
||||
vec2 k2 = vec2(r2-r1,2.0*h);
|
||||
vec2 ca = vec2(q.x-min(q.x,(q.y < 0.0)?r1:r2), abs(q.y)-h);
|
||||
vec2 cb = q - k1 + k2*clamp( dot(k1-q,k2)/dot2(k2), 0.0, 1.0 );
|
||||
float s = (cb.x < 0.0 && ca.y < 0.0) ? -1.0 : 1.0;
|
||||
return s*sqrt( min(dot2(ca),dot2(cb)) );
|
||||
}
|
||||
|
||||
float sdCappedCone(vec3 p, vec3 a, vec3 b, float ra, float rb)
|
||||
{
|
||||
float rba = rb-ra;
|
||||
float baba = dot(b-a,b-a);
|
||||
float papa = dot(p-a,p-a);
|
||||
float paba = dot(p-a,b-a)/baba;
|
||||
|
||||
float x = sqrt( papa - paba*paba*baba );
|
||||
|
||||
float cax = max(0.0,x-((paba<0.5)?ra:rb));
|
||||
float cay = abs(paba-0.5)-0.5;
|
||||
|
||||
float k = rba*rba + baba;
|
||||
float f = clamp( (rba*(x-ra)+paba*baba)/k, 0.0, 1.0 );
|
||||
|
||||
float cbx = x-ra - f*rba;
|
||||
float cby = paba - f;
|
||||
|
||||
float s = (cbx < 0.0 && cay < 0.0) ? -1.0 : 1.0;
|
||||
|
||||
return s*sqrt( min(cax*cax + cay*cay*baba,
|
||||
cbx*cbx + cby*cby*baba) );
|
||||
}
|
||||
|
||||
// c is the sin/cos of the desired cone angle
|
||||
float sdSolidAngle(vec3 pos, vec2 c, float ra)
|
||||
{
|
||||
vec2 p = vec2( length(pos.xz), pos.y );
|
||||
float l = length(p) - ra;
|
||||
float m = length(p - c*clamp(dot(p,c),0.0,ra) );
|
||||
return max(l,m*sign(c.y*p.x-c.x*p.y));
|
||||
}
|
||||
|
||||
float sdOctahedron(vec3 p, float s)
|
||||
{
|
||||
p = abs(p);
|
||||
float m = p.x + p.y + p.z - s;
|
||||
|
||||
// exact distance
|
||||
#if 0
|
||||
vec3 o = min(3.0*p - m, 0.0);
|
||||
o = max(6.0*p - m*2.0 - o*3.0 + (o.x+o.y+o.z), 0.0);
|
||||
return length(p - s*o/(o.x+o.y+o.z));
|
||||
#endif
|
||||
|
||||
// exact distance
|
||||
#if 1
|
||||
vec3 q;
|
||||
if( 3.0*p.x < m ) q = p.xyz;
|
||||
else if( 3.0*p.y < m ) q = p.yzx;
|
||||
else if( 3.0*p.z < m ) q = p.zxy;
|
||||
else return m*0.57735027;
|
||||
float k = clamp(0.5*(q.z-q.y+s),0.0,s);
|
||||
return length(vec3(q.x,q.y-s+k,q.z-k));
|
||||
#endif
|
||||
|
||||
// bound, not exact
|
||||
#if 0
|
||||
return m*0.57735027;
|
||||
#endif
|
||||
}
|
||||
|
||||
float sdPyramid( in vec3 p, in float h )
|
||||
{
|
||||
float m2 = h*h + 0.25;
|
||||
|
||||
// symmetry
|
||||
p.xz = abs(p.xz);
|
||||
p.xz = (p.z>p.x) ? p.zx : p.xz;
|
||||
p.xz -= 0.5;
|
||||
|
||||
// project into face plane (2D)
|
||||
vec3 q = vec3( p.z, h*p.y - 0.5*p.x, h*p.x + 0.5*p.y);
|
||||
|
||||
float s = max(-q.x,0.0);
|
||||
float t = clamp( (q.y-0.5*p.z)/(m2+0.25), 0.0, 1.0 );
|
||||
|
||||
float a = m2*(q.x+s)*(q.x+s) + q.y*q.y;
|
||||
float b = m2*(q.x+0.5*t)*(q.x+0.5*t) + (q.y-m2*t)*(q.y-m2*t);
|
||||
|
||||
float d2 = min(q.y,-q.x*m2-q.y*0.5) > 0.0 ? 0.0 : min(a,b);
|
||||
|
||||
// recover 3D and scale, and add sign
|
||||
return sqrt( (d2+q.z*q.z)/m2 ) * sign(max(q.z,-p.y));
|
||||
}
|
||||
|
||||
// la,lb=semi axis, h=height, ra=corner
|
||||
float sdRhombus(vec3 p, float la, float lb, float h, float ra)
|
||||
{
|
||||
p = abs(p);
|
||||
vec2 b = vec2(la,lb);
|
||||
float f = clamp( (ndot(b,b-2.0*p.xz))/dot(b,b), -1.0, 1.0 );
|
||||
vec2 q = vec2(length(p.xz-0.5*b*vec2(1.0-f,1.0+f))*sign(p.x*b.y+p.z*b.x-b.x*b.y)-ra, p.y-h);
|
||||
return min(max(q.x,q.y),0.0) + length(max(q,0.0));
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
vec2 opU( vec2 d1, vec2 d2 )
|
||||
{
|
||||
return (d1.x<d2.x) ? d1 : d2;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
#define ZERO (min(int(iFrame),0))
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
vec2 map( in vec3 pos )
|
||||
{
|
||||
vec2 res = vec2( 1e10, 0.0 );
|
||||
|
||||
{
|
||||
res = opU( res, vec2( sdSphere( pos-vec3(-2.0,0.25, 0.0), 0.25 ), 26.9 ) );
|
||||
}
|
||||
|
||||
// bounding box
|
||||
if( sdBox( pos-vec3(0.0,0.3,-1.0),vec3(0.35,0.3,2.5) )<res.x )
|
||||
{
|
||||
// more primitives
|
||||
res = opU( res, vec2( sdBoundingBox( pos-vec3( 0.0,0.25, 0.0), vec3(0.3,0.25,0.2), 0.025 ), 16.9 ) );
|
||||
res = opU( res, vec2( sdTorus( (pos-vec3( 0.0,0.30, 1.0)).xzy, vec2(0.25,0.05) ), 25.0 ) );
|
||||
res = opU( res, vec2( sdCone( pos-vec3( 0.0,0.45,-1.0), vec2(0.6,0.8),0.45 ), 55.0 ) );
|
||||
res = opU( res, vec2( sdCappedCone( pos-vec3( 0.0,0.25,-2.0), 0.25, 0.25, 0.1 ), 13.67 ) );
|
||||
res = opU( res, vec2( sdSolidAngle( pos-vec3( 0.0,0.00,-3.0), vec2(3,4)/5.0, 0.4 ), 49.13 ) );
|
||||
}
|
||||
|
||||
// bounding box
|
||||
if( sdBox( pos-vec3(1.0,0.3,-1.0),vec3(0.35,0.3,2.5) )<res.x )
|
||||
{
|
||||
// more primitives
|
||||
res = opU( res, vec2( sdCappedTorus((pos-vec3( 1.0,0.30, 1.0))*vec3(1,-1,1), vec2(0.866025,-0.5), 0.25, 0.05), 8.5) );
|
||||
res = opU( res, vec2( sdBox( pos-vec3( 1.0,0.25, 0.0), vec3(0.3,0.25,0.1) ), 3.0 ) );
|
||||
res = opU( res, vec2( sdCapsule( pos-vec3( 1.0,0.00,-1.0),vec3(-0.1,0.1,-0.1), vec3(0.2,0.4,0.2), 0.1 ), 31.9 ) );
|
||||
res = opU( res, vec2( sdCylinder( pos-vec3( 1.0,0.25,-2.0), vec2(0.15,0.25) ), 8.0 ) );
|
||||
res = opU( res, vec2( sdHexPrism( pos-vec3( 1.0,0.2,-3.0), vec2(0.2,0.05) ), 18.4 ) );
|
||||
}
|
||||
|
||||
// bounding box
|
||||
if( sdBox( pos-vec3(-1.0,0.35,-1.0),vec3(0.35,0.35,2.5))<res.x )
|
||||
{
|
||||
// more primitives
|
||||
res = opU( res, vec2( sdPyramid( pos-vec3(-1.0,-0.6,-3.0), 1.0 ), 13.56 ) );
|
||||
res = opU( res, vec2( sdOctahedron( pos-vec3(-1.0,0.15,-2.0), 0.35 ), 23.56 ) );
|
||||
res = opU( res, vec2( sdTriPrism( pos-vec3(-1.0,0.15,-1.0), vec2(0.3,0.05) ),43.5 ) );
|
||||
res = opU( res, vec2( sdEllipsoid( pos-vec3(-1.0,0.25, 0.0), vec3(0.2, 0.25, 0.05) ), 43.17 ) );
|
||||
res = opU( res, vec2( sdRhombus( (pos-vec3(-1.0,0.34, 1.0)).xzy, 0.15, 0.25, 0.04, 0.08 ),17.0 ) );
|
||||
}
|
||||
|
||||
// bounding box
|
||||
if( sdBox( pos-vec3(2.0,0.3,-1.0),vec3(0.35,0.3,2.5) )<res.x )
|
||||
{
|
||||
// more primitives
|
||||
res = opU( res, vec2( sdOctogonPrism(pos-vec3( 2.0,0.2,-3.0), 0.2, 0.05), 51.8 ) );
|
||||
res = opU( res, vec2( sdCylinder( pos-vec3( 2.0,0.15,-2.0), vec3(0.1,-0.1,0.0), vec3(-0.2,0.35,0.1), 0.08), 31.2 ) );
|
||||
res = opU( res, vec2( sdCappedCone( pos-vec3( 2.0,0.10,-1.0), vec3(0.1,0.0,0.0), vec3(-0.2,0.40,0.1), 0.15, 0.05), 46.1 ) );
|
||||
res = opU( res, vec2( sdRoundCone( pos-vec3( 2.0,0.15, 0.0), vec3(0.1,0.0,0.0), vec3(-0.1,0.35,0.1), 0.15, 0.05), 51.7 ) );
|
||||
res = opU( res, vec2( sdRoundCone( pos-vec3( 2.0,0.20, 1.0), 0.2, 0.1, 0.3 ), 37.0 ) );
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/boxfunctions/boxfunctions.htm
|
||||
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 rad )
|
||||
{
|
||||
vec3 m = 1.0/rd;
|
||||
vec3 n = m*ro;
|
||||
vec3 k = abs(m)*rad;
|
||||
vec3 t1 = -n - k;
|
||||
vec3 t2 = -n + k;
|
||||
return vec2( max( max( t1.x, t1.y ), t1.z ),
|
||||
min( min( t2.x, t2.y ), t2.z ) );
|
||||
}
|
||||
|
||||
vec2 raycast( in vec3 ro, in vec3 rd )
|
||||
{
|
||||
vec2 res = vec2(-1.0,-1.0);
|
||||
|
||||
float tmin = 1.0;
|
||||
float tmax = 20.0;
|
||||
|
||||
// raytrace floor plane
|
||||
float tp1 = (0.0-ro.y)/rd.y;
|
||||
if( tp1>0.0 )
|
||||
{
|
||||
tmax = min( tmax, tp1 );
|
||||
res = vec2( tp1, 1.0 );
|
||||
}
|
||||
//else return res;
|
||||
|
||||
// raymarch primitives
|
||||
vec2 tb = iBox( ro-vec3(0.0,0.4,-0.5), rd, vec3(2.5,0.41,3.0) );
|
||||
if( tb.x<tb.y && tb.y>0.0 && tb.x<tmax)
|
||||
{
|
||||
//return vec2(tb.x,2.0);
|
||||
tmin = max(tb.x,tmin);
|
||||
tmax = min(tb.y,tmax);
|
||||
|
||||
float t = tmin;
|
||||
for( int i=0; i<70 && t<tmax; i++ )
|
||||
{
|
||||
vec2 h = map( ro+rd*t );
|
||||
if( abs(h.x)<(0.0001*t) )
|
||||
{
|
||||
res = vec2(t,h.y);
|
||||
break;
|
||||
}
|
||||
t += h.x;
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/rmshadows/rmshadows.htm
|
||||
float calcSoftshadow( in vec3 ro, in vec3 rd, in float mint, in float tmax )
|
||||
{
|
||||
// bounding volume
|
||||
float tp = (0.8-ro.y)/rd.y; if( tp>0.0 ) tmax = min( tmax, tp );
|
||||
|
||||
float res = 1.0;
|
||||
float t = mint;
|
||||
for( int i=ZERO; i<24; i++ )
|
||||
{
|
||||
float h = map( ro + rd*t ).x;
|
||||
float s = clamp(8.0*h/t,0.0,1.0);
|
||||
res = min( res, s*s*(3.0-2.0*s) );
|
||||
t += clamp( h, 0.02, 0.2 );
|
||||
if( res<0.004 || t>tmax ) break;
|
||||
}
|
||||
return clamp( res, 0.0, 1.0 );
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/normalsSDF/normalsSDF.htm
|
||||
vec3 calcNormal( in vec3 pos )
|
||||
{
|
||||
#if 0
|
||||
vec2 e = vec2(1.0,-1.0)*0.5773*0.0005;
|
||||
return normalize( e.xyy*map( pos + e.xyy ).x +
|
||||
e.yyx*map( pos + e.yyx ).x +
|
||||
e.yxy*map( pos + e.yxy ).x +
|
||||
e.xxx*map( pos + e.xxx ).x );
|
||||
#else
|
||||
// inspired by tdhooper and klems - a way to prevent the compiler from inlining map() 4 times
|
||||
vec3 n = vec3(0.0);
|
||||
for( int i=ZERO; i<4; i++ )
|
||||
{
|
||||
vec3 e = 0.5773*(2.0*vec3((((i+3)>>1)&1),((i>>1)&1),(i&1))-1.0);
|
||||
n += e*map(pos+0.0005*e).x;
|
||||
//if( n.x+n.y+n.z>100.0 ) break;
|
||||
}
|
||||
return normalize(n);
|
||||
#endif
|
||||
}
|
||||
|
||||
float calcAO( in vec3 pos, in vec3 nor )
|
||||
{
|
||||
float occ = 0.0;
|
||||
float sca = 1.0;
|
||||
for( int i=ZERO; i<5; i++ )
|
||||
{
|
||||
float h = 0.01 + 0.12*float(i)/4.0;
|
||||
float d = map( pos + h*nor ).x;
|
||||
occ += (h-d)*sca;
|
||||
sca *= 0.95;
|
||||
if( occ>0.35 ) break;
|
||||
}
|
||||
return clamp( 1.0 - 3.0*occ, 0.0, 1.0 ) * (0.5+0.5*nor.y);
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/checkerfiltering/checkerfiltering.htm
|
||||
float checkersGradBox( in vec2 p, in vec2 dpdx, in vec2 dpdy )
|
||||
{
|
||||
// filter kernel
|
||||
vec2 w = abs(dpdx)+abs(dpdy) + 0.001;
|
||||
// analytical integral (box filter)
|
||||
vec2 i = 2.0*(abs(fract((p-0.5*w)*0.5)-0.5)-abs(fract((p+0.5*w)*0.5)-0.5))/w;
|
||||
// xor pattern
|
||||
return 0.5 - 0.5*i.x*i.y;
|
||||
}
|
||||
|
||||
vec3 render( in vec3 ro, in vec3 rd, in vec3 rdx, in vec3 rdy )
|
||||
{
|
||||
// background
|
||||
vec3 col = vec3(0.7, 0.7, 0.9) - max(rd.y,0.0)*0.3;
|
||||
|
||||
// raycast scene
|
||||
vec2 res = raycast(ro,rd);
|
||||
float t = res.x;
|
||||
float m = res.y;
|
||||
if( m>-0.5 )
|
||||
{
|
||||
vec3 pos = ro + t*rd;
|
||||
vec3 nor = (m<1.5) ? vec3(0.0,1.0,0.0) : calcNormal( pos );
|
||||
vec3 ref = reflect( rd, nor );
|
||||
|
||||
// material
|
||||
col = 0.2 + 0.2*sin( m*2.0 + vec3(0.0,1.0,2.0) );
|
||||
float ks = 1.0;
|
||||
|
||||
if( m<1.5 )
|
||||
{
|
||||
// project pixel footprint into the plane
|
||||
vec3 dpdx = ro.y*(rd/rd.y-rdx/rdx.y);
|
||||
vec3 dpdy = ro.y*(rd/rd.y-rdy/rdy.y);
|
||||
|
||||
float f = checkersGradBox( 3.0*pos.xz, 3.0*dpdx.xz, 3.0*dpdy.xz );
|
||||
col = 0.15 + f*vec3(0.05);
|
||||
ks = 0.4;
|
||||
}
|
||||
|
||||
// lighting
|
||||
float occ = calcAO( pos, nor );
|
||||
|
||||
vec3 lin = vec3(0.0);
|
||||
|
||||
// sun
|
||||
{
|
||||
vec3 lig = normalize( vec3(-0.5, 0.4, -0.6) );
|
||||
vec3 hal = normalize( lig-rd );
|
||||
float dif = clamp( dot( nor, lig ), 0.0, 1.0 );
|
||||
//if( dif>0.0001 )
|
||||
dif *= calcSoftshadow( pos, lig, 0.02, 2.5 );
|
||||
float spe = pow( clamp( dot( nor, hal ), 0.0, 1.0 ),16.0);
|
||||
spe *= dif;
|
||||
spe *= 0.04+0.96*pow(clamp(1.0-dot(hal,lig),0.0,1.0),5.0);
|
||||
lin += col*2.20*dif*vec3(1.30,1.00,0.70);
|
||||
lin += 5.00*spe*vec3(1.30,1.00,0.70)*ks;
|
||||
}
|
||||
// sky
|
||||
{
|
||||
float dif = sqrt(clamp( 0.5+0.5*nor.y, 0.0, 1.0 ));
|
||||
dif *= occ;
|
||||
float spe = smoothstep( -0.2, 0.2, ref.y );
|
||||
spe *= dif;
|
||||
spe *= 0.04+0.96*pow(clamp(1.0+dot(nor,rd),0.0,1.0), 5.0 );
|
||||
//if( spe>0.001 )
|
||||
spe *= calcSoftshadow( pos, ref, 0.02, 2.5 );
|
||||
lin += col*0.60*dif*vec3(0.40,0.60,1.15);
|
||||
lin += 2.00*spe*vec3(0.40,0.60,1.30)*ks;
|
||||
}
|
||||
// back
|
||||
{
|
||||
float dif = clamp( dot( nor, normalize(vec3(0.5,0.0,0.6))), 0.0, 1.0 )*clamp( 1.0-pos.y,0.0,1.0);
|
||||
dif *= occ;
|
||||
lin += col*0.55*dif*vec3(0.25,0.25,0.25);
|
||||
}
|
||||
// sss
|
||||
{
|
||||
float dif = pow(clamp(1.0+dot(nor,rd),0.0,1.0),2.0);
|
||||
dif *= occ;
|
||||
lin += col*0.25*dif*vec3(1.00,1.00,1.00);
|
||||
}
|
||||
|
||||
col = lin;
|
||||
|
||||
col = mix( col, vec3(0.7,0.7,0.9), 1.0-exp( -0.0001*t*t*t ) );
|
||||
}
|
||||
|
||||
return vec3( clamp(col,0.0,1.0) );
|
||||
}
|
||||
|
||||
mat3 setCamera( in vec3 ro, in vec3 ta, float cr )
|
||||
{
|
||||
vec3 cw = normalize(ta-ro);
|
||||
vec3 cp = vec3(sin(cr), cos(cr),0.0);
|
||||
vec3 cu = normalize( cross(cw,cp) );
|
||||
vec3 cv = ( cross(cu,cw) );
|
||||
return mat3( cu, cv, cw );
|
||||
}
|
||||
|
||||
vec4 mainImage( vec2 fragCoord )
|
||||
{
|
||||
vec2 mo = iMouse.xy/iResolution.xy;
|
||||
float time = 32.0 + iTime*1.5;
|
||||
|
||||
// camera
|
||||
vec3 ta = vec3( 0.5, -0.5, -0.6 );
|
||||
vec3 ro = ta + vec3( 4.5*cos(0.1*time + 7.0*mo.x), 1.3 + 2.0*mo.y, 4.5*sin(0.1*time + 7.0*mo.x) );
|
||||
// camera-to-world transformation
|
||||
mat3 ca = setCamera( ro, ta, 0.0 );
|
||||
|
||||
vec3 tot = vec3(0.0);
|
||||
#if AA>1
|
||||
for( int m=ZERO; m<AA; m++ )
|
||||
for( int n=ZERO; n<AA; n++ )
|
||||
{
|
||||
// pixel coordinates
|
||||
vec2 o = vec2(float(m),float(n)) / float(AA) - 0.5;
|
||||
vec2 p = (2.0*(fragCoord+o)-iResolution.xy)/iResolution.y;
|
||||
#else
|
||||
vec2 p = (2.0*fragCoord-iResolution.xy)/iResolution.y;
|
||||
#endif
|
||||
|
||||
// focal length
|
||||
const float fl = 2.5;
|
||||
|
||||
// ray direction
|
||||
vec3 rd = ca * normalize( vec3(p,fl) );
|
||||
|
||||
// ray differentials
|
||||
vec2 px = (2.0*(fragCoord+vec2(1.0,0.0))-iResolution.xy)/iResolution.y;
|
||||
vec2 py = (2.0*(fragCoord+vec2(0.0,1.0))-iResolution.xy)/iResolution.y;
|
||||
vec3 rdx = ca * normalize( vec3(px,fl) );
|
||||
vec3 rdy = ca * normalize( vec3(py,fl) );
|
||||
|
||||
// render
|
||||
vec3 col = render( ro, rd, rdx, rdy );
|
||||
|
||||
// gain
|
||||
// col = col*3.0/(2.5+col);
|
||||
|
||||
// gamma
|
||||
col = pow( col, vec3(0.4545) );
|
||||
|
||||
tot += col;
|
||||
#if AA>1
|
||||
}
|
||||
tot /= float(AA*AA);
|
||||
#endif
|
||||
|
||||
//fragColor = vec4( tot, 1.0 );
|
||||
return vec4( tot, 1.0 );
|
||||
}
|
||||
|
||||
//*********************************************************
|
||||
// END Ray Marching
|
||||
//*********************************************************
|
||||
|
||||
void main() {
|
||||
vec4 c = color;
|
||||
vec4 txt = texture(sampler2D(tex, smp), uv);
|
||||
c = txt * c;
|
||||
vec2 uv1 = uv * iResolution;
|
||||
vec4 col_ray = mainImage(uv1);
|
||||
|
||||
// use this to mix the chessboart texture with the ray marching
|
||||
//frag_color = clamp(c*iMouse.y/512.0,0.0,1.0) * col_ray ;
|
||||
|
||||
frag_color = c*0.00001 + col_ray ;
|
||||
}
|
||||
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @program rt vs fs
|
||||
@@ -0,0 +1,424 @@
|
||||
// vtest build: misc-tooling // needs .h files that are produced by `v shader`
|
||||
/**********************************************************************
|
||||
*
|
||||
* Sokol 3d cube demo
|
||||
*
|
||||
* Copyright (c) 2021 Dario Deledda. All rights reserved.
|
||||
* Use of this source code is governed by an MIT license
|
||||
* that can be found in the LICENSE file.
|
||||
*
|
||||
* HOW TO COMPILE SHADERS:
|
||||
* Run `v shader .` in this directory to compile the shaders.
|
||||
* For more info and help with shader compilation see `docs.md` and `v help shader`.
|
||||
*
|
||||
* TODO:
|
||||
* - frame counter
|
||||
**********************************************************************/
|
||||
import gg
|
||||
import gg.m4
|
||||
// import math
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
import sokol.sgl
|
||||
import time
|
||||
|
||||
// GLSL Include and functions
|
||||
|
||||
#include "@VMODROOT/rt_glsl.h" # It should be generated with `v shader .` (see the instructions at the top of this file)
|
||||
|
||||
fn C.rt_shader_desc(gfx.Backend) &gfx.ShaderDesc
|
||||
|
||||
const win_width = 800
|
||||
const win_height = 800
|
||||
const bg_color = gg.white
|
||||
|
||||
struct App {
|
||||
mut:
|
||||
gg &gg.Context = unsafe { nil }
|
||||
texture gfx.Image
|
||||
sampler gfx.Sampler
|
||||
init_flag bool
|
||||
frame_count int
|
||||
|
||||
mouse_x int = -1
|
||||
mouse_y int = -1
|
||||
// glsl
|
||||
cube_pip_glsl gfx.Pipeline
|
||||
cube_bind gfx.Bindings
|
||||
// time
|
||||
ticks i64
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Texture functions
|
||||
******************************************************************************/
|
||||
fn create_texture(w int, h int, buf &u8) (gfx.Image, gfx.Sampler) {
|
||||
sz := w * h * 4
|
||||
mut img_desc := gfx.ImageDesc{
|
||||
width: w
|
||||
height: h
|
||||
num_mipmaps: 0
|
||||
// min_filter: .linear
|
||||
// mag_filter: .linear
|
||||
// usage: .dynamic
|
||||
// wrap_u: .clamp_to_edge
|
||||
// wrap_v: .clamp_to_edge
|
||||
label: &char(unsafe { nil })
|
||||
d3d11_texture: 0
|
||||
}
|
||||
// comment if .dynamic is enabled
|
||||
img_desc.data.subimage[0][0] = gfx.Range{
|
||||
ptr: buf
|
||||
size: usize(sz)
|
||||
}
|
||||
|
||||
sg_img := gfx.make_image(&img_desc)
|
||||
|
||||
mut smp_desc := gfx.SamplerDesc{
|
||||
min_filter: .linear
|
||||
mag_filter: .linear
|
||||
wrap_u: .clamp_to_edge
|
||||
wrap_v: .clamp_to_edge
|
||||
}
|
||||
|
||||
sg_smp := gfx.make_sampler(&smp_desc)
|
||||
return sg_img, sg_smp
|
||||
}
|
||||
|
||||
fn destroy_texture(sg_img gfx.Image) {
|
||||
gfx.destroy_image(sg_img)
|
||||
}
|
||||
|
||||
// Use only if usage: .dynamic is enabled
|
||||
fn update_text_texture(sg_img gfx.Image, w int, h int, buf &u8) {
|
||||
sz := w * h * 4
|
||||
mut tmp_sbc := gfx.ImageData{}
|
||||
tmp_sbc.subimage[0][0] = gfx.Range{
|
||||
ptr: buf
|
||||
size: usize(sz)
|
||||
}
|
||||
gfx.update_image(sg_img, &tmp_sbc)
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Draw functions
|
||||
******************************************************************************
|
||||
Cube vertex buffer with packed vertex formats for color and texture coords.
|
||||
Note that a vertex format which must be portable across all
|
||||
backends must only use the normalized integer formats
|
||||
(BYTE4N, UBYTE4N, SHORT2N, SHORT4N), which can be converted
|
||||
to floating point formats in the vertex shader inputs.
|
||||
The reason is that D3D11 cannot convert from non-normalized
|
||||
formats to floating point inputs (only to integer inputs),
|
||||
and WebGL2 / GLES2 don't support integer vertex shader inputs.
|
||||
*/
|
||||
|
||||
struct Vertex_t {
|
||||
x f32
|
||||
y f32
|
||||
z f32
|
||||
color u32
|
||||
u f32
|
||||
v f32
|
||||
// u u16 // for compatibility with D3D11
|
||||
// v u16 // for compatibility with D3D11
|
||||
}
|
||||
|
||||
fn init_cube_glsl(mut app App) {
|
||||
// cube vertex buffer
|
||||
// d := u16(32767) // for compatibility with D3D11, 32767 stand for 1
|
||||
d := f32(1.0)
|
||||
c := u32(0xFFFFFF_FF) // color RGBA8
|
||||
// vfmt off
|
||||
vertices := [
|
||||
// Face 0
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{ 1.0, -1.0, -1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, -1.0, c, d, d},
|
||||
Vertex_t{-1.0, 1.0, -1.0, c, 0, d},
|
||||
// Face 1
|
||||
Vertex_t{-1.0, -1.0, 1.0, c, 0, 0},
|
||||
Vertex_t{ 1.0, -1.0, 1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{-1.0, 1.0, 1.0, c, 0, d},
|
||||
// Face 2
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{-1.0, 1.0, -1.0, c, d, 0},
|
||||
Vertex_t{-1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{-1.0, -1.0, 1.0, c, 0, d},
|
||||
// Face 3
|
||||
Vertex_t{ 1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{ 1.0, 1.0, -1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{ 1.0, -1.0, 1.0, c, 0, d},
|
||||
// Face 4
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{-1.0, -1.0, 1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, -1.0, 1.0, c, d, d},
|
||||
Vertex_t{ 1.0, -1.0, -1.0, c, 0, d},
|
||||
// Face 5
|
||||
Vertex_t{-1.0, 1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{-1.0, 1.0, 1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{ 1.0, 1.0, -1.0, c, 0, d},
|
||||
]
|
||||
// vfmt on
|
||||
|
||||
mut vert_buffer_desc := gfx.BufferDesc{
|
||||
label: c'cube-vertices'
|
||||
}
|
||||
unsafe { vmemset(&vert_buffer_desc, 0, int(sizeof(vert_buffer_desc))) }
|
||||
|
||||
vert_buffer_desc.size = usize(vertices.len * int(sizeof(Vertex_t)))
|
||||
vert_buffer_desc.data = gfx.Range{
|
||||
ptr: vertices.data
|
||||
size: usize(vertices.len * int(sizeof(Vertex_t)))
|
||||
}
|
||||
|
||||
vert_buffer_desc.type = .vertexbuffer
|
||||
vbuf := gfx.make_buffer(&vert_buffer_desc)
|
||||
|
||||
// create an index buffer for the cube
|
||||
// vfmt off
|
||||
indices := [
|
||||
u16(0), 1, 2, 0, 2, 3,
|
||||
6, 5, 4, 7, 6, 4,
|
||||
8, 9, 10, 8, 10, 11,
|
||||
14, 13, 12, 15, 14, 12,
|
||||
16, 17, 18, 16, 18, 19,
|
||||
22, 21, 20, 23, 22, 20,
|
||||
]
|
||||
// vfmt on
|
||||
|
||||
mut index_buffer_desc := gfx.BufferDesc{
|
||||
label: c'cube-indices'
|
||||
}
|
||||
unsafe { vmemset(&index_buffer_desc, 0, int(sizeof(index_buffer_desc))) }
|
||||
|
||||
index_buffer_desc.size = usize(indices.len * int(sizeof(u16)))
|
||||
index_buffer_desc.data = gfx.Range{
|
||||
ptr: indices.data
|
||||
size: usize(indices.len * int(sizeof(u16)))
|
||||
}
|
||||
|
||||
index_buffer_desc.type = .indexbuffer
|
||||
ibuf := gfx.make_buffer(&index_buffer_desc)
|
||||
|
||||
// create shader
|
||||
shader := gfx.make_shader(voidptr(C.rt_shader_desc(C.sg_query_backend())))
|
||||
|
||||
mut pipdesc := gfx.PipelineDesc{}
|
||||
unsafe { vmemset(&pipdesc, 0, int(sizeof(pipdesc))) }
|
||||
pipdesc.layout.buffers[0].stride = int(sizeof(Vertex_t))
|
||||
|
||||
// the constants [C.ATTR_vs_pos, C.ATTR_vs_color0, C.ATTR_vs_texcoord0] are generated by sokol-shdc
|
||||
pipdesc.layout.attrs[C.ATTR_vs_pos].format = .float3 // x,y,z as f32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_color0].format = .ubyte4n // color as u32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_texcoord0].format = .float2 // u,v as f32
|
||||
// pipdesc.layout.attrs[C.ATTR_vs_texcoord0].format = .short2n // u,v as u16
|
||||
|
||||
pipdesc.shader = shader
|
||||
pipdesc.index_type = .uint16
|
||||
|
||||
pipdesc.depth = gfx.DepthState{
|
||||
write_enabled: true
|
||||
compare: .less_equal
|
||||
}
|
||||
pipdesc.cull_mode = .back
|
||||
|
||||
pipdesc.label = c'glsl_shader pipeline'
|
||||
|
||||
app.cube_bind.vertex_buffers[0] = vbuf
|
||||
app.cube_bind.index_buffer = ibuf
|
||||
app.cube_bind.fs.images[C.SLOT_tex] = app.texture
|
||||
app.cube_bind.fs.samplers[C.SLOT_smp] = app.sampler
|
||||
app.cube_pip_glsl = gfx.make_pipeline(&pipdesc)
|
||||
println('GLSL init DONE!')
|
||||
}
|
||||
|
||||
@[inline]
|
||||
fn vec4(x f32, y f32, z f32, w f32) m4.Vec4 {
|
||||
return m4.Vec4{
|
||||
e: [x, y, z, w]!
|
||||
}
|
||||
}
|
||||
|
||||
fn calc_tr_matrices(w f32, h f32, rx f32, ry f32, in_scale f32) m4.Mat4 {
|
||||
proj := m4.perspective(60, w / h, 0.01, 10.0)
|
||||
view := m4.look_at(vec4(f32(0.0), 0, 6, 0), vec4(f32(0), 0, 0, 0), vec4(f32(0), 1, 0, 0))
|
||||
view_proj := view * proj
|
||||
|
||||
rxm := m4.rotate(m4.rad(rx), vec4(f32(1), 0, 0, 0))
|
||||
rym := m4.rotate(m4.rad(ry), vec4(f32(0), 1, 0, 0))
|
||||
|
||||
model := rym * rxm
|
||||
scale_m := m4.scale(vec4(in_scale, in_scale, in_scale, 1))
|
||||
|
||||
res := (scale_m * model) * view_proj
|
||||
return res
|
||||
}
|
||||
|
||||
fn draw_cube_glsl(app App) {
|
||||
if app.init_flag == false {
|
||||
return
|
||||
}
|
||||
|
||||
ws := gg.window_size_real_pixels()
|
||||
ratio := f32(ws.width) / ws.height
|
||||
dw := f32(ws.width / 2)
|
||||
dh := f32(ws.height / 2)
|
||||
|
||||
// use the following commented lines to rotate the 3d glsl cube
|
||||
// rot := [f32(app.mouse_y), f32(app.mouse_x)]
|
||||
// calc_tr_matrices(dw, dh, rot[0], rot[1] ,2.3)
|
||||
tr_matrix := calc_tr_matrices(dw, dh, 0, 0, 2.3)
|
||||
gfx.apply_viewport(0, 0, ws.width, ws.height, true)
|
||||
|
||||
// apply the pipeline and bindings
|
||||
gfx.apply_pipeline(app.cube_pip_glsl)
|
||||
gfx.apply_bindings(app.cube_bind)
|
||||
|
||||
// Uniforms
|
||||
// *** vertex shader uniforms ***
|
||||
// passing the view matrix as uniform
|
||||
// res is a 4x4 matrix of f32 thus: 4*16 byte of size
|
||||
vs_uniforms_range := gfx.Range{
|
||||
ptr: &tr_matrix
|
||||
size: usize(4 * 16)
|
||||
}
|
||||
gfx.apply_uniforms(.vs, C.SLOT_vs_params, &vs_uniforms_range)
|
||||
|
||||
// *** fragment shader uniforms ***
|
||||
time_ticks := f32(time.ticks() - app.ticks) / 1000
|
||||
mut tmp_fs_params := [
|
||||
f32(ws.width),
|
||||
ws.height * ratio, // x,y resolution to pass to FS
|
||||
app.mouse_x, // mouse x
|
||||
ws.height - app.mouse_y * 2, // mouse y scaled
|
||||
time_ticks, // time as f32
|
||||
app.frame_count, // frame count
|
||||
0,
|
||||
0, // padding bytes , see "fs_params" struct paddings in rt_glsl.h
|
||||
]!
|
||||
fs_uniforms_range := gfx.Range{
|
||||
ptr: unsafe { &tmp_fs_params }
|
||||
size: usize(sizeof(tmp_fs_params))
|
||||
}
|
||||
gfx.apply_uniforms(.fs, C.SLOT_fs_params, &fs_uniforms_range)
|
||||
|
||||
// 3 vertices for triangle * 2 triangles per face * 6 faces = 36 vertices to draw
|
||||
gfx.draw(0, (3 * 2) * 6, 1)
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
|
||||
fn frame(mut app App) {
|
||||
// clear
|
||||
mut color_action := gfx.ColorAttachmentAction{
|
||||
load_action: .clear
|
||||
clear_value: gfx.Color{
|
||||
r: 0.0
|
||||
g: 0.0
|
||||
b: 0.0
|
||||
a: 1.0
|
||||
}
|
||||
}
|
||||
|
||||
mut pass_action := gfx.PassAction{}
|
||||
pass_action.colors[0] = color_action
|
||||
pass := sapp.create_default_pass(pass_action)
|
||||
gfx.begin_pass(&pass)
|
||||
|
||||
// glsl cube
|
||||
draw_cube_glsl(app)
|
||||
app.frame_count++
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Init / Cleanup
|
||||
******************************************************************************/
|
||||
fn my_init(mut app App) {
|
||||
// set max vertices,
|
||||
// for a large number of the same type of object it is better use the instances!!
|
||||
desc := sapp.create_desc()
|
||||
gfx.setup(&desc)
|
||||
sgl_desc := sgl.Desc{
|
||||
max_vertices: 50 * 65536
|
||||
}
|
||||
sgl.setup(&sgl_desc)
|
||||
|
||||
// create chessboard texture 256*256 RGBA
|
||||
w := 256
|
||||
h := 256
|
||||
sz := w * h * 4
|
||||
tmp_txt := unsafe { malloc(sz) }
|
||||
mut i := 0
|
||||
for i < sz {
|
||||
unsafe {
|
||||
y := (i >> 0x8) >> 5 // 8 cell
|
||||
x := (i & 0xFF) >> 5 // 8 cell
|
||||
// upper left corner
|
||||
if x == 0 && y == 0 {
|
||||
tmp_txt[i + 0] = u8(0xFF)
|
||||
tmp_txt[i + 1] = u8(0)
|
||||
tmp_txt[i + 2] = u8(0)
|
||||
tmp_txt[i + 3] = u8(0xFF)
|
||||
}
|
||||
// low right corner
|
||||
else if x == 7 && y == 7 {
|
||||
tmp_txt[i + 0] = u8(0)
|
||||
tmp_txt[i + 1] = u8(0xFF)
|
||||
tmp_txt[i + 2] = u8(0)
|
||||
tmp_txt[i + 3] = u8(0xFF)
|
||||
} else {
|
||||
col := if ((x + y) & 1) == 1 { 0xFF } else { 128 }
|
||||
tmp_txt[i + 0] = u8(col) // red
|
||||
tmp_txt[i + 1] = u8(col) // green
|
||||
tmp_txt[i + 2] = u8(col) // blue
|
||||
tmp_txt[i + 3] = u8(0xFF) // alpha
|
||||
}
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
app.texture, app.sampler = create_texture(w, h, tmp_txt)
|
||||
free(tmp_txt)
|
||||
}
|
||||
// glsl
|
||||
init_cube_glsl(mut app)
|
||||
app.init_flag = true
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* events handling
|
||||
******************************************************************************/
|
||||
fn my_event_manager(mut ev gg.Event, mut app App) {
|
||||
if ev.typ == .mouse_move {
|
||||
app.mouse_x = int(ev.mouse_x)
|
||||
app.mouse_y = int(ev.mouse_y)
|
||||
}
|
||||
if ev.typ == .touches_began || ev.typ == .touches_moved {
|
||||
if ev.num_touches > 0 {
|
||||
touch_point := ev.touches[0]
|
||||
app.mouse_x = int(touch_point.pos_x)
|
||||
app.mouse_y = int(touch_point.pos_y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
mut app := &App{}
|
||||
app.gg = gg.new_context(
|
||||
width: win_width
|
||||
height: win_height
|
||||
create_window: true
|
||||
window_title: '3D Ray Marching Cube'
|
||||
user_data: app
|
||||
bg_color: bg_color
|
||||
frame_fn: frame
|
||||
init_fn: my_init
|
||||
event_fn: my_event_manager
|
||||
)
|
||||
app.ticks = time.ticks()
|
||||
app.gg.run()
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,339 @@
|
||||
// vtest build: misc-tooling // needs .h files that are produced by `v shader`
|
||||
/**********************************************************************
|
||||
* Sokol 3d cube multishader demo
|
||||
* Copyright (c) 2024 Dario Deledda. All rights reserved.
|
||||
* Use of this source code is governed by an MIT license
|
||||
* that can be found in the LICENSE file.
|
||||
*
|
||||
* HOW TO COMPILE SHADERS:
|
||||
* Run `v shader .` in this directory to compile the shaders.
|
||||
* For more info and help with shader compilation see `docs.md` and `v help shader`.
|
||||
**********************************************************************/
|
||||
import gg
|
||||
import gg.m4
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
import sokol.sgl
|
||||
import time
|
||||
|
||||
// GLSL Include and functions
|
||||
#include "@VMODROOT/rt_glsl_march.h" # It should be generated with `v shader .` (see the instructions at the top of this file)
|
||||
#include "@VMODROOT/rt_glsl_puppy.h" # It should be generated with `v shader .` (see the instructions at the top of this file)
|
||||
|
||||
fn C.rt_march_shader_desc(gfx.Backend) &gfx.ShaderDesc
|
||||
fn C.rt_puppy_shader_desc(gfx.Backend) &gfx.ShaderDesc
|
||||
|
||||
const start_ticks = time.ticks()
|
||||
|
||||
@[heap]
|
||||
struct App {
|
||||
mut:
|
||||
gg &gg.Context = unsafe { nil }
|
||||
texture gfx.Image
|
||||
sampler gfx.Sampler
|
||||
init_flag bool
|
||||
mouse_x int = 502
|
||||
mouse_y int = 394
|
||||
mouse_down bool
|
||||
// glsl
|
||||
cube_pip_glsl gfx.Pipeline
|
||||
cube_bind gfx.Bindings
|
||||
pipe map[string]gfx.Pipeline
|
||||
bind map[string]gfx.Bindings
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Texture functions
|
||||
******************************************************************************/
|
||||
fn create_texture(w int, h int, buf byteptr) (gfx.Image, gfx.Sampler) {
|
||||
sz := w * h * 4
|
||||
mut img_desc := gfx.ImageDesc{
|
||||
width: w
|
||||
height: h
|
||||
}
|
||||
img_desc.data.subimage[0][0] = gfx.Range{
|
||||
ptr: buf
|
||||
size: usize(sz)
|
||||
}
|
||||
sg_img := gfx.make_image(&img_desc)
|
||||
mut smp_desc := gfx.SamplerDesc{
|
||||
min_filter: .linear
|
||||
mag_filter: .linear
|
||||
wrap_u: .clamp_to_edge
|
||||
wrap_v: .clamp_to_edge
|
||||
}
|
||||
sg_smp := gfx.make_sampler(&smp_desc)
|
||||
return sg_img, sg_smp
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Draw functions
|
||||
******************************************************************************
|
||||
Cube vertex buffer with packed vertex formats for color and texture coords.
|
||||
Note that a vertex format which must be portable across all
|
||||
backends must only use the normalized integer formats
|
||||
(BYTE4N, UBYTE4N, SHORT2N, SHORT4N), which can be converted
|
||||
to floating point formats in the vertex shader inputs.
|
||||
The reason is that D3D11 cannot convert from non-normalized
|
||||
formats to floating point inputs (only to integer inputs),
|
||||
and WebGL2 / GLES2 does not support integer vertex shader inputs.
|
||||
*/
|
||||
struct Vertex_t {
|
||||
x f32
|
||||
y f32
|
||||
z f32
|
||||
color u32
|
||||
u f32
|
||||
v f32
|
||||
}
|
||||
|
||||
const vertices = cube_vertices()
|
||||
|
||||
fn cube_vertices() []Vertex_t {
|
||||
// cube vertex buffer
|
||||
d := f32(1.0)
|
||||
c := u32(0xFF_FF_FF_FF) // white color RGBA8
|
||||
// vfmt off
|
||||
// 6 faces, each defined by 4 vertices:
|
||||
cube := [
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0}, Vertex_t{ 1.0, -1.0, -1.0, c, d, 0}, Vertex_t{ 1.0, 1.0, -1.0, c, d, d}, Vertex_t{-1.0, 1.0, -1.0, c, 0, d},
|
||||
Vertex_t{-1.0, -1.0, 1.0, c, 0, 0}, Vertex_t{ 1.0, -1.0, 1.0, c, d, 0}, Vertex_t{ 1.0, 1.0, 1.0, c, d, d}, Vertex_t{-1.0, 1.0, 1.0, c, 0, d},
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0}, Vertex_t{-1.0, 1.0, -1.0, c, d, 0}, Vertex_t{-1.0, 1.0, 1.0, c, d, d}, Vertex_t{-1.0, -1.0, 1.0, c, 0, d},
|
||||
Vertex_t{ 1.0, -1.0, -1.0, c, 0, 0}, Vertex_t{ 1.0, 1.0, -1.0, c, d, 0}, Vertex_t{ 1.0, 1.0, 1.0, c, d, d}, Vertex_t{ 1.0, -1.0, 1.0, c, 0, d},
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0}, Vertex_t{-1.0, -1.0, 1.0, c, d, 0}, Vertex_t{ 1.0, -1.0, 1.0, c, d, d}, Vertex_t{ 1.0, -1.0, -1.0, c, 0, d},
|
||||
Vertex_t{-1.0, 1.0, -1.0, c, 0, 0}, Vertex_t{-1.0, 1.0, 1.0, c, d, 0}, Vertex_t{ 1.0, 1.0, 1.0, c, d, d}, Vertex_t{ 1.0, 1.0, -1.0, c, 0, d},
|
||||
]
|
||||
// vfmt off
|
||||
return cube
|
||||
}
|
||||
|
||||
fn (mut app App) init_glsl_shader(shader_name string, shader_desc &gfx.ShaderDesc, indices []u16) {
|
||||
mut vert_buffer_desc := gfx.BufferDesc{}
|
||||
unsafe { vmemset(&vert_buffer_desc, 0, sizeof(vert_buffer_desc)) }
|
||||
vert_buffer_desc.label = c'cube-vertices'
|
||||
vert_buffer_desc.size = usize(vertices.len) * sizeof(Vertex_t)
|
||||
vert_buffer_desc.data = gfx.Range{
|
||||
ptr: vertices.data
|
||||
size: vert_buffer_desc.size
|
||||
}
|
||||
vert_buffer_desc.type = .vertexbuffer
|
||||
vbuf := gfx.make_buffer(&vert_buffer_desc)
|
||||
|
||||
mut index_buffer_desc := gfx.BufferDesc{}
|
||||
unsafe { vmemset(&index_buffer_desc, 0, sizeof(index_buffer_desc)) }
|
||||
index_buffer_desc.label = c'cube-indices'
|
||||
index_buffer_desc.size = usize(indices.len) * sizeof(u16)
|
||||
index_buffer_desc.data = gfx.Range{
|
||||
ptr: indices.data
|
||||
size: index_buffer_desc.size
|
||||
}
|
||||
index_buffer_desc.type = .indexbuffer
|
||||
ibuf := gfx.make_buffer(&index_buffer_desc)
|
||||
|
||||
// create shader
|
||||
shader := gfx.make_shader(shader_desc)
|
||||
|
||||
mut pipdesc := gfx.PipelineDesc{}
|
||||
unsafe { vmemset(&pipdesc, 0, sizeof(pipdesc)) }
|
||||
pipdesc.label = c'glsl_shader pipeline'
|
||||
pipdesc.layout.buffers[0].stride = int(sizeof(Vertex_t))
|
||||
|
||||
// the constants [C.ATTR_vs_m_pos, C.ATTR_vs_m_color0, C.ATTR_vs_m_texcoord0] are generated by sokol-shdc
|
||||
pipdesc.layout.attrs[C.ATTR_vs_m_pos].format = .float3 // x,y,z as f32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_m_color0].format = .ubyte4n // color as u32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_m_texcoord0].format = .float2 // u,v as f32
|
||||
// pipdesc.layout.attrs[C.ATTR_vs_m_texcoord0].format = .short2n // u,v as u16
|
||||
pipdesc.shader = shader
|
||||
pipdesc.index_type = .uint16
|
||||
pipdesc.depth = gfx.DepthState{
|
||||
write_enabled: true
|
||||
compare: .less_equal
|
||||
}
|
||||
pipdesc.cull_mode = .back
|
||||
|
||||
mut bind := gfx.Bindings{}
|
||||
unsafe { vmemset(&bind, 0, sizeof(bind)) }
|
||||
bind.vertex_buffers[0] = vbuf
|
||||
bind.index_buffer = ibuf
|
||||
bind.fs.images[C.SLOT_tex] = app.texture
|
||||
bind.fs.samplers[C.SLOT_smp] = app.sampler
|
||||
app.bind[shader_name] = bind
|
||||
app.pipe[shader_name] = gfx.make_pipeline(&pipdesc)
|
||||
println('${@FN} for shader `${shader_name}` done.')
|
||||
}
|
||||
|
||||
fn calc_tr_matrices(w f32, h f32, rx f32, ry f32, in_scale f32) m4.Mat4 {
|
||||
proj := m4.perspective(60, w / h, 0.01, 10.0)
|
||||
view := m4.look_at(m4.vec4(0.0, 0, 6, 0), m4.vec4(0, 0, 0, 0), m4.vec4(0, 1, 0, 0))
|
||||
view_proj := view * proj
|
||||
|
||||
rxm := m4.rotate(m4.rad(rx), m4.vec4(1, 0, 0, 0))
|
||||
rym := m4.rotate(m4.rad(ry), m4.vec4(0, 1, 0, 0))
|
||||
|
||||
model := rym * rxm
|
||||
scale_m := m4.scale(m4.vec4(in_scale, in_scale, in_scale, 1))
|
||||
|
||||
res := (scale_m * model) * view_proj
|
||||
return res
|
||||
}
|
||||
|
||||
fn (app &App) draw_glsl_shader(shader_name string) {
|
||||
ws := gg.window_size_real_pixels()
|
||||
ratio := f32(ws.width) / ws.height
|
||||
dw := f32(ws.width / 2)
|
||||
dh := f32(ws.height / 2)
|
||||
|
||||
rot := [f32(app.mouse_y), f32(app.mouse_x)]
|
||||
tr_matrix := calc_tr_matrices(dw, dh, rot[0], rot[1], 2.3)
|
||||
|
||||
// apply the pipeline and bindings
|
||||
gfx.apply_pipeline(app.pipe[shader_name])
|
||||
gfx.apply_bindings(app.bind[shader_name])
|
||||
|
||||
// Uniforms
|
||||
// *** vertex shadeer uniforms ***
|
||||
// passing the view matrix as uniform
|
||||
// res is a 4x4 matrix of f32 thus: 4*16 byte of size
|
||||
vs_uniforms_range := gfx.Range{
|
||||
ptr: &tr_matrix
|
||||
size: usize(4 * 16)
|
||||
}
|
||||
gfx.apply_uniforms(.vs, C.SLOT_vs_params_m, &vs_uniforms_range)
|
||||
|
||||
// *** fragment shader uniforms ***
|
||||
time_ticks := f32(time.ticks() - start_ticks) / 1000
|
||||
mut tmp_fs_params := [
|
||||
f32(ws.width),
|
||||
ws.height * ratio, // x,y resolution to pass to FS
|
||||
0,
|
||||
0, // dont send mouse position
|
||||
// app.mouse_x, // mouse x
|
||||
// ws.height - app.mouse_y*2, // mouse y scaled
|
||||
time_ticks, // time as f32
|
||||
f32(app.gg.frame), // frame count
|
||||
0,
|
||||
0, // padding bytes , see "fs_params" struct paddings in rt_glsl.h
|
||||
]!
|
||||
fs_uniforms_range := gfx.Range{
|
||||
ptr: unsafe { &tmp_fs_params }
|
||||
size: usize(sizeof(tmp_fs_params))
|
||||
}
|
||||
gfx.apply_uniforms(.fs, C.SLOT_fs_params_p, &fs_uniforms_range)
|
||||
|
||||
// 3 vertices for triangle * 2 triangles per face * 6 faces = 36 vertices to draw
|
||||
gfx.draw(0, (3 * 2) * 3, 1)
|
||||
}
|
||||
|
||||
fn (mut app App) frame() {
|
||||
mut pass_action := gfx.PassAction{}
|
||||
pass_action.colors[0] = gfx.ColorAttachmentAction{
|
||||
load_action: .clear
|
||||
clear_value: gfx.Color{b: 0.9}
|
||||
}
|
||||
gfx.begin_pass(sapp.create_default_pass(pass_action))
|
||||
if !app.init_flag {
|
||||
return
|
||||
}
|
||||
ws := gg.window_size_real_pixels()
|
||||
gfx.apply_viewport(0, 0, ws.width, ws.height, true)
|
||||
app.draw_glsl_shader('march')
|
||||
app.draw_glsl_shader('puppy')
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
|
||||
fn (mut app App) on_init() {
|
||||
// set max vertices, but note, that for a large number of the same type of object it is better use the instances!!
|
||||
gfx.setup(sapp.create_desc())
|
||||
sgl.setup(sgl.Desc{max_vertices: 50 * 65536})
|
||||
|
||||
// create chessboard texture 256*256 RGBA
|
||||
w := 256
|
||||
h := 256
|
||||
sz := w * h * 4
|
||||
tmp_txt := unsafe { malloc(sz) }
|
||||
defer {
|
||||
unsafe { free(tmp_txt) }
|
||||
}
|
||||
mut i := 0
|
||||
for i < sz {
|
||||
unsafe {
|
||||
y := (i >> 0x8) >> 5 // 8 cell
|
||||
x := (i & 0xFF) >> 5 // 8 cell
|
||||
// upper left corner
|
||||
if x == 0 && y == 0 {
|
||||
tmp_txt[i + 0] = 0xFF
|
||||
tmp_txt[i + 1] = 0
|
||||
tmp_txt[i + 2] = 0
|
||||
tmp_txt[i + 3] = 0xFF
|
||||
}
|
||||
// low right corner
|
||||
else if x == 7 && y == 7 {
|
||||
tmp_txt[i + 0] = 0
|
||||
tmp_txt[i + 1] = 0xFF
|
||||
tmp_txt[i + 2] = 0
|
||||
tmp_txt[i + 3] = 0xFF
|
||||
} else {
|
||||
col := if ((x + y) & 1) == 1 { u8(0xFF) } else { 128 }
|
||||
tmp_txt[i + 0] = col // red
|
||||
tmp_txt[i + 1] = col // green
|
||||
tmp_txt[i + 2] = col // blue
|
||||
tmp_txt[i + 3] = 0xFF // alpha
|
||||
}
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
app.texture, app.sampler = create_texture(w, h, tmp_txt)
|
||||
|
||||
// vfmt off
|
||||
app.init_glsl_shader('march', voidptr(C.rt_march_shader_desc(C.sg_query_backend())), [
|
||||
u16(0), 1, 2, 0, 2, 3,
|
||||
6, 5, 4, 7, 6, 4,
|
||||
8, 9, 10, 8, 10, 11,
|
||||
])
|
||||
app.init_glsl_shader('puppy', voidptr(C.rt_puppy_shader_desc(C.sg_query_backend())), [
|
||||
u16(14), 13, 12, 15, 14, 12,
|
||||
16, 17, 18, 16, 18, 19,
|
||||
22, 21, 20, 23, 22, 20,
|
||||
])
|
||||
// vfmt on
|
||||
app.init_flag = true
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* events handling
|
||||
******************************************************************************/
|
||||
fn (mut app App) on_event(ev &gg.Event, x voidptr) {
|
||||
if ev.typ == .mouse_down {
|
||||
app.mouse_down = true
|
||||
}
|
||||
if ev.typ == .mouse_up {
|
||||
app.mouse_down = false
|
||||
}
|
||||
if app.mouse_down == true && ev.typ == .mouse_move {
|
||||
app.mouse_x = int(ev.mouse_x)
|
||||
app.mouse_y = int(ev.mouse_y)
|
||||
}
|
||||
if ev.typ == .touches_began || ev.typ == .touches_moved {
|
||||
if ev.num_touches > 0 {
|
||||
touch_point := ev.touches[0]
|
||||
app.mouse_x = int(touch_point.pos_x)
|
||||
app.mouse_y = int(touch_point.pos_y)
|
||||
}
|
||||
}
|
||||
// eprintln('> app.mouse_x: ${app.mouse_x} | app.mouse_y: ${app.mouse_y}')
|
||||
}
|
||||
|
||||
fn main() {
|
||||
mut app := &App{}
|
||||
app.gg = gg.new_context(
|
||||
width: 800
|
||||
height: 800
|
||||
window_title: '3D Dual shader Cube - click and rotate with the mouse'
|
||||
user_data: app
|
||||
frame_fn: app.frame
|
||||
init_fn: app.on_init
|
||||
event_fn: app.on_event
|
||||
)
|
||||
app.gg.run()
|
||||
}
|
||||
@@ -0,0 +1,697 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// Shader code for texcube-sapp sample.
|
||||
//
|
||||
// NOTE: This source file also uses the '#pragma sokol' form of the
|
||||
// custom tags.
|
||||
//------------------------------------------------------------------------------
|
||||
//#pragma sokol @ctype mat4 hmm_mat4
|
||||
|
||||
#pragma sokol @vs vs_m
|
||||
uniform vs_params_m {
|
||||
mat4 mvp;
|
||||
};
|
||||
|
||||
in vec4 pos;
|
||||
in vec4 color0;
|
||||
in vec2 texcoord0;
|
||||
|
||||
out vec4 color;
|
||||
out vec2 uv;
|
||||
|
||||
void main() {
|
||||
gl_Position = mvp * pos;
|
||||
color = color0;
|
||||
uv = texcoord0;
|
||||
}
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @fs fs_m
|
||||
uniform texture2D tex;
|
||||
uniform sampler smp;
|
||||
|
||||
uniform fs_params_m {
|
||||
vec2 iResolution;
|
||||
vec2 iMouse;
|
||||
float iTime;
|
||||
float iFrame;
|
||||
};
|
||||
|
||||
in vec4 color;
|
||||
in vec2 uv;
|
||||
out vec4 frag_color;
|
||||
|
||||
// change to 0 to 4 to increment the AntiAliasing,
|
||||
// increase AA will SLOW the rendering!!
|
||||
#define AA 1
|
||||
|
||||
//*********************************************************
|
||||
// Ray Marching
|
||||
// original code from: https://www.shadertoy.com/view/Xds3zN
|
||||
//*********************************************************
|
||||
// The MIT License
|
||||
// Copyright © 2013 Inigo Quilez
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
// A list of useful distance function to simple primitives. All
|
||||
// these functions (except for ellipsoid) return an exact
|
||||
// euclidean distance, meaning they produce a better SDF than
|
||||
// what you'd get if you were constructing them from boolean
|
||||
// operations.
|
||||
//
|
||||
// More info here:
|
||||
//
|
||||
// https://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
|
||||
|
||||
//------------------------------------------------------------------
|
||||
float dot2( in vec2 v ) { return dot(v,v); }
|
||||
float dot2( in vec3 v ) { return dot(v,v); }
|
||||
float ndot( in vec2 a, in vec2 b ) { return a.x*b.x - a.y*b.y; }
|
||||
|
||||
float sdPlane( vec3 p )
|
||||
{
|
||||
return p.y;
|
||||
}
|
||||
|
||||
float sdSphere( vec3 p, float s )
|
||||
{
|
||||
return length(p)-s;
|
||||
}
|
||||
|
||||
float sdBox( vec3 p, vec3 b )
|
||||
{
|
||||
vec3 d = abs(p) - b;
|
||||
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
|
||||
}
|
||||
|
||||
float sdBoundingBox( vec3 p, vec3 b, float e )
|
||||
{
|
||||
p = abs(p )-b;
|
||||
vec3 q = abs(p+e)-e;
|
||||
|
||||
return min(min(
|
||||
length(max(vec3(p.x,q.y,q.z),0.0))+min(max(p.x,max(q.y,q.z)),0.0),
|
||||
length(max(vec3(q.x,p.y,q.z),0.0))+min(max(q.x,max(p.y,q.z)),0.0)),
|
||||
length(max(vec3(q.x,q.y,p.z),0.0))+min(max(q.x,max(q.y,p.z)),0.0));
|
||||
}
|
||||
float sdEllipsoid( in vec3 p, in vec3 r ) // approximated
|
||||
{
|
||||
float k0 = length(p/r);
|
||||
float k1 = length(p/(r*r));
|
||||
return k0*(k0-1.0)/k1;
|
||||
}
|
||||
|
||||
float sdTorus( vec3 p, vec2 t )
|
||||
{
|
||||
return length( vec2(length(p.xz)-t.x,p.y) )-t.y;
|
||||
}
|
||||
|
||||
float sdCappedTorus(in vec3 p, in vec2 sc, in float ra, in float rb)
|
||||
{
|
||||
p.x = abs(p.x);
|
||||
float k = (sc.y*p.x>sc.x*p.y) ? dot(p.xy,sc) : length(p.xy);
|
||||
return sqrt( dot(p,p) + ra*ra - 2.0*ra*k ) - rb;
|
||||
}
|
||||
|
||||
float sdHexPrism( vec3 p, vec2 h )
|
||||
{
|
||||
vec3 q = abs(p);
|
||||
|
||||
const vec3 k = vec3(-0.8660254, 0.5, 0.57735);
|
||||
p = abs(p);
|
||||
p.xy -= 2.0*min(dot(k.xy, p.xy), 0.0)*k.xy;
|
||||
vec2 d = vec2(
|
||||
length(p.xy - vec2(clamp(p.x, -k.z*h.x, k.z*h.x), h.x))*sign(p.y - h.x),
|
||||
p.z-h.y );
|
||||
return min(max(d.x,d.y),0.0) + length(max(d,0.0));
|
||||
}
|
||||
|
||||
float sdOctogonPrism( in vec3 p, in float r, float h )
|
||||
{
|
||||
const vec3 k = vec3(-0.9238795325, // sqrt(2+sqrt(2))/2
|
||||
0.3826834323, // sqrt(2-sqrt(2))/2
|
||||
0.4142135623 ); // sqrt(2)-1
|
||||
// reflections
|
||||
p = abs(p);
|
||||
p.xy -= 2.0*min(dot(vec2( k.x,k.y),p.xy),0.0)*vec2( k.x,k.y);
|
||||
p.xy -= 2.0*min(dot(vec2(-k.x,k.y),p.xy),0.0)*vec2(-k.x,k.y);
|
||||
// polygon side
|
||||
p.xy -= vec2(clamp(p.x, -k.z*r, k.z*r), r);
|
||||
vec2 d = vec2( length(p.xy)*sign(p.y), p.z-h );
|
||||
return min(max(d.x,d.y),0.0) + length(max(d,0.0));
|
||||
}
|
||||
|
||||
float sdCapsule( vec3 p, vec3 a, vec3 b, float r )
|
||||
{
|
||||
vec3 pa = p-a, ba = b-a;
|
||||
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
|
||||
return length( pa - ba*h ) - r;
|
||||
}
|
||||
|
||||
float sdRoundCone( in vec3 p, in float r1, float r2, float h )
|
||||
{
|
||||
vec2 q = vec2( length(p.xz), p.y );
|
||||
|
||||
float b = (r1-r2)/h;
|
||||
float a = sqrt(1.0-b*b);
|
||||
float k = dot(q,vec2(-b,a));
|
||||
|
||||
if( k < 0.0 ) return length(q) - r1;
|
||||
if( k > a*h ) return length(q-vec2(0.0,h)) - r2;
|
||||
|
||||
return dot(q, vec2(a,b) ) - r1;
|
||||
}
|
||||
|
||||
float sdRoundCone(vec3 p, vec3 a, vec3 b, float r1, float r2)
|
||||
{
|
||||
// sampling independent computations (only depend on shape)
|
||||
vec3 ba = b - a;
|
||||
float l2 = dot(ba,ba);
|
||||
float rr = r1 - r2;
|
||||
float a2 = l2 - rr*rr;
|
||||
float il2 = 1.0/l2;
|
||||
|
||||
// sampling dependent computations
|
||||
vec3 pa = p - a;
|
||||
float y = dot(pa,ba);
|
||||
float z = y - l2;
|
||||
float x2 = dot2( pa*l2 - ba*y );
|
||||
float y2 = y*y*l2;
|
||||
float z2 = z*z*l2;
|
||||
|
||||
// single square root!
|
||||
float k = sign(rr)*rr*rr*x2;
|
||||
if( sign(z)*a2*z2 > k ) return sqrt(x2 + z2) *il2 - r2;
|
||||
if( sign(y)*a2*y2 < k ) return sqrt(x2 + y2) *il2 - r1;
|
||||
return (sqrt(x2*a2*il2)+y*rr)*il2 - r1;
|
||||
}
|
||||
|
||||
float sdTriPrism( vec3 p, vec2 h )
|
||||
{
|
||||
const float k = sqrt(3.0);
|
||||
h.x *= 0.5*k;
|
||||
p.xy /= h.x;
|
||||
p.x = abs(p.x) - 1.0;
|
||||
p.y = p.y + 1.0/k;
|
||||
if( p.x+k*p.y>0.0 ) p.xy=vec2(p.x-k*p.y,-k*p.x-p.y)/2.0;
|
||||
p.x -= clamp( p.x, -2.0, 0.0 );
|
||||
float d1 = length(p.xy)*sign(-p.y)*h.x;
|
||||
float d2 = abs(p.z)-h.y;
|
||||
return length(max(vec2(d1,d2),0.0)) + min(max(d1,d2), 0.);
|
||||
}
|
||||
|
||||
// vertical
|
||||
float sdCylinder( vec3 p, vec2 h )
|
||||
{
|
||||
vec2 d = abs(vec2(length(p.xz),p.y)) - h;
|
||||
return min(max(d.x,d.y),0.0) + length(max(d,0.0));
|
||||
}
|
||||
|
||||
// arbitrary orientation
|
||||
float sdCylinder(vec3 p, vec3 a, vec3 b, float r)
|
||||
{
|
||||
vec3 pa = p - a;
|
||||
vec3 ba = b - a;
|
||||
float baba = dot(ba,ba);
|
||||
float paba = dot(pa,ba);
|
||||
|
||||
float x = length(pa*baba-ba*paba) - r*baba;
|
||||
float y = abs(paba-baba*0.5)-baba*0.5;
|
||||
float x2 = x*x;
|
||||
float y2 = y*y*baba;
|
||||
float d = (max(x,y)<0.0)?-min(x2,y2):(((x>0.0)?x2:0.0)+((y>0.0)?y2:0.0));
|
||||
return sign(d)*sqrt(abs(d))/baba;
|
||||
}
|
||||
|
||||
// vertical
|
||||
float sdCone( in vec3 p, in vec2 c, float h )
|
||||
{
|
||||
vec2 q = h*vec2(c.x,-c.y)/c.y;
|
||||
vec2 w = vec2( length(p.xz), p.y );
|
||||
|
||||
vec2 a = w - q*clamp( dot(w,q)/dot(q,q), 0.0, 1.0 );
|
||||
vec2 b = w - q*vec2( clamp( w.x/q.x, 0.0, 1.0 ), 1.0 );
|
||||
float k = sign( q.y );
|
||||
float d = min(dot( a, a ),dot(b, b));
|
||||
float s = max( k*(w.x*q.y-w.y*q.x),k*(w.y-q.y) );
|
||||
return sqrt(d)*sign(s);
|
||||
}
|
||||
|
||||
float sdCappedCone( in vec3 p, in float h, in float r1, in float r2 )
|
||||
{
|
||||
vec2 q = vec2( length(p.xz), p.y );
|
||||
|
||||
vec2 k1 = vec2(r2,h);
|
||||
vec2 k2 = vec2(r2-r1,2.0*h);
|
||||
vec2 ca = vec2(q.x-min(q.x,(q.y < 0.0)?r1:r2), abs(q.y)-h);
|
||||
vec2 cb = q - k1 + k2*clamp( dot(k1-q,k2)/dot2(k2), 0.0, 1.0 );
|
||||
float s = (cb.x < 0.0 && ca.y < 0.0) ? -1.0 : 1.0;
|
||||
return s*sqrt( min(dot2(ca),dot2(cb)) );
|
||||
}
|
||||
|
||||
float sdCappedCone(vec3 p, vec3 a, vec3 b, float ra, float rb)
|
||||
{
|
||||
float rba = rb-ra;
|
||||
float baba = dot(b-a,b-a);
|
||||
float papa = dot(p-a,p-a);
|
||||
float paba = dot(p-a,b-a)/baba;
|
||||
|
||||
float x = sqrt( papa - paba*paba*baba );
|
||||
|
||||
float cax = max(0.0,x-((paba<0.5)?ra:rb));
|
||||
float cay = abs(paba-0.5)-0.5;
|
||||
|
||||
float k = rba*rba + baba;
|
||||
float f = clamp( (rba*(x-ra)+paba*baba)/k, 0.0, 1.0 );
|
||||
|
||||
float cbx = x-ra - f*rba;
|
||||
float cby = paba - f;
|
||||
|
||||
float s = (cbx < 0.0 && cay < 0.0) ? -1.0 : 1.0;
|
||||
|
||||
return s*sqrt( min(cax*cax + cay*cay*baba,
|
||||
cbx*cbx + cby*cby*baba) );
|
||||
}
|
||||
|
||||
// c is the sin/cos of the desired cone angle
|
||||
float sdSolidAngle(vec3 pos, vec2 c, float ra)
|
||||
{
|
||||
vec2 p = vec2( length(pos.xz), pos.y );
|
||||
float l = length(p) - ra;
|
||||
float m = length(p - c*clamp(dot(p,c),0.0,ra) );
|
||||
return max(l,m*sign(c.y*p.x-c.x*p.y));
|
||||
}
|
||||
|
||||
float sdOctahedron(vec3 p, float s)
|
||||
{
|
||||
p = abs(p);
|
||||
float m = p.x + p.y + p.z - s;
|
||||
|
||||
// exact distance
|
||||
#if 0
|
||||
vec3 o = min(3.0*p - m, 0.0);
|
||||
o = max(6.0*p - m*2.0 - o*3.0 + (o.x+o.y+o.z), 0.0);
|
||||
return length(p - s*o/(o.x+o.y+o.z));
|
||||
#endif
|
||||
|
||||
// exact distance
|
||||
#if 1
|
||||
vec3 q;
|
||||
if( 3.0*p.x < m ) q = p.xyz;
|
||||
else if( 3.0*p.y < m ) q = p.yzx;
|
||||
else if( 3.0*p.z < m ) q = p.zxy;
|
||||
else return m*0.57735027;
|
||||
float k = clamp(0.5*(q.z-q.y+s),0.0,s);
|
||||
return length(vec3(q.x,q.y-s+k,q.z-k));
|
||||
#endif
|
||||
|
||||
// bound, not exact
|
||||
#if 0
|
||||
return m*0.57735027;
|
||||
#endif
|
||||
}
|
||||
|
||||
float sdPyramid( in vec3 p, in float h )
|
||||
{
|
||||
float m2 = h*h + 0.25;
|
||||
|
||||
// symmetry
|
||||
p.xz = abs(p.xz);
|
||||
p.xz = (p.z>p.x) ? p.zx : p.xz;
|
||||
p.xz -= 0.5;
|
||||
|
||||
// project into face plane (2D)
|
||||
vec3 q = vec3( p.z, h*p.y - 0.5*p.x, h*p.x + 0.5*p.y);
|
||||
|
||||
float s = max(-q.x,0.0);
|
||||
float t = clamp( (q.y-0.5*p.z)/(m2+0.25), 0.0, 1.0 );
|
||||
|
||||
float a = m2*(q.x+s)*(q.x+s) + q.y*q.y;
|
||||
float b = m2*(q.x+0.5*t)*(q.x+0.5*t) + (q.y-m2*t)*(q.y-m2*t);
|
||||
|
||||
float d2 = min(q.y,-q.x*m2-q.y*0.5) > 0.0 ? 0.0 : min(a,b);
|
||||
|
||||
// recover 3D and scale, and add sign
|
||||
return sqrt( (d2+q.z*q.z)/m2 ) * sign(max(q.z,-p.y));
|
||||
}
|
||||
|
||||
// la,lb=semi axis, h=height, ra=corner
|
||||
float sdRhombus(vec3 p, float la, float lb, float h, float ra)
|
||||
{
|
||||
p = abs(p);
|
||||
vec2 b = vec2(la,lb);
|
||||
float f = clamp( (ndot(b,b-2.0*p.xz))/dot(b,b), -1.0, 1.0 );
|
||||
vec2 q = vec2(length(p.xz-0.5*b*vec2(1.0-f,1.0+f))*sign(p.x*b.y+p.z*b.x-b.x*b.y)-ra, p.y-h);
|
||||
return min(max(q.x,q.y),0.0) + length(max(q,0.0));
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
vec2 opU( vec2 d1, vec2 d2 )
|
||||
{
|
||||
return (d1.x<d2.x) ? d1 : d2;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
#define ZERO (min(int(iFrame),0))
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
vec2 map( in vec3 pos )
|
||||
{
|
||||
vec2 res = vec2( 1e10, 0.0 );
|
||||
|
||||
{
|
||||
res = opU( res, vec2( sdSphere( pos-vec3(-2.0,0.25, 0.0), 0.25 ), 26.9 ) );
|
||||
}
|
||||
|
||||
// bounding box
|
||||
if( sdBox( pos-vec3(0.0,0.3,-1.0),vec3(0.35,0.3,2.5) )<res.x )
|
||||
{
|
||||
// more primitives
|
||||
res = opU( res, vec2( sdBoundingBox( pos-vec3( 0.0,0.25, 0.0), vec3(0.3,0.25,0.2), 0.025 ), 16.9 ) );
|
||||
res = opU( res, vec2( sdTorus( (pos-vec3( 0.0,0.30, 1.0)).xzy, vec2(0.25,0.05) ), 25.0 ) );
|
||||
res = opU( res, vec2( sdCone( pos-vec3( 0.0,0.45,-1.0), vec2(0.6,0.8),0.45 ), 55.0 ) );
|
||||
res = opU( res, vec2( sdCappedCone( pos-vec3( 0.0,0.25,-2.0), 0.25, 0.25, 0.1 ), 13.67 ) );
|
||||
res = opU( res, vec2( sdSolidAngle( pos-vec3( 0.0,0.00,-3.0), vec2(3,4)/5.0, 0.4 ), 49.13 ) );
|
||||
}
|
||||
|
||||
// bounding box
|
||||
if( sdBox( pos-vec3(1.0,0.3,-1.0),vec3(0.35,0.3,2.5) )<res.x )
|
||||
{
|
||||
// more primitives
|
||||
res = opU( res, vec2( sdCappedTorus((pos-vec3( 1.0,0.30, 1.0))*vec3(1,-1,1), vec2(0.866025,-0.5), 0.25, 0.05), 8.5) );
|
||||
res = opU( res, vec2( sdBox( pos-vec3( 1.0,0.25, 0.0), vec3(0.3,0.25,0.1) ), 3.0 ) );
|
||||
res = opU( res, vec2( sdCapsule( pos-vec3( 1.0,0.00,-1.0),vec3(-0.1,0.1,-0.1), vec3(0.2,0.4,0.2), 0.1 ), 31.9 ) );
|
||||
res = opU( res, vec2( sdCylinder( pos-vec3( 1.0,0.25,-2.0), vec2(0.15,0.25) ), 8.0 ) );
|
||||
res = opU( res, vec2( sdHexPrism( pos-vec3( 1.0,0.2,-3.0), vec2(0.2,0.05) ), 18.4 ) );
|
||||
}
|
||||
|
||||
// bounding box
|
||||
if( sdBox( pos-vec3(-1.0,0.35,-1.0),vec3(0.35,0.35,2.5))<res.x )
|
||||
{
|
||||
// more primitives
|
||||
res = opU( res, vec2( sdPyramid( pos-vec3(-1.0,-0.6,-3.0), 1.0 ), 13.56 ) );
|
||||
res = opU( res, vec2( sdOctahedron( pos-vec3(-1.0,0.15,-2.0), 0.35 ), 23.56 ) );
|
||||
res = opU( res, vec2( sdTriPrism( pos-vec3(-1.0,0.15,-1.0), vec2(0.3,0.05) ),43.5 ) );
|
||||
res = opU( res, vec2( sdEllipsoid( pos-vec3(-1.0,0.25, 0.0), vec3(0.2, 0.25, 0.05) ), 43.17 ) );
|
||||
res = opU( res, vec2( sdRhombus( (pos-vec3(-1.0,0.34, 1.0)).xzy, 0.15, 0.25, 0.04, 0.08 ),17.0 ) );
|
||||
}
|
||||
|
||||
// bounding box
|
||||
if( sdBox( pos-vec3(2.0,0.3,-1.0),vec3(0.35,0.3,2.5) )<res.x )
|
||||
{
|
||||
// more primitives
|
||||
res = opU( res, vec2( sdOctogonPrism(pos-vec3( 2.0,0.2,-3.0), 0.2, 0.05), 51.8 ) );
|
||||
res = opU( res, vec2( sdCylinder( pos-vec3( 2.0,0.15,-2.0), vec3(0.1,-0.1,0.0), vec3(-0.2,0.35,0.1), 0.08), 31.2 ) );
|
||||
res = opU( res, vec2( sdCappedCone( pos-vec3( 2.0,0.10,-1.0), vec3(0.1,0.0,0.0), vec3(-0.2,0.40,0.1), 0.15, 0.05), 46.1 ) );
|
||||
res = opU( res, vec2( sdRoundCone( pos-vec3( 2.0,0.15, 0.0), vec3(0.1,0.0,0.0), vec3(-0.1,0.35,0.1), 0.15, 0.05), 51.7 ) );
|
||||
res = opU( res, vec2( sdRoundCone( pos-vec3( 2.0,0.20, 1.0), 0.2, 0.1, 0.3 ), 37.0 ) );
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/boxfunctions/boxfunctions.htm
|
||||
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 rad )
|
||||
{
|
||||
vec3 m = 1.0/rd;
|
||||
vec3 n = m*ro;
|
||||
vec3 k = abs(m)*rad;
|
||||
vec3 t1 = -n - k;
|
||||
vec3 t2 = -n + k;
|
||||
return vec2( max( max( t1.x, t1.y ), t1.z ),
|
||||
min( min( t2.x, t2.y ), t2.z ) );
|
||||
}
|
||||
|
||||
vec2 raycast( in vec3 ro, in vec3 rd )
|
||||
{
|
||||
vec2 res = vec2(-1.0,-1.0);
|
||||
|
||||
float tmin = 1.0;
|
||||
float tmax = 20.0;
|
||||
|
||||
// raytrace floor plane
|
||||
float tp1 = (0.0-ro.y)/rd.y;
|
||||
if( tp1>0.0 )
|
||||
{
|
||||
tmax = min( tmax, tp1 );
|
||||
res = vec2( tp1, 1.0 );
|
||||
}
|
||||
//else return res;
|
||||
|
||||
// raymarch primitives
|
||||
vec2 tb = iBox( ro-vec3(0.0,0.4,-0.5), rd, vec3(2.5,0.41,3.0) );
|
||||
if( tb.x<tb.y && tb.y>0.0 && tb.x<tmax)
|
||||
{
|
||||
//return vec2(tb.x,2.0);
|
||||
tmin = max(tb.x,tmin);
|
||||
tmax = min(tb.y,tmax);
|
||||
|
||||
float t = tmin;
|
||||
for( int i=0; i<70 && t<tmax; i++ )
|
||||
{
|
||||
vec2 h = map( ro+rd*t );
|
||||
if( abs(h.x)<(0.0001*t) )
|
||||
{
|
||||
res = vec2(t,h.y);
|
||||
break;
|
||||
}
|
||||
t += h.x;
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/rmshadows/rmshadows.htm
|
||||
float calcSoftshadow( in vec3 ro, in vec3 rd, in float mint, in float tmax )
|
||||
{
|
||||
// bounding volume
|
||||
float tp = (0.8-ro.y)/rd.y; if( tp>0.0 ) tmax = min( tmax, tp );
|
||||
|
||||
float res = 1.0;
|
||||
float t = mint;
|
||||
for( int i=ZERO; i<24; i++ )
|
||||
{
|
||||
float h = map( ro + rd*t ).x;
|
||||
float s = clamp(8.0*h/t,0.0,1.0);
|
||||
res = min( res, s*s*(3.0-2.0*s) );
|
||||
t += clamp( h, 0.02, 0.2 );
|
||||
if( res<0.004 || t>tmax ) break;
|
||||
}
|
||||
return clamp( res, 0.0, 1.0 );
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/normalsSDF/normalsSDF.htm
|
||||
vec3 calcNormal( in vec3 pos )
|
||||
{
|
||||
#if 0
|
||||
vec2 e = vec2(1.0,-1.0)*0.5773*0.0005;
|
||||
return normalize( e.xyy*map( pos + e.xyy ).x +
|
||||
e.yyx*map( pos + e.yyx ).x +
|
||||
e.yxy*map( pos + e.yxy ).x +
|
||||
e.xxx*map( pos + e.xxx ).x );
|
||||
#else
|
||||
// inspired by tdhooper and klems - a way to prevent the compiler from inlining map() 4 times
|
||||
vec3 n = vec3(0.0);
|
||||
for( int i=ZERO; i<4; i++ )
|
||||
{
|
||||
vec3 e = 0.5773*(2.0*vec3((((i+3)>>1)&1),((i>>1)&1),(i&1))-1.0);
|
||||
n += e*map(pos+0.0005*e).x;
|
||||
//if( n.x+n.y+n.z>100.0 ) break;
|
||||
}
|
||||
return normalize(n);
|
||||
#endif
|
||||
}
|
||||
|
||||
float calcAO( in vec3 pos, in vec3 nor )
|
||||
{
|
||||
float occ = 0.0;
|
||||
float sca = 1.0;
|
||||
for( int i=ZERO; i<5; i++ )
|
||||
{
|
||||
float h = 0.01 + 0.12*float(i)/4.0;
|
||||
float d = map( pos + h*nor ).x;
|
||||
occ += (h-d)*sca;
|
||||
sca *= 0.95;
|
||||
if( occ>0.35 ) break;
|
||||
}
|
||||
return clamp( 1.0 - 3.0*occ, 0.0, 1.0 ) * (0.5+0.5*nor.y);
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/checkerfiltering/checkerfiltering.htm
|
||||
float checkersGradBox( in vec2 p, in vec2 dpdx, in vec2 dpdy )
|
||||
{
|
||||
// filter kernel
|
||||
vec2 w = abs(dpdx)+abs(dpdy) + 0.001;
|
||||
// analytical integral (box filter)
|
||||
vec2 i = 2.0*(abs(fract((p-0.5*w)*0.5)-0.5)-abs(fract((p+0.5*w)*0.5)-0.5))/w;
|
||||
// xor pattern
|
||||
return 0.5 - 0.5*i.x*i.y;
|
||||
}
|
||||
|
||||
vec3 render( in vec3 ro, in vec3 rd, in vec3 rdx, in vec3 rdy )
|
||||
{
|
||||
// background
|
||||
vec3 col = vec3(0.7, 0.7, 0.9) - max(rd.y,0.0)*0.3;
|
||||
|
||||
// raycast scene
|
||||
vec2 res = raycast(ro,rd);
|
||||
float t = res.x;
|
||||
float m = res.y;
|
||||
if( m>-0.5 )
|
||||
{
|
||||
vec3 pos = ro + t*rd;
|
||||
vec3 nor = (m<1.5) ? vec3(0.0,1.0,0.0) : calcNormal( pos );
|
||||
vec3 ref = reflect( rd, nor );
|
||||
|
||||
// material
|
||||
col = 0.2 + 0.2*sin( m*2.0 + vec3(0.0,1.0,2.0) );
|
||||
float ks = 1.0;
|
||||
|
||||
if( m<1.5 )
|
||||
{
|
||||
// project pixel footprint into the plane
|
||||
vec3 dpdx = ro.y*(rd/rd.y-rdx/rdx.y);
|
||||
vec3 dpdy = ro.y*(rd/rd.y-rdy/rdy.y);
|
||||
|
||||
float f = checkersGradBox( 3.0*pos.xz, 3.0*dpdx.xz, 3.0*dpdy.xz );
|
||||
col = 0.15 + f*vec3(0.05);
|
||||
ks = 0.4;
|
||||
}
|
||||
|
||||
// lighting
|
||||
float occ = calcAO( pos, nor );
|
||||
|
||||
vec3 lin = vec3(0.0);
|
||||
|
||||
// sun
|
||||
{
|
||||
vec3 lig = normalize( vec3(-0.5, 0.4, -0.6) );
|
||||
vec3 hal = normalize( lig-rd );
|
||||
float dif = clamp( dot( nor, lig ), 0.0, 1.0 );
|
||||
//if( dif>0.0001 )
|
||||
dif *= calcSoftshadow( pos, lig, 0.02, 2.5 );
|
||||
float spe = pow( clamp( dot( nor, hal ), 0.0, 1.0 ),16.0);
|
||||
spe *= dif;
|
||||
spe *= 0.04+0.96*pow(clamp(1.0-dot(hal,lig),0.0,1.0),5.0);
|
||||
lin += col*2.20*dif*vec3(1.30,1.00,0.70);
|
||||
lin += 5.00*spe*vec3(1.30,1.00,0.70)*ks;
|
||||
}
|
||||
// sky
|
||||
{
|
||||
float dif = sqrt(clamp( 0.5+0.5*nor.y, 0.0, 1.0 ));
|
||||
dif *= occ;
|
||||
float spe = smoothstep( -0.2, 0.2, ref.y );
|
||||
spe *= dif;
|
||||
spe *= 0.04+0.96*pow(clamp(1.0+dot(nor,rd),0.0,1.0), 5.0 );
|
||||
//if( spe>0.001 )
|
||||
spe *= calcSoftshadow( pos, ref, 0.02, 2.5 );
|
||||
lin += col*0.60*dif*vec3(0.40,0.60,1.15);
|
||||
lin += 2.00*spe*vec3(0.40,0.60,1.30)*ks;
|
||||
}
|
||||
// back
|
||||
{
|
||||
float dif = clamp( dot( nor, normalize(vec3(0.5,0.0,0.6))), 0.0, 1.0 )*clamp( 1.0-pos.y,0.0,1.0);
|
||||
dif *= occ;
|
||||
lin += col*0.55*dif*vec3(0.25,0.25,0.25);
|
||||
}
|
||||
// sss
|
||||
{
|
||||
float dif = pow(clamp(1.0+dot(nor,rd),0.0,1.0),2.0);
|
||||
dif *= occ;
|
||||
lin += col*0.25*dif*vec3(1.00,1.00,1.00);
|
||||
}
|
||||
|
||||
col = lin;
|
||||
|
||||
col = mix( col, vec3(0.7,0.7,0.9), 1.0-exp( -0.0001*t*t*t ) );
|
||||
}
|
||||
|
||||
return vec3( clamp(col,0.0,1.0) );
|
||||
}
|
||||
|
||||
mat3 setCamera( in vec3 ro, in vec3 ta, float cr )
|
||||
{
|
||||
vec3 cw = normalize(ta-ro);
|
||||
vec3 cp = vec3(sin(cr), cos(cr),0.0);
|
||||
vec3 cu = normalize( cross(cw,cp) );
|
||||
vec3 cv = ( cross(cu,cw) );
|
||||
return mat3( cu, cv, cw );
|
||||
}
|
||||
|
||||
vec4 mainImage( vec2 fragCoord )
|
||||
{
|
||||
vec2 mo = iMouse.xy/iResolution.xy;
|
||||
float time = 32.0 + iTime*1.5;
|
||||
|
||||
// camera
|
||||
vec3 ta = vec3( 0.5, -0.5, -0.6 );
|
||||
vec3 ro = ta + vec3( 4.5*cos(0.1*time + 7.0*mo.x), 1.3 + 2.0*mo.y, 4.5*sin(0.1*time + 7.0*mo.x) );
|
||||
// camera-to-world transformation
|
||||
mat3 ca = setCamera( ro, ta, 0.0 );
|
||||
|
||||
vec3 tot = vec3(0.0);
|
||||
#if AA>1
|
||||
for( int m=ZERO; m<AA; m++ )
|
||||
for( int n=ZERO; n<AA; n++ )
|
||||
{
|
||||
// pixel coordinates
|
||||
vec2 o = vec2(float(m),float(n)) / float(AA) - 0.5;
|
||||
vec2 p = (2.0*(fragCoord+o)-iResolution.xy)/iResolution.y;
|
||||
#else
|
||||
vec2 p = (2.0*fragCoord-iResolution.xy)/iResolution.y;
|
||||
#endif
|
||||
|
||||
// focal length
|
||||
const float fl = 2.5;
|
||||
|
||||
// ray direction
|
||||
vec3 rd = ca * normalize( vec3(p,fl) );
|
||||
|
||||
// ray differentials
|
||||
vec2 px = (2.0*(fragCoord+vec2(1.0,0.0))-iResolution.xy)/iResolution.y;
|
||||
vec2 py = (2.0*(fragCoord+vec2(0.0,1.0))-iResolution.xy)/iResolution.y;
|
||||
vec3 rdx = ca * normalize( vec3(px,fl) );
|
||||
vec3 rdy = ca * normalize( vec3(py,fl) );
|
||||
|
||||
// render
|
||||
vec3 col = render( ro, rd, rdx, rdy );
|
||||
|
||||
// gain
|
||||
// col = col*3.0/(2.5+col);
|
||||
|
||||
// gamma
|
||||
col = pow( col, vec3(0.4545) );
|
||||
|
||||
tot += col;
|
||||
#if AA>1
|
||||
}
|
||||
tot /= float(AA*AA);
|
||||
#endif
|
||||
|
||||
//fragColor = vec4( tot, 1.0 );
|
||||
return vec4( tot, 1.0 );
|
||||
}
|
||||
|
||||
//*********************************************************
|
||||
// END Ray Marching
|
||||
//*********************************************************
|
||||
|
||||
void main() {
|
||||
vec4 c = color;
|
||||
vec4 txt = texture(sampler2D(tex, smp), uv);
|
||||
c = txt * c;
|
||||
vec2 uv1 = uv * iResolution;
|
||||
vec4 col_ray = mainImage(uv1);
|
||||
|
||||
// use this to mix the chessboart texture with the ray marching
|
||||
//frag_color = clamp(c*iMouse.y/512.0,0.0,1.0) * col_ray ;
|
||||
|
||||
frag_color = c*0.00001 + col_ray ;
|
||||
}
|
||||
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @program rt_march vs_m fs_m
|
||||
@@ -0,0 +1,570 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// Shader code for texcube-sapp sample.
|
||||
//
|
||||
// NOTE: This source file also uses the '#pragma sokol' form of the
|
||||
// custom tags.
|
||||
//------------------------------------------------------------------------------
|
||||
//#pragma sokol @ctype mat4 hmm_mat4
|
||||
|
||||
#pragma sokol @vs vs_p
|
||||
uniform vs_params_p {
|
||||
mat4 mvp;
|
||||
};
|
||||
|
||||
in vec4 pos;
|
||||
in vec4 color0;
|
||||
in vec2 texcoord0;
|
||||
|
||||
out vec4 color;
|
||||
out vec2 uv;
|
||||
|
||||
void main() {
|
||||
gl_Position = mvp * pos;
|
||||
color = color0;
|
||||
uv = texcoord0;
|
||||
}
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @fs fs_p
|
||||
uniform texture2D tex;
|
||||
uniform sampler smp;
|
||||
|
||||
uniform fs_params_p {
|
||||
vec2 iResolution;
|
||||
vec2 iMouse;
|
||||
float iTime;
|
||||
float iFrame;
|
||||
};
|
||||
|
||||
in vec4 color;
|
||||
in vec2 uv;
|
||||
out vec4 frag_color;
|
||||
|
||||
// change to 0 to 4 to increment the AntiAliasing,
|
||||
// increase AA will SLOW the rendering!!
|
||||
#define AA 1
|
||||
|
||||
//*********************************************************
|
||||
// Ray Marching
|
||||
// original code from: https://www.shadertoy.com/view/Xds3zN
|
||||
//*********************************************************
|
||||
// Created by inigo quilez - iq/2019
|
||||
// I share this piece (art and code) here in Shadertoy and through its Public API, only for educational purposes.
|
||||
// You cannot use, share or host this piece or modifications of it as part of your own commercial or non-commercial product, website or project.
|
||||
// You can share a link to it or an unmodified screenshot of it provided you attribute "by Inigo Quilez, @iquilezles and iquilezles.org".
|
||||
// If you are a teacher, lecturer, educator or similar and these conditions are too restrictive for your needs, please contact me and we'll work it out.
|
||||
|
||||
|
||||
// An animation test - a happy and blobby creature
|
||||
// jumping and looking around. It gets off-model very
|
||||
// often, but it looks good enough I think.
|
||||
//
|
||||
// Making-of with math/shader/art explanations (6 hours
|
||||
// long): https://www.youtube.com/watch?v=Cfe5UQ-1L9Q
|
||||
//
|
||||
// Video capture: https://www.youtube.com/watch?v=s_UOFo2IULQ
|
||||
//
|
||||
// Buy a metal print here: https://www.redbubble.com/i/metal-print/Happy-Jumping-by-InigoQuilez/43594745.0JXQP
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
|
||||
// http://iquilezles.org/www/articles/smin/smin.htm
|
||||
float smin( float a, float b, float k )
|
||||
{
|
||||
float h = max(k-abs(a-b),0.0);
|
||||
return min(a, b) - h*h*0.25/k;
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/smin/smin.htm
|
||||
vec2 smin( vec2 a, vec2 b, float k )
|
||||
{
|
||||
float h = clamp( 0.5+0.5*(b.x-a.x)/k, 0.0, 1.0 );
|
||||
return mix( b, a, h ) - k*h*(1.0-h);
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/smin/smin.htm
|
||||
float smax( float a, float b, float k )
|
||||
{
|
||||
float h = max(k-abs(a-b),0.0);
|
||||
return max(a, b) + h*h*0.25/k;
|
||||
}
|
||||
|
||||
// http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
|
||||
float sdSphere( vec3 p, float s )
|
||||
{
|
||||
return length(p)-s;
|
||||
}
|
||||
|
||||
// http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
|
||||
float sdEllipsoid( in vec3 p, in vec3 r ) // approximated
|
||||
{
|
||||
float k0 = length(p/r);
|
||||
float k1 = length(p/(r*r));
|
||||
return k0*(k0-1.0)/k1;
|
||||
}
|
||||
|
||||
vec2 sdStick(vec3 p, vec3 a, vec3 b, float r1, float r2) // approximated
|
||||
{
|
||||
vec3 pa = p-a, ba = b-a;
|
||||
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
|
||||
return vec2( length( pa - ba*h ) - mix(r1,r2,h*h*(3.0-2.0*h)), h );
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/smin/smin.htm
|
||||
vec4 opU( vec4 d1, vec4 d2 )
|
||||
{
|
||||
return (d1.x<d2.x) ? d1 : d2;
|
||||
}
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
#define ZERO (min(int(iFrame),0))
|
||||
|
||||
//------------------------------------------------------------------
|
||||
|
||||
float href;
|
||||
float hsha;
|
||||
|
||||
vec4 map( in vec3 pos, float atime )
|
||||
{
|
||||
hsha = 1.0;
|
||||
|
||||
float t1 = fract(atime);
|
||||
float t4 = abs(fract(atime*0.5)-0.5)/0.5;
|
||||
|
||||
float p = 4.0*t1*(1.0-t1);
|
||||
float pp = 4.0*(1.0-2.0*t1); // derivative of p
|
||||
|
||||
vec3 cen = vec3( 0.5*(-1.0 + 2.0*t4),
|
||||
pow(p,2.0-p) + 0.1,
|
||||
floor(atime) + pow(t1,0.7) -1.0 );
|
||||
|
||||
// body
|
||||
vec2 uu = normalize(vec2( 1.0, -pp ));
|
||||
vec2 vv = vec2(-uu.y, uu.x);
|
||||
|
||||
float sy = 0.5 + 0.5*p;
|
||||
float compress = 1.0-smoothstep(0.0,0.4,p);
|
||||
sy = sy*(1.0-compress) + compress;
|
||||
float sz = 1.0/sy;
|
||||
|
||||
vec3 q = pos - cen;
|
||||
float rot = -0.25*(-1.0 + 2.0*t4);
|
||||
float rc = cos(rot);
|
||||
float rs = sin(rot);
|
||||
q.xy = mat2x2(rc,rs,-rs,rc)*q.xy;
|
||||
vec3 r = q;
|
||||
href = q.y;
|
||||
q.yz = vec2( dot(uu,q.yz), dot(vv,q.yz) );
|
||||
|
||||
vec4 res = vec4( sdEllipsoid( q, vec3(0.25, 0.25*sy, 0.25*sz) ), 2.0, 0.0, 1.0 );
|
||||
|
||||
if( res.x-1.0 < pos.y ) // bounding volume
|
||||
{
|
||||
float t2 = fract(atime+0.8);
|
||||
float p2 = 0.5-0.5*cos(6.2831*t2);
|
||||
r.z += 0.05-0.2*p2;
|
||||
r.y += 0.2*sy-0.2;
|
||||
vec3 sq = vec3( abs(r.x), r.yz );
|
||||
|
||||
// head
|
||||
vec3 h = r;
|
||||
float hr = sin(0.791*atime);
|
||||
hr = 0.7*sign(hr)*smoothstep(0.5,0.7,abs(hr));
|
||||
h.xz = mat2x2(cos(hr),sin(hr),-sin(hr),cos(hr))*h.xz;
|
||||
vec3 hq = vec3( abs(h.x), h.yz );
|
||||
float d = sdEllipsoid( h-vec3(0.0,0.20,0.02), vec3(0.08,0.2,0.15) );
|
||||
float d2 = sdEllipsoid( h-vec3(0.0,0.21,-0.1), vec3(0.20,0.2,0.20) );
|
||||
d = smin( d, d2, 0.1 );
|
||||
res.x = smin( res.x, d, 0.1 );
|
||||
|
||||
// belly wrinkles
|
||||
{
|
||||
float yy = r.y-0.02-2.5*r.x*r.x;
|
||||
res.x += 0.001*sin(yy*120.0)*(1.0-smoothstep(0.0,0.1,abs(yy)));
|
||||
}
|
||||
|
||||
// arms
|
||||
{
|
||||
vec2 arms = sdStick( sq, vec3(0.18-0.06*hr*sign(r.x),0.2,-0.05), vec3(0.3+0.1*p2,-0.2+0.3*p2,-0.15), 0.03, 0.06 );
|
||||
res.xz = smin( res.xz, arms, 0.01+0.04*(1.0-arms.y)*(1.0-arms.y)*(1.0-arms.y) );
|
||||
}
|
||||
|
||||
// ears
|
||||
{
|
||||
float t3 = fract(atime+0.9);
|
||||
float p3 = 4.0*t3*(1.0-t3);
|
||||
vec2 ear = sdStick( hq, vec3(0.15,0.32,-0.05), vec3(0.2+0.05*p3,0.2+0.2*p3,-0.07), 0.01, 0.04 );
|
||||
res.xz = smin( res.xz, ear, 0.01 );
|
||||
}
|
||||
|
||||
// mouth
|
||||
{
|
||||
d = sdEllipsoid( h-vec3(0.0,0.15+4.0*hq.x*hq.x,0.15), vec3(0.1,0.04,0.2) );
|
||||
res.w = 0.3+0.7*clamp( d*150.0,0.0,1.0);
|
||||
res.x = smax( res.x, -d, 0.03 );
|
||||
}
|
||||
|
||||
// legs
|
||||
{
|
||||
float t6 = cos(6.2831*(atime*0.5+0.25));
|
||||
float ccc = cos(1.57*t6*sign(r.x));
|
||||
float sss = sin(1.57*t6*sign(r.x));
|
||||
vec3 base = vec3(0.12,-0.07,-0.1); base.y -= 0.1/sy;
|
||||
vec2 legs = sdStick( sq, base, base + vec3(0.2,-ccc,sss)*0.2, 0.04, 0.07 );
|
||||
res.xz = smin( res.xz, legs, 0.07 );
|
||||
}
|
||||
|
||||
// eye
|
||||
{
|
||||
float blink = pow(0.5+0.5*sin(2.1*iTime),20.0);
|
||||
float eyeball = sdSphere(hq-vec3(0.08,0.27,0.06),0.065+0.02*blink);
|
||||
res.x = smin( res.x, eyeball, 0.03 );
|
||||
|
||||
vec3 cq = hq-vec3(0.1,0.34,0.08);
|
||||
cq.xy = mat2x2(0.8,0.6,-0.6,0.8)*cq.xy;
|
||||
d = sdEllipsoid( cq, vec3(0.06,0.03,0.03) );
|
||||
res.x = smin( res.x, d, 0.03 );
|
||||
|
||||
float eo = 1.0-0.5*smoothstep(0.01,0.04,length((hq.xy-vec2(0.095,0.285))*vec2(1.0,1.1)));
|
||||
res = opU( res, vec4(sdSphere(hq-vec3(0.08,0.28,0.08),0.060),3.0,0.0,eo));
|
||||
res = opU( res, vec4(sdSphere(hq-vec3(0.075,0.28,0.102),0.0395),4.0,0.0,1.0));
|
||||
}
|
||||
}
|
||||
|
||||
// ground
|
||||
float fh = -0.1 - 0.05*(sin(pos.x*2.0)+sin(pos.z*2.0));
|
||||
float t5f = fract(atime+0.05);
|
||||
float t5i = floor(atime+0.05);
|
||||
float bt4 = abs(fract(t5i*0.5)-0.5)/0.5;
|
||||
vec2 bcen = vec2( 0.5*(-1.0+2.0*bt4),t5i+pow(t5f,0.7)-1.0 );
|
||||
|
||||
float k = length(pos.xz-bcen);
|
||||
float tt = t5f*15.0-6.2831 - k*3.0;
|
||||
fh -= 0.1*exp(-k*k)*sin(tt)*exp(-max(tt,0.0)/2.0)*smoothstep(0.0,0.01,t5f);
|
||||
float d = pos.y - fh;
|
||||
|
||||
// bubbles
|
||||
{
|
||||
vec3 vp = vec3( mod(abs(pos.x),3.0)-1.5,pos.y,mod(pos.z+1.5,3.0)-1.5);
|
||||
vec2 id = vec2( floor(pos.x/3.0), floor((pos.z+1.5)/3.0) );
|
||||
float fid = id.x*11.1 + id.y*31.7;
|
||||
float fy = fract(fid*1.312+atime*0.1);
|
||||
float y = -1.0+4.0*fy;
|
||||
vec3 rad = vec3(0.7,1.0+0.5*sin(fid),0.7);
|
||||
rad -= 0.1*(sin(pos.x*3.0)+sin(pos.y*4.0)+sin(pos.z*5.0));
|
||||
float siz = 4.0*fy*(1.0-fy);
|
||||
float d2 = sdEllipsoid( vp-vec3(0.5,y,0.0), siz*rad );
|
||||
|
||||
d2 -= 0.03*smoothstep(-1.0,1.0,sin(18.0*pos.x)+sin(18.0*pos.y)+sin(18.0*pos.z));
|
||||
d2 *= 0.6;
|
||||
d2 = min(d2,2.0);
|
||||
d = smin( d, d2, 0.32 );
|
||||
if( d<res.x ) { res = vec4(d,1.0,0.0,1.0); hsha=sqrt(siz); }
|
||||
}
|
||||
|
||||
// candy
|
||||
{
|
||||
float fs = 5.0;
|
||||
vec3 qos = fs*vec3(pos.x, pos.y-fh, pos.z );
|
||||
vec2 id = vec2( floor(qos.x+0.5), floor(qos.z+0.5) );
|
||||
vec3 vp = vec3( fract(qos.x+0.5)-0.5,qos.y,fract(qos.z+0.5)-0.5);
|
||||
vp.xz += 0.1*cos( id.x*130.143 + id.y*120.372 + vec2(0.0,2.0) );
|
||||
float den = sin(id.x*0.1+sin(id.y*0.091))+sin(id.y*0.1);
|
||||
float fid = id.x*0.143 + id.y*0.372;
|
||||
float ra = smoothstep(0.0,0.1,den*0.1+fract(fid)-0.95);
|
||||
d = sdSphere( vp, 0.35*ra )/fs;
|
||||
if( d<res.x ) res = vec4(d,5.0,qos.y,1.0);
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
vec4 raycast( in vec3 ro, in vec3 rd, float time )
|
||||
{
|
||||
vec4 res = vec4(-1.0,-1.0,0.0,1.0);
|
||||
|
||||
float tmin = 0.5;
|
||||
float tmax = 20.0;
|
||||
|
||||
#if 1
|
||||
// raytrace bounding plane
|
||||
float tp = (3.5-ro.y)/rd.y;
|
||||
if( tp>0.0 ) tmax = min( tmax, tp );
|
||||
#endif
|
||||
|
||||
// raymarch scene
|
||||
float t = tmin;
|
||||
for( int i=0; i<256 && t<tmax; i++ )
|
||||
{
|
||||
vec4 h = map( ro+rd*t, time );
|
||||
if( abs(h.x)<(0.0005*t) )
|
||||
{
|
||||
res = vec4(t,h.yzw);
|
||||
break;
|
||||
}
|
||||
t += h.x;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/rmshadows/rmshadows.htm
|
||||
float calcSoftshadow( in vec3 ro, in vec3 rd, float time )
|
||||
{
|
||||
float res = 1.0;
|
||||
|
||||
float tmax = 12.0;
|
||||
#if 1
|
||||
float tp = (3.5-ro.y)/rd.y; // raytrace bounding plane
|
||||
if( tp>0.0 ) tmax = min( tmax, tp );
|
||||
#endif
|
||||
|
||||
float t = 0.02;
|
||||
for( int i=0; i<50; i++ )
|
||||
{
|
||||
float h = map( ro + rd*t, time ).x;
|
||||
res = min( res, mix(1.0,16.0*h/t, hsha) );
|
||||
t += clamp( h, 0.05, 0.40 );
|
||||
if( res<0.005 || t>tmax ) break;
|
||||
}
|
||||
return clamp( res, 0.0, 1.0 );
|
||||
}
|
||||
|
||||
// http://iquilezles.org/www/articles/normalsSDF/normalsSDF.htm
|
||||
vec3 calcNormal( in vec3 pos, float time )
|
||||
{
|
||||
|
||||
#if 0
|
||||
vec2 e = vec2(1.0,-1.0)*0.5773*0.001;
|
||||
return normalize( e.xyy*map( pos + e.xyy, time ).x +
|
||||
e.yyx*map( pos + e.yyx, time ).x +
|
||||
e.yxy*map( pos + e.yxy, time ).x +
|
||||
e.xxx*map( pos + e.xxx, time ).x );
|
||||
#else
|
||||
// inspired by tdhooper and klems - a way to prevent the compiler from inlining map() 4 times
|
||||
vec3 n = vec3(0.0);
|
||||
for( int i=ZERO; i<4; i++ )
|
||||
{
|
||||
vec3 e = 0.5773*(2.0*vec3((((i+3)>>1)&1),((i>>1)&1),(i&1))-1.0);
|
||||
n += e*map(pos+0.001*e,time).x;
|
||||
}
|
||||
return normalize(n);
|
||||
#endif
|
||||
}
|
||||
|
||||
float calcOcclusion( in vec3 pos, in vec3 nor, float time )
|
||||
{
|
||||
float occ = 0.0;
|
||||
float sca = 1.0;
|
||||
for( int i=ZERO; i<5; i++ )
|
||||
{
|
||||
float h = 0.01 + 0.11*float(i)/4.0;
|
||||
vec3 opos = pos + h*nor;
|
||||
float d = map( opos, time ).x;
|
||||
occ += (h-d)*sca;
|
||||
sca *= 0.95;
|
||||
}
|
||||
return clamp( 1.0 - 2.0*occ, 0.0, 1.0 );
|
||||
}
|
||||
|
||||
vec3 render( in vec3 ro, in vec3 rd, float time )
|
||||
{
|
||||
// sky dome
|
||||
vec3 col = vec3(0.5, 0.8, 0.9) - max(rd.y,0.0)*0.5;
|
||||
// sky clouds
|
||||
vec2 uv = 1.5*rd.xz/rd.y;
|
||||
float cl = 1.0*(sin(uv.x)+sin(uv.y)); uv *= mat2(0.8,0.6,-0.6,0.8)*2.1;
|
||||
cl += 0.5*(sin(uv.x)+sin(uv.y));
|
||||
col += 0.1*(-1.0+2.0*smoothstep(-0.1,0.1,cl-0.4));
|
||||
// sky horizon
|
||||
col = mix( col, vec3(0.5, 0.7, .9), exp(-10.0*max(rd.y,0.0)) );
|
||||
|
||||
|
||||
// scene geometry
|
||||
vec4 res = raycast(ro,rd, time);
|
||||
if( res.y>-0.5 )
|
||||
{
|
||||
float t = res.x;
|
||||
vec3 pos = ro + t*rd;
|
||||
vec3 nor = calcNormal( pos, time );
|
||||
vec3 ref = reflect( rd, nor );
|
||||
float focc = res.w;
|
||||
|
||||
// material
|
||||
col = vec3(0.2);
|
||||
float ks = 1.0;
|
||||
|
||||
if( res.y>4.5 ) // candy
|
||||
{
|
||||
col = vec3(0.14,0.048,0.0);
|
||||
vec2 id = floor(5.0*pos.xz+0.5);
|
||||
col += 0.036*cos((id.x*11.1+id.y*37.341) + vec3(0.0,1.0,2.0) );
|
||||
col = max(col,0.0);
|
||||
focc = clamp(4.0*res.z,0.0,1.0);
|
||||
}
|
||||
else if( res.y>3.5 ) // eyeball
|
||||
{
|
||||
col = vec3(0.0);
|
||||
}
|
||||
else if( res.y>2.5 ) // iris
|
||||
{
|
||||
col = vec3(0.4);
|
||||
}
|
||||
else if( res.y>1.5 ) // body
|
||||
{
|
||||
col = mix(vec3(0.144,0.09,0.0036),vec3(0.36,0.1,0.04),res.z*res.z);
|
||||
col = mix(col,vec3(0.14,0.09,0.06)*2.0, (1.0-res.z)*smoothstep(-0.15, 0.15, -href));
|
||||
}
|
||||
else // terrain
|
||||
{
|
||||
// base green
|
||||
col = vec3(0.05,0.09,0.02);
|
||||
float f = 0.2*(-1.0+2.0*smoothstep(-0.2,0.2,sin(18.0*pos.x)+sin(18.0*pos.y)+sin(18.0*pos.z)));
|
||||
col += f*vec3(0.06,0.06,0.02);
|
||||
ks = 0.5 + pos.y*0.15;
|
||||
|
||||
// footprints
|
||||
vec2 mp = vec2(pos.x-0.5*(mod(floor(pos.z+0.5),2.0)*2.0-1.0), fract(pos.z+0.5)-0.5 );
|
||||
float mark = 1.0-smoothstep(0.1, 0.5, length(mp));
|
||||
mark *= smoothstep(0.0, 0.1, floor(time) - floor(pos.z+0.5) );
|
||||
col *= mix( vec3(1.0), vec3(0.5,0.5,0.4), mark );
|
||||
ks *= 1.0-0.5*mark;
|
||||
}
|
||||
|
||||
// lighting (sun, sky, bounce, back, sss)
|
||||
float occ = calcOcclusion( pos, nor, time )*focc;
|
||||
float fre = clamp(1.0+dot(nor,rd),0.0,1.0);
|
||||
|
||||
vec3 sun_lig = normalize( vec3(0.6, 0.35, 0.5) );
|
||||
float sun_dif = clamp(dot( nor, sun_lig ), 0.0, 1.0 );
|
||||
vec3 sun_hal = normalize( sun_lig-rd );
|
||||
float sun_sha = calcSoftshadow( pos, sun_lig, time );
|
||||
float sun_spe = ks*pow(clamp(dot(nor,sun_hal),0.0,1.0),8.0)*sun_dif*(0.04+0.96*pow(clamp(1.0+dot(sun_hal,rd),0.0,1.0),5.0));
|
||||
float sky_dif = sqrt(clamp( 0.5+0.5*nor.y, 0.0, 1.0 ));
|
||||
float sky_spe = ks*smoothstep( 0.0, 0.5, ref.y )*(0.04+0.96*pow(fre,4.0));
|
||||
float bou_dif = sqrt(clamp( 0.1-0.9*nor.y, 0.0, 1.0 ))*clamp(1.0-0.1*pos.y,0.0,1.0);
|
||||
float bac_dif = clamp(0.1+0.9*dot( nor, normalize(vec3(-sun_lig.x,0.0,-sun_lig.z))), 0.0, 1.0 );
|
||||
float sss_dif = fre*sky_dif*(0.25+0.75*sun_dif*sun_sha);
|
||||
|
||||
vec3 lin = vec3(0.0);
|
||||
lin += sun_dif*vec3(8.10,6.00,4.20)*vec3(sun_sha,sun_sha*sun_sha*0.5+0.5*sun_sha,sun_sha*sun_sha);
|
||||
lin += sky_dif*vec3(0.50,0.70,1.00)*occ;
|
||||
lin += bou_dif*vec3(0.20,0.70,0.10)*occ;
|
||||
lin += bac_dif*vec3(0.45,0.35,0.25)*occ;
|
||||
lin += sss_dif*vec3(3.25,2.75,2.50)*occ;
|
||||
col = col*lin;
|
||||
col += sun_spe*vec3(9.90,8.10,6.30)*sun_sha;
|
||||
col += sky_spe*vec3(0.20,0.30,0.65)*occ*occ;
|
||||
|
||||
col = pow(col,vec3(0.8,0.9,1.0) );
|
||||
|
||||
// fog
|
||||
col = mix( col, vec3(0.5,0.7,0.9), 1.0-exp( -0.0001*t*t*t ) );
|
||||
}
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
mat3 setCamera( in vec3 ro, in vec3 ta, float cr )
|
||||
{
|
||||
vec3 cw = normalize(ta-ro);
|
||||
vec3 cp = vec3(sin(cr), cos(cr),0.0);
|
||||
vec3 cu = normalize( cross(cw,cp) );
|
||||
vec3 cv = ( cross(cu,cw) );
|
||||
return mat3( cu, cv, cw );
|
||||
}
|
||||
|
||||
//void mainImage( out vec4 fragColor, in vec2 fragCoord )
|
||||
vec4 mainImage( vec2 fragCoord )
|
||||
{
|
||||
vec3 tot = vec3(0.0);
|
||||
#if AA>1
|
||||
for( int m=ZERO; m<AA; m++ )
|
||||
for( int n=ZERO; n<AA; n++ )
|
||||
{
|
||||
// pixel coordinates
|
||||
vec2 o = vec2(float(m),float(n)) / float(AA) - 0.5;
|
||||
vec2 p = (-iResolution.xy + 2.0*(fragCoord+o))/iResolution.y;
|
||||
// time coordinate (motion blurred, shutter=0.5)
|
||||
float d = 0.5+0.5*sin(fragCoord.x*147.0)*sin(fragCoord.y*131.0);
|
||||
float time = iTime - 0.5*(1.0/24.0)*(float(m*AA+n)+d)/float(AA*AA);
|
||||
#else
|
||||
vec2 p = (-iResolution.xy + 2.0*fragCoord)/iResolution.y;
|
||||
float time = iTime;
|
||||
#endif
|
||||
time += -2.6;
|
||||
time *= 0.9;
|
||||
|
||||
// camera
|
||||
float cl = sin(0.5*time);
|
||||
float an = 1.57 + 0.7*sin(0.15*time);
|
||||
vec3 ta = vec3( 0.0, 0.65, -0.6+time*1.0 - 0.4*cl);
|
||||
vec3 ro = ta + vec3( 1.3*cos(an), -0.250, 1.3*sin(an) );
|
||||
float ti = fract(time-0.15);
|
||||
ti = 4.0*ti*(1.0-ti);
|
||||
ta.y += 0.15*ti*ti*(3.0-2.0*ti)*smoothstep(0.4,0.9,cl);
|
||||
|
||||
// camera bounce
|
||||
float t4 = abs(fract(time*0.5)-0.5)/0.5;
|
||||
float bou = -1.0 + 2.0*t4;
|
||||
ro += 0.06*sin(time*12.0+vec3(0.0,2.0,4.0))*smoothstep( 0.85, 1.0, abs(bou) );
|
||||
|
||||
// camera-to-world rotation
|
||||
mat3 ca = setCamera( ro, ta, 0.0 );
|
||||
|
||||
// ray direction
|
||||
vec3 rd = ca * normalize( vec3(p,1.8) );
|
||||
|
||||
// render
|
||||
vec3 col = render( ro, rd, time );
|
||||
|
||||
// color grading
|
||||
col = col*vec3(1.11,0.89,0.79);
|
||||
|
||||
// compress
|
||||
col = 1.35*col/(1.0+col);
|
||||
|
||||
// gamma
|
||||
col = pow( col, vec3(0.4545) );
|
||||
|
||||
tot += col;
|
||||
#if AA>1
|
||||
}
|
||||
tot /= float(AA*AA);
|
||||
#endif
|
||||
|
||||
// s-surve
|
||||
tot = clamp(tot,0.0,1.0);
|
||||
tot = tot*tot*(3.0-2.0*tot);
|
||||
|
||||
// vignetting
|
||||
vec2 q = fragCoord/iResolution.xy;
|
||||
tot *= 0.5 + 0.5*pow(16.0*q.x*q.y*(1.0-q.x)*(1.0-q.y),0.25);
|
||||
|
||||
// output
|
||||
//fragColor = vec4( tot, 1.0 );
|
||||
return vec4( tot, 1.0 );
|
||||
}
|
||||
|
||||
//*********************************************************
|
||||
// END Ray Marching
|
||||
//*********************************************************
|
||||
|
||||
void main() {
|
||||
vec4 c = color;
|
||||
vec4 txt = texture(sampler2D(tex, smp), uv);
|
||||
c = txt * c;
|
||||
vec2 uv1 = uv * iResolution;
|
||||
vec4 col_ray = mainImage(uv1);
|
||||
|
||||
// use this to mix the chessboart texture with the ray marching
|
||||
//frag_color = clamp(c*iMouse.y/512.0,0.0,1.0) * col_ray ;
|
||||
|
||||
frag_color = c*0.00001 + col_ray ;
|
||||
}
|
||||
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @program rt_puppy vs_p fs_p
|
||||
Whitespace-only changes.
@@ -0,0 +1,511 @@
|
||||
// vtest build: misc-tooling // needs .h files that are produced by `v shader`
|
||||
/**********************************************************************
|
||||
*
|
||||
* Sokol 3d cube multishader demo
|
||||
*
|
||||
* Copyright (c) 2021 Dario Deledda. All rights reserved.
|
||||
* Use of this source code is governed by an MIT license
|
||||
* that can be found in the LICENSE file.
|
||||
*
|
||||
* HOW TO COMPILE SHADERS:
|
||||
* Run `v shader .` in this directory to compile the shaders.
|
||||
* For more info and help with shader compilation see `docs.md` and `v help shader`.
|
||||
*
|
||||
* TODO:
|
||||
* - frame counter
|
||||
**********************************************************************/
|
||||
import gg
|
||||
import gg.m4
|
||||
import math
|
||||
import sokol.gfx
|
||||
// import sokol.sgl
|
||||
import time
|
||||
|
||||
const win_width = 800
|
||||
const win_height = 800
|
||||
const bg_color = gg.white
|
||||
const num_inst = 16384
|
||||
|
||||
struct App {
|
||||
mut:
|
||||
gg &gg.Context = unsafe { nil }
|
||||
texture gfx.Image
|
||||
sampler gfx.Sampler
|
||||
init_flag bool
|
||||
frame_count int
|
||||
|
||||
mouse_x int = 903
|
||||
mouse_y int = 638
|
||||
mouse_down bool
|
||||
// glsl
|
||||
cube_pip_glsl gfx.Pipeline
|
||||
cube_bind gfx.Bindings
|
||||
|
||||
pipe map[string]gfx.Pipeline
|
||||
bind map[string]gfx.Bindings
|
||||
// time
|
||||
ticks i64
|
||||
// instances
|
||||
inst_pos [num_inst]m4.Vec4
|
||||
// camera
|
||||
camera_x f32 = -8
|
||||
camera_z f32 = 47
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* GLSL Include and functions
|
||||
******************************************************************************/
|
||||
#include "@VMODROOT/rt_glsl_instancing.h" # It should be generated with `v shader .` (see the instructions at the top of this file)
|
||||
|
||||
fn C.instancing_shader_desc(gfx.Backend) &gfx.ShaderDesc
|
||||
|
||||
/******************************************************************************
|
||||
* Texture functions
|
||||
******************************************************************************/
|
||||
fn create_texture(w int, h int, buf byteptr) (gfx.Image, gfx.Sampler) {
|
||||
sz := w * h * 4
|
||||
// vfmt off
|
||||
mut img_desc := gfx.ImageDesc{
|
||||
width: w
|
||||
height: h
|
||||
num_mipmaps: 0
|
||||
// min_filter: .linear
|
||||
// mag_filter: .linear
|
||||
//usage: .dynamic
|
||||
// wrap_u: .clamp_to_edge
|
||||
// wrap_v: .clamp_to_edge
|
||||
label: &char(unsafe { nil })
|
||||
d3d11_texture: 0
|
||||
}
|
||||
// vfmt on
|
||||
// comment if .dynamic is enabled
|
||||
img_desc.data.subimage[0][0] = gfx.Range{
|
||||
ptr: buf
|
||||
size: usize(sz)
|
||||
}
|
||||
|
||||
sg_img := gfx.make_image(&img_desc)
|
||||
|
||||
mut smp_desc := gfx.SamplerDesc{
|
||||
min_filter: .linear
|
||||
mag_filter: .linear
|
||||
wrap_u: .clamp_to_edge
|
||||
wrap_v: .clamp_to_edge
|
||||
}
|
||||
|
||||
sg_smp := gfx.make_sampler(&smp_desc)
|
||||
return sg_img, sg_smp
|
||||
}
|
||||
|
||||
fn destroy_texture(sg_img gfx.Image) {
|
||||
gfx.destroy_image(sg_img)
|
||||
}
|
||||
|
||||
// Use only if usage: .dynamic is enabled
|
||||
fn update_text_texture(sg_img gfx.Image, w int, h int, buf byteptr) {
|
||||
sz := w * h * 4
|
||||
mut tmp_sbc := gfx.ImageData{}
|
||||
tmp_sbc.subimage[0][0] = gfx.Range{
|
||||
ptr: buf
|
||||
size: usize(sz)
|
||||
}
|
||||
gfx.update_image(sg_img, &tmp_sbc)
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Draw functions
|
||||
******************************************************************************
|
||||
Cube vertex buffer with packed vertex formats for color and texture coords.
|
||||
Note that a vertex format which must be portable across all
|
||||
backends must only use the normalized integer formats
|
||||
(BYTE4N, UBYTE4N, SHORT2N, SHORT4N), which can be converted
|
||||
to floating point formats in the vertex shader inputs.
|
||||
The reason is that D3D11 cannot convert from non-normalized
|
||||
formats to floating point inputs (only to integer inputs),
|
||||
and WebGL2 / GLES2 don't support integer vertex shader inputs.
|
||||
*/
|
||||
|
||||
struct Vertex_t {
|
||||
x f32
|
||||
y f32
|
||||
z f32
|
||||
color u32
|
||||
// u u16 // for compatibility with D3D11
|
||||
// v u16 // for compatibility with D3D11
|
||||
u f32
|
||||
v f32
|
||||
}
|
||||
|
||||
// march shader init
|
||||
fn init_cube_glsl_i(mut app App) {
|
||||
// cube vertex buffer
|
||||
// d := u16(32767) // for compatibility with D3D11, 32767 stand for 1
|
||||
d := f32(1.0)
|
||||
c := u32(0xFFFFFF_FF) // color RGBA8
|
||||
// vfmt off
|
||||
vertices := [
|
||||
// Face 0
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{ 1.0, -1.0, -1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, -1.0, c, d, d},
|
||||
Vertex_t{-1.0, 1.0, -1.0, c, 0, d},
|
||||
// Face 1
|
||||
Vertex_t{-1.0, -1.0, 1.0, c, 0, 0},
|
||||
Vertex_t{ 1.0, -1.0, 1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{-1.0, 1.0, 1.0, c, 0, d},
|
||||
// Face 2
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{-1.0, 1.0, -1.0, c, d, 0},
|
||||
Vertex_t{-1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{-1.0, -1.0, 1.0, c, 0, d},
|
||||
// Face 3
|
||||
Vertex_t{ 1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{ 1.0, 1.0, -1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{ 1.0, -1.0, 1.0, c, 0, d},
|
||||
// Face 4
|
||||
Vertex_t{-1.0, -1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{-1.0, -1.0, 1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, -1.0, 1.0, c, d, d},
|
||||
Vertex_t{ 1.0, -1.0, -1.0, c, 0, d},
|
||||
// Face 5
|
||||
Vertex_t{-1.0, 1.0, -1.0, c, 0, 0},
|
||||
Vertex_t{-1.0, 1.0, 1.0, c, d, 0},
|
||||
Vertex_t{ 1.0, 1.0, 1.0, c, d, d},
|
||||
Vertex_t{ 1.0, 1.0, -1.0, c, 0, d},
|
||||
]
|
||||
// vfmt on
|
||||
|
||||
mut vert_buffer_desc := gfx.BufferDesc{
|
||||
label: c'cube-vertices'
|
||||
}
|
||||
unsafe { vmemset(&vert_buffer_desc, 0, int(sizeof(vert_buffer_desc))) }
|
||||
vert_buffer_desc.size = usize(vertices.len * int(sizeof(Vertex_t)))
|
||||
vert_buffer_desc.data = gfx.Range{
|
||||
ptr: vertices.data
|
||||
size: usize(vertices.len * int(sizeof(Vertex_t)))
|
||||
}
|
||||
vert_buffer_desc.type = .vertexbuffer
|
||||
vbuf := gfx.make_buffer(&vert_buffer_desc)
|
||||
|
||||
// create an instance buffer for the cube
|
||||
mut inst_buffer_desc := gfx.BufferDesc{
|
||||
label: c'instance-data'
|
||||
}
|
||||
unsafe { vmemset(&inst_buffer_desc, 0, int(sizeof(inst_buffer_desc))) }
|
||||
|
||||
inst_buffer_desc.size = usize(num_inst * int(sizeof(m4.Vec4)))
|
||||
inst_buffer_desc.type = .vertexbuffer
|
||||
inst_buffer_desc.usage = .stream
|
||||
inst_buf := gfx.make_buffer(&inst_buffer_desc)
|
||||
|
||||
// create an index buffer for the cube
|
||||
// vfmt off
|
||||
indices := [
|
||||
u16(0), 1, 2, 0, 2, 3,
|
||||
6, 5, 4, 7, 6, 4,
|
||||
8, 9, 10, 8, 10, 11,
|
||||
14, 13, 12, 15, 14, 12,
|
||||
16, 17, 18, 16, 18, 19,
|
||||
22, 21, 20, 23, 22, 20,
|
||||
]
|
||||
// vfmt on
|
||||
|
||||
mut index_buffer_desc := gfx.BufferDesc{
|
||||
label: c'cube-indices'
|
||||
}
|
||||
unsafe { vmemset(&index_buffer_desc, 0, int(sizeof(index_buffer_desc))) }
|
||||
index_buffer_desc.size = usize(indices.len * int(sizeof(u16)))
|
||||
index_buffer_desc.data = gfx.Range{
|
||||
ptr: indices.data
|
||||
size: usize(indices.len * int(sizeof(u16)))
|
||||
}
|
||||
index_buffer_desc.type = .indexbuffer
|
||||
ibuf := gfx.make_buffer(&index_buffer_desc)
|
||||
|
||||
// create shader
|
||||
shader := gfx.make_shader(voidptr(C.instancing_shader_desc(C.sg_query_backend())))
|
||||
|
||||
mut pipdesc := gfx.PipelineDesc{}
|
||||
unsafe { vmemset(&pipdesc, 0, int(sizeof(pipdesc))) }
|
||||
pipdesc.layout.buffers[0].stride = int(sizeof(Vertex_t))
|
||||
|
||||
// vfmt off
|
||||
// the constants [C.ATTR_vs_m_pos, C.ATTR_vs_m_color0, C.ATTR_vs_m_texcoord0] are generated by sokol-shdc
|
||||
pipdesc.layout.attrs[C.ATTR_vs_i_pos ].format = .float3 // x,y,z as f32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_i_pos ].buffer_index = 0
|
||||
pipdesc.layout.attrs[C.ATTR_vs_i_color0 ].format = .ubyte4n // color as u32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_i_pos ].buffer_index = 0
|
||||
pipdesc.layout.attrs[C.ATTR_vs_i_texcoord0].format = .float2 // u,v as f32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_i_pos ].buffer_index = 0
|
||||
|
||||
// instancing
|
||||
// the constant ATTR_vs_i_inst_pos is generated by sokol-shdc
|
||||
pipdesc.layout.buffers[1].stride = int(sizeof(m4.Vec4))
|
||||
pipdesc.layout.buffers[1].step_func = .per_instance // we will pass a single parameter for each instance!!
|
||||
pipdesc.layout.attrs[C.ATTR_vs_i_inst_pos ].format = .float4
|
||||
pipdesc.layout.attrs[C.ATTR_vs_i_inst_pos ].buffer_index = 1
|
||||
// vfmt on
|
||||
|
||||
pipdesc.shader = shader
|
||||
pipdesc.index_type = .uint16
|
||||
|
||||
pipdesc.depth = gfx.DepthState{
|
||||
write_enabled: true
|
||||
compare: .less_equal
|
||||
}
|
||||
pipdesc.cull_mode = .back
|
||||
|
||||
pipdesc.label = c'glsl_shader pipeline'
|
||||
|
||||
mut bind := gfx.Bindings{}
|
||||
unsafe { vmemset(&bind, 0, int(sizeof(bind))) }
|
||||
bind.vertex_buffers[0] = vbuf // vertex buffer
|
||||
bind.vertex_buffers[1] = inst_buf // instance buffer
|
||||
bind.index_buffer = ibuf
|
||||
bind.fs.images[C.SLOT_tex] = app.texture
|
||||
bind.fs.samplers[C.SLOT_smp] = app.sampler
|
||||
app.bind['inst'] = bind
|
||||
app.pipe['inst'] = gfx.make_pipeline(&pipdesc)
|
||||
|
||||
println('GLSL March init DONE!')
|
||||
}
|
||||
|
||||
fn calc_tr_matrices(w f32, h f32, rx f32, ry f32, in_scale f32) m4.Mat4 {
|
||||
// vfmt off
|
||||
proj := m4.perspective(60, w/h, 0.01, 4000.0)
|
||||
view := m4.look_at(m4.Vec4{e:[f32(0.0),100,6,0]!}, m4.Vec4{e:[f32(0),0,0,0]!}, m4.Vec4{e:[f32(0),1.0,0,0]!})
|
||||
view_proj := view * proj
|
||||
|
||||
rxm := m4.rotate(m4.rad(rx), m4.Vec4{e:[f32(1),0,0,0]!})
|
||||
rym := m4.rotate(m4.rad(ry), m4.Vec4{e:[f32(0),1,0,0]!})
|
||||
// vfmt on
|
||||
|
||||
model := rym * rxm
|
||||
scale_m := m4.scale(m4.Vec4{ e: [in_scale, in_scale, in_scale, 1]! })
|
||||
|
||||
res := (scale_m * model) * view_proj
|
||||
return res
|
||||
}
|
||||
|
||||
// triangles draw
|
||||
fn draw_cube_glsl_i(mut app App) {
|
||||
if app.init_flag == false {
|
||||
return
|
||||
}
|
||||
|
||||
ws := gg.window_size_real_pixels()
|
||||
// ratio := f32(ws.width) / ws.height
|
||||
dw := f32(ws.width / 2)
|
||||
dh := f32(ws.height / 2)
|
||||
|
||||
rot := [f32(app.mouse_y), f32(app.mouse_x)]
|
||||
tr_matrix := calc_tr_matrices(dw, dh, rot[0], rot[1], 2.3)
|
||||
|
||||
gfx.apply_pipeline(app.pipe['inst'])
|
||||
gfx.apply_bindings(app.bind['inst'])
|
||||
|
||||
//***************
|
||||
// Instancing
|
||||
//***************
|
||||
// passing the instancing to the vs
|
||||
time_ticks := f32(time.ticks() - app.ticks) / 1000
|
||||
cube_size := 2
|
||||
sz := 128 // field size dimension
|
||||
cx := 64 // x center for the cubes
|
||||
cz := 64 // z center for the cubes
|
||||
// frame := (app.frame_count/4) % 100
|
||||
for index in 0 .. num_inst {
|
||||
x := f32(index % sz)
|
||||
z := f32(index / sz)
|
||||
// simply waves
|
||||
y := f32(math.cos((x + time_ticks) / 2.0) * math.sin(z / 2.0)) * 2
|
||||
// sombrero function
|
||||
// r := ((x-cx)*(x-cx)+(z-cz)*(z-cz))/(sz/2)
|
||||
// y := f32(math.sin(r+time_ticks)*4.0)
|
||||
spare_param := f32(index % 10)
|
||||
// vfmt off
|
||||
app.inst_pos[index] = m4.Vec4{e:[f32((x - cx - app.camera_x) * cube_size),y ,f32( (z - cz - app.camera_z) * cube_size),spare_param]!}
|
||||
// vfmt on
|
||||
}
|
||||
range := gfx.Range{
|
||||
ptr: unsafe { &app.inst_pos }
|
||||
size: usize(num_inst * int(sizeof(m4.Vec4)))
|
||||
}
|
||||
gfx.update_buffer(app.bind['inst'].vertex_buffers[1], &range)
|
||||
|
||||
// Uniforms
|
||||
// *** vertex shadeer uniforms ***
|
||||
// passing the view matrix as uniform
|
||||
// res is a 4x4 matrix of f32 thus: 4*16 byte of size
|
||||
vs_uniforms_range := gfx.Range{
|
||||
ptr: unsafe { &tr_matrix }
|
||||
size: usize(4 * 16)
|
||||
}
|
||||
gfx.apply_uniforms(.vs, C.SLOT_vs_params_i, &vs_uniforms_range)
|
||||
|
||||
/*
|
||||
// *** fragment shader uniforms ***
|
||||
time_ticks := f32(time.ticks() - app.ticks) / 1000
|
||||
// vfmt off
|
||||
mut tmp_fs_params := [
|
||||
f32(ws.width), ws.height * ratio, // x,y resolution to pass to FS
|
||||
0,0, // dont send mouse position
|
||||
//app.mouse_x, // mouse x
|
||||
//ws.height - app.mouse_y*2, // mouse y scaled
|
||||
time_ticks, // time as f32
|
||||
app.frame_count, // frame count
|
||||
0,0 // padding bytes , see "fs_params" struct paddings in rt_glsl.h
|
||||
]!
|
||||
// vfmt on
|
||||
fs_uniforms_range := gfx.Range{
|
||||
ptr: unsafe { &tmp_fs_params }
|
||||
size: usize(sizeof(tmp_fs_params))
|
||||
}
|
||||
gfx.apply_uniforms(.fs, C.SLOT_fs_params, &fs_uniforms_range)
|
||||
*/
|
||||
// 3 vertices for triangle * 2 triangles per face * 6 faces = 36 vertices to draw for num_inst times
|
||||
gfx.draw(0, (3 * 2) * 6, num_inst)
|
||||
}
|
||||
|
||||
fn draw_start_glsl(app App) {
|
||||
if app.init_flag == false {
|
||||
return
|
||||
}
|
||||
|
||||
ws := gg.window_size_real_pixels()
|
||||
// ratio := f32(ws.width) / ws.height
|
||||
// dw := f32(ws.width / 2)
|
||||
// dh := f32(ws.height / 2)
|
||||
|
||||
gfx.apply_viewport(0, 0, ws.width, ws.height, true)
|
||||
}
|
||||
|
||||
fn draw_end_glsl(app App) {
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
|
||||
fn frame(mut app App) {
|
||||
// clear
|
||||
mut color_action := gfx.ColorAttachmentAction{
|
||||
load_action: .clear
|
||||
clear_value: gfx.Color{
|
||||
r: 0.0
|
||||
g: 0.0
|
||||
b: 0.0
|
||||
a: 1.0
|
||||
}
|
||||
}
|
||||
mut pass_action := gfx.PassAction{}
|
||||
pass_action.colors[0] = color_action
|
||||
pass := gg.create_default_pass(pass_action)
|
||||
gfx.begin_pass(&pass)
|
||||
|
||||
draw_start_glsl(app)
|
||||
draw_cube_glsl_i(mut app)
|
||||
draw_end_glsl(app)
|
||||
app.frame_count++
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Init / Cleanup
|
||||
******************************************************************************/
|
||||
fn my_init(mut app App) {
|
||||
// create chessboard texture 256*256 RGBA
|
||||
w := 256
|
||||
h := 256
|
||||
sz := w * h * 4
|
||||
tmp_txt := unsafe { malloc(sz) }
|
||||
mut i := 0
|
||||
for i < sz {
|
||||
unsafe {
|
||||
y := (i >> 0x8) >> 5 // 8 cell
|
||||
x := (i & 0xFF) >> 5 // 8 cell
|
||||
// upper left corner
|
||||
if x == 0 && y == 0 {
|
||||
tmp_txt[i + 0] = u8(0xFF)
|
||||
tmp_txt[i + 1] = u8(0)
|
||||
tmp_txt[i + 2] = u8(0)
|
||||
tmp_txt[i + 3] = u8(0xFF)
|
||||
}
|
||||
// low right corner
|
||||
else if x == 7 && y == 7 {
|
||||
tmp_txt[i + 0] = u8(0)
|
||||
tmp_txt[i + 1] = u8(0xFF)
|
||||
tmp_txt[i + 2] = u8(0)
|
||||
tmp_txt[i + 3] = u8(0xFF)
|
||||
} else {
|
||||
col := if ((x + y) & 1) == 1 { 0xFF } else { 128 }
|
||||
tmp_txt[i + 0] = u8(col) // red
|
||||
tmp_txt[i + 1] = u8(col) // green
|
||||
tmp_txt[i + 2] = u8(col) // blue
|
||||
tmp_txt[i + 3] = u8(0xFF) // alpha
|
||||
}
|
||||
i += 4
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
app.texture, app.sampler = create_texture(w, h, tmp_txt)
|
||||
free(tmp_txt)
|
||||
}
|
||||
// glsl
|
||||
init_cube_glsl_i(mut app)
|
||||
app.init_flag = true
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* events handling
|
||||
******************************************************************************/
|
||||
fn my_event_manager(mut ev gg.Event, mut app App) {
|
||||
if ev.typ == .mouse_down {
|
||||
app.mouse_down = true
|
||||
}
|
||||
if ev.typ == .mouse_up {
|
||||
app.mouse_down = false
|
||||
}
|
||||
if app.mouse_down == true && ev.typ == .mouse_move {
|
||||
app.mouse_x = int(ev.mouse_x)
|
||||
app.mouse_y = int(ev.mouse_y)
|
||||
}
|
||||
if ev.typ == .touches_began || ev.typ == .touches_moved {
|
||||
if ev.num_touches > 0 {
|
||||
touch_point := ev.touches[0]
|
||||
app.mouse_x = int(touch_point.pos_x)
|
||||
app.mouse_y = int(touch_point.pos_y)
|
||||
}
|
||||
}
|
||||
|
||||
// keyboard
|
||||
if ev.typ == .key_down {
|
||||
step := f32(1.0)
|
||||
match ev.key_code {
|
||||
.w { app.camera_z += step }
|
||||
.s { app.camera_z -= step }
|
||||
.a { app.camera_x -= step }
|
||||
.d { app.camera_x += step }
|
||||
else {}
|
||||
}
|
||||
}
|
||||
eprintln('>> app.camera_x: ${app.camera_x} , app.camera_z: ${app.camera_z}, app.mouse_x: ${app.mouse_x}, app.mouse_y: ${app.mouse_y}')
|
||||
}
|
||||
|
||||
fn main() {
|
||||
mut app := &App{}
|
||||
// vfmt off
|
||||
app.gg = gg.new_context(
|
||||
width: win_width
|
||||
height: win_height
|
||||
create_window: true
|
||||
window_title: 'Instancing Cube'
|
||||
user_data: app
|
||||
bg_color: bg_color
|
||||
frame_fn: frame
|
||||
init_fn: my_init
|
||||
event_fn: my_event_manager
|
||||
)
|
||||
// vfmt on
|
||||
app.ticks = time.ticks()
|
||||
app.gg.run()
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// Shader code for texcube-sapp sample.
|
||||
//
|
||||
// NOTE: This source file also uses the '#pragma sokol' form of the
|
||||
// custom tags.
|
||||
//------------------------------------------------------------------------------
|
||||
//#pragma sokol @ctype mat4 hmm_mat4
|
||||
|
||||
#pragma sokol @vs vs_i
|
||||
uniform vs_params_i {
|
||||
mat4 mvp;
|
||||
};
|
||||
|
||||
in vec4 pos;
|
||||
in vec4 color0;
|
||||
in vec2 texcoord0;
|
||||
|
||||
in vec4 inst_pos;
|
||||
|
||||
out vec4 color;
|
||||
out vec4 color_inst;
|
||||
out vec2 uv;
|
||||
|
||||
const vec4 palette[10] = vec4[10](
|
||||
vec4(1,0,0,1),
|
||||
vec4(0,1,0,1),
|
||||
vec4(0,0,1,1),
|
||||
vec4(1,1,0,1),
|
||||
vec4(0,1,1,1),
|
||||
vec4(1,1,1,1),
|
||||
vec4(0,0,0,1),
|
||||
vec4(0.2,0.2,0.2,1),
|
||||
vec4(0.3,0.3,0.3,1),
|
||||
vec4(0.9,0.9,0.9,1)
|
||||
);
|
||||
|
||||
void main() {
|
||||
vec4 delta_pos = vec4(inst_pos.xyz,0);
|
||||
float w = inst_pos.w;
|
||||
color_inst = palette[int(w)];
|
||||
gl_Position = mvp * (pos + delta_pos);
|
||||
color = color0;
|
||||
uv = texcoord0/4;
|
||||
}
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @fs fs_i
|
||||
uniform texture2D tex;
|
||||
uniform sampler smp;
|
||||
|
||||
in vec4 color;
|
||||
in vec4 color_inst;
|
||||
in vec2 uv;
|
||||
out vec4 frag_color;
|
||||
|
||||
void main() {
|
||||
vec4 c = color;
|
||||
vec4 txt = texture(sampler2D(tex, smp), uv);
|
||||
c = txt * c * color_inst;
|
||||
frag_color = c ;
|
||||
}
|
||||
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @program instancing vs_i fs_i
|
||||
Whitespace-only changes.
@@ -0,0 +1,26 @@
|
||||
# Blender MTL File: 'None'
|
||||
# Material Count: 2
|
||||
|
||||
newmtl Material.001
|
||||
Ns 96.078443
|
||||
Ka 1.000000 1.000000 1.000000
|
||||
Kd 0.640000 0.640000 0.640000
|
||||
Ks 0.500000 0.500000 0.500000
|
||||
Ke 0.000000 0.000000 0.000000
|
||||
Ni 1.000000
|
||||
d 1.000000
|
||||
illum 2
|
||||
|
||||
map_Kd apple.png
|
||||
|
||||
newmtl Material.002
|
||||
Ns 96.078443
|
||||
Ka 1.000000 1.000000 1.000000
|
||||
Kd 0.640000 0.640000 0.640000
|
||||
Ks 0.500000 0.500000 0.500000
|
||||
Ke 0.000000 0.000000 0.000000
|
||||
Ni 1.000000
|
||||
d 1.000000
|
||||
illum 2
|
||||
|
||||
map_Kd apple.png
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
@@ -0,0 +1,12 @@
|
||||
# Blender MTL File: 'donut.blend'
|
||||
# Material Count: 1
|
||||
|
||||
newmtl Material.001
|
||||
Ns 225.000000
|
||||
Ka 1.000000 1.000000 1.000000
|
||||
Kd 0.800000 0.800000 0.800000
|
||||
Ks 0.500000 0.500000 0.500000
|
||||
Ke 0.259059 0.005681 0.342383
|
||||
Ni 1.450000
|
||||
d 0.800000
|
||||
illum 9
|
||||
@@ -0,0 +1,20 @@
|
||||
# Blender MTL File: 'v-logo.blend'
|
||||
# Material Count: 2
|
||||
newmtl Material.001
|
||||
Ns 96.078431
|
||||
Ka 0.2 0.2 0.2
|
||||
Kd 0.365 0.529 0.749
|
||||
Ks 0.85 0.85 0.85
|
||||
Ke 0 0 0
|
||||
Ni 1
|
||||
d 1
|
||||
illum 1
|
||||
newmtl Material.002
|
||||
Ns 96.078431
|
||||
Ka 0.1 0.1 0.1
|
||||
Kd 0.325 0.42 0.541
|
||||
Ks 0.85 0.85 0.85
|
||||
Ke 0 0 0
|
||||
Ni 1
|
||||
d 1
|
||||
illum 1
|
||||
@@ -0,0 +1,109 @@
|
||||
//#pragma sokol @ctype mat4 hmm_mat4
|
||||
|
||||
#pragma sokol @vs vs
|
||||
|
||||
uniform vs_params {
|
||||
mat4 u_MVMatrix; // A constant representing the combined model/view matrix.
|
||||
mat4 u_MVPMatrix; // A constant representing the combined model/view/projection matrix.
|
||||
mat4 u_NMatrix; // A constant representing the Normal Matrix
|
||||
};
|
||||
|
||||
in vec4 a_Position; // Per-vertex position information we will pass in.
|
||||
in vec3 a_Normal; // Per-vertex normal information we will pass in.
|
||||
//in vec4 a_Color; // Per-vertex color information we will pass in.
|
||||
in vec2 a_Texcoord0;
|
||||
|
||||
out vec3 v_Position; // This will be passed into the fragment shader.
|
||||
//out vec4 v_Color; // This will be passed into the fragment shader.
|
||||
out vec3 v_Normal; // This will be passed into the fragment shader.
|
||||
out vec3 v_Normal1;
|
||||
out vec2 uv; // This will be passed into the fragment shader.
|
||||
|
||||
// The entry point for our vertex shader.
|
||||
void main()
|
||||
{
|
||||
// Transform the vertex into eye space.
|
||||
v_Position = vec3(u_MVMatrix * a_Position);
|
||||
// Pass through the color.
|
||||
//v_Color = a_Color;
|
||||
// calc eye space normal
|
||||
v_Normal = vec3(u_NMatrix * vec4(a_Normal, 1.0));
|
||||
// texture coord
|
||||
uv = a_Texcoord0;
|
||||
|
||||
v_Normal1 = normalize(vec3(u_MVMatrix * vec4(a_Normal, 1.0)));
|
||||
|
||||
// gl_Position is a special variable used to store the final position.
|
||||
// Multiply the vertex by the matrix to get the final point in normalized screen coordinates.
|
||||
gl_Position = u_MVPMatrix * a_Position;
|
||||
}
|
||||
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @fs fs
|
||||
//precision mediump float; // Set the default precision to medium. We don't need as high of a precision in the fragment shader
|
||||
uniform texture2D tex;
|
||||
uniform sampler smp;
|
||||
uniform fs_params {
|
||||
vec4 u_LightPos; // The position of the light in eye space.
|
||||
vec4 ambientColor;
|
||||
vec4 diffuseColor;
|
||||
vec4 specularColor;
|
||||
|
||||
};
|
||||
in vec3 v_Position; // Interpolated position for this fragment.
|
||||
//in vec4 v_Color; // This is the color from the vertex shader interpolated across the triangle per fragment.
|
||||
in vec3 v_Normal; // Interpolated normal for this fragment.
|
||||
in vec3 v_Normal1;
|
||||
in vec2 uv;
|
||||
out vec4 frag_color;
|
||||
|
||||
vec3 lightDirection = -u_LightPos.xyz;// vec3(0.0, -0.5, 0.5);
|
||||
//const vec4 ambientColor = vec4(0.094, 0.0, 0.0, 1.0);
|
||||
//const vec4 diffuseColor = vec4(0.5, 0.0, 0.0, 1.0);
|
||||
//const vec4 specularColor = vec4(1.0, 1.0, 1.0, 1.0);
|
||||
//const float shininess = 10.0;
|
||||
const vec4 lightColor = vec4(1.0, 1.0, 1.0, 1.0);
|
||||
|
||||
vec3 phongBRDF(vec3 lightDir, vec3 viewDir, vec3 normal, vec3 phongDiffuseCol, vec3 phongSpecularCol, float phongShininess) {
|
||||
vec3 color = phongDiffuseCol;
|
||||
vec3 reflectDir = reflect(-lightDir, normal);
|
||||
float specDot = max(dot(reflectDir, viewDir), 0.0);
|
||||
color += pow(specDot, phongShininess) * phongSpecularCol;
|
||||
return color;
|
||||
}
|
||||
|
||||
vec4 getPhong(in vec4 diffuseColor) {
|
||||
vec3 lightDir = normalize(-lightDirection);
|
||||
vec3 viewDir = normalize(-v_Position);
|
||||
vec3 n = normalize(v_Normal);
|
||||
|
||||
vec3 luminance = ambientColor.rgb * 0.5;
|
||||
|
||||
float illuminance = dot(lightDir, n);
|
||||
if(illuminance > 0.0) {
|
||||
// we save specular shiness in specularColor.a
|
||||
vec3 brdf = phongBRDF(lightDir, viewDir, n, diffuseColor.rgb, specularColor.rgb, specularColor.a * 1000);
|
||||
luminance += brdf * illuminance * lightColor.rgb;
|
||||
}
|
||||
|
||||
vec4 outColor = vec4(luminance,1.0);
|
||||
return outColor;
|
||||
}
|
||||
|
||||
// The entry point for our fragment shader.
|
||||
void main()
|
||||
{
|
||||
vec4 txt = texture(sampler2D(tex, smp), uv);
|
||||
|
||||
// Directional light
|
||||
float directional = dot(normalize(v_Normal1), normalize(vec3(0,0.5,1))) ;
|
||||
directional = directional * 0.15;
|
||||
|
||||
// Multiply the color by the diffuse illumination level to get final output color.
|
||||
frag_color = vec4(clamp(directional + txt.rgb * getPhong(diffuseColor).rgb,0,1), txt.a * diffuseColor.a);
|
||||
|
||||
}
|
||||
#pragma sokol @end
|
||||
|
||||
#pragma sokol @program gouraud vs fs
|
||||
@@ -0,0 +1,597 @@
|
||||
module obj
|
||||
|
||||
/**********************************************************************
|
||||
*
|
||||
* .obj loader
|
||||
*
|
||||
* Copyright (c) 2021 Dario Deledda. All rights reserved.
|
||||
* Use of this source code is governed by an MIT license
|
||||
* that can be found in the LICENSE file.
|
||||
*
|
||||
* TODO:
|
||||
**********************************************************************/
|
||||
import gg.m4
|
||||
import strconv
|
||||
|
||||
enum F_state {
|
||||
start
|
||||
first
|
||||
ints
|
||||
decimals
|
||||
exp_start
|
||||
exp_sign
|
||||
exp_int
|
||||
}
|
||||
|
||||
// read a int from a string
|
||||
fn get_int(s string, start_index int) (int, int) {
|
||||
mut i := start_index
|
||||
mut res := 0
|
||||
mut sgn := 1
|
||||
|
||||
mut state := F_state.start
|
||||
for true {
|
||||
if i >= s.len {
|
||||
break
|
||||
}
|
||||
c := s[i]
|
||||
if state == .start {
|
||||
match c {
|
||||
`+` {
|
||||
i++
|
||||
state = .ints
|
||||
continue
|
||||
}
|
||||
`-` {
|
||||
sgn = -1
|
||||
i++
|
||||
state = .ints
|
||||
continue
|
||||
}
|
||||
`0`...`9` {
|
||||
state = .ints
|
||||
}
|
||||
` `, `\t` {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
else { // no number found
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if state == .ints {
|
||||
match c {
|
||||
`0`...`9` {
|
||||
// println("${res} => ${(int(c) - 48)}")
|
||||
res = res * 10 + (int(c) - 48)
|
||||
i++
|
||||
continue
|
||||
}
|
||||
else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// println("---")
|
||||
return res * sgn, i
|
||||
}
|
||||
|
||||
// reas a float number from a string
|
||||
fn get_float(s string, start_index int) (f64, int) {
|
||||
mut i1 := start_index //+ 1
|
||||
for i1 < s.len && s[i1] in [` `, `\t`] {
|
||||
i1++
|
||||
}
|
||||
mut i := i1
|
||||
for i < s.len {
|
||||
if s[i] in [` `, `\t`] {
|
||||
break
|
||||
}
|
||||
i++
|
||||
}
|
||||
// println(" get_float: (${start_index},${i}) [${s[start_index..i]}]")
|
||||
// f_res := strconv.atof_quick(s[start_index..i])
|
||||
f_res := strconv.atof_quick(s[i1..i])
|
||||
return f_res, i
|
||||
}
|
||||
|
||||
// read 3 f32 in sequence from a string
|
||||
fn parse_3f(row string, start_index int) m4.Vec4 {
|
||||
// println(row)
|
||||
mut i := start_index //+ 1
|
||||
mut f1 := f64(0)
|
||||
mut f2 := f64(0)
|
||||
f0, mut p := get_float(row, i)
|
||||
// print("Here f0: ${f0} ${p} ")
|
||||
f1, p = get_float(row, p + 1)
|
||||
// print("Here f1: ${f1} ${p} ")
|
||||
f2, p = get_float(row, p + 1)
|
||||
// print("Here f2: ${f2} ${p} ")
|
||||
return m4.Vec4{
|
||||
e: [f32(f0), f32(f1), f32(f2), 1]!
|
||||
}
|
||||
}
|
||||
|
||||
// reas a sequence of f32 from a string
|
||||
fn (mut m ObjPart) parse_floats(row string, start_index int) m4.Vec4 {
|
||||
mut i := start_index //+ 1
|
||||
mut res_f := f64(0)
|
||||
mut res := m4.Vec4{
|
||||
e: [f32(0), 0, 0, 1]!
|
||||
}
|
||||
mut c := 0
|
||||
for true {
|
||||
res_f, i = get_float(row, i)
|
||||
unsafe {
|
||||
res.e[c] = f32(res_f)
|
||||
}
|
||||
c++
|
||||
i++
|
||||
if i >= row.len {
|
||||
break
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// read and manage all the faes from an .obj file data
|
||||
fn (mut p Part) parse_faces(row string, start_index int, obj_part ObjPart) {
|
||||
mut i := start_index + 1
|
||||
mut res := [][3]int{}
|
||||
mut v := 0
|
||||
mut t := 0
|
||||
mut n := 0
|
||||
// println("row: ${row[i..]}")
|
||||
for true {
|
||||
t = 0
|
||||
n = 0
|
||||
if i >= row.len {
|
||||
break
|
||||
}
|
||||
mut c := row[i]
|
||||
if (c > `9` || c < `0`) && c != `-` {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
v, i = get_int(row, i)
|
||||
if i < row.len && row[i] == `/` {
|
||||
if row[i + 1] != `/` {
|
||||
t, i = get_int(row, i + 1)
|
||||
if i < row.len && row[i] == `/` {
|
||||
n, i = get_int(row, i + 1)
|
||||
}
|
||||
} else {
|
||||
i++
|
||||
n, i = get_int(row, i + 1)
|
||||
}
|
||||
}
|
||||
// manage negative indexes
|
||||
// NOTE: not well suporeted now
|
||||
if v < 0 {
|
||||
// println("${obj_part.v.len} ${obj_part.v.len-c}")
|
||||
v = obj_part.v.len - v + 1
|
||||
// exit(0)
|
||||
}
|
||||
if n < 0 {
|
||||
n = obj_part.vn.len - n + 1
|
||||
}
|
||||
if t < 0 {
|
||||
t = obj_part.vt.len - t + 1
|
||||
}
|
||||
res << [v - 1, n - 1, t - 1]!
|
||||
}
|
||||
// println("ok res: ${res}")
|
||||
// println(p.faces.len)
|
||||
p.faces << res
|
||||
}
|
||||
|
||||
// parse the obj file, if single_material is true it use only one default material
|
||||
pub fn (mut obj_part ObjPart) parse_obj_buffer(rows []string, single_material bool) {
|
||||
mut mat_count := 0
|
||||
mut row_count := 0
|
||||
default_part := Part{
|
||||
name: 'default part'
|
||||
}
|
||||
obj_part.part << default_part
|
||||
// println("OBJ file has ${rows.len} rows")
|
||||
for c, row in rows {
|
||||
// println("${c} ${row}")
|
||||
mut i := 0
|
||||
row_count++
|
||||
for true {
|
||||
if i >= row.len {
|
||||
break
|
||||
}
|
||||
match row[i] {
|
||||
`s` {
|
||||
break
|
||||
}
|
||||
`m` {
|
||||
if row[i..i + 6] == 'mtllib' {
|
||||
obj_part.material_file = row[i + 7..].trim_space()
|
||||
obj_part.load_materials()
|
||||
}
|
||||
break
|
||||
}
|
||||
`o`, `g` {
|
||||
mut part := Part{}
|
||||
part.name = row[i + 1..].trim_space()
|
||||
obj_part.part << part
|
||||
mat_count = 0
|
||||
break
|
||||
}
|
||||
`u` {
|
||||
if single_material == false && row[i..i + 6] == 'usemtl' {
|
||||
material := row[i + 7..].trim_space()
|
||||
// println("material: ${material}")
|
||||
// manage multiple materials in an part
|
||||
if obj_part.part[obj_part.part.len - 1].material.len > 0 {
|
||||
mat_count++
|
||||
mut part := Part{}
|
||||
if mat_count > 1 {
|
||||
li := obj_part.part[obj_part.part.len - 1].name.last_index('_m') or {
|
||||
obj_part.part[obj_part.part.len - 1].name.len - 1
|
||||
}
|
||||
part.name = obj_part.part[obj_part.part.len - 1].name[..li] +
|
||||
'_m${mat_count:02}'
|
||||
} else {
|
||||
part.name = obj_part.part[obj_part.part.len - 1].name + '_m01'
|
||||
}
|
||||
obj_part.part << part
|
||||
}
|
||||
obj_part.part[obj_part.part.len - 1].material = material
|
||||
}
|
||||
break
|
||||
}
|
||||
`v` {
|
||||
i++
|
||||
match row[i] {
|
||||
// normals
|
||||
`n` {
|
||||
obj_part.vn << parse_3f(row, i + 2)
|
||||
// println("Vertex line: ${c}")
|
||||
break
|
||||
}
|
||||
// parameters uvw
|
||||
`p` {
|
||||
obj_part.vp << parse_3f(row, i + 2)
|
||||
// println("Vertex line: ${obj_part.vp.len}")
|
||||
break
|
||||
}
|
||||
// texture uvw
|
||||
`t` {
|
||||
obj_part.vt << obj_part.parse_floats(row, i + 2)
|
||||
// println("Vertex line: ${c}")
|
||||
break
|
||||
}
|
||||
else {
|
||||
obj_part.v << parse_3f(row, i + 1)
|
||||
// println("${row} => ${obj_part.v[obj_part.v.len-1]}")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
`f` {
|
||||
// println("${c} ${row}")
|
||||
obj_part.part[obj_part.part.len - 1].parse_faces(row, i, obj_part)
|
||||
// println(obj_part.part[obj_part.part.len - 1].faces.len)
|
||||
// println("Faces line: ${c}")
|
||||
break
|
||||
}
|
||||
// end of the line, comments
|
||||
`\n`, `#` {
|
||||
break
|
||||
}
|
||||
else {}
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
// if c == 2 { break }
|
||||
if c % 100000 == 0 && c > 0 {
|
||||
println('${c} rows parsed')
|
||||
}
|
||||
}
|
||||
println('${row_count} .obj Rows parsed')
|
||||
// remove default part if empty
|
||||
if obj_part.part.len > 1 && obj_part.part[0].faces.len == 0 {
|
||||
obj_part.part = obj_part.part[1..]
|
||||
}
|
||||
}
|
||||
|
||||
// load the materials if found the .mtl file
|
||||
fn (mut obj_part ObjPart) load_materials() {
|
||||
rows := read_lines_from_file(obj_part.material_file)
|
||||
println('Material file [${obj_part.material_file}] ${rows.len} Rows.')
|
||||
for row in rows {
|
||||
// println("${row}")
|
||||
mut i := 0
|
||||
for true {
|
||||
if i >= row.len {
|
||||
break
|
||||
}
|
||||
match row[i] {
|
||||
`n` {
|
||||
if row[i..i + 6] == 'newmtl' {
|
||||
name := row[i + 6..].trim_space()
|
||||
mut mat := Material{
|
||||
name: name
|
||||
}
|
||||
obj_part.mat << mat
|
||||
break
|
||||
}
|
||||
}
|
||||
`K` {
|
||||
if row[i + 1] !in [`a`, `d`, `e`, `s`] {
|
||||
break
|
||||
}
|
||||
k_name := row[i..i + 2]
|
||||
i += 3
|
||||
value := parse_3f(row, i)
|
||||
obj_part.mat[obj_part.mat.len - 1].ks[k_name] = value
|
||||
break
|
||||
}
|
||||
`N` {
|
||||
n_name := row[i..i + 2]
|
||||
i += 3
|
||||
value, _ := get_float(row, i)
|
||||
obj_part.mat[obj_part.mat.len - 1].ns[n_name] = f32(value)
|
||||
break
|
||||
}
|
||||
`m` {
|
||||
if row[i..i + 4] == 'map_' {
|
||||
name := row[i..i + 6]
|
||||
if (i + 7) < row.len {
|
||||
file_name := row[i + 7..].trim_space()
|
||||
obj_part.mat[obj_part.mat.len - 1].maps[name] = file_name
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
// transparency
|
||||
`d` {
|
||||
if row[i + 1] == ` ` {
|
||||
value, _ := get_float(row, i + 2)
|
||||
obj_part.mat[obj_part.mat.len - 1].ns['Tr'] = f32(value)
|
||||
}
|
||||
}
|
||||
`T` {
|
||||
if row[i + 1] == `r` {
|
||||
value, _ := get_float(row, i + 3)
|
||||
obj_part.mat[obj_part.mat.len - 1].ns['Tr'] = f32(1.0 - value)
|
||||
}
|
||||
}
|
||||
// end of the line, comments
|
||||
`\n`, `#` {
|
||||
break
|
||||
}
|
||||
` `, `\t` {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
// create map material name => material index
|
||||
for i, m in obj_part.mat {
|
||||
if m.name !in obj_part.mat_map {
|
||||
obj_part.mat_map[m.name] = i
|
||||
}
|
||||
}
|
||||
|
||||
println('Material Loading Done!')
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
// Sokol data
|
||||
//==============================================================================
|
||||
|
||||
// vertex data struct
|
||||
pub struct Vertex_pnct {
|
||||
pub mut:
|
||||
x f32 // position
|
||||
y f32
|
||||
z f32
|
||||
nx f32 // normal
|
||||
ny f32
|
||||
nz f32
|
||||
// color u32 = 0xFFFFFFFF // color
|
||||
u f32 // uv
|
||||
v f32
|
||||
// u u16 // for compatibility with D3D11
|
||||
// v u16 // for compatibility with D3D11
|
||||
}
|
||||
|
||||
// struct used to pass the data to the sokol calls
|
||||
pub struct Skl_buffer {
|
||||
pub mut:
|
||||
vbuf []Vertex_pnct
|
||||
ibuf []u32
|
||||
n_vertex u32
|
||||
}
|
||||
|
||||
// transforms data from .obj format to buffer ready to be used in the render
|
||||
pub fn (mut obj_part ObjPart) get_buffer(in_part_list []int) Skl_buffer {
|
||||
// in_part := 0
|
||||
mut v_count_index := 0
|
||||
mut out_buf := Skl_buffer{}
|
||||
|
||||
mut cache := map[string]int{}
|
||||
mut cache_hit := 0
|
||||
|
||||
// has_normals := obj_part.vn.len > 0
|
||||
// has_uvs := obj_part.vt.len > 0
|
||||
|
||||
for in_part in in_part_list {
|
||||
part := obj_part.part[in_part]
|
||||
for fc, face in part.faces {
|
||||
// println("${fc} ${face}")
|
||||
// default 3 faces
|
||||
mut v_seq := [0, 1, 2]
|
||||
if face.len == 4 {
|
||||
v_seq = [0, 1, 2, 0, 2, 3]
|
||||
}
|
||||
|
||||
// if big faces => use the fan of triangles as solution
|
||||
// Note: this trick doesn't work with concave faces
|
||||
if face.len > 4 {
|
||||
v_seq = []
|
||||
mut i := 1
|
||||
for i < (face.len - 1) {
|
||||
v_seq << 0
|
||||
v_seq << i
|
||||
v_seq << (i + 1)
|
||||
i++
|
||||
}
|
||||
// println("BIG FACES! ${fc} ${face.len} v_seq:${v_seq.len}")
|
||||
}
|
||||
|
||||
// no vertex index, generate normals
|
||||
if face[0][1] == -1 && face.len >= 3 {
|
||||
mut v_count := 0
|
||||
v0 := face[v_count + 0][0]
|
||||
v1 := face[v_count + 1][0]
|
||||
v2 := face[v_count + 2][0]
|
||||
|
||||
vec0 := obj_part.v[v2] - obj_part.v[v1]
|
||||
vec1 := obj_part.v[v0] - obj_part.v[v1]
|
||||
tmp_normal := vec0 % vec1
|
||||
|
||||
for v_count < face.len {
|
||||
obj_part.vn << tmp_normal
|
||||
obj_part.part[in_part].faces[fc][v_count][1] = obj_part.vn.len - 1
|
||||
v_count++
|
||||
}
|
||||
}
|
||||
|
||||
for vertex_index in v_seq {
|
||||
// position
|
||||
if vertex_index >= face.len {
|
||||
continue
|
||||
}
|
||||
v_index := face[vertex_index][0] // vertex index
|
||||
n_index := face[vertex_index][1] // normal index
|
||||
t_index := face[vertex_index][2] // uv texture index
|
||||
key := '${v_index}_${n_index}_${t_index}'
|
||||
if key !in cache {
|
||||
cache[key] = v_count_index
|
||||
mut pnct := Vertex_pnct{
|
||||
x: obj_part.v[v_index].e[0]
|
||||
y: obj_part.v[v_index].e[1]
|
||||
z: obj_part.v[v_index].e[2]
|
||||
}
|
||||
// normal
|
||||
if n_index >= 0 {
|
||||
pnct.nx = obj_part.vn[n_index].e[0]
|
||||
pnct.ny = obj_part.vn[n_index].e[1]
|
||||
pnct.nz = obj_part.vn[n_index].e[2]
|
||||
}
|
||||
// texture uv
|
||||
if t_index >= 0 {
|
||||
pnct.u = obj_part.vt[t_index].e[0]
|
||||
pnct.v = obj_part.vt[t_index].e[1]
|
||||
}
|
||||
|
||||
out_buf.vbuf << pnct
|
||||
out_buf.ibuf << u32(v_count_index)
|
||||
v_count_index++
|
||||
} else {
|
||||
// println("Cache used! ${key}")
|
||||
out_buf.ibuf << u32(cache[key])
|
||||
cache_hit++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
println("------------")
|
||||
for c1, x1 in out_buf.vbuf[..10] {
|
||||
println("${c1} ${x1}")
|
||||
}
|
||||
println(out_buf.ibuf[..10])
|
||||
*/
|
||||
// println("vbuf size: ${out_buf.vbuf.len} ibuf size: ${out_buf.ibuf.len} Cache hit: ${cache_hit}")
|
||||
out_buf.n_vertex = u32(out_buf.ibuf.len)
|
||||
return out_buf
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
// Utility
|
||||
//==============================================================================
|
||||
// print on the console the summary of the .obj model loaded
|
||||
pub fn (obj_part ObjPart) summary() {
|
||||
println('---- Stats ----')
|
||||
println('vertices: ${obj_part.v.len}')
|
||||
println('normals : ${obj_part.vn.len}')
|
||||
println('uv : ${obj_part.vt.len}')
|
||||
println('parts : ${obj_part.part.len}')
|
||||
// Parts
|
||||
println('---- Parts ----')
|
||||
for c, x in obj_part.part {
|
||||
println('${c:3} [${x.name:-16}] mat:[${x.material:-10}] ${x.faces.len:7} faces')
|
||||
}
|
||||
// Materials
|
||||
println('---- Materials ----')
|
||||
println('Material dict: ${obj_part.mat_map.keys()}')
|
||||
for c, mat in obj_part.mat {
|
||||
println('${c:3} [${mat.name:-16}]')
|
||||
for k, v in mat.ks {
|
||||
print('${k} = ${v}')
|
||||
}
|
||||
for k, v in mat.ns {
|
||||
println('${k} = ${v}')
|
||||
}
|
||||
for k, v in mat.maps {
|
||||
println('${k} = ${v}')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// debug test function, do not remove.
|
||||
pub fn tst() {
|
||||
/*
|
||||
//fname := "capsule.obj"
|
||||
//fname := "Forklift.obj"
|
||||
fname := "cube.obj"
|
||||
//fname := "Orange Robot 3D ObjPart.obj"
|
||||
|
||||
mut obj := ObjPart{}
|
||||
buf := os.read_lines(fname) or { panic(err.msg) }
|
||||
obj.parse_obj_buffer(buf)
|
||||
obj.summary()
|
||||
*/
|
||||
/*
|
||||
a :="f 7048 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7003"
|
||||
mut f1 := 0
|
||||
mut f2 := 0
|
||||
f0,mut p := get_int(a,1)
|
||||
f1, p = get_int(a,p)
|
||||
f2, p = get_int(a,p)
|
||||
println("res: ${f0} ${f1} ${f2}")
|
||||
*/
|
||||
/*
|
||||
a :="v -0 0.107769 -0.755914"
|
||||
println("${parse_3f(a,1)}")
|
||||
*/
|
||||
/*
|
||||
ort := m4.ortho(0,300,0,200,0,0)
|
||||
println(ort)
|
||||
a := m4.vec3(0,0,0)
|
||||
println("a: ${a}")
|
||||
res := m4.mul_vec(ort, a)
|
||||
println("res:\n${res}")
|
||||
*/
|
||||
s := 'K 1 1 1'
|
||||
r := strconv.atof_quick(s[1..s.len - 1])
|
||||
println(r)
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
/**********************************************************************
|
||||
*
|
||||
* .obj loader
|
||||
*
|
||||
* Copyright (c) 2021 Dario Deledda. All rights reserved.
|
||||
* Use of this source code is governed by an MIT license
|
||||
* that can be found in the LICENSE file.
|
||||
*
|
||||
* TODO:
|
||||
**********************************************************************/
|
||||
module obj
|
||||
|
||||
import sokol.gfx
|
||||
import gg.m4
|
||||
import math
|
||||
import stbi
|
||||
|
||||
/******************************************************************************
|
||||
* Texture functions
|
||||
******************************************************************************/
|
||||
pub fn create_texture(w int, h int, buf &u8) (gfx.Image, gfx.Sampler) {
|
||||
sz := w * h * 4
|
||||
mut img_desc := gfx.ImageDesc{
|
||||
width: w
|
||||
height: h
|
||||
num_mipmaps: 0
|
||||
// min_filter: .linear
|
||||
// mag_filter: .linear
|
||||
// usage: .dynamic
|
||||
// wrap_u: .clamp_to_edge
|
||||
// wrap_v: .clamp_to_edge
|
||||
label: &char(unsafe { nil })
|
||||
d3d11_texture: 0
|
||||
}
|
||||
// comment if .dynamic is enabled
|
||||
img_desc.data.subimage[0][0] = gfx.Range{
|
||||
ptr: buf
|
||||
size: usize(sz)
|
||||
}
|
||||
|
||||
sg_img := gfx.make_image(&img_desc)
|
||||
|
||||
mut smp_desc := gfx.SamplerDesc{
|
||||
min_filter: .linear
|
||||
mag_filter: .linear
|
||||
wrap_u: .clamp_to_edge
|
||||
wrap_v: .clamp_to_edge
|
||||
}
|
||||
|
||||
sg_smp := gfx.make_sampler(&smp_desc)
|
||||
return sg_img, sg_smp
|
||||
}
|
||||
|
||||
pub fn destroy_texture(sg_img gfx.Image) {
|
||||
gfx.destroy_image(sg_img)
|
||||
}
|
||||
|
||||
pub fn load_texture(file_name string) (gfx.Image, gfx.Sampler) {
|
||||
buffer := read_bytes_from_file(file_name)
|
||||
stbi.set_flip_vertically_on_load(true)
|
||||
img := stbi.load_from_memory(buffer.data, buffer.len) or {
|
||||
eprintln('Texture file: [${file_name}] ERROR!')
|
||||
exit(0)
|
||||
}
|
||||
sg_img, sg_smp := create_texture(int(img.width), int(img.height), img.data)
|
||||
img.free()
|
||||
return sg_img, sg_smp
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Pipeline
|
||||
******************************************************************************/
|
||||
pub fn (mut obj_part ObjPart) create_pipeline(in_part []int, shader gfx.Shader, texture gfx.Image, sampler gfx.Sampler) Render_data {
|
||||
mut res := Render_data{}
|
||||
obj_buf := obj_part.get_buffer(in_part)
|
||||
res.n_vert = obj_buf.n_vertex
|
||||
res.material = obj_part.part[in_part[0]].material
|
||||
|
||||
// vertex buffer
|
||||
mut vert_buffer_desc := gfx.BufferDesc{}
|
||||
unsafe { vmemset(&vert_buffer_desc, 0, int(sizeof(vert_buffer_desc))) }
|
||||
|
||||
vert_buffer_desc.size = usize(obj_buf.vbuf.len * int(sizeof(Vertex_pnct)))
|
||||
vert_buffer_desc.data = gfx.Range{
|
||||
ptr: obj_buf.vbuf.data
|
||||
size: usize(obj_buf.vbuf.len * int(sizeof(Vertex_pnct)))
|
||||
}
|
||||
|
||||
vert_buffer_desc.type = .vertexbuffer
|
||||
vert_buffer_desc.label = &char('vertbuf_part_${in_part:03}'.str)
|
||||
vbuf := gfx.make_buffer(&vert_buffer_desc)
|
||||
|
||||
// index buffer
|
||||
mut index_buffer_desc := gfx.BufferDesc{}
|
||||
unsafe { vmemset(&index_buffer_desc, 0, int(sizeof(index_buffer_desc))) }
|
||||
|
||||
index_buffer_desc.size = usize(obj_buf.ibuf.len * int(sizeof(u32)))
|
||||
index_buffer_desc.data = gfx.Range{
|
||||
ptr: obj_buf.ibuf.data
|
||||
size: usize(obj_buf.ibuf.len * int(sizeof(u32)))
|
||||
}
|
||||
|
||||
index_buffer_desc.type = .indexbuffer
|
||||
index_buffer_desc.label = &char('indbuf_part_${in_part:03}'.str)
|
||||
ibuf := gfx.make_buffer(&index_buffer_desc)
|
||||
|
||||
mut pipdesc := gfx.PipelineDesc{}
|
||||
unsafe { vmemset(&pipdesc, 0, int(sizeof(pipdesc))) }
|
||||
pipdesc.layout.buffers[0].stride = int(sizeof(Vertex_pnct))
|
||||
|
||||
// the constants [C.ATTR_vs_a_Position, C.ATTR_vs_a_Color, C.ATTR_vs_a_Texcoord0] are generated by sokol-shdc
|
||||
pipdesc.layout.attrs[C.ATTR_vs_a_Position].format = .float3 // x,y,z as f32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_a_Normal].format = .float3 // x,y,z as f32
|
||||
// pipdesc.layout.attrs[C.ATTR_vs_a_Color].format = .ubyte4n // color as u32
|
||||
pipdesc.layout.attrs[C.ATTR_vs_a_Texcoord0].format = .float2 // u,v as f32
|
||||
// pipdesc.layout.attrs[C.ATTR_vs_a_Texcoord0].format = .short2n // u,v as u16
|
||||
pipdesc.index_type = .uint32
|
||||
|
||||
color_state := gfx.ColorTargetState{
|
||||
blend: gfx.BlendState{
|
||||
enabled: true
|
||||
src_factor_rgb: .src_alpha
|
||||
dst_factor_rgb: .one_minus_src_alpha
|
||||
}
|
||||
}
|
||||
pipdesc.colors[0] = color_state
|
||||
|
||||
pipdesc.depth = gfx.DepthState{
|
||||
write_enabled: true
|
||||
compare: .less_equal
|
||||
}
|
||||
pipdesc.cull_mode = .front
|
||||
|
||||
pipdesc.label = &char('pip_part_${in_part:03}'.str)
|
||||
|
||||
// shader
|
||||
pipdesc.shader = shader
|
||||
|
||||
res.bind.vertex_buffers[0] = vbuf
|
||||
res.bind.index_buffer = ibuf
|
||||
res.bind.fs.images[C.SLOT_tex] = texture
|
||||
res.bind.fs.samplers[C.SLOT_smp] = sampler
|
||||
res.pipeline = gfx.make_pipeline(&pipdesc)
|
||||
// println('Buffers part [${in_part}] init done!')
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Render functions
|
||||
******************************************************************************/
|
||||
// aggregate all the part by materials
|
||||
pub fn (mut obj_part ObjPart) init_render_data(texture gfx.Image, sampler gfx.Sampler) {
|
||||
// create shader
|
||||
// One shader for all the model
|
||||
shader := gfx.make_shader(voidptr(C.gouraud_shader_desc(gfx.query_backend())))
|
||||
|
||||
mut part_dict := map[string][]int{}
|
||||
for i, p in obj_part.part {
|
||||
if p.faces.len > 0 {
|
||||
part_dict[p.material] << i
|
||||
}
|
||||
}
|
||||
obj_part.rend_data.clear()
|
||||
// println("Material dict: ${obj_part.mat_map.keys()}")
|
||||
|
||||
for k, v in part_dict {
|
||||
// println("${k} => Parts ${v}")
|
||||
|
||||
mut txt := texture
|
||||
mut smp := sampler
|
||||
|
||||
if k in obj_part.mat_map {
|
||||
mat_map := obj_part.mat[obj_part.mat_map[k]]
|
||||
if 'map_Kd' in mat_map.maps {
|
||||
file_name := mat_map.maps['map_Kd']
|
||||
if file_name in obj_part.texture {
|
||||
txt = obj_part.texture[file_name]
|
||||
// println("Texture [${file_name}] => from CACHE")
|
||||
} else {
|
||||
txt, smp = load_texture(file_name)
|
||||
obj_part.texture[file_name] = txt
|
||||
obj_part.sampler[file_name] = smp
|
||||
// println("Texture [${file_name}] => LOADED")
|
||||
}
|
||||
}
|
||||
}
|
||||
// key := obj_part.texture.keys()[0]
|
||||
// obj_part.rend_data << obj_part.create_pipeline(v, shader, obj_part.texture[key])
|
||||
obj_part.rend_data << obj_part.create_pipeline(v, shader, txt, smp)
|
||||
}
|
||||
// println("Texture array len: ${obj_part.texture.len}")
|
||||
// println("Calc bounding box.")
|
||||
obj_part.calc_bbox()
|
||||
println('init_render_data DONE!')
|
||||
}
|
||||
|
||||
pub fn (obj_part ObjPart) bind_and_draw(rend_data_index int, in_data Shader_data) u32 {
|
||||
// apply the pipeline and bindings
|
||||
mut part_render_data := obj_part.rend_data[rend_data_index]
|
||||
|
||||
// pass light position
|
||||
mut tmp_fs_params := Tmp_fs_param{}
|
||||
tmp_fs_params.light = in_data.fs_data.light
|
||||
|
||||
if part_render_data.material in obj_part.mat_map {
|
||||
mat_index := obj_part.mat_map[part_render_data.material]
|
||||
mat := obj_part.mat[mat_index]
|
||||
|
||||
// ambient
|
||||
tmp_fs_params.ka = in_data.fs_data.ka
|
||||
if 'Ka' in mat.ks {
|
||||
tmp_fs_params.ka = mat.ks['Ka']
|
||||
}
|
||||
|
||||
// specular
|
||||
tmp_fs_params.ks = in_data.fs_data.ks
|
||||
if 'Ks' in mat.ks {
|
||||
tmp_fs_params.ks = mat.ks['Ks']
|
||||
}
|
||||
|
||||
// specular exponent Ns
|
||||
if 'Ns' in mat.ns {
|
||||
tmp_fs_params.ks.e[3] = mat.ns['Ns'] / 1000.0
|
||||
} else {
|
||||
// default value is 10
|
||||
tmp_fs_params.ks.e[3] = f32(10) / 1000.0
|
||||
}
|
||||
|
||||
// diffuse
|
||||
tmp_fs_params.kd = in_data.fs_data.kd
|
||||
if 'Kd' in mat.ks {
|
||||
tmp_fs_params.kd = mat.ks['Kd']
|
||||
}
|
||||
|
||||
// alpha/transparency
|
||||
if 'Tr' in mat.ns {
|
||||
tmp_fs_params.kd.e[3] = mat.ns['Tr']
|
||||
}
|
||||
}
|
||||
|
||||
gfx.apply_pipeline(part_render_data.pipeline)
|
||||
gfx.apply_bindings(part_render_data.bind)
|
||||
|
||||
vs_uniforms_range := gfx.Range{
|
||||
ptr: in_data.vs_data
|
||||
size: usize(in_data.vs_len)
|
||||
}
|
||||
fs_uniforms_range := gfx.Range{
|
||||
ptr: unsafe { &tmp_fs_params }
|
||||
size: usize(in_data.fs_len)
|
||||
}
|
||||
|
||||
gfx.apply_uniforms(.vs, C.SLOT_vs_params, &vs_uniforms_range)
|
||||
gfx.apply_uniforms(.fs, C.SLOT_fs_params, &fs_uniforms_range)
|
||||
gfx.draw(0, int(part_render_data.n_vert), 1)
|
||||
return part_render_data.n_vert
|
||||
}
|
||||
|
||||
pub fn (obj_part ObjPart) bind_and_draw_all(in_data Shader_data) u32 {
|
||||
mut n_vert := u32(0)
|
||||
// println("Parts: ${obj_part.rend_data.len}")
|
||||
for i, _ in obj_part.rend_data {
|
||||
n_vert += obj_part.bind_and_draw(i, in_data)
|
||||
}
|
||||
return n_vert
|
||||
}
|
||||
|
||||
pub fn (mut obj_part ObjPart) calc_bbox() {
|
||||
obj_part.max = m4.Vec4{
|
||||
e: [f32(-math.max_f32), -math.max_f32, -math.max_f32, 0]!
|
||||
}
|
||||
obj_part.min = m4.Vec4{
|
||||
e: [f32(math.max_f32), math.max_f32, math.max_f32, 0]!
|
||||
}
|
||||
for v in obj_part.v {
|
||||
if v.e[0] > obj_part.max.e[0] {
|
||||
obj_part.max.e[0] = v.e[0]
|
||||
}
|
||||
if v.e[1] > obj_part.max.e[1] {
|
||||
obj_part.max.e[1] = v.e[1]
|
||||
}
|
||||
if v.e[2] > obj_part.max.e[2] {
|
||||
obj_part.max.e[2] = v.e[2]
|
||||
}
|
||||
|
||||
if v.e[0] < obj_part.min.e[0] {
|
||||
obj_part.min.e[0] = v.e[0]
|
||||
}
|
||||
if v.e[1] < obj_part.min.e[1] {
|
||||
obj_part.min.e[1] = v.e[1]
|
||||
}
|
||||
if v.e[2] < obj_part.min.e[2] {
|
||||
obj_part.min.e[2] = v.e[2]
|
||||
}
|
||||
}
|
||||
val1 := obj_part.max.mod3()
|
||||
val2 := obj_part.min.mod3()
|
||||
if val1 > val2 {
|
||||
obj_part.radius = f32(val1)
|
||||
} else {
|
||||
obj_part.radius = f32(val2)
|
||||
}
|
||||
// println("BBox: ${obj_part.min} <=> ${obj_part.max}\nRadius: ${obj_part.radius}")
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/**********************************************************************
|
||||
*
|
||||
* .obj loader
|
||||
*
|
||||
* Copyright (c) 2021 Dario Deledda. All rights reserved.
|
||||
* Use of this source code is governed by an MIT license
|
||||
* that can be found in the LICENSE file.
|
||||
*
|
||||
* TODO:
|
||||
**********************************************************************/
|
||||
module obj
|
||||
|
||||
import gg.m4
|
||||
import sokol.gfx
|
||||
|
||||
// part struct maintaining the face indices
|
||||
pub struct Part {
|
||||
pub mut:
|
||||
faces [][][3]int // v n t index order, if -1 not available
|
||||
name string
|
||||
material string
|
||||
}
|
||||
|
||||
// material struct, all Ks and Ns are stored as maps of string
|
||||
pub struct Material {
|
||||
pub mut:
|
||||
name string
|
||||
ks map[string]m4.Vec4
|
||||
ns map[string]f32
|
||||
maps map[string]string
|
||||
}
|
||||
|
||||
// render data used for the rendering
|
||||
pub struct Render_data {
|
||||
pub mut:
|
||||
pipeline gfx.Pipeline
|
||||
bind gfx.Bindings
|
||||
n_vert u32
|
||||
material string
|
||||
}
|
||||
|
||||
// base object parts struct
|
||||
pub struct ObjPart {
|
||||
pub mut:
|
||||
v []m4.Vec4 // position
|
||||
vn []m4.Vec4 // normals
|
||||
vp []m4.Vec4 // vertex params
|
||||
vt []m4.Vec4 // textures
|
||||
|
||||
name string
|
||||
part []Part // parts of the ObjPart
|
||||
mat []Material // list of the materials of the ObjPart
|
||||
mat_map map[string]int // mapping material name to its material index
|
||||
texture map[string]gfx.Image // GPU loaded texture map
|
||||
sampler map[string]gfx.Sampler // GPU loaded sampler
|
||||
material_file string // .mtl file name for the .obj
|
||||
|
||||
rend_data []Render_data // render data used for the rendering
|
||||
|
||||
t_m m4.Mat4 = m4.unit_m4() // transform matrix for this ObjPart
|
||||
// child []ObjPart
|
||||
// stats
|
||||
min m4.Vec4 // min 3d position in the ObjPart
|
||||
max m4.Vec4 // max 3d position in the ObjPart
|
||||
radius f32 // bounding circle radius of the ObjPart
|
||||
}
|
||||
|
||||
// used in to pass the matrices to the shader
|
||||
pub struct Mats {
|
||||
pub mut:
|
||||
mv m4.Mat4
|
||||
mvp m4.Mat4
|
||||
nm m4.Mat4
|
||||
}
|
||||
|
||||
// data passed to the vertex shader
|
||||
pub struct Tmp_vs_param {
|
||||
pub mut:
|
||||
mv m4.Mat4
|
||||
mvp m4.Mat4
|
||||
nm m4.Mat4
|
||||
}
|
||||
|
||||
// data passed to the pixel shader
|
||||
pub struct Tmp_fs_param {
|
||||
pub mut:
|
||||
light m4.Vec4
|
||||
ka m4.Vec4 = m4.Vec4{
|
||||
e: [f32(0.1), 0.0, 0.0, 1.0]!
|
||||
}
|
||||
kd m4.Vec4 = m4.Vec4{
|
||||
e: [f32(0.5), 0.5, 0.5, 1.0]!
|
||||
}
|
||||
ks m4.Vec4 = m4.Vec4{
|
||||
e: [f32(1.0), 1.0, 1.0, 1.0]!
|
||||
}
|
||||
}
|
||||
|
||||
// shader data for the rendering
|
||||
pub struct Shader_data {
|
||||
pub mut:
|
||||
vs_data &Tmp_vs_param = unsafe { nil }
|
||||
vs_len int
|
||||
fs_data &Tmp_fs_param = unsafe { nil }
|
||||
fs_len int
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
module obj
|
||||
|
||||
import os
|
||||
import os.asset
|
||||
|
||||
// read a file as single lines
|
||||
pub fn read_lines_from_file(file_path string) []string {
|
||||
if os.exists(file_path) {
|
||||
return os.read_lines(file_path) or { [] }
|
||||
}
|
||||
return read_bytes_from_file(file_path).bytestr().split_into_lines()
|
||||
}
|
||||
|
||||
// read a file as []u8
|
||||
pub fn read_bytes_from_file(file_path string) []u8 {
|
||||
if os.exists(file_path) {
|
||||
return os.read_bytes(file_path) or { [] }
|
||||
}
|
||||
mpath := 'models/${file_path}'
|
||||
return asset.read_bytes('assets', mpath) or {
|
||||
eprintln('Model file NOT FOUND: `${mpath}`')
|
||||
exit(0)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
// vtest build: misc-tooling // needs .h files that are produced by `v shader`
|
||||
/**********************************************************************
|
||||
*
|
||||
* .obj viewer
|
||||
*
|
||||
* Copyright (c) 2021 Dario Deledda. All rights reserved.
|
||||
* Use of this source code is governed by an MIT license
|
||||
* that can be found in the LICENSE file.
|
||||
*
|
||||
* Example .obj model of V from SurmanPP
|
||||
*
|
||||
* HOW TO COMPILE SHADERS:
|
||||
* Run `v shader .` in this directory to compile the shaders.
|
||||
* For more info and help with shader compilation see `docs.md` and `v help shader`.
|
||||
*
|
||||
* ALTERNATIVE .OBJ MODELS:
|
||||
* you can load alternative models putting them in the "assets/model" folder with or without their .mtl file.
|
||||
* use the program help for further instructions.
|
||||
*
|
||||
* TODO:
|
||||
* - frame counter
|
||||
**********************************************************************/
|
||||
import gg
|
||||
import gg.m4
|
||||
import math
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
import sokol.sgl
|
||||
import time
|
||||
import os
|
||||
import obj
|
||||
|
||||
// GLSL Include and functions
|
||||
|
||||
#include "@VMODROOT/gouraud.h" # It should be generated with `v shader .` (see the instructions at the top of this file)
|
||||
|
||||
fn C.gouraud_shader_desc(gfx.Backend) &gfx.ShaderDesc
|
||||
|
||||
const win_width = 600
|
||||
const win_height = 600
|
||||
const bg_color = gg.white
|
||||
|
||||
struct App {
|
||||
mut:
|
||||
gg &gg.Context = unsafe { nil }
|
||||
texture gfx.Image
|
||||
sampler gfx.Sampler
|
||||
init_flag bool
|
||||
frame_count int
|
||||
|
||||
mouse_x int = -1
|
||||
mouse_y int = -1
|
||||
scroll_y int // mouse wheel value
|
||||
// time
|
||||
ticks i64
|
||||
// model
|
||||
obj_part &obj.ObjPart = unsafe { nil }
|
||||
n_vertex u32
|
||||
// init parameters
|
||||
file_name string
|
||||
single_material_flag bool
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Draw functions
|
||||
******************************************************************************/
|
||||
@[inline]
|
||||
fn vec4(x f32, y f32, z f32, w f32) m4.Vec4 {
|
||||
return m4.Vec4{
|
||||
e: [x, y, z, w]!
|
||||
}
|
||||
}
|
||||
|
||||
fn calc_matrices(w f32, h f32, rx f32, ry f32, in_scale f32, pos m4.Vec4) obj.Mats {
|
||||
proj := m4.perspective(60, w / h, 0.01, 100.0) // set far plane to 100 fro the zoom function
|
||||
view := m4.look_at(vec4(f32(0.0), 0, 6, 0), vec4(f32(0), 0, 0, 0), vec4(f32(0), 1, 0, 0))
|
||||
view_proj := view * proj
|
||||
|
||||
rxm := m4.rotate(m4.rad(rx), vec4(f32(1), 0, 0, 0))
|
||||
rym := m4.rotate(m4.rad(ry), vec4(f32(0), 1, 0, 0))
|
||||
|
||||
model_pos := m4.unit_m4().translate(pos)
|
||||
|
||||
model_m := (rym * rxm) * model_pos
|
||||
scale_m := m4.scale(vec4(in_scale, in_scale, in_scale, 1))
|
||||
|
||||
mv := scale_m * model_m // model view
|
||||
nm := mv.inverse().transpose() // normal matrix
|
||||
mvp := mv * view_proj // model view projection
|
||||
|
||||
return obj.Mats{
|
||||
mv: mv
|
||||
mvp: mvp
|
||||
nm: nm
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_model(app App, model_pos m4.Vec4) u32 {
|
||||
if app.init_flag == false {
|
||||
return 0
|
||||
}
|
||||
|
||||
ws := gg.window_size_real_pixels()
|
||||
dw := ws.width / 2
|
||||
dh := ws.height / 2
|
||||
|
||||
mut scale := f32(1)
|
||||
if app.obj_part.radius > 1 {
|
||||
scale = 1 / (app.obj_part.radius)
|
||||
} else {
|
||||
scale = app.obj_part.radius
|
||||
}
|
||||
scale *= 3
|
||||
|
||||
// *** vertex shader uniforms ***
|
||||
rot := [f32(app.mouse_y), f32(app.mouse_x)]
|
||||
mut zoom_scale := scale + f32(app.scroll_y) / (app.obj_part.radius * 4)
|
||||
mats := calc_matrices(dw, dh, rot[0], rot[1], zoom_scale, model_pos)
|
||||
|
||||
mut tmp_vs_param := obj.Tmp_vs_param{
|
||||
mv: mats.mv
|
||||
mvp: mats.mvp
|
||||
nm: mats.nm
|
||||
}
|
||||
|
||||
// *** fragment shader uniforms ***
|
||||
time_ticks := f32(time.ticks() - app.ticks) / 1000
|
||||
radius_light := f32(app.obj_part.radius)
|
||||
x_light := f32(math.cos(time_ticks) * radius_light)
|
||||
z_light := f32(math.sin(time_ticks) * radius_light)
|
||||
|
||||
mut tmp_fs_params := obj.Tmp_fs_param{}
|
||||
tmp_fs_params.light = m4.vec3(x_light, radius_light, z_light)
|
||||
|
||||
sd := obj.Shader_data{
|
||||
vs_data: unsafe { &tmp_vs_param }
|
||||
vs_len: int(sizeof(tmp_vs_param))
|
||||
fs_data: unsafe { &tmp_fs_params }
|
||||
fs_len: int(sizeof(tmp_fs_params))
|
||||
}
|
||||
|
||||
return app.obj_part.bind_and_draw_all(sd)
|
||||
}
|
||||
|
||||
fn frame(mut app App) {
|
||||
// clear
|
||||
mut color_action := gfx.ColorAttachmentAction{
|
||||
load_action: .clear
|
||||
clear_value: gfx.Color{
|
||||
r: 0.0
|
||||
g: 0.0
|
||||
b: 0.0
|
||||
a: 1.0
|
||||
}
|
||||
}
|
||||
|
||||
mut pass_action := gfx.PassAction{}
|
||||
pass_action.colors[0] = color_action
|
||||
pass := sapp.create_default_pass(pass_action)
|
||||
gfx.begin_pass(&pass)
|
||||
|
||||
// render the data
|
||||
draw_start_glsl(app)
|
||||
draw_model(app, m4.Vec4{})
|
||||
// uncomment if you want a raw benchmark mode
|
||||
/*
|
||||
mut n_vertex_drawn := u32(0)
|
||||
n_x_obj := 20
|
||||
|
||||
for x in 0..n_x_obj {
|
||||
for z in 0..30 {
|
||||
for y in 0..4 {
|
||||
n_vertex_drawn += draw_model(app, m4.Vec4{e:[f32((x-(n_x_obj>>1))*3),-3 + y*3,f32(-6*z),1]!})
|
||||
}
|
||||
}
|
||||
}
|
||||
*/
|
||||
draw_end_glsl(app)
|
||||
|
||||
// println("v:${n_vertex_drawn}")
|
||||
app.frame_count++
|
||||
}
|
||||
|
||||
fn draw_start_glsl(app App) {
|
||||
if app.init_flag == false {
|
||||
return
|
||||
}
|
||||
ws := gg.window_size_real_pixels()
|
||||
gfx.apply_viewport(0, 0, ws.width, ws.height, true)
|
||||
}
|
||||
|
||||
fn draw_end_glsl(app App) {
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* Init / Cleanup
|
||||
******************************************************************************/
|
||||
fn my_init(mut app App) {
|
||||
mut object := &obj.ObjPart{}
|
||||
obj_file_lines := obj.read_lines_from_file(app.file_name)
|
||||
object.parse_obj_buffer(obj_file_lines, app.single_material_flag)
|
||||
object.summary()
|
||||
app.obj_part = object
|
||||
|
||||
// set max vertices,
|
||||
// for a large number of the same type of object it is better use the instances!!
|
||||
desc := sapp.create_desc()
|
||||
gfx.setup(&desc)
|
||||
sgl_desc := sgl.Desc{
|
||||
max_vertices: 128 * 65536
|
||||
}
|
||||
sgl.setup(&sgl_desc)
|
||||
|
||||
// 1x1 pixel white, default texture
|
||||
unsafe {
|
||||
tmp_txt := malloc(4)
|
||||
tmp_txt[0] = u8(0xFF)
|
||||
tmp_txt[1] = u8(0xFF)
|
||||
tmp_txt[2] = u8(0xFF)
|
||||
tmp_txt[3] = u8(0xFF)
|
||||
app.texture, app.sampler = obj.create_texture(1, 1, tmp_txt)
|
||||
free(tmp_txt)
|
||||
}
|
||||
// glsl
|
||||
app.obj_part.init_render_data(app.texture, app.sampler)
|
||||
app.init_flag = true
|
||||
}
|
||||
|
||||
fn cleanup(mut app App) {
|
||||
/*
|
||||
for _, mat in app.obj_part.texture {
|
||||
obj.destroy_texture(mat)
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
/******************************************************************************
|
||||
* events handling
|
||||
******************************************************************************/
|
||||
fn my_event_manager(mut ev gg.Event, mut app App) {
|
||||
if ev.typ == .mouse_move {
|
||||
app.mouse_x = int(ev.mouse_x)
|
||||
app.mouse_y = int(ev.mouse_y)
|
||||
}
|
||||
|
||||
if ev.scroll_y != 0 {
|
||||
app.scroll_y += int(ev.scroll_y)
|
||||
}
|
||||
|
||||
if ev.typ == .touches_began || ev.typ == .touches_moved {
|
||||
if ev.num_touches > 0 {
|
||||
touch_point := ev.touches[0]
|
||||
app.mouse_x = int(touch_point.pos_x)
|
||||
app.mouse_y = int(touch_point.pos_y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
/*
|
||||
obj.tst()
|
||||
exit(0)
|
||||
*/
|
||||
// App init
|
||||
mut app := &App{}
|
||||
|
||||
// app.file_name = 'v.obj' // default object is the v logo
|
||||
app.file_name = 'utahTeapot.obj' // default object is the v logo
|
||||
|
||||
app.single_material_flag = false
|
||||
$if !android {
|
||||
if os.args.len > 3 || (os.args.len >= 2 && os.args[1] in ['-h', '--help', '\\?', '-?']) {
|
||||
eprintln('Usage:\nshow_obj [file_name:string] [single_material_flag:(true|false)]\n')
|
||||
eprintln('file_name : name of the .obj file.')
|
||||
eprintln(' If no file name is passed the default V logo will be showed.')
|
||||
eprintln(' Try one of the .obj files in the "assets/models/" folder.')
|
||||
eprintln("single_material_flag: if true the viewer use for all the model's parts the default material")
|
||||
exit(0)
|
||||
}
|
||||
|
||||
if os.args.len >= 2 {
|
||||
app.file_name = os.args[1]
|
||||
}
|
||||
if os.args.len >= 3 {
|
||||
app.single_material_flag = os.args[2].bool()
|
||||
}
|
||||
println('Loading model: ${app.file_name}')
|
||||
println('Using single material: ${app.single_material_flag}')
|
||||
}
|
||||
|
||||
app.gg = gg.new_context(
|
||||
width: win_width
|
||||
height: win_height
|
||||
create_window: true
|
||||
window_title: 'V Wavefront OBJ viewer - Use the mouse wheel to zoom'
|
||||
user_data: app
|
||||
bg_color: bg_color
|
||||
frame_fn: frame
|
||||
init_fn: my_init
|
||||
cleanup_fn: cleanup
|
||||
event_fn: my_event_manager
|
||||
)
|
||||
|
||||
app.ticks = time.ticks()
|
||||
app.gg.run()
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1 @@
|
||||
simple_shader.h
|
||||
@@ -0,0 +1,36 @@
|
||||
// The following defines a vertex shader main function
|
||||
@vs vs
|
||||
in vec4 position;
|
||||
in vec4 color0;
|
||||
|
||||
out vec4 color;
|
||||
|
||||
// You can add more functions here
|
||||
|
||||
void main() {
|
||||
gl_Position = position;
|
||||
color = color0;
|
||||
}
|
||||
@end
|
||||
|
||||
// The following defines a fragment shader main function
|
||||
@fs fs
|
||||
in vec4 color;
|
||||
out vec4 frag_color;
|
||||
|
||||
// You can add more functions here
|
||||
|
||||
void main() {
|
||||
frag_color = color;
|
||||
}
|
||||
@end
|
||||
|
||||
// The value after `@program` and before `vs fs` decide a part of the name
|
||||
// of the C function you need to define in V. The value entered is suffixed `_shader_desc`
|
||||
// in the generated C code. Thus the name for this becomes: `simple_shader_desc`.
|
||||
// In V it's signature then need to be defined as:
|
||||
// `fn C.simple_shader_desc(gfx.Backend) &gfx.ShaderDesc`. See `simple_shader.v` for the define.
|
||||
//
|
||||
// Running `v shader -v .` in this dir will also show you brief information
|
||||
// about how to use the compiled shader.
|
||||
@program simple vs fs
|
||||
@@ -0,0 +1,156 @@
|
||||
// Copyright(C) 2022 Lars Pontoppidan. All rights reserved.
|
||||
// Use of this source code is governed by an MIT license file distributed with this software package
|
||||
// vtest build: misc-tooling // needs .h files that are produced by `v shader`
|
||||
module main
|
||||
|
||||
// Example shader triangle adapted to V from https://github.com/floooh/sokol-samples/blob/1f2ad36/sapp/triangle-sapp.c
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
|
||||
// Use `v shader` or `sokol-shdc` to generate the necessary `.h` file
|
||||
// Using `v shader -v .` in this directory will show some additional
|
||||
// info - and what you should include to make things work.
|
||||
#include "@VMODROOT/simple_shader.h" # It should be generated with `v shader .`
|
||||
|
||||
// simple_shader_desc is a C function declaration defined by
|
||||
// the `@program` entry in the `simple_shader.glsl` shader file.
|
||||
// When the shader is compiled this function name is generated
|
||||
// by the shader compiler for easier inclusion of universal shader code
|
||||
// in C (and V) code.
|
||||
fn C.simple_shader_desc(gfx.Backend) &gfx.ShaderDesc
|
||||
|
||||
// Vertex_t makes it possible to model vertex buffer data
|
||||
// for use with the shader system
|
||||
struct Vertex_t {
|
||||
// Position
|
||||
x f32
|
||||
y f32
|
||||
z f32
|
||||
// Color
|
||||
r f32
|
||||
g f32
|
||||
b f32
|
||||
a f32
|
||||
}
|
||||
|
||||
fn main() {
|
||||
mut app := &App{
|
||||
width: 800
|
||||
height: 400
|
||||
pass_action: gfx.create_clear_pass_action(0.0, 0.0, 0.0, 1.0) // This will create a black color as a default pass (window background color)
|
||||
}
|
||||
app.run()
|
||||
}
|
||||
|
||||
struct App {
|
||||
pass_action gfx.PassAction
|
||||
mut:
|
||||
width int
|
||||
height int
|
||||
shader_pipeline gfx.Pipeline
|
||||
bind gfx.Bindings
|
||||
}
|
||||
|
||||
fn (mut a App) run() {
|
||||
title := 'V Simple Shader Example'
|
||||
desc := sapp.Desc{
|
||||
width: a.width
|
||||
height: a.height
|
||||
user_data: a
|
||||
init_userdata_cb: init
|
||||
frame_userdata_cb: frame
|
||||
window_title: &char(title.str)
|
||||
cleanup_userdata_cb: cleanup
|
||||
sample_count: 4 // Enables MSAA (Multisample anti-aliasing) x4 on rendered output, this can be omitted.
|
||||
}
|
||||
sapp.run(&desc)
|
||||
}
|
||||
|
||||
fn init(user_data voidptr) {
|
||||
mut app := unsafe { &App(user_data) }
|
||||
mut desc := sapp.create_desc()
|
||||
|
||||
gfx.setup(&desc)
|
||||
|
||||
// `vertices` defines a vertex buffer with 3 vertices
|
||||
// with 3 position fields XYZ and 4 color components RGBA -
|
||||
// for drawing a multi-colored triangle.
|
||||
//
|
||||
// C code:
|
||||
// float vertices[] = {
|
||||
// // Positions // Colors
|
||||
// 0.0, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0,
|
||||
// 0.5, -0.5, 0.5, 0.0, 1.0, 0.0, 1.0,
|
||||
// -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 1.0
|
||||
// };
|
||||
//
|
||||
// Array entries in the following V code is the equivalent
|
||||
// of the C code entry described above:
|
||||
vertices := [
|
||||
Vertex_t{0.0, 0.5, 0.5, 1.0, 0.0, 0.0, 1.0},
|
||||
Vertex_t{0.5, -0.5, 0.5, 0.0, 1.0, 0.0, 1.0},
|
||||
Vertex_t{-0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 1.0},
|
||||
]
|
||||
|
||||
// Create a vertex buffer with the 3 vertices defined above.
|
||||
mut vertex_buffer_desc := gfx.BufferDesc{
|
||||
label: c'triangle-vertices'
|
||||
}
|
||||
unsafe { vmemset(&vertex_buffer_desc, 0, int(sizeof(vertex_buffer_desc))) }
|
||||
|
||||
vertex_buffer_desc.size = usize(vertices.len * int(sizeof(Vertex_t)))
|
||||
vertex_buffer_desc.data = gfx.Range{
|
||||
ptr: vertices.data
|
||||
size: vertex_buffer_desc.size
|
||||
}
|
||||
|
||||
app.bind.vertex_buffers[0] = gfx.make_buffer(&vertex_buffer_desc)
|
||||
|
||||
// Create shader from the code-generated sg_shader_desc (gfx.ShaderDesc in V).
|
||||
// Note the function `C.simple_shader_desc()` (also defined above) - this is
|
||||
// the function that returns the compiled shader code/desciption we have
|
||||
// written in `simple_shader.glsl` and compiled with `v shader .` (`sokol-shdc`).
|
||||
shader := gfx.make_shader(voidptr(C.simple_shader_desc(gfx.query_backend())))
|
||||
|
||||
// Create a pipeline object (default render states are fine for triangle)
|
||||
mut pipeline_desc := gfx.PipelineDesc{}
|
||||
// This will zero the memory used to store the pipeline in.
|
||||
unsafe { vmemset(&pipeline_desc, 0, int(sizeof(pipeline_desc))) }
|
||||
|
||||
// Populate the essential struct fields
|
||||
pipeline_desc.shader = shader
|
||||
// The vertex shader (`simple_shader.glsl`) takes 2 inputs:
|
||||
// ```glsl
|
||||
// in vec4 position;
|
||||
// in vec4 color0;
|
||||
// ```
|
||||
// Also note the naming of the C.ATTR_* used as indices.
|
||||
// They are the prefixed versions of the names of the input variables in the shader code.
|
||||
// If they change in the shader code they will also change here.
|
||||
pipeline_desc.layout.attrs[C.ATTR_vs_position].format = .float3 // x,y,z as f32
|
||||
pipeline_desc.layout.attrs[C.ATTR_vs_color0].format = .float4 // r, g, b, a as f32
|
||||
// The .label is optional but can aid debugging sokol shader related issues
|
||||
// When things get complex - and you get tired :)
|
||||
pipeline_desc.label = c'triangle-pipeline'
|
||||
|
||||
app.shader_pipeline = gfx.make_pipeline(&pipeline_desc)
|
||||
}
|
||||
|
||||
fn cleanup(user_data voidptr) {
|
||||
gfx.shutdown()
|
||||
}
|
||||
|
||||
fn frame(user_data voidptr) {
|
||||
mut app := unsafe { &App(user_data) }
|
||||
|
||||
pass := sapp.create_default_pass(app.pass_action)
|
||||
gfx.begin_pass(&pass)
|
||||
|
||||
gfx.apply_pipeline(app.shader_pipeline)
|
||||
gfx.apply_bindings(&app.bind)
|
||||
|
||||
gfx.draw(0, 3, 1)
|
||||
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,2 @@
|
||||
sdf-sapp.c
|
||||
sdf.h
|
||||
@@ -0,0 +1,184 @@
|
||||
//------------------------------------------------------------------------------
|
||||
// Signed-distance-field raymarching shaders, see:
|
||||
// https://iquilezles.org/articles/mandelbulb
|
||||
// https://www.shadertoy.com/view/ltfSWn
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
//--- vertex shader
|
||||
@vs vs
|
||||
uniform vs_params {
|
||||
float aspect;
|
||||
float time;
|
||||
};
|
||||
in vec4 position;
|
||||
|
||||
out vec2 pos;
|
||||
out vec3 eye;
|
||||
out vec3 up;
|
||||
out vec3 right;
|
||||
out vec3 fwd;
|
||||
|
||||
// compute eye position (orbit around center)
|
||||
vec3 eye_pos(float time, vec3 center) {
|
||||
return center + vec3(sin(time * 0.05) * 3.0, sin(time * 0.1) * 2.0, cos(time * 0.05) * 3.0);
|
||||
}
|
||||
|
||||
// a lookat function
|
||||
void lookat(vec3 eye, vec3 center, vec3 up, out vec3 out_fwd, out vec3 out_right, out vec3 out_up) {
|
||||
out_fwd = normalize(center - eye);
|
||||
out_right = normalize(cross(out_fwd, up));
|
||||
out_up = cross(out_right, out_fwd);
|
||||
}
|
||||
|
||||
void main() {
|
||||
gl_Position = position;
|
||||
pos.x = position.x * aspect;
|
||||
pos.y = position.y;
|
||||
const vec3 center = vec3(0.0, 0.0, 0.0);
|
||||
const vec3 up_vec = vec3(0.0, 1.0, 0.0);
|
||||
eye = eye_pos(time * 5, center);
|
||||
lookat(eye, center, up_vec, fwd, right, up);
|
||||
}
|
||||
@end
|
||||
|
||||
//--- fragment shader
|
||||
@fs fs
|
||||
in vec2 pos;
|
||||
in vec3 eye;
|
||||
in vec3 up;
|
||||
in vec3 right;
|
||||
in vec3 fwd;
|
||||
|
||||
out vec4 frag_color;
|
||||
|
||||
float sd_sphere(vec3 p, float s) {
|
||||
return length(p) - s;
|
||||
}
|
||||
|
||||
float sd_mandelbulb(vec3 p, out vec4 res_color) {
|
||||
vec3 w = p;
|
||||
float m = dot(w,w);
|
||||
|
||||
vec4 trap = vec4(abs(w),m);
|
||||
float dz = 1.0;
|
||||
|
||||
for( int i=0; i<4; i++ ) {
|
||||
float m2 = m*m;
|
||||
float m4 = m2*m2;
|
||||
dz = 8.0*sqrt(m4*m2*m)*dz + 1.0;
|
||||
|
||||
float x = w.x; float x2 = x*x; float x4 = x2*x2;
|
||||
float y = w.y; float y2 = y*y; float y4 = y2*y2;
|
||||
float z = w.z; float z2 = z*z; float z4 = z2*z2;
|
||||
|
||||
float k3 = x2 + z2;
|
||||
float k2 = inversesqrt( k3*k3*k3*k3*k3*k3*k3 );
|
||||
float k1 = x4 + y4 + z4 - 6.0*y2*z2 - 6.0*x2*y2 + 2.0*z2*x2;
|
||||
float k4 = x2 - y2 + z2;
|
||||
|
||||
w.x = p.x + 64.0*x*y*z*(x2-z2)*k4*(x4-6.0*x2*z2+z4)*k1*k2;
|
||||
w.y = p.y + -16.0*y2*k3*k4*k4 + k1*k1;
|
||||
w.z = p.z + -8.0*y*k4*(x4*x4 - 28.0*x4*x2*z2 + 70.0*x4*z4 - 28.0*x2*z2*z4 + z4*z4)*k1*k2;
|
||||
|
||||
trap = min( trap, vec4(abs(w),m) );
|
||||
|
||||
m = dot(w,w);
|
||||
if( m > 256.0 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
res_color = vec4(m,trap.yzw);
|
||||
return 0.25*log(m)*sqrt(m)/dz;
|
||||
}
|
||||
|
||||
float d_scene(vec3 p, out vec4 res_color) {
|
||||
float d = sd_sphere(p, 1.1);
|
||||
if (d < 0.1) {
|
||||
d = sd_mandelbulb(p, res_color);
|
||||
}
|
||||
else {
|
||||
res_color = vec4(0.0);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
// surface normal estimation
|
||||
vec3 surface_normal(vec3 p, float dp) {
|
||||
const float eps = 0.001;
|
||||
const vec2 d = vec2(eps, 0);
|
||||
vec4 tra;
|
||||
float x = d_scene(p + d.xyy, tra) - dp;
|
||||
float y = d_scene(p + d.yxy, tra) - dp;
|
||||
float z = d_scene(p + d.yyx, tra) - dp;
|
||||
return normalize(vec3(x, y, z));
|
||||
}
|
||||
|
||||
vec3 calc_color(vec3 ro, vec3 rd, float t, vec4 tra) {
|
||||
const vec3 light1 = vec3( 0.577, 0.577, -0.577);
|
||||
const vec3 light2 = vec3(-0.707, 0.000, 0.707);
|
||||
|
||||
vec3 pos = ro + rd * t;
|
||||
vec3 nrm = surface_normal(pos, t);
|
||||
vec3 hal = normalize(light1 - rd);
|
||||
float occ = clamp(0.05 * log(tra.x), 0.0, 1.0);
|
||||
float fac = clamp(1.0 + dot(rd, nrm), 0.0, 1.0);
|
||||
|
||||
// sun
|
||||
float dif1 = clamp(dot( light1, nrm), 0.0, 1.0);
|
||||
float spe1 = pow(clamp(dot(nrm, hal), 0.0, 1.0), 32.0 )*dif1*(0.04+0.96*pow(clamp(1.0-dot(hal,light1),0.0,1.0),5.0));
|
||||
// bounce
|
||||
float dif2 = clamp( 0.5 + 0.5*dot( light2, nrm ), 0.0, 1.0 )*occ;
|
||||
// sky
|
||||
float dif3 = (0.7+0.3*nrm.y)*(0.2+0.8*occ);
|
||||
|
||||
vec3 col = vec3(0.01);
|
||||
col = mix(col, vec3(0.10,0.20,0.30), clamp(tra.y,0.0,1.0) );
|
||||
col = mix(col, vec3(0.02,0.10,0.30), clamp(tra.z*tra.z,0.0,1.0) );
|
||||
col = mix(col, vec3(0.30,0.10,0.02), clamp(pow(tra.w,6.0),0.0,1.0) );
|
||||
|
||||
vec3 lin = vec3(0.0);
|
||||
lin += 7.0*vec3(1.50,1.10,0.70)*dif1;
|
||||
lin += 4.0*vec3(0.25,0.20,0.15)*dif2;
|
||||
lin += 1.5*vec3(0.10,0.20,0.30)*dif3;
|
||||
lin += 2.5*vec3(0.35,0.30,0.25)*(0.05+0.95*occ); // ambient
|
||||
lin += 4.0*fac*occ; // fake SSS
|
||||
col *= lin;
|
||||
col = pow( col, vec3(0.7,0.9,1.0)); // fake SSS
|
||||
col += spe1*15.0;
|
||||
|
||||
// gamma
|
||||
col = sqrt(col);
|
||||
|
||||
return col;
|
||||
}
|
||||
|
||||
void main() {
|
||||
const float epsilon = 0.001;
|
||||
const float focal_length = 1.8;
|
||||
|
||||
vec3 ray_origin = eye + fwd * focal_length + right * pos.x + up * pos.y;
|
||||
vec3 ray_direction = normalize(ray_origin - eye);
|
||||
|
||||
vec4 tra;
|
||||
vec4 color = vec4(0.10,0.20,0.30,1.0);
|
||||
float t = 0.0;
|
||||
for (int i = 0; i < 96; i++) {
|
||||
vec3 p = ray_origin + ray_direction * t;
|
||||
float d = d_scene(p, tra);
|
||||
if (d < epsilon) {
|
||||
color.xyz = calc_color(p, ray_direction, d, tra);
|
||||
break;
|
||||
}
|
||||
else {
|
||||
color.xyz += vec3(0.003, 0.001, 0.0) * i;
|
||||
}
|
||||
if (t > 3) {
|
||||
break;
|
||||
}
|
||||
t += d;
|
||||
}
|
||||
frag_color = color;
|
||||
}
|
||||
@end
|
||||
|
||||
@program sdf vs fs
|
||||
@@ -0,0 +1,70 @@
|
||||
// A Signed Distance Field rendering demo, ported from https://github.com/floooh/sokol-samples/blob/master/sapp/sdf-sapp.c
|
||||
// which in turn is based on https://iquilezles.org/articles/mandelbulb/ and https://www.shadertoy.com/view/ltfSWn
|
||||
// vtest build: misc-tooling // needs .h files that are produced by `v shader`
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
|
||||
#include "@VMODROOT/sdf.h" # It should be generated with `v shader .`
|
||||
|
||||
fn C.sdf_shader_desc(gfx.Backend) &gfx.ShaderDesc
|
||||
|
||||
@[packed]
|
||||
struct C.vs_params_t {
|
||||
mut:
|
||||
aspect f32
|
||||
time f32
|
||||
}
|
||||
|
||||
struct State {
|
||||
mut:
|
||||
pip gfx.Pipeline
|
||||
bind gfx.Bindings
|
||||
paction gfx.PassAction
|
||||
params C.vs_params_t
|
||||
}
|
||||
|
||||
fn init(mut state State) {
|
||||
gfx.setup(sapp.create_desc())
|
||||
|
||||
fsq_verts := [f32(-1.0), -3.0, 3.0, 1.0, -1.0, 1.0]!
|
||||
state.bind.vertex_buffers[0] = gfx.make_buffer(gfx.BufferDesc{
|
||||
label: c'fsq vertices'
|
||||
data: gfx.Range{&fsq_verts[0], sizeof(fsq_verts)}
|
||||
})
|
||||
|
||||
mut pipeline := gfx.PipelineDesc{}
|
||||
pipeline.layout.attrs[C.ATTR_vs_position].format = .float2
|
||||
pipeline.shader = gfx.make_shader(voidptr(C.sdf_shader_desc(gfx.query_backend())))
|
||||
state.pip = gfx.make_pipeline(&pipeline)
|
||||
|
||||
// No need to clear the window, since the shader will overwrite the whole framebuffer
|
||||
state.paction.colors[0].load_action = .dontcare
|
||||
}
|
||||
|
||||
fn frame(mut state State) {
|
||||
w, h := sapp.width(), sapp.height()
|
||||
state.params.time += f32(sapp.frame_duration())
|
||||
state.params.aspect = f32(w) / f32(h)
|
||||
gfx.begin_pass(sapp.create_default_pass(state.paction))
|
||||
gfx.apply_pipeline(state.pip)
|
||||
gfx.apply_bindings(state.bind)
|
||||
gfx.apply_uniforms(.vs, C.SLOT_vs_params, gfx.Range{&state.params, sizeof(state.params)})
|
||||
gfx.draw(0, 3, 1)
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
sapp.run(sapp.Desc{
|
||||
window_title: c'SDF Rendering'
|
||||
width: 512
|
||||
height: 512
|
||||
frame_userdata_cb: frame
|
||||
init_userdata_cb: init
|
||||
cleanup_cb: gfx.shutdown
|
||||
icon: sapp.IconDesc{
|
||||
sokol_default: true
|
||||
}
|
||||
user_data: &State{}
|
||||
})
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,25 @@
|
||||
// This example shows how to clear your window on each frame, with a different color, using a Sokol pass.
|
||||
// It is ported from https://github.com/floooh/sokol-samples/blob/master/sapp/clear-sapp.c .
|
||||
import sokol.gfx
|
||||
import sokol.sapp
|
||||
|
||||
fn frame(mut action gfx.PassAction) {
|
||||
g := f32(action.colors[0].clear_value.g + 0.01)
|
||||
action.colors[0].clear_value.g = if g > 1.0 { 0 } else { g }
|
||||
gfx.begin_pass(sapp.create_default_pass(action))
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
action := gfx.create_clear_pass_action(1.0, 0, 0, 1.0)
|
||||
sapp.run(
|
||||
window_title: c'Clear (sokol app)'
|
||||
width: 400
|
||||
height: 300
|
||||
init_cb: || gfx.setup(sapp.create_desc())
|
||||
cleanup_cb: || gfx.shutdown()
|
||||
frame_userdata_cb: frame
|
||||
user_data: &action
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// vtest build: !solaris
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
import sokol.sgl
|
||||
|
||||
struct AppState {
|
||||
pass_action gfx.PassAction
|
||||
}
|
||||
|
||||
fn main() {
|
||||
state := &AppState{
|
||||
pass_action: gfx.create_clear_pass_action(0.1, 0.1, 0.1, 1.0)
|
||||
}
|
||||
title := 'Sokol Drawing Template'
|
||||
desc := sapp.Desc{
|
||||
width: 640
|
||||
height: 480
|
||||
user_data: state
|
||||
init_userdata_cb: init
|
||||
frame_userdata_cb: frame
|
||||
window_title: &char(title.str)
|
||||
}
|
||||
sapp.run(&desc)
|
||||
}
|
||||
|
||||
fn init(_user_data voidptr) {
|
||||
desc := sapp.create_desc() // gfx.Desc{
|
||||
gfx.setup(&desc)
|
||||
sgl_desc := sgl.Desc{}
|
||||
sgl.setup(&sgl_desc)
|
||||
}
|
||||
|
||||
fn frame(state &AppState) {
|
||||
// println('frame')
|
||||
draw()
|
||||
pass := sapp.create_default_pass(state.pass_action)
|
||||
gfx.begin_pass(&pass)
|
||||
sgl.draw()
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
|
||||
fn draw() {
|
||||
// first, reset and setup ortho projection
|
||||
sgl.defaults()
|
||||
sgl.matrix_mode_projection()
|
||||
sgl.ortho(0.0, f32(sapp.width()), f32(sapp.height()), 0.0, -1.0, 1.0)
|
||||
sgl.c4b(255, 0, 0, 128)
|
||||
draw_hollow_rect(220, 140, 200, 200)
|
||||
sgl.c4b(25, 150, 255, 128)
|
||||
draw_filled_rect(270, 190, 100, 100)
|
||||
// line(0, 0, 500, 500)
|
||||
}
|
||||
|
||||
fn draw_hollow_rect(x f32, y f32, w f32, h f32) {
|
||||
sgl.begin_line_strip()
|
||||
sgl.v2f(x, y)
|
||||
sgl.v2f(x + w, y)
|
||||
sgl.v2f(x + w, y + h)
|
||||
sgl.v2f(x, y + h)
|
||||
sgl.v2f(x, y)
|
||||
sgl.end()
|
||||
}
|
||||
|
||||
fn draw_filled_rect(x f32, y f32, w f32, h f32) {
|
||||
sgl.begin_quads()
|
||||
sgl.v2f(x, y)
|
||||
sgl.v2f(x + w, y)
|
||||
sgl.v2f(x + w, y + h)
|
||||
sgl.v2f(x, y + h)
|
||||
sgl.end()
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// vtest build: !solaris
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
import sokol.sgl
|
||||
import fontstash
|
||||
import sokol.sfons
|
||||
import os
|
||||
|
||||
struct AppState {
|
||||
mut:
|
||||
pass_action gfx.PassAction
|
||||
font_context &fontstash.Context
|
||||
font_normal int
|
||||
}
|
||||
|
||||
fn main() {
|
||||
state := &AppState{
|
||||
pass_action: gfx.create_clear_pass_action(0.3, 0.3, 0.32, 1.0)
|
||||
font_context: unsafe { nil } // &fontstash.Context(0)
|
||||
}
|
||||
title := 'V Metal/GL Text Rendering'
|
||||
desc := sapp.Desc{
|
||||
user_data: state
|
||||
init_userdata_cb: init
|
||||
frame_userdata_cb: frame
|
||||
window_title: &char(title.str)
|
||||
}
|
||||
sapp.run(&desc)
|
||||
}
|
||||
|
||||
fn init(mut state AppState) {
|
||||
desc := sapp.create_desc()
|
||||
gfx.setup(&desc)
|
||||
s := &sgl.Desc{}
|
||||
sgl.setup(s)
|
||||
state.font_context = sfons.create(512, 512, 1)
|
||||
// or use DroidSerif-Regular.ttf
|
||||
if bytes := os.read_bytes(os.resource_abs_path(os.join_path('..', 'assets', 'fonts',
|
||||
'RobotoMono-Regular.ttf')))
|
||||
{
|
||||
println('loaded font: ${bytes.len}')
|
||||
state.font_normal = state.font_context.add_font_mem('sans', bytes.clone(), true)
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(mut state AppState) {
|
||||
state.render_font()
|
||||
pass := sapp.create_default_pass(state.pass_action)
|
||||
gfx.begin_pass(&pass)
|
||||
sgl.draw()
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
|
||||
fn (state &AppState) render_font() {
|
||||
mut sx := f32(0.0)
|
||||
mut sy := f32(0.0)
|
||||
mut dx := f32(0.0)
|
||||
mut dy := f32(0.0)
|
||||
lh := f32(0.0)
|
||||
white := sfons.rgba(255, 255, 255, 255)
|
||||
black := sfons.rgba(0, 0, 0, 255)
|
||||
brown := sfons.rgba(192, 128, 0, 128)
|
||||
blue := sfons.rgba(0, 192, 255, 255)
|
||||
|
||||
font_context := state.font_context
|
||||
font_context.clear_state()
|
||||
sgl.defaults()
|
||||
sgl.matrix_mode_projection()
|
||||
sgl.ortho(0.0, f32(sapp.width()), f32(sapp.height()), 0.0, -1.0, 1.0)
|
||||
sx = 0
|
||||
sy = 50
|
||||
dx = sx
|
||||
dy = sy
|
||||
font_context.set_font(state.font_normal)
|
||||
font_context.set_size(100.0)
|
||||
ascender := f32(0.0)
|
||||
descender := f32(0.0)
|
||||
font_context.vert_metrics(&ascender, &descender, &lh)
|
||||
dx = sx
|
||||
dy += lh
|
||||
font_context.set_color(white)
|
||||
dx = font_context.draw_text(dx, dy, 'The quick ')
|
||||
font_context.set_font(state.font_normal)
|
||||
font_context.set_size(48.0)
|
||||
font_context.set_color(brown)
|
||||
dx = font_context.draw_text(dx, dy, 'brown ')
|
||||
font_context.set_font(state.font_normal)
|
||||
font_context.set_size(24.0)
|
||||
font_context.set_color(white)
|
||||
dx = font_context.draw_text(dx, dy, 'fox ')
|
||||
dx = sx
|
||||
dy += lh * 1.2
|
||||
font_context.set_size(20.0)
|
||||
font_context.set_font(state.font_normal)
|
||||
font_context.set_color(blue)
|
||||
font_context.draw_text(dx, dy,
|
||||
'Now is the time for all good men to come to the aid of the party.')
|
||||
dx = 300
|
||||
dy = 350
|
||||
font_context.set_alignment(.left | .baseline)
|
||||
font_context.set_size(60.0)
|
||||
font_context.set_font(state.font_normal)
|
||||
font_context.set_color(white)
|
||||
font_context.set_spacing(5.0)
|
||||
font_context.set_blur(6.0)
|
||||
font_context.draw_text(dx, dy, 'Blurry...')
|
||||
dx = 300
|
||||
dy += 50.0
|
||||
font_context.set_size(28.0)
|
||||
font_context.set_font(state.font_normal)
|
||||
font_context.set_color(white)
|
||||
font_context.set_spacing(0.0)
|
||||
font_context.set_blur(3.0)
|
||||
font_context.draw_text(dx, dy + 2, 'DROP SHADOW')
|
||||
font_context.set_color(black)
|
||||
font_context.set_blur(0)
|
||||
font_context.draw_text(dx, dy, 'DROP SHADOW')
|
||||
font_context.set_size(18.0)
|
||||
font_context.set_font(state.font_normal)
|
||||
font_context.set_color(white)
|
||||
dx = 50
|
||||
dy = 350
|
||||
line(f32(dx - 10), f32(dy), f32(dx + 250), f32(dy))
|
||||
font_context.set_alignment(.left | .top)
|
||||
dx = font_context.draw_text(dx, dy, 'Top')
|
||||
dx += 10
|
||||
font_context.set_alignment(.left | .middle)
|
||||
dx = font_context.draw_text(dx, dy, 'Middle')
|
||||
dx += 10
|
||||
font_context.set_alignment(.left | .baseline)
|
||||
dx = font_context.draw_text(dx, dy, 'Baseline')
|
||||
dx += 10
|
||||
font_context.set_alignment(.left | .bottom)
|
||||
font_context.draw_text(dx, dy, 'Bottom')
|
||||
dx = 150
|
||||
dy = 400
|
||||
line(f32(dx), f32(dy - 30), f32(dx), f32(dy + 80.0))
|
||||
font_context.set_alignment(.left | .baseline)
|
||||
font_context.draw_text(dx, dy, 'Left')
|
||||
dy += 30
|
||||
font_context.set_alignment(.center | .baseline)
|
||||
font_context.draw_text(dx, dy, 'Center')
|
||||
dy += 30
|
||||
font_context.set_alignment(.right | .baseline)
|
||||
font_context.draw_text(dx, dy, 'Right')
|
||||
sfons.flush(font_context)
|
||||
}
|
||||
|
||||
fn line(sx f32, sy f32, ex f32, ey f32) {
|
||||
sgl.begin_lines()
|
||||
sgl.c4b(255, 255, 0, 128)
|
||||
sgl.v2f(sx, sy)
|
||||
sgl.v2f(ex, ey)
|
||||
sgl.end()
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
import sokol.sgl
|
||||
import fontstash
|
||||
import sokol.sfons
|
||||
import os
|
||||
|
||||
const text = '
|
||||
Once upon a midnight dreary, while I pondered, weak and weary,
|
||||
Over many a quaint and curious volume of forgotten lore—
|
||||
While I nodded, nearly napping, suddenly there came a tapping,
|
||||
As of some one gently rapping, rapping at my chamber door.
|
||||
“’Tis some visitor,” I muttered, “tapping at my chamber door—
|
||||
Only this and nothing more.”
|
||||
|
||||
Ah, distinctly I remember it was in the bleak December;
|
||||
And each separate dying ember wrought its ghost upon the floor.
|
||||
Eagerly I wished the morrow;—vainly I had sought to borrow
|
||||
From my books surcease of sorrow—sorrow for the lost Lenore—
|
||||
For the rare and radiant maiden whom the angels name Lenore—
|
||||
Nameless here for evermore.
|
||||
|
||||
And the silken, sad, uncertain rustling of each purple curtain
|
||||
Thrilled me—filled me with fantastic terrors never felt before;
|
||||
So that now, to still the beating of my heart, I stood repeating
|
||||
“’Tis some visitor entreating entrance at my chamber door—
|
||||
Some late visitor entreating entrance at my chamber door;—
|
||||
This it is and nothing more.”
|
||||
|
||||
Presently my soul grew stronger; hesitating then no longer,
|
||||
“Sir,” said I, “or Madam, truly your forgiveness I implore;
|
||||
But the fact is I was napping, and so gently you came rapping,
|
||||
And so faintly you came tapping, tapping at my chamber door,
|
||||
That I scarce was sure I heard you”—here I opened wide the door;—
|
||||
Darkness there and nothing more.
|
||||
|
||||
Deep into that darkness peering, long I stood there wondering, fearing,
|
||||
Doubting, dreaming dreams no mortal ever dared to dream before;
|
||||
But the silence was unbroken, and the stillness gave no token,
|
||||
And the only word there spoken was the whispered word, “Lenore?”
|
||||
This I whispered, and an echo murmured back the word, “Lenore!”—
|
||||
Merely this and nothing more.
|
||||
|
||||
Back into the chamber turning, all my soul within me burning,
|
||||
Soon again I heard a tapping somewhat louder than before.
|
||||
“Surely,” said I, “surely that is something at my window lattice;
|
||||
Let me see, then, what thereat is, and this mystery explore—
|
||||
Let my heart be still a moment and this mystery explore;—
|
||||
’Tis the wind and nothing more!”
|
||||
'
|
||||
|
||||
const lines = text.split('\n')
|
||||
|
||||
struct AppState {
|
||||
mut:
|
||||
pass_action gfx.PassAction
|
||||
fons &fontstash.Context = unsafe { nil }
|
||||
font_normal int
|
||||
inited bool
|
||||
}
|
||||
|
||||
fn main() {
|
||||
mut color_action := gfx.ColorAttachmentAction{
|
||||
load_action: .clear
|
||||
clear_value: gfx.Color{
|
||||
r: 1.0
|
||||
g: 1.0
|
||||
b: 1.0
|
||||
a: 1.0
|
||||
}
|
||||
}
|
||||
mut pass_action := gfx.PassAction{}
|
||||
pass_action.colors[0] = color_action
|
||||
state := &AppState{
|
||||
pass_action: pass_action
|
||||
fons: unsafe { nil } // &fontstash.Context(0)
|
||||
}
|
||||
title := 'V Metal/GL Text Rendering'
|
||||
desc := sapp.Desc{
|
||||
user_data: state
|
||||
init_userdata_cb: init
|
||||
frame_userdata_cb: frame
|
||||
window_title: &char(title.str)
|
||||
width: 600
|
||||
height: 700
|
||||
high_dpi: true
|
||||
}
|
||||
sapp.run(&desc)
|
||||
}
|
||||
|
||||
fn init(mut state AppState) {
|
||||
desc := sapp.create_desc()
|
||||
gfx.setup(&desc)
|
||||
s := &sgl.Desc{}
|
||||
sgl.setup(s)
|
||||
state.fons = sfons.create(512, 512, 1)
|
||||
// or use DroidSerif-Regular.ttf
|
||||
if bytes := os.read_bytes(os.resource_abs_path(os.join_path('..', 'assets', 'fonts',
|
||||
'RobotoMono-Regular.ttf')))
|
||||
{
|
||||
println('loaded font: ${bytes.len}')
|
||||
state.font_normal = state.fons.add_font_mem('sans', bytes.clone(), true)
|
||||
}
|
||||
}
|
||||
|
||||
fn frame(mut state AppState) {
|
||||
state.render_font()
|
||||
pass := sapp.create_default_pass(state.pass_action)
|
||||
gfx.begin_pass(&pass)
|
||||
sgl.draw()
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
}
|
||||
|
||||
const black = sfons.rgba(0, 0, 0, 255)
|
||||
|
||||
fn (mut state AppState) render_font() {
|
||||
lh := 30
|
||||
mut dy := lh
|
||||
mut fons := state.fons
|
||||
if !state.inited {
|
||||
fons.clear_state()
|
||||
sgl.defaults()
|
||||
sgl.matrix_mode_projection()
|
||||
sgl.ortho(0.0, f32(sapp.width()), f32(sapp.height()), 0.0, -1.0, 1.0)
|
||||
fons.set_font(state.font_normal)
|
||||
fons.set_size(100.0)
|
||||
fons.set_color(black)
|
||||
fons.set_font(state.font_normal)
|
||||
fons.set_size(35.0)
|
||||
state.inited = true
|
||||
}
|
||||
|
||||
for line in lines {
|
||||
fons.draw_text(40, dy, line)
|
||||
dy += lh
|
||||
}
|
||||
sfons.flush(fons)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Lars Pontoppidan
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright(C) 2019 Lars Pontoppidan. All rights reserved.
|
||||
// Use of this source code is governed by an MIT license file distributed with this software package
|
||||
module particle
|
||||
|
||||
// * Color
|
||||
pub struct Color {
|
||||
mut:
|
||||
r u8
|
||||
g u8
|
||||
b u8
|
||||
a u8
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright(C) 2019 Lars Pontoppidan. All rights reserved.
|
||||
// Use of this source code is governed by an MIT license file distributed with this software package
|
||||
module particle
|
||||
|
||||
import math.vec
|
||||
import sokol.sgl
|
||||
|
||||
const default_life_time = 1000
|
||||
const default_v_color = Color{93, 136, 193, 255}
|
||||
|
||||
// * Module public
|
||||
pub fn new(location vec.Vec2[f64]) &Particle {
|
||||
p := &Particle{
|
||||
location: location
|
||||
velocity: vec.Vec2[f64]{0, 0}
|
||||
acceleration: vec.Vec2[f64]{0, 0}
|
||||
color: default_v_color
|
||||
life_time: default_life_time
|
||||
life_time_init: default_life_time
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
fn remap(v f64, min f64, max f64, new_min f64, new_max f64) f64 {
|
||||
return (((v - min) * (new_max - new_min)) / (max - min)) + new_min
|
||||
}
|
||||
|
||||
// Particle
|
||||
pub struct Particle {
|
||||
pub mut:
|
||||
location vec.Vec2[f64]
|
||||
velocity vec.Vec2[f64]
|
||||
acceleration vec.Vec2[f64]
|
||||
color Color
|
||||
life_time f64
|
||||
life_time_init f64
|
||||
}
|
||||
|
||||
pub fn (mut p Particle) update(dt f64) {
|
||||
mut acc := p.acceleration
|
||||
acc.multiply_scalar(dt)
|
||||
p.velocity = p.velocity.add(acc)
|
||||
p.location = p.location.add(p.velocity)
|
||||
lt := p.life_time - (1000 * dt)
|
||||
if lt > 0 {
|
||||
p.life_time = lt
|
||||
p.color.r = p.color.r - 1 // u8(remap(p.life_time,0.0,p.life_time_init,0,p.color.r))
|
||||
p.color.g = p.color.g - 1 // u8(remap(p.life_time,0.0,p.life_time_init,0,p.color.g))
|
||||
p.color.b = p.color.b - 1 // u8(remap(p.life_time,0.0,p.life_time_init,0,p.color.b))
|
||||
p.color.a = u8(int(remap(p.life_time, 0.0, p.life_time_init, 0, 255))) - 10
|
||||
} else {
|
||||
p.life_time = 0
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (p Particle) is_dead() bool {
|
||||
return p.life_time <= 0.0
|
||||
}
|
||||
|
||||
pub fn (p Particle) draw() {
|
||||
l := p.location
|
||||
sgl.c4b(p.color.r, p.color.g, p.color.b, p.color.a)
|
||||
lx := f32(l.x)
|
||||
ly := f32(l.y)
|
||||
sgl.v2f(lx, ly)
|
||||
sgl.v2f(lx + 2, ly)
|
||||
sgl.v2f(lx + 2, ly + 2)
|
||||
sgl.v2f(lx, ly + 2)
|
||||
}
|
||||
|
||||
pub fn (mut p Particle) reset() {
|
||||
p.location.zero()
|
||||
p.acceleration.zero()
|
||||
p.velocity.zero()
|
||||
// p.color = Color{93, 136, 193, 255}
|
||||
p.color = default_v_color
|
||||
p.life_time = default_life_time
|
||||
p.life_time_init = p.life_time
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// Copyright(C) 2019 Lars Pontoppidan. All rights reserved.
|
||||
// Use of this source code is governed by an MIT license file distributed with this software package
|
||||
module particle
|
||||
|
||||
import math.vec
|
||||
import rand
|
||||
import sokol.sgl
|
||||
|
||||
pub struct SystemConfig {
|
||||
pub:
|
||||
pool int
|
||||
}
|
||||
|
||||
pub struct System {
|
||||
pub:
|
||||
width int
|
||||
height int
|
||||
mut:
|
||||
pool []&Particle
|
||||
bin []&Particle
|
||||
}
|
||||
|
||||
pub fn (mut s System) init(sc SystemConfig) {
|
||||
unsafe { s.pool.flags.set(.noslices | .noshrink) }
|
||||
unsafe { s.bin.flags.set(.noslices | .noshrink) }
|
||||
for i := 0; i < sc.pool; i++ {
|
||||
p := new(vec.Vec2[f64]{f32(s.width) * 0.5, f32(s.height) * 0.5})
|
||||
s.bin << p
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (mut s System) update(dt f64) {
|
||||
mut p := &Particle(unsafe { nil })
|
||||
mut moved := 0
|
||||
for i := 0; i < s.pool.len; i++ {
|
||||
p = s.pool[i]
|
||||
p.update(dt)
|
||||
if p.is_dead() {
|
||||
s.bin << p
|
||||
s.pool.delete(i)
|
||||
moved++
|
||||
}
|
||||
}
|
||||
if moved != 0 {
|
||||
$if trace_moves_spool_to_sbin ? {
|
||||
eprintln('${moved:4} particles s.pool -> s.bin')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (s System) draw() {
|
||||
sgl.begin_quads()
|
||||
for p in s.pool {
|
||||
p.draw()
|
||||
}
|
||||
sgl.end()
|
||||
}
|
||||
|
||||
pub fn (mut s System) reset() {
|
||||
for i in 0 .. s.pool.len {
|
||||
mut p := s.pool[i]
|
||||
p.reset()
|
||||
p.life_time = 0
|
||||
}
|
||||
for i in 0 .. s.bin.len {
|
||||
mut p := s.pool[i]
|
||||
p.reset()
|
||||
p.life_time = 0
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (mut s System) explode(x f32, y f32) {
|
||||
mut reserve := 500
|
||||
center := vec.Vec2[f64]{x, y}
|
||||
mut p := &Particle(unsafe { nil })
|
||||
mut moved := 0
|
||||
for i := 0; i < s.bin.len && reserve > 0; i++ {
|
||||
p = s.bin[i]
|
||||
p.reset()
|
||||
p.location.from(center)
|
||||
p.acceleration = vec.Vec2[f64]{rand.f32_in_range(-0.5, 0.5) or { -0.5 }, rand.f32_in_range(-0.5, 0.5) or {
|
||||
-0.5
|
||||
}}
|
||||
p.velocity = vec.Vec2[f64]{rand.f32_in_range(-0.5, 0.5) or { -0.5 }, rand.f32_in_range(-0.5, 0.5) or {
|
||||
-0.5
|
||||
}}
|
||||
p.life_time = rand.f64_in_range(500, 2000) or { 500 }
|
||||
s.pool << p
|
||||
s.bin.delete(i)
|
||||
moved++
|
||||
reserve--
|
||||
}
|
||||
if moved != 0 {
|
||||
$if trace_moves_sbin_to_spool ? {
|
||||
eprintln('${moved:4} particles s.bin -> s.pool')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (mut s System) free() {
|
||||
for p in s.pool {
|
||||
if unsafe { p == 0 } {
|
||||
print(ptr_str(p) + ' ouch')
|
||||
continue
|
||||
}
|
||||
unsafe { free(p) }
|
||||
}
|
||||
s.pool.clear()
|
||||
for p in s.bin {
|
||||
if unsafe { p == 0 } {
|
||||
print(ptr_str(p) + ' ouch')
|
||||
continue
|
||||
}
|
||||
unsafe {
|
||||
// println('Freeing from bin')
|
||||
free(p)
|
||||
}
|
||||
}
|
||||
s.bin.clear()
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
// Copyright(C) 2019 Lars Pontoppidan. All rights reserved.
|
||||
// Use of this source code is governed by an MIT license file distributed with this software package
|
||||
module main
|
||||
|
||||
import time
|
||||
import sokol.sapp
|
||||
import sokol.gfx
|
||||
import sokol.sgl
|
||||
import particle
|
||||
|
||||
fn main() {
|
||||
mut app := &App{
|
||||
width: 800
|
||||
height: 400
|
||||
pass_action: gfx.create_clear_pass_action(0.1, 0.1, 0.1, 1.0)
|
||||
}
|
||||
app.init()
|
||||
app.run()
|
||||
}
|
||||
|
||||
struct App {
|
||||
pass_action gfx.PassAction
|
||||
mut:
|
||||
width int
|
||||
height int
|
||||
frame i64
|
||||
last i64
|
||||
ps particle.System
|
||||
alpha_pip sgl.Pipeline
|
||||
}
|
||||
|
||||
fn (mut a App) init() {
|
||||
a.frame = 0
|
||||
a.last = time.ticks()
|
||||
a.ps = particle.System{
|
||||
width: a.width
|
||||
height: a.height
|
||||
}
|
||||
a.ps.init(particle.SystemConfig{
|
||||
pool: 20000
|
||||
})
|
||||
}
|
||||
|
||||
fn (mut a App) cleanup() {
|
||||
unsafe {
|
||||
a.ps.free()
|
||||
}
|
||||
}
|
||||
|
||||
fn (mut a App) run() {
|
||||
title := 'V Particle Example'
|
||||
desc := sapp.Desc{
|
||||
width: a.width
|
||||
height: a.height
|
||||
user_data: a
|
||||
init_userdata_cb: init
|
||||
frame_userdata_cb: frame
|
||||
event_userdata_cb: event
|
||||
window_title: &char(title.str)
|
||||
cleanup_userdata_cb: cleanup
|
||||
}
|
||||
sapp.run(&desc)
|
||||
}
|
||||
|
||||
fn (a App) draw() {
|
||||
sgl.load_pipeline(a.alpha_pip)
|
||||
a.ps.draw()
|
||||
}
|
||||
|
||||
fn init(mut app App) {
|
||||
desc := sapp.create_desc()
|
||||
gfx.setup(&desc)
|
||||
sgl_desc := sgl.Desc{
|
||||
max_vertices: 50 * 65536
|
||||
}
|
||||
sgl.setup(&sgl_desc)
|
||||
mut pipdesc := gfx.PipelineDesc{}
|
||||
unsafe { vmemset(&pipdesc, 0, int(sizeof(pipdesc))) }
|
||||
|
||||
color_state := gfx.ColorTargetState{
|
||||
blend: gfx.BlendState{
|
||||
enabled: true
|
||||
src_factor_rgb: .src_alpha
|
||||
dst_factor_rgb: .one_minus_src_alpha
|
||||
}
|
||||
}
|
||||
pipdesc.colors[0] = color_state
|
||||
|
||||
app.alpha_pip = sgl.make_pipeline(&pipdesc)
|
||||
}
|
||||
|
||||
fn cleanup(mut app App) {
|
||||
app.cleanup()
|
||||
gfx.shutdown()
|
||||
}
|
||||
|
||||
fn frame(mut app App) {
|
||||
app.width = sapp.width()
|
||||
app.height = sapp.height()
|
||||
t := time.ticks()
|
||||
dt := f64(t - app.last) / 1000.0
|
||||
app.ps.update(dt)
|
||||
draw(app)
|
||||
pass := sapp.create_default_pass(app.pass_action)
|
||||
gfx.begin_pass(&pass)
|
||||
sgl.default_pipeline()
|
||||
sgl.draw()
|
||||
gfx.end_pass()
|
||||
gfx.commit()
|
||||
app.frame++
|
||||
app.last = t
|
||||
}
|
||||
|
||||
fn event(ev &sapp.Event, mut app App) {
|
||||
if ev.type == .mouse_move {
|
||||
app.ps.explode(ev.mouse_x, ev.mouse_y)
|
||||
}
|
||||
if ev.type == .mouse_up || ev.type == .mouse_down {
|
||||
if ev.mouse_button == .left {
|
||||
is_pressed := ev.type == .mouse_down
|
||||
if is_pressed {
|
||||
app.ps.explode(ev.mouse_x, ev.mouse_y)
|
||||
}
|
||||
}
|
||||
}
|
||||
if ev.type == .key_up || ev.type == .key_down {
|
||||
if ev.key_code == .r {
|
||||
is_pressed := ev.type == .key_down
|
||||
if is_pressed {
|
||||
app.ps.reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
if ev.type == .touches_began || ev.type == .touches_moved {
|
||||
if ev.num_touches > 0 {
|
||||
touch_point := ev.touches[0]
|
||||
app.ps.explode(touch_point.pos_x, touch_point.pos_y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw(a &App) {
|
||||
sgl.defaults()
|
||||
sgl.matrix_mode_projection()
|
||||
sgl.ortho(0, f32(sapp.width()), f32(sapp.height()), 0.0, -1.0, 1.0)
|
||||
sgl.push_matrix()
|
||||
a.draw()
|
||||
sgl.pop_matrix()
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// vtest build: !openbsd
|
||||
import gg
|
||||
import sokol.audio
|
||||
|
||||
struct AppState {
|
||||
mut:
|
||||
frame_0 int // offset of the current audio frames, relative to the start of the music
|
||||
frames [2048]f32 // a copy of the last rendered audio frames
|
||||
gg &gg.Context = unsafe { nil } // used for drawing
|
||||
}
|
||||
|
||||
fn my_audio_stream_callback(mut soundbuffer &f32, num_frames int, num_channels int, mut acontext AppState) {
|
||||
for frame := 0; frame < num_frames; frame++ {
|
||||
t := int(f32(acontext.frame_0 + frame) * 0.245)
|
||||
// "Techno" by Gabriel Miceli
|
||||
y := (t * (((t / 10 | 0) ^ ((t / 10 | 0) - 1280)) % 11) / 2 & 127) +
|
||||
(t * (((t / 640 | 0) ^ ((t / 640 | 0) - 2)) % 13) / 2 & 127)
|
||||
for ch := 0; ch < num_channels; ch++ {
|
||||
idx := frame * num_channels + ch
|
||||
a := f32(y - 127) / 255.0
|
||||
soundbuffer[idx] = a
|
||||
acontext.frames[idx & 2047] = a
|
||||
}
|
||||
}
|
||||
acontext.frame_0 += num_frames
|
||||
}
|
||||
|
||||
fn graphics_frame(mut state AppState) {
|
||||
ws := gg.window_size()
|
||||
center_y := f32(ws.height / 2)
|
||||
state.gg.begin()
|
||||
for x in 0 .. 1024 {
|
||||
vx := ws.width * f32(x) / 1024.0
|
||||
vy := center_y * 3.0 / 4.0 * (state.frames[2 * x] + state.frames[2 * x + 1])
|
||||
color := gg.Color{f(state, x), f(state, x + 300), f(state, x + 700), 255}
|
||||
state.gg.draw_line(vx, center_y, vx, center_y + vy, color)
|
||||
}
|
||||
state.gg.end()
|
||||
}
|
||||
|
||||
fn f(state &AppState, idx int) u8 {
|
||||
return u8(127 + state.frames[(int(state.gg.frame) + idx) & 2047] * 128)
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println('Based on the ByteBeat formula from: https://www.youtube.com/watch?v=V4GfkFbDojc \n "Techno" by Gabriel Miceli')
|
||||
mut state := &AppState{}
|
||||
audio.setup(stream_userdata_cb: my_audio_stream_callback, user_data: state)
|
||||
defer { audio.shutdown() }
|
||||
state.gg = gg.new_context(
|
||||
bg_color: gg.Color{50, 50, 50, 255}
|
||||
width: 800
|
||||
height: 600
|
||||
window_title: 'ByteBeat Music'
|
||||
frame_fn: graphics_frame
|
||||
user_data: state
|
||||
)
|
||||
state.gg.run()
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// vtest build: !openbsd
|
||||
import os
|
||||
import time
|
||||
import sokol.audio
|
||||
import encoding.vorbis
|
||||
|
||||
fn main() {
|
||||
unbuffer_stdout()
|
||||
if os.args.len < 2 {
|
||||
eprintln('Usage: ogg_player file.ogg ...')
|
||||
play_sounds([os.resource_abs_path('pickup.ogg')])!
|
||||
exit(1)
|
||||
}
|
||||
play_sounds(os.args[1..])!
|
||||
}
|
||||
|
||||
fn play_sounds(files []string) ! {
|
||||
mut player := Player{
|
||||
decoder: unsafe { nil }
|
||||
}
|
||||
player.init()
|
||||
for f in files {
|
||||
if !os.exists(f) || os.is_dir(f) {
|
||||
eprintln('skipping "${f}" (does not exist)')
|
||||
continue
|
||||
}
|
||||
fext := os.file_ext(f).to_lower()
|
||||
if fext != '.ogg' {
|
||||
eprintln('skipping "${f}" (not an .ogg file)')
|
||||
continue
|
||||
}
|
||||
player.play_ogg_file(f)!
|
||||
}
|
||||
player.stop()
|
||||
}
|
||||
|
||||
struct Player {
|
||||
mut:
|
||||
channels int
|
||||
sample_rate int
|
||||
pos int
|
||||
finished bool
|
||||
push_slack_ms int = 5
|
||||
stream_rate u32
|
||||
stream_channels int
|
||||
stream_len_samples u32
|
||||
stream_len_seconds f32
|
||||
xerror vorbis.VorbisErrorCode
|
||||
allocator C.stb_vorbis_alloc = C.stb_vorbis_alloc{
|
||||
alloc_buffer: 0
|
||||
alloc_buffer_length_in_bytes: 0
|
||||
}
|
||||
decoder &C.stb_vorbis // TODO: cgen error with -cstrict -gcc, when this is = unsafe { nil } here
|
||||
}
|
||||
|
||||
fn (mut p Player) init() {
|
||||
audio.setup()
|
||||
p.sample_rate = audio.sample_rate()
|
||||
p.channels = audio.channels()
|
||||
alloc_size := 200 * 1024
|
||||
p.allocator = C.stb_vorbis_alloc{
|
||||
alloc_buffer: unsafe { &char(vcalloc(alloc_size)) }
|
||||
alloc_buffer_length_in_bytes: alloc_size
|
||||
}
|
||||
}
|
||||
|
||||
fn (mut p Player) stop() {
|
||||
p.free()
|
||||
audio.shutdown()
|
||||
}
|
||||
|
||||
fn (mut p Player) free() {
|
||||
p.finished = false
|
||||
p.pos = 0
|
||||
p.close_decoder()
|
||||
unsafe { free(p.allocator.alloc_buffer) }
|
||||
unsafe {
|
||||
p.allocator.alloc_buffer = nil
|
||||
}
|
||||
}
|
||||
|
||||
fn (mut p Player) close_decoder() {
|
||||
if !isnil(p.decoder) {
|
||||
C.stb_vorbis_close(p.decoder)
|
||||
}
|
||||
}
|
||||
|
||||
fn (mut p Player) play_ogg_file(fpath string) ! {
|
||||
p.close_decoder()
|
||||
p.pos = 0
|
||||
p.xerror = .no_error
|
||||
p.decoder = C.stb_vorbis_open_filename(&char(fpath.str), voidptr(&p.xerror), &p.allocator)
|
||||
if isnil(p.decoder) || p.xerror != .no_error {
|
||||
return error('could not open ogg file: ${fpath}, xerror: ${p.xerror}')
|
||||
}
|
||||
info := C.stb_vorbis_get_info(p.decoder)
|
||||
p.stream_rate = info.sample_rate
|
||||
p.stream_channels = info.channels
|
||||
p.stream_len_samples = C.stb_vorbis_stream_length_in_samples(p.decoder)
|
||||
p.stream_len_seconds = C.stb_vorbis_stream_length_in_seconds(p.decoder)
|
||||
p.finished = false
|
||||
|
||||
if !(p.channels == p.stream_channels && p.sample_rate == p.stream_rate) {
|
||||
audio.shutdown()
|
||||
audio.setup(
|
||||
num_channels: p.stream_channels
|
||||
sample_rate: int(p.stream_rate)
|
||||
)
|
||||
p.sample_rate = audio.sample_rate()
|
||||
p.channels = audio.channels()
|
||||
}
|
||||
println('> play_ogg_file: rate: ${p.sample_rate:5}, channels: ${p.channels:1} | stream rate: ${p.stream_rate:5}, channels: ${p.stream_channels:1}, samples: ${p.stream_len_samples:8} | seconds: ${p.stream_len_seconds:7.3f} | ${fpath}')
|
||||
|
||||
frames := [16384]f32{}
|
||||
pframes := unsafe { &frames[0] }
|
||||
for !p.finished {
|
||||
mut delay := p.push_slack_ms
|
||||
expected_frames := audio.expect()
|
||||
if expected_frames > 0 {
|
||||
mut decoded_frames := 0
|
||||
for decoded_frames < expected_frames {
|
||||
samples := C.stb_vorbis_get_samples_float_interleaved(p.decoder, p.channels,
|
||||
pframes, 1024)
|
||||
if samples == 0 {
|
||||
p.finished = true
|
||||
break
|
||||
}
|
||||
written_frames := audio.push(pframes, samples)
|
||||
decoded_frames += written_frames
|
||||
p.pos += samples
|
||||
}
|
||||
delay = (1_000 * decoded_frames) / p.sample_rate
|
||||
}
|
||||
print('\r position: ${p.pos:9} / ${p.stream_len_samples:-9} samples | ${p.pos * p.stream_len_seconds / p.stream_len_samples:7.3f} / ${p.stream_len_seconds:-7.3f} seconds')
|
||||
time.sleep(int_max(p.push_slack_ms, delay - p.push_slack_ms) * time.millisecond)
|
||||
}
|
||||
println('')
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,37 @@
|
||||
// vtest build: !openbsd
|
||||
|
||||
// This program illustrates how to use sokol.audio in a simple console app, *without a gui*.
|
||||
// See melody.v for an example of how it can be integrated into a graphics app.
|
||||
import time
|
||||
import sokol.audio
|
||||
|
||||
fn audio_callback(mut soundbuffer &f32, num_frames int, num_channels int, mut frame_0 &i32) {
|
||||
for frame := 0; frame < num_frames; frame++ {
|
||||
t := i32(f32(*frame_0 + frame) * 0.245)
|
||||
y := (t * (((t / 10 | 0) ^ ((t / 10 | 0) - 1280)) % 11) / 2 & 127) +
|
||||
(t * (((t / 640 | 0) ^ ((t / 640 | 0) - 2)) % 13) / 2 & 127)
|
||||
for ch := 0; ch < num_channels; ch++ {
|
||||
idx := frame * num_channels + ch
|
||||
a := f32(y - 127) / 255.0
|
||||
soundbuffer[idx] = a
|
||||
}
|
||||
}
|
||||
frame_0 += num_frames
|
||||
}
|
||||
|
||||
// The example uses \r, to show a simple progress bar, while the music is playing.
|
||||
// That works best, if the output is not buffered at all.
|
||||
unbuffer_stdout()
|
||||
|
||||
println('The ByteBeat formula used in this example is from https://www.youtube.com/watch?v=V4GfkFbDojc , "Techno" by Gabriel Miceli')
|
||||
|
||||
mut frame_0 := i32(0) // offset of the current audio frames, relative to the start of the music
|
||||
audio.setup(stream_userdata_cb: audio_callback, user_data: &frame_0) // our state/user_data can be just a simple integer
|
||||
|
||||
for t in 0 .. 600 {
|
||||
print('\r> t: ${t:5}s , frame_0: ${frame_0:10} samples')
|
||||
time.sleep(1 * time.second)
|
||||
}
|
||||
println('\nGood bye.')
|
||||
|
||||
audio.shutdown()
|
||||
@@ -0,0 +1,116 @@
|
||||
// vtest build: !openbsd
|
||||
import time
|
||||
import math
|
||||
import term
|
||||
import sokol.audio
|
||||
|
||||
struct Note {
|
||||
mut:
|
||||
phase f32
|
||||
freq f32
|
||||
amplitude f32
|
||||
}
|
||||
|
||||
struct App {
|
||||
mut:
|
||||
notes shared []Note
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println('Press the keys (a, s, d, f, g, h, j, k) to play notes. Press ESC to quit.')
|
||||
mut app := &App{
|
||||
notes: []Note{len: 32}
|
||||
}
|
||||
audio.setup(
|
||||
stream_userdata_cb: audio_callback
|
||||
user_data: app
|
||||
)
|
||||
defer { audio.shutdown() }
|
||||
term.enable_echo(false)
|
||||
defer { term.enable_echo(true) }
|
||||
for {
|
||||
key := term.key_pressed(blocking: false)
|
||||
app.handle_key(key) or { break }
|
||||
time.sleep(5 * time.millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
const c_2_pi = 2 * math.pi
|
||||
const c_phase_step_per_freq = c_2_pi / 44100.0
|
||||
const c_note_start_amplitude = 0.33
|
||||
const c_note_decay = 0.3 / 44100.0
|
||||
|
||||
fn (mut app App) handle_key(key i64) ? {
|
||||
if key == -1 {
|
||||
return
|
||||
}
|
||||
mut freq := f32(0.0)
|
||||
match key {
|
||||
27 { return none }
|
||||
` ` { app.silence() }
|
||||
`a` { freq = 261.63 }
|
||||
`s` { freq = 293.66 }
|
||||
`d` { freq = 329.63 }
|
||||
`f` { freq = 349.23 }
|
||||
`g` { freq = 392.00 }
|
||||
`h` { freq = 440.00 }
|
||||
`j` { freq = 493.88 }
|
||||
`k` { freq = 523.25 }
|
||||
else {}
|
||||
}
|
||||
|
||||
if freq > 0 {
|
||||
app.play(freq, c_note_start_amplitude)
|
||||
}
|
||||
}
|
||||
|
||||
fn (mut app App) play(freq f32, volume f32) {
|
||||
lock app.notes {
|
||||
for mut note in app.notes {
|
||||
note.amplitude -= 0.2
|
||||
}
|
||||
for mut note in app.notes {
|
||||
if note.amplitude <= 0 {
|
||||
note = Note{
|
||||
phase: 0.0
|
||||
freq: freq
|
||||
amplitude: volume
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn (mut app App) silence() {
|
||||
lock app.notes {
|
||||
for mut note in app.notes {
|
||||
note.amplitude = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn audio_callback(mut soundbuffer &f32, num_frames int, num_channels int, mut app App) {
|
||||
lock app.notes {
|
||||
for frame in 0 .. num_frames {
|
||||
mut sample := f32(0.0)
|
||||
for mut note in app.notes {
|
||||
if note.amplitude <= 0 {
|
||||
continue
|
||||
}
|
||||
sample += note.amplitude * math.sinf(note.phase)
|
||||
sample += note.amplitude * math.sinf(note.phase * 2.718)
|
||||
sample += note.amplitude * math.sinf(note.phase * 3.141)
|
||||
|
||||
note.phase += note.freq * c_phase_step_per_freq
|
||||
for note.phase >= c_2_pi {
|
||||
note.phase -= c_2_pi
|
||||
}
|
||||
note.amplitude -= c_note_decay
|
||||
}
|
||||
for ch in 0 .. num_channels {
|
||||
soundbuffer[frame * num_channels + ch] = sample
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// vtest build: !openbsd && !sanitize-memory-clang // Fails compilation with: `ld: /lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line`
|
||||
// import log
|
||||
import math
|
||||
import time
|
||||
import sokol.audio
|
||||
|
||||
fn main() {
|
||||
args := arguments()
|
||||
freq := args[1] or { '417' }.int()
|
||||
amplitude := args[2] or { '0.5' }.f32()
|
||||
dump(freq)
|
||||
dump(amplitude)
|
||||
|
||||
audio.setup(num_channels: 1)
|
||||
sample_rate := dump(audio.sample_rate())
|
||||
dump(audio.buffer_frames())
|
||||
dump(audio.expect())
|
||||
|
||||
// create an array of frames, filled with the desired pure sine tone:
|
||||
mut frames := []f32{len: sample_rate * 2} // 2 seconds
|
||||
for i in 0 .. frames.len {
|
||||
t := f32(i) / f32(sample_rate)
|
||||
frames[i] = amplitude * math.sinf(f32(freq) * t * (2 * math.pi))
|
||||
}
|
||||
|
||||
// play the sound by continuosly pushing samples from the generated
|
||||
// array of sound frames, when there is need for more:
|
||||
mut fpos := 0
|
||||
for {
|
||||
expected_frames := audio.expect()
|
||||
if expected_frames > 0 {
|
||||
written_frames := audio.push(unsafe { &frames[fpos] }, expected_frames)
|
||||
fpos += written_frames
|
||||
// log.info('> pushing done ... fpos: ${fpos:6} | expected_frames: ${expected_frames:6} | written: ${written:6}')
|
||||
if fpos > frames.len - 2 * written_frames {
|
||||
// log.info('> fpos too large: ${fpos}')
|
||||
fpos = find_loop_position(fpos, frames)
|
||||
// log.info('> fpos looped back to start: ${fpos}')
|
||||
}
|
||||
}
|
||||
time.sleep(50 * time.millisecond)
|
||||
}
|
||||
audio.shutdown()
|
||||
}
|
||||
|
||||
fn find_loop_position(fpos int, frames []f32) int {
|
||||
return find_matching_position(frames, fpos, 0.01, 2) or {
|
||||
find_matching_position(frames, fpos, 0.05, 2) or {
|
||||
find_matching_position(frames, fpos, 0.1, 2) or { 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@[direct_array_access]
|
||||
fn find_matching_position(frames []f32, fpos int, tol f32, d int) ?int {
|
||||
if fpos - d < 0 || fpos + d >= frames.len {
|
||||
return none
|
||||
}
|
||||
p1, p2, p3 := frames[fpos - d], frames[fpos], frames[fpos + d]
|
||||
for i in 2 .. fpos / 2 {
|
||||
np1, np2, np3 := frames[i - d], frames[i], frames[i + d]
|
||||
if math.tolerance(np1, p1, tol) && math.tolerance(np2, p2, tol)
|
||||
&& math.tolerance(np3, p3, tol) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return none
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// vtest build: !openbsd && !sanitize-memory-clang // Fails compilation with: `ld: /lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line`
|
||||
import time
|
||||
import math
|
||||
import sokol.audio
|
||||
|
||||
const sw = time.new_stopwatch()
|
||||
const sw_start_ms = sw.elapsed().milliseconds()
|
||||
|
||||
@[inline]
|
||||
fn sintone(periods int, frame int, num_frames int) f32 {
|
||||
return math.sinf(f32(periods) * (2 * math.pi) * f32(frame) / f32(num_frames))
|
||||
}
|
||||
|
||||
fn my_audio_stream_callback(mut soundbuffer &f32, num_frames int, num_channels int) {
|
||||
ms := sw.elapsed().milliseconds() - sw_start_ms
|
||||
for frame := 0; frame < num_frames; frame++ {
|
||||
for ch := 0; ch < num_channels; ch++ {
|
||||
idx := frame * num_channels + ch
|
||||
if ms < 250 {
|
||||
soundbuffer[idx] = 0.5 * sintone(20, frame, num_frames)
|
||||
} else if ms < 300 {
|
||||
soundbuffer[idx] = 0.5 * sintone(25, frame, num_frames)
|
||||
} else if ms < 1500 {
|
||||
soundbuffer[idx] *= sintone(22, frame, num_frames)
|
||||
} else {
|
||||
soundbuffer[idx] = 0.5 * sintone(25, frame, num_frames)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
audio.setup(
|
||||
stream_cb: my_audio_stream_callback
|
||||
)
|
||||
time.sleep(2000 * time.millisecond)
|
||||
audio.shutdown()
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,211 @@
|
||||
// vtest build: !openbsd
|
||||
import os
|
||||
import time
|
||||
import sokol.audio
|
||||
|
||||
struct Player {
|
||||
mut:
|
||||
sample_rate int
|
||||
samples []f32
|
||||
pos int
|
||||
finished bool
|
||||
}
|
||||
|
||||
fn main() {
|
||||
if os.args.len < 2 {
|
||||
eprintln('Usage: play_wav file1.wav file2.wav ...')
|
||||
play_sounds([os.resource_abs_path('uhoh.wav')])!
|
||||
exit(1)
|
||||
}
|
||||
play_sounds(os.args[1..])!
|
||||
}
|
||||
|
||||
fn play_sounds(files []string) ! {
|
||||
mut player := Player{}
|
||||
player.init()
|
||||
for f in files {
|
||||
if !os.exists(f) || os.is_dir(f) {
|
||||
eprintln('skipping "${f}" (does not exist)')
|
||||
continue
|
||||
}
|
||||
fext := os.file_ext(f).to_lower()
|
||||
if fext != '.wav' {
|
||||
eprintln('skipping "${f}" (not a .wav file)')
|
||||
continue
|
||||
}
|
||||
player.play_wav_file(f)!
|
||||
}
|
||||
player.stop()
|
||||
}
|
||||
|
||||
//
|
||||
fn audio_player_callback(mut buffer &f32, num_frames int, num_channels int, mut p Player) {
|
||||
ntotal := num_channels * num_frames
|
||||
unsafe { vmemset(buffer, 0, ntotal * 4) }
|
||||
if p.finished {
|
||||
return
|
||||
}
|
||||
nremaining := p.samples.len - p.pos
|
||||
nsamples := if nremaining < ntotal { nremaining } else { ntotal }
|
||||
if nsamples <= 0 {
|
||||
p.finished = true
|
||||
return
|
||||
}
|
||||
unsafe { vmemcpy(buffer, &p.samples[p.pos], nsamples * 4) }
|
||||
p.pos += nsamples
|
||||
}
|
||||
|
||||
fn (mut p Player) init() {
|
||||
audio.setup(
|
||||
num_channels: 1
|
||||
stream_userdata_cb: audio_player_callback
|
||||
user_data: p
|
||||
sample_rate: 44100
|
||||
)
|
||||
p.sample_rate = audio.sample_rate()
|
||||
}
|
||||
|
||||
fn (mut p Player) stop() {
|
||||
audio.shutdown()
|
||||
p.free()
|
||||
}
|
||||
|
||||
fn (mut p Player) play_wav_file(fpath string) ! {
|
||||
println('> play_wav_file: ${fpath}')
|
||||
samples := read_wav_file_samples(fpath)!
|
||||
p.finished = true
|
||||
p.samples << samples
|
||||
p.finished = false
|
||||
for !p.finished {
|
||||
time.sleep(16 * time.millisecond)
|
||||
}
|
||||
p.free()
|
||||
}
|
||||
|
||||
fn (mut p Player) free() {
|
||||
p.finished = false
|
||||
p.samples = []f32{}
|
||||
p.pos = 0
|
||||
}
|
||||
|
||||
// The read_wav_file_samples function below is based on the following sources:
|
||||
// http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
|
||||
// http://www.lightlink.com/tjweber/StripWav/WAVE.html
|
||||
// http://www.lightlink.com/tjweber/StripWav/Canon.html
|
||||
// https://tools.ietf.org/html/draft-ema-vpim-wav-00
|
||||
// Note: > The chunks MAY appear in any order except that the Format chunk
|
||||
// > MUST be placed before the Sound data chunk (but not necessarily
|
||||
// > contiguous to the Sound data chunk).
|
||||
struct RIFFHeader {
|
||||
riff [4]u8
|
||||
file_size u32
|
||||
form_type [4]u8
|
||||
}
|
||||
|
||||
struct RIFFChunkHeader {
|
||||
chunk_type [4]u8
|
||||
chunk_size u32
|
||||
chunk_data voidptr
|
||||
}
|
||||
|
||||
struct RIFFFormat {
|
||||
format_tag u16 // PCM = 1; Values other than 1 indicate some form of compression.
|
||||
nchannels u16 // Nc ; 1 = mono ; 2 = stereo
|
||||
sample_rate u32 // F
|
||||
avg_bytes_per_second u32 // F * M*Nc
|
||||
nblock_align u16 // M*Nc
|
||||
bits_per_sample u16 // 8 * M
|
||||
cbsize u16 // Size of the extension: 22
|
||||
valid_bits_per_sample u16 // at most 8*M
|
||||
channel_mask u32 // Speaker position mask
|
||||
sub_format [16]u8 // GUID
|
||||
}
|
||||
|
||||
fn read_wav_file_samples(fpath string) ![]f32 {
|
||||
mut res := []f32{}
|
||||
// eprintln('> read_wav_file_samples: ${fpath} -------------------------------------------------')
|
||||
mut bytes := os.read_bytes(fpath)!
|
||||
mut pbytes := &u8(bytes.data)
|
||||
mut offset := u32(0)
|
||||
rh := unsafe { &RIFFHeader(pbytes) }
|
||||
// eprintln('rh: ${rh}')
|
||||
if rh.riff != [u8(`R`), `I`, `F`, `F`]! {
|
||||
return error('WAV should start with `RIFF`')
|
||||
}
|
||||
if rh.form_type != [u8(`W`), `A`, `V`, `E`]! {
|
||||
return error('WAV should have `WAVE` form type')
|
||||
}
|
||||
if rh.file_size + 8 != bytes.len {
|
||||
return error('WAV should have valid length')
|
||||
}
|
||||
offset += sizeof(RIFFHeader)
|
||||
mut rf := &RIFFFormat(unsafe { nil })
|
||||
for {
|
||||
if offset >= bytes.len {
|
||||
break
|
||||
}
|
||||
//
|
||||
ch := unsafe { &RIFFChunkHeader(pbytes + offset) }
|
||||
offset += 8 + ch.chunk_size
|
||||
// eprintln('ch: ${ch}')
|
||||
// eprintln('p: ${pbytes} | offset: ${offset} | bytes.len: ${bytes.len}')
|
||||
// ////////
|
||||
if ch.chunk_type == [u8(`L`), `I`, `S`, `T`]! {
|
||||
continue
|
||||
}
|
||||
//
|
||||
if ch.chunk_type == [u8(`i`), `d`, `3`, ` `]! {
|
||||
continue
|
||||
}
|
||||
//
|
||||
if ch.chunk_type == [u8(`f`), `m`, `t`, ` `]! {
|
||||
// eprintln('`fmt ` chunk')
|
||||
rf = unsafe { &RIFFFormat(&ch.chunk_data) }
|
||||
// eprintln('fmt riff format: ${rf}')
|
||||
if rf.format_tag != 1 {
|
||||
return error('only PCM encoded WAVs are supported')
|
||||
}
|
||||
if rf.nchannels < 1 || rf.nchannels > 2 {
|
||||
return error('only mono or stereo WAVs are supported')
|
||||
}
|
||||
if rf.bits_per_sample !in [u16(8), 16] {
|
||||
return error('only 8 or 16 bits per sample WAVs are supported')
|
||||
}
|
||||
continue
|
||||
}
|
||||
//
|
||||
if ch.chunk_type == [u8(`d`), `a`, `t`, `a`]! {
|
||||
if unsafe { rf == 0 } {
|
||||
return error('`data` chunk should be after `fmt ` chunk')
|
||||
}
|
||||
// eprintln('`fmt ` chunk: ${rf}\n`data` chunk: ${ch}')
|
||||
mut doffset := 0
|
||||
mut dp := unsafe { &u8(&ch.chunk_data) }
|
||||
for doffset < ch.chunk_size {
|
||||
for c := 0; c < rf.nchannels; c++ {
|
||||
mut x := f32(0.0)
|
||||
mut step := 0
|
||||
ppos := unsafe { dp + doffset }
|
||||
if rf.bits_per_sample == 8 {
|
||||
d8 := unsafe { &u8(ppos) }
|
||||
x = (f32(*d8) - 128) / 128.0
|
||||
step = 1
|
||||
doffset++
|
||||
}
|
||||
if rf.bits_per_sample == 16 {
|
||||
d16 := unsafe { &i16(ppos) }
|
||||
x = f32(*d16) / 32768.0
|
||||
step = 2
|
||||
}
|
||||
doffset += step
|
||||
if doffset < ch.chunk_size {
|
||||
for _ in 0 .. (44100 / rf.sample_rate) {
|
||||
res << x
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
Reference in new issue
Block a user