From f5c4671bfbad96bf346bd7e9a21fc4317b4959df Mon Sep 17 00:00:00 2001 From: Indrajith K L Date: Sat, 3 Dec 2022 17:00:20 +0530 Subject: Adds most of the tools --- .../sokol/06_obj_viewer/assets/models/v.mtl | 20 + .../sokol/06_obj_viewer/assets/models/v.obj_ | 194 +++++++ .../v/examples/sokol/06_obj_viewer/gouraud.glsl | 108 ++++ .../examples/sokol/06_obj_viewer/modules/obj/obj.v | 595 +++++++++++++++++++++ .../sokol/06_obj_viewer/modules/obj/rend.v | 297 ++++++++++ .../sokol/06_obj_viewer/modules/obj/struct.v | 104 ++++ .../sokol/06_obj_viewer/modules/obj/util.v | 44 ++ .../v/examples/sokol/06_obj_viewer/show_obj.v | 338 ++++++++++++ v_windows/v/examples/sokol/06_obj_viewer/v.mod | 0 9 files changed, 1700 insertions(+) create mode 100644 v_windows/v/examples/sokol/06_obj_viewer/assets/models/v.mtl create mode 100644 v_windows/v/examples/sokol/06_obj_viewer/assets/models/v.obj_ create mode 100644 v_windows/v/examples/sokol/06_obj_viewer/gouraud.glsl create mode 100644 v_windows/v/examples/sokol/06_obj_viewer/modules/obj/obj.v create mode 100644 v_windows/v/examples/sokol/06_obj_viewer/modules/obj/rend.v create mode 100644 v_windows/v/examples/sokol/06_obj_viewer/modules/obj/struct.v create mode 100644 v_windows/v/examples/sokol/06_obj_viewer/modules/obj/util.v create mode 100644 v_windows/v/examples/sokol/06_obj_viewer/show_obj.v create mode 100644 v_windows/v/examples/sokol/06_obj_viewer/v.mod (limited to 'v_windows/v/examples/sokol/06_obj_viewer') diff --git a/v_windows/v/examples/sokol/06_obj_viewer/assets/models/v.mtl b/v_windows/v/examples/sokol/06_obj_viewer/assets/models/v.mtl new file mode 100644 index 0000000..47d0381 --- /dev/null +++ b/v_windows/v/examples/sokol/06_obj_viewer/assets/models/v.mtl @@ -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 \ No newline at end of file diff --git a/v_windows/v/examples/sokol/06_obj_viewer/assets/models/v.obj_ b/v_windows/v/examples/sokol/06_obj_viewer/assets/models/v.obj_ new file mode 100644 index 0000000..d25cc0a --- /dev/null +++ b/v_windows/v/examples/sokol/06_obj_viewer/assets/models/v.obj_ @@ -0,0 +1,194 @@ +# Blender v2.92.0 V Logo +mtllib v.mtl +o Vleft.020_Plane.030 +v -1.379 6.295 0.625 +v -1.389 6.019 -3.177 +v -1.442 6.063 -3.177 +v -1.433 6.339 0.625 +v -4.038 6.499 0.662 +v -4.037 6.537 0.661 +v -4.047 6.261 -3.141 +v -4.048 6.222 -3.140 +v -3.900 6.637 0.658 +v -3.910 6.360 -3.144 +v -3.974 6.342 -3.142 +v -3.964 6.618 0.660 +v -4.012 6.582 0.661 +v -4.022 6.306 -3.142 +v -1.273 6.135 0.624 +v -1.283 5.859 -3.178 +v -1.321 5.933 -3.178 +v -1.311 6.209 0.624 +v 1.288 -1.652 0.018 +v 1.282 -1.628 -3.759 +v -1.510 6.387 0.625 +v -1.520 6.111 -3.177 +v -1.559 6.128 -3.176 +v -1.550 6.404 0.626 +v -1.103 -1.603 0.043 +v -1.113 -1.579 -3.759 +v -1.082 -1.597 -3.759 +v -1.072 -1.620 0.043 +v -1.127 -1.583 0.043 +v -1.137 -1.560 -3.759 +v -1.042 -1.631 0.043 +v -1.052 -1.608 -3.759 +v -1.490 6.095 -3.177 +v -1.480 6.372 0.625 +v -1.148 -1.563 0.043 +v -1.158 -1.540 -3.759 +v -1.164 -1.541 0.043 +v -1.174 -1.518 -3.759 +v -1.171 -1.528 0.043 +v -1.181 -1.504 -3.759 +v -1.347 5.974 -3.178 +v -1.337 6.250 0.624 +v -4.034 6.459 0.662 +v -4.044 6.183 -3.140 +vn 0.634 0.771 -0.057 +vn -0.999 0.034 0.000 +vn -0.278 0.958 -0.068 +vn -0.868 0.494 -0.033 +vn 0.889 0.455 -0.035 +vn 0.947 0.319 -0.012 +vn 0.399 0.914 -0.067 +vn -0.502 -0.864 -0.004 +vn 0.097 0.992 -0.072 +vn -0.630 -0.776 -0.003 +vn -0.009 -0.999 -0.006 +vn 0.564 0.822 -0.061 +vn -0.693 -0.720 -0.002 +vn -0.805 -0.592 -0.001 +vn -0.888 -0.458 -0.000 +vn 0.843 0.535 -0.041 +vn -0.993 -0.116 0.011 +vn 0.731 0.680 -0.051 +vn -0.938 -0.344 0.013 +vn 0.450 0.890 -0.065 +vn -0.604 0.794 -0.056 +vn 0.005 -0.072 0.997 +vn -0.000 0.075 -0.997 +vn -0.329 -0.944 -0.005 +usemtl Material.001 +s 1 +f 1//1 2//1 3//1 4//1 +f 5//2 6//2 7//2 8//2 +f 9//3 10//3 11//3 12//3 +f 6//4 13//4 14//4 7//4 +f 15//5 16//5 17//5 18//5 +f 19//6 20//6 16//6 15//6 +f 21//7 22//7 23//7 24//7 +f 25//8 26//8 27//8 28//8 +f 24//9 23//9 10//9 9//9 +f 29//10 30//10 26//10 25//10 +f 19//11 31//11 32//11 20//11 +f 4//12 3//12 33//12 34//12 +f 35//13 36//13 30//13 29//13 +f 37//14 38//14 36//14 35//14 +f 39//15 40//15 38//15 37//15 +f 18//16 17//16 41//16 42//16 +f 43//17 5//17 8//17 44//17 +f 42//18 41//18 2//18 1//18 +f 39//19 43//19 44//19 40//19 +f 34//20 33//20 22//20 21//20 +f 13//21 12//21 11//21 14//21 +f 15//22 18//22 42//22 1//22 4//22 34//22 21//22 24//22 9//22 12//22 13//22 6//22 5//22 43//22 39//22 37//22 35//22 29//22 25//22 28//22 31//22 19//22 +f 22//23 33//23 3//23 2//23 41//23 17//23 16//23 20//23 32//23 27//23 26//23 30//23 36//23 38//23 40//23 44//23 8//23 7//23 14//23 11//23 10//23 23//23 +f 28//24 27//24 32//24 31//24 +o Vleft.019_Plane.029 +v 1.617 6.547 -4.385 +v 1.627 6.270 -0.582 +v 1.681 6.314 -0.582 +v 1.671 6.591 -4.385 +v 4.277 6.750 -4.422 +v 4.276 6.789 -4.421 +v 4.286 6.513 -0.618 +v 4.287 6.474 -0.618 +v 1.280 -1.685 -3.803 +v 1.290 -1.656 -0.000 +v -1.044 -1.625 -0.000 +v -1.059 -1.615 -3.788 +v 4.250 6.834 -4.420 +v 4.260 6.557 -0.617 +v 1.512 6.387 -4.384 +v 1.522 6.110 -0.581 +v 1.559 6.184 -0.581 +v 1.550 6.461 -4.384 +v 1.410 -1.581 -3.803 +v 4.273 6.711 -4.422 +v 4.282 6.434 -0.619 +v 1.419 -1.552 -0.000 +v 1.749 6.639 -4.385 +v 1.758 6.362 -0.582 +v 1.798 6.380 -0.582 +v 1.788 6.656 -4.386 +v 1.342 -1.657 -3.803 +v 1.351 -1.628 -0.000 +v 1.321 -1.645 -0.000 +v 1.311 -1.674 -3.803 +v 4.148 6.612 -0.615 +v 4.139 6.888 -4.418 +v 4.213 6.593 -0.617 +v 4.203 6.870 -4.420 +v 1.366 -1.637 -3.803 +v 1.375 -1.608 -0.000 +v 1.728 6.347 -0.582 +v 1.719 6.623 -4.385 +v 1.386 -1.617 -3.803 +v 1.396 -1.588 -0.000 +v 1.402 -1.595 -3.803 +v 1.412 -1.566 -0.000 +v 1.585 6.225 -0.581 +v 1.575 6.501 -4.384 +vn -0.634 0.771 0.057 +vn 0.999 0.034 -0.000 +vn -0.021 -0.999 0.002 +vn 0.868 0.494 0.033 +vn -0.889 0.455 0.035 +vn 0.943 -0.332 -0.013 +vn -0.399 0.914 0.067 +vn 0.502 -0.864 0.005 +vn -0.097 0.992 0.072 +vn 0.278 0.958 0.068 +vn 0.630 -0.776 0.004 +vn -0.564 0.822 0.061 +vn 0.693 -0.720 0.003 +vn -0.950 0.311 0.014 +vn 0.805 -0.592 0.002 +vn 0.888 -0.458 0.001 +vn -0.843 0.535 0.041 +vn 0.993 -0.116 -0.011 +vn -0.731 0.680 0.051 +vn -0.450 0.890 0.065 +vn 0.604 0.794 0.056 +vn -0.005 -0.070 -0.997 +vn 0.000 -0.000 1.000 +vn 0.001 0.072 0.997 +vn 0.329 -0.944 0.006 +usemtl Material.002 +s 1 +f 45//25 46//25 47//25 48//25 +f 49//26 50//26 51//26 52//26 +f 53//27 54//27 55//27 56//27 +f 50//28 57//28 58//28 51//28 +f 59//29 60//29 61//29 62//29 +f 63//30 64//30 65//30 66//30 +f 67//31 68//31 69//31 70//31 +f 71//32 72//32 73//32 74//32 +f 70//33 69//33 75//33 76//33 +f 76//34 75//34 77//34 78//34 +f 79//35 80//35 72//35 71//35 +f 48//36 47//36 81//36 82//36 +f 83//37 84//37 80//37 79//37 +f 56//38 55//38 60//38 59//38 +f 85//39 86//39 84//39 83//39 +f 63//40 66//40 86//40 85//40 +f 62//41 61//41 87//41 88//41 +f 64//42 49//42 52//42 65//42 +f 88//43 87//43 46//43 45//43 +f 82//44 81//44 68//44 67//44 +f 57//45 78//45 77//45 58//45 +f 63//46 85//46 83//46 79//46 71//46 74//46 53//46 56//46 59//46 62//46 88//46 45//46 48//46 82//46 67//46 70//46 76//46 78//46 57//46 50//46 49//46 64//46 +f 66//47 84//47 86//47 +f 66//48 65//48 52//48 51//48 58//48 77//48 75//48 69//48 68//48 81//48 47//48 46//48 87//48 61//48 60//48 55//48 54//48 73//48 72//48 80//48 84//48 +f 74//49 73//49 54//49 53//49 diff --git a/v_windows/v/examples/sokol/06_obj_viewer/gouraud.glsl b/v_windows/v/examples/sokol/06_obj_viewer/gouraud.glsl new file mode 100644 index 0000000..7f36499 --- /dev/null +++ b/v_windows/v/examples/sokol/06_obj_viewer/gouraud.glsl @@ -0,0 +1,108 @@ +//#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 sampler2D tex; +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(tex, 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 \ No newline at end of file diff --git a/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/obj.v b/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/obj.v new file mode 100644 index 0000000..1d239a0 --- /dev/null +++ b/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/obj.v @@ -0,0 +1,595 @@ +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 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.v.len} ${obj.v.len-c}") + v = obj.v.len - v + 1 + // exit(0) + } + if n < 0 { + n = obj.vn.len - n + 1 + } + if t < 0 { + t = obj.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 + } + // parameteres 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 + } + } + // trasparency + `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 // poistion + 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) +} diff --git a/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/rend.v b/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/rend.v new file mode 100644 index 0000000..d4ea3bc --- /dev/null +++ b/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/rend.v @@ -0,0 +1,297 @@ +/********************************************************************** +* +* .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 &byte) C.sg_image { + sz := w * h * 4 + mut img_desc := C.sg_image_desc{ + 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: &byte(0) + d3d11_texture: 0 + } + // comment if .dynamic is enabled + img_desc.data.subimage[0][0] = C.sg_range{ + ptr: buf + size: size_t(sz) + } + + sg_img := C.sg_make_image(&img_desc) + return sg_img +} + +pub fn destroy_texture(sg_img C.sg_image) { + C.sg_destroy_image(sg_img) +} + +pub fn load_texture(file_name string) C.sg_image { + 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('Texure file: [$file_name] ERROR!') + exit(0) + } + res := create_texture(int(img.width), int(img.height), img.data) + img.free() + return res +} + +/****************************************************************************** +* Pipeline +******************************************************************************/ +pub fn (mut obj_part ObjPart) create_pipeline(in_part []int, shader C.sg_shader, texture C.sg_image) 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 := C.sg_buffer_desc{ + label: 0 + } + unsafe { C.memset(&vert_buffer_desc, 0, sizeof(vert_buffer_desc)) } + + vert_buffer_desc.size = size_t(obj_buf.vbuf.len * int(sizeof(Vertex_pnct))) + vert_buffer_desc.data = C.sg_range{ + ptr: obj_buf.vbuf.data + size: size_t(obj_buf.vbuf.len * int(sizeof(Vertex_pnct))) + } + + vert_buffer_desc.@type = .vertexbuffer + vert_buffer_desc.label = 'vertbuf_part_${in_part:03}'.str + vbuf := gfx.make_buffer(&vert_buffer_desc) + + // index buffer + mut index_buffer_desc := C.sg_buffer_desc{ + label: 0 + } + unsafe { C.memset(&index_buffer_desc, 0, sizeof(index_buffer_desc)) } + + index_buffer_desc.size = size_t(obj_buf.ibuf.len * int(sizeof(u32))) + index_buffer_desc.data = C.sg_range{ + ptr: obj_buf.ibuf.data + size: size_t(obj_buf.ibuf.len * int(sizeof(u32))) + } + + index_buffer_desc.@type = .indexbuffer + index_buffer_desc.label = 'indbuf_part_${in_part:03}'.str + ibuf := gfx.make_buffer(&index_buffer_desc) + + mut pipdesc := C.sg_pipeline_desc{} + unsafe { C.memset(&pipdesc, 0, 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 := C.sg_color_state{ + blend: C.sg_blend_state{ + enabled: true + src_factor_rgb: gfx.BlendFactor(C.SG_BLENDFACTOR_SRC_ALPHA) + dst_factor_rgb: gfx.BlendFactor(C.SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA) + } + } + pipdesc.colors[0] = color_state + + pipdesc.depth = C.sg_depth_state{ + write_enabled: true + compare: gfx.CompareFunc(C.SG_COMPAREFUNC_LESS_EQUAL) + } + pipdesc.cull_mode = .front + + pipdesc.label = '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.pipeline = gfx.make_pipeline(&pipdesc) + // println('Buffers part [$in_part] init done!') + + return res +} + +/****************************************************************************** +* Render functions +******************************************************************************/ +// agregate all the part by materials +pub fn (mut obj_part ObjPart) init_render_data(texture C.sg_image) { + // create shader + // One shader for all the model + shader := gfx.make_shader(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 + + 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 = load_texture(file_name) + obj_part.texture[file_name] = txt + // 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) + } + // 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 pipline 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.ligth = in_data.fs_data.ligth + + 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 { + // defautl 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 := C.sg_range{ + ptr: in_data.vs_data + size: size_t(in_data.vs_len) + } + fs_uniforms_range := C.sg_range{ + ptr: unsafe { &tmp_fs_params } + size: size_t(in_data.fs_len) + } + + gfx.apply_uniforms(C.SG_SHADERSTAGE_VS, C.SLOT_vs_params, &vs_uniforms_range) + gfx.apply_uniforms(C.SG_SHADERSTAGE_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}") +} diff --git a/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/struct.v b/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/struct.v new file mode 100644 index 0000000..55a528b --- /dev/null +++ b/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/struct.v @@ -0,0 +1,104 @@ +/********************************************************************** +* +* .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 + +// part struct mantain the fae indexes list +pub struct Part { +pub mut: + faces [][][3]int // v n t index order, if -1 not available + name string + material string +} + +// materias 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 C.sg_pipeline + bind C.sg_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 // maping material name to its material index + texture map[string]C.sg_image // GPU loaded texture map + 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 // childs + // 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: + ligth 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 + vs_len int + fs_data &Tmp_fs_param + fs_len int +} diff --git a/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/util.v b/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/util.v new file mode 100644 index 0000000..a1e596a --- /dev/null +++ b/v_windows/v/examples/sokol/06_obj_viewer/modules/obj/util.v @@ -0,0 +1,44 @@ +module obj + +import os + +// read a file as single lines +pub fn read_lines_from_file(file_path string) []string { + mut path := '' + mut rows := []string{} + $if android { + path = 'models/' + file_path + bts := os.read_apk_asset(path) or { + eprintln('File [$path] NOT FOUND!') + return rows + } + rows = bts.bytestr().split_into_lines() + } $else { + path = os.resource_abs_path('assets/models/' + file_path) + rows = os.read_lines(path) or { + eprintln('File [$path] NOT FOUND! file_path: $file_path') + return rows + } + } + return rows +} + +// read a file as []byte +pub fn read_bytes_from_file(file_path string) []byte { + mut path := '' + mut buffer := []byte{} + $if android { + path = 'models/' + file_path + buffer = os.read_apk_asset(path) or { + eprintln('Texure file: [$path] NOT FOUND!') + exit(0) + } + } $else { + path = os.resource_abs_path('assets/models/' + file_path) + buffer = os.read_bytes(path) or { + eprintln('Texure file: [$path] NOT FOUND!') + exit(0) + } + } + return buffer +} diff --git a/v_windows/v/examples/sokol/06_obj_viewer/show_obj.v b/v_windows/v/examples/sokol/06_obj_viewer/show_obj.v new file mode 100644 index 0000000..e2e0be3 --- /dev/null +++ b/v_windows/v/examples/sokol/06_obj_viewer/show_obj.v @@ -0,0 +1,338 @@ +/********************************************************************** +* +* .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: +* - download the sokol shader convertor tool from https://github.com/floooh/sokol-tools-bin +* +* - compile the .glsl shader with: +* linux : sokol-shdc --input gouraud.glsl --output gouraud.h --slang glsl330 +* windows: sokol-shdc.exe --input gouraud.glsl --output gouraud.h --slang glsl330 +* +* --slang parameter can be: +* - glsl330: desktop GL +* - glsl100: GLES2 / WebGL +* - glsl300es: GLES3 / WebGL2 +* - hlsl4: D3D11 +* - hlsl5: D3D11 +* - metal_macos: Metal on macOS +* - metal_ios: Metal on iOS device +* - metal_sim: Metal on iOS simulator +* - wgpu: WebGPU +* +* you can have multiple platforms at the same time passing parameters like this: --slang glsl330:hlsl5:metal_macos +* for further infos have a look at the sokol shader tool docs. +* +* 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 gx +import math +import sokol.sapp +import sokol.gfx +import sokol.sgl +import time +import os +import obj + +// GLSL Include and functions + +#flag -I @VMODROOT/. +#include "gouraud.h" #Please use sokol-shdc to generate the necessary rt_glsl.h file from rt_glsl.glsl (see the instructions at the top of this file) + +fn C.gouraud_shader_desc(gfx.Backend) &C.sg_shader_desc + +const ( + win_width = 600 + win_height = 600 + bg_color = gx.white +) + +struct App { +mut: + gg &gg.Context + texture C.sg_image + 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 + 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.ligth = 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) { + ws := gg.window_size_real_pixels() + + // clear + mut color_action := C.sg_color_attachment_action{ + action: gfx.Action(C.SG_ACTION_CLEAR) + value: C.sg_color{ + r: 0.0 + g: 0.0 + b: 0.0 + a: 1.0 + } + } + + mut pass_action := C.sg_pass_action{} + pass_action.colors[0] = color_action + gfx.begin_default_pass(&pass_action, ws.width, ws.height) + + // render the data + draw_start_glsl(app) + draw_model(app, m4.Vec4{}) + // uncoment 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 := C.sgl_desc_t{ + max_vertices: 128 * 65536 + } + sgl.setup(&sgl_desc) + + // 1x1 pixel white, default texture + unsafe { + tmp_txt := malloc(4) + tmp_txt[0] = byte(0xFF) + tmp_txt[1] = byte(0xFF) + tmp_txt[2] = byte(0xFF) + tmp_txt[3] = byte(0xFF) + app.texture = obj.create_texture(1, 1, tmp_txt) + free(tmp_txt) + } + // glsl + app.obj_part.init_render_data(app.texture) + app.init_flag = true +} + +fn cleanup(mut app App) { + gfx.shutdown() + /* + 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) + } + } +} + +/****************************************************************************** +* Main +******************************************************************************/ +// is needed for easier diagnostics on windows +[console] +fn main() { + /* + obj.tst() + exit(0) + */ + + // App init + mut app := &App{ + gg: 0 + obj_part: 0 + } + + app.file_name = 'v.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, it must be in the folder "assets/models"') + eprintln(' if no file name is passed the default V logo will be showed.') + eprintln(' if you want custom models you can put them in the folder "assets/models".') + eprintln("single_material_flag: if true the viewer use for all the model's parts the default material\n") + 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() +} diff --git a/v_windows/v/examples/sokol/06_obj_viewer/v.mod b/v_windows/v/examples/sokol/06_obj_viewer/v.mod new file mode 100644 index 0000000..e69de29 -- cgit v1.2.3