Skip to content

Commit

Permalink
Update Makie integration and bump version
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesWrigley committed Aug 6, 2024
1 parent cc45149 commit 5c83b60
Show file tree
Hide file tree
Showing 7 changed files with 173 additions and 42 deletions.
6 changes: 5 additions & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
name = "CImGui"
uuid = "5d785b6c-b76f-510e-a07c-3070796c7e87"
authors = ["Yupei Qi <qiyupei@gmail.com>"]
version = "2.2.0"
version = "2.3.0"

[deps]
CEnum = "fa961155-64e5-5f13-b03f-caf6b980ea82"
CImGuiPack_jll = "333409e9-af72-5310-9767-d6ad21a76a05"
CSyntax = "ea656a56-6ca6-5dda-bba5-7b6963a5f74c"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
Statistics = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"

[weakdeps]
GLFW = "f7f18e0c-5ee9-5ccd-a5bf-e8befd85ed98"
Expand All @@ -24,4 +26,6 @@ CSyntax = "0.4"
GLFW = "3"
GLMakie = "0.10.5"
ModernGL = "1"
Printf = "1"
Statistics = "1"
julia = "1.9"
21 changes: 21 additions & 0 deletions docs/src/_changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,27 @@ CurrentModule = CImGui
This documents notable changes in CImGui.jl. The format is based on [Keep a
Changelog](https://keepachangelog.com).

## [v2.3.0] - 2024-08-06

### Added
- The [Makie integration](@ref) now supports displaying rendering statistics,
and has a context menu to change simple plot settings ([#137]). This will be
made more customizeable in the future.

### Fixed
- Fixed a number of bugs in the Makie integration ([#137]).

### Changed
- Upon loading the Makie extension, the default Makie theme will be set to one
that matches ImGui's default dark theme ([#137]).
- The GLFW/OpenGL renderloop will now `yield()` after every drawing iteration
([#137]). This makes it play a little nicer with Julia's event loop.
- **Breaking**: Previously [`MakieFigure()`](@ref) would return a `Bool` to
indicate if the figure was rendered or not, now it returns `nothing`
([#137]).

*Reminder that the [Makie integration](@ref) is not yet covered by semver.*

## [v2.2.0] - 2024-08-02

### Added
Expand Down
Binary file added docs/src/assets/makie-demo.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
12 changes: 12 additions & 0 deletions docs/src/makie.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ custom window type to represent a single `Figure` to be drawn in ImGui. What we
get from GLMakie is a framebuffer with a color image texture attachment, and
that's displayed by us as an image.

It supports all the interaction features in GLMakie:
- Scroll to zoom
- Click and drag to rectangle select a region to zoom to
- Right click and drag to pan
- Shift + {x/y} and scroll to zoom along the X/Y axes
- Ctrl + left click to reset the limits

Here's a quick demo using
[`examples/makie_demo.jl`](https://github.com/Gnimuc/CImGui.jl/blob/master/examples/makie_demo.jl)
(you may want to `Right click -> Open in new tab` to see it in full resolution):
![Makie demo](assets/makie-demo.gif)

```@docs
MakieFigure
```
46 changes: 31 additions & 15 deletions examples/makie_demo.jl
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,25 @@ function makie_demo(; engine=nothing)
io.ConfigFlags = unsafe_load(io.ConfigFlags) | ig.lib.ImGuiConfigFlags_DockingEnable
io.ConfigFlags = unsafe_load(io.ConfigFlags) | ig.lib.ImGuiConfigFlags_ViewportsEnable

ax1_tight_spacing = true
auto_resize_x = true
auto_resize_y = false
tooltip = true
stats = true
stream_data = false

data_task = nothing
function live_data(obs::Observable)
obs_data = obs[]

while stream_data
push!(obs_data, Point2f(length(obs_data), rand()))
obs[] = obs_data
autolimits!(ax1)
sleep(0.01)
end

data_task = nothing
end

# Start the GUI
ig.render(ctx; engine, window_size=(1280, 760), window_title="ImGui Window", opengl_version=v"3.3") do
Expand All @@ -59,30 +74,31 @@ function makie_demo(; engine=nothing)
data[] = generate_data()
end

@c ig.Checkbox("Ax1 tight tick spacing", &ax1_tight_spacing)
ig.SameLine()
HelpMarker("""
Try zooming into the top plot, if this option is disabled
the axis will not resize itself to stop clipping the tick labels on the Y axis.
""")

@c ig.Checkbox("Auto resize X", &auto_resize_x)
ig.SameLine()
@c ig.Checkbox("Auto resize Y", &auto_resize_y)
ig.SameLine()
@c ig.Checkbox("Draw tooltip", &tooltip)
ig.SameLine()
@c ig.Checkbox("Show render times", &stats)
ig.SameLine()
@c ig.Checkbox("Stream data", &stream_data)

if ig.MakieFigure("plot", f; auto_resize_x, auto_resize_y, tooltip)
if ax1_tight_spacing
Makie.tight_ticklabel_spacing!(ax1)
end

Makie.tight_ticklabel_spacing!(ax2)
if stream_data && isnothing(data_task)
data_task = errormonitor(Threads.@spawn live_data(data))
end

ig.MakieFigure("plot", f; auto_resize_x, auto_resize_y, tooltip, stats)

ig.Text("Mouse position in scene: $(scene.events.mouseposition[])")
ig.Text("Scene size: $(size(scene))")
ig.Text("Mouse position in ax1: $(mouseposition(ax1))")

# These extra transformations are necessary to handle non-linear axis
# scales. See: https://github.com/MakieOrg/Makie.jl/pull/4090.
x, y = mouseposition(ax1)
x = Makie.inverse_transform(ax1.xscale[])(x)
y = Makie.inverse_transform(ax1.yscale[])(y)
ig.Text("Mouse position in ax1: ($x, $y)")

ig.End()
end
Expand Down
101 changes: 94 additions & 7 deletions ext/MakieIntegration.jl
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
module MakieIntegration

import Printf: @sprintf
import Statistics: mean, std

import CImGui as ig
import ModernGL as gl
import GLFW
import GLMakie
import GLMakie.Makie as Makie


# Represents a single Figure to be shown as an ImGui image texture
struct ImMakieWindow
glfw_window::GLFW.Window # Only needed for supporting GLMakie requirements
end

struct ImMakieFigure
mutable struct ImMakieFigure
figure::GLMakie.Figure
screen::GLMakie.Screen{ImMakieWindow}

render_times::Vector{Float32}
times_idx::Int
was_dragging::Bool

function ImMakieFigure(figure, screen)
self = new(figure, screen, zeros(Float32, 20), 1, false)
end
end

const makie_context = Dict{ig.ImGuiID, ImMakieFigure}()
Expand Down Expand Up @@ -78,7 +88,7 @@ function draw_figure_tooltip(cursor_pos, image_size)
help_str = "(?)"
text_size = ig.CalcTextSize(help_str)
text_pos = (cursor_pos.x + image_size[1] - text_size.x, cursor_pos.y)
ig.AddText(ig.GetWindowDrawList(), text_pos, ig.IM_COL32_BLACK, help_str)
ig.AddText(ig.GetWindowDrawList(), text_pos, ig.IM_COL32_WHITE, help_str)
hovering = ig.IsMouseHoveringRect(text_pos, (text_pos[1] + text_size.x, text_pos[2] + text_size.y))

if hovering && ig.BeginTooltip()
Expand All @@ -90,13 +100,54 @@ function draw_figure_tooltip(cursor_pos, image_size)
- Right click and drag to pan
- Shift + {x/y} and scroll to zoom along the X/Y axes
- Ctrl + left click to reset the limits
And right-click for plot settings.
""")
ig.PopTextWrapPos()
ig.EndTooltip()
end
end

function ig.MakieFigure(title_id::String, f::GLMakie.Figure; auto_resize_x=true, auto_resize_y=false, tooltip=true)
function draw_figure_stats(cursor_pos, imfigure)
n_samples = length(imfigure.render_times)
mean_time = mean(imfigure.render_times)
std_time = std(imfigure.render_times)
text = @sprintf("Avg. of last %i render times: %.5f ± %.5fs",
n_samples, mean_time, std_time)
ig.AddText(ig.GetWindowDrawList(), cursor_pos, ig.IM_COL32_WHITE, text)
end

function draw_axisscale_buttons(scale, ticks, idx)
if ig.RadioButton("linear##$(idx)", scale[] === identity)
scale[] = identity
end
ig.SameLine()
if ig.RadioButton("pseudolog10##$(idx)", scale[] === Makie.pseudolog10)
scale[] = Makie.pseudolog10
# ticks[] = Makie.LogTicks(Makie.LinearTicks(5))
end
end

function draw_popup(axis)
if ig.BeginPopupContextItem()
ig.Text("Axis settings")
ig.Separator()

ig.Text("X scale:")
ig.SameLine()
draw_axisscale_buttons(axis.xscale, axis.xticks, 1)

ig.Text("Y scale:")
ig.SameLine()
draw_axisscale_buttons(axis.yscale, axis.yticks, 2)

ig.EndPopup()
end
end

function ig.MakieFigure(title_id::String, f::GLMakie.Figure;
auto_resize_x=true, auto_resize_y=false,
tooltip=true, stats=false)
ig.PushID(title_id)
id = ig.GetID(title_id)

Expand Down Expand Up @@ -150,15 +201,14 @@ function ig.MakieFigure(title_id::String, f::GLMakie.Figure; auto_resize_x=true,
auto_resize_y ? region_size[2] : scene_size[2])

if scene_size != new_size && all(new_size .> 0)
@debug "resizing $(scene_size) -> $(new_size)"
scene.events.window_area[] = GLMakie.Rect2i(0, 0, Int(new_size[1]), Int(new_size[2]))
resize!(f, new_size[1], new_size[2])
end

do_render = GLMakie.requires_update(imfigure.screen)
if do_render
@debug "rendering"
GLMakie.render_frame(imfigure.screen)
idx = mod1(imfigure.times_idx, length(imfigure.render_times))
imfigure.render_times[idx] = @elapsed GLMakie.render_frame(imfigure.screen; resize_buffers=false)
end

# The color texture is what we need to render as an image. We add it to the
Expand All @@ -179,6 +229,9 @@ function ig.MakieFigure(title_id::String, f::GLMakie.Figure; auto_resize_x=true,
if tooltip
draw_figure_tooltip(cursor_pos, image_size)
end
if stats
draw_figure_stats(cursor_pos, imfigure)
end

ig.InvisibleButton("figure_image", size(color_buffer))

Expand Down Expand Up @@ -211,6 +264,11 @@ function ig.MakieFigure(title_id::String, f::GLMakie.Figure; auto_resize_x=true,
end
end

# Record if the mouse is dragging
if ig.IsMouseDragging(ig.lib.ImGuiMouseButton_Right)
imfigure.was_dragging = true
end

# Update the scroll rate
wheel_y = unsafe_load(io.MouseWheel)
wheel_x = unsafe_load(io.MouseWheelH)
Expand All @@ -233,13 +291,42 @@ function ig.MakieFigure(title_id::String, f::GLMakie.Figure; auto_resize_x=true,
end
end

# Always clear the dragging field when a new potential drag (right-click) is
# started.
if ig.IsMouseClicked(ig.lib.ImGuiMouseButton_Right)
imfigure.was_dragging = false
end

# Only display the popup if we're not dragging
if !imfigure.was_dragging
for x in f.content
if x isa Makie.Axis && GLMakie.is_mouseinside(x)
draw_popup(x)
end
end
end

ig.PopID()

return do_render
end

function theme_imgui()
theme = Makie.theme_dark()
theme.Legend.framevisible = true
theme.Legend.backgroundcolor = Makie.RGBAf(0, 0, 0, 0.75)
theme.Legend.padding = (5, 5, 5, 5)
theme.textcolor = :gray90

# For some reason FXAA causes artifacts with the dark theme
theme.GLMakie = Makie.Attributes(fxaa=false)

return theme
end

function __init__()
ig.atrenderexit(destroy_context)
Makie.set_theme!(theme_imgui())
end

end
29 changes: 10 additions & 19 deletions src/CImGui.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,19 +70,11 @@ const IMGUI_VERSION = unsafe_string(GetVersion())
"""
MakieFigure(id::String, f::GLMakie.Figure;
auto_resize_x=true, auto_resize_y=false,
tooltip=true)
tooltip=true, stats=false)
Display a Makie figure in ImGui. See `examples/makie_demo.jl` for an example of
how to use it. This supports all the interaction features in GLMakie:
- Scroll to zoom
- Click and drag to rectangle select a region to zoom to
- Right click and drag to pan
- Shift + {x/y} and scroll to zoom along the X/Y axes
- Ctrl + left click to reset the limits
Note that scrolling to zoom will also cause the ImGui window to scroll, which
can be annoying. This may be fixed in the future by using some other key
combination for scrolling to zoom.
Display a Makie figure in ImGui. See
[`examples/makie_demo.jl`](https://github.com/Gnimuc/CImGui.jl/blob/master/examples/makie_demo.jl)
for an example of how to use it.
These are the [interaction
events](https://docs.makie.org/stable/explanations/events#The-Events-struct)
Expand All @@ -93,18 +85,17 @@ that are wired up and can be used:
- `mouseposition`
Known issues:
- Changing tick labels don't trigger the scene to be re-layouted, causing them
to be clipped if the labels change width. See `examples/makie_demo.jl` for an
example workaround using `Makie.tight_ticklabel_spacing!()`.
- The theming doesn't match the ImGui theme so plots look quite out of place by
default.
- Mouse events aren't delivered unless the mouse is hovered over the figure, so
dragging the mouse from within the figure to somewhere outside the figure will
keep the old mouse state. e.g. if you're RMB panning and the mouse goes
outside the figure, when it enters the figure again panning will resume even
the RMB was released.
- Drawing can be a bit janky, occasionally the image will not be drawn for a
frame or two and you'll see an empty black square instead.
- Note that scrolling to zoom will also cause the ImGui window to scroll, which
can be annoying. This may be fixed in the future by using some other key
combination for scrolling to zoom.
- Sometimes zooming way out or in can trigger segfaults if a CImGui window has
been opened multiple times in the same process (e.g. when experimenting in the
REPL). Some resources probably aren't getting cleaned up properly.
!!! note
GLMakie requires OpenGL 3.3, on some systems you will need to explicitly
Expand Down

0 comments on commit 5c83b60

Please sign in to comment.