tools: format most examples and tutorials, add them to `v test-cleancode` (#9826)

pull/9830/head
Lukas Neubert 2021-04-20 16:16:35 +02:00 committed by GitHub
parent dff50686d6
commit 16e79bc3ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
38 changed files with 471 additions and 433 deletions

View File

@ -18,12 +18,18 @@ const (
'examples/term.ui', 'examples/term.ui',
] ]
verify_known_failing_exceptions = [ verify_known_failing_exceptions = [
// Handcrafted meaningful formatting of code parts (mostly arrays)
'examples/sokol/02_cubes_glsl/cube_glsl.v',
'examples/sokol/03_march_tracing_glsl/rt_glsl.v',
'examples/sokol/04_multi_shader_glsl/rt_glsl.v',
'examples/sokol/05_instancing_glsl/rt_glsl.v',
'vlib/gg/m4/graphic.v',
'vlib/gg/m4/m4_test.v',
'vlib/gg/m4/matrix.v',
'vlib/builtin/int_test.v' /* special number formatting that should be tested */, 'vlib/builtin/int_test.v' /* special number formatting that should be tested */,
// TODOs and unfixed vfmt bugs
'vlib/builtin/int.v' /* TODO byteptr: vfmt converts `pub fn (nn byteptr) str() string {` to `nn &byte` and that conflicts with `nn byte` */, 'vlib/builtin/int.v' /* TODO byteptr: vfmt converts `pub fn (nn byteptr) str() string {` to `nn &byte` and that conflicts with `nn byte` */,
'vlib/builtin/string_charptr_byteptr_helpers.v' /* TODO byteptr: a temporary shim to ease the byteptr=>&byte transition */, 'vlib/builtin/string_charptr_byteptr_helpers.v' /* TODO byteptr: a temporary shim to ease the byteptr=>&byte transition */,
'vlib/gg/m4/graphic.v' /* has hand crafted meaningful formatting of matrices */,
'vlib/gg/m4/m4_test.v' /* has hand crafted meaningful formatting of matrices */,
'vlib/gg/m4/matrix.v' /* has hand crafted meaningful formatting of matrices */,
'vlib/v/tests/array_append_short_struct_test.v', /* extra empty line */ 'vlib/v/tests/array_append_short_struct_test.v', /* extra empty line */
'vlib/v/tests/fixed_array_const_size_test.v', /* fixed arr type is changed */ 'vlib/v/tests/fixed_array_const_size_test.v', /* fixed arr type is changed */
'vlib/v/tests/fn_high_test.v', /* param name removed */ 'vlib/v/tests/fn_high_test.v', /* param name removed */
@ -34,9 +40,13 @@ const (
'vlib/v/tests/string_interpolation_test.v' /* TODO byteptr: &byte.str() behaves differently than byteptr.str() */, 'vlib/v/tests/string_interpolation_test.v' /* TODO byteptr: &byte.str() behaves differently than byteptr.str() */,
'vlib/v/gen/js/tests/js.v', /* local `hello` fn, gets replaced with module `hello` aliased as `hl` */ 'vlib/v/gen/js/tests/js.v', /* local `hello` fn, gets replaced with module `hello` aliased as `hl` */
'vlib/v/gen/c/cheaders.v' /* the preprocessor directives are formated to the V standard, even though they are in a string literal */, 'vlib/v/gen/c/cheaders.v' /* the preprocessor directives are formated to the V standard, even though they are in a string literal */,
'examples/c_interop_wkhtmltopdf.v', /* &charptr --> &&char */
'examples/path_tracing.v', /* block --> line comments corrupts code */
] ]
vfmt_verify_list = [ vfmt_verify_list = [
'cmd/', 'cmd/',
'examples/',
'tutorials/',
'vlib/arrays/', 'vlib/arrays/',
'vlib/benchmark/', 'vlib/benchmark/',
'vlib/bitfield/', 'vlib/bitfield/',

View File

@ -1,8 +1,14 @@
struct App {} struct App {}
fn (mut app App) method_one() {} fn (mut app App) method_one() {}
fn (mut app App) method_two() int { return 0 }
fn (mut app App) method_three(s string) string { return s } fn (mut app App) method_two() int {
return 0
}
fn (mut app App) method_three(s string) string {
return s
}
fn main() { fn main() {
$for method in App.methods { $for method in App.methods {
@ -17,9 +23,9 @@ fn main() {
println('$method.name DOES return `int`') println('$method.name DOES return `int`')
} }
$if method.args[0].typ !is string { $if method.args[0].typ !is string {
println("${method.name}'s first arg is NOT `string`") println("$method.name's first arg is NOT `string`")
} $else { } $else {
println("${method.name}'s first arg IS `string`") println("$method.name's first arg IS `string`")
} }
// TODO: Double inversion, should this even be allowed? // TODO: Double inversion, should this even be allowed?
$if method.typ is fn () { $if method.typ is fn () {

View File

@ -15,7 +15,7 @@ fn main() {
assert name == 'Sam' assert name == 'Sam'
users, code := db.exec('select * from users') users, code := db.exec('select * from users')
println("SQL Result code: $code") println('SQL Result code: $code')
for row in users { for row in users {
println(row.vals) println(row.vals)
} }

View File

@ -4,7 +4,7 @@ import some_module
fn main() { fn main() {
mut sub := some_module.get_subscriber() mut sub := some_module.get_subscriber()
sub.subscribe("error", on_error) sub.subscribe('error', on_error)
some_module.do_work() some_module.do_work()
} }

View File

@ -19,16 +19,16 @@ pub:
pub fn do_work() { pub fn do_work() {
work := Work{20} work := Work{20}
for i in 0 .. 20 { for i in 0 .. 20 {
println("working...") println('working...')
if i == 15 { if i == 15 {
error := &MyError{"There was an error."} error := &MyError{'There was an error.'}
eb.publish("error", work, error) some_module.eb.publish('error', work, error)
eb.publish("error", work, error) some_module.eb.publish('error', work, error)
return return
} }
} }
} }
pub fn get_subscriber() eventbus.Subscriber { pub fn get_subscriber() eventbus.Subscriber {
return *eb.subscriber return *some_module.eb.subscriber
} }

View File

@ -61,8 +61,12 @@ fn on_frame(mut app App) {
fn on_event(e &gg.Event, mut app App) { fn on_event(e &gg.Event, mut app App) {
match e.typ { match e.typ {
.resized, .resumed { app.resize() } .resized, .resumed {
.iconified { app.draw_flag = false } app.resize()
}
.iconified {
app.draw_flag = false
}
.restored { .restored {
app.draw_flag = true app.draw_flag = true
app.resize() app.resize()
@ -89,7 +93,8 @@ fn (mut app App) resize() {
app.ui.height = size.height app.ui.height = size.height
} }
[console] // is needed for easier diagnostics on windows // is needed for easier diagnostics on windows
[console]
fn main() { fn main() {
mut font_path := os.resource_abs_path(os.join_path('../assets/fonts/', 'RobotoMono-Regular.ttf')) mut font_path := os.resource_abs_path(os.join_path('../assets/fonts/', 'RobotoMono-Regular.ttf'))
$if android { $if android {

View File

@ -42,7 +42,7 @@ fn main() {
gg: 0 gg: 0
a: automaton.gun() a: automaton.gun()
} }
app.gg = gg.new_context({ app.gg = gg.new_context(
bg_color: gx.white bg_color: gx.white
frame_fn: frame frame_fn: frame
user_data: &app user_data: &app
@ -52,6 +52,6 @@ fn main() {
create_window: true create_window: true
resizable: false resizable: false
window_title: 'v life (with gg, gx)' window_title: 'v life (with gg, gx)'
}) )
app.gg.run() app.gg.run()
} }

View File

@ -79,15 +79,11 @@ pub fn (mut aa Automaton) update() {
for y := 1; y < aa.field.maxy; y++ { for y := 1; y < aa.field.maxy; y++ {
for x := 1; x < aa.field.maxx; x++ { for x := 1; x < aa.field.maxx; x++ {
moore_sum := (0 + aa.field.get(x - 1, y - 1) + aa.field.get(x, y - 1) + aa.field.get(x + moore_sum := (0 + aa.field.get(x - 1, y - 1) + aa.field.get(x, y - 1) + aa.field.get(x +
1, y - 1) + aa.field.get(x - 1, y) + 0 + aa.field.get(x + 1, y) + aa.field.get(x - 1, y + 1) + 1, y - 1) + aa.field.get(x - 1, y) + 0 + aa.field.get(x + 1, y) +
aa.field.get(x, y + 1) + aa.field.get(x + 1, y + 1)) aa.field.get(x - 1, y + 1) + aa.field.get(x, y + 1) + aa.field.get(x + 1, y + 1))
cell := aa.field.get(x, y) cell := aa.field.get(x, y)
v := if cell == 1 { moore_sum in [2, 3] } else { moore_sum == 3 } v := if cell == 1 { moore_sum in [2, 3] } else { moore_sum == 3 }
aa.new_field.set(x, y, if v { aa.new_field.set(x, y, if v { 1 } else { 0 })
1
} else {
0
})
} }
} }
tmp := aa.field tmp := aa.field

View File

@ -19,7 +19,7 @@ fn main() {
mut app := &App{ mut app := &App{
gg: 0 gg: 0
} }
app.gg = gg.new_context({ app.gg = gg.new_context(
bg_color: gx.white bg_color: gx.white
width: win_width width: win_width
height: win_height height: win_height
@ -29,7 +29,7 @@ fn main() {
frame_fn: frame frame_fn: frame
user_data: app user_data: app
init_fn: init_images init_fn: init_images
}) )
app.image = app.gg.create_image(os.resource_abs_path('logo.png')) app.image = app.gg.create_image(os.resource_abs_path('logo.png'))
app.gg.run() app.gg.run()
} }

View File

@ -73,7 +73,7 @@ fn (ctx &Context) draw() {
// y = x * x + stime * stime // y = x * x + stime * stime
// y = stime // y = stime
// y = stime * h // y = stime * h
y = stime * 1.0 * math.sin((x) + stime + atime / 32) * ((h / 256) + x) y = stime * 1.0 * math.sin(x + stime + atime / 32) * ((h / 256) + x)
// y = (stime * x) * x + stime // y = (stime * x) * x + stime
// y = (x + 3) * (x + 3) / stime + stime*2.5 // y = (x + 3) * (x + 3) / stime + stime*2.5
// y = math.sqrt(30.0 - x * x) * stime // y = math.sqrt(30.0 - x * x) * stime

View File

@ -24,6 +24,7 @@ struct Lander {
fn (l Lander) deorbit() { fn (l Lander) deorbit() {
println('leaving orbit') println('leaving orbit')
} }
fn (l Lander) open_parachutes(n int) { fn (l Lander) open_parachutes(n int) {
println('opening $n parachutes') println('opening $n parachutes')
} }

View File

@ -19,7 +19,6 @@ fn hello_response() string {
return 'Hello, World!' return 'Hello, World!'
} }
fn callback(req picohttpparser.Request, mut res picohttpparser.Response) { fn callback(req picohttpparser.Request, mut res picohttpparser.Response) {
if picohttpparser.cmpn(req.method, 'GET ', 4) { if picohttpparser.cmpn(req.method, 'GET ', 4) {
if picohttpparser.cmp(req.path, '/t') { if picohttpparser.cmp(req.path, '/t') {
@ -28,19 +27,16 @@ fn callback(req picohttpparser.Request, mut res picohttpparser.Response) {
res.header_date() res.header_date()
res.plain() res.plain()
res.body(hello_response()) res.body(hello_response())
} } else if picohttpparser.cmp(req.path, '/j') {
else if picohttpparser.cmp(req.path, '/j') {
res.http_ok() res.http_ok()
res.header_server() res.header_server()
res.header_date() res.header_date()
res.json() res.json()
res.body(json_response()) res.body(json_response())
} } else {
else {
res.http_404() res.http_404()
} }
} } else {
else {
res.http_405() res.http_405()
} }
} }

View File

@ -31,10 +31,6 @@ fn main() {
body_type: .html body_type: .html
body: body body: body
} }
mut client := smtp.new_client(client_cfg) or { mut client := smtp.new_client(client_cfg) or { panic('Error configuring smtp') }
panic('Error configuring smtp') client.send(send_cfg) or { panic('Error resolving email address') }
}
client.send(send_cfg) or {
panic('Error resolving email address')
}
} }

View File

@ -9,6 +9,7 @@
* TODO: * TODO:
**********************************************************************/ **********************************************************************/
module obj module obj
import gg.m4 import gg.m4
import strconv import strconv
@ -73,7 +74,6 @@ fn get_int(s string, start_index int) (int, int) {
} }
} }
} }
} }
// println("---") // println("---")
return res * sgn, i return res * sgn, i
@ -110,18 +110,24 @@ fn parse_3f(row string, start_index int) m4.Vec4 {
// print("Here f1: $f1 $p ") // print("Here f1: $f1 $p ")
f2, p = get_float(row, p + 1) f2, p = get_float(row, p + 1)
// print("Here f2: $f2 $p ") // print("Here f2: $f2 $p ")
return m4.Vec4{e:[f32(f0), f32(f1), f32(f2), 1]!} return m4.Vec4{
e: [f32(f0), f32(f1), f32(f2), 1]!
}
} }
// reas a sequence of f32 from a string // reas a sequence of f32 from a string
fn (mut m ObjPart) parse_floats(row string, start_index int) m4.Vec4 { fn (mut m ObjPart) parse_floats(row string, start_index int) m4.Vec4 {
mut i := start_index //+ 1 mut i := start_index //+ 1
mut res_f := f64(0) mut res_f := f64(0)
mut res := m4.Vec4{e:[f32(0), 0, 0, 1]!} mut res := m4.Vec4{
e: [f32(0), 0, 0, 1]!
}
mut c := 0 mut c := 0
for true { for true {
res_f, i = get_float(row, i) res_f, i = get_float(row, i)
unsafe { res.e[c] = f32(res_f) } unsafe {
res.e[c] = f32(res_f)
}
c++ c++
i++ i++
if i >= row.len { if i >= row.len {
@ -161,7 +167,6 @@ fn (mut p Part) parse_faces(row string, start_index int, obj ObjPart) {
i++ i++
n, i = get_int(row, i + 1) n, i = get_int(row, i + 1)
} }
} }
// manage negative indexes // manage negative indexes
// NOTE: not well suporeted now // NOTE: not well suporeted now
@ -181,14 +186,15 @@ fn (mut p Part) parse_faces(row string, start_index int, obj ObjPart) {
// println("ok res: ${res}") // println("ok res: ${res}")
// println(p.faces.len) // println(p.faces.len)
p.faces << res p.faces << res
} }
// parse the obj file, if single_material is true it use only one default material // 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) { pub fn (mut obj_part ObjPart) parse_obj_buffer(rows []string, single_material bool) {
mut mat_count := 0 mut mat_count := 0
mut row_count := 0 mut row_count := 0
default_part := Part{name:"default part"} default_part := Part{
name: 'default part'
}
obj_part.part << default_part obj_part.part << default_part
// println("OBJ file has ${rows.len} rows") // println("OBJ file has ${rows.len} rows")
for c, row in rows { for c, row in rows {
@ -204,7 +210,7 @@ pub fn (mut obj_part ObjPart) parse_obj_buffer(rows []string, single_material bo
break break
} }
`m` { `m` {
if row[i..i+6] == "mtllib" { if row[i..i + 6] == 'mtllib' {
obj_part.material_file = row[i + 7..].trim_space() obj_part.material_file = row[i + 7..].trim_space()
obj_part.load_materials() obj_part.load_materials()
} }
@ -218,7 +224,7 @@ pub fn (mut obj_part ObjPart) parse_obj_buffer(rows []string, single_material bo
break break
} }
`u` { `u` {
if single_material == false && row[i..i+6] == "usemtl" { if single_material == false && row[i..i + 6] == 'usemtl' {
material := row[i + 7..].trim_space() material := row[i + 7..].trim_space()
// println("material: $material") // println("material: $material")
// manage multiple materials in an part // manage multiple materials in an part
@ -226,10 +232,13 @@ pub fn (mut obj_part ObjPart) parse_obj_buffer(rows []string, single_material bo
mat_count++ mat_count++
mut part := Part{} mut part := Part{}
if mat_count > 1 { 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} li := obj_part.part[obj_part.part.len - 1].name.last_index('_m') or {
part.name = obj_part.part[obj_part.part.len - 1].name[..li] + "_m${mat_count:02}" 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 { } else {
part.name = obj_part.part[obj_part.part.len - 1].name + "_m01" part.name = obj_part.part[obj_part.part.len - 1].name + '_m01'
} }
obj_part.part << part obj_part.part << part
} }
@ -258,7 +267,6 @@ pub fn (mut obj_part ObjPart) parse_obj_buffer(rows []string, single_material bo
// println("Vertex line: $c") // println("Vertex line: $c")
break break
} }
else { else {
obj_part.v << parse_3f(row, i + 1) obj_part.v << parse_3f(row, i + 1)
// println("$row => ${obj_part.v[obj_part.v.len-1]}") // println("$row => ${obj_part.v[obj_part.v.len-1]}")
@ -283,10 +291,10 @@ pub fn (mut obj_part ObjPart) parse_obj_buffer(rows []string, single_material bo
} }
// if c == 2 { break } // if c == 2 { break }
if c % 100000 == 0 && c > 0 { if c % 100000 == 0 && c > 0 {
println("$c rows parsed") println('$c rows parsed')
} }
} }
println("$row_count .obj Rows parsed") println('$row_count .obj Rows parsed')
// remove default part if empty // remove default part if empty
if obj_part.part.len > 1 && obj_part.part[0].faces.len == 0 { if obj_part.part.len > 1 && obj_part.part[0].faces.len == 0 {
obj_part.part = obj_part.part[1..] obj_part.part = obj_part.part[1..]
@ -295,8 +303,8 @@ pub fn (mut obj_part ObjPart) parse_obj_buffer(rows []string, single_material bo
// load the materials if found the .mtl file // load the materials if found the .mtl file
fn (mut obj_part ObjPart) load_materials() { fn (mut obj_part ObjPart) load_materials() {
rows := obj.read_lines_from_file(obj_part.material_file) rows := read_lines_from_file(obj_part.material_file)
println("Material file [${obj_part.material_file}] ${rows.len} Rows.") println('Material file [$obj_part.material_file] $rows.len Rows.')
for row in rows { for row in rows {
// println("$row") // println("$row")
mut i := 0 mut i := 0
@ -306,9 +314,11 @@ fn (mut obj_part ObjPart) load_materials() {
} }
match row[i] { match row[i] {
`n` { `n` {
if row[i..i+6] == "newmtl" { if row[i..i + 6] == 'newmtl' {
name := row[i + 6..].trim_space() name := row[i + 6..].trim_space()
mut mat := Material{name: name} mut mat := Material{
name: name
}
obj_part.mat << mat obj_part.mat << mat
break break
} }
@ -331,7 +341,7 @@ fn (mut obj_part ObjPart) load_materials() {
break break
} }
`m` { `m` {
if row[i..i+4] == "map_" { if row[i..i + 4] == 'map_' {
name := row[i..i + 6] name := row[i..i + 6]
if (i + 7) < row.len { if (i + 7) < row.len {
file_name := row[i + 7..].trim_space() file_name := row[i + 7..].trim_space()
@ -376,7 +386,7 @@ fn (mut obj_part ObjPart) load_materials() {
} }
} }
println("Material Loading Done!") println('Material Loading Done!')
} }
//============================================================================== //==============================================================================
@ -413,7 +423,7 @@ pub fn (mut obj_part ObjPart) get_buffer(in_part_list []int) Skl_buffer {
mut v_count_index := 0 mut v_count_index := 0
mut out_buf := Skl_buffer{} mut out_buf := Skl_buffer{}
mut cache := map[string]int mut cache := map[string]int{}
mut cache_hit := 0 mut cache_hit := 0
// has_normals := obj_part.vn.len > 0 // has_normals := obj_part.vn.len > 0
@ -469,7 +479,7 @@ pub fn (mut obj_part ObjPart) get_buffer(in_part_list []int) Skl_buffer {
v_index := face[vertex_index][0] // vertex index v_index := face[vertex_index][0] // vertex index
n_index := face[vertex_index][1] // normal index n_index := face[vertex_index][1] // normal index
t_index := face[vertex_index][2] // uv texture index t_index := face[vertex_index][2] // uv texture index
key := "${v_index}_${n_index}_${t_index}" key := '${v_index}_${n_index}_$t_index'
if key !in cache { if key !in cache {
cache[key] = v_count_index cache[key] = v_count_index
mut pnct := Vertex_pnct{ mut pnct := Vertex_pnct{
@ -497,9 +507,7 @@ pub fn (mut obj_part ObjPart) get_buffer(in_part_list []int) Skl_buffer {
out_buf.ibuf << u32(cache[key]) out_buf.ibuf << u32(cache[key])
cache_hit++ cache_hit++
} }
} }
} }
} }
@ -520,29 +528,29 @@ pub fn (mut obj_part ObjPart) get_buffer(in_part_list []int) Skl_buffer {
//============================================================================== //==============================================================================
// print on the console the summary of the .obj model loaded // print on the console the summary of the .obj model loaded
pub fn (obj_part ObjPart) summary() { pub fn (obj_part ObjPart) summary() {
println("---- Stats ----") println('---- Stats ----')
println("vertices: ${obj_part.v.len}") println('vertices: $obj_part.v.len')
println("normals : ${obj_part.vn.len}") println('normals : $obj_part.vn.len')
println("uv : ${obj_part.vt.len}") println('uv : $obj_part.vt.len')
println("parts : ${obj_part.part.len}") println('parts : $obj_part.part.len')
// Parts // Parts
println("---- Parts ----") println('---- Parts ----')
for c, x in obj_part.part { for c, x in obj_part.part {
println("${c:3} [${x.name:-16}] mat:[${x.material:-10}] ${x.faces.len:7} faces") println('${c:3} [${x.name:-16}] mat:[${x.material:-10}] ${x.faces.len:7} faces')
} }
// Materials // Materials
println("---- Materials ----") println('---- Materials ----')
println("Material dict: ${obj_part.mat_map.keys()}") println('Material dict: $obj_part.mat_map.keys()')
for c, mat in obj_part.mat { for c, mat in obj_part.mat {
println("${c:3} [${mat.name:-16}]") println('${c:3} [${mat.name:-16}]')
for k, v in mat.ks { for k, v in mat.ks {
print("$k = $v") print('$k = $v')
} }
for k, v in mat.ns { for k, v in mat.ns {
println("$k = $v") println('$k = $v')
} }
for k, v in mat.maps { for k, v in mat.maps {
println("$k = $v") println('$k = $v')
} }
} }
} }
@ -581,7 +589,7 @@ pub fn tst(){
res := m4.mul_vec(ort, a) res := m4.mul_vec(ort, a)
println("res:\n${res}") println("res:\n${res}")
*/ */
s := "K 1 1 1" s := 'K 1 1 1'
r := strconv.atof_quick(s[1..s.len - 1]) r := strconv.atof_quick(s[1..s.len - 1])
println(r) println(r)
} }

View File

@ -9,6 +9,7 @@
* TODO: * TODO:
**********************************************************************/ **********************************************************************/
module obj module obj
import sokol.gfx import sokol.gfx
import gg.m4 import gg.m4
import math import math
@ -46,10 +47,10 @@ pub fn destroy_texture(sg_img C.sg_image) {
} }
pub fn load_texture(file_name string) C.sg_image { pub fn load_texture(file_name string) C.sg_image {
buffer := obj.read_bytes_from_file(file_name) buffer := read_bytes_from_file(file_name)
stbi.set_flip_vertically_on_load(true) stbi.set_flip_vertically_on_load(true)
img := stbi.load_from_memory(buffer.data, buffer.len) or { img := stbi.load_from_memory(buffer.data, buffer.len) or {
eprintln("Texure file: [$file_name] ERROR!") eprintln('Texure file: [$file_name] ERROR!')
exit(0) exit(0)
} }
res := create_texture(int(img.width), int(img.height), img.data) res := create_texture(int(img.width), int(img.height), img.data)
@ -91,7 +92,7 @@ pub fn (mut obj_part ObjPart) create_pipeline(in_part []int, shader C.sg_shader,
} }
index_buffer_desc.@type = .indexbuffer index_buffer_desc.@type = .indexbuffer
index_buffer_desc.label = "indbuf_part_${in_part:03}".str index_buffer_desc.label = 'indbuf_part_${in_part:03}'.str
ibuf := gfx.make_buffer(&index_buffer_desc) ibuf := gfx.make_buffer(&index_buffer_desc)
mut pipdesc := C.sg_pipeline_desc{} mut pipdesc := C.sg_pipeline_desc{}
@ -166,7 +167,7 @@ pub fn (mut obj_part ObjPart) init_render_data(texture C.sg_image) {
txt = obj_part.texture[file_name] txt = obj_part.texture[file_name]
// println("Texture [${file_name}] => from CACHE") // println("Texture [${file_name}] => from CACHE")
} else { } else {
txt = obj.load_texture(file_name) txt = load_texture(file_name)
obj_part.texture[file_name] = txt obj_part.texture[file_name] = txt
// println("Texture [${file_name}] => LOADED") // println("Texture [${file_name}] => LOADED")
} }
@ -179,7 +180,7 @@ pub fn (mut obj_part ObjPart) init_render_data(texture C.sg_image) {
// println("Texture array len: ${obj_part.texture.len}") // println("Texture array len: ${obj_part.texture.len}")
// println("Calc bounding box.") // println("Calc bounding box.")
obj_part.calc_bbox() obj_part.calc_bbox()
println("init_render_data DONE!") println('init_render_data DONE!')
} }
pub fn (obj_part ObjPart) bind_and_draw(rend_data_index int, in_data Shader_data) u32 { pub fn (obj_part ObjPart) bind_and_draw(rend_data_index int, in_data Shader_data) u32 {
@ -187,7 +188,7 @@ pub fn (obj_part ObjPart) bind_and_draw(rend_data_index int, in_data Shader_data
mut part_render_data := obj_part.rend_data[rend_data_index] mut part_render_data := obj_part.rend_data[rend_data_index]
// pass light position // pass light position
mut tmp_fs_params := obj.Tmp_fs_param{} mut tmp_fs_params := Tmp_fs_param{}
tmp_fs_params.ligth = in_data.fs_data.ligth tmp_fs_params.ligth = in_data.fs_data.ligth
if part_render_data.material in obj_part.mat_map { if part_render_data.material in obj_part.mat_map {
@ -254,19 +255,39 @@ pub fn (obj_part ObjPart) bind_and_draw_all(in_data Shader_data) u32 {
} }
pub fn (mut obj_part ObjPart) calc_bbox() { 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.max = m4.Vec4{
obj_part.min = m4.Vec4{e:[f32( math.max_f32), math.max_f32, math.max_f32, 0]!} 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 { 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[0] > obj_part.max.e[0] {
if v.e[1] > obj_part.max.e[1] { obj_part.max.e[1] = v.e[1] } obj_part.max.e[0] = v.e[0]
if v.e[2] > obj_part.max.e[2] { obj_part.max.e[2] = v.e[2] } }
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[0] < obj_part.min.e[0] {
if v.e[1] < obj_part.min.e[1] { obj_part.min.e[1] = v.e[1] } obj_part.min.e[0] = v.e[0]
if v.e[2] < obj_part.min.e[2] { obj_part.min.e[2] = v.e[2] } }
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() val1 := obj_part.max.mod3()
val2 := obj_part.min.mod3() val2 := obj_part.min.mod3()
if val1 > val2 { obj_part.radius = f32(val1) } else { obj_part.radius = f32(val2) } 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}") // println("BBox: ${obj_part.min} <=> ${obj_part.max}\nRadius: ${obj_part.radius}")
} }

View File

@ -9,6 +9,7 @@
* TODO: * TODO:
**********************************************************************/ **********************************************************************/
module obj module obj
import gg.m4 import gg.m4
// part struct mantain the fae indexes list // part struct mantain the fae indexes list
@ -56,7 +57,6 @@ pub mut:
t_m m4.Mat4 = m4.unit_m4() // transform matrix for this ObjPart t_m m4.Mat4 = m4.unit_m4() // transform matrix for this ObjPart
// child []ObjPart // childs // child []ObjPart // childs
// stats // stats
min m4.Vec4 // min 3d position in the ObjPart min m4.Vec4 // min 3d position in the ObjPart
max m4.Vec4 // max 3d position in the ObjPart max m4.Vec4 // max 3d position in the ObjPart
@ -83,9 +83,15 @@ pub mut:
pub struct Tmp_fs_param { pub struct Tmp_fs_param {
pub mut: pub mut:
ligth m4.Vec4 ligth m4.Vec4
ka m4.Vec4 = m4.Vec4{e:[f32(0.1), 0.0, 0.0, 1.0]!} ka m4.Vec4 = m4.Vec4{
kd m4.Vec4 = m4.Vec4{e:[f32(0.5), 0.5, 0.5, 1.0]!} e: [f32(0.1), 0.0, 0.0, 1.0]!
ks m4.Vec4 = m4.Vec4{e:[f32(1.0), 1.0, 1.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 // shader data for the rendering

View File

@ -1,21 +1,22 @@
module obj module obj
import os import os
// read a file as single lines // read a file as single lines
pub fn read_lines_from_file(file_path string) []string { pub fn read_lines_from_file(file_path string) []string {
mut path := "" mut path := ''
mut rows := []string{} mut rows := []string{}
$if android { $if android {
path = "models/"+file_path path = 'models/' + file_path
bts := os.read_apk_asset(path) or { bts := os.read_apk_asset(path) or {
eprintln("File [$path] NOT FOUND!") eprintln('File [$path] NOT FOUND!')
return rows return rows
} }
rows = bts.bytestr().split_into_lines() rows = bts.bytestr().split_into_lines()
} $else { } $else {
path = "assets/models/"+file_path path = 'assets/models/' + file_path
rows = os.read_lines(path) or { rows = os.read_lines(path) or {
eprintln("File [$path] NOT FOUND!") eprintln('File [$path] NOT FOUND!')
return rows return rows
} }
} }
@ -24,18 +25,18 @@ pub fn read_lines_from_file(file_path string) []string {
// read a file as []byte // read a file as []byte
pub fn read_bytes_from_file(file_path string) []byte { pub fn read_bytes_from_file(file_path string) []byte {
mut path := "" mut path := ''
mut buffer := []byte{} mut buffer := []byte{}
$if android { $if android {
path = "models/"+file_path path = 'models/' + file_path
buffer = os.read_apk_asset(path) or { buffer = os.read_apk_asset(path) or {
eprintln("Texure file: [$path] NOT FOUND!") eprintln('Texure file: [$path] NOT FOUND!')
exit(0) exit(0)
} }
} $else { } $else {
path = "assets/models/"+file_path path = 'assets/models/' + file_path
buffer = os.read_bytes(path) or { buffer = os.read_bytes(path) or {
eprintln("Texure file: [$path] NOT FOUND!") eprintln('Texure file: [$path] NOT FOUND!')
exit(0) exit(0)
} }
} }

View File

@ -44,7 +44,6 @@ import sokol.sapp
import sokol.gfx import sokol.gfx
import sokol.sgl import sokol.sgl
import time import time
import os import os
import obj import obj
@ -52,6 +51,7 @@ import obj
#flag -I @VMODROOT/. #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) #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 fn C.gouraud_shader_desc(gfx.Backend) &C.sg_shader_desc
const ( const (
@ -70,14 +70,11 @@ mut:
mouse_x int = -1 mouse_x int = -1
mouse_y int = -1 mouse_y int = -1
scroll_y int // mouse wheel value scroll_y int // mouse wheel value
// time // time
ticks i64 ticks i64
// model // model
obj_part &obj.ObjPart obj_part &obj.ObjPart
n_vertex u32 n_vertex u32
// init parameters // init parameters
file_name string file_name string
single_material_flag bool single_material_flag bool
@ -88,12 +85,15 @@ mut:
******************************************************************************/ ******************************************************************************/
[inline] [inline]
fn vec4(x f32, y f32, z f32, w f32) m4.Vec4 { fn vec4(x f32, y f32, z f32, w f32) m4.Vec4 {
return m4.Vec4{e:[x, y, z, w]!} 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 { 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 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 := 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 view_proj := view * proj
rxm := m4.rotate(m4.rad(rx), vec4(f32(1), 0, 0, 0)) rxm := m4.rotate(m4.rad(rx), vec4(f32(1), 0, 0, 0))
@ -108,7 +108,11 @@ fn calc_matrices(w f32, h f32, rx f32, ry f32, in_scale f32, pos m4.Vec4) obj.Ma
nm := mv.inverse().transpose() // normal matrix nm := mv.inverse().transpose() // normal matrix
mvp := mv * view_proj // model view projection mvp := mv * view_proj // model view projection
return obj.Mats{mv:mv, mvp:mvp, nm:nm} return obj.Mats{
mv: mv
mvp: mvp
nm: nm
}
} }
fn draw_model(app App, model_pos m4.Vec4) u32 { fn draw_model(app App, model_pos m4.Vec4) u32 {
@ -134,8 +138,8 @@ fn draw_model(app App, model_pos m4.Vec4) u32 {
mats := calc_matrices(dw, dh, rot[0], rot[1], zoom_scale, model_pos) mats := calc_matrices(dw, dh, rot[0], rot[1], zoom_scale, model_pos)
mut tmp_vs_param := obj.Tmp_vs_param{ mut tmp_vs_param := obj.Tmp_vs_param{
mv: mats.mv, mv: mats.mv
mvp: mats.mvp, mvp: mats.mvp
nm: mats.nm nm: mats.nm
} }
@ -240,7 +244,6 @@ fn my_init(mut app App) {
app.texture = obj.create_texture(1, 1, tmp_txt) app.texture = obj.create_texture(1, 1, tmp_txt)
free(tmp_txt) free(tmp_txt)
} }
// glsl // glsl
app.obj_part.init_render_data(app.texture) app.obj_part.init_render_data(app.texture)
app.init_flag = true app.init_flag = true
@ -280,7 +283,8 @@ fn my_event_manager(mut ev gg.Event, mut app App) {
/****************************************************************************** /******************************************************************************
* Main * Main
******************************************************************************/ ******************************************************************************/
[console] // is needed for easier diagnostics on windows // is needed for easier diagnostics on windows
[console]
fn main() { fn main() {
/* /*
obj.tst() obj.tst()
@ -293,7 +297,7 @@ fn main() {
obj_part: 0 obj_part: 0
} }
app.file_name = "v.obj_" // default object is the v logo app.file_name = 'v.obj_' // default object is the v logo
app.single_material_flag = false app.single_material_flag = false
$if !android { $if !android {
@ -302,7 +306,7 @@ fn main() {
eprintln('file_name : name of the .obj file, it must be in the folder "assets/models"') 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 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(' 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') eprintln("single_material_flag: if true the viewer use for all the model's parts the default material\n")
exit(0) exit(0)
} }
@ -312,8 +316,8 @@ fn main() {
if os.args.len >= 3 { if os.args.len >= 3 {
app.single_material_flag = os.args[2].bool() app.single_material_flag = os.args[2].bool()
} }
println("Loading model: $app.file_name") println('Loading model: $app.file_name')
println("Using single material: $app.single_material_flag") println('Using single material: $app.single_material_flag')
} }
app.gg = gg.new_context( app.gg = gg.new_context(

View File

@ -48,7 +48,8 @@ fn init(mut state AppState) {
// or use DroidSerif-Regular.ttf // or use DroidSerif-Regular.ttf
if bytes := os.read_bytes(os.resource_abs_path('../assets/fonts/RobotoMono-Regular.ttf')) { if bytes := os.read_bytes(os.resource_abs_path('../assets/fonts/RobotoMono-Regular.ttf')) {
println('loaded font: $bytes.len') println('loaded font: $bytes.len')
state.font_normal = C.fonsAddFontMem(state.fons, 'sans', bytes.data, bytes.len, false) state.font_normal = C.fonsAddFontMem(state.fons, 'sans', bytes.data, bytes.len,
false)
} }
} }
@ -101,7 +102,8 @@ fn (state &AppState) render_font() {
C.fonsSetSize(state.fons, 20.0) C.fonsSetSize(state.fons, 20.0)
C.fonsSetFont(state.fons, state.font_normal) C.fonsSetFont(state.fons, state.font_normal)
C.fonsSetColor(state.fons, blue) C.fonsSetColor(state.fons, blue)
C.fonsDrawText(state.fons, dx, dy, c'Now is the time for all good men to come to the aid of the party.', C.NULL) C.fonsDrawText(state.fons, dx, dy, c'Now is the time for all good men to come to the aid of the party.',
C.NULL)
dx = 300 dx = 300
dy = 350 dy = 350
C.fonsSetAlign(state.fons, C.FONS_ALIGN_LEFT | C.FONS_ALIGN_BASELINE) C.fonsSetAlign(state.fons, C.FONS_ALIGN_LEFT | C.FONS_ALIGN_BASELINE)

View File

@ -6,7 +6,6 @@ import sokol.sfons
import os import os
import time import time
const ( const (
text = ' text = '
Once upon a midnight dreary, while I pondered, weak and weary, Once upon a midnight dreary, while I pondered, weak and weary,
@ -102,7 +101,8 @@ fn init(user_data voidptr) {
// or use DroidSerif-Regular.ttf // or use DroidSerif-Regular.ttf
if bytes := os.read_bytes(os.resource_abs_path('../assets/fonts/RobotoMono-Regular.ttf')) { if bytes := os.read_bytes(os.resource_abs_path('../assets/fonts/RobotoMono-Regular.ttf')) {
println('loaded font: $bytes.len') println('loaded font: $bytes.len')
state.font_normal = C.fonsAddFontMem(state.fons, 'sans', bytes.data, bytes.len, false) state.font_normal = C.fonsAddFontMem(state.fons, 'sans', bytes.data, bytes.len,
false)
} }
} }
@ -118,7 +118,6 @@ fn frame(user_data voidptr) {
} }
const ( const (
black = C.sfons_rgba(0, 0, 0, 255) black = C.sfons_rgba(0, 0, 0, 255)
) )

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by an MIT license file distributed with this software package // Use of this source code is governed by an MIT license file distributed with this software package
module particle module particle
import vec2 import particle.vec2
import sokol.sgl import sokol.sgl
const ( const (
@ -16,9 +16,9 @@ pub fn new(location vec2.Vec2) &Particle {
location: location location: location
velocity: vec2.Vec2{0, 0} velocity: vec2.Vec2{0, 0}
acceleration: vec2.Vec2{0, 0} acceleration: vec2.Vec2{0, 0}
color: default_v_color color: particle.default_v_color
life_time: default_life_time life_time: particle.default_life_time
life_time_init: default_life_time life_time_init: particle.default_life_time
} }
return p return p
} }
@ -75,7 +75,7 @@ pub fn (mut p Particle) reset() {
p.acceleration.zero() p.acceleration.zero()
p.velocity.zero() p.velocity.zero()
// p.color = Color{93, 136, 193, 255} // p.color = Color{93, 136, 193, 255}
p.color = default_v_color p.color = particle.default_v_color
p.life_time = default_life_time p.life_time = particle.default_life_time
p.life_time_init = p.life_time p.life_time_init = p.life_time
} }

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by an MIT license file distributed with this software package // Use of this source code is governed by an MIT license file distributed with this software package
module particle module particle
import vec2 import particle.vec2
import rand import rand
import sokol.sgl import sokol.sgl

View File

@ -117,7 +117,6 @@ struct RIFFFormat {
} }
fn read_wav_file_samples(fpath string) ?[]f32 { fn read_wav_file_samples(fpath string) ?[]f32 {
mut res := []f32{} mut res := []f32{}
// eprintln('> read_wav_file_samples: $fpath -------------------------------------------------') // eprintln('> read_wav_file_samples: $fpath -------------------------------------------------')
mut bytes := os.read_bytes(fpath) ? mut bytes := os.read_bytes(fpath) ?
@ -207,5 +206,4 @@ fn read_wav_file_samples(fpath string) ?[]f32 {
} }
} }
return res return res
} }

View File

@ -71,7 +71,9 @@ fn data_get() []SiteConfig {
cat: .web cat: .web
alias: 'marketplace' alias: 'marketplace'
path_code: '/Users/despiegk/codewww/github/threefoldfoundation/www_threefold_marketplace' path_code: '/Users/despiegk/codewww/github/threefoldfoundation/www_threefold_marketplace'
domains: ['now.threefold.io', 'marketplace.threefold.io', 'now.threefold.me', 'marketplace.threefold.me'] domains: ['now.threefold.io', 'marketplace.threefold.io', 'now.threefold.me',
'marketplace.threefold.me',
]
descr: 'apps for community builders, runs on top of evdc' descr: 'apps for community builders, runs on top of evdc'
}, SiteConfig{ }, SiteConfig{
name: 'www_conscious_internet' name: 'www_conscious_internet'
@ -81,9 +83,8 @@ fn data_get() []SiteConfig {
cat: .web cat: .web
alias: 'conscious_internet' alias: 'conscious_internet'
path_code: '/Users/despiegk/codewww/github/threefoldfoundation/www_conscious_internet' path_code: '/Users/despiegk/codewww/github/threefoldfoundation/www_conscious_internet'
domains: ['www.consciousinternet.org', 'eco.threefold.io', 'community.threefold.io', 'eco.threefold.me', domains: ['www.consciousinternet.org', 'eco.threefold.io', 'community.threefold.io',
'community.threefold.me', 'eco.threefold.me', 'community.threefold.me']
]
descr: 'community around threefold, partners, friends, ...' descr: 'community around threefold, partners, friends, ...'
}, SiteConfig{ }, SiteConfig{
name: 'www_threefold_tech' name: 'www_threefold_tech'

View File

@ -393,19 +393,11 @@ fn (mut b Buffer) move_to_word(movement Movement) {
} }
fn imax(x int, y int) int { fn imax(x int, y int) int {
return if x < y { return if x < y { y } else { x }
y
} else {
x
}
} }
fn imin(x int, y int) int { fn imin(x int, y int) int {
return if x < y { return if x < y { x } else { y }
x
} else {
y
}
} }
struct Cursor { struct Cursor {

1
examples/v_script.vsh 100755 → 100644
View File

@ -1,4 +1,5 @@
#!/usr/local/bin/v run #!/usr/local/bin/v run
// The shebang above associates the file to V on Unix-like systems, // The shebang above associates the file to V on Unix-like systems,
// so it can be run just by specifying the path to the file // so it can be run just by specifying the path to the file
// once it's made executable using `chmod +x`. // once it's made executable using `chmod +x`.

View File

@ -18,15 +18,14 @@ pub fn (mut app App) index() vweb.Result {
return $vweb.html() return $vweb.html()
} }
[post] ['/upload'; post]
['/upload']
pub fn (mut app App) upload() vweb.Result { pub fn (mut app App) upload() vweb.Result {
fdata := app.files['upfile'] fdata := app.files['upfile']
mut files := []vweb.RawHtml{} mut files := []vweb.RawHtml{}
for d in fdata { for d in fdata {
files << d.data.replace_each(['\n', '<br>', '\n\r', '<br>' '\t', ' ', ' ', '&nbsp;']) files << d.data.replace_each(['\n', '<br>', '\n\r', '<br>', '\t', ' ', ' ', '&nbsp;'])
} }
return $vweb.html() return $vweb.html()

View File

@ -1,7 +1,6 @@
// Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved. // Copyright (c) 2019-2021 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license // Use of this source code is governed by an MIT license
// that can be found in the LICENSE file. // that can be found in the LICENSE file.
import os import os
fn main() { fn main() {
@ -9,15 +8,14 @@ fn main() {
if os.args.len != 2 { if os.args.len != 2 {
println('usage: word_counter [text_file]') println('usage: word_counter [text_file]')
println('using $path') println('using $path')
} } else {
else {
path = os.args[1] path = os.args[1]
} }
contents := os.read_file(path.trim_space()) or { contents := os.read_file(path.trim_space()) or {
println('failed to open $path') println('failed to open $path')
return return
} }
mut m := map[string]int mut m := map[string]int{}
for word in extract_words(contents) { for word in extract_words(contents) {
m[word]++ m[word]++
} }
@ -37,8 +35,7 @@ fn extract_words(contents string) []string {
for space_splitted in contents.to_lower().split(' ') { for space_splitted in contents.to_lower().split(' ') {
if space_splitted.contains('\n') { if space_splitted.contains('\n') {
splitted << space_splitted.split('\n') splitted << space_splitted.split('\n')
} } else {
else {
splitted << space_splitted splitted << space_splitted
} }
} }

View File

@ -18,4 +18,3 @@ fn main() {
println('done') println('done')
*/ */
} }