From 440bcff5256cc556eb5981704994824737d989d3 Mon Sep 17 00:00:00 2001 From: t-bltg Date: Sat, 24 Dec 2022 22:19:31 +0100 Subject: [PATCH] intial format --- CairoMakie/src/CairoMakie.jl | 6 +- CairoMakie/src/cairo-extension.jl | 30 +- CairoMakie/src/display.jl | 10 +- CairoMakie/src/infrastructure.jl | 8 +- CairoMakie/src/overrides.jl | 27 +- CairoMakie/src/primitives.jl | 203 +++++----- CairoMakie/src/screen.jl | 30 +- CairoMakie/src/utils.jl | 65 ++- CairoMakie/test/rasterization_tests.jl | 7 +- CairoMakie/test/runtests.jl | 36 +- CairoMakie/test/svg_tests.jl | 9 +- GLMakie/experiments/cuda_interop.jl | 4 +- GLMakie/experiments/shaderabstr.jl | 102 ++--- GLMakie/src/GLAbstraction/AbstractGPUArray.jl | 81 ++-- GLMakie/src/GLAbstraction/GLBuffer.jl | 116 +++--- .../src/GLAbstraction/GLExtendedFunctions.jl | 36 +- GLMakie/src/GLAbstraction/GLInfo.jl | 14 +- GLMakie/src/GLAbstraction/GLRender.jl | 22 +- GLMakie/src/GLAbstraction/GLRenderObject.jl | 16 +- GLMakie/src/GLAbstraction/GLShader.jl | 44 +-- GLMakie/src/GLAbstraction/GLTexture.jl | 163 ++++---- GLMakie/src/GLAbstraction/GLTypes.jl | 101 +++-- GLMakie/src/GLAbstraction/GLUniforms.jl | 120 +++--- GLMakie/src/GLAbstraction/GLUtils.jl | 10 +- GLMakie/src/GLMakie.jl | 6 +- GLMakie/src/display.jl | 2 +- GLMakie/src/drawing_primitives.jl | 136 +++---- GLMakie/src/events.jl | 80 ++-- GLMakie/src/gl_backend.jl | 18 +- GLMakie/src/glshaders/image_like.jl | 28 +- GLMakie/src/glshaders/lines.jl | 74 ++-- GLMakie/src/glshaders/mesh.jl | 13 +- GLMakie/src/glshaders/particles.jl | 98 +++-- GLMakie/src/glshaders/surface.jl | 101 +++-- GLMakie/src/glshaders/visualize_interface.jl | 72 ++-- GLMakie/src/glwindow.jl | 30 +- GLMakie/src/picking.jl | 17 +- GLMakie/src/postprocessing.jl | 8 +- GLMakie/src/rendering.jl | 2 +- GLMakie/src/screen.jl | 179 ++++----- GLMakie/test/glmakie_refimages.jl | 51 ++- GLMakie/test/runtests.jl | 2 +- GLMakie/test/unit_tests.jl | 68 ++-- MakieCore/src/attributes.jl | 35 +- MakieCore/src/basic_plots.jl | 20 +- MakieCore/src/conversion.jl | 10 +- MakieCore/src/recipes.jl | 42 +- MakieCore/src/types.jl | 6 +- MakieCore/test/runtests.jl | 8 +- MakieRecipes/src/bezier.jl | 8 +- MakieRecipes/src/pipeline_integration.jl | 52 ++- RPRMakie/examples/bars.jl | 12 +- RPRMakie/examples/eart_topographie_sphere.jl | 16 +- RPRMakie/examples/earth_topography.jl | 12 +- RPRMakie/examples/lego.jl | 36 +- RPRMakie/examples/lines.jl | 8 +- RPRMakie/examples/makie_example.jl | 6 +- RPRMakie/examples/materials.jl | 20 +- RPRMakie/examples/opengl_interop.jl | 56 +-- RPRMakie/examples/sea_cables.jl | 14 +- RPRMakie/src/RPRMakie.jl | 16 +- RPRMakie/src/lines.jl | 8 +- RPRMakie/src/meshes.jl | 26 +- RPRMakie/src/scene.jl | 29 +- RPRMakie/test/lines.jl | 286 +++++++------- RPRMakie/test/runtests.jl | 6 +- ReferenceTests/src/database.jl | 18 +- ReferenceTests/src/image_download.jl | 4 +- ReferenceTests/src/runtests.jl | 38 +- ReferenceTests/src/stable_rng.jl | 8 +- ReferenceTests/src/tests/attributes.jl | 22 +- ReferenceTests/src/tests/examples2d.jl | 280 ++++++------- ReferenceTests/src/tests/examples3d.jl | 250 ++++++------ .../src/tests/figures_and_makielayout.jl | 22 +- ReferenceTests/src/tests/primitives.jl | 88 ++--- ReferenceTests/src/tests/recipes.jl | 29 +- ReferenceTests/src/tests/short_tests.jl | 144 +++---- ReferenceTests/src/tests/text.jl | 74 ++-- ReferenceTests/src/tests/updating.jl | 30 +- ReferenceTests/src/visual-regression.jl | 44 +-- WGLMakie/src/WGLMakie.jl | 2 +- WGLMakie/src/display.jl | 18 +- WGLMakie/src/imagelike.jl | 86 ++-- WGLMakie/src/lines.jl | 26 +- WGLMakie/src/meshes.jl | 25 +- WGLMakie/src/particles.jl | 38 +- WGLMakie/src/precompiles.jl | 2 +- WGLMakie/src/serialization.jl | 140 +++---- WGLMakie/src/three_plot.jl | 23 +- WGLMakie/test/offline_export.jl | 6 +- src/Makie.jl | 24 +- src/basic_recipes/ablines.jl | 8 +- src/basic_recipes/annotations.jl | 12 +- src/basic_recipes/arc.jl | 4 +- src/basic_recipes/arrows.jl | 58 ++- src/basic_recipes/axis.jl | 135 +++---- src/basic_recipes/band.jl | 22 +- src/basic_recipes/barplot.jl | 45 +-- src/basic_recipes/buffers.jl | 62 ++- src/basic_recipes/contourf.jl | 12 +- src/basic_recipes/contours.jl | 45 +-- src/basic_recipes/convenience_functions.jl | 20 +- src/basic_recipes/error_and_rangebars.jl | 16 +- src/basic_recipes/hvlines.jl | 4 +- src/basic_recipes/hvspan.jl | 8 +- src/basic_recipes/pie.jl | 8 +- src/basic_recipes/poly.jl | 37 +- src/basic_recipes/raincloud.jl | 86 ++-- src/basic_recipes/series.jl | 60 ++- src/basic_recipes/spy.jl | 14 +- src/basic_recipes/stairs.jl | 11 +- src/basic_recipes/streamplot.jl | 31 +- src/basic_recipes/text.jl | 94 ++--- src/basic_recipes/tooltip.jl | 108 ++--- src/basic_recipes/tricontourf.jl | 36 +- src/basic_recipes/volumeslices.jl | 4 +- src/basic_recipes/waterfall.jl | 54 +-- src/basic_recipes/wireframe.jl | 8 +- src/bezier.jl | 164 ++++---- src/camera/camera.jl | 32 +- src/camera/camera2d.jl | 27 +- src/camera/camera3d.jl | 136 ++++--- src/camera/old_camera3d.jl | 52 +-- src/camera/projection_math.jl | 168 ++++---- src/colorsampler.jl | 32 +- src/conversions.jl | 325 ++++++--------- src/deprecated.jl | 12 +- src/display.jl | 80 ++-- src/documentation/docstringextension.jl | 4 +- src/documentation/documentation.jl | 21 +- src/event-recorder.jl | 6 +- src/ffmpeg-util.jl | 34 +- src/figureplotting.jl | 12 +- src/figures.jl | 10 +- src/interaction/events.jl | 54 +-- src/interaction/inspector.jl | 163 ++++---- src/interaction/interactive_api.jl | 60 ++- src/interaction/iodevices.jl | 374 +++++++++--------- src/interaction/liftmacro.jl | 4 +- src/interaction/observables.jl | 4 +- src/interfaces.jl | 115 +++--- src/jl_rasterizer/bmp.jl | 4 +- src/jl_rasterizer/main.jl | 127 +++--- src/layouting/boundingbox.jl | 27 +- src/layouting/data_limits.jl | 45 +-- src/layouting/layouting.jl | 44 +-- src/layouting/transformation.jl | 108 ++--- src/makielayout/blocks.jl | 90 ++--- src/makielayout/blocks/axis.jl | 168 ++++---- src/makielayout/blocks/axis3d.jl | 100 +++-- src/makielayout/blocks/button.jl | 6 +- src/makielayout/blocks/colorbar.jl | 60 ++- src/makielayout/blocks/intervalslider.jl | 8 +- src/makielayout/blocks/label.jl | 4 +- src/makielayout/blocks/legend.jl | 130 +++--- src/makielayout/blocks/menu.jl | 134 +++---- src/makielayout/blocks/scene.jl | 12 +- src/makielayout/blocks/slider.jl | 22 +- src/makielayout/blocks/slidergrid.jl | 58 ++- src/makielayout/blocks/textbox.jl | 37 +- src/makielayout/blocks/toggle.jl | 2 +- src/makielayout/defaultattributes.jl | 91 ++--- src/makielayout/geometrybasics_extension.jl | 24 +- src/makielayout/helpers.jl | 60 ++- src/makielayout/interactions.jl | 18 +- src/makielayout/lineaxis.jl | 161 ++++---- src/makielayout/mousestatemachine.jl | 67 ++-- src/makielayout/roundedrect.jl | 10 +- src/makielayout/ticklocators/linear.jl | 14 +- src/makielayout/ticklocators/wilkinson.jl | 14 +- src/makielayout/types.jl | 167 ++++---- src/patterns.jl | 59 ++- src/recording.jl | 21 +- src/scenes.jl | 128 +++--- src/shorthands.jl | 29 +- src/stats/boxplot.jl | 4 +- src/stats/conversions.jl | 8 +- src/stats/crossbar.jl | 68 ++-- src/stats/density.jl | 2 +- src/stats/distributions.jl | 12 +- src/stats/ecdf.jl | 18 +- src/stats/hexbin.jl | 69 ++-- src/stats/hist.jl | 17 +- src/stats/violin.jl | 10 +- src/themes/theme_black.jl | 96 +++-- src/themes/theme_dark.jl | 80 ++-- src/themes/theme_ggplot2.jl | 112 +++--- src/themes/theme_light.jl | 76 ++-- src/themes/theme_minimal.jl | 102 +++-- src/theming.jl | 49 +-- src/types.jl | 30 +- src/units.jl | 40 +- src/utilities/quaternions.jl | 60 ++- src/utilities/texture_atlas.jl | 125 +++--- src/utilities/utilities.jl | 75 ++-- test/boundingboxes.jl | 6 +- test/conversions.jl | 107 ++--- test/events.jl | 149 +++---- test/figures.jl | 4 +- test/liftmacro.jl | 2 +- test/makielayout.jl | 22 +- test/pipeline.jl | 10 +- test/projection_math.jl | 2 +- test/quaternions.jl | 17 +- test/record.jl | 37 +- test/runtests.jl | 2 +- test/stack.jl | 28 +- test/statistical_tests.jl | 52 +-- test/test_primitives.jl | 6 +- test/text.jl | 16 +- test/transformations.jl | 34 +- test/zoom_pan.jl | 32 +- 212 files changed, 4985 insertions(+), 5952 deletions(-) diff --git a/CairoMakie/src/CairoMakie.jl b/CairoMakie/src/CairoMakie.jl index b5995fe1f33..711426244e1 100644 --- a/CairoMakie/src/CairoMakie.jl +++ b/CairoMakie/src/CairoMakie.jl @@ -15,7 +15,7 @@ using Makie: spaces, is_data_space, is_pixel_space, is_relative_space, is_clip_s using Makie: numbers_to_colors # re-export Makie, including deprecated names -for name in names(Makie, all=true) +for name in names(Makie, all = true) if Base.isexported(Makie, name) @eval using Makie: $(name) @eval export $(name) @@ -30,9 +30,7 @@ include("utils.jl") include("primitives.jl") include("overrides.jl") -function __init__() - activate!() -end +__init__() = activate!() include("precompiles.jl") diff --git a/CairoMakie/src/cairo-extension.jl b/CairoMakie/src/cairo-extension.jl index a2a67344627..117c5787f9d 100644 --- a/CairoMakie/src/cairo-extension.jl +++ b/CairoMakie/src/cairo-extension.jl @@ -1,8 +1,6 @@ # TODO, move those to Cairo? -function set_font_matrix(ctx, matrix) - ccall((:cairo_set_font_matrix, Cairo.libcairo), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}), ctx.ptr, Ref(matrix)) -end +set_font_matrix(ctx, matrix) = ccall((:cairo_set_font_matrix, Cairo.libcairo), Cvoid, (Ptr{Cvoid}, Ptr{Cvoid}), ctx.ptr, Ref(matrix)) function get_font_matrix(ctx) matrix = Cairo.CairoMatrix() @@ -10,13 +8,11 @@ function get_font_matrix(ctx) return matrix end -function cairo_font_face_destroy(font_face) - ccall( - (:cairo_font_face_destroy, Cairo.libcairo), - Cvoid, (Ptr{Cvoid},), - font_face - ) -end +cairo_font_face_destroy(font_face) = ccall( + (:cairo_font_face_destroy, Cairo.libcairo), + Cvoid, (Ptr{Cvoid},), + font_face +) function set_ft_font(ctx, font) @@ -40,18 +36,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 @@ -61,9 +57,7 @@ function surface_set_device_scale(surf, device_x_scale, device_y_scale=device_x_ surf.ptr, device_x_scale, device_y_scale) end -function set_miter_limit(ctx, limit) - ccall((:cairo_set_miter_limit, Cairo.libcairo), Cvoid, (Ptr{Nothing}, Cdouble), ctx.ptr, limit) -end +set_miter_limit(ctx, limit) = ccall((:cairo_set_miter_limit, Cairo.libcairo), Cvoid, (Ptr{Nothing}, Cdouble), ctx.ptr, limit) function get_render_type(surface::Cairo.CairoSurface) typ = ccall((:cairo_surface_get_type, Cairo.libcairo), Cint, (Ptr{Nothing},), surface.ptr) diff --git a/CairoMakie/src/display.jl b/CairoMakie/src/display.jl index d5cf249942b..5c8c0c8277d 100644 --- a/CairoMakie/src/display.jl +++ b/CairoMakie/src/display.jl @@ -8,13 +8,12 @@ Try to run a command. Return `true` if `cmd` runs and is successful (exits with a code of `0`). Return `false` otherwise. """ -function tryrun(cmd::Cmd) +tryrun(cmd::Cmd) = try return success(cmd) catch e return false end -end function openurl(url::String) if Sys.isapple() @@ -38,13 +37,13 @@ function display_path(type::String) return abspath(joinpath(@__DIR__, "display." * type)) end -function Base.display(screen::Screen, scene::Scene; connect=false) +function Base.display(screen::Screen, scene::Scene; connect = false) # Nothing to do, since drawing is done in the other functions # TODO write to file and implement upenurl return screen end -function Base.display(screen::Screen{IMAGE}, scene::Scene; connect=false) +function Base.display(screen::Screen{IMAGE}, scene::Scene; connect = false) path = display_path("png") Makie.push_screen!(scene, screen) cairo_draw(screen, scene) @@ -133,7 +132,7 @@ end Converts anything like `"png", :png, "image/png", MIME"image/png"()` to `"image/png"`. """ -function to_mime_string(mime::Union{String, Symbol, MIME}) +to_mime_string(mime::Union{String, Symbol, MIME}) = if mime isa MIME mime_str = string(mime) if !(mime_str in SUPPORTED_MIMES) @@ -147,7 +146,6 @@ function to_mime_string(mime::Union{String, Symbol, MIME}) end return mime_str end -end """ disable_mime!(mime::Union{String, Symbol, MIME}...) diff --git a/CairoMakie/src/infrastructure.jl b/CairoMakie/src/infrastructure.jl index ffe6741e10d..e70acc85651 100644 --- a/CairoMakie/src/infrastructure.jl +++ b/CairoMakie/src/infrastructure.jl @@ -90,13 +90,13 @@ function draw_background(screen::Screen, scene::Scene) Cairo.save(cr) if scene.clear[] bg = scene.backgroundcolor[] - Cairo.set_source_rgba(cr, red(bg), green(bg), blue(bg), alpha(bg)); + Cairo.set_source_rgba(cr, red(bg), green(bg), blue(bg), alpha(bg)) r = pixelarea(scene)[] Cairo.rectangle(cr, origin(r)..., widths(r)...) # background fill(cr) end Cairo.restore(cr) - foreach(child_scene-> draw_background(screen, child_scene), scene.children) + foreach(child_scene -> draw_background(screen, child_scene), scene.children) end function draw_plot(scene::Scene, screen::Screen, primitive::Combined) @@ -150,6 +150,4 @@ function draw_plot_as_image(scene::Scene, screen::Screen, primitive::Combined, s return end -function draw_atomic(::Scene, ::Screen, x) - @warn "$(typeof(x)) is not supported by cairo right now" -end +draw_atomic(::Scene, ::Screen, x) = @warn "$(typeof(x)) is not supported by cairo right now" diff --git a/CairoMakie/src/overrides.jl b/CairoMakie/src/overrides.jl index 3630440ae5a..aae4c035c57 100644 --- a/CairoMakie/src/overrides.jl +++ b/CairoMakie/src/overrides.jl @@ -16,9 +16,7 @@ end """ Fallback method for args without special treatment. """ -function draw_poly(scene::Scene, screen::Screen, poly, args...) - draw_poly_as_mesh(scene, screen, poly) -end +draw_poly(scene::Scene, screen::Screen, poly, args...) = draw_poly_as_mesh(scene, screen, poly) function draw_poly_as_mesh(scene, screen, poly) draw_plot(scene, screen, poly.plots[1]) @@ -27,17 +25,13 @@ end # in the rare case of per-vertex colors redirect to mesh drawing -function draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}, color::AbstractArray, model, strokecolor, strokewidth) - draw_poly_as_mesh(scene, screen, poly) -end +draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}, color::AbstractArray, model, strokecolor, strokewidth) = draw_poly_as_mesh(scene, screen, poly) -function draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}) - draw_poly(scene, screen, poly, points, poly.color[], poly.model[], poly.strokecolor[], poly.strokewidth[]) -end +draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}) = draw_poly(scene, screen, poly, points, poly.color[], poly.model[], poly.strokecolor[], poly.strokewidth[]) # when color is a Makie.AbstractPattern, we don't need to go to Mesh function draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}, color::Union{Symbol, Colorant, Makie.AbstractPattern}, - model, strokecolor, strokewidth) + model, strokecolor, strokewidth) space = to_value(get(poly, :space, :data)) points = project_position.(Ref(scene), space, points, Ref(model)) Cairo.move_to(screen.context, points[1]...) @@ -47,7 +41,7 @@ function draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}, Cairo.close_path(screen.context) if color isa Makie.AbstractPattern cairopattern = Cairo.CairoPattern(color) - Cairo.pattern_set_extend(cairopattern, Cairo.EXTEND_REPEAT); + Cairo.pattern_set_extend(cairopattern, Cairo.EXTEND_REPEAT) Cairo.set_source(screen.context, cairopattern) else Cairo.set_source_rgba(screen.context, rgbatuple(to_color(color))...) @@ -59,13 +53,12 @@ function draw_poly(scene::Scene, screen::Screen, poly, points::Vector{<:Point2}, Cairo.stroke(screen.context) end -function draw_poly(scene::Scene, screen::Screen, poly, points_list::Vector{<:Vector{<:Point2}}) +draw_poly(scene::Scene, screen::Screen, poly, points_list::Vector{<:Vector{<:Point2}}) = broadcast_foreach(points_list, poly.color[], poly.strokecolor[], poly.strokewidth[]) do points, color, strokecolor, strokewidth - draw_poly(scene, screen, poly, points, color, poly.model[], strokecolor, strokewidth) + draw_poly(scene, screen, poly, points, color, poly.model[], strokecolor, strokewidth) end -end draw_poly(scene::Scene, screen::Screen, poly, rect::Rect2) = draw_poly(scene, screen, poly, [rect]) @@ -82,7 +75,7 @@ function draw_poly(scene::Scene, screen::Screen, poly, rects::Vector{<:Rect2}) color = to_color(color) elseif color isa Makie.AbstractPattern cairopattern = Cairo.CairoPattern(color) - Cairo.pattern_set_extend(cairopattern, Cairo.EXTEND_REPEAT); + Cairo.pattern_set_extend(cairopattern, Cairo.EXTEND_REPEAT) end strokecolor = poly.strokecolor[] if strokecolor isa AbstractArray{<:Number} @@ -164,7 +157,7 @@ end ################################################################################ function draw_plot(scene::Scene, screen::Screen, - band::Band{<:Tuple{<:AbstractVector{<:Point2},<:AbstractVector{<:Point2}}}) + band::Band{<:Tuple{<:AbstractVector{<:Point2}, <:AbstractVector{<:Point2}}}) if !(band.color[] isa AbstractArray) upperpoints = band[1][] @@ -211,7 +204,7 @@ function draw_plot(scene::Scene, screen::Screen, tric::Tricontourf) function draw_tripolys(polys, colornumbers, colors) for (i, (pol, colnum, col)) in enumerate(zip(polys, colornumbers, colors)) polypath(screen.context, pol) - if i == length(colornumbers) || colnum != colornumbers[i+1] + if i == length(colornumbers) || colnum != colornumbers[i + 1] Cairo.set_source_rgba(screen.context, rgbatuple(col)...) Cairo.fill(screen.context) end diff --git a/CairoMakie/src/primitives.jl b/CairoMakie/src/primitives.jl index 765295e6d0a..c1f46ed5618 100644 --- a/CairoMakie/src/primitives.jl +++ b/CairoMakie/src/primitives.jl @@ -30,7 +30,7 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Unio space = to_value(get(primitive, :space, :data)) projected_positions = project_position.(Ref(scene), Ref(space), positions, Ref(model)) - if color isa AbstractArray{<: Number} + if color isa AbstractArray{<:Number} color = numbers_to_colors(color, primitive) end @@ -79,12 +79,12 @@ function draw_single(primitive::Lines, ctx, positions) # only take action for non-NaNs if !isnan(p) # new line segment at beginning or if previously NaN - if i == 1 || isnan(positions[i-1]) + if i == 1 || isnan(positions[i - 1]) Cairo.move_to(ctx, p...) else Cairo.line_to(ctx, p...) # complete line segment at end or if next point is NaN - if i == n || isnan(positions[i+1]) + if i == n || isnan(positions[i + 1]) Cairo.stroke(ctx) end end @@ -98,9 +98,9 @@ function draw_single(primitive::LineSegments, ctx, positions) @assert iseven(length(positions)) - @inbounds for i in 1:2:length(positions)-1 + @inbounds for i in 1:2:(length(positions) - 1) p1 = positions[i] - p2 = positions[i+1] + p2 = positions[i + 1] if isnan(p1) || isnan(p2) continue @@ -115,14 +115,10 @@ function draw_single(primitive::LineSegments, ctx, positions) end # if linewidth is not an array -function draw_multi(primitive, ctx, positions, colors::AbstractArray, linewidth, dash) - draw_multi(primitive, ctx, positions, colors, [linewidth for c in colors], dash) -end +draw_multi(primitive, ctx, positions, colors::AbstractArray, linewidth, dash) = draw_multi(primitive, ctx, positions, colors, [linewidth for c in colors], dash) # if color is not an array -function draw_multi(primitive, ctx, positions, color, linewidths::AbstractArray, dash) - draw_multi(primitive, ctx, positions, [color for l in linewidths], linewidths, dash) -end +draw_multi(primitive, ctx, positions, color, linewidths::AbstractArray, dash) = draw_multi(primitive, ctx, positions, [color for l in linewidths], linewidths, dash) function draw_multi(primitive::Union{Lines, LineSegments}, ctx, positions, colors::AbstractArray, linewidths::AbstractArray, dash) if primitive isa LineSegments @@ -132,32 +128,32 @@ function draw_multi(primitive::Union{Lines, LineSegments}, ctx, positions, color @assert length(linewidths) == length(colors) iterator = if primitive isa Lines - 1:length(positions)-1 + 1:(length(positions) - 1) elseif primitive isa LineSegments 1:2:length(positions) end for i in iterator - if isnan(positions[i+1]) || isnan(positions[i]) + if isnan(positions[i + 1]) || isnan(positions[i]) continue end Cairo.move_to(ctx, positions[i]...) - Cairo.line_to(ctx, positions[i+1]...) - if linewidths[i] != linewidths[i+1] + Cairo.line_to(ctx, positions[i + 1]...) + if linewidths[i] != linewidths[i + 1] error("Cairo doesn't support two different line widths ($(linewidths[i]) and $(linewidths[i+1])) at the endpoints of a line.") end Cairo.set_line_width(ctx, linewidths[i]) !isnothing(dash) && Cairo.set_dash(ctx, dash .* linewidths[i]) c1 = colors[i] - c2 = colors[i+1] + c2 = colors[i + 1] # we can avoid the more expensive gradient if the colors are the same # this happens if one color was given for each segment if c1 == c2 Cairo.set_source_rgba(ctx, red(c1), green(c1), blue(c1), alpha(c1)) Cairo.stroke(ctx) else - pat = Cairo.pattern_create_linear(positions[i]..., positions[i+1]...) + pat = Cairo.pattern_create_linear(positions[i]..., positions[i + 1]...) Cairo.pattern_add_color_stop_rgba(pat, 0, red(c1), green(c1), blue(c1), alpha(c1)) Cairo.pattern_add_color_stop_rgba(pat, 1, red(c2), green(c2), blue(c2), alpha(c2)) Cairo.set_source(ctx, pat) @@ -185,7 +181,7 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Scat font = to_font(to_value(get(primitive, :font, Makie.defaultfont()))) - colors = if color isa AbstractArray{<: Number} + colors = if color isa AbstractArray{<:Number} numbers_to_colors(color, primitive) else color @@ -205,12 +201,12 @@ end _marker_convert(markers::AbstractArray) = map(m -> convert_attribute(m, key"marker"(), key"scatter"()), markers) _marker_convert(marker) = convert_attribute(marker, key"marker"(), key"scatter"()) # image arrays need to be converted as a whole -_marker_convert(marker::AbstractMatrix{<:Colorant}) = [ convert_attribute(marker, key"marker"(), key"scatter"()) ] +_marker_convert(marker::AbstractMatrix{<:Colorant}) = [convert_attribute(marker, key"marker"(), key"scatter"())] function draw_atomic_scatter(scene, ctx, transfunc, colors, markersize, strokecolor, strokewidth, marker, marker_offset, rotations, model, positions, size_model, font, markerspace, space) broadcast_foreach(positions, colors, markersize, strokecolor, - strokewidth, marker, marker_offset, remove_billboard(rotations)) do point, col, - markersize, strokecolor, strokewidth, m, mo, rotation + strokewidth, marker, marker_offset, remove_billboard(rotations)) do point, col, + markersize, strokecolor, strokewidth, m, mo, rotation scale = project_scale(scene, markerspace, markersize, size_model) offset = project_scale(scene, markerspace, mo, size_model) @@ -287,17 +283,17 @@ function draw_marker(ctx, marker::Char, font, pos, scale, strokecolor, strokewid set_font_matrix(ctx, old_matrix) end -function draw_marker(ctx, ::Type{<: Circle}, pos, scale, strokecolor, strokewidth, marker_offset, rotation) +function draw_marker(ctx, ::Type{<:Circle}, pos, scale, strokecolor, strokewidth, marker_offset, rotation) marker_offset = marker_offset + scale ./ 2 pos += Point2f(marker_offset[1], -marker_offset[2]) if scale[1] != scale[2] old_matrix = Cairo.get_matrix(ctx) Cairo.scale(ctx, scale[1], scale[2]) - Cairo.translate(ctx, pos[1]/scale[1], pos[2]/scale[2]) - Cairo.arc(ctx, 0, 0, 0.5, 0, 2*pi) + Cairo.translate(ctx, pos[1] / scale[1], pos[2] / scale[2]) + Cairo.arc(ctx, 0, 0, 0.5, 0, 2 * pi) else - Cairo.arc(ctx, pos[1], pos[2], scale[1]/2, 0, 2*pi) + Cairo.arc(ctx, pos[1], pos[2], scale[1] / 2, 0, 2 * pi) end Cairo.fill_preserve(ctx) @@ -311,7 +307,7 @@ function draw_marker(ctx, ::Type{<: Circle}, pos, scale, strokecolor, strokewidt nothing end -function draw_marker(ctx, ::Type{<: Rect}, pos, scale, strokecolor, strokewidth, marker_offset, rotation) +function draw_marker(ctx, ::Type{<:Rect}, pos, scale, strokecolor, strokewidth, marker_offset, rotation) s2 = Point2((scale .* (1, -1))...) pos = pos .+ Point2f(marker_offset[1], -marker_offset[2]) Cairo.rotate(ctx, to_2d_rotation(rotation)) @@ -357,21 +353,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 @@ -380,13 +376,12 @@ end # Text # ################################################################################ -function p3_to_p2(p::Point3{T}) where T +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}}})) ctx = screen.context @@ -405,9 +400,9 @@ end function draw_glyph_collection( - scene, ctx, positions, glyph_collections::AbstractArray, rotation, - model::Mat, space, markerspace, offset - ) + scene, ctx, positions, glyph_collections::AbstractArray, rotation, + model::Mat, space, markerspace, offset +) # TODO: why is the Ref around model necessary? doesn't broadcast_foreach handle staticarrays matrices? broadcast_foreach(positions, glyph_collections, rotation, Ref(model), space, @@ -447,7 +442,7 @@ function draw_glyph_collection(scene, ctx, position, glyph_collection, rotation, Cairo.save(ctx) broadcast_foreach(glyphs, glyphoffsets, fonts, rotations, scales, colors, strokewidths, strokecolors, offsets) do glyph, - glyphoffset, font, rotation, scale, color, strokewidth, strokecolor, offset + glyphoffset, font, rotation, scale, color, strokewidth, strokecolor, offset cairoface = set_ft_font(ctx, font) old_matrix = get_font_matrix(ctx) @@ -524,13 +519,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 @@ -538,9 +533,7 @@ end regularly_spaced_array_to_range(arr::AbstractRange) = arr -function premultiplied_rgba(a::AbstractArray{<:ColorAlpha}) - map(premultiplied_rgba, a) -end +premultiplied_rgba(a::AbstractArray{<:ColorAlpha}) = map(premultiplied_rgba, a) 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) @@ -553,14 +546,14 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Unio if !(xs isa AbstractVector) l, r = extrema(xs) N = size(image, 1) - xs = range(l, r, length = N+1) + xs = range(l, r, length = N + 1) else xs = regularly_spaced_array_to_range(xs) end if !(ys isa AbstractVector) l, r = extrema(ys) N = size(image, 2) - ys = range(l, r, length = N+1) + ys = range(l, r, length = N + 1) else ys = regularly_spaced_array_to_range(ys) end @@ -574,7 +567,7 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Unio # Vector backends don't support FILTER_NEAREST for interp == false, so in that case we also need to draw rects is_vector = is_vector_backend(ctx) t = Makie.transform_func_obs(primitive)[] - identity_transform = (t === identity || t isa Tuple && all(x-> x === identity, t)) && (abs(model[1, 2]) < 1e-15) + identity_transform = (t === identity || t isa Tuple && all(x -> x === identity, t)) && (abs(model[1, 2]) < 1e-15) regular_grid = xs isa AbstractRange && ys isa AbstractRange if interpolate @@ -632,38 +625,36 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Unio end 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] - - # Rectangles and polygons that are directly adjacent usually show - # white lines between them due to anti aliasing. To avoid this we - # increase their size slightly. - - if alpha(colors[i, j]) == 1 - # sign.(p - center) gives the direction in which we need to - # extend the polygon. (Which may change due to rotations in the - # 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)) - end +_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] - Cairo.set_line_width(ctx, 0) - Cairo.move_to(ctx, p1[1], p1[2]) - Cairo.line_to(ctx, p2[1], p2[2]) - Cairo.line_to(ctx, p3[1], p3[2]) - Cairo.line_to(ctx, p4[1], p4[2]) - Cairo.close_path(ctx) - Cairo.set_source_rgba(ctx, rgbatuple(colors[i, j])...) - Cairo.fill(ctx) + # Rectangles and polygons that are directly adjacent usually show + # white lines between them due to anti aliasing. To avoid this we + # increase their size slightly. + + if alpha(colors[i, j]) == 1 + # sign.(p - center) gives the direction in which we need to + # extend the polygon. (Which may change due to rotations in the + # 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)) end + + Cairo.set_line_width(ctx, 0) + Cairo.move_to(ctx, p1[1], p1[2]) + Cairo.line_to(ctx, p2[1], p2[2]) + Cairo.line_to(ctx, p3[1], p3[2]) + Cairo.line_to(ctx, p4[1], p4[2]) + Cairo.close_path(ctx) + Cairo.set_source_rgba(ctx, rgbatuple(colors[i, j])...) + Cairo.fill(ctx) end @@ -688,7 +679,7 @@ end function draw_mesh2D(scene, screen, @nospecialize(plot), @nospecialize(mesh)) @get_attribute(plot, (color,)) color = to_color(hasproperty(mesh, :color) ? mesh.color : color) - vs = decompose(Point2f, mesh)::Vector{Point2f} + vs = decompose(Point2f, mesh)::Vector{Point2f} fs = decompose(GLTriangleFace, mesh)::Vector{GLTriangleFace} uv = decompose_uv(mesh)::Union{Nothing, Vector{Vec2f}} model = plot.model[]::Mat4f @@ -708,7 +699,7 @@ function draw_mesh2D(scene, screen, @nospecialize(plot), @nospecialize(mesh)) end function draw_mesh2D(scene, screen, per_face_cols, space::Symbol, - vs::Vector{Point2f}, fs::Vector{GLTriangleFace}, model::Mat4f) + vs::Vector{Point2f}, fs::Vector{GLTriangleFace}, model::Mat4f) ctx = screen.context # Priorize colors of the mesh if present @@ -716,7 +707,7 @@ function draw_mesh2D(scene, screen, per_face_cols, space::Symbol, for (f, (c1, c2, c3)) in zip(fs, per_face_cols) pattern = Cairo.CairoPatternMesh() - t1, t2, t3 = project_position.(scene, space, vs[f], (model,)) #triangle points + t1, t2, t3 = project_position.(scene, space, vs[f], (model,)) #triangle points Cairo.mesh_pattern_begin_patch(pattern) Cairo.mesh_pattern_move_to(pattern, t1...) @@ -744,7 +735,7 @@ end nan2zero(x) = !isnan(x) * x -function draw_mesh3D(scene, screen, attributes, mesh; pos = Vec4f(0), scale = 1f0) +function draw_mesh3D(scene, screen, attributes, mesh; pos = Vec4f(0), scale = 1.0f0) # Priorize colors of the mesh if present @get_attribute(attributes, (color,)) @@ -781,10 +772,10 @@ function draw_mesh3D(scene, screen, attributes, mesh; pos = Vec4f(0), scale = 1f end function draw_mesh3D( - scene, screen, space, meshpoints, meshfaces, meshnormals, per_face_col, pos, scale, - model, shading, diffuse, - specular, shininess, faceculling - ) + scene, screen, space, meshpoints, meshfaces, meshnormals, per_face_col, pos, scale, + model, shading, diffuse, + specular, shininess, faceculling +) ctx = screen.context view = ifelse(is_data_space(space), scene.camera.view[], Mat4f(I)) projection = Makie.space_to_clip(scene.camera, space, false) @@ -799,8 +790,8 @@ function draw_mesh3D( vs = broadcast(meshpoints, (func,)) do v, f # Should v get a nan2zero? v = Makie.apply_transform(f, v, space) - p4d = to_ndim(Vec4f, scale .* to_ndim(Vec3f, v, 0f0), 1f0) - view * (model * p4d .+ to_ndim(Vec4f, pos, 0f0)) + p4d = to_ndim(Vec4f, scale .* to_ndim(Vec3f, v, 0.0f0), 1.0f0) + view * (model * p4d .+ to_ndim(Vec4f, pos, 0.0f0)) end ns = map(n -> normalize(normalmatrix * n), meshnormals) @@ -828,7 +819,7 @@ function draw_mesh3D( @inbounds begin p = (clip ./ clip[4])[Vec(1, 2)] p_yflip = Vec2f(p[1], -p[2]) - p_0_to_1 = (p_yflip .+ 1f0) ./ 2f0 + p_0_to_1 = (p_yflip .+ 1.0f0) ./ 2.0f0 end p = p_0_to_1 .* scene.camera.resolution[] return Vec3f(p[1], p[2], clip[3]) @@ -846,10 +837,10 @@ function draw_mesh3D( end function _calculate_shaded_vertexcolors(N, v, c, lightpos, ambient, diffuse, specular, shininess) - L = normalize(lightpos .- v[Vec(1,2,3)]) - diff_coeff = max(dot(L, N), 0f0) + L = normalize(lightpos .- v[Vec(1, 2, 3)]) + diff_coeff = max(dot(L, N), 0.0f0) H = normalize(L + normalize(-v[Vec(1, 2, 3)])) - spec_coeff = max(dot(H, N), 0f0)^shininess + spec_coeff = max(dot(H, N), 0.0f0)^shininess c = RGBAf(c) # if this is one expression it introduces allocations?? new_c_part1 = (ambient .+ diff_coeff .* diffuse) .* Vec3f(c.r, c.g, c.b) #.+ @@ -904,7 +895,7 @@ function draw_pattern(ctx, zorder, shading, meshfaces, ts, per_face_col, ns, vs, Cairo.paint(ctx) Cairo.destroy(pattern) end - + end ################################################################################ @@ -928,11 +919,11 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Maki end function surface2mesh(xs, ys, zs::AbstractMatrix) - ps = Makie.matrix_grid(p-> nan2zero.(p), xs, ys, zs) + ps = Makie.matrix_grid(p -> nan2zero.(p), xs, ys, zs) rect = Tesselation(Rect2f(0, 0, 1, 1), size(zs)) faces = decompose(QuadFace{Int}, rect) - uv = map(x-> Vec2f(1f0 - x[2], 1f0 - x[1]), decompose_uv(rect)) - uvm = GeometryBasics.Mesh(GeometryBasics.meta(ps; uv=uv), faces) + uv = map(x -> Vec2f(1.0f0 - x[2], 1.0f0 - x[1]), decompose_uv(rect)) + uvm = GeometryBasics.Mesh(GeometryBasics.meta(ps; uv = uv), faces) return GeometryBasics.normal_mesh(uvm) end @@ -944,7 +935,7 @@ end function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Makie.MeshScatter)) @get_attribute(primitive, (color, model, marker, markersize, rotations)) - if color isa AbstractArray{<: Number} + if color isa AbstractArray{<:Number} color = numbers_to_colors(color, primitive) end @@ -955,17 +946,17 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Maki view = scene.camera.view[] zorder = sortperm(pos, by = p -> begin - p4d = to_ndim(Vec4f, to_ndim(Vec3f, p, 0f0), 1f0) - cam_pos = view * model * p4d - cam_pos[3] / cam_pos[4] - end, rev=false) + p4d = to_ndim(Vec4f, to_ndim(Vec3f, p, 0.0f0), 1.0f0) + cam_pos = view * model * p4d + cam_pos[3] / cam_pos[4] + end, rev = false) submesh = Attributes( - model=model, - color=color, - shading=primitive.shading, diffuse=primitive.diffuse, - specular=primitive.specular, shininess=primitive.shininess, - faceculling=get(primitive, :faceculling, -10) + model = model, + color = color, + shading = primitive.shading, diffuse = primitive.diffuse, + specular = primitive.specular, shininess = primitive.shininess, + faceculling = get(primitive, :faceculling, -10) ) if !(rotations isa Vector) @@ -987,7 +978,7 @@ function draw_atomic(scene::Scene, screen::Screen, @nospecialize(primitive::Maki draw_mesh3D( scene, screen, submesh, m, pos = p, - scale = scale isa Real ? Vec3f(scale) : to_ndim(Vec3f, scale, 1f0) + scale = scale isa Real ? Vec3f(scale) : to_ndim(Vec3f, scale, 1.0f0) ) end diff --git a/CairoMakie/src/screen.jl b/CairoMakie/src/screen.jl index 2dd3f7232df..cb3ed83f09d 100644 --- a/CairoMakie/src/screen.jl +++ b/CairoMakie/src/screen.jl @@ -3,7 +3,7 @@ using Base.Docs: doc @enum RenderType SVG IMAGE PDF EPS Base.convert(::Type{RenderType}, ::MIME{SYM}) where SYM = mime_to_rendertype(SYM) -function Base.convert(::Type{RenderType}, type::String) +Base.convert(::Type{RenderType}, type::String) = if type == "png" return IMAGE elseif type == "svg" @@ -15,7 +15,6 @@ function Base.convert(::Type{RenderType}, type::String) else error("Unsupported cairo render type: $type") end -end "Convert a rendering type to a MIME type" function to_mime(type::RenderType) @@ -40,15 +39,11 @@ function mime_to_rendertype(mime::Symbol)::RenderType end end -function surface_from_output_type(mime::MIME{M}, io, w, h) where M - surface_from_output_type(M, io, w, h) -end +surface_from_output_type(mime::MIME{M}, io, w, h) where M = surface_from_output_type(M, io, w, h) -function surface_from_output_type(mime::Symbol, io, w, h) - surface_from_output_type(mime_to_rendertype(mime), io, w, h) -end +surface_from_output_type(mime::Symbol, io, w, h) = surface_from_output_type(mime_to_rendertype(mime), io, w, h) -function surface_from_output_type(type::RenderType, io, w, h) +surface_from_output_type(type::RenderType, io, w, h) = if type === SVG return Cairo.CairoSVGSurface(io, w, h) elseif type === PDF @@ -61,7 +56,6 @@ function surface_from_output_type(type::RenderType, io, w, h) else error("No available Cairo surface for mode $type") end -end """ Supported options: `[:best => Cairo.ANTIALIAS_BEST, :good => Cairo.ANTIALIAS_GOOD, :subpixel => Cairo.ANTIALIAS_SUBPIXEL, :none => Cairo.ANTIALIAS_NONE]` @@ -94,9 +88,7 @@ function device_scaling_factor(rendertype, sc::ScreenConfig) return isv ? sc.pt_per_unit : sc.px_per_unit end -function device_scaling_factor(surface::Cairo.CairoSurface, sc::ScreenConfig) - return is_vector_backend(surface) ? sc.pt_per_unit : sc.px_per_unit -end +device_scaling_factor(surface::Cairo.CairoSurface, sc::ScreenConfig) = is_vector_backend(surface) ? sc.pt_per_unit : sc.px_per_unit const LAST_INLINE = Ref(true) @@ -110,7 +102,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) @@ -171,9 +163,7 @@ function destroy!(screen::Screen) Cairo.destroy(screen.context) end -function Base.isopen(screen::Screen) - return !(screen.surface.ptr == C_NULL || screen.context.ptr == C_NULL) -end +Base.isopen(screen::Screen) = !(screen.surface.ptr == C_NULL || screen.context.ptr == C_NULL) Base.size(screen::Screen) = round.(Int, (screen.surface.width, screen.surface.height)) # we render the scene directly, since we have @@ -186,9 +176,7 @@ function Base.delete!(screen::Screen, scene::Scene, plot::AbstractPlot) # do something here. end -function Base.show(io::IO, ::MIME"text/plain", screen::Screen{S}) where S - println(io, "CairoMakie.Screen{$S}") -end +Base.show(io::IO, ::MIME"text/plain", screen::Screen{S}) where S = println(io, "CairoMakie.Screen{$S}") function path_to_type(path) type = splitext(path)[2][2:end] @@ -222,7 +210,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 diff --git a/CairoMakie/src/utils.jl b/CairoMakie/src/utils.jl index 695f957aa0e..2fab6aebc3f 100644 --- a/CairoMakie/src/utils.jl +++ b/CairoMakie/src/utils.jl @@ -10,30 +10,26 @@ end function _project_position(scene, space, point, model, yflip) res = scene.camera.resolution[] - p4d = to_ndim(Vec4f, to_ndim(Vec3f, point, 0f0), 1f0) + p4d = to_ndim(Vec4f, to_ndim(Vec3f, point, 0.0f0), 1.0f0) clip = Makie.space_to_clip(scene.camera, space) * model * p4d @inbounds begin # between -1 and 1 p = (clip ./ clip[4])[Vec(1, 2)] # flip y to match cairo - p_yflip = Vec2f(p[1], (1f0 - 2f0 * yflip) * p[2]) + p_yflip = Vec2f(p[1], (1.0f0 - 2.0f0 * yflip) * p[2]) # normalize to between 0 and 1 - p_0_to_1 = (p_yflip .+ 1f0) ./ 2f0 + p_0_to_1 = (p_yflip .+ 1.0f0) ./ 2.0f0 end # multiply with scene resolution for final position return p_0_to_1 .* res end -function project_position(scene, space, point, model, yflip::Bool = true) - project_position(scene, scene.transformation.transform_func[], space, point, model, yflip) -end +project_position(scene, space, point, model, yflip::Bool = true) = project_position(scene, scene.transformation.transform_func[], space, point, model, yflip) -function project_scale(scene::Scene, space, s::Number, model = Mat4f(I)) - project_scale(scene, space, Vec2f(s), model) -end +project_scale(scene::Scene, space, s::Number, model = Mat4f(I)) = project_scale(scene, space, Vec2f(s), model) function project_scale(scene::Scene, space, s, model = Mat4f(I)) - p4d = model * to_ndim(Vec4f, s, 0f0) + p4d = model * to_ndim(Vec4f, s, 0.0f0) if is_data_space(space) @inbounds p = (scene.camera.projectionview[] * p4d)[Vec(1, 2)] return p .* scene.camera.resolution[] .* 0.5 @@ -117,11 +113,9 @@ to_uint32_color(c) = reinterpret(UInt32, convert(ARGB32, premultiplied_rgba(c))) # Image/heatmap -> ARGBSurface # ######################################## -function to_cairo_image(img::AbstractMatrix{<: AbstractFloat}, attributes) - to_cairo_image(to_rgba_image(img, attributes), attributes) -end +to_cairo_image(img::AbstractMatrix{<:AbstractFloat}, attributes) = to_cairo_image(to_rgba_image(img, attributes), attributes) -function to_rgba_image(img::AbstractMatrix{<: AbstractFloat}, attributes) +function to_rgba_image(img::AbstractMatrix{<:AbstractFloat}, attributes) Makie.@get_attribute attributes (colormap, colorrange, nan_color, lowclip, highclip) nan_color = Makie.to_color(nan_color) @@ -131,7 +125,7 @@ function to_rgba_image(img::AbstractMatrix{<: AbstractFloat}, attributes) [get_rgba_pixel(pixel, colormap, colorrange, nan_color, lowclip, highclip) for pixel in img] end -to_rgba_image(img::AbstractMatrix{<: Colorant}, attributes) = RGBAf.(img) +to_rgba_image(img::AbstractMatrix{<:Colorant}, attributes) = RGBAf.(img) function get_rgba_pixel(pixel, colormap, colorrange, nan_color, lowclip, highclip) vmin, vmax = colorrange @@ -146,9 +140,7 @@ function get_rgba_pixel(pixel, colormap, colorrange, nan_color, lowclip, highcli end end -function to_cairo_image(img::AbstractMatrix{<: Colorant}, attributes) - to_cairo_image(to_uint32_color.(img), attributes) -end +to_cairo_image(img::AbstractMatrix{<:Colorant}, attributes) = to_cairo_image(to_uint32_color.(img), attributes) function to_cairo_image(img::Matrix{UInt32}, attributes) # we need to convert from column-major to row-major storage, @@ -166,27 +158,20 @@ struct FaceIterator{Iteration, T, F, ET} <: AbstractVector{ET} faces::F end -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) -end -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) +(::Type{FaceIterator{Typ}})(data::T, faces::F) where {Typ, T, F} = FaceIterator{Typ, T, F}(data, faces) +(::Type{FaceIterator{Typ, T, F}})(data::AbstractVector, faces::F) where {Typ, F, T} = FaceIterator{Typ, T, F, NTuple{3, eltype(data)}}(data, faces) +(::Type{FaceIterator{Typ, T, F}})(data::T, faces::F) where {Typ, T, F} = FaceIterator{Typ, T, F, NTuple{3, T}}(data, faces) +FaceIterator(data::AbstractVector, faces) = if length(data) == length(faces) FaceIterator{:PerFace}(data, faces) else FaceIterator{:PerVert}(data, faces) end -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} @@ -194,14 +179,14 @@ function get_color_attr(attributes, attribute)::Union{Nothing, RGBAf} end function per_face_colors( - color, colormap, colorrange, matcap, faces, normals, uv, - lowclip=nothing, highclip=nothing, nan_color=nothing - ) + color, colormap, colorrange, matcap, faces, normals, uv, + lowclip = nothing, highclip = nothing, nan_color = nothing +) if matcap !== nothing wsize = reverse(size(matcap)) wh = wsize .- 1 cvec = map(normals) do n - muv = 0.5n[Vec(1,2)] .+ Vec2f(0.5) + muv = 0.5n[Vec(1, 2)] .+ Vec2f(0.5) x, y = clamp.(round.(Int, Tuple(muv) .* wh) .+ 1, 1, wh) return matcap[end - (y - 1), x] end @@ -209,9 +194,9 @@ function per_face_colors( elseif color isa Colorant return FaceIterator{:Const}(color, faces) elseif color isa AbstractArray - if color isa AbstractVector{<: Colorant} + if color isa AbstractVector{<:Colorant} return FaceIterator(color, faces) - elseif color isa AbstractArray{<: Number} + elseif color isa AbstractArray{<:Number} low, high = extrema(colorrange) cvec = map(color[:]) do c if isnan(c) && nan_color !== nothing @@ -228,7 +213,7 @@ function per_face_colors( elseif color isa Makie.AbstractPattern # let next level extend and fill with CairoPattern return color - elseif color isa AbstractMatrix{<: Colorant} && uv !== nothing + elseif color isa AbstractMatrix{<:Colorant} && uv !== nothing wsize = reverse(size(color)) wh = wsize .- 1 cvec = map(uv) do uv @@ -243,14 +228,12 @@ function per_face_colors( error("Unsupported Color type: $(typeof(color))") end -function mesh_pattern_set_corner_color(pattern, id, c::Colorant) - Cairo.mesh_pattern_set_corner_color_rgba(pattern, id, rgbatuple(c)...) -end +mesh_pattern_set_corner_color(pattern, id, c::Colorant) = Cairo.mesh_pattern_set_corner_color_rgba(pattern, id, rgbatuple(c)...) # not piracy function Cairo.CairoPattern(color::Makie.AbstractPattern) # the Cairo y-coordinate are fliped - bitmappattern = reverse!(ARGB32.(Makie.to_image(color)); dims=2) + bitmappattern = reverse!(ARGB32.(Makie.to_image(color)); dims = 2) cairoimage = Cairo.CairoImageSurface(bitmappattern) cairopattern = Cairo.CairoPattern(cairoimage) return cairopattern diff --git a/CairoMakie/test/rasterization_tests.jl b/CairoMakie/test/rasterization_tests.jl index 8554bfad939..5bc9d682137 100644 --- a/CairoMakie/test/rasterization_tests.jl +++ b/CairoMakie/test/rasterization_tests.jl @@ -1,6 +1,6 @@ # guard against some future changes silently making simple vector graphics be # rasterized if they are using features unsupported by the SVG spec -function svg_has_image(x) +svg_has_image(x) = mktempdir() do path path = joinpath(path, "test.svg") save(path, x) @@ -8,13 +8,12 @@ function svg_has_image(x) # if an image element is present in the svg return !occursin(" display -mesh(Sphere(Point3f(0), 1f0), color=:red, ambient=Vec3f(0.9)) +display(mesh(Sphere(Point3f(0), 1.0f0))) +mesh(Sphere(Point3f(0), 1.0f0), color = :red, ambient = Vec3f(0.9)) tocolor(x) = RGBf(x...) -positions = Observable(decompose(Point3f, Sphere(Point3f(0), 1f0))) -triangles = Observable(decompose(GLTriangleFace, Sphere(Point3f(0), 1f0))) -uv = Observable(GeometryBasics.decompose_uv(Sphere(Point3f(0), 1f0))) +positions = Observable(decompose(Point3f, Sphere(Point3f(0), 1.0f0))) +triangles = Observable(decompose(GLTriangleFace, Sphere(Point3f(0), 1.0f0))) +uv = Observable(GeometryBasics.decompose_uv(Sphere(Point3f(0), 1.0f0))) xyz_vertex_color = Observable(tocolor.(positions[])) texture = Observable(rand(RGBAf, 10, 10)) @@ -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); @@ -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 = display(mesh(vertexcolor_mesh, show_axis = false)) 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 = display(mesh(texture_mesh, show_axis = false)) 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 = display(mesh(texture_mesh, show_axis = false)) diff --git a/GLMakie/src/GLAbstraction/AbstractGPUArray.jl b/GLMakie/src/GLAbstraction/AbstractGPUArray.jl index b016ec28854..eb75ed63f0f 100644 --- a/GLMakie/src/GLAbstraction/AbstractGPUArray.jl +++ b/GLMakie/src/GLAbstraction/AbstractGPUArray.jl @@ -14,35 +14,34 @@ 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) + array_size = size(value) indexes_size = map(length, ranges) (array_size != indexes_size) && throw(DimensionMismatch("asigning a $array_size to a $(indexes_size) location")) return true end -function to_range(index) +to_range(index) = map(index) do val isa(val, Integer) && return val:val isa(val, AbstractRange) && return val error("Indexing only defined for integers or ranges. Found: $val") end -end 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} ranges = to_range(Base.to_indices(A, indexes)) - v = isa(value, T) ? [value] : convert(Array{T,N}, value) + 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))) + (A[i, range] = reshape(value, (length(value), 1))) function setindex!(A::GPUArray{T, N}, value::Array{T, N}, ranges::UnitRange...) where {T, N} checkbounds(A, ranges...) @@ -52,9 +51,7 @@ 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)) -end +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{T, N}) where {T, N} switch_context!(A) if length(A) != length(value) @@ -68,7 +65,7 @@ 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 @@ -95,7 +92,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,18 +106,18 @@ 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]) @@ -139,61 +136,61 @@ function resize!(v::GPUVector, newlength::Int) v.size = (max(0, newlength),) return v end - resize!(v.buffer, grow_dimensions(v.real_length, length(v), newlength-length(v))) - v.size = (newlength,) + resize!(v.buffer, grow_dimensions(v.real_length, length(v), newlength - length(v))) + v.size = (newlength,) v.real_length = length(v.buffer) end function grow_at(v::GPUVector, index::Int, amount::Int) - resize!(v, length(v)+amount) - copy!(v, index, v, index+amount, amount) + resize!(v, length(v) + amount) + copy!(v, index, v, index + amount, amount) end -function splice!(v::GPUVector{T}, index::UnitRange, x::Vector=T[]) where T +function splice!(v::GPUVector{T}, index::UnitRange, x::Vector = T[]) where T lenv = length(v) - elements_to_grow = length(x)-length(index) # -1 - buffer = similar(v.buffer, length(v)+elements_to_grow) - copy!(v.buffer, 1, buffer, 1, first(index)-1) # copy first half - copy!(v.buffer, last(index)+1, buffer, first(index)+length(x), lenv-last(index)) # shift second half - v.buffer = buffer + elements_to_grow = length(x) - length(index) # -1 + buffer = similar(v.buffer, length(v) + elements_to_grow) + copy!(v.buffer, 1, buffer, 1, first(index) - 1) # copy first half + copy!(v.buffer, last(index) + 1, buffer, first(index) + length(x), lenv - last(index)) # shift second half + v.buffer = buffer v.real_length = length(buffer) - v.size = (v.real_length,) + v.size = (v.real_length,) copy!(x, 1, buffer, first(index), length(x)) # copy contents of insertion vector return end splice!(v::GPUVector{T}, index::Int, x::T) where {T} = v[index] = x -splice!(v::GPUVector{T}, index::Int, x::Vector=T[]) where {T} = splice!(v, index:index, map(T, x)) +splice!(v::GPUVector{T}, index::Int, x::Vector = T[]) where {T} = splice!(v, index:index, map(T, x)) -copy!(a::GPUVector, a_offset::Int, b::Vector, b_offset::Int, amount::Int) = copy!(a.buffer, a_offset, b, b_offset, amount) -copy!(a::GPUVector, a_offset::Int, b::GPUVector, b_offset::Int, amount::Int)= copy!(a.buffer, a_offset, b.buffer, b_offset, amount) +copy!(a::GPUVector, a_offset::Int, b::Vector, b_offset::Int, amount::Int) = copy!(a.buffer, a_offset, b, b_offset, amount) +copy!(a::GPUVector, a_offset::Int, b::GPUVector, b_offset::Int, amount::Int) = copy!(a.buffer, a_offset, b.buffer, b_offset, amount) -copy!(a::GPUArray, a_offset::Int, b::Vector, b_offset::Int, amount::Int) = _copy!(a, a_offset, b, b_offset, amount) -copy!(a::Vector, a_offset::Int, b::GPUArray, b_offset::Int, amount::Int) = _copy!(a, a_offset, b, b_offset, amount) +copy!(a::GPUArray, a_offset::Int, b::Vector, b_offset::Int, amount::Int) = _copy!(a, a_offset, b, b_offset, amount) +copy!(a::Vector, a_offset::Int, b::GPUArray, b_offset::Int, amount::Int) = _copy!(a, a_offset, b, b_offset, amount) copy!(a::GPUArray, a_offset::Int, b::GPUArray, b_offset::Int, amount::Int) = _copy!(a, a_offset, b, b_offset, amount) #don't overwrite Base.copy! with a::Vector, b::Vector function _copy!(a::Union{Vector, GPUArray}, a_offset::Int, b::Union{Vector, GPUArray}, b_offset::Int, amount::Int) (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 gpu_mem = GPUArrayType(data[]; kw...) # TODO merge these and handle update tracking during contruction - obs1 = on(_-> gpu_mem.requires_update[] = true, data) + obs1 = on(_ -> gpu_mem.requires_update[] = true, data) obs2 = on(new_data -> update!(gpu_mem, new_data), data) if GPUArrayType <: TextureBuffer push!(gpu_mem.buffer.observers, obs1, obs2) diff --git a/GLMakie/src/GLAbstraction/GLBuffer.jl b/GLMakie/src/GLAbstraction/GLBuffer.jl index cc071d589bc..2fc7615ab19 100644 --- a/GLMakie/src/GLAbstraction/GLBuffer.jl +++ b/GLMakie/src/GLAbstraction/GLBuffer.jl @@ -35,36 +35,30 @@ end #used to reset buffer target bind(buffer::GLBuffer, other_target) = glBindBuffer(buffer.buffertype, other_target) -function similar(x::GLBuffer{T}, buff_length::Int) where T - GLBuffer{T}(Ptr{T}(C_NULL), buff_length, x.buffertype, x.usage) -end +similar(x::GLBuffer{T}, buff_length::Int) where T = GLBuffer{T}(Ptr{T}(C_NULL), buff_length, x.buffertype, x.usage) 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 - GC.@preserve buffer begin - return GLBuffer{T}(pointer(buffer), length(buffer), buffertype, usage) - end +GLBuffer( + 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 -function GLBuffer( - 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 +GLBuffer( + 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 function GLBuffer( - buffer::ShaderAbstractions.Buffer{T}; - buffertype::GLenum = GL_ARRAY_BUFFER, usage::GLenum = GL_STATIC_DRAW - ) where T <: GLArrayEltypes - b = GLBuffer(ShaderAbstractions.data(buffer); buffertype=buffertype, usage=usage) + buffer::ShaderAbstractions.Buffer{T}; + buffertype::GLenum = GL_ARRAY_BUFFER, usage::GLenum = GL_STATIC_DRAW +) where T <: GLArrayEltypes + b = GLBuffer(ShaderAbstractions.data(buffer); buffertype = buffertype, usage = usage) obsfunc = ShaderAbstractions.connect!(buffer, b) push!(b.observers, obsfunc) return b @@ -74,34 +68,26 @@ end GLBuffer(buffer::GLBuffer) = buffer GLBuffer{T}(buffer::GLBuffer{T}) where {T} = buffer -function GLBuffer( - buffer::AbstractVector{T}; - kw_args... - ) where T <: GLArrayEltypes - GLBuffer(collect(buffer); kw_args...) -end +GLBuffer( + buffer::AbstractVector{T}; + kw_args... +) where T <: GLArrayEltypes = GLBuffer(collect(buffer); kw_args...) -function GLBuffer{T}( - buffer::AbstractVector; - kw_args... - ) where T <: GLArrayEltypes - GLBuffer(convert(Vector{T}, buffer); kw_args...) -end +GLBuffer{T}( + buffer::AbstractVector; + kw_args... +) where T <: GLArrayEltypes = GLBuffer(convert(Vector{T}, buffer); kw_args...) -function GLBuffer( - ::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 +GLBuffer( + ::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) -function indexbuffer( - buffer::VectorTypes{T}; - usage::GLenum = GL_STATIC_DRAW - ) where T <: GLArrayEltypes - GLBuffer(buffer, buffertype = GL_ELEMENT_ARRAY_BUFFER, usage=usage) -end +indexbuffer( + buffer::VectorTypes{T}; + usage::GLenum = GL_STATIC_DRAW +) where T <: GLArrayEltypes = GLBuffer(buffer, buffertype = GL_ELEMENT_ARRAY_BUFFER, usage = usage) # GPUArray interface function gpu_data(b::GLBuffer{T}) where T data = Vector{T}(undef, length(b)) @@ -116,15 +102,15 @@ end function gpu_resize!(buffer::GLBuffer{T}, newdims::NTuple{1, Int}) where T #TODO make this safe! newlength = newdims[1] - oldlen = length(buffer) + oldlen = length(buffer) if oldlen > 0 old_data = gpu_data(buffer) end bind(buffer) - glBufferData(buffer.buffertype, newlength*sizeof(T), C_NULL, buffer.usage) + glBufferData(buffer.buffertype, newlength * sizeof(T), C_NULL, buffer.usage) bind(buffer, 0) buffer.size = newdims - if oldlen>0 + if oldlen > 0 max_len = min(length(old_data), newlength) #might also shrink buffer[1:max_len] = old_data[1:max_len] end @@ -139,14 +125,14 @@ end function gpu_setindex!(b::GLBuffer{T}, value::Vector{T}, offset::Integer) where T multiplicator = sizeof(T) bind(b) - glBufferSubData(b.buffertype, multiplicator*(offset-1), sizeof(value), value) + glBufferSubData(b.buffertype, multiplicator * (offset - 1), sizeof(value), value) bind(b, 0) end function gpu_setindex!(b::GLBuffer{T}, value::Vector{T}, offset::UnitRange{Int}) where T multiplicator = sizeof(T) bind(b) - glBufferSubData(b.buffertype, multiplicator*(first(offset)-1), sizeof(value), value) + glBufferSubData(b.buffertype, multiplicator * (first(offset) - 1), sizeof(value), value) bind(b, 0) return nothing end @@ -160,18 +146,18 @@ function unsafe_copy!(a::GLBuffer{T}, readoffset::Int, b::GLBuffer{T}, writeoffs glBindBuffer(GL_COPY_WRITE_BUFFER, b.id) glCopyBufferSubData( GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, - multiplicator*(readoffset-1), - multiplicator*(writeoffset-1), - multiplicator*len + multiplicator * (readoffset - 1), + multiplicator * (writeoffset - 1), + multiplicator * len ) glBindBuffer(GL_COPY_READ_BUFFER, 0) glBindBuffer(GL_COPY_WRITE_BUFFER, 0) return nothing end -function Base.iterate(buffer::GLBuffer{T}, i=1) where T +function Base.iterate(buffer::GLBuffer{T}, i = 1) where T i > length(buffer) && return nothing - return gpu_getindex(buffer, i:i)[], i+1 + return gpu_getindex(buffer, i:i)[], i + 1 end #copy inside one buffer @@ -179,40 +165,40 @@ function unsafe_copy!(buffer::GLBuffer{T}, readoffset::Int, writeoffset::Int, le len <= 0 && return nothing bind(buffer) ptr = Ptr{T}(glMapBuffer(buffer.buffertype, GL_READ_WRITE)) - for i=1:len+1 - unsafe_store!(ptr, unsafe_load(ptr, i+readoffset-1), i+writeoffset-1) + for i in 1:(len + 1) + unsafe_store!(ptr, unsafe_load(ptr, i + readoffset - 1), i + writeoffset - 1) end glUnmapBuffer(buffer.buffertype) - bind(buffer,0) + bind(buffer, 0) return nothing end function unsafe_copy!(a::Vector{T}, readoffset::Int, b::GLBuffer{T}, writeoffset::Int, len::Int) where T bind(b) ptr = Ptr{T}(glMapBuffer(b.buffertype, GL_WRITE_ONLY)) - for i=1:len - unsafe_store!(ptr, a[i+readoffset-1], i+writeoffset-1) + for i in 1:len + unsafe_store!(ptr, a[i + readoffset - 1], i + writeoffset - 1) end glUnmapBuffer(b.buffertype) - bind(b,0) + bind(b, 0) end function unsafe_copy!(a::GLBuffer{T}, readoffset::Int, b::Vector{T}, writeoffset::Int, len::Int) where T bind(a) ptr = Ptr{T}(glMapBuffer(a.buffertype, GL_READ_ONLY)) for i in 1:len - b[i+writeoffset-1] = unsafe_load(ptr, i+readoffset-2) #-2 => -1 to zero offset, -1 gl indexing starts at 0 + b[i + writeoffset - 1] = unsafe_load(ptr, i + readoffset - 2) #-2 => -1 to zero offset, -1 gl indexing starts at 0 end glUnmapBuffer(a.buffertype) - bind(a,0) + bind(a, 0) end function gpu_getindex(b::GLBuffer{T}, range::UnitRange) where T multiplicator = sizeof(T) - offset = first(range)-1 + offset = first(range) - 1 value = Vector{T}(undef, length(range)) bind(b) - glGetBufferSubData(b.buffertype, multiplicator*offset, sizeof(value), value) + glGetBufferSubData(b.buffertype, multiplicator * offset, sizeof(value), value) bind(b, 0) return value end diff --git a/GLMakie/src/GLAbstraction/GLExtendedFunctions.jl b/GLMakie/src/GLAbstraction/GLExtendedFunctions.jl index 95235c2a67f..149099d4f9b 100644 --- a/GLMakie/src/GLAbstraction/GLExtendedFunctions.jl +++ b/GLMakie/src/GLAbstraction/GLExtendedFunctions.jl @@ -10,14 +10,14 @@ function glGetShaderiv(shaderID::GLuint, variable::GLenum) end function glShaderSource(shaderID::GLuint, shadercode::Vector{UInt8}) shader_code_ptrs = Ptr{UInt8}[pointer(shadercode)] - len = Ref{GLint}(length(shadercode)) + len = Ref{GLint}(length(shadercode)) glShaderSource(shaderID, 1, shader_code_ptrs, len) end glShaderSource(shaderID::GLuint, shadercode::String) = glShaderSource(shaderID, Vector{UInt8}(shadercode)) function glGetAttachedShaders(program::GLuint) - shader_count = glGetProgramiv(program, GL_ATTACHED_SHADERS) + shader_count = glGetProgramiv(program, GL_ATTACHED_SHADERS) length_written = GLsizei[0] - shaders = zeros(GLuint, shader_count) + shaders = zeros(GLuint, shader_count) glGetAttachedShaders(program, shader_count, length_written, shaders) shaders[1:first(length_written)] @@ -61,15 +61,15 @@ function get_uniform_location(program::GLuint, name::String) end function glGetActiveUniform(programID::GLuint, index::Integer) - actualLength = GLsizei[1] - uniformSize = GLint[1] - typ = GLenum[1] - maxcharsize = glGetProgramiv(programID, GL_ACTIVE_UNIFORM_MAX_LENGTH) - name = Vector{GLchar}(undef, maxcharsize) + actualLength = GLsizei[1] + uniformSize = GLint[1] + typ = GLenum[1] + maxcharsize = glGetProgramiv(programID, GL_ACTIVE_UNIFORM_MAX_LENGTH) + name = Vector{GLchar}(undef, maxcharsize) glGetActiveUniform(programID, index, maxcharsize, actualLength, uniformSize, typ, name) - actualLength[1] <= 0 && error("No active uniform at given index. Index: ", index) + actualLength[1] <= 0 && error("No active uniform at given index. Index: ", index) uname = unsafe_string(pointer(name), actualLength[1]) uname = Symbol(replace(uname, r"\[\d*\]" => "")) # replace array brackets. This is not really a good solution. @@ -77,11 +77,11 @@ function glGetActiveUniform(programID::GLuint, index::Integer) end function glGetActiveAttrib(programID::GLuint, index::Integer) - actualLength = GLsizei[1] - attributeSize = GLint[1] - typ = GLenum[1] - maxcharsize = glGetProgramiv(programID, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH) - name = Vector{GLchar}(undef, maxcharsize) + actualLength = GLsizei[1] + attributeSize = GLint[1] + typ = GLenum[1] + maxcharsize = glGetProgramiv(programID, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH) + name = Vector{GLchar}(undef, maxcharsize) glGetActiveAttrib(programID, index, maxcharsize, actualLength, attributeSize, typ, name) @@ -104,7 +104,7 @@ function glGetIntegerv(variable::GLenum) return result[] end -function glGenBuffers(n=1) +function glGenBuffers(n = 1) result = GLuint[0] glGenBuffers(1, result) id = result[] @@ -118,7 +118,7 @@ function glGenVertexArrays() result = GLuint[0] glGenVertexArrays(1, result) id = result[1] - if id <=0 + if id <= 0 error("glGenVertexArrays returned invalid id. OpenGL Context active?") end return id @@ -179,12 +179,12 @@ end function glTexImage(ttype::GLenum, level::Integer, internalFormat::GLenum, w::Integer, h::Integer, d::Integer, border::Integer, format::GLenum, datatype::GLenum, data) glTexImage3D(GL_PROXY_TEXTURE_3D, level, internalFormat, w, h, d, border, format, datatype, C_NULL) - for l in 0:level + for l in 0:level result = glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, l, GL_TEXTURE_WIDTH) if result == 0 error("glTexImage 3D: width too large. Width: ", w) end - result = glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, l,GL_TEXTURE_HEIGHT) + result = glGetTexLevelParameteriv(GL_PROXY_TEXTURE_3D, l, GL_TEXTURE_HEIGHT) if result == 0 error("glTexImage 3D: height too large. height: ", h) end diff --git a/GLMakie/src/GLAbstraction/GLInfo.jl b/GLMakie/src/GLAbstraction/GLInfo.jl index c72c677807f..b793903090d 100644 --- a/GLMakie/src/GLAbstraction/GLInfo.jl +++ b/GLMakie/src/GLAbstraction/GLInfo.jl @@ -1,8 +1,8 @@ getnames(check_function::Function) = filter(check_function, uint32(0:65534)) # gets all the names currently boundo to programs -getProgramNames() = getnames(glIsProgram) -getShaderNames() = getnames(glIsShader) +getProgramNames() = getnames(glIsProgram) +getShaderNames() = getnames(glIsShader) getVertexArrayNames() = getnames(glIsVertexArray) # display info for all active uniforms in a program @@ -16,9 +16,9 @@ function getUniformsInfo(p::GLProgram) size = Ref{GLint}(0) type = Ref{GLenum}() - for i=0:activeUnif-1 + for i in 0:(activeUnif - 1) glGetActiveUniform(program, i, bufSize, buflen, size, type, name) - println(String(name), " ", buflen[], " ", size[], " ", GLENUM(type[]).name) + println(String(name), " ", buflen[], " ", size[], " ", GLENUM(type[]).name) end end @@ -29,7 +29,7 @@ function uniform_name_type(p::GLProgram, location) size = Ref{GLint}(0) type = Ref{GLenum}() glGetActiveUniform(p.id, location, bufSize, buflen, size, type, name) - println(String(name), " ", buflen[], " ", size[], " ", GLENUM(type[]).name) + println(String(name), " ", buflen[], " ", size[], " ", GLENUM(type[]).name) end # display the values for uniforms in the default block @@ -68,8 +68,8 @@ function getAttributesInfo(p::GLProgram) # how many attribs? @show activeAttr = glGetProgramiv(program, GL_ACTIVE_ATTRIBUTES) # get location and type for each attrib - for i=0:activeAttr-1 - @show name, typ, siz = glGetActiveAttrib(program, i) + for i in 0:(activeAttr - 1) + @show name, typ, siz = glGetActiveAttrib(program, i) @show loc = glGetAttribLocation(program, name) end end diff --git a/GLMakie/src/GLAbstraction/GLRender.jl b/GLMakie/src/GLAbstraction/GLRender.jl index 72581554e46..2b7eb9fa9d3 100644 --- a/GLMakie/src/GLAbstraction/GLRender.jl +++ b/GLMakie/src/GLAbstraction/GLRender.jl @@ -54,9 +54,9 @@ It uses dictionaries and doesn't care about OpenGL call optimizations. So rewriting this function could get us a lot of performance for scenes with a lot of objects. """ -function render(renderobject::RenderObject, vertexarray=renderobject.vertexarray) +function render(renderobject::RenderObject, vertexarray = renderobject.vertexarray) renderobject.requires_update = false - + if renderobject.visible renderobject.prerenderfunction() program = vertexarray.program @@ -73,7 +73,7 @@ function render(renderobject::RenderObject, vertexarray=renderobject.vertexarray error("Uniform tuple too long: $(length(value))") end catch e - @warn error("uniform $key doesn't work with value $(renderobject.uniforms[key])") exception=(e, Base.catch_backtrace()) + @warn error("uniform $key doesn't work with value $(renderobject.uniforms[key])") exception = (e, Base.catch_backtrace()) end end end @@ -89,14 +89,14 @@ end Renders a vertexarray, which consists of the usual buffers plus a vector of unitranges which defines the segments of the buffers to be rendered """ -function render(vao::GLVertexArray{T}, mode::GLenum=GL_TRIANGLES) where T <: VecOrSignal{UnitRange{Int}} +function render(vao::GLVertexArray{T}, mode::GLenum = GL_TRIANGLES) where T <: VecOrSignal{UnitRange{Int}} for elem in to_value(vao.indices) glDrawArrays(mode, max(first(elem) - 1, 0), length(elem) + 1) end return nothing end -function render(vao::GLVertexArray{T}, mode::GLenum=GL_TRIANGLES) where T <: TOrSignal{UnitRange{Int}} +function render(vao::GLVertexArray{T}, mode::GLenum = GL_TRIANGLES) where T <: TOrSignal{UnitRange{Int}} r = to_value(vao.indices) offset = first(r) - 1 # 1 based -> 0 based ndraw = length(r) @@ -108,7 +108,7 @@ function render(vao::GLVertexArray{T}, mode::GLenum=GL_TRIANGLES) where T <: TOr return nothing end -function render(vao::GLVertexArray{T}, mode::GLenum=GL_TRIANGLES) where T <: TOrSignal{Int} +function render(vao::GLVertexArray{T}, mode::GLenum = GL_TRIANGLES) where T <: TOrSignal{Int} r = to_value(vao.indices) glDrawArrays(mode, 0, r) return nothing @@ -117,7 +117,7 @@ end """ Renders a vertex array which supplies an indexbuffer """ -function render(vao::GLVertexArray{GLBuffer{T}}, mode::GLenum=GL_TRIANGLES) where T <: Union{Integer,AbstractFace} +function render(vao::GLVertexArray{GLBuffer{T}}, mode::GLenum = GL_TRIANGLES) where T <: Union{Integer, AbstractFace} glDrawElements( mode, length(vao.indices) * cardinality(vao.indices), @@ -129,7 +129,7 @@ end """ Renders a normal vertex array only containing the usual buffers buffers. """ -function render(vao::GLVertexArray, mode::GLenum=GL_TRIANGLES) +function render(vao::GLVertexArray, mode::GLenum = GL_TRIANGLES) glDrawArrays(mode, 0, length(vao)) return end @@ -137,12 +137,12 @@ end """ Render instanced geometry """ -renderinstanced(vao::GLVertexArray, a, primitive=GL_TRIANGLES) = renderinstanced(vao, length(a), primitive) +renderinstanced(vao::GLVertexArray, a, primitive = GL_TRIANGLES) = renderinstanced(vao, length(a), primitive) """ Renders `amount` instances of an indexed geometry """ -function renderinstanced(vao::GLVertexArray{GLBuffer{T}}, amount::Integer, primitive=GL_TRIANGLES) where T <: Union{Integer,AbstractFace} +function renderinstanced(vao::GLVertexArray{GLBuffer{T}}, amount::Integer, primitive = GL_TRIANGLES) where T <: Union{Integer, AbstractFace} glDrawElementsInstanced(primitive, length(vao.indices) * cardinality(vao.indices), julia2glenum(T), C_NULL, amount) return end @@ -150,7 +150,7 @@ end """ Renders `amount` instances of an not indexed geoemtry geometry """ -function renderinstanced(vao::GLVertexArray, amount::Integer, primitive=GL_TRIANGLES) +function renderinstanced(vao::GLVertexArray, amount::Integer, primitive = GL_TRIANGLES) glDrawElementsInstanced(primitive, length(vao), GL_UNSIGNED_INT, C_NULL, amount) return end diff --git a/GLMakie/src/GLAbstraction/GLRenderObject.jl b/GLMakie/src/GLAbstraction/GLRenderObject.jl index fe644f5c586..b22468210c8 100644 --- a/GLMakie/src/GLAbstraction/GLRenderObject.jl +++ b/GLMakie/src/GLAbstraction/GLRenderObject.jl @@ -1,6 +1,4 @@ -function Base.show(io::IO, obj::RenderObject) - println(io, "RenderObject with ID: ", obj.id) -end +Base.show(io::IO, obj::RenderObject) = println(io, "RenderObject with ID: ", obj.id) Base.getindex(obj::RenderObject, symbol::Symbol) = obj.uniforms[symbol] Base.setindex!(obj::RenderObject, value, symbol::Symbol) = obj.uniforms[symbol] = value @@ -9,8 +7,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 """ @@ -64,9 +62,7 @@ struct StandardPostrender primitive::GLenum end -function (sp::StandardPostrender)() - render(sp.vao, sp.primitive) -end +(sp::StandardPostrender)() = render(sp.vao, sp.primitive) struct StandardPostrenderInstanced{T} main::T @@ -74,9 +70,7 @@ struct StandardPostrenderInstanced{T} primitive::GLenum end -function (sp::StandardPostrenderInstanced)() - renderinstanced(sp.vao, to_value(sp.main), sp.primitive) -end +(sp::StandardPostrenderInstanced)() = renderinstanced(sp.vao, to_value(sp.main), sp.primitive) struct EmptyPrerender end diff --git a/GLMakie/src/GLAbstraction/GLShader.jl b/GLMakie/src/GLAbstraction/GLShader.jl index edbc7efff8c..38f3511c068 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] @@ -94,14 +94,12 @@ struct ShaderCache program_cache::Dict{Any, GLProgram} end -function ShaderCache(context) - ShaderCache( - context, - Dict{String, Vector{String}}(), - Dict{String, Dict{Any, Shader}}(), - Dict{Any, GLProgram}() - ) -end +ShaderCache(context) = ShaderCache( + context, + Dict{String, Vector{String}}(), + Dict{String, Dict{Any, Shader}}(), + Dict{Any, GLProgram}() +) abstract type AbstractLazyShader end @@ -149,8 +147,8 @@ function get_shader!(cache::ShaderCache, path, template_replacement) end::Shader end -function get_template!(cache::ShaderCache, path, view, attributes) - return get!(cache.template_cache, path) do +get_template!(cache::ShaderCache, path, view, attributes) = + get!(cache.template_cache, path) do _, ext = splitext(path) typ = shadertype(ext) @@ -166,7 +164,6 @@ function get_template!(cache::ShaderCache, path, view, attributes) return template_keys end -end function compile_program(shaders, fragdatalocation) @@ -187,7 +184,7 @@ function compile_program(shaders, fragdatalocation) if !GLAbstraction.islinked(program) error( "program $program not linked. Error in: \n", - join(map(x-> string(x.name), shaders), " or "), "\n", getinfolog(program) + join(map(x -> string(x.name), shaders), " or "), "\n", getinfolog(program) ) end # Can be deleted, as they will still be linked to Program and released after program gets released @@ -201,19 +198,17 @@ 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 gl_convert(lazyshader::AbstractLazyShader, data) = error("gl_convert shader") -function gl_convert(lazyshader::LazyShader, data) - gl_convert(lazyshader.shader_cache, lazyshader, data) -end +gl_convert(lazyshader::LazyShader, data) = gl_convert(lazyshader.shader_cache, lazyshader, data) function gl_convert(cache::ShaderCache, lazyshader::AbstractLazyShader, data) kw_dict = lazyshader.kw_args paths = lazyshader.paths - if all(x-> isa(x, Shader), paths) + if all(x -> isa(x, Shader), paths) fragdatalocation = get(kw_dict, :fragdatalocation, Tuple{Int, String}[]) ShaderAbstractions.switch_context!(cache.context) return compile_program([paths...], fragdatalocation) @@ -223,10 +218,10 @@ function gl_convert(cache::ShaderCache, lazyshader::AbstractLazyShader, data) # Tuple(Source, ShaderType) if all(paths) do x - isa(x, Tuple) && length(x) == 2 && + isa(x, Tuple) && length(x) == 2 && isa(first(x), AbstractString) && isa(last(x), GLenum) - end + end # we don't cache view & templates for shader strings! shaders = map(paths) do source_typ source, typ = source_typ @@ -296,7 +291,7 @@ function mustache_replace(replace_view::Union{Dict, Function}, string) if char == '}' closed_mustaches += 1 if closed_mustaches == 2 # we found a complete mustache! - insert_from_view(io, replace_view, SubString(string, replace_begin+1, i-2)) + insert_from_view(io, replace_view, SubString(string, replace_begin + 1, i - 2)) open_mustaches = 0 closed_mustaches = 0 replace_started = false @@ -335,7 +330,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 diff --git a/GLMakie/src/GLAbstraction/GLTexture.jl b/GLMakie/src/GLAbstraction/GLTexture.jl index 51ebdbb628e..a639a07d287 100644 --- a/GLMakie/src/GLAbstraction/GLTexture.jl +++ b/GLMakie/src/GLAbstraction/GLTexture.jl @@ -1,7 +1,7 @@ struct TextureParameters{NDim} minfilter::Symbol magfilter::Symbol # magnification - repeat ::NTuple{NDim, Symbol} + repeat::NTuple{NDim, Symbol} anisotropic::Float32 swizzle_mask::Vector{GLenum} end @@ -9,25 +9,25 @@ end abstract type OpenglTexture{T, NDIM} <: GPUArray{T, NDIM} end mutable struct Texture{T <: GLArrayEltypes, NDIM} <: OpenglTexture{T, NDIM} - id ::GLuint - texturetype ::GLenum - pixeltype ::GLenum - internalformat ::GLenum - format ::GLenum - parameters ::TextureParameters{NDIM} - size ::NTuple{NDIM, Int} - context ::GLContext - requires_update ::Observable{Bool} - observers ::Vector{Observables.ObserverFunction} + id::GLuint + texturetype::GLenum + pixeltype::GLenum + internalformat::GLenum + format::GLenum + parameters::TextureParameters{NDIM} + size::NTuple{NDIM, Int} + context::GLContext + requires_update::Observable{Bool} + observers::Vector{Observables.ObserverFunction} function Texture{T, NDIM}( - id ::GLuint, - texturetype ::GLenum, - pixeltype ::GLenum, - internalformat ::GLenum, - format ::GLenum, - parameters ::TextureParameters{NDIM}, - size ::NTuple{NDIM, Int} - ) where {T, NDIM} + id::GLuint, + texturetype::GLenum, + pixeltype::GLenum, + internalformat::GLenum, + format::GLenum, + parameters::TextureParameters{NDIM}, + size::NTuple{NDIM, Int} + ) where {T, NDIM} tex = new( id, texturetype, @@ -89,13 +89,13 @@ function set_packing_alignment(a) # at some point we should specialize to array/ end function Texture( - data::Ptr{T}, dims::NTuple{NDim, Int}; - internalformat::GLenum = default_internalcolorformat(T), - texturetype ::GLenum = default_texturetype(NDim), - format ::GLenum = default_colorformat(T), - mipmap = false, - parameters... # rest should be texture parameters - ) where {T, NDim} + data::Ptr{T}, dims::NTuple{NDim, Int}; + internalformat::GLenum = default_internalcolorformat(T), + texturetype::GLenum = default_texturetype(NDim), + format::GLenum = default_colorformat(T), + mipmap = false, + parameters... # rest should be texture parameters +) where {T, NDim} texparams = TextureParameters(T, NDim; parameters...) id = glGenTextures() glBindTexture(texturetype, id) @@ -153,12 +153,12 @@ end Constructor for Array Texture """ function Texture( - data::Vector{Array{T, 2}}; - internalformat::GLenum = default_internalcolorformat(T), - texturetype::GLenum = GL_TEXTURE_2D_ARRAY, - format::GLenum = default_colorformat(T), - parameters... - ) where T <: GLArrayEltypes + data::Vector{Array{T, 2}}; + internalformat::GLenum = default_internalcolorformat(T), + texturetype::GLenum = GL_TEXTURE_2D_ARRAY, + format::GLenum = default_colorformat(T), + parameters... +) where T <: GLArrayEltypes texparams = TextureParameters(T, 2; parameters...) id = glGenTextures() @@ -166,18 +166,18 @@ 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}( @@ -233,19 +233,18 @@ Creates a texture from an Image Base.show(io::IO, t::Texture) = show(IOContext(io), MIME"text/plain"(), t) -function Base.show(io::IOContext, mime::MIME"text/plain", t::Texture{T,D}) where {T,D} +Base.show(io::IOContext, mime::MIME"text/plain", t::Texture{T, D}) where {T, D} = if get(io, :compact, false) println(io, "Texture$(D)D, ID: $(t.id), Size: $(size(t))") else show(io.io, mime, t) end -end -function Base.show(io::IO, ::MIME"text/plain", t::Texture{T,D}) where {T,D} +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) @@ -290,14 +289,14 @@ function gpu_setindex!(t::Texture{T, 1}, newvalue::Array{T, 1}, indexes::UnitRan texsubimage(t, newvalue, indexes) bind(t, 0) end -function gpu_setindex!(t::Texture{T, N}, newvalue::Array{T, N}, indexes::Union{UnitRange,Integer}...) where {T, N} +function gpu_setindex!(t::Texture{T, N}, newvalue::Array{T, N}, indexes::Union{UnitRange, Integer}...) where {T, N} bind(t) texsubimage(t, newvalue, indexes...) bind(t, 0) end -function gpu_setindex!(target::Texture{T, 2}, source::Texture{T, 2}, fbo=glGenFramebuffers()) where T +function gpu_setindex!(target::Texture{T, 2}, source::Texture{T, 2}, fbo = glGenFramebuffers()) where T glBindFramebuffer(GL_FRAMEBUFFER, fbo) glFramebufferTexture2D( GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, @@ -307,7 +306,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, @@ -333,7 +332,7 @@ function gpu_data(t::Texture{T, ND}) where {T, ND} 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) @@ -348,22 +347,20 @@ 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} - Texture( - Ptr{T}(C_NULL), - newdims, t.texturetype, - t.pixeltype, - t.internalformat, - t.format, - t.parameters - ) -end +similar(t::Texture{T, NDim}, newdims::NTuple{NDim, Int}) where {T, NDim} = Texture( + Ptr{T}(C_NULL), + newdims, t.texturetype, + t.pixeltype, + t.internalformat, + t.format, + t.parameters +) # Resize Texture 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 @@ -379,19 +376,17 @@ 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 - glTexSubImage2D( - t.texturetype, level, - 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, 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), + t.format, t.pixeltype, newvalue +) +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 ) @@ -491,13 +486,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 = 1.0f0 +) T <: Integer && (minfilter == :linear || magfilter == :linear) && error("Wrong Texture Parameter: Integer texture can't interpolate. Try :nearest") repeat = (x_repeat, y_repeat, z_repeat) swizzle_mask = if T <: Gray @@ -508,17 +503,15 @@ 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} - TextureParameters(T, NDim; kw_args...) -end +TextureParameters(t::Texture{T, NDim}; kw_args...) where {T, NDim} = TextureParameters(T, NDim; kw_args...) 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}[] @@ -542,15 +535,9 @@ function set_parameters(t::Texture{T, N}, params::TextureParameters=t.parameters t.parameters = params set_parameters(t, result) end -function texparameter(t::Texture, key::GLenum, val::GLenum) - glTexParameteri(t.texturetype, key, val) -end -function texparameter(t::Texture, key::GLenum, val::Vector) - glTexParameteriv(t.texturetype, key, val) -end -function texparameter(t::Texture, key::GLenum, val::Float32) - glTexParameterf(t.texturetype, key, val) -end +texparameter(t::Texture, key::GLenum, val::GLenum) = glTexParameteri(t.texturetype, key, val) +texparameter(t::Texture, key::GLenum, val::Vector) = glTexParameteriv(t.texturetype, key, val) +texparameter(t::Texture, key::GLenum, val::Float32) = glTexParameterf(t.texturetype, key, val) function set_parameters(t::Texture, parameters::Vector{Tuple{GLenum, Any}}) bind(t) for elem in parameters diff --git a/GLMakie/src/GLAbstraction/GLTypes.jl b/GLMakie/src/GLAbstraction/GLTypes.jl index 3c6e860191a..b6dcc59bd4d 100644 --- a/GLMakie/src/GLAbstraction/GLTypes.jl +++ b/GLMakie/src/GLAbstraction/GLTypes.jl @@ -1,15 +1,15 @@ ############################################################################ -const TOrSignal{T} = Union{Observable{T},T} +const TOrSignal{T} = Union{Observable{T}, T} -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} +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} -const ArrayTypes{T,N} = Union{GPUArray{T,N},ArrayOrSignal{T,N}} -const VectorTypes{T} = ArrayTypes{T,1} -const MatTypes{T} = ArrayTypes{T,2} -const VolumeTypes{T} = ArrayTypes{T,3} +const ArrayTypes{T, N} = Union{GPUArray{T, N}, ArrayOrSignal{T, N}} +const VectorTypes{T} = ArrayTypes{T, 1} +const MatTypes{T} = ArrayTypes{T, 2} +const VolumeTypes{T} = ArrayTypes{T, 3} @enum Projection PERSPECTIVE ORTHOGRAPHIC @enum MouseButton MOUSE_LEFT MOUSE_MIDDLE MOUSE_RIGHT @@ -27,26 +27,18 @@ struct Shader typ::GLenum id::GLuint context::GLContext - function Shader(name, source, typ, id) - new(name, source, typ, id, current_context()) - end + Shader(name, source, typ, id) = new(name, source, typ, id, current_context()) end -function Shader(name, source::Vector{UInt8}, typ) - compile_shader(source, typ, name) -end +Shader(name, source::Vector{UInt8}, typ) = compile_shader(source, typ, name) name(s::Shader) = s.name import Base: == -function (==)(a::Shader, b::Shader) - a.source == b.source && a.typ == b.typ && a.id == b.id && a.context == b.context -end +(==)(a::Shader, b::Shader) = a.source == b.source && a.typ == b.typ && a.id == b.id && a.context == b.context -function Base.hash(s::Shader, h::UInt64) - hash((s.source, s.typ, s.id, s.context), h) -end +Base.hash(s::Shader, h::UInt64) = hash((s.source, s.typ, s.id, s.context), h) function Base.show(io::IO, shader::Shader) @@ -58,10 +50,10 @@ end mutable struct GLProgram id::GLuint shader::Vector{Shader} - nametype::Dict{Symbol,GLenum} - uniformloc::Dict{Symbol,Tuple} + nametype::Dict{Symbol, GLenum} + uniformloc::Dict{Symbol, Tuple} context::GLContext - function GLProgram(id::GLuint, shader::Vector{Shader}, nametype::Dict{Symbol,GLenum}, uniformloc::Dict{Symbol,Tuple}) + function GLProgram(id::GLuint, shader::Vector{Shader}, nametype::Dict{Symbol, GLenum}, uniformloc::Dict{Symbol, Tuple}) obj = new(id, shader, nametype, uniformloc, current_context()) finalizer(free, obj) obj @@ -128,33 +120,31 @@ end ######################################################################################## # OpenGL Arrays -const GLArrayEltypes = Union{StaticVector,Real,Colorant} +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(::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(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{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} + 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 - error("Type: $T not supported as opengl number datatype") -end +julia2glenum(::Type{T}) where T = error("Type: $T not supported as opengl number datatype") include("GLBuffer.jl") include("GLTexture.jl") @@ -171,7 +161,7 @@ mutable struct GLVertexArray{T} program::GLProgram id::GLuint bufferlength::Int - buffers::Dict{String,GLBuffer} + buffers::Dict{String, GLBuffer} indices::T context::GLContext requires_update::Observable{Bool} @@ -204,7 +194,7 @@ function GLVertexArray(bufferdict::Dict, program::GLProgram) id = glGenVertexArrays() glBindVertexArray(id) lenbuffer = 0 - buffers = Dict{String,GLBuffer}() + buffers = Dict{String, GLBuffer}() for (name, buffer) in bufferdict if isa(buffer, GLBuffer) && buffer.buffertype == GL_ELEMENT_ARRAY_BUFFER bind(buffer) @@ -255,7 +245,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) @@ -307,7 +297,7 @@ end mutable struct RenderObject{Pre} context # OpenGL context - uniforms::Dict{Symbol,Any} + uniforms::Dict{Symbol, Any} observables::Vector{Observable} # for clean up vertexarray::GLVertexArray prerenderfunction::Pre @@ -317,12 +307,12 @@ mutable struct RenderObject{Pre} visible::Bool function RenderObject{Pre}( - context, - uniforms::Dict{Symbol,Any}, observables::Vector{Observable}, - vertexarray::GLVertexArray, - prerenderfunctions, postrenderfunctions, - visible, track_updates = true - ) where Pre + context, + uniforms::Dict{Symbol, Any}, observables::Vector{Observable}, + vertexarray::GLVertexArray, + prerenderfunctions, postrenderfunctions, + visible, track_updates = true + ) where Pre fxaa = Bool(to_value(get!(uniforms, :fxaa, true))) RENDER_OBJECT_ID_COUNTER[] += one(UInt32) # Store fxaa in ID, so we can access it in the shader to create a mask @@ -391,10 +381,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) @@ -405,7 +395,7 @@ function RenderObject( targets = get(data, :gl_convert_targets, Dict()) delete!(data, :gl_convert_targets) - passthrough = Dict{Symbol,Any}() # we also save a few non opengl related values in data + passthrough = Dict{Symbol, Any}() # we also save a few non opengl related values in data observables = Observable[] for (k, v) in data # convert everything to OpenGL compatible types @@ -467,14 +457,13 @@ include("GLRenderObject.jl") #################################################################################### # freeing -function free(x) +free(x) = try unsafe_free(x) catch e isa(e, ContextNotAvailable) && return # if context got destroyed no need to worry! rethrow(e) end -end function clean_up_observables(x::T) where T if hasfield(T, :observers) diff --git a/GLMakie/src/GLAbstraction/GLUniforms.jl b/GLMakie/src/GLAbstraction/GLUniforms.jl index 17f83cc7ec8..724bcccb0e9 100644 --- a/GLMakie/src/GLAbstraction/GLUniforms.jl +++ b/GLMakie/src/GLAbstraction/GLUniforms.jl @@ -10,7 +10,7 @@ const NATIVE_TYPES = Union{ 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") @@ -21,13 +21,11 @@ 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 +uniformfunc(typ::DataType, dims::Tuple{Int}) = Symbol(string("glUniform", first(dims), opengl_postfix(typ))) function uniformfunc(typ::DataType, dims::Tuple{Int, Int}) M, N = dims Symbol(string("glUniformMatrix", M == N ? "$M" : "$(M)x$(N)", opengl_postfix(typ))) @@ -72,19 +70,17 @@ function gluniform(location::GLint, target::GLint, t::Texture) end gluniform(location::Integer, x::Enum) = gluniform(GLint(location), GLint(x)) -function gluniform(loc::Integer, x::Observable{T}) where T - gluniform(GLint(loc), to_value(x)) -end +gluniform(loc::Integer, x::Observable{T}) where T = gluniform(GLint(loc), to_value(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) +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) @@ -105,61 +101,52 @@ end 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 +toglsltype_string(x::T) where T = if isa_gl_struct(x) string("uniform ", T.name.name) else 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)) # 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}) - string(keystring, ";") -end -function glsl_variable_access(keystring, s::Observable) - glsl_variable_access(keystring, to_value(s)) -end -function glsl_variable_access(keystring, t::Any) - error("no glsl variable calculation available for : ", keystring, " of type ", typeof(t)) -end +glsl_variable_access(keystring, ::Union{Real, GLBuffer, GPUVector, Mat, Colorant}) = string(keystring, ";") +glsl_variable_access(keystring, s::Observable) = glsl_variable_access(keystring, to_value(s)) +glsl_variable_access(keystring, t::Any) = error("no glsl variable calculation available for : ", keystring, " of type ", typeof(t)) 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) + 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) + 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_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 || - typ == GL_SAMPLER_1D_ARRAY || typ == GL_SAMPLER_2D_ARRAY || - typ == GL_UNSIGNED_INT_SAMPLER_1D_ARRAY || typ == GL_UNSIGNED_INT_SAMPLER_2D_ARRAY || - typ == GL_INT_SAMPLER_1D_ARRAY || typ == GL_INT_SAMPLER_2D_ARRAY - ) -end +istexturesampler(typ::GLenum) = ( + typ == GL_SAMPLER_BUFFER || typ == GL_INT_SAMPLER_BUFFER || typ == GL_UNSIGNED_INT_SAMPLER_BUFFER || + 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 || + typ == GL_SAMPLER_1D_ARRAY || typ == GL_SAMPLER_2D_ARRAY || + typ == GL_UNSIGNED_INT_SAMPLER_1D_ARRAY || typ == GL_UNSIGNED_INT_SAMPLER_2D_ARRAY || + typ == GL_INT_SAMPLER_1D_ARRAY || typ == GL_INT_SAMPLER_2D_ARRAY +) gl_promote(x::Type{T}) where {T <: Integer} = Cint @@ -178,7 +165,7 @@ gl_promote(x::Type{N0f8}) = x const Color3{T} = Colorant{T, 3} const Color4{T} = Colorant{T, 4} -gl_promote(x::Type{Bool}) = GLboolean +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))} @@ -196,7 +183,7 @@ 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::Vector{Matrix{T}}) where {T <: Colorant} = Texture(s) gl_convert(s::Nothing) = s @@ -211,7 +198,7 @@ function isa_gl_struct(x::T) where T fnames = fieldnames(T) !isempty(fnames) && all(name -> isconcretetype(fieldtype(T, name)) && isbits(getfield(x, name)), fnames) end -function gl_convert_struct(x::T, uniform_name::Symbol) where T +gl_convert_struct(x::T, uniform_name::Symbol) where T = if isa_gl_struct(x) return Dict{Symbol, Any}(map(fieldnames(x)) do name (Symbol("$uniform_name.$name") => gl_convert(getfield(x, name))) @@ -219,7 +206,6 @@ function gl_convert_struct(x::T, uniform_name::Symbol) where T else error("can't convert $x to a OpenGL type. Make sure all fields are of a concrete type and isbits(FieldType)-->true") end -end # native types don't need convert! @@ -228,39 +214,33 @@ 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(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(::Type{<:GPUArray}, a::StaticVector) = gl_convert(a) -function gl_convert(T::Type{<: GPUArray}, a::AbstractArray{X, N}; kw_args...) where {X, N} - T(convert(AbstractArray{gl_promote(X), N}, a); kw_args...) -end +gl_convert(T::Type{<:GPUArray}, a::AbstractArray{X, N}; kw_args...) where {X, N} = T(convert(AbstractArray{gl_promote(X), N}, a); kw_args...) -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} - T(a; kw_args...) -end -gl_convert(::Type{<: GPUArray}, a::Observable{<: StaticVector}) = gl_convert(a) +gl_convert(::Type{T}, a::Vector{Array{X, 2}}; kw_args...) where {T <: Texture, X} = T(a; kw_args...) +gl_convert(::Type{<:GPUArray}, a::Observable{<:StaticVector}) = gl_convert(a) -function gl_convert(::Type{T}, a::Observable{<: AbstractArray{X, N}}; kw_args...) where {T <: GPUArray, X, N} +function gl_convert(::Type{T}, a::Observable{<:AbstractArray{X, N}}; kw_args...) where {T <: GPUArray, X, N} TGL = gl_promote(X) - s = (X == TGL) ? a : lift(x-> convert(Array{TGL, N}, x), a) + s = (X == TGL) ? a : lift(x -> convert(Array{TGL, N}, x), a) T(s; kw_args...) end lift_convert(a::AbstractArray, T, N) = lift(x -> convert(Array{T, N}, x), a) -function lift_convert(a::ShaderAbstractions.Sampler, T, N) - ShaderAbstractions.Sampler( - lift(x -> convert(Array{T, N}, x.data), a), - minfilter = a[].minfilter, magfilter = a[].magfilter, - x_repeat = a[].repeat[1], - y_repeat = a[].repeat[min(2, N)], - z_repeat = a[].repeat[min(3, N)], - anisotropic = a[].anisotropic, swizzle_mask = a[].swizzle_mask - ) -end +lift_convert(a::ShaderAbstractions.Sampler, T, N) = ShaderAbstractions.Sampler( + lift(x -> convert(Array{T, N}, x.data), a), + minfilter = a[].minfilter, magfilter = a[].magfilter, + x_repeat = a[].repeat[1], + y_repeat = a[].repeat[min(2, N)], + z_repeat = a[].repeat[min(3, N)], + anisotropic = a[].anisotropic, swizzle_mask = a[].swizzle_mask +) gl_convert(f::Function, a) = f(a) diff --git a/GLMakie/src/GLAbstraction/GLUtils.jl b/GLMakie/src/GLAbstraction/GLUtils.jl index ff6f2ade728..1a517ac00ec 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)) @@ -14,11 +14,11 @@ Needed to match the lazy gl_convert exceptions. `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::Observable{T}) where {Target, T} = applicable(gl_convert, Target, x) || T <: Target matches_target(::Function, x) = true matches_target(::Function, x::Nothing) = false -signal_convert(T1, y::T2) where {T2<:Observable} = lift(convert, Observable(T1), y) +signal_convert(T1, y::T2) where {T2 <: Observable} = lift(convert, Observable(T1), y) """ @@ -50,8 +50,8 @@ macro gen_defaults!(dict, args) # @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 diff --git a/GLMakie/src/GLMakie.jl b/GLMakie/src/GLMakie.jl index 91a2b127204..dcca0cd8194 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) @@ -50,9 +50,7 @@ gl_texture_atlas() = Makie.get_texture_atlas(2048, 64) # don't put this into try catch, to not mess with normal errors include("gl_backend.jl") -function __init__() - activate!() -end +__init__() = activate!() Base.@deprecate set_window_config!(; screen_config...) GLMakie.activate!(; screen_config...) diff --git a/GLMakie/src/display.jl b/GLMakie/src/display.jl index c8d0aef1f72..5e8150569aa 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) diff --git a/GLMakie/src/drawing_primitives.jl b/GLMakie/src/drawing_primitives.jl index dc438ca4796..0ff1d21a7ba 100644 --- a/GLMakie/src/drawing_primitives.jl +++ b/GLMakie/src/drawing_primitives.jl @@ -4,13 +4,11 @@ using Makie: convert_arguments Makie.el32convert(x::GLAbstraction.Texture) = x Makie.convert_attribute(s::ShaderAbstractions.Sampler{RGBAf}, k::key"color") = s -function Makie.convert_attribute(s::ShaderAbstractions.Sampler{T, N}, k::key"color") where {T, N} - 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 +Makie.convert_attribute(s::ShaderAbstractions.Sampler{T, N}, k::key"color") where {T, N} = ShaderAbstractions.Sampler( + el32convert(s.data), minfilter = s.minfilter, magfilter = s.magfilter, + x_repeat = s.repeat[1], y_repeat = s.repeat[min(2, N)], z_repeat = s.repeat[min(3, N)], + anisotropic = s.anisotropic, color_swizzel = s.color_swizzel +) gpuvec(x) = GPUVector(GLBuffer(x)) @@ -20,13 +18,12 @@ to_range(x::VecTypes{2}) = x to_range(x::AbstractRange) = (minimum(x), maximum(x)) to_range(x::AbstractVector) = (minimum(x), maximum(x)) -function to_range(x::AbstractArray) +to_range(x::AbstractArray) = if length(x) in size(x) # assert that just one dim != 1 to_range(vec(x)) else error("Can't convert to a range. Please supply a range/vector/interval or a tuple (min, max)") end -end function to_glvisualize_key(k) k == :rotations && return :rotation @@ -133,11 +130,10 @@ function Base.insert!(screen::Screen, scene::Scene, x::Combined) end end -function remove_automatic!(attributes) +remove_automatic!(attributes) = filter!(attributes) do (k, v) to_value(v) != automatic end -end index1D(x::SubArray) = parentindices(x)[1] @@ -158,15 +154,12 @@ function handle_view(array::Observable{T}, attributes) where T <: SubArray return A end -function lift_convert(key, value, plot) - return lift_convert_inner(value, Key{key}(), Key{Makie.plotkey(plot)}(), plot) -end +lift_convert(key, value, plot) = lift_convert_inner(value, Key{key}(), Key{Makie.plotkey(plot)}(), plot) -function lift_convert_inner(value, key, plot_key, plot) - return lift(value) do value +lift_convert_inner(value, key, plot_key, plot) = + lift(value) do value return convert_attribute(value, key, plot_key) end -end to_vec4(val::RGB) = RGBAf(val, 1.0) to_vec4(val::RGBA) = RGBAf(val) @@ -183,19 +176,18 @@ end pixel2world(scene, msize::AbstractVector) = pixel2world.(scene, msize) -function handle_intensities!(attributes) - if haskey(attributes, :color) && attributes[:color][] isa AbstractVector{<: Number} +handle_intensities!(attributes) = + if haskey(attributes, :color) && attributes[:color][] isa AbstractVector{<:Number} c = pop!(attributes, :color) - attributes[:intensity] = lift(x-> convert(Vector{Float32}, x), c) + attributes[:intensity] = lift(x -> convert(Vector{Float32}, x), c) else delete!(attributes, :intensity) delete!(attributes, :color_map) delete!(attributes, :color_norm) end -end -function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Union{Scatter, MeshScatter})) - return cached_robj!(screen, scene, x) do gl_attributes +draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Union{Scatter, MeshScatter})) = + cached_robj!(screen, scene, x) do gl_attributes # signals not supported for shading yet gl_attributes[:shading] = to_value(get(gl_attributes, :shading, true)) marker = lift_convert(:marker, pop!(gl_attributes, :marker), x) @@ -213,10 +205,10 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Union{Scatte # fast pixel does its own setup if !(marker[] isa FastPixel) connect_camera!(gl_attributes, cam, mspace) - gl_attributes[:billboard] = map(rot-> isa(rot, Billboard), x.rotations) + gl_attributes[:billboard] = map(rot -> isa(rot, Billboard), x.rotations) atlas = gl_texture_atlas() isnothing(gl_attributes[:distancefield][]) && delete!(gl_attributes, :distancefield) - shape = lift(m-> Cint(Makie.marker_to_sdf_shape(m)), marker) + shape = lift(m -> Cint(Makie.marker_to_sdf_shape(m)), marker) gl_attributes[:shape] = shape get!(gl_attributes, :distancefield) do if shape[] === Cint(DISTANCEFIELD) @@ -244,7 +236,7 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Union{Scatte filter!(gl_attributes) do (k, v,) k in (:color_map, :color, :color_norm, :scale, :model, :projectionview, :visible) end - if !(gl_attributes[:color][] isa AbstractVector{<: Number}) + if !(gl_attributes[:color][] isa AbstractVector{<:Number}) delete!(gl_attributes, :color_norm) delete!(gl_attributes, :color_map) end @@ -258,10 +250,9 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Union{Scatte end end end -end -function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Lines)) - return cached_robj!(screen, scene, x) do gl_attributes +draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Lines)) = + cached_robj!(screen, scene, x) do gl_attributes linestyle = pop!(gl_attributes, :linestyle) data = Dict{Symbol, Any}(gl_attributes) ls = to_value(linestyle) @@ -278,10 +269,9 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::Lines)) connect_camera!(data, scene.camera) return draw_lines(screen, positions, data) end -end -function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::LineSegments)) - return cached_robj!(screen, scene, x) do gl_attributes +draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::LineSegments)) = + cached_robj!(screen, scene, x) do gl_attributes linestyle = pop!(gl_attributes, :linestyle) data = Dict{Symbol, Any}(gl_attributes) ls = to_value(linestyle) @@ -294,7 +284,7 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::LineSegments space = get(gl_attributes, :space, :data) # needs to happen before connect_camera! call positions = handle_view(x.converted[1], data) positions = apply_transform(transform_func_obs(x), positions, space) - if haskey(data, :color) && data[:color][] isa AbstractVector{<: Number} + if haskey(data, :color) && data[:color][] isa AbstractVector{<:Number} c = pop!(data, :color) data[:color] = el32convert(c) else @@ -305,15 +295,14 @@ function draw_atomic(screen::Screen, scene::Scene, @nospecialize(x::LineSegments return draw_linesegments(screen, positions, data) end -end function draw_atomic(screen::Screen, scene::Scene, - x::Text{<:Tuple{<:Union{<:Makie.GlyphCollection, <:AbstractVector{<:Makie.GlyphCollection}}}}) + x::Text{<:Tuple{<:Union{<:Makie.GlyphCollection, <:AbstractVector{<:Makie.GlyphCollection}}}}) return cached_robj!(screen, scene, x) do gl_attributes glyphcollection = x[1] - transfunc = Makie.transform_func_obs(scene) + transfunc = Makie.transform_func_obs(scene) pos = gl_attributes[:position] space = get(gl_attributes, :space, Observable(:data)) # needs to happen before connect_camera! call markerspace = gl_attributes[:markerspace] @@ -389,8 +378,8 @@ xy_convert(x::AbstractArray{Float32}, n) = copy(x) xy_convert(x::AbstractArray, n) = el32convert(x) xy_convert(x, n) = Float32[LinRange(extrema(x)..., n + 1);] -function draw_atomic(screen::Screen, scene::Scene, x::Heatmap) - return cached_robj!(screen, scene, x) do gl_attributes +draw_atomic(screen::Screen, scene::Scene, x::Heatmap) = + cached_robj!(screen, scene, x) do gl_attributes t = Makie.transform_func_obs(scene) mat = x[3] space = get(gl_attributes, :space, :data) # needs to happen before connect_camera! call @@ -418,7 +407,7 @@ function draw_atomic(screen::Screen, scene::Scene, x::Heatmap) gl_attributes[:position_y] = Texture(ypos, minfilter = :nearest) # number of planes used to render the heatmap gl_attributes[:instances] = map(xpos, ypos) do x, y - (length(x)-1) * (length(y)-1) + (length(x) - 1) * (length(y) - 1) end interp = to_value(pop!(gl_attributes, :interpolate)) interp = interp ? :linear : :nearest @@ -433,21 +422,20 @@ function draw_atomic(screen::Screen, scene::Scene, x::Heatmap) return draw_heatmap(screen, tex, gl_attributes) end -end -function draw_atomic(screen::Screen, scene::Scene, x::Image) - return cached_robj!(screen, scene, x) do gl_attributes +draw_atomic(screen::Screen, scene::Scene, x::Image) = + cached_robj!(screen, scene, x) do gl_attributes mesh = const_lift(x[1], x[2]) do x, y r = to_range(x, y) x, y = minimum(r[1]), minimum(r[2]) xmax, ymax = maximum(r[1]), maximum(r[2]) - rect = Rect2f(x, y, xmax - x, ymax - y) + rect = Rect2f(x, y, xmax - x, ymax - y) points = decompose(Point2f, rect) faces = decompose(GLTriangleFace, rect) uv = map(decompose_uv(rect)) do uv - return 1f0 .- Vec2f(uv[2], uv[1]) + return 1.0f0 .- Vec2f(uv[2], uv[1]) end - return GeometryBasics.Mesh(meta(points; uv=uv), faces) + return GeometryBasics.Mesh(meta(points; uv = uv), faces) end gl_attributes[:color] = x[3] gl_attributes[:shading] = false @@ -455,7 +443,6 @@ function draw_atomic(screen::Screen, scene::Scene, x::Image) connect_camera!(gl_attributes, scene.camera) return mesh_inner(screen, mesh, transform_func_obs(x), gl_attributes, space) end -end function update_positions(mesh::GeometryBasics.Mesh, positions) points = coordinates(mesh) @@ -464,7 +451,7 @@ function update_positions(mesh::GeometryBasics.Mesh, positions) return GeometryBasics.Mesh(meta(positions; attr...), faces(mesh)) end -function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, space=:data) +function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, space = :data) # signals not supported for shading yet gl_attributes[:shading] = to_value(pop!(gl_attributes, :shading)) color = pop!(gl_attributes, :color) @@ -476,16 +463,16 @@ function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, space=:data) delete!(gl_attributes, :color_norm) elseif to_value(color) isa Makie.AbstractPattern img = lift(x -> el32convert(Makie.to_image(x)), color) - gl_attributes[:image] = ShaderAbstractions.Sampler(img, x_repeat=:repeat, minfilter=:nearest) + gl_attributes[:image] = ShaderAbstractions.Sampler(img, x_repeat = :repeat, minfilter = :nearest) get!(gl_attributes, :fetch_pixel, true) elseif to_value(color) isa AbstractMatrix{<:Colorant} gl_attributes[:image] = Texture(const_lift(el32convert, color), minfilter = interp) delete!(gl_attributes, :color_map) delete!(gl_attributes, :color_norm) - elseif to_value(color) isa AbstractMatrix{<: Number} + elseif to_value(color) isa AbstractMatrix{<:Number} gl_attributes[:image] = Texture(const_lift(el32convert, color), minfilter = interp) gl_attributes[:color] = nothing - elseif to_value(color) isa AbstractVector{<: Union{Number, Colorant}} + elseif to_value(color) isa AbstractVector{<:Union{Number, Colorant}} gl_attributes[:vertex_color] = lift(el32convert, color) else error("Unsupported color type: $(typeof(to_value(color)))") @@ -499,14 +486,13 @@ function mesh_inner(screen::Screen, mesh, transfunc, gl_attributes, space=:data) return draw_mesh(screen, mesh, gl_attributes) end -function draw_atomic(screen::Screen, scene::Scene, meshplot::Mesh) - return cached_robj!(screen, scene, meshplot) do gl_attributes +draw_atomic(screen::Screen, scene::Scene, meshplot::Mesh) = + cached_robj!(screen, scene, meshplot) do gl_attributes t = transform_func_obs(meshplot) space = get(gl_attributes, :space, :data) # needs to happen before connect_camera! call connect_camera!(gl_attributes, scene.camera) return mesh_inner(screen, meshplot[1], t, gl_attributes, space) end -end function draw_atomic(screen::Screen, scene::Scene, x::Surface) robj = cached_robj!(screen, scene, x) do gl_attributes @@ -514,16 +500,16 @@ function draw_atomic(screen::Screen, scene::Scene, x::Surface) img = nothing # signals not supported for shading yet # We automatically insert x[3] into the color channel, so if it's equal we don't need to do anything - if isa(to_value(color), AbstractMatrix{<: Number}) && to_value(color) !== to_value(x[3]) + if isa(to_value(color), AbstractMatrix{<:Number}) && to_value(color) !== to_value(x[3]) img = el32convert(color) elseif to_value(color) isa Makie.AbstractPattern pattern_img = lift(x -> el32convert(Makie.to_image(x)), color) - img = ShaderAbstractions.Sampler(pattern_img, x_repeat=:repeat, minfilter=:nearest) + img = ShaderAbstractions.Sampler(pattern_img, x_repeat = :repeat, minfilter = :nearest) haskey(gl_attributes, :fetch_pixel) || (gl_attributes[:fetch_pixel] = true) gl_attributes[:color_map] = nothing gl_attributes[:color] = nothing gl_attributes[:color_norm] = nothing - elseif isa(to_value(color), AbstractMatrix{<: Colorant}) + elseif isa(to_value(color), AbstractMatrix{<:Colorant}) img = color gl_attributes[:color_map] = nothing gl_attributes[:color] = nothing @@ -560,7 +546,7 @@ function draw_atomic(screen::Screen, scene::Scene, x::Surface) xpos = map(first, xypos) ypos = map(last, xypos) args = map((xpos, ypos, mat)) do arg - Texture(map(x-> convert(Array, el32convert(x)), arg); minfilter=:linear) + Texture(map(x -> convert(Array, el32convert(x)), arg); minfilter = :linear) end if isnothing(img) gl_attributes[:image] = args[3] @@ -568,7 +554,7 @@ function draw_atomic(screen::Screen, scene::Scene, x::Surface) return draw_surface(screen, args, gl_attributes) else gl_attributes[:ranges] = to_range.(to_value.(x[1:2])) - z_data = Texture(el32convert(x[3]); minfilter=:linear) + z_data = Texture(el32convert(x[3]); minfilter = :linear) if isnothing(img) gl_attributes[:image] = z_data end @@ -578,23 +564,21 @@ function draw_atomic(screen::Screen, scene::Scene, x::Surface) return robj end -function draw_atomic(screen::Screen, scene::Scene, vol::Volume) - robj = cached_robj!(screen, scene, vol) do gl_attributes - model = vol[:model] - x, y, z = vol[1], vol[2], vol[3] - gl_attributes[:model] = lift(model, x, y, z) do m, xyz... - mi = minimum.(xyz) - maxi = maximum.(xyz) - w = maxi .- mi - m2 = Mat4f( - w[1], 0, 0, 0, - 0, w[2], 0, 0, - 0, 0, w[3], 0, - mi[1], mi[2], mi[3], 1 - ) - return convert(Mat4f, m) * m2 - end - connect_camera!(gl_attributes, scene.camera) - return draw_volume(screen, vol[4], gl_attributes) +draw_atomic(screen::Screen, scene::Scene, vol::Volume) = robj = cached_robj!(screen, scene, vol) do gl_attributes + model = vol[:model] + x, y, z = vol[1], vol[2], vol[3] + gl_attributes[:model] = lift(model, x, y, z) do m, xyz... + mi = minimum.(xyz) + maxi = maximum.(xyz) + w = maxi .- mi + m2 = Mat4f( + w[1], 0, 0, 0, + 0, w[2], 0, 0, + 0, 0, w[3], 0, + mi[1], mi[2], mi[3], 1 + ) + return convert(Mat4f, m) * m2 end + connect_camera!(gl_attributes, scene.camera) + return draw_volume(screen, vol[4], gl_attributes) end diff --git a/GLMakie/src/events.jl b/GLMakie/src/events.jl index fced12ae9af..2fd689ee90a 100644 --- a/GLMakie/src/events.jl +++ b/GLMakie/src/events.jl @@ -22,19 +22,15 @@ Makie.window_open(scene::Scene, screen) = window_open(scene, to_native(screen)) function Makie.window_open(scene::Scene, window::GLFW.Window) event = scene.events.window_open - function windowclose(win) - @print_error begin - event[] = false - end + windowclose(win) = @print_error begin + event[] = false end disconnect!(window, window_open) event[] = isopen(window) GLFW.SetWindowCloseCallback(window, windowclose) end -function Makie.disconnect!(window::GLFW.Window, ::typeof(window_open)) - GLFW.SetWindowCloseCallback(window, nothing) -end +Makie.disconnect!(window::GLFW.Window, ::typeof(window_open)) = GLFW.SetWindowCloseCallback(window, nothing) function window_position(window::GLFW.Window) xy = GLFW.GetWindowPos(window) @@ -96,32 +92,24 @@ returns `Observable{NTuple{4, Int}}` Makie.mouse_buttons(scene::Scene, screen) = mouse_buttons(scene, to_native(screen)) function Makie.mouse_buttons(scene::Scene, window::GLFW.Window) event = scene.events.mousebutton - function mousebuttons(window, button, action, mods) - @print_error begin - event[] = MouseButtonEvent(Mouse.Button(Int(button)), Mouse.Action(Int(action))) - end + mousebuttons(window, button, action, mods) = @print_error begin + event[] = MouseButtonEvent(Mouse.Button(Int(button)), Mouse.Action(Int(action))) end disconnect!(window, mouse_buttons) GLFW.SetMouseButtonCallback(window, mousebuttons) end -function Makie.disconnect!(window::GLFW.Window, ::typeof(mouse_buttons)) - GLFW.SetMouseButtonCallback(window, nothing) -end +Makie.disconnect!(window::GLFW.Window, ::typeof(mouse_buttons)) = GLFW.SetMouseButtonCallback(window, nothing) Makie.keyboard_buttons(scene::Scene, screen) = keyboard_buttons(scene, to_native(screen)) function Makie.keyboard_buttons(scene::Scene, window::GLFW.Window) event = scene.events.keyboardbutton - function keyoardbuttons(window, button, scancode::Cint, action, mods::Cint) - @print_error begin - event[] = KeyEvent(Keyboard.Button(Int(button)), Keyboard.Action(Int(action))) - end + keyoardbuttons(window, button, scancode::Cint, action, mods::Cint) = @print_error begin + event[] = KeyEvent(Keyboard.Button(Int(button)), Keyboard.Action(Int(action))) end disconnect!(window, keyboard_buttons) GLFW.SetKeyCallback(window, keyoardbuttons) end -function Makie.disconnect!(window::GLFW.Window, ::typeof(keyboard_buttons)) - GLFW.SetKeyCallback(window, nothing) -end +Makie.disconnect!(window::GLFW.Window, ::typeof(keyboard_buttons)) = GLFW.SetKeyCallback(window, nothing) """ Registers a callback for drag and drop of files. @@ -131,18 +119,14 @@ returns `Observable{Vector{String}}`, which are absolute file paths Makie.dropped_files(scene::Scene, screen) = dropped_files(scene, to_native(screen)) function Makie.dropped_files(scene::Scene, window::GLFW.Window) event = scene.events.dropped_files - function droppedfiles(window, files) - @print_error begin - event[] = String.(files) - end + droppedfiles(window, files) = @print_error begin + event[] = String.(files) end disconnect!(window, dropped_files) event[] = String[] GLFW.SetDropCallback(window, droppedfiles) end -function Makie.disconnect!(window::GLFW.Window, ::typeof(dropped_files)) - GLFW.SetDropCallback(window, nothing) -end +Makie.disconnect!(window::GLFW.Window, ::typeof(dropped_files)) = GLFW.SetDropCallback(window, nothing) """ Registers a callback for keyboard unicode input. @@ -153,19 +137,15 @@ containing the pressed char. Is empty, if no key is pressed. Makie.unicode_input(scene::Scene, screen) = unicode_input(scene, to_native(screen)) function Makie.unicode_input(scene::Scene, window::GLFW.Window) event = scene.events.unicode_input - function unicodeinput(window, c::Char) - @print_error begin - event[] = c - end + unicodeinput(window, c::Char) = @print_error begin + event[] = c end disconnect!(window, unicode_input) # x = Char[]; sizehint!(x, 1) # event[] = x GLFW.SetCharCallback(window, unicodeinput) end -function Makie.disconnect!(window::GLFW.Window, ::typeof(unicode_input)) - GLFW.SetCharCallback(window, nothing) -end +Makie.disconnect!(window::GLFW.Window, ::typeof(unicode_input)) = GLFW.SetCharCallback(window, nothing) # TODO memoise? Or to bug ridden for the small performance gain? function retina_scaling_factor(w, fb) @@ -244,17 +224,13 @@ which is an x and y offset. Makie.scroll(scene::Scene, screen) = scroll(scene, to_native(screen)) function Makie.scroll(scene::Scene, window::GLFW.Window) event = scene.events.scroll - function scrollcb(window, w::Cdouble, h::Cdouble) - @print_error begin - event[] = (w, h) - end + scrollcb(window, w::Cdouble, h::Cdouble) = @print_error begin + event[] = (w, h) end disconnect!(window, scroll) GLFW.SetScrollCallback(window, scrollcb) end -function Makie.disconnect!(window::GLFW.Window, ::typeof(scroll)) - GLFW.SetScrollCallback(window, nothing) -end +Makie.disconnect!(window::GLFW.Window, ::typeof(scroll)) = GLFW.SetScrollCallback(window, nothing) """ Registers a callback for the focus of a window. @@ -265,19 +241,15 @@ which is true whenever the window has focus. Makie.hasfocus(scene::Scene, screen) = hasfocus(scene, to_native(screen)) function Makie.hasfocus(scene::Scene, window::GLFW.Window) event = scene.events.hasfocus - function hasfocuscb(window, focus::Bool) - @print_error begin - event[] = focus - end + hasfocuscb(window, focus::Bool) = @print_error begin + event[] = focus end disconnect!(window, hasfocus) GLFW.SetWindowFocusCallback(window, hasfocuscb) event[] = GLFW.GetWindowAttrib(window, GLFW.FOCUSED) nothing end -function Makie.disconnect!(window::GLFW.Window, ::typeof(hasfocus)) - GLFW.SetWindowFocusCallback(window, nothing) -end +Makie.disconnect!(window::GLFW.Window, ::typeof(hasfocus)) = GLFW.SetWindowFocusCallback(window, nothing) """ Registers a callback for if the mouse has entered the window. @@ -288,15 +260,11 @@ which is true whenever the cursor enters the window. Makie.entered_window(scene::Scene, screen) = entered_window(scene, to_native(screen)) function Makie.entered_window(scene::Scene, window::GLFW.Window) event = scene.events.entered_window - function enteredwindowcb(window, entered::Bool) - @print_error begin - event[] = entered - end + enteredwindowcb(window, entered::Bool) = @print_error begin + event[] = entered end disconnect!(window, entered_window) GLFW.SetCursorEnterCallback(window, enteredwindowcb) end -function Makie.disconnect!(window::GLFW.Window, ::typeof(entered_window)) - GLFW.SetCursorEnterCallback(window, nothing) -end +Makie.disconnect!(window::GLFW.Window, ::typeof(entered_window)) = GLFW.SetCursorEnterCallback(window, nothing) diff --git a/GLMakie/src/gl_backend.jl b/GLMakie/src/gl_backend.jl index 1fb7a003f02..44800d112b0 100644 --- a/GLMakie/src/gl_backend.jl +++ b/GLMakie/src/gl_backend.jl @@ -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 = 16.0f0, + mipmap = true ) # update the texture, whenever a new font is added to the atlas function callback(distance_field, rectangle) diff --git a/GLMakie/src/glshaders/image_like.jl b/GLMakie/src/glshaders/image_like.jl index ec21243a53f..6001d6927cc 100644 --- a/GLMakie/src/glshaders/image_like.jl +++ b/GLMakie/src/glshaders/image_like.jl @@ -13,26 +13,28 @@ end vol_depth_init(enable) = enable ? "float depth = 100000.0;" : "" vol_depth_default(enable) = enable ? "gl_FragDepth = gl_FragCoord.z;" : "" -function vol_depth_main(enable) +vol_depth_main(enable) = if enable """ vec4 frag_coord = projectionview * model * vec4(pos, 1); depth = min(depth, frag_coord.z / frag_coord.w); """ - else "" end -end -function vol_depth_write(enable) + else + "" + end +vol_depth_write(enable) = if enable "gl_FragDepth = depth == 100000.0 ? gl_FragDepth : 0.5 * depth + 0.5;" - else "" end -end + else + "" + end @nospecialize """ A matrix of Intensities will result in a contourf kind of plot """ function draw_heatmap(screen, main, data::Dict) - primitive = triangle_mesh(Rect2(0f0,0f0,1f0,1f0)) + primitive = triangle_mesh(Rect2(0.0f0, 0.0f0, 1.0f0, 1.0f0)) to_opengl_mesh!(data, primitive) @gen_defaults! data begin intensity = main => Texture @@ -42,8 +44,8 @@ function draw_heatmap(screen, main, data::Dict) color_map = nothing => Texture color_norm = nothing stroke_width::Float32 = 0.0f0 - levels::Float32 = 0f0 - stroke_color = RGBA{Float32}(0,0,0,0) + levels::Float32 = 0.0f0 + stroke_color = RGBA{Float32}(0, 0, 0, 0) transparency = false shader = GLVisualizeShader( screen, @@ -70,7 +72,7 @@ function draw_volume(screen, main::VolumeTypes, data::Dict) color = color_map === nothing ? default(RGBA, s) : nothing algorithm = MaximumIntensityProjection - absorption = 1f0 + absorption = 1.0f0 isovalue = 0.5f0 isorange = 0.01f0 enable_depth = true @@ -79,9 +81,9 @@ function draw_volume(screen, main::VolumeTypes, data::Dict) screen, "fragment_output.frag", "util.vert", "volume.vert", "volume.frag", view = Dict( - "depth_init" => vol_depth_init(to_value(enable_depth)), - "depth_default" => vol_depth_default(to_value(enable_depth)), - "depth_main" => vol_depth_main(to_value(enable_depth)), + "depth_init" => vol_depth_init(to_value(enable_depth)), + "depth_default" => vol_depth_default(to_value(enable_depth)), + "depth_main" => vol_depth_main(to_value(enable_depth)), "depth_write" => vol_depth_write(to_value(enable_depth)), "buffers" => output_buffers(screen, to_value(transparency)), "buffer_writes" => output_buffer_writes(screen, to_value(transparency)) diff --git a/GLMakie/src/glshaders/lines.jl b/GLMakie/src/glshaders/lines.jl index 323d21e3d01..3ecc8af667c 100644 --- a/GLMakie/src/glshaders/lines.jl +++ b/GLMakie/src/glshaders/lines.jl @@ -1,11 +1,11 @@ function sumlengths(points) T = eltype(points[1]) result = zeros(T, length(points)) - for i=1:length(points) - i0 = max(i-1,1) + for i in 1:length(points) + i0 = max(i - 1, 1) p1, p2 = points[i0], points[i] if !(any(map(isnan, p1)) || any(map(isnan, p2))) - result[i] = result[i0] + norm(p1-p2) + result[i] = result[i0] + norm(p1 - p2) else result[i] = result[i0] end @@ -14,41 +14,37 @@ function sumlengths(points) end intensity_convert(intensity, verts) = intensity -function intensity_convert(intensity::VecOrSignal{T}, verts) where T +intensity_convert(intensity::VecOrSignal{T}, verts) where T = if length(to_value(intensity)) == length(to_value(verts)) GLBuffer(intensity) else Texture(intensity) end -end -function intensity_convert_tex(intensity::VecOrSignal{T}, verts) where T +intensity_convert_tex(intensity::VecOrSignal{T}, verts) where T = if length(to_value(intensity)) == length(to_value(verts)) TextureBuffer(intensity) else Texture(intensity) 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 end return last(ps) - x end -function ticks(points, resolution) - Float16[gappy(x, points) for x = range(first(points), stop=last(points), length=resolution)] -end +ticks(points, resolution) = Float16[gappy(x, points) for x in range(first(points), stop = last(points), length = resolution)] @nospecialize -function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data::Dict) where T<:Point +function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data::Dict) where T <: Point p_vec = if isa(position, GPUArray) position else @@ -56,24 +52,24 @@ function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data:: end @gen_defaults! data begin - total_length::Int32 = const_lift(x-> Int32(length(x)), position) - vertex = p_vec => GLBuffer - intensity = nothing - color_map = nothing => Texture - color_norm = nothing - color = (color_map == nothing ? default(RGBA, s) : nothing) => GLBuffer - thickness::Float32 = 2f0 - pattern = nothing - fxaa = false + total_length::Int32 = const_lift(x -> Int32(length(x)), position) + vertex = p_vec => GLBuffer + intensity = nothing + color_map = nothing => Texture + color_norm = nothing + color = (color_map == nothing ? default(RGBA, s) : nothing) => GLBuffer + thickness::Float32 = 2.0f0 + pattern = nothing + fxaa = false # Duplicate the vertex indices on the ends of the line, as our geometry # shader in `layout(lines_adjacency)` mode requires each rendered # segment to have neighbouring vertices. - indices = const_lift(p_vec) do p + indices = const_lift(p_vec) do p len0 = length(p) - 1 return isempty(p) ? Cuint[] : Cuint[0; 0:len0; len0] end => to_index_buffer transparency = false - shader = GLVisualizeShader( + shader = GLVisualizeShader( screen, "fragment_output.frag", "util.vert", "lines.vert", "lines.geom", "lines.frag", view = Dict( @@ -81,9 +77,9 @@ function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data:: "buffer_writes" => output_buffer_writes(screen, to_value(transparency)) ) ) - gl_primitive = GL_LINE_STRIP_ADJACENCY - valid_vertex = const_lift(p_vec) do points - map(p-> Float32(all(isfinite, p)), points) + gl_primitive = GL_LINE_STRIP_ADJACENCY + valid_vertex = const_lift(p_vec) do points + map(p -> Float32(all(isfinite, p)), points) end => GLBuffer end if pattern !== nothing @@ -96,7 +92,7 @@ function draw_lines(screen, position::Union{VectorTypes{T}, MatTypes{T}}, data:: end @gen_defaults! data begin pattern_length = Float32(last(pattern)) - lastlen = const_lift(sumlengths, p_vec) => GLBuffer + lastlen = const_lift(sumlengths, p_vec) => GLBuffer maxlength = const_lift(last, lastlen) end end @@ -106,18 +102,18 @@ end function draw_linesegments(screen, positions::VectorTypes{T}, data::Dict) where T <: Point @gen_defaults! data begin - vertex = positions => GLBuffer - color = default(RGBA, s, 1) => GLBuffer - color_map = nothing => Texture - color_norm = nothing - thickness = 2f0 => GLBuffer - shape = RECTANGLE - pattern = nothing - fxaa = false - indices = const_lift(length, positions) => to_index_buffer + vertex = positions => GLBuffer + color = default(RGBA, s, 1) => GLBuffer + color_map = nothing => Texture + color_norm = nothing + thickness = 2.0f0 => GLBuffer + shape = RECTANGLE + pattern = nothing + fxaa = false + indices = const_lift(length, positions) => to_index_buffer # TODO update boundingbox transparency = false - shader = GLVisualizeShader( + shader = GLVisualizeShader( screen, "fragment_output.frag", "util.vert", "line_segment.vert", "line_segment.geom", "lines.frag", view = Dict( diff --git a/GLMakie/src/glshaders/mesh.jl b/GLMakie/src/glshaders/mesh.jl index 1cacd125aea..ff525f08e2f 100644 --- a/GLMakie/src/glshaders/mesh.jl +++ b/GLMakie/src/glshaders/mesh.jl @@ -1,18 +1,18 @@ -function to_opengl_mesh!(result, mesh_obs::TOrSignal{<: GeometryBasics.Mesh}) +function to_opengl_mesh!(result, mesh_obs::TOrSignal{<:GeometryBasics.Mesh}) m_attr = map(convert(Observable, mesh_obs)) do m return (m, GeometryBasics.attributes(m)) end - result[:faces] = indexbuffer(map(((m,_),)-> faces(m), m_attr)) - result[:vertices] = GLBuffer(map(((m,_),)-> decompose(Point, m), m_attr)) + result[:faces] = indexbuffer(map(((m, _),) -> faces(m), m_attr)) + result[:vertices] = GLBuffer(map(((m, _),) -> decompose(Point, m), m_attr)) attribs = m_attr[][2] - function to_buffer(name, target) + to_buffer(name, target) = 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)) @@ -22,7 +22,6 @@ function to_opengl_mesh!(result, mesh_obs::TOrSignal{<: GeometryBasics.Mesh}) error("unsupported attribute: $(name)") end end - end to_buffer(:color, :vertex_color) to_buffer(:uv, :texturecoordinates) to_buffer(:uvw, :texturecoordinates) @@ -38,7 +37,7 @@ function draw_mesh(screen, @nospecialize(mesh), data::Dict) to_opengl_mesh!(data, mesh) @gen_defaults! data begin shading = true - backlight = 0f0 + backlight = 0.0f0 vertex_color = nothing => GLBuffer texturecoordinates = Vec2f(0) image = nothing => Texture diff --git a/GLMakie/src/glshaders/particles.jl b/GLMakie/src/glshaders/particles.jl index 3ab7d85661f..e069faae3a1 100644 --- a/GLMakie/src/glshaders/particles.jl +++ b/GLMakie/src/glshaders/particles.jl @@ -1,31 +1,21 @@ using Makie: RectanglePacker -function to_meshcolor(color::TOrSignal{Vector{T}}) where T <: Colorant - TextureBuffer(color) -end +to_meshcolor(color::TOrSignal{Vector{T}}) where T <: Colorant = TextureBuffer(color) -function to_meshcolor(color::TOrSignal{Matrix{T}}) where T <: Colorant - Texture(color) -end -function to_meshcolor(color) - color -end +to_meshcolor(color::TOrSignal{Matrix{T}}) where T <: Colorant = Texture(color) +to_meshcolor(color) = color vec2quaternion(rotation::StaticVector{4}) = rotation -function vec2quaternion(r::StaticVector{2}) - vec2quaternion(Vec3f(r[1], r[2], 0)) -end -function vec2quaternion(rotation::StaticVector{3}) - Makie.rotation_between(Vec3f(0, 0, 1), Vec3f(rotation)) -end +vec2quaternion(r::StaticVector{2}) = vec2quaternion(Vec3f(r[1], r[2], 0)) +vec2quaternion(rotation::StaticVector{3}) = Makie.rotation_between(Vec3f(0, 0, 1), Vec3f(rotation)) vec2quaternion(rotation::Vec4f) = rotation -vec2quaternion(rotation::VectorTypes) = const_lift(x-> vec2quaternion.(x), rotation) +vec2quaternion(rotation::VectorTypes) = const_lift(x -> vec2quaternion.(x), rotation) vec2quaternion(rotation::Observable) = lift(vec2quaternion, rotation) -vec2quaternion(rotation::Makie.Quaternion)= Vec4f(rotation.data) -vec2quaternion(rotation)= vec2quaternion(to_rotation(rotation)) -GLAbstraction.gl_convert(rotation::Makie.Quaternion)= Vec4f(rotation.data) +vec2quaternion(rotation::Makie.Quaternion) = Vec4f(rotation.data) +vec2quaternion(rotation) = vec2quaternion(to_rotation(rotation)) +GLAbstraction.gl_convert(rotation::Makie.Quaternion) = Vec4f(rotation.data) to_pointsize(x::Number) = Float32(x) to_pointsize(x) = Float32(x[1]) struct PointSizeRender @@ -92,13 +82,13 @@ This is supposed to be the fastest way of displaying particles! """ function draw_pixel_scatter(screen, position::VectorTypes, data::Dict) @gen_defaults! data begin - vertex = position => GLBuffer - color_map = nothing => Texture - color = (color_map === nothing ? default(RGBA{Float32}, s) : nothing) => GLBuffer - color_norm = nothing - scale = 2f0 + vertex = position => GLBuffer + color_map = nothing => Texture + color = (color_map === nothing ? default(RGBA{Float32}, s) : nothing) => GLBuffer + color_norm = nothing + scale = 2.0f0 transparency = false - shader = GLVisualizeShader( + shader = GLVisualizeShader( screen, "fragment_output.frag", "dots.vert", "dots.frag", view = Dict( @@ -114,28 +104,28 @@ end function draw_scatter( screen, p::Tuple{TOrSignal{Matrix{C}}, VectorTypes{P}}, data::Dict - ) where {C <: Colorant, P <: Point} +) 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) + rectangles = map(x -> Rect2(0, 0, x...), sizes) rpack = RectanglePacker(Rect2(0, 0, maxdims...)) uv_coordinates = [push!(rpack, rect).area for rect in rectangles] - max_xy = mapreduce(maximum, (a,b)-> max.(a, b), uv_coordinates) + max_xy = mapreduce(maximum, (a, b) -> max.(a, b), uv_coordinates) texture_atlas = Texture(eltype(images[1]), (max_xy...,)) for (area, img) in zip(uv_coordinates, images) texture_atlas[area] = img #transfer to texture atlas @@ -166,34 +156,34 @@ function draw_scatter(screen, (marker, position), data) delete!(data, :rotation) @gen_defaults! data begin - shape = Cint(0) - position = position => GLBuffer - marker_offset = Vec3f(0) => GLBuffer; - scale = Vec2f(0) => GLBuffer - rotation = rot => GLBuffer - image = nothing => Texture + shape = Cint(0) + position = position => GLBuffer + marker_offset = Vec3f(0) => GLBuffer + scale = Vec2f(0) => GLBuffer + rotation = rot => GLBuffer + image = nothing => Texture end @gen_defaults! data begin - quad_offset = Vec2f(0) => GLBuffer - intensity = nothing => GLBuffer - color_map = nothing => Texture - color_norm = nothing - color = nothing => GLBuffer - - glow_color = RGBA{Float32}(0,0,0,0) => GLBuffer - stroke_color = RGBA{Float32}(0,0,0,0) => GLBuffer - stroke_width = 0f0 - glow_width = 0f0 + quad_offset = Vec2f(0) => GLBuffer + intensity = nothing => GLBuffer + color_map = nothing => Texture + color_norm = nothing + color = nothing => GLBuffer + + glow_color = RGBA{Float32}(0, 0, 0, 0) => GLBuffer + stroke_color = RGBA{Float32}(0, 0, 0, 0) => GLBuffer + stroke_width = 0.0f0 + glow_width = 0.0f0 uv_offset_width = Vec4f(0) => GLBuffer - distancefield = nothing => Texture - indices = const_lift(length, position) => to_index_buffer + distancefield = nothing => Texture + indices = const_lift(length, position) => to_index_buffer # rotation and billboard don't go along - billboard = rotation == Vec4f(0,0,0,1) => "if `billboard` == true, particles will always face camera" - fxaa = false - transparency = false - shader = GLVisualizeShader( + billboard = rotation == Vec4f(0, 0, 0, 1) => "if `billboard` == true, particles will always face camera" + fxaa = false + transparency = false + shader = GLVisualizeShader( screen, "fragment_output.frag", "util.vert", "sprites.geom", "sprites.vert", "distance_shape.frag", diff --git a/GLMakie/src/glshaders/surface.jl b/GLMakie/src/glshaders/surface.jl index c4d5961fc1a..c4c5ce8ebe9 100644 --- a/GLMakie/src/glshaders/surface.jl +++ b/GLMakie/src/glshaders/surface.jl @@ -1,7 +1,5 @@ -function position_calc(x...) - _position_calc(Iterators.filter(x->!isa(x, Nothing), x)...) -end +position_calc(x...) = _position_calc(Iterators.filter(x -> !isa(x, Nothing), x)...) function normal_calc(x::Bool, invert_normals::Bool = false) i = invert_normals ? "-" : "" @@ -12,7 +10,7 @@ function normal_calc(x::Bool, invert_normals::Bool = false) end end -function light_calc(x::Bool) +light_calc(x::Bool) = if x """ vec3 L = normalize(o_lightdir); @@ -24,65 +22,56 @@ function light_calc(x::Bool) else "" end -end -function _position_calc( - 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); - vec2 index01 = vec2(index2D) / (vec2(dims)-1.0); - pos = vec3( - texelFetch(position_x, index2D, 0).x, - texelFetch(position_y, index2D, 0).x, - texelFetch(position_z, index2D, 0).x - ); - """ -end +_position_calc( + 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); + vec2 index01 = vec2(index2D) / (vec2(dims)-1.0); + pos = vec3( + texelFetch(position_x, index2D, 0).x, + texelFetch(position_y, index2D, 0).x, + texelFetch(position_z, index2D, 0).x + ); + """ -function _position_calc( - 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); - vec2 index01 = vec2(index2D) / (vec2(dims)-1.0); - pos = vec3( - texelFetch(position_x, index2D.x, 0).x, - texelFetch(position_y, index2D.y, 0).x, - texelFetch(position_z, index2D, 0).x - ); - """ -end +_position_calc( + 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); + vec2 index01 = vec2(index2D) / (vec2(dims)-1.0); + pos = vec3( + texelFetch(position_x, index2D.x, 0).x, + texelFetch(position_y, index2D.y, 0).x, + texelFetch(position_z, index2D, 0).x + ); + """ -function _position_calc( - position_xyz::VectorTypes{T}, target::Type{TextureBuffer} - ) where T <: StaticVector - "pos = texelFetch(position, index).xyz;" -end +_position_calc( + position_xyz::VectorTypes{T}, target::Type{TextureBuffer} +) where T <: StaticVector = "pos = texelFetch(position, index).xyz;" 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 - """ - int index1D = index + offseti.x + offseti.y * dims.x + (index/(dims.x-1)); - ivec2 index2D = ind2sub(dims, index1D); - vec2 index01 = vec2(index2D) / (vec2(dims)-1.0); - float height = texture(position_z, index01).x; - pos = vec3(grid_pos(position, index01), height); - """ -end +_position_calc( + 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); + vec2 index01 = vec2(index2D) / (vec2(dims)-1.0); + float height = texture(position_z, index01).x; + pos = vec3(grid_pos(position, index01), height); + """ @nospecialize # surface(::Matrix, ::Matrix, ::Matrix) @@ -108,7 +97,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(0.0f0, 0.0f0, 1.0f0, 1.0f0)) to_opengl_mesh!(data, primitive) @gen_defaults! data begin scale = nothing @@ -120,7 +109,7 @@ function draw_surface(screen, main, data::Dict) shading = true normal = shading invert_normals = false - backlight = 0f0 + backlight = 0.0f0 end @gen_defaults! data begin color = nothing => Texture @@ -134,7 +123,7 @@ function draw_surface(screen, main, data::Dict) lowclip = RGBAf(0, 0, 0, 0) uv_scale = Vec2f(1) - instances = const_lift(x->(size(x,1)-1) * (size(x,2)-1), main) => "number of planes used to render the surface" + instances = const_lift(x -> (size(x, 1) - 1) * (size(x, 2) - 1), main) => "number of planes used to render the surface" transparency = false shader = GLVisualizeShader( screen, diff --git a/GLMakie/src/glshaders/visualize_interface.jl b/GLMakie/src/glshaders/visualize_interface.jl index 1633084e6b6..226387199d3 100644 --- a/GLMakie/src/glshaders/visualize_interface.jl +++ b/GLMakie/src/glshaders/visualize_interface.jl @@ -1,17 +1,17 @@ @enum CubeSides TOP BOTTOM FRONT BACK RIGHT LEFT -struct Grid{N,T <: AbstractRange} - dims::NTuple{N,T} +struct Grid{N, T <: AbstractRange} + dims::NTuple{N, T} end -Base.ndims(::Grid{N,T}) where {N,T} = N +Base.ndims(::Grid{N, T}) where {N, T} = N Grid(ranges::AbstractRange...) = Grid(ranges) -function Grid(a::Array{T,N}) where {N,T} - s = Vec{N,Float32}(size(a)) +function Grid(a::Array{T, N}) where {N, T} + s = Vec{N, Float32}(size(a)) 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 @@ -23,40 +23,38 @@ Due to the approach, the tuple `ranges` can consist of NTuple(2, T) and all kind of range types. The constructor will make sure that all ranges match 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( +function Grid(a::AbstractArray{T, N}, ranges::Tuple) where {T, N} + 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 Base.length(p::Grid) = prod(size(p)) Base.size(p::Grid) = map(length, p.dims) -function Base.getindex(p::Grid{N,T}, i) where {N,T} +function Base.getindex(p::Grid{N, T}, i) where {N, T} inds = ind2sub(size(p), i) - return Point{N,eltype(T)}(ntuple(Val(N)) do i + return Point{N, eltype(T)}(ntuple(Val(N)) do i p.dims[i][inds[i]] 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" -function GLAbstraction.gl_convert_struct(g::Grid{N,T}, uniform_name::Symbol) where {N,T} - return Dict{Symbol,Any}( - Symbol("$uniform_name.start") => Vec{N,Float32}(minimum.(g.dims)), - Symbol("$uniform_name.stop") => Vec{N,Float32}(maximum.(g.dims)), - Symbol("$uniform_name.lendiv") => Vec{N,Cint}(length.(g.dims) .- 1), - Symbol("$uniform_name.dims") => Vec{N,Cint}(map(length, g.dims)) - ) -end -function GLAbstraction.gl_convert_struct(g::Grid{1,T}, uniform_name::Symbol) where T +GLAbstraction.toglsltype_string(t::Grid{N, T}) where {N, T} = "uniform Grid$(N)D" +GLAbstraction.gl_convert_struct(g::Grid{N, T}, uniform_name::Symbol) where {N, T} = Dict{Symbol, Any}( + Symbol("$uniform_name.start") => Vec{N, Float32}(minimum.(g.dims)), + Symbol("$uniform_name.stop") => Vec{N, Float32}(maximum.(g.dims)), + Symbol("$uniform_name.lendiv") => Vec{N, Cint}(length.(g.dims) .- 1), + Symbol("$uniform_name.dims") => Vec{N, Cint}(map(length, g.dims)) +) +function GLAbstraction.gl_convert_struct(g::Grid{1, T}, uniform_name::Symbol) where T x = g.dims[1] - return Dict{Symbol,Any}( + return Dict{Symbol, Any}( Symbol("$uniform_name.start") => Float32(minimum(x)), Symbol("$uniform_name.stop") => Float32(maximum(x)), Symbol("$uniform_name.lendiv") => Cint(length(x) - 1), @@ -67,11 +65,11 @@ end struct GLVisualizeShader <: AbstractLazyShader screen::Screen paths::Tuple - kw_args::Dict{Symbol,Any} + 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" @@ -84,9 +82,7 @@ struct GLVisualizeShader <: AbstractLazyShader end end -function GLAbstraction.gl_convert(shader::GLVisualizeShader, data) - GLAbstraction.gl_convert(shader.screen.shader_cache, shader, data) -end +GLAbstraction.gl_convert(shader::GLVisualizeShader, data) = GLAbstraction.gl_convert(shader.screen.shader_cache, shader, data) function assemble_shader(data) shader = data[:shader]::GLVisualizeShader @@ -100,7 +96,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 @@ -132,23 +128,19 @@ 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 - indexbuffer(lift(x -> Cuint.(x .- 1), x)) -end +to_index_buffer(x::Observable{<:AbstractVector{I}}) where I <: Integer = indexbuffer(lift(x -> Cuint.(x .- 1), x)) """ 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}} - indexbuffer(x) -end +to_index_buffer(x::VectorTypes{I}) where I <: Union{GLuint, LineFace{GLIndex}} = indexbuffer(x) to_index_buffer(x) = error( "Not a valid index type: $(typeof(x)). Please choose from Int, Vector{UnitRange{Int}}, Vector{Int} or a signal of either of them" ) -function output_buffers(screen::Screen, transparency = false) +output_buffers(screen::Screen, transparency = false) = if transparency """ layout(location=2) out float coverage; @@ -161,9 +153,8 @@ function output_buffers(screen::Screen, transparency = false) else "" end -end -function output_buffer_writes(screen::Screen, transparency = false) +output_buffer_writes(screen::Screen, transparency = false) = if transparency scale = screen.config.transparency_weight_scale """ @@ -181,4 +172,3 @@ function output_buffer_writes(screen::Screen, transparency = false) else "fragment_color = color;" end -end diff --git a/GLMakie/src/glwindow.jl b/GLMakie/src/glwindow.jl index d643f609c5b..7dc7522ecda 100644 --- a/GLMakie/src/glwindow.jl +++ b/GLMakie/src/glwindow.jl @@ -24,14 +24,10 @@ Base.size(fb::GLFramebuffer) = size(fb.buffers[:color]) Base.haskey(fb::GLFramebuffer, key::Symbol) = haskey(fb.buffers, key) Base.getindex(fb::GLFramebuffer, key::Symbol) = fb.buffer_ids[key] => fb.buffers[key] -function getfallback(fb::GLFramebuffer, key::Symbol, fallback_key::Symbol) - haskey(fb, key) ? fb[key] : fb[fallback_key] -end +getfallback(fb::GLFramebuffer, key::Symbol, fallback_key::Symbol) = haskey(fb, key) ? fb[key] : fb[fallback_key] -function attach_framebuffer(t::Texture{T, 2}, attachment) where T - glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, t.id, 0) -end +attach_framebuffer(t::Texture{T, 2}, attachment) where T = glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, GL_TEXTURE_2D, t.id, 0) # attach texture as color attachment with automatic id picking function attach_colorbuffer!(fb::GLFramebuffer, key::Symbol, t::Texture{T, 2}) where T @@ -101,20 +97,20 @@ function GLFramebuffer(fb_size::NTuple{2, Int}) # track of the buffer ids that are already in use. We may also want to reuse # buffers so we give them names for easy fetching. buffer_ids = Dict( - :color => GL_COLOR_ATTACHMENT0, + :color => GL_COLOR_ATTACHMENT0, :objectid => GL_COLOR_ATTACHMENT1, :HDR_color => GL_COLOR_ATTACHMENT2, :OIT_weight => GL_COLOR_ATTACHMENT3, - :depth => GL_DEPTH_ATTACHMENT, - :stencil => GL_STENCIL_ATTACHMENT, + :depth => GL_DEPTH_ATTACHMENT, + :stencil => GL_STENCIL_ATTACHMENT, ) buffers = Dict( - :color => color_buffer, + :color => color_buffer, :objectid => objectid_buffer, :HDR_color => HDR_color_buffer, :OIT_weight => OIT_weight_buffer, - :depth => depth_buffer, - :stencil => depth_buffer + :depth => depth_buffer, + :stencil => depth_buffer ) return GLFramebuffer( @@ -126,7 +122,7 @@ end function Base.resize!(fb::GLFramebuffer, window_size) ws = Int.((window_size[1], window_size[2])) - if ws != size(fb) && all(x-> x > 0, window_size) + if ws != size(fb) && all(x -> x > 0, window_size) for (name, buffer) in fb.buffers resize_nocopy!(buffer, ws) end @@ -169,13 +165,9 @@ function GLContext() return GLContext(context, version, glsl_version, unique_context_counter()) end -function ShaderAbstractions.native_switch_context!(x::GLFW.Window) - GLFW.MakeContextCurrent(x) -end +ShaderAbstractions.native_switch_context!(x::GLFW.Window) = GLFW.MakeContextCurrent(x) -function ShaderAbstractions.native_context_alive(x::GLFW.Window) - GLFW.is_initialized() && !was_destroyed(x) -end +ShaderAbstractions.native_context_alive(x::GLFW.Window) = GLFW.is_initialized() && !was_destroyed(x) function destroy!(nw::GLFW.Window) was_current = ShaderAbstractions.is_current_context(nw) diff --git a/GLMakie/src/picking.jl b/GLMakie/src/picking.jl index a444e8c7998..94ace1f829d 100644 --- a/GLMakie/src/picking.jl +++ b/GLMakie/src/picking.jl @@ -51,7 +51,7 @@ function Makie.pick(scene::Scene, screen::Screen, xy::Vec{2, Float64}) end end -function Makie.pick(scene::Scene, screen::Screen, rect::Rect2i) +Makie.pick(scene::Scene, screen::Screen, rect::Rect2i) = map(pick_native(screen, rect)) do sid if haskey(screen.cache2plot, sid.id) (screen.cache2plot[sid.id], sid.index) @@ -59,7 +59,6 @@ function Makie.pick(scene::Scene, screen::Screen, rect::Rect2i) (nothing, sid.index) end end -end # Skips one set of allocations @@ -70,14 +69,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 @@ -101,16 +101,17 @@ function Makie.pick_sorted(scene::Scene, screen::Screen, xy, range) end x0, y0 = max.(1, floor.(Int, xy .- range)) x1, y1 = min.([w, h], ceil.(Int, xy .+ range)) - dx = x1 - x0; dy = y1 - y0 + dx = x1 - x0 + dy = y1 - y0 picks = pick_native(screen, Rect2i(x0, y0, dx, dy)) selected = filter(x -> x.id > 0 && haskey(screen.cache2plot, x.id), unique(vec(picks))) distances = Float32[range^2 for _ in selected] - x, y = xy .+ 1 .- Vec2f(x0, y0) + x, y = xy .+ 1 .- Vec2f(x0, y0) for i in 1:dx, j in 1:dy if picks[i, j].id > 0 - d = (x-i)^2 + (y-j)^2 + d = (x - i)^2 + (y - j)^2 i = findfirst(isequal(picks[i, j]), selected) if i === nothing @warn "This shouldn't happen..." diff --git a/GLMakie/src/postprocessing.jl b/GLMakie/src/postprocessing.jl index 3c295d158a6..6cfba3108e2 100644 --- a/GLMakie/src/postprocessing.jl +++ b/GLMakie/src/postprocessing.jl @@ -16,7 +16,7 @@ function (sp::PostprocessPrerender)() return end -rcpframe(x) = 1f0 ./ Vec2f(x[1], x[2]) +rcpframe(x) = 1.0f0 ./ Vec2f(x[1], x[2]) struct PostProcessor{F} robjs::Vector{RenderObject} @@ -24,9 +24,7 @@ struct PostProcessor{F} constructor::Any end -function empty_postprocessor(args...; kwargs...) - PostProcessor(RenderObject[], screen -> nothing, empty_postprocessor) -end +empty_postprocessor(args...; kwargs...) = PostProcessor(RenderObject[], screen -> nothing, empty_postprocessor) function OIT_postprocessor(framebuffer, shader_cache) @@ -207,7 +205,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 diff --git a/GLMakie/src/rendering.jl b/GLMakie/src/rendering.jl index 811bb8094f0..ce60a2f980d 100644 --- a/GLMakie/src/rendering.jl +++ b/GLMakie/src/rendering.jl @@ -28,7 +28,7 @@ const selection_queries = Function[] """ Renders a single frame of a `window` """ -function render_frame(screen::Screen; resize_buffers=true) +function render_frame(screen::Screen; resize_buffers = true) nw = to_native(screen) ShaderAbstractions.switch_context!(nw) function sortby(x) diff --git a/GLMakie/src/screen.jl b/GLMakie/src/screen.jl index 9f732df3b22..babf54d4112 100644 --- a/GLMakie/src/screen.jl +++ b/GLMakie/src/screen.jl @@ -60,25 +60,25 @@ mutable struct ScreenConfig transparency_weight_scale::Float32 function ScreenConfig( - # Renderloop - renderloop::Union{Makie.Automatic, Function}, - pause_renderloop::Bool, - vsync::Bool, - render_on_demand::Bool, - framerate::Number, - # GLFW window attributes - float::Bool, - focus_on_show::Bool, - decorated::Bool, - title::AbstractString, - fullscreen::Bool, - debugging::Bool, - monitor::Union{Nothing, GLFW.Monitor}, - # Preproccessor - oit::Bool, - fxaa::Bool, - ssao::Bool, - transparency_weight_scale::Number) + # Renderloop + renderloop::Union{Makie.Automatic, Function}, + pause_renderloop::Bool, + vsync::Bool, + render_on_demand::Bool, + framerate::Number, + # GLFW window attributes + float::Bool, + focus_on_show::Bool, + decorated::Bool, + title::AbstractString, + fullscreen::Bool, + debugging::Bool, + monitor::Union{Nothing, GLFW.Monitor}, + # Preproccessor + oit::Bool, + fxaa::Bool, + ssao::Bool, + transparency_weight_scale::Number) return new( # Renderloop @@ -115,7 +115,7 @@ Note, that the `screen_config` can also be set permanently via `Makie.set_theme! $(Base.doc(ScreenConfig)) """ -function activate!(; inline=LAST_INLINE[], screen_config...) +function activate!(; inline = LAST_INLINE[], screen_config...) if haskey(screen_config, :pause_rendering) error("pause_rendering got renamed to pause_renderloop.") end @@ -162,21 +162,19 @@ mutable struct Screen{GLWindow} <: MakieScreen requires_update::Bool function Screen( - glscreen::GLWindow, - shader_cache::GLAbstraction.ShaderCache, - framebuffer::GLFramebuffer, - config::Union{Nothing, ScreenConfig}, - stop_renderloop::Bool, - rendertask::Union{Nothing, Task}, - - screen2scene::Dict{WeakRef, ScreenID}, - screens::Vector{ScreenArea}, - renderlist::Vector{Tuple{ZIndex, ScreenID, RenderObject}}, - postprocessors::Vector{PostProcessor}, - cache::Dict{UInt64, RenderObject}, - cache2plot::Dict{UInt32, AbstractPlot}, - reuse::Bool - ) where {GLWindow} + glscreen::GLWindow, + shader_cache::GLAbstraction.ShaderCache, + framebuffer::GLFramebuffer, + config::Union{Nothing, ScreenConfig}, + stop_renderloop::Bool, + rendertask::Union{Nothing, Task}, screen2scene::Dict{WeakRef, ScreenID}, + screens::Vector{ScreenArea}, + renderlist::Vector{Tuple{ZIndex, ScreenID, RenderObject}}, + postprocessors::Vector{PostProcessor}, + cache::Dict{UInt64, RenderObject}, + cache2plot::Dict{UInt32, AbstractPlot}, + reuse::Bool + ) where {GLWindow} s = size(framebuffer) screen = new{GLWindow}( @@ -196,20 +194,18 @@ end # gets removed in destroy!(screen) const ALL_SCREENS = Set{Screen}() -function empty_screen(debugging::Bool; reuse=true) +function empty_screen(debugging::Bool; reuse = true) windowhints = [ - (GLFW.SAMPLES, 0), - (GLFW.DEPTH_BITS, 0), + (GLFW.SAMPLES, 0), + (GLFW.DEPTH_BITS, 0), # SETTING THE ALPHA BIT IS REALLY IMPORTANT ON OSX, SINCE IT WILL JUST KEEP SHOWING A BLACK SCREEN # WITHOUT ANY ERROR -.- - (GLFW.ALPHA_BITS, 8), - (GLFW.RED_BITS, 8), - (GLFW.GREEN_BITS, 8), - (GLFW.BLUE_BITS, 8), - - (GLFW.STENCIL_BITS, 0), - (GLFW.AUX_BUFFERS, 0), + (GLFW.ALPHA_BITS, 8), + (GLFW.RED_BITS, 8), + (GLFW.GREEN_BITS, 8), + (GLFW.BLUE_BITS, 8), (GLFW.STENCIL_BITS, 0), + (GLFW.AUX_BUFFERS, 0), ] resolution = (10, 10) window = try @@ -290,9 +286,9 @@ const SINGLETON_SCREEN = Screen[] function singleton_screen(debugging::Bool) if !isempty(SINGLETON_SCREEN) screen = SINGLETON_SCREEN[1] - close(screen; reuse=false) + close(screen; reuse = false) else - screen = empty_screen(debugging; reuse=false) + screen = empty_screen(debugging; reuse = false) push!(SINGLETON_SCREEN, screen) end return reopen!(screen) @@ -300,11 +296,9 @@ end const GLFW_FOCUS_ON_SHOW = 0x0002000C -function Makie.apply_screen_config!(screen::Screen, config::ScreenConfig, scene::Scene, args...) - apply_config!(screen, config) -end +Makie.apply_screen_config!(screen::Screen, config::ScreenConfig, scene::Scene, args...) = apply_config!(screen, config) -function apply_config!(screen::Screen, config::ScreenConfig; visible::Bool=true, start_renderloop::Bool=true) +function apply_config!(screen::Screen, config::ScreenConfig; visible::Bool = true, start_renderloop::Bool = true) ShaderAbstractions.switch_context!(screen.glscreen) glw = screen.glscreen ShaderAbstractions.switch_context!(glw) @@ -345,18 +339,18 @@ function apply_config!(screen::Screen, config::ScreenConfig; visible::Bool=true, end function Screen(; - resolution::Union{Nothing, Tuple{Int, Int}} = nothing, - visible = true, - start_renderloop = true, - screen_config... - ) + resolution::Union{Nothing, Tuple{Int, Int}} = nothing, + visible = true, + start_renderloop = true, + screen_config... +) # Screen config is managed by the current active theme, so managed by Makie config = Makie.merge_screen_config(ScreenConfig, screen_config) screen = screen_from_pool(config.debugging) if !isnothing(resolution) resize!(screen, resolution...) end - apply_config!(screen, config; visible=visible, start_renderloop=start_renderloop) + apply_config!(screen, config; visible = visible, start_renderloop = start_renderloop) return screen end @@ -373,31 +367,31 @@ function display_scene!(screen::Screen, scene::Scene) return end -function Screen(scene::Scene; visible=true, start_renderloop=true, screen_config...) +function Screen(scene::Scene; visible = true, start_renderloop = true, screen_config...) config = Makie.merge_screen_config(ScreenConfig, screen_config) - return Screen(scene, config; visible=visible, start_renderloop=start_renderloop) + return Screen(scene, config; visible = visible, start_renderloop = start_renderloop) end # Open an interactive window -function Screen(scene::Scene, config::ScreenConfig; visible=true, start_renderloop=true) +function Screen(scene::Scene, config::ScreenConfig; visible = true, start_renderloop = true) screen = singleton_screen(config.debugging) - apply_config!(screen, config; visible=visible, start_renderloop=start_renderloop) + apply_config!(screen, config; visible = visible, start_renderloop = start_renderloop) display_scene!(screen, scene) return screen end # Screen to save a png/jpeg to file or io -function Screen(scene::Scene, config::ScreenConfig, io::Union{Nothing, String, IO}, typ::MIME; visible=false, start_renderloop=false) +function Screen(scene::Scene, config::ScreenConfig, io::Union{Nothing, String, IO}, typ::MIME; visible = false, start_renderloop = false) screen = singleton_screen(config.debugging) - apply_config!(screen, config; visible=visible, start_renderloop=start_renderloop) + apply_config!(screen, config; visible = visible, start_renderloop = start_renderloop) display_scene!(screen, scene) return screen end # Screen that is efficient for `colorbuffer(screen)` -function Screen(scene::Scene, config::ScreenConfig, ::Makie.ImageStorageFormat; visible=false, start_renderloop=false) +function Screen(scene::Scene, config::ScreenConfig, ::Makie.ImageStorageFormat; visible = false, start_renderloop = false) screen = singleton_screen(config.debugging) - apply_config!(screen, config; visible=visible, start_renderloop=start_renderloop) + apply_config!(screen, config; visible = visible, start_renderloop = start_renderloop) display_scene!(screen, scene) return screen end @@ -448,7 +442,7 @@ function Base.delete!(screen::Screen, scene::Scene) # Remap scene IDs to a continuous range by replacing the largest ID # with the one that got removed - if deleted_id-1 != length(screen.screens) + if deleted_id - 1 != length(screen.screens) key, max_id = first(screen.screen2scene) for p in screen.screen2scene if p[2] > max_id @@ -507,7 +501,7 @@ function Base.delete!(screen::Screen, scene::Scene, plot::AbstractPlot) renderobject = get(screen.cache, objectid(plot), nothing) if !isnothing(renderobject) destroy!(renderobject) - filter!(x-> x[3] !== renderobject, screen.renderlist) + filter!(x -> x[3] !== renderobject, screen.renderlist) delete!(screen.cache2plot, renderobject.id) end delete!(screen.cache, objectid(plot)) @@ -540,7 +534,7 @@ function Base.empty!(screen::Screen) end function destroy!(screen::Screen) - close(screen; reuse=false) + close(screen; reuse = false) # wait for rendertask to finish # otherwise, during rendertask clean up we may run into a destroyed window wait(screen) @@ -560,9 +554,9 @@ end Closes screen and emptying it. Doesn't destroy the screen and instead frees it for being re-used again, if `reuse=true`. """ -function Base.close(screen::Screen; reuse=true) +function Base.close(screen::Screen; reuse = true) set_screen_visibility!(screen, false) - stop_renderloop!(screen; close_after_renderloop=false) + stop_renderloop!(screen; close_after_renderloop = false) screen.window_open[] = false empty!(screen) if reuse && screen.reuse @@ -590,7 +584,7 @@ function closeall() return end -function resize_native!(window::GLFW.Window, resolution...) +resize_native!(window::GLFW.Window, resolution...) = if isopen(window) ShaderAbstractions.switch_context!(window) oldsize = windowsize(window) @@ -601,7 +595,6 @@ function resize_native!(window::GLFW.Window, resolution...) end GLFW.SetWindowSize(window, round(Int, w), round(Int, h)) end -end function Base.resize!(screen::Screen, w, h) nw = to_native(screen) @@ -633,7 +626,7 @@ heatmap(depth_color, colormap=:grays) """ function depthbuffer(screen::Screen) ShaderAbstractions.switch_context!(screen.glscreen) - render_frame(screen, resize_buffers=false) # let it render + render_frame(screen, resize_buffers = false) # let it render glFinish() # block until opengl is done rendering source = screen.framebuffer.buffers[:depth] depth = Matrix{Float32}(undef, size(source)) @@ -653,7 +646,7 @@ function Makie.colorbuffer(screen::Screen, format::Makie.ImageStorageFormat = Ma # we still need to poll though, to get all the newest events! # GLFW.PollEvents() # keep current buffer size to allows larger-than-window renders - render_frame(screen, resize_buffers=false) # let it render + render_frame(screen, resize_buffers = false) # let it render glFinish() # block until opengl is done rendering if size(ctex) != size(screen.framecache) screen.framecache = Matrix{RGB{N0f8}}(undef, size(ctex)) @@ -726,11 +719,9 @@ function display_loading_image(screen::Screen) end end -function renderloop_running(screen::Screen) - return !screen.stop_renderloop && !isnothing(screen.rendertask) && !istaskdone(screen.rendertask) -end +renderloop_running(screen::Screen) = !screen.stop_renderloop && !isnothing(screen.rendertask) && !istaskdone(screen.rendertask) -function start_renderloop!(screen::Screen) +start_renderloop!(screen::Screen) = if renderloop_running(screen) screen.config.pause_renderloop = false return @@ -746,13 +737,10 @@ function start_renderloop!(screen::Screen) error("What's up with task $(task)") end end -end -function pause_renderloop!(screen::Screen) - screen.config.pause_renderloop = true -end +pause_renderloop!(screen::Screen) = screen.config.pause_renderloop = true -function stop_renderloop!(screen::Screen; close_after_renderloop=screen.close_after_renderloop) +function stop_renderloop!(screen::Screen; close_after_renderloop = screen.close_after_renderloop) # don't double close when stopping renderloop c = screen.close_after_renderloop screen.close_after_renderloop = close_after_renderloop @@ -770,9 +758,7 @@ function stop_renderloop!(screen::Screen; close_after_renderloop=screen.close_af return end -function set_framerate!(screen::Screen, fps=30) - screen.config.framerate = fps -end +set_framerate!(screen::Screen, fps = 30) = screen.config.framerate = fps function refreshwindowcb(window, screen) screen.render_tick[] = nothing @@ -782,10 +768,11 @@ function refreshwindowcb(window, screen) end # TODO add render_tick event to scene events -function vsynced_renderloop(screen) +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 @@ -793,12 +780,12 @@ function vsynced_renderloop(screen) GLFW.SwapBuffers(to_native(screen)) yield() end -end -function fps_renderloop(screen::Screen) +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 @@ -814,7 +801,6 @@ function fps_renderloop(screen::Screen) yield() end end -end function requires_update(screen::Screen) if screen.requires_update @@ -827,7 +813,7 @@ function requires_update(screen::Screen) return false end -function on_demand_renderloop(screen::Screen) +on_demand_renderloop(screen::Screen) = while isopen(screen) && !screen.stop_renderloop t = time_ns() time_per_frame = 1.0 / screen.config.framerate @@ -846,7 +832,6 @@ function on_demand_renderloop(screen::Screen) yield() end end -end function renderloop(screen) isopen(screen) || error("Screen most be open to run renderloop!") @@ -864,14 +849,14 @@ function renderloop(screen) fps_renderloop(screen) end catch e - @warn "error in renderloop" exception=(e, Base.catch_backtrace()) + @warn "error in renderloop" exception = (e, Base.catch_backtrace()) rethrow(e) end if screen.close_after_renderloop try close(screen) catch e - @warn "error closing screen" exception=(e, Base.catch_backtrace()) + @warn "error closing screen" exception = (e, Base.catch_backtrace()) end end screen.rendertask = nothing @@ -880,7 +865,7 @@ end function plot2robjs(screen::Screen, plot) plots = Makie.flatten_plots(plot) - return map(x-> screen.cache[objectid(x)], plots) + return map(x -> screen.cache[objectid(x)], plots) end export plot2robjs diff --git a/GLMakie/test/glmakie_refimages.jl b/GLMakie/test/glmakie_refimages.jl index 5a386d5d0e8..dbd6e5499cf 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 @@ -71,19 +71,18 @@ end end @reference_test "Explicit frame rendering" begin - function update_loop(m, buff, screen) - for i = 1:20 + update_loop(m, buff, screen) = + for i in 1:20 GLFW.PollEvents() - buff .= RNG.rand.(Point3f) .* 20f0 + buff .= RNG.rand.(Point3f) .* 20.0f0 m[1] = buff GLMakie.render_frame(screen) GLFW.SwapBuffers(GLMakie.to_native(screen)) glFinish() end - end - fig, ax, meshplot = meshscatter(RNG.rand(Point3f, 10^4) .* 20f0) - screen = display(GLMakie.Screen(;renderloop=(screen) -> nothing, start_renderloop=false), fig.scene) - buff = RNG.rand(Point3f, 10^4) .* 20f0; + fig, ax, meshplot = meshscatter(RNG.rand(Point3f, 10^4) .* 20.0f0) + screen = display(GLMakie.Screen(; renderloop = (screen) -> nothing, start_renderloop = false), fig.scene) + buff = RNG.rand(Point3f, 10^4) .* 20.0f0 update_loop(meshplot, buff, screen) @test isnothing(screen.rendertask) GLMakie.destroy!(screen) @@ -96,10 +95,10 @@ 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)) + 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), 6.0f0)) 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), 6f0)) + mesh!(right, Sphere(Point3f(5), 6.0f0)) fig end diff --git a/GLMakie/test/runtests.jl b/GLMakie/test/runtests.jl index d73329c6825..b32578ffdfb 100644 --- a/GLMakie/test/runtests.jl +++ b/GLMakie/test/runtests.jl @@ -16,7 +16,7 @@ reference_tests_dir = normpath(joinpath(dirname(pathof(Makie)), "..", "Reference Pkg.develop(PackageSpec(path = reference_tests_dir)) using ReferenceTests -GLMakie.activate!(framerate=1.0) +GLMakie.activate!(framerate = 1.0) @testset "mimes" begin f, ax, pl = scatter(1:4) diff --git a/GLMakie/test/unit_tests.jl b/GLMakie/test/unit_tests.jl index ea16da8f284..18bf8c7c28b 100644 --- a/GLMakie/test/unit_tests.jl +++ b/GLMakie/test/unit_tests.jl @@ -23,7 +23,7 @@ end # A displayed figure should create a singleton screen and leave other # screens untouched - fig, ax, splot = scatter(1:4); + fig, ax, splot = scatter(1:4) screen2 = display(fig) @test screen !== screen2 @test GLMakie.ALL_SCREENS == Set([screen, screen2]) @@ -52,11 +52,11 @@ end @test isempty(events(ax.scene).window_open.listeners) # Test singleton screen replacement - fig, ax, p = scatter(1:4); + fig, ax, p = scatter(1:4) screen = display(fig) ptr = deepcopy(screen.glscreen.handle) @test isopen(screen) && (screen === GLMakie.SINGLETON_SCREEN[1]) - fig2, ax2, p2 = scatter(4:-1:1); + fig2, ax2, p2 = scatter(4:-1:1) screen2 = display(fig2) @test isopen(screen2) && (screen2 === GLMakie.SINGLETON_SCREEN[]) @test screen === screen2 @@ -67,25 +67,25 @@ end @testset "Pick a plot element or plot elements inside a rectangle" begin N = 100000 fig, ax, splot = scatter(1:N, 1:N) - limits!(ax, 99990,100000, 99990,100000) + limits!(ax, 99990, 100000, 99990, 100000) screen = display(GLMakie.Screen(visible = false), fig) # we don't really need the color buffer here, but this should be the best way right now to really # force a full render to happen GLMakie.Makie.colorbuffer(screen) # test for pick a single data point (with idx > 65535) - point_px = project_sp(ax.scene, Point2f(N-1,N-1)) - plot,idx = pick(ax.scene, point_px) - @test idx == N-1 + point_px = project_sp(ax.scene, Point2f(N - 1, N - 1)) + plot, idx = pick(ax.scene, point_px) + @test idx == N - 1 # test for pick a rectangle of data points (also with some indices > 65535) - rect = Rect2f(99990.5,99990.5,8,8) + rect = Rect2f(99990.5, 99990.5, 8, 8) origin_px = project_sp(ax.scene, Point(origin(rect))) tip_px = project_sp(ax.scene, Point(origin(rect) .+ widths(rect))) rect_px = Rect2i(round.(origin_px), round.(tip_px .- origin_px)) picks = unique(pick(ax.scene, rect_px)) # objects returned in plot_idx should be either grid lines (i.e. LineSegments) or Scatter points - @test all(pi-> pi[1] isa Union{LineSegments,Scatter, Makie.Mesh}, picks) + @test all(pi -> pi[1] isa Union{LineSegments, Scatter, Makie.Mesh}, picks) # scatter points should have indices equal to those in 99991:99998 scatter_plot_idx = filter(pi -> pi[1] isa Scatter, picks) @test Set(last.(scatter_plot_idx)) == Set(99991:99998) @@ -96,10 +96,10 @@ end @testset "emtpy!(fig)" begin GLMakie.closeall() fig = Figure() - ax = Axis(fig[1,1]) + ax = Axis(fig[1, 1]) heatmap!(ax, rand(4, 4)) - lines!(ax, 1:5, rand(5); linewidth=3) - text!(ax, [Point2f(2)], text=["hi"]) + lines!(ax, 1:5, rand(5); linewidth = 3) + text!(ax, [Point2f(2)], text = ["hi"]) screen = display(fig) empty!(fig) @testset "all got freed" begin @@ -112,10 +112,10 @@ end @test robj.vertexarray.id == 0 end end - ax = Axis(fig[1,1]) + ax = Axis(fig[1, 1]) heatmap!(ax, rand(4, 4)) - lines!(ax, 1:5, rand(5); linewidth=3) - text!(ax, [Point2f(2)], text=["hi"]) + lines!(ax, 1:5, rand(5); linewidth = 3) + text!(ax, [Point2f(2)], text = ["hi"]) @testset "no freed object after replotting" begin for (_, _, robj) in screen.renderlist for (k, v) in robj.uniforms @@ -133,15 +133,15 @@ end @testset "empty!(ax)" begin GLMakie.closeall() fig = Figure() - ax = Axis(fig[1,1]) + ax = Axis(fig[1, 1]) hmp = heatmap!(ax, rand(4, 4)) - lp = lines!(ax, 1:5, rand(5); linewidth=3) - tp = text!(ax, [Point2f(2)], text=["hi"]) + lp = lines!(ax, 1:5, rand(5); linewidth = 3) + tp = text!(ax, [Point2f(2)], text = ["hi"]) screen = display(fig) @test ax.scene.plots == [hmp, lp, tp] - robjs = map(x-> screen.cache[objectid(x)], [hmp, lp, tp.plots...]) + robjs = map(x -> screen.cache[objectid(x)], [hmp, lp, tp.plots...]) empty!(ax) @@ -156,8 +156,8 @@ end end heatmap!(ax, rand(4, 4)) - lines!(ax, 1:5, rand(5); linewidth=3) - text!(ax, [Point2f(2)], text=["hi"]) + lines!(ax, 1:5, rand(5); linewidth = 3) + text!(ax, [Point2f(2)], text = ["hi"]) @testset "no freed object after replotting" begin for (_, _, robj) in screen.renderlist for (k, v) in robj.uniforms @@ -178,7 +178,7 @@ end @testset "closing and redisplaying" begin GLMakie.closeall() fig = Figure() - ax = Axis(fig[1,1]) # only happens with axis + ax = Axis(fig[1, 1]) # only happens with axis # lines!(ax, 1:5, rand(5); linewidth=5) # but doesn't need a plot screen = display(fig) GLMakie.closeall() @@ -189,11 +189,11 @@ end @testset "closing and redisplaying + resizing" begin GLMakie.closeall() fig = Figure() - ax = Axis(fig[1,1]) # only happens with axis + ax = Axis(fig[1, 1]) # only happens with axis screen = display(fig) close(screen) screen = display(fig) - resize!(fig, 800,601) + resize!(fig, 800, 601) @test true # test for no errors for now # GLMakie.destroy!(screen) end @@ -210,23 +210,23 @@ end @testset "stresstest multi displays" begin GLMakie.closeall() screens = map(1:10) do i - fig = Figure(resolution=(500, 500)) - rng = Random.MersenneTwister(0) - ax, pl = image(fig[1, 1], 0..1, 0..1, rand(rng, 1000, 1000)) - scatter!(ax, rand(rng, Point2f, 1000), color=:red) - lines!(ax, rand(rng, Point2f, 1000), transparency=true) + fig = Figure(resolution = (500, 500)) + rng = Random.MersenneTwister(0) + ax, pl = image(fig[1, 1], 0 .. 1, 0 .. 1, rand(rng, 1000, 1000)) + scatter!(ax, rand(rng, Point2f, 1000), color = :red) + lines!(ax, rand(rng, Point2f, 1000), transparency = true) ax3d, pl = mesh(fig[1, 2], Sphere(Point3f(0), 1)) - meshscatter!(ax3d, rand(rng, Point3f, 100), color=:red) + meshscatter!(ax3d, rand(rng, Point3f, 100), color = :red) heatmap(fig[2, 1], rand(rng, 100, 100)) - surface(fig[2, 2], 0..1, 0..1, rand(rng, 1000, 1000) ./ 2) + surface(fig[2, 2], 0 .. 1, 0 .. 1, rand(rng, 1000, 1000) ./ 2) - display(GLMakie.Screen(visible=false), fig) + display(GLMakie.Screen(visible = false), fig) end images = map(Makie.colorbuffer, screens) - @test all(x-> x ≈ first(images), images) + @test all(x -> x ≈ first(images), images) @test Base.summarysize(screens) / 10^6 > 300 foreach(close, screens) @@ -248,7 +248,7 @@ end @test (Base.summarysize(screen) / 10^6) < 1.2 end # All should go to pool after close - @test all(x-> x in GLMakie.SCREEN_REUSE_POOL, screens) + @test all(x -> x in GLMakie.SCREEN_REUSE_POOL, screens) GLMakie.closeall() # now every screen should be gone diff --git a/MakieCore/src/attributes.jl b/MakieCore/src/attributes.jl index 84eddc36f94..c56f0895409 100644 --- a/MakieCore/src/attributes.jl +++ b/MakieCore/src/attributes.jl @@ -12,7 +12,7 @@ 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 result = Observable(to_value.(x)) - onany((args...)-> args, x...) + onany((args...) -> args, x...) return result end @@ -39,13 +39,9 @@ function Base.iterate(x::Attributes, state...) return (s[1] => x[s[1]], s[2]) end -function Base.copy(attr::Attributes) - return Attributes(copy(attributes(attr))) -end +Base.copy(attr::Attributes) = Attributes(copy(attributes(attr))) -function Base.deepcopy(obs::Observable) - return Observable{Any}(to_value(obs)) -end +Base.deepcopy(obs::Observable) = Observable{Any}(to_value(obs)) function Base.deepcopy(attributes::Attributes) result = Attributes() @@ -71,21 +67,19 @@ Base.merge(target::Attributes, args::Attributes...) = merge!(copy(target), args. @generated hasfield(x::T, ::Val{key}) where {T, key} = :($(key in fieldnames(T))) -@inline function Base.getproperty(x::Union{Attributes, AbstractPlot}, key::Symbol) +@inline Base.getproperty(x::Union{Attributes, AbstractPlot}, key::Symbol) = if hasfield(x, Val(key)) getfield(x, key) else getindex(x, key) end -end -@inline function Base.setproperty!(x::Union{Attributes, AbstractPlot}, key::Symbol, value) +@inline Base.setproperty!(x::Union{Attributes, AbstractPlot}, key::Symbol, value) = if hasfield(x, Val(key)) setfield!(x, key, value) else setindex!(x, value, key) end -end function Base.getindex(x::Attributes, key::Symbol) x = attributes(x)[key] @@ -94,13 +88,12 @@ function Base.getindex(x::Attributes, key::Symbol) return x[] isa Attributes ? x[] : x end -function Base.setindex!(x::Attributes, value, key::Symbol) +Base.setindex!(x::Attributes, value, key::Symbol) = if haskey(x, key) x.attributes[key][] = value else x.attributes[key] = node_any(value) end -end function Base.setindex!(x::Attributes, value::Observable, key::Symbol) if haskey(x, key) @@ -118,7 +111,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) @@ -156,7 +149,7 @@ 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) -function Base.get!(f::Function, x::AttributeOrPlot, key::Symbol) +Base.get!(f::Function, x::AttributeOrPlot, key::Symbol) = if haskey(x, key) return x[key] else @@ -164,10 +157,9 @@ function Base.get!(f::Function, x::AttributeOrPlot, key::Symbol) x[key] = val return x[key] end -end -Base.get!(x::AttributeOrPlot, key::Symbol, default) = get!(()-> default, x, key) +Base.get!(x::AttributeOrPlot, key::Symbol, default) = get!(() -> default, x, key) Base.get(f::Function, x::AttributeOrPlot, key::Symbol) = haskey(x, key) ? x[key] : f() -Base.get(x::AttributeOrPlot, key::Symbol, default) = get(()-> default, x, key) +Base.get(x::AttributeOrPlot, key::Symbol, default) = get(() -> default, x, key) # This is a bit confusing, since for a plot it returns the attribute from the arguments # and not a plot for integer indexing. But, we want to treat plots as "atomic" @@ -233,7 +225,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) +get_attribute(dict, key, default = nothing) = if haskey(dict, key) value = to_value(dict[key]) value isa Automatic && return default @@ -241,7 +233,6 @@ function get_attribute(dict, key, default=nothing) else return default end -end function merge_attributes!(input::Attributes, theme::Attributes) for (key, value) in theme @@ -259,6 +250,4 @@ function merge_attributes!(input::Attributes, theme::Attributes) return input end -function Base.propertynames(x::Union{Attributes, AbstractPlot}) - return (keys(x.attributes)...,) -end +Base.propertynames(x::Union{Attributes, AbstractPlot}) = (keys(x.attributes)...,) diff --git a/MakieCore/src/basic_plots.jl b/MakieCore/src/basic_plots.jl index 325d59d6806..439bf7116e9 100644 --- a/MakieCore/src/basic_plots.jl +++ b/MakieCore/src/basic_plots.jl @@ -199,7 +199,7 @@ Plots a surface, where `(x, y)` define a grid whose heights are the entries in @recipe(Surface, x, y, z) do scene Attributes(; default_theme(scene)..., - backlight = 0f0, + backlight = 0.0f0, color = nothing, colormap = theme(scene, :colormap), colorrange = automatic, @@ -337,7 +337,7 @@ Plots a 3D or 2D mesh. Supported `mesh_object`s include `Mesh` types from [Geome Attributes(; default_theme(scene)..., color = :black, - backlight = 0f0, + backlight = 0.0f0, colormap = theme(scene, :colormap), colorrange = automatic, lowclip = automatic, @@ -396,14 +396,10 @@ Plots a marker for each element in `(x, y, z)`, `(x, y)`, or `positions`. colormap = theme(scene, :colormap), colorrange = automatic, marker = theme(scene, :marker), - markersize = theme(scene, :markersize), - - strokecolor = theme(scene, :markerstrokecolor), + markersize = theme(scene, :markersize), strokecolor = theme(scene, :markerstrokecolor), strokewidth = theme(scene, :markerstrokewidth), glowcolor = (:black, 0.0), - glowwidth = 0.0, - - rotations = Billboard(), + glowwidth = 0.0, rotations = Billboard(), marker_offset = automatic, transform_marker = false, # Applies the plots transformation to marker distancefield = nothing, @@ -465,12 +461,12 @@ Plots a mesh for each element in `(x, y, z)`, `(x, y)`, or `positions` (similar marker = :Sphere, markersize = 0.1, rotations = 0.0, - backlight = 0f0, + backlight = 0.0f0, space = :data, shading = true, fxaa = true, inspectable = theme(scene, :inspectable), - cycle = [:color], + cycle = [:color] ) end @@ -602,7 +598,7 @@ end # default_theme(scene, LineSegments) Attributes(; default_theme(scene, LineSegments)..., - depth_shift = -1f-5, + depth_shift = -1.0f-5 ) end @@ -618,7 +614,7 @@ end linestyle = nothing, align = :origin, normalize = false, - lengthscale = 1f0, + lengthscale = 1.0f0, colormap = theme(scene, :colormap), quality = 32, inspectable = theme(scene, :inspectable), diff --git a/MakieCore/src/conversion.jl b/MakieCore/src/conversion.jl index 09ed90a6eb8..3943ce11d0a 100644 --- a/MakieCore/src/conversion.jl +++ b/MakieCore/src/conversion.jl @@ -18,16 +18,16 @@ conversion_trait(::Type) = NoConversion() convert_arguments(::NoConversion, args...) = args struct PointBased <: ConversionTrait end -conversion_trait(::Type{<: XYBased}) = PointBased() -conversion_trait(::Type{<: Text}) = PointBased() +conversion_trait(::Type{<:XYBased}) = PointBased() +conversion_trait(::Type{<:Text}) = PointBased() abstract type SurfaceLike <: ConversionTrait end struct ContinuousSurface <: SurfaceLike end -conversion_trait(::Type{<: Union{Surface, Image}}) = ContinuousSurface() +conversion_trait(::Type{<:Union{Surface, Image}}) = ContinuousSurface() struct DiscreteSurface <: SurfaceLike end -conversion_trait(::Type{<: Heatmap}) = DiscreteSurface() +conversion_trait(::Type{<:Heatmap}) = DiscreteSurface() struct VolumeLike <: ConversionTrait end -conversion_trait(::Type{<: Volume}) = VolumeLike() +conversion_trait(::Type{<:Volume}) = VolumeLike() diff --git a/MakieCore/src/recipes.jl b/MakieCore/src/recipes.jl index 741ab37a169..955ea538e2a 100644 --- a/MakieCore/src/recipes.jl +++ b/MakieCore/src/recipes.jl @@ -5,20 +5,18 @@ 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 - string(F.name.mt.name) -end +func2string(func::F) where F <: Function = string(F.name.mt.name) plotfunc(::Combined{F}) where F = F -plotfunc(::Type{<: AbstractPlot{Func}}) where Func = Func +plotfunc(::Type{<:AbstractPlot{Func}}) where Func = Func plotfunc(::T) where T <: AbstractPlot = plotfunc(T) plotfunc(f::Function) = f func2type(x::T) where T = func2type(T) -func2type(x::Type{<: AbstractPlot}) = x +func2type(x::Type{<:AbstractPlot}) = x func2type(f::Function) = Combined{f} -plotkey(::Type{<: AbstractPlot{Typ}}) where Typ = Symbol(lowercase(func2string(Typ))) +plotkey(::Type{<:AbstractPlot{Typ}}) where Typ = Symbol(lowercase(func2string(Typ))) plotkey(::T) where T <: AbstractPlot = plotkey(T) plotkey(::Nothing) = :scatter @@ -28,24 +26,16 @@ Creates all the different overloads for `funcname` that need to be supported for Since we add all these signatures to different functions, we make it reusable with this function. The `Core.@__doc__` macro transfers the docstring given to the Recipe into the functions. """ -function default_plot_signatures(funcname, funcname!, PlotType) - quote - Core.@__doc__ function ($funcname)(args...; attributes...) - plot($PlotType, args...; attributes...) - end - - Core.@__doc__ function ($funcname!)(args...; attributes...) - plot!($PlotType, args...; attributes...) - end - end +default_plot_signatures(funcname, funcname!, PlotType) = quote + Core.@__doc__ ($funcname)(args...; attributes...) = plot($PlotType, args...; attributes...) + + Core.@__doc__ ($funcname!)(args...; attributes...) = plot!($PlotType, args...; attributes...) end """ Each argument can be named for a certain plot type `P`. Falls back to `arg1`, `arg2`, etc. """ -function argument_names(plot::P) where {P<:AbstractPlot} - argument_names(P, length(plot.converted)) -end +argument_names(plot::P) where {P <: AbstractPlot} = argument_names(P, length(plot.converted)) function argument_names(::Type{<:AbstractPlot}, num_args::Integer) # this is called in the indexing function, so let's be a bit efficient @@ -171,7 +161,7 @@ macro recipe(theme_func, Tsym::Symbol, args::Symbol...) funcname = esc(funcname_sym) expr = quote $(funcname)() = not_implemented_for($funcname) - const $(PlotType){$(esc(:ArgType))} = Combined{$funcname,$(esc(:ArgType))} + const $(PlotType){$(esc(:ArgType))} = Combined{$funcname, $(esc(:ArgType))} $(MakieCore).plotsym(::Type{<:$(PlotType)}) = $(QuoteNode(Tsym)) $(default_plot_signatures(funcname, funcname!, PlotType)) $(MakieCore).default_theme(scene, ::Type{<:$PlotType}) = $(esc(theme_func))(scene) @@ -198,17 +188,11 @@ eval(default_plot_signatures(:plot, :plot!, :Any)) """ Returns the Combined type that represents the signature of `args`. """ -function Plot(args::Vararg{Any,N}) where {N} - Combined{Any,<:Tuple{args...}} -end +Plot(args::Vararg{Any, N}) where {N} = Combined{Any, <:Tuple{args...}} -Base.@pure function Plot(::Type{T}) where {T} - Combined{Any,<:Tuple{T}} -end +Base.@pure Plot(::Type{T}) where {T} = Combined{Any, <:Tuple{T}} -Base.@pure function Plot(::Type{T1}, ::Type{T2}) where {T1,T2} - Combined{Any,<:Tuple{T1,T2}} -end +Base.@pure Plot(::Type{T1}, ::Type{T2}) where {T1, T2} = Combined{Any, <:Tuple{T1, T2}} """ `plottype(plot_args...)` diff --git a/MakieCore/src/types.jl b/MakieCore/src/types.jl index 3a633fcb09d..a6ddff503e2 100644 --- a/MakieCore/src/types.jl +++ b/MakieCore/src/types.jl @@ -59,9 +59,7 @@ struct Combined{Typ, T} <: ScenePlot{Typ} plots::Vector{AbstractPlot} end -function Base.show(io::IO, plot::Combined) - print(io, typeof(plot)) -end +Base.show(io::IO, plot::Combined) = print(io, typeof(plot)) Base.parent(x::AbstractPlot) = x.parent @@ -107,6 +105,6 @@ Can be used for rotation. struct Billboard{T <: Union{Float32, Vector{Float32}}} rotation::T end -Billboard() = Billboard(0f0) +Billboard() = Billboard(0.0f0) Billboard(angle::Real) = Billboard(Float32(angle)) Billboard(angles::Vector) = Billboard(Float32.(angles)) diff --git a/MakieCore/test/runtests.jl b/MakieCore/test/runtests.jl index 600ac535987..921041b6c25 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,12 +29,10 @@ 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,) # Convert for all point based types (lines, scatter) -function convert_arguments(p::MakieCore.PointBased, x::Solution; attribute = 1.0) - return convert_arguments(p, x.data .* attribute) -end +convert_arguments(p::MakieCore.PointBased, x::Solution; attribute = 1.0) = convert_arguments(p, x.data .* attribute) diff --git a/MakieRecipes/src/bezier.jl b/MakieRecipes/src/bezier.jl index bf222bd1b02..cf7363c80fc 100644 --- a/MakieRecipes/src/bezier.jl +++ b/MakieRecipes/src/bezier.jl @@ -9,16 +9,16 @@ ) end -conversion_trait(::Type{<: Bezier}) = PointBased() +conversion_trait(::Type{<:Bezier}) = PointBased() -function calculated_attributes!(::Type{<: Bezier}, plot) +function calculated_attributes!(::Type{<:Bezier}, plot) color_and_colormap!(plot) pos = plot[1][] # extend one color per linesegment to be one (the same) color per vertex # taken from @edljk in PR #77 if haskey(plot, :color) && isa(plot[:color][], AbstractVector) && iseven(length(pos)) && (length(pos) ÷ 2) == length(plot[:color][]) plot[:color] = lift(plot[:color]) do cols - map(i-> cols[(i + 1) ÷ 2], 1:(length(cols) * 2)) + map(i -> cols[(i + 1) ÷ 2], 1:(length(cols) * 2)) end end end @@ -34,7 +34,7 @@ function from_nansep_vec(v::Vector{T}) where T prev = 1 num = 1 for i in idxs - vs[num] = v[prev:i-1] + vs[num] = v[prev:(i - 1)] prev = i + 1 num += 1 diff --git a/MakieRecipes/src/pipeline_integration.jl b/MakieRecipes/src/pipeline_integration.jl index acbb29b1996..57ee8fea7dd 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 @@ -16,9 +16,7 @@ RecipesBase.apply_recipe(plotattributes, ::Type{T}, ::PlotContext) where T = thr # Preprocessing involves resetting the palette for now. # Later, it may involve setting up a layouting context, among other things. -function RecipesPipeline.preprocess_attributes!(plt::PlotContext, plotattributes) - plt.palette[].i[] = zero(UInt8) -end +RecipesPipeline.preprocess_attributes!(plt::PlotContext, plotattributes) = plt.palette[].i[] = zero(UInt8) # Allow a series type to be plotted. @@ -32,13 +30,13 @@ 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 +46,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 +64,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 @@ -90,9 +88,7 @@ slice_arg(v, idx) = v Returns the Makie plot type which corresponds to the given seriestype. The plot type is returned as a Type (`Lines`, `Scatter`, ...). """ -function makie_plottype(st::Symbol) - return get(makie_seriestype_map, st, Lines) -end +makie_plottype(st::Symbol) = get(makie_seriestype_map, st, Lines) makie_args(::Type{T}, plotattributes) where T <: AbstractPlot = makie_args(conversion_trait(T), plotattributes) @@ -115,11 +111,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) - return (from_nansep_vec(Point2f.(plotattributes[:x], plotattributes[:y])),) -end +makie_args(::Type{<:Poly}, plotattributes) = (from_nansep_vec(Point2f.(plotattributes[:x], plotattributes[:y])),) function translate_to_makie!(st, pa) @@ -289,7 +283,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 +304,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/RPRMakie/examples/bars.jl b/RPRMakie/examples/bars.jl index 61514ecc546..4efc342a4f4 100644 --- a/RPRMakie/examples/bars.jl +++ b/RPRMakie/examples/bars.jl @@ -2,13 +2,13 @@ using GeometryBasics, RPRMakie using Colors, FileIO, ImageShow using Colors: N0f8 -RPRMakie.activate!(plugin=RPR.Northstar) -fig = Figure(; resolution=(800, 600), fontsize=26) +RPRMakie.activate!(plugin = RPR.Northstar) +fig = Figure(; resolution = (800, 600), fontsize = 26) radiance = 10000 lights = [EnvironmentLight(0.5, load(RPR.assetpath("studio026.exr"))), - PointLight(Vec3f(0, 0, 20), RGBf(radiance, radiance, radiance))] + PointLight(Vec3f(0, 0, 20), RGBf(radiance, radiance, radiance))] -ax = LScene(fig[1, 1]; scenekw=(lights=lights,)) +ax = LScene(fig[1, 1]; scenekw = (lights = lights,)) Makie.axis3d!(ax.scene, Rect3f(Vec3f(0), Vec3f(1, 1, 1.2))) rectMesh = FRect3D(Vec3f0(-0.5, -0.5, 0), Vec3f0(1)) recmesh = GeometryBasics.normal_mesh(rectMesh) @@ -16,9 +16,9 @@ n = 100 pos = [Point3f(i, j, 0) ./ 10 for i in 1:n for j in 1:n] z = rand(n, n) -mat = (type=:Microfacet, color=:gray, roughness=0.2, ior=1.390) +mat = (type = :Microfacet, color = :gray, roughness = 0.2, ior = 1.390) -meshscatter!(ax, pos; marker=recmesh, markersize=Vec3f.(0.1, 0.1, z[:]), material=mat, color=vec(z)) +meshscatter!(ax, pos; marker = recmesh, markersize = Vec3f.(0.1, 0.1, z[:]), material = mat, color = vec(z)) cam = cameracontrols(ax.scene) cam.eyeposition[] = Float32[5, 22, 12] diff --git a/RPRMakie/examples/eart_topographie_sphere.jl b/RPRMakie/examples/eart_topographie_sphere.jl index 6bef6b10abc..299a474fd5f 100644 --- a/RPRMakie/examples/eart_topographie_sphere.jl +++ b/RPRMakie/examples/eart_topographie_sphere.jl @@ -7,7 +7,7 @@ lon = dataset["lon"][:] lat = dataset["lat"][:] data = Float32.(dataset["ETOPO1avg"][:, :]) -function toCartesian(lon, lat; r=1, cxyz=(0, 0, 0)) +function toCartesian(lon, lat; r = 1, cxyz = (0, 0, 0)) lat, lon = lat * π / 180, lon * π / 180 x = cxyz[1] + (r + 80_000) * cos(lat) * cos(lon) y = cxyz[2] + (r + 80_000) * cos(lat) * sin(lon) @@ -15,10 +15,10 @@ function toCartesian(lon, lat; r=1, cxyz=(0, 0, 0)) return (x, y, z) ./ 80_000 end -function lonlat3D(lon, lat, data; cxyz=(0, 0, 0)) +function lonlat3D(lon, lat, data; cxyz = (0, 0, 0)) xyzw = zeros(size(data)..., 3) for (i, lon) in enumerate(lon), (j, lat) in enumerate(lat) - x, y, z = toCartesian(lon, lat; r=data[i, j], cxyz=cxyz) + x, y, z = toCartesian(lon, lat; r = data[i, j], cxyz = cxyz) xyzw[i, j, 1] = x xyzw[i, j, 2] = y xyzw[i, j, 3] = z @@ -26,7 +26,7 @@ function lonlat3D(lon, lat, data; cxyz=(0, 0, 0)) return xyzw[:, :, 1], xyzw[:, :, 2], xyzw[:, :, 3] end # this is needed in order to have a closed surface -lonext = cat(collect(lon), lon[1]; dims=1) +lonext = cat(collect(lon), lon[1]; dims = 1) dataext = begin tmpdata = zeros(size(lon)[1] + 1, size(lat)[1]) tmpdata[1:size(lon)[1], :] = data @@ -39,15 +39,15 @@ xetopo, yetopo, zetopo = lonlat3D(lonext, lat, dataext) begin r = 30 lights = [PointLight(Vec3f(2, 1, 3), RGBf(r, r, r))] - fig = Figure(; resolution=(1200, 1200), backgroundcolor=:black) - ax = LScene(fig[1, 1]; show_axis=false)#, scenekw=(lights=lights,)) - pltobj = surface!(ax, xetopo, yetopo, zetopo; color=dataext, colormap=:hot, colorrange=(-6000, 5000)) + fig = Figure(; resolution = (1200, 1200), backgroundcolor = :black) + ax = LScene(fig[1, 1]; show_axis = false)#, scenekw=(lights=lights,)) + pltobj = surface!(ax, xetopo, yetopo, zetopo; color = dataext, colormap = :hot, colorrange = (-6000, 5000)) cam = cameracontrols(ax.scene) cam.fov[] = 10 cam.eyeposition[] = Vec3f(3, 1, 1) cam.lookat[] = Vec3f(0) cam.upvector[] = Vec3f(0, 0, 1) Makie.update_cam!(ax.scene, cam) - RPRMakie.activate!(; iterations=32, plugin=RPR.Tahoe) + RPRMakie.activate!(; iterations = 32, plugin = RPR.Tahoe) display(ax.scene) end diff --git a/RPRMakie/examples/earth_topography.jl b/RPRMakie/examples/earth_topography.jl index 7f52cc43ca2..c55457c2d3b 100644 --- a/RPRMakie/examples/earth_topography.jl +++ b/RPRMakie/examples/earth_topography.jl @@ -27,13 +27,13 @@ function glow_material(data_normed) ) end -RPRMakie.activate!(iterations=32, plugin=RPR.Northstar) -fig = Figure(; resolution=(2000, 800)) +RPRMakie.activate!(iterations = 32, plugin = RPR.Northstar) +fig = Figure(; resolution = (2000, 800)) radiance = 30000 lights = [EnvironmentLight(1.0, load(RPR.assetpath("studio026.exr"))), - PointLight(Vec3f(0, 100, 100), RGBf(radiance, radiance, radiance))] + PointLight(Vec3f(0, 100, 100), RGBf(radiance, radiance, radiance))] -ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) +ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) mini, maxi = extrema(data) data_normed = ((data .- mini) ./ (maxi - mini)) @@ -41,8 +41,8 @@ data_normed = ((data .- mini) ./ (maxi - mini)) material = glow_material(data_normed) pltobj = surface!(ax, lon, lat, data_normed .* 20; - material=material, colormap=[:black, :white, :brown], - colorrange=(0.2, 0.8) .* 20) + material = material, colormap = [:black, :white, :brown], + colorrange = (0.2, 0.8) .* 20) # Set the camera to a nice angle cam = cameracontrols(ax.scene) cam.eyeposition[] = Vec3f(3, -300, 300) diff --git a/RPRMakie/examples/lego.jl b/RPRMakie/examples/lego.jl index 46ac94c5f77..91e4e370955 100644 --- a/RPRMakie/examples/lego.jl +++ b/RPRMakie/examples/lego.jl @@ -34,42 +34,42 @@ function plot_part!(scene, parent, name::String) origin = get(origins, name, nothing) if !isnothing(origin) centered = m.position .- origin - m = GeometryBasics.Mesh(meta(centered; normals=m.normals), faces(m)) + m = GeometryBasics.Mesh(meta(centered; normals = m.normals), faces(m)) translate!(trans, origin) else translate!(trans, -ptrans.translation[]) end - return mesh!(scene, m; color=color, transformation=trans) + return mesh!(scene, m; color = color, transformation = trans) end -function plot_lego_figure(s, floor=true) +function plot_lego_figure(s, floor = true) # Plot hierarchical mesh! figure = Dict() # Plot hierarchical mesh! figure["torso"] = plot_part!(s, s, "torso") - figure["head"] = plot_part!(s, figure["torso"], "head") - figure["eyes_mouth"] = plot_part!(s, figure["head"], "eyes_mouth") - figure["arm_right"] = plot_part!(s, figure["torso"], "arm_right") - figure["hand_right"] = plot_part!(s, figure["arm_right"], "hand_right") - figure["arm_left"] = plot_part!(s, figure["torso"], "arm_left") - figure["hand_left"] = plot_part!(s, figure["arm_left"], "hand_left") - figure["belt"] = plot_part!(s, figure["torso"], "belt") - figure["leg_right"] = plot_part!(s, figure["belt"], "leg_right") - figure["leg_left"] = plot_part!(s, figure["belt"], "leg_left") + figure["head"] = plot_part!(s, figure["torso"], "head") + figure["eyes_mouth"] = plot_part!(s, figure["head"], "eyes_mouth") + figure["arm_right"] = plot_part!(s, figure["torso"], "arm_right") + figure["hand_right"] = plot_part!(s, figure["arm_right"], "hand_right") + figure["arm_left"] = plot_part!(s, figure["torso"], "arm_left") + figure["hand_left"] = plot_part!(s, figure["arm_left"], "hand_left") + figure["belt"] = plot_part!(s, figure["torso"], "belt") + figure["leg_right"] = plot_part!(s, figure["belt"], "leg_right") + figure["leg_left"] = plot_part!(s, figure["belt"], "leg_left") # lift the little guy up translate!(figure["torso"], 0, 0, 20) # add some floor - floor && mesh!(s, Rect3f(Vec3f(-400, -400, -2), Vec3f(800, 800, 2)), color=:white) + floor && mesh!(s, Rect3f(Vec3f(-400, -400, -2), Vec3f(800, 800, 2)), color = :white) return figure end -RPRMakie.activate!(iterations=200, plugin=RPR.Northstar) +RPRMakie.activate!(iterations = 200, plugin = RPR.Northstar) radiance = 50000 lights = [ EnvironmentLight(1.5, rotl90(load(assetpath("sunflowers_1k.hdr"))')), - PointLight(Vec3f(50, 0, 200), RGBf(radiance, radiance, radiance*1.1)), + PointLight(Vec3f(50, 0, 200), RGBf(radiance, radiance, radiance * 1.1)), ] -s = Scene(resolution=(500, 500), lights=lights) +s = Scene(resolution = (500, 500), lights = lights) cam3d!(s) c = cameracontrols(s) @@ -78,12 +78,12 @@ c.far[] = 1000 update_cam!(s, c, Vec3f(100, 30, 80), Vec3f(0, 0, -10)) figure = plot_lego_figure(s) -rot_joints_by = 0.25*pi +rot_joints_by = 0.25 * pi total_translation = 50 animation_strides = 10 a1 = LinRange(0, rot_joints_by, animation_strides) -angles = [a1; reverse(a1[1:end-1]); -a1[2:end]; reverse(-a1[1:end-1]);] +angles = [a1; reverse(a1[1:(end - 1)]); -a1[2:end]; reverse(-a1[1:(end - 1)])] nsteps = length(angles); #Number of animation steps translations = LinRange(0, total_translation, nsteps) diff --git a/RPRMakie/examples/lines.jl b/RPRMakie/examples/lines.jl index 4b6a103fd44..812e696692f 100644 --- a/RPRMakie/examples/lines.jl +++ b/RPRMakie/examples/lines.jl @@ -3,8 +3,8 @@ using Colors, FileIO using Colors: N0f8 begin - RPRMakie.activate!(plugin=RPR.Tahoe) - fig = Figure(; resolution=(1000, 1000)) + RPRMakie.activate!(plugin = RPR.Tahoe) + fig = Figure(; resolution = (1000, 1000)) ax = LScene(fig[1, 1]) points = Point3f[] for i in 4:10 @@ -12,9 +12,9 @@ begin y = LinRange(0, i, n) y2 = (y ./ 2) .- 2 xyz = Point3f.((i - 5) ./ 2, y2, sin.(y) .+ 1) - lines!(ax, xyz; linewidth=5, color=:red) + lines!(ax, xyz; linewidth = 5, color = :red) append!(points, xyz) end - meshscatter!(ax, points, color=:green) + meshscatter!(ax, points, color = :green) ax.scene end diff --git a/RPRMakie/examples/makie_example.jl b/RPRMakie/examples/makie_example.jl index c2dbd65f47a..c2844b9a327 100644 --- a/RPRMakie/examples/makie_example.jl +++ b/RPRMakie/examples/makie_example.jl @@ -1,11 +1,11 @@ using GeometryBasics, Makie using FileIO, Colors using RPRMakie -RPRMakie.activate!(iterations=200) +RPRMakie.activate!(iterations = 200) earth = load(Makie.assetpath("earth.png")) m = uv_mesh(Tesselation(Sphere(Point3f(0), 1.0f0), 60)) -f, ax, mplot = Makie.mesh(m; color=earth) -Makie.mesh!(ax, Sphere(Point3f(2, 0, 0), 0.1f0); color=:red) +f, ax, mplot = Makie.mesh(m; color = earth) +Makie.mesh!(ax, Sphere(Point3f(2, 0, 0), 0.1f0); color = :red) x, y = collect(-8:0.5:8), collect(-8:0.5:8) z = [sinc(√(X^2 + Y^2) / π) for X in x, Y in y] wireframe!(ax, -2 .. 2, -2 .. 2, z) diff --git a/RPRMakie/examples/materials.jl b/RPRMakie/examples/materials.jl index 65e4a92283b..78d1b27f65d 100644 --- a/RPRMakie/examples/materials.jl +++ b/RPRMakie/examples/materials.jl @@ -5,10 +5,10 @@ using Colors: N0f8 image = begin radiance = 500 lights = [EnvironmentLight(1.0, load(RPR.assetpath("studio026.exr"))), - PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] - fig = Figure(; resolution=(1500, 700)) - ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) - screen = Screen(ax.scene; plugin=RPR.Northstar, iterations=400) + PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] + fig = Figure(; resolution = (1500, 700)) + ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) + screen = Screen(ax.scene; plugin = RPR.Northstar, iterations = 400) matsys = screen.matsys emissive = RPR.EmissiveMaterial(matsys) @@ -19,20 +19,20 @@ image = begin dielectric = RPR.DielectricBrdfX(matsys) gold = RPR.SurfaceGoldX(matsys) - materials = [glass chrome; - gold dielectric; - emissive plastic] + materials = [glass chrome + gold dielectric + emissive plastic] - mesh!(ax, load(Makie.assetpath("matball_floor.obj")); color=:white) + mesh!(ax, load(Makie.assetpath("matball_floor.obj")); color = :white) palette = reshape(Makie.default_palettes.color[][1:6], size(materials)) for i in CartesianIndices(materials) x, y = Tuple(i) mat = materials[i] mplot = if mat === emissive - matball!(ax, diffuse; inner=emissive, color=nothing) + matball!(ax, diffuse; inner = emissive, color = nothing) else - matball!(ax, mat; color=nothing) + matball!(ax, mat; color = nothing) end v = Vec3f(((x, y) .- (0.5 .* size(materials)) .- 0.5)..., 0) translate!(mplot, 0.9 .* (v .- Vec3f(0, 3, 0))) diff --git a/RPRMakie/examples/opengl_interop.jl b/RPRMakie/examples/opengl_interop.jl index 40a08cb4d7a..845ef215f3d 100644 --- a/RPRMakie/examples/opengl_interop.jl +++ b/RPRMakie/examples/opengl_interop.jl @@ -5,24 +5,24 @@ using Colors: N0f8 f = (u, v) -> cos(v) * (6 - (5 / 4 + sin(3 * u)) * sin(u - 3 * v)) g = (u, v) -> sin(v) * (6 - (5 / 4 + sin(3 * u)) * sin(u - 3 * v)) h = (u, v) -> -cos(u - 3 * v) * (5 / 4 + sin(3 * u)); -u = range(0; stop=2π, length=150) -v = range(0; stop=2π, length=150) +u = range(0; stop = 2π, length = 150) +v = range(0; stop = 2π, length = 150) radiance = 500 lights = [EnvironmentLight(1.0, load(RPR.assetpath("studio026.exr"))), - PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] + PointLight(Vec3f(10), RGBf(radiance, radiance, radiance * 1.1))] -fig = Figure(; resolution=(1500, 1000)) -ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) -screen = RPRMakie.Screen(size(ax.scene); plugin=RPR.Tahoe) +fig = Figure(; resolution = (1500, 1000)) +ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) +screen = RPRMakie.Screen(size(ax.scene); plugin = RPR.Tahoe) material = RPR.UberMaterial(screen.matsys) -surface!(ax, f.(u, v'), g.(u, v'), h.(u, v'); ambient=Vec3f(0.5), diffuse=Vec3f(1), specular=0.5, - colormap=:balance, material=material) +surface!(ax, f.(u, v'), g.(u, v'), h.(u, v'); ambient = Vec3f(0.5), diffuse = Vec3f(1), specular = 0.5, + colormap = :balance, material = material) function Input(fig, val::RGB) - hue = Slider(fig; range=1:380, width=200) - lightness = Slider(fig; range=LinRange(0, 1, 100), width=200) - labels = [Label(fig, "hue"; halign=:left), Label(fig, "light"; halign=:left)] + hue = Slider(fig; range = 1:380, width = 200) + lightness = Slider(fig; range = LinRange(0, 1, 100), width = 200) + labels = [Label(fig, "hue"; halign = :left), Label(fig, "light"; halign = :left)] layout = grid!(hcat(labels, [hue, lightness])) hsl = HSL(val) set_close_to!(hue, hsl.h) @@ -32,34 +32,34 @@ function Input(fig, val::RGB) end function Input(fig, val::Vec4) - s = Slider(fig; range=LinRange(0, 1, 100), width=200) + s = Slider(fig; range = LinRange(0, 1, 100), width = 200) set_close_to!(s, first(val)) return map(x -> Vec4f(x), s.value), s end function Input(fig, val::Bool) - toggle = Toggle(fig; active=val) + toggle = Toggle(fig; active = val) return toggle.active, toggle end -sliders = (reflection_color=Input(fig, RGB(0, 0, 0)), reflection_weight=Input(fig, Vec4(0)), - reflection_roughness=Input(fig, Vec4(0)), reflection_anisotropy=Input(fig, Vec4(0)), - reflection_anisotropy_rotation=Input(fig, Vec4(0)), reflection_mode=Input(fig, Vec4(0)), - reflection_ior=Input(fig, Vec4(0)), reflection_metalness=Input(fig, Vec4(0)), - refraction_color=Input(fig, RGB(0, 0, 0)), refraction_weight=Input(fig, Vec4(0)), - refraction_roughness=Input(fig, Vec4(0)), refraction_ior=Input(fig, Vec4(0)), - refraction_absorption_color=Input(fig, RGB(0, 0, 0)), - refraction_absorption_distance=Input(fig, Vec4(0)), refraction_caustics=Input(fig, true), - sss_scatter_color=Input(fig, RGB(0, 0, 0)), sss_scatter_distance=Input(fig, Vec4(0)), - sss_scatter_direction=Input(fig, Vec4(0)), sss_weight=Input(fig, Vec4(0)), - sss_multiscatter=Input(fig, false), backscatter_weight=Input(fig, Vec4(0)), - backscatter_color=Input(fig, RGB(0, 0, 0))) +sliders = (reflection_color = Input(fig, RGB(0, 0, 0)), reflection_weight = Input(fig, Vec4(0)), + reflection_roughness = Input(fig, Vec4(0)), reflection_anisotropy = Input(fig, Vec4(0)), + reflection_anisotropy_rotation = Input(fig, Vec4(0)), reflection_mode = Input(fig, Vec4(0)), + reflection_ior = Input(fig, Vec4(0)), reflection_metalness = Input(fig, Vec4(0)), + refraction_color = Input(fig, RGB(0, 0, 0)), refraction_weight = Input(fig, Vec4(0)), + refraction_roughness = Input(fig, Vec4(0)), refraction_ior = Input(fig, Vec4(0)), + refraction_absorption_color = Input(fig, RGB(0, 0, 0)), + refraction_absorption_distance = Input(fig, Vec4(0)), refraction_caustics = Input(fig, true), + sss_scatter_color = Input(fig, RGB(0, 0, 0)), sss_scatter_distance = Input(fig, Vec4(0)), + sss_scatter_direction = Input(fig, Vec4(0)), sss_weight = Input(fig, Vec4(0)), + sss_multiscatter = Input(fig, false), backscatter_weight = Input(fig, Vec4(0)), + backscatter_color = Input(fig, RGB(0, 0, 0))) labels = [] inputs = [] refresh = Observable(nothing) for (key, (obs, input)) in pairs(sliders) - push!(labels, Label(fig, string(key); align=:left)) + push!(labels, Label(fig, string(key); align = :left)) push!(inputs, input) on(obs) do value @show key value @@ -68,7 +68,7 @@ for (key, (obs, input)) in pairs(sliders) end end -fig[1, 2] = grid!(hcat(labels, inputs); width=500) +fig[1, 2] = grid!(hcat(labels, inputs); width = 500) GLMakie.activate!() cam = cameracontrols(ax.scene) @@ -79,7 +79,7 @@ cam.fov[] = 30 display(fig) -context, task = RPRMakie.replace_scene_rpr!(ax.scene, screen; refresh=refresh) +context, task = RPRMakie.replace_scene_rpr!(ax.scene, screen; refresh = refresh) # Change light parameters interactively begin diff --git a/RPRMakie/examples/sea_cables.jl b/RPRMakie/examples/sea_cables.jl index 4c9a6b14a0f..760aef8636f 100644 --- a/RPRMakie/examples/sea_cables.jl +++ b/RPRMakie/examples/sea_cables.jl @@ -48,24 +48,24 @@ end earth_img = load(Downloads.download("https://upload.wikimedia.org/wikipedia/commons/5/56/Blue_Marble_Next_Generation_%2B_topography_%2B_bathymetry.jpg")) # the actual plot ! -RPRMakie.activate!(; iterations=100) +RPRMakie.activate!(; iterations = 100) scene = with_theme(theme_dark()) do - fig = Figure(; resolution=(1000, 1000)) + fig = Figure(; resolution = (1000, 1000)) radiance = 30 lights = [EnvironmentLight(0.5, load(RPR.assetpath("starmap_4k.tif"))), - PointLight(Vec3f(1, 1, 3), RGBf(radiance, radiance, radiance))] - ax = LScene(fig[1, 1]; show_axis=false, scenekw=(lights=lights,)) + PointLight(Vec3f(1, 1, 3), RGBf(radiance, radiance, radiance))] + ax = LScene(fig[1, 1]; show_axis = false, scenekw = (lights = lights,)) n = 1024 ÷ 4 # 2048 θ = LinRange(0, pi, n) φ = LinRange(-pi, pi, 2 * n) xe = [cos(φ) * sin(θ) for θ in θ, φ in φ] ye = [sin(φ) * sin(θ) for θ in θ, φ in φ] ze = [cos(θ) for θ in θ, φ in φ] - surface!(ax, xe, ye, ze; color=earth_img) - meshscatter!(toPoints3D; color=1:length(toPoints3D), markersize=0.005, colormap=:plasma) + surface!(ax, xe, ye, ze; color = earth_img) + meshscatter!(toPoints3D; color = 1:length(toPoints3D), markersize = 0.005, colormap = :plasma) colors = Makie.default_palettes.color[] c = Iterators.cycle(colors) - foreach(((l, c),) -> lines!(ax, l; linewidth=2, color=c), zip(splitLines3D, c)) + foreach(((l, c),) -> lines!(ax, l; linewidth = 2, color = c), zip(splitLines3D, c)) ax.scene.camera_controls.eyeposition[] = Vec3f(1.5) return ax.scene end diff --git a/RPRMakie/src/RPRMakie.jl b/RPRMakie/src/RPRMakie.jl index b3ddead9794..58b07dfd0ed 100644 --- a/RPRMakie/src/RPRMakie.jl +++ b/RPRMakie/src/RPRMakie.jl @@ -25,14 +25,12 @@ struct ScreenConfig plugin::RPR.PluginType end -function ScreenConfig(iterations::Int, max_recursion::Int, render_resource, render_plugin) - return ScreenConfig( - iterations, - max_recursion, - render_resource isa Makie.Automatic ? RPR.RPR_CREATION_FLAGS_ENABLE_GPU0 : render_resource, - render_plugin isa Makie.Automatic ? RPR.Tahoe : render_plugin - ) -end +ScreenConfig(iterations::Int, max_recursion::Int, render_resource, render_plugin) = ScreenConfig( + iterations, + max_recursion, + render_resource isa Makie.Automatic ? RPR.RPR_CREATION_FLAGS_ENABLE_GPU0 : render_resource, + render_plugin isa Makie.Automatic ? RPR.Tahoe : render_plugin +) include("scene.jl") include("lines.jl") @@ -61,7 +59,7 @@ function __init__() return end -for name in names(Makie; all=true) +for name in names(Makie; all = true) if Base.isexported(Makie, name) @eval using Makie: $(name) @eval export $(name) diff --git a/RPRMakie/src/lines.jl b/RPRMakie/src/lines.jl index 467ce80572e..654dab8bb0e 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) @@ -32,7 +32,7 @@ end function to_rpr_object(context, matsys, scene, plot::Makie.LineSegments) points = decompose(Point3f, to_value(plot[1])) - segments = TupleView{2,2}(RPR.rpr_int(0):RPR.rpr_int(length(points) - 1)) + segments = TupleView{2, 2}(RPR.rpr_int(0):RPR.rpr_int(length(points) - 1)) indices = RPR.rpr_int[] for (a, b) in segments @@ -56,7 +56,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.LineSegments) end curve = RPR.Curve(context, points, indices, radius, Vec2f.(0.0, LinRange(0, 1, nsegments)), - fill(1, nsegments)) + fill(1, nsegments)) material = RPR.DiffuseMaterial(matsys) color = to_color(plot.color[]) @@ -73,7 +73,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.LineSegments) if color isa AbstractVector{<:Colorant} set_color!(copy(color)) elseif color isa AbstractVector{<:Number} - sampler = Makie.sampler(to_colormap(plot.colormap[]), color; scaling=Makie.Scaling(identity, plot.colorrange[])) + sampler = Makie.sampler(to_colormap(plot.colormap[]), color; scaling = Makie.Scaling(identity, plot.colorrange[])) set_color!(collect(sampler)) else material.color = to_color(color) diff --git a/RPRMakie/src/meshes.jl b/RPRMakie/src/meshes.jl index 5f67806d33a..3b906f90996 100644 --- a/RPRMakie/src/meshes.jl +++ b/RPRMakie/src/meshes.jl @@ -1,13 +1,11 @@ -function extract_material(matsys, plot) - material = if haskey(plot, :material) - if plot.material isa Attributes - return RPR.Material(matsys, Dict(map(((k,v),)-> k => to_value(v), plot.material))) - else - return plot.material[] - end +extract_material(matsys, plot) = material = if haskey(plot, :material) + if plot.material isa Attributes + return RPR.Material(matsys, Dict(map(((k, v),) -> k => to_value(v), plot.material))) else - return RPR.DiffuseMaterial(matsys) + return plot.material[] end +else + return RPR.DiffuseMaterial(matsys) end function mesh_material(context, matsys, plot, color_obs = plot.color) @@ -29,7 +27,7 @@ function mesh_material(context, matsys, plot, color_obs = plot.color) tex.data = img return tex end - elseif color isa Colorant || color isa Union{String,Symbol} + elseif color isa Colorant || color isa Union{String, Symbol} map(to_color, color_obs) elseif color isa Nothing # ignore! @@ -70,7 +68,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.MeshScatter) RPR.rprShapeSetObjectID(marker, 0) material = if haskey(plot, :material) if plot.material isa Attributes - RPR.Material(matsys, Dict(map(((k,v),)-> k => to_value(v), plot.material))) + RPR.Material(matsys, Dict(map(((k, v),) -> k => to_value(v), plot.material))) else plot.material[] end @@ -78,7 +76,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.MeshScatter) RPR.DiffuseMaterial(matsys) end set!(marker, material) - for i in 1:(n_instances-1) + for i in 1:(n_instances - 1) inst = RPR.Shape(context, marker) RPR.rprShapeSetObjectID(inst, i) push!(instances, inst) @@ -93,7 +91,7 @@ function to_rpr_object(context, matsys, scene, plot::Makie.MeshScatter) object_id = RPR.InputLookupMaterial(matsys) object_id.value = RPR.RPR_MATERIAL_NODE_LOOKUP_OBJECT_ID - uv = object_id * Vec3f(0, 1/n_instances, 0) + uv = object_id * Vec3f(0, 1 / n_instances, 0) tex = RPR.Texture(matsys, collect(color_from_num'); uv = uv) @@ -151,7 +149,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 +173,7 @@ function Makie.plot!(plot::Matball) mat = getproperty(plot, name)[] mat = mat isa Makie.Automatic ? base : mat mesh = load(assetpath("matball_$(name).obj")) - mesh!(plot, mesh, material=mat, color=plot.color) + mesh!(plot, mesh, material = mat, color = plot.color) end return plot end diff --git a/RPRMakie/src/scene.jl b/RPRMakie/src/scene.jl index 20ea24b3067..c6c832037a6 100644 --- a/RPRMakie/src/scene.jl +++ b/RPRMakie/src/scene.jl @@ -14,7 +14,7 @@ function update_rpr_camera!(oldvals, camera, cam_controls, cam) RPR.rprCameraSetFarPlane(camera, far) RPR.rprCameraSetNearPlane(camera, near) h = norm(res) - RPR.rprCameraSetFocalLength(camera, (30*h)/fov) + RPR.rprCameraSetFocalLength(camera, (30 * h) / fov) # RPR_CAMERA_FSTOP # RPR_CAMERA_MODE return new_vals @@ -25,12 +25,12 @@ function to_rpr_object(context, matsys, scene, plot) return nothing end -function insert_plots!(context, matsys, scene, mscene::Makie.Scene, @nospecialize(plot::Combined)) +insert_plots!(context, matsys, scene, mscene::Makie.Scene, @nospecialize(plot::Combined)) = if isempty(plot.plots) # if no plots inserted, this truly is an atomic 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 @@ -40,7 +40,6 @@ function insert_plots!(context, matsys, scene, mscene::Makie.Scene, @nospecializ insert_plots!(context, matsys, scene, mscene, plot) end end -end function to_rpr_light(context::RPR.Context, light::Makie.PointLight) pointlight = RPR.PointLight(context) @@ -83,7 +82,7 @@ function to_rpr_scene(context::RPR.Context, matsys, mscene::Makie.Scene) set!(context, scene) # Only set background image if it isn't set by env light, since # background image takes precedence - if !any(x-> x isa Makie.EnvironmentLight, mscene.lights) + if !any(x -> x isa Makie.EnvironmentLight, mscene.lights) env_img = fill(to_color(mscene.backgroundcolor[]), 1, 1) img = RPR.Image(context, env_img) RPR.rprSceneSetBackgroundImage(scene, img) @@ -99,7 +98,7 @@ function to_rpr_scene(context::RPR.Context, matsys, mscene::Makie.Scene) return scene end -function replace_scene_rpr!(scene::Makie.Scene, screen=Screen(scene); refresh=Observable(nothing)) +function replace_scene_rpr!(scene::Makie.Scene, screen = Screen(scene); refresh = Observable(nothing)) context = screen.context matsys = screen.matsys screen.scene = scene @@ -129,13 +128,13 @@ function replace_scene_rpr!(scene::Makie.Scene, screen=Screen(scene); refresh=Ob cam_values = (;) task = @async while isopen(scene) cam_values = update_rpr_camera!(cam_values, camera, cam_controls, cam) - framebuffer2 = render(screen; clear=clear, iterations=1) + framebuffer2 = render(screen; clear = clear, iterations = 1) if clear clear = false end data = RPR.get_data(framebuffer2) - im[1] = reverse(reshape(data, screen.fb_size); dims=2) - sleep(1/10) + im[1] = reverse(reshape(data, screen.fb_size); dims = 2) + sleep(1 / 10) end return context, task, rpr_scene end @@ -173,7 +172,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) @@ -196,8 +195,8 @@ end 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) +function Screen(fb_size::NTuple{2, <:Integer}, config::ScreenConfig) + context = RPR.Context(; resource = config.resource, plugin = config.plugin) matsys = RPR.MaterialSystem(context, 0) set_standard_tonemapping!(context) set!(context, RPR.RPR_CONTEXT_MAX_RECURSION, UInt(config.max_recursion)) @@ -210,7 +209,7 @@ function Screen(fb_size::NTuple{2,<:Integer}, config::ScreenConfig) config.iterations, false) end -function render(screen; clear=true, iterations=screen.iterations) +function render(screen; clear = true, iterations = screen.iterations) context = screen.context fb_size = screen.fb_size framebuffer1 = screen.framebuffer1 @@ -239,10 +238,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 diff --git a/RPRMakie/test/lines.jl b/RPRMakie/test/lines.jl index e36c4698486..f95d95d3bb7 100644 --- a/RPRMakie/test/lines.jl +++ b/RPRMakie/test/lines.jl @@ -2,7 +2,7 @@ using GLMakie, GeometryBasics, RPRMakie, RadeonProRender using Colors, FileIO using Colors: N0f8 RPR = RadeonProRender -GLMakie.activate!(float=true, focus_on_show=false) +GLMakie.activate!(float = true, focus_on_show = false) cat = load(GLMakie.assetpath("cat.obj")) begin @@ -12,16 +12,16 @@ begin emissive = RPR.EmissiveMaterial(matsys) diffuse = RPR.DiffuseMaterial(matsys) - fig = Figure(resolution=(1000, 1000)) - ax = LScene(fig[1, 1], show_axis=false) + fig = Figure(resolution = (1000, 1000)) + ax = LScene(fig[1, 1], show_axis = false) for i in 4:4:12 n = i + 1 y = LinRange(0, i, n) y2 = (y ./ 2) .- 2 - lines!(ax, fill((i-5) ./ 2, n), y2, sin.(y) .+ 1, linewidth=5) + lines!(ax, fill((i - 5) ./ 2, n), y2, sin.(y) .+ 1, linewidth = 5) end - mesh!(ax, Rect3f(Vec3f(-3, -3, -0.1), Vec3f(6, 6, 0.1)), color=:white) - mesh!(ax, Sphere(Point3f(0, 0, 2), 0.1), material=emissive) + mesh!(ax, Rect3f(Vec3f(-3, -3, -0.1), Vec3f(6, 6, 0.1)), color = :white) + mesh!(ax, Sphere(Point3f(0, 0, 2), 0.1), material = emissive) display(fig) end # fetch(task) @@ -32,41 +32,41 @@ end begin - uber1.color =Vec4f(1, 1, 1, 1) - uber1.diffuse_weight =Vec4f(0, 0, 0, 0) - uber1.diffuse_roughness =Vec4f(1, 1, 1, 1) - uber1.reflection_color =Vec4f(0.996078, 0.858824, 0.639216, 0) - uber1.reflection_weight =Vec4f(1, 1, 1, 1) - uber1.reflection_roughness =Vec4f(0, 0, 0, 0) - uber1.reflection_anisotropy =Vec4f(0, 0, 0, 0) - uber1.reflection_anisotropy_rotation =Vec4f(0, 0, 0, 0) - uber1.reflection_ior =Vec4f(1.36, 1.36, 1.36, 1.36) - uber1.refraction_color =Vec4f(0.996078, 0.858824, 0.639216, 0) - uber1.refraction_weight =Vec4f(1, 1, 1, 1) - uber1.refraction_roughness =Vec4f(0, 0, 0, 0) - uber1.refraction_ior =Vec4f(1.36, 1.36, 1.36, 1.36) - uber1.refraction_absorption_color =Vec4f(0.996078, 0.858824, 0.639216, 0) - uber1.refraction_absorption_distance =Vec4f(0, 0, 0, 0) - uber1.refraction_caustics =Vec4f(0) - uber1.coating_color =Vec4f(1, 1, 1, 1) - uber1.coating_weight =Vec4f(0, 0, 0, 0) - uber1.coating_roughness =Vec4f(0, 0, 0, 0) - uber1.coating_ior =Vec4f(3, 3, 3, 3) - uber1.coating_metalness =Vec4f(0, 0, 0, 0) - uber1.coating_transmission_color =Vec4f(1, 1, 1, 1) - uber1.coating_thickness =Vec4f(0, 0, 0, 0) - uber1.sheen =Vec4f(1, 1, 1, 1) - uber1.sheen_tint =Vec4f(0, 0, 0, 0) - uber1.sheen_weight =Vec4f(0, 0, 0, 0) - uber1.emission_color =Vec4f(1, 1, 1, 1) - uber1.emission_weight =Vec3f( 0, 0, 0) - uber1.transparency =Vec4f(0, 0, 0, 0) - uber1.sss_scatter_color =Vec4f(0, 0, 0, 0) - uber1.sss_scatter_distance =Vec4f(0, 0, 0, 0) - uber1.sss_scatter_direction =Vec4f(0, 0, 0, 0) - uber1.sss_weight =Vec4f(0, 0, 0, 0) - uber1.backscatter_weight =Vec4f(0, 0, 0, 0) - uber1.backscatter_color =Vec4f(1, 1, 1, 1) + uber1.color = Vec4f(1, 1, 1, 1) + uber1.diffuse_weight = Vec4f(0, 0, 0, 0) + uber1.diffuse_roughness = Vec4f(1, 1, 1, 1) + uber1.reflection_color = Vec4f(0.996078, 0.858824, 0.639216, 0) + uber1.reflection_weight = Vec4f(1, 1, 1, 1) + uber1.reflection_roughness = Vec4f(0, 0, 0, 0) + uber1.reflection_anisotropy = Vec4f(0, 0, 0, 0) + uber1.reflection_anisotropy_rotation = Vec4f(0, 0, 0, 0) + uber1.reflection_ior = Vec4f(1.36, 1.36, 1.36, 1.36) + uber1.refraction_color = Vec4f(0.996078, 0.858824, 0.639216, 0) + uber1.refraction_weight = Vec4f(1, 1, 1, 1) + uber1.refraction_roughness = Vec4f(0, 0, 0, 0) + uber1.refraction_ior = Vec4f(1.36, 1.36, 1.36, 1.36) + uber1.refraction_absorption_color = Vec4f(0.996078, 0.858824, 0.639216, 0) + uber1.refraction_absorption_distance = Vec4f(0, 0, 0, 0) + uber1.refraction_caustics = Vec4f(0) + uber1.coating_color = Vec4f(1, 1, 1, 1) + uber1.coating_weight = Vec4f(0, 0, 0, 0) + uber1.coating_roughness = Vec4f(0, 0, 0, 0) + uber1.coating_ior = Vec4f(3, 3, 3, 3) + uber1.coating_metalness = Vec4f(0, 0, 0, 0) + uber1.coating_transmission_color = Vec4f(1, 1, 1, 1) + uber1.coating_thickness = Vec4f(0, 0, 0, 0) + uber1.sheen = Vec4f(1, 1, 1, 1) + uber1.sheen_tint = Vec4f(0, 0, 0, 0) + uber1.sheen_weight = Vec4f(0, 0, 0, 0) + uber1.emission_color = Vec4f(1, 1, 1, 1) + uber1.emission_weight = Vec3f(0, 0, 0) + uber1.transparency = Vec4f(0, 0, 0, 0) + uber1.sss_scatter_color = Vec4f(0, 0, 0, 0) + uber1.sss_scatter_distance = Vec4f(0, 0, 0, 0) + uber1.sss_scatter_direction = Vec4f(0, 0, 0, 0) + uber1.sss_weight = Vec4f(0, 0, 0, 0) + uber1.backscatter_weight = Vec4f(0, 0, 0, 0) + uber1.backscatter_color = Vec4f(1, 1, 1, 1) uber1.reflection_mode = UInt(RPR.RPR_UBER_MATERIAL_IOR_MODE_PBR) uber1.emission_mode = UInt(RPR.RPR_UBER_MATERIAL_EMISSION_MODE_SINGLESIDED) @@ -77,131 +77,131 @@ end begin - uber2.color = Vec4f(0.501961f0,0.0f0,0.0f0,0.0f0) - uber2.diffuse_weight = Vec4f(1.0f0,1.0f0,1.0f0,1.0f0) - uber2.diffuse_roughness = Vec4f(0.500000f0,0.500000f0,0.500000f0,0.500000f0) - uber2.reflection_color = Vec4f(0.490196f0,0.490196f0,0.490196f0,0.0f0) - uber2.reflection_weight = Vec4f(0.990000f0,0.990000f0,0.990000f0,0.990000f0) - uber2.reflection_roughness = Vec4f(0.008000f0,0.008000f0,0.008000f0,0.008000f0) - uber2.reflection_anisotropy = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.reflection_anisotropy_rotation = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) + uber2.color = Vec4f(0.501961f0, 0.0f0, 0.0f0, 0.0f0) + uber2.diffuse_weight = Vec4f(1.0f0, 1.0f0, 1.0f0, 1.0f0) + uber2.diffuse_roughness = Vec4f(0.500000f0, 0.500000f0, 0.500000f0, 0.500000f0) + uber2.reflection_color = Vec4f(0.490196f0, 0.490196f0, 0.490196f0, 0.0f0) + uber2.reflection_weight = Vec4f(0.990000f0, 0.990000f0, 0.990000f0, 0.990000f0) + uber2.reflection_roughness = Vec4f(0.008000f0, 0.008000f0, 0.008000f0, 0.008000f0) + uber2.reflection_anisotropy = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.reflection_anisotropy_rotation = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) uber2.reflection_mode = 1 - uber2.reflection_ior = Vec4f(1.460000f0,1.460000f0,1.460000f0,1.460000f0) - uber2.refraction_color = Vec4f(1.0f0,1.0f0,1.0f0,1.0f0) - uber2.refraction_weight = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.refraction_roughness = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.refraction_ior = Vec4f(1.500000f0,1.500000f0,1.500000f0,1.500000f0) + uber2.reflection_ior = Vec4f(1.460000f0, 1.460000f0, 1.460000f0, 1.460000f0) + uber2.refraction_color = Vec4f(1.0f0, 1.0f0, 1.0f0, 1.0f0) + uber2.refraction_weight = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.refraction_roughness = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.refraction_ior = Vec4f(1.500000f0, 1.500000f0, 1.500000f0, 1.500000f0) uber2.refraction_thin_surface = Vec4f(0) - uber2.refraction_absorption_color = Vec4f(1.0f0,1.0f0,1.0f0,0.0f0) - uber2.refraction_absorption_distance = Vec4f(1.0f0,1.0f0,1.0f0,0.0f0) + uber2.refraction_absorption_color = Vec4f(1.0f0, 1.0f0, 1.0f0, 0.0f0) + uber2.refraction_absorption_distance = Vec4f(1.0f0, 1.0f0, 1.0f0, 0.0f0) uber2.refraction_caustics = 1 - uber2.coating_color = Vec4f(0.490196f0,0.490196f0,0.490196f0,0.0f0) - uber2.coating_weight = Vec4f(1.0f0,1.0f0,1.0f0,1.0f0) - uber2.coating_roughness = Vec4f(0.008000f0,0.008000f0,0.008000f0,0.008000f0) + uber2.coating_color = Vec4f(0.490196f0, 0.490196f0, 0.490196f0, 0.0f0) + uber2.coating_weight = Vec4f(1.0f0, 1.0f0, 1.0f0, 1.0f0) + uber2.coating_roughness = Vec4f(0.008000f0, 0.008000f0, 0.008000f0, 0.008000f0) uber2.coating_mode = 1 - uber2.coating_ior = Vec4f(1.460000f0,1.460000f0,1.460000f0,1.460000f0) - uber2.coating_metalness = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.coating_transmission_color = Vec4f(0.0f0,0.0f0,0.0f0,1.0f0) - uber2.coating_thickness = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sheen = Vec4f(1.0f0,1.0f0,1.0f0,1.0f0) - uber2.sheen_tint = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sheen_weight = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.emission_color = Vec4f(1.0f0,1.0f0,1.0f0,1.0f0) - uber2.emission_weight = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) + uber2.coating_ior = Vec4f(1.460000f0, 1.460000f0, 1.460000f0, 1.460000f0) + uber2.coating_metalness = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.coating_transmission_color = Vec4f(0.0f0, 0.0f0, 0.0f0, 1.0f0) + uber2.coating_thickness = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sheen = Vec4f(1.0f0, 1.0f0, 1.0f0, 1.0f0) + uber2.sheen_tint = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sheen_weight = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.emission_color = Vec4f(1.0f0, 1.0f0, 1.0f0, 1.0f0) + uber2.emission_weight = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) uber2.emission_mode = 1 - uber2.transparency = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sss_scatter_color = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sss_scatter_distance = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sss_scatter_direction = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.sss_weight = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) + uber2.transparency = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sss_scatter_color = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sss_scatter_distance = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sss_scatter_direction = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.sss_weight = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) uber2.sss_multiscatter = false - uber2.backscatter_weight = Vec4f(0.0f0,0.0f0,0.0f0,0.0f0) - uber2.backscatter_color = Vec4f(0.501961f0,0.0f0,0.0f0,0.0f0) + uber2.backscatter_weight = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + uber2.backscatter_color = Vec4f(0.501961f0, 0.0f0, 0.0f0, 0.0f0) end begin - uber3.color = Vec4(0.752941,0.596078,0.443137,0.0) - uber3.diffuse_weight = Vec4(1.0,1.0,1.0,1.0) - uber3.diffuse_roughness = Vec4(0.500000,0.500000,0.500000,0.500000) - uber3.reflection_color = Vec4(0.666667,0.490196,0.313726,0.0) - uber3.reflection_weight = Vec4(1.0,1.0,1.0,1.0) - uber3.reflection_roughness = Vec4(0.300000,0.300000,0.300000,0.300000) - uber3.reflection_anisotropy = Vec4(0.0,0.0,0.0,0.0) - uber3.reflection_anisotropy_rotation = Vec4(0.0,0.0,0.0,0.0) + uber3.color = Vec4(0.752941, 0.596078, 0.443137, 0.0) + uber3.diffuse_weight = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.diffuse_roughness = Vec4(0.500000, 0.500000, 0.500000, 0.500000) + uber3.reflection_color = Vec4(0.666667, 0.490196, 0.313726, 0.0) + uber3.reflection_weight = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.reflection_roughness = Vec4(0.300000, 0.300000, 0.300000, 0.300000) + uber3.reflection_anisotropy = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.reflection_anisotropy_rotation = Vec4(0.0, 0.0, 0.0, 0.0) uber3.reflection_mode = 2 - uber3.reflection_ior = Vec4(1.0,1.0,1.0,1.0) - uber3.refraction_color = Vec4(1.0,1.0,1.0,1.0) - uber3.refraction_weight = Vec4(0.0,0.0,0.0,0.0) - uber3.refraction_roughness = Vec4(0.0,0.0,0.0,0.0) - uber3.refraction_ior = Vec4(1.500000,1.500000,1.500000,1.500000) + uber3.reflection_ior = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.refraction_color = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.refraction_weight = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.refraction_roughness = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.refraction_ior = Vec4(1.500000, 1.500000, 1.500000, 1.500000) uber3.refraction_thin_surface = 0 - uber3.refraction_absorption_color = Vec4(1.0,1.0,1.0,0.0) - uber3.refraction_absorption_distance = Vec4(1.0,1.0,1.0,0.0) + uber3.refraction_absorption_color = Vec4(1.0, 1.0, 1.0, 0.0) + uber3.refraction_absorption_distance = Vec4(1.0, 1.0, 1.0, 0.0) uber3.refraction_caustics = 1 - uber3.coating_color = Vec4(0.752941,0.596078,0.443137,0.0) - uber3.coating_weight = Vec4(1.0,1.0,1.0,1.0) - uber3.coating_roughness = Vec4(0.420000,0.420000,0.420000,0.420000) + uber3.coating_color = Vec4(0.752941, 0.596078, 0.443137, 0.0) + uber3.coating_weight = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.coating_roughness = Vec4(0.420000, 0.420000, 0.420000, 0.420000) uber3.coating_mode = 1 - uber3.coating_ior = Vec4(1.700000,1.700000,1.700000,1.700000) - uber3.coating_metalness = Vec4(0.0,0.0,0.0,0.0) - uber3.coating_transmission_color = Vec4(0.0,0.0,0.0,1.0) - uber3.coating_thickness = Vec4(0.0,0.0,0.0,0.0) - uber3.sheen = Vec4(1.0,1.0,1.0,1.0) - uber3.sheen_tint = Vec4(0.0,0.0,0.0,0.0) - uber3.sheen_weight = Vec4(0.0,0.0,0.0,0.0) - uber3.emission_color = Vec4(1.0,1.0,1.0,1.0) - uber3.emission_weight = Vec4(0.0,0.0,0.0,0.0) + uber3.coating_ior = Vec4(1.700000, 1.700000, 1.700000, 1.700000) + uber3.coating_metalness = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.coating_transmission_color = Vec4(0.0, 0.0, 0.0, 1.0) + uber3.coating_thickness = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sheen = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.sheen_tint = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sheen_weight = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.emission_color = Vec4(1.0, 1.0, 1.0, 1.0) + uber3.emission_weight = Vec4(0.0, 0.0, 0.0, 0.0) uber3.emission_mode = 1 - uber3.transparency = Vec4(0.0,0.0,0.0,0.0) - uber3.sss_scatter_color = Vec4(0.0,0.0,0.0,0.0) - uber3.sss_scatter_distance = Vec4(0.0,0.0,0.0,0.0) - uber3.sss_scatter_direction = Vec4(0.0,0.0,0.0,0.0) - uber3.sss_weight = Vec4(0.0,0.0,0.0,0.0) + uber3.transparency = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sss_scatter_color = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sss_scatter_distance = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sss_scatter_direction = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.sss_weight = Vec4(0.0, 0.0, 0.0, 0.0) uber3.sss_multiscatter = 0 - uber3.backscatter_weight = Vec4(0.0,0.0,0.0,0.0) - uber3.backscatter_color = Vec4(0.752941,0.596078,0.443137,0.0) + uber3.backscatter_weight = Vec4(0.0, 0.0, 0.0, 0.0) + uber3.backscatter_color = Vec4(0.752941, 0.596078, 0.443137, 0.0) end begin - uber4.color = Vec4f(1.0,1.0,1.0,1.0) - uber4.diffuse_weight = Vec4f(0.0,0.0,0.0,0.0) - uber4.diffuse_roughness = Vec4f(1.0,1.0,1.0,1.0) - uber4.reflection_color = Vec4f(0.501961,0.501961,0.501961,0.0) - uber4.reflection_weight = Vec4f(1.0,1.0,1.0,1.0) - uber4.reflection_roughness = Vec4f(0.0,0.0,0.0,0.0) - uber4.reflection_anisotropy = Vec4f(0.0,0.0,0.0,0.0) - uber4.reflection_anisotropy_rotation = Vec4f(0.0,0.0,0.0,0.0) + uber4.color = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.diffuse_weight = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.diffuse_roughness = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.reflection_color = Vec4f(0.501961, 0.501961, 0.501961, 0.0) + uber4.reflection_weight = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.reflection_roughness = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.reflection_anisotropy = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.reflection_anisotropy_rotation = Vec4f(0.0, 0.0, 0.0, 0.0) uber4.reflection_mode = 1 - uber4.reflection_ior = Vec4f(1.330000,1.330000,1.330000,1.330000) - uber4.refraction_color = Vec4f(0.501961,0.898039,0.996078,0.0) - uber4.refraction_weight = Vec4f(1.0,1.0,1.0,1.0) - uber4.refraction_roughness = Vec4f(0.0,0.0,0.0,0.0) - uber4.refraction_ior = Vec4f(1.330000,1.330000,1.330000,1.330000) + uber4.reflection_ior = Vec4f(1.330000, 1.330000, 1.330000, 1.330000) + uber4.refraction_color = Vec4f(0.501961, 0.898039, 0.996078, 0.0) + uber4.refraction_weight = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.refraction_roughness = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.refraction_ior = Vec4f(1.330000, 1.330000, 1.330000, 1.330000) uber4.refraction_thin_surface = 0 - uber4.refraction_absorption_color = Vec4f(0.501961,0.898039,0.996078,0.0) - uber4.refraction_absorption_distance = Vec4f(0.0,0.0,0.0,0.0) + uber4.refraction_absorption_color = Vec4f(0.501961, 0.898039, 0.996078, 0.0) + uber4.refraction_absorption_distance = Vec4f(0.0, 0.0, 0.0, 0.0) uber4.refraction_caustics = 0 - uber4.coating_color = Vec4f(1.0,1.0,1.0,1.0) - uber4.coating_weight = Vec4f(0.0,0.0,0.0,0.0) - uber4.coating_roughness = Vec4f(0.0,0.0,0.0,0.0) + uber4.coating_color = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.coating_weight = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.coating_roughness = Vec4f(0.0, 0.0, 0.0, 0.0) uber4.coating_mode = 1 - uber4.coating_ior = Vec4f(3.0,3.0,3.0,3.0) - uber4.coating_metalness = Vec4f(0.0,0.0,0.0,0.0) - uber4.coating_transmission_color = Vec4f(1.0,1.0,1.0,1.0) - uber4.coating_thickness = Vec4f(0.0,0.0,0.0,0.0) - uber4.sheen = Vec4f(1.0,1.0,1.0,1.0) - uber4.sheen_tint = Vec4f(0.0,0.0,0.0,0.0) - uber4.sheen_weight = Vec4f(0.0,0.0,0.0,0.0) - uber4.emission_color = Vec4f(1.0,1.0,1.0,1.0) - uber4.emission_weight = Vec4f(0.0,0.0,0.0,0.0) + uber4.coating_ior = Vec4f(3.0, 3.0, 3.0, 3.0) + uber4.coating_metalness = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.coating_transmission_color = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.coating_thickness = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sheen = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.sheen_tint = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sheen_weight = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.emission_color = Vec4f(1.0, 1.0, 1.0, 1.0) + uber4.emission_weight = Vec4f(0.0, 0.0, 0.0, 0.0) uber4.emission_mode = 1 - uber4.transparency = Vec4f(0.0,0.0,0.0,0.0) - uber4.sss_scatter_color = Vec4f(0.0,0.0,0.0,0.0) - uber4.sss_scatter_distance = Vec4f(0.0,0.0,0.0,0.0) - uber4.sss_scatter_direction = Vec4f(0.0,0.0,0.0,0.0) - uber4.sss_weight = Vec4f(0.0,0.0,0.0,0.0) + uber4.transparency = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sss_scatter_color = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sss_scatter_distance = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sss_scatter_direction = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.sss_weight = Vec4f(0.0, 0.0, 0.0, 0.0) uber4.sss_multiscatter = 0 - uber4.backscatter_weight = Vec4f(0.0,0.0,0.0,0.0) - uber4.backscatter_color = Vec4f(1.0,1.0,1.0,1.0) + uber4.backscatter_weight = Vec4f(0.0, 0.0, 0.0, 0.0) + uber4.backscatter_color = Vec4f(1.0, 1.0, 1.0, 1.0) end diff --git a/RPRMakie/test/runtests.jl b/RPRMakie/test/runtests.jl index 4a66aafb4bb..f64afa53fdb 100644 --- a/RPRMakie/test/runtests.jl +++ b/RPRMakie/test/runtests.jl @@ -1,9 +1,9 @@ using RPRMakie using Test -RPRMakie.activate!(resource=RPR.RPR_CREATION_FLAGS_ENABLE_CPU, iterations=50) -f, ax, pl = meshscatter(rand(Point3f, 100), color=:blue) +RPRMakie.activate!(resource = RPR.RPR_CREATION_FLAGS_ENABLE_CPU, iterations = 50) +f, ax, pl = meshscatter(rand(Point3f, 100), color = :blue) out = joinpath(@__DIR__, "recorded") -isdir(out) && rm(out; recursive=true, force=true) +isdir(out) && rm(out; recursive = true, force = true) mkdir(out) save(joinpath(out, "test.png"), ax.scene); diff --git a/ReferenceTests/src/database.jl b/ReferenceTests/src/database.jl index 99edfd79b1e..639ec8744de 100644 --- a/ReferenceTests/src/database.jl +++ b/ReferenceTests/src/database.jl @@ -4,7 +4,9 @@ function used_functions(code) if @capture(x, f_(xs__)) push!(used_functions, Symbol(string(f))) end - if @capture(x, f_(xs__) do; body__; end) + if @capture(x, f_(xs__) do + body__ + end) push!(used_functions, Symbol(string(f))) end return x @@ -27,7 +29,7 @@ Records `code` and saves the result to `joinpath(ReferenceTests.RECORDING_DIR[], macro reference_test(name, code) title = string(name) funcs = used_functions(code) - skip = (title in SKIP_TITLES) || any(x-> x in funcs, SKIP_FUNCTIONS) + skip = (title in SKIP_TITLES) || any(x -> x in funcs, SKIP_FUNCTIONS) return quote @testset $(title) begin if $skip @@ -37,7 +39,7 @@ macro reference_test(name, code) error("title must be unique. Duplicate title: $(title)") end println("running $(lpad(COUNTER[] += 1, 3)): $($title)") - Makie.set_theme!(resolution=(500, 500)) + Makie.set_theme!(resolution = (500, 500)) ReferenceTests.RNG.seed_rng!() result = let $(esc(code)) @@ -55,24 +57,24 @@ end Helper, to more easily save all kind of results from the test database """ function save_result(path::String, scene::Makie.FigureLike) - isfile(path * ".png") && rm(path * ".png"; force=true) + isfile(path * ".png") && rm(path * ".png"; force = true) FileIO.save(path * ".png", scene) return true end function save_result(path::String, stream::VideoStream) - isfile(path * ".mp4") && rm(path * ".mp4"; force=true) + isfile(path * ".mp4") && rm(path * ".mp4"; force = true) FileIO.save(path * ".mp4", stream) return true end function save_result(path::String, object) - isfile(path) && rm(path; force=true) + isfile(path) && rm(path; force = true) FileIO.save(path, object) return true end -function mark_broken_tests(title_excludes = []; functions=[]) +function mark_broken_tests(title_excludes = []; functions = []) empty!(SKIP_TITLES) empty!(SKIP_FUNCTIONS) union!(SKIP_TITLES, title_excludes) @@ -87,7 +89,7 @@ macro include_reference_tests(path) include_path = isdir($path) ? $path : joinpath(@__DIR__, "tests", $path) recording_dir = joinpath($toplevel_folder, "recorded_reference_images", name) if isdir(recording_dir) - rm(recording_dir; force=true, recursive=true) + rm(recording_dir; force = true, recursive = true) end ReferenceTests.RECORDING_DIR[] = joinpath(recording_dir, "recorded") mkpath(joinpath(recording_dir, "recorded")) diff --git a/ReferenceTests/src/image_download.jl b/ReferenceTests/src/image_download.jl index 8f3076fc100..ec219185214 100644 --- a/ReferenceTests/src/image_download.jl +++ b/ReferenceTests/src/image_download.jl @@ -5,7 +5,7 @@ function last_major_version() return "v" * string(VersionNumber(version.major, version.minor)) end -function download_refimages(tag=last_major_version(); name="refimages") +function download_refimages(tag = last_major_version(); name = "refimages") url = "https://github.com/MakieOrg/Makie.jl/releases/download/$(tag)/$(name).tar" images_tar = basedir("$(name).tar") images = basedir(name) @@ -17,7 +17,7 @@ function download_refimages(tag=last_major_version(); name="refimages") end end !isfile(images_tar) && download(url, images_tar) - isdir(images) && rm(images, recursive=true, force=true) + isdir(images) && rm(images, recursive = true, force = true) Tar.extract(images_tar, images) return images end diff --git a/ReferenceTests/src/runtests.jl b/ReferenceTests/src/runtests.jl index 13526823361..ddd1a4eddce 100644 --- a/ReferenceTests/src/runtests.jl +++ b/ReferenceTests/src/runtests.jl @@ -1,8 +1,6 @@ -function get_frames(a, b) - return (get_frames(a), get_frames(b)) -end +get_frames(a, b) = (get_frames(a), get_frames(b)) -function get_frames(video) +get_frames(video) = mktempdir() do folder afolder = joinpath(folder, "a") mkpath(afolder) @@ -11,20 +9,17 @@ function get_frames(video) if length(aframes) > 10 # we don't want to compare too many frames since it's time costly # so we just compare 10 random frames if more than 10 - samples = range(1, stop=length(aframes), length=10) + samples = range(1, stop = length(aframes), length = 10) istep = round(Int, length(aframes) / 10) samples = 1:istep:length(aframes) aframes = aframes[samples] end return load.(aframes) end -end -function compare_media(a::Matrix, b::Matrix; sigma=[1,1]) - Images.test_approx_eq_sigma_eps(a, b, sigma, Inf) -end +compare_media(a::Matrix, b::Matrix; sigma = [1, 1]) = Images.test_approx_eq_sigma_eps(a, b, sigma, Inf) -function compare_media(a, b; sigma=[1,1]) +function compare_media(a, b; sigma = [1, 1]) file, ext = splitext(a) if ext in (".png", ".jpg", ".jpeg", ".JPEG", ".JPG") imga = load(a) @@ -34,7 +29,7 @@ function compare_media(a, b; sigma=[1,1]) return Inf end conv(x) = convert(Matrix{RGBf}, x) - return compare_media(conv(imga), conv(imgb), sigma=sigma) + return compare_media(conv(imga), conv(imgb), sigma = sigma) elseif ext in (".mp4", ".gif") aframes, bframes = get_frames(a, b) # Frames can differ in length, which usually shouldn't be the case but can happen @@ -44,21 +39,20 @@ function compare_media(a, b; sigma=[1,1]) @warn "not the same number of frames in video, difference will be Inf" return Inf end - return mean(compare_media.(aframes, bframes; sigma=sigma)) + return mean(compare_media.(aframes, bframes; sigma = sigma)) else error("Unknown media extension: $ext") end end -function get_all_relative_filepaths_recursively(dir) +get_all_relative_filepaths_recursively(dir) = mapreduce(vcat, walkdir(dir)) do (root, dirs, files) relpath.(joinpath.(root, files), dir) end -end -function record_comparison(base_folder::String; record_folder_name="recorded", reference_name = basename(base_folder), tag=last_major_version()) +function record_comparison(base_folder::String; record_folder_name = "recorded", reference_name = basename(base_folder), tag = last_major_version()) record_folder = joinpath(base_folder, record_folder_name) - reference_folder = download_refimages(tag; name=reference_name) + reference_folder = download_refimages(tag; name = reference_name) # we copy the reference images into the output folder, since we want to upload it all as an artifact, to know against what images we compared cp(reference_folder, joinpath(base_folder, "reference")) testimage_paths = get_all_relative_filepaths_recursively(record_folder) @@ -80,17 +74,15 @@ function record_comparison(base_folder::String; record_folder_name="recorded", r return missing_refimages, scores end -function test_comparison(scores; threshold) - @testset "Comparison scores" begin - for (image, score) in pairs(scores) - @testset "$image" begin - @test score <= threshold - end +test_comparison(scores; threshold) = @testset "Comparison scores" begin + for (image, score) in pairs(scores) + @testset "$image" begin + @test score <= threshold end 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..fe00fe3094e 100644 --- a/ReferenceTests/src/stable_rng.jl +++ b/ReferenceTests/src/stable_rng.jl @@ -11,13 +11,9 @@ 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 - return T(Base.rand(r), Base.rand(r), Base.rand(r), Base.rand(r)) -end +Base.rand(r::StableRNGs.LehmerRNG, ::Random.SamplerType{T}) where T <: ColorAlpha = T(Base.rand(r), Base.rand(r), Base.rand(r), Base.rand(r)) -function Base.rand(r::StableRNGs.LehmerRNG, ::Random.SamplerType{T}) where T <: AbstractRGB - return T(Base.rand(r), Base.rand(r), Base.rand(r)) -end +Base.rand(r::StableRNGs.LehmerRNG, ::Random.SamplerType{T}) where T <: AbstractRGB = T(Base.rand(r), Base.rand(r), Base.rand(r)) end diff --git a/ReferenceTests/src/tests/attributes.jl b/ReferenceTests/src/tests/attributes.jl index e81f432d05f..46b3a282c8c 100644 --- a/ReferenceTests/src/tests/attributes.jl +++ b/ReferenceTests/src/tests/attributes.jl @@ -1,39 +1,39 @@ @reference_test "glowcolor, glowwidth" begin - scatter(RNG.randn(10), color=:blue, glowcolor=:orange, glowwidth=10) + scatter(RNG.randn(10), color = :blue, glowcolor = :orange, glowwidth = 10) end @reference_test "isorange, isovalue" begin - r = range(-1, stop=1, length=100) - matr = [(x.^2 + y.^2 + z.^2) for x = r, y = r, z = r] - volume(matr .* (matr .> 1.4), algorithm=:iso, isorange=0.05, isovalue=1.7) + r = range(-1, stop = 1, length = 100) + matr = [(x .^ 2 + y .^ 2 + z .^ 2) for x in r, y in r, z in r] + volume(matr .* (matr .> 1.4), algorithm = :iso, isorange = 0.05, isovalue = 1.7) end @reference_test "levels" begin x = LinRange(-1, 1, 20) y = LinRange(-1, 1, 20) z = x .* y' - contour(x, y, z, linewidth=3, colormap=:colorwheel, levels=50) + contour(x, y, z, linewidth = 3, colormap = :colorwheel, levels = 50) end @reference_test "position" begin - fig, ax, sc = scatter(RNG.rand(10), color=:red) - text!(ax, 5, 1.1, text = "adding text", fontsize=0.6) + fig, ax, sc = scatter(RNG.rand(10), color = :red) + text!(ax, 5, 1.1, text = "adding text", fontsize = 0.6) fig end @reference_test "rotation" begin - text("Hello World", rotation=1.1) + text("Hello World", rotation = 1.1) end @reference_test "shading" begin - mesh(Sphere(Point3f(0), 1f0), color=:orange, shading=false) + mesh(Sphere(Point3f(0), 1.0f0), color = :orange, shading = false) end @reference_test "visible" begin fig = Figure() colors = Makie.resample(to_colormap(:deep), 20) - scatter(fig[1, 1], RNG.randn(20), color=colors, markersize=10, visible=true) - scatter(fig[1, 2], RNG.randn(20), color=colors, markersize=10, visible=false) + scatter(fig[1, 1], RNG.randn(20), color = colors, markersize = 10, visible = true) + scatter(fig[1, 2], RNG.randn(20), color = colors, markersize = 10, visible = false) fig end diff --git a/ReferenceTests/src/tests/examples2d.jl b/ReferenceTests/src/tests/examples2d.jl index 04c134fbe1f..6f8e0d49ff4 100644 --- a/ReferenceTests/src/tests/examples2d.jl +++ b/ReferenceTests/src/tests/examples2d.jl @@ -32,122 +32,122 @@ end @reference_test "poly and colormap" begin # example by @Paulms from MakieOrg/Makie.jl#310 points = Point2f[[0.0, 0.0], [0.1, 0.0], [0.1, 0.1], [0.0, 0.1]] - colors = [0.0 ,0.0, 0.5, 0.0] - fig, ax, polyplot = poly(points, color=colors, colorrange=(0.0, 1.0)) + colors = [0.0, 0.0, 0.5, 0.0] + fig, ax, polyplot = poly(points, color = colors, colorrange = (0.0, 1.0)) points = Point2f[[0.1, 0.1], [0.2, 0.1], [0.2, 0.2], [0.1, 0.2]] - colors = [0.5,0.5,1.0,0.3] - poly!(ax, points, color=colors, colorrange=(0.0, 1.0)) + colors = [0.5, 0.5, 1.0, 0.3] + poly!(ax, points, color = colors, colorrange = (0.0, 1.0)) fig end @reference_test "quiver" begin - x = range(-2, stop=2, length=21) - arrows(x, x, RNG.rand(21, 21), RNG.rand(21, 21), arrowsize=0.05) + x = range(-2, stop = 2, length = 21) + arrows(x, x, RNG.rand(21, 21), RNG.rand(21, 21), arrowsize = 0.05) end @reference_test "Arrows on hemisphere" begin s = Sphere(Point3f(0), 0.9f0) - fig, ax, meshplot = mesh(s, transparency=true, alpha=0.05) + fig, ax, meshplot = mesh(s, transparency = true, alpha = 0.05) pos = decompose(Point3f, s) dirs = decompose_normals(s) - arrows!(ax, pos, dirs, arrowcolor=:red, arrowsize=0.1, linecolor=:red) + arrows!(ax, pos, dirs, arrowcolor = :red, arrowsize = 0.1, linecolor = :red) fig end @reference_test "image" begin fig = Figure() - image(fig[1,1], Makie.logo(), axis = (; aspect = DataAspect())) + image(fig[1, 1], Makie.logo(), axis = (; aspect = DataAspect())) image(fig[1, 2], RNG.rand(100, 500), axis = (; aspect = DataAspect())) fig end @reference_test "FEM polygon 2D" begin coordinates = [ - 0.0 0.0; - 0.5 0.0; - 1.0 0.0; - 0.0 0.5; - 0.5 0.5; - 1.0 0.5; - 0.0 1.0; - 0.5 1.0; - 1.0 1.0; + 0.0 0.0 + 0.5 0.0 + 1.0 0.0 + 0.0 0.5 + 0.5 0.5 + 1.0 0.5 + 0.0 1.0 + 0.5 1.0 + 1.0 1.0 ] connectivity = [ - 1 2 5; - 1 4 5; - 2 3 6; - 2 5 6; - 4 5 8; - 4 7 8; - 5 6 9; - 5 8 9; + 1 2 5 + 1 4 5 + 2 3 6 + 2 5 6 + 4 5 8 + 4 7 8 + 5 6 9 + 5 8 9 ] color = [0.0, 0.0, 0.0, 0.0, -0.375, 0.0, 0.0, 0.0, 0.0] - poly(coordinates, connectivity, color=color, strokecolor=(:black, 0.6), strokewidth=4) + poly(coordinates, connectivity, color = color, strokecolor = (:black, 0.6), strokewidth = 4) end @reference_test "FEM mesh 2D" begin coordinates = [ - 0.0 0.0; - 0.5 0.0; - 1.0 0.0; - 0.0 0.5; - 0.5 0.5; - 1.0 0.5; - 0.0 1.0; - 0.5 1.0; - 1.0 1.0; + 0.0 0.0 + 0.5 0.0 + 1.0 0.0 + 0.0 0.5 + 0.5 0.5 + 1.0 0.5 + 0.0 1.0 + 0.5 1.0 + 1.0 1.0 ] connectivity = [ - 1 2 5; - 1 4 5; - 2 3 6; - 2 5 6; - 4 5 8; - 4 7 8; - 5 6 9; - 5 8 9; + 1 2 5 + 1 4 5 + 2 3 6 + 2 5 6 + 4 5 8 + 4 7 8 + 5 6 9 + 5 8 9 ] color = [0.0, 0.0, 0.0, 0.0, -0.375, 0.0, 0.0, 0.0, 0.0] - fig, ax, meshplot = mesh(coordinates, connectivity, color=color, shading=false) - wireframe!(ax, meshplot[1], color=(:black, 0.6), linewidth=3) + fig, ax, meshplot = mesh(coordinates, connectivity, color = color, shading = false) + wireframe!(ax, meshplot[1], color = (:black, 0.6), linewidth = 3) fig end @reference_test "colored triangle" begin mesh( - [(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], color=[:red, :green, :blue], - shading=false + [(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], color = [:red, :green, :blue], + shading = false ) end @reference_test "colored triangle with poly" begin poly( [(0.0, 0.0), (0.5, 1.0), (1.0, 0.0)], - color=[:red, :green, :blue], - strokecolor=:black, strokewidth=2 + color = [:red, :green, :blue], + strokecolor = :black, strokewidth = 2 ) end @reference_test "scale_plot" begin - t = range(0, stop=1, length=500) # time steps + t = range(0, stop = 1, length = 500) # time steps θ = (6π) .* t # angles x = # x coords of spiral - y = # y coords of spiral - lines(t .* cos.(θ), t .* sin.(θ); - color=t, colormap=:algae, linewidth=8, axis = (; aspect = DataAspect())) + y = # y coords of spiral + lines(t .* cos.(θ), t .* sin.(θ); + color = t, colormap = :algae, linewidth = 8, axis = (; aspect = DataAspect())) end @reference_test "Polygons" begin - points = decompose(Point2f, Circle(Point2f(50), 50f0)) - fig, ax, pol = poly(points, color=:gray, strokewidth=10, strokecolor=:red) + points = decompose(Point2f, Circle(Point2f(50), 50.0f0)) + 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), 50.0f0)], color = :gray, strokewidth = 10, strokecolor = :red) + poly!(ax, [Circle(Point2f(50 + i, 50 + i), 10.0f0) for i in 1:100:400], color = :red) + poly!(ax, [Rect2f(50 + i, 50 + i, 20, 20) for i in 1:100:400], strokewidth = 2, strokecolor = :green) linesegments!(ax, - [Point2f(50 + i, 50 + i) => Point2f(i + 70, i + 70) for i = 1:100:400], linewidth=8, color=:purple + [Point2f(50 + i, 50 + i) => Point2f(i + 70, i + 70) for i in 1:100:400], linewidth = 8, color = :purple ) fig end @@ -155,10 +155,10 @@ end @reference_test "Text Annotation" begin text( ". This is an annotation!", - position=(300, 200), - align=(:center, :center), - fontsize=60, - font="Blackchancery" + position = (300, 200), + align = (:center, :center), + fontsize = 60, + font = "Blackchancery" ) end @@ -167,17 +167,17 @@ end ax = fig[1, 1] = Axis(fig) pos = (500, 500) posis = Point2f[] - for r in range(0, stop=2pi, length=20) + for r in range(0, stop = 2pi, length = 20) p = pos .+ (sin(r) * 100.0, cos(r) * 100) push!(posis, p) text!(ax, "test", - position=p, - fontsize=50, - rotation=1.5pi - r, - align=(:center, :center) + position = p, + fontsize = 50, + rotation = 1.5pi - r, + align = (:center, :center) ) end - scatter!(ax, posis, markersize=10) + scatter!(ax, posis, markersize = 10) fig end @@ -185,12 +185,12 @@ end # Sample 100 Brownian motion path and plot the mean trajectory together # with a ±1σ band (visualizing uncertainty as marginal standard deviation). n, m = 100, 101 - t = range(0, 1, length=m) - X = cumsum(RNG.randn(n, m), dims=2) + t = range(0, 1, length = m) + X = cumsum(RNG.randn(n, m), dims = 2) X = X .- X[:, 1] - μ = vec(mean(X, dims=1)) # mean + μ = vec(mean(X, dims = 1)) # mean lines(t, μ) # plot mean line - σ = vec(std(X, dims=1)) # stddev + σ = vec(std(X, dims = 1)) # stddev band!(t, μ + σ, μ - σ) # plot stddev band current_figure() end @@ -199,8 +199,8 @@ end v(x::Point2{T}, t) where T = Point2{T}(one(T) * x[2] * t, 4 * x[1]) sf = Observable(Base.Fix2(v, 0e0)) title_str = Observable("t = 0.00") - sp = streamplot(sf, -2..2, -2..2; - linewidth=2, colormap=:magma, axis=(;title=title_str)) + sp = streamplot(sf, -2 .. 2, -2 .. 2; + linewidth = 2, colormap = :magma, axis = (; title = title_str)) Record(sp, LinRange(0, 20, 5)) do i sf[] = Base.Fix2(v, i) title_str[] = "t = $(round(i; sigdigits=2))" @@ -209,9 +209,9 @@ end @reference_test "Line changing colour" begin - fig, ax, lineplot = lines(RNG.rand(10); linewidth=10) + fig, ax, lineplot = lines(RNG.rand(10); linewidth = 10) N = 20 - Record(fig, 1:N; framerate=20) do i + Record(fig, 1:N; framerate = 20) do i lineplot.color = RGBf(i / N, (N - i) / N, 0) # animate scene end end @@ -230,7 +230,7 @@ let P.γ * x[1] - x[2] + P.β ) ff(x) = ff(x, P) - streamplot(ff, -1.5..1.5, -1.5..1.5, colormap=:magma) + streamplot(ff, -1.5 .. 1.5, -1.5 .. 1.5, colormap = :magma) end end @@ -238,7 +238,7 @@ end N = 7 # number of colours in default palette fig = Figure() ax = Axis(fig) - fig[1,1] = ax + fig[1, 1] = ax st = Stepper(fig) xs = 0:9 # data @@ -247,8 +247,8 @@ end plots = map(1:N) do i # plot lines lines!(ax, xs, ys; - color=colors[i], - linewidth=5 + color = colors[i], + linewidth = 5 ) # plot lines with colors end @@ -261,9 +261,9 @@ end (8 - i), pi / 2, (pi / 2 - rot); - color=plots[i].color, - linewidth=5, - linestyle=:dash + color = plots[i].color, + linewidth = 5, + linestyle = :dash ) end @@ -351,17 +351,17 @@ end @reference_test "Simple pie chart" begin - fig = Figure(resolution=(800, 800)) - pie(fig[1, 1], 1:5, color=collect(1:5), axis=(;aspect=DataAspect())) + fig = Figure(resolution = (800, 800)) + pie(fig[1, 1], 1:5, color = collect(1:5), axis = (; aspect = DataAspect())) fig end @reference_test "Hollow pie chart" begin - pie(1:5, color=collect(1.0:5), radius=2, inner_radius=1, axis=(;aspect=DataAspect())) + pie(1:5, color = collect(1.0:5), radius = 2, inner_radius = 1, axis = (; aspect = DataAspect())) end @reference_test "Open pie chart" begin - pie(0.1:0.1:1.0, normalize=false, axis=(;aspect=DataAspect())) + pie(0.1:0.1:1.0, normalize = false, axis = (; aspect = DataAspect())) end @reference_test "intersecting polygon" begin @@ -371,22 +371,22 @@ end @reference_test "Line Function" begin - x = range(0, stop=3pi) + x = range(0, stop = 3pi) fig, ax, lineplot = lines(x, sin.(x)) - lines!(ax, x, cos.(x), color=:blue) + lines!(ax, x, cos.(x), color = :blue) fig end @reference_test "Grouped bar" begin - x1 = ["a_right", "a_right", "a_right", "a_right"] - y1 = [2, 3, -3, -2] - grp_dodge1 = [2, 2, 1, 1] - grp_stack1 = [1, 2, 1, 2] + x1 = ["a_right", "a_right", "a_right", "a_right"] + y1 = [2, 3, -3, -2] + grp_dodge1 = [2, 2, 1, 1] + grp_stack1 = [1, 2, 1, 2] - x2 = ["z_left", "z_left", "z_left", "z_left"] - y2 = [2, 3, -3, -2] - grp_dodge2 = [1, 2, 1, 2] - grp_stack2 = [1, 1, 2, 2] + x2 = ["z_left", "z_left", "z_left", "z_left"] + y2 = [2, 3, -3, -2] + grp_dodge2 = [1, 2, 1, 2] + grp_stack2 = [1, 1, 2, 2] perm = [1, 4, 2, 7, 5, 3, 8, 6] x = [x1; x2][perm] @@ -398,7 +398,7 @@ end tbl = (; x = x, grp_dodge = grp_dodge, grp_stack = grp_stack, y = y) fig = Figure() - ax = Axis(fig[1,1]) + ax = Axis(fig[1, 1]) barplot!(ax, levelcode.(tbl.x), tbl.y, dodge = tbl.grp_dodge, stack = tbl.grp_stack, color = tbl.grp_stack) @@ -486,19 +486,19 @@ end @reference_test "Scatter & Text transformations" begin # Check that transformations apply in `space = :data` - fig, ax, p = scatter(Point2f(100, 0.5), marker = 'a', markersize=50) + fig, ax, p = scatter(Point2f(100, 0.5), marker = 'a', markersize = 50) t = text!(Point2f(100, 0.5), text = "Test", fontsize = 50) translate!(p, -100, 0, 0) translate!(t, -100, 0, 0) # Check that scale and rotate don't act on the marker for scatter (only the position) - p2 = scatter!(ax, Point2f(1, 0), marker= 'a', markersize = 50) - Makie.rotate!(p2, pi/4) + p2 = scatter!(ax, Point2f(1, 0), marker = 'a', markersize = 50) + Makie.rotate!(p2, pi / 4) scale!(p2, 0.5, 0.5, 1) # but do act on glyphs of text t2 = text!(ax, 1, 0, text = "Test", fontsize = 50) - Makie.rotate!(t2, pi/4) + Makie.rotate!(t2, pi / 4) scale!(t2, 0.5, 0.5, 1) xlims!(ax, -0.2, 0.5) @@ -509,39 +509,39 @@ end @reference_test "Array of Images Scatter" begin img = Makie.logo() - scatter(1:2, 1:2, marker = [img, img], markersize=reverse(size(img) ./ 10), axis=(limits=(0.5, 2.5, 0.5, 2.5),)) + scatter(1:2, 1:2, marker = [img, img], markersize = reverse(size(img) ./ 10), axis = (limits = (0.5, 2.5, 0.5, 2.5),)) end @reference_test "Image Scatter different sizes" begin img = Makie.logo() img2 = load(Makie.assetpath("doge.png")) images = [img, img2] - markersize = map(img-> Vec2f(reverse(size(img) ./ 10)), images) - scatter(1:2, 1:2, marker = images, markersize=markersize, axis=(limits=(0.5, 2.5, 0.5, 2.5),)) + markersize = map(img -> Vec2f(reverse(size(img) ./ 10)), images) + scatter(1:2, 1:2, marker = images, markersize = markersize, axis = (limits = (0.5, 2.5, 0.5, 2.5),)) end @reference_test "2D surface with explicit color" begin - surface(1:10, 1:10, ones(10, 10); color = [RGBf(x*y/100, 0, 0) for x in 1:10, y in 1:10], shading = false) + surface(1:10, 1:10, ones(10, 10); color = [RGBf(x * y / 100, 0, 0) for x in 1:10, y in 1:10], shading = false) end @reference_test "heatmap and image colormap interpolation" begin - f = Figure(resolution=(500, 500)) + f = Figure(resolution = (500, 500)) crange = LinRange(0, 255, 10) len = length(crange) img = zeros(Float32, len, len + 2) - img[:, 1] .= 255f0 + img[:, 1] .= 255.0f0 for (i, v) in enumerate(crange) ib = i + 1 - img[2:end-1, ib] .= v - img[1, ib] = 255-v - img[end, ib] = 255-v + img[2:(end - 1), ib] .= v + img[1, ib] = 255 - v + img[end, ib] = 255 - v end - kw(p, interpolate) = (axis=(title="$(p)(interpolate=$(interpolate))", aspect=DataAspect()), interpolate=interpolate, colormap=[:white, :black]) + kw(p, interpolate) = (axis = (title = "$(p)(interpolate=$(interpolate))", aspect = DataAspect()), interpolate = interpolate, colormap = [:white, :black]) for (i, p) in enumerate([heatmap, image]) for (j, interpolate) in enumerate([true, false]) - ax, pl = p(f[i,j], img; kw(p, interpolate)...) + ax, pl = p(f[i, j], img; kw(p, interpolate)...) hidedecorations!(ax) end end @@ -557,11 +557,11 @@ end for (i, cat) in enumerate(categorical) for (j, scale) in enumerate(scales) cg = if cat - cgrad(:viridis, 5; scale = scale, categorical=true) + cgrad(:viridis, 5; scale = scale, categorical = true) else - cgrad(:viridis; scale = scale, categorical=nothing) + cgrad(:viridis; scale = scale, categorical = nothing) end - lines!(ax, Point2f.(LinRange(i+0.1, i+0.9, n), j); color = 1:n, colormap = cg, linewidth = 10) + lines!(ax, Point2f.(LinRange(i + 0.1, i + 0.9, n), j); color = 1:n, colormap = cg, linewidth = 10) end end ax.xticks[] = ((1:length(categorical)) .+ 0.5, ["categorical=false", "categorical=true"]) @@ -570,19 +570,19 @@ end end @reference_test "colormap with specific values" begin - cmap = cgrad([:black,:white,:orange],[0,0.2,1]) - fig = Figure(resolution=(400,200)) - ax = Axis(fig[1,1]) - x = range(0,1,length=50) - scatter!(fig[1,1],Point2.(x,fill(0.,50)),color=x,colormap=cmap) + cmap = cgrad([:black, :white, :orange], [0, 0.2, 1]) + fig = Figure(resolution = (400, 200)) + ax = Axis(fig[1, 1]) + x = range(0, 1, length = 50) + scatter!(fig[1, 1], Point2.(x, fill(0.0, 50)), color = x, colormap = cmap) hidedecorations!(ax) - Colorbar(fig[2,1],vertical=false,colormap=cmap) + Colorbar(fig[2, 1], vertical = false, colormap = cmap) fig end @reference_test "multi rect with poly" begin # use thick strokewidth, so it will make tests fail if something is missing - poly([Rect2f(0, 0, 1, 1)], color=:green, strokewidth=100, strokecolor=:black) + poly([Rect2f(0, 0, 1, 1)], color = :green, strokewidth = 100, strokecolor = :black) end @reference_test "minor grid & scales" begin @@ -603,7 +603,7 @@ end end @reference_test "Tooltip" begin - fig, ax, p = scatter(Point2f(0,0)) + fig, ax, p = scatter(Point2f(0, 0)) xlims!(ax, -10, 10) ylims!(ax, -5, 5) tt = tooltip!(ax, Point2f(0), text = "left", placement = :left) @@ -616,7 +616,7 @@ end tooltip!( ax, 0, 0, text = "right", placement = :right, fontsize = 30, outline_linewidth = 5, offset = 30, triangle_size = 15, - strokewidth = 2f0, strokecolor = :cyan + strokewidth = 2.0f0, strokecolor = :cyan ) fig end @@ -656,13 +656,13 @@ end @reference_test "tricontourf manual vs delaunay" begin n = 20 - angles = range(0, 2pi, length = n+1)[1:end-1] - x = [cos.(angles); 2 .* cos.(angles .+ pi/n)] - y = [sin.(angles); 2 .* sin.(angles .+ pi/n)] - z = (x .- 0.5).^2 + (y .- 0.5).^2 .+ 0.5 .* RNG.randn.() + angles = range(0, 2pi, length = n + 1)[1:(end - 1)] + x = [cos.(angles); 2 .* cos.(angles .+ pi / n)] + y = [sin.(angles); 2 .* sin.(angles .+ pi / n)] + z = (x .- 0.5) .^ 2 + (y .- 0.5) .^ 2 .+ 0.5 .* RNG.randn.() triangulation_inner = reduce(hcat, map(i -> [0, 1, n] .+ i, 1:n)) - triangulation_outer = reduce(hcat, map(i -> [n-1, n, 0] .+ i, 1:n)) + triangulation_outer = reduce(hcat, map(i -> [n - 1, n, 0] .+ i, 1:n)) triangulation = hcat(triangulation_inner, triangulation_outer) f, ax, _ = tricontourf(x, y, z, triangulation = triangulation, @@ -678,9 +678,9 @@ end @reference_test "marker offset in data space" begin f = Figure() - ax = Axis(f[1, 1]; xticks=0:1, yticks=0:10) - scatter!(ax, fill(0, 10), 0:9, marker=Rect, marker_offset=Vec2f(0,0), transform_marker=true, markerspace=:data, markersize=Vec2f.(1, LinRange(0.1, 1, 10))) - lines!(ax, Rect(0, 0, 1, 10), color=:red) + ax = Axis(f[1, 1]; xticks = 0:1, yticks = 0:10) + scatter!(ax, fill(0, 10), 0:9, marker = Rect, marker_offset = Vec2f(0, 0), transform_marker = true, markerspace = :data, markersize = Vec2f.(1, LinRange(0.1, 1, 10))) + lines!(ax, Rect(0, 0, 1, 10), color = :red) f end @@ -711,7 +711,7 @@ end y = RNG.rand(300) for i in 2:5 - ax = Axis(f[fldmod1(i-1, 2)...], title = "bins = $i", aspect = DataAspect()) + ax = Axis(f[fldmod1(i - 1, 2)...], title = "bins = $i", aspect = DataAspect()) hexbin!(ax, x, y, bins = i) wireframe!(ax, Rect2f(Point2f.(x, y)), color = :red) scatter!(ax, x, y, color = :red, markersize = 5) @@ -727,7 +727,7 @@ end y = RNG.rand(300) for i in 2:5 - ax = Axis(f[fldmod1(i-1, 2)...], title = "bins = (3, $i)", aspect = DataAspect()) + ax = Axis(f[fldmod1(i - 1, 2)...], title = "bins = (3, $i)", aspect = DataAspect()) hexbin!(ax, x, y, bins = (3, i)) wireframe!(ax, Rect2f(Point2f.(x, y)), color = :red) scatter!(ax, x, y, color = :red, markersize = 5) @@ -790,7 +790,7 @@ end f = Figure() hexbin(f[1, 1], x, y, bins = 40, axis = (aspect = DataAspect(), title = "scale = identity")) - hexbin(f[1, 2], x, y, bins = 40, scale=log10, + hexbin(f[1, 2], x, y, bins = 40, scale = log10, axis = (aspect = DataAspect(), title = "scale = log10")) f end @@ -814,8 +814,8 @@ end @reference_test "Latex labels after the fact" begin f = Figure(fontsize = 50) ax = Axis(f[1, 1]) - ax.xticks = ([3, 6, 9], [L"x" , L"y" , L"z"]) - ax.yticks = ([3, 6, 9], [L"x" , L"y" , L"z"]) + ax.xticks = ([3, 6, 9], [L"x", L"y", L"z"]) + ax.yticks = ([3, 6, 9], [L"x", L"y", L"z"]) f end diff --git a/ReferenceTests/src/tests/examples3d.jl b/ReferenceTests/src/tests/examples3d.jl index 938ef68f456..34466010027 100644 --- a/ReferenceTests/src/tests/examples3d.jl +++ b/ReferenceTests/src/tests/examples3d.jl @@ -1,25 +1,27 @@ @reference_test "Image on Geometry (Moon)" begin moon = loadasset("moon.png") - fig, ax, meshplot = mesh(Sphere(Point3f(0), 1f0), color=moon, shading=false, axis = (;show_axis=false)) + fig, ax, meshplot = mesh(Sphere(Point3f(0), 1.0f0), color = moon, shading = false, axis = (; show_axis = false)) update_cam!(ax.scene, Vec3f(-2, 2, 2), Vec3f(0)) fig end @reference_test "Image on Geometry (Earth)" begin earth = loadasset("earth.png") - m = uv_mesh(Tesselation(Sphere(Point3f(0), 1f0), 60)) - mesh(m, color=earth, shading=false) + m = uv_mesh(Tesselation(Sphere(Point3f(0), 1.0f0), 60)) + mesh(m, color = earth, shading = false) end @reference_test "Orthographic Camera" begin function colormesh((geometry, color)) mesh1 = normal_mesh(geometry) npoints = length(GeometryBasics.coordinates(mesh1)) - return GeometryBasics.pointmeta(mesh1; color=fill(color, npoints)) + return GeometryBasics.pointmeta(mesh1; color = fill(color, npoints)) end # create an array of differently colored boxes in the direction of the 3 axes - x = Vec3f(0); baselen = 0.2f0; dirlen = 1f0 + x = Vec3f(0) + baselen = 0.2f0 + dirlen = 1.0f0 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)), @@ -31,7 +33,7 @@ end scene = ax.scene center!(scene) cam = cameracontrols(scene) - dir = widths(data_limits(scene)) ./ 2. + dir = widths(data_limits(scene)) ./ 2.0 dir_scaled = Vec3f( dir[1] * scene.transformation.scale[][1], 0.0, @@ -47,12 +49,12 @@ end end @reference_test "Volume Function" begin - volume(RNG.rand(32, 32, 32), algorithm=:mip) + volume(RNG.rand(32, 32, 32), algorithm = :mip) end @reference_test "Textured Mesh" begin catmesh = loadasset("cat.obj") - mesh(catmesh, color=loadasset("diffusemap.png")) + mesh(catmesh, color = loadasset("diffusemap.png")) end @reference_test "Load Mesh" begin @@ -68,8 +70,8 @@ end j = [1, 2, 3, 2] k = [2, 3, 1, 3] # indices interpreted as triangles (every 3 sequential indices) - indices = [1, 2, 3, 1, 3, 4, 1, 4, 2, 2, 3, 4] - mesh(x, y, z, indices, color=color) + indices = [1, 2, 3, 1, 3, 4, 1, 4, 2, 2, 3, 4] + mesh(x, y, z, indices, color = color) end @reference_test "Wireframe of a Mesh" begin @@ -77,18 +79,18 @@ end end @reference_test "Wireframe of Sphere" begin - wireframe(Sphere(Point3f(0), 1f0)) + wireframe(Sphere(Point3f(0), 1.0f0)) end @reference_test "Wireframe of a Surface" begin function xy_data(x, y) r = sqrt(x^2 + y^2) - r == 0.0 ? 1f0 : (sin(r) / r) + r == 0.0 ? 1.0f0 : (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 @@ -96,45 +98,45 @@ end N = 30 function xy_data(x, y) r = sqrt(x^2 + y^2) - r == 0.0 ? 1f0 : (sin(r) / r) + r == 0.0 ? 1.0f0 : (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) + large_sphere = Sphere(Point3f(0), 1.0f0) positions = decompose(Point3f, large_sphere) - colS = [RGBAf(RNG.rand(), RNG.rand(), RNG.rand(), 1.0) for i = 1:length(positions)] - sizesS = [RNG.rand(Point3f) .* 0.05f0 for i = 1:length(positions)] - meshscatter(positions, color=colS, markersize=sizesS) + colS = [RGBAf(RNG.rand(), RNG.rand(), RNG.rand(), 1.0) for i in 1:length(positions)] + sizesS = [RNG.rand(Point3f) .* 0.05f0 for i in 1:length(positions)] + meshscatter(positions, color = colS, markersize = sizesS) end @reference_test "scatter" begin - scatter(RNG.rand(20), RNG.rand(20), markersize=10) + scatter(RNG.rand(20), RNG.rand(20), markersize = 10) end @reference_test "Marker sizes" begin colors = Makie.resample(to_colormap(:Spectral), 20) - scatter(RNG.rand(20), RNG.rand(20), markersize=RNG.rand(20) .* 20, color=colors) + scatter(RNG.rand(20), RNG.rand(20), markersize = RNG.rand(20) .* 20, color = colors) end @reference_test "Record Video" begin f(t, v, s) = (sin(v + t) * s, cos(v + t) * s, (cos(v + t) + sin(v)) * s) t = Observable(0.0) # create a life signal limits = Rect3f(Vec3f(-1.5, -1.5, -3), Vec3f(3, 3, 6)) - fig, ax, p1 = meshscatter(lift(t -> f.(t, range(0, stop=2pi, length=50), 1), t), markersize=0.05) - p2 = meshscatter!(ax, lift(t -> f.(t * 2.0, range(0, stop=2pi, length=50), 1.5), t), markersize=0.05) + fig, ax, p1 = meshscatter(lift(t -> f.(t, range(0, stop = 2pi, length = 50), 1), t), markersize = 0.05) + p2 = meshscatter!(ax, lift(t -> f.(t * 2.0, range(0, stop = 2pi, length = 50), 1.5), t), markersize = 0.05) linepoints = lift(p1[1], p2[1]) do pos1, pos2 map((a, b) -> (a => b), pos1, pos2) end - linesegments!(ax, linepoints, linestyle=:dot) + linesegments!(ax, linepoints, linestyle = :dot) Record(fig, 1:2) do i t[] = i / 10 @@ -146,14 +148,14 @@ end xy = [x, y, z] ((xy') * Matrix(I, 3, 3) * xy) / 20 end - x = range(-2pi, stop=2pi, length=100) + x = range(-2pi, stop = 2pi, length = 100) # c[4] == fourth argument of the above plotting command - fig, ax, c = contour(x, x, x, test, levels=6, alpha=0.3, transparency=true) + fig, ax, c = contour(x, x, x, test, levels = 6, alpha = 0.3, transparency = true) xm, ym, zm = minimum(data_limits(c)) - contour!(ax, x, x, map(v -> v[1, :, :], c[4]), transformation=(:xy, zm), linewidth=2) - heatmap!(ax, x, x, map(v -> v[:, 1, :], c[4]), transformation=(:xz, ym)) - contourf!(ax, x, x, map(v -> v[:, :, 1], c[4]), transformation=(:yz, xm)) + contour!(ax, x, x, map(v -> v[1, :, :], c[4]), transformation = (:xy, zm), linewidth = 2) + heatmap!(ax, x, x, map(v -> v[:, 1, :], c[4]), transformation = (:xz, ym)) + contourf!(ax, x, x, map(v -> v[:, :, 1], c[4]), transformation = (:yz, xm)) # reorder plots for transparency ax.scene.plots[:] = ax.scene.plots[[1, 3, 4, 5, 2]] fig @@ -162,10 +164,10 @@ end @reference_test "Contour3d" begin function xy_data(x, y) r = sqrt(x * x + y * y) - r == 0.0 ? 1f0 : (sin(r) / r) + r == 0.0 ? 1.0f0 : (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 @@ -176,33 +178,33 @@ end Point3f.(x, y, z) end n = 100^2 # number of points to generate - r = ones(n); + r = ones(n) θ = acos.(1 .- 2 .* RNG.rand(n)) φ = 2π * RNG.rand(n) pts = SphericalToCartesian(r, θ, φ) - arrows(pts, (normalize.(pts) .* 0.1f0), arrowsize=0.02, linecolor=:green, arrowcolor=:darkblue) + arrows(pts, (normalize.(pts) .* 0.1f0), arrowsize = 0.02, linecolor = :green, arrowcolor = :darkblue) end @reference_test "Image on Surface Sphere" begin n = 20 - θ = [0;(0.5:n - 0.5) / n;1] - φ = [(0:2n - 2) * 2 / (2n - 1);2] + θ = [0; (0.5:(n - 0.5)) / n; 1] + φ = [(0:(2n - 2)) * 2 / (2n - 1); 2] x = [cospi(φ) * sinpi(θ) for θ in θ, φ in φ] y = [sinpi(φ) * sinpi(θ) for θ in θ, φ in φ] z = [cospi(θ) for θ in θ, φ in φ] - RNG.rand([-1f0, 1f0], 3) + RNG.rand([-1.0f0, 1.0f0], 3) pts = vec(Point3f.(x, y, z)) - f, ax, p = surface(x, y, z, color=Makie.logo(), transparency=true) + f, ax, p = surface(x, y, z, color = Makie.logo(), transparency = true) end @reference_test "Arrows on Sphere" begin n = 20 - f = (x, y, z) -> x * exp(cos(y) * z) - ∇f = (x, y, z) -> Point3f(exp(cos(y) * z), -sin(y) * z * x * exp(cos(y) * z), x * cos(y) * exp(cos(y) * z)) + f = (x, y, z) -> x * exp(cos(y) * z) + ∇f = (x, y, z) -> Point3f(exp(cos(y) * z), -sin(y) * z * x * exp(cos(y) * z), x * cos(y) * exp(cos(y) * z)) ∇ˢf = (x, y, z) -> ∇f(x, y, z) - Point3f(x, y, z) * dot(Point3f(x, y, z), ∇f(x, y, z)) - θ = [0;(0.5:n - 0.5) / n;1] - φ = [(0:2n - 2) * 2 / (2n - 1);2] + θ = [0; (0.5:(n - 0.5)) / n; 1] + φ = [(0:(2n - 2)) * 2 / (2n - 1); 2] x = [cospi(φ) * sinpi(θ) for θ in θ, φ in φ] y = [sinpi(φ) * sinpi(θ) for θ in θ, φ in φ] z = [cospi(θ) for θ in θ, φ in φ] @@ -212,7 +214,7 @@ end surface(x, y, z) arrows!( pts, ∇ˢF, - arrowsize=0.03, linecolor=(:white, 0.6), linewidth=0.03 + arrowsize = 0.03, linecolor = (:white, 0.6), linewidth = 0.03 ) current_figure() end @@ -226,7 +228,7 @@ end ax1 = fig[1, 1] = Axis(fig, title = "surface") ax2 = fig[1, 2] = Axis(fig, title = "contour3d") surface!(ax1, vx, vy, f) - contour3d!(ax2, vx, vy, (x, y) -> f(x, y), levels=15, linewidth=3) + contour3d!(ax2, vx, vy, (x, y) -> f(x, y), levels = 15, linewidth = 3) fig end @@ -234,11 +236,11 @@ end cat = loadasset("cat.obj") vertices = decompose(Point3f, cat) faces = decompose(TriangleFace{Int}, cat) - coordinates = [vertices[i][j] for i = 1:length(vertices), j = 1:3] - connectivity = [faces[i][j] for i = 1:length(faces), j = 1:3] + coordinates = [vertices[i][j] for i in 1:length(vertices), j in 1:3] + connectivity = [faces[i][j] for i in 1:length(faces), j in 1:3] mesh( coordinates, connectivity, - color=RNG.rand(length(vertices)) + color = RNG.rand(length(vertices)) ) end @@ -247,7 +249,7 @@ end vy = -1:0.01:1 f(x, y) = (sin(x * 10) + cos(y * 10)) / 4 - scene = Scene(resolution=(500, 500), camera=cam3d!) + scene = Scene(resolution = (500, 500), camera = cam3d!) # One way to style the axis is to pass a nested dictionary / named tuple to it. psurf = surface!(scene, vx, vy, f) axis3d!(scene, frame = (linewidth = 2.0,)) @@ -268,12 +270,12 @@ end t = text!( campixel(scene), "Multipole Representation of first resonances of U-238", - position=(wh[1] / 2.0, wh[2] - 20.0), - align=(:center, :center), - fontsize=20, - font="helvetica" + position = (wh[1] / 2.0, wh[2] - 20.0), + align = (:center, :center), + fontsize = 20, + font = "helvetica" ) - c = lines!(scene, Circle(Point2f(0.1, 0.5), 0.1f0), color=:red, offset=Vec3f(0, 0, 1)) + c = lines!(scene, Circle(Point2f(0.1, 0.5), 0.1f0), color = :red, offset = Vec3f(0, 0, 1)) psurf.converted[3][] = f.(vx .+ 0.5, (vy .+ 0.5)') scene end @@ -281,64 +283,68 @@ 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) + large_sphere = Sphere(Point3f(0), 1.0f0) 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) - cylinder = Cylinder(Point3f(0), Point3f(0, 0, 1.0), 1f0) + ne = size(edges, 1) + np = size(pts, 1) + cylinder = Cylinder(Point3f(0), Point3f(0, 0, 1.0), 1.0f0) # 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 + 1.0f0 ) 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 @reference_test "Connected Sphere" begin - large_sphere = Sphere(Point3f(0), 1f0) + large_sphere = Sphere(Point3f(0), 1.0f0) positions = decompose(Point3f, large_sphere) linepos = view(positions, RNG.rand(1:length(positions), 1000)) - fig, ax, lineplot = lines(linepos, linewidth=0.1, color=:black, transparency=true) + fig, ax, lineplot = lines(linepos, linewidth = 0.1, color = :black, transparency = true) scatter!( - ax, positions, markersize=10, - strokewidth=2, strokecolor=:white, - color=RGBAf(0.9, 0.2, 0.4, 0.3), transparency=true, + ax, positions, markersize = 10, + strokewidth = 2, strokecolor = :white, + color = RGBAf(0.9, 0.2, 0.4, 0.3), transparency = true, ) fig end @@ -346,66 +352,68 @@ 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) + large_sphere = Sphere(Point3f(0), 1.0f0) 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 function xy_data(x, y) r = sqrt(x^2 + y^2) - r == 0.0 ? 1f0 : (sin(r) / r) + r == 0.0 ? 1.0f0 : (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 = 2.0f0, color = lift(x -> to_colormap(x)[5], surf[:colormap]) ) - Record(fig, range(5, stop=40, length=3)) do i + Record(fig, range(5, stop = 40, length = 3)) do i surf[3] = surf_func(i) end end @reference_test "Normals of a Cat" begin x = loadasset("cat.obj") - mesh(x, color=:black) + mesh(x, color = :black) pos = map(decompose(Point3f, x), GeometryBasics.normals(x)) do p, n p => p .+ Point(normalize(n) .* 0.05f0) end - linesegments!(pos, color=:blue) + linesegments!(pos, color = :blue) current_figure() end @reference_test "Sphere Mesh" begin - mesh(Sphere(Point3f(0), 1f0), color=:blue) + mesh(Sphere(Point3f(0), 1.0f0), 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 = 1.0f0 rectangles = [ (Rect(Vec3f(x), Vec3f(dirlen, baselen, baselen)), RGBAf(1, 0, 0, 1)), (Rect(Vec3f(x), Vec3f(baselen, dirlen, baselen)), RGBAf(0, 1, 0, 1)), @@ -417,21 +425,21 @@ end end @reference_test "Line GIF" begin - us = range(0, stop=1, length=100) + us = range(0, stop = 1, length = 100) f, ax, p = linesegments(Rect3f(Vec3f(0, -1, 0), Vec3f(1, 2, 2))) - p = lines!(ax, us, sin.(us), zeros(100), linewidth=3, transparency=true) + p = lines!(ax, us, sin.(us), zeros(100), linewidth = 3, transparency = true) lineplots = [p] Makie.translate!(p, 0, 0, 0) colors = to_colormap(:RdYlBu) N = 5 Record(f, 1:N) do i - t = i/(N/5) + t = i / (N / 5) if length(lineplots) < 20 p = lines!( ax, us, sin.(us .+ t), zeros(100), - color=colors[length(lineplots)], - linewidth=3 + color = colors[length(lineplots)], + linewidth = 3 ) pushfirst!(lineplots, p) translate!(p, 0, 0, 0) @@ -450,13 +458,13 @@ end @reference_test "Surface + wireframe + contour" begin N = 51 - x = range(-2, stop=2, length=N) + x = range(-2, stop = 2, length = N) y = x - z = (-x .* exp.(-x.^2 .- (y').^2)) .* 4 + z = (-x .* exp.(-x .^ 2 .- (y') .^ 2)) .* 4 fig, ax, surfaceplot = surface(x, y, z) xm, ym, zm = minimum(data_limits(ax.scene)) - contour!(ax, x, y, z, levels=15, linewidth=2, transformation=(:xy, zm)) - wireframe!(ax, x, y, z, transparency=true, color=(:black, 0.1)) + contour!(ax, x, y, z, levels = 15, linewidth = 2, transformation = (:xy, zm)) + wireframe!(ax, x, y, z, transparency = true, color = (:black, 0.1)) center!(ax.scene) # center the Scene on the display fig end @@ -477,19 +485,19 @@ let P.γ * x[1] - x[3] - P.β, ) f(x) = f(x, P) - streamplot(f, -1.5..1.5, -1.5..1.5, -1.5..1.5, colormap=:magma, gridsize=(10, 10), arrow_size=0.1, transparency=true) + streamplot(f, -1.5 .. 1.5, -1.5 .. 1.5, -1.5 .. 1.5, colormap = :magma, gridsize = (10, 10), arrow_size = 0.1, transparency = true) end end @reference_test "Volume on black background" begin - r = LinRange(-3, 3, 100); # our value range + r = LinRange(-3, 3, 100) # our value range ρ(x, y, z) = exp(-(abs(x))) # function (charge density) fig, ax, pl = volume( r, r, r, # coordinates to plot on ρ, # charge density (functions as colorant) - algorithm=:mip # maximum-intensity-projection + algorithm = :mip # maximum-intensity-projection ) ax.scene[OldAxis].names.textcolor = :gray # let axis labels be seen on dark background fig.scene.backgroundcolor[] = to_color(:black) @@ -501,28 +509,28 @@ end fig = Figure(resolution = (800, 400)) prim = Rect3(Point3f(0), Vec3f(1)) - ps = RNG.rand(Point3f, 10) .+ Point3f(0, 0, 1) + ps = RNG.rand(Point3f, 10) .+ Point3f(0, 0, 1) mat = RNG.rand(4, 4) - A = RNG.rand(4,4,4) + A = RNG.rand(4, 4, 4) # This generates two sets of plots each on two axis. Both axes have one set # without depth_shift (0f0, red) and one at ∓10eps(1f0) (blue, left/right axis). # A negative shift should push the plot in the foreground, positive in the background. - for (i, _shift) in enumerate((-10eps(1f0), 10eps(1f0))) + for (i, _shift) in enumerate((-10eps(1.0f0), 10eps(1.0f0))) ax = LScene(fig[1, i], show_axis = false) - for (color, shift) in zip((:red, :blue), (0f0, _shift)) + for (color, shift) in zip((:red, :blue), (0.0f0, _shift)) mesh!(ax, prim, color = color, depth_shift = shift) lines!(ax, ps, color = color, depth_shift = shift) linesegments!(ax, ps .+ Point3f(-1, 1, 0), color = color, depth_shift = shift) - scatter!(ax, ps, color = color, markersize=10, depth_shift = shift) + scatter!(ax, ps, color = color, markersize = 10, depth_shift = shift) text!(ax, 0, 1, 1.1, text = "Test", color = color, depth_shift = shift) - surface!(ax, -1..0, 1..2, mat, colormap = [color, color], depth_shift = shift) + surface!(ax, -1 .. 0, 1 .. 2, mat, colormap = [color, color], depth_shift = shift) meshscatter!(ax, ps .+ Point3f(-1, 1, 0), color = color, depth_shift = shift) # # left side in axis - heatmap!(ax, 0..1, 0..1, mat, colormap = [color, color], depth_shift = shift) + heatmap!(ax, 0 .. 1, 0 .. 1, mat, colormap = [color, color], depth_shift = shift) # # right side in axis - image!(ax, -1..0, 1..2, mat, colormap = [color, color], depth_shift = shift) + image!(ax, -1 .. 0, 1 .. 2, mat, colormap = [color, color], depth_shift = shift) p = volume!(ax, A, colormap = [:white, color], depth_shift = shift) translate!(p, -1, 0, 0) scale!(p, 0.25, 0.25, 0.25) @@ -542,13 +550,13 @@ end r = Rect2f(-1, -1, 2, 2) for x in (0, 1) for (i, a) in enumerate((0.25, 0.5, 0.75, 1.0)) - ps = [Point3f(a, (0.15 + 0.01y)*(2x-1) , 0.2y) for y in 1:8] + ps = [Point3f(a, (0.15 + 0.01y) * (2x - 1), 0.2y) for y in 1:8] if x == 0 cs = [RGBAf(1, 0, 0, 0.75), RGBAf(0, 1, 0, 0.5), RGBAf(0, 0, 1, 0.25)] elseif x == 1 cs = [RGBAf(1, x, 0, a), RGBAf(0, 1, x, a), RGBAf(x, 0, 1, a)] end - idxs = [1, 2, 3, 2, 1, 3, 1, 2, 1, 2, 3][i:7+i] + idxs = [1, 2, 3, 2, 1, 3, 1, 2, 1, 2, 3][i:(7 + i)] meshscatter!( ax, ps, marker = r, color = cs[idxs], transparency = true @@ -556,7 +564,7 @@ end end end cam = cameracontrols(ax.scene) - cam.attributes.fov[] = 22f0 + cam.attributes.fov[] = 22.0f0 update_cam!(ax.scene, cam, Vec3f(0.625, 0, 3.5), Vec3f(0.625, 0, 0), Vec3f(0, 1, 0)) fig end @@ -569,7 +577,7 @@ end mesh!(ax, Rect2f(0.8, 0.1, 0.1, 0.8), space = :relative, color = :blue, shading = false) linesegments!(ax, Rect2f(-0.5, -0.5, 1, 1), space = :clip, color = :cyan, linewidth = 5) text!(ax, 0, 0.52, text = "Clip Space", align = (:center, :bottom), space = :clip) - image!(ax, 0..40, 0..800, [x for x in range(0, 1, length=40), _ in 1:10], space = :pixel) + image!(ax, 0 .. 40, 0 .. 800, [x for x in range(0, 1, length = 40), _ in 1:10], space = :pixel) end fig end diff --git a/ReferenceTests/src/tests/figures_and_makielayout.jl b/ReferenceTests/src/tests/figures_and_makielayout.jl index fb91ca36a0a..d79afb7a977 100644 --- a/ReferenceTests/src/tests/figures_and_makielayout.jl +++ b/ReferenceTests/src/tests/figures_and_makielayout.jl @@ -9,10 +9,10 @@ end @reference_test "Figure with Blocks" begin fig = Figure(resolution = (900, 900)) - ax, sc = scatter(fig[1, 1][1, 1], RNG.randn(100, 2), axis = (;title = "Random Dots", xlabel = "Time")) + ax, sc = scatter(fig[1, 1][1, 1], RNG.randn(100, 2), axis = (; title = "Random Dots", xlabel = "Time")) sc2 = scatter!(ax, RNG.randn(100, 2) .+ 2, color = :red) ll = fig[1, 1][1, 2] = Legend(fig, [sc, sc2], ["Scatter", "Other"]) - lines(fig[2, 1:2][1, 3][1, 1], 0..3, sin ∘ exp, axis = (;title = "Exponential Sine")) + lines(fig[2, 1:2][1, 3][1, 1], 0 .. 3, sin ∘ exp, axis = (; title = "Exponential Sine")) heatmap(fig[2, 1:2][1, 1], RNG.randn(30, 30)) heatmap(fig[2, 1:2][1, 2], RNG.randn(30, 30), colormap = :grays) lines!(fig[2, 1:2][1, 2], cumsum(RNG.rand(30)), color = :red, linewidth = 10) @@ -27,7 +27,7 @@ end @reference_test "menus" begin fig = Figure() - funcs = [sqrt, x->x^2, sin, cos] + funcs = [sqrt, x -> x^2, sin, cos] options = zip(["Square Root", "Square", "Sine", "Cosine"], funcs) menu1 = Menu(fig, options = ["viridis", "heat", "blues"], default = 1) @@ -37,10 +37,10 @@ end fig[1, 1] = grid!( [ - Label(fig, "A", width = nothing) Label(fig, "C", width = nothing); - menu1 menu3; - Label(fig, "B", width = nothing) Label(fig, "D", width = nothing); - menu2 menu4; + Label(fig, "A", width = nothing) Label(fig, "C", width = nothing) + menu1 menu3 + Label(fig, "B", width = nothing) Label(fig, "D", width = nothing) + menu2 menu4 ] ) menu2.is_open = true @@ -51,7 +51,7 @@ end @reference_test "Label with text wrapping" begin lorem_ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." fig = Figure(resolution = (1000, 660)) - m!(fig, lbl) = mesh!(fig.scene, lbl.layoutobservables.computedbbox, color = (:red, 0.5), shading=false) + m!(fig, lbl) = mesh!(fig.scene, lbl.layoutobservables.computedbbox, color = (:red, 0.5), shading = false) lbl1 = Label(fig[1, 1:2], "HEADER "^10, fontsize = 40, word_wrap = true) m!(fig, lbl1) @@ -113,11 +113,11 @@ end f = Figure() ax = Axis(f[1, 1], backgroundcolor = :gray80) for i in 1:3 - lines!(ax,( 1:10) .* i, label = "$i") + lines!(ax, (1:10) .* i, label = "$i") end # To verify that RGB values differ across entries - axislegend(ax, position = :lt, patchcolor = :red, patchsize = (100, 100), bgcolor = :gray50); - Legend(f[1, 2], ax, patchcolor = :gray80, patchsize = (100, 100), bgcolor = :gray50); + axislegend(ax, position = :lt, patchcolor = :red, patchsize = (100, 100), bgcolor = :gray50) + Legend(f[1, 2], ax, patchcolor = :gray80, patchsize = (100, 100), bgcolor = :gray50) f end end diff --git a/ReferenceTests/src/tests/primitives.jl b/ReferenceTests/src/tests/primitives.jl index 0d64146d5dd..2c17d6feda3 100644 --- a/ReferenceTests/src/tests/primitives.jl +++ b/ReferenceTests/src/tests/primitives.jl @@ -11,7 +11,7 @@ quote for linewidth in 1:10 for (i, linestyle) in enumerate(linestyles) lines!(s, - scalar .* (points .+ Point2f(linewidth*2, i * 3.25)), + scalar .* (points .+ Point2f(linewidth * 2, i * 3.25)), linewidth = linewidth, linestyle = linestyle, ) @@ -83,7 +83,7 @@ end s = Scene(resolution = (350, 700), camera = campixel!) # half stroke, half glow - strokes = range(1, 4, length=7) + strokes = range(1, 4, length = 7) outline_colors = [:red, :green, :blue, :yellow, :purple, :cyan, :black] colors = [ :red, :green, :blue, @@ -116,7 +116,7 @@ end s = Scene(resolution = (350, 700), camera = campixel!) # half stroke, half glow - glows = range(4, 1, length=7) + glows = range(4, 1, length = 7) outline_colors = [:red, :green, :blue, :yellow, :purple, :cyan, :black] colors = [ :red, :green, :blue, @@ -147,14 +147,14 @@ end @reference_test "scatter image markers" begin - pixel_types = [ RGBA, RGBAf, RGBA{Float16}, ARGB, ARGB{Float16}, RGB, RGBf, RGB{Float16} ] - rotations = [ 2pi/3 * (i-1) for i = 1:length(pixel_types) ] - s = Scene(resolution = (100+100*length(pixel_types), 400), camera = campixel!) + pixel_types = [RGBA, RGBAf, RGBA{Float16}, ARGB, ARGB{Float16}, RGB, RGBf, RGB{Float16}] + rotations = [2pi / 3 * (i - 1) for i in 1:length(pixel_types)] + s = Scene(resolution = (100 + 100 * length(pixel_types), 400), camera = campixel!) filename = Makie.assetpath("icon_transparent.png") marker_image = FileIO.load(filename) for (i, (rot, pxtype)) in enumerate(zip(rotations, pixel_types)) marker = convert.(pxtype, marker_image) - p = Point2f((i-1) * 100 + 100, 200) + p = Point2f((i - 1) * 100 + 100, 200) scatter!(s, p, marker = marker, @@ -205,7 +205,7 @@ end for (i, p) in enumerate(polys) for (j, lw) in enumerate(linewidths) - t = Transformation(scale=Vec3f(scalefactor), translation = Vec3f(1.3 * (i-1), 1.3 * j, 0) .* scalefactor) + t = Transformation(scale = Vec3f(scalefactor), translation = Vec3f(1.3 * (i - 1), 1.3 * j, 0) .* scalefactor) poly!( s, p, @@ -291,19 +291,19 @@ end github = BezierPath(gh_string, fit = true, flipy = true) two_circles_with_holes = Makie.scale(BezierPath([ - MoveTo(Point(2.25, 0)), - EllipticalArc(Point(1.25, 0), 1, 1, 0, 0, 2pi), - ClosePath(), - MoveTo(Point(-0.25, 0)), - EllipticalArc(Point(-1.25, 0), 1, 1, 0, 0, 2pi), - ClosePath(), - MoveTo(Point(2, 0)), - EllipticalArc(Point(1.25, 0), 0.75, 0.75, 0, 0, -2pi), - ClosePath(), - MoveTo(Point(-1, 0)), - EllipticalArc(Point(-1.25, 0), 0.25, 0.25, 0, 0, -2pi), - ClosePath(), - ]), 0.5) + MoveTo(Point(2.25, 0)), + EllipticalArc(Point(1.25, 0), 1, 1, 0, 0, 2pi), + ClosePath(), + MoveTo(Point(-0.25, 0)), + EllipticalArc(Point(-1.25, 0), 1, 1, 0, 0, 2pi), + ClosePath(), + MoveTo(Point(2, 0)), + EllipticalArc(Point(1.25, 0), 0.75, 0.75, 0, 0, -2pi), + ClosePath(), + MoveTo(Point(-1, 0)), + EllipticalArc(Point(-1.25, 0), 0.25, 0.25, 0, 0, -2pi), + ClosePath(), + ]), 0.5) markers = [ arrow, @@ -326,11 +326,11 @@ end p_big = decompose(Point2f, Circle(Point2f(0), 1)) p_small = decompose(Point2f, Circle(Point2f(0), 0.5)) marker = [Polygon(p_big, [p_small]), Polygon(reverse(p_big), [p_small]), Polygon(p_big, [reverse(p_small)]), Polygon(reverse(p_big), [reverse(p_small)])] - scatter(1:4, fill(0, 4), marker=marker, markersize=100, color=1:4, axis=(limits=(0, 5, -1, 1),)) + scatter(1:4, fill(0, 4), marker = marker, markersize = 100, color = 1:4, axis = (limits = (0, 5, -1, 1),)) end function centered_rect(w, h) - wh, hh = w/2, h/2 + wh, hh = w / 2, h / 2 return Point2f[(-wh, -hh), (-wh, hh), (wh, hh), (wh, -hh)] end @@ -348,15 +348,15 @@ function create_rect(inner) return Makie.to_spritemarker(marker) end -function plot_test!(scene, xoffset, yoffset, inner, reverse=true, marker=create_marker) +function plot_test!(scene, xoffset, yoffset, inner, reverse = true, marker = create_marker) bpath = marker(inner) p = [Point2f(xoffset, yoffset) .+ 150] if reverse - scatter!(scene, p, marker=bpath, markersize=280, color=:black) - scatter!(scene, p, marker=Rect, markersize=280, color=:red) + scatter!(scene, p, marker = bpath, markersize = 280, color = :black) + scatter!(scene, p, marker = Rect, markersize = 280, color = :red) else - scatter!(scene, p, marker=Rect, markersize=280, color=:red) - scatter!(scene, p, marker=bpath, markersize=280, color=:black) + scatter!(scene, p, marker = Rect, markersize = 280, color = :red) + scatter!(scene, p, marker = bpath, markersize = 280, color = :black) end end @@ -368,9 +368,9 @@ function plot_row!(scene, yoffset, reverse) plot_test!(scene, 900, yoffset + 0, 0.3, reverse, create_rect) end -function draw_marker_test!(scene, marker, center; markersize=300) +function draw_marker_test!(scene, marker, center; markersize = 300) # scatter!(scene, center, distancefield=matr, uv_offset_width=Vec4f(0, 0, 1, 1), markersize=600) - scatter!(scene, center, marker=marker, markersize=markersize, markerspace=:pixel) + scatter!(scene, center, marker = marker, markersize = markersize, markerspace = :pixel) font = Makie.defaultfont() charextent = Makie.FreeTypeAbstraction.get_extent(font, marker) @@ -380,18 +380,18 @@ function draw_marker_test!(scene, marker, center; markersize=300) w, h = widths(inkbb) .* markersize ox, oy = origin(inkbb) .* markersize mhalf = markersize / 2 - bbmin = center .+ Point2f(-w/2, -h/2) + bbmin = center .+ Point2f(-w / 2, -h / 2) inkbb_scaled = Rect2f(bbmin..., w, h) - lines!(scene, inkbb_scaled, linewidth=5, color=:green) - points = Point2f[(center[1], center[2] - h/2), (center[1], center[2] + h/2), (center[1] - w/2, center[2]), (center[1] + w/2, center[2])] - linesegments!(scene, points, color=:red) + lines!(scene, inkbb_scaled, linewidth = 5, color = :green) + points = Point2f[(center[1], center[2] - h / 2), (center[1], center[2] + h / 2), (center[1] - w / 2, center[2]), (center[1] + w / 2, center[2])] + linesegments!(scene, points, color = :red) scene end @reference_test "marke glyph alignment" begin - scene = Scene(resolution=(1200, 1200)) + scene = Scene(resolution = (1200, 1200)) campixel!(scene) # marker is in front, so it should not be smaller than the background rectangle plot_row!(scene, 0, false) @@ -402,15 +402,15 @@ end # Markers should be well aligned to the red cross and just about touch the green # boundingbox! - draw_marker_test!(scene, 'x', Point2f(150, 750); markersize=550) - draw_marker_test!(scene, 'X', Point2f(450, 750); markersize=400) - draw_marker_test!(scene, 'I', Point2f(750, 750); markersize=400) - draw_marker_test!(scene, 'O', Point2f(1050, 750); markersize=300) - - draw_marker_test!(scene, 'L', Point2f(150, 1050); markersize=350) - draw_marker_test!(scene, 'Y', Point2f(450, 1050); markersize=350) - draw_marker_test!(scene, 'y', Point2f(750, 1050); markersize=350) - draw_marker_test!(scene, 'u', Point2f(1050, 1050); markersize=500) + draw_marker_test!(scene, 'x', Point2f(150, 750); markersize = 550) + draw_marker_test!(scene, 'X', Point2f(450, 750); markersize = 400) + draw_marker_test!(scene, 'I', Point2f(750, 750); markersize = 400) + draw_marker_test!(scene, 'O', Point2f(1050, 750); markersize = 300) + + draw_marker_test!(scene, 'L', Point2f(150, 1050); markersize = 350) + draw_marker_test!(scene, 'Y', Point2f(450, 1050); markersize = 350) + draw_marker_test!(scene, 'y', Point2f(750, 1050); markersize = 350) + draw_marker_test!(scene, 'u', Point2f(1050, 1050); markersize = 500) scene end diff --git a/ReferenceTests/src/tests/recipes.jl b/ReferenceTests/src/tests/recipes.jl index 547920a0538..672fc62b549 100644 --- a/ReferenceTests/src/tests/recipes.jl +++ b/ReferenceTests/src/tests/recipes.jl @@ -2,14 +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)}) - Theme( - advance=0, - molecule_sizes=[0.08, 0.04, 0.04], - molecule_colors=[:maroon, :deepskyblue2, :deepskyblue2] - ) -end +# Probably worth having a macro for this! +Makie.default_theme(scene::SceneLike, ::Type{<:Plot(Simulation)}) = Theme( + advance = 0, + molecule_sizes = [0.08, 0.04, 0.04], + molecule_colors = [:maroon, :deepskyblue2, :deepskyblue2] +) # The recipe! - will get called for plot(!)(x::SimulationResult) function Makie.plot!(p::Plot(Simulation)) sim = to_value(p[1]) # first argument is the SimulationResult @@ -21,15 +19,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 +42,12 @@ end # To write out a video of the whole simulation n = 5 - r = range(-1, stop=1, length=n) + r = range(-1, stop = 1, length = n) grid = Point3f.(r, reshape(r, (1, n, 1)), reshape(r, (1, 1, n))) - molecules = map(1:(n^3) * 3) do i + molecules = map(1:((n^3) * 3)) do i i3 = ((i - 1) ÷ 3) + 1 - xy = 0.1; z = 0.08 + xy = 0.1 + z = 0.08 i % 3 == 1 && return grid[i3] i % 3 == 2 && return grid[i3] + Point3f(xy, xy, z) i % 3 == 0 && return grid[i3] + Point3f(-xy, xy, z) diff --git a/ReferenceTests/src/tests/short_tests.jl b/ReferenceTests/src/tests/short_tests.jl index 1518f5482d7..457cbcee014 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), 10.0f0, 0.0f0, pi, linewidth = 20) -@reference_test "stroked rect poly" poly(Recti(0, 0, 200, 200), strokewidth=20, strokecolor=:red, color=(:black, 0.4)) +@reference_test "stroked rect poly" poly(Recti(0, 0, 200, 200), strokewidth = 20, strokecolor = :red, color = (:black, 0.4)) @reference_test "array of rects poly" begin f, ax, pl = poly([Rect(0, 0, 20, 20)]) - scatter!(Rect(0, 0, 20, 20), color=:red, markersize=20) + scatter!(Rect(0, 0, 20, 20), color = :red, markersize = 20) f end @reference_test "char marker scenespace" begin - f, ax, pl = lines(Rect(0, 0, 1, 1), linewidth=4) - scatter!([Point2f(0.5, 0.5)], markersize=1, markerspace=:data, marker='I') + f, ax, pl = lines(Rect(0, 0, 1, 1), linewidth = 4) + scatter!([Point2f(0.5, 0.5)], markersize = 1, markerspace = :data, marker = 'I') f end -@reference_test "lines number color" lines(RNG.rand(10), RNG.rand(10), color=RNG.rand(10), linewidth=10) -@reference_test "lines array of colors" lines(RNG.rand(10), RNG.rand(10), color=RNG.rand(RGBAf, 10), linewidth=10) -@reference_test "scatter interval" scatter(0..1, RNG.rand(10), markersize=RNG.rand(10) .* 20) +@reference_test "lines number color" lines(RNG.rand(10), RNG.rand(10), color = RNG.rand(10), linewidth = 10) +@reference_test "lines array of colors" lines(RNG.rand(10), RNG.rand(10), color = RNG.rand(RGBAf, 10), linewidth = 10) +@reference_test "scatter interval" scatter(0 .. 1, RNG.rand(10), markersize = RNG.rand(10) .* 20) @reference_test "scatter linrange" scatter(LinRange(0, 1, 10), RNG.rand(10)) @reference_test "scatter rotation" begin - angles = range(0, stop=2pi, length=20) + angles = range(0, stop = 2pi, length = 20) pos = Point2f.(sin.(angles), cos.(angles)) - f, ax, pl = scatter(pos, markersize=0.2, markerspace=:data, rotations=-angles, marker='▲', axis=(;aspect = DataAspect())) - scatter!(pos, markersize=10, color=:red) + f, ax, pl = scatter(pos, markersize = 0.2, markerspace = :data, rotations = -angles, marker = '▲', axis = (; aspect = DataAspect())) + scatter!(pos, markersize = 10, color = :red) f end -@reference_test "heatmap transparent colormap" heatmap(RNG.rand(50, 50), colormap=(:RdBu, 0.2)) +@reference_test "heatmap transparent colormap" heatmap(RNG.rand(50, 50), colormap = (:RdBu, 0.2)) @reference_test "contour small x" contour(RNG.rand(10, 100)) @reference_test "contour small y" contour(RNG.rand(100, 10)) -@reference_test "contour with levels" contour(RNG.randn(100, 90), levels=3) +@reference_test "contour with levels" contour(RNG.randn(100, 90), levels = 3) -@reference_test "contour with levels array" contour(RNG.randn(100, 90), levels=[0.1, 0.5, 0.8]) -@reference_test "contour with color per level" contour(RNG.randn(33, 30), levels=[0.1, 0.5, 0.9], color=[:black, :green, (:blue, 0.4)], linewidth=2) +@reference_test "contour with levels array" contour(RNG.randn(100, 90), levels = [0.1, 0.5, 0.8]) +@reference_test "contour with color per level" contour(RNG.randn(33, 30), levels = [0.1, 0.5, 0.9], color = [:black, :green, (:blue, 0.4)], linewidth = 2) @reference_test "contour with colorrange" contour( - RNG.rand(33, 30) .* 6 .- 3, levels=[-2.5, 0.4, 0.5, 0.6, 2.5], - colormap=[(:black, 0.2), :red, :blue, :green, (:black, 0.2)], - colorrange=(0.2, 0.8) + RNG.rand(33, 30) .* 6 .- 3, levels = [-2.5, 0.4, 0.5, 0.6, 2.5], + colormap = [(:black, 0.2), :red, :blue, :green, (:black, 0.2)], + colorrange = (0.2, 0.8) ) @reference_test "circle line" lines(Circle(Point2f(0), Float32(1))) @reference_test "streamplot with func" begin v(x::Point2{T}) where T = Point2{T}(x[2], 4 * x[1]) - streamplot(v, -2..2, -2..2) + streamplot(v, -2 .. 2, -2 .. 2) end -@reference_test "lines with func" lines(-1..1, x -> x^2) -@reference_test "scatter with func" scatter(-1..1, x -> x^2) +@reference_test "lines with func" lines(-1 .. 1, x -> x^2) +@reference_test "scatter with func" scatter(-1 .. 1, x -> x^2) @reference_test "volume translated" begin - r = range(-3pi, stop=3pi, length=100) - fig, ax, vplot = Makie.volume(r, r, r, (x, y, z) -> cos(x) + sin(y) + cos(z), algorithm=:iso, isorange=0.1f0, axis = (;show_axis=false)) - v2 = volume!(ax, r, r, r, (x, y, z) -> cos(x) + sin(y) + cos(z), algorithm=:mip, - transformation=(translation=Vec3f(6pi, 0, 0),)) + r = range(-3pi, stop = 3pi, length = 100) + fig, ax, vplot = Makie.volume(r, r, r, (x, y, z) -> cos(x) + sin(y) + cos(z), algorithm = :iso, isorange = 0.1f0, axis = (; show_axis = false)) + v2 = volume!(ax, r, r, r, (x, y, z) -> cos(x) + sin(y) + cos(z), algorithm = :mip, + transformation = (translation = Vec3f(6pi, 0, 0),)) fig end -@reference_test "meshscatter color numbers" meshscatter(RNG.rand(10), RNG.rand(10), RNG.rand(10), color=RNG.rand(10)) -@reference_test "meshscatter color array" meshscatter(RNG.rand(10), RNG.rand(10), RNG.rand(10), color=RNG.rand(RGBAf, 10), transparency=true) +@reference_test "meshscatter color numbers" meshscatter(RNG.rand(10), RNG.rand(10), RNG.rand(10), color = RNG.rand(10)) +@reference_test "meshscatter color array" meshscatter(RNG.rand(10), RNG.rand(10), RNG.rand(10), color = RNG.rand(RGBAf, 10), transparency = true) @reference_test "transparent mesh texture" begin - s1 = uv_mesh(Sphere(Point3f(0), 1f0)) - f, ax, pl = mesh(uv_mesh(Sphere(Point3f(0), 1f0)), color=RNG.rand(50, 50)) + s1 = uv_mesh(Sphere(Point3f(0), 1.0f0)) + f, ax, pl = mesh(uv_mesh(Sphere(Point3f(0), 1.0f0)), color = RNG.rand(50, 50)) # ugh, bug In GeometryTypes for UVs of non unit spheres. - s2 = uv_mesh(Sphere(Point3f(0), 1f0)) + s2 = uv_mesh(Sphere(Point3f(0), 1.0f0)) 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 @@ -78,17 +78,17 @@ end NR = 31 function xy_data(x, y) r = sqrt(x^2 + y^2) - r == 0.0 ? 1f0 : (sin(r) / r) + r == 0.0 ? 1.0f0 : (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 @@ -97,17 +97,17 @@ end NR = 31 function xy_data(x, y) r = sqrt(x^2 + y^2) - r == 0.0 ? 1f0 : (sin(r) / r) + r == 0.0 ? 1.0f0 : (sin(r) / r) end - lspace = range(-10, stop=10, length=NL) - rspace = range(-10, stop=10, length=NR) + lspace = range(-10, stop = 10, length = NL) + rspace = range(-10, stop = 10, length = NR) z = Float32[xy_data(x, y) for x in lspace, y in rspace] - l = range(0, stop=3, length=NL) - r = range(0, stop=3, length=NR) + l = range(0, stop = 3, length = NL) + r = range(0, stop = 3, length = NR) surface( [l for l in l, r in r], [r for l in l, r in r], z, - colormap=:Spectral + colormap = :Spectral ) end @@ -147,29 +147,29 @@ end end @reference_test "log10 heatmap" begin - heatmap(RNG.rand(10, 5), axis = (yscale = log10, xscale=log10)) + heatmap(RNG.rand(10, 5), axis = (yscale = log10, xscale = log10)) end @reference_test "reverse range heatmap" begin x = [1 0 - 2 3] + 2 3] heatmap(1:2, 1:-1:0, x) end @reference_test "lines linesegments width test" begin res = 200 - s = Scene(camera=campixel!, resolution=(res, res)) + s = Scene(camera = campixel!, resolution = (res, res)) half = res / 2 linewidth = 10 - xstart = half - (half/2) + xstart = half - (half / 2) xend = xstart + 100 - half_w = linewidth/2 + half_w = linewidth / 2 - lines!(s, Point2f[(xstart, half), (xend, half)], linewidth=linewidth) - scatter!(s, Point2f[(xstart, half + half_w), (xstart, half - half_w), (xend, half + half_w), (xend, half - half_w)], color=:red, markersize=2) + lines!(s, Point2f[(xstart, half), (xend, half)], linewidth = linewidth) + scatter!(s, Point2f[(xstart, half + half_w), (xstart, half - half_w), (xend, half + half_w), (xend, half - half_w)], color = :red, markersize = 2) - l2 = linesegments!(s, Point2f[(xstart, half), (xend, half)], linewidth=linewidth, color=:gray) - s2 = scatter!(s, Point2f[(xstart, half + half_w), (xstart, half - half_w), (xend, half + half_w), (xend, half - half_w)], color=:red, markersize=2) + l2 = linesegments!(s, Point2f[(xstart, half), (xend, half)], linewidth = linewidth, color = :gray) + s2 = scatter!(s, Point2f[(xstart, half + half_w), (xstart, half - half_w), (xend, half + half_w), (xend, half - half_w)], color = :red, markersize = 2) for p in (l2, s2) translate!(p, 0, 20, 0) @@ -180,25 +180,25 @@ end @reference_test "multipoly with multi strokes" begin P = Polygon.([Point2f[[0.45, 0.05], [0.64, 0.15], [0.37, 0.62]], - Point2f[[0.32, 0.66], [0.46, 0.59], [0.09, 0.08]]]) + Point2f[[0.32, 0.66], [0.46, 0.59], [0.09, 0.08]]]) poly(P, color = [:red, :green], strokecolor = [:blue, :red], strokewidth = 2) end @reference_test "fast pixel marker" begin - scatter(RNG.rand(Point2f, 10000), marker=Makie.FastPixel()) + scatter(RNG.rand(Point2f, 10000), marker = Makie.FastPixel()) end @reference_test "axsi3" begin - meshscatter(RNG.rand(Point3f, 10), axis=(type=Axis3,)) + meshscatter(RNG.rand(Point3f, 10), axis = (type = Axis3,)) end @reference_test "pattern barplot" begin - barplot(1:5, color=Makie.LinePattern(linecolor=:red, background_color=:orange)) + barplot(1:5, color = Makie.LinePattern(linecolor = :red, background_color = :orange)) end @reference_test "barplot lowclip highclip nan_color" begin f = Figure() - attrs = (color=[-Inf, 2, NaN, Inf], colorrange=(2, 3), highclip = :red, lowclip=:green, nan_color=:black) + attrs = (color = [-Inf, 2, NaN, Inf], colorrange = (2, 3), highclip = :red, lowclip = :green, nan_color = :black) barplot(f[1, 1], 1:4; attrs...) poly( f[1, 2], @@ -208,11 +208,11 @@ end Point2f[(2, 1), (4, 1), (4, 2), (2, 2)], Point2f[(0, 1), (2, 1), (2, 2), (0, 2)], ]; - strokewidth=2, attrs... + strokewidth = 2, attrs... ) meshscatter(f[2, 1], 1:4, zeros(4), 1:4; attrs...) volcano = readdlm(Makie.assetpath("volcano.csv"), ',', Float64) - ax, cf = contourf(f[2, 2], volcano, levels = range(100, 180, length = 10), extendlow = :green, extendhigh = :red, nan_color=:black) + ax, cf = contourf(f[2, 2], volcano, levels = range(100, 180, length = 10), extendlow = :green, extendhigh = :red, nan_color = :black) Colorbar(f[:, 3], cf) f end @@ -224,9 +224,9 @@ end end @reference_test "scene visibility" begin - f, ax, pl = scatter(1:4, markersize=200) - ax2, pl = scatter(f[1, 2][1, 1], 1:4, color=1:4, markersize=200) - ax3, pl = scatter(f[1, 2][2, 1], 1:4, color=1:4, markersize=200) + f, ax, pl = scatter(1:4, markersize = 200) + ax2, pl = scatter(f[1, 2][1, 1], 1:4, color = 1:4, markersize = 200) + ax3, pl = scatter(f[1, 2][2, 1], 1:4, color = 1:4, markersize = 200) ax3.scene.visible[] = false ax2.scene.visible[] = false ax2.blockscene.visible[] = false @@ -237,8 +237,8 @@ end # https://github.com/MakieOrg/Makie.jl/issues/2392 Makie.inline!(false) f = Figure() - Menu(f[1,1], options=["one", "two", "three"]) - screen = display(f; visible=false) + Menu(f[1, 1], options = ["one", "two", "three"]) + screen = display(f; visible = false) # Close the window & redisplay close(screen) # Now, menu should be displayed again and not stay blank! @@ -246,14 +246,14 @@ end end @reference_test "space test in transformed axis" begin - f = lines(exp.(0.1*(1.0:100)); axis=(yscale=log10,)) - poly!(Rect(1, 1, 100, 100), color=:red, space=:pixel) - scatter!(2*mod.(1:100:10000, 97), 2*mod.(1:101:10000, 97), color=:blue, space=:pixel) - scatter!(Point2f(0, 0.25), space=:clip) - lines!([0.5,0.5], [0, 1]; space=:relative) - lines!([50,50], [0, 100]; space=:pixel) - lines!([0,1], [0.25, 0.25]; space=:clip) - scatter!(Point2f(0.5, 0), space=:relative) + f = lines(exp.(0.1 * (1.0:100)); axis = (yscale = log10,)) + poly!(Rect(1, 1, 100, 100), color = :red, space = :pixel) + scatter!(2 * mod.(1:100:10000, 97), 2 * mod.(1:101:10000, 97), color = :blue, space = :pixel) + scatter!(Point2f(0, 0.25), space = :clip) + lines!([0.5, 0.5], [0, 1]; space = :relative) + lines!([50, 50], [0, 100]; space = :pixel) + lines!([0, 1], [0.25, 0.25]; space = :clip) + scatter!(Point2f(0.5, 0), space = :relative) f end diff --git a/ReferenceTests/src/tests/text.jl b/ReferenceTests/src/tests/text.jl index d2b128a2e01..1008ef55941 100644 --- a/ReferenceTests/src/tests/text.jl +++ b/ReferenceTests/src/tests/text.jl @@ -36,9 +36,9 @@ end i = 1 for halign in (:right, :center, :left), valign in (:top, :center, :bottom) - for rotation in (-pi/6, 0.0, pi/6) + for rotation in (-pi / 6, 0.0, pi / 6) text!(scene, string(halign) * "/" * string(valign) * - " " * string(round(rad2deg(rotation), digits = 0)) * "°", + " " * string(round(rad2deg(rotation), digits = 0)) * "°", color = (:black, 0.5), position = points[i], align = (halign, valign), @@ -53,18 +53,18 @@ end @reference_test "multi_strings_multi_positions" begin scene = Scene(camera = campixel!, resolution = (800, 800)) - angles = (-pi/6, 0.0, pi/6) + angles = (-pi / 6, 0.0, pi / 6) points = [Point(x, y) .* 200 for x in 1:3 for y in 1:3 for angle in angles] aligns = [(halign, valign) for halign in - (:right, :center, :left) for valign in (:top, :center, :bottom) for rotation in angles] + (:right, :center, :left) for valign in (:top, :center, :bottom) for rotation in angles] rotations = [rotation for _ in - (:right, :center, :left) for _ in (:top, :center, :bottom) for rotation in angles] + (:right, :center, :left) for _ in (:top, :center, :bottom) for rotation in angles] strings = [string(halign) * "/" * string(valign) * - " " * string(round(rad2deg(rotation), digits = 0)) * "°" - for halign in (:right, :center, :left) - for valign in (:top, :center, :bottom) - for rotation in angles] + " " * string(round(rad2deg(rotation), digits = 0)) * "°" + for halign in (:right, :center, :left) + for valign in (:top, :center, :bottom) + for rotation in angles] scatter!(scene, points, marker = :circle, markersize = 10px) @@ -102,7 +102,7 @@ end for (p, al) in zip(points[7:9], (:left, :center, :right)) text!(scene, p .+ (80, 0), text = "justification\n:" * string(al), - align = (:center, :top), rotation = pi/2) + align = (:center, :top), rotation = pi / 2) end scene @@ -113,8 +113,8 @@ end t1 = text!(scene, fill("makie", 4), - position = [(200, 200) .+ 60 * Point2f(cos(a), sin(a)) for a in pi/4:pi/2:7pi/4], - rotation = pi/4:pi/2:7pi/4, + position = [(200, 200) .+ 60 * Point2f(cos(a), sin(a)) for a in (pi / 4):(pi / 2):(7pi / 4)], + rotation = (pi / 4):(pi / 2):(7pi / 4), align = (:left, :center), fontsize = 30, markerspace = :data @@ -124,8 +124,8 @@ end t2 = text!(scene, fill("makie", 4), - position = [(200, 600) .+ 60 * Point2f(cos(a), sin(a)) for a in pi/4:pi/2:7pi/4], - rotation = pi/4:pi/2:7pi/4, + position = [(200, 600) .+ 60 * Point2f(cos(a), sin(a)) for a in (pi / 4):(pi / 2):(7pi / 4)], + rotation = (pi / 4):(pi / 2):(7pi / 4), align = (:left, :center), fontsize = 30, markerspace = :pixel @@ -139,7 +139,7 @@ end @reference_test "single_boundingboxes" begin scene = Scene(camera = campixel!, resolution = (800, 800)) - for a in pi/4:pi/2:7pi/4 + for a in (pi / 4):(pi / 2):(7pi / 4) t = text!(scene, "makie", @@ -172,7 +172,7 @@ end text( fill("Makie", 7), rotation = [i / 7 * 1.5pi for i in 1:7], - position = [Point3f(0, 0, i/2) for i in 1:7], + position = [Point3f(0, 0, i / 2) for i in 1:7], color = [cgrad(:viridis)[x] for x in LinRange(0, 1, 7)], align = (:left, :baseline), fontsize = 1, @@ -199,14 +199,14 @@ end @reference_test "3D screenspace annotations" begin positions = RNG.rand(Point3f, 10) - fig, ax, p = meshscatter(positions, color=:white) + fig, ax, p = meshscatter(positions, color = :white) text!( fill("Annotation", 10), position = positions, align = (:center, :center), fontsize = 20, markerspace = :pixel, - overdraw=false) + overdraw = false) fig end @@ -222,16 +222,16 @@ end scatter(f[1, 2], Point2f(0, 0)) text!(0, 0, text = "hello", offset = (40, 0), align = (:left, :center)) text!(0, 0, text = "hello", offset = (40, 0), align = (:left, :center), - rotation = -pi/4) + rotation = -pi / 4) text!(0, 0, text = "hello", offset = (40, 0), align = (:left, :center), - rotation = pi/4) + rotation = pi / 4) scatter(f[2, 1], Point2f[(0, 0), (10, 0), (20, 10)]) text!(0, 0, text = "ABC", markerspace = :data, offset = (0, 0), color = (:red, 0.3), align = (:left, :baseline)) text!(0, 0, text = "ABC", markerspace = :data, offset = (10, 0), color = (:green, 0.3), align = (:left, :baseline)) text!(0, 0, text = "ABC", markerspace = :data, offset = (20, 10), color = (:blue, 0.3), align = (:left, :baseline)) - LScene(f[2, 2], show_axis=false) + LScene(f[2, 2], show_axis = false) scatter!(Point3f[(0, 0, 0), (2, 2, 2)]) text!(1, 1, 1, text = "hello", offset = (10, 10)) @@ -248,12 +248,12 @@ end end @reference_test "latex strings" begin - f, ax , l = lines(cumsum(RNG.randn(1000)), + f, ax, l = lines(cumsum(RNG.randn(1000)), axis = ( - title = L"\sum_k{x y_k}", - xlabel = L"\lim_{x →\infty} A^j v_{(a + b)_k}^i \sqrt{23.5} x!= \sqrt{\frac{1+6}{4+a+g}}\int_{0}^{2π} \sin(x) dx", - ylabel = L"x + y - \sin(x) × \tan(y) + \sqrt{2}", - ), + title = L"\sum_k{x y_k}", + xlabel = L"\lim_{x →\infty} A^j v_{(a + b)_k}^i \sqrt{23.5} x!= \sqrt{\frac{1+6}{4+a+g}}\int_{0}^{2π} \sin(x) dx", + ylabel = L"x + y - \sin(x) × \tan(y) + \sqrt{2}", + ), figure = (fontsize = 18,) ) text!(500, 0, text = L"\int_{0}^{2π} \sin(x) dx") @@ -262,7 +262,7 @@ end end @reference_test "latex hlines in axis" begin - text(1, 1, text = L"\frac{\sqrt{x + y}}{\sqrt{x + y}}", fontsize = 50, rotation = pi/4, + text(1, 1, text = L"\frac{\sqrt{x + y}}{\sqrt{x + y}}", fontsize = 50, rotation = pi / 4, align = (:center, :center)) end @@ -271,7 +271,7 @@ end t = text!(s, L"\sqrt{2}", position = (50, 50), - rotation = pi/2, + rotation = pi / 2, markerspace = :data) s end @@ -327,11 +327,11 @@ end end @reference_test "latex ticks" begin - lines(0..25, x -> 4 * sin(x) / (cos(3x) + 4), figure = (fontsize = 25,), + lines(0 .. 25, x -> 4 * sin(x) / (cos(3x) + 4), figure = (fontsize = 25,), axis = ( xticks = (0:10:20, [L"10^{-3.5}", L"10^{-4.5}", L"10^{-5.5}"]), yticks = ([-1, 0, 1], [L"\sum_%$i{xy}" for i in 1:3]), - yticklabelrotation = pi/8, + yticklabelrotation = pi / 8, title = L"\int_0^1{x^2}", xlabel = L"\sum_k{x_k ⋅ y_k}", ylabel = L"\int_a^b{\sqrt{abx}}" @@ -341,20 +341,20 @@ end @reference_test "dynamic latex ticks" begin - lines(0..25, x -> 4 * sin(x) / (cos(3x) + 4), + lines(0 .. 25, x -> 4 * sin(x) / (cos(3x) + 4), figure = (fontsize = 16,), - axis = (xtickformat = (xs -> [L"e^{\sqrt{%$x}}+\sum" for x in xs]), )) + axis = (xtickformat = (xs -> [L"e^{\sqrt{%$x}}+\sum" for x in xs]),)) end @reference_test "Word Wrapping" begin lorem_ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." - fig = Figure(resolution=(600, 500)) + fig = Figure(resolution = (600, 500)) ax = Axis(fig[1, 1]) - text!(ax, 0, 0, text = latexstring(L"$1$ " * lorem_ipsum), word_wrap_width=250, fontsize = 12, align = (:left, :bottom), justification = :left, color = :black) - text!(ax, 0, 0, text = lorem_ipsum, word_wrap_width=250, fontsize = 12, align = (:left, :top), justification = :right, color = :black) - text!(ax, 0, 0, text = lorem_ipsum, word_wrap_width=250, fontsize = 12, align = (:right, :bottom), justification = :center, color = :red) - text!(ax, -0.3, 0, text = lorem_ipsum, word_wrap_width=200, fontsize = 12, align = (:center, :top), color = :blue) + text!(ax, 0, 0, text = latexstring(L"$1$ " * lorem_ipsum), word_wrap_width = 250, fontsize = 12, align = (:left, :bottom), justification = :left, color = :black) + text!(ax, 0, 0, text = lorem_ipsum, word_wrap_width = 250, fontsize = 12, align = (:left, :top), justification = :right, color = :black) + text!(ax, 0, 0, text = lorem_ipsum, word_wrap_width = 250, fontsize = 12, align = (:right, :bottom), justification = :center, color = :red) + text!(ax, -0.3, 0, text = lorem_ipsum, word_wrap_width = 200, fontsize = 12, align = (:center, :top), color = :blue) xlims!(ax, -0.8, 0.8) ylims!(ax, -0.8, 0.6) fig diff --git a/ReferenceTests/src/tests/updating.jl b/ReferenceTests/src/tests/updating.jl index ea1bb97c44f..d9b3cef5158 100644 --- a/ReferenceTests/src/tests/updating.jl +++ b/ReferenceTests/src/tests/updating.jl @@ -1,10 +1,10 @@ @reference_test "updating 2d primitives" begin fig = Figure() t = Observable(1) - text(fig[1, 1], lift(i-> map(j-> ("$j", Point2f(j*30, 0)), 1:i), t), axis=(limits=(0, 380, -10, 10),), fontsize=50) - scatter(fig[1, 2], lift(i-> Point2f.((1:i).*30, 0), t), axis=(limits=(0, 330, -10, 10),), markersize=50) - linesegments(fig[2, 1], lift(i-> Point2f.((2:2:4i).*30, 0), t), axis=(limits=(30, 650, -10, 10),), linewidth=20) - lines(fig[2, 2], lift(i-> Point2f.((2:2:4i).*30, 0), t), axis=(limits=(30, 650, -10, 10),), linewidth=20) + text(fig[1, 1], lift(i -> map(j -> ("$j", Point2f(j * 30, 0)), 1:i), t), axis = (limits = (0, 380, -10, 10),), fontsize = 50) + scatter(fig[1, 2], lift(i -> Point2f.((1:i) .* 30, 0), t), axis = (limits = (0, 330, -10, 10),), markersize = 50) + linesegments(fig[2, 1], lift(i -> Point2f.((2:2:(4i)) .* 30, 0), t), axis = (limits = (30, 650, -10, 10),), linewidth = 20) + lines(fig[2, 2], lift(i -> Point2f.((2:2:(4i)) .* 30, 0), t), axis = (limits = (30, 650, -10, 10),), linewidth = 20) st = Stepper(fig) @@ -21,21 +21,21 @@ end @reference_test "updating multiple meshes" begin - points = Observable(Point3f[(1,0,0), (0,1,0), (0,0,1)]) + points = Observable(Point3f[(1, 0, 0), (0, 1, 0), (0, 0, 1)]) - meshes = map(p->Makie.normal_mesh(Sphere(p, 0.2)), points[]) - colors = map(p->RGBf(normalize(p)...), points[]) + meshes = map(p -> Makie.normal_mesh(Sphere(p, 0.2)), points[]) + colors = map(p -> RGBf(normalize(p)...), points[]) fig, ax, pl = mesh(meshes; color = colors) st = Stepper(fig) Makie.step!(st) on(points) do pts - pl[1].val = map(p->Makie.normal_mesh(Sphere(p, 0.2)), points[]) - pl.color.val = map(p->RGBf(normalize(p)...), points[]) + pl[1].val = map(p -> Makie.normal_mesh(Sphere(p, 0.2)), points[]) + pl.color.val = map(p -> RGBf(normalize(p)...), points[]) notify(pl[1]) end - append!(points[], Point3f[(0,1,1), (1,0,1), (1,1,0)]) + append!(points[], Point3f[(0, 1, 1), (1, 0, 1), (1, 1, 0)]) notify(points) Makie.step!(st) end @@ -43,10 +43,10 @@ end function generate_plot(N = 3) points = Observable(Point2f[]) color = Observable(RGBAf[]) - fig, ax, pl = scatter(points, color=color, markersize=1.0, marker=Circle, markerspace=:data, axis=(type=Axis, aspect=DataAspect(), limits=(0.4, N + 0.6, 0.4, N + 0.6),), figure=(resolution=(800, 800),)) + fig, ax, pl = scatter(points, color = color, markersize = 1.0, marker = Circle, markerspace = :data, axis = (type = Axis, aspect = DataAspect(), limits = (0.4, N + 0.6, 0.4, N + 0.6),), figure = (resolution = (800, 800),)) function update_func(ij) push!(points.val, Point2f(Tuple(ij))) - push!(color.val, RGBAf((Tuple(ij)./N)..., 0, 1)) + push!(color.val, RGBAf((Tuple(ij) ./ N)..., 0, 1)) notify(color) notify(points) end @@ -60,10 +60,10 @@ end function load_frames(video, dir) framedir = joinpath(dir, "frames") - isdir(framedir) && rm(framedir; recursive=true, force=true) + isdir(framedir) && rm(framedir; recursive = true, force = true) mkdir(framedir) Makie.extract_frames(video, framedir) - return map(readdir(framedir; join=true)) do path + return map(readdir(framedir; join = true)) do path return convert(Matrix{RGB{N0f8}}, load(path)) end end @@ -92,7 +92,7 @@ end compare_videos(reference, path, dir) fig, iter, func = generate_plot(2) - vso = Makie.Record(func, fig, iter; format="mkv") + vso = Makie.Record(func, fig, iter; format = "mkv") path = joinpath(dir, "test.$format") save(path, vso) compare_videos(reference, path, dir) diff --git a/ReferenceTests/src/visual-regression.jl b/ReferenceTests/src/visual-regression.jl index a0a362e94df..1b169799af4 100644 --- a/ReferenceTests/src/visual-regression.jl +++ b/ReferenceTests/src/visual-regression.jl @@ -30,45 +30,41 @@ end minfinite_scalar(a::T, b::T) where {T} = isfinite(a) ? (b < a ? b : a) : b maxfinite_scalar(a::T, b::T) where {T} = isfinite(a) ? (b > a ? b : a) : b -minfinite_scalar(a::T, b::T) where {T <: Union{Integer,FixedPoint}} = b < a ? b : a -maxfinite_scalar(a::T, b::T) where {T <: Union{Integer,FixedPoint}} = b > a ? b : a +minfinite_scalar(a::T, b::T) where {T <: Union{Integer, FixedPoint}} = b < a ? b : a +maxfinite_scalar(a::T, b::T) where {T <: Union{Integer, FixedPoint}} = b > a ? b : a minfinite_scalar(a, b) = minfinite_scalar(promote(a, b)...) maxfinite_scalar(a, b) = maxfinite_scalar(promote(a, b)...) -function minfinite_scalar(c1::C, c2::C) where C <: AbstractRGB - C(minfinite_scalar(c1.r, c2.r), - minfinite_scalar(c1.g, c2.g), - minfinite_scalar(c1.b, c2.b)) -end -function maxfinite_scalar(c1::C, c2::C) where C <: AbstractRGB - C(maxfinite_scalar(c1.r, c2.r), - maxfinite_scalar(c1.g, c2.g), - maxfinite_scalar(c1.b, c2.b)) -end +minfinite_scalar(c1::C, c2::C) where C <: AbstractRGB = C(minfinite_scalar(c1.r, c2.r), + minfinite_scalar(c1.g, c2.g), + minfinite_scalar(c1.b, c2.b)) +maxfinite_scalar(c1::C, c2::C) where C <: AbstractRGB = C(maxfinite_scalar(c1.r, c2.r), + maxfinite_scalar(c1.g, c2.g), + maxfinite_scalar(c1.b, c2.b)) -sentinel_min(::Type{T}) where {T <: Union{Integer,FixedPoint}} = typemax(T) -sentinel_max(::Type{T}) where {T <: Union{Integer,FixedPoint}} = typemin(T) +sentinel_min(::Type{T}) where {T <: Union{Integer, FixedPoint}} = typemax(T) +sentinel_max(::Type{T}) where {T <: Union{Integer, FixedPoint}} = typemin(T) sentinel_min(::Type{T}) where {T <: AbstractFloat} = convert(T, NaN) sentinel_max(::Type{T}) where {T <: AbstractFloat} = convert(T, NaN) sentinel_min(::Type{C}) where {C <: AbstractRGB} = _sentinel_min(C, eltype(C)) -_sentinel_min(::Type{C},::Type{T}) where {C <: AbstractRGB,T} = (s = sentinel_min(T); C(s, s, s)) +_sentinel_min(::Type{C}, ::Type{T}) where {C <: AbstractRGB, T} = (s = sentinel_min(T); C(s, s, s)) sentinel_max(::Type{C}) where {C <: AbstractRGB} = _sentinel_max(C, eltype(C)) -_sentinel_max(::Type{C},::Type{T}) where {C <: AbstractRGB,T} = (s = sentinel_max(T); C(s, s, s)) +_sentinel_max(::Type{C}, ::Type{T}) where {C <: AbstractRGB, T} = (s = sentinel_max(T); C(s, s, s)) difftype(::Type{T}) where {T <: Integer} = Int difftype(::Type{T}) where {T <: Real} = Float32 difftype(::Type{Float64}) = Float64 difftype(::Type{CV}) where {CV <: Colorant} = difftype(CV, eltype(CV)) -difftype(::Type{CV}, ::Type{T}) where {CV <: RGBA,T <: Real} = RGBA{Float32} +difftype(::Type{CV}, ::Type{T}) where {CV <: RGBA, T <: Real} = RGBA{Float32} difftype(::Type{CV}, ::Type{Float64}) where {CV <: RGBA} = RGBA{Float64} difftype(::Type{CV}, ::Type{Float64}) where {CV <: Gray} = Gray{Float64} -difftype(::Type{CV}, ::Type{T}) where {CV <: BGRA,T <: Real} = BGRA{Float32} +difftype(::Type{CV}, ::Type{T}) where {CV <: BGRA, T <: Real} = BGRA{Float32} difftype(::Type{CV}, ::Type{Float64}) where {CV <: BGRA} = BGRA{Float64} -difftype(::Type{CV}, ::Type{T}) where {CV <: AbstractRGB,T <: Real} = RGB{Float32} +difftype(::Type{CV}, ::Type{T}) where {CV <: AbstractRGB, T <: Real} = RGB{Float32} difftype(::Type{CV}, ::Type{Float64}) where {CV <: AbstractRGB} = RGB{Float64} accum(::Type{T}) where {T <: Integer} = Int -accum(::Type{Float32}) = Float32 +accum(::Type{Float32}) = Float32 accum(::Type{T}) where {T <: Real} = Float64 accum(::Type{C}) where {C <: Colorant} = base_colorant_type(C){accum(eltype(C))} function sumdiff(f, A::AbstractArray, B::AbstractArray) @@ -90,10 +86,10 @@ sad(A::AbstractArray, B::AbstractArray) = sumdiff(abs, A, B) function approx_difference( - A::AbstractArray, B::AbstractArray, - sigma::AbstractVector{T}=ones(ndims(A)), - eps::AbstractFloat=1e-2 - ) where T <: Real + A::AbstractArray, B::AbstractArray, + sigma::AbstractVector{T} = ones(ndims(A)), + eps::AbstractFloat = 1e-2 +) where T <: Real if length(sigma) != ndims(A) error("Invalid sigma in test_approx_eq_sigma_eps. Should be ndims(A)-length vector of the number of pixels to blur. Got: $sigma") diff --git a/WGLMakie/src/WGLMakie.jl b/WGLMakie/src/WGLMakie.jl index eaaab22aa03..83c53dc37c3 100644 --- a/WGLMakie/src/WGLMakie.jl +++ b/WGLMakie/src/WGLMakie.jl @@ -79,7 +79,7 @@ function __init__() end # re-export Makie, including deprecated names -for name in names(Makie, all=true) +for name in names(Makie, all = true) if Base.isexported(Makie, name) && name !== :Button && name !== :Slider @eval using Makie: $(name) @eval export $(name) diff --git a/WGLMakie/src/display.jl b/WGLMakie/src/display.jl index ef843258194..933b18ed74e 100644 --- a/WGLMakie/src/display.jl +++ b/WGLMakie/src/display.jl @@ -57,16 +57,12 @@ for M in WEB_MIMES end end -function Makie.backend_showable(::Type{Screen}, ::T) where {T<:MIME} - return T in WEB_MIMES -end +Makie.backend_showable(::Type{Screen}, ::T) where {T <: MIME} = T in WEB_MIMES # TODO implement Base.close(screen::Screen) = nothing -function Base.size(screen::Screen) - return size(screen.scene) -end +Base.size(screen::Screen) = size(screen.scene) function get_three(screen::Screen; timeout = 100) tstart = time() @@ -113,9 +109,7 @@ function Base.display(screen::Screen, scene::Scene; kw...) return screen end -function Base.delete!(td::Screen, scene::Scene, plot::AbstractPlot) - delete!(get_three(td), scene, plot) -end +Base.delete!(td::Screen, scene::Scene, plot::AbstractPlot) = delete!(get_three(td), scene, plot) function session2image(sessionlike) yield() @@ -125,15 +119,13 @@ function session2image(sessionlike) return document.querySelector('canvas').toDataURL() }() """ - picture_base64 = JSServe.evaljs_value(s, to_data; time_out=100) + picture_base64 = JSServe.evaljs_value(s, to_data; time_out = 100) picture_base64 = replace(picture_base64, "data:image/png;base64," => "") bytes = JSServe.Base64.base64decode(picture_base64) return ImageMagick.load_(bytes) end -function Makie.colorbuffer(screen::ThreeDisplay) - return session2image(screen) -end +Makie.colorbuffer(screen::ThreeDisplay) = session2image(screen) function Makie.colorbuffer(screen::Screen) if screen.display !== true diff --git a/WGLMakie/src/imagelike.jl b/WGLMakie/src/imagelike.jl index c5c146b2de3..57ae92cf6b4 100644 --- a/WGLMakie/src/imagelike.jl +++ b/WGLMakie/src/imagelike.jl @@ -24,7 +24,7 @@ function draw_mesh(mscene::Scene, mesh, plot; uniforms...) get!(uniforms, :color, false) get!(uniforms, :pattern, false) get!(uniforms, :model, plot.model) - get!(uniforms, :depth_shift, 0f0) + get!(uniforms, :depth_shift, 0.0f0) get!(uniforms, :lightposition, Vec3f(1)) get!(uniforms, :ambient, Vec3f(1)) get!(uniforms, :interpolate_in_fragment_shader, true) @@ -42,8 +42,8 @@ xy_convert(x, n) = Float32[LinRange(extrema(x)..., n + 1);] function limits_to_uvmesh(plot) px, py, pz = plot[1], plot[2], plot[3] - px = map((x, z)-> xy_convert(x, size(z, 1)), px, pz) - py = map((y, z)-> xy_convert(y, size(z, 2)), py, pz) + px = map((x, z) -> xy_convert(x, size(z, 1)), px, pz) + py = map((y, z) -> xy_convert(y, size(z, 2)), py, pz) # Special path for ranges of length 2 which # can be displayed as a rectangle t = Makie.transform_func_obs(plot)[] @@ -53,18 +53,18 @@ function limits_to_uvmesh(plot) ymin, ymax = extrema(y) return Rect2(xmin, ymin, xmax - xmin, ymax - ymin) end - positions = Buffer(lift(rect-> decompose(Point2f, rect), rect)) + positions = Buffer(lift(rect -> decompose(Point2f, rect), rect)) faces = Buffer(lift(rect -> decompose(GLTriangleFace, rect), rect)) uv = Buffer(lift(decompose_uv, rect)) - else - grid(x, y, trans, space) = Makie.matrix_grid(p-> apply_transform(trans, p, space), x, y, zeros(length(x), length(y))) - rect = lift((x, y) -> Tesselation(Rect2(0f0, 0f0, 1f0, 1f0), (length(x), length(y))), px, py) + else + grid(x, y, trans, space) = Makie.matrix_grid(p -> apply_transform(trans, p, space), x, y, zeros(length(x), length(y))) + rect = lift((x, y) -> Tesselation(Rect2(0.0f0, 0.0f0, 1.0f0, 1.0f0), (length(x), length(y))), px, py) positions = Buffer(lift(grid, px, py, t, get(plot, :space, :data))) faces = Buffer(lift(r -> decompose(GLTriangleFace, r), rect)) uv = Buffer(lift(decompose_uv, rect)) end - vertices = GeometryBasics.meta(positions; uv=uv) + vertices = GeometryBasics.meta(positions; uv = uv) return GeometryBasics.Mesh(vertices, faces) end @@ -80,9 +80,9 @@ end function create_shader(mscene::Scene, plot::Surface) # TODO OWN OPTIMIZED SHADER ... Or at least optimize this a bit more ... px, py, pz = plot[1], plot[2], plot[3] - grid(x, y, z, trans, space) = Makie.matrix_grid(p-> apply_transform(trans, p, space), x, y, z) + grid(x, y, z, trans, space) = Makie.matrix_grid(p -> apply_transform(trans, p, space), x, y, z) positions = Buffer(lift(grid, px, py, pz, transform_func_obs(plot), get(plot, :space, :data))) - rect = lift(z -> Tesselation(Rect2(0f0, 0f0, 1f0, 1f0), size(z)), pz) + rect = lift(z -> Tesselation(Rect2(0.0f0, 0.0f0, 1.0f0, 1.0f0), size(z)), pz) faces = Buffer(lift(r -> decompose(GLTriangleFace, r), rect)) uv = Buffer(lift(decompose_uv, rect)) plot_attributes = copy(plot.attributes) @@ -96,24 +96,24 @@ function create_shader(mscene::Scene, plot::Surface) pz end minfilter = to_value(get(plot, :interpolate, true)) ? :linear : :nearest - color = Sampler(lift(x -> el32convert(to_color(permutedims(x))), pcolor), minfilter=minfilter) + color = Sampler(lift(x -> el32convert(to_color(permutedims(x))), pcolor), minfilter = minfilter) normals = Buffer(lift(surface_normals, px, py, pz)) - vertices = GeometryBasics.meta(positions; uv=uv, normals=normals) + vertices = GeometryBasics.meta(positions; uv = uv, normals = normals) mesh = GeometryBasics.Mesh(vertices, faces) - return draw_mesh(mscene, mesh, plot_attributes; uniform_color=color, color=false, - shading=plot.shading, diffuse=plot.diffuse, - specular=plot.specular, shininess=plot.shininess, - depth_shift=get(plot, :depth_shift, Observable(0f0)), - backlight=plot.backlight, - highclip=get_color(plot, :highclip), - lowclip=get_color(plot, :lowclip), - nan_color=get_color(plot, :nan_color)) + return draw_mesh(mscene, mesh, plot_attributes; uniform_color = color, color = false, + shading = plot.shading, diffuse = plot.diffuse, + specular = plot.specular, shininess = plot.shininess, + depth_shift = get(plot, :depth_shift, Observable(0.0f0)), + backlight = plot.backlight, + highclip = get_color(plot, :highclip), + lowclip = get_color(plot, :lowclip), + nan_color = get_color(plot, :nan_color)) end function create_shader(mscene::Scene, plot::Union{Heatmap, Image}) image = plot[3] color = Sampler(map(x -> el32convert(x'), image); - minfilter=to_value(get(plot, :interpolate, false)) ? :linear : :nearest) + minfilter = to_value(get(plot, :interpolate, false)) ? :linear : :nearest) mesh = limits_to_uvmesh(plot) plot_attributes = copy(plot.attributes) if eltype(color) <: Colorant @@ -122,16 +122,16 @@ function create_shader(mscene::Scene, plot::Union{Heatmap, Image}) end return draw_mesh(mscene, mesh, plot_attributes; - uniform_color=color, color=false, - normals=Vec3f(0), shading=false, - diffuse=plot.diffuse, specular=plot.specular, - colorrange=haskey(plot, :colorrange) ? plot.colorrange : false, - shininess=plot.shininess, - highclip=get_color(plot, :highclip), - lowclip=get_color(plot, :lowclip), - nan_color=get_color(plot, :nan_color), - backlight=0f0, - depth_shift = get(plot, :depth_shift, Observable(0f0))) + uniform_color = color, color = false, + normals = Vec3f(0), shading = false, + diffuse = plot.diffuse, specular = plot.specular, + colorrange = haskey(plot, :colorrange) ? plot.colorrange : false, + shininess = plot.shininess, + highclip = get_color(plot, :highclip), + lowclip = get_color(plot, :lowclip), + nan_color = get_color(plot, :nan_color), + backlight = 0.0f0, + depth_shift = get(plot, :depth_shift, Observable(0.0f0))) end function create_shader(mscene::Scene, plot::Volume) @@ -150,16 +150,16 @@ function create_shader(mscene::Scene, plot::Volume) algorithm = lift(x -> Cuint(convert_attribute(x, key"algorithm"())), plot.algorithm) return Program(WebGL(), lasset("volume.vert"), lasset("volume.frag"), box, - volumedata=Sampler(lift(Makie.el32convert, vol)), - modelinv=modelinv, colormap=Sampler(lift(to_colormap, plot.colormap)), - colorrange=lift(Vec2f, plot.colorrange), - isovalue=lift(Float32, plot.isovalue), - isorange=lift(Float32, plot.isorange), - absorption=lift(Float32, get(plot, :absorption, Observable(1f0))), - algorithm=algorithm, - diffuse=plot.diffuse, specular=plot.specular, shininess=plot.shininess, - model=model2, depth_shift = get(plot, :depth_shift, Observable(0f0)), - # these get filled in later by serialization, but we need them - # as dummy values here, so that the correct uniforms are emitted - lightposition=Vec3f(1), eyeposition=Vec3f(1), ambient=Vec3f(1)) + volumedata = Sampler(lift(Makie.el32convert, vol)), + modelinv = modelinv, colormap = Sampler(lift(to_colormap, plot.colormap)), + colorrange = lift(Vec2f, plot.colorrange), + isovalue = lift(Float32, plot.isovalue), + isorange = lift(Float32, plot.isorange), + absorption = lift(Float32, get(plot, :absorption, Observable(1.0f0))), + algorithm = algorithm, + diffuse = plot.diffuse, specular = plot.specular, shininess = plot.shininess, + model = model2, depth_shift = get(plot, :depth_shift, Observable(0.0f0)), + # these get filled in later by serialization, but we need them + # as dummy values here, so that the correct uniforms are emitted + lightposition = Vec3f(1), eyeposition = Vec3f(1), ambient = Vec3f(1)) end diff --git a/WGLMakie/src/lines.jl b/WGLMakie/src/lines.jl index 6a8fc668f4e..7597c2051de 100644 --- a/WGLMakie/src/lines.jl +++ b/WGLMakie/src/lines.jl @@ -1,17 +1,13 @@ -topoint(x::AbstractVector{Point{N,Float32}}) where {N} = x +topoint(x::AbstractVector{Point{N, Float32}}) where {N} = x # GRRR STUPID SubArray, with eltype different from getindex(x, 1) topoint(x::SubArray) = topoint([el for el in x]) -function topoint(x::AbstractArray{<:Point{N,T}}) where {T,N} - return topoint(Point{N,Float32}.(x)) -end +topoint(x::AbstractArray{<:Point{N, T}}) where {T, N} = topoint(Point{N, Float32}.(x)) -function topoint(x::AbstractArray{<:Tuple{P,P}}) where {P<:Point} - return topoint(reinterpret(P, x)) -end +topoint(x::AbstractArray{<:Tuple{P, P}}) where {P <: Point} = topoint(reinterpret(P, x)) -function create_shader(scene::Scene, plot::Union{Lines,LineSegments}) +function create_shader(scene::Scene, plot::Union{Lines, LineSegments}) # Potentially per instance attributes positions = lift(plot[1], transform_func_obs(plot), get(plot, :space, :data)) do points, trans, space points = apply_transform(trans, topoint(points), space) @@ -29,9 +25,9 @@ function create_shader(scene::Scene, plot::Union{Lines,LineSegments}) return (positions[startr[]], positions[endr[]]) end - per_instance = Dict{Symbol,Any}(:segment_start => Buffer(lift(first, p_start_end)), - :segment_end => Buffer(lift(last, p_start_end))) - uniforms = Dict{Symbol,Any}() + per_instance = Dict{Symbol, Any}(:segment_start => Buffer(lift(first, p_start_end)), + :segment_end => Buffer(lift(last, p_start_end))) + uniforms = Dict{Symbol, Any}() for k in (:linewidth, :color) attribute = lift(plot[k]) do x x = convert_attribute(x, Key{k}(), key"lines"()) @@ -57,12 +53,12 @@ function create_shader(scene::Scene, plot::Union{Lines,LineSegments}) uniforms[:resolution] = scene.camera.resolution uniforms[:model] = plot.model - uniforms[:depth_shift] = get(plot, :depth_shift, Observable(0f0)) + uniforms[:depth_shift] = get(plot, :depth_shift, Observable(0.0f0)) positions = meta(Point2f[(0, -1), (0, 1), (1, -1), (1, 1)], - uv=Vec2f[(0, 0), (0, 0), (0, 0), (0, 0)]) + uv = Vec2f[(0, 0), (0, 0), (0, 0), (0, 0)]) instance = GeometryBasics.Mesh(positions, GLTriangleFace[(1, 2, 3), (2, 4, 3)]) return InstancedProgram(WebGL(), lasset("line_segments.vert"), - lasset("line_segments.frag"), instance, - VertexArray(; per_instance...); uniforms...) + lasset("line_segments.frag"), instance, + VertexArray(; per_instance...); uniforms...) end diff --git a/WGLMakie/src/meshes.jl b/WGLMakie/src/meshes.jl index 9f433ef6486..26dd760db76 100644 --- a/WGLMakie/src/meshes.jl +++ b/WGLMakie/src/meshes.jl @@ -1,32 +1,25 @@ function vertexbuffer(x, trans, space) pos = decompose(Point, x) - return apply_transform(trans, pos, space) + return apply_transform(trans, pos, space) end -function vertexbuffer(x::Observable, p) - return Buffer(lift(vertexbuffer, x, transform_func_obs(p), get(p, :space, :data))) -end +vertexbuffer(x::Observable, p) = Buffer(lift(vertexbuffer, x, transform_func_obs(p), get(p, :space, :data))) facebuffer(x) = facebuffer(GeometryBasics.faces(x)) facebuffer(x::Observable) = Buffer(lift(facebuffer, x)) -function facebuffer(x::AbstractArray{GLTriangleFace}) - return x -end +facebuffer(x::AbstractArray{GLTriangleFace}) = x function array2color(colors, cmap, crange) cmap = RGBAf.(Colors.color.(to_colormap(cmap)), 1.0) return Makie.interpolated_getindex.((cmap,), colors, (crange,)) end -function array2color(colors::AbstractArray{<:Colorant}, cmap, crange) - return RGBAf.(colors) -end +array2color(colors::AbstractArray{<:Colorant}, cmap, crange) = RGBAf.(colors) -function converted_attribute(plot::AbstractPlot, key::Symbol) - return lift(plot[key]) do value +converted_attribute(plot::AbstractPlot, key::Symbol) = + lift(plot[key]) do value return convert_attribute(value, Key{key}(), Key{plotkey(plot)}()) end -end function create_shader(scene::Scene, plot::Makie.Mesh) # Potentially per instance attributes @@ -35,8 +28,8 @@ function create_shader(scene::Scene, plot::Makie.Mesh) get_attribute(mesh, key) = lift(x -> getproperty(x, key), mesh) data = mattributes(mesh_signal[]) - uniforms = Dict{Symbol,Any}() - attributes = Dict{Symbol,Any}() + uniforms = Dict{Symbol, Any}() + attributes = Dict{Symbol, Any}() uniforms[:interpolate_in_fragment_shader] = get(plot, :interpolate_in_fragment_shader, true) @@ -118,7 +111,7 @@ function create_shader(scene::Scene, plot::Makie.Mesh) end end - uniforms[:depth_shift] = get(plot, :depth_shift, Observable(0f0)) + uniforms[:depth_shift] = get(plot, :depth_shift, Observable(0.0f0)) uniforms[:normalmatrix] = map(scene.camera.view, plot.model) do v, m i = Vec(1, 2, 3) diff --git a/WGLMakie/src/particles.jl b/WGLMakie/src/particles.jl index b7703701429..f164d0402f1 100644 --- a/WGLMakie/src/particles.jl +++ b/WGLMakie/src/particles.jl @@ -8,8 +8,8 @@ function handle_color!(uniform_dict, instance_dict) nothing, uniform_dict end if color isa Colorant || - color isa AbstractVector{<:Colorant} || - color === nothing + color isa AbstractVector{<:Colorant} || + color === nothing delete!(uniform_dict, :colormap) elseif color isa AbstractArray{<:Real} uniform_dict[:color_getter] = """ @@ -54,7 +54,7 @@ function create_shader(scene::Scene, plot::MeshScatter) return k in per_instance_keys && !(isscalar(v[])) end space = get(plot, :space, :data) - per_instance[:offset] = apply_transform(transform_func_obs(plot), plot[1], space) + per_instance[:offset] = apply_transform(transform_func_obs(plot), plot[1], space) for (k, v) in per_instance per_instance[k] = Buffer(lift_convert(k, v, plot)) @@ -64,7 +64,7 @@ function create_shader(scene::Scene, plot::MeshScatter) return (!haskey(per_instance, k)) && isscalar(v[]) end - uniform_dict = Dict{Symbol,Any}() + uniform_dict = Dict{Symbol, Any}() for (k, v) in uniforms k in IGNORE_KEYS && continue uniform_dict[k] = lift_convert(k, v, plot) @@ -77,7 +77,7 @@ function create_shader(scene::Scene, plot::MeshScatter) uniform_dict[:uv] = Vec2f(0) end - uniform_dict[:depth_shift] = get(plot, :depth_shift, Observable(0f0)) + uniform_dict[:depth_shift] = get(plot, :depth_shift, Observable(0.0f0)) uniform_dict[:backlight] = plot.backlight get!(uniform_dict, :ambient, Vec3f(1)) @@ -90,7 +90,7 @@ function create_shader(scene::Scene, plot::MeshScatter) end return InstancedProgram(WebGL(), lasset("particles.vert"), lasset("particles.frag"), - instance, VertexArray(; per_instance...); uniform_dict...) + instance, VertexArray(; per_instance...); uniform_dict...) end using Makie: to_spritemarker @@ -98,8 +98,8 @@ using Makie: to_spritemarker function scatter_shader(scene::Scene, attributes) # Potentially per instance attributes per_instance_keys = (:pos, :rotations, :markersize, :color, :intensity, - :uv_offset_width, :quad_offset, :marker_offset) - uniform_dict = Dict{Symbol,Any}() + :uv_offset_width, :quad_offset, :marker_offset) + uniform_dict = Dict{Symbol, Any}() uniform_dict[:image] = false marker = nothing atlas = wgl_texture_atlas() @@ -144,27 +144,27 @@ function scatter_shader(scene::Scene, attributes) end if uniform_dict[:shape_type][] == 3 - uniform_dict[:distancefield] = Sampler(atlas.data, minfilter=:linear, - magfilter=:linear, anisotropic=16f0) + uniform_dict[:distancefield] = Sampler(atlas.data, minfilter = :linear, + magfilter = :linear, anisotropic = 16.0f0) uniform_dict[:atlas_texture_size] = Float32(size(atlas, 1)) # Texture must be quadratic else - uniform_dict[:atlas_texture_size] = 0f0 + uniform_dict[:atlas_texture_size] = 0.0f0 uniform_dict[:distancefield] = Observable(false) end handle_color!(uniform_dict, per_instance) - instance = uv_mesh(Rect2(-0.5f0, -0.5f0, 1f0, 1f0)) + instance = uv_mesh(Rect2(-0.5f0, -0.5f0, 1.0f0, 1.0f0)) uniform_dict[:resolution] = scene.camera.resolution return InstancedProgram(WebGL(), lasset("simple.vert"), lasset("sprites.frag"), - instance, VertexArray(; per_instance...); uniform_dict...) + instance, VertexArray(; per_instance...); uniform_dict...) end function create_shader(scene::Scene, plot::Scatter) # Potentially per instance attributes per_instance_keys = (:offset, :rotations, :markersize, :color, :intensity, - :quad_offset) + :quad_offset) per_instance = filter(plot.attributes.attributes) do (k, v) return k in per_instance_keys && !(isscalar(v[])) end @@ -175,14 +175,14 @@ function create_shader(scene::Scene, plot::Scatter) attributes[:preprojection] = map(space, mspace, cam.projectionview, cam.resolution) do space, mspace, _, _ Makie.clip_to_space(cam, mspace) * Makie.space_to_clip(cam, space) end - attributes[:pos] = apply_transform(transform_func_obs(plot), plot[1], space) + attributes[:pos] = apply_transform(transform_func_obs(plot), plot[1], space) quad_offset = get(attributes, :marker_offset, Observable(Vec2f(0))) attributes[:marker_offset] = Vec3f(0) attributes[:quad_offset] = quad_offset attributes[:billboard] = map(rot -> isa(rot, Billboard), plot.rotations) attributes[:model] = plot.model attributes[:markerspace] = plot.markerspace - attributes[:depth_shift] = get(plot, :depth_shift, Observable(0f0)) + attributes[:depth_shift] = get(plot, :depth_shift, Observable(0.0f0)) delete!(attributes, :uv_offset_width) filter!(kv -> !(kv[2] isa Function), attributes) @@ -196,9 +196,9 @@ value_or_first(x) = x function create_shader(scene::Scene, plot::Makie.Text{<:Tuple{<:Union{<:Makie.GlyphCollection, <:AbstractVector{<:Makie.GlyphCollection}}}}) glyphcollection = plot[1] - res = map(x->Vec2f(widths(x)), pixelarea(scene)) + res = map(x -> Vec2f(widths(x)), pixelarea(scene)) projview = scene.camera.projectionview - transfunc = Makie.transform_func_obs(scene) + transfunc = Makie.transform_func_obs(scene) pos = plot.position space = plot.space markerspace = plot.markerspace @@ -266,7 +266,7 @@ function create_shader(scene::Scene, plot::Makie.Text{<:Tuple{<:Union{<:Makie.Gl :uv_offset_width => uv_offset_width, :transform_marker => get(plot.attributes, :transform_marker, Observable(true)), :billboard => Observable(false), - :depth_shift => get(plot, :depth_shift, Observable(0f0)) + :depth_shift => get(plot, :depth_shift, Observable(0.0f0)) ) return scatter_shader(scene, uniforms) diff --git a/WGLMakie/src/precompiles.jl b/WGLMakie/src/precompiles.jl index be5fa88c49a..8bdbe9d3d2d 100644 --- a/WGLMakie/src/precompiles.jl +++ b/WGLMakie/src/precompiles.jl @@ -11,7 +11,7 @@ macro compile(block) three_display(Session(), scene) JSServe.jsrender(Session(), figlike) s = serialize_scene(scene) - JSServe.serialize_binary(Session(), Dict(:data=>s)) + JSServe.serialize_binary(Session(), Dict(:data => s)) end end diff --git a/WGLMakie/src/serialization.jl b/WGLMakie/src/serialization.jl index d5c3bce2170..c314be673ab 100644 --- a/WGLMakie/src/serialization.jl +++ b/WGLMakie/src/serialization.jl @@ -13,9 +13,7 @@ function lift_convert(key, value, plot) end end -function Base.pairs(mesh::GeometryBasics.Mesh) - return (kv for kv in GeometryBasics.attributes(mesh)) -end +Base.pairs(mesh::GeometryBasics.Mesh) = (kv for kv in GeometryBasics.attributes(mesh)) # Don't overload faces to not invalidate _faces(x::VertexArray) = GeometryBasics.faces(getfield(x, :data)) @@ -34,54 +32,34 @@ serialize_three(val::RGBA) = Float32[red(val), green(val), blue(val), alpha(val) serialize_three(val::Mat4f) = vec(val) serialize_three(val::Mat3) = vec(val) -function serialize_three(observable::Observable) - return Dict(:type => "Observable", :id => observable.id, - :value => serialize_three(observable[])) -end +serialize_three(observable::Observable) = Dict(:type => "Observable", :id => observable.id, + :value => serialize_three(observable[])) -function serialize_three(array::AbstractArray) - return serialize_three(flatten_buffer(array)) -end +serialize_three(array::AbstractArray) = serialize_three(flatten_buffer(array)) -function serialize_three(array::Buffer) - return serialize_three(flatten_buffer(array)) -end +serialize_three(array::Buffer) = serialize_three(flatten_buffer(array)) -function serialize_three(array::AbstractArray{UInt8}) - return Dict(:type => "Uint8Array", :data => array) -end +serialize_three(array::AbstractArray{UInt8}) = Dict(:type => "Uint8Array", :data => array) -function serialize_three(array::AbstractArray{Int32}) - return Dict(:type => "Int32Array", :data => array) -end +serialize_three(array::AbstractArray{Int32}) = Dict(:type => "Int32Array", :data => array) -function serialize_three(array::AbstractArray{UInt32}) - return Dict(:type => "Uint32Array", :data => array) -end +serialize_three(array::AbstractArray{UInt32}) = Dict(:type => "Uint32Array", :data => array) -function serialize_three(array::AbstractArray{Float32}) - return Dict(:type => "Float32Array", :data => array) -end +serialize_three(array::AbstractArray{Float32}) = Dict(:type => "Float32Array", :data => array) -function serialize_three(array::AbstractArray{Float16}) - return Dict(:type => "Float32Array", :data => array) -end +serialize_three(array::AbstractArray{Float16}) = Dict(:type => "Float32Array", :data => array) -function serialize_three(array::AbstractArray{Float64}) - return Dict(:type => "Float64Array", :data => array) -end +serialize_three(array::AbstractArray{Float64}) = Dict(:type => "Float64Array", :data => array) -function serialize_three(p::Makie.AbstractPattern) - return serialize_three(Makie.to_image(p)) -end +serialize_three(p::Makie.AbstractPattern) = serialize_three(Makie.to_image(p)) -function serialize_three(color::Sampler{T,N}) where {T,N} +function serialize_three(color::Sampler{T, N}) where {T, N} tex = Dict(:type => "Sampler", :data => serialize_three(color.data), - :size => [size(color.data)...], :three_format => three_format(T), - :three_type => three_type(eltype(T)), - :minFilter => three_filter(color.minfilter), - :magFilter => three_filter(color.magfilter), - :wrapS => three_repeat(color.repeat[1]), :anisotropy => color.anisotropic) + :size => [size(color.data)...], :three_format => three_format(T), + :three_type => three_type(eltype(T)), + :minFilter => three_filter(color.minfilter), + :magFilter => three_filter(color.magfilter), + :wrapS => three_repeat(color.repeat[1]), :anisotropy => color.anisotropic) if N > 1 tex[:wrapT] = three_repeat(color.repeat[2]) end @@ -92,7 +70,7 @@ function serialize_three(color::Sampler{T,N}) where {T,N} end function serialize_uniforms(dict::Dict) - result = Dict{Symbol,Any}() + result = Dict{Symbol, Any}() for (k, v) in dict result[k] = serialize_three(to_value(v)) end @@ -126,21 +104,13 @@ 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}) - return array -end +flatten_buffer(array::AbstractArray{<:Number}) = array -function flatten_buffer(array::Buffer) - return flatten_buffer(getfield(array, :data)) -end +flatten_buffer(array::Buffer) = flatten_buffer(getfield(array, :data)) -function flatten_buffer(array::AbstractArray{T}) where {T<:N0f8} - return reinterpret(UInt8, array) -end +flatten_buffer(array::AbstractArray{T}) where {T <: N0f8} = reinterpret(UInt8, array) -function flatten_buffer(array::AbstractArray{T}) where {T} - return flatten_buffer(reinterpret(eltype(T), array)) -end +flatten_buffer(array::AbstractArray{T}) where {T} = flatten_buffer(reinterpret(eltype(T), array)) lasset(paths...) = read(joinpath(@__DIR__, "..", "assets", paths...), String) @@ -151,15 +121,11 @@ isscalar(x::Billboard) = isscalar(x.rotation) isscalar(x::Observable) = isscalar(x[]) isscalar(x) = true -function ShaderAbstractions.type_string(::ShaderAbstractions.AbstractContext, - ::Type{<:Makie.Quaternion}) - return "vec4" -end +ShaderAbstractions.type_string(::ShaderAbstractions.AbstractContext, + ::Type{<:Makie.Quaternion}) = "vec4" -function ShaderAbstractions.convert_uniform(::ShaderAbstractions.AbstractContext, - t::Quaternion) - return convert(Quaternion, t) -end +ShaderAbstractions.convert_uniform(::ShaderAbstractions.AbstractContext, + t::Quaternion) = convert(Quaternion, t) function wgl_convert(value, key1, key2) val = Makie.convert_attribute(value, key1, key2) @@ -170,19 +136,13 @@ function wgl_convert(value, key1, key2) end end -function wgl_convert(value::AbstractMatrix, ::key"colormap", key2) - return ShaderAbstractions.Sampler(value) -end +wgl_convert(value::AbstractMatrix, ::key"colormap", key2) = ShaderAbstractions.Sampler(value) -function serialize_buffer_attribute(buffer::AbstractVector{T}) where {T} - return Dict(:flat => serialize_three(buffer), :type_length => tlength(T)) -end +serialize_buffer_attribute(buffer::AbstractVector{T}) where {T} = Dict(:flat => serialize_three(buffer), :type_length => tlength(T)) -function serialize_named_buffer(buffer) - return Dict(map(pairs(buffer)) do (name, buff) - return name => serialize_buffer_attribute(buff) - end) -end +serialize_named_buffer(buffer) = Dict(map(pairs(buffer)) do (name, buff) + return name => serialize_buffer_attribute(buff) +end) function register_geometry_updates(update_buffer::Observable, named_buffers) for (name, buffer) in pairs(named_buffers) @@ -201,13 +161,9 @@ function register_geometry_updates(update_buffer::Observable, named_buffers) return update_buffer end -function register_geometry_updates(update_buffer::Observable, program::Program) - return register_geometry_updates(update_buffer, program.vertexarray) -end +register_geometry_updates(update_buffer::Observable, program::Program) = register_geometry_updates(update_buffer, program.vertexarray) -function register_geometry_updates(update_buffer::Observable, program::InstancedProgram) - return register_geometry_updates(update_buffer, program.per_instance) -end +register_geometry_updates(update_buffer::Observable, program::InstancedProgram) = register_geometry_updates(update_buffer, program.per_instance) function uniform_updater(uniforms::Dict) updater = Observable(Any[:none, []]) @@ -244,14 +200,14 @@ function serialize_three(program::Program) attribute_updater = Observable(["", [], 0]) register_geometry_updates(attribute_updater, program) return Dict(:vertexarrays => serialize_named_buffer(program.vertexarray), - :faces => indices, :uniforms => uniforms, - :vertex_source => program.vertex_source, - :fragment_source => program.fragment_source, - :uniform_updater => uniform_updater(program.uniforms), - :attribute_updater => attribute_updater) + :faces => indices, :uniforms => uniforms, + :vertex_source => program.vertex_source, + :fragment_source => program.fragment_source, + :uniform_updater => uniform_updater(program.uniforms), + :attribute_updater => attribute_updater) end -function serialize_scene(scene::Scene, serialized_scenes=[]) +function serialize_scene(scene::Scene, serialized_scenes = []) hexcolor(c) = "#" * hex(Colors.color(to_color(c))) pixel_area = lift(area -> [minimum(area)..., widths(area)...], pixelarea(scene)) cam_controls = cameracontrols(scene) @@ -263,13 +219,13 @@ function serialize_scene(scene::Scene, serialized_scenes=[]) end serialized = Dict(:pixelarea => pixel_area, - :backgroundcolor => lift(hexcolor, scene.backgroundcolor), - :clearscene => scene.clear, - :camera => serialize_camera(scene), - :plots => serialize_plots(scene, scene.plots), - :cam3d_state => cam3d_state, - :visible => scene.visible, - :uuid => js_uuid(scene)) + :backgroundcolor => lift(hexcolor, scene.backgroundcolor), + :clearscene => scene.clear, + :camera => serialize_camera(scene), + :plots => serialize_plots(scene, scene.plots), + :cam3d_state => cam3d_state, + :visible => scene.visible, + :uuid => js_uuid(scene)) push!(serialized_scenes, serialized) foreach(child -> serialize_scene(child, serialized_scenes), scene.children) @@ -277,7 +233,7 @@ function serialize_scene(scene::Scene, serialized_scenes=[]) return serialized_scenes end -function serialize_plots(scene::Scene, plots::Vector{T}, result=[]) where {T<:AbstractPlot} +function serialize_plots(scene::Scene, plots::Vector{T}, result = []) where {T <: AbstractPlot} for plot in plots # if no plots inserted, this truely is an atomic if isempty(plot.plots) diff --git a/WGLMakie/src/three_plot.jl b/WGLMakie/src/three_plot.jl index 430aed731e3..2a14d9ffaff 100644 --- a/WGLMakie/src/three_plot.jl +++ b/WGLMakie/src/three_plot.jl @@ -12,7 +12,7 @@ end function Base.size(screen::ThreeDisplay) # look at d.qs().clientWidth for displayed width - width, height = round.(Int, WGLMakie.JSServe.evaljs_value(screen.session, WGLMakie.JSServe.js"[document.querySelector('canvas').width, document.querySelector('canvas').height]"; time_out=100)) + width, height = round.(Int, WGLMakie.JSServe.evaljs_value(screen.session, WGLMakie.JSServe.js"[document.querySelector('canvas').width, document.querySelector('canvas').height]"; time_out = 100)) return (width, height) end @@ -21,9 +21,12 @@ js_uuid(object) = string(objectid(object)) function Base.insert!(td::ThreeDisplay, scene::Scene, plot::Combined) plot_data = serialize_plots(scene, [plot]) - JSServe.evaljs_value(td.session, js""" - $(WGL).insert_plot($(js_uuid(scene)), $plot_data) - """) + JSServe.evaljs_value( + td.session, + js""" + $(WGL).insert_plot($(js_uuid(scene)), $plot_data) +""" + ) return end @@ -33,13 +36,13 @@ function Base.delete!(td::ThreeDisplay, scene::Scene, plot::Combined) return end -function all_plots_scenes(scene::Scene; scene_uuids=String[], plot_uuids=String[]) +function all_plots_scenes(scene::Scene; scene_uuids = String[], plot_uuids = String[]) push!(scene_uuids, js_uuid(scene)) for plot in scene.plots append!(plot_uuids, (js_uuid(p) for p in Makie.flatten_plots(plot))) end for child in scene.children - all_plots_scenes(child, plot_uuids=plot_uuids, scene_uuids=scene_uuids) + all_plots_scenes(child, plot_uuids = plot_uuids, scene_uuids = scene_uuids) end return scene_uuids, plot_uuids end @@ -49,9 +52,7 @@ end Gets the ThreeJS object representing the plot object. """ -function find_plots(td::ThreeDisplay, plot::AbstractPlot) - return find_plots(JSServe.session(td), plot) -end +find_plots(td::ThreeDisplay, plot::AbstractPlot) = find_plots(JSServe.session(td), plot) function find_plots(session::Session, plot::AbstractPlot) uuids = js_uuid.(Makie.flatten_plots(plot)) @@ -79,9 +80,9 @@ function three_display(session::Session, scene::Scene; screen_config...) width, height = size(scene) - canvas = DOM.um("canvas", tabindex="0") + canvas = DOM.um("canvas", tabindex = "0") wrapper = DOM.div(canvas) - comm = Observable(Dict{String,Any}()) + comm = Observable(Dict{String, Any}()) push!(session, comm) scene_data = Observable(serialized) diff --git a/WGLMakie/test/offline_export.jl b/WGLMakie/test/offline_export.jl index 0d08ca7c066..19261784e35 100644 --- a/WGLMakie/test/offline_export.jl +++ b/WGLMakie/test/offline_export.jl @@ -1,8 +1,6 @@ using JSServe, WGLMakie, Makie -function handler(session, request) - return scatter(1:4, color=1:4) -end +handler(session, request) = scatter(1:4, color = 1:4) dir = joinpath(@__DIR__, "exported") isdir(dir) || mkdir(dir) @@ -10,4 +8,4 @@ JSServe.export_standalone(handler, dir) # Then serve it with e.g. LiveServer using LiveServer -LiveServer.serve(dir=dir) +LiveServer.serve(dir = dir) diff --git a/src/Makie.jl b/src/Makie.jl index 9de6f9550e9..09079fa46af 100644 --- a/src/Makie.jl +++ b/src/Makie.jl @@ -75,7 +75,7 @@ using MakieCore: Key, @key_str, Automatic, automatic, @recipe using MakieCore: Pixel, px, Unit, Billboard using MakieCore: not_implemented_for import MakieCore: plot, plot!, theme, plotfunc, plottype, merge_attributes!, calculated_attributes!, -get_attribute, plotsym, plotkey, attributes, used_attributes + get_attribute, plotsym, plotkey, attributes, used_attributes import MakieCore: arrows, heatmap, image, lines, linesegments, mesh, meshscatter, poly, scatter, surface, text, volume import MakieCore: arrows!, heatmap!, image!, lines!, linesegments!, mesh!, meshscatter!, poly!, scatter!, surface!, text!, volume! import MakieCore: convert_arguments, convert_attribute, default_theme, conversion_trait @@ -241,7 +241,7 @@ export mouseover, onpick, pick, Events, Keyboard, Mouse, mouse_selection, is_mou export ispressed, Exclusively export connect_screen export window_area, window_open, mouse_buttons, mouse_position, mouseposition_px, - scroll, keyboard_buttons, unicode_input, dropped_files, hasfocus, entered_window + scroll, keyboard_buttons, unicode_input, dropped_files, hasfocus, entered_window export disconnect! export DataInspector export Consume @@ -283,19 +283,17 @@ export assetpath function icon() path = assetpath("icons") imgs = FileIO.load.(joinpath.(path, readdir(path))) - icons = map(img-> RGBA{Colors.N0f8}.(img), imgs) - return reinterpret.(NTuple{4,UInt8}, icons) + icons = map(img -> RGBA{Colors.N0f8}.(img), imgs) + return reinterpret.(NTuple{4, UInt8}, icons) end -function logo() - FileIO.load(assetpath("logo.png")) -end +logo() = FileIO.load(assetpath("logo.png")) function __init__() # Make GridLayoutBase default row and colgaps themeable when using Makie # This mutates module-level state so it could mess up other libraries using # GridLayoutBase at the same time as Makie, which is unlikely, though - GridLayoutBase.DEFAULT_COLGAP_GETTER[] = function() + GridLayoutBase.DEFAULT_COLGAP_GETTER[] = function () ct = Makie.current_default_theme() if haskey(ct, :colgap) ct[:colgap][] @@ -303,7 +301,7 @@ function __init__() GridLayoutBase.DEFAULT_COLGAP[] end end - GridLayoutBase.DEFAULT_ROWGAP_GETTER[] = function() + GridLayoutBase.DEFAULT_ROWGAP_GETTER[] = function () ct = Makie.current_default_theme() if haskey(ct, :rowgap) ct[:rowgap][] @@ -316,7 +314,7 @@ function __init__() cfg_path = joinpath(homedir(), ".config", "makie", "theme.jl") if isfile(cfg_path) @warn "The global configuration file is no longer supported." * - "Please include the file manually with `include(\"$cfg_path\")` before plotting." + "Please include the file manually with `include(\"$cfg_path\")` before plotting." end end @@ -331,9 +329,9 @@ include("basic_recipes/text.jl") include("basic_recipes/raincloud.jl") include("deprecated.jl") -export Arrows , Heatmap , Image , Lines , LineSegments , Mesh , MeshScatter , Poly , Scatter , Surface , Text , Volume , Wireframe -export arrows , heatmap , image , lines , linesegments , mesh , meshscatter , poly , scatter , surface , text , volume , wireframe -export arrows! , heatmap! , image! , lines! , linesegments! , mesh! , meshscatter! , poly! , scatter! , surface! , text! , volume! , wireframe! +export Arrows, Heatmap, Image, Lines, LineSegments, Mesh, MeshScatter, Poly, Scatter, Surface, Text, Volume, Wireframe +export arrows, heatmap, image, lines, linesegments, mesh, meshscatter, poly, scatter, surface, text, volume, wireframe +export arrows!, heatmap!, image!, lines!, linesegments!, mesh!, meshscatter!, poly!, scatter!, surface!, text!, volume!, wireframe! export PointLight, EnvironmentLight, AmbientLight, SSAO diff --git a/src/basic_recipes/ablines.jl b/src/basic_recipes/ablines.jl index 5a3f794b54f..c2f7d5cb26b 100644 --- a/src/basic_recipes/ablines.jl +++ b/src/basic_recipes/ablines.jl @@ -11,7 +11,7 @@ All style attributes are the same as for `LineSegments`. xautolimits = false, yautolimits = false, default_theme(LineSegments, scene)..., - cycle = :color, + cycle = :color ) end @@ -19,14 +19,14 @@ function Makie.plot!(p::ABLines) scene = Makie.parent_scene(p) transf = transform_func(scene) - + is_identity_transform(transf) || throw(ArgumentError("ABLines is only defined for the identity transform, not $(typeof(transf)).")) limits = lift(projview_to_2d_limits, scene.camera.projectionview) points = Observable(Point2f[]) - + onany(limits, p[1], p[2]) do lims, intercept, slope inv = inverse_transform(transf) empty!(points[]) @@ -47,6 +47,6 @@ function Makie.plot!(p::ABLines) end function abline!(args...; kwargs...) - Base.depwarn("abline! is deprecated and will be removed in the future. Use ablines / ablines! instead." , :abline!, force = true) + Base.depwarn("abline! is deprecated and will be removed in the future. Use ablines / ablines! instead.", :abline!, force = true) ablines!(args...; kwargs...) end diff --git a/src/basic_recipes/annotations.jl b/src/basic_recipes/annotations.jl index 941614d2301..e27069df11d 100644 --- a/src/basic_recipes/annotations.jl +++ b/src/basic_recipes/annotations.jl @@ -10,13 +10,11 @@ $(ATTRIBUTES) default_theme(scene, Text) end -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)) - end,) -end +convert_arguments(::Type{<:Annotations}, + strings::AbstractVector{<:AbstractString}, + text_positions::AbstractVector{<:Point{N}}) where N = (map(strings, text_positions) do str, pos + (String(str), Point{N, Float32}(pos)) +end,) function plot!(plot::Annotations) # annotations are not necessary anymore with the different text behavior diff --git a/src/basic_recipes/arc.jl b/src/basic_recipes/arc.jl index 8701e7a51bf..38394d68f64 100644 --- a/src/basic_recipes/arc.jl +++ b/src/basic_recipes/arc.jl @@ -17,14 +17,14 @@ $(ATTRIBUTES) @recipe(Arc, origin, radius, start_angle, stop_angle) do scene Attributes(; default_theme(scene, Lines)..., - resolution = 361, + resolution = 361 ) end function plot!(p::Arc) args = getindex.(p, (:origin, :radius, :start_angle, :stop_angle, :resolution)) positions = lift(args...) do origin, radius, start_angle, stop_angle, resolution - map(range(start_angle, stop=stop_angle, length=resolution)) do angle + map(range(start_angle, stop = stop_angle, length = resolution)) do angle origin .+ Point2f((cos(angle), sin(angle)) .* radius) end end diff --git a/src/basic_recipes/arrows.jl b/src/basic_recipes/arrows.jl index 9a7e8ac0952..91c84fecdec 100644 --- a/src/basic_recipes/arrows.jl +++ b/src/basic_recipes/arrows.jl @@ -34,28 +34,26 @@ const quiver! = arrows! export quiver, quiver! arrow_head(N, marker, quality) = marker -function arrow_head(N, marker::Automatic, quality) +arrow_head(N, marker::Automatic, quality) = if N == 2 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, 0.0f0, quality) ]) end -end arrow_tail(N, marker, quality) = marker -function arrow_tail(N, marker::Automatic, quality) +arrow_tail(N, marker::Automatic, quality) = if N == 2 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 function _mantle(origin, extremity, r1, r2, N) @@ -64,7 +62,7 @@ function _mantle(origin, extremity, r1, r2, N) # Equivalent to # xy = cos(atan(temp)) # z = sin(atan(temp)) - temp = -(r2-r1) / norm(extremity .- origin) + temp = -(r2 - r1) / norm(extremity .- origin) xy = 1.0 / sqrt(temp^2 + 1) z = temp / sqrt(temp^2 + 1) @@ -72,43 +70,41 @@ 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) - (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, u, v) = (Point2f.(x, y), Vec2f.(u, v)) +convert_arguments(::Type{<:Arrows}, x::AbstractVector, y::AbstractVector, u::AbstractMatrix, v::AbstractMatrix) = (vec(Point2f.(x, y')), vec(Vec2f.(u, v))) +convert_arguments(::Type{<:Arrows}, x, y, z, u, v, w) = (Point3f.(x, y, z), Vec3f.(u, v, w)) -function plot!(arrowplot::Arrows{<: Tuple{AbstractVector{<: Point{N, T}}, V}}) where {N, T, V} +function plot!(arrowplot::Arrows{<:Tuple{AbstractVector{<:Point{N, T}}, V}}) where {N, T, V} @extract arrowplot ( points, directions, colormap, normalize, align, arrowtail, color, linecolor, linestyle, linewidth, lengthscale, @@ -118,8 +114,8 @@ function plot!(arrowplot::Arrows{<: Tuple{AbstractVector{<: Point{N, T}}, V}}) w fxaa, ssao, transparency, visible, inspectable ) - arrow_c = map((a, c)-> a === automatic ? c : a , arrowcolor, color) - line_c = map((a, c)-> a === automatic ? c : a , linecolor, color) + arrow_c = map((a, c) -> a === automatic ? c : a, arrowcolor, color) + line_c = map((a, c) -> a === automatic ? c : a, linecolor, color) if N == 2 fxaa_bool = @lift($fxaa == automatic ? false : $fxaa) @@ -161,13 +157,13 @@ function plot!(arrowplot::Arrows{<: Tuple{AbstractVector{<: Point{N, T}}, V}}) w linesegments!( arrowplot, headstart, color = line_c, colormap = colormap, linestyle = linestyle, - linewidth = @lift($linewidth === automatic ? 1f0 : $linewidth), + linewidth = @lift($linewidth === automatic ? 1.0f0 : $linewidth), fxaa = fxaa_bool, inspectable = inspectable, transparency = transparency, visible = visible, ) scatter!( arrowplot, - lift(x-> last.(x), headstart), + lift(x -> last.(x), headstart), marker = @lift(arrow_head(2, $arrowhead, $quality)), markersize = @lift($arrowsize === automatic ? theme(scene, :markersize)[] : $arrowsize), color = arrow_c, rotations = rotations, strokewidth = 0.0, diff --git a/src/basic_recipes/axis.jl b/src/basic_recipes/axis.jl index f9744a8efb5..b2f24455542 100644 --- a/src/basic_recipes/axis.jl +++ b/src/basic_recipes/axis.jl @@ -1,20 +1,17 @@ module Formatters - using Showoff - - 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 +using Showoff + +scientific(ticks::AbstractVector) = Showoff.showoff(ticks, :scientific) + +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 @@ -22,10 +19,10 @@ using .Formatters to_3tuple(x) = ntuple(i -> x, Val(3)) -to_3tuple(x::NTuple{3,Any}) = x +to_3tuple(x::NTuple{3, Any}) = x to_2tuple(x) = ntuple(i -> x, Val(2)) -to_2tuple(x::NTuple{2,Any}) = x +to_2tuple(x::NTuple{2, Any}) = x """ $(SIGNATURES) @@ -37,10 +34,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), 1.0f0 * 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 +52,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 -> 1.0f0, Val(3)) + axislinewidth = ntuple(x -> 1.5f0, Val(3)) tsize = 5 # in percent Attributes( visible = true, @@ -75,22 +72,14 @@ $(ATTRIBUTES) align = axisnames_align3d, font = lift(to_3tuple, theme(scene, :font)), gap = 3 - ), - - ticks = Attributes( + ), ticks = Attributes( ranges_labels = (automatic, automatic), - formatter = Formatters.plain, - - textcolor = (tick_color, tick_color, tick_color), - - rotation = tickrotations3d, + formatter = Formatters.plain, textcolor = (tick_color, tick_color, tick_color), rotation = tickrotations3d, fontsize = (tsize, tsize, tsize), align = tickalign3d, gap = 3, font = lift(to_3tuple, theme(scene, :font)), - ), - - frame = Attributes( + ), frame = Attributes( linecolor = (grid_color, grid_color, grid_color), linewidth = (grid_thickness, grid_thickness, grid_thickness), axislinewidth = (axis_linewidth, axis_linewidth, axis_linewidth), @@ -102,38 +91,34 @@ 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::Limits, 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 - ) - scale_func.((filter(t -> lmin <= t <= lmax, ticks))) -end +default_ticks( + lmin::Number, lmax::Number, + ticks::AbstractVector{<:Number}, scale_func::Function +) = scale_func.((filter(t -> lmin <= t <= lmax, ticks))) function default_ticks( - lmin::Number, lmax::Number, ::Automatic, scale_func::Function - ) + lmin::Number, lmax::Number, ::Automatic, scale_func::Function +) # scale the limits scaled_ticks, mini, maxi = optimize_ticks( Float64(scale_func(lmin)), Float64(scale_func(lmax)); k_min = 4, # minimum number of ticks - k_max = 8, # maximum number of ticks + k_max = 8 # maximum number of ticks ) length(scaled_ticks) == 1 && isnan(scaled_ticks[1]) && return [-Inf, Inf] scaled_ticks end function default_ticks( - lmin::Number, lmax::Number, ticks::Integer, scale_func = identity - ) + lmin::Number, lmax::Number, ticks::Integer, scale_func = identity +) scaled_ticks, mini, maxi = optimize_ticks( Float64(scale_func(lmin)), Float64(scale_func(lmax)); @@ -142,35 +127,27 @@ function default_ticks( k_ideal = ticks, # `strict_span = false` rewards cases where the span of the # chosen ticks is not too much bigger than amin - amax: - strict_span = false, + strict_span = false ) scaled_ticks end -function default_ticks(x::Automatic, limits::Tuple, n) - default_ticks(limits, n, identity) -end +default_ticks(x::Automatic, limits::Tuple, n) = default_ticks(limits, n, identity) -function default_ticks(ticks::Tuple, limits::Tuple, n::Tuple) - default_ticks.(ticks, (limits,), n) -end +default_ticks(ticks::Tuple, limits::Tuple, n::Tuple) = default_ticks.(ticks, (limits,), n) default_ticks(ticks::Tuple, limits::Limits, n) = default_ticks.(ticks, limits, (n,)) 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 - default_labels.(x, formatter) -end +default_labels(x::NTuple{N, Any}, formatter::Function) where N = default_labels.(x, formatter) -function default_labels(x::AbstractVector, y::AbstractVector, formatter::Function = Formatters.plain) - default_labels.((x, y), formatter) -end +default_labels(x::AbstractVector, y::AbstractVector, formatter::Function = Formatters.plain) = default_labels.((x, y), formatter) -function default_labels(ticks::AbstractVector, formatter::Function = Formatters.plain) +default_labels(ticks::AbstractVector, formatter::Function = Formatters.plain) = if applicable(formatter, ticks) return formatter(ticks) # takes the whole array elseif applicable(formatter, first(ticks)) @@ -178,15 +155,14 @@ function default_labels(ticks::AbstractVector, formatter::Function = Formatters. else error("Formatting function $(formatter) is neither applicable to $(typeof(ticks)) nor $(eltype(ticks)).") end -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 +170,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 @@ -214,13 +190,13 @@ function labelposition(ranges, dim, dir, tgap, origin::StaticVector{N}) where N 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) = 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,9 +215,9 @@ 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) @@ -252,7 +228,7 @@ function draw_axis3d(textbuffer, linebuffer, scale, limits, ranges_labels, fonts 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 @@ -299,7 +275,7 @@ 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) range = ranges[j] @@ -312,12 +288,13 @@ function draw_axis3d(textbuffer, linebuffer, scale, limits, ranges_labels, fonts end end end - finish!(textbuffer); finish!(linebuffer) + finish!(textbuffer) + finish!(linebuffer) end return end -function plot!(scene::SceneLike, ::Type{<: Axis3D}, attributes::Attributes, args...) +function plot!(scene::SceneLike, ::Type{<:Axis3D}, attributes::Attributes, args...) axis = Axis3D(scene, attributes, args) # Disable any non linear transform for the axis plot! axis.transformation.transform_func[] = identity @@ -343,6 +320,4 @@ function plot!(scene::SceneLike, ::Type{<: Axis3D}, attributes::Attributes, args return axis end -function axis3d!(scene::Scene, lims = data_limits(scene, p -> isaxis(p) || not_in_data_space(p)); kw...) - axis3d!(scene, Attributes(), lims; ticks = (ranges = automatic, labels = automatic), kw...) -end +axis3d!(scene::Scene, lims = data_limits(scene, p -> isaxis(p) || not_in_data_space(p)); kw...) = axis3d!(scene, Attributes(), lims; ticks = (ranges = automatic, labels = automatic), kw...) diff --git a/src/basic_recipes/band.jl b/src/basic_recipes/band.jl index a14219218f4..03c1eeace0a 100644 --- a/src/basic_recipes/band.jl +++ b/src/basic_recipes/band.jl @@ -11,17 +11,17 @@ $(ATTRIBUTES) @recipe(Band, lowerpoints, upperpoints) do scene attr = Attributes(; default_theme(scene, Mesh)..., - colorrange = automatic, + colorrange = automatic ) attr[:shading][] = false attr end -convert_arguments(::Type{<: Band}, x, ylower, yupper) = (Point2f.(x, ylower), Point2f.(x, yupper)) +convert_arguments(::Type{<:Band}, x, ylower, yupper) = (Point2f.(x, ylower), Point2f.(x, yupper)) function band_connect(n) - ns = 1:n-1 - ns2 = n+1:2n-1 + ns = 1:(n - 1) + ns2 = (n + 1):(2n - 1) [GLTriangleFace.(ns, ns .+ 1, ns2); GLTriangleFace.(ns .+ 1, ns2 .+ 1, ns2)] end @@ -40,7 +40,7 @@ function Makie.plot!(plot::Band) # side to make an even band if length(c) == length(lowerpoints[]) return repeat(to_color(c), 2)::RGBColors - # if there's one color for each band vertex, the colors are used directly + # if there's one color for each band vertex, the colors are used directly elseif length(c) == 2 * length(lowerpoints[]) return to_color(c)::RGBColors else @@ -56,15 +56,9 @@ function Makie.plot!(plot::Band) mesh!(plot, attr, coordinates, connectivity) end -function fill_view(x, y1, y2, where::Nothing) - x, y1, y2 -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}}) - view(x, bools), view(y1, bools), view(y2, bools) -end +fill_view(x, y1, y2, where::Nothing) = x, y1, y2 +fill_view(x, y1, y2, where::Function) = fill_view(x, y1, y2, where.(x, y1, y2)) +fill_view(x, y1, y2, bools::AbstractVector{<:Union{Integer, Bool}}) = view(x, bools), view(y1, bools), view(y2, bools) """ fill_between!(scenelike, x, y1, y2; where = nothing, kw_args...) diff --git a/src/basic_recipes/barplot.jl b/src/basic_recipes/barplot.jl index 44517db2eae..0e90a03711c 100644 --- a/src/basic_recipes/barplot.jl +++ b/src/basic_recipes/barplot.jl @@ -1,6 +1,4 @@ -function bar_label_formatter(value::Number) - return string(round(value; digits=3)) -end +bar_label_formatter(value::Number) = string(round(value; digits = 3)) """ barplot(x, y; kwargs...) @@ -34,9 +32,7 @@ $(ATTRIBUTES) direction = :y, visible = theme(scene, :visible), inspectable = theme(scene, :inspectable), - cycle = [:color => :patchcolor], - - bar_labels = nothing, + cycle = [:color => :patchcolor], bar_labels = nothing, flip_labels_at = Inf, label_rotation = 0π, label_color = theme(scene, :textcolor), @@ -50,14 +46,14 @@ $(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... ymin = min(fillto, y) ymax = max(fillto, y) w = abs(width) - rect = Rectf(x - (w / 2f0), ymin, w, ymax - ymin) + rect = Rectf(x - (w / 2.0f0), ymin, w, ymax - ymin) return in_y_direction ? rect : flip(rect) end @@ -71,7 +67,7 @@ function compute_x_and_width(x, width, gap, dodge, n_dodge, dodge_gap) elseif eltype(dodge) <: Integer i_dodge = dodge else - ArgumentError("The keyword argument `dodge` currently supports only `AbstractVector{<: Integer}`") |> throw + throw(ArgumentError("The keyword argument `dodge` currently supports only `AbstractVector{<: Integer}`")) end n_dodge === automatic && (n_dodge = maximum(i_dodge)) dodge_width = scale_width(dodge_gap, n_dodge) @@ -81,13 +77,11 @@ end scale_width(dodge_gap, n_dodge) = (1 - (n_dodge - 1) * dodge_gap) / n_dodge -function shift_dodge(i, dodge_width, dodge_gap) - (dodge_width - 1) / 2 + (i - 1) * (dodge_width + dodge_gap) -end +shift_dodge(i, dodge_width, dodge_gap) = (dodge_width - 1) / 2 + (i - 1) * (dodge_width + dodge_gap) function stack_from_to_sorted(y) to = cumsum(y) - from = [0.0; to[firstindex(to):end-1]] + from = [0.0; to[firstindex(to):(end - 1)]] (from = from, to = to) end @@ -108,7 +102,7 @@ end function stack_grouped_from_to(i_stack, y, grp) from = Array{Float64}(undef, length(y)) - to = Array{Float64}(undef, length(y)) + to = Array{Float64}(undef, length(y)) groupby = StructArray((; grp..., is_pos = y .> 0)) @@ -133,15 +127,14 @@ function text_attributes(values, in_y_direction, flip_labels_at, color_over_back swap(x, y) = in_y_direction ? (x, y) : (y, x) geti(x::AbstractArray, i) = x[i] geti(x, i) = x - function flip(k) + 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)") end - end for (i, k) in enumerate(values) # Plot text inside bar @@ -191,10 +184,10 @@ function Makie.plot!(p::BarPlot) label_offsets = Observable(Vec2f[]) label_colors = Observable(RGBAf[]) function calculate_bars(xy, fillto, offset, width, dodge, n_dodge, gap, dodge_gap, stack, - dir, bar_labels, flip_labels_at, label_color, color_over_background, - color_over_bar, label_formatter, label_offset) + dir, bar_labels, flip_labels_at, label_color, color_over_background, + color_over_bar, label_formatter, label_offset) - in_y_direction = get((y=true, x=false), dir) do + in_y_direction = get((y = true, x = false), dir) do error("Invalid direction $dir. Options are :x and :y.") end @@ -230,7 +223,7 @@ function Makie.plot!(p::BarPlot) from, to = stack_grouped_from_to(i_stack, y, (x = x̂,)) y, fillto = to, from else - ArgumentError("The keyword argument `stack` currently supports only `AbstractVector{<: Integer}`") |> throw + throw(ArgumentError("The keyword argument `stack` currently supports only `AbstractVector{<: Integer}`")) end # -------------------------------- @@ -241,8 +234,8 @@ function Makie.plot!(p::BarPlot) oback = color_over_background === automatic ? label_color : color_over_background obar = color_over_bar === automatic ? label_color : color_over_bar label_args = barplot_labels(x̂, y, bar_labels, in_y_direction, - flip_labels_at, to_color(oback), to_color(obar), - label_formatter, label_offset) + flip_labels_at, to_color(oback), to_color(obar), + label_formatter, label_offset) labels[], label_aligns[], label_offsets[], label_colors[] = label_args end @@ -250,8 +243,8 @@ function Makie.plot!(p::BarPlot) end bars = lift(calculate_bars, p[1], p.fillto, p.offset, p.width, p.dodge, p.n_dodge, p.gap, - p.dodge_gap, p.stack, p.direction, p.bar_labels, p.flip_labels_at, - p.label_color, p.color_over_background, p.color_over_bar, p.label_formatter, p.label_offset) + p.dodge_gap, p.stack, p.direction, p.bar_labels, p.flip_labels_at, + p.label_color, p.color_over_background, p.color_over_bar, p.label_formatter, p.label_offset) poly!( p, bars, color = p.color, colormap = p.colormap, colorrange = p.colorrange, @@ -260,6 +253,6 @@ function Makie.plot!(p::BarPlot) highclip = p.highclip, lowclip = p.lowclip, nan_color = p.nan_color, ) if !isnothing(p.bar_labels[]) - text!(p, labels; align=label_aligns, offset=label_offsets, color=label_colors, font=p.label_font, fontsize=p.label_size, rotation=p.label_rotation) + text!(p, labels; align = label_aligns, offset = label_offsets, color = label_colors, font = p.label_font, fontsize = p.label_size, rotation = p.label_rotation) end end diff --git a/src/basic_recipes/buffers.jl b/src/basic_recipes/buffers.jl index 823ddbcae32..88f623c3e29 100644 --- a/src/basic_recipes/buffers.jl +++ b/src/basic_recipes/buffers.jl @@ -3,16 +3,14 @@ Buffers are just normal plots, with the benefit of being setup correctly to efficiently append + push new values to them =# -function LinesegmentBuffer( - scene::SceneLike, ::Type{Point{N}} = Point{2}; - color = RGBAf[], linewidth = Float32[], - kw_args... - ) where N - linesegments!( - scene, Point{N, Float32}[]; color = color, - linewidth = linewidth, kw_args... - ) -end +LinesegmentBuffer( + scene::SceneLike, ::Type{Point{N}} = Point{2}; + color = RGBAf[], linewidth = Float32[], + kw_args... +) where N = linesegments!( + scene, Point{N, Float32}[]; color = color, + linewidth = linewidth, kw_args... +) function append!(lsb::LineSegments, positions::Vector{Point{N, Float32}}; color = :black, linewidth = 1.0) where N thickv = same_length_array(positions, linewidth, key"linewidth"()) @@ -23,9 +21,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 - append!(tb, [positions]; kw_args...) -end +push!(tb::LineSegments, positions::Point{N, Float32}; kw_args...) where N = append!(tb, [positions]; kw_args...) function start!(lsb::LineSegments) resize!(lsb[1][], 0) @@ -42,25 +38,23 @@ function finish!(lsb::LineSegments) return 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 - annotations!( - scene, String[" "], [Point{N, Float32}(0)]; - rotation = rotation, - color = color, - fontsize = fontsize, - font = font, - align = align, - kw_args... - ) -end +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 = annotations!( + scene, String[" "], [Point{N, Float32}(0)]; + rotation = rotation, + color = color, + fontsize = fontsize, + font = font, + align = align, + kw_args... +) function start!(tb::Annotations) for key in (1, :color, :rotation, :fontsize, :font, :align) @@ -82,9 +76,7 @@ function finish!(tb::Annotations) end -function push!(tb::Annotations, text::String, position::VecTypes{N}; kw_args...) where N - append!(tb, [(String(text), Point{N, Float32}(position))]; kw_args...) -end +push!(tb::Annotations, text::String, position::VecTypes{N}; kw_args...) where N = append!(tb, [(String(text), Point{N, Float32}(position))]; kw_args...) function append!(tb::Annotations, text::Vector{String}, positions::Vector{Point{N, Float32}}; kw_args...) where N text_positions = convert_argument(Annotations, text, positions)[1] diff --git a/src/basic_recipes/contourf.jl b/src/basic_recipes/contourf.jl index 2d8699d64a8..b557f36e8ea 100644 --- a/src/basic_recipes/contourf.jl +++ b/src/basic_recipes/contourf.jl @@ -47,9 +47,7 @@ end # _computed_extendlow # _computed_extendhigh -function _get_isoband_levels(levels::Int, mi, ma) - edges = Float32.(LinRange(mi, ma, levels+1)) -end +_get_isoband_levels(levels::Int, mi, ma) = edges = Float32.(LinRange(mi, ma, levels + 1)) function _get_isoband_levels(levels::AbstractVector{<:Real}, mi, ma) edges = Float32.(levels) @@ -59,9 +57,7 @@ end conversion_trait(::Type{<:Contourf}) = ContinuousSurface() -function _get_isoband_levels(::Val{:normal}, levels, values) - _get_isoband_levels(levels, extrema_nan(values)...) -end +_get_isoband_levels(::Val{:normal}, levels, values) = _get_isoband_levels(levels, extrema_nan(values)...) function _get_isoband_levels(::Val{:relative}, levels::AbstractVector, values) mi, ma = extrema_nan(values) @@ -80,7 +76,7 @@ function Makie.plot!(c::Contourf{<:Tuple{<:AbstractVector{<:Real}, <:AbstractVec minimum(levels), maximum(levels) end computed_colormap = lift(compute_contourf_colormap, c._computed_levels, c.colormap, c.extendlow, - c.extendhigh) + c.extendhigh) c.attributes[:_computed_colormap] = computed_colormap lowcolor = Observable{RGBAf}() @@ -106,7 +102,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 diff --git a/src/basic_recipes/contours.jl b/src/basic_recipes/contours.jl index 5094b86eaf7..ddcba48afa8 100644 --- a/src/basic_recipes/contours.jl +++ b/src/basic_recipes/contours.jl @@ -45,7 +45,7 @@ $(ATTRIBUTES) default_theme(scene, Contour) end -function contourlines(::Type{<: Contour}, contours, cols) +function contourlines(::Type{<:Contour}, contours, cols) result = Point2f[] colors = RGBA{Float32}[] for (color, c) in zip(cols, Contours.levels(contours)) @@ -58,7 +58,7 @@ function contourlines(::Type{<: Contour}, contours, cols) result, colors end -function contourlines(::Type{<: Contour3d}, contours, cols) +function contourlines(::Type{<:Contour3d}, contours, cols) result = Point3f[] colors = RGBA{Float32}[] for (color, c) in zip(cols, Contours.levels(contours)) @@ -73,7 +73,7 @@ function contourlines(::Type{<: Contour3d}, contours, cols) result, colors end -to_levels(x::AbstractVector{<: Number}, cnorm) = x +to_levels(x::AbstractVector{<:Number}, cnorm) = x function to_levels(n::Integer, cnorm) zmin, zmax = cnorm @@ -81,12 +81,12 @@ function to_levels(n::Integer, cnorm) range(zmin + dz; step = dz, length = n) end -conversion_trait(::Type{<: Contour3d}) = ContinuousSurface() -conversion_trait(::Type{<: Contour}) = ContinuousSurface() -conversion_trait(::Type{<: Contour{<: Tuple{X, Y, Z, Vol}}}) where {X, Y, Z, Vol} = VolumeLike() -conversion_trait(::Type{<: Contour{<: Tuple{<: AbstractArray{T, 3}}}}) where T = VolumeLike() +conversion_trait(::Type{<:Contour3d}) = ContinuousSurface() +conversion_trait(::Type{<:Contour}) = ContinuousSurface() +conversion_trait(::Type{<:Contour{<:Tuple{X, Y, Z, Vol}}}) where {X, Y, Z, Vol} = VolumeLike() +conversion_trait(::Type{<:Contour{<:Tuple{<:AbstractArray{T, 3}}}}) where T = VolumeLike() -function plot!(plot::Contour{<: Tuple{X, Y, Z, Vol}}) where {X, Y, Z, Vol} +function plot!(plot::Contour{<:Tuple{X, Y, Z, Vol}}) where {X, Y, Z, Vol} x, y, z, volume = plot[1:4] @extract plot (colormap, levels, linewidth, alpha) valuerange = lift(nan_extrema, volume) @@ -107,7 +107,7 @@ function plot!(plot::Contour{<: Tuple{X, Y, Z, Vol}}) where {X, Y, Z, Vol} v_interval = cliprange[1] .. cliprange[2] # resample colormap and make the empty area between iso surfaces transparent return map(1:N) do i - i01 = (i-1) / (N - 1) + i01 = (i - 1) / (N - 1) c = Makie.interpolated_getindex(cmap, i01) isoval = vrange[1] + (i01 * (vrange[2] - vrange[1])) line = reduce(levels, init = false) do v0, level @@ -126,19 +126,13 @@ function plot!(plot::Contour{<: Tuple{X, Y, Z, Vol}}) where {X, Y, Z, Vol} volume!(plot, attr, x, y, z, volume) end -function color_per_level(color, colormap, colorrange, alpha, levels) - color_per_level(to_color(color), colormap, colorrange, alpha, levels) -end +color_per_level(color, colormap, colorrange, alpha, levels) = color_per_level(to_color(color), colormap, colorrange, alpha, levels) -function color_per_level(color::Colorant, colormap, colorrange, alpha, levels) - fill(color, length(levels)) -end +color_per_level(color::Colorant, colormap, colorrange, alpha, levels) = fill(color, length(levels)) -function color_per_level(colors::AbstractVector, colormap, colorrange, alpha, levels) - color_per_level(to_colormap(colors), colormap, colorrange, alpha, levels) -end +color_per_level(colors::AbstractVector, colormap, colorrange, alpha, levels) = color_per_level(to_colormap(colors), colormap, colorrange, alpha, levels) -function color_per_level(colors::AbstractVector{<: Colorant}, colormap, colorrange, alpha, levels) +color_per_level(colors::AbstractVector{<:Colorant}, colormap, colorrange, alpha, levels) = if length(levels) == length(colors) return colors else @@ -147,7 +141,6 @@ function color_per_level(colors::AbstractVector{<: Colorant}, colormap, colorran have the same length as `levels`. Found $(length(colors)) colors, but $(length(levels)) levels") end -end function color_per_level(::Nothing, colormap, colorrange, a, levels) cmap = to_colormap(colormap) @@ -161,7 +154,7 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} x, y, z = plot[1:3] zrange = lift(nan_extrema, z) levels = lift(plot.levels, zrange) do levels, zrange - if levels isa AbstractVector{<: Number} + if levels isa AbstractVector{<:Number} return levels elseif levels isa Integer to_levels(levels, zrange) @@ -170,15 +163,15 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} end end - replace_automatic!(()-> zrange, plot, :colorrange) + replace_automatic!(() -> zrange, plot, :colorrange) args = @extract plot (color, colormap, colorrange, alpha) level_colors = lift(color_per_level, args..., levels) result = lift(x, y, z, levels, level_colors) do x, y, z, levels, level_colors t = eltype(z) # Compute contours - xv, yv = to_vector(x, size(z,1), t), to_vector(y, size(z,2), t) - contours = Contours.contours(xv, yv, z, convert(Vector{eltype(z)}, levels)) + xv, yv = to_vector(x, size(z, 1), t), to_vector(y, size(z, 2), t) + contours = Contours.contours(xv, yv, z, convert(Vector{eltype(z)}, levels)) contourlines(T, contours, level_colors) end lines!( @@ -192,9 +185,9 @@ function plot!(plot::T) where T <: Union{Contour, Contour3d} plot end -function point_iterator(x::Contour{<: Tuple{X, Y, Z}}) where {X, Y, Z} +function point_iterator(x::Contour{<:Tuple{X, Y, Z}}) where {X, Y, Z} axes = (x[1], x[2]) - extremata = map(extrema∘to_value, axes) + extremata = map(extrema ∘ to_value, axes) minpoint = Point2f(first.(extremata)...) widths = last.(extremata) .- first.(extremata) rect = Rect2f(minpoint, Vec2f(widths)) diff --git a/src/basic_recipes/convenience_functions.jl b/src/basic_recipes/convenience_functions.jl index b9086b27cbd..365393e6f25 100644 --- a/src/basic_recipes/convenience_functions.jl +++ b/src/basic_recipes/convenience_functions.jl @@ -1,6 +1,6 @@ -function Makie.plot!(plot::Plot(AbstractVector{<: Complex})) +function Makie.plot!(plot::Plot(AbstractVector{<:Complex})) plot[:axis, :labels] = ("Re(x)", "Im(x)") - lines!(plot, lift(im-> Point2f.(real.(im), imag.(im)), x[1])) + lines!(plot, lift(im -> Point2f.(real.(im), imag.(im)), x[1])) end @@ -33,13 +33,13 @@ Plots the given colour gradients arranged as horizontal colourbars. If you change the offsets or the font size, you may need to change the resolution. """ function showgradients( - cgrads::AbstractVector{Symbol}; - h = 0.0, - offset = 0.4, - fontsize = 0.7, - resolution = (800, length(cgrads) * 84), - monospace = true - )::Scene + cgrads::AbstractVector{Symbol}; + h = 0.0, + offset = 0.4, + fontsize = 0.7, + resolution = (800, length(cgrads) * 84), + monospace = true +)::Scene scene = Scene(resolution = resolution) @@ -50,7 +50,7 @@ function showgradients( scene, range(0, stop = 10, length = length(c)), range(0, stop = 1, length = length(c)), - reshape(c, (length(c),1)) + reshape(c, (length(c), 1)) )[end] cmapstr = monospace ? UnicodeFun.to_latex("\\mono{$cmap}") : string(cmap, ":") diff --git a/src/basic_recipes/error_and_rangebars.jl b/src/basic_recipes/error_and_rangebars.jl index 69a35f65e4a..ac405fb08c3 100644 --- a/src/basic_recipes/error_and_rangebars.jl +++ b/src/basic_recipes/error_and_rangebars.jl @@ -144,8 +144,8 @@ function Makie.plot!(plot::Errorbars{T}) where T <: Tuple{AbstractVector{<:VecTy map(x_y_low_high) do (x, y, l, h) in_y ? - (Point2f(x, y - l), Point2f(x, y + h)) : - (Point2f(x - l, y), Point2f(x + h, y)) + (Point2f(x, y - l), Point2f(x, y + h)) : + (Point2f(x - l, y), Point2f(x + h, y)) end end @@ -171,8 +171,8 @@ function Makie.plot!(plot::Rangebars{T}) where T <: Tuple{AbstractVector{<:VecTy map(vlh) do (v, l, h) in_y ? - (Point2f(v, l), Point2f(v, h)) : - (Point2f(l, v), Point2f(h, v)) + (Point2f(v, l), Point2f(v, h)) : + (Point2f(l, v), Point2f(h, v)) end end @@ -197,8 +197,8 @@ function _plot_bars!(plot, linesegpairs, is_in_y_direction) screenendpoints = scene_to_screen(endpoints, scene) screenendpoints_shifted_pairs = map(screenendpoints) do sep - (sep .+ f_if(is_in_y_direction[], reverse, Point(0, -whiskerwidth/2)), - sep .+ f_if(is_in_y_direction[], reverse, Point(0, whiskerwidth/2))) + (sep .+ f_if(is_in_y_direction[], reverse, Point(0, -whiskerwidth / 2)), + sep .+ f_if(is_in_y_direction[], reverse, Point(0, whiskerwidth / 2))) end screen_to_scene([p for pair in screenendpoints_shifted_pairs for p in pair], scene) @@ -266,6 +266,4 @@ end # ignore whiskers when determining data limits -function data_limits(bars::Union{Errorbars, Rangebars}) - data_limits(bars.plots[1]) -end +data_limits(bars::Union{Errorbars, Rangebars}) = data_limits(bars.plots[1]) diff --git a/src/basic_recipes/hvlines.jl b/src/basic_recipes/hvlines.jl index 7df939bfedb..ef8bb4b2ee1 100644 --- a/src/basic_recipes/hvlines.jl +++ b/src/basic_recipes/hvlines.jl @@ -14,7 +14,7 @@ All style attributes are the same as for `LineSegments`. xmin = 0, xmax = 1, default_theme(scene, LineSegments)..., - cycle = :color, + cycle = :color ) end @@ -34,7 +34,7 @@ All style attributes are the same as for `LineSegments`. ymin = 0, ymax = 1, default_theme(scene, LineSegments)..., - cycle = :color, + cycle = :color ) end diff --git a/src/basic_recipes/hvspan.jl b/src/basic_recipes/hvspan.jl index 18ac06bdae4..436abf82aac 100644 --- a/src/basic_recipes/hvspan.jl +++ b/src/basic_recipes/hvspan.jl @@ -14,9 +14,9 @@ All style attributes are the same as for `Poly`. xmin = 0, xmax = 1, default_theme(Poly, scene)..., - cycle = [:color => :patchcolor], + cycle = [:color => :patchcolor] ) - end +end """ vspan(xs_low, xs_high; ymin = 0.0, ymax = 1.0, attrs...) @@ -34,7 +34,7 @@ All style attributes are the same as for `Poly`. ymin = 0, ymax = 1, default_theme(Poly, scene)..., - cycle = [:color => :patchcolor], + cycle = [:color => :patchcolor] ) end @@ -48,7 +48,7 @@ function Makie.plot!(p::Union{HSpan, VSpan}) mi = p isa HSpan ? p.xmin : p.ymin ma = p isa HSpan ? p.xmax : p.ymax - + onany(limits, p[1], p[2], mi, ma, transf) do lims, lows, highs, mi, ma, transf inv = inverse_transform(transf) empty!(rects[]) diff --git a/src/basic_recipes/pie.jl b/src/basic_recipes/pie.jl index 206bf6ae633..c0764b4fb27 100644 --- a/src/basic_recipes/pie.jl +++ b/src/basic_recipes/pie.jl @@ -39,7 +39,7 @@ function plot!(plot::Pie) end # create vector of a vector of points for each piece - vertex_arrays = map(boundaries[1:end-1], boundaries[2:end]) do sta, en + vertex_arrays = map(boundaries[1:(end - 1)], boundaries[2:end]) do sta, en distance = en - sta # how many vertices are needed for the curve? nvertices = max(2, ceil(Int, rad2deg(distance) * vertex_per_deg)) @@ -66,9 +66,9 @@ function plot!(plot::Pie) # plot pieces as polys poly!( - plot, polys, - color = plot.color, strokewidth = plot.strokewidth, - strokecolor = plot.strokecolor, inspectable = plot.inspectable, + plot, polys, + color = plot.color, strokewidth = plot.strokewidth, + strokecolor = plot.strokecolor, inspectable = plot.inspectable, visible = plot.visible, transparency = plot.transparency ) diff --git a/src/basic_recipes/poly.jl b/src/basic_recipes/poly.jl index e8d4a7ee57a..eacad05394c 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}} -convert_arguments(::Type{<: Poly}, v::AbstractVector{<: PolyElements}) = (v,) -convert_arguments(::Type{<: Poly}, v::Union{Polygon, MultiPolygon}) = (v,) +convert_arguments(::Type{<:Poly}, v::AbstractVector{<:PolyElements}) = (v,) +convert_arguments(::Type{<:Poly}, v::Union{Polygon, MultiPolygon}) = (v,) -convert_arguments(::Type{<: Poly}, args...) = ([convert_arguments(Scatter, args...)[1]],) -convert_arguments(::Type{<: Poly}, vertices::AbstractArray, indices::AbstractArray) = convert_arguments(Mesh, vertices, indices) -convert_arguments(::Type{<: Poly}, m::GeometryBasics.Mesh) = (m,) -convert_arguments(::Type{<: Poly}, m::GeometryBasics.GeometryPrimitive) = (m,) +convert_arguments(::Type{<:Poly}, args...) = ([convert_arguments(Scatter, args...)[1]],) +convert_arguments(::Type{<:Poly}, vertices::AbstractArray, indices::AbstractArray) = convert_arguments(Mesh, vertices, indices) +convert_arguments(::Type{<:Poly}, m::GeometryBasics.Mesh) = (m,) +convert_arguments(::Type{<:Poly}, m::GeometryBasics.GeometryPrimitive) = (m,) -function plot!(plot::Poly{<: Tuple{Union{GeometryBasics.Mesh, GeometryPrimitive}}}) +function plot!(plot::Poly{<:Tuple{Union{GeometryBasics.Mesh, GeometryPrimitive}}}) mesh!( plot, lift(triangle_mesh, plot[1]), color = plot[:color], @@ -39,25 +39,20 @@ function poly_convert(geometries) end poly_convert(meshes::AbstractVector{<:AbstractMesh}) = meshes poly_convert(polys::AbstractVector{<:Polygon}) = triangle_mesh.(polys) -function poly_convert(multipolygons::AbstractVector{<:MultiPolygon}) - return [merge(triangle_mesh.(multipoly.polygons)) for multipoly in multipolygons] -end +poly_convert(multipolygons::AbstractVector{<:MultiPolygon}) = [merge(triangle_mesh.(multipoly.polygons)) for multipoly in multipolygons] poly_convert(mesh::GeometryBasics.Mesh) = mesh poly_convert(polygon::Polygon) = triangle_mesh(polygon) -function poly_convert(polygon::AbstractVector{<: VecTypes}) - return poly_convert([convert_arguments(Scatter, polygon)[1]]) -end +poly_convert(polygon::AbstractVector{<:VecTypes}) = poly_convert([convert_arguments(Scatter, polygon)[1]]) -function poly_convert(polygons::AbstractVector{<: AbstractVector{<: VecTypes}}) - return map(polygons) do poly +poly_convert(polygons::AbstractVector{<:AbstractVector{<:VecTypes}}) = + map(polygons) do poly point2f = convert(Vector{Point2f}, poly) faces = GeometryBasics.earcut_triangulate([point2f]) return GeometryBasics.Mesh(point2f, faces) end -end to_line_segments(polygon) = convert_arguments(LineSegments, polygon)[1] # Need to explicitly overload for Mesh, since otherwise, Mesh will dispatch to AbstractVector @@ -77,13 +72,13 @@ function to_line_segments(meshes::AbstractVector) return line end -function to_line_segments(polygon::AbstractVector{<: VecTypes}) +function to_line_segments(polygon::AbstractVector{<:VecTypes}) result = Point2f.(polygon) push!(result, polygon[1]) return result end -function plot!(plot::Poly{<: Tuple{<: Union{Polygon, AbstractVector{<: PolyElements}}}}) +function plot!(plot::Poly{<:Tuple{<:Union{Polygon, AbstractVector{<:PolyElements}}}}) geometries = plot[1] meshes = lift(poly_convert, geometries) mesh!(plot, meshes; @@ -121,11 +116,11 @@ function plot!(plot::Poly{<: Tuple{<: Union{Polygon, AbstractVector{<: PolyEleme color = stroke, linestyle = plot.linestyle, linewidth = plot.strokewidth, space = plot.space, overdraw = plot.overdraw, transparency = plot.transparency, - inspectable = plot.inspectable, depth_shift = -1f-5 + inspectable = plot.inspectable, depth_shift = -1.0f-5 ) end -function plot!(plot::Mesh{<: Tuple{<: AbstractVector{P}}}) where P <: Union{AbstractMesh, Polygon} +function plot!(plot::Mesh{<:Tuple{<:AbstractVector{P}}}) where P <: Union{AbstractMesh, Polygon} meshes = plot[1] color_node = plot.color attributes = Attributes( @@ -139,7 +134,7 @@ function plot!(plot::Mesh{<: Tuple{<: AbstractVector{P}}}) where P <: Union{Abst colorrange = get(plot, :colorrange, automatic) ) - num_meshes = lift(meshes; ignore_equal_values=true) do meshes + num_meshes = lift(meshes; ignore_equal_values = true) do meshes return Int[length(coordinates(m)) for m in meshes] end diff --git a/src/basic_recipes/raincloud.jl b/src/basic_recipes/raincloud.jl index 4c5fe446e74..d9de439e77d 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) @@ -164,7 +156,7 @@ 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)) + 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/series.jl b/src/basic_recipes/series.jl index c7bf498cb42..0ac82206e96 100644 --- a/src/basic_recipes/series.jl +++ b/src/basic_recipes/series.jl @@ -22,46 +22,34 @@ Curves can be: """ @recipe(Series, curves) do scene Attributes( - linewidth=2, - color=:lighttest, - solid_color=nothing, - labels=nothing, - - marker=nothing, - markersize=nothing, - markercolor=automatic, - strokecolor=nothing, - strokewidth=nothing, + linewidth = 2, + color = :lighttest, + solid_color = nothing, + labels = nothing, marker = nothing, + markersize = nothing, + markercolor = automatic, + strokecolor = nothing, + strokewidth = nothing, ) end replace_missing(x) = ismissing(x) ? NaN : x -function convert_arguments(T::Type{<: Series}, y::AbstractMatrix) - convert_arguments(T, 1:size(y, 2), y) -end +convert_arguments(T::Type{<:Series}, y::AbstractMatrix) = convert_arguments(T, 1:size(y, 2), y) -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 +convert_arguments(::Type{<:Series}, x::AbstractVector, ys::AbstractMatrix) = (map(1:size(ys, 1)) do i + Point2f.(replace_missing.(x), replace_missing.(view(ys, i, :))) +end,) -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 +convert_arguments(::Type{<:Series}, arg::AbstractVector{<:Tuple{X, Y}}) where {X, Y} = (map(arg) do (x, y) + Point2f.(replace_missing.(x), replace_missing.(y)) +end,) -function convert_arguments(T::Type{<: Series}, arg::Tuple{<:AbstractVector, <:AbstractVector}) - return convert_arguments(T, [arg]) -end +convert_arguments(T::Type{<:Series}, arg::Tuple{<:AbstractVector, <:AbstractVector}) = convert_arguments(T, [arg]) -function convert_arguments(::Type{<: Series}, arg::AbstractVector{<: AbstractVector{<:Point2}}) - return (map(arg) do points - Point2f.(replace_missing.(first.(points)), replace_missing.(last.(points))) - end,) -end +convert_arguments(::Type{<:Series}, arg::AbstractVector{<:AbstractVector{<:Point2}}) = (map(arg) do points + Point2f.(replace_missing.(first.(points)), replace_missing.(last.(points))) +end,) function plot!(plot::Series) @extract plot (curves, labels, linewidth, color, solid_color) @@ -84,14 +72,12 @@ function plot!(plot::Series) mcolor = plot.markercolor markercolor = @lift $mcolor == automatic ? $series_color : $mcolor scatterlines!(plot, positions; - linewidth=linewidth, color=series_color, markercolor=series_color, - label=label[], scatter...) + linewidth = linewidth, color = series_color, markercolor = series_color, + label = label[], scatter...) else - lines!(plot, positions; linewidth=linewidth, color=series_color, label=label) + lines!(plot, positions; linewidth = linewidth, color = series_color, label = label) end end end -function Makie.get_plots(plot::Series) - return plot.plots -end +Makie.get_plots(plot::Series) = plot.plots diff --git a/src/basic_recipes/spy.jl b/src/basic_recipes/spy.jl index 2b3a0469722..4c80fe30cf9 100644 --- a/src/basic_recipes/spy.jl +++ b/src/basic_recipes/spy.jl @@ -26,14 +26,10 @@ $(ATTRIBUTES) ) end -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) - (x, y, z) -end +convert_arguments(::Type{<:Spy}, x::SparseArrays.AbstractSparseArray) = (0 .. size(x, 1), 0 .. size(x, 2), x) +convert_arguments(::Type{<:Spy}, x, y, z::SparseArrays.AbstractSparseArray) = (x, y, z) -function calculated_attributes!(::Type{<: Spy}, plot) +function calculated_attributes!(::Type{<:Spy}, plot) end function plot!(p::Spy) @@ -57,7 +53,7 @@ function plot!(p::Spy) x, y, color = SparseArrays.findnz(z) points = map(x, y) do x, y (((Point2f(x, y) .- 1) ./ Point2f(size(z) .- 1)) .* - widths(rect) .+ minimum(rect)) + widths(rect) .+ minimum(rect)) end points, convert(Vector{Float32}, color) end @@ -80,5 +76,5 @@ function plot!(p::Spy) ) lines!(p, rect, color = p.framecolor, linewidth = p.framesize, inspectable = p.inspectable, - visible = p.visible) + visible = p.visible) end diff --git a/src/basic_recipes/stairs.jl b/src/basic_recipes/stairs.jl index 10e7f27dec6..aa57f4d7605 100644 --- a/src/basic_recipes/stairs.jl +++ b/src/basic_recipes/stairs.jl @@ -29,7 +29,7 @@ function plot!(p::Stairs{<:Tuple{<:AbstractVector{<:Point2}}}) if step == :pre s_points = Vector{Point2f}(undef, length(points) * 2 - 1) s_points[1] = point = points[1] - for i in 1:length(points)-1 + for i in 1:(length(points) - 1) nextpoint = points[i + 1] s_points[2i] = Point2f(point[1], nextpoint[2]) s_points[2i + 1] = nextpoint @@ -39,8 +39,8 @@ function plot!(p::Stairs{<:Tuple{<:AbstractVector{<:Point2}}}) elseif step == :post s_points = Vector{Point2f}(undef, length(points) * 2 - 1) s_points[1] = point = points[1] - for i in 1:length(points)-1 - nextpoint = points[i+1] + for i in 1:(length(points) - 1) + nextpoint = points[i + 1] s_points[2i] = Point2f(nextpoint[1], point[2]) s_points[2i + 1] = nextpoint point = nextpoint @@ -49,8 +49,8 @@ function plot!(p::Stairs{<:Tuple{<:AbstractVector{<:Point2}}}) elseif step == :center s_points = Vector{Point2f}(undef, length(points) * 2) s_points[1] = point = points[1] - for i in 1:length(points)-1 - nextpoint = points[i+1] + for i in 1:(length(points) - 1) + nextpoint = points[i + 1] halfx = (point[1] + nextpoint[1]) / 2 s_points[2i] = Point2f(halfx, point[2]) s_points[2i + 1] = Point2f(halfx, nextpoint[2]) @@ -66,4 +66,3 @@ function plot!(p::Stairs{<:Tuple{<:AbstractVector{<:Point2}}}) lines!(p, steppoints; [x for x in pairs(p.attributes) if x[1] != :step]...) p end - diff --git a/src/basic_recipes/streamplot.jl b/src/basic_recipes/streamplot.jl index 63e12505192..9f5d47b1f74 100644 --- a/src/basic_recipes/streamplot.jl +++ b/src/basic_recipes/streamplot.jl @@ -33,13 +33,13 @@ See the function `Makie.streamplot_impl` for implementation details. ) end -function convert_arguments(::Type{<: StreamPlot}, f::Function, xrange, yrange) +function convert_arguments(::Type{<:StreamPlot}, f::Function, xrange, yrange) xmin, xmax = extrema(xrange) ymin, ymax = extrema(yrange) return (f, Rect(xmin, ymin, xmax - xmin, ymax - ymin)) end -function convert_arguments(::Type{<: StreamPlot}, f::Function, xrange, yrange, zrange) +function convert_arguments(::Type{<:StreamPlot}, f::Function, xrange, yrange, zrange) xmin, xmax = extrema(xrange) ymin, ymax = extrema(yrange) zmin, zmax = extrema(zrange) @@ -48,9 +48,7 @@ function convert_arguments(::Type{<: StreamPlot}, f::Function, xrange, yrange, z return (f, Rect(mini, maxi .- mini)) end -function convert_arguments(::Type{<: StreamPlot}, f::Function, limits::Rect) - return (f, limits) -end +convert_arguments(::Type{<:StreamPlot}, f::Function, limits::Rect) = (f, limits) scatterfun(N) = N == 2 ? scatter! : meshscatter! @@ -73,7 +71,7 @@ Links: [Quasirandom sequences](http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/) """ -function streamplot_impl(CallType, f, limits::Rect{N, T}, resolutionND, stepsize, maxsteps=500, dens=1.0) where {N, T} +function streamplot_impl(CallType, f, limits::Rect{N, T}, resolutionND, stepsize, maxsteps = 500, dens = 1.0) where {N, T} resolution = to_ndim(Vec{N, Int}, resolutionND, last(resolutionND)) mask = trues(resolution...) # unvisited squares arrow_pos = Point{N, Float32}[] @@ -86,20 +84,21 @@ function streamplot_impl(CallType, f, limits::Rect{N, T}, resolutionND, stepsize r = ntuple(N) do i LinRange(mini[i], maxi[i], resolution[i] + 1) end - apply_f(x0, P) = if P <: Point - f(x0) - else - f(x0...) - end + apply_f(x0, P) = + if P <: Point + f(x0) + else + f(x0...) + end # see http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/ ϕ = (MathConstants.φ, 1.324717957244746, 1.2207440846057596)[N] - acoeff = ϕ.^(-(1:N)) + acoeff = ϕ .^ (-(1:N)) n_points = 0 # count visited squares ind = 0 # index of low discrepancy sequence - while n_points < prod(resolution)*min(one(dens), dens) # fill up to 100*dens% of mask + while n_points < prod(resolution) * min(one(dens), dens) # fill up to 100*dens% of mask # next index from low discrepancy sequence c = CartesianIndex(ntuple(N) do i - j = ceil(Int, ((0.5 + acoeff[i]*ind) % 1)*resolution[i]) + j = ceil(Int, ((0.5 + acoeff[i] * ind) % 1) * resolution[i]) clamp(j, 1, size(mask, i)) end) ind += 1 @@ -169,7 +168,7 @@ function plot!(p::StreamPlot) end lines!( p, - lift(x->x[3], data), color = lift(last, data), colormap = p.colormap, colorrange = p.colorrange, + lift(x -> x[3], data), color = lift(last, data), colormap = p.colormap, colorrange = p.colorrange, linestyle = p.linestyle, linewidth = p.linewidth, inspectable = p.inspectable, @@ -204,7 +203,7 @@ function plot!(p::StreamPlot) p, lift(first, data), markersize = p.arrow_size, marker = @lift(arrow_head(N, $(p.arrow_head), $(p.quality))), - color = lift(x-> x[4], data), rotations = rotations, + color = lift(x -> x[4], data), rotations = rotations, colormap = p.colormap, colorrange = p.colorrange, inspectable = p.inspectable, transparency = p.transparency ) diff --git a/src/basic_recipes/text.jl b/src/basic_recipes/text.jl index b22f31c674d..dc367790d5a 100644 --- a/src/basic_recipes/text.jl +++ b/src/basic_recipes/text.jl @@ -6,11 +6,11 @@ function plot!(plot::Text) linewidths = Observable(Float32[]) linecolors = Observable(RGBAf[]) lineindices = Ref(Int[]) - + onany(plot.text, plot.fontsize, plot.font, plot.fonts, plot.align, - plot.rotation, plot.justification, plot.lineheight, plot.color, - plot.strokecolor, plot.strokewidth, plot.word_wrap_width) do str, - ts, f, fs, al, rot, jus, lh, col, scol, swi, www + plot.rotation, plot.justification, plot.lineheight, plot.color, + plot.strokecolor, plot.strokewidth, plot.word_wrap_width) do str, + ts, f, fs, al, rot, jus, lh, col, scol, swi, www ts = to_fontsize(ts) f = to_font(fs, f) rot = to_rotation(rot) @@ -35,7 +35,7 @@ function plot!(plot::Text) # If we have a Vector of strings, Vector arguments are interpreted # as per string. broadcast_foreach( - func, + func, str, 1:attr_broadcast_length(str), ts, f, fs, al, rot, jus, lh, col, scol, swi, www ) else @@ -54,8 +54,8 @@ function plot!(plot::Text) sc = parent_scene(plot) - onany(linesegs, positions, sc.camera.projectionview, sc.px_area, - transform_func_obs(sc), get(plot, :space, :data)) do segs, pos, _, _, transf, space + onany(linesegs, positions, sc.camera.projectionview, sc.px_area, + transform_func_obs(sc), get(plot, :space, :data)) do segs, pos, _, _, transf, space pos_transf = scene_to_screen(apply_transform(transf, pos, space), sc) linesegs_shifted[] = map(segs, lineindices[]) do seg, index seg + attr_broadcast_getindex(pos_transf, index) @@ -86,7 +86,7 @@ function _get_glyphcollection_and_linesegments(str::AbstractString, index, ts, f end function _get_glyphcollection_and_linesegments(latexstring::LaTeXString, index, ts, f, fs, al, rot, jus, lh, col, scol, swi, www) tex_elements, glyphcollections, offset = texelems_and_glyph_collection(latexstring, ts, - al[1], al[2], rot, col, scol, swi, www) + al[1], al[2], rot, col, scol, swi, www) linesegs = Point2f[] linewidths = Float32[] @@ -119,11 +119,11 @@ function plot!(plot::Text{<:Tuple{<:AbstractString}}) end # conversion stopper for previous methods -convert_arguments(::Type{<: Text}, gcs::AbstractVector{<:GlyphCollection}) = (gcs,) -convert_arguments(::Type{<: Text}, gc::GlyphCollection) = (gc,) -convert_arguments(::Type{<: Text}, vec::AbstractVector{<:Tuple{<:AbstractString, <:Point}}) = (vec,) -convert_arguments(::Type{<: Text}, strings::AbstractVector{<:AbstractString}) = (strings,) -convert_arguments(::Type{<: Text}, string::AbstractString) = (string,) +convert_arguments(::Type{<:Text}, gcs::AbstractVector{<:GlyphCollection}) = (gcs,) +convert_arguments(::Type{<:Text}, gc::GlyphCollection) = (gc,) +convert_arguments(::Type{<:Text}, vec::AbstractVector{<:Tuple{<:AbstractString, <:Point}}) = (vec,) +convert_arguments(::Type{<:Text}, strings::AbstractVector{<:AbstractString}) = (strings,) +convert_arguments(::Type{<:Text}, string::AbstractString) = (string,) # TODO: is this necessary? there seems to be a recursive loop with the above # function without these two interceptions, but I didn't need it before merging @@ -137,13 +137,13 @@ function plot!(plot::Text{<:Tuple{<:AbstractArray{<:AbstractString}}}) end # overload text plotting for a vector of tuples of a string and a point each -function plot!(plot::Text{<:Tuple{<:AbstractArray{<:Tuple{<:AbstractString, <:Point}}}}) +function plot!(plot::Text{<:Tuple{<:AbstractArray{<:Tuple{<:AbstractString, <:Point}}}}) strings_and_positions = plot[1] strings = Observable{Vector{AbstractString}}(first.(strings_and_positions[])) positions = Observable( - Point3f[to_ndim(Point3f, last(x), 0) for x in strings_and_positions[]] # avoid Any for zero elements + Point3f[to_ndim(Point3f, last(x), 0) for x in strings_and_positions[]] # avoid Any for zero elements ) attrs = plot.attributes @@ -165,7 +165,7 @@ function plot!(plot::Text{<:Tuple{<:AbstractArray{<:Tuple{<:AbstractString, <:Po end function texelems_and_glyph_collection(str::LaTeXString, fontscale_px, halign, valign, - rotation, color, strokecolor, strokewidth, word_wrap_width) + rotation, color, strokecolor, strokewidth, word_wrap_width) rot = convert_attribute(rotation, key"rotation"()) @@ -195,7 +195,7 @@ function texelems_and_glyph_collection(str::LaTeXString, fontscale_px, halign, v if word_wrap_width > 0 last_space_idx = 0 last_newline_idx = 1 - newline_offset = Point3f(basepositions[1][1], 0f0, 0) + newline_offset = Point3f(basepositions[1][1], 0.0f0, 0) for i in eachindex(texchars) basepositions[i] -= newline_offset @@ -204,12 +204,12 @@ function texelems_and_glyph_collection(str::LaTeXString, fontscale_px, halign, v if last_space_idx != 0 && right_pos > word_wrap_width section_offset = basepositions[last_space_idx + 1][1] lineheight = maximum((height(bb) for bb in bboxes[last_newline_idx:last_space_idx])) - last_newline_idx = last_space_idx+1 + last_newline_idx = last_space_idx + 1 newline_offset += Point3f(section_offset, lineheight, 0) # TODO: newlines don't really need to represented at all? # chars[last_space_idx] = '\n' - for j in last_space_idx+1:i + for j in (last_space_idx + 1):i basepositions[j] -= Point3f(section_offset, lineheight, 0) end end @@ -265,10 +265,10 @@ iswhitespace(l::LaTeXString) = iswhitespace(replace(l.s, '$' => "")) struct RichText <: AbstractString type::Symbol - children::Vector{Union{RichText,String}} + children::Vector{Union{RichText, String}} attributes::Dict{Symbol, Any} function RichText(type::Symbol, children...; kwargs...) - cs = Union{RichText,String}[children...] + cs = Union{RichText, String}[children...] typeof(cs) new(type, cs, Dict(kwargs)) end @@ -284,13 +284,9 @@ end Base.ncodeunits(r::RichText) = ncodeunits(String(r)) # needed for isempty -function Base.show(io::IO, ::MIME"text/plain", r::RichText) - print(io, "RichText: \"$(String(r))\"") -end +Base.show(io::IO, ::MIME"text/plain", r::RichText) = print(io, "RichText: \"$(String(r))\"") -function Base.:(==)(r1::RichText, r2::RichText) - r1.type == r2.type && r1.children == r2.children && r1.attributes == r2.attributes -end +Base.:(==)(r1::RichText, r2::RichText) = r1.type == r2.type && r1.children == r2.children && r1.attributes == r2.attributes rich(args...; kwargs...) = RichText(:span, args...; kwargs...) subscript(args...; kwargs...) = RichText(:sub, args...; kwargs...) @@ -323,19 +319,17 @@ struct GlyphInfo strokewidth::Float32 end -function GlyphCollection(v::Vector{GlyphInfo}) - GlyphCollection( - [i.glyph for i in v], - [i.font for i in v], - [Point3f(i.origin..., 0) for i in v], - [i.extent for i in v], - [i.size for i in v], - [i.rotation for i in v], - [i.color for i in v], - [i.strokecolor for i in v], - [i.strokewidth for i in v], - ) -end +GlyphCollection(v::Vector{GlyphInfo}) = GlyphCollection( + [i.glyph for i in v], + [i.font for i in v], + [Point3f(i.origin..., 0) for i in v], + [i.extent for i in v], + [i.size for i in v], + [i.rotation for i in v], + [i.color for i in v], + [i.strokecolor for i in v], + [i.strokewidth for i in v], +) function layout_text(rt::RichText, ts, f, fset, al, rot, jus, lh, col) @@ -345,7 +339,7 @@ function layout_text(rt::RichText, ts, f, fset, al, rot, jus, lh, col) stack = [GlyphState(0, 0, Vec2f(ts), _f, to_color(col))] lines = [GlyphInfo[]] - + process_rt_node!(stack, lines, rt, fset) apply_lineheight!(lines, lh) @@ -363,7 +357,7 @@ function apply_lineheight!(lines, lh) for (i, line) in enumerate(lines) for j in eachindex(line) l = line[j] - l = Setfield.@set l.origin[2] -= (i-1) * 20 # TODO: Lineheight + l = Setfield.@set l.origin[2] -= (i - 1) * 20 # TODO: Lineheight line[j] = l end end @@ -372,7 +366,7 @@ end function apply_alignment_and_justification!(lines, ju, al) max_xs = map(lines) do line - maximum(line, init = 0f0) do ginfo + maximum(line, init = 0.0f0) do ginfo ginfo.origin[1] + ginfo.extent.hadvance * ginfo.size[1] end end @@ -388,11 +382,11 @@ function apply_alignment_and_justification!(lines, ju, al) al_offset_x = if al[1] == :center max_x / 2 elseif al[1] == :left - 0f0 + 0.0f0 elseif al[1] == :right max_x else - 0f0 + 0.0f0 end al_offset_y = if al[2] == :center @@ -402,11 +396,11 @@ function apply_alignment_and_justification!(lines, ju, al) elseif al[2] == :top top_y else - 0f0 + 0.0f0 end fju = float_justification(ju, al) - + for (i, line) in enumerate(lines) ju_offset = fju * (max_x - max_xs[i]) for j in eachindex(line) @@ -477,7 +471,7 @@ function process_rt_node!(stack, lines, s::String, _) to_rotation(0), gs.color, RGBAf(0, 0, 0, 0), - 0f0, + 0.0f0, )) x = x + gext.hadvance * gs.size[1] end @@ -486,9 +480,7 @@ function process_rt_node!(stack, lines, s::String, _) return end -function new_glyphstate(gs::GlyphState, rt::RichText, val::Val, fonts) - gs -end +new_glyphstate(gs::GlyphState, rt::RichText, val::Val, fonts) = gs _get_color(attributes, default)::RGBAf = haskey(attributes, :color) ? to_color(attributes[:color]) : default _get_font(attributes, default::NativeFont, fonts)::NativeFont = haskey(attributes, :font) ? to_font(fonts, attributes[:font]) : default diff --git a/src/basic_recipes/tooltip.jl b/src/basic_recipes/tooltip.jl index 01b88fbe9fd..336f2b2d437 100644 --- a/src/basic_recipes/tooltip.jl +++ b/src/basic_recipes/tooltip.jl @@ -37,15 +37,15 @@ Creates a tooltip pointing at `position` displaying the given `string` @recipe(Tooltip, position) do scene Attributes(; # General - text = "", + text = "", offset = 10, placement = :above, align = 0.5, - xautolimits = false, - yautolimits = false, + xautolimits = false, + yautolimits = false, zautolimits = false, overdraw = false, - depth_shift = 0f0, + depth_shift = 0.0f0, transparency = false, visible = true, inspectable = false, @@ -62,18 +62,18 @@ Creates a tooltip pointing at `position` displaying the given `string` # Background backgroundcolor = :white, triangle_size = 10, - + # Outline outline_color = :black, - outline_linewidth = 2f0, - outline_linestyle = nothing, + outline_linewidth = 2.0f0, + outline_linestyle = nothing ) end -convert_arguments(::Type{<: Tooltip}, x::Real, y::Real, str::AbstractString) = (Point2f(x, y), str) -convert_arguments(::Type{<: Tooltip}, x::Real, y::Real) = (Point2f(x, y),) +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] + plot.attributes[:text] = plot[2] tooltip!(plot, plot[1]; plot.attributes...) plot end @@ -103,14 +103,14 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) text_offset = map(p.offset, textpadding, p.triangle_size, p.placement, p.align) do o, pad, ts, placement, align l, r, b, t = pad - if placement == :left + if placement == :left return Vec2f(-o - r - ts, b - align * (b + t)) elseif placement == :right - return Vec2f( o + l + ts, b - align * (b + t)) + return Vec2f(o + l + ts, b - align * (b + t)) elseif placement in (:below, :down, :bottom) return Vec2f(l - align * (l + r), -o - t - ts) elseif placement in (:above, :up, :top) - return Vec2f(l - align * (l + r), o + b + ts) + return Vec2f(l - align * (l + r), o + b + ts) else @error "Tooltip placement $placement invalid. Assuming :above" return Vec2f(0, o + b + ts) @@ -118,7 +118,7 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) end text_align = map(p.placement, p.align) do placement, align - if placement == :left + if placement == :left return (1.0, align) elseif placement == :right return (0.0, align) @@ -145,11 +145,11 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) # TODO react to glyphcollection instead bbox = map( - px_pos, p.text, text_align, text_offset, textpadding, p.align - ) do p, s, _, o, pad, align + px_pos, p.text, text_align, text_offset, textpadding, p.align + ) do p, s, _, o, pad, align bb = Rect2f(boundingbox(tp)) + o l, r, b, t = pad - return Rect2f(origin(bb) .- (l, b), widths(bb) .+ (l+r, b+t)) + return Rect2f(origin(bb) .- (l, b), widths(bb) .+ (l + r, b + t)) end # Text background mesh @@ -157,7 +157,7 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) mesh!( p, bbox, shading = false, space = :pixel, color = p.backgroundcolor, fxaa = false, - transparency = p.transparency, visible = p.visible, + transparency = p.transparency, visible = p.visible, overdraw = p.overdraw, depth_shift = p.depth_shift, inspectable = p.inspectable ) @@ -166,36 +166,37 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) triangle = GeometryBasics.Mesh( Point2f[(-0.5, 0), (0.5, 0), (0, -1)], - GLTriangleFace[(1,2,3)] + GLTriangleFace[(1, 2, 3)] ) mp = mesh!( p, triangle, shading = false, space = :pixel, - color = p.backgroundcolor, + color = p.backgroundcolor, transparency = p.transparency, visible = p.visible, overdraw = p.overdraw, depth_shift = p.depth_shift, inspectable = p.inspectable ) onany(bbox, p.triangle_size, p.placement, p.align) do bb, s, placement, align - o = origin(bb); w = widths(bb) + o = origin(bb) + w = widths(bb) scale!(mp, s, s, s) - - if placement == :left + + if placement == :left translate!(mp, Vec3f(o[1] + w[1], o[2] + align * w[2], 0)) - rotate!(mp, qrotation(Vec3f(0,0,1), 0.5pi)) + rotate!(mp, qrotation(Vec3f(0, 0, 1), 0.5pi)) elseif placement == :right translate!(mp, Vec3f(o[1], o[2] + align * w[2], 0)) - rotate!(mp, qrotation(Vec3f(0,0,1), -0.5pi)) + rotate!(mp, qrotation(Vec3f(0, 0, 1), -0.5pi)) elseif placement in (:below, :down, :bottom) translate!(mp, Vec3f(o[1] + align * w[1], o[2] + w[2], 0)) - rotate!(mp, Quaternionf(0,0,1,0)) # pi + rotate!(mp, Quaternionf(0, 0, 1, 0)) # pi elseif placement in (:above, :up, :top) translate!(mp, Vec3f(o[1] + align * w[1], o[2], 0)) - rotate!(mp, Quaternionf(0,0,0,1)) # 0 + rotate!(mp, Quaternionf(0, 0, 0, 1)) # 0 else @error "Tooltip placement $placement invalid. Assuming :above" translate!(mp, Vec3f(o[1] + align * w[1], o[2], 0)) - rotate!(mp, Quaternionf(0,0,0,1)) + rotate!(mp, Quaternionf(0, 0, 0, 1)) end return end @@ -203,7 +204,8 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) # Outline outline = map(bbox, p.triangle_size, p.placement, p.align) do bb, s, placement, align - l, b = origin(bb); w, h = widths(bb) + l, b = origin(bb) + w, h = widths(bb) r, t = (l, b) .+ (w, h) # We start/end at half width/height here to avoid corners like this: @@ -212,45 +214,45 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) # | ____ # | | - shift = if placement == :left + shift = if placement == :left Vec2f[ - (l, b + 0.5h), (l, t), (r, t), - (r, b + align * h + 0.5s), - (r + s, b + align * h), - (r, b + align * h - 0.5s), + (l, b + 0.5h), (l, t), (r, t), + (r, b + align * h + 0.5s), + (r + s, b + align * h), + (r, b + align * h - 0.5s), (r, b), (l, b), (l, b + 0.5h) ] elseif placement == :right Vec2f[ - (l + 0.5w, b), (l, b), - (l, b + align * h - 0.5s), - (l-s, b + align * h), - (l, b + align * h + 0.5s), + (l + 0.5w, b), (l, b), + (l, b + align * h - 0.5s), + (l - s, b + align * h), + (l, b + align * h + 0.5s), (l, t), (r, t), (r, b), (l + 0.5w, b) ] elseif placement in (:below, :down, :bottom) Vec2f[ - (l, b + 0.5h), (l, t), - (l + align * w - 0.5s, t), - (l + align * w, t+s), - (l + align * w + 0.5s, t), + (l, b + 0.5h), (l, t), + (l + align * w - 0.5s, t), + (l + align * w, t + s), + (l + align * w + 0.5s, t), (r, t), (r, b), (l, b), (l, b + 0.5h) ] elseif placement in (:above, :up, :top) Vec2f[ - (l, b + 0.5h), (l, t), (r, t), (r, b), - (l + align * w + 0.5s, b), - (l + align * w, b-s), - (l + align * w - 0.5s, b), + (l, b + 0.5h), (l, t), (r, t), (r, b), + (l + align * w + 0.5s, b), + (l + align * w, b - s), + (l + align * w - 0.5s, b), (l, b), (l, b + 0.5h) ] else @error "Tooltip placement $placement invalid. Assuming :above" Vec2f[ - (l, b + 0.5h), (l, t), (r, t), (r, b), - (l + align * w + 0.5s, b), - (l + align * w, b-s), - (l + align * w - 0.5s, b), + (l, b + 0.5h), (l, t), (r, t), (r, b), + (l + align * w + 0.5s, b), + (l + align * w, b - s), + (l + align * w - 0.5s, b), (l, b), (l, b + 0.5h) ] end @@ -259,8 +261,8 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) end lines!( - p, outline, - color = p.outline_color, space = :pixel, + p, outline, + color = p.outline_color, space = :pixel, linewidth = p.outline_linewidth, linestyle = p.outline_linestyle, transparency = p.transparency, visible = p.visible, overdraw = p.overdraw, depth_shift = p.depth_shift, @@ -270,4 +272,4 @@ function plot!(p::Tooltip{<:Tuple{<:VecTypes}}) notify(p[1]) return p -end \ No newline at end of file +end diff --git a/src/basic_recipes/tricontourf.jl b/src/basic_recipes/tricontourf.jl index deef1fc3e49..e53737c6b88 100644 --- a/src/basic_recipes/tricontourf.jl +++ b/src/basic_recipes/tricontourf.jl @@ -45,9 +45,7 @@ $(ATTRIBUTES) ) end -function Makie.convert_arguments(::Type{<:Tricontourf}, x::AbstractVector{<:Real}, y::AbstractVector{<:Real}, z::AbstractVector{<:Real}) - map(x -> elconvert(Float32, x), (x, y, z)) -end +Makie.convert_arguments(::Type{<:Tricontourf}, x::AbstractVector{<:Real}, y::AbstractVector{<:Real}, z::AbstractVector{<:Real}) = map(x -> elconvert(Float32, x), (x, y, z)) function compute_contourf_colormap(levels, cmap, elow, ehigh) levels_scaled = (levels .- minimum(levels)) ./ (maximum(levels) - minimum(levels)) @@ -56,21 +54,21 @@ 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 -function compute_lowcolor(el, cmap) +compute_lowcolor(el, cmap) = if isnothing(el) return RGBAf(0, 0, 0, 0) elseif el === automatic || el == :auto @@ -78,9 +76,8 @@ function compute_lowcolor(el, cmap) else return to_color(el)::RGBAf end -end -function compute_highcolor(eh, cmap) +compute_highcolor(eh, cmap) = if isnothing(eh) return RGBAf(0, 0, 0, 0) elseif eh === automatic || eh == :auto @@ -88,9 +85,8 @@ function compute_highcolor(eh, cmap) else return to_color(eh)::RGBAf end -end -function Makie.plot!(c::Tricontourf{<:Tuple{<:AbstractVector{<:Real},<:AbstractVector{<:Real},<:AbstractVector{<:Real}}}) +function Makie.plot!(c::Tricontourf{<:Tuple{<:AbstractVector{<:Real}, <:AbstractVector{<:Real}, <:AbstractVector{<:Real}}}) xs, ys, zs = c[1:3] c.attributes[:_computed_levels] = lift(zs, c.levels, c.mode) do zs, levels, mode @@ -101,7 +97,7 @@ function Makie.plot!(c::Tricontourf{<:Tuple{<:AbstractVector{<:Real},<:AbstractV minimum(levels), maximum(levels) end computed_colormap = lift(compute_contourf_colormap, c._computed_levels, c.colormap, c.extendlow, - c.extendhigh) + c.extendhigh) c.attributes[:_computed_colormap] = computed_colormap lowcolor = Observable{RGBAf}() @@ -130,7 +126,7 @@ function Makie.plot!(c::Tricontourf{<:Tuple{<:AbstractVector{<:Real},<:AbstractV @assert issorted(levels) is_extended_low && pushfirst!(levels, -Inf) is_extended_high && push!(levels, Inf) - lows = levels[1:end-1] + lows = levels[1:(end - 1)] highs = levels[2:end] trianglelist = compute_triangulation(triangulation, xs, ys) @@ -145,7 +141,7 @@ function Makie.plot!(c::Tricontourf{<:Tuple{<:AbstractVector{<:Real},<:AbstractV if isempty(pointvecs) continue end - + for pointvec in pointvecs p = Makie.Polygon(pointvec) push!(polys[], p) @@ -199,9 +195,9 @@ function filled_tricontours(m::TriplotBase.TriMesh, z, levels) @assert issorted(levels) nlevels = length(levels) filled_contours = TriplotBase.FilledContour{eltype(levels)}[] - for i=1:nlevels-1 + for i in 1:(nlevels - 1) lower = levels[i] - upper = levels[i+1] + upper = levels[i + 1] push!(filled_contours, TriplotBase.generate_filled_contours(m, z, lower, upper)) end filled_contours diff --git a/src/basic_recipes/volumeslices.jl b/src/basic_recipes/volumeslices.jl index a43598099b5..c88ffc6d923 100644 --- a/src/basic_recipes/volumeslices.jl +++ b/src/basic_recipes/volumeslices.jl @@ -33,11 +33,11 @@ function plot!(plot::VolumeSlices) mx, Mx = extrema(x) my, My = extrema(y) mz, Mz = extrema(z) - Rect3(mx, my, mz, Mx-mx, My-my, Mz-mz) + Rect3(mx, my, mz, Mx - mx, My - my, Mz - mz) end axes = :x, :y, :z - for (ax, p, r, (X, Y)) ∈ zip(axes, (:yz, :xz, :xy), (x, y, z), ((y, z), (x, z), (x, y))) + for (ax, p, r, (X, Y)) in zip(axes, (:yz, :xz, :xy), (x, y, z), ((y, z), (x, z), (x, y))) plot[Symbol(:heatmap_, p)] = hmap = heatmap!( plot, attr, X, Y, zeros(length(X[]), length(Y[])) ) diff --git a/src/basic_recipes/waterfall.jl b/src/basic_recipes/waterfall.jl index 04667aba03a..c8943427bb9 100644 --- a/src/basic_recipes/waterfall.jl +++ b/src/basic_recipes/waterfall.jl @@ -12,21 +12,21 @@ Furthermore the same attributes as for `barplot` are supported. """ @recipe(Waterfall, x, y) do scene return Attributes(; - dodge=automatic, - n_dodge=automatic, - gap=0.2, - dodge_gap=0.03, - width=automatic, - cycle=[:color => :patchcolor], - stack=automatic, - show_direction=false, - marker_pos=:utriangle, - marker_neg=:dtriangle, - direction_color=theme(scene, :backgroundcolor), - show_final=false, - final_color=plot_color(:grey90, 0.5), - final_gap=automatic, - final_dodge_gap=0, + dodge = automatic, + n_dodge = automatic, + gap = 0.2, + dodge_gap = 0.03, + width = automatic, + cycle = [:color => :patchcolor], + stack = automatic, + show_direction = false, + marker_pos = :utriangle, + marker_neg = :dtriangle, + direction_color = theme(scene, :backgroundcolor), + show_final = false, + final_color = plot_color(:grey90, 0.5), + final_gap = automatic, + final_dodge_gap = 0 ) end @@ -43,14 +43,14 @@ function Makie.plot!(p::Waterfall) xy = similar(xy) fillto = similar(x) final = similar(xy) - groupby = StructArray(; grp=i_group) + groupby = StructArray(; grp = i_group) for (grp, inds) in StructArrays.finduniquesorted(groupby) fromto = stack_from_to_final(i_stack[inds], y[inds]) fillto[inds] .= fromto.from xy[inds] .= Point2f.(x[inds], fromto.to) final[inds] .= Point2f.(x[inds], fromto.final) end - return (xy=xy, fillto=fillto, final=final) + return (xy = xy, fillto = fillto, final = final) end fromto = lift(stack_bars, p[1], p.dodge, p.stack) @@ -60,10 +60,10 @@ function Makie.plot!(p::Waterfall) barplot!( p, lift(x -> x.final, fromto); - dodge=p.dodge, - color=p.final_color, - dodge_gap=p.final_dodge_gap, - gap=final_gap, + dodge = p.dodge, + color = p.final_color, + dodge_gap = p.final_dodge_gap, + gap = final_gap ) end @@ -71,8 +71,8 @@ function Makie.plot!(p::Waterfall) p, lift(x -> x.xy, fromto); p.attributes..., - fillto=lift(x -> x.fillto, fromto), - stack=automatic, + fillto = lift(x -> x.fillto, fromto), + stack = automatic ) if p.show_direction[] @@ -99,7 +99,7 @@ function Makie.plot!(p::Waterfall) shapes[i] = marker_neg end end - return (xy=xy, shapes=shapes) + return (xy = xy, shapes = shapes) end markers = lift( @@ -117,8 +117,8 @@ function Makie.plot!(p::Waterfall) scatter!( p, lift(x -> x.xy, markers); - marker=lift(x -> x.shapes, markers), - color=p.direction_color) + marker = lift(x -> x.shapes, markers), + color = p.direction_color) end return p @@ -129,5 +129,5 @@ function stack_from_to_final(i_stack, y) perm = sortperm(i_stack) # sort by i_stack inv_perm = sortperm(order[perm]) # restore original order from, to = stack_from_to_sorted(view(y, perm)) - return (from=view(from, inv_perm), to=view(to, inv_perm), final=last(to)) + return (from = view(from, inv_perm), to = view(to, inv_perm), final = last(to)) end diff --git a/src/basic_recipes/wireframe.jl b/src/basic_recipes/wireframe.jl index 374a2f4464c..f50236007ad 100644 --- a/src/basic_recipes/wireframe.jl +++ b/src/basic_recipes/wireframe.jl @@ -15,18 +15,16 @@ See [`wireframe`](@ref). """ wireframe! -function convert_arguments(::Type{<: Wireframe}, x::AbstractVector, y::AbstractVector, z::AbstractMatrix) - (ngrid(x, y)..., z) -end +convert_arguments(::Type{<:Wireframe}, x::AbstractVector, y::AbstractVector, z::AbstractMatrix) = (ngrid(x, y)..., z) xvector(x::AbstractVector, len) = x -xvector(x::ClosedInterval, len) = range(minimum(x), stop=maximum(x), length=len) +xvector(x::ClosedInterval, len) = range(minimum(x), stop = maximum(x), length = len) xvector(x::AbstractMatrix, len) = x yvector(x, len) = xvector(x, len)' yvector(x::AbstractMatrix, len) = x -function plot!(plot::Wireframe{<: Tuple{<: Any, <: Any, <: AbstractMatrix}}) +function plot!(plot::Wireframe{<:Tuple{<:Any, <:Any, <:AbstractMatrix}}) points_faces = lift(plot[1:3]...) do x, y, z M, N = size(z) points = vec(Point3f.(xvector(x, M), yvector(y, N), z)) diff --git a/src/bezier.jl b/src/bezier.jl index 924f0d675bc..5ef90e53acb 100644 --- a/src/bezier.jl +++ b/src/bezier.jl @@ -85,7 +85,7 @@ function scale(e::EllipticalArc, v::VecTypes{2}) elseif x < 0 && y > 0 pi - e.angle, -e.a1, -e.a2 else - pi - e.angle, pi-e.a1, pi-e.a2 + pi - e.angle, pi - e.a1, pi - e.a2 end EllipticalArc(e.c .* v, e.r1 * abs(x), e.r2 * abs(y), ang, a1, a2) end @@ -96,7 +96,7 @@ rotate(c::ClosePath, a) = c rotate(l::LineTo, a) = LineTo(rotmatrix2d(a) * l.p) function rotate(c::CurveTo, a) m = rotmatrix2d(a) - CurveTo(m * c.c1, m * c.c2, m *c.p) + CurveTo(m * c.c1, m * c.c2, m * c.p) end function rotate(e::EllipticalArc, a) m = rotmatrix2d(a) @@ -124,9 +124,7 @@ function fit_to_bbox(b::BezierPath, bb_target::Rect2; keep_aspect = true) bb_t = translate(scale(translate(b, -center_path), scale_factor_aspect), center_target) end -function fit_to_unit_square(b::BezierPath, keep_aspect = true) - fit_to_bbox(b, Rect2((0.0, 0.0), (1.0, 1.0)), keep_aspect = keep_aspect) -end +fit_to_unit_square(b::BezierPath, keep_aspect = true) = fit_to_bbox(b, Rect2((0.0, 0.0), (1.0, 1.0)), keep_aspect = keep_aspect) Base.:+(pc::EllipticalArc, p::Point2) = EllipticalArc(pc.c + p, pc.r1, pc.r2, pc.angle, pc.a1, pc.a2) Base.:+(pc::ClosePath, p::Point2) = pc @@ -148,9 +146,9 @@ const BezierUTriangle = let h = 0.97 # sqrt(aspect) * sqrt(2) w = 0.97 # 1/sqrt(aspect) * sqrt(2) # r = Float32(sqrt(1 / (3 * sqrt(3) / 4))) - p1 = Point(0, h/2) - p2 = Point2(-w/2, -h/2) - p3 = Point2(w/2, -h/2) + p1 = Point(0, h / 2) + p2 = Point2(-w / 2, -h / 2) + p3 = Point2(w / 2, -h / 2) centroid = (p1 + p2 + p3) / 3 bp = BezierPath([ MoveTo(p1 - centroid), @@ -160,13 +158,13 @@ const BezierUTriangle = let ]) end -const BezierLTriangle = rotate(BezierUTriangle, pi/2) +const BezierLTriangle = rotate(BezierUTriangle, pi / 2) const BezierDTriangle = rotate(BezierUTriangle, pi) -const BezierRTriangle = rotate(BezierUTriangle, 3pi/2) +const BezierRTriangle = rotate(BezierUTriangle, 3pi / 2) const BezierSquare = let - r = 0.95 * sqrt(pi)/2/2 # this gives a little less area as the r=0.5 circle + r = 0.95 * sqrt(pi) / 2 / 2 # this gives a little less area as the r=0.5 circle BezierPath([ MoveTo(Point2(r, -r)), LineTo(Point2(r, r)), @@ -177,15 +175,15 @@ const BezierSquare = let end const BezierCross = let - cutfraction = 2/3 + cutfraction = 2 / 3 r = 0.5 # 1/(2 * sqrt(1 - cutfraction^2)) ri = 0.166 #r * (1 - cutfraction) first_three = Point2[(r, ri), (ri, ri), (ri, r)] - all = map(0:pi/2:3pi/2) do a + all = (x -> reduce(vcat, x))(map(0:(pi / 2):(3pi / 2)) do a m = Mat2f(sin(a), cos(a), cos(a), -sin(a)) Ref(m) .* first_three - end |> x -> reduce(vcat, x) + end) BezierPath([ MoveTo(all[1]), @@ -194,13 +192,13 @@ const BezierCross = let ]) end -const BezierX = rotate(BezierCross, pi/4) +const BezierX = rotate(BezierCross, pi / 4) function bezier_ngon(n, radius, angle) points = [radius * Point2f(cos(a + angle), sin(a + angle)) - for a in range(0, 2pi, length = n+1)[1:end-1]] + for a in range(0, 2pi, length = n + 1)[1:(end - 1)]] BezierPath([ - MoveTo(points[1]); + MoveTo(points[1]) LineTo.(points[2:end]) ]) end @@ -208,10 +206,10 @@ end function bezier_star(n, inner_radius, outer_radius, angle) points = [ (isodd(i) ? outer_radius : inner_radius) * - Point2f(cos(a + angle), sin(a + angle)) - for (i, a) in enumerate(range(0, 2pi, length = 2n+1)[1:end-1])] + Point2f(cos(a + angle), sin(a + angle)) + for (i, a) in enumerate(range(0, 2pi, length = 2n + 1)[1:(end - 1)])] BezierPath([ - MoveTo(points[1]); + MoveTo(points[1]) LineTo.(points[2:end]) ]) end @@ -301,27 +299,27 @@ function parse_bezier_commands(svg) end if comm == "M" - x, y = parse.(Float64, args[i+1:i+2]) + x, y = parse.(Float64, args[(i + 1):(i + 2)]) push!(commands, MoveTo(Point2(x, y))) i += 3 elseif comm == "m" - x, y = parse.(Float64, args[i+1:i+2]) + x, y = parse.(Float64, args[(i + 1):(i + 2)]) push!(commands, MoveTo(Point2(x, y) + lastp())) i += 3 elseif comm == "L" - x, y = parse.(Float64, args[i+1:i+2]) + x, y = parse.(Float64, args[(i + 1):(i + 2)]) push!(commands, LineTo(Point2(x, y))) i += 3 elseif comm == "l" - x, y = parse.(Float64, args[i+1:i+2]) + x, y = parse.(Float64, args[(i + 1):(i + 2)]) push!(commands, LineTo(Point2(x, y) + lastp())) i += 3 elseif comm == "H" - x = parse(Float64, args[i+1]) + x = parse(Float64, args[i + 1]) push!(commands, LineTo(Point2(x, lastp()[2]))) i += 2 elseif comm == "h" - x = parse(Float64, args[i+1]) + x = parse(Float64, args[i + 1]) push!(commands, LineTo(X(x) + lastp())) i += 2 elseif comm == "Z" @@ -331,55 +329,55 @@ function parse_bezier_commands(svg) push!(commands, ClosePath()) i += 1 elseif comm == "C" - x1, y1, x2, y2, x3, y3 = parse.(Float64, args[i+1:i+6]) + x1, y1, x2, y2, x3, y3 = parse.(Float64, args[(i + 1):(i + 6)]) push!(commands, CurveTo(Point2(x1, y1), Point2(x2, y2), Point2(x3, y3))) i += 7 elseif comm == "c" - x1, y1, x2, y2, x3, y3 = parse.(Float64, args[i+1:i+6]) + x1, y1, x2, y2, x3, y3 = parse.(Float64, args[(i + 1):(i + 6)]) l = lastp() push!(commands, CurveTo(Point2(x1, y1) + l, Point2(x2, y2) + l, Point2(x3, y3) + l)) i += 7 elseif comm == "S" - x1, y1, x2, y2 = parse.(Float64, args[i+1:i+4]) + x1, y1, x2, y2 = parse.(Float64, args[(i + 1):(i + 4)]) prev = commands[end] reflected = prev.p + (prev.p - prev.c2) push!(commands, CurveTo(reflected, Point2(x1, y1), Point2(x2, y2))) i += 5 elseif comm == "s" - x1, y1, x2, y2 = parse.(Float64, args[i+1:i+4]) + x1, y1, x2, y2 = parse.(Float64, args[(i + 1):(i + 4)]) prev = commands[end] reflected = prev.p + (prev.p - prev.c2) l = lastp() push!(commands, CurveTo(reflected, Point2(x1, y1) + l, Point2(x2, y2) + l)) i += 5 elseif comm == "A" - args[i+1:i+7] - r1, r2 = parse.(Float64, args[i+1:i+2]) - angle = parse(Float64, args[i+3]) - large_arc_flag, sweep_flag = parse.(Bool, args[i+4:i+5]) - x2, y2 = parse.(Float64, args[i+6:i+7]) + args[(i + 1):(i + 7)] + r1, r2 = parse.(Float64, args[(i + 1):(i + 2)]) + angle = parse(Float64, args[i + 3]) + large_arc_flag, sweep_flag = parse.(Bool, args[(i + 4):(i + 5)]) + x2, y2 = parse.(Float64, args[(i + 6):(i + 7)]) x1, y1 = lastp() push!(commands, EllipticalArc(x1, y1, x2, y2, r1, r2, angle, large_arc_flag, sweep_flag)) i += 8 elseif comm == "a" - r1, r2 = parse.(Float64, args[i+1:i+2]) - angle = parse(Float64, args[i+3]) - large_arc_flag, sweep_flag = parse.(Bool, args[i+4:i+5]) + r1, r2 = parse.(Float64, args[(i + 1):(i + 2)]) + angle = parse(Float64, args[i + 3]) + large_arc_flag, sweep_flag = parse.(Bool, args[(i + 4):(i + 5)]) x1, y1 = lastp() - x2, y2 = parse.(Float64, args[i+6:i+7]) .+ (x1, y1) + x2, y2 = parse.(Float64, args[(i + 6):(i + 7)]) .+ (x1, y1) push!(commands, EllipticalArc(x1, y1, x2, y2, r1, r2, angle, large_arc_flag, sweep_flag)) i += 8 elseif comm == "v" - dy = parse(Float64, args[i+1]) + dy = parse(Float64, args[i + 1]) l = lastp() push!(commands, LineTo(Point2(l[1], l[2] + dy))) i += 2 elseif comm == "V" - y = parse(Float64, args[i+1]) + y = parse(Float64, args[i + 1]) l = lastp() push!(commands, LineTo(Point2(l[1], y))) i += 2 @@ -407,15 +405,15 @@ function EllipticalArc(x1, y1, x2, y2, rx, ry, ϕ, largearc::Bool, sweepflag::Bo x1′, y1′ = m1 * (0.5 * (p1 - p2)) tempsqrt = (rx^2 * ry^2 - rx^2 * y1′^2 - ry^2 * x1′^2) / - (rx^2 * y1′^2 + ry^2 * x1′^2) + (rx^2 * y1′^2 + ry^2 * x1′^2) c′ = (largearc == sweepflag ? -1 : 1) * - sqrt(tempsqrt) * Point(rx * y1′ / ry, -ry * x1′ / rx) + sqrt(tempsqrt) * Point(rx * y1′ / ry, -ry * x1′ / rx) c = Mat2(cos(ϕ), sin(ϕ), -sin(ϕ), cos(ϕ)) * c′ + 0.5 * (p1 + p2) vecangle(u, v) = sign(u[1] * v[2] - u[2] * v[1]) * - acos(dot(u, v) / (norm(u) * norm(v))) + acos(dot(u, v) / (norm(u) * norm(v))) px(sign) = Point((sign * x1′ - c′[1]) / rx, (sign * y1′ - c′[2]) / rx) @@ -474,17 +472,11 @@ end ftvec(p) = FT_Vector(round(Int, p[1]), round(Int, p[2])) -function convert_command(m::MoveTo) - true, 1, ftvec.([m.p]), [FT_Curve_Tag_On] -end +convert_command(m::MoveTo) = true, 1, ftvec.([m.p]), [FT_Curve_Tag_On] -function convert_command(l::LineTo) - false, 1, ftvec.([l.p]), [FT_Curve_Tag_On] -end +convert_command(l::LineTo) = false, 1, ftvec.([l.p]), [FT_Curve_Tag_On] -function convert_command(c::CurveTo) - false, 3, ftvec.([c.c1, c.c2, c.p]), [FT_Curve_Tag_Cubic, FT_Curve_Tag_Cubic, FT_Curve_Tag_On] -end +convert_command(c::CurveTo) = false, 3, ftvec.([c.c1, c.c2, c.p]), [FT_Curve_Tag_Cubic, FT_Curve_Tag_Cubic, FT_Curve_Tag_On] function render_path(path, bitmap_size_px = 256) # in the outline, 1 unit = 1/64px @@ -596,9 +588,7 @@ segment(p, c::CurveTo) = BezierSegment(p, c.c1, c.c2, c.p) endpoint(m::MoveTo) = m.p endpoint(l::LineTo) = l.p endpoint(c::CurveTo) = c.p -function endpoint(e::EllipticalArc) - point_at_angle(e, e.a2) -end +endpoint(e::EllipticalArc) = point_at_angle(e, e.a2) function point_at_angle(e::EllipticalArc, theta) M = abs(e.r1) * cos(theta) @@ -618,13 +608,9 @@ function cleanup_bbox(bb::Rect2f) end bbox(p, x::Union{LineTo, CurveTo}) = bbox(segment(p, x)) -function bbox(p, e::EllipticalArc) - bbox(elliptical_arc_to_beziers(e)) -end +bbox(p, e::EllipticalArc) = bbox(elliptical_arc_to_beziers(e)) -function bbox(ls::LineSegment) - Rect2f(ls.from, ls.to - ls.from) -end +bbox(ls::LineSegment) = Rect2f(ls.from, ls.to - ls.from) function bbox(b::BezierSegment) @@ -637,44 +623,44 @@ function bbox(b::BezierSegment) ma = [max.(p0, p3)...] c = -p0 + p1 - b = p0 - 2p1 + p2 + b = p0 - 2p1 + p2 a = -p0 + 3p1 - 3p2 + 1p3 - h = [(b.*b - a.*c)...] + h = [(b .* b - a .* c)...] if h[1] > 0 h[1] = sqrt(h[1]) t = (-b[1] - h[1]) / a[1] if t > 0 && t < 1 - s = 1.0-t - q = s*s*s*p0[1] + 3.0*s*s*t*p1[1] + 3.0*s*t*t*p2[1] + t*t*t*p3[1] - mi[1] = min(mi[1],q) - ma[1] = max(ma[1],q) + s = 1.0 - t + q = s * s * s * p0[1] + 3.0 * s * s * t * p1[1] + 3.0 * s * t * t * p2[1] + t * t * t * p3[1] + mi[1] = min(mi[1], q) + ma[1] = max(ma[1], q) end - t = (-b[1] + h[1])/a[1] - if t>0 && t<1 - s = 1.0-t - q = s*s*s*p0[1] + 3.0*s*s*t*p1[1] + 3.0*s*t*t*p2[1] + t*t*t*p3[1] - mi[1] = min(mi[1],q) - ma[1] = max(ma[1],q) + t = (-b[1] + h[1]) / a[1] + if t > 0 && t < 1 + s = 1.0 - t + q = s * s * s * p0[1] + 3.0 * s * s * t * p1[1] + 3.0 * s * t * t * p2[1] + t * t * t * p3[1] + mi[1] = min(mi[1], q) + ma[1] = max(ma[1], q) end end - if h[2]>0.0 + if h[2] > 0.0 h[2] = sqrt(h[2]) - t = (-b[2] - h[2])/a[2] - if t>0.0 && t<1.0 - s = 1.0-t - q = s*s*s*p0[2] + 3.0*s*s*t*p1[2] + 3.0*s*t*t*p2[2] + t*t*t*p3[2] - mi[2] = min(mi[2],q) - ma[2] = max(ma[2],q) + t = (-b[2] - h[2]) / a[2] + if t > 0.0 && t < 1.0 + s = 1.0 - t + q = s * s * s * p0[2] + 3.0 * s * s * t * p1[2] + 3.0 * s * t * t * p2[2] + t * t * t * p3[2] + mi[2] = min(mi[2], q) + ma[2] = max(ma[2], q) end - t = (-b[2] + h[2])/a[2] - if t>0.0 && t<1.0 - s = 1.0-t - q = s*s*s*p0[2] + 3.0*s*s*t*p1[2] + 3.0*s*t*t*p2[2] + t*t*t*p3[2] - mi[2] = min(mi[2],q) - ma[2] = max(ma[2],q) + t = (-b[2] + h[2]) / a[2] + if t > 0.0 && t < 1.0 + s = 1.0 - t + q = s * s * s * p0[2] + 3.0 * s * s * t * p1[2] + 3.0 * s * t * t * p2[2] + t * t * t * p3[2] + mi[2] = min(mi[2], q) + ma[2] = max(ma[2], q) end end @@ -688,9 +674,9 @@ function elliptical_arc_to_beziers(arc::EllipticalArc) angles = range(arc.a1, arc.a2, length = n_beziers + 1) startpoint = Point2f(cos(arc.a1), sin(arc.a1)) - curves = map(angles[1:end-1], angles[2:end]) do start, stop + curves = map(angles[1:(end - 1)], angles[2:end]) do start, stop theta = stop - start - kappa = 4/3 * tan(theta/4) + kappa = 4 / 3 * tan(theta / 4) c1 = Point2f(cos(start) - kappa * sin(start), sin(start) + kappa * cos(start)) c2 = Point2f(cos(stop) + kappa * sin(stop), sin(stop) - kappa * cos(stop)) b = Point2f(cos(stop), sin(stop)) diff --git a/src/camera/camera.jl b/src/camera/camera.jl index 338aec7233b..563d867d141 100644 --- a/src/camera/camera.jl +++ b/src/camera/camera.jl @@ -1,14 +1,10 @@ -function Base.copy(x::Camera) - Camera(ntuple(7) do i - getfield(x, i) - end...) -end +Base.copy(x::Camera) = Camera(ntuple(7) do i + getfield(x, i) +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) -end +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) function Base.show(io::IO, camera::Camera) println(io, "Camera:") @@ -44,9 +40,7 @@ struct CameraLift{F, Args} args::Args end -function (cl::CameraLift{F, Args})(val) where {F, Args} - cl.f(map(to_value, cl.args)...) -end +(cl::CameraLift{F, Args})(val) where {F, Args} = cl.f(map(to_value, cl.args)...) """ on(f, c::Camera, observables::Observable...) @@ -54,12 +48,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 @@ -67,10 +61,10 @@ end function Camera(px_area) pixel_space = lift(px_area) do window_size - nearclip = -10_000f0 - farclip = 10_000f0 + nearclip = -10_000.0f0 + farclip = 10_000.0f0 w, h = Float32.(widths(window_size)) - return orthographicprojection(0f0, w, 0f0, h, nearclip, farclip) + return orthographicprojection(0.0f0, w, 0.0f0, h, nearclip, farclip) end view = Observable(Mat4f(I)) proj = Observable(Mat4f(I)) @@ -80,7 +74,7 @@ function Camera(px_area) view, proj, proj_view, - lift(a-> Vec2f(widths(a)), px_area), + lift(a -> Vec2f(widths(a)), px_area), Observable(Vec3f(1)), ObserverFunction[] ) diff --git a/src/camera/camera2d.jl b/src/camera/camera2d.jl index 3a9a07c9024..8eeff75be22 100644 --- a/src/camera/camera2d.jl +++ b/src/camera/camera2d.jl @@ -58,7 +58,7 @@ function update_cam!(scene::Scene, cam::Camera2D, area3d::Rect) area = Rect2f(area3d) area = positive_widths(area) # ignore rects with width almost 0 - any(x-> x ≈ 0.0, widths(area)) && return + any(x -> x ≈ 0.0, widths(area)) && return pa = pixelarea(scene)[] px_wh = normalize(widths(pa)) @@ -78,17 +78,17 @@ end function update_cam!(scene::SceneLike, cam::Camera2D) x, y = minimum(cam.area[]) - w, h = widths(cam.area[]) ./ 2f0 + w, h = widths(cam.area[]) ./ 2.0f0 # These observables should be final, no one should do map(cam.projection), # so we don't push! and just update the value in place view = translationmatrix(Vec3f(-x - w, -y - h, 0)) - projection = orthographicprojection(-w, w, -h, h, -10_000f0, 10_000f0) + projection = orthographicprojection(-w, w, -h, h, -10_000.0f0, 10_000.0f0) set_proj_view!(camera(scene), projection, view) cam.last_area[] = Vec(size(scene)) return end -function correct_ratio!(scene, cam) +correct_ratio!(scene, cam) = on(camera(scene), pixelarea(scene)) do area neww = widths(area) change = neww .- cam.last_area[] @@ -100,7 +100,6 @@ function correct_ratio!(scene, cam) end return end -end function add_pan!(scene::SceneLike, cam::Camera2D) startpos = RefValue((0.0, 0.0)) @@ -157,7 +156,7 @@ function add_zoom!(scene::SceneLike, cam::Camera2D) zoom = Float32(x[2]) if zoom != 0 && ispressed(scene, zoombutton) && is_mouseinside(scene) pa = pixelarea(scene)[] - z = (1f0 - zoomspeed)^zoom + z = (1.0f0 - zoomspeed)^zoom mp = Vec2f(e.mouseposition[]) - minimum(pa) mp = (mp .* wscale(pa, area)) + minimum(area) p1, p2 = minimum(area), maximum(area) @@ -188,7 +187,7 @@ end function selection_rect!(scene, cam, key) rect = RefValue(Rectf(NaN, NaN, NaN, NaN)) - lw = 2f0 + lw = 2.0f0 scene_unscaled = Scene( scene, transformation = Transformation(), cam = copy(camera(scene)), clear = false @@ -198,7 +197,7 @@ function selection_rect!(scene, cam, key) scene_unscaled, rect[], linestyle = :dot, - linewidth = 2f0, + linewidth = 2.0f0, color = (:black, 0.4), visible = false ) @@ -284,9 +283,9 @@ function add_restriction!(cam, window, rarea::Rect2, minwidths::Vec) maxi = maxi - newmax newo = newo - maxi newwh = newmax - newo - scale = 1f0 + scale = 1.0f0 for (w1, w2) in zip(minwidths, newwh) - stmp = w1 > w2 ? w1 / w2 : 1f0 + stmp = w1 > w2 ? w1 / w2 : 1.0f0 scale = max(scale, stmp) end newwh = newwh * scale @@ -311,7 +310,7 @@ end function (cam::UpdatePixelCam)(window_size) w, h = Float32.(widths(window_size)) - projection = orthographicprojection(0f0, w, 0f0, h, cam.near, cam.far) + projection = orthographicprojection(0.0f0, w, 0.0f0, h, cam.near, cam.far) set_proj_view!(cam.camera, projection, Mat4f(I)) end @@ -320,7 +319,7 @@ end Creates a pixel-level camera for the `Scene`. No controls! """ -function campixel!(scene::Scene; nearclip=-10_000f0, farclip=10_000f0) +function campixel!(scene::Scene; nearclip = -10_000.0f0, farclip = 10_000.0f0) disconnect!(camera(scene)) update_once = Observable(false) closure = UpdatePixelCam(camera(scene), nearclip, farclip) @@ -340,8 +339,8 @@ struct RelativeCamera <: AbstractCamera end Creates a pixel-level camera for the `Scene`. No controls! """ -function cam_relative!(scene::Scene; nearclip=-10_000f0, farclip=10_000f0) - projection = orthographicprojection(0f0, 1f0, 0f0, 1f0, nearclip, farclip) +function cam_relative!(scene::Scene; nearclip = -10_000.0f0, farclip = 10_000.0f0) + projection = orthographicprojection(0.0f0, 1.0f0, 0.0f0, 1.0f0, nearclip, farclip) set_proj_view!(camera(scene), projection, Mat4f(I)) cam = RelativeCamera() cameracontrols!(scene, cam) diff --git a/src/camera/camera3d.jl b/src/camera/camera3d.jl index dc05aeb5ea0..71bafa945c1 100644 --- a/src/camera/camera3d.jl +++ b/src/camera/camera3d.jl @@ -85,46 +85,46 @@ function Camera3D(scene::Scene; kwargs...) Attributes( # Keyboard controls # Translations - up_key = Keyboard.r, - down_key = Keyboard.f, - left_key = Keyboard.a, - right_key = Keyboard.d, - forward_key = Keyboard.w, - backward_key = Keyboard.s, + up_key = Keyboard.r, + down_key = Keyboard.f, + left_key = Keyboard.a, + right_key = Keyboard.d, + forward_key = Keyboard.w, + backward_key = Keyboard.s, # Zooms - zoom_in_key = Keyboard.u, - zoom_out_key = Keyboard.o, - stretch_view_key = Keyboard.page_up, + zoom_in_key = Keyboard.u, + zoom_out_key = Keyboard.o, + stretch_view_key = Keyboard.page_up, contract_view_key = Keyboard.page_down, # Rotations - pan_left_key = Keyboard.j, + pan_left_key = Keyboard.j, pan_right_key = Keyboard.l, - tilt_up_key = Keyboard.i, + tilt_up_key = Keyboard.i, tilt_down_key = Keyboard.k, - roll_clockwise_key = Keyboard.e, + roll_clockwise_key = Keyboard.e, roll_counterclockwise_key = Keyboard.q, # Mouse controls translation_button = Mouse.right, - scroll_mod = true, - rotation_button = Mouse.left, + scroll_mod = true, + rotation_button = Mouse.left, # Shared controls fix_x_key = Keyboard.x, fix_y_key = Keyboard.y, fix_z_key = Keyboard.z, reset = Keyboard.home, # Settings - keyboard_rotationspeed = 1f0, + keyboard_rotationspeed = 1.0f0, keyboard_translationspeed = 0.5f0, - keyboard_zoomspeed = 1f0, - mouse_rotationspeed = 1f0, - mouse_translationspeed = 1f0, - mouse_zoomspeed = 1f0, + keyboard_zoomspeed = 1.0f0, + mouse_rotationspeed = 1.0f0, + mouse_translationspeed = 1.0f0, + mouse_zoomspeed = 1.0f0, circular_rotation = (true, true, true), - fov = 45f0, # base fov + fov = 45.0f0, # base fov near = automatic, far = automatic, rotation_center = :lookat, - update_rate = 1/30, + update_rate = 1 / 30, projectiontype = Perspective, fixed_axis = true, zoom_shift_lookat = false, # doesn't really work with fov @@ -136,16 +136,12 @@ function Camera3D(scene::Scene; kwargs...) cam = Camera3D( pop!(attr, :eyeposition, Vec3f(3)), - pop!(attr, :lookat, Vec3f(0)), - pop!(attr, :upvector, Vec3f(0, 0, 1)), - - Observable(1f0), + pop!(attr, :lookat, Vec3f(0)), + pop!(attr, :upvector, Vec3f(0, 0, 1)), Observable(1.0f0), Observable(attr[:fov][]), Observable(attr[:near][] === automatic ? 0.1f0 : attr[:near][]), - Observable(attr[:far][] === automatic ? 100f0 : attr[:far][]), - Observable(-1.0), - - attr + Observable(attr[:far][] === automatic ? 100.0f0 : attr[:far][]), + Observable(-1.0), attr ) disconnect!(camera(scene)) @@ -173,7 +169,7 @@ function Camera3D(scene::Scene; kwargs...) # Start ticking if relevant keys are pressed on(camera(scene), events(scene).keyboardbutton) do event if event.action in (Keyboard.press, Keyboard.repeat) && cam.pulser[] == -1.0 && - attr.selected[] && any(key -> ispressed(scene, attr[key][]), keynames) + attr.selected[] && any(key -> ispressed(scene, attr[key][]), keynames) cam.pulser[] = time() return Consume(true) @@ -204,7 +200,7 @@ function Camera3D(scene::Scene; kwargs...) end on(camera(scene), attr[:near], attr[:far]) do near, far near === automatic || (cam.near[] = near) - far === automatic || (cam.far[] = far) + far === automatic || (cam.far[] = far) update_cam!(scene, cam) end @@ -215,7 +211,7 @@ function Camera3D(scene::Scene; kwargs...) # might make sense to keep user set lookat, upvector, eyeposition # around somewhere for this? cam.lookat[] = Vec3f(0) - cam.upvector[] = Vec3f(0,0,1) + cam.upvector[] = Vec3f(0, 0, 1) cam.eyeposition[] = Vec3f(3) center!(scene) return Consume(true) @@ -254,16 +250,15 @@ function add_translation!(scene, cam::Camera3D) last_mousepos = RefValue(Vec2f(0, 0)) dragging = RefValue(false) - function compute_diff(delta) + compute_diff(delta) = if cam.attributes[:projectiontype][] == Orthographic aspect = Float32((/)(widths(scene.px_area[])...)) - aspect_scale = Vec2f(1f0 + aspect, 1f0 + 1f0 / aspect) + aspect_scale = Vec2f(1.0f0 + aspect, 1.0f0 + 1.0f0 / aspect) return cam.zoom_mult[] * delta .* aspect_scale ./ widths(scene.px_area[]) else viewdir = cam.lookat[] - cam.eyeposition[] return 0.002f0 * cam.zoom_mult[] * norm(viewdir) * delta end - end # drag start/stop on(camera(scene), scene.events.mousebutton) do event @@ -278,7 +273,7 @@ function add_translation!(scene, cam::Camera3D) diff = compute_diff(last_mousepos[] .- mousepos) last_mousepos[] = mousepos dragging[] = false - translate_cam!(scene, cam, translationspeed[] .* Vec3f(diff[1], diff[2], 0f0)) + translate_cam!(scene, cam, translationspeed[] .* Vec3f(diff[1], diff[2], 0.0f0)) return Consume(true) end return Consume(false) @@ -290,7 +285,7 @@ function add_translation!(scene, cam::Camera3D) mousepos = screen_relative(scene, mp) diff = compute_diff(last_mousepos[] .- mousepos) last_mousepos[] = mousepos - translate_cam!(scene, cam, translationspeed[] * Vec3f(diff[1], diff[2], 0f0)) + translate_cam!(scene, cam, translationspeed[] * Vec3f(diff[1], diff[2], 0.0f0)) return Consume(true) end return Consume(false) @@ -298,7 +293,7 @@ function add_translation!(scene, cam::Camera3D) on(camera(scene), scene.events.scroll) do scroll if is_mouseinside(scene) && ispressed(scene, scroll_mod[]) - zoom_step = (1f0 + 0.1f0 * zoomspeed[]) ^ -scroll[2] + zoom_step = (1.0f0 + 0.1f0 * zoomspeed[])^-scroll[2] zoom!(scene, cam, zoom_step, shift_lookat[], cad[]) return Consume(true) end @@ -327,7 +322,7 @@ function add_rotation!(scene, cam::Camera3D) rot_scaling = rotationspeed[] * (e.window_dpi[] * 0.005) mp = (last_mousepos[] .- mousepos) .* 0.01f0 .* rot_scaling last_mousepos[] = mousepos - rotate_cam!(scene, cam, Vec3f(-mp[2], mp[1], 0f0), true) + rotate_cam!(scene, cam, Vec3f(-mp[2], mp[1], 0.0f0), true) return Consume(true) end return Consume(false) @@ -340,7 +335,7 @@ function add_rotation!(scene, cam::Camera3D) rot_scaling = rotationspeed[] * (e.window_dpi[] * 0.005) mp = (last_mousepos[] .- mousepos) * 0.01f0 * rot_scaling last_mousepos[] = mousepos - rotate_cam!(scene, cam, Vec3f(-mp[2], mp[1], 0f0), true) + rotate_cam!(scene, cam, Vec3f(-mp[2], mp[1], 0.0f0), true) return Consume(true) end return Consume(false) @@ -363,7 +358,7 @@ function on_pulse(scene, cam, timestep) if translating # translation in camera space x/y/z direction translation = attr[:keyboard_translationspeed][] * timestep * - Vec3f(right - left, up - down, backward - forward) + Vec3f(right - left, up - down, backward - forward) viewdir = cam.lookat[] - cam.eyeposition[] _translate_cam!(scene, cam, cam.zoom_mult[] * norm(viewdir) * translation) end @@ -380,7 +375,7 @@ function on_pulse(scene, cam, timestep) if rotating # rotations around camera space x/y/z axes angles = attr[:keyboard_rotationspeed][] * timestep * - Vec3f(up - down, left - right, counterclockwise - clockwise) + Vec3f(up - down, left - right, counterclockwise - clockwise) _rotate_cam!(scene, cam, angles) end @@ -391,14 +386,14 @@ function on_pulse(scene, cam, timestep) zooming = zoom_out || zoom_in if zooming - zoom_step = (1f0 + attr[:keyboard_zoomspeed][] * timestep) ^ (zoom_out - zoom_in) + zoom_step = (1.0f0 + attr[:keyboard_zoomspeed][] * timestep)^(zoom_out - zoom_in) _zoom!(scene, cam, zoom_step, false) end stretch = ispressed(scene, attr[:stretch_view_key][]) contract = ispressed(scene, attr[:contract_view_key][]) if stretch || contract - zoom_step = (1f0 + attr[:keyboard_zoomspeed][] * timestep) ^ (stretch - contract) + zoom_step = (1.0f0 + attr[:keyboard_zoomspeed][] * timestep)^(stretch - contract) cam.eyeposition[] = cam.lookat[] + zoom_step * (cam.eyeposition[] - cam.lookat[]) end zooming = zooming || stretch || contract @@ -444,12 +439,12 @@ function _translate_cam!(scene, cam, t) end -function rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse=false) +function rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse = false) _rotate_cam!(scene, cam, angles, from_mouse) update_cam!(scene, cam) nothing end -function _rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse=false) +function _rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse = false) # This applies rotations around the x/y/z axis of the camera coordinate system # x expands right, y expands up and z expands towards the screen lookat = cam.lookat[] @@ -479,7 +474,7 @@ function _rotate_cam!(scene, cam::Camera3D, angles::VecTypes, from_mouse=false) # drawing circles creates continuous rotations around the fixed axis mp = mouseposition_px(scene) past_half = 0.5f0 .* widths(scene.px_area[]) .> mp - flip = 2f0 * past_half .- 1f0 + flip = 2.0f0 * past_half .- 1.0f0 angle = flip[1] * angles[1] + flip[2] * angles[2] angles = Vec3f(-angle, angle, -angle) # only one fix is true so this only rotates around one axis @@ -534,9 +529,9 @@ function _zoom!(scene::Scene, cam::Camera3D, zoom_step, shift_lookat = false, ca viewdir = lookat - eyepos # -z right = cross(viewdir, up) # +x - rel_pos = 2f0 * mouseposition_px(scene) ./ widths(scene.px_area[]) .- 1f0 + rel_pos = 2.0f0 * mouseposition_px(scene) ./ widths(scene.px_area[]) .- 1.0f0 shift = rel_pos[1] * normalize(right) + rel_pos[2] * normalize(up) - shifted = eyepos + 0.1f0 * sign(1f0 - zoom_step) * norm(viewdir) * shift + shifted = eyepos + 0.1f0 * sign(1.0f0 - zoom_step) * norm(viewdir) * shift cam.eyeposition[] = lookat + norm(viewdir) * normalize(shifted - lookat) elseif shift_lookat lookat = cam.lookat[] @@ -551,22 +546,22 @@ function _zoom!(scene::Scene, cam::Camera3D, zoom_step, shift_lookat = false, ca # translate both eyeposition and lookat to more or less keep data # under the mouse in view fov = cam.attributes[:fov][] - before = tan(clamp(cam.zoom_mult[] * fov, 0.01f0, 175f0) / 360f0 * Float32(pi)) - after = tan(clamp(cam.zoom_mult[] * zoom_step * fov, 0.01f0, 175f0) / 360f0 * Float32(pi)) + before = tan(clamp(cam.zoom_mult[] * fov, 0.01f0, 175.0f0) / 360.0f0 * Float32(pi)) + after = tan(clamp(cam.zoom_mult[] * zoom_step * fov, 0.01f0, 175.0f0) / 360.0f0 * Float32(pi)) aspect = Float32((/)(widths(scene.px_area[])...)) - rel_pos = 2f0 * mouseposition_px(scene) ./ widths(scene.px_area[]) .- 1f0 + rel_pos = 2.0f0 * mouseposition_px(scene) ./ widths(scene.px_area[]) .- 1.0f0 shift = rel_pos[1] * u_x + rel_pos[2] * u_y shift = -(after - before) * norm(viewdir) * normalize(aspect .* shift) else - mx, my = 2f0 * mouseposition_px(scene) ./ widths(scene.px_area[]) .- 1f0 + mx, my = 2.0f0 * mouseposition_px(scene) ./ widths(scene.px_area[]) .- 1.0f0 aspect = Float32((/)(widths(scene.px_area[])...)) - w = 0.5f0 * (1f0 + aspect) * cam.zoom_mult[] - h = 0.5f0 * (1f0 + 1f0 / aspect) * cam.zoom_mult[] - shift = (1f0 - zoom_step) * (mx * w * u_x + my * h * u_y) + w = 0.5f0 * (1.0f0 + aspect) * cam.zoom_mult[] + h = 0.5f0 * (1.0f0 + 1.0f0 / aspect) * cam.zoom_mult[] + shift = (1.0f0 - zoom_step) * (mx * w * u_x + my * h * u_y) end - cam.lookat[] = lookat + shift + cam.lookat[] = lookat + shift cam.eyeposition[] = eyepos + shift end @@ -580,16 +575,17 @@ end function update_cam!(scene::Scene, cam::Camera3D) @extractvalue cam (lookat, eyeposition, upvector) - near = cam.near[]; far = cam.far[] + near = cam.near[] + far = cam.far[] aspect = Float32((/)(widths(scene.px_area[])...)) if cam.attributes[:projectiontype][] == Perspective - fov = clamp(cam.zoom_mult[] * cam.attributes[:fov][], 0.01f0, 175f0) + fov = clamp(cam.zoom_mult[] * cam.attributes[:fov][], 0.01f0, 175.0f0) cam.fov[] = fov proj = perspectiveprojection(fov, aspect, near, far) else - w = 0.5f0 * (1f0 + aspect) * cam.zoom_mult[] - h = 0.5f0 * (1f0 + 1f0 / aspect) * cam.zoom_mult[] + w = 0.5f0 * (1.0f0 + aspect) * cam.zoom_mult[] + h = 0.5f0 * (1.0f0 + 1.0f0 / aspect) * cam.zoom_mult[] proj = orthographicprojection(-w, w, -h, h, near, far) end @@ -604,23 +600,23 @@ function update_cam!(scene::Scene, camera::Camera3D, area3d::Rect) @extractvalue camera (lookat, eyeposition, upvector) bb = Rect3f(area3d) width = widths(bb) - half_width = width ./ 2f0 + half_width = width ./ 2.0f0 middle = maximum(bb) - half_width old_dir = normalize(eyeposition .- lookat) camera.lookat[] = middle - neweyepos = middle .+ (1.2*norm(width) .* old_dir) + neweyepos = middle .+ (1.2 * norm(width) .* old_dir) camera.eyeposition[] = neweyepos - camera.upvector[] = Vec3f(0,0,1) + camera.upvector[] = Vec3f(0, 0, 1) if camera.attributes[:near][] === automatic camera.near[] = 0.1f0 * norm(widths(bb)) end if camera.attributes[:far][] === automatic - camera.far[] = 3f0 * norm(widths(bb)) + camera.far[] = 3.0f0 * norm(widths(bb)) end if camera.attributes[:projectiontype][] == Orthographic camera.zoom_mult[] = 0.6 * norm(width) else - camera.zoom_mult[] = 1f0 + camera.zoom_mult[] = 1.0f0 end update_cam!(scene, camera) return @@ -637,9 +633,9 @@ end function show_cam(scene) cam = cameracontrols(scene) println("cam=cameracontrols(scene)") - println("cam.eyeposition[] = ", round.(cam.eyeposition[], digits=2)) - println("cam.lookat[] = ", round.(cam.lookat[], digits=2)) - println("cam.upvector[] = ", round.(cam.upvector[], digits=2)) - println("cam.fov[] = ", round.(cam.fov[], digits=2)) + println("cam.eyeposition[] = ", round.(cam.eyeposition[], digits = 2)) + println("cam.lookat[] = ", round.(cam.lookat[], digits = 2)) + println("cam.upvector[] = ", round.(cam.upvector[], digits = 2)) + println("cam.fov[] = ", round.(cam.fov[], digits = 2)) return end diff --git a/src/camera/old_camera3d.jl b/src/camera/old_camera3d.jl index 2d5f424cccf..76bd965f70f 100644 --- a/src/camera/old_camera3d.jl +++ b/src/camera/old_camera3d.jl @@ -31,9 +31,9 @@ function old_cam3d_cad!(scene::Scene; kw_args...) eyeposition = Vec3f(3), lookat = Vec3f(0), upvector = Vec3f(0, 0, 1), - fov = 45f0, + fov = 45.0f0, near = 0.01f0, - far = 100f0, + far = 100.0f0, projectiontype = Perspective, pan_button = Mouse.right, rotate_button = Mouse.left, @@ -67,9 +67,9 @@ function old_cam3d_turntable!(scene::Scene; kw_args...) eyeposition = Vec3f(3), lookat = Vec3f(0), upvector = Vec3f(0, 0, 1), - fov = 45f0, + fov = 45.0f0, near = 0.01f0, - far = 100f0, + far = 100.0f0, projectiontype = Perspective, pan_button = Mouse.right, rotate_button = Mouse.left, @@ -99,10 +99,10 @@ the plot's axis. const old_cam3d! = old_cam3d_turntable! function projection_switch( - wh::Rect2, - fov::T, near::T, far::T, - projectiontype::ProjectionEnum, zoom::T - ) where T <: Real + wh::Rect2, + fov::T, near::T, far::T, + projectiontype::ProjectionEnum, zoom::T +) where T <: Real aspect = T((/)(widths(wh)...)) h = T(tan(fov / 360.0 * pi) * near) w = T(h * aspect) @@ -112,9 +112,9 @@ function projection_switch( end function rotate_cam( - theta::Vec{3, T}, - cam_right::Vec{3, T}, cam_up::Vec{3, T}, cam_dir::Vec{3, T} - ) where T + theta::Vec{3, T}, + cam_right::Vec{3, T}, cam_up::Vec{3, T}, cam_dir::Vec{3, T} +) where T rotation = Quaternion{T}(0, 0, 0, 1) if !all(isfinite.(theta)) # We can only rotate for finite values @@ -151,7 +151,7 @@ function add_translation!(scene, cam, key, button, zoom_shift_lookat::Bool) dragging[] = false diff = (last_mousepos[] - mousepos) * cam.translationspeed[] last_mousepos[] = mousepos - translate_cam!(scene, cam, Vec3f(0f0, diff[1], diff[2])) + translate_cam!(scene, cam, Vec3f(0.0f0, diff[1], diff[2])) return Consume(true) end end @@ -163,7 +163,7 @@ function add_translation!(scene, cam, key, button, zoom_shift_lookat::Bool) mousepos = screen_relative(scene, mp) diff = (last_mousepos[] .- mousepos) * cam.translationspeed[] last_mousepos[] = mousepos - translate_cam!(scene, cam, Vec3f(0f0, diff[1], diff[2])) + translate_cam!(scene, cam, Vec3f(0.0f0, diff[1], diff[2])) return Consume(true) end return Consume(false) @@ -173,7 +173,7 @@ function add_translation!(scene, cam, key, button, zoom_shift_lookat::Bool) if ispressed(scene, button[]) && is_mouseinside(scene) cam_res = Vec2f(widths(scene.px_area[])) mouse_pos_normalized = mouseposition_px(scene) ./ cam_res - mouse_pos_normalized = 2*mouse_pos_normalized .- 1f0 + mouse_pos_normalized = 2 * mouse_pos_normalized .- 1.0f0 zoom_step = scroll[2] zoom!(scene, mouse_pos_normalized, zoom_step, zoom_shift_lookat) return Consume(true) @@ -199,7 +199,7 @@ function add_rotation!(scene, cam, button, key, fixed_axis::Bool) rot_scaling = cam.rotationspeed[] * (e.window_dpi[] * 0.005) mp = (last_mousepos[] - mousepos) * rot_scaling last_mousepos[] = mousepos - rotate_cam!(scene, cam, Vec3f(mp[1], -mp[2], 0f0), fixed_axis) + rotate_cam!(scene, cam, Vec3f(mp[1], -mp[2], 0.0f0), fixed_axis) return Consume(true) end end @@ -212,7 +212,7 @@ function add_rotation!(scene, cam, button, key, fixed_axis::Bool) rot_scaling = cam.rotationspeed[] * (e.window_dpi[] * 0.005) mp = (last_mousepos[] .- mousepos) * rot_scaling last_mousepos[] = mousepos - rotate_cam!(scene, cam, Vec3f(mp[1], -mp[2], 0f0), fixed_axis) + rotate_cam!(scene, cam, Vec3f(mp[1], -mp[2], 0.0f0), fixed_axis) return Consume(true) end return Consume(false) @@ -263,8 +263,8 @@ function zoom!(scene, point::VecTypes, zoom_step, shift_lookat::Bool) # split zoom into two components: # the offset perpendicular to `eyeposition - lookat`, based on mouse offset ~ ray_dir # the offset parallel to `eyeposition - lookat` ~ dir - ray_eye = inv(scene.camera.projection[]) * Vec4f(point[1],point[2],0,0) - ray_eye = Vec4f(ray_eye[Vec(1, 2)]...,0,0) + ray_eye = inv(scene.camera.projection[]) * Vec4f(point[1], point[2], 0, 0) + ray_eye = Vec4f(ray_eye[Vec(1, 2)]..., 0, 0) ray_dir = Vec3f((inv(scene.camera.view[]) * ray_eye)) dir = eyeposition - lookat @@ -274,12 +274,12 @@ 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) * (1.0f0 - 0.9f0^zoom_step) + cam.lookat[] = lookat + (1.0f0 - 0.9f0^zoom_step) * ray_dir else # Rotations need more extreme eyeposition shifts step = zoom_step - while abs(step) > 0f0 + while abs(step) > 0.0f0 cam.eyeposition[] = cam.eyeposition[] + sign(zoom_step) * (ray_dir - dir * 0.1f0) dir = cam.eyeposition[] - lookat step -= sign(step) @@ -322,7 +322,7 @@ function update_cam!(scene::Scene, cam::OldCamera3D) zoom = norm(lookat - eyeposition) # TODO this means you can't set FarClip... SAD! # TODO use boundingbox(scene) for optimal far/near - far = max(zoom * 5f0, 30f0) + far = max(zoom * 5.0f0, 30.0f0) proj = projection_switch(scene.px_area[], fov, near, far, projectiontype, zoom) view = Makie.lookat(eyeposition, lookat, upvector) set_proj_view!(camera(scene), proj, view) @@ -333,15 +333,15 @@ 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 / 2.0f0 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)) + camera.far[] = 3.0f0 * norm(widths(bb)) update_cam!(scene, camera) return end diff --git a/src/camera/projection_math.jl b/src/camera/projection_math.jl index 717224c6a6a..29e4da0ef9d 100644 --- a/src/camera/projection_math.jl +++ b/src/camera/projection_math.jl @@ -1,10 +1,10 @@ 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 @@ -15,10 +15,10 @@ translationmatrix_z(z::T) where {T} = translationmatrix(Vec{3, T}(0, 0, z)) 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 @@ -30,14 +30,14 @@ function rotationmatrix_x(angle::Number) 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 ) @@ -77,7 +77,7 @@ end View frustum matrix (4x4). """ function frustum(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) + (right == left || bottom == top || znear == zfar) && return Mat{4, 4, T}(I) T0, T1, T2 = zero(T), one(T), T(2) return Mat{4}( T2 * znear / (right - left), T0, T0, T0, @@ -101,25 +101,19 @@ function perspectiveprojection(fovy::T, aspect::T, znear::T, zfar::T) where T return frustum(-w, w, -h, h, znear, zfar) end -function perspectiveprojection( - ::Type{T}, fovy::Number, aspect::Number, znear::Number, zfar::Number - ) where T - perspectiveprojection(T(fovy), T(aspect), T(znear), T(zfar)) -end +perspectiveprojection( + ::Type{T}, fovy::Number, aspect::Number, znear::Number, zfar::Number +) where T = perspectiveprojection(T(fovy), T(aspect), T(znear), T(zfar)) """ `proj = perspectiveprojection([T], rect, fov, near, far)` defines the 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) -end +perspectiveprojection(wh::Rect2, fov::T, near::T, far::T) where T = perspectiveprojection(fov, T(wh.w / wh.h), near, far) -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)) -end +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)) """ `view = lookat(eyeposition, lookat, up)` creates a view matrix with @@ -130,68 +124,62 @@ 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)) + 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 -function lookat(::Type{T}, eyePos::Vec{3}, lookAt::Vec{3}, up::Vec{3}) where T - lookat(Vec{3,T}(eyePos), Vec{3,T}(lookAt), Vec{3,T}(up)) -end +lookat(::Type{T}, eyePos::Vec{3}, lookAt::Vec{3}, up::Vec{3}) where T = lookat(Vec{3, T}(eyePos), Vec{3, T}(lookAt), Vec{3, T}(up)) function orthographicprojection(wh::Rect2, near::T, far::T) where T w, h = widths(wh) orthographicprojection(zero(T), T(w), zero(T), T(h), near, far) end -function orthographicprojection( - ::Type{T}, wh::Rect2, near::Number, far::Number - ) where T - orthographicprojection(wh, T(near), T(far)) -end +orthographicprojection( + ::Type{T}, wh::Rect2, near::Number, far::Number +) where T = orthographicprojection(wh, T(near), T(far)) 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 - orthographicprojection( - T(left), T(right), - T(bottom), T(top), - T(znear), T(zfar) - ) -end +orthographicprojection(::Type{T}, + left::Number, right::Number, + bottom::Number, top::Number, + znear::Number, zfar::Number +) where T = orthographicprojection( + T(left), T(right), + T(bottom), T(top), + T(znear), T(zfar) +) 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 +189,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 +197,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,7 +207,7 @@ 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 @@ -231,10 +219,10 @@ 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 @@ -254,10 +242,10 @@ 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}( @@ -269,16 +257,14 @@ function to_world( ws ./ ws[4] end -function to_world( - 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) -end +to_world( + 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) -function project(scene::Scene, point::T) where T<:StaticVector +function project(scene::Scene, point::T) where T <: StaticVector cam = scene.camera area = pixelarea(scene)[] # TODO, I think we need .+ minimum(area) @@ -298,16 +284,14 @@ function project(matrix::Mat4f, p::T, dim4 = 1.0) where T <: VecTypes end function project(proj_view::Mat4f, resolution::Vec2, point::Point) - p4d = to_ndim(Vec4f, to_ndim(Vec3f, point, 0f0), 1f0) + p4d = to_ndim(Vec4f, to_ndim(Vec3f, point, 0.0f0), 1.0f0) clip = proj_view * p4d p = (clip ./ clip[4])[Vec(1, 2)] p = Vec2f(p[1], p[2]) - return (((p .+ 1f0) ./ 2f0) .* (resolution .- 1f0)) .+ 1f0 + return (((p .+ 1.0f0) ./ 2.0f0) .* (resolution .- 1.0f0)) .+ 1.0f0 end -function project_point2(mat4::Mat4, point2::Point2) - Point2f(mat4 * to_ndim(Point4f, to_ndim(Point3f, point2, 0), 1)) -end +project_point2(mat4::Mat4, point2::Point2) = Point2f(mat4 * to_ndim(Point4f, to_ndim(Point3f, point2, 0), 1)) function transform(model::Mat4, x::T) where T x4d = to_ndim(Vec4f, x, 0.0) @@ -315,7 +299,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) +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) @@ -327,9 +311,8 @@ function space_to_clip(cam::Camera, space::Symbol, projectionview::Bool=true) else error("Space $space not recognized. Must be one of $(spaces())") end -end -function clip_to_space(cam::Camera, space::Symbol) +clip_to_space(cam::Camera, space::Symbol) = if is_data_space(space) return inv(cam.projectionview[]) elseif is_pixel_space(space) @@ -342,7 +325,6 @@ function clip_to_space(cam::Camera, space::Symbol) else error("Space $space not recognized. Must be one of $(spaces())") end -end 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 7bca6b4c84a..5b989bd0d12 100644 --- a/src/colorsampler.jl +++ b/src/colorsampler.jl @@ -95,7 +95,7 @@ function Base.getindex(sampler::Sampler, i)::RGBAf return RGBAf(color(c), alpha(c) * sampler.alpha) end -function Base.getindex(sampler::Sampler{2, <: AbstractVector{Vec2f}}, i)::RGBAf +function Base.getindex(sampler::Sampler{2, <:AbstractVector{Vec2f}}, i)::RGBAf uv = sampler.values[i] colors = sampler.colors # indexing confirming to OpenGL uv indexing @@ -106,13 +106,11 @@ 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) - return sampler(cmap, LinRange(0, 1, n); scaling = scaling, alpha = alpha, interpolation = interpolation) -end +sampler(cmap::Union{Symbol, String}, n::Int = 20; + scaling = Scaling(), alpha = 1.0, interpolation = Linear) = sampler(cmap, LinRange(0, 1, n); scaling = scaling, alpha = alpha, interpolation = interpolation) -function sampler(cmap::Union{Symbol, String}, values::AbstractVector{<: AbstractFloat}; - scaling=Scaling(), alpha=1.0, interpolation=Linear) +function sampler(cmap::Union{Symbol, String}, values::AbstractVector{<:AbstractFloat}; + scaling = Scaling(), alpha = 1.0, interpolation = Linear) cs = PlotUtils.get_colorscheme(cmap) @@ -121,20 +119,14 @@ 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) - return Sampler(RGBAf.(cmap), values, alpha, interpolation, scaling) -end +sampler(cmap::Vector{<:Colorant}, values::AbstractVector{<:AbstractFloat}; + scaling = Scaling(), alpha = 1.0, interpolation = Linear) = Sampler(RGBAf.(cmap), values, alpha, interpolation, scaling) -function sampler(cmap::AbstractVector, values, crange; - alpha=1.0, interpolation=Linear) - return Sampler(to_color.(cmap), values, alpha, interpolation, Scaling(identity, crange)) -end +sampler(cmap::AbstractVector, values, crange; + alpha = 1.0, interpolation = Linear) = Sampler(to_color.(cmap), values, alpha, interpolation, Scaling(identity, crange)) # uv texture sampler -function sampler(cmap::Matrix{<: Colorant}, uv::AbstractVector{Vec2f}; - alpha=1.0, interpolation=Linear) - return Sampler(cmap, uv, alpha, interpolation, Scaling()) -end +sampler(cmap::Matrix{<:Colorant}, uv::AbstractVector{Vec2f}; + alpha = 1.0, interpolation = Linear) = Sampler(cmap, uv, alpha, interpolation, Scaling()) function numbers_to_colors(numbers::AbstractArray{<:Number}, primitive) @@ -149,7 +141,7 @@ function numbers_to_colors(numbers::AbstractArray{<:Number}, primitive) lowclip = get_attribute(primitive, :lowclip) highclip = get_attribute(primitive, :highclip) - nan_color = get_attribute(primitive, :nan_color, RGBAf(0,0,0,0)) + nan_color = get_attribute(primitive, :nan_color, RGBAf(0, 0, 0, 0)) cmin, cmax = colorrange::Vec2f diff --git a/src/conversions.jl b/src/conversions.jl index 215edf871bb..9a83ddba4ab 100644 --- a/src/conversions.jl +++ b/src/conversions.jl @@ -68,14 +68,10 @@ end convert_single_argument(x) = x # replace missings with NaNs -function convert_single_argument(a::AbstractArray{<:Union{Missing, <:Real}}) - [ismissing(x) ? NaN32 : convert(Float32, x) for x in a] -end +convert_single_argument(a::AbstractArray{<:Union{Missing, <:Real}}) = [ismissing(x) ? NaN32 : convert(Float32, x) for x in a] # 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] -end +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] ################################################################################ # PointBased # @@ -84,23 +80,15 @@ end """ Wrap a single point or equivalent object in a single-element array. """ -function convert_arguments(::PointBased, x::Real, y::Real) - ([Point2f(x, y)],) -end +convert_arguments(::PointBased, x::Real, y::Real) = ([Point2f(x, y)],) -function convert_arguments(::PointBased, x::Real, y::Real, z::Real) - ([Point3f(x, y, z)],) -end +convert_arguments(::PointBased, x::Real, y::Real, z::Real) = ([Point3f(x, y, z)],) -function convert_arguments(::PointBased, position::VecTypes{N, <: Number}) where N - ([convert(Point{N, Float32}, position)],) -end +convert_arguments(::PointBased, position::VecTypes{N, <:Number}) where N = ([convert(Point{N, Float32}, position)],) -function convert_arguments(::PointBased, positions::AbstractVector{<: VecTypes{N, <: Number}}) where N - (elconvert(Point{N, Float32}, positions),) -end +convert_arguments(::PointBased, positions::AbstractVector{<:VecTypes{N, <:Number}}) where N = (elconvert(Point{N, Float32}, positions),) -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 @@ -109,9 +97,7 @@ end Enables to use scatter like a surface plot with x::Vector, y::Vector, z::Matrix spanning z over the grid spanned by x y """ -function convert_arguments(::PointBased, x::AbstractVector, y::AbstractVector, z::AbstractMatrix) - (vec(Point3f.(x, y', z)),) -end +convert_arguments(::PointBased, x::AbstractVector, y::AbstractVector, z::AbstractMatrix) = (vec(Point3f.(x, y', z)),) """ convert_arguments(P, x, y, z)::(Vector) @@ -129,9 +115,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}) - (to_vertices(pos),) -end +convert_arguments(::PointBased, pos::AbstractMatrix{<:Number}) = (to_vertices(pos),) convert_arguments(P::PointBased, x::AbstractVector{<:Real}, y::AbstractVector{<:Real}) = (Point2f.(x, y),) @@ -171,26 +155,22 @@ function convert_arguments(P::PointBased, x::Rect2) return convert_arguments(P, decompose(Point2f, x)[[1, 2, 4, 3]]) end -function convert_arguments(P::PointBased, mesh::AbstractMesh) - return convert_arguments(P, decompose(Point3f, mesh)) -end +convert_arguments(P::PointBased, mesh::AbstractMesh) = convert_arguments(P, decompose(Point3f, mesh)) -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 -function convert_arguments(P::PointBased, rect::Rect3) - return (decompose(Point3f, rect),) -end +convert_arguments(P::PointBased, rect::Rect3) = (decompose(Point3f, rect),) -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]],) @@ -201,9 +181,7 @@ end Takes an input `LineString` and decomposes it to points. """ -function convert_arguments(PB::PointBased, linestring::LineString) - return convert_arguments(PB, decompose(Point, linestring)) -end +convert_arguments(PB::PointBased, linestring::LineString) = convert_arguments(PB, decompose(Point, linestring)) """ convert_arguments(PB, Union{Array{<:LineString}, MultiLineString}) @@ -268,9 +246,9 @@ function edges(v::AbstractVector) # Equivalent to # mids = 0.5 .* (v[1:end-1] .+ v[2:end]) # borders = [2v[1] - mids[1]; mids; 2v[end] - mids[end]] - borders = [0.5 * (v[max(1, i)] + v[min(end, i+1)]) for i in 0:length(v)] + borders = [0.5 * (v[max(1, i)] + v[min(end, i + 1)]) for i in 0:length(v)] borders[1] = 2borders[1] - borders[2] - borders[end] = 2borders[end] - borders[end-1] + borders[end] = 2borders[end] - borders[end - 1] return borders end end @@ -292,12 +270,8 @@ whether they represent edges or centers of the heatmap bins. If they are centers, convert to edges. Convert eltypes to `Float32` and return outputs as a `Tuple`. """ -function convert_arguments(SL::SurfaceLike, x::AbstractVecOrMat{<: Number}, y::AbstractVecOrMat{<: Number}, z::AbstractMatrix{<: Union{Number, Colorant}}) - return map(el32convert, adjust_axes(SL, x, y, z)) -end -function convert_arguments(SL::SurfaceLike, x::AbstractVecOrMat{<: Number}, y::AbstractVecOrMat{<: Number}, z::AbstractMatrix{<:Number}) - return map(el32convert, adjust_axes(SL, x, y, z)) -end +convert_arguments(SL::SurfaceLike, x::AbstractVecOrMat{<:Number}, y::AbstractVecOrMat{<:Number}, z::AbstractMatrix{<:Union{Number, Colorant}}) = map(el32convert, adjust_axes(SL, x, y, z)) +convert_arguments(SL::SurfaceLike, x::AbstractVecOrMat{<:Number}, y::AbstractVecOrMat{<:Number}, z::AbstractMatrix{<:Number}) = map(el32convert, adjust_axes(SL, x, y, z)) convert_arguments(sl::SurfaceLike, x::AbstractMatrix, y::AbstractMatrix) = convert_arguments(sl, x, y, zeros(size(y))) @@ -308,9 +282,7 @@ Takes 2 ClosedIntervals's `x`, `y`, and an AbstractMatrix `z`, and converts the linspaces with size(z, 1/2) `P` is the plot Type (it is optional). """ -function convert_arguments(P::SurfaceLike, x::ClosedInterval, y::ClosedInterval, z::AbstractMatrix) - convert_arguments(P, to_linspace(x, size(z, 1)), to_linspace(y, size(z, 2)), z) -end +convert_arguments(P::SurfaceLike, x::ClosedInterval, y::ClosedInterval, z::AbstractMatrix) = convert_arguments(P, to_linspace(x, size(z, 1)), to_linspace(y, size(z, 2)), z) """ convert_arguments(P, Matrix)::Tuple{ClosedInterval, ClosedInterval, Matrix} @@ -322,7 +294,7 @@ and stores the `ClosedInterval` to `n` and `m`, plus the original matrix in a Tu """ function convert_arguments(sl::SurfaceLike, data::AbstractMatrix) n, m = Float32.(size(data)) - convert_arguments(sl, 0f0 .. n, 0f0 .. m, el32convert(data)) + convert_arguments(sl, 0.0f0 .. n, 0.0f0 .. m, el32convert(data)) end function convert_arguments(ds::DiscreteSurface, data::AbstractMatrix) @@ -387,12 +359,10 @@ and stores the `ClosedInterval` to `n`, `m` and `k`, plus the original array in """ 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)) + return (0.0f0 .. n, 0.0f0 .. m, 0.0f0 .. k, el32convert(data)) end -function convert_arguments(::VolumeLike, x::RangeLike, y::RangeLike, z::RangeLike, data::AbstractArray{T, 3}) where T - return (x, y, z, el32convert(data)) -end +convert_arguments(::VolumeLike, x::RangeLike, y::RangeLike, z::RangeLike, data::AbstractArray{T, 3}) where T = (x, y, z, el32convert(data)) """ convert_arguments(P, x, y, z, i)::(Vector, Vector, Vector, Matrix) @@ -400,9 +370,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 - (x, y, z, el32convert(i)) -end +convert_arguments(::VolumeLike, x::AbstractVector, y::AbstractVector, z::AbstractVector, i::AbstractArray{T, 3}) where T = (x, y, z, el32convert(i)) """ @@ -419,7 +387,7 @@ function convert_arguments(::VolumeLike, x::AbstractVector, y::AbstractVector, z end _x, _y, _z = ntuple(Val(3)) do i A = (x, y, z)[i] - reshape(A, ntuple(j-> j != i ? 1 : length(A), Val(3))) + reshape(A, ntuple(j -> j != i ? 1 : length(A), Val(3))) end return (x, y, z, el32convert.(f.(_x, _y, _z))) end @@ -428,7 +396,7 @@ end # <:Lines # ################################################################################ -function convert_arguments(::Type{<: Lines}, x::Rect2) +function convert_arguments(::Type{<:Lines}, x::Rect2) # TODO fix the order of decompose points = decompose(Point2f, x) return (points[[1, 2, 4, 3, 1]],) @@ -442,11 +410,9 @@ 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)),) -end +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}, 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]],) @@ -474,12 +440,10 @@ Takes an input `AbstractString` `x` and converts it to a string. Takes real vectors x, y, z and constructs a mesh out of those, under the assumption that every 3 points form a triangle. """ -function convert_arguments( - T::Type{<:Mesh}, - x::RealVector, y::RealVector, z::RealVector - ) - convert_arguments(T, Point3f.(x, y, z)) -end +convert_arguments( + T::Type{<:Mesh}, + x::RealVector, y::RealVector, z::RealVector +) = convert_arguments(T, Point3f.(x, y, z)) """ convert_arguments(Mesh, xyz::AbstractVector)::GLNormalMesh @@ -487,10 +451,10 @@ Takes an input mesh and a vector `xyz` representing the vertices of the mesh, an creates indices under the assumption, that each triplet in `xyz` forms a triangle. """ function convert_arguments( - MT::Type{<:Mesh}, - xyz::AbstractVector - ) - faces = connect(UInt32.(0:length(xyz)-1), GLTriangleFace) + MT::Type{<:Mesh}, + xyz::AbstractVector +) + faces = connect(UInt32.(0:(length(xyz) - 1)), GLTriangleFace) # TODO support faceview natively return convert_arguments(MT, xyz, collect(faces)) end @@ -504,22 +468,18 @@ function convert_arguments(::Type{<:Mesh}, mesh::GeometryBasics.Mesh{N}) where { mesh = GeometryBasics.pointmeta(mesh, decompose(Vec3f, n)) end end - return (GeometryBasics.mesh(mesh, pointtype=Point{N, Float32}, facetype=GLTriangleFace),) + return (GeometryBasics.mesh(mesh, pointtype = Point{N, Float32}, facetype = GLTriangleFace),) end -function convert_arguments( - MT::Type{<:Mesh}, - meshes::AbstractVector{<: Union{AbstractMesh, AbstractPolygon}} - ) - return (meshes,) -end +convert_arguments( + MT::Type{<:Mesh}, + meshes::AbstractVector{<:Union{AbstractMesh, AbstractPolygon}} +) = (meshes,) -function convert_arguments( - MT::Type{<:Mesh}, - xyz::Union{AbstractPolygon, AbstractVector{<: AbstractPoint{2}}} - ) - return convert_arguments(MT, triangle_mesh(xyz)) -end +convert_arguments( + MT::Type{<:Mesh}, + xyz::Union{AbstractPolygon, AbstractVector{<:AbstractPoint{2}}} +) = convert_arguments(MT, triangle_mesh(xyz)) function convert_arguments(MT::Type{<:Mesh}, geom::GeometryPrimitive) # we convert to UV mesh as default, because otherwise the uv informations get lost @@ -533,13 +493,11 @@ end Takes real vectors x, y, z and constructs a triangle mesh out of those, using the 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 - ) - return convert_arguments(T, Point3f.(x, y, z), indices) -end +convert_arguments( + T::Type{<:Mesh}, + x::RealVector, y::RealVector, z::RealVector, + indices::AbstractVector +) = convert_arguments(T, Point3f.(x, y, z), indices) """ convert_arguments(Mesh, vertices, indices)::GLNormalMesh @@ -549,10 +507,10 @@ See [`to_vertices`](@ref) and [`to_triangles`](@ref) for more information about accepted types. """ function convert_arguments( - ::Type{<:Mesh}, - vertices::AbstractArray, - indices::AbstractArray - ) + ::Type{<:Mesh}, + vertices::AbstractArray, + indices::AbstractArray +) m = normal_mesh(to_vertices(vertices), to_triangles(indices)) (m,) end @@ -596,12 +554,12 @@ end # OffsetArrays conversions function convert_arguments(sl::SurfaceLike, wm::OffsetArray) - x1, y1 = wm.offsets .+ 1 - nx, ny = size(wm) - x = range(x1, length = nx) - y = range(y1, length = ny) - v = parent(wm) - return convert_arguments(sl, x, y, v) + x1, y1 = wm.offsets .+ 1 + nx, ny = size(wm) + x = range(x1, length = nx) + y = range(y1, length = ny) + v = parent(wm) + return convert_arguments(sl, x, y, v) end ################################################################################ @@ -615,9 +573,9 @@ Converts the elemen array type to `T1` without making a copy if the element type """ elconvert(::Type{T1}, x::AbstractArray{T2, N}) where {T1, T2, N} = convert(AbstractArray{T1, N}, x) float32type(x::Type) = Float32 -float32type(::Type{<: RGB}) = RGB{Float32} -float32type(::Type{<: RGBA}) = RGBA{Float32} -float32type(::Type{<: Colorant}) = RGBA{Float32} +float32type(::Type{<:RGB}) = RGB{Float32} +float32type(::Type{<:RGBA}) = RGBA{Float32} +float32type(::Type{<:Colorant}) = RGBA{Float32} float32type(x::AbstractArray{T}) where T = float32type(T) float32type(x::T) where T = float32type(T) el32convert(x::AbstractArray) = elconvert(float32type(x), x) @@ -625,11 +583,9 @@ 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} - return map(x) do elem - return (ismissing(elem) ? NaN32 : convert(Float32, elem))::Float32 - end::Array{Float32, N} -end +el32convert(x::AbstractArray{T, N}) where {T <: Union{Missing, <:Number}, N} = map(x) do elem + return (ismissing(elem) ? NaN32 : convert(Float32, elem))::Float32 +end::Array{Float32, N} """ to_triangles(indices) @@ -645,18 +601,14 @@ function to_triangles(x::AbstractVector{Int}) return to_triangles(idx0) end -function to_triangles(idx0::AbstractVector{UInt32}) - reinterpret(GLTriangleFace, idx0) -end +to_triangles(idx0::AbstractVector{UInt32}) = reinterpret(GLTriangleFace, idx0) -function to_triangles(faces::AbstractVector{TriangleFace{T}}) where T - elconvert(GLTriangleFace, faces) -end +to_triangles(faces::AbstractVector{TriangleFace{T}}) where T = elconvert(GLTriangleFace, faces) function to_triangles(faces::AbstractMatrix{T}) where T <: Integer @assert size(faces, 2) == 3 return broadcast(1:size(faces, 1), 3) do fidx, n - GLTriangleFace(ntuple(i-> faces[fidx, i], n)) + GLTriangleFace(ntuple(i -> faces[fidx, i], n)) end end @@ -675,16 +627,14 @@ Converts a representation of vertices `v` to its canonical representation as a - if `v` has 2 or 3 rows, it will treat each column as a vertex, - otherwise if `v` has 2 or 3 columns, it will treat each row as a vertex. """ -function to_vertices(verts::AbstractVector{<: VecTypes{3, T}}) where T +function to_vertices(verts::AbstractVector{<:VecTypes{3, T}}) where T vert3f0 = T != Float32 ? Point3f.(verts) : verts return reinterpret(Point3f, vert3f0) end -function to_vertices(verts::AbstractVector{<: VecTypes}) - to_vertices(to_ndim.(Point3f, verts, 0.0)) -end +to_vertices(verts::AbstractVector{<:VecTypes}) = to_vertices(to_ndim.(Point3f, verts, 0.0)) -function to_vertices(verts::AbstractMatrix{<: Number}) +to_vertices(verts::AbstractMatrix{<:Number}) = if size(verts, 1) in (2, 3) to_vertices(verts, Val(1)) elseif size(verts, 2) in (2, 3) @@ -692,7 +642,6 @@ function to_vertices(verts::AbstractMatrix{<: Number}) else error("You are using a matrix for vertices which uses neither dimension to encode the dimension of the space. Please have either size(verts, 1/2) in the range of 2-3. Found: $(size(verts))") end -end function to_vertices(verts::AbstractMatrix{T}, ::Val{1}) where T <: Number N = size(verts, 1) @@ -701,19 +650,18 @@ function to_vertices(verts::AbstractMatrix{T}, ::Val{1}) where T <: Number else let N = Val(N), lverts = verts broadcast(1:size(verts, 2), N) do vidx, n - to_ndim(Point3f, ntuple(i-> lverts[i, vidx], n), 0.0) + to_ndim(Point3f, ntuple(i -> lverts[i, vidx], n), 0.0) end end end end -function to_vertices(verts::AbstractMatrix{T}, ::Val{2}) where T <: Number +to_vertices(verts::AbstractMatrix{T}, ::Val{2}) where T <: Number = let N = Val(size(verts, 2)), lverts = verts broadcast(1:size(verts, 1), N) do vidx, n - to_ndim(Point3f, ntuple(i-> lverts[vidx, i], n), 0.0) + to_ndim(Point3f, ntuple(i -> lverts[vidx, i], n), 0.0) end end -end ################################################################################ @@ -748,9 +696,9 @@ 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)) function to_color(p::Palette) @@ -765,9 +713,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 @@ -812,11 +760,9 @@ convert_attribute(A::AbstractVector, ::key"linestyle") = A """ A `Symbol` equal to `:dash`, `:dot`, `:dashdot`, `:dashdotdot` """ -convert_attribute(ls::Union{Symbol,AbstractString}, ::key"linestyle") = line_pattern(ls, :normal) +convert_attribute(ls::Union{Symbol, AbstractString}, ::key"linestyle") = line_pattern(ls, :normal) -function convert_attribute(ls::Tuple{<:Union{Symbol,AbstractString},<:Any}, ::key"linestyle") - line_pattern(ls[1], ls[2]) -end +convert_attribute(ls::Tuple{<:Union{Symbol, AbstractString}, <:Any}, ::key"linestyle") = line_pattern(ls[1], ls[2]) function line_pattern(linestyle, gaps) pattern = line_diff_pattern(linestyle, gaps) @@ -825,7 +771,7 @@ end "The linestyle patterns are inspired by the LaTeX package tikZ as seen here https://tex.stackexchange.com/questions/45275/tikz-get-values-for-predefined-dash-patterns." -function line_diff_pattern(ls::Symbol, gaps = :normal) +line_diff_pattern(ls::Symbol, gaps = :normal) = if ls == :solid nothing elseif ls == :dash @@ -846,7 +792,6 @@ function line_diff_pattern(ls::Symbol, gaps = :normal) """ ) end -end function line_diff_pattern(ls_str::AbstractString, gaps = :normal) dot = 1 @@ -858,7 +803,7 @@ function line_diff_pattern(ls_str::AbstractString, gaps = :normal) pattern = Float64[] for i in 1:length(ls_str) curr_char = ls_str[i] - next_char = i == lastindex(ls_str) ? ls_str[firstindex(ls_str)] : ls_str[i+1] + next_char = i == lastindex(ls_str) ? ls_str[firstindex(ls_str)] : ls_str[i + 1] # push dash or dot if curr_char == '-' push!(pattern, dash) @@ -884,27 +829,27 @@ function check_line_pattern(ls_str) end function convert_gaps(gaps) - error_msg = "You provided the gaps modifier $gaps when specifying the linestyle. The modifier must be `∈ ([:normal, :dense, :loose])`, a real number or a collection of two real numbers." - if gaps isa Symbol - gaps in [:normal, :dense, :loose] || throw(ArgumentError(error_msg)) - dot_gaps = (normal = 2, dense = 1, loose = 4) - dash_gaps = (normal = 3, dense = 2, loose = 6) - - dot_gap = getproperty(dot_gaps, gaps) - dash_gap = getproperty(dash_gaps, gaps) - elseif gaps isa Real - dot_gap = gaps - dash_gap = gaps - elseif length(gaps) == 2 && eltype(gaps) <: Real - dot_gap, dash_gap = gaps - else - throw(ArgumentError(error_msg)) - end - (dot_gap = dot_gap, dash_gap = dash_gap) + error_msg = "You provided the gaps modifier $gaps when specifying the linestyle. The modifier must be `∈ ([:normal, :dense, :loose])`, a real number or a collection of two real numbers." + if gaps isa Symbol + gaps in [:normal, :dense, :loose] || throw(ArgumentError(error_msg)) + dot_gaps = (normal = 2, dense = 1, loose = 4) + dash_gaps = (normal = 3, dense = 2, loose = 6) + + dot_gap = getproperty(dot_gaps, gaps) + dash_gap = getproperty(dash_gaps, gaps) + elseif gaps isa Real + dot_gap = gaps + dash_gap = gaps + elseif length(gaps) == 2 && eltype(gaps) <: Real + dot_gap, dash_gap = gaps + else + throw(ArgumentError(error_msg)) + end + (dot_gap = dot_gap, dash_gap = dash_gap) end -convert_attribute(c::Tuple{<: Number, <: Number}, ::key"position") = Point2f(c[1], c[2]) -convert_attribute(c::Tuple{<: Number, <: Number, <: Number}, ::key"position") = Point3f(c) +convert_attribute(c::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) """ @@ -936,7 +881,7 @@ function to_font(x::String) end fontpath = assetpath("fonts") - font = FreeTypeAbstraction.findfont(str; additional_fonts=fontpath) + font = FreeTypeAbstraction.findfont(str; additional_fonts = fontpath) if font === nothing @warn("Could not find font $str, using TeX Gyre Heros Makie") if "tex gyre heros makie" == lowercase(str) @@ -975,7 +920,7 @@ to_font(fonts::Attributes, x) = to_font(x) to_rotation(s::Quaternionf) = s to_rotation(s::Quaternion) = Quaternionf(s.data...) -function to_rotation(s::VecTypes{N}) where N +to_rotation(s::VecTypes{N}) where N = if N == 4 Quaternionf(s...) elseif N == 3 @@ -985,12 +930,11 @@ function to_rotation(s::VecTypes{N}) where N else error("The $N dimensional vector $s can't be converted to a rotation.") end -end 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) @@ -1040,16 +984,14 @@ 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 return cols[1:categories] end -function categorical_colors(cols::AbstractVector, categories::Integer) - return categorical_colors(to_color.(cols), categories) -end +categorical_colors(cols::AbstractVector, categories::Integer) = categorical_colors(to_color.(cols), categories) function categorical_colors(cs::Union{String, Symbol}, categories::Integer) cs_string = string(cs) @@ -1088,9 +1030,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 @@ -1134,7 +1076,7 @@ end Enum values: `IsoValue` `Absorption` `MaximumIntensityProjection` `AbsorptionRGBA` `AdditiveRGBA` `IndexedAbsorptionRGBA` """ -function convert_attribute(value, ::key"algorithm") +convert_attribute(value, ::key"algorithm") = if isa(value, RaymarchAlgorithm) return Int32(value) elseif isa(value, Int32) && value in 0:5 @@ -1144,7 +1086,6 @@ function convert_attribute(value, ::key"algorithm") else error("$value is not a valid volume algorithm. Please have a look at the docstring of `to_volume_algorithm` (in the REPL, `?to_volume_algorithm`).") end -end """ Symbol/String: iso, absorption, mip, absorptionrgba, indexedabsorption @@ -1159,8 +1100,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 const DEFAULT_MARKER_MAP = Dict{Symbol, BezierPath}() @@ -1179,20 +1120,20 @@ function default_marker_map() if isempty(DEFAULT_MARKER_MAP) size_factor = 0.75 DEFAULT_MARKER_MAP[:rect] = scale(BezierSquare, size_factor) - DEFAULT_MARKER_MAP[:diamond] = scale(rotate(BezierSquare, pi/4), size_factor) - DEFAULT_MARKER_MAP[:hexagon] = scale(bezier_ngon(6, 0.5, pi/2), size_factor) + DEFAULT_MARKER_MAP[:diamond] = scale(rotate(BezierSquare, pi / 4), size_factor) + DEFAULT_MARKER_MAP[:hexagon] = scale(bezier_ngon(6, 0.5, pi / 2), size_factor) DEFAULT_MARKER_MAP[:cross] = scale(BezierCross, size_factor) DEFAULT_MARKER_MAP[:xcross] = scale(BezierX, size_factor) DEFAULT_MARKER_MAP[:utriangle] = scale(BezierUTriangle, size_factor) DEFAULT_MARKER_MAP[:dtriangle] = scale(BezierDTriangle, size_factor) DEFAULT_MARKER_MAP[:ltriangle] = scale(BezierLTriangle, size_factor) DEFAULT_MARKER_MAP[:rtriangle] = scale(BezierRTriangle, size_factor) - DEFAULT_MARKER_MAP[:pentagon] = scale(bezier_ngon(5, 0.5, pi/2), size_factor) - DEFAULT_MARKER_MAP[:octagon] = scale(bezier_ngon(8, 0.5, pi/2), size_factor) - DEFAULT_MARKER_MAP[:star4] = scale(bezier_star(4, 0.25, 0.6, pi/2), size_factor) - DEFAULT_MARKER_MAP[:star5] = scale(bezier_star(5, 0.28, 0.6, pi/2), size_factor) - DEFAULT_MARKER_MAP[:star6] = scale(bezier_star(6, 0.30, 0.6, pi/2), size_factor) - DEFAULT_MARKER_MAP[:star8] = scale(bezier_star(8, 0.33, 0.6, pi/2), size_factor) + DEFAULT_MARKER_MAP[:pentagon] = scale(bezier_ngon(5, 0.5, pi / 2), size_factor) + DEFAULT_MARKER_MAP[:octagon] = scale(bezier_ngon(8, 0.5, pi / 2), size_factor) + DEFAULT_MARKER_MAP[:star4] = scale(bezier_star(4, 0.25, 0.6, pi / 2), size_factor) + DEFAULT_MARKER_MAP[:star5] = scale(bezier_star(5, 0.28, 0.6, pi / 2), size_factor) + DEFAULT_MARKER_MAP[:star6] = scale(bezier_star(6, 0.30, 0.6, pi / 2), size_factor) + DEFAULT_MARKER_MAP[:star8] = scale(bezier_star(8, 0.33, 0.6, pi / 2), size_factor) DEFAULT_MARKER_MAP[:vline] = scale(scale(BezierSquare, (0.2, 1.0)), size_factor) DEFAULT_MARKER_MAP[:hline] = scale(scale(BezierSquare, (1.0, 0.2)), size_factor) DEFAULT_MARKER_MAP[:+] = scale(BezierCross, size_factor) @@ -1236,16 +1177,14 @@ 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) to_spritemarker(b) = error("Not a valid scatter marker: $(typeof(b))") -function to_spritemarker(str::String) - error("Using strings for multiple char markers is deprecated. Use `collect(string)` or `['x', 'o', ...]` instead. Found: $(str)") -end +to_spritemarker(str::String) = error("Using strings for multiple char markers is deprecated. Use `collect(string)` or `['x', 'o', ...]` instead. Found: $(str)") """ to_spritemarker(b, marker::Char) @@ -1257,24 +1196,23 @@ 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()` """ -function to_spritemarker(marker::Symbol) +to_spritemarker(marker::Symbol) = if haskey(default_marker_map(), marker) return to_spritemarker(default_marker_map()[marker]) else @warn("Unsupported marker: $marker, using ● instead") return '●' end -end @@ -1283,14 +1221,11 @@ convert_attribute(value, ::key"marker", ::key"scatter") = to_spritemarker(value) convert_attribute(value, ::key"isovalue", ::key"volume") = Float32(value) convert_attribute(value, ::key"isorange", ::key"volume") = Float32(value) -function convert_attribute(value::Symbol, ::key"marker", ::key"meshscatter") +convert_attribute(value::Symbol, ::key"marker", ::key"meshscatter") = if value == :Sphere - return normal_mesh(Sphere(Point3f(0), 1f0)) + return normal_mesh(Sphere(Point3f(0), 1.0f0)) else error("Unsupported marker: $(value)") end -end -function convert_attribute(value::AbstractGeometry, ::key"marker", ::key"meshscatter") - return normal_mesh(value) -end +convert_attribute(value::AbstractGeometry, ::key"marker", ::key"meshscatter") = normal_mesh(value) diff --git a/src/deprecated.jl b/src/deprecated.jl index 5bc7fe2b141..86380ca4a7f 100644 --- a/src/deprecated.jl +++ b/src/deprecated.jl @@ -1,9 +1,5 @@ -function register_backend!(backend) - @warn("`register_backend!` is an internal deprecated function, which shouldn't be used outside Makie. - if you must really use this function, it's now `set_active_backend!(::Module)") -end +register_backend!(backend) = @warn("`register_backend!` is an internal deprecated function, which shouldn't be used outside Makie. + if you must really use this function, it's now `set_active_backend!(::Module)") -function backend_display(args...) - @warn("`backend_display` is an internal deprecated function, which shouldn't be used outside Makie. - if you must really use this function, it's now just `display(::Backend.Screen, figlike)`") -end +backend_display(args...) = @warn("`backend_display` is an internal deprecated function, which shouldn't be used outside Makie. + if you must really use this function, it's now just `display(::Backend.Screen, figlike)`") diff --git a/src/display.jl b/src/display.jl index 6ba313ee9c0..a3ddd5a9a50 100644 --- a/src/display.jl +++ b/src/display.jl @@ -15,9 +15,7 @@ function set_active_backend!(backend::Union{Missing, Module}) return end -function push_screen!(scene::Scene, display) - error("$(display) not a valid Makie display.") -end +push_screen!(scene::Scene, display) = error("$(display) not a valid Makie display.") """ push_screen!(scene::Scene, screen::MakieScreen) @@ -38,7 +36,7 @@ function push_screen!(scene::Scene, screen::MakieScreen) # Now we push the screen :) push!(scene.current_screens, screen) deregister = nothing - deregister = on(events(scene).window_open, priority=typemax(Int)) do is_open + deregister = on(events(scene).window_open, priority = typemax(Int)) do is_open # when screen closes, it should set the scene isopen event to false # so that's when we can remove the screen if !is_open @@ -59,7 +57,7 @@ Removes screen from scene and cleans up screen function delete_screen!(scene::Scene, screen::MakieScreen) delete!(screen, scene) empty!(screen) - filter!(x-> x !== screen, scene.current_screens) + filter!(x -> x !== screen, scene.current_screens) return end @@ -103,9 +101,7 @@ Only case Makie always shows the plot inside the plotpane is when using VSCode e If you want to always force inlining the plot into the plotpane, set `inline!(true)` (E.g. when run in the VSCode REPL). In other cases `inline!(true/false)` won't do anything. """ -function inline!(inline=true) - ALWAYS_INLINE_PLOTS[] = inline -end +inline!(inline = true) = ALWAYS_INLINE_PLOTS[] = inline """ Base.display(figlike::FigureLike; backend=current_backend(), screen_config...) @@ -115,7 +111,7 @@ Displays the figurelike in a window or the browser, depending on the backend. The parameters for `screen_config` are backend dependend, see `?Backend.Screen` or `Base.doc(Backend.Screen)` for applicable options. """ -function Base.display(figlike::FigureLike; backend=current_backend(), update=true, screen_config...) +function Base.display(figlike::FigureLike; backend = current_backend(), update = true, screen_config...) if ismissing(backend) error(""" No backend available! @@ -142,7 +138,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...) @@ -176,9 +172,7 @@ function backend_show(backend, io::IO, ::MIME"text/plain", scene::Scene) return end -function Base.show(io::IO, ::MIME"text/plain", scene::Scene) - show(io, scene) -end +Base.show(io::IO, ::MIME"text/plain", scene::Scene) = show(io, scene) function Base.show(io::IO, m::MIME, figlike::FigureLike) scene = get_scene(figlike) @@ -225,19 +219,17 @@ 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. - `px_per_unit`: The size of one scene unit in `px` when exporting to a bitmap format. This provides a mechanism to export the same scene with higher or lower resolution. """ -function FileIO.save( - filename::String, fig::FigureLike; args... - ) - FileIO.save(FileIO.query(filename), fig; args...) -end +FileIO.save( + filename::String, fig::FigureLike; args... +) = FileIO.save(FileIO.query(filename), fig; args...) function FileIO.save( - file::FileIO.Formatted, fig::FigureLike; - resolution = size(get_scene(fig)), - backend = current_backend(), - update = true, - screen_config... - ) + file::FileIO.Formatted, fig::FigureLike; + resolution = size(get_scene(fig)), + backend = current_backend(), + update = true, + screen_config... +) scene = get_scene(fig) if resolution != size(scene) resize!(scene, resolution) @@ -257,12 +249,12 @@ function FileIO.save( # If the scene already got displayed, we get the current screen its displayed on # Else, we create a new scene and update the state of the fig update && update_state_before_display!(fig) - screen = getscreen(backend, scene, io, mime; visible=false, screen_config...) + screen = getscreen(backend, scene, io, mime; visible = false, screen_config...) backend_show(screen, io, mime, scene) end catch e # So, if open(io-> error(...), "w"), the file will get created, but not removed... - isfile(filename) && rm(filename; force=true) + isfile(filename) && rm(filename; force = true) rethrow(e) end end @@ -272,26 +264,22 @@ raw_io(io::IO) = io raw_io(io::IOContext) = raw_io(io.io) # This has to be overloaded by the backend for its screen type. -function colorbuffer(x::MakieScreen) - error("colorbuffer not implemented for screen $(typeof(x))") -end - -function jl_to_gl_format(image) - @static if VERSION < v"1.6" - d1, d2 = size(image) - bufc = Array{eltype(image)}(undef, d2, d1) #permuted - ind1, ind2 = axes(image) - n = first(ind1) + last(ind1) - for i in ind1 - @simd for j in ind2 - @inbounds bufc[j, n-i] = image[i, j] - end +colorbuffer(x::MakieScreen) = error("colorbuffer not implemented for screen $(typeof(x))") + +jl_to_gl_format(image) = @static if VERSION < v"1.6" + d1, d2 = size(image) + bufc = Array{eltype(image)}(undef, d2, d1) #permuted + ind1, ind2 = axes(image) + n = first(ind1) + last(ind1) + for i in ind1 + @simd for j in ind2 + @inbounds bufc[j, n - i] = image[i, j] end - return bufc - else - reverse!(image; dims=1) - return PermutedDimsArray(image, (2, 1)) end + return bufc +else + reverse!(image; dims = 1) + return PermutedDimsArray(image, (2, 1)) end # less specific for overloading by backends @@ -335,10 +323,10 @@ or RGBA. used in FFMPEG without conversion - `screen_config`: Backend dependend, look up via `?Backend.Screen`/`Base.doc(Backend.Screen)` """ -function colorbuffer(fig::FigureLike, format::ImageStorageFormat = JuliaNative; update=true, backend = current_backend(), screen_config...) +function colorbuffer(fig::FigureLike, format::ImageStorageFormat = JuliaNative; update = true, backend = current_backend(), screen_config...) scene = get_scene(fig) update && update_state_before_display!(fig) - screen = getscreen(backend, scene, format; start_renderloop=false, visible=false, screen_config...) + screen = getscreen(backend, scene, format; start_renderloop = false, visible = false, screen_config...) return colorbuffer(screen, format) end diff --git a/src/documentation/docstringextension.jl b/src/documentation/docstringextension.jl index 25d991af9d4..6a67524db29 100644 --- a/src/documentation/docstringextension.jl +++ b/src/documentation/docstringextension.jl @@ -11,8 +11,8 @@ struct DocThemer <: DocStringExtensions.Abbreviation end const ATTRIBUTES = DocThemer() function DocStringExtensions.format(::DocThemer, buf, doc) - binding = doc.data[:binding] |> Docs.resolve - help_attributes(buf, binding; extended=true) + binding = Docs.resolve(doc.data[:binding]) + help_attributes(buf, binding; extended = true) end ############################################################ diff --git a/src/documentation/documentation.jl b/src/documentation/documentation.jl index ce83835cd4c..5af47d945eb 100644 --- a/src/documentation/documentation.jl +++ b/src/documentation/documentation.jl @@ -48,9 +48,7 @@ function _help(io::IO, input::Type{T}; extended = false) where T <: AbstractPlot end end -function _help(io::IO, input::Function; extended = false) - _help(io, to_type(input); extended = extended) -end +_help(io::IO, input::Function; extended = false) = _help(io, to_type(input); extended = extended) """ help_arguments([io], func) @@ -151,9 +149,7 @@ function help_attributes(io::IO, Typ::Type{T}; extended = false) where T <: Abst println(io, "```") end -function help_attributes(io::IO, func::Function; extended = false) - help_attributes(io, to_type(func); extended = extended) -end +help_attributes(io::IO, func::Function; extended = false) = help_attributes(io, to_type(func); extended = extended) function help_attributes(io::IO, Typ::Type{T}; extended = false) where T <: Axis3D if extended @@ -174,9 +170,7 @@ end Maps the input of a Type name to its cooresponding function. """ -function to_func(Typ::Type{<: AbstractPlot{F}}) where F - F -end +to_func(Typ::Type{<:AbstractPlot{F}}) where F = F to_func(func::Function) = func @@ -195,9 +189,7 @@ to_type(Typ::Type{T}) where T <: AbstractPlot = Typ Turns the input of a function name or plot Type into a string. """ -function to_string(func::Function) - str = string(typeof(func).name.mt.name) -end +to_string(func::Function) = str = string(typeof(func).name.mt.name) to_string(Typ::Type{T}) where T <: AbstractPlot = to_string(to_func(Typ)) to_string(s::Symbol) = string(s) @@ -211,9 +203,9 @@ in a nicely-indented format. Use the optional `extended = true` keyword argument to see more details. """ -function print_rec(io::IO, dict, indent::Int = 1; extended = false) +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) @@ -229,4 +221,3 @@ function print_rec(io::IO, dict, indent::Int = 1; extended = false) println(io, v) end end -end diff --git a/src/event-recorder.jl b/src/event-recorder.jl index 4fe6eab44d7..32df131334e 100644 --- a/src/event-recorder.jl +++ b/src/event-recorder.jl @@ -7,11 +7,11 @@ for `scene` and serializes them to `path`. """ function record_events(f, scene::Scene, path::String) display(scene) - result = Vector{Pair{Float64,Pair{Symbol,Any}}}() + result = Vector{Pair{Float64, Pair{Symbol, Any}}}() for field in fieldnames(Events) # These are not Observables (field == :mousebuttonstate || field == :keyboardstate) && continue - on(getfield(scene.events, field); priority=typemax(Int)) do value + on(getfield(scene.events, field); priority = typemax(Int)) do value value = isa(value, Set) ? copy(value) : value push!(result, time() => (field => value)) return Consume(false) @@ -32,7 +32,7 @@ Replays the serialized events recorded with `record_events` in `path` in `scene` replay_events(scene::Scene, path::String) = replay_events(() -> nothing, scene, path) function replay_events(f, scene::Scene, path::String) events = open(io -> deserialize(io), path) - sort!(events; by=first) + sort!(events; by = first) for i in 1:length(events) t1, (field, value) = events[i] (field == :mousebuttonstate || field == :keyboardstate) && continue diff --git a/src/ffmpeg-util.jl b/src/ffmpeg-util.jl index e44e3038c7c..e0e846bd575 100644 --- a/src/ffmpeg-util.jl +++ b/src/ffmpeg-util.jl @@ -33,17 +33,17 @@ applies to `mp4`. Defaults to `yuv444p` for `profile = high444`. struct VideoStreamOptions format::String framerate::Int - compression::Union{Nothing,Int} - profile::Union{Nothing,String} - pixel_format::Union{Nothing,String} + compression::Union{Nothing, Int} + profile::Union{Nothing, String} + pixel_format::Union{Nothing, String} loglevel::String input::String rawvideo::Bool function VideoStreamOptions( - format::AbstractString, framerate::Integer, compression, profile, - pixel_format, loglevel::String, input::String, rawvideo::Bool=true) + format::AbstractString, framerate::Integer, compression, profile, + pixel_format, loglevel::String, input::String, rawvideo::Bool = true) if format == "mp4" (profile === nothing) && (profile = "high422") @@ -56,8 +56,8 @@ struct VideoStreamOptions # items are name, value, allowed_formats allowed_kwargs = [("compression", compression, ("mp4", "webm")), - ("profile", profile, ("mp4",)), - ("pixel_format", pixel_format, ("mp4",))] + ("profile", profile, ("mp4",)), + ("pixel_format", pixel_format, ("mp4",))] for (name, value, allowed_formats) in allowed_kwargs if !(format in allowed_formats) && value !== nothing @@ -91,11 +91,9 @@ struct VideoStreamOptions end end -function VideoStreamOptions(; format="mp4", framerate=24, compression=nothing, profile=nothing, pixel_format=nothing, loglevel="quiet", input="pipe:0", rawvideo=true) - return VideoStreamOptions(format, framerate, compression, profile, pixel_format, loglevel, input, rawvideo) -end +VideoStreamOptions(; format = "mp4", framerate = 24, compression = nothing, profile = nothing, pixel_format = nothing, loglevel = "quiet", input = "pipe:0", rawvideo = true) = VideoStreamOptions(format, framerate, compression, profile, pixel_format, loglevel, input, rawvideo) -function to_ffmpeg_cmd(vso::VideoStreamOptions, xdim::Integer=0, ydim::Integer=0) +function to_ffmpeg_cmd(vso::VideoStreamOptions, xdim::Integer = 0, ydim::Integer = 0) # explanation of ffmpeg args. note that the order of args is important; args pertaining # to the input have to go before -i and args pertaining to the output have to go after. # -y: "yes", overwrite any existing without confirmation @@ -199,15 +197,15 @@ $(Base.doc(VideoStreamOptions)) * `screen_config...`: See `?Backend.Screen` or `Base.doc(Backend.Screen)` for applicable options that can be passed and forwarded to the backend. """ function VideoStream(fig::FigureLike; - format="mp4", framerate=24, compression=nothing, profile=nothing, pixel_format=nothing, loglevel="quiet", - visible=false, connect=false, backend=current_backend(), - screen_config...) + format = "mp4", framerate = 24, compression = nothing, profile = nothing, pixel_format = nothing, loglevel = "quiet", + visible = false, connect = false, backend = current_backend(), + screen_config...) dir = mktempdir() path = joinpath(dir, "$(gensym(:video)).$(format)") scene = get_scene(fig) update_state_before_display!(fig) - screen = getscreen(backend, scene, GLNative; visible=visible, start_renderloop=false, screen_config...) + screen = getscreen(backend, scene, GLNative; visible = visible, start_renderloop = false, screen_config...) _xdim, _ydim = size(screen) xdim = iseven(_xdim) ? _xdim : _xdim + 1 ydim = iseven(_ydim) ? _ydim : _ydim + 1 @@ -251,7 +249,7 @@ function save(path::String, io::VideoStream; video_options...) # Maybe warn? convert_video(io.path, path; video_options...) else - cp(io.path, path; force=true) + cp(io.path, path; force = true) end rm(io.path) return path @@ -260,12 +258,12 @@ end function convert_video(input_path, output_path; video_options...) p, typ = splitext(output_path) format = lstrip(typ, '.') - vso = VideoStreamOptions(; format=format, input=input_path, rawvideo=false, video_options...) + vso = VideoStreamOptions(; format = format, input = input_path, rawvideo = false, video_options...) cmd = to_ffmpeg_cmd(vso) @ffmpeg_env run(`$cmd $output_path`) end -function extract_frames(video, frame_folder; loglevel="quiet") +function extract_frames(video, frame_folder; loglevel = "quiet") path = joinpath(frame_folder, "frame%04d.png") FFMPEG.ffmpeg_exe(`-loglevel $(loglevel) -i $video -y $path`) end diff --git a/src/figureplotting.jl b/src/figureplotting.jl index 1c71419006a..dc314a1ba59 100644 --- a/src/figureplotting.jl +++ b/src/figureplotting.jl @@ -11,7 +11,7 @@ Base.iterate(ap::AxisPlot, args...) = iterate((ap.axis, ap.plot), args...) get_scene(ap::AxisPlot) = get_scene(ap.axis.scene) -function _validate_nt_like_keyword(@nospecialize(kw), name) +_validate_nt_like_keyword(@nospecialize(kw), name) = if !(kw isa NamedTuple || kw isa AbstractDict{Symbol} || kw isa Attributes) throw(ArgumentError(""" The $name keyword argument received an unexpected value $(repr(kw)). @@ -20,16 +20,14 @@ function _validate_nt_like_keyword(@nospecialize(kw), name) Write (key = value,) or (; key = value) instead.""" )) end -end -function _disallow_keyword(kw, attributes) +_disallow_keyword(kw, attributes) = if haskey(attributes, kw) throw(ArgumentError("You cannot pass `$kw` as a keyword argument to this plotting function. Note that `axis` can only be passed to non-mutating plotting functions (not ending with a `!`) that implicitly create an axis, and `figure` only to those that implicitly create a `Figure`.")) end -end function plot(P::PlotFunc, args...; axis = NamedTuple(), figure = NamedTuple(), kw_attributes...) - + _validate_nt_like_keyword(axis, "axis") _validate_nt_like_keyword(figure, "figure") @@ -118,7 +116,7 @@ end function plot(P::PlotFunc, gsp::GridSubposition, args...; axis = NamedTuple(), kwargs...) _validate_nt_like_keyword(axis, "axis") - + layout = GridLayoutBase.get_layout_at!(gsp.parent, createmissing = true) c = contents(gsp, exact = true) if !isempty(c) @@ -177,4 +175,4 @@ function update_state_before_display!(f::Figure) update_state_before_display!(c) end return -end \ No newline at end of file +end diff --git a/src/figures.jl b/src/figures.jl index b1b212c367d..e224004acd7 100644 --- a/src/figures.jl +++ b/src/figures.jl @@ -44,9 +44,7 @@ function current_axis!(fig::Figure, ax) fig.current_axis[] = ax ax end -function current_axis!(fig::Figure, ::Nothing) - fig.current_axis[] = nothing -end +current_axis!(fig::Figure, ::Nothing) = fig.current_axis[] = nothing function current_axis!(ax) fig = ax.parent if !(fig isa Figure) @@ -67,7 +65,7 @@ function Figure(; kwargs...) kwargs_dict = Dict(kwargs) padding = pop!(kwargs_dict, :figure_padding, current_default_theme()[:figure_padding]) - scene = Scene(; camera=campixel!, kwargs_dict...) + scene = Scene(; camera = campixel!, kwargs_dict...) padding = padding isa Observable ? padding : Observable{Any}(padding) alignmode = lift(Outside ∘ to_rectsides, padding) @@ -96,9 +94,7 @@ end export Figure, current_axis, current_figure, current_axis!, current_figure! -function Base.getindex(fig::Figure, rows, cols, side = GridLayoutBase.Inner()) - fig.layout[rows, cols, side] -end +Base.getindex(fig::Figure, rows, cols, side = GridLayoutBase.Inner()) = fig.layout[rows, cols, side] function Base.setindex!(fig::Figure, obj, rows, cols, side = GridLayoutBase.Inner()) fig.layout[rows, cols, side] = obj diff --git a/src/interaction/events.jl b/src/interaction/events.jl index 0a28e6a6cde..67f976fcf63 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 @@ -174,30 +174,22 @@ And(x) = x Or(x) = x -function Base.:(&)( - 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} - ) - And(left, right) -end -function Base.:(|)( - 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} - ) - Or(left, right) -end +Base.:(&)( + left::Union{BooleanOperator, Keyboard.Button, Mouse.Button}, + right::Union{BooleanOperator, Keyboard.Button, Mouse.Button, Bool} +) = And(left, right) +Base.:(&)( + left::Bool, + right::Union{BooleanOperator, Keyboard.Button, Mouse.Button} +) = And(left, right) +Base.:(|)( + left::Union{BooleanOperator, Keyboard.Button, Mouse.Button}, + right::Union{BooleanOperator, Keyboard.Button, Mouse.Button, Bool} +) = Or(left, right) +Base.:(|)( + left::Bool, + right::Union{BooleanOperator, Keyboard.Button, Mouse.Button} +) = Or(left, right) Base.:(!)(x::Union{BooleanOperator, Keyboard.Button, Mouse.Button}) = Not(x) @@ -209,15 +201,11 @@ 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)] -end +create_sets(x::And) = [union(left, right) for left in create_sets(x.left) + for right in create_sets(x.right)] 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,))] -end +create_sets(b::Union{Keyboard.Button, Mouse.Button}) = [Set{Union{Keyboard.Button, Mouse.Button}}((b,))] create_sets(s::Set) = [Set{Union{Keyboard.Button, Mouse.Button}}(s)] @@ -261,7 +249,7 @@ ispressed(scene, key::Keyboard.Button) = ispressed(events(scene), key) # Boolean Operator evaluation ispressed(scene, op::And) = ispressed(scene, op.left) && ispressed(scene, op.right) -ispressed(scene, op::Or) = ispressed(scene, op.left) || ispressed(scene, op.right) +ispressed(scene, op::Or) = ispressed(scene, op.left) || ispressed(scene, op.right) ispressed(scene, op::Not) = !ispressed(scene, op.x) ispressed(scene::Scene, op::Exclusively) = ispressed(events(scene), op) ispressed(e::Events, op::Exclusively) = op.x == union(e.keyboardstate, e.mousebuttonstate) diff --git a/src/interaction/inspector.jl b/src/interaction/inspector.jl index 6d02b191f81..66dc416c8a4 100644 --- a/src/interaction/inspector.jl +++ b/src/interaction/inspector.jl @@ -37,13 +37,12 @@ end color2text(c::AbstractFloat) = @sprintf("%0.3f", c) color2text(c::Symbol) = string(c) color2text(c) = color2text(to_color(c)) -function color2text(c::RGBAf) +color2text(c::RGBAf) = if c.alpha == 1.0 @sprintf("RGB(%0.2f, %0.2f, %0.2f)", c.r, c.g, c.b) else @sprintf("RGBA(%0.2f, %0.2f, %0.2f, %0.2f)", c.r, c.g, c.b, c.alpha) end -end color2text(name, i::Integer, j::Integer, c) = "$name[$i, $j] = $(color2text(c))" function color2text(name, i, j, c) @@ -69,7 +68,8 @@ _to_rotation(x::Vector, idx) = to_rotation(x[idx]) function closest_point_on_line(p0::Point2f, p1::Point2f, r::Point2f) # This only works in 2D - AP = P .- A; AB = B .- A + AP = P .- A + AB = B .- A A .+ AB * dot(AP, AB) / dot(AB, AB) end @@ -81,16 +81,16 @@ function view_ray(inv_view_proj, mpos, area::Rect2) # This figures out the camera view direction from the projectionview matrix (?) # and computes a ray from a near and a far point. # Based on ComputeCameraRay from ImGuizmo - mp = 2f0 .* (mpos .- minimum(area)) ./ widths(area) .- 1f0 + mp = 2.0f0 .* (mpos .- minimum(area)) ./ widths(area) .- 1.0f0 v = inv_view_proj * Vec4f(0, 0, -10, 1) reversed = v[3] < v[4] - near = reversed ? 1f0 - 1e-6 : 0f0 - far = reversed ? 0f0 : 1f0 - 1e-6 + near = reversed ? 1.0f0 - 1e-6 : 0.0f0 + far = reversed ? 0.0f0 : 1.0f0 - 1e-6 - origin = inv_view_proj * Vec4f(mp[1], mp[2], near, 1f0) + origin = inv_view_proj * Vec4f(mp[1], mp[2], near, 1.0f0) origin = origin[Vec(1, 2, 3)] ./ origin[4] - p = inv_view_proj * Vec4f(mp[1], mp[2], far, 1f0) + p = inv_view_proj * Vec4f(mp[1], mp[2], far, 1.0f0) p = p[Vec(1, 2, 3)] ./ p[4] dir = normalize(p .- origin) @@ -99,14 +99,12 @@ end # These work in 2D and 3D -function closest_point_on_line(A, B, origin, dir) - closest_point_on_line( - to_ndim(Point3f, A, 0), - to_ndim(Point3f, B, 0), - to_ndim(Point3f, origin, 0), - to_ndim(Vec3f, dir, 0) - ) -end +closest_point_on_line(A, B, origin, dir) = closest_point_on_line( + to_ndim(Point3f, A, 0), + to_ndim(Point3f, B, 0), + to_ndim(Point3f, origin, 0), + to_ndim(Vec3f, dir, 0) +) function closest_point_on_line(A::Point3f, B::Point3f, origin::Point3f, dir::Vec3f) # See: # https://en.wikipedia.org/wiki/Line%E2%80%93plane_intersection @@ -141,11 +139,11 @@ end ### Surface positions ######################################## -surface_x(xs::ClosedInterval, i, j, N) = minimum(xs) + (maximum(xs) - minimum(xs)) * (i-1) / (N-1) +surface_x(xs::ClosedInterval, i, j, N) = minimum(xs) + (maximum(xs) - minimum(xs)) * (i - 1) / (N - 1) surface_x(xs, i, j, N) = xs[i] surface_x(xs::AbstractMatrix, i, j, N) = xs[i, j] -surface_y(ys::ClosedInterval, i, j, N) = minimum(ys) + (maximum(ys) - minimum(ys)) * (j-1) / (N-1) +surface_y(ys::ClosedInterval, i, j, N) = minimum(ys) + (maximum(ys) - minimum(ys)) * (j - 1) / (N - 1) surface_y(ys, i, j, N) = ys[j] surface_y(ys::AbstractMatrix, i, j, N) = ys[i, j] @@ -184,13 +182,11 @@ end ## Shifted projection ######################################## -function shift_project(scene, plot, pos) - project( - camera(scene).projectionview[], - Vec2f(widths(pixelarea(scene)[])), - apply_transform(transform_func(plot), pos, to_value(get(plot, :space, :data))) - ) .+ Vec2f(origin(pixelarea(scene)[])) -end +shift_project(scene, plot, pos) = project( + camera(scene).projectionview[], + Vec2f(widths(pixelarea(scene)[])), + apply_transform(transform_func(plot), pos, to_value(get(plot, :space, :data))) +) .+ Vec2f(origin(pixelarea(scene)[])) @@ -227,9 +223,7 @@ function cleanup(inspector::DataInspector) inspector end -function Base.delete!(::Union{Scene, Figure}, inspector::DataInspector) - cleanup(inspector) -end +Base.delete!(::Union{Scene, Figure}, inspector::DataInspector) = cleanup(inspector) enable!(inspector::DataInspector) = inspector.attributes.enabled[] = true disable!(inspector::DataInspector) = inspector.attributes.enabled[] = false @@ -259,9 +253,7 @@ returning a label. See Makie documentation for more detail. tooltip is always in front. - and all attributes from `Tooltip` """ -function DataInspector(fig_or_block; kwargs...) - DataInspector(get_scene(fig_or_block); kwargs...) -end +DataInspector(fig_or_block; kwargs...) = DataInspector(get_scene(fig_or_block); kwargs...) function DataInspector(scene::Scene; priority = 100, kwargs...) parent = root(scene) @@ -274,7 +266,7 @@ function DataInspector(scene::Scene; priority = 100, kwargs...) enabled = pop!(attrib_dict, :enabled, true), depth = pop!(attrib_dict, :depth, 9e3), enable_indicators = pop!(attrib_dict, :show_bbox_indicators, true), - offset = get(attrib_dict, :offset, 10f0), + offset = get(attrib_dict, :offset, 10.0f0), # Settings for indicators (plots that highlight the current selection) indicator_color = pop!(attrib_dict, :indicator_color, :red), @@ -285,10 +277,10 @@ function DataInspector(scene::Scene; priority = 100, kwargs...) indicator_visible = false, # General reusable - _color = RGBAf(0,0,0,0), + _color = RGBAf(0, 0, 0, 0), ) - plot = tooltip!(parent, Observable(Point2f(0)), text = Observable(""); visible=false, attrib_dict...) + plot = tooltip!(parent, Observable(Point2f(0)), text = Observable(""); visible = false, attrib_dict...) on(z -> translate!(plot, 0, 0, z), base_attrib.depth) notify(base_attrib.depth) @@ -382,7 +374,7 @@ function show_data_recursion(inspector, plot::AbstractPlot, idx, source) if processed inspector.selection = plot end - + return processed end end @@ -401,9 +393,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 @@ -523,7 +515,7 @@ function show_data(inspector::DataInspector, plot::Union{Lines, LineSegments}, i scene = parent_scene(plot) # cast ray from cursor into screen, find closest point to line - p0, p1 = plot[1][][idx-1:idx] + p0, p1 = plot[1][][(idx - 1):idx] origin, dir = view_ray(scene) pos = closest_point_on_line(p0, p1, origin, dir) lw = plot.linewidth[] isa Vector ? plot.linewidth[][idx] : plot.linewidth[] @@ -605,19 +597,20 @@ function show_data(inspector::DataInspector, plot::Surface, idx) ys = plot[2][] zs = plot[3][] w, h = size(zs) - _i = mod1(idx, w); _j = div(idx-1, w) + _i = mod1(idx, w) + _j = div(idx - 1, w) # This isn't the most accurate so we include some neighboring faces origin, dir = view_ray(scene) pos = Point3f(NaN) - for i in _i-1:_i+1, j in _j-1:_j+1 + for i in (_i - 1):(_i + 1), j in (_j - 1):(_j + 1) (1 <= i <= w) && (1 <= j < h) || continue if i - 1 > 0 pos = ray_triangle_intersection( surface_pos(xs, ys, zs, i, j), - surface_pos(xs, ys, zs, i-1, j), - surface_pos(xs, ys, zs, i, j+1), + surface_pos(xs, ys, zs, i - 1, j), + surface_pos(xs, ys, zs, i, j + 1), origin, dir ) end @@ -625,8 +618,8 @@ function show_data(inspector::DataInspector, plot::Surface, idx) if i + 1 <= w && isnan(pos) pos = ray_triangle_intersection( surface_pos(xs, ys, zs, i, j), - surface_pos(xs, ys, zs, i, j+1), - surface_pos(xs, ys, zs, i+1, j+1), + surface_pos(xs, ys, zs, i, j + 1), + surface_pos(xs, ys, zs, i + 1, j + 1), origin, dir ) end @@ -642,7 +635,7 @@ function show_data(inspector::DataInspector, plot::Surface, idx) tt.text[] = position2string(pos) end tt.visible[] = true - tt.offset[] = 0f0 + tt.offset[] = 0.0f0 else tt.visible[] = false end @@ -651,13 +644,9 @@ function show_data(inspector::DataInspector, plot::Surface, idx) return true end -function show_data(inspector::DataInspector, plot::Heatmap, idx) - show_imagelike(inspector, plot, "H", true) -end +show_data(inspector::DataInspector, plot::Heatmap, idx) = show_imagelike(inspector, plot, "H", true) -function show_data(inspector::DataInspector, plot::Image, idx) - show_imagelike(inspector, plot, "img", false) -end +show_data(inspector::DataInspector, plot::Image, idx) = show_imagelike(inspector, plot, "img", false) function show_imagelike(inspector, plot, name, edge_based) a = inspector.attributes @@ -670,7 +659,8 @@ function show_imagelike(inspector, plot, name, edge_based) x, y = mpos else i, j, z = _pixelated_getindex(plot[1][], plot[2][], plot[3][], mpos, edge_based) - x = i; y = j + x = i + y = j end if haskey(plot, :inspector_label) @@ -707,11 +697,11 @@ function show_imagelike(inspector, plot, name, edge_based) scene, position, color = a._color, visible = a.indicator_visible, inspectable = false, - marker=:rect, markersize = map(r -> 3r, a.range), + marker = :rect, markersize = map(r -> 3r, a.range), strokecolor = a.indicator_color, strokewidth = a.indicator_linewidth ) - translate!(p, Vec3f(0, 0, a.depth[]-1)) + translate!(p, Vec3f(0, 0, a.depth[] - 1)) push!(inspector.temp_plots, p) elseif !isempty(inspector.temp_plots) p = inspector.temp_plots[1] @@ -727,7 +717,7 @@ function show_imagelike(inspector, plot, name, edge_based) strokewidth = a.indicator_linewidth, linestyle = a.indicator_linestyle, visible = a.indicator_visible, inspectable = false ) - translate!(p, Vec3f(0, 0, a.depth[]-1)) + translate!(p, Vec3f(0, 0, a.depth[] - 1)) push!(inspector.temp_plots, p) elseif !isempty(inspector.temp_plots) p = inspector.temp_plots[1] @@ -750,12 +740,12 @@ function _interpolated_getindex(xs, ys, img, mpos) i = clamp((x - x0) / (x1 - x0) * size(img, 1) + 0.5, 1, size(img, 1)) j = clamp((y - y0) / (y1 - y0) * size(img, 2) + 0.5, 1, size(img, 2)) - l = clamp(floor(Int, i), 1, size(img, 1)-1); - r = clamp(l+1, 2, size(img, 1)) - b = clamp(floor(Int, j), 1, size(img, 2)-1); - t = clamp(b+1, 2, size(img, 2)) - z = ((r-i) * img[l, b] + (i-l) * img[r, b]) * (t-j) + - ((r-i) * img[l, t] + (i-l) * img[r, t]) * (j-b) + l = clamp(floor(Int, i), 1, size(img, 1) - 1) + r = clamp(l + 1, 2, size(img, 1)) + b = clamp(floor(Int, j), 1, size(img, 2) - 1) + t = clamp(b + 1, 2, size(img, 2)) + z = ((r - i) * img[l, b] + (i - l) * img[r, b]) * (t - j) + + ((r - i) * img[l, t] + (i - l) * img[r, t]) * (j - b) # float, float, value (i, j are no longer used) return i, j, z @@ -769,7 +759,7 @@ function _pixelated_getindex(xs, ys, img, mpos, edge_based) j = clamp(round(Int, (y - y0) / (y1 - y0) * size(img, 2) + 0.5), 1, size(img, 2)) # int, int, value - return i, j, img[i,j] + return i, j, img[i, j] end function _interpolated_getindex(xs::Vector, ys::Vector, img, mpos) @@ -779,39 +769,35 @@ 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) +_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 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) +_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) - return false -end +show_data(inspector::DataInspector, plot, idx, source = nothing) = false ################################################################################ @@ -820,13 +806,9 @@ end -function show_data(inspector::DataInspector, plot::BarPlot, idx, ::Lines) - return show_data(inspector, plot, div(idx-1, 6)+1) -end +show_data(inspector::DataInspector, plot::BarPlot, idx, ::Lines) = show_data(inspector, plot, div(idx - 1, 6) + 1) -function show_data(inspector::DataInspector, plot::BarPlot, idx, ::Mesh) - return show_data(inspector, plot, div(idx-1, 4)+1) -end +show_data(inspector::DataInspector, plot::BarPlot, idx, ::Mesh) = show_data(inspector, plot, div(idx - 1, 4) + 1) @@ -871,9 +853,7 @@ function show_data(inspector::DataInspector, plot::BarPlot, idx) return true end -function show_data(inspector::DataInspector, plot::Arrows, idx, ::LineSegments) - return show_data(inspector, plot, div(idx+1, 2), nothing) -end +show_data(inspector::DataInspector, plot::Arrows, idx, ::LineSegments) = show_data(inspector, plot, div(idx + 1, 2), nothing) function show_data(inspector::DataInspector, plot::Arrows, idx, source) a = inspector.plot.attributes tt = inspector.plot @@ -947,7 +927,7 @@ function show_poly(inspector, plot, idx, source) strokewidth = a.indicator_linewidth, linestyle = a.indicator_linestyle, visible = a.indicator_visible, inspectable = false ) - translate!(p, Vec3f(0, 0, a.depth[]-1)) + translate!(p, Vec3f(0, 0, a.depth[] - 1)) push!(inspector.temp_plots, p) elseif !isempty(inspector.temp_plots) @@ -990,11 +970,14 @@ function show_data(inspector::DataInspector, plot::VolumeSlices, idx, child::Hea if !isnan(pos) child_idx = findfirst(isequal(child), plot.plots) if child_idx == 2 - x = pos[2]; y = pos[3] + x = pos[2] + y = pos[3] elseif child_idx == 3 - x = pos[1]; y = pos[3] + x = pos[1] + y = pos[3] else - x = pos[1]; y = pos[2] + x = pos[1] + y = pos[2] end i = clamp(round(Int, (x - qs[1]) / (qs[2] - qs[1]) * size(data, 1) + 0.5), 1, size(data, 1)) j = clamp(round(Int, (y - ps[1]) / (ps[2] - ps[1]) * size(data, 2) + 0.5), 1, size(data, 2)) diff --git a/src/interaction/interactive_api.jl b/src/interaction/interactive_api.jl index 309a8ed3fec..473956f0ed3 100644 --- a/src/interaction/interactive_api.jl +++ b/src/interaction/interactive_api.jl @@ -20,8 +20,8 @@ Calls `f(plot, idx)` whenever the mouse is over any of `plots`. `idx` is an index, e.g. when over a scatter plot, it will be the index of the hovered element """ -onpick(f, x, plots::AbstractPlot...; range=1) = onpick(f, get_scene(x), plots..., range = range) -function onpick(f, scene::Scene, plots::AbstractPlot...; range=1) +onpick(f, x, plots::AbstractPlot...; range = 1) = onpick(f, get_scene(x), plots..., range = range) +function onpick(f, scene::Scene, plots::AbstractPlot...; range = 1) fplots = flatten_plots(plots) args = range == 1 ? (scene,) : (scene, range) on(events(scene).mouseposition) do mp @@ -80,9 +80,7 @@ end 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)) -end +pick(scene::Scene, x::Number, y::Number) = pick(scene, Vec{2, Float64}(x, y)) """ @@ -117,15 +115,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) @@ -154,16 +153,17 @@ function pick_sorted(scene::Scene, screen, xy, range) 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 @@ -195,9 +195,7 @@ end Normalizes mouse position `pos` relative to the screen rectangle. """ screen_relative(x, mpos) = screen_relative(get_scene(x), mpos) -function screen_relative(scene::Scene, mpos) - return Point2f(mpos) .- Point2f(minimum(pixelarea(scene)[])) -end +screen_relative(scene::Scene, mpos) = Point2f(mpos) .- Point2f(minimum(pixelarea(scene)[])) """ mouseposition(scene = hovered_scene()) @@ -208,14 +206,10 @@ given `scene`. By default uses the `scene` that the mouse is currently hovering over. """ mouseposition(x) = mouseposition(get_scene(x)) -function mouseposition(scene::Scene = hovered_scene()) - return to_world(scene, mouseposition_px(scene)) -end +mouseposition(scene::Scene = hovered_scene()) = to_world(scene, mouseposition_px(scene)) mouseposition_px(x) = mouseposition_px(get_scene(x)) -function mouseposition_px(scene::Scene = hovered_scene()) - return screen_relative(scene, events(scene).mouseposition[]) -end +mouseposition_px(scene::Scene = hovered_scene()) = screen_relative(scene, events(scene).mouseposition[]) """ hovered_scene() @@ -253,7 +247,7 @@ function select_rectangle(scene; blocking = false, priority = 2, strokewidth = 3 scene, rect, visible = false, color = RGBAf(0, 0, 0, 0), strokecolor = RGBAf(0.1, 0.1, 0.8, 0.5), strokewidth = strokewidth, kwargs..., ) - on(events(scene).mousebutton, priority=priority) do event + on(events(scene).mousebutton, priority = priority) do event if event.button == key if event.action == Mouse.press && is_mouseinside(scene) mp = mouseposition(scene) @@ -279,7 +273,7 @@ function select_rectangle(scene; blocking = false, priority = 2, strokewidth = 3 return Consume(false) end - on(events(scene).mouseposition, priority=priority) do event + on(events(scene).mouseposition, priority = priority) do event if waspressed[] mp = mouseposition(scene) mini = minimum(rect[]) @@ -309,15 +303,15 @@ The `kwargs...` are propagated into `lines!` which plots the selected line. function select_line(scene; blocking = false, priority = 2, kwargs...) key = Mouse.left waspressed = Observable(false) - line = Observable([Point2f(0,0), Point2f(1,1)]) - line_ret = Observable([Point2f(0,0), Point2f(1,1)]) + line = Observable([Point2f(0, 0), Point2f(1, 1)]) + line_ret = Observable([Point2f(0, 0), Point2f(1, 1)]) # Create an initially hidden arrow plotted_line = lines!( scene, line; visible = false, color = RGBAf(0.1, 0.1, 0.8, 0.5), - linewidth = 4, kwargs..., + linewidth = 4, kwargs... ) - on(events(scene).mousebutton, priority=priority) do event + on(events(scene).mousebutton, priority = priority) do event if event.button == key && is_mouseinside(scene) mp = mouseposition(scene) if event.action == Mouse.press @@ -341,7 +335,7 @@ function select_line(scene; blocking = false, priority = 2, kwargs...) end return Consume(false) end - on(events(scene).mouseposition, priority=priority) do event + on(events(scene).mouseposition, priority = priority) do event if waspressed[] mp = mouseposition(scene) line[][2] = mp @@ -367,19 +361,19 @@ The value of the returned point is updated **only** when the user un-clicks. The `kwargs...` are propagated into `scatter!` which plots the selected point. """ -function select_point(scene; blocking = false, priority=2, kwargs...) +function select_point(scene; blocking = false, priority = 2, kwargs...) key = Mouse.left pmarker = Circle(Point2f(0, 0), Float32(1)) waspressed = Observable(false) - point = Observable([Point2f(0,0)]) - point_ret = Observable(Point2f(0,0)) + point = Observable([Point2f(0, 0)]) + point_ret = Observable(Point2f(0, 0)) # Create an initially hidden arrow plotted_point = scatter!( scene, point; visible = false, marker = pmarker, markersize = 20px, - color = RGBAf(0.1, 0.1, 0.8, 0.5), kwargs..., + color = RGBAf(0.1, 0.1, 0.8, 0.5), kwargs... ) - on(events(scene).mousebutton, priority=priority) do event + on(events(scene).mousebutton, priority = priority) do event if event.button == key && is_mouseinside(scene) mp = mouseposition(scene) if event.action == Mouse.press @@ -400,7 +394,7 @@ function select_point(scene; blocking = false, priority=2, kwargs...) end return Consume(false) end - on(events(scene).mouseposition, priority=priority) do event + on(events(scene).mouseposition, priority = priority) do event if waspressed[] mp = mouseposition(scene) point[][1] = mp diff --git a/src/interaction/iodevices.jl b/src/interaction/iodevices.jl index 416f8580f69..2a941f00fb4 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,48 +156,48 @@ Backend independent enums and fields which represent mouse actions. """ module Mouse - using ..Makie: INSTANCES # import the docstring extensions - - """ - Mouse.Button - - Enumerates all mouse buttons in accordance with the GLFW spec. - - $(INSTANCES) - """ - @enum Button begin - left = 0 - middle = 2 - right = 1 # Conform to GLFW - none = -1 # for convenience - end - - """ - Mouse.Action - - Enumerates all mouse states/actions in accordance with the GLFW spec. - - $(INSTANCES) - """ - @enum Action begin - press = 1 - release = 0 - end - - # deprecated, remove eventually - """ - Mouse.DragEnum - - Enumerates the drag states of the mouse. - - $(INSTANCES) - """ - @enum DragEnum begin - down - up - pressed - notpressed - end +using ..Makie: INSTANCES # import the docstring extensions + +""" + Mouse.Button + +Enumerates all mouse buttons in accordance with the GLFW spec. + +$(INSTANCES) +""" +@enum Button begin + left = 0 + middle = 2 + right = 1 # Conform to GLFW + none = -1 # for convenience +end + +""" + Mouse.Action + +Enumerates all mouse states/actions in accordance with the GLFW spec. + +$(INSTANCES) +""" +@enum Action begin + press = 1 + release = 0 +end + +# deprecated, remove eventually +""" + Mouse.DragEnum + +Enumerates the drag states of the mouse. + +$(INSTANCES) +""" +@enum DragEnum begin + down + up + pressed + notpressed +end end # Void for no button needs to be pressed, diff --git a/src/interaction/liftmacro.jl b/src/interaction/liftmacro.jl index eaf867127d2..12cd4a92855 100644 --- a/src/interaction/liftmacro.jl +++ b/src/interaction/liftmacro.jl @@ -17,9 +17,7 @@ end find_observable_expressions(x) = Set() is_interpolated_observable(x) = false -function is_interpolated_observable(e::Expr) - e.head == Symbol(:$) && length(e.args) == 1 -end +is_interpolated_observable(e::Expr) = e.head == Symbol(:$) && length(e.args) == 1 """ Replaces every subexpression that looks like a observable expression with a substitute symbol stored in `exprdict`. diff --git a/src/interaction/observables.jl b/src/interaction/observables.jl index fa58ddc1793..29bd7d353f3 100644 --- a/src/interaction/observables.jl +++ b/src/interaction/observables.jl @@ -34,8 +34,8 @@ test(Observable(1), Observable(2)) """ function map_once( - f, input::Observable, inputrest::Observable... - ) + f, input::Observable, inputrest::Observable... +) for arg in (input, inputrest...) safe_off(arg, f) end diff --git a/src/interfaces.jl b/src/interfaces.jl index da63febdc95..de0904425d6 100644 --- a/src/interfaces.jl +++ b/src/interfaces.jl @@ -1,27 +1,25 @@ -function default_theme(scene) - Attributes( - # color = theme(scene, :color), - linewidth = 1, - transformation = automatic, - model = automatic, - visible = true, - transparency = false, - overdraw = false, - diffuse = Vec3f(0.4), - specular = Vec3f(0.2), - shininess = 32f0, - nan_color = RGBAf(0,0,0,0), - ssao = false, - inspectable = theme(scene, :inspectable), - depth_shift = 0f0, - space = :data - ) -end +default_theme(scene) = Attributes( + # color = theme(scene, :color), + linewidth = 1, + transformation = automatic, + model = automatic, + visible = true, + transparency = false, + overdraw = false, + diffuse = Vec3f(0.4), + specular = Vec3f(0.2), + shininess = 32.0f0, + nan_color = RGBAf(0, 0, 0, 0), + ssao = false, + inspectable = theme(scene, :inspectable), + depth_shift = 0.0f0, + space = :data +) -function color_and_colormap!(plot, intensity = plot[:color]) - if isa(intensity[], AbstractArray{<: Number}) +color_and_colormap!(plot, intensity = plot[:color]) = + if isa(intensity[], AbstractArray{<:Number}) haskey(plot, :colormap) || error("Plot $(typeof(plot)) needs to have a colormap to allow the attribute color to be an array of numbers") replace_automatic!(plot, :colorrange) do @@ -44,49 +42,46 @@ function color_and_colormap!(plot, intensity = plot[:color]) delete!(plot, :colorrange) return false end -end -function calculated_attributes!(T::Type{<: Mesh}, plot) +function calculated_attributes!(T::Type{<:Mesh}, plot) mesha = lift(GeometryBasics.attributes, plot.mesh) - color = haskey(mesha[], :color) ? lift(x-> x[:color], mesha) : plot.color + color = haskey(mesha[], :color) ? lift(x -> x[:color], mesha) : plot.color need_cmap = color_and_colormap!(plot, color) need_cmap || delete!(plot, :colormap) return end -function calculated_attributes!(::Type{<: Union{Heatmap, Image}}, plot) +function calculated_attributes!(::Type{<:Union{Heatmap, Image}}, plot) plot[:color] = plot[3] color_and_colormap!(plot) end -function calculated_attributes!(::Type{<: Surface}, plot) +function calculated_attributes!(::Type{<:Surface}, plot) colors = plot[3] if haskey(plot, :color) color = plot[:color][] - if isa(color, AbstractMatrix{<: Number}) && !(color === to_value(colors)) + if isa(color, AbstractMatrix{<:Number}) && !(color === to_value(colors)) colors = plot[:color] end end color_and_colormap!(plot, colors) end -function calculated_attributes!(::Type{<: MeshScatter}, plot) - color_and_colormap!(plot) -end +calculated_attributes!(::Type{<:MeshScatter}, plot) = color_and_colormap!(plot) -function calculated_attributes!(::Type{<: Scatter}, plot) +function calculated_attributes!(::Type{<:Scatter}, plot) # calculate base case color_and_colormap!(plot) replace_automatic!(plot, :marker_offset) do # default to middle - lift(x-> to_2d_scale(map(x-> x .* -0.5f0, x)), plot[:markersize]) + lift(x -> to_2d_scale(map(x -> x .* -0.5f0, x)), plot[:markersize]) end replace_automatic!(plot, :markerspace) do lift(plot.markersize) do ms - if ms isa Pixel || (ms isa AbstractVector && all(x-> ms isa Pixel, ms)) + if ms isa Pixel || (ms isa AbstractVector && all(x -> ms isa Pixel, ms)) return :pixel else return :data @@ -95,7 +90,7 @@ function calculated_attributes!(::Type{<: Scatter}, plot) end end -function calculated_attributes!(::Type{T}, plot) where {T<:Union{Lines, LineSegments}} +function calculated_attributes!(::Type{T}, plot) where {T <: Union{Lines, LineSegments}} color_and_colormap!(plot) pos = plot[1][] # extend one color/linewidth per linesegment to be one (the same) color/linewidth per vertex @@ -117,11 +112,9 @@ const atomic_function_symbols = ( ) const atomic_functions = getfield.(Ref(Makie), atomic_function_symbols) -const Atomic{Arg} = Union{map(x-> Combined{x, Arg}, atomic_functions)...} +const Atomic{Arg} = Union{map(x -> Combined{x, Arg}, atomic_functions)...} -function (PT::Type{<: Combined})(parent, transformation, attributes, input_args, converted) - PT(parent, transformation, attributes, input_args, converted, AbstractPlot[]) -end +(PT::Type{<:Combined})(parent, transformation, attributes, input_args, converted) = PT(parent, transformation, attributes, input_args, converted, AbstractPlot[]) """ used_attributes(args...) = () @@ -151,9 +144,7 @@ used_attributes(PlotType, args...) = () apply for return type (args...,) """ -function apply_convert!(P, attributes::Attributes, x::Tuple) - return (plottype(P, x...), x) -end +apply_convert!(P, attributes::Attributes, x::Tuple) = (plottype(P, x...), x) """ apply for return type PlotSpec @@ -168,7 +159,7 @@ function apply_convert!(P, attributes::Attributes, x::PlotSpec{S}) where S return (plottype(S, P), args) end -function seperate_tuple(args::Observable{<: NTuple{N, Any}}) where N +seperate_tuple(args::Observable{<:NTuple{N, Any}}) where N = ntuple(N) do i lift(args) do x if i <= length(x) @@ -178,9 +169,8 @@ function seperate_tuple(args::Observable{<: NTuple{N, Any}}) where N end end end -end -function (PlotType::Type{<: AbstractPlot{Typ}})(scene::SceneLike, attributes::Attributes, args) where Typ +function (PlotType::Type{<:AbstractPlot{Typ}})(scene::SceneLike, attributes::Attributes, args) where Typ input = convert.(Observable, args) argnodes = lift(input...) do args... convert_arguments(PlotType, args...) @@ -201,7 +191,7 @@ function plot(scene::Scene, plot::AbstractPlot) return plot end -function (PlotType::Type{<: AbstractPlot{Typ}})(scene::SceneLike, attributes::Attributes, input, args) where Typ +function (PlotType::Type{<:AbstractPlot{Typ}})(scene::SceneLike, attributes::Attributes, input, args) where Typ # The argument type of the final plot object is the assumened to stay constant after # argument conversion. This might not always hold, but it simplifies # things quite a bit @@ -211,7 +201,7 @@ function (PlotType::Type{<: AbstractPlot{Typ}})(scene::SceneLike, attributes::At FinalType = Combined{Typ, ArgTyp} plot_attributes = merged_get!( - ()-> default_theme(scene, FinalType), + () -> default_theme(scene, FinalType), plotsym(FinalType), scene, attributes ) @@ -238,17 +228,17 @@ end ## generic definitions # If the Combined has no plot func, calculate them -plottype(::Type{<: Combined{Any}}, argvalues...) = plottype(argvalues...) +plottype(::Type{<:Combined{Any}}, argvalues...) = plottype(argvalues...) plottype(::Type{Any}, argvalues...) = plottype(argvalues...) # If it has something more concrete than Any, use it directly -plottype(P::Type{<: Combined{T}}, argvalues...) where T = P +plottype(P::Type{<:Combined{T}}, argvalues...) where T = P ## specialized definitions for types plottype(::AbstractVector, ::AbstractVector, ::AbstractVector) = Scatter plottype(::AbstractVector, ::AbstractVector) = Scatter plottype(::AbstractVector) = Scatter -plottype(::AbstractMatrix{<: Real}) = Heatmap -plottype(::Array{<: AbstractFloat, 3}) = Volume +plottype(::AbstractMatrix{<:Real}) = Heatmap +plottype(::Array{<:AbstractFloat, 3}) = Volume plottype(::AbstractString) = Text plottype(::LineString) = Lines @@ -271,11 +261,11 @@ function convert_arguments(P::PlotFunc, args...) end ``` """ -plottype(P1::Type{<: Combined{Any}}, P2::Type{<: Combined{T}}) where T = P2 -plottype(P1::Type{<: Combined{T}}, P2::Type{<: Combined}) where T = P1 +plottype(P1::Type{<:Combined{Any}}, P2::Type{<:Combined{T}}) where T = P2 +plottype(P1::Type{<:Combined{T}}, P2::Type{<:Combined}) where T = P1 # all the plotting functions that get a plot type -const PlotFunc = Union{Type{Any}, Type{<: AbstractPlot}} +const PlotFunc = Union{Type{Any}, Type{<:AbstractPlot}} ###################################################################### @@ -312,7 +302,7 @@ function plot!(scene::Union{Combined, SceneLike}, P::PlotFunc, attributes::Attri Observable(()) else # Remove used attributes from `attributes` and collect them in a `Tuple` to pass them more easily - lift((args...)-> Pair.(convert_keys, args), pop!.(attributes, convert_keys)...) + lift((args...) -> Pair.(convert_keys, args), pop!.(attributes, convert_keys)...) end # call convert_arguments for a first time to get things started converted = convert_arguments(PreType, argvalues...; kw_signal[]...) @@ -321,7 +311,7 @@ function plot!(scene::Union{Combined, SceneLike}, P::PlotFunc, attributes::Attri FinalType, argsconverted = apply_convert!(PreType, attributes, converted) converted_node = Observable(argsconverted) - input_nodes = convert.(Observable, args) + input_nodes = convert.(Observable, args) onany(kw_signal, input_nodes...) do kwargs, args... # do the argument conversion inside a lift result = convert_arguments(FinalType, args...; kwargs...) @@ -340,9 +330,7 @@ plot!(p::Combined) = _plot!(p) _plot!(p::Atomic{T}) where T = p -function _plot!(p::Combined{fn, T}) where {fn, T} - throw(PlotMethodError(fn, T)) -end +_plot!(p::Combined{fn, T}) where {fn, T} = throw(PlotMethodError(fn, T)) struct PlotMethodError <: Exception fn @@ -356,11 +344,11 @@ function Base.showerror(io::IO, err::PlotMethodError) typed_args = join(string.("::", args), ", ") print(io, "PlotMethodError: no ") - printstyled(io, fn == Any ? "plot" : fn; color=:cyan) + printstyled(io, fn == Any ? "plot" : fn; color = :cyan) print(io, " method for arguments ") - printstyled(io, "($typed_args)"; color=:cyan) + printstyled(io, "($typed_args)"; color = :cyan) print(io, ". To support these arguments, define\n ") - printstyled(io, "plot!(::$(Combined{fn,S} where {S<:T}))"; color=:cyan) + printstyled(io, "plot!(::$(Combined{fn,S} where {S<:T}))"; color = :cyan) print(io, "\nAvailable methods are:\n") for m in methods(plot!) if m.sig <: Tuple{typeof(plot!), Combined{fn}} @@ -369,11 +357,10 @@ function Base.showerror(io::IO, err::PlotMethodError) end end -function show_attributes(attributes) +show_attributes(attributes) = for (k, v) in attributes println(" ", k, ": ", v[] == nothing ? "nothing" : v[]) end -end """ extract_scene_attributes!(attributes) @@ -423,7 +410,7 @@ function plot!(scene::SceneLike, P::PlotFunc, attributes::Attributes, input::NTu return plot_object end -function plot!(scene::Combined, P::PlotFunc, attributes::Attributes, input::NTuple{N,Observable}, args::Observable) where {N} +function plot!(scene::Combined, P::PlotFunc, attributes::Attributes, input::NTuple{N, Observable}, args::Observable) where {N} # create "empty" plot type - empty meaning containing no plots, just attributes + arguments plot_object = P(scene, attributes, input, args) diff --git a/src/jl_rasterizer/bmp.jl b/src/jl_rasterizer/bmp.jl index bf35407b4d3..a7317eaadf5 100644 --- a/src/jl_rasterizer/bmp.jl +++ b/src/jl_rasterizer/bmp.jl @@ -6,7 +6,7 @@ function writebmp(io, img) # be a multiple of 4 bytes. extrabytes = 4 - ((w * 3) % 4) (extrabytes == 4) && (extrabytes = 0) - paddedsize = ((w * 3) + extrabytes) * h; + paddedsize = ((w * 3) + extrabytes) * h # file header write(io, b"BM") @@ -34,7 +34,7 @@ function writebmp(io, img) write(io, reinterpret(UInt8, green(rgb))) write(io, reinterpret(UInt8, red(rgb))) end - for i = 1:extrabytes + for i in 1:extrabytes write(io, UInt8(0)) end end diff --git a/src/jl_rasterizer/main.jl b/src/jl_rasterizer/main.jl index 471d2a98bde..a2d060b24e5 100644 --- a/src/jl_rasterizer/main.jl +++ b/src/jl_rasterizer/main.jl @@ -3,9 +3,7 @@ using GeometryBasics, Interpolations using ImageShow using Makie: orthographicprojection -@inline function edge_function(a, b, c) - (c[1] - a[1]) * (b[2] - a[2]) - (c[2] - a[2]) * (b[1] - a[1]) -end +@inline edge_function(a, b, c) = (c[1] - a[1]) * (b[2] - a[2]) - (c[2] - a[2]) * (b[1] - a[1]) @inline function src_alpha(c::T) where T <: Colorant a = alpha(c) @@ -17,9 +15,7 @@ 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] -function standard_transparency(source, dest::T) where T - (alpha(source) .* source) .+ ((one(eltype(T)) - alpha(source)) .* dest) -end +standard_transparency(source, dest::T) where T = (alpha(source) .* source) .+ ((one(eltype(T)) - alpha(source)) .* dest) mutable struct FixedGeomView{GeomOut, VT} buffer::Vector{GeomOut} @@ -34,15 +30,14 @@ end Base.length(x::TriangleStripView) = 2 Base.size(x::TriangleStripView) = (2,) -function Base.getindex(x::TriangleStripView, i) +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) @@ -59,9 +54,7 @@ function FixedGeomView(T, max_primitives, primitive_in, primitive_out) return FixedGeomView(buffer, geometry_view, 1) end -function reset!(A::FixedGeomView) - A.idx = 1 -end +reset!(A::FixedGeomView) = A.idx = 1 function Base.push!(A::FixedGeomView, element) if A.idx > length(A.buffer) @@ -81,21 +74,19 @@ 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}( - vertexshader, - fragmentshader, - geometryshader, - geometry_view, - emit - ) -end +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, + geometry_view, + emit +) function geometry_return_type(vertex_array, vertexshader, geometryshader, uniforms) typ = Any @@ -114,15 +105,15 @@ 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) @@ -154,13 +145,12 @@ 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} +interpolate(bary, face::NTuple{N, T}, vn::Val{0}, aggregate) where {N, T} = if T <: Tuple aggregate else T(aggregate...) end -end function interpolate(bary, face, vn::Val{N}, aggregate = ()) where N @inbounds begin @@ -179,14 +169,15 @@ broadcastmax(a, b) = max.(a, b) function clip2pixel_space(position, resolution) clipspace = position ./ position[4] p = clipspace[Vec(1, 2)] - (((p .+ 1f0) / 2f0) .* (resolution .- 1f0)) .+ 1f0, clipspace[3] + (((p .+ 1.0f0) / 2.0f0) .* (resolution .- 1.0f0)) .+ 1.0f0, clipspace[3] end function (r::JLRasterizer{Vert, Args, FragN})( - canvas, vertex_array::AbstractArray{Vert}, uniforms::Args - ) where {Vert, Args, FragN} - framebuffers = canvas.color; depthbuffer = canvas.depth + 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 @@ -216,11 +207,11 @@ function (r::JLRasterizer{Vert, Args, FragN})( depths = map(last, fdepth) vertex_out = map(last, geom_face) # Bounding rectangle - mini = max.(reduce(broadcastmin, f), 1f0) + mini = max.(reduce(broadcastmin, f), 1.0f0) 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 +219,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 >= 0.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 +228,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 +261,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) @@ -318,7 +309,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]) ) @@ -355,7 +346,7 @@ function geom_particles(emit!, vertex_out, uniforms) pos_scale = arg.rect pos = pos_scale[Vec(1, 2)] scale = pos_scale[Vec(3, 4)] - quad = Vec4f(0f0, 0f0, scale[1], scale[2]) + quad = Vec4f(0.0f0, 0.0f0, scale[1], scale[2]) uv = arg.uvrect emit_vertex(emit!, quad[Vec(1, 2)], uv[Vec(1, 4)], arg, pos, uniforms) emit_vertex(emit!, quad[Vec(1, 4)], uv[Vec(1, 2)], arg, pos, uniforms) @@ -366,28 +357,30 @@ end function sdf2color(dist, bg_color, color) - inside = aastep(0f0, dist) + inside = aastep(0.0f0, dist) mix(bg_color, color, inside) 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), ) + bg_color = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.0f0) + (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) + bg_color = Vec4f(0.0f0, 0.0f0, 0.0f0, 0.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) +proj = Makie.orthographicprojection(Rect2(0, 0, resolution...), -10_000.0f0, 10_000.0f0) circle(uv::Vec{2, T}) where {T} = -T(norm(uv .- 0.5) - 0.5) @@ -400,13 +393,13 @@ uniforms = Uniforms( N = 10 -middle = Vec2f(resolution) / 2f0 -radius = (min(resolution...) / 2f0) - 50 +middle = Vec2f(resolution) / 2.0f0 +radius = (min(resolution...) / 2.0f0) - 50 vertices = [(VertexCS( - Vec2f((sin(2pi * (i / N)) , cos(2pi * (i / N))) .* radius) .+ middle, - Vec4f(1, i/N, 0, 1), + Vec2f((sin(2pi * (i / N)), cos(2pi * (i / N))) .* radius) .+ middle, + Vec4f(1, i / N, 0, 1), Vec2f(40, 40) -),) for i = 1:N] +),) for i in 1:N] raster, rest = rasterizer( @@ -417,7 +410,7 @@ raster, rest = rasterizer( geometryshader = geom_particles, max_primitives = 4, primitive_in = :points, - primitive_out = :triangle_strip, + primitive_out = :triangle_strip ) struct Canvas{N} @@ -426,7 +419,7 @@ struct Canvas{N} end function Canvas(xdim::Integer, ydim::Integer) - color = fill(RGBA{Float32}(0,0,0,0), xdim, ydim) + color = fill(RGBA{Float32}(0, 0, 0, 0), xdim, ydim) depth = ones(Float32, xdim, ydim) return Canvas((color,), depth) end diff --git a/src/layouting/boundingbox.jl b/src/layouting/boundingbox.jl index 18757dcb7a5..79867650015 100644 --- a/src/layouting/boundingbox.jl +++ b/src/layouting/boundingbox.jl @@ -3,9 +3,7 @@ function parent_transform(x) isnothing(p) ? Mat4f(I) : p.model[] end -function boundingbox(x, exclude = (p)-> false) - return parent_transform(x) * data_limits(x, exclude) -end +boundingbox(x, exclude = (p) -> false) = parent_transform(x) * data_limits(x, exclude) function project_widths(matrix, vec) pr = project(matrix, vec) @@ -39,7 +37,7 @@ function height_insensitive_boundingbox(ext::GlyphExtent) end function height_insensitive_boundingbox_with_advance(ext::GlyphExtent) - l = 0f0 + l = 0.0f0 r = ext.hadvance b = ext.descender h = ext.ascender @@ -48,9 +46,7 @@ end _inkboundingbox(ext::GlyphExtent) = ext.ink_bounding_box -function boundingbox(glyphcollection::GlyphCollection, position::Point3f, rotation::Quaternion) - return boundingbox(glyphcollection, rotation) + position -end +boundingbox(glyphcollection::GlyphCollection, position::Point3f, rotation::Quaternion) = boundingbox(glyphcollection, rotation) + position function boundingbox(glyphcollection::GlyphCollection, rotation::Quaternion) if isempty(glyphcollection.glyphs) @@ -73,7 +69,7 @@ function boundingbox(glyphcollection::GlyphCollection, rotation::Quaternion) return bb end -function boundingbox(layouts::AbstractArray{<:GlyphCollection}, positions, rotations) +boundingbox(layouts::AbstractArray{<:GlyphCollection}, positions, rotations) = if isempty(layouts) return Rect3f((0, 0, 0), (0, 0, 0)) else @@ -88,7 +84,6 @@ function boundingbox(layouts::AbstractArray{<:GlyphCollection}, positions, rotat !isfinite_rect(bb) && error("Invalid text boundingbox") return bb end -end function boundingbox(x::Text{<:Tuple{<:GlyphCollection}}) if x.space[] == x.markerspace[] @@ -130,11 +125,11 @@ _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, - RGBAf(0, 0, 0, 0), RGBAf(0, 0, 0, 0), 0f0, 0f0) + RGBAf(0, 0, 0, 0), RGBAf(0, 0, 0, 0), 0.0f0, 0.0f0) return boundingbox(layout, Point3f(0), rot) end @@ -147,9 +142,9 @@ function rotatedrect(rect::Rect{2, T}, angle)::Rect{2, T} where T wx, wy = rect.widths 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}( cos(angle), -sin(angle), @@ -157,8 +152,8 @@ function rotatedrect(rect::Rect{2, T}, angle)::Rect{2, T} where T ) rotated = mrot * points - rmins = minimum(rotated; dims=2) - rmaxs = maximum(rotated; dims=2) + rmins = minimum(rotated; dims = 2) + rmaxs = maximum(rotated; dims = 2) return Rect2(rmins..., (rmaxs .- rmins)...) end diff --git a/src/layouting/data_limits.jl b/src/layouting/data_limits.jl index 4d3e624d2a5..34a1b77c1f3 100644 --- a/src/layouting/data_limits.jl +++ b/src/layouting/data_limits.jl @@ -1,6 +1,6 @@ _isfinite(x) = isfinite(x) _isfinite(x::VecTypes) = all(isfinite, x) -isfinite_rect(x::Rect) = all(isfinite, x.origin) && all(isfinite, x.widths) +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) @@ -35,12 +35,10 @@ 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}) - return plot.positions[] -end +point_iterator(plot::Union{Scatter, MeshScatter, Lines, LineSegments}) = plot.positions[] # TODO? -function point_iterator(text::Text{<: Tuple{<: Union{GlyphCollection, AbstractVector{GlyphCollection}}}}) +point_iterator(text::Text{<:Tuple{<:Union{GlyphCollection, AbstractVector{GlyphCollection}}}}) = if is_data_space(text.markerspace[]) return decompose(Point, boundingbox(text)) else @@ -50,29 +48,20 @@ function point_iterator(text::Text{<: Tuple{<: Union{GlyphCollection, AbstractVe return convert_arguments(PointBased(), text.position[])[1] end end -end -function point_iterator(text::Text) - return point_iterator(text.plots[1]) -end +point_iterator(text::Text) = point_iterator(text.plots[1]) point_iterator(mesh::GeometryBasics.Mesh) = decompose(Point, mesh) -function point_iterator(list::AbstractVector) - Iterators.flatten((point_iterator(elem) for elem in list)) -end +point_iterator(list::AbstractVector) = Iterators.flatten((point_iterator(elem) for elem in list)) point_iterator(plot::Combined) = point_iterator(plot.plots) point_iterator(plot::Mesh) = point_iterator(plot.mesh[]) -function br_getindex(vector::AbstractVector, idx::CartesianIndex, dim::Int) - return vector[Tuple(idx)[dim]] -end +br_getindex(vector::AbstractVector, idx::CartesianIndex, dim::Int) = vector[Tuple(idx)[dim]] -function br_getindex(matrix::AbstractMatrix, idx::CartesianIndex, dim::Int) - return matrix[idx] -end +br_getindex(matrix::AbstractMatrix, idx::CartesianIndex, dim::Int) = matrix[idx] function get_point_xyz(linear_indx::Int, indices, X, Y, Z) idx = indices[linear_indx] @@ -117,7 +106,7 @@ end function point_iterator(x::Volume) axes = (x[1], x[2], x[3]) - extremata = map(extrema∘to_value, axes) + extremata = map(extrema ∘ to_value, axes) minpoint = Point3f(first.(extremata)...) widths = last.(extremata) .- first.(extremata) rect = Rect3f(minpoint, Vec3f(widths)) @@ -126,19 +115,18 @@ 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) foreach_plot(f, s::FigureAxisPlot) = foreach_plot(f, s.figure) foreach_plot(f, list::AbstractVector) = foreach(f, list) -function foreach_plot(f, plot::Combined) +foreach_plot(f, plot::Combined) = if isempty(plot.plots) f(plot) else foreach_plot(f, plot.plots) end -end function foreach_transformed(f, point_iterator, model, trans_func) for point in point_iterator @@ -168,16 +156,13 @@ function iterate_transformed(plot) iterate_transformed(points, model, trans_func) end -function iterate_transformed(points, model, trans_func) - (to_ndim(Point3f, project(model, apply_transform(trans_func, point)), 0f0) for point in points) -end +iterate_transformed(points, model, trans_func) = (to_ndim(Point3f, project(model, apply_transform(trans_func, point)), 0.0f0) for point in points) -function update_boundingbox!(bb_ref, point) +update_boundingbox!(bb_ref, point) = if all(isfinite, point) vec = to_ndim(Vec3f, point, 0.0) bb_ref[] = update(bb_ref[], vec) end -end function update_boundingbox!(bb_ref, bb::Rect) # ref is uninitialized, so just set it to the first bb @@ -192,9 +177,7 @@ function update_boundingbox!(bb_ref, bb::Rect) return end -function data_limits(plot::AbstractPlot) - limits_from_transformed_points(iterate_transformed(plot)) -end +data_limits(plot::AbstractPlot) = limits_from_transformed_points(iterate_transformed(plot)) function _update_rect(rect::Rect{N, T}, point::Point{N, T}) where {N, T} mi = minimum(rect) @@ -216,7 +199,7 @@ function limits_from_transformed_points(points_iterator) return bb end -function data_limits(scenelike, exclude=(p)-> false) +function data_limits(scenelike, exclude = (p) -> false) bb_ref = Base.RefValue(Rect3f()) foreach_plot(scenelike) do plot if !exclude(plot) diff --git a/src/layouting/layouting.jl b/src/layouting/layouting.jl index 024500aecc2..364f213f3a2 100644 --- a/src/layouting/layouting.jl +++ b/src/layouting/layouting.jl @@ -2,9 +2,7 @@ using FreeTypeAbstraction: hadvance, leftinkbound, inkwidth, get_extent, ascende one_attribute_per_char(attribute, string) = (attribute for char in string) -function one_attribute_per_char(font::NativeFont, string) - return (find_font_for_char(char, font) for char in string) -end +one_attribute_per_char(font::NativeFont, string) = (find_font_for_char(char, font) for char in string) function attribute_per_char(string, attribute) n_words = 0 @@ -39,10 +37,10 @@ end Compute a GlyphCollection for a `string` given fontsize, font, align, rotation, model, justification, and lineheight. """ function layout_text( - string::AbstractString, fontsize::Union{AbstractVector, Number}, - font, fonts, align, rotation, justification, lineheight, color, - strokecolor, strokewidth, word_wrap_width - ) + string::AbstractString, fontsize::Union{AbstractVector, Number}, + font, fonts, align, rotation, justification, lineheight, color, + strokecolor, strokewidth, word_wrap_width +) ft_font = to_font(font) rscale = to_fontsize(fontsize) @@ -68,13 +66,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 @@ -95,8 +93,8 @@ function glyph_collection( last_space_local_idx = 0 last_space_global_idx = 0 - newline_offset = 0f0 - x = 0f0 + newline_offset = 0.0f0 + x = 0.0f0 xs = [Float32[]] # If word_wrap_width > 0: @@ -114,13 +112,13 @@ function glyph_collection( x += ci.extent.hadvance * ci.scale if 0 < word_wrap_width < x && last_space_local_idx != 0 && - ((ci.char in (' ', '\n')) || i == length(charinfos)) + ((ci.char in (' ', '\n')) || i == length(charinfos)) newline_offset = xs[end][last_space_local_idx + 1] - push!(xs, xs[end][last_space_local_idx+1:end] .- newline_offset) - xs[end-1] = xs[end-1][1:last_space_local_idx] + push!(xs, xs[end][(last_space_local_idx + 1):end] .- newline_offset) + xs[end - 1] = xs[end - 1][1:last_space_local_idx] push!(lineinfos, view(charinfos, last_line_start:last_space_global_idx)) - last_line_start = last_space_global_idx+1 + last_line_start = last_space_global_idx + 1 x = xs[end][end] + ci.extent.hadvance * ci.scale # TODO Do we need to redo the metrics for newlines? @@ -135,8 +133,8 @@ function glyph_collection( push!(xs, Float32[]) push!(lineinfos, view(charinfos, last_line_start:i)) last_space_local_idx = 0 - last_line_start = i+1 - x = 0f0 + last_line_start = i + 1 + x = 0.0f0 elseif i == length(charinfos) push!(lineinfos, view(charinfos, last_line_start:i)) end @@ -234,9 +232,9 @@ function glyph_collection( va = if valign isa Number Float32(valign) elseif valign == :top - 1f0 + 1.0f0 elseif valign == :bottom - 0f0 + 0.0f0 elseif valign == :center 0.5f0 else @@ -335,7 +333,7 @@ function text_quads(atlas::TextureAtlas, position::VecTypes, gc::GlyphCollection return pos, char_offsets, quad_offsets, uvs, scales end -function text_quads(atlas::TextureAtlas, position::Vector, gcs::Vector{<: GlyphCollection}, offset, transfunc, space) +function text_quads(atlas::TextureAtlas, position::Vector, gcs::Vector{<:GlyphCollection}, offset, transfunc, space) ps = apply_transform(transfunc, position, space) pos = [to_ndim(Point3f, p, 0) for (p, gc) in zip(ps, gcs) for _ in gc.origins] diff --git a/src/layouting/transformation.jl b/src/layouting/transformation.jl index 98af0448537..5b45e385b61 100644 --- a/src/layouting/transformation.jl +++ b/src/layouting/transformation.jl @@ -1,9 +1,9 @@ Base.parent(t::Transformation) = isassigned(t.parent) ? t.parent[] : nothing -function Transformation(transform_func=identity; - scale=Vec3f(1), - translation=Vec3f(0), - rotation=Quaternionf(0, 0, 0, 1)) +function Transformation(transform_func = identity; + scale = Vec3f(1), + translation = Vec3f(0), + rotation = Quaternionf(0, 0, 0, 1)) scale_o = convert(Observable{Vec3f}, scale) translation_o = convert(Observable{Vec3f}, translation) @@ -19,9 +19,9 @@ function Transformation(transform_func=identity; end function Transformation(transformable::Transformable; - scale=Vec3f(1), - translation=Vec3f(0), - rotation=Quaternionf(0, 0, 0, 1)) + scale = Vec3f(1), + translation = Vec3f(0), + rotation = Quaternionf(0, 0, 0, 1)) scale_o = convert(Observable{Vec3f}, scale) translation_o = convert(Observable{Vec3f}, translation) @@ -45,9 +45,7 @@ function Transformation(transformable::Transformable; return trans end -function model_transform(transformation::Transformation) - return transformationmatrix(transformation.translation[], transformation.scale[], transformation.rotation[]) -end +model_transform(transformation::Transformation) = transformationmatrix(transformation.translation[], transformation.scale[], transformation.rotation[]) function translated(scene::Scene, translation...) tscene = Scene(scene, transformation = Transformation()) @@ -62,21 +60,19 @@ function translated(scene::Scene; kw_args...) end function transform!( - scene::Transformable; - translation = Vec3f(0), - scale = Vec3f(1), - rotation = 0.0, - ) + scene::Transformable; + translation = Vec3f(0), + scale = Vec3f(1), + rotation = 0.0 +) translate!(scene, to_value(translation)) scale!(scene, to_value(scale)) rotate!(scene, to_value(rotation)) end -function transform!( - scene::Transformable, attributes::Union{Attributes, AbstractDict} - ) - transform!(scene; attributes...) -end +transform!( + scene::Transformable, attributes::Union{Attributes, AbstractDict} +) = transform!(scene; attributes...) transformation(t::Scene) = t.transformation transformation(t::AbstractPlot) = t.transformation @@ -171,20 +167,20 @@ Translate the scene relative to its current position. """ translate!(::Type{T}, scene::Transformable, xyz...) where T = translate!(T, scene, xyz) -function transform!(scene::Transformable, x::Tuple{Symbol, <: Number}) +function transform!(scene::Transformable, x::Tuple{Symbol, <:Number}) plane, dimval = string(x[1]), Float32(x[2]) - if length(plane) != 2 || (!all(x-> x in ('x', 'y', 'z'), plane)) + if length(plane) != 2 || (!all(x -> x in ('x', 'y', 'z'), plane)) error("plane needs to define a 2D plane in xyz. It should only contain 2 symbols out of (:x, :y, :z). Found: $plane") end - if all(x-> x in ('x', 'y'), plane) # xy plane + if all(x -> x in ('x', 'y'), plane) # xy plane translate!(scene, 0, 0, dimval) - elseif all(x-> x in ('x', 'z'), plane) # xz plane + elseif all(x -> x in ('x', 'z'), plane) # xz plane rotate!(scene, Vec3f(1, 0, 0), 0.5pi) translate!(scene, 0, dimval, 0) else #yz plane r1 = qrotation(Vec3f(0, 1, 0), 0.5pi) r2 = qrotation(Vec3f(1, 0, 0), 0.5pi) - rotate!(scene, r2 * r1) + rotate!(scene, r2 * r1) translate!(scene, dimval, 0, 0) end scene @@ -200,10 +196,8 @@ transform_func_obs(x) = transformation(x).transform_func Apply the data transform func to the data if the space matches one of the the transformation spaces (currently only :data is transformed) """ -apply_transform(f, data, space) = space == :data ? apply_transform(f, data) : data -function apply_transform(f::Observable, data::Observable, space::Observable) - return lift((f, d, s)-> apply_transform(f, d, s), f, data, space) -end +apply_transform(f, data, space) = space == :data ? apply_transform(f, data) : data +apply_transform(f::Observable, data::Observable, space::Observable) = lift((f, d, s) -> apply_transform(f, d, s), f, data, space) """ apply_transform(f, data) @@ -242,57 +236,45 @@ end # PointTrans{N}(func::F) where {N, F} = PointTrans{N, F}(func) Base.broadcastable(x::PointTrans) = (x,) -function apply_transform(f::PointTrans{N}, point::Point{N}) where N - return f.f(point) -end +apply_transform(f::PointTrans{N}, point::Point{N}) where N = f.f(point) 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) + 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) end end -function apply_transform(f, data::AbstractArray) - map(point-> apply_transform(f, point), data) -end +apply_transform(f, data::AbstractArray) = map(point -> apply_transform(f, point), data) -function apply_transform(f::Tuple{Any, Any}, point::VecTypes{2}) - Point2{Float32}( - f[1](point[1]), - f[2](point[2]), - ) -end +apply_transform(f::Tuple{Any, Any}, point::VecTypes{2}) = Point2{Float32}( + f[1](point[1]), + f[2](point[2]), +) # ambiguity fix apply_transform(f::NTuple{2, typeof(identity)}, point::VecTypes{2}) = point -function apply_transform(f::Tuple{Any, Any}, point::VecTypes{3}) - apply_transform((f..., identity), point) -end +apply_transform(f::Tuple{Any, Any}, point::VecTypes{3}) = apply_transform((f..., identity), point) # ambiguity fix apply_transform(f::NTuple{2, typeof(identity)}, point::VecTypes{3}) = point -function apply_transform(f::Tuple{Any, Any, Any}, point::VecTypes{3}) - Point3{Float32}( - f[1](point[1]), - f[2](point[2]), - f[3](point[3]), - ) -end +apply_transform(f::Tuple{Any, Any, Any}, point::VecTypes{3}) = Point3{Float32}( + f[1](point[1]), + f[2](point[2]), + f[3](point[3]), +) # ambiguity fix 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) -end +apply_transform(f::Observable, data::Observable) = lift((f, d) -> apply_transform(f, d), f, data) apply_transform(f, itr::Pair) = apply_transform(f, itr[1]) => apply_transform(f, itr[2]) function apply_transform(f, itr::ClosedInterval) @@ -338,7 +320,7 @@ end Symlog10(x) = Symlog10(-x, x) -function (s::Symlog10)(x) +(s::Symlog10)(x) = if x > 0 x <= s.high ? x / s.high * log10(s.high) : log10(x) elseif x < 0 @@ -346,9 +328,8 @@ function (s::Symlog10)(x) else x end -end -function inv_symlog10(x, low, high) +inv_symlog10(x, low, high) = if x > 0 l = log10(high) x <= l ? x / l * high : exp10(x) @@ -358,22 +339,19 @@ function inv_symlog10(x, low, high) else x end -end inverse_transform(::typeof(identity)) = identity inverse_transform(::typeof(log10)) = exp10 inverse_transform(::typeof(log)) = exp inverse_transform(::typeof(log2)) = exp2 -inverse_transform(::typeof(sqrt)) = x -> x ^ 2 +inverse_transform(::typeof(sqrt)) = x -> x^2 inverse_transform(::typeof(pseudolog10)) = inv_pseudolog10 inverse_transform(F::Tuple) = map(inverse_transform, F) inverse_transform(::typeof(logit)) = logistic inverse_transform(s::Symlog10) = x -> inv_symlog10(x, s.low, s.high) inverse_transform(s) = nothing -function is_identity_transform(t) - return t === identity || t isa Tuple && all(x-> x === identity, t) -end +is_identity_transform(t) = t === identity || t isa Tuple && all(x -> x === identity, t) # this is a simplification which will only really work with non-rotated or @@ -382,6 +360,4 @@ end # by translating e.g. the axis spines forward so they are not obscured halfway # by heatmaps or images zvalue2d(x)::Float32 = Makie.translation(x)[][3] + zvalue2d(x.parent) -zvalue2d(::Nothing)::Float32 = 0f0 - - +zvalue2d(::Nothing)::Float32 = 0.0f0 diff --git a/src/makielayout/blocks.jl b/src/makielayout/blocks.jl index a3f709aceb7..1cf50a1c4d1 100644 --- a/src/makielayout/blocks.jl +++ b/src/makielayout/blocks.jl @@ -28,7 +28,7 @@ macro Block(name::Symbol, body::Expr = Expr(:block)) i_forwarded_layout = findfirst( x -> x isa Expr && x.head == :macrocall && - x.args[1] == Symbol("@forwarded_layout"), + x.args[1] == Symbol("@forwarded_layout"), body.args ) has_forwarded_layout = i_forwarded_layout !== nothing @@ -48,9 +48,7 @@ macro Block(name::Symbol, body::Expr = Expr(:block)) end constructor = quote - function $name($(basefields...)) - new($(basefields...)) - end + $name($(basefields...)) = new($(basefields...)) end push!(fields_vector, constructor) @@ -63,9 +61,7 @@ macro Block(name::Symbol, body::Expr = Expr(:block)) export $name - function Makie.is_attribute(::Type{$(name)}, sym::Symbol) - sym in ($((attrs !== nothing ? [QuoteNode(a.symbol) for a in attrs] : [])...),) - end + Makie.is_attribute(::Type{$(name)}, sym::Symbol) = sym in ($((attrs !== nothing ? [QuoteNode(a.symbol) for a in attrs] : [])...),) function Makie.default_attribute_values(::Type{$(name)}, scene::Union{Scene, Nothing}) sceneattrs = scene === nothing ? Attributes() : theme(scene) @@ -74,25 +70,21 @@ macro Block(name::Symbol, body::Expr = Expr(:block)) $(make_attr_dict_expr(attrs, :sceneattrs, :curdeftheme)) end - function Makie.attribute_default_expressions(::Type{$name}) - $( - if attrs === nothing - Dict{Symbol, String}() - else - Dict{Symbol, String}([a.symbol => _defaultstring(a.default) for a in attrs]) - end - ) - end + Makie.attribute_default_expressions(::Type{$name}) = $( + if attrs === nothing + Dict{Symbol, String}() + else + Dict{Symbol, String}([a.symbol => _defaultstring(a.default) for a in attrs]) + end + ) - function Makie._attribute_docs(::Type{$(name)}) - Dict( - $( - (attrs !== nothing ? - [Expr(:call, :(=>), QuoteNode(a.symbol), a.docs) for a in attrs] : - [])... - ) + Makie._attribute_docs(::Type{$(name)}) = Dict( + $( + (attrs !== nothing ? + [Expr(:call, :(=>), QuoteNode(a.symbol), a.docs) for a in attrs] : + [])... ) - end + ) Makie.has_forwarded_layout(::Type{$name}) = $has_forwarded_layout end @@ -103,13 +95,11 @@ end _defaultstring(x) = string(x) _defaultstring(x::String) = repr(x) -function make_attr_dict_expr(::Nothing, sceneattrsym, curthemesym) - :(Dict()) -end +make_attr_dict_expr(::Nothing, sceneattrsym, curthemesym) = :(Dict()) block_docs(x) = "" -function Docs.getdoc(@nospecialize T::Type{<:Block}) +Docs.getdoc(@nospecialize T::Type{<:Block}) = if T === Block Markdown.parse(""" abstract type Block @@ -131,7 +121,6 @@ function Docs.getdoc(@nospecialize T::Type{<:Block}) """ Markdown.parse(s) end -end function _attribute_list(T) ks = sort(collect(keys(default_attribute_values(T, nothing)))) @@ -190,14 +179,12 @@ function attribute_help(T) end end -function attribute_help(T, key) - println(_attribute_docs(T)[key]) -end +attribute_help(T, key) = println(_attribute_docs(T)[key]) 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 @@ -275,9 +262,7 @@ function extract_attributes!(body) end # intercept all block constructors and divert to _block(T, ...) -function (::Type{T})(args...; kwargs...) where {T<:Block} - _block(T, args...; kwargs...) -end +(::Type{T})(args...; kwargs...) where {T <: Block} = _block(T, args...; kwargs...) can_be_current_axis(x) = false @@ -285,7 +270,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 @@ -296,11 +281,11 @@ function _block(T::Type{<:Block}, end function _block(T::Type{<:Block}, fig_or_scene::Union{Figure, Scene}, - args...; bbox = nothing, kwargs...) + args...; bbox = nothing, kwargs...) # first sort out all user kwargs that correspond to block attributes kwdict = Dict(kwargs) - + if haskey(kwdict, :textsize) throw(ArgumentError("The attribute `textsize` has been renamed to `fontsize` in Makie v0.19. Please change all occurrences of `textsize` to `fontsize` or revert back to an earlier version.")) end @@ -328,13 +313,13 @@ function _block(T::Type{<:Block}, fig_or_scene::Union{Figure, Scene}, # give kwargs priority if haskey(attribute_kwargs, key) attributes[key] = attribute_kwargs[key] - # otherwise scene theme + # otherwise scene theme elseif haskey(typekey_scene_attrs, key) attributes[key] = typekey_scene_attrs[key] - # otherwise global theme + # otherwise global theme elseif haskey(typekey_attrs, key) attributes[key] = typekey_attrs[key] - # otherwise its the value from the type default theme + # otherwise its the value from the type default theme else attributes[key] = val end @@ -470,7 +455,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 Base.setproperty!(x::T, key::Symbol, value) where T <: Block = if hasfield(T, key) if fieldtype(T, key) <: Observable if value isa Observable @@ -479,20 +464,17 @@ 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 setfield!(x, key, value) end -end # treat all blocks as scalars when broadcasting Base.Broadcast.broadcastable(l::Block) = Ref(l) -function Base.show(io::IO, ::T) where T <: Block - print(io, "$T()") -end +Base.show(io::IO, ::T) where T <: Block = print(io, "$T()") function Base.delete!(block::Block) block.parent === nothing && return @@ -533,17 +515,11 @@ deleting elements and removing from gridlayout function on_delete(block) end -function remove_element(x) - delete!(x) -end +remove_element(x) = delete!(x) -function remove_element(x::AbstractPlot) - delete!(x.parent, x) -end +remove_element(x::AbstractPlot) = delete!(x.parent, x) -function remove_element(xs::AbstractArray) - foreach(remove_element, xs) -end +remove_element(xs::AbstractArray) = foreach(remove_element, xs) function remove_element(::Nothing) end diff --git a/src/makielayout/blocks/axis.jl b/src/makielayout/blocks/axis.jl index 7c8f881f39d..d1cd22688eb 100644 --- a/src/makielayout/blocks/axis.jl +++ b/src/makielayout/blocks/axis.jl @@ -1,20 +1,18 @@ -function block_docs(::Type{Axis}) - """ - A 2D axis which can be plotted into. +block_docs(::Type{Axis}) = """ + A 2D axis which can be plotted into. - ## Constructors + ## Constructors - ```julia - Axis(fig_or_scene; palette = nothing, kwargs...) - ``` + ```julia + Axis(fig_or_scene; palette = nothing, kwargs...) + ``` - ## Examples + ## Examples - ```julia - ax = Axis(fig[1, 1]) - ``` - """ -end + ```julia + ax = Axis(fig[1, 1]) + ``` + """ function update_gridlines!(grid_obs::Observable{Vector{Point2f}}, offset::Point2f, tickpositions::Vector{Point2f}) result = grid_obs[] @@ -79,11 +77,11 @@ function register_events!(ax, scene) end function update_axis_camera(camera::Camera, t, lims, xrev::Bool, yrev::Bool) - nearclip = -10_000f0 - farclip = 10_000f0 + nearclip = -10_000.0f0 + farclip = 10_000.0f0 # we are computing transformed camera position, so this isn't space dependent - tlims = Makie.apply_transform(t, lims) + tlims = Makie.apply_transform(t, lims) left, bottom = minimum(tlims) right, top = maximum(tlims) @@ -115,22 +113,22 @@ function calculate_title_position(area, titlegap, subtitlegap, align, xaxisposit local subtitlespace::Float32 = if ax.subtitlevisible[] && !iswhitespace(ax.subtitle[]) boundingbox(subtitlet).widths[2] + subtitlegap else - 0f0 + 0.0f0 end - local yoffset::Float32 = top(area) + titlegap + (xaxisposition === :top ? xaxisprotrusion : 0f0) + - subtitlespace + local yoffset::Float32 = top(area) + titlegap + (xaxisposition === :top ? xaxisprotrusion : 0.0f0) + + 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 + local left::Float32, right::Float32, bottom::Float32, top::Float32 = 0.0f0, 0.0f0, 0.0f0, 0.0f0 if xaxisposition === :bottom bottom = xaxisprotrusion @@ -142,12 +140,12 @@ function compute_protrusions(title, titlesize, titlegap, titlevisible, spinewidt subtitleheight = boundingbox(subtitlet).widths[2] + subtitlegap titlespace = if !titlevisible || iswhitespace(title) - 0f0 + 0.0f0 else titleheight end subtitlespace = if !subtitlevisible || iswhitespace(subtitle) - 0f0 + 0.0f0 else subtitleheight end @@ -177,7 +175,7 @@ function initialize_block!(ax::Axis; palette = nothing) # initialize either with user limits, or pick defaults based on scales # so that we don't immediately error targetlimits = Observable{Rect2f}(defaultlimits(ax.limits[], ax.xscale[], ax.yscale[])) - finallimits = Observable{Rect2f}(targetlimits[]; ignore_equal_values=true) + finallimits = Observable{Rect2f}(targetlimits[]; ignore_equal_values = true) setfield!(ax, :targetlimits, targetlimits) setfield!(ax, :finallimits, finallimits) @@ -201,12 +199,12 @@ function initialize_block!(ax::Axis; palette = nothing) scenearea = sceneareanode!(ax.layoutobservables.computedbbox, finallimits, ax.aspect) - scene = Scene(topscene, px_area=scenearea) + scene = Scene(topscene, px_area = scenearea) ax.scene = scene # TODO: replace with mesh, however, CairoMakie needs a poly path for this signature # so it doesn't rasterize the scene - background = poly!(topscene, scenearea; color=ax.backgroundcolor, inspectable=false, shading=false, strokecolor=:transparent) + background = poly!(topscene, scenearea; color = ax.backgroundcolor, inspectable = false, shading = false, strokecolor = :transparent) translate!(background, 0, 0, -100) decorations[:background] = background @@ -216,7 +214,7 @@ function initialize_block!(ax::Axis; palette = nothing) ax.xaxislinks = Axis[] ax.yaxislinks = Axis[] - xgridnode = Observable(Point2f[]; ignore_equal_values=true) + xgridnode = Observable(Point2f[]; ignore_equal_values = true) xgridlines = linesegments!( topscene, xgridnode, linewidth = ax.xgridwidth, visible = ax.xgridvisible, color = ax.xgridcolor, linestyle = ax.xgridstyle, inspectable = false @@ -225,7 +223,7 @@ function initialize_block!(ax::Axis; palette = nothing) translate!(xgridlines, 0, 0, -10) decorations[:xgridlines] = xgridlines - xminorgridnode = Observable(Point2f[]; ignore_equal_values=true) + xminorgridnode = Observable(Point2f[]; ignore_equal_values = true) xminorgridlines = linesegments!( topscene, xminorgridnode, linewidth = ax.xminorgridwidth, visible = ax.xminorgridvisible, color = ax.xminorgridcolor, linestyle = ax.xminorgridstyle, inspectable = false @@ -234,7 +232,7 @@ function initialize_block!(ax::Axis; palette = nothing) translate!(xminorgridlines, 0, 0, -10) decorations[:xminorgridlines] = xminorgridlines - ygridnode = Observable(Point2f[]; ignore_equal_values=true) + ygridnode = Observable(Point2f[]; ignore_equal_values = true) ygridlines = linesegments!( topscene, ygridnode, linewidth = ax.ygridwidth, visible = ax.ygridvisible, color = ax.ygridcolor, linestyle = ax.ygridstyle, inspectable = false @@ -243,7 +241,7 @@ function initialize_block!(ax::Axis; palette = nothing) translate!(ygridlines, 0, 0, -10) decorations[:ygridlines] = ygridlines - yminorgridnode = Observable(Point2f[]; ignore_equal_values=true) + yminorgridnode = Observable(Point2f[]; ignore_equal_values = true) yminorgridlines = linesegments!( topscene, yminorgridnode, linewidth = ax.yminorgridwidth, visible = ax.yminorgridvisible, color = ax.yminorgridcolor, linestyle = ax.yminorgridstyle, inspectable = false @@ -261,7 +259,7 @@ function initialize_block!(ax::Axis; palette = nothing) onany(update_axis_camera, camera(scene), scene.transformation.transform_func, finallimits, ax.xreversed, ax.yreversed) - xaxis_endpoints = lift(ax.xaxisposition, scene.px_area; ignore_equal_values=true) do xaxisposition, area + xaxis_endpoints = lift(ax.xaxisposition, scene.px_area; ignore_equal_values = true) do xaxisposition, area if xaxisposition == :bottom return bottomline(Rect2f(area)) elseif xaxisposition == :top @@ -271,7 +269,7 @@ function initialize_block!(ax::Axis; palette = nothing) end end - yaxis_endpoints = lift(ax.yaxisposition, scene.px_area; ignore_equal_values=true) do yaxisposition, area + yaxis_endpoints = lift(ax.yaxisposition, scene.px_area; ignore_equal_values = true) do yaxisposition, area if yaxisposition == :left return leftline(Rect2f(area)) elseif yaxisposition == :right @@ -281,36 +279,36 @@ function initialize_block!(ax::Axis; palette = nothing) end end - xaxis_flipped = lift(x->x == :top, ax.xaxisposition; ignore_equal_values=true) - yaxis_flipped = lift(x->x == :right, ax.yaxisposition; ignore_equal_values=true) + xaxis_flipped = lift(x -> x == :top, ax.xaxisposition; ignore_equal_values = true) + yaxis_flipped = lift(x -> x == :right, ax.yaxisposition; ignore_equal_values = true) - xspinevisible = lift(xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible; ignore_equal_values=true) do xflip, bv, tv + xspinevisible = lift(xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible; ignore_equal_values = true) do xflip, bv, tv xflip ? tv : bv end - xoppositespinevisible = lift(xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible; ignore_equal_values=true) do xflip, bv, tv + xoppositespinevisible = lift(xaxis_flipped, ax.bottomspinevisible, ax.topspinevisible; ignore_equal_values = true) do xflip, bv, tv xflip ? bv : tv end - yspinevisible = lift(yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible; ignore_equal_values=true) do yflip, lv, rv + yspinevisible = lift(yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible; ignore_equal_values = true) do yflip, lv, rv yflip ? rv : lv end - yoppositespinevisible = lift(yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible; ignore_equal_values=true) do yflip, lv, rv + yoppositespinevisible = lift(yaxis_flipped, ax.leftspinevisible, ax.rightspinevisible; ignore_equal_values = true) do yflip, lv, rv yflip ? lv : rv end - xspinecolor = lift(xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor; ignore_equal_values=true) do xflip, bc, tc + xspinecolor = lift(xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor; ignore_equal_values = true) do xflip, bc, tc xflip ? tc : bc end - xoppositespinecolor = lift(xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor; ignore_equal_values=true) do xflip, bc, tc + xoppositespinecolor = lift(xaxis_flipped, ax.bottomspinecolor, ax.topspinecolor; ignore_equal_values = true) do xflip, bc, tc xflip ? bc : tc end - yspinecolor = lift(yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor; ignore_equal_values=true) do yflip, lc, rc + yspinecolor = lift(yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor; ignore_equal_values = true) do yflip, lc, rc yflip ? rc : lc end - yoppositespinecolor = lift(yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor; ignore_equal_values=true) do yflip, lc, rc + yoppositespinecolor = lift(yaxis_flipped, ax.leftspinecolor, ax.rightspinecolor; ignore_equal_values = true) do yflip, lc, rc yflip ? lc : rc end - xlims = lift(xlimits, finallimits; ignore_equal_values=true) - ylims = lift(ylimits, finallimits; ignore_equal_values=true) + xlims = lift(xlimits, finallimits; ignore_equal_values = true) + ylims = lift(ylimits, finallimits; ignore_equal_values = true) xaxis = LineAxis(topscene, endpoints = xaxis_endpoints, limits = xlims, flipped = xaxis_flipped, ticklabelrotation = ax.xticklabelrotation, @@ -322,7 +320,7 @@ function initialize_block!(ax::Axis; palette = nothing) ticklabelsize = ax.xticklabelsize, trimspine = ax.xtrimspine, ticksize = ax.xticksize, reversed = ax.xreversed, tickwidth = ax.xtickwidth, tickcolor = ax.xtickcolor, minorticksvisible = ax.xminorticksvisible, minortickalign = ax.xminortickalign, minorticksize = ax.xminorticksize, minortickwidth = ax.xminortickwidth, minortickcolor = ax.xminortickcolor, minorticks = ax.xminorticks, scale = ax.xscale, - ) + ) ax.xaxis = xaxis yaxis = LineAxis(topscene, endpoints = yaxis_endpoints, limits = ylims, @@ -333,13 +331,13 @@ function initialize_block!(ax::Axis; palette = nothing) ticklabelspace = ax.yticklabelspace, ticks = ax.yticks, tickformat = ax.ytickformat, ticklabelsvisible = ax.yticklabelsvisible, ticksvisible = ax.yticksvisible, spinevisible = yspinevisible, spinecolor = yspinecolor, spinewidth = ax.spinewidth, trimspine = ax.ytrimspine, ticklabelsize = ax.yticklabelsize, ticksize = ax.yticksize, flip_vertical_label = ax.flip_ylabel, reversed = ax.yreversed, tickwidth = ax.ytickwidth, - tickcolor = ax.ytickcolor, + tickcolor = ax.ytickcolor, minorticksvisible = ax.yminorticksvisible, minortickalign = ax.yminortickalign, minorticksize = ax.yminorticksize, minortickwidth = ax.yminortickwidth, minortickcolor = ax.yminortickcolor, minorticks = ax.yminorticks, scale = ax.yscale, - ) + ) ax.yaxis = yaxis - xoppositelinepoints = lift(scene.px_area, ax.spinewidth, ax.xaxisposition; ignore_equal_values=true) do r, sw, xaxpos + xoppositelinepoints = lift(scene.px_area, ax.spinewidth, ax.xaxisposition; ignore_equal_values = true) do r, sw, xaxpos if xaxpos == :top y = bottom(r) p1 = Point2f(left(r) - 0.5sw, y) @@ -353,7 +351,7 @@ function initialize_block!(ax::Axis; palette = nothing) end end - yoppositelinepoints = lift(scene.px_area, ax.spinewidth, ax.yaxisposition; ignore_equal_values=true) do r, sw, yaxpos + yoppositelinepoints = lift(scene.px_area, ax.spinewidth, ax.yaxisposition; ignore_equal_values = true) do r, sw, yaxpos if yaxpos == :right x = left(r) p1 = Point2f(x, bottom(r) - 0.5sw) @@ -420,8 +418,8 @@ function initialize_block!(ax::Axis; palette = nothing) update_gridlines!(yminorgridnode, Point2f(offset, 0), tickpos) end - subtitlepos = lift(scene.px_area, ax.titlegap, ax.titlealign, ax.xaxisposition, xaxis.protrusion; ignore_equal_values=true) do a, - titlegap, align, xaxisposition, xaxisprotrusion + subtitlepos = lift(scene.px_area, ax.titlegap, ax.titlealign, ax.xaxisposition, xaxis.protrusion; ignore_equal_values = true) do a, + titlegap, align, xaxisposition, xaxisprotrusion x = if align == :center a.origin[1] + a.widths[1] / 2 @@ -433,12 +431,12 @@ function initialize_block!(ax::Axis; palette = nothing) error("Title align $align not supported.") end - yoffset = top(a) + titlegap + (xaxisposition == :top ? xaxisprotrusion : 0f0) + yoffset = top(a) + titlegap + (xaxisposition == :top ? xaxisprotrusion : 0.0f0) return Point2f(x, yoffset) end - titlealignnode = lift(ax.titlealign; ignore_equal_values=true) do align + titlealignnode = lift(ax.titlealign; ignore_equal_values = true) do align (align, :bottom) end @@ -455,7 +453,7 @@ function initialize_block!(ax::Axis; palette = nothing) inspectable = false) titlepos = lift(calculate_title_position, scene.px_area, ax.titlegap, ax.subtitlegap, - ax.titlealign, ax.xaxisposition, xaxis.protrusion, ax.subtitlelineheight, ax, subtitlet; ignore_equal_values=true) + ax.titlealign, ax.xaxisposition, xaxis.protrusion, ax.subtitlelineheight, ax, subtitlet; ignore_equal_values = true) titlet = text!( topscene, titlepos, @@ -471,10 +469,10 @@ function initialize_block!(ax::Axis; palette = nothing) decorations[:title] = titlet map!(compute_protrusions, ax.layoutobservables.protrusions, ax.title, ax.titlesize, ax.titlegap, ax.titlevisible, ax.spinewidth, - ax.topspinevisible, ax.bottomspinevisible, ax.leftspinevisible, ax.rightspinevisible, - xaxis.protrusion, yaxis.protrusion, ax.xaxisposition, ax.yaxisposition, - ax.subtitle, ax.subtitlevisible, ax.subtitlesize, ax.subtitlegap, - ax.titlelineheight, ax.subtitlelineheight, subtitlet, titlet) + ax.topspinevisible, ax.bottomspinevisible, ax.leftspinevisible, ax.rightspinevisible, + xaxis.protrusion, yaxis.protrusion, ax.xaxisposition, ax.yaxisposition, + ax.subtitle, ax.subtitlevisible, ax.subtitlesize, ax.subtitlegap, + ax.titlelineheight, ax.subtitlelineheight, subtitlet, titlet) # trigger first protrusions with one of the observables notify(ax.title) @@ -516,21 +514,21 @@ function mirror_ticks(tickpositions, ticksize, tickalign, px_area, side, axispos a = px_area[][] if side == :x opp = axisposition == :bottom ? top(a) : bottom(a) - sign = axisposition == :bottom ? 1 : -1 + sign = axisposition == :bottom ? 1 : -1 else opp = axisposition == :left ? right(a) : left(a) sign = axisposition == :left ? 1 : -1 end d = ticksize * sign - points = Vector{Point2f}(undef, 2*length(tickpositions)) + points = Vector{Point2f}(undef, 2 * length(tickpositions)) if side == :x for (i, (x, _)) in enumerate(tickpositions) - points[2i-1] = Point2f(x, opp - d * tickalign) + points[2i - 1] = Point2f(x, opp - d * tickalign) points[2i] = Point2f(x, opp + d - d * tickalign) end else for (i, (_, y)) in enumerate(tickpositions) - points[2i-1] = Point2f(opp - d * tickalign, y) + points[2i - 1] = Point2f(opp - d * tickalign, y) points[2i] = Point2f(opp + d - d * tickalign, y) end end @@ -633,13 +631,9 @@ 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}) - (lims[1:2], lims[3:4]) -end +convert_limit_attribute(lims::Tuple{Any, Any, Any, Any}) = (lims[1:2], lims[3:4]) -function convert_limit_attribute(lims::Tuple{Any, Any}) - lims -end +convert_limit_attribute(lims::Tuple{Any, Any}) = lims can_be_current_axis(ax::Axis) = true function validate_limits_for_scales(lims::Rect, xsc, ysc) @@ -662,13 +656,12 @@ validate_limits_for_scale(lims, scale) = all(x -> x in defined_interval(scale), palettesyms(cycle::Cycle) = [c[2] for c in cycle.cycle] attrsyms(cycle::Cycle) = [c[1] for c in cycle.cycle] -function get_cycler_index!(c::Cycler, P::Type) +get_cycler_index!(c::Cycler, P::Type) = if !haskey(c.counters, P) c.counters[P] = 1 else c.counters[P] += 1 end -end function get_cycle_for_plottype(allattrs, P)::Cycle psym = MakieCore.plotsym(P) @@ -760,9 +753,9 @@ function add_cycle_attributes!(allattrs, P, cycle::Cycle, cycler::Cycler, palett end function Makie.plot!( - la::Axis, P::Makie.PlotFunc, - attributes::Makie.Attributes, args...; - kw_attributes...) + la::Axis, P::Makie.PlotFunc, + attributes::Makie.Attributes, args...; + kw_attributes...) allattrs = merge(attributes, Attributes(kw_attributes)) @@ -801,7 +794,7 @@ function needs_tight_limits(c::Contourf) end function expandbboxwithfractionalmargins(bb, margins) - newwidths = bb.widths .* (1f0 .+ margins) + newwidths = bb.widths .* (1.0f0 .+ margins) diffs = newwidths .- bb.widths neworigin = bb.origin .- (0.5f0 .* diffs) return Rect2f(neworigin, newwidths) @@ -1061,7 +1054,7 @@ protrusions for the axis and the layout will adjust. This is so the layout doesn immediately readjust during interaction, which would let the whole layout jitter around. """ function timed_ticklabelspace_reset(ax::Axis, reset_timer::Ref, - prev_xticklabelspace::Ref, prev_yticklabelspace::Ref, threshold_sec::Real) + prev_xticklabelspace::Ref, prev_yticklabelspace::Ref, threshold_sec::Real) if !isnothing(reset_timer[]) close(reset_timer[]) @@ -1090,7 +1083,7 @@ end Hide decorations of the x-axis: label, ticklabels, ticks and grid. """ function hidexdecorations!(la::Axis; label = true, ticklabels = true, ticks = true, grid = true, - minorgrid = true, minorticks = true) + minorgrid = true, minorticks = true) if label la.xlabelvisible = false end @@ -1118,7 +1111,7 @@ end Hide decorations of the y-axis: label, ticklabels, ticks and grid. """ function hideydecorations!(la::Axis; label = true, ticklabels = true, ticks = true, grid = true, - minorgrid = true, minorticks = true) + minorgrid = true, minorticks = true) if label la.ylabelvisible = false end @@ -1145,7 +1138,7 @@ end Hide decorations of both x and y-axis: label, ticklabels, ticks and grid. """ function hidedecorations!(la::Axis; label = true, ticklabels = true, ticks = true, grid = true, - minorgrid = true, minorticks = true) + minorgrid = true, minorticks = true) hidexdecorations!(la; label = label, ticklabels = ticklabels, ticks = ticks, grid = grid, minorgrid = minorgrid, minorticks = minorticks) hideydecorations!(la; label = label, ticklabels = ticklabels, ticks = ticks, grid = grid, @@ -1158,7 +1151,7 @@ end Hide all specified axis spines. Hides all spines by default, otherwise choose with the symbols :l, :r, :b and :t. """ -function hidespines!(la::Axis, spines::Symbol... = (:l, :r, :b, :t)...) +hidespines!(la::Axis, spines::Symbol... = (:l, :r, :b, :t)...) = for s in spines @match s begin :l => (la.leftspinevisible = false) @@ -1168,7 +1161,6 @@ function hidespines!(la::Axis, spines::Symbol... = (:l, :r, :b, :t)...) x => error("Invalid spine identifier $x. Valid options are :l, :r, :b and :t.") end end -end """ space = tight_xticklabel_spacing!(ax::Axis) @@ -1294,9 +1286,7 @@ function limits!(ax::Axis, rect::Rect2) Makie.ylims!(ax, ymin, ymax) end -function limits!(args...) - limits!(current_axis(), args...) -end +limits!(args...) = limits!(current_axis(), args...) function Base.delete!(ax::Axis, plot::AbstractPlot) delete!(ax.scene, plot) @@ -1314,9 +1304,7 @@ 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) - BBox(userlimits...) -end +defaultlimits(userlimits::Tuple{Real, Real, Real, Real}, xscale, yscale) = BBox(userlimits...) defaultlimits(l::Tuple{Any, Any, Any, Any}, xscale, yscale) = defaultlimits(((l[1], l[2]), (l[3], l[4])), xscale, yscale) @@ -1344,7 +1332,7 @@ defaultlimits(::Makie.Symlog10) = (0.0, 100.0) defined_interval(::typeof(identity)) = OpenInterval(-Inf, Inf) defined_interval(::Union{typeof(log2), typeof(log10), typeof(log)}) = OpenInterval(0.0, Inf) -defined_interval(::typeof(sqrt)) = Interval{:closed,:open}(0, Inf) +defined_interval(::typeof(sqrt)) = Interval{:closed, :open}(0, Inf) defined_interval(::typeof(Makie.logit)) = OpenInterval(0.0, 1.0) defined_interval(::typeof(Makie.pseudolog10)) = OpenInterval(-Inf, Inf) defined_interval(::Makie.Symlog10) = OpenInterval(-Inf, Inf) diff --git a/src/makielayout/blocks/axis3d.jl b/src/makielayout/blocks/axis3d.jl index bad81bdc8c8..be2832968d9 100644 --- a/src/makielayout/blocks/axis3d.jl +++ b/src/makielayout/blocks/axis3d.jl @@ -9,7 +9,7 @@ function initialize_block!(ax::Axis3) end notify(ax.protrusions) - finallimits = Observable(Rect3f(Vec3f(0f0, 0f0, 0f0), Vec3f(100f0, 100f0, 100f0))) + finallimits = Observable(Rect3f(Vec3f(0.0f0, 0.0f0, 0.0f0), Vec3f(100.0f0, 100.0f0, 100.0f0))) setfield!(ax, :finallimits, finallimits) scenearea = lift(round_to_IRect2D, ax.layoutobservables.computedbbox) @@ -19,12 +19,12 @@ function initialize_block!(ax::Axis3) cam = OrthographicCamera() cameracontrols!(scene, cam) - mi1 = Observable(!(pi/2 <= mod1(ax.azimuth[], 2pi) < 3pi/2)) + mi1 = Observable(!(pi / 2 <= mod1(ax.azimuth[], 2pi) < 3pi / 2)) mi2 = Observable(0 <= mod1(ax.azimuth[], 2pi) < pi) mi3 = Observable(ax.elevation[] > 0) on(ax.azimuth) do x - b = !(pi/2 <= mod1(x, 2pi) < 3pi/2) + b = !(pi / 2 <= mod1(x, 2pi) < 3pi / 2) mi1.val == b || (mi1[] = b) return end @@ -175,7 +175,7 @@ function calculate_matrices(limits, px_area, elev, azim, perspectiveness, aspect t = Makie.translationmatrix(-Float64.(limits.origin)) - s = if aspect == :equal + s = Makie.scalematrix(if aspect == :equal scales = 2 ./ Float64.(ws) elseif aspect == :data scales = 2 ./ max.(maximum(ws), Float64.(ws)) @@ -183,7 +183,7 @@ function calculate_matrices(limits, px_area, elev, azim, perspectiveness, aspect scales = 2 ./ Float64.(ws) .* Float64.(aspect) ./ maximum(aspect) else error("Invalid aspect $aspect") - end |> Makie.scalematrix + end) t2 = Makie.translationmatrix(-0.5 .* ws .* scales) scale_matrix = t2 * s * t @@ -251,12 +251,12 @@ function projectionmatrix(viewmatrix, limits, eyepos, radius, azim, elev, angle, if viewmode == :fitzoom if ratio_y > ratio_x - pm = Makie.scalematrix(Vec3(1/ratio_y, 1/ratio_y, 1)) * pm + pm = Makie.scalematrix(Vec3(1 / ratio_y, 1 / ratio_y, 1)) * pm else - pm = Makie.scalematrix(Vec3(1/ratio_x, 1/ratio_x, 1)) * pm + pm = Makie.scalematrix(Vec3(1 / ratio_x, 1 / ratio_x, 1)) * pm end else - pm = Makie.scalematrix(Vec3(1/ratio_x, 1/ratio_y, 1)) * pm + pm = Makie.scalematrix(Vec3(1 / ratio_x, 1 / ratio_y, 1)) * pm end end pm @@ -325,10 +325,10 @@ function getlimits(ax::Axis3, dim) filtered_plots = filter(ax.scene.plots) do p attr = p.attributes to_value(get(attr, :visible, true)) && - is_data_space(to_value(get(attr, :space, :data))) && - ifelse(dim == 1, to_value(get(attr, :xautolimits, true)), true) && - ifelse(dim == 2, to_value(get(attr, :yautolimits, true)), true) && - ifelse(dim == 3, to_value(get(attr, :zautolimits, true)), true) + is_data_space(to_value(get(attr, :space, :data))) && + ifelse(dim == 1, to_value(get(attr, :xautolimits, true)), true) && + ifelse(dim == 2, to_value(get(attr, :yautolimits, true)), true) && + ifelse(dim == 3, to_value(get(attr, :zautolimits, true)), true) end bboxes = Makie.data_limits.(filtered_plots) @@ -349,7 +349,7 @@ end # end -function dimpoint(dim, v, v1, v2) +dimpoint(dim, v, v1, v2) = if dim == 1 Point(v, v1, v2) elseif dim == 2 @@ -357,9 +357,8 @@ function dimpoint(dim, v, v1, v2) elseif dim == 3 Point(v1, v2, v) end -end -function dim1(dim) +dim1(dim) = if dim == 1 2 elseif dim == 2 @@ -367,9 +366,8 @@ function dim1(dim) elseif dim == 3 1 end -end -function dim2(dim) +dim2(dim) = if dim == 1 3 elseif dim == 2 @@ -377,7 +375,6 @@ function dim2(dim) elseif dim == 3 2 end -end function add_gridlines_and_frames!(topscene, scene, ax, dim::Int, limits, ticknode, miv, min1, min2) @@ -422,7 +419,7 @@ function add_gridlines_and_frames!(topscene, scene, ax, dim::Int, limits, tickno framepoints = lift(limits, scene.camera.projectionview, scene.px_area, min1, min2 - ) do lims, _, pxa, mi1, mi2 + ) do lims, _, pxa, mi1, mi2 o = pxa.origin f(mi) = mi ? minimum : maximum @@ -472,8 +469,8 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno ticklabels = @lift($ticknode[2]) tick_segments = lift(limits, tickvalues, miv, min1, min2, - scene.camera.projectionview, scene.px_area) do lims, ticks, miv, min1, min2, - pview, pxa + scene.camera.projectionview, scene.px_area) do lims, ticks, miv, min1, min2, + pview, pxa f1 = !min1 ? minimum(lims)[d1] : maximum(lims)[d1] f2 = min2 ? minimum(lims)[d2] : maximum(lims)[d2] @@ -515,7 +512,7 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno color = attr(:tickcolor), linewidth = attr(:tickwidth), visible = attr(:ticksvisible)) labels_positions = lift(scene.px_area, scene.camera.projectionview, - tick_segments, ticklabels, attr(:ticklabelpad)) do pxa, pv, ticksegs, ticklabs, pad + tick_segments, ticklabels, attr(:ticklabelpad)) do pxa, pv, ticksegs, ticklabs, pad o = pxa.origin @@ -551,13 +548,13 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno translate!(ticklabels, 0, 0, 1000) label_position = Observable(Point2f(0)) - label_rotation = Observable(0f0) + label_rotation = Observable(0.0f0) label_align = Observable((:center, :top)) onany( - scene.px_area, scene.camera.projectionview, limits, miv, min1, min2, - attr(:labeloffset), attr(:labelrotation), attr(:labelalign) - ) do pxa, pv, lims, miv, min1, min2, labeloffset, lrotation, lalign + scene.px_area, scene.camera.projectionview, limits, miv, min1, min2, + attr(:labeloffset), attr(:labelrotation), attr(:labelalign) + ) do pxa, pv, lims, miv, min1, min2, labeloffset, lrotation, lalign o = pxa.origin @@ -584,18 +581,18 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno (min1 ⊻ min2) ? 1 : -1 end - a = pi/2 + a = pi / 2 # get the vector pointing from the axis in the direction of the label anchor offset_vec = (Makie.Mat2f(cos(a), sin(a), -sin(a), cos(a)) * - Makie.GeometryBasics.normalize(diffsign * diff)) + Makie.GeometryBasics.normalize(diffsign * diff)) # calculate the label offset from the axis midpoint plus_offset = midpoint + labeloffset * offset_vec offset_ang = atan(offset_vec[2], offset_vec[1]) - offset_ang_90deg = offset_ang + pi/2 - offset_ang_90deg_alwaysup = ((offset_ang + pi/2 + pi/2) % pi) - pi/2 + offset_ang_90deg = offset_ang + pi / 2 + offset_ang_90deg_alwaysup = ((offset_ang + pi / 2 + pi / 2) % pi) - pi / 2 # # prefer rotated left 90deg to rotated right 90deg slight_flip = offset_ang_90deg_alwaysup < -deg2rad(88) @@ -640,7 +637,7 @@ function add_ticks_and_ticklabels!(topscene, scene, ax, dim::Int, limits, tickno return ticks, ticklabels, label end -function dim3point(dim1, dim2, dim3, v1, v2, v3) +dim3point(dim1, dim2, dim3, v1, v2, v3) = if (dim1, dim2, dim3) == (1, 2, 3) Point(v1, v2, v3) elseif (dim1, dim2, dim3) == (2, 3, 1) @@ -650,12 +647,11 @@ function dim3point(dim1, dim2, dim3, v1, v2, v3) else error("Invalid dim order $dim1, $dim2, $dim3") end -end function add_panel!(scene, ax, dim1, dim2, dim3, limits, min3) dimsym(sym) = Symbol(string((:x, :y, :z)[dim1]) * - string((:x, :y, :z)[dim2]) * string(sym)) + string((:x, :y, :z)[dim2]) * string(sym)) attr(sym) = getproperty(ax, dimsym(sym)) vertices = lift(limits, min3) do lims, mi3 @@ -782,13 +778,9 @@ 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}) - (lims[1:2], lims[3:4], lims[5:6]) -end +convert_limit_attribute(lims::Tuple{Any, Any, Any, Any, Any, Any}) = (lims[1:2], lims[3:4], lims[5:6]) -function convert_limit_attribute(lims::Tuple{Any, Any, Any}) - lims -end +convert_limit_attribute(lims::Tuple{Any, Any, Any}) = lims function xautolimits(ax::Axis3) @@ -838,11 +830,11 @@ function Makie.xlims!(ax::Axis3, xlims::Tuple{Union{Real, Nothing}, Union{Real, error("Invalid xlims length of $(length(xlims)), must be 2.") elseif xlims[1] == xlims[2] error("Can't set x limits to the same value $(xlims[1]).") - # elseif all(x -> x isa Real, xlims) && xlims[1] > xlims[2] - # xlims = reverse(xlims) - # ax.xreversed[] = true - # else - # ax.xreversed[] = false + # elseif all(x -> x isa Real, xlims) && xlims[1] > xlims[2] + # xlims = reverse(xlims) + # ax.xreversed[] = true + # else + # ax.xreversed[] = false end ax.limits.val = (xlims, ax.limits[][2], ax.limits[][3]) @@ -855,11 +847,11 @@ function Makie.ylims!(ax::Axis3, ylims::Tuple{Union{Real, Nothing}, Union{Real, error("Invalid ylims length of $(length(ylims)), must be 2.") elseif ylims[1] == ylims[2] error("Can't set y limits to the same value $(ylims[1]).") - # elseif all(x -> x isa Real, ylims) && ylims[1] > ylims[2] - # ylims = reverse(ylims) - # ax.yreversed[] = true - # else - # ax.yreversed[] = false + # elseif all(x -> x isa Real, ylims) && ylims[1] > ylims[2] + # ylims = reverse(ylims) + # ax.yreversed[] = true + # else + # ax.yreversed[] = false end ax.limits.val = (ax.limits[][1], ylims, ax.limits[][3]) @@ -872,11 +864,11 @@ function Makie.zlims!(ax::Axis3, zlims) error("Invalid zlims length of $(length(zlims)), must be 2.") elseif zlims[1] == zlims[2] error("Can't set y limits to the same value $(zlims[1]).") - # elseif all(x -> x isa Real, zlims) && zlims[1] > zlims[2] - # zlims = reverse(zlims) - # ax.zreversed[] = true - # else - # ax.zreversed[] = false + # elseif all(x -> x isa Real, zlims) && zlims[1] > zlims[2] + # zlims = reverse(zlims) + # ax.zreversed[] = true + # else + # ax.zreversed[] = false end ax.limits.val = (ax.limits[][1], ax.limits[][2], zlims) diff --git a/src/makielayout/blocks/button.jl b/src/makielayout/blocks/button.jl index 59d956bbaf1..ee94085d058 100644 --- a/src/makielayout/blocks/button.jl +++ b/src/makielayout/blocks/button.jl @@ -7,7 +7,7 @@ function initialize_block!(b::Button) subarea = lift(b.layoutobservables.computedbbox) do bbox round_to_IRect2D(bbox) end - subscene = Scene(scene, subarea, camera=campixel!) + subscene = Scene(scene, subarea, camera = campixel!) # buttonrect is without the left bottom offset of the bbox buttonrect = lift(b.layoutobservables.computedbbox) do bbox @@ -24,14 +24,14 @@ function initialize_block!(b::Button) bcolors = (; out = b.buttoncolor, active = b.buttoncolor_active, hover = b.buttoncolor_hover) bcolor = Observable{RGBColors}() - map!((s,_...)-> to_color(bcolors[s][]), bcolor, mousestate, values(bcolors)...) + map!((s, _...) -> to_color(bcolors[s][]), bcolor, mousestate, values(bcolors)...) button = poly!(subscene, roundedrectpoints, strokewidth = b.strokewidth, strokecolor = b.strokecolor, color = bcolor, inspectable = false) lcolors = (; out = b.labelcolor, active = b.labelcolor_active, hover = b.labelcolor_hover) lcolor = Observable{RGBColors}() - map!((s,_...)-> to_color(lcolors[s][]), lcolor, mousestate, values(lcolors)...) + map!((s, _...) -> to_color(lcolors[s][]), lcolor, mousestate, values(lcolors)...) labeltext = text!(subscene, textpos, text = b.label, fontsize = b.fontsize, font = b.font, color = lcolor, align = (:center, :center), markerspace = :data, inspectable = false) diff --git a/src/makielayout/blocks/colorbar.jl b/src/makielayout/blocks/colorbar.jl index e29b95e9928..5040fb71183 100644 --- a/src/makielayout/blocks/colorbar.jl +++ b/src/makielayout/blocks/colorbar.jl @@ -1,21 +1,19 @@ -function block_docs(::Type{Colorbar}) - """ - Create a colorbar that shows a continuous or categorical colormap with ticks - chosen according to the colorrange. - - You can set colorrange and colormap manually, or pass a plot object as the second argument - to copy its respective attributes. - - ## Constructors - - ```julia - Colorbar(fig_or_scene; kwargs...) - Colorbar(fig_or_scene, plot::AbstractPlot; kwargs...) - Colorbar(fig_or_scene, heatmap::Union{Heatmap, Image}; kwargs...) - Colorbar(fig_or_scene, contourf::Makie.Contourf; kwargs...) - ``` - """ -end +block_docs(::Type{Colorbar}) = """ + Create a colorbar that shows a continuous or categorical colormap with ticks + chosen according to the colorrange. + + You can set colorrange and colormap manually, or pass a plot object as the second argument + to copy its respective attributes. + + ## Constructors + + ```julia + Colorbar(fig_or_scene; kwargs...) + Colorbar(fig_or_scene, plot::AbstractPlot; kwargs...) + Colorbar(fig_or_scene, heatmap::Union{Heatmap, Image}; kwargs...) + Colorbar(fig_or_scene, contourf::Makie.Contourf; kwargs...) + ``` + """ function Colorbar(fig_or_scene, plot::AbstractPlot; kwargs...) @@ -119,15 +117,15 @@ function initialize_block!(cb::Colorbar) return c != compare end - lowclip_tri_visible = lift(isvisible, cb.lowclip, lift(x-> get(x, 0), cgradient)) - highclip_tri_visible = lift(isvisible, cb.highclip, lift(x-> get(x, 1), cgradient)) + lowclip_tri_visible = lift(isvisible, cb.lowclip, lift(x -> get(x, 0), cgradient)) + highclip_tri_visible = lift(isvisible, cb.highclip, lift(x -> get(x, 1), cgradient)) tri_heights = lift(highclip_tri_visible, lowclip_tri_visible, framebox) do hv, lv, box if cb.vertical[] (lv * width(box), hv * width(box)) else (lv * height(box), hv * height(box)) - end .* sin(pi/3) + end .* sin(pi / 3) end barsize = lift(tri_heights) do heights @@ -182,14 +180,14 @@ function initialize_block!(cb::Colorbar) rects = if v yvals = s_scaled .* (ymax - ymin) .+ ymin [BBox(xmin, xmax, b, t) - for (b, t) in zip(yvals[1:end-1], yvals[2:end])] + for (b, t) in zip(yvals[1:(end - 1)], yvals[2:end])] else xvals = s_scaled .* (xmax - xmin) .+ xmin [BBox(l, r, ymin, ymax) - for (l, r) in zip(xvals[1:end-1], xvals[2:end])] + for (l, r) in zip(xvals[1:(end - 1)], xvals[2:end])] end - colors = get.(Ref(gradient), (steps[1:end-1] .+ steps[2:end]) ./2) + colors = get.(Ref(gradient), (steps[1:(end - 1)] .+ steps[2:end]) ./ 2) rects, colors end @@ -226,11 +224,11 @@ function initialize_block!(cb::Colorbar) lb, rb = topline(box) l = lb r = rb - t = ((l .+ r) ./ 2) .+ Point2f(0, sqrt(sum((r .- l) .^ 2)) * sin(pi/3)) + t = ((l .+ r) ./ 2) .+ Point2f(0, sqrt(sum((r .- l) .^ 2)) * sin(pi / 3)) [l, r, t] else b, t = rightline(box) - r = ((b .+ t) ./ 2) .+ Point2f(sqrt(sum((t .- b) .^ 2)) * sin(pi/3), 0) + r = ((b .+ t) ./ 2) .+ Point2f(sqrt(sum((t .- b) .^ 2)) * sin(pi / 3), 0) [t, b, r] end end @@ -248,11 +246,11 @@ function initialize_block!(cb::Colorbar) lb, rb = bottomline(box) l = lb r = rb - t = ((l .+ r) ./ 2) .- Point2f(0, sqrt(sum((r .- l) .^ 2)) * sin(pi/3)) + t = ((l .+ r) ./ 2) .- Point2f(0, sqrt(sum((r .- l) .^ 2)) * sin(pi / 3)) [l, r, t] else b, t = leftline(box) - l = ((b .+ t) ./ 2) .- Point2f(sqrt(sum((t .- b) .^ 2)) * sin(pi/3), 0) + l = ((b .+ t) ./ 2) .- Point2f(sqrt(sum((t .- b) .^ 2)) * sin(pi / 3), 0) [b, t, l] end end @@ -294,7 +292,7 @@ function initialize_block!(cb::Colorbar) lines!(blockscene, borderpoints, linewidth = cb.spinewidth, color = cb.topspinecolor, inspectable = false) axispoints = lift(barbox, cb.vertical, cb.flipaxis) do scenearea, - vertical, flipaxis + vertical, flipaxis if vertical if flipaxis @@ -331,10 +329,10 @@ function initialize_block!(cb::Colorbar) onany(axis.protrusion, cb.vertical, cb.flipaxis) do axprotrusion, - vertical, flipaxis + vertical, flipaxis - left, right, top, bottom = 0f0, 0f0, 0f0, 0f0 + left, right, top, bottom = 0.0f0, 0.0f0, 0.0f0, 0.0f0 if vertical if flipaxis diff --git a/src/makielayout/blocks/intervalslider.jl b/src/makielayout/blocks/intervalslider.jl index a8a50a6366d..fb9e1316e3a 100644 --- a/src/makielayout/blocks/intervalslider.jl +++ b/src/makielayout/blocks/intervalslider.jl @@ -19,12 +19,12 @@ function initialize_block!(isl::IntervalSlider) if horizontal y = bottom(bb) + h / 2 - [Point2f(left(bb) + h/2, y), - Point2f(right(bb) - h/2, y)] + [Point2f(left(bb) + h / 2, y), + Point2f(right(bb) - h / 2, y)] else x = left(bb) + w / 2 - [Point2f(x, bottom(bb) + w/2), - Point2f(x, top(bb) - w/2)] + [Point2f(x, bottom(bb) + w / 2), + Point2f(x, top(bb) - w / 2)] end end diff --git a/src/makielayout/blocks/label.jl b/src/makielayout/blocks/label.jl index a755cc54e05..70d2da1eacf 100644 --- a/src/makielayout/blocks/label.jl +++ b/src/makielayout/blocks/label.jl @@ -6,12 +6,12 @@ function initialize_block!(l::Label) layoutobservables = l.layoutobservables textpos = Observable(Point3f(0, 0, 0)) - word_wrap_width = Observable(-1f0) + word_wrap_width = Observable(-1.0f0) t = text!( topscene, textpos, text = l.text, fontsize = l.fontsize, font = l.font, color = l.color, visible = l.visible, align = (:center, :center), rotation = l.rotation, markerspace = :data, - justification = l.justification, lineheight = l.lineheight, word_wrap_width = word_wrap_width, + justification = l.justification, lineheight = l.lineheight, word_wrap_width = word_wrap_width, inspectable = false) textbb = Ref(BBox(0, 1, 0, 1)) diff --git a/src/makielayout/blocks/legend.jl b/src/makielayout/blocks/legend.jl index fa33e25d764..2e7191c2e67 100644 --- a/src/makielayout/blocks/legend.jl +++ b/src/makielayout/blocks/legend.jl @@ -1,5 +1,5 @@ function initialize_block!(leg::Legend, - entry_groups::Observable{Vector{Tuple{Optional{<:AbstractString}, Vector{LegendEntry}}}}) + entry_groups::Observable{Vector{Tuple{Optional{<:AbstractString}, Vector{LegendEntry}}}}) blockscene = leg.blockscene @@ -81,7 +81,7 @@ function initialize_block!(leg::Legend, end elseif leg.orientation[] == :horizontal if leg.titleposition[] == :left - isnothing(title) || (grid[1, 2g-1] = title) + isnothing(title) || (grid[1, 2g - 1] = title) grid[1, 2g] = GridLayout(halign = leg.gridshalign[], valign = leg.gridsvalign[]) elseif leg.titleposition[] == :top isnothing(title) || (grid[1, g] = title) @@ -91,17 +91,17 @@ function initialize_block!(leg::Legend, for (n, (et, er)) in enumerate(zip(etexts, erects)) i, j = leg.orientation[] == :vertical ? rowcol(n) : reverse(rowcol(n)) - subgl[i, 2j-1] = er + subgl[i, 2j - 1] = er subgl[i, 2j] = et end rowgap!(subgl, leg.rowgap[]) - for c in 1:ncols(subgl)-1 + for c in 1:(ncols(subgl) - 1) colgap!(subgl, c, c % 2 == 1 ? leg.patchlabelgap[] : leg.colgap[]) end end - for r in 1:nrows(grid)-1 + for r in 1:(nrows(grid) - 1) if leg.orientation[] == :horizontal if leg.titleposition[] == :left # nothing @@ -116,7 +116,7 @@ function initialize_block!(leg::Legend, end end end - for c in 1:ncols(grid)-1 + for c in 1:(ncols(grid) - 1) if leg.orientation[] == :horizontal if leg.titleposition[] == :left colgap!(grid, c, c % 2 == 1 ? leg.titlegap[] : leg.groupgap[]) @@ -147,7 +147,7 @@ function initialize_block!(leg::Legend, end onany(leg.nbanks, leg.titleposition, leg.rowgap, leg.colgap, leg.patchlabelgap, leg.groupgap, leg.titlegap, - leg.titlevisible, leg.orientation, leg.gridshalign, leg.gridsvalign) do args... + leg.titlevisible, leg.orientation, leg.gridshalign, leg.gridsvalign) do args... relayout() end @@ -203,12 +203,12 @@ function initialize_block!(leg::Legend, return lj isa Automatic ? lha : lj end push!(etexts, - Label(scene; text=e.label, fontsize=e.labelsize, font=e.labelfont, justification=justification, - color=e.labelcolor, halign=e.labelhalign, valign=e.labelvalign)) + Label(scene; text = e.label, fontsize = e.labelsize, font = e.labelfont, justification = justification, + color = e.labelcolor, halign = e.labelhalign, valign = e.labelvalign)) # create the patch rectangle - rect = Box(scene; color=e.patchcolor, strokecolor=e.patchstrokecolor, strokewidth=e.patchstrokewidth, - width=lift(x -> x[1], e.patchsize), height=lift(x -> x[2], e.patchsize)) + rect = Box(scene; color = e.patchcolor, strokecolor = e.patchstrokecolor, strokewidth = e.patchstrokewidth, + width = lift(x -> x[1], e.patchsize), height = lift(x -> x[2], e.patchsize)) push!(erects, rect) translate!(rect.blockscene, 0, 0, -5) # patches before background but behind legend elements (legend is at +10) @@ -216,7 +216,7 @@ function initialize_block!(leg::Legend, symbolplots = AbstractPlot[] for element in e.elements append!(symbolplots, - legendelement_plots!(scene, element, rect.layoutobservables.computedbbox, e.attributes)) + legendelement_plots!(scene, element, rect.layoutobservables.computedbbox, e.attributes)) end push!(eplots, symbolplots) @@ -287,25 +287,21 @@ function legendelement_plots!(scene, element::PolyElement, bbox::Observable{Rect [pol] end -function Base.getproperty(lentry::LegendEntry, s::Symbol) +Base.getproperty(lentry::LegendEntry, s::Symbol) = if s in fieldnames(LegendEntry) getfield(lentry, s) else lentry.attributes[s] end -end -function Base.setproperty!(lentry::LegendEntry, s::Symbol, value) +Base.setproperty!(lentry::LegendEntry, s::Symbol, value) = if s in fieldnames(LegendEntry) setfield!(lentry, s, value) else lentry.attributes[s][] = value end -end -function Base.propertynames(lentry::LegendEntry) - [fieldnames(T)..., keys(lentry.attributes)...] -end +Base.propertynames(lentry::LegendEntry) = [fieldnames(T)..., keys(lentry.attributes)...] legendelements(le::LegendElement, legend) = LegendElement[le] legendelements(les::AbstractArray{<:LegendElement}, legend) = LegendElement[les...] @@ -332,17 +328,11 @@ function LegendEntry(label::Optional{AbstractString}, contentelement, legend; kw end -function LineElement(;kwargs...) - _legendelement(LineElement, Attributes(kwargs)) -end +LineElement(; kwargs...) = _legendelement(LineElement, Attributes(kwargs)) -function MarkerElement(;kwargs...) - _legendelement(MarkerElement, Attributes(kwargs)) -end +MarkerElement(; kwargs...) = _legendelement(MarkerElement, Attributes(kwargs)) -function PolyElement(;kwargs...) - _legendelement(PolyElement, Attributes(kwargs)) -end +PolyElement(; kwargs...) = _legendelement(PolyElement, Attributes(kwargs)) function _legendelement(T::Type{<:LegendElement}, a::Attributes) _rename_attributes!(T, a) @@ -389,31 +379,25 @@ function scalar_lift(attr, default) return observable end -function legendelements(plot::Union{Lines, LineSegments}, legend) - LegendElement[LineElement( - color = scalar_lift(plot.color, legend.linecolor), - linestyle = scalar_lift(plot.linestyle, legend.linestyle), - linewidth = scalar_lift(plot.linewidth, legend.linewidth))] -end +legendelements(plot::Union{Lines, LineSegments}, legend) = LegendElement[LineElement( + color = scalar_lift(plot.color, legend.linecolor), + linestyle = scalar_lift(plot.linestyle, legend.linestyle), + linewidth = scalar_lift(plot.linewidth, legend.linewidth))] -function legendelements(plot::Scatter, legend) - LegendElement[MarkerElement( - color = scalar_lift(plot.color, legend.markercolor), - marker = scalar_lift(plot.marker, legend.marker), - markersize = scalar_lift(plot.markersize, legend.markersize), - strokewidth = scalar_lift(plot.strokewidth, legend.markerstrokewidth), - strokecolor = scalar_lift(plot.strokecolor, legend.markerstrokecolor), - )] -end +legendelements(plot::Scatter, legend) = LegendElement[MarkerElement( + color = scalar_lift(plot.color, legend.markercolor), + marker = scalar_lift(plot.marker, legend.marker), + markersize = scalar_lift(plot.markersize, legend.markersize), + strokewidth = scalar_lift(plot.strokewidth, legend.markerstrokewidth), + strokecolor = scalar_lift(plot.strokecolor, legend.markerstrokecolor), +)] -function legendelements(plot::Union{Poly, Violin, BoxPlot, CrossBar, Density}, legend) - LegendElement[PolyElement( - color = scalar_lift(plot.color, legend.polycolor), - strokecolor = scalar_lift(plot.strokecolor, legend.polystrokecolor), - strokewidth = scalar_lift(plot.strokewidth, legend.polystrokewidth), - )] -end +legendelements(plot::Union{Poly, Violin, BoxPlot, CrossBar, Density}, legend) = LegendElement[PolyElement( + color = scalar_lift(plot.color, legend.polycolor), + strokecolor = scalar_lift(plot.strokecolor, legend.polystrokecolor), + strokewidth = scalar_lift(plot.strokewidth, legend.polystrokewidth), +)] function legendelements(plot::Band, legend) # there seems to be no stroke for Band, so we set it invisible @@ -429,25 +413,21 @@ function legendelements(plot, legend)::Vector{LegendElement} reduce(vcat, [legendelements(childplot, legend) for childplot in plot.plots]) end -function Base.getproperty(legendelement::T, s::Symbol) where T <: LegendElement +Base.getproperty(legendelement::T, s::Symbol) where T <: LegendElement = if s in fieldnames(T) getfield(legendelement, s) else legendelement.attributes[s] end -end -function Base.setproperty!(legendelement::T, s::Symbol, value) where T <: LegendElement +Base.setproperty!(legendelement::T, s::Symbol, value) where T <: LegendElement = if s in fieldnames(T) setfield!(legendelement, s, value) else legendelement.attributes[s][] = value end -end -function Base.propertynames(legendelement::T) where T <: LegendElement - [fieldnames(T)..., keys(legendelement.attributes)...] -end +Base.propertynames(legendelement::T) where T <: LegendElement = [fieldnames(T)..., keys(legendelement.attributes)...] @@ -465,10 +445,10 @@ one content element. A content element can be an `AbstractPlot`, an array of `legendelements` method is defined. """ function Legend(fig_or_scene, - contents::AbstractArray, - labels::AbstractArray{<:Optional{AbstractString}}, - title::Optional{<:AbstractString} = nothing; - kwargs...) + contents::AbstractArray, + labels::AbstractArray{<:Optional{AbstractString}}, + title::Optional{<:AbstractString} = nothing; + kwargs...) if length(contents) != length(labels) error("Number of elements not equal: $(length(contents)) content elements and $(length(labels)) labels.") @@ -500,10 +480,10 @@ element can be an `AbstractPlot`, an array of `AbstractPlots`, a `LegendElement` or any other object for which the `legendelements` method is defined. """ function Legend(fig_or_scene, - contentgroups::AbstractArray{<:AbstractArray}, - labelgroups::AbstractArray{<:AbstractArray}, - titles::AbstractArray{<:Optional{<:AbstractString}}; - kwargs...) + contentgroups::AbstractArray{<:AbstractArray}, + labelgroups::AbstractArray{<:AbstractArray}, + titles::AbstractArray{<:Optional{<:AbstractString}}; + kwargs...) if !(length(titles) == length(contentgroups) == length(labelgroups)) error("Number of elements not equal: $(length(titles)) titles, $(length(contentgroups)) content groups and $(length(labelgroups)) label groups.") @@ -513,7 +493,7 @@ function Legend(fig_or_scene, entrygroups = Observable{Vector{EntryGroup}}([]) legend = Legend(fig_or_scene, entrygroups; kwargs...) entries = [[LegendEntry(l, pg, legend) for (l, pg) in zip(labelgroup, contentgroup)] - for (labelgroup, contentgroup) in zip(labelgroups, contentgroups)] + for (labelgroup, contentgroup) in zip(labelgroups, contentgroups)] entrygroups[] = [(t, en) for (t, en) in zip(titles, entries)] legend end @@ -552,7 +532,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 @@ -595,13 +575,11 @@ 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 axislegend(ax, args...; position = :rt, kwargs...) - Legend(ax.parent, args...; - bbox = ax.scene.px_area, - margin = (10, 10, 10, 10), - legend_position_to_aligns(position)..., - kwargs...) -end +axislegend(ax, args...; position = :rt, kwargs...) = Legend(ax.parent, args...; + bbox = ax.scene.px_area, + margin = (10, 10, 10, 10), + legend_position_to_aligns(position)..., + kwargs...) function legend_position_to_aligns(s::Symbol) p = string(s) @@ -624,6 +602,4 @@ 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}) - (halign = t[1], valign = t[2]) -end +legend_position_to_aligns(t::Tuple{Any, Any}) = (halign = t[1], valign = t[2]) diff --git a/src/makielayout/blocks/menu.jl b/src/makielayout/blocks/menu.jl index c1083b5bb96..efabd6ca10f 100644 --- a/src/makielayout/blocks/menu.jl +++ b/src/makielayout/blocks/menu.jl @@ -1,61 +1,59 @@ -function block_docs(::Type{Menu}) - """ - A drop-down menu with multiple selectable options. You can pass options - with the keyword argument `options`. +block_docs(::Type{Menu}) = """ + A drop-down menu with multiple selectable options. You can pass options + with the keyword argument `options`. - Options are given as an iterable of elements. - For each element, the option label in the menu is determined with `optionlabel(element)` - and the option value with `optionvalue(element)`. These functions can be - overloaded for custom types. The default is that tuples of two elements are expected to be label and value, - where `string(label)` is used as the label, while for all other objects, label = `string(object)` and value = object. + Options are given as an iterable of elements. + For each element, the option label in the menu is determined with `optionlabel(element)` + and the option value with `optionvalue(element)`. These functions can be + overloaded for custom types. The default is that tuples of two elements are expected to be label and value, + where `string(label)` is used as the label, while for all other objects, label = `string(object)` and value = object. - When an item is selected in the menu, the menu's `selection` attribute is set to - `optionvalue(selected_element)`. When nothing is selected, that value is `nothing`. + When an item is selected in the menu, the menu's `selection` attribute is set to + `optionvalue(selected_element)`. When nothing is selected, that value is `nothing`. - You can set the initial selection by passing one of the labels with the `default` keyword. + You can set the initial selection by passing one of the labels with the `default` keyword. - ## Constructors + ## Constructors - ```julia - Menu(fig_or_scene; default = nothing, kwargs...) - ``` + ```julia + Menu(fig_or_scene; default = nothing, kwargs...) + ``` - ## Examples + ## Examples - Menu with string entries, second preselected: + Menu with string entries, second preselected: - ```julia - menu1 = Menu(fig[1, 1], options = ["first", "second", "third"], default = "second") - ``` + ```julia + menu1 = Menu(fig[1, 1], options = ["first", "second", "third"], default = "second") + ``` - Menu with two-element entries, label and function: + Menu with two-element entries, label and function: - ```julia - funcs = [sin, cos, tan] - labels = ["Sine", "Cosine", "Tangens"] + ```julia + funcs = [sin, cos, tan] + labels = ["Sine", "Cosine", "Tangens"] - menu2 = Menu(fig[1, 1], options = zip(labels, funcs)) - ``` + menu2 = Menu(fig[1, 1], options = zip(labels, funcs)) + ``` - Executing a function when a selection is made: + Executing a function when a selection is made: - ```julia - on(menu2.selection) do selected_function - # do something with the selected function - end - ``` - """ -end + ```julia + on(menu2.selection) do selected_function + # do something with the selected function + end + ``` + """ function initialize_block!(m::Menu; default = 1) blockscene = m.blockscene - listheight = Observable(0.0; ignore_equal_values=true) + listheight = Observable(0.0; ignore_equal_values = true) # the direction is auto-chosen as up if there is too little space below and if the space below # is smaller than above - _direction = Observable{Symbol}(:none; ignore_equal_values=true) + _direction = Observable{Symbol}(:none; ignore_equal_values = true) map!(_direction, m.layoutobservables.computedbbox, m.direction) do bb, dir if dir == Makie.automatic @@ -73,17 +71,17 @@ function initialize_block!(m::Menu; default = 1) end end - scenearea = lift(m.layoutobservables.computedbbox, listheight, _direction, m.is_open; ignore_equal_values=true) do bbox, h, d, open + scenearea = lift(m.layoutobservables.computedbbox, listheight, _direction, m.is_open; ignore_equal_values = true) do bbox, h, d, open !open ? - round_to_IRect2D(BBox(left(bbox), right(bbox), 0, 0)) : - round_to_IRect2D(BBox( - left(bbox), - right(bbox), - d == :down ? max(0, bottom(bbox) - h) : top(bbox), - d == :down ? bottom(bbox) : min(top(bbox) + h, top(blockscene.px_area[])))) + round_to_IRect2D(BBox(left(bbox), right(bbox), 0, 0)) : + round_to_IRect2D(BBox( + left(bbox), + right(bbox), + d == :down ? max(0, bottom(bbox) - h) : top(bbox), + d == :down ? bottom(bbox) : min(top(bbox) + h, top(blockscene.px_area[])))) end - menuscene = Scene(blockscene, scenearea, camera = campixel!, clear=true) + menuscene = Scene(blockscene, scenearea, camera = campixel!, clear = true) translate!(menuscene, 0, 0, 200) onany(scenearea, listheight) do area, listheight @@ -93,9 +91,9 @@ function initialize_block!(m::Menu; default = 1) translate!(menuscene, t[1], new_y, t[3]) end - optionstrings = lift(o -> optionlabel.(o), m.options; ignore_equal_values=true) + optionstrings = lift(o -> optionlabel.(o), m.options; ignore_equal_values = true) - selected_text = lift(m.prompt, m.i_selected; ignore_equal_values=true) do prompt, i_selected + selected_text = lift(m.prompt, m.i_selected; ignore_equal_values = true) do prompt, i_selected if i_selected == 0 prompt else @@ -103,14 +101,14 @@ function initialize_block!(m::Menu; default = 1) end end - selectionarea = Observable(Rect2f(0, 0, 0, 0); ignore_equal_values=true) + selectionarea = Observable(Rect2f(0, 0, 0, 0); ignore_equal_values = true) selectionpoly = poly!( blockscene, selectionarea, color = m.selection_cell_color_inactive[]; inspectable = false ) - selectiontextpos = Observable(Point2f(0, 0); ignore_equal_values=true) + selectiontextpos = Observable(Point2f(0, 0); ignore_equal_values = true) selectiontext = text!( blockscene, selectiontextpos, text = selected_text, align = (:left, :center), fontsize = m.fontsize, color = m.textcolor, markerspace = :data, inspectable = false @@ -125,13 +123,13 @@ function initialize_block!(m::Menu; default = 1) on(m.layoutobservables.computedbbox) do cbb selectionarea[] = cbb ch = height(cbb) - selectiontextpos[] = cbb.origin + Point2f(m.textpadding[][1], ch/2) + selectiontextpos[] = cbb.origin + Point2f(m.textpadding[][1], ch / 2) end - textpositions = Observable(zeros(Point2f, length(optionstrings[])); ignore_equal_values=true) + textpositions = Observable(zeros(Point2f, length(optionstrings[])); ignore_equal_values = true) - optionrects = Observable([Rect2f(0, 0, 0, 0)]; ignore_equal_values=true) - optionpolycolors = Observable(RGBAf[RGBAf(0.5, 0.5, 0.5, 1)]; ignore_equal_values=true) + optionrects = Observable([Rect2f(0, 0, 0, 0)]; ignore_equal_values = true) + optionpolycolors = Observable(RGBAf[RGBAf(0.5, 0.5, 0.5, 1)]; ignore_equal_values = true) function update_option_colors!(hovered) n = length(optionstrings[]) @@ -166,7 +164,7 @@ function initialize_block!(m::Menu; default = 1) heights_cumsum = [zero(eltype(heights)); cumsum(heights)] h = sum(heights) list_y_bounds[] = h .- heights_cumsum - texts_y = @views h .- 0.5 .* (heights_cumsum[1:end-1] .+ heights_cumsum[2:end]) + texts_y = @views h .- 0.5 .* (heights_cumsum[1:(end - 1)] .+ heights_cumsum[2:end]) textpositions[] = Point2f.(pad[1], texts_y) listheight[] = h w_bbox = width(bbox) @@ -174,7 +172,7 @@ function initialize_block!(m::Menu; default = 1) resize!(optionrects.val, length(bbs)) optionrects.val .= map(eachindex(bbs)) do i - BBox(0, w_bbox, h - heights_cumsum[i+1], h - heights_cumsum[i]) + BBox(0, w_bbox, h - heights_cumsum[i + 1], h - heights_cumsum[i]) end update_option_colors!(0) @@ -189,8 +187,8 @@ function initialize_block!(m::Menu; default = 1) # translation due to scrolling has to be removed first ytrans = y - translation(menuscene)[][2] i = argmin( - i -> abs(ytrans - 0.5 * (list_y_bounds[][i+1] + list_y_bounds[][i])), - 1:length(list_y_bounds[])-1 + i -> abs(ytrans - 0.5 * (list_y_bounds[][i + 1] + list_y_bounds[][i])), + 1:(length(list_y_bounds[]) - 1) ) end @@ -220,7 +218,7 @@ function initialize_block!(m::Menu; default = 1) return false end - onany(e.mouseposition, e.mousebutton, priority=64) do position, butt + onany(e.mouseposition, e.mousebutton, priority = 64) do position, butt mp = screen_relative(menuscene, position) # track if we have been inside menu/options to clean up if we haven't been is_over_options = false @@ -289,7 +287,7 @@ function initialize_block!(m::Menu; default = 1) return Consume(false) end - on(menuscene.events.scroll, priority=61) do (x, y) + on(menuscene.events.scroll, priority = 61) do (x, y) if is_mouseinside(menuscene) t = translation(menuscene)[] new_y = max(min(t[2] - y, 0), height(menuscene.px_area[]) - listheight[]) @@ -361,7 +359,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) @@ -371,18 +369,10 @@ function initialize_block!(m::Menu; default = 1) return end -function optionlabel(option) - string(option) -end +optionlabel(option) = string(option) -function optionlabel(option::Tuple{Any, Any}) - string(option[1]) -end +optionlabel(option::Tuple{Any, Any}) = string(option[1]) -function optionvalue(option) - option -end +optionvalue(option) = option -function optionvalue(option::Tuple{Any, Any}) - option[2] -end +optionvalue(option::Tuple{Any, Any}) = option[2] diff --git a/src/makielayout/blocks/scene.jl b/src/makielayout/blocks/scene.jl index f1c05989190..53e350814d2 100644 --- a/src/makielayout/blocks/scene.jl +++ b/src/makielayout/blocks/scene.jl @@ -1,7 +1,7 @@ function Makie.plot!( - lscene::LScene, P::Makie.PlotFunc, - attributes::Makie.Attributes, args...; - kw_attributes...) + lscene::LScene, P::Makie.PlotFunc, + attributes::Makie.Attributes, args...; + kw_attributes...) plot = Makie.plot!(lscene.scene, P, attributes, args...; kw_attributes...) notify(lscene.scene.theme.limits) @@ -19,7 +19,7 @@ end function initialize_block!(ls::LScene; scenekw = NamedTuple()) blockscene = ls.blockscene # pick a camera and draw axis. - scenekw = merge((clear = false, camera=cam3d!), scenekw) + scenekw = merge((clear = false, camera = cam3d!), scenekw) ls.scene = Scene(blockscene, lift(round_to_IRect2D, ls.layoutobservables.computedbbox); scenekw...) on(ls.show_axis) do show_axis @@ -32,7 +32,7 @@ function initialize_block!(ls::LScene; scenekw = NamedTuple()) if lims === automatic dl = data_limits(ls.scene, p -> Makie.isaxis(p) || Makie.not_in_data_space(p)) if any(isinf, widths(dl)) || any(isinf, Makie.origin(dl)) - Rect3f((0f0, 0f0, 0f0), (1f0, 1f0, 1f0)) + Rect3f((0.0f0, 0.0f0, 0.0f0), (1.0f0, 1.0f0, 1.0f0)) else dl end @@ -42,7 +42,7 @@ function initialize_block!(ls::LScene; scenekw = NamedTuple()) end Makie.axis3d!(ls.scene, limits) # Make sure axis is always in pos 1 - sort!(ls.scene.plots, by=!Makie.isaxis) + sort!(ls.scene.plots, by = !Makie.isaxis) else ax.visible = true end diff --git a/src/makielayout/blocks/slider.jl b/src/makielayout/blocks/slider.jl index 000b5f8ff72..7791a94e537 100644 --- a/src/makielayout/blocks/slider.jl +++ b/src/makielayout/blocks/slider.jl @@ -3,7 +3,7 @@ function initialize_block!(sl::Slider) topscene = sl.blockscene sliderrange = sl.range - + onany(sl.linewidth, sl.horizontal) do lw, horizontal if horizontal sl.layoutobservables.autosize[] = (nothing, Float32(lw)) @@ -21,12 +21,12 @@ function initialize_block!(sl::Slider) if horizontal y = bottom(bb) + h / 2 - [Point2f(left(bb) + h/2, y), - Point2f(right(bb) - h/2, y)] + [Point2f(left(bb) + h / 2, y), + Point2f(right(bb) - h / 2, y)] else x = left(bb) + w / 2 - [Point2f(x, bottom(bb) + w/2), - Point2f(x, top(bb) - w/2)] + [Point2f(x, bottom(bb) + w / 2), + Point2f(x, top(bb) - w / 2)] end end @@ -79,7 +79,7 @@ function initialize_block!(sl::Slider) end endbuttons = scatter!(topscene, endpoints, color = linecolors, - markersize = sl.linewidth, strokewidth = 0, inspectable = false, marker=Circle) + markersize = sl.linewidth, strokewidth = 0, inspectable = false, marker = Circle) linesegs = linesegments!(topscene, linepoints, color = linecolors, linewidth = sl.linewidth, inspectable = false) @@ -87,7 +87,7 @@ function initialize_block!(sl::Slider) button_magnification = Observable(1.0) buttonsize = @lift($(sl.linewidth) * $button_magnification) button = scatter!(topscene, middlepoint, color = sl.color_active, strokewidth = 0, - markersize = buttonsize, inspectable = false, marker=Circle) + markersize = buttonsize, inspectable = false, marker = Circle) mouseevents = addmouseevents!(topscene, sl.layoutobservables.computedbbox) @@ -95,10 +95,10 @@ function initialize_block!(sl::Slider) dragging[] = true dif = event.px - event.prev_px fraction = clamp(if sl.horizontal[] - (event.px[1] - endpoints[][1][1]) / (endpoints[][2][1] - endpoints[][1][1]) - else - (event.px[2] - endpoints[][1][2]) / (endpoints[][2][2] - endpoints[][1][2]) - end, 0, 1) + (event.px[1] - endpoints[][1][1]) / (endpoints[][2][1] - endpoints[][1][1]) + else + (event.px[2] - endpoints[][1][2]) / (endpoints[][2][2] - endpoints[][1][2]) + end, 0, 1) newindex = closest_fractionindex(sliderrange[], fraction) if sl.snap[] diff --git a/src/makielayout/blocks/slidergrid.jl b/src/makielayout/blocks/slidergrid.jl index ea57b2fcad4..e48d6aadb83 100644 --- a/src/makielayout/blocks/slidergrid.jl +++ b/src/makielayout/blocks/slidergrid.jl @@ -1,41 +1,39 @@ -function block_docs(::Type{SliderGrid}) - """ - A grid of horizontal `Slider`s, where each slider has one name label on the left, - and a value label on the right. +block_docs(::Type{SliderGrid}) = """ + A grid of horizontal `Slider`s, where each slider has one name label on the left, + and a value label on the right. - Each `NamedTuple` you pass specifies one `Slider`. You always have to pass `range` - and `label`, and optionally a `format` for the value label. Beyond that, you can set - any keyword that `Slider` takes, such as `startvalue`. + Each `NamedTuple` you pass specifies one `Slider`. You always have to pass `range` + and `label`, and optionally a `format` for the value label. Beyond that, you can set + any keyword that `Slider` takes, such as `startvalue`. - The `format` keyword can be a `String` with Formatting.jl style, such as "{:.2f}Hz", or - a function. + The `format` keyword can be a `String` with Formatting.jl style, such as "{:.2f}Hz", or + a function. - ## Constructors + ## Constructors - ```julia - SliderGrid(fig_or_scene, nts::NamedTuple...; kwargs...) - ``` + ```julia + SliderGrid(fig_or_scene, nts::NamedTuple...; kwargs...) + ``` - ## Examples + ## Examples - ```julia - sg = SliderGrid(fig[1, 1], - (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), "π")) - ) - ``` + ```julia + sg = SliderGrid(fig[1, 1], + (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), "π")) + ) + ``` - Working with slider values: + Working with slider values: - ```julia - on(sg.sliders[1].value) do val - # do something with `val` - end - ``` - """ -end + ```julia + on(sg.sliders[1].value) do val + # do something with `val` + end + ``` + """ function initialize_block!(sg::SliderGrid, nts::NamedTuple...) diff --git a/src/makielayout/blocks/textbox.jl b/src/makielayout/blocks/textbox.jl index 9c4b21fa1d0..adfcc84ff8b 100644 --- a/src/makielayout/blocks/textbox.jl +++ b/src/makielayout/blocks/textbox.jl @@ -90,7 +90,7 @@ function initialize_block!(tbox::Textbox) end if 0 < ci < length(bbs) - [leftline(bbs[ci+1])...] + [leftline(bbs[ci + 1])...] elseif ci == 0 [leftline(bbs[1])...] else @@ -125,7 +125,7 @@ function initialize_block!(tbox::Textbox) pos = state.data closest_charindex = argmin( - [sum((pos .- center(bb)).^2) for bb in displayed_charbbs[]] + [sum((pos .- center(bb)) .^ 2) for bb in displayed_charbbs[]] ) # set cursor to index of closest char if right of center, or previous char if left of center cursorindex[] = if (pos .- center(displayed_charbbs[][closest_charindex]))[1] > 0 @@ -160,17 +160,15 @@ 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 - function appendchar!(c) - insertchar!(c, length(tbox.displayed_string[])) - end + appendchar!(c) = insertchar!(c, length(tbox.displayed_string[])) 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 = [' '] @@ -200,15 +198,12 @@ function initialize_block!(tbox::Textbox) end end - function cursor_forward() + cursor_forward() = if tbox.displayed_string[] != " " cursorindex[] = min(length(tbox.displayed_string[]), cursorindex[] + 1) end - end - function cursor_backward() - cursorindex[] = max(0, cursorindex[] - 1) - end + cursor_backward() = cursorindex[] = max(0, cursorindex[] - 1) on(events(scene).keyboardbutton, priority = 60) do event @@ -283,13 +278,9 @@ function charbbs(text) bbs end -function validate_textbox(str, validator::Function) - validator(str) -end +validate_textbox(str, validator::Function) = validator(str) -function validate_textbox(str, T::Type) - !isnothing(tryparse(T, str)) -end +validate_textbox(str, T::Type) = !isnothing(tryparse(T, str)) function validate_textbox(str, validator::Regex) m = match(validator, str) @@ -297,13 +288,9 @@ function validate_textbox(str, validator::Regex) !isnothing(m) && m.match == str end -function is_allowed(char, restriction::Nothing) - true -end +is_allowed(char, restriction::Nothing) = true -function is_allowed(char, restriction::Function) - allowed::Bool = restriction(char) -end +is_allowed(char, restriction::Function) = allowed::Bool = restriction(char) """ reset!(tb::Textbox) @@ -343,7 +330,7 @@ function focus!(tb::Textbox) [0, 1.0], [Colors.alphacolor(COLOR_ACCENT[], 0), Colors.alphacolor(COLOR_ACCENT[], 1)], Animations.sineio(n = 2, yoyo = true, postwait = 0.2)), - 0.0, 0.0, 1000) + 0.0, 0.0, 1000) if !isnothing(tb.cursoranimtask) Animations.stop(tb.cursoranimtask) diff --git a/src/makielayout/blocks/toggle.jl b/src/makielayout/blocks/toggle.jl index 6cdc5bb4d4c..146eca94b86 100644 --- a/src/makielayout/blocks/toggle.jl +++ b/src/makielayout/blocks/toggle.jl @@ -75,7 +75,7 @@ function initialize_block!(t::Toggle) animating[] = false break end - sleep(1/FPS[]) + sleep(1 / FPS[]) end return Consume(true) end diff --git a/src/makielayout/defaultattributes.jl b/src/makielayout/defaultattributes.jl index 01626c8203d..a6873991f06 100644 --- a/src/makielayout/defaultattributes.jl +++ b/src/makielayout/defaultattributes.jl @@ -1,61 +1,54 @@ -function inherit(scene, attr::Symbol, default_value) +inherit(scene, attr::Symbol, default_value) = if haskey(scene.theme, attr) lift(identity, scene.theme[attr]) else inherit(scene.parent, attr, default_value) end -end -function inherit(::Nothing, attr::Symbol, default_value) - default_value -end +inherit(::Nothing, attr::Symbol, default_value) = default_value -function default_attributes(::Type{LineAxis}) - Attributes( - endpoints = (Point2f(0, 0), Point2f(100, 0)), - trimspine = false, - limits = (0f0, 100f0), - flipped = false, - flip_vertical_label = false, - ticksize = 6f0, - tickwidth = 1f0, - tickcolor = RGBf(0, 0, 0), - tickalign = 0f0, - ticks = Makie.automatic, - tickformat = Makie.automatic, - ticklabelalign = (:center, :top), - ticksvisible = true, - ticklabelrotation = 0f0, - ticklabelsize = 20f0, - ticklabelcolor = RGBf(0, 0, 0), - ticklabelsvisible = true, - spinewidth = 1f0, - label = "label", - labelsize = 20f0, - labelcolor = RGBf(0, 0, 0), - labelvisible = true, - ticklabelspace = Makie.automatic, - ticklabelpad = 3f0, - labelpadding = 5f0, - reversed = false, - minorticksvisible = true, - minortickalign = 0f0, - minorticksize = 4f0, - minortickwidth = 1f0, - minortickcolor = :black, - minorticks = Makie.automatic, - scale = identity, - ) -end +default_attributes(::Type{LineAxis}) = Attributes( + endpoints = (Point2f(0, 0), Point2f(100, 0)), + trimspine = false, + limits = (0.0f0, 100.0f0), + flipped = false, + flip_vertical_label = false, + ticksize = 6.0f0, + tickwidth = 1.0f0, + tickcolor = RGBf(0, 0, 0), + tickalign = 0.0f0, + ticks = Makie.automatic, + tickformat = Makie.automatic, + ticklabelalign = (:center, :top), + ticksvisible = true, + ticklabelrotation = 0.0f0, + ticklabelsize = 20.0f0, + ticklabelcolor = RGBf(0, 0, 0), + ticklabelsvisible = true, + spinewidth = 1.0f0, + label = "label", + labelsize = 20.0f0, + labelcolor = RGBf(0, 0, 0), + labelvisible = true, + ticklabelspace = Makie.automatic, + ticklabelpad = 3.0f0, + labelpadding = 5.0f0, + reversed = false, + minorticksvisible = true, + minortickalign = 0.0f0, + minorticksize = 4.0f0, + minortickwidth = 1.0f0, + minortickcolor = :black, + minorticks = Makie.automatic, + scale = identity, +) -function attributenames(::Type{LegendEntry}) - (:label, :labelsize, :labelfont, :labelcolor, :labelhalign, :labelvalign, - :patchsize, :patchstrokecolor, :patchstrokewidth, :patchcolor, - :linepoints, :linewidth, :linecolor, :linestyle, - :markerpoints, :markersize, :markerstrokewidth, :markercolor, :markerstrokecolor, - :polypoints, :polystrokewidth, :polycolor, :polystrokecolor) -end +attributenames(::Type{LegendEntry}) = (:label, :labelsize, :labelfont, :labelcolor, :labelhalign, :labelvalign, + :patchsize, :patchstrokecolor, :patchstrokewidth, :patchcolor, + :linepoints, :linewidth, :linecolor, :linestyle, + :markerpoints, :markersize, :markerstrokewidth, :markercolor, :markerstrokecolor, + :polypoints, :polystrokewidth, :polycolor, :polystrokecolor) function extractattributes(attributes::Attributes, typ::Type) extracted = Attributes() diff --git a/src/makielayout/geometrybasics_extension.jl b/src/makielayout/geometrybasics_extension.jl index 3edcc050fbe..48f01a38928 100644 --- a/src/makielayout/geometrybasics_extension.jl +++ b/src/makielayout/geometrybasics_extension.jl @@ -14,37 +14,25 @@ bottomline(bbox::Rect2) = (bottomleft(bbox), bottomright(bbox)) leftline(bbox::Rect2) = (bottomleft(bbox), topleft(bbox)) rightline(bbox::Rect2) = (bottomright(bbox), topright(bbox)) -function shrinkbymargin(rect, margin) - return Recti(minimum(rect) .+ margin, (widths(rect) .- 2 .* margin)) -end +shrinkbymargin(rect, margin) = Recti(minimum(rect) .+ margin, (widths(rect) .- 2 .* margin)) function limits(r::Rect{N, T}) where {N, T} mini, maxi = extrema(r) return ntuple(i -> (mini[i], maxi[i]), N) end -function limits(r::Rect, dim::Integer) - return (minimum(r)[dim], maximum(r)[dim]) -end +limits(r::Rect, dim::Integer) = (minimum(r)[dim], maximum(r)[dim]) xlimits(r::Rect) = limits(r, 1) ylimits(r::Rect) = limits(r, 2) -function enlarge(bbox::Rect2, l, r, b, t) - BBox(left(bbox) - l, right(bbox) + r, bottom(bbox) - b, top(bbox) + t) -end +enlarge(bbox::Rect2, l, r, b, t) = BBox(left(bbox) - l, right(bbox) + r, bottom(bbox) - b, top(bbox) + t) -function center(bbox::Rect2) - Point2((right(bbox) + left(bbox)) / 2, (top(bbox) + bottom(bbox)) / 2) -end +center(bbox::Rect2) = Point2((right(bbox) + left(bbox)) / 2, (top(bbox) + bottom(bbox)) / 2) """ Converts a point in fractions of rect dimensions into real coordinates. """ -function fractionpoint(bbox::Rect2f, point::T) where T <: Point2 - T(left(bbox) + point[1] * width(bbox), bottom(bbox) + point[2] * height(bbox)) -end +fractionpoint(bbox::Rect2f, point::T) where T <: Point2 = T(left(bbox) + point[1] * width(bbox), bottom(bbox) + point[2] * height(bbox)) -function anglepoint(center::Point2, angle::Real, radius::Real) - Ref(center) .+ Ref(Point2(cos(angle), sin(angle))) .* radius -end +anglepoint(center::Point2, angle::Real, radius::Real) = Ref(center) .+ Ref(Point2(cos(angle), sin(angle))) .* radius diff --git a/src/makielayout/helpers.jl b/src/makielayout/helpers.jl index 5d0b24ef525..ce4eac0eb3d 100644 --- a/src/makielayout/helpers.jl +++ b/src/makielayout/helpers.jl @@ -10,8 +10,8 @@ function round_to_IRect2D(r::Rect{2}) Rect{2, Int}(newori, newwidth) end -function sceneareanode!(finalbbox, limits, aspect) - return map(finalbbox, limits, aspect; ignore_equal_values=true) do bbox, limits, aspect +sceneareanode!(finalbbox, limits, aspect) = + map(finalbbox, limits, aspect; ignore_equal_values = true) do bbox, limits, aspect w = width(bbox) h = height(bbox) @@ -48,7 +48,6 @@ function sceneareanode!(finalbbox, limits, aspect) # only update scene if pixel positions change return round_to_IRect2D(newbbox) end -end function roundedrectvertices(rect, cornerradius, cornersegments) cr = cornerradius @@ -67,24 +66,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,11 +110,10 @@ Example: tightlimits!(laxis, Bottom()) ``` """ -function tightlimits!(la::Axis, sides::Union{Left, Right, Bottom, Top}...) +tightlimits!(la::Axis, sides::Union{Left, Right, Bottom, Top}...) = for s in sides tightlimits!(la, s) end -end function tightlimits!(la::Axis, ::Left) la.xautolimitmargin = Base.setindex(la.xautolimitmargin[], 0.0, 1) @@ -172,13 +170,13 @@ function axislines!(scene, rect, spinewidth, topspinevisible, rightspinevisible, end (lines!(scene, bottomline, linewidth = spinewidth, - visible = bottomspinevisible, color = bottomspinecolor), - lines!(scene, leftline, linewidth = spinewidth, - visible = leftspinevisible, color = leftspinecolor), - lines!(scene, rightline, linewidth = spinewidth, - visible = rightspinevisible, color = rightspinecolor), - lines!(scene, topline, linewidth = spinewidth, - visible = topspinevisible, color = topspinecolor)) + visible = bottomspinevisible, color = bottomspinecolor), + lines!(scene, leftline, linewidth = spinewidth, + visible = leftspinevisible, color = leftspinecolor), + lines!(scene, rightline, linewidth = spinewidth, + visible = rightspinevisible, color = rightspinecolor), + lines!(scene, topline, linewidth = spinewidth, + visible = topspinevisible, color = topspinecolor)) end @@ -249,17 +247,17 @@ macro documented_attributes(exp) # make a dictionary of :variable_name => docstring_expression exp_docdict = Expr(:call, :Dict, (Expr(:call, Symbol("=>"), QuoteNode(name), strexp) - for (name, _, strexp) in vars_and_exps)...) + for (name, _, strexp) in vars_and_exps)...) # make a dictionary of :variable_name => docstring_expression defaults_dict = Expr(:call, :Dict, (Expr(:call, Symbol("=>"), QuoteNode(name), exp isa String ? "\"$exp\"" : string(exp)) - for (name, exp, _) in vars_and_exps)...) + for (name, exp, _) in vars_and_exps)...) # make an Attributes instance with of variable_name = variable_expression exp_attrs = Expr(:call, :Attributes, (Expr(:kw, name, exp) - for (name, exp, _) in vars_and_exps)...) + for (name, exp, _) in vars_and_exps)...) esc(quote ($exp_attrs, $exp_docdict, $defaults_dict) @@ -317,13 +315,13 @@ layout[1, 1] = ls.layout ``` """ function labelslider!(scene, label, range; format = string, - sliderkw = Dict(), labelkw = Dict(), valuekw = Dict(), value_column_width = automatic, layoutkw...) + sliderkw = Dict(), labelkw = Dict(), valuekw = Dict(), value_column_width = automatic, layoutkw...) slider = Slider(scene; range = range, sliderkw...) label = Label(scene, label; labelkw...) valuelabel = Label(scene, lift(x -> apply_format(x, format), slider.value); valuekw...) layout = hbox!(label, slider, valuelabel; layoutkw...) - Base.depwarn("labelslider! is deprecated and will be removed in the future. Use SliderGrid instead." , :labelslider!, force = true) + Base.depwarn("labelslider! is deprecated and will be removed in the future. Use SliderGrid instead.", :labelslider!, force = true) if value_column_width === automatic maxwidth = 0.0 @@ -376,9 +374,9 @@ layout[1, 1] = ls.layout ``` """ function labelslidergrid!(scene, labels, ranges; formats = [string], value_column_width = automatic, - sliderkw = Dict(), labelkw = Dict(), valuekw = Dict(), layoutkw...) + sliderkw = Dict(), labelkw = Dict(), valuekw = Dict(), layoutkw...) - Base.depwarn("labelslidergrid! is deprecated and will be removed in the future. Use SliderGrid instead." , :labelslidergrid!, force = true) + Base.depwarn("labelslidergrid! is deprecated and will be removed in the future. Use SliderGrid instead.", :labelslidergrid!, force = true) elements = broadcast(labels, ranges, formats) do label, range, format slider = Slider(scene; range = range, sliderkw...) @@ -420,13 +418,9 @@ function labelslidergrid!(scene, labels, ranges; formats = [string], value_colum (sliders = sliders, labels = labels, valuelabels = valuelabels, layout = layout) end -function apply_format(value, format) - format(value) -end +apply_format(value, format) = format(value) -function apply_format(value, formatstring::String) - Formatting.format(formatstring, value) -end +apply_format(value, formatstring::String) = Formatting.format(formatstring, value) Makie.get_scene(ax::Axis) = ax.scene Makie.get_scene(ax::Axis3) = ax.scene diff --git a/src/makielayout/interactions.jl b/src/makielayout/interactions.jl index 537f114a552..f1a2d8b6931 100644 --- a/src/makielayout/interactions.jl +++ b/src/makielayout/interactions.jl @@ -151,7 +151,7 @@ function process_interaction(r::RectangleZoom, event::MouseEvent, ax::Axis) inv_transf = Makie.inverse_transform(transf) if isnothing(inv_transf) - @warn "Can't rectangle zoom without inverse transform" maxlog=1 + @warn "Can't rectangle zoom without inverse transform" maxlog = 1 # TODO, what can we do without inverse? return Consume(false) end @@ -179,7 +179,7 @@ function process_interaction(r::RectangleZoom, event::MouseEvent, ax::Axis) try r.callback(r.rectnode[]) catch e - @warn "error in rectangle zoom" exception=e + @warn "error in rectangle zoom" exception = e end r.active[] = false return Consume(true) @@ -243,16 +243,16 @@ function process_interaction(s::ScrollZoom, event::ScrollEvent, ax::Axis) if zoom != 0 pa = pixelarea(scene)[] - z = (1f0 - s.speed)^zoom + z = (1.0f0 - s.speed)^zoom mp_axscene = Vec4f((e.mouseposition[] .- pa.origin)..., 0, 1) # first to normal -1..1 space - mp_axfraction = (cam.pixel_space[] * mp_axscene)[Vec(1, 2)] .* - # now to 1..-1 if an axis is reversed to correct zoom point - (-2 .* ((ax.xreversed[], ax.yreversed[])) .+ 1) .* - # now to 0..1 - 0.5 .+ 0.5 + mp_axfraction = (cam.pixel_space[] * mp_axscene)[Vec(1, 2)] .* + # now to 1..-1 if an axis is reversed to correct zoom point + (-2 .* ((ax.xreversed[], ax.yreversed[])) .+ 1) .* + # now to 0..1 + 0.5 .+ 0.5 xscale = ax.xscale[] yscale = ax.yscale[] @@ -361,7 +361,7 @@ function process_interaction(dr::DragRotate, event::MouseEvent, ax3d) dpx = event.px - event.prev_px ax3d.azimuth[] += -dpx[1] * 0.01 - ax3d.elevation[] = clamp(ax3d.elevation[] - dpx[2] * 0.01, -pi/2 + 0.001, pi/2 - 0.001) + ax3d.elevation[] = clamp(ax3d.elevation[] - dpx[2] * 0.01, -pi / 2 + 0.001, pi / 2 - 0.001) return Consume(true) end diff --git a/src/makielayout/lineaxis.jl b/src/makielayout/lineaxis.jl index aed8d714e90..9d324f2e3f9 100644 --- a/src/makielayout/lineaxis.jl +++ b/src/makielayout/lineaxis.jl @@ -21,33 +21,33 @@ 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 label_is_empty::Bool = iswhitespace(label) || isempty(label) real_labelsize::Float32 = if label_is_empty - 0f0 + 0.0f0 else boundingbox(labeltext).widths[horizontal[] ? 2 : 1] end - labelspace::Float32 = (labelvisible && !label_is_empty) ? real_labelsize + labelpadding : 0f0 + labelspace::Float32 = (labelvisible && !label_is_empty) ? real_labelsize + labelpadding : 0.0f0 - _tickspace::Float32 = (ticksvisible && !isempty(ticklabel_annotation_obs[])) ? tickspace : 0f0 + _tickspace::Float32 = (ticksvisible && !isempty(ticklabel_annotation_obs[])) ? tickspace : 0.0f0 - ticklabelgap::Float32 = (ticklabelsvisible && actual_ticklabelspace > 0) ? actual_ticklabelspace + ticklabelpad : 0f0 + ticklabelgap::Float32 = (ticklabelsvisible && actual_ticklabelspace > 0) ? actual_ticklabelspace + ticklabelpad : 0.0f0 return _tickspace + ticklabelgap + labelspace 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 @@ -97,13 +97,13 @@ function calculate_real_ticklabel_align(al, horizontal, fl::Bool, rot::Number) else (fl ? :left : :right, :center) end - elseif rot ≈ pi/2 + elseif rot ≈ pi / 2 if hor (fl ? :left : :right, :center) else (:center, fl ? :top : :bottom) end - elseif rot ≈ -pi/2 + elseif rot ≈ -pi / 2 if hor (fl ? :right : :left, :center) else @@ -130,9 +130,9 @@ function calculate_real_ticklabel_align(al, horizontal, fl::Bool, rot::Number) end function update_ticklabel_node( - closure_args, - ticklabel_annotation_obs::Observable, - labelgap::Number, flipped::Bool, tickpositions::Vector{Point2f}, tickstrings) + closure_args, + ticklabel_annotation_obs::Observable, + labelgap::Number, flipped::Bool, tickpositions::Vector{Point2f}, tickstrings) # tickspace is always updated before labelgap # tickpositions are always updated before tickstrings # so we don't need to lift those @@ -144,9 +144,9 @@ function update_ticklabel_node( ticklabelgap::Float32 = spinewidth[] + tickspace[] + ticklabelpad[] shift = if horizontal[] - Point2f(0f0, flipped ? ticklabelgap : -ticklabelgap) + Point2f(0.0f0, flipped ? ticklabelgap : -ticklabelgap) else - Point2f(flipped ? ticklabelgap : -ticklabelgap, 0f0) + Point2f(flipped ? ticklabelgap : -ticklabelgap, 0.0f0) end # re-use already allocated array result = ticklabel_annotation_obs[] @@ -167,14 +167,14 @@ function update_tick_obs(tick_obs, horizontal::Observable{Bool}, flipped::Observ sign::Int = flipped[] ? -1 : 1 if horizontal[] for tp in tickpositions - tstart = tp + sign * Point2f(0f0, tickalign * ticksize - 0.5f0 * spinewidth) - tend = tstart + sign * Point2f(0f0, -ticksize) + tstart = tp + sign * Point2f(0.0f0, tickalign * ticksize - 0.5f0 * spinewidth) + tend = tstart + sign * Point2f(0.0f0, -ticksize) push!(result, tstart, tend) end else for tp in tickpositions - tstart = tp + sign * Point2f(tickalign * ticksize - 0.5f0 * spinewidth, 0f0) - tend = tstart + sign * Point2f(-ticksize, 0f0) + tstart = tp + sign * Point2f(tickalign * ticksize - 0.5f0 * spinewidth, 0.0f0) + tend = tstart + sign * Point2f(-ticksize, 0.0f0) push!(result, tstart, tend) end end @@ -203,7 +203,7 @@ function update_tickpos_string(closure_args, tickvalues_labels_unfiltered, rever # we only check approximately because otherwise because of floating point errors, ticks can be dismissed sometimes i_values_within_limits = findall(tickvalues_unfiltered) do tv return (limits[1] <= tv || limits[1] ≈ tv) && - (tv <= limits[2] || tv ≈ limits[2]) + (tv <= limits[2] || tv ≈ limits[2]) end tickvalues[] = tickvalues_unfiltered[i_values_within_limits] @@ -263,13 +263,13 @@ function LineAxis(parent::Scene, attrs::Attributes) labelrotation, labelvisible, spinevisible, trimspine, flip_vertical_label, reversed, minorticksvisible, minortickalign, minorticksize, minortickwidth, minortickcolor, minorticks) - pos_extents_horizontal = lift(calculate_horizontal_extends, endpoints; ignore_equal_values=true) - horizontal = lift(x-> x[3], pos_extents_horizontal) + pos_extents_horizontal = lift(calculate_horizontal_extends, endpoints; ignore_equal_values = true) + horizontal = lift(x -> x[3], pos_extents_horizontal) # Tuple constructor converts more than `convert(NTuple{2, Float32}, x)` but we still need the conversion to Float32 tuple: - limits = lift(x-> convert(NTuple{2, Float32}, Tuple(x)), attrs.limits; ignore_equal_values=true) - flipped = lift(x-> convert(Bool, x), attrs.flipped; ignore_equal_values=true) + limits = lift(x -> convert(NTuple{2, Float32}, Tuple(x)), attrs.limits; ignore_equal_values = true) + flipped = lift(x -> convert(Bool, x), attrs.flipped; ignore_equal_values = true) - ticksnode = Observable(Point2f[]; ignore_equal_values=true) + ticksnode = Observable(Point2f[]; ignore_equal_values = true) ticklines = linesegments!( parent, ticksnode, linewidth = tickwidth, color = tickcolor, linestyle = nothing, visible = ticksvisible, inspectable = false @@ -277,7 +277,7 @@ function LineAxis(parent::Scene, attrs::Attributes) decorations[:ticklines] = ticklines translate!(ticklines, 0, 0, 10) - minorticksnode = Observable(Point2f[]; ignore_equal_values=true) + minorticksnode = Observable(Point2f[]; ignore_equal_values = true) minorticklines = linesegments!( parent, minorticksnode, linewidth = minortickwidth, color = minortickcolor, linestyle = nothing, visible = minorticksvisible, inspectable = false @@ -285,21 +285,21 @@ function LineAxis(parent::Scene, attrs::Attributes) decorations[:minorticklines] = minorticklines translate!(minorticklines, 0, 0, 10) - realticklabelalign = Observable{Tuple{Symbol, Symbol}}((:none, :none); ignore_equal_values=true) + realticklabelalign = Observable{Tuple{Symbol, Symbol}}((:none, :none); ignore_equal_values = true) map!(calculate_real_ticklabel_align, realticklabelalign, ticklabelalign, horizontal, flipped, ticklabelrotation) - ticklabel_annotation_obs = Observable(Tuple{AbstractString, Point2f}[]; ignore_equal_values=true) + ticklabel_annotation_obs = Observable(Tuple{AbstractString, Point2f}[]; ignore_equal_values = true) ticklabels = nothing # this gets overwritten later to be used in the below - ticklabel_ideal_space = Observable(0f0; ignore_equal_values=true) + ticklabel_ideal_space = Observable(0.0f0; ignore_equal_values = true) map!(ticklabel_ideal_space, ticklabel_annotation_obs, ticklabelalign, ticklabelrotation, ticklabelfont, ticklabelsvisible) do args... maxwidth = if pos_extents_horizontal[][3] - # height - ticklabelsvisible[] ? (ticklabels === nothing ? 0f0 : height(Rect2f(boundingbox(ticklabels)))) : 0f0 - else - # width - ticklabelsvisible[] ? (ticklabels === nothing ? 0f0 : width(Rect2f(boundingbox(ticklabels)))) : 0f0 + # height + ticklabelsvisible[] ? (ticklabels === nothing ? 0.0f0 : height(Rect2f(boundingbox(ticklabels)))) : 0.0f0 + else + # width + ticklabelsvisible[] ? (ticklabels === nothing ? 0.0f0 : width(Rect2f(boundingbox(ticklabels)))) : 0.0f0 end # in case there is no string in the annotations and the boundingbox comes back all NaN if !isfinite(maxwidth) @@ -308,7 +308,7 @@ function LineAxis(parent::Scene, attrs::Attributes) return maxwidth end - attrs[:actual_ticklabelspace] = 0f0 + attrs[:actual_ticklabelspace] = 0.0f0 actual_ticklabelspace = attrs[:actual_ticklabelspace] onany(ticklabel_ideal_space, ticklabelspace) do idealspace, space @@ -322,22 +322,22 @@ function LineAxis(parent::Scene, attrs::Attributes) end end - tickspace = Observable(0f0; ignore_equal_values=true) + tickspace = Observable(0.0f0; ignore_equal_values = true) map!(tickspace, ticksvisible, ticksize, tickalign) do ticksvisible, ticksize, tickalign - ticksvisible ? max(0f0, ticksize * (1f0 - tickalign)) : 0f0 + ticksvisible ? max(0.0f0, ticksize * (1.0f0 - tickalign)) : 0.0f0 end - labelgap = Observable(0f0; ignore_equal_values=true) + labelgap = Observable(0.0f0; ignore_equal_values = true) map!(labelgap, spinewidth, tickspace, ticklabelsvisible, actual_ticklabelspace, ticklabelpad, labelpadding) do spinewidth, tickspace, ticklabelsvisible, - actual_ticklabelspace, ticklabelpad, labelpadding + actual_ticklabelspace, ticklabelpad, labelpadding return spinewidth + tickspace + - (ticklabelsvisible ? actual_ticklabelspace + ticklabelpad : 0f0) + - labelpadding + (ticklabelsvisible ? actual_ticklabelspace + ticklabelpad : 0.0f0) + + labelpadding end - labelpos = Observable(Point2f(NaN); ignore_equal_values=true) + labelpos = Observable(Point2f(NaN); ignore_equal_values = true) map!(labelpos, pos_extents_horizontal, flipped, labelgap) do (position, extents, horizontal), flipped, labelgap # fullgap = tickspace[] + labelgap @@ -349,9 +349,9 @@ function LineAxis(parent::Scene, attrs::Attributes) end # Initial values should be overwritten by map!. `ignore_equal_values` doesn't work right now without initial values - labelalign = Observable((:none, :none); ignore_equal_values=true) + labelalign = Observable((:none, :none); ignore_equal_values = true) map!(labelalign, labelrotation, horizontal, flipped, flip_vertical_label) do labelrotation, - horizontal::Bool, flipped::Bool, flip_vertical_label::Bool + horizontal::Bool, flipped::Bool, flip_vertical_label::Bool return if labelrotation isa Automatic if horizontal (:center, flipped ? :bottom : :top) @@ -367,12 +367,12 @@ function LineAxis(parent::Scene, attrs::Attributes) end::NTuple{2, Symbol} end - labelrot = Observable(0f0; ignore_equal_values=true) + labelrot = Observable(0.0f0; ignore_equal_values = true) map!(labelrot, labelrotation, horizontal, flip_vertical_label) do labelrotation, - horizontal::Bool, flip_vertical_label::Bool + horizontal::Bool, flip_vertical_label::Bool return if labelrotation isa Automatic if horizontal - 0f0 + 0.0f0 else (flip_vertical_label ? -0.5f0 : 0.5f0) * π end @@ -392,38 +392,38 @@ function LineAxis(parent::Scene, attrs::Attributes) # in order to prevent plot and axis overlap onany(labelrotation, flipped, horizontal) do labelrotation, flipped, horizontal xs::Float32, ys::Float32 = if labelrotation isa Automatic - 0f0, 0f0 + 0.0f0, 0.0f0 else wx, wy = widths(boundingbox(labeltext)) sign::Int = flipped ? 1 : -1 if horizontal - 0f0, Float32(sign * 0.5f0 * wy) + 0.0f0, Float32(sign * 0.5f0 * wy) else - Float32(sign * 0.5f0 * wx), 0f0 + Float32(sign * 0.5f0 * wx), 0.0f0 end end - translate!(labeltext, xs, ys, 0f0) + translate!(labeltext, xs, ys, 0.0f0) end decorations[:labeltext] = labeltext - tickvalues = Observable(Float32[]; ignore_equal_values=true) + tickvalues = Observable(Float32[]; ignore_equal_values = true) - tickvalues_labels_unfiltered = Observable{Tuple{Vector{Float32},Vector{AbstractString}}}() + tickvalues_labels_unfiltered = Observable{Tuple{Vector{Float32}, Vector{AbstractString}}}() map!(tickvalues_labels_unfiltered, pos_extents_horizontal, limits, ticks, tickformat, attrs.scale) do (position, extents, horizontal), - limits, ticks, tickformat, scale + limits, ticks, tickformat, scale get_ticks(ticks, scale, tickformat, limits...) end - tickpositions = Observable(Point2f[]; ignore_equal_values=true) - tickstrings = Observable(AbstractString[]; ignore_equal_values=true) + tickpositions = Observable(Point2f[]; ignore_equal_values = true) + tickstrings = Observable(AbstractString[]; ignore_equal_values = true) onany(update_tickpos_string, Observable((tickstrings, tickpositions, tickvalues, pos_extents_horizontal, limits)), tickvalues_labels_unfiltered, reversed, attrs.scale) - minortickvalues = Observable(Float32[]; ignore_equal_values=true) - minortickpositions = Observable(Point2f[]; ignore_equal_values=true) + minortickvalues = Observable(Float32[]; ignore_equal_values = true) + minortickpositions = Observable(Point2f[]; ignore_equal_values = true) onany(tickvalues, minorticks) do tickvalues, minorticks minortickvalues[] = get_minor_tickvalues(minorticks, attrs.scale[], tickvalues, limits[]...) @@ -455,7 +455,7 @@ function LineAxis(parent::Scene, attrs::Attributes) translate!(decorations[:axisline], 0, 0, 20) - protrusion = Observable(0f0; ignore_equal_values=true) + protrusion = Observable(0.0f0; ignore_equal_values = true) map!(calculate_protrusion, protrusion, # we pass these as observables, to not trigger on them @@ -508,11 +508,11 @@ function tight_ticklabel_spacing!(la::LineAxis) tls = la.elements[:ticklabels] maxwidth = if horizontal - # height - tls.visible[] ? height(Rect2f(boundingbox(tls))) : 0f0 - else - # width - tls.visible[] ? width(Rect2f(boundingbox(tls))) : 0f0 + # height + tls.visible[] ? height(Rect2f(boundingbox(tls))) : 0.0f0 + else + # width + tls.visible[] ? width(Rect2f(boundingbox(tls))) : 0.0f0 end la.attributes.ticklabelspace = maxwidth return Float64(maxwidth) @@ -521,7 +521,7 @@ end iswhitespace(str) = match(r"^\s*$", str) !== nothing -function Base.delete!(la::LineAxis) +Base.delete!(la::LineAxis) = for (_, d) in la.elements if d isa AbstractPlot delete!(d.parent, d) @@ -529,7 +529,6 @@ function Base.delete!(la::LineAxis) delete!(d) end end -end """ get_ticks(ticks, scale, formatter, vmin, vmax) @@ -580,10 +579,8 @@ _logbase(::typeof(log2)) = "2" _logbase(::typeof(log)) = "e" -function get_ticks(::Automatic, scale::Union{typeof(log10), typeof(log2), typeof(log)}, - any_formatter, vmin, vmax) - get_ticks(LogTicks(WilkinsonTicks(5, k_min = 3)), scale, any_formatter, vmin, vmax) -end +get_ticks(::Automatic, scale::Union{typeof(log10), typeof(log2), typeof(log)}, + any_formatter, vmin, vmax) = get_ticks(LogTicks(WilkinsonTicks(5, k_min = 3)), scale, any_formatter, vmin, vmax) # log ticks just use the normal pipeline but with log'd limits, then transform the labels function get_ticks(l::LogTicks, scale::Union{typeof(log10), typeof(log2), typeof(log)}, ::Automatic, vmin, vmax) @@ -597,7 +594,7 @@ function get_ticks(l::LogTicks, scale::Union{typeof(log10), typeof(log2), typeof xs -> Showoff.showoff(xs, :plain), ticks_scaled ) - labels = rich.(_logbase(scale), superscript.(labels_scaled, offset = Vec2f(0.1f0, 0f0))) + labels = rich.(_logbase(scale), superscript.(labels_scaled, offset = Vec2f(0.1f0, 0.0f0))) (ticks, labels) end @@ -696,21 +693,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) @@ -734,21 +731,21 @@ function get_minor_tickvalues(i::IntervalsBetween, scale::Union{typeof(log), typ prevtick = invscale(scale(tickvalues[1]) - firstinterval_scaled) stepsize = (tickvalues[1] - prevtick) / n v = tickvalues[1] - stepsize - prepend!(vals, v:-stepsize:vmin) + prepend!(vals, v:(-stepsize):vmin) end - for (lo, hi) in zip(@view(tickvalues[1:end-1]), @view(tickvalues[2:end])) + for (lo, hi) in zip(@view(tickvalues[1:(end - 1)]), @view(tickvalues[2:end])) interval = hi - lo stepsize = interval / n v = lo - for i in 1:n-1 + for i in 1:(n - 1) v += stepsize push!(vals, v) end end if i.mirror - lastinterval_scaled = scale(tickvalues[end]) - scale(tickvalues[end-1]) + lastinterval_scaled = scale(tickvalues[end]) - scale(tickvalues[end - 1]) nexttick = invscale(scale(tickvalues[end]) + lastinterval_scaled) stepsize = (nexttick - tickvalues[end]) / n v = tickvalues[end] + stepsize @@ -758,6 +755,4 @@ function get_minor_tickvalues(i::IntervalsBetween, scale::Union{typeof(log), typ vals end -function get_minor_tickvalues(v::AbstractVector{<:Real}, _, _, _, _) - Float32.(v) -end +get_minor_tickvalues(v::AbstractVector{<:Real}, _, _, _, _) = Float32.(v) diff --git a/src/makielayout/mousestatemachine.jl b/src/makielayout/mousestatemachine.jl index 40653697f4a..99b3762a90e 100644 --- a/src/makielayout/mousestatemachine.jl +++ b/src/makielayout/mousestatemachine.jl @@ -1,32 +1,32 @@ module MouseEventTypes - @enum MouseEventType begin - out - enter - over - leftdown - rightdown - middledown - leftup - rightup - middleup - leftdragstart - rightdragstart - middledragstart - leftdrag - rightdrag - middledrag - leftdragstop - rightdragstop - middledragstop - leftclick - rightclick - middleclick - leftdoubleclick - rightdoubleclick - middledoubleclick - downoutside - end - export MouseEventType +@enum MouseEventType begin + out + enter + over + leftdown + rightdown + middledown + leftup + rightup + middleup + leftdragstart + rightdragstart + middledragstart + leftdrag + rightdrag + middledrag + leftdragstop + rightdragstop + middledragstop + leftclick + rightclick + middleclick + leftdoubleclick + rightdoubleclick + middledoubleclick + downoutside +end +export MouseEventType end using .MouseEventTypes @@ -80,14 +80,13 @@ for eventtype in instances(MouseEventType) Executes the function f whenever the `MouseEventHandle`'s observable is set to a MouseEvent with `event.type === $($eventtype)`. """ - function $onfunctionname(f, mev::MouseEventHandle; priority = 0) + $onfunctionname(f, mev::MouseEventHandle; priority = 0) = on(mev.obs, priority = priority) do event if event.type === $eventtype return f(event) end return Consume(false) end - end export $onfunctionname end end @@ -116,7 +115,7 @@ function addmouseevents!(scene, elements...; priority = 1) is_mouse_over_relevant_area() = isempty(elements) ? Makie.is_mouseinside(scene) : mouseover(scene, elements...) _addmouseevents!(scene, is_mouse_over_relevant_area, priority) end -function addmouseevents!(scene, bbox::Observables.AbstractObservable{<: Rect2}; priority = 1) +function addmouseevents!(scene, bbox::Observables.AbstractObservable{<:Rect2}; priority = 1) is_mouse_over_relevant_area() = Makie.mouseposition_px(scene) in bbox[] _addmouseevents!(scene, is_mouse_over_relevant_area, priority) end @@ -143,7 +142,7 @@ function _addmouseevents!(scene, is_mouse_over_relevant_area, priority) last_click_was_double = Ref(false) # react to mouse position changes - mousepos_observerfunc = on(events(scene).mouseposition, priority=priority) do mp + mousepos_observerfunc = on(events(scene).mouseposition, priority = priority) do mp consumed = false t = time() data = mouseposition(scene) @@ -229,7 +228,7 @@ function _addmouseevents!(scene, is_mouse_over_relevant_area, priority) # react to mouse button changes - mousedrag_observerfunc = on(events(scene).mousebutton, priority=priority) do event + mousedrag_observerfunc = on(events(scene).mousebutton, priority = priority) do event consumed = false t = time() data = prev_data[] @@ -318,7 +317,7 @@ function _addmouseevents!(scene, is_mouse_over_relevant_area, priority) # guard against mouse coming in from outside, then mouse upping if mouse_downed_inside[] if dt_last_click < dblclick_max_interval && !last_click_was_double[] && - mouse_downed_button[] == b_last_click[] + mouse_downed_button[] == b_last_click[] event = @match mouse_downed_button[] begin Mouse.left => MouseEventTypes.leftdoubleclick diff --git a/src/makielayout/roundedrect.jl b/src/makielayout/roundedrect.jl index f8109fe645a..26eb53c49f0 100644 --- a/src/makielayout/roundedrect.jl +++ b/src/makielayout/roundedrect.jl @@ -17,7 +17,7 @@ function plot!(roundrect::RoundedRect) widthattr = roundrect.width roundedrectpoints = lift(rect, cornerradius, cornersegments) do rect, - cr, csegs + cr, csegs cr = min(width(rect) / 2, height(rect) / 2, cr) @@ -27,10 +27,10 @@ function plot!(roundrect::RoundedRect) icbl = bottomleft(rect) .+ Point2(cr, cr) icbr = bottomright(rect) .+ Point2(-cr, cr) - cstr = anglepoint.(Ref(ictr), LinRange(0, pi/2, csegs), cr) - cstl = anglepoint.(Ref(ictl), LinRange(pi/2, pi, csegs), cr) - csbl = anglepoint.(Ref(icbl), LinRange(pi, 3pi/2, csegs), cr) - csbr = anglepoint.(Ref(icbr), LinRange(3pi/2, 2pi, csegs), cr) + cstr = anglepoint.(Ref(ictr), LinRange(0, pi / 2, csegs), cr) + cstl = anglepoint.(Ref(ictl), LinRange(pi / 2, pi, csegs), cr) + csbl = anglepoint.(Ref(icbl), LinRange(pi, 3pi / 2, csegs), cr) + csbr = anglepoint.(Ref(icbr), LinRange(3pi / 2, 2pi, csegs), cr) return [cstr; cstl; csbl; csbr] end diff --git a/src/makielayout/ticklocators/linear.jl b/src/makielayout/ticklocators/linear.jl index 75e6d02c133..5d5d290bd98 100644 --- a/src/makielayout/ticklocators/linear.jl +++ b/src/makielayout/ticklocators/linear.jl @@ -1,23 +1,23 @@ -function scale_range(vmin, vmax, n=1, threshold=100) +function scale_range(vmin, vmax, n = 1, threshold = 100) dv = abs(vmax - vmin) # > 0 as nonsingular is called before. meanv = (vmax + vmin) / 2 offset = if abs(meanv) / dv < threshold 0.0 else - copysign(10 ^ (log10(abs(meanv)) ÷ 1), meanv) + copysign(10^(log10(abs(meanv)) ÷ 1), meanv) end - scale = 10 ^ (log10(dv / n) ÷ 1) + scale = 10^(log10(dv / n) ÷ 1) scale, offset end function _staircase(steps) n = length(steps) result = Vector{Float64}(undef, 2n) - for i in 1:(n-1) + for i in 1:(n - 1) @inbounds result[i] = 0.1 * steps[i] end for i in 1:n - @inbounds result[i+(n-1)] = steps[i] + @inbounds result[i + (n - 1)] = steps[i] end result[end] = 10 * steps[2] return result @@ -40,7 +40,7 @@ end function closeto(e::EdgeInteger, ms, edge) tol = if e.offset > 0 digits = log10(e.offset / e.step) - tol = max(1e-10, 10 ^ (digits - 12)) + tol = max(1e-10, 10^(digits - 12)) min(0.4999, tol) else 1e-10 @@ -142,7 +142,7 @@ function locateticks(vmin, vmax, n_ideal::Int, _integer::Bool = false, _min_n_ti # 0.08000000001 instead of 0.08 # so here we round off the numbers to the required number of digits after the decimal point exponent = floor(Int, minimum(log10.(abs.(diff(vals))))) - round.(vals, digits = max(0, -exponent+1)) + round.(vals, digits = max(0, -exponent + 1)) end diff --git a/src/makielayout/ticklocators/wilkinson.jl b/src/makielayout/ticklocators/wilkinson.jl index 2e5922db448..6b44fb5b585 100644 --- a/src/makielayout/ticklocators/wilkinson.jl +++ b/src/makielayout/ticklocators/wilkinson.jl @@ -1,10 +1,10 @@ function WilkinsonTicks(k_ideal::Int; k_min = 2, k_max = 10, - Q = [(1.0,1.0), (5.0, 0.9), (2.0, 0.7), (2.5, 0.5), (3.0, 0.2)], - granularity_weight = 1/4, - simplicity_weight = 1/6, - coverage_weight = 1/3, - niceness_weight = 1/4, - min_px_dist = 50.0) + Q = [(1.0, 1.0), (5.0, 0.9), (2.0, 0.7), (2.5, 0.5), (3.0, 0.2)], + granularity_weight = 1 / 4, + simplicity_weight = 1 / 6, + coverage_weight = 1 / 3, + niceness_weight = 1 / 4, + min_px_dist = 50.0) if !(0 < k_min <= k_ideal <= k_max) error("Invalid tick number specifications k_ideal $k_ideal, k_min $k_min, k_max $k_max") @@ -19,7 +19,7 @@ get_tickvalues(ticks::WilkinsonTicks, vmin, vmax) = get_tickvalues(ticks, Float6 function get_tickvalues(ticks::WilkinsonTicks, vmin::Float64, vmax::Float64) tickvalues, _ = PlotUtils.optimize_ticks(Float64(vmin), Float64(vmax); - extend_ticks = false, strict_span=true, span_buffer = nothing, + extend_ticks = false, strict_span = true, span_buffer = nothing, k_min = ticks.k_min, k_max = ticks.k_max, k_ideal = ticks.k_ideal, diff --git a/src/makielayout/types.jl b/src/makielayout/types.jl index bf52b111bb7..bd16262f0bb 100644 --- a/src/makielayout/types.jl +++ b/src/makielayout/types.jl @@ -143,10 +143,8 @@ mutable struct RectangleZoom rectnode::Observable{Rect2f} end -function RectangleZoom(callback::Function; restrict_x=false, restrict_y=false) - return RectangleZoom(callback, Observable(false), restrict_x, restrict_y, - nothing, nothing, Observable(Rect2f(0, 0, 1, 1))) -end +RectangleZoom(callback::Function; restrict_x = false, restrict_y = false) = RectangleZoom(callback, Observable(false), restrict_x, restrict_y, + nothing, nothing, Observable(Rect2f(0, 0, 1, 1))) struct ScrollZoom speed::Float32 @@ -156,9 +154,7 @@ struct ScrollZoom 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) -end +ScrollZoom(speed, reset_delay) = ScrollZoom(speed, RefValue{Union{Nothing, Timer}}(nothing), RefValue{Union{Automatic, Float64}}(0.0), RefValue{Union{Automatic, Float64}}(0.0), reset_delay) struct DragPan reset_timer::RefValue{Union{Nothing, Timer}} @@ -167,9 +163,7 @@ struct DragPan 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) -end +DragPan(reset_delay) = DragPan(RefValue{Union{Nothing, Timer}}(nothing), RefValue{Union{Automatic, Float64}}(0.0), RefValue{Union{Automatic, Float64}}(0.0), reset_delay) struct DragRotate @@ -209,9 +203,9 @@ end "The font family of the title." titlefont = :bold "The title's font size." - titlesize::Float64 = @inherit(:fontsize, 16f0) + titlesize::Float64 = @inherit(:fontsize, 16.0f0) "The gap between axis and title." - titlegap::Float64 = 4f0 + titlegap::Float64 = 4.0f0 "Controls if the title is visible." titlevisible::Bool = true "The horizontal alignment of the title." @@ -225,7 +219,7 @@ end "The font family of the subtitle." subtitlefont = :regular "The subtitle's font size." - subtitlesize::Float64 = @inherit(:fontsize, 16f0) + subtitlesize::Float64 = @inherit(:fontsize, 16.0f0) "The gap between subtitle and title." subtitlegap::Float64 = 0 "Controls if the subtitle is visible." @@ -243,17 +237,17 @@ end "The color of the ylabel." ylabelcolor::RGBAf = @inherit(:textcolor, :black) "The font size of the xlabel." - xlabelsize::Float64 = @inherit(:fontsize, 16f0) + xlabelsize::Float64 = @inherit(:fontsize, 16.0f0) "The font size of the ylabel." - ylabelsize::Float64 = @inherit(:fontsize, 16f0) + ylabelsize::Float64 = @inherit(:fontsize, 16.0f0) "Controls if the xlabel is visible." xlabelvisible::Bool = true "Controls if the ylabel is visible." ylabelvisible::Bool = true "The padding between the xlabel and the ticks or axis." - xlabelpadding::Float64 = 3f0 + xlabelpadding::Float64 = 3.0f0 "The padding between the ylabel and the ticks or axis." - ylabelpadding::Float64 = 5f0 # xlabels usually have some more visual padding because of ascenders, which are larger than the hadvance gaps of ylabels + ylabelpadding::Float64 = 5.0f0 # xlabels usually have some more visual padding because of ascenders, which are larger than the hadvance gaps of ylabels "The xlabel rotation in radians." xlabelrotation = Makie.automatic "The ylabel rotation in radians." @@ -267,9 +261,9 @@ end "The color of yticklabels." yticklabelcolor::RGBAf = @inherit(:textcolor, :black) "The font size of the xticklabels." - xticklabelsize::Float64 = @inherit(:fontsize, 16f0) + xticklabelsize::Float64 = @inherit(:fontsize, 16.0f0) "The font size of the yticklabels." - yticklabelsize::Float64 = @inherit(:fontsize, 16f0) + yticklabelsize::Float64 = @inherit(:fontsize, 16.0f0) "Controls if the xticklabels are visible." xticklabelsvisible::Bool = true "Controls if the yticklabels are visible." @@ -279,33 +273,33 @@ end "The space reserved for the yticklabels." yticklabelspace::Union{Makie.Automatic, Float64} = Makie.automatic "The space between xticks and xticklabels." - xticklabelpad::Float64 = 2f0 + xticklabelpad::Float64 = 2.0f0 "The space between yticks and yticklabels." - yticklabelpad::Float64 = 4f0 + yticklabelpad::Float64 = 4.0f0 "The counterclockwise rotation of the xticklabels in radians." - xticklabelrotation::Float64 = 0f0 + xticklabelrotation::Float64 = 0.0f0 "The counterclockwise rotation of the yticklabels in radians." - yticklabelrotation::Float64 = 0f0 + yticklabelrotation::Float64 = 0.0f0 "The horizontal and vertical alignment of the xticklabels." 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 "The size of the xtick marks." - xticksize::Float64 = 6f0 + xticksize::Float64 = 6.0f0 "The size of the ytick marks." - yticksize::Float64 = 6f0 + yticksize::Float64 = 6.0f0 "Controls if the xtick marks are visible." xticksvisible::Bool = true "Controls if the ytick marks are visible." yticksvisible::Bool = true "The alignment of the xtick marks relative to the axis spine (0 = out, 1 = in)." - xtickalign::Float64 = 0f0 + xtickalign::Float64 = 0.0f0 "The alignment of the ytick marks relative to the axis spine (0 = out, 1 = in)." - ytickalign::Float64 = 0f0 + ytickalign::Float64 = 0.0f0 "The width of the xtick marks." - xtickwidth::Float64 = 1f0 + xtickwidth::Float64 = 1.0f0 "The width of the ytick marks." - ytickwidth::Float64 = 1f0 + ytickwidth::Float64 = 1.0f0 "The color of the xtick marks." xtickcolor::RGBAf = RGBf(0, 0, 0) "The color of the ytick marks." @@ -327,15 +321,15 @@ end "Controls if rectangle zooming affects the y dimension." yrectzoom::Bool = true "The width of the axis spines." - spinewidth::Float64 = 1f0 + spinewidth::Float64 = 1.0f0 "Controls if the x grid lines are visible." xgridvisible::Bool = true "Controls if the y grid lines are visible." ygridvisible::Bool = true "The width of the x grid lines." - xgridwidth::Float64 = 1f0 + xgridwidth::Float64 = 1.0f0 "The width of the y grid lines." - ygridwidth::Float64 = 1f0 + ygridwidth::Float64 = 1.0f0 "The color of the x grid lines." xgridcolor::RGBAf = RGBAf(0, 0, 0, 0.12) "The color of the y grid lines." @@ -349,9 +343,9 @@ end "Controls if the y minor grid lines are visible." yminorgridvisible::Bool = false "The width of the x minor grid lines." - xminorgridwidth::Float64 = 1f0 + xminorgridwidth::Float64 = 1.0f0 "The width of the y minor grid lines." - yminorgridwidth::Float64 = 1f0 + yminorgridwidth::Float64 = 1.0f0 "The color of the x minor grid lines." xminorgridcolor::RGBAf = RGBAf(0, 0, 0, 0.05) "The color of the y minor grid lines." @@ -417,9 +411,9 @@ end "The position of the y axis (`:left` or `:right`)." yaxisposition::Symbol = :left "Controls if the x spine is limited to the furthest tick marks or not." - xtrimspine::Union{Bool, Tuple{Bool,Bool}} = false + xtrimspine::Union{Bool, Tuple{Bool, Bool}} = false "Controls if the y spine is limited to the furthest tick marks or not." - ytrimspine::Union{Bool, Tuple{Bool,Bool}} = false + ytrimspine::Union{Bool, Tuple{Bool, Bool}} = false "The background color of the axis." backgroundcolor::RGBAf = :white "Controls if the ylabel's rotation is flipped." @@ -437,11 +431,11 @@ end "Controls if minor ticks on the x axis are visible" xminorticksvisible::Bool = false "The alignment of x minor ticks on the axis spine" - xminortickalign::Float64 = 0f0 + xminortickalign::Float64 = 0.0f0 "The tick size of x minor ticks" - xminorticksize::Float64 = 4f0 + xminorticksize::Float64 = 4.0f0 "The tick width of x minor ticks" - xminortickwidth::Float64 = 1f0 + xminortickwidth::Float64 = 1.0f0 "The tick color of x minor ticks" xminortickcolor::RGBAf = :black "The tick locator for the x minor ticks" @@ -449,11 +443,11 @@ end "Controls if minor ticks on the y axis are visible" yminorticksvisible::Bool = false "The alignment of y minor ticks on the axis spine" - yminortickalign::Float64 = 0f0 + yminortickalign::Float64 = 0.0f0 "The tick size of y minor ticks" - yminorticksize::Float64 = 4f0 + yminorticksize::Float64 = 4.0f0 "The tick width of y minor ticks" - yminortickwidth::Float64 = 1f0 + yminortickwidth::Float64 = 1.0f0 "The tick color of y minor ticks" yminortickcolor::RGBAf = :black "The tick locator for the y minor ticks" @@ -473,20 +467,19 @@ function RectangleZoom(f::Function, ax::Axis; kw...) # plot to blockscene, so ax.scene stays exclusive for user plots # That's also why we need to pass `ax.scene` to _selection_vertices, so it can project to that space mesh = mesh!(ax.blockscene, selection_vertices, faces, color = (:black, 0.2), shading = false, - inspectable = false, visible=r.active, transparency=true) + inspectable = false, visible = r.active, transparency = true) # translate forward so selection mesh and frame are never behind data translate!(mesh, 0, 0, 100) return r end -function RectangleZoom(ax::Axis; kw...) - return RectangleZoom(ax; kw...) do newlims +RectangleZoom(ax::Axis; kw...) = + RectangleZoom(ax; kw...) do newlims if !(0 in widths(newlims)) ax.targetlimits[] = newlims end return end -end @Block Colorbar begin axis::LineAxis @@ -498,23 +491,23 @@ end "The label font family." labelfont = :regular "The label font size." - labelsize = @inherit(:fontsize, 16f0) + labelsize = @inherit(:fontsize, 16.0f0) "Controls if the label is visible." labelvisible = true "The gap between the label and the ticks." - labelpadding = 5f0 + labelpadding = 5.0f0 "The label rotation in radians." labelrotation = Makie.automatic "The font family of the tick labels." ticklabelfont = :regular "The font size of the tick labels." - ticklabelsize = @inherit(:fontsize, 16f0) + ticklabelsize = @inherit(:fontsize, 16.0f0) "Controls if the tick labels are visible." ticklabelsvisible = true "The color of the tick labels." ticklabelcolor = @inherit(:textcolor, :black) "The size of the tick marks." - ticksize = 6f0 + ticksize = 6.0f0 "Controls if the tick marks are visible." ticksvisible = true "The ticks." @@ -524,19 +517,19 @@ end "The space reserved for the tick labels." ticklabelspace = Makie.automatic "The gap between tick labels and tick marks." - ticklabelpad = 3f0 + ticklabelpad = 3.0f0 "The alignment of the tick marks relative to the axis spine (0 = out, 1 = in)." - tickalign = 0f0 + tickalign = 0.0f0 "The line width of the tick marks." - tickwidth = 1f0 + tickwidth = 1.0f0 "The color of the tick marks." tickcolor = RGBf(0, 0, 0) "The horizontal and vertical alignment of the tick labels." ticklabelalign = Makie.automatic "The rotation of the ticklabels." - ticklabelrotation = 0f0 + ticklabelrotation = 0.0f0 "The line width of the spines." - spinewidth = 1f0 + spinewidth = 1.0f0 "Controls if the top spine is visible." topspinevisible = true "Controls if the right spine is visible." @@ -588,11 +581,11 @@ end "Controls if minor ticks are visible" minorticksvisible = false "The alignment of minor ticks on the axis spine" - minortickalign = 0f0 + minortickalign = 0.0f0 "The tick size of minor ticks" - minorticksize = 4f0 + minorticksize = 4.0f0 "The tick width of minor ticks" - minortickwidth = 1f0 + minortickwidth = 1.0f0 "The tick color of minor ticks" minortickcolor = :black "The tick locator for the minor ticks" @@ -613,7 +606,7 @@ end "The color of the text." color::RGBAf = @inherit(:textcolor, :black) "The font size of the text." - fontsize::Float32 = @inherit(:fontsize, 16f0) + fontsize::Float32 = @inherit(:fontsize, 16.0f0) "The font family of the text." font = :regular "The justification of the text (:left, :right, :center)." @@ -625,9 +618,9 @@ end "The horizontal alignment of the text in its suggested boundingbox" halign = :center "The counterclockwise rotation of the text in radians." - rotation::Float32 = 0f0 + rotation::Float32 = 0.0f0 "The extra space added to the sides of the text boundingbox." - padding = (0f0, 0f0, 0f0, 0f0) + padding = (0.0f0, 0.0f0, 0.0f0, 0.0f0) "The height setting of the text." height = Auto() "The width setting of the text." @@ -654,9 +647,9 @@ end "The horizontal alignment of the rectangle in its suggested boundingbox" halign = :center "The extra space added to the sides of the rectangle boundingbox." - padding = (0f0, 0f0, 0f0, 0f0) + padding = (0.0f0, 0.0f0, 0.0f0, 0.0f0) "The line width of the rectangle's border." - strokewidth = 1f0 + strokewidth = 1.0f0 "Controls if the border of the rectangle is visible." strokevisible = true "The color of the border." @@ -783,9 +776,9 @@ end "The vertical alignment of the button in its suggested boundingbox" valign = :center "The extra space added to the sides of the button label's boundingbox." - padding = (10f0, 10f0, 10f0, 10f0) + padding = (10.0f0, 10.0f0, 10.0f0, 10.0f0) "The font size of the button label." - fontsize = @inherit(:fontsize, 16f0) + fontsize = @inherit(:fontsize, 16.0f0) "The text of the button label." label = "Button" "The font family of the button label." @@ -803,7 +796,7 @@ end "The number of poly segments used for each rounded corner." cornersegments = 10 "The line width of the button border." - strokewidth = 2f0 + strokewidth = 2.0f0 "The color of the button border." strokecolor = :transparent "The color of the button." @@ -900,7 +893,7 @@ end "The list of options selectable in the menu. This can be any iterable of a mixture of strings and containers with one string and one other value. If an entry is just a string, that string is both label and selection. If an entry is a container with one string and one other value, the string is the label and the other value is the selection." options = ["no options"] "Font size of the cell texts" - fontsize = @inherit(:fontsize, 16f0) + fontsize = @inherit(:fontsize, 16.0f0) "Padding of entry texts" textpadding = (10, 10, 10, 10) "Color of entry texts" @@ -955,7 +948,7 @@ const EntryGroup = Tuple{Optional{<:AbstractString}, Vector{LegendEntry}} "The font family of the legend group titles." titlefont = :bold "The font size of the legend group titles." - titlesize = @inherit(:fontsize, 16f0) + titlesize = @inherit(:fontsize, 16.0f0) "The horizontal alignment of the legend group titles." titlehalign = :center "The vertical alignment of the legend group titles." @@ -967,7 +960,7 @@ const EntryGroup = Tuple{Optional{<:AbstractString}, Vector{LegendEntry}} "The group title positions relative to their groups. Can be `:top` or `:left`." titleposition = :top "The font size of the entry labels." - labelsize = @inherit(:fontsize, 16f0) + labelsize = @inherit(:fontsize, 16.0f0) "The font family of the entry labels." labelfont = :regular "The color of the entry labels." @@ -979,23 +972,23 @@ const EntryGroup = Tuple{Optional{<:AbstractString}, Vector{LegendEntry}} "The vertical alignment of the entry labels." labelvalign = :center "The additional space between the legend content and the border." - padding = (10f0, 10f0, 8f0, 8f0) + padding = (10.0f0, 10.0f0, 8.0f0, 8.0f0) "The additional space between the legend and its suggested boundingbox." - margin = (0f0, 0f0, 0f0, 0f0) + margin = (0.0f0, 0.0f0, 0.0f0, 0.0f0) "The background color of the legend." bgcolor = :white "The color of the legend border." framecolor = :black "The line width of the legend border." - framewidth = 1f0 + framewidth = 1.0f0 "Controls if the legend border is visible." framevisible = true "The size of the rectangles containing the legend markers." - patchsize = (20f0, 20f0) + patchsize = (20.0f0, 20.0f0) "The color of the border of the patches containing the legend markers." patchstrokecolor = :transparent "The line width of the border of the patches containing the legend markers." - patchstrokewidth = 1f0 + patchstrokewidth = 1.0f0 "The color of the patches containing the legend markers." patchcolor = :transparent "The default entry label." @@ -1102,7 +1095,7 @@ end "Controls if the textbox is defocused when a string is submitted." defocus_on_submit = true "Text size." - fontsize = @inherit(:fontsize, 16f0) + fontsize = @inherit(:fontsize, 16.0f0) "Text color." textcolor = @inherit(:textcolor, :black) "Text color for the placeholder." @@ -1126,7 +1119,7 @@ end "Color of the box border when focused and invalid." bordercolor_focused_invalid = RGBf(1, 0, 0) "Width of the box border." - borderwidth = 2f0 + borderwidth = 2.0f0 "Padding of the text against the box." textpadding = (10, 10, 10, 10) "If the textbox is focused and receives text input." @@ -1169,13 +1162,13 @@ end "The alignment of the scene in its suggested bounding box." alignmode = Inside() "The elevation angle of the camera" - elevation = pi/8 + elevation = pi / 8 "The azimuth angle of the camera" azimuth = 1.275 * pi "A number between 0 and 1, where 0 is orthographic, and 1 full perspective" - perspectiveness = 0f0 + perspectiveness = 0.0f0 "Aspects of the 3 axes with each other" - aspect = (1.0, 1.0, 2/3) # :data :equal + aspect = (1.0, 1.0, 2 / 3) # :data :equal "The view mode which affects the final projection. `:fit` results in the projection that always fits the limits into the viewport, invariant to rotation. `:fitzoom` keeps the x/y ratio intact but stretches the view so the corners touch the scene viewport. `:stretch` scales separately in both x and y direction to fill the viewport, which can distort the `aspect` that is set." viewmode = :fitzoom # :fit :fitzoom :stretch "The background color" @@ -1211,11 +1204,11 @@ end "Controls if the z ticks are visible" zticksvisible = true "The x label size" - xlabelsize = @inherit(:fontsize, 16f0) + xlabelsize = @inherit(:fontsize, 16.0f0) "The y label size" - ylabelsize = @inherit(:fontsize, 16f0) + ylabelsize = @inherit(:fontsize, 16.0f0) "The z label size" - zlabelsize = @inherit(:fontsize, 16f0) + zlabelsize = @inherit(:fontsize, 16.0f0) "The x label font" xlabelfont = :regular "The y label font" @@ -1247,11 +1240,11 @@ end "The z ticklabel color" zticklabelcolor = @inherit(:textcolor, :black) "The x ticklabel size" - xticklabelsize = @inherit(:fontsize, 16f0) + xticklabelsize = @inherit(:fontsize, 16.0f0) "The y ticklabel size" - yticklabelsize = @inherit(:fontsize, 16f0) + yticklabelsize = @inherit(:fontsize, 16.0f0) "The z ticklabel size" - zticklabelsize = @inherit(:fontsize, 16f0) + zticklabelsize = @inherit(:fontsize, 16.0f0) "The x ticklabel pad" xticklabelpad = 5 "The y ticklabel pad" @@ -1343,9 +1336,9 @@ end "The font family of the title." titlefont = :bold "The title's font size." - titlesize = @inherit(:fontsize, 16f0) + titlesize = @inherit(:fontsize, 16.0f0) "The gap between axis and title." - titlegap = 4f0 + titlegap = 4.0f0 "Controls if the title is visible." titlevisible = true "The horizontal alignment of the title." diff --git a/src/patterns.jl b/src/patterns.jl index 88f834a01d7..6838db6ce50 100644 --- a/src/patterns.jl +++ b/src/patterns.jl @@ -9,13 +9,9 @@ function, which must return a `Matrix{<: AbstractRGB}`. 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) - print(io, typeof(p)) -end +Base.show(io::IO, p::AbstractPattern) = print(io, typeof(p)) -function Base.show(io::IO, ::MIME"text/plain", p::AbstractPattern) - print(io, typeof(p)) -end +Base.show(io::IO, ::MIME"text/plain", p::AbstractPattern) = print(io, typeof(p)) struct ImagePattern <: AbstractPattern{RGBAf} img::Matrix{RGBAf} @@ -32,10 +28,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 @@ -69,10 +65,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 = 2.0f0, 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)) @@ -95,23 +91,22 @@ Creates a line pattern based on the given argument. Available patterns are to the keyword arguments for [`LinePattern`](@ref). """ Pattern(style::String; kwargs...) = Pattern(style[1]; kwargs...) -function Pattern(style::Char = '/'; kwargs...) +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 -end function to_image(p::LinePattern) tilesize = p.tilesize @@ -123,31 +118,31 @@ function to_image(p::LinePattern) # m = dx / dy; x = m * (y-1) + 1 m = dir[1] / dir[2] for y in 1:tilesize[2] - cx = m * (y-shift[2]) + shift[1] - r = floor(Int64, cx-0.5width):ceil(Int64, cx+0.5width) - for x in r[2:end-1] + cx = m * (y - shift[2]) + shift[1] + r = floor(Int64, cx - 0.5width):ceil(Int64, cx + 0.5width) + for x in r[2:(end - 1)] mask[mod1(x, tilesize[1]), y] = 1.0 end - mask[mod1(r[1], tilesize[1]), y] = 1 - abs(cx-0.5width - r[1]) - mask[mod1(r[end], tilesize[1]), y] = 1 - abs(cx+0.5width - r[end]) + mask[mod1(r[1], tilesize[1]), y] = 1 - abs(cx - 0.5width - r[1]) + mask[mod1(r[end], tilesize[1]), y] = 1 - abs(cx + 0.5width - r[end]) end else # m = dy / dx; y = m * (x-1) + 1 m = dir[2] / dir[1] for x in 1:tilesize[1] - cy = m * (x-shift[1]) + shift[2] - r = floor(Int64, cy-0.5width):ceil(Int64, cy+0.5width) - for y in r[2:end-1] + cy = m * (x - shift[1]) + shift[2] + r = floor(Int64, cy - 0.5width):ceil(Int64, cy + 0.5width) + for y in r[2:(end - 1)] mask[x, mod1(y, tilesize[2])] = 1.0 end - mask[x, mod1(r[1], tilesize[2])] = 1 - abs(cy-0.5width - r[1]) - mask[x, mod1(r[end], tilesize[2])] = 1 - abs(cy+0.5width - r[end]) + mask[x, mod1(r[1], tilesize[2])] = 1 - abs(cy - 0.5width - r[1]) + mask[x, mod1(r[end], tilesize[2])] = 1 - abs(cy + 0.5width - r[end]) end end full_mask .+= mask end return map(full_mask) do x - return convert(RGBAf, p.colors[1] * clamp(x, 0, 1) + p.colors[2] * (1-clamp(x, 0, 1))) + return convert(RGBAf, p.colors[1] * clamp(x, 0, 1) + p.colors[2] * (1 - clamp(x, 0, 1))) end end diff --git a/src/recording.jl b/src/recording.jl index 449f04b9d98..f80e203b99a 100644 --- a/src/recording.jl +++ b/src/recording.jl @@ -26,15 +26,15 @@ mutable struct RamStepper format::Symbol end -function Stepper(figlike::FigureLike; backend=current_backend(), format=:png, visible=false, connect=false, srceen_kw...) - screen = getscreen(backend, get_scene(figlike), JuliaNative; visible=visible, start_renderloop=false, srceen_kw...) - display(screen, figlike; connect=connect) +function Stepper(figlike::FigureLike; backend = current_backend(), format = :png, visible = false, connect = false, srceen_kw...) + screen = getscreen(backend, get_scene(figlike), JuliaNative; visible = visible, start_renderloop = false, srceen_kw...) + display(screen, figlike; connect = connect) return RamStepper(figlike, screen, Matrix{RGBf}[], format) end -function Stepper(figlike::FigureLike, path::String, step::Int; format=:png, backend=current_backend(), visible=false, connect=false, screen_config...) - screen = getscreen(backend, get_scene(figlike), JuliaNative; visible=visible, start_renderloop=false, srceen_kw...) - display(screen, figlike; connect=connect) +function Stepper(figlike::FigureLike, path::String, step::Int; format = :png, backend = current_backend(), visible = false, connect = false, screen_config...) + screen = getscreen(backend, get_scene(figlike), JuliaNative; visible = visible, start_renderloop = false, srceen_kw...) + display(screen, figlike; connect = connect) return FolderStepper(figlike, screen, path, format, step) end @@ -139,13 +139,13 @@ end """ function record(func, figlike::FigureLike, path::AbstractString; kw_args...) format = lstrip(splitext(path)[2], '.') - io = Record(func, figlike; format=format, kw_args...) + io = Record(func, figlike; format = format, kw_args...) save(path, io) end function record(func, figlike::FigureLike, path::AbstractString, iter; kw_args...) format = lstrip(splitext(path)[2], '.') - io = Record(func, figlike, iter; format=format, kw_args...) + io = Record(func, figlike, iter; format = format, kw_args...) save(path, io) end @@ -166,13 +166,13 @@ 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 end -function Base.show(io::IO, ::MIME"text/html", vs::VideoStream) +Base.show(io::IO, ::MIME"text/html", vs::VideoStream) = mktempdir() do dir path = save(joinpath(dir, "video.mp4"), vs) print( @@ -182,4 +182,3 @@ function Base.show(io::IO, ::MIME"text/html", vs::VideoStream) """" type="video/mp4">""" ) end -end diff --git a/src/scenes.jl b/src/scenes.jl index 29633cf39d5..b9d19dc791e 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 @@ -138,29 +138,29 @@ function Base.show(io::IO, scene::Scene) print(io, ":") for (i, subscene) in enumerate(scene.children) print(io, "\n") - print(io," $(i == length(scene.children) ? '└' : '├') Scene ($(size(subscene, 1))px, $(size(subscene, 2))px)") + print(io, " $(i == length(scene.children) ? '└' : '├') Scene ($(size(subscene, 1))px, $(size(subscene, 2))px)") end end end function Scene(; - px_area::Union{Observable{Rect2i}, Nothing} = nothing, - events::Events = Events(), - clear::Bool = true, - transform_func=identity, - camera::Union{Function, Camera, Nothing} = nothing, - camera_controls::AbstractCamera = EmptyCamera(), - transformation::Transformation = Transformation(transform_func), - plots::Vector{AbstractPlot} = AbstractPlot[], - theme::Attributes = Attributes(), - children::Vector{Scene} = Scene[], - current_screens::Vector{MakieScreen} = MakieScreen[], - parent = nothing, - visible = Observable(true), - ssao = SSAO(), - lights = automatic, - theme_kw... - ) + px_area::Union{Observable{Rect2i}, Nothing} = nothing, + events::Events = Events(), + clear::Bool = true, + transform_func = identity, + camera::Union{Function, Camera, Nothing} = nothing, + camera_controls::AbstractCamera = EmptyCamera(), + transformation::Transformation = Transformation(transform_func), + plots::Vector{AbstractPlot} = AbstractPlot[], + theme::Attributes = Attributes(), + children::Vector{Scene} = Scene[], + current_screens::Vector{MakieScreen} = MakieScreen[], + parent = nothing, + visible = Observable(true), + ssao = SSAO(), + lights = automatic, + theme_kw... +) m_theme = current_default_theme(; theme..., theme_kw...) bg = map(to_color, m_theme.backgroundcolor) @@ -213,7 +213,7 @@ function Scene(; end function get_one_light(scene::Scene, Typ) - indices = findall(x-> x isa Typ, scene.lights) + indices = findall(x -> x isa Typ, scene.lights) isempty(indices) && return nothing if length(indices) > 1 @warn("Only one light supported by backend right now. Using only first light") @@ -226,21 +226,21 @@ get_ambient_light(scene::Scene) = get_one_light(scene, AmbientLight) function Scene( - parent::Scene; - events=parent.events, - px_area=nothing, - clear=false, - camera=nothing, - camera_controls=parent.camera_controls, - transformation=Transformation(parent), - theme=theme(parent), - current_screens=parent.current_screens, - kw... - ) + parent::Scene; + events = parent.events, + px_area = nothing, + clear = false, + camera = nothing, + camera_controls = parent.camera_controls, + transformation = Transformation(parent), + theme = theme(parent), + current_screens = parent.current_screens, + kw... +) if isnothing(px_area) - px_area = lift(zero_origin, parent.px_area; ignore_equal_values=true) + px_area = lift(zero_origin, parent.px_area; ignore_equal_values = true) else - px_area = lift(pixelarea(parent), convert(Observable, px_area); ignore_equal_values=true) do p, a + px_area = lift(pixelarea(parent), convert(Observable, px_area); ignore_equal_values = true) do p, a # make coordinates relative to parent rect = Rect2i(minimum(p) .+ minimum(a), widths(a)) return rect @@ -250,15 +250,15 @@ function Scene( camera_controls = EmptyCamera() end child = Scene(; - events=events, - px_area=px_area, - clear=clear, - camera=camera, - camera_controls=camera_controls, - parent=parent, - transformation=transformation, - theme=theme, - current_screens=current_screens, + events = events, + px_area = px_area, + clear = clear, + camera = camera, + camera_controls = camera_controls, + parent = parent, + transformation = transformation, + theme = theme, + current_screens = current_screens, kw... ) push!(parent.children, child) @@ -267,9 +267,7 @@ function Scene( end # legacy constructor -function Scene(parent::Scene, area; kw...) - return Scene(parent; px_area=area, kw...) -end +Scene(parent::Scene, area; kw...) = Scene(parent; px_area = area, kw...) # Base overloads for Scene Base.parent(scene::Scene) = scene.parent @@ -289,13 +287,9 @@ GeometryBasics.widths(scene::Scene) = widths(to_value(pixelarea(scene))) Base.size(scene::Scene) = Tuple(widths(scene)) Base.size(x::Scene, i) = size(x)[i] -function Base.resize!(scene::Scene, xy::Tuple{Number,Number}) - resize!(scene, Recti(0, 0, xy)) -end +Base.resize!(scene::Scene, xy::Tuple{Number, Number}) = resize!(scene, Recti(0, 0, xy)) Base.resize!(scene::Scene, x::Number, y::Number) = resize!(scene, (x, y)) -function Base.resize!(scene::Scene, rect::Rect2) - pixelarea(scene)[] = rect -end +Base.resize!(scene::Scene, rect::Rect2) = pixelarea(scene)[] = rect """ getscreen(scene::Scene) @@ -315,7 +309,7 @@ end getscreen(scene::SceneLike) = getscreen(rootparent(scene)) # Just indexing into a scene gets you plot 1, plot 2 etc -Base.iterate(scene::Scene, idx=1) = idx <= length(scene) ? (scene[idx], idx + 1) : nothing +Base.iterate(scene::Scene, idx = 1) = idx <= length(scene) ? (scene[idx], idx + 1) : nothing Base.length(scene::Scene) = length(scene.plots) Base.lastindex(scene::Scene) = length(scene.plots) getindex(scene::Scene, idx::Integer) = scene.plots[idx] @@ -323,24 +317,16 @@ struct OldAxis end zero_origin(area) = Recti(0, 0, widths(area)) -function child(scene::Scene; camera, attributes...) - return Scene(scene, lift(zero_origin, pixelarea(scene)); camera=camera, attributes...) -end +child(scene::Scene; camera, attributes...) = Scene(scene, lift(zero_origin, pixelarea(scene)); camera = camera, attributes...) """ Creates a subscene with a pixel camera """ -function cam2d(scene::Scene) - return child(scene, clear=false, camera=cam2d!) -end +cam2d(scene::Scene) = child(scene, clear = false, camera = cam2d!) -function campixel(scene::Scene) - return child(scene, clear=false, camera=campixel!) -end +campixel(scene::Scene) = child(scene, clear = false, camera = campixel!) -function camrelative(scene::Scene) - return child(scene, clear=false, camera=cam_relative!) -end +camrelative(scene::Scene) = child(scene, clear = false, camera = cam_relative!) function getindex(scene::Scene, ::Type{OldAxis}) for plot in scene @@ -410,9 +396,7 @@ function Base.push!(scene::Scene, plot::AbstractPlot) end end -function Base.delete!(screen::MakieScreen, ::Scene, ::AbstractPlot) - @warn "Deleting plots not implemented for backend: $(typeof(screen))" -end +Base.delete!(screen::MakieScreen, ::Scene, ::AbstractPlot) = @warn "Deleting plots not implemented for backend: $(typeof(screen))" function Base.delete!(screen::MakieScreen, ::Scene) # This may not be necessary for every backed @debug "Deleting scenes not implemented for backend: $(typeof(screen))" @@ -474,7 +458,7 @@ plots(scene::SceneLike) = scene.plots Fetches all plots sharing the same camera """ plots_from_camera(scene::Scene) = plots_from_camera(scene, scene.camera) -function plots_from_camera(scene::Scene, camera::Camera, list=AbstractPlot[]) +function plots_from_camera(scene::Scene, camera::Camera, list = AbstractPlot[]) append!(list, scene.plots) for child in scene.children child.camera == camera && plots_from_camera(child, camera, list) @@ -485,7 +469,7 @@ end """ Flattens all the combined plots and returns a Vector of Atomic plots """ -function flatten_combined(plots::Vector, flat=AbstractPlot[]) +function flatten_combined(plots::Vector, flat = AbstractPlot[]) for elem in plots if (elem isa Combined) flatten_combined(elem.plots, flat) @@ -506,11 +490,9 @@ end update_cam!(x, bb::AbstractCamera, rect) = update_cam!(get_scene(x), bb, rect) update_cam!(scene::Scene, bb::AbstractCamera, rect) = nothing -function not_in_data_space(p) - !is_data_space(to_value(get(p, :space, :data))) -end +not_in_data_space(p) = !is_data_space(to_value(get(p, :space, :data))) -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) diff --git a/src/shorthands.jl b/src/shorthands.jl index 31fded1dfe9..90f30ebf7ab 100644 --- a/src/shorthands.jl +++ b/src/shorthands.jl @@ -82,7 +82,7 @@ yticklabels(scene) = ticklabels(scene)[2] Returns the all the z-axis tick labels. See also `ticklabels`. """ function zticklabels(scene) - @assert !is2d(scene) "The Scene does not have a z-axis!" + @assert !is2d(scene) "The Scene does not have a z-axis!" ticklabels(scene)[3] end @@ -117,7 +117,7 @@ ytickrange(scene) = tickranges(scene)[2] Returns the tick range along the z-axis. See also `tickranges`. """ function ztickrange(scene) - @assert !is2d(scene) "The Scene does not have a z-axis!" + @assert !is2d(scene) "The Scene does not have a z-axis!" return tickranges(scene)[3] end @@ -127,7 +127,7 @@ end Set the tick labels and ranges along all axes. The respective labels and ranges along each axis must be of the same length. """ -function ticks!(scene::Scene; tickranges=tickranges(scene), ticklabels=ticklabels(scene)) +function ticks!(scene::Scene; tickranges = tickranges(scene), ticklabels = ticklabels(scene)) axis = scene[OldAxis] @assert !isnothing(axis) "The Scene does not have an axis!" # Have to set `ranges_labels` first so that any changes in the length of these @@ -143,8 +143,8 @@ end Set the tick labels and range along the x-axes. See also `ticks!`. """ -function xticks!(scene::Scene; xtickrange=xtickrange(scene), xticklabels=xticklabels(scene)) - ticks!(scene, tickranges=(xtickrange, tickranges(scene)[2:end]...), ticklabels=(xticklabels, ticklabels(scene)[2:end]...)) +function xticks!(scene::Scene; xtickrange = xtickrange(scene), xticklabels = xticklabels(scene)) + ticks!(scene, tickranges = (xtickrange, tickranges(scene)[2:end]...), ticklabels = (xticklabels, ticklabels(scene)[2:end]...)) return nothing end @@ -153,13 +153,13 @@ end Set the tick labels and range along all the y-axis. See also `ticks!`. """ -function yticks!(scene::Scene; ytickrange=ytickrange(scene), yticklabels=yticklabels(scene)) +function yticks!(scene::Scene; ytickrange = ytickrange(scene), yticklabels = yticklabels(scene)) r = tickranges(scene) l = ticklabels(scene) if length(r) == 2 - ticks!(scene, tickranges=(first(r), ytickrange), ticklabels=(first(l), yticklabels)) + ticks!(scene, tickranges = (first(r), ytickrange), ticklabels = (first(l), yticklabels)) else # length(r) == 3 - ticks!(scene, tickranges=(first(r), ytickrange, last(r)), ticklabels =(first(l), yticklabels, last(l))) + ticks!(scene, tickranges = (first(r), ytickrange, last(r)), ticklabels = (first(l), yticklabels, last(l))) end return nothing end @@ -169,9 +169,9 @@ end Set the tick labels and range along all z-axis. See also `ticks!`. """ -function zticks!(scene::Scene; ztickrange=ztickrange(scene), zticklabels=zticklabels(scene)) - @assert !is2d(scene) "The Scene does not have a z-axis!" - ticks!(scene, tickranges=(tickranges(scene)[1:2]..., ztickrange), ticklabels=(ticklabels(scene)[1:2]..., zticklabels)) +function zticks!(scene::Scene; ztickrange = ztickrange(scene), zticklabels = zticklabels(scene)) + @assert !is2d(scene) "The Scene does not have a z-axis!" + ticks!(scene, tickranges = (tickranges(scene)[1:2]..., ztickrange), ticklabels = (ticklabels(scene)[1:2]..., zticklabels)) return nothing end @@ -209,7 +209,7 @@ ytickrotation(scene) = tickrotations(scene)[2] Returns the rotation of tick labels along the z-axis. See also `tickrotations` """ function ztickrotation(scene) - @assert !is2d(scene) "The Scene does not have a z-axis!" + @assert !is2d(scene) "The Scene does not have a z-axis!" return tickrotations(scene)[3] end @@ -240,13 +240,12 @@ end Set the rotation of tick labels along the y-axis. See also `tickrotations!`. """ -function ytickrotation!(scene::Scene, yangle) +ytickrotation!(scene::Scene, yangle) = if is2d(scene) tickrotations!(scene, (xtickrotation(scene), yangle)) else # length(r) == 3 tickrotations!(scene, (xtickrotation(scene), yangle, ztickrotation(scene))) end -end """ ztickrotation!([scene,] zangle) @@ -254,7 +253,7 @@ end Set the rotation of tick labels along the z-axis. See also `tickrotations!`. """ function ztickrotation!(scene::Scene, zangle) - @assert !is2d(scene) "The Scene does not have a z-axis!" + @assert !is2d(scene) "The Scene does not have a z-axis!" tickrotations!(scene, (tickrotations(scene)[1:2]..., zangle)) return nothing end diff --git a/src/stats/boxplot.jl b/src/stats/boxplot.jl index 7ec7fb4f5ae..32feec9cafb 100644 --- a/src/stats/boxplot.jl +++ b/src/stats/boxplot.jl @@ -76,7 +76,7 @@ _cycle(v::AbstractVector, idx::Integer) = v[mod1(idx, length(v))] _cycle(v, idx::Integer) = v flip_xy(p::Point2f) = reverse(p) -flip_xy(r::Rect{2,T}) where {T} = Rect{2,T}(reverse(r.origin), reverse(r.widths)) +flip_xy(r::Rect{2, T}) where {T} = Rect{2, T}(reverse(r.origin), reverse(r.widths)) function Makie.plot!(plot::BoxPlot) args = @extract plot (weights, width, range, show_outliers, whiskerwidth, show_notch, orientation, gap, dodge, n_dodge, dodge_gap) @@ -122,7 +122,7 @@ function Makie.plot!(plot::BoxPlot) if Float64(range) != 0.0 # if the range is 0.0, the whiskers will extend to the data limit = range * (q4 - q2) inside = Float64[] - for (value, idx) in zip(values,idxs) + for (value, idx) in zip(values, idxs) if (value < (q2 - limit)) || (value > (q4 + limit)) if show_outliers push!(outlier_points, (center, value)) diff --git a/src/stats/conversions.jl b/src/stats/conversions.jl index ae48ecbec2b..497620457ac 100644 --- a/src/stats/conversions.jl +++ b/src/stats/conversions.jl @@ -1,9 +1,5 @@ struct SampleBased <: ConversionTrait end -function convert_arguments(::SampleBased, args::NTuple{N,AbstractVector{<:Number}}) where {N} - return args -end +convert_arguments(::SampleBased, args::NTuple{N, AbstractVector{<:Number}}) where {N} = args -function convert_arguments(P::SampleBased, positions::Vararg{AbstractVector}) - return convert_arguments(P, positions) -end +convert_arguments(P::SampleBased, positions::Vararg{AbstractVector}) = convert_arguments(P, positions) diff --git a/src/stats/crossbar.jl b/src/stats/crossbar.jl index 683b341ecba..cd8147b09f5 100644 --- a/src/stats/crossbar.jl +++ b/src/stats/crossbar.jl @@ -23,30 +23,30 @@ It is most commonly used as part of the `boxplot`. """ @recipe(CrossBar, x, y, ymin, ymax) do scene t = Theme( - color=theme(scene, :patchcolor), - colormap=theme(scene, :colormap), - colorrange=automatic, - orientation=:vertical, - # box and dodging - width = automatic, - dodge = automatic, - n_dodge = automatic, - gap = 0.2, - dodge_gap = 0.03, - strokecolor = theme(scene, :patchstrokecolor), - strokewidth = theme(scene, :patchstrokewidth), - # notch - show_notch=false, - notchmin=automatic, - notchmax=automatic, - notchwidth=0.5, - # median line - show_midline=true, - midlinecolor=automatic, - midlinewidth=theme(scene, :linewidth), - inspectable = theme(scene, :inspectable), - cycle = [:color => :patchcolor], -) + color = theme(scene, :patchcolor), + colormap = theme(scene, :colormap), + colorrange = automatic, + orientation = :vertical, + # box and dodging + width = automatic, + dodge = automatic, + n_dodge = automatic, + gap = 0.2, + dodge_gap = 0.03, + strokecolor = theme(scene, :patchstrokecolor), + strokewidth = theme(scene, :patchstrokewidth), + # notch + show_notch = false, + notchmin = automatic, + notchmax = automatic, + notchwidth = 0.5, + # median line + show_midline = true, + midlinecolor = automatic, + midlinewidth = theme(scene, :linewidth), + inspectable = theme(scene, :inspectable), + cycle = [:color => :patchcolor], + ) t end @@ -90,8 +90,8 @@ function Makie.plot!(plot::CrossBar) fpoint.(m .- nw .* hw, y), # notch left fpoint.(l, nmin), fpoint.(l, ymin) - ))) - boxes = if points isa AbstractVector{<: Point} # poly + ))) + boxes = if points isa AbstractVector{<:Point} # poly [GeometryBasics.triangle_mesh(points)] else # multiple polys (Vector{Vector{<:Point}}) GeometryBasics.triangle_mesh.(points) @@ -108,22 +108,22 @@ function Makie.plot!(plot::CrossBar) poly!( plot, boxes, - color=plot.color, - colorrange=plot.colorrange, - colormap=plot.colormap, - strokecolor=plot.strokecolor, - strokewidth=plot.strokewidth, + color = plot.color, + colorrange = plot.colorrange, + colormap = plot.colormap, + strokecolor = plot.strokecolor, + strokewidth = plot.strokewidth, inspectable = plot[:inspectable] ) linesegments!( plot, - color=lift( + color = lift( (mc, sc) -> mc === automatic ? sc : mc, plot.midlinecolor, plot.strokecolor, ), - linewidth=plot[:midlinewidth], - visible=plot[:show_midline], + linewidth = plot[:midlinewidth], + visible = plot[:show_midline], inspectable = plot[:inspectable], midlines, ) diff --git a/src/stats/density.jl b/src/stats/density.jl index 4d19df179fa..93d1b7a670e 100644 --- a/src/stats/density.jl +++ b/src/stats/density.jl @@ -6,7 +6,7 @@ end function convert_arguments(::Type{<:Poly}, d::KernelDensity.UnivariateKDE) points = Vector{Point2f}(undef, length(d.x) + 2) points[1] = Point2f(d.x[1], 0) - points[2:end-1] .= Point2f.(d.x, d.density) + points[2:(end - 1)] .= Point2f.(d.x, d.density) points[end] = Point2f(d.x[end], 0) (points,) end diff --git a/src/stats/distributions.jl b/src/stats/distributions.jl index da7b65cc154..fe3b735828b 100644 --- a/src/stats/distributions.jl +++ b/src/stats/distributions.jl @@ -4,21 +4,21 @@ 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 -isdiscrete(::Distribution{<:VariateForm,<:Discrete}) = true +isdiscrete(::Distribution{<:VariateForm, <:Discrete}) = true support(dist::Distribution) = default_range(dist) -support(dist::Distribution{<:VariateForm,<:Discrete}) = UnitRange(endpoints(default_range(dist))...) +support(dist::Distribution{<:VariateForm, <:Discrete}) = UnitRange(endpoints(default_range(dist))...) convert_arguments(P::PlotFunc, dist::Distribution) = convert_arguments(P, support(dist), dist) -function convert_arguments(P::PlotFunc, x::Union{Interval,AbstractVector}, dist::Distribution) +function convert_arguments(P::PlotFunc, x::Union{Interval, AbstractVector}, dist::Distribution) default_ptype = isdiscrete(dist) ? ScatterLines : Lines ptype = plottype(P, default_ptype) to_plotspec(ptype, convert_arguments(ptype, x, x -> pdf(dist, x))) @@ -86,7 +86,7 @@ end function fit_qqplot(x, y; qqline = :none) if !(qqline in (:identity, :fit, :fitrobust, :none)) msg = "valid values for qqline are :identity, :fit, :fitrobust or :none, " * - "encountered " * repr(qqline) + "encountered " * repr(qqline) throw(ArgumentError(msg)) end h = qqbuild(x, y) diff --git a/src/stats/ecdf.jl b/src/stats/ecdf.jl index 6494ca58df9..23dbd741ed6 100644 --- a/src/stats/ecdf.jl +++ b/src/stats/ecdf.jl @@ -2,15 +2,15 @@ function ecdf_xvalues(ecdf::StatsBase.ECDF, npoints) x = ecdf.sorted_values n = length(x) npoints ≥ n && return float(unique(x)) - return @inbounds range(x[1], x[n]; length=npoints) + return @inbounds range(x[1], x[n]; length = npoints) end used_attributes(::PlotFunc, ::StatsBase.ECDF) = (:npoints,) -function convert_arguments(P::PlotFunc, ecdf::StatsBase.ECDF; npoints=10_000) +function convert_arguments(P::PlotFunc, ecdf::StatsBase.ECDF; npoints = 10_000) ptype = plottype(P, Stairs) x0 = ecdf_xvalues(ecdf, npoints) if ptype <: Stairs - kwargs = (; step=:post) + kwargs = (; step = :post) x1 = x0[1] x = [x1 - eps(x1); x0] else @@ -21,7 +21,7 @@ function convert_arguments(P::PlotFunc, ecdf::StatsBase.ECDF; npoints=10_000) end function convert_arguments(P::PlotFunc, x::AbstractVector, ecdf::StatsBase.ECDF) ptype = plottype(P, Stairs) - kwargs = ptype <: Stairs ? (; step=:post) : NamedTuple() + kwargs = ptype <: Stairs ? (; step = :post) : NamedTuple() return to_plotspec(ptype, convert_arguments(ptype, x, ecdf(x)); kwargs...) end function convert_arguments(P::PlotFunc, x0::AbstractInterval, ecdf::StatsBase.ECDF) @@ -29,7 +29,7 @@ function convert_arguments(P::PlotFunc, x0::AbstractInterval, ecdf::StatsBase.EC z = ecdf_xvalues(ecdf, Inf) n = length(z) imin, imax = findfirst(>(xmin), z), findlast(<(xmax), z) - idx_min = imin === nothing ? n+1 : imin + idx_min = imin === nothing ? n + 1 : imin idx_max = imax === nothing ? -1 : imax x = [xmin - eps(oftype(z[1], xmin)); xmin; view(z, idx_min:idx_max); xmax] return convert_arguments(P, x, ecdf) @@ -54,9 +54,9 @@ used_attributes(::Type{<:ECDFPlot}, ::AbstractVector) = (:npoints, :weights) function convert_arguments( ::Type{<:ECDFPlot}, x::AbstractVector; - npoints=10_000, - weights=StatsBase.Weights(Float64[]), + npoints = 10_000, + weights = StatsBase.Weights(Float64[]) ) - ecdf = StatsBase.ecdf(x; weights=weights) - return convert_arguments(Stairs, ecdf; npoints=npoints) + ecdf = StatsBase.ecdf(x; weights = weights) + return convert_arguments(Stairs, ecdf; npoints = npoints) end diff --git a/src/stats/hexbin.jl b/src/stats/hexbin.jl index 21527975726..87388fd00f2 100644 --- a/src/stats/hexbin.jl +++ b/src/stats/hexbin.jl @@ -19,17 +19,17 @@ Plots a heatmap with hexagonal bins for the observations `xs` and `ys`. """ @recipe(Hexbin) do scene return Attributes(; - colormap=theme(scene, :colormap), - colorrange=Makie.automatic, - bins=20, - cellsize=nothing, - threshold=1, - scale=identity, - strokewidth=0, - strokecolor=:black) + colormap = theme(scene, :colormap), + colorrange = Makie.automatic, + bins = 20, + cellsize = nothing, + threshold = 1, + scale = identity, + strokewidth = 0, + strokecolor = :black) end -function spacings_offsets_nbins(bins::Tuple{Int,Int}, cellsize::Nothing, xmi, xma, ymi, yma) +function spacings_offsets_nbins(bins::Tuple{Int, Int}, cellsize::Nothing, xmi, xma, ymi, yma) any(<(2), bins) && error("Minimum number of bins in one direction is 2, got $bins.") x_diff = xma - xmi y_diff = yma - ymi @@ -38,21 +38,17 @@ function spacings_offsets_nbins(bins::Tuple{Int,Int}, cellsize::Nothing, xmi, xm return xspacing, yspacing, xmi, ymi, bins... end -function spacings_offsets_nbins(bins, cellsize::Real, xmi, xma, ymi, yma) - return spacings_offsets_nbins(bins, (cellsize, cellsize * 2 / sqrt(3)), xmi, xma, ymi, yma) -end -function spacings_offsets_nbins(bins::Int, cellsize::Nothing, xmi, xma, ymi, yma) - return spacings_offsets_nbins((bins, bins), cellsize, xmi, xma, ymi, yma) -end +spacings_offsets_nbins(bins, cellsize::Real, xmi, xma, ymi, yma) = spacings_offsets_nbins(bins, (cellsize, cellsize * 2 / sqrt(3)), xmi, xma, ymi, yma) +spacings_offsets_nbins(bins::Int, cellsize::Nothing, xmi, xma, ymi, yma) = spacings_offsets_nbins((bins, bins), cellsize, xmi, xma, ymi, yma) -function spacings_offsets_nbins(bins, cellsizes::Tuple{<:Real,<:Real}, xmi, xma, ymi, yma) +function spacings_offsets_nbins(bins, cellsizes::Tuple{<:Real, <:Real}, xmi, xma, ymi, yma) x_diff = xma - xmi y_diff = yma - ymi xspacing = cellsizes[1] / 2 yspacing = cellsizes[2] * 3 / 4 (nx, restx), (ny, resty) = fldmod.((x_diff, y_diff), (xspacing, yspacing)) return xspacing, yspacing, xmi - (restx > 0 ? (xspacing - restx) / 2 : 0), - ymi - (resty > 0 ? (yspacing - resty) / 2 : 0), Int(nx) + (restx > 0), Int(ny) + (resty > 0) + ymi - (resty > 0 ? (yspacing - resty) / 2 : 0), Int(nx) + (restx > 0), Int(ny) + (resty > 0) end Makie.conversion_trait(::Type{<:Hexbin}) = PointBased() @@ -60,7 +56,7 @@ Makie.conversion_trait(::Type{<:Hexbin}) = PointBased() function data_limits(hb::Hexbin) bb = Rect3f(hb.plots[1][1][]) fn(num::Real) = Float32(num) - fn(tup::Union{Tuple,Vec2}) = Vec2f(tup...) + fn(tup::Union{Tuple, Vec2}) = Vec2f(tup...) ms = 2 .* fn(hb.plots[1].markersize[]) nw = widths(bb) .+ (ms..., 0.0f0) @@ -94,7 +90,7 @@ function Makie.plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) y_diff = yma - ymi xspacing, yspacing, xoff, yoff, nbinsx, nbinsy = spacings_offsets_nbins(bins, cellsize, xmi, xma, ymi, - yma) + yma) ysize = yspacing / 3 * 4 ry = ysize / 2 @@ -102,7 +98,7 @@ function Makie.plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) xsize = xspacing * 2 rx = xsize / sqrt3 - d = Dict{Tuple{Int,Int},Int}() + d = Dict{Tuple{Int, Int}, Int}() # 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 @@ -119,16 +115,16 @@ function Makie.plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) is_grid1 = d1 < d2 # _xy = is_grid1 ? (nx, ny) : (nxs, nys) - + id = if is_grid1 ( cld(dvx, 2), - iseven(dvy) ? dvy : dvy+1 + iseven(dvy) ? dvy : dvy + 1 ) else ( fld(dvx, 2), - iseven(dvy) ? dvy+1 : dvy, + iseven(dvy) ? dvy + 1 : dvy, ) end @@ -136,9 +132,9 @@ function Makie.plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) end if threshold == 0 - for iy in 0:nbinsy-1 + for iy in 0:(nbinsy - 1) _nx = isodd(iy) ? fld(nbinsx, 2) : cld(nbinsx, 2) - for ix in 0:_nx-1 + for ix in 0:(_nx - 1) _x = xoff + 2 * ix * xspacing + (isodd(iy) * xspacing) _y = yoff + iy * yspacing c = get(d, (ix, iy), 0) @@ -174,30 +170,29 @@ function Makie.plot!(hb::Hexbin{<:Tuple{<:AbstractVector{<:Point2}}}) end end - hexmarker = Polygon(Point2f[(cos(a), sin(a)) for a in range(pi / 6, 13pi / 6; length=7)[1:6]]) + hexmarker = Polygon(Point2f[(cos(a), sin(a)) for a in range(pi / 6, 13pi / 6; length = 7)[1:6]]) return scatter!(hb, points; - colorrange=hb.colorrange, - color=count_hex, - colormap=hb.colormap, - marker=hexmarker, - markersize=markersize, - markerspace=:data, - strokewidth=hb.strokewidth, - strokecolor=hb.strokecolor) + colorrange = hb.colorrange, + color = count_hex, + colormap = hb.colormap, + marker = hexmarker, + markersize = markersize, + markerspace = :data, + strokewidth = hb.strokewidth, + strokecolor = hb.strokecolor) end -function center_value(dv, spacing, offset, is_grid1) +center_value(dv, spacing, offset, is_grid1) = if is_grid1 offset + spacing * (dv + isodd(dv)) else offset + spacing * (dv + iseven(dv)) end -end function nearest_center(val, spacing, offset) dv = Int(fld(val - offset, spacing)) rounded = offset + spacing * (dv + isodd(dv)) rounded_scaled = offset + spacing * (dv + iseven(dv)) return rounded, rounded_scaled, dv -end \ No newline at end of file +end diff --git a/src/stats/hist.jl b/src/stats/hist.jl index 3ab8d0f281a..c97628371e1 100644 --- a/src/stats/hist.jl +++ b/src/stats/hist.jl @@ -2,7 +2,7 @@ const histogram_plot_types = [BarPlot, Heatmap, Volume] function convert_arguments(P::Type{<:AbstractPlot}, h::StatsBase.Histogram{<:Any, N}) where N ptype = plottype(P, histogram_plot_types[N]) - f(edges) = edges[1:end-1] .+ diff(edges)./2 + f(edges) = edges[1:(end - 1)] .+ diff(edges) ./ 2 kwargs = N == 1 ? (; width = step(h.edges[1]), gap = 0, dodge_gap = 0) : NamedTuple() to_plotspec(ptype, convert_arguments(ptype, map(f, h.edges)..., Float64.(h.weights)); kwargs...) end @@ -52,9 +52,7 @@ $(ATTRIBUTES) color = theme(scene, :patchcolor), offset = 0.0, fillto = automatic, - scale_to = nothing, - - bar_labels = nothing, + scale_to = nothing, bar_labels = nothing, flip_labels_at = Inf, label_color = theme(scene, :textcolor), over_background_color = automatic, @@ -66,7 +64,7 @@ $(ATTRIBUTES) ) end -function pick_hist_edges(vals, bins) +pick_hist_edges(vals, bins) = if bins isa Int mi, ma = float.(extrema(vals)) if mi == ma @@ -74,25 +72,24 @@ 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") end return bins end -end function Makie.plot!(plot::Hist) values = plot.values - edges = lift(pick_hist_edges, values, plot.bins) + edges = lift(pick_hist_edges, values, plot.bins) points = lift(edges, plot.normalization, plot.scale_to, plot.weights) do edges, normalization, scale_to, wgts w = wgts === automatic ? () : (StatsBase.weights(wgts),) h = StatsBase.fit(StatsBase.Histogram, values[], w..., edges) h_norm = StatsBase.normalize(h, mode = normalization) - centers = edges[1:end-1] .+ (diff(edges) ./ 2) + centers = edges[1:(end - 1)] .+ (diff(edges) ./ 2) weights = h_norm.weights if !isnothing(scale_to) max = maximum(weights) @@ -113,7 +110,7 @@ function Makie.plot!(plot::Hist) x === :values ? :y : x end # plot the values, not the observables, to be in control of updating - bp = barplot!(plot, points[]; width = widths[], gap = 0, plot.attributes..., fillto=plot.fillto, offset=plot.offset, bar_labels=bar_labels, color=color) + bp = barplot!(plot, points[]; width = widths[], gap = 0, plot.attributes..., fillto = plot.fillto, offset = plot.offset, bar_labels = bar_labels, color = color) # update the barplot points without triggering, then trigger with `width` on(widths) do w diff --git a/src/stats/violin.jl b/src/stats/violin.jl index 0361ef246c6..f7e671c4899 100644 --- a/src/stats/violin.jl +++ b/src/stats/violin.jl @@ -31,7 +31,7 @@ Draw a violin plot. max_density = automatic, show_median = false, mediancolor = theme(scene, :linecolor), - medianlinewidth = theme(scene, :linewidth), + medianlinewidth = theme(scene, :linewidth) ) end @@ -62,7 +62,7 @@ function plot!(plot::Violin) # Allow `side` to be either scalar or vector sides = broadcast(x̂, vside) do _, s - return s == :left ? - 1 : s == :right ? 1 : 0 + return s == :left ? -1 : s == :right ? 1 : 0 end sa = StructArray((x = x̂, side = sides)) @@ -96,7 +96,7 @@ function plot!(plot::Violin) colors = RGBA{Float32}[] for spec in specs - scale = 0.5*violinwidth/max + scale = 0.5 * violinwidth / max xl = reverse(spec.x .- spec.kde.density .* scale) xr = spec.x .+ spec.kde.density .* scale yl = reverse(spec.kde.x) @@ -116,8 +116,8 @@ function plot!(plot::Violin) # interpolate median bounds between corresponding points xm = spec.median ip = findfirst(>(xm), spec.kde.x) - ym₋, ym₊ = spec.kde.density[ip-1], spec.kde.density[ip] - xm₋, xm₊ = spec.kde.x[ip-1], spec.kde.x[ip] + ym₋, ym₊ = spec.kde.density[ip - 1], spec.kde.density[ip] + xm₋, xm₊ = spec.kde.x[ip - 1], spec.kde.x[ip] ym = (xm * (ym₊ - ym₋) + xm₊ * ym₋ - xm₋ * ym₊) / (xm₊ - xm₋) median_left = point_func(spec.side == 1 ? spec.x : spec.x - ym * scale, xm) median_right = point_func(spec.side == -1 ? spec.x : spec.x + ym * scale, xm) diff --git a/src/themes/theme_black.jl b/src/themes/theme_black.jl index 1f0b9965b59..4335ebc2da2 100644 --- a/src/themes/theme_black.jl +++ b/src/themes/theme_black.jl @@ -1,50 +1,48 @@ -function theme_black() - Theme( - backgroundcolor = :black, - textcolor = :white, - linecolor = :white, - Axis = ( - backgroundcolor = :transparent, - bottomspinecolor = :white, - topspinecolor = :white, - leftspinecolor = :white, - rightspinecolor = :white, - xgridcolor = RGBAf(1, 1, 1, 0.16), - ygridcolor = RGBAf(1, 1, 1, 0.16), - xtickcolor = :white, - ytickcolor = :white, - ), - Legend = ( - framecolor = :white, - bgcolor = :black, - ), - Axis3 = ( - xgridcolor = RGBAf(1, 1, 1, 0.16), - ygridcolor = RGBAf(1, 1, 1, 0.16), - zgridcolor = RGBAf(1, 1, 1, 0.16), - xspinecolor_1 = :white, - yspinecolor_1 = :white, - zspinecolor_1 = :white, - xspinecolor_2 = :white, - yspinecolor_2 = :white, - zspinecolor_2 = :white, - xspinecolor_3 = :white, - yspinecolor_3 = :white, - zspinecolor_3 = :white, - xticklabelpad = 3, - yticklabelpad = 3, - zticklabelpad = 6, - xtickcolor = :white, - ytickcolor = :white, - ztickcolor = :white, - ), - Colorbar = ( - tickcolor = :white, - spinecolor = :white, - topspinecolor = :white, - bottomspinecolor = :white, - leftspinecolor = :white, - rightspinecolor = :white, - ) +theme_black() = Theme( + backgroundcolor = :black, + textcolor = :white, + linecolor = :white, + Axis = ( + backgroundcolor = :transparent, + bottomspinecolor = :white, + topspinecolor = :white, + leftspinecolor = :white, + rightspinecolor = :white, + xgridcolor = RGBAf(1, 1, 1, 0.16), + ygridcolor = RGBAf(1, 1, 1, 0.16), + xtickcolor = :white, + ytickcolor = :white, + ), + Legend = ( + framecolor = :white, + bgcolor = :black, + ), + Axis3 = ( + xgridcolor = RGBAf(1, 1, 1, 0.16), + ygridcolor = RGBAf(1, 1, 1, 0.16), + zgridcolor = RGBAf(1, 1, 1, 0.16), + xspinecolor_1 = :white, + yspinecolor_1 = :white, + zspinecolor_1 = :white, + xspinecolor_2 = :white, + yspinecolor_2 = :white, + zspinecolor_2 = :white, + xspinecolor_3 = :white, + yspinecolor_3 = :white, + zspinecolor_3 = :white, + xticklabelpad = 3, + yticklabelpad = 3, + zticklabelpad = 6, + xtickcolor = :white, + ytickcolor = :white, + ztickcolor = :white, + ), + Colorbar = ( + tickcolor = :white, + spinecolor = :white, + topspinecolor = :white, + bottomspinecolor = :white, + leftspinecolor = :white, + rightspinecolor = :white, ) -end +) diff --git a/src/themes/theme_dark.jl b/src/themes/theme_dark.jl index b284e95ca3a..6d60f337305 100644 --- a/src/themes/theme_dark.jl +++ b/src/themes/theme_dark.jl @@ -1,42 +1,40 @@ -function theme_dark() - Theme( - backgroundcolor = :gray10, - textcolor = :gray45, - linecolor = :gray60, - Axis = ( - backgroundcolor = :transparent, - xgridcolor = (:white, 0.09), - ygridcolor = (:white, 0.09), - leftspinevisible = false, - rightspinevisible = false, - bottomspinevisible = false, - topspinevisible = false, - xminorticksvisible = false, - yminorticksvisible = false, - xticksvisible = false, - yticksvisible = false, - xlabelpadding = 3, - ylabelpadding = 3 - ), - Legend = ( - framevisible = false, - padding = (0, 0, 0, 0), - ), - Axis3 = ( - xgridcolor = (:white, 0.09), - ygridcolor = (:white, 0.09), - zgridcolor = (:white, 0.09), - xspinesvisible = false, - yspinesvisible = false, - zspinesvisible = false, - xticksvisible = false, - yticksvisible = false, - zticksvisible = false, - ), - Colorbar = ( - ticksvisible = false, - spinewidth = 0, - ticklabelpad = 5, - ) +theme_dark() = Theme( + backgroundcolor = :gray10, + textcolor = :gray45, + linecolor = :gray60, + Axis = ( + backgroundcolor = :transparent, + xgridcolor = (:white, 0.09), + ygridcolor = (:white, 0.09), + leftspinevisible = false, + rightspinevisible = false, + bottomspinevisible = false, + topspinevisible = false, + xminorticksvisible = false, + yminorticksvisible = false, + xticksvisible = false, + yticksvisible = false, + xlabelpadding = 3, + ylabelpadding = 3 + ), + Legend = ( + framevisible = false, + padding = (0, 0, 0, 0), + ), + Axis3 = ( + xgridcolor = (:white, 0.09), + ygridcolor = (:white, 0.09), + zgridcolor = (:white, 0.09), + xspinesvisible = false, + yspinesvisible = false, + zspinesvisible = false, + xticksvisible = false, + yticksvisible = false, + zticksvisible = false, + ), + Colorbar = ( + ticksvisible = false, + spinewidth = 0, + ticklabelpad = 5, ) -end +) diff --git a/src/themes/theme_ggplot2.jl b/src/themes/theme_ggplot2.jl index d3166c8c8bd..9fd5a4eb36b 100644 --- a/src/themes/theme_ggplot2.jl +++ b/src/themes/theme_ggplot2.jl @@ -1,58 +1,56 @@ -function theme_ggplot2() - Theme( - Axis = ( - backgroundcolor = :gray92, - xgridcolor = :white, - ygridcolor = :white, - xminorgridcolor = (:white, 0.5), - xminorgridvisible = true, - yminorgridcolor = (:white, 0.5), - yminorgridvisible = true, - leftspinevisible = false, - rightspinevisible = false, - bottomspinevisible = false, - topspinevisible = false, - xminorticksvisible = false, - yminorticksvisible = false, - xtickcolor = :gray21, - ytickcolor = :gray21, - spinewidth = 0, - xticklabelcolor = :gray31, - yticklabelcolor = :gray31, - xticksize = 4, - yticksize = 4, - xtickwidth = 1.5, - ytickwidth = 1.5, - xgridwidth = 1.5, - ygridwidth = 1.5, - xlabelpadding = 3, - ylabelpadding = 3 - ), - Legend = ( - framevisible = false, - padding = (0, 0, 0, 0), - patchcolor = :gray92, - ), - Axis3 = ( - xgridcolor = :white, - ygridcolor = :white, - zgridcolor = :white, - xspinesvisible = false, - yspinesvisible = false, - zspinesvisible = false, - yzpanelcolor = :gray92, - xzpanelcolor = :gray92, - xypanelcolor = :gray92, - xticklabelcolor = :gray31, - yticklabelcolor = :gray31, - zticklabelcolor = :gray31, - ), - Colorbar = ( - tickcolor = :white, - tickalign = 1, - ticklabelcolor = :gray31, - spinewidth = 0, - ticklabelpad = 5, - ) +theme_ggplot2() = Theme( + Axis = ( + backgroundcolor = :gray92, + xgridcolor = :white, + ygridcolor = :white, + xminorgridcolor = (:white, 0.5), + xminorgridvisible = true, + yminorgridcolor = (:white, 0.5), + yminorgridvisible = true, + leftspinevisible = false, + rightspinevisible = false, + bottomspinevisible = false, + topspinevisible = false, + xminorticksvisible = false, + yminorticksvisible = false, + xtickcolor = :gray21, + ytickcolor = :gray21, + spinewidth = 0, + xticklabelcolor = :gray31, + yticklabelcolor = :gray31, + xticksize = 4, + yticksize = 4, + xtickwidth = 1.5, + ytickwidth = 1.5, + xgridwidth = 1.5, + ygridwidth = 1.5, + xlabelpadding = 3, + ylabelpadding = 3 + ), + Legend = ( + framevisible = false, + padding = (0, 0, 0, 0), + patchcolor = :gray92, + ), + Axis3 = ( + xgridcolor = :white, + ygridcolor = :white, + zgridcolor = :white, + xspinesvisible = false, + yspinesvisible = false, + zspinesvisible = false, + yzpanelcolor = :gray92, + xzpanelcolor = :gray92, + xypanelcolor = :gray92, + xticklabelcolor = :gray31, + yticklabelcolor = :gray31, + zticklabelcolor = :gray31, + ), + Colorbar = ( + tickcolor = :white, + tickalign = 1, + ticklabelcolor = :gray31, + spinewidth = 0, + ticklabelpad = 5, ) -end +) diff --git a/src/themes/theme_light.jl b/src/themes/theme_light.jl index 83bc2313207..060509322f3 100644 --- a/src/themes/theme_light.jl +++ b/src/themes/theme_light.jl @@ -1,40 +1,38 @@ -function theme_light() - Theme( - textcolor = :gray50, - Axis = ( - backgroundcolor = :transparent, - xgridcolor = (:black, 0.07), - ygridcolor = (:black, 0.07), - leftspinevisible = false, - rightspinevisible = false, - bottomspinevisible = false, - topspinevisible = false, - xminorticksvisible = false, - yminorticksvisible = false, - xticksvisible = false, - yticksvisible = false, - xlabelpadding = 3, - ylabelpadding = 3 - ), - Legend = ( - framevisible = false, - padding = (0, 0, 0, 0), - ), - Axis3 = ( - xgridcolor = (:black, 0.07), - ygridcolor = (:black, 0.07), - zgridcolor = (:black, 0.07), - xspinesvisible = false, - yspinesvisible = false, - zspinesvisible = false, - xticksvisible = false, - yticksvisible = false, - zticksvisible = false, - ), - Colorbar = ( - ticksvisible = false, - spinewidth = 0, - ticklabelpad = 5, - ) +theme_light() = Theme( + textcolor = :gray50, + Axis = ( + backgroundcolor = :transparent, + xgridcolor = (:black, 0.07), + ygridcolor = (:black, 0.07), + leftspinevisible = false, + rightspinevisible = false, + bottomspinevisible = false, + topspinevisible = false, + xminorticksvisible = false, + yminorticksvisible = false, + xticksvisible = false, + yticksvisible = false, + xlabelpadding = 3, + ylabelpadding = 3 + ), + Legend = ( + framevisible = false, + padding = (0, 0, 0, 0), + ), + Axis3 = ( + xgridcolor = (:black, 0.07), + ygridcolor = (:black, 0.07), + zgridcolor = (:black, 0.07), + xspinesvisible = false, + yspinesvisible = false, + zspinesvisible = false, + xticksvisible = false, + yticksvisible = false, + zticksvisible = false, + ), + Colorbar = ( + ticksvisible = false, + spinewidth = 0, + ticklabelpad = 5, ) -end +) diff --git a/src/themes/theme_minimal.jl b/src/themes/theme_minimal.jl index 4c3ac1af7e6..5b1d47ff57d 100644 --- a/src/themes/theme_minimal.jl +++ b/src/themes/theme_minimal.jl @@ -1,53 +1,51 @@ -function theme_minimal() - Theme( - Axis = ( - backgroundcolor = :transparent, - xgridvisible = false, - ygridvisible = false, - xminorgridvisible = false, - yminorgridvisible = false, - leftspinevisible = true, - rightspinevisible = false, - bottomspinevisible = true, - topspinevisible = false, - xminorticksvisible = false, - yminorticksvisible = false, - xticksvisible = false, - yticksvisible = false, - xlabelpadding = 3, - ylabelpadding = 3 - ), - Legend = ( - framevisible = false, - padding = (0, 0, 0, 0), - ), - Axis3 = ( - xgridvisible = false, - ygridvisible = false, - zgridvisible = false, - xspinesvisible = true, - yspinesvisible = true, - zspinesvisible = true, - yzpanelvisible = false, - xzpanelvisible = false, - xypanelvisible = false, - xticksvisible = false, - yticksvisible = false, - zticksvisible = false, - xticklabelpad = 3, - yticklabelpad = 3, - zticklabelpad = 6, - xspinecolor_2 = :transparent, - xspinecolor_3 = :transparent, - yspinecolor_2 = :transparent, - yspinecolor_3 = :transparent, - zspinecolor_2 = :transparent, - zspinecolor_3 = :transparent, - ), - Colorbar = ( - ticksvisible = false, - spinewidth = 0, - ticklabelpad = 5, - ) +theme_minimal() = Theme( + Axis = ( + backgroundcolor = :transparent, + xgridvisible = false, + ygridvisible = false, + xminorgridvisible = false, + yminorgridvisible = false, + leftspinevisible = true, + rightspinevisible = false, + bottomspinevisible = true, + topspinevisible = false, + xminorticksvisible = false, + yminorticksvisible = false, + xticksvisible = false, + yticksvisible = false, + xlabelpadding = 3, + ylabelpadding = 3 + ), + Legend = ( + framevisible = false, + padding = (0, 0, 0, 0), + ), + Axis3 = ( + xgridvisible = false, + ygridvisible = false, + zgridvisible = false, + xspinesvisible = true, + yspinesvisible = true, + zspinesvisible = true, + yzpanelvisible = false, + xzpanelvisible = false, + xypanelvisible = false, + xticksvisible = false, + yticksvisible = false, + zticksvisible = false, + xticklabelpad = 3, + yticklabelpad = 3, + zticklabelpad = 6, + xspinecolor_2 = :transparent, + xspinecolor_3 = :transparent, + yspinecolor_2 = :transparent, + yspinecolor_3 = :transparent, + zspinecolor_2 = :transparent, + zspinecolor_3 = :transparent, + ), + Colorbar = ( + ticksvisible = false, + spinewidth = 0, + ticklabelpad = 5, ) -end +) diff --git a/src/theming.jl b/src/theming.jl index 7193ef849de..354584b7770 100644 --- a/src/theming.jl +++ b/src/theming.jl @@ -10,9 +10,9 @@ if Sys.iswindows() elseif Sys.isapple() const _CoreGraphics = "CoreGraphics.framework/CoreGraphics" function primary_resolution() - dispid = ccall((:CGMainDisplayID, _CoreGraphics), UInt32,()) - height = ccall((:CGDisplayPixelsHigh,_CoreGraphics), Int, (UInt32,), dispid) - width = ccall((:CGDisplayPixelsWide,_CoreGraphics), Int, (UInt32,), dispid) + dispid = ccall((:CGMainDisplayID, _CoreGraphics), UInt32, ()) + height = ccall((:CGDisplayPixelsHigh, _CoreGraphics), Int, (UInt32,), dispid) + width = ccall((:CGDisplayPixelsWide, _CoreGraphics), Int, (UInt32,), dispid) return (width, height) end else @@ -34,13 +34,13 @@ https://www.nature.com/articles/nmeth.1618?WT.ec_id=NMETH-201106 function wong_colors(alpha = 1.0) colors = [ - RGB(0/255, 114/255, 178/255), # blue - RGB(230/255, 159/255, 0/255), # orange - RGB(0/255, 158/255, 115/255), # green - RGB(204/255, 121/255, 167/255), # reddish purple - RGB(86/255, 180/255, 233/255), # sky blue - RGB(213/255, 94/255, 0/255), # vermillion - RGB(240/255, 228/255, 66/255), # yellow + RGB(0 / 255, 114 / 255, 178 / 255), # blue + RGB(230 / 255, 159 / 255, 0 / 255), # orange + RGB(0 / 255, 158 / 255, 115 / 255), # green + RGB(204 / 255, 121 / 255, 167 / 255), # reddish purple + RGB(86 / 255, 180 / 255, 233 / 255), # sky blue + RGB(213 / 255, 94 / 255, 0 / 255), # vermillion + RGB(240 / 255, 228 / 255, 66 / 255), # yellow ] @. RGBAf(red(colors), green(colors), blue(colors), alpha) end @@ -98,17 +98,13 @@ const minimal_default = Attributes( ), ambient = RGBf(0.55, 0.55, 0.55), lightposition = :eyeposition, - inspectable = true, - - CairoMakie = Attributes( + inspectable = true, CairoMakie = Attributes( px_per_unit = 1.0, pt_per_unit = 0.75, antialias = :best, visible = true, start_renderloop = false - ), - - GLMakie = Attributes( + ), GLMakie = Attributes( # Renderloop renderloop = automatic, pause_renderloop = false, @@ -132,14 +128,10 @@ const minimal_default = Attributes( # This adjusts a factor in the rendering shaders for order independent # transparency. This should be the same for all of them (within one rendering # pipeline) otherwise depth "order" will be broken. - transparency_weight_scale = 1000f0 - ), - - WGLMakie = Attributes( + transparency_weight_scale = 1000.0f0 + ), WGLMakie = Attributes( framerate = 30.0 - ), - - RPRMakie = Attributes( + ), RPRMakie = Attributes( iterations = 200, resource = automatic, plugin = automatic, @@ -149,9 +141,7 @@ const minimal_default = Attributes( const CURRENT_DEFAULT_THEME = deepcopy(minimal_default) -function current_default_theme(; kw_args...) - return merge!(Attributes(kw_args), deepcopy(CURRENT_DEFAULT_THEME)) -end +current_default_theme(; kw_args...) = merge!(Attributes(kw_args), deepcopy(CURRENT_DEFAULT_THEME)) """ set_theme(theme; kwargs...) @@ -216,15 +206,12 @@ function update_theme!(with_theme = Theme()::Attributes; kwargs...) return end -function _update_attrs!(attrs1, attrs2) +_update_attrs!(attrs1, attrs2) = for (key, value) in attrs2 _update_key!(attrs1, key, value) end -end -function _update_key!(theme, key::Symbol, content) - theme[key] = content -end +_update_key!(theme, key::Symbol, content) = theme[key] = content function _update_key!(theme, key::Symbol, content::Attributes) if haskey(theme, key) && theme[key] isa Attributes diff --git a/src/types.jl b/src/types.jl index c28e74df6a8..a0708d3bcff 100644 --- a/src/types.jl +++ b/src/types.jl @@ -117,14 +117,10 @@ function Events() events = Events( Observable(Recti(0, 0, 0, 0)), Observable(100.0), - Observable(false), - - Observable(MouseButtonEvent(Mouse.none, Mouse.release)), + Observable(false), Observable(MouseButtonEvent(Mouse.none, Mouse.release)), Set{Mouse.Button}(), Observable((0.0, 0.0)), - Observable((0.0, 0.0)), - - Observable(KeyEvent(Keyboard.unknown, Keyboard.release)), + Observable((0.0, 0.0)), Observable(KeyEvent(Keyboard.unknown, Keyboard.release)), Set{Keyboard.Button}(), Observable('\0'), Observable(String[]), @@ -170,7 +166,7 @@ function connect_states!(e::Events) end # Compat only -function Base.getproperty(e::Events, field::Symbol) +Base.getproperty(e::Events, field::Symbol) = if field === :mousebuttons error("`events.mousebuttons` is deprecated. Use `events.mousebutton` to react to `MouseButtonEvent`s instead.") elseif field === :keyboardbuttons @@ -180,7 +176,6 @@ function Base.getproperty(e::Events, field::Symbol) else return getfield(e, field) end -end function Base.empty!(events::Events) for field in fieldnames(Events) @@ -252,12 +247,10 @@ struct Transformation <: Transformable model::Observable{Mat4f} # data conversion observable, for e.g. log / log10 etc transform_func::Observable{Any} - function Transformation(translation, scale, rotation, model, transform_func) - return new( - RefValue{Transformation}(), - translation, scale, rotation, model, transform_func - ) - end + Transformation(translation, scale, rotation, model, transform_func) = new( + RefValue{Transformation}(), + translation, scale, rotation, model, transform_func + ) end """ @@ -266,10 +259,10 @@ end Object encoding positional arguments (`args`), a `NamedTuple` of attributes (`kwargs`) as well as plot type `P` of a basic plot. """ -struct PlotSpec{P<:AbstractPlot} +struct PlotSpec{P <: AbstractPlot} args::Tuple kwargs::NamedTuple - PlotSpec{P}(args...; kwargs...) where {P<:AbstractPlot} = new{P}(args, values(kwargs)) + PlotSpec{P}(args...; kwargs...) where {P <: AbstractPlot} = new{P}(args, values(kwargs)) end PlotSpec(args...; kwargs...) = PlotSpec{Combined{Any}}(args...; kwargs...) @@ -294,7 +287,7 @@ Base.convert(::Type{<:ScalarOrVector}, v::AbstractVector{T}) where T = ScalarOrV Base.convert(::Type{<:ScalarOrVector}, x::T) where T = ScalarOrVector{T}(x) Base.convert(::Type{<:ScalarOrVector{T}}, x::ScalarOrVector{T}) where T = x -function collect_vector(sv::ScalarOrVector, n::Int) +collect_vector(sv::ScalarOrVector, n::Int) = if sv.sv isa Vector if length(sv.sv) != n error("Requested collected vector with $n elements, contained vector had $(length(sv.sv)) elements.") @@ -303,7 +296,6 @@ function collect_vector(sv::ScalarOrVector, n::Int) else fill(sv.sv, n) end -end """ GlyphExtent @@ -356,7 +348,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 diff --git a/src/units.jl b/src/units.jl index d93d71f8331..045b3cb94f0 100644 --- a/src/units.jl +++ b/src/units.jl @@ -17,16 +17,14 @@ # struct DIP <: DisplaySpace end ######### -function to_screen(scene::Scene, mpos) - return Point2f(mpos) .- Point2f(minimum(pixelarea(scene)[])) -end +to_screen(scene::Scene, mpos) = Point2f(mpos) .- Point2f(minimum(pixelarea(scene)[])) number(x::Unit) = x.value number(x) = x -Base.:(*)(a::T, b::Number) where {T<:Unit} = basetype(T)(number(a) * b) -Base.:(*)(a::Number, b::T) where {T<:Unit} = basetype(T)(a * number(b)) -Base.convert(::Type{T}, x::Unit) where T<:Number = convert(T, number(x)) +Base.:(*)(a::T, b::Number) where {T <: Unit} = basetype(T)(number(a) * b) +Base.:(*)(a::Number, b::T) where {T <: Unit} = basetype(T)(a * number(b)) +Base.convert(::Type{T}, x::Unit) where T <: Number = convert(T, number(x)) """ Unit space of the scene it's displayed on. @@ -46,14 +44,14 @@ application that an underlying system then converts to physical pixels. 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 +62,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") @@ -72,48 +70,44 @@ Base.:(*)(a::Number, b::DIP) = DIP(a * number(b)) dpi(scene::Scene) = events(scene).window_dpi[] -function pixel_per_mm(scene) - dpi(scene) ./ 25.4 -end +pixel_per_mm(scene) = dpi(scene) ./ 25.4 -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) - Millimeter(number(x * dip_in_millimeter)) -end +Base.convert(::Type{<:Millimeter}, scene::Scene, x::DIP) = Millimeter(number(x * dip_in_millimeter)) -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 diff --git a/src/utilities/quaternions.jl b/src/utilities/quaternions.jl index bcae57f50de..d46c3962db3 100644 --- a/src/utilities/quaternions.jl +++ b/src/utilities/quaternions.jl @@ -12,7 +12,7 @@ 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} @@ -27,10 +27,8 @@ 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} - T(T2.(x.data)) -end +Base.convert(T::Type{<:Quaternion}, x::NTuple{4, Any}) = T(x) +Base.convert(T::Type{Quaternion{T1}}, x::Quaternion{T2}) where {T1, T2} = T(T2.(x.data)) Quaternion(x1, x2, x3, s) = Quaternion(promote(x1, x2, x3, s)) Quaternion(x::NTuple{4, T}) where T = Quaternion{T}(x) Base.getindex(x::Quaternion, i::Integer) = x.data[i] @@ -42,9 +40,7 @@ function qrotation(axis::StaticVector{3}, theta::Number) return Quaternion(s * u[1], s * u[2], s * u[3], cos(theta / 2)) end -function Base.broadcast(f, arg1::Quaternion, arg2::Quaternion) - Quaternion(f.(arg1.data, arg2.data)) -end +Base.broadcast(f, arg1::Quaternion, arg2::Quaternion) = Quaternion(f.(arg1.data, arg2.data)) Base.abs(q::Quaternion) = sqrt(sum(q.data .^ 2)) @@ -76,34 +72,32 @@ function Base.:(*)(quat::Quaternion{T}, vec::P) where {T, P <: StaticVector{3}} num12 = quat[4] * num3 return P( - (1f0 - (num5 + num6)) * vec[1] + (num7 - num12) * vec[2] + (num8 + num11) * vec[3], - (num7 + num12) * vec[1] + (1f0 - (num4 + num6)) * vec[2] + (num9 - num10) * vec[3], - (num8 - num11) * vec[1] + (num9 + num10) * vec[2] + (1f0 - (num4 + num5)) * vec[3] + (1.0f0 - (num5 + num6)) * vec[1] + (num7 - num12) * vec[2] + (num8 + num11) * vec[3], + (num7 + num12) * vec[1] + (1.0f0 - (num4 + num6)) * vec[2] + (num9 - num10) * vec[3], + (num8 - num11) * vec[1] + (num9 + num10) * vec[2] + (1.0f0 - (num4 + num5)) * vec[3] ) end Base.conj(q::Quaternion) = Quaternion(-q[1], -q[2], -q[3], q[4]) -function Base.:(*)(q::Quaternion, w::Quaternion) - return Quaternion( - q[4] * w[1] + q[1] * w[4] + q[2] * w[3] - q[3] * w[2], - q[4] * w[2] - q[1] * w[3] + q[2] * w[4] + q[3] * w[1], - q[4] * w[3] + q[1] * w[2] - q[2] * w[1] + q[3] * w[4], - q[4] * w[4] - q[1] * w[1] - q[2] * w[2] - q[3] * w[3], - ) -end +Base.:(*)(q::Quaternion, w::Quaternion) = Quaternion( + q[4] * w[1] + q[1] * w[4] + q[2] * w[3] - q[3] * w[2], + q[4] * w[2] - q[1] * w[3] + q[2] * w[4] + q[3] * w[1], + q[4] * w[3] + q[1] * w[2] - q[2] * w[1] + q[3] * w[4], + q[4] * w[4] - q[1] * w[1] - q[2] * w[2] - q[3] * w[3], +) 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 + 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 + 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 @@ -111,14 +105,14 @@ 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 + 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) + T1 - (yy + zz), xy + sz, xz - sy, + xy - sz, T1 - (xx + zz), yz + sx, + xz + sy, yz - sx, T1 - (xx + yy) ) end @@ -130,7 +124,7 @@ end function rotation_between(u::StaticVector{3, T}, v::StaticVector{3, T}) where T k_cos_theta = dot(u, v) - k = sqrt((norm(u) ^ 2) * (norm(v) ^ 2)) + k = sqrt((norm(u)^2) * (norm(v)^2)) if (k_cos_theta / k) ≈ T(-1) # 180 degree rotation around any orthogonal vector return Quaternion(normalize(orthogonal(u))..., T(0)) diff --git a/src/utilities/texture_atlas.jl b/src/utilities/texture_atlas.jl index 3730ab5c65f..ab9a8358817 100644 --- a/src/utilities/texture_atlas.jl +++ b/src/utilities/texture_atlas.jl @@ -46,19 +46,17 @@ 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) - return TextureAtlas( - RectanglePacker(Rect2{Int32}(0, 0, resolution, resolution)), - 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[], - pix_per_glyph, - glyph_padding, - downsample, - Function[] - ) -end +TextureAtlas(; resolution = 2048, pix_per_glyph = 64, glyph_padding = 12, downsample = 5) = TextureAtlas( + RectanglePacker(Rect2{Int32}(0, 0, resolution, resolution)), + 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[], + pix_per_glyph, + glyph_padding, + downsample, + Function[] +) function Base.show(io::IO, atlas::TextureAtlas) println(io, "TextureAtlas:") @@ -125,7 +123,7 @@ function read_array(io::IO, T) return array end -function store_texture_atlas(path::AbstractString, atlas::TextureAtlas) +store_texture_atlas(path::AbstractString, atlas::TextureAtlas) = open(path, "w") do io write_node(io, atlas.rectangle_packer) write_array(io, collect(atlas.mapping)) @@ -135,9 +133,8 @@ function store_texture_atlas(path::AbstractString, atlas::TextureAtlas) write(io, atlas.glyph_padding) write(io, atlas.downsample) end -end -function load_texture_atlas(path::AbstractString) +load_texture_atlas(path::AbstractString) = open(path) do io packer = read_node(io, Int32) mapping = read_array(io, Pair{UInt32, Int64}) @@ -148,15 +145,13 @@ function load_texture_atlas(path::AbstractString) downsample = read(io, Int32) return TextureAtlas(packer, Dict(mapping), data, uv_rectangles, pix_per_glyph, glyph_padding, downsample, Function[]) end -end 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 +get_texture_atlas(resolution::Int = 2048, pix_per_glyph::Int = 64) = + get!(TEXTURE_ATLASES, (resolution, pix_per_glyph)) do return cached_load(resolution, pix_per_glyph) # initialize only on demand end -end const CACHE_DOWNLOAD_URL = "https://github.com/MakieOrg/Makie.jl/releases/download/v0.19.0/" @@ -167,18 +162,18 @@ function cached_load(resolution::Int, pix_per_glyph::Int) url = CACHE_DOWNLOAD_URL * basename(path) Downloads.download(url, path) catch e - @warn "downloading texture atlas failed, need to re-create from scratch." exception=(e, Base.catch_backtrace()) + @warn "downloading texture atlas failed, need to re-create from scratch." exception = (e, Base.catch_backtrace()) end end if isfile(path) try return load_texture_atlas(path) catch e - @warn "reading texture atlas on disk failed, need to re-create from scratch." exception=(e, Base.catch_backtrace()) - rm(path; force=true) + @warn "reading texture atlas on disk failed, need to re-create from scratch." exception = (e, Base.catch_backtrace()) + rm(path; force = true) end end - atlas = TextureAtlas(; resolution=resolution, pix_per_glyph=pix_per_glyph) + atlas = TextureAtlas(; resolution = resolution, pix_per_glyph = pix_per_glyph) @warn("Makie is caching fonts, this may take a while. This should usually not happen, unless you're getting your own texture atlas or are without internet!") render_default_glyphs!(atlas) store_texture_atlas(path, atlas) # cache it @@ -229,8 +224,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 @@ -273,17 +268,11 @@ function glyph_index!(atlas::TextureAtlas, glyph, font::NativeFont) return insert_glyph!(atlas, glyph, font) end -function glyph_index!(atlas::TextureAtlas, b::BezierPath) - return insert_glyph!(atlas, b) -end +glyph_index!(atlas::TextureAtlas, b::BezierPath) = insert_glyph!(atlas, b) -function glyph_uv_width!(atlas::TextureAtlas, glyph, font::NativeFont) - return atlas.uv_rectangles[glyph_index!(atlas, glyph, font)] -end +glyph_uv_width!(atlas::TextureAtlas, glyph, font::NativeFont) = atlas.uv_rectangles[glyph_index!(atlas, glyph, font)] -function glyph_uv_width!(atlas::TextureAtlas, b::BezierPath) - return atlas.uv_rectangles[glyph_index!(atlas, b)] -end +glyph_uv_width!(atlas::TextureAtlas, b::BezierPath) = atlas.uv_rectangles[glyph_index!(atlas, b)] function insert_glyph!(atlas::TextureAtlas, glyph, font::NativeFont) glyphindex = FreeTypeAbstraction.glyph_index(font, glyph) @@ -291,13 +280,11 @@ function insert_glyph!(atlas::TextureAtlas, glyph, font::NativeFont) return insert_glyph!(atlas, hash, (glyphindex, font)) end -function insert_glyph!(atlas::TextureAtlas, path::BezierPath) - return insert_glyph!(atlas, StableHashTraits.stable_hash(path), path) -end +insert_glyph!(atlas::TextureAtlas, path::BezierPath) = insert_glyph!(atlas, StableHashTraits.stable_hash(path), path) -function insert_glyph!(atlas::TextureAtlas, hash::UInt32, path_or_glyp::Union{BezierPath, Tuple{UInt64, NativeFont}}) - return get!(atlas.mapping, hash) do +insert_glyph!(atlas::TextureAtlas, hash::UInt32, path_or_glyp::Union{BezierPath, Tuple{UInt64, NativeFont}}) = + get!(atlas.mapping, hash) do uv_pixel = render(atlas, path_or_glyp) tex_size = Vec2f(size(atlas)) # 0 based @@ -311,7 +298,6 @@ function insert_glyph!(atlas::TextureAtlas, hash::UInt32, path_or_glyp::Union{Be push!(atlas.uv_rectangles, uv_offset_rect) return length(atlas.uv_rectangles) end -end """ sdistancefield(img, downsample, pad) @@ -336,20 +322,16 @@ 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! return Float32.(sdf(in_or_out, xres, yres) ./ downsample) end -function font_render_callback!(f, atlas::TextureAtlas) - push!(atlas.font_render_callback, f) -end +font_render_callback!(f, atlas::TextureAtlas) = push!(atlas.font_render_callback, f) -function remove_font_render_callback!(atlas::TextureAtlas, f) - filter!(f2-> f2 != f, atlas.font_render_callback) -end +remove_font_render_callback!(atlas::TextureAtlas, f) = filter!(f2 -> f2 != f, atlas.font_render_callback) function render(atlas::TextureAtlas, (glyph_index, font)::Tuple{UInt64, NativeFont}) downsample = atlas.downsample @@ -431,28 +413,25 @@ function marker_to_sdf_shape(arr::AbstractVector) return shape1 end -function marker_to_sdf_shape(marker::Observable) - return lift(marker; ignore_equal_values=true) do marker +marker_to_sdf_shape(marker::Observable) = + lift(marker; ignore_equal_values = true) do marker return Cint(marker_to_sdf_shape(to_spritemarker(marker))) end -end """ Extracts the offset from a primitive. """ primitive_offset(x, scale::Nothing) = Vec2f(0) # default offset -primitive_offset(x, scale) = scale ./ -2f0 # default offset +primitive_offset(x, scale) = scale ./ -2.0f0 # 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) -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) -end +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, marker::Observable, font::Observable) = lift((m, f) -> primitive_uv_offset_width(atlas, m, f), marker, font; ignore_equal_values = true) _bcast(x::Vec) = (x,) _bcast(x) = x @@ -473,30 +452,24 @@ function bezierpath_pad_scale_factor(atlas::TextureAtlas, bp) uv_width = Vec(lbrt[3] - lbrt[1], lbrt[4] - lbrt[2]) full_pixel_size_in_atlas = uv_width * Vec2f(size(atlas)) # left + right pad - cutoff from pixel centering - full_pad = 2f0 * atlas.glyph_padding - 1 + full_pad = 2.0f0 * atlas.glyph_padding - 1 return full_pad ./ (full_pixel_size_in_atlas .- full_pad) end function marker_scale_factor(atlas::TextureAtlas, path::BezierPath) # padded_width = (unpadded_target_width + unpadded_target_width * pad_per_unit) path_width = widths(Makie.bbox(path)) - return (1f0 .+ bezierpath_pad_scale_factor(atlas, path)) .* path_width + return (1.0f0 .+ bezierpath_pad_scale_factor(atlas, path)) .* path_width end -function rescale_marker(atlas::TextureAtlas, pathmarker::BezierPath, font, markersize) - return markersize .* marker_scale_factor(atlas, pathmarker) -end +rescale_marker(atlas::TextureAtlas, pathmarker::BezierPath, font, markersize) = markersize .* marker_scale_factor(atlas, pathmarker) -function rescale_marker(atlas::TextureAtlas, pathmarker::AbstractVector{T}, font, markersize) where T <: BezierPath - return _bcast(markersize) .* marker_scale_factor.(Ref(atlas), pathmarker) -end +rescale_marker(atlas::TextureAtlas, pathmarker::AbstractVector{T}, font, markersize) where T <: BezierPath = _bcast(markersize) .* marker_scale_factor.(Ref(atlas), pathmarker) # Rect / Circle dont need no rescaling rescale_marker(atlas, char, font, markersize) = markersize -function rescale_marker(atlas::TextureAtlas, char::AbstractVector{Char}, font, markersize) - return _bcast(markersize) .* marker_scale_factor.(Ref(atlas), char, font) -end +rescale_marker(atlas::TextureAtlas, char::AbstractVector{Char}, font, markersize) = _bcast(markersize) .* marker_scale_factor.(Ref(atlas), char, font) function rescale_marker(atlas::TextureAtlas, char::Char, font, markersize) factor = marker_scale_factor.(Ref(atlas), char, font) @@ -509,24 +482,18 @@ function offset_bezierpath(atlas::TextureAtlas, bp::BezierPath, markersize::Vec2 return markersize .* pad_offset end -function offset_bezierpath(atlas::TextureAtlas, bp, scale, offset) - return offset_bezierpath.(Ref(atlas), bp, _bcast(scale), _bcast(offset)) -end +offset_bezierpath(atlas::TextureAtlas, bp, scale, offset) = offset_bezierpath.(Ref(atlas), bp, _bcast(scale), _bcast(offset)) -function offset_marker(atlas::TextureAtlas, marker::Union{T, AbstractVector{T}}, font, markersize, markeroffset) where T <: BezierPath - return offset_bezierpath(atlas, marker, markersize, markeroffset) -end +offset_marker(atlas::TextureAtlas, marker::Union{T, AbstractVector{T}}, font, markersize, markeroffset) where T <: BezierPath = offset_bezierpath(atlas, marker, markersize, markeroffset) -function offset_marker(atlas::TextureAtlas, marker::Union{T, AbstractVector{T}}, font, markersize, markeroffset) where T <: Char - return rescale_marker(atlas, marker, font, markeroffset) -end +offset_marker(atlas::TextureAtlas, marker::Union{T, AbstractVector{T}}, font, markersize, markeroffset) where T <: Char = rescale_marker(atlas, marker, font, markeroffset) offset_marker(atlas, marker, font, markersize, markeroffset) = markeroffset function marker_attributes(atlas::TextureAtlas, marker, markersize, font, marker_offset) atlas_obs = Observable(atlas) # for map to work - scale = map(rescale_marker, atlas_obs, marker, font, markersize; ignore_equal_values=true) - quad_offset = map(offset_marker, atlas_obs, marker, font, markersize, marker_offset; ignore_equal_values=true) + scale = map(rescale_marker, atlas_obs, marker, font, markersize; ignore_equal_values = true) + quad_offset = map(offset_marker, atlas_obs, marker, font, markersize, marker_offset; ignore_equal_values = true) return scale, quad_offset end diff --git a/src/utilities/utilities.jl b/src/utilities/utilities.jl index d2a92459a3a..db3fe9418ae 100644 --- a/src/utilities/utilities.jl +++ b/src/utilities/utilities.jl @@ -1,8 +1,6 @@ -function to_image(image::AbstractMatrix{<: AbstractFloat}, colormap::AbstractVector{<: Colorant}, colorrange) - return interpolated_getindex.((to_value(colormap),), image, (to_value(colorrange),)) -end +to_image(image::AbstractMatrix{<:AbstractFloat}, colormap::AbstractVector{<:Colorant}, colorrange) = interpolated_getindex.((to_value(colormap),), image, (to_value(colorrange),)) """ resample(A::AbstractVector, len::Integer) @@ -10,7 +8,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,9 +19,9 @@ 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) + r = range(0.0, stop = 1.0, length = ncolors) if alpha isa Tuple{<:Number, <:Number} alphas = LinRange(alpha..., ncolors) else @@ -31,7 +29,7 @@ function resample_cmap(cmap, ncolors::Integer; alpha=1.0) 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 @@ -41,14 +39,12 @@ end Resample the color attribute from `attributes`. Resamples `:colormap` if present, or repeats `:color`. """ -function resampled_colors(attributes, levels::Integer) - cols = if haskey(attributes, :color) - c = get_attribute(attributes, :color) - c isa AbstractVector ? resample(c, levels) : repeated(c, levels) - else - c = get_attribute(attributes, :colormap) - resample(c, levels) - end +resampled_colors(attributes, levels::Integer) = cols = if haskey(attributes, :color) + c = get_attribute(attributes, :color) + c isa AbstractVector ? resample(c, levels) : repeated(c, levels) +else + c = get_attribute(attributes, :colormap) + resample(c, levels) end @@ -78,8 +74,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 @@ -133,7 +129,7 @@ macro get_attribute(scene, args) extract_expr(get_attribute, scene, args) end -@inline getindex_value(x::Union{Dict,Attributes,AbstractPlot}, key::Symbol) = to_value(x[key]) +@inline getindex_value(x::Union{Dict, Attributes, AbstractPlot}, key::Symbol) = to_value(x[key]) @inline getindex_value(x, key::Symbol) = to_value(getfield(x, key)) """ @@ -211,11 +207,9 @@ end Creates the type `T` from the fields in dict. Automatically converts to the correct types. """ -function from_dict(::Type{T}, dict) where T - T(map(fieldnames(T)) do name - convert(fieldtype(T, name), dict[name]) - end...) -end +from_dict(::Type{T}, dict) where T = T(map(fieldnames(T)) do name + convert(fieldtype(T, name), dict[name]) +end...) same_length_array(array, value::NativeFont) = repeated(value, length(array)) same_length_array(array, value) = repeated(value, length(array)) @@ -227,18 +221,14 @@ 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} - T(ntuple(Val(N)) do i - i > N2 && return ET(fillval) - @inbounds return vec[i] - end) -end +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] +end) lerp(a::T, b::T, val::AbstractFloat) where {T} = (a .+ (val * (b .- a))) -function merged_get!(defaults::Function, key, scene, input::Vector{Any}) - return merged_get!(defaults, key, scene, Attributes(input)) -end +merged_get!(defaults::Function, key, scene, input::Vector{Any}) = merged_get!(defaults, key, scene, Attributes(input)) function merged_get!(defaults::Function, key, scene::SceneLike, input::Attributes) d = defaults() @@ -251,16 +241,15 @@ function merged_get!(defaults::Function, key, scene::SceneLike, input::Attribute end to_vector(x::AbstractVector, len, T) = convert(Vector{T}, x) -function to_vector(x::AbstractArray, len, T) +to_vector(x::AbstractArray, len, T) = if length(x) in size(x) # assert that just one dim != 1 to_vector(vec(x), len, T) else error("Can't convert to a Vector. Please supply a range/vector/interval") end -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 """ @@ -272,12 +261,10 @@ x[0.5] # returns color at half point of colormap """ struct ColorSampler{Data <: AbstractArray} colormap::Data - color_range::Tuple{Float64,Float64} + color_range::Tuple{Float64, Float64} end -function Base.getindex(cs::ColorSampler, value::Number) - return interpolated_getindex(cs.colormap, value, cs.color_range) -end +Base.getindex(cs::ColorSampler, value::Number) = interpolated_getindex(cs.colormap, value, cs.color_range) # This function was copied from GR.jl, @@ -287,10 +274,10 @@ end Return a nonlinear function on a grid. Useful for test cases. """ -function peaks(n=49) +function peaks(n = 49) x = LinRange(-3, 3, n) y = LinRange(-3, 3, n) - 3 * (1 .- x').^2 .* exp.(-(x'.^2) .- (y .+ 1).^2) .- 10 * (x' / 5 .- x'.^3 .- y.^5) .* exp.(-x'.^2 .- y.^2) .- 1 / 3 * exp.(-(x' .+ 1).^2 .- y.^2) + 3 * (1 .- x') .^ 2 .* exp.(-(x' .^ 2) .- (y .+ 1) .^ 2) .- 10 * (x' / 5 .- x' .^ 3 .- y .^ 5) .* exp.(-x' .^ 2 .- y .^ 2) .- 1 / 3 * exp.(-(x' .+ 1) .^ 2 .- y .^ 2) end @@ -316,7 +303,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 @@ -334,9 +321,7 @@ function matrix_grid(f, x::AbstractArray, y::AbstractArray, z::AbstractMatrix) return vec(g) end -function matrix_grid(f, x::ClosedInterval, y::ClosedInterval, z::AbstractMatrix) - matrix_grid(f, LinRange(extrema(x)..., size(z, 1)), LinRange(extrema(x)..., size(z, 2)), z) -end +matrix_grid(f, x::ClosedInterval, y::ClosedInterval, z::AbstractMatrix) = matrix_grid(f, LinRange(extrema(x)..., size(z, 1)), LinRange(extrema(x)..., size(z, 2)), z) function extract_keys(attributes, keys) attr = Attributes() diff --git a/test/boundingboxes.jl b/test/boundingboxes.jl index 266548725d8..ac3bfd2e1d6 100644 --- a/test/boundingboxes.jl +++ b/test/boundingboxes.jl @@ -8,7 +8,7 @@ @test bb.origin ≈ Point3f(-0.1678, -0.002068, -0.358661) @test bb.widths ≈ Vec3f(0.339423, 0.92186, 1.3318559) - fig, ax, p = surface([x*y for x in 1:10, y in 1:10]) + fig, ax, p = surface([x * y for x in 1:10, y in 1:10]) bb = boundingbox(p) @test bb.origin ≈ Point3f(0.0, 0.0, 1.0) @test bb.widths ≈ Vec3f(10.0, 10.0, 99.0) @@ -42,7 +42,7 @@ bb = boundingbox(p) @test bb.origin ≈ Point3f(0.5, 0.5, 0) @test bb.widths ≈ Vec3f(10.0, 10.0, 0) - + fig, ax, p = image(rand(10, 10)) bb = boundingbox(p) @test bb.origin ≈ Point3f(0) @@ -55,4 +55,4 @@ bb = boundingbox(p) @test bb.origin ≈ Point3f(340, 341, 0) @test bb.widths ≈ Vec3f(32.24, 23.3, 0) -end \ No newline at end of file +end diff --git a/test/conversions.jl b/test/conversions.jl index 8c01def1a27..78f1c9f64bc 100644 --- a/test/conversions.jl +++ b/test/conversions.jl @@ -13,72 +13,73 @@ using Makie: let nctt = NoConversionTestType(), ncttt = conversion_trait(nctt) + @test convert_arguments(ncttt, 1, 2, 3) == (1, 2, 3) end end @testset "changing input types" begin - input = Observable{Any}(decompose(Point2f, Circle(Point2f(0), 2f0))) + input = Observable{Any}(decompose(Point2f, Circle(Point2f(0), 2.0f0))) f, ax, pl = mesh(input) - m = Makie.triangle_mesh(Circle(Point2f(0), 1f0)) + m = Makie.triangle_mesh(Circle(Point2f(0), 1.0f0)) input[] = m @test pl[1][] == m end @testset "to_vertices" begin - X1 = [Point(rand(3)...) for i = 1:10] + X1 = [Point(rand(3)...) for i in 1:10] V1 = to_vertices(X1) @test Float32(X1[7][1]) == V1[7][1] - X2 = [tuple(rand(3)...) for i = 1:10] + X2 = [tuple(rand(3)...) for i in 1:10] V2 = to_vertices(X2) @test Float32(X2[7][1]) == V2[7][1] - X4 = rand(2,10) + X4 = rand(2, 10) V4 = to_vertices(X4) - @test Float32(X4[1,7]) == V4[7][1] + @test Float32(X4[1, 7]) == V4[7][1] @test V4[7][3] == 0 - X5 = rand(3,10) + X5 = rand(3, 10) V5 = to_vertices(X5) - @test Float32(X5[1,7]) == V5[7][1] + @test Float32(X5[1, 7]) == V5[7][1] - X6 = rand(10,2) + X6 = rand(10, 2) V6 = to_vertices(X6) - @test Float32(X6[7,1]) == V6[7][1] + @test Float32(X6[7, 1]) == V6[7][1] @test V6[7][3] == 0 - X7 = rand(10,3) + X7 = rand(10, 3) V7 = to_vertices(X7) - @test Float32(X7[7,1]) == V7[7][1] + @test Float32(X7[7, 1]) == V7[7][1] end @testset "functions" begin - x = -pi..pi + x = -pi .. pi s = convert_arguments(Lines, x, sin) xy = s.args[1] @test xy[1][1] ≈ -pi @test xy[end][1] ≈ pi for (val, fval) in xy - @test fval ≈ sin(val) atol=1f-6 + @test fval ≈ sin(val) atol = 1.0f-6 end - x = range(-pi, stop=pi, length=100) + x = range(-pi, stop = pi, length = 100) s = convert_arguments(Lines, x, sin) xy = s.args[1] @test xy[1][1] ≈ -pi @test xy[end][1] ≈ pi for (val, fval) in xy - @test fval ≈ sin(val) atol=1f-6 + @test fval ≈ sin(val) atol = 1.0f-6 end - pts = [Point(1, 2), Point(4,5), Point(10, 8), Point(1, 2)] - ls=LineString(pts) + pts = [Point(1, 2), Point(4, 5), Point(10, 8), Point(1, 2)] + ls = LineString(pts) p = convert_arguments(Makie.PointBased(), ls) @test p[1] == pts - pts1 = [Point(5, 2), Point(4,8), Point(2, 8), Point(5, 2)] + pts1 = [Point(5, 2), Point(4, 8), Point(2, 8), Point(5, 2)] ls1 = LineString(pts1) lsa = [ls, ls1] p1 = convert_arguments(Makie.PointBased(), lsa) @@ -92,7 +93,7 @@ end pol_e = Polygon(ls) p3_e = convert_arguments(Makie.PointBased(), pol_e) - @test p3_e[1][1:end-1] == pts # for poly we repeat last point + @test p3_e[1][1:(end - 1)] == pts # for poly we repeat last point pol = Polygon(ls, [ls1]) p3 = convert_arguments(Makie.PointBased(), pol) @@ -100,8 +101,8 @@ end @test p3[1][7:10] == pts1 pts2 = Point{2, Int}[(5, 1), (3, 3), (4, 8), (1, 2), (5, 1)] - pts3 = Point{2, Int}[(2, 2), (2, 3),(3, 4), (2, 2)] - pts4 = Point{2, Int}[(2, 2), (3, 8),(5, 6), (3, 4), (2, 2)] + pts3 = Point{2, Int}[(2, 2), (2, 3), (3, 4), (2, 2)] + pts4 = Point{2, Int}[(2, 2), (3, 8), (5, 6), (3, 4), (2, 2)] ls2 = LineString(pts2) ls3 = LineString(pts3) ls4 = LineString(pts4) @@ -126,23 +127,23 @@ using Makie: check_line_pattern, line_diff_pattern # for readability, the length of dash and dot dash, dot = 3.0, 1.0 - @test line_diff_pattern(:dash) == - line_diff_pattern("-", :normal) == [dash, 3.0] - @test line_diff_pattern(:dot) == - line_diff_pattern(".", :normal) == [dot, 2.0] - @test line_diff_pattern(:dashdot) == - line_diff_pattern("-.", :normal) == [dash, 3.0, dot, 3.0] - @test line_diff_pattern(:dashdotdot) == - line_diff_pattern("-..", :normal) == [dash, 3.0, dot, 2.0, dot, 3.0] - - @test line_diff_pattern(:dash, :loose) == [dash, 6.0] - @test line_diff_pattern(:dot, :loose) == [dot, 4.0] - @test line_diff_pattern("-", :dense) == [dash, 2.0] - @test line_diff_pattern(".", :dense) == [dot, 1.0] - @test line_diff_pattern(:dash, 0.5) == [dash, 0.5] - @test line_diff_pattern(:dot, 0.5) == [dot, 0.5] - @test line_diff_pattern("-", (0.4, 0.6)) == [dash, 0.6] - @test line_diff_pattern(:dot, (0.4, 0.6)) == [dot, 0.4] + @test line_diff_pattern(:dash) == + line_diff_pattern("-", :normal) == [dash, 3.0] + @test line_diff_pattern(:dot) == + line_diff_pattern(".", :normal) == [dot, 2.0] + @test line_diff_pattern(:dashdot) == + line_diff_pattern("-.", :normal) == [dash, 3.0, dot, 3.0] + @test line_diff_pattern(:dashdotdot) == + line_diff_pattern("-..", :normal) == [dash, 3.0, dot, 2.0, dot, 3.0] + + @test line_diff_pattern(:dash, :loose) == [dash, 6.0] + @test line_diff_pattern(:dot, :loose) == [dot, 4.0] + @test line_diff_pattern("-", :dense) == [dash, 2.0] + @test line_diff_pattern(".", :dense) == [dot, 1.0] + @test line_diff_pattern(:dash, 0.5) == [dash, 0.5] + @test line_diff_pattern(:dot, 0.5) == [dot, 0.5] + @test line_diff_pattern("-", (0.4, 0.6)) == [dash, 0.6] + @test line_diff_pattern(:dot, (0.4, 0.6)) == [dot, 0.4] @test line_diff_pattern("-..", (0.4, 0.6)) == [dash, 0.6, dot, 0.4, dot, 0.6] # gaps must be Symbol, a number, or two numbers @@ -195,15 +196,15 @@ end end @testset "resample colormap" begin - cs = Makie.resample_cmap(:viridis, 10; alpha=LinRange(0, 1, 10)) + cs = Makie.resample_cmap(:viridis, 10; alpha = LinRange(0, 1, 10)) @test Colors.alpha.(cs) == Float32.(LinRange(0, 1, 10)) - cs = Makie.resample_cmap(:viridis, 2; alpha=0.5) - @test all(x-> x == 0.5, Colors.alpha.(cs)) + cs = Makie.resample_cmap(:viridis, 2; alpha = 0.5) + @test all(x -> x == 0.5, Colors.alpha.(cs)) @test Colors.color.(cs) == Colors.color.(Makie.resample(to_colormap(:viridis), 2)) cs = Makie.resample_cmap(:Set1, 100) - @test all(x-> x == 1.0, Colors.alpha.(cs)) + @test all(x -> x == 1.0, Colors.alpha.(cs)) @test Colors.color.(cs) == Colors.color.(Makie.resample(to_colormap(:Set1), 100)) - cs = Makie.resample_cmap(:Set1, 10; alpha=(0, 1)) + cs = Makie.resample_cmap(:Set1, 10; alpha = (0, 1)) @test Colors.alpha.(cs) == Float32.(LinRange(0, 1, 10)) end @@ -237,11 +238,11 @@ end @test to_colormap((:viridis, 0.1)) isa Vector{RGBAf} @test to_colormap(Reverse(:viridis)) isa Vector{RGBAf} @test to_colormap(:cividis) isa Vector{RGBAf} - @test to_colormap(cgrad(:cividis, 8, categorical=true)) isa Vector{RGBAf} + @test to_colormap(cgrad(:cividis, 8, categorical = true)) isa Vector{RGBAf} @test to_colormap(cgrad(:cividis, 8)) isa Vector{RGBAf} @test to_colormap(cgrad(:cividis)) isa Vector{RGBAf} - @test alpha(to_colormap(cgrad(:cividis, 8; alpha=0.5))[1]) == 0.5 - @test alpha(to_colormap(cgrad(:cividis, 8; alpha=0.5, categorical=true))[1]) == 0.5 + @test alpha(to_colormap(cgrad(:cividis, 8; alpha = 0.5))[1]) == 0.5 + @test alpha(to_colormap(cgrad(:cividis, 8; alpha = 0.5, categorical = true))[1]) == 0.5 @inferred to_colormap([HSL(0, 10, 20)]) @@ -250,21 +251,21 @@ end @inferred to_colormap((:viridis, 0.1)) @inferred to_colormap(Reverse(:viridis)) @inferred to_colormap(:cividis) - @inferred to_colormap(cgrad(:cividis, 8, categorical=true)) + @inferred to_colormap(cgrad(:cividis, 8, categorical = true)) @inferred to_colormap(cgrad(:cividis, 8)) @inferred to_colormap(cgrad(:cividis)) - @inferred to_colormap(cgrad(:cividis, 8; alpha=0.5)) - @inferred to_colormap(cgrad(:cividis, 8; alpha=0.5, categorical=true)) + @inferred to_colormap(cgrad(:cividis, 8; alpha = 0.5)) + @inferred to_colormap(cgrad(:cividis, 8; alpha = 0.5, categorical = true)) end @testset "empty poly" begin - f, ax, pl = poly(Rect2f[]); - pl[1] = [Rect2f(0, 0, 1, 1)]; + f, ax, pl = poly(Rect2f[]) + pl[1] = [Rect2f(0, 0, 1, 1)] @test pl.plots[1][1][] == [GeometryBasics.triangle_mesh(Rect2f(0, 0, 1, 1))] f, ax, pl = poly(Vector{Point2f}[]) - points = decompose(Point2f, Circle(Point2f(0),1)) + points = decompose(Point2f, Circle(Point2f(0), 1)) pl[1] = [points] @test pl.plots[1][1][] == Makie.poly_convert(points) end diff --git a/test/events.jl b/test/events.jl index 31b2b484eb8..cfe01aa32a6 100644 --- a/test/events.jl +++ b/test/events.jl @@ -50,9 +50,9 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right @test !ispressed(events, Mouse.right) # Collections - @test ispressed(events, (Keyboard.a, )) - @test ispressed(events, [Keyboard.a, ]) - @test ispressed(events, Set((Keyboard.a, ))) + @test ispressed(events, (Keyboard.a,)) + @test ispressed(events, [Keyboard.a,]) + @test ispressed(events, Set((Keyboard.a,))) @test !ispressed(events, (Keyboard.a, Keyboard.b)) @test !ispressed(events, [Keyboard.a, Keyboard.b]) @@ -135,8 +135,8 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right clipboard() = CLIP[] end @testset "copy_paste" begin - f = Figure(resolution=(640,480)) - tb = Textbox(f[1,1], placeholder="Copy/paste into me") + f = Figure(resolution = (640, 480)) + tb = Textbox(f[1, 1], placeholder = "Copy/paste into me") e = events(f.scene) # Initial state @@ -166,8 +166,8 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right # Refresh figure to test right control + v combination empty!(f) - f = Figure(resolution=(640,480)) - tb = Textbox(f[1,1], placeholder="Copy/paste into me") + f = Figure(resolution = (640, 480)) + tb = Textbox(f[1, 1], placeholder = "Copy/paste into me") e = events(f.scene) # Initial state @@ -196,109 +196,112 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right # This testset is based on the results the current camera system has. If # cam3d! is updated this is likely to break. @testset "cam3d!" begin - scene = Scene(resolution=(800, 600)); + scene = Scene(resolution = (800, 600)) e = events(scene) - cam3d!(scene, fixed_axis=true, cad=false, zoom_shift_lookat=false) + cam3d!(scene, fixed_axis = true, cad = false, zoom_shift_lookat = false) cc = cameracontrols(scene) # Verify initial camera state - @test cc.lookat[] == Vec3f(0) - @test cc.eyeposition[] == Vec3f(3) - @test cc.upvector[] == Vec3f(0, 0, 1) + @test cc.lookat[] == Vec3f(0) + @test cc.eyeposition[] == Vec3f(3) + @test cc.upvector[] == Vec3f(0, 0, 1) # Rotation # 1) In scene, in drag e.mouseposition[] = (400, 250) e.mousebutton[] = MouseButtonEvent(Mouse.left, Mouse.press) e.mouseposition[] = (600, 250) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ Vec3f(4.14532, -0.9035063, 3.0) - @test cc.upvector[] ≈ Vec3f(0, 0, 1) + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(4.14532, -0.9035063, 3.0) + @test cc.upvector[] ≈ Vec3f(0, 0, 1) # 2) Outside scene, in drag e.mouseposition[] = (1000, 450) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ Vec3f(-2.8912058, -3.8524969, -1.9491522) - @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(-2.8912058, -3.8524969, -1.9491522) + @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) # 3) not in drag e.mousebutton[] = MouseButtonEvent(Mouse.left, Mouse.release) e.mouseposition[] = (400, 250) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ Vec3f(-2.8912058, -3.8524969, -1.9491522) - @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(-2.8912058, -3.8524969, -1.9491522) + @test cc.upvector[] ≈ Vec3f(-0.5050875, -0.6730229, 0.5403024) # Reset state so this is indepentent from the last checks - scene = Scene(resolution=(800, 600)); + scene = Scene(resolution = (800, 600)) e = events(scene) - cam3d!(scene, fixed_axis=true, cad=false, zoom_shift_lookat=false) + cam3d!(scene, fixed_axis = true, cad = false, zoom_shift_lookat = false) cc = cameracontrols(scene) # Verify initial camera state - @test cc.lookat[] == Vec3f(0) - @test cc.eyeposition[] == Vec3f(3) - @test cc.upvector[] == Vec3f(0, 0, 1) + @test cc.lookat[] == Vec3f(0) + @test cc.eyeposition[] == Vec3f(3) + @test cc.upvector[] == Vec3f(0, 0, 1) # translation # 1) In scene, in drag e.mousebutton[] = MouseButtonEvent(Mouse.right, Mouse.press) e.mouseposition[] = (600, 250) - @test cc.lookat[] ≈ Vec3f(5.4697413, -3.3484206, -2.1213205) - @test cc.eyeposition[] ≈ Vec3f(8.469742, -0.34842062, 0.8786795) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(5.4697413, -3.3484206, -2.1213205) + @test cc.eyeposition[] ≈ Vec3f(8.469742, -0.34842062, 0.8786795) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) # 2) Outside scene, in drag e.mouseposition[] = (1000, 450) - @test cc.lookat[] ≈ Vec3f(9.257657, -5.4392805, -3.818377) - @test cc.eyeposition[] ≈ Vec3f(12.257658, -2.4392805, -0.81837714) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(9.257657, -5.4392805, -3.818377) + @test cc.eyeposition[] ≈ Vec3f(12.257658, -2.4392805, -0.81837714) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) # 3) not in drag e.mousebutton[] = MouseButtonEvent(Mouse.right, Mouse.release) e.mouseposition[] = (400, 250) - @test cc.lookat[] ≈ Vec3f(9.257657, -5.4392805, -3.818377) - @test cc.eyeposition[] ≈ Vec3f(12.257658, -2.4392805, -0.81837714) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.lookat[] ≈ Vec3f(9.257657, -5.4392805, -3.818377) + @test cc.eyeposition[] ≈ Vec3f(12.257658, -2.4392805, -0.81837714) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) # Reset state - scene = Scene(resolution=(800, 600)); + scene = Scene(resolution = (800, 600)) e = events(scene) - cam3d!(scene, fixed_axis=true, cad=false, zoom_shift_lookat=false) + cam3d!(scene, fixed_axis = true, cad = false, zoom_shift_lookat = false) cc = cameracontrols(scene) # Verify initial camera state - @test cc.lookat[] == Vec3f(0) - @test cc.eyeposition[] == Vec3f(3) - @test cc.upvector[] == Vec3f(0, 0, 1) - @test cc.zoom_mult[] == 1f0 + @test cc.lookat[] == Vec3f(0) + @test cc.eyeposition[] == Vec3f(3) + @test cc.upvector[] == Vec3f(0, 0, 1) + @test cc.zoom_mult[] == 1.0f0 # Zoom e.scroll[] = (0.0, 4.0) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ Vec3f(3) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) - @test cc.zoom_mult[] ≈ 0.6830134f0 + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(3) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.zoom_mult[] ≈ 0.6830134f0 # should not work outside the scene e.mouseposition[] = (1000, 450) e.scroll[] = (0.0, 4.0) - @test cc.lookat[] ≈ Vec3f(0) - @test cc.eyeposition[] ≈ Vec3f(3) - @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) - @test cc.zoom_mult[] ≈ 0.6830134f0 + @test cc.lookat[] ≈ Vec3f(0) + @test cc.eyeposition[] ≈ Vec3f(3) + @test cc.upvector[] ≈ Vec3f(0.0, 0.0, 1.0) + @test cc.zoom_mult[] ≈ 0.6830134f0 end @testset "mouse state machine" begin - scene = Scene(resolution=(800, 600)); + scene = Scene(resolution = (800, 600)) e = events(scene) bbox = Observable(Rect2(200, 200, 400, 300)) - msm = addmouseevents!(scene, bbox, priority=typemax(Int)) + msm = addmouseevents!(scene, bbox, priority = typemax(Int)) eventlog = MouseEvent[] - on(x -> begin push!(eventlog, x); false end, msm.obs) + on(x -> begin + push!(eventlog, x) + false + end, msm.obs) e.mouseposition[] = (0, 200) @test isempty(eventlog) @@ -325,10 +328,10 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right e.mousebutton[] = MouseButtonEvent(getfield(Mouse, button), Mouse.release) @test length(eventlog) == 3 for (i, t) in enumerate(( - getfield(MouseEventTypes, Symbol(button, :down)), - getfield(MouseEventTypes, Symbol(button, :click)), - getfield(MouseEventTypes, Symbol(button, :up)) - )) + getfield(MouseEventTypes, Symbol(button, :down)), + getfield(MouseEventTypes, Symbol(button, :click)), + getfield(MouseEventTypes, Symbol(button, :up)) + )) @test eventlog[i].type == t @test eventlog[i].px == Point2f(300, 300) @test eventlog[i].prev_px == Point2f(300, 300) @@ -340,10 +343,10 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right e.mousebutton[] = MouseButtonEvent(getfield(Mouse, button), Mouse.release) @test length(eventlog) == 3 for (i, t) in enumerate(( - getfield(MouseEventTypes, Symbol(button, :down)), - getfield(MouseEventTypes, Symbol(button, :doubleclick)), - getfield(MouseEventTypes, Symbol(button, :up)) - )) + getfield(MouseEventTypes, Symbol(button, :down)), + getfield(MouseEventTypes, Symbol(button, :doubleclick)), + getfield(MouseEventTypes, Symbol(button, :up)) + )) @test eventlog[i].type == t @test eventlog[i].px == Point2f(300, 300) @test eventlog[i].prev_px == Point2f(300, 300) @@ -355,10 +358,10 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right e.mousebutton[] = MouseButtonEvent(getfield(Mouse, button), Mouse.release) @test length(eventlog) == 3 for (i, t) in enumerate(( - getfield(MouseEventTypes, Symbol(button, :down)), - getfield(MouseEventTypes, Symbol(button, :click)), - getfield(MouseEventTypes, Symbol(button, :up)) - )) + getfield(MouseEventTypes, Symbol(button, :down)), + getfield(MouseEventTypes, Symbol(button, :click)), + getfield(MouseEventTypes, Symbol(button, :up)) + )) @test eventlog[i].type == t @test eventlog[i].px == Point2f(300, 300) @test eventlog[i].prev_px == Point2f(300, 300) @@ -372,16 +375,16 @@ Base.:(==)(l::Or, r::Or) = l.left == r.left && l.right == r.right e.mousebutton[] = MouseButtonEvent(getfield(Mouse, button), Mouse.release) @test length(eventlog) == 6 prev_px = Point2f[(300, 300), (300, 300), (300, 300), (500, 300), (700, 200), (700, 200)] - px = Point2f[(300, 300), (500, 300), (500, 300), (700, 200), (700, 200), (700, 200)] + px = Point2f[(300, 300), (500, 300), (500, 300), (700, 200), (700, 200), (700, 200)] for (i, t) in enumerate(( - getfield(MouseEventTypes, Symbol(button, :down)), - getfield(MouseEventTypes, Symbol(button, :dragstart)), - getfield(MouseEventTypes, Symbol(button, :drag)), - getfield(MouseEventTypes, Symbol(button, :drag)), - getfield(MouseEventTypes, Symbol(button, :dragstop)), - getfield(MouseEventTypes, :out), - # TODO this is kinda missing an "up outside" - )) + getfield(MouseEventTypes, Symbol(button, :down)), + getfield(MouseEventTypes, Symbol(button, :dragstart)), + getfield(MouseEventTypes, Symbol(button, :drag)), + getfield(MouseEventTypes, Symbol(button, :drag)), + getfield(MouseEventTypes, Symbol(button, :dragstop)), + getfield(MouseEventTypes, :out), + # TODO this is kinda missing an "up outside" + )) @test eventlog[i].type == t @test eventlog[i].px == px[i] @test eventlog[i].prev_px == prev_px[i] diff --git a/test/figures.jl b/test/figures.jl index 4d844d115af..813e590d1bc 100644 --- a/test/figures.jl +++ b/test/figures.jl @@ -158,7 +158,7 @@ end @test_throws ArgumentError lines(1:10, axis = (aspect = DataAspect()), figure = (resolution = (100, 100))) @test_throws ArgumentError lines(1:10, figure = (resolution = (100, 100))) @test_throws ArgumentError lines(1:10, axis = (aspect = DataAspect())) - + # these just shouldn't error lines(1:10, axis = (aspect = DataAspect(),)) lines(1:10, axis = Attributes(aspect = DataAspect())) @@ -167,4 +167,4 @@ end f = Figure() @test_throws ArgumentError lines(f[1, 1], 1:10, axis = (aspect = DataAspect())) @test_throws ArgumentError lines(f[1, 1][2, 2], 1:10, axis = (aspect = DataAspect())) -end \ No newline at end of file +end diff --git a/test/liftmacro.jl b/test/liftmacro.jl index 195febf5cd2..f184c887ec2 100644 --- a/test/liftmacro.jl +++ b/test/liftmacro.jl @@ -2,7 +2,7 @@ x = Observable(1.0) y = Observable(2.0) z = (x = x, y = y) - + t1 = @lift($x + $y) @test t1[] == 3.0 t2 = @lift($(z.x) - $(z.y)) diff --git a/test/makielayout.jl b/test/makielayout.jl index 92008f2bc0c..cd103618e76 100644 --- a/test/makielayout.jl +++ b/test/makielayout.jl @@ -12,7 +12,7 @@ to = gl2[1, 4] = Toggle(fig) te = fig[0, :] = Label(fig, "A super title") - me = fig[end + 1, :] = Menu(fig, options=["one", "two", "three"]) + me = fig[end + 1, :] = Menu(fig, options = ["one", "two", "three"]) tb = fig[end + 1, :] = Textbox(fig) is = fig[end + 1, :] = IntervalSlider(fig) @test true @@ -42,8 +42,8 @@ end _, hm = heatmap(fig[1, 1], xs, ys, zs) cb = Colorbar(fig[1, 2], hm) - @test hm.attributes[:colorrange][] == (-.5, .5) - @test cb.limits[] == (-.5, .5) + @test hm.attributes[:colorrange][] == (-0.5, 0.5) + @test cb.limits[] == (-0.5, 0.5) hm.attributes[:colorrange][] = Float32.((-1, 1)) @test cb.limits[] == (-1, 1) @@ -158,12 +158,12 @@ end @testset "Colorbars" begin fig = Figure() hmap = heatmap!(Axis(fig[1, 1]), rand(4, 4)) - cb1 = Colorbar(fig[1,2], hmap; height = Relative(0.65)) + cb1 = Colorbar(fig[1, 2], hmap; height = Relative(0.65)) @test cb1.height[] == Relative(0.65) @testset "conversion" begin # https://github.com/MakieOrg/Makie.jl/issues/2278 fig = Figure() - cbar = Colorbar(fig[1,1], colormap=:viridis, colorrange=Vec2f(0, 1)) + cbar = Colorbar(fig[1, 1], colormap = :viridis, colorrange = Vec2f(0, 1)) ticklabel_strings = first.(cbar.axis.elements[:ticklabels][1][]) @test ticklabel_strings[1] == "0.0" @test ticklabel_strings[end] == "1.0" @@ -185,14 +185,14 @@ end # triggering a conversion error # So we just check that the same scenario doesn't error again f = Figure() - ax = Axis(f[1,1], xticks = 20:10:80) + ax = Axis(f[1, 1], xticks = 20:10:80) scatter!(ax, 30:10:100, rand(Float64, 8), color = :red) end # issues 1958 and 2006 @testset "axislegend number align" begin f = Figure() - ax = Axis(f[1,1], xticks = 20:10:80) + ax = Axis(f[1, 1], xticks = 20:10:80) lines!(ax, 1:10, label = "A line") leg = axislegend(ax, position = (0.4, 0.8)) @test leg.halign[] == 0.4 @@ -205,18 +205,18 @@ end f = Figure() kw = (; backgroundcolor = :red) @test_throws ArgumentError lines(f[1, 1], 1:10, figure = kw) - @test_nowarn lines(f[1, 2], 1:10, axis = kw) + @test_nowarn lines(f[1, 2], 1:10, axis = kw) @test_throws ArgumentError lines(f[1, 3][1, 1], 1:10, figure = kw) - @test_nowarn lines(f[1, 4][1, 2], 1:10, axis = kw) + @test_nowarn lines(f[1, 4][1, 2], 1:10, axis = kw) ax = T(f[1, 5]) @test_throws ArgumentError lines!(ax, 1:10, axis = kw) @test_throws ArgumentError lines!(ax, 1:10, axis = kw) @test_throws ArgumentError lines!(1:10, axis = kw) @test_throws ArgumentError lines!(1:10, figure = kw) - @test_nowarn lines!(1:10) + @test_nowarn lines!(1:10) @test_throws ArgumentError lines!(f[1, 5], 1:10, figure = kw) @test_throws ArgumentError lines!(f[1, 5], 1:10, axis = kw) - @test_nowarn lines!(f[1, 5], 1:10) + @test_nowarn lines!(f[1, 5], 1:10) end end diff --git a/test/pipeline.jl b/test/pipeline.jl index 3faf0ca29ff..3beda146e24 100644 --- a/test/pipeline.jl +++ b/test/pipeline.jl @@ -2,24 +2,22 @@ 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 -function test_copy2(attr; kw...) - return merge!(Attributes(kw), attr) -end +test_copy2(attr; kw...) = merge!(Attributes(kw), attr) @testset "don't copy in theme merge" begin x = Observable{Any}(1) - res=test_copy(linewidth=x) + res = test_copy(linewidth = x) res.linewidth === x end @testset "don't copy observables in when calling merge!" begin x = Observable{Any}(1) - res=test_copy2(Attributes(linewidth=x)) + res = test_copy2(Attributes(linewidth = x)) res.linewidth === x end diff --git a/test/projection_math.jl b/test/projection_math.jl index 946f4e6adf0..3aef948d3f6 100644 --- a/test/projection_math.jl +++ b/test/projection_math.jl @@ -1,4 +1,4 @@ @testset "Projection math" begin @test eltype(Makie.rotationmatrix_x(1)) == Float64 - @test eltype(Makie.rotationmatrix_x(1f0)) == Float32 + @test eltype(Makie.rotationmatrix_x(1.0f0)) == Float32 end diff --git a/test/quaternions.jl b/test/quaternions.jl index 77fd813a030..a49164db64b 100644 --- a/test/quaternions.jl +++ b/test/quaternions.jl @@ -2,8 +2,8 @@ struct Degree{T} <: Number θ::T end Base.:/(θ::Degree, x::Number) = Degree(θ.θ / x) -Base.sin(θ::Degree) = sin(θ.θ * π/180) -Base.cos(θ::Degree) = cos(θ.θ * π/180) +Base.sin(θ::Degree) = sin(θ.θ * π / 180) +Base.cos(θ::Degree) = cos(θ.θ * π / 180) @testset "Quaternions" begin @@ -12,18 +12,21 @@ Base.cos(θ::Degree) = cos(θ.θ * π/180) @test Base.power_by_squaring(qx, 2) ≈ qrotation(Vec(1.0, 0.0, 0.0), pi / 2) theta = pi / 8 qx = qrotation(Vec(1.0, 0.0, 0.0), theta) - c = cos(theta); s = sin(theta) + c = cos(theta) + s = sin(theta) Rx = [1 0 0; 0 c -s; 0 s c] @test Mat3f(qx) ≈ Rx theta = pi / 6 qy = qrotation(Vec(0.0, 1.0, 0.0), theta) - c = cos(theta); s = sin(theta) + c = cos(theta) + s = sin(theta) Ry = [c 0 s; 0 1 0; -s 0 c] @test Mat3f(qy) ≈ Ry theta = 4pi / 3 qz = qrotation(Vec(0.0, 0.0, 1.0), theta) - c = cos(theta); s = sin(theta) + c = cos(theta) + s = sin(theta) Rz = [c -s 0; s c 0; 0 0 1] @test Mat3f(qz) ≈ Rz @@ -54,6 +57,6 @@ Base.cos(θ::Degree) = cos(θ.θ * π/180) # `π` is not an `AbstractFloat` but it is a `Number` @test to_rotation(π) == to_rotation(1.0π) @test to_rotation((v, π)) == to_rotation((v, 1.0π)) - @test to_rotation(Degree(90)) == to_rotation(π/2) - @test to_rotation((v, Degree(90))) == to_rotation((v, π/2)) + @test to_rotation(Degree(90)) == to_rotation(π / 2) + @test to_rotation((v, Degree(90))) == to_rotation((v, π / 2)) end diff --git a/test/record.jl b/test/record.jl index 9e2310a28ed..43fcbb70363 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 @@ -41,22 +41,21 @@ mktempdir() do tempdir # test that the proper warnings are thrown @testset "Warnings" begin - function run_record(dst; kwargs...) + run_record(dst; kwargs...) = record(fig, dst, 1:n; kwargs...) do i lines!(ax, sin.(i .* x)) return nothing end - end # kwarg => (value, (should_warn => format)) warn_tests = [ (:compression, 20, ["mkv", "gif"], ["mp4", "webm"]), (:profile, "high422", ["mkv", "webm", "gif"], ["mp4"]), ( - kwarg=:pixel_format, - value="yuv420p", - warn_fmts=["mkv", "webm", "gif"], - no_warn_fmts=["mp4"], + kwarg = :pixel_format, + value = "yuv420p", + warn_fmts = ["mkv", "webm", "gif"], + no_warn_fmts = ["mp4"], ), ] diff --git a/test/runtests.jl b/test/runtests.jl index 5d46b19a92e..2f8a425ac98 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -15,7 +15,7 @@ using Makie: volume lims = Makie.data_limits(vplot) lo, hi = extrema(lims) @test all(lo .<= 1) - @test all(hi .>= (8,8,10)) + @test all(hi .>= (8, 8, 10)) end include("pipeline.jl") diff --git a/test/stack.jl b/test/stack.jl index e03b5779a8b..f517bbd9e97 100644 --- a/test/stack.jl +++ b/test/stack.jl @@ -1,27 +1,27 @@ using Makie: stack_grouped_from_to @testset "grouped bar: stack" begin - x1 = [1, 1, 1, 1] - grp_dodge1 = [2, 2, 1, 1] - grp_stack1 = [1, 2, 1, 2] - y1 = [2, 3, -3, -2] + x1 = [1, 1, 1, 1] + grp_dodge1 = [2, 2, 1, 1] + grp_stack1 = [1, 2, 1, 2] + y1 = [2, 3, -3, -2] - x2 = [2, 2, 2, 2] - grp_dodge2 = [3, 4, 3, 4] - grp_stack2 = [3, 4, 3, 4] - y2 = [2, 3, -3, -2] + x2 = [2, 2, 2, 2] + grp_dodge2 = [3, 4, 3, 4] + grp_stack2 = [3, 4, 3, 4] + y2 = [2, 3, -3, -2] from, to = stack_grouped_from_to(grp_stack1, y1, (; x1 = x1, grp_dodge1 = grp_dodge1)) - from1 = [0.0, 2.0, 0.0, -3.0] - to1 = [2.0, 5.0, -3.0, -5.0] + from1 = [0.0, 2.0, 0.0, -3.0] + to1 = [2.0, 5.0, -3.0, -5.0] @test from == from1 - @test to == to1 + @test to == to1 from, to = stack_grouped_from_to(grp_stack2, y2, (; x2 = x2, grp_dodge2 = grp_dodge2)) - from2 = [0.0, 0.0, 0.0, 0.0] - to2 = [2.0, 3.0, -3.0, -2.0] + from2 = [0.0, 0.0, 0.0, 0.0] + to2 = [2.0, 3.0, -3.0, -2.0] @test from == from2 - @test to == to2 + @test to == to2 perm = [1, 4, 2, 7, 5, 3, 8, 6] x = [x1; x2][perm] diff --git a/test/statistical_tests.jl b/test/statistical_tests.jl index ca47a2f3cc9..cce19869fa9 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 @@ -83,11 +83,11 @@ end fix, ax, plt = plot(d) @test plt isa Lines @test !Makie.isdiscrete(d) - @test first(plt[1][][1]) ≈ minimum(rg) rtol = 1f-6 - @test first(plt[1][][end]) ≈ maximum(rg) rtol = 1f-6 + @test first(plt[1][][1]) ≈ minimum(rg) rtol = 1.0f-6 + @test first(plt[1][][end]) ≈ maximum(rg) rtol = 1.0f-6 for (x, pd) in plt[1][] - @test pd ≈ Distributions.pdf(d, x) rtol = 1f-6 + @test pd ≈ Distributions.pdf(d, x) rtol = 1.0f-6 end d = Distributions.Poisson() @@ -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) @@ -181,17 +181,17 @@ end @test p.plots[1] isa Poly @test p.plots[1][1][] == [Rect2f(Float32[0.6, 2.0], Float32[0.8, 2.0]),] @test p.plots[2] isa LineSegments - @test p.plots[2][1][] == Point{2,Float32}[Float32[0.6, 3.0], Float32[1.4, 3.0]] + @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]] + 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]] @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]] + @test p.plots[2][1][] == Point{2, Float32}[Float32[0.8, 3.0], Float32[1.2, 3.0]] end @testset "boxplot" begin @@ -239,12 +239,12 @@ 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 - pts = Point{2,Float32}[ + pts = Point{2, Float32}[ [1.0, 5.75], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 15.25], [1.0, 20.0], [1.0, 20.0], [1.0, 20.0], [2.0, 25.75], [2.0, 21.0], [2.0, 21.0], [2.0, 21.0], [2.0, 35.25], [2.0, 40.0], [2.0, 40.0], @@ -261,11 +261,11 @@ end @test plts[3] isa CrossBar @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]])] + 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]])] meshes = plts[3].plots[1][1][] @testset for (i, mesh) in enumerate(meshes) @test mesh isa Makie.AbstractMesh diff --git a/test/test_primitives.jl b/test/test_primitives.jl index 851d56866a4..3b2aed769f0 100644 --- a/test/test_primitives.jl +++ b/test/test_primitives.jl @@ -10,16 +10,16 @@ fig, ax, p = surface(rand(4, 7)) fig, ax, p = volume(rand(4, 4, 4)) begin fig, ax, p = heatmap(rand(4, 4)) - scatter!(Makie.point_iterator(p) |> collect, color=:red, markersize=10) + scatter!(collect(Makie.point_iterator(p)), color = :red, markersize = 10) display(fig) end fig, ax, p = image(rand(4, 5)) -scatter!(Makie.point_iterator(p) |> collect, color=:red, markersize=10) +scatter!(collect(Makie.point_iterator(p)), color = :red, markersize = 10) display(fig) begin fig, ax, p = scatter(1:5, rand(5)) - linesegments!(Makie.data_limits(ax.scene), color=:red) + linesegments!(Makie.data_limits(ax.scene), color = :red) display(fig) end diff --git a/test/text.jl b/test/text.jl index c0b1f427eae..124a794fd54 100644 --- a/test/text.jl +++ b/test/text.jl @@ -33,7 +33,7 @@ # This is just repeating code from Makie unit_extents = [FreeTypeAbstraction.get_extent(font, char) for char in chars] - origins = cumsum(20f0 * Float32[ + origins = cumsum(20.0f0 * Float32[ 0, unit_extents[1].advance[1], unit_extents[2].advance[1], @@ -45,9 +45,9 @@ @test glyph_collection.fonts == [font for _ in 1:4] @test all(isapprox.(glyph_collection.origins, [Point3f(x, 0, 0) for x in origins], atol = 1e-10)) @test glyph_collection.scales.sv == [Vec2f(p.fontsize[]) for _ in 1:4] - @test glyph_collection.rotations.sv == [Quaternionf(0,0,0,1) for _ in 1:4] - @test glyph_collection.colors.sv == [RGBAf(0,0,0,1) for _ in 1:4] - @test glyph_collection.strokecolors.sv == [RGBAf(0,0,0,0) for _ in 1:4] + @test glyph_collection.rotations.sv == [Quaternionf(0, 0, 0, 1) for _ in 1:4] + @test glyph_collection.colors.sv == [RGBAf(0, 0, 0, 1) for _ in 1:4] + @test glyph_collection.strokecolors.sv == [RGBAf(0, 0, 0, 0) for _ in 1:4] @test glyph_collection.strokewidths.sv == Float32[0, 0, 0, 0] makie_hi_bb = Makie.height_insensitive_boundingbox.(glyph_collection.extents) @@ -75,19 +75,19 @@ # end fta_quad_offsets = map(chars) do c - mini = FreeTypeAbstraction.metrics_bb(c, font, 20.0)[1] |> minimum + mini = minimum(FreeTypeAbstraction.metrics_bb(c, font, 20.0)[1]) Vec2f(mini .- atlas.glyph_padding * 20.0 / atlas.pix_per_glyph) end fta_scales = map(chars) do c - mini = FreeTypeAbstraction.metrics_bb(c, font, 20.0)[1] |> widths + mini = widths(FreeTypeAbstraction.metrics_bb(c, font, 20.0)[1]) Vec2f(mini .+ 2 * atlas.glyph_padding * 20.0 / atlas.pix_per_glyph) end - @test all(isequal(to_ndim(Point3f, p.position[], 0f0)), positions) + @test all(isequal(to_ndim(Point3f, p.position[], 0.0f0)), positions) @test char_offsets == glyph_collection.origins @test quad_offsets == fta_quad_offsets - @test scales == fta_scales + @test scales == fta_scales end diff --git a/test/transformations.jl b/test/transformations.jl index fd568f82534..1a7c80a0d98 100644 --- a/test/transformations.jl +++ b/test/transformations.jl @@ -10,13 +10,9 @@ function xyz_boundingbox(trans, points) end @testset "Basic transforms" begin - function fpoint2(x::Point2) - return Point2f(x[1] + 10, x[2] - 77) - end + fpoint2(x::Point2) = Point2f(x[1] + 10, x[2] - 77) - function fpoint3(x::Point3) - return Point3f(x[1] + 10, x[2] - 77, x[3] / 4) - end + fpoint3(x::Point3) = Point3f(x[1] + 10, x[2] - 77, x[3] / 4) trans2 = PointTrans{2}(fpoint2) trans3 = PointTrans{3}(fpoint3) points2 = [Point2f(0, 0), Point2f(0, 1)] @@ -77,14 +73,14 @@ end @test apply_transform(i2, 1) == 1 @test apply_transform(i3, 1) == 1 - @test apply_transform(identity, 1..2) == 1..2 - @test apply_transform(i2, 1..2) == 1..2 - @test apply_transform(i3, 1..2) == 1..2 + @test apply_transform(identity, 1 .. 2) == 1 .. 2 + @test apply_transform(i2, 1 .. 2) == 1 .. 2 + @test apply_transform(i3, 1 .. 2) == 1 .. 2 pa = Point2f(1, 2) pb = Point2f(3, 4) r2 = Rect2f(pa, pb .- pa) - @test apply_transform(t1, r2) == Rect2f(apply_transform(t1, pa), apply_transform(t1, pb) .- apply_transform(t1, pa) ) + @test apply_transform(t1, r2) == Rect2f(apply_transform(t1, pa), apply_transform(t1, pb) .- apply_transform(t1, pa)) end @testset "Coordinate Systems" begin @@ -105,14 +101,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 / (√2.0f0), √2.0f0, √2.0f0).origin) + @test all(Makie.rotatedrect(box, π / 4).widths .≈ Rect2f(0, -1 / (√2.0f0), √2.0f0, √2.0f0).widths) end @@ -125,10 +121,10 @@ end p3 = Point(2.0, 5.0, 4.0) spaces_and_desired_transforms = Dict( - :data => (x,y) -> y, # uses changes - :clip => (x,y) -> x, # no change - :relative => (x,y) -> x, # no change - :pixel => (x,y) -> x, # no transformation + :data => (x, y) -> y, # uses changes + :clip => (x, y) -> x, # no change + :relative => (x, y) -> x, # no change + :pixel => (x, y) -> x, # no transformation ) for (space, desired_transform) in spaces_and_desired_transforms @test apply_transform(identity, p2, space) == p2 @@ -141,5 +137,5 @@ end @test apply_transform(t2, p3, space) == desired_transform(p3, Point3f(sqrt(2.0), log(5.0), 4.0)) @test apply_transform(t3, p3, space) == desired_transform(p3, Point3f(sqrt(2.0), log(5.0), log10(4.0))) - end + end end diff --git a/test/zoom_pan.jl b/test/zoom_pan.jl index 8a5a3e5daa7..ef9b742f8f0 100644 --- a/test/zoom_pan.jl +++ b/test/zoom_pan.jl @@ -13,17 +13,17 @@ end @testset "zoom Axis" begin ax, axbox, lim, e = cleanaxes() # Put the mouse in the center - e.mouseposition[] = Tuple(axbox.origin + axbox.widths/2) + e.mouseposition[] = Tuple(axbox.origin + axbox.widths / 2) # zoom in e.scroll[] = (0.0, -1.0) newlim = ax.finallimits[] @test newlim.widths ≈ 0.9 * lim.widths - @test newlim.origin ≈ lim.origin + (lim.widths - newlim.widths)/2 + @test newlim.origin ≈ lim.origin + (lim.widths - newlim.widths) / 2 # zoom out restores original position e.scroll[] = (0.0, 1.0) newlim = ax.finallimits[] @test newlim.widths ≈ lim.widths - @test all(abs.(newlim.origin - lim.origin) .< 1e-7*lim.widths) + @test all(abs.(newlim.origin - lim.origin) .< 1e-7 * lim.widths) ax.finallimits[] = lim # Put mouse in corner e.mouseposition[] = Tuple(axbox.origin) @@ -31,12 +31,12 @@ end e.scroll[] = (0.0, -1.0) newlim = ax.finallimits[] @test newlim.widths ≈ 0.9 * lim.widths - @test all(abs.(newlim.origin - lim.origin) .< 1e-7*lim.widths) + @test all(abs.(newlim.origin - lim.origin) .< 1e-7 * lim.widths) # zoom out e.scroll[] = (0.0, 1.0) newlim = ax.finallimits[] @test newlim.widths ≈ lim.widths - @test all(abs.(newlim.origin - lim.origin) .< 1e-7*lim.widths) + @test all(abs.(newlim.origin - lim.origin) .< 1e-7 * lim.widths) ax.finallimits[] = lim # Zoom only x or y @@ -45,17 +45,17 @@ end lock = getproperty(ax, lockname) @test !lock[] lock[] = true - e.mouseposition[] = Tuple(axbox.origin + axbox.widths/2) + e.mouseposition[] = Tuple(axbox.origin + axbox.widths / 2) e.scroll[] = (0.0, -1.0) newlim = ax.finallimits[] @test newlim.widths[idx] == lim.widths[idx] - @test newlim.widths[3-idx] ≈ 0.9 * lim.widths[3-idx] + @test newlim.widths[3 - idx] ≈ 0.9 * lim.widths[3 - idx] @test newlim.origin[idx] == lim.origin[idx] - @test newlim.origin[3-idx] ≈ lim.origin[3-idx] + (lim.widths[3-idx] - newlim.widths[3-idx])/2 + @test newlim.origin[3 - idx] ≈ lim.origin[3 - idx] + (lim.widths[3 - idx] - newlim.widths[3 - idx]) / 2 e.scroll[] = (0.0, 1.0) newlim = ax.finallimits[] @test newlim.widths ≈ lim.widths - @test all(abs.(newlim.origin - lim.origin) .< 1e-7*lim.widths) + @test all(abs.(newlim.origin - lim.origin) .< 1e-7 * lim.widths) ax.finallimits[] = lim lock[] = false # Simulate pressing the keys @@ -66,13 +66,13 @@ end e.scroll[] = (0.0, -1.0) newlim = ax.finallimits[] @test newlim.widths[idx] == lim.widths[idx] - @test newlim.widths[3-idx] ≈ 0.9 * lim.widths[3-idx] + @test newlim.widths[3 - idx] ≈ 0.9 * lim.widths[3 - idx] @test newlim.origin[idx] == lim.origin[idx] - @test newlim.origin[3-idx] ≈ lim.origin[3-idx] + (lim.widths[3-idx] - newlim.widths[3-idx])/2 + @test newlim.origin[3 - idx] ≈ lim.origin[3 - idx] + (lim.widths[3 - idx] - newlim.widths[3 - idx]) / 2 e.scroll[] = (0.0, 1.0) newlim = ax.finallimits[] @test newlim.widths ≈ lim.widths - @test all(abs.(newlim.origin - lim.origin) .< 1e-7*lim.widths) + @test all(abs.(newlim.origin - lim.origin) .< 1e-7 * lim.widths) end # Rubber band selection @@ -104,23 +104,23 @@ end empty!(e.mousebuttons[]) empty!(keypresses) newlim = ax.finallimits[] - @test all(lim.origin .>= newlim.origin) && all(lim.origin+lim.widths .<= newlim.origin+newlim.widths) + @test all(lim.origin .>= newlim.origin) && all(lim.origin + lim.widths .<= newlim.origin + newlim.widths) end @testset "pan Axis" begin ax, axbox, lim, e = cleanaxes() - e.mouseposition[] = Tuple(axbox.origin + axbox.widths/2) + e.mouseposition[] = Tuple(axbox.origin + axbox.widths / 2) e.scroll[] = (0.0, -1.0) newlim = ax.finallimits[] e.mouseposition[] = Tuple(axbox.origin) panbtn = ax.panbutton[] e.mousebuttons[] = Set([panbtn]) e.mousedrag[] = Mouse.down - e.mouseposition[] = Tuple(axbox.origin + axbox.widths/10) + e.mouseposition[] = Tuple(axbox.origin + axbox.widths / 10) e.mousedrag[] = Mouse.pressed e.mousebuttons[] = Set{typeof(panbtn)}() e.mousedrag[] = Mouse.up panlim = ax.finallimits[] @test panlim.widths == newlim.widths - @test (5/4)*panlim.origin ≈ -newlim.origin + @test (5 / 4) * panlim.origin ≈ -newlim.origin end