/
tile_map.clj
1266 lines (1111 loc) · 50.6 KB
/
tile_map.clj
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;; Copyright 2020-2024 The Defold Foundation
;; Copyright 2014-2020 King
;; Copyright 2009-2014 Ragnar Svensson, Christian Murray
;; Licensed under the Defold License version 1.0 (the "License"); you may not use
;; this file except in compliance with the License.
;;
;; You may obtain a copy of the License, together with FAQs at
;; https://www.defold.com/license
;;
;; Unless required by applicable law or agreed to in writing, software distributed
;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
;; CONDITIONS OF ANY KIND, either express or implied. See the License for the
;; specific language governing permissions and limitations under the License.
(ns editor.tile-map
;; switch to released version once https://dev.clojure.org/jira/browse/DIMAP-15 has been fixed
(:require [clojure.data.int-map-fixed :as int-map]
[dynamo.graph :as g]
[editor.build-target :as bt]
[editor.core :as core]
[editor.defold-project :as project]
[editor.geom :as geom]
[editor.gl :as gl]
[editor.gl.pass :as pass]
[editor.gl.shader :as shader]
[editor.gl.texture :as texture]
[editor.gl.vertex2 :as vtx]
[editor.graph-util :as gu]
[editor.handler :as handler]
[editor.material :as material]
[editor.math :as math]
[editor.outline :as outline]
[editor.properties :as properties]
[editor.protobuf :as protobuf]
[editor.resource :as resource]
[editor.resource-node :as resource-node]
[editor.scene :as scene]
[editor.scene-picking :as scene-picking]
[editor.tile-map-grid :as tile-map-grid]
[editor.tile-source :as tile-source]
[editor.validation :as validation]
[editor.workspace :as workspace])
(:import [com.dynamo.gamesys.proto Tile$TileGrid Tile$TileGrid$BlendMode Tile$TileLayer]
[com.jogamp.opengl GL2]
[editor.gl.shader ShaderLifecycle]
[javax.vecmath Matrix4d Point3d Vector3d]))
(set! *warn-on-reflection* true)
(defn- min-l
^long [^long a ^long b]
(Math/min a b))
(defn- max-l
^long [^long a ^long b]
(Math/max a b))
(defn- max-d
^double [^double a ^double b]
(Math/max a b))
(defn- floor-d
^double [^double n]
(Math/floor n))
(defn single
[coll]
(when-not (next coll) (first coll)))
(defn toggler
[a b]
(fn [v] (if (= v a) b a)))
(def tile-map-icon "icons/32/Icons_48-Tilemap.png")
(def tile-map-layer-icon "icons/32/Icons_42-Layers.png")
;; manipulating cells
(defrecord Tile [^long x ^long y ^long tile ^boolean h-flip ^boolean v-flip ^boolean rotate90])
(defn cell-index ^long [^long x ^long y]
(bit-or (bit-shift-left y Integer/SIZE)
(bit-and x 0xFFFFFFFF)))
(defn paint-cell!
[cell-map x y tile h-flip v-flip rotate90]
(if tile
(assoc! cell-map (cell-index x y) (->Tile x y tile h-flip v-flip rotate90))
(dissoc! cell-map (cell-index x y))))
(defn make-cell-map
[cells]
(persistent! (reduce (fn [ret {:keys [x y tile h-flip v-flip rotate90] :or {h-flip 0 v-flip 0} :as cell}]
(paint-cell! ret x y tile (not= 0 h-flip) (not= 0 v-flip) (not= 0 rotate90)))
(transient (int-map/int-map))
cells)))
(defn paint
[cell-map [sx sy] brush]
(let [{:keys [width height tiles]} brush]
(let [ex (+ sx width)
ey (+ sy height)]
(loop [x sx
y sy
tiles tiles
cell-map (transient cell-map)]
(if (< y ey)
(if (< x ex)
(let [{:keys [tile h-flip v-flip rotate90]} (first tiles)]
(recur (inc x) y (rest tiles) (paint-cell! cell-map x y tile h-flip v-flip rotate90)))
(recur sx (inc y) tiles cell-map))
(persistent! cell-map))))))
(defn make-brush
[tile]
{:width 1 :height 1 :tiles [{:tile tile :h-flip false :v-flip false :rotate90 false}]})
(defn make-brush-from-selection
[cell-map start-cell end-cell]
(let [[sx sy] start-cell
[ex ey] end-cell
x0 (min-l sx ex)
y0 (min-l sy ey)
x1 (inc (max-l sx ex))
y1 (inc (max-l sy ey))
w (- x1 x0)
h (- y1 y0)]
{:width w
:height h
:tiles (vec (for [y (range y0 y1)
x (range x0 x1)]
(get cell-map (cell-index x y))))}))
(def erase-brush (make-brush nil))
;;--------------------------------------------------------------------
;; rendering
(vtx/defvertex pos-uv-vtx
(vec3 position)
(vec2 texcoord0))
(shader/defshader tile-map-id-vertex-shader
(uniform mat4 view_proj)
(uniform mat4 world)
(attribute vec4 position)
(attribute vec2 texcoord0)
(varying vec2 var_texcoord0)
(defn void main []
(setq mat4 mvp (* view_proj world))
(setq gl_Position (* mvp (vec4 position.xyz 1.0)))
(setq var_texcoord0 texcoord0)))
(shader/defshader tile-map-id-fragment-shader
(varying vec2 var_texcoord0)
(uniform sampler2D DIFFUSE_TEXTURE)
(uniform vec4 id)
(defn void main []
(setq vec4 color (texture2D DIFFUSE_TEXTURE var_texcoord0))
(if (> color.a 0.05)
(setq gl_FragColor id)
(discard))))
(def tile-map-id-shader (shader/make-shader ::tile-map-id-shader tile-map-id-vertex-shader tile-map-id-fragment-shader {"view_proj" :view-proj "world" :world "id" :id}))
(defn render-layer
[^GL2 gl render-args renderables n]
(let [pass (:pass render-args)]
(condp = pass
pass/transparent
(let [{:keys [selected ^Matrix4d world-transform user-data]} (first renderables)
{:keys [node-id vbuf shader gpu-texture blend-mode]} user-data]
(when vbuf
(let [render-args (merge render-args
(math/derive-render-transforms
world-transform
(:view render-args)
(:projection render-args)
(:texture render-args)))
;; In the runtime, vertices are in world space. In the editor we
;; prefer to keep the vertices in local space in order to avoid
;; unnecessary buffer updates. As a workaround, we trick the
;; shader by supplying a world-view-projection matrix for the
;; view-projection matrix. If this turns out to be a problem, we
;; need to produce world-space buffers here in the render
;; function, seeing as we don't have the final world-transform
;; until the scene has been flattened.
render-args (assoc render-args :view-proj (:world-view-proj render-args))
vertex-binding (vtx/use-with node-id vbuf shader)]
(gl/with-gl-bindings gl render-args [shader vertex-binding gpu-texture]
(gl/set-blend-mode gl blend-mode)
;; TODO: can't use selected because we also need to know when nothing is selected
#_(if selected
(shader/set-uniform shader gl "tint" (Vector4d. 1.0 1.0 1.0 1.0))
(shader/set-uniform shader gl "tint" (Vector4d. 1.0 1.0 1.0 0.5)))
(gl/gl-draw-arrays gl GL2/GL_QUADS 0 (count vbuf))
(.glBlendFunc gl GL2/GL_SRC_ALPHA GL2/GL_ONE_MINUS_SRC_ALPHA)))))
pass/selection
(let [{:keys [^Matrix4d world-transform user-data]} (first renderables)
{:keys [node-id vbuf gpu-texture]} user-data]
(when vbuf
(let [vertex-binding (vtx/use-with node-id vbuf tile-map-id-shader)]
(gl/with-gl-bindings gl (assoc render-args :id (scene-picking/renderable-picking-id-uniform (first renderables))) [tile-map-id-shader vertex-binding gpu-texture]
(gl/gl-push-matrix gl
(gl/gl-mult-matrix-4d gl world-transform)
(gl/gl-draw-arrays gl GL2/GL_QUADS 0 (count vbuf))))))))))
(defn make-tile-uv-lookup-cache
[tile-count uv-transforms]
(let [uv-cache (object-array tile-count)]
(fn [tile]
(if (< tile tile-count)
(or (aget uv-cache tile)
(let [[[u0 v0] [u1 v1]] (geom/uv-trans (nth uv-transforms tile) [[0 0] [1 1]])
uv-coords (float-array 4 [u0 v0 u1 v1])]
(aset uv-cache tile uv-coords)
uv-coords))
(float-array [0 1 1 0])))))
(defn gen-layer-render-data
[cell-map texture-set-data]
(let [{:keys [^long tile-width ^long tile-height ^long tile-count]
:or {tile-width 0, tile-height 0, tile-count 0}} (:texture-set texture-set-data)
uv-lookup (make-tile-uv-lookup-cache tile-count (:uv-transforms texture-set-data))]
(loop [^java.util.Iterator it (.iterator (.values ^java.util.Map cell-map))
vbuf (->pos-uv-vtx (* 6 (count cell-map)))
min-x 0 min-y 0 max-x 0 max-y 0]
(if (.hasNext it)
(let [^Tile tile (.next it)
x0 (* (.x tile) tile-width)
y0 (* (.y tile) tile-height)
x1 (+ x0 tile-width)
y1 (+ y0 tile-height)
^floats uvs (uv-lookup (.tile tile))
u0 (aget uvs (if (.h-flip tile) 2 0))
v0 (aget uvs (if (.v-flip tile) 3 1))
u1 (aget uvs (if (.h-flip tile) 0 2))
v1 (aget uvs (if (.v-flip tile) 1 3))]
(recur it
(if (.rotate90 tile)
(-> vbuf
(pos-uv-vtx-put! x0 y1 0 u0 v1)
(pos-uv-vtx-put! x1 y1 0 u0 v0)
(pos-uv-vtx-put! x1 y0 0 u1 v0)
(pos-uv-vtx-put! x0 y0 0 u1 v1))
(-> vbuf
(pos-uv-vtx-put! x0 y0 0 u0 v1)
(pos-uv-vtx-put! x0 y1 0 u0 v0)
(pos-uv-vtx-put! x1 y1 0 u1 v0)
(pos-uv-vtx-put! x1 y0 0 u1 v1)))
(min-l min-x x0)
(min-l min-y y0)
(max-l max-x x1)
(max-l max-y y1)))
{:vbuf (vtx/flip! vbuf)
:aabb (geom/coords->aabb [min-x min-y 0]
[max-x max-y 0])}))))
(g/defnk produce-layer-scene
[_node-id id cell-map texture-set-data z gpu-texture shader blend-mode visible]
(when visible
(let [{:keys [aabb vbuf]} (gen-layer-render-data cell-map texture-set-data)
transform (doto (Matrix4d.) (.set (Vector3d. 0.0 0.0 z)))
;; The visibility-aabb is used to determine the scene extents. We use
;; it to adjust the camera near and far clip planes to encompass the
;; scene. When editing, layers that do not yet have any tiles on them
;; will produce an empty aabb which will not expand the scene extents.
;; To ensure empty layers will push the scene extents and not be
;; outside the camera clip planes, we give them a small bounding box.
;; This makes the brush for yet-to-be-painted tiles visible.
visibility-aabb
(if (geom/empty-aabb? aabb)
(geom/make-aabb (Point3d. 0.0 0.0 0.0)
(Point3d. 0.001 0.001 0.0))
aabb)]
{:node-id _node-id
:node-outline-key id
:transform transform
:aabb aabb
:visibility-aabb visibility-aabb
:renderable {:render-fn render-layer
:tags #{:tilemap}
:user-data {:node-id _node-id
:vbuf vbuf
:gpu-texture gpu-texture
:shader shader
:blend-mode blend-mode}
:passes [pass/transparent pass/selection]}})))
(g/defnk produce-layer-outline
[_node-id id z]
{:node-id _node-id
:node-outline-key id
:label id
:z z
:icon tile-map-layer-icon})
(g/defnk produce-layer-pb-msg
[id z visible cell-map]
{:id id
:z z
:is-visible (if visible 1 0)
:cell (mapv (fn [{:keys [x y tile v-flip h-flip rotate90]}]
{:x x
:y y
:tile tile
:v-flip (if v-flip 1 0)
:h-flip (if h-flip 1 0)
:rotate90 (if rotate90 1 0)})
(vals cell-map))})
(g/defnode LayerNode
(inherits outline/OutlineNode)
(input texture-set-data g/Any)
(input gpu-texture g/Any)
(input shader ShaderLifecycle)
(input blend-mode g/Any)
(property cell-map g/Any
(dynamic visible (g/constantly false)))
(property id g/Str)
(property z g/Num
(dynamic error (validation/prop-error-fnk :warning validation/prop-1-1? z)))
(property visible g/Bool)
(output scene g/Any :cached produce-layer-scene)
(output node-outline outline/OutlineData :cached produce-layer-outline)
(output pb-msg g/Any :cached produce-layer-pb-msg))
(defn attach-layer-node
[parent layer-node]
(concat
(g/connect layer-node :_node-id parent :nodes)
(g/connect layer-node :id parent :layer-ids)
(g/connect layer-node :node-outline parent :child-outlines)
(g/connect layer-node :scene parent :child-scenes)
(g/connect layer-node :pb-msg parent :layer-msgs)
(g/connect parent :texture-set-data layer-node :texture-set-data)
(g/connect parent :material-shader layer-node :shader)
(g/connect parent :gpu-texture layer-node :gpu-texture)
(g/connect parent :blend-mode layer-node :blend-mode)))
(defn make-layer-node
[parent tile-layer]
(let [graph-id (g/node-id->graph-id parent)]
(g/make-nodes
graph-id
[layer-node [LayerNode {:id (:id tile-layer)
:z (:z tile-layer)
:visible (not= 0 (:is-visible tile-layer))
:cell-map (make-cell-map (:cell tile-layer))}]]
(attach-layer-node parent layer-node))))
(defn world-pos->tile
[^Point3d pos tile-width tile-height]
[(long (Math/floor (/ (.x pos) tile-width)))
(long (Math/floor (/ (.y pos) tile-height)))])
(defn load-tile-map
[project self resource tile-grid]
(let [tile-source (workspace/resolve-resource resource (:tile-set tile-grid))
material (workspace/resolve-resource resource (:material tile-grid))]
(concat
(g/connect project :default-tex-params self :default-tex-params)
(g/set-property self
:tile-source tile-source
:material material
:blend-mode (:blend-mode tile-grid))
(for [tile-layer (:layers tile-grid)]
(make-layer-node self tile-layer)))))
(g/defnk produce-scene
[_node-id child-scenes]
{:node-id _node-id
:aabb geom/null-aabb
:renderable {:passes [pass/selection]}
:children child-scenes})
(g/defnk produce-node-outline
[_node-id child-outlines]
{:node-id _node-id
:node-outline-key "Tile Map"
:label "Tile Map"
:icon tile-map-icon
:children (vec (sort-by :z child-outlines))})
(g/defnk produce-pb-msg
[tile-source material blend-mode layer-msgs]
{:tile-set (resource/resource->proj-path tile-source)
:material (resource/resource->proj-path material)
:blend-mode blend-mode
:layers (sort-by :z layer-msgs)})
(defn build-tile-map
[resource dep-resources user-data]
(let [pb-msg (reduce #(assoc %1 (first %2) (second %2))
(:pb-msg user-data)
(map (fn [[label res]] [label (resource/proj-path (get dep-resources res))]) (:dep-resources user-data)))]
{:resource resource
:content (protobuf/map->bytes Tile$TileGrid pb-msg)}))
(defn- prop-resource-error [nil-severity _node-id prop-kw prop-value prop-name]
(or (validation/prop-error nil-severity _node-id prop-kw validation/prop-nil? prop-value prop-name)
(validation/prop-error :fatal _node-id prop-kw validation/prop-resource-not-exists? prop-value prop-name)))
(defn- prop-tile-source-range-error
[_node-id tile-source tile-count max-tile-index]
(validation/prop-error :fatal _node-id :tile-source
(fn [v name]
(when-not (< max-tile-index tile-count)
(format "Tile map uses tiles outside the range of this tile source (%d tiles in source, but a tile with index %d is used in tile map)" tile-count max-tile-index))) tile-source "Tile Source"))
(g/defnk produce-build-targets
[_node-id resource tile-source material pb-msg dep-build-targets tile-count max-tile-index]
(g/precluding-errors
[(prop-resource-error :fatal _node-id :tile-source tile-source "Tile Source")
(prop-tile-source-range-error _node-id tile-source tile-count max-tile-index)]
(let [dep-build-targets (flatten dep-build-targets)
deps-by-resource (into {} (map (juxt (comp :resource :resource) :resource) dep-build-targets))
dep-resources (map (fn [[label resource]]
[label (get deps-by-resource resource)])
[[:tile-set tile-source]
[:material material]])]
[(bt/with-content-hash
{:node-id _node-id
:resource (workspace/make-build-resource resource)
:build-fn build-tile-map
:user-data {:pb-msg pb-msg
:dep-resources dep-resources}
:deps dep-build-targets})])))
(g/defnode TileMapNode
(inherits resource-node/ResourceNode)
(input layer-ids g/Any :array)
(input layer-msgs g/Any :array)
(input child-scenes g/Any :array)
(input dep-build-targets g/Any :array)
(input tile-source-resource resource/Resource)
(input tile-source-attributes g/Any)
(input texture-set-data g/Any)
(input gpu-texture g/Any)
(input material-resource resource/Resource)
(input material-shader ShaderLifecycle)
(input material-samplers g/Any)
(input default-tex-params g/Any)
;; tile source
(property tile-source resource/Resource
(value (gu/passthrough tile-source-resource))
(set (fn [evaluation-context self old-value new-value]
(project/resource-setter evaluation-context self old-value new-value
[:resource :tile-source-resource]
[:build-targets :dep-build-targets]
[:tile-source-attributes :tile-source-attributes]
[:texture-set-data :texture-set-data]
[:gpu-texture :gpu-texture])))
(dynamic error (g/fnk [_node-id tile-source tile-count max-tile-index]
(or (prop-resource-error :fatal _node-id :tile-source tile-source "Tile Source")
(prop-tile-source-range-error _node-id tile-source tile-count max-tile-index))))
(dynamic edit-type (g/constantly {:type resource/Resource :ext "tilesource"})))
;; material
(property material resource/Resource
(value (gu/passthrough material-resource))
(set (fn [evaluation-context self old-value new-value]
(project/resource-setter evaluation-context self old-value new-value
[:resource :material-resource]
[:build-targets :dep-build-targets]
[:shader :material-shader]
[:samplers :material-samplers])))
(dynamic error (g/fnk [_node-id material]
(prop-resource-error :fatal _node-id :material material "Material")))
(dynamic edit-type (g/constantly {:type resource/Resource :ext "material"})))
(property blend-mode g/Any
(dynamic edit-type (g/constantly (properties/->pb-choicebox Tile$TileGrid$BlendMode))))
(output max-tile-index g/Any :cached (g/fnk [pb-msg]
(transduce (comp (mapcat :cell)
(map :tile))
max 0 (:layers pb-msg))))
(output tile-source-attributes g/Any (gu/passthrough tile-source-attributes))
(output tile-count g/Int (g/fnk [tile-source-attributes]
(* (:tiles-per-row tile-source-attributes 0) (:tiles-per-column tile-source-attributes 0))))
(output tile-dimensions g/Any
(g/fnk [tile-source-attributes]
(when tile-source-attributes
(let [{:keys [width height]} tile-source-attributes]
(when (and width height)
[width height])))))
(output texture-set-data g/Any (gu/passthrough texture-set-data))
(output tex-params g/Any (g/fnk [material-samplers default-tex-params]
(or (some-> material-samplers first material/sampler->tex-params)
default-tex-params)))
(output gpu-texture g/Any (g/fnk [gpu-texture tex-params] (texture/set-params gpu-texture tex-params)))
(output material-shader ShaderLifecycle (gu/passthrough material-shader))
(output scene g/Any :cached produce-scene)
(output node-outline outline/OutlineData :cached produce-node-outline)
(output pb-msg g/Any :cached produce-pb-msg)
(output save-value g/Any (gu/passthrough pb-msg))
(output build-targets g/Any :cached produce-build-targets))
;;--------------------------------------------------------------------
;; tool
(shader/defshader pos-uv-vert
(attribute vec4 position)
(attribute vec2 texcoord0)
(varying vec2 var_texcoord0)
(defn void main []
(setq gl_Position (* gl_ModelViewProjectionMatrix position))
(setq var_texcoord0 texcoord0)))
(shader/defshader pos-uv-frag
(varying vec2 var_texcoord0)
(uniform sampler2D texture_sampler)
(defn void main []
(setq gl_FragColor (texture2D texture_sampler var_texcoord0.xy))))
(def tex-shader (shader/make-shader ::tex-shader pos-uv-vert pos-uv-frag))
(vtx/defvertex color-vtx
(vec3 position)
(vec4 color))
(shader/defshader pos-color-vert
(attribute vec4 position)
(attribute vec4 color)
(varying vec4 var_color)
(defn void main []
(setq gl_Position (* gl_ModelViewProjectionMatrix position))
(setq var_color color)))
(shader/defshader pos-color-frag
(varying vec4 var_color)
(defn void main []
(setq gl_FragColor var_color)))
(def color-shader (shader/make-shader ::color-shader pos-color-vert pos-color-frag))
;; brush
(defn render-brush-outline
[^GL2 gl render-args renderables count]
(let [renderable (first renderables)
world-transform (:world-transform renderable)
user-data (:user-data renderable)
[x y] (:cell user-data)
{:keys [width height]} (:brush user-data)
[tile-width tile-height] (:tile-dimensions user-data)]
(when (and x y)
(let [x0 (* tile-width x)
y0 (* tile-height y)
x1 (+ x0 (* width tile-width))
y1 (+ y0 (* height tile-height))
z 0.0
c (double-array (map #(/ % 255.0) [255 255 255]))]
(.glMatrixMode gl GL2/GL_MODELVIEW)
(gl/gl-push-matrix gl
(gl/gl-mult-matrix-4d gl world-transform)
(.glColor3d gl (nth c 0) (nth c 1) (nth c 2))
(.glBegin gl GL2/GL_LINE_LOOP)
(.glVertex3d gl x0 y0 z)
(.glVertex3d gl x1 y0 z)
(.glVertex3d gl x1 y1 z)
(.glVertex3d gl x0 y1 z)
(.glEnd gl))))))
(defn conj-brush-quad!
[vbuf {:keys [tile h-flip v-flip]} uvs w h x y]
(if-not tile
vbuf
(let [uv (nth uvs tile (geom/identity-uv-trans))
[p1 p2] (geom/uv-trans uv [[0 0] [1 1]])
u0 (first (if h-flip p2 p1))
v0 (second (if v-flip p2 p1))
u1 (first (if h-flip p1 p2))
v1 (second (if v-flip p1 p2))
x0 x
y0 y
x1 (+ x0 w)
y1 (+ y0 h)]
(-> vbuf
(pos-uv-vtx-put! x0 y0 0 u0 v1)
(pos-uv-vtx-put! x0 y1 0 u0 v0)
(pos-uv-vtx-put! x1 y1 0 u1 v0)
(pos-uv-vtx-put! x1 y0 0 u1 v1)))))
(defn gen-brush-vbuf
[brush uvs tile-width tile-height]
(let [{:keys [width height tiles]} brush]
(loop [x 0
y 0
tiles tiles
vbuf (->pos-uv-vtx (* 4 (count tiles)))]
(if (< y height)
(if (< x width)
(recur (inc x) y (rest tiles) (conj-brush-quad! vbuf (first tiles) uvs tile-width tile-height (* x tile-width) (* y tile-height)))
(recur 0 (inc y) tiles vbuf))
(vtx/flip! vbuf)))))
(defn render-brush
[^GL2 gl render-args renderables n]
(let [renderable (first renderables)
user-data (:user-data renderable)
{:keys [texture-set-data gpu-texture brush]} user-data
uvs (:uv-transforms texture-set-data)
[x y] (:cell user-data)
[w h] (:tile-dimensions user-data)
vbuf (gen-brush-vbuf brush uvs w h)
vb (vtx/use-with ::brush vbuf tex-shader)
^Matrix4d layer-transform (:world-transform renderable)
local-transform (doto (Matrix4d. geom/Identity4d)
(.set (Vector3d. (* x w) (* y h) 0)))
brush-transform (doto (Matrix4d. local-transform)
(.mul layer-transform))]
(.glMatrixMode gl GL2/GL_MODELVIEW)
(gl/gl-push-matrix gl
(gl/gl-mult-matrix-4d gl brush-transform)
(gl/with-gl-bindings gl render-args [tex-shader vb gpu-texture]
(shader/set-uniform tex-shader gl "texture_sampler" 0)
(gl/gl-draw-arrays gl GL2/GL_QUADS 0 (count vbuf))))))
;; palette
(def ^:private tile-border-size 1)
(def ^:private ideal-tile-size 32)
(def ^:private edge-offset 100)
(def ^:private clamp-palette-mouse-offset (geom/clamper -0.5 0.5))
(defn- make-palette-transform
[tile-source-attributes viewport ^Vector3d cursor-screen-pos]
(let [{:keys [width
height
visual-width
visual-height
tiles-per-row
tiles-per-column]} tile-source-attributes
{:keys [bottom right]} viewport
cursor-pos (or cursor-screen-pos
(Vector3d. (* right 0.5) (* height 0.5) 0))
scale (-> ideal-tile-size
(/ (max-l width height))
floor-d
(max-d 1.0))
palette-width (-> tile-border-size
(* (dec tiles-per-row))
(+ visual-width)
(* scale))
palette-height (-> tile-border-size
(* (dec tiles-per-column))
(+ visual-height)
(* scale))
max-offset-x (-> palette-width
(- right)
(+ (* 2 edge-offset))
(max-d 0))
max-offset-y (-> palette-height
(- bottom)
(+ (* 2 edge-offset))
(max-d 0))
mouse-offset-ratio-x (-> (.-x cursor-pos)
(- edge-offset)
(/ (- right (* 2 edge-offset)))
(- 0.5)
clamp-palette-mouse-offset)
mouse-offset-ratio-y (-> (.-y cursor-pos)
(- edge-offset)
(/ (- bottom (* 2 edge-offset)))
(- 0.5)
clamp-palette-mouse-offset)
scale-m (doto (Matrix4d.)
(.setIdentity)
(.set (Vector3d. (* 0.5 right)
(* 0.5 bottom)
0.0))
(.setScale scale))
trans-m (doto (Matrix4d.)
(.set (Vector3d. (-> 0
(- (* max-offset-x mouse-offset-ratio-x))
(- (* 0.5 palette-width))
(/ scale))
(-> 0
(- (* max-offset-y mouse-offset-ratio-y))
(- (* 0.5 palette-height))
(/ scale))
0.0)))]
(doto scale-m
(.mul trans-m))))
(g/defnk produce-palette-tile
[^Vector3d cursor-screen-pos
tile-source-attributes
tile-dimensions
^Matrix4d palette-transform]
(when (and cursor-screen-pos tile-source-attributes)
(let [{:keys [width height tiles-per-row tiles-per-column]} tile-source-attributes
p (Point3d. cursor-screen-pos)
t (doto (Matrix4d. palette-transform)
(.invert))
_ (.transform t p)
[x y] (world-pos->tile p
(+ width tile-border-size)
(+ height tile-border-size))]
(when (and (<= 0 x (dec tiles-per-row))
(<= 0 y (dec tiles-per-column)))
(+ (* y tiles-per-row) x)))))
(defn gen-palette-tiles-vbuf
[tile-source-attributes texture-set-data]
(let [uvs (:uv-transforms texture-set-data)
w (:width tile-source-attributes)
h (:height tile-source-attributes)
rows (:tiles-per-column tile-source-attributes)
cols (:tiles-per-row tile-source-attributes)
vbuf (->pos-uv-vtx (* 4 (:tile-count (:texture-set texture-set-data))))]
(loop [x 0
y 0
vbuf vbuf]
(if (< y rows)
(if (< x cols)
(let [uv (nth uvs (+ x (* y cols)))
x0 (+ (* x (+ tile-border-size w)) tile-border-size)
x1 (+ x0 w)
y0 (+ (* y (+ tile-border-size h)) tile-border-size)
y1 (+ y0 h)
[[u0 v0] [u1 v1]] (geom/uv-trans uv [[0 0] [1 1]])]
(recur (inc x)
y
(-> vbuf
(pos-uv-vtx-put! x0 y0 0 u0 v0)
(pos-uv-vtx-put! x0 y1 0 u0 v1)
(pos-uv-vtx-put! x1 y1 0 u1 v1)
(pos-uv-vtx-put! x1 y0 0 u1 v0))))
(recur 0 (inc y) vbuf))
(vtx/flip! vbuf)))))
(defn- render-palette-tiles
[^GL2 gl render-args tile-source-attributes texture-set-data gpu-texture]
(let [vbuf (gen-palette-tiles-vbuf tile-source-attributes texture-set-data)
vb (vtx/use-with ::palette-tiles vbuf tex-shader)
gpu-texture (texture/set-params gpu-texture tile-source/texture-params)]
(gl/with-gl-bindings gl render-args [tex-shader vb gpu-texture]
(shader/set-uniform tex-shader gl "texture_sampler" 0)
(gl/gl-draw-arrays gl GL2/GL_QUADS 0 (count vbuf)))))
(defn gen-palette-grid-vbuf
[tile-source-attributes]
(let [tw (:width tile-source-attributes)
th (:height tile-source-attributes)
rows (:tiles-per-column tile-source-attributes)
cols (:tiles-per-row tile-source-attributes)
w (+ (:visual-width tile-source-attributes) (* (inc cols) tile-border-size))
h (+ (:visual-height tile-source-attributes) (* rows tile-border-size))]
(as-> (->color-vtx (+ (* (+ 1 rows) 4)
(* (+ 1 cols) 4)))
vbuf
(reduce (fn [vbuf y]
(let [y0 (* y (+ th tile-border-size))]
(-> vbuf
(color-vtx-put! 0 y0 0 0.3 0.3 0.3 1.0)
(color-vtx-put! w y0 0 0.3 0.3 0.3 1.0)
(color-vtx-put! w (+ tile-border-size y0) 0 0.3 0.3 0.3 1.0)
(color-vtx-put! 0 (+ tile-border-size y0) 0 0.3 0.3 0.3 1.0))))
vbuf
(range (inc rows)))
(reduce (fn [vbuf x]
(let [x0 (* x (+ tw tile-border-size))]
(-> vbuf
(color-vtx-put! x0 0 0 0.3 0.3 0.3 1.0)
(color-vtx-put! x0 h 0 0.3 0.3 0.3 1.0)
(color-vtx-put! (+ tile-border-size x0) h 0 0.3 0.3 0.3 1.0)
(color-vtx-put! (+ tile-border-size x0) 0 0 0.3 0.3 0.3 1.0))))
vbuf
(range (inc cols)))
(vtx/flip! vbuf))))
(defn- render-palette-grid
[^GL2 gl render-args tile-source-attributes]
(let [vbuf (gen-palette-grid-vbuf tile-source-attributes)
vb (vtx/use-with ::palette-grid vbuf color-shader)]
(gl/with-gl-bindings gl render-args [color-shader vb]
(gl/gl-draw-arrays gl GL2/GL_QUADS 0 (count vbuf)))))
(defn- render-palette-active
[^GL2 gl render-args tile-source-attributes palette-tile]
(when palette-tile
(let [n palette-tile
w (:width tile-source-attributes)
h (:height tile-source-attributes)
x (mod n (:tiles-per-row tile-source-attributes))
y (int (/ n (:tiles-per-row tile-source-attributes)))
x0 (* x (+ tile-border-size w))
x1 (+ x0 w tile-border-size)
y0 (* y (+ tile-border-size h))
y1 (+ y0 h tile-border-size)
vbuf (-> (->color-vtx 16)
;; left edge
(color-vtx-put! x0 y0 0 1.0 1.0 1.0 1.0)
(color-vtx-put! x0 y1 0 1.0 1.0 1.0 1.0)
(color-vtx-put! (+ x0 tile-border-size) y1 0 1.0 1.0 1.0 1.0)
(color-vtx-put! (+ x0 tile-border-size) y0 0 1.0 1.0 1.0 1.0)
;; right edge
(color-vtx-put! x1 y0 0 1.0 1.0 1.0 1.0)
(color-vtx-put! x1 y1 0 1.0 1.0 1.0 1.0)
(color-vtx-put! (+ x1 tile-border-size) y1 0 1.0 1.0 1.0 1.0)
(color-vtx-put! (+ x1 tile-border-size) y0 0 1.0 1.0 1.0 1.0)
;; bottom edge
(color-vtx-put! x0 y0 0 1.0 1.0 1.0 1.0)
(color-vtx-put! x1 y0 0 1.0 1.0 1.0 1.0)
(color-vtx-put! x1 (+ y0 tile-border-size) 0 1.0 1.0 1.0 1.0)
(color-vtx-put! x0 (+ y0 tile-border-size) 0 1.0 1.0 1.0 1.0)
;; top edge
(color-vtx-put! x0 y1 0 1.0 1.0 1.0 1.0)
(color-vtx-put! (+ x1 tile-border-size) y1 0 1.0 1.0 1.0 1.0)
(color-vtx-put! (+ x1 tile-border-size) (+ y1 tile-border-size) 0 1.0 1.0 1.0 1.0)
(color-vtx-put! x0 (+ y1 tile-border-size) 0 1.0 1.0 1.0 1.0)
(vtx/flip!))
vb (vtx/use-with ::palette-active vbuf color-shader)]
(gl/with-gl-bindings gl render-args [color-shader vb]
(gl/gl-draw-arrays gl GL2/GL_QUADS 0 (count vbuf))))))
(defn render-palette-background
[^GL2 gl viewport]
(let [{:keys [top left right bottom]} viewport]
(.glColor4d gl 0.0 0.0 0.0 0.7)
(.glBegin gl GL2/GL_QUADS)
(.glVertex2d gl 0.0 0.0)
(.glVertex2d gl right 0.0)
(.glVertex2d gl right bottom)
(.glVertex2d gl 0.0 bottom)
(.glEnd gl)))
(defn render-palette
[^GL2 gl render-args renderables count]
(let [user-data (:user-data (first renderables))
{:keys [viewport tile-source-attributes texture-set-data gpu-texture palette-transform palette-tile]} user-data]
(render-palette-background gl viewport)
(.glMatrixMode gl GL2/GL_MODELVIEW)
(gl/gl-push-matrix gl
(gl/gl-mult-matrix-4d gl palette-transform)
(render-palette-tiles gl render-args tile-source-attributes texture-set-data gpu-texture)
(render-palette-grid gl render-args tile-source-attributes)
(render-palette-active gl render-args tile-source-attributes palette-tile))))
(defn render-editor-select-outline
[^GL2 gl render-args renderables count]
(let [renderable (first renderables)
world-transform (:world-transform renderable)
user-data (:user-data renderable)
[sx sy] (:start user-data)
[ex ey] (:end user-data)
[tile-width tile-height] (:tile-dimensions user-data)]
(when (and sx sy ex ey)
(let [x0 (* tile-width (min-l sx ex))
y0 (* tile-height (min-l sy ey))
x1 (* tile-width (inc (max-l sx ex)))
y1 (* tile-height (inc (max-l sy ey)))
z 0.0
c (double-array (map #(/ % 255.0) [255 255 255]))]
(.glMatrixMode gl GL2/GL_MODELVIEW)
(gl/gl-push-matrix gl
(gl/gl-mult-matrix-4d gl world-transform)
(.glColor3d gl (nth c 0) (nth c 1) (nth c 2))
(.glBegin gl GL2/GL_LINE_LOOP)
(.glVertex3d gl x0 y0 z)
(.glVertex3d gl x1 y0 z)
(.glVertex3d gl x1 y1 z)
(.glVertex3d gl x0 y1 z)
(.glEnd gl))))))
(defn render-editor-select
[^GL2 gl render-args renderables n]
(let [pass (:pass render-args)]
(condp = pass
pass/outline
(render-editor-select-outline gl render-args renderables n))))
(defn render-editor
[^GL2 gl render-args renderables n]
(let [pass (:pass render-args)]
(condp = pass
pass/transparent
(render-brush gl render-args renderables n)
pass/outline
(render-brush-outline gl render-args renderables n))))
(g/defnk produce-palette-renderables
[viewport tile-source-attributes texture-set-data gpu-texture palette-transform palette-tile]
{pass/overlay [{:world-transform (Matrix4d. geom/Identity4d)
:render-fn render-palette
:user-data {:viewport viewport
:tile-source-attributes tile-source-attributes
:texture-set-data texture-set-data
:gpu-texture gpu-texture
:palette-transform palette-transform
:palette-tile palette-tile}}]})
(g/defnk produce-editor-renderables
[active-layer-renderable op op-select-start op-select-end current-tile tile-dimensions brush viewport texture-set-data gpu-texture]
(when active-layer-renderable
{pass/transparent (cond
(= :select op)
[]
current-tile
[{:world-transform (:world-transform active-layer-renderable)
:render-fn render-editor
:user-data {:cell current-tile
:brush brush
:tile-dimensions tile-dimensions
:texture-set-data texture-set-data
:gpu-texture gpu-texture}}])
pass/outline (cond
(= :select op) [{:world-transform (:world-transform active-layer-renderable)
:render-fn render-editor-select
:user-data {:start op-select-start
:end op-select-end
:tile-dimensions tile-dimensions}}]
current-tile
[{:world-transform (:world-transform active-layer-renderable)
:render-fn render-editor
:user-data {:cell current-tile
:brush brush
:tile-dimensions tile-dimensions}}])}))
(g/defnk produce-tool-renderables
[mode editor-renderables palette-renderables]
(case mode
:editor editor-renderables
:palette palette-renderables))
;;--------------------------------------------------------------------
;; input handling
(defmulti begin-op (fn [op node action state evaluation-context] op))
(defmulti update-op (fn [op node action state evaluation-context] op))
(defmulti end-op (fn [op node action state evaluation-context] op))
;; painting tiles from brush
(defmethod begin-op :paint
[op self action state evaluation-context]
(when-let [active-layer (g/node-value self :active-layer evaluation-context)]
(when-let [current-tile (g/node-value self :current-tile evaluation-context)]
(let [brush (g/node-value self :brush evaluation-context)
op-seq (gensym)]
(swap! state assoc :last-tile current-tile)
[(g/set-property self :op-seq op-seq)
(g/operation-sequence op-seq)
(g/update-property active-layer :cell-map paint current-tile brush)]))))
(defmethod update-op :paint
[op self action state evaluation-context]
(when-let [active-layer (g/node-value self :active-layer evaluation-context)]
(when-let [current-tile (g/node-value self :current-tile evaluation-context)]
(when (not= current-tile (-> state deref :last-tile))
(swap! state assoc :last-tile current-tile)
(let [brush (g/node-value self :brush evaluation-context)
op-seq (g/node-value self :op-seq evaluation-context)]
[(g/operation-sequence op-seq)
(g/update-property active-layer :cell-map paint current-tile brush)])))))
(defmethod end-op :paint
[op self action state evaluation-context]
(swap! state dissoc :last-tile)
[(g/set-property self :op-seq nil)])
;; selecting brush from cell-map
(defmethod begin-op :select
[op self action state evaluation-context]
(when-let [active-layer (g/node-value self :active-layer evaluation-context)]
(when-let [current-tile (g/node-value self :current-tile evaluation-context)]
[(g/set-property self :op-select-start current-tile)
(g/set-property self :op-select-end current-tile)])))