~nch/gamelog

ref: 2860fd647c20bdd08c60e5362e2ecffd9a4c1961 gamelog/game.nim -rw-r--r-- 14.1 KiB View raw
2860fd64 — nc minor reorg 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# set makeprg=nim\ c\ df.nim\ &&\ ./df
import glm
import opengl
import glfw
import gara
import tables
import strutils
import sugar
import sets
import macros
import math
import complex
import options
import bitops
import draw_util
import debug_draw

const max_entities = 1024;

# TODO: soa this sucker
type
    Entity = tuple[id: uint16]
    Mesh = tuple[filepath: string, vao: uint32, nfaces: uint16, nverts: uint16]
    Texture = tuple[filepath: string, handle: uint64, width: uint16, height: uint16]
    Drawable = tuple[mesh_id: uint16, pos: Vec3f]
    TextureBinding = tuple[drawable_id: uint16, texture_handle: uint64, texture_name: string]

# TODO: use fixed allocation and fill in the values
var entities = newSeq[Entity]()
var meshes = newSeq[Mesh]()
var textures = newSeq[Texture]()
var drawables = newSeq[Drawable]()
var texture_bindings = newSeq[TextureBinding]()

# filter a list based on pattern matching
macro where(list: typed, bl: untyped): untyped =
    let T = list.get_type_inst()[1]

    result = quote do:
        var s = newSeq[`T`]()
        for d in `list`:
            if d.matches(`bl`):
                s.add(d)
        s

when isMainModule:
    assert(where(@[1,2,3], 1) == @[1])
    assert(where(@[(1, 2), (1, 2), (2, 3)], (1, @n)) == @[(1, 2), (1, 2)])


## math

type
    Plane* = tuple[pos: Vec3f, normal: Vec3f]
    Ellipse* = tuple[pos: Vec3f, radius: Vec3f]
    Triangle* = array[3, Vec3f]

proc is_facing(p: Plane, dir: Vec3f): bool =
    return p.normal.dot(dir) <= 0

proc point_distance(p: Plane, point: Vec3f): float =
    let v = point - p.pos
    return v.dot(p.normal)

proc triangle_plane(t: Triangle): Plane =
    let n: Vec3f = (t[1] - t[0]).cross(t[2] - t[0]).normalize()
    return (pos: t[0], normal: n).Plane

proc get_lowest_root(a, b, c, max_r: float32): Option[float32] =
    let det = b * b - 4 * a * c
    if det < 0: return none(float32)

    let sqrt_d = sqrt(det)
    var r1 = (-b - sqrt_d) / (2 * a)
    var r2 = (-b + sqrt_d) / (2 * a)

    if r1 > r2: swap(r1, r2)
    if r1 > 0 and r1 < max_r:
        return some(r1)
    if r2 > 0 and r2 < max_r:
        return some(r2)



proc in_triangle(p: Vec3f, t: Triangle): bool =
    let e10 = t[1] - t[0]
    let e20 = t[2] - t[0]

    let a = e10.dot(e10)
    let b = e10.dot(e20)
    let c = e20.dot(e20)
    let ac_bb = (a * c) - (b * b)
    let vp = vec3f(p.x - t[0].x, p.y - t[0].y, p.z - t[0].z)

    let d = vp.dot(e10)
    let e = vp.dot(e20)

    let x = (d * c) - (e * b)
    let y = (e * a) - (d * b)
    let z = x + y - ac_bb

    return bitand(bitand(z.uint32, bitnot(bitor(x.uint32, y.uint32))), 0x80000000.uint32) != 0
proc parse_obj(path: string): (seq[float32], seq[uint16]) =
    var
        vertices = newSeq[Vec3f]()
        normals = newSeq[Vec3f]()
        uvs = newSeq[Vec2f]()
        faces = newSeq[seq[seq[int]]]()

    for line in path.lines:
        let tokens = line.split(' ')
        match(tokens):
            @[@head, * @rest]:
                if head[0] == '#': # skip comments
                    continue
                case head:
                of "v":
                    let fs = rest.map(parse_float)
                    assert fs.len == 3
                    vertices.add(vec3f(fs[0], fs[1], fs[2]))
                of "vn":
                    let fs = rest.map(parse_float)
                    assert fs.len == 3
                    normals.add(vec3f(fs[0], fs[1], fs[2]))
                of "vt":
                    let fs = rest.map(parse_float)
                    assert fs.len == 2
                    # !!! opengl flips the y coordinates of UVs from what obj exports. which is fun.
                    uvs.add(vec2f(fs[0], 1 - fs[1]))
                of "f":
                    assert rest.len == 3, "only supports triangles for now"
                    faces.add(rest.map(x => x.split('/').map(y => y.parse_int)))
                else:
                    echo "unhandled obj directive: " & head
            _:
                echo "unable to handle line: " & tokens

    type
        VertData = array[8, float32] # (vx, vy, vz, vnx, vny, vnz, vu, vv)
    var
        element_indices = newSeq[uint16]()
        data = initOrderedSet[VertData]()


    for face in faces:
        for field in face:
            let vi = field[0] - 1
            let vt = field[1] - 1
            let vn = field[2] - 1
            let new_vert: VertData =  [vertices[vi].x, vertices[vi].y, vertices[vi].z,
                                       normals[vn].x, normals[vn].y, normals[vn].z,
                                       uvs[vt].x, uvs[vt].y]
            if new_vert in data:
                for i, v in data.pairs:
                    if new_vert == v:
                        element_indices.add(i.uint16)
                        break
            else:
                data.incl(new_vert)
                element_indices.add((data.len - 1).uint16)

    assert data.len > 0
    assert element_indices.len > 0

    var r = newSeq[float32]()
    for d in data.items:
        r.add(d)
    return (r, element_indices)

proc check_collision*(e: Ellipse, vel: Vec3f, tri: Triangle): Option[Vec3f] =
    let tp = triangle_plane(tri)
    if not tp.is_facing(-vel):
        return

    let dist = tp.point_distance(e.pos)
    let norm_dot_vel = tp.normal.dot(vel)
    var embedded = false
    var t0, t1: float # time of start/stop intersection

    if norm_dot_vel == 0: # parallel
        if abs(dist) >= 1:
            return
        else:
            embedded = true
            t0 = 0
            t1 = 1
    else: # not parallel
        t0 = (-1 - dist) / norm_dot_vel
        t1 = ( 1 - dist) / norm_dot_vel

        if t0 > t1:
            swap(t0, t1)

        if t0 > 1 or t1 < 0:
            return

        t0 = t0.clamp(0, 1)
        t1 = t1.clamp(0, 1)

    var found_col = false
    var t = 1.0
    var col_point: Vec3f

    if not embedded:
        let plane_intersection = (e.pos - tp.normal) + (t0.float32 * vel)
        if plane_intersection.in_triangle(tri):
            found_col = true
            t = t0
            col_point = plane_intersection

    let vel_length2 = vel.length2()

    if not found_col:
        # check points
        for p in tri:
            {.unroll: 3.}
            let a = vel_length2
            let b = 2.float32 * vel.dot(e.pos - p)
            let c = (p - e.pos).length2() - 1.float32
            let r = get_lowest_root(a, b, c, t)
            if r.is_some():
                t = r.get()
                found_col = true
                col_point = p


        # check edges
        for pair in [(tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])]:
            {.unroll: 3.}
            let edge = pair[1] - pair[0]
            let pos_to_vert = pair[0] - e.pos
            let edge_len2 = edge.length2()
            let edge_dot_vel = edge.dot(vel)
            let edge_dot_pos_to_vert = edge.dot(pos_to_vert)

            let a = edge_len2 * -vel_length2 + edge_dot_vel * edge_dot_vel
            let b = edge_len2 * (2 * vel.dot(pos_to_vert)) - 2 * edge_dot_vel * edge_dot_pos_to_vert
            let c = edge_len2 * (1 - pos_to_vert.length2()) + edge_dot_pos_to_vert * edge_dot_pos_to_vert

            let r = get_lowest_root(a, b, c, t)
            if r.is_some():
                let f = (edge_dot_vel * r.get() - edge_dot_pos_to_vert) / edge_len2
                if f >= 0 and f <= 1:
                    t = r.get()
                    found_col = true
                    col_point = pair[0] + f * edge

    if found_col:
        return some(col_point)

proc load_mesh(path: string): uint16 =
    let (vert_data, face_indices) = parse_obj(path)
    let vao = make_mesh(vert_data, face_indices)
    meshes.add((filepath: path, vao: vao.uint32, nfaces: face_indices.len.uint16, nverts: (face_indices.len * 3).uint16).Mesh)
    return (meshes.len - 1).uint16

if is_main_module:
    var cam_pos = vec3f(0, 1, 2)
    var cam_look = vec3f(0, 0, 1)
    let cam_up = vec3f(0, 1, 0)
    var cam_yaw: float = radians(0.0)
    var cam_pitch: float = radians(90.0)

    let width = 800
    let height = 600

    var last_x = (width/2).float64
    var last_y = (height/2).float64

    proc cursor_pos_callback(w: Window, pos: tuple[x, y: float64]) =
        let dx = last_x - pos.x
        let dy = last_y - pos.y
        last_x = pos.x
        last_y = pos.y
        cam_pitch += (dy * 0.1)
        cam_yaw -= (dx * 0.1)
        cam_look.x = cos(radians(cam_pitch)) * cos(radians(cam_yaw))
        cam_look.y = sin(radians(cam_pitch))
        cam_look.z = cos(radians(cam_pitch)) * sin(radians(cam_yaw))
        cam_look = cam_look.normalize()

    ###

    glfw.initialize()

    load_extensions()

    var c = DefaultOpenglWindowConfig
    c.title = "game"
    c.version = glv45

    var w = new_window(c)
    w.cursor_position_cb = cursor_pos_callback
    w.cursor_mode = cm_disabled

    glfw.make_context_current(w)
    var debug = init_debug()

    echo "Version: ", cast[cstring](gl_get_string(GL_VERSION))

    ###

    let prog = make_program((GL_VERTEX_SHADER, """
#version 450 core
#extension GL_ARB_bindless_texture : require
    layout(location = 0) in vec3 vpos;
    layout(location = 1) in vec3 norm;
    layout(location = 2) in vec2 iuv;
    uniform mat4 M;
    uniform mat4 MVP;

    uniform mat4 lightSpaceMatrix;

    out vec3 normal;
    out vec3 worldPos;
    out vec4 fragPosLightSpace;
    out vec2 uv;
    void main() {
        gl_Position = MVP * vec4(vpos, 1.0);
        uv = iuv;
        worldPos = (M * vec4(vpos, 1.0)).xyz;
        fragPosLightSpace = lightSpaceMatrix * vec4(worldPos, 1.0);
        normal = norm;
    }
    """),
    (GL_FRAGMENT_SHADER, """
#version 450 core
#extension GL_ARB_bindless_texture : require
    in vec3 normal;
    in vec3 worldPos;
    in vec4 fragPosLightSpace;
    in vec2 uv;
    out vec3 color;
    layout(bindless_sampler, location=1) uniform sampler2D diffuse;

    void main() {
        vec3 lightPos = vec3(4, 4, 4);
        vec3 n = normalize(normal);
        vec3 lightDir = normalize(lightPos - worldPos);
        float diff = max(dot(n, lightDir), 0.0);
        color = diff * texture(diffuse, uv).xyz;
    }
    """
    ))

    let wireframe_prog = make_program((GL_VERTEX_SHADER, """
#version 450 core
    layout(location = 0) in vec3 vpos;
    layout(location = 1) in vec3 norm;
    layout(location = 2) in vec2 iuv;
    uniform mat4 MVP;

    void main() {
       gl_Position = MVP * vec4(vpos, 1.0);
    }
    """),
    (GL_GEOMETRY_SHADER, """
#version 450

    layout (triangles) in;
    layout (line_strip, max_vertices=3) out;

    void main(void)
    {
        int i;
        for (i = 0; i < gl_in.length(); i++)
        {
            gl_Position = gl_in[i].gl_Position; //Pass through
            EmitVertex();
        }
        EndPrimitive();
    }
    """
    ),
    (GL_FRAGMENT_SHADER, """
#version 450 core

    out vec3 color;
    uniform sampler2D diffuse;

    void main() {
        color = vec3(0, 1, 1);
    }
    """
    ))

    let player_mesh = load_mesh("ninja.obj")
    drawables.add((mesh_id: player_mesh, pos: vec3f(0, 0, 0)).Drawable)

    let ninja_tex = load_texture("ninja_mask.png").Texture
    textures.insert(ninja_tex)
    let test_tex = load_texture("test.png").Texture
    textures.insert(test_tex)
    texture_bindings.insert((player_mesh, ninja_tex.handle, "diffuse").TextureBinding)

    let terrain_id = load_mesh("terrain.obj")
    drawables.add((mesh_id: terrain_id, pos: vec3f(0, 0, 0)).Drawable)
    texture_bindings.insert((terrain_id, test_tex.handle, "diffuse").TextureBinding)

    gl_clear_color(0, 0, 0, 1)
    gl_clear_depth(1)
    gl_enable(GL_DEPTH_TEST)
    gl_depth_func(GL_LEQUAL)

    var ell = (pos: vec3f(0, 0, 0), radius: vec3f(1, 1, 1)).Ellipse

    let proj: Mat4[float32] = perspective[float32](Pi / 4, width.float32 / height.float32, 0.1, 100)

    let use_progs = [prog, wireframe_prog]
    var use_prog_i = 0
    var use_prog = use_progs[use_prog_i]

    proc keyboard_callback(w: Window, key: Key, scancode: int32, action: KeyAction, modKeys: set[ModifierKey]) =
        if key == Key.keyV and action == KeyAction.kaDown:
            use_prog_i = (use_prog_i + 1) mod len(use_progs)
            use_prog = use_progs[use_prog_i]
    w.key_cb = keyboard_callback

    while true:
        let move_speed = if w.is_key_down(Key.keyLeftShift): 0.2 else: 0.05
        if w.is_key_down(Key.keyW): cam_pos += move_speed.float32 * cam_look
        if w.is_key_down(Key.keyS): cam_pos -= move_speed.float32 * cam_look
        if w.is_key_down(Key.keyA): cam_pos -= move_speed.float32 * cam_look.cross(cam_up).normalize
        if w.is_key_down(Key.keyD): cam_pos += move_speed.float32 * cam_look.cross(cam_up).normalize
        ####
        if w.is_key_down(Key.keyI): ell.pos.y += 0.1
        if w.is_key_down(Key.keyK): ell.pos.y -= 0.1
        if w.is_key_down(Key.keyJ): ell.pos.x += 0.1
        if w.is_key_down(Key.keyL): ell.pos.x -= 0.1

        let view: Mat4[float32] = look_at(cam_pos, cam_pos + cam_look, cam_up)
        gl_clear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) # Clear color and depth buffers
        gl_use_program(use_prog)

        debug.clear()

        for id, d in drawables:
            let mesh = meshes[d.mesh_id]

            for i, b in texture_bindings.where((drawable_id: id.uint16, texture_id: _, texture_name: _)):
                gl_uniform_handle_ui64ARB(gl_get_uniform_location(use_prog, b.texture_name), b.texture_handle)

            var m = translate(mat4f(), d.pos) # model matrix
            var mvp: Mat4[float32] = proj * view * m

            gl_uniform_matrix4fv(gl_get_uniform_location(use_prog, "MVP"), 1, false, mvp.caddr)
            gl_uniform_matrix4fv(gl_get_uniform_location(use_prog, "M"), 1, false, m.caddr)

            gl_bind_vertex_array(mesh.vao)
            gl_draw_elements(GL_TRIANGLES, mesh.nfaces.GLsizei, cGL_UNSIGNED_SHORT, cast[ptr int](0))

        #debug_edge(vec3f(0, 0, 0), vec3f(0.1,0.1,0.1))
        #debug_edge(vec3f(0.1,0.1,0.1), vec3f(-0.3,0.1,0.1))
        debug.AABB(vec3f(0, 0, 2), vec3f(1, 1, 3))
        debug.sphere(ell.pos, ell.radius.x)

        var debug_mvp = proj * view
        debug.draw(debug_mvp)

        w.swap_buffers
        poll_events()
        if w.should_close == true or w.is_key_down(keyEscape):
            break

    w.destroy()
    glfw.terminate()