-
-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathplayground.html
More file actions
394 lines (357 loc) · 15.4 KB
/
playground.html
File metadata and controls
394 lines (357 loc) · 15.4 KB
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
<!DOCTYPE html>
<html>
<head>
<title>Squint</title>
<meta content="width=device-width, initial-scale=1" name="viewport">
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script src="https://unpkg.com/node-inspect-extracted/dist/inspect.js"></script>
<script async src="https://ga.jspm.io/npm:es-module-shims@1.8.2/dist/es-module-shims.js" crossorigin="anonymous"></script>
<script type="importmap">
{
"imports": {
"squint-cljs": "https://unpkg.com/squint-cljs@0.4.67/index.js",
"squint-cljs/core.js": "https://unpkg.com/squint-cljs@0.4.67/core.js",
"squint-cljs/string.js": "https://unpkg.com/squint-cljs@0.4.67/string.js",
"@codemirror/language": "https://ga.jspm.io/npm:@codemirror/language@6.9.2/dist/index.js",
"@codemirror/state": "https://ga.jspm.io/npm:@codemirror/state@6.3.1/dist/index.js",
"@codemirror/view": "https://ga.jspm.io/npm:@codemirror/view@6.21.4/dist/index.js",
"@nextjournal/clojure-mode": "https://ga.jspm.io/npm:@nextjournal/clojure-mode@0.3.0/dist/nextjournal/clojure_mode.mjs",
"@nextjournal/clojure-mode/extensions/eval-region": "https://ga.jspm.io/npm:@nextjournal/clojure-mode@0.3.0/dist/nextjournal/clojure_mode/extensions/eval_region.mjs",
"three": "https://unpkg.com/three@0.158.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.158.0/examples/jsm/",
"easing": "https://ga.jspm.io/npm:easing@1.2.1/browser-easing.js",
"bezier-easing": "https://unpkg.com/bezier-easing@2.1.0/dist/bezier-easing.js"
},
"scopes": {
"https://ga.jspm.io/": {
"@codemirror/commands": "https://ga.jspm.io/npm:@codemirror/commands@6.3.0/dist/index.js",
"@lezer/common": "https://ga.jspm.io/npm:@lezer/common@1.1.0/dist/index.js",
"@lezer/highlight": "https://ga.jspm.io/npm:@lezer/highlight@1.1.6/dist/index.js",
"@lezer/lr": "https://ga.jspm.io/npm:@lezer/lr@1.3.13/dist/index.js",
"@lezer/markdown": "https://ga.jspm.io/npm:@lezer/markdown@1.1.0/dist/index.js",
"@nextjournal/lezer-clojure": "https://ga.jspm.io/npm:@nextjournal/lezer-clojure@1.0.0/dist/index.es.js",
"style-mod": "https://ga.jspm.io/npm:style-mod@4.1.0/src/style-mod.js",
"w3c-keyname": "https://ga.jspm.io/npm:w3c-keyname@2.2.8/index.js"
}
}
}
</script>
<style>
:root {
--teal-color: #31afd0;
}
</style>
<script type="module">
import { default_extensions, complete_keymap } from '@nextjournal/clojure-mode';
import * as eval_region from '@nextjournal/clojure-mode/extensions/eval-region';
import { EditorView, drawSelection, keymap } from '@codemirror/view';
import { EditorState } from '@codemirror/state';
import { syntaxHighlighting, defaultHighlightStyle, foldGutter } from '@codemirror/language';
let theme = EditorView.theme({
".cm-content": {whitespace: "pre-wrap",
passing: "10px 0",
flex: "1 1 0"},
"&.cm-focused": {outline: "0 !important"},
".cm-line": {"padding": "0 9px",
"line-height": "1.6",
"font-size": "16px",
"font-family": "var(--code-font)"},
".cm-matchingBracket": {"border-bottom": "1px solid var(--teal-color)",
"color": "inherit"},
".cm-gutters": {background: "transparent",
border: "none"},
".cm-gutterElement": {"margin-left": "5px"},
// only show cursor when focused
".cm-cursor": {visibility: "hidden"},
"&.cm-focused .cm-cursor": {visibility: "visible"}
});
let squintExtension = ( opts ) => {
return keymap.of([{key: "Alt-Enter", run: evalCell},
{key: opts.modifier + "-Enter",
run: evalAtCursor,
shift: evalToplevel
}])}
let urlParams = new URLSearchParams(window.location.search);
var repl = true;
let evalCode = async (code) => {
try {
let js = compileString(`(do ${code}\n)`, {repl: repl, "elide-exports": repl, context: repl ? 'return' : 'statement'});
if (dev) {
js = js.replace('squint-cljs/core.js', 'http://' + window.location.host + '/core.js');
}
document.querySelector('#compiledCode').innerText = js;
if (!repl) {
const encodedJs = encodeURIComponent(js);
const dataUri = 'data:text/javascript;charset=utf-8;eval=' + Date.now() + ',' + encodedJs;
let result = await import(dataUri);
} else {
let result = await eval(`(async function() { ${js} })()`);
document.querySelector('#result').innerText = util.inspect(result);
if (docChanged) {
let url = new URL(window.location.href);
url.searchParams.delete("src");
window.history.replaceState(null, null, url);
localStorage.setItem("document", editor.state.doc.toString());
docChanged = false;
}
}
}
catch (e) {
document.querySelector('#result').innerText = util.inspect(e);
console.error(e);
}
}
let evalCell = (opts) => {
let js = opts.state.doc.toString();
evalCode(js);
return true;
}
let evalAtCursor = (opts) => {
if (!repl) return;
let js = eval_region.cursor_node_string(opts.state).toString();
evalCode(js);
return true;
}
let docChanged = false;
let evalToplevel = (js) => {
if (!repl) return;
return true;
}
let updateExt = EditorView.updateListener.of((update) => {
if (update.docChanged) docChanged = true;
});
let extensions = [
theme,
foldGutter(),
syntaxHighlighting(defaultHighlightStyle),
drawSelection(),
keymap.of(complete_keymap),
squintExtension({modifier: "Meta"}),
eval_region.extension({modifier: "Meta"}),
updateExt,
...default_extensions
];
let doc = `
(ns user
(:require ["squint-cljs/core.js" :as squint]
["three" :as three]
["three/addons/postprocessing/EffectComposer.js" :refer [EffectComposer]]
["three/addons/postprocessing/RenderPass.js" :refer [RenderPass]]
["three/addons/postprocessing/UnrealBloomPass.js" :refer [UnrealBloomPass]]
["three/addons/postprocessing/FilmPass.js" :refer [FilmPass]]
["easing$default" :as easing]
["bezier-easing" :as BezierEasing]))
(def BezierEasing js/globalThis.BezierEasing)
(def Math js/globalThis.Math)
(defn ^:async eval-script [url]
(let [resp (js-await (js/fetch url))
script (js-await (.text resp))]
(js/eval.call js/globalThis script)))
(js-await (eval-script "https://unpkg.com/dat.gui@0.7.9/build/dat.gui.js"))
(def dat js/globalThis.dat)
(js-await (eval-script "https://unpkg.com/stats.js@0.17.0/build/stats.min.js"))
(def Stats js/globalThis.Stats)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; controls
(def params
{:magnitude 0.1
:x-scale 1.0
:y-scale 0.5
:sin-x-scale 0.0
:cos-y-scale 1.0})
(def gui
(doto (dat/GUI.)
(.add params "magnitude" 0.0 0.5)
(.add params "x-scale" 0.0 2.0)
(.add params "y-scale" 0.0 2.0)
(.add params "sin-x-scale" 0.0 2.0)
(.add params "cos-y-scale" 0.0 2.0)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; basic three.js setup
(def scene
(three/Scene.))
(def origin (three/Vector3.))
(def height (/ (.-innerHeight js/window) 2))
(def width (min (* 2 height) (.-innerWidth js/window)))
(def camera
(doto (three/PerspectiveCamera. 75 (/ width height) 0.1 1000)
(-> :position ((fn [pos] (.set pos 0 0 70))))
(.lookAt origin)))
(def renderer
(doto (three/WebGLRenderer. (clj->js {:antialias true}))
(.setPixelRatio (.-devicePixelRatio js/window))
(.setSize width height)
(-> (assoc! :toneMapping three/ReinhardToneMapping
:toneMappingExposure (Math/pow 1.4 5.0))
(-> :domElement js/document.body.prepend))))
;; effects composer for after effects
(def composer
(let [w (get js/window :innerWidth)
h (get js/window :innerHeight)]
(doto (EffectComposer. renderer)
(.addPass (RenderPass. scene camera))
(.addPass (UnrealBloomPass. (three/Vector2. w h) ; viewport resolution
0.3 ; strength
0.2 ; radius
0.8)) ; threshold
(.addPass (assoc! (FilmPass. 0.25 ; noise intensity
0.26 ; scanline intensity
648 ; scanline count
false); grayscale
:renderToScreen true)))))
;; animation helpers
(def current-frame (atom 0))
(def linear (easing 76 "linear" {:endToEnd true}))
(def bezier
(mapv (BezierEasing. 0.74 -0.01 0.21 0.99)
(range 0 1 (/ 1.0 76))))
(defn fix-zero [n]
(if (zero? n) 1 n))
(def mesh
(let [m (three/Points. (three/SphereGeometry. 11 64 64)
(three/PointsMaterial. {:vertexColors true
:size 0.7
:transparent true
:alphaTest 0.5
:blending three/AdditiveBlending}))]
(.add scene m)
m))
(defn render []
(let [num-frames 76]
(swap! current-frame #(mod (inc %) num-frames))
(let [sphere (three/SphereGeometry. 11 64 64)
sphere-verts (.getAttribute sphere "position")
points (mapv #(let [sv (.fromBufferAttribute (three/Vector3.) sphere-verts %)]
(.addScaledVector sv sv (* (:magnitude params)
(fix-zero (* (:x-scale params) (.-x sv)))
(fix-zero (* (:y-scale params) (.-y sv)))
(fix-zero (* (:sin-x-scale params) (Math/sin (.-x sv))))
(fix-zero (* (:cos-y-scale params) (Math/cos (.-y sv))))
(nth linear @current-frame))))
(range (:count sphere-verts)))
dists (mapv #(.distanceTo origin %) points)
min-dist (apply min dists)
max-dist (- (apply max dists) min-dist)]
(doto (.-geometry mesh)
(.setFromPoints points)
(.setAttribute "color" (three/Float32BufferAttribute.
(mapcat #(let [c (three/Color.)]
;; mutate the color object and return the resulting RGB values
(.setHSL c
(+ 0.3 (* 0.5 (max (min 1.0 (/ (- (get dists %) min-dist) max-dist)) 0)))
0.8
0.2)
[(.-r c) (.-g c) (.-b c)])
(range (:count sphere-verts)))
3))))
(squint/assoc-in! mesh [:rotation :y] (* 1.5 Math/PI (nth bezier @current-frame))))
(.render composer (nth bezier @current-frame))) ; render from the effects composer
(defn animate [s]
(.begin s)
(render)
(.end s)
(.requestAnimationFrame js/window #(animate s)))
(defn ^:async init []
(let [s (Stats. [])]
(js/document.body.prepend (:dom s))
(animate s)))
(defonce doit (do (init) true))
`.trim();
let boilerplate = urlParams.get('boilerplate');
let boilerplateSrc;
if (boilerplate) {
boilerplateSrc = await fetch(boilerplate).then(p => p.text());
}
let src = urlParams.get('src');
if (src) {
if (/http(s)?:\/\/.*/.test(src)) {
src = await fetch(src).then(p => p.text());
}
else {
src = atob(src)
};
doc = src;
} else {
// doc = localStorage.getItem("document") || doc;
}
let state = EditorState.create({doc: doc,
extensions: extensions });
let editorElt = document.querySelector('#editor');
let editor = new EditorView({state: state,
parent: editorElt,
extensions: extensions });
globalThis.editor = editor;
var dev = JSON.parse(urlParams.get('dev')) ?? location.hostname === 'localhost';
var squintUrl;
if (dev) {
console.log('Loading development squint.js')
squintUrl = '/index.js';
} else {
squintUrl = 'squint-cljs';
}
var squint = await(import(squintUrl));
var compileString = squint.compileString;
window.compile = () => {
let code = editor.state.doc.toString();
code = '' + boilerplateSrc + '\n\n' + code;
evalCode(code);
}
window.share = () => {
let code = editor.state.doc.toString().trim();
code = btoa(code);
let url = new URL(window.location);
url.searchParams.set('src', code);
window.location = url;
}
window.changeREPL = (target) => {
document.getElementById('result').innerText = '';
if (target.checked) {
repl = true;
compile();
} else {
repl = false;
compile();
}
let url = new URL(window.location.href);
if (repl) {
url.searchParams.set("repl", repl);
} else {
url.searchParams.delete("repl");
}
window.history.replaceState(null, null, url);
}
if (repl) {
document.getElementById('replCheckBox').checked = true;
}
compile();
</script>
</head>
<body>
<div style="display: flex; flex-direction: row; max-height: 90vh; overflow: auto;">
<div style="position: absolute; right: 0px; top: 0px; margin: 2px">
<a href="https://gitHub.com/squint-cljs/squint"><img src="https://img.shields.io/github/stars/squint-cljs/squint.svg?style=social&label=Star"></a></div>
<div id="editor" style="max-height: 90vh; overflow: auto; width: 50%; border: 1px solid grey; border-radius: 10px; margin-bottom: 10px;">
</div>
<div style="width: 50%; max-height: 90vh; overflow: auto; border: 1px solid grey; border-radius: 10px; margin-left: 10px; padding: 10px; margin-bottom: 10px;">
<button onClick="compile()">
Compile!
</button>
<button onClick="share()">
Share!
</button>
<br>
<label>REPL-mode
<input type="checkbox" id="replCheckBox" name="repl" onChange="changeREPL(this)" />
</label>
<br>
In REPL-mode you can evaluate individual expression by using the ⌘ (macOS) or Windows key + Enter. The result will appear below.
<pre><code style="white-space: pre-wrap;max-width:80%;" id="result"></code>
</pre>
Compiled code:
<pre><code style="white-space: pre-wrap;max-width:80%;" id="compiledCode"></code>
</pre>
</div>
</div>
</body>
</html>