diff --git a/CairoMakie/src/CairoMakie.jl b/CairoMakie/src/CairoMakie.jl index b5995fe1f33..0a0c6d5cb72 100644 --- a/CairoMakie/src/CairoMakie.jl +++ b/CairoMakie/src/CairoMakie.jl @@ -15,7 +15,7 @@ using Makie: spaces, is_data_space, is_pixel_space, is_relative_space, is_clip_s using Makie: numbers_to_colors # re-export Makie, including deprecated names -for name in names(Makie, all=true) +for name in names(Makie, all = true) if Base.isexported(Makie, name) @eval using Makie: $(name) @eval export $(name) diff --git a/CairoMakie/src/cairo-extension.jl b/CairoMakie/src/cairo-extension.jl index a2a67344627..8920ea0c83c 100644 --- a/CairoMakie/src/cairo-extension.jl +++ b/CairoMakie/src/cairo-extension.jl @@ -40,18 +40,18 @@ end function show_glyph(ctx, glyph, x, y) cg = Ref(CairoGlyph(glyph, x, y)) ccall((:cairo_show_glyphs, Cairo.libcairo), - Nothing, (Ptr{Nothing}, Ptr{CairoGlyph}, Cint), - ctx.ptr, cg, 1) + Nothing, (Ptr{Nothing}, Ptr{CairoGlyph}, Cint), + ctx.ptr, cg, 1) end function glyph_path(ctx, glyph, x, y) cg = Ref(CairoGlyph(glyph, x, y)) ccall((:cairo_glyph_path, Cairo.libcairo), - Nothing, (Ptr{Nothing}, Ptr{CairoGlyph}, Cint), - ctx.ptr, cg, 1) + Nothing, (Ptr{Nothing}, Ptr{CairoGlyph}, Cint), + ctx.ptr, cg, 1) end -function surface_set_device_scale(surf, device_x_scale, device_y_scale=device_x_scale) +function surface_set_device_scale(surf, device_x_scale, device_y_scale = device_x_scale) # this sets a scaling factor on the lowest level that is "hidden" so its even # enabled when the drawing space is reset for strokes # that means it can be used to increase or decrease the image resolution diff --git a/CairoMakie/src/display.jl b/CairoMakie/src/display.jl index d5cf249942b..6deaabc5392 100644 --- a/CairoMakie/src/display.jl +++ b/CairoMakie/src/display.jl @@ -38,13 +38,13 @@ function display_path(type::String) return abspath(joinpath(@__DIR__, "display." * type)) end -function Base.display(screen::Screen, scene::Scene; connect=false) +function Base.display(screen::Screen, scene::Scene; connect = false) # Nothing to do, since drawing is done in the other functions # TODO write to file and implement upenurl return screen end -function Base.display(screen::Screen{IMAGE}, scene::Scene; connect=false) +function Base.display(screen::Screen{IMAGE}, scene::Scene; connect = false) path = display_path("png") Makie.push_screen!(scene, screen) cairo_draw(screen, scene) @@ -133,7 +133,7 @@ end Converts anything like `"png", :png, "image/png", MIME"image/png"()` to `"image/png"`. """ -function to_mime_string(mime::Union{String, Symbol, MIME}) +function to_mime_string(mime::Union{String,Symbol,MIME}) if mime isa MIME mime_str = string(mime) if !(mime_str in SUPPORTED_MIMES) @@ -156,7 +156,7 @@ The default is automatic, which lets the display system figure out the best mime If set to any other valid mime, will result in `showable(any_other_mime, figurelike)` to return false and only return true for `showable(preferred_mime, figurelike)`. Depending on the display system used, this may result in nothing getting displayed. """ -function disable_mime!(mimes::Union{String, Symbol, MIME}...) +function disable_mime!(mimes::Union{String,Symbol,MIME}...) empty!(DISABLED_MIMES) # always start from 0 if isempty(mimes) # Reset disabled mimes when called with no arguments @@ -170,7 +170,7 @@ function disable_mime!(mimes::Union{String, Symbol, MIME}...) return end -function enable_only_mime!(mimes::Union{String, Symbol, MIME}...) +function enable_only_mime!(mimes::Union{String,Symbol,MIME}...) empty!(DISABLED_MIMES) # always start from 0 if isempty(mimes) # Reset disabled mimes when called with no arguments diff --git a/CairoMakie/src/infrastructure.jl b/CairoMakie/src/infrastructure.jl index ffe6741e10d..30c7b0c74d1 100644 --- a/CairoMakie/src/infrastructure.jl +++ b/CairoMakie/src/infrastructure.jl @@ -90,13 +90,13 @@ function draw_background(screen::Screen, scene::Scene) Cairo.save(cr) if scene.clear[] bg = scene.backgroundcolor[] - Cairo.set_source_rgba(cr, red(bg), green(bg), blue(bg), alpha(bg)); + Cairo.set_source_rgba(cr, red(bg), green(bg), blue(bg), alpha(bg)) r = pixelarea(scene)[] Cairo.rectangle(cr, origin(r)..., widths(r)...) # background fill(cr) end Cairo.restore(cr) - foreach(child_scene-> draw_background(screen, child_scene), scene.children) + foreach(child_scene -> draw_background(screen, child_scene), scene.children) end function draw_plot(scene::Scene, screen::Screen, primitive::Combined) diff --git a/CairoMakie/src/overrides.jl b/CairoMakie/src/overrides.jl index 3630440ae5a..4a9ef8d946b 100644 --- a/CairoMakie/src/overrides.jl +++ b/CairoMakie/src/overrides.jl @@ -36,8 +36,8 @@ function draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}) end # when color is a Makie.AbstractPattern, we don't need to go to Mesh -function draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}, color::Union{Symbol, Colorant, Makie.AbstractPattern}, - model, strokecolor, strokewidth) +function draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}, color::Union{Symbol,Colorant,Makie.AbstractPattern}, + model, strokecolor, strokewidth) space = to_value(get(poly, :space, :data)) points = project_position.(Ref(scene), space, points, Ref(model)) Cairo.move_to(screen.context, points[1]...) @@ -47,7 +47,7 @@ function draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}, Cairo.close_path(screen.context) if color isa Makie.AbstractPattern cairopattern = Cairo.CairoPattern(color) - Cairo.pattern_set_extend(cairopattern, Cairo.EXTEND_REPEAT); + Cairo.pattern_set_extend(cairopattern, Cairo.EXTEND_REPEAT) Cairo.set_source(screen.context, cairopattern) else Cairo.set_source_rgba(screen.context, rgbatuple(to_color(color))...) @@ -63,7 +63,7 @@ function draw_poly(scene::Scene, screen::Screen, poly, points_list::Vector{<:Vec broadcast_foreach(points_list, poly.color[], poly.strokecolor[], poly.strokewidth[]) do points, color, strokecolor, strokewidth - draw_poly(scene, screen, poly, points, color, poly.model[], strokecolor, strokewidth) + draw_poly(scene, screen, poly, points, color, poly.model[], strokecolor, strokewidth) end end @@ -82,7 +82,7 @@ function draw_poly(scene::Scene, screen::Screen, poly, rects::Vector{<:Rect2}) color = to_color(color) elseif color isa Makie.AbstractPattern cairopattern = Cairo.CairoPattern(color) - Cairo.pattern_set_extend(cairopattern, Cairo.EXTEND_REPEAT); + Cairo.pattern_set_extend(cairopattern, Cairo.EXTEND_REPEAT) end strokecolor = poly.strokecolor[] if strokecolor isa AbstractArray{<:Number} @@ -164,7 +164,7 @@ end ################################################################################ function draw_plot(scene::Scene, screen::Screen, - band::Band{<:Tuple{<:AbstractVector{<:Point2},<:AbstractVector{<:Point2}}}) + band::Band{<:Tuple{<:AbstractVector{<:Point2},<:AbstractVector{<:Point2}}}) if !(band.color[] isa AbstractArray) upperpoints = band[1][] @@ -211,7 +211,7 @@ function draw_plot(scene::Scene, screen::Screen, tric::Tricontourf) function draw_tripolys(polys, colornumbers, colors) for (i, (pol, colnum, col)) in enumerate(zip(polys, colornumbers, colors)) polypath(screen.context, pol) - if i == length(colornumbers) || colnum != colornumbers[i+1] + if i == length(colornumbers) || colnum != colornumbers[i + 1] Cairo.set_source_rgba(screen.context, rgbatuple(col)...) Cairo.fill(screen.context) end diff --git a/CairoMakie/src/primitives.jl b/CairoMakie/src/primitives.jl index 765295e6d0a..c8547d058a4 100644 --- a/CairoMakie/src/primitives.jl +++ b/CairoMakie/src/primitives.jl @@ -2,7 +2,7 @@ # Lines, LineSegments # ################################################################################ -function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Union{Lines, LineSegments})) +function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Union{Lines,LineSegments})) fields = @get_attribute(primitive, (color, linewidth, linestyle)) linestyle = Makie.convert_attribute(linestyle, Makie.key"linestyle"()) ctx = screen.context @@ -16,7 +16,7 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Unio # a vector of tuples of two points. we convert those to a list of points # so they don't trip up the rest of the pipeline # TODO this shouldn't be necessary anymore! - if positions isa SubArray{<:Point3, 1, P, <:Tuple{Array{<:AbstractFace}}} where P + if positions isa SubArray{<:Point3,1,P,<:Tuple{Array{<:AbstractFace}}} where P positions = let pos = Point3f[] for tup in positions @@ -30,7 +30,7 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Unio space = to_value(get(primitive, :space, :data)) projected_positions = project_position.(Ref(scene), Ref(space), positions, Ref(model)) - if color isa AbstractArray{<: Number} + if color isa AbstractArray{<:Number} color = numbers_to_colors(color, primitive) end @@ -79,12 +79,12 @@ function draw_single(primitive::Lines, ctx, positions) # only take action for non-NaNs if !isnan(p) # new line segment at beginning or if previously NaN - if i == 1 || isnan(positions[i-1]) + if i == 1 || isnan(positions[i - 1]) Cairo.move_to(ctx, p...) else Cairo.line_to(ctx, p...) # complete line segment at end or if next point is NaN - if i == n || isnan(positions[i+1]) + if i == n || isnan(positions[i + 1]) Cairo.stroke(ctx) end end @@ -98,9 +98,9 @@ function draw_single(primitive::LineSegments, ctx, positions) @assert iseven(length(positions)) - @inbounds for i in 1:2:length(positions)-1 + @inbounds for i in 1:2:(length(positions) - 1) p1 = positions[i] - p2 = positions[i+1] + p2 = positions[i + 1] if isnan(p1) || isnan(p2) continue @@ -124,7 +124,7 @@ function draw_multi(primitive, ctx, positions, color, linewidths::AbstractArray, draw_multi(primitive, ctx, positions, [color for l in linewidths], linewidths, dash) end -function draw_multi(primitive::Union{Lines, LineSegments}, ctx, positions, colors::AbstractArray, linewidths::AbstractArray, dash) +function draw_multi(primitive::Union{Lines,LineSegments}, ctx, positions, colors::AbstractArray, linewidths::AbstractArray, dash) if primitive isa LineSegments @assert iseven(length(positions)) end @@ -132,32 +132,32 @@ function draw_multi(primitive::Union{Lines, LineSegments}, ctx, positions, color @assert length(linewidths) == length(colors) iterator = if primitive isa Lines - 1:length(positions)-1 + 1:(length(positions) - 1) elseif primitive isa LineSegments 1:2:length(positions) end for i in iterator - if isnan(positions[i+1]) || isnan(positions[i]) + if isnan(positions[i + 1]) || isnan(positions[i]) continue end Cairo.move_to(ctx, positions[i]...) - Cairo.line_to(ctx, positions[i+1]...) - if linewidths[i] != linewidths[i+1] + Cairo.line_to(ctx, positions[i + 1]...) + if linewidths[i] != linewidths[i + 1] error("Cairo doesn't support two different line widths ($(linewidths[i]) and $(linewidths[i+1])) at the endpoints of a line.") end Cairo.set_line_width(ctx, linewidths[i]) !isnothing(dash) && Cairo.set_dash(ctx, dash .* linewidths[i]) c1 = colors[i] - c2 = colors[i+1] + c2 = colors[i + 1] # we can avoid the more expensive gradient if the colors are the same # this happens if one color was given for each segment if c1 == c2 Cairo.set_source_rgba(ctx, red(c1), green(c1), blue(c1), alpha(c1)) Cairo.stroke(ctx) else - pat = Cairo.pattern_create_linear(positions[i]..., positions[i+1]...) + pat = Cairo.pattern_create_linear(positions[i]..., positions[i + 1]...) Cairo.pattern_add_color_stop_rgba(pat, 0, red(c1), green(c1), blue(c1), alpha(c1)) Cairo.pattern_add_color_stop_rgba(pat, 1, red(c2), green(c2), blue(c2), alpha(c2)) Cairo.set_source(ctx, pat) @@ -185,7 +185,7 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Scat font = to_font(to_value(get(primitive, :font, Makie.defaultfont()))) - colors = if color isa AbstractArray{<: Number} + colors = if color isa AbstractArray{<:Number} numbers_to_colors(color, primitive) else color @@ -205,12 +205,12 @@ end _marker_convert(markers::AbstractArray) = map(m -> convert_attribute(m, key"marker"(), key"scatter"()), markers) _marker_convert(marker) = convert_attribute(marker, key"marker"(), key"scatter"()) # image arrays need to be converted as a whole -_marker_convert(marker::AbstractMatrix{<:Colorant}) = [ convert_attribute(marker, key"marker"(), key"scatter"()) ] +_marker_convert(marker::AbstractMatrix{<:Colorant}) = [convert_attribute(marker, key"marker"(), key"scatter"())] function draw_atomic_scatter(scene, ctx, transfunc, colors, markersize, strokecolor, strokewidth, marker, marker_offset, rotations, model, positions, size_model, font, markerspace, space) broadcast_foreach(positions, colors, markersize, strokecolor, - strokewidth, marker, marker_offset, remove_billboard(rotations)) do point, col, - markersize, strokecolor, strokewidth, m, mo, rotation + strokewidth, marker, marker_offset, remove_billboard(rotations)) do point, col, + markersize, strokecolor, strokewidth, m, mo, rotation scale = project_scale(scene, markerspace, markersize, size_model) offset = project_scale(scene, markerspace, mo, size_model) @@ -287,17 +287,17 @@ function draw_marker(ctx, marker::Char, font, pos, scale, strokecolor, strokewid set_font_matrix(ctx, old_matrix) end -function draw_marker(ctx, ::Type{<: Circle}, pos, scale, strokecolor, strokewidth, marker_offset, rotation) +function draw_marker(ctx, ::Type{<:Circle}, pos, scale, strokecolor, strokewidth, marker_offset, rotation) marker_offset = marker_offset + scale ./ 2 pos += Point2f(marker_offset[1], -marker_offset[2]) if scale[1] != scale[2] old_matrix = Cairo.get_matrix(ctx) Cairo.scale(ctx, scale[1], scale[2]) - Cairo.translate(ctx, pos[1]/scale[1], pos[2]/scale[2]) - Cairo.arc(ctx, 0, 0, 0.5, 0, 2*pi) + Cairo.translate(ctx, pos[1] / scale[1], pos[2] / scale[2]) + Cairo.arc(ctx, 0, 0, 0.5, 0, 2 * pi) else - Cairo.arc(ctx, pos[1], pos[2], scale[1]/2, 0, 2*pi) + Cairo.arc(ctx, pos[1], pos[2], scale[1] / 2, 0, 2 * pi) end Cairo.fill_preserve(ctx) @@ -311,7 +311,7 @@ function draw_marker(ctx, ::Type{<: Circle}, pos, scale, strokecolor, strokewidt nothing end -function draw_marker(ctx, ::Type{<: Rect}, pos, scale, strokecolor, strokewidth, marker_offset, rotation) +function draw_marker(ctx, ::Type{<:Rect}, pos, scale, strokecolor, strokewidth, marker_offset, rotation) s2 = Point2((scale .* (1, -1))...) pos = pos .+ Point2f(marker_offset[1], -marker_offset[2]) Cairo.rotate(ctx, to_2d_rotation(rotation)) @@ -357,21 +357,21 @@ end function draw_marker(ctx, marker::Matrix{T}, pos, scale, - strokecolor #= unused =#, strokewidth #= unused =#, - marker_offset, rotation) where T<:Colorant + strokecolor, strokewidth, #= unused =# + marker_offset, rotation) where T<:Colorant # convert marker to Cairo compatible image data - marker = permutedims(marker, (2,1)) + marker = permutedims(marker, (2, 1)) marker_surf = to_cairo_image(marker, ()) w, h = size(marker) Cairo.translate(ctx, - scale[1]/2 + pos[1] + marker_offset[1], - scale[2]/2 + pos[2] + marker_offset[2]) + scale[1] / 2 + pos[1] + marker_offset[1], + scale[2] / 2 + pos[2] + marker_offset[2]) Cairo.rotate(ctx, to_2d_rotation(rotation)) Cairo.scale(ctx, scale[1] / w, scale[2] / h) - Cairo.set_source_surface(ctx, marker_surf, -w/2, -h/2) + Cairo.set_source_surface(ctx, marker_surf, -w / 2, -h / 2) Cairo.paint(ctx) end @@ -382,13 +382,13 @@ end function p3_to_p2(p::Point3{T}) where T if p[3] == 0 || isnan(p[3]) - Point2{T}(p[Vec(1,2)]...) + Point2{T}(p[Vec(1, 2)]...) else error("Can't reduce Point3 to Point2 with nonzero third component $(p[3]).") end end -function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Text{<:Tuple{<:Union{AbstractArray{<:Makie.GlyphCollection}, Makie.GlyphCollection}}})) +function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Text{<:Tuple{<:Union{AbstractArray{<:Makie.GlyphCollection},Makie.GlyphCollection}}})) ctx = screen.context @get_attribute(primitive, (rotation, model, space, markerspace, offset)) position = primitive.position[] @@ -405,9 +405,9 @@ end function draw_glyph_collection( - scene, ctx, positions, glyph_collections::AbstractArray, rotation, - model::Mat, space, markerspace, offset - ) + scene, ctx, positions, glyph_collections::AbstractArray, rotation, + model::Mat, space, markerspace, offset +) # TODO: why is the Ref around model necessary? doesn't broadcast_foreach handle staticarrays matrices? broadcast_foreach(positions, glyph_collections, rotation, Ref(model), space, @@ -447,7 +447,7 @@ function draw_glyph_collection(scene, ctx, position, glyph_collection, rotation, Cairo.save(ctx) broadcast_foreach(glyphs, glyphoffsets, fonts, rotations, scales, colors, strokewidths, strokecolors, offsets) do glyph, - glyphoffset, font, rotation, scale, color, strokewidth, strokecolor, offset + glyphoffset, font, rotation, scale, color, strokewidth, strokecolor, offset cairoface = set_ft_font(ctx, font) old_matrix = get_font_matrix(ctx) @@ -524,13 +524,13 @@ If not, returns array unchanged. function regularly_spaced_array_to_range(arr) diffs = unique!(sort!(diff(arr))) step = sum(diffs) ./ length(diffs) - if all(x-> x ≈ step, diffs) + if all(x -> x ≈ step, diffs) m, M = extrema(arr) if step < zero(step) m, M = M, m end # don't use stop=M, since that may not include M - return range(m; step=step, length=length(arr)) + return range(m; step = step, length = length(arr)) else return arr end @@ -546,21 +546,21 @@ premultiplied_rgba(a::AbstractArray{<:Color}) = RGBA.(a) premultiplied_rgba(r::RGBA) = RGBA(r.r * r.alpha, r.g * r.alpha, r.b * r.alpha, r.alpha) premultiplied_rgba(c::Colorant) = premultiplied_rgba(RGBA(c)) -function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Union{Heatmap, Image})) +function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Union{Heatmap,Image})) ctx = screen.context image = primitive[3][] xs, ys = primitive[1][], primitive[2][] if !(xs isa AbstractVector) l, r = extrema(xs) N = size(image, 1) - xs = range(l, r, length = N+1) + xs = range(l, r, length = N + 1) else xs = regularly_spaced_array_to_range(xs) end if !(ys isa AbstractVector) l, r = extrema(ys) N = size(image, 2) - ys = range(l, r, length = N+1) + ys = range(l, r, length = N + 1) else ys = regularly_spaced_array_to_range(ys) end @@ -574,7 +574,7 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Unio # Vector backends don't support FILTER_NEAREST for interp == false, so in that case we also need to draw rects is_vector = is_vector_backend(ctx) t = Makie.transform_func_obs(primitive)[] - identity_transform = (t === identity || t isa Tuple && all(x-> x === identity, t)) && (abs(model[1, 2]) < 1e-15) + identity_transform = (t === identity || t isa Tuple && all(x -> x === identity, t)) && (abs(model[1, 2]) < 1e-15) regular_grid = xs isa AbstractRange && ys isa AbstractRange if interpolate @@ -635,9 +635,9 @@ end function _draw_rect_heatmap(ctx, xys, ni, nj, colors) @inbounds for i in 1:ni, j in 1:nj p1 = xys[i, j] - p2 = xys[i+1, j] - p3 = xys[i+1, j+1] - p4 = xys[i, j+1] + p2 = xys[i + 1, j] + p3 = xys[i + 1, j + 1] + p4 = xys[i, j + 1] # Rectangles and polygons that are directly adjacent usually show # white lines between them due to anti aliasing. To avoid this we @@ -649,10 +649,10 @@ function _draw_rect_heatmap(ctx, xys, ni, nj, colors) # model matrix.) (i!=1) etc is used to avoid increasing the # outer extent of the heatmap. center = 0.25f0 * (p1 + p2 + p3 + p4) - p1 += sign.(p1 - center) .* Point2f(0.5f0 * (i!=1), 0.5f0 * (j!=1)) - p2 += sign.(p2 - center) .* Point2f(0.5f0 * (i!=ni), 0.5f0 * (j!=1)) - p3 += sign.(p3 - center) .* Point2f(0.5f0 * (i!=ni), 0.5f0 * (j!=nj)) - p4 += sign.(p4 - center) .* Point2f(0.5f0 * (i!=1), 0.5f0 * (j!=nj)) + p1 += sign.(p1 - center) .* Point2f(0.5f0 * (i != 1), 0.5f0 * (j != 1)) + p2 += sign.(p2 - center) .* Point2f(0.5f0 * (i != ni), 0.5f0 * (j != 1)) + p3 += sign.(p3 - center) .* Point2f(0.5f0 * (i != ni), 0.5f0 * (j != nj)) + p4 += sign.(p4 - center) .* Point2f(0.5f0 * (i != 1), 0.5f0 * (j != nj)) end Cairo.set_line_width(ctx, 0) @@ -674,7 +674,7 @@ end function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Makie.Mesh)) mesh = primitive[1][] - if Makie.cameracontrols(scene) isa Union{Camera2D, Makie.PixelCamera, Makie.EmptyCamera} + if Makie.cameracontrols(scene) isa Union{Camera2D,Makie.PixelCamera,Makie.EmptyCamera} draw_mesh2D(scene, screen, primitive, mesh) else if !haskey(primitive, :faceculling) @@ -688,12 +688,12 @@ end function draw_mesh2D(scene, screen, @nospecialize(plot), @nospecialize(mesh)) @get_attribute(plot, (color,)) color = to_color(hasproperty(mesh, :color) ? mesh.color : color) - vs = decompose(Point2f, mesh)::Vector{Point2f} + vs = decompose(Point2f, mesh)::Vector{Point2f} fs = decompose(GLTriangleFace, mesh)::Vector{GLTriangleFace} - uv = decompose_uv(mesh)::Union{Nothing, Vector{Vec2f}} + uv = decompose_uv(mesh)::Union{Nothing,Vector{Vec2f}} model = plot.model[]::Mat4f colormap = haskey(plot, :colormap) ? to_colormap(plot.colormap[]) : nothing - colorrange = convert_attribute(to_value(get(plot, :colorrange, nothing)), key"colorrange"())::Union{Nothing, Vec2f} + colorrange = convert_attribute(to_value(get(plot, :colorrange, nothing)), key"colorrange"())::Union{Nothing,Vec2f} lowclip = get_color_attr(plot, :lowclip) highclip = get_color_attr(plot, :highclip) @@ -708,7 +708,7 @@ function draw_mesh2D(scene, screen, @nospecialize(plot), @nospecialize(mesh)) end function draw_mesh2D(scene, screen, per_face_cols, space::Symbol, - vs::Vector{Point2f}, fs::Vector{GLTriangleFace}, model::Mat4f) + vs::Vector{Point2f}, fs::Vector{GLTriangleFace}, model::Mat4f) ctx = screen.context # Priorize colors of the mesh if present @@ -716,7 +716,7 @@ function draw_mesh2D(scene, screen, per_face_cols, space::Symbol, for (f, (c1, c2, c3)) in zip(fs, per_face_cols) pattern = Cairo.CairoPatternMesh() - t1, t2, t3 = project_position.(scene, space, vs[f], (model,)) #triangle points + t1, t2, t3 = project_position.(scene, space, vs[f], (model,)) #triangle points Cairo.mesh_pattern_begin_patch(pattern) Cairo.mesh_pattern_move_to(pattern, t1...) @@ -749,14 +749,14 @@ function draw_mesh3D(scene, screen, attributes, mesh; pos = Vec4f(0), scale = 1f @get_attribute(attributes, (color,)) colormap = haskey(attributes, :colormap) ? to_colormap(attributes.colormap[]) : nothing - colorrange = convert_attribute(to_value(get(attributes, :colorrange, nothing)), key"colorrange"())::Union{Nothing, Vec2f} + colorrange = convert_attribute(to_value(get(attributes, :colorrange, nothing)), key"colorrange"())::Union{Nothing,Vec2f} matcap = to_value(get(attributes, :matcap, nothing)) color = hasproperty(mesh, :color) ? mesh.color : color meshpoints = decompose(Point3f, mesh)::Vector{Point3f} meshfaces = decompose(GLTriangleFace, mesh)::Vector{GLTriangleFace} meshnormals = decompose_normals(mesh)::Vector{Vec3f} - meshuvs = texturecoordinates(mesh)::Union{Nothing, Vector{Vec2f}} + meshuvs = texturecoordinates(mesh)::Union{Nothing,Vector{Vec2f}} lowclip = get_color_attr(attributes, :lowclip) highclip = get_color_attr(attributes, :highclip) @@ -781,10 +781,10 @@ function draw_mesh3D(scene, screen, attributes, mesh; pos = Vec4f(0), scale = 1f end function draw_mesh3D( - scene, screen, space, meshpoints, meshfaces, meshnormals, per_face_col, pos, scale, - model, shading, diffuse, - specular, shininess, faceculling - ) + scene, screen, space, meshpoints, meshfaces, meshnormals, per_face_col, pos, scale, + model, shading, diffuse, + specular, shininess, faceculling +) ctx = screen.context view = ifelse(is_data_space(space), scene.camera.view[], Mat4f(I)) projection = Makie.space_to_clip(scene.camera, space, false) @@ -846,7 +846,7 @@ function draw_mesh3D( end function _calculate_shaded_vertexcolors(N, v, c, lightpos, ambient, diffuse, specular, shininess) - L = normalize(lightpos .- v[Vec(1,2,3)]) + L = normalize(lightpos .- v[Vec(1, 2, 3)]) diff_coeff = max(dot(L, N), 0f0) H = normalize(L + normalize(-v[Vec(1, 2, 3)])) spec_coeff = max(dot(H, N), 0f0)^shininess @@ -904,7 +904,7 @@ function draw_pattern(ctx, zorder, shading, meshfaces, ts, per_face_col, ns, vs, Cairo.paint(ctx) Cairo.destroy(pattern) end - + end ################################################################################ @@ -928,11 +928,11 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Maki end function surface2mesh(xs, ys, zs::AbstractMatrix) - ps = Makie.matrix_grid(p-> nan2zero.(p), xs, ys, zs) + ps = Makie.matrix_grid(p -> nan2zero.(p), xs, ys, zs) rect = Tesselation(Rect2f(0, 0, 1, 1), size(zs)) faces = decompose(QuadFace{Int}, rect) - uv = map(x-> Vec2f(1f0 - x[2], 1f0 - x[1]), decompose_uv(rect)) - uvm = GeometryBasics.Mesh(GeometryBasics.meta(ps; uv=uv), faces) + uv = map(x -> Vec2f(1f0 - x[2], 1f0 - x[1]), decompose_uv(rect)) + uvm = GeometryBasics.Mesh(GeometryBasics.meta(ps; uv = uv), faces) return GeometryBasics.normal_mesh(uvm) end @@ -944,7 +944,7 @@ end function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Makie.MeshScatter)) @get_attribute(primitive, (color, model, marker, markersize, rotations)) - if color isa AbstractArray{<: Number} + if color isa AbstractArray{<:Number} color = numbers_to_colors(color, primitive) end @@ -955,17 +955,17 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Maki view = scene.camera.view[] zorder = sortperm(pos, by = p -> begin - p4d = to_ndim(Vec4f, to_ndim(Vec3f, p, 0f0), 1f0) - cam_pos = view * model * p4d - cam_pos[3] / cam_pos[4] - end, rev=false) + p4d = to_ndim(Vec4f, to_ndim(Vec3f, p, 0f0), 1f0) + cam_pos = view * model * p4d + cam_pos[3] / cam_pos[4] + end, rev = false) submesh = Attributes( - model=model, - color=color, - shading=primitive.shading, diffuse=primitive.diffuse, - specular=primitive.specular, shininess=primitive.shininess, - faceculling=get(primitive, :faceculling, -10) + model = model, + color = color, + shading = primitive.shading, diffuse = primitive.diffuse, + specular = primitive.specular, shininess = primitive.shininess, + faceculling = get(primitive, :faceculling, -10) ) if !(rotations isa Vector) diff --git a/CairoMakie/src/screen.jl b/CairoMakie/src/screen.jl index 2dd3f7232df..f8d9f7d5537 100644 --- a/CairoMakie/src/screen.jl +++ b/CairoMakie/src/screen.jl @@ -110,7 +110,7 @@ Note, that the `screen_config` can also be set permanently via `Makie.set_theme! $(Base.doc(ScreenConfig)) """ -function activate!(; inline=LAST_INLINE[], type="png", screen_config...) +function activate!(; inline = LAST_INLINE[], type = "png", screen_config...) Makie.inline!(inline) LAST_INLINE[] = inline Makie.set_screen_config!(CairoMakie, screen_config) @@ -222,7 +222,7 @@ function scaled_scene_resolution(typ::RenderType, config::ScreenConfig, scene::S end function Makie.apply_screen_config!( - screen::Screen{SCREEN_RT}, config::ScreenConfig, scene::Scene, io::Union{Nothing, IO}, m::MIME{SYM}) where {SYM, SCREEN_RT} + screen::Screen{SCREEN_RT}, config::ScreenConfig, scene::Scene, io::Union{Nothing,IO}, m::MIME{SYM}) where {SYM,SCREEN_RT} # the surface size is the scene size scaled by the device scaling factor new_rendertype = mime_to_rendertype(SYM) # we need to re-create the screen if the rendertype changes, or for all vector backends @@ -251,7 +251,7 @@ end Screen(scene::Scene, config::ScreenConfig) = Screen(scene, config, nothing, IMAGE) -function Screen(screen::Screen, io_or_path::Union{Nothing, String, IO}, typ::Union{MIME, Symbol, RenderType}) +function Screen(screen::Screen, io_or_path::Union{Nothing,String,IO}, typ::Union{MIME,Symbol,RenderType}) rtype = convert(RenderType, typ) # the resolution may change between rendertypes, so, we can't just use `size(screen)` here for recreating the Screen: w, h = scaled_scene_resolution(rtype, screen.config, screen.scene) @@ -259,7 +259,7 @@ function Screen(screen::Screen, io_or_path::Union{Nothing, String, IO}, typ::Uni return Screen(screen.scene, screen.config, surface) end -function Screen(scene::Scene, config::ScreenConfig, io_or_path::Union{Nothing, String, IO}, typ::Union{MIME, Symbol, RenderType}) +function Screen(scene::Scene, config::ScreenConfig, io_or_path::Union{Nothing,String,IO}, typ::Union{MIME,Symbol,RenderType}) rtype = convert(RenderType, typ) w, h = scaled_scene_resolution(rtype, config, scene) surface = surface_from_output_type(rtype, io_or_path, w, h) diff --git a/CairoMakie/src/utils.jl b/CairoMakie/src/utils.jl index 695f957aa0e..fdee8bfca03 100644 --- a/CairoMakie/src/utils.jl +++ b/CairoMakie/src/utils.jl @@ -52,7 +52,7 @@ function project_rect(scene, space, rect::Rect, model) return Rect(mini, maxi .- mini) end -function project_polygon(scene, space, poly::P, model) where P <: Polygon +function project_polygon(scene, space, poly::P, model) where P<:Polygon ext = decompose(Point2f, poly.exterior) interiors = decompose.(Point2f, poly.interiors) Polygon( @@ -117,11 +117,11 @@ to_uint32_color(c) = reinterpret(UInt32, convert(ARGB32, premultiplied_rgba(c))) # Image/heatmap -> ARGBSurface # ######################################## -function to_cairo_image(img::AbstractMatrix{<: AbstractFloat}, attributes) +function to_cairo_image(img::AbstractMatrix{<:AbstractFloat}, attributes) to_cairo_image(to_rgba_image(img, attributes), attributes) end -function to_rgba_image(img::AbstractMatrix{<: AbstractFloat}, attributes) +function to_rgba_image(img::AbstractMatrix{<:AbstractFloat}, attributes) Makie.@get_attribute attributes (colormap, colorrange, nan_color, lowclip, highclip) nan_color = Makie.to_color(nan_color) @@ -131,7 +131,7 @@ function to_rgba_image(img::AbstractMatrix{<: AbstractFloat}, attributes) [get_rgba_pixel(pixel, colormap, colorrange, nan_color, lowclip, highclip) for pixel in img] end -to_rgba_image(img::AbstractMatrix{<: Colorant}, attributes) = RGBAf.(img) +to_rgba_image(img::AbstractMatrix{<:Colorant}, attributes) = RGBAf.(img) function get_rgba_pixel(pixel, colormap, colorrange, nan_color, lowclip, highclip) vmin, vmax = colorrange @@ -146,7 +146,7 @@ function get_rgba_pixel(pixel, colormap, colorrange, nan_color, lowclip, highcli end end -function to_cairo_image(img::AbstractMatrix{<: Colorant}, attributes) +function to_cairo_image(img::AbstractMatrix{<:Colorant}, attributes) to_cairo_image(to_uint32_color.(img), attributes) end @@ -161,19 +161,19 @@ end # Mesh handling # ################################################################################ -struct FaceIterator{Iteration, T, F, ET} <: AbstractVector{ET} +struct FaceIterator{Iteration,T,F,ET} <: AbstractVector{ET} data::T faces::F end -function (::Type{FaceIterator{Typ}})(data::T, faces::F) where {Typ, T, F} - FaceIterator{Typ, T, F}(data, faces) +function (::Type{FaceIterator{Typ}})(data::T, faces::F) where {Typ,T,F} + FaceIterator{Typ,T,F}(data, faces) end -function (::Type{FaceIterator{Typ, T, F}})(data::AbstractVector, faces::F) where {Typ, F, T} - FaceIterator{Typ, T, F, NTuple{3, eltype(data)}}(data, faces) +function (::Type{FaceIterator{Typ,T,F}})(data::AbstractVector, faces::F) where {Typ,F,T} + FaceIterator{Typ,T,F,NTuple{3,eltype(data)}}(data, faces) end -function (::Type{FaceIterator{Typ, T, F}})(data::T, faces::F) where {Typ, T, F} - FaceIterator{Typ, T, F, NTuple{3, T}}(data, faces) +function (::Type{FaceIterator{Typ,T,F}})(data::T, faces::F) where {Typ,T,F} + FaceIterator{Typ,T,F,NTuple{3,T}}(data, faces) end function FaceIterator(data::AbstractVector, faces) if length(data) == length(faces) @@ -186,22 +186,22 @@ end Base.size(fi::FaceIterator) = size(fi.faces) Base.getindex(fi::FaceIterator{:PerFace}, i::Integer) = fi.data[i] Base.getindex(fi::FaceIterator{:PerVert}, i::Integer) = fi.data[fi.faces[i]] -Base.getindex(fi::FaceIterator{:Const}, i::Integer) = ntuple(i-> fi.data, 3) +Base.getindex(fi::FaceIterator{:Const}, i::Integer) = ntuple(i -> fi.data, 3) color_or_nothing(c) = isnothing(c) ? nothing : to_color(c) -function get_color_attr(attributes, attribute)::Union{Nothing, RGBAf} +function get_color_attr(attributes, attribute)::Union{Nothing,RGBAf} return color_or_nothing(to_value(get(attributes, attribute, nothing))) end function per_face_colors( - color, colormap, colorrange, matcap, faces, normals, uv, - lowclip=nothing, highclip=nothing, nan_color=nothing - ) + color, colormap, colorrange, matcap, faces, normals, uv, + lowclip = nothing, highclip = nothing, nan_color = nothing +) if matcap !== nothing wsize = reverse(size(matcap)) wh = wsize .- 1 cvec = map(normals) do n - muv = 0.5n[Vec(1,2)] .+ Vec2f(0.5) + muv = 0.5n[Vec(1, 2)] .+ Vec2f(0.5) x, y = clamp.(round.(Int, Tuple(muv) .* wh) .+ 1, 1, wh) return matcap[end - (y - 1), x] end @@ -209,9 +209,9 @@ function per_face_colors( elseif color isa Colorant return FaceIterator{:Const}(color, faces) elseif color isa AbstractArray - if color isa AbstractVector{<: Colorant} + if color isa AbstractVector{<:Colorant} return FaceIterator(color, faces) - elseif color isa AbstractArray{<: Number} + elseif color isa AbstractArray{<:Number} low, high = extrema(colorrange) cvec = map(color[:]) do c if isnan(c) && nan_color !== nothing @@ -228,7 +228,7 @@ function per_face_colors( elseif color isa Makie.AbstractPattern # let next level extend and fill with CairoPattern return color - elseif color isa AbstractMatrix{<: Colorant} && uv !== nothing + elseif color isa AbstractMatrix{<:Colorant} && uv !== nothing wsize = reverse(size(color)) wh = wsize .- 1 cvec = map(uv) do uv @@ -250,7 +250,7 @@ end # not piracy function Cairo.CairoPattern(color::Makie.AbstractPattern) # the Cairo y-coordinate are fliped - bitmappattern = reverse!(ARGB32.(Makie.to_image(color)); dims=2) + bitmappattern = reverse!(ARGB32.(Makie.to_image(color)); dims = 2) cairoimage = Cairo.CairoImageSurface(bitmappattern) cairopattern = Cairo.CairoPattern(cairoimage) return cairopattern diff --git a/CairoMakie/test/rasterization_tests.jl b/CairoMakie/test/rasterization_tests.jl index 8554bfad939..70e22ddd99d 100644 --- a/CairoMakie/test/rasterization_tests.jl +++ b/CairoMakie/test/rasterization_tests.jl @@ -12,9 +12,9 @@ end @testset "Internal rasterization" begin fig = Figure() - ax = Axis(fig[1,1]) + ax = Axis(fig[1, 1]) lp = lines!(ax, vcat(1:10, 10:-1:1)) - pts = Makie.GeometryBasics.Point2f[(0,0), (1,0), (0,1)] + pts = Makie.GeometryBasics.Point2f[(0, 0), (1, 0), (0, 1)] pl = poly!(ax, Makie.GeometryBasics.Polygon(pts)) @testset "Unrasterized SVG" begin diff --git a/CairoMakie/test/runtests.jl b/CairoMakie/test/runtests.jl index cd46e5ba170..8b614e8ba2b 100644 --- a/CairoMakie/test/runtests.jl +++ b/CairoMakie/test/runtests.jl @@ -9,7 +9,7 @@ Pkg.develop(PackageSpec(path = path)) @testset "Runs without error" begin fig = Figure() scatter(fig[1, 1], rand(10)) - fn = tempname()*".png" + fn = tempname() * ".png" try save(fn, fig) finally @@ -39,11 +39,11 @@ include(joinpath(@__DIR__, "rasterization_tests.jl")) @testset "saving pdf two times" begin # https://github.com/MakieOrg/Makie.jl/issues/2433 - fig = Figure(resolution=(480, 792)) + fig = Figure(resolution = (480, 792)) ax = Axis(fig[1, 1]) # The IO was shared between screens, which left the second figure empty - save("fig.pdf", fig, pt_per_unit=0.5) - save("fig2.pdf", fig, pt_per_unit=0.5) + save("fig.pdf", fig, pt_per_unit = 0.5) + save("fig2.pdf", fig, pt_per_unit = 0.5) @test !isempty("fig.pdf") @test !isempty("fig2.pdf") rm("fig.pdf") @@ -54,14 +54,14 @@ include(joinpath(@__DIR__, "rasterization_tests.jl")) # https://github.com/MakieOrg/Makie.jl/issues/2438 # This bug was caused by using the screen size of the pdf screen, which # has a different device_scaling_factor, and therefore a different screen size - fig = scatter(1:4, figure=(; resolution=(800, 800))) + fig = scatter(1:4, figure = (; resolution = (800, 800))) save("test.pdf", fig) size(Makie.colorbuffer(fig)) == (800, 800) rm("test.pdf") end @testset "switching from pdf screen to png, save" begin - fig = scatter(1:4, figure=(; resolution=(800, 800))) + fig = scatter(1:4, figure = (; resolution = (800, 800))) save("test.pdf", fig) save("test.png", fig) @test size(load("test.png")) == (800, 800) @@ -72,32 +72,32 @@ include(joinpath(@__DIR__, "rasterization_tests.jl")) @testset "changing resolution of same format" begin # see: https://github.com/MakieOrg/Makie.jl/issues/2433 # and: https://github.com/MakieOrg/AlgebraOfGraphics.jl/pull/441 - scene = Scene(resolution=(800, 800)); + scene = Scene(resolution = (800, 800)) load_save(s; kw...) = (save("test.png", s; kw...); load("test.png")) - @test size(load_save(scene, px_per_unit=2)) == (1600, 1600) - @test size(load_save(scene, px_per_unit=1)) == (800, 800) + @test size(load_save(scene, px_per_unit = 2)) == (1600, 1600) + @test size(load_save(scene, px_per_unit = 1)) == (800, 800) rm("test.png") end end @testset "mimes" begin f, ax, pl = scatter(1:4) - CairoMakie.activate!(type="pdf") + CairoMakie.activate!(type = "pdf") @test showable("application/pdf", f) - CairoMakie.activate!(type="eps") + CairoMakie.activate!(type = "eps") @test showable("application/postscript", f) - CairoMakie.activate!(type="svg") + CairoMakie.activate!(type = "svg") @test showable("image/svg+xml", f) - CairoMakie.activate!(type="png") + CairoMakie.activate!(type = "png") @test showable("image/png", f) # see https://github.com/MakieOrg/Makie.jl/pull/2167 @test !showable("blaaa", f) - CairoMakie.activate!(type="png") + CairoMakie.activate!(type = "png") @test showable("image/png", Scene()) @test !showable("image/svg+xml", Scene()) # setting svg should leave png as showable, since it's usually lower in the display stack priority - CairoMakie.activate!(type="svg") + CairoMakie.activate!(type = "svg") @test showable("image/png", Scene()) @test showable("image/svg+xml", Scene()) end @@ -105,8 +105,8 @@ end @testset "VideoStream & screen options" begin N = 3 points = Observable(Point2f[]) - f, ax, pl = scatter(points, axis=(type=Axis, aspect=DataAspect(), limits=(0.4, N + 0.6, 0.4, N + 0.6),), figure=(resolution=(600, 800),)) - vio = Makie.VideoStream(f; format="mp4", px_per_unit=2.0, backend=CairoMakie) + f, ax, pl = scatter(points, axis = (type = Axis, aspect = DataAspect(), limits = (0.4, N + 0.6, 0.4, N + 0.6),), figure = (resolution = (600, 800),)) + vio = Makie.VideoStream(f; format = "mp4", px_per_unit = 2.0, backend = CairoMakie) @test vio.screen isa CairoMakie.Screen{CairoMakie.IMAGE} @test size(vio.screen) == size(f.scene) .* 2 @test vio.screen.device_scaling_factor == 2.0 @@ -174,7 +174,7 @@ functions = [:volume, :volume!, :uv_mesh] @testset "refimages" begin CairoMakie.activate!(type = "png") - ReferenceTests.mark_broken_tests(excludes, functions=functions) + ReferenceTests.mark_broken_tests(excludes, functions = functions) recorded_files, recording_dir = @include_reference_tests "refimages.jl" missing_images, scores = ReferenceTests.record_comparison(recording_dir) ReferenceTests.test_comparison(scores; threshold = 0.032) diff --git a/CairoMakie/test/svg_tests.jl b/CairoMakie/test/svg_tests.jl index 580d11dbc46..913c73cfa2e 100644 --- a/CairoMakie/test/svg_tests.jl +++ b/CairoMakie/test/svg_tests.jl @@ -12,7 +12,11 @@ end @testset "SVG rasterization" begin @test svg_isnt_rasterized(Scene()) - @test svg_isnt_rasterized(begin f = Figure(); Axis(f[1, 1]); f end) + @test svg_isnt_rasterized(begin + f = Figure() + Axis(f[1, 1]) + f + end) @test svg_isnt_rasterized(scatter(1:3)) @test svg_isnt_rasterized(lines(1:3)) @test svg_isnt_rasterized(heatmap(rand(5, 5))) diff --git a/GLMakie/experiments/cuda_interop.jl b/GLMakie/experiments/cuda_interop.jl index ca8d8443c1c..50c8bc9a6c7 100644 --- a/GLMakie/experiments/cuda_interop.jl +++ b/GLMakie/experiments/cuda_interop.jl @@ -1,11 +1,11 @@ using CUDA, GLMakie -scene = scatter(rand(Point2f, 10_000), show_axis=false) +scene = scatter(rand(Point2f, 10_000), show_axis = false) screen = display(scene) buffer = screen.renderlist[1][3][:position] resource = -cuGraphicsGLRegisterBuffer(&resource, pbo, cudaGraphicsRegisterFlagsReadOnly) + cuGraphicsGLRegisterBuffer(&resource, pbo, cudaGraphicsRegisterFlagsReadOnly) CUDA.cuGraphicsMapResources diff --git a/GLMakie/experiments/shaderabstr.jl b/GLMakie/experiments/shaderabstr.jl index 5dfe724fe48..71353b917fa 100644 --- a/GLMakie/experiments/shaderabstr.jl +++ b/GLMakie/experiments/shaderabstr.jl @@ -2,7 +2,7 @@ using ShaderAbstractions: Buffer, Sampler, VertexArray # Mesh mesh(Sphere(Point3f(0), 1f0)) |> display -mesh(Sphere(Point3f(0), 1f0), color=:red, ambient=Vec3f(0.9)) +mesh(Sphere(Point3f(0), 1f0), color = :red, ambient = Vec3f(0.9)) tocolor(x) = RGBf(x...) positions = Observable(decompose(Point3f, Sphere(Point3f(0), 1f0))) @@ -18,7 +18,7 @@ uv_buff = Buffer(uv) texture_buff = Sampler(texture) texsampler = Makie.sampler(:viridis, rand(length(positions))) -coords = VertexArray(pos_buff, triangles_buff, color=vert_color_buff) +coords = VertexArray(pos_buff, triangles_buff, color = vert_color_buff) mesh = GeometryBasics.Mesh(coords) GeometryBasics.coordinates(mesh); @@ -43,7 +43,7 @@ p = ShaderAbstractions.Program( println(p.vertex_source) -uniforms = Dict{Symbol, Any}( +uniforms = Dict{Symbol,Any}( :texturecoordinates => Vec2f(0), :image => nothing ) @@ -52,77 +52,89 @@ rshader = GLMakie.GLAbstraction.gl_convert(shader, uniforms) vbo = GLMakie.GLAbstraction.GLVertexArray(program, posmeta, triangles_buff) m = GeometryBasics.Mesh(posmeta, triangles_buff) -disp = display(Makie.mesh(m, show_axis=false)); +disp = display(Makie.mesh(m, show_axis = false)); mesh_normals = GeometryBasics.normals(positions, triangles) -coords = meta(positions, color=xyz_vertex_color, normals=mesh_normals) +coords = meta(positions, color = xyz_vertex_color, normals = mesh_normals) vertexcolor_mesh = GeometryBasics.Mesh(coords, triangles) -scren = mesh(vertexcolor_mesh, show_axis=false) |> display +scren = mesh(vertexcolor_mesh, show_axis = false) |> display function getter_function(io::IO, ::Fragment, sampler::Sampler, name::Symbol) index_t = type_string(context, sampler.values) sampler_t = type_string(context, sampler.colors) - println(io, """ - in $(value_t) fragment_$(name)_index; - uniform $(sampler_t) $(name)_texture; + println( + io, + """ +in $(value_t) fragment_$(name)_index; +uniform $(sampler_t) $(name)_texture; - vec4 get_$(name)(){ - return texture($(name)_texture, fragment_$(name)_index); - } - """) +vec4 get_$(name)(){ + return texture($(name)_texture, fragment_$(name)_index); +} +""" + ) end function getter_function(io::IO, ::Vertex, sampler::Sampler, name::Symbol) index_t = type_string(context, sampler.values) - println(io, """ - in $(index_t) $(name)_index; - out $(index_t) fragment_$(name)_index; - - vec4 get_$(name)(){ - fragment_uv = uv; - // color gets calculated in fragment! - return vec4(0); - } - """) + println( + io, + """ +in $(index_t) $(name)_index; +out $(index_t) fragment_$(name)_index; + +vec4 get_$(name)(){ + fragment_uv = uv; + // color gets calculated in fragment! + return vec4(0); +} +""" + ) end function getter_function(io::IO, ::Fragment, ::AbstractVector{T}, name) where T t_str = type_string(context, T) - println(io, """ - in $(t_str) fragment_$(name); - $(t_str) get_$(name)(){ - return fragment_$(name); - } - """) + println( + io, + """ +in $(t_str) fragment_$(name); +$(t_str) get_$(name)(){ + return fragment_$(name); +} +""" + ) end function getter_function(io::IO, ::Vertex, ::AbstractVector{T}, name) where T t_str = type_string(context, T) - println(io, """ - in $(t_str) $(name); - out $(t_str) fragment_$(name); - - $(t_str) get_$(name)(){ - fragment_$(name) = $(name); - return $(name); - } - """) + println( + io, + """ +in $(t_str) $(name); +out $(t_str) fragment_$(name); + +$(t_str) get_$(name)(){ + fragment_$(name) = $(name); + return $(name); +} +""" + ) end texsampler = Makie.sampler(rand(RGBf, 4, 4), uv) -coords = meta(positions, color=texsampler, normals=mesh_normals) +coords = meta(positions, color = texsampler, normals = mesh_normals) texture_mesh = GeometryBasics.Mesh(coords, triangles) -scren = mesh(texture_mesh, show_axis=false) |> display +scren = mesh(texture_mesh, show_axis = false) |> display texsampler = Makie.sampler(:viridis, rand(length(positions))) -coords = meta(positions, color=texsampler, normals=mesh_normals) +coords = meta(positions, color = texsampler, normals = mesh_normals) texture_mesh = GeometryBasics.Mesh(coords, triangles) -scren = mesh(texture_mesh, show_axis=false) |> display +scren = mesh(texture_mesh, show_axis = false) |> display diff --git a/GLMakie/src/GLAbstraction/AbstractGPUArray.jl b/GLMakie/src/GLAbstraction/AbstractGPUArray.jl index b016ec28854..0622c5defe7 100644 --- a/GLMakie/src/GLAbstraction/AbstractGPUArray.jl +++ b/GLMakie/src/GLAbstraction/AbstractGPUArray.jl @@ -9,12 +9,12 @@ import Base: map import Base: size import Base: iterate -abstract type GPUArray{T, NDim} <: AbstractArray{T, NDim} end +abstract type GPUArray{T,NDim} <: AbstractArray{T,NDim} end size(A::GPUArray) = A.size -function checkdimensions(value::Array, ranges::Union{Integer, UnitRange}...) - array_size = size(value) +function checkdimensions(value::Array, ranges::Union{Integer,UnitRange}...) + array_size = size(value) indexes_size = map(length, ranges) (array_size != indexes_size) && throw(DimensionMismatch("asigning a $array_size to a $(indexes_size) location")) return true @@ -27,24 +27,24 @@ function to_range(index) end end -setindex!(A::GPUArray{T, N}, value::Union{T, Array{T, N}}) where {T, N} = (A[1] = value) +setindex!(A::GPUArray{T,N}, value::Union{T,Array{T,N}}) where {T,N} = (A[1] = value) -function setindex!(A::GPUArray{T, N}, value, indices::Vararg{<: Integer, N}) where {T, N} - v = Array{T, N}(undef, ntuple(i-> 1, N)) +function setindex!(A::GPUArray{T,N}, value, indices::Vararg{<:Integer,N}) where {T,N} + v = Array{T,N}(undef, ntuple(i -> 1, N)) v[1] = convert(T, value) setindex!(A, v, (:).(indices, indices)...) end -function setindex!(A::GPUArray{T, N}, value, indexes...) where {T, N} +function setindex!(A::GPUArray{T,N}, value, indexes...) where {T,N} ranges = to_range(Base.to_indices(A, indexes)) v = isa(value, T) ? [value] : convert(Array{T,N}, value) setindex!(A, v, ranges...) end -setindex!(A::GPUArray{T, 2}, value::Vector{T}, i::Integer, range::UnitRange) where {T} = - (A[i, range] = reshape(value, (length(value),1))) +setindex!(A::GPUArray{T,2}, value::Vector{T}, i::Integer, range::UnitRange) where {T} = + (A[i, range] = reshape(value, (length(value), 1))) -function setindex!(A::GPUArray{T, N}, value::Array{T, N}, ranges::UnitRange...) where {T, N} +function setindex!(A::GPUArray{T,N}, value::Array{T,N}, ranges::UnitRange...) where {T,N} checkbounds(A, ranges...) checkdimensions(value, ranges...) gpu_setindex!(A, value, ranges...) @@ -52,10 +52,10 @@ function setindex!(A::GPUArray{T, N}, value::Array{T, N}, ranges::UnitRange...) end ShaderAbstractions.switch_context!(A::GPUArray) = switch_context!(A.context) -function update!(A::GPUArray{T, N}, value::AbstractArray{T2, N}) where {T, N, T2} - update!(A, convert(Array{T, N}, value)) +function update!(A::GPUArray{T,N}, value::AbstractArray{T2,N}) where {T,N,T2} + update!(A, convert(Array{T,N}, value)) end -function update!(A::GPUArray{T, N}, value::AbstractArray{T, N}) where {T, N} +function update!(A::GPUArray{T,N}, value::AbstractArray{T,N}) where {T,N} switch_context!(A) if length(A) != length(value) if isa(A, GLBuffer) @@ -68,22 +68,22 @@ function update!(A::GPUArray{T, N}, value::AbstractArray{T, N}) where {T, N} error("Dynamic resizing not implemented for $(typeof(A))") end end - dims = map(x-> 1:x, size(A)) + dims = map(x -> 1:x, size(A)) A[dims...] = value return end update!(A::GPUArray, value::ShaderAbstractions.Sampler) = update!(A, value.data) -function getindex(A::GPUArray{T, N}, i::Int) where {T, N} +function getindex(A::GPUArray{T,N}, i::Int) where {T,N} checkbounds(A, i) gpu_getindex(A, i:i)[1] # not as bad as its looks, as so far gpu data must be loaded into an array anyways end -function getindex(A::GPUArray{T, N}, ranges::UnitRange...) where {T, N} +function getindex(A::GPUArray{T,N}, ranges::UnitRange...) where {T,N} checkbounds(A, ranges...) gpu_getindex(A, ranges...) end -mutable struct GPUVector{T} <: GPUArray{T, 1} +mutable struct GPUVector{T} <: GPUArray{T,1} buffer size real_length @@ -95,7 +95,7 @@ function update!(A::GPUVector{T}, value::AbstractVector{T}) where T if isa(A, GLBuffer) && (length(A) != length(value)) resize!(A, length(value)) end - dims = map(x->1:x, size(A)) + dims = map(x -> 1:x, size(A)) A.buffer[dims...] = value return end @@ -109,26 +109,26 @@ setindex!(v::GPUVector{T}, value::T, index::Int) where {T} = v.buffer[index] = v setindex!(v::GPUVector{T}, value::T, index::UnitRange) where {T} = v.buffer[index] = value -function grow_dimensions(real_length::Int, _size::Int, additonal_size::Int, growfactor::Real=1.5) - new_dim = round(Int, real_length*growfactor) - return max(new_dim, additonal_size+_size) +function grow_dimensions(real_length::Int, _size::Int, additonal_size::Int, growfactor::Real = 1.5) + new_dim = round(Int, real_length * growfactor) + return max(new_dim, additonal_size + _size) end function Base.push!(v::GPUVector{T}, x::AbstractVector{T}) where T lv, lx = length(v), length(x) - if (v.real_length < lv+lx) + if (v.real_length < lv + lx) resize!(v.buffer, grow_dimensions(v.real_length, lv, lx)) end - v.buffer[lv+1:(lv+lx)] = x - v.real_length = length(v.buffer) - v.size = (lv+lx,) + v.buffer[(lv + 1):(lv + lx)] = x + v.real_length = length(v.buffer) + v.size = (lv + lx,) v end push!(v::GPUVector{T}, x::T) where {T} = push!(v, [x]) push!(v::GPUVector{T}, x::T...) where {T} = push!(v, [x...]) append!(v::GPUVector{T}, x::Vector{T}) where {T} = push!(v, x) -resize!(A::GPUArray{T, NDim}, dims::Int...) where {T, NDim} = resize!(A, dims) -function resize!(A::GPUArray{T, NDim}, newdims::NTuple{NDim, Int}) where {T, NDim} +resize!(A::GPUArray{T,NDim}, dims::Int...) where {T,NDim} = resize!(A, dims) +function resize!(A::GPUArray{T,NDim}, newdims::NTuple{NDim,Int}) where {T,NDim} newdims == size(A) && return A gpu_resize!(A, newdims) A @@ -139,61 +139,61 @@ function resize!(v::GPUVector, newlength::Int) v.size = (max(0, newlength),) return v end - resize!(v.buffer, grow_dimensions(v.real_length, length(v), newlength-length(v))) - v.size = (newlength,) + resize!(v.buffer, grow_dimensions(v.real_length, length(v), newlength - length(v))) + v.size = (newlength,) v.real_length = length(v.buffer) end function grow_at(v::GPUVector, index::Int, amount::Int) - resize!(v, length(v)+amount) - copy!(v, index, v, index+amount, amount) + resize!(v, length(v) + amount) + copy!(v, index, v, index + amount, amount) end -function splice!(v::GPUVector{T}, index::UnitRange, x::Vector=T[]) where T +function splice!(v::GPUVector{T}, index::UnitRange, x::Vector = T[]) where T lenv = length(v) - elements_to_grow = length(x)-length(index) # -1 - buffer = similar(v.buffer, length(v)+elements_to_grow) - copy!(v.buffer, 1, buffer, 1, first(index)-1) # copy first half - copy!(v.buffer, last(index)+1, buffer, first(index)+length(x), lenv-last(index)) # shift second half - v.buffer = buffer + elements_to_grow = length(x) - length(index) # -1 + buffer = similar(v.buffer, length(v) + elements_to_grow) + copy!(v.buffer, 1, buffer, 1, first(index) - 1) # copy first half + copy!(v.buffer, last(index) + 1, buffer, first(index) + length(x), lenv - last(index)) # shift second half + v.buffer = buffer v.real_length = length(buffer) - v.size = (v.real_length,) + v.size = (v.real_length,) copy!(x, 1, buffer, first(index), length(x)) # copy contents of insertion vector return end splice!(v::GPUVector{T}, index::Int, x::T) where {T} = v[index] = x -splice!(v::GPUVector{T}, index::Int, x::Vector=T[]) where {T} = splice!(v, index:index, map(T, x)) +splice!(v::GPUVector{T}, index::Int, x::Vector = T[]) where {T} = splice!(v, index:index, map(T, x)) -copy!(a::GPUVector, a_offset::Int, b::Vector, b_offset::Int, amount::Int) = copy!(a.buffer, a_offset, b, b_offset, amount) -copy!(a::GPUVector, a_offset::Int, b::GPUVector, b_offset::Int, amount::Int)= copy!(a.buffer, a_offset, b.buffer, b_offset, amount) +copy!(a::GPUVector, a_offset::Int, b::Vector, b_offset::Int, amount::Int) = copy!(a.buffer, a_offset, b, b_offset, amount) +copy!(a::GPUVector, a_offset::Int, b::GPUVector, b_offset::Int, amount::Int) = copy!(a.buffer, a_offset, b.buffer, b_offset, amount) -copy!(a::GPUArray, a_offset::Int, b::Vector, b_offset::Int, amount::Int) = _copy!(a, a_offset, b, b_offset, amount) -copy!(a::Vector, a_offset::Int, b::GPUArray, b_offset::Int, amount::Int) = _copy!(a, a_offset, b, b_offset, amount) +copy!(a::GPUArray, a_offset::Int, b::Vector, b_offset::Int, amount::Int) = _copy!(a, a_offset, b, b_offset, amount) +copy!(a::Vector, a_offset::Int, b::GPUArray, b_offset::Int, amount::Int) = _copy!(a, a_offset, b, b_offset, amount) copy!(a::GPUArray, a_offset::Int, b::GPUArray, b_offset::Int, amount::Int) = _copy!(a, a_offset, b, b_offset, amount) #don't overwrite Base.copy! with a::Vector, b::Vector -function _copy!(a::Union{Vector, GPUArray}, a_offset::Int, b::Union{Vector, GPUArray}, b_offset::Int, amount::Int) +function _copy!(a::Union{Vector,GPUArray}, a_offset::Int, b::Union{Vector,GPUArray}, b_offset::Int, amount::Int) (amount <= 0) && return nothing - @assert a_offset > 0 && (a_offset-1) + amount <= length(a) "a_offset $a_offset, amount $amount, lengtha $(length(a))" - @assert b_offset > 0 && (b_offset-1) + amount <= length(b) "b_offset $b_offset, amount $amount, lengthb $(length(b))" + @assert a_offset > 0 && (a_offset - 1) + amount <= length(a) "a_offset $a_offset, amount $amount, lengtha $(length(a))" + @assert b_offset > 0 && (b_offset - 1) + amount <= length(b) "b_offset $b_offset, amount $amount, lengthb $(length(b))" unsafe_copy!(a, a_offset, b, b_offset, amount) return nothing end # Interface: -gpu_data(t) = error("gpu_data not implemented for: $(typeof(t)). This happens, when you call data on an array, without implementing the GPUArray interface") -gpu_resize!(t) = error("gpu_resize! not implemented for: $(typeof(t)). This happens, when you call resize! on an array, without implementing the GPUArray interface") -gpu_getindex(t) = error("gpu_getindex not implemented for: $(typeof(t)). This happens, when you call getindex on an array, without implementing the GPUArray interface") +gpu_data(t) = error("gpu_data not implemented for: $(typeof(t)). This happens, when you call data on an array, without implementing the GPUArray interface") +gpu_resize!(t) = error("gpu_resize! not implemented for: $(typeof(t)). This happens, when you call resize! on an array, without implementing the GPUArray interface") +gpu_getindex(t) = error("gpu_getindex not implemented for: $(typeof(t)). This happens, when you call getindex on an array, without implementing the GPUArray interface") gpu_setindex!(t) = error("gpu_setindex! not implemented for: $(typeof(t)). This happens, when you call setindex! on an array, without implementing the GPUArray interface") -max_dim(t) = error("max_dim not implemented for: $(typeof(t)). This happens, when you call setindex! on an array, without implementing the GPUArray interface") +max_dim(t) = error("max_dim not implemented for: $(typeof(t)). This happens, when you call setindex! on an array, without implementing the GPUArray interface") -function (::Type{GPUArrayType})(data::Observable; kw...) where GPUArrayType <: GPUArray +function (::Type{GPUArrayType})(data::Observable; kw...) where GPUArrayType<:GPUArray gpu_mem = GPUArrayType(data[]; kw...) # TODO merge these and handle update tracking during contruction - obs1 = on(_-> gpu_mem.requires_update[] = true, data) + obs1 = on(_ -> gpu_mem.requires_update[] = true, data) obs2 = on(new_data -> update!(gpu_mem, new_data), data) if GPUArrayType <: TextureBuffer push!(gpu_mem.buffer.observers, obs1, obs2) diff --git a/GLMakie/src/GLAbstraction/GLBuffer.jl b/GLMakie/src/GLAbstraction/GLBuffer.jl index cc071d589bc..8bd5148f753 100644 --- a/GLMakie/src/GLAbstraction/GLBuffer.jl +++ b/GLMakie/src/GLAbstraction/GLBuffer.jl @@ -1,6 +1,6 @@ -mutable struct GLBuffer{T} <: GPUArray{T, 1} +mutable struct GLBuffer{T} <: GPUArray{T,1} id::GLuint - size::NTuple{1, Int} + size::NTuple{1,Int} buffertype::GLenum usage::GLenum context::GLContext @@ -43,28 +43,28 @@ cardinality(::GLBuffer{T}) where {T} = cardinality(T) #Function to deal with any Immutable type with Real as Subtype function GLBuffer( - buffer::Union{Base.ReinterpretArray{T, 1}, DenseVector{T}}; - buffertype::GLenum = GL_ARRAY_BUFFER, usage::GLenum = GL_STATIC_DRAW - ) where T <: GLArrayEltypes + buffer::Union{Base.ReinterpretArray{T,1},DenseVector{T}}; + buffertype::GLenum = GL_ARRAY_BUFFER, usage::GLenum = GL_STATIC_DRAW +) where T<:GLArrayEltypes GC.@preserve buffer begin return GLBuffer{T}(pointer(buffer), length(buffer), buffertype, usage) end end function GLBuffer( - buffer::DenseVector{T}; - buffertype::GLenum = GL_ARRAY_BUFFER, usage::GLenum = GL_STATIC_DRAW - ) where T <: GLArrayEltypes + buffer::DenseVector{T}; + buffertype::GLenum = GL_ARRAY_BUFFER, usage::GLenum = GL_STATIC_DRAW +) where T<:GLArrayEltypes GC.@preserve buffer begin return GLBuffer{T}(pointer(buffer), length(buffer), buffertype, usage) end end function GLBuffer( - buffer::ShaderAbstractions.Buffer{T}; - buffertype::GLenum = GL_ARRAY_BUFFER, usage::GLenum = GL_STATIC_DRAW - ) where T <: GLArrayEltypes - b = GLBuffer(ShaderAbstractions.data(buffer); buffertype=buffertype, usage=usage) + buffer::ShaderAbstractions.Buffer{T}; + buffertype::GLenum = GL_ARRAY_BUFFER, usage::GLenum = GL_STATIC_DRAW +) where T<:GLArrayEltypes + b = GLBuffer(ShaderAbstractions.data(buffer); buffertype = buffertype, usage = usage) obsfunc = ShaderAbstractions.connect!(buffer, b) push!(b.observers, obsfunc) return b @@ -75,32 +75,32 @@ GLBuffer(buffer::GLBuffer) = buffer GLBuffer{T}(buffer::GLBuffer{T}) where {T} = buffer function GLBuffer( - buffer::AbstractVector{T}; - kw_args... - ) where T <: GLArrayEltypes + buffer::AbstractVector{T}; + kw_args... +) where T<:GLArrayEltypes GLBuffer(collect(buffer); kw_args...) end function GLBuffer{T}( - buffer::AbstractVector; - kw_args... - ) where T <: GLArrayEltypes + buffer::AbstractVector; + kw_args... +) where T<:GLArrayEltypes GLBuffer(convert(Vector{T}, buffer); kw_args...) end function GLBuffer( - ::Type{T}, len::Int; - buffertype::GLenum = GL_ARRAY_BUFFER, usage::GLenum = GL_STATIC_DRAW - ) where T <: GLArrayEltypes + ::Type{T}, len::Int; + buffertype::GLenum = GL_ARRAY_BUFFER, usage::GLenum = GL_STATIC_DRAW +) where T<:GLArrayEltypes GLBuffer{T}(Ptr{T}(C_NULL), len, buffertype, usage) end function indexbuffer( - buffer::VectorTypes{T}; - usage::GLenum = GL_STATIC_DRAW - ) where T <: GLArrayEltypes - GLBuffer(buffer, buffertype = GL_ELEMENT_ARRAY_BUFFER, usage=usage) + buffer::VectorTypes{T}; + usage::GLenum = GL_STATIC_DRAW +) where T<:GLArrayEltypes + GLBuffer(buffer, buffertype = GL_ELEMENT_ARRAY_BUFFER, usage = usage) end # GPUArray interface function gpu_data(b::GLBuffer{T}) where T @@ -113,18 +113,18 @@ end # Resize buffer -function gpu_resize!(buffer::GLBuffer{T}, newdims::NTuple{1, Int}) where T +function gpu_resize!(buffer::GLBuffer{T}, newdims::NTuple{1,Int}) where T #TODO make this safe! newlength = newdims[1] - oldlen = length(buffer) + oldlen = length(buffer) if oldlen > 0 old_data = gpu_data(buffer) end bind(buffer) - glBufferData(buffer.buffertype, newlength*sizeof(T), C_NULL, buffer.usage) + glBufferData(buffer.buffertype, newlength * sizeof(T), C_NULL, buffer.usage) bind(buffer, 0) buffer.size = newdims - if oldlen>0 + if oldlen > 0 max_len = min(length(old_data), newlength) #might also shrink buffer[1:max_len] = old_data[1:max_len] end @@ -139,14 +139,14 @@ end function gpu_setindex!(b::GLBuffer{T}, value::Vector{T}, offset::Integer) where T multiplicator = sizeof(T) bind(b) - glBufferSubData(b.buffertype, multiplicator*(offset-1), sizeof(value), value) + glBufferSubData(b.buffertype, multiplicator * (offset - 1), sizeof(value), value) bind(b, 0) end function gpu_setindex!(b::GLBuffer{T}, value::Vector{T}, offset::UnitRange{Int}) where T multiplicator = sizeof(T) bind(b) - glBufferSubData(b.buffertype, multiplicator*(first(offset)-1), sizeof(value), value) + glBufferSubData(b.buffertype, multiplicator * (first(offset) - 1), sizeof(value), value) bind(b, 0) return nothing end @@ -160,18 +160,18 @@ function unsafe_copy!(a::GLBuffer{T}, readoffset::Int, b::GLBuffer{T}, writeoffs glBindBuffer(GL_COPY_WRITE_BUFFER, b.id) glCopyBufferSubData( GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, - multiplicator*(readoffset-1), - multiplicator*(writeoffset-1), - multiplicator*len + multiplicator * (readoffset - 1), + multiplicator * (writeoffset - 1), + multiplicator * len ) glBindBuffer(GL_COPY_READ_BUFFER, 0) glBindBuffer(GL_COPY_WRITE_BUFFER, 0) return nothing end -function Base.iterate(buffer::GLBuffer{T}, i=1) where T +function Base.iterate(buffer::GLBuffer{T}, i = 1) where T i > length(buffer) && return nothing - return gpu_getindex(buffer, i:i)[], i+1 + return gpu_getindex(buffer, i:i)[], i + 1 end #copy inside one buffer @@ -179,40 +179,40 @@ function unsafe_copy!(buffer::GLBuffer{T}, readoffset::Int, writeoffset::Int, le len <= 0 && return nothing bind(buffer) ptr = Ptr{T}(glMapBuffer(buffer.buffertype, GL_READ_WRITE)) - for i=1:len+1 - unsafe_store!(ptr, unsafe_load(ptr, i+readoffset-1), i+writeoffset-1) + for i in 1:(len + 1) + unsafe_store!(ptr, unsafe_load(ptr, i + readoffset - 1), i + writeoffset - 1) end glUnmapBuffer(buffer.buffertype) - bind(buffer,0) + bind(buffer, 0) return nothing end function unsafe_copy!(a::Vector{T}, readoffset::Int, b::GLBuffer{T}, writeoffset::Int, len::Int) where T bind(b) ptr = Ptr{T}(glMapBuffer(b.buffertype, GL_WRITE_ONLY)) - for i=1:len - unsafe_store!(ptr, a[i+readoffset-1], i+writeoffset-1) + for i in 1:len + unsafe_store!(ptr, a[i + readoffset - 1], i + writeoffset - 1) end glUnmapBuffer(b.buffertype) - bind(b,0) + bind(b, 0) end function unsafe_copy!(a::GLBuffer{T}, readoffset::Int, b::Vector{T}, writeoffset::Int, len::Int) where T bind(a) ptr = Ptr{T}(glMapBuffer(a.buffertype, GL_READ_ONLY)) for i in 1:len - b[i+writeoffset-1] = unsafe_load(ptr, i+readoffset-2) #-2 => -1 to zero offset, -1 gl indexing starts at 0 + b[i + writeoffset - 1] = unsafe_load(ptr, i + readoffset - 2) #-2 => -1 to zero offset, -1 gl indexing starts at 0 end glUnmapBuffer(a.buffertype) - bind(a,0) + bind(a, 0) end function gpu_getindex(b::GLBuffer{T}, range::UnitRange) where T multiplicator = sizeof(T) - offset = first(range)-1 + offset = first(range) - 1 value = Vector{T}(undef, length(range)) bind(b) - glGetBufferSubData(b.buffertype, multiplicator*offset, sizeof(value), value) + glGetBufferSubData(b.buffertype, multiplicator * offset, sizeof(value), value) bind(b, 0) return value end diff --git a/GLMakie/src/GLAbstraction/GLExtendedFunctions.jl b/GLMakie/src/GLAbstraction/GLExtendedFunctions.jl index 95235c2a67f..149099d4f9b 100644 --- a/GLMakie/src/GLAbstraction/GLExtendedFunctions.jl +++ b/GLMakie/src/GLAbstraction/GLExtendedFunctions.jl @@ -10,14 +10,14 @@ function glGetShaderiv(shaderID::GLuint, variable::GLenum) end function glShaderSource(shaderID::GLuint, shadercode::Vector{UInt8}) shader_code_ptrs = Ptr{UInt8}[pointer(shadercode)] - len = Ref{GLint}(length(shadercode)) + len = Ref{GLint}(length(shadercode)) glShaderSource(shaderID, 1, shader_code_ptrs, len) end glShaderSource(shaderID::GLuint, shadercode::String) = glShaderSource(shaderID, Vector{UInt8}(shadercode)) function glGetAttachedShaders(program::GLuint) - shader_count = glGetProgramiv(program, GL_ATTACHED_SHADERS) + shader_count = glGetProgramiv(program, GL_ATTACHED_SHADERS) length_written = GLsizei[0] - shaders = zeros(GLuint, shader_count) + shaders = zeros(GLuint, shader_count) glGetAttachedShaders(program, shader_count, length_written, shaders) shaders[1:first(length_written)] @@ -61,15 +61,15 @@ function get_uniform_location(program::GLuint, name::String) end function glGetActiveUniform(programID::GLuint, index::Integer) - actualLength = GLsizei[1] - uniformSize = GLint[1] - typ = GLenum[1] - maxcharsize = glGetProgramiv(programID, GL_ACTIVE_UNIFORM_MAX_LENGTH) - name = Vector{GLchar}(undef, maxcharsize) + actualLength = GLsizei[1] + uniformSize = GLint[1] + typ = GLenum[1] + maxcharsize = glGetProgramiv(programID, GL_ACTIVE_UNIFORM_MAX_LENGTH) + name = Vector{GLchar}(undef, maxcharsize) glGetActiveUniform(programID, index, maxcharsize, actualLength, uniformSize, typ, name) - actualLength[1] <= 0 && error("No active uniform at given index. Index: ", index) + actualLength[1] <= 0 && error("No active uniform at given index. Index: ", index) uname = unsafe_string(pointer(name), actualLength[1]) uname = Symbol(replace(uname, r"\[\d*\]" => "")) # replace array brackets. This is not really a good solution. @@ -77,11 +77,11 @@ function glGetActiveUniform(programID::GLuint, index::Integer) end function glGetActiveAttrib(programID::GLuint, index::Integer) - actualLength = GLsizei[1] - attributeSize = GLint[1] - typ = GLenum[1] - maxcharsize = glGetProgramiv(programID, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH) - name = Vector{GLchar}(undef, maxcharsize) + actualLength = GLsizei[1] + attributeSize = GLint[1] + typ = GLenum[1] + maxcharsize = glGetProgramiv(programID, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH) + name = Vector{GLchar}(undef, maxcharsize) glGetActiveAttrib(programID, index, maxcharsize, actualLength, attributeSize, typ, name) @@ -104,7 +104,7 @@ function glGetIntegerv(variable::GLenum) return result[] end -function glGenBuffers(n=1) +function glGenBuffers(n = 1) result = GLuint[0] glGenBuffers(1, result) id = result[] @@ -118,7 +118,7 @@ function glGenVertexArrays() result = GLuint[0] glGenVertexArrays(1, result) id = result[1] - if id <=0 + if id <= 0 error("glGenVertexArrays returned invalid id. OpenGL Context active?") end return id @@ -179,12 +179,12 @@ end function glTexImage(ttype::GLenum, level::Integer, internalFormat::GLenum, w::Integer, h::Integer, d::Integer, border::Integer, format::GLenum, datatype::GLenum, data) glTexImage3D(GL_PROXY_TEXTURE_3D, level, internalFormat, w, h, d, border, format, datatype, C_NULL) - for l in 0:level + for l in 0:level result = glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, l, GL_TEXTURE_WIDTH) if result == 0 error("glTexImage 3D: width too large. Width: ", w) end - result = glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, l,GL_TEXTURE_HEIGHT) + result = glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, l, GL_TEXTURE_HEIGHT) if result == 0 error("glTexImage 3D: height too large. height: ", h) end diff --git a/GLMakie/src/GLAbstraction/GLInfo.jl b/GLMakie/src/GLAbstraction/GLInfo.jl index c72c677807f..b793903090d 100644 --- a/GLMakie/src/GLAbstraction/GLInfo.jl +++ b/GLMakie/src/GLAbstraction/GLInfo.jl @@ -1,8 +1,8 @@ getnames(check_function::Function) = filter(check_function, uint32(0:65534)) # gets all the names currently boundo to programs -getProgramNames() = getnames(glIsProgram) -getShaderNames() = getnames(glIsShader) +getProgramNames() = getnames(glIsProgram) +getShaderNames() = getnames(glIsShader) getVertexArrayNames() = getnames(glIsVertexArray) # display info for all active uniforms in a program @@ -16,9 +16,9 @@ function getUniformsInfo(p::GLProgram) size = Ref{GLint}(0) type = Ref{GLenum}() - for i=0:activeUnif-1 + for i in 0:(activeUnif - 1) glGetActiveUniform(program, i, bufSize, buflen, size, type, name) - println(String(name), " ", buflen[], " ", size[], " ", GLENUM(type[]).name) + println(String(name), " ", buflen[], " ", size[], " ", GLENUM(type[]).name) end end @@ -29,7 +29,7 @@ function uniform_name_type(p::GLProgram, location) size = Ref{GLint}(0) type = Ref{GLenum}() glGetActiveUniform(p.id, location, bufSize, buflen, size, type, name) - println(String(name), " ", buflen[], " ", size[], " ", GLENUM(type[]).name) + println(String(name), " ", buflen[], " ", size[], " ", GLENUM(type[]).name) end # display the values for uniforms in the default block @@ -68,8 +68,8 @@ function getAttributesInfo(p::GLProgram) # how many attribs? @show activeAttr = glGetProgramiv(program, GL_ACTIVE_ATTRIBUTES) # get location and type for each attrib - for i=0:activeAttr-1 - @show name, typ, siz = glGetActiveAttrib(program, i) + for i in 0:(activeAttr - 1) + @show name, typ, siz = glGetActiveAttrib(program, i) @show loc = glGetAttribLocation(program, name) end end diff --git a/GLMakie/src/GLAbstraction/GLRender.jl b/GLMakie/src/GLAbstraction/GLRender.jl index 72581554e46..dd8ca6458fd 100644 --- a/GLMakie/src/GLAbstraction/GLRender.jl +++ b/GLMakie/src/GLAbstraction/GLRender.jl @@ -54,9 +54,9 @@ It uses dictionaries and doesn't care about OpenGL call optimizations. So rewriting this function could get us a lot of performance for scenes with a lot of objects. """ -function render(renderobject::RenderObject, vertexarray=renderobject.vertexarray) +function render(renderobject::RenderObject, vertexarray = renderobject.vertexarray) renderobject.requires_update = false - + if renderobject.visible renderobject.prerenderfunction() program = vertexarray.program @@ -73,7 +73,7 @@ function render(renderobject::RenderObject, vertexarray=renderobject.vertexarray error("Uniform tuple too long: $(length(value))") end catch e - @warn error("uniform $key doesn't work with value $(renderobject.uniforms[key])") exception=(e, Base.catch_backtrace()) + @warn error("uniform $key doesn't work with value $(renderobject.uniforms[key])") exception = (e, Base.catch_backtrace()) end end end @@ -89,14 +89,14 @@ end Renders a vertexarray, which consists of the usual buffers plus a vector of unitranges which defines the segments of the buffers to be rendered """ -function render(vao::GLVertexArray{T}, mode::GLenum=GL_TRIANGLES) where T <: VecOrSignal{UnitRange{Int}} +function render(vao::GLVertexArray{T}, mode::GLenum = GL_TRIANGLES) where T<:VecOrSignal{UnitRange{Int}} for elem in to_value(vao.indices) glDrawArrays(mode, max(first(elem) - 1, 0), length(elem) + 1) end return nothing end -function render(vao::GLVertexArray{T}, mode::GLenum=GL_TRIANGLES) where T <: TOrSignal{UnitRange{Int}} +function render(vao::GLVertexArray{T}, mode::GLenum = GL_TRIANGLES) where T<:TOrSignal{UnitRange{Int}} r = to_value(vao.indices) offset = first(r) - 1 # 1 based -> 0 based ndraw = length(r) @@ -108,7 +108,7 @@ function render(vao::GLVertexArray{T}, mode::GLenum=GL_TRIANGLES) where T <: TOr return nothing end -function render(vao::GLVertexArray{T}, mode::GLenum=GL_TRIANGLES) where T <: TOrSignal{Int} +function render(vao::GLVertexArray{T}, mode::GLenum = GL_TRIANGLES) where T<:TOrSignal{Int} r = to_value(vao.indices) glDrawArrays(mode, 0, r) return nothing @@ -117,7 +117,7 @@ end """ Renders a vertex array which supplies an indexbuffer """ -function render(vao::GLVertexArray{GLBuffer{T}}, mode::GLenum=GL_TRIANGLES) where T <: Union{Integer,AbstractFace} +function render(vao::GLVertexArray{GLBuffer{T}}, mode::GLenum = GL_TRIANGLES) where T<:Union{Integer,AbstractFace} glDrawElements( mode, length(vao.indices) * cardinality(vao.indices), @@ -129,7 +129,7 @@ end """ Renders a normal vertex array only containing the usual buffers buffers. """ -function render(vao::GLVertexArray, mode::GLenum=GL_TRIANGLES) +function render(vao::GLVertexArray, mode::GLenum = GL_TRIANGLES) glDrawArrays(mode, 0, length(vao)) return end @@ -137,12 +137,12 @@ end """ Render instanced geometry """ -renderinstanced(vao::GLVertexArray, a, primitive=GL_TRIANGLES) = renderinstanced(vao, length(a), primitive) +renderinstanced(vao::GLVertexArray, a, primitive = GL_TRIANGLES) = renderinstanced(vao, length(a), primitive) """ Renders `amount` instances of an indexed geometry """ -function renderinstanced(vao::GLVertexArray{GLBuffer{T}}, amount::Integer, primitive=GL_TRIANGLES) where T <: Union{Integer,AbstractFace} +function renderinstanced(vao::GLVertexArray{GLBuffer{T}}, amount::Integer, primitive = GL_TRIANGLES) where T<:Union{Integer,AbstractFace} glDrawElementsInstanced(primitive, length(vao.indices) * cardinality(vao.indices), julia2glenum(T), C_NULL, amount) return end @@ -150,7 +150,7 @@ end """ Renders `amount` instances of an not indexed geoemtry geometry """ -function renderinstanced(vao::GLVertexArray, amount::Integer, primitive=GL_TRIANGLES) +function renderinstanced(vao::GLVertexArray, amount::Integer, primitive = GL_TRIANGLES) glDrawElementsInstanced(primitive, length(vao), GL_UNSIGNED_INT, C_NULL, amount) return end diff --git a/GLMakie/src/GLAbstraction/GLRenderObject.jl b/GLMakie/src/GLAbstraction/GLRenderObject.jl index fe644f5c586..f5e203f0c45 100644 --- a/GLMakie/src/GLAbstraction/GLRenderObject.jl +++ b/GLMakie/src/GLAbstraction/GLRenderObject.jl @@ -9,8 +9,8 @@ Base.getindex(obj::RenderObject, symbol::Symbol, x::Function) = getindex(obj, Va Base.getindex(obj::RenderObject, ::Val{:prerender}, x::Function) = obj.prerenderfunctions[x] Base.getindex(obj::RenderObject, ::Val{:postrender}, x::Function) = obj.postrenderfunctions[x] -Base.setindex!(obj::RenderObject, value, symbol::Symbol, x::Function) = setindex!(obj, value, Val(symbol), x) -Base.setindex!(obj::RenderObject, value, ::Val{:prerender}, x::Function) = obj.prerenderfunctions[x] = value +Base.setindex!(obj::RenderObject, value, symbol::Symbol, x::Function) = setindex!(obj, value, Val(symbol), x) +Base.setindex!(obj::RenderObject, value, ::Val{:prerender}, x::Function) = obj.prerenderfunctions[x] = value Base.setindex!(obj::RenderObject, value, ::Val{:postrender}, x::Function) = obj.postrenderfunctions[x] = value """ diff --git a/GLMakie/src/GLAbstraction/GLShader.jl b/GLMakie/src/GLAbstraction/GLShader.jl index edbc7efff8c..66fa31895fa 100644 --- a/GLMakie/src/GLAbstraction/GLShader.jl +++ b/GLMakie/src/GLAbstraction/GLShader.jl @@ -22,9 +22,9 @@ end function getinfolog(obj::GLuint) # Return the info log for obj, whether it be a shader or a program. - isShader = glIsShader(obj) - getiv = isShader == GL_TRUE ? glGetShaderiv : glGetProgramiv - get_log = isShader == GL_TRUE ? glGetShaderInfoLog : glGetProgramInfoLog + isShader = glIsShader(obj) + getiv = isShader == GL_TRUE ? glGetShaderiv : glGetProgramiv + get_log = isShader == GL_TRUE ? glGetShaderInfoLog : glGetProgramInfoLog # Get the maximum possible length for the descriptive error message maxlength = GLint[0] @@ -69,8 +69,8 @@ function shadertype(ext::AbstractString) error("$ext not a valid shader extension") end -function uniformlocations(nametypedict::Dict{Symbol, GLenum}, program) - result = Dict{Symbol, Tuple}() +function uniformlocations(nametypedict::Dict{Symbol,GLenum}, program) + result = Dict{Symbol,Tuple}() texturetarget = -1 # start -1, as texture samplers start at 0 for (name, typ) in nametypedict loc = get_uniform_location(program, name) @@ -88,18 +88,18 @@ struct ShaderCache # path --> template keys # cache for template keys per file context::Any - template_cache::Dict{String, Vector{String}} + template_cache::Dict{String,Vector{String}} # path --> Dict{template_replacements --> Shader) - shader_cache::Dict{String, Dict{Any, Shader}} - program_cache::Dict{Any, GLProgram} + shader_cache::Dict{String,Dict{Any,Shader}} + program_cache::Dict{Any,GLProgram} end function ShaderCache(context) ShaderCache( context, - Dict{String, Vector{String}}(), - Dict{String, Dict{Any, Shader}}(), - Dict{Any, GLProgram}() + Dict{String,Vector{String}}(), + Dict{String,Dict{Any,Shader}}(), + Dict{Any,GLProgram}() ) end @@ -108,10 +108,10 @@ abstract type AbstractLazyShader end struct LazyShader <: AbstractLazyShader shader_cache::ShaderCache paths::Tuple - kw_args::Dict{Symbol, Any} + kw_args::Dict{Symbol,Any} function LazyShader(cache::ShaderCache, paths...; kw_args...) - args = Dict{Symbol, Any}(kw_args) - get!(args, :view, Dict{String, String}()) + args = Dict{Symbol,Any}(kw_args) + get!(args, :view, Dict{String,String}()) new(cache, paths, args) end end @@ -187,7 +187,7 @@ function compile_program(shaders, fragdatalocation) if !GLAbstraction.islinked(program) error( "program $program not linked. Error in: \n", - join(map(x-> string(x.name), shaders), " or "), "\n", getinfolog(program) + join(map(x -> string(x.name), shaders), " or "), "\n", getinfolog(program) ) end # Can be deleted, as they will still be linked to Program and released after program gets released @@ -201,7 +201,7 @@ end function get_view(kw_dict) _view = kw_dict[:view] extension = Sys.isapple() ? "" : "#extension GL_ARB_draw_instanced : enable\n" - _view["GLSL_EXTENSION"] = extension*get(_view, "GLSL_EXTENSIONS", "") + _view["GLSL_EXTENSION"] = extension * get(_view, "GLSL_EXTENSIONS", "") _view["GLSL_VERSION"] = glsl_version_string() _view end @@ -213,20 +213,20 @@ end function gl_convert(cache::ShaderCache, lazyshader::AbstractLazyShader, data) kw_dict = lazyshader.kw_args paths = lazyshader.paths - if all(x-> isa(x, Shader), paths) - fragdatalocation = get(kw_dict, :fragdatalocation, Tuple{Int, String}[]) + if all(x -> isa(x, Shader), paths) + fragdatalocation = get(kw_dict, :fragdatalocation, Tuple{Int,String}[]) ShaderAbstractions.switch_context!(cache.context) return compile_program([paths...], fragdatalocation) end v = get_view(kw_dict) - fragdatalocation = get(kw_dict, :fragdatalocation, Tuple{Int, String}[]) + fragdatalocation = get(kw_dict, :fragdatalocation, Tuple{Int,String}[]) # Tuple(Source, ShaderType) if all(paths) do x - isa(x, Tuple) && length(x) == 2 && + isa(x, Tuple) && length(x) == 2 && isa(first(x), AbstractString) && isa(last(x), GLenum) - end + end # we don't cache view & templates for shader strings! shaders = map(paths) do source_typ source, typ = source_typ @@ -278,7 +278,7 @@ Replaces {{keyword}} with the key in `replace_view`, or replace_view(key) in a string """ -function mustache_replace(replace_view::Union{Dict, Function}, string) +function mustache_replace(replace_view::Union{Dict,Function}, string) io = IOBuffer() replace_started = false open_mustaches = 0 @@ -296,7 +296,7 @@ function mustache_replace(replace_view::Union{Dict, Function}, string) if char == '}' closed_mustaches += 1 if closed_mustaches == 2 # we found a complete mustache! - insert_from_view(io, replace_view, SubString(string, replace_begin+1, i-2)) + insert_from_view(io, replace_view, SubString(string, replace_begin + 1, i - 2)) open_mustaches = 0 closed_mustaches = 0 replace_started = false @@ -335,7 +335,8 @@ function mustache2replacement(mustache_key, view, attributes) if !isa(val, AbstractString) if postfix == "_type" return toglsltype_string(val)::String - else postfix == "_calculation" + else + postfix == "_calculation" return glsl_variable_access(keystring, val) end end @@ -346,9 +347,9 @@ function mustache2replacement(mustache_key, view, attributes) end # Takes a shader template and renders the template and returns shader source -template2source(source::Vector{UInt8}, view, attributes::Dict{Symbol, Any}) = template2source(String(source), attributes, view) -function template2source(source::AbstractString, view, attributes::Dict{Symbol, Any}) - replacements = Dict{String, String}() +template2source(source::Vector{UInt8}, view, attributes::Dict{Symbol,Any}) = template2source(String(source), attributes, view) +function template2source(source::AbstractString, view, attributes::Dict{Symbol,Any}) + replacements = Dict{String,String}() source = mustache_replace(source) do mustache_key r = mustache2replacement(mustache_key, view, attributes) replacements[mustache_key] = r diff --git a/GLMakie/src/GLAbstraction/GLTexture.jl b/GLMakie/src/GLAbstraction/GLTexture.jl index 51ebdbb628e..dc25c73c909 100644 --- a/GLMakie/src/GLAbstraction/GLTexture.jl +++ b/GLMakie/src/GLAbstraction/GLTexture.jl @@ -1,33 +1,33 @@ struct TextureParameters{NDim} minfilter::Symbol magfilter::Symbol # magnification - repeat ::NTuple{NDim, Symbol} + repeat::NTuple{NDim,Symbol} anisotropic::Float32 swizzle_mask::Vector{GLenum} end -abstract type OpenglTexture{T, NDIM} <: GPUArray{T, NDIM} end - -mutable struct Texture{T <: GLArrayEltypes, NDIM} <: OpenglTexture{T, NDIM} - id ::GLuint - texturetype ::GLenum - pixeltype ::GLenum - internalformat ::GLenum - format ::GLenum - parameters ::TextureParameters{NDIM} - size ::NTuple{NDIM, Int} - context ::GLContext - requires_update ::Observable{Bool} - observers ::Vector{Observables.ObserverFunction} - function Texture{T, NDIM}( - id ::GLuint, - texturetype ::GLenum, - pixeltype ::GLenum, - internalformat ::GLenum, - format ::GLenum, - parameters ::TextureParameters{NDIM}, - size ::NTuple{NDIM, Int} - ) where {T, NDIM} +abstract type OpenglTexture{T,NDIM} <: GPUArray{T,NDIM} end + +mutable struct Texture{T<:GLArrayEltypes,NDIM} <: OpenglTexture{T,NDIM} + id::GLuint + texturetype::GLenum + pixeltype::GLenum + internalformat::GLenum + format::GLenum + parameters::TextureParameters{NDIM} + size::NTuple{NDIM,Int} + context::GLContext + requires_update::Observable{Bool} + observers::Vector{Observables.ObserverFunction} + function Texture{T,NDIM}( + id::GLuint, + texturetype::GLenum, + pixeltype::GLenum, + internalformat::GLenum, + format::GLenum, + parameters::TextureParameters{NDIM}, + size::NTuple{NDIM,Int} + ) where {T,NDIM} tex = new( id, texturetype, @@ -46,12 +46,12 @@ mutable struct Texture{T <: GLArrayEltypes, NDIM} <: OpenglTexture{T, NDIM} end # for bufferSampler, aka Texture Buffer -mutable struct TextureBuffer{T <: GLArrayEltypes} <: OpenglTexture{T, 1} - texture::Texture{T, 1} +mutable struct TextureBuffer{T<:GLArrayEltypes} <: OpenglTexture{T,1} + texture::Texture{T,1} buffer::GLBuffer{T} requires_update::Observable{Bool} - function TextureBuffer(texture::Texture{T, 1}, buffer::GLBuffer{T}) where T + function TextureBuffer(texture::Texture{T,1}, buffer::GLBuffer{T}) where T x = map((_, _) -> true, buffer.requires_update, texture.requires_update) new{T}(texture, buffer, x) end @@ -79,7 +79,7 @@ is_texturearray(t::Texture) = t.texturetype == GL_TEXTURE_2D_ARRAY is_texturebuffer(t::Texture) = t.texturetype == GL_TEXTURE_BUFFER colordim(::Type{T}) where {T} = cardinality(T) -colordim(::Type{T}) where {T <: Real} = 1 +colordim(::Type{T}) where {T<:Real} = 1 function set_packing_alignment(a) # at some point we should specialize to array/ptr a glPixelStorei(GL_UNPACK_ALIGNMENT, 1) @@ -89,13 +89,13 @@ function set_packing_alignment(a) # at some point we should specialize to array/ end function Texture( - data::Ptr{T}, dims::NTuple{NDim, Int}; - internalformat::GLenum = default_internalcolorformat(T), - texturetype ::GLenum = default_texturetype(NDim), - format ::GLenum = default_colorformat(T), - mipmap = false, - parameters... # rest should be texture parameters - ) where {T, NDim} + data::Ptr{T}, dims::NTuple{NDim,Int}; + internalformat::GLenum = default_internalcolorformat(T), + texturetype::GLenum = default_texturetype(NDim), + format::GLenum = default_colorformat(T), + mipmap = false, + parameters... # rest should be texture parameters +) where {T,NDim} texparams = TextureParameters(T, NDim; parameters...) id = glGenTextures() glBindTexture(texturetype, id) @@ -103,16 +103,16 @@ function Texture( numbertype = julia2glenum(eltype(T)) glTexImage(texturetype, 0, internalformat, dims..., 0, format, numbertype, data) mipmap && glGenerateMipmap(texturetype) - texture = Texture{T, NDim}( + texture = Texture{T,NDim}( id, texturetype, numbertype, internalformat, format, texparams, dims ) set_parameters(texture) - texture::Texture{T, NDim} + texture::Texture{T,NDim} end export resize_nocopy! -function resize_nocopy!(t::Texture{T, ND}, newdims::NTuple{ND, Int}) where {T, ND} +function resize_nocopy!(t::Texture{T,ND}, newdims::NTuple{ND,Int}) where {T,ND} bind(t) glTexImage(t.texturetype, 0, t.internalformat, newdims..., 0, t.format, t.pixeltype, C_NULL) t.size = newdims @@ -125,8 +125,8 @@ Constructor for empty initialization with NULL pointer instead of an array with You just need to pass the wanted color/vector type and the dimensions. To which values the texture gets initialized is driver dependent """ -Texture(::Type{T}, dims::NTuple{N, Int}; kw_args...) where {T <: GLArrayEltypes, N} = - Texture(convert(Ptr{T}, C_NULL), dims; kw_args...)::Texture{T, N} +Texture(::Type{T}, dims::NTuple{N,Int}; kw_args...) where {T<:GLArrayEltypes,N} = + Texture(convert(Ptr{T}, C_NULL), dims; kw_args...)::Texture{T,N} """ Constructor for a normal array, with color or Abstract Arrays as elements. @@ -134,10 +134,10 @@ So Array{Real, 2} == Texture2D with 1D Colorant dimension Array{Vec1/2/3/4, 2} == Texture2D with 1/2/3/4D Colorant dimension Colors from Colors.jl should mostly work as well """ -Texture(image::Array{T, NDim}; kw_args...) where {T <: GLArrayEltypes, NDim} = - Texture(pointer(image), size(image); kw_args...)::Texture{T, NDim} +Texture(image::Array{T,NDim}; kw_args...) where {T<:GLArrayEltypes,NDim} = + Texture(pointer(image), size(image); kw_args...)::Texture{T,NDim} -function Texture(s::ShaderAbstractions.Sampler{T, N}; kwargs...) where {T, N} +function Texture(s::ShaderAbstractions.Sampler{T,N}; kwargs...) where {T,N} tex = Texture( pointer(s.data), size(s.data), minfilter = s.minfilter, magfilter = s.magfilter, @@ -153,12 +153,12 @@ end Constructor for Array Texture """ function Texture( - data::Vector{Array{T, 2}}; - internalformat::GLenum = default_internalcolorformat(T), - texturetype::GLenum = GL_TEXTURE_2D_ARRAY, - format::GLenum = default_colorformat(T), - parameters... - ) where T <: GLArrayEltypes + data::Vector{Array{T,2}}; + internalformat::GLenum = default_internalcolorformat(T), + texturetype::GLenum = GL_TEXTURE_2D_ARRAY, + format::GLenum = default_colorformat(T), + parameters... +) where T<:GLArrayEltypes texparams = TextureParameters(T, 2; parameters...) id = glGenTextures() @@ -166,21 +166,21 @@ function Texture( numbertype = julia2glenum(eltype(T)) - layers = length(data) - dims = map(size, data) - maxdims = foldl(dims, init = (0,0)) do v0, x + layers = length(data) + dims = map(size, data) + maxdims = foldl(dims, init = (0, 0)) do v0, x a = max(v0[1], x[1]) b = max(v0[2], x[2]) - (a,b) + (a, b) end set_packing_alignment(data) glTexStorage3D(GL_TEXTURE_2D_ARRAY, 1, internalformat, maxdims..., layers) for (layer, texel) in enumerate(data) width, height = size(texel) - glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, layer-1, width, height, 1, format, numbertype, texel) + glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, layer - 1, width, height, 1, format, numbertype, texel) end - texture = Texture{T, 2}( + texture = Texture{T,2}( id, texturetype, numbertype, internalformat, format, texparams, tuple(maxdims...) @@ -191,20 +191,20 @@ end -function TextureBuffer(buffer::GLBuffer{T}) where T <: GLArrayEltypes +function TextureBuffer(buffer::GLBuffer{T}) where T<:GLArrayEltypes texture_type = GL_TEXTURE_BUFFER id = glGenTextures() glBindTexture(texture_type, id) internalformat = default_internalcolorformat(T) glTexBuffer(texture_type, internalformat, buffer.id) - tex = Texture{T, 1}( + tex = Texture{T,1}( id, texture_type, julia2glenum(T), internalformat, default_colorformat(T), TextureParameters(T, 1), size(buffer) ) TextureBuffer(tex, buffer) end -function TextureBuffer(buffer::Vector{T}) where T <: GLArrayEltypes +function TextureBuffer(buffer::Vector{T}) where T<:GLArrayEltypes buff = GLBuffer(buffer, buffertype = GL_TEXTURE_BUFFER, usage = GL_DYNAMIC_DRAW) TextureBuffer(buff) end @@ -245,7 +245,7 @@ function Base.show(io::IO, ::MIME"text/plain", t::Texture{T,D}) where {T,D} println(io, "Texture$(D)D: ") println(io, " ID: ", t.id) println(io, " Size: ", reduce(size(t), init = "Dimensions: ") do v0, v1 - v0*"x"*string(v1) + v0 * "x" * string(v1) end) println(io, " Julia pixel type: ", T) println(io, " OpenGL pixel type: ", GLENUM(t.pixeltype).name) @@ -278,26 +278,26 @@ function unsafe_copy!(a::TextureBuffer{T}, readoffset::Int, b::TextureBuffer{T}, bind(t.texture, 0) end -function gpu_setindex!(t::TextureBuffer{T}, newvalue::Vector{T}, indexes::UnitRange{I}) where {T, I <: Integer} +function gpu_setindex!(t::TextureBuffer{T}, newvalue::Vector{T}, indexes::UnitRange{I}) where {T,I<:Integer} bind(t.texture) t.buffer[indexes] = newvalue # set buffer indexes glTexBuffer(t.texture.texturetype, t.texture.internalformat, t.buffer.id) # update texture bind(t.texture, 0) end -function gpu_setindex!(t::Texture{T, 1}, newvalue::Array{T, 1}, indexes::UnitRange{I}) where {T, I <: Integer} +function gpu_setindex!(t::Texture{T,1}, newvalue::Array{T,1}, indexes::UnitRange{I}) where {T,I<:Integer} bind(t) texsubimage(t, newvalue, indexes) bind(t, 0) end -function gpu_setindex!(t::Texture{T, N}, newvalue::Array{T, N}, indexes::Union{UnitRange,Integer}...) where {T, N} +function gpu_setindex!(t::Texture{T,N}, newvalue::Array{T,N}, indexes::Union{UnitRange,Integer}...) where {T,N} bind(t) texsubimage(t, newvalue, indexes...) bind(t, 0) end -function gpu_setindex!(target::Texture{T, 2}, source::Texture{T, 2}, fbo=glGenFramebuffers()) where T +function gpu_setindex!(target::Texture{T,2}, source::Texture{T,2}, fbo = glGenFramebuffers()) where T glBindFramebuffer(GL_FRAMEBUFFER, fbo) glFramebufferTexture2D( GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, @@ -307,7 +307,7 @@ function gpu_setindex!(target::Texture{T, 2}, source::Texture{T, 2}, fbo=glGenFr GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, target.id, 0 ) - glDrawBuffer(GL_COLOR_ATTACHMENT1); + glDrawBuffer(GL_COLOR_ATTACHMENT1) w, h = map(minimum, zip(size(target), size(source))) glBlitFramebuffer( 0, 0, w, h, 0, 0, w, h, @@ -327,13 +327,13 @@ function gpu_setindex!{T}(target::Texture{T, 2}, source::Texture{T, 2}, fbo=glGe end =# # Implementing the GPUArray interface -function gpu_data(t::Texture{T, ND}) where {T, ND} - result = Array{T, ND}(undef, size(t)) +function gpu_data(t::Texture{T,ND}) where {T,ND} + result = Array{T,ND}(undef, size(t)) unsafe_copy!(result, t) return result end -function unsafe_copy!(dest::Array{T, N}, source::Texture{T, N}) where {T,N} +function unsafe_copy!(dest::Array{T,N}, source::Texture{T,N}) where {T,N} bind(source) glGetTexImage(source.texturetype, 0, source.format, source.pixeltype, dest) bind(source, 0) @@ -343,12 +343,12 @@ end gpu_data(t::TextureBuffer{T}) where {T} = gpu_data(t.buffer) gpu_getindex(t::TextureBuffer{T}, i::UnitRange{Int64}) where {T} = t.buffer[i] -similar(t::Texture{T, NDim}, newdims::Int...) where {T, NDim} = similar(t, newdims) -function similar(t::TextureBuffer{T}, newdims::NTuple{1, Int}) where T +similar(t::Texture{T,NDim}, newdims::Int...) where {T,NDim} = similar(t, newdims) +function similar(t::TextureBuffer{T}, newdims::NTuple{1,Int}) where T buff = similar(t.buffer, newdims...) return TextureBuffer(buff) end -function similar(t::Texture{T, NDim}, newdims::NTuple{NDim, Int}) where {T, NDim} +function similar(t::Texture{T,NDim}, newdims::NTuple{NDim,Int}) where {T,NDim} Texture( Ptr{T}(C_NULL), newdims, t.texturetype, @@ -359,16 +359,16 @@ function similar(t::Texture{T, NDim}, newdims::NTuple{NDim, Int}) where {T, NDim ) end # Resize Texture -function gpu_resize!(t::TextureBuffer{T}, newdims::NTuple{1, Int}) where T +function gpu_resize!(t::TextureBuffer{T}, newdims::NTuple{1,Int}) where T resize!(t.buffer, newdims) bind(t.texture) glTexBuffer(t.texture.texturetype, t.texture.internalformat, t.buffer.id) #update data in texture - t.texture.size = newdims + t.texture.size = newdims bind(t.texture, 0) t end # Resize Texture -function gpu_resize!(t::Texture{T, ND}, newdims::NTuple{ND, Int}) where {T, ND} +function gpu_resize!(t::Texture{T,ND}, newdims::NTuple{ND,Int}) where {T,ND} # dangerous code right here...Better write a few tests for this newtex = similar(t, newdims) old_size = size(t) @@ -379,25 +379,25 @@ function gpu_resize!(t::Texture{T, ND}, newdims::NTuple{ND, Int}) where {T, ND} return t end -texsubimage(t::Texture{T, 1}, newvalue::Array{T, 1}, xrange::UnitRange, level=0) where {T} = glTexSubImage1D( - t.texturetype, level, first(xrange)-1, length(xrange), t.format, t.pixeltype, newvalue +texsubimage(t::Texture{T,1}, newvalue::Array{T,1}, xrange::UnitRange, level = 0) where {T} = glTexSubImage1D( + t.texturetype, level, first(xrange) - 1, length(xrange), t.format, t.pixeltype, newvalue ) -function texsubimage(t::Texture{T, 2}, newvalue::Array{T, 2}, xrange::UnitRange, yrange::UnitRange, level=0) where T +function texsubimage(t::Texture{T,2}, newvalue::Array{T,2}, xrange::UnitRange, yrange::UnitRange, level = 0) where T glTexSubImage2D( t.texturetype, level, - first(xrange)-1, first(yrange)-1, length(xrange), length(yrange), + first(xrange) - 1, first(yrange) - 1, length(xrange), length(yrange), t.format, t.pixeltype, newvalue ) end -texsubimage(t::Texture{T, 3}, newvalue::Array{T, 3}, xrange::UnitRange, yrange::UnitRange, zrange::UnitRange, level=0) where {T} = glTexSubImage3D( +texsubimage(t::Texture{T,3}, newvalue::Array{T,3}, xrange::UnitRange, yrange::UnitRange, zrange::UnitRange, level = 0) where {T} = glTexSubImage3D( t.texturetype, level, - first(xrange)-1, first(yrange)-1, first(zrange)-1, length(xrange), length(yrange), length(zrange), + first(xrange) - 1, first(yrange) - 1, first(zrange) - 1, length(xrange), length(yrange), length(zrange), t.format, t.pixeltype, newvalue ) Base.iterate(t::TextureBuffer{T}) where {T} = iterate(t.buffer) -function Base.iterate(t::TextureBuffer{T}, state::Tuple{Ptr{T}, Int}) where T +function Base.iterate(t::TextureBuffer{T}, state::Tuple{Ptr{T},Int}) where T v_idx = iterate(t.buffer, state) if v_idx === nothing bind(t) @@ -417,10 +417,10 @@ function default_colorformat_sym(colordim::Integer, isinteger::Bool, colororder: return Symbol(sym) end -default_colorformat_sym(::Type{T}) where {T <: Real} = default_colorformat_sym(1, T <: Integer, "RED") -default_colorformat_sym(::Type{T}) where {T <: AbstractArray} = default_colorformat_sym(cardinality(T), eltype(T) <: Integer, "RGBA") -default_colorformat_sym(::Type{T}) where {T <: StaticVector} = default_colorformat_sym(cardinality(T), eltype(T) <: Integer, "RGBA") -default_colorformat_sym(::Type{T}) where {T <: Colorant} = default_colorformat_sym(cardinality(T), eltype(T) <: Integer, string(Base.typename(T).name)) +default_colorformat_sym(::Type{T}) where {T<:Real} = default_colorformat_sym(1, T <: Integer, "RED") +default_colorformat_sym(::Type{T}) where {T<:AbstractArray} = default_colorformat_sym(cardinality(T), eltype(T) <: Integer, "RGBA") +default_colorformat_sym(::Type{T}) where {T<:StaticVector} = default_colorformat_sym(cardinality(T), eltype(T) <: Integer, "RGBA") +default_colorformat_sym(::Type{T}) where {T<:Colorant} = default_colorformat_sym(cardinality(T), eltype(T) <: Integer, string(Base.typename(T).name)) @generated function default_colorformat(::Type{T}) where T sym = default_colorformat_sym(T) @@ -472,7 +472,7 @@ function default_texturetype(ndim::Integer) end -map_texture_paramers(s::NTuple{N, Symbol}) where {N} = map(map_texture_paramers, s) +map_texture_paramers(s::NTuple{N,Symbol}) where {N} = map(map_texture_paramers, s) function map_texture_paramers(s::Symbol) @@ -491,13 +491,13 @@ function map_texture_paramers(s::Symbol) end function TextureParameters(T, NDim; - minfilter = T <: Integer ? :nearest : :linear, - magfilter = minfilter, # magnification - x_repeat = :clamp_to_edge, #wrap_s - y_repeat = x_repeat, #wrap_t - z_repeat = x_repeat, #wrap_r - anisotropic = 1f0 - ) + minfilter = T <: Integer ? :nearest : :linear, + magfilter = minfilter, # magnification + x_repeat = :clamp_to_edge, #wrap_s + y_repeat = x_repeat, #wrap_t + z_repeat = x_repeat, #wrap_r + anisotropic = 1f0 +) T <: Integer && (minfilter == :linear || magfilter == :linear) && error("Wrong Texture Parameter: Integer texture can't interpolate. Try :nearest") repeat = (x_repeat, y_repeat, z_repeat) swizzle_mask = if T <: Gray @@ -508,20 +508,20 @@ function TextureParameters(T, NDim; GLenum[] end TextureParameters( - minfilter, magfilter, ntuple(i->repeat[i], NDim), + minfilter, magfilter, ntuple(i -> repeat[i], NDim), anisotropic, swizzle_mask ) end -function TextureParameters(t::Texture{T, NDim}; kw_args...) where {T, NDim} +function TextureParameters(t::Texture{T,NDim}; kw_args...) where {T,NDim} TextureParameters(T, NDim; kw_args...) end const GL_TEXTURE_MAX_ANISOTROPY_EXT = GLenum(0x84FE) -function set_parameters(t::Texture{T, N}, params::TextureParameters=t.parameters) where {T, N} +function set_parameters(t::Texture{T,N}, params::TextureParameters = t.parameters) where {T,N} fnames = (:minfilter, :magfilter, :repeat) data = Dict([(name, map_texture_paramers(getfield(params, name))) for name in fnames]) - result = Tuple{GLenum, Any}[] + result = Tuple{GLenum,Any}[] push!(result, (GL_TEXTURE_MIN_FILTER, data[:minfilter])) push!(result, (GL_TEXTURE_MAG_FILTER, data[:magfilter])) push!(result, (GL_TEXTURE_WRAP_S, data[:repeat][1])) @@ -551,7 +551,7 @@ end function texparameter(t::Texture, key::GLenum, val::Float32) glTexParameterf(t.texturetype, key, val) end -function set_parameters(t::Texture, parameters::Vector{Tuple{GLenum, Any}}) +function set_parameters(t::Texture, parameters::Vector{Tuple{GLenum,Any}}) bind(t) for elem in parameters texparameter(t, elem...) diff --git a/GLMakie/src/GLAbstraction/GLTypes.jl b/GLMakie/src/GLAbstraction/GLTypes.jl index 3c6e860191a..44301ce87d4 100644 --- a/GLMakie/src/GLAbstraction/GLTypes.jl +++ b/GLMakie/src/GLAbstraction/GLTypes.jl @@ -1,7 +1,7 @@ ############################################################################ const TOrSignal{T} = Union{Observable{T},T} -const ArrayOrSignal{T,N} = TOrSignal{X} where X <: AbstractArray{T,N} +const ArrayOrSignal{T,N} = TOrSignal{X} where X<:AbstractArray{T,N} const VecOrSignal{T} = ArrayOrSignal{T,1} const MatOrSignal{T} = ArrayOrSignal{T,2} const VolumeOrSignal{T} = ArrayOrSignal{T,3} @@ -19,7 +19,7 @@ Returns the cardinality of a type. falls back to length """ cardinality(x) = length(x) cardinality(x::Number) = 1 -cardinality(x::Type{T}) where {T <: Number} = 1 +cardinality(x::Type{T}) where {T<:Number} = 1 struct Shader name::Symbol @@ -132,24 +132,24 @@ const GLArrayEltypes = Union{StaticVector,Real,Colorant} """ Transform julia datatypes to opengl enum type """ -julia2glenum(x::Type{T}) where {T <: FixedPoint} = julia2glenum(FixedPointNumbers.rawtype(x)) -julia2glenum(x::Union{Type{T},T}) where {T <: Union{StaticVector,Colorant}} = julia2glenum(eltype(x)) +julia2glenum(x::Type{T}) where {T<:FixedPoint} = julia2glenum(FixedPointNumbers.rawtype(x)) +julia2glenum(x::Union{Type{T},T}) where {T<:Union{StaticVector,Colorant}} = julia2glenum(eltype(x)) julia2glenum(::Type{OffsetInteger{O,T}}) where {O,T} = julia2glenum(T) -julia2glenum(::Type{GLubyte}) = GL_UNSIGNED_BYTE -julia2glenum(::Type{GLbyte}) = GL_BYTE -julia2glenum(::Type{GLuint}) = GL_UNSIGNED_INT +julia2glenum(::Type{GLubyte}) = GL_UNSIGNED_BYTE +julia2glenum(::Type{GLbyte}) = GL_BYTE +julia2glenum(::Type{GLuint}) = GL_UNSIGNED_INT julia2glenum(::Type{GLushort}) = GL_UNSIGNED_SHORT -julia2glenum(::Type{GLshort}) = GL_SHORT -julia2glenum(::Type{GLint}) = GL_INT -julia2glenum(::Type{GLfloat}) = GL_FLOAT +julia2glenum(::Type{GLshort}) = GL_SHORT +julia2glenum(::Type{GLint}) = GL_INT +julia2glenum(::Type{GLfloat}) = GL_FLOAT julia2glenum(::Type{GLdouble}) = GL_DOUBLE -julia2glenum(::Type{Float16}) = GL_HALF_FLOAT +julia2glenum(::Type{Float16}) = GL_HALF_FLOAT struct DepthStencil_24_8 <: Real data::NTuple{4,UInt8} end -Base.eltype(::Type{<: DepthStencil_24_8}) = DepthStencil_24_8 +Base.eltype(::Type{<:DepthStencil_24_8}) = DepthStencil_24_8 julia2glenum(x::Type{DepthStencil_24_8}) = GL_UNSIGNED_INT_24_8 function julia2glenum(::Type{T}) where T @@ -255,7 +255,7 @@ function GLVertexArray(bufferdict::Dict, program::GLProgram) return obj end using ShaderAbstractions: Buffer -function GLVertexArray(program::GLProgram, buffers::Buffer, triangles::AbstractVector{<: GLTriangleFace}) +function GLVertexArray(program::GLProgram, buffers::Buffer, triangles::AbstractVector{<:GLTriangleFace}) # get the size of the first array, to assert later, that all have the same size id = glGenVertexArrays() glBindVertexArray(id) @@ -317,12 +317,12 @@ mutable struct RenderObject{Pre} visible::Bool function RenderObject{Pre}( - context, - uniforms::Dict{Symbol,Any}, observables::Vector{Observable}, - vertexarray::GLVertexArray, - prerenderfunctions, postrenderfunctions, - visible, track_updates = true - ) where Pre + context, + uniforms::Dict{Symbol,Any}, observables::Vector{Observable}, + vertexarray::GLVertexArray, + prerenderfunctions, postrenderfunctions, + visible, track_updates = true + ) where Pre fxaa = Bool(to_value(get!(uniforms, :fxaa, true))) RENDER_OBJECT_ID_COUNTER[] += one(UInt32) # Store fxaa in ID, so we can access it in the shader to create a mask @@ -391,10 +391,10 @@ mutable struct RenderObject{Pre} end function RenderObject( - data::Dict{Symbol,Any}, program, - pre::Pre, post, - context=current_context() - ) where Pre + data::Dict{Symbol,Any}, program, + pre::Pre, post, + context = current_context() +) where Pre switch_context!(context) diff --git a/GLMakie/src/GLAbstraction/GLUniforms.jl b/GLMakie/src/GLAbstraction/GLUniforms.jl index 17f83cc7ec8..76e4c9c556b 100644 --- a/GLMakie/src/GLAbstraction/GLUniforms.jl +++ b/GLMakie/src/GLAbstraction/GLUniforms.jl @@ -5,48 +5,48 @@ const GLSL_COMPATIBLE_NUMBER_TYPES = (GLfloat, GLint, GLuint, GLdouble) const NATIVE_TYPES = Union{ - StaticVector, Mat, GLSL_COMPATIBLE_NUMBER_TYPES..., - ZeroIndex{GLint}, ZeroIndex{GLuint}, - GLBuffer, GPUArray, Shader, GLProgram + StaticVector,Mat,GLSL_COMPATIBLE_NUMBER_TYPES..., + ZeroIndex{GLint},ZeroIndex{GLuint}, + GLBuffer,GPUArray,Shader,GLProgram } -opengl_prefix(T) = error("Object $T is not a supported uniform element type") +opengl_prefix(T) = error("Object $T is not a supported uniform element type") opengl_postfix(T) = error("Object $T is not a supported uniform element type") -opengl_prefix(x::Type{T}) where {T <: Union{FixedPoint, Float32, Float16}} = "" -opengl_prefix(x::Type{T}) where {T <: Float64} = "d" +opengl_prefix(x::Type{T}) where {T<:Union{FixedPoint,Float32,Float16}} = "" +opengl_prefix(x::Type{T}) where {T<:Float64} = "d" opengl_prefix(x::Type{Cint}) = "i" -opengl_prefix(x::Type{T}) where {T <: Union{Cuint, UInt8, UInt16}} = "u" +opengl_prefix(x::Type{T}) where {T<:Union{Cuint,UInt8,UInt16}} = "u" opengl_postfix(x::Type{Float64}) = "dv" opengl_postfix(x::Type{Float32}) = "fv" -opengl_postfix(x::Type{Cint}) = "iv" -opengl_postfix(x::Type{Cuint}) = "uiv" +opengl_postfix(x::Type{Cint}) = "iv" +opengl_postfix(x::Type{Cuint}) = "uiv" function uniformfunc(typ::DataType, dims::Tuple{Int}) Symbol(string("glUniform", first(dims), opengl_postfix(typ))) end -function uniformfunc(typ::DataType, dims::Tuple{Int, Int}) +function uniformfunc(typ::DataType, dims::Tuple{Int,Int}) M, N = dims Symbol(string("glUniformMatrix", M == N ? "$M" : "$(M)x$(N)", opengl_postfix(typ))) end gluniform(location::Integer, x::Nothing) = nothing -function gluniform(location::Integer, x::Union{StaticVector, Mat, Colorant}) +function gluniform(location::Integer, x::Union{StaticVector,Mat,Colorant}) xref = [x] gluniform(location, xref) end _size(p) = size(p) _size(p::Colorant) = (length(p),) -_size(p::Type{T}) where {T <: Colorant} = (length(p),) +_size(p::Type{T}) where {T<:Colorant} = (length(p),) _ndims(p) = ndims(p) -_ndims(p::Type{T}) where {T <: Colorant} = 1 +_ndims(p::Type{T}) where {T<:Colorant} = 1 -@generated function gluniform(location::Integer, x::Vector{FSA}) where FSA <: Union{Mat, Colorant, StaticVector} +@generated function gluniform(location::Integer, x::Vector{FSA}) where FSA<:Union{Mat,Colorant,StaticVector} func = uniformfunc(eltype(FSA), _size(FSA)) callexpr = if _ndims(FSA) == 2 :($func(location, length(x), GL_FALSE, x)) @@ -76,15 +76,15 @@ function gluniform(loc::Integer, x::Observable{T}) where T gluniform(GLint(loc), to_value(x)) end -gluniform(location::Integer, x::Union{GLubyte, GLushort, GLuint}) = glUniform1ui(GLint(location), x) -gluniform(location::Integer, x::Union{GLbyte, GLshort, GLint, Bool}) = glUniform1i(GLint(location), x) -gluniform(location::Integer, x::GLfloat) = glUniform1f(GLint(location), x) -gluniform(location::Integer, x::GLdouble) = glUniform1d(GLint(location), x) +gluniform(location::Integer, x::Union{GLubyte,GLushort,GLuint}) = glUniform1ui(GLint(location), x) +gluniform(location::Integer, x::Union{GLbyte,GLshort,GLint,Bool}) = glUniform1i(GLint(location), x) +gluniform(location::Integer, x::GLfloat) = glUniform1f(GLint(location), x) +gluniform(location::Integer, x::GLdouble) = glUniform1d(GLint(location), x) #Uniform upload functions for julia arrays... -gluniform(location::GLint, x::Vector{Float32}) = glUniform1fv(location, length(x), x) -gluniform(location::GLint, x::Vector{GLdouble}) = glUniform1dv(location, length(x), x) -gluniform(location::GLint, x::Vector{GLint}) = glUniform1iv(location, length(x), x) +gluniform(location::GLint, x::Vector{Float32}) = glUniform1fv(location, length(x), x) +gluniform(location::GLint, x::Vector{GLdouble}) = glUniform1dv(location, length(x), x) +gluniform(location::GLint, x::Vector{GLint}) = glUniform1iv(location, length(x), x) gluniform(location::GLint, x::Vector{GLuint}) = glUniform1uiv(location, length(x), x) glsl_typename(x::T) where {T} = glsl_typename(T) @@ -94,21 +94,21 @@ glsl_typename(t::Type{GLfloat}) = "float" glsl_typename(t::Type{GLdouble}) = "double" glsl_typename(t::Type{GLuint}) = "uint" glsl_typename(t::Type{GLint}) = "int" -glsl_typename(t::Type{T}) where {T <: Union{StaticVector, Colorant}} = string(opengl_prefix(eltype(T)), "vec", length(T)) +glsl_typename(t::Type{T}) where {T<:Union{StaticVector,Colorant}} = string(opengl_prefix(eltype(T)), "vec", length(T)) glsl_typename(t::Type{TextureBuffer{T}}) where {T} = string(opengl_prefix(eltype(T)), "samplerBuffer") -function glsl_typename(t::Texture{T, D}) where {T, D} +function glsl_typename(t::Texture{T,D}) where {T,D} str = string(opengl_prefix(eltype(T)), "sampler", D, "D") t.texturetype == GL_TEXTURE_2D_ARRAY && (str *= "Array") str end -function glsl_typename(t::Type{T}) where T <: Mat +function glsl_typename(t::Type{T}) where T<:Mat M, N = size(t) - string(opengl_prefix(eltype(t)), "mat", M==N ? M : string(M, "x", N)) + string(opengl_prefix(eltype(t)), "mat", M == N ? M : string(M, "x", N)) end toglsltype_string(t::Observable) = toglsltype_string(to_value(t)) -toglsltype_string(x::T) where {T<:Union{Real, Mat, StaticVector, Texture, Colorant, TextureBuffer, Nothing}} = "uniform $(glsl_typename(x))" +toglsltype_string(x::T) where {T<:Union{Real,Mat,StaticVector,Texture,Colorant,TextureBuffer,Nothing}} = "uniform $(glsl_typename(x))" #Handle GLSL structs, which need to be addressed via single fields function toglsltype_string(x::T) where T if isa_gl_struct(x) @@ -117,16 +117,16 @@ function toglsltype_string(x::T) where T error("can't splice $T into an OpenGL shader. Make sure all fields are of a concrete type and isbits(FieldType)-->true") end end -toglsltype_string(t::Union{GLBuffer{T}, GPUVector{T}}) where {T} = string("in ", glsl_typename(T)) +toglsltype_string(t::Union{GLBuffer{T},GPUVector{T}}) where {T} = string("in ", glsl_typename(T)) # Gets used to access a -function glsl_variable_access(keystring, t::Texture{T, D}) where {T,D} +function glsl_variable_access(keystring, t::Texture{T,D}) where {T,D} fields = SubString("rgba", 1, length(T)) if t.texturetype == GL_TEXTURE_BUFFER return string("texelFetch(", keystring, "index).", fields, ";") end return string("getindex(", keystring, "index).", fields, ";") end -function glsl_variable_access(keystring, ::Union{Real, GLBuffer, GPUVector, Mat, Colorant}) +function glsl_variable_access(keystring, ::Union{Real,GLBuffer,GPUVector,Mat,Colorant}) string(keystring, ";") end function glsl_variable_access(keystring, s::Observable) @@ -138,20 +138,20 @@ end function uniform_name_type(program::GLuint) uniformLength = glGetProgramiv(program, GL_ACTIVE_UNIFORMS) - Dict{Symbol, GLenum}(ntuple(uniformLength) do i # take size and name - name, typ = glGetActiveUniform(program, i-1) + Dict{Symbol,GLenum}(ntuple(uniformLength) do i # take size and name + name, typ = glGetActiveUniform(program, i - 1) end) end function attribute_name_type(program::GLuint) uniformLength = glGetProgramiv(program, GL_ACTIVE_ATTRIBUTES) - Dict{Symbol, GLenum}(ntuple(uniformLength) do i - name, typ = glGetActiveAttrib(program, i-1) + Dict{Symbol,GLenum}(ntuple(uniformLength) do i + name, typ = glGetActiveAttrib(program, i - 1) end) end function istexturesampler(typ::GLenum) return ( typ == GL_SAMPLER_BUFFER || typ == GL_INT_SAMPLER_BUFFER || typ == GL_UNSIGNED_INT_SAMPLER_BUFFER || - typ == GL_IMAGE_2D || + typ == GL_IMAGE_2D || typ == GL_SAMPLER_1D || typ == GL_SAMPLER_2D || typ == GL_SAMPLER_3D || typ == GL_UNSIGNED_INT_SAMPLER_1D || typ == GL_UNSIGNED_INT_SAMPLER_2D || typ == GL_UNSIGNED_INT_SAMPLER_3D || typ == GL_INT_SAMPLER_1D || typ == GL_INT_SAMPLER_2D || typ == GL_INT_SAMPLER_3D || @@ -162,39 +162,39 @@ function istexturesampler(typ::GLenum) end -gl_promote(x::Type{T}) where {T <: Integer} = Cint -gl_promote(x::Type{Union{Int16, Int8}}) = x +gl_promote(x::Type{T}) where {T<:Integer} = Cint +gl_promote(x::Type{Union{Int16,Int8}}) = x -gl_promote(x::Type{T}) where {T <: Unsigned} = Cuint -gl_promote(x::Type{Union{UInt16, UInt8}}) = x +gl_promote(x::Type{T}) where {T<:Unsigned} = Cuint +gl_promote(x::Type{Union{UInt16,UInt8}}) = x -gl_promote(x::Type{T}) where {T <: AbstractFloat} = Float32 +gl_promote(x::Type{T}) where {T<:AbstractFloat} = Float32 gl_promote(x::Type{Float16}) = x -gl_promote(x::Type{T}) where {T <: Normed} = N0f32 +gl_promote(x::Type{T}) where {T<:Normed} = N0f32 gl_promote(x::Type{N0f16}) = x gl_promote(x::Type{N0f8}) = x -const Color3{T} = Colorant{T, 3} -const Color4{T} = Colorant{T, 4} +const Color3{T} = Colorant{T,3} +const Color4{T} = Colorant{T,4} -gl_promote(x::Type{Bool}) = GLboolean -gl_promote(x::Type{T}) where {T <: Gray} = Gray{gl_promote(eltype(T))} -gl_promote(x::Type{T}) where {T <: Color3} = RGB{gl_promote(eltype(T))} -gl_promote(x::Type{T}) where {T <: Color4} = RGBA{gl_promote(eltype(T))} -gl_promote(x::Type{T}) where {T <: BGRA} = BGRA{gl_promote(eltype(T))} -gl_promote(x::Type{T}) where {T <: BGR} = BGR{gl_promote(eltype(T))} +gl_promote(x::Type{Bool}) = GLboolean +gl_promote(x::Type{T}) where {T<:Gray} = Gray{gl_promote(eltype(T))} +gl_promote(x::Type{T}) where {T<:Color3} = RGB{gl_promote(eltype(T))} +gl_promote(x::Type{T}) where {T<:Color4} = RGBA{gl_promote(eltype(T))} +gl_promote(x::Type{T}) where {T<:BGRA} = BGRA{gl_promote(eltype(T))} +gl_promote(x::Type{T}) where {T<:BGR} = BGR{gl_promote(eltype(T))} -gl_promote(x::Type{Vec{N, T}}) where {N, T} = Vec{N, gl_promote(T)} -gl_promote(x::Type{Point{N, T}}) where {N, T} = Point{N, gl_promote(T)} +gl_promote(x::Type{Vec{N,T}}) where {N,T} = Vec{N,gl_promote(T)} +gl_promote(x::Type{Point{N,T}}) where {N,T} = Point{N,gl_promote(T)} gl_convert(x::AbstractVector{Vec3f}) = x -gl_convert(x::T) where {T <: Number} = gl_promote(T)(x) -gl_convert(x::T) where {T <: Colorant} = gl_promote(T)(x) -gl_convert(x::T) where {T <: AbstractMesh} = gl_convert(x) -gl_convert(x::T) where {T <: GeometryBasics.Mesh} = gl_promote(T)(x) -gl_convert(x::Observable{T}) where {T <: GeometryBasics.Mesh} = gl_promote(T)(x) +gl_convert(x::T) where {T<:Number} = gl_promote(T)(x) +gl_convert(x::T) where {T<:Colorant} = gl_promote(T)(x) +gl_convert(x::T) where {T<:AbstractMesh} = gl_convert(x) +gl_convert(x::T) where {T<:GeometryBasics.Mesh} = gl_promote(T)(x) +gl_convert(x::Observable{T}) where {T<:GeometryBasics.Mesh} = gl_promote(T)(x) gl_convert(s::Vector{Matrix{T}}) where {T<:Colorant} = Texture(s) gl_convert(s::Nothing) = s @@ -213,7 +213,7 @@ function isa_gl_struct(x::T) where T end function gl_convert_struct(x::T, uniform_name::Symbol) where T if isa_gl_struct(x) - return Dict{Symbol, Any}(map(fieldnames(x)) do name + return Dict{Symbol,Any}(map(fieldnames(x)) do name (Symbol("$uniform_name.$name") => gl_convert(getfield(x, name))) end) else @@ -223,38 +223,38 @@ end # native types don't need convert! -gl_convert(a::T) where {T <: NATIVE_TYPES} = a -gl_convert(s::Observable{T}) where {T <: NATIVE_TYPES} = s +gl_convert(a::T) where {T<:NATIVE_TYPES} = a +gl_convert(s::Observable{T}) where {T<:NATIVE_TYPES} = s gl_convert(s::Observable{T}) where T = const_lift(gl_convert, s) -gl_convert(x::StaticVector{N, T}) where {N, T} = map(gl_promote(T), x) -gl_convert(x::Mat{N, M, T}) where {N, M, T} = map(gl_promote(T), x) -gl_convert(a::AbstractVector{<: AbstractFace}) = indexbuffer(s) -gl_convert(t::Type{T}, a::T; kw_args...) where T <: NATIVE_TYPES = a -gl_convert(::Type{<: GPUArray}, a::StaticVector) = gl_convert(a) - -function gl_convert(T::Type{<: GPUArray}, a::AbstractArray{X, N}; kw_args...) where {X, N} - T(convert(AbstractArray{gl_promote(X), N}, a); kw_args...) +gl_convert(x::StaticVector{N,T}) where {N,T} = map(gl_promote(T), x) +gl_convert(x::Mat{N,M,T}) where {N,M,T} = map(gl_promote(T), x) +gl_convert(a::AbstractVector{<:AbstractFace}) = indexbuffer(s) +gl_convert(t::Type{T}, a::T; kw_args...) where T<:NATIVE_TYPES = a +gl_convert(::Type{<:GPUArray}, a::StaticVector) = gl_convert(a) + +function gl_convert(T::Type{<:GPUArray}, a::AbstractArray{X,N}; kw_args...) where {X,N} + T(convert(AbstractArray{gl_promote(X),N}, a); kw_args...) end -gl_convert(::Type{<: GLBuffer}, x::GLBuffer; kw_args...) = x +gl_convert(::Type{<:GLBuffer}, x::GLBuffer; kw_args...) = x gl_convert(::Type{Texture}, x::Texture) = x -gl_convert(::Type{<: GPUArray}, x::GPUArray) = x +gl_convert(::Type{<:GPUArray}, x::GPUArray) = x -function gl_convert(::Type{T}, a::Vector{Array{X, 2}}; kw_args...) where {T <: Texture, X} +function gl_convert(::Type{T}, a::Vector{Array{X,2}}; kw_args...) where {T<:Texture,X} T(a; kw_args...) end -gl_convert(::Type{<: GPUArray}, a::Observable{<: StaticVector}) = gl_convert(a) +gl_convert(::Type{<:GPUArray}, a::Observable{<:StaticVector}) = gl_convert(a) -function gl_convert(::Type{T}, a::Observable{<: AbstractArray{X, N}}; kw_args...) where {T <: GPUArray, X, N} +function gl_convert(::Type{T}, a::Observable{<:AbstractArray{X,N}}; kw_args...) where {T<:GPUArray,X,N} TGL = gl_promote(X) - s = (X == TGL) ? a : lift(x-> convert(Array{TGL, N}, x), a) + s = (X == TGL) ? a : lift(x -> convert(Array{TGL,N}, x), a) T(s; kw_args...) end -lift_convert(a::AbstractArray, T, N) = lift(x -> convert(Array{T, N}, x), a) +lift_convert(a::AbstractArray, T, N) = lift(x -> convert(Array{T,N}, x), a) function lift_convert(a::ShaderAbstractions.Sampler, T, N) ShaderAbstractions.Sampler( - lift(x -> convert(Array{T, N}, x.data), a), + lift(x -> convert(Array{T,N}, x.data), a), minfilter = a[].minfilter, magfilter = a[].magfilter, x_repeat = a[].repeat[1], y_repeat = a[].repeat[min(2, N)], diff --git a/GLMakie/src/GLAbstraction/GLUtils.jl b/GLMakie/src/GLAbstraction/GLUtils.jl index ff6f2ade728..3a5b2a62969 100644 --- a/GLMakie/src/GLAbstraction/GLUtils.jl +++ b/GLMakie/src/GLAbstraction/GLUtils.jl @@ -1,6 +1,6 @@ function print_with_lines(out::IO, text::AbstractString) io = IOBuffer() - for (i,line) in enumerate(split(text, "\n")) + for (i, line) in enumerate(split(text, "\n")) println(io, @sprintf("%-4d: %s", i, line)) end write(out, take!(io)) @@ -13,8 +13,8 @@ Needed to match the lazy gl_convert exceptions. `Target`: targeted OpenGL type `x`: the variable that gets matched """ -matches_target(::Type{Target}, x::T) where {Target, T} = applicable(gl_convert, Target, x) || T <: Target # it can be either converted to Target, or it's already the target -matches_target(::Type{Target}, x::Observable{T}) where {Target, T} = applicable(gl_convert, Target, x) || T <: Target +matches_target(::Type{Target}, x::T) where {Target,T} = applicable(gl_convert, Target, x) || T <: Target # it can be either converted to Target, or it's already the target +matches_target(::Type{Target}, x::Observable{T}) where {Target,T} = applicable(gl_convert, Target, x) || T <: Target matches_target(::Function, x) = true matches_target(::Function, x::Nothing) = false @@ -45,13 +45,13 @@ macro gen_defaults!(dict, args) dictsym = gensym() return_expression = Expr(:block) push!(return_expression.args, :($dictsym = $dict)) # dict could also be an expression, so we need to asign it to a variable at the beginning - push!(return_expression.args, :(gl_convert_targets = get!($dictsym, :gl_convert_targets, Dict{Symbol, Any}()))) # exceptions for glconvert. - push!(return_expression.args, :(doc_strings = get!($dictsym, :doc_string, Dict{Symbol, Any}()))) # exceptions for glconvert. + push!(return_expression.args, :(gl_convert_targets = get!($dictsym, :gl_convert_targets, Dict{Symbol,Any}()))) # exceptions for glconvert. + push!(return_expression.args, :(doc_strings = get!($dictsym, :doc_string, Dict{Symbol,Any}()))) # exceptions for glconvert. # @gen_defaults can be used multiple times, so we need to reuse gl_convert_targets if already in here for (i, elem) in enumerate(tuple_list) opengl_convert_target = :() # is optional, so first is an empty expression - convert_target = :() # is optional, so first is an empty expression - doc_strings = :() + convert_target = :() # is optional, so first is an empty expression + doc_strings = :() if Meta.isexpr(elem, :(=)) key_name, value_expr = elem.args if isa(key_name, Expr) && key_name.head == :(::) # we need to convert to a julia type @@ -103,5 +103,5 @@ export @gen_defaults! makesignal(@nospecialize(v)) = convert(Observable, v) -@inline const_lift(f::Union{DataType, Type, Function}, inputs...) = lift(f, map(makesignal, inputs)...) +@inline const_lift(f::Union{DataType,Type,Function}, inputs...) = lift(f, map(makesignal, inputs)...) export const_lift diff --git a/GLMakie/src/GLMakie.jl b/GLMakie/src/GLMakie.jl index 91a2b127204..84c0b825a39 100644 --- a/GLMakie/src/GLMakie.jl +++ b/GLMakie/src/GLMakie.jl @@ -31,7 +31,7 @@ using Base.Iterators: repeated, drop using LinearAlgebra # re-export Makie, including deprecated names -for name in names(Makie, all=true) +for name in names(Makie, all = true) if Base.isexported(Makie, name) @eval using Makie: $(name) @eval export $(name) diff --git a/GLMakie/src/display.jl b/GLMakie/src/display.jl index c8d0aef1f72..45a3c0a37de 100644 --- a/GLMakie/src/display.jl +++ b/GLMakie/src/display.jl @@ -1,4 +1,4 @@ -function Base.display(screen::Screen, scene::Scene; connect=true) +function Base.display(screen::Screen, scene::Scene; connect = true) # So, the GLFW window events are not guarantee to fire # when we close a window, so we ensure this here! if !Makie.is_displayed(screen, scene) @@ -10,4 +10,4 @@ function Base.display(screen::Screen, scene::Scene; connect=true) return screen end -Makie.backend_showable(::Type{Screen}, ::Union{MIME"image/jpeg", MIME"image/png"}) = true +Makie.backend_showable(::Type{Screen}, ::Union{MIME"image/jpeg",MIME"image/png"}) = true diff --git a/GLMakie/src/drawing_primitives.jl b/GLMakie/src/drawing_primitives.jl index dc438ca4796..0dba818f9ab 100644 --- a/GLMakie/src/drawing_primitives.jl +++ b/GLMakie/src/drawing_primitives.jl @@ -4,7 +4,7 @@ using Makie: convert_arguments Makie.el32convert(x::GLAbstraction.Texture) = x Makie.convert_attribute(s::ShaderAbstractions.Sampler{RGBAf}, k::key"color") = s -function Makie.convert_attribute(s::ShaderAbstractions.Sampler{T, N}, k::key"color") where {T, N} +function Makie.convert_attribute(s::ShaderAbstractions.Sampler{T,N}, k::key"color") where {T,N} ShaderAbstractions.Sampler( el32convert(s.data), minfilter = s.minfilter, magfilter = s.magfilter, x_repeat = s.repeat[1], y_repeat = s.repeat[min(2, N)], z_repeat = s.repeat[min(3, N)], @@ -90,7 +90,7 @@ function cached_robj!(robj_func, screen, scene, x::AbstractPlot) )) end - gl_attributes = Dict{Symbol, Any}(map(filtered) do key_value + gl_attributes = Dict{Symbol,Any}(map(filtered) do key_value key, value = key_value gl_key = to_glvisualize_key(key) gl_value = lift_convert(key, value, x) @@ -151,7 +151,7 @@ function handle_view(array::SubArray, attributes) return A end -function handle_view(array::Observable{T}, attributes) where T <: SubArray +function handle_view(array::Observable{T}, attributes) where T<:SubArray A = lift(parent, array) indices = lift(index1D, array) attributes[:indices] = indices @@ -184,9 +184,9 @@ end pixel2world(scene, msize::AbstractVector) = pixel2world.(scene, msize) function handle_intensities!(attributes) - if haskey(attributes, :color) && attributes[:color][] isa AbstractVector{<: Number} + if haskey(attributes, :color) && attributes[:color][] isa AbstractVector{<:Number} c = pop!(attributes, :color) - attributes[:intensity] = lift(x-> convert(Vector{Float32}, x), c) + attributes[:intensity] = lift(x -> convert(Vector{Float32}, x), c) else delete!(attributes, :intensity) delete!(attributes, :color_map) @@ -194,7 +194,7 @@ function handle_intensities!(attributes) end end -function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Union{Scatter, MeshScatter})) +function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Union{Scatter,MeshScatter})) return cached_robj!(screen, scene, x) do gl_attributes # signals not supported for shading yet gl_attributes[:shading] = to_value(get(gl_attributes, :shading, true)) @@ -213,10 +213,10 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Union{Scatte # fast pixel does its own setup if !(marker[] isa FastPixel) connect_camera!(gl_attributes, cam, mspace) - gl_attributes[:billboard] = map(rot-> isa(rot, Billboard), x.rotations) + gl_attributes[:billboard] = map(rot -> isa(rot, Billboard), x.rotations) atlas = gl_texture_atlas() isnothing(gl_attributes[:distancefield][]) && delete!(gl_attributes, :distancefield) - shape = lift(m-> Cint(Makie.marker_to_sdf_shape(m)), marker) + shape = lift(m -> Cint(Makie.marker_to_sdf_shape(m)), marker) gl_attributes[:shape] = shape get!(gl_attributes, :distancefield) do if shape[] === Cint(DISTANCEFIELD) @@ -244,7 +244,7 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Union{Scatte filter!(gl_attributes) do (k, v,) k in (:color_map, :color, :color_norm, :scale, :model, :projectionview, :visible) end - if !(gl_attributes[:color][] isa AbstractVector{<: Number}) + if !(gl_attributes[:color][] isa AbstractVector{<:Number}) delete!(gl_attributes, :color_norm) delete!(gl_attributes, :color_map) end @@ -263,7 +263,7 @@ end function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Lines)) return cached_robj!(screen, scene, x) do gl_attributes linestyle = pop!(gl_attributes, :linestyle) - data = Dict{Symbol, Any}(gl_attributes) + data = Dict{Symbol,Any}(gl_attributes) ls = to_value(linestyle) if isnothing(ls) data[:pattern] = ls @@ -283,7 +283,7 @@ end function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::LineSegments)) return cached_robj!(screen, scene, x) do gl_attributes linestyle = pop!(gl_attributes, :linestyle) - data = Dict{Symbol, Any}(gl_attributes) + data = Dict{Symbol,Any}(gl_attributes) ls = to_value(linestyle) if isnothing(ls) data[:pattern] = ls @@ -294,7 +294,7 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::LineSegments space = get(gl_attributes, :space, :data) # needs to happen before connect_camera! call positions = handle_view(x.converted[1], data) positions = apply_transform(transform_func_obs(x), positions, space) - if haskey(data, :color) && data[:color][] isa AbstractVector{<: Number} + if haskey(data, :color) && data[:color][] isa AbstractVector{<:Number} c = pop!(data, :color) data[:color] = el32convert(c) else @@ -308,12 +308,12 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::LineSegments end function draw_atomic(screen::Screen, scene::Scene, - x::Text{<:Tuple{<:Union{<:Makie.GlyphCollection, <:AbstractVector{<:Makie.GlyphCollection}}}}) + x::Text{<:Tuple{<:Union{<:Makie.GlyphCollection,<:AbstractVector{<:Makie.GlyphCollection}}}}) return cached_robj!(screen, scene, x) do gl_attributes glyphcollection = x[1] - transfunc = Makie.transform_func_obs(scene) + transfunc = Makie.transform_func_obs(scene) pos = gl_attributes[:position] space = get(gl_attributes, :space, Observable(:data)) # needs to happen before connect_camera! call markerspace = gl_attributes[:markerspace] @@ -418,7 +418,7 @@ function draw_atomic(screen::Screen, scene::Scene, x::Heatmap) gl_attributes[:position_y] = Texture(ypos, minfilter = :nearest) # number of planes used to render the heatmap gl_attributes[:instances] = map(xpos, ypos) do x, y - (length(x)-1) * (length(y)-1) + (length(x) - 1) * (length(y) - 1) end interp = to_value(pop!(gl_attributes, :interpolate)) interp = interp ? :linear : :nearest @@ -441,13 +441,13 @@ function draw_atomic(screen::Screen, scene::Scene, x::Image) r = to_range(x, y) x, y = minimum(r[1]), minimum(r[2]) xmax, ymax = maximum(r[1]), maximum(r[2]) - rect = Rect2f(x, y, xmax - x, ymax - y) + rect = Rect2f(x, y, xmax - x, ymax - y) points = decompose(Point2f, rect) faces = decompose(GLTriangleFace, rect) uv = map(decompose_uv(rect)) do uv return 1f0 .- Vec2f(uv[2], uv[1]) end - return GeometryBasics.Mesh(meta(points; uv=uv), faces) + return GeometryBasics.Mesh(meta(points; uv = uv), faces) end gl_attributes[:color] = x[3] gl_attributes[:shading] = false @@ -464,7 +464,7 @@ function update_positions(mesh::GeometryBasics.Mesh, positions) return GeometryBasics.Mesh(meta(positions; attr...), faces(mesh)) end -function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, space=:data) +function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, space = :data) # signals not supported for shading yet gl_attributes[:shading] = to_value(pop!(gl_attributes, :shading)) color = pop!(gl_attributes, :color) @@ -476,16 +476,16 @@ function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, space=:data) delete!(gl_attributes, :color_norm) elseif to_value(color) isa Makie.AbstractPattern img = lift(x -> el32convert(Makie.to_image(x)), color) - gl_attributes[:image] = ShaderAbstractions.Sampler(img, x_repeat=:repeat, minfilter=:nearest) + gl_attributes[:image] = ShaderAbstractions.Sampler(img, x_repeat = :repeat, minfilter = :nearest) get!(gl_attributes, :fetch_pixel, true) elseif to_value(color) isa AbstractMatrix{<:Colorant} gl_attributes[:image] = Texture(const_lift(el32convert, color), minfilter = interp) delete!(gl_attributes, :color_map) delete!(gl_attributes, :color_norm) - elseif to_value(color) isa AbstractMatrix{<: Number} + elseif to_value(color) isa AbstractMatrix{<:Number} gl_attributes[:image] = Texture(const_lift(el32convert, color), minfilter = interp) gl_attributes[:color] = nothing - elseif to_value(color) isa AbstractVector{<: Union{Number, Colorant}} + elseif to_value(color) isa AbstractVector{<:Union{Number,Colorant}} gl_attributes[:vertex_color] = lift(el32convert, color) else error("Unsupported color type: $(typeof(to_value(color)))") @@ -514,16 +514,16 @@ function draw_atomic(screen::Screen, scene::Scene, x::Surface) img = nothing # signals not supported for shading yet # We automatically insert x[3] into the color channel, so if it's equal we don't need to do anything - if isa(to_value(color), AbstractMatrix{<: Number}) && to_value(color) !== to_value(x[3]) + if isa(to_value(color), AbstractMatrix{<:Number}) && to_value(color) !== to_value(x[3]) img = el32convert(color) elseif to_value(color) isa Makie.AbstractPattern pattern_img = lift(x -> el32convert(Makie.to_image(x)), color) - img = ShaderAbstractions.Sampler(pattern_img, x_repeat=:repeat, minfilter=:nearest) + img = ShaderAbstractions.Sampler(pattern_img, x_repeat = :repeat, minfilter = :nearest) haskey(gl_attributes, :fetch_pixel) || (gl_attributes[:fetch_pixel] = true) gl_attributes[:color_map] = nothing gl_attributes[:color] = nothing gl_attributes[:color_norm] = nothing - elseif isa(to_value(color), AbstractMatrix{<: Colorant}) + elseif isa(to_value(color), AbstractMatrix{<:Colorant}) img = color gl_attributes[:color_map] = nothing gl_attributes[:color] = nothing @@ -539,7 +539,7 @@ function draw_atomic(screen::Screen, scene::Scene, x::Surface) @assert to_value(x[3]) isa AbstractMatrix types = map(v -> typeof(to_value(v)), x[1:2]) - if all(T -> T <: Union{AbstractMatrix, AbstractVector}, types) + if all(T -> T <: Union{AbstractMatrix,AbstractVector}, types) t = Makie.transform_func_obs(scene) mat = x[3] xypos = map(t, x[1], x[2], space) do t, x, y, space @@ -560,7 +560,7 @@ function draw_atomic(screen::Screen, scene::Scene, x::Surface) xpos = map(first, xypos) ypos = map(last, xypos) args = map((xpos, ypos, mat)) do arg - Texture(map(x-> convert(Array, el32convert(x)), arg); minfilter=:linear) + Texture(map(x -> convert(Array, el32convert(x)), arg); minfilter = :linear) end if isnothing(img) gl_attributes[:image] = args[3] @@ -568,7 +568,7 @@ function draw_atomic(screen::Screen, scene::Scene, x::Surface) return draw_surface(screen, args, gl_attributes) else gl_attributes[:ranges] = to_range.(to_value.(x[1:2])) - z_data = Texture(el32convert(x[3]); minfilter=:linear) + z_data = Texture(el32convert(x[3]); minfilter = :linear) if isnothing(img) gl_attributes[:image] = z_data end diff --git a/GLMakie/src/events.jl b/GLMakie/src/events.jl index fced12ae9af..8de8b26f4d7 100644 --- a/GLMakie/src/events.jl +++ b/GLMakie/src/events.jl @@ -44,7 +44,7 @@ end struct WindowAreaUpdater window::GLFW.Window dpi::Observable{Float64} - area::Observable{GeometryBasics.HyperRectangle{2, Int64}} + area::Observable{GeometryBasics.HyperRectangle{2,Int64}} end function (x::WindowAreaUpdater)(::Nothing) @@ -197,7 +197,7 @@ end struct MousePositionUpdater window::GLFW.Window - mouseposition::Observable{Tuple{Float64, Float64}} + mouseposition::Observable{Tuple{Float64,Float64}} hasfocus::Observable{Bool} end diff --git a/GLMakie/src/gl_backend.jl b/GLMakie/src/gl_backend.jl index 1fb7a003f02..de0066c4ea5 100644 --- a/GLMakie/src/gl_backend.jl +++ b/GLMakie/src/gl_backend.jl @@ -14,7 +14,7 @@ include("GLAbstraction/GLAbstraction.jl") using .GLAbstraction -const atlas_texture_cache = Dict{Any, Tuple{Texture{Float16, 2}, Function}}() +const atlas_texture_cache = Dict{Any,Tuple{Texture{Float16,2},Function}}() function get_texture!(atlas::Makie.TextureAtlas) current_ctx = GLAbstraction.current_context() @@ -34,15 +34,15 @@ function get_texture!(atlas::Makie.TextureAtlas) tex, func = get!(atlas_texture_cache, (pointer(atlas.data), current_ctx)) do tex = Texture( - atlas.data, - minfilter = :linear, - magfilter = :linear, - # TODO: Consider alternatives to using the builtin anisotropic - # samplers for signed distance fields; the anisotropic - # filtering should happen *after* the SDF thresholding, but - # with the builtin sampler it happens before. - anisotropic = 16f0, - mipmap = true + atlas.data, + minfilter = :linear, + magfilter = :linear, + # TODO: Consider alternatives to using the builtin anisotropic + # samplers for signed distance fields; the anisotropic + # filtering should happen *after* the SDF thresholding, but + # with the builtin sampler it happens before. + anisotropic = 16f0, + mipmap = true ) # update the texture, whenever a new font is added to the atlas function callback(distance_field, rectangle) diff --git a/GLMakie/src/glshaders/image_like.jl b/GLMakie/src/glshaders/image_like.jl index ec21243a53f..de02a1c1472 100644 --- a/GLMakie/src/glshaders/image_like.jl +++ b/GLMakie/src/glshaders/image_like.jl @@ -19,12 +19,16 @@ function vol_depth_main(enable) vec4 frag_coord = projectionview * model * vec4(pos, 1); depth = min(depth, frag_coord.z / frag_coord.w); """ - else "" end + else + "" + end end function vol_depth_write(enable) if enable "gl_FragDepth = depth == 100000.0 ? gl_FragDepth : 0.5 * depth + 0.5;" - else "" end + else + "" + end end @nospecialize @@ -32,7 +36,7 @@ end A matrix of Intensities will result in a contourf kind of plot """ function draw_heatmap(screen, main, data::Dict) - primitive = triangle_mesh(Rect2(0f0,0f0,1f0,1f0)) + primitive = triangle_mesh(Rect2(0f0, 0f0, 1f0, 1f0)) to_opengl_mesh!(data, primitive) @gen_defaults! data begin intensity = main => Texture @@ -43,7 +47,7 @@ function draw_heatmap(screen, main, data::Dict) color_norm = nothing stroke_width::Float32 = 0.0f0 levels::Float32 = 0f0 - stroke_color = RGBA{Float32}(0,0,0,0) + stroke_color = RGBA{Float32}(0, 0, 0, 0) transparency = false shader = GLVisualizeShader( screen, @@ -79,9 +83,9 @@ function draw_volume(screen, main::VolumeTypes, data::Dict) screen, "fragment_output.frag", "util.vert", "volume.vert", "volume.frag", view = Dict( - "depth_init" => vol_depth_init(to_value(enable_depth)), - "depth_default" => vol_depth_default(to_value(enable_depth)), - "depth_main" => vol_depth_main(to_value(enable_depth)), + "depth_init" => vol_depth_init(to_value(enable_depth)), + "depth_default" => vol_depth_default(to_value(enable_depth)), + "depth_main" => vol_depth_main(to_value(enable_depth)), "depth_write" => vol_depth_write(to_value(enable_depth)), "buffers" => output_buffers(screen, to_value(transparency)), "buffer_writes" => output_buffer_writes(screen, to_value(transparency)) diff --git a/GLMakie/src/glshaders/lines.jl b/GLMakie/src/glshaders/lines.jl index 323d21e3d01..f8945c30ab2 100644 --- a/GLMakie/src/glshaders/lines.jl +++ b/GLMakie/src/glshaders/lines.jl @@ -1,11 +1,11 @@ function sumlengths(points) T = eltype(points[1]) result = zeros(T, length(points)) - for i=1:length(points) - i0 = max(i-1,1) + for i in 1:length(points) + i0 = max(i - 1, 1) p1, p2 = points[i0], points[i] if !(any(map(isnan, p1)) || any(map(isnan, p2))) - result[i] = result[i0] + norm(p1-p2) + result[i] = result[i0] + norm(p1 - p2) else result[i] = result[i0] end @@ -29,14 +29,14 @@ function intensity_convert_tex(intensity::VecOrSignal{T}, verts) where T end end #TODO NaNMath.min/max? -dist(a, b) = abs(a-b) +dist(a, b) = abs(a - b) mindist(x, a, b) = min(dist(a, x), dist(b, x)) function gappy(x, ps) n = length(ps) x <= first(ps) && return first(ps) - x - for j=1:(n-1) + for j in 1:(n - 1) p0 = ps[j] - p1 = ps[min(j+1, n)] + p1 = ps[min(j + 1, n)] if p0 <= x && p1 >= x return mindist(x, p0, p1) * (isodd(j) ? 1 : -1) end @@ -44,11 +44,11 @@ function gappy(x, ps) return last(ps) - x end function ticks(points, resolution) - Float16[gappy(x, points) for x = range(first(points), stop=last(points), length=resolution)] + Float16[gappy(x, points) for x in range(first(points), stop = last(points), length = resolution)] end @nospecialize -function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data::Dict) where T<:Point +function draw_lines(screen, position::Union{VectorTypes{T},MatTypes{T}}, data::Dict) where T<:Point p_vec = if isa(position, GPUArray) position else @@ -56,24 +56,24 @@ function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data:: end @gen_defaults! data begin - total_length::Int32 = const_lift(x-> Int32(length(x)), position) - vertex = p_vec => GLBuffer - intensity = nothing - color_map = nothing => Texture - color_norm = nothing - color = (color_map == nothing ? default(RGBA, s) : nothing) => GLBuffer - thickness::Float32 = 2f0 - pattern = nothing - fxaa = false + total_length::Int32 = const_lift(x -> Int32(length(x)), position) + vertex = p_vec => GLBuffer + intensity = nothing + color_map = nothing => Texture + color_norm = nothing + color = (color_map == nothing ? default(RGBA, s) : nothing) => GLBuffer + thickness::Float32 = 2f0 + pattern = nothing + fxaa = false # Duplicate the vertex indices on the ends of the line, as our geometry # shader in `layout(lines_adjacency)` mode requires each rendered # segment to have neighbouring vertices. - indices = const_lift(p_vec) do p + indices = const_lift(p_vec) do p len0 = length(p) - 1 return isempty(p) ? Cuint[] : Cuint[0; 0:len0; len0] end => to_index_buffer transparency = false - shader = GLVisualizeShader( + shader = GLVisualizeShader( screen, "fragment_output.frag", "util.vert", "lines.vert", "lines.geom", "lines.frag", view = Dict( @@ -81,9 +81,9 @@ function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data:: "buffer_writes" => output_buffer_writes(screen, to_value(transparency)) ) ) - gl_primitive = GL_LINE_STRIP_ADJACENCY - valid_vertex = const_lift(p_vec) do points - map(p-> Float32(all(isfinite, p)), points) + gl_primitive = GL_LINE_STRIP_ADJACENCY + valid_vertex = const_lift(p_vec) do points + map(p -> Float32(all(isfinite, p)), points) end => GLBuffer end if pattern !== nothing @@ -96,7 +96,7 @@ function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data:: end @gen_defaults! data begin pattern_length = Float32(last(pattern)) - lastlen = const_lift(sumlengths, p_vec) => GLBuffer + lastlen = const_lift(sumlengths, p_vec) => GLBuffer maxlength = const_lift(last, lastlen) end end @@ -104,20 +104,20 @@ function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data:: return assemble_shader(data) end -function draw_linesegments(screen, positions::VectorTypes{T}, data::Dict) where T <: Point +function draw_linesegments(screen, positions::VectorTypes{T}, data::Dict) where T<:Point @gen_defaults! data begin - vertex = positions => GLBuffer - color = default(RGBA, s, 1) => GLBuffer - color_map = nothing => Texture - color_norm = nothing - thickness = 2f0 => GLBuffer - shape = RECTANGLE - pattern = nothing - fxaa = false - indices = const_lift(length, positions) => to_index_buffer + vertex = positions => GLBuffer + color = default(RGBA, s, 1) => GLBuffer + color_map = nothing => Texture + color_norm = nothing + thickness = 2f0 => GLBuffer + shape = RECTANGLE + pattern = nothing + fxaa = false + indices = const_lift(length, positions) => to_index_buffer # TODO update boundingbox transparency = false - shader = GLVisualizeShader( + shader = GLVisualizeShader( screen, "fragment_output.frag", "util.vert", "line_segment.vert", "line_segment.geom", "lines.frag", view = Dict( diff --git a/GLMakie/src/glshaders/mesh.jl b/GLMakie/src/glshaders/mesh.jl index 1cacd125aea..a5a787dcaeb 100644 --- a/GLMakie/src/glshaders/mesh.jl +++ b/GLMakie/src/glshaders/mesh.jl @@ -1,10 +1,10 @@ -function to_opengl_mesh!(result, mesh_obs::TOrSignal{<: GeometryBasics.Mesh}) +function to_opengl_mesh!(result, mesh_obs::TOrSignal{<:GeometryBasics.Mesh}) m_attr = map(convert(Observable, mesh_obs)) do m return (m, GeometryBasics.attributes(m)) end - result[:faces] = indexbuffer(map(((m,_),)-> faces(m), m_attr)) - result[:vertices] = GLBuffer(map(((m,_),)-> decompose(Point, m), m_attr)) + result[:faces] = indexbuffer(map(((m, _),) -> faces(m), m_attr)) + result[:vertices] = GLBuffer(map(((m, _),) -> decompose(Point, m), m_attr)) attribs = m_attr[][2] @@ -12,7 +12,7 @@ function to_opengl_mesh!(result, mesh_obs::TOrSignal{<: GeometryBasics.Mesh}) if haskey(attribs, name) val = attribs[name] if mesh_obs isa Observable - val = map(((m, a),)-> a[name], m_attr) + val = map(((m, a),) -> a[name], m_attr) end if val[] isa AbstractVector result[target] = GLBuffer(map(metafree, val)) diff --git a/GLMakie/src/glshaders/particles.jl b/GLMakie/src/glshaders/particles.jl index 3ab7d85661f..91e989d20af 100644 --- a/GLMakie/src/glshaders/particles.jl +++ b/GLMakie/src/glshaders/particles.jl @@ -1,10 +1,10 @@ using Makie: RectanglePacker -function to_meshcolor(color::TOrSignal{Vector{T}}) where T <: Colorant +function to_meshcolor(color::TOrSignal{Vector{T}}) where T<:Colorant TextureBuffer(color) end -function to_meshcolor(color::TOrSignal{Matrix{T}}) where T <: Colorant +function to_meshcolor(color::TOrSignal{Matrix{T}}) where T<:Colorant Texture(color) end function to_meshcolor(color) @@ -21,11 +21,11 @@ function vec2quaternion(rotation::StaticVector{3}) end vec2quaternion(rotation::Vec4f) = rotation -vec2quaternion(rotation::VectorTypes) = const_lift(x-> vec2quaternion.(x), rotation) +vec2quaternion(rotation::VectorTypes) = const_lift(x -> vec2quaternion.(x), rotation) vec2quaternion(rotation::Observable) = lift(vec2quaternion, rotation) -vec2quaternion(rotation::Makie.Quaternion)= Vec4f(rotation.data) -vec2quaternion(rotation)= vec2quaternion(to_rotation(rotation)) -GLAbstraction.gl_convert(rotation::Makie.Quaternion)= Vec4f(rotation.data) +vec2quaternion(rotation::Makie.Quaternion) = Vec4f(rotation.data) +vec2quaternion(rotation) = vec2quaternion(to_rotation(rotation)) +GLAbstraction.gl_convert(rotation::Makie.Quaternion) = Vec4f(rotation.data) to_pointsize(x::Number) = Float32(x) to_pointsize(x) = Float32(x[1]) struct PointSizeRender @@ -92,13 +92,13 @@ This is supposed to be the fastest way of displaying particles! """ function draw_pixel_scatter(screen, position::VectorTypes, data::Dict) @gen_defaults! data begin - vertex = position => GLBuffer - color_map = nothing => Texture - color = (color_map === nothing ? default(RGBA{Float32}, s) : nothing) => GLBuffer - color_norm = nothing - scale = 2f0 + vertex = position => GLBuffer + color_map = nothing => Texture + color = (color_map === nothing ? default(RGBA{Float32}, s) : nothing) => GLBuffer + color_norm = nothing + scale = 2f0 transparency = false - shader = GLVisualizeShader( + shader = GLVisualizeShader( screen, "fragment_output.frag", "dots.vert", "dots.frag", view = Dict( @@ -113,29 +113,29 @@ function draw_pixel_scatter(screen, position::VectorTypes, data::Dict) end function draw_scatter( - screen, p::Tuple{TOrSignal{Matrix{C}}, VectorTypes{P}}, data::Dict - ) where {C <: Colorant, P <: Point} + screen, p::Tuple{TOrSignal{Matrix{C}},VectorTypes{P}}, data::Dict +) where {C<:Colorant,P<:Point} data[:image] = p[1] # we don't want this to be overwritten by user @gen_defaults! data begin - scale = lift(x-> Vec2f(size(x)), p[1]) + scale = lift(x -> Vec2f(size(x)), p[1]) offset = Vec2f(0) end draw_scatter(screen, (RECTANGLE, p[2]), data) end function draw_scatter( - screen, p::Tuple{VectorTypes{Matrix{C}}, VectorTypes{P}}, data::Dict - ) where {C <: Colorant, P <: Point} + screen, p::Tuple{VectorTypes{Matrix{C}},VectorTypes{P}}, data::Dict +) where {C<:Colorant,P<:Point} images = map(el32convert, to_value(p[1])) isempty(images) && error("Can not display empty vector of images as primitive") sizes = map(size, images) - if !all(x-> x == sizes[1], sizes) # if differently sized + if !all(x -> x == sizes[1], sizes) # if differently sized # create texture atlas - maxdims = sum(map(Vec{2, Int}, sizes)) - rectangles = map(x->Rect2(0, 0, x...), sizes) + maxdims = sum(map(Vec{2,Int}, sizes)) + rectangles = map(x -> Rect2(0, 0, x...), sizes) rpack = RectanglePacker(Rect2(0, 0, maxdims...)) uv_coordinates = [push!(rpack, rect).area for rect in rectangles] - max_xy = mapreduce(maximum, (a,b)-> max.(a, b), uv_coordinates) + max_xy = mapreduce(maximum, (a, b) -> max.(a, b), uv_coordinates) texture_atlas = Texture(eltype(images[1]), (max_xy...,)) for (area, img) in zip(uv_coordinates, images) texture_atlas[area] = img #transfer to texture atlas @@ -166,34 +166,34 @@ function draw_scatter(screen, (marker, position), data) delete!(data, :rotation) @gen_defaults! data begin - shape = Cint(0) - position = position => GLBuffer - marker_offset = Vec3f(0) => GLBuffer; - scale = Vec2f(0) => GLBuffer - rotation = rot => GLBuffer - image = nothing => Texture + shape = Cint(0) + position = position => GLBuffer + marker_offset = Vec3f(0) => GLBuffer + scale = Vec2f(0) => GLBuffer + rotation = rot => GLBuffer + image = nothing => Texture end @gen_defaults! data begin - quad_offset = Vec2f(0) => GLBuffer - intensity = nothing => GLBuffer - color_map = nothing => Texture - color_norm = nothing - color = nothing => GLBuffer - - glow_color = RGBA{Float32}(0,0,0,0) => GLBuffer - stroke_color = RGBA{Float32}(0,0,0,0) => GLBuffer - stroke_width = 0f0 - glow_width = 0f0 + quad_offset = Vec2f(0) => GLBuffer + intensity = nothing => GLBuffer + color_map = nothing => Texture + color_norm = nothing + color = nothing => GLBuffer + + glow_color = RGBA{Float32}(0, 0, 0, 0) => GLBuffer + stroke_color = RGBA{Float32}(0, 0, 0, 0) => GLBuffer + stroke_width = 0f0 + glow_width = 0f0 uv_offset_width = Vec4f(0) => GLBuffer - distancefield = nothing => Texture - indices = const_lift(length, position) => to_index_buffer + distancefield = nothing => Texture + indices = const_lift(length, position) => to_index_buffer # rotation and billboard don't go along - billboard = rotation == Vec4f(0,0,0,1) => "if `billboard` == true, particles will always face camera" - fxaa = false - transparency = false - shader = GLVisualizeShader( + billboard = rotation == Vec4f(0, 0, 0, 1) => "if `billboard` == true, particles will always face camera" + fxaa = false + transparency = false + shader = GLVisualizeShader( screen, "fragment_output.frag", "util.vert", "sprites.geom", "sprites.vert", "distance_shape.frag", diff --git a/GLMakie/src/glshaders/surface.jl b/GLMakie/src/glshaders/surface.jl index c4d5961fc1a..d4ccd8abb63 100644 --- a/GLMakie/src/glshaders/surface.jl +++ b/GLMakie/src/glshaders/surface.jl @@ -1,6 +1,6 @@ function position_calc(x...) - _position_calc(Iterators.filter(x->!isa(x, Nothing), x)...) + _position_calc(Iterators.filter(x -> !isa(x, Nothing), x)...) end function normal_calc(x::Bool, invert_normals::Bool = false) @@ -27,8 +27,8 @@ function light_calc(x::Bool) end function _position_calc( - position_x::MatTypes{T}, position_y::MatTypes{T}, position_z::MatTypes{T}, target::Type{Texture} - ) where T<:AbstractFloat + position_x::MatTypes{T}, position_y::MatTypes{T}, position_z::MatTypes{T}, target::Type{Texture} +) where T<:AbstractFloat """ int index1D = index + offseti.x + offseti.y * dims.x + (index/(dims.x-1)); ivec2 index2D = ind2sub(dims, index1D); @@ -42,9 +42,9 @@ function _position_calc( end function _position_calc( - position_x::VectorTypes{T}, position_y::VectorTypes{T}, position_z::MatTypes{T}, - target::Type{Texture} - ) where T<:AbstractFloat + position_x::VectorTypes{T}, position_y::VectorTypes{T}, position_z::MatTypes{T}, + target::Type{Texture} +) where T<:AbstractFloat """ int index1D = index + offseti.x + offseti.y * dims.x + (index/(dims.x-1)); ivec2 index2D = ind2sub(dims, index1D); @@ -58,23 +58,23 @@ function _position_calc( end function _position_calc( - position_xyz::VectorTypes{T}, target::Type{TextureBuffer} - ) where T <: StaticVector + position_xyz::VectorTypes{T}, target::Type{TextureBuffer} +) where T<:StaticVector "pos = texelFetch(position, index).xyz;" end function _position_calc( - position_xyz::VectorTypes{T}, target::Type{GLBuffer} - ) where T <: StaticVector + position_xyz::VectorTypes{T}, target::Type{GLBuffer} +) where T<:StaticVector len = length(T) - filler = join(ntuple(x->0, 3-len), ", ") + filler = join(ntuple(x -> 0, 3 - len), ", ") needs_comma = len != 3 ? ", " : "" "pos = vec3(position $needs_comma $filler);" end function _position_calc( - grid::Grid{2}, position_z::MatTypes{T}, target::Type{Texture} - ) where T<:AbstractFloat + grid::Grid{2}, position_z::MatTypes{T}, target::Type{Texture} +) where T<:AbstractFloat """ int index1D = index + offseti.x + offseti.y * dims.x + (index/(dims.x-1)); ivec2 index2D = ind2sub(dims, index1D); @@ -86,7 +86,7 @@ end @nospecialize # surface(::Matrix, ::Matrix, ::Matrix) -function draw_surface(screen, main::Tuple{MatTypes{T}, MatTypes{T}, MatTypes{T}}, data::Dict) where T <: AbstractFloat +function draw_surface(screen, main::Tuple{MatTypes{T},MatTypes{T},MatTypes{T}}, data::Dict) where T<:AbstractFloat @gen_defaults! data begin position_x = main[1] => (Texture, "x position, must be a `Matrix{Float}`") position_y = main[2] => (Texture, "y position, must be a `Matrix{Float}`") @@ -97,7 +97,7 @@ function draw_surface(screen, main::Tuple{MatTypes{T}, MatTypes{T}, MatTypes{T}} end # surface(Vector or Range, Vector or Range, ::Matrix) -function draw_surface(screen, main::Tuple{VectorTypes{T}, VectorTypes{T}, MatTypes{T}}, data::Dict) where T <: AbstractFloat +function draw_surface(screen, main::Tuple{VectorTypes{T},VectorTypes{T},MatTypes{T}}, data::Dict) where T<:AbstractFloat @gen_defaults! data begin position_x = main[1] => (Texture, "x position, must be a `Vector{Float}`") position_y = main[2] => (Texture, "y position, must be a `Vector{Float}`") @@ -108,7 +108,7 @@ function draw_surface(screen, main::Tuple{VectorTypes{T}, VectorTypes{T}, MatTyp end function draw_surface(screen, main, data::Dict) - primitive = triangle_mesh(Rect2(0f0,0f0,1f0,1f0)) + primitive = triangle_mesh(Rect2(0f0, 0f0, 1f0, 1f0)) to_opengl_mesh!(data, primitive) @gen_defaults! data begin scale = nothing @@ -134,7 +134,7 @@ function draw_surface(screen, main, data::Dict) lowclip = RGBAf(0, 0, 0, 0) uv_scale = Vec2f(1) - instances = const_lift(x->(size(x,1)-1) * (size(x,2)-1), main) => "number of planes used to render the surface" + instances = const_lift(x -> (size(x, 1) - 1) * (size(x, 2) - 1), main) => "number of planes used to render the surface" transparency = false shader = GLVisualizeShader( screen, diff --git a/GLMakie/src/glshaders/visualize_interface.jl b/GLMakie/src/glshaders/visualize_interface.jl index 1633084e6b6..8064a806fa5 100644 --- a/GLMakie/src/glshaders/visualize_interface.jl +++ b/GLMakie/src/glshaders/visualize_interface.jl @@ -1,6 +1,6 @@ @enum CubeSides TOP BOTTOM FRONT BACK RIGHT LEFT -struct Grid{N,T <: AbstractRange} +struct Grid{N,T<:AbstractRange} dims::NTuple{N,T} end Base.ndims(::Grid{N,T}) where {N,T} = N @@ -11,7 +11,7 @@ function Grid(a::Array{T,N}) where {N,T} smax = maximum(s) s = s ./ smax Grid(ntuple(Val{N}) do i - range(0, stop=s[i], length=size(a, i)) + range(0, stop = s[i], length = size(a, i)) end) end @@ -24,12 +24,12 @@ and all kind of range types. The constructor will make sure that all ranges matc the size of the dimension of the array `a`. """ function Grid(a::AbstractArray{T,N}, ranges::Tuple) where {T,N} - length(ranges) = ! N && throw(ArgumentError( + length(ranges) = !N && throw(ArgumentError( "You need to supply a range for every dimension of the array. Given: $ranges given Array: $(typeof(a))" )) Grid(ntuple(Val(N)) do i - range(first(ranges[i]), stop=last(ranges[i]), length=size(a, i)) + range(first(ranges[i]), stop = last(ranges[i]), length = size(a, i)) end) end @@ -42,7 +42,7 @@ function Base.getindex(p::Grid{N,T}, i) where {N,T} end) end -Base.iterate(g::Grid, i=1) = i <= length(g) ? (g[i], i + 1) : nothing +Base.iterate(g::Grid, i = 1) = i <= length(g) ? (g[i], i + 1) : nothing GLAbstraction.isa_gl_struct(x::Grid) = true GLAbstraction.toglsltype_string(t::Grid{N,T}) where {N,T} = "uniform Grid$(N)D" @@ -69,15 +69,15 @@ struct GLVisualizeShader <: AbstractLazyShader paths::Tuple kw_args::Dict{Symbol,Any} function GLVisualizeShader( - screen::Screen, paths::String...; - view = Dict{String,String}(), kw_args... - ) + screen::Screen, paths::String...; + view = Dict{String,String}(), kw_args... + ) # TODO properly check what extensions are available @static if !Sys.isapple() view["GLSL_EXTENSIONS"] = "#extension GL_ARB_conservative_depth: enable" view["SUPPORTED_EXTENSIONS"] = "#define DEPTH_LAYOUT" end - args = Dict{Symbol, Any}(kw_args) + args = Dict{Symbol,Any}(kw_args) args[:view] = view args[:fragdatalocation] = [(0, "fragment_color"), (1, "fragment_groupid")] new(screen, map(x -> loadshader(x), paths), args) @@ -100,7 +100,7 @@ function assemble_shader(data) pre = if !isnothing(pre_fun) _pre_fun = GLAbstraction.StandardPrerender(transp, overdraw) - ()->(_pre_fun(); pre_fun()) + () -> (_pre_fun(); pre_fun()) else GLAbstraction.StandardPrerender(transp, overdraw) end @@ -131,15 +131,15 @@ to_index_buffer(x::TOrSignal{UnitRange{Int}}) = x """ For integers, we transform it to 0 based indices """ -to_index_buffer(x::AbstractVector{I}) where {I <: Integer} = indexbuffer(Cuint.(x .- 1)) -function to_index_buffer(x::Observable{<: AbstractVector{I}}) where I <: Integer +to_index_buffer(x::AbstractVector{I}) where {I<:Integer} = indexbuffer(Cuint.(x .- 1)) +function to_index_buffer(x::Observable{<:AbstractVector{I}}) where I<:Integer indexbuffer(lift(x -> Cuint.(x .- 1), x)) end """ If already GLuint, we assume its 0 based (bad heuristic, should better be solved with some Index type) """ -function to_index_buffer(x::VectorTypes{I}) where I <: Union{GLuint,LineFace{GLIndex}} +function to_index_buffer(x::VectorTypes{I}) where I<:Union{GLuint,LineFace{GLIndex}} indexbuffer(x) end diff --git a/GLMakie/src/glwindow.jl b/GLMakie/src/glwindow.jl index d643f609c5b..72491e5d692 100644 --- a/GLMakie/src/glwindow.jl +++ b/GLMakie/src/glwindow.jl @@ -3,7 +3,7 @@ Selection of random objects on the screen is realized by rendering an object id + plus an arbitrary index into the framebuffer. The index can be used for e.g. instanced geometries. """ -struct SelectionID{T <: Integer} +struct SelectionID{T<:Integer} id::T index::T end @@ -11,11 +11,11 @@ Base.convert(::Type{SelectionID{T}}, s::SelectionID) where T = SelectionID{T}(T( Base.zero(::Type{GLMakie.SelectionID{T}}) where T = SelectionID{T}(T(0), T(0)) mutable struct GLFramebuffer - resolution::Observable{NTuple{2, Int}} + resolution::Observable{NTuple{2,Int}} id::GLuint - buffer_ids::Dict{Symbol, GLuint} - buffers::Dict{Symbol, Texture} + buffer_ids::Dict{Symbol,GLuint} + buffers::Dict{Symbol,Texture} render_buffer_ids::Vector{GLuint} end @@ -29,12 +29,12 @@ function getfallback(fb::GLFramebuffer, key::Symbol, fallback_key::Symbol) end -function attach_framebuffer(t::Texture{T, 2}, attachment) where T +function attach_framebuffer(t::Texture{T,2}, attachment) where T glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, t.id, 0) end # attach texture as color attachment with automatic id picking -function attach_colorbuffer!(fb::GLFramebuffer, key::Symbol, t::Texture{T, 2}) where T +function attach_colorbuffer!(fb::GLFramebuffer, key::Symbol, t::Texture{T,2}) where T if haskey(fb.buffer_ids, key) || haskey(fb.buffers, key) error("Key $key already exists.") end @@ -56,7 +56,7 @@ function attach_colorbuffer!(fb::GLFramebuffer, key::Symbol, t::Texture{T, 2}) w return next_color_id end -function GLFramebuffer(fb_size::NTuple{2, Int}) +function GLFramebuffer(fb_size::NTuple{2,Int}) # Create framebuffer frambuffer_id = glGenFramebuffers() glBindFramebuffer(GL_FRAMEBUFFER, frambuffer_id) @@ -68,7 +68,7 @@ function GLFramebuffer(fb_size::NTuple{2, Int}) ) # Holds a (plot id, element id) for point picking objectid_buffer = Texture( - Vec{2, GLuint}, fb_size, minfilter = :nearest, x_repeat = :clamp_to_edge + Vec{2,GLuint}, fb_size, minfilter = :nearest, x_repeat = :clamp_to_edge ) # holds depth and stencil values depth_buffer = Texture( @@ -101,20 +101,20 @@ function GLFramebuffer(fb_size::NTuple{2, Int}) # track of the buffer ids that are already in use. We may also want to reuse # buffers so we give them names for easy fetching. buffer_ids = Dict( - :color => GL_COLOR_ATTACHMENT0, + :color => GL_COLOR_ATTACHMENT0, :objectid => GL_COLOR_ATTACHMENT1, :HDR_color => GL_COLOR_ATTACHMENT2, :OIT_weight => GL_COLOR_ATTACHMENT3, - :depth => GL_DEPTH_ATTACHMENT, - :stencil => GL_STENCIL_ATTACHMENT, + :depth => GL_DEPTH_ATTACHMENT, + :stencil => GL_STENCIL_ATTACHMENT, ) buffers = Dict( - :color => color_buffer, + :color => color_buffer, :objectid => objectid_buffer, :HDR_color => HDR_color_buffer, :OIT_weight => OIT_weight_buffer, - :depth => depth_buffer, - :stencil => depth_buffer + :depth => depth_buffer, + :stencil => depth_buffer ) return GLFramebuffer( @@ -126,7 +126,7 @@ end function Base.resize!(fb::GLFramebuffer, window_size) ws = Int.((window_size[1], window_size[2])) - if ws != size(fb) && all(x-> x > 0, window_size) + if ws != size(fb) && all(x -> x > 0, window_size) for (name, buffer) in fb.buffers resize_nocopy!(buffer, ws) end @@ -139,22 +139,22 @@ end struct MonitorProperties name::String isprimary::Bool - position::Vec{2, Int} - physicalsize::Vec{2, Int} + position::Vec{2,Int} + physicalsize::Vec{2,Int} videomode::GLFW.VidMode videomode_supported::Vector{GLFW.VidMode} - dpi::Vec{2, Float64} + dpi::Vec{2,Float64} monitor::GLFW.Monitor end function MonitorProperties(monitor::GLFW.Monitor) name = GLFW.GetMonitorName(monitor) isprimary = GLFW.GetPrimaryMonitor() == monitor - position = Vec{2, Int}(GLFW.GetMonitorPos(monitor)...) - physicalsize = Vec{2, Int}(GLFW.GetMonitorPhysicalSize(monitor)...) + position = Vec{2,Int}(GLFW.GetMonitorPos(monitor)...) + physicalsize = Vec{2,Int}(GLFW.GetMonitorPhysicalSize(monitor)...) videomode = GLFW.GetVideoMode(monitor) sfactor = Sys.isapple() ? 2.0 : 1.0 - dpi = Vec(videomode.width * 25.4, videomode.height * 25.4) * sfactor ./ Vec{2, Float64}(physicalsize) + dpi = Vec(videomode.width * 25.4, videomode.height * 25.4) * sfactor ./ Vec{2,Float64}(physicalsize) videomode_supported = GLFW.GetVideoModes(monitor) MonitorProperties(name, isprimary, position, physicalsize, videomode, videomode_supported, dpi, monitor) diff --git a/GLMakie/src/picking.jl b/GLMakie/src/picking.jl index a444e8c7998..6943c13b501 100644 --- a/GLMakie/src/picking.jl +++ b/GLMakie/src/picking.jl @@ -23,7 +23,7 @@ function pick_native(screen::Screen, rect::Rect2i) end end -function pick_native(screen::Screen, xy::Vec{2, Float64}) +function pick_native(screen::Screen, xy::Vec{2,Float64}) isopen(screen) || return SelectionID{Int}(0, 0) ShaderAbstractions.switch_context!(screen.glscreen) sid = Base.RefValue{SelectionID{UInt32}}() @@ -41,7 +41,7 @@ function pick_native(screen::Screen, xy::Vec{2, Float64}) return SelectionID{Int}(0, 0) end -function Makie.pick(scene::Scene, screen::Screen, xy::Vec{2, Float64}) +function Makie.pick(scene::Scene, screen::Screen, xy::Vec{2,Float64}) sid = pick_native(screen, xy) if haskey(screen.cache2plot, sid.id) plot = screen.cache2plot[sid.id] @@ -70,14 +70,15 @@ function Makie.pick_closest(scene::Scene, screen::Screen, xy, range) x0, y0 = max.(1, floor.(Int, xy .- range)) x1, y1 = min.((w, h), floor.(Int, xy .+ range)) - dx = x1 - x0; dy = y1 - y0 + dx = x1 - x0 + dy = y1 - y0 sids = pick_native(screen, Rect2i(x0, y0, dx, dy)) min_dist = range^2 id = SelectionID{Int}(0, 0) - x, y = xy .+ 1 .- Vec2f(x0, y0) + x, y = xy .+ 1 .- Vec2f(x0, y0) for i in 1:dx, j in 1:dy - d = (x-i)^2 + (y-j)^2 + d = (x - i)^2 + (y - j)^2 sid = sids[i, j] if (d < min_dist) && (sid.id > 0) && haskey(screen.cache2plot, sid.id) min_dist = d @@ -97,20 +98,21 @@ function Makie.pick_sorted(scene::Scene, screen::Screen, xy, range) isopen(screen) || return (nothing, 0) w, h = size(screen) if !((1.0 <= xy[1] <= w) && (1.0 <= xy[2] <= h)) - return Tuple{AbstractPlot, Int}[] + return Tuple{AbstractPlot,Int}[] end x0, y0 = max.(1, floor.(Int, xy .- range)) x1, y1 = min.([w, h], ceil.(Int, xy .+ range)) - dx = x1 - x0; dy = y1 - y0 + dx = x1 - x0 + dy = y1 - y0 picks = pick_native(screen, Rect2i(x0, y0, dx, dy)) selected = filter(x -> x.id > 0 && haskey(screen.cache2plot, x.id), unique(vec(picks))) distances = Float32[range^2 for _ in selected] - x, y = xy .+ 1 .- Vec2f(x0, y0) + x, y = xy .+ 1 .- Vec2f(x0, y0) for i in 1:dx, j in 1:dy if picks[i, j].id > 0 - d = (x-i)^2 + (y-j)^2 + d = (x - i)^2 + (y - j)^2 i = findfirst(isequal(picks[i, j]), selected) if i === nothing @warn "This shouldn't happen..." diff --git a/GLMakie/src/postprocessing.jl b/GLMakie/src/postprocessing.jl index 3c295d158a6..7c4e5d1f56f 100644 --- a/GLMakie/src/postprocessing.jl +++ b/GLMakie/src/postprocessing.jl @@ -37,7 +37,7 @@ function OIT_postprocessor(framebuffer, shader_cache) loadshader("postprocessing/fullscreen.vert"), loadshader("postprocessing/OIT_blend.frag") ) - data = Dict{Symbol, Any}( + data = Dict{Symbol,Any}( # :opaque_color => framebuffer[:color][2], :sum_color => framebuffer[:HDR_color][2], :prod_alpha => framebuffer[:OIT_weight][2], @@ -120,7 +120,7 @@ function ssao_postprocessor(framebuffer, shader_cache) "N_samples" => "$N_samples" ) ) - data1 = Dict{Symbol, Any}( + data1 = Dict{Symbol,Any}( :position_buffer => framebuffer[:position][2], :normal_occlusion_buffer => getfallback(framebuffer, :normal_occlusion, :HDR_color)[2], :kernel => kernel, @@ -143,7 +143,7 @@ function ssao_postprocessor(framebuffer, shader_cache) loadshader("postprocessing/fullscreen.vert"), loadshader("postprocessing/SSAO_blur.frag") ) - data2 = Dict{Symbol, Any}( + data2 = Dict{Symbol,Any}( :normal_occlusion => getfallback(framebuffer, :normal_occlusion, :HDR_color)[2], :color_texture => framebuffer[:color][2], :ids => framebuffer[:objectid][2], @@ -207,7 +207,7 @@ function fxaa_postprocessor(framebuffer, shader_cache) if !haskey(framebuffer, :HDR_color) glBindFramebuffer(GL_FRAMEBUFFER, framebuffer.id[1]) color_luma_buffer = Texture( - RGBA{N0f8}, size(framebuffer), minfilter=:linear, x_repeat=:clamp_to_edge + RGBA{N0f8}, size(framebuffer), minfilter = :linear, x_repeat = :clamp_to_edge ) luma_id = attach_colorbuffer!(framebuffer, :color_luma, color_luma_buffer) else @@ -221,7 +221,7 @@ function fxaa_postprocessor(framebuffer, shader_cache) loadshader("postprocessing/fullscreen.vert"), loadshader("postprocessing/postprocess.frag") ) - data1 = Dict{Symbol, Any}( + data1 = Dict{Symbol,Any}( :color_texture => framebuffer[:color][2], :object_ids => framebuffer[:objectid][2] ) @@ -234,7 +234,7 @@ function fxaa_postprocessor(framebuffer, shader_cache) loadshader("postprocessing/fullscreen.vert"), loadshader("postprocessing/fxaa.frag") ) - data2 = Dict{Symbol, Any}( + data2 = Dict{Symbol,Any}( :color_texture => getfallback(framebuffer, :color_luma, :HDR_color)[2], :RCPFrame => lift(rcpframe, framebuffer.resolution), ) @@ -278,7 +278,7 @@ function to_screen_postprocessor(framebuffer, shader_cache, screen_fb_id = nothi loadshader("postprocessing/fullscreen.vert"), loadshader("postprocessing/copy.frag") ) - data = Dict{Symbol, Any}( + data = Dict{Symbol,Any}( :color_texture => framebuffer[:color][2] ) pass = RenderObject(data, shader, PostprocessPrerender(), nothing) diff --git a/GLMakie/src/rendering.jl b/GLMakie/src/rendering.jl index 811bb8094f0..ce60a2f980d 100644 --- a/GLMakie/src/rendering.jl +++ b/GLMakie/src/rendering.jl @@ -28,7 +28,7 @@ const selection_queries = Function[] """ Renders a single frame of a `window` """ -function render_frame(screen::Screen; resize_buffers=true) +function render_frame(screen::Screen; resize_buffers = true) nw = to_native(screen) ShaderAbstractions.switch_context!(nw) function sortby(x) diff --git a/GLMakie/src/screen.jl b/GLMakie/src/screen.jl index 9f732df3b22..6ea0569f2d2 100644 --- a/GLMakie/src/screen.jl +++ b/GLMakie/src/screen.jl @@ -1,7 +1,7 @@ const ScreenID = UInt16 const ZIndex = Int # ID, Area, clear, is visible, background color -const ScreenArea = Tuple{ScreenID, Scene} +const ScreenArea = Tuple{ScreenID,Scene} function renderloop end @@ -51,7 +51,7 @@ mutable struct ScreenConfig title::String fullscreen::Bool debugging::Bool - monitor::Union{Nothing, GLFW.Monitor} + monitor::Union{Nothing,GLFW.Monitor} # Postprocessor oit::Bool @@ -60,25 +60,25 @@ mutable struct ScreenConfig transparency_weight_scale::Float32 function ScreenConfig( - # Renderloop - renderloop::Union{Makie.Automatic, Function}, - pause_renderloop::Bool, - vsync::Bool, - render_on_demand::Bool, - framerate::Number, - # GLFW window attributes - float::Bool, - focus_on_show::Bool, - decorated::Bool, - title::AbstractString, - fullscreen::Bool, - debugging::Bool, - monitor::Union{Nothing, GLFW.Monitor}, - # Preproccessor - oit::Bool, - fxaa::Bool, - ssao::Bool, - transparency_weight_scale::Number) + # Renderloop + renderloop::Union{Makie.Automatic,Function}, + pause_renderloop::Bool, + vsync::Bool, + render_on_demand::Bool, + framerate::Number, + # GLFW window attributes + float::Bool, + focus_on_show::Bool, + decorated::Bool, + title::AbstractString, + fullscreen::Bool, + debugging::Bool, + monitor::Union{Nothing,GLFW.Monitor}, + # Preproccessor + oit::Bool, + fxaa::Bool, + ssao::Bool, + transparency_weight_scale::Number) return new( # Renderloop @@ -115,7 +115,7 @@ Note, that the `screen_config` can also be set permanently via `Makie.set_theme! $(Base.doc(ScreenConfig)) """ -function activate!(; inline=LAST_INLINE[], screen_config...) +function activate!(; inline = LAST_INLINE[], screen_config...) if haskey(screen_config, :pause_rendering) error("pause_rendering got renamed to pause_renderloop.") end @@ -141,42 +141,40 @@ mutable struct Screen{GLWindow} <: MakieScreen glscreen::GLWindow shader_cache::GLAbstraction.ShaderCache framebuffer::GLFramebuffer - config::Union{Nothing, ScreenConfig} + config::Union{Nothing,ScreenConfig} stop_renderloop::Bool - rendertask::Union{Task, Nothing} + rendertask::Union{Task,Nothing} - screen2scene::Dict{WeakRef, ScreenID} + screen2scene::Dict{WeakRef,ScreenID} screens::Vector{ScreenArea} - renderlist::Vector{Tuple{ZIndex, ScreenID, RenderObject}} + renderlist::Vector{Tuple{ZIndex,ScreenID,RenderObject}} postprocessors::Vector{PostProcessor} - cache::Dict{UInt64, RenderObject} - cache2plot::Dict{UInt32, AbstractPlot} + cache::Dict{UInt64,RenderObject} + cache2plot::Dict{UInt32,AbstractPlot} framecache::Matrix{RGB{N0f8}} render_tick::Observable{Nothing} window_open::Observable{Bool} - root_scene::Union{Scene, Nothing} + root_scene::Union{Scene,Nothing} reuse::Bool close_after_renderloop::Bool # To trigger rerenders that aren't related to an existing renderobject. requires_update::Bool function Screen( - glscreen::GLWindow, - shader_cache::GLAbstraction.ShaderCache, - framebuffer::GLFramebuffer, - config::Union{Nothing, ScreenConfig}, - stop_renderloop::Bool, - rendertask::Union{Nothing, Task}, - - screen2scene::Dict{WeakRef, ScreenID}, - screens::Vector{ScreenArea}, - renderlist::Vector{Tuple{ZIndex, ScreenID, RenderObject}}, - postprocessors::Vector{PostProcessor}, - cache::Dict{UInt64, RenderObject}, - cache2plot::Dict{UInt32, AbstractPlot}, - reuse::Bool - ) where {GLWindow} + glscreen::GLWindow, + shader_cache::GLAbstraction.ShaderCache, + framebuffer::GLFramebuffer, + config::Union{Nothing,ScreenConfig}, + stop_renderloop::Bool, + rendertask::Union{Nothing,Task}, screen2scene::Dict{WeakRef,ScreenID}, + screens::Vector{ScreenArea}, + renderlist::Vector{Tuple{ZIndex,ScreenID,RenderObject}}, + postprocessors::Vector{PostProcessor}, + cache::Dict{UInt64,RenderObject}, + cache2plot::Dict{UInt32,AbstractPlot}, + reuse::Bool + ) where {GLWindow} s = size(framebuffer) screen = new{GLWindow}( @@ -196,20 +194,18 @@ end # gets removed in destroy!(screen) const ALL_SCREENS = Set{Screen}() -function empty_screen(debugging::Bool; reuse=true) +function empty_screen(debugging::Bool; reuse = true) windowhints = [ - (GLFW.SAMPLES, 0), - (GLFW.DEPTH_BITS, 0), + (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), + (GLFW.ALPHA_BITS, 8), + (GLFW.RED_BITS, 8), + (GLFW.GREEN_BITS, 8), + (GLFW.BLUE_BITS, 8), (GLFW.STENCIL_BITS, 0), + (GLFW.AUX_BUFFERS, 0), ] resolution = (10, 10) window = try @@ -250,12 +246,12 @@ function empty_screen(debugging::Bool; reuse=true) window, shader_cache, fb, nothing, false, nothing, - Dict{WeakRef, ScreenID}(), + Dict{WeakRef,ScreenID}(), ScreenArea[], - Tuple{ZIndex, ScreenID, RenderObject}[], + Tuple{ZIndex,ScreenID,RenderObject}[], postprocessors, - Dict{UInt64, RenderObject}(), - Dict{UInt32, AbstractPlot}(), + Dict{UInt64,RenderObject}(), + Dict{UInt32,AbstractPlot}(), reuse, ) GLFW.SetWindowRefreshCallback(window, window -> refreshwindowcb(window, screen)) @@ -290,9 +286,9 @@ const SINGLETON_SCREEN = Screen[] function singleton_screen(debugging::Bool) if !isempty(SINGLETON_SCREEN) screen = SINGLETON_SCREEN[1] - close(screen; reuse=false) + close(screen; reuse = false) else - screen = empty_screen(debugging; reuse=false) + screen = empty_screen(debugging; reuse = false) push!(SINGLETON_SCREEN, screen) end return reopen!(screen) @@ -304,7 +300,7 @@ function Makie.apply_screen_config!(screen::Screen, config::ScreenConfig, scene: apply_config!(screen, config) end -function apply_config!(screen::Screen, config::ScreenConfig; visible::Bool=true, start_renderloop::Bool=true) +function apply_config!(screen::Screen, config::ScreenConfig; visible::Bool = true, start_renderloop::Bool = true) ShaderAbstractions.switch_context!(screen.glscreen) glw = screen.glscreen ShaderAbstractions.switch_context!(glw) @@ -345,18 +341,18 @@ function apply_config!(screen::Screen, config::ScreenConfig; visible::Bool=true, end function Screen(; - resolution::Union{Nothing, Tuple{Int, Int}} = nothing, - visible = true, - start_renderloop = true, - screen_config... - ) + resolution::Union{Nothing,Tuple{Int,Int}} = nothing, + visible = true, + start_renderloop = true, + screen_config... +) # Screen config is managed by the current active theme, so managed by Makie config = Makie.merge_screen_config(ScreenConfig, screen_config) screen = screen_from_pool(config.debugging) if !isnothing(resolution) resize!(screen, resolution...) end - apply_config!(screen, config; visible=visible, start_renderloop=start_renderloop) + apply_config!(screen, config; visible = visible, start_renderloop = start_renderloop) return screen end @@ -373,31 +369,31 @@ function display_scene!(screen::Screen, scene::Scene) return end -function Screen(scene::Scene; visible=true, start_renderloop=true, screen_config...) +function Screen(scene::Scene; visible = true, start_renderloop = true, screen_config...) config = Makie.merge_screen_config(ScreenConfig, screen_config) - return Screen(scene, config; visible=visible, start_renderloop=start_renderloop) + return Screen(scene, config; visible = visible, start_renderloop = start_renderloop) end # Open an interactive window -function Screen(scene::Scene, config::ScreenConfig; visible=true, start_renderloop=true) +function Screen(scene::Scene, config::ScreenConfig; visible = true, start_renderloop = true) screen = singleton_screen(config.debugging) - apply_config!(screen, config; visible=visible, start_renderloop=start_renderloop) + apply_config!(screen, config; visible = visible, start_renderloop = start_renderloop) display_scene!(screen, scene) return screen end # Screen to save a png/jpeg to file or io -function Screen(scene::Scene, config::ScreenConfig, io::Union{Nothing, String, IO}, typ::MIME; visible=false, start_renderloop=false) +function Screen(scene::Scene, config::ScreenConfig, io::Union{Nothing,String,IO}, typ::MIME; visible = false, start_renderloop = false) screen = singleton_screen(config.debugging) - apply_config!(screen, config; visible=visible, start_renderloop=start_renderloop) + apply_config!(screen, config; visible = visible, start_renderloop = start_renderloop) display_scene!(screen, scene) return screen end # Screen that is efficient for `colorbuffer(screen)` -function Screen(scene::Scene, config::ScreenConfig, ::Makie.ImageStorageFormat; visible=false, start_renderloop=false) +function Screen(scene::Scene, config::ScreenConfig, ::Makie.ImageStorageFormat; visible = false, start_renderloop = false) screen = singleton_screen(config.debugging) - apply_config!(screen, config; visible=visible, start_renderloop=start_renderloop) + apply_config!(screen, config; visible = visible, start_renderloop = start_renderloop) display_scene!(screen, scene) return screen end @@ -448,7 +444,7 @@ function Base.delete!(screen::Screen, scene::Scene) # Remap scene IDs to a continuous range by replacing the largest ID # with the one that got removed - if deleted_id-1 != length(screen.screens) + if deleted_id - 1 != length(screen.screens) key, max_id = first(screen.screen2scene) for p in screen.screen2scene if p[2] > max_id @@ -507,7 +503,7 @@ function Base.delete!(screen::Screen, scene::Scene, plot::AbstractPlot) renderobject = get(screen.cache, objectid(plot), nothing) if !isnothing(renderobject) destroy!(renderobject) - filter!(x-> x[3] !== renderobject, screen.renderlist) + filter!(x -> x[3] !== renderobject, screen.renderlist) delete!(screen.cache2plot, renderobject.id) end delete!(screen.cache, objectid(plot)) @@ -540,7 +536,7 @@ function Base.empty!(screen::Screen) end function destroy!(screen::Screen) - close(screen; reuse=false) + close(screen; reuse = false) # wait for rendertask to finish # otherwise, during rendertask clean up we may run into a destroyed window wait(screen) @@ -560,9 +556,9 @@ end Closes screen and emptying it. Doesn't destroy the screen and instead frees it for being re-used again, if `reuse=true`. """ -function Base.close(screen::Screen; reuse=true) +function Base.close(screen::Screen; reuse = true) set_screen_visibility!(screen, false) - stop_renderloop!(screen; close_after_renderloop=false) + stop_renderloop!(screen; close_after_renderloop = false) screen.window_open[] = false empty!(screen) if reuse && screen.reuse @@ -610,7 +606,7 @@ function Base.resize!(screen::Screen, w, h) resize!(fb, (w, h)) end -function fast_color_data!(dest::Array{RGB{N0f8}, 2}, source::Texture{T, 2}) where T +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) @@ -633,7 +629,7 @@ heatmap(depth_color, colormap=:grays) """ function depthbuffer(screen::Screen) ShaderAbstractions.switch_context!(screen.glscreen) - render_frame(screen, resize_buffers=false) # let it render + render_frame(screen, resize_buffers = false) # let it render glFinish() # block until opengl is done rendering source = screen.framebuffer.buffers[:depth] depth = Matrix{Float32}(undef, size(source)) @@ -653,7 +649,7 @@ function Makie.colorbuffer(screen::Screen, format::Makie.ImageStorageFormat = Ma # we still need to poll though, to get all the newest events! # GLFW.PollEvents() # keep current buffer size to allows larger-than-window renders - render_frame(screen, resize_buffers=false) # let it render + render_frame(screen, resize_buffers = false) # let it render glFinish() # block until opengl is done rendering if size(ctex) != size(screen.framecache) screen.framecache = Matrix{RGB{N0f8}}(undef, size(ctex)) @@ -752,7 +748,7 @@ function pause_renderloop!(screen::Screen) screen.config.pause_renderloop = true end -function stop_renderloop!(screen::Screen; close_after_renderloop=screen.close_after_renderloop) +function stop_renderloop!(screen::Screen; close_after_renderloop = screen.close_after_renderloop) # don't double close when stopping renderloop c = screen.close_after_renderloop screen.close_after_renderloop = close_after_renderloop @@ -770,7 +766,7 @@ function stop_renderloop!(screen::Screen; close_after_renderloop=screen.close_af return end -function set_framerate!(screen::Screen, fps=30) +function set_framerate!(screen::Screen, fps = 30) screen.config.framerate = fps end @@ -785,7 +781,8 @@ end function vsynced_renderloop(screen) while isopen(screen) && !screen.stop_renderloop if screen.config.pause_renderloop - pollevents(screen); sleep(0.1) + pollevents(screen) + sleep(0.1) continue end pollevents(screen) # GLFW poll @@ -798,7 +795,8 @@ end function fps_renderloop(screen::Screen) while isopen(screen) && !screen.stop_renderloop if screen.config.pause_renderloop - pollevents(screen); sleep(0.1) + pollevents(screen) + sleep(0.1) continue end time_per_frame = 1.0 / screen.config.framerate @@ -864,14 +862,14 @@ function renderloop(screen) fps_renderloop(screen) end catch e - @warn "error in renderloop" exception=(e, Base.catch_backtrace()) + @warn "error in renderloop" exception = (e, Base.catch_backtrace()) rethrow(e) end if screen.close_after_renderloop try close(screen) catch e - @warn "error closing screen" exception=(e, Base.catch_backtrace()) + @warn "error closing screen" exception = (e, Base.catch_backtrace()) end end screen.rendertask = nothing @@ -880,7 +878,7 @@ end function plot2robjs(screen::Screen, plot) plots = Makie.flatten_plots(plot) - return map(x-> screen.cache[objectid(x)], plots) + return map(x -> screen.cache[objectid(x)], plots) end export plot2robjs diff --git a/GLMakie/test/glmakie_refimages.jl b/GLMakie/test/glmakie_refimages.jl index 5a386d5d0e8..b4d566fdd6a 100644 --- a/GLMakie/test/glmakie_refimages.jl +++ b/GLMakie/test/glmakie_refimages.jl @@ -11,18 +11,18 @@ using ReferenceTests.RNG scene = Scene() cam2d!(scene) r = 4 - sep = 4*r - scatter!(scene, (sep+2*r)*[-1,-1,1,1], (sep+2*r)*[-1,1,-1,1]) + sep = 4 * r + scatter!(scene, (sep + 2 * r) * [-1, -1, 1, 1], (sep + 2 * r) * [-1, 1, -1, 1]) - for i=-1:1 - for j=-1:1 - angle = pi/2 + pi/4*i - x = r*[-cos(angle/2),0,-cos(angle/2)] - y = r*[-sin(angle/2),0,sin(angle/2)] + for i in -1:1 + for j in -1:1 + angle = pi / 2 + pi / 4 * i + x = r * [-cos(angle / 2), 0, -cos(angle / 2)] + y = r * [-sin(angle / 2), 0, sin(angle / 2)] linewidth = 40 * 2.0^j - lines!(scene, x .+ sep*i, y .+ sep*j, color=RGBAf(0,0,0,0.5), linewidth=linewidth) - lines!(scene, x .+ sep*i, y .+ sep*j, color=:red) + lines!(scene, x .+ sep * i, y .+ sep * j, color = RGBAf(0, 0, 0, 0.5), linewidth = linewidth) + lines!(scene, x .+ sep * i, y .+ sep * j, color = :red) end end center!(scene) @@ -31,7 +31,7 @@ end @reference_test "Sampler type" begin # Directly access texture parameters: - x = Sampler(fill(to_color(:yellow), 100, 100), minfilter=:nearest) + x = Sampler(fill(to_color(:yellow), 100, 100), minfilter = :nearest) scene = image(x) # indexing will go straight to the GPU, while only transfering the changes st = Stepper(scene) @@ -49,21 +49,21 @@ end pos = Observable(RNG.rand(Point3f, 2)) rot = Observable(RNG.rand(Vec3f, 2)) color = Observable(RNG.rand(RGBf, 2)) - size = Observable(0.1*RNG.rand(2)) + size = Observable(0.1 * RNG.rand(2)) makenew = Observable(1) on(makenew) do i pos[] = RNG.rand(Point3f, i) rot[] = RNG.rand(Vec3f, i) color[] = RNG.rand(RGBf, i) - size[] = 0.1*RNG.rand(i) + size[] = 0.1 * RNG.rand(i) end fig, ax, p = meshscatter(pos, - rotations=rot, - color=color, - markersize=size, - axis = (; scenekw = (;limits=Rect3f(Point3(0), Point3(1)))) + rotations = rot, + color = color, + markersize = size, + axis = (; scenekw = (; limits = Rect3f(Point3(0), Point3(1)))) ) Record(fig, [10, 5, 100, 60, 177]) do i makenew[] = i @@ -72,7 +72,7 @@ end @reference_test "Explicit frame rendering" begin function update_loop(m, buff, screen) - for i = 1:20 + for i in 1:20 GLFW.PollEvents() buff .= RNG.rand.(Point3f) .* 20f0 m[1] = buff @@ -82,8 +82,8 @@ end end end fig, ax, meshplot = meshscatter(RNG.rand(Point3f, 10^4) .* 20f0) - screen = display(GLMakie.Screen(;renderloop=(screen) -> nothing, start_renderloop=false), fig.scene) - buff = RNG.rand(Point3f, 10^4) .* 20f0; + screen = display(GLMakie.Screen(; renderloop = (screen) -> nothing, start_renderloop = false), fig.scene) + buff = RNG.rand(Point3f, 10^4) .* 20f0 update_loop(meshplot, buff, screen) @test isnothing(screen.rendertask) GLMakie.destroy!(screen) @@ -96,7 +96,7 @@ end fig = Figure() left = LScene(fig[1, 1]) - contour!(left, [sin(i+j) * sin(j+k) * sin(i+k) for i in 1:10, j in 1:10, k in 1:10], enable_depth = true) + contour!(left, [sin(i + j) * sin(j + k) * sin(i + k) for i in 1:10, j in 1:10, k in 1:10], enable_depth = true) mesh!(left, Sphere(Point3f(5), 6f0)) right = LScene(fig[1, 2]) volume!(right, [sin(2i) * sin(2j) * sin(2k) for i in 1:10, j in 1:10, k in 1:10], algorithm = :iso, enable_depth = true) diff --git a/GLMakie/test/runtests.jl b/GLMakie/test/runtests.jl index d73329c6825..b32578ffdfb 100644 --- a/GLMakie/test/runtests.jl +++ b/GLMakie/test/runtests.jl @@ -16,7 +16,7 @@ reference_tests_dir = normpath(joinpath(dirname(pathof(Makie)), "..", "Reference Pkg.develop(PackageSpec(path = reference_tests_dir)) using ReferenceTests -GLMakie.activate!(framerate=1.0) +GLMakie.activate!(framerate = 1.0) @testset "mimes" begin f, ax, pl = scatter(1:4) diff --git a/GLMakie/test/unit_tests.jl b/GLMakie/test/unit_tests.jl index ea16da8f284..ce48629fe39 100644 --- a/GLMakie/test/unit_tests.jl +++ b/GLMakie/test/unit_tests.jl @@ -23,7 +23,7 @@ end # A displayed figure should create a singleton screen and leave other # screens untouched - fig, ax, splot = scatter(1:4); + fig, ax, splot = scatter(1:4) screen2 = display(fig) @test screen !== screen2 @test GLMakie.ALL_SCREENS == Set([screen, screen2]) @@ -52,11 +52,11 @@ end @test isempty(events(ax.scene).window_open.listeners) # Test singleton screen replacement - fig, ax, p = scatter(1:4); + fig, ax, p = scatter(1:4) screen = display(fig) ptr = deepcopy(screen.glscreen.handle) @test isopen(screen) && (screen === GLMakie.SINGLETON_SCREEN[1]) - fig2, ax2, p2 = scatter(4:-1:1); + fig2, ax2, p2 = scatter(4:-1:1) screen2 = display(fig2) @test isopen(screen2) && (screen2 === GLMakie.SINGLETON_SCREEN[]) @test screen === screen2 @@ -67,25 +67,25 @@ end @testset "Pick a plot element or plot elements inside a rectangle" begin N = 100000 fig, ax, splot = scatter(1:N, 1:N) - limits!(ax, 99990,100000, 99990,100000) + limits!(ax, 99990, 100000, 99990, 100000) screen = display(GLMakie.Screen(visible = false), fig) # we don't really need the color buffer here, but this should be the best way right now to really # force a full render to happen GLMakie.Makie.colorbuffer(screen) # test for pick a single data point (with idx > 65535) - point_px = project_sp(ax.scene, Point2f(N-1,N-1)) - plot,idx = pick(ax.scene, point_px) - @test idx == N-1 + point_px = project_sp(ax.scene, Point2f(N - 1, N - 1)) + plot, idx = pick(ax.scene, point_px) + @test idx == N - 1 # test for pick a rectangle of data points (also with some indices > 65535) - rect = Rect2f(99990.5,99990.5,8,8) + rect = Rect2f(99990.5, 99990.5, 8, 8) origin_px = project_sp(ax.scene, Point(origin(rect))) tip_px = project_sp(ax.scene, Point(origin(rect) .+ widths(rect))) rect_px = Rect2i(round.(origin_px), round.(tip_px .- origin_px)) picks = unique(pick(ax.scene, rect_px)) # objects returned in plot_idx should be either grid lines (i.e. LineSegments) or Scatter points - @test all(pi-> pi[1] isa Union{LineSegments,Scatter, Makie.Mesh}, picks) + @test all(pi -> pi[1] isa Union{LineSegments,Scatter,Makie.Mesh}, picks) # scatter points should have indices equal to those in 99991:99998 scatter_plot_idx = filter(pi -> pi[1] isa Scatter, picks) @test Set(last.(scatter_plot_idx)) == Set(99991:99998) @@ -96,10 +96,10 @@ end @testset "emtpy!(fig)" begin GLMakie.closeall() fig = Figure() - ax = Axis(fig[1,1]) + ax = Axis(fig[1, 1]) heatmap!(ax, rand(4, 4)) - lines!(ax, 1:5, rand(5); linewidth=3) - text!(ax, [Point2f(2)], text=["hi"]) + lines!(ax, 1:5, rand(5); linewidth = 3) + text!(ax, [Point2f(2)], text = ["hi"]) screen = display(fig) empty!(fig) @testset "all got freed" begin @@ -112,10 +112,10 @@ end @test robj.vertexarray.id == 0 end end - ax = Axis(fig[1,1]) + ax = Axis(fig[1, 1]) heatmap!(ax, rand(4, 4)) - lines!(ax, 1:5, rand(5); linewidth=3) - text!(ax, [Point2f(2)], text=["hi"]) + lines!(ax, 1:5, rand(5); linewidth = 3) + text!(ax, [Point2f(2)], text = ["hi"]) @testset "no freed object after replotting" begin for (_, _, robj) in screen.renderlist for (k, v) in robj.uniforms @@ -133,15 +133,15 @@ end @testset "empty!(ax)" begin GLMakie.closeall() fig = Figure() - ax = Axis(fig[1,1]) + ax = Axis(fig[1, 1]) hmp = heatmap!(ax, rand(4, 4)) - lp = lines!(ax, 1:5, rand(5); linewidth=3) - tp = text!(ax, [Point2f(2)], text=["hi"]) + lp = lines!(ax, 1:5, rand(5); linewidth = 3) + tp = text!(ax, [Point2f(2)], text = ["hi"]) screen = display(fig) @test ax.scene.plots == [hmp, lp, tp] - robjs = map(x-> screen.cache[objectid(x)], [hmp, lp, tp.plots...]) + robjs = map(x -> screen.cache[objectid(x)], [hmp, lp, tp.plots...]) empty!(ax) @@ -156,8 +156,8 @@ end end heatmap!(ax, rand(4, 4)) - lines!(ax, 1:5, rand(5); linewidth=3) - text!(ax, [Point2f(2)], text=["hi"]) + lines!(ax, 1:5, rand(5); linewidth = 3) + text!(ax, [Point2f(2)], text = ["hi"]) @testset "no freed object after replotting" begin for (_, _, robj) in screen.renderlist for (k, v) in robj.uniforms @@ -178,7 +178,7 @@ end @testset "closing and redisplaying" begin GLMakie.closeall() fig = Figure() - ax = Axis(fig[1,1]) # only happens with axis + ax = Axis(fig[1, 1]) # only happens with axis # lines!(ax, 1:5, rand(5); linewidth=5) # but doesn't need a plot screen = display(fig) GLMakie.closeall() @@ -189,11 +189,11 @@ end @testset "closing and redisplaying + resizing" begin GLMakie.closeall() fig = Figure() - ax = Axis(fig[1,1]) # only happens with axis + ax = Axis(fig[1, 1]) # only happens with axis screen = display(fig) close(screen) screen = display(fig) - resize!(fig, 800,601) + resize!(fig, 800, 601) @test true # test for no errors for now # GLMakie.destroy!(screen) end @@ -210,23 +210,23 @@ end @testset "stresstest multi displays" begin GLMakie.closeall() screens = map(1:10) do i - fig = Figure(resolution=(500, 500)) - rng = Random.MersenneTwister(0) - ax, pl = image(fig[1, 1], 0..1, 0..1, rand(rng, 1000, 1000)) - scatter!(ax, rand(rng, Point2f, 1000), color=:red) - lines!(ax, rand(rng, Point2f, 1000), transparency=true) + fig = Figure(resolution = (500, 500)) + rng = Random.MersenneTwister(0) + ax, pl = image(fig[1, 1], 0 .. 1, 0 .. 1, rand(rng, 1000, 1000)) + scatter!(ax, rand(rng, Point2f, 1000), color = :red) + lines!(ax, rand(rng, Point2f, 1000), transparency = true) ax3d, pl = mesh(fig[1, 2], Sphere(Point3f(0), 1)) - meshscatter!(ax3d, rand(rng, Point3f, 100), color=:red) + meshscatter!(ax3d, rand(rng, Point3f, 100), color = :red) heatmap(fig[2, 1], rand(rng, 100, 100)) - surface(fig[2, 2], 0..1, 0..1, rand(rng, 1000, 1000) ./ 2) + surface(fig[2, 2], 0 .. 1, 0 .. 1, rand(rng, 1000, 1000) ./ 2) - display(GLMakie.Screen(visible=false), fig) + display(GLMakie.Screen(visible = false), fig) end images = map(Makie.colorbuffer, screens) - @test all(x-> x ≈ first(images), images) + @test all(x -> x ≈ first(images), images) @test Base.summarysize(screens) / 10^6 > 300 foreach(close, screens) @@ -248,7 +248,7 @@ end @test (Base.summarysize(screen) / 10^6) < 1.2 end # All should go to pool after close - @test all(x-> x in GLMakie.SCREEN_REUSE_POOL, screens) + @test all(x -> x in GLMakie.SCREEN_REUSE_POOL, screens) GLMakie.closeall() # now every screen should be gone diff --git a/MakieCore/src/attributes.jl b/MakieCore/src/attributes.jl index 84eddc36f94..3273ec49aa2 100644 --- a/MakieCore/src/attributes.jl +++ b/MakieCore/src/attributes.jl @@ -10,9 +10,9 @@ value_convert(x::Observables.AbstractObservable) = Observables.observe(x) value_convert(@nospecialize(x)) = x # We transform a tuple of observables into a Observable(tuple(values...)) -function value_convert(x::NTuple{N, Union{Any, Observables.AbstractObservable}}) where N +function value_convert(x::NTuple{N,Union{Any,Observables.AbstractObservable}}) where N result = Observable(to_value.(x)) - onany((args...)-> args, x...) + onany((args...) -> args, x...) return result end @@ -22,12 +22,12 @@ value_convert(x::NamedTuple) = Attributes(x) node_any(@nospecialize(obj)) = isa(obj, Observable{Any}) ? obj : isa(obj, Observable) ? convert(Observable{Any}, obj) : Observable{Any}(obj) -node_pairs(pair::Union{Pair, Tuple{Any, Any}}) = (pair[1] => node_any(value_convert(pair[2]))) +node_pairs(pair::Union{Pair,Tuple{Any,Any}}) = (pair[1] => node_any(value_convert(pair[2]))) node_pairs(pairs) = (node_pairs(pair) for pair in pairs) -Attributes(; kw_args...) = Attributes(Dict{Symbol, Observable}(node_pairs(kw_args))) -Attributes(pairs::Pair...) = Attributes(Dict{Symbol, Observable}(node_pairs(pairs))) -Attributes(pairs::AbstractVector) = Attributes(Dict{Symbol, Observable}(node_pairs.(pairs))) +Attributes(; kw_args...) = Attributes(Dict{Symbol,Observable}(node_pairs(kw_args))) +Attributes(pairs::Pair...) = Attributes(Dict{Symbol,Observable}(node_pairs(pairs))) +Attributes(pairs::AbstractVector) = Attributes(Dict{Symbol,Observable}(node_pairs.(pairs))) Attributes(pairs::Iterators.Pairs) = Attributes(collect(pairs)) Attributes(nt::NamedTuple) = Attributes(; nt...) attributes(x::Attributes) = getfield(x, :attributes) @@ -69,9 +69,9 @@ end Base.merge(target::Attributes, args::Attributes...) = merge!(copy(target), args...) -@generated hasfield(x::T, ::Val{key}) where {T, key} = :($(key in fieldnames(T))) +@generated hasfield(x::T, ::Val{key}) where {T,key} = :($(key in fieldnames(T))) -@inline function Base.getproperty(x::Union{Attributes, AbstractPlot}, key::Symbol) +@inline function Base.getproperty(x::Union{Attributes,AbstractPlot}, key::Symbol) if hasfield(x, Val(key)) getfield(x, key) else @@ -79,7 +79,7 @@ Base.merge(target::Attributes, args::Attributes...) = merge!(copy(target), args. end end -@inline function Base.setproperty!(x::Union{Attributes, AbstractPlot}, key::Symbol, value) +@inline function Base.setproperty!(x::Union{Attributes,AbstractPlot}, key::Symbol, value) if hasfield(x, Val(key)) setfield!(x, key, value) else @@ -118,7 +118,7 @@ end _indent_attrs(s, n) = join(split(s, '\n'), "\n" * " "^n) -function Base.show(io::IO,::MIME"text/plain", attr::Attributes) +function Base.show(io::IO, ::MIME"text/plain", attr::Attributes) io = IOContext(io, :compact => true) @@ -152,7 +152,7 @@ theme(x::AbstractPlot) = x.attributes isvisible(x) = haskey(x, :visible) && to_value(x[:visible]) #dict interface -const AttributeOrPlot = Union{AbstractPlot, Attributes} +const AttributeOrPlot = Union{AbstractPlot,Attributes} Base.pop!(x::AttributeOrPlot, args...) = pop!(x.attributes, args...) Base.haskey(x::AttributeOrPlot, key) = haskey(x.attributes, key) Base.delete!(x::AttributeOrPlot, key) = delete!(x.attributes, key) @@ -165,9 +165,9 @@ function Base.get!(f::Function, x::AttributeOrPlot, key::Symbol) return x[key] end end -Base.get!(x::AttributeOrPlot, key::Symbol, default) = get!(()-> default, x, key) +Base.get!(x::AttributeOrPlot, key::Symbol, default) = get!(() -> default, x, key) Base.get(f::Function, x::AttributeOrPlot, key::Symbol) = haskey(x, key) ? x[key] : f() -Base.get(x::AttributeOrPlot, key::Symbol, default) = get(()-> default, x, key) +Base.get(x::AttributeOrPlot, key::Symbol, default) = get(() -> default, x, key) # This is a bit confusing, since for a plot it returns the attribute from the arguments # and not a plot for integer indexing. But, we want to treat plots as "atomic" @@ -233,7 +233,7 @@ function Base.setindex!(x::AbstractPlot, value::Observable, key::Symbol) end # a few shortcut functions to make attribute conversion easier -function get_attribute(dict, key, default=nothing) +function get_attribute(dict, key, default = nothing) if haskey(dict, key) value = to_value(dict[key]) value isa Automatic && return default @@ -259,6 +259,6 @@ function merge_attributes!(input::Attributes, theme::Attributes) return input end -function Base.propertynames(x::Union{Attributes, AbstractPlot}) +function Base.propertynames(x::Union{Attributes,AbstractPlot}) return (keys(x.attributes)...,) end diff --git a/MakieCore/src/basic_plots.jl b/MakieCore/src/basic_plots.jl index 325d59d6806..ec944d9a8e0 100644 --- a/MakieCore/src/basic_plots.jl +++ b/MakieCore/src/basic_plots.jl @@ -396,14 +396,10 @@ Plots a marker for each element in `(x, y, z)`, `(x, y)`, or `positions`. colormap = theme(scene, :colormap), colorrange = automatic, marker = theme(scene, :marker), - markersize = theme(scene, :markersize), - - strokecolor = theme(scene, :markerstrokecolor), + markersize = theme(scene, :markersize), strokecolor = theme(scene, :markerstrokecolor), strokewidth = theme(scene, :markerstrokewidth), glowcolor = (:black, 0.0), - glowwidth = 0.0, - - rotations = Billboard(), + glowwidth = 0.0, rotations = Billboard(), marker_offset = automatic, transform_marker = false, # Applies the plots transformation to marker distancefield = nothing, @@ -470,7 +466,7 @@ Plots a mesh for each element in `(x, y, z)`, `(x, y)`, or `positions` (similar shading = true, fxaa = true, inspectable = theme(scene, :inspectable), - cycle = [:color], + cycle = [:color] ) end @@ -602,7 +598,7 @@ end # default_theme(scene, LineSegments) Attributes(; default_theme(scene, LineSegments)..., - depth_shift = -1f-5, + depth_shift = -1f-5 ) end diff --git a/MakieCore/src/conversion.jl b/MakieCore/src/conversion.jl index 09ed90a6eb8..d93d20feb80 100644 --- a/MakieCore/src/conversion.jl +++ b/MakieCore/src/conversion.jl @@ -9,7 +9,7 @@ function used_attributes end abstract type ConversionTrait end -const XYBased = Union{MeshScatter, Scatter, Lines, LineSegments} +const XYBased = Union{MeshScatter,Scatter,Lines,LineSegments} struct NoConversion <: ConversionTrait end @@ -18,16 +18,16 @@ conversion_trait(::Type) = NoConversion() convert_arguments(::NoConversion, args...) = args struct PointBased <: ConversionTrait end -conversion_trait(::Type{<: XYBased}) = PointBased() -conversion_trait(::Type{<: Text}) = PointBased() +conversion_trait(::Type{<:XYBased}) = PointBased() +conversion_trait(::Type{<:Text}) = PointBased() abstract type SurfaceLike <: ConversionTrait end struct ContinuousSurface <: SurfaceLike end -conversion_trait(::Type{<: Union{Surface, Image}}) = ContinuousSurface() +conversion_trait(::Type{<:Union{Surface,Image}}) = ContinuousSurface() struct DiscreteSurface <: SurfaceLike end -conversion_trait(::Type{<: Heatmap}) = DiscreteSurface() +conversion_trait(::Type{<:Heatmap}) = DiscreteSurface() struct VolumeLike <: ConversionTrait end -conversion_trait(::Type{<: Volume}) = VolumeLike() +conversion_trait(::Type{<:Volume}) = VolumeLike() diff --git a/MakieCore/src/recipes.jl b/MakieCore/src/recipes.jl index 741ab37a169..6356c7aa11a 100644 --- a/MakieCore/src/recipes.jl +++ b/MakieCore/src/recipes.jl @@ -5,21 +5,21 @@ to_func_name(x::Symbol) = Symbol(lowercase(string(x))) # Will get overloaded by recipe Macro plotsym(x) = :plot -function func2string(func::F) where F <: Function +function func2string(func::F) where F<:Function string(F.name.mt.name) end plotfunc(::Combined{F}) where F = F -plotfunc(::Type{<: AbstractPlot{Func}}) where Func = Func -plotfunc(::T) where T <: AbstractPlot = plotfunc(T) +plotfunc(::Type{<:AbstractPlot{Func}}) where Func = Func +plotfunc(::T) where T<:AbstractPlot = plotfunc(T) plotfunc(f::Function) = f func2type(x::T) where T = func2type(T) -func2type(x::Type{<: AbstractPlot}) = x +func2type(x::Type{<:AbstractPlot}) = x func2type(f::Function) = Combined{f} -plotkey(::Type{<: AbstractPlot{Typ}}) where Typ = Symbol(lowercase(func2string(Typ))) -plotkey(::T) where T <: AbstractPlot = plotkey(T) +plotkey(::Type{<:AbstractPlot{Typ}}) where Typ = Symbol(lowercase(func2string(Typ))) +plotkey(::T) where T<:AbstractPlot = plotkey(T) plotkey(::Nothing) = :scatter """ @@ -220,4 +220,4 @@ e.g.: plottype(x::Array{<: AbstractFloat, 3}) = Volume ``` """ -plottype(plot_args...) = Combined{Any, Tuple{typeof.(to_value.(plot_args))...}} # default to dispatch to type recipes! +plottype(plot_args...) = Combined{Any,Tuple{typeof.(to_value.(plot_args))...}} # default to dispatch to type recipes! diff --git a/MakieCore/src/types.jl b/MakieCore/src/types.jl index 3a633fcb09d..1e5f4e34fa3 100644 --- a/MakieCore/src/types.jl +++ b/MakieCore/src/types.jl @@ -40,17 +40,17 @@ push_screen!(scene, screen) """ abstract type MakieScreen <: AbstractDisplay end -const SceneLike = Union{AbstractScene, ScenePlot} +const SceneLike = Union{AbstractScene,ScenePlot} """ Main structure for holding attributes, for theming plots etc! Will turn all values into observables, so that they can be updated. """ struct Attributes - attributes::Dict{Symbol, Observable} + attributes::Dict{Symbol,Observable} end -struct Combined{Typ, T} <: ScenePlot{Typ} +struct Combined{Typ,T} <: ScenePlot{Typ} parent::SceneLike transformation::Transformable attributes::Attributes @@ -104,7 +104,7 @@ const px = Pixel(1) Billboard attribute to always have a primitive face the camera. Can be used for rotation. """ -struct Billboard{T <: Union{Float32, Vector{Float32}}} +struct Billboard{T<:Union{Float32,Vector{Float32}}} rotation::T end Billboard() = Billboard(0f0) diff --git a/MakieCore/test/runtests.jl b/MakieCore/test/runtests.jl index 600ac535987..278fb4bd588 100644 --- a/MakieCore/test/runtests.jl +++ b/MakieCore/test/runtests.jl @@ -12,7 +12,7 @@ end function plot!(plot::Plot(AbstractTimeseriesSolution)) # plot contains any keyword arguments that you pass to plot(series; kw...) var = get(plot, :var, Observable(5)) - density!(plot, map((v, r)-> v .* r.results, var, plot[1])) + density!(plot, map((v, r) -> v .* r.results, var, plot[1])) end struct Test2 @@ -29,7 +29,7 @@ function plot!(plot::Plot(Test2)) ser = AbstractTimeseriesSolution(arg1[].series) sol = Solution(arg1[].series) plot!(plot, ser, var = 10) - scatter!(plot, sol, attribute = 3, color=:red) + scatter!(plot, sol, attribute = 3, color = :red) end used_attributes(::Any, x::Solution) = (:attribute,) diff --git a/MakieRecipes/src/attribute_table.jl b/MakieRecipes/src/attribute_table.jl index 5909ceeaff0..1b90e525fe7 100644 --- a/MakieRecipes/src/attribute_table.jl +++ b/MakieRecipes/src/attribute_table.jl @@ -1,4 +1,4 @@ -const makie_linetype = Dict{Symbol, Any}( +const makie_linetype = Dict{Symbol,Any}( :auto => nothing, :solid => nothing, :dash => :dash, @@ -14,7 +14,7 @@ function makie_color(c) convert(RGBA, c) end -makie_seriestype_map = Dict{Symbol, Type}( +makie_seriestype_map = Dict{Symbol,Type}( :path => Lines, :path3d => Lines, :scatter => Scatter, diff --git a/MakieRecipes/src/bezier.jl b/MakieRecipes/src/bezier.jl index bf222bd1b02..cf7363c80fc 100644 --- a/MakieRecipes/src/bezier.jl +++ b/MakieRecipes/src/bezier.jl @@ -9,16 +9,16 @@ ) end -conversion_trait(::Type{<: Bezier}) = PointBased() +conversion_trait(::Type{<:Bezier}) = PointBased() -function calculated_attributes!(::Type{<: Bezier}, plot) +function calculated_attributes!(::Type{<:Bezier}, plot) color_and_colormap!(plot) pos = plot[1][] # extend one color per linesegment to be one (the same) color per vertex # taken from @edljk in PR #77 if haskey(plot, :color) && isa(plot[:color][], AbstractVector) && iseven(length(pos)) && (length(pos) ÷ 2) == length(plot[:color][]) plot[:color] = lift(plot[:color]) do cols - map(i-> cols[(i + 1) ÷ 2], 1:(length(cols) * 2)) + map(i -> cols[(i + 1) ÷ 2], 1:(length(cols) * 2)) end end end @@ -34,7 +34,7 @@ function from_nansep_vec(v::Vector{T}) where T prev = 1 num = 1 for i in idxs - vs[num] = v[prev:i-1] + vs[num] = v[prev:(i - 1)] prev = i + 1 num += 1 diff --git a/MakieRecipes/src/layout_integration.jl b/MakieRecipes/src/layout_integration.jl index 6cf6ad5206f..b17e6e5e8f9 100644 --- a/MakieRecipes/src/layout_integration.jl +++ b/MakieRecipes/src/layout_integration.jl @@ -1,4 +1,4 @@ function tomakie!(sc::AbstractScene, layout::Makie.GridLayout, args...; attrs...) # TODO create a finalizer for a Tuple{Scene, Layout, Vector{LAxis}} - RecipesPipeline.recipe_pipeline!(sc, Dict{Symbol, Any}(attrs), args) + RecipesPipeline.recipe_pipeline!(sc, Dict{Symbol,Any}(attrs), args) end diff --git a/MakieRecipes/src/pipeline_integration.jl b/MakieRecipes/src/pipeline_integration.jl index acbb29b1996..6f34ff875d7 100644 --- a/MakieRecipes/src/pipeline_integration.jl +++ b/MakieRecipes/src/pipeline_integration.jl @@ -3,10 +3,10 @@ # ## Types and aliases const PlotContext = Union{ - AbstractScene, - AbstractPlot, - MakieLayout.LAxis - } + AbstractScene, + AbstractPlot, + MakieLayout.LAxis +} # ## API implementation @@ -25,20 +25,20 @@ end RecipesPipeline.is_seriestype_supported(sc::PlotContext, st) = haskey(makie_seriestype_map, st) # Forward the argument preprocessing to Plots for now. -RecipesPipeline.series_defaults(sc::PlotContext, args...) = Dict{Symbol, Any}() +RecipesPipeline.series_defaults(sc::PlotContext, args...) = Dict{Symbol,Any}() # Pre-processing of user recipes function RecipesPipeline.process_userrecipe!(sc::PlotContext, kw_list, kw) if isa(get(kw, :marker_z, nothing), Function) # TODO: should this take y and/or z as arguments? kw[:marker_z] = isa(kw[:z], Nothing) ? map(kw[:marker_z], kw[:x], kw[:y]) : - map(kw[:marker_z], kw[:x], kw[:y], kw[:z]) + map(kw[:marker_z], kw[:x], kw[:y], kw[:z]) end # map line_z if it's a Function if isa(get(kw, :line_z, nothing), Function) kw[:line_z] = isa(kw[:z], Nothing) ? map(kw[:line_z], kw[:x], kw[:y]) : - map(kw[:line_z], kw[:x], kw[:y], kw[:z]) + map(kw[:line_z], kw[:x], kw[:y], kw[:z]) end push!(kw_list, kw) @@ -48,14 +48,14 @@ end function RecipesPipeline.get_axis_limits(sc::PlotContext, f, letter) lims = to_value(data_limits(sc)) i = if letter === :x - 1 - elseif letter === :y - 2 - elseif letter === :z - 3 - else - throw(ArgumentError("Letter $letter does not correspond to an axis.")) - end + 1 + elseif letter === :y + 2 + elseif letter === :z + 3 + else + throw(ArgumentError("Letter $letter does not correspond to an axis.")) + end o = origin(lims) return (o[i], o[i] + widths(lims)[i]) @@ -66,9 +66,9 @@ end ######################################## function slice_arg(v::AbstractMatrix, idx::Int) - c = mod1(idx, size(v,2)) - m,n = axes(v) - size(v,1) == 1 ? v[first(m),n[c]] : v[:,n[c]] + c = mod1(idx, size(v, 2)) + m, n = axes(v) + size(v, 1) == 1 ? v[first(m), n[c]] : v[:, n[c]] end # slice_arg(wrapper::Plots.InputWrapper, idx) = wrapper.obj slice_arg(v, idx) = v @@ -94,7 +94,7 @@ function makie_plottype(st::Symbol) return get(makie_seriestype_map, st, Lines) end -makie_args(::Type{T}, plotattributes) where T <: AbstractPlot = makie_args(conversion_trait(T), plotattributes) +makie_args(::Type{T}, plotattributes) where T<:AbstractPlot = makie_args(conversion_trait(T), plotattributes) function makie_args(::PointBased, plotattributes) @@ -115,9 +115,9 @@ end # TODO use Makie.plottype makie_args(::SurfaceLike, plotattributes) = (plotattributes[:x], plotattributes[:y], plotattributes[:z].surf) -makie_args(::Type{<: Contour}, plotattributes) = (plotattributes[:x], plotattributes[:y], plotattributes[:z].surf) +makie_args(::Type{<:Contour}, plotattributes) = (plotattributes[:x], plotattributes[:y], plotattributes[:z].surf) -function makie_args(::Type{<: Poly}, plotattributes) +function makie_args(::Type{<:Poly}, plotattributes) return (from_nansep_vec(Point2f.(plotattributes[:x], plotattributes[:y])),) end @@ -275,7 +275,7 @@ function set_series_color!(scene, st, plotattributes) # println() end - if !(plot isa Union{Heatmap, Surface, Image, Spy, Axis2D, Axis3D}) + if !(plot isa Union{Heatmap,Surface,Image,Spy,Axis2D,Axis3D}) get!(plotattributes, :seriescolor, to_color(plotattributes[:palette])) @@ -289,7 +289,7 @@ function set_palette!(plt, plotattributes) pt = get!(plotattributes, :palette, default_palette) if pt isa Palette # nothing - elseif pt isa Vector{<: Colorant} + elseif pt isa Vector{<:Colorant} plotattributes[:palette] = Palette(pt) else @warn "Palette was unrecognizable!" @@ -310,7 +310,7 @@ function plot_series_annotations!(plt, args, pt, plotattributes) @debug("Series annotations say hi") - annotations!(plt, strs, positions; fontsize = fontsize/30, align = (:center, :center), color = get(plotattributes, :textcolor, :black)) + annotations!(plt, strs, positions; fontsize = fontsize / 30, align = (:center, :center), color = get(plotattributes, :textcolor, :black)) end diff --git a/MakieRecipes/src/recipeplot.jl b/MakieRecipes/src/recipeplot.jl index c2ad9918bf6..a2924654eb8 100644 --- a/MakieRecipes/src/recipeplot.jl +++ b/MakieRecipes/src/recipeplot.jl @@ -8,7 +8,7 @@ return th end -function plot!(p::T) where T <: RecipePlot +function plot!(p::T) where T<:RecipePlot # What happens here is that I want to lift on every available observable, # so they need to be splatted. This also means that nested attributes @@ -23,7 +23,7 @@ function plot!(p::T) where T <: RecipePlot RecipesPipeline.recipe_pipeline!( p, - Dict{Symbol, Any}(keys(attrs) .=> to_value.(values(attrs))), + Dict{Symbol,Any}(keys(attrs) .=> to_value.(values(attrs))), to_value.(args) ) diff --git a/RPRMakie/examples/bars.jl b/RPRMakie/examples/bars.jl index 61514ecc546..4efc342a4f4 100644 --- a/RPRMakie/examples/bars.jl +++ b/RPRMakie/examples/bars.jl @@ -2,13 +2,13 @@ using GeometryBasics, RPRMakie using Colors, FileIO, ImageShow using Colors: N0f8 -RPRMakie.activate!(plugin=RPR.Northstar) -fig = Figure(; resolution=(800, 600), fontsize=26) +RPRMakie.activate!(plugin = RPR.Northstar) +fig = Figure(; resolution = (800, 600), fontsize = 26) radiance = 10000 lights = [EnvironmentLight(0.5, load(RPR.assetpath("studio026.exr"))), - PointLight(Vec3f(0, 0, 20), RGBf(radiance, radiance, radiance))] + PointLight(Vec3f(0, 0, 20), RGBf(radiance, radiance, radiance))] -ax = LScene(fig[1, 1]; scenekw=(lights=lights,)) +ax = LScene(fig[1, 1]; scenekw = (lights = lights,)) Makie.axis3d!(ax.scene, Rect3f(Vec3f(0), Vec3f(1, 1, 1.2))) rectMesh = FRect3D(Vec3f0(-0.5, -0.5, 0), Vec3f0(1)) recmesh = GeometryBasics.normal_mesh(rectMesh) @@ -16,9 +16,9 @@ n = 100 pos = [Point3f(i, j, 0) ./ 10 for i in 1:n for j in 1:n] z = rand(n, n) -mat = (type=:Microfacet, color=:gray, roughness=0.2, ior=1.390) +mat = (type = :Microfacet, color = :gray, roughness = 0.2, ior = 1.390) -meshscatter!(ax, pos; marker=recmesh, markersize=Vec3f.(0.1, 0.1, z[:]), material=mat, color=vec(z)) +meshscatter!(ax, pos; marker = recmesh, markersize = Vec3f.(0.1, 0.1, z[:]), material = mat, color = vec(z)) cam = cameracontrols(ax.scene) cam.eyeposition[] = Float32[5, 22, 12] diff --git a/RPRMakie/examples/eart_topographie_sphere.jl b/RPRMakie/examples/eart_topographie_sphere.jl index 6bef6b10abc..299a474fd5f 100644 --- a/RPRMakie/examples/eart_topographie_sphere.jl +++ b/RPRMakie/examples/eart_topographie_sphere.jl @@ -7,7 +7,7 @@ lon = dataset["lon"][:] lat = dataset["lat"][:] data = Float32.(dataset["ETOPO1avg"][:, :]) -function toCartesian(lon, lat; r=1, cxyz=(0, 0, 0)) +function toCartesian(lon, lat; r = 1, cxyz = (0, 0, 0)) lat, lon = lat * π / 180, lon * π / 180 x = cxyz[1] + (r + 80_000) * cos(lat) * cos(lon) y = cxyz[2] + (r + 80_000) * cos(lat) * sin(lon) @@ -15,10 +15,10 @@ function toCartesian(lon, lat; r=1, cxyz=(0, 0, 0)) return (x, y, z) ./ 80_000 end -function lonlat3D(lon, lat, data; cxyz=(0, 0, 0)) +function lonlat3D(lon, lat, data; cxyz = (0, 0, 0)) xyzw = zeros(size(data)..., 3) for (i, lon) in enumerate(lon), (j, lat) in enumerate(lat) - x, y, z = toCartesian(lon, lat; r=data[i, j], cxyz=cxyz) + x, y, z = toCartesian(lon, lat; r = data[i, j], cxyz = cxyz) xyzw[i, j, 1] = x xyzw[i, j, 2] = y xyzw[i, j, 3] = z @@ -26,7 +26,7 @@ function lonlat3D(lon, lat, data; cxyz=(0, 0, 0)) return xyzw[:, :, 1], xyzw[:, :, 2], xyzw[:, :, 3] end # this is needed in order to have a closed surface -lonext = cat(collect(lon), lon[1]; dims=1) +lonext = cat(collect(lon), lon[1]; dims = 1) dataext = begin tmpdata = zeros(size(lon)[1] + 1, size(lat)[1]) tmpdata[1:size(lon)[1], :] = data @@ -39,15 +39,15 @@ xetopo, yetopo, zetopo = lonlat3D(lonext, lat, dataext) begin r = 30 lights = [PointLight(Vec3f(2, 1, 3), RGBf(r, r, r))] - fig = Figure(; resolution=(1200, 1200), backgroundcolor=:black) - ax = LScene(fig[1, 1]; show_axis=false)#, scenekw=(lights=lights,)) - pltobj = surface!(ax, xetopo, yetopo, zetopo; color=dataext, colormap=:hot, colorrange=(-6000, 5000)) + fig = Figure(; resolution = (1200, 1200), backgroundcolor = :black) + ax = LScene(fig[1, 1]; show_axis = false)#, scenekw=(lights=lights,)) + pltobj = surface!(ax, xetopo, yetopo, zetopo; color = dataext, colormap = :hot, colorrange = (-6000, 5000)) cam = cameracontrols(ax.scene) cam.fov[] = 10 cam.eyeposition[] = Vec3f(3, 1, 1) cam.lookat[] = Vec3f(0) cam.upvector[] = Vec3f(0, 0, 1) Makie.update_cam!(ax.scene, cam) - RPRMakie.activate!(; iterations=32, plugin=RPR.Tahoe) + RPRMakie.activate!(; iterations = 32, plugin = RPR.Tahoe) display(ax.scene) end diff --git a/RPRMakie/examples/earth_topography.jl b/RPRMakie/examples/earth_topography.jl index 7f52cc43ca2..c55457c2d3b 100644 --- a/RPRMakie/examples/earth_topography.jl +++ b/RPRMakie/examples/earth_topography.jl @@ -27,13 +27,13 @@ function glow_material(data_normed) ) end -RPRMakie.activate!(iterations=32, plugin=RPR.Northstar) -fig = Figure(; resolution=(2000, 800)) +RPRMakie.activate!(iterations = 32, plugin = RPR.Northstar) +fig = Figure(; resolution = (2000, 800)) radiance = 30000 lights = [EnvironmentLight(1.0, load(RPR.assetpath("studio026.exr"))), - PointLight(Vec3f(0, 100, 100), RGBf(radiance, radiance, radiance))] + PointLight(Vec3f(0, 100, 100), RGBf(radiance, radiance, radiance))] -ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) +ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) mini, maxi = extrema(data) data_normed = ((data .- mini) ./ (maxi - mini)) @@ -41,8 +41,8 @@ data_normed = ((data .- mini) ./ (maxi - mini)) material = glow_material(data_normed) pltobj = surface!(ax, lon, lat, data_normed .* 20; - material=material, colormap=[:black, :white, :brown], - colorrange=(0.2, 0.8) .* 20) + material = material, colormap = [:black, :white, :brown], + colorrange = (0.2, 0.8) .* 20) # Set the camera to a nice angle cam = cameracontrols(ax.scene) cam.eyeposition[] = Vec3f(3, -300, 300) diff --git a/RPRMakie/examples/lego.jl b/RPRMakie/examples/lego.jl index 46ac94c5f77..91e4e370955 100644 --- a/RPRMakie/examples/lego.jl +++ b/RPRMakie/examples/lego.jl @@ -34,42 +34,42 @@ function plot_part!(scene, parent, name::String) origin = get(origins, name, nothing) if !isnothing(origin) centered = m.position .- origin - m = GeometryBasics.Mesh(meta(centered; normals=m.normals), faces(m)) + m = GeometryBasics.Mesh(meta(centered; normals = m.normals), faces(m)) translate!(trans, origin) else translate!(trans, -ptrans.translation[]) end - return mesh!(scene, m; color=color, transformation=trans) + return mesh!(scene, m; color = color, transformation = trans) end -function plot_lego_figure(s, floor=true) +function plot_lego_figure(s, floor = true) # Plot hierarchical mesh! figure = Dict() # Plot hierarchical mesh! figure["torso"] = plot_part!(s, s, "torso") - figure["head"] = plot_part!(s, figure["torso"], "head") - figure["eyes_mouth"] = plot_part!(s, figure["head"], "eyes_mouth") - figure["arm_right"] = plot_part!(s, figure["torso"], "arm_right") - figure["hand_right"] = plot_part!(s, figure["arm_right"], "hand_right") - figure["arm_left"] = plot_part!(s, figure["torso"], "arm_left") - figure["hand_left"] = plot_part!(s, figure["arm_left"], "hand_left") - figure["belt"] = plot_part!(s, figure["torso"], "belt") - figure["leg_right"] = plot_part!(s, figure["belt"], "leg_right") - figure["leg_left"] = plot_part!(s, figure["belt"], "leg_left") + figure["head"] = plot_part!(s, figure["torso"], "head") + figure["eyes_mouth"] = plot_part!(s, figure["head"], "eyes_mouth") + figure["arm_right"] = plot_part!(s, figure["torso"], "arm_right") + figure["hand_right"] = plot_part!(s, figure["arm_right"], "hand_right") + figure["arm_left"] = plot_part!(s, figure["torso"], "arm_left") + figure["hand_left"] = plot_part!(s, figure["arm_left"], "hand_left") + figure["belt"] = plot_part!(s, figure["torso"], "belt") + figure["leg_right"] = plot_part!(s, figure["belt"], "leg_right") + figure["leg_left"] = plot_part!(s, figure["belt"], "leg_left") # lift the little guy up translate!(figure["torso"], 0, 0, 20) # add some floor - floor && mesh!(s, Rect3f(Vec3f(-400, -400, -2), Vec3f(800, 800, 2)), color=:white) + floor && mesh!(s, Rect3f(Vec3f(-400, -400, -2), Vec3f(800, 800, 2)), color = :white) return figure end -RPRMakie.activate!(iterations=200, plugin=RPR.Northstar) +RPRMakie.activate!(iterations = 200, plugin = RPR.Northstar) radiance = 50000 lights = [ EnvironmentLight(1.5, rotl90(load(assetpath("sunflowers_1k.hdr"))')), - PointLight(Vec3f(50, 0, 200), RGBf(radiance, radiance, radiance*1.1)), + PointLight(Vec3f(50, 0, 200), RGBf(radiance, radiance, radiance * 1.1)), ] -s = Scene(resolution=(500, 500), lights=lights) +s = Scene(resolution = (500, 500), lights = lights) cam3d!(s) c = cameracontrols(s) @@ -78,12 +78,12 @@ c.far[] = 1000 update_cam!(s, c, Vec3f(100, 30, 80), Vec3f(0, 0, -10)) figure = plot_lego_figure(s) -rot_joints_by = 0.25*pi +rot_joints_by = 0.25 * pi total_translation = 50 animation_strides = 10 a1 = LinRange(0, rot_joints_by, animation_strides) -angles = [a1; reverse(a1[1:end-1]); -a1[2:end]; reverse(-a1[1:end-1]);] +angles = [a1; reverse(a1[1:(end - 1)]); -a1[2:end]; reverse(-a1[1:(end - 1)])] nsteps = length(angles); #Number of animation steps translations = LinRange(0, total_translation, nsteps) diff --git a/RPRMakie/examples/lines.jl b/RPRMakie/examples/lines.jl index 4b6a103fd44..812e696692f 100644 --- a/RPRMakie/examples/lines.jl +++ b/RPRMakie/examples/lines.jl @@ -3,8 +3,8 @@ using Colors, FileIO using Colors: N0f8 begin - RPRMakie.activate!(plugin=RPR.Tahoe) - fig = Figure(; resolution=(1000, 1000)) + RPRMakie.activate!(plugin = RPR.Tahoe) + fig = Figure(; resolution = (1000, 1000)) ax = LScene(fig[1, 1]) points = Point3f[] for i in 4:10 @@ -12,9 +12,9 @@ begin y = LinRange(0, i, n) y2 = (y ./ 2) .- 2 xyz = Point3f.((i - 5) ./ 2, y2, sin.(y) .+ 1) - lines!(ax, xyz; linewidth=5, color=:red) + lines!(ax, xyz; linewidth = 5, color = :red) append!(points, xyz) end - meshscatter!(ax, points, color=:green) + meshscatter!(ax, points, color = :green) ax.scene end diff --git a/RPRMakie/examples/makie_example.jl b/RPRMakie/examples/makie_example.jl index c2dbd65f47a..c2844b9a327 100644 --- a/RPRMakie/examples/makie_example.jl +++ b/RPRMakie/examples/makie_example.jl @@ -1,11 +1,11 @@ using GeometryBasics, Makie using FileIO, Colors using RPRMakie -RPRMakie.activate!(iterations=200) +RPRMakie.activate!(iterations = 200) earth = load(Makie.assetpath("earth.png")) m = uv_mesh(Tesselation(Sphere(Point3f(0), 1.0f0), 60)) -f, ax, mplot = Makie.mesh(m; color=earth) -Makie.mesh!(ax, Sphere(Point3f(2, 0, 0), 0.1f0); color=:red) +f, ax, mplot = Makie.mesh(m; color = earth) +Makie.mesh!(ax, Sphere(Point3f(2, 0, 0), 0.1f0); color = :red) x, y = collect(-8:0.5:8), collect(-8:0.5:8) z = [sinc(√(X^2 + Y^2) / π) for X in x, Y in y] wireframe!(ax, -2 .. 2, -2 .. 2, z) diff --git a/RPRMakie/examples/materials.jl b/RPRMakie/examples/materials.jl index 65e4a92283b..78d1b27f65d 100644 --- a/RPRMakie/examples/materials.jl +++ b/RPRMakie/examples/materials.jl @@ -5,10 +5,10 @@ using Colors: N0f8 image = begin radiance = 500 lights = [EnvironmentLight(1.0, load(RPR.assetpath("studio026.exr"))), - PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] - fig = Figure(; resolution=(1500, 700)) - ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) - screen = Screen(ax.scene; plugin=RPR.Northstar, iterations=400) + PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] + fig = Figure(; resolution = (1500, 700)) + ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) + screen = Screen(ax.scene; plugin = RPR.Northstar, iterations = 400) matsys = screen.matsys emissive = RPR.EmissiveMaterial(matsys) @@ -19,20 +19,20 @@ image = begin dielectric = RPR.DielectricBrdfX(matsys) gold = RPR.SurfaceGoldX(matsys) - materials = [glass chrome; - gold dielectric; - emissive plastic] + materials = [glass chrome + gold dielectric + emissive plastic] - mesh!(ax, load(Makie.assetpath("matball_floor.obj")); color=:white) + mesh!(ax, load(Makie.assetpath("matball_floor.obj")); color = :white) palette = reshape(Makie.default_palettes.color[][1:6], size(materials)) for i in CartesianIndices(materials) x, y = Tuple(i) mat = materials[i] mplot = if mat === emissive - matball!(ax, diffuse; inner=emissive, color=nothing) + matball!(ax, diffuse; inner = emissive, color = nothing) else - matball!(ax, mat; color=nothing) + matball!(ax, mat; color = nothing) end v = Vec3f(((x, y) .- (0.5 .* size(materials)) .- 0.5)..., 0) translate!(mplot, 0.9 .* (v .- Vec3f(0, 3, 0))) diff --git a/RPRMakie/examples/opengl_interop.jl b/RPRMakie/examples/opengl_interop.jl index 40a08cb4d7a..845ef215f3d 100644 --- a/RPRMakie/examples/opengl_interop.jl +++ b/RPRMakie/examples/opengl_interop.jl @@ -5,24 +5,24 @@ using Colors: N0f8 f = (u, v) -> cos(v) * (6 - (5 / 4 + sin(3 * u)) * sin(u - 3 * v)) g = (u, v) -> sin(v) * (6 - (5 / 4 + sin(3 * u)) * sin(u - 3 * v)) h = (u, v) -> -cos(u - 3 * v) * (5 / 4 + sin(3 * u)); -u = range(0; stop=2π, length=150) -v = range(0; stop=2π, length=150) +u = range(0; stop = 2π, length = 150) +v = range(0; stop = 2π, length = 150) radiance = 500 lights = [EnvironmentLight(1.0, load(RPR.assetpath("studio026.exr"))), - PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] + PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] -fig = Figure(; resolution=(1500, 1000)) -ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) -screen = RPRMakie.Screen(size(ax.scene); plugin=RPR.Tahoe) +fig = Figure(; resolution = (1500, 1000)) +ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) +screen = RPRMakie.Screen(size(ax.scene); plugin = RPR.Tahoe) material = RPR.UberMaterial(screen.matsys) -surface!(ax, f.(u, v'), g.(u, v'), h.(u, v'); ambient=Vec3f(0.5), diffuse=Vec3f(1), specular=0.5, - colormap=:balance, material=material) +surface!(ax, f.(u, v'), g.(u, v'), h.(u, v'); ambient = Vec3f(0.5), diffuse = Vec3f(1), specular = 0.5, + colormap = :balance, material = material) function Input(fig, val::RGB) - hue = Slider(fig; range=1:380, width=200) - lightness = Slider(fig; range=LinRange(0, 1, 100), width=200) - labels = [Label(fig, "hue"; halign=:left), Label(fig, "light"; halign=:left)] + hue = Slider(fig; range = 1:380, width = 200) + lightness = Slider(fig; range = LinRange(0, 1, 100), width = 200) + labels = [Label(fig, "hue"; halign = :left), Label(fig, "light"; halign = :left)] layout = grid!(hcat(labels, [hue, lightness])) hsl = HSL(val) set_close_to!(hue, hsl.h) @@ -32,34 +32,34 @@ function Input(fig, val::RGB) end function Input(fig, val::Vec4) - s = Slider(fig; range=LinRange(0, 1, 100), width=200) + s = Slider(fig; range = LinRange(0, 1, 100), width = 200) set_close_to!(s, first(val)) return map(x -> Vec4f(x), s.value), s end function Input(fig, val::Bool) - toggle = Toggle(fig; active=val) + toggle = Toggle(fig; active = val) return toggle.active, toggle end -sliders = (reflection_color=Input(fig, RGB(0, 0, 0)), reflection_weight=Input(fig, Vec4(0)), - reflection_roughness=Input(fig, Vec4(0)), reflection_anisotropy=Input(fig, Vec4(0)), - reflection_anisotropy_rotation=Input(fig, Vec4(0)), reflection_mode=Input(fig, Vec4(0)), - reflection_ior=Input(fig, Vec4(0)), reflection_metalness=Input(fig, Vec4(0)), - refraction_color=Input(fig, RGB(0, 0, 0)), refraction_weight=Input(fig, Vec4(0)), - refraction_roughness=Input(fig, Vec4(0)), refraction_ior=Input(fig, Vec4(0)), - refraction_absorption_color=Input(fig, RGB(0, 0, 0)), - refraction_absorption_distance=Input(fig, Vec4(0)), refraction_caustics=Input(fig, true), - sss_scatter_color=Input(fig, RGB(0, 0, 0)), sss_scatter_distance=Input(fig, Vec4(0)), - sss_scatter_direction=Input(fig, Vec4(0)), sss_weight=Input(fig, Vec4(0)), - sss_multiscatter=Input(fig, false), backscatter_weight=Input(fig, Vec4(0)), - backscatter_color=Input(fig, RGB(0, 0, 0))) +sliders = (reflection_color = Input(fig, RGB(0, 0, 0)), reflection_weight = Input(fig, Vec4(0)), + reflection_roughness = Input(fig, Vec4(0)), reflection_anisotropy = Input(fig, Vec4(0)), + reflection_anisotropy_rotation = Input(fig, Vec4(0)), reflection_mode = Input(fig, Vec4(0)), + reflection_ior = Input(fig, Vec4(0)), reflection_metalness = Input(fig, Vec4(0)), + refraction_color = Input(fig, RGB(0, 0, 0)), refraction_weight = Input(fig, Vec4(0)), + refraction_roughness = Input(fig, Vec4(0)), refraction_ior = Input(fig, Vec4(0)), + refraction_absorption_color = Input(fig, RGB(0, 0, 0)), + refraction_absorption_distance = Input(fig, Vec4(0)), refraction_caustics = Input(fig, true), + sss_scatter_color = Input(fig, RGB(0, 0, 0)), sss_scatter_distance = Input(fig, Vec4(0)), + sss_scatter_direction = Input(fig, Vec4(0)), sss_weight = Input(fig, Vec4(0)), + sss_multiscatter = Input(fig, false), backscatter_weight = Input(fig, Vec4(0)), + backscatter_color = Input(fig, RGB(0, 0, 0))) labels = [] inputs = [] refresh = Observable(nothing) for (key, (obs, input)) in pairs(sliders) - push!(labels, Label(fig, string(key); align=:left)) + push!(labels, Label(fig, string(key); align = :left)) push!(inputs, input) on(obs) do value @show key value @@ -68,7 +68,7 @@ for (key, (obs, input)) in pairs(sliders) end end -fig[1, 2] = grid!(hcat(labels, inputs); width=500) +fig[1, 2] = grid!(hcat(labels, inputs); width = 500) GLMakie.activate!() cam = cameracontrols(ax.scene) @@ -79,7 +79,7 @@ cam.fov[] = 30 display(fig) -context, task = RPRMakie.replace_scene_rpr!(ax.scene, screen; refresh=refresh) +context, task = RPRMakie.replace_scene_rpr!(ax.scene, screen; refresh = refresh) # Change light parameters interactively begin diff --git a/RPRMakie/examples/sea_cables.jl b/RPRMakie/examples/sea_cables.jl index 4c9a6b14a0f..760aef8636f 100644 --- a/RPRMakie/examples/sea_cables.jl +++ b/RPRMakie/examples/sea_cables.jl @@ -48,24 +48,24 @@ end earth_img = load(Downloads.download("https://upload.wikimedia.org/wikipedia/commons/5/56/Blue_Marble_Next_Generation_%2B_topography_%2B_bathymetry.jpg")) # the actual plot ! -RPRMakie.activate!(; iterations=100) +RPRMakie.activate!(; iterations = 100) scene = with_theme(theme_dark()) do - fig = Figure(; resolution=(1000, 1000)) + fig = Figure(; resolution = (1000, 1000)) radiance = 30 lights = [EnvironmentLight(0.5, load(RPR.assetpath("starmap_4k.tif"))), - PointLight(Vec3f(1, 1, 3), RGBf(radiance, radiance, radiance))] - ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) + PointLight(Vec3f(1, 1, 3), RGBf(radiance, radiance, radiance))] + ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) n = 1024 ÷ 4 # 2048 θ = LinRange(0, pi, n) φ = LinRange(-pi, pi, 2 * n) xe = [cos(φ) * sin(θ) for θ in θ, φ in φ] ye = [sin(φ) * sin(θ) for θ in θ, φ in φ] ze = [cos(θ) for θ in θ, φ in φ] - surface!(ax, xe, ye, ze; color=earth_img) - meshscatter!(toPoints3D; color=1:length(toPoints3D), markersize=0.005, colormap=:plasma) + surface!(ax, xe, ye, ze; color = earth_img) + meshscatter!(toPoints3D; color = 1:length(toPoints3D), markersize = 0.005, colormap = :plasma) colors = Makie.default_palettes.color[] c = Iterators.cycle(colors) - foreach(((l, c),) -> lines!(ax, l; linewidth=2, color=c), zip(splitLines3D, c)) + foreach(((l, c),) -> lines!(ax, l; linewidth = 2, color = c), zip(splitLines3D, c)) ax.scene.camera_controls.eyeposition[] = Vec3f(1.5) return ax.scene end diff --git a/RPRMakie/src/RPRMakie.jl b/RPRMakie/src/RPRMakie.jl index b3ddead9794..0d2aeaa6381 100644 --- a/RPRMakie/src/RPRMakie.jl +++ b/RPRMakie/src/RPRMakie.jl @@ -61,7 +61,7 @@ function __init__() return end -for name in names(Makie; all=true) +for name in names(Makie; all = true) if Base.isexported(Makie, name) @eval using Makie: $(name) @eval export $(name) diff --git a/RPRMakie/src/lines.jl b/RPRMakie/src/lines.jl index 467ce80572e..4cc4c872bc5 100644 --- a/RPRMakie/src/lines.jl +++ b/RPRMakie/src/lines.jl @@ -3,7 +3,7 @@ function line2segments(points) indices = RPR.rpr_int[] count = 0 for i in 1:npoints - push!(indices, i - 1) + push!(indices, i - 1) count += 1 if count == 4 && !(i == npoints) push!(indices, i - 1) @@ -56,7 +56,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.LineSegments) end curve = RPR.Curve(context, points, indices, radius, Vec2f.(0.0, LinRange(0, 1, nsegments)), - fill(1, nsegments)) + fill(1, nsegments)) material = RPR.DiffuseMaterial(matsys) color = to_color(plot.color[]) @@ -73,7 +73,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.LineSegments) if color isa AbstractVector{<:Colorant} set_color!(copy(color)) elseif color isa AbstractVector{<:Number} - sampler = Makie.sampler(to_colormap(plot.colormap[]), color; scaling=Makie.Scaling(identity, plot.colorrange[])) + sampler = Makie.sampler(to_colormap(plot.colormap[]), color; scaling = Makie.Scaling(identity, plot.colorrange[])) set_color!(collect(sampler)) else material.color = to_color(color) diff --git a/RPRMakie/src/meshes.jl b/RPRMakie/src/meshes.jl index 5f67806d33a..d355639458b 100644 --- a/RPRMakie/src/meshes.jl +++ b/RPRMakie/src/meshes.jl @@ -1,7 +1,7 @@ function extract_material(matsys, plot) material = if haskey(plot, :material) if plot.material isa Attributes - return RPR.Material(matsys, Dict(map(((k,v),)-> k => to_value(v), plot.material))) + return RPR.Material(matsys, Dict(map(((k, v),) -> k => to_value(v), plot.material))) else return plot.material[] end @@ -70,7 +70,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.MeshScatter) RPR.rprShapeSetObjectID(marker, 0) material = if haskey(plot, :material) if plot.material isa Attributes - RPR.Material(matsys, Dict(map(((k,v),)-> k => to_value(v), plot.material))) + RPR.Material(matsys, Dict(map(((k, v),) -> k => to_value(v), plot.material))) else plot.material[] end @@ -78,7 +78,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.MeshScatter) RPR.DiffuseMaterial(matsys) end set!(marker, material) - for i in 1:(n_instances-1) + for i in 1:(n_instances - 1) inst = RPR.Shape(context, marker) RPR.rprShapeSetObjectID(inst, i) push!(instances, inst) @@ -93,7 +93,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.MeshScatter) object_id = RPR.InputLookupMaterial(matsys) object_id.value = RPR.RPR_MATERIAL_NODE_LOOKUP_OBJECT_ID - uv = object_id * Vec3f(0, 1/n_instances, 0) + uv = object_id * Vec3f(0, 1 / n_instances, 0) tex = RPR.Texture(matsys, collect(color_from_num'); uv = uv) @@ -151,7 +151,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.Surface) faces = decompose(GLTriangleFace, r) uv = decompose_uv(r) # with this we can beuild a mesh - mesh = GeometryBasics.Mesh(meta(vec(positions[]), uv=uv), faces) + mesh = GeometryBasics.Mesh(meta(vec(positions[]), uv = uv), faces) rpr_mesh = RPR.Shape(context, mesh) color = plot.color[] @@ -175,7 +175,7 @@ function Makie.plot!(plot::Matball) mat = getproperty(plot, name)[] mat = mat isa Makie.Automatic ? base : mat mesh = load(assetpath("matball_$(name).obj")) - mesh!(plot, mesh, material=mat, color=plot.color) + mesh!(plot, mesh, material = mat, color = plot.color) end return plot end diff --git a/RPRMakie/src/scene.jl b/RPRMakie/src/scene.jl index 20ea24b3067..fd8ce6c37f5 100644 --- a/RPRMakie/src/scene.jl +++ b/RPRMakie/src/scene.jl @@ -14,7 +14,7 @@ function update_rpr_camera!(oldvals, camera, cam_controls, cam) RPR.rprCameraSetFarPlane(camera, far) RPR.rprCameraSetNearPlane(camera, near) h = norm(res) - RPR.rprCameraSetFocalLength(camera, (30*h)/fov) + RPR.rprCameraSetFocalLength(camera, (30 * h) / fov) # RPR_CAMERA_FSTOP # RPR_CAMERA_MODE return new_vals @@ -30,7 +30,7 @@ function insert_plots!(context, matsys, scene, mscene::Makie.Scene, @nospecializ object = to_rpr_object(context, matsys, mscene, plot) if !isnothing(object) if object isa AbstractVector - foreach(x-> push!(scene, x), object) + foreach(x -> push!(scene, x), object) else push!(scene, object) end @@ -83,7 +83,7 @@ function to_rpr_scene(context::RPR.Context, matsys, mscene::Makie.Scene) set!(context, scene) # Only set background image if it isn't set by env light, since # background image takes precedence - if !any(x-> x isa Makie.EnvironmentLight, mscene.lights) + if !any(x -> x isa Makie.EnvironmentLight, mscene.lights) env_img = fill(to_color(mscene.backgroundcolor[]), 1, 1) img = RPR.Image(context, env_img) RPR.rprSceneSetBackgroundImage(scene, img) @@ -99,7 +99,7 @@ function to_rpr_scene(context::RPR.Context, matsys, mscene::Makie.Scene) return scene end -function replace_scene_rpr!(scene::Makie.Scene, screen=Screen(scene); refresh=Observable(nothing)) +function replace_scene_rpr!(scene::Makie.Scene, screen = Screen(scene); refresh = Observable(nothing)) context = screen.context matsys = screen.matsys screen.scene = scene @@ -129,13 +129,13 @@ function replace_scene_rpr!(scene::Makie.Scene, screen=Screen(scene); refresh=Ob cam_values = (;) task = @async while isopen(scene) cam_values = update_rpr_camera!(cam_values, camera, cam_controls, cam) - framebuffer2 = render(screen; clear=clear, iterations=1) + framebuffer2 = render(screen; clear = clear, iterations = 1) if clear clear = false end data = RPR.get_data(framebuffer2) - im[1] = reverse(reshape(data, screen.fb_size); dims=2) - sleep(1/10) + im[1] = reverse(reshape(data, screen.fb_size); dims = 2) + sleep(1 / 10) end return context, task, rpr_scene end @@ -157,10 +157,10 @@ mutable struct Screen <: Makie.MakieScreen matsys::RPR.MaterialSystem framebuffer1::RPR.FrameBuffer framebuffer2::RPR.FrameBuffer - fb_size::Tuple{Int, Int} - scene::Union{Nothing, Scene} + fb_size::Tuple{Int,Int} + scene::Union{Nothing,Scene} setup_scene::Bool - rpr_scene::Union{Nothing, RPR.Scene} + rpr_scene::Union{Nothing,RPR.Scene} iterations::Int cleared::Bool end @@ -173,7 +173,7 @@ function Base.show(io::IO, ::MIME"image/png", screen::Screen) end function Makie.apply_screen_config!(screen::Screen, config::ScreenConfig) - context = RPR.Context(; resource=config.resource, plugin=config.plugin) + context = RPR.Context(; resource = config.resource, plugin = config.plugin) screen.context = context screen.matsys = RPR.MaterialSystem(context, 0) set_standard_tonemapping!(context) @@ -197,7 +197,7 @@ Screen(scene::Scene, config::ScreenConfig, ::IO, ::MIME) = Screen(scene, config) Screen(scene::Scene, config::ScreenConfig, ::Makie.ImageStorageFormat) = Screen(scene, config) function Screen(fb_size::NTuple{2,<:Integer}, config::ScreenConfig) - context = RPR.Context(; resource=config.resource, plugin=config.plugin) + context = RPR.Context(; resource = config.resource, plugin = config.plugin) matsys = RPR.MaterialSystem(context, 0) set_standard_tonemapping!(context) set!(context, RPR.RPR_CONTEXT_MAX_RECURSION, UInt(config.max_recursion)) @@ -210,7 +210,7 @@ function Screen(fb_size::NTuple{2,<:Integer}, config::ScreenConfig) config.iterations, false) end -function render(screen; clear=true, iterations=screen.iterations) +function render(screen; clear = true, iterations = screen.iterations) context = screen.context fb_size = screen.fb_size framebuffer1 = screen.framebuffer1 @@ -239,10 +239,10 @@ function Makie.colorbuffer(screen::Screen) display(screen, screen.scene) end data_1d = RPR.get_data(render(screen)) - r = reverse(reshape(data_1d, screen.fb_size), dims=2) + r = reverse(reshape(data_1d, screen.fb_size), dims = 2) img = rotl90(r) return map(img) do color - RGB{Colors.N0f8}(mapc(x-> clamp(x, 0, 1), color)) + RGB{Colors.N0f8}(mapc(x -> clamp(x, 0, 1), color)) end end @@ -267,4 +267,4 @@ function Base.insert!(screen::Screen, scene::Scene, plot::AbstractPlot) return screen end -Makie.backend_showable(::Type{Screen}, ::Union{MIME"image/jpeg", MIME"image/png"}) = true +Makie.backend_showable(::Type{Screen}, ::Union{MIME"image/jpeg",MIME"image/png"}) = true diff --git a/RPRMakie/test/lines.jl b/RPRMakie/test/lines.jl index e36c4698486..f95d95d3bb7 100644 --- a/RPRMakie/test/lines.jl +++ b/RPRMakie/test/lines.jl @@ -2,7 +2,7 @@ using GLMakie, GeometryBasics, RPRMakie, RadeonProRender using Colors, FileIO using Colors: N0f8 RPR = RadeonProRender -GLMakie.activate!(float=true, focus_on_show=false) +GLMakie.activate!(float = true, focus_on_show = false) cat = load(GLMakie.assetpath("cat.obj")) begin @@ -12,16 +12,16 @@ begin emissive = RPR.EmissiveMaterial(matsys) diffuse = RPR.DiffuseMaterial(matsys) - fig = Figure(resolution=(1000, 1000)) - ax = LScene(fig[1, 1], show_axis=false) + fig = Figure(resolution = (1000, 1000)) + ax = LScene(fig[1, 1], show_axis = false) for i in 4:4:12 n = i + 1 y = LinRange(0, i, n) y2 = (y ./ 2) .- 2 - lines!(ax, fill((i-5) ./ 2, n), y2, sin.(y) .+ 1, linewidth=5) + lines!(ax, fill((i - 5) ./ 2, n), y2, sin.(y) .+ 1, linewidth = 5) end - mesh!(ax, Rect3f(Vec3f(-3, -3, -0.1), Vec3f(6, 6, 0.1)), color=:white) - mesh!(ax, Sphere(Point3f(0, 0, 2), 0.1), material=emissive) + mesh!(ax, Rect3f(Vec3f(-3, -3, -0.1), Vec3f(6, 6, 0.1)), color = :white) + mesh!(ax, Sphere(Point3f(0, 0, 2), 0.1), material = emissive) display(fig) end # fetch(task) @@ -32,41 +32,41 @@ end begin - uber1.color =Vec4f(1, 1, 1, 1) - uber1.diffuse_weight =Vec4f(0, 0, 0, 0) - uber1.diffuse_roughness =Vec4f(1, 1, 1, 1) - uber1.reflection_color =Vec4f(0.996078, 0.858824, 0.639216, 0) - uber1.reflection_weight =Vec4f(1, 1, 1, 1) - uber1.reflection_roughness =Vec4f(0, 0, 0, 0) - uber1.reflection_anisotropy =Vec4f(0, 0, 0, 0) - uber1.reflection_anisotropy_rotation =Vec4f(0, 0, 0, 0) - uber1.reflection_ior =Vec4f(1.36, 1.36, 1.36, 1.36) - uber1.refraction_color =Vec4f(0.996078, 0.858824, 0.639216, 0) - uber1.refraction_weight =Vec4f(1, 1, 1, 1) - uber1.refraction_roughness =Vec4f(0, 0, 0, 0) - uber1.refraction_ior =Vec4f(1.36, 1.36, 1.36, 1.36) - uber1.refraction_absorption_color =Vec4f(0.996078, 0.858824, 0.639216, 0) - uber1.refraction_absorption_distance =Vec4f(0, 0, 0, 0) - uber1.refraction_caustics =Vec4f(0) - uber1.coating_color =Vec4f(1, 1, 1, 1) - uber1.coating_weight =Vec4f(0, 0, 0, 0) - uber1.coating_roughness =Vec4f(0, 0, 0, 0) - uber1.coating_ior =Vec4f(3, 3, 3, 3) - uber1.coating_metalness =Vec4f(0, 0, 0, 0) - uber1.coating_transmission_color =Vec4f(1, 1, 1, 1) - uber1.coating_thickness =Vec4f(0, 0, 0, 0) - uber1.sheen =Vec4f(1, 1, 1, 1) - uber1.sheen_tint =Vec4f(0, 0, 0, 0) - uber1.sheen_weight =Vec4f(0, 0, 0, 0) - uber1.emission_color =Vec4f(1, 1, 1, 1) - uber1.emission_weight =Vec3f( 0, 0, 0) - uber1.transparency =Vec4f(0, 0, 0, 0) - uber1.sss_scatter_color =Vec4f(0, 0, 0, 0) - uber1.sss_scatter_distance =Vec4f(0, 0, 0, 0) - uber1.sss_scatter_direction =Vec4f(0, 0, 0, 0) - uber1.sss_weight =Vec4f(0, 0, 0, 0) - uber1.backscatter_weight =Vec4f(0, 0, 0, 0) - uber1.backscatter_color =Vec4f(1, 1, 1, 1) + uber1.color = Vec4f(1, 1, 1, 1) + uber1.diffuse_weight = Vec4f(0, 0, 0, 0) + uber1.diffuse_roughness = Vec4f(1, 1, 1, 1) + uber1.reflection_color = Vec4f(0.996078, 0.858824, 0.639216, 0) + uber1.reflection_weight = Vec4f(1, 1, 1, 1) + uber1.reflection_roughness = Vec4f(0, 0, 0, 0) + uber1.reflection_anisotropy = Vec4f(0, 0, 0, 0) + uber1.reflection_anisotropy_rotation = Vec4f(0, 0, 0, 0) + uber1.reflection_ior = Vec4f(1.36, 1.36, 1.36, 1.36) + uber1.refraction_color = Vec4f(0.996078, 0.858824, 0.639216, 0) + uber1.refraction_weight = Vec4f(1, 1, 1, 1) + uber1.refraction_roughness = Vec4f(0, 0, 0, 0) + uber1.refraction_ior = Vec4f(1.36, 1.36, 1.36, 1.36) + uber1.refraction_absorption_color = Vec4f(0.996078, 0.858824, 0.639216, 0) + uber1.refraction_absorption_distance = Vec4f(0, 0, 0, 0) + uber1.refraction_caustics = Vec4f(0) + uber1.coating_color = Vec4f(1, 1, 1, 1) + uber1.coating_weight = Vec4f(0, 0, 0, 0) + uber1.coating_roughness = Vec4f(0, 0, 0, 0) + uber1.coating_ior = Vec4f(3, 3, 3, 3) + uber1.coating_metalness = Vec4f(0, 0, 0, 0) + uber1.coating_transmission_color = Vec4f(1, 1, 1, 1) + uber1.coating_thickness = Vec4f(0, 0, 0, 0) + uber1.sheen = Vec4f(1, 1, 1, 1) + uber1.sheen_tint = Vec4f(0, 0, 0, 0) + uber1.sheen_weight = Vec4f(0, 0, 0, 0) + uber1.emission_color = Vec4f(1, 1, 1, 1) + uber1.emission_weight = Vec3f(0, 0, 0) + uber1.transparency = Vec4f(0, 0, 0, 0) + uber1.sss_scatter_color = Vec4f(0, 0, 0, 0) + uber1.sss_scatter_distance = Vec4f(0, 0, 0, 0) + uber1.sss_scatter_direction = Vec4f(0, 0, 0, 0) + uber1.sss_weight = Vec4f(0, 0, 0, 0) + uber1.backscatter_weight = Vec4f(0, 0, 0, 0) + uber1.backscatter_color = Vec4f(1, 1, 1, 1) uber1.reflection_mode = UInt(RPR.RPR_UBER_MATERIAL_IOR_MODE_PBR) uber1.emission_mode = UInt(RPR.RPR_UBER_MATERIAL_EMISSION_MODE_SINGLESIDED) @@ -77,131 +77,131 @@ end begin - uber2.color = Vec4f(0.501961f0,0.0f0,0.0f0,0.0f0) - uber2.diffuse_weight = Vec4f(1.0f0,1.0f0,1.0f0,1.0f0) - uber2.diffuse_roughness = Vec4f(0.500000f0,0.500000f0,0.500000f0,0.500000f0) - uber2.reflection_color = Vec4f(0.490196f0,0.490196f0,0.490196f0,0.0f0) - uber2.reflection_weight = Vec4f(0.990000f0,0.990000f0,0.990000f0,0.990000f0) - uber2.reflection_roughness = Vec4f(0.008000f0,0.008000f0,0.008000f0,0.008000f0) - uber2.reflection_anisotropy = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.reflection_anisotropy_rotation = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) + uber2.color = Vec4f(0.501961f0, 0.0f0, 0.0f0, 0.0f0) + uber2.diffuse_weight = Vec4f(1.0f0, 1.0f0, 1.0f0, 1.0f0) + uber2.diffuse_roughness = Vec4f(0.500000f0, 0.500000f0, 0.500000f0, 0.500000f0) + uber2.reflection_color = Vec4f(0.490196f0, 0.490196f0, 0.490196f0, 0.0f0) + uber2.reflection_weight = Vec4f(0.990000f0, 0.990000f0, 0.990000f0, 0.990000f0) + uber2.reflection_roughness = Vec4f(0.008000f0, 0.008000f0, 0.008000f0, 0.008000f0) + uber2.reflection_anisotropy = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.reflection_anisotropy_rotation = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) uber2.reflection_mode = 1 - uber2.reflection_ior = Vec4f(1.460000f0,1.460000f0,1.460000f0,1.460000f0) - uber2.refraction_color = Vec4f(1.0f0,1.0f0,1.0f0,1.0f0) - uber2.refraction_weight = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.refraction_roughness = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.refraction_ior = Vec4f(1.500000f0,1.500000f0,1.500000f0,1.500000f0) + uber2.reflection_ior = Vec4f(1.460000f0, 1.460000f0, 1.460000f0, 1.460000f0) + uber2.refraction_color = Vec4f(1.0f0, 1.0f0, 1.0f0, 1.0f0) + uber2.refraction_weight = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.refraction_roughness = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.refraction_ior = Vec4f(1.500000f0, 1.500000f0, 1.500000f0, 1.500000f0) uber2.refraction_thin_surface = Vec4f(0) - uber2.refraction_absorption_color = Vec4f(1.0f0,1.0f0,1.0f0,0.0f0) - uber2.refraction_absorption_distance = Vec4f(1.0f0,1.0f0,1.0f0,0.0f0) + uber2.refraction_absorption_color = Vec4f(1.0f0, 1.0f0, 1.0f0, 0.0f0) + uber2.refraction_absorption_distance = Vec4f(1.0f0, 1.0f0, 1.0f0, 0.0f0) uber2.refraction_caustics = 1 - uber2.coating_color = Vec4f(0.490196f0,0.490196f0,0.490196f0,0.0f0) - uber2.coating_weight = Vec4f(1.0f0,1.0f0,1.0f0,1.0f0) - uber2.coating_roughness = Vec4f(0.008000f0,0.008000f0,0.008000f0,0.008000f0) + uber2.coating_color = Vec4f(0.490196f0, 0.490196f0, 0.490196f0, 0.0f0) + uber2.coating_weight = Vec4f(1.0f0, 1.0f0, 1.0f0, 1.0f0) + uber2.coating_roughness = Vec4f(0.008000f0, 0.008000f0, 0.008000f0, 0.008000f0) uber2.coating_mode = 1 - uber2.coating_ior = Vec4f(1.460000f0,1.460000f0,1.460000f0,1.460000f0) - uber2.coating_metalness = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.coating_transmission_color = Vec4f(0.0f0,0.0f0,0.0f0,1.0f0) - uber2.coating_thickness = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sheen = Vec4f(1.0f0,1.0f0,1.0f0,1.0f0) - uber2.sheen_tint = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sheen_weight = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.emission_color = Vec4f(1.0f0,1.0f0,1.0f0,1.0f0) - uber2.emission_weight = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) + uber2.coating_ior = Vec4f(1.460000f0, 1.460000f0, 1.460000f0, 1.460000f0) + uber2.coating_metalness = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.coating_transmission_color = Vec4f(0.0f0, 0.0f0, 0.0f0, 1.0f0) + uber2.coating_thickness = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sheen = Vec4f(1.0f0, 1.0f0, 1.0f0, 1.0f0) + uber2.sheen_tint = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sheen_weight = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.emission_color = Vec4f(1.0f0, 1.0f0, 1.0f0, 1.0f0) + uber2.emission_weight = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) uber2.emission_mode = 1 - uber2.transparency = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sss_scatter_color = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sss_scatter_distance = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sss_scatter_direction = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sss_weight = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) + uber2.transparency = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sss_scatter_color = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sss_scatter_distance = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sss_scatter_direction = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sss_weight = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) uber2.sss_multiscatter = false - uber2.backscatter_weight = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.backscatter_color = Vec4f(0.501961f0,0.0f0,0.0f0,0.0f0) + uber2.backscatter_weight = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.backscatter_color = Vec4f(0.501961f0, 0.0f0, 0.0f0, 0.0f0) end begin - uber3.color = Vec4(0.752941,0.596078,0.443137,0.0) - uber3.diffuse_weight = Vec4(1.0,1.0,1.0,1.0) - uber3.diffuse_roughness = Vec4(0.500000,0.500000,0.500000,0.500000) - uber3.reflection_color = Vec4(0.666667,0.490196,0.313726,0.0) - uber3.reflection_weight = Vec4(1.0,1.0,1.0,1.0) - uber3.reflection_roughness = Vec4(0.300000,0.300000,0.300000,0.300000) - uber3.reflection_anisotropy = Vec4(0.0,0.0,0.0,0.0) - uber3.reflection_anisotropy_rotation = Vec4(0.0,0.0,0.0,0.0) + uber3.color = Vec4(0.752941, 0.596078, 0.443137, 0.0) + uber3.diffuse_weight = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.diffuse_roughness = Vec4(0.500000, 0.500000, 0.500000, 0.500000) + uber3.reflection_color = Vec4(0.666667, 0.490196, 0.313726, 0.0) + uber3.reflection_weight = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.reflection_roughness = Vec4(0.300000, 0.300000, 0.300000, 0.300000) + uber3.reflection_anisotropy = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.reflection_anisotropy_rotation = Vec4(0.0, 0.0, 0.0, 0.0) uber3.reflection_mode = 2 - uber3.reflection_ior = Vec4(1.0,1.0,1.0,1.0) - uber3.refraction_color = Vec4(1.0,1.0,1.0,1.0) - uber3.refraction_weight = Vec4(0.0,0.0,0.0,0.0) - uber3.refraction_roughness = Vec4(0.0,0.0,0.0,0.0) - uber3.refraction_ior = Vec4(1.500000,1.500000,1.500000,1.500000) + uber3.reflection_ior = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.refraction_color = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.refraction_weight = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.refraction_roughness = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.refraction_ior = Vec4(1.500000, 1.500000, 1.500000, 1.500000) uber3.refraction_thin_surface = 0 - uber3.refraction_absorption_color = Vec4(1.0,1.0,1.0,0.0) - uber3.refraction_absorption_distance = Vec4(1.0,1.0,1.0,0.0) + uber3.refraction_absorption_color = Vec4(1.0, 1.0, 1.0, 0.0) + uber3.refraction_absorption_distance = Vec4(1.0, 1.0, 1.0, 0.0) uber3.refraction_caustics = 1 - uber3.coating_color = Vec4(0.752941,0.596078,0.443137,0.0) - uber3.coating_weight = Vec4(1.0,1.0,1.0,1.0) - uber3.coating_roughness = Vec4(0.420000,0.420000,0.420000,0.420000) + uber3.coating_color = Vec4(0.752941, 0.596078, 0.443137, 0.0) + uber3.coating_weight = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.coating_roughness = Vec4(0.420000, 0.420000, 0.420000, 0.420000) uber3.coating_mode = 1 - uber3.coating_ior = Vec4(1.700000,1.700000,1.700000,1.700000) - uber3.coating_metalness = Vec4(0.0,0.0,0.0,0.0) - uber3.coating_transmission_color = Vec4(0.0,0.0,0.0,1.0) - uber3.coating_thickness = Vec4(0.0,0.0,0.0,0.0) - uber3.sheen = Vec4(1.0,1.0,1.0,1.0) - uber3.sheen_tint = Vec4(0.0,0.0,0.0,0.0) - uber3.sheen_weight = Vec4(0.0,0.0,0.0,0.0) - uber3.emission_color = Vec4(1.0,1.0,1.0,1.0) - uber3.emission_weight = Vec4(0.0,0.0,0.0,0.0) + uber3.coating_ior = Vec4(1.700000, 1.700000, 1.700000, 1.700000) + uber3.coating_metalness = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.coating_transmission_color = Vec4(0.0, 0.0, 0.0, 1.0) + uber3.coating_thickness = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sheen = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.sheen_tint = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sheen_weight = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.emission_color = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.emission_weight = Vec4(0.0, 0.0, 0.0, 0.0) uber3.emission_mode = 1 - uber3.transparency = Vec4(0.0,0.0,0.0,0.0) - uber3.sss_scatter_color = Vec4(0.0,0.0,0.0,0.0) - uber3.sss_scatter_distance = Vec4(0.0,0.0,0.0,0.0) - uber3.sss_scatter_direction = Vec4(0.0,0.0,0.0,0.0) - uber3.sss_weight = Vec4(0.0,0.0,0.0,0.0) + uber3.transparency = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sss_scatter_color = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sss_scatter_distance = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sss_scatter_direction = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sss_weight = Vec4(0.0, 0.0, 0.0, 0.0) uber3.sss_multiscatter = 0 - uber3.backscatter_weight = Vec4(0.0,0.0,0.0,0.0) - uber3.backscatter_color = Vec4(0.752941,0.596078,0.443137,0.0) + uber3.backscatter_weight = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.backscatter_color = Vec4(0.752941, 0.596078, 0.443137, 0.0) end begin - uber4.color = Vec4f(1.0,1.0,1.0,1.0) - uber4.diffuse_weight = Vec4f(0.0,0.0,0.0,0.0) - uber4.diffuse_roughness = Vec4f(1.0,1.0,1.0,1.0) - uber4.reflection_color = Vec4f(0.501961,0.501961,0.501961,0.0) - uber4.reflection_weight = Vec4f(1.0,1.0,1.0,1.0) - uber4.reflection_roughness = Vec4f(0.0,0.0,0.0,0.0) - uber4.reflection_anisotropy = Vec4f(0.0,0.0,0.0,0.0) - uber4.reflection_anisotropy_rotation = Vec4f(0.0,0.0,0.0,0.0) + uber4.color = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.diffuse_weight = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.diffuse_roughness = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.reflection_color = Vec4f(0.501961, 0.501961, 0.501961, 0.0) + uber4.reflection_weight = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.reflection_roughness = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.reflection_anisotropy = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.reflection_anisotropy_rotation = Vec4f(0.0, 0.0, 0.0, 0.0) uber4.reflection_mode = 1 - uber4.reflection_ior = Vec4f(1.330000,1.330000,1.330000,1.330000) - uber4.refraction_color = Vec4f(0.501961,0.898039,0.996078,0.0) - uber4.refraction_weight = Vec4f(1.0,1.0,1.0,1.0) - uber4.refraction_roughness = Vec4f(0.0,0.0,0.0,0.0) - uber4.refraction_ior = Vec4f(1.330000,1.330000,1.330000,1.330000) + uber4.reflection_ior = Vec4f(1.330000, 1.330000, 1.330000, 1.330000) + uber4.refraction_color = Vec4f(0.501961, 0.898039, 0.996078, 0.0) + uber4.refraction_weight = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.refraction_roughness = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.refraction_ior = Vec4f(1.330000, 1.330000, 1.330000, 1.330000) uber4.refraction_thin_surface = 0 - uber4.refraction_absorption_color = Vec4f(0.501961,0.898039,0.996078,0.0) - uber4.refraction_absorption_distance = Vec4f(0.0,0.0,0.0,0.0) + uber4.refraction_absorption_color = Vec4f(0.501961, 0.898039, 0.996078, 0.0) + uber4.refraction_absorption_distance = Vec4f(0.0, 0.0, 0.0, 0.0) uber4.refraction_caustics = 0 - uber4.coating_color = Vec4f(1.0,1.0,1.0,1.0) - uber4.coating_weight = Vec4f(0.0,0.0,0.0,0.0) - uber4.coating_roughness = Vec4f(0.0,0.0,0.0,0.0) + uber4.coating_color = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.coating_weight = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.coating_roughness = Vec4f(0.0, 0.0, 0.0, 0.0) uber4.coating_mode = 1 - uber4.coating_ior = Vec4f(3.0,3.0,3.0,3.0) - uber4.coating_metalness = Vec4f(0.0,0.0,0.0,0.0) - uber4.coating_transmission_color = Vec4f(1.0,1.0,1.0,1.0) - uber4.coating_thickness = Vec4f(0.0,0.0,0.0,0.0) - uber4.sheen = Vec4f(1.0,1.0,1.0,1.0) - uber4.sheen_tint = Vec4f(0.0,0.0,0.0,0.0) - uber4.sheen_weight = Vec4f(0.0,0.0,0.0,0.0) - uber4.emission_color = Vec4f(1.0,1.0,1.0,1.0) - uber4.emission_weight = Vec4f(0.0,0.0,0.0,0.0) + uber4.coating_ior = Vec4f(3.0, 3.0, 3.0, 3.0) + uber4.coating_metalness = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.coating_transmission_color = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.coating_thickness = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sheen = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.sheen_tint = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sheen_weight = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.emission_color = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.emission_weight = Vec4f(0.0, 0.0, 0.0, 0.0) uber4.emission_mode = 1 - uber4.transparency = Vec4f(0.0,0.0,0.0,0.0) - uber4.sss_scatter_color = Vec4f(0.0,0.0,0.0,0.0) - uber4.sss_scatter_distance = Vec4f(0.0,0.0,0.0,0.0) - uber4.sss_scatter_direction = Vec4f(0.0,0.0,0.0,0.0) - uber4.sss_weight = Vec4f(0.0,0.0,0.0,0.0) + uber4.transparency = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sss_scatter_color = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sss_scatter_distance = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sss_scatter_direction = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sss_weight = Vec4f(0.0, 0.0, 0.0, 0.0) uber4.sss_multiscatter = 0 - uber4.backscatter_weight = Vec4f(0.0,0.0,0.0,0.0) - uber4.backscatter_color = Vec4f(1.0,1.0,1.0,1.0) + uber4.backscatter_weight = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.backscatter_color = Vec4f(1.0, 1.0, 1.0, 1.0) end diff --git a/RPRMakie/test/runtests.jl b/RPRMakie/test/runtests.jl index 4a66aafb4bb..f64afa53fdb 100644 --- a/RPRMakie/test/runtests.jl +++ b/RPRMakie/test/runtests.jl @@ -1,9 +1,9 @@ using RPRMakie using Test -RPRMakie.activate!(resource=RPR.RPR_CREATION_FLAGS_ENABLE_CPU, iterations=50) -f, ax, pl = meshscatter(rand(Point3f, 100), color=:blue) +RPRMakie.activate!(resource = RPR.RPR_CREATION_FLAGS_ENABLE_CPU, iterations = 50) +f, ax, pl = meshscatter(rand(Point3f, 100), color = :blue) out = joinpath(@__DIR__, "recorded") -isdir(out) && rm(out; recursive=true, force=true) +isdir(out) && rm(out; recursive = true, force = true) mkdir(out) save(joinpath(out, "test.png"), ax.scene); diff --git a/ReferenceTests/src/database.jl b/ReferenceTests/src/database.jl index 99edfd79b1e..639ec8744de 100644 --- a/ReferenceTests/src/database.jl +++ b/ReferenceTests/src/database.jl @@ -4,7 +4,9 @@ function used_functions(code) if @capture(x, f_(xs__)) push!(used_functions, Symbol(string(f))) end - if @capture(x, f_(xs__) do; body__; end) + if @capture(x, f_(xs__) do + body__ + end) push!(used_functions, Symbol(string(f))) end return x @@ -27,7 +29,7 @@ Records `code` and saves the result to `joinpath(ReferenceTests.RECORDING_DIR[], macro reference_test(name, code) title = string(name) funcs = used_functions(code) - skip = (title in SKIP_TITLES) || any(x-> x in funcs, SKIP_FUNCTIONS) + skip = (title in SKIP_TITLES) || any(x -> x in funcs, SKIP_FUNCTIONS) return quote @testset $(title) begin if $skip @@ -37,7 +39,7 @@ macro reference_test(name, code) error("title must be unique. Duplicate title: $(title)") end println("running $(lpad(COUNTER[] += 1, 3)): $($title)") - Makie.set_theme!(resolution=(500, 500)) + Makie.set_theme!(resolution = (500, 500)) ReferenceTests.RNG.seed_rng!() result = let $(esc(code)) @@ -55,24 +57,24 @@ end Helper, to more easily save all kind of results from the test database """ function save_result(path::String, scene::Makie.FigureLike) - isfile(path * ".png") && rm(path * ".png"; force=true) + isfile(path * ".png") && rm(path * ".png"; force = true) FileIO.save(path * ".png", scene) return true end function save_result(path::String, stream::VideoStream) - isfile(path * ".mp4") && rm(path * ".mp4"; force=true) + isfile(path * ".mp4") && rm(path * ".mp4"; force = true) FileIO.save(path * ".mp4", stream) return true end function save_result(path::String, object) - isfile(path) && rm(path; force=true) + isfile(path) && rm(path; force = true) FileIO.save(path, object) return true end -function mark_broken_tests(title_excludes = []; functions=[]) +function mark_broken_tests(title_excludes = []; functions = []) empty!(SKIP_TITLES) empty!(SKIP_FUNCTIONS) union!(SKIP_TITLES, title_excludes) @@ -87,7 +89,7 @@ macro include_reference_tests(path) include_path = isdir($path) ? $path : joinpath(@__DIR__, "tests", $path) recording_dir = joinpath($toplevel_folder, "recorded_reference_images", name) if isdir(recording_dir) - rm(recording_dir; force=true, recursive=true) + rm(recording_dir; force = true, recursive = true) end ReferenceTests.RECORDING_DIR[] = joinpath(recording_dir, "recorded") mkpath(joinpath(recording_dir, "recorded")) diff --git a/ReferenceTests/src/image_download.jl b/ReferenceTests/src/image_download.jl index 8f3076fc100..ec219185214 100644 --- a/ReferenceTests/src/image_download.jl +++ b/ReferenceTests/src/image_download.jl @@ -5,7 +5,7 @@ function last_major_version() return "v" * string(VersionNumber(version.major, version.minor)) end -function download_refimages(tag=last_major_version(); name="refimages") +function download_refimages(tag = last_major_version(); name = "refimages") url = "https://github.com/MakieOrg/Makie.jl/releases/download/$(tag)/$(name).tar" images_tar = basedir("$(name).tar") images = basedir(name) @@ -17,7 +17,7 @@ function download_refimages(tag=last_major_version(); name="refimages") end end !isfile(images_tar) && download(url, images_tar) - isdir(images) && rm(images, recursive=true, force=true) + isdir(images) && rm(images, recursive = true, force = true) Tar.extract(images_tar, images) return images end diff --git a/ReferenceTests/src/runtests.jl b/ReferenceTests/src/runtests.jl index 13526823361..d6322003aa4 100644 --- a/ReferenceTests/src/runtests.jl +++ b/ReferenceTests/src/runtests.jl @@ -11,7 +11,7 @@ function get_frames(video) if length(aframes) > 10 # we don't want to compare too many frames since it's time costly # so we just compare 10 random frames if more than 10 - samples = range(1, stop=length(aframes), length=10) + samples = range(1, stop = length(aframes), length = 10) istep = round(Int, length(aframes) / 10) samples = 1:istep:length(aframes) aframes = aframes[samples] @@ -20,11 +20,11 @@ function get_frames(video) end end -function compare_media(a::Matrix, b::Matrix; sigma=[1,1]) +function compare_media(a::Matrix, b::Matrix; sigma = [1, 1]) Images.test_approx_eq_sigma_eps(a, b, sigma, Inf) end -function compare_media(a, b; sigma=[1,1]) +function compare_media(a, b; sigma = [1, 1]) file, ext = splitext(a) if ext in (".png", ".jpg", ".jpeg", ".JPEG", ".JPG") imga = load(a) @@ -34,7 +34,7 @@ function compare_media(a, b; sigma=[1,1]) return Inf end conv(x) = convert(Matrix{RGBf}, x) - return compare_media(conv(imga), conv(imgb), sigma=sigma) + return compare_media(conv(imga), conv(imgb), sigma = sigma) elseif ext in (".mp4", ".gif") aframes, bframes = get_frames(a, b) # Frames can differ in length, which usually shouldn't be the case but can happen @@ -44,7 +44,7 @@ function compare_media(a, b; sigma=[1,1]) @warn "not the same number of frames in video, difference will be Inf" return Inf end - return mean(compare_media.(aframes, bframes; sigma=sigma)) + return mean(compare_media.(aframes, bframes; sigma = sigma)) else error("Unknown media extension: $ext") end @@ -56,9 +56,9 @@ function get_all_relative_filepaths_recursively(dir) end end -function record_comparison(base_folder::String; record_folder_name="recorded", reference_name = basename(base_folder), tag=last_major_version()) +function record_comparison(base_folder::String; record_folder_name = "recorded", reference_name = basename(base_folder), tag = last_major_version()) record_folder = joinpath(base_folder, record_folder_name) - reference_folder = download_refimages(tag; name=reference_name) + reference_folder = download_refimages(tag; name = reference_name) # we copy the reference images into the output folder, since we want to upload it all as an artifact, to know against what images we compared cp(reference_folder, joinpath(base_folder, "reference")) testimage_paths = get_all_relative_filepaths_recursively(record_folder) @@ -90,7 +90,7 @@ function test_comparison(scores; threshold) end end -function compare(relative_test_paths::Vector{String}, reference_dir::String, record_dir; o_refdir=reference_dir, missing_refimages=String[], scores=Dict{String,Float64}()) +function compare(relative_test_paths::Vector{String}, reference_dir::String, record_dir; o_refdir = reference_dir, missing_refimages = String[], scores = Dict{String,Float64}()) for relative_test_path in relative_test_paths ref_path = joinpath(reference_dir, relative_test_path) rec_path = joinpath(record_dir, relative_test_path) diff --git a/ReferenceTests/src/stable_rng.jl b/ReferenceTests/src/stable_rng.jl index ba257b3dd6b..3a7d73cbc86 100644 --- a/ReferenceTests/src/stable_rng.jl +++ b/ReferenceTests/src/stable_rng.jl @@ -11,11 +11,11 @@ randn(args...) = Base.randn(STABLE_RNG, args...) seed_rng!() = Random.seed!(STABLE_RNG, 123) -function Base.rand(r::StableRNGs.LehmerRNG, ::Random.SamplerType{T}) where T <: ColorAlpha +function Base.rand(r::StableRNGs.LehmerRNG, ::Random.SamplerType{T}) where T<:ColorAlpha return T(Base.rand(r), Base.rand(r), Base.rand(r), Base.rand(r)) end -function Base.rand(r::StableRNGs.LehmerRNG, ::Random.SamplerType{T}) where T <: AbstractRGB +function Base.rand(r::StableRNGs.LehmerRNG, ::Random.SamplerType{T}) where T<:AbstractRGB return T(Base.rand(r), Base.rand(r), Base.rand(r)) end diff --git a/ReferenceTests/src/tests/attributes.jl b/ReferenceTests/src/tests/attributes.jl index e81f432d05f..052ab6bdd22 100644 --- a/ReferenceTests/src/tests/attributes.jl +++ b/ReferenceTests/src/tests/attributes.jl @@ -1,39 +1,39 @@ @reference_test "glowcolor, glowwidth" begin - scatter(RNG.randn(10), color=:blue, glowcolor=:orange, glowwidth=10) + scatter(RNG.randn(10), color = :blue, glowcolor = :orange, glowwidth = 10) end @reference_test "isorange, isovalue" begin - r = range(-1, stop=1, length=100) - matr = [(x.^2 + y.^2 + z.^2) for x = r, y = r, z = r] - volume(matr .* (matr .> 1.4), algorithm=:iso, isorange=0.05, isovalue=1.7) + r = range(-1, stop = 1, length = 100) + matr = [(x .^ 2 + y .^ 2 + z .^ 2) for x in r, y in r, z in r] + volume(matr .* (matr .> 1.4), algorithm = :iso, isorange = 0.05, isovalue = 1.7) end @reference_test "levels" begin x = LinRange(-1, 1, 20) y = LinRange(-1, 1, 20) z = x .* y' - contour(x, y, z, linewidth=3, colormap=:colorwheel, levels=50) + contour(x, y, z, linewidth = 3, colormap = :colorwheel, levels = 50) end @reference_test "position" begin - fig, ax, sc = scatter(RNG.rand(10), color=:red) - text!(ax, 5, 1.1, text = "adding text", fontsize=0.6) + fig, ax, sc = scatter(RNG.rand(10), color = :red) + text!(ax, 5, 1.1, text = "adding text", fontsize = 0.6) fig end @reference_test "rotation" begin - text("Hello World", rotation=1.1) + text("Hello World", rotation = 1.1) end @reference_test "shading" begin - mesh(Sphere(Point3f(0), 1f0), color=:orange, shading=false) + mesh(Sphere(Point3f(0), 1f0), color = :orange, shading = false) end @reference_test "visible" begin fig = Figure() colors = Makie.resample(to_colormap(:deep), 20) - scatter(fig[1, 1], RNG.randn(20), color=colors, markersize=10, visible=true) - scatter(fig[1, 2], RNG.randn(20), color=colors, markersize=10, visible=false) + scatter(fig[1, 1], RNG.randn(20), color = colors, markersize = 10, visible = true) + scatter(fig[1, 2], RNG.randn(20), color = colors, markersize = 10, visible = false) fig end diff --git a/ReferenceTests/src/tests/examples2d.jl b/ReferenceTests/src/tests/examples2d.jl index 04c134fbe1f..47185cf1227 100644 --- a/ReferenceTests/src/tests/examples2d.jl +++ b/ReferenceTests/src/tests/examples2d.jl @@ -32,122 +32,122 @@ end @reference_test "poly and colormap" begin # example by @Paulms from MakieOrg/Makie.jl#310 points = Point2f[[0.0, 0.0], [0.1, 0.0], [0.1, 0.1], [0.0, 0.1]] - colors = [0.0 ,0.0, 0.5, 0.0] - fig, ax, polyplot = poly(points, color=colors, colorrange=(0.0, 1.0)) + colors = [0.0, 0.0, 0.5, 0.0] + fig, ax, polyplot = poly(points, color = colors, colorrange = (0.0, 1.0)) points = Point2f[[0.1, 0.1], [0.2, 0.1], [0.2, 0.2], [0.1, 0.2]] - colors = [0.5,0.5,1.0,0.3] - poly!(ax, points, color=colors, colorrange=(0.0, 1.0)) + colors = [0.5, 0.5, 1.0, 0.3] + poly!(ax, points, color = colors, colorrange = (0.0, 1.0)) fig end @reference_test "quiver" begin - x = range(-2, stop=2, length=21) - arrows(x, x, RNG.rand(21, 21), RNG.rand(21, 21), arrowsize=0.05) + x = range(-2, stop = 2, length = 21) + arrows(x, x, RNG.rand(21, 21), RNG.rand(21, 21), arrowsize = 0.05) end @reference_test "Arrows on hemisphere" begin s = Sphere(Point3f(0), 0.9f0) - fig, ax, meshplot = mesh(s, transparency=true, alpha=0.05) + fig, ax, meshplot = mesh(s, transparency = true, alpha = 0.05) pos = decompose(Point3f, s) dirs = decompose_normals(s) - arrows!(ax, pos, dirs, arrowcolor=:red, arrowsize=0.1, linecolor=:red) + arrows!(ax, pos, dirs, arrowcolor = :red, arrowsize = 0.1, linecolor = :red) fig end @reference_test "image" begin fig = Figure() - image(fig[1,1], Makie.logo(), axis = (; aspect = DataAspect())) + image(fig[1, 1], Makie.logo(), axis = (; aspect = DataAspect())) image(fig[1, 2], RNG.rand(100, 500), axis = (; aspect = DataAspect())) fig end @reference_test "FEM polygon 2D" begin coordinates = [ - 0.0 0.0; - 0.5 0.0; - 1.0 0.0; - 0.0 0.5; - 0.5 0.5; - 1.0 0.5; - 0.0 1.0; - 0.5 1.0; - 1.0 1.0; + 0.0 0.0 + 0.5 0.0 + 1.0 0.0 + 0.0 0.5 + 0.5 0.5 + 1.0 0.5 + 0.0 1.0 + 0.5 1.0 + 1.0 1.0 ] connectivity = [ - 1 2 5; - 1 4 5; - 2 3 6; - 2 5 6; - 4 5 8; - 4 7 8; - 5 6 9; - 5 8 9; + 1 2 5 + 1 4 5 + 2 3 6 + 2 5 6 + 4 5 8 + 4 7 8 + 5 6 9 + 5 8 9 ] color = [0.0, 0.0, 0.0, 0.0, -0.375, 0.0, 0.0, 0.0, 0.0] - poly(coordinates, connectivity, color=color, strokecolor=(:black, 0.6), strokewidth=4) + poly(coordinates, connectivity, color = color, strokecolor = (:black, 0.6), strokewidth = 4) end @reference_test "FEM mesh 2D" begin coordinates = [ - 0.0 0.0; - 0.5 0.0; - 1.0 0.0; - 0.0 0.5; - 0.5 0.5; - 1.0 0.5; - 0.0 1.0; - 0.5 1.0; - 1.0 1.0; + 0.0 0.0 + 0.5 0.0 + 1.0 0.0 + 0.0 0.5 + 0.5 0.5 + 1.0 0.5 + 0.0 1.0 + 0.5 1.0 + 1.0 1.0 ] connectivity = [ - 1 2 5; - 1 4 5; - 2 3 6; - 2 5 6; - 4 5 8; - 4 7 8; - 5 6 9; - 5 8 9; + 1 2 5 + 1 4 5 + 2 3 6 + 2 5 6 + 4 5 8 + 4 7 8 + 5 6 9 + 5 8 9 ] color = [0.0, 0.0, 0.0, 0.0, -0.375, 0.0, 0.0, 0.0, 0.0] - fig, ax, meshplot = mesh(coordinates, connectivity, color=color, shading=false) - wireframe!(ax, meshplot[1], color=(:black, 0.6), linewidth=3) + fig, ax, meshplot = mesh(coordinates, connectivity, color = color, shading = false) + wireframe!(ax, meshplot[1], color = (:black, 0.6), linewidth = 3) fig end @reference_test "colored triangle" begin mesh( - [(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], color=[:red, :green, :blue], - shading=false + [(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], color = [:red, :green, :blue], + shading = false ) end @reference_test "colored triangle with poly" begin poly( [(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], - color=[:red, :green, :blue], - strokecolor=:black, strokewidth=2 + color = [:red, :green, :blue], + strokecolor = :black, strokewidth = 2 ) end @reference_test "scale_plot" begin - t = range(0, stop=1, length=500) # time steps + t = range(0, stop = 1, length = 500) # time steps θ = (6π) .* t # angles x = # x coords of spiral - y = # y coords of spiral - lines(t .* cos.(θ), t .* sin.(θ); - color=t, colormap=:algae, linewidth=8, axis = (; aspect = DataAspect())) + y = # y coords of spiral + lines(t .* cos.(θ), t .* sin.(θ); + color = t, colormap = :algae, linewidth = 8, axis = (; aspect = DataAspect())) end @reference_test "Polygons" begin points = decompose(Point2f, Circle(Point2f(50), 50f0)) - fig, ax, pol = poly(points, color=:gray, strokewidth=10, strokecolor=:red) + fig, ax, pol = poly(points, color = :gray, strokewidth = 10, strokecolor = :red) # Optimized forms - poly!(ax, [Circle(Point2f(50 + 300), 50f0)], color=:gray, strokewidth=10, strokecolor=:red) - poly!(ax, [Circle(Point2f(50 + i, 50 + i), 10f0) for i = 1:100:400], color=:red) - poly!(ax, [Rect2f(50 + i, 50 + i, 20, 20) for i = 1:100:400], strokewidth=2, strokecolor=:green) + poly!(ax, [Circle(Point2f(50 + 300), 50f0)], color = :gray, strokewidth = 10, strokecolor = :red) + poly!(ax, [Circle(Point2f(50 + i, 50 + i), 10f0) for i in 1:100:400], color = :red) + poly!(ax, [Rect2f(50 + i, 50 + i, 20, 20) for i in 1:100:400], strokewidth = 2, strokecolor = :green) linesegments!(ax, - [Point2f(50 + i, 50 + i) => Point2f(i + 70, i + 70) for i = 1:100:400], linewidth=8, color=:purple + [Point2f(50 + i, 50 + i) => Point2f(i + 70, i + 70) for i in 1:100:400], linewidth = 8, color = :purple ) fig end @@ -155,10 +155,10 @@ end @reference_test "Text Annotation" begin text( ". This is an annotation!", - position=(300, 200), - align=(:center, :center), - fontsize=60, - font="Blackchancery" + position = (300, 200), + align = (:center, :center), + fontsize = 60, + font = "Blackchancery" ) end @@ -167,17 +167,17 @@ end ax = fig[1, 1] = Axis(fig) pos = (500, 500) posis = Point2f[] - for r in range(0, stop=2pi, length=20) + for r in range(0, stop = 2pi, length = 20) p = pos .+ (sin(r) * 100.0, cos(r) * 100) push!(posis, p) text!(ax, "test", - position=p, - fontsize=50, - rotation=1.5pi - r, - align=(:center, :center) + position = p, + fontsize = 50, + rotation = 1.5pi - r, + align = (:center, :center) ) end - scatter!(ax, posis, markersize=10) + scatter!(ax, posis, markersize = 10) fig end @@ -185,12 +185,12 @@ end # Sample 100 Brownian motion path and plot the mean trajectory together # with a ±1σ band (visualizing uncertainty as marginal standard deviation). n, m = 100, 101 - t = range(0, 1, length=m) - X = cumsum(RNG.randn(n, m), dims=2) + t = range(0, 1, length = m) + X = cumsum(RNG.randn(n, m), dims = 2) X = X .- X[:, 1] - μ = vec(mean(X, dims=1)) # mean + μ = vec(mean(X, dims = 1)) # mean lines(t, μ) # plot mean line - σ = vec(std(X, dims=1)) # stddev + σ = vec(std(X, dims = 1)) # stddev band!(t, μ + σ, μ - σ) # plot stddev band current_figure() end @@ -199,8 +199,8 @@ end v(x::Point2{T}, t) where T = Point2{T}(one(T) * x[2] * t, 4 * x[1]) sf = Observable(Base.Fix2(v, 0e0)) title_str = Observable("t = 0.00") - sp = streamplot(sf, -2..2, -2..2; - linewidth=2, colormap=:magma, axis=(;title=title_str)) + sp = streamplot(sf, -2 .. 2, -2 .. 2; + linewidth = 2, colormap = :magma, axis = (; title = title_str)) Record(sp, LinRange(0, 20, 5)) do i sf[] = Base.Fix2(v, i) title_str[] = "t = $(round(i; sigdigits=2))" @@ -209,9 +209,9 @@ end @reference_test "Line changing colour" begin - fig, ax, lineplot = lines(RNG.rand(10); linewidth=10) + fig, ax, lineplot = lines(RNG.rand(10); linewidth = 10) N = 20 - Record(fig, 1:N; framerate=20) do i + Record(fig, 1:N; framerate = 20) do i lineplot.color = RGBf(i / N, (N - i) / N, 0) # animate scene end end @@ -230,7 +230,7 @@ let P.γ * x[1] - x[2] + P.β ) ff(x) = ff(x, P) - streamplot(ff, -1.5..1.5, -1.5..1.5, colormap=:magma) + streamplot(ff, -1.5 .. 1.5, -1.5 .. 1.5, colormap = :magma) end end @@ -238,7 +238,7 @@ end N = 7 # number of colours in default palette fig = Figure() ax = Axis(fig) - fig[1,1] = ax + fig[1, 1] = ax st = Stepper(fig) xs = 0:9 # data @@ -247,8 +247,8 @@ end plots = map(1:N) do i # plot lines lines!(ax, xs, ys; - color=colors[i], - linewidth=5 + color = colors[i], + linewidth = 5 ) # plot lines with colors end @@ -261,9 +261,9 @@ end (8 - i), pi / 2, (pi / 2 - rot); - color=plots[i].color, - linewidth=5, - linestyle=:dash + color = plots[i].color, + linewidth = 5, + linestyle = :dash ) end @@ -351,17 +351,17 @@ end @reference_test "Simple pie chart" begin - fig = Figure(resolution=(800, 800)) - pie(fig[1, 1], 1:5, color=collect(1:5), axis=(;aspect=DataAspect())) + fig = Figure(resolution = (800, 800)) + pie(fig[1, 1], 1:5, color = collect(1:5), axis = (; aspect = DataAspect())) fig end @reference_test "Hollow pie chart" begin - pie(1:5, color=collect(1.0:5), radius=2, inner_radius=1, axis=(;aspect=DataAspect())) + pie(1:5, color = collect(1.0:5), radius = 2, inner_radius = 1, axis = (; aspect = DataAspect())) end @reference_test "Open pie chart" begin - pie(0.1:0.1:1.0, normalize=false, axis=(;aspect=DataAspect())) + pie(0.1:0.1:1.0, normalize = false, axis = (; aspect = DataAspect())) end @reference_test "intersecting polygon" begin @@ -371,22 +371,22 @@ end @reference_test "Line Function" begin - x = range(0, stop=3pi) + x = range(0, stop = 3pi) fig, ax, lineplot = lines(x, sin.(x)) - lines!(ax, x, cos.(x), color=:blue) + lines!(ax, x, cos.(x), color = :blue) fig end @reference_test "Grouped bar" begin - x1 = ["a_right", "a_right", "a_right", "a_right"] - y1 = [2, 3, -3, -2] - grp_dodge1 = [2, 2, 1, 1] - grp_stack1 = [1, 2, 1, 2] + x1 = ["a_right", "a_right", "a_right", "a_right"] + y1 = [2, 3, -3, -2] + grp_dodge1 = [2, 2, 1, 1] + grp_stack1 = [1, 2, 1, 2] - x2 = ["z_left", "z_left", "z_left", "z_left"] - y2 = [2, 3, -3, -2] - grp_dodge2 = [1, 2, 1, 2] - grp_stack2 = [1, 1, 2, 2] + x2 = ["z_left", "z_left", "z_left", "z_left"] + y2 = [2, 3, -3, -2] + grp_dodge2 = [1, 2, 1, 2] + grp_stack2 = [1, 1, 2, 2] perm = [1, 4, 2, 7, 5, 3, 8, 6] x = [x1; x2][perm] @@ -398,7 +398,7 @@ end tbl = (; x = x, grp_dodge = grp_dodge, grp_stack = grp_stack, y = y) fig = Figure() - ax = Axis(fig[1,1]) + ax = Axis(fig[1, 1]) barplot!(ax, levelcode.(tbl.x), tbl.y, dodge = tbl.grp_dodge, stack = tbl.grp_stack, color = tbl.grp_stack) @@ -486,19 +486,19 @@ end @reference_test "Scatter & Text transformations" begin # Check that transformations apply in `space = :data` - fig, ax, p = scatter(Point2f(100, 0.5), marker = 'a', markersize=50) + fig, ax, p = scatter(Point2f(100, 0.5), marker = 'a', markersize = 50) t = text!(Point2f(100, 0.5), text = "Test", fontsize = 50) translate!(p, -100, 0, 0) translate!(t, -100, 0, 0) # Check that scale and rotate don't act on the marker for scatter (only the position) - p2 = scatter!(ax, Point2f(1, 0), marker= 'a', markersize = 50) - Makie.rotate!(p2, pi/4) + p2 = scatter!(ax, Point2f(1, 0), marker = 'a', markersize = 50) + Makie.rotate!(p2, pi / 4) scale!(p2, 0.5, 0.5, 1) # but do act on glyphs of text t2 = text!(ax, 1, 0, text = "Test", fontsize = 50) - Makie.rotate!(t2, pi/4) + Makie.rotate!(t2, pi / 4) scale!(t2, 0.5, 0.5, 1) xlims!(ax, -0.2, 0.5) @@ -509,39 +509,39 @@ end @reference_test "Array of Images Scatter" begin img = Makie.logo() - scatter(1:2, 1:2, marker = [img, img], markersize=reverse(size(img) ./ 10), axis=(limits=(0.5, 2.5, 0.5, 2.5),)) + scatter(1:2, 1:2, marker = [img, img], markersize = reverse(size(img) ./ 10), axis = (limits = (0.5, 2.5, 0.5, 2.5),)) end @reference_test "Image Scatter different sizes" begin img = Makie.logo() img2 = load(Makie.assetpath("doge.png")) images = [img, img2] - markersize = map(img-> Vec2f(reverse(size(img) ./ 10)), images) - scatter(1:2, 1:2, marker = images, markersize=markersize, axis=(limits=(0.5, 2.5, 0.5, 2.5),)) + markersize = map(img -> Vec2f(reverse(size(img) ./ 10)), images) + scatter(1:2, 1:2, marker = images, markersize = markersize, axis = (limits = (0.5, 2.5, 0.5, 2.5),)) end @reference_test "2D surface with explicit color" begin - surface(1:10, 1:10, ones(10, 10); color = [RGBf(x*y/100, 0, 0) for x in 1:10, y in 1:10], shading = false) + surface(1:10, 1:10, ones(10, 10); color = [RGBf(x * y / 100, 0, 0) for x in 1:10, y in 1:10], shading = false) end @reference_test "heatmap and image colormap interpolation" begin - f = Figure(resolution=(500, 500)) + f = Figure(resolution = (500, 500)) crange = LinRange(0, 255, 10) len = length(crange) img = zeros(Float32, len, len + 2) img[:, 1] .= 255f0 for (i, v) in enumerate(crange) ib = i + 1 - img[2:end-1, ib] .= v - img[1, ib] = 255-v - img[end, ib] = 255-v + img[2:(end - 1), ib] .= v + img[1, ib] = 255 - v + img[end, ib] = 255 - v end - kw(p, interpolate) = (axis=(title="$(p)(interpolate=$(interpolate))", aspect=DataAspect()), interpolate=interpolate, colormap=[:white, :black]) + kw(p, interpolate) = (axis = (title = "$(p)(interpolate=$(interpolate))", aspect = DataAspect()), interpolate = interpolate, colormap = [:white, :black]) for (i, p) in enumerate([heatmap, image]) for (j, interpolate) in enumerate([true, false]) - ax, pl = p(f[i,j], img; kw(p, interpolate)...) + ax, pl = p(f[i, j], img; kw(p, interpolate)...) hidedecorations!(ax) end end @@ -557,11 +557,11 @@ end for (i, cat) in enumerate(categorical) for (j, scale) in enumerate(scales) cg = if cat - cgrad(:viridis, 5; scale = scale, categorical=true) + cgrad(:viridis, 5; scale = scale, categorical = true) else - cgrad(:viridis; scale = scale, categorical=nothing) + cgrad(:viridis; scale = scale, categorical = nothing) end - lines!(ax, Point2f.(LinRange(i+0.1, i+0.9, n), j); color = 1:n, colormap = cg, linewidth = 10) + lines!(ax, Point2f.(LinRange(i + 0.1, i + 0.9, n), j); color = 1:n, colormap = cg, linewidth = 10) end end ax.xticks[] = ((1:length(categorical)) .+ 0.5, ["categorical=false", "categorical=true"]) @@ -570,19 +570,19 @@ end end @reference_test "colormap with specific values" begin - cmap = cgrad([:black,:white,:orange],[0,0.2,1]) - fig = Figure(resolution=(400,200)) - ax = Axis(fig[1,1]) - x = range(0,1,length=50) - scatter!(fig[1,1],Point2.(x,fill(0.,50)),color=x,colormap=cmap) + cmap = cgrad([:black, :white, :orange], [0, 0.2, 1]) + fig = Figure(resolution = (400, 200)) + ax = Axis(fig[1, 1]) + x = range(0, 1, length = 50) + scatter!(fig[1, 1], Point2.(x, fill(0., 50)), color = x, colormap = cmap) hidedecorations!(ax) - Colorbar(fig[2,1],vertical=false,colormap=cmap) + Colorbar(fig[2, 1], vertical = false, colormap = cmap) fig end @reference_test "multi rect with poly" begin # use thick strokewidth, so it will make tests fail if something is missing - poly([Rect2f(0, 0, 1, 1)], color=:green, strokewidth=100, strokecolor=:black) + poly([Rect2f(0, 0, 1, 1)], color = :green, strokewidth = 100, strokecolor = :black) end @reference_test "minor grid & scales" begin @@ -603,7 +603,7 @@ end end @reference_test "Tooltip" begin - fig, ax, p = scatter(Point2f(0,0)) + fig, ax, p = scatter(Point2f(0, 0)) xlims!(ax, -10, 10) ylims!(ax, -5, 5) tt = tooltip!(ax, Point2f(0), text = "left", placement = :left) @@ -656,13 +656,13 @@ end @reference_test "tricontourf manual vs delaunay" begin n = 20 - angles = range(0, 2pi, length = n+1)[1:end-1] - x = [cos.(angles); 2 .* cos.(angles .+ pi/n)] - y = [sin.(angles); 2 .* sin.(angles .+ pi/n)] - z = (x .- 0.5).^2 + (y .- 0.5).^2 .+ 0.5 .* RNG.randn.() + angles = range(0, 2pi, length = n + 1)[1:(end - 1)] + x = [cos.(angles); 2 .* cos.(angles .+ pi / n)] + y = [sin.(angles); 2 .* sin.(angles .+ pi / n)] + z = (x .- 0.5) .^ 2 + (y .- 0.5) .^ 2 .+ 0.5 .* RNG.randn.() triangulation_inner = reduce(hcat, map(i -> [0, 1, n] .+ i, 1:n)) - triangulation_outer = reduce(hcat, map(i -> [n-1, n, 0] .+ i, 1:n)) + triangulation_outer = reduce(hcat, map(i -> [n - 1, n, 0] .+ i, 1:n)) triangulation = hcat(triangulation_inner, triangulation_outer) f, ax, _ = tricontourf(x, y, z, triangulation = triangulation, @@ -678,9 +678,9 @@ end @reference_test "marker offset in data space" begin f = Figure() - ax = Axis(f[1, 1]; xticks=0:1, yticks=0:10) - scatter!(ax, fill(0, 10), 0:9, marker=Rect, marker_offset=Vec2f(0,0), transform_marker=true, markerspace=:data, markersize=Vec2f.(1, LinRange(0.1, 1, 10))) - lines!(ax, Rect(0, 0, 1, 10), color=:red) + ax = Axis(f[1, 1]; xticks = 0:1, yticks = 0:10) + scatter!(ax, fill(0, 10), 0:9, marker = Rect, marker_offset = Vec2f(0, 0), transform_marker = true, markerspace = :data, markersize = Vec2f.(1, LinRange(0.1, 1, 10))) + lines!(ax, Rect(0, 0, 1, 10), color = :red) f end @@ -711,7 +711,7 @@ end y = RNG.rand(300) for i in 2:5 - ax = Axis(f[fldmod1(i-1, 2)...], title = "bins = $i", aspect = DataAspect()) + ax = Axis(f[fldmod1(i - 1, 2)...], title = "bins = $i", aspect = DataAspect()) hexbin!(ax, x, y, bins = i) wireframe!(ax, Rect2f(Point2f.(x, y)), color = :red) scatter!(ax, x, y, color = :red, markersize = 5) @@ -727,7 +727,7 @@ end y = RNG.rand(300) for i in 2:5 - ax = Axis(f[fldmod1(i-1, 2)...], title = "bins = (3, $i)", aspect = DataAspect()) + ax = Axis(f[fldmod1(i - 1, 2)...], title = "bins = (3, $i)", aspect = DataAspect()) hexbin!(ax, x, y, bins = (3, i)) wireframe!(ax, Rect2f(Point2f.(x, y)), color = :red) scatter!(ax, x, y, color = :red, markersize = 5) @@ -790,7 +790,7 @@ end f = Figure() hexbin(f[1, 1], x, y, bins = 40, axis = (aspect = DataAspect(), title = "scale = identity")) - hexbin(f[1, 2], x, y, bins = 40, scale=log10, + hexbin(f[1, 2], x, y, bins = 40, scale = log10, axis = (aspect = DataAspect(), title = "scale = log10")) f end @@ -814,8 +814,8 @@ end @reference_test "Latex labels after the fact" begin f = Figure(fontsize = 50) ax = Axis(f[1, 1]) - ax.xticks = ([3, 6, 9], [L"x" , L"y" , L"z"]) - ax.yticks = ([3, 6, 9], [L"x" , L"y" , L"z"]) + ax.xticks = ([3, 6, 9], [L"x", L"y", L"z"]) + ax.yticks = ([3, 6, 9], [L"x", L"y", L"z"]) f end diff --git a/ReferenceTests/src/tests/examples3d.jl b/ReferenceTests/src/tests/examples3d.jl index 938ef68f456..a008314e45d 100644 --- a/ReferenceTests/src/tests/examples3d.jl +++ b/ReferenceTests/src/tests/examples3d.jl @@ -1,7 +1,7 @@ @reference_test "Image on Geometry (Moon)" begin moon = loadasset("moon.png") - fig, ax, meshplot = mesh(Sphere(Point3f(0), 1f0), color=moon, shading=false, axis = (;show_axis=false)) + fig, ax, meshplot = mesh(Sphere(Point3f(0), 1f0), color = moon, shading = false, axis = (; show_axis = false)) update_cam!(ax.scene, Vec3f(-2, 2, 2), Vec3f(0)) fig end @@ -9,17 +9,19 @@ end @reference_test "Image on Geometry (Earth)" begin earth = loadasset("earth.png") m = uv_mesh(Tesselation(Sphere(Point3f(0), 1f0), 60)) - mesh(m, color=earth, shading=false) + mesh(m, color = earth, shading = false) end @reference_test "Orthographic Camera" begin function colormesh((geometry, color)) mesh1 = normal_mesh(geometry) npoints = length(GeometryBasics.coordinates(mesh1)) - return GeometryBasics.pointmeta(mesh1; color=fill(color, npoints)) + return GeometryBasics.pointmeta(mesh1; color = fill(color, npoints)) end # create an array of differently colored boxes in the direction of the 3 axes - x = Vec3f(0); baselen = 0.2f0; dirlen = 1f0 + x = Vec3f(0) + baselen = 0.2f0 + dirlen = 1f0 rectangles = [ (Rect(Vec3f(x), Vec3f(dirlen, baselen, baselen)), RGBAf(1, 0, 0, 1)), (Rect(Vec3f(x), Vec3f(baselen, dirlen, baselen)), RGBAf(0, 1, 0, 1)), @@ -47,12 +49,12 @@ end end @reference_test "Volume Function" begin - volume(RNG.rand(32, 32, 32), algorithm=:mip) + volume(RNG.rand(32, 32, 32), algorithm = :mip) end @reference_test "Textured Mesh" begin catmesh = loadasset("cat.obj") - mesh(catmesh, color=loadasset("diffusemap.png")) + mesh(catmesh, color = loadasset("diffusemap.png")) end @reference_test "Load Mesh" begin @@ -68,8 +70,8 @@ end j = [1, 2, 3, 2] k = [2, 3, 1, 3] # indices interpreted as triangles (every 3 sequential indices) - indices = [1, 2, 3, 1, 3, 4, 1, 4, 2, 2, 3, 4] - mesh(x, y, z, indices, color=color) + indices = [1, 2, 3, 1, 3, 4, 1, 4, 2, 2, 3, 4] + mesh(x, y, z, indices, color = color) end @reference_test "Wireframe of a Mesh" begin @@ -86,9 +88,9 @@ end r == 0.0 ? 1f0 : (sin(r) / r) end N = 30 - lspace = range(-10, stop=10, length=N) + lspace = range(-10, stop = 10, length = N) z = Float32[xy_data(x, y) for x in lspace, y in lspace] - r = range(0, stop=3, length=N) + r = range(0, stop = 3, length = N) wireframe(r, r, z) end @@ -98,43 +100,43 @@ end r = sqrt(x^2 + y^2) r == 0.0 ? 1f0 : (sin(r) / r) end - xrange = range(-2, stop=2, length=N) - surf_func(i) = [Float32(xy_data(x * i, y * i)) for x = xrange, y = xrange] + xrange = range(-2, stop = 2, length = N) + surf_func(i) = [Float32(xy_data(x * i, y * i)) for x in xrange, y in xrange] surface( xrange, xrange, surf_func(10), - color=RNG.rand(RGBAf, 124, 124) + color = RNG.rand(RGBAf, 124, 124) ) end @reference_test "Meshscatter Function" begin large_sphere = Sphere(Point3f(0), 1f0) positions = decompose(Point3f, large_sphere) - colS = [RGBAf(RNG.rand(), RNG.rand(), RNG.rand(), 1.0) for i = 1:length(positions)] - sizesS = [RNG.rand(Point3f) .* 0.05f0 for i = 1:length(positions)] - meshscatter(positions, color=colS, markersize=sizesS) + colS = [RGBAf(RNG.rand(), RNG.rand(), RNG.rand(), 1.0) for i in 1:length(positions)] + sizesS = [RNG.rand(Point3f) .* 0.05f0 for i in 1:length(positions)] + meshscatter(positions, color = colS, markersize = sizesS) end @reference_test "scatter" begin - scatter(RNG.rand(20), RNG.rand(20), markersize=10) + scatter(RNG.rand(20), RNG.rand(20), markersize = 10) end @reference_test "Marker sizes" begin colors = Makie.resample(to_colormap(:Spectral), 20) - scatter(RNG.rand(20), RNG.rand(20), markersize=RNG.rand(20) .* 20, color=colors) + scatter(RNG.rand(20), RNG.rand(20), markersize = RNG.rand(20) .* 20, color = colors) end @reference_test "Record Video" begin f(t, v, s) = (sin(v + t) * s, cos(v + t) * s, (cos(v + t) + sin(v)) * s) t = Observable(0.0) # create a life signal limits = Rect3f(Vec3f(-1.5, -1.5, -3), Vec3f(3, 3, 6)) - fig, ax, p1 = meshscatter(lift(t -> f.(t, range(0, stop=2pi, length=50), 1), t), markersize=0.05) - p2 = meshscatter!(ax, lift(t -> f.(t * 2.0, range(0, stop=2pi, length=50), 1.5), t), markersize=0.05) + fig, ax, p1 = meshscatter(lift(t -> f.(t, range(0, stop = 2pi, length = 50), 1), t), markersize = 0.05) + p2 = meshscatter!(ax, lift(t -> f.(t * 2.0, range(0, stop = 2pi, length = 50), 1.5), t), markersize = 0.05) linepoints = lift(p1[1], p2[1]) do pos1, pos2 map((a, b) -> (a => b), pos1, pos2) end - linesegments!(ax, linepoints, linestyle=:dot) + linesegments!(ax, linepoints, linestyle = :dot) Record(fig, 1:2) do i t[] = i / 10 @@ -146,14 +148,14 @@ end xy = [x, y, z] ((xy') * Matrix(I, 3, 3) * xy) / 20 end - x = range(-2pi, stop=2pi, length=100) + x = range(-2pi, stop = 2pi, length = 100) # c[4] == fourth argument of the above plotting command - fig, ax, c = contour(x, x, x, test, levels=6, alpha=0.3, transparency=true) + fig, ax, c = contour(x, x, x, test, levels = 6, alpha = 0.3, transparency = true) xm, ym, zm = minimum(data_limits(c)) - contour!(ax, x, x, map(v -> v[1, :, :], c[4]), transformation=(:xy, zm), linewidth=2) - heatmap!(ax, x, x, map(v -> v[:, 1, :], c[4]), transformation=(:xz, ym)) - contourf!(ax, x, x, map(v -> v[:, :, 1], c[4]), transformation=(:yz, xm)) + contour!(ax, x, x, map(v -> v[1, :, :], c[4]), transformation = (:xy, zm), linewidth = 2) + heatmap!(ax, x, x, map(v -> v[:, 1, :], c[4]), transformation = (:xz, ym)) + contourf!(ax, x, x, map(v -> v[:, :, 1], c[4]), transformation = (:yz, xm)) # reorder plots for transparency ax.scene.plots[:] = ax.scene.plots[[1, 3, 4, 5, 2]] fig @@ -164,45 +166,45 @@ end r = sqrt(x * x + y * y) r == 0.0 ? 1f0 : (sin(r) / r) end - r = range(-1, stop=1, length=100) - contour3d(r, r, (x, y) -> xy_data(10x, 10y), levels=20, linewidth=3) + r = range(-1, stop = 1, length = 100) + contour3d(r, r, (x, y) -> xy_data(10x, 10y), levels = 20, linewidth = 3) end @reference_test "Arrows 3D" begin - function SphericalToCartesian(r::T, θ::T, ϕ::T) where T <: AbstractArray + function SphericalToCartesian(r::T, θ::T, ϕ::T) where T<:AbstractArray x = @.r * sin(θ) * cos(ϕ) y = @.r * sin(θ) * sin(ϕ) z = @.r * cos(θ) Point3f.(x, y, z) end n = 100^2 # number of points to generate - r = ones(n); + r = ones(n) θ = acos.(1 .- 2 .* RNG.rand(n)) φ = 2π * RNG.rand(n) pts = SphericalToCartesian(r, θ, φ) - arrows(pts, (normalize.(pts) .* 0.1f0), arrowsize=0.02, linecolor=:green, arrowcolor=:darkblue) + arrows(pts, (normalize.(pts) .* 0.1f0), arrowsize = 0.02, linecolor = :green, arrowcolor = :darkblue) end @reference_test "Image on Surface Sphere" begin n = 20 - θ = [0;(0.5:n - 0.5) / n;1] - φ = [(0:2n - 2) * 2 / (2n - 1);2] + θ = [0; (0.5:(n - 0.5)) / n; 1] + φ = [(0:(2n - 2)) * 2 / (2n - 1); 2] x = [cospi(φ) * sinpi(θ) for θ in θ, φ in φ] y = [sinpi(φ) * sinpi(θ) for θ in θ, φ in φ] z = [cospi(θ) for θ in θ, φ in φ] RNG.rand([-1f0, 1f0], 3) pts = vec(Point3f.(x, y, z)) - f, ax, p = surface(x, y, z, color=Makie.logo(), transparency=true) + f, ax, p = surface(x, y, z, color = Makie.logo(), transparency = true) end @reference_test "Arrows on Sphere" begin n = 20 - f = (x, y, z) -> x * exp(cos(y) * z) - ∇f = (x, y, z) -> Point3f(exp(cos(y) * z), -sin(y) * z * x * exp(cos(y) * z), x * cos(y) * exp(cos(y) * z)) + f = (x, y, z) -> x * exp(cos(y) * z) + ∇f = (x, y, z) -> Point3f(exp(cos(y) * z), -sin(y) * z * x * exp(cos(y) * z), x * cos(y) * exp(cos(y) * z)) ∇ˢf = (x, y, z) -> ∇f(x, y, z) - Point3f(x, y, z) * dot(Point3f(x, y, z), ∇f(x, y, z)) - θ = [0;(0.5:n - 0.5) / n;1] - φ = [(0:2n - 2) * 2 / (2n - 1);2] + θ = [0; (0.5:(n - 0.5)) / n; 1] + φ = [(0:(2n - 2)) * 2 / (2n - 1); 2] x = [cospi(φ) * sinpi(θ) for θ in θ, φ in φ] y = [sinpi(φ) * sinpi(θ) for θ in θ, φ in φ] z = [cospi(θ) for θ in θ, φ in φ] @@ -212,7 +214,7 @@ end surface(x, y, z) arrows!( pts, ∇ˢF, - arrowsize=0.03, linecolor=(:white, 0.6), linewidth=0.03 + arrowsize = 0.03, linecolor = (:white, 0.6), linewidth = 0.03 ) current_figure() end @@ -226,7 +228,7 @@ end ax1 = fig[1, 1] = Axis(fig, title = "surface") ax2 = fig[1, 2] = Axis(fig, title = "contour3d") surface!(ax1, vx, vy, f) - contour3d!(ax2, vx, vy, (x, y) -> f(x, y), levels=15, linewidth=3) + contour3d!(ax2, vx, vy, (x, y) -> f(x, y), levels = 15, linewidth = 3) fig end @@ -234,11 +236,11 @@ end cat = loadasset("cat.obj") vertices = decompose(Point3f, cat) faces = decompose(TriangleFace{Int}, cat) - coordinates = [vertices[i][j] for i = 1:length(vertices), j = 1:3] - connectivity = [faces[i][j] for i = 1:length(faces), j = 1:3] + coordinates = [vertices[i][j] for i in 1:length(vertices), j in 1:3] + connectivity = [faces[i][j] for i in 1:length(faces), j in 1:3] mesh( coordinates, connectivity, - color=RNG.rand(length(vertices)) + color = RNG.rand(length(vertices)) ) end @@ -247,7 +249,7 @@ end vy = -1:0.01:1 f(x, y) = (sin(x * 10) + cos(y * 10)) / 4 - scene = Scene(resolution=(500, 500), camera=cam3d!) + scene = Scene(resolution = (500, 500), camera = cam3d!) # One way to style the axis is to pass a nested dictionary / named tuple to it. psurf = surface!(scene, vx, vy, f) axis3d!(scene, frame = (linewidth = 2.0,)) @@ -268,12 +270,12 @@ end t = text!( campixel(scene), "Multipole Representation of first resonances of U-238", - position=(wh[1] / 2.0, wh[2] - 20.0), - align=(:center, :center), - fontsize=20, - font="helvetica" + position = (wh[1] / 2.0, wh[2] - 20.0), + align = (:center, :center), + fontsize = 20, + font = "helvetica" ) - c = lines!(scene, Circle(Point2f(0.1, 0.5), 0.1f0), color=:red, offset=Vec3f(0, 0, 1)) + c = lines!(scene, Circle(Point2f(0.1, 0.5), 0.1f0), color = :red, offset = Vec3f(0, 0, 1)) psurf.converted[3][] = f.(vx .+ 0.5, (vy .+ 0.5)') scene end @@ -281,51 +283,55 @@ end @reference_test "Fluctuation 3D" begin # define points/edges perturbfactor = 4e1 - N = 3; nbfacese = 30; radius = 0.02 + N = 3 + nbfacese = 30 + radius = 0.02 large_sphere = Sphere(Point3f(0), 1f0) positions = decompose(Point3f, large_sphere, 30) np = length(positions) - pts = [positions[k][l] for k = 1:length(positions), l = 1:3] + pts = [positions[k][l] for k in 1:length(positions), l in 1:3] pts = vcat(pts, 1.1 .* pts + RNG.randn(size(pts)) / perturbfactor) # light position influence ? edges = hcat(collect(1:np), collect(1:np) .+ np) - ne = size(edges, 1); np = size(pts, 1) + ne = size(edges, 1) + np = size(pts, 1) cylinder = Cylinder(Point3f(0), Point3f(0, 0, 1.0), 1f0) # define markers meshes meshC = normal_mesh(Tesselation(cylinder, nbfacese)) meshS = normal_mesh(Tesselation(large_sphere, 20)) # define colors, markersizes and rotations - pG = [Point3f(pts[k, 1], pts[k, 2], pts[k, 3]) for k = 1:np] - lengthsC = sqrt.(sum((pts[edges[:,1], :] .- pts[edges[:, 2], :]).^2, dims=2)) - sizesC = [Vec3f(radius, radius, lengthsC[i]) for i = 1:ne] - sizesC = [Vec3f(1) for i = 1:ne] - colorsp = [RGBA{Float32}(RNG.rand(), RNG.rand(), RNG.rand(), 1.0) for i = 1:np] - colorsC = [(colorsp[edges[i, 1]] .+ colorsp[edges[i, 2]]) / 2.0 for i = 1:ne] - sizesC = [Vec3f(radius, radius, lengthsC[i]) for i = 1:ne] + pG = [Point3f(pts[k, 1], pts[k, 2], pts[k, 3]) for k in 1:np] + lengthsC = sqrt.(sum((pts[edges[:, 1], :] .- pts[edges[:, 2], :]) .^ 2, dims = 2)) + sizesC = [Vec3f(radius, radius, lengthsC[i]) for i in 1:ne] + sizesC = [Vec3f(1) for i in 1:ne] + colorsp = [RGBA{Float32}(RNG.rand(), RNG.rand(), RNG.rand(), 1.0) for i in 1:np] + colorsC = [(colorsp[edges[i, 1]] .+ colorsp[edges[i, 2]]) / 2.0 for i in 1:ne] + sizesC = [Vec3f(radius, radius, lengthsC[i]) for i in 1:ne] Qlist = zeros(ne, 4) - for k = 1:ne + for k in 1:ne ct = Cylinder( Point3f(pts[edges[k, 1], 1], pts[edges[k, 1], 2], pts[edges[k, 1], 3]), Point3f(pts[edges[k, 2], 1], pts[edges[k, 2], 2], pts[edges[k, 2], 3]), 1f0 ) Q = GeometryBasics.rotation(ct) - r = 0.5 * sqrt(1 .+ Q[1, 1] .+ Q[2, 2] .+ Q[3, 3]); Qlist[k, 4] = r + r = 0.5 * sqrt(1 .+ Q[1, 1] .+ Q[2, 2] .+ Q[3, 3]) + Qlist[k, 4] = r Qlist[k, 1] = (Q[3, 2] .- Q[2, 3]) / (4 .* r) Qlist[k, 2] = (Q[1, 3] .- Q[3, 1]) / (4 .* r) Qlist[k, 3] = (Q[2, 1] .- Q[1, 2]) / (4 .* r) end - rotationsC = [Vec4f(Qlist[i, 1], Qlist[i, 2], Qlist[i, 3], Qlist[i, 4]) for i = 1:ne] + rotationsC = [Vec4f(Qlist[i, 1], Qlist[i, 2], Qlist[i, 3], Qlist[i, 4]) for i in 1:ne] # plot fig, ax, meshplot = meshscatter( pG[edges[:, 1]], - color=colorsC, marker=meshC, - markersize=sizesC, rotations=rotationsC, + color = colorsC, marker = meshC, + markersize = sizesC, rotations = rotationsC, ) meshscatter!( ax, pG, - color=colorsp, marker=meshS, markersize=radius, + color = colorsp, marker = meshS, markersize = radius, ) fig end @@ -334,11 +340,11 @@ end large_sphere = Sphere(Point3f(0), 1f0) positions = decompose(Point3f, large_sphere) linepos = view(positions, RNG.rand(1:length(positions), 1000)) - fig, ax, lineplot = lines(linepos, linewidth=0.1, color=:black, transparency=true) + fig, ax, lineplot = lines(linepos, linewidth = 0.1, color = :black, transparency = true) scatter!( - ax, positions, markersize=10, - strokewidth=2, strokecolor=:white, - color=RGBAf(0.9, 0.2, 0.4, 0.3), transparency=true, + ax, positions, markersize = 10, + strokewidth = 2, strokecolor = :white, + color = RGBAf(0.9, 0.2, 0.4, 0.3), transparency = true, ) fig end @@ -346,18 +352,18 @@ end @reference_test "image scatter" begin scatter( 1:10, 1:10, RNG.rand(10, 10) .* 10, - rotations=normalize.(RNG.rand(Quaternionf, 10 * 10)), - markersize=20, + rotations = normalize.(RNG.rand(Quaternionf, 10 * 10)), + markersize = 20, # can also be an array of images for each point # need to be the same size for best performance, though - marker=Makie.logo() + marker = Makie.logo() ) end @reference_test "Simple meshscatter" begin large_sphere = Sphere(Point3f(0), 1f0) positions = decompose(Point3f, large_sphere) - meshscatter(positions, color=RGBAf(0.9, 0.2, 0.4, 1), markersize=0.05) + meshscatter(positions, color = RGBAf(0.9, 0.2, 0.4, 1), markersize = 0.05) end @reference_test "Animated surface and wireframe" begin @@ -366,46 +372,48 @@ end r == 0.0 ? 1f0 : (sin(r) / r) end - xrange = range(-2, stop=2, length=50) - surf_func(i) = [Float32(xy_data(x * i, y * i)) for x = xrange, y = xrange] + xrange = range(-2, stop = 2, length = 50) + surf_func(i) = [Float32(xy_data(x * i, y * i)) for x in xrange, y in xrange] z = surf_func(20) fig, ax, surf = surface(xrange, xrange, z) wf = wireframe!(ax, xrange, xrange, lift(x -> x .+ 1.0, surf[3]), - linewidth=2f0, color=lift(x -> to_colormap(x)[5], surf[:colormap]) + linewidth = 2f0, color = lift(x -> to_colormap(x)[5], surf[:colormap]) ) - Record(fig, range(5, stop=40, length=3)) do i + Record(fig, range(5, stop = 40, length = 3)) do i surf[3] = surf_func(i) end end @reference_test "Normals of a Cat" begin x = loadasset("cat.obj") - mesh(x, color=:black) + mesh(x, color = :black) pos = map(decompose(Point3f, x), GeometryBasics.normals(x)) do p, n p => p .+ Point(normalize(n) .* 0.05f0) end - linesegments!(pos, color=:blue) + linesegments!(pos, color = :blue) current_figure() end @reference_test "Sphere Mesh" begin - mesh(Sphere(Point3f(0), 1f0), color=:blue) + mesh(Sphere(Point3f(0), 1f0), color = :blue) end @reference_test "Unicode Marker" begin - scatter(Point3f[(1, 0, 0), (0, 1, 0), (0, 0, 1)], marker=[:x, :circle, :cross], - markersize=35) + scatter(Point3f[(1, 0, 0), (0, 1, 0), (0, 0, 1)], marker = [:x, :circle, :cross], + markersize = 35) end @reference_test "Merged color Mesh" begin function colormesh((geometry, color)) mesh1 = normal_mesh(geometry) npoints = length(GeometryBasics.coordinates(mesh1)) - return GeometryBasics.pointmeta(mesh1; color=fill(color, npoints)) + return GeometryBasics.pointmeta(mesh1; color = fill(color, npoints)) end # create an array of differently colored boxes in the direction of the 3 axes - x = Vec3f(0); baselen = 0.2f0; dirlen = 1f0 + x = Vec3f(0) + baselen = 0.2f0 + dirlen = 1f0 rectangles = [ (Rect(Vec3f(x), Vec3f(dirlen, baselen, baselen)), RGBAf(1, 0, 0, 1)), (Rect(Vec3f(x), Vec3f(baselen, dirlen, baselen)), RGBAf(0, 1, 0, 1)), @@ -417,21 +425,21 @@ end end @reference_test "Line GIF" begin - us = range(0, stop=1, length=100) + us = range(0, stop = 1, length = 100) f, ax, p = linesegments(Rect3f(Vec3f(0, -1, 0), Vec3f(1, 2, 2))) - p = lines!(ax, us, sin.(us), zeros(100), linewidth=3, transparency=true) + p = lines!(ax, us, sin.(us), zeros(100), linewidth = 3, transparency = true) lineplots = [p] Makie.translate!(p, 0, 0, 0) colors = to_colormap(:RdYlBu) N = 5 Record(f, 1:N) do i - t = i/(N/5) + t = i / (N / 5) if length(lineplots) < 20 p = lines!( ax, us, sin.(us .+ t), zeros(100), - color=colors[length(lineplots)], - linewidth=3 + color = colors[length(lineplots)], + linewidth = 3 ) pushfirst!(lineplots, p) translate!(p, 0, 0, 0) @@ -450,13 +458,13 @@ end @reference_test "Surface + wireframe + contour" begin N = 51 - x = range(-2, stop=2, length=N) + x = range(-2, stop = 2, length = N) y = x - z = (-x .* exp.(-x.^2 .- (y').^2)) .* 4 + z = (-x .* exp.(-x .^ 2 .- (y') .^ 2)) .* 4 fig, ax, surfaceplot = surface(x, y, z) xm, ym, zm = minimum(data_limits(ax.scene)) - contour!(ax, x, y, z, levels=15, linewidth=2, transformation=(:xy, zm)) - wireframe!(ax, x, y, z, transparency=true, color=(:black, 0.1)) + contour!(ax, x, y, z, levels = 15, linewidth = 2, transformation = (:xy, zm)) + wireframe!(ax, x, y, z, transparency = true, color = (:black, 0.1)) center!(ax.scene) # center the Scene on the display fig end @@ -477,19 +485,19 @@ let P.γ * x[1] - x[3] - P.β, ) f(x) = f(x, P) - streamplot(f, -1.5..1.5, -1.5..1.5, -1.5..1.5, colormap=:magma, gridsize=(10, 10), arrow_size=0.1, transparency=true) + streamplot(f, -1.5 .. 1.5, -1.5 .. 1.5, -1.5 .. 1.5, colormap = :magma, gridsize = (10, 10), arrow_size = 0.1, transparency = true) end end @reference_test "Volume on black background" begin - r = LinRange(-3, 3, 100); # our value range + r = LinRange(-3, 3, 100) # our value range ρ(x, y, z) = exp(-(abs(x))) # function (charge density) fig, ax, pl = volume( r, r, r, # coordinates to plot on ρ, # charge density (functions as colorant) - algorithm=:mip # maximum-intensity-projection + algorithm = :mip # maximum-intensity-projection ) ax.scene[OldAxis].names.textcolor = :gray # let axis labels be seen on dark background fig.scene.backgroundcolor[] = to_color(:black) @@ -501,9 +509,9 @@ end fig = Figure(resolution = (800, 400)) prim = Rect3(Point3f(0), Vec3f(1)) - ps = RNG.rand(Point3f, 10) .+ Point3f(0, 0, 1) + ps = RNG.rand(Point3f, 10) .+ Point3f(0, 0, 1) mat = RNG.rand(4, 4) - A = RNG.rand(4,4,4) + A = RNG.rand(4, 4, 4) # This generates two sets of plots each on two axis. Both axes have one set # without depth_shift (0f0, red) and one at ∓10eps(1f0) (blue, left/right axis). @@ -515,14 +523,14 @@ end mesh!(ax, prim, color = color, depth_shift = shift) lines!(ax, ps, color = color, depth_shift = shift) linesegments!(ax, ps .+ Point3f(-1, 1, 0), color = color, depth_shift = shift) - scatter!(ax, ps, color = color, markersize=10, depth_shift = shift) + scatter!(ax, ps, color = color, markersize = 10, depth_shift = shift) text!(ax, 0, 1, 1.1, text = "Test", color = color, depth_shift = shift) - surface!(ax, -1..0, 1..2, mat, colormap = [color, color], depth_shift = shift) + surface!(ax, -1 .. 0, 1 .. 2, mat, colormap = [color, color], depth_shift = shift) meshscatter!(ax, ps .+ Point3f(-1, 1, 0), color = color, depth_shift = shift) # # left side in axis - heatmap!(ax, 0..1, 0..1, mat, colormap = [color, color], depth_shift = shift) + heatmap!(ax, 0 .. 1, 0 .. 1, mat, colormap = [color, color], depth_shift = shift) # # right side in axis - image!(ax, -1..0, 1..2, mat, colormap = [color, color], depth_shift = shift) + image!(ax, -1 .. 0, 1 .. 2, mat, colormap = [color, color], depth_shift = shift) p = volume!(ax, A, colormap = [:white, color], depth_shift = shift) translate!(p, -1, 0, 0) scale!(p, 0.25, 0.25, 0.25) @@ -542,13 +550,13 @@ end r = Rect2f(-1, -1, 2, 2) for x in (0, 1) for (i, a) in enumerate((0.25, 0.5, 0.75, 1.0)) - ps = [Point3f(a, (0.15 + 0.01y)*(2x-1) , 0.2y) for y in 1:8] + ps = [Point3f(a, (0.15 + 0.01y) * (2x - 1), 0.2y) for y in 1:8] if x == 0 cs = [RGBAf(1, 0, 0, 0.75), RGBAf(0, 1, 0, 0.5), RGBAf(0, 0, 1, 0.25)] elseif x == 1 cs = [RGBAf(1, x, 0, a), RGBAf(0, 1, x, a), RGBAf(x, 0, 1, a)] end - idxs = [1, 2, 3, 2, 1, 3, 1, 2, 1, 2, 3][i:7+i] + idxs = [1, 2, 3, 2, 1, 3, 1, 2, 1, 2, 3][i:(7 + i)] meshscatter!( ax, ps, marker = r, color = cs[idxs], transparency = true @@ -569,7 +577,7 @@ end mesh!(ax, Rect2f(0.8, 0.1, 0.1, 0.8), space = :relative, color = :blue, shading = false) linesegments!(ax, Rect2f(-0.5, -0.5, 1, 1), space = :clip, color = :cyan, linewidth = 5) text!(ax, 0, 0.52, text = "Clip Space", align = (:center, :bottom), space = :clip) - image!(ax, 0..40, 0..800, [x for x in range(0, 1, length=40), _ in 1:10], space = :pixel) + image!(ax, 0 .. 40, 0 .. 800, [x for x in range(0, 1, length = 40), _ in 1:10], space = :pixel) end fig end diff --git a/ReferenceTests/src/tests/figures_and_makielayout.jl b/ReferenceTests/src/tests/figures_and_makielayout.jl index fb91ca36a0a..d79afb7a977 100644 --- a/ReferenceTests/src/tests/figures_and_makielayout.jl +++ b/ReferenceTests/src/tests/figures_and_makielayout.jl @@ -9,10 +9,10 @@ end @reference_test "Figure with Blocks" begin fig = Figure(resolution = (900, 900)) - ax, sc = scatter(fig[1, 1][1, 1], RNG.randn(100, 2), axis = (;title = "Random Dots", xlabel = "Time")) + ax, sc = scatter(fig[1, 1][1, 1], RNG.randn(100, 2), axis = (; title = "Random Dots", xlabel = "Time")) sc2 = scatter!(ax, RNG.randn(100, 2) .+ 2, color = :red) ll = fig[1, 1][1, 2] = Legend(fig, [sc, sc2], ["Scatter", "Other"]) - lines(fig[2, 1:2][1, 3][1, 1], 0..3, sin ∘ exp, axis = (;title = "Exponential Sine")) + lines(fig[2, 1:2][1, 3][1, 1], 0 .. 3, sin ∘ exp, axis = (; title = "Exponential Sine")) heatmap(fig[2, 1:2][1, 1], RNG.randn(30, 30)) heatmap(fig[2, 1:2][1, 2], RNG.randn(30, 30), colormap = :grays) lines!(fig[2, 1:2][1, 2], cumsum(RNG.rand(30)), color = :red, linewidth = 10) @@ -27,7 +27,7 @@ end @reference_test "menus" begin fig = Figure() - funcs = [sqrt, x->x^2, sin, cos] + funcs = [sqrt, x -> x^2, sin, cos] options = zip(["Square Root", "Square", "Sine", "Cosine"], funcs) menu1 = Menu(fig, options = ["viridis", "heat", "blues"], default = 1) @@ -37,10 +37,10 @@ end fig[1, 1] = grid!( [ - Label(fig, "A", width = nothing) Label(fig, "C", width = nothing); - menu1 menu3; - Label(fig, "B", width = nothing) Label(fig, "D", width = nothing); - menu2 menu4; + Label(fig, "A", width = nothing) Label(fig, "C", width = nothing) + menu1 menu3 + Label(fig, "B", width = nothing) Label(fig, "D", width = nothing) + menu2 menu4 ] ) menu2.is_open = true @@ -51,7 +51,7 @@ end @reference_test "Label with text wrapping" begin lorem_ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." fig = Figure(resolution = (1000, 660)) - m!(fig, lbl) = mesh!(fig.scene, lbl.layoutobservables.computedbbox, color = (:red, 0.5), shading=false) + m!(fig, lbl) = mesh!(fig.scene, lbl.layoutobservables.computedbbox, color = (:red, 0.5), shading = false) lbl1 = Label(fig[1, 1:2], "HEADER "^10, fontsize = 40, word_wrap = true) m!(fig, lbl1) @@ -113,11 +113,11 @@ end f = Figure() ax = Axis(f[1, 1], backgroundcolor = :gray80) for i in 1:3 - lines!(ax,( 1:10) .* i, label = "$i") + lines!(ax, (1:10) .* i, label = "$i") end # To verify that RGB values differ across entries - axislegend(ax, position = :lt, patchcolor = :red, patchsize = (100, 100), bgcolor = :gray50); - Legend(f[1, 2], ax, patchcolor = :gray80, patchsize = (100, 100), bgcolor = :gray50); + axislegend(ax, position = :lt, patchcolor = :red, patchsize = (100, 100), bgcolor = :gray50) + Legend(f[1, 2], ax, patchcolor = :gray80, patchsize = (100, 100), bgcolor = :gray50) f end end diff --git a/ReferenceTests/src/tests/primitives.jl b/ReferenceTests/src/tests/primitives.jl index 0d64146d5dd..2c17d6feda3 100644 --- a/ReferenceTests/src/tests/primitives.jl +++ b/ReferenceTests/src/tests/primitives.jl @@ -11,7 +11,7 @@ quote for linewidth in 1:10 for (i, linestyle) in enumerate(linestyles) lines!(s, - scalar .* (points .+ Point2f(linewidth*2, i * 3.25)), + scalar .* (points .+ Point2f(linewidth * 2, i * 3.25)), linewidth = linewidth, linestyle = linestyle, ) @@ -83,7 +83,7 @@ end s = Scene(resolution = (350, 700), camera = campixel!) # half stroke, half glow - strokes = range(1, 4, length=7) + strokes = range(1, 4, length = 7) outline_colors = [:red, :green, :blue, :yellow, :purple, :cyan, :black] colors = [ :red, :green, :blue, @@ -116,7 +116,7 @@ end s = Scene(resolution = (350, 700), camera = campixel!) # half stroke, half glow - glows = range(4, 1, length=7) + glows = range(4, 1, length = 7) outline_colors = [:red, :green, :blue, :yellow, :purple, :cyan, :black] colors = [ :red, :green, :blue, @@ -147,14 +147,14 @@ end @reference_test "scatter image markers" begin - pixel_types = [ RGBA, RGBAf, RGBA{Float16}, ARGB, ARGB{Float16}, RGB, RGBf, RGB{Float16} ] - rotations = [ 2pi/3 * (i-1) for i = 1:length(pixel_types) ] - s = Scene(resolution = (100+100*length(pixel_types), 400), camera = campixel!) + pixel_types = [RGBA, RGBAf, RGBA{Float16}, ARGB, ARGB{Float16}, RGB, RGBf, RGB{Float16}] + rotations = [2pi / 3 * (i - 1) for i in 1:length(pixel_types)] + s = Scene(resolution = (100 + 100 * length(pixel_types), 400), camera = campixel!) filename = Makie.assetpath("icon_transparent.png") marker_image = FileIO.load(filename) for (i, (rot, pxtype)) in enumerate(zip(rotations, pixel_types)) marker = convert.(pxtype, marker_image) - p = Point2f((i-1) * 100 + 100, 200) + p = Point2f((i - 1) * 100 + 100, 200) scatter!(s, p, marker = marker, @@ -205,7 +205,7 @@ end for (i, p) in enumerate(polys) for (j, lw) in enumerate(linewidths) - t = Transformation(scale=Vec3f(scalefactor), translation = Vec3f(1.3 * (i-1), 1.3 * j, 0) .* scalefactor) + t = Transformation(scale = Vec3f(scalefactor), translation = Vec3f(1.3 * (i - 1), 1.3 * j, 0) .* scalefactor) poly!( s, p, @@ -291,19 +291,19 @@ end github = BezierPath(gh_string, fit = true, flipy = true) two_circles_with_holes = Makie.scale(BezierPath([ - MoveTo(Point(2.25, 0)), - EllipticalArc(Point(1.25, 0), 1, 1, 0, 0, 2pi), - ClosePath(), - MoveTo(Point(-0.25, 0)), - EllipticalArc(Point(-1.25, 0), 1, 1, 0, 0, 2pi), - ClosePath(), - MoveTo(Point(2, 0)), - EllipticalArc(Point(1.25, 0), 0.75, 0.75, 0, 0, -2pi), - ClosePath(), - MoveTo(Point(-1, 0)), - EllipticalArc(Point(-1.25, 0), 0.25, 0.25, 0, 0, -2pi), - ClosePath(), - ]), 0.5) + MoveTo(Point(2.25, 0)), + EllipticalArc(Point(1.25, 0), 1, 1, 0, 0, 2pi), + ClosePath(), + MoveTo(Point(-0.25, 0)), + EllipticalArc(Point(-1.25, 0), 1, 1, 0, 0, 2pi), + ClosePath(), + MoveTo(Point(2, 0)), + EllipticalArc(Point(1.25, 0), 0.75, 0.75, 0, 0, -2pi), + ClosePath(), + MoveTo(Point(-1, 0)), + EllipticalArc(Point(-1.25, 0), 0.25, 0.25, 0, 0, -2pi), + ClosePath(), + ]), 0.5) markers = [ arrow, @@ -326,11 +326,11 @@ end p_big = decompose(Point2f, Circle(Point2f(0), 1)) p_small = decompose(Point2f, Circle(Point2f(0), 0.5)) marker = [Polygon(p_big, [p_small]), Polygon(reverse(p_big), [p_small]), Polygon(p_big, [reverse(p_small)]), Polygon(reverse(p_big), [reverse(p_small)])] - scatter(1:4, fill(0, 4), marker=marker, markersize=100, color=1:4, axis=(limits=(0, 5, -1, 1),)) + scatter(1:4, fill(0, 4), marker = marker, markersize = 100, color = 1:4, axis = (limits = (0, 5, -1, 1),)) end function centered_rect(w, h) - wh, hh = w/2, h/2 + wh, hh = w / 2, h / 2 return Point2f[(-wh, -hh), (-wh, hh), (wh, hh), (wh, -hh)] end @@ -348,15 +348,15 @@ function create_rect(inner) return Makie.to_spritemarker(marker) end -function plot_test!(scene, xoffset, yoffset, inner, reverse=true, marker=create_marker) +function plot_test!(scene, xoffset, yoffset, inner, reverse = true, marker = create_marker) bpath = marker(inner) p = [Point2f(xoffset, yoffset) .+ 150] if reverse - scatter!(scene, p, marker=bpath, markersize=280, color=:black) - scatter!(scene, p, marker=Rect, markersize=280, color=:red) + scatter!(scene, p, marker = bpath, markersize = 280, color = :black) + scatter!(scene, p, marker = Rect, markersize = 280, color = :red) else - scatter!(scene, p, marker=Rect, markersize=280, color=:red) - scatter!(scene, p, marker=bpath, markersize=280, color=:black) + scatter!(scene, p, marker = Rect, markersize = 280, color = :red) + scatter!(scene, p, marker = bpath, markersize = 280, color = :black) end end @@ -368,9 +368,9 @@ function plot_row!(scene, yoffset, reverse) plot_test!(scene, 900, yoffset + 0, 0.3, reverse, create_rect) end -function draw_marker_test!(scene, marker, center; markersize=300) +function draw_marker_test!(scene, marker, center; markersize = 300) # scatter!(scene, center, distancefield=matr, uv_offset_width=Vec4f(0, 0, 1, 1), markersize=600) - scatter!(scene, center, marker=marker, markersize=markersize, markerspace=:pixel) + scatter!(scene, center, marker = marker, markersize = markersize, markerspace = :pixel) font = Makie.defaultfont() charextent = Makie.FreeTypeAbstraction.get_extent(font, marker) @@ -380,18 +380,18 @@ function draw_marker_test!(scene, marker, center; markersize=300) w, h = widths(inkbb) .* markersize ox, oy = origin(inkbb) .* markersize mhalf = markersize / 2 - bbmin = center .+ Point2f(-w/2, -h/2) + bbmin = center .+ Point2f(-w / 2, -h / 2) inkbb_scaled = Rect2f(bbmin..., w, h) - lines!(scene, inkbb_scaled, linewidth=5, color=:green) - points = Point2f[(center[1], center[2] - h/2), (center[1], center[2] + h/2), (center[1] - w/2, center[2]), (center[1] + w/2, center[2])] - linesegments!(scene, points, color=:red) + lines!(scene, inkbb_scaled, linewidth = 5, color = :green) + points = Point2f[(center[1], center[2] - h / 2), (center[1], center[2] + h / 2), (center[1] - w / 2, center[2]), (center[1] + w / 2, center[2])] + linesegments!(scene, points, color = :red) scene end @reference_test "marke glyph alignment" begin - scene = Scene(resolution=(1200, 1200)) + scene = Scene(resolution = (1200, 1200)) campixel!(scene) # marker is in front, so it should not be smaller than the background rectangle plot_row!(scene, 0, false) @@ -402,15 +402,15 @@ end # Markers should be well aligned to the red cross and just about touch the green # boundingbox! - draw_marker_test!(scene, 'x', Point2f(150, 750); markersize=550) - draw_marker_test!(scene, 'X', Point2f(450, 750); markersize=400) - draw_marker_test!(scene, 'I', Point2f(750, 750); markersize=400) - draw_marker_test!(scene, 'O', Point2f(1050, 750); markersize=300) - - draw_marker_test!(scene, 'L', Point2f(150, 1050); markersize=350) - draw_marker_test!(scene, 'Y', Point2f(450, 1050); markersize=350) - draw_marker_test!(scene, 'y', Point2f(750, 1050); markersize=350) - draw_marker_test!(scene, 'u', Point2f(1050, 1050); markersize=500) + draw_marker_test!(scene, 'x', Point2f(150, 750); markersize = 550) + draw_marker_test!(scene, 'X', Point2f(450, 750); markersize = 400) + draw_marker_test!(scene, 'I', Point2f(750, 750); markersize = 400) + draw_marker_test!(scene, 'O', Point2f(1050, 750); markersize = 300) + + draw_marker_test!(scene, 'L', Point2f(150, 1050); markersize = 350) + draw_marker_test!(scene, 'Y', Point2f(450, 1050); markersize = 350) + draw_marker_test!(scene, 'y', Point2f(750, 1050); markersize = 350) + draw_marker_test!(scene, 'u', Point2f(1050, 1050); markersize = 500) scene end diff --git a/ReferenceTests/src/tests/recipes.jl b/ReferenceTests/src/tests/recipes.jl index 547920a0538..42bacc0a905 100644 --- a/ReferenceTests/src/tests/recipes.jl +++ b/ReferenceTests/src/tests/recipes.jl @@ -2,12 +2,12 @@ import Makie: Plot, default_theme, plot!, to_value struct Simulation grid::Vector{Point3f} end - # Probably worth having a macro for this! -function Makie.default_theme(scene::SceneLike, ::Type{<: Plot(Simulation)}) +# Probably worth having a macro for this! +function Makie.default_theme(scene::SceneLike, ::Type{<:Plot(Simulation)}) Theme( - advance=0, - molecule_sizes=[0.08, 0.04, 0.04], - molecule_colors=[:maroon, :deepskyblue2, :deepskyblue2] + advance = 0, + molecule_sizes = [0.08, 0.04, 0.04], + molecule_colors = [:maroon, :deepskyblue2, :deepskyblue2] ) end # The recipe! - will get called for plot(!)(x::SimulationResult) @@ -21,15 +21,15 @@ function Makie.plot!(p::Plot(Simulation)) pos = to_value(mpos) N = length(pos) sizes = lift(p[:molecule_sizes]) do s - repeat(s, outer=N ÷ 3) + repeat(s, outer = N ÷ 3) end sizes = lift(p[:molecule_sizes]) do s - repeat(s, outer=N ÷ 3) + repeat(s, outer = N ÷ 3) end colors = lift(p[:molecule_colors]) do c - repeat(c, outer=N ÷ 3) + repeat(c, outer = N ÷ 3) end - scene = meshscatter!(p, mpos, markersize=sizes, color=colors) + scene = meshscatter!(p, mpos, markersize = sizes, color = colors) indices = Int[] for i in 1:3:N push!(indices, i, i + 1, i, i + 2) @@ -44,11 +44,12 @@ end # To write out a video of the whole simulation n = 5 - r = range(-1, stop=1, length=n) + r = range(-1, stop = 1, length = n) grid = Point3f.(r, reshape(r, (1, n, 1)), reshape(r, (1, 1, n))) - molecules = map(1:(n^3) * 3) do i + molecules = map(1:((n^3) * 3)) do i i3 = ((i - 1) ÷ 3) + 1 - xy = 0.1; z = 0.08 + xy = 0.1 + z = 0.08 i % 3 == 1 && return grid[i3] i % 3 == 2 && return grid[i3] + Point3f(xy, xy, z) i % 3 == 0 && return grid[i3] + Point3f(-xy, xy, z) diff --git a/ReferenceTests/src/tests/short_tests.jl b/ReferenceTests/src/tests/short_tests.jl index 1518f5482d7..2699cffdbec 100644 --- a/ReferenceTests/src/tests/short_tests.jl +++ b/ReferenceTests/src/tests/short_tests.jl @@ -1,75 +1,75 @@ -@reference_test "thick arc" arc(Point2f(0), 10f0, 0f0, pi, linewidth=20) +@reference_test "thick arc" arc(Point2f(0), 10f0, 0f0, pi, linewidth = 20) -@reference_test "stroked rect poly" poly(Recti(0, 0, 200, 200), strokewidth=20, strokecolor=:red, color=(:black, 0.4)) +@reference_test "stroked rect poly" poly(Recti(0, 0, 200, 200), strokewidth = 20, strokecolor = :red, color = (:black, 0.4)) @reference_test "array of rects poly" begin f, ax, pl = poly([Rect(0, 0, 20, 20)]) - scatter!(Rect(0, 0, 20, 20), color=:red, markersize=20) + scatter!(Rect(0, 0, 20, 20), color = :red, markersize = 20) f end @reference_test "char marker scenespace" begin - f, ax, pl = lines(Rect(0, 0, 1, 1), linewidth=4) - scatter!([Point2f(0.5, 0.5)], markersize=1, markerspace=:data, marker='I') + f, ax, pl = lines(Rect(0, 0, 1, 1), linewidth = 4) + scatter!([Point2f(0.5, 0.5)], markersize = 1, markerspace = :data, marker = 'I') f end -@reference_test "lines number color" lines(RNG.rand(10), RNG.rand(10), color=RNG.rand(10), linewidth=10) -@reference_test "lines array of colors" lines(RNG.rand(10), RNG.rand(10), color=RNG.rand(RGBAf, 10), linewidth=10) -@reference_test "scatter interval" scatter(0..1, RNG.rand(10), markersize=RNG.rand(10) .* 20) +@reference_test "lines number color" lines(RNG.rand(10), RNG.rand(10), color = RNG.rand(10), linewidth = 10) +@reference_test "lines array of colors" lines(RNG.rand(10), RNG.rand(10), color = RNG.rand(RGBAf, 10), linewidth = 10) +@reference_test "scatter interval" scatter(0 .. 1, RNG.rand(10), markersize = RNG.rand(10) .* 20) @reference_test "scatter linrange" scatter(LinRange(0, 1, 10), RNG.rand(10)) @reference_test "scatter rotation" begin - angles = range(0, stop=2pi, length=20) + angles = range(0, stop = 2pi, length = 20) pos = Point2f.(sin.(angles), cos.(angles)) - f, ax, pl = scatter(pos, markersize=0.2, markerspace=:data, rotations=-angles, marker='▲', axis=(;aspect = DataAspect())) - scatter!(pos, markersize=10, color=:red) + f, ax, pl = scatter(pos, markersize = 0.2, markerspace = :data, rotations = -angles, marker = '▲', axis = (; aspect = DataAspect())) + scatter!(pos, markersize = 10, color = :red) f end -@reference_test "heatmap transparent colormap" heatmap(RNG.rand(50, 50), colormap=(:RdBu, 0.2)) +@reference_test "heatmap transparent colormap" heatmap(RNG.rand(50, 50), colormap = (:RdBu, 0.2)) @reference_test "contour small x" contour(RNG.rand(10, 100)) @reference_test "contour small y" contour(RNG.rand(100, 10)) -@reference_test "contour with levels" contour(RNG.randn(100, 90), levels=3) +@reference_test "contour with levels" contour(RNG.randn(100, 90), levels = 3) -@reference_test "contour with levels array" contour(RNG.randn(100, 90), levels=[0.1, 0.5, 0.8]) -@reference_test "contour with color per level" contour(RNG.randn(33, 30), levels=[0.1, 0.5, 0.9], color=[:black, :green, (:blue, 0.4)], linewidth=2) +@reference_test "contour with levels array" contour(RNG.randn(100, 90), levels = [0.1, 0.5, 0.8]) +@reference_test "contour with color per level" contour(RNG.randn(33, 30), levels = [0.1, 0.5, 0.9], color = [:black, :green, (:blue, 0.4)], linewidth = 2) @reference_test "contour with colorrange" contour( - RNG.rand(33, 30) .* 6 .- 3, levels=[-2.5, 0.4, 0.5, 0.6, 2.5], - colormap=[(:black, 0.2), :red, :blue, :green, (:black, 0.2)], - colorrange=(0.2, 0.8) + RNG.rand(33, 30) .* 6 .- 3, levels = [-2.5, 0.4, 0.5, 0.6, 2.5], + colormap = [(:black, 0.2), :red, :blue, :green, (:black, 0.2)], + colorrange = (0.2, 0.8) ) @reference_test "circle line" lines(Circle(Point2f(0), Float32(1))) @reference_test "streamplot with func" begin v(x::Point2{T}) where T = Point2{T}(x[2], 4 * x[1]) - streamplot(v, -2..2, -2..2) + streamplot(v, -2 .. 2, -2 .. 2) end -@reference_test "lines with func" lines(-1..1, x -> x^2) -@reference_test "scatter with func" scatter(-1..1, x -> x^2) +@reference_test "lines with func" lines(-1 .. 1, x -> x^2) +@reference_test "scatter with func" scatter(-1 .. 1, x -> x^2) @reference_test "volume translated" begin - r = range(-3pi, stop=3pi, length=100) - fig, ax, vplot = Makie.volume(r, r, r, (x, y, z) -> cos(x) + sin(y) + cos(z), algorithm=:iso, isorange=0.1f0, axis = (;show_axis=false)) - v2 = volume!(ax, r, r, r, (x, y, z) -> cos(x) + sin(y) + cos(z), algorithm=:mip, - transformation=(translation=Vec3f(6pi, 0, 0),)) + r = range(-3pi, stop = 3pi, length = 100) + fig, ax, vplot = Makie.volume(r, r, r, (x, y, z) -> cos(x) + sin(y) + cos(z), algorithm = :iso, isorange = 0.1f0, axis = (; show_axis = false)) + v2 = volume!(ax, r, r, r, (x, y, z) -> cos(x) + sin(y) + cos(z), algorithm = :mip, + transformation = (translation = Vec3f(6pi, 0, 0),)) fig end -@reference_test "meshscatter color numbers" meshscatter(RNG.rand(10), RNG.rand(10), RNG.rand(10), color=RNG.rand(10)) -@reference_test "meshscatter color array" meshscatter(RNG.rand(10), RNG.rand(10), RNG.rand(10), color=RNG.rand(RGBAf, 10), transparency=true) +@reference_test "meshscatter color numbers" meshscatter(RNG.rand(10), RNG.rand(10), RNG.rand(10), color = RNG.rand(10)) +@reference_test "meshscatter color array" meshscatter(RNG.rand(10), RNG.rand(10), RNG.rand(10), color = RNG.rand(RGBAf, 10), transparency = true) @reference_test "transparent mesh texture" begin s1 = uv_mesh(Sphere(Point3f(0), 1f0)) - f, ax, pl = mesh(uv_mesh(Sphere(Point3f(0), 1f0)), color=RNG.rand(50, 50)) + f, ax, pl = mesh(uv_mesh(Sphere(Point3f(0), 1f0)), color = RNG.rand(50, 50)) # ugh, bug In GeometryTypes for UVs of non unit spheres. s2 = uv_mesh(Sphere(Point3f(0), 1f0)) s2.position .= s2.position .+ (Point3f(0, 2, 0),) - mesh!(s2, color=RNG.rand(RGBAf, 50, 50)) + mesh!(s2, color = RNG.rand(RGBAf, 50, 50)) f end @@ -80,15 +80,15 @@ end r = sqrt(x^2 + y^2) r == 0.0 ? 1f0 : (sin(r) / r) end - lspace = range(-10, stop=10, length=NL) - rspace = range(-10, stop=10, length=NR) + lspace = range(-10, stop = 10, length = NL) + rspace = range(-10, stop = 10, length = NR) z = Float32[xy_data(x, y) for x in lspace, y in rspace] - l = range(0, stop=3, length=NL) - r = range(0, stop=3, length=NR) + l = range(0, stop = 3, length = NL) + r = range(0, stop = 3, length = NR) surface( l, r, z, - colormap=:Spectral + colormap = :Spectral ) end @@ -99,15 +99,15 @@ end r = sqrt(x^2 + y^2) r == 0.0 ? 1f0 : (sin(r) / r) end - lspace = range(-10, stop=10, length=NL) - rspace = range(-10, stop=10, length=NR) + lspace = range(-10, stop = 10, length = NL) + rspace = range(-10, stop = 10, length = NR) z = Float32[xy_data(x, y) for x in lspace, y in rspace] - l = range(0, stop=3, length=NL) - r = range(0, stop=3, length=NR) + l = range(0, stop = 3, length = NL) + r = range(0, stop = 3, length = NR) surface( [l for l in l, r in r], [r for l in l, r in r], z, - colormap=:Spectral + colormap = :Spectral ) end @@ -147,29 +147,29 @@ end end @reference_test "log10 heatmap" begin - heatmap(RNG.rand(10, 5), axis = (yscale = log10, xscale=log10)) + heatmap(RNG.rand(10, 5), axis = (yscale = log10, xscale = log10)) end @reference_test "reverse range heatmap" begin x = [1 0 - 2 3] + 2 3] heatmap(1:2, 1:-1:0, x) end @reference_test "lines linesegments width test" begin res = 200 - s = Scene(camera=campixel!, resolution=(res, res)) + s = Scene(camera = campixel!, resolution = (res, res)) half = res / 2 linewidth = 10 - xstart = half - (half/2) + xstart = half - (half / 2) xend = xstart + 100 - half_w = linewidth/2 + half_w = linewidth / 2 - lines!(s, Point2f[(xstart, half), (xend, half)], linewidth=linewidth) - scatter!(s, Point2f[(xstart, half + half_w), (xstart, half - half_w), (xend, half + half_w), (xend, half - half_w)], color=:red, markersize=2) + lines!(s, Point2f[(xstart, half), (xend, half)], linewidth = linewidth) + scatter!(s, Point2f[(xstart, half + half_w), (xstart, half - half_w), (xend, half + half_w), (xend, half - half_w)], color = :red, markersize = 2) - l2 = linesegments!(s, Point2f[(xstart, half), (xend, half)], linewidth=linewidth, color=:gray) - s2 = scatter!(s, Point2f[(xstart, half + half_w), (xstart, half - half_w), (xend, half + half_w), (xend, half - half_w)], color=:red, markersize=2) + l2 = linesegments!(s, Point2f[(xstart, half), (xend, half)], linewidth = linewidth, color = :gray) + s2 = scatter!(s, Point2f[(xstart, half + half_w), (xstart, half - half_w), (xend, half + half_w), (xend, half - half_w)], color = :red, markersize = 2) for p in (l2, s2) translate!(p, 0, 20, 0) @@ -180,25 +180,25 @@ end @reference_test "multipoly with multi strokes" begin P = Polygon.([Point2f[[0.45, 0.05], [0.64, 0.15], [0.37, 0.62]], - Point2f[[0.32, 0.66], [0.46, 0.59], [0.09, 0.08]]]) + Point2f[[0.32, 0.66], [0.46, 0.59], [0.09, 0.08]]]) poly(P, color = [:red, :green], strokecolor = [:blue, :red], strokewidth = 2) end @reference_test "fast pixel marker" begin - scatter(RNG.rand(Point2f, 10000), marker=Makie.FastPixel()) + scatter(RNG.rand(Point2f, 10000), marker = Makie.FastPixel()) end @reference_test "axsi3" begin - meshscatter(RNG.rand(Point3f, 10), axis=(type=Axis3,)) + meshscatter(RNG.rand(Point3f, 10), axis = (type = Axis3,)) end @reference_test "pattern barplot" begin - barplot(1:5, color=Makie.LinePattern(linecolor=:red, background_color=:orange)) + barplot(1:5, color = Makie.LinePattern(linecolor = :red, background_color = :orange)) end @reference_test "barplot lowclip highclip nan_color" begin f = Figure() - attrs = (color=[-Inf, 2, NaN, Inf], colorrange=(2, 3), highclip = :red, lowclip=:green, nan_color=:black) + attrs = (color = [-Inf, 2, NaN, Inf], colorrange = (2, 3), highclip = :red, lowclip = :green, nan_color = :black) barplot(f[1, 1], 1:4; attrs...) poly( f[1, 2], @@ -208,11 +208,11 @@ end Point2f[(2, 1), (4, 1), (4, 2), (2, 2)], Point2f[(0, 1), (2, 1), (2, 2), (0, 2)], ]; - strokewidth=2, attrs... + strokewidth = 2, attrs... ) meshscatter(f[2, 1], 1:4, zeros(4), 1:4; attrs...) volcano = readdlm(Makie.assetpath("volcano.csv"), ',', Float64) - ax, cf = contourf(f[2, 2], volcano, levels = range(100, 180, length = 10), extendlow = :green, extendhigh = :red, nan_color=:black) + ax, cf = contourf(f[2, 2], volcano, levels = range(100, 180, length = 10), extendlow = :green, extendhigh = :red, nan_color = :black) Colorbar(f[:, 3], cf) f end @@ -224,9 +224,9 @@ end end @reference_test "scene visibility" begin - f, ax, pl = scatter(1:4, markersize=200) - ax2, pl = scatter(f[1, 2][1, 1], 1:4, color=1:4, markersize=200) - ax3, pl = scatter(f[1, 2][2, 1], 1:4, color=1:4, markersize=200) + f, ax, pl = scatter(1:4, markersize = 200) + ax2, pl = scatter(f[1, 2][1, 1], 1:4, color = 1:4, markersize = 200) + ax3, pl = scatter(f[1, 2][2, 1], 1:4, color = 1:4, markersize = 200) ax3.scene.visible[] = false ax2.scene.visible[] = false ax2.blockscene.visible[] = false @@ -237,8 +237,8 @@ end # https://github.com/MakieOrg/Makie.jl/issues/2392 Makie.inline!(false) f = Figure() - Menu(f[1,1], options=["one", "two", "three"]) - screen = display(f; visible=false) + Menu(f[1, 1], options = ["one", "two", "three"]) + screen = display(f; visible = false) # Close the window & redisplay close(screen) # Now, menu should be displayed again and not stay blank! @@ -246,14 +246,14 @@ end end @reference_test "space test in transformed axis" begin - f = lines(exp.(0.1*(1.0:100)); axis=(yscale=log10,)) - poly!(Rect(1, 1, 100, 100), color=:red, space=:pixel) - scatter!(2*mod.(1:100:10000, 97), 2*mod.(1:101:10000, 97), color=:blue, space=:pixel) - scatter!(Point2f(0, 0.25), space=:clip) - lines!([0.5,0.5], [0, 1]; space=:relative) - lines!([50,50], [0, 100]; space=:pixel) - lines!([0,1], [0.25, 0.25]; space=:clip) - scatter!(Point2f(0.5, 0), space=:relative) + f = lines(exp.(0.1 * (1.0:100)); axis = (yscale = log10,)) + poly!(Rect(1, 1, 100, 100), color = :red, space = :pixel) + scatter!(2 * mod.(1:100:10000, 97), 2 * mod.(1:101:10000, 97), color = :blue, space = :pixel) + scatter!(Point2f(0, 0.25), space = :clip) + lines!([0.5, 0.5], [0, 1]; space = :relative) + lines!([50, 50], [0, 100]; space = :pixel) + lines!([0, 1], [0.25, 0.25]; space = :clip) + scatter!(Point2f(0.5, 0), space = :relative) f end diff --git a/ReferenceTests/src/tests/text.jl b/ReferenceTests/src/tests/text.jl index d2b128a2e01..1008ef55941 100644 --- a/ReferenceTests/src/tests/text.jl +++ b/ReferenceTests/src/tests/text.jl @@ -36,9 +36,9 @@ end i = 1 for halign in (:right, :center, :left), valign in (:top, :center, :bottom) - for rotation in (-pi/6, 0.0, pi/6) + for rotation in (-pi / 6, 0.0, pi / 6) text!(scene, string(halign) * "/" * string(valign) * - " " * string(round(rad2deg(rotation), digits = 0)) * "°", + " " * string(round(rad2deg(rotation), digits = 0)) * "°", color = (:black, 0.5), position = points[i], align = (halign, valign), @@ -53,18 +53,18 @@ end @reference_test "multi_strings_multi_positions" begin scene = Scene(camera = campixel!, resolution = (800, 800)) - angles = (-pi/6, 0.0, pi/6) + angles = (-pi / 6, 0.0, pi / 6) points = [Point(x, y) .* 200 for x in 1:3 for y in 1:3 for angle in angles] aligns = [(halign, valign) for halign in - (:right, :center, :left) for valign in (:top, :center, :bottom) for rotation in angles] + (:right, :center, :left) for valign in (:top, :center, :bottom) for rotation in angles] rotations = [rotation for _ in - (:right, :center, :left) for _ in (:top, :center, :bottom) for rotation in angles] + (:right, :center, :left) for _ in (:top, :center, :bottom) for rotation in angles] strings = [string(halign) * "/" * string(valign) * - " " * string(round(rad2deg(rotation), digits = 0)) * "°" - for halign in (:right, :center, :left) - for valign in (:top, :center, :bottom) - for rotation in angles] + " " * string(round(rad2deg(rotation), digits = 0)) * "°" + for halign in (:right, :center, :left) + for valign in (:top, :center, :bottom) + for rotation in angles] scatter!(scene, points, marker = :circle, markersize = 10px) @@ -102,7 +102,7 @@ end for (p, al) in zip(points[7:9], (:left, :center, :right)) text!(scene, p .+ (80, 0), text = "justification\n:" * string(al), - align = (:center, :top), rotation = pi/2) + align = (:center, :top), rotation = pi / 2) end scene @@ -113,8 +113,8 @@ end t1 = text!(scene, fill("makie", 4), - position = [(200, 200) .+ 60 * Point2f(cos(a), sin(a)) for a in pi/4:pi/2:7pi/4], - rotation = pi/4:pi/2:7pi/4, + position = [(200, 200) .+ 60 * Point2f(cos(a), sin(a)) for a in (pi / 4):(pi / 2):(7pi / 4)], + rotation = (pi / 4):(pi / 2):(7pi / 4), align = (:left, :center), fontsize = 30, markerspace = :data @@ -124,8 +124,8 @@ end t2 = text!(scene, fill("makie", 4), - position = [(200, 600) .+ 60 * Point2f(cos(a), sin(a)) for a in pi/4:pi/2:7pi/4], - rotation = pi/4:pi/2:7pi/4, + position = [(200, 600) .+ 60 * Point2f(cos(a), sin(a)) for a in (pi / 4):(pi / 2):(7pi / 4)], + rotation = (pi / 4):(pi / 2):(7pi / 4), align = (:left, :center), fontsize = 30, markerspace = :pixel @@ -139,7 +139,7 @@ end @reference_test "single_boundingboxes" begin scene = Scene(camera = campixel!, resolution = (800, 800)) - for a in pi/4:pi/2:7pi/4 + for a in (pi / 4):(pi / 2):(7pi / 4) t = text!(scene, "makie", @@ -172,7 +172,7 @@ end text( fill("Makie", 7), rotation = [i / 7 * 1.5pi for i in 1:7], - position = [Point3f(0, 0, i/2) for i in 1:7], + position = [Point3f(0, 0, i / 2) for i in 1:7], color = [cgrad(:viridis)[x] for x in LinRange(0, 1, 7)], align = (:left, :baseline), fontsize = 1, @@ -199,14 +199,14 @@ end @reference_test "3D screenspace annotations" begin positions = RNG.rand(Point3f, 10) - fig, ax, p = meshscatter(positions, color=:white) + fig, ax, p = meshscatter(positions, color = :white) text!( fill("Annotation", 10), position = positions, align = (:center, :center), fontsize = 20, markerspace = :pixel, - overdraw=false) + overdraw = false) fig end @@ -222,16 +222,16 @@ end scatter(f[1, 2], Point2f(0, 0)) text!(0, 0, text = "hello", offset = (40, 0), align = (:left, :center)) text!(0, 0, text = "hello", offset = (40, 0), align = (:left, :center), - rotation = -pi/4) + rotation = -pi / 4) text!(0, 0, text = "hello", offset = (40, 0), align = (:left, :center), - rotation = pi/4) + rotation = pi / 4) scatter(f[2, 1], Point2f[(0, 0), (10, 0), (20, 10)]) text!(0, 0, text = "ABC", markerspace = :data, offset = (0, 0), color = (:red, 0.3), align = (:left, :baseline)) text!(0, 0, text = "ABC", markerspace = :data, offset = (10, 0), color = (:green, 0.3), align = (:left, :baseline)) text!(0, 0, text = "ABC", markerspace = :data, offset = (20, 10), color = (:blue, 0.3), align = (:left, :baseline)) - LScene(f[2, 2], show_axis=false) + LScene(f[2, 2], show_axis = false) scatter!(Point3f[(0, 0, 0), (2, 2, 2)]) text!(1, 1, 1, text = "hello", offset = (10, 10)) @@ -248,12 +248,12 @@ end end @reference_test "latex strings" begin - f, ax , l = lines(cumsum(RNG.randn(1000)), + f, ax, l = lines(cumsum(RNG.randn(1000)), axis = ( - title = L"\sum_k{x y_k}", - xlabel = L"\lim_{x →\infty} A^j v_{(a + b)_k}^i \sqrt{23.5} x!= \sqrt{\frac{1+6}{4+a+g}}\int_{0}^{2π} \sin(x) dx", - ylabel = L"x + y - \sin(x) × \tan(y) + \sqrt{2}", - ), + title = L"\sum_k{x y_k}", + xlabel = L"\lim_{x →\infty} A^j v_{(a + b)_k}^i \sqrt{23.5} x!= \sqrt{\frac{1+6}{4+a+g}}\int_{0}^{2π} \sin(x) dx", + ylabel = L"x + y - \sin(x) × \tan(y) + \sqrt{2}", + ), figure = (fontsize = 18,) ) text!(500, 0, text = L"\int_{0}^{2π} \sin(x) dx") @@ -262,7 +262,7 @@ end end @reference_test "latex hlines in axis" begin - text(1, 1, text = L"\frac{\sqrt{x + y}}{\sqrt{x + y}}", fontsize = 50, rotation = pi/4, + text(1, 1, text = L"\frac{\sqrt{x + y}}{\sqrt{x + y}}", fontsize = 50, rotation = pi / 4, align = (:center, :center)) end @@ -271,7 +271,7 @@ end t = text!(s, L"\sqrt{2}", position = (50, 50), - rotation = pi/2, + rotation = pi / 2, markerspace = :data) s end @@ -327,11 +327,11 @@ end end @reference_test "latex ticks" begin - lines(0..25, x -> 4 * sin(x) / (cos(3x) + 4), figure = (fontsize = 25,), + lines(0 .. 25, x -> 4 * sin(x) / (cos(3x) + 4), figure = (fontsize = 25,), axis = ( xticks = (0:10:20, [L"10^{-3.5}", L"10^{-4.5}", L"10^{-5.5}"]), yticks = ([-1, 0, 1], [L"\sum_%$i{xy}" for i in 1:3]), - yticklabelrotation = pi/8, + yticklabelrotation = pi / 8, title = L"\int_0^1{x^2}", xlabel = L"\sum_k{x_k ⋅ y_k}", ylabel = L"\int_a^b{\sqrt{abx}}" @@ -341,20 +341,20 @@ end @reference_test "dynamic latex ticks" begin - lines(0..25, x -> 4 * sin(x) / (cos(3x) + 4), + lines(0 .. 25, x -> 4 * sin(x) / (cos(3x) + 4), figure = (fontsize = 16,), - axis = (xtickformat = (xs -> [L"e^{\sqrt{%$x}}+\sum" for x in xs]), )) + axis = (xtickformat = (xs -> [L"e^{\sqrt{%$x}}+\sum" for x in xs]),)) end @reference_test "Word Wrapping" begin lorem_ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." - fig = Figure(resolution=(600, 500)) + fig = Figure(resolution = (600, 500)) ax = Axis(fig[1, 1]) - text!(ax, 0, 0, text = latexstring(L"$1$ " * lorem_ipsum), word_wrap_width=250, fontsize = 12, align = (:left, :bottom), justification = :left, color = :black) - text!(ax, 0, 0, text = lorem_ipsum, word_wrap_width=250, fontsize = 12, align = (:left, :top), justification = :right, color = :black) - text!(ax, 0, 0, text = lorem_ipsum, word_wrap_width=250, fontsize = 12, align = (:right, :bottom), justification = :center, color = :red) - text!(ax, -0.3, 0, text = lorem_ipsum, word_wrap_width=200, fontsize = 12, align = (:center, :top), color = :blue) + text!(ax, 0, 0, text = latexstring(L"$1$ " * lorem_ipsum), word_wrap_width = 250, fontsize = 12, align = (:left, :bottom), justification = :left, color = :black) + text!(ax, 0, 0, text = lorem_ipsum, word_wrap_width = 250, fontsize = 12, align = (:left, :top), justification = :right, color = :black) + text!(ax, 0, 0, text = lorem_ipsum, word_wrap_width = 250, fontsize = 12, align = (:right, :bottom), justification = :center, color = :red) + text!(ax, -0.3, 0, text = lorem_ipsum, word_wrap_width = 200, fontsize = 12, align = (:center, :top), color = :blue) xlims!(ax, -0.8, 0.8) ylims!(ax, -0.8, 0.6) fig diff --git a/ReferenceTests/src/tests/updating.jl b/ReferenceTests/src/tests/updating.jl index ea1bb97c44f..d9b3cef5158 100644 --- a/ReferenceTests/src/tests/updating.jl +++ b/ReferenceTests/src/tests/updating.jl @@ -1,10 +1,10 @@ @reference_test "updating 2d primitives" begin fig = Figure() t = Observable(1) - text(fig[1, 1], lift(i-> map(j-> ("$j", Point2f(j*30, 0)), 1:i), t), axis=(limits=(0, 380, -10, 10),), fontsize=50) - scatter(fig[1, 2], lift(i-> Point2f.((1:i).*30, 0), t), axis=(limits=(0, 330, -10, 10),), markersize=50) - linesegments(fig[2, 1], lift(i-> Point2f.((2:2:4i).*30, 0), t), axis=(limits=(30, 650, -10, 10),), linewidth=20) - lines(fig[2, 2], lift(i-> Point2f.((2:2:4i).*30, 0), t), axis=(limits=(30, 650, -10, 10),), linewidth=20) + text(fig[1, 1], lift(i -> map(j -> ("$j", Point2f(j * 30, 0)), 1:i), t), axis = (limits = (0, 380, -10, 10),), fontsize = 50) + scatter(fig[1, 2], lift(i -> Point2f.((1:i) .* 30, 0), t), axis = (limits = (0, 330, -10, 10),), markersize = 50) + linesegments(fig[2, 1], lift(i -> Point2f.((2:2:(4i)) .* 30, 0), t), axis = (limits = (30, 650, -10, 10),), linewidth = 20) + lines(fig[2, 2], lift(i -> Point2f.((2:2:(4i)) .* 30, 0), t), axis = (limits = (30, 650, -10, 10),), linewidth = 20) st = Stepper(fig) @@ -21,21 +21,21 @@ end @reference_test "updating multiple meshes" begin - points = Observable(Point3f[(1,0,0), (0,1,0), (0,0,1)]) + points = Observable(Point3f[(1, 0, 0), (0, 1, 0), (0, 0, 1)]) - meshes = map(p->Makie.normal_mesh(Sphere(p, 0.2)), points[]) - colors = map(p->RGBf(normalize(p)...), points[]) + meshes = map(p -> Makie.normal_mesh(Sphere(p, 0.2)), points[]) + colors = map(p -> RGBf(normalize(p)...), points[]) fig, ax, pl = mesh(meshes; color = colors) st = Stepper(fig) Makie.step!(st) on(points) do pts - pl[1].val = map(p->Makie.normal_mesh(Sphere(p, 0.2)), points[]) - pl.color.val = map(p->RGBf(normalize(p)...), points[]) + pl[1].val = map(p -> Makie.normal_mesh(Sphere(p, 0.2)), points[]) + pl.color.val = map(p -> RGBf(normalize(p)...), points[]) notify(pl[1]) end - append!(points[], Point3f[(0,1,1), (1,0,1), (1,1,0)]) + append!(points[], Point3f[(0, 1, 1), (1, 0, 1), (1, 1, 0)]) notify(points) Makie.step!(st) end @@ -43,10 +43,10 @@ end function generate_plot(N = 3) points = Observable(Point2f[]) color = Observable(RGBAf[]) - fig, ax, pl = scatter(points, color=color, markersize=1.0, marker=Circle, markerspace=:data, axis=(type=Axis, aspect=DataAspect(), limits=(0.4, N + 0.6, 0.4, N + 0.6),), figure=(resolution=(800, 800),)) + fig, ax, pl = scatter(points, color = color, markersize = 1.0, marker = Circle, markerspace = :data, axis = (type = Axis, aspect = DataAspect(), limits = (0.4, N + 0.6, 0.4, N + 0.6),), figure = (resolution = (800, 800),)) function update_func(ij) push!(points.val, Point2f(Tuple(ij))) - push!(color.val, RGBAf((Tuple(ij)./N)..., 0, 1)) + push!(color.val, RGBAf((Tuple(ij) ./ N)..., 0, 1)) notify(color) notify(points) end @@ -60,10 +60,10 @@ end function load_frames(video, dir) framedir = joinpath(dir, "frames") - isdir(framedir) && rm(framedir; recursive=true, force=true) + isdir(framedir) && rm(framedir; recursive = true, force = true) mkdir(framedir) Makie.extract_frames(video, framedir) - return map(readdir(framedir; join=true)) do path + return map(readdir(framedir; join = true)) do path return convert(Matrix{RGB{N0f8}}, load(path)) end end @@ -92,7 +92,7 @@ end compare_videos(reference, path, dir) fig, iter, func = generate_plot(2) - vso = Makie.Record(func, fig, iter; format="mkv") + vso = Makie.Record(func, fig, iter; format = "mkv") path = joinpath(dir, "test.$format") save(path, vso) compare_videos(reference, path, dir) diff --git a/ReferenceTests/src/visual-regression.jl b/ReferenceTests/src/visual-regression.jl index a0a362e94df..413bef27804 100644 --- a/ReferenceTests/src/visual-regression.jl +++ b/ReferenceTests/src/visual-regression.jl @@ -30,47 +30,47 @@ end minfinite_scalar(a::T, b::T) where {T} = isfinite(a) ? (b < a ? b : a) : b maxfinite_scalar(a::T, b::T) where {T} = isfinite(a) ? (b > a ? b : a) : b -minfinite_scalar(a::T, b::T) where {T <: Union{Integer,FixedPoint}} = b < a ? b : a -maxfinite_scalar(a::T, b::T) where {T <: Union{Integer,FixedPoint}} = b > a ? b : a +minfinite_scalar(a::T, b::T) where {T<:Union{Integer,FixedPoint}} = b < a ? b : a +maxfinite_scalar(a::T, b::T) where {T<:Union{Integer,FixedPoint}} = b > a ? b : a minfinite_scalar(a, b) = minfinite_scalar(promote(a, b)...) maxfinite_scalar(a, b) = maxfinite_scalar(promote(a, b)...) -function minfinite_scalar(c1::C, c2::C) where C <: AbstractRGB +function minfinite_scalar(c1::C, c2::C) where C<:AbstractRGB C(minfinite_scalar(c1.r, c2.r), - minfinite_scalar(c1.g, c2.g), - minfinite_scalar(c1.b, c2.b)) + minfinite_scalar(c1.g, c2.g), + minfinite_scalar(c1.b, c2.b)) end -function maxfinite_scalar(c1::C, c2::C) where C <: AbstractRGB +function maxfinite_scalar(c1::C, c2::C) where C<:AbstractRGB C(maxfinite_scalar(c1.r, c2.r), - maxfinite_scalar(c1.g, c2.g), - maxfinite_scalar(c1.b, c2.b)) + maxfinite_scalar(c1.g, c2.g), + maxfinite_scalar(c1.b, c2.b)) end -sentinel_min(::Type{T}) where {T <: Union{Integer,FixedPoint}} = typemax(T) -sentinel_max(::Type{T}) where {T <: Union{Integer,FixedPoint}} = typemin(T) -sentinel_min(::Type{T}) where {T <: AbstractFloat} = convert(T, NaN) -sentinel_max(::Type{T}) where {T <: AbstractFloat} = convert(T, NaN) -sentinel_min(::Type{C}) where {C <: AbstractRGB} = _sentinel_min(C, eltype(C)) -_sentinel_min(::Type{C},::Type{T}) where {C <: AbstractRGB,T} = (s = sentinel_min(T); C(s, s, s)) -sentinel_max(::Type{C}) where {C <: AbstractRGB} = _sentinel_max(C, eltype(C)) -_sentinel_max(::Type{C},::Type{T}) where {C <: AbstractRGB,T} = (s = sentinel_max(T); C(s, s, s)) +sentinel_min(::Type{T}) where {T<:Union{Integer,FixedPoint}} = typemax(T) +sentinel_max(::Type{T}) where {T<:Union{Integer,FixedPoint}} = typemin(T) +sentinel_min(::Type{T}) where {T<:AbstractFloat} = convert(T, NaN) +sentinel_max(::Type{T}) where {T<:AbstractFloat} = convert(T, NaN) +sentinel_min(::Type{C}) where {C<:AbstractRGB} = _sentinel_min(C, eltype(C)) +_sentinel_min(::Type{C}, ::Type{T}) where {C<:AbstractRGB,T} = (s = sentinel_min(T); C(s, s, s)) +sentinel_max(::Type{C}) where {C<:AbstractRGB} = _sentinel_max(C, eltype(C)) +_sentinel_max(::Type{C}, ::Type{T}) where {C<:AbstractRGB,T} = (s = sentinel_max(T); C(s, s, s)) -difftype(::Type{T}) where {T <: Integer} = Int -difftype(::Type{T}) where {T <: Real} = Float32 +difftype(::Type{T}) where {T<:Integer} = Int +difftype(::Type{T}) where {T<:Real} = Float32 difftype(::Type{Float64}) = Float64 -difftype(::Type{CV}) where {CV <: Colorant} = difftype(CV, eltype(CV)) -difftype(::Type{CV}, ::Type{T}) where {CV <: RGBA,T <: Real} = RGBA{Float32} -difftype(::Type{CV}, ::Type{Float64}) where {CV <: RGBA} = RGBA{Float64} -difftype(::Type{CV}, ::Type{Float64}) where {CV <: Gray} = Gray{Float64} -difftype(::Type{CV}, ::Type{T}) where {CV <: BGRA,T <: Real} = BGRA{Float32} -difftype(::Type{CV}, ::Type{Float64}) where {CV <: BGRA} = BGRA{Float64} -difftype(::Type{CV}, ::Type{T}) where {CV <: AbstractRGB,T <: Real} = RGB{Float32} -difftype(::Type{CV}, ::Type{Float64}) where {CV <: AbstractRGB} = RGB{Float64} +difftype(::Type{CV}) where {CV<:Colorant} = difftype(CV, eltype(CV)) +difftype(::Type{CV}, ::Type{T}) where {CV<:RGBA,T<:Real} = RGBA{Float32} +difftype(::Type{CV}, ::Type{Float64}) where {CV<:RGBA} = RGBA{Float64} +difftype(::Type{CV}, ::Type{Float64}) where {CV<:Gray} = Gray{Float64} +difftype(::Type{CV}, ::Type{T}) where {CV<:BGRA,T<:Real} = BGRA{Float32} +difftype(::Type{CV}, ::Type{Float64}) where {CV<:BGRA} = BGRA{Float64} +difftype(::Type{CV}, ::Type{T}) where {CV<:AbstractRGB,T<:Real} = RGB{Float32} +difftype(::Type{CV}, ::Type{Float64}) where {CV<:AbstractRGB} = RGB{Float64} -accum(::Type{T}) where {T <: Integer} = Int -accum(::Type{Float32}) = Float32 -accum(::Type{T}) where {T <: Real} = Float64 -accum(::Type{C}) where {C <: Colorant} = base_colorant_type(C){accum(eltype(C))} +accum(::Type{T}) where {T<:Integer} = Int +accum(::Type{Float32}) = Float32 +accum(::Type{T}) where {T<:Real} = Float64 +accum(::Type{C}) where {C<:Colorant} = base_colorant_type(C){accum(eltype(C))} function sumdiff(f, A::AbstractArray, B::AbstractArray) axes(A) == axes(B) || throw(DimensionMismatch("A and B must have the same axes")) T = promote_type(difftype(eltype(A)), difftype(eltype(B))) @@ -90,10 +90,10 @@ sad(A::AbstractArray, B::AbstractArray) = sumdiff(abs, A, B) function approx_difference( - A::AbstractArray, B::AbstractArray, - sigma::AbstractVector{T}=ones(ndims(A)), - eps::AbstractFloat=1e-2 - ) where T <: Real + A::AbstractArray, B::AbstractArray, + sigma::AbstractVector{T} = ones(ndims(A)), + eps::AbstractFloat = 1e-2 +) where T<:Real if length(sigma) != ndims(A) error("Invalid sigma in test_approx_eq_sigma_eps. Should be ndims(A)-length vector of the number of pixels to blur. Got: $sigma") diff --git a/WGLMakie/src/WGLMakie.jl b/WGLMakie/src/WGLMakie.jl index eaaab22aa03..83c53dc37c3 100644 --- a/WGLMakie/src/WGLMakie.jl +++ b/WGLMakie/src/WGLMakie.jl @@ -79,7 +79,7 @@ function __init__() end # re-export Makie, including deprecated names -for name in names(Makie, all=true) +for name in names(Makie, all = true) if Base.isexported(Makie, name) && name !== :Button && name !== :Slider @eval using Makie: $(name) @eval export $(name) diff --git a/WGLMakie/src/display.jl b/WGLMakie/src/display.jl index ef843258194..179a74d4007 100644 --- a/WGLMakie/src/display.jl +++ b/WGLMakie/src/display.jl @@ -37,7 +37,7 @@ $(Base.doc(MakieScreen)) mutable struct Screen <: Makie.MakieScreen three::Channel{ThreeDisplay} display::Any - scene::Union{Nothing, Scene} + scene::Union{Nothing,Scene} end for M in WEB_MIMES @@ -125,7 +125,7 @@ function session2image(sessionlike) return document.querySelector('canvas').toDataURL() }() """ - picture_base64 = JSServe.evaljs_value(s, to_data; time_out=100) + picture_base64 = JSServe.evaljs_value(s, to_data; time_out = 100) picture_base64 = replace(picture_base64, "data:image/png;base64," => "") bytes = JSServe.Base64.base64decode(picture_base64) return ImageMagick.load_(bytes) @@ -146,7 +146,7 @@ function Makie.colorbuffer(screen::Screen) return session2image(three) end -function wait_for_three(three_ref::Base.RefValue{ThreeDisplay}; timeout = 30)::Union{Nothing, ThreeDisplay} +function wait_for_three(three_ref::Base.RefValue{ThreeDisplay}; timeout = 30)::Union{Nothing,ThreeDisplay} # Screen is not guaranteed to get displayed in the browser, so we wait a while # to see if anything gets displayed! tstart = time() diff --git a/WGLMakie/src/imagelike.jl b/WGLMakie/src/imagelike.jl index c5c146b2de3..ddeb001600a 100644 --- a/WGLMakie/src/imagelike.jl +++ b/WGLMakie/src/imagelike.jl @@ -42,8 +42,8 @@ xy_convert(x, n) = Float32[LinRange(extrema(x)..., n + 1);] function limits_to_uvmesh(plot) px, py, pz = plot[1], plot[2], plot[3] - px = map((x, z)-> xy_convert(x, size(z, 1)), px, pz) - py = map((y, z)-> xy_convert(y, size(z, 2)), py, pz) + px = map((x, z) -> xy_convert(x, size(z, 1)), px, pz) + py = map((y, z) -> xy_convert(y, size(z, 2)), py, pz) # Special path for ranges of length 2 which # can be displayed as a rectangle t = Makie.transform_func_obs(plot)[] @@ -53,18 +53,18 @@ function limits_to_uvmesh(plot) ymin, ymax = extrema(y) return Rect2(xmin, ymin, xmax - xmin, ymax - ymin) end - positions = Buffer(lift(rect-> decompose(Point2f, rect), rect)) + positions = Buffer(lift(rect -> decompose(Point2f, rect), rect)) faces = Buffer(lift(rect -> decompose(GLTriangleFace, rect), rect)) uv = Buffer(lift(decompose_uv, rect)) - else - grid(x, y, trans, space) = Makie.matrix_grid(p-> apply_transform(trans, p, space), x, y, zeros(length(x), length(y))) + else + grid(x, y, trans, space) = Makie.matrix_grid(p -> apply_transform(trans, p, space), x, y, zeros(length(x), length(y))) rect = lift((x, y) -> Tesselation(Rect2(0f0, 0f0, 1f0, 1f0), (length(x), length(y))), px, py) positions = Buffer(lift(grid, px, py, t, get(plot, :space, :data))) faces = Buffer(lift(r -> decompose(GLTriangleFace, r), rect)) uv = Buffer(lift(decompose_uv, rect)) end - vertices = GeometryBasics.meta(positions; uv=uv) + vertices = GeometryBasics.meta(positions; uv = uv) return GeometryBasics.Mesh(vertices, faces) end @@ -80,7 +80,7 @@ end function create_shader(mscene::Scene, plot::Surface) # TODO OWN OPTIMIZED SHADER ... Or at least optimize this a bit more ... px, py, pz = plot[1], plot[2], plot[3] - grid(x, y, z, trans, space) = Makie.matrix_grid(p-> apply_transform(trans, p, space), x, y, z) + grid(x, y, z, trans, space) = Makie.matrix_grid(p -> apply_transform(trans, p, space), x, y, z) positions = Buffer(lift(grid, px, py, pz, transform_func_obs(plot), get(plot, :space, :data))) rect = lift(z -> Tesselation(Rect2(0f0, 0f0, 1f0, 1f0), size(z)), pz) faces = Buffer(lift(r -> decompose(GLTriangleFace, r), rect)) @@ -96,24 +96,24 @@ function create_shader(mscene::Scene, plot::Surface) pz end minfilter = to_value(get(plot, :interpolate, true)) ? :linear : :nearest - color = Sampler(lift(x -> el32convert(to_color(permutedims(x))), pcolor), minfilter=minfilter) + color = Sampler(lift(x -> el32convert(to_color(permutedims(x))), pcolor), minfilter = minfilter) normals = Buffer(lift(surface_normals, px, py, pz)) - vertices = GeometryBasics.meta(positions; uv=uv, normals=normals) + vertices = GeometryBasics.meta(positions; uv = uv, normals = normals) mesh = GeometryBasics.Mesh(vertices, faces) - return draw_mesh(mscene, mesh, plot_attributes; uniform_color=color, color=false, - shading=plot.shading, diffuse=plot.diffuse, - specular=plot.specular, shininess=plot.shininess, - depth_shift=get(plot, :depth_shift, Observable(0f0)), - backlight=plot.backlight, - highclip=get_color(plot, :highclip), - lowclip=get_color(plot, :lowclip), - nan_color=get_color(plot, :nan_color)) + return draw_mesh(mscene, mesh, plot_attributes; uniform_color = color, color = false, + shading = plot.shading, diffuse = plot.diffuse, + specular = plot.specular, shininess = plot.shininess, + depth_shift = get(plot, :depth_shift, Observable(0f0)), + backlight = plot.backlight, + highclip = get_color(plot, :highclip), + lowclip = get_color(plot, :lowclip), + nan_color = get_color(plot, :nan_color)) end -function create_shader(mscene::Scene, plot::Union{Heatmap, Image}) +function create_shader(mscene::Scene, plot::Union{Heatmap,Image}) image = plot[3] color = Sampler(map(x -> el32convert(x'), image); - minfilter=to_value(get(plot, :interpolate, false)) ? :linear : :nearest) + minfilter = to_value(get(plot, :interpolate, false)) ? :linear : :nearest) mesh = limits_to_uvmesh(plot) plot_attributes = copy(plot.attributes) if eltype(color) <: Colorant @@ -122,16 +122,16 @@ function create_shader(mscene::Scene, plot::Union{Heatmap, Image}) end return draw_mesh(mscene, mesh, plot_attributes; - uniform_color=color, color=false, - normals=Vec3f(0), shading=false, - diffuse=plot.diffuse, specular=plot.specular, - colorrange=haskey(plot, :colorrange) ? plot.colorrange : false, - shininess=plot.shininess, - highclip=get_color(plot, :highclip), - lowclip=get_color(plot, :lowclip), - nan_color=get_color(plot, :nan_color), - backlight=0f0, - depth_shift = get(plot, :depth_shift, Observable(0f0))) + uniform_color = color, color = false, + normals = Vec3f(0), shading = false, + diffuse = plot.diffuse, specular = plot.specular, + colorrange = haskey(plot, :colorrange) ? plot.colorrange : false, + shininess = plot.shininess, + highclip = get_color(plot, :highclip), + lowclip = get_color(plot, :lowclip), + nan_color = get_color(plot, :nan_color), + backlight = 0f0, + depth_shift = get(plot, :depth_shift, Observable(0f0))) end function create_shader(mscene::Scene, plot::Volume) @@ -150,16 +150,16 @@ function create_shader(mscene::Scene, plot::Volume) algorithm = lift(x -> Cuint(convert_attribute(x, key"algorithm"())), plot.algorithm) return Program(WebGL(), lasset("volume.vert"), lasset("volume.frag"), box, - volumedata=Sampler(lift(Makie.el32convert, vol)), - modelinv=modelinv, colormap=Sampler(lift(to_colormap, plot.colormap)), - colorrange=lift(Vec2f, plot.colorrange), - isovalue=lift(Float32, plot.isovalue), - isorange=lift(Float32, plot.isorange), - absorption=lift(Float32, get(plot, :absorption, Observable(1f0))), - algorithm=algorithm, - diffuse=plot.diffuse, specular=plot.specular, shininess=plot.shininess, - model=model2, depth_shift = get(plot, :depth_shift, Observable(0f0)), - # these get filled in later by serialization, but we need them - # as dummy values here, so that the correct uniforms are emitted - lightposition=Vec3f(1), eyeposition=Vec3f(1), ambient=Vec3f(1)) + volumedata = Sampler(lift(Makie.el32convert, vol)), + modelinv = modelinv, colormap = Sampler(lift(to_colormap, plot.colormap)), + colorrange = lift(Vec2f, plot.colorrange), + isovalue = lift(Float32, plot.isovalue), + isorange = lift(Float32, plot.isorange), + absorption = lift(Float32, get(plot, :absorption, Observable(1f0))), + algorithm = algorithm, + diffuse = plot.diffuse, specular = plot.specular, shininess = plot.shininess, + model = model2, depth_shift = get(plot, :depth_shift, Observable(0f0)), + # these get filled in later by serialization, but we need them + # as dummy values here, so that the correct uniforms are emitted + lightposition = Vec3f(1), eyeposition = Vec3f(1), ambient = Vec3f(1)) end diff --git a/WGLMakie/src/lines.jl b/WGLMakie/src/lines.jl index 6a8fc668f4e..07031d37c0c 100644 --- a/WGLMakie/src/lines.jl +++ b/WGLMakie/src/lines.jl @@ -19,7 +19,7 @@ function create_shader(scene::Scene, plot::Union{Lines,LineSegments}) return points else # Repeat every second point to connect the lines ! - return topoint(TupleView{2, 1}(points)) + return topoint(TupleView{2,1}(points)) end trans end @@ -30,7 +30,7 @@ function create_shader(scene::Scene, plot::Union{Lines,LineSegments}) end per_instance = Dict{Symbol,Any}(:segment_start => Buffer(lift(first, p_start_end)), - :segment_end => Buffer(lift(last, p_start_end))) + :segment_end => Buffer(lift(last, p_start_end))) uniforms = Dict{Symbol,Any}() for k in (:linewidth, :color) attribute = lift(plot[k]) do x @@ -39,7 +39,7 @@ function create_shader(scene::Scene, plot::Union{Lines,LineSegments}) return x else # Repeat every second point to connect the lines! - return isscalar(x) ? x : reinterpret(eltype(x), TupleView{2, 1}(x)) + return isscalar(x) ? x : reinterpret(eltype(x), TupleView{2,1}(x)) end end if isscalar(attribute) @@ -59,10 +59,10 @@ function create_shader(scene::Scene, plot::Union{Lines,LineSegments}) uniforms[:model] = plot.model uniforms[:depth_shift] = get(plot, :depth_shift, Observable(0f0)) positions = meta(Point2f[(0, -1), (0, 1), (1, -1), (1, 1)], - uv=Vec2f[(0, 0), (0, 0), (0, 0), (0, 0)]) + uv = Vec2f[(0, 0), (0, 0), (0, 0), (0, 0)]) instance = GeometryBasics.Mesh(positions, GLTriangleFace[(1, 2, 3), (2, 4, 3)]) return InstancedProgram(WebGL(), lasset("line_segments.vert"), - lasset("line_segments.frag"), instance, - VertexArray(; per_instance...); uniforms...) + lasset("line_segments.frag"), instance, + VertexArray(; per_instance...); uniforms...) end diff --git a/WGLMakie/src/meshes.jl b/WGLMakie/src/meshes.jl index 9f433ef6486..d5957bae410 100644 --- a/WGLMakie/src/meshes.jl +++ b/WGLMakie/src/meshes.jl @@ -1,6 +1,6 @@ function vertexbuffer(x, trans, space) pos = decompose(Point, x) - return apply_transform(trans, pos, space) + return apply_transform(trans, pos, space) end function vertexbuffer(x::Observable, p) diff --git a/WGLMakie/src/particles.jl b/WGLMakie/src/particles.jl index b7703701429..4bacc1db2ce 100644 --- a/WGLMakie/src/particles.jl +++ b/WGLMakie/src/particles.jl @@ -8,8 +8,8 @@ function handle_color!(uniform_dict, instance_dict) nothing, uniform_dict end if color isa Colorant || - color isa AbstractVector{<:Colorant} || - color === nothing + color isa AbstractVector{<:Colorant} || + color === nothing delete!(uniform_dict, :colormap) elseif color isa AbstractArray{<:Real} uniform_dict[:color_getter] = """ @@ -54,7 +54,7 @@ function create_shader(scene::Scene, plot::MeshScatter) return k in per_instance_keys && !(isscalar(v[])) end space = get(plot, :space, :data) - per_instance[:offset] = apply_transform(transform_func_obs(plot), plot[1], space) + per_instance[:offset] = apply_transform(transform_func_obs(plot), plot[1], space) for (k, v) in per_instance per_instance[k] = Buffer(lift_convert(k, v, plot)) @@ -90,7 +90,7 @@ function create_shader(scene::Scene, plot::MeshScatter) end return InstancedProgram(WebGL(), lasset("particles.vert"), lasset("particles.frag"), - instance, VertexArray(; per_instance...); uniform_dict...) + instance, VertexArray(; per_instance...); uniform_dict...) end using Makie: to_spritemarker @@ -98,7 +98,7 @@ using Makie: to_spritemarker function scatter_shader(scene::Scene, attributes) # Potentially per instance attributes per_instance_keys = (:pos, :rotations, :markersize, :color, :intensity, - :uv_offset_width, :quad_offset, :marker_offset) + :uv_offset_width, :quad_offset, :marker_offset) uniform_dict = Dict{Symbol,Any}() uniform_dict[:image] = false marker = nothing @@ -144,8 +144,8 @@ function scatter_shader(scene::Scene, attributes) end if uniform_dict[:shape_type][] == 3 - uniform_dict[:distancefield] = Sampler(atlas.data, minfilter=:linear, - magfilter=:linear, anisotropic=16f0) + uniform_dict[:distancefield] = Sampler(atlas.data, minfilter = :linear, + magfilter = :linear, anisotropic = 16f0) uniform_dict[:atlas_texture_size] = Float32(size(atlas, 1)) # Texture must be quadratic else uniform_dict[:atlas_texture_size] = 0f0 @@ -158,13 +158,13 @@ function scatter_shader(scene::Scene, attributes) uniform_dict[:resolution] = scene.camera.resolution return InstancedProgram(WebGL(), lasset("simple.vert"), lasset("sprites.frag"), - instance, VertexArray(; per_instance...); uniform_dict...) + instance, VertexArray(; per_instance...); uniform_dict...) end function create_shader(scene::Scene, plot::Scatter) # Potentially per instance attributes per_instance_keys = (:offset, :rotations, :markersize, :color, :intensity, - :quad_offset) + :quad_offset) per_instance = filter(plot.attributes.attributes) do (k, v) return k in per_instance_keys && !(isscalar(v[])) end @@ -175,7 +175,7 @@ function create_shader(scene::Scene, plot::Scatter) attributes[:preprojection] = map(space, mspace, cam.projectionview, cam.resolution) do space, mspace, _, _ Makie.clip_to_space(cam, mspace) * Makie.space_to_clip(cam, space) end - attributes[:pos] = apply_transform(transform_func_obs(plot), plot[1], space) + attributes[:pos] = apply_transform(transform_func_obs(plot), plot[1], space) quad_offset = get(attributes, :marker_offset, Observable(Vec2f(0))) attributes[:marker_offset] = Vec3f(0) attributes[:quad_offset] = quad_offset @@ -194,11 +194,11 @@ value_or_first(x::StaticVector) = x value_or_first(x::Mat) = x value_or_first(x) = x -function create_shader(scene::Scene, plot::Makie.Text{<:Tuple{<:Union{<:Makie.GlyphCollection, <:AbstractVector{<:Makie.GlyphCollection}}}}) +function create_shader(scene::Scene, plot::Makie.Text{<:Tuple{<:Union{<:Makie.GlyphCollection,<:AbstractVector{<:Makie.GlyphCollection}}}}) glyphcollection = plot[1] - res = map(x->Vec2f(widths(x)), pixelarea(scene)) + res = map(x -> Vec2f(widths(x)), pixelarea(scene)) projview = scene.camera.projectionview - transfunc = Makie.transform_func_obs(scene) + transfunc = Makie.transform_func_obs(scene) pos = plot.position space = plot.space markerspace = plot.markerspace diff --git a/WGLMakie/src/precompiles.jl b/WGLMakie/src/precompiles.jl index be5fa88c49a..8bdbe9d3d2d 100644 --- a/WGLMakie/src/precompiles.jl +++ b/WGLMakie/src/precompiles.jl @@ -11,7 +11,7 @@ macro compile(block) three_display(Session(), scene) JSServe.jsrender(Session(), figlike) s = serialize_scene(scene) - JSServe.serialize_binary(Session(), Dict(:data=>s)) + JSServe.serialize_binary(Session(), Dict(:data => s)) end end diff --git a/WGLMakie/src/serialization.jl b/WGLMakie/src/serialization.jl index d5c3bce2170..417ef6211ad 100644 --- a/WGLMakie/src/serialization.jl +++ b/WGLMakie/src/serialization.jl @@ -36,7 +36,7 @@ serialize_three(val::Mat3) = vec(val) function serialize_three(observable::Observable) return Dict(:type => "Observable", :id => observable.id, - :value => serialize_three(observable[])) + :value => serialize_three(observable[])) end function serialize_three(array::AbstractArray) @@ -77,11 +77,11 @@ end function serialize_three(color::Sampler{T,N}) where {T,N} tex = Dict(:type => "Sampler", :data => serialize_three(color.data), - :size => [size(color.data)...], :three_format => three_format(T), - :three_type => three_type(eltype(T)), - :minFilter => three_filter(color.minfilter), - :magFilter => three_filter(color.magfilter), - :wrapS => three_repeat(color.repeat[1]), :anisotropy => color.anisotropic) + :size => [size(color.data)...], :three_format => three_format(T), + :three_type => three_type(eltype(T)), + :minFilter => three_filter(color.minfilter), + :magFilter => three_filter(color.magfilter), + :wrapS => three_repeat(color.repeat[1]), :anisotropy => color.anisotropic) if N > 1 tex[:wrapT] = three_repeat(color.repeat[2]) end @@ -126,7 +126,7 @@ Flattens `array` array to be a 1D Vector of Float32 / UInt8. If presented with AbstractArray{<: Colorant/Tuple/SVector}, it will flatten those to their element type. """ -function flatten_buffer(array::AbstractArray{<: Number}) +function flatten_buffer(array::AbstractArray{<:Number}) return array end @@ -152,12 +152,12 @@ isscalar(x::Observable) = isscalar(x[]) isscalar(x) = true function ShaderAbstractions.type_string(::ShaderAbstractions.AbstractContext, - ::Type{<:Makie.Quaternion}) + ::Type{<:Makie.Quaternion}) return "vec4" end function ShaderAbstractions.convert_uniform(::ShaderAbstractions.AbstractContext, - t::Quaternion) + t::Quaternion) return convert(Quaternion, t) end @@ -180,8 +180,8 @@ end function serialize_named_buffer(buffer) return Dict(map(pairs(buffer)) do (name, buff) - return name => serialize_buffer_attribute(buff) - end) + return name => serialize_buffer_attribute(buff) + end) end function register_geometry_updates(update_buffer::Observable, named_buffers) @@ -244,14 +244,14 @@ function serialize_three(program::Program) attribute_updater = Observable(["", [], 0]) register_geometry_updates(attribute_updater, program) return Dict(:vertexarrays => serialize_named_buffer(program.vertexarray), - :faces => indices, :uniforms => uniforms, - :vertex_source => program.vertex_source, - :fragment_source => program.fragment_source, - :uniform_updater => uniform_updater(program.uniforms), - :attribute_updater => attribute_updater) + :faces => indices, :uniforms => uniforms, + :vertex_source => program.vertex_source, + :fragment_source => program.fragment_source, + :uniform_updater => uniform_updater(program.uniforms), + :attribute_updater => attribute_updater) end -function serialize_scene(scene::Scene, serialized_scenes=[]) +function serialize_scene(scene::Scene, serialized_scenes = []) hexcolor(c) = "#" * hex(Colors.color(to_color(c))) pixel_area = lift(area -> [minimum(area)..., widths(area)...], pixelarea(scene)) cam_controls = cameracontrols(scene) @@ -263,13 +263,13 @@ function serialize_scene(scene::Scene, serialized_scenes=[]) end serialized = Dict(:pixelarea => pixel_area, - :backgroundcolor => lift(hexcolor, scene.backgroundcolor), - :clearscene => scene.clear, - :camera => serialize_camera(scene), - :plots => serialize_plots(scene, scene.plots), - :cam3d_state => cam3d_state, - :visible => scene.visible, - :uuid => js_uuid(scene)) + :backgroundcolor => lift(hexcolor, scene.backgroundcolor), + :clearscene => scene.clear, + :camera => serialize_camera(scene), + :plots => serialize_plots(scene, scene.plots), + :cam3d_state => cam3d_state, + :visible => scene.visible, + :uuid => js_uuid(scene)) push!(serialized_scenes, serialized) foreach(child -> serialize_scene(child, serialized_scenes), scene.children) @@ -277,7 +277,7 @@ function serialize_scene(scene::Scene, serialized_scenes=[]) return serialized_scenes end -function serialize_plots(scene::Scene, plots::Vector{T}, result=[]) where {T<:AbstractPlot} +function serialize_plots(scene::Scene, plots::Vector{T}, result = []) where {T<:AbstractPlot} for plot in plots # if no plots inserted, this truely is an atomic if isempty(plot.plots) diff --git a/WGLMakie/src/three_plot.jl b/WGLMakie/src/three_plot.jl index 430aed731e3..74d2bb322f7 100644 --- a/WGLMakie/src/three_plot.jl +++ b/WGLMakie/src/three_plot.jl @@ -12,7 +12,7 @@ end function Base.size(screen::ThreeDisplay) # look at d.qs().clientWidth for displayed width - width, height = round.(Int, WGLMakie.JSServe.evaljs_value(screen.session, WGLMakie.JSServe.js"[document.querySelector('canvas').width, document.querySelector('canvas').height]"; time_out=100)) + width, height = round.(Int, WGLMakie.JSServe.evaljs_value(screen.session, WGLMakie.JSServe.js"[document.querySelector('canvas').width, document.querySelector('canvas').height]"; time_out = 100)) return (width, height) end @@ -21,9 +21,12 @@ js_uuid(object) = string(objectid(object)) function Base.insert!(td::ThreeDisplay, scene::Scene, plot::Combined) plot_data = serialize_plots(scene, [plot]) - JSServe.evaljs_value(td.session, js""" - $(WGL).insert_plot($(js_uuid(scene)), $plot_data) - """) + JSServe.evaljs_value( + td.session, + js""" + $(WGL).insert_plot($(js_uuid(scene)), $plot_data) +""" + ) return end @@ -33,13 +36,13 @@ function Base.delete!(td::ThreeDisplay, scene::Scene, plot::Combined) return end -function all_plots_scenes(scene::Scene; scene_uuids=String[], plot_uuids=String[]) +function all_plots_scenes(scene::Scene; scene_uuids = String[], plot_uuids = String[]) push!(scene_uuids, js_uuid(scene)) for plot in scene.plots append!(plot_uuids, (js_uuid(p) for p in Makie.flatten_plots(plot))) end for child in scene.children - all_plots_scenes(child, plot_uuids=plot_uuids, scene_uuids=scene_uuids) + all_plots_scenes(child, plot_uuids = plot_uuids, scene_uuids = scene_uuids) end return scene_uuids, plot_uuids end @@ -79,7 +82,7 @@ function three_display(session::Session, scene::Scene; screen_config...) width, height = size(scene) - canvas = DOM.um("canvas", tabindex="0") + canvas = DOM.um("canvas", tabindex = "0") wrapper = DOM.div(canvas) comm = Observable(Dict{String,Any}()) push!(session, comm) diff --git a/WGLMakie/test/offline_export.jl b/WGLMakie/test/offline_export.jl index 0d08ca7c066..bbcfdf8ad98 100644 --- a/WGLMakie/test/offline_export.jl +++ b/WGLMakie/test/offline_export.jl @@ -1,7 +1,7 @@ using JSServe, WGLMakie, Makie function handler(session, request) - return scatter(1:4, color=1:4) + return scatter(1:4, color = 1:4) end dir = joinpath(@__DIR__, "exported") @@ -10,4 +10,4 @@ JSServe.export_standalone(handler, dir) # Then serve it with e.g. LiveServer using LiveServer -LiveServer.serve(dir=dir) +LiveServer.serve(dir = dir) diff --git a/src/Makie.jl b/src/Makie.jl index 9de6f9550e9..f39844f79ff 100644 --- a/src/Makie.jl +++ b/src/Makie.jl @@ -75,7 +75,7 @@ using MakieCore: Key, @key_str, Automatic, automatic, @recipe using MakieCore: Pixel, px, Unit, Billboard using MakieCore: not_implemented_for import MakieCore: plot, plot!, theme, plotfunc, plottype, merge_attributes!, calculated_attributes!, -get_attribute, plotsym, plotkey, attributes, used_attributes + get_attribute, plotsym, plotkey, attributes, used_attributes import MakieCore: arrows, heatmap, image, lines, linesegments, mesh, meshscatter, poly, scatter, surface, text, volume import MakieCore: arrows!, heatmap!, image!, lines!, linesegments!, mesh!, meshscatter!, poly!, scatter!, surface!, text!, volume! import MakieCore: convert_arguments, convert_attribute, default_theme, conversion_trait @@ -84,7 +84,7 @@ export @L_str export ConversionTrait, NoConversion, PointBased, SurfaceLike, ContinuousSurface, DiscreteSurface, VolumeLike export Pixel, px, Unit, plotkey, attributes, used_attributes -const RealVector{T} = AbstractVector{T} where T <: Number +const RealVector{T} = AbstractVector{T} where T<:Number const RGBAf = RGBA{Float32} const RGBf = RGB{Float32} const NativeFont = FreeTypeAbstraction.FTFont @@ -241,7 +241,7 @@ export mouseover, onpick, pick, Events, Keyboard, Mouse, mouse_selection, is_mou export ispressed, Exclusively export connect_screen export window_area, window_open, mouse_buttons, mouse_position, mouseposition_px, - scroll, keyboard_buttons, unicode_input, dropped_files, hasfocus, entered_window + scroll, keyboard_buttons, unicode_input, dropped_files, hasfocus, entered_window export disconnect! export DataInspector export Consume @@ -283,7 +283,7 @@ export assetpath function icon() path = assetpath("icons") imgs = FileIO.load.(joinpath.(path, readdir(path))) - icons = map(img-> RGBA{Colors.N0f8}.(img), imgs) + icons = map(img -> RGBA{Colors.N0f8}.(img), imgs) return reinterpret.(NTuple{4,UInt8}, icons) end @@ -295,7 +295,7 @@ function __init__() # Make GridLayoutBase default row and colgaps themeable when using Makie # This mutates module-level state so it could mess up other libraries using # GridLayoutBase at the same time as Makie, which is unlikely, though - GridLayoutBase.DEFAULT_COLGAP_GETTER[] = function() + GridLayoutBase.DEFAULT_COLGAP_GETTER[] = function () ct = Makie.current_default_theme() if haskey(ct, :colgap) ct[:colgap][] @@ -303,7 +303,7 @@ function __init__() GridLayoutBase.DEFAULT_COLGAP[] end end - GridLayoutBase.DEFAULT_ROWGAP_GETTER[] = function() + GridLayoutBase.DEFAULT_ROWGAP_GETTER[] = function () ct = Makie.current_default_theme() if haskey(ct, :rowgap) ct[:rowgap][] @@ -316,7 +316,7 @@ function __init__() cfg_path = joinpath(homedir(), ".config", "makie", "theme.jl") if isfile(cfg_path) @warn "The global configuration file is no longer supported." * - "Please include the file manually with `include(\"$cfg_path\")` before plotting." + "Please include the file manually with `include(\"$cfg_path\")` before plotting." end end @@ -331,9 +331,9 @@ include("basic_recipes/text.jl") include("basic_recipes/raincloud.jl") include("deprecated.jl") -export Arrows , Heatmap , Image , Lines , LineSegments , Mesh , MeshScatter , Poly , Scatter , Surface , Text , Volume , Wireframe -export arrows , heatmap , image , lines , linesegments , mesh , meshscatter , poly , scatter , surface , text , volume , wireframe -export arrows! , heatmap! , image! , lines! , linesegments! , mesh! , meshscatter! , poly! , scatter! , surface! , text! , volume! , wireframe! +export Arrows, Heatmap, Image, Lines, LineSegments, Mesh, MeshScatter, Poly, Scatter, Surface, Text, Volume, Wireframe +export arrows, heatmap, image, lines, linesegments, mesh, meshscatter, poly, scatter, surface, text, volume, wireframe +export arrows!, heatmap!, image!, lines!, linesegments!, mesh!, meshscatter!, poly!, scatter!, surface!, text!, volume!, wireframe! export PointLight, EnvironmentLight, AmbientLight, SSAO diff --git a/src/basic_recipes/ablines.jl b/src/basic_recipes/ablines.jl index 5a3f794b54f..c2f7d5cb26b 100644 --- a/src/basic_recipes/ablines.jl +++ b/src/basic_recipes/ablines.jl @@ -11,7 +11,7 @@ All style attributes are the same as for `LineSegments`. xautolimits = false, yautolimits = false, default_theme(LineSegments, scene)..., - cycle = :color, + cycle = :color ) end @@ -19,14 +19,14 @@ function Makie.plot!(p::ABLines) scene = Makie.parent_scene(p) transf = transform_func(scene) - + is_identity_transform(transf) || throw(ArgumentError("ABLines is only defined for the identity transform, not $(typeof(transf)).")) limits = lift(projview_to_2d_limits, scene.camera.projectionview) points = Observable(Point2f[]) - + onany(limits, p[1], p[2]) do lims, intercept, slope inv = inverse_transform(transf) empty!(points[]) @@ -47,6 +47,6 @@ function Makie.plot!(p::ABLines) end function abline!(args...; kwargs...) - Base.depwarn("abline! is deprecated and will be removed in the future. Use ablines / ablines! instead." , :abline!, force = true) + Base.depwarn("abline! is deprecated and will be removed in the future. Use ablines / ablines! instead.", :abline!, force = true) ablines!(args...; kwargs...) end diff --git a/src/basic_recipes/annotations.jl b/src/basic_recipes/annotations.jl index 941614d2301..1179decdd38 100644 --- a/src/basic_recipes/annotations.jl +++ b/src/basic_recipes/annotations.jl @@ -10,11 +10,11 @@ $(ATTRIBUTES) default_theme(scene, Text) end -function convert_arguments(::Type{<: Annotations}, - strings::AbstractVector{<: AbstractString}, - text_positions::AbstractVector{<: Point{N}}) where N +function convert_arguments(::Type{<:Annotations}, + strings::AbstractVector{<:AbstractString}, + text_positions::AbstractVector{<:Point{N}}) where N return (map(strings, text_positions) do str, pos - (String(str), Point{N, Float32}(pos)) + (String(str), Point{N,Float32}(pos)) end,) end diff --git a/src/basic_recipes/arc.jl b/src/basic_recipes/arc.jl index 8701e7a51bf..38394d68f64 100644 --- a/src/basic_recipes/arc.jl +++ b/src/basic_recipes/arc.jl @@ -17,14 +17,14 @@ $(ATTRIBUTES) @recipe(Arc, origin, radius, start_angle, stop_angle) do scene Attributes(; default_theme(scene, Lines)..., - resolution = 361, + resolution = 361 ) end function plot!(p::Arc) args = getindex.(p, (:origin, :radius, :start_angle, :stop_angle, :resolution)) positions = lift(args...) do origin, radius, start_angle, stop_angle, resolution - map(range(start_angle, stop=stop_angle, length=resolution)) do angle + map(range(start_angle, stop = stop_angle, length = resolution)) do angle origin .+ Point2f((cos(angle), sin(angle)) .* radius) end end diff --git a/src/basic_recipes/arrows.jl b/src/basic_recipes/arrows.jl index 9a7e8ac0952..ff2e063f955 100644 --- a/src/basic_recipes/arrows.jl +++ b/src/basic_recipes/arrows.jl @@ -39,8 +39,8 @@ function arrow_head(N, marker::Automatic, quality) return :utriangle else merge([ - _circle(Point3f(0), 0.5f0, Vec3f(0,0,-1), quality), - _mantle(Point3f(0), Point3f(0,0,1), 0.5f0, 0f0, quality) + _circle(Point3f(0), 0.5f0, Vec3f(0, 0, -1), quality), + _mantle(Point3f(0), Point3f(0, 0, 1), 0.5f0, 0f0, quality) ]) end end @@ -51,8 +51,8 @@ function arrow_tail(N, marker::Automatic, quality) nothing else merge([ - _circle(Point3f(0,0,-1), 0.5f0, Vec3f(0,0,-1), quality), - _mantle(Point3f(0,0,-1), Point3f(0), 0.5f0, 0.5f0, quality) + _circle(Point3f(0, 0, -1), 0.5f0, Vec3f(0, 0, -1), quality), + _mantle(Point3f(0, 0, -1), Point3f(0), 0.5f0, 0.5f0, quality) ]) end end @@ -64,7 +64,7 @@ function _mantle(origin, extremity, r1, r2, N) # Equivalent to # xy = cos(atan(temp)) # z = sin(atan(temp)) - temp = -(r2-r1) / norm(extremity .- origin) + temp = -(r2 - r1) / norm(extremity .- origin) xy = 1.0 / sqrt(temp^2 + 1) z = temp / sqrt(temp^2 + 1) @@ -72,43 +72,43 @@ function _mantle(origin, extremity, r1, r2, N) normals = Vector{Vec3f}(undef, 2N) faces = Vector{GLTriangleFace}(undef, 2N) - for (i, phi) in enumerate(0:dphi:2pi-0.5dphi) + for (i, phi) in enumerate(0:dphi:(2pi - 0.5dphi)) coords[2i - 1] = origin .+ r1 * Vec3f(cos(phi), sin(phi), 0) coords[2i] = extremity .+ r2 * Vec3f(cos(phi), sin(phi), 0) - normals[2i - 1] = Vec3f(xy*cos(phi), xy*sin(phi), z) - normals[2i] = Vec3f(xy*cos(phi), xy*sin(phi), z) - faces[2i - 1] = GLTriangleFace(2i-1, mod1(2i+1, 2N), 2i) - faces[2i] = GLTriangleFace(mod1(2i+1, 2N), mod1(2i+2, 2N), 2i) + normals[2i - 1] = Vec3f(xy * cos(phi), xy * sin(phi), z) + normals[2i] = Vec3f(xy * cos(phi), xy * sin(phi), z) + faces[2i - 1] = GLTriangleFace(2i - 1, mod1(2i + 1, 2N), 2i) + faces[2i] = GLTriangleFace(mod1(2i + 1, 2N), mod1(2i + 2, 2N), 2i) end - GeometryBasics.Mesh(meta(coords; normals=normals), faces) + GeometryBasics.Mesh(meta(coords; normals = normals), faces) end # GeometryBasics.Circle doesn't work with Point3f... function _circle(origin, r, normal, N) dphi = 2pi / N - coords = Vector{Point3f}(undef, N+1) - normals = fill(normal, N+1) + coords = Vector{Point3f}(undef, N + 1) + normals = fill(normal, N + 1) faces = Vector{GLTriangleFace}(undef, N) - for (i, phi) in enumerate(0:dphi:2pi-0.5dphi) + for (i, phi) in enumerate(0:dphi:(2pi - 0.5dphi)) coords[i] = origin .+ r * Vec3f(cos(phi), sin(phi), 0) - faces[i] = GLTriangleFace(N+1, mod1(i+1, N), i) + faces[i] = GLTriangleFace(N + 1, mod1(i + 1, N), i) end - coords[N+1] = origin + coords[N + 1] = origin - GeometryBasics.Mesh(meta(coords; normals=normals), faces) + GeometryBasics.Mesh(meta(coords; normals = normals), faces) end -convert_arguments(::Type{<: Arrows}, x, y, u, v) = (Point2f.(x, y), Vec2f.(u, v)) -function convert_arguments(::Type{<: Arrows}, x::AbstractVector, y::AbstractVector, u::AbstractMatrix, v::AbstractMatrix) +convert_arguments(::Type{<:Arrows}, x, y, u, v) = (Point2f.(x, y), Vec2f.(u, v)) +function convert_arguments(::Type{<:Arrows}, x::AbstractVector, y::AbstractVector, u::AbstractMatrix, v::AbstractMatrix) (vec(Point2f.(x, y')), vec(Vec2f.(u, v))) end -convert_arguments(::Type{<: Arrows}, x, y, z, u, v, w) = (Point3f.(x, y, z), Vec3f.(u, v, w)) +convert_arguments(::Type{<:Arrows}, x, y, z, u, v, w) = (Point3f.(x, y, z), Vec3f.(u, v, w)) -function plot!(arrowplot::Arrows{<: Tuple{AbstractVector{<: Point{N, T}}, V}}) where {N, T, V} +function plot!(arrowplot::Arrows{<:Tuple{AbstractVector{<:Point{N,T}},V}}) where {N,T,V} @extract arrowplot ( points, directions, colormap, normalize, align, arrowtail, color, linecolor, linestyle, linewidth, lengthscale, @@ -118,8 +118,8 @@ function plot!(arrowplot::Arrows{<: Tuple{AbstractVector{<: Point{N, T}}, V}}) w fxaa, ssao, transparency, visible, inspectable ) - arrow_c = map((a, c)-> a === automatic ? c : a , arrowcolor, color) - line_c = map((a, c)-> a === automatic ? c : a , linecolor, color) + arrow_c = map((a, c) -> a === automatic ? c : a, arrowcolor, color) + line_c = map((a, c) -> a === automatic ? c : a, linecolor, color) if N == 2 fxaa_bool = @lift($fxaa == automatic ? false : $fxaa) @@ -167,7 +167,7 @@ function plot!(arrowplot::Arrows{<: Tuple{AbstractVector{<: Point{N, T}}, V}}) w ) scatter!( arrowplot, - lift(x-> last.(x), headstart), + lift(x -> last.(x), headstart), marker = @lift(arrow_head(2, $arrowhead, $quality)), markersize = @lift($arrowsize === automatic ? theme(scene, :markersize)[] : $arrowsize), color = arrow_c, rotations = rotations, strokewidth = 0.0, @@ -178,8 +178,8 @@ function plot!(arrowplot::Arrows{<: Tuple{AbstractVector{<: Point{N, T}}, V}}) w else fxaa_bool = @lift($fxaa == automatic ? true : $fxaa) - msize = Observable{Union{Vec3f, Vector{Vec3f}}}() - markersize = Observable{Union{Vec3f, Vector{Vec3f}}}() + msize = Observable{Union{Vec3f,Vector{Vec3f}}}() + markersize = Observable{Union{Vec3f,Vector{Vec3f}}}() map!(msize, directions, normalize, linewidth, lengthscale, arrowsize) do dirs, n, linewidth, ls, as ms = as isa Automatic ? Vec3f(0.2, 0.2, 0.3) : as markersize[] = to_3d_scale(ms) diff --git a/src/basic_recipes/axis.jl b/src/basic_recipes/axis.jl index f9744a8efb5..b902194447b 100644 --- a/src/basic_recipes/axis.jl +++ b/src/basic_recipes/axis.jl @@ -1,21 +1,21 @@ module Formatters - using Showoff +using Showoff - function scientific(ticks::AbstractVector) - Showoff.showoff(ticks, :scientific) - end +function scientific(ticks::AbstractVector) + Showoff.showoff(ticks, :scientific) +end - function plain(ticks::AbstractVector) - try - Showoff.showoff(ticks, :plain) - catch e - bt = Base.catch_backtrace() - Base.showerror(stderr, e) - Base.show_backtrace(stdout, bt) - println("with ticks: ", ticks) - String["-Inf", "Inf"] - end +function plain(ticks::AbstractVector) + try + Showoff.showoff(ticks, :plain) + catch e + bt = Base.catch_backtrace() + Base.showerror(stderr, e) + Base.show_backtrace(stdout, bt) + println("with ticks: ", ticks) + String["-Inf", "Inf"] end +end end using .Formatters @@ -37,10 +37,10 @@ $(ATTRIBUTES) """ @recipe(Axis3D) do scene - q1 = qrotation(Vec3f(1, 0, 0), -0.5f0*pi) - q2 = qrotation(Vec3f(0, 0, 1), 1f0*pi) + q1 = qrotation(Vec3f(1, 0, 0), -0.5f0 * pi) + q2 = qrotation(Vec3f(0, 0, 1), 1f0 * pi) tickrotations3d = ( - qrotation(Vec3f(0,0,1), -1.5pi), + qrotation(Vec3f(0, 0, 1), -1.5pi), q2, qrotation(Vec3f(1, 0, 0), -0.5pi) * q2 ) @@ -55,8 +55,8 @@ $(ATTRIBUTES) grid_color = RGBAf(0.5, 0.5, 0.5, 0.4) grid_thickness = 1 axis_linewidth = 1.5 - gridthickness = ntuple(x-> 1f0, Val(3)) - axislinewidth = ntuple(x->1.5f0, Val(3)) + gridthickness = ntuple(x -> 1f0, Val(3)) + axislinewidth = ntuple(x -> 1.5f0, Val(3)) tsize = 5 # in percent Attributes( visible = true, @@ -75,22 +75,14 @@ $(ATTRIBUTES) align = axisnames_align3d, font = lift(to_3tuple, theme(scene, :font)), gap = 3 - ), - - ticks = Attributes( + ), ticks = Attributes( ranges_labels = (automatic, automatic), - formatter = Formatters.plain, - - textcolor = (tick_color, tick_color, tick_color), - - rotation = tickrotations3d, + formatter = Formatters.plain, textcolor = (tick_color, tick_color, tick_color), rotation = tickrotations3d, fontsize = (tsize, tsize, tsize), align = tickalign3d, gap = 3, font = lift(to_3tuple, theme(scene, :font)), - ), - - frame = Attributes( + ), frame = Attributes( linecolor = (grid_color, grid_color, grid_color), linewidth = (grid_thickness, grid_thickness, grid_thickness), axislinewidth = (axis_linewidth, axis_linewidth, axis_linewidth), @@ -102,38 +94,38 @@ end isaxis(x) = false isaxis(x::Axis3D) = true -const Limits{N} = NTuple{N, <:Tuple{<: Number, <: Number}} +const Limits{N} = NTuple{N,<:Tuple{<:Number,<:Number}} function default_ticks(limits::Limits, ticks, scale_func::Function) default_ticks.(limits, (ticks,), scale_func) end -default_ticks(limits::Tuple{Number, Number}, ticks, scale_func::Function) = default_ticks(limits..., ticks, scale_func) +default_ticks(limits::Tuple{Number,Number}, ticks, scale_func::Function) = default_ticks(limits..., ticks, scale_func) function default_ticks( - lmin::Number, lmax::Number, - ticks::AbstractVector{<: Number}, scale_func::Function - ) + lmin::Number, lmax::Number, + ticks::AbstractVector{<:Number}, scale_func::Function +) scale_func.((filter(t -> lmin <= t <= lmax, ticks))) end function default_ticks( - lmin::Number, lmax::Number, ::Automatic, scale_func::Function - ) + lmin::Number, lmax::Number, ::Automatic, scale_func::Function +) # scale the limits scaled_ticks, mini, maxi = optimize_ticks( Float64(scale_func(lmin)), Float64(scale_func(lmax)); k_min = 4, # minimum number of ticks - k_max = 8, # maximum number of ticks + k_max = 8 # maximum number of ticks ) length(scaled_ticks) == 1 && isnan(scaled_ticks[1]) && return [-Inf, Inf] scaled_ticks end function default_ticks( - lmin::Number, lmax::Number, ticks::Integer, scale_func = identity - ) + lmin::Number, lmax::Number, ticks::Integer, scale_func = identity +) scaled_ticks, mini, maxi = optimize_ticks( Float64(scale_func(lmin)), Float64(scale_func(lmax)); @@ -142,7 +134,7 @@ function default_ticks( k_ideal = ticks, # `strict_span = false` rewards cases where the span of the # chosen ticks is not too much bigger than amin - amax: - strict_span = false, + strict_span = false ) scaled_ticks end @@ -159,10 +151,10 @@ default_ticks(ticks::Tuple, limits::Limits, n) = default_ticks.(ticks, limits, ( default_ticks(ticks::Tuple, limits::Limits, n::Tuple) = default_ticks.(ticks, limits, n) -default_ticks(ticks::AbstractVector{<: Number}, limits, n) = ticks +default_ticks(ticks::AbstractVector{<:Number}, limits, n) = ticks -function default_labels(x::NTuple{N, Any}, formatter::Function) where N +function default_labels(x::NTuple{N,Any}, formatter::Function) where N default_labels.(x, formatter) end @@ -183,10 +175,10 @@ end default_labels(x::Automatic, ranges, formatter) = default_labels(ranges, formatter) default_labels(x::Tuple, ranges::Tuple, formatter) = default_labels.(x, ranges, (formatter,)) default_labels(x::Tuple, ranges, formatter) = default_labels.(x, (ranges,), (formatter,)) -default_labels(x::AbstractVector{<: AbstractString}, ranges, formatter::Function) = x -default_labels(x::AbstractVector{<: AbstractString}, ranges::AbstractVector, formatter::Function) = x +default_labels(x::AbstractVector{<:AbstractString}, ranges, formatter::Function) = x +default_labels(x::AbstractVector{<:AbstractString}, ranges::AbstractVector, formatter::Function) = x -function convert_arguments(::Type{<: Axis3D}, limits::Rect) +function convert_arguments(::Type{<:Axis3D}, limits::Rect) e = (minimum(limits), maximum(limits)) return (((e[1][1], e[2][1]), (e[1][2], e[2][2]), (e[1][3], e[2][3])),) end @@ -194,7 +186,7 @@ end a_length(x::AbstractVector) = length(x) a_length(x::Automatic) = x -function calculated_attributes!(::Type{<: Axis3D}, plot) +function calculated_attributes!(::Type{<:Axis3D}, plot) ticks = plot.ticks args = (plot[1], ticks.ranges, ticks.labels, ticks.formatter) ticks[:ranges_labels] = lift(args...) do lims, ranges, labels, formatter @@ -209,18 +201,18 @@ end function labelposition(ranges, dim, dir, tgap, origin::StaticVector{N}) where N a, b = extrema(ranges[dim]) whalf = Float32(((b - a) / 2)) - halfaxis = unit(Point{N, Float32}, dim) .* whalf + halfaxis = unit(Point{N,Float32}, dim) .* whalf origin .+ (halfaxis .+ (normalize(dir) * tgap)) end -_widths(x::Tuple{<: Number, <: Number}) = x[2] - x[1] +_widths(x::Tuple{<:Number,<:Number}) = x[2] - x[1] _widths(x) = Float32(maximum(x) - minimum(x)) to3tuple(x::Tuple{Any}) = (x[1], x[1], x[1]) -to3tuple(x::Tuple{Any, Any}) = (x[1], x[2], x[2]) -to3tuple(x::Tuple{Any, Any, Any}) = x -to3tuple(x) = ntuple(i-> x, Val(3)) +to3tuple(x::Tuple{Any,Any}) = (x[1], x[2], x[2]) +to3tuple(x::Tuple{Any,Any,Any}) = x +to3tuple(x) = ntuple(i -> x, Val(3)) function draw_axis3d(textbuffer, linebuffer, scale, limits, ranges_labels, fonts, args...) # make sure we extend all args to 3D @@ -239,26 +231,26 @@ function draw_axis3d(textbuffer, linebuffer, scale, limits, ranges_labels, fonts start!(textbuffer) start!(linebuffer) - limit_widths = map(x-> x[2] - x[1], limits) + limit_widths = map(x -> x[2] - x[1], limits) # pad the drawn limits and use them as the ranges - limits = map((lim, p)-> (lim[1] - p, lim[2] + p), limits, limit_widths .* padding) + limits = map((lim, p) -> (lim[1] - p, lim[2] + p), limits, limit_widths .* padding) mini, maxi = first.(limits), last.(limits) - origin = Point{N, Float32}(min.(mini, first.(ranges))) + origin = Point{N,Float32}(min.(mini, first.(ranges))) limit_widths = max.(last.(ranges), maxi) .- origin % = minimum(limit_widths) / 100 # percentage tfontsize = (%) .* tfontsize axisnames_size = (%) .* axisnames_size # index of the direction in which ticks and labels are drawn - offset_indices = Vec(ntuple(i-> ifelse(i != 2, mod1(i + 1, N), 1), N)) + offset_indices = Vec(ntuple(i -> ifelse(i != 2, mod1(i + 1, N), 1), N)) # These need the real limits, not (%), to be scale-aware titlegap = 0.01limit_widths[offset_indices] .* titlegap tgap = 0.01limit_widths[offset_indices] .* tgap for i in 1:N - axis_vec = unit(Point{N, Float32}, i) + axis_vec = unit(Point{N,Float32}, i) width = Float32(limit_widths[i]) stop = origin .+ (width .* axis_vec) if showaxis[i] @@ -267,7 +259,7 @@ function draw_axis3d(textbuffer, linebuffer, scale, limits, ranges_labels, fonts if showticks[i] range = ranges[i] j = offset_indices[i] - tickdir = unit(Vec{N, Float32}, j) + tickdir = unit(Vec{N,Float32}, j) offset2 = Float32(limit_widths[j] + tgap[i]) * tickdir for (j, tick) in enumerate(range) labels = ticklabels[i] @@ -299,9 +291,9 @@ function draw_axis3d(textbuffer, linebuffer, scale, limits, ranges_labels, fonts if showgrid[i] c = gridcolors[i] thickness = gridthickness[i] - for _j = (i + 1):(i + N - 1) + for _j in (i + 1):(i + N - 1) j = mod1(_j, N) - dir = unit(Point{N, Float32}, j) + dir = unit(Point{N,Float32}, j) range = ranges[j] for tick in range offset = Float32(tick - origin[j]) * dir @@ -312,12 +304,13 @@ function draw_axis3d(textbuffer, linebuffer, scale, limits, ranges_labels, fonts end end end - finish!(textbuffer); finish!(linebuffer) + finish!(textbuffer) + finish!(linebuffer) end return end -function plot!(scene::SceneLike, ::Type{<: Axis3D}, attributes::Attributes, args...) +function plot!(scene::SceneLike, ::Type{<:Axis3D}, attributes::Attributes, args...) axis = Axis3D(scene, attributes, args) # Disable any non linear transform for the axis plot! axis.transformation.transform_func[] = identity diff --git a/src/basic_recipes/band.jl b/src/basic_recipes/band.jl index a14219218f4..7d550c455c1 100644 --- a/src/basic_recipes/band.jl +++ b/src/basic_recipes/band.jl @@ -11,17 +11,17 @@ $(ATTRIBUTES) @recipe(Band, lowerpoints, upperpoints) do scene attr = Attributes(; default_theme(scene, Mesh)..., - colorrange = automatic, + colorrange = automatic ) attr[:shading][] = false attr end -convert_arguments(::Type{<: Band}, x, ylower, yupper) = (Point2f.(x, ylower), Point2f.(x, yupper)) +convert_arguments(::Type{<:Band}, x, ylower, yupper) = (Point2f.(x, ylower), Point2f.(x, yupper)) function band_connect(n) - ns = 1:n-1 - ns2 = n+1:2n-1 + ns = 1:(n - 1) + ns2 = (n + 1):(2n - 1) [GLTriangleFace.(ns, ns .+ 1, ns2); GLTriangleFace.(ns .+ 1, ns2 .+ 1, ns2)] end @@ -40,7 +40,7 @@ function Makie.plot!(plot::Band) # side to make an even band if length(c) == length(lowerpoints[]) return repeat(to_color(c), 2)::RGBColors - # if there's one color for each band vertex, the colors are used directly + # if there's one color for each band vertex, the colors are used directly elseif length(c) == 2 * length(lowerpoints[]) return to_color(c)::RGBColors else @@ -62,7 +62,7 @@ end function fill_view(x, y1, y2, where::Function) fill_view(x, y1, y2, where.(x, y1, y2)) end -function fill_view(x, y1, y2, bools::AbstractVector{<: Union{Integer, Bool}}) +function fill_view(x, y1, y2, bools::AbstractVector{<:Union{Integer,Bool}}) view(x, bools), view(y1, bools), view(y2, bools) end diff --git a/src/basic_recipes/barplot.jl b/src/basic_recipes/barplot.jl index 44517db2eae..b2bd1735d59 100644 --- a/src/basic_recipes/barplot.jl +++ b/src/basic_recipes/barplot.jl @@ -1,5 +1,5 @@ function bar_label_formatter(value::Number) - return string(round(value; digits=3)) + return string(round(value; digits = 3)) end """ @@ -34,9 +34,7 @@ $(ATTRIBUTES) direction = :y, visible = theme(scene, :visible), inspectable = theme(scene, :inspectable), - cycle = [:color => :patchcolor], - - bar_labels = nothing, + cycle = [:color => :patchcolor], bar_labels = nothing, flip_labels_at = Inf, label_rotation = 0π, label_color = theme(scene, :textcolor), @@ -50,7 +48,7 @@ $(ATTRIBUTES) ) end -conversion_trait(::Type{<: BarPlot}) = PointBased() +conversion_trait(::Type{<:BarPlot}) = PointBased() function bar_rectangle(x, y, width, fillto, in_y_direction) # y could be smaller than fillto... @@ -87,7 +85,7 @@ end function stack_from_to_sorted(y) to = cumsum(y) - from = [0.0; to[firstindex(to):end-1]] + from = [0.0; to[firstindex(to):(end - 1)]] (from = from, to = to) end @@ -108,7 +106,7 @@ end function stack_grouped_from_to(i_stack, y, grp) from = Array{Float64}(undef, length(y)) - to = Array{Float64}(undef, length(y)) + to = Array{Float64}(undef, length(y)) groupby = StructArray((; grp..., is_pos = y .> 0)) @@ -136,7 +134,7 @@ function text_attributes(values, in_y_direction, flip_labels_at, color_over_back function flip(k) if flip_labels_at isa Number return k > flip_labels_at || k < 0 - elseif flip_labels_at isa Tuple{<:Number, <: Number} + elseif flip_labels_at isa Tuple{<:Number,<:Number} return (k > flip_labels_at[2] || k < 0) && k > flip_labels_at[1] else error("flip_labels_at needs to be a tuple of two numbers (low, high), or a single number (high)") @@ -186,15 +184,15 @@ end function Makie.plot!(p::BarPlot) - labels = Observable(Tuple{String, Point2f}[]) + labels = Observable(Tuple{String,Point2f}[]) label_aligns = Observable(Vec2f[]) label_offsets = Observable(Vec2f[]) label_colors = Observable(RGBAf[]) function calculate_bars(xy, fillto, offset, width, dodge, n_dodge, gap, dodge_gap, stack, - dir, bar_labels, flip_labels_at, label_color, color_over_background, - color_over_bar, label_formatter, label_offset) + dir, bar_labels, flip_labels_at, label_color, color_over_background, + color_over_bar, label_formatter, label_offset) - in_y_direction = get((y=true, x=false), dir) do + in_y_direction = get((y = true, x = false), dir) do error("Invalid direction $dir. Options are :x and :y.") end @@ -241,8 +239,8 @@ function Makie.plot!(p::BarPlot) oback = color_over_background === automatic ? label_color : color_over_background obar = color_over_bar === automatic ? label_color : color_over_bar label_args = barplot_labels(x̂, y, bar_labels, in_y_direction, - flip_labels_at, to_color(oback), to_color(obar), - label_formatter, label_offset) + flip_labels_at, to_color(oback), to_color(obar), + label_formatter, label_offset) labels[], label_aligns[], label_offsets[], label_colors[] = label_args end @@ -250,8 +248,8 @@ function Makie.plot!(p::BarPlot) end bars = lift(calculate_bars, p[1], p.fillto, p.offset, p.width, p.dodge, p.n_dodge, p.gap, - p.dodge_gap, p.stack, p.direction, p.bar_labels, p.flip_labels_at, - p.label_color, p.color_over_background, p.color_over_bar, p.label_formatter, p.label_offset) + p.dodge_gap, p.stack, p.direction, p.bar_labels, p.flip_labels_at, + p.label_color, p.color_over_background, p.color_over_bar, p.label_formatter, p.label_offset) poly!( p, bars, color = p.color, colormap = p.colormap, colorrange = p.colorrange, @@ -260,6 +258,6 @@ function Makie.plot!(p::BarPlot) highclip = p.highclip, lowclip = p.lowclip, nan_color = p.nan_color, ) if !isnothing(p.bar_labels[]) - text!(p, labels; align=label_aligns, offset=label_offsets, color=label_colors, font=p.label_font, fontsize=p.label_size, rotation=p.label_rotation) + text!(p, labels; align = label_aligns, offset = label_offsets, color = label_colors, font = p.label_font, fontsize = p.label_size, rotation = p.label_rotation) end end diff --git a/src/basic_recipes/buffers.jl b/src/basic_recipes/buffers.jl index 823ddbcae32..84e48ac2e83 100644 --- a/src/basic_recipes/buffers.jl +++ b/src/basic_recipes/buffers.jl @@ -4,17 +4,17 @@ efficiently append + push new values to them =# function LinesegmentBuffer( - scene::SceneLike, ::Type{Point{N}} = Point{2}; - color = RGBAf[], linewidth = Float32[], - kw_args... - ) where N + scene::SceneLike, ::Type{Point{N}} = Point{2}; + color = RGBAf[], linewidth = Float32[], + kw_args... +) where N linesegments!( - scene, Point{N, Float32}[]; color = color, + scene, Point{N,Float32}[]; color = color, linewidth = linewidth, kw_args... ) end -function append!(lsb::LineSegments, positions::Vector{Point{N, Float32}}; color = :black, linewidth = 1.0) where N +function append!(lsb::LineSegments, positions::Vector{Point{N,Float32}}; color = :black, linewidth = 1.0) where N thickv = same_length_array(positions, linewidth, key"linewidth"()) colorv = same_length_array(positions, color, key"color"()) append!(lsb[1][], positions) @@ -23,7 +23,7 @@ function append!(lsb::LineSegments, positions::Vector{Point{N, Float32}}; color return end -function push!(tb::LineSegments, positions::Point{N, Float32}; kw_args...) where N +function push!(tb::LineSegments, positions::Point{N,Float32}; kw_args...) where N append!(tb, [positions]; kw_args...) end @@ -43,16 +43,16 @@ function finish!(lsb::LineSegments) end function TextBuffer( - scene::SceneLike, ::Type{Point{N}} = Point{2}; - rotation = [Quaternionf(0,0,0,1)], - color = RGBAf[RGBAf(0,0,0,0)], - fontsize = Float32[0], - font = [defaultfont()], - align = [Vec2f(0)], - kw_args... - ) where N + scene::SceneLike, ::Type{Point{N}} = Point{2}; + rotation = [Quaternionf(0, 0, 0, 1)], + color = RGBAf[RGBAf(0, 0, 0, 0)], + fontsize = Float32[0], + font = [defaultfont()], + align = [Vec2f(0)], + kw_args... +) where N annotations!( - scene, String[" "], [Point{N, Float32}(0)]; + scene, String[" "], [Point{N,Float32}(0)]; rotation = rotation, color = color, fontsize = fontsize, @@ -83,16 +83,16 @@ end function push!(tb::Annotations, text::String, position::VecTypes{N}; kw_args...) where N - append!(tb, [(String(text), Point{N, Float32}(position))]; kw_args...) + append!(tb, [(String(text), Point{N,Float32}(position))]; kw_args...) end -function append!(tb::Annotations, text::Vector{String}, positions::Vector{Point{N, Float32}}; kw_args...) where N +function append!(tb::Annotations, text::Vector{String}, positions::Vector{Point{N,Float32}}; kw_args...) where N text_positions = convert_argument(Annotations, text, positions)[1] append!(tb, text_positions; kw_args...) return end -function append!(tb::Annotations, text_positions::Vector{Tuple{String, Point{N, Float32}}}; kw_args...) where N +function append!(tb::Annotations, text_positions::Vector{Tuple{String,Point{N,Float32}}}; kw_args...) where N append!(tb[1][], text_positions) kw = Dict(kw_args) for key in (:color, :rotation, :fontsize, :font, :align) diff --git a/src/basic_recipes/contourf.jl b/src/basic_recipes/contourf.jl index 2d8699d64a8..b62c837b46c 100644 --- a/src/basic_recipes/contourf.jl +++ b/src/basic_recipes/contourf.jl @@ -48,7 +48,7 @@ end # _computed_extendhigh function _get_isoband_levels(levels::Int, mi, ma) - edges = Float32.(LinRange(mi, ma, levels+1)) + edges = Float32.(LinRange(mi, ma, levels + 1)) end function _get_isoband_levels(levels::AbstractVector{<:Real}, mi, ma) @@ -69,7 +69,7 @@ function _get_isoband_levels(::Val{:relative}, levels::AbstractVector, values) end -function Makie.plot!(c::Contourf{<:Tuple{<:AbstractVector{<:Real}, <:AbstractVector{<:Real}, <:AbstractMatrix{<:Real}}}) +function Makie.plot!(c::Contourf{<:Tuple{<:AbstractVector{<:Real},<:AbstractVector{<:Real},<:AbstractMatrix{<:Real}}}) xs, ys, zs = c[1:3] c.attributes[:_computed_levels] = lift(zs, c.levels, c.mode) do zs, levels, mode @@ -80,7 +80,7 @@ function Makie.plot!(c::Contourf{<:Tuple{<:AbstractVector{<:Real}, <:AbstractVec minimum(levels), maximum(levels) end computed_colormap = lift(compute_contourf_colormap, c._computed_levels, c.colormap, c.extendlow, - c.extendhigh) + c.extendhigh) c.attributes[:_computed_colormap] = computed_colormap lowcolor = Observable{RGBAf}() @@ -106,7 +106,7 @@ function Makie.plot!(c::Contourf{<:Tuple{<:AbstractVector{<:Real}, <:AbstractVec @assert issorted(levels) is_extended_low && pushfirst!(levels, -Inf) is_extended_high && push!(levels, Inf) - lows = levels[1:end-1] + lows = levels[1:(end - 1)] highs = levels[2:end] # zs needs to be transposed to match rest of makie @@ -183,7 +183,7 @@ function _group_polys(points, ids) groups = Vector{Vector{Point2f}}[] # a dict that maps index in `polys` to index in `groups` for outer polys - outerindex_groupdict = Dict{Int, Int}() + outerindex_groupdict = Dict{Int,Int}() # all polys have to be classified while !isempty(unclassified_polyindices) diff --git a/src/basic_recipes/contours.jl b/src/basic_recipes/contours.jl index 5094b86eaf7..39f62615ebd 100644 --- a/src/basic_recipes/contours.jl +++ b/src/basic_recipes/contours.jl @@ -45,7 +45,7 @@ $(ATTRIBUTES) default_theme(scene, Contour) end -function contourlines(::Type{<: Contour}, contours, cols) +function contourlines(::Type{<:Contour}, contours, cols) result = Point2f[] colors = RGBA{Float32}[] for (color, c) in zip(cols, Contours.levels(contours)) @@ -58,7 +58,7 @@ function contourlines(::Type{<: Contour}, contours, cols) result, colors end -function contourlines(::Type{<: Contour3d}, contours, cols) +function contourlines(::Type{<:Contour3d}, contours, cols) result = Point3f[] colors = RGBA{Float32}[] for (color, c) in zip(cols, Contours.levels(contours)) @@ -73,7 +73,7 @@ function contourlines(::Type{<: Contour3d}, contours, cols) result, colors end -to_levels(x::AbstractVector{<: Number}, cnorm) = x +to_levels(x::AbstractVector{<:Number}, cnorm) = x function to_levels(n::Integer, cnorm) zmin, zmax = cnorm @@ -81,12 +81,12 @@ function to_levels(n::Integer, cnorm) range(zmin + dz; step = dz, length = n) end -conversion_trait(::Type{<: Contour3d}) = ContinuousSurface() -conversion_trait(::Type{<: Contour}) = ContinuousSurface() -conversion_trait(::Type{<: Contour{<: Tuple{X, Y, Z, Vol}}}) where {X, Y, Z, Vol} = VolumeLike() -conversion_trait(::Type{<: Contour{<: Tuple{<: AbstractArray{T, 3}}}}) where T = VolumeLike() +conversion_trait(::Type{<:Contour3d}) = ContinuousSurface() +conversion_trait(::Type{<:Contour}) = ContinuousSurface() +conversion_trait(::Type{<:Contour{<:Tuple{X,Y,Z,Vol}}}) where {X,Y,Z,Vol} = VolumeLike() +conversion_trait(::Type{<:Contour{<:Tuple{<:AbstractArray{T,3}}}}) where T = VolumeLike() -function plot!(plot::Contour{<: Tuple{X, Y, Z, Vol}}) where {X, Y, Z, Vol} +function plot!(plot::Contour{<:Tuple{X,Y,Z,Vol}}) where {X,Y,Z,Vol} x, y, z, volume = plot[1:4] @extract plot (colormap, levels, linewidth, alpha) valuerange = lift(nan_extrema, volume) @@ -107,7 +107,7 @@ function plot!(plot::Contour{<: Tuple{X, Y, Z, Vol}}) where {X, Y, Z, Vol} v_interval = cliprange[1] .. cliprange[2] # resample colormap and make the empty area between iso surfaces transparent return map(1:N) do i - i01 = (i-1) / (N - 1) + i01 = (i - 1) / (N - 1) c = Makie.interpolated_getindex(cmap, i01) isoval = vrange[1] + (i01 * (vrange[2] - vrange[1])) line = reduce(levels, init = false) do v0, level @@ -138,7 +138,7 @@ function color_per_level(colors::AbstractVector, colormap, colorrange, alpha, le color_per_level(to_colormap(colors), colormap, colorrange, alpha, levels) end -function color_per_level(colors::AbstractVector{<: Colorant}, colormap, colorrange, alpha, levels) +function color_per_level(colors::AbstractVector{<:Colorant}, colormap, colorrange, alpha, levels) if length(levels) == length(colors) return colors else @@ -157,11 +157,11 @@ function color_per_level(::Nothing, colormap, colorrange, a, levels) end end -function plot!(plot::T) where T <: Union{Contour, Contour3d} +function plot!(plot::T) where T<:Union{Contour,Contour3d} x, y, z = plot[1:3] zrange = lift(nan_extrema, z) levels = lift(plot.levels, zrange) do levels, zrange - if levels isa AbstractVector{<: Number} + if levels isa AbstractVector{<:Number} return levels elseif levels isa Integer to_levels(levels, zrange) @@ -170,15 +170,15 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} end end - replace_automatic!(()-> zrange, plot, :colorrange) + replace_automatic!(() -> zrange, plot, :colorrange) args = @extract plot (color, colormap, colorrange, alpha) level_colors = lift(color_per_level, args..., levels) result = lift(x, y, z, levels, level_colors) do x, y, z, levels, level_colors t = eltype(z) # Compute contours - xv, yv = to_vector(x, size(z,1), t), to_vector(y, size(z,2), t) - contours = Contours.contours(xv, yv, z, convert(Vector{eltype(z)}, levels)) + xv, yv = to_vector(x, size(z, 1), t), to_vector(y, size(z, 2), t) + contours = Contours.contours(xv, yv, z, convert(Vector{eltype(z)}, levels)) contourlines(T, contours, level_colors) end lines!( @@ -192,9 +192,9 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} plot end -function point_iterator(x::Contour{<: Tuple{X, Y, Z}}) where {X, Y, Z} +function point_iterator(x::Contour{<:Tuple{X,Y,Z}}) where {X,Y,Z} axes = (x[1], x[2]) - extremata = map(extrema∘to_value, axes) + extremata = map(extrema ∘ to_value, axes) minpoint = Point2f(first.(extremata)...) widths = last.(extremata) .- first.(extremata) rect = Rect2f(minpoint, Vec2f(widths)) diff --git a/src/basic_recipes/convenience_functions.jl b/src/basic_recipes/convenience_functions.jl index b9086b27cbd..365393e6f25 100644 --- a/src/basic_recipes/convenience_functions.jl +++ b/src/basic_recipes/convenience_functions.jl @@ -1,6 +1,6 @@ -function Makie.plot!(plot::Plot(AbstractVector{<: Complex})) +function Makie.plot!(plot::Plot(AbstractVector{<:Complex})) plot[:axis, :labels] = ("Re(x)", "Im(x)") - lines!(plot, lift(im-> Point2f.(real.(im), imag.(im)), x[1])) + lines!(plot, lift(im -> Point2f.(real.(im), imag.(im)), x[1])) end @@ -33,13 +33,13 @@ Plots the given colour gradients arranged as horizontal colourbars. If you change the offsets or the font size, you may need to change the resolution. """ function showgradients( - cgrads::AbstractVector{Symbol}; - h = 0.0, - offset = 0.4, - fontsize = 0.7, - resolution = (800, length(cgrads) * 84), - monospace = true - )::Scene + cgrads::AbstractVector{Symbol}; + h = 0.0, + offset = 0.4, + fontsize = 0.7, + resolution = (800, length(cgrads) * 84), + monospace = true +)::Scene scene = Scene(resolution = resolution) @@ -50,7 +50,7 @@ function showgradients( scene, range(0, stop = 10, length = length(c)), range(0, stop = 1, length = length(c)), - reshape(c, (length(c),1)) + reshape(c, (length(c), 1)) )[end] cmapstr = monospace ? UnicodeFun.to_latex("\\mono{$cmap}") : string(cmap, ":") diff --git a/src/basic_recipes/error_and_rangebars.jl b/src/basic_recipes/error_and_rangebars.jl index 69a35f65e4a..b846c686b38 100644 --- a/src/basic_recipes/error_and_rangebars.jl +++ b/src/basic_recipes/error_and_rangebars.jl @@ -126,7 +126,7 @@ end ### the two plotting functions create linesegpairs in two different ways ### and then hit the same underlying implementation in `_plot_bars!` -function Makie.plot!(plot::Errorbars{T}) where T <: Tuple{AbstractVector{<:VecTypes{4}}} +function Makie.plot!(plot::Errorbars{T}) where T<:Tuple{AbstractVector{<:VecTypes{4}}} x_y_low_high = plot[1] @@ -144,8 +144,8 @@ function Makie.plot!(plot::Errorbars{T}) where T <: Tuple{AbstractVector{<:VecTy map(x_y_low_high) do (x, y, l, h) in_y ? - (Point2f(x, y - l), Point2f(x, y + h)) : - (Point2f(x - l, y), Point2f(x + h, y)) + (Point2f(x, y - l), Point2f(x, y + h)) : + (Point2f(x - l, y), Point2f(x + h, y)) end end @@ -153,7 +153,7 @@ function Makie.plot!(plot::Errorbars{T}) where T <: Tuple{AbstractVector{<:VecTy end -function Makie.plot!(plot::Rangebars{T}) where T <: Tuple{AbstractVector{<:VecTypes{3}}} +function Makie.plot!(plot::Rangebars{T}) where T<:Tuple{AbstractVector{<:VecTypes{3}}} val_low_high = plot[1] @@ -171,8 +171,8 @@ function Makie.plot!(plot::Rangebars{T}) where T <: Tuple{AbstractVector{<:VecTy map(vlh) do (v, l, h) in_y ? - (Point2f(v, l), Point2f(v, h)) : - (Point2f(l, v), Point2f(h, v)) + (Point2f(v, l), Point2f(v, h)) : + (Point2f(l, v), Point2f(h, v)) end end @@ -197,8 +197,8 @@ function _plot_bars!(plot, linesegpairs, is_in_y_direction) screenendpoints = scene_to_screen(endpoints, scene) screenendpoints_shifted_pairs = map(screenendpoints) do sep - (sep .+ f_if(is_in_y_direction[], reverse, Point(0, -whiskerwidth/2)), - sep .+ f_if(is_in_y_direction[], reverse, Point(0, whiskerwidth/2))) + (sep .+ f_if(is_in_y_direction[], reverse, Point(0, -whiskerwidth / 2)), + sep .+ f_if(is_in_y_direction[], reverse, Point(0, whiskerwidth / 2))) end screen_to_scene([p for pair in screenendpoints_shifted_pairs for p in pair], scene) @@ -213,7 +213,7 @@ function _plot_bars!(plot, linesegpairs, is_in_y_direction) return to_color(color)::RGBAf end end - whiskerlinewidths = Observable{Union{Float32, Vector{Float32}}}() + whiskerlinewidths = Observable{Union{Float32,Vector{Float32}}}() map!(whiskerlinewidths, linewidth) do linewidth # same for linewidth if linewidth isa AbstractVector @@ -250,14 +250,14 @@ function screen_to_scene(pts, scene) [Point2.(p[Vec(1, 2)]...) for p in projected] end -function scene_to_screen(p::T, scene) where T <: Point +function scene_to_screen(p::T, scene) where T<:Point p4 = to_ndim(Vec4f, to_ndim(Vec3f, p, 0.0), 1.0) p1m1 = scene.camera.projectionview[] * p4 projected = inv(scene.camera.pixel_space[]) * p1m1 T(projected[Vec(1, 2)]...) end -function screen_to_scene(p::T, scene) where T <: Point +function screen_to_scene(p::T, scene) where T<:Point p4 = to_ndim(Vec4f, to_ndim(Vec3f, p, 0.0), 1.0) p1m1 = scene.camera.pixel_space[] * p4 projected = inv(scene.camera.projectionview[]) * p1m1 @@ -266,6 +266,6 @@ end # ignore whiskers when determining data limits -function data_limits(bars::Union{Errorbars, Rangebars}) +function data_limits(bars::Union{Errorbars,Rangebars}) data_limits(bars.plots[1]) end diff --git a/src/basic_recipes/hvlines.jl b/src/basic_recipes/hvlines.jl index 7df939bfedb..13bd00b4e6d 100644 --- a/src/basic_recipes/hvlines.jl +++ b/src/basic_recipes/hvlines.jl @@ -14,7 +14,7 @@ All style attributes are the same as for `LineSegments`. xmin = 0, xmax = 1, default_theme(scene, LineSegments)..., - cycle = :color, + cycle = :color ) end @@ -34,7 +34,7 @@ All style attributes are the same as for `LineSegments`. ymin = 0, ymax = 1, default_theme(scene, LineSegments)..., - cycle = :color, + cycle = :color ) end @@ -45,7 +45,7 @@ function projview_to_2d_limits(pv) return Rect2f(origin, Vec2f(xmax, ymax) - origin) end -function Makie.plot!(p::Union{HLines, VLines}) +function Makie.plot!(p::Union{HLines,VLines}) scene = parent_scene(p) transf = transform_func_obs(scene) diff --git a/src/basic_recipes/hvspan.jl b/src/basic_recipes/hvspan.jl index 18ac06bdae4..9bc767025d0 100644 --- a/src/basic_recipes/hvspan.jl +++ b/src/basic_recipes/hvspan.jl @@ -14,9 +14,9 @@ All style attributes are the same as for `Poly`. xmin = 0, xmax = 1, default_theme(Poly, scene)..., - cycle = [:color => :patchcolor], + cycle = [:color => :patchcolor] ) - end +end """ vspan(xs_low, xs_high; ymin = 0.0, ymax = 1.0, attrs...) @@ -34,11 +34,11 @@ All style attributes are the same as for `Poly`. ymin = 0, ymax = 1, default_theme(Poly, scene)..., - cycle = [:color => :patchcolor], + cycle = [:color => :patchcolor] ) end -function Makie.plot!(p::Union{HSpan, VSpan}) +function Makie.plot!(p::Union{HSpan,VSpan}) scene = Makie.parent_scene(p) transf = transform_func_obs(scene) @@ -48,7 +48,7 @@ function Makie.plot!(p::Union{HSpan, VSpan}) mi = p isa HSpan ? p.xmin : p.ymin ma = p isa HSpan ? p.xmax : p.ymax - + onany(limits, p[1], p[2], mi, ma, transf) do lims, lows, highs, mi, ma, transf inv = inverse_transform(transf) empty!(rects[]) diff --git a/src/basic_recipes/pie.jl b/src/basic_recipes/pie.jl index 206bf6ae633..c0764b4fb27 100644 --- a/src/basic_recipes/pie.jl +++ b/src/basic_recipes/pie.jl @@ -39,7 +39,7 @@ function plot!(plot::Pie) end # create vector of a vector of points for each piece - vertex_arrays = map(boundaries[1:end-1], boundaries[2:end]) do sta, en + vertex_arrays = map(boundaries[1:(end - 1)], boundaries[2:end]) do sta, en distance = en - sta # how many vertices are needed for the curve? nvertices = max(2, ceil(Int, rad2deg(distance) * vertex_per_deg)) @@ -66,9 +66,9 @@ function plot!(plot::Pie) # plot pieces as polys poly!( - plot, polys, - color = plot.color, strokewidth = plot.strokewidth, - strokecolor = plot.strokecolor, inspectable = plot.inspectable, + plot, polys, + color = plot.color, strokewidth = plot.strokewidth, + strokecolor = plot.strokecolor, inspectable = plot.inspectable, visible = plot.visible, transparency = plot.transparency ) diff --git a/src/basic_recipes/poly.jl b/src/basic_recipes/poly.jl index e8d4a7ee57a..db4d20c5e4c 100644 --- a/src/basic_recipes/poly.jl +++ b/src/basic_recipes/poly.jl @@ -1,14 +1,14 @@ -const PolyElements = Union{Polygon, MultiPolygon, Circle, Rect, AbstractMesh, VecTypes, AbstractVector{<:VecTypes}} +const PolyElements = Union{Polygon,MultiPolygon,Circle,Rect,AbstractMesh,VecTypes,AbstractVector{<:VecTypes}} -convert_arguments(::Type{<: Poly}, v::AbstractVector{<: PolyElements}) = (v,) -convert_arguments(::Type{<: Poly}, v::Union{Polygon, MultiPolygon}) = (v,) +convert_arguments(::Type{<:Poly}, v::AbstractVector{<:PolyElements}) = (v,) +convert_arguments(::Type{<:Poly}, v::Union{Polygon,MultiPolygon}) = (v,) -convert_arguments(::Type{<: Poly}, args...) = ([convert_arguments(Scatter, args...)[1]],) -convert_arguments(::Type{<: Poly}, vertices::AbstractArray, indices::AbstractArray) = convert_arguments(Mesh, vertices, indices) -convert_arguments(::Type{<: Poly}, m::GeometryBasics.Mesh) = (m,) -convert_arguments(::Type{<: Poly}, m::GeometryBasics.GeometryPrimitive) = (m,) +convert_arguments(::Type{<:Poly}, args...) = ([convert_arguments(Scatter, args...)[1]],) +convert_arguments(::Type{<:Poly}, vertices::AbstractArray, indices::AbstractArray) = convert_arguments(Mesh, vertices, indices) +convert_arguments(::Type{<:Poly}, m::GeometryBasics.Mesh) = (m,) +convert_arguments(::Type{<:Poly}, m::GeometryBasics.GeometryPrimitive) = (m,) -function plot!(plot::Poly{<: Tuple{Union{GeometryBasics.Mesh, GeometryPrimitive}}}) +function plot!(plot::Poly{<:Tuple{Union{GeometryBasics.Mesh,GeometryPrimitive}}}) mesh!( plot, lift(triangle_mesh, plot[1]), color = plot[:color], @@ -47,11 +47,11 @@ poly_convert(mesh::GeometryBasics.Mesh) = mesh poly_convert(polygon::Polygon) = triangle_mesh(polygon) -function poly_convert(polygon::AbstractVector{<: VecTypes}) +function poly_convert(polygon::AbstractVector{<:VecTypes}) return poly_convert([convert_arguments(Scatter, polygon)[1]]) end -function poly_convert(polygons::AbstractVector{<: AbstractVector{<: VecTypes}}) +function poly_convert(polygons::AbstractVector{<:AbstractVector{<:VecTypes}}) return map(polygons) do poly point2f = convert(Vector{Point2f}, poly) faces = GeometryBasics.earcut_triangulate([point2f]) @@ -77,13 +77,13 @@ function to_line_segments(meshes::AbstractVector) return line end -function to_line_segments(polygon::AbstractVector{<: VecTypes}) +function to_line_segments(polygon::AbstractVector{<:VecTypes}) result = Point2f.(polygon) push!(result, polygon[1]) return result end -function plot!(plot::Poly{<: Tuple{<: Union{Polygon, AbstractVector{<: PolyElements}}}}) +function plot!(plot::Poly{<:Tuple{<:Union{Polygon,AbstractVector{<:PolyElements}}}}) geometries = plot[1] meshes = lift(poly_convert, geometries) mesh!(plot, meshes; @@ -125,7 +125,7 @@ function plot!(plot::Poly{<: Tuple{<: Union{Polygon, AbstractVector{<: PolyEleme ) end -function plot!(plot::Mesh{<: Tuple{<: AbstractVector{P}}}) where P <: Union{AbstractMesh, Polygon} +function plot!(plot::Mesh{<:Tuple{<:AbstractVector{P}}}) where P<:Union{AbstractMesh,Polygon} meshes = plot[1] color_node = plot.color attributes = Attributes( @@ -139,11 +139,11 @@ function plot!(plot::Mesh{<: Tuple{<: AbstractVector{P}}}) where P <: Union{Abst colorrange = get(plot, :colorrange, automatic) ) - num_meshes = lift(meshes; ignore_equal_values=true) do meshes + num_meshes = lift(meshes; ignore_equal_values = true) do meshes return Int[length(coordinates(m)) for m in meshes] end - mesh_colors = Observable{Union{AbstractPattern, Matrix{RGBAf}, RGBColors}}() + mesh_colors = Observable{Union{AbstractPattern,Matrix{RGBAf},RGBColors}}() map!(mesh_colors, plot.color, num_meshes) do colors, num_meshes # one mesh per color diff --git a/src/basic_recipes/raincloud.jl b/src/basic_recipes/raincloud.jl index 4c5fe446e74..21cfe1abe36 100644 --- a/src/basic_recipes/raincloud.jl +++ b/src/basic_recipes/raincloud.jl @@ -85,24 +85,16 @@ paired with the scatter plot so the default is to not show them) violin_limits = (-Inf, Inf), # Box Plot Settings boxplot_width = 0.1, - whiskerwidth = 0.5, + whiskerwidth = 0.5, strokewidth = 1.0, show_median = true, - boxplot_nudge = 0.075, - - gap = 0.2, - - markersize = 2.0, + boxplot_nudge = 0.075, gap = 0.2, markersize = 2.0, dodge = automatic, n_dodge = automatic, - dodge_gap = 0.01, - - plot_boxplots = true, + dodge_gap = 0.01, plot_boxplots = true, show_boxplot_outliers = false, clouds = violin, - hist_bins = 30, - - color = theme(scene, :patchcolor), + hist_bins = 30, color = theme(scene, :patchcolor), cycle = [:color => :patchcolor], ) end @@ -136,8 +128,8 @@ end #### Functions that make the cloud plot #### function plot!( - ax::Makie.Axis, P::Type{<: RainClouds}, - allattrs::Attributes, category_labels, data_array) + ax::Makie.Axis, P::Type{<:RainClouds}, + allattrs::Attributes, category_labels, data_array) plot = plot!(ax.scene, P, allattrs, category_labels, data_array) @@ -163,8 +155,8 @@ function plot!( end function group_labels(category_labels, data_array) - grouped = Dict{eltype(category_labels), Vector{Int}}() - for (label, data_ix) in zip(category_labels, axes(data_array,1)) + grouped = Dict{eltype(category_labels),Vector{Int}}() + for (label, data_ix) in zip(category_labels, axes(data_array, 1)) push!(get!(grouped, label, eltype(data_array)[]), data_ix) end @@ -186,7 +178,7 @@ function ungroup_labels(category_labels, data_array) return category_labels, data_array end -function convert_arguments(::Type{<: RainClouds}, category_labels, data_array) +function convert_arguments(::Type{<:RainClouds}, category_labels, data_array) cloud_plot_check_args(category_labels, data_array) return (category_labels, data_array) end @@ -213,7 +205,7 @@ function plot!(plot::RainClouds) side = plot.side[] center_boxplot_bool = plot.center_boxplot[] # Cloud plot - cloud_width = plot.cloud_width[] + cloud_width = plot.cloud_width[] cloud_width[] < 0 && ArgumentError("`cloud_width` should be positive.") # Box Plot Settings @@ -253,22 +245,22 @@ function plot!(plot::RainClouds) plot_boxplots || (recenter_to_boxplot_nudge_value = 0.0) # Note: these cloud plots are horizontal full_width = jitter_width + side_scatter_nudge + - (plot_boxplots ? boxplot_width : 0) + - (!isnothing(clouds) ? 1 + abs(recenter_to_boxplot_nudge_value) : 0) + (plot_boxplots ? boxplot_width : 0) + + (!isnothing(clouds) ? 1 + abs(recenter_to_boxplot_nudge_value) : 0) - final_x_positions, width = compute_x_and_width(x_positions .+ recenter_to_boxplot_nudge_value/2, full_width, - plot.gap[], plot.dodge[], - plot.n_dodge[], plot.dodge_gap[]) + final_x_positions, width = compute_x_and_width(x_positions .+ recenter_to_boxplot_nudge_value / 2, full_width, + plot.gap[], plot.dodge[], + plot.n_dodge[], plot.dodge_gap[]) width_ratio = width / full_width jitter = create_jitter_array(length(data_array); - jitter_width = jitter_width*width_ratio) + jitter_width = jitter_width * width_ratio) if !isnothing(clouds) if clouds === violin - violin!(plot, final_x_positions .- recenter_to_boxplot_nudge_value.*width_ratio, data_array; - show_median=show_median, side=side, width=width_ratio*cloud_width, plot.cycle, - datalimits=plot.violin_limits, plot.color, gap=0, orientation=plot.orientation[]) + violin!(plot, final_x_positions .- recenter_to_boxplot_nudge_value .* width_ratio, data_array; + show_median = show_median, side = side, width = width_ratio * cloud_width, plot.cycle, + datalimits = plot.violin_limits, plot.color, gap = 0, orientation = plot.orientation[]) elseif clouds === hist edges = pick_hist_edges(data_array, hist_bins) # dodge belongs below: it ensure that the histogram groups labels by both dodge @@ -281,38 +273,38 @@ function plot!(plot::RainClouds) for (_, ixs) in group_labels(groupings, data_array) isempty(ixs) && continue xoffset = final_x_positions[ixs[1]] - recenter_to_boxplot_nudge_value - hist!(plot, view(data_array, ixs); offset=xoffset, - scale_to=(side == :left ? -1 : 1)*cloud_width*width_ratio, bins=edges, - # yes, we really do want :x when orientation is :vertical - # an :x directed histogram has a vertical orientation - direction=plot.orientation[] == :vertical ? :x : :y, - color=getuniquevalue(plot.color[], ixs)) + hist!(plot, view(data_array, ixs); offset = xoffset, + scale_to = (side == :left ? -1 : 1) * cloud_width * width_ratio, bins = edges, + # yes, we really do want :x when orientation is :vertical + # an :x directed histogram has a vertical orientation + direction = plot.orientation[] == :vertical ? :x : :y, + color = getuniquevalue(plot.color[], ixs)) end else error("cloud attribute accepts (violin, hist, nothing), but not: $(clouds)") end end - scatter_x = final_x_positions .+ side_scatter_nudge_with_direction.*width_ratio .+ - jitter .- recenter_to_boxplot_nudge_value.*width_ratio + scatter_x = final_x_positions .+ side_scatter_nudge_with_direction .* width_ratio .+ + jitter .- recenter_to_boxplot_nudge_value .* width_ratio if plot.orientation[] == :vertical - scatter!(plot, scatter_x, data_array; markersize=markersize, plot.color, plot.cycle) + scatter!(plot, scatter_x, data_array; markersize = markersize, plot.color, plot.cycle) else - scatter!(plot, data_array, scatter_x; markersize=markersize, plot.color, plot.cycle) + scatter!(plot, data_array, scatter_x; markersize = markersize, plot.color, plot.cycle) end if plot_boxplots - boxplot!(plot, final_x_positions .+ side_boxplot_nudge_with_direction.*width_ratio .- - recenter_to_boxplot_nudge_value.*width_ratio, - data_array; - plot.orientation, - strokewidth=strokewidth, - whiskerwidth=whiskerwidth*width_ratio, - width=boxplot_width*width_ratio, - markersize=markersize, - show_outliers=plot.show_boxplot_outliers[], - color=plot.color, - cycle=plot.cycle) + boxplot!(plot, final_x_positions .+ side_boxplot_nudge_with_direction .* width_ratio .- + recenter_to_boxplot_nudge_value .* width_ratio, + data_array; + plot.orientation, + strokewidth = strokewidth, + whiskerwidth = whiskerwidth * width_ratio, + width = boxplot_width * width_ratio, + markersize = markersize, + show_outliers = plot.show_boxplot_outliers[], + color = plot.color, + cycle = plot.cycle) end return plot diff --git a/src/basic_recipes/scatterlines.jl b/src/basic_recipes/scatterlines.jl index d63b9446a4f..ad475c59c5f 100644 --- a/src/basic_recipes/scatterlines.jl +++ b/src/basic_recipes/scatterlines.jl @@ -28,10 +28,10 @@ $(ATTRIBUTES) end -function plot!(p::Combined{scatterlines, <:NTuple{N, Any}}) where N +function plot!(p::Combined{scatterlines,<:NTuple{N,Any}}) where N # markercolor is the same as linecolor if left automatic - real_markercolor = Observable{Union{Vector{RGBAf}, RGBAf}}() + real_markercolor = Observable{Union{Vector{RGBAf},RGBAf}}() map!(real_markercolor, p.color, p.markercolor) do col, mcol if mcol === automatic return to_color(col) diff --git a/src/basic_recipes/series.jl b/src/basic_recipes/series.jl index c7bf498cb42..b65403f2f4f 100644 --- a/src/basic_recipes/series.jl +++ b/src/basic_recipes/series.jl @@ -22,42 +22,40 @@ Curves can be: """ @recipe(Series, curves) do scene Attributes( - linewidth=2, - color=:lighttest, - solid_color=nothing, - labels=nothing, - - marker=nothing, - markersize=nothing, - markercolor=automatic, - strokecolor=nothing, - strokewidth=nothing, + linewidth = 2, + color = :lighttest, + solid_color = nothing, + labels = nothing, marker = nothing, + markersize = nothing, + markercolor = automatic, + strokecolor = nothing, + strokewidth = nothing, ) end replace_missing(x) = ismissing(x) ? NaN : x -function convert_arguments(T::Type{<: Series}, y::AbstractMatrix) +function convert_arguments(T::Type{<:Series}, y::AbstractMatrix) convert_arguments(T, 1:size(y, 2), y) end -function convert_arguments(::Type{<: Series}, x::AbstractVector, ys::AbstractMatrix) +function convert_arguments(::Type{<:Series}, x::AbstractVector, ys::AbstractMatrix) return (map(1:size(ys, 1)) do i Point2f.(replace_missing.(x), replace_missing.(view(ys, i, :))) end,) end -function convert_arguments(::Type{<: Series}, arg::AbstractVector{<: Tuple{X, Y}}) where {X, Y} +function convert_arguments(::Type{<:Series}, arg::AbstractVector{<:Tuple{X,Y}}) where {X,Y} return (map(arg) do (x, y) Point2f.(replace_missing.(x), replace_missing.(y)) end,) end -function convert_arguments(T::Type{<: Series}, arg::Tuple{<:AbstractVector, <:AbstractVector}) +function convert_arguments(T::Type{<:Series}, arg::Tuple{<:AbstractVector,<:AbstractVector}) return convert_arguments(T, [arg]) end -function convert_arguments(::Type{<: Series}, arg::AbstractVector{<: AbstractVector{<:Point2}}) +function convert_arguments(::Type{<:Series}, arg::AbstractVector{<:AbstractVector{<:Point2}}) return (map(arg) do points Point2f.(replace_missing.(first.(points)), replace_missing.(last.(points))) end,) @@ -84,10 +82,10 @@ function plot!(plot::Series) mcolor = plot.markercolor markercolor = @lift $mcolor == automatic ? $series_color : $mcolor scatterlines!(plot, positions; - linewidth=linewidth, color=series_color, markercolor=series_color, - label=label[], scatter...) + linewidth = linewidth, color = series_color, markercolor = series_color, + label = label[], scatter...) else - lines!(plot, positions; linewidth=linewidth, color=series_color, label=label) + lines!(plot, positions; linewidth = linewidth, color = series_color, label = label) end end end diff --git a/src/basic_recipes/spy.jl b/src/basic_recipes/spy.jl index 2b3a0469722..d479bc07d18 100644 --- a/src/basic_recipes/spy.jl +++ b/src/basic_recipes/spy.jl @@ -26,14 +26,14 @@ $(ATTRIBUTES) ) end -function convert_arguments(::Type{<: Spy}, x::SparseArrays.AbstractSparseArray) - (0..size(x, 1), 0..size(x, 2), x) +function convert_arguments(::Type{<:Spy}, x::SparseArrays.AbstractSparseArray) + (0 .. size(x, 1), 0 .. size(x, 2), x) end -function convert_arguments(::Type{<: Spy}, x, y, z::SparseArrays.AbstractSparseArray) +function convert_arguments(::Type{<:Spy}, x, y, z::SparseArrays.AbstractSparseArray) (x, y, z) end -function calculated_attributes!(::Type{<: Spy}, plot) +function calculated_attributes!(::Type{<:Spy}, plot) end function plot!(p::Spy) @@ -57,7 +57,7 @@ function plot!(p::Spy) x, y, color = SparseArrays.findnz(z) points = map(x, y) do x, y (((Point2f(x, y) .- 1) ./ Point2f(size(z) .- 1)) .* - widths(rect) .+ minimum(rect)) + widths(rect) .+ minimum(rect)) end points, convert(Vector{Float32}, color) end @@ -80,5 +80,5 @@ function plot!(p::Spy) ) lines!(p, rect, color = p.framecolor, linewidth = p.framesize, inspectable = p.inspectable, - visible = p.visible) + visible = p.visible) end diff --git a/src/basic_recipes/stairs.jl b/src/basic_recipes/stairs.jl index 10e7f27dec6..aa57f4d7605 100644 --- a/src/basic_recipes/stairs.jl +++ b/src/basic_recipes/stairs.jl @@ -29,7 +29,7 @@ function plot!(p::Stairs{<:Tuple{<:AbstractVector{<:Point2}}}) if step == :pre s_points = Vector{Point2f}(undef, length(points) * 2 - 1) s_points[1] = point = points[1] - for i in 1:length(points)-1 + for i in 1:(length(points) - 1) nextpoint = points[i + 1] s_points[2i] = Point2f(point[1], nextpoint[2]) s_points[2i + 1] = nextpoint @@ -39,8 +39,8 @@ function plot!(p::Stairs{<:Tuple{<:AbstractVector{<:Point2}}}) elseif step == :post s_points = Vector{Point2f}(undef, length(points) * 2 - 1) s_points[1] = point = points[1] - for i in 1:length(points)-1 - nextpoint = points[i+1] + for i in 1:(length(points) - 1) + nextpoint = points[i + 1] s_points[2i] = Point2f(nextpoint[1], point[2]) s_points[2i + 1] = nextpoint point = nextpoint @@ -49,8 +49,8 @@ function plot!(p::Stairs{<:Tuple{<:AbstractVector{<:Point2}}}) elseif step == :center s_points = Vector{Point2f}(undef, length(points) * 2) s_points[1] = point = points[1] - for i in 1:length(points)-1 - nextpoint = points[i+1] + for i in 1:(length(points) - 1) + nextpoint = points[i + 1] halfx = (point[1] + nextpoint[1]) / 2 s_points[2i] = Point2f(halfx, point[2]) s_points[2i + 1] = Point2f(halfx, nextpoint[2]) @@ -66,4 +66,3 @@ function plot!(p::Stairs{<:Tuple{<:AbstractVector{<:Point2}}}) lines!(p, steppoints; [x for x in pairs(p.attributes) if x[1] != :step]...) p end - diff --git a/src/basic_recipes/stem.jl b/src/basic_recipes/stem.jl index d3737b8c31c..4a78cc7252c 100644 --- a/src/basic_recipes/stem.jl +++ b/src/basic_recipes/stem.jl @@ -42,10 +42,10 @@ end conversion_trait(::Type{<:Stem}) = PointBased() -trunkpoint(stempoint::P, offset::Number) where P <: Point2 = P(stempoint[1], offset) -trunkpoint(stempoint::P, offset::Point2) where P <: Point2 = P(offset...) -trunkpoint(stempoint::P, offset::Number) where P <: Point3 = P(stempoint[1], stempoint[2], offset) -trunkpoint(stempoint::P, offset::Point3) where P <: Point3 = P(offset...) +trunkpoint(stempoint::P, offset::Number) where P<:Point2 = P(stempoint[1], offset) +trunkpoint(stempoint::P, offset::Point2) where P<:Point2 = P(offset...) +trunkpoint(stempoint::P, offset::Number) where P<:Point3 = P(stempoint[1], stempoint[2], offset) +trunkpoint(stempoint::P, offset::Point3) where P<:Point3 = P(offset...) function plot!(s::Stem{<:Tuple{<:AbstractVector{<:Point}}}) diff --git a/src/basic_recipes/streamplot.jl b/src/basic_recipes/streamplot.jl index 63e12505192..94277bd0eb9 100644 --- a/src/basic_recipes/streamplot.jl +++ b/src/basic_recipes/streamplot.jl @@ -33,13 +33,13 @@ See the function `Makie.streamplot_impl` for implementation details. ) end -function convert_arguments(::Type{<: StreamPlot}, f::Function, xrange, yrange) +function convert_arguments(::Type{<:StreamPlot}, f::Function, xrange, yrange) xmin, xmax = extrema(xrange) ymin, ymax = extrema(yrange) return (f, Rect(xmin, ymin, xmax - xmin, ymax - ymin)) end -function convert_arguments(::Type{<: StreamPlot}, f::Function, xrange, yrange, zrange) +function convert_arguments(::Type{<:StreamPlot}, f::Function, xrange, yrange, zrange) xmin, xmax = extrema(xrange) ymin, ymax = extrema(yrange) zmin, zmax = extrema(zrange) @@ -48,7 +48,7 @@ function convert_arguments(::Type{<: StreamPlot}, f::Function, xrange, yrange, z return (f, Rect(mini, maxi .- mini)) end -function convert_arguments(::Type{<: StreamPlot}, f::Function, limits::Rect) +function convert_arguments(::Type{<:StreamPlot}, f::Function, limits::Rect) return (f, limits) end @@ -73,33 +73,34 @@ Links: [Quasirandom sequences](http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/) """ -function streamplot_impl(CallType, f, limits::Rect{N, T}, resolutionND, stepsize, maxsteps=500, dens=1.0) where {N, T} - resolution = to_ndim(Vec{N, Int}, resolutionND, last(resolutionND)) +function streamplot_impl(CallType, f, limits::Rect{N,T}, resolutionND, stepsize, maxsteps = 500, dens = 1.0) where {N,T} + resolution = to_ndim(Vec{N,Int}, resolutionND, last(resolutionND)) mask = trues(resolution...) # unvisited squares - arrow_pos = Point{N, Float32}[] - arrow_dir = Vec{N, Float32}[] - line_points = Point{N, Float32}[] + arrow_pos = Point{N,Float32}[] + arrow_dir = Vec{N,Float32}[] + line_points = Point{N,Float32}[] colors = Float64[] line_colors = Float64[] - dt = Point{N, Float32}(stepsize) + dt = Point{N,Float32}(stepsize) mini, maxi = minimum(limits), maximum(limits) r = ntuple(N) do i LinRange(mini[i], maxi[i], resolution[i] + 1) end - apply_f(x0, P) = if P <: Point - f(x0) - else - f(x0...) - end + apply_f(x0, P) = + if P <: Point + f(x0) + else + f(x0...) + end # see http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/ ϕ = (MathConstants.φ, 1.324717957244746, 1.2207440846057596)[N] - acoeff = ϕ.^(-(1:N)) + acoeff = ϕ .^ (-(1:N)) n_points = 0 # count visited squares ind = 0 # index of low discrepancy sequence - while n_points < prod(resolution)*min(one(dens), dens) # fill up to 100*dens% of mask + while n_points < prod(resolution) * min(one(dens), dens) # fill up to 100*dens% of mask # next index from low discrepancy sequence c = CartesianIndex(ntuple(N) do i - j = ceil(Int, ((0.5 + acoeff[i]*ind) % 1)*resolution[i]) + j = ceil(Int, ((0.5 + acoeff[i] * ind) % 1) * resolution[i]) clamp(j, 1, size(mask, i)) end) ind += 1 @@ -121,7 +122,7 @@ function streamplot_impl(CallType, f, limits::Rect{N, T}, resolutionND, stepsize n_linepoints = 1 x = x0 ccur = c - push!(line_points, Point{N, Float32}(NaN), x) + push!(line_points, Point{N,Float32}(NaN), x) push!(line_colors, 0.0, pnorm) while x in limits && n_linepoints < maxsteps point = apply_f(x, CallType) @@ -169,7 +170,7 @@ function plot!(p::StreamPlot) end lines!( p, - lift(x->x[3], data), color = lift(last, data), colormap = p.colormap, colorrange = p.colorrange, + lift(x -> x[3], data), color = lift(last, data), colormap = p.colormap, colorrange = p.colorrange, linestyle = p.linestyle, linewidth = p.linewidth, inspectable = p.inspectable, @@ -204,7 +205,7 @@ function plot!(p::StreamPlot) p, lift(first, data), markersize = p.arrow_size, marker = @lift(arrow_head(N, $(p.arrow_head), $(p.quality))), - color = lift(x-> x[4], data), rotations = rotations, + color = lift(x -> x[4], data), rotations = rotations, colormap = p.colormap, colorrange = p.colorrange, inspectable = p.inspectable, transparency = p.transparency ) diff --git a/src/basic_recipes/text.jl b/src/basic_recipes/text.jl index b22f31c674d..3652a1378bf 100644 --- a/src/basic_recipes/text.jl +++ b/src/basic_recipes/text.jl @@ -6,11 +6,11 @@ function plot!(plot::Text) linewidths = Observable(Float32[]) linecolors = Observable(RGBAf[]) lineindices = Ref(Int[]) - + onany(plot.text, plot.fontsize, plot.font, plot.fonts, plot.align, - plot.rotation, plot.justification, plot.lineheight, plot.color, - plot.strokecolor, plot.strokewidth, plot.word_wrap_width) do str, - ts, f, fs, al, rot, jus, lh, col, scol, swi, www + plot.rotation, plot.justification, plot.lineheight, plot.color, + plot.strokecolor, plot.strokewidth, plot.word_wrap_width) do str, + ts, f, fs, al, rot, jus, lh, col, scol, swi, www ts = to_fontsize(ts) f = to_font(fs, f) rot = to_rotation(rot) @@ -35,7 +35,7 @@ function plot!(plot::Text) # If we have a Vector of strings, Vector arguments are interpreted # as per string. broadcast_foreach( - func, + func, str, 1:attr_broadcast_length(str), ts, f, fs, al, rot, jus, lh, col, scol, swi, www ) else @@ -54,8 +54,8 @@ function plot!(plot::Text) sc = parent_scene(plot) - onany(linesegs, positions, sc.camera.projectionview, sc.px_area, - transform_func_obs(sc), get(plot, :space, :data)) do segs, pos, _, _, transf, space + onany(linesegs, positions, sc.camera.projectionview, sc.px_area, + transform_func_obs(sc), get(plot, :space, :data)) do segs, pos, _, _, transf, space pos_transf = scene_to_screen(apply_transform(transf, pos, space), sc) linesegs_shifted[] = map(segs, lineindices[]) do seg, index seg + attr_broadcast_getindex(pos_transf, index) @@ -86,7 +86,7 @@ function _get_glyphcollection_and_linesegments(str::AbstractString, index, ts, f end function _get_glyphcollection_and_linesegments(latexstring::LaTeXString, index, ts, f, fs, al, rot, jus, lh, col, scol, swi, www) tex_elements, glyphcollections, offset = texelems_and_glyph_collection(latexstring, ts, - al[1], al[2], rot, col, scol, swi, www) + al[1], al[2], rot, col, scol, swi, www) linesegs = Point2f[] linewidths = Float32[] @@ -119,11 +119,11 @@ function plot!(plot::Text{<:Tuple{<:AbstractString}}) end # conversion stopper for previous methods -convert_arguments(::Type{<: Text}, gcs::AbstractVector{<:GlyphCollection}) = (gcs,) -convert_arguments(::Type{<: Text}, gc::GlyphCollection) = (gc,) -convert_arguments(::Type{<: Text}, vec::AbstractVector{<:Tuple{<:AbstractString, <:Point}}) = (vec,) -convert_arguments(::Type{<: Text}, strings::AbstractVector{<:AbstractString}) = (strings,) -convert_arguments(::Type{<: Text}, string::AbstractString) = (string,) +convert_arguments(::Type{<:Text}, gcs::AbstractVector{<:GlyphCollection}) = (gcs,) +convert_arguments(::Type{<:Text}, gc::GlyphCollection) = (gc,) +convert_arguments(::Type{<:Text}, vec::AbstractVector{<:Tuple{<:AbstractString,<:Point}}) = (vec,) +convert_arguments(::Type{<:Text}, strings::AbstractVector{<:AbstractString}) = (strings,) +convert_arguments(::Type{<:Text}, string::AbstractString) = (string,) # TODO: is this necessary? there seems to be a recursive loop with the above # function without these two interceptions, but I didn't need it before merging @@ -137,13 +137,13 @@ function plot!(plot::Text{<:Tuple{<:AbstractArray{<:AbstractString}}}) end # overload text plotting for a vector of tuples of a string and a point each -function plot!(plot::Text{<:Tuple{<:AbstractArray{<:Tuple{<:AbstractString, <:Point}}}}) +function plot!(plot::Text{<:Tuple{<:AbstractArray{<:Tuple{<:AbstractString,<:Point}}}}) strings_and_positions = plot[1] strings = Observable{Vector{AbstractString}}(first.(strings_and_positions[])) positions = Observable( - Point3f[to_ndim(Point3f, last(x), 0) for x in strings_and_positions[]] # avoid Any for zero elements + Point3f[to_ndim(Point3f, last(x), 0) for x in strings_and_positions[]] # avoid Any for zero elements ) attrs = plot.attributes @@ -165,7 +165,7 @@ function plot!(plot::Text{<:Tuple{<:AbstractArray{<:Tuple{<:AbstractString, <:Po end function texelems_and_glyph_collection(str::LaTeXString, fontscale_px, halign, valign, - rotation, color, strokecolor, strokewidth, word_wrap_width) + rotation, color, strokecolor, strokewidth, word_wrap_width) rot = convert_attribute(rotation, key"rotation"()) @@ -204,12 +204,12 @@ function texelems_and_glyph_collection(str::LaTeXString, fontscale_px, halign, v if last_space_idx != 0 && right_pos > word_wrap_width section_offset = basepositions[last_space_idx + 1][1] lineheight = maximum((height(bb) for bb in bboxes[last_newline_idx:last_space_idx])) - last_newline_idx = last_space_idx+1 + last_newline_idx = last_space_idx + 1 newline_offset += Point3f(section_offset, lineheight, 0) # TODO: newlines don't really need to represented at all? # chars[last_space_idx] = '\n' - for j in last_space_idx+1:i + for j in (last_space_idx + 1):i basepositions[j] -= Point3f(section_offset, lineheight, 0) end end @@ -266,7 +266,7 @@ iswhitespace(l::LaTeXString) = iswhitespace(replace(l.s, '$' => "")) struct RichText <: AbstractString type::Symbol children::Vector{Union{RichText,String}} - attributes::Dict{Symbol, Any} + attributes::Dict{Symbol,Any} function RichText(type::Symbol, children...; kwargs...) cs = Union{RichText,String}[children...] typeof(cs) @@ -345,7 +345,7 @@ function layout_text(rt::RichText, ts, f, fset, al, rot, jus, lh, col) stack = [GlyphState(0, 0, Vec2f(ts), _f, to_color(col))] lines = [GlyphInfo[]] - + process_rt_node!(stack, lines, rt, fset) apply_lineheight!(lines, lh) @@ -363,7 +363,7 @@ function apply_lineheight!(lines, lh) for (i, line) in enumerate(lines) for j in eachindex(line) l = line[j] - l = Setfield.@set l.origin[2] -= (i-1) * 20 # TODO: Lineheight + l = Setfield.@set l.origin[2] -= (i - 1) * 20 # TODO: Lineheight line[j] = l end end @@ -406,7 +406,7 @@ function apply_alignment_and_justification!(lines, ju, al) end fju = float_justification(ju, al) - + for (i, line) in enumerate(lines) ju_offset = fju * (max_x - max_xs[i]) for j in eachindex(line) diff --git a/src/basic_recipes/tooltip.jl b/src/basic_recipes/tooltip.jl index 01b88fbe9fd..52bfa252efb 100644 --- a/src/basic_recipes/tooltip.jl +++ b/src/basic_recipes/tooltip.jl @@ -37,12 +37,12 @@ Creates a tooltip pointing at `position` displaying the given `string` @recipe(Tooltip, position) do scene Attributes(; # General - text = "", + text = "", offset = 10, placement = :above, align = 0.5, - xautolimits = false, - yautolimits = false, + xautolimits = false, + yautolimits = false, zautolimits = false, overdraw = false, depth_shift = 0f0, @@ -62,18 +62,18 @@ Creates a tooltip pointing at `position` displaying the given `string` # Background backgroundcolor = :white, triangle_size = 10, - + # Outline outline_color = :black, outline_linewidth = 2f0, - outline_linestyle = nothing, + outline_linestyle = nothing ) end -convert_arguments(::Type{<: Tooltip}, x::Real, y::Real, str::AbstractString) = (Point2f(x, y), str) -convert_arguments(::Type{<: Tooltip}, x::Real, y::Real) = (Point2f(x, y),) -function plot!(plot::Tooltip{<:Tuple{<:VecTypes, <:AbstractString}}) - plot.attributes[:text] = plot[2] +convert_arguments(::Type{<:Tooltip}, x::Real, y::Real, str::AbstractString) = (Point2f(x, y), str) +convert_arguments(::Type{<:Tooltip}, x::Real, y::Real) = (Point2f(x, y),) +function plot!(plot::Tooltip{<:Tuple{<:VecTypes,<:AbstractString}}) + plot.attributes[:text] = plot[2] tooltip!(plot, plot[1]; plot.attributes...) plot end @@ -103,14 +103,14 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) text_offset = map(p.offset, textpadding, p.triangle_size, p.placement, p.align) do o, pad, ts, placement, align l, r, b, t = pad - if placement == :left + if placement == :left return Vec2f(-o - r - ts, b - align * (b + t)) elseif placement == :right - return Vec2f( o + l + ts, b - align * (b + t)) + return Vec2f(o + l + ts, b - align * (b + t)) elseif placement in (:below, :down, :bottom) return Vec2f(l - align * (l + r), -o - t - ts) elseif placement in (:above, :up, :top) - return Vec2f(l - align * (l + r), o + b + ts) + return Vec2f(l - align * (l + r), o + b + ts) else @error "Tooltip placement $placement invalid. Assuming :above" return Vec2f(0, o + b + ts) @@ -118,7 +118,7 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) end text_align = map(p.placement, p.align) do placement, align - if placement == :left + if placement == :left return (1.0, align) elseif placement == :right return (0.0, align) @@ -145,11 +145,11 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) # TODO react to glyphcollection instead bbox = map( - px_pos, p.text, text_align, text_offset, textpadding, p.align - ) do p, s, _, o, pad, align + px_pos, p.text, text_align, text_offset, textpadding, p.align + ) do p, s, _, o, pad, align bb = Rect2f(boundingbox(tp)) + o l, r, b, t = pad - return Rect2f(origin(bb) .- (l, b), widths(bb) .+ (l+r, b+t)) + return Rect2f(origin(bb) .- (l, b), widths(bb) .+ (l + r, b + t)) end # Text background mesh @@ -157,7 +157,7 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) mesh!( p, bbox, shading = false, space = :pixel, color = p.backgroundcolor, fxaa = false, - transparency = p.transparency, visible = p.visible, + transparency = p.transparency, visible = p.visible, overdraw = p.overdraw, depth_shift = p.depth_shift, inspectable = p.inspectable ) @@ -166,36 +166,37 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) triangle = GeometryBasics.Mesh( Point2f[(-0.5, 0), (0.5, 0), (0, -1)], - GLTriangleFace[(1,2,3)] + GLTriangleFace[(1, 2, 3)] ) mp = mesh!( p, triangle, shading = false, space = :pixel, - color = p.backgroundcolor, + color = p.backgroundcolor, transparency = p.transparency, visible = p.visible, overdraw = p.overdraw, depth_shift = p.depth_shift, inspectable = p.inspectable ) onany(bbox, p.triangle_size, p.placement, p.align) do bb, s, placement, align - o = origin(bb); w = widths(bb) + o = origin(bb) + w = widths(bb) scale!(mp, s, s, s) - - if placement == :left + + if placement == :left translate!(mp, Vec3f(o[1] + w[1], o[2] + align * w[2], 0)) - rotate!(mp, qrotation(Vec3f(0,0,1), 0.5pi)) + rotate!(mp, qrotation(Vec3f(0, 0, 1), 0.5pi)) elseif placement == :right translate!(mp, Vec3f(o[1], o[2] + align * w[2], 0)) - rotate!(mp, qrotation(Vec3f(0,0,1), -0.5pi)) + rotate!(mp, qrotation(Vec3f(0, 0, 1), -0.5pi)) elseif placement in (:below, :down, :bottom) translate!(mp, Vec3f(o[1] + align * w[1], o[2] + w[2], 0)) - rotate!(mp, Quaternionf(0,0,1,0)) # pi + rotate!(mp, Quaternionf(0, 0, 1, 0)) # pi elseif placement in (:above, :up, :top) translate!(mp, Vec3f(o[1] + align * w[1], o[2], 0)) - rotate!(mp, Quaternionf(0,0,0,1)) # 0 + rotate!(mp, Quaternionf(0, 0, 0, 1)) # 0 else @error "Tooltip placement $placement invalid. Assuming :above" translate!(mp, Vec3f(o[1] + align * w[1], o[2], 0)) - rotate!(mp, Quaternionf(0,0,0,1)) + rotate!(mp, Quaternionf(0, 0, 0, 1)) end return end @@ -203,7 +204,8 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) # Outline outline = map(bbox, p.triangle_size, p.placement, p.align) do bb, s, placement, align - l, b = origin(bb); w, h = widths(bb) + l, b = origin(bb) + w, h = widths(bb) r, t = (l, b) .+ (w, h) # We start/end at half width/height here to avoid corners like this: @@ -212,45 +214,45 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) # | ____ # | | - shift = if placement == :left + shift = if placement == :left Vec2f[ - (l, b + 0.5h), (l, t), (r, t), - (r, b + align * h + 0.5s), - (r + s, b + align * h), - (r, b + align * h - 0.5s), + (l, b + 0.5h), (l, t), (r, t), + (r, b + align * h + 0.5s), + (r + s, b + align * h), + (r, b + align * h - 0.5s), (r, b), (l, b), (l, b + 0.5h) ] elseif placement == :right Vec2f[ - (l + 0.5w, b), (l, b), - (l, b + align * h - 0.5s), - (l-s, b + align * h), - (l, b + align * h + 0.5s), + (l + 0.5w, b), (l, b), + (l, b + align * h - 0.5s), + (l - s, b + align * h), + (l, b + align * h + 0.5s), (l, t), (r, t), (r, b), (l + 0.5w, b) ] elseif placement in (:below, :down, :bottom) Vec2f[ - (l, b + 0.5h), (l, t), - (l + align * w - 0.5s, t), - (l + align * w, t+s), - (l + align * w + 0.5s, t), + (l, b + 0.5h), (l, t), + (l + align * w - 0.5s, t), + (l + align * w, t + s), + (l + align * w + 0.5s, t), (r, t), (r, b), (l, b), (l, b + 0.5h) ] elseif placement in (:above, :up, :top) Vec2f[ - (l, b + 0.5h), (l, t), (r, t), (r, b), - (l + align * w + 0.5s, b), - (l + align * w, b-s), - (l + align * w - 0.5s, b), + (l, b + 0.5h), (l, t), (r, t), (r, b), + (l + align * w + 0.5s, b), + (l + align * w, b - s), + (l + align * w - 0.5s, b), (l, b), (l, b + 0.5h) ] else @error "Tooltip placement $placement invalid. Assuming :above" Vec2f[ - (l, b + 0.5h), (l, t), (r, t), (r, b), - (l + align * w + 0.5s, b), - (l + align * w, b-s), - (l + align * w - 0.5s, b), + (l, b + 0.5h), (l, t), (r, t), (r, b), + (l + align * w + 0.5s, b), + (l + align * w, b - s), + (l + align * w - 0.5s, b), (l, b), (l, b + 0.5h) ] end @@ -259,8 +261,8 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) end lines!( - p, outline, - color = p.outline_color, space = :pixel, + p, outline, + color = p.outline_color, space = :pixel, linewidth = p.outline_linewidth, linestyle = p.outline_linestyle, transparency = p.transparency, visible = p.visible, overdraw = p.overdraw, depth_shift = p.depth_shift, @@ -270,4 +272,4 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) notify(p[1]) return p -end \ No newline at end of file +end diff --git a/src/basic_recipes/tricontourf.jl b/src/basic_recipes/tricontourf.jl index deef1fc3e49..930a1f95456 100644 --- a/src/basic_recipes/tricontourf.jl +++ b/src/basic_recipes/tricontourf.jl @@ -56,16 +56,16 @@ function compute_contourf_colormap(levels, cmap, elow, ehigh) _cmap = to_colormap(cmap) if elow == :auto && !(ehigh == :auto) - cm_base = cgrad(_cmap, n + 1; categorical=true)[2:end] - cm = cgrad(cm_base, levels_scaled; categorical=true) + cm_base = cgrad(_cmap, n + 1; categorical = true)[2:end] + cm = cgrad(cm_base, levels_scaled; categorical = true) elseif ehigh == :auto && !(elow == :auto) - cm_base = cgrad(_cmap, n + 1; categorical=true)[1:(end - 1)] - cm = cgrad(cm_base, levels_scaled; categorical=true) + cm_base = cgrad(_cmap, n + 1; categorical = true)[1:(end - 1)] + cm = cgrad(cm_base, levels_scaled; categorical = true) elseif ehigh == :auto && elow == :auto - cm_base = cgrad(_cmap, n + 2; categorical=true)[2:(end - 1)] - cm = cgrad(cm_base, levels_scaled; categorical=true) + cm_base = cgrad(_cmap, n + 2; categorical = true)[2:(end - 1)] + cm = cgrad(cm_base, levels_scaled; categorical = true) else - cm = cgrad(_cmap, levels_scaled; categorical=true) + cm = cgrad(_cmap, levels_scaled; categorical = true) end return cm end @@ -101,7 +101,7 @@ function Makie.plot!(c::Tricontourf{<:Tuple{<:AbstractVector{<:Real},<:AbstractV minimum(levels), maximum(levels) end computed_colormap = lift(compute_contourf_colormap, c._computed_levels, c.colormap, c.extendlow, - c.extendhigh) + c.extendhigh) c.attributes[:_computed_colormap] = computed_colormap lowcolor = Observable{RGBAf}() @@ -130,7 +130,7 @@ function Makie.plot!(c::Tricontourf{<:Tuple{<:AbstractVector{<:Real},<:AbstractV @assert issorted(levels) is_extended_low && pushfirst!(levels, -Inf) is_extended_high && push!(levels, Inf) - lows = levels[1:end-1] + lows = levels[1:(end - 1)] highs = levels[2:end] trianglelist = compute_triangulation(triangulation, xs, ys) @@ -145,7 +145,7 @@ function Makie.plot!(c::Tricontourf{<:Tuple{<:AbstractVector{<:Real},<:AbstractV if isempty(pointvecs) continue end - + for pointvec in pointvecs p = Makie.Polygon(pointvec) push!(polys[], p) @@ -199,9 +199,9 @@ function filled_tricontours(m::TriplotBase.TriMesh, z, levels) @assert issorted(levels) nlevels = length(levels) filled_contours = TriplotBase.FilledContour{eltype(levels)}[] - for i=1:nlevels-1 + for i in 1:(nlevels - 1) lower = levels[i] - upper = levels[i+1] + upper = levels[i + 1] push!(filled_contours, TriplotBase.generate_filled_contours(m, z, lower, upper)) end filled_contours diff --git a/src/basic_recipes/volumeslices.jl b/src/basic_recipes/volumeslices.jl index a43598099b5..c88ffc6d923 100644 --- a/src/basic_recipes/volumeslices.jl +++ b/src/basic_recipes/volumeslices.jl @@ -33,11 +33,11 @@ function plot!(plot::VolumeSlices) mx, Mx = extrema(x) my, My = extrema(y) mz, Mz = extrema(z) - Rect3(mx, my, mz, Mx-mx, My-my, Mz-mz) + Rect3(mx, my, mz, Mx - mx, My - my, Mz - mz) end axes = :x, :y, :z - for (ax, p, r, (X, Y)) ∈ zip(axes, (:yz, :xz, :xy), (x, y, z), ((y, z), (x, z), (x, y))) + for (ax, p, r, (X, Y)) in zip(axes, (:yz, :xz, :xy), (x, y, z), ((y, z), (x, z), (x, y))) plot[Symbol(:heatmap_, p)] = hmap = heatmap!( plot, attr, X, Y, zeros(length(X[]), length(Y[])) ) diff --git a/src/basic_recipes/waterfall.jl b/src/basic_recipes/waterfall.jl index 04667aba03a..c8943427bb9 100644 --- a/src/basic_recipes/waterfall.jl +++ b/src/basic_recipes/waterfall.jl @@ -12,21 +12,21 @@ Furthermore the same attributes as for `barplot` are supported. """ @recipe(Waterfall, x, y) do scene return Attributes(; - dodge=automatic, - n_dodge=automatic, - gap=0.2, - dodge_gap=0.03, - width=automatic, - cycle=[:color => :patchcolor], - stack=automatic, - show_direction=false, - marker_pos=:utriangle, - marker_neg=:dtriangle, - direction_color=theme(scene, :backgroundcolor), - show_final=false, - final_color=plot_color(:grey90, 0.5), - final_gap=automatic, - final_dodge_gap=0, + dodge = automatic, + n_dodge = automatic, + gap = 0.2, + dodge_gap = 0.03, + width = automatic, + cycle = [:color => :patchcolor], + stack = automatic, + show_direction = false, + marker_pos = :utriangle, + marker_neg = :dtriangle, + direction_color = theme(scene, :backgroundcolor), + show_final = false, + final_color = plot_color(:grey90, 0.5), + final_gap = automatic, + final_dodge_gap = 0 ) end @@ -43,14 +43,14 @@ function Makie.plot!(p::Waterfall) xy = similar(xy) fillto = similar(x) final = similar(xy) - groupby = StructArray(; grp=i_group) + groupby = StructArray(; grp = i_group) for (grp, inds) in StructArrays.finduniquesorted(groupby) fromto = stack_from_to_final(i_stack[inds], y[inds]) fillto[inds] .= fromto.from xy[inds] .= Point2f.(x[inds], fromto.to) final[inds] .= Point2f.(x[inds], fromto.final) end - return (xy=xy, fillto=fillto, final=final) + return (xy = xy, fillto = fillto, final = final) end fromto = lift(stack_bars, p[1], p.dodge, p.stack) @@ -60,10 +60,10 @@ function Makie.plot!(p::Waterfall) barplot!( p, lift(x -> x.final, fromto); - dodge=p.dodge, - color=p.final_color, - dodge_gap=p.final_dodge_gap, - gap=final_gap, + dodge = p.dodge, + color = p.final_color, + dodge_gap = p.final_dodge_gap, + gap = final_gap ) end @@ -71,8 +71,8 @@ function Makie.plot!(p::Waterfall) p, lift(x -> x.xy, fromto); p.attributes..., - fillto=lift(x -> x.fillto, fromto), - stack=automatic, + fillto = lift(x -> x.fillto, fromto), + stack = automatic ) if p.show_direction[] @@ -99,7 +99,7 @@ function Makie.plot!(p::Waterfall) shapes[i] = marker_neg end end - return (xy=xy, shapes=shapes) + return (xy = xy, shapes = shapes) end markers = lift( @@ -117,8 +117,8 @@ function Makie.plot!(p::Waterfall) scatter!( p, lift(x -> x.xy, markers); - marker=lift(x -> x.shapes, markers), - color=p.direction_color) + marker = lift(x -> x.shapes, markers), + color = p.direction_color) end return p @@ -129,5 +129,5 @@ function stack_from_to_final(i_stack, y) perm = sortperm(i_stack) # sort by i_stack inv_perm = sortperm(order[perm]) # restore original order from, to = stack_from_to_sorted(view(y, perm)) - return (from=view(from, inv_perm), to=view(to, inv_perm), final=last(to)) + return (from = view(from, inv_perm), to = view(to, inv_perm), final = last(to)) end diff --git a/src/basic_recipes/wireframe.jl b/src/basic_recipes/wireframe.jl index 374a2f4464c..05bf44f2a29 100644 --- a/src/basic_recipes/wireframe.jl +++ b/src/basic_recipes/wireframe.jl @@ -15,18 +15,18 @@ See [`wireframe`](@ref). """ wireframe! -function convert_arguments(::Type{<: Wireframe}, x::AbstractVector, y::AbstractVector, z::AbstractMatrix) +function convert_arguments(::Type{<:Wireframe}, x::AbstractVector, y::AbstractVector, z::AbstractMatrix) (ngrid(x, y)..., z) end xvector(x::AbstractVector, len) = x -xvector(x::ClosedInterval, len) = range(minimum(x), stop=maximum(x), length=len) +xvector(x::ClosedInterval, len) = range(minimum(x), stop = maximum(x), length = len) xvector(x::AbstractMatrix, len) = x yvector(x, len) = xvector(x, len)' yvector(x::AbstractMatrix, len) = x -function plot!(plot::Wireframe{<: Tuple{<: Any, <: Any, <: AbstractMatrix}}) +function plot!(plot::Wireframe{<:Tuple{<:Any,<:Any,<:AbstractMatrix}}) points_faces = lift(plot[1:3]...) do x, y, z M, N = size(z) points = vec(Point3f.(xvector(x, M), yvector(y, N), z)) diff --git a/src/bezier.jl b/src/bezier.jl index 924f0d675bc..ff5248a1f00 100644 --- a/src/bezier.jl +++ b/src/bezier.jl @@ -36,7 +36,7 @@ EllipticalArc(cx, cy, r1, r2, angle, a1, a2) = EllipticalArc(Point(cx, cy), struct ClosePath end -const PathCommand = Union{MoveTo, LineTo, CurveTo, EllipticalArc, ClosePath} +const PathCommand = Union{MoveTo,LineTo,CurveTo,EllipticalArc,ClosePath} struct BezierPath commands::Vector{PathCommand} @@ -54,7 +54,7 @@ StableHashTraits.transform(c::ClosePath) = 0 Base.:(==)(b1::BezierPath, b2::BezierPath) = b1.commands == b2.commands Base.broadcastable(b::BezierPath) = Ref(b) -function Base.:+(pc::P, p::Point2) where P <: PathCommand +function Base.:+(pc::P, p::Point2) where P<:PathCommand fnames = fieldnames(P) return P(map(f -> getfield(pc, f) + p, fnames)...) end @@ -85,7 +85,7 @@ function scale(e::EllipticalArc, v::VecTypes{2}) elseif x < 0 && y > 0 pi - e.angle, -e.a1, -e.a2 else - pi - e.angle, pi-e.a1, pi-e.a2 + pi - e.angle, pi - e.a1, pi - e.a2 end EllipticalArc(e.c .* v, e.r1 * abs(x), e.r2 * abs(y), ang, a1, a2) end @@ -96,7 +96,7 @@ rotate(c::ClosePath, a) = c rotate(l::LineTo, a) = LineTo(rotmatrix2d(a) * l.p) function rotate(c::CurveTo, a) m = rotmatrix2d(a) - CurveTo(m * c.c1, m * c.c2, m *c.p) + CurveTo(m * c.c1, m * c.c2, m * c.p) end function rotate(e::EllipticalArc, a) m = rotmatrix2d(a) @@ -148,9 +148,9 @@ const BezierUTriangle = let h = 0.97 # sqrt(aspect) * sqrt(2) w = 0.97 # 1/sqrt(aspect) * sqrt(2) # r = Float32(sqrt(1 / (3 * sqrt(3) / 4))) - p1 = Point(0, h/2) - p2 = Point2(-w/2, -h/2) - p3 = Point2(w/2, -h/2) + p1 = Point(0, h / 2) + p2 = Point2(-w / 2, -h / 2) + p3 = Point2(w / 2, -h / 2) centroid = (p1 + p2 + p3) / 3 bp = BezierPath([ MoveTo(p1 - centroid), @@ -160,13 +160,13 @@ const BezierUTriangle = let ]) end -const BezierLTriangle = rotate(BezierUTriangle, pi/2) +const BezierLTriangle = rotate(BezierUTriangle, pi / 2) const BezierDTriangle = rotate(BezierUTriangle, pi) -const BezierRTriangle = rotate(BezierUTriangle, 3pi/2) +const BezierRTriangle = rotate(BezierUTriangle, 3pi / 2) const BezierSquare = let - r = 0.95 * sqrt(pi)/2/2 # this gives a little less area as the r=0.5 circle + r = 0.95 * sqrt(pi) / 2 / 2 # this gives a little less area as the r=0.5 circle BezierPath([ MoveTo(Point2(r, -r)), LineTo(Point2(r, r)), @@ -177,12 +177,12 @@ const BezierSquare = let end const BezierCross = let - cutfraction = 2/3 + cutfraction = 2 / 3 r = 0.5 # 1/(2 * sqrt(1 - cutfraction^2)) ri = 0.166 #r * (1 - cutfraction) first_three = Point2[(r, ri), (ri, ri), (ri, r)] - all = map(0:pi/2:3pi/2) do a + all = map(0:(pi / 2):(3pi / 2)) do a m = Mat2f(sin(a), cos(a), cos(a), -sin(a)) Ref(m) .* first_three end |> x -> reduce(vcat, x) @@ -194,13 +194,13 @@ const BezierCross = let ]) end -const BezierX = rotate(BezierCross, pi/4) +const BezierX = rotate(BezierCross, pi / 4) function bezier_ngon(n, radius, angle) points = [radius * Point2f(cos(a + angle), sin(a + angle)) - for a in range(0, 2pi, length = n+1)[1:end-1]] + for a in range(0, 2pi, length = n + 1)[1:(end - 1)]] BezierPath([ - MoveTo(points[1]); + MoveTo(points[1]) LineTo.(points[2:end]) ]) end @@ -208,10 +208,10 @@ end function bezier_star(n, inner_radius, outer_radius, angle) points = [ (isodd(i) ? outer_radius : inner_radius) * - Point2f(cos(a + angle), sin(a + angle)) - for (i, a) in enumerate(range(0, 2pi, length = 2n+1)[1:end-1])] + Point2f(cos(a + angle), sin(a + angle)) + for (i, a) in enumerate(range(0, 2pi, length = 2n + 1)[1:(end - 1)])] BezierPath([ - MoveTo(points[1]); + MoveTo(points[1]) LineTo.(points[2:end]) ]) end @@ -301,27 +301,27 @@ function parse_bezier_commands(svg) end if comm == "M" - x, y = parse.(Float64, args[i+1:i+2]) + x, y = parse.(Float64, args[(i + 1):(i + 2)]) push!(commands, MoveTo(Point2(x, y))) i += 3 elseif comm == "m" - x, y = parse.(Float64, args[i+1:i+2]) + x, y = parse.(Float64, args[(i + 1):(i + 2)]) push!(commands, MoveTo(Point2(x, y) + lastp())) i += 3 elseif comm == "L" - x, y = parse.(Float64, args[i+1:i+2]) + x, y = parse.(Float64, args[(i + 1):(i + 2)]) push!(commands, LineTo(Point2(x, y))) i += 3 elseif comm == "l" - x, y = parse.(Float64, args[i+1:i+2]) + x, y = parse.(Float64, args[(i + 1):(i + 2)]) push!(commands, LineTo(Point2(x, y) + lastp())) i += 3 elseif comm == "H" - x = parse(Float64, args[i+1]) + x = parse(Float64, args[i + 1]) push!(commands, LineTo(Point2(x, lastp()[2]))) i += 2 elseif comm == "h" - x = parse(Float64, args[i+1]) + x = parse(Float64, args[i + 1]) push!(commands, LineTo(X(x) + lastp())) i += 2 elseif comm == "Z" @@ -331,55 +331,55 @@ function parse_bezier_commands(svg) push!(commands, ClosePath()) i += 1 elseif comm == "C" - x1, y1, x2, y2, x3, y3 = parse.(Float64, args[i+1:i+6]) + x1, y1, x2, y2, x3, y3 = parse.(Float64, args[(i + 1):(i + 6)]) push!(commands, CurveTo(Point2(x1, y1), Point2(x2, y2), Point2(x3, y3))) i += 7 elseif comm == "c" - x1, y1, x2, y2, x3, y3 = parse.(Float64, args[i+1:i+6]) + x1, y1, x2, y2, x3, y3 = parse.(Float64, args[(i + 1):(i + 6)]) l = lastp() push!(commands, CurveTo(Point2(x1, y1) + l, Point2(x2, y2) + l, Point2(x3, y3) + l)) i += 7 elseif comm == "S" - x1, y1, x2, y2 = parse.(Float64, args[i+1:i+4]) + x1, y1, x2, y2 = parse.(Float64, args[(i + 1):(i + 4)]) prev = commands[end] reflected = prev.p + (prev.p - prev.c2) push!(commands, CurveTo(reflected, Point2(x1, y1), Point2(x2, y2))) i += 5 elseif comm == "s" - x1, y1, x2, y2 = parse.(Float64, args[i+1:i+4]) + x1, y1, x2, y2 = parse.(Float64, args[(i + 1):(i + 4)]) prev = commands[end] reflected = prev.p + (prev.p - prev.c2) l = lastp() push!(commands, CurveTo(reflected, Point2(x1, y1) + l, Point2(x2, y2) + l)) i += 5 elseif comm == "A" - args[i+1:i+7] - r1, r2 = parse.(Float64, args[i+1:i+2]) - angle = parse(Float64, args[i+3]) - large_arc_flag, sweep_flag = parse.(Bool, args[i+4:i+5]) - x2, y2 = parse.(Float64, args[i+6:i+7]) + args[(i + 1):(i + 7)] + r1, r2 = parse.(Float64, args[(i + 1):(i + 2)]) + angle = parse(Float64, args[i + 3]) + large_arc_flag, sweep_flag = parse.(Bool, args[(i + 4):(i + 5)]) + x2, y2 = parse.(Float64, args[(i + 6):(i + 7)]) x1, y1 = lastp() push!(commands, EllipticalArc(x1, y1, x2, y2, r1, r2, angle, large_arc_flag, sweep_flag)) i += 8 elseif comm == "a" - r1, r2 = parse.(Float64, args[i+1:i+2]) - angle = parse(Float64, args[i+3]) - large_arc_flag, sweep_flag = parse.(Bool, args[i+4:i+5]) + r1, r2 = parse.(Float64, args[(i + 1):(i + 2)]) + angle = parse(Float64, args[i + 3]) + large_arc_flag, sweep_flag = parse.(Bool, args[(i + 4):(i + 5)]) x1, y1 = lastp() - x2, y2 = parse.(Float64, args[i+6:i+7]) .+ (x1, y1) + x2, y2 = parse.(Float64, args[(i + 6):(i + 7)]) .+ (x1, y1) push!(commands, EllipticalArc(x1, y1, x2, y2, r1, r2, angle, large_arc_flag, sweep_flag)) i += 8 elseif comm == "v" - dy = parse(Float64, args[i+1]) + dy = parse(Float64, args[i + 1]) l = lastp() push!(commands, LineTo(Point2(l[1], l[2] + dy))) i += 2 elseif comm == "V" - y = parse(Float64, args[i+1]) + y = parse(Float64, args[i + 1]) l = lastp() push!(commands, LineTo(Point2(l[1], y))) i += 2 @@ -407,15 +407,15 @@ function EllipticalArc(x1, y1, x2, y2, rx, ry, ϕ, largearc::Bool, sweepflag::Bo x1′, y1′ = m1 * (0.5 * (p1 - p2)) tempsqrt = (rx^2 * ry^2 - rx^2 * y1′^2 - ry^2 * x1′^2) / - (rx^2 * y1′^2 + ry^2 * x1′^2) + (rx^2 * y1′^2 + ry^2 * x1′^2) c′ = (largearc == sweepflag ? -1 : 1) * - sqrt(tempsqrt) * Point(rx * y1′ / ry, -ry * x1′ / rx) + sqrt(tempsqrt) * Point(rx * y1′ / ry, -ry * x1′ / rx) c = Mat2(cos(ϕ), sin(ϕ), -sin(ϕ), cos(ϕ)) * c′ + 0.5 * (p1 + p2) vecangle(u, v) = sign(u[1] * v[2] - u[2] * v[1]) * - acos(dot(u, v) / (norm(u) * norm(v))) + acos(dot(u, v) / (norm(u) * norm(v))) px(sign) = Point((sign * x1′ - c′[1]) / rx, (sign * y1′ - c′[2]) / rx) @@ -617,7 +617,7 @@ function cleanup_bbox(bb::Rect2f) return bb end -bbox(p, x::Union{LineTo, CurveTo}) = bbox(segment(p, x)) +bbox(p, x::Union{LineTo,CurveTo}) = bbox(segment(p, x)) function bbox(p, e::EllipticalArc) bbox(elliptical_arc_to_beziers(e)) end @@ -637,44 +637,44 @@ function bbox(b::BezierSegment) ma = [max.(p0, p3)...] c = -p0 + p1 - b = p0 - 2p1 + p2 + b = p0 - 2p1 + p2 a = -p0 + 3p1 - 3p2 + 1p3 - h = [(b.*b - a.*c)...] + h = [(b .* b - a .* c)...] if h[1] > 0 h[1] = sqrt(h[1]) t = (-b[1] - h[1]) / a[1] if t > 0 && t < 1 - s = 1.0-t - q = s*s*s*p0[1] + 3.0*s*s*t*p1[1] + 3.0*s*t*t*p2[1] + t*t*t*p3[1] - mi[1] = min(mi[1],q) - ma[1] = max(ma[1],q) + s = 1.0 - t + q = s * s * s * p0[1] + 3.0 * s * s * t * p1[1] + 3.0 * s * t * t * p2[1] + t * t * t * p3[1] + mi[1] = min(mi[1], q) + ma[1] = max(ma[1], q) end - t = (-b[1] + h[1])/a[1] - if t>0 && t<1 - s = 1.0-t - q = s*s*s*p0[1] + 3.0*s*s*t*p1[1] + 3.0*s*t*t*p2[1] + t*t*t*p3[1] - mi[1] = min(mi[1],q) - ma[1] = max(ma[1],q) + t = (-b[1] + h[1]) / a[1] + if t > 0 && t < 1 + s = 1.0 - t + q = s * s * s * p0[1] + 3.0 * s * s * t * p1[1] + 3.0 * s * t * t * p2[1] + t * t * t * p3[1] + mi[1] = min(mi[1], q) + ma[1] = max(ma[1], q) end end - if h[2]>0.0 + if h[2] > 0.0 h[2] = sqrt(h[2]) - t = (-b[2] - h[2])/a[2] - if t>0.0 && t<1.0 - s = 1.0-t - q = s*s*s*p0[2] + 3.0*s*s*t*p1[2] + 3.0*s*t*t*p2[2] + t*t*t*p3[2] - mi[2] = min(mi[2],q) - ma[2] = max(ma[2],q) + t = (-b[2] - h[2]) / a[2] + if t > 0.0 && t < 1.0 + s = 1.0 - t + q = s * s * s * p0[2] + 3.0 * s * s * t * p1[2] + 3.0 * s * t * t * p2[2] + t * t * t * p3[2] + mi[2] = min(mi[2], q) + ma[2] = max(ma[2], q) end - t = (-b[2] + h[2])/a[2] - if t>0.0 && t<1.0 - s = 1.0-t - q = s*s*s*p0[2] + 3.0*s*s*t*p1[2] + 3.0*s*t*t*p2[2] + t*t*t*p3[2] - mi[2] = min(mi[2],q) - ma[2] = max(ma[2],q) + t = (-b[2] + h[2]) / a[2] + if t > 0.0 && t < 1.0 + s = 1.0 - t + q = s * s * s * p0[2] + 3.0 * s * s * t * p1[2] + 3.0 * s * t * t * p2[2] + t * t * t * p3[2] + mi[2] = min(mi[2], q) + ma[2] = max(ma[2], q) end end @@ -688,9 +688,9 @@ function elliptical_arc_to_beziers(arc::EllipticalArc) angles = range(arc.a1, arc.a2, length = n_beziers + 1) startpoint = Point2f(cos(arc.a1), sin(arc.a1)) - curves = map(angles[1:end-1], angles[2:end]) do start, stop + curves = map(angles[1:(end - 1)], angles[2:end]) do start, stop theta = stop - start - kappa = 4/3 * tan(theta/4) + kappa = 4 / 3 * tan(theta / 4) c1 = Point2f(cos(start) - kappa * sin(start), sin(start) + kappa * cos(start)) c2 = Point2f(cos(stop) + kappa * sin(stop), sin(stop) - kappa * cos(stop)) b = Point2f(cos(stop), sin(stop)) diff --git a/src/camera/camera.jl b/src/camera/camera.jl index 338aec7233b..2696fe8cc5a 100644 --- a/src/camera/camera.jl +++ b/src/camera/camera.jl @@ -6,8 +6,8 @@ end function Base.:(==)(a::Camera, b::Camera) to_value(a.view) == to_value(b.view) && - to_value(a.projection) == to_value(b.projection) && - to_value(a.resolution) == to_value(b.resolution) + to_value(a.projection) == to_value(b.projection) && + to_value(a.resolution) == to_value(b.resolution) end function Base.show(io::IO, camera::Camera) @@ -39,12 +39,12 @@ function disconnect!(observables::Vector) return end -struct CameraLift{F, Args} +struct CameraLift{F,Args} f::F args::Args end -function (cl::CameraLift{F, Args})(val) where {F, Args} +function (cl::CameraLift{F,Args})(val) where {F,Args} cl.f(map(to_value, cl.args)...) end @@ -54,12 +54,12 @@ end When mapping over observables for the camera, we store them in the `steering_node` vector, to make it easier to disconnect the camera steering signals later! """ -function Observables.on(f, camera::Camera, observables::AbstractObservable...; priority=0) +function Observables.on(f, camera::Camera, observables::AbstractObservable...; priority = 0) # PriorityObservables don't implement on_any, because that would replace # the method in Observables. CameraLift acts as a workaround for now. cl = CameraLift(f, observables) for n in observables - obs = on(cl, n, priority=priority) + obs = on(cl, n, priority = priority) push!(camera.steering_nodes, obs) end return f @@ -80,7 +80,7 @@ function Camera(px_area) view, proj, proj_view, - lift(a-> Vec2f(widths(a)), px_area), + lift(a -> Vec2f(widths(a)), px_area), Observable(Vec3f(1)), ObserverFunction[] ) diff --git a/src/camera/camera2d.jl b/src/camera/camera2d.jl index 3a9a07c9024..c23855cde55 100644 --- a/src/camera/camera2d.jl +++ b/src/camera/camera2d.jl @@ -2,9 +2,9 @@ struct Camera2D <: AbstractCamera area::Observable{Rect2f} zoomspeed::Observable{Float32} zoombutton::Observable{ButtonTypes} - panbutton::Observable{Union{ButtonTypes, Vector{ButtonTypes}}} + panbutton::Observable{Union{ButtonTypes,Vector{ButtonTypes}}} padding::Observable{Float32} - last_area::Observable{Vec{2, Int}} + last_area::Observable{Vec{2,Int}} update_limits::Observable{Bool} end @@ -58,7 +58,7 @@ function update_cam!(scene::Scene, cam::Camera2D, area3d::Rect) area = Rect2f(area3d) area = positive_widths(area) # ignore rects with width almost 0 - any(x-> x ≈ 0.0, widths(area)) && return + any(x -> x ≈ 0.0, widths(area)) && return pa = pixelarea(scene)[] px_wh = normalize(widths(pa)) @@ -320,7 +320,7 @@ end Creates a pixel-level camera for the `Scene`. No controls! """ -function campixel!(scene::Scene; nearclip=-10_000f0, farclip=10_000f0) +function campixel!(scene::Scene; nearclip = -10_000f0, farclip = 10_000f0) disconnect!(camera(scene)) update_once = Observable(false) closure = UpdatePixelCam(camera(scene), nearclip, farclip) @@ -340,7 +340,7 @@ struct RelativeCamera <: AbstractCamera end Creates a pixel-level camera for the `Scene`. No controls! """ -function cam_relative!(scene::Scene; nearclip=-10_000f0, farclip=10_000f0) +function cam_relative!(scene::Scene; nearclip = -10_000f0, farclip = 10_000f0) projection = orthographicprojection(0f0, 1f0, 0f0, 1f0, nearclip, farclip) set_proj_view!(camera(scene), projection, Mat4f(I)) cam = RelativeCamera() diff --git a/src/camera/camera3d.jl b/src/camera/camera3d.jl index dc05aeb5ea0..64cae4d0917 100644 --- a/src/camera/camera3d.jl +++ b/src/camera/camera3d.jl @@ -85,28 +85,28 @@ function Camera3D(scene::Scene; kwargs...) Attributes( # Keyboard controls # Translations - up_key = Keyboard.r, - down_key = Keyboard.f, - left_key = Keyboard.a, - right_key = Keyboard.d, - forward_key = Keyboard.w, - backward_key = Keyboard.s, + up_key = Keyboard.r, + down_key = Keyboard.f, + left_key = Keyboard.a, + right_key = Keyboard.d, + forward_key = Keyboard.w, + backward_key = Keyboard.s, # Zooms - zoom_in_key = Keyboard.u, - zoom_out_key = Keyboard.o, - stretch_view_key = Keyboard.page_up, + zoom_in_key = Keyboard.u, + zoom_out_key = Keyboard.o, + stretch_view_key = Keyboard.page_up, contract_view_key = Keyboard.page_down, # Rotations - pan_left_key = Keyboard.j, + pan_left_key = Keyboard.j, pan_right_key = Keyboard.l, - tilt_up_key = Keyboard.i, + tilt_up_key = Keyboard.i, tilt_down_key = Keyboard.k, - roll_clockwise_key = Keyboard.e, + roll_clockwise_key = Keyboard.e, roll_counterclockwise_key = Keyboard.q, # Mouse controls translation_button = Mouse.right, - scroll_mod = true, - rotation_button = Mouse.left, + scroll_mod = true, + rotation_button = Mouse.left, # Shared controls fix_x_key = Keyboard.x, fix_y_key = Keyboard.y, @@ -124,7 +124,7 @@ function Camera3D(scene::Scene; kwargs...) near = automatic, far = automatic, rotation_center = :lookat, - update_rate = 1/30, + update_rate = 1 / 30, projectiontype = Perspective, fixed_axis = true, zoom_shift_lookat = false, # doesn't really work with fov @@ -136,16 +136,12 @@ function Camera3D(scene::Scene; kwargs...) cam = Camera3D( pop!(attr, :eyeposition, Vec3f(3)), - pop!(attr, :lookat, Vec3f(0)), - pop!(attr, :upvector, Vec3f(0, 0, 1)), - - Observable(1f0), + pop!(attr, :lookat, Vec3f(0)), + pop!(attr, :upvector, Vec3f(0, 0, 1)), Observable(1f0), Observable(attr[:fov][]), Observable(attr[:near][] === automatic ? 0.1f0 : attr[:near][]), - Observable(attr[:far][] === automatic ? 100f0 : attr[:far][]), - Observable(-1.0), - - attr + Observable(attr[:far][] === automatic ? 100f0 : attr[:far][]), + Observable(-1.0), attr ) disconnect!(camera(scene)) @@ -173,7 +169,7 @@ function Camera3D(scene::Scene; kwargs...) # Start ticking if relevant keys are pressed on(camera(scene), events(scene).keyboardbutton) do event if event.action in (Keyboard.press, Keyboard.repeat) && cam.pulser[] == -1.0 && - attr.selected[] && any(key -> ispressed(scene, attr[key][]), keynames) + attr.selected[] && any(key -> ispressed(scene, attr[key][]), keynames) cam.pulser[] = time() return Consume(true) @@ -204,7 +200,7 @@ function Camera3D(scene::Scene; kwargs...) end on(camera(scene), attr[:near], attr[:far]) do near, far near === automatic || (cam.near[] = near) - far === automatic || (cam.far[] = far) + far === automatic || (cam.far[] = far) update_cam!(scene, cam) end @@ -215,7 +211,7 @@ function Camera3D(scene::Scene; kwargs...) # might make sense to keep user set lookat, upvector, eyeposition # around somewhere for this? cam.lookat[] = Vec3f(0) - cam.upvector[] = Vec3f(0,0,1) + cam.upvector[] = Vec3f(0, 0, 1) cam.eyeposition[] = Vec3f(3) center!(scene) return Consume(true) @@ -298,7 +294,7 @@ function add_translation!(scene, cam::Camera3D) on(camera(scene), scene.events.scroll) do scroll if is_mouseinside(scene) && ispressed(scene, scroll_mod[]) - zoom_step = (1f0 + 0.1f0 * zoomspeed[]) ^ -scroll[2] + zoom_step = (1f0 + 0.1f0 * zoomspeed[])^-scroll[2] zoom!(scene, cam, zoom_step, shift_lookat[], cad[]) return Consume(true) end @@ -363,7 +359,7 @@ function on_pulse(scene, cam, timestep) if translating # translation in camera space x/y/z direction translation = attr[:keyboard_translationspeed][] * timestep * - Vec3f(right - left, up - down, backward - forward) + Vec3f(right - left, up - down, backward - forward) viewdir = cam.lookat[] - cam.eyeposition[] _translate_cam!(scene, cam, cam.zoom_mult[] * norm(viewdir) * translation) end @@ -380,7 +376,7 @@ function on_pulse(scene, cam, timestep) if rotating # rotations around camera space x/y/z axes angles = attr[:keyboard_rotationspeed][] * timestep * - Vec3f(up - down, left - right, counterclockwise - clockwise) + Vec3f(up - down, left - right, counterclockwise - clockwise) _rotate_cam!(scene, cam, angles) end @@ -391,14 +387,14 @@ function on_pulse(scene, cam, timestep) zooming = zoom_out || zoom_in if zooming - zoom_step = (1f0 + attr[:keyboard_zoomspeed][] * timestep) ^ (zoom_out - zoom_in) + zoom_step = (1f0 + attr[:keyboard_zoomspeed][] * timestep)^(zoom_out - zoom_in) _zoom!(scene, cam, zoom_step, false) end stretch = ispressed(scene, attr[:stretch_view_key][]) contract = ispressed(scene, attr[:contract_view_key][]) if stretch || contract - zoom_step = (1f0 + attr[:keyboard_zoomspeed][] * timestep) ^ (stretch - contract) + zoom_step = (1f0 + attr[:keyboard_zoomspeed][] * timestep)^(stretch - contract) cam.eyeposition[] = cam.lookat[] + zoom_step * (cam.eyeposition[] - cam.lookat[]) end zooming = zooming || stretch || contract @@ -444,12 +440,12 @@ function _translate_cam!(scene, cam, t) end -function rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse=false) +function rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse = false) _rotate_cam!(scene, cam, angles, from_mouse) update_cam!(scene, cam) nothing end -function _rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse=false) +function _rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse = false) # This applies rotations around the x/y/z axis of the camera coordinate system # x expands right, y expands up and z expands towards the screen lookat = cam.lookat[] @@ -552,7 +548,7 @@ function _zoom!(scene::Scene, cam::Camera3D, zoom_step, shift_lookat = false, ca # under the mouse in view fov = cam.attributes[:fov][] before = tan(clamp(cam.zoom_mult[] * fov, 0.01f0, 175f0) / 360f0 * Float32(pi)) - after = tan(clamp(cam.zoom_mult[] * zoom_step * fov, 0.01f0, 175f0) / 360f0 * Float32(pi)) + after = tan(clamp(cam.zoom_mult[] * zoom_step * fov, 0.01f0, 175f0) / 360f0 * Float32(pi)) aspect = Float32((/)(widths(scene.px_area[])...)) rel_pos = 2f0 * mouseposition_px(scene) ./ widths(scene.px_area[]) .- 1f0 @@ -566,7 +562,7 @@ function _zoom!(scene::Scene, cam::Camera3D, zoom_step, shift_lookat = false, ca shift = (1f0 - zoom_step) * (mx * w * u_x + my * h * u_y) end - cam.lookat[] = lookat + shift + cam.lookat[] = lookat + shift cam.eyeposition[] = eyepos + shift end @@ -580,7 +576,8 @@ end function update_cam!(scene::Scene, cam::Camera3D) @extractvalue cam (lookat, eyeposition, upvector) - near = cam.near[]; far = cam.far[] + near = cam.near[] + far = cam.far[] aspect = Float32((/)(widths(scene.px_area[])...)) if cam.attributes[:projectiontype][] == Perspective @@ -608,14 +605,14 @@ function update_cam!(scene::Scene, camera::Camera3D, area3d::Rect) middle = maximum(bb) - half_width old_dir = normalize(eyeposition .- lookat) camera.lookat[] = middle - neweyepos = middle .+ (1.2*norm(width) .* old_dir) + neweyepos = middle .+ (1.2 * norm(width) .* old_dir) camera.eyeposition[] = neweyepos - camera.upvector[] = Vec3f(0,0,1) + camera.upvector[] = Vec3f(0, 0, 1) if camera.attributes[:near][] === automatic camera.near[] = 0.1f0 * norm(widths(bb)) end if camera.attributes[:far][] === automatic - camera.far[] = 3f0 * norm(widths(bb)) + camera.far[] = 3f0 * norm(widths(bb)) end if camera.attributes[:projectiontype][] == Orthographic camera.zoom_mult[] = 0.6 * norm(width) @@ -637,9 +634,9 @@ end function show_cam(scene) cam = cameracontrols(scene) println("cam=cameracontrols(scene)") - println("cam.eyeposition[] = ", round.(cam.eyeposition[], digits=2)) - println("cam.lookat[] = ", round.(cam.lookat[], digits=2)) - println("cam.upvector[] = ", round.(cam.upvector[], digits=2)) - println("cam.fov[] = ", round.(cam.fov[], digits=2)) + println("cam.eyeposition[] = ", round.(cam.eyeposition[], digits = 2)) + println("cam.lookat[] = ", round.(cam.lookat[], digits = 2)) + println("cam.upvector[] = ", round.(cam.upvector[], digits = 2)) + println("cam.fov[] = ", round.(cam.fov[], digits = 2)) return end diff --git a/src/camera/old_camera3d.jl b/src/camera/old_camera3d.jl index 2d5f424cccf..87bbe133b31 100644 --- a/src/camera/old_camera3d.jl +++ b/src/camera/old_camera3d.jl @@ -99,10 +99,10 @@ the plot's axis. const old_cam3d! = old_cam3d_turntable! function projection_switch( - wh::Rect2, - fov::T, near::T, far::T, - projectiontype::ProjectionEnum, zoom::T - ) where T <: Real + wh::Rect2, + fov::T, near::T, far::T, + projectiontype::ProjectionEnum, zoom::T +) where T<:Real aspect = T((/)(widths(wh)...)) h = T(tan(fov / 360.0 * pi) * near) w = T(h * aspect) @@ -112,9 +112,9 @@ function projection_switch( end function rotate_cam( - theta::Vec{3, T}, - cam_right::Vec{3, T}, cam_up::Vec{3, T}, cam_dir::Vec{3, T} - ) where T + theta::Vec{3,T}, + cam_right::Vec{3,T}, cam_up::Vec{3,T}, cam_dir::Vec{3,T} +) where T rotation = Quaternion{T}(0, 0, 0, 1) if !all(isfinite.(theta)) # We can only rotate for finite values @@ -173,7 +173,7 @@ function add_translation!(scene, cam, key, button, zoom_shift_lookat::Bool) if ispressed(scene, button[]) && is_mouseinside(scene) cam_res = Vec2f(widths(scene.px_area[])) mouse_pos_normalized = mouseposition_px(scene) ./ cam_res - mouse_pos_normalized = 2*mouse_pos_normalized .- 1f0 + mouse_pos_normalized = 2 * mouse_pos_normalized .- 1f0 zoom_step = scroll[2] zoom!(scene, mouse_pos_normalized, zoom_step, zoom_shift_lookat) return Consume(true) @@ -263,8 +263,8 @@ function zoom!(scene, point::VecTypes, zoom_step, shift_lookat::Bool) # split zoom into two components: # the offset perpendicular to `eyeposition - lookat`, based on mouse offset ~ ray_dir # the offset parallel to `eyeposition - lookat` ~ dir - ray_eye = inv(scene.camera.projection[]) * Vec4f(point[1],point[2],0,0) - ray_eye = Vec4f(ray_eye[Vec(1, 2)]...,0,0) + ray_eye = inv(scene.camera.projection[]) * Vec4f(point[1], point[2], 0, 0) + ray_eye = Vec4f(ray_eye[Vec(1, 2)]..., 0, 0) ray_dir = Vec3f((inv(scene.camera.view[]) * ray_eye)) dir = eyeposition - lookat @@ -274,8 +274,8 @@ function zoom!(scene, point::VecTypes, zoom_step, shift_lookat::Bool) if projectiontype == Perspective ray_dir *= norm(dir) end - cam.eyeposition[] = eyeposition + (ray_dir - dir) * (1f0 - 0.9f0 ^ zoom_step) - cam.lookat[] = lookat + (1f0 - 0.9f0 ^ zoom_step) * ray_dir + cam.eyeposition[] = eyeposition + (ray_dir - dir) * (1f0 - 0.9f0^zoom_step) + cam.lookat[] = lookat + (1f0 - 0.9f0^zoom_step) * ray_dir else # Rotations need more extreme eyeposition shifts step = zoom_step @@ -333,13 +333,13 @@ function update_cam!(scene::Scene, camera::OldCamera3D, area3d::Rect) @extractvalue camera (fov, near, lookat, eyeposition, upvector) bb = Rect3f(area3d) width = widths(bb) - half_width = width/2f0 + half_width = width / 2f0 middle = maximum(bb) - half_width old_dir = normalize(eyeposition .- lookat) camera.lookat[] = middle - neweyepos = middle .+ (1.2*norm(width) .* old_dir) + neweyepos = middle .+ (1.2 * norm(width) .* old_dir) camera.eyeposition[] = neweyepos - camera.upvector[] = Vec3f(0,0,1) + camera.upvector[] = Vec3f(0, 0, 1) camera.near[] = 0.1f0 * norm(widths(bb)) camera.far[] = 3f0 * norm(widths(bb)) update_cam!(scene, camera) diff --git a/src/camera/projection_math.jl b/src/camera/projection_math.jl index 717224c6a6a..7d1cefbff8a 100644 --- a/src/camera/projection_math.jl +++ b/src/camera/projection_math.jl @@ -1,43 +1,43 @@ -function scalematrix(s::Vec{3, T}) where T +function scalematrix(s::Vec{3,T}) where T T0, T1 = zero(T), one(T) Mat{4}( - s[1],T0, T0, T0, - T0, s[2],T0, T0, - T0, T0, s[3],T0, - T0, T0, T0, T1, + s[1], T0, T0, T0, + T0, s[2], T0, T0, + T0, T0, s[3], T0, + T0, T0, T0, T1, ) end -translationmatrix_x(x::T) where {T} = translationmatrix(Vec{3, T}(x, 0, 0)) -translationmatrix_y(y::T) where {T} = translationmatrix(Vec{3, T}(0, y, 0)) -translationmatrix_z(z::T) where {T} = translationmatrix(Vec{3, T}(0, 0, z)) +translationmatrix_x(x::T) where {T} = translationmatrix(Vec{3,T}(x, 0, 0)) +translationmatrix_y(y::T) where {T} = translationmatrix(Vec{3,T}(0, y, 0)) +translationmatrix_z(z::T) where {T} = translationmatrix(Vec{3,T}(0, 0, z)) -function translationmatrix(t::Vec{3, T}) where T +function translationmatrix(t::Vec{3,T}) where T T0, T1 = zero(T), one(T) Mat{4}( - T1, T0, T0, T0, - T0, T1, T0, T0, - T0, T0, T1, T0, - t[1],t[2],t[3],T1, + T1, T0, T0, T0, + T0, T1, T0, T0, + T0, T0, T1, T0, + t[1], t[2], t[3], T1, ) end rotate(angle, axis::Vec{3}) = rotationmatrix4(qrotation(convert(Array, axis), angle)) -rotate(::Type{T}, angle::Number, axis::Vec{3}) where {T} = rotate(T(angle), convert(Vec{3, T}, axis)) +rotate(::Type{T}, angle::Number, axis::Vec{3}) where {T} = rotate(T(angle), convert(Vec{3,T}, axis)) function rotationmatrix_x(angle::Number) T0, T1 = (0, 1) Mat{4}( T1, T0, T0, T0, T0, cos(angle), sin(angle), T0, - T0, -sin(angle), cos(angle), T0, + T0, -sin(angle), cos(angle), T0, T0, T0, T0, T1 ) end function rotationmatrix_y(angle::Number) T0, T1 = (0, 1) Mat{4}( - cos(angle), T0, -sin(angle), T0, + cos(angle), T0, -sin(angle), T0, T0, T1, T0, T0, sin(angle), T0, cos(angle), T0, T0, T0, T0, T1 @@ -47,7 +47,7 @@ function rotationmatrix_z(angle::Number) T0, T1 = (0, 1) Mat{4}( cos(angle), sin(angle), T0, T0, - -sin(angle), cos(angle), T0, T0, + -sin(angle), cos(angle), T0, T0, T0, T0, T1, T0, T0, T0, T0, T1 ) @@ -102,8 +102,8 @@ function perspectiveprojection(fovy::T, aspect::T, znear::T, zfar::T) where T end function perspectiveprojection( - ::Type{T}, fovy::Number, aspect::Number, znear::Number, zfar::Number - ) where T + ::Type{T}, fovy::Number, aspect::Number, znear::Number, zfar::Number +) where T perspectiveprojection(T(fovy), T(aspect), T(znear), T(zfar)) end """ @@ -112,13 +112,13 @@ projection ratio in terms of the rectangular view size `rect` rather than the aspect ratio. """ function perspectiveprojection(wh::Rect2, fov::T, near::T, far::T) where T - perspectiveprojection(fov, T(wh.w/wh.h), near, far) + perspectiveprojection(fov, T(wh.w / wh.h), near, far) end function perspectiveprojection( - ::Type{T}, wh::Rect2, fov::Number, near::Number, far::Number - ) where T - perspectiveprojection(T(fov), T(wh.w/wh.h), T(near), T(far)) + ::Type{T}, wh::Rect2, fov::Number, near::Number, far::Number +) where T + perspectiveprojection(T(fov), T(wh.w / wh.h), T(near), T(far)) end """ @@ -129,16 +129,16 @@ the component of `up` that is perpendicular to the vector pointing from `eyeposition` to `lookat` will be used. All inputs must be supplied as 3-vectors. """ -function lookat(eyePos::Vec{3, T}, lookAt::Vec{3, T}, up::Vec{3, T}) where T - zaxis = normalize(eyePos-lookAt) - xaxis = normalize(cross(up, zaxis)) - yaxis = normalize(cross(zaxis, xaxis)) +function lookat(eyePos::Vec{3,T}, lookAt::Vec{3,T}, up::Vec{3,T}) where T + zaxis = normalize(eyePos - lookAt) + xaxis = normalize(cross(up, zaxis)) + yaxis = normalize(cross(zaxis, xaxis)) T0, T1 = zero(T), one(T) return Mat{4}( xaxis[1], yaxis[1], zaxis[1], T0, xaxis[2], yaxis[2], zaxis[2], T0, xaxis[3], yaxis[3], zaxis[3], T0, - T0, T0, T0, T1 + T0, T0, T0, T1 ) * translationmatrix(-eyePos) end @@ -152,46 +152,46 @@ function orthographicprojection(wh::Rect2, near::T, far::T) where T end function orthographicprojection( - ::Type{T}, wh::Rect2, near::Number, far::Number - ) where T + ::Type{T}, wh::Rect2, near::Number, far::Number +) where T orthographicprojection(wh, T(near), T(far)) end function orthographicprojection( - left::T, right::T, - bottom::T, top::T, - znear::T, zfar::T - ) where T - (right==left || bottom==top || znear==zfar) && return Mat{4,4,T}(I) + left::T, right::T, + bottom::T, top::T, + znear::T, zfar::T +) where T + (right == left || bottom == top || znear == zfar) && return Mat{4,4,T}(I) T0, T1, T2 = zero(T), one(T), T(2) Mat{4}( - T2/(right-left), T0, T0, T0, - T0, T2/(top-bottom), T0, T0, - T0, T0, -T2/(zfar-znear), T0, - -(right+left)/(right-left), -(top+bottom)/(top-bottom), -(zfar+znear)/(zfar-znear), T1 + T2 / (right - left), T0, T0, T0, + T0, T2 / (top - bottom), T0, T0, + T0, T0, -T2 / (zfar - znear), T0, + -(right + left) / (right - left), -(top + bottom) / (top - bottom), -(zfar + znear) / (zfar - znear), T1 ) end function orthographicprojection(::Type{T}, - left ::Number, right::Number, - bottom::Number, top ::Number, - znear ::Number, zfar ::Number - ) where T + left::Number, right::Number, + bottom::Number, top::Number, + znear::Number, zfar::Number +) where T orthographicprojection( - T(left), T(right), + T(left), T(right), T(bottom), T(top), - T(znear), T(zfar) + T(znear), T(zfar) ) end mutable struct Pivot{T} - origin ::Vec{3, T} - xaxis ::Vec{3, T} - yaxis ::Vec{3, T} - zaxis ::Vec{3, T} - rotation ::Quaternion - translation ::Vec{3, T} - scale ::Vec{3, T} + origin::Vec{3,T} + xaxis::Vec{3,T} + yaxis::Vec{3,T} + zaxis::Vec{3,T} + rotation::Quaternion + translation::Vec{3,T} + scale::Vec{3,T} end GeometryBasics.origin(p::Pivot) = p.origin @@ -201,7 +201,7 @@ rotationmatrix4(q::Quaternion{T}) where {T} = Mat4{T}(q) function transformationmatrix(p::Pivot) translationmatrix(p.origin) * #go to origin rotationmatrix4(p.rotation) * #apply rotation - translationmatrix(-p.origin)* # go back to origin + translationmatrix(-p.origin) * # go back to origin translationmatrix(p.translation) #apply translation end @@ -209,9 +209,9 @@ function transformationmatrix(translation, scale) T = eltype(translation) T0, T1 = zero(T), one(T) return Mat{4}( - scale[1],T0, T0, T0, - T0, scale[2],T0, T0, - T0, T0, scale[3],T0, + scale[1], T0, T0, T0, + T0, scale[2], T0, T0, + T0, T0, scale[3], T0, translation[1], translation[2], translation[3], T1 ) end @@ -219,11 +219,11 @@ end function transformationmatrix(translation, scale, rotation::Quaternion) trans_scale = transformationmatrix(translation, scale) rotation = Mat4f(rotation) - trans_scale*rotation + trans_scale * rotation end #Calculate rotation between two vectors -function rotation(u::Vec{3, T}, v::Vec{3, T}) where T +function rotation(u::Vec{3,T}, v::Vec{3,T}) where T # It is important that the inputs are of equal length when # calculating the half-way vector. u, v = normalize(u), normalize(v) @@ -231,14 +231,14 @@ function rotation(u::Vec{3, T}, v::Vec{3, T}) where T # in this case will be (0, 0, 0), which cannot be normalized. if (u == -v) # 180 degree rotation around any orthogonal vector - other = (abs(dot(u, Vec{3, T}(1,0,0))) < 1.0) ? Vec{3, T}(1,0,0) : Vec{3, T}(0,1,0) + other = (abs(dot(u, Vec{3,T}(1, 0, 0))) < 1.0) ? Vec{3,T}(1, 0, 0) : Vec{3,T}(0, 1, 0) return qrotation(normalize(cross(u, other)), T(180)) end - half = normalize(u+v) + half = normalize(u + v) return Quaternion(cross(u, half)..., dot(u, half)) end -function to_world(scene::Scene, point::T) where T <: StaticVector +function to_world(scene::Scene, point::T) where T<:StaticVector cam = scene.camera x = to_world( point, @@ -254,13 +254,13 @@ w_component(x::Point) = 1.0 w_component(x::Vec) = 0.0 function to_world( - p::StaticVector{N, T}, - prj_view_inv::Mat4, - cam_res::StaticVector - ) where {N, T} + p::StaticVector{N,T}, + prj_view_inv::Mat4, + cam_res::StaticVector +) where {N,T} VT = typeof(p) clip_space = ((VT(p) ./ VT(cam_res)) .* T(2)) .- T(1) - pix_space = Vec{4, T}( + pix_space = Vec{4,T}( clip_space[1], clip_space[2], T(0), w_component(p) @@ -270,12 +270,12 @@ function to_world( end function to_world( - p::Vec{N, T}, - prj_view_inv::Mat4, - cam_res::StaticVector - ) where {N, T} + p::Vec{N,T}, + prj_view_inv::Mat4, + cam_res::StaticVector +) where {N,T} to_world(Point(p), prj_view_inv, cam_res) .- - to_world(zeros(Point{N, T}), prj_view_inv, cam_res) + to_world(zeros(Point{N,T}), prj_view_inv, cam_res) end function project(scene::Scene, point::T) where T<:StaticVector @@ -291,7 +291,7 @@ function project(scene::Scene, point::T) where T<:StaticVector ) end -function project(matrix::Mat4f, p::T, dim4 = 1.0) where T <: VecTypes +function project(matrix::Mat4f, p::T, dim4 = 1.0) where T<:VecTypes p = to_ndim(Vec4f, to_ndim(Vec3f, p, 0.0), dim4) p = matrix * p to_ndim(T, p, 0.0) @@ -315,7 +315,7 @@ function transform(model::Mat4, x::T) where T end # project between different coordinate systems/spaces -function space_to_clip(cam::Camera, space::Symbol, projectionview::Bool=true) +function space_to_clip(cam::Camera, space::Symbol, projectionview::Bool = true) if is_data_space(space) return projectionview ? cam.projectionview[] : cam.projection[] elseif is_pixel_space(space) diff --git a/src/colorsampler.jl b/src/colorsampler.jl index 7bca6b4c84a..d0a1d5897c5 100644 --- a/src/colorsampler.jl +++ b/src/colorsampler.jl @@ -1,6 +1,6 @@ @enum Interpolation Linear Nearest -struct Scaling{F, R} +struct Scaling{F,R} # a function to scale a value by, e.g. log10, sqrt etc scaling_function::F # If nothing, no scaling applied! @@ -9,11 +9,11 @@ end Scaling() = Scaling(identity, nothing) -const NoScaling = Scaling{typeof(identity), Nothing} +const NoScaling = Scaling{typeof(identity),Nothing} -struct Sampler{N, V} <: AbstractArray{RGBAf, 1} +struct Sampler{N,V} <: AbstractArray{RGBAf,1} # the colors to sample from! - colors::AbstractArray{T, N} where T + colors::AbstractArray{T,N} where T # or an array of values, which are used to index into colors via interpolation! values::V # additional alpha that gets multiplied @@ -95,7 +95,7 @@ function Base.getindex(sampler::Sampler, i)::RGBAf return RGBAf(color(c), alpha(c) * sampler.alpha) end -function Base.getindex(sampler::Sampler{2, <: AbstractVector{Vec2f}}, i)::RGBAf +function Base.getindex(sampler::Sampler{2,<:AbstractVector{Vec2f}}, i)::RGBAf uv = sampler.values[i] colors = sampler.colors # indexing confirming to OpenGL uv indexing @@ -106,13 +106,13 @@ function Base.getindex(sampler::Sampler{2, <: AbstractVector{Vec2f}}, i)::RGBAf return RGBAf(color(c), alpha(c) * sampler.alpha) end -function sampler(cmap::Union{Symbol, String}, n::Int = 20; - scaling=Scaling(), alpha=1.0, interpolation=Linear) +function sampler(cmap::Union{Symbol,String}, n::Int = 20; + scaling = Scaling(), alpha = 1.0, interpolation = Linear) return sampler(cmap, LinRange(0, 1, n); scaling = scaling, alpha = alpha, interpolation = interpolation) end -function sampler(cmap::Union{Symbol, String}, values::AbstractVector{<: AbstractFloat}; - scaling=Scaling(), alpha=1.0, interpolation=Linear) +function sampler(cmap::Union{Symbol,String}, values::AbstractVector{<:AbstractFloat}; + scaling = Scaling(), alpha = 1.0, interpolation = Linear) cs = PlotUtils.get_colorscheme(cmap) @@ -121,25 +121,25 @@ function sampler(cmap::Union{Symbol, String}, values::AbstractVector{<: Abstract return Sampler(colors, values, alpha, interpolation, scaling) end -function sampler(cmap::Vector{<: Colorant}, values::AbstractVector{<: AbstractFloat}; - scaling=Scaling(), alpha=1.0, interpolation=Linear) +function sampler(cmap::Vector{<:Colorant}, values::AbstractVector{<:AbstractFloat}; + scaling = Scaling(), alpha = 1.0, interpolation = Linear) return Sampler(RGBAf.(cmap), values, alpha, interpolation, scaling) end function sampler(cmap::AbstractVector, values, crange; - alpha=1.0, interpolation=Linear) + alpha = 1.0, interpolation = Linear) return Sampler(to_color.(cmap), values, alpha, interpolation, Scaling(identity, crange)) end # uv texture sampler -function sampler(cmap::Matrix{<: Colorant}, uv::AbstractVector{Vec2f}; - alpha=1.0, interpolation=Linear) +function sampler(cmap::Matrix{<:Colorant}, uv::AbstractVector{Vec2f}; + alpha = 1.0, interpolation = Linear) return Sampler(cmap, uv, alpha, interpolation, Scaling()) end function numbers_to_colors(numbers::AbstractArray{<:Number}, primitive) colormap = get_attribute(primitive, :colormap)::Vector{RGBAf} - _colorrange = get_attribute(primitive, :colorrange)::Union{Nothing, Vec2f} + _colorrange = get_attribute(primitive, :colorrange)::Union{Nothing,Vec2f} if isnothing(_colorrange) # TODO, plot primitive should always expand automatic values colorrange = Vec2f(extrema_nan(numbers)) @@ -149,7 +149,7 @@ function numbers_to_colors(numbers::AbstractArray{<:Number}, primitive) lowclip = get_attribute(primitive, :lowclip) highclip = get_attribute(primitive, :highclip) - nan_color = get_attribute(primitive, :nan_color, RGBAf(0,0,0,0)) + nan_color = get_attribute(primitive, :nan_color, RGBAf(0, 0, 0, 0)) cmin, cmax = colorrange::Vec2f diff --git a/src/conversions.jl b/src/conversions.jl index 215edf871bb..cdd651c1529 100644 --- a/src/conversions.jl +++ b/src/conversions.jl @@ -1,7 +1,7 @@ ################################################################################ # Type Conversions # ################################################################################ -const RangeLike = Union{AbstractRange, AbstractVector, ClosedInterval} +const RangeLike = Union{AbstractRange,AbstractVector,ClosedInterval} # if no plot type based conversion is defined, we try using a trait function convert_arguments(T::PlotFunc, args...; kw...) @@ -68,13 +68,13 @@ end convert_single_argument(x) = x # replace missings with NaNs -function convert_single_argument(a::AbstractArray{<:Union{Missing, <:Real}}) +function convert_single_argument(a::AbstractArray{<:Union{Missing,<:Real}}) [ismissing(x) ? NaN32 : convert(Float32, x) for x in a] end # same for points -function convert_single_argument(a::AbstractArray{<:Union{Missing, <:Point{N}}}) where N - [ismissing(x) ? Point{N, Float32}(NaN32) : Point{N, Float32}(x) for x in a] +function convert_single_argument(a::AbstractArray{<:Union{Missing,<:Point{N}}}) where N + [ismissing(x) ? Point{N,Float32}(NaN32) : Point{N,Float32}(x) for x in a] end ################################################################################ @@ -92,15 +92,15 @@ function convert_arguments(::PointBased, x::Real, y::Real, z::Real) ([Point3f(x, y, z)],) end -function convert_arguments(::PointBased, position::VecTypes{N, <: Number}) where N - ([convert(Point{N, Float32}, position)],) +function convert_arguments(::PointBased, position::VecTypes{N,<:Number}) where N + ([convert(Point{N,Float32}, position)],) end -function convert_arguments(::PointBased, positions::AbstractVector{<: VecTypes{N, <: Number}}) where N - (elconvert(Point{N, Float32}, positions),) +function convert_arguments(::PointBased, positions::AbstractVector{<:VecTypes{N,<:Number}}) where N + (elconvert(Point{N,Float32}, positions),) end -function convert_arguments(::PointBased, positions::SubArray{<: VecTypes, 1}) +function convert_arguments(::PointBased, positions::SubArray{<:VecTypes,1}) # TODO figure out a good subarray solution (positions,) end @@ -129,7 +129,7 @@ Takes an input GeometryPrimitive `x` and decomposes it to points. """ convert_arguments(p::PointBased, x::GeometryPrimitive) = convert_arguments(p, decompose(Point, x)) -function convert_arguments(::PointBased, pos::AbstractMatrix{<: Number}) +function convert_arguments(::PointBased, pos::AbstractMatrix{<:Number}) (to_vertices(pos),) end @@ -175,7 +175,7 @@ function convert_arguments(P::PointBased, mesh::AbstractMesh) return convert_arguments(P, decompose(Point3f, mesh)) end -function convert_arguments(PB::PointBased, linesegments::FaceView{<:Line, P}) where {P<:AbstractPoint} +function convert_arguments(PB::PointBased, linesegments::FaceView{<:Line,P}) where {P<:AbstractPoint} # TODO FaceView should be natively supported by backends! return convert_arguments(PB, collect(reinterpret(P, linesegments))) end @@ -184,13 +184,13 @@ function convert_arguments(P::PointBased, rect::Rect3) return (decompose(Point3f, rect),) end -function convert_arguments(P::Type{<: LineSegments}, rect::Rect3) +function convert_arguments(P::Type{<:LineSegments}, rect::Rect3) f = decompose(LineFace{Int}, rect) p = connect(decompose(Point3f, rect), f) return convert_arguments(P, p) end -function convert_arguments(::Type{<: Lines}, rect::Rect3) +function convert_arguments(::Type{<:Lines}, rect::Rect3) points = unique(decompose(Point3f, rect)) push!(points, Point3f(NaN)) # use to seperate linesegments return (points[[1, 2, 3, 4, 1, 5, 6, 2, 9, 6, 8, 3, 9, 5, 7, 4, 9, 7, 8]],) @@ -210,7 +210,7 @@ end Takes an input `Array{LineString}` or a `MultiLineString` and decomposes it to points. """ -function convert_arguments(PB::PointBased, linestring::Union{Array{<:LineString}, MultiLineString}) +function convert_arguments(PB::PointBased, linestring::Union{Array{<:LineString},MultiLineString}) arr = copy(convert_arguments(PB, linestring[1])[1]) for ls in 2:length(linestring) push!(arr, Point2f(NaN)) @@ -246,7 +246,7 @@ end Takes an input `Array{Polygon}` or a `MultiPolygon` and decomposes it to points. """ -function convert_arguments(PB::PointBased, mp::Union{Array{<:Polygon}, MultiPolygon}) +function convert_arguments(PB::PointBased, mp::Union{Array{<:Polygon},MultiPolygon}) arr = copy(convert_arguments(PB, mp[1])[1]) for p in 2:length(mp) push!(arr, Point2f(NaN)) @@ -268,9 +268,9 @@ function edges(v::AbstractVector) # Equivalent to # mids = 0.5 .* (v[1:end-1] .+ v[2:end]) # borders = [2v[1] - mids[1]; mids; 2v[end] - mids[end]] - borders = [0.5 * (v[max(1, i)] + v[min(end, i+1)]) for i in 0:length(v)] + borders = [0.5 * (v[max(1, i)] + v[min(end, i + 1)]) for i in 0:length(v)] borders[1] = 2borders[1] - borders[2] - borders[end] = 2borders[end] - borders[end-1] + borders[end] = 2borders[end] - borders[end - 1] return borders end end @@ -292,10 +292,10 @@ whether they represent edges or centers of the heatmap bins. If they are centers, convert to edges. Convert eltypes to `Float32` and return outputs as a `Tuple`. """ -function convert_arguments(SL::SurfaceLike, x::AbstractVecOrMat{<: Number}, y::AbstractVecOrMat{<: Number}, z::AbstractMatrix{<: Union{Number, Colorant}}) +function convert_arguments(SL::SurfaceLike, x::AbstractVecOrMat{<:Number}, y::AbstractVecOrMat{<:Number}, z::AbstractMatrix{<:Union{Number,Colorant}}) return map(el32convert, adjust_axes(SL, x, y, z)) end -function convert_arguments(SL::SurfaceLike, x::AbstractVecOrMat{<: Number}, y::AbstractVecOrMat{<: Number}, z::AbstractMatrix{<:Number}) +function convert_arguments(SL::SurfaceLike, x::AbstractVecOrMat{<:Number}, y::AbstractVecOrMat{<:Number}, z::AbstractMatrix{<:Number}) return map(el32convert, adjust_axes(SL, x, y, z)) end @@ -363,7 +363,7 @@ Takes vectors `x` and `y` and the function `f`, and applies `f` on the grid that This is equivalent to `f.(x, y')`. `P` is the plot Type (it is optional). """ -function convert_arguments(sl::SurfaceLike, x::AbstractVector{T1}, y::AbstractVector{T2}, f::Function) where {T1, T2} +function convert_arguments(sl::SurfaceLike, x::AbstractVector{T1}, y::AbstractVector{T2}, f::Function) where {T1,T2} if !applicable(f, x[1], y[1]) error("You need to pass a function with signature f(x::$T1, y::$T2). Found: $f") end @@ -385,12 +385,12 @@ and stores the `ClosedInterval` to `n`, `m` and `k`, plus the original array in `P` is the plot Type (it is optional). """ -function convert_arguments(::VolumeLike, data::AbstractArray{T, 3}) where T +function convert_arguments(::VolumeLike, data::AbstractArray{T,3}) where T n, m, k = Float32.(size(data)) return (0f0 .. n, 0f0 .. m, 0f0 .. k, el32convert(data)) end -function convert_arguments(::VolumeLike, x::RangeLike, y::RangeLike, z::RangeLike, data::AbstractArray{T, 3}) where T +function convert_arguments(::VolumeLike, x::RangeLike, y::RangeLike, z::RangeLike, data::AbstractArray{T,3}) where T return (x, y, z, el32convert(data)) end """ @@ -400,7 +400,7 @@ Takes 3 `AbstractVector` `x`, `y`, and `z` and the `AbstractMatrix` `i`, and put `P` is the plot Type (it is optional). """ -function convert_arguments(::VolumeLike, x::AbstractVector, y::AbstractVector, z::AbstractVector, i::AbstractArray{T, 3}) where T +function convert_arguments(::VolumeLike, x::AbstractVector, y::AbstractVector, z::AbstractVector, i::AbstractArray{T,3}) where T (x, y, z, el32convert(i)) end @@ -419,7 +419,7 @@ function convert_arguments(::VolumeLike, x::AbstractVector, y::AbstractVector, z end _x, _y, _z = ntuple(Val(3)) do i A = (x, y, z)[i] - reshape(A, ntuple(j-> j != i ? 1 : length(A), Val(3))) + reshape(A, ntuple(j -> j != i ? 1 : length(A), Val(3))) end return (x, y, z, el32convert.(f.(_x, _y, _z))) end @@ -428,7 +428,7 @@ end # <:Lines # ################################################################################ -function convert_arguments(::Type{<: Lines}, x::Rect2) +function convert_arguments(::Type{<:Lines}, x::Rect2) # TODO fix the order of decompose points = decompose(Point2f, x) return (points[[1, 2, 4, 3, 1]],) @@ -442,11 +442,11 @@ end Accepts a Vector of Pair of Points (e.g. `[Point(0, 0) => Point(1, 1), ...]`) to encode e.g. linesegments or directions. """ -function convert_arguments(::Type{<: LineSegments}, positions::AbstractVector{E}) where E <: Union{Pair{A, A}, Tuple{A, A}} where A <: VecTypes{N, T} where {N, T} - (elconvert(Point{N, Float32}, reinterpret(Point{N, T}, positions)),) +function convert_arguments(::Type{<:LineSegments}, positions::AbstractVector{E}) where E<:Union{Pair{A,A},Tuple{A,A}} where A<:VecTypes{N,T} where {N,T} + (elconvert(Point{N,Float32}, reinterpret(Point{N,T}, positions)),) end -function convert_arguments(::Type{<: LineSegments}, x::Rect2) +function convert_arguments(::Type{<:LineSegments}, x::Rect2) # TODO fix the order of decompose points = decompose(Point2f, x) return (points[[1, 2, 2, 4, 4, 3, 3, 1]],) @@ -475,9 +475,9 @@ Takes real vectors x, y, z and constructs a mesh out of those, under the assumpt every 3 points form a triangle. """ function convert_arguments( - T::Type{<:Mesh}, - x::RealVector, y::RealVector, z::RealVector - ) + T::Type{<:Mesh}, + x::RealVector, y::RealVector, z::RealVector +) convert_arguments(T, Point3f.(x, y, z)) end """ @@ -487,10 +487,10 @@ Takes an input mesh and a vector `xyz` representing the vertices of the mesh, an creates indices under the assumption, that each triplet in `xyz` forms a triangle. """ function convert_arguments( - MT::Type{<:Mesh}, - xyz::AbstractVector - ) - faces = connect(UInt32.(0:length(xyz)-1), GLTriangleFace) + MT::Type{<:Mesh}, + xyz::AbstractVector +) + faces = connect(UInt32.(0:(length(xyz) - 1)), GLTriangleFace) # TODO support faceview natively return convert_arguments(MT, xyz, collect(faces)) end @@ -504,20 +504,20 @@ function convert_arguments(::Type{<:Mesh}, mesh::GeometryBasics.Mesh{N}) where { mesh = GeometryBasics.pointmeta(mesh, decompose(Vec3f, n)) end end - return (GeometryBasics.mesh(mesh, pointtype=Point{N, Float32}, facetype=GLTriangleFace),) + return (GeometryBasics.mesh(mesh, pointtype = Point{N,Float32}, facetype = GLTriangleFace),) end function convert_arguments( - MT::Type{<:Mesh}, - meshes::AbstractVector{<: Union{AbstractMesh, AbstractPolygon}} - ) + MT::Type{<:Mesh}, + meshes::AbstractVector{<:Union{AbstractMesh,AbstractPolygon}} +) return (meshes,) end function convert_arguments( - MT::Type{<:Mesh}, - xyz::Union{AbstractPolygon, AbstractVector{<: AbstractPoint{2}}} - ) + MT::Type{<:Mesh}, + xyz::Union{AbstractPolygon,AbstractVector{<:AbstractPoint{2}}} +) return convert_arguments(MT, triangle_mesh(xyz)) end @@ -534,10 +534,10 @@ Takes real vectors x, y, z and constructs a triangle mesh out of those, using th faces in `indices`, which can be integers (every 3 -> one triangle), or GeometryBasics.NgonFace{N, <: Integer}. """ function convert_arguments( - T::Type{<: Mesh}, - x::RealVector, y::RealVector, z::RealVector, - indices::AbstractVector - ) + T::Type{<:Mesh}, + x::RealVector, y::RealVector, z::RealVector, + indices::AbstractVector +) return convert_arguments(T, Point3f.(x, y, z), indices) end @@ -549,10 +549,10 @@ See [`to_vertices`](@ref) and [`to_triangles`](@ref) for more information about accepted types. """ function convert_arguments( - ::Type{<:Mesh}, - vertices::AbstractArray, - indices::AbstractArray - ) + ::Type{<:Mesh}, + vertices::AbstractArray, + indices::AbstractArray +) m = normal_mesh(to_vertices(vertices), to_triangles(indices)) (m,) end @@ -596,12 +596,12 @@ end # OffsetArrays conversions function convert_arguments(sl::SurfaceLike, wm::OffsetArray) - x1, y1 = wm.offsets .+ 1 - nx, ny = size(wm) - x = range(x1, length = nx) - y = range(y1, length = ny) - v = parent(wm) - return convert_arguments(sl, x, y, v) + x1, y1 = wm.offsets .+ 1 + nx, ny = size(wm) + x = range(x1, length = nx) + y = range(y1, length = ny) + v = parent(wm) + return convert_arguments(sl, x, y, v) end ################################################################################ @@ -613,11 +613,11 @@ to_linspace(interval, N) = range(minimum(interval), stop = maximum(interval), le """ Converts the elemen array type to `T1` without making a copy if the element type matches """ -elconvert(::Type{T1}, x::AbstractArray{T2, N}) where {T1, T2, N} = convert(AbstractArray{T1, N}, x) +elconvert(::Type{T1}, x::AbstractArray{T2,N}) where {T1,T2,N} = convert(AbstractArray{T1,N}, x) float32type(x::Type) = Float32 -float32type(::Type{<: RGB}) = RGB{Float32} -float32type(::Type{<: RGBA}) = RGBA{Float32} -float32type(::Type{<: Colorant}) = RGBA{Float32} +float32type(::Type{<:RGB}) = RGB{Float32} +float32type(::Type{<:RGBA}) = RGBA{Float32} +float32type(::Type{<:Colorant}) = RGBA{Float32} float32type(x::AbstractArray{T}) where T = float32type(T) float32type(x::T) where T = float32type(T) el32convert(x::AbstractArray) = elconvert(float32type(x), x) @@ -625,10 +625,10 @@ el32convert(x::AbstractArray{Float32}) = x el32convert(x::Observable) = lift(el32convert, x) el32convert(x) = convert(float32type(x), x) -function el32convert(x::AbstractArray{T, N}) where {T<:Union{Missing, <: Number}, N} +function el32convert(x::AbstractArray{T,N}) where {T<:Union{Missing,<:Number},N} return map(x) do elem return (ismissing(elem) ? NaN32 : convert(Float32, elem))::Float32 - end::Array{Float32, N} + end::Array{Float32,N} end """ to_triangles(indices) @@ -653,10 +653,10 @@ function to_triangles(faces::AbstractVector{TriangleFace{T}}) where T elconvert(GLTriangleFace, faces) end -function to_triangles(faces::AbstractMatrix{T}) where T <: Integer +function to_triangles(faces::AbstractMatrix{T}) where T<:Integer @assert size(faces, 2) == 3 return broadcast(1:size(faces, 1), 3) do fidx, n - GLTriangleFace(ntuple(i-> faces[fidx, i], n)) + GLTriangleFace(ntuple(i -> faces[fidx, i], n)) end end @@ -675,16 +675,16 @@ Converts a representation of vertices `v` to its canonical representation as a - if `v` has 2 or 3 rows, it will treat each column as a vertex, - otherwise if `v` has 2 or 3 columns, it will treat each row as a vertex. """ -function to_vertices(verts::AbstractVector{<: VecTypes{3, T}}) where T +function to_vertices(verts::AbstractVector{<:VecTypes{3,T}}) where T vert3f0 = T != Float32 ? Point3f.(verts) : verts return reinterpret(Point3f, vert3f0) end -function to_vertices(verts::AbstractVector{<: VecTypes}) +function to_vertices(verts::AbstractVector{<:VecTypes}) to_vertices(to_ndim.(Point3f, verts, 0.0)) end -function to_vertices(verts::AbstractMatrix{<: Number}) +function to_vertices(verts::AbstractMatrix{<:Number}) if size(verts, 1) in (2, 3) to_vertices(verts, Val(1)) elseif size(verts, 2) in (2, 3) @@ -694,23 +694,23 @@ function to_vertices(verts::AbstractMatrix{<: Number}) end end -function to_vertices(verts::AbstractMatrix{T}, ::Val{1}) where T <: Number +function to_vertices(verts::AbstractMatrix{T}, ::Val{1}) where T<:Number N = size(verts, 1) if T == Float32 && N == 3 - reinterpret(Point{N, T}, elconvert(T, vec(verts))) + reinterpret(Point{N,T}, elconvert(T, vec(verts))) else let N = Val(N), lverts = verts broadcast(1:size(verts, 2), N) do vidx, n - to_ndim(Point3f, ntuple(i-> lverts[i, vidx], n), 0.0) + to_ndim(Point3f, ntuple(i -> lverts[i, vidx], n), 0.0) end end end end -function to_vertices(verts::AbstractMatrix{T}, ::Val{2}) where T <: Number +function to_vertices(verts::AbstractMatrix{T}, ::Val{2}) where T<:Number let N = Val(size(verts, 2)), lverts = verts broadcast(1:size(verts, 1), N) do vidx, n - to_ndim(Point3f, ntuple(i-> lverts[vidx, i], n), 0.0) + to_ndim(Point3f, ntuple(i -> lverts[vidx, i], n), 0.0) end end end @@ -748,11 +748,11 @@ convert_attribute(p::Nothing, ::key"lowclip") = p convert_attribute(p, ::key"nan_color") = to_color(p) struct Palette - colors::Vector{RGBA{Float32}} - i::Ref{Int} - Palette(colors) = new(to_color.(colors), zero(Int)) + colors::Vector{RGBA{Float32}} + i::Ref{Int} + Palette(colors) = new(to_color.(colors), zero(Int)) end -Palette(name::Union{String, Symbol}, n = 8) = Palette(categorical_colors(name, n)) +Palette(name::Union{String,Symbol}, n = 8) = Palette(categorical_colors(name, n)) function to_color(p::Palette) N = length(p.colors) p.i[] = p.i[] == N ? 1 : p.i[] + 1 @@ -765,9 +765,9 @@ to_color(c::Colorant) = convert(RGBA{Float32}, c) to_color(c::Symbol) = to_color(string(c)) to_color(c::String) = parse(RGBA{Float32}, c) to_color(c::AbstractArray) = to_color.(c) -to_color(c::AbstractArray{<: Colorant, N}) where N = convert(Array{RGBAf, N}, c) +to_color(c::AbstractArray{<:Colorant,N}) where N = convert(Array{RGBAf,N}, c) to_color(p::AbstractPattern) = p -function to_color(c::Tuple{<: Any, <: Number}) +function to_color(c::Tuple{<:Any,<:Number}) col = to_color(c[1]) return RGBAf(Colors.color(col), alpha(col) * c[2]) end @@ -782,7 +782,7 @@ convert_attribute(c, ::key"markersize", ::key"scatter") = to_2d_scale(c) convert_attribute(c, ::key"markersize", ::key"meshscatter") = to_3d_scale(c) to_2d_scale(x::Number) = Vec2f(x) to_2d_scale(x::VecTypes) = to_ndim(Vec2f, x, 1) -to_2d_scale(x::Tuple{<:Number, <:Number}) = to_ndim(Vec2f, x, 1) +to_2d_scale(x::Tuple{<:Number,<:Number}) = to_ndim(Vec2f, x, 1) to_2d_scale(x::AbstractVector) = to_2d_scale.(x) to_3d_scale(x::Number) = Vec3f(x) @@ -858,7 +858,7 @@ function line_diff_pattern(ls_str::AbstractString, gaps = :normal) pattern = Float64[] for i in 1:length(ls_str) curr_char = ls_str[i] - next_char = i == lastindex(ls_str) ? ls_str[firstindex(ls_str)] : ls_str[i+1] + next_char = i == lastindex(ls_str) ? ls_str[firstindex(ls_str)] : ls_str[i + 1] # push dash or dot if curr_char == '-' push!(pattern, dash) @@ -884,36 +884,36 @@ function check_line_pattern(ls_str) end function convert_gaps(gaps) - error_msg = "You provided the gaps modifier $gaps when specifying the linestyle. The modifier must be `∈ ([:normal, :dense, :loose])`, a real number or a collection of two real numbers." - if gaps isa Symbol - gaps in [:normal, :dense, :loose] || throw(ArgumentError(error_msg)) - dot_gaps = (normal = 2, dense = 1, loose = 4) - dash_gaps = (normal = 3, dense = 2, loose = 6) - - dot_gap = getproperty(dot_gaps, gaps) - dash_gap = getproperty(dash_gaps, gaps) - elseif gaps isa Real - dot_gap = gaps - dash_gap = gaps - elseif length(gaps) == 2 && eltype(gaps) <: Real - dot_gap, dash_gap = gaps - else - throw(ArgumentError(error_msg)) - end - (dot_gap = dot_gap, dash_gap = dash_gap) -end - -convert_attribute(c::Tuple{<: Number, <: Number}, ::key"position") = Point2f(c[1], c[2]) -convert_attribute(c::Tuple{<: Number, <: Number, <: Number}, ::key"position") = Point3f(c) -convert_attribute(c::VecTypes{N}, ::key"position") where N = Point{N, Float32}(c) + error_msg = "You provided the gaps modifier $gaps when specifying the linestyle. The modifier must be `∈ ([:normal, :dense, :loose])`, a real number or a collection of two real numbers." + if gaps isa Symbol + gaps in [:normal, :dense, :loose] || throw(ArgumentError(error_msg)) + dot_gaps = (normal = 2, dense = 1, loose = 4) + dash_gaps = (normal = 3, dense = 2, loose = 6) + + dot_gap = getproperty(dot_gaps, gaps) + dash_gap = getproperty(dash_gaps, gaps) + elseif gaps isa Real + dot_gap = gaps + dash_gap = gaps + elseif length(gaps) == 2 && eltype(gaps) <: Real + dot_gap, dash_gap = gaps + else + throw(ArgumentError(error_msg)) + end + (dot_gap = dot_gap, dash_gap = dash_gap) +end + +convert_attribute(c::Tuple{<:Number,<:Number}, ::key"position") = Point2f(c[1], c[2]) +convert_attribute(c::Tuple{<:Number,<:Number,<:Number}, ::key"position") = Point3f(c) +convert_attribute(c::VecTypes{N}, ::key"position") where N = Point{N,Float32}(c) """ Text align, e.g.: """ -to_align(x::Tuple{Symbol, Symbol}) = Vec2f(alignment2num.(x)) +to_align(x::Tuple{Symbol,Symbol}) = Vec2f(alignment2num.(x)) to_align(x::Vec2f) = x -const FONT_CACHE = Dict{String, NativeFont}() +const FONT_CACHE = Dict{String,NativeFont}() """ font conversion @@ -936,7 +936,7 @@ function to_font(x::String) end fontpath = assetpath("fonts") - font = FreeTypeAbstraction.findfont(str; additional_fonts=fontpath) + font = FreeTypeAbstraction.findfont(str; additional_fonts = fontpath) if font === nothing @warn("Could not find font $str, using TeX Gyre Heros Makie") if "tex gyre heros makie" == lowercase(str) @@ -987,17 +987,17 @@ function to_rotation(s::VecTypes{N}) where N end end -to_rotation(s::Tuple{VecTypes, Number}) = qrotation(to_ndim(Vec3f, s[1], 0.0), s[2]) +to_rotation(s::Tuple{VecTypes,Number}) = qrotation(to_ndim(Vec3f, s[1], 0.0), s[2]) to_rotation(angle::Number) = qrotation(Vec3f(0, 0, 1), angle) to_rotation(r::AbstractVector) = to_rotation.(r) -to_rotation(r::AbstractVector{<: Quaternionf}) = r +to_rotation(r::AbstractVector{<:Quaternionf}) = r convert_attribute(x, ::key"colorrange") = to_colorrange(x) to_colorrange(x) = isnothing(x) ? nothing : Vec2f(x) convert_attribute(x, ::key"fontsize") = to_fontsize(x) to_fontsize(x::Number) = Float32(x) -to_fontsize(x::AbstractVector{T}) where T <: Number = el32convert(x) +to_fontsize(x::AbstractVector{T}) where T<:Number = el32convert(x) convert_attribute(x, ::key"linewidth") = to_linewidth(x) to_linewidth(x) = Float32(x) @@ -1040,7 +1040,7 @@ to_colormap(cm, categories::Integer) = error("`to_colormap(cm, categories)` is d Creates categorical colors and tries to match `categories`. Will error if color scheme doesn't contain enough categories. Will drop the n last colors, if request less colors than contained in scheme. """ -function categorical_colors(cols::AbstractVector{<: Colorant}, categories::Integer) +function categorical_colors(cols::AbstractVector{<:Colorant}, categories::Integer) if length(cols) < categories error("Not enough colors for number of categories. Categories: $(categories), colors: $(length(cols))") end @@ -1051,7 +1051,7 @@ function categorical_colors(cols::AbstractVector, categories::Integer) return categorical_colors(to_color.(cols), categories) end -function categorical_colors(cs::Union{String, Symbol}, categories::Integer) +function categorical_colors(cs::Union{String,Symbol}, categories::Integer) cs_string = string(cs) if cs_string in all_gradient_names if haskey(ColorBrewer.colorSchemes, cs_string) @@ -1088,9 +1088,9 @@ to_colormap(cs::ColorScheme) = to_colormap(cs.colors) An `AbstractVector{T}` with any object that [`to_color`](@ref) accepts. """ to_colormap(cm::AbstractVector)::Vector{RGBAf} = map(to_color, cm) -to_colormap(cm::AbstractVector{<: Colorant}) = convert(Vector{RGBAf}, cm) +to_colormap(cm::AbstractVector{<:Colorant}) = convert(Vector{RGBAf}, cm) -function to_colormap(cs::Tuple{<: Union{Reverse, Symbol, AbstractString}, Real})::Vector{RGBAf} +function to_colormap(cs::Tuple{<:Union{Reverse,Symbol,AbstractString},Real})::Vector{RGBAf} cmap = to_colormap(cs[1]) return RGBAf.(color.(cmap), alpha.(cmap) .* cs[2]) # We need to rework this to conform to the backend interface. end @@ -1101,7 +1101,7 @@ end A Symbol/String naming the gradient. For more on what names are available please see: `available_gradients()`. For now, we support gradients from `PlotUtils` natively. """ -function to_colormap(cs::Union{String, Symbol})::Vector{RGBAf} +function to_colormap(cs::Union{String,Symbol})::Vector{RGBAf} cs_string = string(cs) if cs_string in all_gradient_names if cs_string in colorbrewer_8color_names # special handling for 8 color only @@ -1149,7 +1149,7 @@ end """ Symbol/String: iso, absorption, mip, absorptionrgba, indexedabsorption """ -function convert_attribute(value::Union{Symbol, String}, k::key"algorithm") +function convert_attribute(value::Union{Symbol,String}, k::key"algorithm") vals = Dict( :iso => IsoValue, :absorption => Absorption, @@ -1159,11 +1159,11 @@ function convert_attribute(value::Union{Symbol, String}, k::key"algorithm") :additive => AdditiveRGBA, ) convert_attribute(get(vals, Symbol(value)) do - error("$value is not a valid volume algorithm. It must be one of $(keys(vals))") - end, k) + error("$value is not a valid volume algorithm. It must be one of $(keys(vals))") + end, k) end -const DEFAULT_MARKER_MAP = Dict{Symbol, BezierPath}() +const DEFAULT_MARKER_MAP = Dict{Symbol,BezierPath}() function default_marker_map() # The bezier markers should not look out of place when used together with text @@ -1179,20 +1179,20 @@ function default_marker_map() if isempty(DEFAULT_MARKER_MAP) size_factor = 0.75 DEFAULT_MARKER_MAP[:rect] = scale(BezierSquare, size_factor) - DEFAULT_MARKER_MAP[:diamond] = scale(rotate(BezierSquare, pi/4), size_factor) - DEFAULT_MARKER_MAP[:hexagon] = scale(bezier_ngon(6, 0.5, pi/2), size_factor) + DEFAULT_MARKER_MAP[:diamond] = scale(rotate(BezierSquare, pi / 4), size_factor) + DEFAULT_MARKER_MAP[:hexagon] = scale(bezier_ngon(6, 0.5, pi / 2), size_factor) DEFAULT_MARKER_MAP[:cross] = scale(BezierCross, size_factor) DEFAULT_MARKER_MAP[:xcross] = scale(BezierX, size_factor) DEFAULT_MARKER_MAP[:utriangle] = scale(BezierUTriangle, size_factor) DEFAULT_MARKER_MAP[:dtriangle] = scale(BezierDTriangle, size_factor) DEFAULT_MARKER_MAP[:ltriangle] = scale(BezierLTriangle, size_factor) DEFAULT_MARKER_MAP[:rtriangle] = scale(BezierRTriangle, size_factor) - DEFAULT_MARKER_MAP[:pentagon] = scale(bezier_ngon(5, 0.5, pi/2), size_factor) - DEFAULT_MARKER_MAP[:octagon] = scale(bezier_ngon(8, 0.5, pi/2), size_factor) - DEFAULT_MARKER_MAP[:star4] = scale(bezier_star(4, 0.25, 0.6, pi/2), size_factor) - DEFAULT_MARKER_MAP[:star5] = scale(bezier_star(5, 0.28, 0.6, pi/2), size_factor) - DEFAULT_MARKER_MAP[:star6] = scale(bezier_star(6, 0.30, 0.6, pi/2), size_factor) - DEFAULT_MARKER_MAP[:star8] = scale(bezier_star(8, 0.33, 0.6, pi/2), size_factor) + DEFAULT_MARKER_MAP[:pentagon] = scale(bezier_ngon(5, 0.5, pi / 2), size_factor) + DEFAULT_MARKER_MAP[:octagon] = scale(bezier_ngon(8, 0.5, pi / 2), size_factor) + DEFAULT_MARKER_MAP[:star4] = scale(bezier_star(4, 0.25, 0.6, pi / 2), size_factor) + DEFAULT_MARKER_MAP[:star5] = scale(bezier_star(5, 0.28, 0.6, pi / 2), size_factor) + DEFAULT_MARKER_MAP[:star6] = scale(bezier_star(6, 0.30, 0.6, pi / 2), size_factor) + DEFAULT_MARKER_MAP[:star8] = scale(bezier_star(8, 0.33, 0.6, pi / 2), size_factor) DEFAULT_MARKER_MAP[:vline] = scale(scale(BezierSquare, (0.2, 1.0)), size_factor) DEFAULT_MARKER_MAP[:hline] = scale(scale(BezierSquare, (1.0, 0.2)), size_factor) DEFAULT_MARKER_MAP[:+] = scale(BezierCross, size_factor) @@ -1236,8 +1236,8 @@ to_spritemarker(marker::AbstractVector) = map(to_spritemarker, marker) to_spritemarker(marker::AbstractVector{Char}) = marker # Don't dispatch to the above! to_spritemarker(x::FastPixel) = x to_spritemarker(x::Circle) = x -to_spritemarker(::Type{<: Circle}) = Circle -to_spritemarker(::Type{<: Rect}) = Rect +to_spritemarker(::Type{<:Circle}) = Circle +to_spritemarker(::Type{<:Rect}) = Rect to_spritemarker(x::Rect) = x to_spritemarker(b::BezierPath) = b to_spritemarker(b::Polygon) = BezierPath(b) @@ -1257,12 +1257,12 @@ to_spritemarker(marker::Char) = marker """ Matrix of AbstractFloat will be interpreted as a distancefield (negative numbers outside shape, positive inside) """ -to_spritemarker(marker::Matrix{<: AbstractFloat}) = el32convert(marker) +to_spritemarker(marker::Matrix{<:AbstractFloat}) = el32convert(marker) """ Any AbstractMatrix{<: Colorant} or other image type """ -to_spritemarker(marker::AbstractMatrix{<: Colorant}) = marker +to_spritemarker(marker::AbstractMatrix{<:Colorant}) = marker """ A `Symbol` - Available options can be printed with `available_marker_symbols()` diff --git a/src/display.jl b/src/display.jl index 6ba313ee9c0..220a0b8da9f 100644 --- a/src/display.jl +++ b/src/display.jl @@ -7,10 +7,10 @@ function backend_show end """ Current backend """ -const CURRENT_BACKEND = Ref{Union{Missing, Module}}(missing) +const CURRENT_BACKEND = Ref{Union{Missing,Module}}(missing) current_backend() = CURRENT_BACKEND[] -function set_active_backend!(backend::Union{Missing, Module}) +function set_active_backend!(backend::Union{Missing,Module}) CURRENT_BACKEND[] = backend return end @@ -38,7 +38,7 @@ function push_screen!(scene::Scene, screen::MakieScreen) # Now we push the screen :) push!(scene.current_screens, screen) deregister = nothing - deregister = on(events(scene).window_open, priority=typemax(Int)) do is_open + deregister = on(events(scene).window_open, priority = typemax(Int)) do is_open # when screen closes, it should set the scene isopen event to false # so that's when we can remove the screen if !is_open @@ -59,7 +59,7 @@ Removes screen from scene and cleans up screen function delete_screen!(scene::Scene, screen::MakieScreen) delete!(screen, scene) empty!(screen) - filter!(x-> x !== screen, scene.current_screens) + filter!(x -> x !== screen, scene.current_screens) return end @@ -103,7 +103,7 @@ Only case Makie always shows the plot inside the plotpane is when using VSCode e If you want to always force inlining the plot into the plotpane, set `inline!(true)` (E.g. when run in the VSCode REPL). In other cases `inline!(true/false)` won't do anything. """ -function inline!(inline=true) +function inline!(inline = true) ALWAYS_INLINE_PLOTS[] = inline end @@ -115,7 +115,7 @@ Displays the figurelike in a window or the browser, depending on the backend. The parameters for `screen_config` are backend dependend, see `?Backend.Screen` or `Base.doc(Backend.Screen)` for applicable options. """ -function Base.display(figlike::FigureLike; backend=current_backend(), update=true, screen_config...) +function Base.display(figlike::FigureLike; backend = current_backend(), update = true, screen_config...) if ismissing(backend) error(""" No backend available! @@ -142,7 +142,7 @@ is_displayed(screen::MakieScreen, scene::Scene) = screen in scene.current_screen # Backends overload display(::Backend.Screen, scene::Scene), while Makie overloads the below, # so that they don't need to worry # about stuff like `update_state_before_display!` -function Base.display(screen::MakieScreen, figlike::FigureLike; update=true, display_attributes...) +function Base.display(screen::MakieScreen, figlike::FigureLike; update = true, display_attributes...) scene = get_scene(figlike) update && update_state_before_display!(figlike) display(screen, get_scene(figlike); display_attributes...) @@ -226,18 +226,18 @@ Save a `Scene` with the specified filename and format. - `px_per_unit`: The size of one scene unit in `px` when exporting to a bitmap format. This provides a mechanism to export the same scene with higher or lower resolution. """ function FileIO.save( - filename::String, fig::FigureLike; args... - ) + filename::String, fig::FigureLike; args... +) FileIO.save(FileIO.query(filename), fig; args...) end function FileIO.save( - file::FileIO.Formatted, fig::FigureLike; - resolution = size(get_scene(fig)), - backend = current_backend(), - update = true, - screen_config... - ) + file::FileIO.Formatted, fig::FigureLike; + resolution = size(get_scene(fig)), + backend = current_backend(), + update = true, + screen_config... +) scene = get_scene(fig) if resolution != size(scene) resize!(scene, resolution) @@ -257,12 +257,12 @@ function FileIO.save( # If the scene already got displayed, we get the current screen its displayed on # Else, we create a new scene and update the state of the fig update && update_state_before_display!(fig) - screen = getscreen(backend, scene, io, mime; visible=false, screen_config...) + screen = getscreen(backend, scene, io, mime; visible = false, screen_config...) backend_show(screen, io, mime, scene) end catch e # So, if open(io-> error(...), "w"), the file will get created, but not removed... - isfile(filename) && rm(filename; force=true) + isfile(filename) && rm(filename; force = true) rethrow(e) end end @@ -284,12 +284,12 @@ function jl_to_gl_format(image) n = first(ind1) + last(ind1) for i in ind1 @simd for j in ind2 - @inbounds bufc[j, n-i] = image[i, j] + @inbounds bufc[j, n - i] = image[i, j] end end return bufc else - reverse!(image; dims=1) + reverse!(image; dims = 1) return PermutedDimsArray(image, (2, 1)) end end @@ -306,7 +306,7 @@ end function apply_screen_config! end -function getscreen(backend::Union{Missing, Module}, scene::Scene, args...; screen_config...) +function getscreen(backend::Union{Missing,Module}, scene::Scene, args...; screen_config...) screen = getscreen(scene) config = Makie.merge_screen_config(backend.ScreenConfig, screen_config) if !isnothing(screen) && parentmodule(typeof(screen)) == backend @@ -335,10 +335,10 @@ or RGBA. used in FFMPEG without conversion - `screen_config`: Backend dependend, look up via `?Backend.Screen`/`Base.doc(Backend.Screen)` """ -function colorbuffer(fig::FigureLike, format::ImageStorageFormat = JuliaNative; update=true, backend = current_backend(), screen_config...) +function colorbuffer(fig::FigureLike, format::ImageStorageFormat = JuliaNative; update = true, backend = current_backend(), screen_config...) scene = get_scene(fig) update && update_state_before_display!(fig) - screen = getscreen(backend, scene, format; start_renderloop=false, visible=false, screen_config...) + screen = getscreen(backend, scene, format; start_renderloop = false, visible = false, screen_config...) return colorbuffer(screen, format) end diff --git a/src/documentation/docstringextension.jl b/src/documentation/docstringextension.jl index 25d991af9d4..c8bbc4644dc 100644 --- a/src/documentation/docstringextension.jl +++ b/src/documentation/docstringextension.jl @@ -12,7 +12,7 @@ const ATTRIBUTES = DocThemer() function DocStringExtensions.format(::DocThemer, buf, doc) binding = doc.data[:binding] |> Docs.resolve - help_attributes(buf, binding; extended=true) + help_attributes(buf, binding; extended = true) end ############################################################ diff --git a/src/documentation/documentation.jl b/src/documentation/documentation.jl index ce83835cd4c..207a5e22a58 100644 --- a/src/documentation/documentation.jl +++ b/src/documentation/documentation.jl @@ -14,7 +14,7 @@ Use the optional `extended = true` keyword argument to see more details. """ help(func; kw_args...) = help(stdout, func; kw_args...) #defaults to STDOUT -function help(io::IO, input::Type{T}; extended = false) where T <: AbstractPlot +function help(io::IO, input::Type{T}; extended = false) where T<:AbstractPlot buffer = IOBuffer() _help(buffer, input; extended = extended) Markdown.parse(String(take!(buffer))) @@ -27,7 +27,7 @@ function help(io::IO, input::Function; extended = false) end # Internal help functions -function _help(io::IO, input::Type{T}; extended = false) where T <: AbstractPlot +function _help(io::IO, input::Type{T}; extended = false) where T<:AbstractPlot func = to_func(input) str = to_string(input) @@ -104,7 +104,7 @@ usage: """ help_attributes(x; kw...) = help_attributes(stdout, x; kw...) -function help_attributes(io::IO, Typ::Type{T}; extended = false) where T <: AbstractPlot +function help_attributes(io::IO, Typ::Type{T}; extended = false) where T<:AbstractPlot # get and sort list of attributes from function (using Scatter as an example) # this is a symbolic dictionary, with symbols as the keys attributes = default_theme(nothing, Typ) @@ -155,7 +155,7 @@ function help_attributes(io::IO, func::Function; extended = false) help_attributes(io, to_type(func); extended = extended) end -function help_attributes(io::IO, Typ::Type{T}; extended = false) where T <: Axis3D +function help_attributes(io::IO, Typ::Type{T}; extended = false) where T<:Axis3D if extended println(io, "OldAxis attributes and their defaults for `$Typ` are: \n") else @@ -174,7 +174,7 @@ end Maps the input of a Type name to its cooresponding function. """ -function to_func(Typ::Type{<: AbstractPlot{F}}) where F +function to_func(Typ::Type{<:AbstractPlot{F}}) where F F end @@ -188,7 +188,7 @@ Maps the input of a function name to its cooresponding Type. """ to_type(func::Function) = Combined{func} -to_type(Typ::Type{T}) where T <: AbstractPlot = Typ +to_type(Typ::Type{T}) where T<:AbstractPlot = Typ """ to_string(func) @@ -199,7 +199,7 @@ function to_string(func::Function) str = string(typeof(func).name.mt.name) end -to_string(Typ::Type{T}) where T <: AbstractPlot = to_string(to_func(Typ)) +to_string(Typ::Type{T}) where T<:AbstractPlot = to_string(to_func(Typ)) to_string(s::Symbol) = string(s) to_string(s::String) = s @@ -213,7 +213,7 @@ Use the optional `extended = true` keyword argument to see more details. """ function print_rec(io::IO, dict, indent::Int = 1; extended = false) for (k, v) in dict - print(io, " "^(indent*4), k) + print(io, " "^(indent * 4), k) if isa(to_value(v), Makie.Attributes) print(io, ": ") println(io) diff --git a/src/event-recorder.jl b/src/event-recorder.jl index 4fe6eab44d7..3e2bcc9ba53 100644 --- a/src/event-recorder.jl +++ b/src/event-recorder.jl @@ -11,7 +11,7 @@ function record_events(f, scene::Scene, path::String) for field in fieldnames(Events) # These are not Observables (field == :mousebuttonstate || field == :keyboardstate) && continue - on(getfield(scene.events, field); priority=typemax(Int)) do value + on(getfield(scene.events, field); priority = typemax(Int)) do value value = isa(value, Set) ? copy(value) : value push!(result, time() => (field => value)) return Consume(false) @@ -32,7 +32,7 @@ Replays the serialized events recorded with `record_events` in `path` in `scene` replay_events(scene::Scene, path::String) = replay_events(() -> nothing, scene, path) function replay_events(f, scene::Scene, path::String) events = open(io -> deserialize(io), path) - sort!(events; by=first) + sort!(events; by = first) for i in 1:length(events) t1, (field, value) = events[i] (field == :mousebuttonstate || field == :keyboardstate) && continue diff --git a/src/ffmpeg-util.jl b/src/ffmpeg-util.jl index e44e3038c7c..b6ccedddb41 100644 --- a/src/ffmpeg-util.jl +++ b/src/ffmpeg-util.jl @@ -42,8 +42,8 @@ struct VideoStreamOptions rawvideo::Bool function VideoStreamOptions( - format::AbstractString, framerate::Integer, compression, profile, - pixel_format, loglevel::String, input::String, rawvideo::Bool=true) + format::AbstractString, framerate::Integer, compression, profile, + pixel_format, loglevel::String, input::String, rawvideo::Bool = true) if format == "mp4" (profile === nothing) && (profile = "high422") @@ -56,8 +56,8 @@ struct VideoStreamOptions # items are name, value, allowed_formats allowed_kwargs = [("compression", compression, ("mp4", "webm")), - ("profile", profile, ("mp4",)), - ("pixel_format", pixel_format, ("mp4",))] + ("profile", profile, ("mp4",)), + ("pixel_format", pixel_format, ("mp4",))] for (name, value, allowed_formats) in allowed_kwargs if !(format in allowed_formats) && value !== nothing @@ -91,11 +91,11 @@ struct VideoStreamOptions end end -function VideoStreamOptions(; format="mp4", framerate=24, compression=nothing, profile=nothing, pixel_format=nothing, loglevel="quiet", input="pipe:0", rawvideo=true) +function VideoStreamOptions(; format = "mp4", framerate = 24, compression = nothing, profile = nothing, pixel_format = nothing, loglevel = "quiet", input = "pipe:0", rawvideo = true) return VideoStreamOptions(format, framerate, compression, profile, pixel_format, loglevel, input, rawvideo) end -function to_ffmpeg_cmd(vso::VideoStreamOptions, xdim::Integer=0, ydim::Integer=0) +function to_ffmpeg_cmd(vso::VideoStreamOptions, xdim::Integer = 0, ydim::Integer = 0) # explanation of ffmpeg args. note that the order of args is important; args pertaining # to the input have to go before -i and args pertaining to the output have to go after. # -y: "yes", overwrite any existing without confirmation @@ -199,15 +199,15 @@ $(Base.doc(VideoStreamOptions)) * `screen_config...`: See `?Backend.Screen` or `Base.doc(Backend.Screen)` for applicable options that can be passed and forwarded to the backend. """ function VideoStream(fig::FigureLike; - format="mp4", framerate=24, compression=nothing, profile=nothing, pixel_format=nothing, loglevel="quiet", - visible=false, connect=false, backend=current_backend(), - screen_config...) + format = "mp4", framerate = 24, compression = nothing, profile = nothing, pixel_format = nothing, loglevel = "quiet", + visible = false, connect = false, backend = current_backend(), + screen_config...) dir = mktempdir() path = joinpath(dir, "$(gensym(:video)).$(format)") scene = get_scene(fig) update_state_before_display!(fig) - screen = getscreen(backend, scene, GLNative; visible=visible, start_renderloop=false, screen_config...) + screen = getscreen(backend, scene, GLNative; visible = visible, start_renderloop = false, screen_config...) _xdim, _ydim = size(screen) xdim = iseven(_xdim) ? _xdim : _xdim + 1 ydim = iseven(_ydim) ? _ydim : _ydim + 1 @@ -251,7 +251,7 @@ function save(path::String, io::VideoStream; video_options...) # Maybe warn? convert_video(io.path, path; video_options...) else - cp(io.path, path; force=true) + cp(io.path, path; force = true) end rm(io.path) return path @@ -260,12 +260,12 @@ end function convert_video(input_path, output_path; video_options...) p, typ = splitext(output_path) format = lstrip(typ, '.') - vso = VideoStreamOptions(; format=format, input=input_path, rawvideo=false, video_options...) + vso = VideoStreamOptions(; format = format, input = input_path, rawvideo = false, video_options...) cmd = to_ffmpeg_cmd(vso) @ffmpeg_env run(`$cmd $output_path`) end -function extract_frames(video, frame_folder; loglevel="quiet") +function extract_frames(video, frame_folder; loglevel = "quiet") path = joinpath(frame_folder, "frame%04d.png") FFMPEG.ffmpeg_exe(`-loglevel $(loglevel) -i $video -y $path`) end diff --git a/src/figureplotting.jl b/src/figureplotting.jl index 1c71419006a..33e163b44ad 100644 --- a/src/figureplotting.jl +++ b/src/figureplotting.jl @@ -29,7 +29,7 @@ function _disallow_keyword(kw, attributes) end function plot(P::PlotFunc, args...; axis = NamedTuple(), figure = NamedTuple(), kw_attributes...) - + _validate_nt_like_keyword(axis, "axis") _validate_nt_like_keyword(figure, "figure") @@ -118,7 +118,7 @@ end function plot(P::PlotFunc, gsp::GridSubposition, args...; axis = NamedTuple(), kwargs...) _validate_nt_like_keyword(axis, "axis") - + layout = GridLayoutBase.get_layout_at!(gsp.parent, createmissing = true) c = contents(gsp, exact = true) if !isempty(c) @@ -177,4 +177,4 @@ function update_state_before_display!(f::Figure) update_state_before_display!(c) end return -end \ No newline at end of file +end diff --git a/src/figures.jl b/src/figures.jl index b1b212c367d..69333d97b57 100644 --- a/src/figures.jl +++ b/src/figures.jl @@ -27,7 +27,7 @@ if an axis is placed at that position (if not it errors) or it can reference an get_scene(fig::Figure) = fig.scene get_scene(fap::FigureAxisPlot) = fap.figure.scene -const _current_figure = Ref{Union{Nothing, Figure}}(nothing) +const _current_figure = Ref{Union{Nothing,Figure}}(nothing) "Returns the current active figure (or the last figure that got created)" current_figure() = _current_figure[] "Set `fig` as the current active scene" @@ -61,13 +61,13 @@ function current_axis!(ax) end to_rectsides(n::Number) = to_rectsides((n, n, n, n)) -to_rectsides(t::Tuple{Any, Any, Any, Any}) = GridLayoutBase.RectSides{Float32}(t...) +to_rectsides(t::Tuple{Any,Any,Any,Any}) = GridLayoutBase.RectSides{Float32}(t...) function Figure(; kwargs...) kwargs_dict = Dict(kwargs) padding = pop!(kwargs_dict, :figure_padding, current_default_theme()[:figure_padding]) - scene = Scene(; camera=campixel!, kwargs_dict...) + scene = Scene(; camera = campixel!, kwargs_dict...) padding = padding isa Observable ? padding : Observable{Any}(padding) alignmode = lift(Outside ∘ to_rectsides, padding) diff --git a/src/interaction/events.jl b/src/interaction/events.jl index 0a28e6a6cde..d80a262d549 100644 --- a/src/interaction/events.jl +++ b/src/interaction/events.jl @@ -59,7 +59,7 @@ Picks a mouse position. Implemented by the backend. function pick end function pick(::Scene, ::Screen, xy) where Screen - @warn "Picking not supported yet by $(parentmodule(Screen))" maxlog=1 + @warn "Picking not supported yet by $(parentmodule(Screen))" maxlog = 1 return nothing, 0 end @@ -85,7 +85,7 @@ If more than two arguments are given a tree of `And` structs is created. See also: [`Or`](@ref), [`Not`](@ref), [`ispressed`](@ref), [`&`](@ref) """ -struct And{L, R} <: BooleanOperator +struct And{L,R} <: BooleanOperator left::L right::R end @@ -100,7 +100,7 @@ If more than two arguments are given a tree of `Or` structs is created. See also: [`And`](@ref), [`Not`](@ref), [`ispressed`](@ref), [`|`](@ref) """ -struct Or{L, R} <: BooleanOperator +struct Or{L,R} <: BooleanOperator left::L right::R end @@ -137,7 +137,7 @@ See also: [`And`](@ref), [`Or`](@ref), [`Not`](@ref), [`ispressed`](@ref), [`&`](@ref), [`|`](@ref), [`!`](@ref) """ struct Exclusively <: BooleanOperator - x::Set{Union{Keyboard.Button, Mouse.Button}} + x::Set{Union{Keyboard.Button,Mouse.Button}} end # Printing @@ -175,34 +175,34 @@ Or(x) = x function Base.:(&)( - left::Union{BooleanOperator, Keyboard.Button, Mouse.Button}, - right::Union{BooleanOperator, Keyboard.Button, Mouse.Button, Bool} - ) + left::Union{BooleanOperator,Keyboard.Button,Mouse.Button}, + right::Union{BooleanOperator,Keyboard.Button,Mouse.Button,Bool} +) And(left, right) end function Base.:(&)( - left::Bool, - right::Union{BooleanOperator, Keyboard.Button, Mouse.Button} - ) + left::Bool, + right::Union{BooleanOperator,Keyboard.Button,Mouse.Button} +) And(left, right) end function Base.:(|)( - left::Union{BooleanOperator, Keyboard.Button, Mouse.Button}, - right::Union{BooleanOperator, Keyboard.Button, Mouse.Button, Bool} - ) + left::Union{BooleanOperator,Keyboard.Button,Mouse.Button}, + right::Union{BooleanOperator,Keyboard.Button,Mouse.Button,Bool} +) Or(left, right) end function Base.:(|)( - left::Bool, - right::Union{BooleanOperator, Keyboard.Button, Mouse.Button} - ) + left::Bool, + right::Union{BooleanOperator,Keyboard.Button,Mouse.Button} +) Or(left, right) end -Base.:(!)(x::Union{BooleanOperator, Keyboard.Button, Mouse.Button}) = Not(x) +Base.:(!)(x::Union{BooleanOperator,Keyboard.Button,Mouse.Button}) = Not(x) -Exclusively(x::Union{Vector, Tuple}) = Exclusively(Set(x)) -Exclusively(x::Union{Keyboard.Button, Mouse.Button}) = Exclusively(Set((x,))) +Exclusively(x::Union{Vector,Tuple}) = Exclusively(Set(x)) +Exclusively(x::Union{Keyboard.Button,Mouse.Button}) = Exclusively(Set((x,))) Exclusively(x::Bool) = x Exclusively(x::Or) = Or(Exclusively(x.left), Exclusively(x.right)) Exclusively(x::And) = Or(Exclusively.(unique(create_sets(x)))...) @@ -211,14 +211,14 @@ Exclusively(x::And) = Or(Exclusively.(unique(create_sets(x)))...) # Sets represent `And`, arrays represent `Or` function create_sets(x::And) [union(left, right) for left in create_sets(x.left) - for right in create_sets(x.right)] + for right in create_sets(x.right)] end create_sets(x::Or) = vcat(create_sets(x.left), create_sets(x.right)) -create_sets(::Not) = Set{Union{Keyboard.Button, Mouse.Button}}() -function create_sets(b::Union{Keyboard.Button, Mouse.Button}) - [Set{Union{Keyboard.Button, Mouse.Button}}((b,))] +create_sets(::Not) = Set{Union{Keyboard.Button,Mouse.Button}}() +function create_sets(b::Union{Keyboard.Button,Mouse.Button}) + [Set{Union{Keyboard.Button,Mouse.Button}}((b,))] end -create_sets(s::Set) = [Set{Union{Keyboard.Button, Mouse.Button}}(s)] +create_sets(s::Set) = [Set{Union{Keyboard.Button,Mouse.Button}}(s)] # ispressed and logic evaluation @@ -261,7 +261,7 @@ ispressed(scene, key::Keyboard.Button) = ispressed(events(scene), key) # Boolean Operator evaluation ispressed(scene, op::And) = ispressed(scene, op.left) && ispressed(scene, op.right) -ispressed(scene, op::Or) = ispressed(scene, op.left) || ispressed(scene, op.right) +ispressed(scene, op::Or) = ispressed(scene, op.left) || ispressed(scene, op.right) ispressed(scene, op::Not) = !ispressed(scene, op.x) ispressed(scene::Scene, op::Exclusively) = ispressed(events(scene), op) ispressed(e::Events, op::Exclusively) = op.x == union(e.keyboardstate, e.mousebuttonstate) diff --git a/src/interaction/inspector.jl b/src/interaction/inspector.jl index 6d02b191f81..c30e42372fd 100644 --- a/src/interaction/inspector.jl +++ b/src/interaction/inspector.jl @@ -69,7 +69,8 @@ _to_rotation(x::Vector, idx) = to_rotation(x[idx]) function closest_point_on_line(p0::Point2f, p1::Point2f, r::Point2f) # This only works in 2D - AP = P .- A; AB = B .- A + AP = P .- A + AB = B .- A A .+ AB * dot(AP, AB) / dot(AB, AB) end @@ -141,11 +142,11 @@ end ### Surface positions ######################################## -surface_x(xs::ClosedInterval, i, j, N) = minimum(xs) + (maximum(xs) - minimum(xs)) * (i-1) / (N-1) +surface_x(xs::ClosedInterval, i, j, N) = minimum(xs) + (maximum(xs) - minimum(xs)) * (i - 1) / (N - 1) surface_x(xs, i, j, N) = xs[i] surface_x(xs::AbstractMatrix, i, j, N) = xs[i, j] -surface_y(ys::ClosedInterval, i, j, N) = minimum(ys) + (maximum(ys) - minimum(ys)) * (j-1) / (N-1) +surface_y(ys::ClosedInterval, i, j, N) = minimum(ys) + (maximum(ys) - minimum(ys)) * (j - 1) / (N - 1) surface_y(ys, i, j, N) = ys[j] surface_y(ys::AbstractMatrix, i, j, N) = ys[i, j] @@ -227,7 +228,7 @@ function cleanup(inspector::DataInspector) inspector end -function Base.delete!(::Union{Scene, Figure}, inspector::DataInspector) +function Base.delete!(::Union{Scene,Figure}, inspector::DataInspector) cleanup(inspector) end @@ -285,10 +286,10 @@ function DataInspector(scene::Scene; priority = 100, kwargs...) indicator_visible = false, # General reusable - _color = RGBAf(0,0,0,0), + _color = RGBAf(0, 0, 0, 0), ) - plot = tooltip!(parent, Observable(Point2f(0)), text = Observable(""); visible=false, attrib_dict...) + plot = tooltip!(parent, Observable(Point2f(0)), text = Observable(""); visible = false, attrib_dict...) on(z -> translate!(plot, 0, 0, z), base_attrib.depth) notify(base_attrib.depth) @@ -382,7 +383,7 @@ function show_data_recursion(inspector, plot::AbstractPlot, idx, source) if processed inspector.selection = plot end - + return processed end end @@ -401,9 +402,9 @@ function clear_temporary_plots!(inspector::DataInspector, plot) # clear attributes which are reused for indicator plots for key in ( - :indicator_color, :indicator_linestyle, - :indicator_linewidth, :indicator_visible - ) + :indicator_color, :indicator_linestyle, + :indicator_linewidth, :indicator_visible + ) empty!(inspector.attributes[key].listeners) end @@ -479,7 +480,7 @@ function show_data(inspector::DataInspector, plot::MeshScatter, idx) upvector = cc.upvector[] end - bbox = Rect{3, Float32}(convert_attribute( + bbox = Rect{3,Float32}(convert_attribute( plot.marker[], Key{:marker}(), Key{Makie.plotkey(plot)}() )) @@ -517,13 +518,13 @@ function show_data(inspector::DataInspector, plot::MeshScatter, idx) end -function show_data(inspector::DataInspector, plot::Union{Lines, LineSegments}, idx) +function show_data(inspector::DataInspector, plot::Union{Lines,LineSegments}, idx) a = inspector.attributes tt = inspector.plot scene = parent_scene(plot) # cast ray from cursor into screen, find closest point to line - p0, p1 = plot[1][][idx-1:idx] + p0, p1 = plot[1][][(idx - 1):idx] origin, dir = view_ray(scene) pos = closest_point_on_line(p0, p1, origin, dir) lw = plot.linewidth[] isa Vector ? plot.linewidth[][idx] : plot.linewidth[] @@ -605,19 +606,20 @@ function show_data(inspector::DataInspector, plot::Surface, idx) ys = plot[2][] zs = plot[3][] w, h = size(zs) - _i = mod1(idx, w); _j = div(idx-1, w) + _i = mod1(idx, w) + _j = div(idx - 1, w) # This isn't the most accurate so we include some neighboring faces origin, dir = view_ray(scene) pos = Point3f(NaN) - for i in _i-1:_i+1, j in _j-1:_j+1 + for i in (_i - 1):(_i + 1), j in (_j - 1):(_j + 1) (1 <= i <= w) && (1 <= j < h) || continue if i - 1 > 0 pos = ray_triangle_intersection( surface_pos(xs, ys, zs, i, j), - surface_pos(xs, ys, zs, i-1, j), - surface_pos(xs, ys, zs, i, j+1), + surface_pos(xs, ys, zs, i - 1, j), + surface_pos(xs, ys, zs, i, j + 1), origin, dir ) end @@ -625,8 +627,8 @@ function show_data(inspector::DataInspector, plot::Surface, idx) if i + 1 <= w && isnan(pos) pos = ray_triangle_intersection( surface_pos(xs, ys, zs, i, j), - surface_pos(xs, ys, zs, i, j+1), - surface_pos(xs, ys, zs, i+1, j+1), + surface_pos(xs, ys, zs, i, j + 1), + surface_pos(xs, ys, zs, i + 1, j + 1), origin, dir ) end @@ -670,7 +672,8 @@ function show_imagelike(inspector, plot, name, edge_based) x, y = mpos else i, j, z = _pixelated_getindex(plot[1][], plot[2][], plot[3][], mpos, edge_based) - x = i; y = j + x = i + y = j end if haskey(plot, :inspector_label) @@ -707,11 +710,11 @@ function show_imagelike(inspector, plot, name, edge_based) scene, position, color = a._color, visible = a.indicator_visible, inspectable = false, - marker=:rect, markersize = map(r -> 3r, a.range), + marker = :rect, markersize = map(r -> 3r, a.range), strokecolor = a.indicator_color, strokewidth = a.indicator_linewidth ) - translate!(p, Vec3f(0, 0, a.depth[]-1)) + translate!(p, Vec3f(0, 0, a.depth[] - 1)) push!(inspector.temp_plots, p) elseif !isempty(inspector.temp_plots) p = inspector.temp_plots[1] @@ -727,7 +730,7 @@ function show_imagelike(inspector, plot, name, edge_based) strokewidth = a.indicator_linewidth, linestyle = a.indicator_linestyle, visible = a.indicator_visible, inspectable = false ) - translate!(p, Vec3f(0, 0, a.depth[]-1)) + translate!(p, Vec3f(0, 0, a.depth[] - 1)) push!(inspector.temp_plots, p) elseif !isempty(inspector.temp_plots) p = inspector.temp_plots[1] @@ -750,12 +753,12 @@ function _interpolated_getindex(xs, ys, img, mpos) i = clamp((x - x0) / (x1 - x0) * size(img, 1) + 0.5, 1, size(img, 1)) j = clamp((y - y0) / (y1 - y0) * size(img, 2) + 0.5, 1, size(img, 2)) - l = clamp(floor(Int, i), 1, size(img, 1)-1); - r = clamp(l+1, 2, size(img, 1)) - b = clamp(floor(Int, j), 1, size(img, 2)-1); - t = clamp(b+1, 2, size(img, 2)) - z = ((r-i) * img[l, b] + (i-l) * img[r, b]) * (t-j) + - ((r-i) * img[l, t] + (i-l) * img[r, t]) * (j-b) + l = clamp(floor(Int, i), 1, size(img, 1) - 1) + r = clamp(l + 1, 2, size(img, 1)) + b = clamp(floor(Int, j), 1, size(img, 2) - 1) + t = clamp(b + 1, 2, size(img, 2)) + z = ((r - i) * img[l, b] + (i - l) * img[r, b]) * (t - j) + + ((r - i) * img[l, t] + (i - l) * img[r, t]) * (j - b) # float, float, value (i, j are no longer used) return i, j, z @@ -769,7 +772,7 @@ function _pixelated_getindex(xs, ys, img, mpos, edge_based) j = clamp(round(Int, (y - y0) / (y1 - y0) * size(img, 2) + 0.5), 1, size(img, 2)) # int, int, value - return i, j, img[i,j] + return i, j, img[i, j] end function _interpolated_getindex(xs::Vector, ys::Vector, img, mpos) @@ -779,16 +782,16 @@ function _interpolated_getindex(xs::Vector, ys::Vector, img, mpos) # z = ((xs[i+1] - x) / w * img[i, j] + (x - xs[i]) / w * img[i+1, j]) * (ys[j+1] - y) / h + # ((xs[i+1] - x) / w * img[i, j+1] + (x - xs[i]) / w * img[i+1, j+1]) * (y - ys[j]) / h # return i, j, z - _interpolated_getindex(minimum(xs)..maximum(xs), minimum(ys)..maximum(ys), img, mpos) + _interpolated_getindex(minimum(xs) .. maximum(xs), minimum(ys) .. maximum(ys), img, mpos) end function _pixelated_getindex(xs::Vector, ys::Vector, img, mpos, edge_based) if edge_based x, y = mpos - i = max(1, something(findfirst(v -> v >= x, xs), length(xs))-1) - j = max(1, something(findfirst(v -> v >= y, ys), length(ys))-1) + i = max(1, something(findfirst(v -> v >= x, xs), length(xs)) - 1) + j = max(1, something(findfirst(v -> v >= y, ys), length(ys)) - 1) return i, j, img[i, j] else - _pixelated_getindex(minimum(xs)..maximum(xs), minimum(ys)..maximum(ys), img, mpos, edge_based) + _pixelated_getindex(minimum(xs) .. maximum(xs), minimum(ys) .. maximum(ys), img, mpos, edge_based) end end @@ -796,20 +799,20 @@ function _pixelated_image_bbox(xs, ys, img, i::Integer, j::Integer, edge_based) x0, x1 = extrema(xs) y0, y1 = extrema(ys) nw, nh = ((x1 - x0), (y1 - y0)) ./ size(img) - Rect2f(x0 + nw * (i-1), y0 + nh * (j-1), nw, nh) + Rect2f(x0 + nw * (i - 1), y0 + nh * (j - 1), nw, nh) end function _pixelated_image_bbox(xs::Vector, ys::Vector, img, i::Integer, j::Integer, edge_based) if edge_based - Rect2f(xs[i], ys[j], xs[i+1] - xs[i], ys[j+1] - ys[j]) + Rect2f(xs[i], ys[j], xs[i + 1] - xs[i], ys[j + 1] - ys[j]) else _pixelated_image_bbox( - minimum(xs)..maximum(xs), minimum(ys)..maximum(ys), + minimum(xs) .. maximum(xs), minimum(ys) .. maximum(ys), img, i, j, edge_based ) end end -function show_data(inspector::DataInspector, plot, idx, source=nothing) +function show_data(inspector::DataInspector, plot, idx, source = nothing) return false end @@ -821,11 +824,11 @@ end function show_data(inspector::DataInspector, plot::BarPlot, idx, ::Lines) - return show_data(inspector, plot, div(idx-1, 6)+1) + return show_data(inspector, plot, div(idx - 1, 6) + 1) end function show_data(inspector::DataInspector, plot::BarPlot, idx, ::Mesh) - return show_data(inspector, plot, div(idx-1, 4)+1) + return show_data(inspector, plot, div(idx - 1, 4) + 1) end @@ -872,7 +875,7 @@ function show_data(inspector::DataInspector, plot::BarPlot, idx) end function show_data(inspector::DataInspector, plot::Arrows, idx, ::LineSegments) - return show_data(inspector, plot, div(idx+1, 2), nothing) + return show_data(inspector, plot, div(idx + 1, 2), nothing) end function show_data(inspector::DataInspector, plot::Arrows, idx, source) a = inspector.plot.attributes @@ -947,7 +950,7 @@ function show_poly(inspector, plot, idx, source) strokewidth = a.indicator_linewidth, linestyle = a.indicator_linestyle, visible = a.indicator_visible, inspectable = false ) - translate!(p, Vec3f(0, 0, a.depth[]-1)) + translate!(p, Vec3f(0, 0, a.depth[] - 1)) push!(inspector.temp_plots, p) elseif !isempty(inspector.temp_plots) @@ -990,11 +993,14 @@ function show_data(inspector::DataInspector, plot::VolumeSlices, idx, child::Hea if !isnan(pos) child_idx = findfirst(isequal(child), plot.plots) if child_idx == 2 - x = pos[2]; y = pos[3] + x = pos[2] + y = pos[3] elseif child_idx == 3 - x = pos[1]; y = pos[3] + x = pos[1] + y = pos[3] else - x = pos[1]; y = pos[2] + x = pos[1] + y = pos[2] end i = clamp(round(Int, (x - qs[1]) / (qs[2] - qs[1]) * size(data, 1) + 0.5), 1, size(data, 1)) j = clamp(round(Int, (y - ps[1]) / (ps[2] - ps[1]) * size(data, 2) + 0.5), 1, size(data, 2)) diff --git a/src/interaction/interactive_api.jl b/src/interaction/interactive_api.jl index 309a8ed3fec..09a06a34d54 100644 --- a/src/interaction/interactive_api.jl +++ b/src/interaction/interactive_api.jl @@ -20,8 +20,8 @@ Calls `f(plot, idx)` whenever the mouse is over any of `plots`. `idx` is an index, e.g. when over a scatter plot, it will be the index of the hovered element """ -onpick(f, x, plots::AbstractPlot...; range=1) = onpick(f, get_scene(x), plots..., range = range) -function onpick(f, scene::Scene, plots::AbstractPlot...; range=1) +onpick(f, x, plots::AbstractPlot...; range = 1) = onpick(f, get_scene(x), plots..., range = range) +function onpick(f, scene::Scene, plots::AbstractPlot...; range = 1) fplots = flatten_plots(plots) args = range == 1 ? (scene,) : (scene, range) on(events(scene).mouseposition) do mp @@ -81,7 +81,7 @@ Returns the plot under pixel position `(x, y)`. """ pick(obj, x::Number, y::Number) = pick(get_scene(obj), x, y) function pick(scene::Scene, x::Number, y::Number) - return pick(scene, Vec{2, Float64}(x, y)) + return pick(scene, Vec{2,Float64}(x, y)) end @@ -95,7 +95,7 @@ pick(obj, xy::VecTypes{2}) = pick(get_scene(obj), xy) function pick(scene::Scene, xy::VecTypes{2}) screen = getscreen(scene) screen === nothing && return (nothing, 0) - pick(scene, screen, Vec{2, Float64}(xy)) + pick(scene, screen, Vec{2,Float64}(xy)) end """ @@ -117,15 +117,16 @@ function pick_closest(scene::SceneLike, screen, xy, range) ((1.0 <= xy[1] <= w) && (1.0 <= xy[2] <= h)) || return (nothing, 0) x0, y0 = max.(1, floor.(Int, xy .- range)) x1, y1 = min.([w, h], floor.(Int, xy .+ range)) - dx = x1 - x0; dy = y1 - y0 + dx = x1 - x0 + dy = y1 - y0 picks = pick(scene, screen, Rect2i(x0, y0, dx, dy)) min_dist = range^2 selected = (0, 0) - x, y = xy .+ 1 .- Vec2f(x0, y0) + x, y = xy .+ 1 .- Vec2f(x0, y0) for i in 1:dx, j in 1:dy - d = (x-i)^2 + (y-j)^2 + d = (x - i)^2 + (y - j)^2 if (d < min_dist) && (picks[i, j][1] != nothing) min_dist = d selected = (i, j) @@ -143,27 +144,28 @@ sorted by distance to `xy`. """ function pick_sorted(scene::Scene, xy, range) screen = getscreen(scene) - screen === nothing && return Tuple{AbstractPlot, Int}[] + screen === nothing && return Tuple{AbstractPlot,Int}[] pick_sorted(scene, screen, xy, range) end function pick_sorted(scene::Scene, screen, xy, range) w, h = widths(events(scene).window_area[]) if !((1.0 <= xy[1] <= w) && (1.0 <= xy[2] <= h)) - return Tuple{AbstractPlot, Int}[] + return Tuple{AbstractPlot,Int}[] end x0, y0 = max.(1, floor.(Int, xy .- range)) x1, y1 = min.([w, h], floor.(Int, xy .+ range)) - dx = x1 - x0; dy = y1 - y0 + dx = x1 - x0 + dy = y1 - y0 picks = pick(scene, screen, Rect2i(x0, y0, dx, dy)) selected = filter(x -> x[1] !== nothing, unique(vec(picks))) distances = [range^2 for _ in selected] - x, y = xy .+ 1 .- Vec2f(x0, y0) + x, y = xy .+ 1 .- Vec2f(x0, y0) for i in 1:dx, j in 1:dy if picks[i, j][1] !== nothing - d = (x-i)^2 + (y-j)^2 + d = (x - i)^2 + (y - j)^2 i = findfirst(isequal(picks[i, j]), selected)::Int if distances[i] > d distances[i] = d @@ -185,7 +187,7 @@ screen boundaries. pick(x, rect::Rect2i) = pick(get_scene(x), rect) function pick(scene::Scene, rect::Rect2i) screen = getscreen(scene) - screen === nothing && return Tuple{AbstractPlot, Int}[] + screen === nothing && return Tuple{AbstractPlot,Int}[] return pick(scene, screen, rect) end @@ -253,7 +255,7 @@ function select_rectangle(scene; blocking = false, priority = 2, strokewidth = 3 scene, rect, visible = false, color = RGBAf(0, 0, 0, 0), strokecolor = RGBAf(0.1, 0.1, 0.8, 0.5), strokewidth = strokewidth, kwargs..., ) - on(events(scene).mousebutton, priority=priority) do event + on(events(scene).mousebutton, priority = priority) do event if event.button == key if event.action == Mouse.press && is_mouseinside(scene) mp = mouseposition(scene) @@ -279,7 +281,7 @@ function select_rectangle(scene; blocking = false, priority = 2, strokewidth = 3 return Consume(false) end - on(events(scene).mouseposition, priority=priority) do event + on(events(scene).mouseposition, priority = priority) do event if waspressed[] mp = mouseposition(scene) mini = minimum(rect[]) @@ -309,15 +311,15 @@ The `kwargs...` are propagated into `lines!` which plots the selected line. function select_line(scene; blocking = false, priority = 2, kwargs...) key = Mouse.left waspressed = Observable(false) - line = Observable([Point2f(0,0), Point2f(1,1)]) - line_ret = Observable([Point2f(0,0), Point2f(1,1)]) + line = Observable([Point2f(0, 0), Point2f(1, 1)]) + line_ret = Observable([Point2f(0, 0), Point2f(1, 1)]) # Create an initially hidden arrow plotted_line = lines!( scene, line; visible = false, color = RGBAf(0.1, 0.1, 0.8, 0.5), - linewidth = 4, kwargs..., + linewidth = 4, kwargs... ) - on(events(scene).mousebutton, priority=priority) do event + on(events(scene).mousebutton, priority = priority) do event if event.button == key && is_mouseinside(scene) mp = mouseposition(scene) if event.action == Mouse.press @@ -341,7 +343,7 @@ function select_line(scene; blocking = false, priority = 2, kwargs...) end return Consume(false) end - on(events(scene).mouseposition, priority=priority) do event + on(events(scene).mouseposition, priority = priority) do event if waspressed[] mp = mouseposition(scene) line[][2] = mp @@ -367,19 +369,19 @@ The value of the returned point is updated **only** when the user un-clicks. The `kwargs...` are propagated into `scatter!` which plots the selected point. """ -function select_point(scene; blocking = false, priority=2, kwargs...) +function select_point(scene; blocking = false, priority = 2, kwargs...) key = Mouse.left pmarker = Circle(Point2f(0, 0), Float32(1)) waspressed = Observable(false) - point = Observable([Point2f(0,0)]) - point_ret = Observable(Point2f(0,0)) + point = Observable([Point2f(0, 0)]) + point_ret = Observable(Point2f(0, 0)) # Create an initially hidden arrow plotted_point = scatter!( scene, point; visible = false, marker = pmarker, markersize = 20px, - color = RGBAf(0.1, 0.1, 0.8, 0.5), kwargs..., + color = RGBAf(0.1, 0.1, 0.8, 0.5), kwargs... ) - on(events(scene).mousebutton, priority=priority) do event + on(events(scene).mousebutton, priority = priority) do event if event.button == key && is_mouseinside(scene) mp = mouseposition(scene) if event.action == Mouse.press @@ -400,7 +402,7 @@ function select_point(scene; blocking = false, priority=2, kwargs...) end return Consume(false) end - on(events(scene).mouseposition, priority=priority) do event + on(events(scene).mouseposition, priority = priority) do event if waspressed[] mp = mouseposition(scene) point[][1] = mp diff --git a/src/interaction/iodevices.jl b/src/interaction/iodevices.jl index 416f8580f69..d65c09f065f 100644 --- a/src/interaction/iodevices.jl +++ b/src/interaction/iodevices.jl @@ -4,151 +4,151 @@ represent keyboard buttons. """ module Keyboard - using ..Makie: INSTANCES # import the docstring extensions - """ - Keyboard.Button - - Enumerates all keyboard buttons. - See the implementation for details. - """ - @enum(Button, - unknown = -1, - # printable keys, - space = 32, - apostrophe = 39, # ', - comma = 44, # ,, - minus = 45, # -, - period = 46, # ., - slash = 47, # /, - _0 = 48, - _1 = 49, - _2 = 50, - _3 = 51, - _4 = 52, - _5 = 53, - _6 = 54, - _7 = 55, - _8 = 56, - _9 = 57, - semicolon = 59, # ;, - equal = 61, # =, - a = 65, - b = 66, - c = 67, - d = 68, - e = 69, - f = 70, - g = 71, - h = 72, - i = 73, - j = 74, - k = 75, - l = 76, - m = 77, - n = 78, - o = 79, - p = 80, - q = 81, - r = 82, - s = 83, - t = 84, - u = 85, - v = 86, - w = 87, - x = 88, - y = 89, - z = 90, - left_bracket = 91, # [, - backslash = 92, # , - right_bracket = 93, # ], - grave_accent = 96, # `, - world_1 = 161, # non-us #1, - world_2 = 162, # non-us #2, - # function keys, - escape = 256, - enter = 257, - tab = 258, - backspace = 259, - insert = 260, - delete = 261, - right = 262, - left = 263, - down = 264, - up = 265, - page_up = 266, - page_down = 267, - home = 268, - _end = 269, - caps_lock = 280, - scroll_lock = 281, - num_lock = 282, - print_screen = 283, - pause = 284, - f1 = 290, - f2 = 291, - f3 = 292, - f4 = 293, - f5 = 294, - f6 = 295, - f7 = 296, - f8 = 297, - f9 = 298, - f10 = 299, - f11 = 300, - f12 = 301, - f13 = 302, - f14 = 303, - f15 = 304, - f16 = 305, - f17 = 306, - f18 = 307, - f19 = 308, - f20 = 309, - f21 = 310, - f22 = 311, - f23 = 312, - f24 = 313, - f25 = 314, - kp_0 = 320, - kp_1 = 321, - kp_2 = 322, - kp_3 = 323, - kp_4 = 324, - kp_5 = 325, - kp_6 = 326, - kp_7 = 327, - kp_8 = 328, - kp_9 = 329, - kp_decimal = 330, - kp_divide = 331, - kp_multiply = 332, - kp_subtract = 333, - kp_add = 334, - kp_enter = 335, - kp_equal = 336, - left_shift = 340, - left_control = 341, - left_alt = 342, - left_super = 343, - right_shift = 344, - right_control = 345, - right_alt = 346, - right_super = 347, - menu = 348, - ) - - """ - Keyboard.Action - - Enumerates all key states/actions in accordance with the GLFW spec. - - $(INSTANCES) - """ - @enum Action begin - release = 0 - press = 1 - repeat = 2 - end +using ..Makie: INSTANCES # import the docstring extensions +""" + Keyboard.Button + +Enumerates all keyboard buttons. +See the implementation for details. +""" +@enum(Button, + unknown = -1, + # printable keys, + space = 32, + apostrophe = 39, # ', + comma = 44, # ,, + minus = 45, # -, + period = 46, # ., + slash = 47, # /, + _0 = 48, + _1 = 49, + _2 = 50, + _3 = 51, + _4 = 52, + _5 = 53, + _6 = 54, + _7 = 55, + _8 = 56, + _9 = 57, + semicolon = 59, # ;, + equal = 61, # =, + a = 65, + b = 66, + c = 67, + d = 68, + e = 69, + f = 70, + g = 71, + h = 72, + i = 73, + j = 74, + k = 75, + l = 76, + m = 77, + n = 78, + o = 79, + p = 80, + q = 81, + r = 82, + s = 83, + t = 84, + u = 85, + v = 86, + w = 87, + x = 88, + y = 89, + z = 90, + left_bracket = 91, # [, + backslash = 92, # , + right_bracket = 93, # ], + grave_accent = 96, # `, + world_1 = 161, # non-us #1, + world_2 = 162, # non-us #2, + # function keys, + escape = 256, + enter = 257, + tab = 258, + backspace = 259, + insert = 260, + delete = 261, + right = 262, + left = 263, + down = 264, + up = 265, + page_up = 266, + page_down = 267, + home = 268, + _end = 269, + caps_lock = 280, + scroll_lock = 281, + num_lock = 282, + print_screen = 283, + pause = 284, + f1 = 290, + f2 = 291, + f3 = 292, + f4 = 293, + f5 = 294, + f6 = 295, + f7 = 296, + f8 = 297, + f9 = 298, + f10 = 299, + f11 = 300, + f12 = 301, + f13 = 302, + f14 = 303, + f15 = 304, + f16 = 305, + f17 = 306, + f18 = 307, + f19 = 308, + f20 = 309, + f21 = 310, + f22 = 311, + f23 = 312, + f24 = 313, + f25 = 314, + kp_0 = 320, + kp_1 = 321, + kp_2 = 322, + kp_3 = 323, + kp_4 = 324, + kp_5 = 325, + kp_6 = 326, + kp_7 = 327, + kp_8 = 328, + kp_9 = 329, + kp_decimal = 330, + kp_divide = 331, + kp_multiply = 332, + kp_subtract = 333, + kp_add = 334, + kp_enter = 335, + kp_equal = 336, + left_shift = 340, + left_control = 341, + left_alt = 342, + left_super = 343, + right_shift = 344, + right_control = 345, + right_alt = 346, + right_super = 347, + menu = 348, +) + +""" + Keyboard.Action + +Enumerates all key states/actions in accordance with the GLFW spec. + +$(INSTANCES) +""" +@enum Action begin + release = 0 + press = 1 + repeat = 2 +end end """ @@ -156,52 +156,52 @@ Backend independent enums and fields which represent mouse actions. """ module Mouse - using ..Makie: INSTANCES # import the docstring extensions - - """ - Mouse.Button - - Enumerates all mouse buttons in accordance with the GLFW spec. - - $(INSTANCES) - """ - @enum Button begin - left = 0 - middle = 2 - right = 1 # Conform to GLFW - none = -1 # for convenience - end - - """ - Mouse.Action - - Enumerates all mouse states/actions in accordance with the GLFW spec. - - $(INSTANCES) - """ - @enum Action begin - press = 1 - release = 0 - end - - # deprecated, remove eventually - """ - Mouse.DragEnum - - Enumerates the drag states of the mouse. - - $(INSTANCES) - """ - @enum DragEnum begin - down - up - pressed - notpressed - end +using ..Makie: INSTANCES # import the docstring extensions + +""" + Mouse.Button + +Enumerates all mouse buttons in accordance with the GLFW spec. + +$(INSTANCES) +""" +@enum Button begin + left = 0 + middle = 2 + right = 1 # Conform to GLFW + none = -1 # for convenience +end + +""" + Mouse.Action + +Enumerates all mouse states/actions in accordance with the GLFW spec. + +$(INSTANCES) +""" +@enum Action begin + press = 1 + release = 0 +end + +# deprecated, remove eventually +""" + Mouse.DragEnum + +Enumerates the drag states of the mouse. + +$(INSTANCES) +""" +@enum DragEnum begin + down + up + pressed + notpressed +end end # Void for no button needs to be pressed, -const ButtonTypes = Union{Nothing, Mouse.Button, Keyboard.Button} +const ButtonTypes = Union{Nothing,Mouse.Button,Keyboard.Button} diff --git a/src/interaction/observables.jl b/src/interaction/observables.jl index fa58ddc1793..29bd7d353f3 100644 --- a/src/interaction/observables.jl +++ b/src/interaction/observables.jl @@ -34,8 +34,8 @@ test(Observable(1), Observable(2)) """ function map_once( - f, input::Observable, inputrest::Observable... - ) + f, input::Observable, inputrest::Observable... +) for arg in (input, inputrest...) safe_off(arg, f) end diff --git a/src/interfaces.jl b/src/interfaces.jl index da63febdc95..dc3c277bdba 100644 --- a/src/interfaces.jl +++ b/src/interfaces.jl @@ -10,7 +10,7 @@ function default_theme(scene) diffuse = Vec3f(0.4), specular = Vec3f(0.2), shininess = 32f0, - nan_color = RGBAf(0,0,0,0), + nan_color = RGBAf(0, 0, 0, 0), ssao = false, inspectable = theme(scene, :inspectable), depth_shift = 0f0, @@ -21,7 +21,7 @@ end function color_and_colormap!(plot, intensity = plot[:color]) - if isa(intensity[], AbstractArray{<: Number}) + if isa(intensity[], AbstractArray{<:Number}) haskey(plot, :colormap) || error("Plot $(typeof(plot)) needs to have a colormap to allow the attribute color to be an array of numbers") replace_automatic!(plot, :colorrange) do @@ -46,47 +46,47 @@ function color_and_colormap!(plot, intensity = plot[:color]) end end -function calculated_attributes!(T::Type{<: Mesh}, plot) +function calculated_attributes!(T::Type{<:Mesh}, plot) mesha = lift(GeometryBasics.attributes, plot.mesh) - color = haskey(mesha[], :color) ? lift(x-> x[:color], mesha) : plot.color + color = haskey(mesha[], :color) ? lift(x -> x[:color], mesha) : plot.color need_cmap = color_and_colormap!(plot, color) need_cmap || delete!(plot, :colormap) return end -function calculated_attributes!(::Type{<: Union{Heatmap, Image}}, plot) +function calculated_attributes!(::Type{<:Union{Heatmap,Image}}, plot) plot[:color] = plot[3] color_and_colormap!(plot) end -function calculated_attributes!(::Type{<: Surface}, plot) +function calculated_attributes!(::Type{<:Surface}, plot) colors = plot[3] if haskey(plot, :color) color = plot[:color][] - if isa(color, AbstractMatrix{<: Number}) && !(color === to_value(colors)) + if isa(color, AbstractMatrix{<:Number}) && !(color === to_value(colors)) colors = plot[:color] end end color_and_colormap!(plot, colors) end -function calculated_attributes!(::Type{<: MeshScatter}, plot) +function calculated_attributes!(::Type{<:MeshScatter}, plot) color_and_colormap!(plot) end -function calculated_attributes!(::Type{<: Scatter}, plot) +function calculated_attributes!(::Type{<:Scatter}, plot) # calculate base case color_and_colormap!(plot) replace_automatic!(plot, :marker_offset) do # default to middle - lift(x-> to_2d_scale(map(x-> x .* -0.5f0, x)), plot[:markersize]) + lift(x -> to_2d_scale(map(x -> x .* -0.5f0, x)), plot[:markersize]) end replace_automatic!(plot, :markerspace) do lift(plot.markersize) do ms - if ms isa Pixel || (ms isa AbstractVector && all(x-> ms isa Pixel, ms)) + if ms isa Pixel || (ms isa AbstractVector && all(x -> ms isa Pixel, ms)) return :pixel else return :data @@ -95,7 +95,7 @@ function calculated_attributes!(::Type{<: Scatter}, plot) end end -function calculated_attributes!(::Type{T}, plot) where {T<:Union{Lines, LineSegments}} +function calculated_attributes!(::Type{T}, plot) where {T<:Union{Lines,LineSegments}} color_and_colormap!(plot) pos = plot[1][] # extend one color/linewidth per linesegment to be one (the same) color/linewidth per vertex @@ -117,9 +117,9 @@ const atomic_function_symbols = ( ) const atomic_functions = getfield.(Ref(Makie), atomic_function_symbols) -const Atomic{Arg} = Union{map(x-> Combined{x, Arg}, atomic_functions)...} +const Atomic{Arg} = Union{map(x -> Combined{x,Arg}, atomic_functions)...} -function (PT::Type{<: Combined})(parent, transformation, attributes, input_args, converted) +function (PT::Type{<:Combined})(parent, transformation, attributes, input_args, converted) PT(parent, transformation, attributes, input_args, converted, AbstractPlot[]) end @@ -168,7 +168,7 @@ function apply_convert!(P, attributes::Attributes, x::PlotSpec{S}) where S return (plottype(S, P), args) end -function seperate_tuple(args::Observable{<: NTuple{N, Any}}) where N +function seperate_tuple(args::Observable{<:NTuple{N,Any}}) where N ntuple(N) do i lift(args) do x if i <= length(x) @@ -180,7 +180,7 @@ function seperate_tuple(args::Observable{<: NTuple{N, Any}}) where N end end -function (PlotType::Type{<: AbstractPlot{Typ}})(scene::SceneLike, attributes::Attributes, args) where Typ +function (PlotType::Type{<:AbstractPlot{Typ}})(scene::SceneLike, attributes::Attributes, args) where Typ input = convert.(Observable, args) argnodes = lift(input...) do args... convert_arguments(PlotType, args...) @@ -201,7 +201,7 @@ function plot(scene::Scene, plot::AbstractPlot) return plot end -function (PlotType::Type{<: AbstractPlot{Typ}})(scene::SceneLike, attributes::Attributes, input, args) where Typ +function (PlotType::Type{<:AbstractPlot{Typ}})(scene::SceneLike, attributes::Attributes, input, args) where Typ # The argument type of the final plot object is the assumened to stay constant after # argument conversion. This might not always hold, but it simplifies # things quite a bit @@ -209,9 +209,9 @@ function (PlotType::Type{<: AbstractPlot{Typ}})(scene::SceneLike, attributes::At # construct the fully qualified plot type, from the possible incomplete (abstract) # PlotType - FinalType = Combined{Typ, ArgTyp} + FinalType = Combined{Typ,ArgTyp} plot_attributes = merged_get!( - ()-> default_theme(scene, FinalType), + () -> default_theme(scene, FinalType), plotsym(FinalType), scene, attributes ) @@ -238,17 +238,17 @@ end ## generic definitions # If the Combined has no plot func, calculate them -plottype(::Type{<: Combined{Any}}, argvalues...) = plottype(argvalues...) +plottype(::Type{<:Combined{Any}}, argvalues...) = plottype(argvalues...) plottype(::Type{Any}, argvalues...) = plottype(argvalues...) # If it has something more concrete than Any, use it directly -plottype(P::Type{<: Combined{T}}, argvalues...) where T = P +plottype(P::Type{<:Combined{T}}, argvalues...) where T = P ## specialized definitions for types plottype(::AbstractVector, ::AbstractVector, ::AbstractVector) = Scatter plottype(::AbstractVector, ::AbstractVector) = Scatter plottype(::AbstractVector) = Scatter -plottype(::AbstractMatrix{<: Real}) = Heatmap -plottype(::Array{<: AbstractFloat, 3}) = Volume +plottype(::AbstractMatrix{<:Real}) = Heatmap +plottype(::Array{<:AbstractFloat,3}) = Volume plottype(::AbstractString) = Text plottype(::LineString) = Lines @@ -271,11 +271,11 @@ function convert_arguments(P::PlotFunc, args...) end ``` """ -plottype(P1::Type{<: Combined{Any}}, P2::Type{<: Combined{T}}) where T = P2 -plottype(P1::Type{<: Combined{T}}, P2::Type{<: Combined}) where T = P1 +plottype(P1::Type{<:Combined{Any}}, P2::Type{<:Combined{T}}) where T = P2 +plottype(P1::Type{<:Combined{T}}, P2::Type{<:Combined}) where T = P1 # all the plotting functions that get a plot type -const PlotFunc = Union{Type{Any}, Type{<: AbstractPlot}} +const PlotFunc = Union{Type{Any},Type{<:AbstractPlot}} ###################################################################### @@ -300,19 +300,19 @@ end """ Main plotting signatures that plot/plot! route to if no Plot Type is given """ -function plot!(scene::Union{Combined, SceneLike}, P::PlotFunc, attributes::Attributes, args...; kw_attributes...) +function plot!(scene::Union{Combined,SceneLike}, P::PlotFunc, attributes::Attributes, args...; kw_attributes...) attributes = merge!(Attributes(kw_attributes), attributes) argvalues = to_value.(args) PreType = plottype(P, argvalues...) # plottype will lose the argument types, so we just extract the plot func # type and recreate the type with the argument type - PreType = Combined{plotfunc(PreType), typeof(argvalues)} + PreType = Combined{plotfunc(PreType),typeof(argvalues)} convert_keys = intersect(used_attributes(PreType, argvalues...), keys(attributes)) kw_signal = if isempty(convert_keys) # lift(f) isn't supported so we need to catch the empty case Observable(()) else # Remove used attributes from `attributes` and collect them in a `Tuple` to pass them more easily - lift((args...)-> Pair.(convert_keys, args), pop!.(attributes, convert_keys)...) + lift((args...) -> Pair.(convert_keys, args), pop!.(attributes, convert_keys)...) end # call convert_arguments for a first time to get things started converted = convert_arguments(PreType, argvalues...; kw_signal[]...) @@ -321,7 +321,7 @@ function plot!(scene::Union{Combined, SceneLike}, P::PlotFunc, attributes::Attri FinalType, argsconverted = apply_convert!(PreType, attributes, converted) converted_node = Observable(argsconverted) - input_nodes = convert.(Observable, args) + input_nodes = convert.(Observable, args) onany(kw_signal, input_nodes...) do kwargs, args... # do the argument conversion inside a lift result = convert_arguments(FinalType, args...; kwargs...) @@ -340,7 +340,7 @@ plot!(p::Combined) = _plot!(p) _plot!(p::Atomic{T}) where T = p -function _plot!(p::Combined{fn, T}) where {fn, T} +function _plot!(p::Combined{fn,T}) where {fn,T} throw(PlotMethodError(fn, T)) end @@ -356,14 +356,14 @@ function Base.showerror(io::IO, err::PlotMethodError) typed_args = join(string.("::", args), ", ") print(io, "PlotMethodError: no ") - printstyled(io, fn == Any ? "plot" : fn; color=:cyan) + printstyled(io, fn == Any ? "plot" : fn; color = :cyan) print(io, " method for arguments ") - printstyled(io, "($typed_args)"; color=:cyan) + printstyled(io, "($typed_args)"; color = :cyan) print(io, ". To support these arguments, define\n ") - printstyled(io, "plot!(::$(Combined{fn,S} where {S<:T}))"; color=:cyan) + printstyled(io, "plot!(::$(Combined{fn,S} where {S<:T}))"; color = :cyan) print(io, "\nAvailable methods are:\n") for m in methods(plot!) - if m.sig <: Tuple{typeof(plot!), Combined{fn}} + if m.sig <: Tuple{typeof(plot!),Combined{fn}} println(io, " ", m) end end @@ -406,7 +406,7 @@ function extract_scene_attributes!(attributes) return result end -function plot!(scene::SceneLike, P::PlotFunc, attributes::Attributes, input::NTuple{N, Observable}, args::Observable) where {N} +function plot!(scene::SceneLike, P::PlotFunc, attributes::Attributes, input::NTuple{N,Observable}, args::Observable) where {N} # create "empty" plot type - empty meaning containing no plots, just attributes + arguments scene_attributes = extract_scene_attributes!(attributes) if haskey(attributes, :textsize) diff --git a/src/jl_rasterizer/bmp.jl b/src/jl_rasterizer/bmp.jl index bf35407b4d3..a7317eaadf5 100644 --- a/src/jl_rasterizer/bmp.jl +++ b/src/jl_rasterizer/bmp.jl @@ -6,7 +6,7 @@ function writebmp(io, img) # be a multiple of 4 bytes. extrabytes = 4 - ((w * 3) % 4) (extrabytes == 4) && (extrabytes = 0) - paddedsize = ((w * 3) + extrabytes) * h; + paddedsize = ((w * 3) + extrabytes) * h # file header write(io, b"BM") @@ -34,7 +34,7 @@ function writebmp(io, img) write(io, reinterpret(UInt8, green(rgb))) write(io, reinterpret(UInt8, red(rgb))) end - for i = 1:extrabytes + for i in 1:extrabytes write(io, UInt8(0)) end end diff --git a/src/jl_rasterizer/main.jl b/src/jl_rasterizer/main.jl index 471d2a98bde..33d4c8a7a9b 100644 --- a/src/jl_rasterizer/main.jl +++ b/src/jl_rasterizer/main.jl @@ -7,13 +7,13 @@ using Makie: orthographicprojection (c[1] - a[1]) * (b[2] - a[2]) - (c[2] - a[2]) * (b[1] - a[1]) end -@inline function src_alpha(c::T) where T <: Colorant +@inline function src_alpha(c::T) where T<:Colorant a = alpha(c) a == 0.0 && return zero(T) c ./ a end -one_minus_alpha(c::T) where {T <: Colorant} = one(T) .- src_alpha(c) +one_minus_alpha(c::T) where {T<:Colorant} = one(T) .- src_alpha(c) blend(source, dest, src_func, dest_func) = clamp01(src_func(source) .+ dest_func(dest)) ColorTypes.alpha(x::StaticVector) = x[4] @@ -21,13 +21,13 @@ function standard_transparency(source, dest::T) where T (alpha(source) .* source) .+ ((one(eltype(T)) - alpha(source)) .* dest) end -mutable struct FixedGeomView{GeomOut, VT} +mutable struct FixedGeomView{GeomOut,VT} buffer::Vector{GeomOut} view::VT idx::Int end -struct TriangleStripView{T} <: AbstractVector{NTuple{3, T}} +struct TriangleStripView{T} <: AbstractVector{NTuple{3,T}} parent::AbstractVector{T} end @@ -36,16 +36,16 @@ Base.size(x::TriangleStripView) = (2,) function Base.getindex(x::TriangleStripView, i) if i === 1 - return ntuple(i-> x.parent[i], 3) + return ntuple(i -> x.parent[i], 3) elseif i === 2 - return map(i-> x.parent[i], (3, 2, 4)) + return map(i -> x.parent[i], (3, 2, 4)) else error("Out of bounds") end end function FixedGeomView(T, max_primitives, primitive_in, primitive_out) - buffer = Vector{Tuple{Point4f, T}}(undef, max_primitives) + buffer = Vector{Tuple{Point4f,T}}(undef, max_primitives) # TODO implement primitive_in and out correctly # this is for triangle_strip and 4 max_primitives if max_primitives != 4 || primitive_out != :triangle_strip @@ -72,7 +72,7 @@ function Base.push!(A::FixedGeomView, element) return end -struct JLRasterizer{Vertex, Args, FragN, VS, FS, GS, GV, EF} +struct JLRasterizer{Vertex,Args,FragN,VS,FS,GS,GV,EF} vertexshader::VS fragmentshader::FS @@ -81,14 +81,14 @@ struct JLRasterizer{Vertex, Args, FragN, VS, FS, GS, GV, EF} emit::EF end -function JLRasterizer{Vertex, Args, FragN}( - vertexshader::VS, - fragmentshader::FS, - geometryshader::GS, - geometry_view::GV, - emit::EF - ) where {Vertex, Args, FragN, VS, FS, GS, GV, EF} - JLRasterizer{Vertex, Args, FragN, VS, FS, GS, GV, EF}( +function JLRasterizer{Vertex,Args,FragN}( + vertexshader::VS, + fragmentshader::FS, + geometryshader::GS, + geometry_view::GV, + emit::EF +) where {Vertex,Args,FragN,VS,FS,GS,GV,EF} + JLRasterizer{Vertex,Args,FragN,VS,FS,GS,GV,EF}( vertexshader, fragmentshader, geometryshader, @@ -108,21 +108,21 @@ function geometry_return_type(vertex_array, vertexshader, geometryshader, unifor typ end -arglength(::Type{T}) where {T <: Tuple} = length(T.parameters) -arglength(::Type{T}) where {T <: AbstractArray} = 1 +arglength(::Type{T}) where {T<:Tuple} = length(T.parameters) +arglength(::Type{T}) where {T<:AbstractArray} = 1 arglength(::Type{T}) where {T} = nfields(T) function rasterizer( - vertexarray::AbstractArray, - uniforms::Tuple, - vertexshader::Function, - fragmentshader::Function; - geometryshader = nothing, - max_primitives = 4, - primitive_in = :points, - primitive_out = :triangle_strip, - ) + vertexarray::AbstractArray, + uniforms::Tuple, + vertexshader::Function, + fragmentshader::Function; + geometryshader = nothing, + max_primitives = 4, + primitive_in = :points, + primitive_out = :triangle_strip +) emit, geometry_view = nothing, nothing fragment_in_ndim = if !isnothing(geometryshader) @@ -132,7 +132,7 @@ function rasterizer( arglength(T) else # when we don't have a geometry shader, vertex shader will feed fragment shader - T = Base.Core.Inference.return_type(vertexshader, Tuple{eltype(vertexarray), map(typeof, uniforms)...}) + T = Base.Core.Inference.return_type(vertexshader, Tuple{eltype(vertexarray),map(typeof, uniforms)...}) if T <: Tuple # TODO error handling arglength(T.parameters[2]) @@ -141,7 +141,7 @@ function rasterizer( end end - raster = JLRasterizer{eltype(vertexarray), typeof(uniforms), fragment_in_ndim}( + raster = JLRasterizer{eltype(vertexarray),typeof(uniforms),fragment_in_ndim}( vertexshader, fragmentshader, geometryshader, @@ -154,7 +154,7 @@ end Base.@pure Next(::Val{N}) where {N} = Val(N - 1) -function interpolate(bary, face::NTuple{N, T}, vn::Val{0}, aggregate) where {N, T} +function interpolate(bary, face::NTuple{N,T}, vn::Val{0}, aggregate) where {N,T} if T <: Tuple aggregate else @@ -183,10 +183,11 @@ function clip2pixel_space(position, resolution) end -function (r::JLRasterizer{Vert, Args, FragN})( - canvas, vertex_array::AbstractArray{Vert}, uniforms::Args - ) where {Vert, Args, FragN} - framebuffers = canvas.color; depthbuffer = canvas.depth +function (r::JLRasterizer{Vert,Args,FragN})( + canvas, vertex_array::AbstractArray{Vert}, uniforms::Args +) where {Vert,Args,FragN} + framebuffers = canvas.color + depthbuffer = canvas.depth resolution = Vec2f(size(framebuffers[1])) # hoisting out functions... Seems to help inference a bit. Or not? vshader = r.vertexshader @@ -219,8 +220,8 @@ function (r::JLRasterizer{Vert, Args, FragN})( mini = max.(reduce(broadcastmin, f), 1f0) maxi = min.(reduce(broadcastmax, f), resolution) area = edge_function(f[1], f[2], f[3]) - for y = mini[2]:maxi[2] - for x = mini[1]:maxi[1] + for y in mini[2]:maxi[2] + for x in mini[1]:maxi[1] p = Vec(x, y) w = Vec( edge_function(f[2], f[3], p), @@ -228,7 +229,7 @@ function (r::JLRasterizer{Vert, Args, FragN})( edge_function(f[1], f[2], p) ) yi, xi = round(Int, y), round(Int, x) - if all(w-> w >= 0f0, w) && checkbounds(Bool, framebuffers[1], yi, xi) + if all(w -> w >= 0f0, w) && checkbounds(Bool, framebuffers[1], yi, xi) bary = w / area depth = bary[1] * depths[1] + bary[2] * depths[2] + bary[3] * depths[3] @@ -237,7 +238,7 @@ function (r::JLRasterizer{Vert, Args, FragN})( depthbuffer[yi, xi] = depth fragment_in = interpolate(bary, vertex_out, FragNVal) fragment_out = fshader(fragment_in, uniforms...) - for i = eachindex(fragment_out) + for i in eachindex(fragment_out) src_color = framebuffers[i][yi, xi] dest_color = fragment_out[i] fragments_drawn += 1 @@ -270,12 +271,12 @@ function smoothstep(edge0, edge1, x::T) where T end function aastep(threshold1::T, value) where T - afwidth = norm(Vec2f(dFdx(value), dFdy(value))) * T(1.05); + afwidth = norm(Vec2f(dFdx(value), dFdy(value))) * T(1.05) smoothstep(threshold1 - afwidth, threshold1 + afwidth, value) end function aastep(threshold1::T, threshold2::T, value::T) where T - afwidth = norm(Vec2f(dFdx(value), dFdy(value))) * T(1.05); + afwidth = norm(Vec2f(dFdx(value), dFdy(value))) * T(1.05) return ( smoothstep(threshold1 - afwidth, threshold1 + afwidth, value) - smoothstep(threshold2 - afwidth, threshold2 + afwidth, value) @@ -302,8 +303,8 @@ mutable struct Uniforms{F} distance_func::F end -struct VertexCS{N, T} - position::Vec{N, T} +struct VertexCS{N,T} + position::Vec{N,T} color::Vec4f scale::Vec2f end @@ -318,7 +319,7 @@ function vert_particles(vertex, uniforms) p = vertex.position scale = vertex.scale return Vertex2Geom( - Vec4f(0,0,1,1), + Vec4f(0, 0, 1, 1), vertex.color, Vec4f(p[1], p[2], scale[1], scale[2]) ) @@ -371,25 +372,27 @@ function sdf2color(dist, bg_color, color) end function frag_particles(geom_out, uniforms, image) - uv = geom_out[1]; color = geom_out[2] + uv = geom_out[1] + color = geom_out[2] dist = -image[uv][1] bg_color = Vec4f(0f0, 0f0, 0f0, 0f0) - (sdf2color(dist, bg_color, color), ) + (sdf2color(dist, bg_color, color),) end function frag_particles(geom_out, uniforms) - uv = geom_out[1]; color = geom_out[2] + uv = geom_out[1] + color = geom_out[2] dist = uniforms.distance_func(uv) bg_color = Vec4f(0f0, 0f0, 0f0, 0f0) # col = Vec4f(norm(uv .- 0.5), 0, 0, 1) - (sdf2color(dist, bg_color, color), ) + (sdf2color(dist, bg_color, color),) end resolution = (1024, 1024) proj = Makie.orthographicprojection(Rect2(0, 0, resolution...), -10_000f0, 10_000f0) -circle(uv::Vec{2, T}) where {T} = -T(norm(uv .- 0.5) - 0.5) +circle(uv::Vec{2,T}) where {T} = -T(norm(uv .- 0.5) - 0.5) uniforms = Uniforms( proj, @@ -403,10 +406,10 @@ N = 10 middle = Vec2f(resolution) / 2f0 radius = (min(resolution...) / 2f0) - 50 vertices = [(VertexCS( - Vec2f((sin(2pi * (i / N)) , cos(2pi * (i / N))) .* radius) .+ middle, - Vec4f(1, i/N, 0, 1), + Vec2f((sin(2pi * (i / N)), cos(2pi * (i / N))) .* radius) .+ middle, + Vec4f(1, i / N, 0, 1), Vec2f(40, 40) -),) for i = 1:N] +),) for i in 1:N] raster, rest = rasterizer( @@ -417,16 +420,16 @@ raster, rest = rasterizer( geometryshader = geom_particles, max_primitives = 4, primitive_in = :points, - primitive_out = :triangle_strip, + primitive_out = :triangle_strip ) struct Canvas{N} - color::NTuple{N, Matrix{RGBA{Float32}}} + color::NTuple{N,Matrix{RGBA{Float32}}} depth::Matrix{Float32} end function Canvas(xdim::Integer, ydim::Integer) - color = fill(RGBA{Float32}(0,0,0,0), xdim, ydim) + color = fill(RGBA{Float32}(0, 0, 0, 0), xdim, ydim) depth = ones(Float32, xdim, ydim) return Canvas((color,), depth) end diff --git a/src/layouting/boundingbox.jl b/src/layouting/boundingbox.jl index 18757dcb7a5..c6a6c086075 100644 --- a/src/layouting/boundingbox.jl +++ b/src/layouting/boundingbox.jl @@ -3,7 +3,7 @@ function parent_transform(x) isnothing(p) ? Mat4f(I) : p.model[] end -function boundingbox(x, exclude = (p)-> false) +function boundingbox(x, exclude = (p) -> false) return parent_transform(x) * data_limits(x, exclude) end @@ -130,7 +130,7 @@ _is_latex_string(x::LaTeXString) = true _is_latex_string(other) = false function text_bb(str, font, size) - rot = Quaternionf(0,0,0,1) + rot = Quaternionf(0, 0, 0, 1) fonts = nothing # TODO: remove the arg if possible layout = layout_text( str, size, font, fonts, Vec2f(0), rot, 0.5, 1.0, @@ -142,23 +142,23 @@ end Calculate an approximation of a tight rectangle around a 2D rectangle rotated by `angle` radians. This is not perfect but works well enough. Check an A vs X to see the difference. """ -function rotatedrect(rect::Rect{2, T}, angle)::Rect{2, T} where T +function rotatedrect(rect::Rect{2,T}, angle)::Rect{2,T} where T ox, oy = rect.origin wx, wy = rect.widths - points = Mat{2, 4, T}( + points = Mat{2,4,T}( ox, oy, - ox, oy+wy, - ox+wx, oy, - ox+wx, oy+wy + ox, oy + wy, + ox + wx, oy, + ox + wx, oy + wy ) - mrot = Mat{2, 2, T}( + mrot = Mat{2,2,T}( cos(angle), -sin(angle), sin(angle), cos(angle) ) rotated = mrot * points - rmins = minimum(rotated; dims=2) - rmaxs = maximum(rotated; dims=2) + rmins = minimum(rotated; dims = 2) + rmaxs = maximum(rotated; dims = 2) return Rect2(rmins..., (rmaxs .- rmins)...) end diff --git a/src/layouting/data_limits.jl b/src/layouting/data_limits.jl index 4d3e624d2a5..55a1e8e72d5 100644 --- a/src/layouting/data_limits.jl +++ b/src/layouting/data_limits.jl @@ -1,9 +1,9 @@ _isfinite(x) = isfinite(x) _isfinite(x::VecTypes) = all(isfinite, x) -isfinite_rect(x::Rect) = all(isfinite, x.origin) && all(isfinite, x.widths) -scalarmax(x::Union{Tuple, AbstractArray}, y::Union{Tuple, AbstractArray}) = max.(x, y) +isfinite_rect(x::Rect) = all(isfinite, x.origin) && all(isfinite, x.widths) +scalarmax(x::Union{Tuple,AbstractArray}, y::Union{Tuple,AbstractArray}) = max.(x, y) scalarmax(x, y) = max(x, y) -scalarmin(x::Union{Tuple, AbstractArray}, y::Union{Tuple, AbstractArray}) = min.(x, y) +scalarmin(x::Union{Tuple,AbstractArray}, y::Union{Tuple,AbstractArray}) = min.(x, y) scalarmin(x, y) = min(x, y) extrema_nan(itr::Pair) = (itr[1], itr[2]) @@ -35,12 +35,12 @@ function distinct_extrema_nan(x) lo == hi ? (lo - 0.5f0, hi + 0.5f0) : (lo, hi) end -function point_iterator(plot::Union{Scatter, MeshScatter, Lines, LineSegments}) +function point_iterator(plot::Union{Scatter,MeshScatter,Lines,LineSegments}) return plot.positions[] end # TODO? -function point_iterator(text::Text{<: Tuple{<: Union{GlyphCollection, AbstractVector{GlyphCollection}}}}) +function point_iterator(text::Text{<:Tuple{<:Union{GlyphCollection,AbstractVector{GlyphCollection}}}}) if is_data_space(text.markerspace[]) return decompose(Point, boundingbox(text)) else @@ -117,7 +117,7 @@ end function point_iterator(x::Volume) axes = (x[1], x[2], x[3]) - extremata = map(extrema∘to_value, axes) + extremata = map(extrema ∘ to_value, axes) minpoint = Point3f(first.(extremata)...) widths = last.(extremata) .- first.(extremata) rect = Rect3f(minpoint, Vec3f(widths)) @@ -126,7 +126,7 @@ end function foreach_plot(f, s::Scene) foreach_plot(f, s.plots) - foreach(sub-> foreach_plot(f, sub), s.children) + foreach(sub -> foreach_plot(f, sub), s.children) end foreach_plot(f, s::Figure) = foreach_plot(f, s.scene) @@ -196,7 +196,7 @@ function data_limits(plot::AbstractPlot) limits_from_transformed_points(iterate_transformed(plot)) end -function _update_rect(rect::Rect{N, T}, point::Point{N, T}) where {N, T} +function _update_rect(rect::Rect{N,T}, point::Point{N,T}) where {N,T} mi = minimum(rect) ma = maximum(rect) mis_mas = map(mi, ma, point) do _mi, _ma, _p @@ -216,7 +216,7 @@ function limits_from_transformed_points(points_iterator) return bb end -function data_limits(scenelike, exclude=(p)-> false) +function data_limits(scenelike, exclude = (p) -> false) bb_ref = Base.RefValue(Rect3f()) foreach_plot(scenelike) do plot if !exclude(plot) diff --git a/src/layouting/layouting.jl b/src/layouting/layouting.jl index 024500aecc2..342cb9ba21a 100644 --- a/src/layouting/layouting.jl +++ b/src/layouting/layouting.jl @@ -39,10 +39,10 @@ end Compute a GlyphCollection for a `string` given fontsize, font, align, rotation, model, justification, and lineheight. """ function layout_text( - string::AbstractString, fontsize::Union{AbstractVector, Number}, - font, fonts, align, rotation, justification, lineheight, color, - strokecolor, strokewidth, word_wrap_width - ) + string::AbstractString, fontsize::Union{AbstractVector,Number}, + font, fonts, align, rotation, justification, lineheight, color, + strokecolor, strokewidth, word_wrap_width +) ft_font = to_font(font) rscale = to_fontsize(fontsize) @@ -68,13 +68,13 @@ This layout in text coordinates, relative to the anchor point [0,0] can then be rotated to wherever it is needed in the plot. """ function glyph_collection( - str::AbstractString, font_per_char, fontscale_px, halign, valign, - lineheight_factor, justification, rotation, color, - strokecolor, strokewidth, word_wrap_width - ) + str::AbstractString, font_per_char, fontscale_px, halign, valign, + lineheight_factor, justification, rotation, color, + strokecolor, strokewidth, word_wrap_width +) isempty(str) && return GlyphCollection( - [], [], Point3f[],FreeTypeAbstraction.FontExtent{Float32}[], + [], [], Point3f[], FreeTypeAbstraction.FontExtent{Float32}[], Vec2f[], Float32[], RGBAf[], RGBAf[], Float32[]) # collect information about every character in the string @@ -114,13 +114,13 @@ function glyph_collection( x += ci.extent.hadvance * ci.scale if 0 < word_wrap_width < x && last_space_local_idx != 0 && - ((ci.char in (' ', '\n')) || i == length(charinfos)) + ((ci.char in (' ', '\n')) || i == length(charinfos)) newline_offset = xs[end][last_space_local_idx + 1] - push!(xs, xs[end][last_space_local_idx+1:end] .- newline_offset) - xs[end-1] = xs[end-1][1:last_space_local_idx] + push!(xs, xs[end][(last_space_local_idx + 1):end] .- newline_offset) + xs[end - 1] = xs[end - 1][1:last_space_local_idx] push!(lineinfos, view(charinfos, last_line_start:last_space_global_idx)) - last_line_start = last_space_global_idx+1 + last_line_start = last_space_global_idx + 1 x = xs[end][end] + ci.extent.hadvance * ci.scale # TODO Do we need to redo the metrics for newlines? @@ -135,7 +135,7 @@ function glyph_collection( push!(xs, Float32[]) push!(lineinfos, view(charinfos, last_line_start:i)) last_space_local_idx = 0 - last_line_start = i+1 + last_line_start = i + 1 x = 0f0 elseif i == length(charinfos) push!(lineinfos, view(charinfos, last_line_start:i)) @@ -270,7 +270,7 @@ function glyph_collection( end # function to concatenate vectors with a value between every pair -function padded_vcat(arrs::AbstractVector{T}, fillvalue) where T <: AbstractVector{S} where S +function padded_vcat(arrs::AbstractVector{T}, fillvalue) where T<:AbstractVector{S} where S n = sum(length.(arrs)) arr = fill(convert(S, fillvalue), n + length(arrs) - 1) @@ -335,7 +335,7 @@ function text_quads(atlas::TextureAtlas, position::VecTypes, gc::GlyphCollection return pos, char_offsets, quad_offsets, uvs, scales end -function text_quads(atlas::TextureAtlas, position::Vector, gcs::Vector{<: GlyphCollection}, offset, transfunc, space) +function text_quads(atlas::TextureAtlas, position::Vector, gcs::Vector{<:GlyphCollection}, offset, transfunc, space) ps = apply_transform(transfunc, position, space) pos = [to_ndim(Point3f, p, 0) for (p, gc) in zip(ps, gcs) for _ in gc.origins] diff --git a/src/layouting/transformation.jl b/src/layouting/transformation.jl index 98af0448537..a0d1f1e89f6 100644 --- a/src/layouting/transformation.jl +++ b/src/layouting/transformation.jl @@ -1,9 +1,9 @@ Base.parent(t::Transformation) = isassigned(t.parent) ? t.parent[] : nothing -function Transformation(transform_func=identity; - scale=Vec3f(1), - translation=Vec3f(0), - rotation=Quaternionf(0, 0, 0, 1)) +function Transformation(transform_func = identity; + scale = Vec3f(1), + translation = Vec3f(0), + rotation = Quaternionf(0, 0, 0, 1)) scale_o = convert(Observable{Vec3f}, scale) translation_o = convert(Observable{Vec3f}, translation) @@ -19,9 +19,9 @@ function Transformation(transform_func=identity; end function Transformation(transformable::Transformable; - scale=Vec3f(1), - translation=Vec3f(0), - rotation=Quaternionf(0, 0, 0, 1)) + scale = Vec3f(1), + translation = Vec3f(0), + rotation = Quaternionf(0, 0, 0, 1)) scale_o = convert(Observable{Vec3f}, scale) translation_o = convert(Observable{Vec3f}, translation) @@ -62,19 +62,19 @@ function translated(scene::Scene; kw_args...) end function transform!( - scene::Transformable; - translation = Vec3f(0), - scale = Vec3f(1), - rotation = 0.0, - ) + scene::Transformable; + translation = Vec3f(0), + scale = Vec3f(1), + rotation = 0.0 +) translate!(scene, to_value(translation)) scale!(scene, to_value(scale)) rotate!(scene, to_value(rotation)) end function transform!( - scene::Transformable, attributes::Union{Attributes, AbstractDict} - ) + scene::Transformable, attributes::Union{Attributes,AbstractDict} +) transform!(scene; attributes...) end @@ -171,20 +171,20 @@ Translate the scene relative to its current position. """ translate!(::Type{T}, scene::Transformable, xyz...) where T = translate!(T, scene, xyz) -function transform!(scene::Transformable, x::Tuple{Symbol, <: Number}) +function transform!(scene::Transformable, x::Tuple{Symbol,<:Number}) plane, dimval = string(x[1]), Float32(x[2]) - if length(plane) != 2 || (!all(x-> x in ('x', 'y', 'z'), plane)) + if length(plane) != 2 || (!all(x -> x in ('x', 'y', 'z'), plane)) error("plane needs to define a 2D plane in xyz. It should only contain 2 symbols out of (:x, :y, :z). Found: $plane") end - if all(x-> x in ('x', 'y'), plane) # xy plane + if all(x -> x in ('x', 'y'), plane) # xy plane translate!(scene, 0, 0, dimval) - elseif all(x-> x in ('x', 'z'), plane) # xz plane + elseif all(x -> x in ('x', 'z'), plane) # xz plane rotate!(scene, Vec3f(1, 0, 0), 0.5pi) translate!(scene, 0, dimval, 0) else #yz plane r1 = qrotation(Vec3f(0, 1, 0), 0.5pi) r2 = qrotation(Vec3f(1, 0, 0), 0.5pi) - rotate!(scene, r2 * r1) + rotate!(scene, r2 * r1) translate!(scene, dimval, 0, 0) end scene @@ -200,10 +200,10 @@ transform_func_obs(x) = transformation(x).transform_func Apply the data transform func to the data if the space matches one of the the transformation spaces (currently only :data is transformed) """ -apply_transform(f, data, space) = space == :data ? apply_transform(f, data) : data -function apply_transform(f::Observable, data::Observable, space::Observable) - return lift((f, d, s)-> apply_transform(f, d, s), f, data, space) -end +apply_transform(f, data, space) = space == :data ? apply_transform(f, data) : data +function apply_transform(f::Observable, data::Observable, space::Observable) + return lift((f, d, s) -> apply_transform(f, d, s), f, data, space) +end """ apply_transform(f, data) @@ -216,26 +216,26 @@ apply_transform(f::typeof(identity), x::VecTypes) = x apply_transform(f::typeof(identity), x::Number) = x apply_transform(f::typeof(identity), x::ClosedInterval) = x -apply_transform(f::NTuple{2, typeof(identity)}, x) = x -apply_transform(f::NTuple{2, typeof(identity)}, x::AbstractArray) = x -apply_transform(f::NTuple{2, typeof(identity)}, x::VecTypes) = x -apply_transform(f::NTuple{2, typeof(identity)}, x::Number) = x -apply_transform(f::NTuple{2, typeof(identity)}, x::ClosedInterval) = x +apply_transform(f::NTuple{2,typeof(identity)}, x) = x +apply_transform(f::NTuple{2,typeof(identity)}, x::AbstractArray) = x +apply_transform(f::NTuple{2,typeof(identity)}, x::VecTypes) = x +apply_transform(f::NTuple{2,typeof(identity)}, x::Number) = x +apply_transform(f::NTuple{2,typeof(identity)}, x::ClosedInterval) = x -apply_transform(f::NTuple{3, typeof(identity)}, x) = x -apply_transform(f::NTuple{3, typeof(identity)}, x::AbstractArray) = x -apply_transform(f::NTuple{3, typeof(identity)}, x::VecTypes) = x -apply_transform(f::NTuple{3, typeof(identity)}, x::Number) = x -apply_transform(f::NTuple{3, typeof(identity)}, x::ClosedInterval) = x +apply_transform(f::NTuple{3,typeof(identity)}, x) = x +apply_transform(f::NTuple{3,typeof(identity)}, x::AbstractArray) = x +apply_transform(f::NTuple{3,typeof(identity)}, x::VecTypes) = x +apply_transform(f::NTuple{3,typeof(identity)}, x::Number) = x +apply_transform(f::NTuple{3,typeof(identity)}, x::ClosedInterval) = x -struct PointTrans{N, F} +struct PointTrans{N,F} f::F - function PointTrans{N}(f::F) where {N, F} + function PointTrans{N}(f::F) where {N,F} if !hasmethod(f, Tuple{Point{N}}) error("PointTrans with parameter N = $N must be applicable to an argument of type Point{$N}.") end - new{N, F}(f) + new{N,F}(f) end end @@ -246,38 +246,38 @@ function apply_transform(f::PointTrans{N}, point::Point{N}) where N return f.f(point) end -function apply_transform(f::PointTrans{N1}, point::Point{N2}) where {N1, N2} - p_dim = to_ndim(Point{N1, Float32}, point, 0.0) +function apply_transform(f::PointTrans{N1}, point::Point{N2}) where {N1,N2} + p_dim = to_ndim(Point{N1,Float32}, point, 0.0) p_trans = f.f(p_dim) if N1 < N2 - p_large = ntuple(i-> i <= N1 ? p_trans[i] : point[i], N2) - return Point{N2, Float32}(p_large) + p_large = ntuple(i -> i <= N1 ? p_trans[i] : point[i], N2) + return Point{N2,Float32}(p_large) else - return to_ndim(Point{N2, Float32}, p_trans, 0.0) + return to_ndim(Point{N2,Float32}, p_trans, 0.0) end end function apply_transform(f, data::AbstractArray) - map(point-> apply_transform(f, point), data) + map(point -> apply_transform(f, point), data) end -function apply_transform(f::Tuple{Any, Any}, point::VecTypes{2}) +function apply_transform(f::Tuple{Any,Any}, point::VecTypes{2}) Point2{Float32}( f[1](point[1]), f[2](point[2]), ) end # ambiguity fix -apply_transform(f::NTuple{2, typeof(identity)}, point::VecTypes{2}) = point +apply_transform(f::NTuple{2,typeof(identity)}, point::VecTypes{2}) = point -function apply_transform(f::Tuple{Any, Any}, point::VecTypes{3}) +function apply_transform(f::Tuple{Any,Any}, point::VecTypes{3}) apply_transform((f..., identity), point) end # ambiguity fix -apply_transform(f::NTuple{2, typeof(identity)}, point::VecTypes{3}) = point +apply_transform(f::NTuple{2,typeof(identity)}, point::VecTypes{3}) = point -function apply_transform(f::Tuple{Any, Any, Any}, point::VecTypes{3}) +function apply_transform(f::Tuple{Any,Any,Any}, point::VecTypes{3}) Point3{Float32}( f[1](point[1]), f[2](point[2]), @@ -285,13 +285,13 @@ function apply_transform(f::Tuple{Any, Any, Any}, point::VecTypes{3}) ) end # ambiguity fix -apply_transform(f::NTuple{3, typeof(identity)}, point::VecTypes{3}) = point +apply_transform(f::NTuple{3,typeof(identity)}, point::VecTypes{3}) = point apply_transform(f, number::Number) = f(number) function apply_transform(f::Observable, data::Observable) - return lift((f, d)-> apply_transform(f, d), f, data) + return lift((f, d) -> apply_transform(f, d), f, data) end apply_transform(f, itr::Pair) = apply_transform(f, itr[1]) => apply_transform(f, itr[2]) @@ -318,8 +318,8 @@ end # ambiguity fix apply_transform(f::typeof(identity), r::Rect) = r -apply_transform(f::NTuple{2, typeof(identity)}, r::Rect) = r -apply_transform(f::NTuple{3, typeof(identity)}, r::Rect) = r +apply_transform(f::NTuple{2,typeof(identity)}, r::Rect) = r +apply_transform(f::NTuple{3,typeof(identity)}, r::Rect) = r pseudolog10(x) = sign(x) * log10(abs(x) + 1) @@ -364,7 +364,7 @@ inverse_transform(::typeof(identity)) = identity inverse_transform(::typeof(log10)) = exp10 inverse_transform(::typeof(log)) = exp inverse_transform(::typeof(log2)) = exp2 -inverse_transform(::typeof(sqrt)) = x -> x ^ 2 +inverse_transform(::typeof(sqrt)) = x -> x^2 inverse_transform(::typeof(pseudolog10)) = inv_pseudolog10 inverse_transform(F::Tuple) = map(inverse_transform, F) inverse_transform(::typeof(logit)) = logistic @@ -372,7 +372,7 @@ inverse_transform(s::Symlog10) = x -> inv_symlog10(x, s.low, s.high) inverse_transform(s) = nothing function is_identity_transform(t) - return t === identity || t isa Tuple && all(x-> x === identity, t) + return t === identity || t isa Tuple && all(x -> x === identity, t) end @@ -383,5 +383,3 @@ end # by heatmaps or images zvalue2d(x)::Float32 = Makie.translation(x)[][3] + zvalue2d(x.parent) zvalue2d(::Nothing)::Float32 = 0f0 - - diff --git a/src/makielayout/blocks.jl b/src/makielayout/blocks.jl index a3f709aceb7..059c8aea685 100644 --- a/src/makielayout/blocks.jl +++ b/src/makielayout/blocks.jl @@ -15,7 +15,7 @@ macro Block(name::Symbol, body::Expr = Expr(:block)) structdef = quote mutable struct $name <: Makie.Block - parent::Union{Figure, Scene, Nothing} + parent::Union{Figure,Scene,Nothing} layoutobservables::Makie.LayoutObservables{GridLayout} blockscene::Scene end @@ -28,7 +28,7 @@ macro Block(name::Symbol, body::Expr = Expr(:block)) i_forwarded_layout = findfirst( x -> x isa Expr && x.head == :macrocall && - x.args[1] == Symbol("@forwarded_layout"), + x.args[1] == Symbol("@forwarded_layout"), body.args ) has_forwarded_layout = i_forwarded_layout !== nothing @@ -67,7 +67,7 @@ macro Block(name::Symbol, body::Expr = Expr(:block)) sym in ($((attrs !== nothing ? [QuoteNode(a.symbol) for a in attrs] : [])...),) end - function Makie.default_attribute_values(::Type{$(name)}, scene::Union{Scene, Nothing}) + function Makie.default_attribute_values(::Type{$(name)}, scene::Union{Scene,Nothing}) sceneattrs = scene === nothing ? Attributes() : theme(scene) curdeftheme = Makie.current_default_theme() @@ -77,9 +77,9 @@ macro Block(name::Symbol, body::Expr = Expr(:block)) function Makie.attribute_default_expressions(::Type{$name}) $( if attrs === nothing - Dict{Symbol, String}() + Dict{Symbol,String}() else - Dict{Symbol, String}([a.symbol => _defaultstring(a.default) for a in attrs]) + Dict{Symbol,String}([a.symbol => _defaultstring(a.default) for a in attrs]) end ) end @@ -88,8 +88,8 @@ macro Block(name::Symbol, body::Expr = Expr(:block)) Dict( $( (attrs !== nothing ? - [Expr(:call, :(=>), QuoteNode(a.symbol), a.docs) for a in attrs] : - [])... + [Expr(:call, :(=>), QuoteNode(a.symbol), a.docs) for a in attrs] : + [])... ) ) end @@ -197,7 +197,7 @@ end function extract_attributes!(body) i = findfirst( (x -> x isa Expr && x.head == :macrocall && x.args[1] == Symbol("@attributes") && - x.args[3] isa Expr && x.args[3].head == :block), + x.args[3] isa Expr && x.args[3].head == :block), body.args ) if i === nothing @@ -285,7 +285,7 @@ get_top_parent(gp::GridPosition) = GridLayoutBase.top_parent(gp.layout) get_top_parent(gp::GridSubposition) = get_top_parent(gp.parent) function _block(T::Type{<:Block}, - gp::Union{GridPosition, GridSubposition}, args...; kwargs...) + gp::Union{GridPosition,GridSubposition}, args...; kwargs...) top_parent = get_top_parent(gp) if top_parent === nothing @@ -295,17 +295,17 @@ function _block(T::Type{<:Block}, b end -function _block(T::Type{<:Block}, fig_or_scene::Union{Figure, Scene}, - args...; bbox = nothing, kwargs...) +function _block(T::Type{<:Block}, fig_or_scene::Union{Figure,Scene}, + args...; bbox = nothing, kwargs...) # first sort out all user kwargs that correspond to block attributes kwdict = Dict(kwargs) - + if haskey(kwdict, :textsize) throw(ArgumentError("The attribute `textsize` has been renamed to `fontsize` in Makie v0.19. Please change all occurrences of `textsize` to `fontsize` or revert back to an earlier version.")) end - attribute_kwargs = Dict{Symbol, Any}() + attribute_kwargs = Dict{Symbol,Any}() for (key, value) in kwdict if is_attribute(T, key) attribute_kwargs[key] = pop!(kwdict, key) @@ -323,18 +323,18 @@ function _block(T::Type{<:Block}, fig_or_scene::Union{Figure, Scene}, # make a final attribute dictionary using different priorities # for the different themes - attributes = Dict{Symbol, Any}() + attributes = Dict{Symbol,Any}() for (key, val) in default_attrs # give kwargs priority if haskey(attribute_kwargs, key) attributes[key] = attribute_kwargs[key] - # otherwise scene theme + # otherwise scene theme elseif haskey(typekey_scene_attrs, key) attributes[key] = typekey_scene_attrs[key] - # otherwise global theme + # otherwise global theme elseif haskey(typekey_attrs, key) attributes[key] = typekey_attrs[key] - # otherwise its the value from the type default theme + # otherwise its the value from the type default theme else attributes[key] = val end @@ -470,7 +470,7 @@ function connect_block_layoutobservables!(@nospecialize(block), layout_width, la return end -@inline function Base.setproperty!(x::T, key::Symbol, value) where T <: Block +@inline function Base.setproperty!(x::T, key::Symbol, value) where T<:Block if hasfield(T, key) if fieldtype(T, key) <: Observable if value isa Observable @@ -479,7 +479,7 @@ end obs = fieldtype(T, key) getfield(x, key)[] = convert_for_attribute(observable_type(obs), value) else - setfield!(x, key, value) + setfield!(x, key, value) end else # this will throw correctly @@ -490,7 +490,7 @@ end # treat all blocks as scalars when broadcasting Base.Broadcast.broadcastable(l::Block) = Ref(l) -function Base.show(io::IO, ::T) where T <: Block +function Base.show(io::IO, ::T) where T<:Block print(io, "$T()") end diff --git a/src/makielayout/blocks/axis.jl b/src/makielayout/blocks/axis.jl index 7c8f881f39d..971d9f0aee4 100644 --- a/src/makielayout/blocks/axis.jl +++ b/src/makielayout/blocks/axis.jl @@ -60,7 +60,7 @@ function register_events!(ax, scene) return Consume(false) end - interactions = Dict{Symbol, Tuple{Bool, Any}}() + interactions = Dict{Symbol,Tuple{Bool,Any}}() setfield!(ax, :interactions, interactions) onany(process_axis_event, ax, mouseeventhandle.obs) @@ -83,7 +83,7 @@ function update_axis_camera(camera::Camera, t, lims, xrev::Bool, yrev::Bool) farclip = 10_000f0 # we are computing transformed camera position, so this isn't space dependent - tlims = Makie.apply_transform(t, lims) + tlims = Makie.apply_transform(t, lims) left, bottom = minimum(tlims) right, top = maximum(tlims) @@ -119,16 +119,16 @@ function calculate_title_position(area, titlegap, subtitlegap, align, xaxisposit end local yoffset::Float32 = top(area) + titlegap + (xaxisposition === :top ? xaxisprotrusion : 0f0) + - subtitlespace + subtitlespace return Point2f(x, yoffset) end function compute_protrusions(title, titlesize, titlegap, titlevisible, spinewidth, - topspinevisible, bottomspinevisible, leftspinevisible, rightspinevisible, - xaxisprotrusion, yaxisprotrusion, xaxisposition, yaxisposition, - subtitle, subtitlevisible, subtitlesize, subtitlegap, titlelineheight, subtitlelineheight, - subtitlet, titlet) + topspinevisible, bottomspinevisible, leftspinevisible, rightspinevisible, + xaxisprotrusion, yaxisprotrusion, xaxisposition, yaxisposition, + subtitle, subtitlevisible, subtitlesize, subtitlegap, titlelineheight, subtitlelineheight, + subtitlet, titlet) local left::Float32, right::Float32, bottom::Float32, top::Float32 = 0f0, 0f0, 0f0, 0f0 @@ -167,7 +167,7 @@ function initialize_block!(ax::Axis; palette = nothing) topscene = ax.blockscene - decorations = Dict{Symbol, Any}() + decorations = Dict{Symbol,Any}() if palette === nothing palette = haskey(topscene.theme, :palette) ? deepcopy(topscene.theme[:palette]) : copy(Makie.default_palettes) @@ -177,7 +177,7 @@ function initialize_block!(ax::Axis; palette = nothing) # initialize either with user limits, or pick defaults based on scales # so that we don't immediately error targetlimits = Observable{Rect2f}(defaultlimits(ax.limits[], ax.xscale[], ax.yscale[])) - finallimits = Observable{Rect2f}(targetlimits[]; ignore_equal_values=true) + finallimits = Observable{Rect2f}(targetlimits[]; ignore_equal_values = true) setfield!(ax, :targetlimits, targetlimits) setfield!(ax, :finallimits, finallimits) @@ -201,12 +201,12 @@ function initialize_block!(ax::Axis; palette = nothing) scenearea = sceneareanode!(ax.layoutobservables.computedbbox, finallimits, ax.aspect) - scene = Scene(topscene, px_area=scenearea) + scene = Scene(topscene, px_area = scenearea) ax.scene = scene # TODO: replace with mesh, however, CairoMakie needs a poly path for this signature # so it doesn't rasterize the scene - background = poly!(topscene, scenearea; color=ax.backgroundcolor, inspectable=false, shading=false, strokecolor=:transparent) + background = poly!(topscene, scenearea; color = ax.backgroundcolor, inspectable = false, shading = false, strokecolor = :transparent) translate!(background, 0, 0, -100) decorations[:background] = background @@ -216,7 +216,7 @@ function initialize_block!(ax::Axis; palette = nothing) ax.xaxislinks = Axis[] ax.yaxislinks = Axis[] - xgridnode = Observable(Point2f[]; ignore_equal_values=true) + xgridnode = Observable(Point2f[]; ignore_equal_values = true) xgridlines = linesegments!( topscene, xgridnode, linewidth = ax.xgridwidth, visible = ax.xgridvisible, color = ax.xgridcolor, linestyle = ax.xgridstyle, inspectable = false @@ -225,7 +225,7 @@ function initialize_block!(ax::Axis; palette = nothing) translate!(xgridlines, 0, 0, -10) decorations[:xgridlines] = xgridlines - xminorgridnode = Observable(Point2f[]; ignore_equal_values=true) + xminorgridnode = Observable(Point2f[]; ignore_equal_values = true) xminorgridlines = linesegments!( topscene, xminorgridnode, linewidth = ax.xminorgridwidth, visible = ax.xminorgridvisible, color = ax.xminorgridcolor, linestyle = ax.xminorgridstyle, inspectable = false @@ -234,7 +234,7 @@ function initialize_block!(ax::Axis; palette = nothing) translate!(xminorgridlines, 0, 0, -10) decorations[:xminorgridlines] = xminorgridlines - ygridnode = Observable(Point2f[]; ignore_equal_values=true) + ygridnode = Observable(Point2f[]; ignore_equal_values = true) ygridlines = linesegments!( topscene, ygridnode, linewidth = ax.ygridwidth, visible = ax.ygridvisible, color = ax.ygridcolor, linestyle = ax.ygridstyle, inspectable = false @@ -243,7 +243,7 @@ function initialize_block!(ax::Axis; palette = nothing) translate!(ygridlines, 0, 0, -10) decorations[:ygridlines] = ygridlines - yminorgridnode = Observable(Point2f[]; ignore_equal_values=true) + yminorgridnode = Observable(Point2f[]; ignore_equal_values = true) yminorgridlines = linesegments!( topscene, yminorgridnode, linewidth = ax.yminorgridwidth, visible = ax.yminorgridvisible, color = ax.yminorgridcolor, linestyle = ax.yminorgridstyle, inspectable = false @@ -261,7 +261,7 @@ function initialize_block!(ax::Axis; palette = nothing) onany(update_axis_camera, camera(scene), scene.transformation.transform_func, finallimits, ax.xreversed, ax.yreversed) - xaxis_endpoints = lift(ax.xaxisposition, scene.px_area; ignore_equal_values=true) do xaxisposition, area + xaxis_endpoints = lift(ax.xaxisposition, scene.px_area; ignore_equal_values = true) do xaxisposition, area if xaxisposition == :bottom return bottomline(Rect2f(area)) elseif xaxisposition == :top @@ -271,7 +271,7 @@ function initialize_block!(ax::Axis; palette = nothing) end end - yaxis_endpoints = lift(ax.yaxisposition, scene.px_area; ignore_equal_values=true) do yaxisposition, area + yaxis_endpoints = lift(ax.yaxisposition, scene.px_area; ignore_equal_values = true) do yaxisposition, area if yaxisposition == :left return leftline(Rect2f(area)) elseif yaxisposition == :right @@ -281,36 +281,36 @@ function initialize_block!(ax::Axis; palette = nothing) end end - xaxis_flipped = lift(x->x == :top, ax.xaxisposition; ignore_equal_values=true) - yaxis_flipped = lift(x->x == :right, ax.yaxisposition; ignore_equal_values=true) + xaxis_flipped = lift(x -> x == :top, ax.xaxisposition; ignore_equal_values = true) + yaxis_flipped = lift(x -> x == :right, ax.yaxisposition; ignore_equal_values = true) - xspinevisible = lift(xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible; ignore_equal_values=true) do xflip, bv, tv + xspinevisible = lift(xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible; ignore_equal_values = true) do xflip, bv, tv xflip ? tv : bv end - xoppositespinevisible = lift(xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible; ignore_equal_values=true) do xflip, bv, tv + xoppositespinevisible = lift(xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible; ignore_equal_values = true) do xflip, bv, tv xflip ? bv : tv end - yspinevisible = lift(yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible; ignore_equal_values=true) do yflip, lv, rv + yspinevisible = lift(yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible; ignore_equal_values = true) do yflip, lv, rv yflip ? rv : lv end - yoppositespinevisible = lift(yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible; ignore_equal_values=true) do yflip, lv, rv + yoppositespinevisible = lift(yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible; ignore_equal_values = true) do yflip, lv, rv yflip ? lv : rv end - xspinecolor = lift(xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor; ignore_equal_values=true) do xflip, bc, tc + xspinecolor = lift(xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor; ignore_equal_values = true) do xflip, bc, tc xflip ? tc : bc end - xoppositespinecolor = lift(xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor; ignore_equal_values=true) do xflip, bc, tc + xoppositespinecolor = lift(xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor; ignore_equal_values = true) do xflip, bc, tc xflip ? bc : tc end - yspinecolor = lift(yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor; ignore_equal_values=true) do yflip, lc, rc + yspinecolor = lift(yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor; ignore_equal_values = true) do yflip, lc, rc yflip ? rc : lc end - yoppositespinecolor = lift(yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor; ignore_equal_values=true) do yflip, lc, rc + yoppositespinecolor = lift(yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor; ignore_equal_values = true) do yflip, lc, rc yflip ? lc : rc end - xlims = lift(xlimits, finallimits; ignore_equal_values=true) - ylims = lift(ylimits, finallimits; ignore_equal_values=true) + xlims = lift(xlimits, finallimits; ignore_equal_values = true) + ylims = lift(ylimits, finallimits; ignore_equal_values = true) xaxis = LineAxis(topscene, endpoints = xaxis_endpoints, limits = xlims, flipped = xaxis_flipped, ticklabelrotation = ax.xticklabelrotation, @@ -322,7 +322,7 @@ function initialize_block!(ax::Axis; palette = nothing) ticklabelsize = ax.xticklabelsize, trimspine = ax.xtrimspine, ticksize = ax.xticksize, reversed = ax.xreversed, tickwidth = ax.xtickwidth, tickcolor = ax.xtickcolor, minorticksvisible = ax.xminorticksvisible, minortickalign = ax.xminortickalign, minorticksize = ax.xminorticksize, minortickwidth = ax.xminortickwidth, minortickcolor = ax.xminortickcolor, minorticks = ax.xminorticks, scale = ax.xscale, - ) + ) ax.xaxis = xaxis yaxis = LineAxis(topscene, endpoints = yaxis_endpoints, limits = ylims, @@ -333,13 +333,13 @@ function initialize_block!(ax::Axis; palette = nothing) ticklabelspace = ax.yticklabelspace, ticks = ax.yticks, tickformat = ax.ytickformat, ticklabelsvisible = ax.yticklabelsvisible, ticksvisible = ax.yticksvisible, spinevisible = yspinevisible, spinecolor = yspinecolor, spinewidth = ax.spinewidth, trimspine = ax.ytrimspine, ticklabelsize = ax.yticklabelsize, ticksize = ax.yticksize, flip_vertical_label = ax.flip_ylabel, reversed = ax.yreversed, tickwidth = ax.ytickwidth, - tickcolor = ax.ytickcolor, + tickcolor = ax.ytickcolor, minorticksvisible = ax.yminorticksvisible, minortickalign = ax.yminortickalign, minorticksize = ax.yminorticksize, minortickwidth = ax.yminortickwidth, minortickcolor = ax.yminortickcolor, minorticks = ax.yminorticks, scale = ax.yscale, - ) + ) ax.yaxis = yaxis - xoppositelinepoints = lift(scene.px_area, ax.spinewidth, ax.xaxisposition; ignore_equal_values=true) do r, sw, xaxpos + xoppositelinepoints = lift(scene.px_area, ax.spinewidth, ax.xaxisposition; ignore_equal_values = true) do r, sw, xaxpos if xaxpos == :top y = bottom(r) p1 = Point2f(left(r) - 0.5sw, y) @@ -353,7 +353,7 @@ function initialize_block!(ax::Axis; palette = nothing) end end - yoppositelinepoints = lift(scene.px_area, ax.spinewidth, ax.yaxisposition; ignore_equal_values=true) do r, sw, yaxpos + yoppositelinepoints = lift(scene.px_area, ax.spinewidth, ax.yaxisposition; ignore_equal_values = true) do r, sw, yaxpos if yaxpos == :right x = left(r) p1 = Point2f(x, bottom(r) - 0.5sw) @@ -420,8 +420,8 @@ function initialize_block!(ax::Axis; palette = nothing) update_gridlines!(yminorgridnode, Point2f(offset, 0), tickpos) end - subtitlepos = lift(scene.px_area, ax.titlegap, ax.titlealign, ax.xaxisposition, xaxis.protrusion; ignore_equal_values=true) do a, - titlegap, align, xaxisposition, xaxisprotrusion + subtitlepos = lift(scene.px_area, ax.titlegap, ax.titlealign, ax.xaxisposition, xaxis.protrusion; ignore_equal_values = true) do a, + titlegap, align, xaxisposition, xaxisprotrusion x = if align == :center a.origin[1] + a.widths[1] / 2 @@ -438,7 +438,7 @@ function initialize_block!(ax::Axis; palette = nothing) return Point2f(x, yoffset) end - titlealignnode = lift(ax.titlealign; ignore_equal_values=true) do align + titlealignnode = lift(ax.titlealign; ignore_equal_values = true) do align (align, :bottom) end @@ -455,7 +455,7 @@ function initialize_block!(ax::Axis; palette = nothing) inspectable = false) titlepos = lift(calculate_title_position, scene.px_area, ax.titlegap, ax.subtitlegap, - ax.titlealign, ax.xaxisposition, xaxis.protrusion, ax.subtitlelineheight, ax, subtitlet; ignore_equal_values=true) + ax.titlealign, ax.xaxisposition, xaxis.protrusion, ax.subtitlelineheight, ax, subtitlet; ignore_equal_values = true) titlet = text!( topscene, titlepos, @@ -471,10 +471,10 @@ function initialize_block!(ax::Axis; palette = nothing) decorations[:title] = titlet map!(compute_protrusions, ax.layoutobservables.protrusions, ax.title, ax.titlesize, ax.titlegap, ax.titlevisible, ax.spinewidth, - ax.topspinevisible, ax.bottomspinevisible, ax.leftspinevisible, ax.rightspinevisible, - xaxis.protrusion, yaxis.protrusion, ax.xaxisposition, ax.yaxisposition, - ax.subtitle, ax.subtitlevisible, ax.subtitlesize, ax.subtitlegap, - ax.titlelineheight, ax.subtitlelineheight, subtitlet, titlet) + ax.topspinevisible, ax.bottomspinevisible, ax.leftspinevisible, ax.rightspinevisible, + xaxis.protrusion, yaxis.protrusion, ax.xaxisposition, ax.yaxisposition, + ax.subtitle, ax.subtitlevisible, ax.subtitlesize, ax.subtitlegap, + ax.titlelineheight, ax.subtitlelineheight, subtitlet, titlet) # trigger first protrusions with one of the observables notify(ax.title) @@ -516,21 +516,21 @@ function mirror_ticks(tickpositions, ticksize, tickalign, px_area, side, axispos a = px_area[][] if side == :x opp = axisposition == :bottom ? top(a) : bottom(a) - sign = axisposition == :bottom ? 1 : -1 + sign = axisposition == :bottom ? 1 : -1 else opp = axisposition == :left ? right(a) : left(a) sign = axisposition == :left ? 1 : -1 end d = ticksize * sign - points = Vector{Point2f}(undef, 2*length(tickpositions)) + points = Vector{Point2f}(undef, 2 * length(tickpositions)) if side == :x for (i, (x, _)) in enumerate(tickpositions) - points[2i-1] = Point2f(x, opp - d * tickalign) + points[2i - 1] = Point2f(x, opp - d * tickalign) points[2i] = Point2f(x, opp + d - d * tickalign) end else for (i, (_, y)) in enumerate(tickpositions) - points[2i-1] = Point2f(opp - d * tickalign, y) + points[2i - 1] = Point2f(opp - d * tickalign, y) points[2i] = Point2f(opp + d - d * tickalign, y) end end @@ -550,9 +550,9 @@ function reset_limits!(ax; xauto = true, yauto = true, zauto = true) mlims = convert_limit_attribute(ax.limits[]) if ax isa Axis - mxlims, mylims = mlims::Tuple{Any, Any} + mxlims, mylims = mlims::Tuple{Any,Any} elseif ax isa Axis3 - mxlims, mylims, mzlims = mlims::Tuple{Any, Any, Any} + mxlims, mylims, mzlims = mlims::Tuple{Any,Any,Any} else error() end @@ -571,7 +571,7 @@ function reset_limits!(ax; xauto = true, yauto = true, zauto = true) (lo, hi) end else - convert(Tuple{Float32, Float32}, tuple(mxlims...)) + convert(Tuple{Float32,Float32}, tuple(mxlims...)) end ylims = if isnothing(mylims) || mylims[1] === nothing || mylims[2] === nothing l = if yauto @@ -587,7 +587,7 @@ function reset_limits!(ax; xauto = true, yauto = true, zauto = true) (lo, hi) end else - convert(Tuple{Float32, Float32}, tuple(mylims...)) + convert(Tuple{Float32,Float32}, tuple(mylims...)) end if ax isa Axis3 @@ -605,7 +605,7 @@ function reset_limits!(ax; xauto = true, yauto = true, zauto = true) (lo, hi) end else - convert(Tuple{Float32, Float32}, tuple(mzlims...)) + convert(Tuple{Float32,Float32}, tuple(mzlims...)) end end @@ -633,11 +633,11 @@ function reset_limits!(ax; xauto = true, yauto = true, zauto = true) end # this is so users can do limits = (left, right, bottom, top) -function convert_limit_attribute(lims::Tuple{Any, Any, Any, Any}) +function convert_limit_attribute(lims::Tuple{Any,Any,Any,Any}) (lims[1:2], lims[3:4]) end -function convert_limit_attribute(lims::Tuple{Any, Any}) +function convert_limit_attribute(lims::Tuple{Any,Any}) lims end can_be_current_axis(ax::Axis) = true @@ -760,9 +760,9 @@ function add_cycle_attributes!(allattrs, P, cycle::Cycle, cycler::Cycler, palett end function Makie.plot!( - la::Axis, P::Makie.PlotFunc, - attributes::Makie.Attributes, args...; - kw_attributes...) + la::Axis, P::Makie.PlotFunc, + attributes::Makie.Attributes, args...; + kw_attributes...) allattrs = merge(attributes, Attributes(kw_attributes)) @@ -793,7 +793,7 @@ function Makie.plot!(P::Makie.PlotFunc, ax::Axis, args...; kw_attributes...) end needs_tight_limits(@nospecialize any) = false -needs_tight_limits(::Union{Heatmap, Image}) = true +needs_tight_limits(::Union{Heatmap,Image}) = true function needs_tight_limits(c::Contourf) # we know that all values are included and the contourf is rectangular # otherwise here it could be in an arbitrary shape @@ -1018,7 +1018,7 @@ function adjustlimits!(la) return end -function linkaxes!(dir::Union{Val{:x}, Val{:y}}, a::Axis, others...) +function linkaxes!(dir::Union{Val{:x},Val{:y}}, a::Axis, others...) axes = Axis[a; others...] all_links = Set{Axis}(axes) @@ -1061,7 +1061,7 @@ protrusions for the axis and the layout will adjust. This is so the layout doesn immediately readjust during interaction, which would let the whole layout jitter around. """ function timed_ticklabelspace_reset(ax::Axis, reset_timer::Ref, - prev_xticklabelspace::Ref, prev_yticklabelspace::Ref, threshold_sec::Real) + prev_xticklabelspace::Ref, prev_yticklabelspace::Ref, threshold_sec::Real) if !isnothing(reset_timer[]) close(reset_timer[]) @@ -1090,7 +1090,7 @@ end Hide decorations of the x-axis: label, ticklabels, ticks and grid. """ function hidexdecorations!(la::Axis; label = true, ticklabels = true, ticks = true, grid = true, - minorgrid = true, minorticks = true) + minorgrid = true, minorticks = true) if label la.xlabelvisible = false end @@ -1118,7 +1118,7 @@ end Hide decorations of the y-axis: label, ticklabels, ticks and grid. """ function hideydecorations!(la::Axis; label = true, ticklabels = true, ticks = true, grid = true, - minorgrid = true, minorticks = true) + minorgrid = true, minorticks = true) if label la.ylabelvisible = false end @@ -1145,7 +1145,7 @@ end Hide decorations of both x and y-axis: label, ticklabels, ticks and grid. """ function hidedecorations!(la::Axis; label = true, ticklabels = true, ticks = true, grid = true, - minorgrid = true, minorticks = true) + minorgrid = true, minorticks = true) hidexdecorations!(la; label = label, ticklabels = ticklabels, ticks = ticks, grid = grid, minorgrid = minorgrid, minorticks = minorticks) hideydecorations!(la; label = label, ticklabels = ticklabels, ticks = ticks, grid = grid, @@ -1314,23 +1314,23 @@ Makie.transform_func(ax::Axis) = Makie.transform_func(ax.scene) # these functions pick limits for different x and y scales, so that # we don't pick values that are invalid, such as 0 for log etc. -function defaultlimits(userlimits::Tuple{Real, Real, Real, Real}, xscale, yscale) +function defaultlimits(userlimits::Tuple{Real,Real,Real,Real}, xscale, yscale) BBox(userlimits...) end -defaultlimits(l::Tuple{Any, Any, Any, Any}, xscale, yscale) = defaultlimits(((l[1], l[2]), (l[3], l[4])), xscale, yscale) +defaultlimits(l::Tuple{Any,Any,Any,Any}, xscale, yscale) = defaultlimits(((l[1], l[2]), (l[3], l[4])), xscale, yscale) -function defaultlimits(userlimits::Tuple{Any, Any}, xscale, yscale) +function defaultlimits(userlimits::Tuple{Any,Any}, xscale, yscale) xl = defaultlimits(userlimits[1], xscale) yl = defaultlimits(userlimits[2], yscale) BBox(xl..., yl...) end defaultlimits(limits::Nothing, scale) = defaultlimits(scale) -defaultlimits(limits::Tuple{Real, Real}, scale) = limits -defaultlimits(limits::Tuple{Real, Nothing}, scale) = (limits[1], defaultlimits(scale)[2]) -defaultlimits(limits::Tuple{Nothing, Real}, scale) = (defaultlimits(scale)[1], limits[2]) -defaultlimits(limits::Tuple{Nothing, Nothing}, scale) = defaultlimits(scale) +defaultlimits(limits::Tuple{Real,Real}, scale) = limits +defaultlimits(limits::Tuple{Real,Nothing}, scale) = (limits[1], defaultlimits(scale)[2]) +defaultlimits(limits::Tuple{Nothing,Real}, scale) = (defaultlimits(scale)[1], limits[2]) +defaultlimits(limits::Tuple{Nothing,Nothing}, scale) = defaultlimits(scale) defaultlimits(::typeof(log10)) = (1.0, 1000.0) @@ -1343,7 +1343,7 @@ defaultlimits(::typeof(Makie.pseudolog10)) = (0.0, 100.0) defaultlimits(::Makie.Symlog10) = (0.0, 100.0) defined_interval(::typeof(identity)) = OpenInterval(-Inf, Inf) -defined_interval(::Union{typeof(log2), typeof(log10), typeof(log)}) = OpenInterval(0.0, Inf) +defined_interval(::Union{typeof(log2),typeof(log10),typeof(log)}) = OpenInterval(0.0, Inf) defined_interval(::typeof(sqrt)) = Interval{:closed,:open}(0, Inf) defined_interval(::typeof(Makie.logit)) = OpenInterval(0.0, 1.0) defined_interval(::typeof(Makie.pseudolog10)) = OpenInterval(-Inf, Inf) diff --git a/src/makielayout/blocks/axis3d.jl b/src/makielayout/blocks/axis3d.jl index bad81bdc8c8..5fbbec1ed1a 100644 --- a/src/makielayout/blocks/axis3d.jl +++ b/src/makielayout/blocks/axis3d.jl @@ -19,12 +19,12 @@ function initialize_block!(ax::Axis3) cam = OrthographicCamera() cameracontrols!(scene, cam) - mi1 = Observable(!(pi/2 <= mod1(ax.azimuth[], 2pi) < 3pi/2)) + mi1 = Observable(!(pi / 2 <= mod1(ax.azimuth[], 2pi) < 3pi / 2)) mi2 = Observable(0 <= mod1(ax.azimuth[], 2pi) < pi) mi3 = Observable(ax.elevation[] > 0) on(ax.azimuth) do x - b = !(pi/2 <= mod1(x, 2pi) < 3pi/2) + b = !(pi / 2 <= mod1(x, 2pi) < 3pi / 2) mi1.val == b || (mi1[] = b) return end @@ -130,7 +130,7 @@ function initialize_block!(ax::Axis3) return Consume(false) end - ax.interactions = Dict{Symbol, Tuple{Bool, Any}}() + ax.interactions = Dict{Symbol,Tuple{Bool,Any}}() on(ax.limits) do lims reset_limits!(ax) @@ -251,12 +251,12 @@ function projectionmatrix(viewmatrix, limits, eyepos, radius, azim, elev, angle, if viewmode == :fitzoom if ratio_y > ratio_x - pm = Makie.scalematrix(Vec3(1/ratio_y, 1/ratio_y, 1)) * pm + pm = Makie.scalematrix(Vec3(1 / ratio_y, 1 / ratio_y, 1)) * pm else - pm = Makie.scalematrix(Vec3(1/ratio_x, 1/ratio_x, 1)) * pm + pm = Makie.scalematrix(Vec3(1 / ratio_x, 1 / ratio_x, 1)) * pm end else - pm = Makie.scalematrix(Vec3(1/ratio_x, 1/ratio_y, 1)) * pm + pm = Makie.scalematrix(Vec3(1 / ratio_x, 1 / ratio_y, 1)) * pm end end pm @@ -317,7 +317,7 @@ function autolimits!(ax::Axis3) end to_protrusions(x::Number) = GridLayoutBase.RectSides{Float32}(x, x, x, x) -to_protrusions(x::Tuple{Any, Any, Any, Any}) = GridLayoutBase.RectSides{Float32}(x...) +to_protrusions(x::Tuple{Any,Any,Any,Any}) = GridLayoutBase.RectSides{Float32}(x...) function getlimits(ax::Axis3, dim) dim in (1, 2, 3) || error("Dimension $dim not allowed. Only 1, 2 or 3.") @@ -325,10 +325,10 @@ function getlimits(ax::Axis3, dim) filtered_plots = filter(ax.scene.plots) do p attr = p.attributes to_value(get(attr, :visible, true)) && - is_data_space(to_value(get(attr, :space, :data))) && - ifelse(dim == 1, to_value(get(attr, :xautolimits, true)), true) && - ifelse(dim == 2, to_value(get(attr, :yautolimits, true)), true) && - ifelse(dim == 3, to_value(get(attr, :zautolimits, true)), true) + is_data_space(to_value(get(attr, :space, :data))) && + ifelse(dim == 1, to_value(get(attr, :xautolimits, true)), true) && + ifelse(dim == 2, to_value(get(attr, :yautolimits, true)), true) && + ifelse(dim == 3, to_value(get(attr, :zautolimits, true)), true) end bboxes = Makie.data_limits.(filtered_plots) @@ -422,7 +422,7 @@ function add_gridlines_and_frames!(topscene, scene, ax, dim::Int, limits, tickno framepoints = lift(limits, scene.camera.projectionview, scene.px_area, min1, min2 - ) do lims, _, pxa, mi1, mi2 + ) do lims, _, pxa, mi1, mi2 o = pxa.origin f(mi) = mi ? minimum : maximum @@ -472,8 +472,8 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno ticklabels = @lift($ticknode[2]) tick_segments = lift(limits, tickvalues, miv, min1, min2, - scene.camera.projectionview, scene.px_area) do lims, ticks, miv, min1, min2, - pview, pxa + scene.camera.projectionview, scene.px_area) do lims, ticks, miv, min1, min2, + pview, pxa f1 = !min1 ? minimum(lims)[d1] : maximum(lims)[d1] f2 = min2 ? minimum(lims)[d2] : maximum(lims)[d2] @@ -515,7 +515,7 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno color = attr(:tickcolor), linewidth = attr(:tickwidth), visible = attr(:ticksvisible)) labels_positions = lift(scene.px_area, scene.camera.projectionview, - tick_segments, ticklabels, attr(:ticklabelpad)) do pxa, pv, ticksegs, ticklabs, pad + tick_segments, ticklabels, attr(:ticklabelpad)) do pxa, pv, ticksegs, ticklabs, pad o = pxa.origin @@ -530,7 +530,7 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno N = min(length(ticklabs), length(points)) v = [(ticklabs[i], points[i]) for i in 1:N] - v::Vector{Tuple{String, Point2f}} + v::Vector{Tuple{String,Point2f}} end align = lift(miv, min1, min2) do mv, m1, m2 @@ -555,9 +555,9 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno label_align = Observable((:center, :top)) onany( - scene.px_area, scene.camera.projectionview, limits, miv, min1, min2, - attr(:labeloffset), attr(:labelrotation), attr(:labelalign) - ) do pxa, pv, lims, miv, min1, min2, labeloffset, lrotation, lalign + scene.px_area, scene.camera.projectionview, limits, miv, min1, min2, + attr(:labeloffset), attr(:labelrotation), attr(:labelalign) + ) do pxa, pv, lims, miv, min1, min2, labeloffset, lrotation, lalign o = pxa.origin @@ -584,18 +584,18 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno (min1 ⊻ min2) ? 1 : -1 end - a = pi/2 + a = pi / 2 # get the vector pointing from the axis in the direction of the label anchor offset_vec = (Makie.Mat2f(cos(a), sin(a), -sin(a), cos(a)) * - Makie.GeometryBasics.normalize(diffsign * diff)) + Makie.GeometryBasics.normalize(diffsign * diff)) # calculate the label offset from the axis midpoint plus_offset = midpoint + labeloffset * offset_vec offset_ang = atan(offset_vec[2], offset_vec[1]) - offset_ang_90deg = offset_ang + pi/2 - offset_ang_90deg_alwaysup = ((offset_ang + pi/2 + pi/2) % pi) - pi/2 + offset_ang_90deg = offset_ang + pi / 2 + offset_ang_90deg_alwaysup = ((offset_ang + pi / 2 + pi / 2) % pi) - pi / 2 # # prefer rotated left 90deg to rotated right 90deg slight_flip = offset_ang_90deg_alwaysup < -deg2rad(88) @@ -655,7 +655,7 @@ end function add_panel!(scene, ax, dim1, dim2, dim3, limits, min3) dimsym(sym) = Symbol(string((:x, :y, :z)[dim1]) * - string((:x, :y, :z)[dim2]) * string(sym)) + string((:x, :y, :z)[dim2]) * string(sym)) attr(sym) = getproperty(ax, dimsym(sym)) vertices = lift(limits, min3) do lims, mi3 @@ -782,11 +782,11 @@ end # this is so users can do limits = (x1, x2, y1, y2, z1, z2) -function convert_limit_attribute(lims::Tuple{Any, Any, Any, Any, Any, Any}) +function convert_limit_attribute(lims::Tuple{Any,Any,Any,Any,Any,Any}) (lims[1:2], lims[3:4], lims[5:6]) end -function convert_limit_attribute(lims::Tuple{Any, Any, Any}) +function convert_limit_attribute(lims::Tuple{Any,Any,Any}) lims end @@ -833,16 +833,16 @@ function zautolimits(ax::Axis3) zlims end -function Makie.xlims!(ax::Axis3, xlims::Tuple{Union{Real, Nothing}, Union{Real, Nothing}}) +function Makie.xlims!(ax::Axis3, xlims::Tuple{Union{Real,Nothing},Union{Real,Nothing}}) if length(xlims) != 2 error("Invalid xlims length of $(length(xlims)), must be 2.") elseif xlims[1] == xlims[2] error("Can't set x limits to the same value $(xlims[1]).") - # elseif all(x -> x isa Real, xlims) && xlims[1] > xlims[2] - # xlims = reverse(xlims) - # ax.xreversed[] = true - # else - # ax.xreversed[] = false + # elseif all(x -> x isa Real, xlims) && xlims[1] > xlims[2] + # xlims = reverse(xlims) + # ax.xreversed[] = true + # else + # ax.xreversed[] = false end ax.limits.val = (xlims, ax.limits[][2], ax.limits[][3]) @@ -850,16 +850,16 @@ function Makie.xlims!(ax::Axis3, xlims::Tuple{Union{Real, Nothing}, Union{Real, nothing end -function Makie.ylims!(ax::Axis3, ylims::Tuple{Union{Real, Nothing}, Union{Real, Nothing}}) +function Makie.ylims!(ax::Axis3, ylims::Tuple{Union{Real,Nothing},Union{Real,Nothing}}) if length(ylims) != 2 error("Invalid ylims length of $(length(ylims)), must be 2.") elseif ylims[1] == ylims[2] error("Can't set y limits to the same value $(ylims[1]).") - # elseif all(x -> x isa Real, ylims) && ylims[1] > ylims[2] - # ylims = reverse(ylims) - # ax.yreversed[] = true - # else - # ax.yreversed[] = false + # elseif all(x -> x isa Real, ylims) && ylims[1] > ylims[2] + # ylims = reverse(ylims) + # ax.yreversed[] = true + # else + # ax.yreversed[] = false end ax.limits.val = (ax.limits[][1], ylims, ax.limits[][3]) @@ -872,11 +872,11 @@ function Makie.zlims!(ax::Axis3, zlims) error("Invalid zlims length of $(length(zlims)), must be 2.") elseif zlims[1] == zlims[2] error("Can't set y limits to the same value $(zlims[1]).") - # elseif all(x -> x isa Real, zlims) && zlims[1] > zlims[2] - # zlims = reverse(zlims) - # ax.zreversed[] = true - # else - # ax.zreversed[] = false + # elseif all(x -> x isa Real, zlims) && zlims[1] > zlims[2] + # zlims = reverse(zlims) + # ax.zreversed[] = true + # else + # ax.zreversed[] = false end ax.limits.val = (ax.limits[][1], ax.limits[][2], zlims) diff --git a/src/makielayout/blocks/button.jl b/src/makielayout/blocks/button.jl index 59d956bbaf1..ee94085d058 100644 --- a/src/makielayout/blocks/button.jl +++ b/src/makielayout/blocks/button.jl @@ -7,7 +7,7 @@ function initialize_block!(b::Button) subarea = lift(b.layoutobservables.computedbbox) do bbox round_to_IRect2D(bbox) end - subscene = Scene(scene, subarea, camera=campixel!) + subscene = Scene(scene, subarea, camera = campixel!) # buttonrect is without the left bottom offset of the bbox buttonrect = lift(b.layoutobservables.computedbbox) do bbox @@ -24,14 +24,14 @@ function initialize_block!(b::Button) bcolors = (; out = b.buttoncolor, active = b.buttoncolor_active, hover = b.buttoncolor_hover) bcolor = Observable{RGBColors}() - map!((s,_...)-> to_color(bcolors[s][]), bcolor, mousestate, values(bcolors)...) + map!((s, _...) -> to_color(bcolors[s][]), bcolor, mousestate, values(bcolors)...) button = poly!(subscene, roundedrectpoints, strokewidth = b.strokewidth, strokecolor = b.strokecolor, color = bcolor, inspectable = false) lcolors = (; out = b.labelcolor, active = b.labelcolor_active, hover = b.labelcolor_hover) lcolor = Observable{RGBColors}() - map!((s,_...)-> to_color(lcolors[s][]), lcolor, mousestate, values(lcolors)...) + map!((s, _...) -> to_color(lcolors[s][]), lcolor, mousestate, values(lcolors)...) labeltext = text!(subscene, textpos, text = b.label, fontsize = b.fontsize, font = b.font, color = lcolor, align = (:center, :center), markerspace = :data, inspectable = false) diff --git a/src/makielayout/blocks/colorbar.jl b/src/makielayout/blocks/colorbar.jl index e29b95e9928..d2cd08c30ed 100644 --- a/src/makielayout/blocks/colorbar.jl +++ b/src/makielayout/blocks/colorbar.jl @@ -34,7 +34,7 @@ function Colorbar(fig_or_scene, plot::AbstractPlot; kwargs...) ) end -function Colorbar(fig_or_scene, heatmap::Union{Heatmap, Image}; kwargs...) +function Colorbar(fig_or_scene, heatmap::Union{Heatmap,Image}; kwargs...) for key in (:colormap, :limits, :highclip, :lowclip) if key in keys(kwargs) @@ -52,7 +52,7 @@ function Colorbar(fig_or_scene, heatmap::Union{Heatmap, Image}; kwargs...) ) end -function Colorbar(fig_or_scene, contourf::Union{Contourf, Tricontourf}; kwargs...) +function Colorbar(fig_or_scene, contourf::Union{Contourf,Tricontourf}; kwargs...) for key in (:colormap, :limits, :highclip, :lowclip) if key in keys(kwargs) @@ -119,15 +119,15 @@ function initialize_block!(cb::Colorbar) return c != compare end - lowclip_tri_visible = lift(isvisible, cb.lowclip, lift(x-> get(x, 0), cgradient)) - highclip_tri_visible = lift(isvisible, cb.highclip, lift(x-> get(x, 1), cgradient)) + lowclip_tri_visible = lift(isvisible, cb.lowclip, lift(x -> get(x, 0), cgradient)) + highclip_tri_visible = lift(isvisible, cb.highclip, lift(x -> get(x, 1), cgradient)) tri_heights = lift(highclip_tri_visible, lowclip_tri_visible, framebox) do hv, lv, box if cb.vertical[] (lv * width(box), hv * width(box)) else (lv * height(box), hv * height(box)) - end .* sin(pi/3) + end .* sin(pi / 3) end barsize = lift(tri_heights) do heights @@ -182,14 +182,14 @@ function initialize_block!(cb::Colorbar) rects = if v yvals = s_scaled .* (ymax - ymin) .+ ymin [BBox(xmin, xmax, b, t) - for (b, t) in zip(yvals[1:end-1], yvals[2:end])] + for (b, t) in zip(yvals[1:(end - 1)], yvals[2:end])] else xvals = s_scaled .* (xmax - xmin) .+ xmin [BBox(l, r, ymin, ymax) - for (l, r) in zip(xvals[1:end-1], xvals[2:end])] + for (l, r) in zip(xvals[1:(end - 1)], xvals[2:end])] end - colors = get.(Ref(gradient), (steps[1:end-1] .+ steps[2:end]) ./2) + colors = get.(Ref(gradient), (steps[1:(end - 1)] .+ steps[2:end]) ./ 2) rects, colors end @@ -226,11 +226,11 @@ function initialize_block!(cb::Colorbar) lb, rb = topline(box) l = lb r = rb - t = ((l .+ r) ./ 2) .+ Point2f(0, sqrt(sum((r .- l) .^ 2)) * sin(pi/3)) + t = ((l .+ r) ./ 2) .+ Point2f(0, sqrt(sum((r .- l) .^ 2)) * sin(pi / 3)) [l, r, t] else b, t = rightline(box) - r = ((b .+ t) ./ 2) .+ Point2f(sqrt(sum((t .- b) .^ 2)) * sin(pi/3), 0) + r = ((b .+ t) ./ 2) .+ Point2f(sqrt(sum((t .- b) .^ 2)) * sin(pi / 3), 0) [t, b, r] end end @@ -248,11 +248,11 @@ function initialize_block!(cb::Colorbar) lb, rb = bottomline(box) l = lb r = rb - t = ((l .+ r) ./ 2) .- Point2f(0, sqrt(sum((r .- l) .^ 2)) * sin(pi/3)) + t = ((l .+ r) ./ 2) .- Point2f(0, sqrt(sum((r .- l) .^ 2)) * sin(pi / 3)) [l, r, t] else b, t = leftline(box) - l = ((b .+ t) ./ 2) .- Point2f(sqrt(sum((t .- b) .^ 2)) * sin(pi/3), 0) + l = ((b .+ t) ./ 2) .- Point2f(sqrt(sum((t .- b) .^ 2)) * sin(pi / 3), 0) [b, t, l] end end @@ -294,7 +294,7 @@ function initialize_block!(cb::Colorbar) lines!(blockscene, borderpoints, linewidth = cb.spinewidth, color = cb.topspinecolor, inspectable = false) axispoints = lift(barbox, cb.vertical, cb.flipaxis) do scenearea, - vertical, flipaxis + vertical, flipaxis if vertical if flipaxis @@ -331,7 +331,7 @@ function initialize_block!(cb::Colorbar) onany(axis.protrusion, cb.vertical, cb.flipaxis) do axprotrusion, - vertical, flipaxis + vertical, flipaxis left, right, top, bottom = 0f0, 0f0, 0f0, 0f0 diff --git a/src/makielayout/blocks/intervalslider.jl b/src/makielayout/blocks/intervalslider.jl index a8a50a6366d..fb9e1316e3a 100644 --- a/src/makielayout/blocks/intervalslider.jl +++ b/src/makielayout/blocks/intervalslider.jl @@ -19,12 +19,12 @@ function initialize_block!(isl::IntervalSlider) if horizontal y = bottom(bb) + h / 2 - [Point2f(left(bb) + h/2, y), - Point2f(right(bb) - h/2, y)] + [Point2f(left(bb) + h / 2, y), + Point2f(right(bb) - h / 2, y)] else x = left(bb) + w / 2 - [Point2f(x, bottom(bb) + w/2), - Point2f(x, top(bb) - w/2)] + [Point2f(x, bottom(bb) + w / 2), + Point2f(x, top(bb) - w / 2)] end end diff --git a/src/makielayout/blocks/label.jl b/src/makielayout/blocks/label.jl index a755cc54e05..ba4893d1eba 100644 --- a/src/makielayout/blocks/label.jl +++ b/src/makielayout/blocks/label.jl @@ -11,7 +11,7 @@ function initialize_block!(l::Label) t = text!( topscene, textpos, text = l.text, fontsize = l.fontsize, font = l.font, color = l.color, visible = l.visible, align = (:center, :center), rotation = l.rotation, markerspace = :data, - justification = l.justification, lineheight = l.lineheight, word_wrap_width = word_wrap_width, + justification = l.justification, lineheight = l.lineheight, word_wrap_width = word_wrap_width, inspectable = false) textbb = Ref(BBox(0, 1, 0, 1)) diff --git a/src/makielayout/blocks/legend.jl b/src/makielayout/blocks/legend.jl index fa33e25d764..aee45a622ca 100644 --- a/src/makielayout/blocks/legend.jl +++ b/src/makielayout/blocks/legend.jl @@ -1,5 +1,5 @@ function initialize_block!(leg::Legend, - entry_groups::Observable{Vector{Tuple{Optional{<:AbstractString}, Vector{LegendEntry}}}}) + entry_groups::Observable{Vector{Tuple{Optional{<:AbstractString},Vector{LegendEntry}}}}) blockscene = leg.blockscene @@ -81,7 +81,7 @@ function initialize_block!(leg::Legend, end elseif leg.orientation[] == :horizontal if leg.titleposition[] == :left - isnothing(title) || (grid[1, 2g-1] = title) + isnothing(title) || (grid[1, 2g - 1] = title) grid[1, 2g] = GridLayout(halign = leg.gridshalign[], valign = leg.gridsvalign[]) elseif leg.titleposition[] == :top isnothing(title) || (grid[1, g] = title) @@ -91,17 +91,17 @@ function initialize_block!(leg::Legend, for (n, (et, er)) in enumerate(zip(etexts, erects)) i, j = leg.orientation[] == :vertical ? rowcol(n) : reverse(rowcol(n)) - subgl[i, 2j-1] = er + subgl[i, 2j - 1] = er subgl[i, 2j] = et end rowgap!(subgl, leg.rowgap[]) - for c in 1:ncols(subgl)-1 + for c in 1:(ncols(subgl) - 1) colgap!(subgl, c, c % 2 == 1 ? leg.patchlabelgap[] : leg.colgap[]) end end - for r in 1:nrows(grid)-1 + for r in 1:(nrows(grid) - 1) if leg.orientation[] == :horizontal if leg.titleposition[] == :left # nothing @@ -116,7 +116,7 @@ function initialize_block!(leg::Legend, end end end - for c in 1:ncols(grid)-1 + for c in 1:(ncols(grid) - 1) if leg.orientation[] == :horizontal if leg.titleposition[] == :left colgap!(grid, c, c % 2 == 1 ? leg.titlegap[] : leg.groupgap[]) @@ -147,7 +147,7 @@ function initialize_block!(leg::Legend, end onany(leg.nbanks, leg.titleposition, leg.rowgap, leg.colgap, leg.patchlabelgap, leg.groupgap, leg.titlegap, - leg.titlevisible, leg.orientation, leg.gridshalign, leg.gridsvalign) do args... + leg.titlevisible, leg.orientation, leg.gridshalign, leg.gridsvalign) do args... relayout() end @@ -203,12 +203,12 @@ function initialize_block!(leg::Legend, return lj isa Automatic ? lha : lj end push!(etexts, - Label(scene; text=e.label, fontsize=e.labelsize, font=e.labelfont, justification=justification, - color=e.labelcolor, halign=e.labelhalign, valign=e.labelvalign)) + Label(scene; text = e.label, fontsize = e.labelsize, font = e.labelfont, justification = justification, + color = e.labelcolor, halign = e.labelhalign, valign = e.labelvalign)) # create the patch rectangle - rect = Box(scene; color=e.patchcolor, strokecolor=e.patchstrokecolor, strokewidth=e.patchstrokewidth, - width=lift(x -> x[1], e.patchsize), height=lift(x -> x[2], e.patchsize)) + rect = Box(scene; color = e.patchcolor, strokecolor = e.patchstrokecolor, strokewidth = e.patchstrokewidth, + width = lift(x -> x[1], e.patchsize), height = lift(x -> x[2], e.patchsize)) push!(erects, rect) translate!(rect.blockscene, 0, 0, -5) # patches before background but behind legend elements (legend is at +10) @@ -216,7 +216,7 @@ function initialize_block!(leg::Legend, symbolplots = AbstractPlot[] for element in e.elements append!(symbolplots, - legendelement_plots!(scene, element, rect.layoutobservables.computedbbox, e.attributes)) + legendelement_plots!(scene, element, rect.layoutobservables.computedbbox, e.attributes)) end push!(eplots, symbolplots) @@ -332,15 +332,15 @@ function LegendEntry(label::Optional{AbstractString}, contentelement, legend; kw end -function LineElement(;kwargs...) +function LineElement(; kwargs...) _legendelement(LineElement, Attributes(kwargs)) end -function MarkerElement(;kwargs...) +function MarkerElement(; kwargs...) _legendelement(MarkerElement, Attributes(kwargs)) end -function PolyElement(;kwargs...) +function PolyElement(; kwargs...) _legendelement(PolyElement, Attributes(kwargs)) end @@ -389,7 +389,7 @@ function scalar_lift(attr, default) return observable end -function legendelements(plot::Union{Lines, LineSegments}, legend) +function legendelements(plot::Union{Lines,LineSegments}, legend) LegendElement[LineElement( color = scalar_lift(plot.color, legend.linecolor), linestyle = scalar_lift(plot.linestyle, legend.linestyle), @@ -407,7 +407,7 @@ function legendelements(plot::Scatter, legend) )] end -function legendelements(plot::Union{Poly, Violin, BoxPlot, CrossBar, Density}, legend) +function legendelements(plot::Union{Poly,Violin,BoxPlot,CrossBar,Density}, legend) LegendElement[PolyElement( color = scalar_lift(plot.color, legend.polycolor), strokecolor = scalar_lift(plot.strokecolor, legend.polystrokecolor), @@ -429,7 +429,7 @@ function legendelements(plot, legend)::Vector{LegendElement} reduce(vcat, [legendelements(childplot, legend) for childplot in plot.plots]) end -function Base.getproperty(legendelement::T, s::Symbol) where T <: LegendElement +function Base.getproperty(legendelement::T, s::Symbol) where T<:LegendElement if s in fieldnames(T) getfield(legendelement, s) else @@ -437,7 +437,7 @@ function Base.getproperty(legendelement::T, s::Symbol) where T <: LegendElement end end -function Base.setproperty!(legendelement::T, s::Symbol, value) where T <: LegendElement +function Base.setproperty!(legendelement::T, s::Symbol, value) where T<:LegendElement if s in fieldnames(T) setfield!(legendelement, s, value) else @@ -445,7 +445,7 @@ function Base.setproperty!(legendelement::T, s::Symbol, value) where T <: Legend end end -function Base.propertynames(legendelement::T) where T <: LegendElement +function Base.propertynames(legendelement::T) where T<:LegendElement [fieldnames(T)..., keys(legendelement.attributes)...] end @@ -465,10 +465,10 @@ one content element. A content element can be an `AbstractPlot`, an array of `legendelements` method is defined. """ function Legend(fig_or_scene, - contents::AbstractArray, - labels::AbstractArray{<:Optional{AbstractString}}, - title::Optional{<:AbstractString} = nothing; - kwargs...) + contents::AbstractArray, + labels::AbstractArray{<:Optional{AbstractString}}, + title::Optional{<:AbstractString} = nothing; + kwargs...) if length(contents) != length(labels) error("Number of elements not equal: $(length(contents)) content elements and $(length(labels)) labels.") @@ -500,10 +500,10 @@ element can be an `AbstractPlot`, an array of `AbstractPlots`, a `LegendElement` or any other object for which the `legendelements` method is defined. """ function Legend(fig_or_scene, - contentgroups::AbstractArray{<:AbstractArray}, - labelgroups::AbstractArray{<:AbstractArray}, - titles::AbstractArray{<:Optional{<:AbstractString}}; - kwargs...) + contentgroups::AbstractArray{<:AbstractArray}, + labelgroups::AbstractArray{<:AbstractArray}, + titles::AbstractArray{<:Optional{<:AbstractString}}; + kwargs...) if !(length(titles) == length(contentgroups) == length(labelgroups)) error("Number of elements not equal: $(length(titles)) titles, $(length(contentgroups)) content groups and $(length(labelgroups)) label groups.") @@ -513,7 +513,7 @@ function Legend(fig_or_scene, entrygroups = Observable{Vector{EntryGroup}}([]) legend = Legend(fig_or_scene, entrygroups; kwargs...) entries = [[LegendEntry(l, pg, legend) for (l, pg) in zip(labelgroup, contentgroup)] - for (labelgroup, contentgroup) in zip(labelgroups, contentgroups)] + for (labelgroup, contentgroup) in zip(labelgroups, contentgroups)] entrygroups[] = [(t, en) for (t, en) in zip(titles, entries)] legend end @@ -528,7 +528,7 @@ attribute `label` set. If `merge` is `true`, all plot objects with the same label will be layered on top of each other into one legend entry. If `unique` is `true`, all plot objects with the same plot type and label will be reduced to one occurrence. """ -function Legend(fig_or_scene, axis::Union{Axis, Axis3, Scene, LScene}, title = nothing; merge = false, unique = false, kwargs...) +function Legend(fig_or_scene, axis::Union{Axis,Axis3,Scene,LScene}, title = nothing; merge = false, unique = false, kwargs...) plots, labels = get_labeled_plots(axis, merge = merge, unique = unique) isempty(plots) && error("There are no plots with labels in the given axis that can be put in the legend. Supply labels to plotting functions like `plot(args...; label = \"My label\")`") Legend(fig_or_scene, plots, labels, title; kwargs...) @@ -552,7 +552,7 @@ function get_labeled_plots(ax; merge::Bool, unique::Bool) if merge ulabels = Base.unique(labels) mergedplots = [[lp for (i, lp) in enumerate(lplots) if labels[i] == ul] - for ul in ulabels] + for ul in ulabels] lplots, labels = mergedplots, ulabels end @@ -561,7 +561,7 @@ function get_labeled_plots(ax; merge::Bool, unique::Bool) end get_plots(p::AbstractPlot) = [p] -get_plots(ax::Union{Axis, Axis3}) = get_plots(ax.scene) +get_plots(ax::Union{Axis,Axis3}) = get_plots(ax.scene) get_plots(lscene::LScene) = get_plots(lscene.scene) function get_plots(scene::Scene) plots = AbstractPlot[] @@ -624,6 +624,6 @@ function legend_position_to_aligns(s::Symbol) (halign = haligns[p[1]], valign = valigns[p[2]]) end -function legend_position_to_aligns(t::Tuple{Any, Any}) +function legend_position_to_aligns(t::Tuple{Any,Any}) (halign = t[1], valign = t[2]) end diff --git a/src/makielayout/blocks/menu.jl b/src/makielayout/blocks/menu.jl index c1083b5bb96..6a2c8fed1ee 100644 --- a/src/makielayout/blocks/menu.jl +++ b/src/makielayout/blocks/menu.jl @@ -51,11 +51,11 @@ end function initialize_block!(m::Menu; default = 1) blockscene = m.blockscene - listheight = Observable(0.0; ignore_equal_values=true) + listheight = Observable(0.0; ignore_equal_values = true) # the direction is auto-chosen as up if there is too little space below and if the space below # is smaller than above - _direction = Observable{Symbol}(:none; ignore_equal_values=true) + _direction = Observable{Symbol}(:none; ignore_equal_values = true) map!(_direction, m.layoutobservables.computedbbox, m.direction) do bb, dir if dir == Makie.automatic @@ -73,17 +73,17 @@ function initialize_block!(m::Menu; default = 1) end end - scenearea = lift(m.layoutobservables.computedbbox, listheight, _direction, m.is_open; ignore_equal_values=true) do bbox, h, d, open + scenearea = lift(m.layoutobservables.computedbbox, listheight, _direction, m.is_open; ignore_equal_values = true) do bbox, h, d, open !open ? - round_to_IRect2D(BBox(left(bbox), right(bbox), 0, 0)) : - round_to_IRect2D(BBox( - left(bbox), - right(bbox), - d == :down ? max(0, bottom(bbox) - h) : top(bbox), - d == :down ? bottom(bbox) : min(top(bbox) + h, top(blockscene.px_area[])))) + round_to_IRect2D(BBox(left(bbox), right(bbox), 0, 0)) : + round_to_IRect2D(BBox( + left(bbox), + right(bbox), + d == :down ? max(0, bottom(bbox) - h) : top(bbox), + d == :down ? bottom(bbox) : min(top(bbox) + h, top(blockscene.px_area[])))) end - menuscene = Scene(blockscene, scenearea, camera = campixel!, clear=true) + menuscene = Scene(blockscene, scenearea, camera = campixel!, clear = true) translate!(menuscene, 0, 0, 200) onany(scenearea, listheight) do area, listheight @@ -93,9 +93,9 @@ function initialize_block!(m::Menu; default = 1) translate!(menuscene, t[1], new_y, t[3]) end - optionstrings = lift(o -> optionlabel.(o), m.options; ignore_equal_values=true) + optionstrings = lift(o -> optionlabel.(o), m.options; ignore_equal_values = true) - selected_text = lift(m.prompt, m.i_selected; ignore_equal_values=true) do prompt, i_selected + selected_text = lift(m.prompt, m.i_selected; ignore_equal_values = true) do prompt, i_selected if i_selected == 0 prompt else @@ -103,14 +103,14 @@ function initialize_block!(m::Menu; default = 1) end end - selectionarea = Observable(Rect2f(0, 0, 0, 0); ignore_equal_values=true) + selectionarea = Observable(Rect2f(0, 0, 0, 0); ignore_equal_values = true) selectionpoly = poly!( blockscene, selectionarea, color = m.selection_cell_color_inactive[]; inspectable = false ) - selectiontextpos = Observable(Point2f(0, 0); ignore_equal_values=true) + selectiontextpos = Observable(Point2f(0, 0); ignore_equal_values = true) selectiontext = text!( blockscene, selectiontextpos, text = selected_text, align = (:left, :center), fontsize = m.fontsize, color = m.textcolor, markerspace = :data, inspectable = false @@ -125,13 +125,13 @@ function initialize_block!(m::Menu; default = 1) on(m.layoutobservables.computedbbox) do cbb selectionarea[] = cbb ch = height(cbb) - selectiontextpos[] = cbb.origin + Point2f(m.textpadding[][1], ch/2) + selectiontextpos[] = cbb.origin + Point2f(m.textpadding[][1], ch / 2) end - textpositions = Observable(zeros(Point2f, length(optionstrings[])); ignore_equal_values=true) + textpositions = Observable(zeros(Point2f, length(optionstrings[])); ignore_equal_values = true) - optionrects = Observable([Rect2f(0, 0, 0, 0)]; ignore_equal_values=true) - optionpolycolors = Observable(RGBAf[RGBAf(0.5, 0.5, 0.5, 1)]; ignore_equal_values=true) + optionrects = Observable([Rect2f(0, 0, 0, 0)]; ignore_equal_values = true) + optionpolycolors = Observable(RGBAf[RGBAf(0.5, 0.5, 0.5, 1)]; ignore_equal_values = true) function update_option_colors!(hovered) n = length(optionstrings[]) @@ -166,7 +166,7 @@ function initialize_block!(m::Menu; default = 1) heights_cumsum = [zero(eltype(heights)); cumsum(heights)] h = sum(heights) list_y_bounds[] = h .- heights_cumsum - texts_y = @views h .- 0.5 .* (heights_cumsum[1:end-1] .+ heights_cumsum[2:end]) + texts_y = @views h .- 0.5 .* (heights_cumsum[1:(end - 1)] .+ heights_cumsum[2:end]) textpositions[] = Point2f.(pad[1], texts_y) listheight[] = h w_bbox = width(bbox) @@ -174,7 +174,7 @@ function initialize_block!(m::Menu; default = 1) resize!(optionrects.val, length(bbs)) optionrects.val .= map(eachindex(bbs)) do i - BBox(0, w_bbox, h - heights_cumsum[i+1], h - heights_cumsum[i]) + BBox(0, w_bbox, h - heights_cumsum[i + 1], h - heights_cumsum[i]) end update_option_colors!(0) @@ -189,8 +189,8 @@ function initialize_block!(m::Menu; default = 1) # translation due to scrolling has to be removed first ytrans = y - translation(menuscene)[][2] i = argmin( - i -> abs(ytrans - 0.5 * (list_y_bounds[][i+1] + list_y_bounds[][i])), - 1:length(list_y_bounds[])-1 + i -> abs(ytrans - 0.5 * (list_y_bounds[][i + 1] + list_y_bounds[][i])), + 1:(length(list_y_bounds[]) - 1) ) end @@ -220,7 +220,7 @@ function initialize_block!(m::Menu; default = 1) return false end - onany(e.mouseposition, e.mousebutton, priority=64) do position, butt + onany(e.mouseposition, e.mousebutton, priority = 64) do position, butt mp = screen_relative(menuscene, position) # track if we have been inside menu/options to clean up if we haven't been is_over_options = false @@ -289,7 +289,7 @@ function initialize_block!(m::Menu; default = 1) return Consume(false) end - on(menuscene.events.scroll, priority=61) do (x, y) + on(menuscene.events.scroll, priority = 61) do (x, y) if is_mouseinside(menuscene) t = translation(menuscene)[] new_y = max(min(t[2] - y, 0), height(menuscene.px_area[]) - listheight[]) @@ -361,7 +361,7 @@ function initialize_block!(m::Menu; default = 1) if i === nothing error("Initial menu selection was set to $(default) but that was not found in the option names.") end - m.i_selected[] = i + m.i_selected[] = i end notify(m.is_open) @@ -375,7 +375,7 @@ function optionlabel(option) string(option) end -function optionlabel(option::Tuple{Any, Any}) +function optionlabel(option::Tuple{Any,Any}) string(option[1]) end @@ -383,6 +383,6 @@ function optionvalue(option) option end -function optionvalue(option::Tuple{Any, Any}) +function optionvalue(option::Tuple{Any,Any}) option[2] end diff --git a/src/makielayout/blocks/scene.jl b/src/makielayout/blocks/scene.jl index f1c05989190..c6a61413871 100644 --- a/src/makielayout/blocks/scene.jl +++ b/src/makielayout/blocks/scene.jl @@ -1,7 +1,7 @@ function Makie.plot!( - lscene::LScene, P::Makie.PlotFunc, - attributes::Makie.Attributes, args...; - kw_attributes...) + lscene::LScene, P::Makie.PlotFunc, + attributes::Makie.Attributes, args...; + kw_attributes...) plot = Makie.plot!(lscene.scene, P, attributes, args...; kw_attributes...) notify(lscene.scene.theme.limits) @@ -19,7 +19,7 @@ end function initialize_block!(ls::LScene; scenekw = NamedTuple()) blockscene = ls.blockscene # pick a camera and draw axis. - scenekw = merge((clear = false, camera=cam3d!), scenekw) + scenekw = merge((clear = false, camera = cam3d!), scenekw) ls.scene = Scene(blockscene, lift(round_to_IRect2D, ls.layoutobservables.computedbbox); scenekw...) on(ls.show_axis) do show_axis @@ -42,7 +42,7 @@ function initialize_block!(ls::LScene; scenekw = NamedTuple()) end Makie.axis3d!(ls.scene, limits) # Make sure axis is always in pos 1 - sort!(ls.scene.plots, by=!Makie.isaxis) + sort!(ls.scene.plots, by = !Makie.isaxis) else ax.visible = true end diff --git a/src/makielayout/blocks/slider.jl b/src/makielayout/blocks/slider.jl index 000b5f8ff72..7791a94e537 100644 --- a/src/makielayout/blocks/slider.jl +++ b/src/makielayout/blocks/slider.jl @@ -3,7 +3,7 @@ function initialize_block!(sl::Slider) topscene = sl.blockscene sliderrange = sl.range - + onany(sl.linewidth, sl.horizontal) do lw, horizontal if horizontal sl.layoutobservables.autosize[] = (nothing, Float32(lw)) @@ -21,12 +21,12 @@ function initialize_block!(sl::Slider) if horizontal y = bottom(bb) + h / 2 - [Point2f(left(bb) + h/2, y), - Point2f(right(bb) - h/2, y)] + [Point2f(left(bb) + h / 2, y), + Point2f(right(bb) - h / 2, y)] else x = left(bb) + w / 2 - [Point2f(x, bottom(bb) + w/2), - Point2f(x, top(bb) - w/2)] + [Point2f(x, bottom(bb) + w / 2), + Point2f(x, top(bb) - w / 2)] end end @@ -79,7 +79,7 @@ function initialize_block!(sl::Slider) end endbuttons = scatter!(topscene, endpoints, color = linecolors, - markersize = sl.linewidth, strokewidth = 0, inspectable = false, marker=Circle) + markersize = sl.linewidth, strokewidth = 0, inspectable = false, marker = Circle) linesegs = linesegments!(topscene, linepoints, color = linecolors, linewidth = sl.linewidth, inspectable = false) @@ -87,7 +87,7 @@ function initialize_block!(sl::Slider) button_magnification = Observable(1.0) buttonsize = @lift($(sl.linewidth) * $button_magnification) button = scatter!(topscene, middlepoint, color = sl.color_active, strokewidth = 0, - markersize = buttonsize, inspectable = false, marker=Circle) + markersize = buttonsize, inspectable = false, marker = Circle) mouseevents = addmouseevents!(topscene, sl.layoutobservables.computedbbox) @@ -95,10 +95,10 @@ function initialize_block!(sl::Slider) dragging[] = true dif = event.px - event.prev_px fraction = clamp(if sl.horizontal[] - (event.px[1] - endpoints[][1][1]) / (endpoints[][2][1] - endpoints[][1][1]) - else - (event.px[2] - endpoints[][1][2]) / (endpoints[][2][2] - endpoints[][1][2]) - end, 0, 1) + (event.px[1] - endpoints[][1][1]) / (endpoints[][2][1] - endpoints[][1][1]) + else + (event.px[2] - endpoints[][1][2]) / (endpoints[][2][2] - endpoints[][1][2]) + end, 0, 1) newindex = closest_fractionindex(sliderrange[], fraction) if sl.snap[] diff --git a/src/makielayout/blocks/textbox.jl b/src/makielayout/blocks/textbox.jl index 9c4b21fa1d0..cea74d3c09b 100644 --- a/src/makielayout/blocks/textbox.jl +++ b/src/makielayout/blocks/textbox.jl @@ -90,7 +90,7 @@ function initialize_block!(tbox::Textbox) end if 0 < ci < length(bbs) - [leftline(bbs[ci+1])...] + [leftline(bbs[ci + 1])...] elseif ci == 0 [leftline(bbs[1])...] else @@ -125,7 +125,7 @@ function initialize_block!(tbox::Textbox) pos = state.data closest_charindex = argmin( - [sum((pos .- center(bb)).^2) for bb in displayed_charbbs[]] + [sum((pos .- center(bb)) .^ 2) for bb in displayed_charbbs[]] ) # set cursor to index of closest char if right of center, or previous char if left of center cursorindex[] = if (pos .- center(displayed_charbbs[][closest_charindex]))[1] > 0 @@ -160,7 +160,7 @@ function initialize_block!(tbox::Textbox) empty!(displayed_chars[]) index = 1 end - newchars = [displayed_chars[][1:index-1]; c; displayed_chars[][index:end]] + newchars = [displayed_chars[][1:(index - 1)]; c; displayed_chars[][index:end]] tbox.displayed_string[] = join(newchars) cursorindex[] = index end @@ -170,7 +170,7 @@ function initialize_block!(tbox::Textbox) end function removechar!(index) - newchars = [displayed_chars[][1:index-1]; displayed_chars[][index+1:end]] + newchars = [displayed_chars[][1:(index - 1)]; displayed_chars[][(index + 1):end]] if isempty(newchars) newchars = [' '] @@ -343,7 +343,7 @@ function focus!(tb::Textbox) [0, 1.0], [Colors.alphacolor(COLOR_ACCENT[], 0), Colors.alphacolor(COLOR_ACCENT[], 1)], Animations.sineio(n = 2, yoyo = true, postwait = 0.2)), - 0.0, 0.0, 1000) + 0.0, 0.0, 1000) if !isnothing(tb.cursoranimtask) Animations.stop(tb.cursoranimtask) diff --git a/src/makielayout/blocks/toggle.jl b/src/makielayout/blocks/toggle.jl index 6cdc5bb4d4c..146eca94b86 100644 --- a/src/makielayout/blocks/toggle.jl +++ b/src/makielayout/blocks/toggle.jl @@ -75,7 +75,7 @@ function initialize_block!(t::Toggle) animating[] = false break end - sleep(1/FPS[]) + sleep(1 / FPS[]) end return Consume(true) end diff --git a/src/makielayout/geometrybasics_extension.jl b/src/makielayout/geometrybasics_extension.jl index 3edcc050fbe..895d06cd127 100644 --- a/src/makielayout/geometrybasics_extension.jl +++ b/src/makielayout/geometrybasics_extension.jl @@ -18,7 +18,7 @@ function shrinkbymargin(rect, margin) return Recti(minimum(rect) .+ margin, (widths(rect) .- 2 .* margin)) end -function limits(r::Rect{N, T}) where {N, T} +function limits(r::Rect{N,T}) where {N,T} mini, maxi = extrema(r) return ntuple(i -> (mini[i], maxi[i]), N) end @@ -41,7 +41,7 @@ end """ Converts a point in fractions of rect dimensions into real coordinates. """ -function fractionpoint(bbox::Rect2f, point::T) where T <: Point2 +function fractionpoint(bbox::Rect2f, point::T) where T<:Point2 T(left(bbox) + point[1] * width(bbox), bottom(bbox) + point[2] * height(bbox)) end diff --git a/src/makielayout/helpers.jl b/src/makielayout/helpers.jl index 5d0b24ef525..27a1fcaea26 100644 --- a/src/makielayout/helpers.jl +++ b/src/makielayout/helpers.jl @@ -7,11 +7,11 @@ function round_to_IRect2D(r::Rect{2}) newori = round.(Int, minimum(r)) othercorner = round.(Int, maximum(r)) newwidth = othercorner .- newori - Rect{2, Int}(newori, newwidth) + Rect{2,Int}(newori, newwidth) end function sceneareanode!(finalbbox, limits, aspect) - return map(finalbbox, limits, aspect; ignore_equal_values=true) do bbox, limits, aspect + return map(finalbbox, limits, aspect; ignore_equal_values = true) do bbox, limits, aspect w = width(bbox) h = height(bbox) @@ -67,24 +67,24 @@ function roundedrectvertices(rect, cornerradius, cornersegments) htouching = height(rect) / 2 == cr cstr = if wtouching - anglepoint.(Ref(ictr), LinRange(0, pi/2, csegs), cr) + anglepoint.(Ref(ictr), LinRange(0, pi / 2, csegs), cr) else - anglepoint.(Ref(ictr), LinRange(0, pi/2, csegs)[1:end-1], cr) + anglepoint.(Ref(ictr), LinRange(0, pi / 2, csegs)[1:(end - 1)], cr) end cstl = if htouching - anglepoint.(Ref(ictl), LinRange(pi/2, pi, csegs), cr) + anglepoint.(Ref(ictl), LinRange(pi / 2, pi, csegs), cr) else - anglepoint.(Ref(ictl), LinRange(pi/2, pi, csegs)[1:end-1], cr) + anglepoint.(Ref(ictl), LinRange(pi / 2, pi, csegs)[1:(end - 1)], cr) end csbl = if wtouching - anglepoint.(Ref(icbl), LinRange(pi, 3pi/2, csegs), cr) + anglepoint.(Ref(icbl), LinRange(pi, 3pi / 2, csegs), cr) else - anglepoint.(Ref(icbl), LinRange(pi, 3pi/2, csegs)[1:end-1], cr) + anglepoint.(Ref(icbl), LinRange(pi, 3pi / 2, csegs)[1:(end - 1)], cr) end csbr = if htouching - anglepoint.(Ref(icbr), LinRange(3pi/2, 2pi, csegs), cr) + anglepoint.(Ref(icbr), LinRange(3pi / 2, 2pi, csegs), cr) else - anglepoint.(Ref(icbr), LinRange(3pi/2, 2pi, csegs)[1:end-1], cr) + anglepoint.(Ref(icbr), LinRange(3pi / 2, 2pi, csegs)[1:(end - 1)], cr) end arr = [cstr; cstl; csbl; csbr] end @@ -111,7 +111,7 @@ Example: tightlimits!(laxis, Bottom()) ``` """ -function tightlimits!(la::Axis, sides::Union{Left, Right, Bottom, Top}...) +function tightlimits!(la::Axis, sides::Union{Left,Right,Bottom,Top}...) for s in sides tightlimits!(la, s) end @@ -172,13 +172,13 @@ function axislines!(scene, rect, spinewidth, topspinevisible, rightspinevisible, end (lines!(scene, bottomline, linewidth = spinewidth, - visible = bottomspinevisible, color = bottomspinecolor), - lines!(scene, leftline, linewidth = spinewidth, - visible = leftspinevisible, color = leftspinecolor), - lines!(scene, rightline, linewidth = spinewidth, - visible = rightspinevisible, color = rightspinecolor), - lines!(scene, topline, linewidth = spinewidth, - visible = topspinevisible, color = topspinecolor)) + visible = bottomspinevisible, color = bottomspinecolor), + lines!(scene, leftline, linewidth = spinewidth, + visible = leftspinevisible, color = leftspinecolor), + lines!(scene, rightline, linewidth = spinewidth, + visible = rightspinevisible, color = rightspinecolor), + lines!(scene, topline, linewidth = spinewidth, + visible = topspinevisible, color = topspinecolor)) end @@ -249,17 +249,17 @@ macro documented_attributes(exp) # make a dictionary of :variable_name => docstring_expression exp_docdict = Expr(:call, :Dict, (Expr(:call, Symbol("=>"), QuoteNode(name), strexp) - for (name, _, strexp) in vars_and_exps)...) + for (name, _, strexp) in vars_and_exps)...) # make a dictionary of :variable_name => docstring_expression defaults_dict = Expr(:call, :Dict, (Expr(:call, Symbol("=>"), QuoteNode(name), exp isa String ? "\"$exp\"" : string(exp)) - for (name, exp, _) in vars_and_exps)...) + for (name, exp, _) in vars_and_exps)...) # make an Attributes instance with of variable_name = variable_expression exp_attrs = Expr(:call, :Attributes, (Expr(:kw, name, exp) - for (name, exp, _) in vars_and_exps)...) + for (name, exp, _) in vars_and_exps)...) esc(quote ($exp_attrs, $exp_docdict, $defaults_dict) @@ -317,13 +317,13 @@ layout[1, 1] = ls.layout ``` """ function labelslider!(scene, label, range; format = string, - sliderkw = Dict(), labelkw = Dict(), valuekw = Dict(), value_column_width = automatic, layoutkw...) + sliderkw = Dict(), labelkw = Dict(), valuekw = Dict(), value_column_width = automatic, layoutkw...) slider = Slider(scene; range = range, sliderkw...) label = Label(scene, label; labelkw...) valuelabel = Label(scene, lift(x -> apply_format(x, format), slider.value); valuekw...) layout = hbox!(label, slider, valuelabel; layoutkw...) - Base.depwarn("labelslider! is deprecated and will be removed in the future. Use SliderGrid instead." , :labelslider!, force = true) + Base.depwarn("labelslider! is deprecated and will be removed in the future. Use SliderGrid instead.", :labelslider!, force = true) if value_column_width === automatic maxwidth = 0.0 @@ -376,9 +376,9 @@ layout[1, 1] = ls.layout ``` """ function labelslidergrid!(scene, labels, ranges; formats = [string], value_column_width = automatic, - sliderkw = Dict(), labelkw = Dict(), valuekw = Dict(), layoutkw...) + sliderkw = Dict(), labelkw = Dict(), valuekw = Dict(), layoutkw...) - Base.depwarn("labelslidergrid! is deprecated and will be removed in the future. Use SliderGrid instead." , :labelslidergrid!, force = true) + Base.depwarn("labelslidergrid! is deprecated and will be removed in the future. Use SliderGrid instead.", :labelslidergrid!, force = true) elements = broadcast(labels, ranges, formats) do label, range, format slider = Slider(scene; range = range, sliderkw...) diff --git a/src/makielayout/interactions.jl b/src/makielayout/interactions.jl index 537f114a552..3fbe98839d7 100644 --- a/src/makielayout/interactions.jl +++ b/src/makielayout/interactions.jl @@ -151,7 +151,7 @@ function process_interaction(r::RectangleZoom, event::MouseEvent, ax::Axis) inv_transf = Makie.inverse_transform(transf) if isnothing(inv_transf) - @warn "Can't rectangle zoom without inverse transform" maxlog=1 + @warn "Can't rectangle zoom without inverse transform" maxlog = 1 # TODO, what can we do without inverse? return Consume(false) end @@ -179,7 +179,7 @@ function process_interaction(r::RectangleZoom, event::MouseEvent, ax::Axis) try r.callback(r.rectnode[]) catch e - @warn "error in rectangle zoom" exception=e + @warn "error in rectangle zoom" exception = e end r.active[] = false return Consume(true) @@ -188,10 +188,10 @@ function process_interaction(r::RectangleZoom, event::MouseEvent, ax::Axis) return Consume(false) end -function rectclamp(p::Point{N, T}, r::Rect) where {N, T} +function rectclamp(p::Point{N,T}, r::Rect) where {N,T} mi, ma = extrema(r) p = clamp.(p, mi, ma) - return Point{N, T}(p) + return Point{N,T}(p) end function process_interaction(r::RectangleZoom, event::KeysEvent, ax::Axis) @@ -248,11 +248,11 @@ function process_interaction(s::ScrollZoom, event::ScrollEvent, ax::Axis) mp_axscene = Vec4f((e.mouseposition[] .- pa.origin)..., 0, 1) # first to normal -1..1 space - mp_axfraction = (cam.pixel_space[] * mp_axscene)[Vec(1, 2)] .* - # now to 1..-1 if an axis is reversed to correct zoom point - (-2 .* ((ax.xreversed[], ax.yreversed[])) .+ 1) .* - # now to 0..1 - 0.5 .+ 0.5 + mp_axfraction = (cam.pixel_space[] * mp_axscene)[Vec(1, 2)] .* + # now to 1..-1 if an axis is reversed to correct zoom point + (-2 .* ((ax.xreversed[], ax.yreversed[])) .+ 1) .* + # now to 0..1 + 0.5 .+ 0.5 xscale = ax.xscale[] yscale = ax.yscale[] @@ -361,7 +361,7 @@ function process_interaction(dr::DragRotate, event::MouseEvent, ax3d) dpx = event.px - event.prev_px ax3d.azimuth[] += -dpx[1] * 0.01 - ax3d.elevation[] = clamp(ax3d.elevation[] - dpx[2] * 0.01, -pi/2 + 0.001, pi/2 - 0.001) + ax3d.elevation[] = clamp(ax3d.elevation[] - dpx[2] * 0.01, -pi / 2 + 0.001, pi / 2 - 0.001) return Consume(true) end diff --git a/src/makielayout/lineaxis.jl b/src/makielayout/lineaxis.jl index aed8d714e90..3c355b8cc12 100644 --- a/src/makielayout/lineaxis.jl +++ b/src/makielayout/lineaxis.jl @@ -3,7 +3,7 @@ function LineAxis(parent::Scene; @nospecialize(kwargs...)) return LineAxis(parent, attrs) end -function calculate_horizontal_extends(endpoints)::Tuple{Float32, NTuple{2, Float32}, Bool} +function calculate_horizontal_extends(endpoints)::Tuple{Float32,NTuple{2,Float32},Bool} if endpoints[1][2] == endpoints[2][2] horizontal = true extents = (endpoints[1][1], endpoints[2][1]) @@ -21,9 +21,9 @@ end function calculate_protrusion( - closure_args, - ticksvisible::Bool, label, labelvisible::Bool, labelpadding::Number, tickspace::Number, ticklabelsvisible::Bool, - actual_ticklabelspace::Number, ticklabelpad::Number, _...) + closure_args, + ticksvisible::Bool, label, labelvisible::Bool, labelpadding::Number, tickspace::Number, ticklabelsvisible::Bool, + actual_ticklabelspace::Number, ticklabelpad::Number, _...) horizontal, labeltext, ticklabel_annotation_obs = closure_args @@ -46,10 +46,10 @@ end function create_linepoints( - pos_ext_hor, - flipped::Bool, spine_width::Number, trimspine::Union{Bool, Tuple{Bool, Bool}}, tickpositions::Vector{Point2f}, tickwidth::Number) + pos_ext_hor, + flipped::Bool, spine_width::Number, trimspine::Union{Bool,Tuple{Bool,Bool}}, tickpositions::Vector{Point2f}, tickwidth::Number) - (position::Float32, extents::NTuple{2, Float32}, horizontal::Bool) = pos_ext_hor + (position::Float32, extents::NTuple{2,Float32}, horizontal::Bool) = pos_ext_hor if trimspine isa Bool trimspine = (trimspine, trimspine) @@ -97,13 +97,13 @@ function calculate_real_ticklabel_align(al, horizontal, fl::Bool, rot::Number) else (fl ? :left : :right, :center) end - elseif rot ≈ pi/2 + elseif rot ≈ pi / 2 if hor (fl ? :left : :right, :center) else (:center, fl ? :top : :bottom) end - elseif rot ≈ -pi/2 + elseif rot ≈ -pi / 2 if hor (fl ? :right : :left, :center) else @@ -122,7 +122,7 @@ function calculate_real_ticklabel_align(al, horizontal, fl::Bool, rot::Number) (fl ? :left : :right, :center) end end - elseif al isa NTuple{2, Symbol} + elseif al isa NTuple{2,Symbol} return al else error("Align needs to be a NTuple{2, Symbol}.") @@ -130,9 +130,9 @@ function calculate_real_ticklabel_align(al, horizontal, fl::Bool, rot::Number) end function update_ticklabel_node( - closure_args, - ticklabel_annotation_obs::Observable, - labelgap::Number, flipped::Bool, tickpositions::Vector{Point2f}, tickstrings) + closure_args, + ticklabel_annotation_obs::Observable, + labelgap::Number, flipped::Bool, tickpositions::Vector{Point2f}, tickstrings) # tickspace is always updated before labelgap # tickpositions are always updated before tickstrings # so we don't need to lift those @@ -185,11 +185,11 @@ end function update_tickpos_string(closure_args, tickvalues_labels_unfiltered, reversed::Bool, scale) tickstrings, tickpositions, tickvalues, pos_extents_horizontal, limits_obs = closure_args - limits = limits_obs[]::NTuple{2, Float32} + limits = limits_obs[]::NTuple{2,Float32} tickvalues_unfiltered, tickstrings_unfiltered = tickvalues_labels_unfiltered - position::Float32, extents_uncorrected::NTuple{2, Float32}, horizontal::Bool = pos_extents_horizontal[] + position::Float32, extents_uncorrected::NTuple{2,Float32}, horizontal::Bool = pos_extents_horizontal[] extents = reversed ? reverse(extents_uncorrected) : extents_uncorrected @@ -203,7 +203,7 @@ function update_tickpos_string(closure_args, tickvalues_labels_unfiltered, rever # we only check approximately because otherwise because of floating point errors, ticks can be dismissed sometimes i_values_within_limits = findall(tickvalues_unfiltered) do tv return (limits[1] <= tv || limits[1] ≈ tv) && - (tv <= limits[2] || tv ≈ limits[2]) + (tv <= limits[2] || tv ≈ limits[2]) end tickvalues[] = tickvalues_unfiltered[i_values_within_limits] @@ -226,8 +226,8 @@ function update_tickpos_string(closure_args, tickvalues_labels_unfiltered, rever return end -function update_minor_ticks(minortickpositions, limits::NTuple{2, Float32}, pos_extents_horizontal, minortickvalues, scale, reversed::Bool) - position::Float32, extents_uncorrected::NTuple{2, Float32}, horizontal::Bool = pos_extents_horizontal +function update_minor_ticks(minortickpositions, limits::NTuple{2,Float32}, pos_extents_horizontal, minortickvalues, scale, reversed::Bool) + position::Float32, extents_uncorrected::NTuple{2,Float32}, horizontal::Bool = pos_extents_horizontal extents = reversed ? reverse(extents_uncorrected) : extents_uncorrected @@ -253,7 +253,7 @@ function update_minor_ticks(minortickpositions, limits::NTuple{2, Float32}, pos_ end function LineAxis(parent::Scene, attrs::Attributes) - decorations = Dict{Symbol, Any}() + decorations = Dict{Symbol,Any}() @extract attrs (endpoints, ticksize, tickwidth, tickcolor, tickalign, ticks, tickformat, ticklabelalign, ticklabelrotation, ticksvisible, @@ -263,13 +263,13 @@ function LineAxis(parent::Scene, attrs::Attributes) labelrotation, labelvisible, spinevisible, trimspine, flip_vertical_label, reversed, minorticksvisible, minortickalign, minorticksize, minortickwidth, minortickcolor, minorticks) - pos_extents_horizontal = lift(calculate_horizontal_extends, endpoints; ignore_equal_values=true) - horizontal = lift(x-> x[3], pos_extents_horizontal) + pos_extents_horizontal = lift(calculate_horizontal_extends, endpoints; ignore_equal_values = true) + horizontal = lift(x -> x[3], pos_extents_horizontal) # Tuple constructor converts more than `convert(NTuple{2, Float32}, x)` but we still need the conversion to Float32 tuple: - limits = lift(x-> convert(NTuple{2, Float32}, Tuple(x)), attrs.limits; ignore_equal_values=true) - flipped = lift(x-> convert(Bool, x), attrs.flipped; ignore_equal_values=true) + limits = lift(x -> convert(NTuple{2,Float32}, Tuple(x)), attrs.limits; ignore_equal_values = true) + flipped = lift(x -> convert(Bool, x), attrs.flipped; ignore_equal_values = true) - ticksnode = Observable(Point2f[]; ignore_equal_values=true) + ticksnode = Observable(Point2f[]; ignore_equal_values = true) ticklines = linesegments!( parent, ticksnode, linewidth = tickwidth, color = tickcolor, linestyle = nothing, visible = ticksvisible, inspectable = false @@ -277,7 +277,7 @@ function LineAxis(parent::Scene, attrs::Attributes) decorations[:ticklines] = ticklines translate!(ticklines, 0, 0, 10) - minorticksnode = Observable(Point2f[]; ignore_equal_values=true) + minorticksnode = Observable(Point2f[]; ignore_equal_values = true) minorticklines = linesegments!( parent, minorticksnode, linewidth = minortickwidth, color = minortickcolor, linestyle = nothing, visible = minorticksvisible, inspectable = false @@ -285,21 +285,21 @@ function LineAxis(parent::Scene, attrs::Attributes) decorations[:minorticklines] = minorticklines translate!(minorticklines, 0, 0, 10) - realticklabelalign = Observable{Tuple{Symbol, Symbol}}((:none, :none); ignore_equal_values=true) + realticklabelalign = Observable{Tuple{Symbol,Symbol}}((:none, :none); ignore_equal_values = true) map!(calculate_real_ticklabel_align, realticklabelalign, ticklabelalign, horizontal, flipped, ticklabelrotation) - ticklabel_annotation_obs = Observable(Tuple{AbstractString, Point2f}[]; ignore_equal_values=true) + ticklabel_annotation_obs = Observable(Tuple{AbstractString,Point2f}[]; ignore_equal_values = true) ticklabels = nothing # this gets overwritten later to be used in the below - ticklabel_ideal_space = Observable(0f0; ignore_equal_values=true) + ticklabel_ideal_space = Observable(0f0; ignore_equal_values = true) map!(ticklabel_ideal_space, ticklabel_annotation_obs, ticklabelalign, ticklabelrotation, ticklabelfont, ticklabelsvisible) do args... maxwidth = if pos_extents_horizontal[][3] - # height - ticklabelsvisible[] ? (ticklabels === nothing ? 0f0 : height(Rect2f(boundingbox(ticklabels)))) : 0f0 - else - # width - ticklabelsvisible[] ? (ticklabels === nothing ? 0f0 : width(Rect2f(boundingbox(ticklabels)))) : 0f0 + # height + ticklabelsvisible[] ? (ticklabels === nothing ? 0f0 : height(Rect2f(boundingbox(ticklabels)))) : 0f0 + else + # width + ticklabelsvisible[] ? (ticklabels === nothing ? 0f0 : width(Rect2f(boundingbox(ticklabels)))) : 0f0 end # in case there is no string in the annotations and the boundingbox comes back all NaN if !isfinite(maxwidth) @@ -322,22 +322,22 @@ function LineAxis(parent::Scene, attrs::Attributes) end end - tickspace = Observable(0f0; ignore_equal_values=true) + tickspace = Observable(0f0; ignore_equal_values = true) map!(tickspace, ticksvisible, ticksize, tickalign) do ticksvisible, ticksize, tickalign ticksvisible ? max(0f0, ticksize * (1f0 - tickalign)) : 0f0 end - labelgap = Observable(0f0; ignore_equal_values=true) + labelgap = Observable(0f0; ignore_equal_values = true) map!(labelgap, spinewidth, tickspace, ticklabelsvisible, actual_ticklabelspace, ticklabelpad, labelpadding) do spinewidth, tickspace, ticklabelsvisible, - actual_ticklabelspace, ticklabelpad, labelpadding + actual_ticklabelspace, ticklabelpad, labelpadding return spinewidth + tickspace + - (ticklabelsvisible ? actual_ticklabelspace + ticklabelpad : 0f0) + - labelpadding + (ticklabelsvisible ? actual_ticklabelspace + ticklabelpad : 0f0) + + labelpadding end - labelpos = Observable(Point2f(NaN); ignore_equal_values=true) + labelpos = Observable(Point2f(NaN); ignore_equal_values = true) map!(labelpos, pos_extents_horizontal, flipped, labelgap) do (position, extents, horizontal), flipped, labelgap # fullgap = tickspace[] + labelgap @@ -349,9 +349,9 @@ function LineAxis(parent::Scene, attrs::Attributes) end # Initial values should be overwritten by map!. `ignore_equal_values` doesn't work right now without initial values - labelalign = Observable((:none, :none); ignore_equal_values=true) + labelalign = Observable((:none, :none); ignore_equal_values = true) map!(labelalign, labelrotation, horizontal, flipped, flip_vertical_label) do labelrotation, - horizontal::Bool, flipped::Bool, flip_vertical_label::Bool + horizontal::Bool, flipped::Bool, flip_vertical_label::Bool return if labelrotation isa Automatic if horizontal (:center, flipped ? :bottom : :top) @@ -364,12 +364,12 @@ function LineAxis(parent::Scene, attrs::Attributes) end else (:center, :center) - end::NTuple{2, Symbol} + end::NTuple{2,Symbol} end - labelrot = Observable(0f0; ignore_equal_values=true) + labelrot = Observable(0f0; ignore_equal_values = true) map!(labelrot, labelrotation, horizontal, flip_vertical_label) do labelrotation, - horizontal::Bool, flip_vertical_label::Bool + horizontal::Bool, flip_vertical_label::Bool return if labelrotation isa Automatic if horizontal 0f0 @@ -407,23 +407,23 @@ function LineAxis(parent::Scene, attrs::Attributes) decorations[:labeltext] = labeltext - tickvalues = Observable(Float32[]; ignore_equal_values=true) + tickvalues = Observable(Float32[]; ignore_equal_values = true) tickvalues_labels_unfiltered = Observable{Tuple{Vector{Float32},Vector{AbstractString}}}() map!(tickvalues_labels_unfiltered, pos_extents_horizontal, limits, ticks, tickformat, attrs.scale) do (position, extents, horizontal), - limits, ticks, tickformat, scale + limits, ticks, tickformat, scale get_ticks(ticks, scale, tickformat, limits...) end - tickpositions = Observable(Point2f[]; ignore_equal_values=true) - tickstrings = Observable(AbstractString[]; ignore_equal_values=true) + tickpositions = Observable(Point2f[]; ignore_equal_values = true) + tickstrings = Observable(AbstractString[]; ignore_equal_values = true) onany(update_tickpos_string, Observable((tickstrings, tickpositions, tickvalues, pos_extents_horizontal, limits)), tickvalues_labels_unfiltered, reversed, attrs.scale) - minortickvalues = Observable(Float32[]; ignore_equal_values=true) - minortickpositions = Observable(Point2f[]; ignore_equal_values=true) + minortickvalues = Observable(Float32[]; ignore_equal_values = true) + minortickpositions = Observable(Point2f[]; ignore_equal_values = true) onany(tickvalues, minorticks) do tickvalues, minorticks minortickvalues[] = get_minor_tickvalues(minorticks, attrs.scale[], tickvalues, limits[]...) @@ -455,7 +455,7 @@ function LineAxis(parent::Scene, attrs::Attributes) translate!(decorations[:axisline], 0, 0, 20) - protrusion = Observable(0f0; ignore_equal_values=true) + protrusion = Observable(0f0; ignore_equal_values = true) map!(calculate_protrusion, protrusion, # we pass these as observables, to not trigger on them @@ -508,11 +508,11 @@ function tight_ticklabel_spacing!(la::LineAxis) tls = la.elements[:ticklabels] maxwidth = if horizontal - # height - tls.visible[] ? height(Rect2f(boundingbox(tls))) : 0f0 - else - # width - tls.visible[] ? width(Rect2f(boundingbox(tls))) : 0f0 + # height + tls.visible[] ? height(Rect2f(boundingbox(tls))) : 0f0 + else + # width + tls.visible[] ? width(Rect2f(boundingbox(tls))) : 0f0 end la.attributes.ticklabelspace = maxwidth return Float64(maxwidth) @@ -555,7 +555,7 @@ get_tickvalues(::Automatic, F, vmin, vmax) = get_tickvalues(automatic, identity, # fall back to non-scale aware behavior if no special version is overloaded get_tickvalues(ticks, scale, vmin, vmax) = get_tickvalues(ticks, vmin, vmax) -function get_ticks(ticks_and_labels::Tuple{Any, Any}, any_scale, ::Automatic, vmin, vmax) +function get_ticks(ticks_and_labels::Tuple{Any,Any}, any_scale, ::Automatic, vmin, vmax) n1 = length(ticks_and_labels[1]) n2 = length(ticks_and_labels[2]) if n1 != n2 @@ -566,7 +566,7 @@ end function get_ticks(tickfunction::Function, any_scale, formatter, vmin, vmax) result = tickfunction(vmin, vmax) - if result isa Tuple{Any, Any} + if result isa Tuple{Any,Any} tickvalues, ticklabels = result else tickvalues = result @@ -580,13 +580,13 @@ _logbase(::typeof(log2)) = "2" _logbase(::typeof(log)) = "e" -function get_ticks(::Automatic, scale::Union{typeof(log10), typeof(log2), typeof(log)}, - any_formatter, vmin, vmax) +function get_ticks(::Automatic, scale::Union{typeof(log10),typeof(log2),typeof(log)}, + any_formatter, vmin, vmax) get_ticks(LogTicks(WilkinsonTicks(5, k_min = 3)), scale, any_formatter, vmin, vmax) end # log ticks just use the normal pipeline but with log'd limits, then transform the labels -function get_ticks(l::LogTicks, scale::Union{typeof(log10), typeof(log2), typeof(log)}, ::Automatic, vmin, vmax) +function get_ticks(l::LogTicks, scale::Union{typeof(log10),typeof(log2),typeof(log)}, ::Automatic, vmin, vmax) ticks_scaled = get_tickvalues(l.linear_ticks, identity, scale(vmin), scale(vmax)) ticks = Makie.inverse_transform(scale).(ticks_scaled) @@ -696,21 +696,21 @@ function get_minor_tickvalues(i::IntervalsBetween, scale, tickvalues, vmin, vmax firstinterval = tickvalues[2] - tickvalues[1] stepsize = firstinterval / n v = tickvalues[1] - stepsize - prepend!(vals, v:-stepsize:vmin) + prepend!(vals, v:(-stepsize):vmin) end - for (lo, hi) in zip(@view(tickvalues[1:end-1]), @view(tickvalues[2:end])) + for (lo, hi) in zip(@view(tickvalues[1:(end - 1)]), @view(tickvalues[2:end])) interval = hi - lo stepsize = interval / n v = lo - for i in 1:n-1 + for i in 1:(n - 1) v += stepsize push!(vals, v) end end if i.mirror - lastinterval = tickvalues[end] - tickvalues[end-1] + lastinterval = tickvalues[end] - tickvalues[end - 1] stepsize = lastinterval / n v = tickvalues[end] + stepsize append!(vals, v:stepsize:vmax) @@ -720,7 +720,7 @@ function get_minor_tickvalues(i::IntervalsBetween, scale, tickvalues, vmin, vmax end # for log scales, we need to step in log steps at the edges -function get_minor_tickvalues(i::IntervalsBetween, scale::Union{typeof(log), typeof(log2), typeof(log10)}, tickvalues, vmin, vmax) +function get_minor_tickvalues(i::IntervalsBetween, scale::Union{typeof(log),typeof(log2),typeof(log10)}, tickvalues, vmin, vmax) vals = Float64[] length(tickvalues) < 2 && return vals @@ -734,21 +734,21 @@ function get_minor_tickvalues(i::IntervalsBetween, scale::Union{typeof(log), typ prevtick = invscale(scale(tickvalues[1]) - firstinterval_scaled) stepsize = (tickvalues[1] - prevtick) / n v = tickvalues[1] - stepsize - prepend!(vals, v:-stepsize:vmin) + prepend!(vals, v:(-stepsize):vmin) end - for (lo, hi) in zip(@view(tickvalues[1:end-1]), @view(tickvalues[2:end])) + for (lo, hi) in zip(@view(tickvalues[1:(end - 1)]), @view(tickvalues[2:end])) interval = hi - lo stepsize = interval / n v = lo - for i in 1:n-1 + for i in 1:(n - 1) v += stepsize push!(vals, v) end end if i.mirror - lastinterval_scaled = scale(tickvalues[end]) - scale(tickvalues[end-1]) + lastinterval_scaled = scale(tickvalues[end]) - scale(tickvalues[end - 1]) nexttick = invscale(scale(tickvalues[end]) + lastinterval_scaled) stepsize = (nexttick - tickvalues[end]) / n v = tickvalues[end] + stepsize diff --git a/src/makielayout/mousestatemachine.jl b/src/makielayout/mousestatemachine.jl index 40653697f4a..f3dc8cd609c 100644 --- a/src/makielayout/mousestatemachine.jl +++ b/src/makielayout/mousestatemachine.jl @@ -1,32 +1,32 @@ module MouseEventTypes - @enum MouseEventType begin - out - enter - over - leftdown - rightdown - middledown - leftup - rightup - middleup - leftdragstart - rightdragstart - middledragstart - leftdrag - rightdrag - middledrag - leftdragstop - rightdragstop - middledragstop - leftclick - rightclick - middleclick - leftdoubleclick - rightdoubleclick - middledoubleclick - downoutside - end - export MouseEventType +@enum MouseEventType begin + out + enter + over + leftdown + rightdown + middledown + leftup + rightup + middleup + leftdragstart + rightdragstart + middledragstart + leftdrag + rightdrag + middledrag + leftdragstop + rightdragstop + middledragstop + leftclick + rightclick + middleclick + leftdoubleclick + rightdoubleclick + middledoubleclick + downoutside +end +export MouseEventType end using .MouseEventTypes @@ -116,7 +116,7 @@ function addmouseevents!(scene, elements...; priority = 1) is_mouse_over_relevant_area() = isempty(elements) ? Makie.is_mouseinside(scene) : mouseover(scene, elements...) _addmouseevents!(scene, is_mouse_over_relevant_area, priority) end -function addmouseevents!(scene, bbox::Observables.AbstractObservable{<: Rect2}; priority = 1) +function addmouseevents!(scene, bbox::Observables.AbstractObservable{<:Rect2}; priority = 1) is_mouse_over_relevant_area() = Makie.mouseposition_px(scene) in bbox[] _addmouseevents!(scene, is_mouse_over_relevant_area, priority) end @@ -143,7 +143,7 @@ function _addmouseevents!(scene, is_mouse_over_relevant_area, priority) last_click_was_double = Ref(false) # react to mouse position changes - mousepos_observerfunc = on(events(scene).mouseposition, priority=priority) do mp + mousepos_observerfunc = on(events(scene).mouseposition, priority = priority) do mp consumed = false t = time() data = mouseposition(scene) @@ -229,7 +229,7 @@ function _addmouseevents!(scene, is_mouse_over_relevant_area, priority) # react to mouse button changes - mousedrag_observerfunc = on(events(scene).mousebutton, priority=priority) do event + mousedrag_observerfunc = on(events(scene).mousebutton, priority = priority) do event consumed = false t = time() data = prev_data[] @@ -318,7 +318,7 @@ function _addmouseevents!(scene, is_mouse_over_relevant_area, priority) # guard against mouse coming in from outside, then mouse upping if mouse_downed_inside[] if dt_last_click < dblclick_max_interval && !last_click_was_double[] && - mouse_downed_button[] == b_last_click[] + mouse_downed_button[] == b_last_click[] event = @match mouse_downed_button[] begin Mouse.left => MouseEventTypes.leftdoubleclick diff --git a/src/makielayout/roundedrect.jl b/src/makielayout/roundedrect.jl index f8109fe645a..26eb53c49f0 100644 --- a/src/makielayout/roundedrect.jl +++ b/src/makielayout/roundedrect.jl @@ -17,7 +17,7 @@ function plot!(roundrect::RoundedRect) widthattr = roundrect.width roundedrectpoints = lift(rect, cornerradius, cornersegments) do rect, - cr, csegs + cr, csegs cr = min(width(rect) / 2, height(rect) / 2, cr) @@ -27,10 +27,10 @@ function plot!(roundrect::RoundedRect) icbl = bottomleft(rect) .+ Point2(cr, cr) icbr = bottomright(rect) .+ Point2(-cr, cr) - cstr = anglepoint.(Ref(ictr), LinRange(0, pi/2, csegs), cr) - cstl = anglepoint.(Ref(ictl), LinRange(pi/2, pi, csegs), cr) - csbl = anglepoint.(Ref(icbl), LinRange(pi, 3pi/2, csegs), cr) - csbr = anglepoint.(Ref(icbr), LinRange(3pi/2, 2pi, csegs), cr) + cstr = anglepoint.(Ref(ictr), LinRange(0, pi / 2, csegs), cr) + cstl = anglepoint.(Ref(ictl), LinRange(pi / 2, pi, csegs), cr) + csbl = anglepoint.(Ref(icbl), LinRange(pi, 3pi / 2, csegs), cr) + csbr = anglepoint.(Ref(icbr), LinRange(3pi / 2, 2pi, csegs), cr) return [cstr; cstl; csbl; csbr] end diff --git a/src/makielayout/ticklocators/linear.jl b/src/makielayout/ticklocators/linear.jl index 75e6d02c133..5d5d290bd98 100644 --- a/src/makielayout/ticklocators/linear.jl +++ b/src/makielayout/ticklocators/linear.jl @@ -1,23 +1,23 @@ -function scale_range(vmin, vmax, n=1, threshold=100) +function scale_range(vmin, vmax, n = 1, threshold = 100) dv = abs(vmax - vmin) # > 0 as nonsingular is called before. meanv = (vmax + vmin) / 2 offset = if abs(meanv) / dv < threshold 0.0 else - copysign(10 ^ (log10(abs(meanv)) ÷ 1), meanv) + copysign(10^(log10(abs(meanv)) ÷ 1), meanv) end - scale = 10 ^ (log10(dv / n) ÷ 1) + scale = 10^(log10(dv / n) ÷ 1) scale, offset end function _staircase(steps) n = length(steps) result = Vector{Float64}(undef, 2n) - for i in 1:(n-1) + for i in 1:(n - 1) @inbounds result[i] = 0.1 * steps[i] end for i in 1:n - @inbounds result[i+(n-1)] = steps[i] + @inbounds result[i + (n - 1)] = steps[i] end result[end] = 10 * steps[2] return result @@ -40,7 +40,7 @@ end function closeto(e::EdgeInteger, ms, edge) tol = if e.offset > 0 digits = log10(e.offset / e.step) - tol = max(1e-10, 10 ^ (digits - 12)) + tol = max(1e-10, 10^(digits - 12)) min(0.4999, tol) else 1e-10 @@ -142,7 +142,7 @@ function locateticks(vmin, vmax, n_ideal::Int, _integer::Bool = false, _min_n_ti # 0.08000000001 instead of 0.08 # so here we round off the numbers to the required number of digits after the decimal point exponent = floor(Int, minimum(log10.(abs.(diff(vals))))) - round.(vals, digits = max(0, -exponent+1)) + round.(vals, digits = max(0, -exponent + 1)) end diff --git a/src/makielayout/ticklocators/wilkinson.jl b/src/makielayout/ticklocators/wilkinson.jl index 2e5922db448..6b44fb5b585 100644 --- a/src/makielayout/ticklocators/wilkinson.jl +++ b/src/makielayout/ticklocators/wilkinson.jl @@ -1,10 +1,10 @@ function WilkinsonTicks(k_ideal::Int; k_min = 2, k_max = 10, - Q = [(1.0,1.0), (5.0, 0.9), (2.0, 0.7), (2.5, 0.5), (3.0, 0.2)], - granularity_weight = 1/4, - simplicity_weight = 1/6, - coverage_weight = 1/3, - niceness_weight = 1/4, - min_px_dist = 50.0) + Q = [(1.0, 1.0), (5.0, 0.9), (2.0, 0.7), (2.5, 0.5), (3.0, 0.2)], + granularity_weight = 1 / 4, + simplicity_weight = 1 / 6, + coverage_weight = 1 / 3, + niceness_weight = 1 / 4, + min_px_dist = 50.0) if !(0 < k_min <= k_ideal <= k_max) error("Invalid tick number specifications k_ideal $k_ideal, k_min $k_min, k_max $k_max") @@ -19,7 +19,7 @@ get_tickvalues(ticks::WilkinsonTicks, vmin, vmax) = get_tickvalues(ticks, Float6 function get_tickvalues(ticks::WilkinsonTicks, vmin::Float64, vmax::Float64) tickvalues, _ = PlotUtils.optimize_ticks(Float64(vmin), Float64(vmax); - extend_ticks = false, strict_span=true, span_buffer = nothing, + extend_ticks = false, strict_span = true, span_buffer = nothing, k_min = ticks.k_min, k_max = ticks.k_max, k_ideal = ticks.k_ideal, diff --git a/src/makielayout/types.jl b/src/makielayout/types.jl index bf52b111bb7..3a672985984 100644 --- a/src/makielayout/types.jl +++ b/src/makielayout/types.jl @@ -1,4 +1,4 @@ -const Optional{T} = Union{Nothing, T} +const Optional{T} = Union{Nothing,T} @@ -10,14 +10,14 @@ struct DataAspect end struct Cycler - counters::Dict{Type, Int} + counters::Dict{Type,Int} end -Cycler() = Cycler(Dict{Type, Int}()) +Cycler() = Cycler(Dict{Type,Int}()) struct Cycle - cycle::Vector{Pair{Vector{Symbol}, Symbol}} + cycle::Vector{Pair{Vector{Symbol},Symbol}} covary::Bool end @@ -27,8 +27,8 @@ to_cycle(single) = [to_cycle_single(single)] to_cycle(::Nothing) = [] to_cycle(symbolvec::Vector) = map(to_cycle_single, symbolvec) to_cycle_single(sym::Symbol) = [sym] => sym -to_cycle_single(pair::Pair{Symbol, Symbol}) = [pair[1]] => pair[2] -to_cycle_single(pair::Pair{Vector{Symbol}, Symbol}) = pair +to_cycle_single(pair::Pair{Symbol,Symbol}) = [pair[1]] => pair[2] +to_cycle_single(pair::Pair{Vector{Symbol},Symbol}) = pair """ Cycled(i::Int) @@ -59,7 +59,7 @@ struct WilkinsonTicks k_ideal::Int k_min::Int k_max::Int - Q::Vector{Tuple{Float64, Float64}} + Q::Vector{Tuple{Float64,Float64}} granularity_weight::Float64 simplicity_weight::Float64 coverage_weight::Float64 @@ -123,7 +123,7 @@ mutable struct LineAxis parent::Scene protrusion::Observable{Float32} attributes::Attributes - elements::Dict{Symbol, Any} + elements::Dict{Symbol,Any} tickpositions::Observable{Vector{Point2f}} tickvalues::Observable{Vector{Float32}} ticklabels::Observable{Vector{AbstractString}} @@ -138,37 +138,37 @@ mutable struct RectangleZoom active::Observable{Bool} restrict_x::Bool restrict_y::Bool - from::Union{Nothing, Point2f} - to::Union{Nothing, Point2f} + from::Union{Nothing,Point2f} + to::Union{Nothing,Point2f} rectnode::Observable{Rect2f} end -function RectangleZoom(callback::Function; restrict_x=false, restrict_y=false) +function RectangleZoom(callback::Function; restrict_x = false, restrict_y = false) return RectangleZoom(callback, Observable(false), restrict_x, restrict_y, - nothing, nothing, Observable(Rect2f(0, 0, 1, 1))) + nothing, nothing, Observable(Rect2f(0, 0, 1, 1))) end struct ScrollZoom speed::Float32 - reset_timer::RefValue{Union{Nothing, Timer}} - prev_xticklabelspace::RefValue{Union{Automatic, Float64}} - prev_yticklabelspace::RefValue{Union{Automatic, Float64}} + reset_timer::RefValue{Union{Nothing,Timer}} + prev_xticklabelspace::RefValue{Union{Automatic,Float64}} + prev_yticklabelspace::RefValue{Union{Automatic,Float64}} reset_delay::Float32 end function ScrollZoom(speed, reset_delay) - return ScrollZoom(speed, RefValue{Union{Nothing, Timer}}(nothing), RefValue{Union{Automatic, Float64}}(0.0), RefValue{Union{Automatic, Float64}}(0.0), reset_delay) + return ScrollZoom(speed, RefValue{Union{Nothing,Timer}}(nothing), RefValue{Union{Automatic,Float64}}(0.0), RefValue{Union{Automatic,Float64}}(0.0), reset_delay) end struct DragPan - reset_timer::RefValue{Union{Nothing, Timer}} - prev_xticklabelspace::RefValue{Union{Automatic, Float64}} - prev_yticklabelspace::RefValue{Union{Automatic, Float64}} + reset_timer::RefValue{Union{Nothing,Timer}} + prev_xticklabelspace::RefValue{Union{Automatic,Float64}} + prev_yticklabelspace::RefValue{Union{Automatic,Float64}} reset_delay::Float32 end function DragPan(reset_delay) - return DragPan(RefValue{Union{Nothing, Timer}}(nothing), RefValue{Union{Automatic, Float64}}(0.0), RefValue{Union{Automatic, Float64}}(0.0), reset_delay) + return DragPan(RefValue{Union{Nothing,Timer}}(nothing), RefValue{Union{Automatic,Float64}}(0.0), RefValue{Union{Automatic,Float64}}(0.0), reset_delay) end @@ -196,7 +196,7 @@ end mouseeventhandle::MouseEventHandle scrollevents::Observable{ScrollEvent} keysevents::Observable{KeysEvent} - interactions::Dict{Symbol, Tuple{Bool, Any}} + interactions::Dict{Symbol,Tuple{Bool,Any}} xaxis::LineAxis yaxis::LineAxis @attributes begin @@ -275,9 +275,9 @@ end "Controls if the yticklabels are visible." yticklabelsvisible::Bool = true "The space reserved for the xticklabels." - xticklabelspace::Union{Makie.Automatic, Float64} = Makie.automatic + xticklabelspace::Union{Makie.Automatic,Float64} = Makie.automatic "The space reserved for the yticklabels." - yticklabelspace::Union{Makie.Automatic, Float64} = Makie.automatic + yticklabelspace::Union{Makie.Automatic,Float64} = Makie.automatic "The space between xticks and xticklabels." xticklabelpad::Float64 = 2f0 "The space between yticks and yticklabels." @@ -287,9 +287,9 @@ end "The counterclockwise rotation of the yticklabels in radians." yticklabelrotation::Float64 = 0f0 "The horizontal and vertical alignment of the xticklabels." - xticklabelalign::Union{Makie.Automatic, Tuple{Symbol, Symbol}} = Makie.automatic + xticklabelalign::Union{Makie.Automatic,Tuple{Symbol,Symbol}} = Makie.automatic "The horizontal and vertical alignment of the yticklabels." - yticklabelalign::Union{Makie.Automatic, Tuple{Symbol, Symbol}} = Makie.automatic + yticklabelalign::Union{Makie.Automatic,Tuple{Symbol,Symbol}} = Makie.automatic "The size of the xtick marks." xticksize::Float64 = 6f0 "The size of the ytick marks." @@ -391,9 +391,9 @@ end "Controls if the parent layout can adjust to this element's height" tellheight::Bool = true "The relative margins added to the autolimits in x direction." - xautolimitmargin::Tuple{Float64, Float64} = (0.05f0, 0.05f0) + xautolimitmargin::Tuple{Float64,Float64} = (0.05f0, 0.05f0) "The relative margins added to the autolimits in y direction." - yautolimitmargin::Tuple{Float64, Float64} = (0.05f0, 0.05f0) + yautolimitmargin::Tuple{Float64,Float64} = (0.05f0, 0.05f0) "The xticks." xticks = Makie.automatic "Format for xticks." @@ -417,9 +417,9 @@ end "The position of the y axis (`:left` or `:right`)." yaxisposition::Symbol = :left "Controls if the x spine is limited to the furthest tick marks or not." - xtrimspine::Union{Bool, Tuple{Bool,Bool}} = false + xtrimspine::Union{Bool,Tuple{Bool,Bool}} = false "Controls if the y spine is limited to the furthest tick marks or not." - ytrimspine::Union{Bool, Tuple{Bool,Bool}} = false + ytrimspine::Union{Bool,Tuple{Bool,Bool}} = false "The background color of the axis." backgroundcolor::RGBAf = :white "Controls if the ylabel's rotation is flipped." @@ -473,7 +473,7 @@ function RectangleZoom(f::Function, ax::Axis; kw...) # plot to blockscene, so ax.scene stays exclusive for user plots # That's also why we need to pass `ax.scene` to _selection_vertices, so it can project to that space mesh = mesh!(ax.blockscene, selection_vertices, faces, color = (:black, 0.2), shading = false, - inspectable = false, visible=r.active, transparency=true) + inspectable = false, visible = r.active, transparency = true) # translate forward so selection mesh and frame are never behind data translate!(mesh, 0, 0, 100) return r @@ -738,8 +738,8 @@ end end @Block IntervalSlider begin - selected_indices::Observable{Tuple{Int, Int}} - displayed_sliderfractions::Observable{Tuple{Float64, Float64}} + selected_indices::Observable{Tuple{Int,Int}} + displayed_sliderfractions::Observable{Tuple{Float64,Float64}} @attributes begin "The horizontal alignment of the slider in its suggested bounding box." halign = :center @@ -932,7 +932,7 @@ struct LegendEntry attributes::Attributes end -const EntryGroup = Tuple{Optional{<:AbstractString}, Vector{LegendEntry}} +const EntryGroup = Tuple{Optional{<:AbstractString},Vector{LegendEntry}} @Block Legend begin entrygroups::Observable{Vector{EntryGroup}} @@ -1150,7 +1150,7 @@ end mouseeventhandle::MouseEventHandle scrollevents::Observable{ScrollEvent} keysevents::Observable{KeysEvent} - interactions::Dict{Symbol, Tuple{Bool, Any}} + interactions::Dict{Symbol,Tuple{Bool,Any}} cycler::Cycler palette::Attributes @attributes begin @@ -1169,13 +1169,13 @@ end "The alignment of the scene in its suggested bounding box." alignmode = Inside() "The elevation angle of the camera" - elevation = pi/8 + elevation = pi / 8 "The azimuth angle of the camera" azimuth = 1.275 * pi "A number between 0 and 1, where 0 is orthographic, and 1 full perspective" perspectiveness = 0f0 "Aspects of the 3 axes with each other" - aspect = (1.0, 1.0, 2/3) # :data :equal + aspect = (1.0, 1.0, 2 / 3) # :data :equal "The view mode which affects the final projection. `:fit` results in the projection that always fits the limits into the viewport, invariant to rotation. `:fitzoom` keeps the x/y ratio intact but stretches the view so the corners touch the scene viewport. `:stretch` scales separately in both x and y direction to fill the viewport, which can distort the `aspect` that is set." viewmode = :fitzoom # :fit :fitzoom :stretch "The background color" diff --git a/src/patterns.jl b/src/patterns.jl index 88f834a01d7..b765b44df89 100644 --- a/src/patterns.jl +++ b/src/patterns.jl @@ -6,7 +6,7 @@ plottable objects. There are currently two subtypes: `LinePattern` and `ImagePattern`. Any abstract pattern must implement the `to_image(pat)` function, which must return a `Matrix{<: AbstractRGB}`. """ -abstract type AbstractPattern{T} <: AbstractArray{T, 2} end +abstract type AbstractPattern{T} <: AbstractArray{T,2} end # for print_array because we defined it as <: Base.AbstractArray function Base.show(io::IO, p::AbstractPattern) @@ -32,10 +32,10 @@ Creates an `ImagePattern` from an `image` (a matrix of colors) or a `mask` texture it. If a `mask` is passed, one can specify to colors between which colors are interpolated. """ -Pattern(img::Array{<: Colorant, 2}) = ImagePattern(img) +Pattern(img::Array{<:Colorant,2}) = ImagePattern(img) -function Pattern(mask::Matrix{<: Real}; color1=RGBAf(0,0,0,1), color2=RGBAf(1,1,1,0)) - img = map(x -> to_color(color1) * x + to_color(color2) * (1-x), mask) +function Pattern(mask::Matrix{<:Real}; color1 = RGBAf(0, 0, 0, 1), color2 = RGBAf(1, 1, 1, 0)) + img = map(x -> to_color(color1) * x + to_color(color2) * (1 - x), mask) return ImagePattern(img) end @@ -46,8 +46,8 @@ struct LinePattern <: AbstractPattern{RGBAf} widths::Vector{Float32} shifts::Vector{Vec2f} - tilesize::NTuple{2, Int} - colors::NTuple{2, RGBAf} + tilesize::NTuple{2,Int} + colors::NTuple{2,RGBAf} end Base.size(pattern::LinePattern) = pattern.tilesize @@ -69,10 +69,10 @@ Multiple `direction`s, `width`s and `shift`s can also be given to create more complex patterns, e.g. a cross-hatching pattern. """ function LinePattern(; - direction = Vec2f(1), width = 2f0, tilesize = (10,10), - shift = map(w -> Vec2f(0.5 - 0.5(w%2)), width), - linecolor = RGBAf(0,0,0,1), background_color = RGBAf(1,1,1,0) - ) + direction = Vec2f(1), width = 2f0, tilesize = (10, 10), + shift = map(w -> Vec2f(0.5 - 0.5(w % 2)), width), + linecolor = RGBAf(0, 0, 0, 1), background_color = RGBAf(1, 1, 1, 0) +) N = 1 direction isa Vector{<:Vec2} && (N = length(direction)) width isa Vector && (length(width) > N) && (N = length(width)) @@ -97,17 +97,17 @@ to the keyword arguments for [`LinePattern`](@ref). Pattern(style::String; kwargs...) = Pattern(style[1]; kwargs...) function Pattern(style::Char = '/'; kwargs...) if style == '/' - LinePattern(direction=Vec2f(1); kwargs...) + LinePattern(direction = Vec2f(1); kwargs...) elseif style == '\\' - LinePattern(direction=Vec2f(1, -1); kwargs...) + LinePattern(direction = Vec2f(1, -1); kwargs...) elseif style == '-' - LinePattern(direction=Vec2f(1, 0); kwargs...) + LinePattern(direction = Vec2f(1, 0); kwargs...) elseif style == '|' - LinePattern(direction=Vec2f(0, 1); kwargs...) + LinePattern(direction = Vec2f(0, 1); kwargs...) elseif style == 'x' - LinePattern(direction=[Vec2f(1), Vec2f(1, -1)]; kwargs...) + LinePattern(direction = [Vec2f(1), Vec2f(1, -1)]; kwargs...) elseif style == '+' - LinePattern(direction=[Vec2f(1, 0), Vec2f(0, 1)]; kwargs...) + LinePattern(direction = [Vec2f(1, 0), Vec2f(0, 1)]; kwargs...) else LinePattern(; kwargs...) end @@ -123,31 +123,31 @@ function to_image(p::LinePattern) # m = dx / dy; x = m * (y-1) + 1 m = dir[1] / dir[2] for y in 1:tilesize[2] - cx = m * (y-shift[2]) + shift[1] - r = floor(Int64, cx-0.5width):ceil(Int64, cx+0.5width) - for x in r[2:end-1] + cx = m * (y - shift[2]) + shift[1] + r = floor(Int64, cx - 0.5width):ceil(Int64, cx + 0.5width) + for x in r[2:(end - 1)] mask[mod1(x, tilesize[1]), y] = 1.0 end - mask[mod1(r[1], tilesize[1]), y] = 1 - abs(cx-0.5width - r[1]) - mask[mod1(r[end], tilesize[1]), y] = 1 - abs(cx+0.5width - r[end]) + mask[mod1(r[1], tilesize[1]), y] = 1 - abs(cx - 0.5width - r[1]) + mask[mod1(r[end], tilesize[1]), y] = 1 - abs(cx + 0.5width - r[end]) end else # m = dy / dx; y = m * (x-1) + 1 m = dir[2] / dir[1] for x in 1:tilesize[1] - cy = m * (x-shift[1]) + shift[2] - r = floor(Int64, cy-0.5width):ceil(Int64, cy+0.5width) - for y in r[2:end-1] + cy = m * (x - shift[1]) + shift[2] + r = floor(Int64, cy - 0.5width):ceil(Int64, cy + 0.5width) + for y in r[2:(end - 1)] mask[x, mod1(y, tilesize[2])] = 1.0 end - mask[x, mod1(r[1], tilesize[2])] = 1 - abs(cy-0.5width - r[1]) - mask[x, mod1(r[end], tilesize[2])] = 1 - abs(cy+0.5width - r[end]) + mask[x, mod1(r[1], tilesize[2])] = 1 - abs(cy - 0.5width - r[1]) + mask[x, mod1(r[end], tilesize[2])] = 1 - abs(cy + 0.5width - r[end]) end end full_mask .+= mask end return map(full_mask) do x - return convert(RGBAf, p.colors[1] * clamp(x, 0, 1) + p.colors[2] * (1-clamp(x, 0, 1))) + return convert(RGBAf, p.colors[1] * clamp(x, 0, 1) + p.colors[2] * (1 - clamp(x, 0, 1))) end end diff --git a/src/recording.jl b/src/recording.jl index 449f04b9d98..8e139b4ae79 100644 --- a/src/recording.jl +++ b/src/recording.jl @@ -26,15 +26,15 @@ mutable struct RamStepper format::Symbol end -function Stepper(figlike::FigureLike; backend=current_backend(), format=:png, visible=false, connect=false, srceen_kw...) - screen = getscreen(backend, get_scene(figlike), JuliaNative; visible=visible, start_renderloop=false, srceen_kw...) - display(screen, figlike; connect=connect) +function Stepper(figlike::FigureLike; backend = current_backend(), format = :png, visible = false, connect = false, srceen_kw...) + screen = getscreen(backend, get_scene(figlike), JuliaNative; visible = visible, start_renderloop = false, srceen_kw...) + display(screen, figlike; connect = connect) return RamStepper(figlike, screen, Matrix{RGBf}[], format) end -function Stepper(figlike::FigureLike, path::String, step::Int; format=:png, backend=current_backend(), visible=false, connect=false, screen_config...) - screen = getscreen(backend, get_scene(figlike), JuliaNative; visible=visible, start_renderloop=false, srceen_kw...) - display(screen, figlike; connect=connect) +function Stepper(figlike::FigureLike, path::String, step::Int; format = :png, backend = current_backend(), visible = false, connect = false, screen_config...) + screen = getscreen(backend, get_scene(figlike), JuliaNative; visible = visible, start_renderloop = false, srceen_kw...) + display(screen, figlike; connect = connect) return FolderStepper(figlike, screen, path, format, step) end @@ -139,13 +139,13 @@ end """ function record(func, figlike::FigureLike, path::AbstractString; kw_args...) format = lstrip(splitext(path)[2], '.') - io = Record(func, figlike; format=format, kw_args...) + io = Record(func, figlike; format = format, kw_args...) save(path, io) end function record(func, figlike::FigureLike, path::AbstractString, iter; kw_args...) format = lstrip(splitext(path)[2], '.') - io = Record(func, figlike, iter; format=format, kw_args...) + io = Record(func, figlike, iter; format = format, kw_args...) save(path, io) end @@ -166,7 +166,7 @@ function Record(func, figlike, iter; kw_args...) for i in iter func(i) recordframe!(io) - @debug "Recording" progress=i/length(iter) + @debug "Recording" progress = i / length(iter) yield() end return io diff --git a/src/scenes.jl b/src/scenes.jl index 29633cf39d5..db793c91017 100644 --- a/src/scenes.jl +++ b/src/scenes.jl @@ -29,7 +29,7 @@ function Base.show(io::IO, ssao::SSAO) println(io, " blur: ", ssao.blur[]) end -function SSAO(; radius=nothing, bias=nothing, blur=nothing) +function SSAO(; radius = nothing, bias = nothing, blur = nothing) defaults = theme(nothing, :SSAO) _radius = isnothing(radius) ? defaults.radius[] : radius _bias = isnothing(bias) ? defaults.bias[] : bias @@ -75,7 +75,7 @@ $(FIELDS) """ mutable struct Scene <: AbstractScene "The parent of the Scene; if it is a top-level Scene, `parent == nothing`." - parent::Union{Nothing, Scene} + parent::Union{Nothing,Scene} "[`Events`](@ref) associated with the Scene." events::Events @@ -138,29 +138,29 @@ function Base.show(io::IO, scene::Scene) print(io, ":") for (i, subscene) in enumerate(scene.children) print(io, "\n") - print(io," $(i == length(scene.children) ? '└' : '├') Scene ($(size(subscene, 1))px, $(size(subscene, 2))px)") + print(io, " $(i == length(scene.children) ? '└' : '├') Scene ($(size(subscene, 1))px, $(size(subscene, 2))px)") end end end function Scene(; - px_area::Union{Observable{Rect2i}, Nothing} = nothing, - events::Events = Events(), - clear::Bool = true, - transform_func=identity, - camera::Union{Function, Camera, Nothing} = nothing, - camera_controls::AbstractCamera = EmptyCamera(), - transformation::Transformation = Transformation(transform_func), - plots::Vector{AbstractPlot} = AbstractPlot[], - theme::Attributes = Attributes(), - children::Vector{Scene} = Scene[], - current_screens::Vector{MakieScreen} = MakieScreen[], - parent = nothing, - visible = Observable(true), - ssao = SSAO(), - lights = automatic, - theme_kw... - ) + px_area::Union{Observable{Rect2i},Nothing} = nothing, + events::Events = Events(), + clear::Bool = true, + transform_func = identity, + camera::Union{Function,Camera,Nothing} = nothing, + camera_controls::AbstractCamera = EmptyCamera(), + transformation::Transformation = Transformation(transform_func), + plots::Vector{AbstractPlot} = AbstractPlot[], + theme::Attributes = Attributes(), + children::Vector{Scene} = Scene[], + current_screens::Vector{MakieScreen} = MakieScreen[], + parent = nothing, + visible = Observable(true), + ssao = SSAO(), + lights = automatic, + theme_kw... +) m_theme = current_default_theme(; theme..., theme_kw...) bg = map(to_color, m_theme.backgroundcolor) @@ -213,7 +213,7 @@ function Scene(; end function get_one_light(scene::Scene, Typ) - indices = findall(x-> x isa Typ, scene.lights) + indices = findall(x -> x isa Typ, scene.lights) isempty(indices) && return nothing if length(indices) > 1 @warn("Only one light supported by backend right now. Using only first light") @@ -226,21 +226,21 @@ get_ambient_light(scene::Scene) = get_one_light(scene, AmbientLight) function Scene( - parent::Scene; - events=parent.events, - px_area=nothing, - clear=false, - camera=nothing, - camera_controls=parent.camera_controls, - transformation=Transformation(parent), - theme=theme(parent), - current_screens=parent.current_screens, - kw... - ) + parent::Scene; + events = parent.events, + px_area = nothing, + clear = false, + camera = nothing, + camera_controls = parent.camera_controls, + transformation = Transformation(parent), + theme = theme(parent), + current_screens = parent.current_screens, + kw... +) if isnothing(px_area) - px_area = lift(zero_origin, parent.px_area; ignore_equal_values=true) + px_area = lift(zero_origin, parent.px_area; ignore_equal_values = true) else - px_area = lift(pixelarea(parent), convert(Observable, px_area); ignore_equal_values=true) do p, a + px_area = lift(pixelarea(parent), convert(Observable, px_area); ignore_equal_values = true) do p, a # make coordinates relative to parent rect = Rect2i(minimum(p) .+ minimum(a), widths(a)) return rect @@ -250,15 +250,15 @@ function Scene( camera_controls = EmptyCamera() end child = Scene(; - events=events, - px_area=px_area, - clear=clear, - camera=camera, - camera_controls=camera_controls, - parent=parent, - transformation=transformation, - theme=theme, - current_screens=current_screens, + events = events, + px_area = px_area, + clear = clear, + camera = camera, + camera_controls = camera_controls, + parent = parent, + transformation = transformation, + theme = theme, + current_screens = current_screens, kw... ) push!(parent.children, child) @@ -268,7 +268,7 @@ end # legacy constructor function Scene(parent::Scene, area; kw...) - return Scene(parent; px_area=area, kw...) + return Scene(parent; px_area = area, kw...) end # Base overloads for Scene @@ -315,7 +315,7 @@ end getscreen(scene::SceneLike) = getscreen(rootparent(scene)) # Just indexing into a scene gets you plot 1, plot 2 etc -Base.iterate(scene::Scene, idx=1) = idx <= length(scene) ? (scene[idx], idx + 1) : nothing +Base.iterate(scene::Scene, idx = 1) = idx <= length(scene) ? (scene[idx], idx + 1) : nothing Base.length(scene::Scene) = length(scene.plots) Base.lastindex(scene::Scene) = length(scene.plots) getindex(scene::Scene, idx::Integer) = scene.plots[idx] @@ -324,22 +324,22 @@ struct OldAxis end zero_origin(area) = Recti(0, 0, widths(area)) function child(scene::Scene; camera, attributes...) - return Scene(scene, lift(zero_origin, pixelarea(scene)); camera=camera, attributes...) + return Scene(scene, lift(zero_origin, pixelarea(scene)); camera = camera, attributes...) end """ Creates a subscene with a pixel camera """ function cam2d(scene::Scene) - return child(scene, clear=false, camera=cam2d!) + return child(scene, clear = false, camera = cam2d!) end function campixel(scene::Scene) - return child(scene, clear=false, camera=campixel!) + return child(scene, clear = false, camera = campixel!) end function camrelative(scene::Scene) - return child(scene, clear=false, camera=cam_relative!) + return child(scene, clear = false, camera = cam_relative!) end function getindex(scene::Scene, ::Type{OldAxis}) @@ -474,7 +474,7 @@ plots(scene::SceneLike) = scene.plots Fetches all plots sharing the same camera """ plots_from_camera(scene::Scene) = plots_from_camera(scene, scene.camera) -function plots_from_camera(scene::Scene, camera::Camera, list=AbstractPlot[]) +function plots_from_camera(scene::Scene, camera::Camera, list = AbstractPlot[]) append!(list, scene.plots) for child in scene.children child.camera == camera && plots_from_camera(child, camera, list) @@ -485,7 +485,7 @@ end """ Flattens all the combined plots and returns a Vector of Atomic plots """ -function flatten_combined(plots::Vector, flat=AbstractPlot[]) +function flatten_combined(plots::Vector, flat = AbstractPlot[]) for elem in plots if (elem isa Combined) flatten_combined(elem.plots, flat) @@ -510,7 +510,7 @@ function not_in_data_space(p) !is_data_space(to_value(get(p, :space, :data))) end -function center!(scene::Scene, padding=0.01, exclude = not_in_data_space) +function center!(scene::Scene, padding = 0.01, exclude = not_in_data_space) bb = boundingbox(scene, exclude) bb = transformationmatrix(scene)[] * bb w = widths(bb) @@ -558,4 +558,4 @@ struct FigureAxisPlot plot::AbstractPlot end -const FigureLike = Union{Scene, Figure, FigureAxisPlot} +const FigureLike = Union{Scene,Figure,FigureAxisPlot} diff --git a/src/shorthands.jl b/src/shorthands.jl index 31fded1dfe9..4a36e00a6ed 100644 --- a/src/shorthands.jl +++ b/src/shorthands.jl @@ -82,7 +82,7 @@ yticklabels(scene) = ticklabels(scene)[2] Returns the all the z-axis tick labels. See also `ticklabels`. """ function zticklabels(scene) - @assert !is2d(scene) "The Scene does not have a z-axis!" + @assert !is2d(scene) "The Scene does not have a z-axis!" ticklabels(scene)[3] end @@ -117,7 +117,7 @@ ytickrange(scene) = tickranges(scene)[2] Returns the tick range along the z-axis. See also `tickranges`. """ function ztickrange(scene) - @assert !is2d(scene) "The Scene does not have a z-axis!" + @assert !is2d(scene) "The Scene does not have a z-axis!" return tickranges(scene)[3] end @@ -127,7 +127,7 @@ end Set the tick labels and ranges along all axes. The respective labels and ranges along each axis must be of the same length. """ -function ticks!(scene::Scene; tickranges=tickranges(scene), ticklabels=ticklabels(scene)) +function ticks!(scene::Scene; tickranges = tickranges(scene), ticklabels = ticklabels(scene)) axis = scene[OldAxis] @assert !isnothing(axis) "The Scene does not have an axis!" # Have to set `ranges_labels` first so that any changes in the length of these @@ -143,8 +143,8 @@ end Set the tick labels and range along the x-axes. See also `ticks!`. """ -function xticks!(scene::Scene; xtickrange=xtickrange(scene), xticklabels=xticklabels(scene)) - ticks!(scene, tickranges=(xtickrange, tickranges(scene)[2:end]...), ticklabels=(xticklabels, ticklabels(scene)[2:end]...)) +function xticks!(scene::Scene; xtickrange = xtickrange(scene), xticklabels = xticklabels(scene)) + ticks!(scene, tickranges = (xtickrange, tickranges(scene)[2:end]...), ticklabels = (xticklabels, ticklabels(scene)[2:end]...)) return nothing end @@ -153,13 +153,13 @@ end Set the tick labels and range along all the y-axis. See also `ticks!`. """ -function yticks!(scene::Scene; ytickrange=ytickrange(scene), yticklabels=yticklabels(scene)) +function yticks!(scene::Scene; ytickrange = ytickrange(scene), yticklabels = yticklabels(scene)) r = tickranges(scene) l = ticklabels(scene) if length(r) == 2 - ticks!(scene, tickranges=(first(r), ytickrange), ticklabels=(first(l), yticklabels)) + ticks!(scene, tickranges = (first(r), ytickrange), ticklabels = (first(l), yticklabels)) else # length(r) == 3 - ticks!(scene, tickranges=(first(r), ytickrange, last(r)), ticklabels =(first(l), yticklabels, last(l))) + ticks!(scene, tickranges = (first(r), ytickrange, last(r)), ticklabels = (first(l), yticklabels, last(l))) end return nothing end @@ -169,9 +169,9 @@ end Set the tick labels and range along all z-axis. See also `ticks!`. """ -function zticks!(scene::Scene; ztickrange=ztickrange(scene), zticklabels=zticklabels(scene)) - @assert !is2d(scene) "The Scene does not have a z-axis!" - ticks!(scene, tickranges=(tickranges(scene)[1:2]..., ztickrange), ticklabels=(ticklabels(scene)[1:2]..., zticklabels)) +function zticks!(scene::Scene; ztickrange = ztickrange(scene), zticklabels = zticklabels(scene)) + @assert !is2d(scene) "The Scene does not have a z-axis!" + ticks!(scene, tickranges = (tickranges(scene)[1:2]..., ztickrange), ticklabels = (ticklabels(scene)[1:2]..., zticklabels)) return nothing end @@ -209,7 +209,7 @@ ytickrotation(scene) = tickrotations(scene)[2] Returns the rotation of tick labels along the z-axis. See also `tickrotations` """ function ztickrotation(scene) - @assert !is2d(scene) "The Scene does not have a z-axis!" + @assert !is2d(scene) "The Scene does not have a z-axis!" return tickrotations(scene)[3] end @@ -254,7 +254,7 @@ end Set the rotation of tick labels along the z-axis. See also `tickrotations!`. """ function ztickrotation!(scene::Scene, zangle) - @assert !is2d(scene) "The Scene does not have a z-axis!" + @assert !is2d(scene) "The Scene does not have a z-axis!" tickrotations!(scene, (tickrotations(scene)[1:2]..., zangle)) return nothing end diff --git a/src/stats/boxplot.jl b/src/stats/boxplot.jl index 7ec7fb4f5ae..330dd5cf0bf 100644 --- a/src/stats/boxplot.jl +++ b/src/stats/boxplot.jl @@ -122,7 +122,7 @@ function Makie.plot!(plot::BoxPlot) if Float64(range) != 0.0 # if the range is 0.0, the whiskers will extend to the data limit = range * (q4 - q2) inside = Float64[] - for (value, idx) in zip(values,idxs) + for (value, idx) in zip(values, idxs) if (value < (q2 - limit)) || (value > (q4 + limit)) if show_outliers push!(outlier_points, (center, value)) diff --git a/src/stats/crossbar.jl b/src/stats/crossbar.jl index 683b341ecba..cd8147b09f5 100644 --- a/src/stats/crossbar.jl +++ b/src/stats/crossbar.jl @@ -23,30 +23,30 @@ It is most commonly used as part of the `boxplot`. """ @recipe(CrossBar, x, y, ymin, ymax) do scene t = Theme( - color=theme(scene, :patchcolor), - colormap=theme(scene, :colormap), - colorrange=automatic, - orientation=:vertical, - # box and dodging - width = automatic, - dodge = automatic, - n_dodge = automatic, - gap = 0.2, - dodge_gap = 0.03, - strokecolor = theme(scene, :patchstrokecolor), - strokewidth = theme(scene, :patchstrokewidth), - # notch - show_notch=false, - notchmin=automatic, - notchmax=automatic, - notchwidth=0.5, - # median line - show_midline=true, - midlinecolor=automatic, - midlinewidth=theme(scene, :linewidth), - inspectable = theme(scene, :inspectable), - cycle = [:color => :patchcolor], -) + color = theme(scene, :patchcolor), + colormap = theme(scene, :colormap), + colorrange = automatic, + orientation = :vertical, + # box and dodging + width = automatic, + dodge = automatic, + n_dodge = automatic, + gap = 0.2, + dodge_gap = 0.03, + strokecolor = theme(scene, :patchstrokecolor), + strokewidth = theme(scene, :patchstrokewidth), + # notch + show_notch = false, + notchmin = automatic, + notchmax = automatic, + notchwidth = 0.5, + # median line + show_midline = true, + midlinecolor = automatic, + midlinewidth = theme(scene, :linewidth), + inspectable = theme(scene, :inspectable), + cycle = [:color => :patchcolor], + ) t end @@ -90,8 +90,8 @@ function Makie.plot!(plot::CrossBar) fpoint.(m .- nw .* hw, y), # notch left fpoint.(l, nmin), fpoint.(l, ymin) - ))) - boxes = if points isa AbstractVector{<: Point} # poly + ))) + boxes = if points isa AbstractVector{<:Point} # poly [GeometryBasics.triangle_mesh(points)] else # multiple polys (Vector{Vector{<:Point}}) GeometryBasics.triangle_mesh.(points) @@ -108,22 +108,22 @@ function Makie.plot!(plot::CrossBar) poly!( plot, boxes, - color=plot.color, - colorrange=plot.colorrange, - colormap=plot.colormap, - strokecolor=plot.strokecolor, - strokewidth=plot.strokewidth, + color = plot.color, + colorrange = plot.colorrange, + colormap = plot.colormap, + strokecolor = plot.strokecolor, + strokewidth = plot.strokewidth, inspectable = plot[:inspectable] ) linesegments!( plot, - color=lift( + color = lift( (mc, sc) -> mc === automatic ? sc : mc, plot.midlinecolor, plot.strokecolor, ), - linewidth=plot[:midlinewidth], - visible=plot[:show_midline], + linewidth = plot[:midlinewidth], + visible = plot[:show_midline], inspectable = plot[:inspectable], midlines, ) diff --git a/src/stats/density.jl b/src/stats/density.jl index 4d19df179fa..93d1b7a670e 100644 --- a/src/stats/density.jl +++ b/src/stats/density.jl @@ -6,7 +6,7 @@ end function convert_arguments(::Type{<:Poly}, d::KernelDensity.UnivariateKDE) points = Vector{Point2f}(undef, length(d.x) + 2) points[1] = Point2f(d.x[1], 0) - points[2:end-1] .= Point2f.(d.x, d.density) + points[2:(end - 1)] .= Point2f.(d.x, d.density) points[end] = Point2f(d.x[end], 0) (points,) end diff --git a/src/stats/distributions.jl b/src/stats/distributions.jl index da7b65cc154..c6c9c4e18fd 100644 --- a/src/stats/distributions.jl +++ b/src/stats/distributions.jl @@ -4,10 +4,10 @@ The StatMakie.jl package is licensed under the MIT "Expat" License: Copyright (c) 2018: Pietro Vertechi. =# # pick a nice default x range given a distribution -function default_range(dist::Distribution, alpha=0.0001) +function default_range(dist::Distribution, alpha = 0.0001) minval = isfinite(minimum(dist)) ? minimum(dist) : quantile(dist, alpha) maxval = isfinite(maximum(dist)) ? maximum(dist) : quantile(dist, 1 - alpha) - minval..maxval + minval .. maxval end isdiscrete(::Distribution) = false @@ -86,7 +86,7 @@ end function fit_qqplot(x, y; qqline = :none) if !(qqline in (:identity, :fit, :fitrobust, :none)) msg = "valid values for qqline are :identity, :fit, :fitrobust or :none, " * - "encountered " * repr(qqline) + "encountered " * repr(qqline) throw(ArgumentError(msg)) end h = qqbuild(x, y) diff --git a/src/stats/ecdf.jl b/src/stats/ecdf.jl index 6494ca58df9..23dbd741ed6 100644 --- a/src/stats/ecdf.jl +++ b/src/stats/ecdf.jl @@ -2,15 +2,15 @@ function ecdf_xvalues(ecdf::StatsBase.ECDF, npoints) x = ecdf.sorted_values n = length(x) npoints ≥ n && return float(unique(x)) - return @inbounds range(x[1], x[n]; length=npoints) + return @inbounds range(x[1], x[n]; length = npoints) end used_attributes(::PlotFunc, ::StatsBase.ECDF) = (:npoints,) -function convert_arguments(P::PlotFunc, ecdf::StatsBase.ECDF; npoints=10_000) +function convert_arguments(P::PlotFunc, ecdf::StatsBase.ECDF; npoints = 10_000) ptype = plottype(P, Stairs) x0 = ecdf_xvalues(ecdf, npoints) if ptype <: Stairs - kwargs = (; step=:post) + kwargs = (; step = :post) x1 = x0[1] x = [x1 - eps(x1); x0] else @@ -21,7 +21,7 @@ function convert_arguments(P::PlotFunc, ecdf::StatsBase.ECDF; npoints=10_000) end function convert_arguments(P::PlotFunc, x::AbstractVector, ecdf::StatsBase.ECDF) ptype = plottype(P, Stairs) - kwargs = ptype <: Stairs ? (; step=:post) : NamedTuple() + kwargs = ptype <: Stairs ? (; step = :post) : NamedTuple() return to_plotspec(ptype, convert_arguments(ptype, x, ecdf(x)); kwargs...) end function convert_arguments(P::PlotFunc, x0::AbstractInterval, ecdf::StatsBase.ECDF) @@ -29,7 +29,7 @@ function convert_arguments(P::PlotFunc, x0::AbstractInterval, ecdf::StatsBase.EC z = ecdf_xvalues(ecdf, Inf) n = length(z) imin, imax = findfirst(>(xmin), z), findlast(<(xmax), z) - idx_min = imin === nothing ? n+1 : imin + idx_min = imin === nothing ? n + 1 : imin idx_max = imax === nothing ? -1 : imax x = [xmin - eps(oftype(z[1], xmin)); xmin; view(z, idx_min:idx_max); xmax] return convert_arguments(P, x, ecdf) @@ -54,9 +54,9 @@ used_attributes(::Type{<:ECDFPlot}, ::AbstractVector) = (:npoints, :weights) function convert_arguments( ::Type{<:ECDFPlot}, x::AbstractVector; - npoints=10_000, - weights=StatsBase.Weights(Float64[]), + npoints = 10_000, + weights = StatsBase.Weights(Float64[]) ) - ecdf = StatsBase.ecdf(x; weights=weights) - return convert_arguments(Stairs, ecdf; npoints=npoints) + ecdf = StatsBase.ecdf(x; weights = weights) + return convert_arguments(Stairs, ecdf; npoints = npoints) end diff --git a/src/stats/hexbin.jl b/src/stats/hexbin.jl index 21527975726..28a4d69ea0c 100644 --- a/src/stats/hexbin.jl +++ b/src/stats/hexbin.jl @@ -19,14 +19,14 @@ Plots a heatmap with hexagonal bins for the observations `xs` and `ys`. """ @recipe(Hexbin) do scene return Attributes(; - colormap=theme(scene, :colormap), - colorrange=Makie.automatic, - bins=20, - cellsize=nothing, - threshold=1, - scale=identity, - strokewidth=0, - strokecolor=:black) + colormap = theme(scene, :colormap), + colorrange = Makie.automatic, + bins = 20, + cellsize = nothing, + threshold = 1, + scale = identity, + strokewidth = 0, + strokecolor = :black) end function spacings_offsets_nbins(bins::Tuple{Int,Int}, cellsize::Nothing, xmi, xma, ymi, yma) @@ -52,7 +52,7 @@ function spacings_offsets_nbins(bins, cellsizes::Tuple{<:Real,<:Real}, xmi, xma, yspacing = cellsizes[2] * 3 / 4 (nx, restx), (ny, resty) = fldmod.((x_diff, y_diff), (xspacing, yspacing)) return xspacing, yspacing, xmi - (restx > 0 ? (xspacing - restx) / 2 : 0), - ymi - (resty > 0 ? (yspacing - resty) / 2 : 0), Int(nx) + (restx > 0), Int(ny) + (resty > 0) + ymi - (resty > 0 ? (yspacing - resty) / 2 : 0), Int(nx) + (restx > 0), Int(ny) + (resty > 0) end Makie.conversion_trait(::Type{<:Hexbin}) = PointBased() @@ -94,7 +94,7 @@ function Makie.plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) y_diff = yma - ymi xspacing, yspacing, xoff, yoff, nbinsx, nbinsy = spacings_offsets_nbins(bins, cellsize, xmi, xma, ymi, - yma) + yma) ysize = yspacing / 3 * 4 ry = ysize / 2 @@ -119,16 +119,16 @@ function Makie.plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) is_grid1 = d1 < d2 # _xy = is_grid1 ? (nx, ny) : (nxs, nys) - + id = if is_grid1 ( cld(dvx, 2), - iseven(dvy) ? dvy : dvy+1 + iseven(dvy) ? dvy : dvy + 1 ) else ( fld(dvx, 2), - iseven(dvy) ? dvy+1 : dvy, + iseven(dvy) ? dvy + 1 : dvy, ) end @@ -136,9 +136,9 @@ function Makie.plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) end if threshold == 0 - for iy in 0:nbinsy-1 + for iy in 0:(nbinsy - 1) _nx = isodd(iy) ? fld(nbinsx, 2) : cld(nbinsx, 2) - for ix in 0:_nx-1 + for ix in 0:(_nx - 1) _x = xoff + 2 * ix * xspacing + (isodd(iy) * xspacing) _y = yoff + iy * yspacing c = get(d, (ix, iy), 0) @@ -174,17 +174,17 @@ function Makie.plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) end end - hexmarker = Polygon(Point2f[(cos(a), sin(a)) for a in range(pi / 6, 13pi / 6; length=7)[1:6]]) + hexmarker = Polygon(Point2f[(cos(a), sin(a)) for a in range(pi / 6, 13pi / 6; length = 7)[1:6]]) return scatter!(hb, points; - colorrange=hb.colorrange, - color=count_hex, - colormap=hb.colormap, - marker=hexmarker, - markersize=markersize, - markerspace=:data, - strokewidth=hb.strokewidth, - strokecolor=hb.strokecolor) + colorrange = hb.colorrange, + color = count_hex, + colormap = hb.colormap, + marker = hexmarker, + markersize = markersize, + markerspace = :data, + strokewidth = hb.strokewidth, + strokecolor = hb.strokecolor) end function center_value(dv, spacing, offset, is_grid1) @@ -200,4 +200,4 @@ function nearest_center(val, spacing, offset) rounded = offset + spacing * (dv + isodd(dv)) rounded_scaled = offset + spacing * (dv + iseven(dv)) return rounded, rounded_scaled, dv -end \ No newline at end of file +end diff --git a/src/stats/hist.jl b/src/stats/hist.jl index 3ab8d0f281a..0fc0ad1dcf9 100644 --- a/src/stats/hist.jl +++ b/src/stats/hist.jl @@ -1,8 +1,8 @@ const histogram_plot_types = [BarPlot, Heatmap, Volume] -function convert_arguments(P::Type{<:AbstractPlot}, h::StatsBase.Histogram{<:Any, N}) where N +function convert_arguments(P::Type{<:AbstractPlot}, h::StatsBase.Histogram{<:Any,N}) where N ptype = plottype(P, histogram_plot_types[N]) - f(edges) = edges[1:end-1] .+ diff(edges)./2 + f(edges) = edges[1:(end - 1)] .+ diff(edges) ./ 2 kwargs = N == 1 ? (; width = step(h.edges[1]), gap = 0, dodge_gap = 0) : NamedTuple() to_plotspec(ptype, convert_arguments(ptype, map(f, h.edges)..., Float64.(h.weights)); kwargs...) end @@ -52,9 +52,7 @@ $(ATTRIBUTES) color = theme(scene, :patchcolor), offset = 0.0, fillto = automatic, - scale_to = nothing, - - bar_labels = nothing, + scale_to = nothing, bar_labels = nothing, flip_labels_at = Inf, label_color = theme(scene, :textcolor), over_background_color = automatic, @@ -74,7 +72,7 @@ function pick_hist_edges(vals, bins) end # hist is right-open, so to include the upper data point, make the last bin a tiny bit bigger ma = nextfloat(ma) - return range(mi, ma, length = bins+1) + return range(mi, ma, length = bins + 1) else if !issorted(bins) error("Histogram bins are not sorted: $bins") @@ -86,13 +84,13 @@ end function Makie.plot!(plot::Hist) values = plot.values - edges = lift(pick_hist_edges, values, plot.bins) + edges = lift(pick_hist_edges, values, plot.bins) points = lift(edges, plot.normalization, plot.scale_to, plot.weights) do edges, normalization, scale_to, wgts w = wgts === automatic ? () : (StatsBase.weights(wgts),) h = StatsBase.fit(StatsBase.Histogram, values[], w..., edges) h_norm = StatsBase.normalize(h, mode = normalization) - centers = edges[1:end-1] .+ (diff(edges) ./ 2) + centers = edges[1:(end - 1)] .+ (diff(edges) ./ 2) weights = h_norm.weights if !isnothing(scale_to) max = maximum(weights) @@ -113,7 +111,7 @@ function Makie.plot!(plot::Hist) x === :values ? :y : x end # plot the values, not the observables, to be in control of updating - bp = barplot!(plot, points[]; width = widths[], gap = 0, plot.attributes..., fillto=plot.fillto, offset=plot.offset, bar_labels=bar_labels, color=color) + bp = barplot!(plot, points[]; width = widths[], gap = 0, plot.attributes..., fillto = plot.fillto, offset = plot.offset, bar_labels = bar_labels, color = color) # update the barplot points without triggering, then trigger with `width` on(widths) do w diff --git a/src/stats/violin.jl b/src/stats/violin.jl index 0361ef246c6..ef8d8d8589c 100644 --- a/src/stats/violin.jl +++ b/src/stats/violin.jl @@ -31,7 +31,7 @@ Draw a violin plot. max_density = automatic, show_median = false, mediancolor = theme(scene, :linecolor), - medianlinewidth = theme(scene, :linewidth), + medianlinewidth = theme(scene, :linewidth) ) end @@ -62,7 +62,7 @@ function plot!(plot::Violin) # Allow `side` to be either scalar or vector sides = broadcast(x̂, vside) do _, s - return s == :left ? - 1 : s == :right ? 1 : 0 + return s == :left ? -1 : s == :right ? 1 : 0 end sa = StructArray((x = x̂, side = sides)) @@ -92,11 +92,11 @@ function plot!(plot::Violin) end vertices = Vector{Point2f}[] - lines = Pair{Point2f, Point2f}[] + lines = Pair{Point2f,Point2f}[] colors = RGBA{Float32}[] for spec in specs - scale = 0.5*violinwidth/max + scale = 0.5 * violinwidth / max xl = reverse(spec.x .- spec.kde.density .* scale) xr = spec.x .+ spec.kde.density .* scale yl = reverse(spec.kde.x) @@ -116,8 +116,8 @@ function plot!(plot::Violin) # interpolate median bounds between corresponding points xm = spec.median ip = findfirst(>(xm), spec.kde.x) - ym₋, ym₊ = spec.kde.density[ip-1], spec.kde.density[ip] - xm₋, xm₊ = spec.kde.x[ip-1], spec.kde.x[ip] + ym₋, ym₊ = spec.kde.density[ip - 1], spec.kde.density[ip] + xm₋, xm₊ = spec.kde.x[ip - 1], spec.kde.x[ip] ym = (xm * (ym₊ - ym₋) + xm₊ * ym₋ - xm₋ * ym₊) / (xm₊ - xm₋) median_left = point_func(spec.side == 1 ? spec.x : spec.x - ym * scale, xm) median_right = point_func(spec.side == -1 ? spec.x : spec.x + ym * scale, xm) diff --git a/src/theming.jl b/src/theming.jl index 7193ef849de..6918bbbefd1 100644 --- a/src/theming.jl +++ b/src/theming.jl @@ -10,9 +10,9 @@ if Sys.iswindows() elseif Sys.isapple() const _CoreGraphics = "CoreGraphics.framework/CoreGraphics" function primary_resolution() - dispid = ccall((:CGMainDisplayID, _CoreGraphics), UInt32,()) - height = ccall((:CGDisplayPixelsHigh,_CoreGraphics), Int, (UInt32,), dispid) - width = ccall((:CGDisplayPixelsWide,_CoreGraphics), Int, (UInt32,), dispid) + dispid = ccall((:CGMainDisplayID, _CoreGraphics), UInt32, ()) + height = ccall((:CGDisplayPixelsHigh, _CoreGraphics), Int, (UInt32,), dispid) + width = ccall((:CGDisplayPixelsWide, _CoreGraphics), Int, (UInt32,), dispid) return (width, height) end else @@ -34,13 +34,13 @@ https://www.nature.com/articles/nmeth.1618?WT.ec_id=NMETH-201106 function wong_colors(alpha = 1.0) colors = [ - RGB(0/255, 114/255, 178/255), # blue - RGB(230/255, 159/255, 0/255), # orange - RGB(0/255, 158/255, 115/255), # green - RGB(204/255, 121/255, 167/255), # reddish purple - RGB(86/255, 180/255, 233/255), # sky blue - RGB(213/255, 94/255, 0/255), # vermillion - RGB(240/255, 228/255, 66/255), # yellow + RGB(0 / 255, 114 / 255, 178 / 255), # blue + RGB(230 / 255, 159 / 255, 0 / 255), # orange + RGB(0 / 255, 158 / 255, 115 / 255), # green + RGB(204 / 255, 121 / 255, 167 / 255), # reddish purple + RGB(86 / 255, 180 / 255, 233 / 255), # sky blue + RGB(213 / 255, 94 / 255, 0 / 255), # vermillion + RGB(240 / 255, 228 / 255, 66 / 255), # yellow ] @. RGBAf(red(colors), green(colors), blue(colors), alpha) end @@ -98,17 +98,13 @@ const minimal_default = Attributes( ), ambient = RGBf(0.55, 0.55, 0.55), lightposition = :eyeposition, - inspectable = true, - - CairoMakie = Attributes( + inspectable = true, CairoMakie = Attributes( px_per_unit = 1.0, pt_per_unit = 0.75, antialias = :best, visible = true, start_renderloop = false - ), - - GLMakie = Attributes( + ), GLMakie = Attributes( # Renderloop renderloop = automatic, pause_renderloop = false, @@ -133,13 +129,9 @@ const minimal_default = Attributes( # transparency. This should be the same for all of them (within one rendering # pipeline) otherwise depth "order" will be broken. transparency_weight_scale = 1000f0 - ), - - WGLMakie = Attributes( + ), WGLMakie = Attributes( framerate = 30.0 - ), - - RPRMakie = Attributes( + ), RPRMakie = Attributes( iterations = 200, resource = automatic, plugin = automatic, diff --git a/src/types.jl b/src/types.jl index c28e74df6a8..82f3f12c527 100644 --- a/src/types.jl +++ b/src/types.jl @@ -67,11 +67,11 @@ struct Events The position of the mouse as a `NTuple{2, Float64}`. Updates once per event poll/frame. """ - mouseposition::Observable{NTuple{2, Float64}} # why no Vec2? + mouseposition::Observable{NTuple{2,Float64}} # why no Vec2? """ The direction of scroll """ - scroll::Observable{NTuple{2, Float64}} # why no Vec2? + scroll::Observable{NTuple{2,Float64}} # why no Vec2? """ Most recently triggered `KeyEvent`. Contains the relevant `event.key` and @@ -117,14 +117,10 @@ function Events() events = Events( Observable(Recti(0, 0, 0, 0)), Observable(100.0), - Observable(false), - - Observable(MouseButtonEvent(Mouse.none, Mouse.release)), + Observable(false), Observable(MouseButtonEvent(Mouse.none, Mouse.release)), Set{Mouse.Button}(), Observable((0.0, 0.0)), - Observable((0.0, 0.0)), - - Observable(KeyEvent(Keyboard.unknown, Keyboard.release)), + Observable((0.0, 0.0)), Observable(KeyEvent(Keyboard.unknown, Keyboard.release)), Set{Keyboard.Button}(), Observable('\0'), Observable(String[]), @@ -280,14 +276,14 @@ Base.getindex(p::PlotSpec, i::Symbol) = getproperty(p.kwargs, i) to_plotspec(::Type{P}, args; kwargs...) where {P} = PlotSpec{P}(args...; kwargs...) -to_plotspec(::Type{P}, p::PlotSpec{S}; kwargs...) where {P, S} = +to_plotspec(::Type{P}, p::PlotSpec{S}; kwargs...) where {P,S} = PlotSpec{plottype(P, S)}(p.args...; p.kwargs..., kwargs...) plottype(::PlotSpec{P}) where {P} = P struct ScalarOrVector{T} - sv::Union{T, Vector{T}} + sv::Union{T,Vector{T}} end Base.convert(::Type{<:ScalarOrVector}, v::AbstractVector{T}) where T = ScalarOrVector{T}(collect(v)) @@ -356,7 +352,7 @@ struct GlyphCollection strokewidths::ScalarOrVector{Float32} function GlyphCollection(glyphs, fonts, origins, extents, scales, rotations, - colors, strokecolors, strokewidths) + colors, strokecolors, strokewidths) n = length(glyphs) @assert length(fonts) == n @@ -377,4 +373,4 @@ end # The color type we ideally use for most color attributes -const RGBColors = Union{RGBAf, Vector{RGBAf}, Vector{Float32}} +const RGBColors = Union{RGBAf,Vector{RGBAf},Vector{Float32}} diff --git a/src/units.jl b/src/units.jl index d93d71f8331..623fb015bd1 100644 --- a/src/units.jl +++ b/src/units.jl @@ -43,17 +43,17 @@ physical unit of measurement based on a coordinate system held by a computer and represents an abstraction of a pixel for use by an application that an underlying system then converts to physical pixels. """ -struct DeviceIndependentPixel{T <: Number} <: Unit{T} +struct DeviceIndependentPixel{T<:Number} <: Unit{T} value::T end -basetype(::Type{<: DeviceIndependentPixel}) = DeviceIndependentPixel +basetype(::Type{<:DeviceIndependentPixel}) = DeviceIndependentPixel const DIP = DeviceIndependentPixel const dip = DIP(1) const dip_in_millimeter = 0.15875 -const dip_in_inch = 1/160 +const dip_in_inch = 1 / 160 -basetype(::Type{<: Pixel}) = Pixel +basetype(::Type{<:Pixel}) = Pixel """ Millimeter on screen. This unit respects the dimension and pixel density of the screen @@ -64,7 +64,7 @@ a camera can change the actually displayed dimensions of any object using the mi struct Millimeter{T} <: Unit{T} value::T end -basetype(::Type{<: Millimeter}) = Millimeter +basetype(::Type{<:Millimeter}) = Millimeter const mm = Millimeter(1) Base.show(io::IO, x::DIP) = print(io, number(x), "dip") @@ -76,51 +76,51 @@ function pixel_per_mm(scene) dpi(scene) ./ 25.4 end -function Base.convert(::Type{<: Millimeter}, scene::Scene, x::SceneSpace) +function Base.convert(::Type{<:Millimeter}, scene::Scene, x::SceneSpace) pixel = convert(Pixel, scene, x) Millimeter(number(pixel_per_mm(scene) / pixel)) end -function Base.convert(::Type{<: SceneSpace}, scene::Scene, x::DIP) +function Base.convert(::Type{<:SceneSpace}, scene::Scene, x::DIP) mm = convert(Millimeter, scene, x) SceneSpace(number(mm * dip_in_millimeter)) end -function Base.convert(::Type{<: Millimeter}, scene::Scene, x::DIP) +function Base.convert(::Type{<:Millimeter}, scene::Scene, x::DIP) Millimeter(number(x * dip_in_millimeter)) end -function Base.convert(::Type{<: Pixel}, scene::Scene, x::Millimeter) +function Base.convert(::Type{<:Pixel}, scene::Scene, x::Millimeter) px = pixel_per_mm(scene) * x Pixel(number(px)) end -function Base.convert(::Type{<: Pixel}, scene::Scene, x::DIP) +function Base.convert(::Type{<:Pixel}, scene::Scene, x::DIP) inch = (x * dip_in_inch) dots = dpi(scene) * inch Pixel(number(dots)) end -function Base.convert(::Type{<: SceneSpace}, scene::Scene, x::Vec{2, <:Pixel}) +function Base.convert(::Type{<:SceneSpace}, scene::Scene, x::Vec{2,<:Pixel}) zero = to_world(scene, to_screen(scene, Point2f(0))) s = to_world(scene, to_screen(scene, number.(Point(x)))) SceneSpace.(Vec(s .- zero)) end -function Base.convert(::Type{<: SceneSpace}, scene::Scene, x::Pixel) +function Base.convert(::Type{<:SceneSpace}, scene::Scene, x::Pixel) zero = to_world(scene, to_screen(scene, Point2f(0))) s = to_world(scene, to_screen(scene, Point2f(number(x), 0.0))) SceneSpace(norm(s .- zero)) end -function Base.convert(::Type{<: SceneSpace}, scene::Scene, x::Millimeter) +function Base.convert(::Type{<:SceneSpace}, scene::Scene, x::Millimeter) pix = convert(Pixel, scene, x) (SceneSpace, mm) end to_2d_scale(x::Pixel) = Vec2f(number(x)) -to_2d_scale(x::Tuple{<:Pixel, <:Pixel}) = Vec2f(number.(x)) -to_2d_scale(x::VecTypes{2, <:Pixel}) = Vec2f(number.(x)) +to_2d_scale(x::Tuple{<:Pixel,<:Pixel}) = Vec2f(number.(x)) +to_2d_scale(x::VecTypes{2,<:Pixel}) = Vec2f(number.(x)) # Exports of units export px diff --git a/src/utilities/quaternions.jl b/src/utilities/quaternions.jl index bcae57f50de..5735761eb98 100644 --- a/src/utilities/quaternions.jl +++ b/src/utilities/quaternions.jl @@ -5,18 +5,18 @@ # TODO replace this file by just `using Quaternions` struct Quaternion{T} - data::NTuple{4, T} - Quaternion{T}(x::NTuple{4, Any}) where T = new{T}(T.(x)) - Quaternion{T}(x::NTuple{4, T}) where T = new{T}(x) + data::NTuple{4,T} + Quaternion{T}(x::NTuple{4,Any}) where T = new{T}(T.(x)) + Quaternion{T}(x::NTuple{4,T}) where T = new{T}(x) end Base.eltype(::Quaternion{T}) where T = T Base.eltype(::Type{Quaternion{T}}) where T = T -Base.length(::Type{<: Quaternion}) = 4 +Base.length(::Type{<:Quaternion}) = 4 Base.length(::Quaternion) = 4 const Quaternionf = Quaternion{Float32} -const SMat{N, L} = Mat{N, N, T, L} where T +const SMat{N,L} = Mat{N,N,T,L} where T function Base.show(io::IO, q::Quaternion) pm(x) = x < 0 ? " - $(-x)" : " + $x" @@ -27,12 +27,12 @@ Random.rand(mt::AbstractRNG, ::Random.SamplerType{Quaternion}) = rand(mt, Quater Random.rand(mt::AbstractRNG, ::Random.SamplerType{Quaternion{T}}) where T = Quaternion(rand(mt, T), rand(mt, T), rand(mt, T), 1.0) Quaternion{T}(x1, x2, x3, s) where T = Quaternion{T}((x1, x2, x3, s)) -Base.convert(T::Type{<: Quaternion}, x::NTuple{4, Any}) = T(x) -function Base.convert(T::Type{Quaternion{T1}}, x::Quaternion{T2}) where {T1, T2} +Base.convert(T::Type{<:Quaternion}, x::NTuple{4,Any}) = T(x) +function Base.convert(T::Type{Quaternion{T1}}, x::Quaternion{T2}) where {T1,T2} T(T2.(x.data)) end Quaternion(x1, x2, x3, s) = Quaternion(promote(x1, x2, x3, s)) -Quaternion(x::NTuple{4, T}) where T = Quaternion{T}(x) +Quaternion(x::NTuple{4,T}) where T = Quaternion{T}(x) Base.getindex(x::Quaternion, i::Integer) = x.data[i] Base.isapprox(x::Quaternion, y::Quaternion) = all((x.data .≈ y.data)) @@ -52,13 +52,13 @@ LinearAlgebra.normalize(q::Quaternion) = q / abs(q) Base.:(/)(q::Quaternion, x::Real) = Quaternion(q[1] / x, q[2] / x, q[3] / x, q[4] / x) -function Base.:(*)(quat::Quaternion, vec::P) where {P <: StaticVector{2}} +function Base.:(*)(quat::Quaternion, vec::P) where {P<:StaticVector{2}} T = eltype(vec) x3 = quat * Vec(vec[1], vec[2], T(0)) return P(x3[1], x3[2]) end -function Base.:(*)(quat::Quaternion{T}, vec::P) where {T, P <: StaticVector{3}} +function Base.:(*)(quat::Quaternion{T}, vec::P) where {T,P<:StaticVector{3}} num = quat[1] * T(2) num2 = quat[2] * T(2) num3 = quat[3] * T(2) @@ -92,45 +92,45 @@ function Base.:(*)(q::Quaternion, w::Quaternion) ) end -SMat{N, L}(q::Quaternion{T}) where {N, T, L} = Mat{N, N, T, L}(q) +SMat{N,L}(q::Quaternion{T}) where {N,T,L} = Mat{N,N,T,L}(q) -function Mat4{ET}(q::Quaternion{T}) where {T, ET} - sx, sy, sz = 2q[4]*q[1], 2q[4]*q[2], 2q[4]*q[3] - xx, xy, xz = 2q[1]^2, 2q[1]*q[2], 2q[1]*q[3] - yy, yz, zz = 2q[2]^2, 2q[2]*q[3], 2q[3]^2 +function Mat4{ET}(q::Quaternion{T}) where {T,ET} + sx, sy, sz = 2q[4] * q[1], 2q[4] * q[2], 2q[4] * q[3] + xx, xy, xz = 2q[1]^2, 2q[1] * q[2], 2q[1] * q[3] + yy, yz, zz = 2q[2]^2, 2q[2] * q[3], 2q[3]^2 T0, T1 = zero(ET), one(ET) - return Mat{4, 4, ET}( - T1-(yy+zz), xy+sz, xz-sy, T0, - xy-sz, T1-(xx+zz), yz+sx, T0, - xz+sy, yz-sx, T1-(xx+yy), T0, - T0, T0, T0, T1 + return Mat{4,4,ET}( + T1 - (yy + zz), xy + sz, xz - sy, T0, + xy - sz, T1 - (xx + zz), yz + sx, T0, + xz + sy, yz - sx, T1 - (xx + yy), T0, + T0, T0, T0, T1 ) end concrete_type(::Type{Any}, ::Type{T}) where T = T concrete_type(::Type{T}, x) where T = T -function Mat3{ET}(q::Quaternion{T}) where {T, ET} - sx, sy, sz = 2q[4]*q[1], 2q[4]*q[2], 2q[4]*q[3] - xx, xy, xz = 2q[1]^2, 2q[1]*q[2], 2q[1]*q[3] - yy, yz, zz = 2q[2]^2, 2q[2]*q[3], 2q[3]^2 +function Mat3{ET}(q::Quaternion{T}) where {T,ET} + sx, sy, sz = 2q[4] * q[1], 2q[4] * q[2], 2q[4] * q[3] + xx, xy, xz = 2q[1]^2, 2q[1] * q[2], 2q[1] * q[3] + yy, yz, zz = 2q[2]^2, 2q[2] * q[3], 2q[3]^2 T0, T1 = zero(ET), one(ET) - return Mat{3, 3, ET}( - T1-(yy+zz), xy+sz, xz-sy, - xy-sz, T1-(xx+zz), yz+sx, - xz+sy, yz-sx, T1-(xx+yy) + return Mat{3,3,ET}( + T1 - (yy + zz), xy + sz, xz - sy, + xy - sz, T1 - (xx + zz), yz + sx, + xz + sy, yz - sx, T1 - (xx + yy) ) end -function orthogonal(v::T) where T <: StaticVector{3} +function orthogonal(v::T) where T<:StaticVector{3} x, y, z = abs.(v) other = x < y ? (x < z ? unit(T, 1) : unit(T, 3)) : (y < z ? unit(T, 2) : unit(T, 3)) return cross(v, other) end -function rotation_between(u::StaticVector{3, T}, v::StaticVector{3, T}) where T +function rotation_between(u::StaticVector{3,T}, v::StaticVector{3,T}) where T k_cos_theta = dot(u, v) - k = sqrt((norm(u) ^ 2) * (norm(v) ^ 2)) + k = sqrt((norm(u)^2) * (norm(v)^2)) if (k_cos_theta / k) ≈ T(-1) # 180 degree rotation around any orthogonal vector return Quaternion(normalize(orthogonal(u))..., T(0)) diff --git a/src/utilities/texture_atlas.jl b/src/utilities/texture_atlas.jl index 3730ab5c65f..658aa9c2ec0 100644 --- a/src/utilities/texture_atlas.jl +++ b/src/utilities/texture_atlas.jl @@ -2,7 +2,7 @@ struct TextureAtlas rectangle_packer::RectanglePacker{Int32} # hash of what we're rendering to index in `uv_rectangles` - mapping::Dict{UInt32, Int64} + mapping::Dict{UInt32,Int64} data::Matrix{Float16} # rectangles we rendered our glyphs into in normalized uv coordinates uv_rectangles::Vector{Vec4f} @@ -46,10 +46,10 @@ function get_uv_img(atlas::TextureAtlas, uv_rect::Vec4f) return atlas.data[Rect(xmin, ymin, xmax - xmin, ymax - ymin)] end -function TextureAtlas(; resolution=2048, pix_per_glyph=64, glyph_padding=12, downsample=5) +function TextureAtlas(; resolution = 2048, pix_per_glyph = 64, glyph_padding = 12, downsample = 5) return TextureAtlas( RectanglePacker(Rect2{Int32}(0, 0, resolution, resolution)), - Dict{UInt32, Int}(), + Dict{UInt32,Int}(), # We use the maximum distance of a glyph as a background to reduce texture bleed. See #2096 fill(Float16(0.5pix_per_glyph + glyph_padding), resolution, resolution), Vec4f[], @@ -140,7 +140,7 @@ end function load_texture_atlas(path::AbstractString) open(path) do io packer = read_node(io, Int32) - mapping = read_array(io, Pair{UInt32, Int64}) + mapping = read_array(io, Pair{UInt32,Int64}) data = read_array(io, Float16) uv_rectangles = read_array(io, Vec4f) pix_per_glyph = read(io, Int32) @@ -150,7 +150,7 @@ function load_texture_atlas(path::AbstractString) end end -const TEXTURE_ATLASES = Dict{Tuple{Int, Int}, TextureAtlas}() +const TEXTURE_ATLASES = Dict{Tuple{Int,Int},TextureAtlas}() function get_texture_atlas(resolution::Int = 2048, pix_per_glyph::Int = 64) return get!(TEXTURE_ATLASES, (resolution, pix_per_glyph)) do @@ -167,18 +167,18 @@ function cached_load(resolution::Int, pix_per_glyph::Int) url = CACHE_DOWNLOAD_URL * basename(path) Downloads.download(url, path) catch e - @warn "downloading texture atlas failed, need to re-create from scratch." exception=(e, Base.catch_backtrace()) + @warn "downloading texture atlas failed, need to re-create from scratch." exception = (e, Base.catch_backtrace()) end end if isfile(path) try return load_texture_atlas(path) catch e - @warn "reading texture atlas on disk failed, need to re-create from scratch." exception=(e, Base.catch_backtrace()) - rm(path; force=true) + @warn "reading texture atlas on disk failed, need to re-create from scratch." exception = (e, Base.catch_backtrace()) + rm(path; force = true) end end - atlas = TextureAtlas(; resolution=resolution, pix_per_glyph=pix_per_glyph) + atlas = TextureAtlas(; resolution = resolution, pix_per_glyph = pix_per_glyph) @warn("Makie is caching fonts, this may take a while. This should usually not happen, unless you're getting your own texture atlas or are without internet!") render_default_glyphs!(atlas) store_texture_atlas(path, atlas) # cache it @@ -229,8 +229,8 @@ end function regenerate_texture_atlas(resolution, pix_per_glyph) path = get_cache_path(resolution, pix_per_glyph) - isfile(path) && rm(path; force=true) - atlas = TextureAtlas(; resolution=resolution, pix_per_glyph=pix_per_glyph) + isfile(path) && rm(path; force = true) + atlas = TextureAtlas(; resolution = resolution, pix_per_glyph = pix_per_glyph) render_default_glyphs!(atlas) store_texture_atlas(path, atlas) # cache it atlas @@ -296,7 +296,7 @@ function insert_glyph!(atlas::TextureAtlas, path::BezierPath) end -function insert_glyph!(atlas::TextureAtlas, hash::UInt32, path_or_glyp::Union{BezierPath, Tuple{UInt64, NativeFont}}) +function insert_glyph!(atlas::TextureAtlas, hash::UInt32, path_or_glyp::Union{BezierPath,Tuple{UInt64,NativeFont}}) return get!(atlas.mapping, hash) do uv_pixel = render(atlas, path_or_glyp) tex_size = Vec2f(size(atlas)) @@ -336,7 +336,7 @@ function sdistancefield(img, downsample, pad) in_or_out = fill(false, dividable_size) # the size we fill the image up to wend, hend = size(img) .+ pad - in_or_out[pad+1:wend, pad+1:hend] .= img .> (0.5 * 255) + in_or_out[(pad + 1):wend, (pad + 1):hend] .= img .> (0.5 * 255) yres, xres = dividable_size .÷ downsample # divide by downsample to normalize distances! @@ -348,10 +348,10 @@ function font_render_callback!(f, atlas::TextureAtlas) end function remove_font_render_callback!(atlas::TextureAtlas, f) - filter!(f2-> f2 != f, atlas.font_render_callback) + filter!(f2 -> f2 != f, atlas.font_render_callback) end -function render(atlas::TextureAtlas, (glyph_index, font)::Tuple{UInt64, NativeFont}) +function render(atlas::TextureAtlas, (glyph_index, font)::Tuple{UInt64,NativeFont}) downsample = atlas.downsample pad = atlas.glyph_padding # the target pixel size of our distance field @@ -416,9 +416,9 @@ returns the Shape type for the distancefield shader marker_to_sdf_shape(x) = error("$(x) is not a valid scatter marker shape.") marker_to_sdf_shape(::AbstractMatrix) = RECTANGLE # Image marker -marker_to_sdf_shape(::Union{BezierPath, Char}) = DISTANCEFIELD -marker_to_sdf_shape(::Type{T}) where {T <: Circle} = CIRCLE -marker_to_sdf_shape(::Type{T}) where {T <: Rect} = RECTANGLE +marker_to_sdf_shape(::Union{BezierPath,Char}) = DISTANCEFIELD +marker_to_sdf_shape(::Type{T}) where {T<:Circle} = CIRCLE +marker_to_sdf_shape(::Type{T}) where {T<:Rect} = RECTANGLE marker_to_sdf_shape(x::Shape) = x function marker_to_sdf_shape(arr::AbstractVector) @@ -432,7 +432,7 @@ function marker_to_sdf_shape(arr::AbstractVector) end function marker_to_sdf_shape(marker::Observable) - return lift(marker; ignore_equal_values=true) do marker + return lift(marker; ignore_equal_values = true) do marker return Cint(marker_to_sdf_shape(to_spritemarker(marker))) end end @@ -446,12 +446,12 @@ primitive_offset(x, scale) = scale ./ -2f0 # default offset """ Extracts the uv offset and width from a primitive. """ -primitive_uv_offset_width(atlas::TextureAtlas, x, font) = Vec4f(0,0,1,1) +primitive_uv_offset_width(atlas::TextureAtlas, x, font) = Vec4f(0, 0, 1, 1) primitive_uv_offset_width(atlas::TextureAtlas, b::BezierPath, font) = glyph_uv_width!(atlas, b) -primitive_uv_offset_width(atlas::TextureAtlas, b::Union{UInt64, Char}, font) = glyph_uv_width!(atlas, b, font) -primitive_uv_offset_width(atlas::TextureAtlas, x::AbstractVector, font) = map(m-> primitive_uv_offset_width(atlas, m, font), x) +primitive_uv_offset_width(atlas::TextureAtlas, b::Union{UInt64,Char}, font) = glyph_uv_width!(atlas, b, font) +primitive_uv_offset_width(atlas::TextureAtlas, x::AbstractVector, font) = map(m -> primitive_uv_offset_width(atlas, m, font), x) function primitive_uv_offset_width(atlas::TextureAtlas, marker::Observable, font::Observable) - return lift((m, f)-> primitive_uv_offset_width(atlas, m, f), marker, font; ignore_equal_values=true) + return lift((m, f) -> primitive_uv_offset_width(atlas, m, f), marker, font; ignore_equal_values = true) end _bcast(x::Vec) = (x,) @@ -473,7 +473,7 @@ function bezierpath_pad_scale_factor(atlas::TextureAtlas, bp) uv_width = Vec(lbrt[3] - lbrt[1], lbrt[4] - lbrt[2]) full_pixel_size_in_atlas = uv_width * Vec2f(size(atlas)) # left + right pad - cutoff from pixel centering - full_pad = 2f0 * atlas.glyph_padding - 1 + full_pad = 2f0 * atlas.glyph_padding - 1 return full_pad ./ (full_pixel_size_in_atlas .- full_pad) end @@ -487,7 +487,7 @@ function rescale_marker(atlas::TextureAtlas, pathmarker::BezierPath, font, marke return markersize .* marker_scale_factor(atlas, pathmarker) end -function rescale_marker(atlas::TextureAtlas, pathmarker::AbstractVector{T}, font, markersize) where T <: BezierPath +function rescale_marker(atlas::TextureAtlas, pathmarker::AbstractVector{T}, font, markersize) where T<:BezierPath return _bcast(markersize) .* marker_scale_factor.(Ref(atlas), pathmarker) end @@ -513,11 +513,11 @@ function offset_bezierpath(atlas::TextureAtlas, bp, scale, offset) return offset_bezierpath.(Ref(atlas), bp, _bcast(scale), _bcast(offset)) end -function offset_marker(atlas::TextureAtlas, marker::Union{T, AbstractVector{T}}, font, markersize, markeroffset) where T <: BezierPath +function offset_marker(atlas::TextureAtlas, marker::Union{T,AbstractVector{T}}, font, markersize, markeroffset) where T<:BezierPath return offset_bezierpath(atlas, marker, markersize, markeroffset) end -function offset_marker(atlas::TextureAtlas, marker::Union{T, AbstractVector{T}}, font, markersize, markeroffset) where T <: Char +function offset_marker(atlas::TextureAtlas, marker::Union{T,AbstractVector{T}}, font, markersize, markeroffset) where T<:Char return rescale_marker(atlas, marker, font, markeroffset) end @@ -525,8 +525,8 @@ offset_marker(atlas, marker, font, markersize, markeroffset) = markeroffset function marker_attributes(atlas::TextureAtlas, marker, markersize, font, marker_offset) atlas_obs = Observable(atlas) # for map to work - scale = map(rescale_marker, atlas_obs, marker, font, markersize; ignore_equal_values=true) - quad_offset = map(offset_marker, atlas_obs, marker, font, markersize, marker_offset; ignore_equal_values=true) + scale = map(rescale_marker, atlas_obs, marker, font, markersize; ignore_equal_values = true) + quad_offset = map(offset_marker, atlas_obs, marker, font, markersize, marker_offset; ignore_equal_values = true) return scale, quad_offset end diff --git a/src/utilities/utilities.jl b/src/utilities/utilities.jl index d2a92459a3a..1132979856f 100644 --- a/src/utilities/utilities.jl +++ b/src/utilities/utilities.jl @@ -1,6 +1,6 @@ -function to_image(image::AbstractMatrix{<: AbstractFloat}, colormap::AbstractVector{<: Colorant}, colorrange) +function to_image(image::AbstractMatrix{<:AbstractFloat}, colormap::AbstractVector{<:Colorant}, colorrange) return interpolated_getindex.((to_value(colormap),), image, (to_value(colorrange),)) end @@ -10,7 +10,7 @@ Resample a vector with linear interpolation to have length `len` """ function resample(A::AbstractVector, len::Integer) length(A) == len && return A - return interpolated_getindex.((A,), range(0.0, stop=1.0, length=len)) + return interpolated_getindex.((A,), range(0.0, stop = 1.0, length = len)) end @@ -21,17 +21,17 @@ end * ncolors: number of desired colors * alpha: additional alpha applied to each color. Can also be an array, matching `colors`, or a tuple giving a start + stop alpha value. """ -function resample_cmap(cmap, ncolors::Integer; alpha=1.0) +function resample_cmap(cmap, ncolors::Integer; alpha = 1.0) cols = to_colormap(cmap) - r = range(0.0, stop=1.0, length=ncolors) - if alpha isa Tuple{<:Number, <:Number} + r = range(0.0, stop = 1.0, length = ncolors) + if alpha isa Tuple{<:Number,<:Number} alphas = LinRange(alpha..., ncolors) else alphas = alpha end return broadcast(r, alphas) do i, a c = interpolated_getindex(cols, i) - return RGBAf(Colors.color(c), Colors.alpha(c) * a) + return RGBAf(Colors.color(c), Colors.alpha(c) * a) end end @@ -78,8 +78,8 @@ function is_unitrange(x::AbstractVector) end function ngrid(x::AbstractVector, y::AbstractVector) - xgrid = [Float32(x[i]) for i = 1:length(x), j = 1:length(y)] - ygrid = [Float32(y[j]) for i = 1:length(x), j = 1:length(y)] + xgrid = [Float32(x[i]) for i in 1:length(x), j in 1:length(y)] + ygrid = [Float32(y[j]) for i in 1:length(x), j in 1:length(y)] xgrid, ygrid end @@ -227,7 +227,7 @@ function same_length_array(arr, value::Vector) end same_length_array(arr, value, key) = same_length_array(arr, convert_attribute(value, key)) -function to_ndim(T::Type{<: VecTypes{N,ET}}, vec::VecTypes{N2}, fillval) where {N,ET,N2} +function to_ndim(T::Type{<:VecTypes{N,ET}}, vec::VecTypes{N2}, fillval) where {N,ET,N2} T(ntuple(Val(N)) do i i > N2 && return ET(fillval) @inbounds return vec[i] @@ -260,7 +260,7 @@ function to_vector(x::AbstractArray, len, T) end function to_vector(x::ClosedInterval, len, T) a, b = T.(extrema(x)) - range(a, stop=b, length=len) + range(a, stop = b, length = len) end """ @@ -270,7 +270,7 @@ x = ColorSampler(colormap, (0.0, 1.0)) x[0.5] # returns color at half point of colormap ``` """ -struct ColorSampler{Data <: AbstractArray} +struct ColorSampler{Data<:AbstractArray} colormap::Data color_range::Tuple{Float64,Float64} end @@ -287,10 +287,10 @@ end Return a nonlinear function on a grid. Useful for test cases. """ -function peaks(n=49) +function peaks(n = 49) x = LinRange(-3, 3, n) y = LinRange(-3, 3, n) - 3 * (1 .- x').^2 .* exp.(-(x'.^2) .- (y .+ 1).^2) .- 10 * (x' / 5 .- x'.^3 .- y.^5) .* exp.(-x'.^2 .- y.^2) .- 1 / 3 * exp.(-(x' .+ 1).^2 .- y.^2) + 3 * (1 .- x') .^ 2 .* exp.(-(x' .^ 2) .- (y .+ 1) .^ 2) .- 10 * (x' / 5 .- x' .^ 3 .- y .^ 5) .* exp.(-x' .^ 2 .- y .^ 2) .- 1 / 3 * exp.(-(x' .+ 1) .^ 2 .- y .^ 2) end @@ -316,7 +316,7 @@ function surface_normals(x, y, z) s = size(z) return Vec3f(get_dim(x, off, 1, s), get_dim(y, off, 2, s), z[off]) end - return normalize(mapreduce(offsets, +, init=Vec3f(0), of)) + return normalize(mapreduce(offsets, +, init = Vec3f(0), of)) end return vec(map(normal, CartesianIndices(z))) end diff --git a/test/boundingboxes.jl b/test/boundingboxes.jl index 266548725d8..ac3bfd2e1d6 100644 --- a/test/boundingboxes.jl +++ b/test/boundingboxes.jl @@ -8,7 +8,7 @@ @test bb.origin ≈ Point3f(-0.1678, -0.002068, -0.358661) @test bb.widths ≈ Vec3f(0.339423, 0.92186, 1.3318559) - fig, ax, p = surface([x*y for x in 1:10, y in 1:10]) + fig, ax, p = surface([x * y for x in 1:10, y in 1:10]) bb = boundingbox(p) @test bb.origin ≈ Point3f(0.0, 0.0, 1.0) @test bb.widths ≈ Vec3f(10.0, 10.0, 99.0) @@ -42,7 +42,7 @@ bb = boundingbox(p) @test bb.origin ≈ Point3f(0.5, 0.5, 0) @test bb.widths ≈ Vec3f(10.0, 10.0, 0) - + fig, ax, p = image(rand(10, 10)) bb = boundingbox(p) @test bb.origin ≈ Point3f(0) @@ -55,4 +55,4 @@ bb = boundingbox(p) @test bb.origin ≈ Point3f(340, 341, 0) @test bb.widths ≈ Vec3f(32.24, 23.3, 0) -end \ No newline at end of file +end diff --git a/test/conversions.jl b/test/conversions.jl index 8c01def1a27..77feab96868 100644 --- a/test/conversions.jl +++ b/test/conversions.jl @@ -13,6 +13,7 @@ using Makie: let nctt = NoConversionTestType(), ncttt = conversion_trait(nctt) + @test convert_arguments(ncttt, 1, 2, 3) == (1, 2, 3) end @@ -27,58 +28,58 @@ end end @testset "to_vertices" begin - X1 = [Point(rand(3)...) for i = 1:10] + X1 = [Point(rand(3)...) for i in 1:10] V1 = to_vertices(X1) @test Float32(X1[7][1]) == V1[7][1] - X2 = [tuple(rand(3)...) for i = 1:10] + X2 = [tuple(rand(3)...) for i in 1:10] V2 = to_vertices(X2) @test Float32(X2[7][1]) == V2[7][1] - X4 = rand(2,10) + X4 = rand(2, 10) V4 = to_vertices(X4) - @test Float32(X4[1,7]) == V4[7][1] + @test Float32(X4[1, 7]) == V4[7][1] @test V4[7][3] == 0 - X5 = rand(3,10) + X5 = rand(3, 10) V5 = to_vertices(X5) - @test Float32(X5[1,7]) == V5[7][1] + @test Float32(X5[1, 7]) == V5[7][1] - X6 = rand(10,2) + X6 = rand(10, 2) V6 = to_vertices(X6) - @test Float32(X6[7,1]) == V6[7][1] + @test Float32(X6[7, 1]) == V6[7][1] @test V6[7][3] == 0 - X7 = rand(10,3) + X7 = rand(10, 3) V7 = to_vertices(X7) - @test Float32(X7[7,1]) == V7[7][1] + @test Float32(X7[7, 1]) == V7[7][1] end @testset "functions" begin - x = -pi..pi + x = -pi .. pi s = convert_arguments(Lines, x, sin) xy = s.args[1] @test xy[1][1] ≈ -pi @test xy[end][1] ≈ pi for (val, fval) in xy - @test fval ≈ sin(val) atol=1f-6 + @test fval ≈ sin(val) atol = 1f-6 end - x = range(-pi, stop=pi, length=100) + x = range(-pi, stop = pi, length = 100) s = convert_arguments(Lines, x, sin) xy = s.args[1] @test xy[1][1] ≈ -pi @test xy[end][1] ≈ pi for (val, fval) in xy - @test fval ≈ sin(val) atol=1f-6 + @test fval ≈ sin(val) atol = 1f-6 end - pts = [Point(1, 2), Point(4,5), Point(10, 8), Point(1, 2)] - ls=LineString(pts) + pts = [Point(1, 2), Point(4, 5), Point(10, 8), Point(1, 2)] + ls = LineString(pts) p = convert_arguments(Makie.PointBased(), ls) @test p[1] == pts - pts1 = [Point(5, 2), Point(4,8), Point(2, 8), Point(5, 2)] + pts1 = [Point(5, 2), Point(4, 8), Point(2, 8), Point(5, 2)] ls1 = LineString(pts1) lsa = [ls, ls1] p1 = convert_arguments(Makie.PointBased(), lsa) @@ -92,16 +93,16 @@ end pol_e = Polygon(ls) p3_e = convert_arguments(Makie.PointBased(), pol_e) - @test p3_e[1][1:end-1] == pts # for poly we repeat last point + @test p3_e[1][1:(end - 1)] == pts # for poly we repeat last point pol = Polygon(ls, [ls1]) p3 = convert_arguments(Makie.PointBased(), pol) @test p3[1][1:4] == pts @test p3[1][7:10] == pts1 - pts2 = Point{2, Int}[(5, 1), (3, 3), (4, 8), (1, 2), (5, 1)] - pts3 = Point{2, Int}[(2, 2), (2, 3),(3, 4), (2, 2)] - pts4 = Point{2, Int}[(2, 2), (3, 8),(5, 6), (3, 4), (2, 2)] + pts2 = Point{2,Int}[(5, 1), (3, 3), (4, 8), (1, 2), (5, 1)] + pts3 = Point{2,Int}[(2, 2), (2, 3), (3, 4), (2, 2)] + pts4 = Point{2,Int}[(2, 2), (3, 8), (5, 6), (3, 4), (2, 2)] ls2 = LineString(pts2) ls3 = LineString(pts3) ls4 = LineString(pts4) @@ -126,23 +127,23 @@ using Makie: check_line_pattern, line_diff_pattern # for readability, the length of dash and dot dash, dot = 3.0, 1.0 - @test line_diff_pattern(:dash) == - line_diff_pattern("-", :normal) == [dash, 3.0] - @test line_diff_pattern(:dot) == - line_diff_pattern(".", :normal) == [dot, 2.0] - @test line_diff_pattern(:dashdot) == - line_diff_pattern("-.", :normal) == [dash, 3.0, dot, 3.0] - @test line_diff_pattern(:dashdotdot) == - line_diff_pattern("-..", :normal) == [dash, 3.0, dot, 2.0, dot, 3.0] - - @test line_diff_pattern(:dash, :loose) == [dash, 6.0] - @test line_diff_pattern(:dot, :loose) == [dot, 4.0] - @test line_diff_pattern("-", :dense) == [dash, 2.0] - @test line_diff_pattern(".", :dense) == [dot, 1.0] - @test line_diff_pattern(:dash, 0.5) == [dash, 0.5] - @test line_diff_pattern(:dot, 0.5) == [dot, 0.5] - @test line_diff_pattern("-", (0.4, 0.6)) == [dash, 0.6] - @test line_diff_pattern(:dot, (0.4, 0.6)) == [dot, 0.4] + @test line_diff_pattern(:dash) == + line_diff_pattern("-", :normal) == [dash, 3.0] + @test line_diff_pattern(:dot) == + line_diff_pattern(".", :normal) == [dot, 2.0] + @test line_diff_pattern(:dashdot) == + line_diff_pattern("-.", :normal) == [dash, 3.0, dot, 3.0] + @test line_diff_pattern(:dashdotdot) == + line_diff_pattern("-..", :normal) == [dash, 3.0, dot, 2.0, dot, 3.0] + + @test line_diff_pattern(:dash, :loose) == [dash, 6.0] + @test line_diff_pattern(:dot, :loose) == [dot, 4.0] + @test line_diff_pattern("-", :dense) == [dash, 2.0] + @test line_diff_pattern(".", :dense) == [dot, 1.0] + @test line_diff_pattern(:dash, 0.5) == [dash, 0.5] + @test line_diff_pattern(:dot, 0.5) == [dot, 0.5] + @test line_diff_pattern("-", (0.4, 0.6)) == [dash, 0.6] + @test line_diff_pattern(:dot, (0.4, 0.6)) == [dot, 0.4] @test line_diff_pattern("-..", (0.4, 0.6)) == [dash, 0.6, dot, 0.4, dot, 0.6] # gaps must be Symbol, a number, or two numbers @@ -195,15 +196,15 @@ end end @testset "resample colormap" begin - cs = Makie.resample_cmap(:viridis, 10; alpha=LinRange(0, 1, 10)) + cs = Makie.resample_cmap(:viridis, 10; alpha = LinRange(0, 1, 10)) @test Colors.alpha.(cs) == Float32.(LinRange(0, 1, 10)) - cs = Makie.resample_cmap(:viridis, 2; alpha=0.5) - @test all(x-> x == 0.5, Colors.alpha.(cs)) + cs = Makie.resample_cmap(:viridis, 2; alpha = 0.5) + @test all(x -> x == 0.5, Colors.alpha.(cs)) @test Colors.color.(cs) == Colors.color.(Makie.resample(to_colormap(:viridis), 2)) cs = Makie.resample_cmap(:Set1, 100) - @test all(x-> x == 1.0, Colors.alpha.(cs)) + @test all(x -> x == 1.0, Colors.alpha.(cs)) @test Colors.color.(cs) == Colors.color.(Makie.resample(to_colormap(:Set1), 100)) - cs = Makie.resample_cmap(:Set1, 10; alpha=(0, 1)) + cs = Makie.resample_cmap(:Set1, 10; alpha = (0, 1)) @test Colors.alpha.(cs) == Float32.(LinRange(0, 1, 10)) end @@ -237,11 +238,11 @@ end @test to_colormap((:viridis, 0.1)) isa Vector{RGBAf} @test to_colormap(Reverse(:viridis)) isa Vector{RGBAf} @test to_colormap(:cividis) isa Vector{RGBAf} - @test to_colormap(cgrad(:cividis, 8, categorical=true)) isa Vector{RGBAf} + @test to_colormap(cgrad(:cividis, 8, categorical = true)) isa Vector{RGBAf} @test to_colormap(cgrad(:cividis, 8)) isa Vector{RGBAf} @test to_colormap(cgrad(:cividis)) isa Vector{RGBAf} - @test alpha(to_colormap(cgrad(:cividis, 8; alpha=0.5))[1]) == 0.5 - @test alpha(to_colormap(cgrad(:cividis, 8; alpha=0.5, categorical=true))[1]) == 0.5 + @test alpha(to_colormap(cgrad(:cividis, 8; alpha = 0.5))[1]) == 0.5 + @test alpha(to_colormap(cgrad(:cividis, 8; alpha = 0.5, categorical = true))[1]) == 0.5 @inferred to_colormap([HSL(0, 10, 20)]) @@ -250,21 +251,21 @@ end @inferred to_colormap((:viridis, 0.1)) @inferred to_colormap(Reverse(:viridis)) @inferred to_colormap(:cividis) - @inferred to_colormap(cgrad(:cividis, 8, categorical=true)) + @inferred to_colormap(cgrad(:cividis, 8, categorical = true)) @inferred to_colormap(cgrad(:cividis, 8)) @inferred to_colormap(cgrad(:cividis)) - @inferred to_colormap(cgrad(:cividis, 8; alpha=0.5)) - @inferred to_colormap(cgrad(:cividis, 8; alpha=0.5, categorical=true)) + @inferred to_colormap(cgrad(:cividis, 8; alpha = 0.5)) + @inferred to_colormap(cgrad(:cividis, 8; alpha = 0.5, categorical = true)) end @testset "empty poly" begin - f, ax, pl = poly(Rect2f[]); - pl[1] = [Rect2f(0, 0, 1, 1)]; + f, ax, pl = poly(Rect2f[]) + pl[1] = [Rect2f(0, 0, 1, 1)] @test pl.plots[1][1][] == [GeometryBasics.triangle_mesh(Rect2f(0, 0, 1, 1))] f, ax, pl = poly(Vector{Point2f}[]) - points = decompose(Point2f, Circle(Point2f(0),1)) + points = decompose(Point2f, Circle(Point2f(0), 1)) pl[1] = [points] @test pl.plots[1][1][] == Makie.poly_convert(points) end diff --git a/test/events.jl b/test/events.jl index 31b2b484eb8..53e66b86bc3 100644 --- a/test/events.jl +++ b/test/events.jl @@ -50,9 +50,9 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right @test !ispressed(events, Mouse.right) # Collections - @test ispressed(events, (Keyboard.a, )) - @test ispressed(events, [Keyboard.a, ]) - @test ispressed(events, Set((Keyboard.a, ))) + @test ispressed(events, (Keyboard.a,)) + @test ispressed(events, [Keyboard.a,]) + @test ispressed(events, Set((Keyboard.a,))) @test !ispressed(events, (Keyboard.a, Keyboard.b)) @test !ispressed(events, [Keyboard.a, Keyboard.b]) @@ -135,8 +135,8 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right clipboard() = CLIP[] end @testset "copy_paste" begin - f = Figure(resolution=(640,480)) - tb = Textbox(f[1,1], placeholder="Copy/paste into me") + f = Figure(resolution = (640, 480)) + tb = Textbox(f[1, 1], placeholder = "Copy/paste into me") e = events(f.scene) # Initial state @@ -166,8 +166,8 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right # Refresh figure to test right control + v combination empty!(f) - f = Figure(resolution=(640,480)) - tb = Textbox(f[1,1], placeholder="Copy/paste into me") + f = Figure(resolution = (640, 480)) + tb = Textbox(f[1, 1], placeholder = "Copy/paste into me") e = events(f.scene) # Initial state @@ -196,109 +196,112 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right # This testset is based on the results the current camera system has. If # cam3d! is updated this is likely to break. @testset "cam3d!" begin - scene = Scene(resolution=(800, 600)); + scene = Scene(resolution = (800, 600)) e = events(scene) - cam3d!(scene, fixed_axis=true, cad=false, zoom_shift_lookat=false) + cam3d!(scene, fixed_axis = true, cad = false, zoom_shift_lookat = false) cc = cameracontrols(scene) # Verify initial camera state - @test cc.lookat[] == Vec3f(0) - @test cc.eyeposition[] == Vec3f(3) - @test cc.upvector[] == Vec3f(0, 0, 1) + @test cc.lookat[] == Vec3f(0) + @test cc.eyeposition[] == Vec3f(3) + @test cc.upvector[] == Vec3f(0, 0, 1) # Rotation # 1) In scene, in drag e.mouseposition[] = (400, 250) e.mousebutton[] = MouseButtonEvent(Mouse.left, Mouse.press) e.mouseposition[] = (600, 250) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ Vec3f(4.14532, -0.9035063, 3.0) - @test cc.upvector[] ≈ Vec3f(0, 0, 1) + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(4.14532, -0.9035063, 3.0) + @test cc.upvector[] ≈ Vec3f(0, 0, 1) # 2) Outside scene, in drag e.mouseposition[] = (1000, 450) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ Vec3f(-2.8912058, -3.8524969, -1.9491522) - @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(-2.8912058, -3.8524969, -1.9491522) + @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) # 3) not in drag e.mousebutton[] = MouseButtonEvent(Mouse.left, Mouse.release) e.mouseposition[] = (400, 250) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ Vec3f(-2.8912058, -3.8524969, -1.9491522) - @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(-2.8912058, -3.8524969, -1.9491522) + @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) # Reset state so this is indepentent from the last checks - scene = Scene(resolution=(800, 600)); + scene = Scene(resolution = (800, 600)) e = events(scene) - cam3d!(scene, fixed_axis=true, cad=false, zoom_shift_lookat=false) + cam3d!(scene, fixed_axis = true, cad = false, zoom_shift_lookat = false) cc = cameracontrols(scene) # Verify initial camera state - @test cc.lookat[] == Vec3f(0) - @test cc.eyeposition[] == Vec3f(3) - @test cc.upvector[] == Vec3f(0, 0, 1) + @test cc.lookat[] == Vec3f(0) + @test cc.eyeposition[] == Vec3f(3) + @test cc.upvector[] == Vec3f(0, 0, 1) # translation # 1) In scene, in drag e.mousebutton[] = MouseButtonEvent(Mouse.right, Mouse.press) e.mouseposition[] = (600, 250) - @test cc.lookat[] ≈ Vec3f(5.4697413, -3.3484206, -2.1213205) - @test cc.eyeposition[] ≈ Vec3f(8.469742, -0.34842062, 0.8786795) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(5.4697413, -3.3484206, -2.1213205) + @test cc.eyeposition[] ≈ Vec3f(8.469742, -0.34842062, 0.8786795) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) # 2) Outside scene, in drag e.mouseposition[] = (1000, 450) - @test cc.lookat[] ≈ Vec3f(9.257657, -5.4392805, -3.818377) - @test cc.eyeposition[] ≈ Vec3f(12.257658, -2.4392805, -0.81837714) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(9.257657, -5.4392805, -3.818377) + @test cc.eyeposition[] ≈ Vec3f(12.257658, -2.4392805, -0.81837714) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) # 3) not in drag e.mousebutton[] = MouseButtonEvent(Mouse.right, Mouse.release) e.mouseposition[] = (400, 250) - @test cc.lookat[] ≈ Vec3f(9.257657, -5.4392805, -3.818377) - @test cc.eyeposition[] ≈ Vec3f(12.257658, -2.4392805, -0.81837714) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(9.257657, -5.4392805, -3.818377) + @test cc.eyeposition[] ≈ Vec3f(12.257658, -2.4392805, -0.81837714) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) # Reset state - scene = Scene(resolution=(800, 600)); + scene = Scene(resolution = (800, 600)) e = events(scene) - cam3d!(scene, fixed_axis=true, cad=false, zoom_shift_lookat=false) + cam3d!(scene, fixed_axis = true, cad = false, zoom_shift_lookat = false) cc = cameracontrols(scene) # Verify initial camera state - @test cc.lookat[] == Vec3f(0) - @test cc.eyeposition[] == Vec3f(3) - @test cc.upvector[] == Vec3f(0, 0, 1) - @test cc.zoom_mult[] == 1f0 + @test cc.lookat[] == Vec3f(0) + @test cc.eyeposition[] == Vec3f(3) + @test cc.upvector[] == Vec3f(0, 0, 1) + @test cc.zoom_mult[] == 1f0 # Zoom e.scroll[] = (0.0, 4.0) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ Vec3f(3) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) - @test cc.zoom_mult[] ≈ 0.6830134f0 + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(3) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.zoom_mult[] ≈ 0.6830134f0 # should not work outside the scene e.mouseposition[] = (1000, 450) e.scroll[] = (0.0, 4.0) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ Vec3f(3) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) - @test cc.zoom_mult[] ≈ 0.6830134f0 + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(3) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.zoom_mult[] ≈ 0.6830134f0 end @testset "mouse state machine" begin - scene = Scene(resolution=(800, 600)); + scene = Scene(resolution = (800, 600)) e = events(scene) bbox = Observable(Rect2(200, 200, 400, 300)) - msm = addmouseevents!(scene, bbox, priority=typemax(Int)) + msm = addmouseevents!(scene, bbox, priority = typemax(Int)) eventlog = MouseEvent[] - on(x -> begin push!(eventlog, x); false end, msm.obs) + on(x -> begin + push!(eventlog, x) + false + end, msm.obs) e.mouseposition[] = (0, 200) @test isempty(eventlog) @@ -325,10 +328,10 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right e.mousebutton[] = MouseButtonEvent(getfield(Mouse, button), Mouse.release) @test length(eventlog) == 3 for (i, t) in enumerate(( - getfield(MouseEventTypes, Symbol(button, :down)), - getfield(MouseEventTypes, Symbol(button, :click)), - getfield(MouseEventTypes, Symbol(button, :up)) - )) + getfield(MouseEventTypes, Symbol(button, :down)), + getfield(MouseEventTypes, Symbol(button, :click)), + getfield(MouseEventTypes, Symbol(button, :up)) + )) @test eventlog[i].type == t @test eventlog[i].px == Point2f(300, 300) @test eventlog[i].prev_px == Point2f(300, 300) @@ -340,10 +343,10 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right e.mousebutton[] = MouseButtonEvent(getfield(Mouse, button), Mouse.release) @test length(eventlog) == 3 for (i, t) in enumerate(( - getfield(MouseEventTypes, Symbol(button, :down)), - getfield(MouseEventTypes, Symbol(button, :doubleclick)), - getfield(MouseEventTypes, Symbol(button, :up)) - )) + getfield(MouseEventTypes, Symbol(button, :down)), + getfield(MouseEventTypes, Symbol(button, :doubleclick)), + getfield(MouseEventTypes, Symbol(button, :up)) + )) @test eventlog[i].type == t @test eventlog[i].px == Point2f(300, 300) @test eventlog[i].prev_px == Point2f(300, 300) @@ -355,10 +358,10 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right e.mousebutton[] = MouseButtonEvent(getfield(Mouse, button), Mouse.release) @test length(eventlog) == 3 for (i, t) in enumerate(( - getfield(MouseEventTypes, Symbol(button, :down)), - getfield(MouseEventTypes, Symbol(button, :click)), - getfield(MouseEventTypes, Symbol(button, :up)) - )) + getfield(MouseEventTypes, Symbol(button, :down)), + getfield(MouseEventTypes, Symbol(button, :click)), + getfield(MouseEventTypes, Symbol(button, :up)) + )) @test eventlog[i].type == t @test eventlog[i].px == Point2f(300, 300) @test eventlog[i].prev_px == Point2f(300, 300) @@ -372,16 +375,16 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right e.mousebutton[] = MouseButtonEvent(getfield(Mouse, button), Mouse.release) @test length(eventlog) == 6 prev_px = Point2f[(300, 300), (300, 300), (300, 300), (500, 300), (700, 200), (700, 200)] - px = Point2f[(300, 300), (500, 300), (500, 300), (700, 200), (700, 200), (700, 200)] + px = Point2f[(300, 300), (500, 300), (500, 300), (700, 200), (700, 200), (700, 200)] for (i, t) in enumerate(( - getfield(MouseEventTypes, Symbol(button, :down)), - getfield(MouseEventTypes, Symbol(button, :dragstart)), - getfield(MouseEventTypes, Symbol(button, :drag)), - getfield(MouseEventTypes, Symbol(button, :drag)), - getfield(MouseEventTypes, Symbol(button, :dragstop)), - getfield(MouseEventTypes, :out), - # TODO this is kinda missing an "up outside" - )) + getfield(MouseEventTypes, Symbol(button, :down)), + getfield(MouseEventTypes, Symbol(button, :dragstart)), + getfield(MouseEventTypes, Symbol(button, :drag)), + getfield(MouseEventTypes, Symbol(button, :drag)), + getfield(MouseEventTypes, Symbol(button, :dragstop)), + getfield(MouseEventTypes, :out), + # TODO this is kinda missing an "up outside" + )) @test eventlog[i].type == t @test eventlog[i].px == px[i] @test eventlog[i].prev_px == prev_px[i] diff --git a/test/figures.jl b/test/figures.jl index 4d844d115af..813e590d1bc 100644 --- a/test/figures.jl +++ b/test/figures.jl @@ -158,7 +158,7 @@ end @test_throws ArgumentError lines(1:10, axis = (aspect = DataAspect()), figure = (resolution = (100, 100))) @test_throws ArgumentError lines(1:10, figure = (resolution = (100, 100))) @test_throws ArgumentError lines(1:10, axis = (aspect = DataAspect())) - + # these just shouldn't error lines(1:10, axis = (aspect = DataAspect(),)) lines(1:10, axis = Attributes(aspect = DataAspect())) @@ -167,4 +167,4 @@ end f = Figure() @test_throws ArgumentError lines(f[1, 1], 1:10, axis = (aspect = DataAspect())) @test_throws ArgumentError lines(f[1, 1][2, 2], 1:10, axis = (aspect = DataAspect())) -end \ No newline at end of file +end diff --git a/test/liftmacro.jl b/test/liftmacro.jl index 195febf5cd2..f184c887ec2 100644 --- a/test/liftmacro.jl +++ b/test/liftmacro.jl @@ -2,7 +2,7 @@ x = Observable(1.0) y = Observable(2.0) z = (x = x, y = y) - + t1 = @lift($x + $y) @test t1[] == 3.0 t2 = @lift($(z.x) - $(z.y)) diff --git a/test/makielayout.jl b/test/makielayout.jl index 92008f2bc0c..cd103618e76 100644 --- a/test/makielayout.jl +++ b/test/makielayout.jl @@ -12,7 +12,7 @@ to = gl2[1, 4] = Toggle(fig) te = fig[0, :] = Label(fig, "A super title") - me = fig[end + 1, :] = Menu(fig, options=["one", "two", "three"]) + me = fig[end + 1, :] = Menu(fig, options = ["one", "two", "three"]) tb = fig[end + 1, :] = Textbox(fig) is = fig[end + 1, :] = IntervalSlider(fig) @test true @@ -42,8 +42,8 @@ end _, hm = heatmap(fig[1, 1], xs, ys, zs) cb = Colorbar(fig[1, 2], hm) - @test hm.attributes[:colorrange][] == (-.5, .5) - @test cb.limits[] == (-.5, .5) + @test hm.attributes[:colorrange][] == (-0.5, 0.5) + @test cb.limits[] == (-0.5, 0.5) hm.attributes[:colorrange][] = Float32.((-1, 1)) @test cb.limits[] == (-1, 1) @@ -158,12 +158,12 @@ end @testset "Colorbars" begin fig = Figure() hmap = heatmap!(Axis(fig[1, 1]), rand(4, 4)) - cb1 = Colorbar(fig[1,2], hmap; height = Relative(0.65)) + cb1 = Colorbar(fig[1, 2], hmap; height = Relative(0.65)) @test cb1.height[] == Relative(0.65) @testset "conversion" begin # https://github.com/MakieOrg/Makie.jl/issues/2278 fig = Figure() - cbar = Colorbar(fig[1,1], colormap=:viridis, colorrange=Vec2f(0, 1)) + cbar = Colorbar(fig[1, 1], colormap = :viridis, colorrange = Vec2f(0, 1)) ticklabel_strings = first.(cbar.axis.elements[:ticklabels][1][]) @test ticklabel_strings[1] == "0.0" @test ticklabel_strings[end] == "1.0" @@ -185,14 +185,14 @@ end # triggering a conversion error # So we just check that the same scenario doesn't error again f = Figure() - ax = Axis(f[1,1], xticks = 20:10:80) + ax = Axis(f[1, 1], xticks = 20:10:80) scatter!(ax, 30:10:100, rand(Float64, 8), color = :red) end # issues 1958 and 2006 @testset "axislegend number align" begin f = Figure() - ax = Axis(f[1,1], xticks = 20:10:80) + ax = Axis(f[1, 1], xticks = 20:10:80) lines!(ax, 1:10, label = "A line") leg = axislegend(ax, position = (0.4, 0.8)) @test leg.halign[] == 0.4 @@ -205,18 +205,18 @@ end f = Figure() kw = (; backgroundcolor = :red) @test_throws ArgumentError lines(f[1, 1], 1:10, figure = kw) - @test_nowarn lines(f[1, 2], 1:10, axis = kw) + @test_nowarn lines(f[1, 2], 1:10, axis = kw) @test_throws ArgumentError lines(f[1, 3][1, 1], 1:10, figure = kw) - @test_nowarn lines(f[1, 4][1, 2], 1:10, axis = kw) + @test_nowarn lines(f[1, 4][1, 2], 1:10, axis = kw) ax = T(f[1, 5]) @test_throws ArgumentError lines!(ax, 1:10, axis = kw) @test_throws ArgumentError lines!(ax, 1:10, axis = kw) @test_throws ArgumentError lines!(1:10, axis = kw) @test_throws ArgumentError lines!(1:10, figure = kw) - @test_nowarn lines!(1:10) + @test_nowarn lines!(1:10) @test_throws ArgumentError lines!(f[1, 5], 1:10, figure = kw) @test_throws ArgumentError lines!(f[1, 5], 1:10, axis = kw) - @test_nowarn lines!(f[1, 5], 1:10) + @test_nowarn lines!(f[1, 5], 1:10) end end diff --git a/test/pipeline.jl b/test/pipeline.jl index 3faf0ca29ff..220d5310962 100644 --- a/test/pipeline.jl +++ b/test/pipeline.jl @@ -2,7 +2,7 @@ function test_copy(; kw...) scene = Scene() return Makie.merged_get!( - ()-> Makie.default_theme(scene, Lines), + () -> Makie.default_theme(scene, Lines), :lines, scene, Attributes(kw) ) end @@ -13,13 +13,13 @@ end @testset "don't copy in theme merge" begin x = Observable{Any}(1) - res=test_copy(linewidth=x) + res = test_copy(linewidth = x) res.linewidth === x end @testset "don't copy observables in when calling merge!" begin x = Observable{Any}(1) - res=test_copy2(Attributes(linewidth=x)) + res = test_copy2(Attributes(linewidth = x)) res.linewidth === x end diff --git a/test/quaternions.jl b/test/quaternions.jl index 77fd813a030..a49164db64b 100644 --- a/test/quaternions.jl +++ b/test/quaternions.jl @@ -2,8 +2,8 @@ struct Degree{T} <: Number θ::T end Base.:/(θ::Degree, x::Number) = Degree(θ.θ / x) -Base.sin(θ::Degree) = sin(θ.θ * π/180) -Base.cos(θ::Degree) = cos(θ.θ * π/180) +Base.sin(θ::Degree) = sin(θ.θ * π / 180) +Base.cos(θ::Degree) = cos(θ.θ * π / 180) @testset "Quaternions" begin @@ -12,18 +12,21 @@ Base.cos(θ::Degree) = cos(θ.θ * π/180) @test Base.power_by_squaring(qx, 2) ≈ qrotation(Vec(1.0, 0.0, 0.0), pi / 2) theta = pi / 8 qx = qrotation(Vec(1.0, 0.0, 0.0), theta) - c = cos(theta); s = sin(theta) + c = cos(theta) + s = sin(theta) Rx = [1 0 0; 0 c -s; 0 s c] @test Mat3f(qx) ≈ Rx theta = pi / 6 qy = qrotation(Vec(0.0, 1.0, 0.0), theta) - c = cos(theta); s = sin(theta) + c = cos(theta) + s = sin(theta) Ry = [c 0 s; 0 1 0; -s 0 c] @test Mat3f(qy) ≈ Ry theta = 4pi / 3 qz = qrotation(Vec(0.0, 0.0, 1.0), theta) - c = cos(theta); s = sin(theta) + c = cos(theta) + s = sin(theta) Rz = [c -s 0; s c 0; 0 0 1] @test Mat3f(qz) ≈ Rz @@ -54,6 +57,6 @@ Base.cos(θ::Degree) = cos(θ.θ * π/180) # `π` is not an `AbstractFloat` but it is a `Number` @test to_rotation(π) == to_rotation(1.0π) @test to_rotation((v, π)) == to_rotation((v, 1.0π)) - @test to_rotation(Degree(90)) == to_rotation(π/2) - @test to_rotation((v, Degree(90))) == to_rotation((v, π/2)) + @test to_rotation(Degree(90)) == to_rotation(π / 2) + @test to_rotation((v, Degree(90))) == to_rotation((v, π / 2)) end diff --git a/test/record.jl b/test/record.jl index 9e2310a28ed..0bc1c3f12d6 100644 --- a/test/record.jl +++ b/test/record.jl @@ -1,23 +1,23 @@ using Logging module VideoBackend - using Makie - struct Screen <: MakieScreen - size::Tuple{Int, Int} - end - struct ScreenConfig - end - Base.size(screen::Screen) = screen.size - Screen(scene::Scene, config::ScreenConfig, ::Makie.ImageStorageFormat) = Screen(size(scene)) - Makie.backend_showable(::Type{Screen}, ::MIME"text/html") = true - Makie.backend_showable(::Type{Screen}, ::MIME"image/png") = true - Makie.colorbuffer(screen::Screen) = zeros(RGBf, reverse(screen.size)...) - Base.display(::Screen, ::Scene; kw...) = nothing +using Makie +struct Screen <: MakieScreen + size::Tuple{Int,Int} +end +struct ScreenConfig +end +Base.size(screen::Screen) = screen.size +Screen(scene::Scene, config::ScreenConfig, ::Makie.ImageStorageFormat) = Screen(size(scene)) +Makie.backend_showable(::Type{Screen}, ::MIME"text/html") = true +Makie.backend_showable(::Type{Screen}, ::MIME"image/png") = true +Makie.colorbuffer(screen::Screen) = zeros(RGBf, reverse(screen.size)...) +Base.display(::Screen, ::Scene; kw...) = nothing end Makie.set_active_backend!(VideoBackend) # We need a screenconfig in the theme for every backend! -set_theme!(VideoBackend=Attributes()) +set_theme!(VideoBackend = Attributes()) mktempdir() do tempdir @@ -53,10 +53,10 @@ mktempdir() do tempdir (:compression, 20, ["mkv", "gif"], ["mp4", "webm"]), (:profile, "high422", ["mkv", "webm", "gif"], ["mp4"]), ( - kwarg=:pixel_format, - value="yuv420p", - warn_fmts=["mkv", "webm", "gif"], - no_warn_fmts=["mp4"], + kwarg = :pixel_format, + value = "yuv420p", + warn_fmts = ["mkv", "webm", "gif"], + no_warn_fmts = ["mp4"], ), ] diff --git a/test/runtests.jl b/test/runtests.jl index 5d46b19a92e..2f8a425ac98 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -15,7 +15,7 @@ using Makie: volume lims = Makie.data_limits(vplot) lo, hi = extrema(lims) @test all(lo .<= 1) - @test all(hi .>= (8,8,10)) + @test all(hi .>= (8, 8, 10)) end include("pipeline.jl") diff --git a/test/stack.jl b/test/stack.jl index e03b5779a8b..f517bbd9e97 100644 --- a/test/stack.jl +++ b/test/stack.jl @@ -1,27 +1,27 @@ using Makie: stack_grouped_from_to @testset "grouped bar: stack" begin - x1 = [1, 1, 1, 1] - grp_dodge1 = [2, 2, 1, 1] - grp_stack1 = [1, 2, 1, 2] - y1 = [2, 3, -3, -2] + x1 = [1, 1, 1, 1] + grp_dodge1 = [2, 2, 1, 1] + grp_stack1 = [1, 2, 1, 2] + y1 = [2, 3, -3, -2] - x2 = [2, 2, 2, 2] - grp_dodge2 = [3, 4, 3, 4] - grp_stack2 = [3, 4, 3, 4] - y2 = [2, 3, -3, -2] + x2 = [2, 2, 2, 2] + grp_dodge2 = [3, 4, 3, 4] + grp_stack2 = [3, 4, 3, 4] + y2 = [2, 3, -3, -2] from, to = stack_grouped_from_to(grp_stack1, y1, (; x1 = x1, grp_dodge1 = grp_dodge1)) - from1 = [0.0, 2.0, 0.0, -3.0] - to1 = [2.0, 5.0, -3.0, -5.0] + from1 = [0.0, 2.0, 0.0, -3.0] + to1 = [2.0, 5.0, -3.0, -5.0] @test from == from1 - @test to == to1 + @test to == to1 from, to = stack_grouped_from_to(grp_stack2, y2, (; x2 = x2, grp_dodge2 = grp_dodge2)) - from2 = [0.0, 0.0, 0.0, 0.0] - to2 = [2.0, 3.0, -3.0, -2.0] + from2 = [0.0, 0.0, 0.0, 0.0] + to2 = [2.0, 3.0, -3.0, -2.0] @test from == from2 - @test to == to2 + @test to == to2 perm = [1, 4, 2, 7, 5, 3, 8, 6] x = [x1; x2][perm] diff --git a/test/statistical_tests.jl b/test/statistical_tests.jl index ca47a2f3cc9..c75917e7c0e 100644 --- a/test/statistical_tests.jl +++ b/test/statistical_tests.jl @@ -15,7 +15,7 @@ seed!(0) @test plt isa BarPlot x = h.edges[1] - @test plt[1][] ≈ Point{2, Float32}.(x[1:end-1] .+ step(x)/2, h.weights) + @test plt[1][] ≈ Point{2,Float32}.(x[1:(end - 1)] .+ step(x) / 2, h.weights) v = (randn(1000), randn(1000)) h = fit(Histogram, v, nbins = 30) @@ -23,16 +23,16 @@ seed!(0) @test plt isa Heatmap x = h.edges[1] y = h.edges[2] - @test plt[1][] ≈ x[1:end-1] .+ step(x)/2 - @test plt[2][] ≈ y[1:end-1] .+ step(y)/2 + @test plt[1][] ≈ x[1:(end - 1)] .+ step(x) / 2 + @test plt[2][] ≈ y[1:(end - 1)] .+ step(y) / 2 @test plt[3][] ≈ h.weights fig, ax, plt = surface(h) @test plt isa Surface x = h.edges[1] y = h.edges[2] - @test plt[1][] ≈ x[1:end-1] .+ step(x)/2 - @test plt[2][] ≈ y[1:end-1] .+ step(y)/2 + @test plt[1][] ≈ x[1:(end - 1)] .+ step(x) / 2 + @test plt[2][] ≈ y[1:(end - 1)] .+ step(y) / 2 @test plt[3][] ≈ h.weights v = (randn(1000), randn(1000), randn(1000)) @@ -43,9 +43,9 @@ seed!(0) x = h.edges[1] y = h.edges[2] z = h.edges[3] - @test plt[1][] ≈ x[1:end-1] .+ step(x)/2 - @test plt[2][] ≈ y[1:end-1] .+ step(y)/2 - @test plt[3][] ≈ z[1:end-1] .+ step(z)/2 + @test plt[1][] ≈ x[1:(end - 1)] .+ step(x) / 2 + @test plt[2][] ≈ y[1:(end - 1)] .+ step(y) / 2 + @test plt[3][] ≈ z[1:(end - 1)] .+ step(z) / 2 @test plt[4][] == h.weights end @@ -152,17 +152,17 @@ end fig, ax, p2 = ecdfplot(v) @test p2 isa ECDFPlot xunique = [vmin - eps(vmin); unique(d.sorted_values)] - fig, ax, p3 = stairs(xunique, d(xunique); step=:post) + fig, ax, p3 = stairs(xunique, d(xunique); step = :post) @test p1[1][] == p3[1][] @test p2.plots[1][1][] == p3[1][] - fig, ax, p4 = ecdfplot(v; npoints=10) + fig, ax, p4 = ecdfplot(v; npoints = 10) pts = p4.plots[1][1][] @test length(pts) == 11 @test pts[1] == Point2f0(vmin - eps(vmin), 0) @test pts[11][2] == 1 - fig, ax, p5 = plot(2..3, ecdf(1:10)) + fig, ax, p5 = plot(2 .. 3, ecdf(1:10)) pts = p5[1][] @test pts[1] == Point2f0(2 - eps(2.0), 0.1) @test pts[2] == Point2f0(2, 0.2) @@ -183,12 +183,12 @@ end @test p.plots[2] isa LineSegments @test p.plots[2][1][] == Point{2,Float32}[Float32[0.6, 3.0], Float32[1.4, 3.0]] - fig, ax, p = crossbar(1, 3, 2, 4; show_notch = true, notchmin = 2.5, notchmax = 3.5); + fig, ax, p = crossbar(1, 3, 2, 4; show_notch = true, notchmin = 2.5, notchmax = 3.5) @test p isa CrossBar @test p.plots[1] isa Poly @test p.plots[1][1][][1] isa Makie.AbstractMesh poly = Point{2,Float32}[[0.6, 2.0], [1.4, 2.0], [1.4, 2.5], [1.2, 3.0], [1.4, 3.5], - [1.4, 4.0], [0.6, 4.0], [0.6, 3.5], [0.8, 3.0], [0.6, 2.5]] + [1.4, 4.0], [0.6, 4.0], [0.6, 3.5], [0.8, 3.0], [0.6, 2.5]] @test map(Point2f, p.plots[1][1][][1].position) == poly @test p.plots[2] isa LineSegments @test p.plots[2][1][] == Point{2,Float32}[Float32[0.8, 3.0], Float32[1.2, 3.0]] @@ -213,7 +213,7 @@ end @test isempty(plts[1][1][]) @test plts[2] isa LineSegments - pts = Point{2, Float32}[ + pts = Point{2,Float32}[ [1.0, 5.75], [1.0, 1.0], [0.6, 1.0], [1.4, 1.0], [1.0, 15.25], [1.0, 20.0], [1.4, 20.0], [0.6, 20.0], [2.0, 25.75], [2.0, 21.0], [1.6, 21.0], [2.4, 21.0], [2.0, 35.25], [2.0, 40.0], [2.4, 40.0], @@ -239,7 +239,7 @@ end @test plts[3].plots[1][1][] == poly #notch - fig, ax, p = boxplot(a, b, show_notch=true) + fig, ax, p = boxplot(a, b, show_notch = true) plts = p.plots @test length(plts) == 3 @@ -262,10 +262,10 @@ end @test plts[3].plots[1] isa Poly notch_boxes = Vector{Point{2,Float32}}[map(Point2f, [[0.6, 5.75], [1.4, 5.75], [1.4, 7.14366], [1.2, 10.5], [1.4, 13.8563], [1.4, 15.25], [0.6, 15.25], [0.6, 13.8563], [0.8, 10.5], [0.6, 7.14366]]), - map(Point2f, [[1.6, 25.75], [2.4, 25.75], [2.4, 27.1437], [2.2, 30.5], [2.4, 33.8563], [2.4, 35.25], [1.6, 35.25], [1.6, 33.8563], [1.8, 30.5], [1.6, 27.1437]]), - map(Point2f, [[2.6, 45.75], [3.4, 45.75], [3.4, 47.1437], [3.2, 50.5], [3.4, 53.8563], [3.4, 55.25], [2.6, 55.25], [2.6, 53.8563], [2.8, 50.5], [2.6, 47.1437]]), - map(Point2f, [[3.6, 65.75], [4.4, 65.75], [4.4, 67.1437], [4.2, 70.5], [4.4, 73.8563], [4.4, 75.25], [3.6, 75.25], [3.6, 73.8563], [3.8, 70.5], [3.6, 67.1437]]), - map(Point2f, [[4.6, 85.75], [5.4, 85.75], [5.4, 87.1437], [5.2, 90.5], [5.4, 93.8563], [5.4, 95.25], [4.6, 95.25], [4.6, 93.8563], [4.8, 90.5], [4.6, 87.1437]])] + map(Point2f, [[1.6, 25.75], [2.4, 25.75], [2.4, 27.1437], [2.2, 30.5], [2.4, 33.8563], [2.4, 35.25], [1.6, 35.25], [1.6, 33.8563], [1.8, 30.5], [1.6, 27.1437]]), + map(Point2f, [[2.6, 45.75], [3.4, 45.75], [3.4, 47.1437], [3.2, 50.5], [3.4, 53.8563], [3.4, 55.25], [2.6, 55.25], [2.6, 53.8563], [2.8, 50.5], [2.6, 47.1437]]), + map(Point2f, [[3.6, 65.75], [4.4, 65.75], [4.4, 67.1437], [4.2, 70.5], [4.4, 73.8563], [4.4, 75.25], [3.6, 75.25], [3.6, 73.8563], [3.8, 70.5], [3.6, 67.1437]]), + map(Point2f, [[4.6, 85.75], [5.4, 85.75], [5.4, 87.1437], [5.2, 90.5], [5.4, 93.8563], [5.4, 95.25], [4.6, 95.25], [4.6, 93.8563], [4.8, 90.5], [4.6, 87.1437]])] meshes = plts[3].plots[1][1][] @testset for (i, mesh) in enumerate(meshes) @test mesh isa Makie.AbstractMesh diff --git a/test/test_primitives.jl b/test/test_primitives.jl index 851d56866a4..e6a66e16259 100644 --- a/test/test_primitives.jl +++ b/test/test_primitives.jl @@ -10,16 +10,16 @@ fig, ax, p = surface(rand(4, 7)) fig, ax, p = volume(rand(4, 4, 4)) begin fig, ax, p = heatmap(rand(4, 4)) - scatter!(Makie.point_iterator(p) |> collect, color=:red, markersize=10) + scatter!(Makie.point_iterator(p) |> collect, color = :red, markersize = 10) display(fig) end fig, ax, p = image(rand(4, 5)) -scatter!(Makie.point_iterator(p) |> collect, color=:red, markersize=10) +scatter!(Makie.point_iterator(p) |> collect, color = :red, markersize = 10) display(fig) begin fig, ax, p = scatter(1:5, rand(5)) - linesegments!(Makie.data_limits(ax.scene), color=:red) + linesegments!(Makie.data_limits(ax.scene), color = :red) display(fig) end diff --git a/test/text.jl b/test/text.jl index c0b1f427eae..65736b79328 100644 --- a/test/text.jl +++ b/test/text.jl @@ -45,9 +45,9 @@ @test glyph_collection.fonts == [font for _ in 1:4] @test all(isapprox.(glyph_collection.origins, [Point3f(x, 0, 0) for x in origins], atol = 1e-10)) @test glyph_collection.scales.sv == [Vec2f(p.fontsize[]) for _ in 1:4] - @test glyph_collection.rotations.sv == [Quaternionf(0,0,0,1) for _ in 1:4] - @test glyph_collection.colors.sv == [RGBAf(0,0,0,1) for _ in 1:4] - @test glyph_collection.strokecolors.sv == [RGBAf(0,0,0,0) for _ in 1:4] + @test glyph_collection.rotations.sv == [Quaternionf(0, 0, 0, 1) for _ in 1:4] + @test glyph_collection.colors.sv == [RGBAf(0, 0, 0, 1) for _ in 1:4] + @test glyph_collection.strokecolors.sv == [RGBAf(0, 0, 0, 0) for _ in 1:4] @test glyph_collection.strokewidths.sv == Float32[0, 0, 0, 0] makie_hi_bb = Makie.height_insensitive_boundingbox.(glyph_collection.extents) @@ -87,7 +87,7 @@ @test all(isequal(to_ndim(Point3f, p.position[], 0f0)), positions) @test char_offsets == glyph_collection.origins @test quad_offsets == fta_quad_offsets - @test scales == fta_scales + @test scales == fta_scales end diff --git a/test/transformations.jl b/test/transformations.jl index fd568f82534..e82327d9603 100644 --- a/test/transformations.jl +++ b/test/transformations.jl @@ -15,7 +15,7 @@ end end function fpoint3(x::Point3) - return Point3f(x[1] + 10, x[2] - 77, x[3] / 4) + return Point3f(x[1] + 10, x[2] - 77, x[3] / 4) end trans2 = PointTrans{2}(fpoint2) trans3 = PointTrans{3}(fpoint3) @@ -77,14 +77,14 @@ end @test apply_transform(i2, 1) == 1 @test apply_transform(i3, 1) == 1 - @test apply_transform(identity, 1..2) == 1..2 - @test apply_transform(i2, 1..2) == 1..2 - @test apply_transform(i3, 1..2) == 1..2 + @test apply_transform(identity, 1 .. 2) == 1 .. 2 + @test apply_transform(i2, 1 .. 2) == 1 .. 2 + @test apply_transform(i3, 1 .. 2) == 1 .. 2 pa = Point2f(1, 2) pb = Point2f(3, 4) r2 = Rect2f(pa, pb .- pa) - @test apply_transform(t1, r2) == Rect2f(apply_transform(t1, pa), apply_transform(t1, pb) .- apply_transform(t1, pa) ) + @test apply_transform(t1, r2) == Rect2f(apply_transform(t1, pa), apply_transform(t1, pb) .- apply_transform(t1, pa)) end @testset "Coordinate Systems" begin @@ -105,14 +105,14 @@ end @testset "Bounding box utilities" begin - box = Rect2f(0,0,1,1) + box = Rect2f(0, 0, 1, 1) @test Makie.rotatedrect(box, π) == Rect2f(-1, -1, 1, 1) - @test Makie.rotatedrect(box, π/2) == Rect2f(0, -1, 1, 1) + @test Makie.rotatedrect(box, π / 2) == Rect2f(0, -1, 1, 1) - @test all(Makie.rotatedrect(box, π/4).origin .≈ Rect2f(0, -1/(√2f0), √2f0, √2f0).origin) - @test all(Makie.rotatedrect(box, π/4).widths .≈ Rect2f(0, -1/(√2f0), √2f0, √2f0).widths) + @test all(Makie.rotatedrect(box, π / 4).origin .≈ Rect2f(0, -1 / (√2f0), √2f0, √2f0).origin) + @test all(Makie.rotatedrect(box, π / 4).widths .≈ Rect2f(0, -1 / (√2f0), √2f0, √2f0).widths) end @@ -125,10 +125,10 @@ end p3 = Point(2.0, 5.0, 4.0) spaces_and_desired_transforms = Dict( - :data => (x,y) -> y, # uses changes - :clip => (x,y) -> x, # no change - :relative => (x,y) -> x, # no change - :pixel => (x,y) -> x, # no transformation + :data => (x, y) -> y, # uses changes + :clip => (x, y) -> x, # no change + :relative => (x, y) -> x, # no change + :pixel => (x, y) -> x, # no transformation ) for (space, desired_transform) in spaces_and_desired_transforms @test apply_transform(identity, p2, space) == p2 @@ -141,5 +141,5 @@ end @test apply_transform(t2, p3, space) == desired_transform(p3, Point3f(sqrt(2.0), log(5.0), 4.0)) @test apply_transform(t3, p3, space) == desired_transform(p3, Point3f(sqrt(2.0), log(5.0), log10(4.0))) - end + end end diff --git a/test/zoom_pan.jl b/test/zoom_pan.jl index 8a5a3e5daa7..ef9b742f8f0 100644 --- a/test/zoom_pan.jl +++ b/test/zoom_pan.jl @@ -13,17 +13,17 @@ end @testset "zoom Axis" begin ax, axbox, lim, e = cleanaxes() # Put the mouse in the center - e.mouseposition[] = Tuple(axbox.origin + axbox.widths/2) + e.mouseposition[] = Tuple(axbox.origin + axbox.widths / 2) # zoom in e.scroll[] = (0.0, -1.0) newlim = ax.finallimits[] @test newlim.widths ≈ 0.9 * lim.widths - @test newlim.origin ≈ lim.origin + (lim.widths - newlim.widths)/2 + @test newlim.origin ≈ lim.origin + (lim.widths - newlim.widths) / 2 # zoom out restores original position e.scroll[] = (0.0, 1.0) newlim = ax.finallimits[] @test newlim.widths ≈ lim.widths - @test all(abs.(newlim.origin - lim.origin) .< 1e-7*lim.widths) + @test all(abs.(newlim.origin - lim.origin) .< 1e-7 * lim.widths) ax.finallimits[] = lim # Put mouse in corner e.mouseposition[] = Tuple(axbox.origin) @@ -31,12 +31,12 @@ end e.scroll[] = (0.0, -1.0) newlim = ax.finallimits[] @test newlim.widths ≈ 0.9 * lim.widths - @test all(abs.(newlim.origin - lim.origin) .< 1e-7*lim.widths) + @test all(abs.(newlim.origin - lim.origin) .< 1e-7 * lim.widths) # zoom out e.scroll[] = (0.0, 1.0) newlim = ax.finallimits[] @test newlim.widths ≈ lim.widths - @test all(abs.(newlim.origin - lim.origin) .< 1e-7*lim.widths) + @test all(abs.(newlim.origin - lim.origin) .< 1e-7 * lim.widths) ax.finallimits[] = lim # Zoom only x or y @@ -45,17 +45,17 @@ end lock = getproperty(ax, lockname) @test !lock[] lock[] = true - e.mouseposition[] = Tuple(axbox.origin + axbox.widths/2) + e.mouseposition[] = Tuple(axbox.origin + axbox.widths / 2) e.scroll[] = (0.0, -1.0) newlim = ax.finallimits[] @test newlim.widths[idx] == lim.widths[idx] - @test newlim.widths[3-idx] ≈ 0.9 * lim.widths[3-idx] + @test newlim.widths[3 - idx] ≈ 0.9 * lim.widths[3 - idx] @test newlim.origin[idx] == lim.origin[idx] - @test newlim.origin[3-idx] ≈ lim.origin[3-idx] + (lim.widths[3-idx] - newlim.widths[3-idx])/2 + @test newlim.origin[3 - idx] ≈ lim.origin[3 - idx] + (lim.widths[3 - idx] - newlim.widths[3 - idx]) / 2 e.scroll[] = (0.0, 1.0) newlim = ax.finallimits[] @test newlim.widths ≈ lim.widths - @test all(abs.(newlim.origin - lim.origin) .< 1e-7*lim.widths) + @test all(abs.(newlim.origin - lim.origin) .< 1e-7 * lim.widths) ax.finallimits[] = lim lock[] = false # Simulate pressing the keys @@ -66,13 +66,13 @@ end e.scroll[] = (0.0, -1.0) newlim = ax.finallimits[] @test newlim.widths[idx] == lim.widths[idx] - @test newlim.widths[3-idx] ≈ 0.9 * lim.widths[3-idx] + @test newlim.widths[3 - idx] ≈ 0.9 * lim.widths[3 - idx] @test newlim.origin[idx] == lim.origin[idx] - @test newlim.origin[3-idx] ≈ lim.origin[3-idx] + (lim.widths[3-idx] - newlim.widths[3-idx])/2 + @test newlim.origin[3 - idx] ≈ lim.origin[3 - idx] + (lim.widths[3 - idx] - newlim.widths[3 - idx]) / 2 e.scroll[] = (0.0, 1.0) newlim = ax.finallimits[] @test newlim.widths ≈ lim.widths - @test all(abs.(newlim.origin - lim.origin) .< 1e-7*lim.widths) + @test all(abs.(newlim.origin - lim.origin) .< 1e-7 * lim.widths) end # Rubber band selection @@ -104,23 +104,23 @@ end empty!(e.mousebuttons[]) empty!(keypresses) newlim = ax.finallimits[] - @test all(lim.origin .>= newlim.origin) && all(lim.origin+lim.widths .<= newlim.origin+newlim.widths) + @test all(lim.origin .>= newlim.origin) && all(lim.origin + lim.widths .<= newlim.origin + newlim.widths) end @testset "pan Axis" begin ax, axbox, lim, e = cleanaxes() - e.mouseposition[] = Tuple(axbox.origin + axbox.widths/2) + e.mouseposition[] = Tuple(axbox.origin + axbox.widths / 2) e.scroll[] = (0.0, -1.0) newlim = ax.finallimits[] e.mouseposition[] = Tuple(axbox.origin) panbtn = ax.panbutton[] e.mousebuttons[] = Set([panbtn]) e.mousedrag[] = Mouse.down - e.mouseposition[] = Tuple(axbox.origin + axbox.widths/10) + e.mouseposition[] = Tuple(axbox.origin + axbox.widths / 10) e.mousedrag[] = Mouse.pressed e.mousebuttons[] = Set{typeof(panbtn)}() e.mousedrag[] = Mouse.up panlim = ax.finallimits[] @test panlim.widths == newlim.widths - @test (5/4)*panlim.origin ≈ -newlim.origin + @test (5 / 4) * panlim.origin ≈ -newlim.origin end