-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathGridVisualizeMakieExt.jl
More file actions
1510 lines (1343 loc) · 47.1 KB
/
GridVisualizeMakieExt.jl
File metadata and controls
1510 lines (1343 loc) · 47.1 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
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
"""
module GridVisualizeMakieExt
Makie extension module for GridVisualize.jl. This is almost fully supported and works with GLMakie,
CairoMalie and WGLMakie.
"""
module GridVisualizeMakieExt
using Colors
using ColorSchemes
using DocStringExtensions
using Printf
using GeometryBasics
using Interpolations: linear_interpolation
using IntervalSets
import GridVisualize: initialize!, save, reveal, gridplot!, scalarplot!, vectorplot!, streamplot!, customplot!, movie
using GridVisualize: MakieType, GridVisualizer, SubVisualizer
using GridVisualize: isolevels, cellcolors, num_cellcolors, vectorsample, quiverdata, regionmesh, bfacesegments
using ExtendableGrids
using GridVisualizeTools
using Observables
include("flippablelayout.jl")
function initialize!(p::GridVisualizer, ::Type{MakieType})
XMakie = p.context[:Plotter]
# Prepare flippable layout
FlippableLayout.setmakie!(XMakie.Makie)
layout = p.context[:layout]
parent, flayout = FlippableLayout.flayoutscene(; size = p.context[:size])
p.context[:figure] = parent
p.context[:flayout] = flayout
# copy arguments to sublayout
for I in CartesianIndices(layout)
ctx = p.subplots[I]
ctx[:figure] = parent
ctx[:flayout] = flayout
end
# Don't call display on pluto
if !isdefined(Main, :PlutoRunner)
XMakie.display(parent)
end
return parent
end
# Adding a scene to the layout just adds to the
# flippable layout.
add_scene!(ctx, ax) = ctx[:flayout][ctx[:subplot]...] = ax
# Revealing the visualizer just returns the figure
function reveal(p::GridVisualizer, ::Type{MakieType})
XMakie = p.context[:Plotter]
layout = p.context[:layout]
# For 1D plots the legend should be rendered only once,
# when all lines+labels are defined
for I in CartesianIndices(layout)
ctx = p.subplots[I]
if ctx[:legend] != :none && haskey(ctx, :scalarplot1d)
if !haskey(ctx, :axislegend)
pos = ctx[:legend] == :best ? :rt : ctx[:legend]
ctx[:axislegend] = XMakie.axislegend(
ctx[:scene];
position = pos,
labelsize = 0.5 * ctx[:fontsize],
backgroundcolor = RGBA(1.0, 1.0, 1.0, 0.85),
)
end
end
end
if haskey(p.context, :videostream)
return XMakie.recordframe!(p.context[:videostream])
else
return p.context[:figure]
end
end
function reveal(ctx::SubVisualizer, TP::Type{MakieType})
FlippableLayout.yieldwait(ctx[:flayout])
if ctx[:show] || ctx[:reveal]
return reveal(ctx[:GridVisualizer], TP)
end
return nothing
end
function save(fname, p::GridVisualizer, ::Type{MakieType})
return p.context[:Plotter].save(fname, p.context[:figure])
end
function save(fname, scene, XMakie, ::Type{MakieType})
return isnothing(scene) ? nothing : XMakie.save(fname, scene)
end
function movie(
func,
vis::GridVisualizer,
::Type{MakieType};
file = nothing,
format = "gif",
kwargs...,
)
Plotter = vis.context[:Plotter]
if !isnothing(file)
format = lstrip(splitext(file)[2], '.')
end
if isdefined(Main, :PlutoRunner) || !isnothing(file)
vis.context[:videostream] = Plotter.VideoStream(vis.context[:figure]; format = format, kwargs...)
end
func(vis)
if !isnothing(file)
return Plotter.save(file, vis.context[:videostream])
elseif isdefined(Main, :PlutoRunner)
return vis.context[:videostream]
else
return nothing
end
end
"""
scene_interaction(update_scene,view,switchkeys::Vector{Symbol}=[:nothing])
Control multiple scene elements via keyboard up/down keys.
Each switchkey is assumed to correspond to one of these elements.
Pressing a switch key transfers control to its associated element.
Control of values of the current associated element is performed
by triggering change values via up/down (± 1) resp. page_up/page_down (±10) keys
The update_scene callback gets passed the change value and the symbol.
"""
function scene_interaction(
update_scene,
scene,
XMakie,
switchkeys::Vector{Symbol} = [:nothing]
)
# Check if pixel position pos sits within the scene
function _inscene(scene, pos)
area = scene.viewport[]
return pos[1] > area.origin[1] &&
pos[1] < area.origin[1] + area.widths[1] &&
pos[2] > area.origin[2] &&
pos[2] < area.origin[2] + area.widths[2]
end
# Initial active switch key is the first in the vector passed
activeswitch = Observable(switchkeys[1])
# Handle mouse position within scene
mouseposition = Observable((0.0, 0.0))
XMakie.on(scene.events.mouseposition) do m
mouseposition[] = m
false
end
# Set keyboard event callback
return XMakie.on(scene.events.keyboardbutton) do buttons
if _inscene(scene, mouseposition[])
# On pressing a switch key, pass control
for i in 1:length(switchkeys)
if switchkeys[i] != :nothing &&
XMakie.ispressed(scene, getproperty(XMakie.Keyboard, switchkeys[i]))
activeswitch[] = switchkeys[i]
update_scene(0, switchkeys[i])
return true
end
end
# Handle change values via up/down control
if XMakie.ispressed(scene, XMakie.Keyboard.up)
update_scene(1, activeswitch[])
return true
elseif XMakie.ispressed(scene, XMakie.Keyboard.down)
update_scene(-1, activeswitch[])
return true
elseif XMakie.ispressed(scene, XMakie.Keyboard.page_up)
update_scene(10, activeswitch[])
return true
elseif XMakie.ispressed(scene, XMakie.Keyboard.page_down)
update_scene(-10, activeswitch[])
return true
end
end
return false
end
end
# Standard kwargs for Makie scenes
scenekwargs(ctx) = Dict(
#:xticklabelsize => 0.5*ctx[:fontsize],
#:yticklabelsize => 0.5*ctx[:fontsize],
#:zticklabelsize => 0.5*ctx[:fontsize],
#:xlabelsize => 0.5*ctx[:fontsize],
#:ylabelsize => 0.5*ctx[:fontsize],
#:zlabelsize => 0.5*ctx[:fontsize],
#:xlabeloffset => 20,
#:ylabeloffset => 20,
#:zlabeloffset => 20,
:titlesize => ctx[:fontsize]
)
#scenekwargs(ctx)=()
############################################################################################################
#1D grid
# Point list for node markers
function basemesh1d(grid, gridscale)
coord = vec(grid[Coordinates])
ncoord = length(coord)
points = Vector{Point2f}(undef, 0)
(xmin, xmax) = extrema(coord)
h = gridscale * (xmax - xmin) / 40.0
for i in 1:ncoord
push!(points, Point2f(coord[i] * gridscale, h))
push!(points, Point2f(coord[i] * gridscale, -h))
end
return points
end
# Point list for intervals
function regionmesh1d(grid, gridscale, iregion; cellcoloring = :cellregions)
coord = vec(grid[Coordinates])
points = Vector{Point2f}(undef, 0)
cn = grid[CellNodes]
cr = cellcolors(grid, cellcoloring)
ncells = length(cr)
for i in 1:ncells
if cr[i] == iregion
push!(points, Point2f(coord[cn[1, i]] * gridscale, 0))
push!(points, Point2f(coord[cn[2, i]] * gridscale, 0))
end
end
return points
end
# Point list for boundary nodes
function bregionmesh1d(grid, gridscale, ibreg)
nbfaces = num_bfaces(grid)
bfacenodes = grid[BFaceNodes]
bfaceregions = grid[BFaceRegions]
coord = vec(grid[Coordinates])
points = Vector{Point2f}(undef, 0)
(xmin, xmax) = extrema(coord)
h = gridscale * (xmax - xmin) / 20.0
for ibface in 1:nbfaces
if bfaceregions[ibface] == ibreg
push!(points, Point2f(coord[bfacenodes[1, ibface]] * gridscale, h))
push!(points, Point2f(coord[bfacenodes[1, ibface]] * gridscale, -h))
end
end
return points
end
# Point list for scene size
function scenecorners1d(grid, gridscale)
coord = vec(grid[Coordinates])
(xmin, xmax) = extrema(coord)
h = gridscale * (xmax - xmin) / 40.0
return [Point2f(xmin * gridscale, -5 * h), Point2f(xmax * gridscale, 5 * h)]
end
function gridplot!(ctx, TP::Type{MakieType}, ::Type{Val{1}}, grid)
XMakie = ctx[:Plotter]
nregions = num_cellregions(grid)
nbregions = num_bfaceregions(grid)
gridscale = ctx[:gridscale]
if !haskey(ctx, :scene)
ctx[:scene] = XMakie.Axis(
ctx[:figure];
yticklabelsvisible = false,
yticksvisible = false,
title = ctx[:title],
scenekwargs(ctx)...,
)
ctx[:grid] = Observable(grid)
cmap = region_cmap(nregions)
bcmap = bregion_cmap(nbregions)
# Set scene size with invisible markers
XMakie.scatter!(
ctx[:scene],
map(g -> scenecorners1d(grid, gridscale), ctx[:grid]);
color = :white,
markersize = 0.0,
strokewidth = 0,
)
# Draw node markers
XMakie.linesegments!(
ctx[:scene],
map(g -> basemesh1d(g, gridscale), ctx[:grid]);
color = :black,
)
# Colored cell regions
for i in 1:nregions
XMakie.linesegments!(
ctx[:scene],
map(g -> regionmesh1d(g, gridscale, i; cellcoloring = ctx[:cellcoloring]), ctx[:grid]);
color = cmap[i],
linewidth = 4,
label = "c $(i)",
)
end
# Colored boundary grid
for i in 1:nbregions
XMakie.linesegments!(
ctx[:scene],
map(g -> bregionmesh1d(g, gridscale, i), ctx[:grid]);
color = bcmap[i],
linewidth = 4,
label = "b$(i)",
)
end
# Legende
if ctx[:legend] != :none
pos = ctx[:legend] == :best ? :rt : ctx[:legend]
XMakie.axislegend(
ctx[:scene];
position = pos,
labelsize = 0.5 * ctx[:fontsize],
nbanks = 5,
)
end
XMakie.reset_limits!(ctx[:scene])
add_scene!(ctx, ctx[:scene])
else
ctx[:grid][] = grid
end
return reveal(ctx, TP)
end
########################################################################
# 1D function
function scalarplot!(ctx, TP::Type{MakieType}, ::Type{Val{1}}, grids, parentgrid, funcs)
XMakie = ctx[:Plotter]
nfuncs = length(funcs)
if ctx[:title] == ""
ctx[:title] = " "
end
ctx[:scalarplot1d] = true
gridscale = ctx[:gridscale]
# ... keep this for the case we are unsorted
function polysegs(grid, func)
points = Vector{Point2f}(undef, 0)
cellnodes = grid[CellNodes]
coord = grid[Coordinates]
for icell in 1:num_cells(grid)
i1 = cellnodes[1, icell]
i2 = cellnodes[2, icell]
x1 = coord[1, i1] * gridscale
x2 = coord[1, i2] * gridscale
push!(points, Point2f(x1, func[i1]))
push!(points, Point2f(x2, func[i2]))
end
return points
end
function polyline(grid, func)
coord = grid[Coordinates]
return points = [Point2f(coord[1, i] * gridscale, func[i]) for i in 1:length(func)]
end
coord = parentgrid[Coordinates]
xlimits = ctx[:xlimits]
ylimits = ctx[:limits]
xmin = coord[1, 1] * gridscale
xmax = coord[1, end] * gridscale
xauto = true
yauto = true
if xlimits[1] < xlimits[2]
xmin = xlimits[1]
xmax = xlimits[2]
xauto = false
end
if ylimits[1] < ylimits[2]
ymin = ylimits[1]
ymax = ylimits[2]
yauto = false
else
ext = extrema.(funcs)
(ymin, ymax) = (minimum(first.(ext)), maximum(last.(ext)))
end
function update_lines(ctx, newrange)
return if ctx[:markershape] == :none
#line without marker
for l in newrange
XMakie.lines!(
ctx[:scene],
map(a -> a, ctx[:lines][l]);
linestyle = ctx[:linestyle],
linewidth = ctx[:linewidth],
color = rgbcolor(ctx[:color])
)
end
if ctx[:label] != ""
XMakie.scatterlines!(
ctx[:scene],
map(a -> a[1:1], ctx[:lines][newrange[begin]]);
linestyle = ctx[:linestyle],
linewidth = ctx[:linewidth],
markersize = 0.1,
color = rgbcolor(ctx[:color]),
label = ctx[:label],
)
end
else
# line with markers separated by markevery
# draw plain line without the label
for l in newrange
XMakie.lines!(
ctx[:scene],
map(a -> a, ctx[:lines][l]);
linestyle = ctx[:linestyle],
color = rgbcolor(ctx[:color]),
linewidth = ctx[:linewidth],
)
# draw markers without label
XMakie.scatter!(
ctx[:scene],
map(a -> a[1:ctx[:markevery]:end], ctx[:lines][l]);
color = rgbcolor(ctx[:color]),
marker = ctx[:markershape],
markersize = ctx[:markersize],
)
end
# Draw dummy line with marker on top of the first
# marker position already drawn in order to
# get the proper legend entry
if ctx[:label] != ""
XMakie.scatterlines!(
ctx[:scene],
map(a -> a[1:1], ctx[:lines][newrange[begin]]);
linestyle = ctx[:linestyle],
linewidth = ctx[:linewidth],
marker = ctx[:markershape],
markersize = ctx[:markersize],
markercolor = rgbcolor(ctx[:color]),
color = rgbcolor(ctx[:color]),
label = ctx[:label],
)
end
end
end
if !haskey(ctx, :scene)
ctx[:xtitle] = Observable(ctx[:title])
# Axis
ctx[:scene] = XMakie.Axis(
ctx[:figure];
title = map(a -> a, ctx[:xtitle]),
xscale = ctx[:xscale] == :log ? log10 : identity,
yscale = ctx[:yscale] == :log ? log10 : identity,
xlabel = ctx[:xlabel],
ylabel = ctx[:ylabel],
scenekwargs(ctx)...,
)
if !xauto
XMakie.xlims!(ctx[:scene], xmin, xmax)
end
if !yauto
XMakie.ylims!(ctx[:scene], ymin, ymax)
end
# Plot size
XMakie.scatter!(
ctx[:scene],
[Point2f(xmin, ymin), Point2f(xmax, ymax)];
color = parse(RGB{Float64}, :white),
markersize = 0.0,
strokewidth = 0,
)
# ctx[:lines] is an array of lines to draw
# Here, we start just with the first one.
ctx[:lines] = [Observable(polyline(grids[i], funcs[i])) for i in 1:nfuncs]
update_lines(ctx, 1:nfuncs)
XMakie.reset_limits!(ctx[:scene])
ctx[:nlines] = nfuncs
XMakie.reset_limits!(ctx[:scene])
add_scene!(ctx, ctx[:scene])
else
if ctx[:clear]
ctx[:nlines] = nfuncs
else
ctx[:nlines] += nfuncs
end
# Either update existing line, or
# create new one. This works with repeating sequences of
# updating lines.
if ctx[:nlines] <= length(ctx[:lines])
for i in 1:nfuncs
ctx[:lines][ctx[:nlines] - nfuncs + i][] = polyline(grids[i], funcs[i])
end
else
r0 = length(ctx[:lines])
for i in 1:nfuncs
push!(ctx[:lines], Observable(polyline(grids[i], funcs[i])))
end
r1 = length(ctx[:lines])
update_lines(ctx, (r0 + 1):r1)
end
XMakie.reset_limits!(ctx[:scene])
ctx[:xtitle][] = ctx[:title]
end
return reveal(ctx, TP)
end
#######################################################################################
# 2D grid
function makescene_grid(ctx)
XMakie = ctx[:Plotter]
GL = XMakie.GridLayout(ctx[:figure])
GL[1, 1] = ctx[:scene]
ncol = length(ctx[:cmap])
nbcol = length(ctx[:bcmap])
# fontsize=0.5*ctx[:fontsize],ticklabelsize=0.5*ctx[:fontsize]
if ctx[:show_colorbar]
if ctx[:colorbar] == :vertical
GL[1, 2] = XMakie.Colorbar(
ctx[:figure];
colormap = XMakie.cgrad(ctx[:cmap]; categorical = true),
limits = (0.5, ncol + 0.5),
ticks = 1:ncol,
width = 15,
label = "cell regions",
)
GL[1, 3] = XMakie.Colorbar(
ctx[:figure];
colormap = XMakie.cgrad(ctx[:bcmap]; categorical = true),
limits = (0.5, nbcol + 0.5),
ticks = 1:nbcol,
width = 15,
label = "boundary regions",
)
elseif ctx[:colorbar] == :horizontal
GL[2, 1] = XMakie.Colorbar(
ctx[:figure];
colormap = XMakie.cgrad(ctx[:cmap]; categorical = true),
limits = (1, ncol),
height = 15,
vertical = false,
label = "cell regions",
)
GL[3, 1] = XMakie.Colorbar(
ctx[:figure];
colormap = XMakie.cgrad(ctx[:bcmap]; categorical = true),
limits = (1, nbcol),
height = 15,
vertical = false,
label = "boundary regions",
)
end
end
return GL
end
# Put all data which could be updated in to one plot.
function set_plot_data!(ctx, key, data)
return haskey(ctx, key) ? ctx[key][] = data : ctx[key] = Observable(data)
end
function gridplot!(ctx, TP::Type{MakieType}, ::Type{Val{2}}, grid)
XMakie = ctx[:Plotter]
nregions = num_cellcolors(grid, ctx[:cellcoloring])
nbregions = num_bfaceregions(grid)
set_plot_data!(ctx, :grid, grid)
if !haskey(ctx, :gridplot)
if !haskey(ctx, :scene)
aspect = nothing
autolimitaspect = nothing
if ctx[:aspect] ≈ 1.0
aspect = XMakie.DataAspect()
else
autolimitaspect = ctx[:aspect]
end
ctx[:scene] = XMakie.Axis(
ctx[:figure];
title = ctx[:title],
aspect = aspect,
autolimitaspect = autolimitaspect,
scenekwargs(ctx)...,
)
xlimits = ctx[:xlimits]
ylimits = ctx[:ylimits]
if xlimits[1] < xlimits[2]
XMakie.xlims!(ctx[:scene], xlimits...)
end
if ylimits[1] < ylimits[2]
XMakie.ylims!(ctx[:scene], ylimits...)
end
end
# Draw cells with region mark
cmap = region_cmap(nregions)
ctx[:cmap] = cmap
for i in 1:nregions
XMakie.poly!(
ctx[:scene],
map(g -> regionmesh(g, ctx[:gridscale], i; cellcoloring = ctx[:cellcoloring]), ctx[:grid]);
color = cmap[i],
strokecolor = :black,
strokewidth = ctx[:linewidth],
)
end
# Draw boundary lines
bcmap = bregion_cmap(nbregions)
ctx[:bcmap] = bcmap
for i in 1:nbregions
lp = XMakie.linesegments!(
ctx[:scene],
map(g -> bfacesegments(g, ctx[:gridscale], i), ctx[:grid]);
label = "$(i)",
color = bcmap[i],
linewidth = 4,
)
XMakie.translate!(lp, 0, 0, 0.1)
end
XMakie.reset_limits!(ctx[:scene])
# Describe legend
if ctx[:legend] != :none
pos = ctx[:legend] == :best ? :rt : ctx[:legend]
XMakie.axislegend(
ctx[:scene];
position = pos,
labelsize = 0.5 * ctx[:fontsize],
backgroundcolor = :transparent,
)
end
add_scene!(ctx, makescene_grid(ctx))
end
return reveal(ctx, TP)
end
"""
makescene2d(ctx)
Complete scene with title and status line showing interaction state.
This uses a gridlayout and its protrusion capabilities.
"""
function makescene2d(ctx, key)
XMakie = ctx[:Plotter]
GL = XMakie.GridLayout(ctx[:figure])
GL[1, 1] = ctx[:scene]
# , fontsize=0.5*ctx[:fontsize],ticklabelsize=0.5*ctx[:fontsize]
if ctx[:show_colorbar]
if ctx[:colorbar] == :vertical
GL[1, 2] = XMakie.Colorbar(
ctx[:figure],
ctx[key];
width = 10,
ticks = unique(ctx[:cbarticks]),
tickformat = "{:.2e}",
)
elseif ctx[:colorbar] == :horizontal
GL[2, 1] = XMakie.Colorbar(
ctx[:figure],
ctx[key];
height = 10,
ticks = unique(ctx[:cbarticks]),
vertical = false,
tickformat = "{:.2e}",
)
end
end
return GL
end
# 2D function
function scalarplot!(ctx, TP::Type{MakieType}, ::Type{Val{2}}, grids, parentgrid, funcs)
XMakie = ctx[:Plotter]
gridscale = ctx[:gridscale]
# Create GeometryBasics.mesh from grid data.
function make_mesh(grids, funcs, elevation)
ngrids = length(grids)
coords = [grid[Coordinates] for grid in grids]
npoints = [num_nodes(grid) for grid in grids]
cellnodes = [grid[CellNodes] for grid in grids]
ncells = [num_cells(grid) for grid in grids]
offsets = zeros(Int, ngrids)
for i in 2:ngrids
offsets[i] = offsets[i - 1] + npoints[i - 1]
end
if elevation ≈ 0.0
points = Vector{Point3f}(undef, sum(npoints))
k = 1
for j in 1:ngrids
for i in 1:npoints[j]
points[k] = Point3f(coords[j][1, i] * gridscale, coords[j][2, i] * gridscale, -0.1)
k = k + 1
end
end
else
points = Vector{Point3f}(undef, sum(npoints))
k = 1
for j in 1:ngrids
for i in 1:npoints[j]
points[k] = Point3f(
coords[j][1, i] * gridscale, coords[j][2, i] * gridscale,
funcs[j][i] * elevation * gridscale
)
k = k + 1
end
end
end
faces = Vector{TriangleFace{Int64}}(undef, sum(ncells))
k = 1
for j in 1:ngrids
for i in 1:ncells[j]
faces[k] = TriangleFace(
cellnodes[j][1, i] + offsets[j],
cellnodes[j][2, i] + offsets[j],
cellnodes[j][3, i] + offsets[j]
)
k = k + 1
end
end
return Mesh(points, faces)
end
levels, crange, ctx[:cbarticks] = isolevels(ctx, funcs)
eps = 1.0e-1
if crange[1] == crange[2]
crange = (crange[1] - eps, crange[1] + eps)
end
set_plot_data!(
ctx,
:contourdata,
(
g = grids,
f = funcs,
e = ctx[:elevation],
t = ctx[:title],
l = levels,
c = crange,
)
)
if !haskey(ctx, :contourplot)
if !haskey(ctx, :scene)
aspect = nothing
autolimitaspect = nothing
if ctx[:aspect] ≈ 1.0
aspect = XMakie.DataAspect()
else
autolimitaspect = ctx[:aspect]
end
if ctx[:elevation] ≈ 0
ctx[:scene] = XMakie.Axis(
ctx[:figure];
title = map(data -> data.t, ctx[:contourdata]),
aspect = aspect,
autolimitaspect = autolimitaspect,
xlabel = ctx[:xlabel],
ylabel = ctx[:ylabel],
scenekwargs(ctx)...,
)
else
ctx[:scene] = XMakie.Axis3(
ctx[:figure];
title = map(data -> data.t, ctx[:contourdata]),
aspect = aspect,
autolimitaspect = autolimitaspect,
scenekwargs(ctx)...,
)
end
xlimits = ctx[:xlimits]
ylimits = ctx[:ylimits]
if xlimits[1] < xlimits[2]
XMakie.xlims!(ctx[:scene], xlimits...)
end
if ylimits[1] < ylimits[2]
XMakie.ylims!(ctx[:scene], ylimits...)
end
end
# Draw the mesh for the cells
ctx[:contourplot] = XMakie.poly!(
ctx[:scene],
map(data -> make_mesh(data.g, data.f, data.e), ctx[:contourdata]);
color = map(data -> vcat(data.f...), ctx[:contourdata]),
colorrange = map(data -> data.c, ctx[:contourdata]),
colormap = ctx[:colormap],
)
# draw the isolines via marching triangles
if ctx[:elevation] ≈ 0
XMakie.linesegments!(
ctx[:scene],
map(data -> first(marching_triangles(data.g, data.f, [], data.l; gridscale)), ctx[:contourdata]);
color = :black,
linewidth = ctx[:linewidth],
)
end
XMakie.reset_limits!(ctx[:scene])
add_scene!(ctx, makescene2d(ctx, :contourplot))
end
return reveal(ctx, TP)
end
# 2D vector
function vectorplot!(ctx, TP::Type{MakieType}, ::Type{Val{2}}, grid, func)
XMakie = ctx[:Plotter]
rc, rv = vectorsample(grid, func; gridscale = ctx[:gridscale], rasterpoints = ctx[:rasterpoints], offset = ctx[:offset])
qc, qv = quiverdata(rc, rv; vscale = ctx[:vscale], vnormalize = ctx[:vnormalize], vconstant = ctx[:vconstant])
set_plot_data!(ctx, :arrowdata, (qc = qc, qv = qv))
if !haskey(ctx, :arrowplot)
if !haskey(ctx, :scene)
ctx[:scene] = XMakie.Axis(
ctx[:figure];
title = ctx[:title],
aspect = XMakie.DataAspect(),
scenekwargs(ctx)...,
)
add_scene!(ctx, ctx[:scene])
end
if isdefined(XMakie, :arrows2d!) # Makie >=0.23
ctx[:arrowplot] = XMakie.arrows2d!(
ctx[:scene],
map(data -> data.qc[1, :], ctx[:arrowdata]),
map(data -> data.qc[2, :], ctx[:arrowdata]),
map(data -> data.qv[1, :], ctx[:arrowdata]),
map(data -> data.qv[2, :], ctx[:arrowdata]);
color = :black,
shaftwidth = ctx[:linewidth],
tipwidth = 3 * ctx[:linewidth],
)
else
ctx[:arrowplot] = XMakie.arrows!(
ctx[:scene],
map(data -> data.qc[1, :], ctx[:arrowdata]),
map(data -> data.qc[2, :], ctx[:arrowdata]),
map(data -> data.qv[1, :], ctx[:arrowdata]),
map(data -> data.qv[2, :], ctx[:arrowdata]);
color = :black,
linewidth = ctx[:linewidth],
)
end
XMakie.reset_limits!(ctx[:scene])
end
return reveal(ctx, TP)
end
function streamplot!(ctx, TP::Type{MakieType}, ::Type{Val{2}}, grid, func)
XMakie = ctx[:Plotter]
rc, rv = vectorsample(
grid, func; rasterpoints = 2 * ctx[:rasterpoints], offset = ctx[:offset], xlimits = ctx[:xlimits],
ylimits = ctx[:ylimits], gridscale = ctx[:gridscale]
)
x = rc[1]
y = rc[2]
ix = linear_interpolation((x, y), rv[1, :, :])
iy = linear_interpolation((x, y), rv[2, :, :])
f(x, y) = Point2(ix(x, y), iy(x, y))
xextent = x[end] - x[begin]
yextent = y[end] - y[begin]
maxextent = max(xextent, yextent)
gridstep = maxextent / (2 * ctx[:rasterpoints])
gridsize = (Int(ceil(xextent / gridstep)), Int(ceil(yextent / gridstep)), 2 * ctx[:rasterpoints])
set_plot_data!(ctx, :streamdata, (xinterval = x[begin] .. x[end], yinterval = y[begin] .. y[end], f = f))
if !haskey(ctx, :streamplot)
if !haskey(ctx, :scene)
ctx[:scene] = XMakie.Axis(
ctx[:figure];
title = ctx[:title],
aspect = XMakie.DataAspect(),
scenekwargs(ctx)...,
)
add_scene!(ctx, ctx[:scene])
end
ctx[:streamplot] = XMakie.streamplot!(
ctx[:scene],
map(data -> data.f, ctx[:streamdata]),
map(data -> data.xinterval, ctx[:streamdata]),
map(data -> data.yinterval, ctx[:streamdata]);
linewidth = ctx[:linewidth],
colormap = ctx[:colormap],
gridsize = gridsize,
arrow_size = 7.5,
stepsize = 0.01 * maxextent
)
XMakie.reset_limits!(ctx[:scene])
end
return reveal(ctx, TP)
end
#######################################################################################
#######################################################################################
# 3D Grid
function xyzminmax(grid::ExtendableGrid, gridscale)
coord = grid[Coordinates]
ndim = size(coord, 1)
xyzmin = zeros(ndim)
xyzmax = ones(ndim)
for idim in 1:ndim
@views mn, mx = extrema(coord[idim, :])
xyzmin[idim] = mn * gridscale
xyzmax[idim] = mx * gridscale
end
return xyzmin, xyzmax
end
"""
makeaxis3d(ctx)
Dispatch between LScene and new Axis3. Axis3 does not allow zoom, so we
support LScene in addition.
"""
function makeaxis3d(ctx)
XMakie = ctx[:Plotter]
if ctx[:scene3d] == :LScene
# "Old" LScene with zoom-in functionality
lim = ctx[:limits]
lim = Observable(Rect3f(Vec3f(lim[1], lim[3], lim[5]), Vec3f(lim[2], lim[4], lim[6])))
scene = XMakie.LScene(ctx[:figure], scenekw = (; limits = lim))
return scene
else
# "New" Axis3 with prospective new stuff by Julius.
return XMakie.Axis3(
ctx[:figure];
aspect = :data,
viewmode = ctx[:viewmode],
limits = ctx[:limits],
elevation = ctx[:elev] * π / 180,
azimuth = ctx[:azim] * π / 180,
perspectiveness = ctx[:perspectiveness],
title = map(data -> data.t, ctx[:data]),
scenekwargs(ctx)...,
)
end
end
"""
makescene3d(ctx)
Complete scene with title and status line showing interaction state.
This uses a gridlayout and its protrusion capabilities.
"""
function makescene3d(ctx)