# agg-sharp Submodule Documentation This directory contains comprehensive documentation of the agg-sharp submodule, the custom graphics and UI framework powering MatterControl. ## Overview **agg-sharp** (Anti-Grain Geometry for C#) is a comprehensive graphics library providing: - 2D software rasterization and vector graphics - Custom widget-based UI framework - 3D mesh data structures and operations - OpenGL rendering integration - Font/typography support - Mathematical primitives and geometry algorithms **Technology Stack:** - .NET 6.0 (C#) - OpenGL (via abstraction layer) - Software rasterization (AGG port) - Multiple font format support (TTF, OTF, WOFF) ## Documentation Index | # | Feature | Description | |---|---------|-------------| | 1 | [Core Graphics (agg)](#1-core-graphics-agg) | 2D vector rendering, image buffers, colors, transforms | | 2 | [GUI Widget System](#2-gui-widget-system) | Widget hierarchy, layout, input, theming | | 3 | [PolygonMesh](#3-polygonmesh) | 3D mesh structures, CSG, file formats | | 4 | [VectorMath](#4-vectormath) | Vectors, matrices, geometric primitives | | 5 | [RenderOpenGL](#5-renderopengl) | OpenGL integration, mesh rendering | | 6 | [DataConverters](#6-dataconverters) | 2D/3D format conversion, Object3D hierarchy | | 7 | [Typography](#7-typography) | Font loading, text shaping, glyph layout | | 8 | [CSG Module](#8-csg-module) | Declarative solid geometry | | 9 | [Supporting Libraries](#9-supporting-libraries) | Clipper, Triangle, geometry3Sharp, etc. | ## Project Structure ``` Submodules/agg-sharp/ ├── agg/ # Core 2D graphics (Anti-Grain Geometry) ├── Gui/ # Widget system and UI framework ├── PolygonMesh/ # 3D mesh data structures ├── VectorMath/ # Linear algebra primitives ├── RenderOpenGl/ # OpenGL rendering integration ├── DataConverters2D/ # 2D data conversion utilities ├── DataConverters3D/ # 3D scene graph and file formats ├── Typography/ # Font loading and text rendering ├── Csg/ # Constructive Solid Geometry ├── clipper_library/ # 2D polygon clipping ├── Tesselate/ # Polygon tessellation ├── Triangle/ # Delaunay triangulation ├── geometry3Sharp/ # 3D geometry algorithms ├── ImageProcessing/ # Image manipulation ├── Localizations/ # Translation support ├── QuadTree/ # Spatial indexing └── examples/ # Sample applications ``` --- # 1. Core Graphics (agg) ## Quick Summary The `agg` module is a C# port of Anti-Grain Geometry providing high-quality 2D software rasterization with anti-aliasing, vector path rendering, image compositing, and color management. ## Technical In-Depth Review ### Architecture The rendering pipeline follows the classic AGG model: ``` IVertexSource (paths) → ScanlineRasterizer → IScanlineCache → ScanlineRenderer → ImageBuffer (with blenders) ``` ### Core Components **Graphics2D** - Main rendering API (`agg/Graphics2D.cs`) - Abstract base class for all 2D rendering operations - Provides drawing primitives: `Line()`, `Circle()`, `Rectangle()`, `FillRectangle()` - Text rendering: `DrawString()` with font support - Transform stack: `PushTransform()`, `PopTransform()`, `SetTransform()` - Extensible via `ImageGraphics2D` concrete implementation **ImageBuffer** - Pixel storage (`agg/Image/ImageBuffer.cs`) - BGRA pixel format (32-bit and 24-bit support) - Configurable stride for memory alignment - Events: `ImageChanged` for reactive updates - Float variant: `ImageBufferFloat` for high-precision **ScanlineRasterizer** - Anti-aliased rasterization (`agg/ScanlineRasterizer.cs`) - 24.8 fixed-point subpixel precision - Filling rules: Non-zero and Even-odd - Gamma correction support - Cell-based anti-aliasing via `RasterizerCellsAa` **Vertex Sources** (`agg/VertexSource/`) - `VertexStorage` - Path container with MoveTo/LineTo/Curve commands - `Ellipse`, `Arc`, `RoundedRect` - Geometric primitives - `Stroke` - Converts paths to stroked outlines (configurable joins/caps) - `FlattenCurves` - Bezier to line segment conversion - `VertexSourceApplyTransform` - Applies affine transforms **Transforms** (`agg/Transform/`) - `Affine` - 2x3 affine transformation matrix - `Bilinear`, `Perspective` - Advanced transformations - Factory methods: `NewTranslation()`, `NewRotation()`, `NewScaling()` **Color System** (`agg/Primitives/Color.cs`) - `Color` struct - BGRA 8-bit per channel - `ColorF` - Floating-point precision variant - Both 0-255 and 0.0-1.0 property accessors - Predefined constants: Black, White, Red, etc. **Blenders** (`agg/Image/Blenders/`) - `BlenderBGRA` - Standard alpha blending - `BlenderPreMultBGRA` - Pre-multiplied alpha - `BlenderGammaBGRA` - Gamma-corrected blending - Interface: `IRecieveBlenderByte`, `IRecieveBlenderFloat` ### Design Choices - **Software rendering**: Provides pixel-perfect cross-platform consistency - **Scanline-based**: Cache-friendly horizontal processing - **Subpixel precision**: 8 fractional bits for smooth anti-aliasing - **Composable transforms**: Matrix multiplication via operator overloading ## API Reference ### Core Classes | Class | Location | Description | |-------|----------|-------------| | `Graphics2D` | agg/Graphics2D.cs | Abstract rendering API | | `ImageGraphics2D` | agg/Image/ImageGraphics2D.cs | ImageBuffer renderer | | `ImageBuffer` | agg/Image/ImageBuffer.cs | Pixel buffer | | `ScanlineRasterizer` | agg/ScanlineRasterizer.cs | AA rasterization | | `ScanlineRenderer` | agg/ScanlineRenderer.cs | Scanline to pixels | | `Color` | agg/Primitives/Color.cs | BGRA color | | `Affine` | agg/Transform/Affine.cs | 2D transformation | | `VertexStorage` | agg/VertexSource/VertexStorage.cs | Path container | ### Key Interfaces | Interface | Purpose | |-----------|---------| | `IVertexSource` | Path/shape data provider | | `IColorType` | Color abstraction | | `IScanlineCache` | Scanline coverage data | | `IRecieveBlenderByte` | Pixel blending strategy | --- # 2. GUI Widget System ## Quick Summary The `Gui` module provides a complete widget-based UI framework with hierarchical layouts, input handling, theming, and platform abstraction. All UI elements inherit from `GuiWidget`. ## Technical In-Depth Review ### Widget Hierarchy ``` GuiWidget (base) ├── Properties: BackgroundColor, Border, Padding, Margin ├── Layout: HAnchor, VAnchor, LayoutEngine ├── Children: AscendableSafeList ├── Input: Mouse/Keyboard events, Focus management └── Rendering: Invalidation, double-buffering ``` ### Layout System **Anchoring** (`GuiWidget.cs`) - `HAnchor`: Left, Center, Right, Fit, Stretch, MaxFitOrStretch - `VAnchor`: Bottom, Center, Top, Fit, Stretch, MaxFitOrStretch - Controls automatic sizing and positioning relative to parent **Layout Engines** (`Gui/LayoutEngines/`) - `LayoutEngineSimpleAlign` - Basic anchor-based alignment - `LayoutEngineFlow` - Sequential flow layout (horizontal/vertical) - `FlowLayoutWidget` - Convenience container using flow layout **FlowDirection Enum:** - `LeftToRight`, `RightToLeft`, `TopToBottom`, `BottomToTop` ### Input Handling **Mouse Events:** - `MouseDown`, `MouseUp`, `Click` - Button interactions - `MouseMove`, `MouseEnter`, `MouseLeave` - Position tracking - `MouseWheel` - Scroll support - `GestureFling` - Touch gestures **Keyboard Events:** - `KeyDown`, `KeyUp` - Key state changes - `KeyPressed` - Character input **Focus Management:** - `Focus()`, `Unfocus()` - Manual control - `Focused`, `ContainsFocus` - State queries - `TabStop`, `TabIndex` - Tab navigation ### Platform Abstraction **SystemWindow** (`Gui/SystemWindow/SystemWindow.cs`) - Top-level window container - Properties: `Title`, `IsModal`, `UseOpenGL` - Manages tooltip display via `ToolTipManager` **IPlatformWindow** Interface: - `Caption`, `DesktopPosition`, `MinimumSize` - `BringToFront()`, `Activate()`, `Close()` - `SetCursor()`, `NewGraphics2D()` **ISystemWindowProvider** Interface: - Abstracts window creation across platforms - Implementations: `SingleWindowProvider`, platform-specific providers ### Theming **ThemeConfig** (`Gui/Theme/ThemeConfig.cs`) - Color palette: `BackgroundColor`, `TextColor`, `PrimaryAccentColor` - Typography: `DefaultFontSize`, `FontSize7-14` - Button styling: `ButtonHeight`, `ButtonRadius`, `ButtonBackgroundColor` - State colors: `ThreeStateColor` (Focused, Hovered, Inactive) **ThemeConfig Methods:** - `MakeRoundedButton()` - Apply rounded style - `ApplyBottomBorder()` - Add border decoration - `CreateHeading()`, `CreateDialogButton()` - Themed widget factories ### Animation & Threading **Animation** (`Gui/Animation.cs`) - `DrawTarget`, `FramesPerSecond`, `SecondsPerUpdate` - `Start()`, `Stop()` - Animation lifecycle - `Animation.Run()` - Static helper for timed animations **UiThread** (`Gui/UiThread.cs`) - `RunOnUiThread()`, `RunOnIdle()` - Deferred execution - `SetInterval()`, `ClearInterval()` - Repeated actions - `ExecuteWhen()` - Condition-based execution ### Key Widgets | Widget | Location | Purpose | |--------|----------|---------| | `Button` | Gui/Button/ | Clickable button | | `CheckBox` | Gui/CheckBox/ | Toggle checkbox | | `TextEditWidget` | Gui/TextWidgets/ | Text input | | `TextWidget` | Gui/TextWidgets/ | Static text display | | `Slider` | Gui/Slider/ | Value slider | | `Menu`, `MenuItem` | Gui/Menu/ | Dropdown menus | | `ScrollableWidget` | Gui/ScrollableWidget/ | Scrolling container | | `DropDownList` | Gui/Menu/ | Selection dropdown | ## API Reference ### Core Classes | Class | Location | Description | |-------|----------|-------------| | `GuiWidget` | Gui/GUIWidget.cs | Base widget class | | `SystemWindow` | Gui/SystemWindow/SystemWindow.cs | Top-level window | | `FlowLayoutWidget` | Gui/FlowLayoutWidget.cs | Flow layout container | | `ThemeConfig` | Gui/Theme/ThemeConfig.cs | Theme configuration | | `Animation` | Gui/Animation.cs | Animation timing | | `UiThread` | Gui/UiThread.cs | UI thread utilities | ### Key Events | Event | Source | Description | |-------|--------|-------------| | `Click` | GuiWidget | Mouse click completed | | `MouseDown/Up` | GuiWidget | Button press/release | | `KeyDown/Up` | GuiWidget | Key press/release | | `FocusChanged` | GuiWidget | Focus state changed | | `BoundsChanged` | GuiWidget | Size/position changed | | `TextChanged` | GuiWidget | Text property changed | --- # 3. PolygonMesh ## Quick Summary The `PolygonMesh` module provides 3D mesh data structures, CSG (boolean) operations, spatial acceleration structures, file format support, and ray tracing capabilities. ## Technical In-Depth Review ### Mesh Data Structure **Mesh** (`PolygonMesh/Mesh.cs`) - `Vertices`: List - Vertex positions - `Faces`: FaceList - Triangles (3 vertex indices each) - `FaceTextures`: Dictionary - Per-face textures - `FaceBspTree`: BspNode - Spatial acceleration - `PropertyBag`: Dictionary - Extensible metadata **Key Operations:** - `Transform(Matrix4X4)` - Apply transformation - `MergeVertices()` - Weld coincident vertices - `ReverseFaces()` - Flip normals - `Split(Plane)` - Split mesh on plane - `GetAxisAlignedBoundingBox()` - Bounds calculation - `CalculateNormals()` - Recompute face normals ### CSG Operations **CsgOperations** (`PolygonMesh/Csg/CsgOperations.cs`) - `Union(meshA, meshB)` - Boolean union - `Subtract(meshA, meshB)` - Boolean difference - `Intersect()` - Boolean intersection **CsgBySlicing** (`PolygonMesh/Csg/CsgBySlicing.cs`) - Polygon-based CSG implementation - Uses Clipper library for 2D polygon operations - BVH acceleration for spatial queries - `SimilarPlaneFinder` for coplanar face grouping **Processing Modes:** - `Polygons` - Standard polygon-based CSG - `Marching_Cubes` - Experimental implicit surface - `Dual_Contouring` - Feature-preserving implicit ### Spatial Acceleration **FaceBspTree** (`PolygonMesh/Processors/FaceBspTree.cs`) - Binary Space Partition for faces - `Create()` - Build from mesh - `GetFacesInVisibilityOrder()` - Depth-sorted rendering - Used for transparent object rendering **BoundingVolumeHierarchy** (`PolygonMesh/RayTracer/Bvh/`) - `BvhBuilderAac` - Axis-aligned clustering - `BvhBuilderBottomUp` - Bottom-up construction - `BvhBuilderLocallyOrderedClustering` - Morton code ordering - O(log n) ray intersection queries ### File Format Support | Format | Class | Features | |--------|-------|----------| | STL | `StlProcessing` | Binary/ASCII, streaming | | OBJ | `ObjSupport`, `Obj` | Materials, textures | | AMF | `AmfDocument` | Multi-material, compressed | | 3MF | `IxMilia.ThreeMf` | Full 3MF spec support | ### Ray Tracing **RayTracer** (`PolygonMesh/RayTracer/RayTracer.cs`) - Anti-aliasing: None, Low(4), Medium(8), High(16), VeryHigh(32) - Buffers: Color, Depth, Normal - Features: Diffuse, Highlights, Reflection, Refraction, Shadows **Primitives** (`PolygonMesh/RayTracer/Primitive/Shapes/`) - `TriangleShape`, `BoxShape`, `SphereShape`, `CylinderShape`, `PlaneShape` - Materials: Solid, Chessboard, Texture ## API Reference ### Core Classes | Class | Location | Description | |-------|----------|-------------| | `Mesh` | PolygonMesh/Mesh.cs | Mesh data structure | | `Face` | PolygonMesh/Face.cs | Triangle face | | `CsgOperations` | PolygonMesh/Csg/CsgOperations.cs | Boolean ops | | `FaceBspTree` | PolygonMesh/Processors/FaceBspTree.cs | BSP tree | | `StlProcessing` | PolygonMesh/Processors/StlProcessing.cs | STL I/O | ### Mesh Extensions | Method | Purpose | |--------|---------| | `Copy()` | Deep copy mesh | | `GetCoplanarFaces()` | Find faces on same plane | | `GetMeshEdges()` | Extract edge topology | | `GetNonManifoldEdges()` | Detect topology errors | | `IsManifold()` | Validate mesh topology | | `RepairTJunctions()` | Fix T-junction artifacts | --- # 4. VectorMath ## Quick Summary The `VectorMath` module provides double-precision vector types, matrices, geometric primitives (rays, planes, AABBs), quaternions, and mathematical utilities for 3D graphics. ## Technical In-Depth Review ### Vector Types **Vector2** (`VectorMath/Vector2.cs`) - Components: X, Y (double) - Constants: Zero, One, UnitX, UnitY - Operations: Dot, Cross (2D scalar), Lerp, Rotate - Extensions: Polygon utilities, path analysis **Vector3** (`VectorMath/Vector3.cs`) - Components: X, Y, Z (double) - Operations: Dot, Cross, Normalize, Lerp - Transforms: Position, Normal, Vector transforms with Matrix4X4 - Float variant: `Vector3Float` for GPU compatibility **Vector4** (`VectorMath/Vector4.cs`) - Components: X, Y, Z, W (double) - Homogeneous coordinates support - Matrix transformation with perspective division - Swizzle: `.Xy`, `.Xyz` properties ### Matrix Types **Matrix4X4** (`VectorMath/Matrix4x4.cs`) - 4x4 double-precision matrix (row-major) - Position in Row3 (graphics convention) - Factory methods: - `CreateTranslation()`, `CreateRotation()`, `CreateScale()` - `CreatePerspectiveFieldOfView()`, `CreateOrthographic()` - `LookAt()` - Camera view matrix - Operations: Mult, Invert, Transpose, GetRotation **Quaternion** (`VectorMath/Quaternion.cs`) - Unit quaternion rotation representation - Construction: Component, from matrix, from two directions - Properties: X, Y, Z, W, Xyz ### Geometric Primitives **Ray** (`VectorMath/Ray.cs`) - Origin + Direction (normalized) - Precomputed: `oneOverDirection`, `sign` array - Range: `minDistanceToConsider`, `maxDistanceToConsider` - Fast AABB intersection (slab method) **Plane** (`VectorMath/Plane.cs`) - Normal + DistanceFromOrigin - Construction: From normal+distance, normal+point, three points - Methods: `GetDistanceFromPlane()`, `LineHitPlane()`, `RayHitPlane()` **AxisAlignedBoundingBox** (`VectorMath/AxisAlignedBoundingBox.cs`) - MinXYZ, MaxXYZ corners - Methods: `ExpandToInclude()`, `Intersects()`, `Contains()` - Properties: Center, Size, Volume, SurfaceArea **Frustum** (`VectorMath/Frustum.cs`) - 6 planes: Left, Right, Top, Bottom, Near, Far - View frustum culling support ### Math Utilities **MathHelper** (`VectorMath/MathHelper.cs`) - Constants: Pi, Tau, E, various Pi fractions - Trigonometric helpers **Easing** (`VectorMath/Easing.cs`) - Animation curves from Tween.js - Types: Linear, Quadratic, Cubic, Elastic, Bounce, etc. - Modes: EaseIn, EaseOut, EaseInOut ## API Reference ### Core Classes | Class | Location | Description | |-------|----------|-------------| | `Vector2` | VectorMath/Vector2.cs | 2D vector | | `Vector3` | VectorMath/Vector3.cs | 3D vector | | `Vector4` | VectorMath/Vector4.cs | 4D/homogeneous | | `Matrix4X4` | VectorMath/Matrix4x4.cs | 4x4 transform | | `Quaternion` | VectorMath/Quaternion.cs | Rotation quaternion | | `Ray` | VectorMath/Ray.cs | Ray primitive | | `Plane` | VectorMath/Plane.cs | Plane primitive | | `AxisAlignedBoundingBox` | VectorMath/AxisAlignedBoundingBox.cs | AABB | ### Coordinate Conventions - Right-handed coordinate system - Row-major matrix layout - Position in Row3 of Matrix4X4 - Unit quaternions for rotation --- # 5. RenderOpenGL ## Quick Summary The `RenderOpenGL` module integrates OpenGL rendering with agg-sharp, providing hardware-accelerated mesh rendering, shader management, and texture handling. ## Technical In-Depth Review ### Core Graphics **Graphics2DOpenGL** (`RenderOpenGl/Renderer/Graphics2DOpenGL.cs`) - Extends `Graphics2D` for OpenGL context - Orthographic projection management - Anti-aliased 2D rendering via texture-based alpha - Scissor test for clipping ### Mesh Rendering Plugins Plugins cache rendering data in mesh `PropertyBag`: **GLMeshTrianglePlugin** (`RenderOpenGl/GLMeshTrianglePlugin.cs`) - Groups faces by texture into `SubTriangleMesh` objects - Data: positions, normals, UVs, per-vertex colors - Invalidation tracking via `mesh.ChangedCount` **GLMeshVertexArrayObjectPlugin** (`RenderOpenGl/GLMeshVertexArrayObjectPlugin.cs`) - Modern VAO-based rendering - VBO for positions, EBO for indices - Uses `GL.DrawElements()` **GLMeshWirePlugin** (`RenderOpenGl/GLMeshWirePlugin.cs`) - Wireframe edge rendering - Optional angle-based edge filtering - Background processing for complex meshes **GLMeshNonManifoldPlugin** (`RenderOpenGl/GLMeshNonManifoldPlugin.cs`) - Highlights non-manifold edges - Background edge analysis ### Texture Management **ImageGlPlugin** (`RenderOpenGl/ImageGlPlugin.cs`) - Weak-reference caching by image buffer - Power-of-2 texture handling - Mipmap generation support - Format: RGBA (converted from BGRA) ### Rendering Pipeline **GLHelper** (`RenderOpenGl/RenderMeshToGl.cs`) - High-level mesh rendering orchestration - RenderTypes: Shaded, Wireframe, Outlines, NonManifold, Overhang **SetGlContext():** - Viewport, face culling, depth function - Lighting setup (2 directional lights) - Projection/modelview matrices **Render Types:** | Type | Description | |------|-------------| | Shaded | Textured/lit solid mesh | | Wireframe | Edges only | | Outlines | Solid + wireframe overlay | | NonManifold | Highlight topology errors | | Overhang | Overhang analysis coloring | ### Lighting **LightingData** (`RenderOpenGl/LightingData.cs`) - Two directional lights - Ambient, Diffuse, Specular components - Per-vertex color material support ### 3D Line Rendering **WorldViewExtensions** (`RenderOpenGl/WorldViewExtensions.cs`) - `Render3DLine()` - Screen-space width lines - `RenderCylinderOutline()`, `RenderRing()`, `RenderAabb()` - Frustum clipping before rendering ## API Reference ### Core Classes | Class | Location | Description | |-------|----------|-------------| | `Graphics2DOpenGL` | RenderOpenGl/Renderer/Graphics2DOpenGL.cs | 2D GL rendering | | `GLMeshTrianglePlugin` | RenderOpenGl/GLMeshTrianglePlugin.cs | Triangle cache | | `ImageGlPlugin` | RenderOpenGl/ImageGlPlugin.cs | Texture management | | `GLHelper` | RenderOpenGl/RenderMeshToGl.cs | Render pipeline | | `LightingData` | RenderOpenGl/LightingData.cs | Light config | ### GL Abstraction | Interface/Class | Purpose | |-----------------|---------| | `IOpenGL` | OpenGL operation abstraction | | `GL` | Thread-safe GL facade | | `GL/Enums/` | OpenGL constant definitions | --- # 6. DataConverters ## Quick Summary The `DataConverters2D` and `DataConverters3D` modules handle format conversion between 2D/3D data types, scene graph management, and file format import/export. ## Technical In-Depth Review ### DataConverters2D **Tessellation** (`DataConverters2D/`) - `CachedTesselator` - Caches vertices/indices during tessellation - `VertexSourceToTesselator` - Converts IVertexSource to tessellator input - Processes vertex commands: MoveTo, LineTo, Close **Polygon Operations** (`DataConverters2D/VertexSourceToClipperPolygons.cs`) - `CreatePolygons()` - IVertexSource to Clipper polygons - `Offset()` - Polygon expansion/contraction - `GetCorrectedWinding()` - Fix winding direction **Image I/O** (`DataConverters2D/ImageIO.cs`) - Load/Save: PNG, JPG, GIF (with animation) - Uses SixLabors.ImageSharp - `ConvertImageToImageBuffer()` - Format conversion ### DataConverters3D **Object3D Hierarchy** (`DataConverters3D/Object3D/`) **IObject3D Interface:** - `Children` - Hierarchical scene graph - `Mesh` - Associated geometry - `Matrix` - Local transformation - `Color`, `MaterialIndex`, `OutputType` - Methods: `Clone()`, `GetAxisAlignedBoundingBox()`, `ToJson()` **Object3D Class:** - Concrete IObject3D implementation - GUID-based identification - Thread-safe rebuild locking - JSON serialization support **InteractiveScene:** - Selection management - `SelectedItem`, `SelectedItemRoot` - Scene-level operations **File Format Support:** | Format | Class | Features | |--------|-------|----------| | AMF | `AmfDocument` | ZIP compression, streaming | | OBJ/MTL | `ObjSupport` | Materials, vertices, faces | | 3MF | `IxMilia.ThreeMf` | Full 3MF specification | **Conversion Utilities:** - `MeshToBVH` - Convert Object3D to ray-traceable BVH - `CenterAndHeightMaintainer` - Position preservation during operations - `CsgToRayTraceable` - CSG to ray tracer primitives ## API Reference ### Core Classes | Class | Location | Description | |-------|----------|-------------| | `CachedTesselator` | DataConverters2D/ | Tessellation cache | | `VertexSourceToClipperPolygons` | DataConverters2D/ | Polygon conversion | | `ImageIO` | DataConverters2D/ | Image I/O | | `IObject3D` | DataConverters3D/Object3D/ | Scene interface | | `Object3D` | DataConverters3D/Object3D/ | Scene implementation | | `InteractiveScene` | DataConverters3D/Object3D/ | Selection management | | `AmfDocument` | DataConverters3D/ | AMF loader | | `ObjSupport` | DataConverters3D/ | OBJ loader | --- # 7. Typography ## Quick Summary The `Typography` module provides comprehensive font loading, glyph management, and text shaping using OpenType features. ## Technical In-Depth Review ### Font Loading **Typeface** (`Typography.OpenFont/Typeface.cs`) - Core font representation - Properties: Name, UnitsPerEm, Ascender, Descender, LineGap - Manages glyph array and all font tables **OpenFontReader** (`Typography.OpenFont/OpenFontReader.cs`) - Reads: TTF, OTF, WOFF, WOFF2, TTC - `ReadPreview()` - Lightweight metadata - `Read()` - Full font parsing ### Font Tables **Core Tables:** - `Head` - Font header, metrics - `HorizontalMetrics` - Advance widths - `Cmap` - Character to glyph mapping - `OS2` - Font classification **TrueType:** - `Glyf` - TrueType outlines - `GlyphLocations` - Glyph offsets **CFF (PostScript):** - `CFFTable` - Compact Font Format - `Type2CharStringParser` - Charstring evaluation **OpenType Layout:** - `GSUB` - Glyph Substitution (ligatures, alternates) - `GPOS` - Glyph Positioning (kerning, marks) - `GDEF` - Glyph Definition ### Text Shaping **GlyphLayout** (`Typography.GlyphLayout/GlyphLayout.cs`) - Text shaping engine - Process: chars → codepoints → glyphs → GSUB → GPOS - Output: `UnscaledGlyphPlan` list **GlyphSubstitution** (`Typography.GlyphLayout/GlyphSubstitution.cs`) - GSUB feature application - Ligatures, composition, alternates **GlyphSetPosition** (`Typography.GlyphLayout/GlyphPosition.cs`) - GPOS feature application - Kerning, mark positioning ### Glyph Representation **Glyph** (`Typography.OpenFont/Glyph.cs`) - Index, Bounds, GlyphPoints, AdvanceWidth - TTF: Point arrays - CFF: Cff1GlyphData ## API Reference ### Core Classes | Class | Location | Description | |-------|----------|-------------| | `Typeface` | Typography.OpenFont/ | Font representation | | `OpenFontReader` | Typography.OpenFont/ | Font file parser | | `GlyphLayout` | Typography.GlyphLayout/ | Text shaping | | `Glyph` | Typography.OpenFont/ | Single glyph | ### Font Tables | Table | Purpose | |-------|---------| | `Head` | Font header | | `Cmap` | Character mapping | | `GSUB` | Glyph substitution | | `GPOS` | Glyph positioning | | `Glyf` | TrueType outlines | --- # 8. CSG Module ## Quick Summary The standalone `Csg` module provides declarative Constructive Solid Geometry with primitives, transformations, and boolean operations that can be converted to polygon meshes. ## Technical In-Depth Review ### Primitive Classes **Box** (`Csg/Solids/Box.cs`) - Rectangular prisms - Methods: `BevelEdge()`, `ChamferEdge()`, `BevelAll()` **Sphere** (`Csg/Solids/Sphere.cs`) - Defined by radius **Cylinder** (`Csg/Solids/Cylinder.cs`) - Dual-radius cones - Configurable polygon sides **LinearExtrude** (`Csg/Solids/LinearExtrude.cs`) - 2D polygon → 3D solid - Optional twist **RotateExtrude** (`Csg/Solids/RotateExtrude.cs`) - Revolution of 2D profile ### Transformations | Class | Operation | |-------|-----------| | `Translate` | Vector3 translation | | `Rotate` | Euler angle rotation | | `Scale` | Per-axis scaling | | `Align` | Align face to position | | `SetCenter` | Recenter object | ### Boolean Operations | Class | Operator | Operation | |-------|----------|-----------| | `Union` | `+` | Combine objects | | `Difference` | `-` | Subtract objects | | `Intersection` | - | Common volume | ### Conversion **CsgToMesh** (`Csg/Processors/CsgToMesh.cs`) - Visitor pattern converter - `Convert(CsgObject) → Mesh` **OpenSCadOutput** (`Csg/Processors/OpenSCadOutput.cs`) - Generate OpenSCAD scripts - `GetScadString(CsgObject) → string` ## API Reference ### Core Classes | Class | Location | Description | |-------|----------|-------------| | `CsgObject` | Csg/CsgObject.cs | Base class | | `Box` | Csg/Solids/Box.cs | Box primitive | | `Cylinder` | Csg/Solids/Cylinder.cs | Cylinder primitive | | `Union` | Csg/Operations/Union.cs | Boolean union | | `Difference` | Csg/Operations/Difference.cs | Boolean difference | | `CsgToMesh` | Csg/Processors/CsgToMesh.cs | Mesh conversion | --- # 9. Supporting Libraries ## Quick Summary Several supporting libraries provide specialized functionality for polygon operations, triangulation, and computational geometry. ## Module Overview ### clipper_library **Purpose:** Robust 2D polygon clipping using the Vatti algorithm. **Key Classes:** - `Clipper` - Main clipping engine - `ClipperOffset` - Polygon offsetting - `PolyTree` - Hierarchical result structure **Operations:** Union, Intersection, Difference, XOR ### Tesselate **Purpose:** GLU-style polygon tessellation. **Key Classes:** - `Tesselator` - Main tessellation engine - Callback interface for triangle output **Features:** Handles complex polygons with holes ### Triangle **Purpose:** Constrained Delaunay triangulation via Triangle.NET. **Key Classes:** - `Mesh` - Triangulation result - `ConstraintMesher` - Constrained triangulation - `QualityMesher` - Mesh refinement ### geometry3Sharp **Purpose:** Comprehensive 3D geometry library (ported from WildMagic5). **Modules:** - `math/` - Vectors, boxes, transforms - `mesh/` - DMesh3, mesh operators - `curve/` - Bezier, NURBS, polygons - `distance/` - Point-to-geometry queries - `comp_geom/` - Convex hull, arrangements ### ImageProcessing **Purpose:** Image manipulation filters. **Key Classes:** - `Blur`, `Dilate`, `Erode`, `Threshold` - `InvertLightness`, `Subtract` ### Localizations **Purpose:** Multi-language translation support. **Key Classes:** - `TranslationMap` - Translation dictionary - Extension: `"text".Localize()` ### QuadTree **Purpose:** 2D spatial indexing. **Key Classes:** - `QuadTree` - Generic quad tree - `Branch`, `Leaf` - Tree nodes - Object pooling for efficiency ## Dependencies ``` PolygonMesh ──┬── VectorMath ├── clipper_library ├── geometry3Sharp └── Triangle DataConverters3D ──┬── PolygonMesh ├── DataConverters2D └── Csg RenderOpenGl ──┬── Agg └── PolygonMesh Gui ──┬── Agg ├── DataConverters2D └── Localizations Agg ──┬── VectorMath └── Typography ``` --- ## Key Namespaces | Namespace | Purpose | |-----------|---------| | `MatterHackers.Agg` | Core 2D graphics | | `MatterHackers.Agg.UI` | Widget system | | `MatterHackers.PolygonMesh` | 3D mesh operations | | `MatterHackers.VectorMath` | Linear algebra | | `MatterHackers.RenderOpenGl` | OpenGL integration | | `MatterHackers.DataConverters2D` | 2D conversion | | `MatterHackers.DataConverters3D` | 3D scene graph | | `Typography.OpenFont` | Font loading | | `Typography.GlyphLayout` | Text shaping | | `MatterHackers.Csg` | Solid geometry | | `ClipperLib` | Polygon clipping | | `TriangleNet` | Mesh triangulation | | `g3` | geometry3Sharp |