-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
323 lines (280 loc) · 11.7 KB
/
app.js
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
const { Sim, render, phys, loadWavefront, loadBitmap } = await import('./sim.js')
window.render = render
window.phys = phys
const doc = document
window.$$ = (q,...vals) => {
if (typeof q != 'string')
q = q.map((s,i) => s + (i < vals.length ? vals[i] : '')).join('')
return doc.querySelectorAll(q)
}
window.$ = (...args) => $$(...args)[0]
function html(type, attrs = {}, content = '') {
const elem = doc.createElement(type)
if (content instanceof Array) elem.append(...content)
else elem.append(content)
for (const [k,v] of Object.entries(attrs))
elem.setAttribute(k,v)
return elem
}
await GeoDB.open()
window.cv = $`canvas`
cv.width = cv.style.width = window.innerWidth
cv.height = cv.style.height = window.innerHeight
cv.style.cursor = 'grab'
window.ctx = cv.getContext('webgpu')
const createCtrl = {
'common': (prefs,key,elem,ctrl,out) => {
if (out) $(elem).append(out)
$(elem).append(ctrl)
ctrl.setAttribute('id', key)
ctrl.setAttribute('name', key)
ctrl.setAttribute('value', prefs[key])
$(elem).append(html('label', {for: key}, key.replaceAll('_',' ')), html('br'))
},
'bool': (prefs, key, elem) => {
const ctrl = html('input', {type:'checkbox'}).on('change', () => { prefs[key] = ctrl.checked })
ctrl.checked = prefs[key]
createCtrl.common(prefs, key, elem, ctrl)
},
'num': (prefs, key, elem) => {
const ctrl = html('output', {}, prefs[key])
ctrl.on('pointerdown', e => {
const off = window.onoff('pointermove', e => {
const step = prefs.step[key]
prefs[key] = roundEps(clamp(prefs[key] + e.movementX*step, prefs.lo[key], prefs.hi[key]))
ctrl.textContent = prefs[key]
})
window.once('pointerup', e => off())
e.preventDefault()
})
createCtrl.common(prefs, key, elem, ctrl)
},
'choice': (prefs, key, elem) => {
const select = doc.createElement('select').on('change', () => { prefs[key] = select.value })
for (const opt of prefs.opts[key]) {
const option = html('option', {value: opt}, opt)
option.selected = prefs[key] == opt
select.append(option)
}
createCtrl.common(prefs, key, elem, select)
}
}
for (const key of phys.keys)
createCtrl[phys.type[key]](phys, key, '#pedit')
for (const key of render.keys)
if (!render.hidden[key])
createCtrl[render.type[key]](render,key,'#rpref')
const step = html('button', {id: 'step'}, '\u{1F463}').on('click', () => { sim.computer.fwdstep() })
step.style.display = phys.paused ? 'inline' : 'none'
const icon = (color,path) =>
`data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg"%3E%3Cpath style='fill:%23${color}' d='${path}'/%3E%3C/svg%3E`
const playIcon = icon('11DD44', 'M 0,0 32,16 0,32 Z')
const stopIcon = icon('DD1144', 'M 0,0 32,0 32,32 0,32 Z')
$`#icon`.href = phys.paused ? stopIcon : playIcon;
phys.watch(['paused'], () => {
step.style.display = phys.paused ? 'inline' : 'none'
$`#icon`.href = phys.paused ? stopIcon : playIcon;
})
const paused = $`input[name="paused"]`
paused.parentNode.insertBefore(step,paused.nextSibling.nextSibling)
async function updateInfo() {
const lines = []
lines.push(sim.gpu.info.description)
lines.push(sim.gpu.info.driver)
let physStat = await sim.computer.stats(), renderStat = await sim.renderer.stats()
let ttotal = 0
lines.push(`render fps:${renderStat.fps.toFixed(2)}`)
lines.push(`phys fps:${physStat.fps.toFixed(2)}`)
lines.push(' ')
for (const { kind, profile } of [physStat, renderStat]) {
if (!profile) continue
for (const [label, nsecs] of profile) lines.push(`${label}: ${(nsecs / 1000).toFixed(1)} μs`)
let steptot = profile.sum(([label, nsecs]) => nsecs, 0) / 1000
if (steptot > 0n) lines.push(`${kind} tot: ${steptot.toFixed(1)} μs`)
lines.push(' ')
ttotal += steptot * (kind == 'render' ? 1 : phys.frameratio)
}
lines.push(`frameratio(avg): ${(physStat.fps / renderStat.fps).toFixed(2)}`)
if (ttotal > 0n) lines.push(`total: ${ttotal.toFixed(1)} μs`)
lines.push(' ')
lines.push(`cam pos: ${sim.uni.cam_x}`)
lines.push(`cam dir: ${sim.eyeDir()}`)
lines.push(`sim t: ${sim.uni.t}`)
$`#info`.innerHTML = lines.join('<br/>')
setTimeout(updateInfo, 500)
}
class EditorTable extends HTMLDivElement {
constructor(name) {
const dis = Object.setPrototypeOf(html('div'), EditorTable.prototype)
dis.classList.add('editTable')
dis.name = name
dis.page = 0
dis.nrows = name == 'bitmaps' ? 2 : 25
dis.counting = html('span')
dis.back = html('button', {}, '<').on('click', () => { dis.page--; dis.update() })
dis.fwd = html('button', {}, '>').on('click', () => { dis.page++; dis.update() })
dis.table = html('table')
dis.summary = html('div', { class:'summary' }, [html('b', {}, dis.name+': '), dis.back, dis.fwd, dis.counting])
dis.append(dis.summary, dis.table)
dis.tabButton = html('button',{},name).on('click', () => dis.show())
return dis
}
show() {
this.style.display = 'flex'
this.parentNode.active = this
for (const sibling of this.parentNode.children)
if (sibling instanceof EditorTable)
if (sibling != this) {
sibling.style.display = 'none'
sibling.tabButton.className = ''
}
this.update()
this.tabButton.className = 'opentab'
}
async update() {
const start = this.page * this.nrows
let results = await transact([this.name],'readonly', async x => await x.query(this.name))
let ntot = results.size
results = [...results.entries()].slice(start, start + this.nrows)
let stop = start + results.length
this.back.disabled = this.page <= 0
this.fwd.disabled = stop >= ntot
this.counting.textContent = ` 0 found`
this.table.replaceChildren()
if (results.length == 0) return
this.counting.textContent = ` ${start + 1}-${stop} of ${ntot}`
const cols = Object.keys(results[0][1])
const rows = [html('tr', {}, [html('th',{},'id'), ...cols.map(col => html('th',{},col))])]
rows.push(...results.map(([id,result]) => {
let idcol = html('td',{},id)
let delcol = html('td', { class:'delrow' }, html('button',{},'\u274C').on('click', async () => {
transact(db.storeNames, 'readwrite', async x => {
await x.deleteWithRelatives(this.name, id)
this.update()
})
}))
let editcols = cols.map(col => {
const orig = result[col]
if (orig instanceof ImageBitmap) {
const preview = html('canvas', { width:256, height:256 })
ctx = preview.getContext('2d')
ctx.scale(256/orig.width, 256/orig.height);
ctx.drawImage(orig,0,0);
return html('td',{},preview)
}
const edit = html('td', { contenteditable: true }, repr(orig)).on('blur', () => {
let val = edit.textContent
if (typeof orig == 'number') val = parseFloat(val)
else if (orig instanceof Array) val = eval(val)
transact([this.name], 'readwrite', async x => {
await x.update(this.name, id, col, val)
edit.textContent = repr(val)
})
})
return edit
})
const row = html('tr',{},[idcol, ...editcols, delcol])
return row
}))
this.table.append(...rows)
}
}
let openTransacts = 0
let transact = async (stores, perm, cb) => {
return await db.transact(stores, perm, async x => {
if (perm == 'readwrite')
for (let ctrl of $$('.editor button, .editor input, .editor label')) {
ctrl.disabled = true
ctrl.className = 'disabled'
}
let result = await cb(x)
if (perm == 'readwrite') {
for (let ctrl of $$('.editor button, .editor input, .editor label')) {
ctrl.disabled = false
ctrl.className = 'enabled'
}
window.editor.active.update()
}
return result
})
}
const stores = {}
const storeBtns = []
for (const name of ['meshes', 'verts', 'faces', 'bitmaps']) {
const table = new EditorTable(name)
stores[name] = table
storeBtns.push(table.tabButton)
}
const storeNav = html('div', { class:'stores' }, storeBtns)
const storeFooter = html('div', { class:'footer' })
storeFooter.append(html('input', { id:'objfile', type:'file', accept:'.obj' }).on('change', function() {
const file = this.files[0]
if (!file) return
const reader = new FileReader().on('load', e => {
transact(db.storeNames, 'readwrite', async x => loadWavefront(file.name.split('.')[0], e.target.result, x))
})
reader.readAsText(file)
this.value = ''
}), html('label', {for:'objfile', class:'enabled'}, 'Load .obj'))
storeFooter.append(html('input', { id:'pngfile', type:'file', accept:'.png' }).on('change', function() {
const file = this.files[0]
if (!file) return
const reader = new FileReader().on('load', async e => {
const img = new Image()
img.src = e.target.result
await img.decode()
const bitmap = await createImageBitmap(img)
transact(db.storeNames, 'readwrite', async x => loadBitmap(file.name, bitmap, x))
})
reader.readAsDataURL(file)
this.value = ''
}), html('label', {for:'pngfile', class:'enabled'}, 'Load .png'))
storeFooter.append(html('button', {}, 'reset').on('click', async () => {
await GeoDB.reset()
window.editor.active.update()
}))
window.editor = html('dialog', { id:'editor', class:'editor' }, [storeNav, ...Object.values(stores), storeFooter])
stores['meshes'].show()
doc.body.append(editor)
$`#scene`.on('click', e => editor.open ? editor.close() : editor.show())
window.sim = await Sim(cv.width, cv.height, ctx)
window.sim.run()
cv.on('pointerdown', down => {
if (down.button != 0) return
if (editor.open) return editor.close()
const off = window.onoff('pointermove', move => sim.rotateCam(.005*move.movementX, -.005*move.movementY))
window.once('pointerup', up => off())
})
cv.on('pointerdown', down => {
if (down.button != 1) return
const off = window.onoff('pointermove', move => sim.strafeCam(.001*move.movementX, -.001*move.movementY))
window.once('pointerup', up => off())
})
cv.on('pointerdown', down => {
if (down.button != 2) return
sim.grabParticle(down.x, down.y).then(() => {
cv.style.cursor = 'grabbing'
const moveoff = window.onoff('pointermove', move => sim.moveParticle(move.x, move.y))
const lmboff = cv.onoff('pointerdown', down2 => down2.button == 0 && sim.fixParticle())
window.once('pointerup', up => {
moveoff()
lmboff()
sim.dropParticle()
cv.style.cursor = 'grab'
})
})
})
cv.on('wheel', wheel => sim.advanceCam(-0.0002 * wheel.deltaY), { passive: true })
cv.on('contextmenu', menu => menu.preventDefault())
window.on('resize', () => {
cv.width = cv.style.width = window.innerWidth
cv.height = cv.style.height = window.innerHeight
sim.resize(cv.width, cv.height)
})
window.debug = (n = 18) => {
sim.pull('debug').then(data => {
window.d = new Float32Array(data.buffer)
dbg({debug:window.d.subarray(0,n).map(x => round(x*1e5)/1e5).join(' ')})
})
}
setTimeout(updateInfo, 100)