~nch/gamelog

ref: 75432213d3972f26c03ef636da68ed482f0ac908 gamelog/main.lua -rw-r--r-- 11.3 KiB View raw
75432213 — nc refactoring debug code out a bit 5 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
local gl_loaded, gl = pcall(require, "moongl")
if not gl_loaded then
    print("Unable to load GL. Assuming tests are being run.")
end

local mi_loaded, mi = pcall(require, "moonimage")
if not mi_loaded then
    print("Unable to load moonimage. Assuming tests are being run.")
end

local m = require('moonglmath') -- math

fun = require 'fun'
tuple = require 'tuple'
set = require 'set'
pprint = require 'pprint'
require 'datalog'

db = set()
entity = predicate(db, 'entity')
mesh = predicate(db, 'mesh')
texture = predicate(db, 'texture')
texture_binding = predicate(db, 'texture_binding')
drawable = predicate(db, 'drawable')
frame_debug = predicate(db, 'frame_debug')
collider = predicate(db, 'collider')

function new_entity()
    local new_id = max(entity.query('@id'), '@id') + 1
    entity.insert(new_id)
    return new_id
end

--[[
repl = require 'repl.console'
for _, plugin in pairs({'autoreturn', 'pretty_print'}) do
    if not repl:hasplugin(plugin) then
        repl:loadplugin(plugin)
    end
end
]]--

function split(str, pattern)
    local t = {}
    local function helper(line)
        table.insert(t, line)
        return ""
    end
    helper((str:gsub("(.-)("..(pattern or "%s+")..")", helper)))
    return t
end

local function test_split()
    assert(is_eq(split('a b c', ' '), {'a', 'b', 'c'}))
    assert(is_eq(split('a/b/c', '/'), {'a', 'b', 'c'}))
    assert(is_eq(split('a b c'), {'a', 'b', 'c'}))
end

function indexof(lst, e)
    for i, x in ipairs(lst) do
        if x == e then
            return i
        end
    end
end

local function test_indexof()
    assert(indexof({'a', 'b', 'c'}, 'a') == 1)
    assert(indexof({'a', 'b', 'c'}, 'b') == 2)
    assert(indexof({'a', 'b', 'c'}, 'c') == 3)
    assert(indexof({'a', 'b', 'c'}, 'x') == nil)
end

function curry(f, x) return function(...) return f(x, ...) end end
function curryr(f, x) return function(...) return f(..., x) end end
function compose(a, b) return function(...) return a(b(...)) end end

table.append = compose(fun.totable, fun.chain)
mapt = compose(fun.totable, fun.map)

function parse_obj(file)
    local vertices = {}
    local obj_sections = {}

    for line in io.lines(file) do
        local tokens = split(line)
        local head = tokens[1]
        if string.sub(head, 1, 1) ~= '#' then
            if obj_sections[head] == nil then
                obj_sections[head] = {}
            end
            table.insert(obj_sections[head], fun.totable(fun.tail(tokens)))
        end
    end

    obj_sections['v'] = mapt(function(x)
        assert(#x == 3, "vertex should only have 3 components")
        return mapt(tonumber, x)
    end, obj_sections['v'])
    obj_sections['vn'] = mapt(function(x)
        assert(#x == 3, "vertex normal should only have 3 components")
        return mapt(tonumber, x)
    end, obj_sections['vn'])
    obj_sections['vt'] = mapt(function(x)
       assert(#x == 2, "vertex uv should only have 2 components")
       local uv = mapt(tonumber, x)
       uv[2] = 1 - uv[2] -- !!! opengl flips the y coordinates of UVs from what obj exports. which is fun.
       return uv
    end, obj_sections['vt'] or {{0, 0}})

    local vert_data = {} -- [(vx, vy, vz, vnx, vny, vnz, vu, vv), ...]
    local element_indices = {}
    local s = set()
    for i, f in pairs(obj_sections['f']) do
        assert(#f == 3, "parse_obj: only accepts files constructed of triangles")
        for j, v in pairs(f) do
            local fields = fun.totable(split(v, "/"))
            local vi = tonumber(fields[1])
            assert(vi ~= nil, "needs a vertex attribute")
            local vt = tonumber(fields[2]) or 1
            local vn = tonumber(fields[3]) or 1
            local new_vert = tuple(table.unpack(table.append(
                  assert(obj_sections['v'][vi]),
                  assert(obj_sections['vn'][vn]),
                  assert(obj_sections['vt'][vt])
                  )))
            if s[new_vert] then -- only add new indexes
                -- technically this indexof() call makes this function slightly better than n^2,
                -- but it actually runs -- quite fast... if it ain't slow don't waste time
                -- optimizing it ¯\_(ツ)_/¯
                table.insert(element_indices, indexof(vert_data, new_vert) - 1)
            else
                s:add(new_vert)
                table.insert(vert_data, new_vert)
                table.insert(element_indices, #vert_data - 1)
            end
        end
    end
    assert(#vert_data > 0)
    assert(#element_indices > 0)
    return vert_data, element_indices
end

local MAX_DEBUG_POINTS = 1024
local floatsz = gl.sizeof('float')

function make_debug_mesh()
    local vao = gl.new_vertex_array()
    local vbo = gl.new_buffer('array')

    gl.buffer_data('array', 3*floatsz*MAX_DEBUG_POINTS, 'static draw')
    gl.vertex_attrib_pointer(0, 3, 'float', false, 3*floatsz, 0) -- pos
    gl.enable_vertex_attrib_array(0)

    gl.unbind_vertex_array()
    return vao, vbo
end

function make_mesh(vertices, face_indices)
    local vao = gl.new_vertex_array()
    local vbo = gl.new_buffer('array')
    gl.buffer_data('array', gl.pack('float', vertices), 'static draw')
    gl.vertex_attrib_pointer(0, 3, 'float', false, 8*floatsz, 0) -- pos
    gl.enable_vertex_attrib_array(0)
    gl.vertex_attrib_pointer(1, 3, 'float', false, 8*floatsz, 3*floatsz) -- normal
    gl.enable_vertex_attrib_array(1)
    gl.vertex_attrib_pointer(2, 2, 'float', false, 8*floatsz, 6*floatsz) -- uv
    gl.enable_vertex_attrib_array(2)

    local ebo = gl.new_buffer('element array')
    gl.buffer_data('element array', gl.pack('ushort', face_indices), 'static draw')

    gl.unbind_vertex_array()
    return vao
end

function debug_point(pos)
    frame_debug.insert('point', pos)
end

function debug_line(p1, p2)
    frame_debug.insert('line', p1)
    frame_debug.insert('line', p2)
end

function load_mesh(obj_path)
    local q = mesh.query(obj_path, '@vao', '_', '_')
    if #q > 0 then
        return q[1]['@vao']
    end
    -- load new mesh
    local vs, fs = parse_obj(obj_path)
    local vao = make_mesh(gl.flatten_table(vs), gl.flatten_table(fs))
    mesh.insert(obj_path, vao, #fs, #vs)
    return vao
end

function load_texture(file)
    local q = texture.query(file, '@id', '_', '_')
    if #q > 0 then
        return q[1]['@id']
    end
    -- load new texture
    local id = gl.new_texture('2d')
    gl.texture_parameter('2d', 'wrap s', 'clamp to edge')
    gl.texture_parameter('2d', 'wrap t', 'clamp to edge')
    gl.texture_parameter('2d', 'min filter', 'linear')
    gl.texture_parameter('2d', 'mag filter', 'linear')
    local img, w, h = mi.load(file, 'rgb')
    gl.texture_image('2d', 0, 'rgb', 'rgb', 'ubyte', img, w, h)
    gl.unbind_texture('2d')
    texture.insert(file, id, w, h)
    return id
end

local debug_vao, debug_vbo
function init()
    gl.init()
    debug_vao, debug_vbo = make_debug_mesh()

    require('scene1')

program_id = gl.make_program_s(
'vertex',
[[
#version 450 core
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;
}
]],
'fragment',
[[
#version 450 core
in vec3 normal;
in vec3 worldPos;
in vec4 fragPosLightSpace;
in vec2 uv;
out vec3 color;
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;
}
]]
)

    debug_prog = gl.make_program_s(
    'vertex',
    [[
#version 450 core
layout(location = 0) in vec3 vpos;
uniform mat4 MVP;

void main() {
   gl_PointSize = 7.0;
   gl_Position = MVP * vec4(vpos, 1.0);
}
    ]],
    'fragment',
    [[
#version 450 core
out vec3 color;

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

view = m.look_at(m.vec3(0, 1, 2), m.vec3(0, 0, 0), m.vec3(0, 1, 0))
proj = m.perspective(math.pi / 4, 800 / 600, 0.1, 100)

x = 0
z = 0
speed = 0.1
function draw()
    local dx, dz = 0, 0
    if is_down('A') then
        dx = dx + speed
    end
    if is_down('D') then
        dx = dx - speed
    end
    if is_down('W') then
        dz = dz + speed
    end
    if is_down('S') then
        dz = dz - speed
    end
    update(db, {'drawable', player_id, '_', '_'}, function(t)
       return t:update(4, m.vec3(t[4].x + dx, t[4].y, t[4].z + dz))
    end)

    local drawables = drawable.query('@id', '@vao', '@pos')
    for i=1, #drawables do
        -- camera calculation
        local d = drawables[i]
        local M = m.translate(d['@pos'])
        local MVP = proj * view * M
        gl.use_program(program_id)
        gl.uniform_matrix(gl.get_uniform_location(program_id, 'MVP'), 'float', '4x4', true, gl.flatten(MVP))
        gl.uniform_matrix(gl.get_uniform_location(program_id, 'M'), 'float', '4x4', true, gl.flatten(M))

        local textures = texture_binding.query(d['@id'], '@name', '@tex_id')
        for i=1, #textures do
            gl.active_texture(i)
            gl.bind_texture('2d', textures[i]['@tex_id'])
            gl.uniform(gl.get_uniform_location(program_id, textures[i]['@name']), 'int', i)
        end

        local n = query_single(db, {'mesh', '_', d['@vao'], '@nfs', '_'})['@nfs']
        gl.bind_vertex_array(d['@vao'])
        gl.draw_elements('triangles', n, 'ushort', 0)

        gl.unbind_texture('2d')
    end

    debug_point(m.vec3(0, 0, 0))
    debug_point(m.vec3(0.1, 0.1, 0.1))
    debug_point(m.vec3(0.2, 0.2, 0.2))
    debug_line(m.vec3(0.2, 0.2, 0.2), m.vec3(-0.5, -0.5, -0.5))

    do -- debug draw
       local debugs = query_record(db, frame_debug('@type', '@pos'))
       if #debugs > 0 then
          local debug_points = flat_map(
          function(p)
              if p[2] == 'point' then
                  return {p[3].x, p[3].y, p[3].z}
              else
                  return {}
              end
          end, debugs):totable()

          local debug_lines = flat_map(
          function(p)
              if p[2] == 'line' then
                  return {p[3].x, p[3].y, p[3].z}
              else
                  return {}
              end
          end, debugs):totable()

          gl.bind_vertex_array(debug_vao)
          gl.bind_buffer('array', debug_vbo) -- vbo has to be bound for buffer_sub_data...

          -- TODO: use map_buffer since it's faster
          gl.buffer_sub_data('array', 0, gl.pack('float', fun.chain(debug_points, debug_lines):totable()))

          local MVP = proj * view * m.translate(0, 0, 0)
          gl.use_program(debug_prog)
          gl.uniform_matrix(gl.get_uniform_location(debug_prog, 'MVP'), 'float', '4x4', true, gl.flatten(MVP))

          gl.draw_arrays('points', 0, #debug_points / 3)
          gl.draw_arrays('lines', #debug_points / 3, #debug_lines / 3)
          gl.unbind_vertex_array()

          for i=1, #debugs do
             delete(db, debugs[i])
          end
       end
    end
end

function support_sphere(pos, radius, dir)
   return pos + (dir * radius)
end

function gjk2d(support_f, support_g)
   local function support(dir)
      return support_f(dir) - support_g(-dir)
   end
end

function reload() -- reload module
    package.loaded.main = nil
    require 'main'
end