This repository has been archived by the owner on Jul 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
screen.jl
369 lines (325 loc) · 11 KB
/
screen.jl
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
const ScreenID = UInt8
const ZIndex = Int
# ID, Area, clear, is visible, background color
const ScreenArea = Tuple{ScreenID, Node{IRect2D}, Node{Bool}, Node{Bool}, Node{RGBAf0}}
abstract type GLScreen <: AbstractScreen end
mutable struct Screen <: GLScreen
glscreen::GLFW.Window
framebuffer::GLFramebuffer
rendertask::RefValue{Task}
screen2scene::Dict{WeakRef, ScreenID}
screens::Vector{ScreenArea}
renderlist::Vector{Tuple{ZIndex, ScreenID, RenderObject}}
cache::Dict{UInt64, RenderObject}
cache2plot::Dict{UInt16, AbstractPlot}
framecache::Tuple{Matrix{RGB{N0f8}}, Matrix{RGB{N0f8}}}
function Screen(
glscreen::GLFW.Window,
framebuffer::GLFramebuffer,
rendertask::RefValue{Task},
screen2scene::Dict{WeakRef, ScreenID},
screens::Vector{ScreenArea},
renderlist::Vector{Tuple{ZIndex, ScreenID, RenderObject}},
cache::Dict{UInt64, RenderObject},
cache2plot::Dict{UInt16, AbstractPlot},
)
s = size(framebuffer)
obj = new(
glscreen, framebuffer, rendertask, screen2scene,
screens, renderlist, cache, cache2plot,
(Matrix{RGB{N0f8}}(undef, s), Matrix{RGB{N0f8}}(undef, reverse(s)))
)
finalizer(obj) do obj
# save_print("Freeing screen")
empty!.((obj.renderlist, obj.screens, obj.cache, obj.screen2scene, obj.cache2plot))
return
end
obj
end
end
GeometryTypes.widths(x::Screen) = size(x.framebuffer.color)
Base.wait(x::Screen) = isassigned(x.rendertask) && wait(x.rendertask[])
Base.wait(scene::Scene) = wait(global_gl_screen()) # TODO per scene screen
Base.show(io::IO, screen::Screen) = print(io, "GLMakie.Screen(...)")
function insertplots!(screen::GLScreen, scene::Scene)
for elem in scene.plots
insert!(screen, scene, elem)
end
foreach(s-> insertplots!(screen, s), scene.children)
end
function Base.empty!(screen::GLScreen)
empty!(screen.renderlist)
empty!(screen.screen2scene)
empty!(screen.screens)
end
function destroy!(screen::Screen)
empty!(screen)
empty!(screen.cache)
empty!(screen.cache2plot)
destroy!(screen.glscreen)
end
function Base.resize!(window::GLFW.Window, resolution...)
if isopen(window)
retina_scale = retina_scaling_factor(window)
w, h = resolution ./ retina_scale
GLFW.SetWindowSize(window, round(Int, w), round(Int, h))
end
end
function Base.resize!(screen::Screen, w, h)
nw = to_native(screen)
resize!(nw, w, h)
fb = screen.framebuffer
resize!(fb, (w, h))
end
function Base.display(screen::Screen, scene::Scene)
empty!(screen)
resize!(screen, size(scene)...)
GLFW.PollEvents() # let the size change go through (TODO is this necessary?)
register_callbacks(scene, to_native(screen))
insertplots!(screen, scene)
AbstractPlotting.update!(scene)
return
end
function to_jl_layout!(A, B)
ind1, ind2 = axes(A)
n = first(ind2) + last(ind2)
for i in ind1
@simd for j in ind2
@inbounds B[n-j, i] = ImageCore.clamp01nan(A[i, j])
end
end
return B
end
function fast_color_data!(dest::Array{RGB{N0f8}, 2}, source::Texture{T, 2}) where T
GLAbstraction.bind(source)
glPixelStorei(GL_PACK_ALIGNMENT, 1)
glGetTexImage(source.texturetype, 0, GL_RGB, GL_UNSIGNED_BYTE, dest)
GLAbstraction.bind(source, 0)
nothing
end
function AbstractPlotting.colorbuffer(screen::Screen)
if isopen(screen)
GLFW.PollEvents()
render_frame(screen) # let it render
GLFW.SwapBuffers(to_native(screen))
glFinish() # block until opengl is done rendering
ctex = screen.framebuffer.color
if size(ctex) != size(screen.framecache[1])
s = size(ctex)
screen.framecache = (Matrix{RGB{N0f8}}(undef, s), Matrix{RGB{N0f8}}(undef, reverse(s)))
end
fast_color_data!(screen.framecache[1], ctex)
to_jl_layout!(screen.framecache...)
return screen.framecache[2]
else
error("Screen not open!")
end
end
Base.isopen(x::Screen) = isopen(x.glscreen)
function Base.push!(screen::GLScreen, scene::Scene, robj)
filter!(screen.screen2scene) do (k, v)
k.value != nothing
end
screenid = get!(screen.screen2scene, WeakRef(scene)) do
id = length(screen.screens) + 1
bg = lift(to_color, scene.theme[:backgroundcolor])
clear = lift(identity, scene.theme[:clear])
visible = lift(identity, scene.theme[:visible])
push!(screen.screens, (id, scene.px_area, clear, visible, bg))
id
end
push!(screen.renderlist, (0, screenid, robj))
return robj
end
to_native(x::Screen) = x.glscreen
const gl_screens = GLFW.Window[]
"""
OpenGL shares all data containers between shared contexts, but not vertexarrays -.-
So to share a robjs between a context, we need to rewrap the vertexarray into a new one for that
specific context.
"""
function rewrap(robj::RenderObject{Pre}) where Pre
RenderObject{Pre}(
robj.main,
robj.uniforms,
GLVertexArray(robj.vertexarray),
robj.prerenderfunction,
robj.postrenderfunction,
robj.boundingbox,
)
end
const _global_gl_screen = Ref{Screen}()
# will get overloaded later
function renderloop end
# TODO a global is not very nice, but it's the simplest way right now to swap out
# the rendering loop
const opengl_renderloop = Ref{Function}(renderloop)
function Screen(; resolution = (10, 10), visible = false, kw_args...)
if !isempty(gl_screens)
for elem in gl_screens
isopen(elem) && destroy!(elem)
end
empty!(gl_screens)
end
window = GLFW.Window(
name = "Makie", resolution = (10, 10), # 10, because smaller sizes seem to error on some platforms
windowhints = [
(GLFW.SAMPLES, 0),
(GLFW.DEPTH_BITS, 0),
# SETTING THE ALPHA BIT IS REALLY IMPORTANT ON OSX, SINCE IT WILL JUST KEEP SHOWING A BLACK SCREEN
# WITHOUT ANY ERROR -.-
(GLFW.ALPHA_BITS, 8),
(GLFW.RED_BITS, 8),
(GLFW.GREEN_BITS, 8),
(GLFW.BLUE_BITS, 8),
(GLFW.STENCIL_BITS, 0),
(GLFW.AUX_BUFFERS, 0)
],
visible = false,
kw_args...
)
GLFW.SetWindowIcon(window , AbstractPlotting.icon())
# tell GLAbstraction that we created a new context.
# This is important for resource tracking, and only needed for the first context
GLAbstraction.switch_context!(window)
GLAbstraction.empty_shader_cache!()
push!(gl_screens, window)
GLFW.SwapInterval(0)
# Retina screens on osx have a different scaling!
retina_scale = retina_scaling_factor(window)
resolution = round.(Int, retina_scale .* resolution)
# Set the resolution for real now!
GLFW.SetWindowSize(window, resolution...)
fb = GLFramebuffer(Int.(resolution))
screen = Screen(
window, fb,
RefValue{Task}(),
Dict{WeakRef, ScreenID}(),
ScreenArea[],
Tuple{ZIndex, ScreenID, RenderObject}[],
Dict{UInt64, RenderObject}(),
Dict{UInt16, AbstractPlot}(),
)
if visible
GLFW.ShowWindow(window)
else
GLFW.HideWindow(window)
end
screen.rendertask[] = @async((opengl_renderloop[])(screen))
screen
end
function global_gl_screen()
screen = if isassigned(_global_gl_screen) && isopen(_global_gl_screen[])
_global_gl_screen[]
else
_global_gl_screen[] = Screen()
_global_gl_screen[]
end
GLFW.set_visibility!(to_native(screen), AbstractPlotting.use_display[])
screen
end
# TODO per scene screen
getscreen(scene) = global_gl_screen()
function pick_native(scene::SceneLike, xy::VectorTypes{2}, sid = Base.RefValue{SelectionID{UInt16}}())
screen = getscreen(scene)
screen == nothing && return SelectionID{Int}(0, 0)
window_size = widths(screen)
fb = screen.framebuffer
buff = fb.objectid
glBindFramebuffer(GL_FRAMEBUFFER, fb.id[1])
glReadBuffer(GL_COLOR_ATTACHMENT1)
x, y = Int.(floor.(xy))
w, h = window_size
if x > 0 && y > 0 && x <= w && y <= h
glReadPixels(x, y, 1, 1, buff.format, buff.pixeltype, sid)
return convert(SelectionID{Int}, sid[])
end
return SelectionID{Int}(0, 0)
end
pick(scene::SceneLike, xy...) = pick(scene, Float64.(xy))
function pick(scene::SceneLike, xy::VectorTypes{2})
sid = pick_native(scene, xy)
screen = getscreen(scene)
if screen != nothing && haskey(screen.cache2plot, sid.id)
plot = screen.cache2plot[sid.id]
return (plot, sid.index)
end
return (nothing, 0)
end
# TODO does this actually needs to be a global?
const _mouse_selection_id = Base.RefValue{SelectionID{UInt16}}()
function mouse_selection_native(scene::SceneLike)
function query_mouse(buff, w, h)
xy = events(scene).mouseposition[]
x, y = Int.(floor.(xy))
if x > 0 && y > 0 && x <= w && y <= h
glReadPixels(x, y, 1, 1, buff.format, buff.pixeltype, _mouse_selection_id)
end
return
end
if !(query_mouse in selection_queries)
push!(selection_queries, query_mouse)
# TODO, this is not optimal since it does way more
# than calling query_mouse() on first click,
# but otherwise it might get into an inconsistent state.
render_frame(getscreen(scene))
end
convert(SelectionID{Int}, _mouse_selection_id[])
end
function mouse_selection(scene::SceneLike)
sid = mouse_selection_native(scene)
screen = getscreen(scene)
if screen != nothing && haskey(screen.cache2plot, sid.id)
plot = screen.cache2plot[sid.id]
return (plot, sid.index)
end
return (nothing, 0)
end
function mouseover(scene::SceneLike, plots::AbstractPlot...)
p, idx = mouse_selection(scene)
p in flatten_plots(plots)
end
function flatten_plots(x::Atomic, plots = AbstractPlot[])
if isempty(x.plots)
push!(plots, x)
else
flatten_plots(x.plots, plots)
end
plots
end
function flatten_plots(x::Combined, plots = AbstractPlot[])
for elem in x.plots
flatten_plots(elem, plots)
end
plots
end
function flatten_plots(array, plots = AbstractPlot[])
for elem in array
flatten_plots(elem, plots)
end
plots
end
function onpick(f, scene::SceneLike, plots::AbstractPlot...)
fplots = flatten_plots(plots)
map_once(events(scene).mouseposition) do mp
p, idx = mouse_selection(scene)
(p in fplots) && f(idx)
return
end
end
function pick(screen::Screen, rect::IRect2D)
window_size = widths(screen)
buff = screen.framebuffer.objectid
sid = zeros(SelectionID{UInt16}, widths(rect)...)
glReadBuffer(GL_COLOR_ATTACHMENT1)
x, y = minimum(rect)
rw, rh = widths(rect)
w, h = window_size
if x > 0 && y > 0 && x <= w && y <= h
glReadPixels(x, y, rw, rh, buff.format, buff.pixeltype, sid)
return map(unique(vec(SelectionID{Int}.(sid)))) do sid
screen.cache2plot[sid.id], Int(sid.index)
end
end
return SelectionID{Int}[]
end