diff --git a/docs/src/gui/vismach.adoc b/docs/src/gui/vismach.adoc index f67066b08a7..ad9ed96e200 100644 --- a/docs/src/gui/vismach.adoc +++ b/docs/src/gui/vismach.adoc @@ -70,44 +70,93 @@ 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. +into the model script with the `STL()` or `OBJ()` 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 ...")` + +* `part = STL(filename="path/to/file.stl")` + + `part = STL(data="solid part1 facet normal ....")` + + (Legacy alias: `AsciiSTL`.) + + `part = OBJ(filename="path/to/file.obj")` + + `part = OBJ(data="v 0.123 0.234 0.345 ...")` + + (Legacy alias: `AsciiOBJ`.) + 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. + possible to assemble the model in the CAD package. Both ASCII and + Binary STL files or `bytes` buffers are supported automatically, and + Wavefront OBJ files support triangles, quads, and convex polygons with + automatic face normals when `vn` normals are omitted. + + Both loaders provide a `.reload(filename=None, data=None, force=False)` + method to reload geometry from disk or new data at runtime whenever + the source file or buffer changes (pass `force=True` to force a + reload even if unchanged). 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)` + +of *shape primitives*. All primitives accept static numbers, an optional +leading prefix object (`[prefix,]` such as a `hal.component`, +`linuxcnc.stat`, `hal`, or `dict`), `"prefix.attr"` dot-notation strings, +or `"{prefix.attr}"` expressions. Many shapes are created at the origin +and need to be moved to the required location after creation: + +* `cylinder = CylinderX([prefix,] x1, r1, x2, r2)` + + `cylinder = CylinderY([prefix,] y1, r1, y2, r2)` + + `cylinder = CylinderZ([prefix,] 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)` + +* `sphere = Sphere([prefix,] x, y, z, r)` + + Creates a sphere of radius `r` at `(x, y, z)`. +* `triangle = TriangleXY([prefix,] x1, y1, x2, y2, x3, y3, z1, z2)` + + `triangle = TriangleXZ([prefix,] x1, z1, x2, z2, x3, z3, y1, y2)` + + `triangle = TriangleYZ([prefix,] 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)` + +* `arc = ArcX([prefix,] x1, x2, r1, r2, a1, a2, steps)` + + Creates a curved arc segment along the X-axis between `x1` and `x2`, + with inner radius `r1`, outer radius `r2`, start/end angles `a1` and + `a2` (in degrees), and `steps` subdivisions. +* `box = Box([prefix,] 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. +* `box = BoxCentered([prefix,] xw, yw, zw)` + + Creates an `xw` by `yw` by `zw` box centred on the origin. +* `box = BoxCenteredXY([prefix,] xw, yw, zw)` + + Creates a box of width `xw` / `yw` and height `zw`. +* `line = Line([prefix,] x1, y1, z1, x2, y2, z2, stretch=1, r=5)` + + (Legacy alias: `HalLine`.) + + Creates a cylindrical line segment starting at `(x1, y1, z1)` along + vector `(x2, y2, z2)` scaled by `stretch` with radius `r`. +* `grid = Grid([prefix,] s=500)` + + `grid = Grid([prefix,] x, y, z, vx, vy, vz, s=500)` + + `grid = Grid([prefix,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500)` + + (Legacy aliases: `HalGrid`, `HalGridFromNormal`, `HalGridFromNormalAndDirection`.) + + Creates a reference grid of half-size `s` on the XY plane at the + origin, perpendicular to normal vector `(vx, vy, vz)` at `(x, y, z)`, + or aligned to origin `(ox, oy, oz)`, X-direction `(xx, xy, xz)`, and + Z-normal `(zx, zy, zz)`. +* `plane = Plane([prefix,] s=500)` + + `plane = Plane([prefix,] x, y, z, vx, vy, vz, s=500)` + + `plane = Plane([prefix,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500)` + + (Legacy alias: `HalPlaneFromNormal`.) + + Creates a solid reference plane of half-size `s` at the origin, + aligned to a normal vector, or aligned to an origin, X-direction + vector, and Z-normal vector. +* `coords = Coords([prefix,] stretch=1, r=5)` + + `coords = Coords([prefix,] ox, oy, oz, zx, zy, zz, stretch=1, r=5)` + + `coords = Coords([prefix,] ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch=1, r=5)` + + (Legacy alias: `HalCoordsFromNormalAndDirection`.) + + Creates a 3-axis RGB coordinate indicator (X=Red, Y=Green, Z=Blue) of + base length `50 * stretch` and radius `r` at the origin, aligned to a + Z-normal vector, or aligned to an origin, X-direction vector, and + Z-normal vector. + +[NOTE] +==== +Legacy `Hal*` aliases (such as `HalLine`, `HalGrid`, +`HalGridFromNormal`, `HalGridFromNormalAndDirection`, `HalPlaneFromNormal`, +and `HalCoordsFromNormalAndDirection`) remain supported for backwards +compatibility, though they may be deprecated in the future. +==== Composite parts may be created by *assembling* these primitives either at creation time or subsequently using `Collection()`: @@ -131,44 +180,87 @@ rotation axis is created at the origin (but moves with the Part): * `part1 = Rotate([part1], theta, x, y, z)` + Rotate the part by angle theta about an axis between the origin and x, y, z. +* `part1 = Scale([part1], x, y, z)` + + Scale the part by factors `x`, `y`, and `z` along the respective axes. +* `part1 = RotateEuler([part1], th1, th2, th3, order=123)` + + Apply three successive Euler rotations (`th1`, `th2`, `th3` in degrees) + about the axes specified by `order` (default `123` for X-Y-Z). +* `part1 = Show([part1], const, var, scaleby_true=1, scaleby_false=0)` + + Toggle part visibility/scale between `scaleby_true` and `scaleby_false` + depending on whether `const == var`. + +[NOTE] +==== +Legacy `Hal*` aliases (such as `HalTranslate`, `HalVectorTranslate`, +`HalRotate`, `HalVectorRotate`, `HalScale`, `HalRotateEuler`, and +`HalShow`) remain supported for backwards compatibility, though they may +be deprecated in the future. +==== == 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. +To animate the model, transforms, primitives, and `Color` accept static +numbers, HAL pin names with an explicit prefix object, `"prefix.attr"` +dot-notation strings, or `"{prefix.attr}"` math and conditional +expressions. For parts to move inside an assembly they need to have their +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 live values as the model is animated: + +* `part = Translate([part], [prefix,] x, y, z)` + + `part = Translate([part], [prefix,] var, x, y, z)` + + (Legacy alias: `HalTranslate`.) + + In the 3-argument form, moves `part` by `(x, y, z)`. In the 4-argument + form, moves `part` along vector `(x, y, z)` scaled by `var`. +* `part = VectorTranslate([part], [prefix,] xvar, yvar, zvar, scale=1)` + + (Legacy alias: `HalVectorTranslate`.) + + Moves `part` along `(xvar, yvar, zvar)` scaled by `scale` (which may + be passed either positionally or as a keyword argument). +* `part = Rotate([part], [prefix,] th, x, y, z)` + + `part = Rotate([part], [prefix,] var, th, x, y, z)` + + (Legacy aliases: `HalRotate`, `HalVectorRotate`.) + + Rotates `part` around the axis `(x, y, z)` by angle `th` (in degrees), + or by `th * var` when a variable multiplier `var` is given. +* `part = RotateEuler([part], [prefix,] x, y, z, order=123)` + + (Legacy alias: `HalRotateEuler`.) + + Applies sequential Euler rotations `x`, `y`, `z` (in degrees) around + axes `1` (X), `2` (Y), and `3` (Z) in the specified `order`. +* `part = Scale([part], [prefix,] x, y, z)` + + `part = Scale([part], [prefix,] x, y, z, var)` + + (Legacy alias: `HalScale`.) + + Scales `part` along `(x, y, z)`, or scales by `(x * var, y * var, + z * var)` when a variable multiplier `var` is given. +* `part = Show([part], [prefix,] const, var, scaleby_true=1, scaleby_false=0)` + + (Legacy alias: `HalShow`.) + + Compares `var` against `const`. When `var == const`, `part` is scaled by + `scaleby_true` (default `1`, visible); otherwise it is scaled by + `scaleby_false` (default `0`, hidden). + +=== Prefix and Expression Syntax + +Any numeric parameter on a transform, primitive, or `Color` can be driven +dynamically in three ways: + +* *Explicit prefix object + attribute name:* + + Pass a `hal.component`, `linuxcnc.stat`, `hal` module, or Python `dict` + as the prefix argument followed by pin or attribute names: +** `Translate([part], c, "joint0", 1, 0, 0)` (reads `c["joint0"]`) +** `Translate([part], s, "g5x_offset[0]", 1, 0, 0)` (reads `s.g5x_offset[0]`) +* *Dot-notation strings (`"prefix.attr"`):* + + Omit the leading prefix object and reference any `hal.component`, + `linuxcnc.stat`, `hal`, or `dict` variable in scope directly by name: +** `"c.joint0"` (reads `c["joint0"]`) +** `"hal.spindle.0.speed"` (reads `hal.get_value("spindle.0.speed")`) +** `"s.actual_position[2]"` (reads `s.actual_position[2]`, polled once per redraw) +* *Math and conditional expressions (`"{prefix.attr}"`):* + + Wrap one or more `"prefix.attr"` tokens in curly braces `{...}` inside a + Python math or conditional expression. Hyphenated HAL pin names (such as + `"{c.pivot-z}"`) are supported directly: +** `Translate([part], 0, 0, "{s.actual_position[2] - s.g5x_offset[2]}")` +** `Rotate([part], "{sin(radians(c.angle)) * 45}", 0, 1, 0)` +** `Show([part], 1, "{1 if s.tool_in_spindle > 0 else 0}")` +** `Color([part], ["{1.0 if c.active else 0.2}", 0.2, 0.2, 1.0])` == Assembling the model. @@ -195,25 +287,26 @@ of drive dogs: #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 = Rotate([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) +draw = Translate([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) +head = Translate([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]) ---- @@ -242,27 +335,43 @@ 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. +* `part = Color([part], [prefix,] [colorspec], glow=0)` + + (Legacy swapped order `Color([colorspec], [part])` is also supported as + opaque only, without transparency or `glow`.) + + Sets the display color and optional emissive glow of the part. The + `colorspec` consists of the three RGB values and an optional opacity + (default `1.0`), for example `[1, 0, 0, 0.5]` for a 50% opacity red. + When opacity is less than `1.0`, the part is automatically rendered in + a second translucent pass after opaque parts so internal components + remain visible (`0.0` fades the part out completely). `glow` (`0.0` to + `1.0`) controls self-illuminated emission (`GL_EMISSION`). Each color + channel and `glow` may be a static number, `"prefix.attr"`, or + `"{prefix.attr}"` expression. +* `part = Track([part], [prefix,] position, target, world)` + + Aligns `part` along the vector from `position` to `target` in `world` + space. `position` and `target` may each be a `Capture()` object or a + 3-element `[x, y, z]` list containing static numbers, `"prefix.attr"`, + or `"{prefix.attr}"` expressions. * `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. -//// + Creates a heads-up display in the Vismach GUI to display text, HAL + pins, `linuxcnc.stat` values, and `{prefix.attr}` expressions. + `myhud.add_txt("Z: {{s.actual_position[2]} - {s.g5x_offset[2]}:.3f}")` + evaluates embedded expressions (including math and conditionals) with + optional format specifiers on each redraw, and `add_pin`, + `show_tag_if_same`, `show_tags_in_pin`, and `hide_all` accept both + legacy HAL pin names and `"prefix.attr"` / `"{prefix.attr}"` + expressions. * `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. + model moves. Calling `tooltip.world_pos(world)` returns its `[x, y, z]` + coordinates relative to `world` (or in model space if `world` is omitted). * `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)` + + lat=0, lon=0, function=None)` + 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 @@ -274,7 +383,10 @@ Need to play around with this to see how it works. 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. +** _function_ is an optional zero-argument callback executed on each + periodic update cycle (after `linuxcnc.stat` polling and before + redrawing), useful for computing derived values into a Python `dict` + prefix. == Basic structure of a Vismach script. @@ -295,7 +407,7 @@ 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 = Rotate([part1],comp,"pin_name",360,0,0,1) part1 = Translate([dogs],-1,49,0) ... #create a top-level model @@ -304,4 +416,75 @@ model = Collection([base, saddle, head, carousel]) main(model, tooltip, work, 100, lat=-75, lon=215) ---- +== Dynamic Values and Expressions + +=== Custom Prefix Identifiers + +Prefix names are not restricted to `c` or `s`. Any valid Python variable +name bound in the caller's scope to a `hal.component`, `linuxcnc.stat`, +`hal` module, or `dict` can be used as a prefix: + +[source,python] +---- +comp = hal.component("mygui") +status = linuxcnc.stat() +world = Capture() +spindle_tip = Capture() +cable = {"anchor_x": 0.0, "anchor_y": 0.0, "anchor_z": 100.0} + +def update_cable_anchor(): + x, y, z = spindle_tip.world_pos(world) + cable["anchor_x"] = x + cable["anchor_y"] = y + cable["anchor_z"] = z + 50.0 + status.g5x_offset[2] + +# Orient a flexible hose or cable between the moving spindle tip and a derived anchor +hose = Track( + [CylinderZ(0, 4, 100, 4)], + spindle_tip, + ["cable.anchor_x", "cable.anchor_y", "{cable.anchor_z + comp.slack}"], + world, +) + +main(model, tooltip, work, 100, lat=-75, lon=215, function=update_cable_anchor) +---- + +Multiple prefix objects of the same or different types can be combined +within a single expression. Passing `function=update_cable_anchor` to +`main()` updates the `dict` values on every refresh cycle immediately +before the scene is redrawn. + +[NOTE] +==== +Any `linuxcnc.stat` instance referenced in a Vismach prefix or +expression is automatically registered and polled once per refresh +cycle before `function` runs. If a `linuxcnc.stat` instance is used +*exclusively* inside your custom `function` callback (and not referenced +in any Vismach part or transform), call `status.poll()` inside that +function so its attributes stay current. +==== + +=== Expression Parsing and `stat` Polling + +String arguments containing `"prefix.attr"` tokens or `"{prefix.attr}"` +expressions are compiled once when the model is constructed: + +* *Scope capture and compilation:* At initialization, Vismach captures + matching prefix objects (`hal.component`, `linuxcnc.stat`, `hal`, or + `dict`) from the caller's scope and compiles each expression into a + reusable bytecode object evaluated without Python built-ins. Standard + `math` functions (`sin`, `cos`, `tan`, `radians`, `degrees`, `sqrt`, + `hypot`, `abs`, `min`, `max`, `round`, `floor`, `ceil`, `pi`, etc.) + and conditional expressions (`a if cond else b`) are available inside + `{...}`. +* *Hyphenated HAL pins:* Pin names containing hyphens (such as + `"{c.pivot-z}"`) are extracted as single `{...}` tokens before + compilation, so they are resolved as pin lookups rather than parsed as + subtraction. +* *Once-per-frame `linuxcnc.stat` polling:* Any `linuxcnc.stat` object + referenced via a prefix or expression is registered automatically and + polled once at the start of each redraw cycle (`poll_all_stats()`), + avoiding redundant status polls across multiple model parts. + + // vim: set syntax=asciidoc: diff --git a/lib/python/vismach.py b/lib/python/vismach.py index 95648aefab6..43802f73eed 100644 --- a/lib/python/vismach.py +++ b/lib/python/vismach.py @@ -14,7 +14,6 @@ # 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 tkinter @@ -22,25 +21,209 @@ from OpenGL.GLU import * from math import * import glnav -import hal +import os +import struct +import inspect +import operator +import linuxcnc + +_registered_stats = [] +_stats_fresh = False +_render_pass = "opaque" +_has_transparent = False + +_EXPR_MATH = { + "sin": sin, "cos": cos, "tan": tan, + "asin": asin, "acos": acos, "atan": atan, "atan2": atan2, + "hypot": hypot, "sqrt": sqrt, "pi": pi, "tau": tau, "e": e, + "abs": abs, "min": min, "max": max, "round": round, + "floor": floor, "ceil": ceil, "fmod": fmod, + "pow": pow, "exp": exp, "log": log, "log10": log10, + "radians": radians, "degrees": degrees, +} + +def _register_stat(st): + """Registers a linuxcnc.stat instance for once-per-frame polling.""" + if isinstance(st, linuxcnc.stat) and st not in _registered_stats: + _registered_stats.append(st) + +def _check_stats_ready(): + """Verifies at startup that all registered linuxcnc.stat instances can poll.""" + # Objects used in parts or Hud are already registered during scene construction + # (including local builder scopes and imported sub-assemblies). Scan main()'s + # caller globals as well to catch instances used only in function=... callbacks. + if not _registered_stats: + try: + caller_globals = sys._getframe(2).f_globals + for val in caller_globals.values(): + if isinstance(val, linuxcnc.stat): + _register_stat(val) + except ValueError: + pass + + for st in _registered_stats: + try: + st.poll() + except linuxcnc.error as exc: + sys.stderr.write( + "Vismach Error: Cannot poll linuxcnc.stat (%s). " + "Is LinuxCNC running?\n" % exc + ) + raise SystemExit(1) + +def poll_all_stats(): + """Polls all registered linuxcnc.stat instances once per update/redraw cycle.""" + global _stats_fresh + if _stats_fresh: + return + for st in _registered_stats: + st.poll() + _stats_fresh = True + +def _is_valid_prefix_obj(obj): + return isinstance(obj, (hal.component, linuxcnc.stat, dict)) or obj is hal + +def _capture_caller_prefixes(): + """Snapshots valid prefix objects (hal.component, linuxcnc.stat, hal, dict) from caller scope.""" + prefixes = {"hal": hal} + frame = inspect.currentframe() + try: + caller = frame.f_back + while caller is not None and caller.f_globals.get("__name__") == __name__: + caller = caller.f_back + if caller is not None: + for scope in (caller.f_globals, caller.f_locals): + for k, v in scope.items(): + if not k.startswith("_") and _is_valid_prefix_obj(v): + prefixes[k] = v + if isinstance(v, linuxcnc.stat): + _register_stat(v) + finally: + del frame + return prefixes + +def _split_comp(args): + """Detects an optional leading prefix (hal.component, linuxcnc.stat, hal, dict) in *args.""" + if args and _is_valid_prefix_obj(args[0]): + if isinstance(args[0], linuxcnc.stat): + _register_stat(args[0]) + return args[0], args[1:] + return None, args + +def _make_attr_getter(obj, attr_path): + """Creates a fast getter for 'attr' or 'attr[idx]' on a prefix object.""" + if isinstance(obj, hal.component): + return lambda c=obj, p=attr_path: c[p] + if obj is hal: + return lambda p=attr_path: hal.get_value(p) + if isinstance(obj, dict): + if "[" not in attr_path: + return lambda d=obj, k=attr_path: d[k] + head, tail = attr_path.split("[", 1) + code = compile("_d[%r][%s" % (head, tail), "", "eval") + return lambda c=code, d=obj: eval(c, {"__builtins__": None}, {"_d": d}) + if isinstance(obj, linuxcnc.stat): + _register_stat(obj) + if "[" not in attr_path: + getter = operator.attrgetter(attr_path) + return lambda o=obj, g=getter: g(o) + code = compile("_o." + attr_path, "", "eval") + return lambda c=code, o=obj: eval(c, {"__builtins__": None}, {"_o": o}) + +def _resolve_token(token, explicit_prefix, prefix_cache): + """Resolves a single 'prefix.attr' or bare 'attr' token into a zero-arg getter.""" + if explicit_prefix is not None: + if "." in token: + head, rest = token.split(".", 1) + if head in prefix_cache and prefix_cache[head] is explicit_prefix: + return _make_attr_getter(explicit_prefix, rest) + if head in prefix_cache: + return _make_attr_getter(prefix_cache[head], rest) + return _make_attr_getter(explicit_prefix, token) + + if "." not in token: + raise ValueError("No prefix passed: expected 'prefix.attribute', got %r" % token) + + head, rest = token.split(".", 1) + if head not in prefix_cache: + raise NameError("Prefix %r not found in caller scope" % head) + return _make_attr_getter(prefix_cache[head], rest) + +def _compile_arg(val, explicit_prefix, prefix_cache): + """ + Compiles a static value, 'prefix.attr' string, or '{prefix.attr}' math/conditional + expression into a zero-arg callable with {"__builtins__": None}. + """ + if not isinstance(val, str): + return lambda: val + + s = val.strip() + + if "{" in s or "}" in s: + getters = [] + parts = [] + i = 0 + n = len(s) + while i < n: + open_idx = s.find("{", i) + if open_idx == -1: + parts.append(s[i:]) + break + close_idx = s.find("}", open_idx + 1) + if close_idx == -1: + raise SyntaxError("Vismach Error: Unmatched '{' in expression %r" % val) + parts.append(s[i:open_idx]) + token = s[open_idx + 1:close_idx].strip() + slot = "__v%d" % len(getters) + getters.append(_resolve_token(token, explicit_prefix, prefix_cache)) + parts.append(slot) + i = close_idx + 1 + + py_expr = "".join(parts) + try: + code = compile(py_expr, "", "eval") + except SyntaxError as exc: + raise SyntaxError("Vismach Error: Cannot compile expression %r: %s" % (val, exc)) from exc + + # Pre-allocate a single reusable env and overwrite only the keys in-place on each evaluation + env = dict(_EXPR_MATH) + slots = [("__v%d" % idx, fn) for idx, fn in enumerate(getters)] + + def _eval_expr(): + for slot, fn in slots: + env[slot] = fn() + return eval(code, {"__builtins__": None}, env) + + return _eval_expr + + return _resolve_token(s, explicit_prefix, prefix_cache) + class Collection(object): def __init__(self, parts): self.parts = parts self.vol = 0 - def traverse(self): + def _build_steps(self): + steps = [] for p in self.parts: - if hasattr(p, "apply"): - p.apply() - if hasattr(p, "capture"): - p.capture() - if hasattr(p, "draw"): - p.draw() - if hasattr(p, "traverse"): - p.traverse() - if hasattr(p, "unapply"): - p.unapply() + if isinstance(p, Color): + steps.append(p.traverse) + continue + for name in ("apply", "capture", "draw", "traverse", "unapply"): + fn = getattr(p, name, None) + if fn is not None: + steps.append(fn) + self._steps = steps + self._steps_parts = list(self.parts) + return steps + + def traverse(self): + steps = getattr(self, "_steps", None) + if steps is None or self._steps_parts != self.parts: + steps = self._build_steps() + for fn in steps: + fn() def volume(self): if hasattr(self, "vol") and self.vol != 0: @@ -56,728 +239,733 @@ def volume(self): def set_volume(self,vol): self.vol = vol; -class Translate(Collection): - def __init__(self, parts, x, y, z): - self.parts = parts - self.where = x, y, z - def apply(self): - glPushMatrix() - glTranslatef(*self.where) +def _cross3(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]] - def unapply(self): - glPopMatrix() +def _polar3(v, stretch=1.0): + length = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]) * stretch + axis = (1, 0, 0) if hypot(v[0], v[1]) < 0.001 else _cross3(v, (0, 0, 1)) + angle = -atan2(hypot(v[0], v[1]), v[2]) * 180.0 / pi + return (length, angle, axis) -class Scale(Collection): - def __init__(self, parts, x, y, z): - self.parts = parts - self.scaleby = x, y, z +class ArgsBase(object): + """Resolves static values, 'prefix.attr' paths, and '{prefix.attr}' expressions.""" + def __init__(self, *args): + if args and (args[0] is None or _is_valid_prefix_obj(args[0])): + comp, rest = args[0], args[1:] + if isinstance(comp, linuxcnc.stat): + _register_stat(comp) + else: + comp, rest = _split_comp(args) - def apply(self): - glPushMatrix() - glScalef(*self.scaleby) + self.comp = comp + self._args = rest + if not any(isinstance(v, str) for v in rest): + self._static_vals = list(rest) + self._resolvers = None + else: + self._static_vals = None + prefix_cache = _capture_caller_prefixes() + self._resolvers = [_compile_arg(v, comp, prefix_cache) for v in rest] + + # redundant once we move to OpenGl 3.3 + @property + def q(self): + quad = self.__dict__.get("_q") + if quad is None: + quad = gluNewQuadric() + self.__dict__["_q"] = quad + return quad - def unapply(self): - glPopMatrix() + def coords(self): + if self._static_vals is not None: + return self._static_vals + return [fn() for fn in self._resolvers] -class HalTranslate(Collection): - def __init__(self, parts, comp, var, x, y, z): - self.parts = parts - self.where = x, y, z - self.comp = comp - self.var = var + def cross(self, a, b): + return _cross3(a, b) - def apply(self): - x, y, z = self.where - v = self.comp[self.var] - - glPushMatrix() - glTranslatef(x*v, y*v, z*v) + def polar(self, v, stretch=1.0): + return _polar3(v, stretch) - def unapply(self): - glPopMatrix() +# legacy used in: /rotarydelta.py:61:class HexPrismZ(CoordsBase) +CoordsBase = ArgsBase -class HalRotate(Collection): - def __init__(self, parts, comp, var, th, x, y, z): +class Translate(Collection, ArgsBase): + """ + Supports: + - Translate(parts, [comp,] x, y, z) + - Translate(parts, [comp,] var, x, y, z) + """ + def __init__(self, parts, *args): self.parts = parts - self.where = th, x, y, z - self.comp = comp - self.var = var + comp, rest = _split_comp(args) + if len(rest) == 3: + x, y, z = rest + ArgsBase.__init__(self, comp, 1, x, y, z) + elif len(rest) == 4: + var, x, y, z = rest + ArgsBase.__init__(self, comp, var, x, y, z) + else: + raise TypeError("Translate expects (parts, [comp,] [var,] x, y, z)") def apply(self): - th, x, y, z = self.where + v, x, y, z = self.coords() glPushMatrix() - glRotatef(th * self.comp[self.var], x, y, z) + glTranslatef(x * v, y * v, z * v) def unapply(self): glPopMatrix() -class Rotate(Collection): - def __init__(self, parts, th, x, y, z): +class VectorTranslate(Collection, ArgsBase): + """ + Supports: + - VectorTranslate(parts, [comp,] xvar, yvar, zvar, scale=1) + """ + def __init__(self, parts, *args, **kwargs): self.parts = parts - self.where = th, x, y, z + comp, rest = _split_comp(args) + if len(rest) == 3: + x, y, z = rest + sc = kwargs.get("scale", 1) + elif len(rest) == 4: + x, y, z, sc = rest + else: + raise TypeError("VectorTranslate expects (parts, [comp,] xvar, yvar, zvar[, scale])") + ArgsBase.__init__(self, comp, x, y, z, sc) def apply(self): - th, x, y, z = self.where + x, y, z, sc = self.coords() glPushMatrix() - glRotatef(th, x, y, z) + glTranslatef(sc * x, sc * y, sc * z) def unapply(self): glPopMatrix() -class HalRotateEuler(Collection): - def __init__(self, parts, comp, th1, th2, th3, order=123): - self.parts = parts - self.comp = comp - self.order = order - self.th1 = th1 - self.th2 = th2 - self.th3 = th3 +HalTranslate = Translate +HalVectorTranslate = VectorTranslate - 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] - 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] + +class Scale(Collection, ArgsBase): + """ + Unifies legacy classes: + - Scale(parts, x, y, z) + - HalScale(parts, comp, x, y, z, var) + """ + def __init__(self, parts, *args): + self.parts = parts + comp, rest = _split_comp(args) + if len(rest) == 3: + x, y, z = rest + factor = 1 + elif len(rest) == 4: + x, y, z, factor = rest else: - th3 = self.th3 + raise TypeError("Scale expects (parts, [comp,] x, y, z[, var])") + ArgsBase.__init__(self, comp, x, y, z, factor) + def apply(self): + x, y, z, factor = self.coords() glPushMatrix() - if order == 131: - glRotatef(th1, 1, 0, 0) - glRotatef(th2, 0, 0, 1) - glRotatef(th3, 1, 0, 0) - elif order == 121: - glRotatef(th1, 1, 0, 0) - glRotatef(th2, 0, 1, 0) - glRotatef(th3, 1, 0, 0) - elif order == 212: - glRotatef(th1, 0, 1, 0) - glRotatef(th2, 1, 0, 0) - glRotatef(th3, 0, 1, 0) - elif order == 232: - glRotatef(th1, 0, 1, 0) - glRotatef(th2, 0, 0, 1) - glRotatef(th3, 0, 1, 0) - elif order == 323: - glRotatef(th1, 0, 0, 1) - glRotatef(th2, 0, 1, 0) - glRotatef(th3, 0, 0, 1) - elif order == 313: - glRotatef(th1, 0, 0, 1) - glRotatef(th2, 1, 0, 0) - glRotatef(th3, 0, 0, 1) - elif order == 123: - glRotatef(th1, 1, 0, 0) - glRotatef(th2, 0, 1, 0) - glRotatef(th3, 0, 0, 1) - elif order == 132: - glRotatef(th1, 1, 0, 0) - glRotatef(th2, 0, 0, 1) - glRotatef(th3, 0, 1, 0) - elif order == 213: - glRotatef(th1, 0, 1, 0) - glRotatef(th2, 1, 0, 0) - glRotatef(th3, 0, 0, 1) - elif order == 231: - glRotatef(th1, 0, 1, 0) - glRotatef(th2, 0, 0, 1) - glRotatef(th3, 1, 0, 0) - elif order == 321: - glRotatef(th1, 0, 0, 1) - glRotatef(th2, 0, 1, 0) - glRotatef(th3, 1, 0, 0) - elif order == 312: - glRotatef(th1, 0, 0, 1) - glRotatef(th2, 1, 0, 0) - glRotatef(th3, 0, 1, 0) + glScalef(x * factor, y * factor, z * factor) def unapply(self): glPopMatrix() +HalScale = Scale + -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): +class Rotate(Collection, ArgsBase): + """ + Unifies legacy classes: + - Rotate(parts, th, x, y, z) + - HalRotate(parts, comp, var, th, x, y, z) + - HalVectorRotate(parts, comp, var, th, x, y, z) + """ + def __init__(self, parts, *args): self.parts = parts - self.target = target - self.position = position - 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]) + comp, rest = _split_comp(args) + if comp is not None and len(rest) == 5: + var, th, x, y, z = rest + ArgsBase.__init__(self, comp, var, th, x, y, z) + elif len(rest) == 4: + th, x, y, z = rest + ArgsBase.__init__(self, comp, 1, th, x, y, z) + else: + raise TypeError("Rotate expects (parts, [comp, var,] th, x, y, z)") def apply(self): - # make sure we have something to work with first - if len(self.world2view.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)] + if hasattr(self, "get_values"): + # Legacy subclass pattern (e.g. HalRotateNutation) overriding get_values() + c_vals = self.coords() + var = c_vals[0] if isinstance(c_vals, (list, tuple)) else c_vals + th, x, y, z = self.get_values() + else: + var, th, x, y, z = self.coords() glPushMatrix() - glTranslatef(px,py,pz) - glRotatef(az-90,0,0,1) - glRotatef(el-90,1,0,0) + glRotatef(th * var, x, y, z) def unapply(self): - glPopMatrix() + glPopMatrix() + +HalRotate = Rotate +HalVectorRotate = Rotate -# scales an object by the value of a halpin -class HalScale(Collection): - def __init__(self, parts, comp, x, y, z, var): + +class RotateEuler(Collection, ArgsBase): + """Replaces legacy class HalRotateEuler(parts, [comp,] th1, th2, th3, order=123).""" + def __init__(self, parts, *args, order=123): self.parts = parts - self.comp = comp - self.var = var - self.xyz = x, y, z + comp, rest = _split_comp(args) + if len(rest) == 4: + th1, th2, th3, order = rest + elif len(rest) == 3: + th1, th2, th3 = rest + else: + raise TypeError("RotateEuler expects (parts, [comp,] th1, th2, th3[, order])") + ArgsBase.__init__(self, comp, order, th1, th2, th3) def apply(self): - x, y, z = self.xyz - factor = self.comp[self.var] + order, th1, th2, th3 = self.coords() + order = int(order) glPushMatrix() - glScalef(x*factor,y*factor,z*factor) + axes = { + 131: ((1, 0, 0), (0, 0, 1), (1, 0, 0)), + 121: ((1, 0, 0), (0, 1, 0), (1, 0, 0)), + 212: ((0, 1, 0), (1, 0, 0), (0, 1, 0)), + 232: ((0, 1, 0), (0, 0, 1), (0, 1, 0)), + 323: ((0, 0, 1), (0, 1, 0), (0, 0, 1)), + 313: ((0, 0, 1), (1, 0, 0), (0, 0, 1)), + 123: ((1, 0, 0), (0, 1, 0), (0, 0, 1)), + 132: ((1, 0, 0), (0, 0, 1), (0, 1, 0)), + 213: ((0, 1, 0), (1, 0, 0), (0, 0, 1)), + 231: ((0, 1, 0), (0, 0, 1), (1, 0, 0)), + 321: ((0, 0, 1), (0, 1, 0), (1, 0, 0)), + 312: ((0, 0, 1), (1, 0, 0), (0, 1, 0)), + } + if order in axes: + a1, a2, a3 = axes[order] + glRotatef(th1, *a1) + glRotatef(th2, *a2) + glRotatef(th3, *a3) def unapply(self): glPopMatrix() +HalRotateEuler = RotateEuler + -# 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): +class Show(Collection, ArgsBase): + """ + Replaces legacy class HalShow(parts, [comp,] const, var, scaleby_true=1, scaleby_false=0). + """ + def __init__(self, parts, *args): self.parts = parts - self.comp = comp - self.const = const - self.var = var - self.scaleby_true = scaleby_true - self.scaleby_false = scaleby_false + comp, rest = _split_comp(args) + if len(rest) == 2: + const, var = rest + scaleby_true, scaleby_false = 1, 0 + elif len(rest) == 3: + const, var, scaleby_true = rest + scaleby_false = 0 + elif len(rest) == 4: + const, var, scaleby_true, scaleby_false = rest + else: + raise TypeError( + "Show expects (parts, [prefix,] const, var[, scaleby_true[, scaleby_false]])" + ) + ArgsBase.__init__(self, comp, const, var, scaleby_true, scaleby_false) def apply(self): - s_t = self.scaleby_true - s_f = self.scaleby_false + const, var, scaleby_true, scaleby_false = self.coords() glPushMatrix() - if self.const == self.comp[self.var]: - glScalef(s_t,s_t,s_t) + if const == var: + glScalef(scaleby_true, scaleby_true, scaleby_true) else: - glScalef(s_f,s_f,s_f) + glScalef(scaleby_false, scaleby_false, scaleby_false) def unapply(self): glPopMatrix() -# 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 - - 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) +HalShow = Show - def unapply(self): - glPopMatrix() +def matmul(a, b): + """Multiplies two 4x4 transformation matrices.""" + out = [[0.0] * 4 for _ in range(4)] + for i in range(4): + for j in range(4): + out[i][j] = ( + a[i][0] * b[0][j] + + a[i][1] * b[1][j] + + a[i][2] * b[2][j] + + a[i][3] * b[3][j] + ) + return out -class HalVectorRotate(Collection): - def __init__(self, parts, comp, var, th, x, y, z): +def invert(src): + '''' 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. + 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''' + r00, r01, r02 = src[0][0], src[0][1], src[0][2] + r10, r11, r12 = src[1][0], src[1][1], src[1][2] + r20, r21, r22 = src[2][0], src[2][1], src[2][2] + tx, ty, tz = src[3][0], src[3][1], src[3][2] + return [ + [r00, r10, r20, 0.0], + [r01, r11, r21, 0.0], + [r02, r12, r22, 0.0], + [ + -(tx * r00 + ty * r01 + tz * r02), + -(tx * r10 + ty * r11 + tz * r12), + -(tx * r20 + ty * r21 + tz * r22), + 1.0, + ], + ] + +class Track(Collection, ArgsBase): + """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 + Supports: + - Track(parts, position, target, world) + - Track(parts, prefix, position, target, world) + """ + def __init__(self, parts, *args): self.parts = parts - self.comp = comp - self.var = var - self.values = th, x, y, z + comp, rest = _split_comp(args) + if len(rest) != 3: + raise TypeError("Track expects (parts, [prefix,] position, target, world)") + + position, target, world = rest + self.world = world + + expr_args = [] + if isinstance(position, (list, tuple)): + if len(position) != 3: + raise ValueError("Track position list must have 3 coordinates") + self._pos_capture = None + self._pos_slice = (0, 3) + expr_args.extend(position) + else: + self._pos_capture = position + self._pos_slice = None + + if isinstance(target, (list, tuple)): + if len(target) != 3: + raise ValueError("Track target list must have 3 coordinates") + self._tgt_capture = None + start = len(expr_args) + self._tgt_slice = (start, start + 3) + expr_args.extend(target) + else: + self._tgt_capture = target + self._tgt_slice = None + + ArgsBase.__init__(self, comp, *expr_args) + + def _resolve_endpoints(self, vals): + w_inv = invert(self.world.t) + if self._pos_capture is not None: + p = matmul(self._pos_capture.t, w_inv) + x1, y1, z1 = p[3][0], p[3][1], p[3][2] + else: + x1, y1, z1 = vals[self._pos_slice[0]:self._pos_slice[1]] + + if self._tgt_capture is not None: + t = matmul(self._tgt_capture.t, w_inv) + x2, y2, z2 = t[3][0], t[3][1], t[3][2] + else: + x2, y2, z2 = vals[self._tgt_slice[0]:self._tgt_slice[1]] - def get_values(self): - return self.values + return x1, y1, z1, x2, y2, z2 def apply(self): - th, x, y, z = self.get_values() + vals = self.coords() + x1, y1, z1, x2, y2, z2 = self._resolve_endpoints(vals) + dx, dy, dz = x2 - x1, y2 - y1, z2 - z1 + length = sqrt(dx * dx + dy * dy + dz * dz) + if length < 1e-9: + glPushMatrix() + glTranslatef(x1, y1, z1) + return + axis = (1, 0, 0) if hypot(dx, dy) < 0.001 else self.cross((dx, dy, dz), (0, 0, 1)) + angle = -atan2(hypot(dx, dy), dz) * 180.0 / pi glPushMatrix() - glRotatef(th * self.comp[self.var], x, y, z) + glTranslatef(x1, y1, z1) + glRotatef(angle, *axis) def unapply(self): glPopMatrix() -class CoordsBase(object): - def __init__(self, *args): - if args and isinstance(args[0], hal.component): - self.comp = args[0] - args = args[1:] +def _is_parts_list(obj): + if isinstance(obj, Collection): + return True + if isinstance(obj, (list, tuple)): + if len(obj) == 0: + return True + if len(obj) not in (3, 4): + return True + return hasattr(obj[0], "traverse") or hasattr(obj[0], "draw") + return False + +class Color(Collection, ArgsBase): + """ + Sets RGBA material color and optional emissive glow (0.0..1.0). + Supports: + - Color(parts, color[, glow]) + - Color(parts, prefix, color[, glow]) + - Color(color, parts) # legacy swapped order (opaque only, no glow) + """ + def __init__(self, *args, **kwargs): + if not args: + raise TypeError("Color expects (parts, [prefix,] color[, glow]) or (color, parts)") + glow = kwargs.get("glow", 0.0) + if _is_parts_list(args[0]): + parts = args[0] + comp, rest = _split_comp(args[1:]) + if len(rest) == 1: + color = rest[0] + elif len(rest) == 2: + color, glow = rest + else: + raise TypeError("Color expects (parts, [prefix,] color[, glow])") + rgba = list(color) + ([1.0] if len(color) == 3 else []) + if len(rgba) != 4: + raise ValueError("Color specification must have 3 (RGB) or 4 (RGBA) channels") + elif len(args) == 2 and _is_parts_list(args[1]): + if "glow" in kwargs: + raise TypeError("Legacy Color(color, parts) does not support glow") + color, parts, comp, glow = args[0], args[1], None, 0.0 + if len(color) not in (3, 4): + raise ValueError("Color specification must have 3 (RGB) or 4 (RGBA) channels") + # Since GL_BLEND was off the legacy swapped order has always rendered opaque for any A + rgba = [color[0], color[1], color[2], 1.0] else: - self.comp = None - self._coords = args - self.q = gluNewQuadric() + raise TypeError("Color expects (parts, [prefix,] color[, glow]) or (color, parts)") - def coords(self): - return list(map(self._coord, self._coords)) + self.parts = parts + self.vol = 0 + ArgsBase.__init__(self, comp, *(rgba + [glow])) - def _coord(self, v): - if isinstance(v, str): return self.comp[v] - return v + def traverse(self): + global _has_transparent + r, g, b, a, glow = self.coords() + is_transparent = a < 1.0 + if _render_pass == "opaque": + if is_transparent: + _has_transparent = True + return + elif not is_transparent: + return + if a <= 0.0: + return + glPushAttrib(GL_LIGHTING_BIT | GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, [r, g, b, a]) + if glow: + g_val = float(glow) + glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, [r * g_val, g * g_val, b * g_val, 1.0]) + else: + glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, [0.0, 0.0, 0.0, 1.0]) + Collection.traverse(self) + glPopAttrib() -# 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() + def apply(self): + rgba = self.coords() + glPushAttrib(GL_LIGHTING_BIT) + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, rgba) + + def unapply(self): + glPopAttrib() - 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 - 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) +class Line(ArgsBase): + def __init__(self, *args, **kwargs): + comp, rest = _split_comp(args) + if len(rest) < 6 or len(rest) > 8: + raise TypeError("Line expects ([comp,] x1, y1, z1, x2, y2, z2, stretch=1, r=5)") + 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) + ArgsBase.__init__(self, comp, x1, y1, z1, x2, y2, z2, stretch, r) 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) + x1, y1, z1, x2, y2, z2, stretch, r = self.coords() + length, angle, axis = self.polar([x2, y2, z2], stretch) glPushMatrix() glTranslate(x1, y1, z1) - glRotate(angle,*axis) + glRotate(angle, *axis) gluCylinder(self.q, 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() - - 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]) - 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) +HalLine = Line - def square(self,n, s): - glBegin(GL_QUADS) - glNormal3f(n[0],n[1],n[2]) - 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 - v = [vx, vy, vz] - length, angle, axis = self.polar(v) +def _apply_normal_or_basis(origin, vec_z, vec_x=None): + """Pushes a matrix aligned to an origin + Z-normal (and optional X-direction).""" + ox, oy, oz = origin + if vec_x is None: + _, angle, axis = _polar3(vec_z) glPushMatrix() - 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() - - - def draw_vector(self, color): - gluCylinder(self.q, self.r, self.r, 50*self.stretch, 32, 1) - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) + glTranslate(ox, oy, oz) + glRotate(angle, *axis) + else: + xx, xy, xz = vec_x + zx, zy, zz = vec_z + yx, yy, yz = _cross3(vec_z, vec_x) + m_t = [ + [xx, xy, xz, 0], + [yx, yy, yz, 0], + [zx, zy, zz, 0], + [ox, oy, oz, 1], + ] + glPushMatrix() + glMultMatrixf(m_t) - 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]] +def _draw_grid_lines(s): + s_int = int(s) + glBegin(GL_LINES) + for i in range(-s_int, s_int + 10, 10): + glVertex3f(-s_int, i, 0) + glVertex3f(s_int, i, 0) + glVertex3f(i, -s_int, 0) + glVertex3f(i, s_int, 0) + glEnd() + +class Grid(ArgsBase): + """ + Unifies legacy classes: + - HalGrid([comp,] s=500) + - HalGridFromNormal([comp,] x, y, z, vx, vy, vz, s=500) + - HalGridFromNormalAndDirection([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500) + """ + def __init__(self, *args, **kwargs): + comp, rest = _split_comp(args) + n = len(rest) + + if n in (0, 1): + self._mode = "origin" + s = rest[0] if n == 1 else kwargs.get("s", 500) + ArgsBase.__init__(self, comp, s) + elif n in (6, 7): + self._mode = "normal" + x, y, z, vx, vy, vz = rest[:6] + s = rest[6] if n == 7 else kwargs.get("s", 500) + ArgsBase.__init__(self, comp, x, y, z, vx, vy, vz, s) + elif n in (9, 10): + self._mode = "normal_dir" + ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] + s = rest[9] if n == 10 else kwargs.get("s", 500) + ArgsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s) + else: + raise TypeError( + "Grid expects 0-1, 6-7 (origin + normal), or " + "9-10 (origin + X-dir + normal) arguments after optional comp" + ) 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] - vx = [xx, xy, xz] - vz = [zx, zy, zz] - # calculate the missing y vector - vy = [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]] + if self._mode == "origin": + (s,) = self.coords() + elif self._mode == "normal": + x, y, z, vx, vy, vz, s = self.coords() + _apply_normal_or_basis((x, y, z), (vx, vy, vz)) + else: + ox, oy, oz, xx, xy, xz, zx, zy, zz, s = self.coords() + _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz), (xx, xy, xz)) - 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]) + _draw_grid_lines(s) def unapply(self): - glPopMatrix() + if self._mode != "origin": + glPopMatrix() + + +HalGrid = Grid +HalGridFromNormal = Grid +HalGridFromNormalAndDirection = Grid + + +class Plane(ArgsBase): + """ + Replaces legacy class: + - HalPlaneFromNormal([comp,] x, y, z, vx, vy, vz, s=500) + and adds: + - Plane([comp,] s=500) + - Plane([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, s=500) + """ + def __init__(self, *args, **kwargs): + comp, rest = _split_comp(args) + n = len(rest) + + if n in (0, 1): + self._mode = "origin" + s = rest[0] if n == 1 else kwargs.get("s", 500) + ArgsBase.__init__(self, comp, s) + elif n in (6, 7): + self._mode = "normal" + x, y, z, vx, vy, vz = rest[:6] + s = rest[6] if n == 7 else kwargs.get("s", 500) + ArgsBase.__init__(self, comp, x, y, z, vx, vy, vz, s) + elif n in (9, 10): + self._mode = "normal_dir" + ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] + s = rest[9] if n == 10 else kwargs.get("s", 500) + ArgsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, s) + else: + raise TypeError("Plane expects 0-1, 6-7, or 9-10 arguments after optional comp") + def draw(self): + if self._mode == "origin": + (s,) = self.coords() + n = (0, 0, 1) + elif self._mode == "normal": + x, y, z, vx, vy, vz, s = self.coords() + n = (vx, vy, vz) + _apply_normal_or_basis((x, y, z), n) + else: + ox, oy, oz, xx, xy, xz, zx, zy, zz, s = self.coords() + n = (zx, zy, zz) + _apply_normal_or_basis((ox, oy, oz), n, (xx, xy, xz)) -# 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() - - def square(self, 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) - # line 1 in y direction - glVertex3f( i,-s, 0) - glVertex3f( i, s, 0) + glPushAttrib(GL_ENABLE_BIT) + glDisable(GL_CULL_FACE) + glBegin(GL_QUADS) + glNormal3f(*n) + glVertex3f(s, s, 0) + glVertex3f(-s, s, 0) + glVertex3f(-s, -s, 0) + glVertex3f(s, -s, 0) glEnd() + glPopAttrib() - 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]] + def unapply(self): + if self._mode != "origin": + glPopMatrix() + + +HalPlaneFromNormal = Plane + + +class Coords(ArgsBase): + """ + Replaces legacy class: + - HalCoordsFromNormalAndDirection ([comp,] ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch=1, r=5) + and adds: + - Coords([comp,] stretch=1, r=5) + - Coords([comp,] ox, oy, oz, zx, zy, zz, stretch=1, r=5) + """ + def __init__(self, *args, **kwargs): + comp, rest = _split_comp(args) + n = len(rest) + + if n <= 2: + self._mode = "origin" + stretch = rest[0] if n >= 1 else kwargs.get("stretch", 1) + r = rest[1] if n == 2 else kwargs.get("r", 5) + ArgsBase.__init__(self, comp, stretch, r) + elif n in (6, 7, 8): + self._mode = "normal" + ox, oy, oz, zx, zy, zz = rest[:6] + stretch = rest[6] if n >= 7 else kwargs.get("stretch", 1) + r = rest[7] if n == 8 else kwargs.get("r", 5) + ArgsBase.__init__(self, comp, ox, oy, oz, zx, zy, zz, stretch, r) + elif n in (9, 10, 11): + self._mode = "normal_dir" + ox, oy, oz, xx, xy, xz, zx, zy, zz = rest[:9] + stretch = rest[9] if n >= 10 else kwargs.get("stretch", 1) + r = rest[10] if n == 11 else kwargs.get("r", 5) + ArgsBase.__init__(self, comp, ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r) + else: + raise TypeError("Coords expects 0-2, 6-8, or 9-11 arguments after optional comp") + + def draw_vector(self, r, stretch, color): + glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, color) + gluCylinder(self.q, r, r, 50 * stretch, 32, 1) 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] - vx = [xx, xy, xz] - vz = [zx, zy, zz] - # calculate the missing y vector - vy = [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]] + if self._mode == "origin": + stretch, r = self.coords() + glPushMatrix() + elif self._mode == "normal": + ox, oy, oz, zx, zy, zz, stretch, r = self.coords() + _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz)) + else: + ox, oy, oz, xx, xy, xz, zx, zy, zz, stretch, r = self.coords() + _apply_normal_or_basis((ox, oy, oz), (zx, zy, zz), (xx, xy, xz)) - glPushMatrix() - glMultMatrixf(m_t) - self.square(s) + glPushAttrib(GL_LIGHTING_BIT) + self.draw_vector(r, stretch, [0, 0, 1, 1]) + glRotate(90, 0, 1, 0) + self.draw_vector(r, stretch, [1, 0, 0, 1]) + glRotate(-90, 1, 0, 0) + self.draw_vector(r, stretch, [0, 1, 0, 1]) + glPopAttrib() 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() - 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]) - 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 square(self,n, 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) - # line 1 in y direction - 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 - v = [vx, vy, vz] - length, angle, axis = self.polar(v) - glPushMatrix() - glTranslate(x,y,z) - glRotate(angle,*axis) - self.square(v,s) +HalCoordsFromNormalAndDirection = Coords - 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() - - def grid(self, 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) - # line 1 in y direction - glVertex3f( i,-s, 0) - glVertex3f( i, s, 0) - glEnd() +class _CylinderAxis(ArgsBase): + """Shared base class for axis-aligned capped cylinders (X, Y, or Z).""" + _axis_rotation = None # (angle_deg, x, y, z) or None for Z-axis def draw(self): - s = self.s - self.grid(s) + p1, r1, p2, r2 = self.coords() + if p1 > p2: + p1, p2 = p2, p1 + r1, r2 = r2, r1 - -# 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) + if self._axis_rotation is not None: + glRotatef(*self._axis_rotation) + glTranslatef(0, 0, p1) + gluCylinder(self.q, r1, r2, p2 - p1, 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 + glRotatef(180, 1, 0, 0) + + # Top cap glPushMatrix() - glTranslatef(0,0,z2-z1) + glTranslatef(0, 0, p2 - p1) gluDisk(self.q, 0, r2, 32, 1) glPopMatrix() glPopMatrix() 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 + p1, r1, p2, r2 = self.coords() + return (pi / 3.0) * abs(p1 - p2) * (r1 * r1 + r1 * r2 + r2 * r2) -# 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 CylinderX(_CylinderAxis): + _axis_rotation = (90, 0, 1, 0) - 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() - 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 +class CylinderY(_CylinderAxis): + _axis_rotation = (-90, 1, 0, 0) -class CylinderZ(CoordsBase): - def draw(self): - z1, r1, z2, r2 = self.coords() - if z1 > z2: - tmp = z1 - z1 = z2 - z2 = tmp - tmp = r1 - r1 = r2 - r2 = tmp - # need to translate the whole thing to z1 - glPushMatrix() - 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() +class CylinderZ(_CylinderAxis): + _axis_rotation = None - def volume(self): - z1, r1, z2, r2 = self.coords() - # 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 # give center and radius -class Sphere(CoordsBase): +class Sphere(ArgsBase): def draw(self): x, y, z, r = self.coords() # need to translate the whole thing to x,y,z @@ -796,7 +984,7 @@ def volume(self): # triangular plate in XY plane # specify the corners Z values for each side -class TriangleXY(CoordsBase): +class TriangleXY(ArgsBase): def draw(self): x1, y1, x2, y2, x3, y3, z1, z2 = self.coords() x12 = x1-x2 @@ -910,7 +1098,7 @@ def volume(self): return vol -class ArcX(CoordsBase): +class ArcX(ArgsBase): def draw(self): x1, x2, r1, r2, a1, a2, steps = self.coords() if x1 > x2: @@ -1019,7 +1207,7 @@ def volume(self): # six coordinate version - specify each side of the box -class Box(CoordsBase): +class Box(ArgsBase): def draw(self): x1, y1, z1, x2, y2, z2 = self.coords() if x1 > x2: @@ -1084,52 +1272,336 @@ def volume(self): # 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): + comp, rest = _split_comp(args) + if len(rest) == 0: + ArgsBase.__init__(self, comp) + elif len(rest) == 3: + ArgsBase.__init__(self, comp, *rest) + else: + raise TypeError("BoxCentered expects ([prefix,] xw, yw, zw)") + + def coords(self): + xw, yw, zw = ArgsBase.coords(self) + 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) + def __init__(self, *args): + comp, rest = _split_comp(args) + if len(rest) == 0: + ArgsBase.__init__(self, comp) + elif len(rest) == 3: + ArgsBase.__init__(self, comp, *rest) + else: + raise TypeError("BoxCenteredXY expects ([prefix,] xw, yw, zw)") + + def coords(self): + xw, yw, zw = ArgsBase.coords(self) + return [-xw / 2.0, -yw / 2.0, 0, xw / 2.0, yw / 2.0, zw] + + +def _mesh_source_stamp(filename, data): + """Returns a lightweight stamp for change detection on STL/OBJ sources.""" + if data is None and filename is not None: + st = os.stat(filename) + return ("file", os.path.abspath(filename), st.st_mtime_ns, st.st_size) + if isinstance(data, (str, bytes)): + return ("data", data) + return ("data", tuple(data)) + +def _compute_tri_normal(t): + dx1, dy1, dz1 = t[1][0] - t[0][0], t[1][1] - t[0][1], t[1][2] - t[0][2] + dx2, dy2, dz2 = t[2][0] - t[0][0], t[2][1] - t[0][1], t[2][2] - t[0][2] + return [dy1 * dz2 - dy2 * dz1, dz1 * dx2 - dz2 * dx1, dy1 * dx2 - dy2 * dx1] + +class _MeshBase: + """Shared base for reloadable STL and OBJ mesh loaders.""" + def __init__(self, filename=None, data=None): + self._filename = filename + self._data = data + self._source_stamp = None + self.list = None + self._stale_list = None + self._reset_storage() + self.reload(filename, data, force=True) + + def _reset_storage(self): + pass + + def _read_lines(self, filename=None, data=None): + if data is None: + with open(filename, "r", encoding="utf-8", errors="replace") as f: + return f.readlines() + if isinstance(data, bytes): + return data.decode("utf-8", errors="replace").splitlines() + if isinstance(data, str): + return data.split("\n") + return data + + def reload(self, filename=None, data=None, force=False): + """Reloads geometry only when the source file or data has changed (unless force=True).""" + if filename is not None: + self._filename = filename + self._data = None + elif data is not None: + self._data = data + self._filename = None + + new_stamp = _mesh_source_stamp(self._filename, self._data) + if not force and new_stamp == self._source_stamp: + return False + + self._load(self._filename, self._data) + self._source_stamp = new_stamp + if self.list is not None: + self._stale_list = self.list + self.list = None + return True + + def draw(self): + if self._stale_list is not None: + glDeleteLists(self._stale_list, 1) + self._stale_list = None + if self.list is None: + # OpenGL isn't ready yet in __init__ so the display list + # is created during the first draw + new_list = glGenLists(1) + glNewList(new_list, GL_COMPILE) + try: + self._emit_gl() + finally: + glEndList() + self.list = new_list + self._reset_storage() + glCallList(self.list) + + +class STL(_MeshBase): + """Loads both ASCII and Binary STL files or data buffers.""" + def _reset_storage(self): + self.d = [] + + def _load(self, filename=None, data=None): + raw_bytes = None + if data is None and filename is not None: + with open(filename, "rb") as f: + raw_bytes = f.read() + elif isinstance(data, bytes): + raw_bytes = data + + if raw_bytes is not None: + # Binary STL: 80-byte header + uint32 triangle count + 50 bytes per triangle + if len(raw_bytes) >= 84: + tri_count = struct.unpack("= 3 else None + if n: + glNormal3f(*self.vn[n - 1]) + else: + glNormal3f(*face_n) + glVertex3f(*self.v[v - 1]) + glEnd() + glPopAttrib() + + +AsciiSTL = STL +AsciiOBJ = OBJ + # 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 = [] + self.t = [ + [1.0, 0.0, 0.0, 0.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ] def capture(self): self.t = glGetDoublev(GL_MODELVIEW_MATRIX) - + + def world_pos(self, world=None): + if world is not None: + m = matmul(self.t, invert(world.t)) + return [m[3][0], m[3][1], m[3][2]] + return [self.t[3][0], self.t[3][1], self.t[3][2]] + def volume(self): return 0.0 -# 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 -# 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 +def _compile_hud_val(val, prefix_cache): + """Compiles a HUD value/condition into a zero-arg callable with legacy hal.get_value fallback.""" + if not isinstance(val, str): + return lambda v=val: v + s = val.strip() + if "{" in s or "}" in s: + return _compile_arg(s, None, prefix_cache) + if "." in s and s.split(".", 1)[0] in prefix_cache: + return _resolve_token(s, None, prefix_cache) + return lambda p=s: hal.get_value(p) + +def _compile_hud_template(template, prefix_cache): + """Compiles a HUD text string with optional '{expr}' or '{expr:.3f}' placeholders.""" + s = str(template) + if "{" not in s and "}" not in s: + return lambda text=s: text + + fmt_parts, getters = [], [] + i, n = 0, len(s) + while i < n: + open_idx = s.find("{", i) + if open_idx == -1: + fmt_parts.append(s[i:]) + break + # Only treat '{{...}}' as escaped literal braces when closed by '}}' + if open_idx + 1 < n and s[open_idx + 1] == "{" and "}}" in s[open_idx + 2:]: + close_esc = s.find("}}", open_idx + 2) + fmt_parts.append(s[i:close_esc + 2]) + i = close_esc + 2 + continue + + # Find matching closing '}' accounting for nested '{prefix.attr}' braces + brace_depth = 1 + j = open_idx + 1 + while j < n and brace_depth > 0: + if s[j] == "{": + brace_depth += 1 + elif s[j] == "}": + brace_depth -= 1 + j += 1 + if brace_depth != 0: + raise SyntaxError("Vismach Error: Unmatched '{' in Hud string %r" % template) + + close_idx = j - 1 + fmt_parts.append(s[i:open_idx]) + inner = s[open_idx + 1:close_idx].strip() + + expr_part, spec_part, depth = inner, "", 0 + for idx, ch in enumerate(inner): + if ch == "[": + depth += 1 + elif ch == "]": + depth = max(0, depth - 1) + elif ch == ":" and depth == 0: + expr_part = inner[:idx].strip() + spec_part = inner[idx:] + break + + if not expr_part: + fmt_parts.append("{" + spec_part + "}") + else: + wrapped = expr_part if "{" in expr_part else "{%s}" % expr_part + getters.append(_compile_arg(wrapped, None, prefix_cache)) + fmt_parts.append("{%d%s}" % (len(getters) - 1, spec_part)) + i = close_idx + 1 -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 + fmt_str = "".join(fmt_parts) + if not getters: + return lambda f=fmt_str: f + return lambda f=fmt_str, gs=getters: f.format(*[g() for g in gs]) # head up display - draws a semi-transparent text box. class Hud(object): @@ -1163,25 +1635,31 @@ 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 + # displays a string (supports '{prefix.attr}' expressions), optionally a tag or list of tags can be assigned def add_txt(self, string, tag=None): - self.hud_lines += [[str(string), None, tag]] + prefix_cache = _capture_caller_prefixes() + self.hud_lines += [[_compile_hud_template(string, prefix_cache), None, tag]] - # displays a formatted pin value (can be embedded in a string) + # displays a formatted pin or expression value (can be embedded in a string) def add_pin(self, string, pin=None, tag=None): - self.hud_lines += [[str(string), pin, tag]] + prefix_cache = _capture_caller_prefixes() + pin_fn = _compile_hud_val(pin, prefix_cache) if pin is not None else None + self.hud_lines += [[str(string), pin_fn, tag]] - # shows all lines with the specified tag if the pin value = val + # shows all lines with the specified tag if the pin/expression value = val def show_tag_if_same(self, tag, pin, val=True): - self.show_tags += [[tag, pin, val]] + prefix_cache = _capture_caller_prefixes() + self.show_tags += [[tag, _compile_hud_val(pin, prefix_cache), val]] - # shows all lines with a tag equal to the pin value + offset + # shows all lines with a tag equal to the pin/expression value + offset def show_tags_in_pin(self, pin, offs=0): - self.show_tags += [[pin, None, offs]] + prefix_cache = _capture_caller_prefixes() + self.show_tags += [[_compile_hud_val(pin, prefix_cache), None, offs]] - # hides the complete hud if the pin value is equal to val + # hides the complete hud if the pin/expression value is equal to val def hide_all(self, pin, val=True): - self.hide_alls += [[pin, val]] + prefix_cache = _capture_caller_prefixes() + self.hide_alls += [[_compile_hud_val(pin, prefix_cache), val]] # changes the hud color and transparency def set_hud_rgba(self, r, g, b, a): @@ -1203,16 +1681,19 @@ def draw(self): # check if hud should be hidden hide_hud_requested = False for a in self.hide_alls: - if hal.get_value(a[0]) == a[1]: + cur_val = a[0]() if callable(a[0]) else hal.get_value(a[0]) + if cur_val == 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]) + raw_val = b[0]() if callable(b[0]) else hal.get_value(b[0]) + tag = int(raw_val + b[2]) else: # _show_tag_if_same - if hal.get_value(b[1]) == b[2]: + cur_val = b[1]() if callable(b[1]) else hal.get_value(b[1]) + if cur_val == b[2]: tag = b[0] if not isinstance(tag, list): tag = [tag] @@ -1224,9 +1705,10 @@ def draw(self): c[2] = [c[2]] if any(item in c[2] for item in show_list): if c[1] == None: # _txt - messages += [c[0]] + messages += [c[0]() if callable(c[0]) else c[0]] else: # _pin - messages += [c[0].format(hal.get_value(c[1]))] + val = c[1]() if callable(c[1]) else hal.get_value(c[1]) + messages += [c[0].format(val)] drawtext = self.strs + messages # draw head-up-display @@ -1316,6 +1798,7 @@ def basic_lighting(self): 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)) + glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, (0.0, 0.0, 0.0, 1.0)) glDisable(GL_CULL_FACE) glEnable(GL_LIGHTING) glEnable(GL_LIGHT0) @@ -1324,13 +1807,34 @@ def basic_lighting(self): glEnable(GL_DEPTH_TEST) glMatrixMode(GL_MODELVIEW) glLoadIdentity() - - - def redraw(self, *args): + global _stats_fresh, _render_pass, _has_transparent if self.winfo_width() == 1: return + poll_all_stats() + + # Pass 1: Opaque geometry (also updates all Capture() transforms) + _render_pass = "opaque" + _has_transparent = False + glDepthMask(GL_TRUE) + glDisable(GL_BLEND) self.model.traverse() + + # Pass 2: Translucent geometry (only if any alpha < 1.0 was seen) + if _has_transparent: + _render_pass = "transparent" + glEnable(GL_BLEND) + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + glDepthMask(GL_FALSE) + glEnable(GL_CULL_FACE) + glCullFace(GL_BACK) + self.model.traverse() + glDisable(GL_CULL_FACE) + glDepthMask(GL_TRUE) + glDisable(GL_BLEND) + + _render_pass = "opaque" + _stats_fresh = False # current coords: world # the matrices tool2view, work2view, and world2view # transform from tool/work/world coords to viewport coords @@ -1417,128 +1921,11 @@ def redraw(self, *args): def plotclear(self): del self.plotdata[:self.plotlen] -class Color(Collection): - def __init__(self, color, parts): - self.color = color - Collection.__init__(self, parts) - - def apply(self): - glPushAttrib(GL_LIGHTING_BIT) - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, self.color) - - def unapply(self): - glPopAttrib() - -class AsciiSTL: - def __init__(self, filename=None, data=None): - if data is None: - data = open(filename, "r") - elif isinstance(data, str): - data = data.split("\n") - self.list = None - t = [] - 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]) - if len(t) == 3: - if n == [0,0,0]: - 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] - d.append((n, t)) - t = [] - n = [0,0,0] - - def draw(self): - if self.list is None: - # OpenGL isn't ready yet in __init__ so the display list - # is created during the first draw - self.list = glGenLists(1) - glNewList(self.list, GL_COMPILE) - glBegin(GL_TRIANGLES) - for n, t in self.d: - glNormal3f(*n) - glVertex3f(*t[0]) - glVertex3f(*t[1]) - glVertex3f(*t[2]) - glEnd() - glEndList() - del self.d - glCallList(self.list) - -class AsciiOBJ: - def __init__(self, filename=None, data=None): - if data is None: - data = open(filename, "r") - elif isinstance(data, str): - data = data.split("\n") - - self.v = v = [] - self.vn = vn = [] - self.f = f = [] - for line in data: - if line.startswith("#"): continue - if line.startswith("vn"): - vn.append([float(w) for w in line.split()[1:]]) - elif line.startswith("v"): - v.append([float(w) for w in line.split()[1:]]) - 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 - return int(i) - - def parse_slash(self, word): - return [self.parse_int(i) for i in word.split("/")] - - def parse_face(self, line): - return [self.parse_slash(w) for w in line.split()[1:]] - - def draw(self): - if self.list is None: - # OpenGL isn't ready yet in __init__ so the display list - # is created during the first draw - self.list = glGenLists(1) - 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: - if n: - glNormal3f(*self.vn[n-1]) - glVertex3f(*self.v[v-1]) - glEnd() - glEndList() - del self.v - del self.vn - del self.f - glCallList(self.list) - old_plotclear = False -def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0): +def main(model, tool, work, size=10, hud=0, rotation_vectors=None, lat=0, lon=0, function=None): + _check_stats_ready() app = tkinter.Tk() import nf hidpi = nf.init_hidpi(app) @@ -1582,13 +1969,18 @@ 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 + _stats_fresh = False + poll_all_stats() + if function: + function() t.tkRedraw() 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() def quit(*args):