-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathvolume.jl
395 lines (339 loc) · 9.96 KB
/
volume.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
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
translate_4x4(v) = @SMatrix([
1 0 0 v[1]
0 1 0 v[2]
0 0 1 v[3]
0 0 0 1
])
scale_4x4(v) = @SMatrix([
v[1] 0 0 0
0 v[2] 0 0
0 0 v[3] 0
0 0 0 1
])
rotd_x(θ) = @SMatrix([
1 0 0 0
0 cosd(θ) -sind(θ) 0
0 sind(θ) +cosd(θ) 0
0 0 0 1
])
rotd_y(θ) = @SMatrix([
+cosd(θ) 0 sind(θ) 0
0 1 0 0
-sind(θ) 0 cosd(θ) 0
0 0 0 1
])
rotd_z(θ) = @SMatrix([
cosd(θ) -sind(θ) 0 0
sind(θ) +cosd(θ) 0 0
0 0 1 0
0 0 0 1
])
"""
lookat(eye, target, up_vector)
# Description
Computes the scene camera (see songho.ca/opengl/gl_camera.html).
# Arguments
- `eye`: position of the camera in world space (e.g. [0, 0, 10]).
- `target`: target point to look at in world space (usually to origin = [0, 0, 0]).
- `up_vector`: up vector (usually +z = [0, 0, 1]).
"""
function lookat(eye, target = [0, 0, 0], up_vector = [0, 0, 1])
f = normalize(eye - target) # forward vector
l = normalize(cross(up_vector, f)) # left vector
u = cross(f, l) # up vector
@SMatrix(
[
l[1] l[2] l[3] -dot(l, eye)
u[1] u[2] u[3] -dot(u, eye)
f[1] f[2] f[3] -dot(f, eye)
0 0 0 1
]
),
f
end
"""
frustum(l, r, b, t, n, f)
# Description
Computes the perspective projection matrix (see songho.ca/opengl/gl_projectionmatrix.html#perspective).
# Arguments
- `l`: left coordinate of the vertical clipping plane.
- `r`: right coordinate of the vertical clipping plane.
- `b`: bottom coordinate of the horizontal clipping plane.
- `t`: top coordinate of the horizontal clipping plane.
- `n`: distance to the near depth clipping plane.
- `f`: distance to the far depth clipping plane.
"""
function frustum(l, r, b, t, n, f)
@assert n > 0 && f > 0
*(
@SMatrix([ # scale
2n/(r - l) 0 0 0
0 2n/(t - b) 0 0
0 0 1 0
0 0 0 1
]),
@SMatrix([ # translate
1 0 0 (l + r)/2n
0 1 0 (b + t)/2n
0 0 1 0
0 0 0 1
]),
@SMatrix([ # perspective
-1 0 0 0 # flip x
0 -1 0 0 # flip y
0 0 (f + n)/(f - n) -2f * n/(f - n)
0 0 1 0
]),
)
end
"""
ortho(l, r, b, t, n, f)
# Description
Computes the orthographic projection matrix (see songho.ca/opengl/gl_projectionmatrix.html#ortho).
# Arguments
- `l`: left coordinate of the vertical clipping plane.
- `r`: right coordinate of the vertical clipping plane.
- `b`: bottom coordinate of the horizontal clipping plane.
- `t`: top coordinate of the horizontal clipping plane.
- `n`: distance to the near depth clipping plane.
- `f`: distance to the far depth clipping plane.
"""
ortho(l, r, b, t, n, f) = *(
@SMatrix([ # scale
2/(r - l) 0 0 0
0 2/(t - b) 0 0
0 0 2/(f - n) 0
0 0 0 1
]),
@SMatrix([ # translate
1 0 0 -(l + r)/2
0 1 0 -(b + t)/2
0 0 1 -(n + f)/2
0 0 0 1
]),
)
"""
ctr_len_diag(x, y, z)
# Description
Computes data center, minimum and maximum points, and cube diagonal length.
"""
function ctr_len_diag(x, y, z)
mx, Mx = nanless_extrema(x)
my, My = nanless_extrema(y)
mz, Mz = nanless_extrema(z)
lx = Mx - mx
ly = My - my
lz = Mz - mz
(
SVector(mx + 0.5lx, my + 0.5ly, mz + 0.5lz),
SVector(mx, my, mz),
SVector(Mx, My, Mz),
SVector(lx, ly, lz),
√(lx^2 + ly^2 + lz^2),
)
end
cube_corners(mx, Mx, my, My, mz, Mz) = [
mx mx mx mx Mx Mx Mx Mx
my my My My my my My My
mx Mz mx Mz mx Mz mx Mz
]
function view_matrix(center, distance, elevation, azimuth, up)
up_str = string(up)
shift::Int = if (up_axis = Symbol(up_str[end])) ≡ :x
0
elseif up_axis ≡ :y
1
elseif up_axis ≡ :z
2
else
throw(ArgumentError("up vector $up_str not understood"))
end
# we support :x -> +x, :px -> +x or :mx -> -x
up_vector = circshift(
[
length(up_str) == 1 ? 1 : (p = +1, m = -1)[Symbol(up_str[1])]
0
0
],
shift,
)
cam_move = circshift(
distance .* [
sind(elevation)
cosd(azimuth) * cosd(elevation)
sind(azimuth) * cosd(elevation)
],
shift,
)
lookat(center .+ cam_move, center, up_vector)
end
"""
MVP(x, y, z; $(keywords(; default = (), add = (:x, :y, :z, :projection, :elevation, :azimuth, :zoom, :up))))
# Description
Build up the "Model - View - Projection" transformation matrix (see codinglabs.net/article_world_view_projection_matrix.aspx).
This is typically used to adjust how 3D plot is viewed, see also
the `projection` keyword in [`surfaceplot`](@ref), [`isosurface`](@ref).
"""
struct MVP{E,T}
mvp_mat::SMatrix{4,4,T}
mvp_ortho_mat::SMatrix{4,4,T}
mvp_persp_mat::SMatrix{4,4,T}
view_dir::SVector{3,T}
ortho::Bool
dist::T
function MVP() # placeholder for 2D (disabled)
dummy = zeros(Bool, 4, 4)
new{Val{false},Bool}(dummy, dummy, dummy, zeros(Bool, 3), true, true)
end
function MVP(
x,
y,
z;
projection = KEYWORDS.projection,
elevation = KEYWORDS.elevation,
azimuth = KEYWORDS.azimuth,
zoom = KEYWORDS.zoom,
near = KEYWORDS.near,
far = KEYWORDS.far,
up = KEYWORDS.up,
)
@assert projection ∈ (:ortho, :orthographic, :persp, :perspective)
@assert -180 ≤ azimuth ≤ 180
@assert -90 ≤ elevation ≤ 90
F = float(eltype(z))
is_ortho = projection ∈ (:ortho, :orthographic)
ctr, mini, maxi, len, diag = ctr_len_diag(x, y, z)
# half the diagonal (camera distance to the center)
disto = dist = (diag / 2) / zoom
distp = disto / 2
# avoid `NaN`s in `V` when `elevation` is close to ±90
δ = 100eps(F)
elev = clamp(elevation, -90 + δ, 90 - δ)
# Model Matrix
M = SMatrix{4,4,F}(I) # we don't scale, nor translate, nor rotate input data
# View Matrix
V_ortho, view_dir = view_matrix(ctr, disto, elev, azimuth, up)
V_persp, view_dir = view_matrix(ctr, distp, elev, azimuth, up)
V = is_ortho ? V_ortho : V_persp
# Projection Matrix
P_ortho = ortho(-disto, disto, -disto, disto, -disto, disto)
P_persp = frustum(-distp, distp, -distp, distp, near, far)
MVP_ortho = P_ortho * V_ortho * M
MVP_persp = P_persp * V_persp * M
new{Val{true},F}(
is_ortho ? MVP_ortho : MVP_persp,
MVP_ortho,
MVP_persp,
view_dir,
is_ortho,
dist,
)
end
end
create_MVP(projection::Symbol, args...; kw...) = MVP(args...; projection, kw...)
create_MVP(projection::MVP, args...; _...) = projection # NOTE: kw are expected to be lost (see Plots)
create_MVP(::Nothing, args...; _...) = MVP() # NOTE: kw are expected to be lost (see Plots)
@inline is_enabled(::MVP{Val{false}}) = false
@inline is_enabled(::MVP{Val{true}}) = true
@inline transform_matrix(t::MVP{Val{true},T}, n::Symbol) where {T} = if n ≡ :user
t.mvp_mat
elseif n ∈ (:ortho, :orthographic)
t.mvp_ortho_mat
elseif n ∈ (:persp, :perspective)
t.mvp_persp_mat
end::SMatrix{4,4,T}
@inline is_ortho(t::MVP, n::Symbol) = if n ≡ :user
t.ortho
elseif n ∈ (:ortho, :orthographic)
true
elseif n ∈ (:persp, :perspective)
false
end::Bool
"transform a matrix of points, with allocation"
function (tr::MVP{Val{true},T})(p::AbstractMatrix, n::Symbol = :user) where {T}
o = Array{T}(undef, 4, size(p, 2))
tr(p, o, n)
@view(o[1, :]), @view(o[2, :])
end
"inplace transform"
function (tr::MVP{Val{true},T})(
p::AbstractMatrix,
o::AbstractMatrix,
n::Symbol = :user,
) where {T}
mul!(o, transform_matrix(tr, n), p)
persp = !is_ortho(tr, n)
# homogeneous coordinates
@inbounds for i ∈ axes(p, 2)
w = o[4, i]
if abs(w) > eps(T)
o[1, i] /= w
o[2, i] /= w
o[3, i] /= w
end
if persp
z = o[3, i]
if abs(z) > eps(T)
o[1, i] /= z
o[2, i] /= z
end
end
end
nothing
end
"transform a vector"
function (tr::MVP{Val{true},T})(v::SVector{4}, n::Symbol = :user) where {T}
x, y, z, w = transform_matrix(tr, n) * v
# homogeneous coordinates
if abs(w) > eps(T)
x /= w
y /= w
z /= w
end
if !is_ortho(tr, n)
x /= z
y /= z
end
(x, y)
end
(tr::MVP{Val{true}})(v::AbstractVector{T}, n::Symbol = :user) where {T} =
tr(SVector(v[1], v[2], v[3], length(v) == 4 ? v[4] : T(1)), n)
axis_line(tr, proj, start::AbstractVector{T}, stop::AbstractVector{T}) where {T} =
tr(@SMatrix([
start[1] stop[1]
start[2] stop[2]
start[3] stop[3]
T(1) T(1)
]), proj)
"""
draw_axes!(plot, x, y, z, scale = 0.25)
# Description
Draws (X, Y, Z) cartesian coordinates axes in (R, G, B) colors, at position `p = (x, y, z)`.
If `p = (x, y)` is given, draws at screen coordinates instead.
"""
function draw_axes!(plot, x::T, y::T, z::T, scale = T(0.25)) where {T<:AbstractFloat}
tr = plot.projection
# constant apparent size, independent of zoom level
len = T(scale * tr.dist)
start = SVector(x, y, z)
lines!(
plot.graphics,
axis_line(tr, :ortho, start, SVector(x + len, y, z))...,
color = :red,
)
lines!(
plot.graphics,
axis_line(tr, :ortho, start, SVector(x, y + len, z))...,
color = :green,
)
lines!(
plot.graphics,
axis_line(tr, :ortho, start, SVector(x, y, z + len))...,
color = :blue,
)
plot
end
draw_axes!(plot, x::T, y::T, z::Nothing, args...) where {T<:AbstractFloat} =
let (x, y, z) = transform_matrix(plot.projection, :ortho) \ SVector(x, y, T(0), T(1))
draw_axes!(plot, x, y, z, args...)
end