diff --git a/.JuliaFormatter.toml b/.JuliaFormatter.toml index 21954a11560..1f3ada72498 100644 --- a/.JuliaFormatter.toml +++ b/.JuliaFormatter.toml @@ -1,11 +1,6 @@ -always_for_in = true -always_use_return = true -import_to_using = true -margin = 110 -pipe_to_function_call = true -remove_extra_newlines = true -short_to_long_function_def = true -style = "yas" -whitespace_in_kwargs = false +style = "minimal" whitespace_ops_in_indices = true -whitespace_typedefs = false +whitespace_in_kwargs = true +indent_submodule = true +always_for_in = true +ignore = ["docs", "metrics"] diff --git a/.github/workflows/format-check.yml b/.github/workflows/format-check.yml new file mode 100644 index 00000000000..0f53e1a1553 --- /dev/null +++ b/.github/workflows/format-check.yml @@ -0,0 +1,35 @@ +name: JuliaFormatter + +on: + pull_request: + push: + branches: [master] + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: julia-actions/setup-julia@latest + with: + version: '1' + - uses: actions/checkout@v4 + - name: Install JuliaFormatter and format + run: | + julia -e 'using Pkg; Pkg.add(PackageSpec(name="JuliaFormatter"))' + julia -e 'using JuliaFormatter; format(".", verbose=true)' + - name: Format check + run: | + julia -e ' + out = Cmd(`git diff --name-only`) |> read |> String + if out == "" + exit(0) + else + @error "Some files have not been formatted !!!" + write(stdout, out) + exit(1) + end + ' diff --git a/CHANGELOG.md b/CHANGELOG.md index cd81d691795..4e139462bc5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## [Unreleased] +- Add formatter [#2520](https://github.com/MakieOrg/Makie.jl/pull/2520). - Add `axislegend(ax, "title")` method [#3808](https://github.com/MakieOrg/Makie.jl/pull/3808) - Improved thread safety of rendering with CairoMakie (independent `Scene`s only) by locking FreeType handles [#3777](https://github.com/MakieOrg/Makie.jl/pull/3777). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0e89c252a55..7c43551c744 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,6 +26,17 @@ Please add tests for any new functionality that you want to add. Makie uses both reference tests that check for visual regressions, and unit tests that check correctness of functions etc. It is also appreciated if you add docstrings or documentation, and add an entry to the NEWS file. +## Format + +A formatter check is used in Makie in order to work with consistent formatting in source files. + +Please run the following snippet (maybe multiple times) for the format check to pass in PRs: +```julia +pkg> add JuliaFormatter +julia> using JuliaFormatter +julia> format(".") +``` + ### Tests Please ensure locally that your feature works by running the tests. diff --git a/CairoMakie/src/CairoMakie.jl b/CairoMakie/src/CairoMakie.jl index 57b9940e216..53eb82f41e0 100644 --- a/CairoMakie/src/CairoMakie.jl +++ b/CairoMakie/src/CairoMakie.jl @@ -14,7 +14,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 f9f444bfaf8..0d48d08174d 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 65a2671b37c..1b6911b88d0 100644 --- a/CairoMakie/src/display.jl +++ b/CairoMakie/src/display.jl @@ -31,13 +31,13 @@ function openurl(url::String) @warn("Can't find a way to open a browser, open $(url) manually!") 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 = joinpath(mktempdir(), "display.png") Makie.push_screen!(scene, screen) cairo_draw(screen, scene) @@ -73,14 +73,14 @@ function Makie.backend_show(screen::Screen{SVG}, io::IO, ::MIME"image/svg+xml", # across svgs when embedding them on websites. # the hash and therefore the salt will always be the same for the same file # so the output is deterministic - salt = repr(CRC32c.crc32c(svg))[end-7:end] + salt = repr(CRC32c.crc32c(svg))[(end - 7):end] # matches: # id="someid" # xlink:href="someid" (but not xlink:href="data:someothercontent" which is how image data is attached) # url(#someid) svg = replace(svg, r"((?:(?:id|xlink:href)=\"(?!data:)[^\"]+)|url\(#[^)]+)" => SubstitutionString("\\1-$salt")) - + print(io, svg) return screen end @@ -110,7 +110,7 @@ end const DISABLED_MIMES = Set{String}() const SUPPORTED_MIMES = Set([ - map(x->string(x()), Makie.WEB_MIMES)..., + map(x -> string(x()), Makie.WEB_MIMES)..., "image/svg+xml", "application/pdf", "application/postscript", @@ -127,7 +127,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) @@ -150,7 +150,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 @@ -164,7 +164,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 46e0e3bcc2d..04dd3749bd0 100644 --- a/CairoMakie/src/infrastructure.jl +++ b/CairoMakie/src/infrastructure.jl @@ -113,13 +113,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 = viewport(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::Plot) diff --git a/CairoMakie/src/overrides.jl b/CairoMakie/src/overrides.jl index e4bb62fa745..cbd95b620a9 100644 --- a/CairoMakie/src/overrides.jl +++ b/CairoMakie/src/overrides.jl @@ -13,13 +13,13 @@ function draw_plot(scene::Scene, screen::Screen, poly::Poly) # so, we should also take a look at converted # First, we check whether a `draw_poly` method exists for the input arguments # before conversion: - return if Base.hasmethod(draw_poly, Tuple{Scene, Screen, typeof(poly), typeof.(to_value.(poly.args))...}) + return if Base.hasmethod(draw_poly, Tuple{Scene,Screen,typeof(poly),typeof.(to_value.(poly.args))...}) draw_poly(scene, screen, poly, to_value.(poly.args)...) - # If not, we check whether a `draw_poly` method exists for the arguments after conversion - # (`plot.converted`). This allows anything which decomposes to be checked for. - elseif Base.hasmethod(draw_poly, Tuple{Scene, Screen, typeof(poly), typeof.(to_value.(poly.converted))...}) + # If not, we check whether a `draw_poly` method exists for the arguments after conversion + # (`plot.converted`). This allows anything which decomposes to be checked for. + elseif Base.hasmethod(draw_poly, Tuple{Scene,Screen,typeof(poly),typeof.(to_value.(poly.converted))...}) draw_poly(scene, screen, poly, to_value.(poly.converted)...) - # In the worst case, we return to drawing the polygon as a mesh + lines. + # In the worst case, we return to drawing the polygon as a mesh + lines. else draw_poly_as_mesh(scene, screen, poly) end @@ -49,8 +49,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{Colorant, Cairo.CairoPattern}, - model, strokecolor, strokestyle, strokewidth) +function draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}, color::Union{Colorant,Cairo.CairoPattern}, + model, strokecolor, strokestyle, strokewidth) space = to_value(get(poly, :space, :data)) points = project_position.(Ref(poly), space, points, Ref(model)) Cairo.move_to(screen.context, points[1]...) @@ -75,7 +75,7 @@ function draw_poly(scene::Scene, screen::Screen, poly, points_list::Vector{<:Vec broadcast_foreach(points_list, color, strokecolor, strokestyle, poly.strokewidth[], Ref(poly.model[])) do points, color, strokecolor, strokestyle, strokewidth, model - draw_poly(scene, screen, poly, points, color, model, strokecolor, strokestyle, strokewidth) + draw_poly(scene, screen, poly, points, color, model, strokecolor, strokestyle, strokewidth) end end @@ -180,7 +180,7 @@ function draw_poly(scene::Scene, screen::Screen, poly, polygons::AbstractArray{< end -function draw_poly(scene::Scene, screen::Screen, poly, polygons::AbstractArray{<: MultiPolygon}) +function draw_poly(scene::Scene, screen::Screen, poly, polygons::AbstractArray{<:MultiPolygon}) model = poly.model[] space = to_value(get(poly, :space, :data)) projected_polys = project_multipolygon.(Ref(poly), space, polygons, Ref(model)) @@ -210,7 +210,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) color = to_cairo_color(band.color[], band) @@ -262,7 +262,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] set_source(screen.context, col) Cairo.fill(screen.context) end diff --git a/CairoMakie/src/precompiles.jl b/CairoMakie/src/precompiles.jl index a654e938544..1401245c87f 100644 --- a/CairoMakie/src/precompiles.jl +++ b/CairoMakie/src/precompiles.jl @@ -16,8 +16,8 @@ let end end precompile(draw_atomic_scatter, (Scene, Cairo.CairoContext, Tuple{typeof(identity),typeof(identity)}, - Vector{ColorTypes.RGBA{Float32}}, Vec{2,Float32}, ColorTypes.RGBA{Float32}, - Float32, BezierPath, Vec{2,Float32}, Quaternionf, - Mat4f, Vector{Point{2,Float32}}, - Mat4f, Makie.FreeTypeAbstraction.FTFont, Symbol, - Symbol)) + Vector{ColorTypes.RGBA{Float32}}, Vec{2,Float32}, ColorTypes.RGBA{Float32}, + Float32, BezierPath, Vec{2,Float32}, Quaternionf, + Mat4f, Vector{Point{2,Float32}}, + Mat4f, Makie.FreeTypeAbstraction.FTFont, Symbol, + Symbol)) diff --git a/CairoMakie/src/primitives.jl b/CairoMakie/src/primitives.jl index 1c760e12bb0..fd684db8a85 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})) @get_attribute(primitive, (color, linewidth, linestyle)) ctx = screen.context model = primitive[:model][] @@ -15,7 +15,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 @@ -114,12 +114,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 @@ -133,9 +133,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 @@ -165,26 +165,26 @@ function draw_multi(primitive::LineSegments, ctx, positions, colors::AbstractArr @assert length(linewidths) == length(colors) for i in 1:2:length(positions) - if isnan(positions[i+1]) || isnan(positions[i]) + if isnan(positions[i + 1]) || isnan(positions[i]) continue end - if linewidths[i] != linewidths[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.move_to(ctx, positions[i]...) - Cairo.line_to(ctx, positions[i+1]...) + Cairo.line_to(ctx, positions[i + 1]...) 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) @@ -211,7 +211,7 @@ function draw_multi(primitive::Lines, ctx, positions, colors::AbstractArray, lin # first is nan, do nothing end - for i in eachindex(positions)[begin+1:end] + for i in eachindex(positions)[(begin + 1):end] this_position = positions[i] this_color = colors[i] this_nan = isnan(this_position) @@ -316,14 +316,14 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Scat transfunc = Makie.transform_func(primitive) return draw_atomic_scatter(scene, ctx, transfunc, colors, markersize, strokecolor, strokewidth, marker, - marker_offset, rotations, model, positions, size_model, font, markerspace, - space) + marker_offset, rotations, model, positions, size_model, font, markerspace, + space) end 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) @@ -399,17 +399,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) @@ -423,7 +423,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)) @@ -484,21 +484,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 @@ -509,13 +509,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)) transform_marker = to_value(get(primitive, :transform_marker, true))::Bool @@ -532,9 +532,9 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Text end function draw_glyph_collection( - scene, ctx, positions, glyph_collections::AbstractArray, rotation, - model::Mat, space, markerspace, offset, transformation, transform_marker - ) + scene, ctx, positions, glyph_collections::AbstractArray, rotation, + model::Mat, space, markerspace, offset, transformation, transform_marker +) # TODO: why is the Ref around model necessary? doesn't broadcast_foreach handle staticarrays matrices? broadcast_foreach(positions, glyph_collections, rotation, Ref(model), space, @@ -548,8 +548,8 @@ _deref(x) = x _deref(x::Ref) = x[] function draw_glyph_collection( - scene, ctx, position, glyph_collection, rotation, _model, space, - markerspace, offsets, transformation, transform_marker) + scene, ctx, position, glyph_collection, rotation, _model, space, + markerspace, offsets, transformation, transform_marker) glyphs = glyph_collection.glyphs glyphoffsets = glyph_collection.origins @@ -576,7 +576,7 @@ function draw_glyph_collection( 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) @@ -658,13 +658,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 @@ -680,21 +680,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 @@ -708,15 +708,15 @@ 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(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 xy_aligned = let # Only allow scaling and translation pv = scene.camera.projectionview[] M = Mat4f( - pv[1, 1], 0.0, 0.0, 0.0, - 0.0, pv[2, 2], 0.0, 0.0, - 0.0, 0.0, pv[3, 3], 0.0, + pv[1, 1], 0.0, 0.0, 0.0, + 0.0, pv[2, 2], 0.0, 0.0, + 0.0, 0.0, pv[3, 3], 0.0, pv[1, 4], pv[2, 4], pv[3, 4], 1.0 ) pv ≈ M @@ -740,7 +740,7 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Unio w, h = xymax .- xy can_use_fast_path = !(is_vector && !interpolate) && regular_grid && identity_transform && - (interpolate || xy_aligned) + (interpolate || xy_aligned) use_fast_path = can_use_fast_path && !disable_fast_path if use_fast_path @@ -781,9 +781,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 @@ -795,10 +795,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) @@ -820,7 +820,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) @@ -832,9 +832,9 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Maki end function draw_mesh2D(scene, screen, @nospecialize(plot), @nospecialize(mesh)) - 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 color = hasproperty(mesh, :color) ? to_color(mesh.color) : plot.calculated_colors[] cols = per_face_colors(color, nothing, fs, nothing, uv) @@ -844,7 +844,7 @@ function draw_mesh2D(scene, screen, @nospecialize(plot), @nospecialize(mesh)) end function draw_mesh2D(scene, screen, per_face_cols, space::Symbol, transform_func, - 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 @@ -852,7 +852,7 @@ function draw_mesh2D(scene, screen, per_face_cols, space::Symbol, transform_func for (f, (c1, c2, c3)) in zip(fs, per_face_cols) - t1, t2, t3 = project_position.(scene, (transform_func,), space, vs[f], (model,)) #triangle points + t1, t2, t3 = project_position.(scene, (transform_func,), space, vs[f], (model,)) #triangle points # don't draw any mesh faces with NaN components. if isnan(t1) || isnan(t2) || isnan(t3) @@ -895,7 +895,7 @@ function draw_mesh3D(scene, screen, attributes, mesh; pos = Vec4f(0), scale = 1f meshpoints = decompose(Point3f, mesh)::Vector{Point3f} meshfaces = decompose(GLTriangleFace, mesh)::Vector{GLTriangleFace} meshnormals = decompose_normals(mesh)::Vector{Vec3f} # note: can be made NaN-aware. - meshuvs = texturecoordinates(mesh)::Union{Nothing, Vector{Vec2f}} + meshuvs = texturecoordinates(mesh)::Union{Nothing,Vector{Vec2f}} # Priorize colors of the mesh if present color = hasproperty(mesh, :color) ? mesh.color : to_value(attributes.calculated_colors) @@ -923,11 +923,11 @@ function draw_mesh3D(scene, screen, attributes, mesh; pos = Vec4f(0), scale = 1f end function draw_mesh3D( - scene, screen, space, transform_func, meshpoints, meshfaces, meshnormals, per_face_col, - pos, scale, rotation, - model, shading, diffuse, - specular, shininess, faceculling - ) + scene, screen, space, transform_func, meshpoints, meshfaces, meshnormals, per_face_col, + pos, scale, rotation, + model, shading, diffuse, + specular, shininess, faceculling +) ctx = screen.context projectionview = Makie.space_to_clip(scene.camera, space, true) eyeposition = scene.camera.eyeposition[] @@ -951,7 +951,7 @@ function draw_mesh3D( dirlight = Makie.get_directional_light(scene) if !isnothing(dirlight) lightdirection = if dirlight.camera_relative - T = inv(scene.camera.view[][Vec(1,2,3), Vec(1,2,3)]) + T = inv(scene.camera.view[][Vec(1, 2, 3), Vec(1, 2, 3)]) normalize(T * dirlight.direction[]) else normalize(dirlight.direction[]) @@ -959,7 +959,7 @@ function draw_mesh3D( c = dirlight.color[] light_color = Vec3f(red(c), green(c), blue(c)) else - lightdirection = Vec3f(0,0,-1) + lightdirection = Vec3f(0, 0, -1) light_color = Vec3f(0) end @@ -1099,21 +1099,19 @@ 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) color = to_color(primitive.calculated_colors[]) submesh = Attributes( - model=model, + model = model, calculated_colors = color, - shading=primitive.shading, diffuse=primitive.diffuse, - specular=primitive.specular, shininess=primitive.shininess, - faceculling=get(primitive, :faceculling, -10), - transformation=Makie.transformation(primitive) - - ) + shading = primitive.shading, diffuse = primitive.diffuse, + specular = primitive.specular, shininess = primitive.shininess, + faceculling = get(primitive, :faceculling, -10), + transformation = Makie.transformation(primitive)) submesh[:model] = model scales = primitive[:markersize][] diff --git a/CairoMakie/src/screen.jl b/CairoMakie/src/screen.jl index 588159df2b4..066d296e3c8 100644 --- a/CairoMakie/src/screen.jl +++ b/CairoMakie/src/screen.jl @@ -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[], 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) @@ -225,7 +225,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 @@ -248,13 +248,13 @@ function Makie.apply_screen_config!(screen::Screen, config::ScreenConfig, scene: end function Screen(scene::Scene; screen_config...) - config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol, Any}(screen_config)) + config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol,Any}(screen_config)) return Screen(scene, config) 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) @@ -262,7 +262,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 12d0f9ae981..2617e786242 100644 --- a/CairoMakie/src/utils.jl +++ b/CairoMakie/src/utils.jl @@ -53,7 +53,7 @@ function project_shape(@nospecialize(scenelike), space, rect::Rect, model) return Rect(mini, maxi .- mini) end -function project_polygon(@nospecialize(scenelike), space, poly::P, model) where P <: Polygon +function project_polygon(@nospecialize(scenelike), space, poly::P, model) where P<:Polygon ext = decompose(Point2f, poly.exterior) interiors = decompose.(Point2f, poly.interiors) Polygon( @@ -62,7 +62,7 @@ function project_polygon(@nospecialize(scenelike), space, poly::P, model) where ) end -function project_multipolygon(@nospecialize(scenelike), space, multipoly::MP, model) where MP <: MultiPolygon +function project_multipolygon(@nospecialize(scenelike), space, multipoly::MP, model) where MP<:MultiPolygon return MultiPolygon(project_polygon.(Ref(scenelike), Ref(space), multipoly.polygons, Ref(model))) end @@ -121,7 +121,7 @@ to_uint32_color(c) = reinterpret(UInt32, convert(ARGB32, premultiplied_rgba(c))) # handle patterns 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 @@ -131,14 +131,14 @@ end # Common color utilities # ######################################## -function to_cairo_color(colors::Union{AbstractVector{<: Number},Number}, plot_object) +function to_cairo_color(colors::Union{AbstractVector{<:Number},Number}, plot_object) cmap = Makie.assemble_colors(colors, Observable(colors), plot_object) return to_color(to_value(cmap)) end function to_cairo_color(color::Makie.AbstractPattern, plot_object) cairopattern = Cairo.CairoPattern(color) - Cairo.pattern_set_extend(cairopattern, Cairo.EXTEND_REPEAT); + Cairo.pattern_set_extend(cairopattern, Cairo.EXTEND_REPEAT) return cairopattern end @@ -159,7 +159,7 @@ end ######################################## -to_cairo_image(img::AbstractMatrix{<: Colorant}) = to_cairo_image(to_uint32_color.(img)) +to_cairo_image(img::AbstractMatrix{<:Colorant}) = to_cairo_image(to_uint32_color.(img)) function to_cairo_image(img::Matrix{UInt32}) # we need to convert from column-major to row-major storage, @@ -172,19 +172,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) @@ -197,10 +197,10 @@ 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 @@ -210,19 +210,19 @@ function per_face_colors(_color, matcap, faces, normals, uv) 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 return FaceIterator(cvec, faces) elseif color isa Colorant return FaceIterator{:Const}(color, faces) - elseif color isa AbstractVector{<: Colorant} + elseif color isa AbstractVector{<:Colorant} return FaceIterator(color, faces) elseif color isa Makie.AbstractPattern # let next level extend and fill with CairoPattern return color - elseif color isa AbstractMatrix{<: Colorant} && !isnothing(uv) + elseif color isa AbstractMatrix{<:Colorant} && !isnothing(uv) wsize = reverse(size(color)) wh = wsize .- 1 cvec = map(uv) do uv diff --git a/CairoMakie/test/rasterization_tests.jl b/CairoMakie/test/rasterization_tests.jl index c5fc95a56ce..4a98490a5db 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 @@ -28,4 +28,4 @@ end @test svg_has_image(fig) end -end \ No newline at end of file +end diff --git a/CairoMakie/test/runtests.jl b/CairoMakie/test/runtests.jl index afac97bc2d5..ccd68599375 100644 --- a/CairoMakie/test/runtests.jl +++ b/CairoMakie/test/runtests.jl @@ -7,7 +7,7 @@ using ReferenceTests @testset "Runs without error" begin fig = Figure() scatter(fig[1, 1], rand(10)) - fn = tempname()*".png" + fn = tempname() * ".png" try save(fn, fig) finally @@ -40,8 +40,8 @@ include(joinpath(@__DIR__, "rasterization_tests.jl")) fig = Figure(size = (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") @@ -52,14 +52,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=(; size = (800, 800))) + fig = scatter(1:4, figure = (; size = (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=(; size = (800, 800))) + fig = scatter(1:4, figure = (; size = (800, 800))) save("test.pdf", fig) save("test.png", fig) @test size(load("test.png")) == (1600, 1600) @@ -89,32 +89,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(size = (800, 800)); + scene = Scene(size = (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 @@ -122,8 +122,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=(size=(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 = (size = (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 @@ -191,7 +191,7 @@ functions = [:volume, :volume!, :uv_mesh] @testset "refimages" begin CairoMakie.activate!(type = "png", px_per_unit = 1) - ReferenceTests.mark_broken_tests(excludes, functions=functions) + ReferenceTests.mark_broken_tests(excludes, functions = functions) recorded_files, recording_dir = @include_reference_tests CairoMakie "refimages.jl" missing_images, scores = ReferenceTests.record_comparison(recording_dir) ReferenceTests.test_comparison(scores; threshold = 0.05) diff --git a/CairoMakie/test/svg_tests.jl b/CairoMakie/test/svg_tests.jl index 93cb0b9349f..492ab671423 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))) @@ -20,9 +24,9 @@ end # issue 2510 @test svg_isnt_rasterized(begin fig = Figure() - ax = Axis(fig[1,1]) - poly!(ax, Makie.GeometryBasics.Polygon(Point2.([[0,0],[1,0],[0,1],[0,0]])), color = ("#FF0000", 0.7), label = "foo") - poly!(ax, Makie.GeometryBasics.Polygon(Point2.([[0,0],[1,0],[0,1],[0,0]])), color = (:blue, 0.7), label = "bar") + ax = Axis(fig[1, 1]) + poly!(ax, Makie.GeometryBasics.Polygon(Point2.([[0, 0], [1, 0], [0, 1], [0, 0]])), color = ("#FF0000", 0.7), label = "foo") + poly!(ax, Makie.GeometryBasics.Polygon(Point2.([[0, 0], [1, 0], [0, 1], [0, 0]])), color = (:blue, 0.7), label = "bar") fig[1, 2] = Legend(fig, ax, "Bar") fig end) diff --git a/GLMakie/experiments/cuda_interop.jl b/GLMakie/experiments/cuda_interop.jl index c149d4f7b4b..151d064e908 100644 --- a/GLMakie/experiments/cuda_interop.jl +++ b/GLMakie/experiments/cuda_interop.jl @@ -2,13 +2,13 @@ using CUDA, GLMakie, NVTX using GLMakie.GLAbstraction # from https://discourse.julialang.org/t/cuarray-glmakie/52461/11?u=maleadt -function cu_plot(; T=Float32, N=1024, resolution=(800, 600)) +function cu_plot(; T = Float32, N = 1024, resolution = (800, 600)) t = CUDA.rand(T, N) X = CUDA.rand(T, N) # so that we can create a GLBuffer before having rendered anything. fig = Figure(; resolution) - ax = Axis(fig[1, 1]; limits=(0, 1, 0, 1)) + ax = Axis(fig[1, 1]; limits = (0, 1, 0, 1)) screen = display(fig) # get a buffer object and register it with CUDA @@ -16,7 +16,7 @@ function cu_plot(; T=Float32, N=1024, resolution=(800, 600)) resource = let ref = Ref{CUDA.CUgraphicsResource}() CUDA.cuGraphicsGLRegisterBuffer(ref, buffer.id, - CUDA.CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD) + CUDA.CU_GRAPHICS_MAP_RESOURCE_FLAGS_WRITE_DISCARD) ref[] end @@ -53,7 +53,7 @@ function cu_plot(; T=Float32, N=1024, resolution=(800, 600)) NVTX.@range "Makie" begin scatter!(ax, buffer) # force everything to render (for benchmarking purposes) - GLMakie.render_frame(screen; resize_buffers=false) + GLMakie.render_frame(screen; resize_buffers = false) GLMakie.glFinish() end end 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 2241931b7f4..8a29d6d5d6b 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("Assigning 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 size(A) != size(value) if isa(A, GLBuffer) && length(A) != length(value) @@ -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,58 +139,58 @@ 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 obs2 = on(new_data -> update!(gpu_mem, new_data), data) diff --git a/GLMakie/src/GLAbstraction/GLBuffer.jl b/GLMakie/src/GLAbstraction/GLBuffer.jl index a19d789af23..83ae44a8c42 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 @@ -41,28 +41,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) au = ShaderAbstractions.updater(buffer) obsfunc = on(au.update) do (f, args) f(b, args...) # forward setindex! etc @@ -77,32 +77,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 @@ -115,18 +115,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 @@ -141,14 +141,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 @@ -162,18 +162,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 @@ -181,40 +181,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 d6eb089f410..85b98d66c49 100644 --- a/GLMakie/src/GLAbstraction/GLRender.jl +++ b/GLMakie/src/GLAbstraction/GLRender.jl @@ -54,7 +54,7 @@ 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) if renderobject.visible renderobject.prerenderfunction() program = vertexarray.program @@ -71,7 +71,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 @@ -87,14 +87,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) @@ -106,7 +106,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 @@ -115,7 +115,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), @@ -127,7 +127,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 @@ -135,12 +135,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 @@ -148,7 +148,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 8e8ab99061c..815dbe64400 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::Vector{ShaderSource} - kw_args::Dict{Symbol, Any} + kw_args::Dict{Symbol,Any} function LazyShader(cache::ShaderCache, paths::ShaderSource...; 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 @@ -171,7 +171,7 @@ function compile_program(shaders::Vector{Shader}, 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 @@ -185,7 +185,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 @@ -200,7 +200,7 @@ function gl_convert(cache::ShaderCache, lazyshader::AbstractLazyShader, data) paths = lazyshader.paths v = get_view(kw_dict) - fragdatalocation = get(kw_dict, :fragdatalocation, Tuple{Int, String}[]) + fragdatalocation = get(kw_dict, :fragdatalocation, Tuple{Int,String}[]) template_keys = Vector{Vector{String}}(undef, length(paths)) replacements = Vector{Vector{String}}(undef, length(paths)) @@ -240,7 +240,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 @@ -258,7 +258,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 @@ -297,7 +297,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 @@ -308,8 +309,8 @@ function mustache2replacement(mustache_key, view, attributes) end # Takes a shader template and renders the template and returns shader source -function template2source(source::AbstractString, view, attributes::Dict{Symbol, Any}) - replacements = Dict{String, String}() +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 028c23db012..4d0598245f4 100644 --- a/GLMakie/src/GLAbstraction/GLTexture.jl +++ b/GLMakie/src/GLAbstraction/GLTexture.jl @@ -1,32 +1,32 @@ 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 - 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 + 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, @@ -44,10 +44,10 @@ 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} - function TextureBuffer(texture::Texture{T, 1}, buffer::GLBuffer{T}) where T + function TextureBuffer(texture::Texture{T,1}, buffer::GLBuffer{T}) where T new{T}(texture, buffer) end end @@ -73,7 +73,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) @@ -83,13 +83,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) @@ -97,16 +97,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 @@ -119,8 +119,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. @@ -128,13 +128,13 @@ 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} -Texture(image::AbstractArray{T, NDim}; kw_args...) where {T <: GLArrayEltypes, NDim} = +Texture(image::AbstractArray{T,NDim}; kw_args...) where {T<:GLArrayEltypes,NDim} = Texture(collect(image); kw_args...) -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, @@ -150,12 +150,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() @@ -163,21 +163,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...) @@ -188,20 +188,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 @@ -242,7 +242,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) @@ -275,26 +275,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, @@ -304,7 +304,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, @@ -324,13 +324,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) @@ -340,17 +340,17 @@ 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} id = glGenTextures() glBindTexture(t.texturetype, id) glTexImage(t.texturetype, 0, t.internalformat, newdims..., 0, t.format, t.pixeltype, C_NULL) - return Texture{T, NDim}( + return Texture{T,NDim}( id, t.texturetype, t.pixeltype, @@ -361,16 +361,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) @@ -381,24 +381,24 @@ 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) @@ -418,10 +418,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) @@ -473,7 +473,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) @@ -492,13 +492,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 @@ -509,20 +509,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])) @@ -552,7 +552,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 206a8dda42a..abb08b2406a 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 @@ -247,7 +247,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) @@ -308,12 +308,12 @@ mutable struct RenderObject{Pre} visible::Bool function RenderObject{Pre}( - context, - uniforms::Dict{Symbol,Any}, observables::Vector{Observable}, - vertexarray::GLVertexArray, - prerenderfunctions, postrenderfunctions, - visible - ) where Pre + context, + uniforms::Dict{Symbol,Any}, observables::Vector{Observable}, + vertexarray::GLVertexArray, + prerenderfunctions, postrenderfunctions, + visible + ) 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 @@ -338,10 +338,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) @@ -380,7 +380,7 @@ function RenderObject( merge!(data, gl_convert_struct(v, k)) delete!(data, k) - # try direct conversion + # try direct conversion elseif applicable(gl_convert, v) try data[k] = gl_convert(v) @@ -388,8 +388,8 @@ function RenderObject( rethrow(e) end - # Otherwise just let the value pass through - # TODO: Is this ok/ever not filtered? + # Otherwise just let the value pass through + # TODO: Is this ok/ever not filtered? else # @debug "Passed on $k -> $(typeof(v)) without conversion." end diff --git a/GLMakie/src/GLAbstraction/GLUniforms.jl b/GLMakie/src/GLAbstraction/GLUniforms.jl index a51af4024bc..8b686aefe0f 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 @@ -214,7 +214,7 @@ function isa_gl_struct(x::T) where T end function gl_convert_struct(obs::Observable{T}, uniform_name::Symbol) where T if isa_gl_struct(obs) - return Dict{Symbol, Any}(map(fieldnames(T)) do name + return Dict{Symbol,Any}(map(fieldnames(T)) do name Symbol("$uniform_name.$name") => map(x -> gl_convert(getfield(x, name)), obs) end) else @@ -223,7 +223,7 @@ function gl_convert_struct(obs::Observable{T}, uniform_name::Symbol) 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(T)) do name + return Dict{Symbol,Any}(map(fieldnames(T)) do name Symbol("$uniform_name.$name") => gl_convert(getfield(x, name)) end) else @@ -233,32 +233,32 @@ 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) +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) gl_convert(x::Vector) = x -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...) +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 diff --git a/GLMakie/src/GLAbstraction/GLUtils.jl b/GLMakie/src/GLAbstraction/GLUtils.jl index 4176bdc97b9..ca650098906 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 47361006a81..8ba4b26d171 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) @@ -56,7 +56,7 @@ end const GL_ASSET_DIR = RelocatableFolders.@path joinpath(@__DIR__, "..", "assets") const SHADER_DIR = RelocatableFolders.@path joinpath(GL_ASSET_DIR, "shader") -const LOADED_SHADERS = Dict{String, ShaderSource}() +const LOADED_SHADERS = Dict{String,ShaderSource}() function loadshader(name) # Turns out, joinpath is so slow, that it actually makes sense diff --git a/GLMakie/src/display.jl b/GLMakie/src/display.jl index c8cb5a85064..02103e5f743 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) @@ -14,4 +14,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", Makie.WEB_MIMES...}) = true +Makie.backend_showable(::Type{Screen}, ::Union{MIME"image/jpeg",MIME"image/png",Makie.WEB_MIMES...}) = true diff --git a/GLMakie/src/drawing_primitives.jl b/GLMakie/src/drawing_primitives.jl index 44b7a30026f..fbbdf34816a 100644 --- a/GLMakie/src/drawing_primitives.jl +++ b/GLMakie/src/drawing_primitives.jl @@ -18,9 +18,9 @@ function handle_lights(attr::Dict, screen::Screen, lights::Vector{Makie.Abstract # Other parameters like position, direction, etc differe between light types. # To avoid wasting a bunch of memory we squash all of them into one vector of # size MAX_PARAMS. - attr[:N_lights] = Observable(0) - attr[:light_types] = Observable(sizehint!(Int32[], MAX_LIGHTS)) - attr[:light_colors] = Observable(sizehint!(RGBf[], MAX_LIGHTS)) + attr[:N_lights] = Observable(0) + attr[:light_types] = Observable(sizehint!(Int32[], MAX_LIGHTS)) + attr[:light_colors] = Observable(sizehint!(RGBf[], MAX_LIGHTS)) attr[:light_parameters] = Observable(sizehint!(Float32[], MAX_PARAMS)) on(screen.render_tick, priority = typemin(Int)) do _ @@ -78,7 +78,7 @@ function handle_lights(attr::Dict, screen::Screen, lights::Vector{Makie.Abstract idx = push_inplace!(parameters, idx, light.attenuation[]) elseif light isa DirectionalLight if light.camera_relative - T = inv(attr[:view][][Vec(1,2,3), Vec(1,2,3)]) + T = inv(attr[:view][][Vec(1, 2, 3), Vec(1, 2, 3)]) dir = normalize(T * light.direction[]) else dir = normalize(light.direction[]) @@ -144,9 +144,9 @@ function connect_camera!(plot, gl_attributes, cam, space = gl_attributes[:space] end get!(gl_attributes, :view) do # get!(cam.calculated_values, Symbol("view_$(space[])")) do - return lift(plot, cam.view, space) do view, space - return is_data_space(space) ? view : Mat4f(I) - end + return lift(plot, cam.view, space) do view, space + return is_data_space(space) ? view : Mat4f(I) + end # end end @@ -167,22 +167,22 @@ function connect_camera!(plot, gl_attributes, cam, space = gl_attributes[:space] end get!(gl_attributes, :projection) do # return get!(cam.calculated_values, Symbol("projection_$(space[])")) do - return lift(plot, cam.projection, cam.pixel_space, space) do _, _, space - return Makie.space_to_clip(cam, space, false) - end + return lift(plot, cam.projection, cam.pixel_space, space) do _, _, space + return Makie.space_to_clip(cam, space, false) + end # end end get!(gl_attributes, :projectionview) do # get!(cam.calculated_values, Symbol("projectionview_$(space[])")) do - return lift(plot, cam.projectionview, cam.pixel_space, space) do _, _, space - Makie.space_to_clip(cam, space, true) - end + return lift(plot, cam.projectionview, cam.pixel_space, space) do _, _, space + Makie.space_to_clip(cam, space, true) + end # end end # resolution in real hardware pixels, not scaled pixels/units get!(gl_attributes, :resolution) do # get!(cam.calculated_values, :resolution) do - return lift(*, plot, gl_attributes[:px_per_unit], cam.resolution) + return lift(*, plot, gl_attributes[:px_per_unit], cam.resolution) # end end @@ -199,7 +199,7 @@ function handle_intensities!(screen, attributes, plot) end attributes[:intensity] = color[].color_scaled interp = color[].color_mapping_type[] === Makie.continuous ? :linear : :nearest - attributes[:color_map] = Texture(color[].colormap; minfilter=interp) + attributes[:color_map] = Texture(color[].colormap; minfilter = interp) attributes[:color_norm] = color[].colorrange_scaled attributes[:nan_color] = color[].nan_color attributes[:highclip] = Makie.highclip(color[]) @@ -222,10 +222,10 @@ function get_space(x) end const EXCLUDE_KEYS = Set([:transformation, :tickranges, :ticklabels, :raw, :SSAO, - :lightposition, :material, :axis_cycler, - :inspector_label, :inspector_hover, :inspector_clear, :inspectable, - :colorrange, :colormap, :colorscale, :highclip, :lowclip, :nan_color, - :calculated_colors, :space, :markerspace, :model]) + :lightposition, :material, :axis_cycler, + :inspector_label, :inspector_hover, :inspector_clear, :inspectable, + :colorrange, :colormap, :colorscale, :highclip, :lowclip, :nan_color, + :calculated_colors, :space, :markerspace, :model]) function cached_robj!(robj_func, screen, scene, plot::AbstractPlot) @@ -250,7 +250,7 @@ function cached_robj!(robj_func, screen, scene, plot::AbstractPlot) screen.requires_update = true end 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, plot, screen) @@ -281,7 +281,7 @@ function cached_robj!(robj_func, screen, scene, plot::AbstractPlot) if !isnothing(dirlight) gl_attributes[:light_direction] = if dirlight.camera_relative map(gl_attributes[:view], dirlight.direction) do view, dir - return normalize(inv(view[Vec(1,2,3), Vec(1,2,3)]) * dir) + return normalize(inv(view[Vec(1, 2, 3), Vec(1, 2, 3)]) * dir) end else map(normalize, dirlight.direction) @@ -290,14 +290,14 @@ function cached_robj!(robj_func, screen, scene, plot::AbstractPlot) gl_attributes[:light_color] = dirlight.color else gl_attributes[:light_direction] = Observable(Vec3f(0)) - gl_attributes[:light_color] = Observable(RGBf(0,0,0)) + gl_attributes[:light_color] = Observable(RGBf(0, 0, 0)) end ambientlight = Makie.get_ambient_light(scene) if !isnothing(ambientlight) gl_attributes[:ambient] = ambientlight.color else - gl_attributes[:ambient] = Observable(RGBf(0,0,0)) + gl_attributes[:ambient] = Observable(RGBf(0, 0, 0)) end elseif shading == MultiLightShading handle_lights(gl_attributes, screen, scene.lights) @@ -341,7 +341,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 @@ -375,7 +375,7 @@ end pixel2world(scene, msize::AbstractVector) = pixel2world.(scene, msize) -function draw_atomic(screen::Screen, scene::Scene, @nospecialize(plot::Union{Scatter, MeshScatter})) +function draw_atomic(screen::Screen, scene::Scene, @nospecialize(plot::Union{Scatter,MeshScatter})) return cached_robj!(screen, scene, plot) do gl_attributes # signals not supported for shading yet marker = pop!(gl_attributes, :marker) @@ -388,7 +388,7 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(plot::Union{Sca mspace = plot.markerspace cam = scene.camera gl_attributes[:preprojection] = lift(plot, space, mspace, cam.projectionview, - cam.resolution) do space, mspace, _, _ + cam.resolution) do space, mspace, _, _ return Makie.clip_to_space(cam, mspace) * Makie.space_to_clip(cam, space) end # fast pixel does its own setup @@ -411,7 +411,7 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(plot::Union{Sca return Makie.primitive_uv_offset_width(atlas, marker, font) end scale, quad_offset = Makie.marker_attributes(atlas, marker, gl_attributes[:scale], font, - gl_attributes[:quad_offset], plot) + gl_attributes[:quad_offset], plot) gl_attributes[:scale] = scale gl_attributes[:quad_offset] = quad_offset end @@ -427,7 +427,7 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(plot::Union{Sca return draw_pixel_scatter(screen, positions, gl_attributes) else if plot isa MeshScatter - if haskey(gl_attributes, :color) && to_value(gl_attributes[:color]) isa AbstractMatrix{<: Colorant} + if haskey(gl_attributes, :color) && to_value(gl_attributes[:color]) isa AbstractMatrix{<:Colorant} gl_attributes[:image] = gl_attributes[:color] end return draw_mesh_particle(screen, (marker, positions), gl_attributes) @@ -444,7 +444,7 @@ _mean(xs) = sum(xs) / length(xs) # skip Statistics import function draw_atomic(screen::Screen, scene::Scene, @nospecialize(plot::Lines)) return cached_robj!(screen, scene, plot) do gl_attributes linestyle = pop!(gl_attributes, :linestyle) - data = Dict{Symbol, Any}(gl_attributes) + data = Dict{Symbol,Any}(gl_attributes) positions = handle_view(plot[1], data) transform_func = transform_func_obs(plot) @@ -465,7 +465,7 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(plot::Lines)) pvm = lift(*, plot, data[:projectionview], data[:model]) positions = lift(plot, transform_func, positions, space, pvm, - data[:resolution]) do f, ps, space, pvm, res + data[:resolution]) do f, ps, space, pvm, res transformed = apply_transform(f, ps, space) output = Vector{Point3f}(undef, length(transformed)) scale = Vec3f(res[1], res[2], 1f0) @@ -483,7 +483,7 @@ end function draw_atomic(screen::Screen, scene::Scene, @nospecialize(plot::LineSegments)) return cached_robj!(screen, scene, plot) do gl_attributes linestyle = pop!(gl_attributes, :linestyle) - data = Dict{Symbol, Any}(gl_attributes) + data = Dict{Symbol,Any}(gl_attributes) px_per_unit = data[:px_per_unit] ls = to_value(linestyle) if isnothing(ls) @@ -508,7 +508,7 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(plot::LineSegme end function draw_atomic(screen::Screen, scene::Scene, - plot::Text{<:Tuple{<:Union{<:Makie.GlyphCollection, <:AbstractVector{<:Makie.GlyphCollection}}}}) + plot::Text{<:Tuple{<:Union{<:Makie.GlyphCollection,<:AbstractVector{<:Makie.GlyphCollection}}}}) return cached_robj!(screen, scene, plot) do gl_attributes glyphcollection = plot[1] @@ -618,7 +618,7 @@ function draw_atomic(screen::Screen, scene::Scene, plot::Heatmap) gl_attributes[:position_y] = Texture(ypos, minfilter = :nearest) # number of planes used to render the heatmap gl_attributes[:instances] = lift(plot, 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 @@ -626,7 +626,7 @@ function draw_atomic(screen::Screen, scene::Scene, plot::Heatmap) if intensity isa ShaderAbstractions.Sampler gl_attributes[:intensity] = to_value(intensity) else - gl_attributes[:intensity] = Texture(el32convert(intensity); minfilter=interp) + gl_attributes[:intensity] = Texture(el32convert(intensity); minfilter = interp) end return draw_heatmap(screen, gl_attributes) @@ -638,7 +638,7 @@ function draw_atomic(screen::Screen, scene::Scene, plot::Image) position = lift(plot, plot[1], plot[2]) do x, y xmin, xmax = extrema(x) ymin, ymax = extrema(y) - rect = Rect2f(xmin, ymin, xmax - xmin, ymax - ymin) + rect = Rect2f(xmin, ymin, xmax - xmin, ymax - ymin) return decompose(Point2f, rect) end gl_attributes[:vertices] = lift(apply_transform, plot, transform_func_obs(plot), position, plot.space) @@ -651,15 +651,15 @@ function draw_atomic(screen::Screen, scene::Scene, plot::Image) _interp = to_value(pop!(gl_attributes, :interpolate, true)) interp = _interp ? :linear : :nearest if haskey(gl_attributes, :intensity) - gl_attributes[:image] = Texture(pop!(gl_attributes, :intensity); minfilter=interp) + gl_attributes[:image] = Texture(pop!(gl_attributes, :intensity); minfilter = interp) else - gl_attributes[:image] = Texture(pop!(gl_attributes, :color); minfilter=interp) + gl_attributes[:image] = Texture(pop!(gl_attributes, :color); minfilter = interp) end return draw_mesh(screen, gl_attributes) end end -function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, plot, space=:data) +function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, plot, space = :data) # signals not supported for shading yet shading = to_value(gl_attributes[:shading])::Makie.MakieCore.ShadingAlgorithm matcap_active = !isnothing(to_value(get(gl_attributes, :matcap, nothing))) @@ -672,16 +672,16 @@ function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, plot, space= delete!(gl_attributes, :color_norm) elseif to_value(color) isa Makie.AbstractPattern img = lift(x -> el32convert(Makie.to_image(x)), plot, 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(lift(el32convert, plot, 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(lift(el32convert, plot, 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, plot, color) else # error("Unsupported color type: $(typeof(to_value(color)))") @@ -700,7 +700,7 @@ function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, plot, space= gl_attributes[:vertices] = lift(transfunc, mesh, space) do t, mesh, space apply_transform(t, metafree(coordinates(mesh)), space) end - gl_attributes[:faces] = lift(x-> decompose(GLTriangleFace, x), mesh) + gl_attributes[:faces] = lift(x -> decompose(GLTriangleFace, x), mesh) if hasproperty(to_value(mesh), :uv) gl_attributes[:texturecoordinates] = lift(decompose_uv, mesh) end @@ -730,12 +730,12 @@ function draw_atomic(screen::Screen, scene::Scene, plot::Surface) img = pop!(gl_attributes, :intensity) elseif to_value(color) isa Makie.AbstractPattern pattern_img = lift(x -> el32convert(Makie.to_image(x)), plot, 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 @@ -745,12 +745,12 @@ function draw_atomic(screen::Screen, scene::Scene, plot::Surface) space = plot.space interp = to_value(pop!(gl_attributes, :interpolate, true)) interp = interp ? :linear : :nearest - gl_attributes[:image] = Texture(img; minfilter=interp) + gl_attributes[:image] = Texture(img; minfilter = interp) @assert to_value(plot[3]) isa AbstractMatrix types = map(v -> typeof(to_value(v)), plot[1:2]) - if all(T -> T <: Union{AbstractMatrix, AbstractVector}, types) + if all(T -> T <: Union{AbstractMatrix,AbstractVector}, types) t = Makie.transform_func_obs(plot) mat = plot[3] xypos = lift(plot, t, plot[1], plot[2], space) do t, x, y, space @@ -771,7 +771,7 @@ function draw_atomic(screen::Screen, scene::Scene, plot::Surface) xpos = lift(first, plot, xypos) ypos = lift(last, plot, xypos) args = map((xpos, ypos, mat)) do arg - Texture(lift(x-> convert(Array, el32convert(x)), plot, arg); minfilter=:linear) + Texture(lift(x -> convert(Array, el32convert(x)), plot, arg); minfilter = :linear) end if isnothing(img) gl_attributes[:image] = args[3] @@ -779,7 +779,7 @@ function draw_atomic(screen::Screen, scene::Scene, plot::Surface) return draw_surface(screen, args, gl_attributes) else gl_attributes[:ranges] = to_range.(to_value.(plot[1:2])) - z_data = Texture(lift(el32convert, plot, plot[3]); minfilter=:linear) + z_data = Texture(lift(el32convert, plot, plot[3]); minfilter = :linear) if isnothing(img) gl_attributes[:image] = z_data end @@ -807,7 +807,7 @@ function draw_atomic(screen::Screen, scene::Scene, plot::Volume) end interp = to_value(pop!(gl_attributes, :interpolate)) interp = interp ? :linear : :nearest - Tex(x) = Texture(x; minfilter=interp) + Tex(x) = Texture(x; minfilter = interp) if haskey(gl_attributes, :intensity) intensity = pop!(gl_attributes, :intensity) return draw_volume(screen, Tex(intensity), gl_attributes) diff --git a/GLMakie/src/events.jl b/GLMakie/src/events.jl index 52f631095ce..7d5a355cb99 100644 --- a/GLMakie/src/events.jl +++ b/GLMakie/src/events.jl @@ -181,7 +181,7 @@ end struct MousePositionUpdater screen::Screen - mouseposition::Observable{Tuple{Float64, Float64}} + mouseposition::Observable{Tuple{Float64,Float64}} hasfocus::Observable{Bool} end @@ -228,7 +228,7 @@ which is an x and y offset. """ Makie.scroll(scene::Scene, screen) = scroll(scene, to_native(screen)) mutable struct ScrollUpdater <: Function - event::Observable{Tuple{Float64, Float64}} + event::Observable{Tuple{Float64,Float64}} integer_scroll::Bool end function (sc::ScrollUpdater)(window, w::Cdouble, h::Cdouble) diff --git a/GLMakie/src/gl_backend.jl b/GLMakie/src/gl_backend.jl index b8ed7a35dfd..c6d5a65e4c9 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 0fd7ccbaa05..7abcdef776c 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, data::Dict) - primitive = triangle_mesh(Rect2(0f0,0f0,1f0,1f0)) + primitive = triangle_mesh(Rect2(0f0, 0f0, 1f0, 1f0)) to_opengl_mesh!(data, primitive) pop!(data, :shading, FastShading) @gen_defaults! data begin @@ -81,9 +85,9 @@ function draw_volume(screen, main::VolumeTypes, data::Dict) "shading" => light_calc(shading), "MAX_LIGHTS" => "#define MAX_LIGHTS $(screen.config.max_lights)", "MAX_LIGHT_PARAMETERS" => "#define MAX_LIGHT_PARAMETERS $(screen.config.max_light_parameters)", - "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 562460de1f6..e1b97d31ebd 100644 --- a/GLMakie/src/glshaders/lines.jl +++ b/GLMakie/src/glshaders/lines.jl @@ -3,7 +3,7 @@ function sumlengths(points) result = zeros(T, length(points)) i12 = Vec(1, 2) for i in eachindex(points) - i0 = max(i-1, 1) + 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[i12] - p2[i12]) @@ -30,14 +30,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 @@ -56,12 +56,12 @@ function ticks(points, resolution) # so we need rescaling by ((resolution + 1) / resolution) scaled = ((resolution + 1) / resolution) .* points - r = range(first(scaled), stop=last(scaled), length=resolution+1)[1:end-1] - return Float16[gappy(x, scaled) for x = r] + r = range(first(scaled), stop = last(scaled), length = resolution + 1)[1:(end - 1)] + return Float16[gappy(x, scaled) for x in r] 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 @@ -69,26 +69,26 @@ 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 = nothing => GLBuffer - color_map = nothing => Texture - color_norm = nothing - thickness = 2f0 => GLBuffer - pattern = nothing - pattern_sections = pattern => Texture - fxaa = false + total_length::Int32 = const_lift(x -> Int32(length(x)), position) + vertex = p_vec => GLBuffer + intensity = nothing + color = nothing => GLBuffer + color_map = nothing => Texture + color_norm = nothing + thickness = 2f0 => GLBuffer + pattern = nothing + pattern_sections = pattern => Texture + 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 - fast = false - shader = GLVisualizeShader( + fast = false + shader = GLVisualizeShader( screen, "fragment_output.frag", "util.vert", "lines.vert", "lines.geom", "lines.frag", view = Dict( @@ -97,12 +97,12 @@ function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data:: "define_fast_path" => to_value(fast) ? "#define FAST_PATH" : "" ) ) - 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 - lastlen = const_lift(sumlengths, p_vec) => GLBuffer - pattern_length = 1f0 # we divide by pattern_length a lot. + lastlen = const_lift(sumlengths, p_vec) => GLBuffer + pattern_length = 1f0 # we divide by pattern_length a lot. end if to_value(pattern) !== nothing if !isa(pattern, Texture) @@ -119,21 +119,21 @@ 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 - fast = 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 + fast = false + indices = const_lift(length, positions) => to_index_buffer # TODO update boundingbox - transparency = false - shader = GLVisualizeShader( + transparency = false + shader = GLVisualizeShader( screen, "fragment_output.frag", "util.vert", "line_segment.vert", "line_segment.geom", "lines.frag", view = Dict( @@ -142,7 +142,7 @@ function draw_linesegments(screen, positions::VectorTypes{T}, data::Dict) where "define_fast_path" => to_value(fast) ? "#define FAST_PATH" : "" ) ) - gl_primitive = GL_LINES + gl_primitive = GL_LINES pattern_length = 1f0 end if !isa(pattern, Texture) && to_value(pattern) !== nothing diff --git a/GLMakie/src/glshaders/mesh.jl b/GLMakie/src/glshaders/mesh.jl index 877ddf90dea..fdc29a61930 100644 --- a/GLMakie/src/glshaders/mesh.jl +++ b/GLMakie/src/glshaders/mesh.jl @@ -1,9 +1,9 @@ -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[:faces] = indexbuffer(map(((m, _),) -> faces(m), m_attr)) result[:vertices] = GLBuffer(map(((m, _),) -> metafree(coordinates(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 b0066970c23..8e6b558a8de 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 @@ -103,13 +103,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 = nothing => GLBuffer - color_norm = nothing - scale = 2f0 + vertex = position => GLBuffer + color_map = nothing => Texture + color = nothing => GLBuffer + color_norm = nothing + scale = 2f0 transparency = false - shader = GLVisualizeShader( + shader = GLVisualizeShader( screen, "fragment_output.frag", "dots.vert", "dots.frag", view = Dict( @@ -124,29 +124,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 @@ -191,17 +191,17 @@ function draw_scatter(screen, (marker, position), data) end @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 data[:shape] = map( - convert(Observable{Int}, pop!(data, :shape)), data[:scale] - ) do shape, scale + convert(Observable{Int}, pop!(data, :shape)), data[:scale] + ) do shape, scale if shape == 0 && !is_all_equal_scale(scale) return Cint(5) # scaled CIRCLE -> ELLIPSE else @@ -210,25 +210,25 @@ function draw_scatter(screen, (marker, position), data) 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 ef7810a96f8..ba403f4e564 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) @@ -25,7 +25,7 @@ function light_calc(x::Makie.MakieCore.ShadingAlgorithm) return "#define FAST_SHADING" elseif x === MultiLightShading return "#define MULTI_LIGHT_SHADING" - # elseif x === :PBR # TODO? + # elseif x === :PBR # TODO? else @warn "Did not recognize shading value :$x. Defaulting to FastShading." return "#define FAST_SHADING" @@ -33,8 +33,8 @@ function light_calc(x::Makie.MakieCore.ShadingAlgorithm) 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); @@ -49,9 +49,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); @@ -66,23 +66,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); @@ -95,7 +95,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}`") @@ -106,7 +106,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}`") @@ -117,7 +117,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) shading = pop!(data, :shading, FastShading)::Makie.MakieCore.ShadingAlgorithm @gen_defaults! data begin @@ -143,7 +143,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 d9236e4f61c..a4fd70d369d 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 7901b34c074..bafd33b74ab 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 @@ -86,7 +86,7 @@ function check_framebuffer() return enum_to_error(status) 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) @@ -98,7 +98,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( @@ -130,14 +130,14 @@ 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{Symbol,GLuint}( - :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{Symbol, Texture}( + buffers = Dict{Symbol,Texture}( :color => color_buffer, :objectid => objectid_buffer, :HDR_color => HDR_color_buffer, @@ -166,22 +166,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 ab718ba7bcc..137044fd438 100644 --- a/GLMakie/src/picking.jl +++ b/GLMakie/src/picking.jl @@ -24,7 +24,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) fb = screen.framebuffer @@ -43,7 +43,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] @@ -72,14 +72,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 @@ -99,20 +100,21 @@ function Makie.pick_sorted(scene::Scene, screen::Screen, xy, range) isopen(screen) || return (nothing, 0) w, h = size(scene) 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 idx = findfirst(isequal(picks[i, j]), selected) if idx === nothing continue diff --git a/GLMakie/src/postprocessing.jl b/GLMakie/src/postprocessing.jl index 60c978e07cf..6970b3be53d 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], @@ -208,7 +208,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 @@ -222,7 +222,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] ) @@ -235,7 +235,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), ) @@ -279,7 +279,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/precompiles.jl b/GLMakie/src/precompiles.jl index d2bd372aa14..3900625ca1f 100644 --- a/GLMakie/src/precompiles.jl +++ b/GLMakie/src/precompiles.jl @@ -26,7 +26,7 @@ let shared_precompile = joinpath(base_path, "shared-precompile.jl") include(shared_precompile) try - display(plot(x); visible=false) + display(plot(x); visible = false) catch end Makie.CURRENT_FIGURE[] = nothing @@ -37,13 +37,13 @@ let close(screen) destroy!(screen) - config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol, Any}()) - screen = Screen(Scene(), config, nothing, MIME"image/png"(); visible=false, start_renderloop=false) + config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol,Any}()) + screen = Screen(Scene(), config, nothing, MIME"image/png"(); visible = false, start_renderloop = false) close(screen) config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol,Any}()) - screen = Screen(Scene(), config; visible=false, start_renderloop=false) + screen = Screen(Scene(), config; visible = false, start_renderloop = false) close(screen) empty!(atlas_texture_cache) @@ -63,7 +63,7 @@ precompile(glTexImage, (GLenum, Int, GLenum, Int, Int, Int, GLenum, GLenum, Ptr{ precompile(glTexImage, (GLenum, Int, GLenum, Int, Int, Int, GLenum, GLenum, Ptr{RGBf})) precompile(glTexImage, (GLenum, Int, GLenum, Int, Int, Int, GLenum, GLenum, Ptr{RGBA{N0f8}})) precompile(glTexImage, - (GLenum, Int, GLenum, Int, Int, Int, GLenum, GLenum, Ptr{GLAbstraction.DepthStencil_24_8})) + (GLenum, Int, GLenum, Int, Int, Int, GLenum, GLenum, Ptr{GLAbstraction.DepthStencil_24_8})) precompile(glTexImage, (GLenum, Int, GLenum, Int, Int, Int, GLenum, GLenum, Ptr{Vec{2,GLuint}})) precompile(glTexImage, (GLenum, Int, GLenum, Int, Int, Int, GLenum, GLenum, Ptr{RGBA{Float16}})) precompile(glTexImage, (GLenum, Int, GLenum, Int, Int, Int, GLenum, GLenum, Ptr{N0f8})) diff --git a/GLMakie/src/rendering.jl b/GLMakie/src/rendering.jl index dda559f5ec3..7e134c79b33 100644 --- a/GLMakie/src/rendering.jl +++ b/GLMakie/src/rendering.jl @@ -26,7 +26,7 @@ end """ 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 8133ed61ed1..4b6879efcb5 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 @@ -46,7 +46,7 @@ mutable struct ScreenConfig vsync::Bool render_on_demand::Bool framerate::Float64 - px_per_unit::Union{Nothing, Float32} + px_per_unit::Union{Nothing,Float32} # GLFW window attributes float::Bool @@ -55,9 +55,9 @@ mutable struct ScreenConfig title::String fullscreen::Bool debugging::Bool - monitor::Union{Nothing, GLFW.Monitor} + monitor::Union{Nothing,GLFW.Monitor} visible::Bool - scalefactor::Union{Nothing, Float32} + scalefactor::Union{Nothing,Float32} # Render Constants & Postprocessor oit::Bool @@ -68,31 +68,31 @@ mutable struct ScreenConfig max_light_parameters::Int function ScreenConfig( - # Renderloop - renderloop::Union{Makie.Automatic, Function}, - pause_renderloop::Bool, - vsync::Bool, - render_on_demand::Bool, - framerate::Number, - px_per_unit::Union{Makie.Automatic, Number}, - # GLFW window attributes - float::Bool, - focus_on_show::Bool, - decorated::Bool, - title::AbstractString, - fullscreen::Bool, - debugging::Bool, - monitor::Union{Nothing, GLFW.Monitor}, - visible::Bool, - scalefactor::Union{Makie.Automatic, Number}, - - # Preprocessor - oit::Bool, - fxaa::Bool, - ssao::Bool, - transparency_weight_scale::Number, - max_lights::Int, - max_light_parameters::Int) + # Renderloop + renderloop::Union{Makie.Automatic,Function}, + pause_renderloop::Bool, + vsync::Bool, + render_on_demand::Bool, + framerate::Number, + px_per_unit::Union{Makie.Automatic,Number}, + # GLFW window attributes + float::Bool, + focus_on_show::Bool, + decorated::Bool, + title::AbstractString, + fullscreen::Bool, + debugging::Bool, + monitor::Union{Nothing,GLFW.Monitor}, + visible::Bool, + scalefactor::Union{Makie.Automatic,Number}, + + # Preprocessor + oit::Bool, + fxaa::Bool, + ssao::Bool, + transparency_weight_scale::Number, + max_lights::Int, + max_light_parameters::Int) return new( # Renderloop renderloop isa Makie.Automatic ? GLMakie.renderloop : renderloop, @@ -122,7 +122,7 @@ mutable struct ScreenConfig end end -const LAST_INLINE = Ref{Union{Makie.Automatic, Bool}}(false) +const LAST_INLINE = Ref{Union{Makie.Automatic,Bool}}(false) """ GLMakie.activate!(; screen_config...) @@ -134,7 +134,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 @@ -160,44 +160,42 @@ 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} px_per_unit::Observable{Float32} - 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} # listeners must not Consume(true) window_open::Observable{Bool} scalefactor::Observable{Float32} - 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}( @@ -219,22 +217,18 @@ Makie.isvisible(screen::Screen) = screen.config.visible # 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.SCALE_TO_MONITOR, true), + (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.SCALE_TO_MONITOR, true), ] resolution = (10, 10) window = try @@ -275,12 +269,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, refreshwindowcb(screen)) @@ -322,11 +316,11 @@ function singleton_screen(debugging::Bool) if !isempty(SINGLETON_SCREEN) @debug("reusing singleton screen") screen = SINGLETON_SCREEN[1] - close(screen; reuse=false) + close(screen; reuse = false) else @debug("new singleton screen") # reuse=false, because we "manually" re-use the singleton screen! - screen = empty_screen(debugging; reuse=false) + screen = empty_screen(debugging; reuse = false) push!(SINGLETON_SCREEN, screen) end return reopen!(screen) @@ -336,7 +330,7 @@ function Makie.apply_screen_config!(screen::Screen, config::ScreenConfig, scene: apply_config!(screen, config) end -function apply_config!(screen::Screen, config::ScreenConfig; start_renderloop::Bool=true) +function apply_config!(screen::Screen, config::ScreenConfig; start_renderloop::Bool = true) @debug("Applying screen config! to existing screen") glw = screen.glscreen ShaderAbstractions.switch_context!(glw) @@ -382,14 +376,14 @@ function apply_config!(screen::Screen, config::ScreenConfig; start_renderloop::B end function Screen(; - resolution::Union{Nothing, Tuple{Int, Int}} = nothing, - start_renderloop = true, - screen_config... - ) + resolution::Union{Nothing,Tuple{Int,Int}} = nothing, + start_renderloop = true, + screen_config... +) # Screen config is managed by the current active theme, so managed by Makie - config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol, Any}(screen_config)) + config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol,Any}(screen_config)) screen = screen_from_pool(config.debugging) - apply_config!(screen, config; start_renderloop=start_renderloop) + apply_config!(screen, config; start_renderloop = start_renderloop) if !isnothing(resolution) resize!(screen, resolution...) end @@ -412,34 +406,34 @@ function display_scene!(screen::Screen, scene::Scene) return end -function Screen(scene::Scene; start_renderloop=true, screen_config...) - config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol, Any}(screen_config)) - return Screen(scene, config; start_renderloop=start_renderloop) +function Screen(scene::Scene; start_renderloop = true, screen_config...) + config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol,Any}(screen_config)) + return Screen(scene, config; start_renderloop = start_renderloop) end # Open an interactive window -function Screen(scene::Scene, config::ScreenConfig; visible=nothing, start_renderloop=true) +function Screen(scene::Scene, config::ScreenConfig; visible = nothing, start_renderloop = true) screen = singleton_screen(config.debugging) !isnothing(visible) && (config.visible = visible) - apply_config!(screen, config; start_renderloop=start_renderloop) + apply_config!(screen, config; 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=nothing, start_renderloop=false) +function Screen(scene::Scene, config::ScreenConfig, io::Union{Nothing,String,IO}, typ::MIME; visible = nothing, start_renderloop = false) screen = singleton_screen(config.debugging) !isnothing(visible) && (config.visible = visible) - apply_config!(screen, config; start_renderloop=start_renderloop) + apply_config!(screen, config; 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; start_renderloop=false) +function Screen(scene::Scene, config::ScreenConfig, ::Makie.ImageStorageFormat; start_renderloop = false) screen = singleton_screen(config.debugging) config.visible = false - apply_config!(screen, config; start_renderloop=start_renderloop) + apply_config!(screen, config; start_renderloop = start_renderloop) display_scene!(screen, scene) return screen end @@ -497,7 +491,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 @@ -556,7 +550,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)) @@ -596,7 +590,7 @@ end function destroy!(screen::Screen) @debug("Destroy 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) @@ -620,10 +614,10 @@ end Closes screen and empties it. Doesn't destroy the screen and instead frees it to be re-used again, if `reuse=true`. """ -function Base.close(screen::Screen; reuse=true) +function Base.close(screen::Screen; reuse = true) @debug("Close screen!") set_screen_visibility!(screen, false) - stop_renderloop!(screen; close_after_renderloop=false) + stop_renderloop!(screen; close_after_renderloop = false) if screen.window_open[] # otherwise we trigger an infinite loop of closing screen.window_open[] = false end @@ -683,7 +677,7 @@ function Base.resize!(screen::Screen, w::Int, h::Int) return nothing 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) @@ -709,7 +703,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)) @@ -729,7 +723,7 @@ function Makie.colorbuffer(screen::Screen, format::Makie.ImageStorageFormat = Ma # we still need to poll though, to get all the newest events! pollevents(screen) # 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 if screen.config.visible GLFW.SwapBuffers(to_native(screen)) else @@ -837,7 +831,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 @@ -855,7 +849,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 @@ -890,7 +884,8 @@ scalechangeobs(screen) = scalefactor -> scalechangeobs(screen, scalefactor) 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 @@ -903,7 +898,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 @@ -969,7 +965,7 @@ 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 @@ -977,7 +973,7 @@ function renderloop(screen) @debug("Closing screen after quiting renderloop!") 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 @@ -986,7 +982,7 @@ end function plot2robjs(screen::Screen, plot) plots = Makie.collect_atomic_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 7aadbc3fa4b..df3c9622b2e 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 @@ -81,9 +81,9 @@ end glFinish() end end - fig, ax, meshplot = meshscatter(RNG.rand(Point3f, 10^4) .* 20f0; color=:black) - screen = display(GLMakie.Screen(;renderloop=(screen) -> nothing, start_renderloop=false), fig.scene) - buff = RNG.rand(Point3f, 10^4) .* 20f0; + fig, ax, meshplot = meshscatter(RNG.rand(Point3f, 10^4) .* 20f0; color = :black) + 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,11 +96,11 @@ 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) - mesh!(left, Sphere(Point3f(5), 6f0), color=:black) + 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), color = :black) 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) - mesh!(right, Sphere(Point3f(5), 6.0f0); color=:black) + mesh!(right, Sphere(Point3f(5), 6.0f0); color = :black) fig end @@ -108,13 +108,13 @@ end angle2pos(phi) = Point3f(cosd(phi), sind(phi), 0) lights = [ AmbientLight(RGBf(0.1, 0.1, 0.1)), - SpotLight(RGBf(2,0,0), angle2pos(0), Vec3f(0, 0, -1), Vec2f(pi/5, pi/4)), - SpotLight(RGBf(0,2,0), angle2pos(120), Vec3f(0, 0, -1), Vec2f(pi/5, pi/4)), - SpotLight(RGBf(0,0,2), angle2pos(240), Vec3f(0, 0, -1), Vec2f(pi/5, pi/4)), - PointLight(RGBf(1,1,1), Point3f(-4, -4, -2.5), 10.0), - PointLight(RGBf(1,1,0), Point3f(-4, 4, -2.5), 10.0), - PointLight(RGBf(1,0,1), Point3f( 4, 4, -2.5), 10.0), - PointLight(RGBf(0,1,1), Point3f( 4, -4, -2.5), 10.0), + SpotLight(RGBf(2, 0, 0), angle2pos(0), Vec3f(0, 0, -1), Vec2f(pi / 5, pi / 4)), + SpotLight(RGBf(0, 2, 0), angle2pos(120), Vec3f(0, 0, -1), Vec2f(pi / 5, pi / 4)), + SpotLight(RGBf(0, 0, 2), angle2pos(240), Vec3f(0, 0, -1), Vec2f(pi / 5, pi / 4)), + PointLight(RGBf(1, 1, 1), Point3f(-4, -4, -2.5), 10.0), + PointLight(RGBf(1, 1, 0), Point3f(-4, 4, -2.5), 10.0), + PointLight(RGBf(1, 0, 1), Point3f(4, 4, -2.5), 10.0), + PointLight(RGBf(0, 1, 1), Point3f(4, -4, -2.5), 10.0), ] scene = Scene(size = (400, 400), camera = cam3d!, lights = lights) @@ -132,9 +132,9 @@ end angle2dir(phi) = Vec3f(cosd(phi), sind(phi), -2) lights = [ AmbientLight(RGBf(0.1, 0.1, 0.1)), - DirectionalLight(RGBf(1,0,0), angle2dir(0)), - DirectionalLight(RGBf(0,1,0), angle2dir(120)), - DirectionalLight(RGBf(0,0,1), angle2dir(240)), + DirectionalLight(RGBf(1, 0, 0), angle2dir(0)), + DirectionalLight(RGBf(0, 1, 0), angle2dir(120)), + DirectionalLight(RGBf(0, 0, 1), angle2dir(240)), ] scene = Scene(size = (400, 400), camera = cam3d!, center = false, lights = lights, backgroundcolor = :black) @@ -151,8 +151,8 @@ end lights = Makie.AbstractLight[ RectLight(RGBf(0.5, 0, 0), Point3f(-0.5, -1, 2), Vec3f(3, 0, 0), Vec3f(0, 3, 0)), RectLight(RGBf(0, 0.5, 0), Rect2f(-1, 1, 1, 3)), - RectLight(RGBf(0, 0, 0.5), Point3f( 1, 0.5, 2), Vec3f(3, 0, 0), Vec3f(0, 3, 0)), - RectLight(RGBf(0.5, 0.5, 0.5), Point3f( 1, -1, 2), Vec3f(3, 0, 0), Vec3f(0, 3, 0), Vec3f(-0.3, 0.3, -1)), + RectLight(RGBf(0, 0, 0.5), Point3f(1, 0.5, 2), Vec3f(3, 0, 0), Vec3f(0, 3, 0)), + RectLight(RGBf(0.5, 0.5, 0.5), Point3f(1, -1, 2), Vec3f(3, 0, 0), Vec3f(0, 3, 0), Vec3f(-0.3, 0.3, -1)), ] # Test transformations translate!(lights[2], Vec3f(-1, 1, 2)) # translate to by default @@ -171,7 +171,7 @@ end # scatter/text shader xs = 20:20:280 ys = fill(170, length(xs)) - zs = range(3, 1, length=length(xs)) + zs = range(3, 1, length = length(xs)) scatter!(scene, xs, ys, zs, color = :blue, markersize = 40, fxaa = false) ys = fill(130, length(xs)) scatter!(scene, xs, ys, zs, color = :blue, markersize = 40, fxaa = true) @@ -181,7 +181,7 @@ end # lines/linesegments shader xs = 20:10:270 ys = [50 + shift for _ in 1:13 for shift in (-10, 10)] - zs = range(3, 1, length=length(xs)) + zs = range(3, 1, length = length(xs)) lines!(scene, xs, ys, zs, color = :blue, linewidth = 4, fxaa = false) ys = [20 + shift for _ in 1:13 for shift in (-10, 10)] lines!(scene, xs, ys, zs, color = :blue, linewidth = 4, fxaa = true) @@ -190,4 +190,4 @@ end mesh!(scene, Rect2f(0, 0, 300, 200), color = :red) scene -end \ No newline at end of file +end diff --git a/GLMakie/test/runtests.jl b/GLMakie/test/runtests.jl index 98e30bc505c..189462fc9c3 100644 --- a/GLMakie/test/runtests.jl +++ b/GLMakie/test/runtests.jl @@ -11,7 +11,7 @@ if !GLMakie.ModernGL.enable_opengl_debugging @warn("TESTING WITHOUT OPENGL DEBUGGING") end -GLMakie.activate!(framerate=1.0, scalefactor=1.0) +GLMakie.activate!(framerate = 1.0, scalefactor = 1.0) @testset "mimes" begin Makie.inline!(true) diff --git a/GLMakie/test/unit_tests.jl b/GLMakie/test/unit_tests.jl index 726f4b90705..af15fa6f3e3 100644 --- a/GLMakie/test/unit_tests.jl +++ b/GLMakie/test/unit_tests.jl @@ -63,7 +63,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]) @@ -92,11 +92,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 @@ -107,25 +107,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) @@ -136,10 +136,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) @test screen in fig.scene.current_screens @@ -154,10 +154,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 @@ -175,15 +175,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) @@ -198,8 +198,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 @@ -220,7 +220,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() @@ -231,11 +231,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 @@ -253,23 +253,23 @@ end GLMakie.closeall() set_theme!() screens = map(1:10) do i - fig = Figure(size=(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(size = (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, scalefactor=1), fig) + display(GLMakie.Screen(visible = false, scalefactor = 1), 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 > 60 foreach(close, screens) @@ -293,7 +293,7 @@ end @test (Base.summarysize(screen) / 10^6) < 1.4 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 @@ -307,9 +307,9 @@ end W, H = 400, 400 N = 51 - x = collect(range(0.0, 2π, length=N)) + x = collect(range(0.0, 2π, length = N)) y = sin.(x) - fig, ax, pl = scatter(x, y, figure = (; size = (W, H))); + fig, ax, pl = scatter(x, y, figure = (; size = (W, H))) hidedecorations!(ax) # On OSX, the native window size has an underlying scale factor that we need to account @@ -330,7 +330,7 @@ end # check that picking works through the resized GL buffers GLMakie.Makie.colorbuffer(screen) # force render # - point pick - point_px = project_sp(ax.scene, Point2f(x[end÷2], y[end÷2])) + point_px = project_sp(ax.scene, Point2f(x[end ÷ 2], y[end ÷ 2])) elem, idx = pick(ax.scene, point_px) @test elem === pl @test idx == length(x) ÷ 2 @@ -340,7 +340,7 @@ end quadrant = Rect2i(round.(bottom_px)..., round.(right_px - bottom_px)...) picks = pick(ax.scene, quadrant) points = Set(Int(p[2]) for p in picks if p[1] isa Scatter) - @test points == Set(((N+1)÷2):N) + @test points == Set(((N + 1) ÷ 2):N) # render at lower resolution screen = display(GLMakie.Screen(visible = false, scalefactor = 2, px_per_unit = 1), fig) @@ -360,7 +360,7 @@ end # save at current size @test screen.px_per_unit[] == 1 - save(file, fig; px_per_unit=1) + save(file, fig; px_per_unit = 1) img = load(file) @test size(img) == (W, H) # save with a different resolution @@ -370,7 +370,7 @@ end # writing to file should not effect the visible figure @test_broken screen.px_per_unit[] == 1 # Make sure switching back resizes the screen correctly! - save(file, fig; px_per_unit=1) + save(file, fig; px_per_unit = 1) img = load(file) @test size(img) == (W, H) end @@ -436,7 +436,7 @@ end @testset "image size changes" begin s = Scene() - im = image!(s, 0..10, 0..10, zeros(RGBf, 10, 20)) + im = image!(s, 0 .. 10, 0 .. 10, zeros(RGBf, 10, 20)) display(s) im[3][] = zeros(RGBf, 20, 10) # same length, different size im[3][] = zeros(RGBf, 15, 5) # smaller size @@ -445,21 +445,21 @@ end end @testset "Verify camera uniforms after delete" begin - f=Figure(size=(200,200)) + f = Figure(size = (200, 200)) screen = display(f, visible = false) - ax=Axis(f[1,1]) - lines!(ax,sin.(0.0:0.1:2pi)) - text!(ax,10.0,0.0,text="sine wave") + ax = Axis(f[1, 1]) + lines!(ax, sin.(0.0:0.1:(2pi))) + text!(ax, 10.0, 0.0, text = "sine wave") empty!(ax) ids = [robj.id for (_, _, robj) in screen.renderlist] - lines!(ax, sin.(0.0:0.1:2pi)) - text!(ax,10.0,0.0,text="sine wave") + lines!(ax, sin.(0.0:0.1:(2pi))) + text!(ax, 10.0, 0.0, text = "sine wave") resize!(current_figure(), 800, 800) robj = filter(x -> !(x.id in ids), last.(screen.renderlist))[1] cam = ax.scene.camera - @test robj.uniforms[:resolution][] == screen.px_per_unit[] * cam.resolution[] + @test robj.uniforms[:resolution][] == screen.px_per_unit[] * cam.resolution[] @test robj.uniforms[:projectionview][] == cam.projectionview[] -end \ No newline at end of file +end diff --git a/MakieCore/src/attributes.jl b/MakieCore/src/attributes.jl index aecc9cedfc2..270927f612f 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,13 +22,13 @@ 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::Dict) = Attributes(Dict{Symbol, Observable}(node_pairs(pairs))) -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::Dict) = Attributes(Dict{Symbol,Observable}(node_pairs(pairs))) +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) @@ -79,7 +79,7 @@ end Base.merge(target::Attributes, args::Attributes...) = merge!(copy(target), args...) -function Base.getproperty(x::Union{Attributes, AbstractPlot}, key::Symbol) +function Base.getproperty(x::Union{Attributes,AbstractPlot}, key::Symbol) if hasfield(typeof(x), key) getfield(x, key) else @@ -94,7 +94,7 @@ function Base.setindex!(x::Attributes, value::NamedTuple, key::Symbol) return x[key] = Attributes(value) end -function Base.setproperty!(x::Union{Attributes, AbstractPlot}, key::Symbol, value) +function Base.setproperty!(x::Union{Attributes,AbstractPlot}, key::Symbol, value) if hasfield(typeof(x), key) setfield!(x, key, value) else @@ -133,7 +133,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) @@ -167,7 +167,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) @@ -180,9 +180,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" @@ -248,7 +248,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 @@ -280,6 +280,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 326657fb33e..6b4de5c9b5a 100644 --- a/MakieCore/src/basic_plots.jl +++ b/MakieCore/src/basic_plots.jl @@ -183,11 +183,7 @@ $(Base.Docs.doc(colormap_attributes!)) $(Base.Docs.doc(MakieCore.generic_plot_attributes!)) """ @recipe(Heatmap, x, y, values) do scene - attr = Attributes(; - - interpolate = false, - - linewidth = 0.0, + attr = Attributes(; interpolate = false, linewidth = 0.0, fxaa = true, ) generic_plot_attributes!(attr) @@ -223,9 +219,7 @@ $(Base.Docs.doc(colormap_attributes!)) $(Base.Docs.doc(MakieCore.generic_plot_attributes!)) """ @recipe(Volume, x, y, z, volume) do scene - attr = Attributes(; - - algorithm = :mip, + attr = Attributes(; algorithm = :mip, isovalue = 0.5, isorange = 0.05, interpolate = true, @@ -259,9 +253,7 @@ $(Base.Docs.doc(MakieCore.generic_plot_attributes!)) @recipe(Surface, x, y, z) do scene attr = Attributes(; color = nothing, - invert_normals = false, - - fxaa = true, + invert_normals = false, fxaa = true, ) shading_attributes!(attr) generic_plot_attributes!(attr) @@ -292,16 +284,12 @@ $(Base.Docs.doc(colormap_attributes!)) $(Base.Docs.doc(MakieCore.generic_plot_attributes!)) """ @recipe(Lines, positions) do scene - attr = Attributes(; - - color = theme(scene, :linecolor), - linewidth = theme(scene, :linewidth), - - linestyle = nothing, + attr = Attributes(; color = theme(scene, :linecolor), + linewidth = theme(scene, :linewidth), linestyle = nothing, fxaa = false, cycle = [:color], ) - generic_plot_attributes!(attr, ) + generic_plot_attributes!(attr,) return colormap_attributes!(attr, theme(scene, :colormap)) end @@ -358,9 +346,7 @@ $(Base.Docs.doc(MakieCore.generic_plot_attributes!)) @recipe(Mesh, mesh) do scene attr = Attributes(; color = :black, - interpolate = true, - - fxaa = true, + interpolate = true, fxaa = true, cycle = [:color => :patchcolor], ) shading_attributes!(attr) @@ -398,25 +384,15 @@ $(Base.Docs.doc(MakieCore.generic_plot_attributes!)) """ @recipe(Scatter, positions) do scene attr = Attributes(; - color = theme(scene, :markercolor), - - marker = theme(scene, :marker), - markersize = theme(scene, :markersize), - - strokecolor = theme(scene, :markerstrokecolor), + color = theme(scene, :markercolor), marker = theme(scene, :marker), + markersize = theme(scene, :markersize), strokecolor = theme(scene, :markerstrokecolor), strokewidth = theme(scene, :markerstrokewidth), glowcolor = (:black, 0.0), - glowwidth = 0.0, - - rotations = Billboard(), - marker_offset = automatic, - - transform_marker = false, # Applies the plots transformation to marker + glowwidth = 0.0, rotations = Billboard(), + marker_offset = automatic, transform_marker = false, # Applies the plots transformation to marker distancefield = nothing, uv_offset_width = (0.0, 0.0, 0.0, 0.0), - markerspace = :pixel, - - fxaa = false, + markerspace = :pixel, fxaa = false, cycle = [:color], ) generic_plot_attributes!(attr) @@ -450,14 +426,10 @@ $(Base.Docs.doc(MakieCore.generic_plot_attributes!)) """ @recipe(MeshScatter, positions) do scene attr = Attributes(; - color = theme(scene, :markercolor), - - marker = :Sphere, + color = theme(scene, :markercolor), marker = :Sphere, markersize = 0.1, rotations = 0.0, - space = :data, - - fxaa = true, + space = :data, fxaa = true, cycle = [:color], ) shading_attributes!(attr) @@ -498,12 +470,8 @@ $(Base.Docs.doc(MakieCore.generic_plot_attributes!)) """ @recipe(Text, positions) do scene attr = Attributes(; - color = theme(scene, :textcolor), - - font = theme(scene, :font), - fonts = theme(scene, :fonts), - - strokecolor = (:black, 0.0), + color = theme(scene, :textcolor), font = theme(scene, :font), + fonts = theme(scene, :fonts), strokecolor = (:black, 0.0), strokewidth = 0, align = (:left, :bottom), rotation = 0.0, @@ -555,17 +523,11 @@ $(Base.Docs.doc(MakieCore.generic_plot_attributes!)) """ @recipe(Poly) do scene attr = Attributes(; - color = theme(scene, :patchcolor), - - strokecolor = theme(scene, :patchstrokecolor), + color = theme(scene, :patchcolor), strokecolor = theme(scene, :patchstrokecolor), strokecolormap = theme(scene, :colormap), strokewidth = theme(scene, :patchstrokewidth), - linestyle = nothing, - - shading = NoShading, - fxaa = true, - - cycle = [:color => :patchcolor], + linestyle = nothing, shading = NoShading, + fxaa = true, cycle = [:color => :patchcolor], ) generic_plot_attributes!(attr) return colormap_attributes!(attr, theme(scene, :colormap)) @@ -580,22 +542,12 @@ end @recipe(Arrows, points, directions) do scene attr = Attributes( - color = :black, - - arrowsize = automatic, + color = :black, arrowsize = automatic, arrowhead = automatic, - arrowtail = automatic, - - linecolor = automatic, + arrowtail = automatic, linecolor = automatic, linestyle = nothing, - align = :origin, - - normalize = false, - lengthscale = 1f0, - - colorscale = identity, - - quality = 32, + align = :origin, normalize = false, + lengthscale = 1f0, colorscale = identity, quality = 32, markerspace = :pixel, ) diff --git a/MakieCore/src/conversion.jl b/MakieCore/src/conversion.jl index 2b2b9635d2d..138467e6e96 100644 --- a/MakieCore/src/conversion.jl +++ b/MakieCore/src/conversion.jl @@ -23,7 +23,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 @@ -40,8 +40,8 @@ Plots with the `PointBased` trait convert their input data to a `Vector{Point{D, Float32}}`. """ struct PointBased <: ConversionTrait end -conversion_trait(::Type{<: XYBased}) = PointBased() -conversion_trait(::Type{<: Text}) = PointBased() +conversion_trait(::Type{<:XYBased}) = PointBased() +conversion_trait(::Type{<:Text}) = PointBased() """ GridBased <: ConversionTrait @@ -67,7 +67,7 @@ See also: [`CellGrid`](@ref), [`ImageLike`](@ref) Used for: Surface """ struct VertexGrid <: GridBased end -conversion_trait(::Type{<: Surface}) = VertexGrid() +conversion_trait(::Type{<:Surface}) = VertexGrid() """ CellGrid() <: GridBased <: ConversionTrait @@ -81,7 +81,7 @@ See also: [`VertexGrid`](@ref), [`ImageLike`](@ref) Used for: Heatmap """ struct CellGrid <: GridBased end -conversion_trait(::Type{<: Heatmap}) = CellGrid() +conversion_trait(::Type{<:Heatmap}) = CellGrid() """ ImageLike() <: ConversionTrait @@ -94,9 +94,9 @@ See also: [`CellGrid`](@ref), [`VertexGrid`](@ref) Used for: Image """ struct ImageLike <: ConversionTrait end -conversion_trait(::Type{<: Image}) = ImageLike() +conversion_trait(::Type{<:Image}) = ImageLike() # Rect2f(xmin, ymin, xmax, ymax) 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 2e31672853c..9383e644e72 100644 --- a/MakieCore/src/recipes.jl +++ b/MakieCore/src/recipes.jl @@ -5,26 +5,26 @@ 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(::Plot{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) = Plot{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 plotkey(any) = nothing -argtypes(::T) where {T <: Tuple} = T +argtypes(::T) where {T<:Tuple} = T function create_axis_like end function create_axis_like! end @@ -36,8 +36,8 @@ function _create_plot! end -plot(args...; kw...) = _create_plot(plot, Dict{Symbol, Any}(kw), args...) -plot!(args...; kw...) = _create_plot!(plot, Dict{Symbol, Any}(kw), args...) +plot(args...; kw...) = _create_plot(plot, Dict{Symbol,Any}(kw), args...) +plot!(args...; kw...) = _create_plot!(plot, Dict{Symbol,Any}(kw), args...) """ Each argument can be named for a certain plot type `P`. Falls back to `arg1`, `arg2`, etc. @@ -54,8 +54,8 @@ end # Since we can use Plot like a scene in some circumstances, we define this alias theme(x::SceneLike, args...) = theme(x.parent, args...) theme(x::AbstractScene) = x.theme -theme(x::AbstractScene, key; default=nothing) = deepcopy(get(x.theme, key, default)) -theme(x::AbstractPlot, key; default=nothing) = deepcopy(get(x.attributes, key, default)) +theme(x::AbstractScene, key; default = nothing) = deepcopy(get(x.theme, key, default)) +theme(x::AbstractPlot, key; default = nothing) = deepcopy(get(x.attributes, key, default)) Attributes(x::AbstractPlot) = x.attributes @@ -172,8 +172,8 @@ macro recipe(theme_func, Tsym::Symbol, args::Symbol...) $(funcname)() = not_implemented_for($funcname) const $(PlotType){$(esc(:ArgType))} = Plot{$funcname,$(esc(:ArgType))} $(MakieCore).plotsym(::Type{<:$(PlotType)}) = $(QuoteNode(Tsym)) - Core.@__doc__ ($funcname)(args...; kw...) = _create_plot($funcname, Dict{Symbol, Any}(kw), args...) - ($funcname!)(args...; kw...) = _create_plot!($funcname, Dict{Symbol, Any}(kw), args...) + Core.@__doc__ ($funcname)(args...; kw...) = _create_plot($funcname, Dict{Symbol,Any}(kw), args...) + ($funcname!)(args...; kw...) = _create_plot!($funcname, Dict{Symbol,Any}(kw), args...) $(MakieCore).default_theme(scene, ::Type{<:$PlotType}) = $(esc(theme_func))(scene) export $PlotType, $funcname, $funcname! end @@ -211,15 +211,15 @@ plot(MyType(...)) ``` """ function Plot(args::Vararg{DataType,N}) where {N} - Plot{plot, <:Tuple{args...}} + Plot{plot,<:Tuple{args...}} end function Plot(::Type{T}) where {T} - Plot{plot, <:Tuple{T}} + Plot{plot,<:Tuple{T}} end function Plot(::Type{T1}, ::Type{T2}) where {T1,T2} - Plot{plot, <:Tuple{T1,T2}} + Plot{plot,<:Tuple{T1,T2}} end """ diff --git a/MakieCore/src/types.jl b/MakieCore/src/types.jl index e80345d339c..0ab96c33514 100644 --- a/MakieCore/src/types.jl +++ b/MakieCore/src/types.jl @@ -40,14 +40,14 @@ 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 """ @@ -63,8 +63,8 @@ Plot{scatter}((1:4,), Dict{Symbol, Any}(:color => :red)) isa Scatter Scatter((1:4,), Dict{Symbol, Any}(:color => :red)) ``` """ -mutable struct Plot{PlotFunc, T} <: ScenePlot{PlotFunc} - transformation::Union{Nothing, Transformable} +mutable struct Plot{PlotFunc,T} <: ScenePlot{PlotFunc} + transformation::Union{Nothing,Transformable} # Unprocessed arguments directly from the user command e.g. `plot(args...; kw...)`` kw::Dict{Symbol,Any} @@ -78,9 +78,9 @@ mutable struct Plot{PlotFunc, T} <: ScenePlot{PlotFunc} deregister_callbacks::Vector{Observables.ObserverFunction} parent::Union{AbstractScene,Plot} - function Plot{Typ,T}(kw::Dict{Symbol, Any}, args::Vector{Any}, converted::NTuple{N, Observable}) where {Typ,T,N} + function Plot{Typ,T}(kw::Dict{Symbol,Any}, args::Vector{Any}, converted::NTuple{N,Observable}) where {Typ,T,N} return new{Typ,T}(nothing, kw, args, converted, Attributes(), Plot[], - Observables.ObserverFunction[]) + Observables.ObserverFunction[]) end end @@ -129,7 +129,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 c3c0afd2324..62e19a26257 100644 --- a/MakieRecipes/src/bezier.jl +++ b/MakieRecipes/src/bezier.jl @@ -9,15 +9,15 @@ ) end -conversion_trait(::Type{<: Bezier}) = PointBased() +conversion_trait(::Type{<:Bezier}) = PointBased() -function calculated_attributes!(::Type{<: Bezier}, plot) +function calculated_attributes!(::Type{<:Bezier}, 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 color_and_colormap!(plot) @@ -35,7 +35,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 c9bba8d60eb..a84681c5588 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 993be72e3eb..fdda443376e 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, resource=RPR.GPU0) -fig = Figure(; size=(800, 600), fontsize=26) +RPRMakie.activate!(plugin = RPR.Northstar, resource = RPR.GPU0) +fig = Figure(; size = (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/datashader-rpr.jl b/RPRMakie/examples/datashader-rpr.jl index dce5f7c845e..a2e17b0d771 100644 --- a/RPRMakie/examples/datashader-rpr.jl +++ b/RPRMakie/examples/datashader-rpr.jl @@ -1,12 +1,12 @@ using DelimitedFiles, GLMakie GLMakie.activate!() # hide # For saving/showing/inlining into documentation we need to disable async calculation. -Makie.set_theme!(DataShader=(; async_latest=false)) +Makie.set_theme!(DataShader = (; async_latest = false)) airports = Point2f.(eachrow(readdlm(assetpath("airportlocations.csv")))) (xmin, ymin), (xmax, ymax) = extrema(xx) xx = Rect2f(points) -all(x-> x in xx, points) +all(x -> x in xx, points) canvas = Canvas(Rect2f(points)) @@ -14,7 +14,7 @@ aggregate!(canvas, points); m = collect(Makie.get_aggregation(canvas)) -(xmin, ymin), (xmax, ymax) = map(x-> x./widths(canvas.bounds), extrema(canvas.bounds)) +(xmin, ymin), (xmax, ymax) = map(x -> x ./ widths(canvas.bounds), extrema(canvas.bounds)) xw, yw = 1 ./ size(m) maxi = maximum(mscaled) @@ -24,29 +24,29 @@ lights = [EnvironmentLight(0.5, load(RPR.assetpath("studio026.exr"))), PointLight(Vec3f(0, 0, 2), RGBf(radiance, radiance, radiance))] mscaled = m ./ widths(canvas.bounds)[1] recmesh = GeometryBasics.normal_mesh(Rect3f(Vec3f(-0.5), Vec3f(1))) -RPRMakie.activate!(plugin=RPR.Northstar, iterations=1, resource=RPR.RPR_CREATION_FLAGS_ENABLE_GPU1) +RPRMakie.activate!(plugin = RPR.Northstar, iterations = 1, resource = RPR.RPR_CREATION_FLAGS_ENABLE_GPU1) f, ax, pl = meshscatter( xmin .. xmax, ymin .. ymax, mscaled; - axis=(; type=LScene, show_axis=false, scenekw=(; lights=lights)), - marker=recmesh, - color=mscaled, - colorrange=Vec2f(0.000001, maxi), - lowclip=(:blue, 0.1), - colormap=[:white, :red], - material=(; type=:Microfacet, color=:gray, roughness=0.2, ior=1.390), - markersize=Vec3f.(xw, yw, vec(mscaled)) + axis = (; type = LScene, show_axis = false, scenekw = (; lights = lights)), + marker = recmesh, + color = mscaled, + colorrange = Vec2f(0.000001, maxi), + lowclip = (:blue, 0.1), + colormap = [:white, :red], + material = (; type = :Microfacet, color = :gray, roughness = 0.2, ior = 1.390), + markersize = Vec3f.(xw, yw, vec(mscaled)) ) ax.scene |> display -display(f; backend=GLMakie) +display(f; backend = GLMakie) using RPRMakie, FileIO -RPRMakie.activate!(plugin=RPR.Tahoe, iterations=1, resource=RPR.RPR_CREATION_FLAGS_ENABLE_GPU1) +RPRMakie.activate!(plugin = RPR.Tahoe, iterations = 1, resource = RPR.RPR_CREATION_FLAGS_ENABLE_GPU1) RPRMakie.replace_scene_rpr!(ax.scene) l = lights[2] -l.position[] = Vec3f(xmin + xmax/2, ymin + ymax / 2, widths(canvas.bounds)[1]) +l.position[] = Vec3f(xmin + xmax / 2, ymin + ymax / 2, widths(canvas.bounds)[1]) l.radiance[] = RGBf(500, 500, 500) pl.colorrange[] = Vec2f(0.000001, maxi) diff --git a/RPRMakie/examples/eart_topographie_sphere.jl b/RPRMakie/examples/eart_topographie_sphere.jl index e02ee0a2fc9..ba0d219bfb7 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(; size=(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(; size = (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 ceaf99ef70a..7898fb365ca 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(; size=(2000, 800)) +RPRMakie.activate!(iterations = 32, plugin = RPR.Northstar) +fig = Figure(; size = (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 fa9956c947d..e7b983dcad5 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(size=(500, 500), lights=lights) +s = Scene(size = (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) s diff --git a/RPRMakie/examples/lines.jl b/RPRMakie/examples/lines.jl index 2fed509dc2d..eecb45b34ba 100644 --- a/RPRMakie/examples/lines.jl +++ b/RPRMakie/examples/lines.jl @@ -4,29 +4,29 @@ using Colors: N0f8 function box!(ax, size) orig = Vec3f(-2, -2, 0) - mesh!(ax, Rect3f(orig, Vec3f(size, size, 0.1)); color=:white, - material=(reflection_color=Vec4f(1), reflection_weight=10f0)) - mesh!(ax, Rect3f(orig, Vec3f(0.1, size, size)); color=:white) - mesh!(ax, Rect3f(orig, Vec3f(size, 0.1, size)); color=:white) + mesh!(ax, Rect3f(orig, Vec3f(size, size, 0.1)); color = :white, + material = (reflection_color = Vec4f(1), reflection_weight = 10f0)) + mesh!(ax, Rect3f(orig, Vec3f(0.1, size, size)); color = :white) + mesh!(ax, Rect3f(orig, Vec3f(size, 0.1, size)); color = :white) return end begin - fig = Figure(; size=(1000, 1000)) + fig = Figure(; size = (1000, 1000)) radiance = 100 lights = Makie.AbstractLight[PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] - ax = LScene(fig[1, 1]; scenekw=(; lights=lights), show_axis=false) + ax = LScene(fig[1, 1]; scenekw = (; lights = lights), show_axis = false) points = Point3f[] for i in 4:10 n = i + 1 y = LinRange(0, i, n) y2 = (y ./ 2) .- 2 xyz = Point3f.((i - 5) ./ 2, y2, sin.(y) .+ 1) - lp = lines!(ax, xyz; linewidth=10, color=:white) + lp = lines!(ax, xyz; linewidth = 10, color = :white) append!(points, xyz) end - mat = (; emission_color=:red, emission_weight=Vec3f(5.0f0)) - meshscatter!(ax, points; material=mat) + mat = (; emission_color = :red, emission_weight = Vec3f(5.0f0)) + meshscatter!(ax, points; material = mat) box!(ax, 5) RPRMakie.activate!(plugin = RPR.Northstar, iterations = 500, resource = RPR.GPU0) ax.scene |> display 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/material_x.jl b/RPRMakie/examples/material_x.jl index 757fd825c90..197ec57d99a 100644 --- a/RPRMakie/examples/material_x.jl +++ b/RPRMakie/examples/material_x.jl @@ -6,15 +6,15 @@ material = "Pinwheel_Pattern_Marble_Tiles_4k_16b" # folder you downloaded & extr img = begin radiance = 1000 lights = [EnvironmentLight(0.5, load(RPR.assetpath("studio026.exr"))), - PointLight(Vec3f(5), RGBf(radiance, radiance, radiance * 1.1))] - fig = Figure(; size=(1500, 700)) - ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) - screen = RPRMakie.Screen(ax.scene; plugin=RPR.Northstar, iterations=500, resource=RPR.GPU0) + PointLight(Vec3f(5), RGBf(radiance, radiance, radiance * 1.1))] + fig = Figure(; size = (1500, 700)) + ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) + screen = RPRMakie.Screen(ax.scene; plugin = RPR.Northstar, iterations = 500, resource = RPR.GPU0) matsys = screen.matsys marble_tiles = RPR.Matx(matsys, joinpath(material, "Pinwheel_Pattern_Marble_Tiles.mtlx")) - mesh!(ax, load(Makie.assetpath("matball_floor.obj")); color=:white) - matball!(ax, marble_tiles; color=nothing) + mesh!(ax, load(Makie.assetpath("matball_floor.obj")); color = :white) + matball!(ax, marble_tiles; color = nothing) cam = cameracontrols(ax.scene) cam.eyeposition[] = Vec3f(0.0, -2, 1) cam.lookat[] = Vec3f(0) diff --git a/RPRMakie/examples/materials.jl b/RPRMakie/examples/materials.jl index 80f7d9a0f2e..f676b43dff0 100644 --- a/RPRMakie/examples/materials.jl +++ b/RPRMakie/examples/materials.jl @@ -5,10 +5,10 @@ using Colors: N0f8 img = begin radiance = 500 lights = [EnvironmentLight(1.0, load(RPR.assetpath("studio026.exr"))), - PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] - fig = Figure(; size=(1500, 700)) - ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) - screen = RPRMakie.Screen(ax.scene; plugin=RPR.Northstar, iterations=1000) + PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] + fig = Figure(; size = (1500, 700)) + ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) + screen = RPRMakie.Screen(ax.scene; plugin = RPR.Northstar, iterations = 1000) matsys = screen.matsys emissive = RPR.EmissiveMaterial(matsys) @@ -20,19 +20,19 @@ img = begin gold = RPR.SurfaceGoldX(matsys) materials = [glass chrome; - gold dielectric; - emissive plastic] + 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 6141b833658..61ce2cd40fc 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(; size=(1500, 1000)) -ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) -screen = RPRMakie.Screen(size(ax.scene); plugin=RPR.Northstar, resource=RPR.RPR_CREATION_FLAGS_ENABLE_GPU0) +fig = Figure(; size = (1500, 1000)) +ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) +screen = RPRMakie.Screen(size(ax.scene); plugin = RPR.Northstar, resource = RPR.RPR_CREATION_FLAGS_ENABLE_GPU0) 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); justification=:left)) + push!(labels, Label(fig, string(key); justification = :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) @@ -77,10 +77,10 @@ cam.lookat[] = Vec3f(0, 0, -1) cam.upvector[] = Vec3f(0, 0, 1) cam.fov[] = 30 -GLMakie.activate!(inline=false) -display(fig; inline=false, backend=GLMakie) -RPRMakie.activate!(iterations=1, plugin=RPR.Northstar, resource=RPR.GPU0) -context, task = RPRMakie.replace_scene_rpr!(ax.scene, screen; refresh=refresh); +GLMakie.activate!(inline = false) +display(fig; inline = false, backend = GLMakie) +RPRMakie.activate!(iterations = 1, plugin = RPR.Northstar, resource = RPR.GPU0) +context, task = RPRMakie.replace_scene_rpr!(ax.scene, screen; refresh = refresh); nothing # Change light parameters interactively diff --git a/RPRMakie/examples/sea_cables.jl b/RPRMakie/examples/sea_cables.jl index 0f78515347f..0c6ea471be8 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(; size=(1000, 1000)) + fig = Figure(; size = (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/examples/volume.jl b/RPRMakie/examples/volume.jl index c44b59b7dc1..e91456ad0a7 100644 --- a/RPRMakie/examples/volume.jl +++ b/RPRMakie/examples/volume.jl @@ -2,13 +2,13 @@ using RPRMakie using Makie, NIfTI, FileIO using GLMakie r = LinRange(-1, 1, 100) -cube = [(x .^ 2 + y .^ 2 + z .^ 2) for x = r, y = r, z = r] +cube = [(x .^ 2 + y .^ 2 + z .^ 2) for x in r, y in r, z in r] brain = Float32.(niread(Makie.assetpath("brain.nii.gz")).raw) radiance = 5000 lights = [EnvironmentLight(1.0, load(RPR.assetpath("studio026.exr"))), PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] -fig = Figure(; size=(1000, 1000)) -ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) -Makie.volume!(ax, 0..3, 0..3.78, 0..3.18, brain, algorithm=:absorption, absorption=0.3) -display(ax.scene; iterations=5000) +fig = Figure(; size = (1000, 1000)) +ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) +Makie.volume!(ax, 0 .. 3, 0 .. 3.78, 0 .. 3.18, brain, algorithm = :absorption, absorption = 0.3) +display(ax.scene; iterations = 5000) diff --git a/RPRMakie/src/RPRMakie.jl b/RPRMakie/src/RPRMakie.jl index b83ae20599e..5b801e6f43f 100644 --- a/RPRMakie/src/RPRMakie.jl +++ b/RPRMakie/src/RPRMakie.jl @@ -66,7 +66,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 5f85f8db0c3..cfd958725f8 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) @@ -58,7 +58,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 = extract_material(matsys, plot) color = to_color(plot.color[]) @@ -75,7 +75,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 43bb3862d17..bc95381201b 100644 --- a/RPRMakie/src/meshes.jl +++ b/RPRMakie/src/meshes.jl @@ -1,7 +1,7 @@ function extract_material(matsys, plot) 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 @@ -38,7 +38,7 @@ function mesh_material(context, matsys, plot, color_obs = plot.color) end material = extract_material(matsys, plot) - on(plot, color_signal; update=true) do color + on(plot, color_signal; update = true) do color if !isnothing(color) && hasproperty(material, :color) material.color = color end @@ -69,7 +69,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.MeshScatter) RPR.rprShapeSetObjectID(marker, 0) material = extract_material(matsys, plot) 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) @@ -81,7 +81,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) @@ -91,14 +91,14 @@ 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, color_from_num; uv=uv) + tex = RPR.Texture(matsys, color_from_num; uv = uv) material.color = tex elseif color isa Colorant material.color = color - elseif color isa AbstractMatrix{<: Colorant} + elseif color isa AbstractMatrix{<:Colorant} material.color = color else error("Unsupported color type for RadeonProRender backend: $(typeof(color))") @@ -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 65ff446771e..ed4c0fd5276 100644 --- a/RPRMakie/src/scene.jl +++ b/RPRMakie/src/scene.jl @@ -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 @@ -67,12 +67,12 @@ function to_rpr_light(context::RPR.Context, rpr_scene, light::Makie.DirectionalL directionallight = RPR.DirectionalLight(context) map(light.direction) do dir if light.camera_relative - T = inv(scene.camera.view[][Vec(1,2,3), Vec(1,2,3)]) + T = inv(scene.camera.view[][Vec(1, 2, 3), Vec(1, 2, 3)]) dir = normalize(T * dir) else dir = normalize(dir) end - quart = Makie.rotation_between(dir, Vec3f(0,0,-1)) + quart = Makie.rotation_between(dir, Vec3f(0, 0, -1)) transform!(directionallight, Makie.rotationmatrix4(quart)) end map(light.color) do c @@ -102,7 +102,7 @@ end function to_rpr_light(context::RPR.Context, rpr_scene, light::Makie.SpotLight) spotlight = RPR.SpotLight(context) map(light.position, light.direction) do pos, dir - quart = Makie.rotation_between(dir, Vec3f(0,0,-1)) + quart = Makie.rotation_between(dir, Vec3f(0, 0, -1)) transform!(spotlight, Makie.translationmatrix(pos) * Makie.rotationmatrix4(quart)) end map(light.color) do c @@ -144,7 +144,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) @@ -160,7 +160,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 @@ -192,14 +192,14 @@ function replace_scene_rpr!(scene::Makie.Scene, screen=Screen(scene); refresh=Ob task = @async while isopen(scene) t = time() 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) + im[1] = reverse(reshape(data, screen.fb_size); dims = 2) tframe = time() - t - to_sleep = (1/10) - tframe + to_sleep = (1 / 10) - tframe if to_sleep < 0.0 yield() else @@ -226,10 +226,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 @@ -242,7 +242,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) @@ -252,12 +252,12 @@ function Makie.apply_screen_config!(screen::Screen, config::ScreenConfig) end function Screen(fb_size::NTuple{2,<:Integer}; screen_config...) - config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol, Any}(screen_config)) + config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol,Any}(screen_config)) return Screen(fb_size, config) end function Screen(scene::Scene; screen_config...) - config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol, Any}(screen_config)) + config = Makie.merge_screen_config(ScreenConfig, Dict{Symbol,Any}(screen_config)) return Screen(scene, config) end @@ -271,7 +271,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)) @@ -284,7 +284,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 @@ -313,10 +313,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 @@ -341,4 +341,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/src/volume.jl b/RPRMakie/src/volume.jl index 197c56ed1a0..05f269dc9bb 100644 --- a/RPRMakie/src/volume.jl +++ b/RPRMakie/src/volume.jl @@ -26,7 +26,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.Volume) color_sampler.uv = gridsampler volmat = RPR.VolumeMaterial(matsys) - on(plot.absorption; update=true) do absorption + on(plot.absorption; update = true) do absorption return volmat.density = Vec4f(absorption, 0.0, 0.0, 0.0) end volmat.densitygrid = gridsampler diff --git a/RPRMakie/test/lines.jl b/RPRMakie/test/lines.jl index 9dba114232c..2ece0df3236 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(size=(1000, 1000)) - ax = LScene(fig[1, 1], show_axis=false) + fig = Figure(size = (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 730e57ca3df..a6db591a777 100644 --- a/RPRMakie/test/runtests.jl +++ b/RPRMakie/test/runtests.jl @@ -1,9 +1,9 @@ using RPRMakie using Test -RPRMakie.activate!(iterations=50) -f, ax, pl = meshscatter(rand(Point3f, 100), color=:blue) +RPRMakie.activate!(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 49c5bafdbf0..fd11c609b3d 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 @@ -38,19 +40,19 @@ macro reference_test(name, code) error("title must be unique. Duplicate title: $(title)") end println("running $(lpad(COUNTER[] += 1, 3)): $($title)") - Makie.set_theme!(; size=(500, 500), - CairoMakie=(; px_per_unit=1), - GLMakie=(; scalefactor=1, px_per_unit=1), - WGLMakie=(; scalefactor=1, px_per_unit=1)) + Makie.set_theme!(; size = (500, 500), + CairoMakie = (; px_per_unit = 1), + GLMakie = (; scalefactor = 1, px_per_unit = 1), + WGLMakie = (; scalefactor = 1, px_per_unit = 1)) ReferenceTests.RNG.seed_rng!() result = let $(esc(code)) end @test save_result(joinpath(RECORDING_DIR[], $title), result) push!($REGISTERED_TESTS, $title) - elapsed = round(time() - t1; digits=5) + elapsed = round(time() - t1; digits = 5) total = Sys.total_memory() - mem = round((total - Sys.free_memory()) / 10^9; digits=3) + mem = round((total - Sys.free_memory()) / 10^9; digits = 3) # TODO, write to file and create an overview in the end, similar to the benchmark results! println("Used $(mem)gb of $(round(total / 10^9; digits=3))gb RAM, time: $(elapsed)s") end @@ -64,24 +66,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) @@ -97,7 +99,7 @@ macro include_reference_tests(backend::Symbol, path, paths...) end recording_dir = joinpath($toplevel_folder, "reference_images") if isdir(recording_dir) - rm(recording_dir; force=true, recursive=true) + rm(recording_dir; force = true, recursive = true) end # prefix the recordings with the backend name so that each backend has its own versions ReferenceTests.RECORDING_DIR[] = joinpath(recording_dir, "recorded", $(string(backend))) diff --git a/ReferenceTests/src/image_download.jl b/ReferenceTests/src/image_download.jl index e1e72cb9cf2..4b890a8cd88 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()) +function download_refimages(tag = last_major_version()) url = "https://github.com/MakieOrg/Makie.jl/releases/download/$(tag)/reference_images.tar" images_tar = basedir("reference_images.tar") images = basedir("reference_images") @@ -17,7 +17,7 @@ function download_refimages(tag=last_major_version()) 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 cb0d0672322..59f7b161305 100644 --- a/ReferenceTests/src/runtests.jl +++ b/ReferenceTests/src/runtests.jl @@ -14,7 +14,7 @@ function get_frames(video::AbstractString) 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] @@ -38,7 +38,7 @@ function compare_images(a::AbstractMatrix{<:Union{RGB,RGBA}}, b::AbstractMatrix{ range_dim1 = round.(Int, range(0, size(a, 1), length = ceil(Int, size(a, 1) / approx_tile_size_px))) range_dim2 = round.(Int, range(0, size(a, 2), length = ceil(Int, size(a, 2) / approx_tile_size_px))) - boundary_iter(boundaries) = zip(boundaries[1:end-1] .+ 1, boundaries[2:end]) + boundary_iter(boundaries) = zip(boundaries[1:(end - 1)] .+ 1, boundaries[2:end]) _norm(rgb1::RGBf, rgb2::RGBf) = sqrt(sum(((rgb1.r - rgb2.r)^2, (rgb1.g - rgb2.g)^2, (rgb1.b - rgb2.b)^2))) _norm(rgba1::RGBAf, rgba2::RGBAf) = sqrt(sum(((rgba1.r - rgba2.r)^2, (rgba1.g - rgba2.g)^2, (rgba1.b - rgba2.b)^2, (rgba1.alpha - rgba2.alpha)^2))) @@ -81,7 +81,7 @@ function get_all_relative_filepaths_recursively(dir) end end -function record_comparison(base_folder::String; record_folder_name="recorded", tag=last_major_version()) +function record_comparison(base_folder::String; record_folder_name = "recorded", tag = last_major_version()) record_folder = joinpath(base_folder, record_folder_name) @info "Downloading reference images" reference_folder = download_refimages(tag) @@ -120,7 +120,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 5b89c3d86bd..1521b10aa58 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, colorrange=(0, 1)) + 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, colorrange = (0, 1)) 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=NoShading) + mesh(Sphere(Point3f(0), 1f0), color = :orange, shading = NoShading) 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 2bedc371f4b..b10b99a3fb5 100644 --- a/ReferenceTests/src/tests/examples2d.jl +++ b/ReferenceTests/src/tests/examples2d.jl @@ -32,17 +32,17 @@ 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 @@ -50,13 +50,13 @@ end fig, ax, meshplot = mesh(s) 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 @@ -71,7 +71,7 @@ end 1.0 0.5; 0.0 1.0; 0.5 1.0; - 1.0 1.0; + 1.0 1.0 ] connectivity = [ 1 2 5; @@ -81,10 +81,10 @@ end 4 5 8; 4 7 8; 5 6 9; - 5 8 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 @@ -97,7 +97,7 @@ end 1.0 0.5; 0.0 1.0; 0.5 1.0; - 1.0 1.0; + 1.0 1.0 ] connectivity = [ 1 2 5; @@ -107,47 +107,47 @@ end 4 5 8; 4 7 8; 5 6 9; - 5 8 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=NoShading) - wireframe!(ax, meshplot[1], color=(:black, 0.6), linewidth=3) + fig, ax, meshplot = mesh(coordinates, connectivity, color = color, shading = NoShading) + 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=NoShading + [(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], color = [:red, :green, :blue], + shading = NoShading ) 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,9 +199,9 @@ end v(x::Point2{T}, t) where T = Point2{T}(one(T) * x[2] * t, 4 * x[1]) sf = Observable(Base.Fix2(v, 0.0)) title_str = Observable("t = 0.00") - sp = streamplot(sf, -2..2, -2..2; - linewidth=2, colormap=:magma, axis=(;title=title_str)) - Record(sp, LinRange(0, 20, 5); framerate=1) do i + sp = streamplot(sf, -2 .. 2, -2 .. 2; + linewidth = 2, colormap = :magma, axis = (; title = title_str)) + Record(sp, LinRange(0, 20, 5); framerate = 1) do i sf[] = Base.Fix2(v, i) title_str[] = "t = $(round(i; sigdigits=2))" end @@ -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=1) do i + Record(fig, 1:N; framerate = 1) 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 @@ -360,17 +360,17 @@ end @reference_test "Simple pie chart" begin - fig = Figure(size=(800, 800)) - pie(fig[1, 1], 1:5, color=collect(1:5), axis=(;aspect=DataAspect())) + fig = Figure(size = (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 @@ -380,22 +380,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] @@ -407,7 +407,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) @@ -495,19 +495,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) - t = text!(Point2f(100, 0.5), text = "Test", fontsize = 50, transform_marker=true) + fig, ax, p = scatter(Point2f(100, 0.5), marker = 'a', markersize = 50) + t = text!(Point2f(100, 0.5), text = "Test", fontsize = 50, transform_marker = true) 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, transform_marker=true) - Makie.rotate!(t2, pi/4) + t2 = text!(ax, 1, 0, text = "Test", fontsize = 50, transform_marker = true) + Makie.rotate!(t2, pi / 4) scale!(t2, 0.5, 0.5, 1) xlims!(ax, -0.2, 0.5) @@ -518,39 +518,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 = NoShading) + 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 = NoShading) end @reference_test "heatmap and image colormap interpolation" begin - f = Figure(size=(500, 500)) + f = Figure(size = (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 @@ -566,11 +566,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"]) @@ -579,18 +579,18 @@ end end @reference_test "colormap with specific values" begin - cmap = cgrad([:black,:white,:orange],[0,0.2,1]) - fig = Figure(size=(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(size = (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 "colorscale (heatmap)" begin - x = 10.0.^(1:0.1:4) + x = 10.0 .^ (1:0.1:4) y = 1.0:0.1:5.0 fig, ax, hm = heatmap(x, y, (x, y) -> x; axis = (; xscale = log10), colorscale = log10) Colorbar(fig[1, 2], hm) @@ -601,8 +601,8 @@ end xs = 0:0.01:10 ys = 2 .* (1 .+ sin.(xs)) fig = Figure() - lines(fig[1, 1], xs, ys; linewidth=50, color=ys, colorscale=identity) - lines(fig[2, 1], xs, ys; linewidth=50, color=ys, colorscale=sqrt) + lines(fig[1, 1], xs, ys; linewidth = 50, color = ys, colorscale = identity) + lines(fig[2, 1], xs, ys; linewidth = 50, color = ys, colorscale = sqrt) fig end @@ -628,7 +628,7 @@ 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 @@ -649,7 +649,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) @@ -702,13 +702,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, @@ -724,13 +724,13 @@ end @reference_test "tricontourf with boundary nodes" 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.() inner = [n:-1:1; n] # clockwise inner - outer = [(n+1):(2n); n+1] # counter-clockwise outer + outer = [(n + 1):(2n); n + 1] # counter-clockwise outer boundary_nodes = [[outer], [inner]] tri = triangulate([x'; y'], boundary_nodes = boundary_nodes) f, ax, _ = tricontourf(tri, z) @@ -740,10 +740,10 @@ end @reference_test "tricontourf with boundary nodes and edges" begin curve_1 = [ - [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (15.0, 0.0), (20.0, 0.0), (25.0, 0.0)], - [(25.0, 0.0), (25.0, 5.0), (25.0, 10.0), (25.0, 15.0), (25.0, 20.0), (25.0, 25.0)], - [(25.0, 25.0), (20.0, 25.0), (15.0, 25.0), (10.0, 25.0), (5.0, 25.0), (0.0, 25.0)], - [(0.0, 25.0), (0.0, 20.0), (0.0, 15.0), (0.0, 10.0), (0.0, 5.0), (0.0, 0.0)] + [(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (15.0, 0.0), (20.0, 0.0), (25.0, 0.0)], + [(25.0, 0.0), (25.0, 5.0), (25.0, 10.0), (25.0, 15.0), (25.0, 20.0), (25.0, 25.0)], + [(25.0, 25.0), (20.0, 25.0), (15.0, 25.0), (10.0, 25.0), (5.0, 25.0), (0.0, 25.0)], + [(0.0, 25.0), (0.0, 20.0), (0.0, 15.0), (0.0, 10.0), (0.0, 5.0), (0.0, 0.0)] ] curve_2 = [ [(4.0, 6.0), (4.0, 14.0), (4.0, 20.0), (18.0, 20.0), (20.0, 20.0)], @@ -764,7 +764,7 @@ end (13.0, 19.0), (13.0, 12.0), (16.0, 8.0), (9.8, 8.0), (7.5, 6.0), (12.0, 13.0), (19.0, 15.0) ] - boundary_nodes, points = convert_boundary_points_to_indices(curves; existing_points=points) + boundary_nodes, points = convert_boundary_points_to_indices(curves; existing_points = points) edges = Set(((1, 19), (19, 12), (46, 4), (45, 12))) tri = triangulate(points; boundary_nodes = boundary_nodes, edges = edges, check_arguments = false) @@ -774,7 +774,7 @@ end end @reference_test "tricontourf with provided triangulation" begin - θ = [LinRange(0, 2π * (1 - 1/19), 20); 0] + θ = [LinRange(0, 2π * (1 - 1 / 19), 20); 0] xy = Vector{Vector{Vector{NTuple{2,Float64}}}}() cx = [0.0, 3.0] for i in 1:2 @@ -782,8 +782,8 @@ end push!(xy, [[(cx[i] + 0.5cos(θ), 0.5sin(θ)) for θ in reverse(θ)]]) end boundary_nodes, points = convert_boundary_points_to_indices(xy) - tri = triangulate(points; boundary_nodes=boundary_nodes, check_arguments=false) - z = [(x - 3/2)^2 + y^2 for (x, y) in each_point(tri)] + tri = triangulate(points; boundary_nodes = boundary_nodes, check_arguments = false) + z = [(x - 3 / 2)^2 + y^2 for (x, y) in each_point(tri)] f, ax, tr = tricontourf(tri, z, colormap = :matter) f @@ -810,9 +810,9 @@ end @reference_test "contour labels with transform_func" begin f = Figure(size = (400, 400)) a = Axis(f[1, 1], xscale = log10) - xs = 10 .^ range(0, 3, length=101) - ys = range(1, 4, length=101) - zs = [sqrt(x*x + y*y) for x in -50:50, y in -50:50] + xs = 10 .^ range(0, 3, length = 101) + ys = range(1, 4, length = 101) + zs = [sqrt(x * x + y * y) for x in -50:50, y in -50:50] contour!(a, xs, ys, zs, labels = true, labelsize = 20) f end @@ -821,10 +821,10 @@ end fig = Figure() Axis3(fig[1, 1]) - xs = ys = range(-.5, .5; length = 50) + xs = ys = range(-0.5, 0.5; length = 50) zs = @. √(xs^2 + ys'^2) - levels = .025:.05:.475 + levels = 0.025:0.05:0.475 contour3d!(-zs; levels = -levels, labels = true, color = :blue) contour3d!(+zs; levels = +levels, labels = true, color = :red, labelcolor = :black) fig @@ -832,9 +832,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 @@ -865,7 +865,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) @@ -881,7 +881,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) @@ -944,7 +944,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, colorscale=log10, + hexbin(f[1, 2], x, y, bins = 40, colorscale = log10, axis = (aspect = DataAspect(), title = "scale = log10")) f end @@ -968,8 +968,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 @@ -989,12 +989,12 @@ end end @reference_test "bracket scalar" begin - f, ax, l = lines(0..9, sin; axis = (; xgridvisible = false, ygridvisible = false)) + f, ax, l = lines(0 .. 9, sin; axis = (; xgridvisible = false, ygridvisible = false)) ylims!(ax, -1.5, 1.5) - bracket!(pi/2, 1, 5pi/2, 1, offset = 5, text = "Period length", style = :square) + bracket!(pi / 2, 1, 5pi / 2, 1, offset = 5, text = "Period length", style = :square) - bracket!(pi/2, 1, pi/2, -1, text = "Amplitude", orientation = :down, + bracket!(pi / 2, 1, pi / 2, -1, text = "Amplitude", orientation = :down, linestyle = :dash, rotation = 0, align = (:right, :center), textoffset = 4, linewidth = 2, color = :red, textcolor = :red) bracket!(2.3, sin(2.3), 4.0, sin(4.0), @@ -1020,7 +1020,7 @@ end ) bracket!(ax, - [(Point2f(i, i-0.7), Point2f(i+2, i-0.7)) for i in 1:5], + [(Point2f(i, i - 0.7), Point2f(i + 2, i - 0.7)) for i in 1:5], text = ["F", "G", "H", "I", "J"], color = [:red, :blue, :green, :orange, :brown], linestyle = [:dash, :dot, :dash, :dot, :dash], @@ -1045,24 +1045,24 @@ end hist( f[1, 1], RNG.randn(10^6); - axis=(; yscale=log2) + axis = (; yscale = log2) ) hist( f[1, 2], RNG.randn(10^6); - axis=(; xscale=log2), + axis = (; xscale = log2), direction = :x ) # make a gap in histogram as edge case hist( f[2, 1], - filter!(x-> x<0 || x > 1.5, RNG.randn(10^6)); - axis=(; yscale=log10) + filter!(x -> x < 0 || x > 1.5, RNG.randn(10^6)); + axis = (; yscale = log10) ) hist( f[2, 2], - filter!(x-> x<0 || x > 1.5, RNG.randn(10^6)); - axis=(; xscale=log10), + filter!(x -> x < 0 || x > 1.5, RNG.randn(10^6)); + axis = (; xscale = log10), direction = :x ) f @@ -1075,7 +1075,8 @@ end hist(fig[1, 1], data) hist(fig[1, 2], data, bins = 30, color = :orange) a, p = hist(fig[1, 3], data, bins = 10, color = :transparent, strokecolor = :red, strokewidth = 4.0) - a.xgridcolor[] = RGBAf(0,0,0,1); a.ygridcolor[] = RGBAf(0,0,0,1) + a.xgridcolor[] = RGBAf(0, 0, 0, 1) + a.ygridcolor[] = RGBAf(0, 0, 0, 1) hist(fig[2, 1], data, normalization = :pdf, direction = :x) hist(fig[2, 2], data, normalization = :density, color = 1:15) @@ -1110,8 +1111,8 @@ end @reference_test "LaTeXStrings linesegment offsets" begin s = Scene(camera = campixel!, size = (600, 600)) for (i, (offx, offy)) in enumerate(zip([0, 20, 50], [0, 10, 30])) - for (j, rot) in enumerate([0, pi/4, pi/2]) - scatter!(s, 150i, 150j, color=:black) + for (j, rot) in enumerate([0, pi / 4, pi / 2]) + scatter!(s, 150i, 150j, color = :black) text!(s, 150i, 150j, text = L"\sqrt{x+y}", offset = (offx, offy), rotation = rot, fontsize = 30) end @@ -1166,11 +1167,11 @@ end p = Makie.Polygon(Point2f[]) q = Makie.Polygon(Point2f[(-1.0, 0.0), (1.0, 0.0), (0.0, 1.0)]) fig, ax, sc = poly([p, q]) - poly!(Axis(fig[1,2]), p, color = :black) - poly!(Axis(fig[2,1]), [p, q], color = [:red, :blue]) - poly!(Axis(fig[2,2]), [p, q], color = :red) - poly!(Axis(fig[3,1]), Makie.MultiPolygon([p]), color = :green) - poly!(Axis(fig[3,2]), Makie.MultiPolygon([p, q]), color = [:black, :red]) + poly!(Axis(fig[1, 2]), p, color = :black) + poly!(Axis(fig[2, 1]), [p, q], color = [:red, :blue]) + poly!(Axis(fig[2, 2]), [p, q], color = :red) + poly!(Axis(fig[3, 1]), Makie.MultiPolygon([p]), color = :green) + poly!(Axis(fig[3, 2]), Makie.MultiPolygon([p, q]), color = [:black, :red]) fig end @@ -1195,9 +1196,9 @@ end end @reference_test "contour with single alpha color" begin - x = range(-π, π; length=50) + x = range(-π, π; length = 50) z = @. sin(x) * cos(x') - fig, ax = contour(x, x, z, color=RGBAf(1,0,0,0.4), linewidth=6) + fig, ax = contour(x, x, z, color = RGBAf(1, 0, 0, 0.4), linewidth = 6) end @reference_test "Triplot with points, ghost edges, and convex hull" begin @@ -1205,11 +1206,9 @@ end tri = triangulate(pts; rng = RNG.STABLE_RNG) fig, ax, sc = triplot(tri, triangle_color = :lightgray, strokewidth = 4, - show_points=true, markersize = 20, markercolor = :orange, - show_ghost_edges=true, ghost_edge_linewidth = 4, - show_convex_hull=true, convex_hull_linewidth = 4 - - ) + show_points = true, markersize = 20, markercolor = :orange, + show_ghost_edges = true, ghost_edge_linewidth = 4, + show_convex_hull = true, convex_hull_linewidth = 4) fig end @@ -1265,13 +1264,13 @@ end @reference_test "Triplot with nonlinear transformation" begin f = Figure() ax = PolarAxis(f[1, 1]) - points = Point2f[(phi, r) for r in 1:10 for phi in range(0, 2pi, length=36)[1:35]] + points = Point2f[(phi, r) for r in 1:10 for phi in range(0, 2pi, length = 36)[1:35]] tr = triplot!(ax, points) f end @reference_test "Triplot after adding points and make sure the representative_point_list is correctly updated" begin - points = [(0.0,0.0),(0.95,0.0),(1.0,1.4),(0.0,1.0)] # not 1 so that we have a unique triangulation + points = [(0.0, 0.0), (0.95, 0.0), (1.0, 1.4), (0.0, 1.0)] # not 1 so that we have a unique triangulation tri = Observable(triangulate(points; delete_ghosts = false)) fig, ax, sc = triplot(tri, show_points = true, markersize = 14, show_ghost_edges = true, recompute_centers = true) for p in [(0.3, 0.5), (-1.5, 2.3), (0.2, 0.2), (0.2, 0.5)] @@ -1297,19 +1296,19 @@ end cx += 3.0 end boundary_nodes, points = convert_boundary_points_to_indices(xy) - tri = triangulate(points; boundary_nodes=boundary_nodes, check_arguments=false) - fig, ax, sc = triplot(tri, show_ghost_edges=true) + tri = triangulate(points; boundary_nodes = boundary_nodes, check_arguments = false) + fig, ax, sc = triplot(tri, show_ghost_edges = true) fig end @reference_test "Voronoiplot for a centroidal tessellation with an automatic colormap" begin - points = [(0.0,0.0),(1.0,0.0),(1.0,1.0),(0.0,1.0)] - tri = triangulate(points; boundary_nodes = [1,2,3,4,1], rng = RNG.STABLE_RNG) - refine!(tri; max_area=1e-2, min_angle = 29.871, rng = RNG.STABLE_RNG) + points = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)] + tri = triangulate(points; boundary_nodes = [1, 2, 3, 4, 1], rng = RNG.STABLE_RNG) + refine!(tri; max_area = 1e-2, min_angle = 29.871, rng = RNG.STABLE_RNG) vorn = voronoi(tri) smooth_vorn = centroidal_smooth(vorn; maxiters = 250, rng = RNG.STABLE_RNG) cmap = cgrad(:matter) - fig, ax, sc = voronoiplot(smooth_vorn, markersize=10, strokewidth = 4, markercolor = :red) + fig, ax, sc = voronoiplot(smooth_vorn, markersize = 10, strokewidth = 4, markercolor = :red) fig end @@ -1318,14 +1317,14 @@ end tri = triangulate(pts; rng = RNG.STABLE_RNG) vorn = voronoi(tri, false) fig, ax, sc = voronoiplot(vorn, - show_generators=true, - colormap=:RdBu, - strokecolor=:white, - strokewidth=4, - markersize=25, + show_generators = true, + colormap = :RdBu, + strokecolor = :white, + strokewidth = 4, + markersize = 25, marker = 'x', - markercolor=:green, - unbounded_edge_extension_factor=5.0) + markercolor = :green, + unbounded_edge_extension_factor = 5.0) xlims!(ax, -120, 120) ylims!(ax, -120, 120) fig @@ -1335,13 +1334,13 @@ end pts = 25RNG.randn(2, 10) tri = triangulate(pts; rng = RNG.STABLE_RNG) vorn = voronoi(tri, true) - fig, ax, sc = voronoiplot(vorn, color = (:blue,0.2), markersize = 20, strokewidth = 4) + fig, ax, sc = voronoiplot(vorn, color = (:blue, 0.2), markersize = 20, strokewidth = 4) # used to be bugged points = [(0.0, 1.0), (-1.0, 2.0), (-2.0, -1.0)] tri = triangulate(points) vorn = voronoi(tri) - voronoiplot(fig[1,2], vorn, show_generators = true, strokewidth = 4, + voronoiplot(fig[1, 2], vorn, show_generators = true, strokewidth = 4, color = [:red, :blue, :green], markercolor = :white, markersize = 20) fig @@ -1350,9 +1349,9 @@ end @reference_test "Voronoiplot with a nonlinear transform" begin f = Figure() ax = PolarAxis(f[1, 1], theta_as_x = false) - points = Point2f[(r, phi) for r in 1:10 for phi in range(0, 2pi, length=36)[1:35]] - polygon_color = [r for r in 1:10 for phi in range(0, 2pi, length=36)[1:35]] - polygon_color_2 = [phi for r in 1:10 for phi in range(0, 2pi, length=36)[1:35]] + points = Point2f[(r, phi) for r in 1:10 for phi in range(0, 2pi, length = 36)[1:35]] + polygon_color = [r for r in 1:10 for phi in range(0, 2pi, length = 36)[1:35]] + polygon_color_2 = [phi for r in 1:10 for phi in range(0, 2pi, length = 36)[1:35]] tr = voronoiplot!(ax, points, smooth = false, show_generators = false, color = polygon_color) Makie.rlims!(ax, 12) # to make rect clip visible if circular clip doesn't happen ax = PolarAxis(f[1, 2], theta_as_x = false) @@ -1368,13 +1367,13 @@ end color = [:red, :blue, :green, :yellow, :cyan, :magenta, :black, :brown] # the polygon colors should not change even if some are not included (because they're outside of the box) fig = Figure() ax1 = Axis(fig[1, 1], title = "Default") - voronoiplot!(ax1, vorn, show_generators = true, markersize=14, strokewidth = 4, color = color) + voronoiplot!(ax1, vorn, show_generators = true, markersize = 14, strokewidth = 4, color = color) ax2 = Axis(fig[1, 2], title = "Some excluded") - voronoiplot!(ax2, vorn, show_generators = true, markersize=14, strokewidth = 4, color = color, clip = BBox(0.0, 5.0, -15.0, 15.0)) + voronoiplot!(ax2, vorn, show_generators = true, markersize = 14, strokewidth = 4, color = color, clip = BBox(0.0, 5.0, -15.0, 15.0)) ax3 = Axis(fig[2, 1], title = "Bigger range") - voronoiplot!(ax3, vorn, show_generators = true, markersize=14, strokewidth = 4, color = color, clip = (-15.0, 15.0, -15.0, 15.0)) + voronoiplot!(ax3, vorn, show_generators = true, markersize = 14, strokewidth = 4, color = color, clip = (-15.0, 15.0, -15.0, 15.0)) ax4 = Axis(fig[2, 2], title = "Only one polygon") - voronoiplot!(ax4, vorn, show_generators = true, markersize=14, strokewidth = 4, color = color, clip = (10.0, 12.0, 2.0, 5.0)) + voronoiplot!(ax4, vorn, show_generators = true, markersize = 14, strokewidth = 4, color = color, clip = (10.0, 12.0, 2.0, 5.0)) for ax in fig.content xlims!(ax4, -15, 15) ylims!(ax4, -15, 15) @@ -1383,21 +1382,21 @@ end end @reference_test "Voronoiplot after adding points" begin - points = Observable([(0.0,0.0), (1.0,0.0), (1.0,1.0), (0.0,1.0)]) - fig, ax, sc = voronoiplot(points, show_generators=true, markersize=36) # make sure any regressions with missing generators are identified, so use 36 + points = Observable([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]) + fig, ax, sc = voronoiplot(points, show_generators = true, markersize = 36) # make sure any regressions with missing generators are identified, so use 36 push!(points[], (2.0, 2.0), (0.5, 0.5), (0.25, 0.25), (0.25, 0.75), (0.75, 0.25), (0.75, 0.75)) notify(points) ax2 = Axis(fig[1, 2]) - voronoiplot!(ax2, voronoi(triangulate(points[])), show_generators=true, markersize=36) - xlims!(ax,-0.5,2.5) - ylims!(ax,-0.5,2.5) - xlims!(ax2,-0.5,2.5) - ylims!(ax2,-0.5,2.5) # need to make sure all generators are shown, and the bounding box is automatically updated + voronoiplot!(ax2, voronoi(triangulate(points[])), show_generators = true, markersize = 36) + xlims!(ax, -0.5, 2.5) + ylims!(ax, -0.5, 2.5) + xlims!(ax2, -0.5, 2.5) + ylims!(ax2, -0.5, 2.5) # need to make sure all generators are shown, and the bounding box is automatically updated fig end function ppu_test_plot(resolution, px_per_unit, scalefactor) - fig, ax, pl = scatter(1:4, markersize=100, color=1:4, figure=(; size=resolution), axis=(; titlesize=50, title="ppu: $px_per_unit, sf: $scalefactor")) + fig, ax, pl = scatter(1:4, markersize = 100, color = 1:4, figure = (; size = resolution), axis = (; titlesize = 50, title = "ppu: $px_per_unit, sf: $scalefactor")) DataInspector(ax) hidedecorations!(ax) fig @@ -1409,7 +1408,7 @@ end @testset begin matr = [(px, scale) for px in [0.5, 1, 2], scale in [0.5, 1, 2]] imgs = map(matr) do (px_per_unit, scalefactor) - img = colorbuffer(ppu_test_plot(resolution, px_per_unit, scalefactor); px_per_unit=px_per_unit, scalefactor=scalefactor) + img = colorbuffer(ppu_test_plot(resolution, px_per_unit, scalefactor); px_per_unit = px_per_unit, scalefactor = scalefactor) @test size(img) == (800, 800) .* px_per_unit return img end @@ -1421,8 +1420,8 @@ end end @reference_test "spurious minor tick (#3487)" begin - fig = Figure(size=(227, 170)) - ax = Axis(fig[1, 1]; yticks = 0:.2:1, yminorticksvisible = true) + fig = Figure(size = (227, 170)) + ax = Axis(fig[1, 1]; yticks = 0:0.2:1, yminorticksvisible = true) ylims!(ax, 0, 1) fig end @@ -1445,7 +1444,7 @@ end ys = vcat(RNG.randn(6000), RNG.randn(4000) * 2) for (i, scale) in enumerate([:area, :count, :width]) ax = Axis(fig[i, 1]) - violin!(ax, xs, ys; scale, show_median=true) + violin!(ax, xs, ys; scale, show_median = true) Makie.xlims!(0.2, 4.8) ax.title = "scale=:$(scale)" end diff --git a/ReferenceTests/src/tests/examples3d.jl b/ReferenceTests/src/tests/examples3d.jl index 014f156cff0..71f0c01be01 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=NoShading, axis = (;show_axis=false)) + fig, ax, meshplot = mesh(Sphere(Point3f(0), 1f0), color = moon, shading = NoShading, axis = (; show_axis = false)) update_cam!(ax.scene, Vec3f(-2, 2, 2), Vec3f(0)) cameracontrols(ax).settings.center[] = false # avoid recenter on display fig @@ -10,17 +10,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=NoShading) + mesh(m, color = earth, shading = NoShading) 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)), @@ -41,12 +43,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 "Textured meshscatter" begin @@ -55,13 +57,13 @@ end rot = qrotation(Vec3f(1, 0, 0), 0.5pi) * qrotation(Vec3f(0, 1, 0), 0.7pi) meshscatter( 1:3, 1:3, fill(0, 3, 3), - marker=catmesh, color=img, markersize=1, rotations=rot, - axis=(type=LScene, show_axis=false) + marker = catmesh, color = img, markersize = 1, rotations = rot, + axis = (type = LScene, show_axis = false) ) end @reference_test "Load Mesh" begin - mesh(loadasset("cat.obj"); color=:black) + mesh(loadasset("cat.obj"); color = :black) end @reference_test "Colored Mesh" begin @@ -73,8 +75,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 @@ -91,9 +93,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 @@ -103,52 +105,52 @@ 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 "Ellipsoid marker sizes" begin # see PR #3722 pts = Point3f[[0, 0, 0], [1, 0, 0]] markersize = Vec3f[[0.5, 0.2, 0.5], [0.5, 0.2, 0.5]] rotations = [qrotation(Vec3f(1, 0, 0), 0), qrotation(Vec3f(1, 1, 0), π / 4)] - meshscatter(pts; markersize, rotations, color=:white, diffuse=Vec3f(-2, 0, 4), specular=Vec3f(4, 0, -2)) + meshscatter(pts; markersize, rotations, color = :white, diffuse = Vec3f(-2, 0, 4), specular = Vec3f(4, 0, -2)) 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; framerate=1) do i + Record(fig, 1:2; framerate = 1) do i t[] = i / 10 end end @@ -158,14 +160,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 @@ -176,44 +178,44 @@ 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 φ] 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 φ] @@ -223,7 +225,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 @@ -237,7 +239,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 @@ -260,8 +262,8 @@ end indices = connect(1:length(X), TriangleFace) fig = Figure() - poly!(Axis3(fig[1, 1]), vertices, indices; color=C[:], colorscale=identity) - poly!(Axis3(fig[1, 2]), vertices, indices; color=C[:], colorscale=log10) + poly!(Axis3(fig[1, 1]), vertices, indices; color = C[:], colorscale = identity) + poly!(Axis3(fig[1, 2]), vertices, indices; color = C[:], colorscale = log10) fig end @@ -269,11 +271,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 @@ -282,7 +284,7 @@ end vy = -1:0.01:1 f(x, y) = (sin(x * 10) + cos(y * 10)) / 4 - scene = Scene(size=(500, 500), camera=cam3d!) + scene = Scene(size = (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,)) @@ -303,10 +305,10 @@ 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" ) psurf.converted[3][] = f.(vx .+ 0.5, (vy .+ 0.5)') scene @@ -315,51 +317,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 @@ -368,11 +374,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 @@ -380,18 +386,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 @@ -400,46 +406,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); framerate=1) do i + Record(fig, range(5, stop = 40, length = 3); framerate = 1) 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)), @@ -451,21 +459,21 @@ end end @reference_test "Line GIF" begin - us = range(0, stop=1, length=100) - f, ax, p = linesegments(Rect3f(Vec3f(0, -1, 0), Vec3f(1, 2, 2)); color=:black) - p = lines!(ax, us, sin.(us), zeros(100), linewidth=3, transparency=true, color=:black) + us = range(0, stop = 1, length = 100) + f, ax, p = linesegments(Rect3f(Vec3f(0, -1, 0), Vec3f(1, 2, 2)); color = :black) + p = lines!(ax, us, sin.(us), zeros(100), linewidth = 3, transparency = true, color = :black) lineplots = [p] Makie.translate!(p, 0, 0, 0) colors = to_colormap(:RdYlBu) N = 5 - Record(f, 1:N; framerate=1) do i - t = i/(N/5) + Record(f, 1:N; framerate = 1) do i + 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) @@ -484,13 +492,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 @@ -511,20 +519,20 @@ 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 - colorrange=(0, 1), + algorithm = :mip, # maximum-intensity-projection + colorrange = (0, 1), ) ax.scene[OldAxis].names.textcolor = :gray # let axis labels be seen on dark background fig.scene.backgroundcolor[] = to_color(:black) @@ -536,9 +544,9 @@ end fig = Figure(size = (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). @@ -550,14 +558,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) @@ -577,13 +585,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 @@ -605,12 +613,12 @@ end mesh!(ax, Rect2f(0.8, 0.1, 0.1, 0.8), space = :relative, color = :blue, shading = NoShading) 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 # TODO: get 3D images working in CairoMakie and test them here too @reference_test "Heatmap 3D" begin - heatmap(-2..2, -1..1, RNG.rand(100, 100); axis = (; type = LScene)) + heatmap(-2 .. 2, -1 .. 1, RNG.rand(100, 100); axis = (; type = LScene)) end diff --git a/ReferenceTests/src/tests/figures_and_makielayout.jl b/ReferenceTests/src/tests/figures_and_makielayout.jl index fb49156980b..32566265ce7 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(size = (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,18 +27,18 @@ end @reference_test "Figure with boxes" begin fig = Figure(size = (900, 900)) - Box(fig[1,1], color = :red, strokewidth = 3, linestyle = :solid, strokecolor = :black) - Box(fig[1,2], color = (:red, 0.5), strokewidth = 3, linestyle = :dash, strokecolor = :red) - Box(fig[1,3], color = :white, strokewidth = 3, linestyle = :dot, strokecolor = (:black, 0.5)) - Box(fig[2,1], color = :red, strokewidth = 3, linestyle = :solid, strokecolor = :black, cornerradius = 0) - Box(fig[2,2], color = (:red, 0.5), strokewidth = 3, linestyle = :dash, strokecolor = :red, cornerradius = 20) - Box(fig[2,3], color = :white, strokewidth = 3, linestyle = :dot, strokecolor = (:black, 0.5), cornerradius = (0, 10, 20, 30)) + Box(fig[1, 1], color = :red, strokewidth = 3, linestyle = :solid, strokecolor = :black) + Box(fig[1, 2], color = (:red, 0.5), strokewidth = 3, linestyle = :dash, strokecolor = :red) + Box(fig[1, 3], color = :white, strokewidth = 3, linestyle = :dot, strokecolor = (:black, 0.5)) + Box(fig[2, 1], color = :red, strokewidth = 3, linestyle = :solid, strokecolor = :black, cornerradius = 0) + Box(fig[2, 2], color = (:red, 0.5), strokewidth = 3, linestyle = :dash, strokecolor = :red, cornerradius = 20) + Box(fig[2, 3], color = :white, strokewidth = 3, linestyle = :dot, strokecolor = (:black, 0.5), cornerradius = (0, 10, 20, 30)) fig 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) @@ -49,9 +49,9 @@ end fig[1, 1] = grid!( [ Label(fig, "A", width = nothing) Label(fig, "C", width = nothing); - menu1 menu3; + menu1 menu3; Label(fig, "B", width = nothing) Label(fig, "D", width = nothing); - menu2 menu4; + menu2 menu4 ] ) menu2.is_open = true @@ -62,7 +62,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(size = (1000, 660)) - m!(fig, lbl) = mesh!(fig.scene, lbl.layoutobservables.computedbbox, color = (:red, 0.5), shading=NoShading) + m!(fig, lbl) = mesh!(fig.scene, lbl.layoutobservables.computedbbox, color = (:red, 0.5), shading = NoShading) lbl1 = Label(fig[1, 1:2], "HEADER "^10, fontsize = 40, word_wrap = true) m!(fig, lbl1) @@ -138,11 +138,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), backgroundcolor = :gray50); - Legend(f[1, 2], ax, patchcolor = :gray80, patchsize = (100, 100), backgroundcolor = :gray50); + axislegend(ax, position = :lt, patchcolor = :red, patchsize = (100, 100), backgroundcolor = :gray50) + Legend(f[1, 2], ax, patchcolor = :gray80, patchsize = (100, 100), backgroundcolor = :gray50) f end end @@ -184,8 +184,8 @@ end @reference_test "PolarAxis surface" begin f = Figure() ax = PolarAxis(f[1, 1]) - zs = [r*cos(phi) for phi in range(0, 4pi, length=100), r in range(1, 2, length=100)] - p = surface!(ax, 0..2pi, 0..10, zs, shading = NoShading, colormap = :coolwarm, colorrange=(-2, 2)) + zs = [r * cos(phi) for phi in range(0, 4pi, length = 100), r in range(1, 2, length = 100)] + p = surface!(ax, 0 .. 2pi, 0 .. 10, zs, shading = NoShading, colormap = :coolwarm, colorrange = (-2, 2)) rlims!(ax, 0, 11) # verify that r = 10 doesn't end up at r > 10 translate!(p, 0, 0, -200) Colorbar(f[1, 2], p) @@ -196,13 +196,13 @@ end @reference_test "PolarAxis scatterlines spine" begin f = Figure(size = (800, 400)) ax1 = PolarAxis(f[1, 1], title = "No spine", spinevisible = false, theta_as_x = false) - scatterlines!(ax1, range(0, 1, length=100), range(0, 10pi, length=100), color = 1:100) + scatterlines!(ax1, range(0, 1, length = 100), range(0, 10pi, length = 100), color = 1:100) ax2 = PolarAxis(f[1, 2], title = "Modified spine") ax2.spinecolor[] = :red ax2.spinestyle[] = :dash ax2.spinewidth[] = 5 - scatterlines!(ax2, range(0, 10pi, length=100), range(0, 1, length=100), color = 1:100) + scatterlines!(ax2, range(0, 10pi, length = 100), range(0, 1, length = 100), color = 1:100) f end @@ -219,11 +219,11 @@ end thetaminorgridwidth = 1.0, thetaminorgridstyle = :dash, rgridwidth = 2, rgridcolor = :red, thetagridwidth = 2, thetagridcolor = :blue, - rticklabelsize = 18, rticklabelcolor = :red, rtickangle = pi/6, + rticklabelsize = 18, rticklabelcolor = :red, rtickangle = pi / 6, rticklabelstrokewidth = 1, rticklabelstrokecolor = :white, thetaticklabelsize = 18, thetaticklabelcolor = :blue, thetaticklabelstrokewidth = 1, thetaticklabelstrokecolor = :white, - thetaticks = ([0, π/2, π, 3π/2], ["A", "B", "C", rich("D", color = :orange)]), # https://github.com/MakieOrg/Makie.jl/issues/3583 + thetaticks = ([0, π / 2, π, 3π / 2], ["A", "B", "C", rich("D", color = :orange)]), # https://github.com/MakieOrg/Makie.jl/issues/3583 rticks = ([0.0, 2.5, 5.0, 7.5, 10.0], ["0.0", "2.5", "5.0", "7.5", rich("10.0", color = :orange)]) ) f @@ -231,11 +231,11 @@ end @reference_test "PolarAxis limits" begin f = Figure(size = (800, 600)) - for (i, theta_0) in enumerate((0, -pi/6, pi/2)) - for (j, thetalims) in enumerate(((0, 2pi), (-pi/2, pi/2), (0, pi/12))) - po = PolarAxis(f[i, j], theta_0 = theta_0, thetalimits = thetalims, rlimits = (1 + 2(j-1), 7)) - po.scene.backgroundcolor[] = RGBAf(1,0.5,0.5,1) - lines!(po, range(0, 20pi, length=201), range(0, 10, length=201), color = :white, linewidth = 5) + for (i, theta_0) in enumerate((0, -pi / 6, pi / 2)) + for (j, thetalims) in enumerate(((0, 2pi), (-pi / 2, pi / 2), (0, pi / 12))) + po = PolarAxis(f[i, j], theta_0 = theta_0, thetalimits = thetalims, rlimits = (1 + 2(j - 1), 7)) + po.scene.backgroundcolor[] = RGBAf(1, 0.5, 0.5, 1) + lines!(po, range(0, 20pi, length = 201), range(0, 10, length = 201), color = :white, linewidth = 5) b = Box(f[i, j], color = (:blue, 0.2)) translate!(b.blockscene, 0, 0, 9001) @@ -247,8 +247,8 @@ end end @reference_test "PolarAxis radial shift and clip" begin - phis = range(pi/4, 9pi/4, length=201) - rs = 1.0 ./ sin.(range(pi/4, 3pi/4, length=51)[1:end-1]) + phis = range(pi / 4, 9pi / 4, length = 201) + rs = 1.0 ./ sin.(range(pi / 4, 3pi / 4, length = 51)[1:(end - 1)]) rs = vcat(rs, rs, rs, rs, rs[1]) fig = Figure(size = (900, 300)) @@ -274,37 +274,37 @@ end end @reference_test "Colorbar for recipes" begin - fig, ax, pl = barplot(1:3; color=1:3, colormap=Makie.Categorical(:viridis), figure=(;size=(800, 800))) - Colorbar(fig[1, 2], pl; size=100) + fig, ax, pl = barplot(1:3; color = 1:3, colormap = Makie.Categorical(:viridis), figure = (; size = (800, 800))) + Colorbar(fig[1, 2], pl; size = 100) x = LinRange(-1, 1, 20) y = LinRange(-1, 1, 20) z = LinRange(-1, 1, 20) values = [sin(x[i]) * cos(y[j]) * sin(z[k]) for i in 1:20, j in 1:20, k in 1:20] # TO not make this fail in CairoMakie, we dont actually plot the volume - _f, ax, cp = contour(x, y, z, values; levels=10, colormap=:viridis) - Colorbar(fig[2, 1], cp; size=300) + _f, ax, cp = contour(x, y, z, values; levels = 10, colormap = :viridis) + Colorbar(fig[2, 1], cp; size = 300) - _f, ax, vs = volumeslices(x, y, z, values, colormap=:bluesreds) + _f, ax, vs = volumeslices(x, y, z, values, colormap = :bluesreds) Colorbar(fig[2, 2], vs) # horizontal colorbars - Colorbar(fig[1, 3][2, 1]; limits=(0, 10), colormap=:viridis, - vertical=false) - Colorbar(fig[1, 3][3, 1]; limits=(0, 5), size=25, - colormap=cgrad(:Spectral, 5; categorical=true), vertical=false) - Colorbar(fig[1, 3][4, 1]; limits=(-1, 1), colormap=:heat, vertical=false, flipaxis=false, - highclip=:cyan, lowclip=:red) + Colorbar(fig[1, 3][2, 1]; limits = (0, 10), colormap = :viridis, + vertical = false) + Colorbar(fig[1, 3][3, 1]; limits = (0, 5), size = 25, + colormap = cgrad(:Spectral, 5; categorical = true), vertical = false) + Colorbar(fig[1, 3][4, 1]; limits = (-1, 1), colormap = :heat, vertical = false, flipaxis = false, + highclip = :cyan, lowclip = :red) xs = LinRange(0, 20, 50) ys = LinRange(0, 15, 50) zs = [cos(x) * sin(y) for x in xs, y in ys] ax, hm = contourf(fig[2, 3][1, 1], xs, ys, zs; - colormap=:Spectral, levels=[-1, -0.5, -0.25, 0, 0.25, 0.5, 1]) - Colorbar(fig[2, 3][1, 2], hm; ticks=-1:0.25:1) + colormap = :Spectral, levels = [-1, -0.5, -0.25, 0, 0.25, 0.5, 1]) + Colorbar(fig[2, 3][1, 2], hm; ticks = -1:0.25:1) ax, hm = contourf(fig[3, :][1, 1], xs, ys, zs; - colormap=:Spectral, colorscale=sqrt, levels=[ 0, 0.25, 0.5, 1]) - Colorbar(fig[3, :][1, 2], hm; width=200) + colormap = :Spectral, colorscale = sqrt, levels = [0, 0.25, 0.5, 1]) + Colorbar(fig[3, :][1, 2], hm; width = 200) fig end @@ -313,17 +313,16 @@ end airports = Point2f.(eachrow(readdlm(assetpath("airportlocations.csv")))) # Dont use the full dataset, since WGLMakie seems to time out if it's too big fewer = airports[RNG.rand(1:length(airports), 1000)] - fig, ax, ds = datashader(fewer; async=false) - Colorbar(fig[1, 2], ds; width=100) + fig, ax, ds = datashader(fewer; async = false) + Colorbar(fig[1, 2], ds; width = 100) hidedecorations!(ax) hidespines!(ax) normaldist = RNG.randn(Point2f, 100000) ds1 = normaldist .+ (Point2f(-1, 0),) ds2 = normaldist .+ (Point2f(1, 0),) - ax, pl = datashader(fig[2, :], Dict("a" => ds1, "b" => ds2); async=false) + ax, pl = datashader(fig[2, :], Dict("a" => ds1, "b" => ds2); async = false) hidedecorations!(ax) axislegend(ax) fig end - diff --git a/ReferenceTests/src/tests/primitives.jl b/ReferenceTests/src/tests/primitives.jl index d59149c3822..9d21e4ddfc7 100644 --- a/ReferenceTests/src/tests/primitives.jl +++ b/ReferenceTests/src/tests/primitives.jl @@ -10,10 +10,10 @@ 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, - color=:black + color = :black ) end end @@ -54,7 +54,7 @@ end Point2f(i, j) .* 45, marker = m, markersize = ms, - color=:black + color = :black ) end end @@ -77,7 +77,7 @@ end marker = m, markersize = 30, rotations = rot, - color=:black + color = :black ) scatter!(s, p, color = :red, markersize = 6) end @@ -89,7 +89,7 @@ end s = Scene(size = (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, @@ -122,7 +122,7 @@ end s = Scene(size = (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, @@ -153,14 +153,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(size = (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(size = (100 + 100 * length(pixel_types), 400), camera = campixel!) filename = Makie.assetpath("icon_transparent.png") marker_image = 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, @@ -211,7 +211,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, @@ -329,19 +329,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, @@ -364,11 +364,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 @@ -386,15 +386,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 @@ -406,9 +406,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, color=:black, marker=marker, markersize=markersize, markerspace=:pixel) + scatter!(scene, center, color = :black, marker = marker, markersize = markersize, markerspace = :pixel) font = Makie.defaultfont() charextent = Makie.FreeTypeAbstraction.get_extent(font, marker) @@ -418,18 +418,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(size=(1200, 1200)) + scene = Scene(size = (1200, 1200)) campixel!(scene) # marker is in front, so it should not be smaller than the background rectangle plot_row!(scene, 0, false) @@ -440,26 +440,26 @@ 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, '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, '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 @reference_test "Surface with NaN points" begin # prepare surface data - zs = [x^2 + y^2 for x in range(-2, 0, length=10), y in range(-2, 0, length=10)] + zs = [x^2 + y^2 for x in range(-2, 0, length = 10), y in range(-2, 0, length = 10)] ns = copy(zs) ns[4, 3:6] .= NaN # plot surface - f, a, p = surface(1..10, 1..10, ns, colormap = [:lightblue, :lightblue]) + f, a, p = surface(1 .. 10, 1 .. 10, ns, colormap = [:lightblue, :lightblue]) # plot a wireframe so we can see what's going on, and in which cells. m = Makie.surface2mesh(to_value.(p.converted)...) scatter!(a, m.position, color = isnan.(m.normals), depth_shift = -1f-3) @@ -473,8 +473,8 @@ end lab2 = lab1 # lab2 = L"\frac{a}{b} - \sqrt{b}" # this will not work until #2667 is fixed - barplot(fig[1,1], [1, 2], [0.5, 0.2], bar_labels = [lab1, lab2], flip_labels_at = 0.3, direction=:x) - barplot(fig[1,2], [1, 2], [0.5, 0.2], bar_labels = [lab1, lab2], flip_labels_at = 0.3) + barplot(fig[1, 1], [1, 2], [0.5, 0.2], bar_labels = [lab1, lab2], flip_labels_at = 0.3, direction = :x) + barplot(fig[1, 2], [1, 2], [0.5, 0.2], bar_labels = [lab1, lab2], flip_labels_at = 0.3) fig end @@ -490,10 +490,10 @@ end empty!(ax.scene.lights) hidedecorations!(ax) - heatmap!(ax, 0..0.5, 0..0.5, [i+j for i in 1:10, j in 1:10], transformation = Transformation()) - image!(ax, 0..0.5, 0.5..1, [i+j for i in 1:10, j in 1:10], transformation = Transformation()) + heatmap!(ax, 0 .. 0.5, 0 .. 0.5, [i + j for i in 1:10, j in 1:10], transformation = Transformation()) + image!(ax, 0 .. 0.5, 0.5 .. 1, [i + j for i in 1:10, j in 1:10], transformation = Transformation()) mesh!(ax, Rect2f(0.5, 0.0, 1.0, 0.25), transformation = Transformation(), color = :green) - p = surface!(ax, 0.5..1, 0.25..0.75, [i+j for i in 1:10, j in 1:10], transformation = Transformation()) + p = surface!(ax, 0.5 .. 1, 0.25 .. 0.75, [i + j for i in 1:10, j in 1:10], transformation = Transformation()) translate!(p, Vec3f(0, 0, -20)) poly!(ax, Rect2f(0.5, 0.75, 1.0, 1.0), transformation = Transformation(), color = :blue) @@ -504,4 +504,4 @@ end meshscatter!(ax, [0.1, 0.9], [0.6, 0.7], markersize = 0.05, color = :red, transformation = Transformation()) fig -end \ No newline at end of file +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 b28d814a8ee..fa1ee7159ff 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), colorrange=(0, 1), 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, colorrange=(0, 1), - 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), colorrange = (0, 1), 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, colorrange = (0, 1), + 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!, size=(res, res)) + s = Scene(camera = campixel!, size = (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 @@ -263,18 +263,18 @@ end ax2 = Axis(fig[1, 2]) ax3 = Axis(fig[2, 2]) ax4 = Axis(fig[2, 1]) - scatter!(ax1, 1:10, 1:10; markersize=50, color=1:10) - scatter!(ax2, 1:10, 1:10; markersize=50, color=:red) + scatter!(ax1, 1:10, 1:10; markersize = 50, color = 1:10) + scatter!(ax2, 1:10, 1:10; markersize = 50, color = :red) heatmap!(ax3, -8:0.1:8, 8:0.1:8, (x, y) -> sin(x) + cos(y)) - meshscatter!(ax4, 1:10, 1:10; markersize=1, color=:red) - img1 = colorbuffer(ax1; include_decorations=true) - img2 = colorbuffer(ax2; include_decorations=false) - img3 = colorbuffer(ax3; include_decorations=true) - img4 = colorbuffer(ax4; include_decorations=false) - f, ax5, pl = image(rotr90(img1); axis=(; aspect=DataAspect())) - ax6, pl = image(f[1, 2], rotr90(img2); axis=(; aspect=DataAspect())) - ax7, pl = image(f[2, 2], rotr90(img3); axis=(; aspect=DataAspect())) - ax8, pl = image(f[2, 1], rotr90(img4); axis=(; aspect=DataAspect())) + meshscatter!(ax4, 1:10, 1:10; markersize = 1, color = :red) + img1 = colorbuffer(ax1; include_decorations = true) + img2 = colorbuffer(ax2; include_decorations = false) + img3 = colorbuffer(ax3; include_decorations = true) + img4 = colorbuffer(ax4; include_decorations = false) + f, ax5, pl = image(rotr90(img1); axis = (; aspect = DataAspect())) + ax6, pl = image(f[1, 2], rotr90(img2); axis = (; aspect = DataAspect())) + ax7, pl = image(f[2, 2], rotr90(img3); axis = (; aspect = DataAspect())) + ax8, pl = image(f[2, 1], rotr90(img4); axis = (; aspect = DataAspect())) hidedecorations!(ax5) hidedecorations!(ax6) hidedecorations!(ax7) diff --git a/ReferenceTests/src/tests/specapi.jl b/ReferenceTests/src/tests/specapi.jl index f12a39585ee..ed091177c76 100644 --- a/ReferenceTests/src/tests/specapi.jl +++ b/ReferenceTests/src/tests/specapi.jl @@ -18,40 +18,40 @@ end st = Makie.Stepper(f) sync_step!(st) obs = pl[1] - obs[] = S.GridLayout([S.Axis(; plots=[S.Lines(1:4; color=:black, linewidth=5), S.Scatter(1:4; markersize=20)]) - S.Axis3(; plots=[S.Scatter(Rect3f(Vec3f(0), Vec3f(1)); color=:red, markersize=50)])]) + obs[] = S.GridLayout([S.Axis(; plots = [S.Lines(1:4; color = :black, linewidth = 5), S.Scatter(1:4; markersize = 20)]); + S.Axis3(; plots = [S.Scatter(Rect3f(Vec3f(0), Vec3f(1)); color = :red, markersize = 50)])]) sync_step!(st) obs[] = begin - ax = S.Axis(; plots=[S.Scatter(1:4)]) - ax2 = S.Axis3(; title="Title 0", plots=[S.Scatter(1:4; color=1:4, markersize=20)]) - c = S.Colorbar(; limits=(0, 1), colormap=:heat) + ax = S.Axis(; plots = [S.Scatter(1:4)]) + ax2 = S.Axis3(; title = "Title 0", plots = [S.Scatter(1:4; color = 1:4, markersize = 20)]) + c = S.Colorbar(; limits = (0, 1), colormap = :heat) S.GridLayout([ax ax2 c]) end sync_step!(st) obs[] = begin - p1 = S.Scatter(1:4; markersize=50) - ax = S.Axis(; plots=[p1], title="Title 1") - p2 = S.Scatter(2:4; color=1:3, markersize=30) - ax2 = S.Axis3(; plots=[p2]) - c = S.Colorbar(; limits=(2, 10), colormap=:viridis, width=50) + p1 = S.Scatter(1:4; markersize = 50) + ax = S.Axis(; plots = [p1], title = "Title 1") + p2 = S.Scatter(2:4; color = 1:3, markersize = 30) + ax2 = S.Axis3(; plots = [p2]) + c = S.Colorbar(; limits = (2, 10), colormap = :viridis, width = 50) S.GridLayout([ax ax2 c]) end sync_step!(st) - ax1 = S.Axis(; plots=[S.Scatter(1:4; markersize=20), S.Lines(1:4; color=:darkred, linewidth=6)]) - ax2 = S.Axis3(; plots=[S.Scatter(Rect3f(Vec3f(0), Vec3f(1)); color=(:red, 0.5), markersize=30)]) + ax1 = S.Axis(; plots = [S.Scatter(1:4; markersize = 20), S.Lines(1:4; color = :darkred, linewidth = 6)]) + ax2 = S.Axis3(; plots = [S.Scatter(Rect3f(Vec3f(0), Vec3f(1)); color = (:red, 0.5), markersize = 30)]) obs[] = S.GridLayout([ax1 ax2]) sync_step!(st) - elem_1 = [LineElement(; color=:red, linestyle=nothing), - MarkerElement(; color=:blue, marker='x', markersize=15, - strokecolor=:black)] + elem_1 = [LineElement(; color = :red, linestyle = nothing), + MarkerElement(; color = :blue, marker = 'x', markersize = 15, + strokecolor = :black)] - elem_2 = [PolyElement(; color=:red, strokecolor=:blue, strokewidth=1), - LineElement(; color=:black, linestyle=:dash)] + elem_2 = [PolyElement(; color = :red, strokecolor = :blue, strokewidth = 1), + LineElement(; color = :black, linestyle = :dash)] - elem_3 = LineElement(; color=:green, linestyle=nothing, - points=Point2f[(0, 0), (0, 1), (1, 0), (1, 1)]) + elem_3 = LineElement(; color = :green, linestyle = nothing, + points = Point2f[(0, 0), (0, 1), (1, 0), (1, 1)]) obs[] = begin S.GridLayout(S.Legend([elem_1, elem_2, elem_3], ["elem 1", "elem 2", "elem 3"], "Legend Title")) @@ -75,9 +75,9 @@ struct PlotGrid end function Makie.convert_arguments(::Type{<:AbstractPlot}, obj::PlotGrid) - plots = [S.Lines(1:4; linewidth=5, color=Cycled(1)), - S.Lines(2:5; linewidth=7, color=Cycled(2))] - axes = [S.Axis(; plots=plots) for i in 1:obj.nplots[1], j in 1:obj.nplots[2]] + plots = [S.Lines(1:4; linewidth = 5, color = Cycled(1)), + S.Lines(2:5; linewidth = 7, color = Cycled(2))] + axes = [S.Axis(; plots = plots) for i in 1:obj.nplots[1], j in 1:obj.nplots[2]] return S.GridLayout(axes) end @@ -88,10 +88,10 @@ end function Makie.convert_arguments(::Type{<:AbstractPlot}, obj::LineScatter, data...) plots = PlotSpec[] if obj.show_lines - push!(plots, S.Lines(data...; linewidth=5)) + push!(plots, S.Lines(data...; linewidth = 5)) end if obj.show_scatter - push!(plots, S.Scatter(data...; markersize=20)) + push!(plots, S.Scatter(data...; markersize = 20)) end return plots end diff --git a/ReferenceTests/src/tests/text.jl b/ReferenceTests/src/tests/text.jl index 036f7af8ab1..6fc54adfc89 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,20 +53,20 @@ end @reference_test "multi_strings_multi_positions" begin scene = Scene(camera = campixel!, size = (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, color=:black) + scatter!(scene, points, marker = :circle, markersize = 10px, color = :black) text!(scene, points, text = strings, align = aligns, rotation = rotations, color = [(:black, alpha) for alpha in LinRange(0.3, 0.7, length(points))]) @@ -78,7 +78,7 @@ end scene = Scene(camera = campixel!, size = (800, 800)) points = [Point(x, y) .* 200 for x in 1:3 for y in 1:3] - scatter!(scene, points, marker = :circle, markersize = 10px, color=:black) + scatter!(scene, points, marker = :circle, markersize = 10px, color = :black) symbols = (:left, :center, :right) @@ -101,7 +101,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 @@ -112,8 +112,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 @@ -123,8 +123,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 @@ -138,7 +138,7 @@ end @reference_test "single_boundingboxes" begin scene = Scene(camera = campixel!, size = (800, 800)) - for a in pi/4:pi/2:7pi/4 + for a in (pi / 4):(pi / 2):(7pi / 4) t = text!(scene, "makie", @@ -171,12 +171,12 @@ 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, markerspace = :data, - axis=(; type=LScene) + axis = (; type = LScene) ) end @@ -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 @@ -283,7 +283,7 @@ end position = Point2f(50, 50), rotation = 0.0, markerspace = :data) - wireframe!(s, boundingbox(t), color=:black) + wireframe!(s, boundingbox(t), color = :black) 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(size=(600, 500)) + fig = Figure(size = (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 @@ -379,4 +379,4 @@ end p[1][] = "-!ħ█?-" # "!ħ█?" are all new symbols Makie.step!(st) st -end \ No newline at end of file +end diff --git a/ReferenceTests/src/tests/updating.jl b/ReferenceTests/src/tests/updating.jl index 3c362fbea7f..3821937d825 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=(size=(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 = (size = (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) @@ -104,7 +104,7 @@ end @reference_test "deletion" begin f = Figure() - l = Legend(f[1, 1], [LineElement(color=:red)], ["Line"]) + l = Legend(f[1, 1], [LineElement(color = :red)], ["Line"]) s = display(f) @test f.scene.current_screens[1] === s @test f.scene.children[1].current_screens[1] === s @@ -113,13 +113,13 @@ end @test f.scene.current_screens[1] === s ## legend should be gone ax = Axis(f[1, 1]) - scatter!(ax, 1:4, markersize=200, color=1:4) + scatter!(ax, 1:4, markersize = 200, color = 1:4) f end @reference_test "deletion and observable args" begin obs = Observable(1:5) - f, ax, pl = scatter(obs; markersize=150) + f, ax, pl = scatter(obs; markersize = 150) s = display(f) # So, for GLMakie it will be 2, since we register an additional listener for # State changes for the on demand renderloop @@ -135,8 +135,8 @@ end @reference_test "interactive colorscale - mesh" begin brain = load(assetpath("brain.stl")) color = [abs(tri[1][2]) for tri in brain for i in 1:3] - f, ax, m = mesh(brain; color, colorscale=identity) - mesh(f[1, 2], brain; color, colorscale=log10) + f, ax, m = mesh(brain; color, colorscale = identity) + mesh(f[1, 2], brain; color, colorscale = log10) st = Stepper(f) Makie.step!(st) m.colorscale = log10 @@ -145,9 +145,9 @@ end @reference_test "interactive colorscale - heatmap" begin data = exp.(abs.(RNG.randn(20, 20))) - f, ax, hm = heatmap(data, colorscale=log10, axis=(; title="log10")) + f, ax, hm = heatmap(data, colorscale = log10, axis = (; title = "log10")) Colorbar(f[1, 2], hm) - ax2, hm2 = heatmap(f[1, 3], data, colorscale=log10, axis=(; title="log10")) + ax2, hm2 = heatmap(f[1, 3], data, colorscale = log10, axis = (; title = "log10")) st = Stepper(f) Makie.step!(st) @@ -164,9 +164,9 @@ end x = RNG.randn(1_000) y = RNG.randn(1_000) f = Figure() - hexbin(f[1, 1], x, y; axis=(aspect=DataAspect(), title="identity")) - ax, hb = hexbin(f[1, 2], x, y; colorscale=log, axis=(aspect=DataAspect(), title="log")) - Colorbar(f[1, end+1], hb) + hexbin(f[1, 1], x, y; axis = (aspect = DataAspect(), title = "identity")) + ax, hb = hexbin(f[1, 2], x, y; colorscale = log, axis = (aspect = DataAspect(), title = "log")) + Colorbar(f[1, end + 1], hb) st = Stepper(f) Makie.step!(st) hb.colorscale = identity diff --git a/ReferenceUpdater/src/ReferenceUpdater.jl b/ReferenceUpdater/src/ReferenceUpdater.jl index cdb9d003cf8..9388291acd1 100644 --- a/ReferenceUpdater/src/ReferenceUpdater.jl +++ b/ReferenceUpdater/src/ReferenceUpdater.jl @@ -24,4 +24,4 @@ include("image_download.jl") basedir(files...) = normpath(joinpath(@__DIR__, "..", files...)) -end \ No newline at end of file +end diff --git a/ReferenceUpdater/src/image_download.jl b/ReferenceUpdater/src/image_download.jl index 063edf9860b..7519259b5f1 100644 --- a/ReferenceUpdater/src/image_download.jl +++ b/ReferenceUpdater/src/image_download.jl @@ -11,7 +11,7 @@ function last_major_version() return "v" * string(VersionNumber(version.major, version.minor)) end -function upload_reference_images(path=basedir("recorded"), tag=last_major_version()) +function upload_reference_images(path = basedir("recorded"), tag = last_major_version()) mktempdir() do dir tarfile = joinpath(dir, "reference_images.tar") Tar.create(path, tarfile) diff --git a/ReferenceUpdater/src/local_server.jl b/ReferenceUpdater/src/local_server.jl index 854ba474fad..40b4baaad38 100644 --- a/ReferenceUpdater/src/local_server.jl +++ b/ReferenceUpdater/src/local_server.jl @@ -1,10 +1,10 @@ -const URL_CACHE = Dict{String, String}() +const URL_CACHE = Dict{String,String}() function serve_update_page_from_dir(folder) folder = realpath(folder) @assert isdir(folder) "$folder is not a valid directory." - + router = HTTP.Router() function receive_update(req) @@ -98,7 +98,7 @@ function serve_update_page(; commit = nothing, pr = nothing) checkruns = filter(checksinfo["check_runs"]) do checkrun name = checkrun["name"] id = checkrun["id"] - + if name == "Merge artifacts" job = JSON3.read(authget("https://api.github.com/repos/MakieOrg/Makie.jl/actions/jobs/$(id)").body) run = JSON3.read(authget(job["run_url"]).body) @@ -155,15 +155,15 @@ function serve_update_page(; commit = nothing, pr = nothing) end function unzip(file, exdir = "") - fileFullPath = isabspath(file) ? file : joinpath(pwd(),file) + fileFullPath = isabspath(file) ? file : joinpath(pwd(), file) basePath = dirname(fileFullPath) - outPath = (exdir == "" ? basePath : (isabspath(exdir) ? exdir : joinpath(pwd(),exdir))) + outPath = (exdir == "" ? basePath : (isabspath(exdir) ? exdir : joinpath(pwd(), exdir))) isdir(outPath) ? "" : mkdir(outPath) @info "Extracting zip file $file to $outPath" zarchive = ZipFile.Reader(fileFullPath) for f in zarchive.files - fullFilePath = joinpath(outPath,f.name) - if (endswith(f.name,"/") || endswith(f.name,"\\")) + fullFilePath = joinpath(outPath, f.name) + if (endswith(f.name, "/") || endswith(f.name, "\\")) mkdir(fullFilePath) else mkpath(dirname(fullFilePath)) diff --git a/WGLMakie/src/WGLMakie.jl b/WGLMakie/src/WGLMakie.jl index 8eb0d8089b7..58b3c1a715f 100644 --- a/WGLMakie/src/WGLMakie.jl +++ b/WGLMakie/src/WGLMakie.jl @@ -43,7 +43,7 @@ include("meshes.jl") include("imagelike.jl") include("picking.jl") -const LAST_INLINE = Base.RefValue{Union{Automatic, Bool}}(Makie.automatic) +const LAST_INLINE = Base.RefValue{Union{Automatic,Bool}}(Makie.automatic) """ WGLMakie.activate!(; screen_config...) @@ -55,7 +55,7 @@ Note, that the `screen_config` can also be set permanently via `Makie.set_theme! $(Base.doc(ScreenConfig)) """ -function activate!(; inline::Union{Automatic,Bool}=LAST_INLINE[], screen_config...) +function activate!(; inline::Union{Automatic,Bool} = LAST_INLINE[], screen_config...) Makie.inline!(inline) LAST_INLINE[] = inline Makie.set_active_backend!(WGLMakie) @@ -86,7 +86,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 01c7cf1629a..04c567d2bb0 100644 --- a/WGLMakie/src/display.jl +++ b/WGLMakie/src/display.jl @@ -13,7 +13,7 @@ struct ScreenConfig scalefactor::Union{Nothing,Float64} resize_to_body::Bool function ScreenConfig(framerate::Number, resize_to::Any, px_per_unit::Union{Number,Automatic,Nothing}, - scalefactor::Union{Number,Automatic,Nothing}, resize_to_body::Union{Nothing,Bool}) + scalefactor::Union{Number,Automatic,Nothing}, resize_to_body::Union{Nothing,Bool}) if px_per_unit isa Automatic px_per_unit = nothing end @@ -58,7 +58,7 @@ mutable struct Screen <: Makie.MakieScreen end end -function scene_already_displayed(screen::Screen, scene=screen.scene) +function scene_already_displayed(screen::Screen, scene = screen.scene) scene === nothing && return false screen.scene === scene || return false screen.canvas === nothing && return false @@ -139,15 +139,18 @@ function Base.show(io::IO, screen::Screen) ppu = c.px_per_unit sf = c.scalefactor three_str = sprint(io -> show(io, MIME"text/plain"(), screen.plot_initialized)) - return print(io, """WGLMakie.Screen( - framerate = $(c.framerate), - resize_to = $(c.resize_to), - px_per_unit = $(isnothing(ppu) ? :automatic : ppu), - scalefactor = $(isnothing(sf) ? :automatic : sf), - session = $(isnothing(screen.session) ? :nothing : isopen(screen.session)), - three = $(three_str), - scene = $(isnothing(screen.scene) ? :nothing : screen.scene), - )""") + return print( + io, + """WGLMakie.Screen( + framerate = $(c.framerate), + resize_to = $(c.resize_to), + px_per_unit = $(isnothing(ppu) ? :automatic : ppu), + scalefactor = $(isnothing(sf) ? :automatic : sf), + session = $(isnothing(screen.session) ? :nothing : isopen(screen.session)), + three = $(three_str), + scene = $(isnothing(screen.scene) ? :nothing : screen.scene), +)""" + ) end # Resizing the scene is enough for WGLMakie @@ -169,7 +172,7 @@ end for M in Makie.WEB_MIMES @eval begin function Makie.backend_show(screen::Screen, io::IO, m::$M, scene::Scene) - inline_display = App(title="WGLMakie") do session::Session + inline_display = App(title = "WGLMakie") do session::Session return render_with_init(screen, session, scene) end Base.show(io, m, inline_display) @@ -189,8 +192,8 @@ function Base.size(screen::Screen) return size(screen.scene) end -function get_screen_session(screen::Screen; timeout=100, - error::Union{Nothing,String}=nothing)::Union{Nothing,Session} +function get_screen_session(screen::Screen; timeout = 100, + error::Union{Nothing,String} = nothing)::Union{Nothing,Session} function throw_error(status) if !isnothing(error) message = "Can't get three: $(status)\n$(error)" @@ -205,12 +208,12 @@ function get_screen_session(screen::Screen; timeout=100, throw_error("Screen Session uninitialized. Not yet displayed? Session status: $(screen.session.status)") return nothing end - success = Bonito.wait_for_ready(screen.session; timeout=timeout) + success = Bonito.wait_for_ready(screen.session; timeout = timeout) if success !== :success throw_error("Timed out waiting for session to get ready") return nothing end - success = Bonito.wait_for(() -> isready(screen.plot_initialized); timeout=timeout) + success = Bonito.wait_for(() -> isready(screen.plot_initialized); timeout = timeout) # Throw error if error message specified if success !== :success throw_error("Timed out waiting $(timeout)s for session to get initilize") @@ -246,13 +249,13 @@ function Base.display(screen::Screen, scene::Scene; unused...) if scene_already_displayed(screen, scene) return screen end - app = App(title="WGLMakie") do session + app = App(title = "WGLMakie") do session return render_with_init(screen, session, scene) end display(app) Bonito.wait_for_ready(screen.session) # wait for plot to be full initialized, so that operations don't get racy (e.g. record/RamStepper & friends) - get_screen_session(screen; error="Waiting for plot to be initialized in display") + get_screen_session(screen; error = "Waiting for plot to be initialized in display") return screen end @@ -266,7 +269,7 @@ function session2image(session::Session, scene::Scene) }) }() """ - picture_base64 = Bonito.evaljs_value(session, to_data; timeout=100) + picture_base64 = Bonito.evaljs_value(session, to_data; timeout = 100) picture_base64 = replace(picture_base64, "data:image/png;base64," => "") bytes = Bonito.Base64.base64decode(picture_base64) return PNGFiles.load(IOBuffer(bytes)) @@ -276,7 +279,7 @@ function Makie.colorbuffer(screen::Screen) if isnothing(screen.session) Base.display(screen, screen.scene) end - session = get_screen_session(screen; error="Not able to show scene in a browser") + session = get_screen_session(screen; error = "Not able to show scene in a browser") return session2image(session, screen.scene) end @@ -293,16 +296,19 @@ function insert_scene!(session::Session, screen::Screen, scene::Scene) parent = scene.parent parent_uuid = js_uuid(parent) err = "Cant find scene js_uuid(scene) == $(parent_uuid)" - evaljs_value(session, js""" - $(WGL).then(WGL=> { - const parent = WGL.find_scene($(parent_uuid)); - if (!parent) { - throw new Error($(err)) - } - const new_scene = WGL.deserialize_scene($scene_ser, parent.screen); - parent.scene_children.push(new_scene); - }) - """) + evaljs_value( + session, + js""" +$(WGL).then(WGL=> { + const parent = WGL.find_scene($(parent_uuid)); + if (!parent) { + throw new Error($(err)) + } + const new_scene = WGL.deserialize_scene($scene_ser, parent.screen); + parent.scene_children.push(new_scene); +}) +""" + ) mark_as_displayed!(screen, scene) return false end @@ -317,12 +323,12 @@ function insert_plot!(session::Session, scene::Scene, @nospecialize(plot::Plot)) $(WGL).then(WGL=> { WGL.insert_plot($(js_uuid(scene)), $plot_data); })""" - Bonito.evaljs_value(plot_sub, js; timeout=50) + Bonito.evaljs_value(plot_sub, js; timeout = 50) return end function Base.insert!(screen::Screen, scene::Scene, @nospecialize(plot::Plot)) - session = get_screen_session(screen; error="Plot needs to be displayed to insert additional plots") + session = get_screen_session(screen; error = "Plot needs to be displayed to insert additional plots") if js_uuid(scene) in screen.displayed_scenes insert_plot!(session, scene, plot) else @@ -343,23 +349,26 @@ function Base.insert!(screen::Screen, scene::Scene, @nospecialize(plot::Plot)) end function delete_js_objects!(screen::Screen, plot_uuids::Vector{String}, - session::Union{Nothing,Session}) + session::Union{Nothing,Session}) main_session = get_screen_session(screen) isnothing(main_session) && return # if no session we haven't displayed and dont need to delete isready(main_session) || return - Bonito.evaljs(main_session, js""" - $(WGL).then(WGL=> { - WGL.delete_plots($(plot_uuids)); - })""") + Bonito.evaljs( + main_session, + js""" +$(WGL).then(WGL=> { + WGL.delete_plots($(plot_uuids)); +})""" + ) !isnothing(session) && close(session) return end -function all_plots_scenes(scene::Scene; scene_uuids=String[], plots=Plot[]) +function all_plots_scenes(scene::Scene; scene_uuids = String[], plots = Plot[]) push!(scene_uuids, js_uuid(scene)) append!(plots, scene.plots) for child in scene.children - all_plots_scenes(child; plots=plots, scene_uuids=scene_uuids) + all_plots_scenes(child; plots = plots, scene_uuids = scene_uuids) end return scene_uuids, plots end @@ -375,10 +384,13 @@ function delete_js_objects!(screen::Screen, scene::Scene) close(wgl_session) end end - Bonito.evaljs(session, js""" - $(WGL).then(WGL=> { - WGL.delete_scenes($scene_uuids, $(js_uuid.(plots))); - })""") + Bonito.evaljs( + session, + js""" +$(WGL).then(WGL=> { + WGL.delete_scenes($scene_uuids, $(js_uuid.(plots))); +})""" + ) return end @@ -393,10 +405,10 @@ end function LockfreeQueue{T}(execute_job::F) where {T,F} return LockfreeQueue{T,F}(T[], - T[], - Threads.Atomic{Int}(1), - Base.RefValue{Union{Nothing,Task}}(nothing), - execute_job) + T[], + Threads.Atomic{Int}(1), + Base.RefValue{Union{Nothing,Task}}(nothing), + execute_job) end function run_jobs!(queue::LockfreeQueue) diff --git a/WGLMakie/src/events.jl b/WGLMakie/src/events.jl index bd129e83d53..6f8d923ebcd 100644 --- a/WGLMakie/src/events.jl +++ b/WGLMakie/src/events.jl @@ -106,7 +106,7 @@ function connect_scene_events!(scene::Scene, comm::Observable) resize!(scene, tuple(resize...)) end catch err - @warn "Error in window event callback" exception=(err, Base.catch_backtrace()) + @warn "Error in window event callback" exception = (err, Base.catch_backtrace()) end return end diff --git a/WGLMakie/src/imagelike.jl b/WGLMakie/src/imagelike.jl index e5417f19fe7..bc93b98da90 100644 --- a/WGLMakie/src/imagelike.jl +++ b/WGLMakie/src/imagelike.jl @@ -9,7 +9,7 @@ nothing_or_color(c::Nothing) = RGBAf(0, 0, 0, 1) 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) # TODO: Use Makie.surface2mesh ps = lift(grid, plot, px, py, pz, transform_func_obs(plot), get(plot, :space, :data)) @@ -24,7 +24,7 @@ function create_shader(mscene::Scene, plot::Surface) uv = Buffer(lift(plot, rect) do r Nx, Ny = r.nvertices f = Vec2f(1 / Nx, 1 / Ny) - [f .* Vec2f(0.5 + i, 0.5 + j) for j in Ny-1:-1:0 for i in 0:Nx-1] + [f .* Vec2f(0.5 + i, 0.5 + j) for j in (Ny - 1):-1:0 for i in 0:(Nx - 1)] end) normals = Buffer(lift(Makie.nan_aware_normals, plot, ps, fs)) @@ -34,7 +34,7 @@ function create_shader(mscene::Scene, plot::Surface) return draw_mesh(mscene, per_vertex, plot, uniforms) end -function create_shader(mscene::Scene, plot::Union{Heatmap, Image}) +function create_shader(mscene::Scene, plot::Union{Heatmap,Image}) mesh = limits_to_uvmesh(plot) uniforms = Dict( :normals => Vec3f(0), @@ -69,7 +69,7 @@ function create_shader(mscene::Scene, plot::Volume) - uniforms = Dict{Symbol, Any}( + uniforms = Dict{Symbol,Any}( :modelinv => modelinv, :isovalue => lift(Float32, plot, plot.isovalue), :isorange => lift(Float32, plot, plot.isorange), @@ -90,7 +90,7 @@ function create_shader(mscene::Scene, plot::Volume) :object_id => UInt32(0) ) - handle_color!(plot, uniforms, nothing, :volumedata; permute_tex=false) + handle_color!(plot, uniforms, nothing, :volumedata; permute_tex = false) return Program(WebGL(), lasset("volume.vert"), lasset("volume.frag"), box, uniforms) end @@ -127,8 +127,8 @@ end 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; ignore_equal_values=true) - py = map((y, z) -> xy_convert(y, size(z, 2)), py, pz; ignore_equal_values=true) + px = map((x, z) -> xy_convert(x, size(z, 1)), px, pz; ignore_equal_values = true) + py = map((y, z) -> xy_convert(y, size(z, 2)), py, pz; ignore_equal_values = true) # Special path for ranges of length 2 which # can be displayed as a rectangle t = Makie.transform_func_obs(plot)[] @@ -148,7 +148,7 @@ function limits_to_uvmesh(plot) function grid(x, y, trans, space) return Makie.matrix_grid(p -> apply_transform(trans, p, space), x, y, zeros(length(x), length(y))) end - resolution = lift((x, y) -> (length(x), length(y)), plot, px, py; ignore_equal_values=true) + resolution = lift((x, y) -> (length(x), length(y)), plot, px, py; ignore_equal_values = true) positions = Buffer(lift(grid, plot, px, py, t, get(plot, :space, :data))) faces = Buffer(lift(fast_faces, plot, resolution)) uv = Buffer(lift(fast_uv, plot, resolution)) diff --git a/WGLMakie/src/lines.jl b/WGLMakie/src/lines.jl index a69e160135b..84b058bacf5 100644 --- a/WGLMakie/src/lines.jl +++ b/WGLMakie/src/lines.jl @@ -1,4 +1,4 @@ -function serialize_three(scene::Scene, plot::Union{Lines, LineSegments}) +function serialize_three(scene::Scene, plot::Union{Lines,LineSegments}) Makie.@converted_attribute plot (linewidth,) uniforms = Dict( :model => plot.model, @@ -19,9 +19,9 @@ function serialize_three(scene::Scene, plot::Union{Lines, LineSegments}) uniforms[name] = RGBAf(0, 0, 0, 0) end end - points_transformed = lift(apply_transform, plot, transform_func_obs(plot), plot[1], plot.space) + points_transformed = lift(apply_transform, plot, transform_func_obs(plot), plot[1], plot.space) positions = lift(serialize_buffer_attribute, plot, points_transformed) - attributes = Dict{Symbol, Any}(:linepoint => positions) + attributes = Dict{Symbol,Any}(:linepoint => positions) for (name, attr) in [:color => color, :linewidth => linewidth] if Makie.is_scalar_attribute(to_value(attr)) uniforms[Symbol("$(name)_start")] = attr diff --git a/WGLMakie/src/meshes.jl b/WGLMakie/src/meshes.jl index ded9dee2ab7..918a00f020b 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, @nospecialize(p)) @@ -17,7 +17,7 @@ function converted_attribute(plot::AbstractPlot, key::Symbol) end end -function handle_color!(plot, uniforms, buffers, uniform_color_name = :uniform_color; permute_tex=true) +function handle_color!(plot, uniforms, buffers, uniform_color_name = :uniform_color; permute_tex = true) color = plot.calculated_colors minfilter = to_value(get(plot, :interpolate, true)) ? :linear : :nearest @@ -29,15 +29,15 @@ function handle_color!(plot, uniforms, buffers, uniform_color_name = :uniform_co buffers[:color] = Buffer(color) elseif color[] isa Makie.AbstractPattern uniforms[:pattern] = true - uniforms[uniform_color_name] = Sampler(convert_text(color); minfilter=minfilter) + uniforms[uniform_color_name] = Sampler(convert_text(color); minfilter = minfilter) elseif color[] isa AbstractMatrix - uniforms[uniform_color_name] = Sampler(convert_text(color); minfilter=minfilter) + uniforms[uniform_color_name] = Sampler(convert_text(color); minfilter = minfilter) elseif color[] isa Makie.ColorMapping if color[].color_scaled[] isa AbstractVector buffers[:color] = Buffer(color[].color_scaled) else color_scaled = convert_text(color[].color_scaled) - uniforms[uniform_color_name] = Sampler(color_scaled; minfilter=minfilter) + uniforms[uniform_color_name] = Sampler(color_scaled; minfilter = minfilter) end uniforms[:colormap] = Sampler(color[].colormap) uniforms[:colorrange] = color[].colorrange_scaled @@ -58,9 +58,9 @@ end lift_or(f, p, x) = f(x) lift_or(f, @nospecialize(p), x::Observable) = lift(f, p, x) -function draw_mesh(mscene::Scene, per_vertex, plot, uniforms; permute_tex=true) +function draw_mesh(mscene::Scene, per_vertex, plot, uniforms; permute_tex = true) filter!(kv -> !(kv[2] isa Function), uniforms) - handle_color!(plot, uniforms, per_vertex; permute_tex=permute_tex) + handle_color!(plot, uniforms, per_vertex; permute_tex = permute_tex) get!(uniforms, :pattern, false) get!(uniforms, :model, plot.model) @@ -123,5 +123,5 @@ function create_shader(scene::Scene, plot::Makie.Mesh) attributes[:faces] = faces attributes[:positions] = positions - return draw_mesh(scene, attributes, plot, uniforms; permute_tex=false) + return draw_mesh(scene, attributes, plot, uniforms; permute_tex = false) end diff --git a/WGLMakie/src/particles.jl b/WGLMakie/src/particles.jl index ae087c43a02..dbed679c487 100644 --- a/WGLMakie/src/particles.jl +++ b/WGLMakie/src/particles.jl @@ -93,7 +93,7 @@ function create_shader(scene::Scene, plot::MeshScatter) uniform_dict[:shading] = map(x -> x != NoShading, plot.shading) 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 @@ -105,18 +105,18 @@ using Makie: to_spritemarker Optimization to just send the texture atlas one time to JS and then look it up from there in wglmakie.js, instead of uploading this texture 10x in every plot. """ -struct NoDataTextureAtlas <: ShaderAbstractions.AbstractSampler{Float16, 2} - dims::NTuple{2, Int} +struct NoDataTextureAtlas <: ShaderAbstractions.AbstractSampler{Float16,2} + dims::NTuple{2,Int} end function serialize_three(fta::NoDataTextureAtlas) tex = Dict(:type => "Sampler", :data => "texture_atlas", - :size => [fta.dims...], :three_format => three_format(Float16), - :three_type => three_type(Float16), - :minFilter => three_filter(:linear), - :magFilter => three_filter(:linear), - :wrapS => "RepeatWrapping", - :anisotropy => 16f0) + :size => [fta.dims...], :three_format => three_format(Float16), + :three_type => three_type(Float16), + :minFilter => three_filter(:linear), + :magFilter => three_filter(:linear), + :wrapS => "RepeatWrapping", + :anisotropy => 16f0) tex[:wrapT] = "RepeatWrapping" return tex end @@ -124,7 +124,7 @@ end function scatter_shader(scene::Scene, attributes, plot) # 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 @@ -160,7 +160,7 @@ function scatter_shader(scene::Scene, attributes, plot) end color_keys = Set([:color, :colormap, :highclip, :lowclip, :nan_color, :colorrange, :colorscale, - :calculated_colors]) + :calculated_colors]) for (k, v) in uniforms k in IGNORE_KEYS && continue @@ -170,7 +170,7 @@ function scatter_shader(scene::Scene, attributes, plot) if !isnothing(marker) get!(uniform_dict, :shape_type) do - return lift(plot, marker; ignore_equal_values=true) do marker + return lift(plot, marker; ignore_equal_values = true) do marker return Cint(Makie.marker_to_sdf_shape(to_spritemarker(marker))) end end @@ -209,7 +209,7 @@ function scatter_shader(scene::Scene, attributes, plot) get!(uniform_dict, :glowcolor, RGBAf(0, 0, 0, 0)) return InstancedProgram(WebGL(), lasset("sprites.vert"), lasset("sprites.frag"), - instance, VertexArray(; per_instance...), uniform_dict) + instance, VertexArray(; per_instance...), uniform_dict) end function create_shader(scene::Scene, plot::Scatter) @@ -217,7 +217,7 @@ function create_shader(scene::Scene, plot::Scatter) attributes = copy(plot.attributes.attributes) space = get(attributes, :space, :data) attributes[:preprojection] = Mat4f(I) # calculate this in JS - attributes[:pos] = lift(apply_transform, plot, transform_func_obs(plot), plot[1], space) + attributes[:pos] = lift(apply_transform, plot, transform_func_obs(plot), plot[1], space) quad_offset = get(attributes, :marker_offset, Observable(Vec2f(0))) attributes[:marker_offset] = Vec3f(0) @@ -236,7 +236,7 @@ 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] transfunc = Makie.transform_func_obs(plot) pos = plot.position @@ -244,7 +244,7 @@ function create_shader(scene::Scene, plot::Makie.Text{<:Tuple{<:Union{<:Makie.Gl offset = plot.offset atlas = wgl_texture_atlas() - glyph_data = lift(plot, pos, glyphcollection, offset, transfunc, space; ignore_equal_values=true) do pos, gc, offset, transfunc, space + glyph_data = lift(plot, pos, glyphcollection, offset, transfunc, space; ignore_equal_values = true) do pos, gc, offset, transfunc, space Makie.text_quads(atlas, pos, to_value(gc), offset, transfunc, space) end diff --git a/WGLMakie/src/picking.jl b/WGLMakie/src/picking.jl index 38a4f3fc8e6..27249f0b321 100644 --- a/WGLMakie/src/picking.jl +++ b/WGLMakie/src/picking.jl @@ -2,12 +2,15 @@ function pick_native(screen::Screen, rect::Rect2i) (x, y) = minimum(rect) (w, h) = widths(rect) - session = get_screen_session(screen; error="Can't do picking!") + session = get_screen_session(screen; error = "Can't do picking!") scene = screen.scene - picking_data = Bonito.evaljs_value(session, js""" - Promise.all([$(WGL), $(scene)]).then(([WGL, scene]) => WGL.pick_native_matrix(scene, $x, $y, $w, $h)) - """) - empty = Matrix{Tuple{Union{Nothing, AbstractPlot}, Int}}(undef, 0, 0) + picking_data = Bonito.evaljs_value( + session, + js""" + Promise.all([$(WGL), $(scene)]).then(([WGL, scene]) => WGL.pick_native_matrix(scene, $x, $y, $w, $h)) +""" + ) + empty = Matrix{Tuple{Union{Nothing,AbstractPlot},Int}}(undef, 0, 0) if isnothing(picking_data) return empty end @@ -35,10 +38,13 @@ function Makie.pick_closest(scene::Scene, screen::Screen, xy, range::Integer) # isopen(screen) || return (nothing, 0) xy_vec = Cint[round.(Cint, xy)...] range = round(Int, range) - session = get_screen_session(screen; error="Can't do picking!") - selection = Bonito.evaljs_value(session, js""" - Promise.all([$(WGL), $(scene)]).then(([WGL, scene]) => WGL.pick_closest(scene, $(xy_vec), $(range))) - """) + session = get_screen_session(screen; error = "Can't do picking!") + selection = Bonito.evaljs_value( + session, + js""" + Promise.all([$(WGL), $(scene)]).then(([WGL, scene]) => WGL.pick_closest(scene, $(xy_vec), $(range))) +""" + ) lookup = plot_lookup(scene) return (lookup[selection[1]], selection[2] + 1) end @@ -48,10 +54,13 @@ function Makie.pick_sorted(scene::Scene, screen::Screen, xy, range) xy_vec = Cint[round.(Cint, xy)...] range = round(Int, range) - session = get_screen_session(screen; error="Can't do picking!") - selection = Bonito.evaljs_value(session, js""" - Promise.all([$(WGL), $(scene)]).then(([WGL, scene]) => WGL.pick_sorted(scene, $(xy_vec), $(range))) - """) + session = get_screen_session(screen; error = "Can't do picking!") + selection = Bonito.evaljs_value( + session, + js""" + Promise.all([$(WGL), $(scene)]).then(([WGL, scene]) => WGL.pick_sorted(scene, $(xy_vec), $(range))) +""" + ) isnothing(selection) && return Tuple{Union{Nothing,AbstractPlot},Int}[] lookup = plot_lookup(scene) return map(selection) do (plot_id, index) @@ -101,12 +110,12 @@ struct ToolTip scene::Scene callback::Bonito.JSCode plot_uuids::Vector{String} - function ToolTip(figlike, callback; plots=nothing) + function ToolTip(figlike, callback; plots = nothing) scene = Makie.get_scene(figlike) if isnothing(plots) plots = scene.plots end - all_plots = js_uuid.(filter!(x-> x.inspectable[], Makie.collect_atomic_plots(plots))) + all_plots = js_uuid.(filter!(x -> x.inspectable[], Makie.collect_atomic_plots(plots))) new(scene, callback, all_plots) end end @@ -115,13 +124,16 @@ const POPUP_CSS = Bonito.Asset(joinpath(@__DIR__, "popup.css")) function Bonito.jsrender(session::Session, tt::ToolTip) scene = tt.scene - popup = DOM.div("", class="popup") - Bonito.evaljs(session, js""" - $(scene).then(scene => { - const plots_to_pick = new Set($(tt.plot_uuids)); - const callback = $(tt.callback); - WGL.register_popup($popup, scene, plots_to_pick, callback) - }) - """) + popup = DOM.div("", class = "popup") + Bonito.evaljs( + session, + js""" + $(scene).then(scene => { + const plots_to_pick = new Set($(tt.plot_uuids)); + const callback = $(tt.callback); + WGL.register_popup($popup, scene, plots_to_pick, callback) + }) +""" + ) return DOM.span(Bonito.jsrender(session, POPUP_CSS), popup) end diff --git a/WGLMakie/src/precompiles.jl b/WGLMakie/src/precompiles.jl index b6be76a9107..a29fe155727 100644 --- a/WGLMakie/src/precompiles.jl +++ b/WGLMakie/src/precompiles.jl @@ -9,7 +9,7 @@ macro compile(block) # while precompiling # So we just do all parts of the stack we can do without browser scene = Makie.get_scene(figlike) - session = Session(Bonito.NoConnection(); asset_server=Bonito.NoServer()) + session = Session(Bonito.NoConnection(); asset_server = Bonito.NoServer()) three_display(Screen(scene), session, scene) Bonito.jsrender(session, figlike) s = serialize_scene(scene) diff --git a/WGLMakie/src/serialization.jl b/WGLMakie/src/serialization.jl index 0bd6ad2d261..d59a2cae853 100644 --- a/WGLMakie/src/serialization.jl +++ b/WGLMakie/src/serialization.jl @@ -94,11 +94,11 @@ end function serialize_three(color::Sampler{T,N}) where {T,N} tex = Dict(:type => "Sampler", :data => serialize_three(color.data), - :size => Int32[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 => Int32[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 @@ -127,7 +127,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 function flatten_buffer(array::AbstractArray{<:AbstractFloat}) @@ -155,12 +155,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 @@ -185,8 +185,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(@nospecialize(plot), update_buffer::Observable, named_buffers) @@ -264,11 +264,11 @@ function serialize_three(@nospecialize(plot), program::Program) # TODO, make this configurable in ShaderAbstractions update_shader(x) = replace(x, "#version 300 es" => "") return Dict(:vertexarrays => serialize_named_buffer(program.vertexarray), - :faces => indices, :uniforms => uniforms, - :vertex_source => update_shader(program.vertex_source), - :fragment_source => update_shader(program.fragment_source), - :uniform_updater => uniform_updater(plot, program.uniforms), - :attribute_updater => attribute_updater) + :faces => indices, :uniforms => uniforms, + :vertex_source => update_shader(program.vertex_source), + :fragment_source => update_shader(program.fragment_source), + :uniform_updater => uniform_updater(plot, program.uniforms), + :attribute_updater => attribute_updater) end function serialize_scene(scene::Scene) @@ -287,28 +287,28 @@ function serialize_scene(scene::Scene) nothing end - children = map(child-> serialize_scene(child), scene.children) + children = map(child -> serialize_scene(child), scene.children) dirlight = Makie.get_directional_light(scene) light_dir = isnothing(dirlight) ? Observable(Vec3f(1)) : dirlight.direction cam_rel = isnothing(dirlight) ? false : dirlight.camera_relative serialized = Dict(:viewport => pixel_area, - :backgroundcolor => lift(hexcolor, scene, scene.backgroundcolor), - :backgroundcolor_alpha => lift(Colors.alpha, scene, scene.backgroundcolor), - :clearscene => scene.clear, - :camera => serialize_camera(scene), - :light_direction => light_dir, - :camera_relative_light => cam_rel, - :plots => serialize_plots(scene, scene.plots), - :cam3d_state => cam3d_state, - :visible => scene.visible, - :uuid => js_uuid(scene), - :children => children) + :backgroundcolor => lift(hexcolor, scene, scene.backgroundcolor), + :backgroundcolor_alpha => lift(Colors.alpha, scene, scene.backgroundcolor), + :clearscene => scene.clear, + :camera => serialize_camera(scene), + :light_direction => light_dir, + :camera_relative_light => cam_rel, + :plots => serialize_plots(scene, scene.plots), + :cam3d_state => cam3d_state, + :visible => scene.visible, + :uuid => js_uuid(scene), + :children => children) return serialized end -function serialize_plots(scene::Scene, @nospecialize(plots::Vector{T}), result=[]) where {T<:AbstractPlot} +function serialize_plots(scene::Scene, @nospecialize(plots::Vector{T}), result = []) where {T<:AbstractPlot} for plot in plots plot isa Makie.PlotList && continue # if no plots inserted, this truely is an atomic diff --git a/WGLMakie/src/three_plot.jl b/WGLMakie/src/three_plot.jl index aee3f71f7b8..08af59c3d5b 100644 --- a/WGLMakie/src/three_plot.jl +++ b/WGLMakie/src/three_plot.jl @@ -33,32 +33,35 @@ function three_display(screen::Screen, session::Session, scene::Scene) window_open = scene.events.window_open width, height = size(scene) canvas_width = lift(x -> [round.(Int, widths(x))...], scene, viewport(scene)) - canvas = DOM.m("canvas"; tabindex="0", style="display: block") - wrapper = DOM.div(canvas; style="width: 100%; height: 100%") + canvas = DOM.m("canvas"; tabindex = "0", style = "display: block") + wrapper = DOM.div(canvas; style = "width: 100%; height: 100%") comm = Observable(Dict{String,Any}()) done_init = Observable(false) # Keep texture atlas in parent session, so we don't need to send it over and over again ta = Bonito.Retain(TEXTURE_ATLAS) - evaljs(session, js""" - $(WGL).then(WGL => { - try { - const renderer = WGL.create_scene( - $wrapper, $canvas, $canvas_width, $scene_serialized, $comm, $width, $height, - $(ta), $(config.framerate), $(config.resize_to), $(config.px_per_unit), $(config.scalefactor) - ) - const gl = renderer.getContext() - const err = gl.getError() - if (err != gl.NO_ERROR) { - throw new Error("WebGL error: " + WGL.wglerror(gl, err)) - } - $(done_init).notify(true) - } catch (e) { - Bonito.Connection.send_error("error initializing scene", e) - $(done_init).notify(false) - return + evaljs( + session, + js""" +$(WGL).then(WGL => { + try { + const renderer = WGL.create_scene( + $wrapper, $canvas, $canvas_width, $scene_serialized, $comm, $width, $height, + $(ta), $(config.framerate), $(config.resize_to), $(config.px_per_unit), $(config.scalefactor) + ) + const gl = renderer.getContext() + const err = gl.getError() + if (err != gl.NO_ERROR) { + throw new Error("WebGL error: " + WGL.wglerror(gl, err)) } - }) - """) + $(done_init).notify(true) + } catch (e) { + Bonito.Connection.send_error("error initializing scene", e) + $(done_init).notify(false) + return + } +}) +""" + ) on(session, done_init) do val window_open[] = true end diff --git a/WGLMakie/test/offline_export.jl b/WGLMakie/test/offline_export.jl index 109dca0443e..9397133c0c1 100644 --- a/WGLMakie/test/offline_export.jl +++ b/WGLMakie/test/offline_export.jl @@ -1,7 +1,7 @@ using Bonito, 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 @@ Bonito.export_standalone(handler, dir) # Then serve it with e.g. LiveServer using LiveServer -LiveServer.serve(dir=dir) +LiveServer.serve(dir = dir) diff --git a/WGLMakie/test/runtests.jl b/WGLMakie/test/runtests.jl index f3b9b4161b8..00c2c8f955b 100644 --- a/WGLMakie/test/runtests.jl +++ b/WGLMakie/test/runtests.jl @@ -50,7 +50,7 @@ excludes = Set([ ]) Makie.inline!(Makie.automatic) -edisplay = Bonito.use_electron_display(devtools=true) +edisplay = Bonito.use_electron_display(devtools = true) @testset "refimages" begin WGLMakie.activate!() ReferenceTests.mark_broken_tests(excludes) @@ -63,9 +63,9 @@ end Makie.CURRENT_FIGURE[] = nothing app = App(nothing) display(edisplay, app) - GC.gc(true); + GC.gc(true) # Somehow this may take a while to get emptied completely - Bonito.wait_for(() -> (GC.gc(true);isempty(run(edisplay.window, "Object.keys(WGL.plot_cache)")));timeout=20) + Bonito.wait_for(() -> (GC.gc(true); isempty(run(edisplay.window, "Object.keys(WGL.plot_cache)"))); timeout = 20) wgl_plots = run(edisplay.window, "Object.keys(WGL.scene_cache)") @test isempty(wgl_plots) @@ -76,7 +76,7 @@ end @test session_size / 10^6 < 6 @test texture_atlas_size < 6 s_keys = "Object.keys(Bonito.Sessions.SESSIONS)" - Bonito.wait_for(() -> (GC.gc(true); 2 == length(run(edisplay.window, s_keys))); timeout=30) + Bonito.wait_for(() -> (GC.gc(true); 2 == length(run(edisplay.window, s_keys))); timeout = 30) js_sessions = run(edisplay.window, "Bonito.Sessions.SESSIONS") js_objects = run(edisplay.window, "Bonito.Sessions.GLOBAL_OBJECT_CACHE") # @test Set([app.session[].id, app.session[].parent.id]) == keys(js_sessions) diff --git a/gallery.jl b/gallery.jl index c6bf2780152..396a6ccd5ed 100644 --- a/gallery.jl +++ b/gallery.jl @@ -5,26 +5,26 @@ using DataFrames using GLMakie using LinearAlgebra url = "https://raw.githubusercontent.com/plotly/datasets/master/vortex.csv" -df = CSV.File(HTTP.get(url).body)|> DataFrame; +df = CSV.File(HTTP.get(url).body) |> DataFrame; uvw = Vec3f.(df.u, df.v, df.w) len = norm.(uvw) -arrows(df.x, df.y, df.z, df.u, df.v, df.w, linewidth=0, color=len, arrowsize = Vec3f(0.5, 0.5, 1)) |> display +arrows(df.x, df.y, df.z, df.u, df.v, df.w, linewidth = 0, color = len, arrowsize = Vec3f(0.5, 0.5, 1)) |> display # surface parameterization (u, v)----> (f(u,v), g(u,v), h(u,v)): -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)); +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) -tr = surface(f.(u,v'), - g.(u,v'), - h.(u,v'), - ambient=Vec3f(0.5), - diffuse=Vec3f(1), - specular=0.5, - colormap=:balance) |> display +tr = surface(f.(u, v'), + g.(u, v'), + h.(u, v'), + ambient = Vec3f(0.5), + diffuse = Vec3f(1), + specular = 0.5, + colormap = :balance) |> display diff --git a/precompile/shared-precompile.jl b/precompile/shared-precompile.jl index ecb28bde129..2af2b5950df 100644 --- a/precompile/shared-precompile.jl +++ b/precompile/shared-precompile.jl @@ -1,74 +1,74 @@ # File to run to snoop/trace all functions to compile using GeometryBasics -@compile scatter(1:4; color=1:4, colormap=:turbo, markersize=20, visible=true) +@compile scatter(1:4; color = 1:4, colormap = :turbo, markersize = 20, visible = true) -@compile poly(Recti(0, 0, 200, 200), strokewidth=20, strokecolor=:red, color=(:black, 0.4)) +@compile poly(Recti(0, 0, 200, 200), strokewidth = 20, strokecolor = :red, color = (:black, 0.4)) -@compile scatter(0..1, rand(10), markersize=rand(10) .* 20) +@compile scatter(0 .. 1, rand(10), markersize = rand(10) .* 20) @compile scatter(LinRange(0, 1, 10), rand(10)) -@compile scatter(-1..1, x -> x^2) +@compile scatter(-1 .. 1, x -> x^2) @compile 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 -@compile lines(rand(10), rand(10), color=rand(10), linewidth=10) -@compile lines(rand(10), rand(10), color=rand(RGBAf, 10), linewidth=10) +@compile lines(rand(10), rand(10), color = rand(10), linewidth = 10) +@compile lines(rand(10), rand(10), color = rand(RGBAf, 10), linewidth = 10) @compile lines(Circle(Point2f(0), Float32(1))) -@compile lines(-1..1, x -> x^2) +@compile lines(-1 .. 1, x -> x^2) -@compile heatmap(rand(50, 50), colormap=(:RdBu, 0.2)) +@compile heatmap(rand(50, 50), colormap = (:RdBu, 0.2)) -@compile contour(randn(100, 90), levels=3) -@compile contour(randn(33, 30), levels=[0.1, 0.5, 0.9], color=[:black, :green, (:blue, 0.4)], linewidth=2) +@compile contour(randn(100, 90), levels = 3) +@compile contour(randn(33, 30), levels = [0.1, 0.5, 0.9], color = [:black, :green, (:blue, 0.4)], linewidth = 2) -@compile meshscatter(rand(10), rand(10), rand(10), color=rand(10)) -@compile meshscatter(rand(Point3f, 10), color=rand(RGBAf, 10), transparency=true) +@compile meshscatter(rand(10), rand(10), rand(10), color = rand(10)) +@compile meshscatter(rand(Point3f, 10), color = rand(RGBAf, 10), transparency = true) @compile begin - l = range(-10, stop=10, length=10) - surface(l, l, rand(10, 10), colormap=:Spectral) + l = range(-10, stop = 10, length = 10) + surface(l, l, rand(10, 10), colormap = :Spectral) end @compile begin NL = 30 NR = 31 - 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], rand(NL, NR), - colormap=:Spectral + colormap = :Spectral ) end @compile begin - heatmap(rand(10, 5), axis = (yscale = log10, xscale=log10)) + heatmap(rand(10, 5), axis = (yscale = log10, xscale = log10)) end @compile begin x = [1 0 - 2 3] + 2 3] heatmap(1:2, 1:-1:0, x) end @compile begin res = 200 - s = Scene(camera=campixel!, size=(res, res)) + s = Scene(camera = campixel!, size = (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) @@ -79,10 +79,10 @@ end @compile 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 @compile begin - meshscatter(rand(Point3f, 10), axis=(type=Axis3,)) + meshscatter(rand(Point3f, 10), axis = (type = Axis3,)) end diff --git a/relocatability.jl b/relocatability.jl index 835aec2fc3a..50d2052a1ac 100644 --- a/relocatability.jl +++ b/relocatability.jl @@ -24,7 +24,7 @@ Pkg.activate("MakieApp") paths = [makie_dir, joinpath(makie_dir, "MakieCore"), joinpath(makie_dir, "GLMakie")] -Pkg.develop(map(x-> (;path=x), paths)) +Pkg.develop(map(x -> (; path = x), paths)) open("MakieApp/src/MakieApp.jl", "w") do io print(io, module_src) @@ -35,7 +35,7 @@ Pkg.add("PackageCompiler") using PackageCompiler -create_app(joinpath(pwd(), "MakieApp"), "executable"; force=true, incremental=true, include_transitive_dependencies=false) +create_app(joinpath(pwd(), "MakieApp"), "executable"; force = true, incremental = true, include_transitive_dependencies = false) exe = joinpath(pwd(), "executable", "bin", "MakieApp") @test success(`$(exe)`) julia_pkg_dir = joinpath(Base.DEPOT_PATH[1], "packages") diff --git a/src/Makie.jl b/src/Makie.jl index 0859d41f837..8f6b8a8e617 100644 --- a/src/Makie.jl +++ b/src/Makie.jl @@ -86,7 +86,7 @@ using MakieCore: Pixel, px, Unit, Billboard using MakieCore: NoShading, FastShading, MultiLightShading 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: create_axis_like, create_axis_like!, figurelike_return, figurelike_return! 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! @@ -97,7 +97,7 @@ export ConversionTrait, NoConversion, PointBased, GridBased, VertexGrid, CellGri export Pixel, px, Unit, plotkey, attributes, used_attributes export Linestyle -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 @@ -266,7 +266,7 @@ export mouseover, onpick, pick, Events, Keyboard, Mouse, is_mouseinside 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 @@ -313,7 +313,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 @@ -328,18 +328,18 @@ 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() - return convert(Float64, to_value(Makie.theme(:colgap; default=GridLayoutBase.DEFAULT_COLGAP[]))) + GridLayoutBase.DEFAULT_COLGAP_GETTER[] = function () + return convert(Float64, to_value(Makie.theme(:colgap; default = GridLayoutBase.DEFAULT_COLGAP[]))) end - GridLayoutBase.DEFAULT_ROWGAP_GETTER[] = function() - return convert(Float64, to_value(Makie.theme(:rowgap; default=GridLayoutBase.DEFAULT_ROWGAP[]))) + GridLayoutBase.DEFAULT_ROWGAP_GETTER[] = function () + return convert(Float64, to_value(Makie.theme(:rowgap; default = GridLayoutBase.DEFAULT_ROWGAP[]))) end # fonts aren't cacheable by precompilation, so we need to empty it on load! empty!(FONT_CACHE) 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 global makie_cache_dir = @get_scratch!("makie") @@ -356,9 +356,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 AmbientLight, PointLight, DirectionalLight, SpotLight, EnvironmentLight, RectLight, SSAO diff --git a/src/basic_recipes/ablines.jl b/src/basic_recipes/ablines.jl index 3c2268b241e..63b1d16fc5b 100644 --- a/src/basic_recipes/ablines.jl +++ b/src/basic_recipes/ablines.jl @@ -44,6 +44,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 70e239baae7..2e5e648f4ad 100644 --- a/src/basic_recipes/arc.jl +++ b/src/basic_recipes/arc.jl @@ -24,7 +24,7 @@ end function plot!(p::Arc) args = getindex.(p, (:origin, :radius, :start_angle, :stop_angle, :resolution)) positions = lift(p, args...) do origin, radius, start_angle, stop_angle, resolution - return map(range(start_angle, stop=stop_angle, length=resolution)) do angle + return map(range(start_angle, stop = stop_angle, length = resolution)) do angle return origin .+ Point2f((cos(angle), sin(angle)) .* radius) end end diff --git a/src/basic_recipes/arrows.jl b/src/basic_recipes/arrows.jl index c9a04553ea6..58762dfa89b 100644 --- a/src/basic_recipes/arrows.jl +++ b/src/basic_recipes/arrows.jl @@ -44,8 +44,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 @@ -56,8 +56,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 @@ -69,7 +69,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) @@ -77,42 +77,42 @@ 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}}, V}}) where {N, V} +function plot!(arrowplot::Arrows{<:Tuple{AbstractVector{<:Point{N}},V}}) where {N,V} @extract arrowplot ( points, directions, colormap, colorscale, normalize, align, arrowtail, color, linecolor, linestyle, linewidth, lengthscale, @@ -122,8 +122,8 @@ function plot!(arrowplot::Arrows{<: Tuple{AbstractVector{<: Point{N}}, V}}) wher fxaa, ssao, transparency, visible, inspectable ) - arrow_c = map((a, c)-> a === automatic ? c : a , arrowplot, arrowcolor, color) - line_c = map((a, c)-> a === automatic ? c : a , arrowplot, linecolor, color) + arrow_c = map((a, c) -> a === automatic ? c : a, arrowplot, arrowcolor, color) + line_c = map((a, c) -> a === automatic ? c : a, arrowplot, linecolor, color) fxaa_bool = lift(fxaa -> fxaa == automatic ? N == 3 : fxaa, arrowplot, fxaa) # automatic == fxaa for 3D marker_head = lift((ah, q) -> arrow_head(N, ah, q), arrowplot, arrowhead, quality) @@ -165,25 +165,25 @@ function plot!(arrowplot::Arrows{<: Tuple{AbstractVector{<: Point{N}}, V}}) wher linesegments!( arrowplot, headstart, - color=line_c, colormap=colormap, colorscale=colorscale, linestyle=linestyle, - colorrange=arrowplot.colorrange, - linewidth=lift(lw -> lw === automatic ? 1.0f0 : lw, arrowplot, linewidth), + color = line_c, colormap = colormap, colorscale = colorscale, linestyle = linestyle, + colorrange = arrowplot.colorrange, + linewidth = lift(lw -> lw === automatic ? 1.0f0 : lw, arrowplot, linewidth), fxaa = fxaa_bool, inspectable = inspectable, transparency = transparency, visible = visible, ) scatter!( arrowplot, - lift(x-> last.(x), arrowplot, headstart), - marker=marker_head, - markersize = lift(as-> as === automatic ? theme(scene, :markersize)[] : as, arrowplot, arrowsize), + lift(x -> last.(x), arrowplot, headstart), + marker = marker_head, + markersize = lift(as -> as === automatic ? theme(scene, :markersize)[] : as, arrowplot, arrowsize), color = arrow_c, rotations = rotations, strokewidth = 0.0, - colormap=colormap, markerspace=arrowplot.markerspace, colorrange=arrowplot.colorrange, + colormap = colormap, markerspace = arrowplot.markerspace, colorrange = arrowplot.colorrange, fxaa = fxaa_bool, inspectable = inspectable, transparency = transparency, visible = visible ) else - 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!(arrowplot, 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 82db813c536..65e47a96afb 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,24 +94,24 @@ 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)), @@ -132,8 +124,8 @@ function default_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)); @@ -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,7 +304,8 @@ function draw_axis3d(textbuffer, linebuffer, scale, limits, ranges_labels, fonts end end end - finish!(textbuffer); finish!(linebuffer) + finish!(textbuffer) + finish!(linebuffer) end return end @@ -337,7 +330,7 @@ function plot!(axis::Axis3D) onany( draw_axis3d, Observable(textbuffer), Observable(linebuffer), scale(scene), - axis[1], axis.ticks.ranges_labels, Observable(axis.fonts), args...; update=true + axis[1], axis.ticks.ranges_labels, Observable(axis.fonts), args...; update = true ) return axis end diff --git a/src/basic_recipes/band.jl b/src/basic_recipes/band.jl index 9a8de39b48d..aed818f1e62 100644 --- a/src/basic_recipes/band.jl +++ b/src/basic_recipes/band.jl @@ -17,11 +17,11 @@ $(ATTRIBUTES) 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) return [GLTriangleFace.(ns, ns .+ 1, ns2); GLTriangleFace.(ns .+ 1, ns2 .+ 1, ns2)] end @@ -42,7 +42,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 @@ -63,7 +63,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 e08fede2e9e..3f6e828fedf 100644 --- a/src/basic_recipes/barplot.jl +++ b/src/basic_recipes/barplot.jl @@ -1,4 +1,4 @@ -bar_label_formatter(value::Number) = string(round(value; digits=3)) +bar_label_formatter(value::Number) = string(round(value; digits = 3)) bar_label_formatter(label::String) = label bar_label_formatter(label::LaTeXString) = label @@ -23,11 +23,11 @@ end # `fillto` is related to `y-axis` transofrmation only, thus we expect `tf::Tuple` function bar_default_fillto(tf::Tuple, ys, offset, in_y_direction) - _logT = Union{typeof(log), typeof(log2), typeof(log10), Base.Fix1{typeof(log), <: Real}} + _logT = Union{typeof(log),typeof(log2),typeof(log10),Base.Fix1{typeof(log),<:Real}} if in_y_direction && tf[2] isa _logT || (!in_y_direction && tf[1] isa _logT) # x-scale log and !(in_y_direction) is equiavlent to y-scale log in_y_direction # use the minimal non-zero y divided by 2 as lower bound for log scale - smart_fillto = minimum(y -> y<=0 ? oftype(y, Inf) : y, ys) / 2 + smart_fillto = minimum(y -> y <= 0 ? oftype(y, Inf) : y, ys) / 2 return clamp.(ys, smart_fillto, Inf), smart_fillto else return ys, offset @@ -68,9 +68,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), @@ -85,7 +83,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... @@ -122,7 +120,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 @@ -142,7 +140,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...)) grps = StructArrays.finduniquesorted(groupby) @@ -166,14 +164,14 @@ end function calculate_bar_label_align(label_align, label_rotation::Real, in_y_direction::Bool, flip::Bool) if label_align == automatic - return angle2align(-label_rotation - !flip * pi + in_y_direction * pi/2) + return angle2align(-label_rotation - !flip * pi + in_y_direction * pi / 2) else return to_align(label_align, "Failed to convert `label_align` $label_align.") end end function text_attributes(values, in_y_direction, flip_labels_at, color_over_background, color_over_bar, - label_offset, label_rotation, label_align) + label_offset, label_rotation, label_align) aligns = Vec2f[] offsets = Vec2f[] text_colors = RGBAf[] @@ -183,7 +181,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)") @@ -210,8 +208,8 @@ function text_attributes(values, in_y_direction, flip_labels_at, color_over_back end function barplot_labels(xpositions, ypositions, offset, bar_labels, in_y_direction, flip_labels_at, - color_over_background, color_over_bar, label_formatter, label_offset, label_rotation, - label_align) + color_over_background, color_over_bar, label_formatter, label_offset, label_rotation, + label_align) if bar_labels isa Symbol && bar_labels in (:x, :y) bar_labels = map(xpositions, ypositions) do x, y if bar_labels === :x @@ -224,9 +222,9 @@ function barplot_labels(xpositions, ypositions, offset, bar_labels, in_y_directi if bar_labels isa AbstractVector if length(bar_labels) == length(xpositions) attributes = text_attributes(ypositions, in_y_direction, flip_labels_at, color_over_background, - color_over_bar, label_offset, label_rotation, label_align) + color_over_bar, label_offset, label_rotation, label_align) label_pos = broadcast(xpositions, ypositions, offset, bar_labels) do x, y, off, l - return (string(label_formatter(l)), in_y_direction ? Point2f(x, y+off) : Point2f(y, x+off)) + return (string(label_formatter(l)), in_y_direction ? Point2f(x, y + off) : Point2f(y, x + off)) end return (label_pos, attributes...) else @@ -242,15 +240,15 @@ function Makie.plot!(p::BarPlot) if !(eltype(bar_points[]) <: Point2) error("barplot only accepts x/y coordinates. Use `barplot(x, y)` or `barplot(xy::Vector{<:Point2})`.") end - labels = Observable(Tuple{Union{String,LaTeXStrings.LaTeXString}, Point2f}[]) + labels = Observable(Tuple{Union{String,LaTeXStrings.LaTeXString},Point2f}[]) label_aligns = Observable(Vec2f[]) label_offsets = Observable(Vec2f[]) label_colors = Observable(RGBAf[]) function calculate_bars(xy, fillto, offset, transformation, 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, label_rotation, label_align) + dir, bar_labels, flip_labels_at, label_color, color_over_background, + color_over_bar, label_formatter, label_offset, label_rotation, label_align) - 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 @@ -297,8 +295,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, offset, bar_labels, in_y_direction, - flip_labels_at, to_color(oback), to_color(obar), - label_formatter, label_offset, label_rotation, label_align) + flip_labels_at, to_color(oback), to_color(obar), + label_formatter, label_offset, label_rotation, label_align) labels[], label_aligns[], label_offsets[], label_colors[] = label_args end @@ -306,8 +304,8 @@ function Makie.plot!(p::BarPlot) end bars = lift(calculate_bars, p, p[1], p.fillto, p.offset, p.transformation.transform_func, 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.label_rotation, p.label_align; priority = 1) + 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.label_rotation, p.label_align; priority = 1) poly!( p, bars, color = p.color, colormap = p.colormap, colorscale = p.colorscale, colorrange = p.colorrange, strokewidth = p.strokewidth, strokecolor = p.strokecolor, visible = p.visible, @@ -316,6 +314,6 @@ function Makie.plot!(p::BarPlot) ) 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/bracket.jl b/src/basic_recipes/bracket.jl index 9a76143e342..9e45aa68bd1 100644 --- a/src/basic_recipes/bracket.jl +++ b/src/basic_recipes/bracket.jl @@ -55,8 +55,8 @@ function Makie.plot!(pl::Bracket) end onany(pl, points, scene.camera.projectionview, pl.model, transform_func(pl), - scene.viewport, pl.offset, pl.width, pl.orientation, realtextoffset, - pl.style, pl.text) do points, _, _, _, _, offset, width, orientation, textoff, style, text + scene.viewport, pl.offset, pl.width, pl.orientation, realtextoffset, + pl.style, pl.text) do points, _, _, _, _, offset, width, orientation, textoff, style, text empty!(bp[]) empty!(textoffset_vec[]) 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 c2a15ddbe34..e3fde6f6619 100644 --- a/src/basic_recipes/contourf.jl +++ b/src/basic_recipes/contourf.jl @@ -48,7 +48,7 @@ end # _computed_extendlow # _computed_extendhigh -_get_isoband_levels(levels::Int, mi, ma) = collect(range(Float32(mi), nextfloat(Float32(ma)), length = levels+1)) +_get_isoband_levels(levels::Int, mi, ma) = collect(range(Float32(mi), nextfloat(Float32(ma)), length = levels + 1)) function _get_isoband_levels(levels::AbstractVector{<:Real}, mi, ma) edges = Float32.(levels) @@ -67,7 +67,7 @@ function _get_isoband_levels(::Val{:relative}, levels::AbstractVector, values) return Float32.(levels .* (ma - mi) .+ mi) 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(c, zs, c.levels, c.mode) do zs, levels, mode @@ -78,7 +78,7 @@ function Makie.plot!(c::Contourf{<:Tuple{<:AbstractVector{<:Real}, <:AbstractVec minimum(levels), maximum(levels) end computed_colormap = lift(compute_contourf_colormap, c, c._computed_levels, c.colormap, c.extendlow, - c.extendhigh) + c.extendhigh) c.attributes[:_computed_colormap] = computed_colormap lowcolor = Observable{RGBAf}() @@ -103,7 +103,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 @@ -178,7 +178,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 861b9e249ed..db053096e23 100644 --- a/src/basic_recipes/contours.jl +++ b/src/basic_recipes/contours.jl @@ -29,9 +29,7 @@ $(ATTRIBUTES) linestyle = nothing, enable_depth = true, transparency = false, - labels = false, - - labelfont = theme(scene, :font), + labels = false, labelfont = theme(scene, :font), labelcolor = nothing, # matches color by default labelformatter = contour_label_formatter, labelsize = 10, # arbitrary @@ -71,7 +69,7 @@ function label_info(lev, vertices, col) ) end -function contourlines(::Type{<: Contour}, contours, cols, labels) +function contourlines(::Type{<:Contour}, contours, cols, labels) points = Point2f[] colors = RGBA{Float32}[] lev_pos_col = Tuple{Float32,NTuple{3,Point2f},RGBA{Float32}}[] @@ -86,7 +84,7 @@ function contourlines(::Type{<: Contour}, contours, cols, labels) points, colors, lev_pos_col end -function contourlines(::Type{<: Contour3d}, contours, cols, labels) +function contourlines(::Type{<:Contour3d}, contours, cols, labels) points = Point3f[] colors = RGBA{Float32}[] lev_pos_col = Tuple{Float32,NTuple{3,Point3f},RGBA{Float32}}[] @@ -103,7 +101,7 @@ function contourlines(::Type{<: Contour3d}, contours, cols, labels) points, colors, lev_pos_col end -to_levels(x::AbstractVector{<: Number}, cnorm) = x +to_levels(x::AbstractVector{<:Number}, cnorm) = x function to_levels(n::Integer, cnorm) zmin, zmax = cnorm @@ -111,16 +109,16 @@ function to_levels(n::Integer, cnorm) range(zmin + dz; step = dz, length = n) end -conversion_trait(::Type{<: Contour3d}) = VertexGrid() -conversion_trait(::Type{<: Contour}) = VertexGrid() -conversion_trait(::Type{<:Contour}, x, y, z, ::Union{Function, AbstractArray{<: Number, 3}}) = VolumeLike() -conversion_trait(::Type{<: Contour}, ::AbstractArray{<: Number, 3}) = VolumeLike() +conversion_trait(::Type{<:Contour3d}) = VertexGrid() +conversion_trait(::Type{<:Contour}) = VertexGrid() +conversion_trait(::Type{<:Contour}, x, y, z, ::Union{Function,AbstractArray{<:Number,3}}) = VolumeLike() +conversion_trait(::Type{<:Contour}, ::AbstractArray{<:Number,3}) = 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, plot, volume) - cliprange = replace_automatic!(()-> valuerange, plot, :colorrange) + cliprange = replace_automatic!(() -> valuerange, plot, :colorrange) cmap = lift(plot, colormap, levels, alpha, cliprange, valuerange) do _cmap, l, alpha, cliprange, vrange levels = to_levels(l, vrange) nlevels = length(levels) @@ -135,7 +133,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 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 @@ -167,7 +165,7 @@ color_per_level(color, args...) = color_per_level(to_color(color), args...) color_per_level(color::Colorant, _, _, _, _, levels) = fill(color, length(levels)) color_per_level(colors::AbstractVector, args...) = color_per_level(to_colormap(colors), args...) -function color_per_level(colors::AbstractVector{<: Colorant}, _, _, _, _, levels) +function color_per_level(colors::AbstractVector{<:Colorant}, _, _, _, _, levels) if length(levels) == length(colors) return colors else @@ -202,11 +200,11 @@ function has_changed(old_args, new_args) false 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, plot, z) levels = lift(plot, 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) @@ -215,7 +213,7 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} end end - replace_automatic!(()-> zrange, plot, :colorrange) + replace_automatic!(() -> zrange, plot, :colorrange) @extract plot (labels, labelsize, labelfont, labelcolor, labelformatter) args = @extract plot (color, colormap, colorscale, colorrange, alpha) @@ -223,7 +221,7 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} args = (x, y, z, levels, level_colors, labels) arg_values = map(to_value, args) old_values = map(copy, arg_values) - points, colors, lev_pos_col = Observable.(contourlines(arg_values..., T); ignore_equal_values=true) + points, colors, lev_pos_col = Observable.(contourlines(arg_values..., T); ignore_equal_values = true) onany(plot, args...) do args... # contourlines is expensive enough, that it's worth to copy & check against old values # We need to copy, since the values may get mutated in place @@ -251,13 +249,17 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} ) lift(scene.camera.projectionview, transformationmatrix(plot), scene.viewport, - labels, labelcolor, labelformatter, lev_pos_col - ) do _, _, _, labels, labelcolor, labelformatter, lev_pos_col + labels, labelcolor, labelformatter, lev_pos_col + ) do _, _, _, labels, labelcolor, labelformatter, lev_pos_col labels || return - pos = texts.positions.val; empty!(pos) - rot = texts.rotation.val; empty!(rot) - col = texts.color.val; empty!(col) - lbl = texts.text.val; empty!(lbl) + pos = texts.positions.val + empty!(pos) + rot = texts.rotation.val + empty!(rot) + col = texts.color.val + empty!(col) + lbl = texts.text.val + empty!(lbl) for (lev, (p1, p2, p3), color) in lev_pos_col px_pos1 = project(scene, apply_transform(transform_func(plot), p1, space)) px_pos3 = project(scene, apply_transform(transform_func(plot), p3, space)) @@ -281,7 +283,7 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} return end - bboxes = lift(labels, texts.text; ignore_equal_values=true) do labels, _ + bboxes = lift(labels, texts.text; ignore_equal_values = true) do labels, _ labels || return return broadcast(texts.plots[1][1].val, texts.positions.val, texts.rotation.val) do gc, pt, rot # drop the depth component of the bounding box for 3D @@ -304,7 +306,7 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} for (i, p) in enumerate(segments) if isnan(p) && n < nlab bb = bboxes[n += 1] # next segment is materialized by a NaN, thus consider next label - # wireframe!(plot, bb, space = :pixel) # toggle to debug labels + # wireframe!(plot, bb, space = :pixel) # toggle to debug labels elseif project(scene, apply_transform(transform_func(plot), p, space)) in bb masked[i] = nan for dir in (-1, +1) @@ -326,19 +328,19 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} color = colors, linewidth = plot.linewidth, linestyle = plot.linestyle, - visible=plot.visible, - transparency=plot.transparency, - overdraw=plot.overdraw, - inspectable=plot.inspectable, - depth_shift=plot.depth_shift, - space=plot.space + visible = plot.visible, + transparency = plot.transparency, + overdraw = plot.overdraw, + inspectable = plot.inspectable, + depth_shift = plot.depth_shift, + space = plot.space ) 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 e54669b9361..49caf4171b5 100644 --- a/src/basic_recipes/convenience_functions.jl +++ b/src/basic_recipes/convenience_functions.jl @@ -23,24 +23,24 @@ 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}; - size = (800, length(cgrads) * 84), - ) + cgrads::AbstractVector{Symbol}; + size = (800, length(cgrads) * 84), +) - f = Figure(; size=size) + f = Figure(; size = size) ax = Axis(f[1, 1]) labels = map(enumerate(cgrads)) do (i, cmap) c = to_colormap(cmap) image!( ax, - 0..10, - i..(i+1), - reshape(c, (length(c),1)) + 0 .. 10, + i .. (i + 1), + reshape(c, (length(c), 1)) ) cmapstr = string(cmap) - return ((i + (i + 1))/2, cmapstr) + return ((i + (i + 1)) / 2, cmapstr) end ax.yticks = (first.(labels), last.(labels)) diff --git a/src/basic_recipes/datashader.jl b/src/basic_recipes/datashader.jl index d9bf42b2244..8d41e275564 100644 --- a/src/basic_recipes/datashader.jl +++ b/src/basic_recipes/datashader.jl @@ -38,7 +38,7 @@ Basically does `operation(map!(local_operation, result, canvas.pixelbuffer))`, b simplifies passing a local or global operation. Allocates the result buffer every time and can be made non allocating by passing the correct result buffer. """ -function get_aggregation(canvas::Canvas; operation=equalize_histogram, local_operation=identity, result=similar(canvas.pixelbuffer, canvas.resolution)) +function get_aggregation(canvas::Canvas; operation = equalize_histogram, local_operation = identity, result = similar(canvas.pixelbuffer, canvas.resolution)) pix_reshaped = Base.ReshapedArray(canvas.pixelbuffer, canvas.resolution, ()) # we want to make it easy to set local_operation or operation, without them clashing, while also being able to set both! if operation === Makie.automatic @@ -90,7 +90,7 @@ function Canvas(xmin::Number, xmax::Number, ymin::Number, ymax::Number; args...) return Canvas(Rect2(xmin, ymin, xmax - xmin, ymax - ymin); args...) end -function Canvas(bounds::Rect2; resolution::Tuple{Int,Int}=(800, 800), op=AggCount()) +function Canvas(bounds::Rect2; resolution::Tuple{Int,Int} = (800, 800), op = AggCount()) xsize, ysize = resolution n_elements = xsize * ysize o0 = null(op) @@ -103,7 +103,7 @@ end n_threads(::AggSerial) = 1 n_threads(::AggThreads) = Threads.nthreads() -function Base.resize!(canvas::Canvas, resolution::Tuple{Int,Int}, nthreads=1) +function Base.resize!(canvas::Canvas, resolution::Tuple{Int,Int}, nthreads = 1) npixel = prod(resolution) n_elements = npixel * nthreads length(canvas.pixelbuffer) == npixel && length(canvas.aggbuffer) == n_elements && return false @@ -131,7 +131,7 @@ using InteractiveUtils Aggregate points into a canvas. The points are transformed by `point_transform` before aggregation. Method can be `AggSerial()` or `AggThreads()`. """ -function aggregate!(c::Canvas, points; point_transform=identity, method::AggMethod=AggSerial()) +function aggregate!(c::Canvas, points; point_transform = identity, method::AggMethod = AggSerial()) resize!(c, c.resolution, n_threads(method)) # make sure we have the right size for the method aggbuffer, pixelbuffer = c.aggbuffer, c.pixelbuffer fill!(aggbuffer, null(c.op)) @@ -139,9 +139,9 @@ function aggregate!(c::Canvas, points; point_transform=identity, method::AggMeth end function aggregation_implementation!(::AggSerial, - aggbuffer::AbstractVector, pixelbuffer::AbstractVector, - c::Canvas, op::AggOp, - points, point_transform) + aggbuffer::AbstractVector, pixelbuffer::AbstractVector, + c::Canvas, op::AggOp, + points, point_transform) (xmin, ymin), (xmax, ymax) = extrema(c.bounds) xsize, ysize = size(c) xwidth, ywidth = widths(c.bounds) @@ -186,9 +186,9 @@ function aggregation_implementation!(::AggSerial, end function aggregation_implementation!(::AggThreads, - aggbuffer::AbstractVector, pixelbuffer::AbstractVector, - c::Canvas, op::AggOp, - points, point_transform) + aggbuffer::AbstractVector, pixelbuffer::AbstractVector, + c::Canvas, op::AggOp, + points, point_transform) (xmin, ymin), (xmax, ymax) = extrema(c.bounds) xsize, ysize = size(c) # by adding eps to width we can use the scaling factor plus floor directly to compute the bin indices @@ -207,7 +207,7 @@ function aggregation_implementation!(::AggThreads, out2 = Base.ReshapedArray(pixelbuffer, (xsize, ysize), ()) n = length(points) - chunks = round.(Int, range(1, n; length=Threads.nthreads() + 1)) + chunks = round.(Int, range(1, n; length = Threads.nthreads() + 1)) @threads for t in 1:Threads.nthreads() from = chunks[t] @@ -258,9 +258,9 @@ end using ..Aggregation using ..Aggregation: Canvas, change_op!, aggregate! -function equalize_histogram(matrix; nbins=256) - h_eq = StatsBase.fit(StatsBase.Histogram, vec(matrix); nbins=nbins) - h_eq = normalize(h_eq; mode=:density) +function equalize_histogram(matrix; nbins = 256) + h_eq = StatsBase.fit(StatsBase.Histogram, vec(matrix); nbins = nbins) + h_eq = normalize(h_eq; mode = :density) cdf = cumsum(h_eq.weights) cdf = cdf / cdf[end] edg = h_eq.edges[1] @@ -318,21 +318,15 @@ $(Base.Docs.doc(MakieCore.colormap_attributes!)) $(Base.Docs.doc(MakieCore.generic_plot_attributes!)) """ @recipe(DataShader, points) do scene - attr = Theme( - - agg = AggCount(), + attr = Theme(agg = AggCount(), method = AggThreads(), async = true, # Defaults to equalize_histogram # just set to automatic, so that if one sets local_operation, one doesn't do equalize_histogram on top of things. - operation=automatic, - local_operation=identity, - - point_transform = identity, + operation = automatic, + local_operation = identity, point_transform = identity, binsize = 1, - show_timings = false, - - interpolate = true + show_timings = false, interpolate = true ) MakieCore.generic_plot_attributes!(attr) return MakieCore.colormap_attributes!(attr, theme(scene, :colormap)) @@ -355,7 +349,7 @@ end function canvas_obs(limits::Observable, pixel_area::Observable, op, binsize::Observable) - canvas = Canvas(limits[]; resolution=(widths(pixel_area[])...,), op=op[]) + canvas = Canvas(limits[]; resolution = (widths(pixel_area[])...,), op = op[]) canvas_obs = Observable(canvas) onany(limits, pixel_area, binsize, op) do lims, pxarea, binsize, op binsize isa Int || error("Bin factor $binsize is not an Int.") @@ -374,24 +368,24 @@ function canvas_obs(limits::Observable, pixel_area::Observable, op, binsize::Obs return canvas_obs end -function Makie.plot!(p::DataShader{<: Tuple{<: AbstractVector{<: Point}}}) +function Makie.plot!(p::DataShader{<:Tuple{<:AbstractVector{<:Point}}}) scene = parent_scene(p) - limits = lift(projview_to_2d_limits, p, scene.camera.projectionview; ignore_equal_values=true) - viewport = lift(identity, p, scene.viewport; ignore_equal_values=true) + limits = lift(projview_to_2d_limits, p, scene.camera.projectionview; ignore_equal_values = true) + viewport = lift(identity, p, scene.viewport; ignore_equal_values = true) canvas = canvas_obs(limits, viewport, p.agg, p.binsize) p._boundingbox = lift(fast_bb, p.points, p.point_transform) on_func = p.async[] ? onany_latest : onany canvas_with_aggregation = Observable(canvas[]) # Canvas that only gets notified after get_aggregation happened p.canvas = canvas_with_aggregation colorrange = Observable(Vec2f(0, 1)) - on(p.colorrange; update=true) do crange + on(p.colorrange; update = true) do crange if !(crange isa Automatic) colorrange[] = Vec2f(crange) end end on_func(canvas, p.points, p.point_transform) do canvas, points, f - Aggregation.aggregate!(canvas, points; point_transform=f, method=p.method[]) + Aggregation.aggregate!(canvas, points; point_transform = f, method = p.method[]) canvas_with_aggregation[] = canvas # If not automatic, it will get updated by the above on(p.colorrange) if p.colorrange[] isa Automatic @@ -401,17 +395,17 @@ function Makie.plot!(p::DataShader{<: Tuple{<: AbstractVector{<: Point}}}) end p.raw_colorrange = colorrange image!(p, canvas_with_aggregation; - operation=p.operation, local_operation=p.local_operation, interpolate=p.interpolate, + operation = p.operation, local_operation = p.local_operation, interpolate = p.interpolate, MakieCore.generic_plot_attributes(p)..., MakieCore.colormap_attributes(p)...) return p end -function aggregate_categories!(canvases, categories; method=AggThreads()) +function aggregate_categories!(canvases, categories; method = AggThreads()) for (k, canvas) in canvases points = categories[k] - Aggregation.aggregate!(canvas, points; method=method) + Aggregation.aggregate!(canvas, points; method = method) end end @@ -421,25 +415,25 @@ function Makie.convert_arguments(::Type{<:DataShader}, groups::AbstractVector, p if length(groups) != length(points) error("Each point needs a group. Length $(length(groups)) != $(length(points))") end - categories = Dict{String, Vector{Point2f}}() + categories = Dict{String,Vector{Point2f}}() for (g, p) in zip(groups, points) - gpoints = get!(()-> Point2f[], categories, string(g)) + gpoints = get!(() -> Point2f[], categories, string(g)) push!(gpoints, p) end return (categories,) end -function Makie.plot!(p::DataShader{<:Tuple{Dict{String, Vector{Point{2, Float32}}}}}) +function Makie.plot!(p::DataShader{<:Tuple{Dict{String,Vector{Point{2,Float32}}}}}) scene = parent_scene(p) - limits = lift(projview_to_2d_limits, p, scene.camera.projectionview; ignore_equal_values=true) - viewport = lift(identity, p, scene.viewport; ignore_equal_values=true) + limits = lift(projview_to_2d_limits, p, scene.camera.projectionview; ignore_equal_values = true) + viewport = lift(identity, p, scene.viewport; ignore_equal_values = true) canvas = canvas_obs(limits, viewport, Observable(AggCount{Float32}()), p.binsize) p._boundingbox = lift(p.points, p.point_transform) do cats, func rects = map(points -> fast_bb(points, func), values(cats)) return reduce(union, rects) end categories = p.points[] - canvases = Dict(k => Canvas(canvas[].bounds; resolution=canvas[].resolution, op=AggCount{Float32}()) + canvases = Dict(k => Canvas(canvas[].bounds; resolution = canvas[].resolution, op = AggCount{Float32}()) for (k, v) in categories) on_func = p.async[] ? onany_latest : onany @@ -451,7 +445,7 @@ function Makie.plot!(p::DataShader{<:Tuple{Dict{String, Vector{Point{2, Float32} Base.resize!(c, canvas.resolution) c.bounds = canvas.bounds end - aggregate_categories!(canvases, cats; method=p.method[]) + aggregate_categories!(canvases, cats; method = p.method[]) toal_value[] = Float32(maximum(sum(map(x -> x.pixelbuffer, values(canvases))))) return end @@ -461,18 +455,18 @@ function Makie.plot!(p::DataShader{<:Tuple{Dict{String, Vector{Point{2, Float32} for (k, canvas) in canvases color = colors[k] cmap = [(color, 0.0), (color, 1.0)] - image!(p, canvas; colorrange=Vec2f(0, 1), colormap=cmap, operation=identity, local_operation=op) + image!(p, canvas; colorrange = Vec2f(0, 1), colormap = cmap, operation = identity, local_operation = op) end return p end -data_limits(p::DataShader) = p._boundingbox[] +data_limits(p::DataShader) = p._boundingbox[] used_attributes(::Canvas) = (:operation, :local_operation) function convert_arguments(P::Type{<:Union{MeshScatter,Image,Surface,Contour,Contour3d}}, canvas::Canvas; - operation=automatic, local_operation=identity) - pixel = Aggregation.get_aggregation(canvas; operation=operation, local_operation=local_operation) + operation = automatic, local_operation = identity) + pixel = Aggregation.get_aggregation(canvas; operation = operation, local_operation = local_operation) (xmin, ymin), (xmax, ymax) = extrema(canvas.bounds) return convert_arguments(P, xmin .. xmax, ymin .. ymax, pixel) end @@ -485,12 +479,12 @@ Base.getindex(x::FakePlot, key::Symbol) = getindex(getfield(x, :attributes), key function get_plots(plot::DataShader) return map(collect(plot._categories[])) do (name, color) - return FakePlot(Attributes(; label=name, color=color)) + return FakePlot(Attributes(; label = name, color = color)) end end function legendelements(plot::FakePlot, legend) - return [PolyElement(; color=plot.attributes.color, strokecolor=legend.polystrokecolor, strokewidth=legend.polystrokewidth)] + return [PolyElement(; color = plot.attributes.color, strokecolor = legend.polystrokecolor, strokewidth = legend.polystrokewidth)] end # Sadly we must define the colorbar here and cant use the default fallback, @@ -500,7 +494,7 @@ end function extract_colormap(plot::DataShader) color = map(x -> x.aggbuffer, plot.canvas) return ColorMapping( - color[], color, plot.colormap, plot.raw_colorrange, + color[], color, plot.colormap, plot.raw_colorrange, plot.colorscale, plot.alpha, plot.highclip, diff --git a/src/basic_recipes/error_and_rangebars.jl b/src/basic_recipes/error_and_rangebars.jl index 95dc2ec39e1..c6e8cf2e436 100644 --- a/src/basic_recipes/error_and_rangebars.jl +++ b/src/basic_recipes/error_and_rangebars.jl @@ -130,7 +130,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] @@ -160,7 +160,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] @@ -205,8 +205,8 @@ function _plot_bars!(plot, linesegpairs, is_in_y_direction) screenendpoints = plot_to_screen(plot, endpoints) 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 return [p for pair in screenendpoints_shifted_pairs for p in pair] @@ -221,7 +221,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!(plot, whiskerlinewidths, linewidth) do linewidth # same for linewidth if linewidth isa AbstractVector @@ -289,6 +289,6 @@ function screen_to_plot(plot, p::VecTypes) 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 a919629d6b6..c77dfda7e2f 100644 --- a/src/basic_recipes/hvlines.jl +++ b/src/basic_recipes/hvlines.jl @@ -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) @@ -81,7 +81,7 @@ function Makie.plot!(p::Union{HLines, VLines}) notify(p[1]) line_attributes = copy(p.attributes) - foreach(key-> delete!(line_attributes, key), [:ymin, :ymax, :xmin, :xmax, :xautolimits, :yautolimits]) + foreach(key -> delete!(line_attributes, key), [:ymin, :ymax, :xmin, :xmax, :xautolimits, :yautolimits]) # Drop transform_func because we handle it manually line_attributes[:transformation] = Transformation(p, transform_func = identity) linesegments!(p, line_attributes, points) @@ -104,4 +104,4 @@ function data_limits(p::VLines) xmin, xmax = extrema(p[1][]) ymin, ymax = apply_transform.(itf[2], getindex.(extrema(limits), 2)) return Rect3f(Point3f(xmin, ymin, 0), Vec3f(xmax - xmin, ymax - ymin, 0)) -end \ No newline at end of file +end diff --git a/src/basic_recipes/hvspan.jl b/src/basic_recipes/hvspan.jl index cb082347705..573fd68d53c 100644 --- a/src/basic_recipes/hvspan.jl +++ b/src/basic_recipes/hvspan.jl @@ -16,7 +16,7 @@ All style attributes are the same as for `Poly`. default_theme(Poly, scene)..., cycle = [:color => :patchcolor], ) - end +end """ vspan(xs_low, xs_high; ymin = 0.0, ymax = 1.0, attrs...) @@ -38,7 +38,7 @@ All style attributes are the same as for `Poly`. ) 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) @@ -57,13 +57,13 @@ function Makie.plot!(p::Union{HSpan, VSpan}) if p isa HSpan x_mi = min_x + (max_x - min_x) * mi x_ma = min_x + (max_x - min_x) * ma - low = _apply_y_transform(transf, low) + low = _apply_y_transform(transf, low) high = _apply_y_transform(transf, high) push!(rects[], Rect2f(Point2f(x_mi, low), Vec2f(x_ma - x_mi, high - low))) elseif p isa VSpan y_mi = min_y + (max_y - min_y) * mi y_ma = min_y + (max_y - min_y) * ma - low = _apply_x_transform(transf, low) + low = _apply_x_transform(transf, low) high = _apply_x_transform(transf, high) push!(rects[], Rect2f(Point2f(low, y_mi), Vec2f(high - low, y_ma - y_mi))) end @@ -74,7 +74,7 @@ function Makie.plot!(p::Union{HSpan, VSpan}) notify(p[1]) poly_attributes = copy(p.attributes) - foreach(x-> delete!(poly_attributes, x), [:ymin, :ymax, :xmin, :xmax, :xautolimits, :yautolimits]) + foreach(x -> delete!(poly_attributes, x), [:ymin, :ymax, :xmin, :xmax, :xautolimits, :yautolimits]) # we handle transform_func manually poly_attributes[:transformation] = Transformation(p, transform_func = identity) @@ -108,4 +108,4 @@ function data_limits(p::VSpan) xmax = maximum(p[2][]) ymin, ymax = apply_transform.(itf[2], getindex.(extrema(limits), 2)) return Rect3f(Point3f(xmin, ymin, 0), Vec3f(xmax - xmin, ymax - ymin, 0)) -end \ No newline at end of file +end diff --git a/src/basic_recipes/pie.jl b/src/basic_recipes/pie.jl index e13033d39e9..65e31fe9204 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)) diff --git a/src/basic_recipes/poly.jl b/src/basic_recipes/poly.jl index 8792eadfb0c..984bee7f310 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, plot[1]), @@ -37,30 +37,30 @@ function plot!(plot::Poly{<: Tuple{Union{GeometryBasics.Mesh, GeometryPrimitive} end # Poly conversion -function poly_convert(geometries::AbstractVector, transform_func=identity) +function poly_convert(geometries::AbstractVector, transform_func = identity) isempty(geometries) && return typeof(GeometryBasics.Mesh(Point2f[], GLTriangleFace[]))[] return poly_convert.(geometries, (transform_func,)) end -function poly_convert(geometry::AbstractGeometry, transform_func=identity) +function poly_convert(geometry::AbstractGeometry, transform_func = identity) return GeometryBasics.triangle_mesh(geometry) end -poly_convert(meshes::AbstractVector{<:AbstractMesh}, transform_func=identity) = poly_convert.(meshes, (transform_func,)) +poly_convert(meshes::AbstractVector{<:AbstractMesh}, transform_func = identity) = poly_convert.(meshes, (transform_func,)) -function poly_convert(polys::AbstractVector{<:Polygon}, transform_func=identity) +function poly_convert(polys::AbstractVector{<:Polygon}, transform_func = identity) # GLPlainMesh2D is not concrete? - T = GeometryBasics.Mesh{2, Float32, GeometryBasics.Ngon{2, Float32, 3, Point2f}, SimpleFaceView{2, Float32, 3, GLIndex, Point2f, GLTriangleFace}} + T = GeometryBasics.Mesh{2,Float32,GeometryBasics.Ngon{2,Float32,3,Point2f},SimpleFaceView{2,Float32,3,GLIndex,Point2f,GLTriangleFace}} return isempty(polys) ? T[] : poly_convert.(polys, (transform_func,)) end -function poly_convert(multipolygons::AbstractVector{<:MultiPolygon}, transform_func=identity) +function poly_convert(multipolygons::AbstractVector{<:MultiPolygon}, transform_func = identity) return [merge(poly_convert.(multipoly.polygons, (transform_func,))) for multipoly in multipolygons] end -poly_convert(mesh::GeometryBasics.Mesh, transform_func=identity) = mesh +poly_convert(mesh::GeometryBasics.Mesh, transform_func = identity) = mesh -function poly_convert(polygon::Polygon, transform_func=identity) +function poly_convert(polygon::Polygon, transform_func = identity) outer = metafree(coordinates(polygon.exterior)) points = Vector{Point2f}[apply_transform(transform_func, outer)] points_flat = Point2f[outer;] @@ -77,7 +77,7 @@ function poly_convert(polygon::Polygon, transform_func=identity) return GeometryBasics.Mesh(points_flat, faces) end -function poly_convert(polygon::AbstractVector{<:VecTypes}, transform_func=identity) +function poly_convert(polygon::AbstractVector{<:VecTypes}, transform_func = identity) point2f = convert(Vector{Point2f}, polygon) points_transformed = apply_transform(transform_func, point2f) faces = GeometryBasics.earcut_triangulate([points_transformed]) @@ -85,7 +85,7 @@ function poly_convert(polygon::AbstractVector{<:VecTypes}, transform_func=identi return GeometryBasics.Mesh(point2f, faces) end -function poly_convert(polygons::AbstractVector{<:AbstractVector{<:VecTypes}}, transform_func=identity) +function poly_convert(polygons::AbstractVector{<:AbstractVector{<:VecTypes}}, transform_func = identity) return map(polygons) do poly return poly_convert(poly, transform_func) end @@ -109,13 +109,13 @@ function to_lines(meshes::AbstractVector) return line end -function to_lines(polygon::AbstractVector{<: VecTypes}) +function to_lines(polygon::AbstractVector{<:VecTypes}) result = Point2f.(polygon) isempty(result) || 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] transform_func = plot.transformation.transform_func meshes = lift(poly_convert, plot, geometries, transform_func) @@ -128,8 +128,8 @@ function plot!(plot::Poly{<: Tuple{<: Union{Polygon, AbstractVector{<: PolyEleme colorrange = plot.colorrange, lowclip = plot.lowclip, highclip = plot.highclip, - nan_color=plot.nan_color, - alpha=plot.alpha, + nan_color = plot.nan_color, + alpha = plot.alpha, overdraw = plot.overdraw, fxaa = plot.fxaa, transparency = plot.transparency, @@ -162,13 +162,13 @@ 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] attributes = Attributes( visible = plot.visible, shading = plot.shading, fxaa = plot.fxaa, inspectable = plot.inspectable, transparency = plot.transparency, space = plot.space, ssao = plot.ssao, - alpha=plot.alpha, + alpha = plot.alpha, lowclip = get(plot, :lowclip, automatic), highclip = get(plot, :highclip, automatic), nan_color = get(plot, :nan_color, :transparent), @@ -177,16 +177,16 @@ function plot!(plot::Mesh{<: Tuple{<: AbstractVector{P}}}) where P <: Union{Abst colorrange = get(plot, :colorrange, automatic) ) - num_meshes = lift(plot, meshes; ignore_equal_values=true) do meshes + num_meshes = lift(plot, 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, Float32}}() + mesh_colors = Observable{Union{AbstractPattern,Matrix{RGBAf},RGBColors,Float32}}() map!(plot, mesh_colors, plot.color, num_meshes) do colors, num_meshes # one mesh per color if colors isa AbstractVector && length(colors) == length(num_meshes) - ccolors = colors isa AbstractArray{<: Number} ? colors : to_color(colors) + ccolors = colors isa AbstractArray{<:Number} ? colors : to_color(colors) result = similar(ccolors, float32type(ccolors), sum(num_meshes)) i = 1 for (cs, len) in zip(ccolors, num_meshes) diff --git a/src/basic_recipes/raincloud.jl b/src/basic_recipes/raincloud.jl index 93b47b07fbc..9c39644929f 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 cc2e02d4ec8..1abac5c1716 100644 --- a/src/basic_recipes/scatterlines.jl +++ b/src/basic_recipes/scatterlines.jl @@ -28,10 +28,10 @@ $(ATTRIBUTES) ) end -conversion_trait(::Type{<: ScatterLines}) = PointBased() +conversion_trait(::Type{<:ScatterLines}) = PointBased() -function plot!(p::Plot{scatterlines, <:NTuple{N, Any}}) where N +function plot!(p::Plot{scatterlines,<:NTuple{N,Any}}) where N # markercolor is the same as linecolor if left automatic real_markercolor = Observable{Any}() diff --git a/src/basic_recipes/series.jl b/src/basic_recipes/series.jl index a0375a0790a..c1a479c7306 100644 --- a/src/basic_recipes/series.jl +++ b/src/basic_recipes/series.jl @@ -22,43 +22,43 @@ Curves can be: """ @recipe(Series, curves) do scene Attributes( - linewidth=2, - color=:lighttest, - solid_color=nothing, - labels=nothing, - linestyle=:solid, - marker=nothing, - markersize=nothing, - markercolor=automatic, - strokecolor=nothing, - strokewidth=nothing, + linewidth = 2, + color = :lighttest, + solid_color = nothing, + labels = nothing, + linestyle = :solid, + marker = nothing, + markersize = nothing, + markercolor = automatic, + strokecolor = nothing, + strokewidth = nothing, space = :data, ) 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,) @@ -78,18 +78,18 @@ function plot!(plot::Series) end for i in 1:nseries - label = lift(l-> isnothing(l) ? "series $(i)" : l[i], plot, labels) - positions = lift(c-> c[i], plot, curves) - series_color = lift(c-> c isa AbstractVector ? c[i] : c, plot, colors) - series_linestyle = lift(ls-> ls isa AbstractVector ? ls[i] : ls, plot, linestyle) + label = lift(l -> isnothing(l) ? "series $(i)" : l[i], plot, labels) + positions = lift(c -> c[i], plot, curves) + series_color = lift(c -> c isa AbstractVector ? c[i] : c, plot, colors) + series_linestyle = lift(ls -> ls isa AbstractVector ? ls[i] : ls, plot, linestyle) if !isempty(scatter) mcolor = plot.markercolor - markercolor = lift((mc, sc)-> mc == automatic ? sc : mc, plot, mcolor, series_color) + markercolor = lift((mc, sc) -> mc == automatic ? sc : mc, plot, mcolor, series_color) scatterlines!(plot, positions; - linewidth=linewidth, color=series_color, markercolor=series_color, - label=label[], scatter..., space = space, linestyle = series_linestyle) + linewidth = linewidth, color = series_color, markercolor = series_color, + label = label[], scatter..., space = space, linestyle = series_linestyle) else - lines!(plot, positions; linewidth=linewidth, color=series_color, label=label, space = space, + lines!(plot, positions; linewidth = linewidth, color = series_color, label = label, space = space, linestyle = series_linestyle) end end diff --git a/src/basic_recipes/spy.jl b/src/basic_recipes/spy.jl index eda01af1237..3b8bd9cff04 100644 --- a/src/basic_recipes/spy.jl +++ b/src/basic_recipes/spy.jl @@ -27,14 +27,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) @@ -58,7 +58,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 @@ -77,9 +77,9 @@ function plot!(p::Spy) p, lift(first, p, xycol), color = lift(last, p, xycol), marker = marker, markersize = markersize, colorrange = p.colorrange, - colormap = p.colormap, colorscale = p.colorscale,inspectable = p.inspectable, visible = p.visible + colormap = p.colormap, colorscale = p.colorscale, inspectable = p.inspectable, visible = p.visible ) 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 4d74024c9b1..3c6a321d0a4 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]) diff --git a/src/basic_recipes/stem.jl b/src/basic_recipes/stem.jl index 682478762e5..de50b52675f 100644 --- a/src/basic_recipes/stem.jl +++ b/src/basic_recipes/stem.jl @@ -43,10 +43,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 6855c9858c5..83c5f9fd955 100644 --- a/src/basic_recipes/streamplot.jl +++ b/src/basic_recipes/streamplot.jl @@ -26,14 +26,10 @@ See the function `Makie.streamplot_impl` for implementation details. stepsize = 0.01, gridsize = (32, 32, 32), maxsteps = 500, - color = norm, - - arrow_size = automatic, + color = norm, arrow_size = automatic, arrow_head = automatic, density = 1.0, - quality = 16, - - linewidth = theme(scene, :linewidth), + quality = 16, linewidth = theme(scene, :linewidth), linestyle = nothing, ) MakieCore.colormap_attributes!(attr, theme(scene, :colormap)) @@ -41,13 +37,13 @@ See the function `Makie.streamplot_impl` for implementation details. return attr 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) @@ -56,7 +52,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 @@ -81,17 +77,17 @@ 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, color_func = norm) 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, color_func = norm) 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}[] - _cfunc = x-> to_color(color_func(x)) + arrow_pos = Point{N,Float32}[] + arrow_dir = Vec{N,Float32}[] + line_points = Point{N,Float32}[] + _cfunc = x -> to_color(color_func(x)) ColorType = typeof(_cfunc(Point{N,Float32}(0.0))) line_colors = ColorType[] colors = ColorType[] - 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) @@ -100,13 +96,13 @@ function streamplot_impl(CallType, f, limits::Rect{N, T}, resolutionND, stepsize # 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 @@ -129,7 +125,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, color, color) while x in limits && n_linepoints < maxsteps point = apply_f(x, CallType) @@ -180,7 +176,7 @@ function plot!(p::StreamPlot) lines!( p, - lift(x->x[3], p, data), + lift(x -> x[3], p, data), color = lift(last, p, data), linestyle = p.linestyle, linewidth = p.linewidth; @@ -228,8 +224,8 @@ function plot!(p::StreamPlot) scatterfun(N)( p, lift(first, p, data); - markersize=arrow_size, rotations=rotations, - color=lift(x -> x[4], p, data), + markersize = arrow_size, rotations = rotations, + color = lift(x -> x[4], p, data), marker = lift((ah, q) -> arrow_head(N, ah, q), p, p.arrow_head, p.quality), colormap_args..., generic_plot_attributes... diff --git a/src/basic_recipes/text.jl b/src/basic_recipes/text.jl index 1b42770ede3..d002d587dbb 100644 --- a/src/basic_recipes/text.jl +++ b/src/basic_recipes/text.jl @@ -8,16 +8,16 @@ function plot!(plot::Text) check_textsize_deprecation(plot) positions = plot[1] # attach a function to any text that calculates the glyph layout and stores it - glyphcollections = Observable(GlyphCollection[]; ignore_equal_values=true) - linesegs = Observable(Point2f[]; ignore_equal_values=true) - linewidths = Observable(Float32[]; ignore_equal_values=true) - linecolors = Observable(RGBAf[]; ignore_equal_values=true) + glyphcollections = Observable(GlyphCollection[]; ignore_equal_values = true) + linesegs = Observable(Point2f[]; ignore_equal_values = true) + linewidths = Observable(Float32[]; ignore_equal_values = true) + linecolors = Observable(RGBAf[]; ignore_equal_values = true) lineindices = Ref(Int[]) onany(plot, plot.text, plot.fontsize, plot.font, plot.fonts, plot.align, - plot.rotation, plot.justification, plot.lineheight, plot.calculated_colors, - plot.strokecolor, plot.strokewidth, plot.word_wrap_width, plot.offset) do str, - ts, f, fs, al, rot, jus, lh, col, scol, swi, www, offs + plot.rotation, plot.justification, plot.lineheight, plot.calculated_colors, + plot.strokecolor, plot.strokewidth, plot.word_wrap_width, plot.offset) do str, + ts, f, fs, al, rot, jus, lh, col, scol, swi, www, offs ts = to_fontsize(ts) f = to_font(fs, f) rot = to_rotation(rot) @@ -56,12 +56,12 @@ function plot!(plot::Text) linesegs[] = lsegs end - linesegs_shifted = Observable(Point2f[]; ignore_equal_values=true) + linesegs_shifted = Observable(Point2f[]; ignore_equal_values = true) sc = parent_scene(plot) onany(plot, linesegs, positions, sc.camera.projectionview, sc.viewport, - transform_func_obs(sc), get(plot, :space, :data)) do segs, pos, _, _, transf, space + transform_func_obs(sc), get(plot, :space, :data)) do segs, pos, _, _, transf, space pos_transf = plot_to_screen(plot, pos) linesegs_shifted[] = map(segs, lineindices[]) do seg, index seg + attr_broadcast_getindex(pos_transf, index) @@ -96,7 +96,7 @@ end function _get_glyphcollection_and_linesegments(latexstring::LaTeXString, index, ts, f, fs, al, rot, jus, lh, col, scol, swi, www, offs) 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[] @@ -129,11 +129,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{<:Any, <: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{<:Any,<: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 @@ -147,13 +147,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{<:Any, <:Point}}}}) +function plot!(plot::Text{<:Tuple{<:AbstractArray{<:Tuple{<:Any,<:Point}}}}) strings_and_positions = plot[1] strings = Observable{Vector{Any}}(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 @@ -180,7 +180,7 @@ function plot!(plot::Text{<:Tuple{<:AbstractArray{<:Tuple{<:Any, <:Point}}}}) 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"()) @@ -219,12 +219,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 @@ -242,7 +242,7 @@ function texelems_and_glyph_collection(str::LaTeXString, fontscale_px, halign, v end xshift = get_xshift(minimum(bb)[1], maximum(bb)[1], halign) - yshift = get_yshift(minimum(bb)[2], maximum(bb)[2], valign, default=0f0) + yshift = get_yshift(minimum(bb)[2], maximum(bb)[2], valign, default = 0f0) shift = Vec3f(xshift, yshift, 0) positions = basepositions .- Ref(shift) @@ -268,7 +268,7 @@ iswhitespace(l::LaTeXString) = iswhitespace(replace(l.s, '$' => "")) struct RichText 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) @@ -321,25 +321,25 @@ end # Copy constructor, to overwrite a field function GlyphInfo(gi::GlyphInfo; - glyph=gi.glyph, - font=gi.font, - origin=gi.origin, - extent=gi.extent, - size=gi.size, - rotation=gi.rotation, - color=gi.color, - strokecolor=gi.strokecolor, - strokewidth=gi.strokewidth) + glyph = gi.glyph, + font = gi.font, + origin = gi.origin, + extent = gi.extent, + size = gi.size, + rotation = gi.rotation, + color = gi.color, + strokecolor = gi.strokecolor, + strokewidth = gi.strokewidth) return GlyphInfo(glyph, - font, - origin, - extent, - size, - rotation, - color, - strokecolor, - strokewidth) + font, + origin, + extent, + size, + rotation, + color, + strokecolor, + strokewidth) end @@ -385,7 +385,7 @@ function apply_lineheight!(lines, lh) l = line[j] ox, oy = l.origin # TODO: Lineheight - l = GlyphInfo(l; origin=Point2f(ox, oy - (i - 1) * 20)) + l = GlyphInfo(l; origin = Point2f(ox, oy - (i - 1) * 20)) line[j] = l end end @@ -393,7 +393,7 @@ function apply_lineheight!(lines, lh) end function max_x_advance(glyph_infos::Vector{GlyphInfo})::Float32 - return maximum(glyph_infos; init=0.0f0) do ginfo + return maximum(glyph_infos; init = 0.0f0) do ginfo ginfo.origin[1] + ginfo.extent.hadvance * ginfo.size[1] end end @@ -418,8 +418,8 @@ function apply_alignment_and_justification!(lines, ju, al) top_y = max_y_ascender(lines[1]) bottom_y = min_y_descender(lines[end]) - al_offset_x = get_xshift(0f0, max_x, al[1]; default=0f0) - al_offset_y = get_yshift(bottom_y, top_y, al[2]; default=0f0) + al_offset_x = get_xshift(0f0, max_x, al[1]; default = 0f0) + al_offset_y = get_yshift(bottom_y, top_y, al[2]; default = 0f0) fju = float_justification(ju, al) @@ -440,7 +440,7 @@ function float_justification(ju, al)::Float32 float_justification = if ju === automatic get_xshift(0f0, 1f0, halign) else - get_xshift(0f0, 1f0, ju; default=ju) # errors if wrong symbol is used + get_xshift(0f0, 1f0, ju; default = ju) # errors if wrong symbol is used end end @@ -540,20 +540,20 @@ end iswhitespace(r::RichText) = iswhitespace(String(r)) -function get_xshift(lb, ub, align; default=0.5f0) +function get_xshift(lb, ub, align; default = 0.5f0) if align isa Symbol - align = align === :left ? 0.0f0 : + align = align === :left ? 0.0f0 : align === :center ? 0.5f0 : - align === :right ? 1.0f0 : default + align === :right ? 1.0f0 : default end - lb * (1-align) + ub * align |> Float32 + lb * (1 - align) + ub * align |> Float32 end -function get_yshift(lb, ub, align; default=0.5f0) +function get_yshift(lb, ub, align; default = 0.5f0) if align isa Symbol align = align === :bottom ? 0.0f0 : align === :center ? 0.5f0 : - align === :top ? 1.0f0 : default + align === :top ? 1.0f0 : default end - lb * (1-align) + ub * align |> Float32 + lb * (1 - align) + ub * align |> Float32 end diff --git a/src/basic_recipes/tooltip.jl b/src/basic_recipes/tooltip.jl index b94b557a74b..f03578b2659 100644 --- a/src/basic_recipes/tooltip.jl +++ b/src/basic_recipes/tooltip.jl @@ -71,10 +71,10 @@ Creates a tooltip pointing at `position` displaying the given `string` ) 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 @@ -84,8 +84,8 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) # TODO align scene = parent_scene(p) px_pos = map( - p, p[1], scene.camera.projectionview, p.model, transform_func(p), - p.space, scene.viewport) do pos, _, model, tf, space, viewport + p, p[1], scene.camera.projectionview, p.model, transform_func(p), + p.space, scene.viewport) do pos, _, model, tf, space, viewport # Adjusted from error_and_rangebars spvm = clip_to_space(scene.camera, :pixel) * space_to_clip(scene.camera, space) * model @@ -113,11 +113,11 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) 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) @@ -152,11 +152,11 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) # TODO react to glyphcollection instead bbox = map( - p, px_pos, p.text, text_align, text_offset, textpadding, p.align - ) do p, s, _, o, pad, align + p, px_pos, p.text, text_align, text_offset, textpadding, p.align + ) do p, s, _, o, pad, align bb = boundingbox(tp) + to_ndim(Vec3f, o, 0) l, r, b, t = pad - return Rect3f(origin(bb) .- (l, b, 0), widths(bb) .+ (l+r, b+t, 0)) + return Rect3f(origin(bb) .- (l, b, 0), widths(bb) .+ (l + r, b + t, 0)) end # Text background mesh @@ -173,7 +173,7 @@ 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!( @@ -184,25 +184,26 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) inspectable = p.inspectable, transformation = Transformation() ) onany(p, 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 translate!(mp, Vec3f(o[1] + w[1], o[2] + align * w[2], o[3])) - 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], o[3])) - 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], o[3])) - 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], o[3])) - rotate!(mp, Quaternionf(0,0,0,1)) + rotate!(mp, Quaternionf(0, 0, 0, 1)) end return end @@ -210,7 +211,8 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) # Outline outline = map(p, bbox, p.triangle_size, p.placement, p.align) do bb, s, placement, align - l, b, z = origin(bb); w, h, _ = widths(bb) + l, b, z = 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: @@ -222,24 +224,24 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) shift = if placement === :left Vec2f[ (l, b + 0.5h), (l, t), (r, t), - (r, b + align * h + 0.5s), + (r, b + align * h + 0.5s), (r + s, b + align * h), - (r, b + align * h - 0.5s), + (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, 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, t + s), (l + align * w + 0.5s, t), (r, t), (r, b), (l, b), (l, b + 0.5h) ] @@ -247,7 +249,7 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) 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, b - s), (l + align * w - 0.5s, b), (l, b), (l, b + 0.5h) ] @@ -256,7 +258,7 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) 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, b - s), (l + align * w - 0.5s, b), (l, b), (l, b + 0.5h) ] @@ -277,4 +279,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 e711345735d..79e5c30927c 100644 --- a/src/basic_recipes/tricontourf.jl +++ b/src/basic_recipes/tricontourf.jl @@ -55,7 +55,7 @@ function Makie.used_attributes(::Type{<:Tricontourf}, ::AbstractVector{<:Real}, end function Makie.convert_arguments(::Type{<:Tricontourf}, x::AbstractVector{<:Real}, y::AbstractVector{<:Real}, z::AbstractVector{<:Real}; - triangulation=DelaunayTriangulation()) + triangulation = DelaunayTriangulation()) z = elconvert(Float32, z) points = [x'; y'] if triangulation isa DelaunayTriangulation @@ -81,16 +81,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 @@ -115,7 +115,7 @@ function compute_highcolor(eh, cmap) end end -function Makie.plot!(c::Tricontourf{<:Tuple{<:DelTri.Triangulation, <:AbstractVector{<:Real}}}) +function Makie.plot!(c::Tricontourf{<:Tuple{<:DelTri.Triangulation,<:AbstractVector{<:Real}}}) tri, zs = c[1:2] c.attributes[:_computed_levels] = lift(c, zs, c.levels, c.mode) do zs, levels, mode @@ -124,7 +124,7 @@ function Makie.plot!(c::Tricontourf{<:Tuple{<:DelTri.Triangulation, <:AbstractVe colorrange = lift(extrema_nan, c, c._computed_levels) computed_colormap = lift(compute_contourf_colormap, c, c._computed_levels, c.colormap, c.extendlow, - c.extendhigh) + c.extendhigh) c.attributes[:_computed_colormap] = computed_colormap lowcolor = Observable{RGBAf}() @@ -153,7 +153,7 @@ function Makie.plot!(c::Tricontourf{<:Tuple{<:DelTri.Triangulation, <:AbstractVe @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] xs = [DelTri.getx(p) for p in DelTri.each_point(triangulation)] # each_point preserves indices @@ -217,9 +217,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/triplot.jl b/src/basic_recipes/triplot.jl index 917e3ff4265..145672b613c 100644 --- a/src/basic_recipes/triplot.jl +++ b/src/basic_recipes/triplot.jl @@ -38,38 +38,38 @@ Plots a triangulation based on the provided position or `Triangulation` from Del @recipe(Triplot, triangles) do scene sc = default_theme(scene, Scatter) return Attributes(; - # Toggles - show_points=false, - show_convex_hull=false, - show_ghost_edges=false, - show_constrained_edges=false, - recompute_centers=false, - - # Mesh settings - markersize=theme(scene, :markersize), - marker=theme(scene, :marker), - markercolor=sc.color, - strokecolor=theme(scene, :patchstrokecolor), - strokewidth=1, - linestyle=:solid, - triangle_color=(:white, 0.0), - - # Convex hull settings - convex_hull_color=:red, - convex_hull_linestyle=:dash, - convex_hull_linewidth=theme(scene, :linewidth), - - # Ghost edge settings - ghost_edge_color=:blue, - ghost_edge_linestyle=theme(scene, :linestyle), - ghost_edge_linewidth=theme(scene, :linewidth), - ghost_edge_extension_factor=0.1, - bounding_box=automatic, - - # Constrained edge settings - constrained_edge_color=:magenta, - constrained_edge_linestyle=theme(scene, :linestyle), - constrained_edge_linewidth=theme(scene, :linewidth)) + # Toggles + show_points = false, + show_convex_hull = false, + show_ghost_edges = false, + show_constrained_edges = false, + recompute_centers = false, + + # Mesh settings + markersize = theme(scene, :markersize), + marker = theme(scene, :marker), + markercolor = sc.color, + strokecolor = theme(scene, :patchstrokecolor), + strokewidth = 1, + linestyle = :solid, + triangle_color = (:white, 0.0), + + # Convex hull settings + convex_hull_color = :red, + convex_hull_linestyle = :dash, + convex_hull_linewidth = theme(scene, :linewidth), + + # Ghost edge settings + ghost_edge_color = :blue, + ghost_edge_linestyle = theme(scene, :linestyle), + ghost_edge_linewidth = theme(scene, :linewidth), + ghost_edge_extension_factor = 0.1, + bounding_box = automatic, + + # Constrained edge settings + constrained_edge_color = :magenta, + constrained_edge_linestyle = theme(scene, :linestyle), + constrained_edge_linewidth = theme(scene, :linewidth)) end function get_all_triangulation_points!(points, tri) @@ -110,12 +110,12 @@ function get_triangulation_ghost_edges!(ghost_edges, extent, tri, bounding_box) if bounding_box === automatic if DelTri.has_boundary_nodes(tri) xmin, xmax, ymin, ymax = DelTri.polygon_bounds(DelTri.get_points(tri), - DelTri.get_boundary_nodes(tri), - Val(true)) + DelTri.get_boundary_nodes(tri), + Val(true)) else xmin, xmax, ymin, ymax = DelTri.polygon_bounds(DelTri.get_points(tri), - DelTri.get_convex_hull_indices(tri), - Val(true)) + DelTri.get_convex_hull_indices(tri), + Val(true)) end Δx = xmax - xmin Δy = ymax - ymin @@ -189,7 +189,7 @@ function Makie.plot!(p::Triplot{<:Tuple{<:Vector{<:Point}}}) return DelTri.triangulate(transformed) end - attr[:transformation] = Transformation(p.transformation; transform_func=identity) + attr[:transformation] = Transformation(p.transformation; transform_func = identity) triplot!(p, attr, tri) return end @@ -220,23 +220,23 @@ function Makie.plot!(p::Triplot{<:Tuple{<:DelTri.Triangulation}}) p.show_constrained_edges[] && get_triangulation_constrained_edges!(constrained_edges_2f[], tri) foreach(notify, - (points_2f, present_points_2f, triangles_3f, ghost_edges_2f, convex_hull_2f, - constrained_edges_2f)) + (points_2f, present_points_2f, triangles_3f, ghost_edges_2f, convex_hull_2f, + constrained_edges_2f)) return nothing end onany(update_plot, p, p[1]) update_plot(p[1][]) - poly!(p, points_2f, triangles_3f; strokewidth=p.strokewidth, strokecolor=p.strokecolor, - color=p.triangle_color) - linesegments!(p, ghost_edges_2f; color=p.ghost_edge_color, linewidth=p.ghost_edge_linewidth, - linestyle=p.ghost_edge_linestyle, xautolimits=false, yautolimits=false) - lines!(p, convex_hull_2f; color=p.convex_hull_color, linewidth=p.convex_hull_linewidth, - linestyle=p.convex_hull_linestyle, depth_shift=-1.0f-5) - linesegments!(p, constrained_edges_2f; color=p.constrained_edge_color, depth_shift=-2.0f-5, - linewidth=p.constrained_edge_linewidth, linestyle=p.constrained_edge_linestyle) - scatter!(p, present_points_2f; markersize=p.markersize, color=p.markercolor, - strokecolor=p.strokecolor, marker=p.marker, visible=p.show_points, depth_shift=-3.0f-5) + poly!(p, points_2f, triangles_3f; strokewidth = p.strokewidth, strokecolor = p.strokecolor, + color = p.triangle_color) + linesegments!(p, ghost_edges_2f; color = p.ghost_edge_color, linewidth = p.ghost_edge_linewidth, + linestyle = p.ghost_edge_linestyle, xautolimits = false, yautolimits = false) + lines!(p, convex_hull_2f; color = p.convex_hull_color, linewidth = p.convex_hull_linewidth, + linestyle = p.convex_hull_linestyle, depth_shift = -1.0f-5) + linesegments!(p, constrained_edges_2f; color = p.constrained_edge_color, depth_shift = -2.0f-5, + linewidth = p.constrained_edge_linewidth, linestyle = p.constrained_edge_linestyle) + scatter!(p, present_points_2f; markersize = p.markersize, color = p.markercolor, + strokecolor = p.strokecolor, marker = p.marker, visible = p.show_points, depth_shift = -3.0f-5) return p end @@ -252,4 +252,4 @@ function data_limits(p::Triplot{<:Tuple{<:Vector{<:Point}}}) # cases span the full limits of the plot data_limits(p.plots[1]) end -end \ No newline at end of file +end 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/voronoiplot.jl b/src/basic_recipes/voronoiplot.jl index 7ce3d6f87b2..b7ef4bd32da 100644 --- a/src/basic_recipes/voronoiplot.jl +++ b/src/basic_recipes/voronoiplot.jl @@ -29,21 +29,21 @@ $(Base.Docs.doc(MakieCore.colormap_attributes!)) th = default_theme(scene, Mesh) sc = default_theme(scene, Scatter) attr = Attributes(; - # Toggles - show_generators=true, - smooth=false, - - # Point settings - markersize=sc.markersize, - marker=sc.marker, - markercolor=sc.color, - - # Polygon settings - strokecolor=theme(scene, :patchstrokecolor), - strokewidth=1.0, - color=automatic, - unbounded_edge_extension_factor=0.1, - clip=automatic) + # Toggles + show_generators = true, + smooth = false, + + # Point settings + markersize = sc.markersize, + marker = sc.marker, + markercolor = sc.color, + + # Polygon settings + strokecolor = theme(scene, :patchstrokecolor), + strokewidth = 1.0, + color = automatic, + unbounded_edge_extension_factor = 0.1, + clip = automatic) MakieCore.colormap_attributes!(attr, theme(scene, :colormap)) return attr end @@ -155,7 +155,7 @@ function plot!(p::Voronoiplot{<:Tuple{<:Vector{<:Point{N}}}}) where {N} # Default to circular clip for polar transformed data attr[:clip] = map(p, pop!(attr, :clip), p.unbounded_edge_extension_factor, - transform_func_obs(p), ps) do bb, ext, tf, ps + transform_func_obs(p), ps) do bb, ext, tf, ps if bb === automatic && tf isa Polar rscaled = maximum(p -> p[1 + tf.theta_as_x], ps) * (1 + ext) return Circle(Point2f(0), rscaled) @@ -163,7 +163,7 @@ function plot!(p::Voronoiplot{<:Tuple{<:Vector{<:Point{N}}}}) where {N} return bb end end - attr[:transformation] = Transformation(p.transformation; transform_func=identity) + attr[:transformation] = Transformation(p.transformation; transform_func = identity) return voronoiplot!(p, attr, vorn) end @@ -192,7 +192,7 @@ function plot!(p::Voronoiplot{<:Tuple{<:DelTri.VoronoiTessellation}}) return cs elseif color isa AbstractArray @assert(length(color) == DelTri.num_points(DelTri.get_triangulation(vorn)), - "Color vector must have the same length as the number of generators, including any not yet in the tessellation.") + "Color vector must have the same length as the number of generators, including any not yet in the tessellation.") return [color[i] for i in DelTri.each_generator(vorn)] # this matches the polygon order else return color # constant color @@ -204,7 +204,7 @@ function plot!(p::Voronoiplot{<:Tuple{<:DelTri.VoronoiTessellation}}) bbox = nothing elseif p.clip[] === automatic extent = p.unbounded_edge_extension_factor[] - bbox = DelTri.polygon_bounds(vorn, extent; include_polygon_vertices=false) + bbox = DelTri.polygon_bounds(vorn, extent; include_polygon_vertices = false) else bbox = p.clip[] end @@ -216,22 +216,22 @@ function plot!(p::Voronoiplot{<:Tuple{<:DelTri.VoronoiTessellation}}) update_plot(p[1][]) poly!(p, polygons; - strokecolor=p.strokecolor, - strokewidth=p.strokewidth, - color=p._calculated_colors, - colormap=p.colormap, - colorscale=p.colorscale, - colorrange=p.colorrange, - lowclip=p.lowclip, - highclip=p.highclip, - nan_color=p.nan_color) + strokecolor = p.strokecolor, + strokewidth = p.strokewidth, + color = p._calculated_colors, + colormap = p.colormap, + colorscale = p.colorscale, + colorrange = p.colorrange, + lowclip = p.lowclip, + highclip = p.highclip, + nan_color = p.nan_color) scatter!(p, generators_2f; - markersize=p.markersize, - marker=p.marker, - color=p.markercolor, - visible=p.show_generators, - depth_shift=-2.0f-5) + markersize = p.markersize, + marker = p.marker, + color = p.markercolor, + visible = p.show_generators, + depth_shift = -2.0f-5) return p end diff --git a/src/basic_recipes/waterfall.jl b/src/basic_recipes/waterfall.jl index 1aa0bf787cb..5a27ed2e05d 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, p[1], p.dodge, p.stack) @@ -60,10 +60,10 @@ function Makie.plot!(p::Waterfall) barplot!( p, lift(x -> x.final, p, 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, p, fromto); p.attributes..., - fillto=lift(x -> x.fillto, p, fromto), - stack=automatic, + fillto = lift(x -> x.fillto, p, fromto), + stack = automatic, ) if p.show_direction[] @@ -104,7 +104,7 @@ function Makie.plot!(p::Waterfall) push!(shapes, marker_pos) end end - return (xy=xy, shapes=shapes) + return (xy = xy, shapes = shapes) end markers = lift( @@ -123,8 +123,8 @@ function Makie.plot!(p::Waterfall) scatter!( p, lift(x -> x.xy, p, markers); - marker=lift(x -> x.shapes, p, markers), - color=p.direction_color) + marker = lift(x -> x.shapes, p, markers), + color = p.direction_color) end return p @@ -135,5 +135,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 bbf6d271e0d..08d4e8a2193 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, 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 b3e410b540f..9de50f1b697 100644 --- a/src/bezier.jl +++ b/src/bezier.jl @@ -35,7 +35,7 @@ EllipticalArc(cx, cy, r1, r2, angle, a1, a2) = EllipticalArc(Point2d(cx, cy), r1, r2, angle, a1, a2) struct ClosePath end -const PathCommand = Union{MoveTo, LineTo, CurveTo, EllipticalArc, ClosePath} +const PathCommand = Union{MoveTo,LineTo,CurveTo,EllipticalArc,ClosePath} # For hashing with crc32c function Base.write(io::IO, command::PathCommand) @@ -61,7 +61,7 @@ end function elliptical_arc_to_beziers(arc::EllipticalArc) delta_a = abs(arc.a2 - arc.a1) n_beziers = ceil(Int, delta_a / 0.5pi) - angles = range(arc.a1, arc.a2; length=n_beziers + 1) + 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 @@ -95,7 +95,7 @@ function point_at_angle(e::EllipticalArc, theta) M = abs(e.r1) * cos(theta) N = abs(e.r2) * sin(theta) return Point2f(e.c[1] + cos(e.angle) * M - sin(e.angle) * N, - e.c[2] + sin(e.angle) * M + cos(e.angle) * N) + e.c[2] + sin(e.angle) * M + cos(e.angle) * N) end function cleanup_bbox(bb::Rect2f) @@ -124,7 +124,7 @@ fast_stable_hash(x::BezierPath) = x.hash 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 @@ -155,7 +155,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 @@ -166,7 +166,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) @@ -207,7 +207,7 @@ Base.:+(bp::BezierPath, p::Point2) = BezierPath(bp.commands .+ Ref(p)) 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]); LineTo.(@view points[2:end]); @@ -218,8 +218,8 @@ 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]); LineTo.(points[2:end]); @@ -317,27 +317,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(Point2d(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(Point2d(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(Point2d(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(Point2d(x, y) + lastp())) i += 3 elseif comm == "H" - x = parse(Float64, args[i+1]) + x = parse(Float64, args[i + 1]) push!(commands, LineTo(Point2d(x, lastp()[2]))) i += 2 elseif comm == "h" - x = parse(Float64, args[i+1]) + x = parse(Float64, args[i + 1]) push!(commands, LineTo(Point2d(x, 0) + lastp())) i += 2 elseif comm == "Z" @@ -347,55 +347,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(Point2d(x1, y1), Point2d(x2, y2), Point2d(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(Point2d(x1, y1) + l, Point2d(x2, y2) + l, Point2d(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, Point2d(x1, y1), Point2d(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, Point2d(x1, y1) + l, Point2d(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(Point2d(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(Point2d(l[1], y))) i += 2 @@ -423,15 +423,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) * Point2d(rx * y1′ / ry, -ry * x1′ / rx) + sqrt(tempsqrt) * Point2d(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) = Point2d((sign * x1′ - c′[1]) / rx, (sign * y1′ - c′[2]) / rx) @@ -662,8 +662,8 @@ segment(p, c::CurveTo) = BezierSegment(p, c.c1, c.c2, c.p) const BezierCircle = let r = 0.47 # sqrt(1/pi) BezierPath([MoveTo(Point(r, 0.0)), - EllipticalArc(Point(0.0, 0), r, r, 0.0, 0.0, 2pi), - ClosePath()]) + EllipticalArc(Point(0.0, 0), r, r, 0.0, 0.0, 2pi), + ClosePath()]) end const BezierUTriangle = let @@ -676,9 +676,9 @@ const BezierUTriangle = let p3 = Point2d(w / 2, -h / 2) centroid = (p1 + p2 + p3) / 3 bp = BezierPath([MoveTo(p1 - centroid), - LineTo(p2 - centroid), - LineTo(p3 - centroid), - ClosePath()]) + LineTo(p2 - centroid), + LineTo(p3 - centroid), + ClosePath()]) end const BezierLTriangle = rotate(BezierUTriangle, pi / 2) @@ -688,10 +688,10 @@ 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 BezierPath([MoveTo(Point2d(r, -r)), - LineTo(Point2d(r, r)), - LineTo(Point2d(-r, r)), - LineTo(Point2d(-r, -r)), - ClosePath()]) + LineTo(Point2d(r, r)), + LineTo(Point2d(-r, r)), + LineTo(Point2d(-r, -r)), + ClosePath()]) end const BezierCross = let @@ -701,13 +701,13 @@ const BezierCross = let first_three = Point2d[(r, ri), (ri, ri), (ri, r)] all = (x -> reduce(vcat, x))(map(0:(pi / 2):(3pi / 2)) do a - m = Mat2f(sin(a), cos(a), cos(a), -sin(a)) - return Ref(m) .* first_three - end) + m = Mat2f(sin(a), cos(a), cos(a), -sin(a)) + return Ref(m) .* first_three + end) BezierPath([MoveTo(all[1]), - LineTo.(all[2:end])..., - ClosePath()]) + LineTo.(all[2:end])..., + ClosePath()]) end const BezierX = rotate(BezierCross, pi / 4) diff --git a/src/camera/camera.jl b/src/camera/camera.jl index 2d75f3dc9ca..1354269a9cc 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) @@ -30,9 +30,7 @@ function disconnect!(c::Camera) return end -function disconnect!(c::EmptyCamera) - return -end +disconnect!(c::EmptyCamera) = nothing function disconnect!(observables::Vector) for obs in observables @@ -42,12 +40,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 @@ -57,12 +55,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 @@ -83,11 +81,11 @@ function Camera(viewport) view, proj, proj_view, - lift(a-> Vec2f(widths(a)), viewport), + lift(a -> Vec2f(widths(a)), viewport), Observable(Vec3f(0)), Observable(Vec3f(1)), ObserverFunction[], - Dict{Symbol, Observable}() + Dict{Symbol,Observable}() ) end diff --git a/src/camera/camera2d.jl b/src/camera/camera2d.jl index d9d354a180f..dc206927aee 100644 --- a/src/camera/camera2d.jl +++ b/src/camera/camera2d.jl @@ -4,7 +4,7 @@ struct Camera2D <: AbstractCamera zoombutton::Observable{IsPressedInputType} panbutton::Observable{IsPressedInputType} padding::Observable{Float32} - last_area::Observable{Vec{2, Int}} + last_area::Observable{Vec{2,Int}} update_limits::Observable{Bool} end @@ -75,7 +75,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 = viewport(scene)[] px_wh = normalize(widths(pa)) @@ -341,7 +341,7 @@ Creates a pixel camera for the given `scene`. This means that the positional data of a plot will be interpreted in pixel units. This camera does not feature 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) @@ -363,7 +363,7 @@ get_space(::RelativeCamera) = :relative Creates a camera for the given `scene` which maps the scene area to a 0..1 by 0..1 range. This camera does not feature 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 6c8d72d0647..2cb2d7b2e1d 100644 --- a/src/camera/camera3d.jl +++ b/src/camera/camera3d.jl @@ -119,29 +119,29 @@ function Camera3D(scene::Scene; kwargs...) controls = 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, + zoom_in_key = Keyboard.u, + zoom_out_key = Keyboard.o, increase_fov_key = Keyboard.b, decrease_fov_key = Keyboard.n, # 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, - rotation_button = Mouse.left, - scroll_mod = true, - reposition_button = Keyboard.left_alt & Mouse.left, + rotation_button = Mouse.left, + scroll_mod = true, + reposition_button = Keyboard.left_alt & Mouse.left, # Shared controls fix_x_key = Keyboard.x, fix_y_key = Keyboard.y, @@ -154,16 +154,12 @@ function Camera3D(scene::Scene; kwargs...) settings = Attributes( keyboard_rotationspeed = 1f0, keyboard_translationspeed = 0.5f0, - keyboard_zoomspeed = 1f0, - - mouse_rotationspeed = 1f0, + keyboard_zoomspeed = 1f0, mouse_rotationspeed = 1f0, mouse_translationspeed = 1f0, - mouse_zoomspeed = 1f0, - - projectiontype = Makie.Perspective, + mouse_zoomspeed = 1f0, projectiontype = Makie.Perspective, circular_rotation = (true, true, true), rotation_center = :lookat, - update_rate = 1/30, + update_rate = 1 / 30, zoom_shift_lookat = true, fixed_axis = true, cad = false, @@ -190,8 +186,8 @@ function Camera3D(scene::Scene; kwargs...) # Semi-Internal - view matrix get(overwrites, :eyeposition, Observable(Vec3f(3, 3, 3))), - get(overwrites, :lookat, Observable(Vec3f(0, 0, 0))), - get(overwrites, :upvector, Observable(Vec3f(0, 0, 1))), + get(overwrites, :lookat, Observable(Vec3f(0, 0, 0))), + get(overwrites, :upvector, Observable(Vec3f(0, 0, 1))), # Semi-Internal - projection matrix get(overwrites, :fov, Observable(45.0)), @@ -225,7 +221,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 && - cam.selected[] && any(key -> ispressed(scene, controls[key][]), keynames) + cam.selected[] && any(key -> ispressed(scene, controls[key][]), keynames) cam.pulser[] = time() return Consume(true) end @@ -261,7 +257,7 @@ function Camera3D(scene::Scene; kwargs...) # reset on(camera(scene), events(scene).keyboardbutton, events(scene).mousebutton, priority = 1) do ke, me if cam.selected[] && ispressed(scene, controls[:reset][]) && - (ke.action == Keyboard.press || me.action == Mouse.press) + (ke.action == Keyboard.press || me.action == Mouse.press) # center keeps the rotation of the camera so we reset that here # might make sense to keep user set lookat, upvector, eyeposition # around somewhere for this? @@ -325,12 +321,12 @@ function on_pulse(scene, cam::Camera3D, timestep) ) # translation - right = ispressed(scene, right_key) - left = ispressed(scene, left_key) - up = ispressed(scene, up_key) - down = ispressed(scene, down_key) - backward = ispressed(scene, backward_key) - forward = ispressed(scene, forward_key) + right = ispressed(scene, right_key) + left = ispressed(scene, left_key) + up = ispressed(scene, up_key) + down = ispressed(scene, down_key) + backward = ispressed(scene, backward_key) + forward = ispressed(scene, forward_key) translating = right || left || up || down || backward || forward if translating @@ -339,44 +335,44 @@ function on_pulse(scene, cam::Camera3D, timestep) viewnorm = norm(cam.lookat[] - cam.eyeposition[]) xynorm = 2 * viewnorm * tand(0.5 * cam.fov[]) translation = keyboard_translationspeed * timestep * Vec3f( - xynorm * (right - left), - xynorm * (up - down), - viewnorm * (backward - forward) - ) + xynorm * (right - left), + xynorm * (up - down), + viewnorm * (backward - forward) + ) else # translation in camera space x/y/z direction viewnorm = norm(cam.eyeposition[] - cam.lookat[]) translation = 2 * viewnorm * keyboard_translationspeed * timestep * Vec3f( - right - left, up - down, backward - forward - ) + right - left, up - down, backward - forward + ) end _translate_cam!(scene, cam, translation) end # rotation - up = ispressed(scene, tilt_up_key) - down = ispressed(scene, tilt_down_key) - left = ispressed(scene, pan_left_key) - right = ispressed(scene, pan_right_key) + up = ispressed(scene, tilt_up_key) + down = ispressed(scene, tilt_down_key) + left = ispressed(scene, pan_left_key) + right = ispressed(scene, pan_right_key) counterclockwise = ispressed(scene, roll_counterclockwise_key) - clockwise = ispressed(scene, roll_clockwise_key) + clockwise = ispressed(scene, roll_clockwise_key) rotating = up || down || left || right || counterclockwise || clockwise if rotating # rotations around camera space x/y/z axes angles = keyboard_rotationspeed * timestep * - Vec3f(up - down, left - right, counterclockwise - clockwise) + Vec3f(up - down, left - right, counterclockwise - clockwise) _rotate_cam!(scene, cam, angles) end # zoom zoom_out = ispressed(scene, zoom_out_key) - zoom_in = ispressed(scene, zoom_in_key) + zoom_in = ispressed(scene, zoom_in_key) zooming = zoom_out || zoom_in if zooming - zoom_step = (1f0 + keyboard_zoomspeed * timestep) ^ (zoom_out - zoom_in) + zoom_step = (1f0 + keyboard_zoomspeed * timestep)^(zoom_out - zoom_in) _zoom!(scene, cam, zoom_step, false, false) end @@ -386,7 +382,7 @@ function on_pulse(scene, cam::Camera3D, timestep) fov_adjustment = fov_inc || fov_dec if fov_adjustment - step = (1 + keyboard_zoomspeed * timestep) ^ (fov_inc - fov_dec) + step = (1 + keyboard_zoomspeed * timestep)^(fov_inc - fov_dec) cam.fov[] = clamp(cam.fov[] * step, 0.1, 179) end @@ -414,7 +410,7 @@ function add_mouse_controls!(scene, cam::Camera3D) function compute_diff(delta) if projectiontype[] == Perspective - # TODO wrong scaling? :( + # TODO wrong scaling? :( ynorm = 2 * norm(cam.lookat[] - cam.eyeposition[]) * tand(0.5 * cam.fov[]) return ynorm / size(scene, 2) * delta else @@ -436,7 +432,7 @@ function add_mouse_controls!(scene, cam::Camera3D) dragging[] = (true, false) return Consume(true) end - # drag stop & repostion + # drag stop & repostion elseif event.action == Mouse.release consume = false @@ -500,7 +496,7 @@ function add_mouse_controls!(scene, cam::Camera3D) #zoom on(camera(scene), e.scroll) do scroll if is_mouseinside(scene) && ispressed(scene, scroll_mod[]) - zoom_step = (1f0 + 0.1f0 * mouse_zoomspeed[]) ^ -scroll[2] + zoom_step = (1f0 + 0.1f0 * mouse_zoomspeed[])^-scroll[2] zoom!(scene, cam, zoom_step, cad[], zoom_shift_lookat[]) return Consume(true) end @@ -543,7 +539,7 @@ Note that this method reacts to `fix_x_key` etc and `fixed_axis`. The former restrict the rotation around a specific axis when a given key is pressed. The latter keeps the camera y axis fixed as the data space z axis. """ -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 @@ -597,7 +593,7 @@ function _translate_cam!(scene, cam::Camera3D, t) end -function _rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse=false) +function _rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse = false) @extractvalue cam.controls (fix_x_key, fix_y_key, fix_z_key) @extractvalue cam.settings (fixed_axis, circular_rotation, rotation_center) @@ -701,7 +697,7 @@ function _zoom!(scene, cam::Camera3D, zoom_step, cad = false, zoom_shift_lookat scale = norm(viewdir) * tand(0.5 * cam.fov[]) end - cam.lookat[] = lookat + scale * shift + cam.lookat[] = lookat + scale * shift cam.eyeposition[] = lookat - zoom_step * viewdir + scale * shift else # just zoom in/out @@ -725,7 +721,8 @@ function update_cam!(scene::Scene, cam::Camera3D) if cam.settings.clipping_mode[] === :view_relative view_dist = norm(eyeposition - lookat) - near = view_dist * near; far = view_dist * far + near = view_dist * near + far = view_dist * far elseif cam.settings.clipping_mode[] === :bbox_relative view_dist = norm(eyeposition - lookat) center_dist = norm(eyeposition - origin(bounding_sphere)) @@ -734,7 +731,8 @@ function update_cam!(scene::Scene, cam::Camera3D) far = far_dist * far elseif cam.settings.clipping_mode[] === :adaptive view_dist = norm(eyeposition - lookat) - near = view_dist * near; far = max(radius(bounding_sphere) / tand(0.5f0 * cam.fov[]), view_dist) * far + near = view_dist * near + far = max(radius(bounding_sphere) / tand(0.5f0 * cam.fov[]), view_dist) * far elseif cam.settings.clipping_mode[] !== :static @error "clipping_mode = $(cam.settings.clipping_mode[]) not recognized, using :static." end @@ -743,7 +741,8 @@ function update_cam!(scene::Scene, cam::Camera3D) if cam.settings.projectiontype[] == Makie.Perspective proj = perspectiveprojection(fov, aspect, near, far) else - h = norm(eyeposition - lookat); w = h * aspect + h = norm(eyeposition - lookat) + w = h * aspect proj = orthographicprojection(-w, w, -h, h, near, far) end @@ -791,9 +790,9 @@ end # Update camera position via camera Position & Orientation function update_cam!(scene::Scene, camera::Camera3D, eyeposition::VecTypes, lookat::VecTypes, up::VecTypes = camera.upvector[]) - camera.lookat[] = Vec3f(lookat) + camera.lookat[] = Vec3f(lookat) camera.eyeposition[] = Vec3f(eyeposition) - camera.upvector[] = Vec3f(up) + camera.upvector[] = Vec3f(up) update_cam!(scene, camera) return end @@ -807,17 +806,17 @@ Set the camera position based on two angles `0 ≤ ϕ ≤ 2π` and `-pi/2 ≤ θ and an optional radius around the current `cam.lookat[]`. """ function update_cam!( - scene::Scene, camera::Camera3D, phi::Real, theta::Real, - radius::Real = norm(camera.eyeposition[] - camera.lookat[]), - center = camera.lookat[] - ) + scene::Scene, camera::Camera3D, phi::Real, theta::Real, + radius::Real = norm(camera.eyeposition[] - camera.lookat[]), + center = camera.lookat[] +) st, ct = sincos(theta) sp, cp = sincos(phi) v = Vec3f(ct * cp, ct * sp, st) u = Vec3f(-st * cp, -st * sp, ct) - camera.lookat[] = center + camera.lookat[] = center camera.eyeposition[] = center .+ radius * v - camera.upvector[] = u + camera.upvector[] = u update_cam!(scene, camera) return end @@ -826,9 +825,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 33d381d2e45..4d242b0a91a 100644 --- a/src/camera/old_camera3d.jl +++ b/src/camera/old_camera3d.jl @@ -106,10 +106,10 @@ old_cam3d!(scene::Scene; kwargs...) = old_cam3d_turntable!(scene; kwargs...) 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) @@ -119,9 +119,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 @@ -180,7 +180,7 @@ function add_translation!(scene, cam, key, button, zoom_shift_lookat::Bool) if ispressed(scene, button[]) && is_mouseinside(scene) cam_res = Vec2f(widths(scene)) 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) @@ -270,8 +270,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 @@ -281,8 +281,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 @@ -340,13 +340,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 eada9918c2e..79c2bfa8dcf 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) @@ -354,11 +354,11 @@ get_space(plot::Plot) = to_value(get(plot, :space, :data))::Symbol is_space_compatible(a, b) = is_space_compatible(get_space(a), get_space(b)) is_space_compatible(a::Symbol, b::Symbol) = a === b -is_space_compatible(a::Symbol, b::Union{Tuple, Vector}) = a in b -function is_space_compatible(a::Union{Tuple, Vector}, b::Union{Tuple, Vector}) +is_space_compatible(a::Symbol, b::Union{Tuple,Vector}) = a in b +function is_space_compatible(a::Union{Tuple,Vector}, b::Union{Tuple,Vector}) any(x -> is_space_compatible(x, b), a) end -is_space_compatible(a::Union{Tuple, Vector}, b::Symbol) = is_space_compatible(b, a) +is_space_compatible(a::Union{Tuple,Vector}, b::Symbol) = is_space_compatible(b, a) function project(cam::Camera, input_space::Symbol, output_space::Symbol, pos) input_space === output_space && return to_ndim(Point3f, pos, 0) diff --git a/src/colorsampler.jl b/src/colorsampler.jl index a1abf9cbd0b..d75a97c908f 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 @@ -87,7 +87,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 @@ -98,13 +98,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) @@ -113,18 +113,18 @@ 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 @@ -134,7 +134,7 @@ apply_scale(scale, x) = broadcast(scale, x) function numbers_to_colors(numbers::Union{AbstractArray{<:Number},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} colorscale = get_attribute(primitive, :colorscale) colorrange = if isnothing(_colorrange) # TODO, plot primitive should always expand automatic values @@ -146,16 +146,16 @@ function numbers_to_colors(numbers::Union{AbstractArray{<:Number},Number}, primi lowclip = get_attribute(primitive, :lowclip)::RGBAf highclip = get_attribute(primitive, :highclip)::RGBAf - nan_color = get_attribute(primitive, :nan_color, RGBAf(0,0,0,0))::RGBAf + nan_color = get_attribute(primitive, :nan_color, RGBAf(0, 0, 0, 0))::RGBAf return numbers_to_colors(numbers, colormap, colorscale, colorrange, lowclip, highclip, nan_color) end -function numbers_to_colors(numbers::Union{AbstractArray{<:Number, N},Number}, - colormap, colorscale, colorrange::Vec2, - lowclip::Union{Automatic,RGBAf}, - highclip::Union{Automatic,RGBAf}, - nan_color::RGBAf)::Union{Array{RGBAf, N},RGBAf} where {N} +function numbers_to_colors(numbers::Union{AbstractArray{<:Number,N},Number}, + colormap, colorscale, colorrange::Vec2, + lowclip::Union{Automatic,RGBAf}, + highclip::Union{Automatic,RGBAf}, + nan_color::RGBAf)::Union{Array{RGBAf,N},RGBAf} where {N} cmin, cmax = colorrange scaled_cmin = apply_scale(colorscale, cmin) scaled_cmax = apply_scale(colorscale, cmax) @@ -197,11 +197,11 @@ struct ColorMapping{N,T<:AbstractArray{<:Number,N},T2<:AbstractArray{<:Number,N} scale::Observable{Function} # The 0-1 scaled values from crange, which describe the colormapping - mapping::Observable{Union{Nothing, Vector{Float64}}} + mapping::Observable{Union{Nothing,Vector{Float64}}} colorrange::Observable{Vec{2,Float64}} - lowclip::Observable{Union{Automatic, RGBAf}} # Defaults to first color in colormap - highclip::Observable{Union{Automatic, RGBAf}} # Defaults to last color in colormap + lowclip::Observable{Union{Automatic,RGBAf}} # Defaults to first color in colormap + highclip::Observable{Union{Automatic,RGBAf}} # Defaults to last color in colormap nan_color::Observable{RGBAf} color_mapping_type::Observable{ColorMappingType} @@ -246,20 +246,20 @@ colormapping_type(::Categorical) = categorical function _colormapping( - color_tight::Observable{V}, - @nospecialize(colors_obs), - @nospecialize(colormap), - @nospecialize(colorrange), - @nospecialize(colorscale), - @nospecialize(alpha), - @nospecialize(lowclip), - @nospecialize(highclip), - @nospecialize(nan_color), - color_mapping_type) where {V <: AbstractArray{T, N}} where {N, T} - - map_colors = Observable(RGBAf[]; ignore_equal_values=true) - raw_colormap = Observable(RGBAf[]; ignore_equal_values=true) - mapping = Observable{Union{Nothing,Vector{Float64}}}(nothing; ignore_equal_values=true) + color_tight::Observable{V}, + @nospecialize(colors_obs), + @nospecialize(colormap), + @nospecialize(colorrange), + @nospecialize(colorscale), + @nospecialize(alpha), + @nospecialize(lowclip), + @nospecialize(highclip), + @nospecialize(nan_color), + color_mapping_type) where {V<:AbstractArray{T,N}} where {N,T} + + map_colors = Observable(RGBAf[]; ignore_equal_values = true) + raw_colormap = Observable(RGBAf[]; ignore_equal_values = true) + mapping = Observable{Union{Nothing,Vector{Float64}}}(nothing; ignore_equal_values = true) colorscale = convert(Observable{Function}, colorscale) function update_colors(cmap, a) @@ -280,22 +280,22 @@ function _colormapping( onany(update_colors, colormap, alpha) update_colors(colormap[], alpha[]) - _lowclip = Observable{Union{Automatic,RGBAf}}(automatic; ignore_equal_values=true) - on(lowclip; update=true) do lc + _lowclip = Observable{Union{Automatic,RGBAf}}(automatic; ignore_equal_values = true) + on(lowclip; update = true) do lc _lowclip[] = lc isa Union{Nothing,Automatic} ? automatic : to_color(lc) return end - _highclip = Observable{Union{Automatic,RGBAf}}(automatic; ignore_equal_values=true) - on(highclip; update=true) do hc + _highclip = Observable{Union{Automatic,RGBAf}}(automatic; ignore_equal_values = true) + on(highclip; update = true) do hc _highclip[] = hc isa Union{Nothing,Automatic} ? automatic : to_color(hc) return end - colorrange = lift(color_tight, colorrange; ignore_equal_values=true) do color, crange + colorrange = lift(color_tight, colorrange; ignore_equal_values = true) do color, crange return crange isa Automatic ? Vec2{Float64}(distinct_extrema_nan(color)) : Vec2{Float64}(crange) end - colorrange_scaled = lift(colorrange, colorscale; ignore_equal_values=true) do range, scale + colorrange_scaled = lift(colorrange, colorscale; ignore_equal_values = true) do range, scale return Vec2f(apply_scale(scale, range)) end @@ -305,40 +305,40 @@ function _colormapping( CT = ColorMapping{N,V,typeof(color_scaled[])} return CT(color_tight, - map_colors, - raw_colormap, - colorscale, - mapping, - colorrange, - _lowclip, - _highclip, - lift(to_color, nan_color), - color_mapping_type, - colorrange_scaled, - color_scaled) + map_colors, + raw_colormap, + colorscale, + mapping, + colorrange, + _lowclip, + _highclip, + lift(to_color, nan_color), + color_mapping_type, + colorrange_scaled, + color_scaled) end function ColorMapping( - color::AbstractArray{<:Number, N}, - @nospecialize(colors_obs), - @nospecialize(colormap), - @nospecialize(colorrange), - @nospecialize(colorscale), - @nospecialize(alpha), - @nospecialize(lowclip), - @nospecialize(highclip), - @nospecialize(nan_color), - color_mapping_type=lift(colormapping_type, colormap; ignore_equal_values=true)) where {N} + color::AbstractArray{<:Number,N}, + @nospecialize(colors_obs), + @nospecialize(colormap), + @nospecialize(colorrange), + @nospecialize(colorscale), + @nospecialize(alpha), + @nospecialize(lowclip), + @nospecialize(highclip), + @nospecialize(nan_color), + color_mapping_type = lift(colormapping_type, colormap; ignore_equal_values = true)) where {N} T = _array_value_type(color) color_tight = convert(Observable{T}, colors_obs)::Observable{T} _colormapping(color_tight, colors_obs, colormap, colorrange, - colorscale, alpha, lowclip, highclip, nan_color, color_mapping_type) + colorscale, alpha, lowclip, highclip, nan_color, color_mapping_type) end function assemble_colors(c::AbstractArray{<:Number}, @nospecialize(color), @nospecialize(plot)) return ColorMapping(c, color, plot.colormap, plot.colorrange, plot.colorscale, plot.alpha, plot.lowclip, - plot.highclip, plot.nan_color) + plot.highclip, plot.nan_color) end function to_color(c::ColorMapping) @@ -347,13 +347,13 @@ end function Base.get(c::ColorMapping, value::Number) return numbers_to_colors([value], c.colormap[], c.scale[], c.colorrange_scaled[], lowclip(c)[], - highclip(c)[], c.nan_color[])[1] + highclip(c)[], c.nan_color[])[1] end function assemble_colors(colortype, color, plot) return lift(plot, color, plot.alpha) do color, a if a < 1.0 - return broadcast(c-> RGBAf(Colors.color(c), Colors.alpha(c) * a), to_color(color)) + return broadcast(c -> RGBAf(Colors.color(c), Colors.alpha(c) * a), to_color(color)) else return to_color(color) end @@ -364,8 +364,8 @@ function assemble_colors(::Number, color, plot) plot.colorrange[] isa Automatic && error("Cannot determine a colorrange automatically for single number color value. Pass an explicit colorrange.") cm = assemble_colors([color[]], lift(x -> [x], color), plot) - return lift((args...)-> numbers_to_colors(args...)[1], cm.color_scaled, cm.colormap, identity, cm.colorrange_scaled, cm.lowclip, cm.highclip, - cm.nan_color) + return lift((args...) -> numbers_to_colors(args...)[1], cm.color_scaled, cm.colormap, identity, cm.colorrange_scaled, cm.lowclip, cm.highclip, + cm.nan_color) end highclip(cmap::ColorMapping) = lift((cm, hc) -> hc isa Automatic ? last(cm) : hc, cmap.colormap, cmap.highclip) diff --git a/src/conversions.jl b/src/conversions.jl index 45a1476e516..4024bdf2b66 100644 --- a/src/conversions.jl +++ b/src/conversions.jl @@ -1,7 +1,7 @@ ################################################################################ # Type Conversions # ################################################################################ -const RangeLike = Union{AbstractVector, ClosedInterval, Tuple{Any,Any}} +const RangeLike = Union{AbstractVector,ClosedInterval,Tuple{Any,Any}} # 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 @@ -138,7 +138,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 @@ -183,7 +183,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 @@ -192,13 +192,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]],) @@ -218,8 +218,9 @@ end Takes an input `Array{LineString}` or a `MultiLineString` and decomposes it to points. """ -function convert_arguments(PB::PointBased, linestring::Union{Array{<:LineString}, MultiLineString}) - arr = Point2f[]; n = length(linestring) +function convert_arguments(PB::PointBased, linestring::Union{Array{<:LineString},MultiLineString}) + arr = Point2f[] + n = length(linestring) for idx in 1:n append!(arr, convert_arguments(PB, linestring[idx])[1]) if idx != n # don't add NaN at the end @@ -258,7 +259,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 = Point2f[] n = length(mp) for idx in 1:n @@ -278,7 +279,7 @@ function convert_arguments(::PointBased, b::BezierPath) last_moveto = false function poly3(t, p0, p1, p2, p3) - Point2f((1-t)^3 .* p0 .+ t*p1*(3*(1-t)^2) + p2*(3*(1-t)*t^2) .+ p3*t^3) + Point2f((1 - t)^3 .* p0 .+ t * p1 * (3 * (1 - t)^2) + p2 * (3 * (1 - t) * t^2) .+ p3 * t^3) end for command in b2.commands @@ -321,9 +322,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 @@ -345,10 +346,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(ct::GridBased, x::AbstractVecOrMat{<: Number}, y::AbstractVecOrMat{<: Number}, z::AbstractMatrix{<: Union{Number, Colorant}}) +function convert_arguments(ct::GridBased, x::AbstractVecOrMat{<:Number}, y::AbstractVecOrMat{<:Number}, z::AbstractMatrix{<:Union{Number,Colorant}}) return map(el32convert, adjust_axes(ct, x, y, z)) end -function convert_arguments(ct::GridBased, x::AbstractVecOrMat{<: Number}, y::AbstractVecOrMat{<: Number}, z::AbstractMatrix{<:Number}) +function convert_arguments(ct::GridBased, x::AbstractVecOrMat{<:Number}, y::AbstractVecOrMat{<:Number}, z::AbstractMatrix{<:Number}) return map(el32convert, adjust_axes(ct, x, y, z)) end @@ -360,7 +361,7 @@ convert_arguments(ct::VertexGrid, x::AbstractMatrix, y::AbstractMatrix) = conver Takes one or two ClosedIntervals `x` and `y` and converts them to closed ranges with size(z, 1/2). """ -function convert_arguments(P::GridBased, x::RangeLike, y::RangeLike, z::AbstractMatrix{<: Union{Number, Colorant}}) +function convert_arguments(P::GridBased, x::RangeLike, y::RangeLike, z::AbstractMatrix{<:Union{Number,Colorant}}) convert_arguments(P, to_linspace(x, size(z, 1)), to_linspace(y, size(z, 2)), z) end @@ -386,7 +387,7 @@ function convert_arguments(::ImageLike, xs::RangeLike, ys::RangeLike, data::Abst print_range_warning("y", ys) end _interval(v::Union{Interval,AbstractVector}) = Float32(minimum(v)) .. Float32(maximum(v)) # having minimum and maximum here actually invites bugs - _interval(t::Tuple{Any, Any}) = Float32(t[1]) .. Float32(t[2]) + _interval(t::Tuple{Any,Any}) = Float32(t[1]) .. Float32(t[2]) x = _interval(xs) y = _interval(ys) return (x, y, el32convert(data)) @@ -430,7 +431,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(ct::Union{GridBased, ImageLike}, x::AbstractVector{T1}, y::AbstractVector{T2}, f::Function) where {T1, T2} +function convert_arguments(ct::Union{GridBased,ImageLike}, 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 @@ -452,12 +453,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 """ @@ -467,7 +468,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 @@ -475,7 +476,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]],) @@ -489,11 +490,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]],) @@ -522,9 +523,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 """ @@ -534,10 +535,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 @@ -548,29 +549,29 @@ function convert_arguments(::Type{<:Mesh}, mesh::GeometryBasics.Mesh{N}) where { n = normals(metafree(decompose(Point, mesh)), faces(mesh)) # Normals can be nothing, when it's impossible to calculate the normals (e.g. 2d mesh) if !isnothing(n) - mesh = GeometryBasics.pointmeta(mesh; normals=decompose(Vec3f, n)) + mesh = GeometryBasics.pointmeta(mesh; normals = decompose(Vec3f, n)) end end # If already correct eltypes for GL, we can pass the mesh through as is - if eltype(metafree(coordinates(mesh))) == Point{N, Float32} && eltype(faces(mesh)) == GLTriangleFace + if eltype(metafree(coordinates(mesh))) == Point{N,Float32} && eltype(faces(mesh)) == GLTriangleFace return (mesh,) else # Else, we need to convert it! - return (GeometryBasics.mesh(mesh, pointtype=Point{N, Float32}, facetype=GLTriangleFace),) + return (GeometryBasics.mesh(mesh, pointtype = Point{N,Float32}, facetype = GLTriangleFace),) end 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 @@ -587,10 +588,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 @@ -602,18 +603,18 @@ 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 +) vs = to_vertices(vertices) fs = to_triangles(indices) if eltype(vs) <: Point{3} ns = normals(vs, fs) - m = GeometryBasics.Mesh(meta(vs; normals=ns), fs) + m = GeometryBasics.Mesh(meta(vs; normals = ns), fs) else # TODO, we don't need to add normals here, but maybe nice for type stability? - m = GeometryBasics.Mesh(meta(vs; normals=fill(Vec3f(0, 0, 1), length(vs))), fs) + m = GeometryBasics.Mesh(meta(vs; normals = fill(Vec3f(0, 0, 1), length(vs))), fs) end return (m,) end @@ -633,7 +634,7 @@ function convert_arguments(::Type{<:Arrows}, x::AbstractVector, y::AbstractVecto end function convert_arguments(::Type{<:Arrows}, x::AbstractVector, y::AbstractVector, z::AbstractVector, - f::Function) + f::Function) points = [Point3f(x, y, z) for x in x, y in y, z in z] f_out = Vec3f.(f.(points)) return (vec(points), vec(f_out)) @@ -694,12 +695,12 @@ end # OffsetArrays conversions function convert_arguments(sl::GridBased, 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 ################################################################################ @@ -711,11 +712,11 @@ to_linspace(interval, N) = range(minimum(interval), stop = maximum(interval), le """ Converts the element 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) @@ -723,10 +724,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) @@ -751,10 +752,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 @@ -773,16 +774,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 ? map(Point3f, verts) : verts return reinterpret(Point3f, vert3f0) end -function to_vertices(verts::AbstractVector{<: VecTypes{N}}) where {N} - return map(Point{N, Float32}, verts) +function to_vertices(verts::AbstractVector{<:VecTypes{N}}) where {N} + return map(Point{N,Float32}, verts) 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) @@ -792,23 +793,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 - Point(ntuple(i-> Float32(lverts[i, vidx]), n)) + Point(ntuple(i -> Float32(lverts[i, vidx]), n)) 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 - Point(ntuple(i-> Float32(verts[vidx, i]), n)) + Point(ntuple(i -> Float32(verts[vidx, i]), n)) end end end @@ -837,11 +838,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 @@ -854,9 +855,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 @@ -871,7 +872,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) @@ -921,12 +922,12 @@ end to_linestyle(style::Linestyle) = Float32[x - style.value[1] for x in style.value] # TODO only use NTuple{2, <: Real} and not any other container -const GapType = Union{Real, Symbol, Tuple, AbstractVector} +const GapType = Union{Real,Symbol,Tuple,AbstractVector} # A `Symbol` equal to `:dash`, `:dot`, `:dashdot`, `:dashdotdot` -to_linestyle(ls::Union{Symbol, AbstractString}) = line_pattern(ls, :normal) +to_linestyle(ls::Union{Symbol,AbstractString}) = line_pattern(ls, :normal) -function to_linestyle(ls::Tuple{<:Union{Symbol, AbstractString}, <: GapType}) +function to_linestyle(ls::Tuple{<:Union{Symbol,AbstractString},<:GapType}) return line_pattern(ls[1], ls[2]) end @@ -970,7 +971,7 @@ function line_diff_pattern(ls_str::AbstractString, gaps::GapType = :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) @@ -999,10 +1000,10 @@ function convert_gaps(gaps::GapType) error_msg = "You provided the gaps modifier $gaps when specifying the linestyle. The modifier must be one of the symbols `:normal`, `:dense` or `:loose`, a real number or a tuple 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) + dot_gaps = (normal = 2, dense = 1, loose = 4) dash_gaps = (normal = 3, dense = 2, loose = 6) - dot_gap = getproperty(dot_gaps, gaps) + dot_gap = getproperty(dot_gaps, gaps) dash_gap = getproperty(dash_gaps, gaps) elseif gaps isa Real dot_gap = gaps @@ -1015,9 +1016,9 @@ function convert_gaps(gaps::GapType) return (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) +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) """ to_align(align[, error_prefix]) @@ -1029,7 +1030,7 @@ To specify a custom error message you can add an `error_prefix` or use `halign2num(value, error_msg)` and `valign2num(value, error_msg)` respectively. """ to_align(x::Tuple) = Vec2f(halign2num(x[1]), valign2num(x[2])) -to_align(x::VecTypes{2, <:Real}) = Vec2f(x) +to_align(x::VecTypes{2,<:Real}) = Vec2f(x) function to_align(v, error_prefix::String) try @@ -1096,7 +1097,7 @@ function angle2align(angle::Real) end -const FONT_CACHE = Dict{String, NativeFont}() +const FONT_CACHE = Dict{String,NativeFont}() const FONT_CACHE_LOCK = Base.ReentrantLock() function load_font(filepath) @@ -1127,13 +1128,13 @@ function to_font(str::String) return load_font(assetpath("fonts", "TeXGyreHerosMakie-Italic.otf")) elseif str == "TeX Gyre Heros Makie Bold Italic" return load_font(assetpath("fonts", "TeXGyreHerosMakie-BoldItalic.otf")) - # load fonts directly if they are given as font paths + # load fonts directly if they are given as font paths elseif isfile(str) return load_font(str) end # for all other cases, search for the best match on the system 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") return to_font("TeX Gyre Heros Makie") @@ -1181,19 +1182,19 @@ 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) to_fontsize(x::Vec2) = Vec2f(x) -to_fontsize(x::AbstractVector{T}) where T <: Vec2 = Vec2f.(x) +to_fontsize(x::AbstractVector{T}) where T<:Vec2 = Vec2f.(x) convert_attribute(x, ::key"linewidth") = to_linewidth(x) to_linewidth(x) = Float32(x) @@ -1236,7 +1237,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 @@ -1247,7 +1248,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) @@ -1284,9 +1285,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 @@ -1297,7 +1298,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 @@ -1339,7 +1340,7 @@ function convert_attribute(value, ::key"algorithm") 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, @@ -1349,8 +1350,8 @@ 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 #= @@ -1394,220 +1395,220 @@ See: https://github.com/MakieOrg/Makie.jl/pull/3394 =# const DEFAULT_MARKER_MAP = Dict(:+ => BezierPath([Makie.MoveTo([0.1245, 0.375]), - Makie.LineTo([0.1245, 0.1245]), - Makie.LineTo([0.375, 0.1245]), - Makie.LineTo([0.375, -0.12449999999999999]), - Makie.LineTo([0.1245, -0.1245]), - Makie.LineTo([0.12450000000000003, -0.375]), - Makie.LineTo([-0.12449999999999997, -0.375]), - Makie.LineTo([-0.12449999999999999, -0.12450000000000003]), - Makie.LineTo([-0.375, -0.12450000000000006]), - Makie.LineTo([-0.375, 0.12449999999999994]), - Makie.LineTo([-0.12450000000000003, 0.12449999999999999]), - Makie.LineTo([-0.12450000000000007, 0.37499999999999994]), - Makie.ClosePath()]), - :diamond => BezierPath([Makie.MoveTo([0.4464931614186469, - -5.564531862779532e-17]), - Makie.LineTo([2.10398220755128e-17, - 0.4464931614186469]), - Makie.LineTo([-0.4464931614186469, - 5.564531862779532e-17]), - Makie.LineTo([-2.10398220755128e-17, - -0.4464931614186469]), - Makie.ClosePath()]), - :star4 => BezierPath([Makie.MoveTo([2.7554554183166277e-17, - 0.44999999999999996]), - Makie.LineTo([-0.13258251920342445, - 0.13258251920342445]), - Makie.LineTo([-0.44999999999999996, - 5.5109108366332553e-17]), - Makie.LineTo([-0.13258251920342445, - -0.13258251920342445]), - Makie.LineTo([-8.266365659379842e-17, - -0.44999999999999996]), - Makie.LineTo([0.13258251920342445, - -0.13258251920342445]), - Makie.LineTo([0.44999999999999996, - -1.1021821673266511e-16]), - Makie.LineTo([0.13258251920342445, 0.13258251920342445]), - Makie.ClosePath()]), - :star8 => BezierPath([Makie.MoveTo([2.7554554183166277e-17, - 0.44999999999999996]), - Makie.LineTo([-0.09471414797008038, 0.2286601772904396]), - Makie.LineTo([-0.31819804608821867, - 0.31819804608821867]), - Makie.LineTo([-0.2286601772904396, 0.09471414797008038]), - Makie.LineTo([-0.44999999999999996, - 5.5109108366332553e-17]), - Makie.LineTo([-0.2286601772904396, - -0.09471414797008038]), - Makie.LineTo([-0.31819804608821867, - -0.31819804608821867]), - Makie.LineTo([-0.09471414797008038, - -0.2286601772904396]), - Makie.LineTo([-8.266365659379842e-17, - -0.44999999999999996]), - Makie.LineTo([0.09471414797008038, -0.2286601772904396]), - Makie.LineTo([0.31819804608821867, - -0.31819804608821867]), - Makie.LineTo([0.2286601772904396, -0.09471414797008038]), - Makie.LineTo([0.44999999999999996, - -1.1021821673266511e-16]), - Makie.LineTo([0.2286601772904396, 0.09471414797008038]), - Makie.LineTo([0.31819804608821867, 0.31819804608821867]), - Makie.LineTo([0.09471414797008038, 0.2286601772904396]), - Makie.ClosePath()]), - :star6 => BezierPath([Makie.MoveTo([2.7554554183166277e-17, - 0.44999999999999996]), - Makie.LineTo([-0.11249999999999999, 0.1948557123541832]), - Makie.LineTo([-0.3897114247083664, 0.22499999999999998]), - Makie.LineTo([-0.22499999999999998, - 2.7554554183166277e-17]), - Makie.LineTo([-0.3897114247083664, - -0.22499999999999998]), - Makie.LineTo([-0.11249999999999999, - -0.1948557123541832]), - Makie.LineTo([-8.266365659379842e-17, - -0.44999999999999996]), - Makie.LineTo([0.11249999999999999, -0.1948557123541832]), - Makie.LineTo([0.3897114247083664, -0.22499999999999998]), - Makie.LineTo([0.22499999999999998, - -5.5109108366332553e-17]), - Makie.LineTo([0.3897114247083664, 0.22499999999999998]), - Makie.LineTo([0.11249999999999999, 0.1948557123541832]), - Makie.ClosePath()]), - :rtriangle => BezierPath([Makie.MoveTo([0.485, -8.909305463796994e-17]), - Makie.LineTo([-0.24249999999999994, 0.36375]), - Makie.LineTo([-0.2425000000000001, - -0.36374999999999996]), - Makie.ClosePath()]), - :x => BezierPath([Makie.MoveTo([-0.1771302486872301, 0.35319983720268056]), - Makie.LineTo([1.39759596452057e-17, 0.17606958851545035]), - Makie.LineTo([0.17713024868723018, 0.3531998372026805]), - Makie.LineTo([0.3531998372026805, 0.17713024868723012]), - Makie.LineTo([0.17606958851545035, -1.025465786723834e-17]), - Makie.LineTo([0.3531998372026805, -0.17713024868723015]), - Makie.LineTo([0.17713024868723015, -0.3531998372026805]), - Makie.LineTo([1.1151998010815531e-17, -0.17606958851545035]), - Makie.LineTo([-0.17713024868723015, -0.3531998372026805]), - Makie.LineTo([-0.35319983720268044, -0.17713024868723018]), - Makie.LineTo([-0.17606958851545035, - -1.4873299788782892e-17]), - Makie.LineTo([-0.3531998372026805, 0.1771302486872301]), - Makie.ClosePath()]), - :circle => BezierPath([Makie.MoveTo([0.3525, 0.0]), - EllipticalArc([0.0, 0.0], 0.3525, 0.3525, 0.0, 0.0, - 6.283185307179586), Makie.ClosePath()]), - :pentagon => BezierPath([Makie.MoveTo([2.2962128485971897e-17, 0.375]), - Makie.LineTo([-0.35664620250463486, - 0.11588137596845627]), - Makie.LineTo([-0.22041946649551392, - -0.30338137596845627]), - Makie.LineTo([0.22041946649551392, - -0.30338137596845627]), - Makie.LineTo([0.35664620250463486, - 0.11588137596845627]), - Makie.ClosePath()]), - :vline => BezierPath([Makie.MoveTo([0.063143668438509, -0.315718342192545]), - Makie.LineTo([0.063143668438509, 0.315718342192545]), - Makie.LineTo([-0.063143668438509, 0.315718342192545]), - Makie.LineTo([-0.063143668438509, -0.315718342192545]), - Makie.ClosePath()]), - :cross => BezierPath([Makie.MoveTo([0.1245, 0.375]), - Makie.LineTo([0.1245, 0.1245]), - Makie.LineTo([0.375, 0.1245]), - Makie.LineTo([0.375, -0.12449999999999999]), - Makie.LineTo([0.1245, -0.1245]), - Makie.LineTo([0.12450000000000003, -0.375]), - Makie.LineTo([-0.12449999999999997, -0.375]), - Makie.LineTo([-0.12449999999999999, - -0.12450000000000003]), - Makie.LineTo([-0.375, -0.12450000000000006]), - Makie.LineTo([-0.375, 0.12449999999999994]), - Makie.LineTo([-0.12450000000000003, - 0.12449999999999999]), - Makie.LineTo([-0.12450000000000007, - 0.37499999999999994]), - Makie.ClosePath()]), - :xcross => BezierPath([Makie.MoveTo([-0.1771302486872301, - 0.35319983720268056]), - Makie.LineTo([1.39759596452057e-17, - 0.17606958851545035]), - Makie.LineTo([0.17713024868723018, 0.3531998372026805]), - Makie.LineTo([0.3531998372026805, 0.17713024868723012]), - Makie.LineTo([0.17606958851545035, - -1.025465786723834e-17]), - Makie.LineTo([0.3531998372026805, - -0.17713024868723015]), - Makie.LineTo([0.17713024868723015, - -0.3531998372026805]), - Makie.LineTo([1.1151998010815531e-17, - -0.17606958851545035]), - Makie.LineTo([-0.17713024868723015, - -0.3531998372026805]), - Makie.LineTo([-0.35319983720268044, - -0.17713024868723018]), - Makie.LineTo([-0.17606958851545035, - -1.4873299788782892e-17]), - Makie.LineTo([-0.3531998372026805, 0.1771302486872301]), - Makie.ClosePath()]), - :rect => BezierPath([Makie.MoveTo([0.315718342192545, -0.315718342192545]), - Makie.LineTo([0.315718342192545, 0.315718342192545]), - Makie.LineTo([-0.315718342192545, 0.315718342192545]), - Makie.LineTo([-0.315718342192545, -0.315718342192545]), - Makie.ClosePath()]), - :ltriangle => BezierPath([Makie.MoveTo([-0.485, 2.969768487932331e-17]), - Makie.LineTo([0.2425, -0.36375]), - Makie.LineTo([0.24250000000000005, 0.36375]), - Makie.ClosePath()]), - :dtriangle => BezierPath([Makie.MoveTo([-0.0, -0.485]), - Makie.LineTo([0.36375, 0.24250000000000002]), - Makie.LineTo([-0.36375, 0.24250000000000002]), - Makie.ClosePath()]), - :utriangle => BezierPath([Makie.MoveTo([0.0, 0.485]), - Makie.LineTo([-0.36375, -0.24250000000000002]), - Makie.LineTo([0.36375, -0.24250000000000002]), - Makie.ClosePath()]), - :star5 => BezierPath([Makie.MoveTo([2.7554554183166277e-17, - 0.44999999999999996]), - Makie.LineTo([-0.12343490123748782, - 0.16989357054233553]), - Makie.LineTo([-0.4279754430055618, 0.13905765116214752]), - Makie.LineTo([-0.19972187340259556, - -0.06489357054233552]), - Makie.LineTo([-0.2645033597946167, -0.3640576511621475]), - Makie.LineTo([-3.8576373077105933e-17, - -0.21000000000000002]), - Makie.LineTo([0.2645033597946167, -0.3640576511621475]), - Makie.LineTo([0.19972187340259556, - -0.06489357054233552]), - Makie.LineTo([0.4279754430055618, 0.13905765116214752]), - Makie.LineTo([0.12343490123748782, 0.16989357054233553]), - Makie.ClosePath()]), - :octagon => BezierPath([Makie.MoveTo([2.2962128485971897e-17, 0.375]), - Makie.LineTo([-0.2651650384068489, - 0.2651650384068489]), - Makie.LineTo([-0.375, 4.5924256971943795e-17]), - Makie.LineTo([-0.2651650384068489, - -0.2651650384068489]), - Makie.LineTo([-6.888638049483202e-17, -0.375]), - Makie.LineTo([0.2651650384068489, - -0.2651650384068489]), - Makie.LineTo([0.375, -9.184851394388759e-17]), - Makie.LineTo([0.2651650384068489, 0.2651650384068489]), - Makie.ClosePath()]), - :hline => BezierPath([Makie.MoveTo([0.315718342192545, -0.063143668438509]), - Makie.LineTo([0.315718342192545, 0.063143668438509]), - Makie.LineTo([-0.315718342192545, 0.063143668438509]), - Makie.LineTo([-0.315718342192545, -0.063143668438509]), - Makie.ClosePath()]), - :hexagon => BezierPath([Makie.MoveTo([2.2962128485971897e-17, 0.375]), - Makie.LineTo([-0.32475952059030533, 0.1875]), - Makie.LineTo([-0.32475952059030533, -0.1875]), - Makie.LineTo([-6.888638049483202e-17, -0.375]), - Makie.LineTo([0.32475952059030533, -0.1875]), - Makie.LineTo([0.32475952059030533, 0.1875]), - Makie.ClosePath()])) + Makie.LineTo([0.1245, 0.1245]), + Makie.LineTo([0.375, 0.1245]), + Makie.LineTo([0.375, -0.12449999999999999]), + Makie.LineTo([0.1245, -0.1245]), + Makie.LineTo([0.12450000000000003, -0.375]), + Makie.LineTo([-0.12449999999999997, -0.375]), + Makie.LineTo([-0.12449999999999999, -0.12450000000000003]), + Makie.LineTo([-0.375, -0.12450000000000006]), + Makie.LineTo([-0.375, 0.12449999999999994]), + Makie.LineTo([-0.12450000000000003, 0.12449999999999999]), + Makie.LineTo([-0.12450000000000007, 0.37499999999999994]), + Makie.ClosePath()]), + :diamond => BezierPath([Makie.MoveTo([0.4464931614186469, + -5.564531862779532e-17]), + Makie.LineTo([2.10398220755128e-17, + 0.4464931614186469]), + Makie.LineTo([-0.4464931614186469, + 5.564531862779532e-17]), + Makie.LineTo([-2.10398220755128e-17, + -0.4464931614186469]), + Makie.ClosePath()]), + :star4 => BezierPath([Makie.MoveTo([2.7554554183166277e-17, + 0.44999999999999996]), + Makie.LineTo([-0.13258251920342445, + 0.13258251920342445]), + Makie.LineTo([-0.44999999999999996, + 5.5109108366332553e-17]), + Makie.LineTo([-0.13258251920342445, + -0.13258251920342445]), + Makie.LineTo([-8.266365659379842e-17, + -0.44999999999999996]), + Makie.LineTo([0.13258251920342445, + -0.13258251920342445]), + Makie.LineTo([0.44999999999999996, + -1.1021821673266511e-16]), + Makie.LineTo([0.13258251920342445, 0.13258251920342445]), + Makie.ClosePath()]), + :star8 => BezierPath([Makie.MoveTo([2.7554554183166277e-17, + 0.44999999999999996]), + Makie.LineTo([-0.09471414797008038, 0.2286601772904396]), + Makie.LineTo([-0.31819804608821867, + 0.31819804608821867]), + Makie.LineTo([-0.2286601772904396, 0.09471414797008038]), + Makie.LineTo([-0.44999999999999996, + 5.5109108366332553e-17]), + Makie.LineTo([-0.2286601772904396, + -0.09471414797008038]), + Makie.LineTo([-0.31819804608821867, + -0.31819804608821867]), + Makie.LineTo([-0.09471414797008038, + -0.2286601772904396]), + Makie.LineTo([-8.266365659379842e-17, + -0.44999999999999996]), + Makie.LineTo([0.09471414797008038, -0.2286601772904396]), + Makie.LineTo([0.31819804608821867, + -0.31819804608821867]), + Makie.LineTo([0.2286601772904396, -0.09471414797008038]), + Makie.LineTo([0.44999999999999996, + -1.1021821673266511e-16]), + Makie.LineTo([0.2286601772904396, 0.09471414797008038]), + Makie.LineTo([0.31819804608821867, 0.31819804608821867]), + Makie.LineTo([0.09471414797008038, 0.2286601772904396]), + Makie.ClosePath()]), + :star6 => BezierPath([Makie.MoveTo([2.7554554183166277e-17, + 0.44999999999999996]), + Makie.LineTo([-0.11249999999999999, 0.1948557123541832]), + Makie.LineTo([-0.3897114247083664, 0.22499999999999998]), + Makie.LineTo([-0.22499999999999998, + 2.7554554183166277e-17]), + Makie.LineTo([-0.3897114247083664, + -0.22499999999999998]), + Makie.LineTo([-0.11249999999999999, + -0.1948557123541832]), + Makie.LineTo([-8.266365659379842e-17, + -0.44999999999999996]), + Makie.LineTo([0.11249999999999999, -0.1948557123541832]), + Makie.LineTo([0.3897114247083664, -0.22499999999999998]), + Makie.LineTo([0.22499999999999998, + -5.5109108366332553e-17]), + Makie.LineTo([0.3897114247083664, 0.22499999999999998]), + Makie.LineTo([0.11249999999999999, 0.1948557123541832]), + Makie.ClosePath()]), + :rtriangle => BezierPath([Makie.MoveTo([0.485, -8.909305463796994e-17]), + Makie.LineTo([-0.24249999999999994, 0.36375]), + Makie.LineTo([-0.2425000000000001, + -0.36374999999999996]), + Makie.ClosePath()]), + :x => BezierPath([Makie.MoveTo([-0.1771302486872301, 0.35319983720268056]), + Makie.LineTo([1.39759596452057e-17, 0.17606958851545035]), + Makie.LineTo([0.17713024868723018, 0.3531998372026805]), + Makie.LineTo([0.3531998372026805, 0.17713024868723012]), + Makie.LineTo([0.17606958851545035, -1.025465786723834e-17]), + Makie.LineTo([0.3531998372026805, -0.17713024868723015]), + Makie.LineTo([0.17713024868723015, -0.3531998372026805]), + Makie.LineTo([1.1151998010815531e-17, -0.17606958851545035]), + Makie.LineTo([-0.17713024868723015, -0.3531998372026805]), + Makie.LineTo([-0.35319983720268044, -0.17713024868723018]), + Makie.LineTo([-0.17606958851545035, + -1.4873299788782892e-17]), + Makie.LineTo([-0.3531998372026805, 0.1771302486872301]), + Makie.ClosePath()]), + :circle => BezierPath([Makie.MoveTo([0.3525, 0.0]), + EllipticalArc([0.0, 0.0], 0.3525, 0.3525, 0.0, 0.0, + 6.283185307179586), Makie.ClosePath()]), + :pentagon => BezierPath([Makie.MoveTo([2.2962128485971897e-17, 0.375]), + Makie.LineTo([-0.35664620250463486, + 0.11588137596845627]), + Makie.LineTo([-0.22041946649551392, + -0.30338137596845627]), + Makie.LineTo([0.22041946649551392, + -0.30338137596845627]), + Makie.LineTo([0.35664620250463486, + 0.11588137596845627]), + Makie.ClosePath()]), + :vline => BezierPath([Makie.MoveTo([0.063143668438509, -0.315718342192545]), + Makie.LineTo([0.063143668438509, 0.315718342192545]), + Makie.LineTo([-0.063143668438509, 0.315718342192545]), + Makie.LineTo([-0.063143668438509, -0.315718342192545]), + Makie.ClosePath()]), + :cross => BezierPath([Makie.MoveTo([0.1245, 0.375]), + Makie.LineTo([0.1245, 0.1245]), + Makie.LineTo([0.375, 0.1245]), + Makie.LineTo([0.375, -0.12449999999999999]), + Makie.LineTo([0.1245, -0.1245]), + Makie.LineTo([0.12450000000000003, -0.375]), + Makie.LineTo([-0.12449999999999997, -0.375]), + Makie.LineTo([-0.12449999999999999, + -0.12450000000000003]), + Makie.LineTo([-0.375, -0.12450000000000006]), + Makie.LineTo([-0.375, 0.12449999999999994]), + Makie.LineTo([-0.12450000000000003, + 0.12449999999999999]), + Makie.LineTo([-0.12450000000000007, + 0.37499999999999994]), + Makie.ClosePath()]), + :xcross => BezierPath([Makie.MoveTo([-0.1771302486872301, + 0.35319983720268056]), + Makie.LineTo([1.39759596452057e-17, + 0.17606958851545035]), + Makie.LineTo([0.17713024868723018, 0.3531998372026805]), + Makie.LineTo([0.3531998372026805, 0.17713024868723012]), + Makie.LineTo([0.17606958851545035, + -1.025465786723834e-17]), + Makie.LineTo([0.3531998372026805, + -0.17713024868723015]), + Makie.LineTo([0.17713024868723015, + -0.3531998372026805]), + Makie.LineTo([1.1151998010815531e-17, + -0.17606958851545035]), + Makie.LineTo([-0.17713024868723015, + -0.3531998372026805]), + Makie.LineTo([-0.35319983720268044, + -0.17713024868723018]), + Makie.LineTo([-0.17606958851545035, + -1.4873299788782892e-17]), + Makie.LineTo([-0.3531998372026805, 0.1771302486872301]), + Makie.ClosePath()]), + :rect => BezierPath([Makie.MoveTo([0.315718342192545, -0.315718342192545]), + Makie.LineTo([0.315718342192545, 0.315718342192545]), + Makie.LineTo([-0.315718342192545, 0.315718342192545]), + Makie.LineTo([-0.315718342192545, -0.315718342192545]), + Makie.ClosePath()]), + :ltriangle => BezierPath([Makie.MoveTo([-0.485, 2.969768487932331e-17]), + Makie.LineTo([0.2425, -0.36375]), + Makie.LineTo([0.24250000000000005, 0.36375]), + Makie.ClosePath()]), + :dtriangle => BezierPath([Makie.MoveTo([-0.0, -0.485]), + Makie.LineTo([0.36375, 0.24250000000000002]), + Makie.LineTo([-0.36375, 0.24250000000000002]), + Makie.ClosePath()]), + :utriangle => BezierPath([Makie.MoveTo([0.0, 0.485]), + Makie.LineTo([-0.36375, -0.24250000000000002]), + Makie.LineTo([0.36375, -0.24250000000000002]), + Makie.ClosePath()]), + :star5 => BezierPath([Makie.MoveTo([2.7554554183166277e-17, + 0.44999999999999996]), + Makie.LineTo([-0.12343490123748782, + 0.16989357054233553]), + Makie.LineTo([-0.4279754430055618, 0.13905765116214752]), + Makie.LineTo([-0.19972187340259556, + -0.06489357054233552]), + Makie.LineTo([-0.2645033597946167, -0.3640576511621475]), + Makie.LineTo([-3.8576373077105933e-17, + -0.21000000000000002]), + Makie.LineTo([0.2645033597946167, -0.3640576511621475]), + Makie.LineTo([0.19972187340259556, + -0.06489357054233552]), + Makie.LineTo([0.4279754430055618, 0.13905765116214752]), + Makie.LineTo([0.12343490123748782, 0.16989357054233553]), + Makie.ClosePath()]), + :octagon => BezierPath([Makie.MoveTo([2.2962128485971897e-17, 0.375]), + Makie.LineTo([-0.2651650384068489, + 0.2651650384068489]), + Makie.LineTo([-0.375, 4.5924256971943795e-17]), + Makie.LineTo([-0.2651650384068489, + -0.2651650384068489]), + Makie.LineTo([-6.888638049483202e-17, -0.375]), + Makie.LineTo([0.2651650384068489, + -0.2651650384068489]), + Makie.LineTo([0.375, -9.184851394388759e-17]), + Makie.LineTo([0.2651650384068489, 0.2651650384068489]), + Makie.ClosePath()]), + :hline => BezierPath([Makie.MoveTo([0.315718342192545, -0.063143668438509]), + Makie.LineTo([0.315718342192545, 0.063143668438509]), + Makie.LineTo([-0.315718342192545, 0.063143668438509]), + Makie.LineTo([-0.315718342192545, -0.063143668438509]), + Makie.ClosePath()]), + :hexagon => BezierPath([Makie.MoveTo([2.2962128485971897e-17, 0.375]), + Makie.LineTo([-0.32475952059030533, 0.1875]), + Makie.LineTo([-0.32475952059030533, -0.1875]), + Makie.LineTo([-6.888638049483202e-17, -0.375]), + Makie.LineTo([0.32475952059030533, -0.1875]), + Makie.LineTo([0.32475952059030533, 0.1875]), + Makie.ClosePath()])) function default_marker_map() return DEFAULT_MARKER_MAP @@ -1647,8 +1648,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) @@ -1669,12 +1670,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()` @@ -1717,10 +1718,10 @@ convert_attribute(value, ::key"backlight") = Float32(value) convert_attribute(s::ShaderAbstractions.Sampler{RGBAf}, k::key"color") = s function convert_attribute(s::ShaderAbstractions.Sampler{T,N}, k::key"color") where {T,N} - return 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)], - anisotropic=s.anisotropic, color_swizzel=s.color_swizzel) + return 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)], + anisotropic = s.anisotropic, color_swizzel = s.color_swizzel) end function el32convert(x::ShaderAbstractions.Sampler{T,N}) where {T,N} @@ -1728,10 +1729,10 @@ function el32convert(x::ShaderAbstractions.Sampler{T,N}) where {T,N} T32 === T && return x data = el32convert(x.data) return ShaderAbstractions.Sampler{T32,N,typeof(data)}(data, x.minfilter, x.magfilter, - x.repeat, - x.anisotropic, - x.color_swizzel, - ShaderAbstractions.ArrayUpdater(data, x.updates.update)) + x.repeat, + x.anisotropic, + x.color_swizzel, + ShaderAbstractions.ArrayUpdater(data, x.updates.update)) end to_color(sampler::ShaderAbstractions.Sampler) = el32convert(sampler) diff --git a/src/display.jl b/src/display.jl index c7cf1b3f5b7..fa3c12bdab5 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 @@ -49,7 +49,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 @@ -81,7 +81,7 @@ function merge_screen_config(::Type{Config}, config::Dict) where Config end -const ALWAYS_INLINE_PLOTS = Ref{Union{Automatic, Bool}}(automatic) +const ALWAYS_INLINE_PLOTS = Ref{Union{Automatic,Bool}}(automatic) """ inline!(inline=true) @@ -92,7 +92,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=automatic) +function inline!(inline = automatic) ALWAYS_INLINE_PLOTS[] = inline end @@ -127,9 +127,9 @@ see `?Backend.Screen` or `Base.doc(Backend.Screen)` for applicable options. `backend` accepts Makie backend modules, e.g.: `backend = GLMakie`, `backend = CairoMakie`, etc. """ -function Base.display(figlike::FigureLike; backend=current_backend(), - inline=ALWAYS_INLINE_PLOTS[], update = true, screen_config...) - config = Dict{Symbol, Any}(screen_config) +function Base.display(figlike::FigureLike; backend = current_backend(), + inline = ALWAYS_INLINE_PLOTS[], update = true, screen_config...) + config = Dict{Symbol,Any}(screen_config) if ismissing(backend) error(""" No backend available! @@ -174,7 +174,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...) @@ -255,7 +255,7 @@ function Base.show(io::IO, m::MIME, figlike::FigureLike) backend = current_backend() # get current screen the scene is already displayed on, or create a new screen update_state_before_display!(figlike) - screen = getscreen(backend, scene, Dict(:visible=>false), io, m) + screen = getscreen(backend, scene, Dict(:visible => false), io, m) backend_show(screen, io, m, scene) return screen end @@ -300,19 +300,19 @@ Save a `Scene` with the specified filename and format. - `pt_per_unit`: The size of one scene unit in `pt` when exporting to a vector format. """ 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; - size = Base.size(get_scene(fig)), - resolution = nothing, - backend = current_backend(), - update = true, - screen_config... - ) + file::FileIO.Formatted, fig::FigureLike; + size = Base.size(get_scene(fig)), + resolution = nothing, + backend = current_backend(), + update = true, + screen_config... +) scene = get_scene(fig) if resolution !== nothing @warn "The keyword argument `resolution` for `save()` has been deprecated. Use `size` instead, which better reflects that this is a unitless size and not a pixel resolution." @@ -338,14 +338,14 @@ function FileIO.save( # Else, we create a new scene and update the state of the fig update && update_state_before_display!(fig) visible = isvisible(getscreen(scene)) # if already has a screen, don't hide it! - config = Dict{Symbol, Any}(screen_config) + config = Dict{Symbol,Any}(screen_config) get!(config, :visible, visible) screen = getscreen(backend, scene, config, io, mime) 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 @@ -367,12 +367,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 @@ -395,7 +395,7 @@ function apply_screen_config! end Gets the current screen a scene is associated with. Returns nothing if not yet displayed on a screen. """ -function getscreen(scene::Scene, backend=current_backend()) +function getscreen(scene::Scene, backend = current_backend()) isempty(scene.current_screens) && return nothing # stop search idx = findfirst(scene.current_screens) do screen parentmodule(typeof(screen)) === backend @@ -405,9 +405,9 @@ function getscreen(scene::Scene, backend=current_backend()) return scene.current_screens[idx] end -getscreen(scene::SceneLike, backend=current_backend()) = getscreen(get_scene(scene), backend) +getscreen(scene::SceneLike, backend = current_backend()) = getscreen(get_scene(scene), backend) -function getscreen(backend::Union{Missing, Module}, scene::Scene, _config::Dict, args...) +function getscreen(backend::Union{Missing,Module}, scene::Scene, _config::Dict, args...) screen = getscreen(scene, backend) config = merge_screen_config(backend.ScreenConfig, _config) if !isnothing(screen) && parentmodule(typeof(screen)) == backend @@ -454,7 +454,7 @@ or RGBA. - `screen_config`: Backend dependent, look up via `?Backend.Screen`/`Base.doc(Backend.Screen)` - `update=true`: resets/updates limits. Set to false, if you want to preserver camera movements. """ -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) # if already has a screen, use their visibility value, if no screen, returns false 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 31001416569..d33de136b60 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) = Plot{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 6eb489c804d..c37b3c3e808 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 8c148ec6640..e17e215cb31 100644 --- a/src/ffmpeg-util.jl +++ b/src/ffmpeg-util.jl @@ -46,8 +46,8 @@ struct VideoStreamOptions rawvideo::Bool function VideoStreamOptions( - format::AbstractString, framerate::Real, compression, profile, - pixel_format, loop, loglevel::String, input::String, rawvideo::Bool=true) + format::AbstractString, framerate::Real, compression, profile, + pixel_format, loop, loglevel::String, input::String, rawvideo::Bool = true) if !isa(framerate, Integer) @warn "The given framefrate is not a subtype of `Integer`, and will be rounded to the nearest integer. To supress this warning, provide an integer as the framerate." @@ -69,9 +69,9 @@ struct VideoStreamOptions # items are name, value, allowed_formats allowed_kwargs = [("compression", compression, ("mp4", "webm")), - ("profile", profile, ("mp4",)), - ("pixel_format", pixel_format, ("mp4",)), - ("loop", loop, ("gif",))] + ("profile", profile, ("mp4",)), + ("pixel_format", pixel_format, ("mp4",)), + ("loop", loop, ("gif",))] for (name, value, allowed_formats) in allowed_kwargs if !(format in allowed_formats) && value !== nothing @@ -105,11 +105,11 @@ struct VideoStreamOptions end end -function VideoStreamOptions(; format="mp4", framerate=24, compression=nothing, profile=nothing, pixel_format=nothing, loop=nothing, loglevel="quiet", input="pipe:0", rawvideo=true) +function VideoStreamOptions(; format = "mp4", framerate = 24, compression = nothing, profile = nothing, pixel_format = nothing, loop = nothing, loglevel = "quiet", input = "pipe:0", rawvideo = true) return VideoStreamOptions(format, framerate, compression, profile, pixel_format, loop, 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 @@ -213,9 +213,9 @@ $(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, loop=nothing, - loglevel="quiet", visible=false, update=true, backend=current_backend(), - screen_config...) + format = "mp4", framerate = 24, compression = nothing, profile = nothing, pixel_format = nothing, loop = nothing, + loglevel = "quiet", visible = false, update = true, backend = current_backend(), + screen_config...) dir = mktempdir() path = joinpath(dir, "$(gensym(:video)).$(format)") @@ -268,7 +268,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 @@ -277,12 +277,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) return run(`$(FFMPEG_jll.ffmpeg()) $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") run(`$(FFMPEG_jll.ffmpeg()) -loglevel $(loglevel) -i $video -y $path`) end diff --git a/src/figureplotting.jl b/src/figureplotting.jl index 24dde103026..3831c880997 100644 --- a/src/figureplotting.jl +++ b/src/figureplotting.jl @@ -38,7 +38,7 @@ struct FigureOnly end function args_preferred_axis(::Type{<:Union{Wireframe,Surface,Contour3d}}, x::AbstractArray, y::AbstractArray, - z::AbstractArray) + z::AbstractArray) return all(x -> z[1] ≈ x, z) ? Axis : LScene end @@ -118,7 +118,7 @@ function create_axis_like(plot::AbstractPlot, attributes::Dict, ::Nothing) end end -MakieCore.create_axis_like!(@nospecialize(::AbstractPlot), attributes::Dict, s::Union{Plot, Scene}) = s +MakieCore.create_axis_like!(@nospecialize(::AbstractPlot), attributes::Dict, s::Union{Plot,Scene}) = s function MakieCore.create_axis_like!(@nospecialize(::AbstractPlot), attributes::Dict, ::Nothing) figure = current_figure() @@ -133,7 +133,7 @@ end function MakieCore.create_axis_like!(@nospecialize(::AbstractPlot), attributes::Dict, gp::GridPosition) _disallow_keyword(:figure, attributes) - c = contents(gp; exact=true) + c = contents(gp; exact = true) if !(length(c) == 1 && can_be_current_axis(c[1])) error("There needs to be a single axis-like object at $(gp.span), $(gp.side) to plot into.\nUse a non-mutating plotting command to create an axis implicitly.") end @@ -145,7 +145,7 @@ end function create_axis_like(plot::AbstractPlot, attributes::Dict, gp::GridPosition) _disallow_keyword(:figure, attributes) figure = get_top_parent(gp) - c = contents(gp; exact=true) + c = contents(gp; exact = true) if !isempty(c) error(""" You have used the non-mutating plotting syntax with a GridPosition, which requires an empty GridLayout slot to create an axis in, but there are already the following objects at this layout position: @@ -165,9 +165,9 @@ end function MakieCore.create_axis_like!(@nospecialize(::AbstractPlot), attributes::Dict, gsp::GridSubposition) _disallow_keyword(:figure, attributes) - layout = GridLayoutBase.get_layout_at!(gsp.parent; createmissing=false) + layout = GridLayoutBase.get_layout_at!(gsp.parent; createmissing = false) gp = layout[gsp.rows, gsp.cols, gsp.side] - c = contents(gp; exact=true) + c = contents(gp; exact = true) if !(length(c) == 1 && can_be_current_axis(c[1])) error("There is not just one axis at $(gp).") end @@ -177,8 +177,8 @@ end function create_axis_like(plot::AbstractPlot, attributes::Dict, gsp::GridSubposition) _disallow_keyword(:figure, attributes) - GridLayoutBase.get_layout_at!(gsp.parent; createmissing=true) - c = contents(gsp; exact=true) + GridLayoutBase.get_layout_at!(gsp.parent; createmissing = true) + c = contents(gsp; exact = true) if !isempty(c) error(""" You have used the non-mutating plotting syntax with a GridSubposition, which requires an empty GridLayout slot to create an axis in, but there are already the following objects at this layout position: @@ -208,7 +208,7 @@ end figurelike_return(fa::FigureAxis, plot::AbstractPlot) = FigureAxisPlot(fa.figure, fa.axis, plot) figurelike_return(ax::AbstractAxis, plot::AbstractPlot) = AxisPlot(ax, plot) figurelike_return!(::AbstractAxis, plot::AbstractPlot) = plot -figurelike_return!(::Union{Plot, Scene}, plot::AbstractPlot) = plot +figurelike_return!(::Union{Plot,Scene}, plot::AbstractPlot) = plot update_state_before_display!(f::FigureAxisPlot) = update_state_before_display!(f.figure) @@ -223,7 +223,7 @@ end @inline plot_args(args...) = (nothing, args) @inline function plot_args(a::Union{Figure,AbstractAxis,Scene,Plot,GridSubposition,GridPosition}, - args...) + args...) return (a, args) end function fig_keywords!(kws) @@ -258,9 +258,9 @@ end Tried plotting with `$(F)!` into a `FigureAxisPlot` object, this is not allowed. The `FigureAxisPlot` object is returned by plotting functions not ending in `!` like `lines(...)` or `scatter(...)`. - + It contains the new `Figure`, the new axis object, for example an `Axis`, `LScene` or `Axis3`, and the new plot object. It exists just as a convenience because returning it displays the contained figure. For all further operations, you should split it into its parts instead. This way, it is clear which of its components you are targeting. - + You can do this with the destructuring syntax `fig, ax, plt = some_plot(...)` and then continue, for example with `$(F)!(ax, ...)`. """)) end @@ -270,9 +270,9 @@ end The `AxisPlot` object is returned by plotting functions not ending in `!` with a `GridPosition` as the first argument, like `lines(fig[1, 2], ...)` or `scatter(fig[1, 2], ...)`. - + It contains the new axis object, for example an `Axis`, `LScene` or `Axis3`, and the new plot object. For all further operations, you should split it into its parts instead. This way, it is clear which of its components you are targeting. - + You can do this with the destructuring syntax `ax, plt = some_plot(fig[1, 2], ...)` and then continue, for example with `$(F)!(ax, ...)`. """)) end @@ -294,7 +294,7 @@ end # This enables convert_arguments(::Type{<:AbstractPlot}, ::X) -> FigureSpec # Which skips axis creation # TODO, what to return for the dynamically created axes? -const PlotSpecPlot = Plot{plot, Tuple{<: GridLayoutSpec}} +const PlotSpecPlot = Plot{plot,Tuple{<:GridLayoutSpec}} figurelike_return(f::GridPosition, p::PlotSpecPlot) = p figurelike_return(f::Figure, p::PlotSpecPlot) = FigureAxisPlot(f, nothing, p) diff --git a/src/figures.jl b/src/figures.jl index b349ca71635..45054dc7781 100644 --- a/src/figures.jl +++ b/src/figures.jl @@ -31,7 +31,7 @@ get_scene(gp::GridLayoutBase.GridSubposition) = get_scene(get_figure(gp)) -const CURRENT_FIGURE = Ref{Union{Nothing, Figure}}(nothing) +const CURRENT_FIGURE = Ref{Union{Nothing,Figure}}(nothing) const CURRENT_FIGURE_LOCK = Base.ReentrantLock() """ @@ -40,7 +40,7 @@ const CURRENT_FIGURE_LOCK = Base.ReentrantLock() Returns the current active figure (or the last figure created). Returns `nothing` if there is no current active figure. """ -current_figure() = lock(()-> CURRENT_FIGURE[], CURRENT_FIGURE_LOCK) +current_figure() = lock(() -> CURRENT_FIGURE[], CURRENT_FIGURE_LOCK) """ current_figure!(fig) @@ -93,13 +93,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, theme(:figure_padding)) - scene = Scene(; camera=campixel!, clear = true, kwargs_dict...) + scene = Scene(; camera = campixel!, clear = true, kwargs_dict...) padding = convert(Observable{Any}, padding) alignmode = lift(Outside ∘ to_rectsides, padding) diff --git a/src/interaction/events.jl b/src/interaction/events.jl index fbc08f862a5..f119c396858 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 @@ -83,7 +83,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 @@ -98,7 +98,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 @@ -135,7 +135,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 @@ -173,34 +173,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)))...) @@ -209,14 +209,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 @@ -267,10 +267,10 @@ ispressed(parent, key::Keyboard.Button, waspressed = nothing) = ispressed(events # Boolean Operator evaluation ispressed(parent, op::And, waspressed = nothing) = ispressed(parent, op.left, waspressed) && ispressed(parent, op.right, waspressed) -ispressed(parent, op::Or, waspressed = nothing) = ispressed(parent, op.left, waspressed) || ispressed(parent, op.right, waspressed) +ispressed(parent, op::Or, waspressed = nothing) = ispressed(parent, op.left, waspressed) || ispressed(parent, op.right, waspressed) ispressed(parent, op::Not, waspressed = nothing) = !ispressed(parent, op.x, waspressed) ispressed(parent, op::Exclusively, waspressed = nothing) = ispressed(events(parent), op, waspressed) -ispressed(e::Events, op::Exclusively, waspressed::Union{Mouse.Button, Keyboard.Button}) = op.x == union(e.keyboardstate, e.mousebuttonstate, waspressed) +ispressed(e::Events, op::Exclusively, waspressed::Union{Mouse.Button,Keyboard.Button}) = op.x == union(e.keyboardstate, e.mousebuttonstate, waspressed) ispressed(e::Events, op::Exclusively, waspressed = nothing) = op.x == union(e.keyboardstate, e.mousebuttonstate) # collections diff --git a/src/interaction/inspector.jl b/src/interaction/inspector.jl index 5a536e4c56e..0c107e7f73f 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(A::Point2f, B::Point2f, P::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 @@ -130,9 +131,9 @@ this computes parameter `f` such that the line from `A + f * (B - A)` to inside the quad and that none of the edges cross. """ function point_in_quad_parameter( - A::Point2, B::Point2, C::Point2, D::Point2, P::Point2; - iterations = 50, epsilon = 1e-6 - ) + A::Point2, B::Point2, C::Point2, D::Point2, P::Point2; + iterations = 50, epsilon = 1e-6 +) # Our initial guess is that P is in the center of the quad (in terms of AB and DC) f = 0.5 @@ -206,7 +207,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 @@ -267,10 +268,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) @@ -388,9 +389,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 @@ -468,7 +469,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)}() )) T = Transformation( @@ -509,7 +510,7 @@ 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) @@ -647,7 +648,8 @@ function show_imagelike(inspector, plot, name, edge_based) x, y = pos else i, j, z = _pixelated_getindex(plot[1][], plot[2][], plot[3][], pos, edge_based) - x = i; y = j + x = i + y = j end # in case we hover over NaN values @@ -679,7 +681,7 @@ function show_imagelike(inspector, plot, name, edge_based) if a.enable_indicators[] if plot.interpolate[] if inspector.selection != plot || (length(inspector.temp_plots) != 1) || - !(inspector.temp_plots[1] isa Scatter) + !(inspector.temp_plots[1] isa Scatter) clear_temporary_plots!(inspector, plot) p = scatter!( scene, pos, color = a._color, @@ -687,7 +689,7 @@ function show_imagelike(inspector, plot, name, edge_based) inspectable = false, model = plot.model, # TODO switch to Rect with 2r-1 or 2r-2 markersize to have # just enough space to always detect the underlying image - marker=:rect, markersize = map(r -> 2r, a.range), + marker = :rect, markersize = map(r -> 2r, a.range), strokecolor = a.indicator_color, strokewidth = a.indicator_linewidth, depth_shift = -1f-3 @@ -701,7 +703,7 @@ function show_imagelike(inspector, plot, name, edge_based) else bbox = _pixelated_image_bbox(plot[1][], plot[2][], plot[3][], i, j, edge_based) if inspector.selection != plot || (length(inspector.temp_plots) != 1) || - !(inspector.temp_plots[1] isa Wireframe) + !(inspector.temp_plots[1] isa Wireframe) clear_temporary_plots!(inspector, plot) p = wireframe!( scene, bbox, color = a.indicator_color, model = plot.model, @@ -731,12 +733,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 @@ -750,7 +752,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) @@ -760,16 +762,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 @@ -777,20 +779,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 @@ -802,11 +804,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 @@ -853,7 +855,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.attributes @@ -988,9 +990,9 @@ function show_data(inspector::DataInspector, plot::Band, idx::Integer, mesh::Mes ps2 = plot.converted[2][] # find first triangle containing the cursor position - idx = findfirst(1:length(ps1)-1) do i - point_in_triangle(ps1[i], ps1[i+1], ps2[i+1], pos) || - point_in_triangle(ps1[i], ps2[i+1], ps2[i], pos) + idx = findfirst(1:(length(ps1) - 1)) do i + point_in_triangle(ps1[i], ps1[i + 1], ps2[i + 1], pos) || + point_in_triangle(ps1[i], ps2[i + 1], ps2[i], pos) end if idx !== nothing @@ -998,9 +1000,9 @@ function show_data(inspector::DataInspector, plot::Band, idx::Integer, mesh::Mes # Within the quad we can draw a line from ps1[idx] + f * (ps1[idx+1] - ps1[idx]) # to ps2[idx] + f * (ps2[idx+1] - ps2[idx]) which crosses through the # cursor position. Find the parameter f that describes this line - f = point_in_quad_parameter(ps1[idx], ps1[idx+1], ps2[idx+1], ps2[idx], pos) - P1 = ps1[idx] + f * (ps1[idx+1] - ps1[idx]) - P2 = ps2[idx] + f * (ps2[idx+1] - ps2[idx]) + f = point_in_quad_parameter(ps1[idx], ps1[idx + 1], ps2[idx + 1], ps2[idx], pos) + P1 = ps1[idx] + f * (ps1[idx + 1] - ps1[idx]) + P2 = ps2[idx] + f * (ps2[idx + 1] - ps2[idx]) # Draw the line if a.enable_indicators[] diff --git a/src/interaction/interactive_api.jl b/src/interaction/interactive_api.jl index 4fea246ad69..052095c1f03 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 = collect_atomic_plots(plots) args = range == 1 ? (scene,) : (scene, range) on(events(scene).mouseposition) do mp @@ -56,7 +56,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 @@ -70,7 +70,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 """ @@ -92,15 +92,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) @@ -120,27 +121,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}[] return pick_sorted(scene, screen, xy, range) end function pick_sorted(scene::Scene, screen, xy, range) w, h = size(scene) 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 @@ -162,7 +164,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 @@ -231,7 +233,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) @@ -257,7 +259,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[]) @@ -287,15 +289,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..., ) - 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 @@ -319,7 +321,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 @@ -345,19 +347,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..., ) - 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 @@ -378,7 +380,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 4d6d2855d1d..3fe1f27f692 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,57 +156,57 @@ 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 - button_4 = 3 - button_5 = 4 - button_6 = 5 - button_7 = 6 - button_8 = 7 - 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 + button_4 = 3 + button_5 = 4 + button_6 = 5 + button_7 = 6 + button_8 = 7 +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 203a9257a4d..b2f2b45b541 100644 --- a/src/interaction/observables.jl +++ b/src/interaction/observables.jl @@ -17,18 +17,18 @@ function safe_off(o::Observables.AbstractObservable, f) end end -function on_latest(f, observable::Observable; update=false, spawn=false) - return on_latest(f, nothing, observable; update=update, spawn=spawn) +function on_latest(f, observable::Observable; update = false, spawn = false) + return on_latest(f, nothing, observable; update = update, spawn = spawn) end -function on_latest(f, to_track, observable::Observable; update=false, spawn=false) +function on_latest(f, to_track, observable::Observable; update = false, spawn = false) last_task = nothing has_changed = Threads.Atomic{Bool}(false) function run_f(new_value) try f(new_value) catch e - @warn "Error in f" exception=(e, Base.catch_backtrace()) + @warn "Error in f" exception = (e, Base.catch_backtrace()) end # Since we skip updates completely while executing the above `f` # We need to check after finishing, if the value has changed! @@ -64,19 +64,19 @@ function on_latest(f, to_track, observable::Observable; update=false, spawn=fals end end -function onany_latest(f, observables...; update=false, spawn=false) +function onany_latest(f, observables...; update = false, spawn = false) result = Observable{Any}(map(to_value, observables)) - onany((args...)-> (result[] = args), observables...) - on_latest((args)-> f(args...), result; update=update, spawn=spawn) + onany((args...) -> (result[] = args), observables...) + on_latest((args) -> f(args...), result; update = update, spawn = spawn) end -function map_latest!(f, result::Observable, observables...; update=false, spawn=false) +function map_latest!(f, result::Observable, observables...; update = false, spawn = false) callback = Observables.MapCallback(f, result, observables) - return onany_latest(callback, observables...; update=update, spawn=spawn) + return onany_latest(callback, observables...; update = update, spawn = spawn) end -function map_latest(f, observables...; spawn=false, ignore_equal_values=false) - result = Observable(f(map(to_value, observables)...); ignore_equal_values=ignore_equal_values) - map_latest!(f, result, observables...; spawn=spawn) +function map_latest(f, observables...; spawn = false, ignore_equal_values = false) + result = Observable(f(map(to_value, observables)...); ignore_equal_values = ignore_equal_values) + map_latest!(f, result, observables...; spawn = spawn) return result end diff --git a/src/interaction/ray_casting.jl b/src/interaction/ray_casting.jl index 75f52c77e18..fa54e533aa6 100644 --- a/src/interaction/ray_casting.jl +++ b/src/interaction/ray_casting.jl @@ -56,16 +56,16 @@ function Ray(scene::Scene, cam::Camera2D, xy::VecTypes{2}) m = Vec2f(pv[1, 1], pv[2, 2]) b = Vec2f(pv[1, 4], pv[2, 4]) origin = (2 * rel_pos .- 1 - b) ./ m - return Ray(to_ndim(Point3f, origin, 10_000f0), Vec3f(0,0,-1)) + return Ray(to_ndim(Point3f, origin, 10_000f0), Vec3f(0, 0, -1)) end function Ray(::Scene, ::PixelCamera, xy::VecTypes{2}) - return Ray(to_ndim(Point3f, xy, 10_000f0), Vec3f(0,0,-1)) + return Ray(to_ndim(Point3f, xy, 10_000f0), Vec3f(0, 0, -1)) end function Ray(scene::Scene, ::RelativeCamera, xy::VecTypes{2}) origin = xy ./ widths(scene) - return Ray(to_ndim(Point3f, origin, 10_000f0), Vec3f(0,0,-1)) + return Ray(to_ndim(Point3f, origin, 10_000f0), Vec3f(0, 0, -1)) end Ray(scene::Scene, cam, xy::VecTypes{2}) = ray_from_projectionview(scene, xy) @@ -98,8 +98,8 @@ end function transform(M::Mat4f, ray::Ray) p4d = M * to_ndim(Point4f, ray.origin, 1f0) - dir = normalize(M[Vec(1,2,3), Vec(1,2,3)] * ray.direction) - return Ray(p4d[Vec(1,2,3)] / p4d[4], dir) + dir = normalize(M[Vec(1, 2, 3), Vec(1, 2, 3)] * ray.direction) + return Ray(p4d[Vec(1, 2, 3)] / p4d[4], dir) end @@ -151,8 +151,9 @@ end function ray_rect_intersection(rect::Rect2f, ray::Ray) possible_hit = ray.origin - ray.origin[3] / ray.direction[3] * ray.direction - min = minimum(rect); max = maximum(rect) - if all(min <= possible_hit[Vec(1,2)] <= max) + min = minimum(rect) + max = maximum(rect) + if all(min <= possible_hit[Vec(1, 2)] <= max) return possible_hit end return Point3f(NaN) @@ -239,7 +240,7 @@ function position_on_plot(plot::AbstractPlot, idx::Integer; apply_transform = tr end -function position_on_plot(plot::Union{Scatter, MeshScatter}, idx, ray::Ray; apply_transform = true) +function position_on_plot(plot::Union{Scatter,MeshScatter}, idx, ray::Ray; apply_transform = true) point = plot[1][][idx] point3f = to_ndim(Point3f, point, 0.0f0) point_t = if apply_transform && !isnan(point3f) @@ -250,11 +251,11 @@ function position_on_plot(plot::Union{Scatter, MeshScatter}, idx, ray::Ray; appl return to_ndim(typeof(point), point_t, 0.0f0) end -function position_on_plot(plot::Union{Lines, LineSegments}, idx, ray::Ray; apply_transform = true) +function position_on_plot(plot::Union{Lines,LineSegments}, idx, ray::Ray; apply_transform = true) if idx == 1 idx = 2 end - p0, p1 = apply_transform_and_model(plot, plot[1][][(idx-1):idx]) + p0, p1 = apply_transform_and_model(plot, plot[1][][(idx - 1):idx]) pos = closest_point_on_line(p0, p1, ray) @@ -268,7 +269,7 @@ function position_on_plot(plot::Union{Lines, LineSegments}, idx, ray::Ray; apply end end -function position_on_plot(plot::Union{Heatmap, Image}, idx, ray::Ray; apply_transform = true) +function position_on_plot(plot::Union{Heatmap,Image}, idx, ray::Ray; apply_transform = true) # Heatmap and Image are always a Rect2f. The transform function is currently # not allowed to change this, so applying it should be fine. Applying the # model matrix may add a z component to the Rect2f, which we can't represent. @@ -317,11 +318,11 @@ function position_on_plot(plot::Mesh, idx, ray::Ray; apply_transform = true) end # Handling indexing into different surface input types -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] @@ -335,7 +336,8 @@ function position_on_plot(plot::Surface, idx, ray::Ray; apply_transform = true) 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) ray = transform(inv(plot.model[]), ray) tf = transform_func(plot) @@ -343,14 +345,14 @@ function position_on_plot(plot::Surface, idx, ray::Ray; apply_transform = true) # This isn't the most accurate so we include some neighboring faces 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 # transforms only apply to x and y coordinates of surfaces - A = surface_pos(xs, ys, zs, i, j) - B = surface_pos(xs, ys, zs, i-1, j) - C = surface_pos(xs, ys, zs, i, j+1) + A = surface_pos(xs, ys, zs, i, j) + B = surface_pos(xs, ys, zs, i - 1, j) + C = surface_pos(xs, ys, zs, i, j + 1) A, B, C = map((A, B, C)) do p xy = Makie.apply_transform(tf, Point2f(p), space) Point3f(xy[1], xy[2], p[3]) @@ -359,9 +361,9 @@ function position_on_plot(plot::Surface, idx, ray::Ray; apply_transform = true) end if i + 1 <= w && isnan(pos) - A = surface_pos(xs, ys, zs, i, j) - B = surface_pos(xs, ys, zs, i, j+1) - C = surface_pos(xs, ys, zs, i+1, j+1) + A = surface_pos(xs, ys, zs, i, j) + B = surface_pos(xs, ys, zs, i, j + 1) + C = surface_pos(xs, ys, zs, i + 1, j + 1) A, B, C = map((A, B, C)) do p xy = Makie.apply_transform(tf, Point2f(p), space) Point3f(xy[1], xy[2], p[3]) diff --git a/src/interfaces.jl b/src/interfaces.jl index bcd154eabf9..550b60de3af 100644 --- a/src/interfaces.jl +++ b/src/interfaces.jl @@ -1,5 +1,5 @@ -function add_cycle_attribute!(plot::Plot, scene::Scene, cycle=get_cycle_for_plottype(plot.cycle[])) +function add_cycle_attribute!(plot::Plot, scene::Scene, cycle = get_cycle_for_plottype(plot.cycle[])) cycler = scene.cycler palette = scene.theme.palette add_cycle_attributes!(plot, cycle, cycler, palette) @@ -15,25 +15,25 @@ function color_and_colormap!(plot, colors = plot.color) attributes(plot.attributes)[:calculated_colors] = colors end -function calculated_attributes!(::Type{<: AbstractPlot}, plot) +function calculated_attributes!(::Type{<:AbstractPlot}, plot) scene = parent_scene(plot) if !isnothing(scene) && haskey(plot, :cycle) add_cycle_attribute!(plot, scene) end end -function calculated_attributes!(::Type{<: Mesh}, plot) +function calculated_attributes!(::Type{<:Mesh}, plot) mesha = lift(GeometryBasics.attributes, plot, plot.mesh) - color = haskey(mesha[], :color) ? lift(x-> x[:color], plot, mesha) : plot.color + color = haskey(mesha[], :color) ? lift(x -> x[:color], plot, mesha) : plot.color color_and_colormap!(plot, color) return end -function calculated_attributes!(::Type{<: Union{Heatmap, Image}}, plot) +function calculated_attributes!(::Type{<:Union{Heatmap,Image}}, plot) color_and_colormap!(plot, plot[3]) end -function calculated_attributes!(::Type{<: Surface}, plot) +function calculated_attributes!(::Type{<:Surface}, plot) colors = plot[3] if haskey(plot, :color) color = plot[:color][] @@ -44,7 +44,7 @@ function calculated_attributes!(::Type{<: Surface}, plot) color_and_colormap!(plot, colors) end -function calculated_attributes!(::Type{<: MeshScatter}, plot) +function calculated_attributes!(::Type{<:MeshScatter}, plot) color_and_colormap!(plot) return end @@ -59,7 +59,7 @@ function calculated_attributes!(::Type{<:Text}, plot) return end -function calculated_attributes!(::Type{<: Scatter}, plot) +function calculated_attributes!(::Type{<:Scatter}, plot) # calculate base case color_and_colormap!(plot) @@ -72,7 +72,7 @@ function calculated_attributes!(::Type{<: Scatter}, plot) replace_automatic!(plot, :markerspace) do lift(plot, 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 @@ -81,7 +81,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}} pos = plot[1][] # extend one color/linewidth per linesegment to be one (the same) color/linewidth per vertex if T <: LineSegments @@ -103,7 +103,7 @@ const atomic_functions = ( text, meshscatter, scatter, mesh, linesegments, lines, surface, volume, heatmap, image ) -const Atomic{Arg} = Union{map(x-> Plot{x, Arg}, atomic_functions)...} +const Atomic{Arg} = Union{map(x -> Plot{x,Arg}, atomic_functions)...} function convert_arguments!(plot::Plot{F}) where {F} P = Plot{F,Any} @@ -186,9 +186,9 @@ used_attributes(args...) = () # Chose the more specific plot type from arguments or input type # Note the plottype(Scatter, Plot{plot}) will return Scatter # And plottype(args...) falls back to Plot{plot} -plottype(P::Type{<: Plot{T}}, argvalues...) where T = plottype(P, plottype(argvalues...)) +plottype(P::Type{<:Plot{T}}, argvalues...) where T = plottype(P, plottype(argvalues...)) plottype(P::Type{<:Plot{T}}) where {T} = P -plottype(P1::Type{<:Plot{T1}}, ::Type{<:Plot{T2}}) where {T1, T2} = P1 +plottype(P1::Type{<:Plot{T1}}, ::Type{<:Plot{T2}}) where {T1,T2} = P1 plottype(::Type{Plot{plot}}, ::Type{Plot{plot}}) = Plot{plot} """ plottype(P1::Type{<: Plot{T1}}, P2::Type{<: Plot{T2}}) @@ -209,8 +209,8 @@ plottype(P::Type{<:Plot{T}}, ::Type{Plot{plot}}) where {T} = P 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 @@ -267,7 +267,7 @@ function plot!(scene::SceneLike, plot::Plot) return plot end -function apply_theme!(scene::Scene, plot::P) where {P<: Plot} +function apply_theme!(scene::Scene, plot::P) where {P<:Plot} raw_attr = attributes(plot.attributes) plot_theme = default_theme(scene, P) plot_sym = plotsym(P) 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 24305d1d28c..9074813ca5a 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( @@ -421,12 +424,12 @@ raster, rest = rasterizer( ) 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 0a9226d16b1..3f4008d1651 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 @@ -129,7 +129,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, @@ -141,23 +141,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 92d4e94a38b..e70b00163ba 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 data_limits(text::Text{<: Tuple{<: Union{GlyphCollection, AbstractVector{GlyphCollection}}}}) +function data_limits(text::Text{<:Tuple{<:Union{GlyphCollection,AbstractVector{GlyphCollection}}}}) if is_data_space(text.markerspace[]) return boundingbox(text) else @@ -84,14 +84,14 @@ function br_getindex(matrix::AbstractMatrix, idx::CartesianIndex, dim::Int) return matrix[idx] end -function point_iterator(plot::Union{Image, Heatmap, Surface}) +function point_iterator(plot::Union{Image,Heatmap,Surface}) rect = data_limits(plot) return unique(decompose(Point3f, rect)) 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)) @@ -100,7 +100,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) @@ -182,7 +182,7 @@ function data_limits(plot::AbstractPlot) return bb_ref[] end -function _update_rect(rect::Rect{N, T}, point::VecTypes{N, T}) where {N, T} +function _update_rect(rect::Rect{N,T}, point::VecTypes{N,T}) where {N,T} mi = minimum(rect) ma = maximum(rect) mis_mas = map(mi, ma, point) do _mi, _ma, _p @@ -218,7 +218,7 @@ function limits_from_transformed_points(positions, scales, rotations, element_bb return full_bbox[] 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 4765bbc7cad..28fbf42a4d8 100644 --- a/src/layouting/layouting.jl +++ b/src/layouting/layouting.jl @@ -41,10 +41,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) @@ -70,13 +70,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 @@ -116,13 +116,13 @@ function glyph_collection( x += ci.extent.hadvance * first(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 * first(ci.scale) # TODO Do we need to redo the metrics for newlines? @@ -137,7 +137,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)) @@ -246,7 +246,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) @@ -301,7 +301,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 409328f6308..63000b6beeb 100644 --- a/src/layouting/transformation.jl +++ b/src/layouting/transformation.jl @@ -1,13 +1,13 @@ Base.parent(t::Transformation) = isassigned(t.parent) ? t.parent[] : nothing -function Observables.connect!(parent::Transformation, child::Transformation; connect_func=true) +function Observables.connect!(parent::Transformation, child::Transformation; connect_func = true) tfuncs = [] - obsfunc = on(parent.model; update=true) do m + obsfunc = on(parent.model; update = true) do m return child.parent_model[] = m end push!(tfuncs, obsfunc) if connect_func - t2 = on(parent.transform_func; update=true) do f + t2 = on(parent.transform_func; update = true) do f child.transform_func[] = f return end @@ -40,23 +40,23 @@ end function translated(scene::Scene; kw_args...) tscene = Scene(scene, transformation = Transformation()) transform!(tscene; kw_args...) - tscene + tscene end function transform!( - t::Transformable; - translation = Vec3f(0), - scale = Vec3f(1), - rotation = 0.0, - ) + t::Transformable; + translation = Vec3f(0), + scale = Vec3f(1), + rotation = 0.0, +) translate!(t, to_value(translation)) scale!(t, to_value(scale)) rotate!(t, to_value(rotation)) end function transform!( - t::Transformable, attributes::Union{Attributes, AbstractDict, NamedTuple} - ) + t::Transformable, attributes::Union{Attributes,AbstractDict,NamedTuple} +) transform!(t; attributes...) end @@ -153,20 +153,20 @@ Translate the given `Transformable` (a Scene or Plot), relative to its current p """ translate!(::Type{T}, t::Transformable, xyz...) where T = translate!(T, t, xyz) -function transform!(t::Transformable, x::Tuple{Symbol, <: Number}) +function transform!(t::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!(t, 0, 0, dimval) - elseif all(x-> x in ('x', 'z'), plane) # xz plane + elseif all(x -> x in ('x', 'z'), plane) # xz plane rotate!(t, Vec3f(1, 0, 0), 0.5pi) translate!(t, 0, dimval, 0) else #yz plane r1 = qrotation(Vec3f(0, 1, 0), 0.5pi) r2 = qrotation(Vec3f(1, 0, 0), 0.5pi) - rotate!(t, r2 * r1) + rotate!(t, r2 * r1) translate!(t, dimval, 0, 0) end t @@ -212,7 +212,7 @@ 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) + return lift((f, d, s) -> apply_transform(f, d, s), f, data, space) end """ @@ -226,26 +226,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 @@ -256,14 +256,14 @@ 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 @@ -271,23 +271,23 @@ function apply_transform(f, data::AbstractArray) 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]), @@ -295,13 +295,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]) @@ -327,49 +327,51 @@ 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 const pseudolog10 = ReversibleScale( x -> sign(x) * log10(abs(x) + 1), x -> sign(x) * (exp10(abs(x)) - 1); - limits=(0f0, 3f0), - name=:pseudolog10 + limits = (0f0, 3f0), + name = :pseudolog10 ) Symlog10(hi) = Symlog10(-hi, hi) function Symlog10(lo, hi) - forward(x) = if x > 0 - x <= hi ? x / hi * log10(hi) : log10(x) - elseif x < 0 - x >= lo ? x / abs(lo) * log10(abs(lo)) : -log10(abs(x)) - else - x - end - inverse(x) = if x > 0 - l = log10(hi) - x <= l ? x / l * hi : exp10(x) - elseif x < 0 - l = -log10(abs(lo)) - x >= l ? x / l * abs(lo) : -exp10(abs(x)) - else - x - end - return ReversibleScale(forward, inverse; limits=(0.0f0, 3.0f0), name=:Symlog10) + forward(x) = + if x > 0 + x <= hi ? x / hi * log10(hi) : log10(x) + elseif x < 0 + x >= lo ? x / abs(lo) * log10(abs(lo)) : -log10(abs(x)) + else + x + end + inverse(x) = + if x > 0 + l = log10(hi) + x <= l ? x / l * hi : exp10(x) + elseif x < 0 + l = -log10(abs(lo)) + x >= l ? x / l * abs(lo) : -exp10(abs(x)) + else + x + end + return ReversibleScale(forward, inverse; limits = (0.0f0, 3.0f0), name = :Symlog10) end inverse_transform(::typeof(identity)) = identity inverse_transform(::typeof(log10)) = exp10 inverse_transform(::typeof(log2)) = exp2 inverse_transform(::typeof(log)) = exp -inverse_transform(::typeof(sqrt)) = x -> x ^ 2 +inverse_transform(::typeof(sqrt)) = x -> x^2 inverse_transform(F::Tuple) = map(inverse_transform, F) inverse_transform(::typeof(logit)) = logistic inverse_transform(s::ReversibleScale) = s.inverse inverse_transform(::Any) = 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 @@ -413,7 +415,7 @@ end Base.broadcastable(x::Polar) = (x,) -function apply_transform(trans::Polar, point::VecTypes{2, T}) where T <: Real +function apply_transform(trans::Polar, point::VecTypes{2,T}) where T<:Real if trans.theta_as_x θ, r = point else @@ -429,14 +431,14 @@ function apply_transform(trans::Polar, point::VecTypes{2, T}) where T <: Real end # Point2 may get expanded to Point3. In that case we leave z untransformed -function apply_transform(f::Polar, point::VecTypes{N2, T}) where {N2, T} +function apply_transform(f::Polar, point::VecTypes{N2,T}) where {N2,T} p_dim = to_ndim(Point2f, point, 0.0) p_trans = apply_transform(f, p_dim) if 2 < N2 - p_large = ntuple(i-> i <= 2 ? p_trans[i] : point[i], N2) - return Point{N2, Float32}(p_large) + p_large = ntuple(i -> i <= 2 ? 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 @@ -444,7 +446,7 @@ function inverse_transform(trans::Polar) if trans.theta_as_x return Makie.PointTrans{2}() do point typeof(point)( - mod(trans.direction * atan(point[2], point[1]) - trans.theta_0, 0..2pi), + mod(trans.direction * atan(point[2], point[1]) - trans.theta_0, 0 .. 2pi), hypot(point[1], point[2]) + trans.r0 ) end @@ -452,7 +454,7 @@ function inverse_transform(trans::Polar) return Makie.PointTrans{2}() do point typeof(point)( hypot(point[1], point[2]) + trans.r0, - mod(trans.direction * atan(point[2], point[1]) - trans.theta_0, 0..2pi) + mod(trans.direction * atan(point[2], point[1]) - trans.theta_0, 0 .. 2pi) ) end end diff --git a/src/lighting.jl b/src/lighting.jl index ca2b21e1ca1..ff58878a77b 100644 --- a/src/lighting.jl +++ b/src/lighting.jl @@ -4,12 +4,12 @@ abstract type AbstractLight end # These need to match up with light shaders to differentiate light types module LightType - const UNDEFINED = 0 - const Ambient = 1 - const PointLight = 2 - const DirectionalLight = 3 - const SpotLight = 4 - const RectLight = 5 +const UNDEFINED = 0 +const Ambient = 1 +const PointLight = 2 +const DirectionalLight = 3 +const SpotLight = 4 +const RectLight = 5 end # Each light should implement @@ -59,15 +59,15 @@ struct PointLight <: AbstractLight end # no attenuation -function PointLight(color::Union{Colorant, Observable{<: Colorant}}, position::Union{VecTypes{3}, Observable{<: VecTypes{3}}}) +function PointLight(color::Union{Colorant,Observable{<:Colorant}}, position::Union{VecTypes{3},Observable{<:VecTypes{3}}}) return PointLight(color, position, Vec2f(0)) end # automatic attenuation -function PointLight(color::Union{Colorant, Observable{<: Colorant}}, position::Union{VecTypes{3}, Observable{<: VecTypes{3}}}, range::Real) +function PointLight(color::Union{Colorant,Observable{<:Colorant}}, position::Union{VecTypes{3},Observable{<:VecTypes{3}}}, range::Real) return PointLight(color, position, default_attenuation(range)) end -@deprecate PointLight(position::Union{VecTypes{3}, Observable{<: VecTypes{3}}}, color::Union{Colorant, Observable{<: Colorant}}) PointLight(color, position) +@deprecate PointLight(position::Union{VecTypes{3},Observable{<:VecTypes{3}}}, color::Union{Colorant,Observable{<:Colorant}}) PointLight(color, position) light_type(::PointLight) = LightType.PointLight light_color(l::PointLight) = l.color[] @@ -75,8 +75,8 @@ light_color(l::PointLight) = l.color[] # fit of values used on learnopengl/ogre3d function default_attenuation(range::Real) return Vec2f( - 4.690507869767646 * range ^ -1.009712247799057, - 82.4447791934059 * range ^ -2.0192061630628966 + 4.690507869767646 * range^-1.009712247799057, + 82.4447791934059 * range^-2.0192061630628966 ) end @@ -169,11 +169,12 @@ end RectLight(color, pos, u1, u2) = RectLight(color, pos, u1, u2, -normalize(cross(u1, u2))) function RectLight(color, r::Rect2) - mini = minimum(r); ws = widths(r) + mini = minimum(r) + ws = widths(r) position = Observable(to_ndim(Point3f, mini + 0.5 * ws, 0)) u1 = Observable(Vec3f(ws[1], 0, 0)) u2 = Observable(Vec3f(0, ws[2], 0)) - return RectLight(color, position, u1, u2, normalize(Vec3f(0,0,-1))) + return RectLight(color, position, u1, u2, normalize(Vec3f(0, 0, -1))) end # Implement Transformable interface (more or less) to simplify working with @@ -222,12 +223,12 @@ light_color(l::RectLight) = l.color[] function get_one_light(lights, Typ) - indices = findall(x-> x isa Typ, lights) + indices = findall(x -> x isa Typ, lights) isempty(indices) && return nothing return lights[indices[1]] end -function default_shading!(plot, lights::Vector{<: AbstractLight}) +function default_shading!(plot, lights::Vector{<:AbstractLight}) # if the plot does not have :shading we assume the plot doesn't support it haskey(plot.attributes, :shading) || return @@ -275,4 +276,4 @@ function default_shading!(plot, lights::Vector{<: AbstractLight}) plot.attributes[:shading] = shading return -end \ No newline at end of file +end diff --git a/src/makielayout/blocks.jl b/src/makielayout/blocks.jl index c6bf0bdb73f..650ab2b2766 100644 --- a/src/makielayout/blocks.jl +++ b/src/makielayout/blocks.jl @@ -6,7 +6,7 @@ function attribute_default_expressions end function _attribute_docs end function has_forwarded_layout end -macro Block(_name::Union{Expr, Symbol}, body::Expr = Expr(:block)) +macro Block(_name::Union{Expr,Symbol}, body::Expr = Expr(:block)) body.head === :block || error("A Block needs to be defined within a `begin end` block") @@ -14,7 +14,7 @@ macro Block(_name::Union{Expr, Symbol}, body::Expr = Expr(:block)) name = _name isa Symbol ? _name : _name.args[1] structdef = quote mutable struct $(type_expr) - parent::Union{Figure, Scene, Nothing} + parent::Union{Figure,Scene,Nothing} layoutobservables::Makie.LayoutObservables{GridLayout} blockscene::Scene end @@ -27,7 +27,7 @@ macro Block(_name::Union{Expr, 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 @@ -63,7 +63,7 @@ macro Block(_name::Union{Expr, 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.fast_deepcopy($(Makie).CURRENT_DEFAULT_THEME) $(make_attr_dict_expr(attrs, :sceneattrs, :curdeftheme)) @@ -72,9 +72,9 @@ macro Block(_name::Union{Expr, 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 @@ -83,8 +83,8 @@ macro Block(_name::Union{Expr, 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 @@ -172,7 +172,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 @@ -261,7 +261,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 @@ -272,18 +272,18 @@ function _block(T::Type{<:Block}, 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...) return _block(T, fig_or_scene, Any[args...], Dict{Symbol,Any}(kwargs), bbox) end -function block_defaults(blockname::Symbol, attribute_kwargs::Dict, scene::Union{Nothing, Scene}) +function block_defaults(blockname::Symbol, attribute_kwargs::Dict, scene::Union{Nothing,Scene}) return block_defaults(getfield(Makie, blockname), attribute_kwargs, scene) end -function block_defaults(::Type{B}, attribute_kwargs::Dict, scene::Union{Nothing, Scene}) where {B <: Block} +function block_defaults(::Type{B}, attribute_kwargs::Dict, scene::Union{Nothing,Scene}) where {B<:Block} default_attrs = default_attribute_values(B, scene) blockname = nameof(B) typekey_scene_attrs = get(theme(scene), blockname, Attributes()) - typekey_attrs = theme(blockname; default=Attributes())::Attributes + typekey_attrs = theme(blockname; default = Attributes())::Attributes attributes = Dict{Symbol,Any}() # make a final attribute dictionary using different priorities # for the different themes @@ -305,12 +305,12 @@ function block_defaults(::Type{B}, attribute_kwargs::Dict, scene::Union{Nothing, return attributes end -function _block(T::Type{<:Block}, fig_or_scene::Union{Figure,Scene}, args, kwdict::Dict, bbox; kwdict_complete=false) +function _block(T::Type{<:Block}, fig_or_scene::Union{Figure,Scene}, args, kwdict::Dict, bbox; kwdict_complete = false) # first sort out all user kwargs that correspond to block attributes check_textsize_deprecation(kwdict) - 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) @@ -349,7 +349,7 @@ function _block(T::Type{<:Block}, fig_or_scene::Union{Figure,Scene}, args, kwdic suggestedbbox = bbox ) - blockscene = Scene(topscene, clear=false, camera = campixel!) + blockscene = Scene(topscene, clear = false, camera = campixel!) # create base block with otherwise undefined fields b = T(fig_or_scene, lobservables, blockscene) @@ -418,7 +418,7 @@ end """ Get the scene which blocks need from their parent to plot stuff into """ -get_topscene(f::Union{GridPosition, GridSubposition}) = get_topscene(get_top_parent(f)) +get_topscene(f::Union{GridPosition,GridSubposition}) = get_topscene(get_top_parent(f)) get_topscene(f::Figure) = f.scene function get_topscene(s::Scene) if !(Makie.cameracontrols(s) isa Makie.PixelCamera) @@ -450,7 +450,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 @@ -459,7 +459,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 @@ -470,7 +470,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 e43c2d6f74c..e81c9c34931 100644 --- a/src/makielayout/blocks/axis.jl +++ b/src/makielayout/blocks/axis.jl @@ -54,7 +54,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, scene, ax, mouseeventhandle.obs) @@ -113,16 +113,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 @@ -160,13 +160,13 @@ end function initialize_block!(ax::Axis; palette = nothing) blockscene = ax.blockscene - elements = Dict{Symbol, Any}() + elements = Dict{Symbol,Any}() ax.elements = elements # 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) @@ -182,7 +182,7 @@ function initialize_block!(ax::Axis; palette = nothing) scenearea = sceneareanode!(ax.layoutobservables.computedbbox, finallimits, ax.aspect) - scene = Scene(blockscene, viewport=scenearea) + scene = Scene(blockscene, viewport = scenearea) ax.scene = scene if !isnothing(palette) @@ -193,7 +193,7 @@ function initialize_block!(ax::Axis; palette = nothing) # TODO: replace with mesh, however, CairoMakie needs a poly path for this signature # so it doesn't rasterize the scene - background = poly!(blockscene, scenearea; color=ax.backgroundcolor, inspectable=false, shading=NoShading, strokecolor=:transparent) + background = poly!(blockscene, scenearea; color = ax.backgroundcolor, inspectable = false, shading = NoShading, strokecolor = :transparent) translate!(background, 0, 0, -100) elements[:background] = background @@ -203,7 +203,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!( blockscene, xgridnode, linewidth = ax.xgridwidth, visible = ax.xgridvisible, color = ax.xgridcolor, linestyle = ax.xgridstyle, inspectable = false @@ -212,7 +212,7 @@ function initialize_block!(ax::Axis; palette = nothing) translate!(xgridlines, 0, 0, -10) elements[:xgridlines] = xgridlines - xminorgridnode = Observable(Point2f[]; ignore_equal_values=true) + xminorgridnode = Observable(Point2f[]; ignore_equal_values = true) xminorgridlines = linesegments!( blockscene, xminorgridnode, linewidth = ax.xminorgridwidth, visible = ax.xminorgridvisible, color = ax.xminorgridcolor, linestyle = ax.xminorgridstyle, inspectable = false @@ -221,7 +221,7 @@ function initialize_block!(ax::Axis; palette = nothing) translate!(xminorgridlines, 0, 0, -10) elements[:xminorgridlines] = xminorgridlines - ygridnode = Observable(Point2f[]; ignore_equal_values=true) + ygridnode = Observable(Point2f[]; ignore_equal_values = true) ygridlines = linesegments!( blockscene, ygridnode, linewidth = ax.ygridwidth, visible = ax.ygridvisible, color = ax.ygridcolor, linestyle = ax.ygridstyle, inspectable = false @@ -230,7 +230,7 @@ function initialize_block!(ax::Axis; palette = nothing) translate!(ygridlines, 0, 0, -10) elements[:ygridlines] = ygridlines - yminorgridnode = Observable(Point2f[]; ignore_equal_values=true) + yminorgridnode = Observable(Point2f[]; ignore_equal_values = true) yminorgridlines = linesegments!( blockscene, yminorgridnode, linewidth = ax.yminorgridwidth, visible = ax.yminorgridvisible, color = ax.yminorgridcolor, linestyle = ax.yminorgridstyle, inspectable = false @@ -256,10 +256,10 @@ function initialize_block!(ax::Axis; palette = nothing) # 3. Update the view onto the plot (camera matrices) onany(update_axis_camera, blockscene, camera(scene), scene.transformation.transform_func, finallimits, - ax.xreversed, ax.yreversed; priority=-2) + ax.xreversed, ax.yreversed; priority = -2) xaxis_endpoints = lift(blockscene, ax.xaxisposition, scene.viewport; - ignore_equal_values=true) do xaxisposition, area + ignore_equal_values = true) do xaxisposition, area if xaxisposition === :bottom return bottomline(Rect2f(area)) elseif xaxisposition === :top @@ -270,7 +270,7 @@ function initialize_block!(ax::Axis; palette = nothing) end yaxis_endpoints = lift(blockscene, ax.yaxisposition, scene.viewport; - ignore_equal_values=true) do yaxisposition, area + ignore_equal_values = true) do yaxisposition, area if yaxisposition === :left return leftline(Rect2f(area)) elseif yaxisposition === :right @@ -280,44 +280,44 @@ function initialize_block!(ax::Axis; palette = nothing) end end - xaxis_flipped = lift(x -> x === :top, blockscene, ax.xaxisposition; ignore_equal_values=true) - yaxis_flipped = lift(x -> x === :right, blockscene, ax.yaxisposition; ignore_equal_values=true) + xaxis_flipped = lift(x -> x === :top, blockscene, ax.xaxisposition; ignore_equal_values = true) + yaxis_flipped = lift(x -> x === :right, blockscene, ax.yaxisposition; ignore_equal_values = true) xspinevisible = lift(blockscene, xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible; - ignore_equal_values=true) do xflip, bv, tv + ignore_equal_values = true) do xflip, bv, tv xflip ? tv : bv end xoppositespinevisible = lift(blockscene, xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible; - ignore_equal_values=true) do xflip, bv, tv + ignore_equal_values = true) do xflip, bv, tv xflip ? bv : tv end yspinevisible = lift(blockscene, yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible; - ignore_equal_values=true) do yflip, lv, rv + ignore_equal_values = true) do yflip, lv, rv yflip ? rv : lv end yoppositespinevisible = lift(blockscene, yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible; - ignore_equal_values=true) do yflip, lv, rv + ignore_equal_values = true) do yflip, lv, rv yflip ? lv : rv end xspinecolor = lift(blockscene, xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor; - ignore_equal_values=true) do xflip, bc, tc + ignore_equal_values = true) do xflip, bc, tc xflip ? tc : bc end xoppositespinecolor = lift(blockscene, xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor; - ignore_equal_values=true) do xflip, bc, tc + ignore_equal_values = true) do xflip, bc, tc xflip ? bc : tc end yspinecolor = lift(blockscene, yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor; - ignore_equal_values=true) do yflip, lc, rc + ignore_equal_values = true) do yflip, lc, rc yflip ? rc : lc end yoppositespinecolor = lift(blockscene, yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor; - ignore_equal_values=true) do yflip, lc, rc + ignore_equal_values = true) do yflip, lc, rc yflip ? lc : rc end - xlims = lift(xlimits, blockscene, finallimits; ignore_equal_values=true) - ylims = lift(ylimits, blockscene, finallimits; ignore_equal_values=true) + xlims = lift(xlimits, blockscene, finallimits; ignore_equal_values = true) + ylims = lift(ylimits, blockscene, finallimits; ignore_equal_values = true) xaxis = LineAxis(blockscene, endpoints = xaxis_endpoints, limits = xlims, flipped = xaxis_flipped, ticklabelrotation = ax.xticklabelrotation, @@ -329,7 +329,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(blockscene, endpoints = yaxis_endpoints, limits = ylims, @@ -340,14 +340,14 @@ 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(blockscene, scene.viewport, ax.spinewidth, ax.xaxisposition; - ignore_equal_values=true) do r, sw, xaxpos + ignore_equal_values = true) do r, sw, xaxpos if xaxpos === :top y = bottom(r) p1 = Point2f(left(r) - 0.5sw, y) @@ -362,7 +362,7 @@ function initialize_block!(ax::Axis; palette = nothing) end yoppositelinepoints = lift(blockscene, scene.viewport, ax.spinewidth, ax.yaxisposition; - ignore_equal_values=true) do r, sw, yaxpos + ignore_equal_values = true) do r, sw, yaxpos if yaxpos === :right x = left(r) p1 = Point2f(x, bottom(r) - 0.5sw) @@ -377,22 +377,22 @@ function initialize_block!(ax::Axis; palette = nothing) end xticksmirrored = lift(mirror_ticks, blockscene, xaxis.tickpositions, ax.xticksize, ax.xtickalign, - scene.viewport, :x, ax.xaxisposition[], ax.spinewidth) + scene.viewport, :x, ax.xaxisposition[], ax.spinewidth) xticksmirrored_lines = linesegments!(blockscene, xticksmirrored, visible = @lift($(ax.xticksmirrored) && $(ax.xticksvisible)), linewidth = ax.xtickwidth, color = ax.xtickcolor) translate!(xticksmirrored_lines, 0, 0, 10) yticksmirrored = lift(mirror_ticks, blockscene, yaxis.tickpositions, ax.yticksize, ax.ytickalign, - scene.viewport, :y, ax.yaxisposition[], ax.spinewidth) + scene.viewport, :y, ax.yaxisposition[], ax.spinewidth) yticksmirrored_lines = linesegments!(blockscene, yticksmirrored, visible = @lift($(ax.yticksmirrored) && $(ax.yticksvisible)), linewidth = ax.ytickwidth, color = ax.ytickcolor) translate!(yticksmirrored_lines, 0, 0, 10) xminorticksmirrored = lift(mirror_ticks, blockscene, xaxis.minortickpositions, ax.xminorticksize, - ax.xminortickalign, scene.viewport, :x, ax.xaxisposition[], ax.spinewidth) + ax.xminortickalign, scene.viewport, :x, ax.xaxisposition[], ax.spinewidth) xminorticksmirrored_lines = linesegments!(blockscene, xminorticksmirrored, visible = @lift($(ax.xticksmirrored) && $(ax.xminorticksvisible)), linewidth = ax.xminortickwidth, color = ax.xminortickcolor) translate!(xminorticksmirrored_lines, 0, 0, 10) yminorticksmirrored = lift(mirror_ticks, blockscene, yaxis.minortickpositions, ax.yminorticksize, - ax.yminortickalign, scene.viewport, :y, ax.yaxisposition[], ax.spinewidth) + ax.yminortickalign, scene.viewport, :y, ax.yaxisposition[], ax.spinewidth) yminorticksmirrored_lines = linesegments!(blockscene, yminorticksmirrored, visible = @lift($(ax.yticksmirrored) && $(ax.yminorticksvisible)), linewidth = ax.yminortickwidth, color = ax.yminortickcolor) translate!(yminorticksmirrored_lines, 0, 0, 10) @@ -434,9 +434,9 @@ function initialize_block!(ax::Axis; palette = nothing) end subtitlepos = lift(blockscene, scene.viewport, ax.titlegap, ax.titlealign, ax.xaxisposition, - xaxis.protrusion; - ignore_equal_values=true) do a, - titlegap, align, xaxisposition, xaxisprotrusion + xaxis.protrusion; + ignore_equal_values = true) do a, + titlegap, align, xaxisposition, xaxisprotrusion align_factor = halign2num(align, "Horizontal title align $align not supported.") x = a.origin[1] + align_factor * a.widths[1] @@ -446,7 +446,7 @@ function initialize_block!(ax::Axis; palette = nothing) return Point2f(x, yoffset) end - titlealignnode = lift(blockscene, ax.titlealign; ignore_equal_values=true) do align + titlealignnode = lift(blockscene, ax.titlealign; ignore_equal_values = true) do align (align, :bottom) end @@ -463,7 +463,7 @@ function initialize_block!(ax::Axis; palette = nothing) inspectable = false) titlepos = lift(calculate_title_position, blockscene, scene.viewport, 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!( blockscene, titlepos, @@ -479,11 +479,11 @@ function initialize_block!(ax::Axis; palette = nothing) elements[:title] = titlet map!(compute_protrusions, blockscene, 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.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) # trigger first protrusions with one of the observables notify(ax.title) @@ -525,22 +525,22 @@ function mirror_ticks(tickpositions, ticksize, tickalign, viewport, side, axispo a = viewport 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)) spineoffset = sign * (0.5 * spinewidth) if side === :x for (i, (x, _)) in enumerate(tickpositions) - points[2i-1] = Point2f(x, opp - d * tickalign + spineoffset) + points[2i - 1] = Point2f(x, opp - d * tickalign + spineoffset) points[2i] = Point2f(x, opp + d - d * tickalign + spineoffset) end else for (i, (_, y)) in enumerate(tickpositions) - points[2i-1] = Point2f(opp - d * tickalign + spineoffset, y) + points[2i - 1] = Point2f(opp - d * tickalign + spineoffset, y) points[2i] = Point2f(opp + d - d * tickalign + spineoffset, y) end end @@ -560,9 +560,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 @@ -581,7 +581,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 @@ -597,7 +597,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 @@ -615,7 +615,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 @@ -644,11 +644,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 @@ -771,7 +771,7 @@ is_open_or_any_parent(::Nothing) = false 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 @@ -911,7 +911,7 @@ function autolimits!(ax::Axis) end function autolimits!() curr_ax = current_axis() - isnothing(curr_ax) && throw(ArgumentError("Attempted to call `autolimits!` on `current_axis()`, but `current_axis()` returned nothing.")) + isnothing(curr_ax) && throw(ArgumentError("Attempted to call `autolimits!` on `current_axis()`, but `current_axis()` returned nothing.")) autolimits!(curr_ax) end @@ -1010,7 +1010,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) @@ -1053,7 +1053,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[]) @@ -1083,7 +1083,7 @@ Hide decorations of the x-axis: label, ticklabels, ticks and grid. Keyword arguments can be used to disable hiding of certain types of decorations. """ 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 @@ -1112,7 +1112,7 @@ Hide decorations of the y-axis: label, ticklabels, ticks and grid. Keyword arguments can be used to disable hiding of certain types of decorations. """ 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 @@ -1143,7 +1143,7 @@ Keyword arguments can be used to disable hiding of certain types of decorations. See also [`hidexdecorations!`], [`hideydecorations!`], [`hidezdecorations!`] """ 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, @@ -1373,7 +1373,7 @@ function limits!(ax::Axis, rect::Rect2) Makie.ylims!(ax, ymin, ymax) end -function limits!(args::Union{Nothing, Real, HyperRectangle}...) +function limits!(args::Union{Nothing,Real,HyperRectangle}...) axis = current_axis() axis isa Nothing && error("There is no currently active axis!") limits!(axis, args...) @@ -1383,28 +1383,29 @@ 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(scale::ReversibleScale) = inverse_transform(scale).(scale.limits) -defaultlimits(scale::LogFunctions) = let inv_scale = inverse_transform(scale) - (inv_scale(0.0), inv_scale(3.0)) -end +defaultlimits(scale::LogFunctions) = + let inv_scale = inverse_transform(scale) + (inv_scale(0.0), inv_scale(3.0)) + end defaultlimits(::typeof(identity)) = (0.0, 10.0) defaultlimits(::typeof(sqrt)) = (0.0, 100.0) defaultlimits(::typeof(Makie.logit)) = (0.01, 0.99) @@ -1843,7 +1844,7 @@ end Gets the colorbuffer of the `Axis` in `JuliaNative` image format. If `include_decorations=false`, only the inside of the axis is fetched. """ -function colorbuffer(ax::Axis; include_decorations=true, update=true, colorbuffer_kws...) +function colorbuffer(ax::Axis; include_decorations = true, update = true, colorbuffer_kws...) if update update_state_before_display!(ax) end @@ -1854,6 +1855,6 @@ function colorbuffer(ax::Axis; include_decorations=true, update=true, colorbuffe viewport(ax.scene)[] end - img = colorbuffer(root(ax.scene); update=false, colorbuffer_kws...) + img = colorbuffer(root(ax.scene); update = false, colorbuffer_kws...) return get_sub_picture(img, JuliaNative, bb) end diff --git a/src/makielayout/blocks/axis3d.jl b/src/makielayout/blocks/axis3d.jl index ec72eb0dce7..b69b6f92c4a 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(scene, 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 @@ -39,7 +39,7 @@ function initialize_block!(ax::Axis3) end matrices = lift(calculate_matrices, scene, finallimits, scene.viewport, ax.elevation, ax.azimuth, - ax.perspectiveness, ax.aspect, ax.viewmode, ax.xreversed, ax.yreversed, ax.zreversed) + ax.perspectiveness, ax.aspect, ax.viewmode, ax.xreversed, ax.yreversed, ax.zreversed) on(scene, matrices) do (model, view, proj, eyepos) cam = camera(scene) @@ -125,7 +125,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(scene, ax.limits) do lims reset_limits!(ax) @@ -253,12 +253,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 @@ -292,7 +292,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.") @@ -300,10 +300,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) @@ -398,7 +398,7 @@ function add_gridlines_and_frames!(topscene, scene, ax, dim::Int, limits, tickno framepoints = lift(limits, scene.camera.projectionview, scene.viewport, min1, min2, xreversed, yreversed, zreversed - ) do lims, _, pxa, mi1, mi2, xrev, yrev, zrev + ) do lims, _, pxa, mi1, mi2, xrev, yrev, zrev o = pxa.origin rev1 = (xrev, yrev, zrev)[d1] @@ -458,8 +458,8 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno ticksize = attr(:ticksize) tick_segments = lift(topscene, limits, tickvalues, miv, min1, min2, - scene.camera.projectionview, scene.viewport, ticksize, xreversed, yreversed, zreversed) do lims, ticks, miv, min1, min2, - pview, pxa, tsize, xrev, yrev, zrev + scene.camera.projectionview, scene.viewport, ticksize, xreversed, yreversed, zreversed) do lims, ticks, miv, min1, min2, + pview, pxa, tsize, xrev, yrev, zrev rev1 = (xrev, yrev, zrev)[d1] rev2 = (xrev, yrev, zrev)[d2] @@ -493,7 +493,7 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno diff_pp = Makie.GeometryBasics.normalize(Point2f(pp2 - pp1)) return (pp1, pp1 .+ Float32(tsize) .* diff_pp) - end + end end # we are going to transform the 3d tick segments into 2d of the topscene # because otherwise they @@ -514,7 +514,7 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno labels_positions = Observable{Any}() map!(topscene, labels_positions, scene.viewport, 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 @@ -549,9 +549,9 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno label_align = Observable((:center, :top)) onany(topscene, - scene.viewport, scene.camera.projectionview, limits, miv, min1, min2, - attr(:labeloffset), attr(:labelrotation), attr(:labelalign), xreversed, yreversed, zreversed - ) do pxa, pv, lims, miv, min1, min2, labeloffset, lrotation, lalign, xrev, yrev, zrev + scene.viewport, scene.camera.projectionview, limits, miv, min1, min2, + attr(:labeloffset), attr(:labelrotation), attr(:labelalign), xreversed, yreversed, zreversed + ) do pxa, pv, lims, miv, min1, min2, labeloffset, lrotation, lalign, xrev, yrev, zrev o = pxa.origin @@ -585,18 +585,18 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno (min1 ⊻ min2 ⊻ revdim) ? 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) @@ -654,7 +654,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 @@ -787,11 +787,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 @@ -838,7 +838,7 @@ 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] && xlims[1] !== nothing @@ -856,7 +856,7 @@ 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] && ylims[1] !== nothing diff --git a/src/makielayout/blocks/box.jl b/src/makielayout/blocks/box.jl index 77dd49be62f..5ea59b25004 100644 --- a/src/makielayout/blocks/box.jl +++ b/src/makielayout/blocks/box.jl @@ -16,22 +16,22 @@ function initialize_block!(box::Box) ]) else w, h = widths(bbox) - _max = min(w/2, h/2) - r1, r2, r3, r4 = r isa NTuple{4, Real} ? r : r isa Real ? (r, r, r, r) : throw(ArgumentError("Invalid cornerradius value $r. Must be a `Real` or a tuple with 4 `Real`s.")) + _max = min(w / 2, h / 2) + r1, r2, r3, r4 = r isa NTuple{4,Real} ? r : r isa Real ? (r, r, r, r) : throw(ArgumentError("Invalid cornerradius value $r. Must be a `Real` or a tuple with 4 `Real`s.")) r1, r2, r3, r4 = min.(_max, (r1, r2, r3, r4)) BezierPath([ - MoveTo(bbox.origin + Point(w, h/2)), - EllipticalArc(topright(bbox) - Point2f(r1, r1), r1, r1, 0.0, 0, pi/2), - EllipticalArc(topleft(bbox) + Point2f(r4, -r4), r4, r4, 0.0, pi/2, pi), - EllipticalArc(bottomleft(bbox) + Point2f(r3, r3), r3, r3, 0.0, pi, 3/2 * pi), - EllipticalArc(bottomright(bbox) + Point2f(-r2, r2), r2, r2, 0.0, 3/2 * pi, 2pi), + MoveTo(bbox.origin + Point(w, h / 2)), + EllipticalArc(topright(bbox) - Point2f(r1, r1), r1, r1, 0.0, 0, pi / 2), + EllipticalArc(topleft(bbox) + Point2f(r4, -r4), r4, r4, 0.0, pi / 2, pi), + EllipticalArc(bottomleft(bbox) + Point2f(r3, r3), r3, r3, 0.0, pi, 3 / 2 * pi), + EllipticalArc(bottomright(bbox) + Point2f(-r2, r2), r2, r2, 0.0, 3 / 2 * pi, 2pi), ClosePath(), ]) end end - + poly!(blockscene, path, color = box.color, visible = box.visible, strokecolor = strokecolor_with_visibility, strokewidth = box.strokewidth, @@ -109,4 +109,4 @@ function attribute_examples(::Type{Box}) ) ], ) -end \ No newline at end of file +end diff --git a/src/makielayout/blocks/button.jl b/src/makielayout/blocks/button.jl index c52d71e7426..ad2a7ed450f 100644 --- a/src/makielayout/blocks/button.jl +++ b/src/makielayout/blocks/button.jl @@ -7,7 +7,7 @@ function initialize_block!(b::Button) subarea = lift(scene, 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(scene, b.layoutobservables.computedbbox) do bbox diff --git a/src/makielayout/blocks/colorbar.jl b/src/makielayout/blocks/colorbar.jl index 9032a15a888..96bcf003df9 100644 --- a/src/makielayout/blocks/colorbar.jl +++ b/src/makielayout/blocks/colorbar.jl @@ -46,14 +46,14 @@ function extract_colormap(@nospecialize(plot::AbstractPlot)) get(plot, :alpha, Observable(1.0)), get(plot, :highclip, Observable(automatic)), get(plot, :lowclip, Observable(automatic)), - get(plot, :nan_color, Observable(RGBAf(0,0,0,0))), + get(plot, :nan_color, Observable(RGBAf(0, 0, 0, 0))), ) else return nothing end end -function extract_colormap(plot::Union{Arrows, StreamPlot}) +function extract_colormap(plot::Union{Arrows,StreamPlot}) return extract_colormap(plot.plots[1]) end @@ -72,11 +72,11 @@ function extract_colormap(plot::Union{Contourf,Tricontourf}) elow = lift(extend_color, plot.extendlow, plot._computed_extendlow) ehigh = lift(extend_color, plot.extendhigh, plot._computed_extendhigh) return ColorMapping(levels[], levels, plot._computed_colormap, limits, plot.colorscale, Observable(1.0), - elow, ehigh, plot.nan_color) + elow, ehigh, plot.nan_color) end -function extract_colormap_recursive(@nospecialize(plot::T)) where {T <: AbstractPlot} +function extract_colormap_recursive(@nospecialize(plot::T)) where {T<:AbstractPlot} cmap = extract_colormap(plot) if !isnothing(cmap) return cmap @@ -88,7 +88,7 @@ function extract_colormap_recursive(@nospecialize(plot::T)) where {T <: Abstract return nothing else # Prefer ColorMapping if in doubt! - cmaps = filter(x-> x isa ColorMapping, colormaps) + cmaps = filter(x -> x isa ColorMapping, colormaps) length(cmaps) == 1 && return cmaps[1] error("Multiple colormaps found for plot $(plot), please specify which one to use manually. Please overload `Makie.extract_colormap(::$(T))` to allow for the automatical creation of a Colorbar.") end @@ -107,7 +107,7 @@ function Colorbar(fig_or_scene, plot::AbstractPlot; kwargs...) error("extract_colormap(::$(Plot{func})) returned an invalid value: $cmap. Needs to return either a `Makie.ColorMapping`.") end - if to_value(cmap.color) isa Union{AbstractVector{<: Colorant}, Colorant} + if to_value(cmap.color) isa Union{AbstractVector{<:Colorant},Colorant} error("""Plot $(func)'s color attribute uses colors directly, so it can't be used to create a Colorbar, since no numbers are mapped to a color via the colormap. Please create the colorbar manually e.g. via `Colorbar(f[1, 2], colorrange=the_range, colormap=the_colormap)`.. """) @@ -115,7 +115,7 @@ function Colorbar(fig_or_scene, plot::AbstractPlot; kwargs...) return Colorbar( fig_or_scene; - colormap=cmap, + colormap = cmap, kwargs... ) end @@ -162,12 +162,12 @@ function initialize_block!(cb::Colorbar) end limits = cmap.colorrange colors = lift(blockscene, cmap.mapping, cmap.color_mapping_type, cmap.color, cb.nsteps, limits; - ignore_equal_values=true) do mapping, mapping_type, values, n, limits + ignore_equal_values = true) do mapping, mapping_type, values, n, limits if mapping === nothing if mapping_type === Makie.banded error("Banded without a mapping is invalid. Please use colormap=cgrad(...; categorical=true)") elseif mapping_type === Makie.categorical - return convert(Vector{Float64},1:length(unique(values))) + return convert(Vector{Float64}, 1:length(unique(values))) else return convert(Vector{Float64}, LinRange(limits..., n)) end @@ -187,9 +187,9 @@ function initialize_block!(cb::Colorbar) end end - lowclip_tri_visible = lift(x -> !(x isa Automatic), blockscene, cmap.lowclip; ignore_equal_values=true) - highclip_tri_visible = lift(x -> !(x isa Automatic), blockscene, cmap.highclip; ignore_equal_values=true) - tri_heights = lift(blockscene, highclip_tri_visible, lowclip_tri_visible, framebox; ignore_equal_values=true) do hv, lv, box + lowclip_tri_visible = lift(x -> !(x isa Automatic), blockscene, cmap.lowclip; ignore_equal_values = true) + highclip_tri_visible = lift(x -> !(x isa Automatic), blockscene, cmap.highclip; ignore_equal_values = true) + tri_heights = lift(blockscene, highclip_tri_visible, lowclip_tri_visible, framebox; ignore_equal_values = true) do hv, lv, box if cb.vertical[] return (lv * width(box), hv * width(box)) else @@ -197,7 +197,7 @@ function initialize_block!(cb::Colorbar) end .* sin(pi / 3) end - barbox = lift(blockscene, framebox; ignore_equal_values=true) do fbox + barbox = lift(blockscene, framebox; ignore_equal_values = true) do fbox if cb.vertical[] return BBox(left(fbox), right(fbox), bottom(fbox) + tri_heights[][1], top(fbox) - tri_heights[][2]) else @@ -205,8 +205,8 @@ function initialize_block!(cb::Colorbar) end end - xrange = Observable(Float32[]; ignore_equal_values=true) - yrange = Observable(Float32[]; ignore_equal_values=true) + xrange = Observable(Float32[]; ignore_equal_values = true) + yrange = Observable(Float32[]; ignore_equal_values = true) function update_xyrange(bb, v, colors, scale, mapping_type) xmin, ymin = minimum(bb) @@ -233,18 +233,18 @@ function initialize_block!(cb::Colorbar) # for continous colormaps we sample a 1d image # to avoid white lines when rendering vector graphics continous_pixels = lift(blockscene, cb.vertical, colors, - cmap.color_mapping_type) do v, colors, mapping_type + cmap.color_mapping_type) do v, colors, mapping_type if mapping_type !== Makie.categorical - colors = (colors[1:end-1] .+ colors[2:end]) ./2 + colors = (colors[1:(end - 1)] .+ colors[2:end]) ./ 2 end n = length(colors) return v ? reshape((colors), 1, n) : reshape((colors), n, 1) end # TODO, implement interpolate = true for irregular grics in CairoMakie # Then, we can just use heatmap! and don't need the image plot! - show_cats = Observable(false; ignore_equal_values=true) - show_continous = Observable(false; ignore_equal_values=true) - on(blockscene, cmap.color_mapping_type; update=true) do type + show_cats = Observable(false; ignore_equal_values = true) + show_continous = Observable(false; ignore_equal_values = true) + on(blockscene, cmap.color_mapping_type; update = true) do type if type === continuous show_continous[] = true show_cats[] = false @@ -255,9 +255,9 @@ function initialize_block!(cb::Colorbar) end heatmap!(blockscene, xrange, yrange, continous_pixels; - colormap=colormap, - visible=show_cats, - inspectable=false + colormap = colormap, + visible = show_cats, + inspectable = false ) image!(blockscene, lift(extrema, xrange), lift(extrema, yrange), continous_pixels; @@ -271,11 +271,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 @@ -293,11 +293,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 @@ -339,7 +339,7 @@ function initialize_block!(cb::Colorbar) lines!(blockscene, borderpoints, linewidth = cb.spinewidth, color = cb.topspinecolor, inspectable = false) axispoints = lift(blockscene, barbox, cb.vertical, cb.flipaxis) do scenearea, - vertical, flipaxis + vertical, flipaxis if vertical if flipaxis @@ -368,11 +368,11 @@ function initialize_block!(cb::Colorbar) end axis = LineAxis(blockscene, endpoints = axispoints, flipped = cb.flipaxis, - limits=lims, ticklabelalign=cb.ticklabelalign, label=cb.label, + limits = lims, ticklabelalign = cb.ticklabelalign, label = cb.label, labelpadding = cb.labelpadding, labelvisible = cb.labelvisible, labelsize = cb.labelsize, labelcolor = cb.labelcolor, labelrotation = cb.labelrotation, - labelfont=cb.labelfont, ticklabelfont=cb.ticklabelfont, ticks=ticks, - tickformat=cb.tickformat, + labelfont = cb.labelfont, ticklabelfont = cb.ticklabelfont, ticks = ticks, + tickformat = cb.tickformat, ticklabelsize = cb.ticklabelsize, ticklabelsvisible = cb.ticklabelsvisible, ticksize = cb.ticksize, ticksvisible = cb.ticksvisible, ticklabelpad = cb.ticklabelpad, tickalign = cb.tickalign, ticklabelrotation = cb.ticklabelrotation, @@ -386,7 +386,7 @@ function initialize_block!(cb::Colorbar) cb.axis = axis onany(blockscene, axis.protrusion, cb.vertical, cb.flipaxis) do axprotrusion, - vertical, flipaxis + vertical, flipaxis left, right, top, bottom = 0f0, 0f0, 0f0, 0f0 @@ -435,7 +435,7 @@ function scaled_steps(steps, scale, lims) # scale with scaling function steps_scaled = scale.(steps) # normalize to lims range - steps_lim_scaled = @. steps_scaled * (scale(lims[2]) - scale(lims[1])) + scale(lims[1]) + steps_lim_scaled = @. steps_scaled * (scale(lims[2]) - scale(lims[1])) + scale(lims[1]) # then rescale to 0 to 1 return @. (steps_lim_scaled - steps_lim_scaled[begin]) / (steps_lim_scaled[end] - steps_lim_scaled[begin]) end diff --git a/src/makielayout/blocks/intervalslider.jl b/src/makielayout/blocks/intervalslider.jl index 01c456ca210..917bd37ce8f 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 adc7de7fbc7..377f5690a1d 100644 --- a/src/makielayout/blocks/label.jl +++ b/src/makielayout/blocks/label.jl @@ -17,7 +17,7 @@ function initialize_block!(l::Label) textbb = Ref(BBox(0, 1, 0, 1)) onany(topscene, l.text, l.fontsize, l.font, l.rotation, word_wrap_width, - l.padding) do _, _, _, _, _, padding + l.padding) do _, _, _, _, _, padding textbb[] = Rect2f(boundingbox(t)) autowidth = width(textbb[]) + padding[1] + padding[2] autoheight = height(textbb[]) + padding[3] + padding[4] diff --git a/src/makielayout/blocks/legend.jl b/src/makielayout/blocks/legend.jl index 28897c6dd98..7d42b1f84ad 100644 --- a/src/makielayout/blocks/legend.jl +++ b/src/makielayout/blocks/legend.jl @@ -89,7 +89,7 @@ function initialize_block!(leg::Legend; entrygroups) 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) @@ -99,17 +99,17 @@ function initialize_block!(leg::Legend; entrygroups) 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 @@ -124,7 +124,7 @@ function initialize_block!(leg::Legend; entrygroups) 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[]) @@ -156,8 +156,8 @@ function initialize_block!(leg::Legend; entrygroups) end onany(blockscene, 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.titlegap, + leg.titlevisible, leg.orientation, leg.gridshalign, leg.gridsvalign) do args... relayout() return end @@ -214,12 +214,12 @@ function initialize_block!(leg::Legend; entrygroups) 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], blockscene, e.patchsize), height=lift(x -> x[2], blockscene, e.patchsize)) + rect = Box(scene; color = e.patchcolor, strokecolor = e.patchstrokecolor, strokewidth = e.patchstrokewidth, + width = lift(x -> x[1], blockscene, e.patchsize), height = lift(x -> x[2], blockscene, e.patchsize)) push!(erects, rect) translate!(rect.blockscene, 0, 0, -5) # patches before background but behind legend elements (legend is at +10) @@ -227,7 +227,7 @@ function initialize_block!(leg::Legend; entrygroups) 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) @@ -353,15 +353,15 @@ function LegendEntry(label, contentelement, legend; kwargs...) 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 @@ -415,7 +415,7 @@ function extract_color(@nospecialize(plot), color_default) return choose_scalar(color, color_default) end -function legendelements(plot::Union{Lines, LineSegments}, legend) +function legendelements(plot::Union{Lines,LineSegments}, legend) LegendElement[LineElement( color = extract_color(plot, legend[:linecolor]), linestyle = choose_scalar(plot.linestyle, legend[:linestyle]), @@ -437,7 +437,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) color = extract_color(plot, legend[:polycolor]) LegendElement[PolyElement( color = color, @@ -474,7 +474,7 @@ function legendelements(plot::Text, legend)::Vector{LegendElement} [] 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 @@ -482,7 +482,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 @@ -490,11 +490,11 @@ 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 -function to_entry_group(legend_defaults, contents::AbstractVector, labels::AbstractVector, title=nothing) +function to_entry_group(legend_defaults, contents::AbstractVector, labels::AbstractVector, title = nothing) if length(contents) != length(labels) error("Number of elements not equal: $(length(contents)) content elements and $(length(labels)) labels.") end @@ -503,13 +503,13 @@ function to_entry_group(legend_defaults, contents::AbstractVector, labels::Abstr end function to_entry_group( - legend_defaults, contentgroups::AbstractVector{<:AbstractVector}, - labelgroups::AbstractVector{<:AbstractVector}, titles::AbstractVector) + legend_defaults, contentgroups::AbstractVector{<:AbstractVector}, + labelgroups::AbstractVector{<:AbstractVector}, titles::AbstractVector) 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.") end entries = [[LegendEntry(l, pg, legend_defaults) for (l, pg) in zip(labelgroup, contentgroup)] - for (labelgroup, contentgroup) in zip(labelgroups, contentgroups)] + for (labelgroup, contentgroup) in zip(labelgroups, contentgroups)] return [(t, en) for (t, en) in zip(titles, entries)] end @@ -527,18 +527,18 @@ one content element. A content element can be an `AbstractPlot`, an array of `legendelements` method is defined. """ function Legend(fig_or_scene, - contents::AbstractVector, - labels::AbstractVector, - title = nothing; - bbox=nothing, kwargs...) + contents::AbstractVector, + labels::AbstractVector, + title = nothing; + bbox = nothing, kwargs...) scene = get_topscene(fig_or_scene) - legend_defaults = block_defaults(:Legend, Dict{Symbol, Any}(kwargs), scene) + legend_defaults = block_defaults(:Legend, Dict{Symbol,Any}(kwargs), scene) entry_groups = to_entry_group(Attributes(legend_defaults), contents, labels, title) entrygroups = Observable(entry_groups) legend_defaults[:entrygroups] = entrygroups # Use low-level constructor to not calculate legend_defaults a second time - return _block(Legend, fig_or_scene, (), legend_defaults, bbox; kwdict_complete=true) + return _block(Legend, fig_or_scene, (), legend_defaults, bbox; kwdict_complete = true) end @@ -560,17 +560,17 @@ 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::AbstractVector{<:AbstractVector}, - labelgroups::AbstractVector{<:AbstractVector}, - titles::AbstractVector; - bbox=nothing, kwargs...) + contentgroups::AbstractVector{<:AbstractVector}, + labelgroups::AbstractVector{<:AbstractVector}, + titles::AbstractVector; + bbox = nothing, kwargs...) scene = get_scene(fig_or_scene) legend_defaults = block_defaults(:Legend, Dict{Symbol,Any}(kwargs), scene) entry_groups = to_entry_group(legend_defaults, contentgroups, labelgroups, titles) entrygroups = Observable(entry_groups) legend_defaults[:entrygroups] = entrygroups - return _block(Legend, fig_or_scene, (), legend_defaults, bbox; kwdict_complete=true) + return _block(Legend, fig_or_scene, (), legend_defaults, bbox; kwdict_complete = true) end @@ -583,7 +583,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...) @@ -607,7 +607,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 @@ -616,7 +616,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[] @@ -681,7 +681,7 @@ 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 a88471351ff..e4f1c7b13df 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!(blockscene, _direction, m.layoutobservables.computedbbox, m.direction) do bb, dir if dir == Makie.automatic @@ -74,17 +74,17 @@ function initialize_block!(m::Menu; default = 1) end scenearea = lift(blockscene, m.layoutobservables.computedbbox, listheight, _direction, m.is_open; - ignore_equal_values=true) do bbox, h, d, 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.viewport[])))) + 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.viewport[])))) end - menuscene = Scene(blockscene, scenearea, camera = campixel!, clear=true) + menuscene = Scene(blockscene, scenearea, camera = campixel!, clear = true) translate!(menuscene, 0, 0, 200) onany(blockscene, scenearea, listheight) do area, listheight @@ -94,9 +94,9 @@ function initialize_block!(m::Menu; default = 1) translate!(menuscene, t[1], new_y, t[3]) end - optionstrings = lift(o -> optionlabel.(o), blockscene, m.options; ignore_equal_values=true) + optionstrings = lift(o -> optionlabel.(o), blockscene, m.options; ignore_equal_values = true) - selected_text = lift(blockscene, m.prompt, m.i_selected; ignore_equal_values=true) do prompt, i_selected + selected_text = lift(blockscene, m.prompt, m.i_selected; ignore_equal_values = true) do prompt, i_selected if i_selected == 0 prompt else @@ -104,14 +104,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 @@ -126,13 +126,13 @@ function initialize_block!(m::Menu; default = 1) on(blockscene, 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[]) @@ -167,7 +167,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) @@ -175,7 +175,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) @@ -190,8 +190,8 @@ function initialize_block!(m::Menu; default = 1) # translation due to scrolling has to be removed first ytrans = y - translation(menuscene)[][2] return 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 @@ -221,7 +221,7 @@ function initialize_block!(m::Menu; default = 1) return false end - onany(blockscene, e.mouseposition, e.mousebutton; priority=64) do position, butt + onany(blockscene, 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 @@ -290,7 +290,7 @@ function initialize_block!(m::Menu; default = 1) return Consume(false) end - on(blockscene, menuscene.events.scroll; priority=61) do (x, y) + on(blockscene, menuscene.events.scroll; priority = 61) do (x, y) if is_mouseinside(menuscene) t = translation(menuscene)[] # Hack to differentiate mousewheel and trackpad scrolling @@ -330,7 +330,7 @@ function initialize_block!(m::Menu; default = 1) end dropdown_arrow = scatter!( blockscene, symbol_pos; - marker=lift(iso -> iso ? :utriangle : :dtriangle, blockscene, m.is_open), + marker = lift(iso -> iso ? :utriangle : :dtriangle, blockscene, m.is_open), markersize = m.dropdown_arrow_size, color = m.dropdown_arrow_color, strokecolor = :transparent, @@ -366,7 +366,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) @@ -380,7 +380,7 @@ function optionlabel(option) string(option) end -function optionlabel(option::Tuple{Any, Any}) +function optionlabel(option::Tuple{Any,Any}) string(option[1]) end @@ -388,6 +388,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/polaraxis.jl b/src/makielayout/blocks/polaraxis.jl index 2250fad0d09..2bb78ce1c81 100644 --- a/src/makielayout/blocks/polaraxis.jl +++ b/src/makielayout/blocks/polaraxis.jl @@ -2,7 +2,7 @@ ### Main Block Intialization ################################################################################ -function initialize_block!(po::PolarAxis; palette=nothing) +function initialize_block!(po::PolarAxis; palette = nothing) # Setup Scenes cb = po.layoutobservables.computedbbox scenearea = map(po.blockscene, cb) do cb @@ -44,28 +44,28 @@ function initialize_block!(po::PolarAxis; palette=nothing) # TODO: Should we include rticks here? # OPT: only update on relevant text attributes rather than glyphcollection onany( - po.blockscene, - rticklabelplot.plots[1].text, - rticklabelplot.plots[1].fontsize, - rticklabelplot.plots[1].font, - po.rticklabelpad, - thetaticklabelplot.plots[1].text, - thetaticklabelplot.plots[1].fontsize, - thetaticklabelplot.plots[1].font, - po.thetaticklabelpad, - po.overlay.viewport - ) do _, _, _, rpad, _, _, _, tpad, area + po.blockscene, + rticklabelplot.plots[1].text, + rticklabelplot.plots[1].fontsize, + rticklabelplot.plots[1].font, + po.rticklabelpad, + thetaticklabelplot.plots[1].text, + thetaticklabelplot.plots[1].fontsize, + thetaticklabelplot.plots[1].font, + po.thetaticklabelpad, + po.overlay.viewport + ) do _, _, _, rpad, _, _, _, tpad, area # get maximum size of tick label # (each boundingbox represents a string without text.position applied) max_widths = Vec2f(0) for gc in thetaticklabelplot.plots[1].plots[1][1][] bbox = boundingbox(gc, Quaternionf(0, 0, 0, 1)) # no rotation - max_widths = max.(max_widths, widths(bbox)[Vec(1,2)]) + max_widths = max.(max_widths, widths(bbox)[Vec(1, 2)]) end for gc in rticklabelplot.plots[1].plots[1][1][] bbox = boundingbox(gc, Quaternionf(0, 0, 0, 1)) # no rotation - max_widths = max.(max_widths, widths(bbox)[Vec(1,2)]) + max_widths = max.(max_widths, widths(bbox)[Vec(1, 2)]) end max_width, max_height = max_widths @@ -80,13 +80,13 @@ function initialize_block!(po::PolarAxis; palette=nothing) # Set up the title position title_position = map( - po.blockscene, - po.target_rlims, po.target_thetalims, po.target_theta_0, po.direction, - po.rticklabelsize, po.rticklabelpad, - po.thetaticklabelsize, po.thetaticklabelpad, - po.overlay.viewport, po.overlay.camera.projectionview, - po.titlegap, po.titlesize, po.titlealign - ) do rlims, thetalims, theta_0, dir, r_fs, r_pad, t_fs, t_pad, area, pv, gap, size, align + po.blockscene, + po.target_rlims, po.target_thetalims, po.target_theta_0, po.direction, + po.rticklabelsize, po.rticklabelpad, + po.thetaticklabelsize, po.thetaticklabelpad, + po.overlay.viewport, po.overlay.camera.projectionview, + po.titlegap, po.titlesize, po.titlealign + ) do rlims, thetalims, theta_0, dir, r_fs, r_pad, t_fs, t_pad, area, pv, gap, size, align # derive y position # transform to pixel space @@ -100,7 +100,8 @@ function initialize_block!(po::PolarAxis; palette=nothing) # theta fontsize & pad relevant ypx = (m * 1.0 + b) + (2t_pad + t_fs + gap) else - y1 = sin(thetamin); y2 = sin(thetamax) + y1 = sin(thetamin) + y2 = sin(thetamax) rscale = rlims[1] / rlims[2] y = max(rscale * y1, rscale * y2, y1, y2) ypx = (m * y + b) + (2max(t_pad, r_pad) + max(t_fs, r_fs) + gap) @@ -139,8 +140,8 @@ function initialize_block!(po::PolarAxis; palette=nothing) # Since we handle ticks within out `scenearea` this only needs to reserve # space for the title protrusions = map( - po.blockscene, po.title, po.titlegap, po.titlesize - ) do title, gap, size + po.blockscene, po.title, po.titlegap, po.titlesize + ) do title, gap, size titlespace = po.title[] == "" ? 0f0 : Float32(2gap + size) return GridLayoutBase.RectSides(0f0, 0f0, 0f0, titlespace) end @@ -166,7 +167,7 @@ function polaraxis_bbox(rlims, thetalims, r0, dir, theta_0) thetamin, thetamax = thetalims rmin, rmax = max.(0.0, rlims .- r0) - if abs(thetamax - thetamin) > 3pi/2 + if abs(thetamax - thetamin) > 3pi / 2 return Rect2f(-rmax, -rmax, 2rmax, 2rmax) end @@ -191,14 +192,14 @@ function polaraxis_bbox(rlims, thetalims, r0, dir, theta_0) bb = _update_rect(bb, polar2cartesian(rmax, thetamax)) # only outer circle can update bb - if thetamin < -3pi/2 < thetamax || thetamin < pi/2 < thetamax - bb = _update_rect(bb, polar2cartesian(rmax, pi/2)) + if thetamin < -3pi / 2 < thetamax || thetamin < pi / 2 < thetamax + bb = _update_rect(bb, polar2cartesian(rmax, pi / 2)) end if thetamin < -pi < thetamax || thetamin < pi < thetamax bb = _update_rect(bb, polar2cartesian(rmax, pi)) end - if thetamin < -pi/2 < thetamax || thetamin < 3pi/2 < thetamax - bb = _update_rect(bb, polar2cartesian(rmax, 3pi/2)) + if thetamin < -pi / 2 < thetamax || thetamin < 3pi / 2 < thetamax + bb = _update_rect(bb, polar2cartesian(rmax, 3pi / 2)) end if thetamin < 0 < thetamax bb = _update_rect(bb, polar2cartesian(rmax, 0)) @@ -210,8 +211,8 @@ end function setup_camera_matrices!(po::PolarAxis) # Initialization usable_fraction = Observable(Vec2f(1.0, 1.0)) - setfield!(po, :target_rlims, Observable{Tuple{Float64, Float64}}((0.0, 10.0))) - setfield!(po, :target_thetalims, Observable{Tuple{Float64, Float64}}((0.0, 2pi))) + setfield!(po, :target_rlims, Observable{Tuple{Float64,Float64}}((0.0, 10.0))) + setfield!(po, :target_thetalims, Observable{Tuple{Float64,Float64}}((0.0, 2pi))) setfield!(po, :target_theta_0, map(identity, po.theta_0)) setfield!(po, :target_r0, Observable{Float32}(po.radius_at_origin[] isa Real ? po.radius_at_origin[] : 0f0)) reset_limits!(po) @@ -227,7 +228,8 @@ function setup_camera_matrices!(po::PolarAxis) # fit data_bbox into the usable area of PolarAxis (i.e. with tick space subtracted) onany(po.blockscene, usable_fraction, data_bbox) do usable_fraction, bb - mini = minimum(bb); ws = widths(bb) + mini = minimum(bb) + ws = widths(bb) scale = minimum(2usable_fraction ./ ws) trans = to_ndim(Vec3f, -scale .* (mini .+ 0.5ws), 0) camera(po.scene).view[] = transformationmatrix(trans, Vec3f(scale, scale, 1)) @@ -237,7 +239,8 @@ function setup_camera_matrices!(po::PolarAxis) # same as above, but with rmax scaled to 1 # OPT: data_bbox triggers on target_r0, target_rlims updates onany(po.blockscene, usable_fraction, data_bbox) do usable_fraction, bb - mini = minimum(bb); ws = widths(bb) + mini = minimum(bb) + ws = widths(bb) rmax = po.target_rlims[][2] - po.target_r0[] scale = minimum(2usable_fraction ./ ws) trans = to_ndim(Vec3f, -scale .* (mini .+ 0.5ws), 0) @@ -271,9 +274,9 @@ function setup_camera_matrices!(po::PolarAxis) if is_mouseinside(po.scene) && (!po.rzoomlock[] || !po.thetazoomlock[]) mp = mouseposition(po.scene) r = norm(mp) - zoom_scale = (1.0 - po.zoomspeed[]) ^ scroll[2] + zoom_scale = (1.0 - po.zoomspeed[])^scroll[2] rmin, rmax = po.target_rlims[] - thetamin, thetamax = po.target_thetalims[] + thetamin, thetamax = po.target_thetalims[] # keep circumference to radial length ratio constant by default dtheta = thetamax - thetamin @@ -305,12 +308,12 @@ function setup_camera_matrices!(po::PolarAxis) # angle of mouse position normalized to range theta = po.direction[] * atan(mp[2], mp[1]) - po.target_theta_0[] thetacenter = 0.5 * (thetamin + thetamax) - theta = mod(theta, thetacenter-pi .. thetacenter+pi) + theta = mod(theta, thetacenter - pi .. thetacenter + pi) w = (theta - thetamin) / (thetamax - thetamin) dtheta = (thetamax - thetamin) - clamp(aspect * (rmax - rmin) / r, 0, 2pi) thetamin = thetamin + w * dtheta - thetamax = thetamax - (1-w) * dtheta + thetamax = thetamax - (1 - w) * dtheta if !ispressed(e, po.rzoomkey[]) && !po.thetazoomlock[] if po.normalize_theta_ticks[] @@ -324,7 +327,7 @@ function setup_camera_matrices!(po::PolarAxis) end end - # don't open a gap when zooming a full circle near the center + # don't open a gap when zooming a full circle near the center elseif r > 0.1rmax && zoom_scale < 1 # open angle on the opposite site of theta @@ -383,10 +386,10 @@ function setup_camera_matrices!(po::PolarAxis) if norm(p0) * norm(p1) < 1e-6 Δθ = 0.0 else - Δθ = mod(po.direction[] * (atan(p1[2], p1[1]) - atan(p0[2], p0[1])), -pi..pi) + Δθ = mod(po.direction[] * (atan(p1[2], p1[1]) - atan(p0[2], p0[1])), -pi .. pi) end - po.target_theta_0[] = mod(po.target_theta_0[] + Δθ, 0..2pi) + po.target_theta_0[] = mod(po.target_theta_0[] + Δθ, 0 .. 2pi) last_px_pos[] = Point2f(mouseposition_px(po.scene)) last_pos[] = Point2f(mouseposition(po.scene)) @@ -415,7 +418,7 @@ function setup_camera_matrices!(po::PolarAxis) thetamin, thetamax = po.target_thetalims[] if thetamax - thetamin > 2pi - 1e-5 # full circle -> rotate view - po.target_theta_0[] = mod(po.target_theta_0[] + Δθ, 0..2pi) + po.target_theta_0[] = mod(po.target_theta_0[] + Δθ, 0 .. 2pi) else # partial circle -> rotate and adjust limits thetamin, thetamax = (thetamin, thetamax) .- Δθ @@ -424,7 +427,7 @@ function setup_camera_matrices!(po::PolarAxis) else po.target_thetalims[] = (thetamin, thetamax) end - po.target_theta_0[] = mod(po.target_theta_0[] + Δθ, 0..2pi) + po.target_theta_0[] = mod(po.target_theta_0[] + Δθ, 0 .. 2pi) end end @@ -439,7 +442,7 @@ function setup_camera_matrices!(po::PolarAxis) # Reset button onany(po.blockscene, e.mousebutton, e.keyboardbutton) do e1, e2 if ispressed(e, po.reset_button[]) && is_mouseinside(po.scene) && - (e1.action == Mouse.press) && (e2.action == Keyboard.press) + (e1.action == Mouse.press) && (e2.action == Keyboard.press) old_thetalims = po.target_thetalims[] if ispressed(e, Keyboard.left_shift) autolimits!(po) @@ -450,7 +453,7 @@ function setup_camera_matrices!(po::PolarAxis) notify(po.theta_0) else diff = 0.5 * sum(po.target_thetalims[] .- old_thetalims) - po.target_theta_0[] = mod(po.target_theta_0[] - diff, 0..2pi) + po.target_theta_0[] = mod(po.target_theta_0[] - diff, 0 .. 2pi) end return Consume(true) end @@ -518,11 +521,14 @@ function reset_limits!(po::PolarAxis) else # no plot limits, use defaults - rmin = 0.0; rmax = 10.0; thetamin = 0.0; thetamax = 2pi + rmin = 0.0 + rmax = 10.0 + thetamin = 0.0 + thetamax = 2pi end # apply - po.target_rlims[] = ifelse.(isnothing.(rlimits), (rmin, rmax), rlimits) + po.target_rlims[] = ifelse.(isnothing.(rlimits), (rmin, rmax), rlimits) po.target_thetalims[] = ifelse.(isnothing.(po.thetalimits[]), (thetamin, thetamax), po.thetalimits[]) else # all limits set if po.target_rlims[] != rlimits @@ -544,9 +550,9 @@ end # generates large square with circle sector cutout function _polar_clip_polygon( - thetamin, thetamax, steps = 120, outer = 1e4, - exterior = Point2f[(-outer, -outer), (-outer, outer), (outer, outer), (outer, -outer), (-outer, -outer)] - ) + thetamin, thetamax, steps = 120, outer = 1e4, + exterior = Point2f[(-outer, -outer), (-outer, outer), (outer, outer), (outer, -outer), (-outer, -outer)] +) # make sure we have 2+ points per arc interior = map(theta -> polar2cartesian(1.0, theta), LinRange(thetamin, thetamax, steps)) (abs(thetamax - thetamin) ≈ 2pi) || push!(interior, Point2f(0)) @@ -554,7 +560,7 @@ function _polar_clip_polygon( end function draw_axis!(po::PolarAxis) - rtick_pos_lbl = Observable{Vector{<:Tuple{Any, Point2f}}}() + rtick_pos_lbl = Observable{Vector{<:Tuple{Any,Point2f}}}() rtick_align = Observable{Point2f}() rtick_offset = Observable{Point2f}() rtick_rotation = Observable{Float32}() @@ -574,11 +580,11 @@ function draw_axis!(po::PolarAxis) end onany( - po.blockscene, - po.rticks, po.rminorticks, po.rtickformat, po.rtickangle, - po.direction, po.target_rlims, po.target_thetalims, po.sample_density, po.target_r0 - ) do rticks, rminorticks, rtickformat, rtickangle, - dir, rlims, thetalims, sample_density, target_r0 + po.blockscene, + po.rticks, po.rminorticks, po.rtickformat, po.rtickangle, + po.direction, po.target_rlims, po.target_thetalims, po.sample_density, po.target_r0 + ) do rticks, rminorticks, rtickformat, rtickangle, + dir, rlims, thetalims, sample_density, target_r0 # For text: rmaxinv = 1.0 / (rlims[2] - target_r0) @@ -600,12 +606,12 @@ function draw_axis!(po::PolarAxis) # doesn't have a lot of overlap with the inputs above so calculate this independently onany( - po.blockscene, - po.direction, po.target_theta_0, po.rtickangle, po.target_thetalims, po.rticklabelpad, - po.rticklabelrotation - ) do dir, theta_0, rtickangle, thetalims, pad, rot - angle = mod(dir * (default_rtickangle(rtickangle, dir, thetalims) + theta_0), 0..2pi) - s, c = sincos(angle - pi/2) + po.blockscene, + po.direction, po.target_theta_0, po.rtickangle, po.target_thetalims, po.rticklabelpad, + po.rticklabelrotation + ) do dir, theta_0, rtickangle, thetalims, pad, rot + angle = mod(dir * (default_rtickangle(rtickangle, dir, thetalims) + theta_0), 0 .. 2pi) + s, c = sincos(angle - pi / 2) rtick_offset[] = Point2f(pad * c, pad * s) if rot === automatic rot = (thetalims[2] - thetalims[1]) > 1.9pi ? (:horizontal) : (:aligned) @@ -615,12 +621,12 @@ function draw_axis!(po::PolarAxis) scale = 1 / max(abs(s), abs(c)) # point on ellipse -> point on bbox rtick_align[] = Point2f(0.5 - 0.5scale * c, 0.5 - 0.5scale * s) elseif rot === :radial - rtick_rotation[] = angle - pi/2 + rtick_rotation[] = angle - pi / 2 rtick_align[] = Point2f(0, 0.5) elseif rot === :aligned - N = trunc(Int, div(angle + pi/4, pi/2)) % 4 - rtick_rotation[] = angle - N * pi/2 # mod(angle, -pi/4 .. pi/4) - rtick_align[] = Point2f((0.5, 0.0, 0.5, 1.0)[N+1], (1.0, 0.5, 0.0, 0.5)[N+1]) + N = trunc(Int, div(angle + pi / 4, pi / 2)) % 4 + rtick_rotation[] = angle - N * pi / 2 # mod(angle, -pi/4 .. pi/4) + rtick_align[] = Point2f((0.5, 0.0, 0.5, 1.0)[N + 1], (1.0, 0.5, 0.0, 0.5)[N + 1]) elseif rot isa Real rtick_rotation[] = rot scale = 1 / max(abs(s), abs(c)) @@ -630,17 +636,17 @@ function draw_axis!(po::PolarAxis) end - thetatick_pos_lbl = Observable{Vector{<:Tuple{Any, Point2f}}}() + thetatick_pos_lbl = Observable{Vector{<:Tuple{Any,Point2f}}}() thetatick_align = Observable(Point2f[]) thetatick_offset = Observable(Point2f[]) thetagridpoints = Observable{Vector{Point2f}}() thetaminorgridpoints = Observable{Vector{Point2f}}() onany( - po.blockscene, - po.thetaticks, po.thetaminorticks, po.thetatickformat, po.thetaticklabelpad, - po.direction, po.target_theta_0, po.target_rlims, po.target_thetalims, po.target_r0 - ) do thetaticks, thetaminorticks, thetatickformat, px_pad, dir, theta_0, rlims, thetalims, r0 + po.blockscene, + po.thetaticks, po.thetaminorticks, po.thetatickformat, po.thetaticklabelpad, + po.direction, po.target_theta_0, po.target_rlims, po.target_thetalims, po.target_r0 + ) do thetaticks, thetaminorticks, thetatickformat, px_pad, dir, theta_0, rlims, thetalims, r0 _thetatickvalues, _thetaticklabels = get_ticks(thetaticks, identity, thetatickformat, thetalims...) @@ -806,7 +812,7 @@ function draw_axis!(po::PolarAxis) onany(po.blockscene, po.target_thetalims, po.direction, po.target_theta_0) do thetalims, dir, theta_0 thetamin, thetamax = dir .* (thetalims .+ theta_0) angle = dir > 0 ? thetamin : thetamax - rotate!.((outer_clip_plot, inner_clip_plot), (Vec3f(0,0,1),), angle) + rotate!.((outer_clip_plot, inner_clip_plot), (Vec3f(0, 0, 1),), angle) end onany(po.blockscene, po.target_rlims, po.target_r0) do lims, r0 @@ -818,8 +824,8 @@ function draw_axis!(po::PolarAxis) # spine traces circle sector - inner circle spine_points = map(po.blockscene, - po.target_rlims, po.target_thetalims, po.target_r0, po.sample_density - ) do (rmin, rmax), thetalims, r0, N + po.target_rlims, po.target_thetalims, po.target_r0, po.sample_density + ) do (rmin, rmax), thetalims, r0, N thetamin, thetamax = thetalims rmin = (rmin - r0) / (rmax - r0) rmax = 1.0 @@ -832,7 +838,7 @@ function draw_axis!(po::PolarAxis) append!(ps, Point2f.(rmin, LinRange(thetamin, thetamax, N))) end else - ps = sizehint!(Point2f[], 2N+1) + ps = sizehint!(Point2f[], 2N + 1) for angle in LinRange(thetamin, thetamax, N) push!(ps, Point2f(rmin, angle)) end @@ -881,7 +887,7 @@ function normalize_thetalims(thetamin, thetamax) diff = thetamax - thetamin if diff < 2pi # displayed limits may go from -diff .. 0 to 0 .. diff - thetamin_norm = mod(thetamin, -diff..(2pi-diff)) + thetamin_norm = mod(thetamin, -diff .. (2pi - diff)) thetamax_norm = thetamin_norm + clamp(diff, 0, 2pi) return thetamin_norm, thetamax_norm else @@ -920,9 +926,9 @@ end Sets the radial limits of a given `PolarAxis`. """ -rlims!(po::PolarAxis, r::Union{Symbol, Nothing, Real}) = rlims!(po, po.rlimits[][1], r) +rlims!(po::PolarAxis, r::Union{Symbol,Nothing,Real}) = rlims!(po, po.rlimits[][1], r) -function rlims!(po::PolarAxis, rmin::Union{Symbol, Nothing, Real}, rmax::Union{Nothing, Real}) +function rlims!(po::PolarAxis, rmin::Union{Symbol,Nothing,Real}, rmax::Union{Nothing,Real}) po.rlimits[] = (rmin, rmax) return end @@ -932,7 +938,7 @@ end Sets the angular limits of a given `PolarAxis`. """ -function thetalims!(po::PolarAxis, thetamin::Union{Nothing, Real}, thetamax::Union{Nothing, Real}) +function thetalims!(po::PolarAxis, thetamin::Union{Nothing,Real}, thetamax::Union{Nothing,Real}) po.thetalimits[] = (thetamin, thetamax) return end diff --git a/src/makielayout/blocks/scene.jl b/src/makielayout/blocks/scene.jl index e5cac177b0f..5dfa94d4a20 100644 --- a/src/makielayout/blocks/scene.jl +++ b/src/makielayout/blocks/scene.jl @@ -8,7 +8,7 @@ tightlimits!(::LScene) = nothing # TODO implement!? 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, blockscene, ls.layoutobservables.computedbbox); scenekw...) on(blockscene, ls.show_axis) do show_axis @@ -31,7 +31,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 28ebc809db4..931667235fd 100644 --- a/src/makielayout/blocks/slider.jl +++ b/src/makielayout/blocks/slider.jl @@ -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(*, topscene, 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 f679c7a9222..5d0e88f37d2 100644 --- a/src/makielayout/blocks/textbox.jl +++ b/src/makielayout/blocks/textbox.jl @@ -57,7 +57,7 @@ function initialize_block!(tbox::Textbox) realtextcolor = Observable{RGBAf}() map!(topscene, realtextcolor, tbox.textcolor, tbox.textcolor_placeholder, tbox.focused, - tbox.stored_string, tbox.displayed_string) do tc, tcph, foc, cont, disp + tbox.stored_string, tbox.displayed_string) do tc, tcph, foc, cont, disp # the textbox has normal text color if it's focused # if it's defocused, the displayed text has to match the stored text in order # to be normal colored @@ -91,7 +91,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 @@ -126,7 +126,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 @@ -161,7 +161,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 @@ -171,7 +171,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 = [' '] @@ -184,7 +184,7 @@ function initialize_block!(tbox::Textbox) tbox.displayed_string[] = join(newchars) end - on(topscene, events(scene).unicode_input; priority=60) do char + on(topscene, events(scene).unicode_input; priority = 60) do char if tbox.focused[] && is_allowed(char, tbox.restriction[]) insertchar!(char, cursorindex[] + 1) return Consume(true) @@ -212,7 +212,7 @@ function initialize_block!(tbox::Textbox) end - on(topscene, events(scene).keyboardbutton; priority=60) do event + on(topscene, events(scene).keyboardbutton; priority = 60) do event if tbox.focused[] ctrl_v = (Keyboard.left_control | Keyboard.right_control) & Keyboard.v if ispressed(scene, ctrl_v) @@ -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 2c37f8d38ba..6cf13fe6fbe 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/defaultattributes.jl b/src/makielayout/defaultattributes.jl index 76c1c8420a3..757ee53acdb 100644 --- a/src/makielayout/defaultattributes.jl +++ b/src/makielayout/defaultattributes.jl @@ -10,12 +10,12 @@ function inherit(::Nothing, attr::Symbol, default_value) default_value end -inherit(scene, attr::NTuple{1, <: Symbol}, default_value) = inherit(scene, attr[begin], default_value) +inherit(scene, attr::NTuple{1,<:Symbol}, default_value) = inherit(scene, attr[begin], default_value) -function inherit(scene, attr::NTuple{N, <: Symbol}, default_value) where N +function inherit(scene, attr::NTuple{N,<:Symbol}, default_value) where N current_dict = scene.theme - for i in 1:(N-1) + for i in 1:(N - 1) if haskey(current_dict, attr[i]) current_dict = current_dict[attr[i]] else @@ -30,7 +30,7 @@ function inherit(scene, attr::NTuple{N, <: Symbol}, default_value) where N end end -function inherit(::Nothing, attr::NTuple{N, Symbol}, default_value::T) where {N, T} +function inherit(::Nothing, attr::NTuple{N,Symbol}, default_value::T) where {N,T} default_value 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 0b2c2e81212..b61fc40edbf 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 @@ -138,7 +138,7 @@ function tightlimits!(la::Axis, ::Top) end function GridLayoutBase.GridLayout(scene::Scene, args...; kwargs...) - return GridLayout(args...; bbox=lift(Rect2f, viewport(scene)), kwargs...) + return GridLayout(args...; bbox = lift(Rect2f, viewport(scene)), kwargs...) end function axislines!(scene, rect, spinewidth, topspinevisible, rightspinevisible, @@ -174,13 +174,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 @@ -251,17 +251,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) @@ -319,13 +319,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), scene, 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 @@ -378,15 +378,15 @@ 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...) label = Label(scene, label; halign = :left, labelkw...) - valuelabel = Label(scene, lift(x -> apply_format(x, format), scene, slider.value); halign=:right, - valuekw...) + valuelabel = Label(scene, lift(x -> apply_format(x, format), scene, slider.value); halign = :right, + valuekw...) (; slider = slider, label = label, valuelabel = valuelabel) end diff --git a/src/makielayout/interactions.jl b/src/makielayout/interactions.jl index 3945f0ba86e..6fcde12706b 100644 --- a/src/makielayout/interactions.jl +++ b/src/makielayout/interactions.jl @@ -152,7 +152,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 @@ -180,7 +180,7 @@ function process_interaction(r::RectangleZoom, event::MouseEvent, ax::Axis) try r.callback(r.rectnode[]) catch e - @warn "error in rectangle zoom" exception=(e, Base.catch_backtrace()) + @warn "error in rectangle zoom" exception = (e, Base.catch_backtrace()) end r.active[] = false return Consume(true) @@ -189,10 +189,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) @@ -249,11 +249,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 471da012cda..097b1573f08 100644 --- a/src/makielayout/lineaxis.jl +++ b/src/makielayout/lineaxis.jl @@ -8,7 +8,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]) @@ -26,9 +26,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 @@ -51,10 +51,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) @@ -102,13 +102,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 @@ -127,7 +127,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}.") @@ -135,9 +135,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 @@ -194,11 +194,11 @@ is_within_limits(tv, limits) = (limits[1] ≤ tv || limits[1] ≈ tv) && (tv ≤ 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 @@ -230,8 +230,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_unfiltered, 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_unfiltered, scale, reversed::Bool) + position::Float32, extents_uncorrected::NTuple{2,Float32}, horizontal::Bool = pos_extents_horizontal extents = reversed ? reverse(extents_uncorrected) : extents_uncorrected @@ -256,7 +256,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, @@ -266,13 +266,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, parent, endpoints; ignore_equal_values=true) + pos_extents_horizontal = lift(calculate_horizontal_extends, parent, endpoints; ignore_equal_values = true) horizontal = lift(x -> x[3], parent, 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)), parent, attrs.limits; ignore_equal_values=true) - flipped = lift(x -> convert(Bool, x), parent, attrs.flipped; ignore_equal_values=true) + limits = lift(x -> convert(NTuple{2,Float32}, Tuple(x)), parent, attrs.limits; ignore_equal_values = true) + flipped = lift(x -> convert(Bool, x), parent, 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 @@ -280,7 +280,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 @@ -288,22 +288,22 @@ 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, parent, realticklabelalign, ticklabelalign, horizontal, flipped, - ticklabelrotation) + ticklabelrotation) - ticklabel_annotation_obs = Observable(Tuple{Any, Point2f}[]; ignore_equal_values=true) + ticklabel_annotation_obs = Observable(Tuple{Any,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!(parent, 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) @@ -326,25 +326,25 @@ function LineAxis(parent::Scene, attrs::Attributes) end end - tickspace = Observable(0f0; ignore_equal_values=true) + tickspace = Observable(0f0; ignore_equal_values = true) map!(parent, 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!(parent, 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!(parent, labelpos, pos_extents_horizontal, flipped, - labelgap) do (position, extents, horizontal), flipped, labelgap + labelgap) do (position, extents, horizontal), flipped, labelgap # fullgap = tickspace[] + labelgap middle = extents[1] + 0.5f0 * (extents[2] - extents[1]) @@ -354,10 +354,10 @@ 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!(parent, labelalign, labelrotation, horizontal, flipped, - flip_vertical_label) do labelrotation, - horizontal::Bool, flipped::Bool, flip_vertical_label::Bool + flip_vertical_label) do labelrotation, + horizontal::Bool, flipped::Bool, flip_vertical_label::Bool return if labelrotation isa Automatic if horizontal (:center, flipped ? :bottom : :top) @@ -370,13 +370,13 @@ 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!(parent, labelrot, labelrotation, horizontal, - flip_vertical_label) do labelrotation, - horizontal::Bool, flip_vertical_label::Bool + flip_vertical_label) do labelrotation, + horizontal::Bool, flip_vertical_label::Bool return if labelrotation isa Automatic if horizontal 0f0 @@ -414,24 +414,24 @@ 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{Any}}}() map!(parent, tickvalues_labels_unfiltered, pos_extents_horizontal, limits, ticks, tickformat, - attrs.scale) do (position, extents, horizontal), - limits, ticks, tickformat, scale + attrs.scale) do (position, extents, horizontal), + limits, ticks, tickformat, scale get_ticks(ticks, scale, tickformat, limits...) end - tickpositions = Observable(Point2f[]; ignore_equal_values=true) - tickstrings = Observable(Any[]; ignore_equal_values=true) + tickpositions = Observable(Point2f[]; ignore_equal_values = true) + tickstrings = Observable(Any[]; ignore_equal_values = true) onany(update_tickpos_string, parent, 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(parent, tickvalues, minorticks) do tickvalues, minorticks minortickvalues[] = get_minor_tickvalues(minorticks, attrs.scale[], tickvalues, limits[]...) @@ -457,14 +457,14 @@ function LineAxis(parent::Scene, attrs::Attributes) tickpositions, tickalign, ticksize, spinewidth) linepoints = lift(create_linepoints, parent, pos_extents_horizontal, flipped, spinewidth, trimspine, - tickpositions, tickwidth) + tickpositions, tickwidth) decorations[:axisline] = linesegments!(parent, linepoints, linewidth = spinewidth, visible = spinevisible, color = spinecolor, inspectable = false, linestyle = nothing) translate!(decorations[:axisline], 0, 0, 20) - protrusion = Observable(0f0; ignore_equal_values=true) + protrusion = Observable(0f0; ignore_equal_values = true) map!(calculate_protrusion, parent, protrusion, # we pass these as observables, to not trigger on them @@ -518,11 +518,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) @@ -565,7 +565,7 @@ get_tickvalues(::Automatic, _, vmin, vmax) = get_tickvalues(automatic, identity, # fall back to non-scale aware behavior if no special version is overloaded get_tickvalues(ticks, _, vmin, vmax) = get_tickvalues(ticks, vmin, vmax) -function get_ticks(ticks_and_labels::Tuple{Any, Any}, _, ::Automatic, vmin, vmax) +function get_ticks(ticks_and_labels::Tuple{Any,Any}, _, ::Automatic, vmin, vmax) n1 = length(ticks_and_labels[1]) n2 = length(ticks_and_labels[2]) if n1 != n2 @@ -576,7 +576,7 @@ end function get_ticks(tickfunction::Function, _, 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 @@ -691,11 +691,11 @@ function get_ticks(m::AngularTicks, any_scale, ::Automatic, vmin, vmax) end ϵ = 1e-6 - vmin = ceil(Int, dvmin / ideal_step - ϵ) * ideal_step + vmin = ceil(Int, dvmin / ideal_step - ϵ) * ideal_step vmax = floor(Int, dvmax / ideal_step + ϵ) * ideal_step - multiples = collect(vmin:ideal_step:vmax+ϵ) + multiples = collect(vmin:ideal_step:(vmax + ϵ)) else - s = 360/2pi + s = 360 / 2pi multiples = Makie.get_tickvalues(LinearTicks(3), s * dvmin, s * dvmax) ./ s end @@ -722,21 +722,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) @@ -759,21 +759,21 @@ function get_minor_tickvalues(i::IntervalsBetween, scale::LogFunctions, tickvalu 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 c7fe0ddadd1..54c8b4ada6b 100644 --- a/src/makielayout/mousestatemachine.jl +++ b/src/makielayout/mousestatemachine.jl @@ -1,40 +1,40 @@ module MouseEventTypes - @enum MouseEventType begin - out - enter - over +@enum MouseEventType begin + out + enter + over - leftdown - rightdown - middledown + leftdown + rightdown + middledown - leftup - rightup - middleup + leftup + rightup + middleup - leftdragstart - rightdragstart - middledragstart + leftdragstart + rightdragstart + middledragstart - leftdrag - rightdrag - middledrag + leftdrag + rightdrag + middledrag - leftdragstop - rightdragstop - middledragstop + leftdragstop + rightdragstop + middledragstop - leftclick - rightclick - middleclick + leftclick + rightclick + middleclick - leftdoubleclick - rightdoubleclick - middledoubleclick + leftdoubleclick + rightdoubleclick + middledoubleclick - downoutside - end - export MouseEventType + downoutside +end +export MouseEventType end using .MouseEventTypes @@ -124,7 +124,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 @@ -206,7 +206,7 @@ function _addmouseevents!(scene, is_mouse_over_relevant_area, priority) last_click_was_double = Ref(false) # react to mouse position changes - mousepos_observerfunc = on(scene, events(scene).mouseposition; priority=priority) do mp + mousepos_observerfunc = on(scene, events(scene).mouseposition; priority = priority) do mp consumed = false t = time() data = mouseposition(scene) @@ -277,7 +277,7 @@ function _addmouseevents!(scene, is_mouse_over_relevant_area, priority) # react to mouse button changes - mousedrag_observerfunc = on(scene, events(scene).mousebutton, priority=priority) do event + mousedrag_observerfunc = on(scene, events(scene).mousebutton, priority = priority) do event consumed = false t = time() data = prev_data[] @@ -350,7 +350,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 = to_doubleclick_event(mouse_downed_button[]) x = setindex!(mouseevent, @@ -372,7 +372,7 @@ function _addmouseevents!(scene, is_mouse_over_relevant_area, priority) mouse_downed_inside[] = false # up after click - event = to_up_event(mouse_downed_button[]) + event = to_up_event(mouse_downed_button[]) x = setindex!(mouseevent, MouseEvent(event, t, data, px, prev_t[], prev_data[], prev_px[]) ) diff --git a/src/makielayout/roundedrect.jl b/src/makielayout/roundedrect.jl index 217e02e0d76..ca62dabfb93 100644 --- a/src/makielayout/roundedrect.jl +++ b/src/makielayout/roundedrect.jl @@ -17,7 +17,7 @@ function plot!(roundrect::RoundedRect) widthattr = roundrect.width roundedrectpoints = lift(roundrect, 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 7723db9bf9c..b13d27988dd 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} @@ -9,7 +9,7 @@ end struct DataAspect end struct Cycle - cycle::Vector{Pair{Vector{Symbol}, Symbol}} + cycle::Vector{Pair{Vector{Symbol},Symbol}} covary::Bool end @@ -19,8 +19,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) @@ -51,7 +51,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 @@ -135,7 +135,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{Any}} @@ -150,38 +150,38 @@ 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} modifier::Any # e.g. Keyboard.left_alt, or some other button that needs to be pressed to start rectangle... Defaults to `true`, which means no modifier needed end -function RectangleZoom(callback::Function; restrict_x=false, restrict_y=false, modifier=true) +function RectangleZoom(callback::Function; restrict_x = false, restrict_y = false, modifier = true) return RectangleZoom(callback, Observable(false), restrict_x, restrict_y, - nothing, nothing, Observable(Rect2f(0, 0, 1, 1)), modifier) + nothing, nothing, Observable(Rect2f(0, 0, 1, 1)), modifier) 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 @@ -207,10 +207,10 @@ 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 - elements::Dict{Symbol, Any} + elements::Dict{Symbol,Any} @attributes begin """ The content of the x axis label. @@ -304,9 +304,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." @@ -316,9 +316,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 = 5f0 "The size of the ytick marks." @@ -437,9 +437,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) """ Controls what numerical tick values are calculated for the x axis. @@ -526,12 +526,12 @@ end If `true`, limits the x axis spine's extent to the outermost major tick marks. Can also be set to a `Tuple{Bool,Bool}` to control each side separately. """ - xtrimspine::Union{Bool, Tuple{Bool,Bool}} = false + xtrimspine::Union{Bool,Tuple{Bool,Bool}} = false """ If `true`, limits the y axis spine's extent to the outermost major tick marks. Can also be set to a `Tuple{Bool,Bool}` to control each side separately. """ - 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." @@ -656,13 +656,13 @@ end function RectangleZoom(f::Function, ax::Axis; kw...) r = RectangleZoom(f; kw...) selection_vertices = lift(_selection_vertices, ax.blockscene, Observable(ax.scene), ax.finallimits, - r.rectnode) + r.rectnode) # manually specify correct faces for a rectangle with a rectangle hole inside faces = [1 2 5; 5 2 6; 2 3 6; 6 3 7; 3 4 7; 7 4 8; 4 1 8; 8 1 5] # 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 = NoShading, - 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 @@ -933,8 +933,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 @@ -1129,7 +1129,7 @@ struct LegendEntry attributes::Attributes end -const EntryGroup = Tuple{Any, Vector{LegendEntry}} +const EntryGroup = Tuple{Any,Vector{LegendEntry}} @Block Legend begin entrygroups::Observable{Vector{EntryGroup}} @@ -1361,7 +1361,7 @@ end mouseeventhandle::MouseEventHandle scrollevents::Observable{ScrollEvent} keysevents::Observable{KeysEvent} - interactions::Dict{Symbol, Tuple{Bool, Any}} + interactions::Dict{Symbol,Tuple{Bool,Any}} @attributes begin "The height setting of the scene." height = nothing @@ -1378,7 +1378,7 @@ end "The alignment of the scene in its suggested bounding box." alignmode = Inside() "The elevation (up / down) angle of the camera. Possible values are between -pi/2 (looking from the bottom up) and +pi/2 (looking from the top down)." - elevation = pi/8 + elevation = pi / 8 """ The azimuth (left / right) angle of the camera. @@ -1402,7 +1402,7 @@ end where a cube in data space looks like a cube and not a cuboid. - `:equal` which is a shorthand for `(1, 1, 1)` """ - aspect = (1.0, 1.0, 2/3) # :data :equal + aspect = (1.0, 1.0, 2 / 3) # :data :equal """ The view mode affects the final projection of the axis by fitting the axis cuboid into the available space in different ways. @@ -1645,8 +1645,8 @@ end @Block PolarAxis <: AbstractAxis begin scene::Scene overlay::Scene - target_rlims::Observable{Tuple{Float64, Float64}} - target_thetalims::Observable{Tuple{Float64, Float64}} + target_rlims::Observable{Tuple{Float64,Float64}} + target_thetalims::Observable{Tuple{Float64,Float64}} target_theta_0::Observable{Float32} target_r0::Observable{Float32} @attributes begin @@ -1695,9 +1695,9 @@ end "Controls whether `r < 0` (after applying `radius_at_origin`) gets clipped (true) or not (false)." clip_r::Bool = true "The relative margins added to the autolimits in r direction." - rautolimitmargin::Tuple{Float64, Float64} = (0.05, 0.05) + rautolimitmargin::Tuple{Float64,Float64} = (0.05, 0.05) "The relative margins added to the autolimits in theta direction." - thetaautolimitmargin::Tuple{Float64, Float64} = (0.05, 0.05) + thetaautolimitmargin::Tuple{Float64,Float64} = (0.05, 0.05) # Spine @@ -1749,7 +1749,7 @@ end # Theta ticks "The specifier for the angular (`theta`) ticks, similar to `yticks` for a normal Axis." - thetaticks = AngularTicks(180/pi, "°") # ((0:45:315) .* pi/180, ["$(x)°" for x in 0:45:315]) + thetaticks = AngularTicks(180 / pi, "°") # ((0:45:315) .* pi/180, ["$(x)°" for x in 0:45:315]) "The specifier for the minor `theta` ticks." thetaminorticks = IntervalsBetween(2) "The formatter for the `theta` ticks." 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/precompiles.jl b/src/precompiles.jl index 1ed6f3e0054..7f75c97e4b8 100644 --- a/src/precompiles.jl +++ b/src/precompiles.jl @@ -11,15 +11,15 @@ end precompile(Makie.initialize_block!, (Axis,)) precompile(_get_glyphcollection_and_linesegments, - (LaTeXStrings.LaTeXString, Int64, Float32, - FreeTypeAbstraction.FTFont, Attributes, - Tuple{Symbol,Symbol}, Quaternion{Float64}, - MakieCore.Automatic, Float64, - ColorTypes.RGBA{Float32}, ColorTypes.RGBA{Float32}, - Int64, Int64, Vec{2,Float32})) + (LaTeXStrings.LaTeXString, Int64, Float32, + FreeTypeAbstraction.FTFont, Attributes, + Tuple{Symbol,Symbol}, Quaternion{Float64}, + MakieCore.Automatic, Float64, + ColorTypes.RGBA{Float32}, ColorTypes.RGBA{Float32}, + Int64, Int64, Vec{2,Float32})) precompile(Makie.apply_alignment_and_justification!, (Vector{Vector{Makie.GlyphInfo}}, MakieCore.Automatic, - Tuple{Symbol,Symbol})) + Tuple{Symbol,Symbol})) precompile(MakieCore.convert_arguments, (Type{Scatter}, UnitRange{Int64})) precompile(Makie.assemble_colors, (UnitRange{Int64}, Any, Any)) @@ -49,6 +49,6 @@ precompile(translate, (MoveTo, Vec2{Float64})) precompile(scale, (MoveTo, Vec{2,Float32})) precompile(append!, (Vector{FreeType.FT_Vector_}, Vector{FreeType.FT_Vector_})) precompile(convert_command, (MoveTo,)) -precompile(plot!, (MakieCore.Text{Tuple{Vector{Point{2, Float32}}}},)) +precompile(plot!, (MakieCore.Text{Tuple{Vector{Point{2,Float32}}}},)) precompile(Vec2{Float64}, (Tuple{Int64,Int64},)) precompile(MakieCore._create_plot, (typeof(scatter), Dict{Symbol,Any}, UnitRange{Int64})) diff --git a/src/recording.jl b/src/recording.jl index a06999a8251..0f446f01231 100644 --- a/src/recording.jl +++ b/src/recording.jl @@ -26,21 +26,21 @@ mutable struct RamStepper format::Symbol end -function Stepper(figlike::FigureLike; backend=current_backend(), format=:png, visible=false, connect=false, screen_kw...) +function Stepper(figlike::FigureLike; backend = current_backend(), format = :png, visible = false, connect = false, screen_kw...) config = Dict{Symbol,Any}(screen_kw) get!(config, :visible, visible) get!(config, :start_renderloop, false) screen = getscreen(backend, get_scene(figlike), config, JuliaNative) - display(screen, figlike; connect=connect) + 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_kw...) +function Stepper(figlike::FigureLike, path::String, step::Int; format = :png, backend = current_backend(), visible = false, connect = false, screen_kw...) config = Dict{Symbol,Any}(screen_kw) get!(config, :visible, visible) get!(config, :start_renderloop, false) screen = getscreen(backend, get_scene(figlike), config, JuliaNative) - display(screen, figlike; connect=connect) + display(screen, figlike; connect = connect) return FolderStepper(figlike, screen, path, format, step) end @@ -145,13 +145,13 @@ end """ function record(func, figlike::FigureLike, path::AbstractString; kw_args...) format = lstrip(splitext(path)[2], '.') - io = Record(func, figlike; format=format, visible=true, kw_args...) + io = Record(func, figlike; format = format, visible = true, 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 @@ -172,7 +172,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 fe16c2d868a..696b91893cd 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 @@ -48,7 +48,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 @@ -90,22 +90,22 @@ mutable struct Scene <: AbstractScene cycler::Cycler function Scene( - parent::Union{Nothing, Scene}, - events::Events, - viewport::Observable{Rect2i}, - clear::Observable{Bool}, - camera::Camera, - camera_controls::AbstractCamera, - transformation::Transformation, - plots::Vector{AbstractPlot}, - theme::Attributes, - children::Vector{Scene}, - current_screens::Vector{MakieScreen}, - backgroundcolor::Observable{RGBAf}, - visible::Observable{Bool}, - ssao::SSAO, - lights::Vector - ) + parent::Union{Nothing,Scene}, + events::Events, + viewport::Observable{Rect2i}, + clear::Observable{Bool}, + camera::Camera, + camera_controls::AbstractCamera, + transformation::Transformation, + plots::Vector{AbstractPlot}, + theme::Attributes, + children::Vector{Scene}, + current_screens::Vector{MakieScreen}, + backgroundcolor::Observable{RGBAf}, + visible::Observable{Bool}, + ssao::SSAO, + lights::Vector + ) scene = new( parent, events, @@ -131,20 +131,20 @@ mutable struct Scene <: AbstractScene end # on & map versions that deregister when scene closes! -function Observables.on(@nospecialize(f), @nospecialize(scene::Union{Plot,Scene}), @nospecialize(observable::Observable); update=false, priority=0) - to_deregister = on(f, observable; update=update, priority=priority)::Observables.ObserverFunction +function Observables.on(@nospecialize(f), @nospecialize(scene::Union{Plot,Scene}), @nospecialize(observable::Observable); update = false, priority = 0) + to_deregister = on(f, observable; update = update, priority = priority)::Observables.ObserverFunction push!(scene.deregister_callbacks::Vector{Observables.ObserverFunction}, to_deregister) return to_deregister end -function Observables.onany(@nospecialize(f), @nospecialize(scene::Union{Plot,Scene}), @nospecialize(observables...); update=false, priority=0) - to_deregister = onany(f, observables...; priority=priority, update=update) +function Observables.onany(@nospecialize(f), @nospecialize(scene::Union{Plot,Scene}), @nospecialize(observables...); update = false, priority = 0) + to_deregister = onany(f, observables...; priority = priority, update = update) append!(scene.deregister_callbacks::Vector{Observables.ObserverFunction}, to_deregister) return to_deregister end @inline function Base.map!(f, @nospecialize(scene::Union{Plot,Scene}), result::AbstractObservable, os...; - update::Bool=true, priority = 0) + update::Bool = true, priority = 0) # note: the @inline prevents de-specialization due to the splatting callback = Observables.MapCallback(f, result, os) for o in os @@ -155,10 +155,10 @@ end end @inline function Base.map(f::F, @nospecialize(scene::Union{Plot,Scene}), arg1::AbstractObservable, args...; - ignore_equal_values=false, priority = 0) where {F} + ignore_equal_values = false, priority = 0) where {F} # note: the @inline prevents de-specialization due to the splatting - obs = Observable(f(arg1[], map(Observables.to_value, args)...); ignore_equal_values=ignore_equal_values) - map!(f, scene, obs, arg1, args...; update=false, priority = priority) + obs = Observable(f(arg1[], map(Observables.to_value, args)...); ignore_equal_values = ignore_equal_values) + map!(f, scene, obs, arg1, args...; update = false, priority = priority) return obs end @@ -185,34 +185,34 @@ 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(; - viewport::Union{Observable{Rect2i}, Nothing} = nothing, - events::Events = Events(), - clear::Union{Automatic, Observable{Bool}, Bool} = automatic, - transform_func=identity, - camera::Union{Function, Camera, Nothing} = nothing, - camera_controls::AbstractCamera = EmptyCamera(), - transformation::Transformation = Transformation(transform_func), - plots::Vector{AbstractPlot} = AbstractPlot[], - children::Vector{Scene} = Scene[], - current_screens::Vector{MakieScreen} = MakieScreen[], - parent = nothing, - visible = Observable(true), - ssao = SSAO(), - lights = automatic, - theme = Attributes(), - theme_kw... - ) + viewport::Union{Observable{Rect2i},Nothing} = nothing, + events::Events = Events(), + clear::Union{Automatic,Observable{Bool},Bool} = automatic, + transform_func = identity, + camera::Union{Function,Camera,Nothing} = nothing, + camera_controls::AbstractCamera = EmptyCamera(), + transformation::Transformation = Transformation(transform_func), + plots::Vector{AbstractPlot} = AbstractPlot[], + children::Vector{Scene} = Scene[], + current_screens::Vector{MakieScreen} = MakieScreen[], + parent = nothing, + visible = Observable(true), + ssao = SSAO(), + lights = automatic, + theme = Attributes(), + theme_kw... +) global_theme = merge_without_obs!(copy(theme), current_default_theme()) m_theme = merge_without_obs!(Attributes(theme_kw), global_theme) - bg = Observable{RGBAf}(to_color(m_theme.backgroundcolor[]); ignore_equal_values=true) + bg = Observable{RGBAf}(to_color(m_theme.backgroundcolor[]); ignore_equal_values = true) wasnothing = isnothing(viewport) if wasnothing @@ -222,7 +222,7 @@ function Scene(; else m_theme.size[] end - viewport = Observable(Recti(0, 0, sz); ignore_equal_values=true) + viewport = Observable(Recti(0, 0, sz); ignore_equal_values = true) end cam = camera isa Camera ? camera : Camera(viewport) @@ -280,30 +280,30 @@ get_ambient_light(scene::Scene) = get_one_light(scene.lights, AmbientLight) default_shading!(plot, scene::Scene) = default_shading!(plot, scene.lights) function Scene( - parent::Scene; - events=parent.events, - viewport=nothing, - clear=false, - camera=nothing, - camera_controls=parent.camera_controls, - transformation=Transformation(parent), - kw... - ) + parent::Scene; + events = parent.events, + viewport = nothing, + clear = false, + camera = nothing, + camera_controls = parent.camera_controls, + transformation = Transformation(parent), + kw... +) if camera !== parent.camera camera_controls = EmptyCamera() end - child_px_area = viewport isa Observable ? viewport : Observable(Rect2i(0, 0, 0, 0); ignore_equal_values=true) + child_px_area = viewport isa Observable ? viewport : Observable(Rect2i(0, 0, 0, 0); ignore_equal_values = true) child = Scene(; - events=events, - viewport=child_px_area, - clear=convert(Observable{Bool}, clear), - camera=camera, - camera_controls=camera_controls, - parent=parent, - transformation=transformation, - current_screens=copy(parent.current_screens), - theme=theme(parent), + events = events, + viewport = child_px_area, + clear = convert(Observable{Bool}, clear), + camera = camera, + camera_controls = camera_controls, + parent = parent, + transformation = transformation, + current_screens = copy(parent.current_screens), + theme = theme(parent), kw... ) if isnothing(viewport) @@ -322,7 +322,7 @@ end # legacy constructor function Scene(parent::Scene, area; kw...) - return Scene(parent; viewport=area, kw...) + return Scene(parent; viewport = area, kw...) end # Base overloads for Scene @@ -358,7 +358,7 @@ function Base.resize!(scene::Scene, rect::Rect2) end # 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] @@ -367,22 +367,22 @@ struct OldAxis end zero_origin(area) = Recti(0, 0, widths(area)) function child(scene::Scene; camera, attributes...) - return Scene(scene; camera=camera, attributes...) + return Scene(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}) @@ -399,7 +399,7 @@ function delete_scene!(scene::Scene) end function free(scene::Scene) - empty!(scene; free=true) + empty!(scene; free = true) for field in [:backgroundcolor, :viewport, :visible] Observables.clear(getfield(scene, field)) end @@ -411,7 +411,7 @@ function free(scene::Scene) return end -function Base.empty!(scene::Scene; free=false) +function Base.empty!(scene::Scene; free = false) foreach(empty!, copy(scene.children)) # clear plots of this scene for plot in copy(scene.plots) @@ -420,7 +420,7 @@ function Base.empty!(scene::Scene; free=false) # clear all child scenes if !isnothing(scene.parent) - filter!(x-> x !== scene, scene.parent.children) + filter!(x -> x !== scene, scene.parent.children) end empty!(scene.children) @@ -522,7 +522,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) @@ -545,7 +545,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) @@ -593,7 +593,7 @@ struct FigureAxisPlot plot::AbstractPlot end -const FigureLike = Union{Scene, Figure, FigureAxisPlot} +const FigureLike = Union{Scene,Figure,FigureAxisPlot} """ is_atomic_plot(plot::Plot) @@ -611,27 +611,27 @@ is_atomic_plot(plot::Plot) = isempty(plot.plots) Collects all plots in the provided `<: ScenePlot` and returns a vector of all plots which satisfy `is_atomic_plot`, which defaults to Makie's definition of `Makie.is_atomic_plot`. """ -function collect_atomic_plots(xplot::Plot, plots=AbstractPlot[]; is_atomic_plot=is_atomic_plot) +function collect_atomic_plots(xplot::Plot, plots = AbstractPlot[]; is_atomic_plot = is_atomic_plot) if is_atomic_plot(xplot) # Atomic plot! push!(plots, xplot) else for elem in xplot.plots - collect_atomic_plots(elem, plots; is_atomic_plot=is_atomic_plot) + collect_atomic_plots(elem, plots; is_atomic_plot = is_atomic_plot) end end return plots end -function collect_atomic_plots(array, plots=AbstractPlot[]; is_atomic_plot=is_atomic_plot) +function collect_atomic_plots(array, plots = AbstractPlot[]; is_atomic_plot = is_atomic_plot) for elem in array - collect_atomic_plots(elem, plots; is_atomic_plot=is_atomic_plot) + collect_atomic_plots(elem, plots; is_atomic_plot = is_atomic_plot) end plots end -function collect_atomic_plots(scene::Scene, plots=AbstractPlot[]; is_atomic_plot=is_atomic_plot) - collect_atomic_plots(scene.plots, plots; is_atomic_plot=is_atomic_plot) - collect_atomic_plots(scene.children, plots; is_atomic_plot=is_atomic_plot) +function collect_atomic_plots(scene::Scene, plots = AbstractPlot[]; is_atomic_plot = is_atomic_plot) + collect_atomic_plots(scene.plots, plots; is_atomic_plot = is_atomic_plot) + collect_atomic_plots(scene.children, plots; is_atomic_plot = is_atomic_plot) plots end diff --git a/src/shorthands.jl b/src/shorthands.jl index a3e52857b23..92f29128ef8 100644 --- a/src/shorthands.jl +++ b/src/shorthands.jl @@ -82,7 +82,7 @@ yticklabels(scene) = ticklabels(scene)[2] Returns 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-axis. 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/specapi.jl b/src/specapi.jl index ad26b89206c..202e5419ea7 100644 --- a/src/specapi.jl +++ b/src/specapi.jl @@ -22,7 +22,7 @@ as well as plot type `P` of a basic plot. struct PlotSpec type::Symbol args::Vector{Any} - kwargs::Dict{Symbol, Any} + kwargs::Dict{Symbol,Any} function PlotSpec(type::Symbol, args...; kwargs...) type_str = string(type) if type_str[end] == '!' @@ -66,7 +66,7 @@ end Base.getindex(p::PlotSpec, i::Int) = getindex(p.args, i) Base.getindex(p::PlotSpec, i::Symbol) = getproperty(p.kwargs, i) -PlotSpec(::Type{P}, args...; kwargs...) where {P <: Plot} = PlotSpec(plotsym(P), args...; kwargs...) +PlotSpec(::Type{P}, args...; kwargs...) where {P<:Plot} = PlotSpec(plotsym(P), args...; kwargs...) to_plotspec(::Type{P}, args; kwargs...) where {P} = PlotSpec(plotsym(P), args...; kwargs...) function to_plotspec(::Type{P}, p::PlotSpec; kwargs...) where {P} @@ -82,7 +82,7 @@ struct BlockSpec plots::Vector{PlotSpec} end -function BlockSpec(typ::Symbol, args...; plots::Vector{PlotSpec}=PlotSpec[], kw...) +function BlockSpec(typ::Symbol, args...; plots::Vector{PlotSpec} = PlotSpec[], kw...) attr = Dict{Symbol,Any}(kw) if typ == :Legend # TODO, this is hacky and works around the fact, @@ -115,8 +115,8 @@ rangeunion(r1, r2::Colon) = r1 struct GridLayoutSpec content::Vector{Pair{GridLayoutPosition,Union{GridLayoutSpec,BlockSpec}}} - size::Tuple{Int, Int} - offsets::Tuple{Int, Int} + size::Tuple{Int,Int} + offsets::Tuple{Int,Int} colsizes::Vector{ContentSize} rowsizes::Vector{ContentSize} @@ -129,17 +129,17 @@ struct GridLayoutSpec valign::Float64 function GridLayoutSpec( - content::AbstractVector{<:Pair}; - colsizes = nothing, - rowsizes = nothing, - colgaps = nothing, - rowgaps = nothing, - alignmode::AlignMode = GridLayoutBase.Inside(), - tellheight::Bool = true, - tellwidth::Bool = true, - halign::Union{Symbol,Real} = :center, - valign::Union{Symbol,Real} = :center, - ) + content::AbstractVector{<:Pair}; + colsizes = nothing, + rowsizes = nothing, + colgaps = nothing, + rowgaps = nothing, + alignmode::AlignMode = GridLayoutBase.Inside(), + tellheight::Bool = true, + tellwidth::Bool = true, + halign::Union{Symbol,Real} = :center, + valign::Union{Symbol,Real} = :center, + ) rowspan, colspan = foldl(content; init = (1:1, 1:1)) do (rows, cols), ((_rows, _cols, _...), _) rangeunion(rows, _rows), rangeunion(cols, _cols) @@ -266,7 +266,7 @@ end function compare_specs(a::PlotSpec, b::PlotSpec) a.type === b.type || return false length(a.args) == length(b.args) || return false - all(i-> typeof(a.args[i]) == typeof(b.args[i]), 1:length(a.args)) || return false + all(i -> typeof(a.args[i]) == typeof(b.args[i]), 1:length(a.args)) || return false length(a.kwargs) == length(b.kwargs) || return false ka = keys(a.kwargs) @@ -412,7 +412,7 @@ function find_reusable_plot(plotspec::PlotSpec, reusable_plots::IdDict{PlotSpec, end function diff_plotlist!(scene::Scene, plotspecs::Vector{PlotSpec}, obs_to_notify, reusable_plots, - plotlist::Union{Nothing,PlotList}=nothing) + plotlist::Union{Nothing,PlotList} = nothing) new_plots = IdDict{PlotSpec,Plot}() # needed to be mutated empty!(scene.cycler.counters) # Global list of observables that need updating @@ -441,7 +441,7 @@ function diff_plotlist!(scene::Scene, plotspecs::Vector{PlotSpec}, obs_to_notify return new_plots end -function update_plotspecs!(scene::Scene, list_of_plotspecs::Observable, plotlist::Union{Nothing, PlotList}=nothing) +function update_plotspecs!(scene::Scene, list_of_plotspecs::Observable, plotlist::Union{Nothing,PlotList} = nothing) # Cache plots here so that we aren't re-creating plots every time; # if a plot still exists from last time, update it accordingly. # If the plot is removed from `plotspecs`, we'll delete it from here @@ -466,7 +466,7 @@ function update_plotspecs!(scene::Scene, list_of_plotspecs::Observable, plotlist delete!(scene, plot) end # Transfer all new plots into unused_plots for the next update! - @assert !any(x-> x in unused_plots, new_plots) + @assert !any(x -> x in unused_plots, new_plots) empty!(unused_plots) merge!(unused_plots, new_plots) # finally, notify all changes at once @@ -474,7 +474,7 @@ function update_plotspecs!(scene::Scene, list_of_plotspecs::Observable, plotlist return end l = Base.ReentrantLock() - on(scene, list_of_plotspecs; update=true) do plotspecs + on(scene, list_of_plotspecs; update = true) do plotspecs lock(l) do update_plotlist(plotspecs) end @@ -483,7 +483,7 @@ function update_plotspecs!(scene::Scene, list_of_plotspecs::Observable, plotlist return end -function Makie.plot!(p::PlotList{<: Tuple{<: AbstractArray{PlotSpec}}}) +function Makie.plot!(p::PlotList{<:Tuple{<:AbstractArray{PlotSpec}}}) scene = Makie.parent_scene(p) update_plotspecs!(scene, p[1], p) return @@ -498,7 +498,7 @@ function compare_layout_slot((anesting, ap, a)::Tuple{Int,GP,BlockSpec}, (bnesti return true end -function compare_layout_slot((anesting, ap, a)::Tuple{Int,GP, GridLayoutSpec}, (bnesting, bp, b)::Tuple{Int,GP, GridLayoutSpec}) where {GP <: GridLayoutPosition} +function compare_layout_slot((anesting, ap, a)::Tuple{Int,GP,GridLayoutSpec}, (bnesting, bp, b)::Tuple{Int,GP,GridLayoutSpec}) where {GP<:GridLayoutPosition} anesting !== bnesting && return false ap !== bp && return false for (ac, bc) in zip(a.content, b.content) @@ -520,20 +520,20 @@ end function to_layoutable(parent, position::GridLayoutPosition, spec::GridLayoutSpec) # TODO pass colsizes etc gl = GridLayout(length(spec.rowsizes), length(spec.colsizes); - colsizes=spec.colsizes, - rowsizes=spec.rowsizes, - colgaps=spec.colgaps, - rowgaps=spec.rowgaps, - alignmode=spec.alignmode, - tellwidth=spec.tellwidth, - tellheight=spec.tellheight, - halign=spec.halign, - valign=spec.valign) + colsizes = spec.colsizes, + rowsizes = spec.rowsizes, + colgaps = spec.colgaps, + rowgaps = spec.rowgaps, + alignmode = spec.alignmode, + tellwidth = spec.tellwidth, + tellheight = spec.tellheight, + halign = spec.halign, + valign = spec.valign) parent[position...] = gl return gl end -function update_layoutable!(block::T, plot_obs, old_spec::BlockSpec, spec::BlockSpec) where T <: Block +function update_layoutable!(block::T, plot_obs, old_spec::BlockSpec, spec::BlockSpec) where T<:Block old_attr = keys(old_spec.kwargs) new_attr = keys(spec.kwargs) # attributes that have been set previously and need to get unset now @@ -573,7 +573,7 @@ function to_gl_key(key::Symbol) return key end -function update_layoutable!(layout::GridLayout, obs, old_spec::Union{GridLayoutSpec, Nothing}, spec::GridLayoutSpec) +function update_layoutable!(layout::GridLayout, obs, old_spec::Union{GridLayoutSpec,Nothing}, spec::GridLayoutSpec) # Block updates until very end where all children etc got deleted! layout.block_updates = true keys = (:alignmode, :tellwidth, :tellheight, :halign, :valign) @@ -617,8 +617,8 @@ function find_layoutable(spec, layoutables) end -function update_gridlayout!(gridlayout::GridLayout, nesting::Int, oldgridspec::Union{Nothing, GridLayoutSpec}, - gridspec::GridLayoutSpec, previous_contents, new_layoutables) +function update_gridlayout!(gridlayout::GridLayout, nesting::Int, oldgridspec::Union{Nothing,GridLayoutSpec}, + gridspec::GridLayoutSpec, previous_contents, new_layoutables) update_layoutable!(gridlayout, nothing, oldgridspec, gridspec) @@ -641,7 +641,7 @@ function update_gridlayout!(gridlayout::GridLayout, nesting::Int, oldgridspec::U elseif new_layoutable isa GridLayout # Make sure all plots & blocks are inserted update_gridlayout!(new_layoutable, nesting + 1, spec, spec, previous_contents, - new_layoutables) + new_layoutables) end push!(new_layoutables, (nesting, position, spec) => (new_layoutable, obs)) else @@ -664,7 +664,7 @@ function update_gridlayout!(gridlayout::GridLayout, nesting::Int, oldgridspec::U end get_layout!(fig::Figure) = fig.layout -get_layout!(gp::Union{GridSubposition,GridPosition}) = GridLayoutBase.get_layout_at!(gp; createmissing=true) +get_layout!(gp::Union{GridSubposition,GridPosition}) = GridLayoutBase.get_layout_at!(gp; createmissing = true) # We use this to decide if we can re-use a plot. # (nesting_level_in_layout, position_in_layout, spec) @@ -682,14 +682,14 @@ end function update_fig!(fig::Union{Figure,GridPosition,GridSubposition}, layout_obs::Observable{GridLayoutSpec}) # Global list of all layoutables. The LayoutableKey includes a nesting, so that we can keep even nested layouts in one global list. # Vector of Pairs should allow to have an identical key without overwriting the previous value - unused_layoutables = Pair{LayoutableKey, Tuple{Layoutable,Observable{Vector{PlotSpec}}}}[] + unused_layoutables = Pair{LayoutableKey,Tuple{Layoutable,Observable{Vector{PlotSpec}}}}[] new_layoutables = Pair{LayoutableKey,Tuple{Layoutable,Observable{Vector{PlotSpec}}}}[] sizehint!(unused_layoutables, 50) sizehint!(new_layoutables, 50) l = Base.ReentrantLock() layout = get_layout!(fig) - on(get_topscene(fig), layout_obs; update=true) do layout_spec + on(get_topscene(fig), layout_obs; update = true) do layout_spec lock(l) do # For each update we look into `unused_layoutables` to see if we can re-use a layoutable (GridLayout/Block). # Every re-used layoutable and every newly created gets pushed into `new_layoutables`, @@ -729,7 +729,7 @@ args_preferred_axis(::GridLayoutSpec) = FigureOnly plot!(plot::Plot{MakieCore.plot,Tuple{GridLayoutSpec}}) = plot -function plot!(fig::Union{Figure, GridLayoutBase.GridPosition}, plot::Plot{MakieCore.plot,Tuple{GridLayoutSpec}}) +function plot!(fig::Union{Figure,GridLayoutBase.GridPosition}, plot::Plot{MakieCore.plot,Tuple{GridLayoutSpec}}) figure = fig isa Figure ? fig : get_top_parent(fig) connect_plot!(figure.scene, plot) update_fig!(fig, plot[1]) diff --git a/src/stats/boxplot.jl b/src/stats/boxplot.jl index e6cbe36c2a0..71504adb994 100644 --- a/src/stats/boxplot.jl +++ b/src/stats/boxplot.jl @@ -36,7 +36,7 @@ The boxplot has 3 components: weights = automatic, color = theme(scene, :patchcolor), colormap = theme(scene, :colormap), - colorscale=identity, + colorscale = identity, colorrange = automatic, orientation = :vertical, # box and dodging @@ -124,7 +124,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 5fb77c29f0f..8d9b390a723 100644 --- a/src/stats/crossbar.jl +++ b/src/stats/crossbar.jl @@ -23,31 +23,31 @@ 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), - colorscale=identity, - 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), + colorscale = identity, + 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 @@ -92,8 +92,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) @@ -105,29 +105,29 @@ function Makie.plot!(plot::CrossBar) end return [boxes;], [midlines;] end - boxes = lift(s-> s[1], plot, signals) - midlines = lift(s-> s[2], plot, signals) + boxes = lift(s -> s[1], plot, signals) + midlines = lift(s -> s[2], plot, signals) poly!( plot, boxes, - color=plot.color, - colorrange=plot.colorrange, - colormap=plot.colormap, - colorscale=plot.colorscale, - strokecolor=plot.strokecolor, - strokewidth=plot.strokewidth, + color = plot.color, + colorrange = plot.colorrange, + colormap = plot.colormap, + colorscale = plot.colorscale, + strokecolor = plot.strokecolor, + strokewidth = plot.strokewidth, inspectable = plot[:inspectable] ) linesegments!( plot, - color=lift( + color = lift( (mc, sc) -> mc === automatic ? sc : mc, plot, 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 82034cce2e3..57e9f94f85e 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 6f2221119f3..f4468908186 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 f8038456a9e..1ae6a8ada77 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 @@ -22,7 +22,7 @@ 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 @@ -31,7 +31,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) @@ -56,9 +56,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 c163f29bf0a..f2221fe2cfc 100644 --- a/src/stats/hexbin.jl +++ b/src/stats/hexbin.jl @@ -20,18 +20,18 @@ Plots a heatmap with hexagonal bins for the observations `xs` and `ys`. """ @recipe(Hexbin) do scene return Attributes(; - colormap=theme(scene, :colormap), - colorscale=identity, - colorrange=Makie.automatic, + colormap = theme(scene, :colormap), + colorscale = identity, + colorrange = Makie.automatic, lowclip = automatic, highclip = automatic, nan_color = :transparent, - bins=20, - weights=nothing, - cellsize=nothing, - threshold=1, - strokewidth=0, - strokecolor=:black) + bins = 20, + weights = nothing, + cellsize = nothing, + threshold = 1, + strokewidth = 0, + strokecolor = :black) end function spacings_offsets_nbins(bins::Tuple{Int,Int}, cellsize::Nothing, xmi, xma, ymi, yma) @@ -57,7 +57,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 conversion_trait(::Type{<:Hexbin}) = PointBased() @@ -111,7 +111,7 @@ function plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) xsize = xspacing * 2 rx = xsize / sqrt3 - d = Dict{Tuple{Int,Int}, Float64}() + d = Dict{Tuple{Int,Int},Float64}() # for the distance measurement, the y dimension must be weighted relative to the x # dimension according to the different sizes in each, otherwise the attribution to hexagonal @@ -133,12 +133,12 @@ function plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) 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 @@ -147,9 +147,9 @@ function 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.0) @@ -198,7 +198,7 @@ function 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]]) scale = if haskey(hb, :scale) @warn("`hexbin(..., scale=$(hb.scale[]))` is deprecated, use `hexbin(..., colorscale=$(hb.scale[]))` instead") hb.scale @@ -206,18 +206,18 @@ function plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) hb.colorscale end return scatter!(hb, points; - colorrange=hb.colorrange, - color=count_hex, - colormap=hb.colormap, - colorscale=scale, - lowclip=hb.lowclip, - highclip=hb.highclip, - nan_color=hb.nan_color, - marker=hexmarker, - markersize=markersize, - markerspace=:data, - strokewidth=hb.strokewidth, - strokecolor=hb.strokecolor) + colorrange = hb.colorrange, + color = count_hex, + colormap = hb.colormap, + colorscale = scale, + lowclip = hb.lowclip, + highclip = hb.highclip, + nan_color = hb.nan_color, + marker = hexmarker, + markersize = markersize, + markerspace = :data, + strokewidth = hb.strokewidth, + strokecolor = hb.strokecolor) end function center_value(dv, spacing, offset, is_grid1) diff --git a/src/stats/hist.jl b/src/stats/hist.jl index 1b4a5bb2196..f8bda5ae07d 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() return to_plotspec(ptype, convert_arguments(ptype, map(f, h.edges)..., Float64.(h.weights)); kwargs...) end @@ -12,7 +12,7 @@ function _hist_center_weights(values, edges, normalization, scale_to, wgts) h = StatsBase.fit(StatsBase.Histogram, values[], w..., edges) h_norm = StatsBase.normalize(h; mode = normalization) weights = h_norm.weights - centers = edges[1:end-1] .+ (diff(edges) ./ 2) + centers = edges[1:(end - 1)] .+ (diff(edges) ./ 2) if scale_to === :flip weights .= -weights elseif !isnothing(scale_to) @@ -59,7 +59,7 @@ function Makie.plot!(plot::StepHist) edges = lift(pick_hist_edges, plot, values, plot.bins) points = lift(plot, edges, plot.normalization, plot.scale_to, - plot.weights) do edges, normalization, scale_to, wgts + plot.weights) do edges, normalization, scale_to, wgts _, weights = _hist_center_weights(values, edges, normalization, scale_to, wgts) phantomedge = edges[end] # to bring step back to baseline edges = vcat(edges, phantomedge) @@ -80,7 +80,7 @@ function Makie.plot!(plot::StepHist) pop!(attr, :normalization) pop!(attr, :scale_to) pop!(attr, :bins) - stairs!(plot, points; attr..., color=color) + stairs!(plot, points; attr..., color = color) plot end @@ -132,9 +132,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, @@ -154,7 +152,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") @@ -169,7 +167,7 @@ function Makie.plot!(plot::Hist) edges = lift(pick_hist_edges, plot, values, plot.bins) points = lift(plot, edges, plot.normalization, plot.scale_to, - plot.weights) do edges, normalization, scale_to, wgts + plot.weights) do edges, normalization, scale_to, wgts centers, weights = _hist_center_weights(values, edges, normalization, scale_to, wgts) return Point2f.(centers, weights) end @@ -186,7 +184,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(plot, widths) do w diff --git a/src/stats/violin.jl b/src/stats/violin.jl index 73bbe24a788..ab5a59232b1 100644 --- a/src/stats/violin.jl +++ b/src/stats/violin.jl @@ -54,8 +54,8 @@ function plot!(plot::Violin) args = @extract plot (width, side, scale, color, show_median, npoints, boundary, bandwidth, weights, datalimits, max_density, dodge, n_dodge, gap, dodge_gap, orientation) signals = lift(plot, x, y, - args...) do x, y, width, vside, scale_type, color, show_median, n, bound, bw, w, limits, max_density, - dodge, n_dodge, gap, dodge_gap, orientation + args...) do x, y, width, vside, scale_type, color, show_median, n, bound, bw, w, limits, max_density, + dodge, n_dodge, gap, dodge_gap, orientation x̂, violinwidth = compute_x_and_width(x, width, gap, dodge, n_dodge, dodge_gap) # for horizontal violin just flip all componentes @@ -66,7 +66,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)) @@ -103,7 +103,7 @@ function plot!(plot::Violin) end vertices = Vector{Point2f}[] - lines = Pair{Point2f, Point2f}[] + lines = Pair{Point2f,Point2f}[] colors = RGBA{Float32}[] for spec in specs @@ -134,8 +134,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) @@ -151,7 +151,7 @@ function plot!(plot::Violin) poly!( plot, lift(s -> s.vertices, plot, signals); - color=lift(s -> s.colors, plot, signals), + color = lift(s -> s.colors, plot, signals), strokecolor = plot[:strokecolor], strokewidth = plot[:strokewidth], ) diff --git a/src/theming.jl b/src/theming.jl index 5eb76a75567..7abfd7d5b32 100644 --- a/src/theming.jl +++ b/src/theming.jl @@ -4,13 +4,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 ] return RGBAf.(colors, alpha) end @@ -87,9 +87,7 @@ const MAKIE_DEFAULT_THEME = Attributes( antialias = :best, visible = true, start_renderloop = false - ), - - GLMakie = Attributes( + ), GLMakie = Attributes( # Renderloop renderloop = automatic, pause_renderloop = false, @@ -120,9 +118,7 @@ const MAKIE_DEFAULT_THEME = Attributes( # maximum number of lights with shading = :verbose max_lights = 64, max_light_parameters = 5 * 64 - ), - - WGLMakie = Attributes( + ), WGLMakie = Attributes( framerate = 30.0, resize_to = nothing, # DEPRECATED in favor of resize_to @@ -130,9 +126,7 @@ const MAKIE_DEFAULT_THEME = Attributes( resize_to_body = nothing, px_per_unit = automatic, scalefactor = automatic - ), - - RPRMakie = Attributes( + ), RPRMakie = Attributes( iterations = 200, resource = automatic, plugin = automatic, @@ -193,7 +187,7 @@ current_default_theme() = CURRENT_DEFAULT_THEME Set the global default theme to `theme` and add / override any attributes given as keyword arguments. """ -function set_theme!(new_theme=Attributes(); kwargs...) +function set_theme!(new_theme = Attributes(); kwargs...) lock(THEME_LOCK) do empty!(CURRENT_DEFAULT_THEME) new_theme = merge_without_obs!(fast_deepcopy(new_theme), MAKIE_DEFAULT_THEME) @@ -233,12 +227,12 @@ function with_theme(f, theme = Theme(); kwargs...) end end -theme(::Nothing, key::Symbol; default=nothing) = theme(key; default) +theme(::Nothing, key::Symbol; default = nothing) = theme(key; default) theme(::Nothing) = CURRENT_DEFAULT_THEME -function theme(key::Symbol; default=nothing) +function theme(key::Symbol; default = nothing) if haskey(CURRENT_DEFAULT_THEME, key) val = to_value(CURRENT_DEFAULT_THEME[key]) - if val isa Union{NamedTuple, Attributes} + if val isa Union{NamedTuple,Attributes} return val else Observable{Any}(val) diff --git a/src/types.jl b/src/types.jl index 2d814a7e8ac..281b02d73ed 100644 --- a/src/types.jl +++ b/src/types.jl @@ -69,11 +69,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 @@ -119,14 +119,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[]), @@ -256,7 +252,7 @@ struct Camera """ steering_nodes::Vector{ObserverFunction} - calculated_values::Dict{Symbol, Observable} + calculated_values::Dict{Symbol,Observable} end """ @@ -283,38 +279,38 @@ struct Transformation <: Transformable end transform_func_o = convert(Observable{Any}, transform_func) return new(RefValue{Transformation}(), - translation_o, scale_o, rotation_o, model, parent_model, transform_func_o) + translation_o, scale_o, rotation_o, model, parent_model, transform_func_o) end end -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)) return Transformation(translation, - scale, - rotation, - transform_func) + scale, + rotation, + transform_func) end function Transformation(parent::Transformable; - scale=Vec3f(1), - translation=Vec3f(0), - rotation=Quaternionf(0, 0, 0, 1), - transform_func=nothing) + scale = Vec3f(1), + translation = Vec3f(0), + rotation = Quaternionf(0, 0, 0, 1), + transform_func = nothing) connect_func = isnothing(transform_func) trans = isnothing(transform_func) ? identity : transform_func trans = Transformation(translation, - scale, - rotation, - trans) - connect!(transformation(parent), trans; connect_func=connect_func) + scale, + rotation, + trans) + connect!(transformation(parent), trans; connect_func = connect_func) return trans end 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)) @@ -383,7 +379,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 @@ -404,9 +400,9 @@ 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}} -const LogFunctions = Union{typeof(log10), typeof(log2), typeof(log)} +const LogFunctions = Union{typeof(log10),typeof(log2),typeof(log)} """ ReversibleScale @@ -416,7 +412,7 @@ Custom scale struct, taking a forward and inverse arbitrary scale function. ## Fields $(TYPEDFIELDS) """ -struct ReversibleScale{F <: Function, I <: Function, T <: AbstractInterval} <: Function +struct ReversibleScale{F<:Function,I<:Function,T<:AbstractInterval} <: Function """ forward transformation (e.g. `log10`) """ @@ -434,7 +430,7 @@ struct ReversibleScale{F <: Function, I <: Function, T <: AbstractInterval} <: F """ interval::T name::Symbol - function ReversibleScale(forward, inverse = Automatic(); limits = (0f0, 10f0), interval = (-Inf32, Inf32), name=Symbol(forward)) + function ReversibleScale(forward, inverse = Automatic(); limits = (0f0, 10f0), interval = (-Inf32, Inf32), name = Symbol(forward)) inverse isa Automatic && (inverse = inverse_transform(forward)) isnothing(inverse) && throw(ArgumentError( "Cannot determine inverse transform: you can use `ReversibleScale($(forward), inverse($(forward)))` instead." diff --git a/src/units.jl b/src/units.jl index 7105410199e..7729971e53a 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 f5ccf832bc3..e6bd7996ea1 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) @@ -103,45 +103,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 8882f8f9995..e87ea351b92 100644 --- a/src/utilities/texture_atlas.jl +++ b/src/utilities/texture_atlas.jl @@ -3,7 +3,7 @@ const SERIALIZATION_FORMAT_VERSION = "v7" 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} @@ -47,10 +47,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[], @@ -139,7 +139,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) @@ -149,7 +149,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 @@ -166,18 +166,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 @@ -218,7 +218,7 @@ end function render_default_glyphs!(atlas) chars = ['a':'z'..., 'A':'Z'..., '0':'9'..., '.', '-', MINUS_SIGN] - fonts = map(x-> to_font(to_value(x)), values(MAKIE_DEFAULT_THEME.fonts)) + fonts = map(x -> to_font(to_value(x)), values(MAKIE_DEFAULT_THEME.fonts)) for font in fonts for c in chars insert_glyph!(atlas, c, font) @@ -232,8 +232,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 @@ -299,7 +299,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)) @@ -339,7 +339,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! @@ -351,10 +351,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 @@ -419,9 +419,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) @@ -436,7 +436,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 @@ -450,12 +450,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,) @@ -493,7 +493,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 @@ -538,11 +538,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 @@ -550,9 +550,9 @@ offset_marker(atlas, marker, font, markersize, markeroffset) = markeroffset function marker_attributes(atlas::TextureAtlas, marker, markersize, font, marker_offset, plot_object) atlas_obs = Observable(atlas) # for map to work - scale = map(rescale_marker, plot_object, atlas_obs, marker, font, markersize; ignore_equal_values=true) + scale = map(rescale_marker, plot_object, atlas_obs, marker, font, markersize; ignore_equal_values = true) quad_offset = map(offset_marker, plot_object, atlas_obs, marker, font, markersize, marker_offset; - ignore_equal_values=true) + ignore_equal_values = true) return scale, quad_offset end diff --git a/src/utilities/utilities.jl b/src/utilities/utilities.jl index 450b2125854..a7956a6cb45 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 @@ -61,8 +61,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 @@ -129,9 +129,9 @@ macro get_attribute(scene, args) end # a few shortcut functions to make attribute conversion easier -function converted_attribute(dict, key, default=nothing) +function converted_attribute(dict, key, default = nothing) if haskey(dict, key) - return lift(x-> convert_attribute(x, Key{key}()), dict[key]) + return lift(x -> convert_attribute(x, Key{key}()), dict[key]) else return default end @@ -172,7 +172,7 @@ attr_broadcast_length(x::ScalarOrVector) = x.sv isa Vector ? length(x.sv) : 1 attr_broadcast_getindex(x::NativeFont, i) = x attr_broadcast_getindex(x::VecTypes, i) = x # these are our rules, and for what we do, Vecs are usually scalars attr_broadcast_getindex(x::AbstractVector, i) = x[i] -attr_broadcast_getindex(x::AbstractArray{T, 0}, i) where T = x[1] +attr_broadcast_getindex(x::AbstractArray{T,0}, i) where T = x[1] attr_broadcast_getindex(x::AbstractPattern, i) = x attr_broadcast_getindex(x, i) = x attr_broadcast_getindex(x::Ref, i) = x[] # unwrap Refs just like in normal broadcasting, for protecting iterables @@ -239,7 +239,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] @@ -288,7 +288,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 # This function was copied from GR.jl, @@ -298,10 +298,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 @@ -327,7 +327,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 @@ -396,9 +396,9 @@ function surface2mesh(xs, ys, zs::AbstractMatrix, transform_func = identity, spa # and remove quads that contain a NaN coordinate to avoid drawing triangles faces = filter(f -> !any(i -> isnan(ps[i]), f), faces) # create the uv (texture) vectors - uv = map(x-> Vec2f(1f0 - x[2], 1f0 - x[1]), decompose_uv(rect)) + uv = map(x -> Vec2f(1f0 - x[2], 1f0 - x[1]), decompose_uv(rect)) # return a mesh with known uvs and normals. - return GeometryBasics.Mesh(GeometryBasics.meta(ps; uv=uv, normals = nan_aware_normals(ps, faces)), faces, ) + return GeometryBasics.Mesh(GeometryBasics.meta(ps; uv = uv, normals = nan_aware_normals(ps, faces)), faces,) end diff --git a/test/PolarAxis.jl b/test/PolarAxis.jl index 8029e1835f1..91e27198538 100644 --- a/test/PolarAxis.jl +++ b/test/PolarAxis.jl @@ -2,13 +2,13 @@ @testset "rtick rotations" begin f = Figure() angles = [ - 7pi/4+0.01, 0, pi/4-0.01, - pi/4+0.01, pi/2, 3pi/4-0.01, - 3pi/4+0.01, pi, 5pi/4-0.01, - 5pi/4+0.01, 3pi/2, 7pi/4-0.01, + 7pi / 4 + 0.01, 0, pi / 4 - 0.01, + pi / 4 + 0.01, pi / 2, 3pi / 4 - 0.01, + 3pi / 4 + 0.01, pi, 5pi / 4 - 0.01, + 5pi / 4 + 0.01, 3pi / 2, 7pi / 4 - 0.01, ] po = PolarAxis( - f[1, 1], thetalimits = (0, pi/4), rticklabelrotation = Makie.automatic, + f[1, 1], thetalimits = (0, pi / 4), rticklabelrotation = Makie.automatic, rticklabelpad = 10f0 ) rticklabelplot = po.overlay.plots[5].plots[1] @@ -20,18 +20,18 @@ for i in 1:4 align = (Vec2f(0.5, 1.0), Vec2f(0.0, 0.5), Vec2f(0.5, 0.0), Vec2f(1.0, 0.5))[i] for j in 1:3 - po.theta_0[] = angles[j + 3(i-1)] - s, c = sincos(angles[j + 3(i-1)] - pi/2) + po.theta_0[] = angles[j + 3(i - 1)] + s, c = sincos(angles[j + 3(i - 1)] - pi / 2) @test rticklabelplot.plots[1].offset[] ≈ 10f0 * Vec2f(c, s) @test rticklabelplot.align[] ≈ align - @test isapprox(mod(rticklabelplot.rotation[], -pi..pi), (-pi/4+0.01, 0, pi/4-0.01)[j], atol = 1e-3) + @test isapprox(mod(rticklabelplot.rotation[], -pi .. pi), (-pi / 4 + 0.01, 0, pi / 4 - 0.01)[j], atol = 1e-3) end end # value v = 2pi * rand() po.rticklabelrotation[] = v - s, c = sincos(po.theta_0[] - pi/2) + s, c = sincos(po.theta_0[] - pi / 2) @test rticklabelplot.plots[1].offset[] ≈ 10f0 * Vec2f(c, s) scale = 1 / max(abs(s), abs(c)) @test rticklabelplot.align[] ≈ Point2f(0.5 - 0.5scale * c, 0.5 - 0.5scale * s) @@ -47,13 +47,13 @@ po.rticklabelrotation[] = :radial @test rticklabelplot.plots[1].offset[] ≈ 10f0 * Vec2f(c, s) @test rticklabelplot.align[] ≈ Vec2f(0, 0.5) - @test rticklabelplot.rotation[] ≈ po.theta_0[] - pi/2 + @test rticklabelplot.rotation[] ≈ po.theta_0[] - pi / 2 # aligned po.rticklabelrotation[] = :aligned @test rticklabelplot.plots[1].offset[] ≈ 10f0 * Vec2f(c, s) @test rticklabelplot.align[] ≈ Vec2f(1, 0.5) - @test rticklabelplot.rotation[] ≈ po.theta_0[] - 3pi/2 + @test rticklabelplot.rotation[] ≈ po.theta_0[] - 3pi / 2 end @@ -97,20 +97,20 @@ scatter!(ax, Point2f(0.5pi, 1)) reset_limits!(ax) @test ax.target_rlims[] == (0.0, 10.0) - @test all(isapprox.(ax.target_thetalims[], (-0.025pi, 0.525pi), rtol=1e-6)) + @test all(isapprox.(ax.target_thetalims[], (-0.025pi, 0.525pi), rtol = 1e-6)) # derive both scatter!(ax, Point2f(pi, 2)) reset_limits!(ax) - @test all(isapprox.(ax.target_rlims[], (0.95, 2.05), rtol=1e-6)) - @test all(isapprox.(ax.target_thetalims[], (-0.05pi, 1.05pi), rtol=1e-6)) + @test all(isapprox.(ax.target_rlims[], (0.95, 2.05), rtol = 1e-6)) + @test all(isapprox.(ax.target_thetalims[], (-0.05pi, 1.05pi), rtol = 1e-6)) # set limits rlims!(ax, 0.0, 3.0) reset_limits!(ax) @test ax.rlimits[] == (0.0, 3.0) @test ax.target_rlims[] == (0.0, 3.0) - @test all(isapprox.(ax.target_thetalims[], (-0.05pi, 1.05pi), rtol=1e-6)) + @test all(isapprox.(ax.target_thetalims[], (-0.05pi, 1.05pi), rtol = 1e-6)) thetalims!(ax, 0.0, 2pi) reset_limits!(ax) @@ -122,7 +122,7 @@ # test tightlimits fig = Figure() ax = PolarAxis(fig[1, 1]) - surface!(ax, 0.5pi..pi, 2..5, rand(10, 10)) + surface!(ax, 0.5pi .. pi, 2 .. 5, rand(10, 10)) tightlimits!(ax) @test ax.rautolimitmargin[] == (0.0, 0.0) @@ -141,7 +141,7 @@ @test ax.rlimits[] == (nothing, nothing) @test ax.thetalimits[] == (nothing, nothing) @test ax.target_rlims[] == (2.0, 5.0) - @test all(isapprox.(ax.target_thetalims[], (0.5pi, 1.0pi), rtol=1e-6)) + @test all(isapprox.(ax.target_thetalims[], (0.5pi, 1.0pi), rtol = 1e-6)) end @testset "Radial Offset" begin @@ -149,4 +149,4 @@ ax = PolarAxis(fig[1, 1], radius_at_origin = -1.0, rlimits = (0, 10)) @test ax.scene.transformation.transform_func[].r0 == -1.0 end -end \ No newline at end of file +end diff --git a/test/barplot.jl b/test/barplot.jl index 2a1e6bf9a79..b491925e1fd 100644 --- a/test/barplot.jl +++ b/test/barplot.jl @@ -9,26 +9,26 @@ y_dir, flip = false, false @test Makie.calculate_bar_label_align(al, 0.0, y_dir, flip) ≈ Vec2f(0.0, 0.5) @test Makie.calculate_bar_label_align(al, π, y_dir, flip) ≈ Vec2f(1.0, 0.5) - @test Makie.calculate_bar_label_align(al, π/2, y_dir, flip) ≈ Vec2f(0.5, 1.0) - @test Makie.calculate_bar_label_align(al, -π/2, y_dir, flip) ≈ Vec2f(0.5, 0.0) + @test Makie.calculate_bar_label_align(al, π / 2, y_dir, flip) ≈ Vec2f(0.5, 1.0) + @test Makie.calculate_bar_label_align(al, -π / 2, y_dir, flip) ≈ Vec2f(0.5, 0.0) y_dir, flip = true, false @test Makie.calculate_bar_label_align(al, 0.0, y_dir, flip) ≈ Vec2f(0.5, 0.0) @test Makie.calculate_bar_label_align(al, π, y_dir, flip) ≈ Vec2f(0.5, 1.0) - @test Makie.calculate_bar_label_align(al, π/2, y_dir, flip) ≈ Vec2f(0.0, 0.5) - @test Makie.calculate_bar_label_align(al, -π/2, y_dir, flip) ≈ Vec2f(1.0, 0.5) + @test Makie.calculate_bar_label_align(al, π / 2, y_dir, flip) ≈ Vec2f(0.0, 0.5) + @test Makie.calculate_bar_label_align(al, -π / 2, y_dir, flip) ≈ Vec2f(1.0, 0.5) y_dir, flip = false, true @test Makie.calculate_bar_label_align(al, 0.0, y_dir, flip) ≈ Vec2f(1.0, 0.5) @test Makie.calculate_bar_label_align(al, π, y_dir, flip) ≈ Vec2f(0.0, 0.5) - @test Makie.calculate_bar_label_align(al, π/2, y_dir, flip) ≈ Vec2f(0.5, 0.0) - @test Makie.calculate_bar_label_align(al, -π/2, y_dir, flip) ≈ Vec2f(0.5, 1.0) + @test Makie.calculate_bar_label_align(al, π / 2, y_dir, flip) ≈ Vec2f(0.5, 0.0) + @test Makie.calculate_bar_label_align(al, -π / 2, y_dir, flip) ≈ Vec2f(0.5, 1.0) y_dir, flip = true, true @test Makie.calculate_bar_label_align(al, 0.0, y_dir, flip) ≈ Vec2f(0.5, 1.0) @test Makie.calculate_bar_label_align(al, π, y_dir, flip) ≈ Vec2f(0.5, 0.0) - @test Makie.calculate_bar_label_align(al, π/2, y_dir, flip) ≈ Vec2f(1.0, 0.5) - @test Makie.calculate_bar_label_align(al, -π/2, y_dir, flip) ≈ Vec2f(0.0, 0.5) + @test Makie.calculate_bar_label_align(al, π / 2, y_dir, flip) ≈ Vec2f(1.0, 0.5) + @test Makie.calculate_bar_label_align(al, -π / 2, y_dir, flip) ≈ Vec2f(0.0, 0.5) end @testset "manual" begin @@ -52,27 +52,27 @@ end @testset "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 = Makie.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 = Makie.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] @@ -123,7 +123,7 @@ y = [0.0, 1.0, -1.0, -1.0] from = [0.0, 0.0, 0.0, -1.0] to = [0.0, 1.0, -1.0, -2.0] - from_, to_ = Makie.stack_grouped_from_to(1:4, y, (; x=ones(4))) + from_, to_ = Makie.stack_grouped_from_to(1:4, y, (; x = ones(4))) @test from == from_ @test to == to_ end diff --git a/test/boundingboxes.jl b/test/boundingboxes.jl index 5008cf1fe5c..3286c7b1018 100644 --- a/test/boundingboxes.jl +++ b/test/boundingboxes.jl @@ -1,6 +1,6 @@ function Base.isapprox(r1::Rect{D}, r2::Rect{D}; kwargs...) where D return isapprox(minimum(r1), minimum(r2); kwargs...) && - isapprox(widths(r1), widths(r2); kwargs...) + isapprox(widths(r1), widths(r2); kwargs...) end @testset "data_limits(plot)" begin @@ -17,7 +17,7 @@ end @test data_limits(p) ≈ Rect3f(Point3f(0), Vec3f(1, 1, 0)) fig = Figure() - ax = Axis(fig[1, 1], yscale=log, xscale=log) + ax = Axis(fig[1, 1], yscale = log, xscale = log) scatter!(ax, [0.5, 1, 2], [0.5, 1, 2]) p1 = vlines!(ax, [0.5]) p2 = hlines!(ax, [0.5]) @@ -26,7 +26,8 @@ end Makie.reset_limits!(ax) lims = ax.finallimits[] - x, y = minimum(lims); w, h = widths(lims) + x, y = minimum(lims) + w, h = widths(lims) @test data_limits(p1) ≈ Rect3f(Point3f(0.5, y, 0), Vec3f(0, h, 0)) @test data_limits(p2) ≈ Rect3f(Point3f(x, 0.5, 0), Vec3f(w, 0, 0)) @@ -44,7 +45,7 @@ end @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(1.0, 1.0, 1.0) @test bb.widths ≈ Vec3f(9.0, 9.0, 99.0) @@ -59,7 +60,7 @@ end [Point3f(0) for _ in 1:3], marker = Rect3f(Point3f(-0.1, -0.1, -0.1), Vec3f(0.2, 0.2, 1.2)), markersize = Vec3f(1, 1, 2), - rotations = Makie.rotation_between.((Vec3f(0,0,1),), Vec3f[(1,0,0), (0,1,0), (0,0,1)]) + rotations = Makie.rotation_between.((Vec3f(0, 0, 1),), Vec3f[(1, 0, 0), (0, 1, 0), (0, 0, 1)]) ) bb = boundingbox(p) @test bb.origin ≈ Point3f(-0.2) diff --git a/test/conversions.jl b/test/conversions.jl index be31c61cc7c..890cdc6318b 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,29 +28,29 @@ 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] - 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] - 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 "GeometryBasics Lines & Polygons" begin @@ -114,20 +115,20 @@ end end @testset "functions" begin - x = -pi..pi + x = -pi .. pi (xy,) = convert_arguments(Lines, x, sin) @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) (xy,) = convert_arguments(Lines, x, sin) @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 end @@ -141,23 +142,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 @@ -210,15 +211,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 @@ -252,11 +253,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)]) @@ -265,32 +266,32 @@ 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 # Geometry Primitive - 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))] # Empty Polygon - f, ax, pl = poly(Polygon(Point2f[])); - pl[1] = Polygon(Point2f[(1,0), (1,1), (0,1)]); + f, ax, pl = poly(Polygon(Point2f[])) + pl[1] = Polygon(Point2f[(1, 0), (1, 1), (0, 1)]) @test pl.plots[1][1][] == GeometryBasics.triangle_mesh(pl[1][]) - f, ax, pl = poly(Polygon[]); - pl[1] = [Polygon(Point2f[(1,0), (1,1), (0,1)])]; + f, ax, pl = poly(Polygon[]) + pl[1] = [Polygon(Point2f[(1, 0), (1, 1), (0, 1)])] @test pl.plots[1][1][] == GeometryBasics.triangle_mesh.(pl[1][]) # PointBased inputs f, ax, pl = poly(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) @@ -323,16 +324,16 @@ end v1 = collect(1:10) v2 = collect(1:6) - i1 = 1..10 - i2 = 1..6 + i1 = 1 .. 10 + i2 = 1 .. 6 o3 = Float32.(m3) # Conversions @testset "ImageLike conversion" begin - @test convert_arguments(Image, m3) == (0f0..10f0, 0f0..6f0, o3) - @test convert_arguments(Image, v1, r2, m3) == (1f0..10f0, 1f0..6f0, o3) - @test convert_arguments(Image, i1, v2, m3) == (1f0..10f0, 1f0..6f0, o3) + @test convert_arguments(Image, m3) == (0f0 .. 10f0, 0f0 .. 6f0, o3) + @test convert_arguments(Image, v1, r2, m3) == (1f0 .. 10f0, 1f0 .. 6f0, o3) + @test convert_arguments(Image, i1, v2, m3) == (1f0 .. 10f0, 1f0 .. 6f0, o3) @test_throws ErrorException convert_arguments(Image, m1, m2, m3) @test_throws ErrorException convert_arguments(Heatmap, m1, m2) end @@ -342,17 +343,17 @@ end vo2 = Float32.(v2) mo1 = Float32.(m1) mo2 = Float32.(m2) - @test convert_arguments(Surface, m3) == (vo1, vo2, o3) - @test convert_arguments(Contour, i1, v2, m3) == (vo1, vo2, o3) + @test convert_arguments(Surface, m3) == (vo1, vo2, o3) + @test convert_arguments(Contour, i1, v2, m3) == (vo1, vo2, o3) @test convert_arguments(Contourf, v1, r2, m3) == (vo1, vo2, o3) - @test convert_arguments(Surface, m1, m2, m3) == (mo1, mo2, o3) - @test convert_arguments(Surface, m1, m2) == (mo1, mo2, zeros(Float32, size(o3))) + @test convert_arguments(Surface, m1, m2, m3) == (mo1, mo2, o3) + @test convert_arguments(Surface, m1, m2) == (mo1, mo2, zeros(Float32, size(o3))) end @testset "CellGrid conversion" begin o1 = Float32.(0.5:1:10.5) o2 = Float32.(0.5:1:6.5) - @test convert_arguments(Heatmap, m3) == (o1, o2, o3) + @test convert_arguments(Heatmap, m3) == (o1, o2, o3) @test convert_arguments(Heatmap, r1, i2, m3) == (o1, o2, o3) @test convert_arguments(Heatmap, v1, r2, m3) == (o1, o2, o3) @test convert_arguments(Heatmap, 0:10, v2, m3) == (collect(0f0:10f0), o2, o3) @@ -398,7 +399,7 @@ end @test convert_arguments(Voronoiplot, xs, ys, zs)[1] == Point3f.(xs, ys', zs)[:] # color sorting - zs = [exp(-(x-y)^2) for x in LinRange(-1, 1, 10), y in LinRange(-1, 1, 10)] + zs = [exp(-(x - y)^2) for x in LinRange(-1, 1, 10), y in LinRange(-1, 1, 10)] fig, ax, sc = voronoiplot(1:10, 1:10, zs, markersize = 10, strokewidth = 3) ps = [Point2f(x, y) for x in 1:10 for y in 1:10] vorn = Makie.DelTri.voronoi(Makie.DelTri.triangulate(ps)) @@ -441,6 +442,6 @@ end @test Makie.angle2align(angle) ≈ Vec2f(0.5c, 0.5s) ./ max(abs(s), abs(c)) .+ Vec2f(0.5) end # sanity checks - @test isapprox(Makie.angle2align(pi/4), Vec2f(1, 1), atol = 1e-12) - @test isapprox(Makie.angle2align(5pi/4), Vec2f(0, 0), atol = 1e-12) + @test isapprox(Makie.angle2align(pi / 4), Vec2f(1, 1), atol = 1e-12) + @test isapprox(Makie.angle2align(5pi / 4), Vec2f(0, 0), atol = 1e-12) end diff --git a/test/deprecated.jl b/test/deprecated.jl index 8c0ef0db74e..9c949d8404b 100644 --- a/test/deprecated.jl +++ b/test/deprecated.jl @@ -18,15 +18,15 @@ end # test that deprecated `resolution keyword still works but throws warning` logger = Test.TestLogger() Base.with_logger(logger) do - scene = Scene(; resolution=(999, 999), size=(123, 123)) + scene = Scene(; resolution = (999, 999), size = (123, 123)) @test scene.viewport[] == Rect2i((0, 0), (999, 999)) end @test occursin("The `resolution` keyword for `Scene`s and `Figure`s has been deprecated", - logger.logs[1].message) - scene = Scene(; size=(600, 450)) + logger.logs[1].message) + scene = Scene(; size = (600, 450)) msg = @depwarn_message scene.px_area @test occursin(".px_area` got renamed to `.viewport`, and means the area the scene maps to in device independent units", - msg) + msg) # @test_deprecated seems to be broken on 1.10?! msg = @depwarn_message pixelarea(scene) # only works with depwarn on @@ -47,9 +47,9 @@ end @test occursin("ContinuousSurface is deprecated", msg) end @testset "AbstractVector ImageLike" begin - msg = @depwarn_message image(1:10, 1..10, zeros(10, 10)) + msg = @depwarn_message image(1:10, 1 .. 10, zeros(10, 10)) @test occursin("Encountered an `AbstractVector` with value 1:10 on side x", msg) - msg = @depwarn_message image(1..10, 1:10, zeros(10, 10)) + msg = @depwarn_message image(1 .. 10, 1:10, zeros(10, 10)) @test occursin("Encountered an `AbstractVector` with value 1:10 on side y", msg) end end diff --git a/test/events.jl b/test/events.jl index 41b7a94d440..654bc991eaf 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(size=(640,480)) - tb = Textbox(f[1,1], placeholder="Copy/paste into me") + f = Figure(size = (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(size=(640,480)) - tb = Textbox(f[1,1], placeholder="Copy/paste into me") + f = Figure(size = (640, 480)) + tb = Textbox(f[1, 1], placeholder = "Copy/paste into me") e = events(f.scene) # Initial state @@ -196,108 +196,111 @@ 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(size=(800, 600)); + scene = Scene(size = (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.9491514) - @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(-2.8912058, -3.8524969, -1.9491514) + @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.9491514) - @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(-2.8912058, -3.8524969, -1.9491514) + @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) # Reset state so this is indepentent from the last checks - scene = Scene(size=(800, 600)); + scene = Scene(size = (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.mouseposition[] = (400, 250) e.mousebutton[] = MouseButtonEvent(Mouse.right, Mouse.press) e.mouseposition[] = (600, 250) - @test cc.lookat[] ≈ Vec3f(1.0146117, -1.0146117, 0.0) - @test cc.eyeposition[] ≈ Vec3f(4.0146117, 1.9853883, 3.0) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(1.0146117, -1.0146117, 0.0) + @test cc.eyeposition[] ≈ Vec3f(4.0146117, 1.9853883, 3.0) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) # 2) Outside scene, in drag e.mouseposition[] = (1000, 450) - @test cc.lookat[] ≈ Vec3f(3.6296215, -2.4580488, -1.1715729) - @test cc.eyeposition[] ≈ Vec3f(6.6296215, 0.5419513, 1.8284271) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(3.6296215, -2.4580488, -1.1715729) + @test cc.eyeposition[] ≈ Vec3f(6.6296215, 0.5419513, 1.8284271) + @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(3.6296215, -2.4580488, -1.1715729) - @test cc.eyeposition[] ≈ Vec3f(6.6296215, 0.5419513, 1.8284271) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(3.6296215, -2.4580488, -1.1715729) + @test cc.eyeposition[] ≈ Vec3f(6.6296215, 0.5419513, 1.8284271) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) # Reset state - scene = Scene(size=(800, 600)); + scene = Scene(size = (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) # Zoom e.mouseposition[] = (400, 250) # for debugging e.scroll[] = (0.0, 4.0) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ 0.6830134f0 * Vec3f(3) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ 0.6830134f0 * Vec3f(3) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) # should not work outside the scene e.mouseposition[] = (1000, 450) e.scroll[] = (0.0, 4.0) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ 0.6830134f0 * Vec3f(3) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ 0.6830134f0 * Vec3f(3) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) end @testset "mouse state machine" begin - scene = Scene(size=(800, 600)); + scene = Scene(size = (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) @@ -324,10 +327,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) @@ -339,10 +342,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) @@ -354,10 +357,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) @@ -371,16 +374,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/makielayout.jl b/test/makielayout.jl index 945dfdbbf02..001a06a2575 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 @@ -43,7 +43,7 @@ end cb = Colorbar(fig[1, 2], hm) @test hm.calculated_colors[].colorrange[] == Vec(-0.5, 0.5) - @test cb.limits[] == Vec(-.5, .5) + @test cb.limits[] == Vec(-0.5, 0.5) hm.colorrange = Float32.((-1, 1)) @test cb.limits[] == Vec(-1, 1) @@ -113,48 +113,48 @@ end @test ax.limits[] == (nothing, [5, 7]) @test ax.targetlimits[] == BBox(-5, 11, 5, 7) @test ax.finallimits[] == BBox(-5, 11, 5, 7) - @test_throws MethodError limits!(f[1,1], -1, 1, -1, 1) + @test_throws MethodError limits!(f[1, 1], -1, 1, -1, 1) end # issue 3240 @testset "Axis limits 4-tuple" begin fig = Figure() - ax = Axis(fig[1,1],limits=(0,600,0,15)) - xlims!(ax,100,400) - @test ax.limits[] == ((100,400),(0,15)) + ax = Axis(fig[1, 1], limits = (0, 600, 0, 15)) + xlims!(ax, 100, 400) + @test ax.limits[] == ((100, 400), (0, 15)) xlims!() - @test ax.limits[] == ((nothing,nothing),(0,15)) + @test ax.limits[] == ((nothing, nothing), (0, 15)) - ax = Axis(fig[1,1],limits=(0,600,0,15)) - ylims!(ax,1,13) - @test ax.limits[] == ((0,600),(1,13)) + ax = Axis(fig[1, 1], limits = (0, 600, 0, 15)) + ylims!(ax, 1, 13) + @test ax.limits[] == ((0, 600), (1, 13)) ylims!() - @test ax.limits[] == ((0,600),(nothing,nothing)) + @test ax.limits[] == ((0, 600), (nothing, nothing)) - ax = Axis(fig[1,1],limits=(0,600,0,15)) - limits!(ax,350,700,2,14) - @test ax.limits[] == ((350,700),(2,14)) + ax = Axis(fig[1, 1], limits = (0, 600, 0, 15)) + limits!(ax, 350, 700, 2, 14) + @test ax.limits[] == ((350, 700), (2, 14)) end @testset "Axis3 limits 6-tuple" begin fig = Figure() - ax = Axis3(fig[1,1],limits=(0,1,0,2,0,3)) - xlims!(ax,1,2) - @test ax.limits[] == ((1,2),(0,2),(0,3)) + ax = Axis3(fig[1, 1], limits = (0, 1, 0, 2, 0, 3)) + xlims!(ax, 1, 2) + @test ax.limits[] == ((1, 2), (0, 2), (0, 3)) xlims!() - @test ax.limits[] == ((nothing,nothing),(0,2),(0,3)) + @test ax.limits[] == ((nothing, nothing), (0, 2), (0, 3)) - ax = Axis3(fig[1,1],limits=(0,1,0,2,0,3)) - ylims!(ax,1,3) - @test ax.limits[] == ((0,1),(1,3),(0,3)) + ax = Axis3(fig[1, 1], limits = (0, 1, 0, 2, 0, 3)) + ylims!(ax, 1, 3) + @test ax.limits[] == ((0, 1), (1, 3), (0, 3)) ylims!() - @test ax.limits[] == ((0,1),(nothing,nothing),(0,3)) + @test ax.limits[] == ((0, 1), (nothing, nothing), (0, 3)) - ax = Axis3(fig[1,1],limits=(0,1,0,2,0,3)) - zlims!(ax,1,5) - @test ax.limits[] == ((0,1),(0,2),(1,5)) + ax = Axis3(fig[1, 1], limits = (0, 1, 0, 2, 0, 3)) + zlims!(ax, 1, 5) + @test ax.limits[] == ((0, 1), (0, 2), (1, 5)) zlims!() - @test ax.limits[] == ((0,1),(0,2),(nothing,nothing)) + @test ax.limits[] == ((0, 1), (0, 2), (nothing, nothing)) end @testset "Colorbar plot object kwarg clash" begin @@ -200,33 +200,33 @@ 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" end @testset "errors" begin f, ax, pl1 = scatter(rand(10)) - pl2 = scatter!(ax, rand(10); color=rand(RGBf, 10)) - pl3 = barplot!(ax, 1:3; colorrange=(0, 1)) + pl2 = scatter!(ax, rand(10); color = rand(RGBf, 10)) + pl3 = barplot!(ax, 1:3; colorrange = (0, 1)) @test_throws ErrorException Colorbar(f[1, 2], pl1) @test_throws ErrorException Colorbar(f[1, 2], pl2) @test_throws ErrorException Colorbar(f[1, 2], pl3) end @testset "Recipes" begin - f, ax, pl = barplot(1:3; color=1:3) + f, ax, pl = barplot(1:3; color = 1:3) cbar = Colorbar(f[1, 2], pl) @test cbar.limits[] == Vec(1.0, 3.0) - let data = fill(1.0, 2,2,2) + let data = fill(1.0, 2, 2, 2) data[1] = 3.0 f, ax, pl = volumeslices(1:2, 1:2, 1:2, data) - cbar = Colorbar(f[1,2], pl) + cbar = Colorbar(f[1, 2], pl) @test cbar.limits[] == Vec(1.0, 3.0) end end @@ -247,14 +247,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 @@ -268,18 +268,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 @@ -377,7 +377,7 @@ function dictdiff(before, after) d = Dict{String,Vector}() for key in keys(after) befset = Set(last.(before[key])) - v = filter(after[key]) do (prio,func) + v = filter(after[key]) do (prio, func) func ∉ befset end isempty(v) || (d[key] = v) @@ -386,7 +386,7 @@ function dictdiff(before, after) end function get_difference_dict(blockfunc) - s = Scene(camera = campixel!); + s = Scene(camera = campixel!) before = listener_dict(s) block = blockfunc(s) delete!(block) @@ -405,8 +405,8 @@ end SliderGrid(scene, (label = "Amplitude", range = 0:0.1:10, startvalue = 5), (label = "Frequency", range = 0:0.5:50, format = "{:.1f}Hz", startvalue = 10), - (label = "Phase", range = 0:0.01:2pi, - format = x -> string(round(x/pi, digits = 2), "π")) + (label = "Phase", range = 0:0.01:(2pi), + format = x -> string(round(x / pi, digits = 2), "π")) ) end @test isempty(d) @@ -414,10 +414,10 @@ end @testset "Legend" begin d = get_difference_dict() do scene Legend(scene, [ - MarkerElement(marker = :cross), - LineElement(), - PolyElement(), - ], ["Label 1", "Label 2", "Label 3"]) + MarkerElement(marker = :cross), + LineElement(), + PolyElement(), + ], ["Label 1", "Label 2", "Label 3"]) end @test isempty(d) end @@ -425,10 +425,10 @@ end @testset "Legend with rich text" begin fig = Figure() - ax = Axis(fig[1,1]) - l1 = lines!( 0..2π , sin ) + ax = Axis(fig[1, 1]) + l1 = lines!(0 .. 2π, sin) @test_nowarn Legend( - fig[1,2], + fig[1, 2], [l1], [rich("some", subscript("entry"))], rich("title", color = :red, font = :bold_italic)) @@ -453,7 +453,7 @@ end # end @testset "Colorscales" begin - x = 10.0.^(1:0.1:4) + x = 10.0 .^ (1:0.1:4) y = 1.0:0.1:5.0 z = broadcast((x, y) -> x, x, y') diff --git a/test/pipeline.jl b/test/pipeline.jl index 6f18bc98729..7218d5325dd 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 @@ -39,18 +39,18 @@ end @testset "Figure / Axis / Gridposition creation test" begin @testset "proper errors for wrongly used (non) mutating plot functions" begin f = Figure() - x = range(0, 10, length=100) + x = range(0, 10, length = 100) @test_throws ErrorException scatter!(f[1, 1], x, sin) @test_throws ErrorException scatter!(f[1, 2][1, 1], x, sin) @test_throws ErrorException scatter!(f[1, 2][1, 2], x, sin) - @test_throws ErrorException meshscatter!(f[2, 1], x, sin; axis=(type=Axis3,)) - @test_throws ErrorException meshscatter!(f[2, 2][1, 1], x, sin; axis=(type=Axis3,)) - @test_throws ErrorException meshscatter!(f[2, 2][1, 2], x, sin; axis=(type=Axis3,)) + @test_throws ErrorException meshscatter!(f[2, 1], x, sin; axis = (type = Axis3,)) + @test_throws ErrorException meshscatter!(f[2, 2][1, 1], x, sin; axis = (type = Axis3,)) + @test_throws ErrorException meshscatter!(f[2, 2][1, 2], x, sin; axis = (type = Axis3,)) - @test_throws ErrorException meshscatter!(f[3, 1], rand(Point3f, 10); axis=(type=LScene,)) - @test_throws ErrorException meshscatter!(f[3, 2][1, 1], rand(Point3f, 10); axis=(type=LScene,)) - @test_throws ErrorException meshscatter!(f[3, 2][1, 2], rand(Point3f, 10); axis=(type=LScene,)) + @test_throws ErrorException meshscatter!(f[3, 1], rand(Point3f, 10); axis = (type = LScene,)) + @test_throws ErrorException meshscatter!(f[3, 2][1, 1], rand(Point3f, 10); axis = (type = LScene,)) + @test_throws ErrorException meshscatter!(f[3, 2][1, 2], rand(Point3f, 10); axis = (type = LScene,)) sub = f[4, :] f = Figure() @@ -63,7 +63,7 @@ end @testset "creating plot object for different (non) mutating plotting functions into figure" begin f = Figure() - x = range(0, 10; length=100) + x = range(0, 10; length = 100) ax, pl = scatter(f[1, 1], x, sin) @test ax isa Axis @test pl isa AbstractPlot @@ -76,24 +76,24 @@ end @test ax isa Axis @test pl isa AbstractPlot - ax, pl = meshscatter(f[2, 1], x, sin; axis=(type=Axis3,)) + ax, pl = meshscatter(f[2, 1], x, sin; axis = (type = Axis3,)) @test ax isa Axis3 @test pl isa AbstractPlot - ax, pl = meshscatter(f[2, 2][1, 1], x, sin; axis=(type=Axis3,)) + ax, pl = meshscatter(f[2, 2][1, 1], x, sin; axis = (type = Axis3,)) @test ax isa Axis3 @test pl isa AbstractPlot - ax, pl = meshscatter(f[2, 2][1, 2], x, sin; axis=(type=Axis3,)) + ax, pl = meshscatter(f[2, 2][1, 2], x, sin; axis = (type = Axis3,)) @test ax isa Axis3 @test pl isa AbstractPlot - ax, pl = meshscatter(f[3, 1], rand(Point3f, 10); axis=(type=LScene,)) + ax, pl = meshscatter(f[3, 1], rand(Point3f, 10); axis = (type = LScene,)) @test ax isa LScene @test pl isa AbstractPlot - ax, pl = meshscatter(f[3, 2][1, 1], rand(Point3f, 10); axis=(type=LScene,)) + ax, pl = meshscatter(f[3, 2][1, 1], rand(Point3f, 10); axis = (type = LScene,)) @test ax isa LScene @test pl isa AbstractPlot - ax, pl = meshscatter(f[3, 2][1, 2], rand(Point3f, 10); axis=(type=LScene,)) + ax, pl = meshscatter(f[3, 2][1, 2], rand(Point3f, 10); axis = (type = LScene,)) @test ax isa LScene @test pl isa AbstractPlot @@ -113,10 +113,10 @@ end @testset "Cycled" begin # Test for https://github.com/MakieOrg/Makie.jl/issues/3266 - f, ax, pl = lines(1:4; color=Cycled(2)) + f, ax, pl = lines(1:4; color = Cycled(2)) cpalette = ax.scene.theme.palette[:color][] @test pl.calculated_colors[] == cpalette[2] - pl2 = lines!(ax, 1:4; color=Cycled(1)) + pl2 = lines!(ax, 1:4; color = Cycled(1)) @test pl2.calculated_colors[] == cpalette[1] end @@ -134,7 +134,7 @@ end @testset "plot defaults" begin plots = test_default([10, 15, 20]) - @test all(x-> x isa Scatter, plots) + @test all(x -> x isa Scatter, plots) plots = test_default(rand(4, 4)) @test all(x -> x isa Heatmap, plots) diff --git a/test/primitives.jl b/test/primitives.jl index ad5a74ad1e6..1ccb1ec3ee9 100644 --- a/test/primitives.jl +++ b/test/primitives.jl @@ -14,8 +14,8 @@ end # https://github.com/MakieOrg/Makie.jl/issues/3273 directions = decompose(Point2f, Circle(Point2f(0), 1)) points = decompose(Point2f, Circle(Point2f(0), 0.5)) - color = range(0, 1, length=length(directions)) - fig, ax, pl = arrows(points, directions; color=color) + color = range(0, 1, length = length(directions)) + fig, ax, pl = arrows(points, directions; color = color) cbar = Colorbar(fig[1, 2], pl) @test cbar.limits[] == Vec2f(0, 1) pl.colorrange = (0.5, 0.6) @@ -57,7 +57,7 @@ end @testset "scalar color for scatterlines" begin colorrange = (1, 5) colormap = :Blues - f, ax, sl = scatterlines(1:10,1:10,color=3,colormap=colormap,colorrange=colorrange) + f, ax, sl = scatterlines(1:10, 1:10, color = 3, colormap = colormap, colorrange = colorrange) l = sl.plots[1]::Lines sc = sl.plots[2]::Scatter @test l.color[] == 3 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/ray_casting.jl b/test/ray_casting.jl index 73b5beaa20a..1a1ad428e11 100644 --- a/test/ray_casting.jl +++ b/test/ray_casting.jl @@ -29,7 +29,7 @@ # Generate rate that passes through transformed point transformed = Point3f(model * Point4f(point..., 1)) - direction = (1 + 10*rand()) * rand(Vec3f) + direction = (1 + 10 * rand()) * rand(Vec3f) ray = Makie.Ray(transformed + direction, normalize(direction)) @test Makie.is_point_on_ray(transformed, ray) @@ -94,14 +94,14 @@ # Heatmap (2D) & Image (3D) scene = Scene(size = (400, 400)) - p = heatmap!(scene, 0..1, -1..1, rand(10, 10)) + p = heatmap!(scene, 0 .. 1, -1 .. 1, rand(10, 10)) cam2d!(scene) ray = Makie.Ray(scene, (228.0, 91.0)) pos = Makie.position_on_plot(p, 0, ray) @test pos ≈ Point3f(0.13999999, -0.54499996, 0.0) scene = Scene(size = (400, 400)) - p = image!(scene, -1..1, -1..1, rand(10, 10)) + p = image!(scene, -1 .. 1, -1 .. 1, rand(10, 10)) cam3d!(scene) ray = Makie.Ray(scene, (309.0, 197.0)) pos = Makie.position_on_plot(p, 3, ray) @@ -118,7 +118,7 @@ # Surface (3D) scene = Scene(size = (400, 400)) - p = surface!(scene, -2..2, -2..2, [sin(x) * cos(y) for x in -10:10, y in -10:10]) + p = surface!(scene, -2 .. 2, -2 .. 2, [sin(x) * cos(y) for x in -10:10, y in -10:10]) cam3d!(scene) ray = Makie.Ray(scene, (52.0, 238.0)) pos = Makie.position_on_plot(p, 57, ray) diff --git a/test/record.jl b/test/record.jl index 9cda4e3dd03..84697b8de0f 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"], ), (:loop, 0, ["mkv", "webm", "mp4"], ["gif"]), ] diff --git a/test/runtests.jl b/test/runtests.jl index 25a86f9f68a..780206df484 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("deprecated.jl") diff --git a/test/scenes.jl b/test/scenes.jl index a2c26e96b92..e9abf4c505d 100644 --- a/test/scenes.jl +++ b/test/scenes.jl @@ -4,13 +4,13 @@ @testset "getproperty(scene, :$field)" for field in fieldnames(Scene) @test getproperty(scene, field) !== missing # well, just don't error end - @test theme(nothing, :nonexistant, default=1) == 1 - @test theme(scene, :nonexistant, default=1) == 1 + @test theme(nothing, :nonexistant, default = 1) == 1 + @test theme(scene, :nonexistant, default = 1) == 1 end @testset "Lighting" begin @testset "Shading default" begin - plot = (attributes = Attributes(), ) # simplified "plot" + plot = (attributes = Attributes(),) # simplified "plot" # Based on number of lights lights = Makie.AbstractLight[] @@ -43,7 +43,7 @@ end @test to_value(plot.attributes[:shading]) === MultiLightShading plot.attributes[:shading] = Observable(Makie.automatic) - lights = [EnvironmentLight(1.0, rand(2,2))] + lights = [EnvironmentLight(1.0, rand(2, 2))] Makie.default_shading!(plot, lights) @test to_value(plot.attributes[:shading]) === NoShading # only affects RPRMakie so skipped here diff --git a/test/specapi.jl b/test/specapi.jl index a31b45373c0..91bc6d607c5 100644 --- a/test/specapi.jl +++ b/test/specapi.jl @@ -3,21 +3,21 @@ import Makie.SpecApi as S @testset "diffing" begin @testset "update_plot!" begin obs = Observable[] - oldspec = S.Scatter(1:4; cycle=[]) - newspec = S.Scatter(1:4; cycle=[]) + oldspec = S.Scatter(1:4; cycle = []) + newspec = S.Scatter(1:4; cycle = []) p = Makie.to_plot_object(newspec) s = Scene() plot!(s, p) Makie.update_plot!(obs, p, oldspec, newspec) @test isempty(obs) - newspec = S.Scatter(1:4; color=:red) + newspec = S.Scatter(1:4; color = :red) Makie.update_plot!(obs, p, oldspec, newspec) oldspec = newspec @test length(obs) == 1 @test obs[1] === p.color - newspec = S.Scatter(1:4; color=:green, cycle=[]) + newspec = S.Scatter(1:4; color = :green, cycle = []) empty!(obs) Makie.update_plot!(obs, p, oldspec, newspec) oldspec = newspec @@ -25,15 +25,15 @@ import Makie.SpecApi as S @test obs[1] === p.color @test obs[1].val == to_color(:green) - newspec = S.Scatter(1:5; color=:green, cycle=[]) + newspec = S.Scatter(1:5; color = :green, cycle = []) empty!(obs) Makie.update_plot!(obs, p, oldspec, newspec) oldspec = newspec @test length(obs) == 1 @test obs[1] === p.args[1] - oldspec = S.Scatter(1:5; color=:green, marker=:rect, cycle=[]) - newspec = S.Scatter(1:4; color=:red, marker=:circle, cycle=[]) + oldspec = S.Scatter(1:5; color = :green, marker = :rect, cycle = []) + newspec = S.Scatter(1:4; color = :red, marker = :circle, cycle = []) empty!(obs) p = Makie.to_plot_object(oldspec) s = Scene() @@ -46,8 +46,8 @@ import Makie.SpecApi as S end @testset "diff_plotlist!" begin - scene = Scene(); - plotspecs = [S.Scatter(1:4; color=:red), S.Scatter(1:4; color=:red)] + scene = Scene() + plotspecs = [S.Scatter(1:4; color = :red), S.Scatter(1:4; color = :red)] reusable_plots = IdDict{PlotSpec,Plot}() obs_to_notify = Observable[] new_plots = Makie.diff_plotlist!(scene, plotspecs, obs_to_notify, reusable_plots) @@ -61,7 +61,7 @@ import Makie.SpecApi as S @test Set(scene.plots) == Set(values(new_plots2)) @test isempty(obs_to_notify) - plotspecs = [S.Scatter(1:4; color=:yellow), S.Scatter(1:4; color=:green)] + plotspecs = [S.Scatter(1:4; color = :yellow), S.Scatter(1:4; color = :green)] new_plots3 = Makie.diff_plotlist!(scene, plotspecs, obs_to_notify, new_plots2) @test isempty(new_plots) # they got all used up @@ -75,7 +75,7 @@ end struct TestPlot end function Makie.convert_arguments(P::Type{<:Plot}, ::TestPlot) - return PlotSpec(P, Point2f.(1:5, 1:5); color=1:5, cycle=[]) + return PlotSpec(P, Point2f.(1:5, 1:5); color = 1:5, cycle = []) end @testset "PlotSpec with attributes in convert_arguments" begin diff --git a/test/statistical_tests.jl b/test/statistical_tests.jl index 9e7e15f5ed4..032da728347 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/text.jl b/test/text.jl index 4881afa3a12..8146e4ae2b3 100644 --- a/test/text.jl +++ b/test/text.jl @@ -62,9 +62,9 @@ end @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) @@ -104,7 +104,7 @@ end @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 ff3366a9737..55d5c1a70c3 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 "Polar Transform" begin @@ -95,40 +95,40 @@ end @test tf.direction == 1 @test tf.r0 == 0.0 - input = Point2f.([0, pi/3, pi/2, pi, 2pi, 3pi], 1:6) + input = Point2f.([0, pi / 3, pi / 2, pi, 2pi, 3pi], 1:6) output = [r * Point2f(cos(phi), sin(phi)) for (phi, r) in input] - inv = Point2f.(mod.([0, pi/3, pi/2, pi, 2pi, 3pi], (0..2pi,)), 1:6) + inv = Point2f.(mod.([0, pi / 3, pi / 2, pi, 2pi, 3pi], (0 .. 2pi,)), 1:6) @test apply_transform(tf, input) ≈ output @test apply_transform(Makie.inverse_transform(tf), output) ≈ inv - tf = Makie.Polar(pi/2, 1, 0, false) - input = Point2f.(1:6, [0, pi/3, pi/2, pi, 2pi, 3pi]) - output = [r * Point2f(cos(phi+pi/2), sin(phi+pi/2)) for (r, phi) in input] - inv = Point2f.(1:6, mod.([0, pi/3, pi/2, pi, 2pi, 3pi], (0..2pi,))) + tf = Makie.Polar(pi / 2, 1, 0, false) + input = Point2f.(1:6, [0, pi / 3, pi / 2, pi, 2pi, 3pi]) + output = [r * Point2f(cos(phi + pi / 2), sin(phi + pi / 2)) for (r, phi) in input] + inv = Point2f.(1:6, mod.([0, pi / 3, pi / 2, pi, 2pi, 3pi], (0 .. 2pi,))) @test apply_transform(tf, input) ≈ output @test apply_transform(Makie.inverse_transform(tf), output) ≈ inv - tf = Makie.Polar(pi/2, -1, 0, false) - output = [r * Point2f(cos(-phi-pi/2), sin(-phi-pi/2)) for (r, phi) in input] + tf = Makie.Polar(pi / 2, -1, 0, false) + output = [r * Point2f(cos(-phi - pi / 2), sin(-phi - pi / 2)) for (r, phi) in input] @test apply_transform(tf, input) ≈ output @test apply_transform(Makie.inverse_transform(tf), output) ≈ inv - tf = Makie.Polar(pi/2, -1, 0.5, false) - output = [(r - 0.5) * Point2f(cos(-phi-pi/2), sin(-phi-pi/2)) for (r, phi) in input] + tf = Makie.Polar(pi / 2, -1, 0.5, false) + output = [(r - 0.5) * Point2f(cos(-phi - pi / 2), sin(-phi - pi / 2)) for (r, phi) in input] @test apply_transform(tf, input) ≈ output @test apply_transform(Makie.inverse_transform(tf), output) ≈ inv tf = Makie.Polar(0, 1, 0, true) - input = Point2f.([0, pi/3, pi/2, pi, 2pi, 3pi], 1:6) + input = Point2f.([0, pi / 3, pi / 2, pi, 2pi, 3pi], 1:6) output = [r * Point2f(cos(phi), sin(phi)) for (phi, r) in input] - inv = Point2f.(mod.([0, pi/3, pi/2, pi, 2pi, 3pi], (0..2pi,)), 1:6) + inv = Point2f.(mod.([0, pi / 3, pi / 2, pi, 2pi, 3pi], (0 .. 2pi,)), 1:6) @test apply_transform(tf, input) ≈ output @test apply_transform(Makie.inverse_transform(tf), output) ≈ inv tf = Makie.Polar(0, 1, 0, true, false) - input = Point2f.([0, pi/3, pi/2, pi, 2pi, 3pi], -6:-1) + input = Point2f.([0, pi / 3, pi / 2, pi, 2pi, 3pi], -6:-1) output = [r * Point2f(cos(phi), sin(phi)) for (phi, r) in input] - inv = Point2f.(mod.([0, pi/3, pi/2, pi, 2pi, 3pi] .+ pi, (0..2pi,)), 6:-1:1) + inv = Point2f.(mod.([0, pi / 3, pi / 2, pi, 2pi, 3pi] .+ pi, (0 .. 2pi,)), 6:-1:1) @test apply_transform(tf, input) ≈ output @test apply_transform(Makie.inverse_transform(tf), output) ≈ inv end @@ -151,14 +151,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 @@ -171,10 +171,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 diff --git a/test/zoom_pan.jl b/test/zoom_pan.jl index 5fd708e80df..a8e186b2bf9 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 diff --git a/tooling/bump_versions.jl b/tooling/bump_versions.jl index d1d458649fe..312cf6950cc 100644 --- a/tooling/bump_versions.jl +++ b/tooling/bump_versions.jl @@ -4,9 +4,9 @@ using Pkg dictmap(f, d) = Dict(key => f(key, value) for (key, value) in d) -bump_patch(v::VersionNumber) = VersionNumber(v.major, v.minor, v.patch+1) -bump_minor(v::VersionNumber) = VersionNumber(v.major, v.minor+1, 0) -bump_major(v::VersionNumber) = VersionNumber(v.major+1, 0, 0) +bump_patch(v::VersionNumber) = VersionNumber(v.major, v.minor, v.patch + 1) +bump_minor(v::VersionNumber) = VersionNumber(v.major, v.minor + 1, 0) +bump_major(v::VersionNumber) = VersionNumber(v.major + 1, 0, 0) function bump_versions() @@ -109,4 +109,4 @@ function bump_versions() println("Done") end -bump_versions() \ No newline at end of file +bump_versions()