From c2d19ce212782f5486a995048e9571d978cca380 Mon Sep 17 00:00:00 2001 From: David Date: Sun, 29 Nov 2026 15:49:02 +0100 Subject: [PATCH] vismach: unify static/HAL classes, add mixed expressions & two-pass transparency Consolidate static and HAL-driven Vismach primitives and transforms into unified classes backed by pre-compiled bytecode/attribute evaluators, multi-source expression support, and automatic two-pass transparency. Key changes: - Unified classes & aliases: Merge static (Translate, Rotate, Scale, Box, CylinderX/Y/Z, Sphere, TriangleXY/XZ/YZ, ArcX, AsciiSTL, AsciiOBJ) and Hal* classes into single implementations while retaining all Hal* names as aliases. - Multi-source expressions & optional prefixes: Add ArgsBase with one-time caller-scope prefix caching for hal.component, hal module, and linuxcnc.stat. Support "prefix.attr" dot notation, "{prefix.attr}" math expressions, and zero-overhead static numeric fast-paths. - Single stat.poll() per cycle: Register linuxcnc.stat instances across scene objects and user callbacks (main(..., function=...)) via poll_all_stats() so status is polled once per update cycle/redraw. - Two-pass alpha transparency & Color glow: Extend Color to support (parts, color, glow=0), dynamic RGBA expressions, emission glow, and opaque-first / transparent-second traversal with back-face culling for 0.0 < alpha < 1.0 (preserving legacy [R, G, B, 0] opaque parts). - Dynamic mesh loading: Add path support and dynamic filename/path expressions to AsciiSTL and AsciiOBJ, freeing old OpenGL display lists with glDeleteLists() on reload. - Upgraded Hud: Support linuxcnc.stat, mixed/conditional expressions, multi-value tuple unpacking in format strings, dynamic HUD colors, and non-crashing Vismach HUD Warning diagnostics. - Bug fixes & math cleanup: Fix CylinderY dynamic initialization, HalGrid prefix handling, Python 3 floor division in O.redraw() backplot trimming, uncaptured Capture() guards, and replace copy.deepcopy() in invert() with scale-safe tuple unpacking. - Backwards compatibility: Retain CoordsBase, legacy Color(color, parts) order, zero-arg coords()/get_values() subclass overrides, and dummy single-arg primitive calls (e.g., TriangleXZ(0)). --- docs/src/gui/vismach.adoc | 1498 +++++++++++++++---- lib/python/vismach.py | 2883 ++++++++++++++++++++++++------------- 2 files changed, 3097 insertions(+), 1284 deletions(-) diff --git a/docs/src/gui/vismach.adoc b/docs/src/gui/vismach.adoc index f67066b08a7..4962697eb4a 100644 --- a/docs/src/gui/vismach.adoc +++ b/docs/src/gui/vismach.adoc @@ -1,307 +1,1237 @@ -:lang: en -:toc: += Vismach Class Reference & Call Signatures +:toc: left +:toclevels: 3 +:source-highlighter: highlight.js -[[cha:vismach]] -= Vismach +== General Rules -Vismach is a set of Python functions that can be used to create and -animate models of machines. Vismach displays the model in a 3D viewport -and the model parts are animated as the values of associated HAL pins -change. +* **Optional Prefixes:** The `prefix` argument (`c`, `s`, `hal`, `None`, or a `dict`) can be omitted on all classes whenever attributes are passed in `"prefix.attr"` notation or as math expressions such as `"-{c.var1}+{s.var2}"`. +* **Static Fast-Path:** When only static numeric values are passed without a prefix, classes bypass `ArgsBase` entirely and run with zero runtime evaluation overhead. +* **Backwards Compatibility:** All legacy `Hal...` class names (e.g., `HalTranslate`, `HalBox`, `HalAsciiSTL`, `HalColor`) remain available as aliases and continue to support the traditional single-prefix signature. +* **Legacy Subclass & Custom `coords()` / `get_values()` Support:** + * Multi-argument geometry primitives (`Box`, `CylinderZ`/`Y`/`X`, `Sphere`, `TriangleXY`/`XZ`/`YZ`, `ArcX`) accept 0 or 1 dummy argument (such as `HalToolCylinder(c)` or `TriangleXZ(0)`), while `BoxCentered`, `BoxCenteredXY`, `Show`, and transforms (`Translate`, `Rotate`, `Scale`) accept 0 coordinate arguments for legacy subclasses that override `coords(self)`. + * Custom primitives subclassing `CoordsBase` (such as `HexPrismZ`) remain supported with automatic prefix stripping and `self.q` quadric initialization. + * Subclasses of `VectorRotate` / `VectorRotate` that override `get_values(self)` (such as `HalRotateNutation`) are detected and evaluated automatically. -image::images/vismach.png["Vismach displays the model in a 3D viewport",align="center"] +== Math & Conditional Expressions -The Vismach viewport view can be manipulated as follows: +Any string argument in a Vismach transform, geometry primitive, mesh loader, `Color` node, or `Hud` method can contain Python arithmetic, trigonometry, comparison, or conditional expressions. At initialization, `ArgsBase` replaces each `{prefix.attr}` placeholder with a fast getter call and compiles the expression into native Python bytecode (`compile(..., "", "eval")`). -* *zoom* by scroll wheel or right button drag, -* *pan* by left button drag, -* *rotate* by middle-button drag or shift-drag. +=== 1. Syntax Rules -A Vismach model takes the form of a Python script and can use standard -Python syntax. This means that there is more than one way to lay out the -script, but in the examples given in this document I will use the -simplest and most basic of them. +* **Wrap every pin or status attribute in `{...}`:** Whenever you combine a pin or status attribute with numbers, operators, math functions, or other attributes, enclose each source token in curly braces (for example, `"-{c.offset_z}"` or `"{s.g5x_offset[0]} + {s.g92_offset[0]}"`). +* **Single-source vs. multi-source expressions:** + * When `prefix` is omitted, include the source variable name inside the braces (`"{c.pin_a} + {s.attr_b}"`). + * When an explicit `prefix` is passed (for example, `HalCylinderZ(c, "-{pivot-z} + 200", 140, 100, 140)`), omit the variable prefix inside the braces (`"{pivot-z}"`). +* **Sandboxed math & conversion namespace:** Expressions execute with `__builtins__` disabled for safety and include a whitelisted set of standard math and conversion functions: + * **General & Conversions:** `abs`, `min`, `max`, `round`, `str`, `int`, `float`, `bool` + * **Trigonometry & Geometry:** `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `hypot`, `sqrt`, `radians`, `degrees`, `pi` -The basic sequence in creating the Vismach model is -* Create the HAL pins that control the motion. -* Create the parts. -* Define how they move. -* Assemble into movement groups. +=== 2. Supported Operations & Examples -== Start the script +==== Arithmetic, Scaling & Trigonometry -It is useful for testing to include the '#!/usr/bin/env python3' to -allow the file to be run as a script. The first thing to do is to import -the required libraries. +Use standard Python math operators and whitelisted trig/math functions to negate pins, compute nutating or rotary projections, clamp values, or combine multiple axes: [source,python] ---- -#!/usr/bin/env python3 +# Negate a HAL pin and add a fixed offset +spindle_cyl = CylinderZ("-{c.pivot-z} + 200", 140, 100, 140) -from vismach import * -import hal -import math -import sys +# Compute rotary axis projection directly using sin/cos/radians +nutation_y = VectorRotate( + [head], + "hal.joint.3.pos-fb", + 1.0, + 0, + "sin(radians({c.nutation_angle}))", + "cos(radians({c.nutation_angle}))", +) + +# Clamp transparency alpha safely between 0.1 and 1.0 +work_piece = Color([0.5, 0.5, 0.5, "max(0.1, min(1.0, {c.scale-coords}))"], [work_piece]) + +# Combine a HAL component pin with a linuxcnc.stat tuple element +part = Translate([part], 1, "-{c.scale_coords} + {s.g5x_offset[0]}", 0, 0) +---- + +==== Comparisons & Boolean Logic (`==`, `!=`, `<`, `<=`, `>`, `>=`, `and`, `or`, `not`) + +Comparison and boolean expressions evaluate to `True` (`1`) or `False` (`0`), making them ideal for `Show(...)`, `Hud(showme=...)`, and `Hud.hide_all(...)`: + +[source,python] +---- +# Show control point when either TCP kinematics (kins-type == 0) or G68 work plane is active +tcp_ctrl_pt = Show([tcp_ctrl_pt], 1, "({hal.motion.kins-type} == 0) or ({s.g68_active} > 0)") + +# Hide HUD whenever the spindle body is hidden +myhud = Hud(showme="not {c.hide-spindle-body}") + +# Hide HUD during estop or MDI mode +myhud.hide_all("{s.estop} or ({s.task_mode} == 2)") +---- + +==== Inline Conditional Expressions (`A if condition else B`) + +Use Python ternary expressions to guard against zero values, clamp ranges, or switch text labels dynamically in `Hud.add_pin()`: + +[source,python] +---- +# Fallback to a default radius of 2.0 when tool diameter is 0 +tool_cyl = CylinderZ( + "-{c.tool_length}", + "{c.tool_diameter} / 2 if {c.tool_diameter} > 0 else 2", + 0, + "{c.tool_diameter} / 2 if {c.tool_diameter} > 0 else 2", +) + +# Guard against division by zero +ratio_line = myhud.add_pin("Ratio: {:.2f}", "{c.num} / {c.den} if {c.den} != 0 else 0") + +# Switch text string dynamically in the HUD +myhud.add_pin("Kins Mode: {}", "'TCP' if {hal.motion.kins-type} == 0 else 'WORLD'") +---- + +==== Tuple Expressions for Multi-Placeholder `Hud` Lines + +In `Hud.add_pin()`, separating multiple expressions with commas produces a Python tuple that is automatically unpacked into `string.format(*val)`: + +[source,python] +---- +myhud.add_pin( + "TWP Origin: {:7.2f}, {:7.2f}, {:7.2f}", + "{s.g68_offset[0]}, {s.g68_offset[1]}, {s.g68_offset[2]}", +) +---- + +== Working with HAL (`hal` Module & `hal.component`) + +Vismach supports two ways of connecting scene geometry, transforms, and HUD elements to LinuxCNC's Hardware Abstraction Layer (HAL): + +1. **Custom Vismach HAL Component (`hal.component`):** Pins created by your GUI script (for example, `c = hal.component("...")` or `mycomp = hal.component("...")`). +2. **Global HAL Namespace (`hal` module):** Any existing HAL pin in the running LinuxCNC system (such as `joint.0.pos-fb`, `motion.kins-type`, or `halui.tool.diameter`). + +=== 1. Using the `hal` Module Prefix + +You can reference any system-wide HAL pin either by omitting the `prefix` argument and using `"hal."` notation, or by passing the `hal` module explicitly as the `prefix` argument. + +* **Prefix-omitted dot notation (recommended for mixed expressions):** ++ +[source,python] +---- +# Direct pin lookup +axis_x = Translate([spindle], 1, 0, 0, "hal.joint.0.pos-fb") + +# Mixed expression combining hal module pins, custom component pins, and linuxcnc.stat +tool_cyl = CylinderZ( + "-{hal.motion.tooloffset.z}", + "{hal.halui.tool.diameter}/2", + 0, + "{hal.halui.tool.diameter}/2", +) +---- + +* **Explicit `hal` prefix (legacy single-source style):** ++ +[source,python] +---- +axis_x = HalTranslate([spindle], hal, 1, "joint.0.pos-fb", 0, 0, 1) +---- + +[IMPORTANT] +==== +When using `"hal."` or `"{hal.}"` without passing `prefix=hal` explicitly, ensure `import hal` is present in the caller's scope where the Vismach object is instantiated so `ArgsBase` can resolve `hal` automatically. +==== + +=== 2. Using a `hal.component` Instance (Any Variable Name) + +You can assign your `hal.component(...)` instance to **any valid Python variable name**—such as `c`, `mycomp`, `gui`, or `spindle_comp`—and even mix multiple HAL components in the same expression. `ArgsBase` dynamically resolves whatever variable name appears before the dot (`.`) in your string or expression from the caller's scope. + +[NOTE] +==== +The prefix in your string (`"mycomp.pivot-z"` or `"{mycomp.pivot-z}"`) must match the **Python variable name** in your script (`mycomp`), not the internal HAL component name string (`"mazak-integrex-gui"`). +==== + +[source,python] +---- +mycomp = hal.component("mazak-integrex-gui") +mycomp.newpin("pivot-z", hal.Type.REAL, hal.HAL_IN) +mycomp.newpin("offset-x", hal.Type.REAL, hal.HAL_IN) +mycomp.ready() + +# Optional second HAL component +aux_comp = hal.component("aux-offsets") +aux_comp.newpin("trim-x", hal.Type.REAL, hal.HAL_IN) +aux_comp.ready() + +# Prefix-omitted expression using 'mycomp' and combining two HAL components +spindle = Translate([spindle], 1, "{mycomp.offset-x} + {aux_comp.trim-x}", 0, "-{mycomp.pivot-z}") + +# Explicit component prefix (legacy style) +spindle = HalTranslate([spindle], mycomp, -1, "pivot-z", 0, 0, 1) +---- + +=== 3. HAL Pins in `Hud` Methods + +In `Hud` (`add_pin`, `show_tag_if_same`, `show_tags_in_pin`, and `hide_all`), HAL pins are resolved using the following rules: + +* **Dot or brace notation (`"hal.joint.0.pos-fb"`, `"mycomp.my-pin"`, `"{hal.motion.kins-type}"`):** Resolved automatically from the caller's scope without needing `prefix=...`. +* **Legacy full HAL pin names (`"my-gui.pin_name"`):** When `prefix` is omitted and the substring before the first dot matches a ready HAL component (`hal.component_is_ready(...)`), `Hud` binds the pin directly via `hal`. +* **Bare pin name without dots or braces (`"my-pin"`):** Defaults to `prefix=hal` if `prefix` is omitted, or uses the explicit `prefix` argument (`prefix=mycomp` or `prefix=hal`). + +[source,python] +---- +# System HAL pin using dot notation +myhud.add_pin("Joint 0: {:8.3f}", "hal.joint.0.pos-fb") + +# Custom component variable name +myhud.add_pin("Pivot Z: {:8.3f}", "mycomp.pivot-z") + +# Conditional expression combining hal and linuxcnc.stat +myhud.add_pin( + "Kins Mode: {}", + "'TCP' if {hal.motion.kins-type} == 0 else 'WORLD'", +) + +# Legacy explicit prefix +myhud.add_pin("Pivot Z: {:8.3f}", "pivot-z", prefix=mycomp) +---- +== Working with `linuxcnc.stat` + +Vismach allows you to bind transforms, geometry primitives, meshes, and `Hud` lines directly to attributes of a `linuxcnc.stat()` channel (such as `g5x_offset`, `g92_offset`, `g68_active`, `g68_offset`, `g68_rotation`, `tool_in_spindle`, `feedrate`, or `estop`). + +=== 1. Setting Up `linuxcnc.stat` + +Create a `linuxcnc.stat()` instance in your script (typically named `s`, or any valid Python variable name such as `stat`) **before** instantiating Vismach objects: + +[source,python] +---- +import linuxcnc + +s = linuxcnc.stat() +---- + +[NOTE] +==== +You do **not** need to call `s.poll()` manually inside your scene definitions or periodic `function=` callback. Every `linuxcnc.stat` instance referenced by any Vismach object, `Hud` item, or user callback is automatically registered and polled **once per update cycle** (and immediately during mouse camera redraws) via `poll_all_stats()`. +==== + +=== 2. Referencing `linuxcnc.stat` Attributes + +You can reference status attributes either with prefix-omitted dot/brace notation (`"s."` / `"{s.}"`) or by passing `s` explicitly as the `prefix` argument. + +* **Scalar attributes (compiled with `operator.attrgetter`):** ++ +[source,python] +---- +# Show/hide branch based on active G68 tilted work plane +work_plane = Show([work_plane], 1, "s.g68_active") + +# Load tool STL dynamically from tool_in_spindle +tool_mesh = AsciiSTL("s.tool_in_spindle", path="tools/") + +# Display feedrate in HUD +hud.add_pin("Feedrate: {:7.1f}", "s.feedrate") +---- + +* **Tuple and dictionary attributes (always specify an index):** + Many `linuxcnc.stat` fields (such as `g5x_offset`, `g92_offset`, `g68_offset`, `g68_rotation`, `actual_position`, or `joint`) are 9-element tuples or dictionaries. Always include the element index (`[0]`, `[1]`, `[2]`, etc.) when passing them to coordinate or math expressions. ++ +[source,python] +---- +# Combine G5x and G92 work offsets in a single VectorTranslate +work_plane = VectorTranslate( + [work_plane], + "{s.g5x_offset[0]} + {s.g92_offset[0]}", + "{s.g5x_offset[1]} + {s.g92_offset[1]}", + "{s.g5x_offset[2]} + {s.g92_offset[2]}", +) + +# Display G68 origin vector on a single HUD line +hud.add_pin( + "TWP Origin: {:7.2f}, {:7.2f}, {:7.2f}", + "{s.g68_offset[0]}, {s.g68_offset[1]}, {s.g68_offset[2]}", +) +---- + +* **Explicit `s` prefix (legacy single-source style):** ++ +[source,python] +---- +work_coords = VectorTranslate([work_coords], s, "g5x_offset[0]", "g5x_offset[1]", "g5x_offset[2]") +hud.add_pin("Active Tool: {:d}", "tool_in_spindle", prefix=s) +---- + +=== 3. Mixing `linuxcnc.stat` with HAL Pins + +Because `ArgsBase` resolves each `{prefix.attr}` token independently, you can combine `linuxcnc.stat` attributes, `hal.component` pins, and `hal` module pins in a single expression: + +[source,python] +---- +# Combine HAL component scale factor with linuxcnc.stat work offset +part = Translate([part], 1, "-{c.scale_coords} + {s.g5x_offset[0]}", 0, 0) + +# Combine hal.motion.kins-type and s.g68_active in a visibility condition +tcp_ctrl_pt = Show([tcp_ctrl_pt], 1, "({hal.motion.kins-type} + {s.g68_active}) > 0") +---- + + +== Transformations & Visibility + +=== Translate / HalTranslate + +Moves child parts along the X, Y, and Z axes. Supports fixed offsets, single-prefix pins/attributes, or a scaling multiplier `var` combined with mixed-prefix math expressions. + +* `Translate(parts, x, y, z)` ++ +[source,python] +---- +Translate([part], 30, 25, -170) +---- + +* `Translate(parts, prefix, x, y, z)` ++ +[source,python] +---- +Translate([part], s, "g5x_offset[0]", "g5x_offset[1]", 0) +---- + +* `Translate(parts, var, x, y, z)` ++ +[source,python] +---- +Translate([part], 1, "-{c.scale_coords}+{s.g5x_offset[0]}", "s.g68_offset[1]", 0) +---- + +* `Translate(parts, prefix, var, x, y, z)` ++ +[source,python] +---- +HalTranslate([part], s, 1, "g68_offset[0]", "g68_offset[1]", "g68_offset[2]") +---- + +=== Rotate / HalRotate + +Rotates child parts by angle `th` (in degrees) around the axis vector `(x, y, z)`. Optionally accepts a multiplier `var` to scale the rotation angle dynamically. + +* `Rotate(parts, th, x, y, z)` ++ +[source,python] +---- +Rotate([spindle], 90, 0, 1, 0) +---- + +* `Rotate(parts, prefix, th, x, y, z)` ++ +[source,python] +---- +Rotate([spindle], c, "spindle_angle", 0, 0, 1) +---- + +* `Rotate(parts, var, th, x, y, z)` ++ +[source,python] +---- +Rotate([head], "c.angle-y-yt", 1, 0, 0, 1) +---- + +* `Rotate(parts, prefix, var, th, x, y, z)` ++ +[source,python] +---- +HalRotate([head], c, "angle-y-yt", 1, 0, 0, 1) +---- + +=== RotateEuler + +Applies three sequential Euler rotations (`th1`, `th2`, `th3` in degrees) according to the specified axis rotation `order` (such as `123` for X-Y-Z or `321` for Z-Y-X). + +* `RotateEuler(parts, th1, th2, th3, order=123)` ++ +[source,python] +---- +RotateEuler([head], "{c.rot_x}+{s.g68_rot}", "s.joint[0]['output']", 0, order=321) +---- + +* `RotateEuler(parts, prefix, th1, th2, th3, order=123)` ++ +[source,python] +---- +RotateEuler([head], c, "rot_x", "rot_y", "rot_z", order=123) +---- + +=== Scale / HalScale + +Scales child parts along the X, Y, and Z axes. Accepts an optional uniform multiplier `var` that scales all three axes together. + +* `Scale(parts, x, y, z)` ++ +[source,python] +---- +Scale([part], 1.0, 1.0, 2.0) +---- + +* `Scale(parts, prefix, x, y, z)` ++ +[source,python] +---- +Scale([part], c, 1.0, 1.0, "z_scale") +---- + +* `Scale(parts, x, y, z, var)` ++ +[source,python] +---- +Scale([abs_coords], 1, 1, 1, "c.scale-coords") +---- + +* `Scale(parts, prefix, x, y, z, var)` ++ +[source,python] +---- +HalScale([abs_coords], c, 1, 1, 1, "scale-coords") +---- + +=== Show + +Toggles the visibility or scale of child parts by applying `scaleby_true` when `const == var`, and `scaleby_false` (default `0`, hidden) otherwise. + +* `Show(parts, const, var, scaleby_true=1, scaleby_false=0)` ++ +[source,python] +---- +Show([tool_tip], 1, "c.tool_selected", scaleby_true="{s.feed_override}", scaleby_false=0) +---- + +* `Show(parts, prefix, const, var, scaleby_true=1, scaleby_false=0)` ++ +[source,python] +---- +Show([tool_tip], c, 1, "tool_selected") +---- + +=== VectorTranslate + +Translates child parts along a dynamic vector `(xvar, yvar, zvar)` multiplied by `scale` (use `scale=-1` to invert the direction). + +* `VectorTranslate(parts, xvar, yvar, zvar, scale=1)` ++ +[source,python] +---- +VectorTranslate([part], "-{c.scale_x}+{s.g5x_offset[0]}", "s.g5x_offset[1]", 0, scale=-1) +---- + +* `VectorTranslate(parts, prefix, xvar, yvar, zvar, scale=1)` ++ +[source,python] +---- +VectorTranslate([part], s, "g5x_offset[0]", "g5x_offset[1]", "g5x_offset[2]", scale=-1) +---- + +=== VectorRotate + +Rotates child parts around the axis `(x, y, z)` by an angle equal to `th * var`, making it ideal for gearing ratios or unit conversions. + +* `VectorRotate(parts, var, th, x, y, z)` ++ +[source,python] +---- +VectorRotate([part], "{c.rot_angle}+{s.spindle_pos}", 1, 0, 0, 1) +---- + +* `VectorRotate(parts, prefix, var, th, x, y, z)` ++ +[source,python] +---- +VectorRotate([part], c, "rot_angle", 1, 0, 0, 1) +---- + +== Scene Hierarchy + +=== Collection + +Groups multiple Vismach parts, transforms, and `Capture()` nodes into a single drawable branch. + +When `traverse()` is invoked at the root of the scene, `Collection` automatically executes a **two-pass render**: + +1. **Opaque pass (`alpha >= 1.0`):** Traverses the scene hierarchy, updates `Capture()` matrices, and renders all solid parts first. +2. **Transparent pass (`alpha < 1.0`):** Re-traverses active transforms and renders all transparent `Color` branches afterward so solid geometry behind them is always visible—regardless of where transparent parts are nested in the hierarchy. + +* `Collection(parts)` ++ +[source,python] +---- +machine = Collection([base, table, spindle_head, work_piece]) +---- + +== Color & Material + +=== Color + +Sets the OpenGL diffuse/ambient RGBA material color and optional yellow emission (`glow=1`) for child parts. Supports live expressions inside the `[R, G, B, A]` list and `glow` flag. + +When `0.0 < A < 1.0`, `Collection.traverse()` automatically defers the branch to the transparent pass, enables OpenGL alpha blending (`GL_SRC_ALPHA`, `GL_ONE_MINUS_SRC_ALPHA`), pauses depth-buffer writing (`glDepthMask(GL_FALSE)`), and enables back-face culling (`GL_CULL_FACE` / `GL_BACK`) to prevent overlapping internal triangles on closed meshes. + +[NOTE] +==== +Legacy Vismach models often specify `[R, G, B, 0]` (with `A = 0`) for solid parts because older versions ignored the alpha channel. To keep legacy models opaque, `A == 0` and `A >= 1.0` both render in the opaque pass; use `0.0 < A < 1.0` (e.g., `0.1` to `0.9`) for translucent parts. +==== + +[TIP] +==== +You do not need to move transparent parts to the end of your root `Collection`. If multiple transparent shells overlap (such as an inner transparent workpiece inside an outer transparent enclosure), list the inner transparent parts before the outer transparent parts so the outer layer blends over the inner one. +==== + +* `Color(parts, color, glow=0)` ++ +[source,python] +---- +Color([spindle], ["{c.red_val}", 0.2, 0.2, 1.0], glow="s.paused") +---- + +* `Color(color, parts, glow=0)` _(Legacy argument order)_ ++ +[source,python] +---- +Color([0.5, 0.5, 0.5, "c.scale-coords"], [work_piece]) +---- + +* `Color(parts, prefix, color, glow=0)` ++ +[source,python] +---- +Color([spindle], c, ["red_val", 0.2, 0.2, 1.0], glow=1) +---- + + + +== Geometry Primitives + +=== Box / HalBox + +Draws a solid rectangular box defined by two opposite corner coordinates `(x1, y1, z1)` and `(x2, y2, z2)`. + +* `Box(x1, y1, z1, x2, y2, z2)` ++ +[source,python] +---- +Box(-10, -10, 0, 10, 10, "s.tool_offset[2]") +---- + +* `Box(prefix, x1, y1, z1, x2, y2, z2)` ++ +[source,python] +---- +HalBox(c, 0, 0, 0, "box_x", "box_y", "box_z") +---- + +=== BoxCentered / HalBoxCentered + +Draws a solid rectangular box with widths `(xw, yw, zw)` centered symmetrically around the local origin `(0, 0, 0)`. + +* `BoxCentered(xw, yw, zw)` ++ +[source,python] +---- +BoxCentered("{c.table_x}", "{c.table_y}", 20) +---- + +* `BoxCentered(prefix, xw, yw, zw)` ++ +[source,python] +---- +HalBoxCentered(c, "width_x", "width_y", 20) +---- + +=== BoxCenteredXY / HalBoxCenteredXY + +Draws a solid rectangular box centered in X and Y (`-xw/2` to `+xw/2`, `-yw/2` to `+yw/2`) extending along Z from `0` to `zw`. + +* `BoxCenteredXY(xw, yw, zw)` ++ +[source,python] +---- +BoxCenteredXY(50, 50, "-{c.base_z}+{s.g5x_offset[2]}") +---- + +* `BoxCenteredXY(prefix, xw, yw, zw)` ++ +[source,python] +---- +HalBoxCenteredXY(s, 50, 50, "tool_offset[2]") +---- + +=== CylinderZ / HalCylinderZ + +Draws a capped cylinder or conical frustum aligned along the Z axis from `z_start` (radius `r_start`) to `z_end` (radius `r_end`). + +* `CylinderZ(z_start, r_start, z_end, r_end)` ++ +[source,python] +---- +CylinderZ(0, "{c.r_base}", "-{c.tool_len}+{s.tool_offset[2]}", "{c.r_tip}") +---- + +* `CylinderZ(prefix, z_start, r_start, z_end, r_end)` ++ +[source,python] +---- +HalCylinderZ(c, 0, 10, "tool_length", 10) +---- + +=== CylinderY / HalCylinderY + +Draws a capped cylinder or conical frustum aligned along the Y axis from `y_start` (radius `r_start`) to `y_end` (radius `r_end`). + +* `CylinderY(y_start, r_start, y_end, r_end)` ++ +[source,python] +---- +CylinderY(-20, 5, "c.y_end", 8) +---- + +* `CylinderY(prefix, y_start, r_start, y_end, r_end)` ++ +[source,python] +---- +HalCylinderY(c, -20, 5, "y_end", 8) +---- + +=== CylinderX / HalCylinderX + +Draws a capped cylinder or conical frustum aligned along the X axis from `x_start` (radius `r_start`) to `x_end` (radius `r_end`). + +* `CylinderX(x_start, r_start, x_end, r_end)` ++ +[source,python] +---- +CylinderX(0, 12, "s.g5x_offset[0]", 12) +---- + +* `CylinderX(prefix, x_start, r_start, x_end, r_end)` ++ +[source,python] +---- +HalCylinderX(s, 0, 5, "g5x_offset[0]", 5) +---- + +=== Sphere / HalSphere + +Draws a solid sphere of the given `radius` centered at `(x_center, y_center, z_center)`. + +* `Sphere(x_center, y_center, z_center, radius)` ++ +[source,python] +---- +Sphere("-{c.scale_coords}+{s.g5x_offset[0]}", "s.g5x_offset[1]", 0, "{c.probe_radius}") +---- + +* `Sphere(prefix, x_center, y_center, z_center, radius)` ++ +[source,python] +---- +HalSphere(c, 0, 0, 0, "probe_radius") +---- + +=== TriangleXY / HalTriangleXY + +Extrudes a triangular plate in the XY plane between corner points `(x1, y1)`, `(x2, y2)`, `(x3, y3)` from thickness `z1` to `z2`. + +* `TriangleXY(x1, y1, x2, y2, x3, y3, z1, z2)` ++ +[source,python] +---- +TriangleXY(0, 0, "-{c.scale_coords}+{s.g5x_offset[0]}", 0, 25, 40, 0, "{c.thickness}") +---- + +* `TriangleXY(prefix, x1, y1, x2, y2, x3, y3, z1, z2)` ++ +[source,python] +---- +HalTriangleXY(c, 0, 0, "x2_pin", 0, 25, 40, 0, 10) +---- + +=== TriangleXZ / HalTriangleXZ + +Extrudes a triangular plate in the XZ plane between corner points `(x1, z1)`, `(x2, z2)`, `(x3, z3)` from depth `y1` to `y2`. + +* `TriangleXZ(x1, z1, x2, z2, x3, z3, y1, y2)` ++ +[source,python] +---- +TriangleXZ(0, 0, 50, 0, 25, "s.g5x_offset[2]", -5, 5) +---- + +* `TriangleXZ(prefix, x1, z1, x2, z2, x3, z3, y1, y2)` ++ +[source,python] +---- +HalTriangleXZ(s, 0, 0, 50, 0, 25, "g5x_offset[2]", -5, 5) +---- + +=== TriangleYZ / HalTriangleYZ + +Extrudes a triangular plate in the YZ plane between corner points `(y1, z1)`, `(y2, z2)`, `(y3, z3)` from width `x1` to `x2`. + +* `TriangleYZ(y1, z1, y2, z2, y3, z3, x1, x2)` ++ +[source,python] +---- +TriangleYZ(0, 0, 50, 0, 25, "{c.z_peak}", -5, 5) +---- + +* `TriangleYZ(prefix, y1, z1, y2, z2, y3, z3, x1, x2)` ++ +[source,python] +---- +HalTriangleYZ(c, 0, 0, 50, 0, 25, "z_peak", -5, 5) +---- + +=== ArcX / HalArcX + +Draws a hollow pipe segment along the X axis from `x1` to `x2`, bounded by inner radius `r1`, outer radius `r2`, and sweep angles `a1` to `a2` (in degrees) subdivided into `steps`. + +* `ArcX(x1, x2, r1, r2, a1, a2, steps)` ++ +[source,python] +---- +ArcX(0, 20, 40, 50, "{c.start_deg}", "{s.spindle_pos}", 36) +---- + +* `ArcX(prefix, x1, x2, r1, r2, a1, a2, steps)` ++ +[source,python] +---- +HalArcX(c, 0, 20, 40, 50, "start_deg", "end_deg", 36) +---- + +== Construction Lines, Planes & Grids + +=== Line / HalLine + +Draws an open cylindrical line from `(x_start, y_start, z_start)` by direction vector `(x_end, y_end, z_end)`, scaled by `stretch` with cylinder radius `r`. + +* `Line(x_start, y_start, z_start, x_end, y_end, z_end, stretch=1, r=5)` ++ +[source,python] +---- +Line(0, 0, 0, "-{c.scale_coords}+{s.g5x_offset[0]}", "s.g5x_offset[1]", 0, r="{c.line_radius}") +---- + +* `Line(prefix, x_start, y_start, z_start, x_end, y_end, z_end, stretch=1, r=5)` ++ +[source,python] +---- +HalLine(s, 0, 0, 0, "g5x_offset[0]", "g5x_offset[1]", "g5x_offset[2]", r=2) +---- + +=== PlaneFromNormal / HalPlaneFromNormal + +Draws a square planar quad centered at `(x_orig, y_orig, z_orig)` perpendicular to the normal vector `(x_vec, y_vec, z_vec)` with half-width `quadrant_size` (or `s`). + +* `PlaneFromNormal(x_orig, y_orig, z_orig, x_vec, y_vec, z_vec, quadrant_size=500)` ++ +[source,python] +---- +PlaneFromNormal("s.g5x_offset[0]", "s.g5x_offset[1]", 0, "{c.nx}", "{c.ny}", "{c.nz}", quadrant_size=250) +---- + +* `PlaneFromNormal(prefix, x_orig, y_orig, z_orig, x_vec, y_vec, z_vec, s=500)` ++ +[source,python] +---- +HalPlaneFromNormal(s, "g5x_offset[0]", "g5x_offset[1]", "g5x_offset[2]", 0, 0, 1, s=300) +---- + +=== Grid / HalGrid + +Draws a flat XY reference grid at the local origin with 10-unit line spacing extending `+-quadrant_size` (or `+-s`) in X and Y. + +* `Grid(quadrant_size=500)` ++ +[source,python] +---- +Grid("-{c.offset}+{s.g5x_offset[0]}") +---- + +* `Grid(prefix, s=500)` ++ +[source,python] +---- +HalGrid(c, "grid_size") +---- + +=== GridFromNormal / HalGridFromNormal + +Draws a 10-unit spaced line grid centered at `(x_orig, y_orig, z_orig)` oriented perpendicular to the normal vector `(x_vec, y_vec, z_vec)`. + +* `GridFromNormal(x_orig, y_orig, z_orig, x_vec, y_vec, z_vec, quadrant_size=500)` ++ +[source,python] +---- +GridFromNormal("s.g5x_offset[0]", "s.g5x_offset[1]", 0, "{c.vx}", "{c.vy}", "{c.vz}", quadrant_size="{c.grid_size}") +---- + +* `GridFromNormal(prefix, ox, oy, oz, vx, vy, vz, s=500)` ++ +[source,python] +---- +HalGridFromNormal(s, "g5x_offset[0]", "g5x_offset[1]", "g5x_offset[2]", 0, 0, 1, s=300) +---- + +=== GridFromNormalAndDirection / HalGridFromNormalAndDirection + +Draws a fully oriented 10-unit spaced line grid at `(x_orig, y_orig, z_orig)` aligned to both a Z-normal vector `(vec_Zx, vec_Zy, vec_Zz)` and an X-direction vector `(vec_Xx, vec_Xy, vec_Xz)`. + +* `GridFromNormalAndDirection(x_orig, y_orig, z_orig, vec_Xx, vec_Xy, vec_Xz, vec_Zx, vec_Zy, vec_Zz, quadrant_size=500)` ++ +[source,python] +---- +GridFromNormalAndDirection("s.g5x_offset[0]", "s.g5x_offset[1]", 0, "{c.xx}", "{c.xy}", "{c.xz}", "{c.zx}", "{c.zy}", "{c.zz}") +---- + +* `GridFromNormalAndDirection(prefix, ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500)` ++ +[source,python] +---- +HalGridFromNormalAndDirection(s, "g5x_offset[0]", "g5x_offset[1]", "g5x_offset[2]", 1, 0, 0, 0, 0, 1, s=300) +---- + +=== CoordsFromNormalAndDirection / HalCoordsFromNormalAndDirection + +Draws a 3-axis RGB coordinate triad (Red = X, Green = Y, Blue = Z) at `(x_orig, y_orig, z_orig)` defined by the X-direction and Z-normal vectors, with axis length `50 * stretchfactor` and cylinder radius `radius`. + +* `CoordsFromNormalAndDirection(x_orig, y_orig, z_orig, vec_Xx, vec_Xy, vec_Xz, vec_Zx, vec_Zy, vec_Zz, stretchfactor=1, radius=5)` ++ +[source,python] +---- +CoordsFromNormalAndDirection("s.g5x_offset[0]", "s.g5x_offset[1]", 0, "{c.xx}", "{c.xy}", "{c.xz}", "{c.zx}", "{c.zy}", "{c.zz}", stretchfactor="{c.axis_scale}", radius=4) +---- + +* `CoordsFromNormalAndDirection(prefix, ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch=1, r=5)` ++ +[source,python] +---- +HalCoordsFromNormalAndDirection(s, "g5x_offset[0]", "g5x_offset[1]", "g5x_offset[2]", 1, 0, 0, 0, 0, 1, stretch=1.5, r=3) +---- + +== Mesh Import (STL & OBJ) + +=== AsciiSTL / HalAsciiSTL + +Loads and renders an ASCII `.stl` mesh from a static file path, inline string `data`, or a dynamically changing file name (such as `tool_in_spindle`) combined with `path`. Automatically computes surface normals from triangle vertices when zero normals (`[0, 0, 0]`) are encountered and frees previous OpenGL display lists (`glDeleteLists`) upon reloading. + +* `AsciiSTL(filename=None, path='', data=None)` ++ +[source,python] +---- +AsciiSTL("{c.model_offset}+{s.tool_in_spindle}", path="tools/") +---- + +* `AsciiSTL(prefix, filename=None, path='', data=None)` ++ +[source,python] +---- +HalAsciiSTL(s, "tool_in_spindle", path="tools/") +---- + +=== AsciiOBJ / HalAsciiOBJ + +Loads and renders a Wavefront `.obj` mesh from a static file path, inline string `data`, or a dynamically changing file name combined with `path`, freeing previous OpenGL display lists when switching models. + +[NOTE] +==== +`AsciiOBJ` compiles `glDisable(GL_CULL_FACE)` into its display list for two-sided rendering of opaque meshes. If you render a closed `.obj` mesh with alpha transparency (`A < 1.0`), `AsciiSTL` is recommended so `Color` can manage back-face culling automatically. +==== + +* `AsciiOBJ(filename=None, path='', data=None)` ++ +[source,python] +---- +AsciiOBJ("s.tool_in_spindle", path="tools/") +---- + +* `AsciiOBJ(prefix, filename=None, path='', data=None)` ++ +[source,python] +---- +HalAsciiOBJ(c, "part_id", path="models/") ---- -== Create the HAL pins. +=== Capture + +Snapshots the active OpenGL `GL_MODELVIEW_MATRIX` at its position in the scene hierarchy so `Track` or custom Python logic can read the live position of moving machine parts. Because the captured matrix is in camera/view space, place one `Capture()` at the root of your model (`world`) and additional `Capture()` instances inside the moving branches (`position`, `target`). + +* `Capture()` — Creates a matrix capture node to insert into a `Collection`. ++ +[source,python] +---- +world = Capture() +spindle_tip = Capture() +workpiece_target = Capture() -HAL pins are created with the normal Python "hal" library, and are not -specific to Vismach. Further details can be found in the -<> section. -A component should be created with a name that matches the script file -name and then the HAL pins are added to that component. They will be -referenced by their component handle and short name when used to animate -the Vismach model. +# Inside scene assembly: +# root = Collection([world, ..., spindle_tip, ..., workpiece_target]) +# link = Track([beam], spindle_tip, workpiece_target, world) +---- +* `capture.world_pos(world=None)` — Returns the captured `[x, y, z]` coordinates transformed back into world space when the root `world` `Capture()` instance is passed (or raw view-space coordinates if `world` is omitted). Passing another `Capture()` reference frame (such as `work`) returns coordinates relative to that moving frame. ++ [source,python] ---- -c = hal.component("samplegui") -c.newpin("joint0", hal.Type.REAL, hal.Dir.IN) -c.newpin("joint1", hal.Type.REAL, hal.Dir.IN) +# 1. Create HAL output pins for live coordinates +c.newpin("tip-world-x", hal.Type.FLOAT, hal.HAL_OUT) +c.newpin("tip-world-y", hal.Type.FLOAT, hal.HAL_OUT) +c.newpin("tip-world-z", hal.Type.FLOAT, hal.HAL_OUT) c.ready() + +# 2. Place 'world' at the root and 'spindle_tip' at the end of the moving kinematic chain +world = Capture() +spindle_tip = Capture() +spindle_branch = Collection([tool_geometry, spindle_tip]) +# ... apply axis transforms to spindle_branch ... +model = Collection([world, table, spindle_branch, base]) + +# 3. Read world coordinates in the periodic callback and display in HUD +def myfunction(): + wx, wy, wz = spindle_tip.world_pos(world) + c["tip-world-x"] = wx + c["tip-world-y"] = wy + c["tip-world-z"] = wz + +myhud.add_pin( + "Tip World: {:7.2f}, {:7.2f}, {:7.2f}", + "{c.tip-world-x}, {c.tip-world-y}, {c.tip-world-z}", +) + +main(model, tooltip, work, hud=myhud, function=myfunction) +---- + +=== Track + +Moves and rotates child parts so they align along the vector pointing from `position` to `target`, using `world` (`Capture()`) to convert OpenGL model-view coordinates back into world space. Both `position` and `target` accept `Capture()` instances or 3-element `[x, y, z]` coordinate lists containing static numbers, pins, or mixed expressions. + +* `Track(parts, position, target, world)` ++ +[source,python] +---- +Track([cylinder_link], base_capture, tip_capture, world_capture) +---- + +* `Track(parts, position, [x, y, z], world)` ++ +[source,python] +---- +Track([laser_beam], spindle_capture, ["s.g5x_offset[0]", "s.g5x_offset[1]", "{c.target_z}"], world_capture) +---- + +* `Track(parts, prefix, position, target, world)` ++ +[source,python] +---- +Track([laser_beam], s, spindle_capture, ["g5x_offset[0]", "g5x_offset[1]", "g5x_offset[2]"], world_capture) +---- + +== Head-Up Display (HUD) + +=== Hud + +Renders a semi-transparent 2D text overlay in the upper-left corner of the OpenGL viewport. All `Hud` methods pre-compile their arguments at setup time and support static values, HAL pins, `linuxcnc.stat` attributes, mixed math expressions, and conditional Python expressions. + +==== Prefix Resolution & Graceful Diagnostics in `Hud` + +* **Dot or brace notation (`"c.pin"`, `"hal.joint.0.pos-fb"`, `"{s.g5x_offset[0]}"`):** Resolved automatically from the caller's scope without needing `prefix=...`. +* **Legacy full HAL pin names (`"my-gui.pin_name"`):** When `prefix` is omitted and the substring before the first dot matches a ready HAL component (`hal.component_is_ready(...)`), `Hud` binds the pin directly via `hal`. +* **Bare pin name without dots or braces (`"my-pin"`):** Defaults to `prefix=hal` when `prefix` is omitted, or uses the explicit `prefix` argument (`prefix=c`, `prefix=s`, or `prefix=hal`). +* **Graceful fallback:** If a pin, status attribute, or prefix cannot be resolved at startup, `Hud` prints a `Vismach HUD Warning` message to the console and substitutes `0` so the 3D scene still launches cleanly. + +==== Methods & Examples + +* `Hud(showme=1)` — Initializes the HUD overlay. Pass `showme=0` to start hidden, or bind `showme` to a dynamic pin or boolean expression. ++ +[source,python] +---- +hud = Hud(showme="not {c.hide-spindle-body}") +---- + +* `hud.add_txt(string, tag=None)` — Appends a static text line, optionally assigned to a single tag or a list of tags. Lines with `tag=None` are always displayed when the HUD is visible. ++ +[source,python] +---- +hud.add_txt("Machine Status:", tag="info") +hud.add_txt("TWP Active", tag=[1, 2, 3]) +---- + +* `hud.add_pin(string, pin=None, tag=None, prefix=None)` — Appends a formatted line populated dynamically from a HAL pin, `linuxcnc.stat` attribute, conditional string expression, or comma-separated tuple of expressions (unpacked automatically into `string.format(*val)`). ++ +[source,python] +---- +# System HAL pin using dot notation (requires 'import hal' in caller scope) +hud.add_pin("Joint 0: {:8.3f}", "hal.joint.0.pos-fb") + +# Legacy full HAL component pin string +hud.add_pin("Xx: {:8.3f}", "xyzbca-trsrn-gui.twp_xx", [1, 2, 3]) + +# Mixed expression combining a HAL component and linuxcnc.stat +hud.add_pin("X-Offset: {:.3f}", "-{c.scale_coords}+{s.g5x_offset[0]}") + +# Conditional string expression +hud.add_pin("Kins Mode: {}", "'TCP' if {hal.motion.kins-type} == 0 else 'WORLD'") + +# Multi-value tuple unpacked into multiple format placeholders +hud.add_pin( + "Origin: {:7.2f}, {:7.2f}, {:7.2f}", + "{s.g68_offset[0]}, {s.g68_offset[1]}, {s.g68_offset[2]}", + tag=[1, 2, 3], +) + +# Legacy explicit prefix +hud.add_pin("Feed: {:.1f}", "feedrate", prefix=s) +---- + +* `hud.show_tag_if_same(tag, pin, val=True, prefix=None)` — Displays all lines matching `tag` (or list of tags) whenever `pin` evaluates equal to `val`. ++ +[source,python] +---- +hud.show_tag_if_same("alarm", "s.estop", 1) +---- + +* `hud.show_tags_in_pin(pin, offs=0, prefix=None)` — Displays lines whose integer tag equals `int(pin + offs)`, useful for switching between multi-page or multi-state HUD views. ++ +[source,python] +---- +hud.show_tags_in_pin("s.g68_active", offs=0) +---- + +* `hud.hide_all(pin, val=True, prefix=None)` — Hides the entire HUD overlay whenever `pin` evaluates equal to `val`. ++ +[source,python] +---- +hud.hide_all("{c.hide_overlay} or {s.task_mode} == 2") +---- + +* `hud.set_hud_rgba(r, g, b, a, prefix=None)` — Sets the background RGB color and alpha transparency (`0.0` to `1.0`) of the HUD text box. Supports static floats or dynamic expressions. ++ +[source,python] +---- +hud.set_hud_rgba(0.05, 0.12, 0.18, 0.65) +---- + +* `hud.set_hud_text_rgb(r, g, b, prefix=None)` — Sets the RGB text color of the HUD lines. Supports static floats or dynamic expressions. ++ +[source,python] +---- +hud.set_hud_text_rgb(0.95, 0.90, 0.65) +---- + +* `hud.show(string)` / `hud.hide()` _(Legacy methods)_ — `show(string)` unhides the HUD and appends a permanent text line; `hide()` unconditionally hides the overlay. ++ +[source,python] +---- +hud.show("XYZACB-trsrn") +---- + + + +== Migration Guide for Existing Vismach Models + +Existing Vismach model scripts remain **100% backwards compatible** and require no mandatory changes. When updating existing models or writing new ones, you can simplify your scene definitions using the patterns below. + +=== 1. Replace Nested Single-Prefix Transforms with Combined Expressions + +Previously, combining values from two different sources (such as a HAL component `c` and `linuxcnc.stat` `s`) required nesting two separate `HalTranslate` or `HalRotate` blocks. You can now collapse them into a single transform using curly-brace `{prefix.attr}` expressions. + +* **Before (nested transforms):** ++ +[source,python] +---- +part = HalTranslate([part], c, -1, "scale_coords", 0, 0) +part = HalTranslate([part], s, 1, "g5x_offset[0]", 0, 0) +---- + +* **After (single unified transform):** ++ +[source,python] +---- +part = Translate([part], 1, "-{c.scale_coords}+{s.g5x_offset[0]}", 0, 0) +---- + +=== 2. Omit the `prefix` Argument When Using Dot Notation + +Whenever an attribute or pin string already specifies its source (`"c.pin_name"` or `"s.attr_name"`), you can drop the `prefix` argument completely. + +* **Before:** ++ +[source,python] +---- +spindle = HalRotate([spindle], c, "spindle_angle", 1, 0, 0, 1) +hud.add_pin("Feed: {:.1f}", "feedrate", prefix=s) ---- -Will create HAL pins 'samplegui.joint0' and 'samplegui.joint1'. When -loading the Vismach model with 'loadusr -W samplegui' the 'c.ready()' -function tells loadusr it's ready. - -== Creating Parts - -It is probably easiest to create geometry in a CAD package and *import* -into the model script with the `AsciiSTL()` or `AsciiOBJ()` functions. -Both functions can take one of two named arguments, either a filename -or raw data: - -* `part = AsciiSTL(filename="path/to/file.stl") + - part = AsciiSTL(data="solid part1 facet normal ....") + - part = AsciiOBJ(filename="path/to/file.obj") + - part = AsciiOBJ(data="v 0.123 0.234 0.345 1.0 ...")` + - The parts will be created in the Vismach space in the same locations - as they occupy in the STL or OBJ space. This means that it may be - possible to assemble the model in the CAD package. - -Alternatively parts can be created inside the model script from a range -of *shape primitives*. Many shapes are created at the origin and need to -be moved to the required location after creation: - -* `cylinder = CylinderX(x1, r1, x2, r2) + - cylinder = CylinderY(y1, r1, y2, r2) + - cylinder = CylinderZ(z1, r1, z2, r2)` + - Creates a (optionally tapered) cylinder on the given axis with the - given radii at the given points on the axis. -* `sphere = Sphere(x, y, z, r)` + - Creates a sphere of radius r at (x,y,z) -* `triangle = TriangleXY(x1, y1, x2, y2, x3, y3, z1, z2) + - triangle = TriangleXZ(x1, z1, x2, z2, x3, z3, y1, y2) + - triangle = TriangleYZ(y1, z1, y2, z2, y3, z3, x1, x2)` + - Creates a triangular plate between planes defined by the last two - values parallel to the specified plane, with vertices given by the - three coordinate pairs. -* `arc = ArcX(x1, x2, r1, r2, a1, a2)` + - Create an arc shape. -* `box = Box(x1, y1, z1, x2, y2, z2)` + - Creates a rectangular prism with opposite corners at the specified - positions and edges parallel to the XYZ axes. -* `box = BoxCentered(xw, yw, zw)` + - Creates an xw by yw by zw box centred on the origin. -* `box = BoxCenteredXY(xw, yw, z)` + - Creates a box of width xw / yw and height z. - -Composite parts may be created by *assembling* these primitives either -at creation time or subsequently using `Collection()`: - -[source,python] ----- -part1 = Collection([Sphere(100,100,100,50), CylinderX(100,40,150,30)]) -part2 = Box(50,40,75,100,75,100) -part3 = Collection([part2, TriangleXY(10,10,20,10,15,20,100,101)]) -part4 = Collection([part1, part2]) ----- - -== Moving Parts - -Parts may need to be moved in the Vismach space to assemble the model. -They may also need to be moved to create the animation as the animation -rotation axis is created at the origin (but moves with the Part): - -* `part1 = Translate([part1], x, y, z)` + - Move part1 the specified distances in x, y and z. -* `part1 = Rotate([part1], theta, x, y, z)` + - Rotate the part by angle theta about an axis between the origin and - x, y, z. - -== Animating Parts - -To animate the model (controlled by the values of HAL pins) there are -two functions 'HalTranslate' and 'HalRotate'. For parts to move inside -an assembly they need to have their HAL motions defined before being -assembled with the "Collection" command. The rotation axis and -translation vector move with the part as it is moved by the vismach -script during model assembly, or as it moves in response to the HAL pins -as the model is animated: - -* `part = HalTranslate([part], comp, "hal_pin", xs, ys, zs)` + - The function arguments are: -** first a _collection/part_ which can be pre-created earlier in the - script, or could be created at this point if preferred eg - `part1 = HalTranslate([Box(....)], ...)`. -** The _HAL component_ is the next argument, i.e. the object returned by - the `comp = hal.component(...)` command. After that is the name of - the HAL in that will animate the motion, this needs to match an - existing HAL pin that is part of the HAL component created earlier in - the script. -** Then follow the _X, Y, Z scales_. + - For a Cartesian machine created at 1:1 scale this would typically be - 1,0,0 for a motion in the positive X direction. + - However if the STL file happened to be in cm and the machine was in - inches, this could be fixed at this point by using 0.3937 - (1cm /2.54in) as the scale. -* `part = HalRotate([part], comp, "hal_pin", angle_scale, x, y, z)` + - This command is similar in its operation to HalTranslate except that - it is typically necessary to move the part to the origin first to - define the axis. -** The _axis of rotation_ is from the origin point to the point defined - by (x,y,z). + - When the part is moved back away from the origin to its correct - location the axis of rotation can be considered to remain "embedded" - in the part. -** _Rotation angles_ are in degrees, so for a rotary joint with a 0-1 - scaling you would need to use an angle scale of 360. - -== Assembling the model. - -In order for parts to move together they need to be assembled with the -Collection() command. It is important to assemble the parts and define -their motions in the correct sequence. For example to create a moving -head milling machine with a rotating spindle and an animated draw bar -you would: - -* Create the head main body. -* Create the spindle at the origin. -* Define the rotation. -* Move the head to the spindle or spindle to the head. -* Create the draw bar. -* Define the motion of the draw bar. -* Assemble the three parts into a head assembly. -* Define the motion of the head assembly. - -In this example the spindle rotation is indicated by rotation of a set -of drive dogs: - -[source,python] ----- -#Drive dogs -dogs = Box(-6,-3,94,6,3,100) -dogs = Color([1,1,1,1],[dogs]) -dogs = HalRotate([dogs],c,"spindle",360,0,0,1) -dogs = Translate([dogs],-1,49,0) - -#Drawbar -draw = CylinderZ(120,3,125,3) -draw = Color([1,0,.5,1],[draw]) -draw = Translate([draw],-1,49,0) -draw = HalTranslate([draw],c,"drawbar",0,0,1) - -# head/spindle -head = AsciiSTL(filename="./head.stl") -head = Color([0.3,0.3,0.3,1],[head]) -head = Translate([head],0,0,4) -head = Collection([head, tool, dogs, draw]) -head = HalTranslate([head],c,"Z",0,0,0.1) - -# base -base = AsciiSTL(filename="./base.stl") -base = Color([0.5,0.5,0.5,1],[base]) -# mount head on it -base = Collection([head, base]) ----- - -Finally a single collection of all the machine parts, floor and work (if -any) needs to be created: - -* For a _serial machine_ each new part will be added to the collection of - the previous part. -* For a _parallel machine_ there may be several "base" parts. - -Thus, for example, in scaragui.py link3 is added to link2, link2 to -link1 and link1 to link0, so the final model is created by: - -[source,python] ----- -model = Collection([link0, floor, table]) ----- - -Whereas a VMC model with separate parts moving on the base might have: - -[source,python] ----- -model = Collection([base, saddle, head, carousel]) ----- - -== Other functions - -* `part = Color([colorspec], [part])` + - Sets the display color of the part. Note that unlike the other - functions the part definition comes second in this case. + - The colorspec consists of the three RGB values and an opacity. - For example [1,0,0,0.5] for a 50% opacity red. -* `myhud = Hud()` + - Creates a heads-up display in the Vismach GUI to display such items as - axis positions. -//// -Need to play around with this to see how it works. -//// -* `tooltip = Capture()` + - Think of this as an invisible part that needs to be attached to the - tooltip to track the position and orientation of the tool coordinate system. - It is actually a transformation matrix that is constantly updated as the - model moves. -* `work = Capture()` + - Same as above but attached to the work table to track the work coordinate - system. -* `main(model, tooltip, work, size=10, hud=0, rotation_vectors=None, - lat=0, lon=0)` + - This is the command that makes it all happen, creates the display etc. -** _model_ should be a collection that contains all the machine parts. -** _tooltip_ and _work_ need to be created by `Capture()`. Vismach needs - this information to draw the backplot which is basically the tooltip - position drawn in the work coordinate system. + - See `scaragui.py` for an example of how to connect the tool tip to a - tool and the tool to the model. -** Either _rotation_vectors_ or _latitude/longitude_ can be used to set - the original viewpoint and it is advisable to do as the default - initial viewpoint is rather unhelpfully from immediately overhead. -** _size_ sets the extent of the volume visualized in the initial view. -** _hud_ refers to a head-up display of axis positions. - -== Basic structure of a Vismach script. - -[source,python] ----- -#imports -from vismach import * -import hal -#create the HAL component and pins -comp = hal.component("compname") -comp.newpin("pin_name", hal.Type.REAL, hal.Dir.IN) -... -#create the floor, tool and work -floor = Box(-50, -50, -3, 50, 50, 0) -work = Capture() -tooltip = Capture() -... -#Build and assemble the model -part1 = Collection([Box(-6,-3,94,6,3,100)]) -part1 = Color([1,1,1,1],[part1]) -part1 = HalRotate([part1],comp,"pin_name",360,0,0,1) -part1 = Translate([dogs],-1,49,0) -... -#create a top-level model -model = Collection([base, saddle, head, carousel]) -#Start the visualization -main(model, tooltip, work, 100, lat=-75, lon=215) ----- - -// vim: set syntax=asciidoc: +* **After:** ++ +[source,python] +---- +spindle = Rotate([spindle], "c.spindle_angle", 1, 0, 0, 1) +hud.add_pin("Feed: {:.1f}", "s.feedrate") +---- + +=== 3. Use Unified Class Names for Both Static and Dynamic Geometry + +You no longer need to switch between static classes (`Box`, `CylinderZ`, `Translate`, `AsciiSTL`) and dynamic classes (`HalBox`, `HalCylinderZ`, `HalTranslate`, `HalAsciiSTL`). + +* Passing **numbers only** automatically uses the zero-overhead static fast-path. +* Passing **strings or expressions** automatically compiles them into pre-cached getters at startup. + +[source,python] +---- +# Static fast-path (zero ArgsBase overhead) +table = BoxCentered(400, 300, 20) + +# Dynamic expression using the exact same class +stock = BoxCentered("{c.stock_x}", "{c.stock_y}", "-{c.base_z}+{s.g5x_offset[2]}") +---- + +=== 4. Ensure `poll_all_stats()` Is Called Once per Frame + +If you are integrating the updated `ArgsBase` into a custom `vismach.py`, make sure `poll_all_stats()` is called once at the beginning of your OpenGL widget's `redraw()` method so all `linuxcnc.stat` attributes stay synchronized on a single status snapshot per frame: + +[source,python] +---- +def redraw(self): + poll_all_stats() + # ... existing OpenGL rendering code ... +---- + +=== 5. Keep Prefix Variables in Caller Scope + +Because `ArgsBase` resolves and caches prefix names (`c`, `s`, `hal`) from the caller's scope when objects are instantiated: + +* Define your HAL component (`c = hal.component(...)`) and status channel (`s = linuxcnc.stat()`) **before** instantiating Vismach parts or `Hud` lines. +* If you build parts inside a helper function, either pass the prefix explicitly (`Translate([part], c, ...)`) or ensure `c` and `s` are accessible in that function's local or global scope. + +=== 6. Legacy Custom `coords()` / `get_values()` Subclasses & `CoordsBase` + +Older Vismach models sometimes define custom subclasses with zero geometry arguments (such as `HalToolCylinder(c)`), instantiate primitives with a dummy argument (`TriangleXZ(0)`), subclass `CoordsBase` directly (`HexPrismZ(CoordsBase)`), or override `get_values()` on `VectorRotate` (`HalRotateNutation`): + +[source,python] +---- +class HalToolCylinder(CylinderZ): + def __init__(self, comp, *args): + CylinderZ.__init__(self, *args) + self.comp = comp + + def coords(self): + r = c.tool_diameter / 2 if c.tool_diameter > 0 else 2 + return -c.tool_length, r, 0, r + +class HexPrismZ(CoordsBase): + def draw(self): + z0, z1, h = self.coords() + # ... +---- + +All of these legacy patterns continue to work without modification. In new models, you can replace custom subclasses with a single inline expression: + +[source,python] +---- +tool_cyl = CylinderZ( + "-{c.tool_length}", + "{c.tool_diameter}/2 if {c.tool_diameter} > 0 else 2", + 0, + "{c.tool_diameter}/2 if {c.tool_diameter} > 0 else 2", +) +---- + +== Performance & Caching + +To maintain high frame rates in complex multi-axis machine simulations, `ArgsBase` shifts all string parsing, scope lookups, and expression compilation from the OpenGL render loop to model initialization. + +=== 1. One-Time Prefix Resolution & Caching + +* When a Vismach object is instantiated without an explicit `prefix` argument, `ArgsBase` inspects the caller's local and global namespace **once** to resolve prefix aliases (such as `c`, `s`, or `hal`). +* Validated prefix objects are stored in a local dictionary (`_prefix_cache`), and the stack frame reference is discarded immediately—eliminating per-frame `inspect` overhead or memory retention. + +=== 2. Pre-Compiled Bytecode & Lambda Evaluators + +* **Static Fast-Path:** Arguments passed as plain numbers (`int` or `float`) bypass `ArgsBase` completely when no dynamic expressions are present in the same transform or primitive. +* **Direct Pin & Attribute Getters:** Single HAL pins compile into direct `hal.get_value()` closures, while `linuxcnc.stat` attributes compile into C-level `operator.attrgetter` functions (or pre-compiled lambdas for indexed attributes like `g5x_offset[0]`). +* **Math Expressions:** Curly-brace expressions (such as `"-{c.scale_coords}+{s.g5x_offset[0]}"`) are compiled into Python bytecode (`compile(..., "eval")`) once at startup. During rendering, `coords()` executes native Python bytecode with zero string splitting or runtime `eval()`. + +=== 3. Single `linuxcnc.stat.poll()` per Frame & Callback Auto-Registration + +* Every `linuxcnc.stat` instance referenced by any transform, primitive, `Hud` item, or user callback (`main(..., function=myfunction)`) is automatically registered in `_registered_stats`. +* Calling `poll_all_stats(force=True)` inside the periodic `update()` loop—and `poll_all_stats()` at the top of `O.redraw()`—ensures that `s.poll()` runs **once per update cycle** (or immediately on interactive mouse camera drags), keeping user callbacks, 3D kinematics, and the HUD synchronized on a single status snapshot. + +[source,python] +---- +def redraw(self, *args): + global _stats_fresh + if self.winfo_width() == 1: + return + poll_all_stats() + _stats_fresh = False + self.model.traverse() + # ... +---- + +=== 4. Zero-Copy Scale-Safe Matrix Inversion + +* `invert(src)` unpacks 4×4 OpenGL model-view matrices directly via tuple destructuring without `copy.deepcopy()`, normalizing transposed basis vectors by squared length (`1.0 / length^2`) so `Capture()` and `Track()` remain accurate even inside scaled scene branches. + +== Troubleshooting + +=== `NameError: Prefix '' not found in caller scope` + +* **Cause:** An attribute or expression references a prefix (such as `"c.pin"` or `"{s.g5x_offset[0]}"`) that was not defined in the local or global scope where the Vismach object was instantiated. +* **Solution:** + 1. Ensure `c = hal.component(...)` and `s = linuxcnc.stat()` are created **before** instantiating any Vismach parts or `Hud` lines. + 2. If you build geometry inside a separate factory function or imported module where `c` and `s` are not globals, either pass them into that scope or supply the prefix explicitly (`Translate([part], c, "pin_name", 0, 0)`). + +=== `ValueError: No prefix passed: expected 'prefix.attribute', got ''` + +* **Cause:** A bare pin or attribute name (such as `"g5x_offset[0]"`) was passed without a leading `prefix` argument and without dot notation (`"s.g5x_offset[0]"`). +* **Solution:** Either prepend the source variable (`"s.g5x_offset[0]"`) or pass the prefix explicitly as the argument after `parts` (`Translate([part], s, 1, "g5x_offset[0]", 0, 0)`). + +=== `ctypes.ArgumentError: argument 1: TypeError: must be real number, not tuple` + +* **Cause:** A tuple attribute from `linuxcnc.stat` (such as `s.g5x_offset` or `s.g68_offset`) was referenced without an element index (`[0]`, `[1]`, `[2]`), passing a 9-element tuple into an OpenGL coordinate argument. +* **Solution:** Always specify the axis index when referencing tuple attributes in expressions (e.g., `"{s.g5x_offset[0]} + {s.g92_offset[0]}"`). + +=== `Vismach Error: Cannot compile expression ...` or `Cannot evaluate expression ...` + +* **Cause:** A math expression contains mismatched curly braces `{...}`, invalid Python operator syntax, or references a HAL pin / status attribute that does not exist. +* **Solution:** + 1. Wrap every pin or status attribute inside `{...}` when combining values with operators (e.g., `"-{c.scale_coords}+{s.g5x_offset[0]}"`). + 2. Verify the exact HAL pin name using `halcmd show pin` and verify `linuxcnc.stat` attribute names (e.g., `g5x_offset[0]`, `joint[0]['output']`). + 3. Watch for division by zero when dividing by a HAL pin that initializes to `0.0` at startup. + +=== `linuxcnc.stat` Values Appear Frozen or Out of Sync + +* **Cause:** `poll_all_stats()` is missing from the OpenGL widget's `redraw()` or `update()` loop, so `s` is never refreshed after initialization. +* **Solution:** Verify that `poll_all_stats()` is called at the top of `O.redraw()` and `poll_all_stats(force=True)` runs before `function()` in `main()`'s `update()` loop. + +=== Transparent STL/OBJ Mesh Looks Inside-Out or Missing Front Faces + +* **Cause:** Back-face culling (`GL_CULL_FACE` with `GL_BACK`) relies on triangle vertex winding order matching outward-facing surface normals. Some CAD exporters write STL files with inward-facing normals. +* **Solution:** + 1. Re-export the STL with outward-facing normals (or run a "Recalculate Normals Outside" operation in Blender / FreeCAD / MeshLab). + 2. Alternatively, if you want both the back and front walls of a hollow transparent part visible at the same time, use two-step culling (`glCullFace(GL_FRONT)` followed by `glCullFace(GL_BACK)`) inside `Color.traverse()`. + +=== `TypeError: ... expects (...)` When Passing Optional Arguments + +* **Cause:** Positional arguments were passed in an unexpected order, or an invalid object was passed in the `prefix` position. +* **Solution:** Check the target class signature in the Class Reference above, and pass optional trailing arguments (`scaleby_true`, `scaleby_false`, `order`, `stretch`, `r`, `quadrant_size`, `path`, `data`, `glow`) as keyword arguments for clarity. +Verwende Code mit Vorsicht. +If you would like, I can: +• Review the Hud class at the bottom of exp_vismach.py +• Provide the complete, consolidated vismach.adoc document in a single clean code block ready to copy-paste + +=== `Vismach HUD Warning: Could not bind '' ...` + +* **Cause:** A `Hud` method (`add_pin`, `show_tag_if_same`, `show_tags_in_pin`, or `hide_all`) referenced a HAL component, pin, or `linuxcnc.stat` attribute that does not exist or is not visible in the caller's scope. +* **Solution:** + 1. Prefix system HAL pins explicitly with `hal.` (e.g., `"hal.joint.0.pos-fb"` or `"hal.my-comp.pin"`) and ensure `import hal` is present in your script. + 2. Prefix local HAL component pins with your component variable (e.g., `"c.my-pin"`) or pass `prefix=c` / `prefix=hal` / `prefix=s`. + 3. Verify the pin name at runtime with `halcmd show pin`. diff --git a/lib/python/vismach.py b/lib/python/vismach.py index 6249934570e..e502151b436 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -14,34 +14,326 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -import copy -import sys, rs274.OpenGLTk, signal, hal +import sys +import rs274.OpenGLTk +import signal import tkinter - from OpenGL.GL import * from OpenGL.GLU import * from math import * import glnav import hal +import linuxcnc +import os +import inspect +import operator -class Collection(object): - def __init__(self, parts): - self.parts = parts - self.vol = 0 +s = linuxcnc.stat() +_registered_stats = {s} - def traverse(self): +old_plotclear = False + +# Tracks all linuxcnc.stat instances used across Vismach transforms +_stats_fresh = False + +def poll_all_stats(force=False): + """Polls all registered linuxcnc.stat instances once per cycle/frame.""" + global _stats_fresh + if _stats_fresh and not force: + return + for stat_obj in _registered_stats: + stat_obj.poll() + _stats_fresh = True + +def check_prefix(self, prefix): + """Validates and normalizes a prefix (hal module, linuxcnc.stat, hal.component, or prefix string).""" + if isinstance(prefix, dict): + return {k: check_prefix(self, v) for k, v in prefix.items()} + + checked_prefix = None + if isinstance(prefix, type(hal)) or isinstance(prefix, linuxcnc.stat): + checked_prefix = prefix + elif isinstance(prefix, hal.component): + checked_prefix = prefix.getprefix() + elif isinstance(prefix, str): + if hal.component_is_ready(prefix): + checked_prefix = prefix + return checked_prefix + +def make_stat_getter(stat_obj, val): + """Pre-compiles fast attribute or indexed access on a linuxcnc.stat instance.""" + _registered_stats.add(stat_obj) + try: + if '[' not in val: + getter = operator.attrgetter(val) + else: + getter = eval(f"lambda s: s.{val}", {"__builtins__": {}}) + + def read_stat(): + try: + return getter(stat_obj) + except Exception as e: + print("Vismach Error: Cannot get stat attribute %s,\n Error: %s" % (val, e)) + sys.exit() + + return read_stat + except Exception as e: + print("Vismach Error: Invalid stat attribute %s,\n Error: %s" % (val, e)) + sys.exit() + +_SAFE_MATH_GLOBALS = { + "__builtins__": {}, + "str": str, + "int": int, + "float": float, + "bool": bool, + "abs": abs, + "min": min, + "max": max, + "round": round, + "sin": sin, + "cos": cos, + "tan": tan, + "asin": asin, + "acos": acos, + "atan": atan, + "atan2": atan2, + "hypot": hypot, + "sqrt": sqrt, + "radians": radians, + "degrees": degrees, + "pi": pi, +} + +class ArgsBase(object): + """Parses, caches prefixes, and pre-compiles arguments into fast zero-arg callables.""" + def __init__(self, *args): + if not hasattr(self, 'prefix'): + self.prefix = None + self._args = args + self._prefix_cache = {} + + if self.prefix is None: + self._build_prefix_cache() + + self._evaluators = [self._compile_arg(arg) for arg in self._args] + + def _build_prefix_cache(self): + aliases = set() + # Flatten lists/tuples so strings inside e.g. [r, g, b, a] are also scanned + flat_args = [] + for arg in self._args: + if isinstance(arg, (list, tuple)): + flat_args.extend(arg) + else: + flat_args.append(arg) + + for arg in flat_args: + if not isinstance(arg, str) or os.path.isdir(arg): + continue + if '{' not in arg: + if '.' in arg: + aliases.add(arg.split('.', 1)[0]) + else: + for p in arg.split("{"): + if "}" in p: + token = p.split("}")[0] + if '.' in token: + aliases.add(token.split('.', 1)[0]) + + if not aliases: + return + + frame = inspect.currentframe() + try: + while frame: + caller_self = frame.f_locals.get('self') + if caller_self is not self and not isinstance(caller_self, ArgsBase): + for alias in aliases: + if alias in frame.f_locals: + raw = frame.f_locals[alias] + elif alias in frame.f_globals: + raw = frame.f_globals[alias] + else: + raise NameError("Prefix '%s' not found in caller scope" % alias) + + checked = check_prefix(self, raw) + if checked is None: + raise ValueError("'%s' is not a valid HAL component, hal module, or linuxcnc.stat" % alias) + self._prefix_cache[alias] = checked + break + frame = frame.f_back + finally: + del frame + + + def _make_token_getter(self, token): + """Returns a pre-compiled zero-argument getter for a single pin or stat attribute.""" + if self.prefix is None: + if '.' not in token: + raise ValueError("No prefix set: expected 'prefix.attribute', got '%s'" % token) + alias, attr = token.split('.', 1) + pfx = self._prefix_cache[alias] + elif isinstance(self.prefix, dict): + if '.' not in token: + raise ValueError("Expected 'prefix.attribute', got '%s'" % token) + alias, attr = token.split('.', 1) + pfx = self.prefix[alias] + else: + pfx = self.prefix + attr = token + + if isinstance(pfx, linuxcnc.stat): + return make_stat_getter(pfx, attr) + + if isinstance(pfx, type(hal)): + def read_hal(pin=attr): + try: + return hal.get_value(pin) + except Exception as e: + print("Vismach Error: Cannot get pin value %s,\n Error: %s" % (pin, e)) + sys.exit() + return read_hal + + if isinstance(pfx, str) and hal.component_is_ready(pfx): + full_pin = f"{pfx}.{attr}" + def read_comp_pin(pin=full_pin): + try: + return hal.get_value(pin) + except Exception as e: + print("Vismach Error: Cannot get pin value %s,\n Error: %s" % (pin, e)) + sys.exit() + return read_comp_pin + + print("Vismach Error: Invalid prefix for %s" % token) + sys.exit() + + def _compile_arg(self, v): + # Compile each element if a list or tuple (e.g. RGBA color list) is passed + if isinstance(v, (list, tuple)): + elem_getters = [self._compile_arg(item) for item in v] + return lambda: [fn() for fn in elem_getters] + + if not isinstance(v, str) or os.path.isdir(v): + return lambda val=v: val + + if self.prefix is None and '.' not in v: + print("Vismach Error: No prefix passed and string '%s' has no 'prefix.attr' notation." % v) + sys.exit() + + if '{' not in v: + return self._make_token_getter(v) + + try: + tokens = [p.split("}")[0] for p in v.split("{") if "}" in p] + unique_tokens = list(dict.fromkeys(tokens)) + + compiled_expr = v + getters = [] + for idx, tok in enumerate(unique_tokens): + var_name = f"_v{idx}" + compiled_expr = compiled_expr.replace("{" + tok + "}", var_name) + getters.append((var_name, self._make_token_getter(tok))) + + code_obj = compile(compiled_expr, "", "eval") + + def eval_compiled(): + try: + local_vars = {name: getter() for name, getter in getters} + return eval(code_obj, _SAFE_MATH_GLOBALS, local_vars) + except Exception as e: + print("Vismach Error: Cannot evaluate expression %s,\n Error: %s" % (v, e)) + sys.exit() + + return eval_compiled + except Exception as e: + print("Vismach Error: Cannot compile expression %s,\n Error: %s" % (v, e)) + sys.exit() + + + def coords(self): + if len(self._evaluators) == 1: + return self._evaluators[0]() + return [fn() for fn in self._evaluators] + + +class CoordsBase(ArgsBase): + """Backwards-compatible base class for legacy custom primitives (e.g. HexPrismZ) + that subclass CoordsBase and pass an optional leading prefix (comp/hal/stat).""" + def __init__(self, *args): + self.prefix, rest = _split_optional_prefix(self, args) + self.comp = args[0] if (args and isinstance(args[0], hal.component)) else None + self.q = gluNewQuadric() + ArgsBase.__init__(self, *rest) + + +######################## +# Parts Collector # +######################## + +# Two-pass rendering state for automatic opaque-first / transparent-second traversal +_render_pass = None +_in_transparent_branch = False + + +class Collection(ArgsBase): + def __init__(self, parts, *args): + if parts is None: + raise TypeError("Vismach Error: Must have at least one part.") + if not isinstance(parts, list): + parts = [parts] + self.parts = parts + for part in parts: + if not hasattr(part, 'coords') and not hasattr(part, 'capture') and not hasattr(part, 'draw'): + raise TypeError("Vismach Error: '%s' is not a valid part" % (part)) + ArgsBase.__init__(self, *args) + + def _traverse_pass(self): + if not isinstance(self.parts, list): + self.parts = [self.parts] for p in self.parts: + if isinstance(p, Color): + p.traverse() + continue + + did_apply = False + did_draw = False + if hasattr(p, "apply"): p.apply() - if hasattr(p, "capture"): + did_apply = True + + if hasattr(p, "capture") and _render_pass != "transparent": p.capture() - if hasattr(p, "draw"): + + should_draw = (_render_pass != "transparent") or _in_transparent_branch + if hasattr(p, "draw") and should_draw: p.draw() + did_draw = True + if hasattr(p, "traverse"): p.traverse() - if hasattr(p, "unapply"): + + if hasattr(p, "unapply") and (did_apply or did_draw): p.unapply() + def traverse(self): + global _render_pass + # If already inside an active pass (nested Collection), run just that pass + if _render_pass is not None: + self._traverse_pass() + return + + # Top-level call: run opaque pass first, then transparent pass + try: + _render_pass = "opaque" + self._traverse_pass() + _render_pass = "transparent" + self._traverse_pass() + finally: + _render_pass = None + + def volume(self): if hasattr(self, "vol") and self.vol != 0: vol = self.vol @@ -56,106 +348,264 @@ def volume(self): def set_volume(self,vol): self.vol = vol; -class Translate(Collection): - def __init__(self, parts, x, y, z): + +########################## +# Part Manipulators # +########################## + +def _split_optional_prefix(self, args): + """Detects whether args[0] is a prefix (or None/dict) or if the prefix was omitted.""" + if not args: + return None, args + first = args[0] + if first is None or isinstance(first, dict) or check_prefix(self, first) is not None: + return check_prefix(self, first), args[1:] + return None, args + +class Translate(Collection, ArgsBase): + def __init__(self, parts, *args): self.parts = parts - self.where = x, y, z + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) == 0: + # Legacy subclass pattern overriding coords() -> (x, y, z) + self._mode = "dynamic_3" + return + + if len(rest) == 3: + # Signature: (parts, [prefix,] x, y, z) + x, y, z = rest + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in (x, y, z)): + self._mode = "static_3" + self.where = (x, y, z) + else: + self._mode = "dynamic_3" + ArgsBase.__init__(self, x, y, z) + + elif len(rest) == 4: + # Signature: (parts, [prefix,] var, x, y, z) + var, x, y, z = rest + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in (var, x, y, z)): + self._mode = "static_3" + self.where = (x * var, y * var, z * var) + else: + self._mode = "dynamic_4" + ArgsBase.__init__(self, var, x, y, z) + + else: + raise TypeError("Translate expects (parts, [prefix,] x, y, z) or (parts, [prefix,] var, x, y, z)") def apply(self): glPushMatrix() - glTranslatef(*self.where) + if self._mode == "static_3": + glTranslatef(*self.where) + elif self._mode == "dynamic_3": + glTranslatef(*self.coords()) + else: + v, x, y, z = self.coords() + glTranslatef(x * v, y * v, z * v) def unapply(self): glPopMatrix() -class Scale(Collection): - def __init__(self, parts, x, y, z): +HalTranslate = Translate + + +class Rotate(Collection, ArgsBase): + def __init__(self, parts, *args): self.parts = parts - self.scaleby = x, y, z + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) == 0: + # Legacy subclass pattern overriding coords() -> (th, x, y, z) + self._mode = "dynamic_4" + return + + if len(rest) == 4: + # Signature: (parts, [prefix,] th, x, y, z) + th, x, y, z = rest + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in (th, x, y, z)): + self._mode = "static_4" + self.where = (th, x, y, z) + else: + self._mode = "dynamic_4" + ArgsBase.__init__(self, th, x, y, z) + + elif len(rest) == 5: + # Signature: (parts, [prefix,] var, th, x, y, z) + var, th, x, y, z = rest + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in (var, th, x, y, z)): + self._mode = "static_4" + self.where = (th * var, x, y, z) + else: + self._mode = "dynamic_5" + ArgsBase.__init__(self, var, th, x, y, z) + + else: + raise TypeError("Rotate expects (parts, [prefix,] th, x, y, z) or (parts, [prefix,] var, th, x, y, z)") def apply(self): glPushMatrix() - glScalef(*self.scaleby) + if self._mode == "static_4": + glRotatef(*self.where) + elif self._mode == "dynamic_4": + glRotatef(*self.coords()) + else: + v, th, x, y, z = self.coords() + glRotatef(th * v, x, y, z) def unapply(self): glPopMatrix() -class HalTranslate(Collection): - def __init__(self, parts, comp, var, x, y, z): +HalRotate = Rotate + + +class Scale(Collection, ArgsBase): + def __init__(self, parts, *args): self.parts = parts - self.where = x, y, z - self.comp = comp - self.var = var + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) == 0: + # Legacy subclass pattern overriding coords() -> (x, y, z) + self._mode = "dynamic_3" + return + + if len(rest) == 3: + # Signature: (parts, [prefix,] x, y, z) + x, y, z = rest + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in (x, y, z)): + self._mode = "static_3" + self.scaleby = (x, y, z) + else: + self._mode = "dynamic_3" + ArgsBase.__init__(self, x, y, z) + + elif len(rest) == 4: + # Signature: (parts, [prefix,] x, y, z, var) + x, y, z, var = rest + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in (x, y, z, var)): + self._mode = "static_3" + self.scaleby = (x * var, y * var, z * var) + else: + self._mode = "dynamic_4" + ArgsBase.__init__(self, x, y, z, var) + + else: + raise TypeError("Scale expects (parts, [prefix,] x, y, z) or (parts, [prefix,] x, y, z, var)") def apply(self): - x, y, z = self.where - v = self.comp[self.var] - glPushMatrix() - glTranslatef(x*v, y*v, z*v) + if self._mode == "static_3": + glScalef(*self.scaleby) + elif self._mode == "dynamic_3": + glScalef(*self.coords()) + else: + x, y, z, v = self.coords() + glScalef(x * v, y * v, z * v) def unapply(self): glPopMatrix() +HalScale = Scale -class HalRotate(Collection): - def __init__(self, parts, comp, var, th, x, y, z): +class Show(Collection, ArgsBase): + def __init__(self, parts, *args, **kwargs): self.parts = parts - self.where = th, x, y, z - self.comp = comp - self.var = var + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) == 0: + # Legacy subclass pattern overriding coords() -> (const, var, scaleby_true, scaleby_false) + return + + if len(rest) < 2 or len(rest) > 4: + raise TypeError("HalShow expects (parts, [prefix,] const, var, scaleby_true=1, scaleby_false=0)") + + it = iter(rest) + const = next(it) + var = next(it) + scaleby_true = next(it, kwargs.get("scaleby_true", 1)) + scaleby_false = next(it, kwargs.get("scaleby_false", 0)) + + ArgsBase.__init__(self, const, var, scaleby_true, scaleby_false) def apply(self): - th, x, y, z = self.where + const, var, s_t, s_f = self.coords() glPushMatrix() - glRotatef(th * self.comp[self.var], x, y, z) + if const == var: + glScalef(s_t, s_t, s_t) + else: + glScalef(s_f, s_f, s_f) def unapply(self): glPopMatrix() +HalShow = Show -class Rotate(Collection): - def __init__(self, parts, th, x, y, z): + +class VectorTranslate(Collection, ArgsBase): + def __init__(self, parts, *args, **kwargs): self.parts = parts - self.where = th, x, y, z + self.prefix, rest = _split_optional_prefix(self, args) + + # Unpack (xvar, yvar, zvar, scale=1) supporting both positional & keyword args + if len(rest) < 3 or len(rest) > 4: + raise TypeError("HalVectorTranslate expects (parts, [prefix,] xvar, yvar, zvar, scale=1)") + xvar, yvar, zvar = rest[0], rest[1], rest[2] + scale = rest[3] if len(rest) == 4 else kwargs.get("scale", 1) + + ArgsBase.__init__(self, xvar, yvar, zvar, scale) def apply(self): - th, x, y, z = self.where + xvar, yvar, zvar, sc = self.coords() glPushMatrix() - glRotatef(th, x, y, z) + glTranslatef(sc * xvar, sc * yvar, sc * zvar) def unapply(self): glPopMatrix() +HalVectorTranslate = VectorTranslate + -class HalRotateEuler(Collection): - def __init__(self, parts, comp, th1, th2, th3, order=123): +class VectorRotate(Collection, ArgsBase): + def __init__(self, parts, *args): self.parts = parts - self.comp = comp - self.order = order - self.th1 = th1 - self.th2 = th2 - self.th3 = th3 + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) != 5: + raise TypeError("HalVectorRotate expects (parts, [prefix,] var, th, x, y, z)") + ArgsBase.__init__(self, *rest) def apply(self): - # check whether pins or values have been passed - if isinstance(self.order, str): - order = int(self.comp[self.order]) - else: - order = self.order - if isinstance(self.th1, str): - th1 = self.comp[self.th1] + if hasattr(self, "get_values"): + # Legacy subclass pattern (e.g. HalRotateNutation) overriding get_values() + var = self.coords() + th, x, y, z = self.get_values() else: - th1 = self.th1 - if isinstance(self.th2, str): - th2 = self.comp[self.th2] - else: - th2 = self.th2 - if isinstance(self.th3, str): - th3 = self.comp[self.th3] - else: - th3 = self.th3 + var, th, x, y, z = self.coords() + glPushMatrix() + glRotatef(th * var, x, y, z) + + def unapply(self): + glPopMatrix() + +HalVectorRotate = VectorRotate + +class RotateEuler(Collection, ArgsBase): + def __init__(self, parts, *args, **kwargs): + self.parts = parts + self.prefix, rest = _split_optional_prefix(self, args) + + # Unpack (th1, th2, th3, order=123) supporting both positional & keyword args + if len(rest) < 3 or len(rest) > 4: + raise TypeError("HalRotateEuler expects (parts, [prefix,] th1, th2, th3, order=123)") + th1, th2, th3 = rest[0], rest[1], rest[2] + order = rest[3] if len(rest) == 4 else kwargs.get("order", 123) + + ArgsBase.__init__(self, th1, th2, th3, order) + + def apply(self): + th1, th2, th3, order = self.coords() glPushMatrix() if order == 131: glRotatef(th1, 1, 0, 0) @@ -209,372 +659,451 @@ def apply(self): def unapply(self): glPopMatrix() +HalRotateEuler = RotateEuler + +class Track(Collection, ArgsBase): + """Move and rotate an object to point from one capture()'d + coordinate system (or [x, y, z] point/expression) to another. + Requires 'world' Capture() to convert GL_MODELVIEW coordinates + back to the world coordinate system.""" -class Track(Collection): - '''move and rotate an object to point from one capture()'d - coordinate system to another. - we need "world" to convert coordinates from GL_MODELVIEW coordinates - to our coordinate system''' - def __init__(self, parts, position, target, world): + def __init__(self, parts, *args): self.parts = parts - self.target = target - self.position = position + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) != 3: + raise TypeError("Track expects (parts, [prefix,] position, target, world)") + + position, target, world = rest self.world2view = world - def angle_to(self,x,y,z): - '''returns polar coordinates in degrees to a point from the origin - a rotates around the x-axis; b rotates around the y axis; r is the distance''' - azimuth = atan2(y, x)*180/pi #longitude - elevation = atan2(z, sqrt(x**2 + y**2))*180/pi - radius = sqrt(x**2+y**2+z**2) - return((azimuth, elevation, radius)) - - def map_coords(self,tx,ty,tz,transform): - # now we have to transform them to the world frame - wx = tx*transform[0][0]+ty*transform[1][0]+tz*transform[2][0]+transform[3][0] - wy = tx*transform[0][1]+ty*transform[1][1]+tz*transform[2][1]+transform[3][1] - wz = tx*transform[0][2]+ty*transform[1][2]+tz*transform[2][2]+transform[3][2] - return([wx,wy,wz]) + # Check if position or target is a [x, y, z] list/tuple instead of a Capture() object + self._pos_is_capture = hasattr(position, "t") + self._tgt_is_capture = hasattr(target, "t") + + if self._pos_is_capture and self._tgt_is_capture: + # Fast path: standard Capture() objects (zero ArgsBase overhead) + self._dynamic = False + self.position = position + self.target = target + else: + # Hybrid path: at least one endpoint is a static or dynamic [x, y, z] coordinate + self._dynamic = True + self.position = position + self.target = target + pos_arg = [0, 0, 0] if self._pos_is_capture else list(position) + tgt_arg = [0, 0, 0] if self._tgt_is_capture else list(target) + ArgsBase.__init__(self, pos_arg, tgt_arg) + + def angle_to(self, x, y, z): + """Returns polar coordinates (azimuth, elevation, radius) in degrees.""" + azimuth = atan2(y, x) * 180.0 / pi + elevation = atan2(z, sqrt(x * x + y * y)) * 180.0 / pi + radius = sqrt(x * x + y * y + z * z) + return (azimuth, elevation, radius) + + def map_coords(self, tx, ty, tz, transform): + """Transforms local/view coordinates into the world frame.""" + row0, row1, row2, row3 = transform + m00, m01, m02, _ = row0 + m10, m11, m12, _ = row1 + m20, m21, m22, _ = row2 + m30, m31, m32, _ = row3 + wx = tx * m00 + ty * m10 + tz * m20 + m30 + wy = tx * m01 + ty * m11 + tz * m21 + m31 + wz = tx * m02 + ty * m12 + tz * m22 + m32 + return (wx, wy, wz) def apply(self): - # make sure we have something to work with first + # Ensure all required Capture() matrices have been populated if len(self.world2view.t) < 4: glPushMatrix() return + if self._pos_is_capture and len(self.position.t) < 4: + glPushMatrix() + return + if self._tgt_is_capture and len(self.target.t) < 4: + glPushMatrix() + return + view2world = invert(self.world2view.t) - px, py, pz = self.position.t[3][:3] - px, py, pz = self.map_coords(px,py,pz,view2world) - tx, ty, tz = self.target.t[3][:3] - tx, ty, tz = self.map_coords(tx,ty,tz,view2world) - dx = tx - px; dy = ty - py; dz = tz - pz; - (az,el,r) = self.angle_to(dx,dy,dz) - if(hasattr(HUD, "debug_track") and HUD.debug_track == 1): - HUD.strs = [] - HUD.strs += ["current coords: %3.4f %3.4f %3.4f " % (px, py, pz)] - HUD.strs += ["target coords: %3.4f %3.4f %3.4f" % (tx, ty, tz)] - HUD.strs += ["az,el,r: %3.4f %3.4f %3.4f" % (az,el,r)] - glPushMatrix() - glTranslatef(px,py,pz) - glRotatef(az-90,0,0,1) - glRotatef(el-90,1,0,0) - def unapply(self): - glPopMatrix() + if self._dynamic: + pos_vals, tgt_vals = self.coords() -# scales an object by the value of a halpin -class HalScale(Collection): - def __init__(self, parts, comp, x, y, z, var): - self.parts = parts - self.comp = comp - self.var = var - self.xyz = x, y, z + if self._pos_is_capture: + _, _, _, pos_row3 = self.position.t + px, py, pz = self.map_coords(*pos_row3[:3], view2world) + else: + px, py, pz = pos_vals + + if self._tgt_is_capture: + _, _, _, tgt_row3 = self.target.t + tx, ty, tz = self.map_coords(*tgt_row3[:3], view2world) + else: + tx, ty, tz = tgt_vals + + dx = tx - px + dy = ty - py + dz = tz - pz + az, el, r = self.angle_to(dx, dy, dz) + + if hasattr(HUD, "debug_track") and HUD.debug_track == 1: + HUD.strs = [ + "current coords: %3.4f %3.4f %3.4f " % (px, py, pz), + "target coords: %3.4f %3.4f %3.4f" % (tx, ty, tz), + "az,el,r: %3.4f %3.4f %3.4f" % (az, el, r), + ] - def apply(self): - x, y, z = self.xyz - factor = self.comp[self.var] glPushMatrix() - glScalef(x*factor,y*factor,z*factor) + glTranslatef(px, py, pz) + glRotatef(az - 90.0, 0, 0, 1) + glRotatef(el - 90.0, 1, 0, 0) def unapply(self): glPopMatrix() -# shows an object if const=var and hides it otherwise, behavior can be changed -# using the optional arguments for scalefactors when true or false -class HalShow(Collection): - def __init__(self, parts, comp, const, var, scaleby_true=1, scaleby_false=0): - self.parts = parts - self.comp = comp - self.const = const - self.var = var - self.scaleby_true = scaleby_true - self.scaleby_false = scaleby_false +class Color(Collection, ArgsBase): + def __init__(self, arg1, arg2, *args, **kwargs): + # Detect if an optional prefix was passed as arg2 (e.g. Color(parts, prefix, color, glow=0)) + if arg2 is None or isinstance(arg2, dict) or check_prefix(self, arg2) is not None: + self.parts = arg1 if isinstance(arg1, list) else [arg1] + self.prefix = check_prefix(self, arg2) + if not args: + raise TypeError("Color expects a color argument after prefix") + it = iter(args) + color = next(it) + glow = next(it, kwargs.get("glow", 0)) + else: + self.prefix = None + it = iter(args) + glow = next(it, kwargs.get("glow", 0)) + test_list = arg1 if isinstance(arg1, (list, tuple)) else [arg1] + + # Legacy argument order: (color, parts) when arg1 contains numbers or color expressions + if all(isinstance(item, (int, float, str)) for item in test_list): + self.parts = arg2 if isinstance(arg2, list) else [arg2] + color = arg1 + else: + self.parts = test_list + color = arg2 + + ArgsBase.__init__(self, color, glow) + + def _is_transparent(self, color): + # Treat 0.0 < alpha < 1.0 as transparent; alpha == 0 is legacy opaque shorthand + if len(color) < 4: + return False + r, g, b, a = color[:4] + return 0.0 < a < 1.0 def apply(self): - s_t = self.scaleby_true - s_f = self.scaleby_false - glPushMatrix() - if self.const == self.comp[self.var]: - glScalef(s_t,s_t,s_t) + color, glow = getattr(self, "_frame_color_glow", None) or self.coords() + glPushAttrib(GL_LIGHTING_BIT | GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_POLYGON_BIT) + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) + + if self._is_transparent(color): + glEnable(GL_BLEND) + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + glDepthMask(GL_FALSE) + glEnable(GL_CULL_FACE) + glCullFace(GL_BACK) + + if glow == 1: + glMaterialfv(GL_FRONT, GL_EMISSION, (1, 1, 0, 1)) else: - glScalef(s_f,s_f,s_f) + glMaterialfv(GL_FRONT, GL_EMISSION, (0, 0, 0, 1)) - def unapply(self): - glPopMatrix() + def traverse(self): + global _in_transparent_branch + color, glow = self.coords() + is_trans = self._is_transparent(color) + if _render_pass == "opaque" and is_trans: + return + if _render_pass == "transparent" and not is_trans: + return -# translates an object using a variable translation vector -# use scale=-1 to change direction -class HalVectorTranslate(Collection): - def __init__(self, parts, comp, xvar, yvar, zvar, scale=1): - self.parts = parts - self.comp = comp - self.xvar = xvar - self.yvar = yvar - self.zvar = zvar - self.sc = scale + self._frame_color_glow = (color, glow) + prev_branch = _in_transparent_branch + if is_trans: + _in_transparent_branch = True + try: + self.apply() + super().traverse() + self.unapply() + finally: + _in_transparent_branch = prev_branch + self._frame_color_glow = None - def apply(self): - # check for zero vector components - xvar = 0 if self.xvar == 0 else self.comp[self.xvar] - yvar = 0 if self.yvar == 0 else self.comp[self.yvar] - zvar = 0 if self.zvar == 0 else self.comp[self.zvar] - sc = self.sc - glPushMatrix() - glTranslatef(sc*xvar, sc*yvar, sc*zvar) def unapply(self): - glPopMatrix() + glPopAttrib() -class HalVectorRotate(Collection): - def __init__(self, parts, comp, var, th, x, y, z): - self.parts = parts - self.comp = comp - self.var = var - self.values = th, x, y, z +HalColor = Color - def get_values(self): - return self.values - def apply(self): - th, x, y, z = self.get_values() - glPushMatrix() - glRotatef(th * self.comp[self.var], x, y, z) +###################### +# Part Creators # +###################### - def unapply(self): - glPopMatrix() +class Line(ArgsBase): + def __init__(self, *args, **kwargs): + self.prefix, rest = _split_optional_prefix(self, args) + if len(rest) < 6 or len(rest) > 8: + raise TypeError("Line expects ([prefix,] x_start, y_start, z_start, x_end, y_end, z_end, stretch=1, r=5)") -class CoordsBase(object): - def __init__(self, *args): - if args and isinstance(args[0], hal.component): - self.comp = args[0] - args = args[1:] - else: - self.comp = None - self._coords = args - self.q = gluNewQuadric() + x1, y1, z1, x2, y2, z2 = rest[:6] + stretch = rest[6] if len(rest) >= 7 else kwargs.get("stretch", 1) + r = rest[7] if len(rest) == 8 else kwargs.get("r", 5) - def coords(self): - return list(map(self._coord, self._coords)) - - def _coord(self, v): - if isinstance(v, str): return self.comp[v] - return v - - -# draw an open cylinder from point_1 to point_2, radius is optional (defaults to 5) -class HalLine(): - def __init__(self, comp, x1var, y1var, z1var, x2var, y2var, z2var, stretch, r=5): - self.comp = comp - self.x1var = x1var - self.y1var = y1var - self.z1var = z1var - self.x2var = x2var - self.y2var = y2var - self.z2var = z2var - self.stretch = stretch - self.r = r - self.q = gluNewQuadric() + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in (x1, y1, z1, x2, y2, z2, stretch, r)): + self._dynamic = False + self._static_vals = (x1, y1, z1, x2, y2, z2, stretch, r) + else: + self._dynamic = True + ArgsBase.__init__(self, x1, y1, z1, x2, y2, z2, stretch, r) def cross(self, a, b): return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]] # calculate polar coordinates in degrees # a rotates around the x-axis; b rotates around the y axis - def polar(self, v): - length = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) * self.stretch + def polar(self, v, s): + length = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) * s axis = (1, 0, 0) if hypot(v[0], v[1]) < 0.001 else self.cross(v, (0, 0, 1)) angle = -atan2(hypot(v[0], v[1]), v[2])*180/pi return (length, angle, axis) def draw(self): - x1 = 0 if self.x1var == 0 else self.comp[self.x1var] - y1 = 0 if self.y1var == 0 else self.comp[self.y1var] - z1 = 0 if self.z1var == 0 else self.comp[self.z1var] - x2 = 0 if self.x2var == 0 else self.comp[self.x2var] - y2 = 0 if self.y2var == 0 else self.comp[self.y2var] - z2 = 0 if self.z2var == 0 else self.comp[self.z2var] - r = self.r - v = [x2,y2,z2] - length, angle, axis = self.polar(v) + if self._dynamic: + x1, y1, z1, x2, y2, z2, s, r = self.coords() + else: + x1, y1, z1, x2, y2, z2, s, r = self._static_vals + + v = [x2, y2, z2] + length, angle, axis = self.polar(v, s) glPushMatrix() glTranslate(x1, y1, z1) - glRotate(angle,*axis) - gluCylinder(self.q, r, r, length, 32, 1) + glRotate(angle, *axis) + gluCylinder(gluNewQuadric(), r, r, length, 32, 1) def unapply(self): glPopMatrix() -# draw a plane defined by it's normal vector(vx,vy,vz) origin at (x,y,z) -class HalPlaneFromNormal(): - def __init__(self, comp, x, y, z, vx, vy, vz, s=500): - self.comp = comp - self.x = x - self.y = y - self.z = z - self.vx = vx - self.vy = vy - self.vz = vz - self.s = s - self.q = gluNewQuadric() +# Optional alias so any existing HalLine(...) calls continue working +HalLine = Line + +class PlaneFromNormal(ArgsBase): + def __init__(self, *args, **kwargs): + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) < 6 or len(rest) > 7: + raise TypeError( + "PlaneFromNormal expects ([prefix,] x_orig, y_orig, z_orig, " + "x_vec, y_vec, z_vec, quadrant_size=500)" + ) + + x, y, z, vx, vy, vz = rest[:6] + if len(rest) == 7: + size = rest[6] + else: + size = kwargs.get("quadrant_size", kwargs.get("s", 500)) + + if self.prefix is None and not any( + isinstance(arg, (str, list, tuple)) for arg in (x, y, z, vx, vy, vz, size) + ): + self._dynamic = False + self._static_vals = (x, y, z, vx, vy, vz, size) + else: + self._dynamic = True + ArgsBase.__init__(self, x, y, z, vx, vy, vz, size) def cross(self, a, b): - return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]] + return [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], + ] # calculate polar coordinates in degrees # a rotates around the x-axis; b rotates around the y axis def polar(self, v): - length = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) + length = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) axis = (1, 0, 0) if hypot(v[0], v[1]) < 0.001 else self.cross(v, (0, 0, 1)) - angle = -atan2(hypot(v[0], v[1]), v[2])*180/pi + angle = -atan2(hypot(v[0], v[1]), v[2]) * 180 / pi return (length, angle, axis) - def square(self,n, s): + def square(self, n, s): glBegin(GL_QUADS) - glNormal3f(n[0],n[1],n[2]) - glVertex3f( s, s, 0) - glVertex3f(-s, s, 0) + glNormal3f(n[0], n[1], n[2]) + glVertex3f(s, s, 0) + glVertex3f(-s, s, 0) glVertex3f(-s, -s, 0) - glVertex3f( s, -s, 0) + glVertex3f(s, -s, 0) glEnd() def draw(self): - # check for zero values in the arguments - x = 0 if self.x == 0 else self.comp[self.x] - y = 0 if self.y == 0 else self.comp[self.y] - z = 0 if self.z == 0 else self.comp[self.z] - vx = 0 if self.vx == 0 else self.comp[self.vx] - vy = 0 if self.vy == 0 else self.comp[self.vy] - vz = 0 if self.vz == 0 else self.comp[self.vz] - s = self.s + if self._dynamic: + x, y, z, vx, vy, vz, s = self.coords() + else: + x, y, z, vx, vy, vz, s = self._static_vals + v = [vx, vy, vz] length, angle, axis = self.polar(v) glPushMatrix() - glTranslate(x,y,z) - glRotate(angle,*axis) - self.square(v,s) + glTranslate(x, y, z) + glRotate(angle, *axis) + self.square(v, s) def unapply(self): glPopMatrix() -# draw a coordinate system defined by it's normal vector(zx,zy,zz) and x-direction vector(xx, xy, xz) -# optional r to define the thickness of the cylinders -class HalCoordsFromNormalAndDirection(): - def __init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r=5): - self.comp = comp - self.ox = ox - self.oy = oy - self.oz = oz - self.xx = xx - self.xy = xy - self.xz = xz - self.zx = zx - self.zy = zy - self.zz = zz - self.stretch = stretch - self.r = r - self.q = gluNewQuadric() +# Alias so existing HalPlaneFromNormal(...) calls continue working +HalPlaneFromNormal = PlaneFromNormal + + + +class CoordsFromNormalAndDirection(ArgsBase): + def __init__(self, *args, **kwargs): + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) < 9 or len(rest) > 11: + raise TypeError( + "CoordsFromNormalAndDirection expects ([prefix,] x_orig, y_orig, z_orig, " + "vec_Xx, vec_Xy, vec_Xz, vec_Zx, vec_Zy, vec_Zz, stretchfactor=1, radius=5)" + ) + + ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] + if len(rest) >= 10: + stretch = rest[9] + else: + stretch = kwargs.get("stretchfactor", kwargs.get("stretch", 1)) + + if len(rest) == 11: + r = rest[10] + else: + r = kwargs.get("radius", kwargs.get("r", 5)) + all_args = (ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r) + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in all_args): + self._dynamic = False + self._static_vals = all_args + else: + self._dynamic = True + ArgsBase.__init__(self, *all_args) - def draw_vector(self, color): - gluCylinder(self.q, self.r, self.r, 50*self.stretch, 32, 1) + def draw_vector(self, r, stretch, color): glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) + quad = gluNewQuadric() + gluCylinder(quad, r, r, 50 * stretch, 32, 1) + gluDeleteQuadric(quad) def cross(self, a, b): - return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]] + return [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], + ] def draw(self): - # check for zero values in the arguments - ox = 0 if self.ox == 0 else self.comp[self.ox] - oy = 0 if self.oy == 0 else self.comp[self.oy] - oz = 0 if self.oz == 0 else self.comp[self.oz] - xx = 0 if self.xx == 0 else self.comp[self.xx] - xy = 0 if self.xy == 0 else self.comp[self.xy] - xz = 0 if self.xz == 0 else self.comp[self.xz] - zx = 0 if self.zx == 0 else self.comp[self.zx] - zy = 0 if self.zy == 0 else self.comp[self.zy] - zz = 0 if self.zz == 0 else self.comp[self.zz] - r = self.r - vo = [ox, oy, oz] + if self._dynamic: + ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r = self.coords() + else: + ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r = self._static_vals + vx = [xx, xy, xz] vz = [zx, zy, zz] # calculate the missing y vector - vy = [yx, yy, yz] = self.cross(vz,vx) + yx, yy, yz = self.cross(vz, vx) # for some reason we need to rotate in the opposite (transpose) sense - m_t=[[ xx, xy, xz, 0], - [ yx, yy, yz, 0], - [ zx, zy, zz, 0], - [ ox, oy, oz, 1]] - + m_t = [ + [xx, xy, xz, 0], + [yx, yy, yz, 0], + [zx, zy, zz, 0], + [ox, oy, oz, 1], + ] glPushMatrix() glMultMatrixf(m_t) - self.draw_vector([1,0,0,1]) - glRotate(90,0,1,0) - self.draw_vector([0,1,0,1]) - glRotate(-90,1,0,0) - self.draw_vector([0,0,1,1]) + self.draw_vector(r, stretch, [0, 0, 1, 1]) # Z-axis (Blue) + glRotate(90, 0, 1, 0) + self.draw_vector(r, stretch, [1, 0, 0, 1]) # X-axis (Red) + glRotate(-90, 1, 0, 0) + self.draw_vector(r, stretch, [0, 1, 0, 1]) # Y-axis (Green) def unapply(self): glPopMatrix() -# draw a grid defined by it's normal vector(zx,zy,zz) and x-direction vector(xx, xy, xz) -# optional s to define the half-width from the origin (ox,oy,oz) -class HalGridFromNormalAndDirection(): - def __init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500): - self.comp = comp - self.ox = ox - self.oy = oy - self.oz = oz - self.xx = xx - self.xy = xy - self.xz = xz - self.zx = zx - self.zy = zy - self.zz = zz - self.s = s - self.q = gluNewQuadric() +# Alias so existing HalCoordsFromNormalAndDirection(...) calls continue working +HalCoordsFromNormalAndDirection = CoordsFromNormalAndDirection + + + +class GridFromNormalAndDirection(ArgsBase): + def __init__(self, *args, **kwargs): + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) < 9 or len(rest) > 10: + raise TypeError( + "GridFromNormalAndDirection expects ([prefix,] x_orig, y_orig, z_orig, " + "vec_Xx, vec_Xy, vec_Xz, vec_Zx, vec_Zy, vec_Zz, quadrant_size=500)" + ) + + ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] + if len(rest) == 10: + size = rest[9] + else: + size = kwargs.get("quadrant_size", kwargs.get("s", 500)) + + all_args = (ox, oy, oz, xx, xy, xz, zx, zy, zz, size) + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in all_args): + self._dynamic = False + self._static_vals = all_args + else: + self._dynamic = True + ArgsBase.__init__(self, *all_args) def square(self, s): - glBegin(GL_LINES); - for i in range (-s,s+10,10): + s = int(s) + glBegin(GL_LINES) + for i in range(-s, s + 10, 10): # line 1 in x direction glVertex3f(-s, i, 0) - glVertex3f( s, i, 0) + glVertex3f(s, i, 0) # line 1 in y direction - glVertex3f( i,-s, 0) - glVertex3f( i, s, 0) + glVertex3f(i, -s, 0) + glVertex3f(i, s, 0) glEnd() def cross(self, a, b): - return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]] + return [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], + ] def draw(self): - # check for zero values in the arguments - ox = 0 if self.ox == 0 else self.comp[self.ox] - oy = 0 if self.oy == 0 else self.comp[self.oy] - oz = 0 if self.oz == 0 else self.comp[self.oz] - xx = 0 if self.xx == 0 else self.comp[self.xx] - xy = 0 if self.xy == 0 else self.comp[self.xy] - xz = 0 if self.xz == 0 else self.comp[self.xz] - zx = 0 if self.zx == 0 else self.comp[self.zx] - zy = 0 if self.zy == 0 else self.comp[self.zy] - zz = 0 if self.zz == 0 else self.comp[self.zz] - s = self.s - vo = [ox, oy, oz] + if self._dynamic: + ox, oy, oz, xx, xy, xz, zx, zy, zz, s = self.coords() + else: + ox, oy, oz, xx, xy, xz, zx, zy, zz, s = self._static_vals + vx = [xx, xy, xz] vz = [zx, zy, zz] # calculate the missing y vector - vy = [yx, yy, yz] = self.cross(vz,vx) + yx, yy, yz = self.cross(vz, vx) # for some reason we need to rotate in the opposite (transpose) sense - m_t=[[ xx, xy, xz, 0], - [ yx, yy, yz, 0], - [ zx, zy, zz, 0], - [ ox, oy, oz, 1]] - + m_t = [ + [xx, xy, xz, 0], + [yx, yy, yz, 0], + [zx, zy, zz, 0], + [ox, oy, oz, 1], + ] glPushMatrix() glMultMatrixf(m_t) self.square(s) @@ -582,492 +1111,575 @@ def draw(self): def unapply(self): glPopMatrix() -# draw a grid defined by it's normal vector(vx,vy,vz) origin at (x,y,z) -class HalGridFromNormal(): - def __init__(self, comp, x, y, z, vx, vy, vz, s=500): - self.comp = comp - self.x = x - self.y = y - self.z = z - self.vx = vx - self.vy = vy - self.vz = vz - self.s = s - self.q = gluNewQuadric() + +# Alias so existing HalGridFromNormalAndDirection(...) calls continue working +HalGridFromNormalAndDirection = GridFromNormalAndDirection + + + +class GridFromNormal(ArgsBase): + def __init__(self, *args, **kwargs): + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) < 6 or len(rest) > 7: + raise TypeError( + "GridFromNormal expects ([prefix,] x_orig, y_orig, z_orig, " + "x_vec, y_vec, z_vec, quadrant_size=500)" + ) + + x, y, z, vx, vy, vz = rest[:6] + if len(rest) == 7: + size = rest[6] + else: + size = kwargs.get("quadrant_size", kwargs.get("s", 500)) + + all_args = (x, y, z, vx, vy, vz, size) + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in all_args): + self._dynamic = False + self._static_vals = all_args + else: + self._dynamic = True + ArgsBase.__init__(self, *all_args) def cross(self, a, b): - return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]] + return [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], + ] # calculate polar coordinates in degrees # a rotates around the x-axis; b rotates around the y axis def polar(self, v): - length = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]) + length = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) axis = (1, 0, 0) if hypot(v[0], v[1]) < 0.001 else self.cross(v, (0, 0, 1)) - angle = -atan2(hypot(v[0], v[1]), v[2])*180/pi + angle = -atan2(hypot(v[0], v[1]), v[2]) * 180 / pi return (length, angle, axis) - def square(self,n, s): - glBegin(GL_LINES); - for i in range (-s,s+10,10): + def square(self, n, s): + s = int(s) + glBegin(GL_LINES) + for i in range(-s, s + 10, 10): # line 1 in x direction glVertex3f(-s, i, 0) - glVertex3f( s, i, 0) + glVertex3f(s, i, 0) # line 1 in y direction - glVertex3f( i,-s, 0) - glVertex3f( i, s, 0) + glVertex3f(i, -s, 0) + glVertex3f(i, s, 0) glEnd() def draw(self): - # check for zero values in the arguments - x = 0 if self.x == 0 else self.comp[self.x] - y = 0 if self.y == 0 else self.comp[self.y] - z = 0 if self.z == 0 else self.comp[self.z] - vx = 0 if self.vx == 0 else self.comp[self.vx] - vy = 0 if self.vy == 0 else self.comp[self.vy] - vz = 0 if self.vz == 0 else self.comp[self.vz] - s = self.s + if self._dynamic: + x, y, z, vx, vy, vz, s = self.coords() + else: + x, y, z, vx, vy, vz, s = self._static_vals + v = [vx, vy, vz] length, angle, axis = self.polar(v) glPushMatrix() - glTranslate(x,y,z) - glRotate(angle,*axis) - self.square(v,s) + glTranslate(x, y, z) + glRotate(angle, *axis) + self.square(v, s) def unapply(self): glPopMatrix() -# draw a grid defined by it's normal vector(vx,vy,vz) origin at (x,y,z) -class HalGrid(): - def __init__(self, comp, s=500): - self.comp = comp - self.s = s - self.q = gluNewQuadric() + +# Alias so existing HalGridFromNormal(...) calls continue working +HalGridFromNormal = GridFromNormal + + + +class Grid(ArgsBase): + def __init__(self, *args, **kwargs): + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) > 1: + raise TypeError("Grid expects ([prefix,] quadrant_size=500)") + + if len(rest) == 1: + size = rest[0] + else: + size = kwargs.get("quadrant_size", kwargs.get("s", 500)) + + if self.prefix is None and not isinstance(size, (str, list, tuple)): + self._dynamic = False + self._static_val = size + else: + self._dynamic = True + ArgsBase.__init__(self, size) def grid(self, s): - glBegin(GL_LINES); - for i in range (-s,s+10,10): + s = int(s) + glBegin(GL_LINES) + for i in range(-s, s + 10, 10): # line 1 in x direction glVertex3f(-s, i, 0) - glVertex3f( s, i, 0) + glVertex3f(s, i, 0) # line 1 in y direction - glVertex3f( i,-s, 0) - glVertex3f( i, s, 0) + glVertex3f(i, -s, 0) + glVertex3f(i, s, 0) glEnd() def draw(self): - s = self.s + if self._dynamic: + s = self.coords() + else: + s = self._static_val self.grid(s) -# give endpoint X values and radii -# resulting cylinder is on the X axis -class CylinderX(CoordsBase): - def draw(self): - x1, r1, x2, r2 = self.coords() - if x1 > x2: - tmp = x1 - x1 = x2 - x2 = tmp - tmp = r1 - r1 = r2 - r2 = tmp - glPushMatrix() - # GL creates cylinders along Z, so need to rotate - z1 = x1 - z2 = x2 - glRotatef(90,0,1,0) - # need to translate the whole thing to z1 - glTranslatef(0,0,z1) - # the cylinder starts out at Z=0 - gluCylinder(self.q, r1, r2, z2-z1, 32, 1) - # bottom cap - glRotatef(180,1,0,0) - gluDisk(self.q, 0, r1, 32, 1) - glRotatef(180,1,0,0) - # the top cap needs flipped and translated - glPushMatrix() - glTranslatef(0,0,z2-z1) - gluDisk(self.q, 0, r2, 32, 1) - glPopMatrix() - glPopMatrix() +# Alias so existing HalGrid(...) calls continue working +HalGrid = Grid - def volume(self): - x1, r1, x2, r2 = self.coords() - # actually a frustum of a cone - vol = 3.1415927/3.0 * abs(x1-x2)*(r1*r1+r1*r2+r2*r2) - #print "CylinderX.volume", vol - return vol -# give endpoint Y values and radii -# resulting cylinder is on the Y axis -class CylinderY(CoordsBase): - def __init__(self, y1, r1, y2, r2): - self._coords = y1, r1, y2, r2 - self.q = gluNewQuadric() +class CylinderZ(ArgsBase): + def __init__(self, *args): + self.prefix, rest = _split_optional_prefix(self, args) - def draw(self): - y1, r1, y2, r2 = self.coords() - if y1 > y2: - tmp = y1 - y1 = y2 - y2 = tmp - tmp = r1 - r1 = r2 - r2 = tmp - glPushMatrix() - # GL creates cylinders along Z, so need to rotate - z1 = y1 - z2 = y2 - glRotatef(-90,1,0,0) - # need to translate the whole thing to z1 - glTranslatef(0,0,z1) - # the cylinder starts out at Z=0 - gluCylinder(self.q, r1, r2, z2-z1, 32, 1) - # bottom cap - glRotatef(180,1,0,0) - gluDisk(self.q, 0, r1, 32, 1) - glRotatef(180,1,0,0) - # the top cap needs flipped and translated - glPushMatrix() - glTranslatef(0,0,z2-z1) - gluDisk(self.q, 0, r2, 32, 1) - glPopMatrix() - glPopMatrix() + if len(rest) <= 1: + # Legacy subclass pattern (e.g. HalToolCylinder) that overrides coords() + self._dynamic = True + return - def volume(self): - y1, r1, y2, r2 = self.coords() - # actually a frustum of a cone - vol = 3.1415927/3.0 * abs(y1-y2)*(r1*r1+r1*r2+r2*r2) - #print "CylinderY.volume", vol - return vol + if len(rest) != 4: + raise TypeError( + "%s expects ([prefix,] start, r_start, end, r_end)" % self.__class__.__name__ + ) + + start, r_start, end, r_end = rest[0], rest[1], rest[2], rest[3] + all_args = (start, r_start, end, r_end) + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in all_args): + self._dynamic = False + self._static_vals = all_args + else: + self._dynamic = True + ArgsBase.__init__(self, *all_args) + + def _get_params(self): + return self.coords() if self._dynamic else self._static_vals -class CylinderZ(CoordsBase): def draw(self): - z1, r1, z2, r2 = self.coords() + z1, r1, z2, r2 = self._get_params() if z1 > z2: - tmp = z1 - z1 = z2 - z2 = tmp - tmp = r1 - r1 = r2 - r2 = tmp + z1, z2 = z2, z1 + r1, r2 = r2, r1 + # need to translate the whole thing to z1 glPushMatrix() - glTranslatef(0,0,z1) + if hasattr(self, 'orient'): + self.orient() + glTranslatef(0, 0, z1) # the cylinder starts out at Z=0 - gluCylinder(self.q, r1, r2, z2-z1, 32, 1) + gluCylinder(gluNewQuadric(), r1, r2, z2 - z1, 32, 1) # bottom cap - glRotatef(180,1,0,0) - gluDisk(self.q, 0, r1, 32, 1) - glRotatef(180,1,0,0) + glRotatef(180, 1, 0, 0) + gluDisk(gluNewQuadric(), 0, r1, 32, 1) + glRotatef(180, 1, 0, 0) # the top cap needs flipped and translated glPushMatrix() - glTranslatef(0,0,z2-z1) - gluDisk(self.q, 0, r2, 32, 1) + glTranslatef(0, 0, z2 - z1) + gluDisk(gluNewQuadric(), 0, r2, 32, 1) glPopMatrix() glPopMatrix() def volume(self): - z1, r1, z2, r2 = self.coords() + z1, r1, z2, r2 = self._get_params() # actually a frustum of a cone - vol = 3.1415927/3.0 * abs(z1-z2)*(r1*r1+r1*r2+r2*r2) - #print "CylinderZ.volume", vol - return vol + return 3.1415927 / 3.0 * abs(z1 - z2) * (r1 * r1 + r1 * r2 + r2 * r2) + + +# give endpoint Y values and radii +# resulting cylinder is on the Y axis +class CylinderY(CylinderZ): + def orient(self): + glRotatef(-90, 1, 0, 0) + + +# give endpoint X values and radii +# resulting cylinder is on the X axis +class CylinderX(CylinderZ): + def orient(self): + glRotatef(90, 0, 1, 0) + + +# Aliases so existing HalCylinder* calls continue working +HalCylinderZ = CylinderZ +HalCylinderY = CylinderY +HalCylinderX = CylinderX + # give center and radius -class Sphere(CoordsBase): +class Sphere(ArgsBase): + def __init__(self, *args): + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) <= 1: + # Legacy subclass pattern overriding coords() + self._dynamic = True + return + + if len(rest) != 4: + raise TypeError( + "%s expects ([prefix,] x_center, y_center, z_center, radius)" + % self.__class__.__name__ + ) + + x_center, y_center, z_center, radius = rest[0], rest[1], rest[2], rest[3] + all_args = (x_center, y_center, z_center, radius) + + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in all_args): + self._dynamic = False + self._static_vals = all_args + else: + self._dynamic = True + ArgsBase.__init__(self, *all_args) + + def _get_params(self): + return self.coords() if self._dynamic else self._static_vals + def draw(self): - x, y, z, r = self.coords() + x, y, z, r = self._get_params() # need to translate the whole thing to x,y,z glPushMatrix() - glTranslatef(x,y,z) + glTranslatef(x, y, z) # the sphere starts out at the origin - gluSphere(self.q, r, 32, 16) + gluSphere(gluNewQuadric(), r, 32, 16) glPopMatrix() def volume(self): - x, y, z, r = self.coords() - vol = 1.3333333*3.1415927*r*r*r - #print "Sphere.volume", vol - return vol + x, y, z, r = self._get_params() + return 1.3333333 * 3.1415927 * r * r * r + + +# Alias so existing HalSphere(...) calls continue working +HalSphere = Sphere # triangular plate in XY plane # specify the corners Z values for each side -class TriangleXY(CoordsBase): +class TriangleXY(ArgsBase): + def __init__(self, *args): + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) <= 1: + # Legacy subclass pattern overriding coords() + self._dynamic = True + return + + if len(rest) != 8: + raise TypeError( + "%s expects ([prefix,] c1_a, c1_b, c2_a, c2_b, c3_a, c3_b, d1, d2)" + % self.__class__.__name__ + ) + + all_args = tuple(rest) + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in all_args): + self._dynamic = False + self._static_vals = all_args + else: + self._dynamic = True + ArgsBase.__init__(self, *all_args) + + def _get_params(self): + return self.coords() if self._dynamic else self._static_vals + def draw(self): - x1, y1, x2, y2, x3, y3, z1, z2 = self.coords() - x12 = x1-x2 - y12 = y1-y2 - x13 = x1-x3 - y13 = y1-y3 - cross = x12*y13 - x13*y12 + x1, y1, x2, y2, x3, y3, z1, z2 = self._get_params() + x12 = x1 - x2 + y12 = y1 - y2 + x13 = x1 - x3 + y13 = y1 - y3 + cross = x12 * y13 - x13 * y12 if cross < 0: - tmp = x2 - x2 = x3 - x3 = tmp - tmp = y2 - y2 = y3 - y3 = tmp + x2, x3 = x3, x2 + y2, y3 = y3, y2 if z1 > z2: - tmp = z1 - z1 = z2 - z2 = tmp - x12 = x1-x2 - y12 = y1-y2 - x23 = x2-x3 - y23 = y2-y3 - x31 = x3-x1 - y31 = y3-y1 + z1, z2 = z2, z1 + + x12 = x1 - x2 + y12 = y1 - y2 + x23 = x2 - x3 + y23 = y2 - y3 + x31 = x3 - x1 + y31 = y3 - y1 + glBegin(GL_QUADS) # side 1-2 - h = hypot(x12,y12) - glNormal3f(-y12/h,x12/h,0) - glVertex3f(x1, y1, z1) - glVertex3f(x2, y2, z1) - glVertex3f(x2, y2, z2) - glVertex3f(x1, y1, z2) + h = hypot(x12, y12) + if h > 0: + glNormal3f(-y12 / h, x12 / h, 0) + glVertex3f(x1, y1, z1) + glVertex3f(x2, y2, z1) + glVertex3f(x2, y2, z2) + glVertex3f(x1, y1, z2) # side 2-3 - h = hypot(x23,y23) - glNormal3f(-y23/h,x23/h,0) - glVertex3f(x2, y2, z1) - glVertex3f(x3, y3, z1) - glVertex3f(x3, y3, z2) - glVertex3f(x2, y2, z2) + h = hypot(x23, y23) + if h > 0: + glNormal3f(-y23 / h, x23 / h, 0) + glVertex3f(x2, y2, z1) + glVertex3f(x3, y3, z1) + glVertex3f(x3, y3, z2) + glVertex3f(x2, y2, z2) # side 3-1 - h = hypot(x31,y31) - glNormal3f(-y31/h,x31/h,0) - glVertex3f(x3, y3, z1) - glVertex3f(x1, y1, z1) - glVertex3f(x1, y1, z2) - glVertex3f(x3, y3, z2) + h = hypot(x31, y31) + if h > 0: + glNormal3f(-y31 / h, x31 / h, 0) + glVertex3f(x3, y3, z1) + glVertex3f(x1, y1, z1) + glVertex3f(x1, y1, z2) + glVertex3f(x3, y3, z2) glEnd() + glBegin(GL_TRIANGLES) # upper face - glNormal3f(0,0,1) + glNormal3f(0, 0, 1) glVertex3f(x1, y1, z2) glVertex3f(x2, y2, z2) glVertex3f(x3, y3, z2) # lower face - glNormal3f(0,0,-1) + glNormal3f(0, 0, -1) glVertex3f(x1, y1, z1) glVertex3f(x3, y3, z1) glVertex3f(x2, y2, z1) glEnd() def volume(self): - x1, y1, x2, y2, x3, y3, z1, z2 = self.coords() + x1, y1, x2, y2, x3, y3, z1, z2 = self._get_params() # compute pts 2 and 3 relative to 1 (puts pt1 at origin) - x2 = x2-x1 - x3 = x3-x1 - y2 = y2-y1 - y3 = y3-y1 + x2 = x2 - x1 + x3 = x3 - x1 + y2 = y2 - y1 + y3 = y3 - y1 # compute area of triangle - area = 0.5*abs(x2*y3 - x3*y2) - thk = abs(z1-z2) - vol = area*thk - #print "TriangleXY.volume = area * thickness)",vol, area, thk - return vol + area = 0.5 * abs(x2 * y3 - x3 * y2) + thk = abs(z1 - z2) + return area * thk + # triangular plate in XZ plane class TriangleXZ(TriangleXY): - def coords(self): - x1, z1, x2, z2, x3, z3, y1, y2 = TriangleXY.coords(self) + def _get_params(self): + x1, z1, x2, z2, x3, z3, y1, y2 = super()._get_params() return x1, z1, x2, z2, x3, z3, -y1, -y2 - + def draw(self): glPushMatrix() - glRotatef(90,1,0,0) - # create the triangle in XY plane + glRotatef(90, 1, 0, 0) TriangleXY.draw(self) - # bottom cap glPopMatrix() - def volume(self): - vol = TriangleXY.volume(self) - #print " TriangleXZ.volume",vol - return vol # triangular plate in YZ plane class TriangleYZ(TriangleXY): - def coords(self): - y1, z1, y2, z2, y3, z3, x1, x2 = TriangleXY.coords(self) + def _get_params(self): + y1, z1, y2, z2, y3, z3, x1, x2 = super()._get_params() return z1, y1, z2, y2, z3, y3, -x1, -x2 - + def draw(self): glPushMatrix() - glRotatef(90,0,-1,0) - # create the triangle in XY plane + glRotatef(90, 0, -1, 0) TriangleXY.draw(self) - # bottom cap glPopMatrix() - def volume(self): - vol = TriangleXY.volume(self) - #print " TriangleYZ.volume",vol - return vol + +# Aliases so existing HalTriangle* calls continue working +HalTriangleXY = TriangleXY +HalTriangleXZ = TriangleXZ +HalTriangleYZ = TriangleYZ -class ArcX(CoordsBase): + +class ArcX(ArgsBase): + def __init__(self, *args): + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) <= 1: + # Legacy subclass pattern overriding coords() + self._dynamic = True + return + + if len(rest) != 7: + raise TypeError("%s expects ([prefix,] x1, x2, r1, r2, a1, a2, steps)" % self.__class__.__name__) + + all_args = tuple(rest) + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in all_args): + self._dynamic = False + self._static_vals = all_args + else: + self._dynamic = True + ArgsBase.__init__(self, *all_args) + + def _get_params(self): + return self.coords() if self._dynamic else self._static_vals + def draw(self): - x1, x2, r1, r2, a1, a2, steps = self.coords() + x1, x2, r1, r2, a1, a2, steps = self._get_params() + steps = max(1, int(steps)) if x1 > x2: - tmp = x1 - x1 = x2 - x2 = tmp + x1, x2 = x2, x1 if r1 > r2: - tmp = r1 - r1 = r2 - r2 = tmp + r1, r2 = r2, r1 while a1 > a2: - a2 = a2 + 360 - astep = ((a2-a1)/steps)*(pi/180) - a1rads = a1 * (pi/180) + a2 += 360 + + astep = ((a2 - a1) / steps) * (pi / 180) + a1rads = a1 * (pi / 180) + # positive X end face glBegin(GL_QUAD_STRIP) - glNormal3f(1,0,0) + glNormal3f(1, 0, 0) n = 0 while n <= steps: - angle = a1rads+n*astep + angle = a1rads + n * astep s = sin(angle) c = cos(angle) - glVertex3f(x2, r1*s, r1*c) - glVertex3f(x2, r2*s, r2*c) - n = n + 1 - + glVertex3f(x2, r1 * s, r1 * c) + glVertex3f(x2, r2 * s, r2 * c) + n += 1 glEnd() + # negative X end face glBegin(GL_QUAD_STRIP) - glNormal3f(-1,0,0) + glNormal3f(-1, 0, 0) n = 0 while n <= steps: - angle = a1rads+n*astep + angle = a1rads + n * astep s = sin(angle) c = cos(angle) - glVertex3f(x1, r1*s, r1*c) - glVertex3f(x1, r2*s, r2*c) - n = n + 1 + glVertex3f(x1, r1 * s, r1 * c) + glVertex3f(x1, r2 * s, r2 * c) + n += 1 glEnd() + # inner diameter glBegin(GL_QUAD_STRIP) n = 0 while n <= steps: - angle = a1rads+n*astep + angle = a1rads + n * astep s = sin(angle) c = cos(angle) - glNormal3f(0,-s, -c) - glVertex3f(x1, r1*s, r1*c) - glVertex3f(x2, r1*s, r1*c) - n = n + 1 + glNormal3f(0, -s, -c) + glVertex3f(x1, r1 * s, r1 * c) + glVertex3f(x2, r1 * s, r1 * c) + n += 1 glEnd() + # outer diameter glBegin(GL_QUAD_STRIP) n = 0 while n <= steps: - angle = a1rads+n*astep + angle = a1rads + n * astep s = sin(angle) c = cos(angle) glNormal3f(0, s, c) - glVertex3f(x1, r2*s, r2*c) - glVertex3f(x2, r2*s, r2*c) - n = n + 1 + glVertex3f(x1, r2 * s, r2 * c) + glVertex3f(x2, r2 * s, r2 * c) + n += 1 glEnd() + # end plates glBegin(GL_QUADS) # first end plate - angle = a1 * (pi/180) + angle = a1 * (pi / 180) s = sin(angle) c = cos(angle) glNormal3f(0, -c, s) - glVertex3f(x1, r2*s, r2*c) - glVertex3f(x2, r2*s, r2*c) - glVertex3f(x2, r1*s, r1*c) - glVertex3f(x1, r1*s, r1*c) - # other end - angle = a2 * (pi/180) + glVertex3f(x1, r2 * s, r2 * c) + glVertex3f(x2, r2 * s, r2 * c) + glVertex3f(x2, r1 * s, r1 * c) + glVertex3f(x1, r1 * s, r1 * c) + # second end plate + angle = a2 * (pi / 180) s = sin(angle) c = cos(angle) glNormal3f(0, c, -s) - glVertex3f(x1, r2*s, r2*c) - glVertex3f(x2, r2*s, r2*c) - glVertex3f(x2, r1*s, r1*c) - glVertex3f(x1, r1*s, r1*c) + glVertex3f(x1, r2 * s, r2 * c) + glVertex3f(x2, r2 * s, r2 * c) + glVertex3f(x2, r1 * s, r1 * c) + glVertex3f(x1, r1 * s, r1 * c) glEnd() def volume(self): - x1, x2, r1, r2, a1, a2, steps = self.coords() - if x1 > x2: - tmp = x1 - x1 = x2 - x2 = tmp - if r1 > r2: - tmp = r1 - r1 = r2 - r2 = tmp - while a1 > a2: - a2 = a2 + 360 - height = x2 - x1 - angle = a2 - a1 - area = (angle/360.0)*pi*(r2*r2-r1*r1) - vol = area * height - #print "Arc.volume = angle * area * height",vol, angle, area, height - return vol - + x1, x2, r1, r2, a1, a2, _ = self._get_params() + if x1 > x2: x1, x2 = x2, x1 + if r1 > r2: r1, r2 = r2, r1 + while a1 > a2: a2 += 360 + return ((a2 - a1) / 360.0) * pi * (r2*r2 - r1*r1) * (x2 - x1) +HalArcX = ArcX # six coordinate version - specify each side of the box -class Box(CoordsBase): +class Box(ArgsBase): + def __init__(self, *args): + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) <= 1: + # Legacy subclass pattern overriding coords() + self._dynamic = True + return + + if len(rest) != 6: + raise TypeError( + "%s expects ([prefix,] x1, y1, z1, x2, y2, z2)" % self.__class__.__name__ + ) + + all_args = tuple(rest) + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in all_args): + self._dynamic = False + self._static_vals = all_args + else: + self._dynamic = True + ArgsBase.__init__(self, *all_args) + + def _get_params(self): + return self.coords() if self._dynamic else self._static_vals + def draw(self): - x1, y1, z1, x2, y2, z2 = self.coords() + x1, y1, z1, x2, y2, z2 = self._get_params() if x1 > x2: - tmp = x1 - x1 = x2 - x2 = tmp + x1, x2 = x2, x1 if y1 > y2: - tmp = y1 - y1 = y2 - y2 = tmp + y1, y2 = y2, y1 if z1 > z2: - tmp = z1 - z1 = z2 - z2 = tmp + z1, z2 = z2, z1 glBegin(GL_QUADS) # bottom face - glNormal3f(0,0,-1) + glNormal3f(0, 0, -1) glVertex3f(x2, y1, z1) glVertex3f(x1, y1, z1) glVertex3f(x1, y2, z1) glVertex3f(x2, y2, z1) # positive X face - glNormal3f(1,0,0) + glNormal3f(1, 0, 0) glVertex3f(x2, y1, z1) glVertex3f(x2, y2, z1) glVertex3f(x2, y2, z2) glVertex3f(x2, y1, z2) # positive Y face - glNormal3f(0,1,0) + glNormal3f(0, 1, 0) glVertex3f(x1, y2, z1) glVertex3f(x1, y2, z2) glVertex3f(x2, y2, z2) glVertex3f(x2, y2, z1) # negative Y face - glNormal3f(0,-1,0) + glNormal3f(0, -1, 0) glVertex3f(x2, y1, z2) glVertex3f(x1, y1, z2) glVertex3f(x1, y1, z1) glVertex3f(x2, y1, z1) # negative X face - glNormal3f(-1,0,0) + glNormal3f(-1, 0, 0) glVertex3f(x1, y1, z1) glVertex3f(x1, y1, z2) glVertex3f(x1, y2, z2) glVertex3f(x1, y2, z1) # top face - glNormal3f(0,0,1) + glNormal3f(0, 0, 1) glVertex3f(x1, y2, z2) glVertex3f(x1, y1, z2) glVertex3f(x2, y1, z2) @@ -1075,393 +1687,161 @@ def draw(self): glEnd() def volume(self): - x1, y1, z1, x2, y2, z2 = self.coords() - vol = abs((x1-x2)*(y1-y2)*(z1-z2)) - #print "Box.volume", vol - return vol + x1, y1, z1, x2, y2, z2 = self._get_params() + return abs((x1 - x2) * (y1 - y2) * (z1 - z2)) # specify the width in X and Y, and the height in Z # the box is centered on the origin class BoxCentered(Box): - def __init__(self, xw, yw, zw): - Box.__init__(self, -xw/2.0, -yw/2.0, -zw/2.0, xw/2.0, yw/2.0, zw/2.0) + def __init__(self, *args): + self.prefix, rest = _split_optional_prefix(self, args) + + if len(rest) == 0: + # Legacy subclass pattern overriding coords() + self._dynamic = True + return + + if len(rest) != 3: + raise TypeError( + "%s expects ([prefix,] xw, yw, zw)" % self.__class__.__name__ + ) + + xw, yw, zw = rest + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in (xw, yw, zw)): + self._dynamic = False + self._static_vals = (-xw / 2.0, -yw / 2.0, -zw / 2.0, xw / 2.0, yw / 2.0, zw / 2.0) + else: + self._dynamic = True + ArgsBase.__init__(self, xw, yw, zw) + + def _get_params(self): + if not self._dynamic: + return self._static_vals + xw, yw, zw = self.coords() + return (-xw / 2.0, -yw / 2.0, -zw / 2.0, xw / 2.0, yw / 2.0, zw / 2.0) + # specify the width in X and Y, and the height in Z # the box is centered in X and Y, and runs from Z=0 up # (or down) to the specified Z value class BoxCenteredXY(Box): - def __init__(self, xw, yw, zw): - Box.__init__(self, -xw/2.0, -yw/2.0, 0, xw/2.0, yw/2.0, zw) - -# capture current transformation matrix -# note that this transforms from the current coordinate system -# to the viewport system, NOT to the world system -class Capture(object): - def __init__(self): - self.t = [] + def __init__(self, *args): + self.prefix, rest = _split_optional_prefix(self, args) - def capture(self): - self.t = glGetDoublev(GL_MODELVIEW_MATRIX) - - def volume(self): - return 0.0 + if len(rest) == 0: + # Legacy subclass pattern overriding coords() + self._dynamic = True + return -# function to invert a transform matrix -# based on http://steve.hollasch.net/cgindex/math/matrix/afforthinv.c -# with simplifications since we don't do scaling + if len(rest) != 3: + raise TypeError( + "%s expects ([prefix,] xw, yw, zw)" % self.__class__.__name__ + ) -# This function inverts a 4x4 matrix that is affine and orthogonal. In -# other words, the perspective components are [0 0 0 1], and the basis -# vectors are orthogonal to each other. In addition, the matrix must -# not do scaling + xw, yw, zw = rest + if self.prefix is None and not any(isinstance(arg, (str, list, tuple)) for arg in (xw, yw, zw)): + self._dynamic = False + self._static_vals = (-xw / 2.0, -yw / 2.0, 0, xw / 2.0, yw / 2.0, zw) + else: + self._dynamic = True + ArgsBase.__init__(self, xw, yw, zw) -def invert(src): - # make a copy - inv=copy.deepcopy(src) - # The inverse of the upper 3x3 is the transpose (since the basis - # vectors are orthogonal to each other. - inv[0][1],inv[1][0] = inv[1][0],inv[0][1] - inv[0][2],inv[2][0] = inv[2][0],inv[0][2] - inv[1][2],inv[2][1] = inv[2][1],inv[1][2] - # The inverse of the translation component is just the negation - # of the translation after dotting with the new upper3x3 rows. */ - inv[3][0] = -(src[3][0]*inv[0][0] + src[3][1]*inv[1][0] + src[3][2]*inv[2][0]) - inv[3][1] = -(src[3][0]*inv[0][1] + src[3][1]*inv[1][1] + src[3][2]*inv[2][1]) - inv[3][2] = -(src[3][0]*inv[0][2] + src[3][1]*inv[1][2] + src[3][2]*inv[2][2]) - return inv - -# head up display - draws a semi-transparent text box. -class Hud(object): - def __init__(self, showme=1): - self.app = [] - self.strs = [] - self.messages = [] - self.fontbase = [] - self.hud_lines = [] - self.show_tags = [] - self.hide_alls = [] - self.hud_rgba_r = 0 - self.hud_rgba_g = 0.2 - self.hud_rgba_b = 0 - self.hud_rgba_a = 0.5 - self.hud_text_rgb_r = 1 - self.hud_text_rgb_g = 0.8 - self.hud_text_rgb_b = 0.4 - self.hide_hud = showme == 0 - - # legacy function, unconditionally hides the overlay - def hide(self): - self.hide_hud = True - - # legacy function, no longer supported, use add_txt() with a tag instead - def clear(self): - print("vismach.py, clear() deprecated, use add_txt() with a tag instead ") - - # legacy vismach models used this - def show(self, string): - self.hide_hud = False - self.add_txt(string) - - # displays a string, optionally a tag or list of tags can be assigned - def add_txt(self, string, tag=None): - self.hud_lines += [[str(string), None, tag]] - - # displays a formatted pin value (can be embedded in a string) - def add_pin(self, string, pin=None, tag=None): - self.hud_lines += [[str(string), pin, tag]] - - # shows all lines with the specified tag if the pin value = val - def show_tag_if_same(self, tag, pin, val=True): - self.show_tags += [[tag, pin, val]] - - # shows all lines with a tag equal to the pin value + offset - def show_tags_in_pin(self, pin, offs=0): - self.show_tags += [[pin, None, offs]] - - # hides the complete hud if the pin value is equal to val - def hide_all(self, pin, val=True): - self.hide_alls += [[pin, val]] - - # changes the hud color and transparency - def set_hud_rgba(self, r, g, b, a): - self.hud_rgba_r = r - self.hud_rgba_g = g - self.hud_rgba_b = b - self.hud_rgba_a = a - - # changes the hud text color - def set_hud_text_rgb(self, r, g, b): - self.hud_text_rgb_r = r - self.hud_text_rgb_g = g - self.hud_text_rgb_b = b - - # update the lines in the hud using the lists created above - def draw(self): - messages = [] - show_list = [None] - # check if hud should be hidden - hide_hud_requested = False - for a in self.hide_alls: - if hal.get_value(a[0]) == a[1]: - hide_hud_requested = True - if not self.hide_hud and not hide_hud_requested: - # create list of all line tags to be shown - for b in self.show_tags: - tag = None - if b[1] == None: # _show_tags_in_pin - tag = int(hal.get_value(b[0]) + b[2]) - else: # _show_tag_if_same - if hal.get_value(b[1]) == b[2]: - tag = b[0] - if not isinstance(tag, list): - tag = [tag] - if tag is not None: - show_list = show_list + tag - # build the - for c in self.hud_lines: - if not isinstance(c[2], list): - c[2] = [c[2]] - if any(item in c[2] for item in show_list): - if c[1] == None: # _txt - messages += [c[0]] - else: # _pin - messages += [c[0].format(hal.get_value(c[1]))] - drawtext = self.strs + messages - - # draw head-up-display - # see axis.py for more font/color configurability - if len(drawtext) == 0: - return - - glMatrixMode(GL_PROJECTION) - glPushMatrix() - glLoadIdentity() - - if not self.fontbase: - self.fontbase = int(self.app.loadbitmapfont("9x15")) - char_width, char_height = 9, 15 - xmargin,ymargin = 5,5 - ypos = float(self.app.winfo_height()) - - glOrtho(0.0, self.app.winfo_width(), 0.0, ypos, -1.0, 1.0) - glMatrixMode(GL_MODELVIEW) - glPushMatrix() - glLoadIdentity() - - # draw the text box - maxlen = max([len(p) for p in drawtext]) - box_width = maxlen * char_width - glDepthFunc(GL_ALWAYS) - glDepthMask(GL_FALSE) - glDisable(GL_LIGHTING) - glEnable(GL_BLEND) - glEnable(GL_NORMALIZE) - glBlendFunc(GL_ONE, GL_CONSTANT_ALPHA) - # sets the color of the hud overlay - glColor3f(self.hud_rgba_r, self.hud_rgba_g, self.hud_rgba_b) - # rgba, sets the transparency of the overlay using the 'a' value - glBlendColor(0,0,0,self.hud_rgba_a) - glBegin(GL_QUADS) - glVertex3f(0, ypos, 1) #upper left - glVertex3f(0, ypos - 2*ymargin - char_height*len(drawtext), 1) #lower left - glVertex3f(box_width+2*xmargin, ypos - 2*ymargin - char_height*len(drawtext), 1) #lower right - glVertex3f(box_width+2*xmargin, ypos , 1) #upper right - glEnd() - glDisable(GL_BLEND) - glEnable(GL_LIGHTING) - - # fill the box with text - maxlen = 0 - ypos -= char_height+ymargin - i = 0 - glDisable(GL_LIGHTING) - # sets the color of the text in the hud - glColor3f(self.hud_text_rgb_r, self.hud_text_rgb_g, self.hud_text_rgb_b) - for string in drawtext: - maxlen = max(maxlen, len(string)) - glRasterPos2i(xmargin, int(ypos)) - for char in string: - glCallList(self.fontbase + ord(char)) - ypos -= char_height - i = i + 1 - glDepthFunc(GL_LESS) - glDepthMask(GL_TRUE) - glEnable(GL_LIGHTING) - - glPopMatrix() - glMatrixMode(GL_PROJECTION) - glPopMatrix() - glMatrixMode(GL_MODELVIEW) + def _get_params(self): + if not self._dynamic: + return self._static_vals + xw, yw, zw = self.coords() + return (-xw / 2.0, -yw / 2.0, 0, xw / 2.0, yw / 2.0, zw) -class O(rs274.OpenGLTk.Opengl): - def __init__(self, *args, **kw): - rs274.OpenGLTk.Opengl.__init__(self, *args, **kw) - self.r_back = self.g_back = self.b_back = 0 - #self.q1 = gluNewQuadric() - #self.q2 = gluNewQuadric() - #self.q3 = gluNewQuadric() - self.plotdata = [] - self.plotlen = 16000 - #does not show HUD by default - self.hud = Hud() +# Aliases so existing HalBox* calls continue working +HalBox = Box +HalBoxCentered = BoxCentered +HalBoxCenteredXY = BoxCenteredXY - def basic_lighting(self): - self.activate() - glLightfv(GL_LIGHT0, GL_POSITION, (1, -1, .5, 0)) - glLightfv(GL_LIGHT0, GL_AMBIENT, (.2,.2,.2,0)) - glLightfv(GL_LIGHT0, GL_DIFFUSE, (.6,.6,.4,0)) - glLightfv(GL_LIGHT0+1, GL_POSITION, (-1, -1, .5, 0)) - glLightfv(GL_LIGHT0+1, GL_AMBIENT, (.0,.0,.0,0)) - glLightfv(GL_LIGHT0+1, GL_DIFFUSE, (.0,.0,.4,0)) - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, (1,1,1,0)) - glDisable(GL_CULL_FACE) - glEnable(GL_LIGHTING) - glEnable(GL_LIGHT0) - glEnable(GL_LIGHT0+1) - glDepthFunc(GL_LESS) - glEnable(GL_DEPTH_TEST) - glMatrixMode(GL_MODELVIEW) - glLoadIdentity() - - - def redraw(self, *args): - if self.winfo_width() == 1: return - self.model.traverse() - # current coords: world - # the matrices tool2view, work2view, and world2view - # transform from tool/work/world coords to viewport coords - # if we want to draw in tool coords, we need to do - # "tool -> view -> world" (since the current frame is world) - # and if we want to draw in work coords, we need - # "work -> view -> world". For both, we need to invert - # the world2view matrix to do the second step - view2world = invert(self.world2view.t) - # likewise, for backplot, we want to transform the tooltip - # position from tool coords (where it is [0,0,0]) to work - # coords, so we need tool -> view -> work - # so lets also invert the work2view matrix - view2work = invert(self.work2view.t) - - # since backplot lines only need vertices, not orientation, - # and the tooltip is at the origin, getting the tool coords - # is easy - tx, ty, tz = self.tool2view.t[3][:3] - # now we have to transform them to the work frame - wx = tx*view2work[0][0]+ty*view2work[1][0]+tz*view2work[2][0]+view2work[3][0] - wy = tx*view2work[0][1]+ty*view2work[1][1]+tz*view2work[2][1]+view2work[3][1] - wz = tx*view2work[0][2]+ty*view2work[1][2]+tz*view2work[2][2]+view2work[3][2] - # wx, wy, wz are the values to use for backplot - # so we save them in a buffer - if len(self.plotdata) == self.plotlen: - del self.plotdata[:self.plotlen / 10] - point = [ wx, wy, wz ] - if not self.plotdata or point != self.plotdata[-1]: - self.plotdata.append(point) - - # now lets draw something in the tool coordinate system - #glPushMatrix() - # matrixes take effect in reverse order, so the next - # two lines do "tool -> view -> world" - #glMultMatrixd(view2world) - #glMultMatrixd(self.tool2view.t) - - # do drawing here - # cylinder normally goes to +Z, we want it down - #glTranslatef(0,0,-60) - #gluCylinder(self.q1, 20, 20, 60, 32, 16) - - # back to world coords - #glPopMatrix() - - - # we can also draw in the work coord system - glPushMatrix() - # "work -> view -> world" - glMultMatrixd(view2world) - glMultMatrixd(self.work2view.t) - # now we can draw in work coords, and whatever we draw - # will move with the work, (if the work is attached to - # a table or indexer or something that moves with - # respect to the world - - # just a test object, sitting on the table - #gluCylinder(self.q2, 40, 20, 60, 32, 16) - - #draw head up display - if(hasattr(self.hud, "draw")): - self.hud.draw() - - # draw backplot - glDisable(GL_LIGHTING) - glLineWidth(2) - glColor3f(1.0,0.5,0.5) +class AsciiSTL(ArgsBase): + def __init__(self, *args, **kwargs): + self.list = None + self.explicit_path = None + self.old_filepath = None + self.error_path = None - glBegin(GL_LINE_STRIP) - for p in self.plotdata: - glVertex3f(*p) - glEnd() + self.prefix, rest = _split_optional_prefix(self, args) - glEnable(GL_LIGHTING) - glColor3f(1,1,1) - glLineWidth(1) - glDisable(GL_BLEND) - glDepthFunc(GL_LESS) + filename = rest[0] if len(rest) >= 1 else kwargs.get("filename", None) + path = rest[1] if len(rest) >= 2 else kwargs.get("path", "") + data = rest[2] if len(rest) >= 3 else kwargs.get("data", None) - # back to world again - glPopMatrix() + if len(rest) > 3: + raise TypeError("AsciiSTL expects ([prefix,] filename=None, path='', data=None)") - def plotclear(self): - del self.plotdata[:self.plotlen] + # 1. Raw STL string data passed directly + if data is not None: + self.explicit_path = "" + self.load(None, data) + return -class Color(Collection): - def __init__(self, color, parts): - self.color = color - Collection.__init__(self, parts) + # 2. Check if filename (or path + filename) points to an existing static file + if isinstance(filename, str): + candidate = os.path.join(path, filename) if (path and isinstance(path, str)) else filename + if os.path.isfile(candidate): + self.explicit_path = candidate + self.load(self.explicit_path, None) + return - def apply(self): - glPushAttrib(GL_LIGHTING_BIT) - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, self.color) + # 3. Dynamic filename/path driven by HAL pin or linuxcnc.stat attribute + if filename is None: + raise ValueError("AsciiSTL requires either a valid file path, raw data, or a dynamic pin/attribute") - def unapply(self): - glPopAttrib() + # Keep path as a literal string unless it contains a dynamic expression + path_arg = path if (isinstance(path, str) and ("{" in path or "." in path)) else [path] + ArgsBase.__init__(self, filename, path_arg) -class AsciiSTL: - def __init__(self, filename=None, data=None): + def load(self, filename, data): if data is None: - data = open(filename, "r") + with open(filename, "r") as f: + lines = f.readlines() elif isinstance(data, str): - data = data.split("\n") - self.list = None + lines = data.splitlines() + else: + lines = data + + if self.list is not None: + glDeleteLists(self.list, 1) + self.list = None + t = [] - n = [0,0,0] + n = [0, 0, 0] self.d = d = [] - for line in data: - if line.find("normal") != -1: - line = line.split() - x, y, z = list(map(float, line[-3:])) - n = [x,y,z] - elif line.find("vertex") != -1: - line = line.split() - x, y, z = list(map(float, line[-3:])) - t.append([x,y,z]) + for line in lines: + if "normal" in line: + parts = line.split() + x, y, z = map(float, parts[-3:]) + n = [x, y, z] + elif "vertex" in line: + parts = line.split() + x, y, z = map(float, parts[-3:]) + t.append([x, y, z]) if len(t) == 3: - if n == [0,0,0]: + if not any(n): dx1 = t[1][0] - t[0][0] dy1 = t[1][1] - t[0][1] dz1 = t[1][2] - t[0][2] dx2 = t[2][0] - t[0][0] dy2 = t[2][1] - t[0][1] dz2 = t[2][2] - t[0][2] - n = [dy1*dz2 - dy2*dz1, dz1*dx2 - dz2*dx1, dy1*dx2 - dy2*dx1] + n = [ + dy1 * dz2 - dy2 * dz1, + dz1 * dx2 - dz2 * dx1, + dy1 * dx2 - dy2 * dx1, + ] d.append((n, t)) t = [] - n = [0,0,0] + n = [0, 0, 0] - def draw(self): + def _draw_list(self): if self.list is None: # OpenGL isn't ready yet in __init__ so the display list # is created during the first draw @@ -1478,18 +1858,98 @@ def draw(self): del self.d glCallList(self.list) -class AsciiOBJ: - def __init__(self, filename=None, data=None): + def draw(self): + if self.explicit_path is not None: + self._draw_list() + return + + filename, path = self.coords() + if isinstance(path, list): + path = path[0] + + fname_str = str(filename) + if not fname_str.lower().endswith(".stl"): + fname_str += ".stl" + + self.filepath = os.path.join(path, fname_str) if path else fname_str + + if self.filepath != self.old_filepath: + self.old_filepath = self.filepath + if not os.path.isfile(self.filepath): + if self.filepath != self.error_path: + print("Vismach Error: Unable to read file", self.filepath) + self.error_path = self.filepath + else: + self.load(self.filepath, None) + self.error_path = None + + if self.error_path is None: + self._draw_list() + + +# Alias so existing HalAsciiSTL(...) calls continue working +HalAsciiSTL = AsciiSTL + + + + +class AsciiOBJ(ArgsBase): + def __init__(self, *args, **kwargs): + self.list = None + self.explicit_path = None + self.old_filepath = None + self.error_path = None + + self.prefix, rest = _split_optional_prefix(self, args) + + filename = rest[0] if len(rest) >= 1 else kwargs.get("filename", None) + path = rest[1] if len(rest) >= 2 else kwargs.get("path", "") + data = rest[2] if len(rest) >= 3 else kwargs.get("data", None) + + if len(rest) > 3: + raise TypeError("AsciiOBJ expects ([prefix,] filename=None, path='', data=None)") + + # 1. Raw OBJ string data passed directly + if data is not None: + self.explicit_path = "" + self.load(None, data) + return + + # 2. Check if filename (or path + filename) points to an existing static file + if isinstance(filename, str): + candidate = os.path.join(path, filename) if (path and isinstance(path, str)) else filename + if os.path.isfile(candidate): + self.explicit_path = candidate + self.load(self.explicit_path, None) + return + + # 3. Dynamic filename/path driven by HAL pin or linuxcnc.stat attribute + if filename is None: + raise ValueError("AsciiOBJ requires either a valid file path, raw data, or a dynamic pin/attribute") + + # Keep path as a literal string unless it contains a dynamic expression + path_arg = path if (isinstance(path, str) and ("{" in path or "." in path)) else [path] + ArgsBase.__init__(self, filename, path_arg) + + def load(self, filename, data): if data is None: - data = open(filename, "r") + with open(filename, "r") as f: + lines = f.readlines() elif isinstance(data, str): - data = data.split("\n") + lines = data.splitlines() + else: + lines = data + + if self.list is not None: + glDeleteLists(self.list, 1) + self.list = None self.v = v = [] self.vn = vn = [] self.f = f = [] - for line in data: - if line.startswith("#"): continue + for line in lines: + if line.startswith("#"): + continue if line.startswith("vn"): vn.append([float(w) for w in line.split()[1:]]) elif line.startswith("v"): @@ -1497,15 +1957,9 @@ def __init__(self, filename=None, data=None): elif line.startswith("f"): f.append(self.parse_face(line)) -# print v[:5] -# print vn[:5] -# print f[:5] - - self.list = None - - def parse_int(self, i): - if i == '': return None + if i == '': + return None return int(i) def parse_slash(self, word): @@ -1514,7 +1968,7 @@ def parse_slash(self, word): def parse_face(self, line): return [self.parse_slash(w) for w in line.split()[1:]] - def draw(self): + def _draw_list(self): if self.list is None: # OpenGL isn't ready yet in __init__ so the display list # is created during the first draw @@ -1522,12 +1976,11 @@ def draw(self): glNewList(self.list, GL_COMPILE) glDisable(GL_CULL_FACE) glBegin(GL_TRIANGLES) - #print "obj", len(self.f) - for f in self.f: - for v, t, n in f: + for face in self.f: + for v, t, n in face: if n: - glNormal3f(*self.vn[n-1]) - glVertex3f(*self.v[v-1]) + glNormal3f(*self.vn[n - 1]) + glVertex3f(*self.v[v - 1]) glEnd() glEndList() del self.v @@ -1535,17 +1988,442 @@ def draw(self): del self.f glCallList(self.list) + def draw(self): + if self.explicit_path is not None: + self._draw_list() + return + + filename, path = self.coords() + if isinstance(path, list): + path = path[0] -old_plotclear = False + fname_str = str(filename) + if not fname_str.lower().endswith(".obj"): + fname_str += ".obj" -def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0): - app = tkinter.Tk() - import nf - hidpi = nf.init_hidpi(app) + self.filepath = os.path.join(path, fname_str) if path else fname_str + + if self.filepath != self.old_filepath: + self.old_filepath = self.filepath + if not os.path.isfile(self.filepath): + if self.filepath != self.error_path: + print("Vismach Error: Unable to read file", self.filepath) + self.error_path = self.filepath + else: + self.load(self.filepath, None) + self.error_path = None + + if self.error_path is None: + self._draw_list() + + +# Alias so existing HalAsciiOBJ(...) calls continue working +HalAsciiOBJ = AsciiOBJ + + +class Capture(object): + """Captures the current OpenGL GL_MODELVIEW_MATRIX during scene traversal. + Note: The captured matrix transforms from the local coordinate system + into viewport/camera space, not directly into world space.""" + + def __init__(self): + self.t = [] + self.tracked_parts = [self] + + def capture(self): + self.t = glGetDoublev(GL_MODELVIEW_MATRIX) + + def world_pos(self, world=None): + """Returns the captured [x, y, z] position in world coordinates + if a root 'world' Capture() is passed, or raw view coordinates otherwise.""" + if len(self.t) < 4: + return [0.0, 0.0, 0.0] + _, _, _, row3 = self.t + px, py, pz = row3[:3] + if world is None or len(world.t) < 4: + return [px, py, pz] + inv_r0, inv_r1, inv_r2, inv_r3 = invert(world.t) + m00, m01, m02, _ = inv_r0 + m10, m11, m12, _ = inv_r1 + m20, m21, m22, _ = inv_r2 + m30, m31, m32, _ = inv_r3 + wx = px * m00 + py * m10 + pz * m20 + m30 + wy = px * m01 + py * m11 + pz * m21 + m31 + wz = px * m02 + py * m12 + pz * m22 + m32 + return [wx, wy, wz] + + + def volume(self): + return 0.0 + +def invert(src): + """Inverts an affine, orthogonal 4x4 matrix (including uniform or axis scaling).""" + row0, row1, row2, row3 = src + m00, m01, m02, _ = row0 + m10, m11, m12, _ = row1 + m20, m21, m22, _ = row2 + tx, ty, tz, _ = row3 + + # Transpose upper 3x3 and normalize by squared basis vector lengths + l0 = 1.0 / (m00 * m00 + m01 * m01 + m02 * m02) + r00 = l0 * m00 + r10 = l0 * m01 + r20 = l0 * m02 + + l1 = 1.0 / (m10 * m10 + m11 * m11 + m12 * m12) + r01 = l1 * m10 + r11 = l1 * m11 + r21 = l1 * m12 + + l2 = 1.0 / (m20 * m20 + m21 * m21 + m22 * m22) + r02 = l2 * m20 + r12 = l2 * m21 + r22 = l2 * m22 + + # Negate translation dotted with the inverted upper 3x3 + r30 = -(tx * r00 + ty * r10 + tz * r20) + r31 = -(tx * r01 + ty * r11 + tz * r21) + r32 = -(tx * r02 + ty * r12 + tz * r22) + + return [ + [r00, r01, r02, 0.0], + [r10, r11, r12, 0.0], + [r20, r21, r22, 0.0], + [r30, r31, r32, 1.0], + ] + + + +class Hud(ArgsBase): + def __init__(self, showme=1): + self.app = [] + self.strs = [] + self.messages = [] + self.fontbase = [] + self.hud_lines = [] + self.show_tags = [] + self.hide_alls = [] + self._rgba_getters = (lambda: 0, lambda: 0.2, lambda: 0, lambda: 0.5) + self._text_rgb_getters = (lambda: 1, lambda: 0.8, lambda: 0.4) + self._showme_getter = self._compile_value(showme, prefix=None) + + def _resolve_hud_prefix(self, pin, prefix): + """Resolves legacy full HAL pin names ('comp-name.pin') and bare pin names.""" + if prefix is not None or not isinstance(pin, str) or "{" in pin: + return prefix + if "." not in pin: + return hal + comp_name = pin.split(".", 1)[0] + if hal.component_is_ready(comp_name): + return hal + return None + + def _compile_value(self, val, prefix=None): + """Compiles a static value, pin/attribute, or expression into a zero-arg callable. + Prints a clear diagnostic message instead of crashing if a prefix or pin is invalid.""" + if not isinstance(val, (str, list, tuple)): + return lambda v=val: v + try: + helper = ArgsBase.__new__(ArgsBase) + helper.prefix = check_prefix(helper, prefix) if prefix is not None else None + ArgsBase.__init__(helper, val) + return helper._evaluators[0] + except Exception as e: + print( + f"Vismach HUD Warning: Could not bind '{val}' ({e}). " + f"Use 'hal..', 'c.', or pass prefix=hal/c/s." + ) + return lambda: 0 + + # legacy function, unconditionally hides the overlay + def hide(self): + self._showme_getter = lambda: 0 + + # legacy function, no longer supported, use add_txt() with a tag instead + def clear(self): + print("vismach.py, Hud.clear() deprecated, use add_txt() with a tag instead ") + + # legacy vismach models used this + def show(self, string): + self._showme_getter = lambda: 1 + self.add_txt(string) + + # displays a string, optionally a tag or list of tags can be assigned + def add_txt(self, string, tag=None): + self.hud_lines.append((str(string), None, tag)) + + # displays a formatted pin or status value (can be embedded in a string) + def add_pin(self, string, pin=None, tag=None, prefix=None): + if pin is None: + self.hud_lines.append((str(string), None, tag)) + return + + eff_prefix = self._resolve_hud_prefix(pin, prefix) + getter = self._compile_value(pin, prefix=eff_prefix) + self.hud_lines.append((str(string), getter, tag)) + + # shows all lines with the specified tag if the pin/expression value == val + def show_tag_if_same(self, tag, pin, val=True, prefix=None): + eff_prefix = self._resolve_hud_prefix(pin, prefix) + pin_getter = self._compile_value(pin, prefix=eff_prefix) + val_getter = self._compile_value(val, prefix=prefix) + self.show_tags.append(("if_same", tag, pin_getter, val_getter)) + + # shows all lines with a tag equal to the pin/expression value + offset + def show_tags_in_pin(self, pin, offs=0, prefix=None): + eff_prefix = self._resolve_hud_prefix(pin, prefix) + pin_getter = self._compile_value(pin, prefix=eff_prefix) + offs_getter = self._compile_value(offs, prefix=prefix) + self.show_tags.append(("in_pin", None, pin_getter, offs_getter)) + + # hides the complete hud if the pin/expression value is equal to val + def hide_all(self, pin, val=True, prefix=None): + eff_prefix = self._resolve_hud_prefix(pin, prefix) + pin_getter = self._compile_value(pin, prefix=eff_prefix) + val_getter = self._compile_value(val, prefix=prefix) + self.hide_alls.append((pin_getter, val_getter)) + + # changes the hud color and transparency (supports static numbers or dynamic expressions) + def set_hud_rgba(self, r, g, b, a, prefix=None): + self._rgba_getters = tuple(self._compile_value(c, prefix=prefix) for c in (r, g, b, a)) + + # changes the hud text color (supports static numbers or dynamic expressions) + def set_hud_text_rgb(self, r, g, b, prefix=None): + self._text_rgb_getters = tuple(self._compile_value(c, prefix=prefix) for c in (r, g, b)) + + # update the lines in the hud using the lists created above + def draw(self): + if self._showme_getter() == 0: + return + + for pin_getter, val_getter in self.hide_alls: + if pin_getter() == val_getter(): + return + + messages = [] + show_list = [None] + + # create list of all line tags to be shown + for mode, tag, pin_getter, param_getter in self.show_tags: + active_tag = None + if mode == "in_pin": + active_tag = int(pin_getter() + param_getter()) + elif pin_getter() == param_getter(): + active_tag = tag + + if active_tag is not None: + if isinstance(active_tag, list): + show_list.extend(active_tag) + else: + show_list.append(active_tag) + + # create list of message lines to be shown + for string, getter, tag in self.hud_lines: + tag_list = tag if isinstance(tag, list) else [tag] + if any(item in tag_list for item in show_list): + if getter is None: + messages.append(string) + else: + val = getter() + if isinstance(val, tuple): + messages.append(string.format(*val)) + else: + messages.append(string.format(val)) + + drawtext = self.strs + messages + if not drawtext: + return + + # draw head-up-display + glMatrixMode(GL_PROJECTION) + glPushMatrix() + glLoadIdentity() + + if not self.fontbase: + self.fontbase = int(self.app.loadbitmapfont("9x15")) + char_width, char_height = 9, 15 + xmargin, ymargin = 5, 5 + ypos = float(self.app.winfo_height()) + + glOrtho(0.0, self.app.winfo_width(), 0.0, ypos, -1.0, 1.0) + glMatrixMode(GL_MODELVIEW) + glPushMatrix() + glLoadIdentity() + + # draw the text box + maxlen = max(len(p) for p in drawtext) + box_width = maxlen * char_width + glDepthFunc(GL_ALWAYS) + glDepthMask(GL_FALSE) + glDisable(GL_LIGHTING) + glEnable(GL_BLEND) + glEnable(GL_NORMALIZE) + glBlendFunc(GL_ONE, GL_CONSTANT_ALPHA) + + r, g, b, a = (fn() for fn in self._rgba_getters) + glColor3f(r, g, b) + glBlendColor(0, 0, 0, a) + glBegin(GL_QUADS) + glVertex3f(0, ypos, 1) # upper left + glVertex3f(0, ypos - 2 * ymargin - char_height * len(drawtext), 1) # lower left + glVertex3f(box_width + 2 * xmargin, ypos - 2 * ymargin - char_height * len(drawtext), 1) # lower right + glVertex3f(box_width + 2 * xmargin, ypos, 1) # upper right + glEnd() + glDisable(GL_BLEND) + glEnable(GL_LIGHTING) + + # fill the box with text + ypos -= char_height + ymargin + glDisable(GL_LIGHTING) + tr, tg, tb = (fn() for fn in self._text_rgb_getters) + glColor3f(tr, tg, tb) + for string in drawtext: + glRasterPos2i(xmargin, int(ypos)) + for char in string: + glCallList(self.fontbase + ord(char)) + ypos -= char_height + glDepthFunc(GL_LESS) + glDepthMask(GL_TRUE) + glEnable(GL_LIGHTING) + + glPopMatrix() + glMatrixMode(GL_PROJECTION) + glPopMatrix() + glMatrixMode(GL_MODELVIEW) - # Togl's default 400x400 is in device pixels; scale it for HiDPI. - t = O(app, double=1, depth=1, - width=int(round(400 * hidpi)), height=int(round(400 * hidpi))) + + + + +class O(rs274.OpenGLTk.Opengl): + def __init__(self, *args, **kw): + rs274.OpenGLTk.Opengl.__init__(self, *args, **kw) + self.r_back = self.g_back = self.b_back = 0 + #self.q1 = gluNewQuadric() + #self.q2 = gluNewQuadric() + #self.q3 = gluNewQuadric() + self.plotdata = [] + self.plotlen = 16000 + #does not show HUD by default + self.hud = Hud() + + def basic_lighting(self): + self.activate() + glLightfv(GL_LIGHT0, GL_POSITION, (1, -1, .5, 0)) + glLightfv(GL_LIGHT0, GL_AMBIENT, (.2,.2,.2,0)) + glLightfv(GL_LIGHT0, GL_DIFFUSE, (.6,.6,.4,0)) + glLightfv(GL_LIGHT0+1, GL_POSITION, (-1, -1, .5, 0)) + glLightfv(GL_LIGHT0+1, GL_AMBIENT, (.0,.0,.0,0)) + glLightfv(GL_LIGHT0+1, GL_DIFFUSE, (.0,.0,.4,0)) + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, (1,1,1,0)) + glDisable(GL_CULL_FACE) + glEnable(GL_LIGHTING) + glEnable(GL_LIGHT0) + glEnable(GL_LIGHT0+1) + glDepthFunc(GL_LESS) + glEnable(GL_DEPTH_TEST) + glMatrixMode(GL_MODELVIEW) + glLoadIdentity() + + def redraw(self, *args): + global _stats_fresh + if self.winfo_width() == 1: + return + + # Poll registered linuxcnc.stat instances if this redraw was triggered + # by mouse navigation rather than the 100ms update() timer + poll_all_stats() + _stats_fresh = False + + self.model.traverse() + + # Ensure world2view, work2view, and tool2view have been captured + if len(self.world2view.t) < 4 or len(self.work2view.t) < 4: + return + + view2world = invert(self.world2view.t) + view2work = invert(self.work2view.t) + + # Only record new backplot points if tool2view was captured in this frame + if len(self.tool2view.t) >= 4: + w_row0, w_row1, w_row2, w_row3 = view2work + w00, w01, w02, _ = w_row0 + w10, w11, w12, _ = w_row1 + w20, w21, w22, _ = w_row2 + w30, w31, w32, _ = w_row3 + + _, _, _, t_row3 = self.tool2view.t + tx, ty, tz, _ = t_row3 + wx = tx * w00 + ty * w10 + tz * w20 + w30 + wy = tx * w01 + ty * w11 + tz * w21 + w31 + wz = tx * w02 + ty * w12 + tz * w22 + w32 + + if len(self.plotdata) == self.plotlen: + del self.plotdata[:self.plotlen // 10] + point = [wx, wy, wz] + if not self.plotdata or point != self.plotdata[-1]: + self.plotdata.append(point) + + # Draw in the work coord system ("work -> view -> world") + glPushMatrix() + glMultMatrixd(view2world) + glMultMatrixd(self.work2view.t) + + # Draw head-up display + if hasattr(self.hud, "draw"): + self.hud.draw() + + # Draw backplot + glDisable(GL_LIGHTING) + glLineWidth(2) + glColor3f(1.0, 0.5, 0.5) + + glBegin(GL_LINE_STRIP) + for p in self.plotdata: + glVertex3f(*p) + glEnd() + + glEnable(GL_LIGHTING) + glColor3f(1, 1, 1) + glLineWidth(1) + glDisable(GL_BLEND) + glDepthFunc(GL_LESS) + + # Back to world again + glPopMatrix() + + + def plotclear(self): + del self.plotdata[:self.plotlen] + + +def _register_stats_from_callable(func): + """Finds and registers any linuxcnc.stat instances referenced by a user callback.""" + if func is None or not callable(func): + return + + # 1. Check module globals accessible to the callback + func_globals = getattr(func, "__globals__", {}) + for val in func_globals.values(): + if isinstance(val, linuxcnc.stat): + _registered_stats.add(val) + + # 2. Check closure variables (if the callback was defined inside another function) + closures = getattr(func, "__closure__", None) + if closures: + for cell in closures: + try: + val = cell.cell_contents + if isinstance(val, linuxcnc.stat): + _registered_stats.add(val) + except ValueError: + pass + + +def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0, function=None): + _register_stats_from_callable(function) + app = tkinter.Tk() + t = O(app, double=1, depth=1) # set which axes to rotate around if rotation_vectors: t.rotation_vectors = rotation_vectors # we want to be able to see the model from all angles @@ -1561,16 +2439,16 @@ def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0) global HUD HUD = 0 if(hud != 0 and hasattr(hud, "app")): - HUD = hud - #point our app at the global - t.hud = HUD + HUD = hud + #point our app at the global + t.hud = HUD + t.hud.app = t #HUD needs to know where to draw - t.hud.app = t #HUD needs to know where to draw - # need to capture the world coordinate system world = Capture() t.model = Collection([model, world]) + t.perspective = True t.distance = size * 3 t.near = size * 0.01 t.far = size * 10.0 @@ -1581,12 +2459,16 @@ def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0) t.pack(fill="both", expand=1) def update(): - global old_plotclear + global old_plotclear, _stats_fresh + poll_all_stats(force=True) + if function is not None: + function() t.tkRedraw() + _stats_fresh = False new_plotclear = vcomp["plotclear"] if new_plotclear and not old_plotclear: t.plotclear() - old_plotclear=new_plotclear + old_plotclear = new_plotclear t.after(100, update) update() @@ -1597,3 +2479,4 @@ def quit(*args): signal.signal(signal.SIGINT, quit) app.mainloop() +