diff --git a/.gitattributes b/.gitattributes index 30e1d28..a133a22 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,3 @@ .gitattributes export-ignore tools/upstream/** linguist-vendored=true +love/** linguist-generated=true diff --git a/.gitmodules b/.gitmodules index f73a6ab..cc94566 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "tools/core"] path = tools/core - url = https://git.bug.tools/bug/imgui-luau.git + url = https://github.com/4DBug/imgui-luau.git diff --git a/love/ImPlot3D.lua b/love/ImPlot3D.lua new file mode 100644 index 0000000..38acaa6 --- /dev/null +++ b/love/ImPlot3D.lua @@ -0,0 +1,4918 @@ +-- GENERATED by tools/love.sh from the Luau source - do not edit +local function __iter(t, ...) if type(t) ~= 'table' or (getmetatable(t) and getmetatable(t).__call) then return t, ... end local n, i, k = #t, 0, nil return function() if i < n then i = i + 1 return i, t[i] end repeat k = next(t, k) until k == nil or type(k) ~= 'number' or k < 1 or k > n or k % 1 ~= 0 if k ~= nil then return k, t[k] end end end table.create = table.create or function(n, v) local t = {} if v ~= nil then for i = 1, n do t[i] = v end end return t end table.clone = table.clone or function(t) local c = {} for k, v in pairs(t) do c[k] = v end return setmetatable(c, getmetatable(t)) end math.clamp = math.clamp or function(x, a, b) return math.max(a, math.min(b, x)) end math.sign = math.sign or function(x) return x > 0 and 1 or (x < 0 and -1 or 0) end math.round = math.round or function(x) return x >= 0 and math.floor(x + 0.5) or math.ceil(x - 0.5) end +-- ImPlot3D for imgui-luau. Port of https://github.com/brenocq/implot3d (7913cf11684730119bd284fd8e7052d140e72f61). +-- Usage: local ImPlot3D = require(path.to.ImPlot3D)(require(path.to.ImGui)) +return function(G) + local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4 + local IM_COL32, IM_ASSERT = G.IM_COL32, G.IM_ASSERT + local ImPlot3D = {} + -- [Port] internal API (implot3d_internal.h). Exposed as ImPlot3D.internal for later milestones. + local internal = {} + ImPlot3D.internal = internal + + -- [Port] module-level context pointer (C++ global GImPlot3D) + local GImPlot3D = nil + + ImPlot3D.IMPLOT3D_VERSION = "0.5 WIP" -- ImPlot3D version + ImPlot3D.IMPLOT3D_VERSION_NUM = 500 -- Integer encoded version + ImPlot3D.IMPLOT3D_AUTO = -1 -- Deduce variable automatically + -- [Port] function instead of macro so each use gets a fresh ImVec4 + local function IMPLOT3D_AUTO_COL() return ImVec4(0, 0, 0, -1) end -- Deduce color automatically + ImPlot3D.IMPLOT3D_AUTO_COL = IMPLOT3D_AUTO_COL + + -------------------------------------------------------------------------- + -- [SECTION] Flags & Enumerations (implot3d.h) + -- [Port] ImPlot3DFlags_NoTitle -> ImPlot3D.ImPlot3DFlags.NoTitle; values identical to upstream. + -------------------------------------------------------------------------- + do + -- Plotting properties. These provide syntactic sugar for creating ImPlot3DSpec from (ImPlot3DProp,value) pairs + ImPlot3D.ImPlot3DProp = { + LineColor = 0, -- Line color; IMPLOT3D_AUTO_COL will use next Colormap color + LineColors = 1, -- Array of line colors (ImU32*); if nullptr, use LineColor for all + LineWeight = 2, -- Line weight in pixels + FillColor = 3, -- Fill color (applies to shaded regions); IMPLOT3D_AUTO_COL will use next Colormap color + FillColors = 4, -- Array of fill colors (ImU32*); if nullptr, use FillColor for all + FillAlpha = 5, -- Alpha multiplier (applies to FillColor, FillColors, MarkerFillColor, and MarkerFillColors) + Marker = 6, -- Marker type + MarkerSize = 7, -- Size of markers (radius) *in pixels* + MarkerSizes = 8, -- Array of marker sizes (float*); if nullptr, use MarkerSize for all + MarkerLineColor = 9, -- Marker outline color; IMPLOT3D_AUTO_COL will use next LineColor + MarkerLineColors = 10, -- Array of marker outline colors (ImU32*); if nullptr, use MarkerLineColor for all + MarkerFillColor = 11, -- Marker fill color; IMPLOT3D_AUTO_COL will use LineColor + MarkerFillColors = 12, -- Array of marker fill colors (ImU32*); if nullptr, use MarkerFillColor for all + Offset = 13, -- Data index offset + Stride = 14, -- Data stride in bytes; IMPLOT3D_AUTO will result in sizeof(T) where T is the type passed to PlotX + Flags = 15, -- Optional item flags; can be composed from common ImPlot3DItemFlags and/or specialized ImPlot3DXFlags + } + -- Flags for ImPlot3D::BeginPlot() + ImPlot3D.ImPlot3DFlags = { + None = 0, -- Default + NoTitle = 1, -- Hide plot title + NoLegend = 2, -- Hide plot legend + NoMouseText = 4, -- Hide mouse position in plot coordinates + NoClip = 8, -- Disable 3D box clipping + NoMenus = 16, -- The user will not be able to open context menus + Equal = 32, -- X, Y, and Z axes will be constrained to have the same units/pixel + NoRotate = 64, -- Lock rotation interaction + NoPan = 128, -- Lock panning/translation interaction + NoZoom = 256, -- Lock zoom interaction + NoInputs = 512, -- Disable all user inputs + CanvasOnly = 7, + } + -- Represents a condition for SetupAxisLimits etc. (same as ImGuiCond, but we only support a subset of those enums) + ImPlot3D.ImPlot3DCond = { + None = 0, -- No condition (always set the variable), same as _Always + Always = 1, -- No condition (always set the variable) + Once = 2, -- Set the variable once per runtime session (only the first call will succeed) + } + ImPlot3D.ImPlot3DCol = { + -- Plot colors + TitleText = 0, -- Title color + InlayText = 1, -- Color for texts appearing inside of plots + FrameBg = 2, -- Frame background color + PlotBg = 3, -- Plot area background color + PlotBorder = 4, -- Plot area border color + -- Legend colors + LegendBg = 5, -- Legend background color + LegendBorder = 6, -- Legend border color + LegendText = 7, -- Legend text color + -- Axis colors + AxisText = 8, -- Axis label and tick lables color + AxisGrid = 9, -- Axis grid color + AxisTick = 10, -- Axis tick color (defaults to AxisGrid) + AxisBg = 11, -- Background color of axis hover region (defaults to transparent) + AxisBgHovered = 12, -- Axis hover color (defaults to ImGuiCol_ButtonHovered) + AxisBgActive = 13, -- Axis active color (defaults to ImGuiCol_ButtonActive) + COUNT = 14, + } + -- Plot styling variables + ImPlot3D.ImPlot3DStyleVar = { + -- Item style + LineWeight = 0, -- float, plot item line weight in pixels + Marker = 1, -- int, marker specification + MarkerSize = 2, -- float, marker size in pixels (roughly the marker's "radius") + FillAlpha = 3, -- float, alpha modifier applied to all plot item fills + -- Plot style + PlotDefaultSize = 4, -- ImVec2, default size used when ImVec2(0,0) is passed to BeginPlot + PlotMinSize = 5, -- ImVec2, minimum size plot frame can be when shrunk + PlotPadding = 6, -- ImVec2, padding between widget frame and plot area, labels, or outside legends (i.e. main padding) + LabelPadding = 7, -- ImVec2, padding between axes labels, tick labels, and plot edge + ViewScaleFactor = 8, -- float, scale factor for 3D view, you can use it to make the whole plot larger or smaller + -- Legend style + LegendPadding = 9, -- ImVec2, legend padding from plot edges + LegendInnerPadding = 10, -- ImVec2, legend inner padding from legend edges + LegendSpacing = 11, -- ImVec2, spacing between legend entries + COUNT = 12, + } + ImPlot3D.ImPlot3DMarker = { + Invalid = -3, -- [Port] ImPlot3DMarkerInternal_ (implot3d_internal.h) + None = -2, -- No marker + Auto = -1, -- Automatic marker selection + Circle = 0, -- Circle marker (default) + Square = 1, -- Square maker + Diamond = 2, -- Diamond marker + Up = 3, -- Upward-pointing triangle marker + Down = 4, -- Downward-pointing triangle marker + Left = 5, -- Leftward-pointing triangle marker + Right = 6, -- Rightward-pointing triangle marker + Cross = 7, -- Cross marker (not fillable) + Plus = 8, -- Plus marker (not fillable) + Asterisk = 9, -- Asterisk marker (not fillable) + COUNT = 10, + } + -- Flags for items + ImPlot3D.ImPlot3DItemFlags = { + None = 0, -- Default + NoLegend = 1, -- The item won't have a legend entry displayed + NoFit = 2, -- The item won't be considered for plot fits + } + -- Flags for PlotScatter + ImPlot3D.ImPlot3DScatterFlags = { + None = 0, -- Default + NoLegend = 1, + NoFit = 2, + } + -- Flags for PlotLine + ImPlot3D.ImPlot3DLineFlags = { + None = 0, -- Default + NoLegend = 1, + NoFit = 2, + Segments = 1024, -- A line segment will be rendered from every two consecutive points + Loop = 2048, -- The last and first point will be connected to form a closed loop + SkipNaN = 4096, -- NaNs values will be skipped instead of rendered as missing data + } + -- [Port] Triangle/Quad/Surface/Mesh flags share identical values upstream + local function FillFlags() + return { + None = 0, -- Default + NoLegend = 1, + NoFit = 2, + NoLines = 1024, -- No lines will be rendered + NoFill = 2048, -- No fill will be rendered + NoMarkers = 4096, -- No markers will be rendered + } + end + ImPlot3D.ImPlot3DTriangleFlags = FillFlags() -- Flags for PlotTriangle + ImPlot3D.ImPlot3DQuadFlags = FillFlags() -- Flags for PlotQuad + ImPlot3D.ImPlot3DSurfaceFlags = FillFlags() -- Flags for PlotSurface + ImPlot3D.ImPlot3DMeshFlags = FillFlags() -- Flags for PlotMesh + -- Flags for PlotImage + ImPlot3D.ImPlot3DImageFlags = { + None = 0, -- Default + NoLegend = 1, + NoFit = 2, + } + -- Flags for PlotDummy + ImPlot3D.ImPlot3DDummyFlags = { + None = 0, -- Default + } + -- Flags for legends + ImPlot3D.ImPlot3DLegendFlags = { + None = 0, -- Default + NoButtons = 1, -- Legend icons will not function as hide/show buttons + NoHighlightItem = 2, -- Plot items will not be highlighted when their legend entry is hovered + Horizontal = 4, -- Legend entries will be displayed horizontally + } + -- Used to position legend on a plot + ImPlot3D.ImPlot3DLocation = { + Center = 0, -- Center-center + North = 1, -- Top-center + South = 2, -- Bottom-center + West = 4, -- Center-left + East = 8, -- Center-right + NorthWest = 5, -- Top-left + NorthEast = 9, -- Top-right + SouthWest = 6, -- Bottom-left + SouthEast = 10, -- Bottom-right + } + -- Flags for axis + ImPlot3D.ImPlot3DAxisFlags = { + None = 0, -- Default + NoLabel = 1, -- No axis label will be displayed + NoGridLines = 2, -- No grid lines will be displayed + NoTickMarks = 4, -- No tick marks will be displayed + NoTickLabels = 8, -- No tick labels will be displayed + LockMin = 16, -- The axis minimum value will be locked when panning/zooming + LockMax = 32, -- The axis maximum value will be locked when panning/zooming + AutoFit = 64, -- Axis will be auto-fitting to data extents + Invert = 128, -- The axis will be inverted + PanStretch = 256, -- Panning in a locked or constrained state will cause the axis to stretch if possible + Lock = 48, + NoDecorations = 11, + } + -- Axis indices + ImPlot3D.ImAxis3D = { + X = 0, -- X-axis + Y = 1, -- Y-axis + Z = 2, -- Z-axis + COUNT = 3, + } + -- Plane indices + ImPlot3D.ImPlane3D = { + YZ = 0, -- YZ plane (perpendicular to X-axis) + XZ = 1, -- XZ plane (perpendicular to Y-axis) + XY = 2, -- XY plane (perpendicular to Z-axis) + COUNT = 3, + } + -- Axis scale + ImPlot3D.ImPlot3DScale = { + Linear = 0, -- Default linear scale + Log10 = 1, -- Base 10 log scale + SymLog = 2, -- Symmetric base 10 log scale + } + -- Colormaps + ImPlot3D.ImPlot3DColormap = { + Deep = 0, -- Same as seaborn "deep" + Dark = 1, -- Same as matplotlib "Set1" + Pastel = 2, -- Same as matplotlib "Pastel1" + Paired = 3, -- Same as matplotlib "Paired" + Viridis = 4, -- Same as matplotlib "viridis" + Plasma = 5, -- Same as matplotlib "plasma" + Hot = 6, -- Same as matplotlib/MATLAB "hot" + Cool = 7, -- Same as matplotlib/MATLAB "cool" + Pink = 8, -- Same as matplotlib/MATLAB "pink" + Jet = 9, -- Same as matplotlib/MATLAB "jet" + Twilight = 10, -- Same as matplotlib "twilight" + RdBu = 11, -- Same as matplotlib "RdBu" + BrBG = 12, -- Same as matplotlib "BrGB" + PiYG = 13, -- Same as matplotlib "PiYG" + Spectral = 14, -- Same as matplotlib "Spectral" + Greys = 15, -- White/black + } + end + + local ImPlot3DCol = ImPlot3D.ImPlot3DCol + local ImPlot3DStyleVar = ImPlot3D.ImPlot3DStyleVar + local ImGuiCol = G.ImGuiCol + + -------------------------------------------------------------------------- + -- [SECTION] Generic Helpers (implot3d_internal.h) + -------------------------------------------------------------------------- + do + -- Returns true if val is NAN + function internal.ImNan(val) return val ~= val end + -- Returns always positive modulo (assumes r != 0) + function internal.ImPosMod(l, r) return (l % r + r) % r end + -- Returns true if flag is set + function internal.ImHasFlag(set, flag) return bit32.band(set, flag) == flag end + local DBL_MAX = G.DBL_MAX + -- Returns true if val is NAN or INFINITY + function internal.ImNanOrInf(val) return not (val >= -DBL_MAX and val <= DBL_MAX) end + -- Turns NANs to 0s + function internal.ImConstrainNan(val) if val ~= val then return 0 end return val end + -- Turns infinity to floating point maximums (half DBL_MAX to prevent overflow) + function internal.ImConstrainInf(val) + local max_val = DBL_MAX * 0.5 + if val >= max_val then return max_val elseif val <= -max_val then return -max_val end + return val + end + internal.DBL_MIN = 2.2250738585072014e-308 + internal.DBL_EPSILON = 2.220446049250313e-16 + -- True if two numbers are approximately equal using units in the last place. + function internal.ImAlmostEqual(v1, v2, ulp) + ulp = ulp or 2 + local d = math.abs(v1 - v2) + return d < internal.DBL_EPSILON * math.abs(v1 + v2) * ulp or d < internal.DBL_MIN + end + internal.IMPLOT3D_LABEL_FORMAT = "%g" + end + + -------------------------------------------------------------------------- + -- [SECTION] ImPlot3DPoint, ImPlot3DRay, ImPlot3DPlane, ImPlot3DBox, ImPlot3DRange, ImPlot3DQuat + -- [Port] Operators map to metamethods. Compound assignments (a += b) rebind to a new value, as Luau does natively. + -------------------------------------------------------------------------- + do + local sqrt, sin, cos, acos, abs = math.sqrt, math.sin, math.cos, math.acos, math.abs + + -- ImPlot3DPoint: 3D vector to store points in 3D space + local PointMT = {} + local PointMethods = {} + local function ImPlot3DPoint(x, y, z) + return setmetatable({ x = x or 0.0, y = y or 0.0, z = z or 0.0 }, PointMT) + end + ImPlot3D.ImPlot3DPoint = ImPlot3DPoint + + -- Accessors + -- [Port] operator[]: 0 -> x, 1 -> y, 2 -> z + local idx_keys = { [0] = "x", [1] = "y", [2] = "z" } + PointMT.__index = function(self, k) + local f = idx_keys[k] + if f then return rawget(self, f) end + return PointMethods[k] + end + PointMT.__newindex = function(self, k, v) + local f = idx_keys[k] + IM_ASSERT(f ~= nil) + rawset(self, f, v) + end + + -- Binary operators + -- [Port] operator*(double) / operator*(ImPlot3DPoint) / friend operator*(double, ImPlot3DPoint) overloads + PointMT.__mul = function(a, b) + if type(a) == "number" then return ImPlot3DPoint(a * b.x, a * b.y, a * b.z) end + if type(b) == "number" then return ImPlot3DPoint(a.x * b, a.y * b, a.z * b) end + return ImPlot3DPoint(a.x * b.x, a.y * b.y, a.z * b.z) + end + PointMT.__div = function(a, b) + if type(b) == "number" then return ImPlot3DPoint(a.x / b, a.y / b, a.z / b) end + return ImPlot3DPoint(a.x / b.x, a.y / b.y, a.z / b.z) + end + PointMT.__add = function(a, b) return ImPlot3DPoint(a.x + b.x, a.y + b.y, a.z + b.z) end + PointMT.__sub = function(a, b) return ImPlot3DPoint(a.x - b.x, a.y - b.y, a.z - b.z) end + + -- Unary operator + PointMT.__unm = function(a) return ImPlot3DPoint(-a.x, -a.y, -a.z) end + + -- Comparison operators + PointMT.__eq = function(a, b) return a.x == b.x and a.y == b.y and a.z == b.z end + + PointMT.__tostring = function(a) return string.format("ImPlot3DPoint(%g, %g, %g)", a.x, a.y, a.z) end + + -- Dot product + function PointMethods:Dot(rhs) return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z end + + -- Cross product + function PointMethods:Cross(rhs) + return ImPlot3DPoint(self.y * rhs.z - self.z * rhs.y, self.z * rhs.x - self.x * rhs.z, self.x * rhs.y - self.y * rhs.x) + end + + -- Get vector length + function PointMethods:Length() return sqrt(self.x * self.x + self.y * self.y + self.z * self.z) end + + -- Get vector squared length + function PointMethods:LengthSquared() return self.x * self.x + self.y * self.y + self.z * self.z end + + -- Normalize to unit length + function PointMethods:Normalize() + local l = self:Length() + self.x =self.x/ l + self.y =self.y/ l + self.z =self.z/ l + end + + -- Return vector normalized to unit length + function PointMethods:Normalized() + local l = self:Length() + return ImPlot3DPoint(self.x / l, self.y / l, self.z / l) + end + + -- Check if the point is NaN + function PointMethods:IsNaN() return internal.ImNan(self.x) or internal.ImNan(self.y) or internal.ImNan(self.z) end + + -- [Port] copy helper replacing C++ value semantics + function PointMethods:Copy() return ImPlot3DPoint(self.x, self.y, self.z) end + + -- ImPlot3DRay: Represents a ray in 3D space with an origin and direction + function ImPlot3D.ImPlot3DRay(origin, direction) + return { Origin = origin or ImPlot3DPoint(), Direction = direction or ImPlot3DPoint() } + end + + -- ImPlot3DPlane: Represents a plane in 3D space defined by a point and normal vector + function ImPlot3D.ImPlot3DPlane(point, normal) + return { Point = point or ImPlot3DPoint(), Normal = normal or ImPlot3DPoint() } + end + + -- ImPlot3DBox: Axis-aligned bounding box in 3D space + local BoxMT = {} + BoxMT.__index = BoxMT + function ImPlot3D.ImPlot3DBox(min, max) + return setmetatable({ Min = min or ImPlot3DPoint(), Max = max or ImPlot3DPoint() }, BoxMT) + end + + -- Method to expand the box to include a point + function BoxMT:Expand(point) + local Min, Max = self.Min, self.Max + Min.x = math.min(Min.x, point.x) + Min.y = math.min(Min.y, point.y) + Min.z = math.min(Min.z, point.z) + Max.x = math.max(Max.x, point.x) + Max.y = math.max(Max.y, point.y) + Max.z = math.max(Max.z, point.z) + end + + -- Method to check if a point is inside the box + function BoxMT:Contains(point) + local Min, Max = self.Min, self.Max + return (point.x >= Min.x and point.x <= Max.x) and (point.y >= Min.y and point.y <= Max.y) and (point.z >= Min.z and point.z <= Max.z) + end + + -- Method to clip a line segment against the box + -- [Port] returns p0_clipped, p1_clipped, result (clipped points are nil when result is false) + function BoxMT:ClipLineSegment(p0, p1) + -- Check if the line segment is completely inside the box + if self:Contains(p0) and self:Contains(p1) then + return p0:Copy(), p1:Copy(), true + end + + -- Perform Liang-Barsky 3D clipping + local t0 = 0.0 + local t1 = 1.0 + local d = p1 - p0 + + -- Define the clipping boundaries + local xmin, xmax = self.Min.x, self.Max.x + local ymin, ymax = self.Min.y, self.Max.y + local zmin, zmax = self.Min.z, self.Max.z + + -- Lambda function to update t0 and t1 + local function update(p, q) + if p == 0.0 then + if q < 0.0 then + return false -- Line is parallel and outside the boundary + else + return true -- Line is parallel and inside or coincident with boundary + end + end + local r = q / p + if p < 0.0 then + if r > t1 then return false end -- Line is outside + if r > t0 then t0 = r end -- Move up t0 + else + if r < t0 then return false end -- Line is outside + if r < t1 then t1 = r end -- Move down t1 + end + return true + end + + -- Clip against each boundary + if not update(-d.x, p0.x - xmin) then return nil, nil, false end -- Left + if not update(d.x, xmax - p0.x) then return nil, nil, false end -- Right + if not update(-d.y, p0.y - ymin) then return nil, nil, false end -- Bottom + if not update(d.y, ymax - p0.y) then return nil, nil, false end -- Top + if not update(-d.z, p0.z - zmin) then return nil, nil, false end -- Near + if not update(d.z, zmax - p0.z) then return nil, nil, false end -- Far + + -- Compute clipped points + return p0 + d * t0, p0 + d * t1, true + end + + -- ImPlot3DRange: Represents a 1D range with min and max values + local RangeMT = {} + RangeMT.__index = RangeMT + function ImPlot3D.ImPlot3DRange(min, max) + return setmetatable({ Min = min or 0.0, Max = max or 0.0 }, RangeMT) + end + -- Expand range to include value + function RangeMT:Expand(value) + self.Min = math.min(self.Min, value) + self.Max = math.max(self.Max, value) + end + -- Check if value is within range + function RangeMT:Contains(value) return value >= self.Min and value <= self.Max end + -- Get range size + function RangeMT:Size() return self.Max - self.Min end + + -- ImPlot3DQuat: Quaternion for representing 3D rotations + local QuatMT = {} + QuatMT.__index = QuatMT + -- [Port] ImPlot3DQuat() / (x, y, z, w) / (angle, axis) constructor overloads + local function ImPlot3DQuat(a, b, c, d) + if type(b) == "table" then + -- Construct quaternion from angle-axis representation (angle in radians) + local half_angle = a * 0.5 + local s = sin(half_angle) + return setmetatable({ x = s * b.x, y = s * b.y, z = s * b.z, w = cos(half_angle) }, QuatMT) + end + if a == nil then + return setmetatable({ x = 0.0, y = 0.0, z = 0.0, w = 1.0 }, QuatMT) + end + return setmetatable({ x = a, y = b, z = c, w = d }, QuatMT) + end + -- [Port] callable table so statics work as ImPlot3D.ImPlot3DQuat.FromTwoVectors(...) (also reachable via instances) + ImPlot3D.ImPlot3DQuat = setmetatable({}, { + __index = QuatMT, + __call = function(_, ...) return ImPlot3DQuat(...) end, + }) + + -- Create quaternion that rotates from v0 to v1 + function QuatMT.FromTwoVectors(v0, v1) + local q = ImPlot3DQuat() + + -- Compute the dot product and lengths of the vectors + local dot = v0:Dot(v1) + local length_v0 = v0:Length() + local length_v1 = v1:Length() + + -- Normalize the dot product + local normalized_dot = dot / (length_v0 * length_v1) + + -- Handle edge cases: if vectors are very close or identical + local epsilon = 1e-6 + if abs(normalized_dot - 1.0) < epsilon then + -- v0 and v1 are nearly identical; return an identity quaternion + return q + end + + -- Handle edge case: if vectors are opposite + if abs(normalized_dot + 1.0) < epsilon then + -- v0 and v1 are opposite; choose an arbitrary orthogonal axis + local arbitrary_axis + if abs(v0.x) > abs(v0.z) then + arbitrary_axis = ImPlot3DPoint(-v0.y, v0.x, 0.0) + else + arbitrary_axis = ImPlot3DPoint(0.0, -v0.z, v0.y) + end + arbitrary_axis:Normalize() + q.x = arbitrary_axis.x + q.y = arbitrary_axis.y + q.z = arbitrary_axis.z + q.w = 0.0 + return q + end + + -- General case + local axis = v0:Cross(v1) + axis:Normalize() + local angle = acos(normalized_dot) + local half_angle = angle * 0.5 + local s = sin(half_angle) + q.x = s * axis.x + q.y = s * axis.y + q.z = s * axis.z + q.w = cos(half_angle) + + return q + end + + -- Create quaternion from elevation and azimuth angles (in radians) + function QuatMT.FromElAz(elevation, azimuth) + -- Create quaternions for azimuth and elevation + local azimuth_quat = ImPlot3DQuat(azimuth, ImPlot3DPoint(0.0, 0.0, 1.0)) -- Rotate around Z-axis + local elevation_quat = ImPlot3DQuat(elevation, ImPlot3DPoint(1.0, 0.0, 0.0)) -- Rotate around X-axis + local zero_quat = ImPlot3DQuat(-math.pi / 2, ImPlot3DPoint(1.0, 0.0, 0.0)) -- Rotate to zero azimuth/elevation orientation + + -- Combine rotations + return elevation_quat * zero_quat * azimuth_quat + end + + -- Get quaternion length + function QuatMT:Length() return sqrt(self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w) end + + -- Get normalized quaternion + function QuatMT:Normalized() + local l = self:Length() + return ImPlot3DQuat(self.x / l, self.y / l, self.z / l, self.w / l) + end + + -- Conjugate of the quaternion + function QuatMT:Conjugate() return ImPlot3DQuat(-self.x, -self.y, -self.z, self.w) end + + -- Inverse of the quaternion + function QuatMT:Inverse() + local l_squared = self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w + return ImPlot3DQuat(-self.x / l_squared, -self.y / l_squared, -self.z / l_squared, self.w / l_squared) + end + + -- Binary operators + -- [Port] operator*(ImPlot3DQuat) quaternion multiplication / operator*(ImPlot3DPoint) rotate a 3D point + QuatMT.__mul = function(q, rhs) + local x, y, z, w = q.x, q.y, q.z, q.w + if getmetatable(rhs) == PointMT then + -- Extract vector part of the quaternion + local qv = ImPlot3DPoint(x, y, z) + + -- Compute the cross products needed for rotation + local uv = qv:Cross(rhs) -- uv = qv x point + local uuv = qv:Cross(uv) -- uuv = qv x uv + + -- Compute the rotated vector + return rhs + (uv * w * 2.0) + (uuv * 2.0) + end + return ImPlot3DQuat(w * rhs.x + x * rhs.w + y * rhs.z - z * rhs.y, w * rhs.y - x * rhs.z + y * rhs.w + z * rhs.x, + w * rhs.z + x * rhs.y - y * rhs.x + z * rhs.w, w * rhs.w - x * rhs.x - y * rhs.y - z * rhs.z) + end + + -- Normalize the quaternion in place + function QuatMT:Normalize() + local l = self:Length() + self.x =self.x/ l + self.y =self.y/ l + self.z =self.z/ l + self.w =self.w/ l + return self + end + + -- Comparison operators + QuatMT.__eq = function(a, b) return a.x == b.x and a.y == b.y and a.z == b.z and a.w == b.w end + + QuatMT.__tostring = function(q) return string.format("ImPlot3DQuat(%g, %g, %g, %g)", q.x, q.y, q.z, q.w) end + + -- Spherical linear interpolation between two quaternions (t in [0,1]) + function QuatMT.Slerp(q1, q2, t) + -- Clamp t to [0, 1] + t = math.clamp(t, 0.0, 1.0) + + -- Compute the dot product (cosine of the angle between quaternions) + local dot = q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w + + -- If the dot product is negative, negate one quaternion to take the shorter path + local q2_ = q2 + if dot < 0.0 then + q2_ = ImPlot3DQuat(-q2.x, -q2.y, -q2.z, -q2.w) + dot = -dot + end + + -- If the quaternions are very close, use linear interpolation to avoid numerical instability + if dot > 0.9995 then + return ImPlot3DQuat(q1.x + t * (q2_.x - q1.x), q1.y + t * (q2_.y - q1.y), q1.z + t * (q2_.z - q1.z), q1.w + t * (q2_.w - q1.w)):Normalized() + end + + -- Compute the angle and the interpolation factors + local theta_0 = acos(dot) -- Angle between input quaternions + local theta = theta_0 * t -- Interpolated angle + local sin_theta = sin(theta) -- Sine of interpolated angle + local sin_theta_0 = sin(theta_0) -- Sine of original angle + + local s1 = cos(theta) - dot * sin_theta / sin_theta_0 + local s2 = sin_theta / sin_theta_0 + + -- Interpolate and return the result + return ImPlot3DQuat(s1 * q1.x + s2 * q2_.x, s1 * q1.y + s2 * q2_.y, s1 * q1.z + s2 * q2_.z, s1 * q1.w + s2 * q2_.w) + end + + -- Get quaternion dot product + function QuatMT:Dot(rhs) return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z + self.w * rhs.w end + end + + -------------------------------------------------------------------------- + -- [SECTION] ImPlot3DStyle + -------------------------------------------------------------------------- + do + function ImPlot3D.ImPlot3DStyle() + local s = {} + -- Item style + s.LineWeight = 1.0 + s.Marker = ImPlot3D.ImPlot3DMarker.None + s.MarkerSize = 4.0 + s.FillAlpha = 1.0 + -- Plot style + s.PlotDefaultSize = ImVec2(400, 400) + s.PlotMinSize = ImVec2(200, 200) + s.PlotPadding = ImVec2(10, 10) + s.LabelPadding = ImVec2(5, 5) + s.ViewScaleFactor = 1.0 + -- Legend style + s.LegendPadding = ImVec2(10, 10) + s.LegendInnerPadding = ImVec2(5, 5) + s.LegendSpacing = ImVec2(5, 0) + -- Colors + -- [Port] Colors is keyed by 0-based ImPlot3DCol values: Colors[ImPlot3DCol.FrameBg] + s.Colors = {} + ImPlot3D.StyleColorsAuto(s) + s.Colormap = ImPlot3D.ImPlot3DColormap.Deep + return s + end + end + + -------------------------------------------------------------------------- + -- [SECTION] Styles + -------------------------------------------------------------------------- + do + -- [Port] ImPlot3DStyleVarInfo: { Type, Count, Field }, keyed by 0-based ImPlot3DStyleVar + local GPlot3DStyleVarInfo = { + -- Item style + [ImPlot3DStyleVar.LineWeight] = { Type = "Float", Count = 1, Field = "LineWeight" }, + [ImPlot3DStyleVar.Marker] = { Type = "S32", Count = 1, Field = "Marker" }, + [ImPlot3DStyleVar.MarkerSize] = { Type = "Float", Count = 1, Field = "MarkerSize" }, + [ImPlot3DStyleVar.FillAlpha] = { Type = "Float", Count = 1, Field = "FillAlpha" }, + + -- Plot style + [ImPlot3DStyleVar.PlotDefaultSize] = { Type = "Float", Count = 2, Field = "PlotDefaultSize" }, + [ImPlot3DStyleVar.PlotMinSize] = { Type = "Float", Count = 2, Field = "PlotMinSize" }, + [ImPlot3DStyleVar.PlotPadding] = { Type = "Float", Count = 2, Field = "PlotPadding" }, + [ImPlot3DStyleVar.LabelPadding] = { Type = "Float", Count = 2, Field = "LabelPadding" }, + [ImPlot3DStyleVar.ViewScaleFactor] = { Type = "Float", Count = 1, Field = "ViewScaleFactor" }, + + -- Legend style + [ImPlot3DStyleVar.LegendPadding] = { Type = "Float", Count = 2, Field = "LegendPadding" }, + [ImPlot3DStyleVar.LegendInnerPadding] = { Type = "Float", Count = 2, Field = "LegendInnerPadding" }, + [ImPlot3DStyleVar.LegendSpacing] = { Type = "Float", Count = 2, Field = "LegendSpacing" }, + } + + local function GetPlotStyleVarInfo(idx) + IM_ASSERT(idx >= 0 and idx < ImPlot3DStyleVar.COUNT) + return GPlot3DStyleVarInfo[idx] + end + + function ImPlot3D.GetStyle() + IM_ASSERT(GImPlot3D ~= nil, "No current context. Did you call ImPlot3D::CreateContext() or ImPlot3D::SetCurrentContext()?") + return GImPlot3D.Style + end + function ImPlot3D.SetStyle(style) + -- [Port] copy assignment + local s = table.clone(style) + s.Colors = table.clone(style.Colors) + GImPlot3D.Style = s + end + + -- [Port] C++ `dst ? dst : &ImPlot3D::GetStyle()` + local function StyleOrCurrent(dst) + if dst then return dst end + return ImPlot3D.GetStyle() + end + + function ImPlot3D.StyleColorsAuto(dst) + local style = StyleOrCurrent(dst) + local colors = style.Colors + + colors[ImPlot3DCol.TitleText] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.InlayText] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.FrameBg] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.PlotBg] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.PlotBorder] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.LegendBg] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.LegendBorder] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.LegendText] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisText] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisGrid] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisTick] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBg] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBgHovered] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBgActive] = IMPLOT3D_AUTO_COL() + end + + function ImPlot3D.StyleColorsDark(dst) + local style = StyleOrCurrent(dst) + local colors = style.Colors + + colors[ImPlot3DCol.TitleText] = ImVec4(1.00, 1.00, 1.00, 1.00) + colors[ImPlot3DCol.InlayText] = ImVec4(1.00, 1.00, 1.00, 1.00) + colors[ImPlot3DCol.FrameBg] = ImVec4(1.00, 1.00, 1.00, 0.07) + colors[ImPlot3DCol.PlotBg] = ImVec4(0.00, 0.00, 0.00, 0.50) + colors[ImPlot3DCol.PlotBorder] = ImVec4(0.43, 0.43, 0.50, 0.50) + colors[ImPlot3DCol.LegendBg] = ImVec4(0.08, 0.08, 0.08, 0.94) + colors[ImPlot3DCol.LegendBorder] = ImVec4(0.43, 0.43, 0.50, 0.50) + colors[ImPlot3DCol.LegendText] = ImVec4(1.00, 1.00, 1.00, 1.00) + colors[ImPlot3DCol.AxisText] = ImVec4(1.00, 1.00, 1.00, 1.00) + colors[ImPlot3DCol.AxisGrid] = ImVec4(1.00, 1.00, 1.00, 0.25) + colors[ImPlot3DCol.AxisTick] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBg] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBgHovered] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBgActive] = IMPLOT3D_AUTO_COL() + end + + function ImPlot3D.StyleColorsLight(dst) + local style = StyleOrCurrent(dst) + local colors = style.Colors + + colors[ImPlot3DCol.TitleText] = ImVec4(0.00, 0.00, 0.00, 1.00) + colors[ImPlot3DCol.InlayText] = ImVec4(0.00, 0.00, 0.00, 1.00) + colors[ImPlot3DCol.FrameBg] = ImVec4(1.00, 1.00, 1.00, 1.00) + colors[ImPlot3DCol.PlotBg] = ImVec4(0.42, 0.57, 1.00, 0.13) + colors[ImPlot3DCol.PlotBorder] = ImVec4(0.00, 0.00, 0.00, 0.00) + colors[ImPlot3DCol.LegendBg] = ImVec4(1.00, 1.00, 1.00, 0.98) + colors[ImPlot3DCol.LegendBorder] = ImVec4(0.82, 0.82, 0.82, 0.80) + colors[ImPlot3DCol.LegendText] = ImVec4(0.00, 0.00, 0.00, 1.00) + colors[ImPlot3DCol.AxisText] = ImVec4(0.00, 0.00, 0.00, 1.00) + colors[ImPlot3DCol.AxisGrid] = ImVec4(1.00, 1.00, 1.00, 1.00) + colors[ImPlot3DCol.AxisTick] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBg] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBgHovered] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBgActive] = IMPLOT3D_AUTO_COL() + end + + function ImPlot3D.StyleColorsClassic(dst) + local style = StyleOrCurrent(dst) + local colors = style.Colors + + colors[ImPlot3DCol.TitleText] = ImVec4(0.90, 0.90, 0.90, 1.00) + colors[ImPlot3DCol.InlayText] = ImVec4(0.90, 0.90, 0.90, 1.00) + colors[ImPlot3DCol.FrameBg] = ImVec4(0.43, 0.43, 0.43, 0.39) + colors[ImPlot3DCol.PlotBg] = ImVec4(0.00, 0.00, 0.00, 0.35) + colors[ImPlot3DCol.PlotBorder] = ImVec4(0.50, 0.50, 0.50, 0.50) + colors[ImPlot3DCol.LegendBg] = ImVec4(0.11, 0.11, 0.14, 0.92) + colors[ImPlot3DCol.LegendBorder] = ImVec4(0.50, 0.50, 0.50, 0.50) + colors[ImPlot3DCol.LegendText] = ImVec4(0.90, 0.90, 0.90, 1.00) + colors[ImPlot3DCol.AxisText] = ImVec4(0.90, 0.90, 0.90, 1.00) + colors[ImPlot3DCol.AxisGrid] = ImVec4(0.90, 0.90, 0.90, 0.25) + colors[ImPlot3DCol.AxisTick] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBg] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBgHovered] = IMPLOT3D_AUTO_COL() + colors[ImPlot3DCol.AxisBgActive] = IMPLOT3D_AUTO_COL() + end + + -- [Port] PushStyleColor(idx, ImU32) / PushStyleColor(idx, ImVec4) overloads + function ImPlot3D.PushStyleColor(idx, col) + local gp = GImPlot3D + local b = gp.Style.Colors[idx] + table.insert(gp.ColorModifiers, { Col = idx, BackupValue = ImVec4(b.x, b.y, b.z, b.w) }) + if type(col) == "number" then + gp.Style.Colors[idx] = ImGui.ColorConvertU32ToFloat4(col) + else + gp.Style.Colors[idx] = ImVec4(col.x, col.y, col.z, col.w) + end + end + + function ImPlot3D.PopStyleColor(count) + if count == nil then count = 1 end + local gp = GImPlot3D + IM_ASSERT(count <= #gp.ColorModifiers, "You can't pop more modifiers than have been pushed!") + while count > 0 do + local backup = table.remove(gp.ColorModifiers) + gp.Style.Colors[backup.Col] = backup.BackupValue + count = count - 1 + end + end + + -- [Port] float/int/ImVec2 overloads merged: number -> Count 1 (Float or S32), table -> Count 2. + -- Luau has one number type, so the int overload's float fallback is implicit. + function ImPlot3D.PushStyleVar(idx, val) + local gp = GImPlot3D + local var_info = GetPlotStyleVarInfo(idx) + if type(val) == "number" then + if var_info.Count == 1 then + table.insert(gp.StyleModifiers, { VarIdx = idx, Backup = gp.Style[var_info.Field] }) + gp.Style[var_info.Field] = val + return + end + IM_ASSERT(false, "Called PushStyleVar() float variant but variable is not a float!") + else + if var_info.Type == "Float" and var_info.Count == 2 then + local p = gp.Style[var_info.Field] + table.insert(gp.StyleModifiers, { VarIdx = idx, Backup = ImVec2(p.x, p.y) }) + gp.Style[var_info.Field] = ImVec2(val.x, val.y) + return + end + IM_ASSERT(false, "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!") + end + end + + function ImPlot3D.PopStyleVar(count) + if count == nil then count = 1 end + local gp = GImPlot3D + IM_ASSERT(count <= #gp.StyleModifiers, "You can't pop more modifiers than have been pushed!") + while count > 0 do + local backup = table.remove(gp.StyleModifiers) + local info = GetPlotStyleVarInfo(backup.VarIdx) + gp.Style[info.Field] = backup.Backup + count = count - 1 + end + end + + -- [SECTION] Style Utils + function internal.IsColorAuto(col) + -- [Port] IsColorAuto(ImVec4) / IsColorAuto(ImPlot3DCol) overloads + if type(col) == "number" then col = GImPlot3D.Style.Colors[col] end + return col.w == -1 + end + + function internal.GetAutoColor(idx) + if idx == ImPlot3DCol.TitleText then return ImGui.GetStyleColorVec4(ImGuiCol.Text) end + if idx == ImPlot3DCol.InlayText then return ImGui.GetStyleColorVec4(ImGuiCol.Text) end + if idx == ImPlot3DCol.FrameBg then return ImGui.GetStyleColorVec4(ImGuiCol.FrameBg) end + if idx == ImPlot3DCol.PlotBg then return ImGui.GetStyleColorVec4(ImGuiCol.WindowBg) end + if idx == ImPlot3DCol.PlotBorder then return ImGui.GetStyleColorVec4(ImGuiCol.Border) end + if idx == ImPlot3DCol.LegendBg then return ImGui.GetStyleColorVec4(ImGuiCol.PopupBg) end + if idx == ImPlot3DCol.LegendBorder then return ImGui.GetStyleColorVec4(ImGuiCol.Border) end + if idx == ImPlot3DCol.LegendText then return ImGui.GetStyleColorVec4(ImGuiCol.Text) end + if idx == ImPlot3DCol.AxisText then return ImGui.GetStyleColorVec4(ImGuiCol.Text) end + if idx == ImPlot3DCol.AxisGrid then + local c = ImGui.GetStyleColorVec4(ImGuiCol.Text) + return ImVec4(c.x, c.y, c.z, c.w * 0.25) + end + if idx == ImPlot3DCol.AxisTick then return ImPlot3D.GetStyleColorVec4(ImPlot3DCol.AxisGrid) end + if idx == ImPlot3DCol.AxisBg then return ImVec4(0, 0, 0, 0) end + if idx == ImPlot3DCol.AxisBgHovered then return ImGui.GetStyleColorVec4(ImGuiCol.ButtonHovered) end + if idx == ImPlot3DCol.AxisBgActive then return ImGui.GetStyleColorVec4(ImGuiCol.ButtonActive) end + return IMPLOT3D_AUTO_COL() + end + + local color_names = { + "TitleText", "InlayText", "FrameBg", "PlotBg", "PlotBorder", "LegendBg", "LegendBorder", + "LegendText", "AxisText", "AxisGrid", "AxisTick", "AxisBg", "AxisBgHovered", "AxisBgActive", + } + function internal.GetStyleColorName(idx) + return color_names[idx + 1] -- [Port] 0-based idx + end + + -- Returns white or black text given background color + -- [Port] CalcTextColor(ImVec4) / CalcTextColor(ImU32) overloads + function internal.CalcTextColor(bg) + if type(bg) == "number" then bg = ImGui.ColorConvertU32ToFloat4(bg) end + if (bg.x * 0.299 + bg.y * 0.587 + bg.z * 0.114) > 0.5 then return G.IM_COL32_BLACK end + return G.IM_COL32_WHITE + end + + -- Get color + function ImPlot3D.GetStyleColorVec4(idx) + if internal.IsColorAuto(idx) then return internal.GetAutoColor(idx) end + local c = GImPlot3D.Style.Colors[idx] + return ImVec4(c.x, c.y, c.z, c.w) -- [Port] by-value copy + end + + function ImPlot3D.GetStyleColorU32(idx) return ImGui.ColorConvertFloat4ToU32(ImPlot3D.GetStyleColorVec4(idx)) end + end + + -------------------------------------------------------------------------- + -- [SECTION] Colormap data storage (implot3d_internal.h ImPlot3DColormapData) + -- [Port] ImVectors -> 1-based Lua arrays; offsets/indices stay 0-based values (array[off + idx + 1]). + -- [Port] Text/TextOffsets -> Names[cmap + 1]; ImGuiStorage Map keyed by ImHashStr -> Lua table keyed by name. + -------------------------------------------------------------------------- + do + local band, bor, rshift = bit32.band, bit32.bor, bit32.rshift + + -- Mix color a and b by factor s in [0 256] + local function ImMixU32(a, b, s) + local af = 256 - s + local bf = s + local al = band(a, 0x00ff00ff) + local ah = rshift(band(a, 0xff00ff00), 8) + local bl = band(b, 0x00ff00ff) + local bh = rshift(band(b, 0xff00ff00), 8) + local ml = al * af + bl * bf + local mh = ah * af + bh * bf + return bor(band(mh, 0xff00ff00), rshift(band(ml, 0xff00ff00), 8)) + end + internal.ImMixU32 = ImMixU32 + + local CM = {} + CM.__index = CM + + function internal.ImPlot3DColormapData() + return setmetatable({ + Keys = {}, KeyCounts = {}, KeyOffsets = {}, + Tables = {}, TableSizes = {}, TableOffsets = {}, + Names = {}, Quals = {}, Map = {}, Count = 0, + }, CM) + end + + function CM:Append(name, keys, count, qual) + if self:GetIndex(name) ~= -1 then + return -1 + end + table.insert(self.KeyOffsets, #self.Keys) + table.insert(self.KeyCounts, count) + for i = 1, count do + table.insert(self.Keys, keys[i]) + end + table.insert(self.Names, name) + table.insert(self.Quals, qual) + local idx = self.Count + self.Count = self.Count + 1 + self.Map[name] = idx + self:_AppendTable(idx) + return idx + end + + function CM:_AppendTable(cmap) + local key_count = self:GetKeyCount(cmap) + local koff = self.KeyOffsets[cmap + 1] + local keys = self.Keys + local tables = self.Tables + local off = #tables + table.insert(self.TableOffsets, off) + if self:IsQual(cmap) then + for i = 0, key_count - 1 do + table.insert(tables, keys[koff + i + 1]) + end + table.insert(self.TableSizes, key_count) + else + local max_size = 255 * (key_count - 1) + 1 + for i = 0, key_count - 2 do + for s = 0, 254 do + local a = keys[koff + i + 1] + local b = keys[koff + i + 2] + table.insert(tables, ImMixU32(a, b, s)) + end + end + table.insert(tables, keys[koff + key_count]) + table.insert(self.TableSizes, max_size) + end + end + + function CM:RebuildTables() + table.clear(self.Tables) + table.clear(self.TableSizes) + table.clear(self.TableOffsets) + for i = 0, self.Count - 1 do + self:_AppendTable(i) + end + end + + function CM:IsQual(cmap) return self.Quals[cmap + 1] end + function CM:GetName(cmap) + if cmap < self.Count then return self.Names[cmap + 1] end + return nil + end + function CM:GetIndex(name) + local v = self.Map[name] + if v == nil then return -1 end + return v + end + + -- [Port] GetKeys/GetTable return (array, 0-based offset) instead of a pointer + function CM:GetKeys(cmap) return self.Keys, self.KeyOffsets[cmap + 1] end + function CM:GetKeyCount(cmap) return self.KeyCounts[cmap + 1] end + function CM:GetKeyColor(cmap, idx) return self.Keys[self.KeyOffsets[cmap + 1] + idx + 1] end + function CM:SetKeyColor(cmap, idx, value) + self.Keys[self.KeyOffsets[cmap + 1] + idx + 1] = value + self:RebuildTables() + end + + function CM:GetTable(cmap) return self.Tables, self.TableOffsets[cmap + 1] end + function CM:GetTableSize(cmap) return self.TableSizes[cmap + 1] end + function CM:GetTableColor(cmap, idx) return self.Tables[self.TableOffsets[cmap + 1] + idx + 1] end + + function CM:LerpTable(cmap, t) + local off = self.TableOffsets[cmap + 1] + local siz = self.TableSizes[cmap + 1] + local idx + if self.Quals[cmap + 1] then + idx = math.clamp(math.floor(siz * t), 0, siz - 1) -- [Port] (int) truncation; t >= 0 in practice + else + idx = math.floor((siz - 1) * t + 0.5) + end + return self.Tables[off + idx + 1] + end + end + + -------------------------------------------------------------------------- + -- [SECTION] Context / Context Utils + -------------------------------------------------------------------------- + do + function internal.ImPlot3DContext() + return { + Plots = G.ImPool(function() return internal.ImPlot3DPlot() end), -- ImPool + CurrentPlot = nil, + CurrentItems = nil, + CurrentItem = nil, + NextItemData = internal.ImPlot3DNextItemData(), + Style = ImPlot3D.ImPlot3DStyle(), + ColorModifiers = {}, + StyleModifiers = {}, + ColormapModifiers = {}, + ColormapData = internal.ImPlot3DColormapData(), + } + end + + -- Creates a new ImPlot3D context. Call this after ImGui::CreateContext + function ImPlot3D.CreateContext() + local ctx = internal.ImPlot3DContext() + if GImPlot3D == nil then + ImPlot3D.SetCurrentContext(ctx) + end + internal.InitializeContext(ctx) + return ctx + end + + -- Destroys an ImPlot3D context. Call this before ImGui::DestroyContext. nullptr = destroy current context + function ImPlot3D.DestroyContext(ctx) + if ctx == nil then + ctx = GImPlot3D + end + if GImPlot3D == ctx then + ImPlot3D.SetCurrentContext(nil) + end + end + + -- Returns the current ImPlot3D context. nullptr if no context has been set + function ImPlot3D.GetCurrentContext() return GImPlot3D end + + -- Sets the current ImPlot3D context + function ImPlot3D.SetCurrentContext(ctx) GImPlot3D = ctx end + + local function IM_RGB(r, g, b) return IM_COL32(r, g, b, 255) end + + -- [Port] {name, qual, keys} in IMPLOT3D_APPEND_CMAP order + local cmaps = { + { "Deep", true, { 4289753676, 4283598045, 4285048917, 4283584196, 4289950337, 4284512403, 4291005402, 4287401100, 4285839820, 4291671396 } }, + { "Dark", true, { 4280031972, 4290281015, 4283084621, 4288892568, 4278222847, 4281597951, 4280833702, 4290740727, 4288256409 } }, + { "Pastel", true, { 4289639675, 4293119411, 4291161036, 4293184478, 4289124862, 4291624959, 4290631909, 4293712637, 4294111986 } }, + { "Paired", true, { 4293119554, 4290017311, 4287291314, 4281114675, 4288256763, 4280031971, + 4285513725, 4278222847, 4292260554, 4288298346, 4288282623, 4280834481 } }, + { "Viridis", false, { 4283695428, 4285867080, 4287054913, 4287455029, 4287526954, 4287402273, + 4286883874, 4285579076, 4283552122, 4280737725, 4280674301 } }, + { "Plasma", false, { 4287039501, 4288480321, 4289200234, 4288941455, 4287638193, 4286072780, + 4284638433, 4283139314, 4281771772, 4280667900, 4280416752 } }, + { "Hot", false, { 4278190144, 4278190208, 4278190271, 4278190335, 4278206719, 4278223103, + 4278239231, 4278255615, 4283826175, 4289396735, 4294967295 } }, + { "Cool", false, { 4294967040, 4294960666, 4294954035, 4294947661, 4294941030, 4294934656, + 4294928025, 4294921651, 4294915020, 4294908646, 4294902015 } }, + { "Pink", false, { 4278190154, 4282532475, 4284308894, 4285690554, 4286879686, 4287870160, + 4288794330, 4289651940, 4291685869, 4293392118, 4294967295 } }, + { "Jet", false, { 4289331200, 4294901760, 4294923520, 4294945280, 4294967040, 4289396565, + 4283826090, 4278255615, 4278233855, 4278212095, 4278190335 } }, + { "Twilight", false, { IM_RGB(226, 217, 226), IM_RGB(166, 191, 202), IM_RGB(109, 144, 192), IM_RGB(95, 88, 176), + IM_RGB(83, 30, 124), IM_RGB(47, 20, 54), IM_RGB(100, 25, 75), IM_RGB(159, 60, 80), + IM_RGB(192, 117, 94), IM_RGB(208, 179, 158), IM_RGB(226, 217, 226) } }, + { "RdBu", false, { IM_RGB(103, 0, 31), IM_RGB(178, 24, 43), IM_RGB(214, 96, 77), IM_RGB(244, 165, 130), + IM_RGB(253, 219, 199), IM_RGB(247, 247, 247), IM_RGB(209, 229, 240), IM_RGB(146, 197, 222), + IM_RGB(67, 147, 195), IM_RGB(33, 102, 172), IM_RGB(5, 48, 97) } }, + { "BrBG", false, { IM_RGB(84, 48, 5), IM_RGB(140, 81, 10), IM_RGB(191, 129, 45), IM_RGB(223, 194, 125), + IM_RGB(246, 232, 195), IM_RGB(245, 245, 245), IM_RGB(199, 234, 229), IM_RGB(128, 205, 193), + IM_RGB(53, 151, 143), IM_RGB(1, 102, 94), IM_RGB(0, 60, 48) } }, + { "PiYG", false, { IM_RGB(142, 1, 82), IM_RGB(197, 27, 125), IM_RGB(222, 119, 174), IM_RGB(241, 182, 218), + IM_RGB(253, 224, 239), IM_RGB(247, 247, 247), IM_RGB(230, 245, 208), IM_RGB(184, 225, 134), + IM_RGB(127, 188, 65), IM_RGB(77, 146, 33), IM_RGB(39, 100, 25) } }, + { "Spectral", false, { IM_RGB(158, 1, 66), IM_RGB(213, 62, 79), IM_RGB(244, 109, 67), IM_RGB(253, 174, 97), + IM_RGB(254, 224, 139), IM_RGB(255, 255, 191), IM_RGB(230, 245, 152), IM_RGB(171, 221, 164), + IM_RGB(102, 194, 165), IM_RGB(50, 136, 189), IM_RGB(94, 79, 162) } }, + { "Greys", false, { G.IM_COL32_WHITE, G.IM_COL32_BLACK } }, + } + + -- Initialize ImPlot3DContext + function internal.InitializeContext(ctx) + internal.ResetContext(ctx) + for _, c in __iter(ipairs(cmaps)) do + ctx.ColormapData:Append(c[1], c[3], #c[3], c[2]) + end + end + + -- Reset ImPlot3DContext + function internal.ResetContext(ctx) + ctx.CurrentPlot = nil + ctx.CurrentItems = nil + ctx.CurrentItem = nil + ctx.Style = ImPlot3D.ImPlot3DStyle() + end + end + + -------------------------------------------------------------------------- + -- [SECTION] Colormaps + -------------------------------------------------------------------------- + do + local IMPLOT3D_AUTO = ImPlot3D.IMPLOT3D_AUTO + + -- [Port] ImVec4* / ImU32* overloads: `colormap` is a 1-based array of ImVec4 or ImU32; size defaults to #colormap + function ImPlot3D.AddColormap(name, colormap, size, qual) + local gp = GImPlot3D + size = size or #colormap + if qual == nil then qual = true end + IM_ASSERT(size > 1, "The colormap size must be greater than 1!") + IM_ASSERT(gp.ColormapData:GetIndex(name) == -1, "The colormap name has already been used!") + local buffer = table.create(size) + for i = 1, size do + local c = colormap[i] + if type(c) == "number" then + buffer[i] = c + else + buffer[i] = ImGui.ColorConvertFloat4ToU32(c) + end + end + return gp.ColormapData:Append(name, buffer, size, qual) + end + + function ImPlot3D.GetColormapCount() return GImPlot3D.ColormapData.Count end + + function ImPlot3D.GetColormapName(colormap) return GImPlot3D.ColormapData:GetName(colormap) end + + function ImPlot3D.GetColormapIndex(name) return GImPlot3D.ColormapData:GetIndex(name) end + + -- [Port] PushColormap(ImPlot3DColormap) / PushColormap(const char*) overloads + function ImPlot3D.PushColormap(colormap) + local gp = GImPlot3D + if type(colormap) == "string" then + local idx = gp.ColormapData:GetIndex(colormap) + IM_ASSERT(idx ~= -1, "The colormap name is invalid!") + colormap = idx + end + IM_ASSERT(colormap >= 0 and colormap < gp.ColormapData.Count, "The colormap index is invalid!") + table.insert(gp.ColormapModifiers, gp.Style.Colormap) + gp.Style.Colormap = colormap + end + + function ImPlot3D.PopColormap(count) + if count == nil then count = 1 end + local gp = GImPlot3D + IM_ASSERT(count <= #gp.ColormapModifiers, "You can't pop more modifiers than have been pushed!") + while count > 0 do + gp.Style.Colormap = table.remove(gp.ColormapModifiers) + count = count - 1 + end + end + + function internal.NextColormapColorU32() + local gp = GImPlot3D + IM_ASSERT(gp.CurrentItems ~= nil, "NextColormapColor() needs to be called between BeginPlot() and EndPlot()!") + local idx = gp.CurrentItems.ColormapIdx % gp.ColormapData:GetKeyCount(gp.Style.Colormap) + local col = gp.ColormapData:GetKeyColor(gp.Style.Colormap, idx) + gp.CurrentItems.ColormapIdx = gp.CurrentItems.ColormapIdx + 1 + return col + end + + function ImPlot3D.NextColormapColor() return ImGui.ColorConvertU32ToFloat4(internal.NextColormapColorU32()) end + + local function ResolveCmap(gp, cmap) + if cmap == nil or cmap == IMPLOT3D_AUTO then cmap = gp.Style.Colormap end + IM_ASSERT(cmap >= 0 and cmap < gp.ColormapData.Count, "Invalid colormap index!") + return cmap + end + + function ImPlot3D.GetColormapSize(cmap) + local gp = GImPlot3D + cmap = ResolveCmap(gp, cmap) + return gp.ColormapData:GetKeyCount(cmap) + end + + function internal.GetColormapColorU32(idx, cmap) + local gp = GImPlot3D + cmap = ResolveCmap(gp, cmap) + idx = idx % gp.ColormapData:GetKeyCount(cmap) + return gp.ColormapData:GetKeyColor(cmap, idx) + end + + function ImPlot3D.GetColormapColor(idx, cmap) return ImGui.ColorConvertU32ToFloat4(internal.GetColormapColorU32(idx, cmap)) end + + function internal.SampleColormapU32(t, cmap) + local gp = GImPlot3D + cmap = ResolveCmap(gp, cmap) + return gp.ColormapData:LerpTable(cmap, t) + end + + function ImPlot3D.SampleColormap(t, cmap) return ImGui.ColorConvertU32ToFloat4(internal.SampleColormapU32(t, cmap)) end + end + + -------------------------------------------------------------------------- + -- [SECTION] ImPlot3DTicker, Formatter, Locator + -- [Port] ImPlot3DFormatter is `function(value, data) -> string` (no char buffer). + -------------------------------------------------------------------------- + do + -- Tick mark info + function internal.ImPlot3DTick(value, major, show_label) + return { PlotPos = value, Major = major, ShowLabel = show_label, LabelSize = ImVec2(0, 0), TextOffset = -1, Idx = 0, Label = nil } + end + + local Ticker = {} + Ticker.__index = Ticker + + -- Collection of ticks + -- [Port] TextBuffer replaced by per-tick Label strings; TextOffset kept (0 when labelled) for parity. + function internal.ImPlot3DTicker() return setmetatable({ Ticks = {} }, Ticker) end + + -- [Port] AddTick(value, major, show_label, label) / (..., formatter, data) / (tick) overloads + function Ticker:AddTick(value, major, show_label, fmt, data) + local tick + if type(value) == "table" then + tick = value + else + tick = internal.ImPlot3DTick(value, major, show_label) + local label + if show_label and type(fmt) == "string" then + label = fmt + elseif show_label and fmt ~= nil then + label = fmt(tick.PlotPos, data) + end + if label ~= nil then + tick.TextOffset = 0 + tick.Label = label + tick.LabelSize = ImGui.CalcTextSize(label) + end + end + tick.Idx = #self.Ticks + table.insert(self.Ticks, tick) + return tick + end + + -- [Port] accepts 0-based index or tick + function Ticker:GetText(idx) + if type(idx) == "table" then idx = idx.Idx end + return self.Ticks[idx + 1].Label or "" + end + function Ticker:Reset() table.clear(self.Ticks) end + function Ticker:TickCount() return #self.Ticks end + + -- Formatter_Default: data is a printf format string + function internal.Formatter_Default(value, data) return string.format(data, value) end + + local function IM_ROUND(x) return math.floor(x + 0.5) end + + function internal.NiceNum(x, round) + local expv = math.floor(math.log10(x)) + local f = x / 10 ^ expv + local nf + if round then + if f < 1.5 then nf = 1 elseif f < 3 then nf = 2 elseif f < 7 then nf = 5 else nf = 10 end + else + if f <= 1 then nf = 1 elseif f <= 2 then nf = 2 elseif f <= 5 then nf = 5 else nf = 10 end + end + return nf * 10 ^ expv + end + + function internal.Locator_Default(ticker, range, pixels, formatter, formatter_data) + if range.Min == range.Max then return end + local nMinor = math.min(math.max(1, IM_ROUND(pixels / 30.0)), 5) + local nMajor = math.max(2, IM_ROUND(pixels / 80.0)) + local max_ticks_labels = 7 + local nice_range = internal.NiceNum(range:Size() * 0.99, false) + local interval = internal.NiceNum(nice_range / (nMajor - 1), true) + local graphmin = math.floor(range.Min / interval) * interval + local graphmax = math.ceil(range.Max / interval) * interval + local first_major_set = false + local first_major_idx = 0 + local idx0 = ticker:TickCount() -- Ticker may have user custom ticks + local major = graphmin + while major < graphmax + 0.5 * interval do + -- Is this zero? combat zero formatting issues + if major - interval < 0 and major + interval > 0 then major = 0 end + if range:Contains(major) then + if not first_major_set then + first_major_idx = ticker:TickCount() + first_major_set = true + end + ticker:AddTick(major, true, true, formatter, formatter_data) + end + for i = 1, nMinor - 1 do + local minor = major + i * interval / nMinor + if range:Contains(minor) then + ticker:AddTick(minor, false, true, formatter, formatter_data) + end + end + major =major+ interval + end + -- Prune tick labels + if ticker:TickCount() > max_ticks_labels then + for i = first_major_idx - 1, idx0, -2 do ticker.Ticks[i + 1].ShowLabel = false end + for i = first_major_idx + 1, ticker:TickCount() - 1, 2 do ticker.Ticks[i + 1].ShowLabel = false end + end + end + + -- Transforms (implot3d_internal.h) + local DBL_MIN, DBL_EPSILON = internal.DBL_MIN, internal.DBL_EPSILON + local function ImSign(v) return v < 0 and-1 or 1 end + local function Trunc(v) return (v < 0 and{(math.ceil(v) )}or{(math.floor(v) )})[1]end -- [Port] C (int) cast + function internal.TransformForward_Log10(v, _) return math.log10((v <= 0.0 and{DBL_MIN }or{v})[1]) end + function internal.TransformInverse_Log10(v, _) return 10 ^ v end + -- [Port] no math.asinh in Luau: sign-symmetric log form + function internal.TransformForward_SymLog(v, _) + local x = v / 2.0 + local a = math.abs(x) + return 2.0 * ImSign(x) * math.log(a + math.sqrt(a * a + 1)) + end + function internal.TransformInverse_SymLog(v, _) return 2.0 * math.sinh(v / 2.0) end + + -- [Port] returns ok, exp_min, exp_max, exp_step instead of out-params + function internal.CalcLogarithmicExponents(range, pix) + if range.Min * range.Max > 0 then + local nMajor = math.max(2, IM_ROUND(pix * 0.01)) -- TODO: magic numbers + local log_min = math.log10(math.abs(range.Min)) + local log_max = math.log10(math.abs(range.Max)) + local log_a, log_b = math.min(log_min, log_max), math.max(log_min, log_max) + local exp_step = math.max(1, Trunc(Trunc(log_b - log_a) / nMajor)) + local exp_min, exp_max = Trunc(log_a), Trunc(log_b) + if exp_step ~= 1 then + while exp_step % 3 ~= 0 do exp_step =exp_step+ 1 end -- make step size multiple of three + while math.fmod(exp_min, exp_step) ~= 0 do exp_min =exp_min- 1 end -- decrease exp_min until exp_min + N * exp_step will be 0 + end + return true, exp_min, exp_max, exp_step + end + return false, 0, 0, 1 + end + + function internal.AddTicksLogarithmic(range, exp_min, exp_max, exp_step, ticker, formatter, data) + local sign = ImSign(range.Max) + local e = exp_min - exp_step + while e < exp_max + exp_step do + local major1 = sign * 10 ^ e + if major1 >= range.Min - DBL_EPSILON and major1 <= range.Max + DBL_EPSILON then + ticker:AddTick(major1, true, true, formatter, data) + end + for j = 0, exp_step - 1 do + major1 = sign * 10 ^ (e + j) + local interval = (sign * 10 ^ (e + j + 1) - major1) / 9 + for i = 1, (j < exp_step - 1 and 9 or 8) do + local minor = major1 + i * interval + if minor >= range.Min - DBL_EPSILON and minor <= range.Max + DBL_EPSILON then + ticker:AddTick(minor, false, false, formatter, data) + end + end + end + e =e+ exp_step + end + end + + function internal.Locator_Log10(ticker, range, pixels, formatter, formatter_data) + local ok, exp_min, exp_max, exp_step = internal.CalcLogarithmicExponents(range, pixels) + if ok then internal.AddTicksLogarithmic(range, exp_min, exp_max, exp_step, ticker, formatter, formatter_data) end + end + + local function CalcSymLogPixel(plt, range, pixels) + local f = internal.TransformForward_SymLog + local scaleToPixels = pixels / range:Size() + local scaleMin, scaleMax, s = f(range.Min), f(range.Max), f(plt) + local t = (s - scaleMin) / (scaleMax - scaleMin) + plt = range.Min + range:Size() * t + return 0 + scaleToPixels * (plt - range.Min) + end + + function internal.Locator_SymLog(ticker, range, pixels, formatter, formatter_data) + if range.Min >= -1 and range.Max <= 1 then + internal.Locator_Default(ticker, range, pixels, formatter, formatter_data) + elseif range.Min * range.Max < 0 then -- cross zero + local pix_min, pix_max = 0, pixels + local pix_p1 = CalcSymLogPixel(1, range, pixels) + local pix_n1 = CalcSymLogPixel(-1, range, pixels) + local rp, rn = ImPlot3D.ImPlot3DRange(1, range.Max), ImPlot3D.ImPlot3DRange(range.Min, -1) + local _, exp_min_p, exp_max_p, exp_step_p = internal.CalcLogarithmicExponents(rp, math.abs(pix_max - pix_p1)) + local _, exp_min_n, exp_max_n, exp_step_n = internal.CalcLogarithmicExponents(rn, math.abs(pix_n1 - pix_min)) + local exp_step = math.max(exp_step_n, exp_step_p) + ticker:AddTick(0, true, true, formatter, formatter_data) + internal.AddTicksLogarithmic(rp, exp_min_p, exp_max_p, exp_step, ticker, formatter, formatter_data) + internal.AddTicksLogarithmic(rn, exp_min_n, exp_max_n, exp_step, ticker, formatter, formatter_data) + else + internal.Locator_Log10(ticker, range, pixels, formatter, formatter_data) + end + end + + -- [Port] values/labels are 1-based arrays + function internal.AddTicksCustom(values, labels, n, ticker, formatter, data) + for i = 1, n do + if labels ~= nil then + ticker:AddTick(values[i], false, true, labels[i]) + else + ticker:AddTick(values[i], false, true, formatter, data) + end + end + end + end + + -------------------------------------------------------------------------- + -- [SECTION] ImPlot3DAxis + -- [Port] ImPlot3DTransform is `function(value, data) -> number`. + -------------------------------------------------------------------------- + do + local ImPlot3DRange = ImPlot3D.ImPlot3DRange + local AxisFlags = ImPlot3D.ImPlot3DAxisFlags + local Cond = ImPlot3D.ImPlot3DCond + local ImHasFlag, ImNanOrInf = internal.ImHasFlag, internal.ImNanOrInf + local ImConstrainNan, ImConstrainInf = internal.ImConstrainNan, internal.ImConstrainInf + local HUGE_VAL = math.huge + + local Axis = {} + Axis.__index = Axis + + -- Holds axis information + function internal.ImPlot3DAxis() + return setmetatable({ + Flags = AxisFlags.None, PreviousFlags = AxisFlags.None, + Range = ImPlot3DRange(0.0, 1.0), RangeCond = Cond.None, + NDCScale = 1.0, Scale = ImPlot3D.ImPlot3DScale.Linear, + Label = "", -- [Port] ImGuiTextBuffer -> string + Ticker = internal.ImPlot3DTicker(), + Formatter = nil, FormatterData = nil, Locator = nil, ShowDefaultTicks = true, + TransformForward = nil, TransformInverse = nil, TransformData = nil, + ScaledRange = ImPlot3DRange(), + FitThisFrame = true, FitExtents = ImPlot3DRange(HUGE_VAL, -HUGE_VAL), + ConstraintRange = ImPlot3DRange(-HUGE_VAL, HUGE_VAL), + ConstraintZoom = ImPlot3DRange(internal.DBL_MIN, HUGE_VAL), + Hovered = false, Held = false, + ColorBg = 0, ColorHov = 0, ColorAct = 0, -- IM_COL32_BLACK_TRANS + }, Axis) + end + + function Axis:Reset() + self.RangeCond = Cond.None + self.Scale = ImPlot3D.ImPlot3DScale.Linear + self.TransformForward, self.TransformInverse, self.TransformData = nil, nil, nil + self.Ticker:Reset() + self.Formatter, self.FormatterData, self.Locator = nil, nil, nil + self.ShowDefaultTicks = true + self.FitExtents = ImPlot3DRange(HUGE_VAL, -HUGE_VAL) + self.ConstraintRange = ImPlot3DRange(-HUGE_VAL, HUGE_VAL) + self.ConstraintZoom = ImPlot3DRange(internal.DBL_MIN, HUGE_VAL) + end + + function Axis:SetRange(v1, v2) + v1 = ImConstrainNan(ImConstrainInf(v1)) + v2 = ImConstrainNan(ImConstrainInf(v2)) + self.Range.Min = math.min(v1, v2) + self.Range.Max = math.max(v1, v2) + self:Constrain() + self:UpdateTransformCache() + end + + function Axis:SetMin(_min, force) + if not force and self:IsLockedMin() then return false end + _min = ImConstrainNan(ImConstrainInf(_min)) + -- Constraints + if _min < self.ConstraintRange.Min then _min = self.ConstraintRange.Min end + local zoom = self.Range.Max - _min + if zoom < self.ConstraintZoom.Min then _min = self.Range.Max - self.ConstraintZoom.Min end + if zoom > self.ConstraintZoom.Max then _min = self.Range.Max - self.ConstraintZoom.Max end + -- Ensure min is less than max + if _min >= self.Range.Max then return false end + self.Range.Min = _min + self:UpdateTransformCache() + return true + end + + function Axis:SetMax(_max, force) + if not force and self:IsLockedMax() then return false end + _max = ImConstrainNan(ImConstrainInf(_max)) + -- Constraints + if _max > self.ConstraintRange.Max then _max = self.ConstraintRange.Max end + local zoom = _max - self.Range.Min + if zoom < self.ConstraintZoom.Min then _max = self.Range.Min + self.ConstraintZoom.Min end + if zoom > self.ConstraintZoom.Max then _max = self.Range.Min + self.ConstraintZoom.Max end + -- Ensure max is greater than min + if _max <= self.Range.Min then return false end + self.Range.Max = _max + self:UpdateTransformCache() + return true + end + + function Axis:Constrain() + local r, cr, cz = self.Range, self.ConstraintRange, self.ConstraintZoom + r.Min = ImConstrainNan(ImConstrainInf(r.Min)) + r.Max = ImConstrainNan(ImConstrainInf(r.Max)) + if r.Min < cr.Min then r.Min = cr.Min end + if r.Max > cr.Max then r.Max = cr.Max end + local zoom = r:Size() + if zoom < cz.Min then + local delta = (cz.Min - zoom) * 0.5 + r.Min =r.Min- delta + r.Max =r.Max+ delta + end + if zoom > cz.Max then + local delta = (zoom - cz.Max) * 0.5 + r.Min =r.Min+ delta + r.Max =r.Max- delta + end + if r.Max <= r.Min then r.Max = r.Min + internal.DBL_EPSILON end + end + + function Axis:UpdateTransformCache() + if self.TransformForward ~= nil then + self.ScaledRange.Min = self.TransformForward(self.Range.Min, self.TransformData) + self.ScaledRange.Max = self.TransformForward(self.Range.Max, self.TransformData) + else + self.ScaledRange.Min = self.Range.Min + self.ScaledRange.Max = self.Range.Max + end + end + + function Axis:PlotToNDC(plt) + if self.TransformForward ~= nil then + local s = self.TransformForward(plt, self.TransformData) + return (s - self.ScaledRange.Min) / (self.ScaledRange.Max - self.ScaledRange.Min) + end + return (plt - self.Range.Min) / (self.Range.Max - self.Range.Min) + end + + function Axis:NDCToPlot(t) + if self.TransformInverse ~= nil then + local s = t * (self.ScaledRange.Max - self.ScaledRange.Min) + self.ScaledRange.Min + return self.TransformInverse(s, self.TransformData) + end + return self.Range.Min + t * (self.Range.Max - self.Range.Min) + end + + function Axis:IsRangeLocked() return self.RangeCond == Cond.Always end + function Axis:IsLockedMin() return self:IsRangeLocked() or ImHasFlag(self.Flags, AxisFlags.LockMin) end + function Axis:IsLockedMax() return self:IsRangeLocked() or ImHasFlag(self.Flags, AxisFlags.LockMax) end + function Axis:IsLocked() return self:IsLockedMin() and self:IsLockedMax() end + function Axis:IsInputLockedMin() return self:IsLockedMin() or self:IsAutoFitting() end + function Axis:IsInputLockedMax() return self:IsLockedMax() or self:IsAutoFitting() end + function Axis:IsInputLocked() return self:IsLocked() or self:IsAutoFitting() end + + function Axis:IsPanLocked(increasing) + if ImHasFlag(self.Flags, AxisFlags.PanStretch) then + return self:IsInputLocked() + end + if self:IsLockedMin() or self:IsLockedMax() or self:IsAutoFitting() then return false end + if increasing then return self.Range.Max == self.ConstraintRange.Max end + return self.Range.Min == self.ConstraintRange.Min + end + + function Axis:SetLabel(label) + -- [Port] FindRenderedTextEnd: label text up to "##" + if label and (string.find(label, "##", 1, true) or #label + 1) > 1 then + self.Label = label + else + self.Label = "" + end + end + function Axis:GetLabel() return self.Label end + + -- By default, the axis span from NDC -0.5 to 0.5, so size is 1.0 (scaled by NDCScale) + function Axis:NDCSize() return self.NDCScale end + + function Axis:SetAspect(units_per_ndc_unit) + local new_size = units_per_ndc_unit * self:NDCSize() + local delta = (new_size - self.Range:Size()) * 0.5 + local lmin, lmax = self:IsLockedMin(), self:IsLockedMax() + if lmin and lmax then + return + elseif lmin then + self:SetRange(self.Range.Min, self.Range.Max + 2 * delta) + elseif lmax then + self:SetRange(self.Range.Min - 2 * delta, self.Range.Max) + else + self:SetRange(self.Range.Min - delta, self.Range.Max + delta) + end + end + function Axis:GetAspect() return self.Range:Size() / self:NDCSize() end + + function Axis:HasLabel() return self.Label ~= "" and not ImHasFlag(self.Flags, AxisFlags.NoLabel) end + function Axis:HasGridLines() return not ImHasFlag(self.Flags, AxisFlags.NoGridLines) end + function Axis:HasTickLabels() return not ImHasFlag(self.Flags, AxisFlags.NoTickLabels) end + function Axis:HasTickMarks() return not ImHasFlag(self.Flags, AxisFlags.NoTickMarks) end + function Axis:IsAutoFitting() return ImHasFlag(self.Flags, AxisFlags.AutoFit) end + + function Axis:ExtendFit(value) + -- Only extend fit with values within the constraint range (log scale ignores <= 0) + if not ImNanOrInf(value) and value >= self.ConstraintRange.Min and value <= self.ConstraintRange.Max then + self.FitExtents.Min = math.min(self.FitExtents.Min, value) + self.FitExtents.Max = math.max(self.FitExtents.Max, value) + end + end + + function Axis:ApplyFit() + if not self:IsLockedMin() and not ImNanOrInf(self.FitExtents.Min) then self.Range.Min = self.FitExtents.Min end + if not self:IsLockedMax() and not ImNanOrInf(self.FitExtents.Max) then self.Range.Max = self.FitExtents.Max end + if internal.ImAlmostEqual(self.Range.Min, self.Range.Max) then +do local __DARKLUA_VAR= self.Range __DARKLUA_VAR.Max =__DARKLUA_VAR.Max+ 0.5 +end do local __DARKLUA_VAR0= self.Range __DARKLUA_VAR0.Min =__DARKLUA_VAR0.Min- 0.5 +end end + self:Constrain() + self:UpdateTransformCache() + self.FitExtents.Min = HUGE_VAL + self.FitExtents.Max = -HUGE_VAL + end + end + + -------------------------------------------------------------------------- + -- [SECTION] ImPlot3DLegend, ImPlot3DItemGroup (data only), ImPlot3DPlot + -------------------------------------------------------------------------- + do + local P, Q = ImPlot3D.ImPlot3DPoint, ImPlot3D.ImPlot3DQuat + local ImHasFlag, ImNanOrInf = internal.ImHasFlag, internal.ImNanOrInf + local ImRect = G.ImRect + + -- Holds legend state + function internal.ImPlot3DLegend() + local loc = ImPlot3D.ImPlot3DLocation.NorthWest + return { + Flags = 0, PreviousFlags = 0, Location = loc, PreviousLocation = loc, + Scroll = ImVec2(0, 0), Indices = {}, LabelList = {}, -- [Port] Labels text buffer -> LabelList + Rect = ImRect(), RectClamped = ImRect(), Hovered = false, Held = false, + } + end + + -- Holds items + -- [Port] item methods live in internal.ItemGroup (GetItem, GetOrAddItem, ...) + function internal.ImPlot3DItemGroup() + return { ID = 0, ItemPool = G.ImPool(function() return internal.ImPlot3DItem() end), Legend = internal.ImPlot3DLegend(), ColormapIdx = 0, MarkerIdx = 0 } + end + + local Plot = {} + Plot.__index = Plot + + -- Holds plot state information that must persist after EndPlot + function internal.ImPlot3DPlot() + local rot = Q(0.0, 0.0, 0.0, 1.0) + return setmetatable({ + ID = 0, Flags = 0, PreviousFlags = 0, Title = "", + JustCreated = true, Initialized = false, + FrameRect = ImRect(), CanvasRect = ImRect(), PlotRect = ImRect(), + InitialRotation = Q(-0.513269, -0.212596, -0.318184, 0.76819), + Rotation = rot, RotationCond = ImPlot3D.ImPlot3DCond.None, + Axes = { [0] = internal.ImPlot3DAxis(), internal.ImPlot3DAxis(), internal.ImPlot3DAxis() }, -- [Port] 0-based like ImAxis3D + AnimationTime = 0.0, RotationAnimationEnd = rot, + SetupLocked = false, Hovered = false, Held = false, + HeldEdgeIdx = -1, HeldPlaneIdx = -1, DragRotationAxis = P(0.0, 0.0, 0.0), + FitThisFrame = true, + Items = internal.ImPlot3DItemGroup(), + DrawList = internal.ImDrawList3D(), + ContextClick = false, OpenContextThisFrame = false, + }, Plot) + end + + function Plot:SetTitle(title) + if title and (string.find(title, "##", 1, true) or #title + 1) > 1 then self.Title = title else self.Title = "" end + end + function Plot:HasTitle() return self.Title ~= "" and not ImHasFlag(self.Flags, ImPlot3D.ImPlot3DFlags.NoTitle) end + function Plot:GetTitle() return self.Title end + function Plot:IsRotationLocked() return self.RotationCond == ImPlot3D.ImPlot3DCond.Always end + + -- Extends the fit range of all three axes to include the provided point + function Plot:ExtendFit(point) + for i = 0, 2 do + if not ImNanOrInf(point[i]) and self.Axes[i].FitThisFrame then self.Axes[i]:ExtendFit(point[i]) end + end + end + + function Plot:RangeMin() local a = self.Axes return P(a[0].Range.Min, a[1].Range.Min, a[2].Range.Min) end + function Plot:RangeMax() local a = self.Axes return P(a[0].Range.Max, a[1].Range.Max, a[2].Range.Max) end + function Plot:RangeCenter() + local a = self.Axes + return P((a[0].Range.Min + a[0].Range.Max) * 0.5, (a[1].Range.Min + a[1].Range.Max) * 0.5, (a[2].Range.Min + a[2].Range.Max) * 0.5) + end + + function Plot:SetRange(min, max) + self.Axes[0]:SetRange(min.x, max.x) + self.Axes[1]:SetRange(min.y, max.y) + self.Axes[2]:SetRange(min.z, max.z) + end + + -- Constant to convert from NDC coordinates to pixels coordinates + function Plot:GetViewScale() + return math.min(self.PlotRect:GetWidth(), self.PlotRect:GetHeight()) / 1.8 * GImPlot3D.Style.ViewScaleFactor + end + + function Plot:GetBoxScale() return P(self.Axes[0]:NDCSize(), self.Axes[1]:NDCSize(), self.Axes[2]:NDCSize()) end + + -- Applies equal aspect ratio constraint using the specified axis as reference. + function Plot:ApplyEqualAspect(ref_axis) + local aspect = self.Axes[ref_axis]:GetAspect() + for i = 0, 2 do + if i ~= ref_axis and not self.Axes[i]:IsInputLocked() then self.Axes[i]:SetAspect(aspect) end + end + end + + function internal.GetCurrentPlot() return GImPlot3D.CurrentPlot end + function internal.BustPlotCache() GImPlot3D.Plots:Clear() end + end + + -------------------------------------------------------------------------- + -- [SECTION] Setup / Plot Utils (coordinate helpers) + -------------------------------------------------------------------------- + do + local P, Q = ImPlot3D.ImPlot3DPoint, ImPlot3D.ImPlot3DQuat + local Cond, AxisFlags = ImPlot3D.ImPlot3DCond, ImPlot3D.ImPlot3DAxisFlags + local ImHasFlag = internal.ImHasFlag + local IM_PI = math.pi + + local function CurrentPlotForSetup(name) + local gp = GImPlot3D + IM_ASSERT(gp.CurrentPlot ~= nil and not gp.CurrentPlot.SetupLocked, + name .. "() needs to be called after BeginPlot() and before any setup locking functions (e.g. PlotX)!") + return gp.CurrentPlot + end + + local ANIMATION_ANGULAR_VELOCITY = 2 * 3.1415 + function internal.CalcAnimationTime(q0, q1) + -- Compute the angular distance between orientations + local dot_product = math.clamp(q0:Dot(q1), -1.0, 1.0) + return 2.0 * math.acos(math.abs(dot_product)) / ANIMATION_ANGULAR_VELOCITY + end + + function ImPlot3D.SetupAxis(idx, label, flags) + flags = flags or 0 + local axis = CurrentPlotForSetup("SetupAxis").Axes[idx] + if axis.PreviousFlags ~= flags then axis.Flags = flags end + axis.PreviousFlags = flags + axis:SetLabel(label) + end + + function ImPlot3D.SetupAxisLimits(idx, min_lim, max_lim, cond) + cond = cond or Cond.Once + local plot = CurrentPlotForSetup("SetupAxisLimits") + local axis = plot.Axes[idx] + if not plot.Initialized or cond == Cond.Always then + axis:SetRange(min_lim, max_lim) + axis.RangeCond = cond + axis.FitThisFrame = false + -- Apply equal aspect ratio constraint if needed + if ImHasFlag(plot.Flags, ImPlot3D.ImPlot3DFlags.Equal) then plot:ApplyEqualAspect(idx) end + end + end + + function ImPlot3D.SetupAxisFormat(idx, formatter, data) + local axis = CurrentPlotForSetup("SetupAxisFormat").Axes[idx] + -- [Port] string formatter = printf format (C++ users pass Formatter_Default + fmt implicitly) + if type(formatter) == "string" then formatter, data = internal.Formatter_Default, formatter end + axis.Formatter = formatter + axis.FormatterData = data + end + + -- [Port] SetupAxisTicks(idx, values, n_ticks, labels, keep_default) / (idx, v_min, v_max, n_ticks, labels, keep_default) + function ImPlot3D.SetupAxisTicks(idx, a, b, c, d, e) + local values, n_ticks, labels, keep_default + if type(a) == "table" then + values, n_ticks, labels, keep_default = a, b or #a, c, d + else + n_ticks = math.max(c, 2) + values = table.create(n_ticks) + local step = (b - a) / (n_ticks - 1) + for i = 0, n_ticks - 1 do values[i + 1] = a + i * step end -- FillRange + labels, keep_default = d, e + end + local axis = CurrentPlotForSetup("SetupAxisTicks").Axes[idx] + axis.ShowDefaultTicks = keep_default or false + local fmt = axis.Formatter or internal.Formatter_Default + local data = (axis.Formatter and axis.FormatterData) or internal.IMPLOT3D_LABEL_FORMAT + internal.AddTicksCustom(values, labels, n_ticks, axis.Ticker, fmt, data) + end + + -- [Port] SetupAxisScale(idx, ImPlot3DScale) / (idx, forward, inverse, data) overloads + function ImPlot3D.SetupAxisScale(idx, scale, inverse, data) + local axis = CurrentPlotForSetup("SetupAxisScale").Axes[idx] + if type(scale) == "function" then + axis.Scale = ImPlot3D.IMPLOT3D_AUTO + axis.TransformForward, axis.TransformInverse, axis.TransformData = scale, inverse, data + return + end + local Scale = ImPlot3D.ImPlot3DScale + axis.Scale = scale + axis.TransformData = nil + if scale == Scale.Log10 then + axis.TransformForward, axis.TransformInverse = internal.TransformForward_Log10, internal.TransformInverse_Log10 + axis.Locator = internal.Locator_Log10 + axis.ConstraintRange = ImPlot3D.ImPlot3DRange(1.175494351e-38, math.huge) -- FLT_MIN + elseif scale == Scale.SymLog then + axis.TransformForward, axis.TransformInverse = internal.TransformForward_SymLog, internal.TransformInverse_SymLog + axis.Locator = internal.Locator_SymLog + axis.ConstraintRange = ImPlot3D.ImPlot3DRange(-math.huge, math.huge) + else + axis.TransformForward, axis.TransformInverse, axis.Locator = nil, nil, nil + axis.ConstraintRange = ImPlot3D.ImPlot3DRange(-math.huge, math.huge) + end + end + + function ImPlot3D.SetupAxisLimitsConstraints(idx, v_min, v_max) + local axis = CurrentPlotForSetup("SetupAxisLimitsConstraints").Axes[idx] + axis.ConstraintRange.Min, axis.ConstraintRange.Max = v_min, v_max + end + + function ImPlot3D.SetupAxisZoomConstraints(idx, zoom_min, zoom_max) + local axis = CurrentPlotForSetup("SetupAxisZoomConstraints").Axes[idx] + axis.ConstraintZoom.Min, axis.ConstraintZoom.Max = zoom_min, zoom_max + end + + function ImPlot3D.SetupAxes(x_label, y_label, z_label, x_flags, y_flags, z_flags) + ImPlot3D.SetupAxis(0, x_label, x_flags) + ImPlot3D.SetupAxis(1, y_label, y_flags) + ImPlot3D.SetupAxis(2, z_label, z_flags) + end + + function ImPlot3D.SetupAxesLimits(x_min, x_max, y_min, y_max, z_min, z_max, cond) + cond = cond or Cond.Once + ImPlot3D.SetupAxisLimits(0, x_min, x_max, cond) + ImPlot3D.SetupAxisLimits(1, y_min, y_max, cond) + ImPlot3D.SetupAxisLimits(2, z_min, z_max, cond) + if cond == Cond.Once then GImPlot3D.CurrentPlot.FitThisFrame = false end + end + + -- [Port] (elevation, azimuth [deg], animate, cond) / (quat, animate, cond) overloads + function ImPlot3D.SetupBoxRotation(a, b, c, d) + local rotation, animate, cond + if type(a) == "number" then + rotation, animate, cond = Q.FromElAz(a * IM_PI / 180.0, b * IM_PI / 180.0), c, d + else + rotation, animate, cond = a, b, c + end + cond = cond or Cond.Once + local plot = CurrentPlotForSetup("SetupBoxRotation") + if not plot.Initialized or cond == Cond.Always then + if not animate then + plot.Rotation = rotation + plot.AnimationTime = 0.0 -- Force any running rotation animation to stop + else + plot.RotationAnimationEnd = rotation + plot.AnimationTime = internal.CalcAnimationTime(plot.Rotation, plot.RotationAnimationEnd) + end + plot.RotationCond = cond + end + end + + -- [Port] (elevation, azimuth [deg]) / (quat) overloads + function ImPlot3D.SetupBoxInitialRotation(a, b) + local rotation = a + if type(a) == "number" then rotation = Q.FromElAz(a * IM_PI / 180.0, b * IM_PI / 180.0) end + CurrentPlotForSetup("SetupBoxInitialRotation").InitialRotation = rotation + end + + function ImPlot3D.SetupBoxScale(x, y, z) + local plot = CurrentPlotForSetup("SetupBoxScale") + IM_ASSERT(x > 0.0 and y > 0.0 and z > 0.0, "SetupBoxScale() requires all aspect ratios to be greater than 0!") + plot.Axes[0].NDCScale = x + plot.Axes[1].NDCScale = y + plot.Axes[2].NDCScale = z + end + + function ImPlot3D.SetupLegend(location, flags) + flags = flags or 0 + CurrentPlotForSetup("SetupLegend") + local gp = GImPlot3D + IM_ASSERT(gp.CurrentItems ~= nil, "SetupLegend() needs to be called within an itemized context!") + local legend = gp.CurrentItems.Legend + if legend.PreviousLocation ~= location then legend.Location = location end + legend.PreviousLocation = location + if legend.PreviousFlags ~= flags then legend.Flags = flags end + legend.PreviousFlags = flags + end + + -- Convert a position in the plot's NDC to pixels + function internal.NDCToPixels(plot, point) + local center = plot.PlotRect:GetCenter() + local point_pix = plot:GetViewScale() * (plot.Rotation * point) + return ImVec2(point_pix.x + center.x, -point_pix.y + center.y) -- Invert y-axis + end + + -- Convert a position in the plot's coordinate system to NDC + function internal.PlotToNDC(plot, point) + local ndc = P(0, 0, 0) + for i = 0, 2 do + local axis = plot.Axes[i] + local t = axis:PlotToNDC(point[i]) -- normalize to [0, 1] + -- Convert to NDC range [-0.5*NDCScale, 0.5*NDCScale] + ndc[i] = ((ImHasFlag(axis.Flags, AxisFlags.Invert) and{(0.5 - t )}or{(t - 0.5)})[1]) * axis.NDCScale + end + return ndc + end + + -- [Port] body of upstream ImPlot3D::NDCToPlot, split out so it works on an explicit plot + function internal.NDCToPlot(plot, point) + local out = P(0, 0, 0) + for i = 0, 2 do + local axis = plot.Axes[i] + local ndc_range = 0.5 * axis.NDCScale + local t = (ImHasFlag(axis.Flags, AxisFlags.Invert) and{(ndc_range - point[i] )}or{(point[i] + ndc_range +)})[1] out[i] = axis:NDCToPlot(t / axis.NDCScale) + end + return out + end + + function internal.PlotToPixels(plot, point) return internal.NDCToPixels(plot, internal.PlotToNDC(plot, point)) end + + local function CurrentPlot(name) + local gp = GImPlot3D + IM_ASSERT(gp.CurrentPlot ~= nil, name .. "() needs to be called between BeginPlot() and EndPlot()!") + ImPlot3D.SetupLock() + return gp.CurrentPlot + end + + local MOUSE_CURSOR_DRAG_THRESHOLD = 5.0 + local axis_contexts = { [0] = "##XAxisContext", "##YAxisContext", "##ZAxisContext" } + local plane_contexts = { [0] = "##YZPlaneContext", "##XZPlaneContext", "##XYPlaneContext" } + internal.axis_contexts, internal.plane_contexts = axis_contexts, plane_contexts + -- Map edge index to the two faces it belongs to, and corresponding plane: {face_index, plane} + local edge_to_faces = { + [0] = { { 1, 1 }, { 2, 2 } }, { { 2, 2 }, { 3, 0 } }, { { 2, 2 }, { 4, 1 } }, { { 0, 0 }, { 2, 2 } }, + { { 1, 1 }, { 5, 2 } }, { { 3, 0 }, { 5, 2 } }, { { 4, 1 }, { 5, 2 } }, { { 0, 0 }, { 5, 2 } }, + { { 0, 0 }, { 1, 1 } }, { { 1, 1 }, { 3, 0 } }, { { 3, 0 }, { 4, 1 } }, { { 0, 0 }, { 4, 1 } }, + } + + -- [Port] translates plot.Axes[i] along the interaction plane by reprojecting its range extremes (pan) or + -- scaling them around the mouse (zoom); shared body of upstream's two identical inline blocks + local function ReprojectRange(plot, i, mouse_pos_plot, mouse_plane, f) + local axis = plot.Axes[i] + local p_min, p_max = mouse_pos_plot:Copy(), mouse_pos_plot:Copy() + p_min[i], p_max[i] = axis.Range.Min, axis.Range.Max + local pix_min, pix_max = f(internal.PlotToPixels(plot, p_min), internal.PlotToPixels(plot, p_max)) + return ImPlot3D.PixelsToPlotPlane(pix_min, mouse_plane, false)[i], ImPlot3D.PixelsToPlotPlane(pix_max, mouse_plane, false)[i] + end + + -- [Port] ROTATION part of upstream HandleInput, split out for size + function internal.HandleInputRotation(plot, hovered_plane, active_faces, allow_rotate) + local MB = G.ImGuiMouseButton + -- Handle reset rotation with right mouse double click (animate to face the hovered plane) + if plot.Held and ImGui.IsMouseDoubleClicked(MB.Right) and not plot:IsRotationLocked() and allow_rotate then + local rot_end = plot.Rotation + if hovered_plane == -1 then + rot_end = plot.InitialRotation + else + -- Compute plane normal + local axis_normal = P(0, 0, 0) + axis_normal[hovered_plane] = active_faces[hovered_plane] == 1 and-1.0 or 1.0 + if ImHasFlag(plot.Axes[hovered_plane].Flags, AxisFlags.Invert) then axis_normal[hovered_plane]=axis_normal[hovered_plane]* -1 end + -- Compute rotation to align the plane normal with the z-axis + rot_end = Q.FromTwoVectors(rot_end * axis_normal, P(0, 0, 1)) * rot_end + if hovered_plane ~= 2 then + -- Compute rotation to point z-axis up + rot_end = Q.FromTwoVectors(rot_end * P(0, 0, 1), P(0, 1, 0)) * rot_end + else + -- Find the axis most aligned with the up direction + local up = P(0, 1, 0) + local best, best_dot = nil, -math.huge + for _, v in __iter({ P(1, 0, 0), P(0, 1, 0), P(-1, 0, 0), P(0, -1, 0) }) do + local a = rot_end * v + local d = a:Dot(up) + if d > best_dot then best, best_dot = a, d end + end + rot_end = Q.FromTwoVectors(best, up) * rot_end + end + end + plot.RotationAnimationEnd = rot_end + plot.AnimationTime = internal.CalcAnimationTime(plot.Rotation, plot.RotationAnimationEnd) + end + -- Handle rotation with right mouse dragging + if plot.Held and ImGui.IsMouseDown(MB.Right) and not plot:IsRotationLocked() and allow_rotate then + local delta = ImGui.GetIO().MouseDelta + -- Map delta to rotation angles (in radians) + local angle_x, angle_y = delta.x * (3.1415 / 180.0), delta.y * (3.1415 / 180.0) + -- If drag just started, determine and store the rotation axis + if plot.DragRotationAxis == P(0, 0, 0) then + local is_upside_down = (plot.Rotation * P(0, 0, 1)).z < 0.0 + plot.DragRotationAxis = (is_upside_down and{(P(0, 0, -1) )}or{(P(0, 0, 1) +)})[1] end + plot.Rotation = Q(angle_y, P(1, 0, 0)) * plot.Rotation * Q(angle_x, plot.DragRotationAxis) + plot.Rotation:Normalize() + else + -- Reset drag rotation axis when not dragging + plot.DragRotationAxis = P(0, 0, 0) + end + end + + function internal.HandleInput(plot) + local Flags, MB = ImPlot3D.ImPlot3DFlags, G.ImGuiMouseButton + if ImHasFlag(plot.Flags, Flags.NoInputs) then return end + local IO = ImGui.GetIO() + local BF = G.ImGuiButtonFlags + local plot_button_flags = bit32.bor(BF.AllowOverlap, BF.PressedOnClick, BF.PressedOnDoubleClick, BF.MouseButtonLeft, + BF.MouseButtonRight, BF.MouseButtonMiddle) + local plot_clicked + plot_clicked, plot.Hovered, plot.Held = ImGui.ButtonBehavior(plot.PlotRect, plot.ID, plot_button_flags) + -- State + local rot_drag = ImGui.GetMouseDragDelta(MB.Right) + local rotating = rot_drag.x * rot_drag.x + rot_drag.y * rot_drag.y > MOUSE_CURSOR_DRAG_THRESHOLD + local axis_equal = ImHasFlag(plot.Flags, Flags.Equal) + local allow_rotate = not ImHasFlag(plot.Flags, Flags.NoRotate) + local allow_pan = not ImHasFlag(plot.Flags, Flags.NoPan) + local allow_zoom = not ImHasFlag(plot.Flags, Flags.NoZoom) + local A = plot.Axes + + -- HOVERING STATE + local active_faces, corners_pix, _, plane_2d, axis_corners = internal.GetAxesParameters(plot) + local hovered_plane = internal.GetMouseOverPlane(active_faces, corners_pix) + local hovered_plane_idx = hovered_plane + local hovered_axis, hovered_edge_idx = internal.GetMouseOverAxis(plot, corners_pix, plane_2d, axis_corners) + if hovered_axis ~= -1 then hovered_plane_idx, hovered_plane = -1, -1 end + -- If the user is no longer pressing the translation/zoom buttons, set axes as not held + if not ImGui.IsMouseDown(MB.Left) and not ImGui.IsMouseDown(MB.Middle) then + for i = 0, 2 do A[i].Held = false end + end + -- Reset held edge/plane indices (it will be set if mouse button is down) + if not plot.Held then plot.HeldEdgeIdx, plot.HeldPlaneIdx = -1, -1 end + -- Check which axes should be transformed (fit/zoom/translate) + local any_axis_held = A[0].Held or A[1].Held or A[2].Held + if not any_axis_held then + -- Only update the transformation axes if the user is not already performing a transformation + for i = 0, 2 do + A[i].Hovered = (hovered_axis ~= -1 and{(i == hovered_axis )}or{(hovered_plane ~= -1 and{(i ~= hovered_plane )}or{true +})[1]})[1] end + end + -- Compute plane that is being hovered by mouse + local mouse_plane = 2 + if plane_2d ~= -1 then + mouse_plane = plane_2d + elseif A[1].Hovered and A[2].Hovered then + mouse_plane = 0 + elseif A[0].Hovered and A[2].Hovered then + mouse_plane = 1 + elseif A[0].Hovered and A[1].Hovered then + mouse_plane = 2 + elseif plot.HeldEdgeIdx ~= -1 or hovered_edge_idx ~= -1 then + -- Single axis hovered: pick the visible (active) face of the two faces sharing the edge + local ef = edge_to_faces[(plot.HeldEdgeIdx ~= -1 and{plot.HeldEdgeIdx }or{hovered_edge_idx})[1] ] + local function face_active(f) return (f < 3 and{(active_faces[f] == 0 )}or{(active_faces[f - 3] == 1 )})[1]end + mouse_plane = (not face_active(ef[1][1]) and face_active(ef[2][1]) and{ef[2][2] }or{ef[1][2] +})[1] end + local mouse_pos = ImGui.GetMousePos() + local mouse_pos_plot = ImPlot3D.PixelsToPlotPlane(mouse_pos, mouse_plane, false) + local function SetHeldIndices() + if not any_axis_held then plot.HeldEdgeIdx, plot.HeldPlaneIdx = hovered_edge_idx, hovered_plane_idx end + end + + -- AUTO FIT: translation/zoom fit with double click + if plot_clicked and (ImGui.IsMouseDoubleClicked(MB.Left) or ImGui.IsMouseDoubleClicked(MB.Middle)) and allow_pan and allow_zoom then + plot.FitThisFrame = true + for i = 0, 2 do A[i].FitThisFrame = A[i].Hovered end + end + -- Handle auto fit + for i = 0, 2 do + if A[i]:IsAutoFitting() then + plot.FitThisFrame = true + A[i].FitThisFrame = true + end + end + + -- TRANSLATION with left mouse button + if plot.Held and ImGui.IsMouseDown(MB.Left) and allow_pan then + local delta = IO.MouseDelta + if A[0].Hovered and A[1].Hovered and A[2].Hovered then + -- Unconstrained translation on the viewer's plane + local delta_NDC = plot.Rotation:Inverse() * (P(delta.x, -delta.y, 0.0) / plot:GetViewScale()) + local p_min_ndc, p_max_ndc = P(0, 0, 0), P(0, 0, 0) + for i = 0, 2 do + local half_scale = 0.5 * A[i].NDCScale + p_min_ndc[i] = -half_scale - delta_NDC[i] + p_max_ndc[i] = half_scale - delta_NDC[i] + end + local p_min_plt, p_max_plt = internal.NDCToPlot(plot, p_min_ndc), internal.NDCToPlot(plot, p_max_ndc) + for i = 0, 2 do + local axis = A[i] + local new_min, new_max = math.min(p_min_plt[i], p_max_plt[i]), math.max(p_min_plt[i], p_max_plt[i]) + local increasing = new_min > axis.Range.Min + if (new_min ~= axis.Range.Min or new_max ~= axis.Range.Max) and not axis:IsPanLocked(increasing) then + axis:SetRange(new_min, new_max) + if axis_equal then plot:ApplyEqualAspect(i) end + end + axis.Held = true + end + SetHeldIndices() + elseif A[0].Hovered or A[1].Hovered or A[2].Hovered then + -- Translate along plane/axis + for i = 0, 2 do + local axis = A[i] + if axis.Hovered then + local new_min, new_max = ReprojectRange(plot, i, mouse_pos_plot, mouse_plane, function(a, b) + return a - delta, b - delta + end) + local increasing = new_min < axis.Range.Min + if (new_min ~= axis.Range.Min or new_max ~= axis.Range.Max) and not axis:IsPanLocked(increasing) then + axis:SetRange(new_min, new_max) + if axis_equal then plot:ApplyEqualAspect(i) end + end + axis.Held = true + end + end + SetHeldIndices() + end + end + + -- ROTATION + internal.HandleInputRotation(plot, hovered_plane, active_faces, allow_rotate) + + -- ZOOM with mouse wheel / middle drag + if plot.Hovered and allow_zoom then + ImGui.SetKeyOwner(G.ImGuiKey.MouseWheelY, plot.ID) + if ImGui.IsMouseDown(MB.Middle) or IO.MouseWheel ~= 0.0 then + local zoom_rate = (ImGui.IsMouseDown(MB.Middle) and{(-0.01 * IO.MouseDelta.y )}or{(-0.1 * IO.MouseWheel +)})[1] local zoom_around_mouse = hovered_axis ~= -1 or hovered_plane ~= -1 + local ref_axis = 0 + for i = 0, 2 do + local axis = A[i] + if axis.Hovered and not axis:IsInputLocked() then + local mouse_pix = internal.PlotToPixels(plot, mouse_pos_plot) + local dmin, dmax + local new_min, new_max = ReprojectRange(plot, i, mouse_pos_plot, mouse_plane, function(a, b) + dmin, dmax = a - mouse_pix, b - mouse_pix + return mouse_pix + dmin * (1.0 + zoom_rate), mouse_pix + dmax * (1.0 + zoom_rate) + end) + local moved = dmin.x ~= 0 or dmin.y ~= 0 or dmax.x ~= 0 or dmax.y ~= 0 + if zoom_around_mouse and moved then + axis:SetRange(new_min, new_max) + else + -- Zoom around center + local ndc_limit = 0.5 * axis.NDCScale * (1.0 + zoom_rate) + local ndc_min, ndc_max = P(0, 0, 0), P(0, 0, 0) + ndc_min[i], ndc_max[i] = -ndc_limit, ndc_limit + axis:SetRange(internal.NDCToPlot(plot, ndc_min)[i], internal.NDCToPlot(plot, ndc_max)[i]) + end + axis.Held = true + ref_axis = i + end + end + if axis_equal then plot:ApplyEqualAspect(ref_axis) end + SetHeldIndices() + end + end + + -- CONTEXT MENU with right mouse button + if plot.Held and ImGui.IsMouseClicked(MB.Right) and not ImHasFlag(plot.Flags, Flags.NoMenus) then plot.ContextClick = true end + if rotating or (ImGui.IsMouseDoubleClicked(MB.Right) and allow_rotate) then plot.ContextClick = false end + -- Should not happen if it is a double click action + local not_double_click = not allow_rotate or (ImGui.GetTime() - IO.MouseClickedTime[MB.Right]) > IO.MouseDoubleClickTime + if plot.Hovered and plot.ContextClick and not_double_click and not ImGui.IsMouseDown(MB.Right) then + plot.ContextClick = false + plot.OpenContextThisFrame = true + end + if plot.OpenContextThisFrame then + if plot.Items.Legend.Hovered then + ImGui.OpenPopup("##LegendContext") + elseif hovered_axis ~= -1 then + ImGui.OpenPopup(axis_contexts[hovered_axis]) + elseif hovered_plane ~= -1 then + ImGui.OpenPopup(plane_contexts[hovered_plane]) + elseif plot.Hovered then + ImGui.OpenPopup("##PlotContext") + end + end + end + + local axis_labels = { [0] = "X-Axis", "Y-Axis", "Z-Axis" } + local plane_labels = { [0] = "YZ-Plane", "XZ-Plane", "XY-Plane" } + local short_legend_location = { [0] = "C", [1] = "N", [2] = "S", [4] = "W", [8] = "E", [5] = "NW", [9] = "NE", [6] = "SW", [10] = "SE" } + function internal.GetShortLegendLocationName(loc) return short_legend_location[loc] end + + -- [Port] returns true when "Show" toggled (visible passed by value) + function internal.ShowLegendContextMenu(legend, visible) + local Loc, LF = ImPlot3D.ImPlot3DLocation, ImPlot3D.ImPlot3DLegendFlags + local s = ImGui.GetFrameHeight() + local ret = ImGui.Checkbox("Show", visible) + local horiz = ImHasFlag(legend.Flags, LF.Horizontal) + if ImGui.RadioButton("H", horiz) then legend.Flags = bit32.bor(legend.Flags, LF.Horizontal) end + ImGui.SameLine() + if ImGui.RadioButton("V", not horiz) then legend.Flags = bit32.band(legend.Flags, bit32.bnot(LF.Horizontal)) end + ImGui.PushStyleVar(G.ImGuiStyleVar.ItemSpacing, ImVec2(2, 2)) + local size = ImVec2(1.5 * s, s) + local rows = { { Loc.NorthWest, Loc.North, Loc.NorthEast }, { Loc.West, Loc.Center, Loc.East }, { Loc.SouthWest, Loc.South, Loc.SouthEast } } + for _, row in __iter(rows) do + for j, loc in __iter(row) do + if loc == Loc.Center then + ImGui.InvisibleButton(short_legend_location[loc], size) + elseif ImGui.Button(short_legend_location[loc], size) then + legend.Location = loc + end + if j < 3 then ImGui.SameLine() end + end + end + ImGui.PopStyleVar() + return ret + end + + local function FlipFlag(t, k, flag) t[k] = bit32.bxor(t[k], flag) end + + function internal.ShowAxisContextMenu(plot, axis_id) + ImGui.PushItemWidth(75) + local axis = plot.Axes[axis_id] + local always_locked = axis:IsRangeLocked() or axis:IsAutoFitting() + local size = axis.Range:Size() + local drag_speed = size <= 2.220446049250313e-16 and 2.220446049250313e-16 * 1.0e+13 or 0.01 * size -- Recover from almost equal axis limits + local equal_aspect = ImHasFlag(plot.Flags, ImPlot3D.ImPlot3DFlags.Equal) + local Double = G.ImGuiDataType.Double + + ImGui.BeginDisabled(always_locked) + local _, fl = ImGui.CheckboxFlags("##LockMin", axis.Flags, AxisFlags.LockMin); axis.Flags = fl + ImGui.EndDisabled() + ImGui.SameLine() + ImGui.BeginDisabled(axis:IsLockedMin() or always_locked) + local v, changed = ImGui.DragScalar("Min", Double, axis.Range.Min, drag_speed, axis.ConstraintRange.Min, axis.Range.Max) + if changed then + axis:SetMin(v, true) + if equal_aspect then plot:ApplyEqualAspect(axis_id) end + end + ImGui.EndDisabled() + + ImGui.BeginDisabled(always_locked) + _, fl = ImGui.CheckboxFlags("##LockMax", axis.Flags, AxisFlags.LockMax); axis.Flags = fl + ImGui.EndDisabled() + ImGui.SameLine() + ImGui.BeginDisabled(axis:IsLockedMax() or always_locked) + v, changed = ImGui.DragScalar("Max", Double, axis.Range.Max, drag_speed, axis.Range.Min, axis.ConstraintRange.Max) + if changed then + axis:SetMax(v, true) + if equal_aspect then plot:ApplyEqualAspect(axis_id) end + end + ImGui.EndDisabled() + ImGui.Separator() + + _, fl = ImGui.CheckboxFlags("Auto-Fit", axis.Flags, AxisFlags.AutoFit); axis.Flags = fl + ImGui.Separator() + if ImGui.Checkbox("Invert", ImHasFlag(axis.Flags, AxisFlags.Invert)) then FlipFlag(axis, "Flags", AxisFlags.Invert) end + ImGui.Separator() + ImGui.BeginDisabled(axis.Label == "") + if ImGui.Checkbox("Label", axis:HasLabel()) then FlipFlag(axis, "Flags", AxisFlags.NoLabel) end + ImGui.EndDisabled() + if ImGui.Checkbox("Grid Lines", axis:HasGridLines()) then FlipFlag(axis, "Flags", AxisFlags.NoGridLines) end + if ImGui.Checkbox("Tick Marks", axis:HasTickMarks()) then FlipFlag(axis, "Flags", AxisFlags.NoTickMarks) end + if ImGui.Checkbox("Tick Labels", axis:HasTickLabels()) then FlipFlag(axis, "Flags", AxisFlags.NoTickLabels) end + ImGui.PopItemWidth() -- [Port] upstream leaks this PushItemWidth + end + + local function AxisMenus(plot, skip) + for i = 0, 2 do + if i ~= skip then + local axis = plot.Axes[i] + ImGui.PushID(i) + if ImGui.BeginMenu((axis:HasLabel() and{(axis:GetLabel() )}or{axis_labels[i]})[1]) then + internal.ShowAxisContextMenu(plot, i) + ImGui.EndMenu() + end + ImGui.PopID() + end + end + end + + function internal.ShowPlaneContextMenu(plot, plane_idx) AxisMenus(plot, plane_idx) end + + function internal.ShowPlotContextMenu(plot) + local Flags = ImPlot3D.ImPlot3DFlags + AxisMenus(plot, -1) + ImGui.Separator() + if ImGui.BeginMenu("Box") then + ImGui.PushItemWidth(75) + for i, name in __iter({ [0] = "Scale X", "Scale Y", "Scale Z" }) do + local v, changed = ImGui.DragFloat(name, plot.Axes[i].NDCScale, 0.01, 0.1, 3.0) + if changed then plot.Axes[i].NDCScale = math.max(v, 0.01) end + end + ImGui.PopItemWidth() + ImGui.EndMenu() + end + ImGui.Separator() + if ImGui.BeginMenu("Legend") then + if internal.ShowLegendContextMenu(plot.Items.Legend, not ImHasFlag(plot.Flags, Flags.NoLegend)) then FlipFlag(plot, "Flags", Flags.NoLegend) end + ImGui.EndMenu() + end + if ImGui.BeginMenu("Settings") then + if ImGui.MenuItem("Equal", nil, ImHasFlag(plot.Flags, Flags.Equal)) then FlipFlag(plot, "Flags", Flags.Equal) end + ImGui.BeginDisabled(plot.Title == "") + if ImGui.MenuItem("Title", nil, plot:HasTitle()) then FlipFlag(plot, "Flags", Flags.NoTitle) end + ImGui.EndDisabled() + if ImGui.MenuItem("Clip", nil, not ImHasFlag(plot.Flags, Flags.NoClip)) then FlipFlag(plot, "Flags", Flags.NoClip) end + if ImGui.MenuItem("Mouse Position", nil, not ImHasFlag(plot.Flags, Flags.NoMouseText)) then FlipFlag(plot, "Flags", Flags.NoMouseText) end + ImGui.EndMenu() + end + end + + -- [Port] EndPlot's mouse text + context menu popups + function internal.ShowPlotPopups(plot) + local Flags = ImPlot3D.ImPlot3DFlags + internal.RenderMousePos() + if ImGui.BeginPopup("##LegendContext") then + ImGui.Text("Legend") + ImGui.Separator() + if internal.ShowLegendContextMenu(plot.Items.Legend, not ImHasFlag(plot.Flags, Flags.NoLegend)) then FlipFlag(plot, "Flags", Flags.NoLegend) end + ImGui.EndPopup() + end + for i = 0, 2 do + local axis = plot.Axes[i] + if ImGui.BeginPopup(axis_contexts[i]) then + ImGui.TextUnformatted((axis:HasLabel() and{(axis:GetLabel() )}or{axis_labels[i]})[1]) + ImGui.Separator() + internal.ShowAxisContextMenu(plot, i) + ImGui.EndPopup() + end + end + for i = 0, 2 do + if ImGui.BeginPopup(plane_contexts[i]) then + ImGui.Text(plane_labels[i]) + ImGui.Separator() + internal.ShowPlaneContextMenu(plot, i) + ImGui.EndPopup() + end + end + if ImGui.BeginPopup("##PlotContext") then + internal.ShowPlotContextMenu(plot) + ImGui.EndPopup() + end + end + + function ImPlot3D.SetupLock() + local gp = GImPlot3D + IM_ASSERT(gp.CurrentPlot ~= nil, "SetupLock() needs to be called between BeginPlot() and EndPlot()!") + local plot = gp.CurrentPlot + if plot.SetupLocked then return end + plot.SetupLocked = true + local draw_list = ImGui.GetWindowDrawList() + -- Set default formatter/locator + for i = 0, 2 do + local axis = plot.Axes[i] + if axis.Formatter == nil then + axis.Formatter = internal.Formatter_Default + if axis.FormatterData == nil then axis.FormatterData = internal.IMPLOT3D_LABEL_FORMAT end + end + if axis.Locator == nil then axis.Locator = internal.Locator_Default end + end + -- Draw frame background + draw_list:AddRectFilled(plot.FrameRect.Min, plot.FrameRect.Max, ImPlot3D.GetStyleColorU32(ImPlot3D.ImPlot3DCol.FrameBg)) + -- Compute canvas/plot rectangle + local pad = gp.Style.PlotPadding + plot.CanvasRect = G.ImRect(plot.FrameRect.Min + pad, plot.FrameRect.Max - pad) + plot.PlotRect = G.ImRect(plot.CanvasRect.Min, plot.CanvasRect.Max) + -- Apply equal axis aspect constraint if not approximately equal + if ImHasFlag(plot.Flags, ImPlot3D.ImPlot3DFlags.Equal) then + local xar, yar, zar = plot.Axes[0]:GetAspect(), plot.Axes[1]:GetAspect(), plot.Axes[2]:GetAspect() + if not internal.ImAlmostEqual(xar, yar) or not internal.ImAlmostEqual(xar, zar) then + local aspect = (xar + yar + zar) / 3.0 + for i = 0, 2 do plot.Axes[i]:SetAspect(aspect) end + end + end + -- Compute ticks + for i = 0, 2 do + local axis = plot.Axes[i] + if axis.ShowDefaultTicks then + axis.Locator(axis.Ticker, axis.Range, plot:GetViewScale() * axis.NDCScale, axis.Formatter, axis.FormatterData) + end + end + -- Cache axis colors + for i = 0, 2 do + local axis = plot.Axes[i] + axis.ColorBg = ImPlot3D.GetStyleColorU32(ImPlot3D.ImPlot3DCol.AxisBg) + axis.ColorHov = ImPlot3D.GetStyleColorU32(ImPlot3D.ImPlot3DCol.AxisBgHovered) + axis.ColorAct = ImPlot3D.GetStyleColorU32(ImPlot3D.ImPlot3DCol.AxisBgActive) + end + -- Render title + if plot:HasTitle() then + local col = ImPlot3D.GetStyleColorU32(ImPlot3D.ImPlot3DCol.TitleText) + internal.AddTextCentered(draw_list, ImVec2(plot.FrameRect:GetCenter().x, plot.CanvasRect.Min.y), col, plot:GetTitle()) +do local __DARKLUA_VAR= plot.PlotRect.Min __DARKLUA_VAR.y =__DARKLUA_VAR.y+ (ImGui.GetTextLineHeight() + gp.Style.LabelPadding.y +)end end + -- Handle animation + if plot.AnimationTime > 0.0 then + local dt = ImGui.GetIO().DeltaTime + local t = math.clamp(dt / plot.AnimationTime, 0.0, 1.0) + plot.AnimationTime = math.max(plot.AnimationTime - dt, 0.0) + plot.Rotation = Q.Slerp(plot.Rotation, plot.RotationAnimationEnd, t) + end + plot.Initialized = true + -- Handle user input + internal.HandleInput(plot) + -- Push plot rect clipping + ImGui.PushClipRect(plot.PlotRect.Min, plot.PlotRect.Max, true) + -- Render plot box + internal.RenderPlotBox(draw_list, plot) + end + + function ImPlot3D.PlotToNDC(point) return internal.PlotToNDC(CurrentPlot("PlotToNDC"), point) end + function ImPlot3D.NDCToPlot(point) return internal.NDCToPlot(CurrentPlot("NDCToPlot"), point) end + function ImPlot3D.NDCToPixels(point) return internal.NDCToPixels(CurrentPlot("NDCToPixels"), point) end + -- [Port] (point) / (x, y, z) overloads + function ImPlot3D.PlotToPixels(x, y, z) + if type(x) == "number" then x = P(x, y, z) end + return ImPlot3D.NDCToPixels(ImPlot3D.PlotToNDC(x)) + end + + function ImPlot3D.PixelsToNDCRay(pix) + local plot = CurrentPlot("PixelsToNDCRay") + -- Undo screen transformations to get back to NDC space + local zoom, center = plot:GetViewScale(), plot.PlotRect:GetCenter() + local x = (pix.x - center.x) / zoom + local y = -(pix.y - center.y) / zoom -- Invert y-axis + local inv = plot.Rotation:Inverse() + local ndc_near, ndc_far = inv * P(x, y, 10.0), inv * P(x, y, -10.0) + return ImPlot3D.ImPlot3DRay(ndc_near, (ndc_far - ndc_near):Normalized()) + end + + function ImPlot3D.NDCRayToPlotRay(ray) + local plot = CurrentPlot("NDCRayToPlotRay") + local plot_origin = internal.NDCToPlot(plot, ray.Origin) + local plot_along = internal.NDCToPlot(plot, ray.Origin + ray.Direction) + return ImPlot3D.ImPlot3DRay(plot_origin, (plot_along - plot_origin):Normalized()) + end + + -- [Port] (pix) / (x, y) overloads + function ImPlot3D.PixelsToPlotRay(x, y) + if type(x) == "number" then x = ImVec2(x, y) end + return ImPlot3D.NDCRayToPlotRay(ImPlot3D.PixelsToNDCRay(x)) + end + + -- [Port] (pix, plane, mask) / (x, y, plane, mask) overloads + function ImPlot3D.PixelsToPlotPlane(pix, plane, mask, mask2) + if type(pix) == "number" then pix, plane, mask = ImVec2(pix, plane), mask, mask2 end + local plot = CurrentPlot("PixelsToPlotPlane") + local ray = ImPlot3D.PixelsToNDCRay(pix) + local O, D = ray.Origin, ray.Direction + local NAN = 0 / 0 + -- Compute which plane to intersect with + local active_faces = internal.ComputeActiveFaces(plot.Rotation, plot.Axes) + local half = 0.5 * plot.Axes[plane].NDCScale + local coord = (active_faces[plane] == 1 and{half }or{(-half +)})[1] -- Solve for t in O[plane] + D[plane]*t = coord + local denom = D[plane] + if math.abs(denom) < 1e-12 then return P(NAN, NAN, NAN) end -- Ray is parallel to the plane + local t = (coord - O[plane]) / denom + if t < 0.0 then return P(NAN, NAN, NAN) end -- Intersection behind the ray origin + local p = O + D * t + -- Handle mask (if the intersection is out of the plot box, return NAN) + if mask then + local box_scale = plot:GetBoxScale() + for i = 0, 2 do + if i ~= plane and (p[i] < -0.5 * box_scale[i] or p[i] > 0.5 * box_scale[i]) then return P(NAN, NAN, NAN) end + end + end + return internal.NDCToPlot(plot, p) + end + end + + -------------------------------------------------------------------------- + -- [SECTION] Text Utils + -------------------------------------------------------------------------- + do + -- [Port] text_end dropped: Luau strings carry their length + function internal.AddTextRotated(draw_list, pos, angle, col, text) + local g = ImGui.GetCurrentContext() + local font_baked = ImGui.GetFontBaked() + local scale = g.FontSize / font_baked.Size + -- Align to be pixel perfect + pos = ImVec2(math.floor(pos.x), math.floor(pos.y)) + -- Measure the size of the text in unrotated coordinates + local text_size = ImGui.CalcTextSize(text) + -- Precompute sine and cosine of the angle (note: angle should be positive for rotation in ImGui) + local cos_a, sin_a = math.cos(-angle), math.sin(-angle) + -- [Port] ponytail: per-glyph PrimReserve instead of reserve-all + PrimUnreserve + -- Adjust pen position to center the text + local pen_x, pen_y = -text_size.x * 0.5, -text_size.y * 0.5 + do -- [Port] utf8.codes() raises on malformed UTF-8 (upstream breaks out of the loop) + for _, c in __iter(utf8.codes(text)) do + local glyph = font_baked:FindGlyph(c) + if glyph ~= nil then + -- Glyph quad corners in unrotated space, then rotate and translate + local x0, y0 = pen_x + glyph.X0 * scale, pen_y + glyph.Y0 * scale + local x1, y1 = pen_x + glyph.X1 * scale, pen_y + glyph.Y1 * scale + local function R(x, y) return ImVec2(x * cos_a - y * sin_a + pos.x, x * sin_a + y * cos_a + pos.y) end + draw_list:PrimReserve(6, 4) + draw_list:PrimQuadUV(R(x0, y0), R(x1, y0), R(x1, y1), R(x0, y1), + ImVec2(glyph.U0, glyph.V0), ImVec2(glyph.U1, glyph.V0), ImVec2(glyph.U1, glyph.V1), ImVec2(glyph.U0, glyph.V1), col) + -- Advance the pen position + pen_x =pen_x+ glyph.AdvanceX * scale + end + end + end + end + + function internal.AddTextCentered(draw_list, top_center, col, text) + local text_end = ImGui.FindRenderedTextEnd(text) + local text_size = ImGui.CalcTextSize(text, text_end, true) + draw_list:AddText(ImVec2(top_center.x - text_size.x * 0.5, top_center.y), col, text, text_end) + end + end + + -------------------------------------------------------------------------- + -- [SECTION] Plot Box Utils + -- [Port] lookup tables keep upstream's 0-based corner/edge/face indices; rows are 1-based Luau arrays + -------------------------------------------------------------------------- + do + local P = ImPlot3D.ImPlot3DPoint + local ImHasFlag = internal.ImHasFlag + + -- Faces of the box (defined by 4 corner indices) + local faces = { + [0] = { 0, 3, 7, 4 }, -- X-min face + { 0, 4, 5, 1 }, -- Y-min face + { 0, 1, 2, 3 }, -- Z-min face + { 1, 2, 6, 5 }, -- X-max face + { 3, 7, 6, 2 }, -- Y-max face + { 4, 5, 6, 7 }, -- Z-max face + } + -- Edges of the box (defined by 2 corner indices) + local edges = { + [0] = { 0, 1 }, { 1, 2 }, { 2, 3 }, { 3, 0 }, -- Bottom face edges + { 4, 5 }, { 5, 6 }, { 6, 7 }, { 7, 4 }, -- Top face edges + { 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 }, -- Vertical edges + } + -- Face edges (4 edge indices for each face) + local face_edges = { + [0] = { 3, 11, 8, 7 }, -- X-min face + { 0, 8, 4, 9 }, -- Y-min face + { 0, 1, 2, 3 }, -- Z-min face + { 1, 9, 5, 10 }, -- X-max face + { 2, 10, 6, 11 }, -- Y-max face + { 4, 5, 6, 7 }, -- Z-max face + } + -- Lookup table for axis_corners based on active_faces (3D plot) + local axis_corners_lookup_3d = { + [0] = { [0] = { 3, 2 }, { 1, 2 }, { 1, 5 } }, -- {0, 0, 0} + { [0] = { 7, 6 }, { 5, 6 }, { 1, 5 } }, -- {0, 0, 1} + { [0] = { 0, 1 }, { 1, 2 }, { 2, 6 } }, -- {0, 1, 0} + { [0] = { 4, 5 }, { 5, 6 }, { 2, 6 } }, -- {0, 1, 1} + { [0] = { 3, 2 }, { 0, 3 }, { 0, 4 } }, -- {1, 0, 0} + { [0] = { 7, 6 }, { 4, 7 }, { 0, 4 } }, -- {1, 0, 1} + { [0] = { 0, 1 }, { 0, 3 }, { 3, 7 } }, -- {1, 1, 0} + { [0] = { 4, 5 }, { 4, 7 }, { 3, 7 } }, -- {1, 1, 1} + } + internal.box_faces, internal.box_edges, internal.box_face_edges = faces, edges, face_edges + + -- [Port] active_faces is a 0-based array of 0/1 ints (C++ bool used as index) + function internal.Active3DFacesToAxisLookupIndex(active_faces) + return active_faces[0] * 4 + active_faces[1] * 2 + active_faces[2] + end + + function internal.ComputeEdgeOutwardDir(p0, p1, box_center) + local dir = p1 - p0 + local len = math.sqrt(dir.x * dir.x + dir.y * dir.y) + if len < 0.001 then return ImVec2(0, 0) end + dir = ImVec2(dir.x / len, dir.y / len) + -- Perpendicular direction, pointing away from box center + local perp = ImVec2(-dir.y, dir.x) + local to_edge = (p0 + p1) * 0.5 - box_center + if perp.x * to_edge.x + perp.y * to_edge.y < 0 then perp = ImVec2(-perp.x, -perp.y) end + return perp + end + + -- Compute active faces based on the rotation. Returns active_faces, plane_2d + -- If the plot is close to 2D, plane_2d is the plane index (0 -> YZ, 1 -> XZ, 2 -> XY), -1 otherwise + function internal.ComputeActiveFaces(rotation, axes) + local active_faces, plane_2d = {}, -1 + local rot_face_n = { [0] = rotation * P(1, 0, 0), rotation * P(0, 1, 0), rotation * P(0, 0, 1) } + local num_deg = 0 -- Number of planes that are degenerate (seen as a line) + for i = 0, 2 do + local n = rot_face_n[i] + local active + if math.abs(n.z) < 0.025 then + -- If aligned with the plane, choose the min face for bottom/left + active = n.x + n.y < 0.0 + num_deg =num_deg+ 1 + else + local is_inverted = ImHasFlag(axes[i].Flags, ImPlot3D.ImPlot3DAxisFlags.Invert) + active = (is_inverted and{(n.z > 0.0 )}or{(n.z < 0.0 +)})[1] plane_2d = i -- Set this plane as possible 2d plane + end + active_faces[i] = active and 1 or 0 + end + -- Only return 2d plane if there are exactly 2 degenerate planes + if num_deg ~= 2 then plane_2d = -1 end + return active_faces, plane_2d + end + + -- Box corners in plot space (0-based) + function internal.ComputeBoxCorners(range_min, range_max) + local a, b = range_min, range_max + return { + [0] = P(a.x, a.y, a.z), P(b.x, a.y, a.z), P(b.x, b.y, a.z), P(a.x, b.y, a.z), + P(a.x, a.y, b.z), P(b.x, a.y, b.z), P(b.x, b.y, b.z), P(a.x, b.y, b.z), + } + end + + function internal.ComputeBoxCornersPix(plot, corners) + local corners_pix = {} + for i = 0, 7 do corners_pix[i] = internal.PlotToPixels(plot, corners[i]) end + return corners_pix + end + + -- [Port] returns active_faces, corners_pix, corners, plane_2d, axis_corners (out-params in C++) + function internal.GetAxesParameters(plot) + local active_faces, plane_2d = internal.ComputeActiveFaces(plot.Rotation, plot.Axes) + local corners = internal.ComputeBoxCorners(plot:RangeMin(), plot:RangeMax()) + local corners_pix = internal.ComputeBoxCornersPix(plot, corners) + local axis_corners = { [0] = { -1, -1 }, { -1, -1 }, { -1, -1 } } -- [Port] axis_corners[a][1|2] + if plane_2d ~= -1 then + local face = plane_2d + 3 * active_faces[plane_2d] -- Face of the 2D plot + local common_edges = { -1, -1 } -- Edges shared by the 3 faces + for i = 1, 4 do + local edge = face_edges[face][i] + for j = 0, 1 do + local axis = (plane_2d + 1 + j) % 3 + if table.find(face_edges[axis + active_faces[axis] * 3], edge) then common_edges[j + 1] = edge end + end + end + -- Get corners from 2 edges (origin is the corner in common) + local origin_corner, x_corner, y_corner = -1, -1, -1 + local e0, e1 = edges[common_edges[1] ], edges[common_edges[2] ] + for i = 1, 2 do + for j = 1, 2 do + if e0[i] == e1[j] then origin_corner, x_corner, y_corner = e0[i], e0[3 - i], e1[3 - j] end + end + end + -- Swap x and y if they are flipped + local x_vec = corners_pix[x_corner] - corners_pix[origin_corner] + local y_vec = corners_pix[y_corner] - corners_pix[origin_corner] + if y_vec.x > x_vec.x then x_corner, y_corner = y_corner, x_corner end + -- Check which 3d axis the 2d axis refers to + local origin_3d = corners[origin_corner] + local x_3d = (corners[x_corner] - origin_3d):Normalized() + local y_3d = (corners[y_corner] - origin_3d):Normalized() + local x_axis, x_inverted, y_axis, y_inverted = -1, false, -1, false + for i = 0, 1 do + local axis_i = (plane_2d + 1 + i) % 3 + if y_axis ~= -1 or (math.abs(x_3d[axis_i]) > 1e-8 and x_axis == -1) then + x_axis, x_inverted = axis_i, x_3d[axis_i] < 0.0 + else + y_axis, y_inverted = axis_i, y_3d[axis_i] < 0.0 + end + end + -- Set the 3d axis corners based on the 2d axis corners + axis_corners[x_axis] = x_inverted and{ x_corner, origin_corner } or{ origin_corner, x_corner } + axis_corners[y_axis] = y_inverted and{ y_corner, origin_corner } or{ origin_corner, y_corner } + else + local lookup = axis_corners_lookup_3d[internal.Active3DFacesToAxisLookupIndex(active_faces)] + for a = 0, 2 do axis_corners[a] = { lookup[a][1], lookup[a][2] } end + end + return active_faces, corners_pix, corners, plane_2d, axis_corners + end + + -- Spacing constants for axis tick labels and axis labels + local AXIS_TICK_INNER_PAD = 5.0 -- gap between axis edge and inner edge of tick labels + local AXIS_LABEL_PAD = 10.0 -- gap between tick label outer edge and axis label center + local AXIS_RECT_MIN_WIDTH = 40.0 -- minimum hover rect width when labels are absent + local AxisFlags = ImPlot3D.ImPlot3DAxisFlags + local Col = ImPlot3D.ImPlot3DCol + + -- Computes the maximum extent of tick labels perpendicular to the axis in screen space + function internal.ComputeMaxTickLabelExtent(axis) + if ImHasFlag(axis.Flags, AxisFlags.NoTickLabels) then return 0.0 end + local max_extent = 0.0 + for _, tick in __iter(axis.Ticker.Ticks) do + if tick.ShowLabel then max_extent = math.max(max_extent, tick.LabelSize.x * 0.5) end + end + return max_extent + end + + -- Computes the total outward width of the hover rect for an axis + function internal.ComputeAxisHoverWidth(axis) + local w = 2.0 * internal.ComputeMaxTickLabelExtent(axis) + AXIS_TICK_INNER_PAD + if axis:HasLabel() then w =w+ (AXIS_LABEL_PAD + ImGui.CalcTextSize(axis:GetLabel()).y * 0.5 )end + return math.max(w, AXIS_RECT_MIN_WIDTH) + end + + -- [Port] returns hovered plane (0 -> YZ, 1 -> XZ, 2 -> XY) or -1; plane_out dropped (always equal) + function internal.GetMouseOverPlane(active_faces, corners_pix) + local mouse_pos = ImGui.GetIO().MousePos + local contains = G.ImStd.ImTriangleContainsPoint + for a = 0, 2 do + local idx = faces[a + 3 * active_faces[a] ] + local p0, p1, p2, p3 = corners_pix[idx[1] ], corners_pix[idx[2] ], corners_pix[idx[3] ], corners_pix[idx[4] ] + if contains(p0, p1, p2, mouse_pos) or contains(p2, p3, p0, mouse_pos) then return a end + end + return -1 + end + + -- Check if a point is inside an edge's hover region (a rectangle extending outward from the edge) + function internal.IsPointInEdgeHoverRegion(point, p0, p1, outward_dir, width) + local dir = p1 - p0 + local len = math.sqrt(dir.x * dir.x + dir.y * dir.y) + if len < 0.001 then return false end + local local_ = point - p0 + local along = (local_.x * dir.x + local_.y * dir.y) / len + local across = local_.x * outward_dir.x + local_.y * outward_dir.y + return along >= 0 and along <= len and across >= 0 and across <= width + end + + -- [Port] returns hovered axis (or -1), hovered edge index (or -1) + function internal.GetMouseOverAxis(plot, corners_pix, plane_2d, axis_corners) + local mouse_pos = ImGui.GetIO().MousePos + local box_center = ImVec2(0, 0) + for i = 0, 7 do box_center = box_center + corners_pix[i] end + box_center = box_center * (1.0 / 8.0) + for axis_idx = 0, 2 do + local idx0, idx1 = axis_corners[axis_idx][1], axis_corners[axis_idx][2] + if not (plane_2d ~= -1 and axis_idx == plane_2d) and idx0 ~= -1 and idx1 ~= -1 then + local edge = -1 + for e = 0, 11 do + local ed = edges[e] + if (ed[1] == idx0 and ed[2] == idx1) or (ed[1] == idx1 and ed[2] == idx0) then edge = e; break end + end + if edge ~= -1 then + local p0, p1 = corners_pix[idx0], corners_pix[idx1] + local outward_dir = internal.ComputeEdgeOutwardDir(p0, p1, box_center) + if internal.IsPointInEdgeHoverRegion(mouse_pos, p0, p1, outward_dir, internal.ComputeAxisHoverWidth(plot.Axes[axis_idx])) then + return axis_idx, edge + end + end + end + end + return -1, -1 + end + + function internal.GetLocationPos(outer_rect, inner_size, loc, pad) + local Loc = ImPlot3D.ImPlot3DLocation + local W, E = ImHasFlag(loc, Loc.West), ImHasFlag(loc, Loc.East) + local N, S = ImHasFlag(loc, Loc.North), ImHasFlag(loc, Loc.South) + local center = outer_rect:GetCenter() + local x = (W and not E and{(outer_rect.Min.x + pad.x +)}or{(E and not W and{(outer_rect.Max.x - pad.x - inner_size.x +)}or{(center.x - inner_size.x * 0.5 +)})[1]})[1] local y = (N and not S and{(outer_rect.Min.y + pad.y +)}or{(S and not N and{(outer_rect.Max.y - pad.y - inner_size.y +)}or{(center.y - inner_size.y * 0.5 +)})[1]})[1] return ImVec2(math.floor(x + 0.5), math.floor(y + 0.5)) + end + + function internal.RenderMousePos() + local plot = GImPlot3D.CurrentPlot + if ImHasFlag(plot.Flags, ImPlot3D.ImPlot3DFlags.NoMouseText) then return end + local mouse_pos = ImGui.GetMousePos() + local pos = ImPlot3D.PixelsToPlotPlane(mouse_pos, 0, true) + if pos:IsNaN() then pos = ImPlot3D.PixelsToPlotPlane(mouse_pos, 1, true) end + if pos:IsNaN() then pos = ImPlot3D.PixelsToPlotPlane(mouse_pos, 2, true) end + if pos:IsNaN() then return end + local parts = {} + for i = 0, 2 do + local axis = plot.Axes[i] + parts[i + 1] = axis.Formatter(pos[i], axis.FormatterData) + end + local text = "(" .. table.concat(parts, ", ") .. ")" + local p = internal.GetLocationPos(plot.PlotRect, ImGui.CalcTextSize(text), ImPlot3D.ImPlot3DLocation.SouthEast, ImVec2(10, 10)) + ImGui.GetWindowDrawList():AddText(p, ImPlot3D.GetStyleColorU32(ImPlot3D.ImPlot3DCol.InlayText), text) + end + + function internal.RenderPlotBackground(draw_list, plot, corners_pix, active_faces, plane_2d, axis_corners) + local col_bg = ImPlot3D.GetStyleColorVec4(Col.PlotBg) + local col_bg_hov = col_bg + ImVec4(0.03, 0.03, 0.03, 0.0) + local hovered_plane + if not plot.Held then + -- If the mouse is not held, highlight plane hovering when mouse over it + hovered_plane = internal.GetMouseOverPlane(active_faces, corners_pix) + if internal.GetMouseOverAxis(plot, corners_pix, plane_2d, axis_corners) ~= -1 then hovered_plane = -1 end + else + -- If the mouse is held, highlight the held plane + hovered_plane = plot.HeldPlaneIdx + end + for a = 0, 2 do + local idx = faces[a + 3 * active_faces[a] ] + local col = ImGui.ColorConvertFloat4ToU32((hovered_plane == a and{col_bg_hov }or{col_bg})[1]) + draw_list:AddQuadFilled(corners_pix[idx[1] ], corners_pix[idx[2] ], corners_pix[idx[3] ], corners_pix[idx[4] ], col) + end + end + + function internal.RenderAxisRects(draw_list, plot, corners_pix, _, plane_2d, axis_corners) + local hovered_axis = internal.GetMouseOverAxis(plot, corners_pix, plane_2d, axis_corners) + -- Compute box center in screen space + local box_center = ImVec2(0, 0) + for i = 0, 7 do box_center = box_center + corners_pix[i] end + box_center = box_center * (1.0 / 8.0) + for axis_idx = 0, 2 do + local idx0, idx1 = axis_corners[axis_idx][1], axis_corners[axis_idx][2] + -- In 2D mode, skip the perpendicular axis + if not (plane_2d ~= -1 and axis_idx == plane_2d) and idx0 ~= -1 and idx1 ~= -1 then + local axis = plot.Axes[axis_idx] + local p0, p1 = corners_pix[idx0], corners_pix[idx1] + local outward_dir = internal.ComputeEdgeOutwardDir(p0, p1, box_center) + local hover_width = internal.ComputeAxisHoverWidth(axis) + -- Active only when the drag started on this axis rect (HeldEdgeIdx set), not on a plane or outside. + local col + if axis.Held and plot.HeldEdgeIdx ~= -1 then + col = axis.ColorAct + elseif axis_idx == hovered_axis and not plot.Held then + col = axis.ColorHov + else + col = axis.ColorBg + end + -- Draw hover rectangle if color is not transparent + if col ~= 0 then + draw_list:AddQuadFilled(p0, p0 + outward_dir * hover_width, p1 + outward_dir * hover_width, p1, col) + end + end + end + end + + function internal.RenderPlotBorder(draw_list, _, corners_pix, active_faces, plane_2d) + -- Determine which edges to render (all visible edges) + local render_edge = {} + for a = 0, 2 do + if not (plane_2d ~= -1 and a ~= plane_2d) then + for _, e in __iter(face_edges[a + 3 * active_faces[a] ]) do render_edge[e] = true end + end + end + local col_bd = ImPlot3D.GetStyleColorU32(Col.PlotBorder) + for i = 0, 11 do + if render_edge[i] then draw_list:AddLine(corners_pix[edges[i][1] ], corners_pix[edges[i][2] ], col_bd, 1.0) end + end + end + + function internal.RenderGrid(draw_list, plot, corners, active_faces, plane_2d) + local col_grid = ImPlot3D.GetStyleColorVec4(Col.AxisGrid) + local col_grid_minor = ImGui.GetColorU32(ImVec4(col_grid.x, col_grid.y, col_grid.z, col_grid.w * 0.3)) + local col_grid_major = ImGui.GetColorU32(ImVec4(col_grid.x, col_grid.y, col_grid.z, col_grid.w * 0.6)) + -- Draw grid lines for ticks of `axis` sweeping from a->b (start) / c->d (end) + local function lines(axis, s0, s1, vec) + if ImHasFlag(axis.Flags, AxisFlags.NoGridLines) then return end + for _, tick in __iter(axis.Ticker.Ticks) do + local t = (tick.PlotPos - axis.Range.Min) / (axis.Range.Max - axis.Range.Min) + -- Skip ticks that are out of range + if t >= 0.0 and t <= 1.0 then + local p_start = internal.PlotToPixels(plot, s0 + vec * t) + local p_end = internal.PlotToPixels(plot, s1 + vec * t) + draw_list:AddLine(p_start, p_end, (tick.Major and{col_grid_major }or{col_grid_minor})[1]) + end + end + end + for face = 0, 2 do + if not (plane_2d ~= -1 and face ~= plane_2d) then + local f = faces[face + 3 * active_faces[face] ] + -- Corners of the face in plot space; u/v are the two axes that define the face plane + local p0, p1, p3 = corners[f[1] ], corners[f[2] ], corners[f[4] ] + lines(plot.Axes[(face + 1) % 3], p0, p3, p1 - p0) -- along u + lines(plot.Axes[(face + 2) % 3], p0, p1, p3 - p0) -- along v + end + end + end + internal.AXIS_TICK_INNER_PAD, internal.AXIS_LABEL_PAD = AXIS_TICK_INNER_PAD, AXIS_LABEL_PAD + + function internal.RenderTickMarks(draw_list, plot, corners, corners_pix, axis_corners, plane_2d) + local col_tick = ImPlot3D.GetStyleColorU32(Col.AxisTick) + -- Tick lengths in NDC units + local major_size_ndc, minor_size_ndc = 0.06, 0.03 + for a = 0, 2 do + local axis = plot.Axes[a] + local idx0, idx1 = axis_corners[a][1], axis_corners[a][2] + -- [Port] `continue` chain flattened into a repeat/break block + repeat + if ImHasFlag(axis.Flags, AxisFlags.NoTickMarks) or idx0 == idx1 then break end -- axis not visible or invalid + local axis_start = corners[idx0] + local axis_dir = corners[idx1] - axis_start + local axis_len = axis_dir:Length() + if axis_len < 1e-12 then break end + axis_dir = axis_dir / axis_len + -- Draw axis line + draw_list:AddLine(corners_pix[idx0], corners_pix[idx1], col_tick) + -- Choose plane: 2D plane if any, else X/Y axis -> XY plane (2), Z axis -> XZ plane (1) + local chosen_plane = (plane_2d ~= -1 and{plane_2d }or{a == 2 and 1 or 2 +})[1] -- Project axis_dir onto chosen plane + local proj_dir = P(axis_dir.x, axis_dir.y, axis_dir.z) + proj_dir[chosen_plane] = 0.0 + local proj_len = proj_dir:Length() + if proj_len < 1e-12 then break end -- Axis is parallel to plane normal, skip ticks + proj_dir = proj_dir / proj_len + -- Rotate 90 degrees in chosen plane + local tick_dir + if chosen_plane == 0 then + tick_dir = P(0, -proj_dir.z, proj_dir.y) -- YZ plane + elseif chosen_plane == 1 then + tick_dir = P(-proj_dir.z, 0, proj_dir.x) -- XZ plane + else + tick_dir = P(-proj_dir.y, proj_dir.x, 0) -- XY plane + end + tick_dir:Normalize() + for _, tick in __iter(axis.Ticker.Ticks) do + local v = (tick.PlotPos - axis.Range.Min) / (axis.Range.Max - axis.Range.Min) + -- Skip ticks that are out of range + if v >= 0.0 and v <= 1.0 then + local tick_pos_ndc = internal.PlotToNDC(plot, axis_start + axis_dir * (v * axis_len)) + -- Half tick on each side of the axis line + local half_tick_ndc = tick_dir * (((tick.Major and{major_size_ndc }or{minor_size_ndc})[1]) * 0.5) + draw_list:AddLine(internal.NDCToPixels(plot, tick_pos_ndc - half_tick_ndc), + internal.NDCToPixels(plot, tick_pos_ndc + half_tick_ndc), col_tick) + end + end + until true + end + end + + -- Normalized screen-space direction of an axis edge + local function ScreenDir(p0, p1) + local d = p1 - p0 + local len = math.sqrt(d.x * d.x + d.y * d.y) + return (len > 0.0 and{(ImVec2(d.x / len, d.y / len) )}or{(ImVec2(1.0, 0.0) +)})[1] end + + function internal.RenderTickLabels(draw_list, plot, corners, corners_pix, axis_corners) + local col_tick_txt = ImPlot3D.GetStyleColorU32(Col.AxisText) + local IM_PI = math.pi + for a = 0, 2 do + local axis = plot.Axes[a] + local idx0, idx1 = axis_corners[a][1], axis_corners[a][2] + -- If normal to the 2D plot, ignore the ticks + if not ImHasFlag(axis.Flags, AxisFlags.NoTickLabels) and idx0 ~= idx1 then + local axis_start = corners[idx0] + local axis_dir = corners[idx1] - axis_start + local axis_start_pix, axis_end_pix = corners_pix[idx0], corners_pix[idx1] + local axis_screen_dir = ScreenDir(axis_start_pix, axis_end_pix) + -- Outward perpendicular direction and label offset + local outward_dir = internal.ComputeEdgeOutwardDir(axis_start_pix, axis_end_pix, internal.PlotToPixels(plot, plot:RangeCenter())) + local offset_pix = outward_dir * (internal.ComputeMaxTickLabelExtent(axis) + AXIS_TICK_INNER_PAD) + -- Compute angle perpendicular to axis in screen space, normalized to [-pi, pi], kept upright + local angle = math.atan2(-axis_screen_dir.y, axis_screen_dir.x) + IM_PI * 0.5 + if angle > IM_PI then angle =angle- 2 * IM_PI end + if angle < -IM_PI then angle =angle+ 2 * IM_PI end + if angle > IM_PI * 0.5 then angle =angle- IM_PI end + if angle < -IM_PI * 0.5 then angle =angle+ IM_PI end + for _, tick in __iter(axis.Ticker.Ticks) do + local t_axis = (tick.PlotPos - axis.Range.Min) / (axis.Range.Max - axis.Range.Min) + if tick.ShowLabel and t_axis >= 0.0 and t_axis <= 1.0 then + local tick_pos_pix = internal.PlotToPixels(plot, axis_start + axis_dir * t_axis) + internal.AddTextRotated(draw_list, tick_pos_pix + offset_pix, angle, col_tick_txt, axis.Ticker:GetText(tick)) + end + end + end + end + end + + function internal.RenderAxisLabels(draw_list, plot, _, corners_pix, axis_corners) + local col_ax_txt = ImPlot3D.GetStyleColorU32(Col.AxisText) + local IM_PI = math.pi + for a = 0, 2 do + local axis = plot.Axes[a] + local idx0, idx1 = axis_corners[a][1], axis_corners[a][2] + -- If normal to the 2D plot, ignore axis label + if axis:HasLabel() and idx0 ~= idx1 then + local axis_start_pix, axis_end_pix = corners_pix[idx0], corners_pix[idx1] + local axis_screen_dir = ScreenDir(axis_start_pix, axis_end_pix) + -- Tick labels are centered at (max_tick_extent + AXIS_TICK_INNER_PAD) from the axis edge, + -- so the axis label sits one more max_tick_extent + AXIS_LABEL_PAD beyond that. + local outward_dir = internal.ComputeEdgeOutwardDir(axis_start_pix, axis_end_pix, internal.PlotToPixels(plot, plot:RangeCenter())) + local max_tick_extent = internal.ComputeMaxTickLabelExtent(axis) + local total_offset = max_tick_extent + AXIS_TICK_INNER_PAD + max_tick_extent + AXIS_LABEL_PAD + local label_pos_pix = (axis_start_pix + axis_end_pix) * 0.5 + outward_dir * total_offset + -- Compute text angle + local angle = math.atan2(-axis_screen_dir.y, axis_screen_dir.x) + if angle > IM_PI * 0.5 then angle =angle- IM_PI end + if angle < -IM_PI * 0.5 then angle =angle+ IM_PI end + internal.AddTextRotated(draw_list, label_pos_pix, angle, col_ax_txt, axis:GetLabel()) + end + end + end + + function internal.RenderPlotBox(draw_list, plot) + local active_faces, corners_pix, corners, plane_2d, axis_corners = internal.GetAxesParameters(plot) + internal.RenderPlotBackground(draw_list, plot, corners_pix, active_faces, plane_2d, axis_corners) + internal.RenderAxisRects(draw_list, plot, corners_pix, active_faces, plane_2d, axis_corners) + internal.RenderPlotBorder(draw_list, plot, corners_pix, active_faces, plane_2d) + internal.RenderGrid(draw_list, plot, corners, active_faces, plane_2d) + internal.RenderTickMarks(draw_list, plot, corners, corners_pix, axis_corners, plane_2d) + internal.RenderTickLabels(draw_list, plot, corners, corners_pix, axis_corners) + internal.RenderAxisLabels(draw_list, plot, corners, corners_pix, axis_corners) + end + end + + -------------------------------------------------------------------------- + -- [SECTION] ImPlot3DSpec, ImPlot3DItem, ImPlot3DItemGroup methods, ImPlot3DNextItemData, Item Utils + -------------------------------------------------------------------------- + do + local Prop, Marker = ImPlot3D.ImPlot3DProp, ImPlot3D.ImPlot3DMarker + local ImHasFlag, IsColorAuto = internal.ImHasFlag, internal.IsColorAuto + local AUTO = ImPlot3D.IMPLOT3D_AUTO + + -- [Port] Prop -> field name. Array props take Lua arrays (1-based) of ImU32/float. + local prop_fields = { + [Prop.LineColor] = "LineColor", [Prop.LineColors] = "LineColors", [Prop.LineWeight] = "LineWeight", + [Prop.FillColor] = "FillColor", [Prop.FillColors] = "FillColors", [Prop.FillAlpha] = "FillAlpha", + [Prop.Marker] = "Marker", [Prop.MarkerSize] = "MarkerSize", [Prop.MarkerSizes] = "MarkerSizes", + [Prop.MarkerLineColor] = "MarkerLineColor", [Prop.MarkerLineColors] = "MarkerLineColors", + [Prop.MarkerFillColor] = "MarkerFillColor", [Prop.MarkerFillColors] = "MarkerFillColors", + [Prop.Offset] = "Offset", [Prop.Stride] = "Stride", [Prop.Flags] = "Flags", + } + local color_fields = { LineColor = true, FillColor = true, MarkerLineColor = true, MarkerFillColor = true } + + local SpecMT = {} + SpecMT.__index = SpecMT + + -- Set properties from (ImPlot3DProp,value) pairs in any order + -- [Port] colors accept ImU32 or ImVec4 (the scalar/ImVec4 SetProp overloads) + function SpecMT:SetProp(...) + local n = select("#", ...) + IM_ASSERT(n % 2 == 0, "Odd number of arguments! You must provide (ImPlot3DProp,value) pairs!") + for i = 1, n, 2 do + local prop, v = select(i, ...) + local field = prop_fields[prop] + IM_ASSERT(field ~= nil, "User provided an invalid ImPlot3DProp!") + if color_fields[field] and type(v) == "number" then v = ImGui.ColorConvertU32ToFloat4(v) end + self[field] = v + end + return self + end + + -- [Port] ImPlot3DSpec() / ImPlot3DSpec(prop, value, ...). A plain table of fields is also accepted by PlotX. + function ImPlot3D.ImPlot3DSpec(...) + local s = setmetatable({ + LineColor = IMPLOT3D_AUTO_COL(), LineColors = nil, LineWeight = 1.0, + FillColor = IMPLOT3D_AUTO_COL(), FillColors = nil, FillAlpha = AUTO, + Marker = Marker.Auto, MarkerSize = AUTO, MarkerSizes = nil, + MarkerLineColor = IMPLOT3D_AUTO_COL(), MarkerLineColors = nil, + MarkerFillColor = IMPLOT3D_AUTO_COL(), MarkerFillColors = nil, + Offset = 0, Stride = AUTO, Flags = 0, + }, SpecMT) + if select("#", ...) > 0 then s:SetProp(...) end + return s + end + + -- [Port] copy a user spec (ImPlot3DSpec or partial table) into a full spec; colors copied by value + local function CopySpec(dst, src) + local def = ImPlot3D.ImPlot3DSpec() + for k, v in __iter(def) do + local sv = src and src[k] + if sv == nil then sv = v end + if color_fields[k] then + if type(sv) == "number" then sv = ImGui.ColorConvertU32ToFloat4(sv) else sv = ImVec4(sv.x, sv.y, sv.z, sv.w) end + end + dst[k] = sv + end + for _, k in __iter({ "LineColors", "FillColors", "MarkerSizes", "MarkerLineColors", "MarkerFillColors" }) do + dst[k] = src and src[k] or nil + end + return dst + end + internal.CopySpec = CopySpec + + -- State information for plot items + function internal.ImPlot3DItem() + return { ID = 0, Color = G.IM_COL32_WHITE, Marker = Marker.None, NameOffset = -1, Show = true, LegendHovered = false, SeenThisFrame = false } + end + + function internal.ImPlot3DNextItemData() + local n = { Spec = ImPlot3D.ImPlot3DSpec() } + internal.ResetNextItemData(n) + return n + end + function internal.ResetNextItemData(n) + CopySpec(n.Spec, nil) + n.RenderLine, n.RenderFill = false, false + n.RenderMarkerLine, n.RenderMarkerFill = true, true + n.IsAutoFill, n.IsAutoLine = true, true + n.Hidden = false + end + + -- [Port] ImPlot3DItemGroup methods (group is the table from internal.ImPlot3DItemGroup) + -- [Port] Legend.Labels -> Legend.LabelList (1-based array of label strings); NameOffset = 0-based index into it + local IG = {} + internal.ItemGroup = IG + function IG.GetItemCount(g) return g.ItemPool.BufSize end + function IG.GetItemID(_, label_id) return ImGui.GetID(label_id) end + function IG.GetItem(g, id) if type(id) == "string" then id = ImGui.GetID(id) end return g.ItemPool:GetByKey(id) end + function IG.GetOrAddItem(g, id) return g.ItemPool:GetOrAddByKey(id) end + function IG.GetItemByIndex(g, i) return g.ItemPool:GetByIndex(i) end + function IG.GetItemIndex(g, item) return g.ItemPool:GetIndex(item) end + function IG.GetLegendCount(g) return #g.Legend.Indices end + function IG.GetLegendItem(g, i) return g.ItemPool:GetByIndex(g.Legend.Indices[i + 1]) end + function IG.GetLegendLabel(g, i) return g.Legend.LabelList[IG.GetLegendItem(g, i).NameOffset + 1] end + function IG.Reset(g) + g.ItemPool:Clear() + table.clear(g.Legend.Indices) + table.clear(g.Legend.LabelList) + g.ColormapIdx, g.MarkerIdx = 0, 0 + end + + function internal.NextMarker() + local gp = GImPlot3D + IM_ASSERT(gp.CurrentItems ~= nil, "NextMarker() needs to be called between BeginPlot() and EndPlot()!") + local idx = gp.CurrentItems.MarkerIdx % Marker.COUNT +do local __DARKLUA_VAR= gp.CurrentItems __DARKLUA_VAR.MarkerIdx =__DARKLUA_VAR.MarkerIdx+ 1 +end return idx + end + + function internal.RegisterOrGetItem(label_id, flags) + local gp = GImPlot3D + local Items = gp.CurrentItems + local id = ImGui.GetID(label_id) + local just_created = Items.ItemPool:GetByKey(id) == nil + local item = Items.ItemPool:GetOrAddByKey(id) + -- Avoid re-adding the same item to the legend (the legend is reset every frame) + if item.SeenThisFrame then return item, just_created end + item.SeenThisFrame = true + -- Add item to the legend + local idx = Items.ItemPool:GetIndex(item) + item.ID = id + local display_end = string.find(label_id, "##", 1, true) + if not ImHasFlag(flags, ImPlot3D.ImPlot3DItemFlags.NoLegend) and display_end ~= 1 and label_id ~= "" then + local legend = Items.Legend + table.insert(legend.Indices, idx) + item.NameOffset = #legend.LabelList + table.insert(legend.LabelList, label_id) + end + return item, just_created + end + + function internal.GetCurrentItem() return GImPlot3D.CurrentItem end + function internal.GetItemData() return GImPlot3D.NextItemData end + + function internal.BustItemCache() + for _, plot in __iter(GImPlot3D.Plots.Buf) do + if plot then IG.Reset(plot.Items) end + end + end + + local ITEM_HIGHLIGHT_LINE_SCALE, ITEM_HIGHLIGHT_MARK_SCALE = 2.0, 1.25 + + function internal.EndItem() + local gp = GImPlot3D + internal.ResetNextItemData(gp.NextItemData) + gp.CurrentItem = nil + end + + function internal.BeginItem(label_id, spec, item_col, item_mkr) + local gp = GImPlot3D + IM_ASSERT(gp.CurrentPlot ~= nil, "PlotX() needs to be called between BeginPlot() and EndPlot()!") + ImPlot3D.SetupLock() + local style = gp.Style + local n = gp.NextItemData + local s = CopySpec(n.Spec, spec) + -- Register item + local item, just_created = internal.RegisterOrGetItem(label_id, s.Flags) + gp.CurrentItem = item + -- Set/override item color + if item_col ~= nil and type(item_col) == "number" then item_col = ImGui.ColorConvertU32ToFloat4(item_col) end + if item_col ~= nil and not IsColorAuto(item_col) then + item.Color = ImGui.ColorConvertFloat4ToU32(item_col) + elseif just_created then + item.Color = internal.NextColormapColorU32() + end + -- Set/override item marker + item_mkr = item_mkr or Marker.Invalid + if item_mkr ~= Marker.Invalid then + if item_mkr ~= Marker.Auto then + item.Marker = item_mkr + elseif just_created or item.Marker == Marker.None then + item.Marker = internal.NextMarker() + end + end + -- Set next item color + local ic = ImGui.ColorConvertU32ToFloat4(item.Color) + n.IsAutoLine = IsColorAuto(s.LineColor) + n.IsAutoFill = IsColorAuto(s.FillColor) + if IsColorAuto(s.LineColor) then s.LineColor = ImVec4(ic.x, ic.y, ic.z, ic.w) end + if IsColorAuto(s.FillColor) then s.FillColor = ImVec4(ic.x, ic.y, ic.z, ic.w) end + if IsColorAuto(s.MarkerLineColor) then local c = s.LineColor s.MarkerLineColor = ImVec4(c.x, c.y, c.z, c.w) end + if IsColorAuto(s.MarkerFillColor) then local c = s.LineColor s.MarkerFillColor = ImVec4(c.x, c.y, c.z, c.w) end + -- Set size & weight + if s.LineWeight < 0 then s.LineWeight = style.LineWeight end + if s.Marker < 0 then s.Marker = style.Marker end + if s.MarkerSize < 0 then s.MarkerSize = style.MarkerSize end + if s.FillAlpha < 0 then s.FillAlpha = style.FillAlpha end +do local __DARKLUA_VAR= -- Apply alpha modifiers + s.FillColor __DARKLUA_VAR.w =__DARKLUA_VAR.w* s.FillAlpha +end do local __DARKLUA_VAR0= s.MarkerFillColor __DARKLUA_VAR0.w =__DARKLUA_VAR0.w* s.FillAlpha +end -- Set render flags + n.RenderLine = s.LineColor.w > 0 and s.LineWeight > 0 + n.RenderFill = s.FillColor.w > 0 + n.RenderMarkerLine = s.LineColor.w > 0 and s.LineWeight > 0 + n.RenderMarkerFill = s.FillColor.w > 0 + -- Don't render if item is hidden + if not item.Show then + internal.EndItem() + return false + elseif item.LegendHovered and not ImHasFlag(gp.CurrentItems.Legend.Flags, ImPlot3D.ImPlot3DLegendFlags.NoHighlightItem) then + -- Legend hover highlight + s.LineWeight =s.LineWeight* ITEM_HIGHLIGHT_LINE_SCALE + s.MarkerSize =s.MarkerSize* ITEM_HIGHLIGHT_MARK_SCALE + end + return true + end + + -- [Port] getter: { Count, Get = function(g, idx) -> x, y, z } (see Getters section) + function internal.BeginItemEx(label_id, getter, spec, item_col, item_mkr) + if internal.BeginItem(label_id, spec, item_col, item_mkr) then + local plot = GImPlot3D.CurrentPlot + if plot.FitThisFrame and not ImHasFlag(GImPlot3D.NextItemData.Spec.Flags, ImPlot3D.ImPlot3DItemFlags.NoFit) then + local a0, a1, a2 = plot.Axes[0], plot.Axes[1], plot.Axes[2] + local f0, f1, f2 = a0.FitThisFrame, a1.FitThisFrame, a2.FitThisFrame + local get = getter.Get + for i = 0, getter.Count - 1 do + -- [Port] plot.ExtendFit(getter(i)) inlined: no ImPlot3DPoint per point + local x, y, z = get(getter, i) + if f0 then a0:ExtendFit(x) end + if f1 then a1:ExtendFit(y) end + if f2 then a2:ExtendFit(z) end + end + end + return true + end + return false + end + end + + -------------------------------------------------------------------------- + -- [SECTION] Getters, Renderers, RenderPrimitives (implot3d_items.cpp) + -- [Port] Getters are { Count, Get = function(g, idx) -> x, y, z } (idx 0-based), color getters -> + -- renderer fields Col/Cols/Alpha, size getters -> Size/Sizes. Hot loops work on scalars: the + -- plot->pixel transform and depth are cached per RenderPrimitivesEx call (no ImPlot3DPoint/ImVec2 per point). + -------------------------------------------------------------------------- + do + local ImHasFlag = internal.ImHasFlag + local writef64, writeu32, sqrt, min, max = buffer.writef64, buffer.writeu32, math.sqrt, math.min, math.max + local VTX_STRIDE = G.VTX_STRIDE or 36 + local HUGE = math.huge + + -- Indexers / Getters + local function GetXYZ(g, idx) + local s, off = g.Stride, g.Offset + local i = ((off == 0 and{idx }or{((off + idx) % g.Count)})[1]) * s + 1 + return g.Xs[i], g.Ys[i], g.Zs[i] + end + function internal.GetterXYZ(xs, ys, zs, count, offset, stride) + return { Xs = xs, Ys = ys, Zs = zs, Count = count, Offset = (count > 0 and{(internal.ImPosMod(offset or 0, count) )}or{0})[1], + Stride = stride or 1, Get = GetXYZ } + end + local function GetLoop(g, idx) local inner = g.Getter return inner.Get(inner, idx % (g.Count - 1)) end + function internal.GetterLoop(getter) return { Getter = getter, Count = getter.Count + 1, Get = GetLoop } end + local function GetTriLines(g, idx) local inner = g.Getter return inner.Get(inner, (math.floor((idx % 6 + 1) / 2)) % 3 + math.floor(idx / 6 )* 3) end + function internal.GetterTriangleLines(getter) return { Getter = getter, Count = getter.Count * 2, Get = GetTriLines } end + local function GetQuadLines(g, idx) local inner = g.Getter return inner.Get(inner, (math.floor((idx % 8 + 1) / 2)) % 4 + math.floor(idx / 8 )* 4) end + function internal.GetterQuadLines(getter) return { Getter = getter, Count = getter.Count * 2, Get = GetQuadLines } end + local function GetSurfaceLines(g, idx) + local endpoint_i, segment_i, xc = idx % 2, math.floor(idx / 2), g.XCount + local horizontal_segments = (xc - 1) * g.YCount + local px, py + if segment_i < horizontal_segments then + -- Horizontal segment: endpoints (col, row), (col+1, row) + px, py = segment_i % (xc - 1) + endpoint_i, math.floor(segment_i / (xc - 1) +) else + -- Vertical segment: endpoints (col, row), (col, row+1) + local seg_v = segment_i - horizontal_segments + px, py = math.floor(seg_v / (g.YCount - 1)), seg_v % (g.YCount - 1) + endpoint_i + end + local inner = g.Getter + return inner.Get(inner, py * xc + px) + end + function internal.GetterSurfaceLines(getter, x_count, y_count) + return { Getter = getter, XCount = x_count, YCount = y_count, Get = GetSurfaceLines, + Count = ((x_count - 1) * y_count + (y_count - 1) * x_count) * 2 } + end + -- [Port] idx is a 1-based Lua array of 0-based vertex indices (upstream semantics) + local function GetMeshTri(g, i) local v = g.Getter return v.Get(v, g.Idx[i + 1]) end + function internal.GetterMeshTriangles(vtx_getter, idx, idx_count) + return { Getter = vtx_getter, Idx = idx, TriCount = math.floor(idx_count / 3), Count = idx_count, Get = GetMeshTri } + end + + -- Transform cache (PlotToPixels + GetPointDepth as scalars) + local ax_tf, ax_td, ax_min, ax_size, ax_inv, ax_ndc = {}, {}, {}, {}, {}, {} + local qx, qy, qz, qw, vscale, cx, cy = 0, 0, 0, 1, 1, 0, 0 + local function CacheTransform(plot) + for i = 0, 2 do + local a = plot.Axes[i] + ax_tf[i], ax_td[i] = a.TransformForward, a.TransformData + local r = (a.TransformForward ~= nil and{a.ScaledRange }or{a.Range +})[1] ax_min[i], ax_size[i] = r.Min, r.Max - r.Min + ax_inv[i] = ImHasFlag(a.Flags, ImPlot3D.ImPlot3DAxisFlags.Invert) + ax_ndc[i] = a.NDCScale + end + local q = plot.Rotation + qx, qy, qz, qw = q.x, q.y, q.z, q.w + vscale = plot:GetViewScale() + local c = plot.PlotRect:GetCenter() + cx, cy = c.x, c.y + end + local function Rotate(x, y, z) + local ux, uy, uz = qy * z - qz * y, qz * x - qx * z, qx * y - qy * x + local vx, vy, vz = qy * uz - qz * uy, qz * ux - qx * uz, qx * uy - qy * ux + return x + 2 * (qw * ux + vx), y + 2 * (qw * uy + vy), z + 2 * (qw * uz + vz) + end + local function NDC(i, v) + local tf = ax_tf[i] + if tf ~= nil then v = tf(v, ax_td[i]) end + local t = (v - ax_min[i]) / ax_size[i] + return ((ax_inv[i] and{(0.5 - t )}or{(t - 0.5)})[1]) * ax_ndc[i] + end + local function ToPixels(x, y, z) + local rx, ry = Rotate(NDC(0, x), NDC(1, y), NDC(2, z)) + return rx * vscale + cx, -ry * vscale + cy + end + local function Depth(x, y, z) + if ax_inv[0] then x = -x end + if ax_inv[1] then y = -y end + if ax_inv[2] then z = -z end + local _, _, rz = Rotate(x, y, z) + return rz + end + internal.CacheTransform, internal.TransformToPixels, internal.GetPointDepth = CacheTransform, ToPixels, Depth + + -- Liang-Barsky clip against the cull box; returns t0, t1 or nil when outside + -- [Port] upstream lambda -> module-level helper on ct0/ct1 (no closure per call) + local bx0, by0, bz0, bx1, by1, bz1 = 0, 0, 0, 0, 0, 0 + local ct0, ct1 = 0.0, 1.0 + local function upd(p, q) + if p == 0.0 then return q >= 0.0 end + local r = q / p + if p < 0.0 then + if r > ct1 then return false end + if r > ct0 then ct0 = r end + else + if r < ct0 then return false end + if r < ct1 then ct1 = r end + end + return true + end + local function Clip(x0, y0, z0, x1, y1, z1) + if x0 >= bx0 and x0 <= bx1 and y0 >= by0 and y0 <= by1 and z0 >= bz0 and z0 <= bz1 + and x1 >= bx0 and x1 <= bx1 and y1 >= by0 and y1 <= by1 and z1 >= bz0 and z1 <= bz1 then + return 0.0, 1.0 + end + ct0, ct1 = 0.0, 1.0 + local dx, dy, dz = x1 - x0, y1 - y0, z1 - z0 + if not (upd(-dx, x0 - bx0) and upd(dx, bx1 - x0) and upd(-dy, y0 - by0) and upd(dy, by1 - y0) + and upd(-dz, z0 - bz0) and upd(dz, bz1 - z0)) then return nil end + return ct0, ct1 + end + + -- [Port] ColorConvertU32ToFloat4 -> c.w *= alpha -> ColorConvertFloat4ToU32, without the ImVec4 + local band, bor, lshift, rshift, floor = bit32.band, bit32.bor, bit32.lshift, bit32.rshift, math.floor + local function MulAlpha(col, alpha) + return bor(band(col, 0x00FFFFFF), lshift(floor(rshift(col, 24) * alpha + 0.5), 24)) + end + internal.MulAlpha = MulAlpha + + local function GetCol(r, prim) + local cols = r.Cols + if cols == nil then return r.Col end + local col = cols[prim + 1] + if r.Alpha < 1.0 then col = MulAlpha(col, r.Alpha) end + return col + end + + local function PrimLine(dl, x1, y1, x2, y2, hw, col, u0, v0, u1, v1, z) + local dx, dy = x2 - x1, y2 - y1 + local d2 = dx * dx + dy * dy + if d2 > 0 then local inv = 1 / sqrt(d2); dx =dx* inv; dy =dy* inv end + dx =dx* hw; dy =dy* hw + local b, o = dl.VtxBuffer.Buf, (dl._VtxWritePtr - 1) * VTX_STRIDE + writef64(b, o, x1 + dy); writef64(b, o + 8, y1 - dx); writef64(b, o + 16, u0); writef64(b, o + 24, v0); writeu32(b, o + 32, col) + o =o+ VTX_STRIDE + writef64(b, o, x2 + dy); writef64(b, o + 8, y2 - dx); writef64(b, o + 16, u0); writef64(b, o + 24, v0); writeu32(b, o + 32, col) + o =o+ VTX_STRIDE + writef64(b, o, x2 - dy); writef64(b, o + 8, y2 + dx); writef64(b, o + 16, u1); writef64(b, o + 24, v1); writeu32(b, o + 32, col) + o =o+ VTX_STRIDE + writef64(b, o, x1 - dy); writef64(b, o + 8, y1 + dx); writef64(b, o + 16, u1); writef64(b, o + 24, v1); writeu32(b, o + 32, col) + local idx, id, iw = dl._VtxCurrentIdx, dl.IdxBuffer, dl._IdxWritePtr + id[iw] = idx; id[iw + 1] = idx + 1; id[iw + 2] = idx + 2 + id[iw + 3] = idx; id[iw + 4] = idx + 2; id[iw + 5] = idx + 3 + local zb, zw = dl.ZBuffer, dl._ZWritePtr + zb[zw] = z; zb[zw + 1] = z + dl._VtxWritePtr =dl._VtxWritePtr+ 4; dl._IdxWritePtr = iw + 6; dl._VtxCurrentIdx = idx + 4; dl._ZWritePtr = zw + 2 + end + + local function LineInit(r) + local hw = r.HalfWeight + local u0, v0, u1, v1, fringe = ImGui.GetWindowDrawList():_SelectLineTexture(hw * 2.0, r.DLFlags) + r.HalfWeight, r.U0, r.V0, r.U1, r.V1 = hw + fringe * 0.5, u0, v0, u1, v1 + end + local function WhiteInit(r) + local uv = ImGui.GetDrawListSharedData().TexUvWhitePixel + r.U, r.V = uv.x, uv.y + end + + -- Shared segment render: clip, project, emit (P1 -> P2) + local function Segment(r, dl, prim, x1, y1, z1, x2, y2, z2) + local t0, t1 = Clip(x1, y1, z1, x2, y2, z2) + if t0 == nil then return false end + local dx, dy, dz = x2 - x1, y2 - y1, z2 - z1 + local ax, ay = ToPixels(x1 + dx * t0, y1 + dy * t0, z1 + dz * t0) + local bx, by = ToPixels(x1 + dx * t1, y1 + dy * t1, z1 + dz * t1) + PrimLine(dl, ax, ay, bx, by, r.HalfWeight, GetCol(r, prim), r.U0, r.V0, r.U1, r.V1, + Depth((x1 + x2) * 0.5, (y1 + y2) * 0.5, (z1 + z2) * 0.5)) + return true + end + + local function LineStripRender(r, dl, prim) + local g = r.Getter + local x2, y2, z2 = g.Get(g, prim + 1) + local vis = Segment(r, dl, prim, r.X1, r.Y1, r.Z1, x2, y2, z2) + r.X1, r.Y1, r.Z1 = x2, y2, z2 + return vis + end + local function LineStripSkipRender(r, dl, prim) + local g = r.Getter + local x2, y2, z2 = g.Get(g, prim + 1) + local x1, y1, z1 = r.X1, r.Y1, r.Z1 + local vis = false + if x1 == x1 and y1 == y1 and z1 == z1 and x2 == x2 and y2 == y2 and z2 == z2 then + vis = Segment(r, dl, prim, x1, y1, z1, x2, y2, z2) + end + if x2 == x2 and y2 == y2 and z2 == z2 then r.X1, r.Y1, r.Z1 = x2, y2, z2 end + return vis + end + local function LineSegmentsRender(r, dl, prim) + local g = r.Getter + local x1, y1, z1 = g.Get(g, prim * 2) + local x2, y2, z2 = g.Get(g, prim * 2 + 1) + if x1 == x1 and y1 == y1 and z1 == z1 and x2 == x2 and y2 == y2 and z2 == z2 then + return Segment(r, dl, prim, x1, y1, z1, x2, y2, z2) + end + return false + end + local line_renders = { Strip = LineStripRender, StripSkip = LineStripSkipRender, Segments = LineSegmentsRender } + -- kind: "Strip" | "StripSkip" | "Segments" + function internal.RendererLine(kind, getter, weight) + local r = { Getter = getter, HalfWeight = max(1.0, weight) * 0.5, IdxConsumed = 6, VtxConsumed = 4, + Prims = (kind == "Segments" and{(math.floor(getter.Count / 2 ))}or{(getter.Count - 1)})[1], + Init = LineInit, Render = line_renders[kind] } + if kind ~= "Segments" then r.X1, r.Y1, r.Z1 = getter.Get(getter, 0) end + return r + end + + local function MarkersFillRender(r, dl, prim) + local g = r.Getter + local x, y, z = g.Get(g, prim) + if not (x >= bx0 and x <= bx1 and y >= by0 and y <= by1 and z >= bz0 and z <= bz1) then return false end + local px, py = ToPixels(x, y, z) + local col = GetCol(r, prim) + local size = (r.Sizes and{r.Sizes[prim + 1] }or{r.Size +})[1] local m, count, u, v = r.Marker, r.Count, r.U, r.V + local b, o = dl.VtxBuffer.Buf, (dl._VtxWritePtr - 1) * VTX_STRIDE + for i = 0, count - 1 do + writef64(b, o, px + m[i * 2 + 1] * size); writef64(b, o + 8, py + m[i * 2 + 2] * size) + writef64(b, o + 16, u); writef64(b, o + 24, v); writeu32(b, o + 32, col) + o =o+ VTX_STRIDE + end + local idx, id, iw = dl._VtxCurrentIdx, dl.IdxBuffer, dl._IdxWritePtr + local zb, zw, depth = dl.ZBuffer, dl._ZWritePtr, Depth(x, y, z) + for i = 2, count - 1 do + id[iw] = idx; id[iw + 1] = idx + i - 1; id[iw + 2] = idx + i + iw =iw+ 3 + zb[zw] = depth; zw =zw+ 1 + end + dl._VtxWritePtr =dl._VtxWritePtr+ count; dl._IdxWritePtr = iw; dl._VtxCurrentIdx = idx + count; dl._ZWritePtr = zw + return true + end + function internal.RendererMarkersFill(getter, marker, count) + return { Prims = getter.Count, IdxConsumed = (count - 2) * 3, VtxConsumed = count, + Getter = getter, Marker = marker, Count = count, Init = WhiteInit, Render = MarkersFillRender } + end + + local function MarkersLineRender(r, dl, prim) + local g = r.Getter + local x, y, z = g.Get(g, prim) + if not (x >= bx0 and x <= bx1 and y >= by0 and y <= by1 and z >= bz0 and z <= bz1) then return false end + local px, py = ToPixels(x, y, z) + local col = GetCol(r, prim) + local size = (r.Sizes and{r.Sizes[prim + 1] }or{r.Size +})[1] local m, hw, depth = r.Marker, r.HalfWeight, Depth(x, y, z) + for i = 0, r.Count - 1, 2 do + PrimLine(dl, px + m[i * 2 + 1] * size, py + m[i * 2 + 2] * size, px + m[i * 2 + 3] * size, py + m[i * 2 + 4] * size, + hw, col, r.U0, r.V0, r.U1, r.V1, depth) + end + return true + end + function internal.RendererMarkersLine(getter, marker, count, weight) + return { Prims = getter.Count, IdxConsumed = math.floor(count / 2 )* 6, VtxConsumed = math.floor(count / 2 )* 4, + Getter = getter, Marker = marker, Count = count, HalfWeight = max(1.0, weight) * 0.5, + Init = LineInit, Render = MarkersLineRender } + end + + local function InBox(x, y, z) return x >= bx0 and x <= bx1 and y >= by0 and y <= by1 and z >= bz0 and z <= bz1 end + local function Vtx(b, o, x, y, z, u, v, col) + local px, py = ToPixels(x, y, z) + writef64(b, o, px); writef64(b, o + 8, py); writef64(b, o + 16, u); writef64(b, o + 24, v); writeu32(b, o + 32, col) + end + -- Two triangles (0,1,2) (0,2,3) for the 4 vertices just written + local function QuadIdx(dl, z0, z1) + local idx, id, iw = dl._VtxCurrentIdx, dl.IdxBuffer, dl._IdxWritePtr + id[iw] = idx; id[iw + 1] = idx + 1; id[iw + 2] = idx + 2 + id[iw + 3] = idx; id[iw + 4] = idx + 2; id[iw + 5] = idx + 3 + local zb, zw = dl.ZBuffer, dl._ZWritePtr + zb[zw] = z0; zb[zw + 1] = z1 + dl._VtxWritePtr =dl._VtxWritePtr+ 4; dl._IdxWritePtr = iw + 6; dl._VtxCurrentIdx = idx + 4; dl._ZWritePtr = zw + 2 + end + + local function TriangleFillRender(r, dl, prim) + local g, i = r.Getter, 3 * prim + local x0, y0, z0 = g.Get(g, i) + local x1, y1, z1 = g.Get(g, i + 1) + local x2, y2, z2 = g.Get(g, i + 2) + if not InBox(x0, y0, z0) and not InBox(x1, y1, z1) and not InBox(x2, y2, z2) then return false end + local b, o, u, v = dl.VtxBuffer.Buf, (dl._VtxWritePtr - 1) * VTX_STRIDE, r.U, r.V + Vtx(b, o, x0, y0, z0, u, v, GetCol(r, i)) + Vtx(b, o + VTX_STRIDE, x1, y1, z1, u, v, GetCol(r, i + 1)) + Vtx(b, o + 2 * VTX_STRIDE, x2, y2, z2, u, v, GetCol(r, i + 2)) + local idx, id, iw = dl._VtxCurrentIdx, dl.IdxBuffer, dl._IdxWritePtr + id[iw] = idx; id[iw + 1] = idx + 1; id[iw + 2] = idx + 2 + dl.ZBuffer[dl._ZWritePtr] = Depth((x0 + x1 + x2) / 3, (y0 + y1 + y2) / 3, (z0 + z1 + z2) / 3) + dl._VtxWritePtr =dl._VtxWritePtr+ 3; dl._IdxWritePtr = iw + 3; dl._VtxCurrentIdx = idx + 3; dl._ZWritePtr =dl._ZWritePtr+ 1 + return true + end + function internal.RendererTriangleFill(getter) + return { Getter = getter, Prims = math.floor(getter.Count / 3), IdxConsumed = 3, VtxConsumed = 3, Init = WhiteInit, Render = TriangleFillRender } + end + + local function QuadFillRender(r, dl, prim) + local g, i = r.Getter, 4 * prim + local x0, y0, z0 = g.Get(g, i) + local x1, y1, z1 = g.Get(g, i + 1) + local x2, y2, z2 = g.Get(g, i + 2) + local x3, y3, z3 = g.Get(g, i + 3) + if not InBox(x0, y0, z0) and not InBox(x1, y1, z1) and not InBox(x2, y2, z2) and not InBox(x3, y3, z3) then return false end + local b, o = dl.VtxBuffer.Buf, (dl._VtxWritePtr - 1) * VTX_STRIDE + local tex = r.TexRef + if tex ~= nil then + -- RendererQuadImage: per-corner UVs, constant tint + dl:SetTexture(tex) + local uv, col = r.UVs, r.Col + Vtx(b, o, x0, y0, z0, uv[1], uv[2], col) + Vtx(b, o + VTX_STRIDE, x1, y1, z1, uv[3], uv[4], col) + Vtx(b, o + 2 * VTX_STRIDE, x2, y2, z2, uv[5], uv[6], col) + Vtx(b, o + 3 * VTX_STRIDE, x3, y3, z3, uv[7], uv[8], col) + else + local u, v = r.U, r.V + Vtx(b, o, x0, y0, z0, u, v, GetCol(r, i)) + Vtx(b, o + VTX_STRIDE, x1, y1, z1, u, v, GetCol(r, i + 1)) + Vtx(b, o + 2 * VTX_STRIDE, x2, y2, z2, u, v, GetCol(r, i + 2)) + Vtx(b, o + 3 * VTX_STRIDE, x3, y3, z3, u, v, GetCol(r, i + 3)) + end + local z = Depth((x0 + x1 + x2 + x3) / 4, (y0 + y1 + y2 + y3) / 4, (z0 + z1 + z2 + z3) / 4) + QuadIdx(dl, z, z) + if tex ~= nil then dl:ResetTexture() end + return true + end + function internal.RendererQuadFill(getter) + return { Getter = getter, Prims = math.floor(getter.Count / 4), IdxConsumed = 6, VtxConsumed = 4, Init = WhiteInit, Render = QuadFillRender } + end + -- uvs: flat {u0, v0, u1, v1, u2, v2, u3, v3} + function internal.RendererQuadImage(getter, tex_ref, uvs, col) + return { Getter = getter, Prims = math.floor(getter.Count / 4), IdxConsumed = 6, VtxConsumed = 4, Init = WhiteInit, + Render = QuadFillRender, TexRef = tex_ref, UVs = uvs, Col = col } + end + + local function SurfaceInit(r) + WhiteInit(r) + -- Compute min and max values for the colormap (if not solid fill) + local n = GImPlot3D.NextItemData + r.N = n + if n.IsAutoFill then + local g, lo, hi = r.Getter, HUGE, -HUGE + for i = 0, g.Count - 1 do + local _, _, z = g.Get(g, i) + lo = min(lo, z); hi = max(hi, z) + end + r.Min, r.Max = lo, hi + end + end + local SampleU32 + local function SurfaceCol(r, vi, z) + local s = r.N.Spec + if s.FillColors ~= nil then return MulAlpha(s.FillColors[vi + 1], s.FillAlpha) end + if r.N.IsAutoFill then + local lo, hi = r.Min, r.Max + if r.ScaleMin ~= 0.0 or r.ScaleMax ~= 0.0 then lo, hi = r.ScaleMin, r.ScaleMax end + local t = hi == lo and 0 or(z - lo) / (hi - lo) -- ImRemap01 + SampleU32 = SampleU32 or internal.SampleColormapU32 + return MulAlpha(SampleU32(math.clamp(t, 0.0, 1.0)), s.FillAlpha) + end + return r.Col + end + local function SurfaceFillRender(r, dl, prim) + local xc = r.XCount + local x, y = prim % (xc - 1), math.floor(prim / (xc - 1) +) local i0, i1, i2, i3 = x + y * xc, x + 1 + y * xc, x + 1 + (y + 1) * xc, x + (y + 1) * xc + local g = r.Getter + local x0, y0, z0 = g.Get(g, i0) + local x1, y1, z1 = g.Get(g, i1) + local x2, y2, z2 = g.Get(g, i2) + local x3, y3, z3 = g.Get(g, i3) + if not InBox(x0, y0, z0) and not InBox(x1, y1, z1) and not InBox(x2, y2, z2) and not InBox(x3, y3, z3) then return false end + local b, o, u, v = dl.VtxBuffer.Buf, (dl._VtxWritePtr - 1) * VTX_STRIDE, r.U, r.V + Vtx(b, o, x0, y0, z0, u, v, SurfaceCol(r, i0, z0)) + Vtx(b, o + VTX_STRIDE, x1, y1, z1, u, v, SurfaceCol(r, i1, z1)) + Vtx(b, o + 2 * VTX_STRIDE, x2, y2, z2, u, v, SurfaceCol(r, i2, z2)) + Vtx(b, o + 3 * VTX_STRIDE, x3, y3, z3, u, v, SurfaceCol(r, i3, z3)) + QuadIdx(dl, Depth((x0 + x1 + x2) / 3, (y0 + y1 + y2) / 3, (z0 + z1 + z2) / 3), + Depth((x0 + x2 + x3) / 3, (y0 + y2 + y3) / 3, (z0 + z2 + z3) / 3)) + return true + end + function internal.RendererSurfaceFill(getter, x_count, y_count, col, scale_min, scale_max) + return { Getter = getter, Prims = (x_count - 1) * (y_count - 1), IdxConsumed = 6, VtxConsumed = 4, Min = 0, Max = 0, + XCount = x_count, YCount = y_count, Col = col, ScaleMin = scale_min, ScaleMax = scale_max, + Init = SurfaceInit, Render = SurfaceFillRender } + end + + -- [Port] color getter (GetterConstColor/GetterIdxColor) and size getter folded into renderer fields + function internal.RenderPrimitivesEx(r, col, cols, alpha, size, sizes) + local plot = GImPlot3D.CurrentPlot + local dl = plot.DrawList + r.Col, r.Cols, r.Alpha, r.Size, r.Sizes, r.DLFlags = col, cols, alpha or 1.0, size, sizes, dl._Flags + if ImHasFlag(plot.Flags, ImPlot3D.ImPlot3DFlags.NoClip) then + bx0, by0, bz0, bx1, by1, bz1 = -HUGE, -HUGE, -HUGE, HUGE, HUGE, HUGE + else + local a = plot.Axes + bx0, by0, bz0 = a[0].Range.Min, a[1].Range.Min, a[2].Range.Min + bx1, by1, bz1 = a[0].Range.Max, a[1].Range.Max, a[2].Range.Max + end + CacheTransform(plot) + -- Find how many can be reserved up to end of current draw command's limit + local prims = min(r.Prims, math.floor((internal.ImDrawList3D_MaxIdx - dl._VtxCurrentIdx) / r.VtxConsumed)) + if prims <= 0 then return end + dl:PrimReserve(prims * r.IdxConsumed, prims * r.VtxConsumed) + r.Init(r) + local render, culled = r.Render, 0 + for i = 0, prims - 1 do + if not render(r, dl, i) then culled =culled+ 1 end + end + dl:PrimUnreserve(culled * r.IdxConsumed, culled * r.VtxConsumed) + end + end + + -------------------------------------------------------------------------- + -- [SECTION] Markers, PlotScatter, PlotLine + -- [Port] marker shapes are flat {x1, y1, x2, y2, ...} arrays + -- [Port] PlotX(label_id, xs, ys, zs, count?, spec?): xs/ys/zs are 1-based Lua arrays; count defaults to #xs. + -- spec is an ImPlot3DSpec or a plain table of spec fields. Stride is in elements (default 1). + -------------------------------------------------------------------------- + do + local M, LineFlags = ImPlot3D.ImPlot3DMarker, ImPlot3D.ImPlot3DLineFlags + local ImHasFlag = internal.ImHasFlag + local S12, S32 = 0.70710678118, 0.86602540378 + local FILL = { + [M.Circle] = { 1.0, 0.0, 0.809017, 0.58778524, 0.30901697, 0.95105654, -0.30901703, 0.9510565, -0.80901706, 0.5877852, + -1.0, 0.0, -0.80901694, -0.58778536, -0.3090171, -0.9510565, 0.30901712, -0.9510565, 0.80901694, -0.5877853 }, + [M.Square] = { S12, S12, S12, -S12, -S12, -S12, -S12, S12 }, + [M.Diamond] = { 1, 0, 0, -1, -1, 0, 0, 1 }, + [M.Up] = { S32, 0.5, 0, -1, -S32, 0.5 }, + [M.Down] = { S32, -0.5, 0, 1, -S32, -0.5 }, + [M.Left] = { -1, 0, 0.5, S32, 0.5, -S32 }, + [M.Right] = { 1, 0, -0.5, S32, -0.5, -S32 }, + } + -- Line markers: closed outlines of the fill shapes as segment pairs, plus the line-only markers + local LINE = { + [M.Asterisk] = { -S32, -0.5, S32, 0.5, -S32, 0.5, S32, -0.5, 0, -1, 0, 1 }, + [M.Plus] = { -1, 0, 1, 0, 0, -1, 0, 1 }, + [M.Cross] = { -S12, -S12, S12, S12, S12, -S12, -S12, S12 }, + } + for m, f in __iter(FILL) do + local n, out = math.floor(#f / 2), {} + for i = 0, n - 1 do + local j = (i + 1) % n + table.insert(out, f[i * 2 + 1]); table.insert(out, f[i * 2 + 2]) + table.insert(out, f[j * 2 + 1]); table.insert(out, f[j * 2 + 2]) + end + LINE[m] = out + end + + local function RenderMarkers(getter, marker, rend_fill, col_fill, cols_fill, fill_alpha, rend_line, col_line, cols_line, size, sizes, weight) + local f = FILL[marker] + if rend_fill and f then + internal.RenderPrimitivesEx(internal.RendererMarkersFill(getter, f, math.floor(#f / 2)), col_fill, cols_fill, fill_alpha, size, sizes) + end + local l = LINE[marker] + if rend_line and l then + internal.RenderPrimitivesEx(internal.RendererMarkersLine(getter, l, math.floor(#l / 2), weight), col_line, cols_line, 1.0, size, sizes) + end + end + internal.RenderMarkers = RenderMarkers + + function internal.RenderColoredMarkers(getter, n) + local s = n.Spec + RenderMarkers(getter, s.Marker, n.RenderMarkerFill, ImGui.GetColorU32(s.MarkerFillColor), s.MarkerFillColors, s.FillAlpha, + n.RenderMarkerLine, ImGui.GetColorU32(s.MarkerLineColor), s.MarkerLineColors, s.MarkerSize, s.MarkerSizes, s.LineWeight) + end + + -- [Port] overload dispatch: (label, xs, ys, zs, [count], [spec]) + local function Args(xs, count, spec) + if type(count) == "table" then count, spec = nil, count end + return count or #xs, spec or ImPlot3D.ImPlot3DSpec() + end + local function Stride(spec) return (spec.Stride == nil or spec.Stride == ImPlot3D.IMPLOT3D_AUTO )and 1 or spec.Stride end + + function internal.PlotScatterEx(label_id, getter, spec) + if internal.BeginItemEx(label_id, getter, spec, spec.MarkerLineColor, spec.Marker or M.Auto) then + local n = GImPlot3D.NextItemData + -- Scatter always renders a marker; default to Circle + if n.Spec.Marker == M.None then n.Spec.Marker = M.Circle end + internal.RenderColoredMarkers(getter, n) + internal.EndItem() + end + end + + function ImPlot3D.PlotScatter(label_id, xs, ys, zs, count, spec) + count, spec = Args(xs, count, spec) + if count < 1 then return end + internal.PlotScatterEx(label_id, internal.GetterXYZ(xs, ys, zs, count, spec.Offset, Stride(spec)), spec) + end + + function internal.PlotLineEx(label_id, getter, spec) + if internal.BeginItemEx(label_id, getter, spec, spec.LineColor, spec.Marker or M.Auto) then + local n = GImPlot3D.NextItemData + local s = n.Spec + local flags = s.Flags + if getter.Count >= 2 and n.RenderLine then + local col = ImGui.GetColorU32(s.LineColor) + local kind, g = "Strip", getter + if ImHasFlag(flags, LineFlags.Segments) then + kind = "Segments" + else + if ImHasFlag(flags, LineFlags.Loop) then g = internal.GetterLoop(getter) end + if ImHasFlag(flags, LineFlags.SkipNaN) then kind = "StripSkip" end + end + internal.RenderPrimitivesEx(internal.RendererLine(kind, g, s.LineWeight), col, s.LineColors, 1.0) + end + -- Render markers + if s.Marker ~= M.None then internal.RenderColoredMarkers(getter, n) end + internal.EndItem() + end + end + + function ImPlot3D.PlotLine(label_id, xs, ys, zs, count, spec) + count, spec = Args(xs, count, spec) + if count < 2 then return end + internal.PlotLineEx(label_id, internal.GetterXYZ(xs, ys, zs, count, spec.Offset, Stride(spec)), spec) + end + + -- Shared body of PlotTriangle/PlotQuad/PlotSurface/PlotMesh: fill renderer, line getter, markers + local FillFlags = ImPlot3D.ImPlot3DTriangleFlags -- same NoLines/NoFill/NoMarkers bits for all fill items + local function FillLinesMarkers(n, getter, fill, line_getter, min_fill) + local s = n.Spec + if getter.Count >= min_fill and n.RenderFill and fill and not ImHasFlag(s.Flags, FillFlags.NoFill) then + fill() + end + if line_getter and getter.Count >= 2 and n.RenderLine and not ImHasFlag(s.Flags, FillFlags.NoLines) then + internal.RenderPrimitivesEx(internal.RendererLine("Segments", line_getter, s.LineWeight), ImGui.GetColorU32(s.LineColor), s.LineColors, 1.0) + end + if s.Marker ~= M.None and not ImHasFlag(s.Flags, FillFlags.NoMarkers) then internal.RenderColoredMarkers(getter, n) end + internal.EndItem() + end + + local function PlotPolyEx(label_id, getter, spec, ctor, line_getter, min_fill) + if internal.BeginItemEx(label_id, getter, spec, spec.FillColor, spec.Marker) then + local n = GImPlot3D.NextItemData + local s = n.Spec + FillLinesMarkers(n, getter, function() + internal.RenderPrimitivesEx(ctor(getter), ImGui.GetColorU32(s.FillColor), s.FillColors, s.FillAlpha) + end, line_getter(getter), min_fill) + end + end + function internal.PlotTriangleEx(label_id, getter, spec) + PlotPolyEx(label_id, getter, spec, internal.RendererTriangleFill, internal.GetterTriangleLines, 3) + end + function internal.PlotQuadEx(label_id, getter, spec) + PlotPolyEx(label_id, getter, spec, internal.RendererQuadFill, internal.GetterQuadLines, 4) + end + + function ImPlot3D.PlotTriangle(label_id, xs, ys, zs, count, spec) + count, spec = Args(xs, count, spec) + if count < 3 then return end + internal.PlotTriangleEx(label_id, internal.GetterXYZ(xs, ys, zs, count, spec.Offset, Stride(spec)), spec) + end + + function ImPlot3D.PlotQuad(label_id, xs, ys, zs, count, spec) + count, spec = Args(xs, count, spec) + if count < 3 then return end + internal.PlotQuadEx(label_id, internal.GetterXYZ(xs, ys, zs, count, spec.Offset, Stride(spec)), spec) + end + + function internal.PlotSurfaceEx(label_id, getter, x_count, y_count, scale_min, scale_max, spec) + if internal.BeginItemEx(label_id, getter, spec, spec.FillColor, spec.Marker) then + local n = GImPlot3D.NextItemData + FillLinesMarkers(n, getter, function() + local col = ImGui.GetColorU32(n.Spec.FillColor) + internal.RenderPrimitivesEx(internal.RendererSurfaceFill(getter, x_count, y_count, col, scale_min, scale_max), col) + end, internal.GetterSurfaceLines(getter, x_count, y_count), 4) + end + end + + -- PlotSurface(label_id, xs, ys, zs, x_count, y_count, [scale_min], [scale_max], [spec]) + -- Grid of x_count * y_count points, row-major (index = x + y * x_count). Fill is colormap-shaded by z + -- (over [scale_min, scale_max], or the data's z range when both are 0) unless FillColor/FillColors is set. + function ImPlot3D.PlotSurface(label_id, xs, ys, zs, x_count, y_count, scale_min, scale_max, spec) + if type(scale_min) == "table" then scale_min, spec = nil, scale_min end + spec = spec or ImPlot3D.ImPlot3DSpec() + local count = x_count * y_count + if count < 4 then return end + internal.PlotSurfaceEx(label_id, internal.GetterXYZ(xs, ys, zs, count, spec.Offset, Stride(spec)), x_count, y_count, + scale_min or 0.0, scale_max or 0.0, spec) + end + + function internal.PlotMeshEx(label_id, getter, getter_triangles, spec) + if internal.BeginItemEx(label_id, getter, spec, spec.FillColor, spec.Marker) then + local n = GImPlot3D.NextItemData + local s = n.Spec + -- Mesh lines are only drawn with an explicit LineColor (not the auto item color) + FillLinesMarkers(n, getter, function() + internal.RenderPrimitivesEx(internal.RendererTriangleFill(getter_triangles), ImGui.GetColorU32(s.FillColor), s.FillColors, s.FillAlpha) + end, (n.IsAutoLine and{nil }or{(internal.GetterTriangleLines(getter_triangles))})[1], 3) + end + end + + -- PlotMesh(label_id, vtx_xs, vtx_ys, vtx_zs, idxs, [vtx_count], [idx_count], [spec]) + -- [Port] idxs is a 1-based Lua array holding 0-based vertex indices, exactly as upstream (idxs[1] == 0 is the + -- first vertex), so upstream index data / ImPlot3D.Meshes can be used unchanged. + function ImPlot3D.PlotMesh(label_id, vtx_xs, vtx_ys, vtx_zs, idxs, vtx_count, idx_count, spec) + if type(vtx_count) == "table" then vtx_count, idx_count, spec = nil, nil, vtx_count end + vtx_count, idx_count, spec = vtx_count or #vtx_xs, idx_count or #idxs, spec or ImPlot3D.ImPlot3DSpec() + if vtx_count < 3 or idx_count < 3 then return end + local getter = internal.GetterXYZ(vtx_xs, vtx_ys, vtx_zs, vtx_count, spec.Offset, Stride(spec)) + internal.PlotMeshEx(label_id, getter, internal.GetterMeshTriangles(getter, idxs, idx_count), spec) + end + + -- PlotImage(label_id, tex_ref, center, axis_u, axis_v, [uv0], [uv1], [tint_col], [spec]) + -- PlotImage(label_id, tex_ref, p0, p1, p2, p3, [uv0], [uv1], [uv2], [uv3], [tint_col], [spec]) + -- [Port] tex_ref: ImTextureRef (as ImDrawList:AddImage); a raw ImTextureID is wrapped. Points are ImPlot3DPoint. + function ImPlot3D.PlotImage(label_id, tex_ref, a, b, c, d, ...) + local p0, p1, p2, p3, uv0, uv1, uv2, uv3, tint, spec + if d ~= nil and d.z ~= nil then + p0, p1, p2, p3 = a, b, c, d + uv0, uv1, uv2, uv3, tint, spec = ... + uv0, uv1 = uv0 or ImVec2(0, 0), uv1 or ImVec2(1, 0) + uv2, uv3 = uv2 or ImVec2(1, 1), uv3 or ImVec2(0, 1) + else + local center, u, v = a, b, c + local uv_a, uv_b = d, nil + uv_b, tint, spec = ... + uv_a, uv_b = uv_a or ImVec2(0, 0), uv_b or ImVec2(1, 1) + -- Compute corners from center and axes + p0 = ImPlot3D.ImPlot3DPoint(center.x - u.x - v.x, center.y - u.y - v.y, center.z - u.z - v.z) -- Bottom-left + p1 = ImPlot3D.ImPlot3DPoint(center.x + u.x - v.x, center.y + u.y - v.y, center.z + u.z - v.z) -- Bottom-right + p2 = ImPlot3D.ImPlot3DPoint(center.x + u.x + v.x, center.y + u.y + v.y, center.z + u.z + v.z) -- Top-right + p3 = ImPlot3D.ImPlot3DPoint(center.x - u.x + v.x, center.y - u.y + v.y, center.z - u.z + v.z) -- Top-left + -- Map ImPlot-style 2-point UVs into full 4-corner UVs + uv0, uv1, uv2, uv3 = uv_a, ImVec2(uv_b.x, uv_a.y), uv_b, ImVec2(uv_a.x, uv_b.y) + end + tint = tint or ImVec4(1, 1, 1, 1) + if type(tint) == "number" then tint = ImGui.ColorConvertU32ToFloat4(tint) end + spec = spec or ImPlot3D.ImPlot3DSpec() + if type(tex_ref) ~= "table" then tex_ref = G.ImTextureRef(tex_ref) end + local gp = GImPlot3D + IM_ASSERT(gp.CurrentPlot ~= nil, "PlotImage() needs to be called between BeginPlot() and EndPlot()!") + ImPlot3D.SetupLock() + local getter = internal.GetterXYZ({ p0.x, p1.x, p2.x, p3.x }, { p0.y, p1.y, p2.y, p3.y }, { p0.z, p1.z, p2.z, p3.z }, 4) + -- Invert Y from UVs + local uvs = { uv0.x, 1 - uv0.y, uv1.x, 1 - uv1.y, uv2.x, 1 - uv2.y, uv3.x, 1 - uv3.y } + if internal.BeginItemEx(label_id, getter, spec, tint, spec.Marker) then + local tint_col32 = ImGui.ColorConvertFloat4ToU32(tint) + internal.GetCurrentItem().Color = tint_col32 + if bit32.band(tint_col32, G.IM_COL32_A_MASK or 0xFF000000) ~= 0 then + internal.RenderPrimitivesEx(internal.RendererQuadImage(getter, tex_ref, uvs, tint_col32), tint_col32) + end + internal.EndItem() + end + end + + -- PlotText(text, x, y, z, [angle], [pix_offset]) + -- PlotDummy(label_id, [spec]): legend entry only + function ImPlot3D.PlotDummy(label_id, spec) + spec = internal.CopySpec({}, spec) + -- Pick the first non-auto color from the spec to override the legend icon color + local item_col = spec.LineColor + for _, k in __iter({ "FillColor", "MarkerLineColor", "MarkerFillColor" }) do + if internal.IsColorAuto(item_col) then item_col = spec[k] end + end + if internal.BeginItem(label_id, spec, item_col, spec.Marker) then internal.EndItem() end + end + + function ImPlot3D.PlotText(text, x, y, z, angle, pix_offset) + local gp = GImPlot3D + IM_ASSERT(gp.CurrentPlot ~= nil, "PlotText() needs to be called between BeginPlot() and EndPlot()!") + ImPlot3D.SetupLock() + local plot = gp.CurrentPlot + if not ImHasFlag(plot.Flags, ImPlot3D.ImPlot3DFlags.NoClip) then + local a = plot.Axes + for i, v in __iter({ x, y, z }) do + local r = a[i - 1].Range + if not (v >= r.Min and v <= r.Max) then return end + end + end + local p = ImPlot3D.PlotToPixels(x, y, z) + if pix_offset then p = ImVec2(p.x + pix_offset.x, p.y + pix_offset.y) end + internal.AddTextRotated(ImPlot3D.GetPlotDrawList(), p, angle or 0.0, ImPlot3D.GetStyleColorU32(ImPlot3D.ImPlot3DCol.InlayText), text) + end + end + + -------------------------------------------------------------------------- + -- [SECTION] Legend Utils + -------------------------------------------------------------------------- + do + local ImHasFlag, IG = internal.ImHasFlag, internal.ItemGroup + local LF = ImPlot3D.ImPlot3DLegendFlags + local band, bnot, lshift = bit32.band, bit32.bnot, bit32.lshift + local ImRect = G.ImRect + + local function ImAlphaU32(col, alpha) return band(col, bnot(lshift(math.floor((1 - alpha) * 255), 24))) end + internal.ImAlphaU32 = ImAlphaU32 + + function internal.CalcLegendSize(items, pad, spacing, vertical) + local n = IG.GetLegendCount(items) + local txt_ht = ImGui.GetTextLineHeight() + local icon_size = txt_ht + local max_w, sum_w = 0, 0 + for i = 0, n - 1 do + local w = ImGui.CalcTextSize(IG.GetLegendLabel(items, i), nil, true).x + max_w = math.max(max_w, w) + sum_w =sum_w+ w + end + if vertical then + return ImVec2(pad.x * 2 + icon_size + max_w, pad.y * 2 + n * txt_ht + (n - 1) * spacing.y) + end + return ImVec2(pad.x * 2 + icon_size * n + sum_w + (n - 1) * spacing.x, pad.y * 2 + txt_ht) + end + + -- [Port] modifies legend_rect in place, returns clamped + function internal.ClampLegendRect(r, outer, pad) + local clamped = false + local minx, miny, maxx, maxy = outer.Min.x + pad.x, outer.Min.y + pad.y, outer.Max.x - pad.x, outer.Max.y - pad.y + if r.Min.x < minx then r.Min.x = minx; clamped = true end + if r.Min.y < miny then r.Min.y = miny; clamped = true end + if r.Max.x > maxx then r.Max.x = maxx; clamped = true end + if r.Max.y > maxy then r.Max.y = maxy; clamped = true end + return clamped + end + + function internal.ShowLegendEntries(items, legend_bb, pad, spacing, vertical, draw_list) + local txt_ht = ImGui.GetTextLineHeight() + local icon_size, icon_shrink = txt_ht, 2 + local col_txt = ImPlot3D.GetStyleColorU32(ImPlot3D.ImPlot3DCol.LegendText) + local col_txt_dis = ImAlphaU32(col_txt, 0.25) + local sum_label_width = 0 + local n = IG.GetLegendCount(items) + for i = 0, n - 1 do + local item = IG.GetLegendItem(items, i) + local label = IG.GetLegendLabel(items, i) + local label_width = ImGui.CalcTextSize(label, nil, true).x + local top_left = (vertical and{(legend_bb.Min + pad + ImVec2(0, i * (txt_ht + spacing.y)) +)}or{(legend_bb.Min + pad + ImVec2(i * (icon_size + spacing.x) + sum_label_width, 0) +)})[1] sum_label_width =sum_label_width+ label_width + local icon_min = top_left + ImVec2(icon_shrink, icon_shrink) + local icon_max = top_left + ImVec2(icon_size - icon_shrink, icon_size - icon_shrink) + local label_max = top_left + ImVec2(label_width + icon_size, icon_size) + local col_item = ImAlphaU32(item.Color, 1) + local button_bb = ImRect(icon_min, label_max) + ImGui.KeepAliveID(item.ID) + local item_clk, item_hov, item_hld = false, false, false + if not ImHasFlag(items.Legend.Flags, LF.NoButtons) then + item_clk, item_hov, item_hld = ImGui.ButtonBehavior(button_bb, item.ID) + end + if item_clk then item.Show = not item.Show end + local col_txt_hl + if item_hov and not ImHasFlag(items.Legend.Flags, LF.NoHighlightItem) then + item.LegendHovered = true + col_txt_hl = internal.ImMixU32(col_txt, col_item, 64) + else + item.LegendHovered = false + col_txt_hl = ImGui.GetColorU32(col_txt, nil, true) + end + local col_icon + if item_hld then + col_icon = (item.Show and{(ImAlphaU32(col_item, 0.5) )}or{(ImGui.GetColorU32(G.ImGuiCol.TextDisabled, 0.5) +)})[1] elseif item_hov then + col_icon = (item.Show and{(ImAlphaU32(col_item, 0.75) )}or{(ImGui.GetColorU32(G.ImGuiCol.TextDisabled, 0.75) +)})[1] else + col_icon = (item.Show and{col_item }or{col_txt_dis +})[1] end + draw_list:AddRectFilled(icon_min, icon_max, col_icon) + local text_end = ImGui.FindRenderedTextEnd(label) + if text_end > 1 then + draw_list:AddText(top_left + ImVec2(icon_size, 0), (item.Show and{col_txt_hl }or{col_txt_dis})[1], label, text_end) + end + end + end + + function internal.RenderLegend() + local gp = GImPlot3D + local plot = gp.CurrentPlot + if ImHasFlag(plot.Flags, ImPlot3D.ImPlot3DFlags.NoLegend) or IG.GetLegendCount(plot.Items) == 0 then return end + local draw_list = ImGui.GetWindowDrawList() + local IO = ImGui.GetIO() + local style = gp.Style + local legend = plot.Items.Legend + local legend_horz = ImHasFlag(legend.Flags, LF.Horizontal) + local legend_size = internal.CalcLegendSize(plot.Items, style.LegendInnerPadding, style.LegendSpacing, not legend_horz) + local legend_pos = internal.GetLocationPos(plot.PlotRect, legend_size, legend.Location, style.LegendPadding) + legend.Rect = ImRect(legend_pos, legend_pos + legend_size) + legend.RectClamped = ImRect(legend.Rect.Min, legend.Rect.Max) + local legend_scrollable = internal.ClampLegendRect(legend.RectClamped, plot.PlotRect, style.LegendPadding) + -- Test hover (using the clamped rect so off-screen overflow does not register) + local BF = G.ImGuiButtonFlags + local flags = bit32.bor(BF.AllowOverlap, BF.PressedOnClick, BF.PressedOnDoubleClick, BF.MouseButtonLeft, + BF.MouseButtonRight, BF.MouseButtonMiddle, BF.FlattenChildren) + ImGui.KeepAliveID(plot.Items.ID) + local _ + _, legend.Hovered, legend.Held = ImGui.ButtonBehavior(legend.RectClamped, plot.Items.ID, flags) + legend.Hovered = legend.Hovered or legend.RectClamped:Contains(IO.MousePos) + -- Handle legend scrolling + if legend_scrollable then + if legend.Hovered then + ImGui.SetKeyOwner(G.ImGuiKey.MouseWheelY, plot.Items.ID) + if IO.MouseWheel ~= 0.0 then + local max_step = legend.Rect:GetSize() * 0.67 + local step = math.floor(math.min(2 * ImGui.GetFontSize(), max_step.x)) +do local __DARKLUA_VAR= legend.Scroll __DARKLUA_VAR.x =__DARKLUA_VAR.x+ step * IO.MouseWheel +end do local __DARKLUA_VAR0= legend.Scroll __DARKLUA_VAR0.y =__DARKLUA_VAR0.y+ step * IO.MouseWheel +end end + end + local min_off = legend.RectClamped:GetSize() - legend.Rect:GetSize() + legend.Scroll.x = math.clamp(legend.Scroll.x, math.min(min_off.x, 0), 0) + legend.Scroll.y = math.clamp(legend.Scroll.y, math.min(min_off.y, 0), 0) + local scroll = (legend_horz and{(ImVec2(legend.Scroll.x, 0) )}or{(ImVec2(0, legend.Scroll.y) +)})[1] local off = legend.RectClamped.Min - legend.Rect.Min + scroll + legend.Rect = ImRect(legend.Rect.Min + off, legend.Rect.Max + off) + else + legend.Scroll = ImVec2(0, 0) + end + -- Render background and entries (clipped to the clamped rect) + local col_bg = ImPlot3D.GetStyleColorU32(ImPlot3D.ImPlot3DCol.LegendBg) + local col_bd = ImPlot3D.GetStyleColorU32(ImPlot3D.ImPlot3DCol.LegendBorder) + ImGui.PushClipRect(legend.RectClamped.Min, legend.RectClamped.Max, true) + draw_list:AddRectFilled(legend.RectClamped.Min, legend.RectClamped.Max, col_bg) + internal.ShowLegendEntries(plot.Items, legend.Rect, style.LegendInnerPadding, style.LegendSpacing, not legend_horz, draw_list) + draw_list:AddRect(legend.RectClamped.Min, legend.RectClamped.Max, col_bd) + ImGui.PopClipRect() + end + end + + -------------------------------------------------------------------------- + -- [SECTION] ImDrawList3D + -- [Port] VtxBuffer is an ImDrawVtxBuffer (same 36-byte vertex layout as ImDrawList), IdxBuffer/ZBuffer are + -- 1-based Lua arrays sized by IdxSize/ZSize (never shrunk, so no per-frame allocation). Write ptrs are 1-based; + -- _VtxCurrentIdx is 0-based (local to this list) and offset by ImDrawList._VtxCurrentIdx on move. + -- [Port] textures are ImTextureRef (as ImDrawList:AddImage takes); nil stands for upstream ImTextureID(0) (= window default). + -------------------------------------------------------------------------- + do + local DL3 = {} + DL3.__index = DL3 + local MAX_IDX = 4294967295 + internal.ImDrawList3D_MaxIdx = MAX_IDX + + function internal.ImDrawList3D() + local self = setmetatable({ + VtxBuffer = G.ImDrawVtxBuffer(), IdxBuffer = {}, ZBuffer = {}, IdxSize = 0, ZSize = 0, + _VtxCurrentIdx = 0, _VtxWritePtr = 1, _IdxWritePtr = 1, _ZWritePtr = 1, + _Flags = 0, _SharedData = nil, _Order = {}, _TextureBuffer = {}, + }, DL3) + return self + end + + function DL3:ResetBuffers() + self.VtxBuffer.Size = 0 + self.IdxSize, self.ZSize = 0, 0 + self._VtxCurrentIdx = 0 + self._VtxWritePtr, self._IdxWritePtr, self._ZWritePtr = 1, 1, 1 + table.clear(self._TextureBuffer) + self:ResetTexture() + end + + local function SameTex(a, b) + return a == b or (a ~= nil and b ~= nil and a._TexID == b._TexID and a._TexData == b._TexData) + end + + -- [Port] _TextureBuffer items are { TexRef, VtxIdx } + function DL3:SetTexture(tex_ref) + local tb = self._TextureBuffer + local n = #tb + if n == 0 then + -- First texture assignment + tb[1] = { TexRef = tex_ref, VtxIdx = self._VtxCurrentIdx } + return + end + local prev = tb[n] + if prev.VtxIdx == self._VtxCurrentIdx then + -- Same vertex index: update existing texture; drop it if equal to the one before + prev.TexRef = tex_ref + if n >= 2 and SameTex(tb[n - 1].TexRef, tex_ref) then tb[n] = nil end + elseif not SameTex(prev.TexRef, tex_ref) then + tb[n + 1] = { TexRef = tex_ref, VtxIdx = self._VtxCurrentIdx } + end + end + function DL3:ResetTexture() self:SetTexture(nil) end + + function DL3:PrimReserve(idx_count, vtx_count) + IM_ASSERT(idx_count >= 0 and vtx_count >= 0 and idx_count % 3 == 0) + local vb = self.VtxBuffer + local old = vb.Size + vb:resize(old + vtx_count) + self._VtxWritePtr = old + 1 + self._IdxWritePtr = self.IdxSize + 1 + self.IdxSize =self.IdxSize+ idx_count + self._ZWritePtr = self.ZSize + 1 + self.ZSize =self.ZSize+ math.floor(idx_count / 3 +) end + + function DL3:PrimUnreserve(idx_count, vtx_count) +do local __DARKLUA_VAR= self.VtxBuffer __DARKLUA_VAR.Size =__DARKLUA_VAR.Size- vtx_count +end self.IdxSize =self.IdxSize- idx_count + self.ZSize =self.ZSize- math.floor(idx_count / 3 +) end + + -- Move triangles to the current window draw list, sorted by depth + function DL3:SortedMoveToImGuiDrawList() + local draw_list = ImGui.GetWindowDrawList() + local tri_count = self.ZSize + if tri_count == 0 then + self:ResetBuffers() + return + end + -- Sort triangle indices by z (distance from viewer) + local order, Z = self._Order, self.ZBuffer + for i = 1, tri_count do order[i] = i end + for i = #order, tri_count + 1, -1 do order[i] = nil end + table.sort(order, function(a, b) return Z[a] < Z[b] end) + + local vtx_count = self.VtxBuffer.Size + draw_list:PrimReserve(self.IdxSize, vtx_count) + -- Copy vertices (no reordering needed) + local stride = G.VTX_STRIDE or 36 + buffer.copy(draw_list.VtxBuffer.Buf, (draw_list._VtxWritePtr - 1) * stride, self.VtxBuffer.Buf, 0, vtx_count * stride) + local idx_offset = draw_list._VtxCurrentIdx + draw_list._VtxWritePtr =draw_list._VtxWritePtr+ vtx_count + draw_list._VtxCurrentIdx =draw_list._VtxCurrentIdx+ vtx_count + local max_index_allowed = MAX_IDX - idx_offset + -- Copy indices with triangle sorting + local idx_in, idx_out, iw = self.IdxBuffer, draw_list.IdxBuffer.Data, draw_list._IdxWritePtr + local idx_begin = iw + local skipped = 0 + for i = 1, tri_count do + local base = (order[i] - 1) * 3 + local i0, i1, i2 = idx_in[base + 1], idx_in[base + 2], idx_in[base + 3] + if i0 > max_index_allowed or i1 > max_index_allowed or i2 > max_index_allowed then + skipped =skipped+ 3 + else + idx_out[iw] = i0 + idx_offset; idx_out[iw + 1] = i1 + idx_offset; idx_out[iw + 2] = i2 + idx_offset + iw =iw+ 3 + end + end + draw_list._IdxWritePtr = iw + if skipped > 0 then + -- [Port] upstream leaves the skipped indices reserved; give them back so ElemCount stays exact + draw_list.IdxBuffer:shrink(draw_list.IdxBuffer.Size - skipped) +do local __DARKLUA_VAR= draw_list.CmdBuffer.Data[draw_list.CmdBuffer.Size]__DARKLUA_VAR.ElemCount =__DARKLUA_VAR.ElemCount- skipped +end end + -- If multiple textures were used (e.g. PlotImage was called), generate multiple ImDrawCmd + -- [Port] idx_out pointers -> 1-based positions in draw_list.IdxBuffer.Data + local tb = self._TextureBuffer + if #tb > 1 then + local header, cmds = draw_list._CmdHeader, draw_list.CmdBuffer + local default_tex = header.TexRef + local curr_tex = default_tex +do local __DARKLUA_VAR= cmds.Data[cmds.Size]__DARKLUA_VAR.ElemCount =__DARKLUA_VAR.ElemCount- (iw - idx_begin -- Remove elements reserved from PrimReserve +)end local last = idx_begin + for p = idx_begin, iw - 1, 3 do + local vtx_idx = idx_out[p] - idx_offset + local tri_tex = nil + for j = 1, #tb do + if vtx_idx >= tb[j].VtxIdx then tri_tex = tb[j].TexRef end + end + if tri_tex == nil then tri_tex = default_tex end + if not SameTex(tri_tex, curr_tex) then +do local __DARKLUA_VAR0= cmds.Data[cmds.Size]__DARKLUA_VAR0.ElemCount =__DARKLUA_VAR0.ElemCount+ (p - last +)end last = p + curr_tex = tri_tex + header.TexRef = curr_tex + local cmd = G.ImDrawCmd() + local cr = header.ClipRect + cmd.ClipRect.x, cmd.ClipRect.y, cmd.ClipRect.z, cmd.ClipRect.w = cr.x, cr.y, cr.z, cr.w + cmd.TexRef, cmd.VtxOffset, cmd.IdxOffset = curr_tex, header.VtxOffset, p - 1 + cmds:push_back(cmd) + end + end +do local __DARKLUA_VAR0= -- Flush last elements to cmd buffer + cmds.Data[cmds.Size]__DARKLUA_VAR0.ElemCount =__DARKLUA_VAR0.ElemCount+ (iw - last +)end if not SameTex(curr_tex, default_tex) then + -- Restore default texture and flush last draw cmd with custom texture + header.TexRef = default_tex + draw_list:AddDrawCmd() + end + end + self:ResetBuffers() + end + end + + -------------------------------------------------------------------------- + -- [SECTION] Begin/End Plot + -------------------------------------------------------------------------- + do + local Flags = ImPlot3D.ImPlot3DFlags + + function ImPlot3D.BeginPlot(title_id, size, flags) + size = size or ImVec2(-1, 0) + flags = flags or 0 + local gp = GImPlot3D + IM_ASSERT(gp ~= nil, "No current context. Did you call ImPlot3D::CreateContext() or ImPlot3D::SetCurrentContext()?") + IM_ASSERT(gp.CurrentPlot == nil, "Mismatched BeginPlot()/EndPlot()!") + local window = ImGui.GetCurrentWindow() + -- Skip if needed + if window.SkipItems then return false end + -- Get or create plot + local ID = window:GetID(title_id) + local just_created = gp.Plots:GetByKey(ID) == nil + gp.CurrentPlot = gp.Plots:GetOrAddByKey(ID) + local plot = gp.CurrentPlot + gp.CurrentItems = plot.Items + -- Populate plot + plot.ID = ID + plot.Items.ID = ID - 1 + plot.JustCreated = just_created + if just_created then + plot.Rotation = plot.InitialRotation + plot.FitThisFrame = true + for i = 0, 2 do + plot.Axes[i] = internal.ImPlot3DAxis() + plot.Axes[i].FitThisFrame = true + end + end + if plot.PreviousFlags ~= flags then plot.Flags = flags end + plot.PreviousFlags = flags + plot.SetupLocked = false + plot.OpenContextThisFrame = false + plot.RotationCond = ImPlot3D.ImPlot3DCond.None + -- Populate title + plot:SetTitle(title_id) + -- Calculate frame size + local style = gp.Style + local frame_size = ImGui.CalcItemSize(size, style.PlotDefaultSize.x, style.PlotDefaultSize.y) + if frame_size.x < style.PlotMinSize.x and size.x < 0.0 then frame_size.x = style.PlotMinSize.x end + if frame_size.y < style.PlotMinSize.y and size.y < 0.0 then frame_size.y = style.PlotMinSize.y end + -- Create plot ImGui item + local cursor = window.DC.CursorPos + plot.FrameRect = G.ImRect(ImVec2(cursor.x, cursor.y), cursor + frame_size) + ImGui.ItemSize(plot.FrameRect) + if not ImGui.ItemAdd(plot.FrameRect, plot.ID, plot.FrameRect) then + gp.CurrentPlot, gp.CurrentItems, gp.CurrentItem = nil, nil, nil + return false + end + -- Reset legend + local legend = plot.Items.Legend + table.clear(legend.Indices) + table.clear(legend.LabelList) + -- Reset axes + for i = 0, 2 do plot.Axes[i]:Reset() end + -- Push frame rect clipping + ImGui.PushClipRect(plot.FrameRect.Min, plot.FrameRect.Max, true) + -- Setup 3D draw list + plot.DrawList._Flags = window.DrawList.Flags + plot.DrawList._SharedData = ImGui.GetDrawListSharedData() + return true + end + + function ImPlot3D.EndPlot() + local gp = GImPlot3D + IM_ASSERT(gp ~= nil, "No current context. Did you call ImPlot3D::CreateContext() or ImPlot3D::SetCurrentContext()?") + IM_ASSERT(gp.CurrentPlot ~= nil, "Mismatched BeginPlot()/EndPlot()!") + local plot = gp.CurrentPlot + -- Move triangles from 3D draw list to ImGui draw list + plot.DrawList:SortedMoveToImGuiDrawList() + -- Handle data fitting + if plot.FitThisFrame then + plot.FitThisFrame = false + if not internal.ImHasFlag(plot.Flags, Flags.Equal) then + -- Apply fit to all axes independently + for i = 0, 2 do + local axis = plot.Axes[i] + if axis.FitThisFrame then + axis.FitThisFrame = false + axis:ApplyFit() + end + end + else + -- Fit all axes, then use the one with the highest aspect ratio (units per NDC unit) as reference + local ref_axis, max_aspect = 0, 0.0 + for i = 0, 2 do + local axis = plot.Axes[i] + if axis.FitThisFrame then + axis.FitThisFrame = false + axis:ApplyFit() + local aspect = axis:GetAspect() + if aspect > max_aspect then max_aspect, ref_axis = aspect, i end + end + end + plot:ApplyEqualAspect(ref_axis) + end + end + -- Lock setup if not already done + ImPlot3D.SetupLock() + -- Pop plot rect clipping + ImGui.PopClipRect() + -- Reset legend hover + plot.Items.Legend.Hovered = false + -- Render legend + internal.RenderLegend() + -- Mouse position text and context menus + internal.ShowPlotPopups(plot) + -- Pop frame rect clipping + ImGui.PopClipRect() + -- Reset current plot + gp.CurrentPlot, gp.CurrentItems, gp.CurrentItem = nil, nil, nil + -- Reset the plot items for the next frame + for _, item in __iter(plot.Items.ItemPool.Buf) do + if item then item.SeenThisFrame = false end + end + end + + local function CurrentPlot(name) + local gp = GImPlot3D + IM_ASSERT(gp.CurrentPlot ~= nil, name .. "() needs to be called between BeginPlot() and EndPlot()!") + return gp.CurrentPlot + end + + function ImPlot3D.GetPlotRectPos() + local plot = CurrentPlot("GetPlotRectPos") + ImPlot3D.SetupLock() + return plot.PlotRect.Min + end + + function ImPlot3D.GetPlotRectSize() + local plot = CurrentPlot("GetPlotRectSize") + ImPlot3D.SetupLock() + return plot.PlotRect:GetSize() + end + + function ImPlot3D.GetFramePos() return CurrentPlot("GetFramePos").FrameRect.Min end + function ImPlot3D.GetFrameSize() return CurrentPlot("GetFrameSize").FrameRect:GetSize() end + function ImPlot3D.GetPlotDrawList() return ImGui.GetWindowDrawList() end + end + + -------------------------------------------------------------------------- + -- [SECTION] Colormap widgets, selectors, metrics (implot3d.cpp) + -------------------------------------------------------------------------- + do + local ImGuiCol, ImGuiStyleVar, ImRect = G.ImGuiCol, G.ImGuiStyleVar, G.ImRect + local function B(v) return v and"true" or"false" end + + -- [Port] colors passed as (array, 0-based offset) as returned by ColormapData:GetKeys; bounds is an ImRect + function internal.RenderColorBar(colors, offset, size, DrawList, bounds, vert, reversed, continuous) + local n = (continuous and{(size - 1 )}or{size +})[1] local function col(i) -- 0-based + return colors[offset + ((reversed and{(size - i - 1 )}or{i})[1]) + 1] + end + local step = (vert and{(bounds:GetHeight() / n )}or{(bounds:GetWidth() / n +)})[1] for i = 0, n - 1 do + local col1 = col(i) + local col2 = (continuous and{(col(i + 1) )}or{col1 +})[1] if vert then + local y = bounds.Min.y + i * step + DrawList:AddRectFilledMultiColor(ImVec2(bounds.Min.x, y), ImVec2(bounds.Max.x, y + step), col1, col1, col2, col2) + else + local x = bounds.Min.x + i * step + DrawList:AddRectFilledMultiColor(ImVec2(x, bounds.Min.y), ImVec2(x + step, bounds.Max.y), col1, col2, col2, col1) + end + end + end + + local function ResolveCmap(gp, cmap) + cmap = ((cmap == nil or cmap == ImPlot3D.IMPLOT3D_AUTO )and{gp.Style.Colormap }or{cmap +})[1] IM_ASSERT(cmap >= 0 and cmap < gp.ColormapData.Count, "Invalid colormap index!") + return cmap + end + + -- [Port] float* t / ImVec4* out -> returns (t, changed); `out` (ImVec4) is filled in place when given + function ImPlot3D.ColormapSlider(label, t, out, format, cmap) + t = math.clamp(t, 0.0, 1.0) + local Window = ImGui.GetCurrentWindow() + if Window.SkipItems then return t, false end + local gp = GImPlot3D + cmap = ResolveCmap(gp, cmap) + local keys, off = gp.ColormapData:GetKeys(cmap) + local pos = Window.DC.CursorPos + local rect = ImRect(pos.x, pos.y, pos.x + ImGui.CalcItemWidth(), pos.y + ImGui.GetFrameHeight()) + internal.RenderColorBar(keys, off, gp.ColormapData:GetKeyCount(cmap), ImGui.GetWindowDrawList(), rect, false, false, + not gp.ColormapData:IsQual(cmap)) + local grab = internal.CalcTextColor(gp.ColormapData:LerpTable(cmap, t)) + ImGui.PushStyleColor(ImGuiCol.FrameBg, G.IM_COL32_BLACK_TRANS) + ImGui.PushStyleColor(ImGuiCol.FrameBgActive, G.IM_COL32_BLACK_TRANS) + ImGui.PushStyleColor(ImGuiCol.FrameBgHovered, ImVec4(1, 1, 1, 0.1)) + ImGui.PushStyleColor(ImGuiCol.SliderGrab, grab) + ImGui.PushStyleColor(ImGuiCol.SliderGrabActive, grab) + ImGui.PushStyleVar(ImGuiStyleVar.GrabMinSize, 2) + ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 0) + local changed + t, changed = ImGui.SliderFloat(label, t, 0, 1, format or "") + ImGui.PopStyleColor(5) + ImGui.PopStyleVar(2) + if out ~= nil then + local c = ImGui.ColorConvertU32ToFloat4(gp.ColormapData:LerpTable(cmap, t)) + out.x, out.y, out.z, out.w = c.x, c.y, c.z, c.w + end + return t, changed + end + internal.ResolveColormap = ResolveCmap + + local style_idx = -1 + function ImPlot3D.ShowStyleSelector(label) + local changed + style_idx, changed = ImGui.Combo(label, style_idx, "Auto\0Classic\0Dark\0Light\0") + if changed then + if style_idx == 0 then ImPlot3D.StyleColorsAuto() + elseif style_idx == 1 then ImPlot3D.StyleColorsClassic() + elseif style_idx == 2 then ImPlot3D.StyleColorsDark() + elseif style_idx == 3 then ImPlot3D.StyleColorsLight() end + return true + end + return false + end + + function ImPlot3D.ShowColormapSelector(label) + local gp = GImPlot3D + local set = false + if ImGui.BeginCombo(label, gp.ColormapData:GetName(gp.Style.Colormap)) then + for i = 0, gp.ColormapData.Count - 1 do + if ImGui.Selectable(gp.ColormapData:GetName(i), gp.Style.Colormap == i) then + gp.Style.Colormap = i + internal.BustItemCache() + set = true + end + end + ImGui.EndCombo() + end + return set + end + + local function ShowAxisMetrics(axis) + ImGui.BulletText("Label: %s", axis:GetLabel()) + ImGui.BulletText("Flags: 0x%08X", axis.Flags) + ImGui.BulletText("Range: [%f,%f]", axis.Range.Min, axis.Range.Max) + ImGui.BulletText("NDC Scale: %f", axis.NDCScale) + ImGui.BulletText("NDC Range: [%f,%f]", -0.5 * axis.NDCScale, 0.5 * axis.NDCScale) + ImGui.BulletText("Aspect: %f", axis:GetAspect()) + ImGui.BulletText("ShowDefaultTicks: %s", B(axis.ShowDefaultTicks)) + ImGui.BulletText("FitThisFrame: %s", B(axis.FitThisFrame)) + ImGui.BulletText("FitExtents: [%f,%f]", axis.FitExtents.Min, axis.FitExtents.Min) -- [sic] upstream prints Min twice + ImGui.BulletText("ConstraintRange: [%f,%f]", axis.ConstraintRange.Min, axis.ConstraintRange.Min) + ImGui.BulletText("ConstraintZoom: [%f,%f]", axis.ConstraintZoom.Min, axis.ConstraintZoom.Min) + ImGui.BulletText("Hovered: %s", B(axis.Hovered)) + ImGui.BulletText("Held: %s", B(axis.Held)) + if ImGui.TreeNode("Ticks") then + ImGui.BulletText("Size: %d", axis.Ticker:TickCount()) + ImGui.TreePop() + end + end + + local axis_labels = { [0] = "X-Axis", "Y-Axis", "Z-Axis" } + local plane_labels = { [0] = "YZ-Plane", "XZ-Plane", "XY-Plane" } + local axis_edges_lookup_3d = { [0] = { 2, 1, 9 }, { 6, 5, 9 }, { 0, 1, 10 }, { 4, 5, 10 }, { 2, 3, 8 }, { 6, 7, 8 }, { 0, 3, 11 }, { 4, 7, 11 } } + local M = { frame = false, canvas = false, plot = false, box = false, axis_line = false, corners = false, faces = false, + edges = false, legend = false, t = 0.5 } + local HIDDEN, ACTIVE, NOT_ACTIVE = 0, 1, 2 -- DisplayedType + + -- [Port] "Plots" tree of ShowMetricsWindow, split out for size + function internal.ShowMetricsPlots(gp, n_plots, axis_labels, plane_labels, axis_edges_lookup_3d, ShowAxisMetrics, B) + if not ImGui.TreeNode("Plots", "Plots (%d)", n_plots) then return end + local IG = internal.ItemGroup + local _ + for p = 0, n_plots - 1 do + local plot = gp.Plots:GetByIndex(p) + ImGui.PushID(p) + if ImGui.TreeNode("Plot", "Plot [0x%08X]", plot.ID) then + local n_items = IG.GetItemCount(plot.Items) + if ImGui.TreeNode("Items", "Items (%d)", n_items) then + for i = 0, n_items - 1 do + local item = IG.GetItemByIndex(plot.Items, i) + ImGui.PushID(i) + if ImGui.TreeNode("Item", "Item [0x%08X]", item.ID) then + ImGui.Bullet() + _, item.Show = ImGui.Checkbox("Show", item.Show) + ImGui.Bullet() + local temp = ImGui.ColorConvertU32ToFloat4(item.Color) + if ImGui.ColorEdit4("Color", temp, G.ImGuiColorEditFlags.NoInputs) then item.Color = ImGui.ColorConvertFloat4ToU32(temp) end + ImGui.BulletText("NameOffset: %d", item.NameOffset) + ImGui.BulletText("Name: %s", (item.NameOffset ~= -1 and{plot.Items.Legend.LabelList[item.NameOffset + 1] or "N/A" }or{"N/A"})[1]) + ImGui.BulletText("Hovered: %s", B(item.LegendHovered)) + ImGui.TreePop() + end + ImGui.PopID() + end + ImGui.TreePop() + end + if ImGui.TreeNode("Axes") then + local active_faces, corners_pix, corners, plane_2d, axis_corners = internal.GetAxesParameters(plot) + for a = 0, 2 do + if not (plane_2d ~= -1 and plane_2d == a) and ImGui.TreeNode(axis_labels[a]) then + ShowAxisMetrics(plot.Axes[a]) + ImGui.TreePop() + end + end + if plane_2d ~= -1 then + ImGui.BulletText("Plane2D: %d %s", plane_2d, plane_labels[plane_2d]) + else + local idx = internal.Active3DFacesToAxisLookupIndex(active_faces) + ImGui.BulletText("3D Active Faces: [%s,%s,%s]=%d", active_faces[0] == 1 and"X-max" or"X-min", +active_faces[1] == 1 and"Y-max" or"Y-min", active_faces[2] == 1 and"Z-max" or"Z-min", idx) + local e = axis_edges_lookup_3d[idx] + ImGui.BulletText("3D Active Edges Lookup: [%d,%d,%d]", e[1], e[2], e[3]) + end + for a = 0, 2 do + ImGui.BulletText("%s Label Corners: [%d,%d]", axis_labels[a], axis_corners[a][1], axis_corners[a][2]) + end + for c = 0, 7 do + ImGui.BulletText("Corner %d: [%.2f,%.2f,%.2f] [%.2f,%.2f]", c, corners[c].x, corners[c].y, corners[c].z, + corners_pix[c].x, corners_pix[c].y) + end + ImGui.TreePop() + end + local L = plot.Items.Legend + ImGui.BulletText("Title: %s", (plot:HasTitle() and{(plot:GetTitle() )}or{"none"})[1]) + ImGui.BulletText("Flags: 0x%08X", plot.Flags) + ImGui.BulletText("Initialized: %s", B(plot.Initialized)) + ImGui.BulletText("Hovered: %s", B(plot.Hovered)) + ImGui.BulletText("Held: %s", B(plot.Held)) + ImGui.BulletText("HeldEdgeIdx: %d", plot.HeldEdgeIdx) + ImGui.BulletText("HeldPlaneIdx: %d", plot.HeldPlaneIdx) + ImGui.BulletText("LegendLocation: %s", internal.GetShortLegendLocationName(L.Location) or "?") + ImGui.BulletText("LegendHovered: %s", B(L.Hovered)) + ImGui.BulletText("LegendHeld: %s", B(L.Held)) + ImGui.BulletText("RotationCond: 0x%08X", plot.RotationCond) + local q, r, ae = plot.InitialRotation, plot.Rotation, plot.RotationAnimationEnd + ImGui.BulletText("InitialRotation: [%.2f,%.2f,%.2f,%.2f]", q.x, q.y, q.z, q.w) + ImGui.BulletText("Rotation: [%.2f,%.2f,%.2f,%.2f]", r.x, r.y, r.z, r.w) + ImGui.BulletText("Animation: Time=%.4f RotationEnd=[%.2f,%.2f,%.2f,%.2f]", plot.AnimationTime, ae.x, ae.y, r.z, ae.w) + ImGui.BulletText("ViewScale: %.2f", plot:GetViewScale()) + ImGui.TreePop() + end + ImGui.PopID() + end + ImGui.TreePop() + end + + -- [Port] bool* p_popen -> returns the new open state + function ImPlot3D.ShowMetricsWindow(p_open) + local fg = ImGui.GetForegroundDrawList() + local gp = GImPlot3D + local io = ImGui.GetIO() + local faces, edges, face_edges = internal.box_faces, internal.box_edges, internal.box_face_edges + local _ + p_open = ImGui.Begin("Metrics (ImPlot3D)", p_open) + ImGui.Text("ImPlot3D " .. ImPlot3D.IMPLOT3D_VERSION) + ImGui.Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0 / io.Framerate, io.Framerate) + ImGui.Text("Mouse Position: [%.0f,%.0f]", io.MousePos.x, io.MousePos.y) + ImGui.Separator() + if ImGui.TreeNode("Tools") then + if ImGui.Button("Bust Plot Cache") then internal.BustPlotCache() end + ImGui.SameLine() + if ImGui.Button("Bust Item Cache") then internal.BustItemCache() end + for _, e in { { "frame", "Show Frame Rects" }, { "canvas", "Show Canvas Rects" }, { "plot", "Show Plot Rects" }, + { "box", "Show Plot Box" }, { "axis_line", "Show Axis Line" }, { "corners", "Show Axis Corner Indexes" }, + { "faces", "Show Axis Face Indexes" }, { "edges", "Show Axis Edge Indexes" }, { "legend", "Show Legend Rects" } } do + _, M[e[1] ] = ImGui.Checkbox(e[2], M[e[1] ]) + end + ImGui.TreePop() + end + local n_plots = gp.Plots.BufSize + -- Render rectangles + for p = 0, n_plots - 1 do + local plot = gp.Plots:GetByIndex(p) + if M.frame then fg:AddRect(plot.FrameRect.Min, plot.FrameRect.Max, IM_COL32(255, 0, 255, 255)) end + if M.canvas then fg:AddRect(plot.CanvasRect.Min, plot.CanvasRect.Max, IM_COL32(0, 255, 255, 255)) end + if M.plot then fg:AddRect(plot.PlotRect.Min, plot.PlotRect.Max, IM_COL32(255, 255, 0, 255)) end + local active_faces, corners_pix, plane_2d, axis_corners + if M.box or M.axis_line or M.corners or M.faces or M.edges then + active_faces, corners_pix, _, plane_2d, axis_corners = internal.GetAxesParameters(plot) + end + if M.box or M.edges then + local edge_types = {} + for e = 0, 11 do edge_types[e] = (plane_2d == -1 and M.box and{NOT_ACTIVE }or{HIDDEN })[1]end + for a = 0, 2 do + if plane_2d == -1 or a == plane_2d then + for _, e in __iter(face_edges[a + 3 * active_faces[a] ]) do edge_types[e] = ACTIVE end + end + end + for e = 0, 11 do + local c0, c1 = corners_pix[edges[e][1] ], corners_pix[edges[e][2] ] + if M.box then + if edge_types[e] == ACTIVE then fg:AddLine(c0, c1, IM_COL32(255, 200, 0, 255)) + elseif edge_types[e] == NOT_ACTIVE then fg:AddLine(c0, c1, IM_COL32(100, 255, 0, 125)) end + end + if M.edges and edge_types[e] ~= HIDDEN then + local mid = ImVec2((c0.x + c1.x) / 2, (c0.y + c1.y) / 2) + local angle = math.atan2(-(c1.y - c0.y), c1.x - c0.x) + -- Adjust angle to keep labels upright + if angle > math.pi * 0.5 then angle =angle- math.pi end + if angle < -math.pi * 0.5 then angle =angle+ math.pi end + internal.AddTextRotated(fg, mid, angle, IM_COL32(200, 0, 0, 200), "E" .. e) + end + end + end + if M.axis_line then + for a = 0, 2 do + if plane_2d == -1 or a ~= plane_2d then + fg:AddLine(corners_pix[axis_corners[a][1] ], corners_pix[axis_corners[a][2] ], IM_COL32(0, 255, 255, 255)) + end + end + end + if M.corners then + local corner_types = {} + for c = 0, 7 do corner_types[c] = (plane_2d == -1 and M.box and{NOT_ACTIVE }or{HIDDEN })[1]end + for a = 0, 2 do + if plane_2d == -1 or a == plane_2d then + for _, c in __iter(faces[a + 3 * active_faces[a] ]) do corner_types[c] = ACTIVE end + end + end + for c = 0, 7 do + if corner_types[c] ~= HIDDEN then internal.AddTextRotated(fg, corners_pix[c], 0.0, IM_COL32(0, 200, 0, 200), "C" .. c) end + end + end + if M.faces then + for a = 0, 2 do + for f = 0, 1 do + if (plane_2d == -1 or a == plane_2d) and (f == active_faces[a] or M.box) then + local face_idx = a + 3 * f + local fi = faces[face_idx] + local c0, c2 = corners_pix[fi[1] ], corners_pix[fi[3] ] + internal.AddTextRotated(fg, ImVec2((c0.x + c2.x) / 2, (c0.y + c2.y) / 2), 0.0, IM_COL32(0, 200, 200, 200), "F" .. face_idx) + end + end + end + end + local legend = plot.Items.Legend + if M.legend and internal.ItemGroup.GetLegendCount(plot.Items) > 0 then + fg:AddRect(legend.Rect.Min, legend.Rect.Max, IM_COL32(255, 192, 0, 255)) + fg:AddRect(legend.RectClamped.Min, legend.RectClamped.Max, IM_COL32(255, 128, 0, 255)) + end + end + internal.ShowMetricsPlots(gp, n_plots, axis_labels, plane_labels, axis_edges_lookup_3d, ShowAxisMetrics, B) + if ImGui.TreeNode("Colormaps") then + local cd = gp.ColormapData + ImGui.BulletText("Colormaps: %d", cd.Count) + ImGui.BulletText("Memory: %d bytes", #cd.Tables * 4) + if ImGui.TreeNode("Data") then + for m = 0, cd.Count - 1 do + if ImGui.TreeNode(cd:GetName(m)) then + local size = cd:GetTableSize(m) + ImGui.BulletText("Qualitative: %s", B(cd:IsQual(m))) + ImGui.BulletText("Key Count: %d", cd:GetKeyCount(m)) + ImGui.BulletText("Table Size: %d", size) + ImGui.Indent() + local samp = ImVec4(0, 0, 0, 0) + ImGui.SetNextItemWidth(32 * 10 - ImGui.GetFrameHeight() - ImGui.GetStyle().ItemSpacing.x) + M.t = ImPlot3D.ColormapSlider("##Sample", M.t, samp, "%.3f", m) + ImGui.SameLine() + ImGui.ColorButton("Sampler", samp) + ImGui.PushStyleColor(ImGuiCol.FrameBg, ImVec4(0, 0, 0, 0)) + ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, ImVec2(0, 0)) + for c = 0, size - 1 do + ImGui.PushID(m * 1000 + c) + ImGui.ColorButton("", ImGui.ColorConvertU32ToFloat4(cd:GetTableColor(m, c)), 0, ImVec2(10, 10)) + ImGui.PopID() + if (c + 1) % 32 ~= 0 and c ~= size - 1 then ImGui.SameLine() end + end + ImGui.PopStyleVar() + ImGui.PopStyleColor() + ImGui.Unindent() + ImGui.TreePop() + end + end + ImGui.TreePop() + end + ImGui.TreePop() + end + ImGui.End() + return p_open + end + end + + -------------------------------------------------------------------------- + -- [SECTION] Meshes (implot3d_meshes.cpp) + -- [Port] ImPlot3D.Meshes. = { VtxXs, VtxYs, VtxZs, Idx, VtxCount, IdxCount }; Idx holds 0-based vertex + -- indices (upstream semantics) for ImPlot3D.PlotMesh(label, m.VtxXs, m.VtxYs, m.VtxZs, m.Idx, m.VtxCount, m.IdxCount, spec). + -- Duck: Rubber Duck by Poly by Google [CC-BY] via Poly Pizza + -------------------------------------------------------------------------- + do + local Meshes = {} + ImPlot3D.Meshes = Meshes + Meshes.Cube = { + VtxCount = 8, IdxCount = 36, + VtxXs = { + -1, 1, 1, -1, -1, 1, 1, -1 + }, + VtxYs = { + -1, -1, 1, 1, -1, -1, 1, 1 + }, + VtxZs = { + -1, -1, -1, -1, 1, 1, 1, 1 + }, + Idx = { + 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 0, 3, 7, 0, 7, 4, 1, 5, 6, 1, 6, 2, 3, 2, 6, 3, 6, 7, 0, 1, 5, 0, 5, 4 + }, + } + Meshes.Sphere = { + VtxCount = 162, IdxCount = 960, + VtxXs = { + -0.525731, 0.525731, -0.525731, 0.525731, 0, 0, 0, 0, 0.850651, 0.850651, -0.850651, -0.850651, -0.809017, -0.5, -0.309017, + 0.309017, 0, 0.309017, -0.309017, -0.5, -0.809017, -1, 0.5, 0.809017, -0.5, 0, -0.809017, -0.809017, 0, -0.5, 0.809017, 0.5, + 0.809017, 0.5, 0.309017, -0.309017, 0, -0.309017, 0.309017, 0.5, 0.809017, 1, -0.69378, -0.587785, -0.433889, -0.862668, + -0.702046, -0.688191, -0.425325, -0.259892, -0.160622, -0.16246, -0.273267, 0.160622, 0, 0.16246, 0.433889, 0.273267, -0.16246, + -0.433889, 0.433889, 0.16246, 0, 0.160622, -0.160622, -0.587785, -0.69378, -0.259892, -0.425325, -0.688191, -0.702046, -0.862668, + -0.850651, -0.961938, -0.951057, -0.951057, -0.961938, 0.587785, 0.69378, 0.259892, 0.425325, 0.688191, 0.702046, 0.862668, + -0.262866, 0, -0.702046, -0.525731, -0.262866, -0.259892, 0, -0.951057, -0.862668, -0.862668, -0.951057, -0.850651, -0.69378, + -0.69378, -0.525731, -0.702046, 0, -0.262866, -0.262866, 0, -0.259892, 0.425325, 0.259892, 0.69378, 0.587785, 0.688191, 0.862668, + 0.702046, 0.69378, 0.587785, 0.433889, 0.862668, 0.702046, 0.688191, 0.425325, 0.259892, 0.160622, 0.16246, 0.273267, -0.160622, + 0, -0.16246, -0.433889, -0.273267, 0.16246, 0.433889, -0.433889, -0.16246, 0, -0.160622, 0.160622, 0.587785, 0.69378, 0.259892, + 0.425325, 0.688191, 0.702046, 0.862668, 0.850651, 0.961938, 0.951057, 0.951057, 0.961938, 0.262866, 0.525731, 0.262866, + -0.587785, -0.425325, -0.688191, -0.425325, -0.587785, -0.688191, 0.525731, 0.262866, 0.262866, 0.951057, 0.951057, 0.850651 + }, + VtxYs = { + 0.850651, 0.850651, -0.850651, -0.850651, -0.525731, 0.525731, -0.525731, 0.525731, 0, 0, 0, 0, 0.5, 0.309017, 0.809017, + 0.809017, 1, 0.809017, 0.809017, 0.309017, 0.5, 0, 0.309017, 0.5, -0.309017, 0, -0.5, -0.5, 0, -0.309017, 0.5, 0.309017, -0.5, + -0.309017, -0.809017, -0.809017, -1, -0.809017, -0.809017, -0.309017, -0.5, 0, 0.702046, 0.688191, 0.862668, 0.259892, 0.160622, + 0.425325, 0.587785, 0.433889, 0.69378, 0.951057, 0.961938, 0.69378, 0.850651, 0.951057, 0.862668, 0.961938, 0.951057, 0.862668, + 0.862668, 0.951057, 0.850651, 0.69378, 0.69378, 0.688191, 0.702046, 0.433889, 0.587785, 0.425325, 0.160622, 0.259892, 0.525731, + 0, 0.262866, 0.262866, 0, 0.688191, 0.702046, 0.433889, 0.587785, 0.425325, 0.160622, 0.259892, 0.16246, 0.273267, -0.160622, 0, + -0.16246, -0.433889, -0.273267, -0.262866, -0.259892, -0.259892, -0.262866, -0.525731, -0.702046, -0.702046, 0, -0.160622, + 0.273267, 0.16246, -0.16246, -0.273267, -0.433889, 0.587785, 0.433889, 0.702046, 0.688191, 0.425325, 0.259892, 0.160622, + -0.702046, -0.688191, -0.862668, -0.259892, -0.160622, -0.425325, -0.587785, -0.433889, -0.69378, -0.951057, -0.961938, -0.69378, + -0.850651, -0.951057, -0.862668, -0.961938, -0.951057, -0.862668, -0.862668, -0.951057, -0.850651, -0.69378, -0.69378, -0.688191, + -0.702046, -0.433889, -0.587785, -0.425325, -0.160622, -0.259892, -0.525731, 0, -0.262866, -0.262866, 0, -0.16246, 0, 0.16246, + -0.688191, -0.587785, -0.425325, -0.587785, -0.688191, -0.425325, 0, -0.16246, 0.16246, 0.262866, 0.262866, 0.525731 + }, + VtxZs = { + 0, 0, 0, 0, 0.850651, 0.850651, -0.850651, -0.850651, -0.525731, 0.525731, -0.525731, 0.525731, 0.309017, 0.809017, 0.5, 0.5, 0, + -0.5, -0.5, -0.809017, -0.309017, 0, 0.809017, 0.309017, 0.809017, 1, -0.309017, 0.309017, -1, -0.809017, -0.309017, -0.809017, + 0.309017, 0.809017, 0.5, 0.5, 0, -0.5, -0.5, -0.809017, -0.309017, 0, 0.160622, 0.425325, 0.259892, 0.433889, 0.69378, 0.587785, + 0.688191, 0.862668, 0.702046, 0.262866, 0, 0.702046, 0.525731, 0.262866, 0.259892, 0, -0.262866, -0.259892, -0.259892, -0.262866, + -0.525731, -0.702046, -0.702046, -0.425325, -0.160622, -0.862668, -0.688191, -0.587785, -0.69378, -0.433889, 0, -0.273267, + -0.16246, 0.16246, 0.273267, 0.425325, 0.160622, 0.862668, 0.688191, 0.587785, 0.69378, 0.433889, 0.951057, 0.961938, 0.69378, + 0.850651, 0.951057, 0.862668, 0.961938, 0.16246, 0.433889, -0.433889, -0.16246, 0, -0.160622, 0.160622, -0.850651, -0.69378, + -0.961938, -0.951057, -0.951057, -0.961938, -0.862668, -0.688191, -0.862668, -0.160622, -0.425325, -0.587785, -0.433889, + -0.69378, 0.160622, 0.425325, 0.259892, 0.433889, 0.69378, 0.587785, 0.688191, 0.862668, 0.702046, 0.262866, 0, 0.702046, + 0.525731, 0.262866, 0.259892, 0, -0.262866, -0.259892, -0.259892, -0.262866, -0.525731, -0.702046, -0.702046, -0.425325, + -0.160622, -0.862668, -0.688191, -0.587785, -0.69378, -0.433889, 0, -0.273267, -0.16246, 0.16246, 0.273267, 0.951057, 0.850651, + 0.951057, 0.425325, 0.688191, 0.587785, -0.688191, -0.425325, -0.587785, -0.850651, -0.951057, -0.951057, 0.16246, -0.16246, 0 + }, + Idx = { + 0, 42, 44, 42, 12, 43, 44, 43, 14, 42, 43, 44, 12, 45, 47, 45, 11, 46, 47, 46, 13, 45, 46, 47, 14, 48, 50, 48, 13, 49, 50, 49, 5, + 48, 49, 50, 12, 47, 43, 47, 13, 48, 43, 48, 14, 47, 48, 43, 0, 44, 52, 44, 14, 51, 52, 51, 16, 44, 51, 52, 14, 50, 54, 50, 5, 53, + 54, 53, 15, 50, 53, 54, 16, 55, 57, 55, 15, 56, 57, 56, 1, 55, 56, 57, 14, 54, 51, 54, 15, 55, 51, 55, 16, 54, 55, 51, 0, 52, 59, + 52, 16, 58, 59, 58, 18, 52, 58, 59, 16, 57, 61, 57, 1, 60, 61, 60, 17, 57, 60, 61, 18, 62, 64, 62, 17, 63, 64, 63, 7, 62, 63, 64, + 16, 61, 58, 61, 17, 62, 58, 62, 18, 61, 62, 58, 0, 59, 66, 59, 18, 65, 66, 65, 20, 59, 65, 66, 18, 64, 68, 64, 7, 67, 68, 67, 19, + 64, 67, 68, 20, 69, 71, 69, 19, 70, 71, 70, 10, 69, 70, 71, 18, 68, 65, 68, 19, 69, 65, 69, 20, 68, 69, 65, 0, 66, 42, 66, 20, + 72, 42, 72, 12, 66, 72, 42, 20, 71, 74, 71, 10, 73, 74, 73, 21, 71, 73, 74, 12, 75, 45, 75, 21, 76, 45, 76, 11, 75, 76, 45, 20, + 74, 72, 74, 21, 75, 72, 75, 12, 74, 75, 72, 1, 56, 78, 56, 15, 77, 78, 77, 23, 56, 77, 78, 15, 53, 80, 53, 5, 79, 80, 79, 22, 53, + 79, 80, 23, 81, 83, 81, 22, 82, 83, 82, 9, 81, 82, 83, 15, 80, 77, 80, 22, 81, 77, 81, 23, 80, 81, 77, 5, 49, 85, 49, 13, 84, 85, + 84, 25, 49, 84, 85, 13, 46, 87, 46, 11, 86, 87, 86, 24, 46, 86, 87, 25, 88, 90, 88, 24, 89, 90, 89, 4, 88, 89, 90, 13, 87, 84, + 87, 24, 88, 84, 88, 25, 87, 88, 84, 11, 76, 92, 76, 21, 91, 92, 91, 27, 76, 91, 92, 21, 73, 94, 73, 10, 93, 94, 93, 26, 73, 93, + 94, 27, 95, 97, 95, 26, 96, 97, 96, 2, 95, 96, 97, 21, 94, 91, 94, 26, 95, 91, 95, 27, 94, 95, 91, 10, 70, 99, 70, 19, 98, 99, + 98, 29, 70, 98, 99, 19, 67, 101, 67, 7, 100, 101, 100, 28, 67, 100, 101, 29, 102, 104, 102, 28, 103, 104, 103, 6, 102, 103, 104, + 19, 101, 98, 101, 28, 102, 98, 102, 29, 101, 102, 98, 7, 63, 106, 63, 17, 105, 106, 105, 31, 63, 105, 106, 17, 60, 108, 60, 1, + 107, 108, 107, 30, 60, 107, 108, 31, 109, 111, 109, 30, 110, 111, 110, 8, 109, 110, 111, 17, 108, 105, 108, 30, 109, 105, 109, + 31, 108, 109, 105, 3, 112, 114, 112, 32, 113, 114, 113, 34, 112, 113, 114, 32, 115, 117, 115, 9, 116, 117, 116, 33, 115, 116, + 117, 34, 118, 120, 118, 33, 119, 120, 119, 4, 118, 119, 120, 32, 117, 113, 117, 33, 118, 113, 118, 34, 117, 118, 113, 3, 114, + 122, 114, 34, 121, 122, 121, 36, 114, 121, 122, 34, 120, 124, 120, 4, 123, 124, 123, 35, 120, 123, 124, 36, 125, 127, 125, 35, + 126, 127, 126, 2, 125, 126, 127, 34, 124, 121, 124, 35, 125, 121, 125, 36, 124, 125, 121, 3, 122, 129, 122, 36, 128, 129, 128, + 38, 122, 128, 129, 36, 127, 131, 127, 2, 130, 131, 130, 37, 127, 130, 131, 38, 132, 134, 132, 37, 133, 134, 133, 6, 132, 133, + 134, 36, 131, 128, 131, 37, 132, 128, 132, 38, 131, 132, 128, 3, 129, 136, 129, 38, 135, 136, 135, 40, 129, 135, 136, 38, 134, + 138, 134, 6, 137, 138, 137, 39, 134, 137, 138, 40, 139, 141, 139, 39, 140, 141, 140, 8, 139, 140, 141, 38, 138, 135, 138, 39, + 139, 135, 139, 40, 138, 139, 135, 3, 136, 112, 136, 40, 142, 112, 142, 32, 136, 142, 112, 40, 141, 144, 141, 8, 143, 144, 143, + 41, 141, 143, 144, 32, 145, 115, 145, 41, 146, 115, 146, 9, 145, 146, 115, 40, 144, 142, 144, 41, 145, 142, 145, 32, 144, 145, + 142, 4, 119, 90, 119, 33, 147, 90, 147, 25, 119, 147, 90, 33, 116, 148, 116, 9, 82, 148, 82, 22, 116, 82, 148, 25, 149, 85, 149, + 22, 79, 85, 79, 5, 149, 79, 85, 33, 148, 147, 148, 22, 149, 147, 149, 25, 148, 149, 147, 2, 126, 97, 126, 35, 150, 97, 150, 27, + 126, 150, 97, 35, 123, 151, 123, 4, 89, 151, 89, 24, 123, 89, 151, 27, 152, 92, 152, 24, 86, 92, 86, 11, 152, 86, 92, 35, 151, + 150, 151, 24, 152, 150, 152, 27, 151, 152, 150, 6, 133, 104, 133, 37, 153, 104, 153, 29, 133, 153, 104, 37, 130, 154, 130, 2, 96, + 154, 96, 26, 130, 96, 154, 29, 155, 99, 155, 26, 93, 99, 93, 10, 155, 93, 99, 37, 154, 153, 154, 26, 155, 153, 155, 29, 154, 155, + 153, 8, 140, 111, 140, 39, 156, 111, 156, 31, 140, 156, 111, 39, 137, 157, 137, 6, 103, 157, 103, 28, 137, 103, 157, 31, 158, + 106, 158, 28, 100, 106, 100, 7, 158, 100, 106, 39, 157, 156, 157, 28, 158, 156, 158, 31, 157, 158, 156, 9, 146, 83, 146, 41, 159, + 83, 159, 23, 146, 159, 83, 41, 143, 160, 143, 8, 110, 160, 110, 30, 143, 110, 160, 23, 161, 78, 161, 30, 107, 78, 107, 1, 161, + 107, 78, 41, 160, 159, 160, 30, 161, 159, 161, 23, 160, 161, 159 + }, + } + Meshes.Duck = { + VtxCount = 254, IdxCount = 1428, + VtxXs = { + 0.26337, 0.358677, 0.292714, 0.349165, 0, 0, 0, 0, 0, 0.416629, 0.386268, 0, 0.170659, 0.180454, 0.155948, 0.15505, 0.151757, 0, + 0, 0, 0.371476, 0.331315, 0.206943, 0, 0, 0.283809, 0, 0, 0.27849, 0, 0.164839, 0.230536, 0.220279, 0.216836, 0.238591, 0.244763, + 0, 0.163341, 0.374463, 0.379897, 0.289253, 0.399568, 0.416824, 0.226948, 0, 0.199617, 0, 0.221169, 0.414907, 0.383278, 0, + 0.485071, 0.474322, 0.451926, 0.464485, 0.376105, 0.458732, 0.414064, 0.482586, 0, 0.146952, 0.261607, 0.193018, 0, 0, 0.241792, + 0.312765, 0.214627, 0, 0, 0.138512, 0.234026, 0, 0.160964, 0.193354, 0, 0, 0.229117, 0.409787, 0.45877, 0.385168, 0.34442, + 0.437609, 0.386172, 0.203357, 0, 0.368402, 0.408311, 0.317982, 0, 0.194647, 0.332827, 0.252044, 0, 0, 0.204859, 0.382866, + 0.437191, 0.277419, 0.165994, 0.36652, 0, 0.554754, 0.548457, 0.496187, 0.410754, 0.501407, -0.26337, -0.358677, -0.292714, + -0.349165, -0.416629, -0.386268, -0.170659, -0.180454, -0.155948, -0.15505, -0.151757, -0.371476, -0.331315, -0.206943, + -0.283809, -0.27849, -0.164839, -0.230536, -0.220279, -0.216836, -0.238591, -0.244763, -0.163341, -0.374463, -0.379897, + -0.289253, -0.399568, -0.416824, -0.226948, -0.199617, -0.221169, -0.414907, -0.383278, -0.485071, -0.474322, -0.451926, + -0.464485, -0.376105, -0.458732, -0.414064, -0.482586, -0.146952, -0.261606, -0.193018, -0.241792, -0.312765, -0.214627, + -0.138512, -0.234026, -0.160964, -0.193354, -0.229117, -0.409787, -0.45877, -0.385168, -0.34442, -0.437609, -0.386172, -0.203357, + -0.368402, -0.408311, -0.317982, -0.194647, -0.332827, -0.252044, -0.204859, -0.382866, -0.437191, -0.277419, -0.165994, + -0.36652, -0.554754, -0.548457, -0.496187, -0.410754, -0.501407, -0.147251, -0.047291, -0.224222, -0.07545, -0.075797, -0.096675, + -0.159031, -0.223648, -0.072544, 0, 0, 0, -0.176269, -0.051675, 0, 0, -0.152228, 0, 0, -0.123466, 0.147251, 0.047291, 0.224222, + 0.07545, 0.075797, 0.096675, 0.159031, 0.223648, 0.072544, 0.176269, 0.051675, 0.152228, 0.123466, 0, 0, 0, 0, 0, 0, 0, + -0.133409, -0.06009, -0.224222, -0.094843, -0.15133, 0, -0.120579, -0.187682, -0.213355, -0.09294, -0.176269, -0.130777, + -0.075297, -0.182747, -0.150873, -0.055104, 0.133409, 0.06009, 0.224222, 0.094843, 0.15133, 0.120579, 0.187682, 0.213355, + 0.09294, 0.176269, 0.130777, 0.075297, 0.182747, 0.150873, 0.055104 + }, + VtxYs = { + 0.782383, -0.624396, 0.782558, -0.57943, 0.985995, -0.771795, 0.884807, -0.793724, -0.299071, -0.234865, -0.264259, -0.154521, + -0.255441, -0.704124, 0.918253, -0.228032, -0.513087, -0.182899, -0.57833, 0.685169, 0.629238, 0.641641, 0.597766, 0.614709, + -0.737692, -0.10266, 0.014558, -0.736425, -0.087547, 0.02578, 0.864781, 0.696343, -0.2945, -0.741049, -0.660227, -0.660211, + -0.363444, -0.354552, -0.37235, -0.380938, -0.469584, -0.463659, -0.506064, -0.58028, -0.596101, 0.050031, 0.056331, 0.056088, + 0.057214, 0.079881, 0.066068, -0.225034, -0.235931, -0.378909, -0.423127, 0.621725, 0.078611, 0.58752, 0.065612, -0.672915, + -0.607627, -0.401487, -0.190607, -0.095407, -0.044418, -0.13212, -0.375473, -0.620202, -0.694664, -0.682358, -0.610831, + -0.438399, 0.914951, 0.841809, 0.741696, 0.800313, 0.405613, 0.399656, 0.383452, 0.376363, 0.580561, 0.600331, 0.339612, + 0.365055, 0.342793, 0.367574, 0.509624, 0.494489, -0.276765, -0.705078, -0.634647, -0.390756, -0.1538, -0.052325, -0.845971, + -0.77431, -0.635409, -0.532057, 0.820517, 0.946464, 0.694046, 1, 0.0812, -0.24071, -0.443697, 0.655281, 0.340701, 0.782383, + -0.624396, 0.782558, -0.57943, -0.234865, -0.264259, -0.255441, -0.704124, 0.918253, -0.228032, -0.513087, 0.629238, 0.641641, + 0.597766, -0.10266, -0.087547, 0.864781, 0.696343, -0.2945, -0.741049, -0.660227, -0.660211, -0.354552, -0.37235, -0.380938, + -0.469584, -0.463659, -0.506064, -0.58028, 0.050031, 0.056088, 0.057214, 0.079881, -0.225034, -0.235931, -0.378909, -0.423127, + 0.621725, 0.078611, 0.58752, 0.065612, -0.607627, -0.401487, -0.190607, -0.13212, -0.375473, -0.620202, -0.610831, -0.438399, + 0.841809, 0.741696, 0.399656, 0.383452, 0.376363, 0.580561, 0.600331, 0.339612, 0.365055, 0.342793, 0.509624, 0.494489, + -0.276765, -0.634647, -0.390756, -0.1538, -0.77431, -0.635409, -0.532057, 0.820517, 0.946464, 0.694046, 0.0812, -0.24071, + -0.443697, 0.655281, 0.340701, -0.668523, -0.930817, -0.665336, -0.918607, -0.674119, -0.818748, -0.798414, -0.656683, -0.935279, + -0.961081, -0.726138, -0.969221, -0.669386, -0.862571, -0.680106, -0.974061, -0.819158, -0.86777, -0.827887, -0.78803, -0.668523, + -0.930817, -0.665336, -0.918607, -0.674119, -0.818748, -0.798414, -0.656683, -0.935279, -0.669386, -0.862571, -0.819158, + -0.78803, -0.994773, -0.647443, -0.986165, -0.703971, -1, -0.787658, -0.961085, -0.653443, -0.929363, -0.658853, -0.932646, + -0.675024, -0.932532, -0.791706, -0.791724, -0.651997, -0.939719, -0.66686, -0.793601, -0.913539, -0.797038, -0.786911, + -0.898766, -0.653443, -0.929363, -0.658853, -0.932646, -0.675024, -0.791706, -0.791724, -0.651997, -0.939719, -0.66686, + -0.793601, -0.913539, -0.797038, -0.786911, -0.898766 + }, + VtxZs = { + -0.488235, -0.546179, -0.125229, -0.151545, 0.055503, -0.060755, -0.562217, -0.609042, -0.806689, -0.718575, -0.087117, 0.030419, + 0.007066, -0.06192, -0.001556, 0.751753, 0.744284, 0.779477, 0.76461, -0.739686, -0.627667, -0.175468, -0.089039, -0.054922, + 0.299441, 0.299441, 0.299441, 0.474106, 0.474106, 0.474106, -0.52856, -0.704629, -0.788924, -0.5797, 0.299441, 0.474106, + 0.812572, 0.773703, 0.474106, 0.299441, -0.04885, -0.141744, -0.619739, -0.719311, -0.755098, -0.023613, -0.812572, -0.80043, + -0.741319, -0.106452, 0.011448, -0.615697, -0.130497, -0.18223, -0.533935, -0.201967, -0.144688, -0.543056, -0.653211, 0.096026, + 0.096026, 0.096026, 0.096026, 0.096026, 0.665235, 0.640095, 0.640095, 0.640095, 0.65802, 0.030419, 0.030419, 0.030419, 0.07736, + 0.024144, -0.037907, 0.001882, -0.811128, -0.791482, -0.704163, -0.605461, -0.185704, -0.166386, -0.230592, -0.180691, -0.082669, + -0.043515, -0.189577, -0.224777, -0.036125, 0.171934, 0.171934, 0.171934, 0.171934, 0.171934, -0.319676, -0.326206, -0.351147, + -0.362802, -0.36241, -0.306175, -0.383403, -0.305615, -0.400087, -0.37182, -0.357878, -0.382353, -0.406753, -0.488235, -0.546179, + -0.125229, -0.151545, -0.718575, -0.087117, 0.007066, -0.06192, -0.001556, 0.751753, 0.744284, -0.627667, -0.175468, -0.089039, + 0.299441, 0.474106, -0.52856, -0.704629, -0.788924, -0.5797, 0.299441, 0.474106, 0.773703, 0.474106, 0.299441, -0.04885, + -0.141744, -0.619739, -0.719311, -0.023613, -0.80043, -0.741319, -0.106452, -0.615697, -0.130497, -0.18223, -0.533935, -0.201967, + -0.144688, -0.543056, -0.653211, 0.096026, 0.096026, 0.096026, 0.640095, 0.640095, 0.640095, 0.030419, 0.030419, 0.024144, + -0.037907, -0.791482, -0.704163, -0.605461, -0.185704, -0.166386, -0.230592, -0.180691, -0.082669, -0.189577, -0.224777, + -0.036125, 0.171934, 0.171934, 0.171934, -0.326206, -0.351147, -0.362802, -0.36241, -0.306175, -0.383403, -0.400087, -0.37182, + -0.357878, -0.382353, -0.406753, 0.330326, 0.472716, 0.415767, 0.533818, 0.54103, 0.395991, 0.462927, 0.331961, 0.500884, + 0.579077, 0.328549, 0.509585, 0.471817, 0.538304, 0.554423, 0.54616, 0.418117, 0.561794, 0.40408, 0.48919, 0.330326, 0.472716, + 0.415767, 0.533818, 0.54103, 0.395991, 0.462927, 0.331961, 0.500884, 0.471817, 0.538304, 0.418117, 0.48919, 0.34573, 0.199203, + 0.291566, 0.341994, 0.31521, 0.226787, 0.352303, 0.222877, 0.267589, 0.342353, 0.34306, 0.346911, 0.323403, 0.239478, 0.341367, + 0.277443, 0.30109, 0.352303, 0.328226, 0.352303, 0.284545, 0.352303, 0.325273, 0.222877, 0.267589, 0.342353, 0.34306, 0.346911, + 0.239478, 0.341367, 0.277443, 0.30109, 0.352303, 0.328226, 0.352303, 0.284545, 0.352303, 0.325273 + }, + Idx = { + 2, 73, 74, 2, 74, 21, 30, 0, 20, 30, 20, 31, 43, 42, 1, 43, 1, 33, 41, 40, 13, 41, 13, 3, 40, 71, 70, 40, 70, 13, 48, 9, 32, 48, + 32, 47, 45, 88, 10, 45, 10, 49, 39, 38, 35, 39, 35, 34, 66, 37, 16, 66, 16, 67, 6, 30, 31, 6, 31, 19, 46, 47, 32, 46, 32, 8, 44, + 43, 33, 44, 33, 7, 70, 69, 5, 70, 5, 13, 35, 27, 24, 35, 24, 34, 16, 18, 68, 16, 68, 67, 36, 18, 16, 36, 16, 37, 64, 17, 15, 64, + 15, 65, 26, 29, 28, 26, 28, 25, 50, 11, 12, 50, 12, 45, 72, 75, 74, 72, 74, 73, 17, 36, 37, 17, 37, 15, 65, 15, 37, 65, 37, 66, + 25, 28, 38, 25, 38, 39, 40, 88, 12, 40, 12, 71, 10, 88, 40, 10, 40, 41, 32, 9, 42, 32, 42, 43, 8, 32, 43, 8, 43, 44, 85, 84, 22, + 85, 22, 23, 20, 78, 77, 20, 77, 31, 19, 31, 77, 19, 77, 76, 48, 58, 51, 48, 51, 9, 10, 52, 56, 10, 56, 49, 41, 53, 52, 41, 52, + 10, 9, 51, 54, 9, 54, 42, 81, 80, 55, 81, 55, 21, 20, 57, 79, 20, 79, 78, 90, 89, 59, 90, 59, 60, 61, 91, 90, 61, 90, 60, 62, 92, + 91, 62, 91, 61, 63, 93, 92, 63, 92, 62, 29, 64, 65, 29, 65, 28, 28, 65, 66, 28, 66, 38, 38, 66, 67, 38, 67, 35, 68, 27, 35, 68, + 35, 67, 60, 59, 69, 60, 69, 70, 71, 61, 60, 71, 60, 70, 12, 62, 61, 12, 61, 71, 11, 63, 62, 11, 62, 12, 14, 4, 72, 14, 72, 73, 2, + 14, 73, 22, 81, 21, 22, 21, 74, 75, 23, 22, 75, 22, 74, 83, 82, 87, 83, 87, 86, 76, 77, 47, 76, 47, 46, 78, 48, 47, 78, 47, 77, + 79, 58, 48, 79, 48, 78, 49, 56, 82, 49, 82, 83, 84, 45, 49, 84, 49, 83, 85, 50, 45, 85, 45, 84, 87, 80, 81, 87, 81, 86, 22, 84, + 83, 22, 83, 86, 45, 12, 88, 34, 24, 89, 34, 89, 90, 91, 39, 34, 91, 34, 90, 92, 25, 39, 92, 39, 91, 93, 26, 25, 93, 25, 92, 0, + 98, 100, 0, 100, 20, 1, 96, 95, 1, 95, 33, 30, 99, 98, 30, 98, 0, 97, 96, 1, 97, 1, 42, 96, 3, 13, 96, 13, 95, 41, 3, 96, 41, 96, + 97, 98, 2, 21, 98, 21, 100, 99, 14, 2, 99, 2, 98, 102, 103, 51, 102, 51, 58, 56, 52, 103, 56, 103, 102, 101, 4, 14, 101, 14, 99, + 6, 101, 99, 6, 99, 30, 95, 94, 7, 95, 7, 33, 13, 5, 94, 13, 94, 95, 52, 53, 104, 52, 104, 103, 103, 104, 54, 103, 54, 51, 105, + 106, 79, 105, 79, 57, 97, 104, 53, 97, 53, 41, 42, 54, 104, 42, 104, 97, 21, 55, 105, 21, 105, 100, 100, 105, 57, 100, 57, 20, + 106, 105, 87, 106, 87, 82, 106, 102, 58, 106, 58, 79, 82, 56, 102, 82, 102, 106, 22, 86, 81, 80, 87, 105, 80, 105, 55, 109, 119, + 157, 109, 157, 156, 123, 124, 118, 123, 118, 107, 135, 126, 108, 135, 108, 134, 133, 110, 114, 133, 114, 132, 132, 114, 154, 132, + 154, 155, 138, 137, 125, 138, 125, 111, 136, 139, 112, 136, 112, 168, 131, 127, 128, 131, 128, 130, 152, 153, 117, 152, 117, 129, + 6, 19, 124, 6, 124, 123, 46, 8, 125, 46, 125, 137, 44, 7, 126, 44, 126, 135, 154, 114, 5, 154, 5, 69, 128, 127, 24, 128, 24, 27, + 117, 153, 68, 117, 68, 18, 36, 129, 117, 36, 117, 18, 64, 151, 116, 64, 116, 17, 26, 121, 122, 26, 122, 29, 50, 136, 113, 50, + 113, 11, 72, 156, 157, 72, 157, 75, 17, 116, 129, 17, 129, 36, 151, 152, 129, 151, 129, 116, 121, 131, 130, 121, 130, 122, 132, + 155, 113, 132, 113, 168, 112, 133, 132, 112, 132, 168, 125, 135, 134, 125, 134, 111, 8, 44, 135, 8, 135, 125, 85, 23, 120, 85, + 120, 165, 118, 124, 158, 118, 158, 159, 19, 76, 158, 19, 158, 124, 138, 111, 140, 138, 140, 147, 112, 139, 145, 112, 145, 141, + 133, 112, 141, 133, 141, 142, 111, 134, 143, 111, 143, 140, 162, 119, 144, 162, 144, 161, 118, 159, 160, 118, 160, 146, 169, 148, + 59, 169, 59, 89, 149, 148, 169, 149, 169, 170, 150, 149, 170, 150, 170, 171, 63, 150, 171, 63, 171, 93, 29, 122, 151, 29, 151, + 64, 122, 130, 152, 122, 152, 151, 130, 128, 153, 130, 153, 152, 68, 153, 128, 68, 128, 27, 148, 154, 69, 148, 69, 59, 155, 154, + 148, 155, 148, 149, 113, 155, 149, 113, 149, 150, 11, 113, 150, 11, 150, 63, 115, 156, 72, 115, 72, 4, 109, 156, 115, 120, 157, + 119, 120, 119, 162, 75, 157, 120, 75, 120, 23, 164, 166, 167, 164, 167, 163, 76, 46, 137, 76, 137, 158, 159, 158, 137, 159, 137, + 138, 160, 159, 138, 160, 138, 147, 139, 164, 163, 139, 163, 145, 165, 164, 139, 165, 139, 136, 85, 165, 136, 85, 136, 50, 167, + 166, 162, 167, 162, 161, 120, 166, 164, 120, 164, 165, 136, 168, 113, 127, 169, 89, 127, 89, 24, 170, 169, 127, 170, 127, 131, + 171, 170, 131, 171, 131, 121, 93, 171, 121, 93, 121, 26, 107, 118, 177, 107, 177, 175, 108, 126, 172, 108, 172, 173, 123, 107, + 175, 123, 175, 176, 174, 134, 108, 174, 108, 173, 173, 172, 114, 173, 114, 110, 133, 174, 173, 133, 173, 110, 175, 177, 119, 175, + 119, 109, 176, 175, 109, 176, 109, 115, 178, 147, 140, 178, 140, 179, 145, 178, 179, 145, 179, 141, 101, 176, 115, 101, 115, 4, + 6, 123, 176, 6, 176, 101, 172, 126, 7, 172, 7, 94, 114, 172, 94, 114, 94, 5, 141, 179, 180, 141, 180, 142, 179, 140, 143, 179, + 143, 180, 181, 146, 160, 181, 160, 182, 174, 133, 142, 174, 142, 180, 134, 174, 180, 134, 180, 143, 119, 177, 181, 119, 181, 144, + 177, 118, 146, 177, 146, 181, 182, 163, 167, 182, 167, 181, 182, 160, 147, 182, 147, 178, 163, 182, 178, 163, 178, 145, 120, 162, + 166, 161, 144, 181, 161, 181, 167, 189, 185, 190, 189, 190, 199, 190, 183, 188, 190, 188, 199, 197, 187, 196, 197, 196, 200, 188, + 183, 193, 188, 193, 201, 192, 186, 191, 192, 191, 198, 191, 184, 194, 191, 194, 198, 188, 184, 191, 188, 191, 199, 191, 186, 189, + 191, 189, 199, 194, 184, 188, 194, 188, 201, 196, 187, 195, 196, 195, 202, 195, 185, 189, 195, 189, 202, 189, 186, 196, 189, 196, + 202, 196, 186, 192, 196, 192, 200, 209, 214, 210, 209, 210, 205, 210, 214, 208, 210, 208, 203, 197, 200, 213, 197, 213, 207, 208, + 201, 193, 208, 193, 203, 192, 198, 211, 192, 211, 206, 211, 198, 194, 211, 194, 204, 208, 214, 211, 208, 211, 204, 211, 214, 209, + 211, 209, 206, 194, 201, 208, 194, 208, 204, 213, 215, 212, 213, 212, 207, 212, 215, 209, 212, 209, 205, 209, 215, 213, 209, 213, + 206, 213, 200, 192, 213, 192, 206, 230, 225, 231, 230, 231, 236, 231, 223, 229, 231, 229, 236, 219, 227, 234, 229, 223, 217, 229, + 217, 221, 216, 226, 232, 216, 232, 220, 232, 224, 218, 232, 218, 220, 229, 224, 232, 229, 232, 236, 232, 226, 230, 232, 230, 236, + 234, 238, 228, 234, 228, 219, 218, 224, 229, 218, 229, 221, 234, 227, 233, 234, 233, 237, 233, 225, 230, 233, 230, 237, 230, 226, + 235, 230, 235, 237, 235, 238, 234, 235, 234, 237, 228, 238, 235, 228, 235, 222, 235, 226, 216, 235, 216, 222, 245, 251, 246, 245, + 246, 241, 246, 251, 244, 246, 244, 239, 219, 249, 243, 244, 221, 217, 244, 217, 239, 216, 220, 247, 216, 247, 242, 247, 220, 218, + 247, 218, 240, 244, 251, 247, 244, 247, 240, 247, 251, 245, 247, 245, 242, 249, 219, 228, 249, 228, 253, 218, 221, 244, 218, 244, + 240, 249, 252, 248, 249, 248, 243, 248, 252, 245, 248, 245, 241, 245, 252, 250, 245, 250, 242, 250, 252, 249, 250, 249, 253, 228, + 222, 250, 228, 250, 253, 250, 222, 216, 250, 216, 242 + }, + } + ImPlot3D.CUBE_VTX_COUNT, ImPlot3D.CUBE_IDX_COUNT = Meshes.Cube.VtxCount, Meshes.Cube.IdxCount + ImPlot3D.SPHERE_VTX_COUNT, ImPlot3D.SPHERE_IDX_COUNT = Meshes.Sphere.VtxCount, Meshes.Sphere.IdxCount + ImPlot3D.DUCK_VTX_COUNT, ImPlot3D.DUCK_IDX_COUNT = Meshes.Duck.VtxCount, Meshes.Duck.IdxCount + end + + return ImPlot3D +end diff --git a/love/ImPlot3DDemo.lua b/love/ImPlot3DDemo.lua new file mode 100644 index 0000000..044f236 --- /dev/null +++ b/love/ImPlot3DDemo.lua @@ -0,0 +1,1536 @@ +-- GENERATED by tools/love.sh from the Luau source - do not edit +local function __iter(t, ...) if type(t) ~= 'table' or (getmetatable(t) and getmetatable(t).__call) then return t, ... end local n, i, k = #t, 0, nil return function() if i < n then i = i + 1 return i, t[i] end repeat k = next(t, k) until k == nil or type(k) ~= 'number' or k < 1 or k > n or k % 1 ~= 0 if k ~= nil then return k, t[k] end end end table.create = table.create or function(n, v) local t = {} if v ~= nil then for i = 1, n do t[i] = v end end return t end table.clone = table.clone or function(t) local c = {} for k, v in pairs(t) do c[k] = v end return setmetatable(c, getmetatable(t)) end math.clamp = math.clamp or function(x, a, b) return math.max(a, math.min(b, x)) end math.sign = math.sign or function(x) return x > 0 and 1 or (x < 0 and -1 or 0) end math.round = math.round or function(x) return x >= 0 and math.floor(x + 0.5) or math.ceil(x - 0.5) end +-- ImPlot3D demo (Luau port of implot3d_demo.cpp). Optional: ImPlot3D.lua never calls into this file. +-- Usage: require(path.to.ImPlot3DDemo)(G, ImPlot3D) -- defines ImPlot3D.ShowDemoWindow(p_open) -> new p_open, +-- ImPlot3D.ShowAllDemos(), ImPlot3D.ShowStyleEditor(ref), ImPlot3D.ShowAboutWindow(p_open) -> new p_open +-- [Port] Lua has no function-level 'static': they are fields of the file-level table S (S.FunctionName.x). +-- [Port] Demo* functions live in the table D (keeps the file chunk under the 200-locals limit). +-- [Port] Specs are plain tables of ImPlot3DSpec fields; arrays are 1-based; Stride/Offset are in elements. +return function(G, ImPlot3D) + local ImGui, ImVec2, ImVec4 = G.ImGui, G.ImVec2, G.ImVec4 + local IM_COL32 = G.IM_COL32 + local IM_PI = math.pi + local P = ImPlot3D.ImPlot3DPoint + local ImAxis3D = ImPlot3D.ImAxis3D + local Flags = ImPlot3D.ImPlot3DFlags + local AxisFlags = ImPlot3D.ImPlot3DAxisFlags + local Marker = ImPlot3D.ImPlot3DMarker + local Cond = ImPlot3D.ImPlot3DCond + local Colormap = ImPlot3D.ImPlot3DColormap + local LineFlags = ImPlot3D.ImPlot3DLineFlags + local TriFlags = ImPlot3D.ImPlot3DTriangleFlags + local QuadFlags = ImPlot3D.ImPlot3DQuadFlags + local SurfFlags = ImPlot3D.ImPlot3DSurfaceFlags + local MeshFlags = ImPlot3D.ImPlot3DMeshFlags + local Meshes = ImPlot3D.Meshes + local band, bor = bit32.band, bit32.bor + local _ + + local S = {} + local D = {} + + -- [Port] IMGUI_DEMO_MARKER: forwarded to ImGui.DemoMarker when available (no __LINE__ in Lua: line is 0) + local function IMGUI_DEMO_MARKER(section) + if ImGui.DemoMarker then ImGui.DemoMarker("implot3d_demo.cpp", 0, section) end + end + + -- [Port] CHECKBOX_FLAG(flags, flag) macro: label is the upstream flag name; returns the new flags + local function CHECKBOX_FLAG(flags, name, flag) + local _, v = ImGui.CheckboxFlags(name, flags, flag) + return v + end + + local function HelpMarker(desc) + ImGui.TextDisabled("(?)") + if ImGui.BeginItemTooltip() then + ImGui.PushTextWrapPos(ImGui.GetFontSize() * 35.0) + ImGui.TextUnformatted(desc) + ImGui.PopTextWrapPos() + ImGui.EndTooltip() + end + end + + -- [Port] rand()/RAND_MAX -> deterministic LCG so srand(0) sections repeat every frame like upstream + local seed = 0 + local function srand(s) seed = s end + local function rand01() + seed = (seed * 1103515245 + 12345) % 2147483648 + return seed / 2147483647 + end + + -- [Port] &arr[base] pointer arithmetic -> read-only proxy (0-based base) + local function Ptr(arr, base) + return setmetatable({}, { __index = function(_, i) return arr[i + base] end }) + end + + -- Utility structure for realtime plot + local function ScrollingBuffer(max_size) return { MaxSize = max_size or 2000, Offset = 0, Data = {} } end + local function AddPoint(b, x) + if #b.Data < b.MaxSize then + table.insert(b.Data, x) + else + b.Data[b.Offset + 1] = x + b.Offset = (b.Offset + 1) % b.MaxSize + end + end + + -- Custom axis formatter that adds metric prefixes (G, M, k, m, u, n) + -- [Port] ImPlot3DFormatter is function(value, data) -> string + local metric_v = { 1000000000, 1000000, 1000, 1, 0.001, 0.000001, 0.000000001 } + local metric_p = { "G", "M", "k", "", "m", "u", "n" } + local function MetricFormatter(value, unit) + if value == 0 then return "0 " .. unit end + for i = 1, 7 do + if math.abs(value) >= metric_v[i] then return string.format("%g %s%s", value / metric_v[i], metric_p[i], unit) end + end + return string.format("%g %s%s", value / metric_v[7], metric_p[7], unit) + end + + local function HSV_U32(h, s, v) return G.ImColor.HSV(h, s, v):U32() end + + --------------------------------------------------------------------------- + -- [SECTION] Plots + --------------------------------------------------------------------------- + + S.DemoLinePlots = { xs1 = {}, ys1 = {}, zs1 = {}, xs2 = {}, ys2 = {}, zs2 = {} } + function D.DemoLinePlots() + IMGUI_DEMO_MARKER("Plots/Line Plots") + local s = S.DemoLinePlots + local t = ImGui.GetTime() + for i = 1, 1001 do + local x = (i - 1) * 0.001 + s.xs1[i], s.ys1[i], s.zs1[i] = x, 0.5 + 0.5 * math.cos(50 * (x + t / 10)), 0.5 + 0.5 * math.sin(50 * (x + t / 10)) + end + for i = 1, 20 do + local x = (i - 1) / 19.0 + s.xs2[i], s.ys2[i], s.zs2[i] = x, x * x, x * x * x + end + if ImPlot3D.BeginPlot("Line Plots") then + ImPlot3D.SetupAxes("x", "y", "z") + ImPlot3D.PlotLine("f(x)", s.xs1, s.ys1, s.zs1, 1001) + ImPlot3D.PlotLine("g(x)", s.xs2, s.ys2, s.zs2, 20, { Marker = Marker.Circle, Flags = LineFlags.Segments }) + ImPlot3D.EndPlot() + end + end + + S.DemoScatterPlots = { xs1 = {}, ys1 = {}, zs1 = {}, xs2 = {}, ys2 = {}, zs2 = {} } + function D.DemoScatterPlots() + IMGUI_DEMO_MARKER("Plots/Scatter Plots") + local s = S.DemoScatterPlots + srand(0) + for i = 1, 100 do + local x = (i - 1) * 0.01 + s.xs1[i], s.ys1[i], s.zs1[i] = x, x + 0.1 * rand01(), x + 0.1 * rand01() + end + for i = 1, 50 do + s.xs2[i], s.ys2[i], s.zs2[i] = 0.25 + 0.2 * rand01(), 0.50 + 0.2 * rand01(), 0.75 + 0.2 * rand01() + end + if ImPlot3D.BeginPlot("Scatter Plots") then + ImPlot3D.PlotScatter("Data 1", s.xs1, s.ys1, s.zs1, 100) + local c = ImPlot3D.GetColormapColor(1) + ImPlot3D.PlotScatter("Data 2", s.xs2, s.ys2, s.zs2, 50, + { Marker = Marker.Square, MarkerSize = 6, MarkerLineColor = c, MarkerFillColor = c, FillAlpha = 0.25 }) + ImPlot3D.EndPlot() + end + end + + -- Pyramid: 6 triangles (4 sides + 2 base), 18 vertices + local function Pyramid() + local cx, cy = { -0.5, 0.5, 0.5, -0.5 }, { -0.5, -0.5, 0.5, 0.5 } + local xs, ys, zs = {}, {}, {} + local function V(x, y, z) table.insert(xs, x); table.insert(ys, y); table.insert(zs, z) end + local function C(i) V(cx[i + 1], cy[i + 1], 0) end + for k = 0, 3 do V(0, 0, 1); C(k); C((k + 1) % 4) end -- sides: apex, corner k, corner k+1 + C(0); C(1); C(2) -- base + C(0); C(2); C(3) + return xs, ys, zs + end + + S.DemoTrianglePlots = { flags = TriFlags.None } + function D.DemoTrianglePlots() + IMGUI_DEMO_MARKER("Plots/Triangle Plots") + local s = S.DemoTrianglePlots + if s.xs == nil then s.xs, s.ys, s.zs = Pyramid() end + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DTriangleFlags_NoLines", TriFlags.NoLines) + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DTriangleFlags_NoFill", TriFlags.NoFill) + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DTriangleFlags_NoMarkers", TriFlags.NoMarkers) + if ImPlot3D.BeginPlot("Triangle Plots") then + ImPlot3D.SetupAxesLimits(-1, 1, -1, 1, -0.5, 1.5) + ImPlot3D.PlotTriangle("Pyramid", s.xs, s.ys, s.zs, 6 * 3, { + FillColor = ImPlot3D.GetColormapColor(0), LineColor = ImPlot3D.GetColormapColor(1), + Marker = Marker.Square, MarkerSize = 3, Flags = s.flags, + }) + ImPlot3D.EndPlot() + end + end + + -- Cube faces as quads: +x, -x, +y, -y, +z, -z (4 vertices each) + -- stylua: ignore + local cube_quads = { + xs = { 1, 1, 1, 1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1 }, + ys = { -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1 }, + zs = { -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1 }, + } + S.DemoQuadPlots = { flags = QuadFlags.None, colorX = ImVec4(0.8, 0.2, 0.2, 0.8), colorY = ImVec4(0.2, 0.8, 0.2, 0.8), + colorZ = ImVec4(0.2, 0.2, 0.8, 0.8) } + function D.DemoQuadPlots() + IMGUI_DEMO_MARKER("Plots/Quad Plots") + local s, q = S.DemoQuadPlots, cube_quads + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DQuadFlags_NoLines", QuadFlags.NoLines) + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DQuadFlags_NoFill", QuadFlags.NoFill) + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DQuadFlags_NoMarkers", QuadFlags.NoMarkers) + if ImPlot3D.BeginPlot("Quad Plots") then + ImPlot3D.SetupAxesLimits(-1.5, 1.5, -1.5, 1.5, -1.5, 1.5) + for k, e in __iter({ { "X", s.colorX }, { "Y", s.colorY }, { "Z", s.colorZ } }) do + local base = (k - 1) * 8 -- [Port] &xs[base] + ImPlot3D.PlotQuad(e[1], Ptr(q.xs, base), Ptr(q.ys, base), Ptr(q.zs, base), 8, + { Marker = Marker.Square, MarkerSize = 3, Flags = s.flags, FillColor = e[2], LineColor = e[2] }) + end + ImPlot3D.EndPlot() + end + end + + local surface_colormaps = { "Viridis", "Plasma", "Hot", "Cool", "Pink", "Jet", "Twilight", "RdBu", "BrBG", "PiYG", "Spectral", "Greys" } + S.DemoSurfacePlots = { xs = {}, ys = {}, zs = {}, custom_colors = {}, t = 0, selected_fill = 1, solid_color = ImVec4(0.8, 0.8, 0.2, 0.6), + sel_colormap = 5, custom_range = false, range_min = -1.0, range_max = 1.0, flags = SurfFlags.NoMarkers } + function D.DemoSurfacePlots() + IMGUI_DEMO_MARKER("Plots/Surface Plots") + local s = S.DemoSurfacePlots + local N = 20 + s.t =s.t+ ImGui.GetIO().DeltaTime + -- Define the range for X and Y + local min_val, max_val = -1.0, 1.0 + local step = (max_val - min_val) / (N - 1) + for i = 0, N - 1 do + for j = 0, N - 1 do + local idx = i * N + j + 1 + local x, y = min_val + j * step, min_val + i * step -- X constant along rows, Y along columns + local z = math.sin(2 * s.t + math.sqrt(x * x + y * y)) -- z = sin(2t + sqrt(x^2 + y^2)) + s.xs[idx], s.ys[idx], s.zs[idx] = x, y, z + -- Custom per-point color: R=x, G=y, B=z (each remapped from [-1,1] to [0,1]) + s.custom_colors[idx] = IM_COL32(math.floor((x + 1) * 0.5 * 255), math.floor((y + 1) * 0.5 * 255), math.floor((z + 1) * 0.5 * 255), 255) + end + end + + -- Choose fill color + ImGui.Text("Fill color") + ImGui.Indent() + _, s.selected_fill = ImGui.RadioButton("Solid", s.selected_fill, 0) + if s.selected_fill == 0 then + ImGui.SameLine() + ImGui.ColorEdit4("##SurfaceSolidColor", s.solid_color) + end + _, s.selected_fill = ImGui.RadioButton("Colormap", s.selected_fill, 1) + if s.selected_fill == 1 then + ImGui.SameLine() + s.sel_colormap = ImGui.Combo("##SurfaceColormap", s.sel_colormap, surface_colormaps) + end + _, s.selected_fill = ImGui.RadioButton("Custom Per-Point", s.selected_fill, 2) + if s.selected_fill == 2 then + ImGui.SameLine(); ImGui.TextDisabled("R=x, G=y, B=z") + end + ImGui.Unindent() + + -- Choose range (only applies to Colormap mode) + if s.selected_fill ~= 1 then ImGui.BeginDisabled() end + _, s.custom_range = ImGui.Checkbox("Custom range", s.custom_range) + ImGui.Indent() + if not s.custom_range then ImGui.BeginDisabled() end + s.range_min = ImGui.SliderFloat("Range min", s.range_min, -1.0, s.range_max - 0.01) + s.range_max = ImGui.SliderFloat("Range max", s.range_max, s.range_min + 0.01, 1.0) + if not s.custom_range then ImGui.EndDisabled() end + ImGui.Unindent() + if s.selected_fill ~= 1 then ImGui.EndDisabled() end + + -- Select flags + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DSurfaceFlags_NoLines", SurfFlags.NoLines) + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DSurfaceFlags_NoFill", SurfFlags.NoFill) + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DSurfaceFlags_NoMarkers", SurfFlags.NoMarkers) + + if s.selected_fill == 1 then ImPlot3D.PushColormap(surface_colormaps[s.sel_colormap + 1]) end + if ImPlot3D.BeginPlot("Surface Plots", ImVec2(-1, 0), Flags.NoClip) then + ImPlot3D.SetupAxesLimits(-1, 1, -1, 1, -1.5, 1.5) + local spec = { FillAlpha = 0.8, Flags = s.flags, Marker = Marker.Square, LineColor = ImPlot3D.GetColormapColor(1) } + if s.selected_fill == 0 then + spec.FillColor = s.solid_color + elseif s.selected_fill == 2 then + spec.FillColors = s.custom_colors + end + local lo, hi = 0.0, 0.0 + if s.custom_range then lo, hi = s.range_min, s.range_max end + ImPlot3D.PlotSurface("Wave Surface", s.xs, s.ys, s.zs, N, N, lo, hi, spec) + ImPlot3D.EndPlot() + end + if s.selected_fill == 1 then ImPlot3D.PopColormap() end + end + + S.DemoMeshPlots = { mesh_id = 0, line_color = ImVec4(0.5, 0.5, 0.2, 0.6), fill_color = ImVec4(0.8, 0.8, 0.2, 0.6), + marker_color = ImVec4(0.5, 0.5, 0.2, 0.6), flags = MeshFlags.NoMarkers } + function D.DemoMeshPlots() + IMGUI_DEMO_MARKER("Plots/Mesh Plots") + local s = S.DemoMeshPlots + s.mesh_id = ImGui.Combo("Mesh", s.mesh_id, "Duck\0Sphere\0Cube\0\0") + ImGui.ColorEdit4("Line Color##Mesh", s.line_color) + ImGui.ColorEdit4("Fill Color##Mesh", s.fill_color) + ImGui.ColorEdit4("Marker Color##Mesh", s.marker_color) + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DMeshFlags_NoLines", MeshFlags.NoLines) + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DMeshFlags_NoFill", MeshFlags.NoFill) + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DMeshFlags_NoMarkers", MeshFlags.NoMarkers) + if ImPlot3D.BeginPlot("Mesh Plots") then + ImPlot3D.SetupAxesLimits(-1, 1, -1, 1, -1, 1) + local spec = { Flags = s.flags, FillColor = s.fill_color, LineColor = s.line_color, Marker = Marker.Square, MarkerSize = 3.0, + MarkerLineColor = s.marker_color, MarkerFillColor = s.marker_color } + -- [Port] ImPlot3D.Meshes keep upstream's 0-based indices + local name = ({ [0] = "Duck", "Sphere", "Cube" })[s.mesh_id] + local m = Meshes[name] + ImPlot3D.PlotMesh(name, m.VtxXs, m.VtxYs, m.VtxZs, m.Idx, m.VtxCount, m.IdxCount, spec) + ImPlot3D.EndPlot() + end + end + + -- [Port] ImPlot3DPoint/ImVec2 statics -> 1-based arrays for SliderFloat3/SliderFloat2; ImVec4 tints edited in place + S.DemoImagePlots = { tint1 = ImVec4(1, 1, 1, 1), tint2 = ImVec4(1, 1, 1, 1), center1 = { 0, 0, 1 }, axis_u1 = { 1, 0, 0 }, + axis_v1 = { 0, 1, 0 }, uv0_1 = { 0, 0 }, uv1_1 = { 1, 1 }, p0 = { -1, -1, 0 }, p1 = { 1, -1, 0 }, p2 = { 1, 1, 0 }, + p3 = { -1, 1, 0 }, uv0 = { 0, 0 }, uv1 = { 1, 0 }, uv2 = { 1, 1 }, uv3 = { 0, 1 } } + function D.DemoImagePlots() + IMGUI_DEMO_MARKER("Plots/Image Plots") + local s = S.DemoImagePlots + ImGui.BulletText("Below we are displaying the font texture, which is the only texture we have\naccess to in this demo.") + ImGui.BulletText("Use the 'ImTextureID' type as storage to pass pointers or identifiers to your\nown texture data.") + ImGui.BulletText("See ImGui Wiki page 'Image Loading and Displaying Examples'.") + ImGui.Dummy(ImVec2(0, 10)) + if ImGui.TreeNodeEx("Image 1 Controls: Center + Axes") then + ImGui.SliderFloat3("Center", s.center1, -2, 2, "%.1f") + ImGui.SliderFloat3("Axis U", s.axis_u1, -2, 2, "%.1f") + ImGui.SliderFloat3("Axis V", s.axis_v1, -2, 2, "%.1f") + ImGui.SliderFloat2("UV0", s.uv0_1, 0, 1, "%.2f") + ImGui.SliderFloat2("UV1", s.uv1_1, 0, 1, "%.2f") + ImGui.ColorEdit4("Tint", s.tint1) + ImGui.TreePop() + end + if ImGui.TreeNodeEx("Image 2 Controls: Full Quad") then + ImGui.SliderFloat3("P0", s.p0, -2, 2, "%.1f") + ImGui.SliderFloat3("P1", s.p1, -2, 2, "%.1f") + ImGui.SliderFloat3("P2", s.p2, -2, 2, "%.1f") + ImGui.SliderFloat3("P3", s.p3, -2, 2, "%.1f") + ImGui.SliderFloat2("UV0", s.uv0, 0, 1, "%.2f") + ImGui.SliderFloat2("UV1", s.uv1, 0, 1, "%.2f") + ImGui.SliderFloat2("UV2", s.uv2, 0, 1, "%.2f") + ImGui.SliderFloat2("UV3", s.uv3, 0, 1, "%.2f") + ImGui.ColorEdit4("Tint##2", s.tint2) + ImGui.TreePop() + end + if ImPlot3D.BeginPlot("Image Plot", ImVec2(-1, 0), Flags.NoClip) then + -- We use the font atlas texture for this demo; your own loaded textures work just as well. + local tex = ImGui.GetIO().Fonts.TexRef + local function p3(a) return P(a[1], a[2], a[3]) end + local function v2(a) return ImVec2(a[1], a[2]) end + ImPlot3D.PlotImage("Image 1", tex, p3(s.center1), p3(s.axis_u1), p3(s.axis_v1), v2(s.uv0_1), v2(s.uv1_1), s.tint1) + ImPlot3D.PlotImage("Image 2", tex, p3(s.p0), p3(s.p1), p3(s.p2), p3(s.p3), v2(s.uv0), v2(s.uv1), v2(s.uv2), v2(s.uv3), s.tint2) + ImPlot3D.EndPlot() + end + end + + S.DemoRealtimePlots = { sdata1 = ScrollingBuffer(), sdata2 = ScrollingBuffer(), sdata3 = ScrollingBuffer(), + flags = AxisFlags.NoTickLabels, t = 0.0, last_t = -1.0 } + function D.DemoRealtimePlots() + IMGUI_DEMO_MARKER("Plots/Realtime Plots") + local s = S.DemoRealtimePlots + ImGui.BulletText("Move your mouse to change the data!") + if ImPlot3D.BeginPlot("Scrolling Plot") then + -- Pool mouse data every 10 ms + s.t =s.t+ ImGui.GetIO().DeltaTime + if s.t - s.last_t > 0.01 then + s.last_t = s.t + local mouse = ImGui.GetMousePos() + if math.abs(mouse.x) < 1e4 and math.abs(mouse.y) < 1e4 then + local pos, size = ImPlot3D.GetFramePos(), ImPlot3D.GetFrameSize() + AddPoint(s.sdata1, s.t) + AddPoint(s.sdata2, mouse.x - (pos.x + size.x / 2)) + AddPoint(s.sdata3, mouse.y - (pos.y + size.y / 2)) + end + end + ImPlot3D.SetupAxes("Time", "Mouse X", "Mouse Y", s.flags, s.flags, s.flags) + ImPlot3D.SetupAxisLimits(ImAxis3D.X, s.t - 10.0, s.t, Cond.Always) + ImPlot3D.SetupAxisLimits(ImAxis3D.Y, -400, 400, Cond.Once) + ImPlot3D.SetupAxisLimits(ImAxis3D.Z, -400, 400, Cond.Once) + ImPlot3D.PlotLine("Mouse", s.sdata1.Data, s.sdata2.Data, s.sdata3.Data, #s.sdata1.Data, { Offset = s.sdata1.Offset }) + ImPlot3D.EndPlot() + end + end + + local plot_flag_list = { + { "NoTitle", "Hide plot title" }, { "NoLegend", "Hide plot legend" }, + { "NoMouseText", "Hide mouse position in plot coordinates" }, { "NoClip", "Disable 3D box clipping" }, + { "NoMenus", "The user will not be able to open context menus" }, + { "Equal", "X, Y, and Z axes will be constrained to have the same units/pixel" }, + { "NoRotate", "Lock rotation interaction" }, { "NoPan", "Lock panning/translation interaction" }, + { "NoZoom", "Lock zooming interaction" }, { "NoInputs", "Disable all user inputs" }, + } + S.DemoPlotFlags = { flags = Flags.None, x = {}, y = {}, z = {} } + for i = 0, 99 do + local t = i * 0.1 + S.DemoPlotFlags.x[i + 1], S.DemoPlotFlags.y[i + 1], S.DemoPlotFlags.z[i + 1] = 3.0 * math.cos(t), 3.0 * math.sin(t), t - 5.0 + end + local corner_xs, corner_ys, corner_zs = { -10, 10, -10, 10, -10, 10, -10, 10 }, { -10, -10, 10, 10, -10, -10, 10, 10 }, { -5, -5, -5, -5, 5, 5, 5, 5 } + function D.DemoPlotFlags() + IMGUI_DEMO_MARKER("Plots/Plot Flags") + local s = S.DemoPlotFlags + -- [Port] the repeated CHECKBOX_FLAG + "(?)" tooltip blocks folded into a loop + for _, f in __iter(plot_flag_list) do + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DFlags_" .. f[1], Flags[f[1] ]) + ImGui.SameLine() + ImGui.TextDisabled("(?)") + if ImGui.IsItemHovered() then ImGui.SetTooltip(f[2]) end + end + if ImPlot3D.BeginPlot("Plot Flags Demo", ImVec2(-1, 0), s.flags) then + ImPlot3D.SetupAxes("X-axis", "Y-axis", "Z-axis") + ImPlot3D.SetupAxesLimits(-10, 10, -10, 10, -5, 5) + ImPlot3D.PlotLine("Helix", s.x, s.y, s.z, 100) + -- Add some scatter points to show equal scaling effect + ImPlot3D.PlotScatter("Cube corners", corner_xs, corner_ys, corner_zs, 8) + ImPlot3D.EndPlot() + end + end + + S.DemoOffsetAndStride = { offset = 0, data = {} } + function D.DemoOffsetAndStride() + IMGUI_DEMO_MARKER("Plots/Offset and Stride") + local s = S.DemoOffsetAndStride + local k_spirals, k_points_per = 11, 50 + local data = s.data + for p = 0, k_points_per - 1 do + for sp = 0, k_spirals - 1 do + local r = sp / (k_spirals - 1) * 0.2 + 0.2 + local theta = p / k_points_per * 6.28 + local base = p * 3 * k_spirals + 3 * sp + 1 + data[base], data[base + 1], data[base + 2] = 0.5 + r * math.cos(theta), 0.5 + r * math.sin(theta), 0.5 + 0.5 * math.sin(2.0 * theta) + end + end + ImGui.BulletText("Offsetting is useful for realtime plots (see above) and circular buffers.") + ImGui.BulletText("Striding is useful for interleaved data (e.g. audio) or plotting structs.") + ImGui.BulletText("Here, all spiral data is stored in a single interleaved buffer:") + ImGui.BulletText("[s0.x0 s0.y0 s0.z0 ... sn.x0 sn.y0 sn.z0 s0.x1 s0.y1 s0.z1 ... sn.x1 sn.y1 sn.z1 ... sn.xm sn.ym sn.zm]") + ImGui.BulletText("The offset value indicates which spiral point index is considered the first.") + ImGui.BulletText("Offsets can be negative and/or larger than the actual data count.") + s.offset = ImGui.SliderInt("Offset", s.offset, -2 * k_points_per, 2 * k_points_per) + if ImPlot3D.BeginPlot("##strideoffset", ImVec2(-1, 0)) then + ImPlot3D.PushColormap(Colormap.Jet) + for sp = 0, k_spirals - 1 do + -- [Port] &data[s*3+k] -> Ptr proxy; Stride is in elements (3*k_spirals doubles) + ImPlot3D.PlotLine(string.format("Spiral %d", sp), Ptr(data, sp * 3), Ptr(data, sp * 3 + 1), Ptr(data, sp * 3 + 2), + k_points_per, { Offset = s.offset, Stride = 3 * k_spirals }) + end + ImPlot3D.EndPlot() + ImPlot3D.PopColormap() + end + end + + local Location, LegendFlags = ImPlot3D.ImPlot3DLocation, ImPlot3D.ImPlot3DLegendFlags + S.DemoLegendOptions = { loc = Location.East, flags = 0, num_dummy_items = 25, t = 0, + xs1 = {}, ys1 = {}, zs1 = {}, xs2 = {}, ys2 = {}, zs2 = {}, xs3 = {}, ys3 = {}, zs3 = {} } + local legend_flag_list = { + { "Horizontal", "Legend entries will be displayed horizontally" }, + { "NoButtons", "Legend icons will not function as hide/show buttons" }, + { "NoHighlightItem", "Plot items will not be highlighted when their legend entry is hovered" }, + } + function D.DemoLegendOptions() + IMGUI_DEMO_MARKER("Plots/Legend Options") + local s = S.DemoLegendOptions + for i, l in __iter({ "North", "South", "West", "East" }) do + if i > 1 then ImGui.SameLine() end + _, s.loc = ImGui.CheckboxFlags(l, s.loc, Location[l]) + end + for _, f in __iter(legend_flag_list) do + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DLegendFlags_" .. f[1], LegendFlags[f[1] ]) + ImGui.SameLine() + ImGui.TextDisabled("(?)") + if ImGui.IsItemHovered() then ImGui.SetTooltip(f[2]) end + end + local style = ImPlot3D.GetStyle() + ImGui.SliderFloat2("LegendPadding", style.LegendPadding, 0.0, 20.0, "%.0f") + ImGui.SliderFloat2("LegendInnerPadding", style.LegendInnerPadding, 0.0, 10.0, "%.0f") + ImGui.SliderFloat2("LegendSpacing", style.LegendSpacing, 0.0, 5.0, "%.0f") + s.num_dummy_items = ImGui.SliderInt("Num Dummy Items (Demo Scrolling)", s.num_dummy_items, 0, 100) + if ImPlot3D.BeginPlot("Legend Options Demo", ImVec2(-1, 0)) then + ImPlot3D.SetupAxes("X-Axis", "Y-Axis", "Z-Axis") + ImPlot3D.SetupAxesLimits(-1, 1, -1, 1, -1, 1) + ImPlot3D.SetupLegend(s.loc, s.flags) + -- Generate some 3D line data + s.t =s.t+ ImGui.GetIO().DeltaTime * 0.5 + local count = 50 + for i = 1, count do + local phase = (i - 1) * 0.1 + s.t + s.xs1[i], s.ys1[i], s.zs1[i] = 0.8 * math.cos(phase), 0.8 * math.sin(phase), 0.5 * math.sin(phase * 2) + s.xs2[i], s.ys2[i], s.zs2[i] = 0.6 * math.cos(phase + 1.0), 0.6 * math.sin(phase + 1.0), -0.3 * math.cos(phase * 1.5) + s.xs3[i], s.ys3[i], s.zs3[i] = 0.4 * math.sin(phase), 0.4 * math.cos(phase), 0.7 * math.cos(phase * 0.8) + end + ImPlot3D.PlotLine("Helix A", s.xs1, s.ys1, s.zs1, count) + ImPlot3D.PlotLine("Helix B##IDText", s.xs2, s.ys2, s.zs2, count) -- Text after ## used for ID only + ImPlot3D.PlotLine("##NotListed", s.xs3, s.ys3, s.zs3, count) -- Plotted, but not added to legend + -- Add dummy items to demonstrate legend scrolling (scroll the mouse wheel over the legend) + for i = 0, s.num_dummy_items - 1 do + ImPlot3D.PlotDummy(string.format("Item %03d", i)) + end + ImPlot3D.EndPlot() + end + end + + S.DemoMarkersAndText = {} + function D.DemoMarkersAndText() + IMGUI_DEMO_MARKER("Plots/Markers and Text") + local s = S.DemoMarkersAndText + if s.mk_size == nil then s.mk_size, s.mk_weight = ImPlot3D.GetStyle().MarkerSize, ImPlot3D.GetStyle().LineWeight end + s.mk_size = ImGui.DragFloat("Marker Size", s.mk_size, 0.1, 2.0, 10.0, "%.2f px") + s.mk_weight = ImGui.DragFloat("Marker Weight", s.mk_weight, 0.05, 0.5, 3.0, "%.2f px") + if ImPlot3D.BeginPlot("##MarkerStyles", ImVec2(-1, 0), Flags.CanvasOnly) then + local nd = AxisFlags.NoDecorations + ImPlot3D.SetupAxes(nil, nil, nil, nd, nd, nd) + local COUNT = Marker.COUNT + ImPlot3D.SetupAxesLimits(-0.5, 1.5, -0.5, 1.5, 0, COUNT + 1) + local xs, ys, zs = { 0, 0 }, { 0, 0 }, { COUNT, COUNT + 1 } + -- Filled markers + for m = 0, COUNT - 1 do + xs[2] = xs[1] + math.cos(zs[1] / COUNT * 2 * IM_PI) * 0.5 + ys[2] = ys[1] + math.sin(zs[1] / COUNT * 2 * IM_PI) * 0.5 + ImGui.PushID(m) + ImPlot3D.PlotLine("##Filled", xs, ys, zs, 2, { Marker = m, MarkerSize = s.mk_size, LineWeight = s.mk_weight }) + ImGui.PopID() + zs[1]=zs[1]- 1; zs[2]=zs[2]- 1 + end + xs[1], ys[1], zs[1] = 1, 1, COUNT + zs[2] = zs[1] + 1 + -- Open markers + for m = 0, COUNT - 1 do + xs[2] = xs[1] + math.cos(zs[1] / COUNT * 2 * IM_PI) * 0.5 + ys[2] = ys[1] - math.sin(zs[1] / COUNT * 2 * IM_PI) * 0.5 + ImGui.PushID(m) + ImPlot3D.PlotLine("##Open", xs, ys, zs, 2, { Marker = m, MarkerSize = s.mk_size, LineWeight = s.mk_weight, FillColor = ImVec4(0, 0, 0, 0) }) + ImGui.PopID() + zs[1]=zs[1]- 1; zs[2]=zs[2]- 1 + end + ImPlot3D.PlotText("Filled Markers", 0.0, 0.0, 6.0) + ImPlot3D.PlotText("Open Markers", 1.0, 1.0, 6.0) + ImPlot3D.PushStyleColor(ImPlot3D.ImPlot3DCol.InlayText, ImVec4(1, 0, 1, 1)) + ImPlot3D.PlotText("Rotated Text", 0.5, 0.5, 6.0, IM_PI / 4, ImVec2(0, 0)) + ImPlot3D.PopStyleColor() + ImPlot3D.EndPlot() + end + end + + S.DemoNaNValues = { include_nan = true, flags = 0 } + function D.DemoNaNValues() + IMGUI_DEMO_MARKER("Plots/NaN Values") + local s = S.DemoNaNValues + local data1, data2, data3 = { 0.0, 0.25, 0.5, 0.75, 1.0 }, { 0.0, 0.25, 0.5, 0.75, 1.0 }, { 0.0, 0.25, 0.5, 0.75, 1.0 } + if s.include_nan then data1[3] = 0 / 0 end + _, s.include_nan = ImGui.Checkbox("Include NaN", s.include_nan) + ImGui.SameLine() + _, s.flags = ImGui.CheckboxFlags("Skip NaN", s.flags, LineFlags.SkipNaN) + if ImPlot3D.BeginPlot("##NaNValues") then + ImPlot3D.PlotLine("Line", data1, data2, data3, 5, { Flags = s.flags, Marker = Marker.Square }) + ImPlot3D.EndPlot() + end + end + + -- Cube [0,1]^3 as quads (+x, -x, +y, -y, +z, -z) + -- stylua: ignore + local unit_quads = { + xs = { 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0 }, + ys = { 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1 }, + zs = { 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0 }, + } + + -- Gouraud-shaded duck: per-vertex normals -> point light + ambient, mapped to index-buffer slots + local function BuildDuckColors() + local m = Meshes.Duck + local X, Y, Z, idx = m.VtxXs, m.VtxYs, m.VtxZs, m.Idx + local nx, ny, nz = table.create(m.VtxCount, 0), table.create(m.VtxCount, 0), table.create(m.VtxCount, 0) + -- Accumulate area-weighted face normals into each vertex + for i = 1, m.IdxCount, 3 do + local a, b, c = idx[i] + 1, idx[i + 1] + 1, idx[i + 2] + 1 + local ux, uy, uz = X[b] - X[a], Y[b] - Y[a], Z[b] - Z[a] + local vx, vy, vz = X[c] - X[a], Y[c] - Y[a], Z[c] - Z[a] + local fx, fy, fz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in __iter({ a, b, c }) do nx[v]=nx[v]+ fx; ny[v]=ny[v]+ fy; nz[v]=nz[v]+ fz end + end + local function norm(x, y, z) + local len = math.sqrt(x * x + y * y + z * z) + if len > 1e-8 then return x / len, y / len, z / len end + return 0, 0, 1 + end + -- Lighting: yellow duck (1, 0.85, 0.1), warm white light (1, 0.95, 0.8) at (2, 2, 3), dim warm ambient (0.15, 0.12, 0.03) + local vtx_colors = {} + for v = 1, m.VtxCount do + local ax, ay, az = norm(nx[v], ny[v], nz[v]) + local lx, ly, lz = norm(2 - X[v], 2 - Y[v], 3 - Z[v]) + local diff = math.max(0, ax * lx + ay * ly + az * lz) + local r = math.min(1, 0.15 + 1.0 * 1.0 * diff) + local g = math.min(1, 0.12 + 0.85 * 0.95 * diff) + local b = math.min(1, 0.03 + 0.1 * 0.8 * diff) + vtx_colors[v] = IM_COL32(math.floor(r * 255), math.floor(g * 255), math.floor(b * 255), 255) + end + local out = {} + for i = 1, m.IdxCount do out[i] = vtx_colors[idx[i] + 1] end + return out + end + + S.Demo_PerIndexColors = { xs1 = {}, ys1 = {}, zs1 = {}, colors1 = {}, xs2 = {}, ys2 = {}, zs2 = {}, colors2 = {} } + function D.Demo_PerIndexColors() + IMGUI_DEMO_MARKER("Plots/Per-Index Colors") + local s = S.Demo_PerIndexColors + local Viridis = Colormap.Viridis + local function cm(t, c) return ImGui.GetColorU32(ImPlot3D.SampleColormap(t, c)) end + -- Colorful Lines + local t = ImGui.GetTime() + for i = 1, 1001 do + local x = (i - 1) * 0.001 + s.xs1[i], s.ys1[i], s.zs1[i] = x, 0.5 + 0.5 * math.sin(50 * (x + t / 10)), 0.5 + 0.5 * math.cos(50 * (x + t / 10)) + s.colors1[i] = HSV_U32((i - 1) / 1000.0, 0.8, 0.9) -- Rainbow colors + end + for i = 1, 20 do + local x = (i - 1) / 19.0 + s.xs2[i], s.ys2[i], s.zs2[i] = x, x * x, x * x * x + s.colors2[i] = cm((i - 1) / 19.0, Viridis) -- Colormap colors (Viridis) + end + if ImPlot3D.BeginPlot("Colorful Lines") then + ImPlot3D.PlotLine("f(x)", s.xs1, s.ys1, s.zs1, 1001, { LineColors = s.colors1 }) + ImPlot3D.PlotLine("g(x)", s.xs2, s.ys2, s.zs2, 20, { Marker = Marker.Circle, Flags = LineFlags.Segments, LineColors = s.colors2, + MarkerFillColors = s.colors2, MarkerLineColors = s.colors2 }) + ImPlot3D.EndPlot() + end + + -- Colorful Scatter + if s.sc == nil then + srand(0) + local sc = { xs1 = {}, ys1 = {}, zs1 = {}, fill1 = {}, line1 = {}, sizes1 = {}, xs2 = {}, ys2 = {}, zs2 = {}, colors2 = {}, sizes2 = {} } + for i = 1, 100 do + local x = (i - 1) * 0.01 + sc.xs1[i], sc.ys1[i], sc.zs1[i] = x, x + 0.1 * rand01(), x + 0.1 * rand01() + local hue = (i - 1) / 99.0 -- Rainbow hue colors + sc.fill1[i], sc.line1[i] = HSV_U32(hue, 0.8, 0.9), HSV_U32(hue, 0.9, 0.7) + sc.sizes1[i] = 2.0 + 4.0 * rand01() -- Random sizes between 2 and 6 + end + for i = 1, 50 do + sc.xs2[i], sc.ys2[i], sc.zs2[i] = 0.25 + 0.2 * rand01(), 0.50 + 0.2 * rand01(), 0.75 + 0.2 * rand01() + sc.colors2[i] = cm((i - 1) / 49.0, Viridis) + sc.sizes2[i] = 2.0 + 4.0 * rand01() + end + -- Colorful Triangles (pyramid, Hot colormap sampled by z) / Colorful Quads (R=x, G=y, B=z) + sc.tx, sc.ty, sc.tz = Pyramid() + sc.tri_colors, sc.quad_colors = {}, {} + for i = 1, 18 do sc.tri_colors[i] = cm(0.5 * sc.tz[i], Colormap.Hot) end + local q = unit_quads + for i = 1, 24 do sc.quad_colors[i] = IM_COL32(q.xs[i] * 255, q.ys[i] * 255, q.zs[i] * 255, 255) end + sc.duck_fill_colors = BuildDuckColors() + s.sc = sc + end + local sc = s.sc + if ImPlot3D.BeginPlot("Colorful Scatter") then + ImPlot3D.PlotScatter("Data 1", sc.xs1, sc.ys1, sc.zs1, 100, { MarkerFillColors = sc.fill1, MarkerLineColors = sc.line1, MarkerSizes = sc.sizes1 }) + ImPlot3D.PlotScatter("Data 2", sc.xs2, sc.ys2, sc.zs2, 50, { Marker = Marker.Square, MarkerFillColors = sc.colors2, + MarkerLineColors = sc.colors2, MarkerSizes = sc.sizes2, FillAlpha = 0.5 }) + ImPlot3D.EndPlot() + end + if ImPlot3D.BeginPlot("Colorful Triangles") then + ImPlot3D.SetupAxesLimits(-1, 1, -1, 1, -0.5, 1.5) + ImPlot3D.PlotTriangle("Pyramid", sc.tx, sc.ty, sc.tz, 18, { FillColors = sc.tri_colors, FillAlpha = 0.8 }) + ImPlot3D.EndPlot() + end + if ImPlot3D.BeginPlot("Colorful Quads") then + ImPlot3D.SetupAxesLimits(-0.5, 1.5, -0.5, 1.5, -0.5, 1.5) + ImPlot3D.PlotQuad("Cube", unit_quads.xs, unit_quads.ys, unit_quads.zs, 24, { FillColors = sc.quad_colors, FillAlpha = 0.8 }) + ImPlot3D.EndPlot() + end + if ImPlot3D.BeginPlot("Gouraud Duck") then + ImPlot3D.SetupAxesLimits(-1, 1, -1, 1, -1, 1) + local m = Meshes.Duck + ImPlot3D.PlotMesh("Duck", m.VtxXs, m.VtxYs, m.VtxZs, m.Idx, m.VtxCount, m.IdxCount, { FillColors = sc.duck_fill_colors, Flags = MeshFlags.NoLines }) + ImPlot3D.EndPlot() + end + end + + --------------------------------------------------------------------------- + -- [SECTION] Axes + --------------------------------------------------------------------------- + + S.DemoBoxScale = { scale = { 1.0, 1.0, 1.0 }, xs = {}, ys = {}, zs = {} } + function D.DemoBoxScale() + IMGUI_DEMO_MARKER("Axes/Box Scale") + local s = S.DemoBoxScale + local N = 100 + for i = 1, N do + local t = (i - 1) / (N - 1) + s.xs[i], s.ys[i], s.zs[i] = math.sin(t * 2 * IM_PI), math.cos(t * 4 * IM_PI), t * 2 - 1 + end + ImGui.SliderFloat3("Box Scale", s.scale, 0.1, 2.0, "%.2f") + if ImPlot3D.BeginPlot("##BoxScale") then + ImPlot3D.SetupBoxScale(s.scale[1], s.scale[2], s.scale[3]) + ImPlot3D.PlotLine("3D Curve", s.xs, s.ys, s.zs, N) + ImPlot3D.EndPlot() + end + end + + S.DemoBoxRotation = { elevation = 45.0, azimuth = -135.0, animate = false, init_elevation = 45.0, init_azimuth = -135.0 } + function D.DemoBoxRotation() + IMGUI_DEMO_MARKER("Axes/Box Rotation") + local s = S.DemoBoxRotation + local origin, axis = { 0.0, 0.0 }, { 0.0, 1.0 } + ImGui.Text("Rotation") + local c1, c2 + s.elevation, c1 = ImGui.SliderFloat("Elevation", s.elevation, -90.0, 90.0, "%.1f degrees") + s.azimuth, c2 = ImGui.SliderFloat("Azimuth", s.azimuth, -180.0, 180.0, "%.1f degrees") + local changed = c1 or c2 + _, s.animate = ImGui.Checkbox("Animate", s.animate) + ImGui.Text("Initial Rotation") + ImGui.SameLine() + HelpMarker("The rotation will be reset to the initial rotation when you double right-click") + s.init_elevation = ImGui.SliderFloat("Initial Elevation", s.init_elevation, -90.0, 90.0, "%.1f degrees") + s.init_azimuth = ImGui.SliderFloat("Initial Azimuth", s.init_azimuth, -180.0, 180.0, "%.1f degrees") + if ImPlot3D.BeginPlot("##BoxRotation") then + ImPlot3D.SetupAxesLimits(-1, 1, -1, 1, -1, 1, Cond.Always) + ImPlot3D.SetupBoxInitialRotation(s.init_elevation, s.init_azimuth) + if changed then ImPlot3D.SetupBoxRotation(s.elevation, s.azimuth, s.animate, Cond.Always) end + ImPlot3D.PlotLine("X-Axis", axis, origin, origin, 2, { LineColor = ImVec4(0.8, 0.2, 0.2, 1) }) + ImPlot3D.PlotLine("Y-Axis", origin, axis, origin, 2, { LineColor = ImVec4(0.2, 0.8, 0.2, 1) }) + ImPlot3D.PlotLine("Z-Axis", origin, origin, axis, 2, { LineColor = ImVec4(0.2, 0.2, 0.8, 1) }) + ImPlot3D.EndPlot() + end + end + + local Scale = ImPlot3D.ImPlot3DScale + S.Demo_LogScale = { xs = {}, ys1 = {}, ys2 = {}, ys3 = {}, zs = {} } + for i = 1, 1001 do + local s, x = S.Demo_LogScale, (i - 1) * 0.1 + s.xs[i], s.ys1[i], s.ys2[i], s.ys3[i], s.zs[i] = x, math.sin(x) + 1, math.log(x), 10 ^ x, 0.0 + end + function D.Demo_LogScale() + IMGUI_DEMO_MARKER("Axes/Log Scale") + local s = S.Demo_LogScale + if ImPlot3D.BeginPlot("Log Plot 3D", ImVec2(-1, 0)) then + ImPlot3D.SetupAxisScale(ImAxis3D.X, Scale.Log10) + ImPlot3D.SetupAxesLimits(0.1, 100, 0, 10, -1, 1) + ImPlot3D.PlotLine("f(x) = x", s.xs, s.xs, s.zs, 1001) + ImPlot3D.PlotLine("f(x) = sin(x)+1", s.xs, s.ys1, s.zs, 1001) + ImPlot3D.PlotLine("f(x) = log(x)", s.xs, s.ys2, s.zs, 1001) + ImPlot3D.PlotLine("f(x) = 10^x", s.xs, s.ys3, s.zs, 21) + ImPlot3D.EndPlot() + end + end + + S.Demo_SymmetricLogScale = { xs = {}, ys1 = {}, ys2 = {}, zs = {} } + for i = 1, 1001 do + local s, x = S.Demo_SymmetricLogScale, (i - 1) * 0.1 - 50 + s.xs[i], s.ys1[i], s.ys2[i], s.zs[i] = x, math.sin(x), (i - 1) * 0.002 - 1, 0.0 + end + function D.Demo_SymmetricLogScale() + IMGUI_DEMO_MARKER("Axes/Symmetric Log Scale") + local s = S.Demo_SymmetricLogScale + if ImPlot3D.BeginPlot("SymLog Plot", ImVec2(-1, 0)) then + ImPlot3D.SetupAxisScale(ImAxis3D.X, Scale.SymLog) + ImPlot3D.PlotLine("f(x) = a*x+b", s.xs, s.ys2, s.zs, 1001) + ImPlot3D.PlotLine("f(x) = sin(x)", s.xs, s.ys1, s.zs, 1001) + ImPlot3D.EndPlot() + end + end + + S.DemoTickLabels = { custom_fmt = true, custom_ticks = false, custom_labels = true } + local letters_ticks, letters_labels = { 0.0, 0.2, 0.4, 0.6, 0.8, 1.0 }, { "A", "B", "C", "D", "E", "F" } + function D.DemoTickLabels() + IMGUI_DEMO_MARKER("Axes/Tick Labels") + local s = S.DemoTickLabels + _, s.custom_fmt = ImGui.Checkbox("Show Custom Format", s.custom_fmt) + ImGui.SameLine() + _, s.custom_ticks = ImGui.Checkbox("Show Custom Ticks", s.custom_ticks) + if s.custom_ticks then + ImGui.SameLine() + _, s.custom_labels = ImGui.Checkbox("Show Custom Labels", s.custom_labels) + end + if ImPlot3D.BeginPlot("##Ticks") then + ImPlot3D.SetupAxesLimits(2, 5, 0, 1, 0, 1000) + if s.custom_fmt then + ImPlot3D.SetupAxisFormat(ImAxis3D.Y, MetricFormatter, "Hz") + ImPlot3D.SetupAxisFormat(ImAxis3D.Z, MetricFormatter, "m") + end + if s.custom_ticks then + local labels = (s.custom_labels and{letters_labels }or{nil +})[1] ImPlot3D.SetupAxisTicks(ImAxis3D.X, { 3.14 }, 1, s.custom_labels and{ "PI" } or nil, true) + ImPlot3D.SetupAxisTicks(ImAxis3D.Y, letters_ticks, 6, labels, false) + ImPlot3D.SetupAxisTicks(ImAxis3D.Z, 0, 1000, 6, labels, false) + end + ImPlot3D.EndPlot() + end + end + + S.DemoAxisConstraints = { limits = { -10, 10 }, zoom = { 1, 20 }, flags = 0 } + function D.DemoAxisConstraints() + IMGUI_DEMO_MARKER("Axes/Axis Constraints") + local s = S.DemoAxisConstraints + ImGui.DragFloat2("Limits Constraints", s.limits, 0.01) + ImGui.DragFloat2("Zoom Constraints", s.zoom, 0.01) + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DAxisFlags_PanStretch", AxisFlags.PanStretch) + if ImPlot3D.BeginPlot("##AxisConstraints", ImVec2(-1, 0)) then + ImPlot3D.SetupAxes("X", "Y", "Z", s.flags, s.flags, s.flags) + ImPlot3D.SetupAxesLimits(-1, 1, -1, 1, -1, 1) + for a = 0, 2 do + ImPlot3D.SetupAxisLimitsConstraints(a, s.limits[1], s.limits[2]) + ImPlot3D.SetupAxisZoomConstraints(a, s.zoom[1], s.zoom[2]) + end + ImPlot3D.EndPlot() + end + end + + S.DemoEqualAxes = { flags = Flags.Equal, cx = {}, cy = {}, cz = {}, hx = {}, hy = {}, hz = {} } + for i = 0, 359 do + local s, angle = S.DemoEqualAxes, i * 2 * IM_PI / 359.0 + s.cx[i + 1], s.cy[i + 1], s.cz[i + 1] = math.cos(angle), math.sin(angle), 0 -- Circle in XY plane at Z=0 + s.hx[i + 1], s.hy[i + 1], s.hz[i + 1] = 0.5 * math.cos(angle), 0.5 * math.sin(angle), i / 359.0 * 2.0 - 1.0 -- Helix + end + local square_xs, square_ys, square_zs = { -0.5, 0.5, 0.5, -0.5, -0.5 }, { -0.5, -0.5, 0.5, 0.5, -0.5 }, { -0.5, -0.5, -0.5, -0.5, -0.5 } + function D.DemoEqualAxes() + IMGUI_DEMO_MARKER("Axes/Equal Axes") + local s = S.DemoEqualAxes + ImGui.BulletText("Equal constraint applies to all three axes (X, Y, Z)") + ImGui.BulletText("When enabled, the axes maintain the same units/pixel ratio") + s.flags = CHECKBOX_FLAG(s.flags, "ImPlot3DFlags_Equal", Flags.Equal) + if ImPlot3D.BeginPlot("##EqualAxes", ImVec2(-1, 0), s.flags) then + ImPlot3D.SetupAxes("X-Axis", "Y-Axis", "Z-Axis") + ImPlot3D.PlotLine("Circle", s.cx, s.cy, s.cz, 360) + ImPlot3D.PlotLine("Helix", s.hx, s.hy, s.hz, 360) + ImPlot3D.PlotLine("Square", square_xs, square_ys, square_zs, 5) + ImPlot3D.EndPlot() + end + end + + S.DemoAutoFittingData = { xflags = AxisFlags.None, yflags = AxisFlags.None, zflags = AxisFlags.AutoFit, x = {}, y = {}, z = {} } + for i = 0, 100 do + local s = S.DemoAutoFittingData + s.x[i + 1], s.y[i + 1], s.z[i + 1] = i * 0.1, i * 0.1, 1 + math.sin(i / 10.0) + end + function D.DemoAutoFittingData() + IMGUI_DEMO_MARKER("Axes/Auto-Fitting Data") + local s = S.DemoAutoFittingData + ImGui.BulletText("Axes can be configured to auto-fit to data extents.") + ImGui.BulletText("Try panning and zooming to see the axes adjust.") + ImGui.BulletText("Disable AutoFit on an axis to fix its range.") + for _, a in __iter({ "x", "y", "z" }) do + ImGui.TextUnformatted(string.upper(a) .. ": ") + ImGui.SameLine() + _, s[a .. "flags"] = ImGui.CheckboxFlags("ImPlot3DAxisFlags_AutoFit##" .. string.upper(a), s[a .. "flags"], AxisFlags.AutoFit) + end + if ImPlot3D.BeginPlot("##AutoFitting") then + ImPlot3D.SetupAxes("X-Axis", "Y-Axis", "Z-Axis", s.xflags, s.yflags, s.zflags) + ImPlot3D.PlotLine("Wave", s.x, s.y, s.z, 101) + ImPlot3D.EndPlot() + end + end + + --------------------------------------------------------------------------- + -- [SECTION] Tools + --------------------------------------------------------------------------- + + local Plane = ImPlot3D.ImPlane3D + S.DemoMousePicking = { points = {}, rays = {}, selected_plane = Plane.XY, mask_plane = true } + function D.DemoMousePicking() + IMGUI_DEMO_MARKER("Tools/Mouse Picking") + local s = S.DemoMousePicking + ImGui.BulletText("Click anywhere in the plot to place points/rays.") + _, s.selected_plane = ImGui.RadioButton("XY-Plane", s.selected_plane, Plane.XY) + ImGui.SameLine() + _, s.selected_plane = ImGui.RadioButton("XZ-Plane", s.selected_plane, Plane.XZ) + ImGui.SameLine() + _, s.selected_plane = ImGui.RadioButton("YZ-Plane", s.selected_plane, Plane.YZ) + _, s.mask_plane = ImGui.Checkbox("Mask Plane", s.mask_plane) + if ImGui.Button("Clear") then + table.clear(s.points) + table.clear(s.rays) + end + if ImPlot3D.BeginPlot("Mouse Picking", ImVec2(-1, 0), Flags.NoClip) then + ImPlot3D.SetupAxes("X-Axis", "Y-Axis", "Z-Axis") + ImPlot3D.SetupAxesLimits(-1, 1, -1, 1, -1, 1) + -- Get mouse position and convert to ray / point on the selected plane + local mouse_pos = ImGui.GetMousePos() + local ray = ImPlot3D.PixelsToPlotRay(mouse_pos) + local point = ImPlot3D.PixelsToPlotPlane(mouse_pos, s.selected_plane, s.mask_plane) + -- Show intersection point + if ImGui.IsItemHovered() and not point:IsNaN() then + ImPlot3D.PlotScatter("##Intersection", { point.x }, { point.y }, { point.z }, 1, + { Marker = Marker.Circle, MarkerSize = 5, FillColor = ImVec4(1, 1, 0, 1) }) + end + -- Add point/ray on click + if ImGui.IsItemHovered() and ImGui.IsMouseClicked(0) and not point:IsNaN() then + table.insert(s.points, point) + table.insert(s.rays, ray) + end + -- [Port] ImVector + Stride = sizeof(ImPlot3DPoint) -> split x/y/z arrays + if #s.points > 0 then + local xs, ys, zs = {}, {}, {} + for i, p in __iter(s.points) do xs[i], ys[i], zs[i] = p.x, p.y, p.z end + ImPlot3D.PlotScatter("Placed Points", xs, ys, zs, #xs, { Marker = Marker.Circle, MarkerSize = 3 }) + -- Ray from added point to the camera + local rx, ry, rz = {}, {}, {} + for i, p in __iter(s.points) do + local d = s.rays[i].Direction + table.insert(rx, p.x); table.insert(ry, p.y); table.insert(rz, p.z) + table.insert(rx, p.x - d.x); table.insert(ry, p.y - d.y); table.insert(rz, p.z - d.z) + end + ImPlot3D.PlotLine("Placed Rays", rx, ry, rz, #rx, { Flags = LineFlags.Segments }) + end + ImPlot3D.EndPlot() + end + end + + --------------------------------------------------------------------------- + -- [SECTION] Custom + --------------------------------------------------------------------------- + + -- [Port] ImPlot3DStyle copy assignment (deep, into dst so GetStyle() references stay valid) + local function CopyStyle(dst, src) + for k, v in __iter(src) do + if k == "Colors" then + dst.Colors = dst.Colors or {} + for i, c in __iter(v) do dst.Colors[i] = ImVec4(c.x, c.y, c.z, c.w) end + elseif type(v) == "table" then + dst[k] = ImVec2(v.x, v.y) + else + dst[k] = v + end + end + return dst + end + + -- Example for Custom Styles section (MyImPlot3D::StyleSeaborn) + local function StyleSeaborn() + local style = ImPlot3D.GetStyle() + local colors, Col = style.Colors, ImPlot3D.ImPlot3DCol + colors[Col.FrameBg] = ImVec4(1.00, 1.00, 1.00, 1.00) + colors[Col.PlotBg] = ImVec4(0.92, 0.92, 0.95, 1.00) + colors[Col.PlotBorder] = ImVec4(0.00, 0.00, 0.00, 0.00) + colors[Col.LegendBg] = ImVec4(0.92, 0.92, 0.95, 1.00) + colors[Col.LegendBorder] = ImVec4(0.80, 0.81, 0.85, 1.00) + colors[Col.LegendText] = ImVec4(0.00, 0.00, 0.00, 1.00) + colors[Col.TitleText] = ImVec4(0.00, 0.00, 0.00, 1.00) + colors[Col.InlayText] = ImVec4(0.00, 0.00, 0.00, 1.00) + colors[Col.AxisText] = ImVec4(0.00, 0.00, 0.00, 1.00) + colors[Col.AxisGrid] = ImVec4(1.00, 1.00, 1.00, 1.00) + style.LineWeight = 1.5 + style.Marker = Marker.None + style.MarkerSize = 4 + style.FillAlpha = 1.0 + style.PlotPadding = ImVec2(12, 12) + style.LabelPadding = ImVec2(5, 5) + style.LegendPadding = ImVec2(5, 5) + style.PlotMinSize = ImVec2(300, 225) + end + ImPlot3D.StyleSeaborn = StyleSeaborn + + local seaborn = { xs = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, ys = table.create(10, 0), lin = { 8, 8, 9, 7, 8, 8, 8, 9, 7, 8 }, + dot = { 7, 6, 6, 7, 8, 5, 6, 5, 8, 7 } } + function D.DemoCustomStyles() + IMGUI_DEMO_MARKER("Custom/Custom Styles") + ImPlot3D.PushColormap(Colormap.Deep) + -- normally you wouldn't change the entire style each frame + local backup = CopyStyle({}, ImPlot3D.GetStyle()) + StyleSeaborn() + if ImPlot3D.BeginPlot("Seaborn Style") then + ImPlot3D.SetupAxes("X-axis", "Y-axis", "Z-axis") + ImPlot3D.SetupAxesLimits(-0.5, 9.5, -0.5, 0.5, 0, 10) + ImPlot3D.NextColormapColor() -- Skip blue + ImPlot3D.PlotLine("Line", seaborn.xs, seaborn.ys, seaborn.lin, 10) + ImPlot3D.NextColormapColor() -- Skip green + ImPlot3D.PlotScatter("Scatter", seaborn.xs, seaborn.ys, seaborn.dot, 10) + ImPlot3D.EndPlot() + end + CopyStyle(ImPlot3D.GetStyle(), backup) + ImPlot3D.PopColormap() + end + + local box_corners = { P(0, 0, 0), P(1, 0, 0), P(1, 1, 0), P(0, 1, 0), P(0, 0, 1), P(1, 0, 1), P(1, 1, 1), P(0, 1, 1) } + function D.DemoCustomRendering() + IMGUI_DEMO_MARKER("Custom/Custom Rendering") + if ImPlot3D.BeginPlot("##CustomRend") then + ImPlot3D.SetupAxesLimits(-0.1, 1.1, -0.1, 1.1, -0.1, 1.1) + local dl = ImPlot3D.GetPlotDrawList() + -- Draw circle + local cntr = ImPlot3D.PlotToPixels(P(0.5, 0.5, 0.5)) + dl:AddCircleFilled(cntr, 20, IM_COL32(255, 255, 0, 255), 20) + -- Draw box + local px = {} + for i = 1, 8 do px[i] = ImPlot3D.PlotToPixels(box_corners[i]) end + local col = IM_COL32(128, 0, 255, 255) + for i = 1, 4 do + local n = i % 4 + 1 + dl:AddLine(px[i], px[n], col) + dl:AddLine(px[i + 4], px[n + 4], col) + dl:AddLine(px[i], px[i + 4], col) + end + ImPlot3D.EndPlot() + end + end + + S.DemoCustomOverlay = {} + local gizmo_axes = { P(1, 0, 0), P(0, 1, 0), P(0, 0, 1) } + local gizmo_colors = { IM_COL32(200, 50, 50, 255), IM_COL32(50, 200, 50, 255), IM_COL32(50, 50, 200, 255) } + local gizmo_labels = { "X", "Y", "Z" } + function D.DemoCustomOverlay() + IMGUI_DEMO_MARKER("Custom/Custom Overlay") + local s = S.DemoCustomOverlay + ImGui.BulletText("Demonstrates custom 2D overlays using GetPlotRectPos/GetPlotRectSize.") + ImGui.BulletText("Shows mouse tooltip, line to closest point, and orientation gizmo.") + if s.xs == nil then + srand(0) + s.xs, s.ys, s.zs = {}, {}, {} + for i = 1, 50 do s.xs[i], s.ys[i], s.zs[i] = rand01(), rand01(), rand01() end + end + if ImPlot3D.BeginPlot("##CustomOverlay", ImVec2(-1, 0)) then + ImPlot3D.SetupAxes("X-Axis", "Y-Axis", "Z-Axis") + ImPlot3D.SetupAxesLimits(0, 1, 0, 1, 0, 1) + ImPlot3D.PlotScatter("Data", s.xs, s.ys, s.zs, 50) + local draw_list = ImPlot3D.GetPlotDrawList() + local mouse_pos = ImGui.GetMousePos() + local plot_pos, plot_size = ImPlot3D.GetPlotRectPos(), ImPlot3D.GetPlotRectSize() + if ImGui.IsItemHovered() then + -- Find closest point to mouse in screen space + local closest_idx, min_dist_sq, closest_px = -1, 1e10, nil + for i = 1, 50 do + local pp = ImPlot3D.PlotToPixels(s.xs[i], s.ys[i], s.zs[i]) + local dx, dy = pp.x - mouse_pos.x, pp.y - mouse_pos.y + if dx * dx + dy * dy < min_dist_sq then min_dist_sq, closest_idx, closest_px = dx * dx + dy * dy, i, pp end + end + if closest_idx >= 1 then + draw_list:AddLine(mouse_pos, closest_px, IM_COL32(255, 255, 0, 255), 2.0) + ImGui.BeginTooltip() + ImGui.Text("Mouse: (%.1f, %.1f)", mouse_pos.x, mouse_pos.y) + ImGui.Text("Closest Point #%d", closest_idx - 1) + ImGui.Text("Position: (%.3f, %.3f, %.3f)", s.xs[closest_idx], s.ys[closest_idx], s.zs[closest_idx]) + ImGui.Text("Distance: %.1f px", math.sqrt(min_dist_sq)) + ImGui.EndTooltip() + end + end + -- Draw orientation gizmo in bottom-right corner + local plot = ImPlot3D.internal.GetCurrentPlot() + if plot then + local gc = ImVec2(plot_pos.x + plot_size.x - 50, plot_pos.y + plot_size.y - 50) + local gizmo_size = 30.0 + draw_list:AddCircleFilled(gc, gizmo_size + 5, IM_COL32(0, 0, 0, 100)) + for i = 1, 3 do + local rotated = plot.Rotation * gizmo_axes[i] -- Rotate axis by quaternion + -- Project to 2D gizmo space (simple orthographic projection, Y flipped for screen coords) + local axis_end = ImVec2(gc.x + rotated.x * gizmo_size, gc.y - rotated.y * gizmo_size) + draw_list:AddLine(gc, axis_end, gizmo_colors[i], 2.0) + draw_list:AddCircleFilled(axis_end, 4.0, gizmo_colors[i]) + draw_list:AddText(ImVec2(axis_end.x + 8, axis_end.y - 8), gizmo_colors[i], gizmo_labels[i]) + end + end + ImPlot3D.EndPlot() + end + end + + S.DemoCustomPerPointStyle = { marker_size = 4.0, cmap = Colormap.Viridis } + local torus_labels = { "Height-colored", "Radial-colored", "Angular-colored" } + local torus_legend_colors = { ImVec4(1, 0, 0, 1), ImVec4(0, 1, 0, 1), ImVec4(0, 0, 1, 1) } + function D.DemoCustomPerPointStyle() + IMGUI_DEMO_MARKER("Custom/Custom Per-Point Style") + local s = S.DemoCustomPerPointStyle + ImGui.BulletText("Demonstrates per-point coloring using colormap sampling.") + ImGui.BulletText("A different color is sampled for each point.") + ImGui.BulletText("All points share the same label for a single legend entry.") + s.marker_size = ImGui.SliderFloat("Marker Size", s.marker_size, 2.0, 10.0) + if ImGui.BeginCombo("Colormap", ImPlot3D.GetColormapName(s.cmap)) then + local cd = ImPlot3D.GetCurrentContext().ColormapData + for i = 0, ImPlot3D.GetColormapCount() - 1 do + -- Only show continuous colormaps + if not cd:IsQual(i) and ImGui.Selectable(ImPlot3D.GetColormapName(i), s.cmap == i) then s.cmap = i end + end + ImGui.EndCombo() + end + -- Generate three stacked toruses with different color patterns (x, y, z, t per point) + if s.tori == nil then + s.tori = {} + local R, r = 0.6, 0.2 -- Major / minor radius + for torus = 1, 3 do + local z_offset = (3 - torus) * 0.6 + local d = { xs = {}, ys = {}, zs = {}, ts = {}, colors = {} } + for i = 0, 19 do + local u = i / 20 * 2 * IM_PI + for j = 0, 19 do + local v = j / 20 * 2 * IM_PI + local z = r * math.sin(v) + z_offset + local t + if torus == 1 then + t = (z - (z_offset - r)) / (2 * r) -- Color by height + elseif torus == 2 then + t = (math.cos(v) + 1) / 2 -- Color by radial distance from tube center + else + t = (math.cos(u) + 1) / 2 -- Angular pattern around the major circle + end + table.insert(d.xs, (R + r * math.cos(v)) * math.cos(u)) + table.insert(d.ys, (R + r * math.cos(v)) * math.sin(u)) + table.insert(d.zs, z) + table.insert(d.ts, t) + end + end + s.tori[torus] = d + end + end + for _, d in __iter(s.tori) do + for i = 1, 400 do d.colors[i] = ImGui.ColorConvertFloat4ToU32(ImPlot3D.SampleColormap(d.ts[i], s.cmap)) end + end + if ImPlot3D.BeginPlot("##PerPointStyle", ImVec2(-1, 0)) then + ImPlot3D.SetupAxes("X", "Y", "Z") + ImPlot3D.SetupAxesLimits(-1, 1, -1, 1, -0.5, 1.5) + for torus = 1, 3 do + local d = s.tori[torus] + ImPlot3D.PlotScatter(torus_labels[torus], d.xs, d.ys, d.zs, 400, + { Marker = Marker.Circle, MarkerSize = s.marker_size, MarkerFillColors = d.colors, MarkerLineColors = d.colors }) + -- Override legend color with PlotDummy + local c = torus_legend_colors[torus] + ImPlot3D.PlotDummy(torus_labels[torus], { Marker = Marker.Circle, MarkerSize = s.marker_size, MarkerFillColor = c, MarkerLineColor = c }) + end + ImPlot3D.EndPlot() + end + end + + --------------------------------------------------------------------------- + -- [SECTION] Config + --------------------------------------------------------------------------- + + S.DemoConfig = {} + function D.DemoConfig() + IMGUI_DEMO_MARKER("Config") + local s = S.DemoConfig + ImGui.ShowFontSelector("Font") + ImGui.ShowStyleSelector("ImGui Style") + ImPlot3D.ShowStyleSelector("ImPlot3D Style") + ImPlot3D.ShowColormapSelector("ImPlot3D Colormap") + ImGui.Separator() + -- Preview plot with 3D spirals + if ImPlot3D.BeginPlot("Preview", ImVec2(-1, 0)) then + if s.xs == nil then + s.xs, s.ys, s.zs = {}, {}, {} + for i = 1, 10 do + s.xs[i], s.ys[i], s.zs[i] = {}, {}, {} + for j = 1, 50 do + local angle = (j - 1) / 49 * 4 * IM_PI + local radius = 0.3 + (i - 1) * 0.05 + s.xs[i][j], s.ys[i][j], s.zs[i][j] = radius * math.cos(angle), radius * math.sin(angle), (i - 1) / 9 + end + end + end + for i = 1, 10 do + ImGui.PushID(i - 1) + ImPlot3D.PlotLine("##Spiral", s.xs[i], s.ys[i], s.zs[i], 50) + ImGui.PopID() + end + ImPlot3D.EndPlot() + end + end + + --------------------------------------------------------------------------- + -- [SECTION] Demo Window + --------------------------------------------------------------------------- + + local help_sections = { + { "Translation", { "Left-click drag to translate.", "If over axis, only that axis will translate.", + "If over plane, only that plane will translate.", "If outside plot area, translate in the view plane." } }, + { "Zoom", { "Scroll or middle-click drag to zoom.", "If over axis, only that axis will zoom.", + "If over plane, only that plane will zoom.", "If outside plot area, zoom the entire plot." } }, + { "Rotation", { "Right-click drag to rotate.", "To reset rotation, double right-click outside plot area.", + "To rotate to plane, double right-click when over the plane." } }, + { "Fit data", { "Double left-click to fit.", "If over axis, fit data to axis.", "If over plane, fit data to plane.", + "If outside plot area, fit data to plot." } }, + { "Context Menus", { "Right-click outside plot area to show full context menu.", "Right-click over legend to show legend context menu.", + "Right-click over axis to show axis context menu.", "Right-click over plane to show plane context menu." } }, + } + function D.DemoHelp() + IMGUI_DEMO_MARKER("Help") + ImGui.SeparatorText("ABOUT THIS DEMO:") + ImGui.BulletText("The other tabs are demonstrating many aspects of the library.") + ImGui.SeparatorText("PROGRAMMER GUIDE:") + ImGui.BulletText("See the ShowDemoWindow() code in ImPlot3DDemo.lua. <- you are here!") + ImGui.BulletText("See comments in ImPlot3DDemo.lua.") + ImGui.BulletText("See example application in examples/ folder.") + ImGui.SeparatorText("USER GUIDE:") + for _, sec in __iter(help_sections) do + ImGui.BulletText(sec[1]) + ImGui.Indent() + for _, line in __iter(sec[2]) do ImGui.BulletText(line) end + ImGui.Unindent() + end + ImGui.BulletText("Click legend label icons to show/hide plot items.") + end + + local function DemoHeader(label, demo) + if ImGui.TreeNodeEx(label) then + demo() + ImGui.TreePop() + end + end + + local demo_tabs = { + { "Plots", { + "Plot Types", { "Line Plots", D.DemoLinePlots }, { "Scatter Plots", D.DemoScatterPlots }, { "Triangle Plots", D.DemoTrianglePlots }, + { "Quad Plots", D.DemoQuadPlots }, { "Surface Plots", D.DemoSurfacePlots }, { "Mesh Plots", D.DemoMeshPlots }, + { "Realtime Plots", D.DemoRealtimePlots }, { "Image Plots", D.DemoImagePlots }, + "Plot Options", { "Plot Flags", D.DemoPlotFlags }, { "Offset and Stride", D.DemoOffsetAndStride }, + { "Legend Options", D.DemoLegendOptions }, { "Markers and Text", D.DemoMarkersAndText }, { "NaN Values", D.DemoNaNValues }, + { "Per-Index Colors", D.Demo_PerIndexColors } } }, + { "Axes", { { "Box Scale", D.DemoBoxScale }, { "Box Rotation", D.DemoBoxRotation }, { "Log Scale", D.Demo_LogScale }, + { "Symmetric Log Scale", D.Demo_SymmetricLogScale }, { "Tick Labels", D.DemoTickLabels }, { "Axis Constraints", D.DemoAxisConstraints }, + { "Equal Axes", D.DemoEqualAxes }, { "Auto-Fitting Data", D.DemoAutoFittingData } } }, + { "Tools", { { "Mouse Picking", D.DemoMousePicking } } }, + { "Custom", { { "Custom Styles", D.DemoCustomStyles }, { "Custom Rendering", D.DemoCustomRendering }, + { "Custom Overlay", D.DemoCustomOverlay }, { "Custom Per-Point Style", D.DemoCustomPerPointStyle } } }, + { "Config", D.DemoConfig }, + { "Help", D.DemoHelp }, + } + + function ImPlot3D.ShowAllDemos() + ImGui.Text("ImPlot3D says olá! (%s) (%d)", ImPlot3D.IMPLOT3D_VERSION, ImPlot3D.IMPLOT3D_VERSION_NUM) + ImGui.Spacing() + if ImGui.BeginTabBar("ImPlot3DDemoTabs") then + for _, tab in __iter(demo_tabs) do + if ImGui.BeginTabItem(tab[1]) then + if type(tab[2]) == "function" then + tab[2]() + else + for _, e in __iter(tab[2]) do + if type(e) == "string" then ImGui.SeparatorText(e) else DemoHeader(e[1], e[2]) end + end + end + ImGui.EndTabItem() + end + end + ImGui.EndTabBar() + end + end + + S.ShowDemoWindow = { show_implot3d_metrics = false, show_implot3d_style_editor = false, show_implot3d_about = false, + show_imgui_metrics = false, show_imgui_style_editor = false, show_imgui_demo = false } + + -- [Port] p_open: true/false/nil (nil = no close button). Returns the new p_open value. + function ImPlot3D.ShowDemoWindow(p_open) + local s = S.ShowDemoWindow + if s.show_implot3d_metrics then s.show_implot3d_metrics = ImPlot3D.ShowMetricsWindow(s.show_implot3d_metrics) end + if s.show_implot3d_style_editor then + s.show_implot3d_style_editor = ImGui.Begin("Style Editor (ImPlot3D)", s.show_implot3d_style_editor) + ImPlot3D.ShowStyleEditor() + ImGui.End() + end + if s.show_implot3d_about then s.show_implot3d_about = ImPlot3D.ShowAboutWindow(s.show_implot3d_about) end + if s.show_imgui_style_editor then + s.show_imgui_style_editor = ImGui.Begin("Style Editor (ImGui)", s.show_imgui_style_editor) + ImGui.ShowStyleEditor() + ImGui.End() + end + if s.show_imgui_metrics then s.show_imgui_metrics = ImGui.ShowMetricsWindow(s.show_imgui_metrics) end + if s.show_imgui_demo then s.show_imgui_demo = ImGui.ShowDemoWindow(s.show_imgui_demo) end + + ImGui.SetNextWindowPos(ImVec2(100, 100), G.ImGuiCond.FirstUseEver) + ImGui.SetNextWindowSize(ImVec2(600, 750), G.ImGuiCond.FirstUseEver) + p_open = ImGui.Begin("ImPlot3D Demo", p_open, G.ImGuiWindowFlags.MenuBar) + if ImGui.BeginMenuBar() then + if ImGui.BeginMenu("Tools") then + _, s.show_implot3d_metrics = ImGui.MenuItem("Metrics", nil, s.show_implot3d_metrics) + _, s.show_implot3d_style_editor = ImGui.MenuItem("Style Editor", nil, s.show_implot3d_style_editor) + _, s.show_implot3d_about = ImGui.MenuItem("About ImPlot3D", nil, s.show_implot3d_about) + ImGui.Separator() + _, s.show_imgui_metrics = ImGui.MenuItem("ImGui Metrics", nil, s.show_imgui_metrics) + _, s.show_imgui_style_editor = ImGui.MenuItem("ImGui Style Editor", nil, s.show_imgui_style_editor) + _, s.show_imgui_demo = ImGui.MenuItem("ImGui Demo", nil, s.show_imgui_demo) + ImGui.EndMenu() + end + ImGui.EndMenuBar() + end + ImPlot3D.ShowAllDemos() + ImGui.End() + return p_open + end + + --------------------------------------------------------------------------- + -- [SECTION] Style Editor + --------------------------------------------------------------------------- + + local internal = ImPlot3D.internal + local ImGuiCol, CEF = G.ImGuiCol, G.ImGuiColorEditFlags + + -- ColormapButton(label, size_arg, cmap) -> pressed + function ImPlot3D.ColormapButton(label, size_arg, cmap) + local style = ImGui.GetStyle() + local Window = ImGui.GetCurrentWindow() + if Window.SkipItems then return false end + local gp = ImPlot3D.GetCurrentContext() + cmap = internal.ResolveColormap(gp, cmap) + local keys, off = gp.ColormapData:GetKeys(cmap) + local pos = Window.DC.CursorPos + local label_size = ImGui.CalcTextSize(label, nil, true) + local size = ImGui.CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0, label_size.y + style.FramePadding.y * 2.0) + local rect = G.ImRect(pos.x, pos.y, pos.x + size.x, pos.y + size.y) + internal.RenderColorBar(keys, off, gp.ColormapData:GetKeyCount(cmap), ImGui.GetWindowDrawList(), rect, false, false, + not gp.ColormapData:IsQual(cmap)) + local text = internal.CalcTextColor(gp.ColormapData:LerpTable(cmap, style.ButtonTextAlign.x)) + ImGui.PushStyleColor(ImGuiCol.Button, G.IM_COL32_BLACK_TRANS) + ImGui.PushStyleColor(ImGuiCol.ButtonHovered, ImVec4(1, 1, 1, 0.1)) + ImGui.PushStyleColor(ImGuiCol.ButtonActive, ImVec4(1, 1, 1, 0.2)) + ImGui.PushStyleColor(ImGuiCol.Text, text) + ImGui.PushStyleVar(G.ImGuiStyleVar.FrameRounding, 0) + local pressed = ImGui.Button(label, size) + ImGui.PopStyleColor(4) + ImGui.PopStyleVar(1) + return pressed + end + + local function ColorsDiffer(a, b) return a.x ~= b.x or a.y ~= b.y or a.z ~= b.z or a.w ~= b.w end + local function V4(c) return ImVec4(c.x, c.y, c.z, c.w) end + + local SE = { init = true, flash_color_time = 0.5, flash_color_idx = nil, flash_color_backup = nil, output_dest = 0, + output_only_modified = true, alpha_flags = CEF.AlphaPreviewHalf, cmap_output_dest = 0, edit = false, qual = true } + + local function StyleEditorColors(style, ref) + local COUNT = ImPlot3D.ImPlot3DCol.COUNT + if ImGui.Button("Export") then + if SE.output_dest == 0 then ImGui.LogToClipboard() else ImGui.LogToTTY() end + ImGui.LogText("ImVec4* colors = ImPlot3D::GetStyle().Colors;\n") + for i = 0, COUNT - 1 do + local col, name = style.Colors[i], internal.GetStyleColorName(i) + if not SE.output_only_modified or ColorsDiffer(col, ref.Colors[i]) then + ImGui.LogText("colors[ImPlot3DCol_%s]%s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);\n", name, string.rep(" ", math.max(0, 15 - #name)), + col.x, col.y, col.z, col.w) + end + end + ImGui.LogFinish() + end + ImGui.SameLine(); ImGui.SetNextItemWidth(120) + SE.output_dest = ImGui.Combo("##output_type", SE.output_dest, "To Clipboard\0To TTY\0") + ImGui.SameLine() + _, SE.output_only_modified = ImGui.Checkbox("Only Modified Colors", SE.output_only_modified) + if SE.filter == nil then SE.filter = G.ImGuiTextFilter() end + ImGui.SetNextItemWidth(ImGui.GetFontSize() * 16) + SE.filter:Draw("Filter colors") + for _, e in __iter({ { "Opaque", CEF.AlphaOpaque }, { "Alpha", CEF.None }, { "Both", CEF.AlphaPreviewHalf } }) do + if ImGui.RadioButtonEx(e[1], SE.alpha_flags == e[2]) then SE.alpha_flags = e[2] end + ImGui.SameLine() + end + HelpMarker("In the color list:\nLeft-click on color square to open color picker,\nRight-click to open edit options menu.") + ImGui.Separator() + for i = 0, COUNT - 1 do + local name = internal.GetStyleColorName(i) + if SE.filter:PassFilter(name) then + ImGui.PushID(i) + -- Flash color + if ImGui.Button("?") then + if SE.flash_color_idx ~= nil then style.Colors[SE.flash_color_idx] = SE.flash_color_backup end + SE.flash_color_time, SE.flash_color_idx, SE.flash_color_backup = 0.5, i, V4(style.Colors[i]) + end + ImGui.SetItemTooltip("Flash given color to identify places where it is used.") + ImGui.SameLine() + -- Handle auto color selection + local is_auto = internal.IsColorAuto(style.Colors[i]) + if is_auto then ImGui.BeginDisabled() end + if ImGui.Button("Auto") then style.Colors[i] = ImPlot3D.IMPLOT3D_AUTO_COL() end + if is_auto then ImGui.EndDisabled() end + -- Color selection + ImGui.SameLine() + if ImGui.ColorEdit4("##Color", style.Colors[i], bor(CEF.NoInputs, SE.alpha_flags)) then + if style.Colors[i].w == -1 then style.Colors[i].w = 1 end + end + -- Save/Revert buttons if color changed + if ColorsDiffer(style.Colors[i], ref.Colors[i]) then + ImGui.SameLine() + if ImGui.Button("Save") then ref.Colors[i] = V4(style.Colors[i]) end + ImGui.SameLine() + if ImGui.Button("Revert") then style.Colors[i] = V4(ref.Colors[i]) end + end + ImGui.SameLine() + ImGui.TextUnformatted(name) + ImGui.PopID() + end + end + end + + local function StyleEditorColormaps(gp) + if ImGui.Button("Export", ImVec2(75, 0)) then + if SE.cmap_output_dest == 0 then ImGui.LogToClipboard() else ImGui.LogToTTY() end + local size = ImPlot3D.GetColormapSize() + local name = ImPlot3D.GetColormapName(gp.Style.Colormap) + ImGui.LogText("static const ImU32 %s_Data[%d] = {\n", name, size) + for i = 0, size - 1 do + ImGui.LogText(" %u%s\n", internal.GetColormapColorU32(i, gp.Style.Colormap), i == size - 1 and"" or",") + end + ImGui.LogText("};\nImPlotColormap %s = ImPlot::AddColormap(\"%s\", %s_Data, %d);", name, name, name, size) + ImGui.LogFinish() + end + ImGui.SameLine(); ImGui.SetNextItemWidth(120) + SE.cmap_output_dest = ImGui.Combo("##output_type", SE.cmap_output_dest, "To Clipboard\0To TTY\0") + ImGui.SameLine() + _, SE.edit = ImGui.Checkbox("Edit Mode", SE.edit) + -- built-in/added + ImGui.Separator() + local cd = gp.ColormapData + for i = 0, cd.Count - 1 do + ImGui.PushID(i) + local size = cd:GetKeyCount(i) + local selected = i == gp.Style.Colormap + if not selected then ImGui.PushStyleVar(G.ImGuiStyleVar.Alpha, 0.25) end + if ImGui.Button(ImPlot3D.GetColormapName(i), ImVec2(100, 0)) then + gp.Style.Colormap = i + internal.BustItemCache() + end + if not selected then ImGui.PopStyleVar() end + ImGui.SameLine() + ImGui.BeginGroup() + if SE.edit then + for c = 0, size - 1 do + ImGui.PushID(c) + local col4 = ImGui.ColorConvertU32ToFloat4(cd:GetKeyColor(i, c)) + if ImGui.ColorEdit4("", col4, CEF.NoInputs) then + cd:SetKeyColor(i, c, ImGui.ColorConvertFloat4ToU32(col4)) + internal.BustItemCache() + end + if (c + 1) % 12 ~= 0 and c ~= size - 1 then ImGui.SameLine() end + ImGui.PopID() + end + elseif ImPlot3D.ColormapButton("##", ImVec2(-1, 0), i) then + SE.edit = true + end + ImGui.EndGroup() + ImGui.PopID() + end + if SE.custom == nil then + SE.custom = { ImVec4(1, 0, 0, 1), ImVec4(0, 1, 0, 1), ImVec4(0, 0, 1, 1) } + SE.name = ImGui.NewTextBuffer("MyColormap", 16) + end + local custom = SE.custom + ImGui.Separator() + ImGui.BeginGroup() + local half = (100 - ImGui.GetStyle().ItemSpacing.x) / 2 + if ImGui.Button("+", ImVec2(half, 0)) then table.insert(custom, ImVec4(0, 0, 0, 1)) end + ImGui.SameLine() + if ImGui.Button("-", ImVec2(half, 0)) and #custom > 2 then table.remove(custom) end + ImGui.SetNextItemWidth(100) + ImGui.InputText("##Name", SE.name, 16, G.ImGuiInputTextFlags.CharsNoBlank) + _, SE.qual = ImGui.Checkbox("Qualitative", SE.qual) + local name = ImGui.TextBufferToString(SE.name) + if ImGui.Button("Add", ImVec2(100, 0)) and cd:GetIndex(name) == -1 then ImPlot3D.AddColormap(name, custom, #custom, SE.qual) end + ImGui.EndGroup() + ImGui.SameLine() + ImGui.BeginGroup() + for c = 1, #custom do + ImGui.PushID(c - 1) + ImGui.ColorEdit4("##Col1", custom[c], CEF.NoInputs) + if c % 12 ~= 0 then ImGui.SameLine() end + ImGui.PopID() + end + ImGui.EndGroup() + end + + -- [Port] ImPlot3DStyle* ref -> optional style table (defaults to internal saved copy) + function ImPlot3D.ShowStyleEditor(ref) + local gp = ImPlot3D.GetCurrentContext() + -- Handle style internal storage + local style = ImPlot3D.GetStyle() + if SE.init and ref == nil then SE.ref_saved_style = CopyStyle({}, style) end + SE.init = false + ref = ref or SE.ref_saved_style + -- Handle flash style color + if SE.flash_color_idx ~= nil then + local color = style.Colors[SE.flash_color_idx] + color.x, color.y, color.z = ImGui.ColorConvertHSVtoRGB(math.cos(SE.flash_color_time * 6.0) * 0.5 + 0.5, 0.5, 0.5) + color.w = 1.0 + -- Decrease timer until zero, then restore the backup color + SE.flash_color_time =SE.flash_color_time- ImGui.GetIO().DeltaTime + if SE.flash_color_time <= 0.0 then + style.Colors[SE.flash_color_idx] = SE.flash_color_backup + SE.flash_color_idx, SE.flash_color_time = nil, 0.5 + end + end + -- Style selector + if ImPlot3D.ShowStyleSelector("Colors##Selector") then CopyStyle(SE.ref_saved_style, style) end + -- Save/Revert button + if ImGui.Button("Save Ref") then + CopyStyle(ref, style) + CopyStyle(SE.ref_saved_style, style) + end + ImGui.SameLine() + if ImGui.Button("Revert Ref") then CopyStyle(style, ref) end + ImGui.SameLine() + HelpMarker("Save/Revert in local non-persistent storage. Default Colors definition are not affected. " + .. "Use \"Export\" below to save them somewhere.") + ImGui.Separator() + if ImGui.BeginTabBar("##Tabs", G.ImGuiTabBarFlags.None) then + if ImGui.BeginTabItem("Variables") then + ImGui.Text("Item Styling") + style.LineWeight = ImGui.SliderFloat("LineWeight", style.LineWeight, 0.0, 5.0, "%.1f") + style.MarkerSize = ImGui.SliderFloat("MarkerSize", style.MarkerSize, 2.0, 10.0, "%.1f") + style.FillAlpha = ImGui.SliderFloat("FillAlpha", style.FillAlpha, 0.0, 1.0, "%.2f") + ImGui.Text("Plot Styling") + ImGui.SliderFloat2("PlotDefaultSize", style.PlotDefaultSize, 0.0, 1000, "%.0f") + ImGui.SliderFloat2("PlotMinSize", style.PlotMinSize, 0.0, 300, "%.0f") + ImGui.SliderFloat2("PlotPadding", style.PlotPadding, 0.0, 20.0, "%.0f") + ImGui.SliderFloat2("LabelPadding", style.LabelPadding, 0.0, 20.0, "%.0f") + style.ViewScaleFactor = ImGui.SliderFloat("ViewScaleFactor", style.ViewScaleFactor, 0.1, 2.0, "%.2f") + ImGui.Text("Legend Styling") + ImGui.SliderFloat2("LegendPadding", style.LegendPadding, 0.0, 20.0, "%.0f") + ImGui.SliderFloat2("LegendInnerPadding", style.LegendInnerPadding, 0.0, 10.0, "%.0f") + ImGui.SliderFloat2("LegendSpacing", style.LegendSpacing, 0.0, 5.0, "%.0f") + ImGui.EndTabItem() + end + if ImGui.BeginTabItem("Colors") then + StyleEditorColors(style, ref) + ImGui.EndTabItem() + end + if ImGui.BeginTabItem("Colormaps") then + StyleEditorColormaps(gp) + ImGui.EndTabItem() + end + ImGui.EndTabBar() + end + end + + S.ShowAboutWindow = { show_config_info = false } + -- [Port] bool* p_open -> returns the new open state + function ImPlot3D.ShowAboutWindow(p_open) + local s = S.ShowAboutWindow + local visible + p_open, visible = ImGui.Begin("About ImPlot3D", p_open, G.ImGuiWindowFlags.AlwaysAutoResize) + if not visible then + ImGui.End() + return p_open + end + ImGui.Text("ImPlot3D %s (%d)", ImPlot3D.IMPLOT3D_VERSION, ImPlot3D.IMPLOT3D_VERSION_NUM) + ImGui.TextLinkOpenURL("Homepage", "https://github.com/brenocq/implot3d") + ImGui.SameLine() + ImGui.TextLinkOpenURL("Q&A", "https://github.com/brenocq/implot3d/discussions/categories/q-a") + ImGui.SameLine() + ImGui.TextLinkOpenURL("Releases", "https://github.com/brenocq/implot3d/releases") + ImGui.SameLine() + ImGui.TextLinkOpenURL("Sponsors", "https://github.com/sponsors/brenocq") + ImGui.Separator() + ImGui.Text("(c) 2024-2025 Breno Cunha Queiroz") + ImGui.Text("Developed by Breno Cunha Queiroz and all ImPlot3D contributors.") + ImGui.Text("ImPlot3D is licensed under the MIT License.") + ImGui.Text("If your company uses ImPlot3D, please consider sponsoring the project.") + _, s.show_config_info = ImGui.Checkbox("Config/Build Information", s.show_config_info) + if s.show_config_info then + local copy_to_clipboard = ImGui.Button("Copy to clipboard") + ImGui.BeginChild(ImGui.GetID("cfg_infos"), ImVec2(0, ImGui.GetTextLineHeightWithSpacing() * 18), G.ImGuiChildFlags.FrameStyle) + if copy_to_clipboard then + ImGui.LogToClipboard() + ImGui.LogText("```\n") + end + ImGui.Text("ImPlot3D %s (%d)", ImPlot3D.IMPLOT3D_VERSION, ImPlot3D.IMPLOT3D_VERSION_NUM) + ImGui.Separator() + -- [Port] C++ sizeof/compiler defines -> Luau runtime info + ImGui.Text("Luau port (imgui-luau), _VERSION: %s", _VERSION) + if copy_to_clipboard then + ImGui.LogText("```\n") + ImGui.LogFinish() + end + ImGui.EndChild() + end + ImGui.End() + return p_open + end + + return ImPlot3D.ShowDemoWindow +end diff --git a/tools/love.sh b/tools/love.sh new file mode 100755 index 0000000..06533f5 --- /dev/null +++ b/tools/love.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env sh +# Regenerates love/: Lua 5.1 (LÖVE/LuaJIT) copies of the Luau sources. Needs darklua + python3. +set -e +cd "$(dirname "$0")/.." +mkdir -p love +CFG=$(mktemp) +echo '{ "generator": "retain_lines", "rules": ["remove_types", "remove_compound_assignment", "remove_if_expression", "remove_continue", "remove_interpolated_string", "remove_floor_division"] }' > "$CFG" +for f in ImPlot3D.lua ImPlot3DDemo.lua; do + out="love/$(basename "$f")" + darklua process -c "$CFG" "$f" "$out" + python3 - "$out" <<'PY' +import re, sys +p = sys.argv[1]; src = open(p).read() +src = re.sub(r"^\s*@native\s*$", "", src, flags=re.M) +# Luau generalized iteration: for k, v in t do -> for k, v in __iter(t) do +src = re.sub(r"^([ \t]*for[ \t]+[\w][\w, \t]*[ \t]in[ \t]+)([^\n]*?)([ \t]+do\b)", r"\1__iter(\2)\3", src, flags=re.M) +head = ("-- GENERATED by tools/love.sh from the Luau source - do not edit\n" + "local function __iter(t, ...) if type(t) ~= 'table' or (getmetatable(t) and getmetatable(t).__call) then return t, ... end " + "local n, i, k = #t, 0, nil return function() if i < n then i = i + 1 return i, t[i] end " + "repeat k = next(t, k) until k == nil or type(k) ~= 'number' or k < 1 or k > n or k % 1 ~= 0 if k ~= nil then return k, t[k] end end end " + "table.create = table.create or function(n, v) local t = {} if v ~= nil then for i = 1, n do t[i] = v end end return t end " + "table.clone = table.clone or function(t) local c = {} for k, v in pairs(t) do c[k] = v end return setmetatable(c, getmetatable(t)) end " + "math.clamp = math.clamp or function(x, a, b) return math.max(a, math.min(b, x)) end " + "math.sign = math.sign or function(x) return x > 0 and 1 or (x < 0 and -1 or 0) end " + "math.round = math.round or function(x) return x >= 0 and math.floor(x + 0.5) or math.ceil(x - 0.5) end\n") +open(p, "w").write(head + src) +PY +done +rm -f "$CFG"