# cadcube

[![CTAN](https://img.shields.io/ctan/v/cadcube.svg?label=CTAN)](https://ctan.org/pkg/cadcube) [![Release](https://img.shields.io/github/v/release/janniksvenson/cadcube.svg?label=Release)](https://github.com/janniksvenson/cadcube/releases) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.23695624.svg)](https://doi.org/10.5281/zenodo.23695624) [![License: LPPL 1.3c](https://img.shields.io/badge/License-LPPL_1.3c-blue.svg)](https://www.latex-project.org/lppl/) [![Author](https://img.shields.io/badge/Author-Jannik_Svenson-blue.svg)](https://github.com/janniksvenson)

`cadcube` is a modular, TikZ-based LaTeX package providing 3D and 2D orientation overlays similar to the "Axis" or "View Cubes" found in CAD, CFD, and scientific visualization software. It allows coordinate indicators to be overlaid dynamically on top of any LaTeX box, image, graphic, or TikZ figure with zero layout shift using either named cardinal anchors or precise percentage-based coordinates. The package features built-in coordinate presets, customizable camera projections, full control over vector geometry and colors, and automatic Z-buffer sorting.

**Documentation:** Please refer to the [compiled PDF manual](cadcube.pdf) for a complete feature overview and usage examples.

## Gallery

| `cartesian` | `cartesian-uvw` | `cylindrical` | `spherical` | `planar` | `polar` |
| :---: | :---: | :---: | :---: | :---: | :---: |
| ![Cartesian](examples/cadcube_cartesian.png) | ![Cartesian UVW](examples/cadcube_cartesian-uvw.png) | ![Cylindrical](examples/cadcube_cylindrical.png) | ![Spherical](examples/cadcube_spherical.png) | ![Planar](examples/cadcube_planar.png) | ![Polar](examples/cadcube_polar.png) |

---

## 1. Installation

### Option A: TeX Distribution (TeX Live / MiKTeX)

`cadcube` is available on CTAN. You can install it directly via your TeX distribution's package manager (e.g., via the **MiKTeX Console** or in **TeX Live**):

```bash
tlmgr install cadcube
```

### Option B: Project-local (Manual)

Simply place the `cadcube.sty` file into the root directory of your LaTeX project (the same folder as your `.tex` file).

### Option C: System-wide Local Tree (Manual)

Place `cadcube.sty` into your local `TEXMF` tree (e.g., `~/texmf/tex/latex/cadcube/` on Linux/macOS) and run `texhash` or `mktexlsr` so your TeX distribution can find it from any directory.

---

## 2. Basic Usage

Load the package in your preamble:

```latex
\usepackage{cadcube}
```

> **Note:** `cadcube` automatically loads `tikz` and `xcolor`. If your main document already loads these packages, LaTeX will safely handle it without causing conflicts or double-loading.

To place an orientation overlay on top of an object (like an image), wrap the object in the `\cadcubeoverlay` command:

```latex
\begin{figure}[H]
    \centering
    \cadcubeoverlay[preset=cartesian, view=+x+y, location=north east]{
        \includegraphics[width=0.8\textwidth]{my_cad_geometry.png}
    }
    \caption{CAD Geometry with CADcube overlay.}
\end{figure}
```

To place a standalone orientation cube without an underlying image (e.g. in a `figure`, `wrapfigure`, table cell, or inline text), use `\cadcube`:

```latex
\begin{figure}[H]
    \centering
    \cadcube[preset=cartesian, size=2cm, view=iso]
    \caption{Standalone orientation cube.}
\end{figure}
```

You can globally set options for all following cubes using:

```latex
\cadcubeset{size=2cm, up=y, grayscale=true}
```

---

## 3. Options Reference

`cadcube` is highly parameterized. You can pass these options to `\cadcubeoverlay[<options>]{...}`, `\cadcube[<options>]`, or globally via `\cadcubeset{<options>}`.

### 3.1 Core Settings

| **Option** | **Default** | **Description** |
| :--- | :--- | :--- |
| `preset` | `cartesian` | Loads a predefined set of properties (shape, colors, labels). |
| `size` | `10mm` | The global bounding box size of the overlay indicator. |
| `location` | `south west` | Anchors overlay relative to content: `west`, `north west`, `north`, `north east`, `center`, ... or percentage `{(75,30)}`. |
| `margin` | `5pt` | The distance between the anchor point and the overlay itself (also `margin X/Y`). |
| `view` | `iso` | Camera projection mode or dynamic camera definition (see *Camera Views*). |
| `cam phi` | `45` | Azimuth angle (rotation around Z-axis in degrees) for dynamic camera. |
| `cam theta` | `54.736` | Zenith angle (elevation in degrees) for dynamic camera. `0` is top-down, `90` is horizontal, `54.736` is iso. |
| `cam roll` | `0` | 2D canvas rotation angle. Rotates projected cube without misaligning text labels. |
| `up` | `z` | Defines vertical upward axis (`x, y, z`); automatically rotates other axes to preserve right-hand rule. |
| `left handed` | `false` | If `true`, mirrors horizontal axes to create a left-handed coordinate system. |
| `grayscale` | `false` | Overrides all colors with shades of gray/black for black-and-white printing. |

> **Spatial Anchoring & Coordinate Systems:**
> * **Anchoring:** The `location` parameter supports standard cardinal anchors (`north west`, `center`, `north east`, `south west`, etc.) as well as fine fractional percentage anchors in the form `{(x,y)}` where `{(0,0)}` represents bottom-left and `{(100,100)}` top-right of the wrapped graphic.
> * **Up-Vector Logic:** The `up` option accepts `x, +x, -x, y, +y, -y, z, +z, -z`. The package automatically recalculates the orthogonal basis to strictly satisfy a right-handed system ($\vec{e}_x \times \vec{e}_y = \vec{e}_z$). Setting `left handed=true` dynamically inverts the horizontal plane.

### 3.2 Visibility Toggles

| **Option** | **Default** | **Description** |
| :--- | :--- | :--- |
| `show axes` | `true` | Toggles coordinate vectors (arrows) on/off. |
| `show arrow tips` | `true` | Toggles arrowhead tips at vector ends (alias: `show vector tips`). |
| `show planes` | `true` | Toggles intersection/projection planes on/off. |
| `show shape` | `true` | Toggles the base geometry (cube, cylinder, sphere, square, disk) on/off. |
| `show labels` | `true` | Toggles text labels on the axes on/off. |
| `show negative axes` | `false` | Draws negative tails of coordinate axes into negative quadrants. |
| `pie slice` | `false` | Draws a filled "pie slice" to visualize angular variables ($\varphi, \theta$). |

> **Component Deconstruction:**
> * **Minimalist Tripod:** Setting `show planes=false` and `show shape=false` leaves only the 3D axis arrows (*axis tripod*), preferred in dense technical schematics.
> * **Solid Navigation Cube:** Setting `show axes=false` leaves only the shaded solid body with optional face labels.
> * **Sweep Slices:** `pie slice=true` highlights angular sweeps ($\varphi, \theta$) in cylindrical and spherical coordinates.

### 3.3 Geometry & Layout

| **Option** | **Default** | **Description** |
| :--- | :--- | :--- |
| `shape` | `cube` | Base geometry solid: `cube`, `square`, `disk`, `cylinder`, `sphere`, `none`. |
| `axes type` | `3D` | Coordinate vector logic: `3D`, `2D`, `cylindrical`, `spherical`, `polar`. |
| `shape scale` | `0.25` | Size of the geometric shape relative to the vector length. |
| `plane scale` | `1.00` | Size of intersection planes relative to the vectors. |
| `arrow length` | `1.00` | Primary length scaling factor for coordinate vectors (all sub-scales normalize to this). |
| `arrow line width` | `0.5pt` | Line thickness of the vector shafts. |
| `arrow tip` | `Stealth` | Arrowhead style (`Stealth`, `Latex`, `Triangle`, `To`, `Circle`, `none`) or TikZ spec. |
| `arrow tip length` | `3.5pt` | Arrowhead length with unit or factor of vector length (e.g. `0.4`). |
| `arrow tip width` | `2.5pt` | Arrowhead width with unit or factor of shaft line width (e.g. `6`). |
| `flat scale` | `1.50` | Relative size of out-of-plane markers ($\odot$, $\otimes$) in 2D orthogonal views. |
| `label flat sep` | `2pt` | Radial spacing between out-of-plane markers ($\odot$, $\otimes$) and their axis label (alias: `flat gap`). |
| `inner axis style` | `densely dotted` | TikZ style applied to the portion of axes *inside* the 3D shape. |
| `outer axis style` | *none* | TikZ style applied to the portion of axes *outside* the 3D shape. |

> **Proportions & 2D Singularities:**
> * `arrow length` serves as the primary master multiplier on the coordinate scale ($L = \text{arrow length} \times \text{size} \times 0.35$). Sub-elements (`shape scale=0.25` and `plane scale=1.00`) are normalized relative to this arrow length.
> * In head-on orthogonal views (e.g., `view=+z`), zero-length vectors are automatically replaced with ISO drafting symbols ($\odot$ = pointing towards viewer, $\otimes$ = pointing away). The marker radius scales proportionally via `flat scale`.

### 3.4 Labels & Text

| **Option** | **Default** | **Description** |
| :--- | :--- | :--- |
| `label X`<br>`label Y`<br>`label Z` | `x`<br>`y`<br>`z` | Text labels for primary, secondary, and tertiary coordinate axes/angles. |
| `labels` | `{x, y, z}` | Shortcut for naming the three axes (automatically placed in math mode). |
| `label pos` | `end` | Position along vector: `end` (tip) or `mid` (shaft center; dynamically placed beside vertical axes). |
| `label font` | `\sffamily`<br>`\bfseries` | Font styling applied to axis text labels. |
| `label scale` | `1` | Scaling factor for axis text labels. |
| `font size` | `\scriptsize` | Global font size for all labels (\LaTeX{} switch like `\footnotesize` or dimension like `8pt`). |
| `label font size` | *none* | Font size specifically for axis/angle labels (overrides `font size`). |
| `label inner sep` | `1.5pt` | Inner padding for axis, arc, and flat-mode label nodes. |
| `arc radius` | `1.35` | Radial distance multiplier for angle labels ($\varphi, \theta$) in curved presets. |
| `label math mode` | `true` | Wraps labels in `$...`. Set to `false` for plain text or glossary macros. |
| `show face labels` | `false` | Toggles solid shape face text on/off (default inscriptions: $x, y, z$). |
| `faces` | *none* | Shortcut to label the three visible positive faces: `{Right, Top, Front}`. |
| `faces all` | *none* | Shortcut to label all six solid faces: `{+X, -X, +Y, -Y, +Z, -Z}`. |
| `face label col` | *empty* | Color of text printed on shape faces (falls back to darkened axis color). |
| `face font size`<br>`face label font size` | *none* | Font size specifically for shape face labels (alias: `face label font size`; overrides `font size`). |
| `face label scale` | `0.65` | Scaling factor for solid shape face text labels. |
| `face label inner sep` | `1.0pt` | Inner padding for shape face label nodes. |

> **Typography & Annotations:**
> * `label math mode=true` allows seamless mathematical notation (`labels={x_1, \mathbf{Y}, z^*}`). Set to `false` for plain text strings or macros.
> * `show face labels=true` enables face annotations on solid shapes (defaults: $x, -x, y, -y, z, -z$). `faces={Right, Top, Front}` customizes positive faces and activates them automatically.
> * `font size` sets a global font size switch (e.g., `\footnotesize`, `\scriptsize`) or dimension (`8pt`), while `label font size` and `face font size` (alias: `face label font size`) allow independent control for outer axes and cube faces.
> * `label inner sep` (default: `1.5pt`) and `face label inner sep` (default: `1.0pt`) configure node inner margins to prevent collision with bounding geometry.

### 3.5 Colors, Backgrounds & Opacities

| **Option** | **Default** | **Description** |
| :--- | :--- | :--- |
| `col X`<br>`col Y`<br>`col Z` | `red!85!black`<br>`green!65!black`<br>`blue!80!black` | Explicit colors for individual coordinate axes (and associated planes). |
| `col plane XY`<br>`col plane XZ`<br>`col plane YZ` | `blue!45`<br>`green!45`<br>`red!45` | Colors for intersecting coordinate planes (default: matching axes). |
| `col shape edge` | `none` | Wireframe edge color: `none` (borderless), `auto` (`black!80` for cube/square, `white` for sphere), or explicit color. |
| `opacity front` | `0.50` | Opacity of faces facing camera (1.0 = fully opaque). |
| `opacity planes` | `0.35` | Opacity of intersecting coordinate planes. |
| `opacity back` | `1.00` | Opacity of rear-facing walls to enhance 3D depth. |
| `opacity axes` | `1.0` | Opacity of primary coordinate axis vectors. |
| `opacity negative axes` | `0.5` | Opacity of negative axis extensions in negative octants. |
| `darken mix` | `60` | Mix ratio (remaining color in percent) for auto-generated label and marker colors with black. |
| `marker col` | *empty* | Explicit color for out-of-plane 2D markers (falls back to darkened axis color). |
| `background color` | `none` | Adds a distinct background shape behind the CAD cube. |
| `background shape` | `rectangle` | Shape of background card: `rectangle`, `rounded`, or `circle`. |
| `background margin` | `5pt` | Padding around vectors for background card (also `background margin X/Y`). |
| `background corner radius` | `4pt` | Corner rounding radius for `background shape=rounded` cards. |

> **Depth Perception & Contrast Backdrops:**
> * Asymmetric dual opacity (`opacity front=0.5` vs `opacity back=1.00`) resolves Necker cube ambiguity on 2D paper.
> * `grayscale=true` automatically shifts all colors to calibrated luminance tones for monochrome printing.
> * `background color=white!90!black` provides a high-contrast backing card over dense simulation contour maps or dark CAD viewports.

## 4. Camera Views (`view=...`)

The package automatically handles Z-buffering (what is drawn in front/back) for more than 100 standardized views. The Z-ordering uses an advanced eleven-layer architecture (`cadcubebg`, `cadcubebackoutvec`, `cadcubeback`, `cadcubebackinvec`, `cadcubeplanes`, `cadcubecross`, `cadcubefrontinvec`, `main`, `cadcubefront`, `cadcubefrontoutvec`, `cadcubedot`) to flawlessly stack inner/outer vectors, planes, out-of-plane markers, and shape faces without graphical glitches. Pass these to the `view` parameter:

### Orthogonal views

* **Base Planes:** `+x`, `-x`, `+y`, `-y`, `+z`, `-z`, `xy`, `xz`, `yz`

### Axonometric views

Each of the following projection styles supports 8 corner views (e.g. `+++`, `+--`) and 12 edge views (e.g. `+x+y`, `-y+z`). Simply append the suffix to the base style name:

* **Isometric:** `iso` (default), `iso+++`, `iso-++`, `iso--+`, `iso+-+`, `iso++-`, `iso+--`, `iso-+-`, `iso---`, `iso+x+y`, `iso-y-z`, etc.

* **Dimetric:** `dimetric+++`, `dimetric-++`, `dimetric+x-y`, etc.

* **Trimetric:** `trimetric+++`, `trimetric--+`, `trimetric-x+z`, etc.

### Oblique views (Plan Oblique & Elevation Oblique)

Similar to axonometric views, oblique projections support all corner and edge suffixes:

* **Cabinet (Half Depth):** `cabinet+++`, `cabinet-+-`, `cabinet+y+z`, etc.

* **Cavalier (Full Depth):** `cavalier+++`, `cavalier+--`, `cavalier-x-z`, etc.

* **Military (Plan Oblique):** `military+++`, `military---`, `military+x-y`, etc.

### Other views

* **Custom:** `free` (Demonstrates an arbitrary custom angle).

### Dynamic Cameras (Spherical & Oblique)

Instead of using static predefined angles, you can freely position the camera using spherical coordinates. `cadcube` features an advanced dynamic rendering engine that automatically calculates **Z-buffer sorting** (what is drawn in front/back) for any custom angle on the fly. 

> **Important:** You *must* wrap functional commands like `cam(...)` and `oblique(...)` in curly braces `{}` so the LaTeX key-value parser doesn't split your arguments at the commas!

#### Orthogonal Camera (Spherical Coordinates)
Use the syntax `view={cam(phi, theta, roll)}` for true 3D spatial rotations.
```latex
% Custom view: 45° azimuth, 30° zenith (looking slightly down), no roll
\cadcubeoverlay[view={cam(45, 30, 0)}]{...}

% Alternatively, use individual keys without curly braces:
\cadcubeoverlay[view=cam, cam phi=45, cam theta=30, cam roll=0]{...}
```
* **`phi` (Azimuth):** Rotation around the Z-axis in the XY-plane.
* **`theta` (Zenith):** Elevation angle. `0` means looking straight down from the top (+Z), `90` means looking exactly horizontally along the XY-plane. 
* **`roll`:** Rotates the final 2D projection on your screen. The brilliant part: while the axes rotate, text labels remain perfectly upright and readable.
  
#### Oblique Camera (Affine Shear)
Since Oblique projections (like Cabinet or Cavalier) preserve the 90° angles of a specific 2D plane by skewing the depth axis, they cannot be modeled using a standard 3D camera. You can define any arbitrary oblique shear using the syntax `view={oblique(v, alpha, axis, roll)}`.

```latex
% Custom Oblique: Depth axis is -Y, foreshortening 0.5, drawn at 45°
\cadcubeoverlay[view={oblique(0.5, 45, -y, 0)}]{...}
```

- **`v`:** Foreshortening factor of the depth axis (e.g., `0.5` for Cabinet, `1.0` for Cavalier).
- **`alpha`:** The 2D drawing angle of the depth axis on your paper/canvas (e.g., `45` or `225`).
- **`axis`:** The depth axis. Accepts `x, -x, y, -y, z, -z`. The package automatically reconstructs the unaffected 2D frontal plane based on a strict right-hand rule.
- **`roll`:** Rotates the final 2D projection on your screen.

  *(Note: Static strings like `view=cabinet` are essentially semantic aliases for specific `oblique(...)` matrices.)*

#### Automatic Flat-Mode Detection
When your dynamic camera looks *exactly* head-on or tail-on at an axis (e.g., looking straight down at the Z-axis with `theta=0`), the package automatically detects this via internal projection math. The 0-length vector is dynamically replaced with an out-of-plane marker:

- $\odot$ (**Dot**) if the axis points towards the camera.
- $\otimes$ (**Cross**) if the axis points away from the camera.

Text labels are automatically shifted radially outwards via `atan2` calculations to prevent overlapping.

---

## 5. Advanced Customization

### 5.1 Creating Custom Presets

If you frequently need a specific setup (e.g., a `my-cylindrical` preset with different labels and custom colors), you can define it using `\tikzset`:

```latex
\tikzset{
  /cadcube/my-cylindrical/.style={
    shape=cylinder, 
    axes type=cylindrical, 
    label math mode=false,
    labels={Radius, \gls{phi}, Height}, 
    col X=blue, col Y=red, col Z=black,
    up=y
  }
}
```

You can then use it simply via `\cadcubeoverlay[preset=my-cylindrical]{...}`.

### 5.2 Defining Custom Camera Views

If the standard perspectives aren't enough, you can define your own arbitrary projection matrix using standard TikZ coordinate system mappings.

Because the package uses internal `@` macros, you must wrap your definition in `\makeatletter` ... `\makeatother`:

```latex
\makeatletter

\tikzset{
  % Define a new view named "mycustomview"
  cadcube@proj@mycustomview/.style = {
    x={(0.8cm, -0.1cm)}, 
    y={(0.4cm, 0.7cm)}, 
    z={(-0.2cm, 0.9cm)}
  }
}

\makeatother
```

Now you can call it with: `\cadcubeoverlay[view=mycustomview]{...}`.

> **Note:** Custom views fallback to the default `iso` Z-buffer sorting logic for front/back plane rendering.

> **Tip:** Before manually calculating projection matrices for `\tikzset`, check if the built-in dynamic camera (`view={cam(phi, theta, roll)}`) can already achieve your desired angle! The dynamic camera has the added benefit of flawless automatic Z-buffering.

### 5.3 Inner and Outer Axis Styling

By default, the portion of an axis that lies *inside* the 3D shape is rendered as `densely dotted` to indicate that it is hidden or piercing through the solid object. The portion *outside* remains solid. You can fully customize this using standard TikZ properties to create technical, blueprint-like, or artistic designs:

```latex
\cadcubeset{
  inner axis style={dashed, gray, very thin},
  outer axis style={solid, thick}
}
```
If you set `show shape=false`, only the outer axis style is applied as a single continuous line.

---

## 6. Acknowledgments & Related Work

- Built on top of [TikZ/PGF](https://ctan.org/pkg/pgf) and [xcolor](https://ctan.org/pkg/xcolor).
- Inspired by orientation cubes in CAD, CFD, and 3D modeling tools.

---

## 7. License & Copyright

Copyright (c) 2026 Jannik Svenson <94602613+janniksvenson@users.noreply.github.com>.

This work may be distributed and/or modified under the conditions of the **LaTeX Project Public License (LPPL)**, either version 1.3c or (at your option) any later version. The latest version of this license is in [https://www.latex-project.org/lppl.txt](https://www.latex-project.org/lppl.txt).

See `LICENSE` for more details.
