Loading...
Searching...
No Matches
mesh Namespace Reference

The Qt-facing MeshKit API (meshkit::core_qt, meshkit::model_qt, meshkit::io_qt): mesh value types and cell attributes, the mesh generator, quad regions, matching and cleanup, mesh statistics, and the INP and 2DM mesh codecs. More...

Namespaces

namespace  detail
 Internal helpers of the Qt facades; not part of the supported API.
 
namespace  native_adapter
 Conversions between the Qt value types of namespace mesh and the standard types of meshkit::plan, used by the Qt facades.
 
namespace  pslg
 Preparation of planar straight-line graphs (PSLG) for meshing: Ramer–Douglas–Peucker simplification, straightness trimming, densification and resampling of paths and rings, hole-ring preparation, and point-in-rings tests.
 
namespace  quadquality_detail
 Internal checks behind the Qt quadrilateral quality metrics; not part of the supported API.
 

Classes

struct  BankPairPatch
 Two open bank polylines with independently supplied directions. More...
 
struct  CellAreaStats
 Min / max / mean / median of cell areas, triangles and quads (project CRS units²). More...
 
struct  CellCoupling
 A 1D node coupled to a mesh cell (centroid coupling). More...
 
struct  CellGeom
 Per-cell derived geometry shared by every consumer. More...
 
struct  CellParamSpec
 Describes one editable per-cell parameter: how to label it, how to configure a numeric editor for it, and whether it is live yet. More...
 
struct  CflStats
 The 2D marcher's CFL characteristic length, per cell and summarised. More...
 
class  CoarseningQueue
 Indexed binary min-heap holding at most one entry per vertex for resolution-aware coarsening. More...
 
struct  ConstraintAuditExample
 Qt form of meshkit::plan::ConstraintAuditExample: one recorded audit violation. More...
 
struct  ConstraintAuditOptions
 Qt form of meshkit::plan::ConstraintAuditOptions: pins, cancellation and resource limits for the constraint audits, copied field by field into the native options. More...
 
struct  ConstraintAuditReport
 Qt form of meshkit::plan::ConstraintAuditReport: result of auditConstraintSimplification() or auditMeshConstraints(). More...
 
struct  ConstraintPolicyOverride
 Partial ConstraintSimplificationPolicy layered over a parent policy, for per-source overrides. More...
 
struct  ConstraintPreview
 Bounded display summary of a simplification candidate, built by makeConstraintPreview(). More...
 
struct  ConstraintPreviewFeature
 Display data for one feature of a constraint-simplification preview. More...
 
struct  ConstraintSegment
 A polyline that must appear as constrained edges in the mesh. More...
 
struct  ConstraintSimplificationOptions
 Collection-wide inputs and resource limits for simplifyConstraints(). More...
 
struct  ConstraintSimplificationPolicy
 Per-feature limits for constraint simplification. More...
 
struct  ConstraintSimplificationResult
 Output of simplifyConstraints(); features and changes are parallel to the input. More...
 
struct  CouplingMap
 1D↔2D coupling map produced by the meshing dialog. More...
 
struct  FacingPair
 One facing run found by findFacingPairs(). More...
 
struct  FacingPairOptions
 Detection policy for findFacingPairs(). More...
 
struct  GenerationOptions
 Quality knobs surfaced to the user dialog. More...
 
struct  GenerationProgress
 Counter snapshot passed to ConstrainedDelaunay::QualityOptions::onProgress during refineQuality(). More...
 
struct  GenerationStats
 What the last generate() built (MeshGenerator::stats()). More...
 
struct  GradingStats
 Size-grading and shape gates (workplans/MESH_OVERHAUL_PLAN_2026-09-29.md §6). More...
 
struct  InfilDefaultRow
 One [2D_INFILTRATION_DEFAULTS] row. More...
 
struct  InfilLookupEntry
 One row of a classified lookup: a key (or key pair, for the Curve-Number landuse×HSG case) mapping to a full InfilRow. More...
 
struct  InfilLookupTable
 An editable, reusable classified lookup table. More...
 
struct  InfilOptions
 [2D_INFILTRATION_OPTIONS]. More...
 
struct  InfilRow
 One infiltration specification: method + positional parameters + destination. More...
 
class  InpMeshReader
 Stateless reader for the [2D_*] mesh sections of a SWMM .inp (inline or via [2D_MESH_FILE]), the counterpart of InpMeshWriter. More...
 
struct  InpMeshReadResult
 Outcome of InpMeshReader::read. More...
 
class  InpMeshWriter
 Stateless writer that renders a MeshResult plus CouplingMap as SWMM [2D_*] section text and writes or patches it into a .inp and, in External mode, a sidecar .2dm. More...
 
class  MeshBCTypes
 Namespace-like QObject that registers the boundary-condition Type with Qt's meta-object system (Q_ENUM) and hosts static label/token/engine conversions. More...
 
struct  MeshEdge
 A boundary edge with its source-segment marker preserved. More...
 
struct  MeshEdgeBC
 Boundary condition, conveyance factor and wall drag of one cell-edge slot. More...
 
class  MeshGenerator
 Generate a 2D triangular mesh. More...
 
struct  MeshResult
 Result of MeshGenerator::generate. More...
 
struct  MeshTriangle
 A cell in the mesh — a triangle or (since the engine's mixed tri-quad meshes, workplans/TRI_QUAD_MESHING_PLAN_2026-09-06.md) a convex quadrilateral — indices into MeshResult::vertices. More...
 
struct  MeshVertex
 A vertex in the generated mesh. More...
 
class  NaturalNeighbourInterpolator
 Natural-neighbour (Sibson or Laplace) interpolator over scattered (x, y, z) seeds. More...
 
struct  PatchAssessment
 Result of assessPlannedPatch(). More...
 
struct  PatchDecision
 Per-region planning record explaining the disposition chosen by planQuadRegions(). More...
 
struct  PatchInterfaceConflict
 One interface face whose nominal-size ratio exceeds the limit. More...
 
struct  PatchInterfaceReport
 Result of auditPatchInterfaces(). More...
 
struct  PatchLimits
 Acceptance limits for one mapped patch, checked cell by cell by assessPlannedPatch(). More...
 
struct  PatchLine
 A polyline through a patch's vertices that must be reported as mesh edges with a marker — a conduit running along a strip's middle row. More...
 
struct  PatchMesh
 A generated patch in local indices. More...
 
struct  QuadBlockGrid
 Local cell size on a regular grid; NaN marks unusable cells. More...
 
struct  QuadBlockOptions
 Policy for placeQuadBlocks(). More...
 
struct  QuadCleanupOptions
 Policy for cleanupAndSmoothQuads(). More...
 
struct  QuadCleanupStats
 Counts reported by cleanupAndSmoothQuads(). More...
 
struct  QuadPairingOptions
 Policy for pairTrianglesIntoQuads(). More...
 
struct  QuadPairingStats
 Counts reported by pairTrianglesIntoQuads(). More...
 
struct  QuadPlan
 Result of planQuadRegions(). More...
 
struct  QuadPlanningGeometry
 Source geometry that protects against planned patches, in the regions' XY frame. More...
 
struct  QuadPlanningOptions
 Settings and budgets for planQuadRegions(). More...
 
struct  QuadQuality
 Shape metrics of one quadrilateral, as computed by quadQuality(). More...
 
struct  QuadQualityBounds
 Acceptance bounds shared by pairing, cleanup, smoothing and the legacy tri-pair merge. More...
 
struct  QuadRegion
 A polygon in which quadrilateral cells are requested, with its spacing, shape and tagging policy. More...
 
struct  QuadRegionReport
 Per-region outcome of generate() (MeshGenerator::quadRegionReports()). More...
 
struct  QuadStats
 Quadrilateral-cell statistics (workplans/TRI_QUAD_MESHING_PLAN §5): count, interior-angle range and bed non-planarity. More...
 
struct  QuadTemplate
 Four vertex ids in cyclic (CCW) order, indexed into the generated mesh passed to pairTrianglesIntoQuads(). More...
 
struct  RefineHook
 Cancellation, progress and graded sizing callbacks. More...
 
struct  RegionMarker
 A region attribute — an interior seed point whose value propagates through the constrained Delaunay region flood fill. More...
 
struct  ResolutionSettings
 Unit-independent mesh resolution choices (lengths in SI metres) with JSON round-trip, legacy migration and validation. More...
 
struct  ResolvedInfil
 Result of resolving one triangle's infiltration. More...
 
struct  SimplificationChange
 Outcome for one input feature; ConstraintSimplificationResult::changes is parallel to the input. More...
 
struct  SimplificationFeature
 One source constraint, an open polyline or a ring, given to simplifyConstraints(). More...
 
class  SizeField
 Distance-to-feature field sampled as a max-area function. More...
 
struct  SizeFieldOptions
 Policy for SizeField::build(). More...
 
struct  SizingAuditExample
 One recorded violation, for diagnostics. More...
 
struct  SizingAuditOptions
 Limits, budgets and callbacks for auditMeshSizing(). More...
 
struct  SizingAuditReport
 Result of auditMeshSizing(). More...
 
class  Sms2dmReader
 Stateless reader that turns an SMS 2DM mesh (file or text) into a MeshResult. More...
 
struct  SteinerPoint
 A point that must appear as a vertex in the output mesh. More...
 
struct  StructuredPatch
 Four-sided patch: corners in cyclic order (either orientation); n subdivisions along corner0→corner1 (and corner3→corner2), m along corner0→corner3 (and corner1→corner2). More...
 
struct  SweptPatch
 Swept patch: the centreline is offset ±width/2 (mitred at interior vertices) and cut into across quads per station. More...
 
struct  TerrainTolerancePolicy
 Maps a reference terrain tolerance and a footprint target size to the tolerance used there. More...
 

Typedefs

using ConstrainedDelaunay = meshkit::BasicConstrainedDelaunay<meshkit::detail::QtStorage>
 The constrained Delaunay kernel on Qt storage (QVector, QPointF, QString); the same implementation as meshkit::ConstrainedDelaunay, which uses standard containers.
 
using EdgeVertexPair = QPair<int, int>
 Undirected mesh edge, as (min, max) vertex indices.
 
using MeshCell = MeshTriangle
 Alias: a "triangle" row is any cell (triangle or quad).
 

Enumerations

enum class  PatchDisposition {
  Triangles ,
  Accepted ,
  Repaired ,
  RequiredFailure
}
 Final outcome of one quad region in unified cell planning. More...
 
enum class  MeshOutputMode {
  External ,
  Inline
}
 Output strategy for the four 2D mesh sections. More...
 
enum class  InfilMethod : int {
  None = -1 ,
  Horton = 0 ,
  ModHorton = 1 ,
  GreenAmpt = 2 ,
  ModGreenAmpt = 3 ,
  CurveNumber = 4 ,
  Constant = 5
}
 Infiltration method. More...
 
enum class  InfilDest : int {
  Lost = 0 ,
  SubcatchAquifer = 1 ,
  Aquifer2D = 2
}
 Destination of infiltrated water (engine Infil2DDest). More...
 
enum class  InfilProvenance : int {
  None = 0 ,
  Star = 1 ,
  Tag = 2 ,
  Override = 3
}
 Where a cell's resolved parameters came from — drives the muted/italic "inherited" rendering in the attribute table and property panels, and is what undo must restore (GUI plan §3.5(3)). More...
 
enum class  QuadRegionMode {
  Auto ,
  Mapped ,
  Submapped ,
  Free ,
  TrianglesOnly
}
 Requested (or classified) cell strategy of a QuadRegion. More...
 
enum  SizingCellFlag : quint8 {
  BelowTarget = 1 ,
  BelowEdgeFloor = 2 ,
  AboveMaximum = 4 ,
  AboveLocalMaximum = 8 ,
  TransitionExceeded = 16 ,
  TouchesConstraint = 32
}
 Per-cell bits in SizingAuditReport::cellFlags and SizingAuditExample::flags. More...
 
enum class  CoarseningOrder
 Order in which terrain coarsening tries to remove free vertices. More...
 
enum class  TerrainToleranceMode
 How TerrainTolerancePolicy::tolerance() derives a footprint's terrain tolerance. More...
 

Functions

QVector< FacingPair > findFacingPairs (const QVector< QVector< QPointF > > &lines, const QVector< QPair< QPointF, QPointF > > &obstacles, const FacingPairOptions &opt)
 Greedily identify near-parallel breakline runs facing across an unobstructed sampled strip.
 
PatchAssessment assessPlannedPatch (const PatchMesh &, const PatchLimits &)
 Check a generated mapped patch cell by cell against acceptance limits.
 
QuadPlan planQuadRegions (const QVector< QuadRegion > &, const QuadPlanningGeometry &, const QuadPlanningOptions &={})
 Plan mapped quad patches for all regions jointly, before CDT construction.
 
PatchInterfaceReport auditPatchInterfaces (const MeshResult &, const QVector< MeshEdge > &, double maximumRatio, const std::function< bool()> &cancelled={}, int maximumExamples=64)
 Measure nominal-size ratios across delivered patch interface edges.
 
ConstraintAuditReport auditConstraintSimplification (const QVector< SimplificationFeature > &original, const ConstraintSimplificationResult &candidate, const ConstraintAuditOptions &options={})
 Qt facade of meshkit::plan::auditConstraintSimplification(): converts the arguments to native copies, runs the native audit and converts the report back.
 
ConstraintAuditReport auditMeshConstraints (const QVector< SimplificationFeature > &constraints, const MeshResult &mesh, const ConstraintAuditOptions &options={})
 Qt facade of meshkit::plan::auditMeshConstraints(): features and options are converted to native copies, the mesh is read through borrowed views during the call.
 
ConstraintPreview makeConstraintPreview (const QVector< SimplificationFeature > &original, const ConstraintSimplificationResult &candidate, const std::function< bool()> &cancelled={}, int maximumVertices=50000, int maximumFeatures=500)
 Build bounded display data comparing source features with a simplification candidate.
 
ConstraintSimplificationResult simplifyConstraints (const QVector< SimplificationFeature > &features, const ConstraintSimplificationOptions &options={})
 Remove redundant vertices from a collection of constraint features without moving any coordinate.
 
bool unitsHeaderIsSI (const QString &unitsHeader)
 Recognize the retained metric-mesh header vocabulary without converting geometry.
 
constexpr int edgeSlot (int cell, int e) noexcept
 Compute the flat stride-four slot for one cell-local edge.
 
constexpr int slotCell (int slot) noexcept
 Decode the owning cell index from a stride-four flat edge slot.
 
constexpr int slotLocal (int slot) noexcept
 Decode local edge position from a stride-four flat slot.
 
constexpr int edgeSlotCount (int nCells) noexcept
 Calculate padded per-edge storage length for a cell count.
 
void edgeEndpoints (const MeshTriangle &t, int k, int &a, int &b) noexcept
 Resolve the ordered vertex IDs of one cell-local opposite-edge convention.
 
bool rt0CellDischarge (int cell, int nv, const float *flux, const float *length, const float *nx, const float *ny, double &qx, double &qy) noexcept
 Reconstruct planar specific discharge by least-squares fitting outward edge-normal discharge.
 
bool cellVelocity (int cell, int nv, const float *flux, const float *length, const float *nx, const float *ny, double depth, double dryDepth, double &vx, double &vy) noexcept
 Reconstruct cell velocity from edge discharge only when a usable wet depth is available.
 
CellGeom cellGeom (const QVector< MeshVertex > &vertices, const MeshTriangle &t)
 Compute triangle/quad subtriangles, positive fan area, area centroid and arithmetic mean elevation.
 
double cellSignedArea (const QVector< MeshVertex > &vertices, const MeshTriangle &t) noexcept
 Compute oriented polygon area in local coordinates to reduce projected-origin cancellation.
 
bool cellIsConvex (const QVector< MeshVertex > &vertices, const MeshTriangle &t) noexcept
 Check strict consistent quad turns, treating every triangle as convex without inspection.
 
bool cellContains (const QVector< MeshVertex > &vertices, const MeshTriangle &t, const QPointF &p, double eps=0.0) noexcept
 Test a point against the elevation-selected cell subtriangle fan using barycentric slack.
 
const QVector< CellParamSpec > & cellParamSpecs ()
 Return the immutable shared registry of mesh cell parameter/editor specifications.
 
const CellParamSpec * cellParamSpec (const QByteArray &key)
 Find a registry specification by its case-sensitive stable byte key.
 
QString cellParamLabel (const QByteArray &key, const QString &depthUnitLabel)
 Build a display label using the registry and an optional project depth-unit suffix.
 
double cellParamValue (const MeshResult &mesh, int tri, const QByteArray &key)
 Read a stored or inheritance-resolved cell parameter without substituting editor defaults.
 
QByteArray initialConditionCounterpart (const QByteArray &key)
 Name the alternative initial-condition key of key.
 
double triangleArea (const MeshResult &mesh, int tri)
 Measure positive fan area for a triangle or quadrilateral cell.
 
QPointF cellCentroid (const MeshResult &mesh, int cell)
 Compute the planar area centroid using the shared cell fan geometry.
 
QuadStats computeQuadStats (const MeshResult &mesh)
 Summarize quad angles, quality, bed twist and interior quad-only vertex valence.
 
CellAreaStats computeCellAreaStats (const MeshResult &mesh)
 Summarize unsigned fan areas of all index-valid triangle and quad rows.
 
QHash< EdgeVertexPair, QVector< int > > buildEdgeTriangles (const MeshResult &mesh)
 Build an owned undirected edge-to-incident-cell adjacency map.
 
QVector< double > computeCellLchar (const MeshResult &mesh)
 Estimate the engine-style CFL characteristic length from cell geometry and interior faces.
 
CflStats computeCflStats (const MeshResult &mesh, int ltsTiers=4)
 Summarize positive geometric CFL lengths and a uniform-depth local-timestep work proxy.
 
GradingStats computeGradingStats (const MeshResult &mesh)
 Summarize adjacent-cell size ratios, face orthogonality and minimum cell corner angles.
 
QPair< int, int > edgeKey (int a, int b) noexcept
 Normalize two endpoint identifiers into an undirected ordered key.
 
ResolvedInfil resolveInfil (const MeshResult &mesh, int tri)
 Resolve an owned infiltration specification while preserving its authoring provenance.
 
InfilRow starDefault (const MeshResult &mesh)
 Copy the first wildcard infiltration default, if present.
 
int indexOfDefault (const MeshResult &mesh, const QString &tag)
 Find the first exact case-sensitive default tag match.
 
bool infilUsesParam (InfilMethod method, int slot)
 Check whether a model uses a zero-based positional parameter slot.
 
int infilParamCount (InfilMethod method)
 Report serialized parameter-column width rather than number of active values.
 
QString infilParamLabel (InfilMethod method, int slot)
 Translate the model-specific label for an active positional parameter.
 
QByteArray infilParamKey (InfilMethod method, int slot)
 Map an active model slot to its case-sensitive shared registry key.
 
int infilSlotForKey (InfilMethod method, const QByteArray &key)
 Resolve a named parameter key to its position under one model.
 
const QVector< QByteArray > & infilParamKeys ()
 Return the immutable union of named infiltration parameter keys in registration order.
 
QString infilMethodToken (InfilMethod m)
 Encode an infiltration method using the stable uppercase file vocabulary.
 
InfilMethod infilMethodFromToken (const QString &token, bool *ok=nullptr)
 Parse a trimmed case-insensitive infiltration method token.
 
QString infilMethodLabel (InfilMethod m)
 Translate a display label for an infiltration method.
 
QStringList infilMethodLabels ()
 Build translated method labels in consecutive enum order from None through Constant.
 
QString infilDestToken (InfilDest d)
 Encode a destination enum as its retained uppercase file token.
 
InfilDest infilDestFromToken (const QString &token, bool *ok=nullptr)
 Parse a retained destination token independently of current engine support.
 
QString infilDestLabel (InfilDest d)
 Translate the display label of a retained destination value.
 
QStringList infilDestLabels ()
 Build translated destination labels in enum order Lost, SubcatchAquifer, Aquifer2D.
 
QString infilDestHint (InfilDest d)
 Translate destination guidance without resolving any open model.
 
bool saveLookupTableCsv (const InfilLookupTable &table, const QString &path, QString *err)
 Serialize classified infiltration entries and optional fallback to a QSaveFile CSV replacement.
 
bool loadLookupTableCsv (InfilLookupTable *table, const QString &path, QString *err)
 Load the permissive unquoted classified-lookup CSV format into a fresh table value.
 
QString validate (const StructuredPatch &p)
 Input checks.
 
QString validate (const SweptPatch &p)
 Check a swept patch's inputs and its representable station, cell and boundary counts.
 
QString validate (const PatchMesh &pm)
 Requires finite convex CCW quads, consistently shared cell edges, and one simple boundary matching exactly the outer cell edges.
 
QPolygonF orderedPatchBoundary (const PatchMesh &pm, QString *err=nullptr)
 Validate the complete patch and return its CCW boundary, without a repeated closing vertex.
 
PatchMesh makeTransfinitePatch (const StructuredPatch &p, QString *err=nullptr)
 Transfinite interpolation on the four straight sides.
 
PatchMesh makeSweptPatch (const SweptPatch &p, QString *err=nullptr)
 Sweep the centreline: (stations)×(across+1) vertices, (stations-1)×across quads.
 
PatchMesh makeBankPairPatch (const BankPairPatch &p, QString *err=nullptr)
 Build a conforming strip between two simple, disjoint banks.
 
PatchMesh makeTransfinitePatch (const QVector< QVector< QPointF > > &sides, int n, int m, const QString &tag, QString *err=nullptr)
 Transfinite (Coons) interpolation on four POLYLINE sides forming a loop: sides[0] runs c0→c1, sides[1] c1→c2, sides[2] c2→c3, sides[3] c3→c0 (each side's last point equals the next side's first).
 
PatchMesh makeTransfinitePatchAtStations (const QVector< QVector< QPointF > > &sides, const QString &tag, QString *err=nullptr)
 Coons patch whose boundary vertices are exactly the given side stations.
 
PatchMesh makeMappedPatch (const QPolygonF &ring, const QVector< int > &corners, double h, const QString &tag, QString *err=nullptr)
 Split a CCW ring at the four corners (ring vertex indices, ring order) into polyline sides, choose n = max(1, round(mean(len0, len2)/h)), m likewise from sides 1/3, and call the polyline overload.
 
PatchMesh makeMappedPatch (const QPolygonF &ring, const QVector< int > &corners, double hAlong, double hAcross, double alongAngleDeg, const QString &tag, QString *err=nullptr)
 Mapped patch with independent physical-axis spacing.
 
QuadCleanupStats cleanupAndSmoothQuads (MeshResult &mesh, const QSet< int > &movable, const QuadCleanupOptions &opts, QVector< int > *vertexOldToNew)
 Remove eligible quad doublets, improve valence diagonals, smooth movable xy and compact/reorder cells.
 
QVector< int > reorderTrianglesFirst (MeshResult &mesh)
 Stable-partition cell rows into triangles followed by quads and remap selected cell metadata.
 
QuadPairingStats pairTrianglesIntoQuads (MeshResult &mesh, const QVector< int > &cellIds, const QVector< QuadTemplate > &templates, const QSet< QPair< int, int > > &lockedEdges, const QuadPairingOptions &opts, QVector< int > *oldToNew)
 Pair selected valid triangle rows into acceptable CCW quads, then rebuild engine cell order.
 
QVector< int > maximumMatching (int n, const QVector< QPair< int, int > > &edges)
 Compute an unweighted maximum-cardinality matching in an undirected general graph.
 
bool unionQuad (const QVector< MeshVertex > &vertices, const MeshTriangle &t1, const MeshTriangle &t2, MeshTriangle &quad)
 Form and convexity-check a CCW quadrilateral candidate from two triangle records.
 
QuadQuality quadQuality (const QPointF &a, const QPointF &b, const QPointF &c, const QPointF &d)
 Measure one quadrilateral using cyclic corners and translation/scale-resistant planar arithmetic.
 
QuadQuality quadQuality (const QVector< MeshVertex > &vertices, const MeshTriangle &t)
 Measure a quad cell through its borrowed vertex records.
 
bool quadAcceptable (const QuadQuality &q, const QuadQualityBounds &b)
 Apply inclusive hard angle/Jacobian/aspect limits to a valid convex metric record.
 
double quadScore (const QuadQuality &q, const QuadQualityBounds &b)
 Rank valid convex quads by Jacobian, rectangularity and a soft aspect penalty.
 
double triangleScaledJacobian (const QPointF &a, const QPointF &b, const QPointF &c)
 Compute the minimum orientation-normalized corner sine of a triangle.
 
double cellCornerAngleDeg (const QVector< MeshVertex > &v, const MeshTriangle &t, int i)
 Compute the unsigned corner angle of a triangle or quad.
 
QuadQualityBounds quadRegionQualityBounds (const QuadRegion &region, QuadQualityBounds global)
 Copy global quality bounds and apply an explicitly nonnegative region aspect override.
 
QPolygonF normalizeRingCCW (const QPolygonF &ring)
 Copy a ring while dropping scale-fuzzy consecutive/closing duplicates and reversing negative area.
 
bool polylineIntersectsRect (const QVector< QPointF > &path, const QRectF &rect)
 Test whether any consecutive path segment meets a normalized closed rectangle.
 
double ringSignedArea (const QPolygonF &ring)
 Compute oriented shoelace area after translating corners to the first vertex.
 
bool pointInRing (const QPolygonF &ring, const QPointF &p)
 Test a point using a strict horizontal-ray odd-even crossing rule.
 
bool pointInRegion (const QPolygonF &ring, const QVector< QPolygonF > &holes, const QPointF &p)
 Combine outer-ring parity with exclusion by every supplied hole-ring parity.
 
bool ringIsSimple (const QPolygonF &ring)
 Reject proper nonadjacent edge crossings using plain double orientation signs.
 
QString validateQuadRegion (const QuadRegion &r, const QVector< QPolygonF > &domains, const QVector< QPolygonF > &holes)
 Check region authoring policy, normalized ring and sampled domain/hole containment.
 
QString validateQuadRegionsDisjoint (const QVector< QuadRegion > &regions)
 Check explicit region pairs for proper crossings or strictly interior sampled vertices.
 
QuadRegionMode classifyQuadRegion (const QPolygonF &ring, QVector< int > *corners, double cornerTolDeg=25.0, double rectilinearTolDeg=2.0)
 Heuristically classify normalized ring turns as Mapped, Submapped or Free.
 
QPolygonF resampleRing (const QPolygonF &ring, double h, double keepTurnDeg=0.0)
 Normalize a ring and insert equal-part subdivisions along all implicit closing edges.
 
double ringTurnDeg (const QPolygonF &ring, int i)
 Compute a signed exterior turn at one ring corner using adjacent edge cross/dot products.
 
void reorderMeshHilbert (MeshResult *m)
 Spatially permute cells within triangle/quad classes and renumber vertices by first use.
 
double meanVertexIndexSpread (const MeshResult &m)
 Compute mean absolute index jump across each cell's consecutive cyclic corner pairs.
 
QuadBlockGrid quadBlockGridFromMesh (const MeshResult &mesh, double pitch, const QVector< QVector< QPointF > > &blockers)
 Estimate local equilateral side lengths from triangles and mask existing quads/features.
 
QuadBlockGrid quadBlockGridFromField (const QRectF &r, double pitch, const std::function< double(const QRectF &)> &f, const QVector< QVector< QPointF > > &b, const std::function< bool()> &cancel, qint64 cap)
 Build a block grid from a size field over a rectangle, before any triangulation (Qt adapter over meshkit::plan::quadBlockGridFromField).
 
QVector< QuadRegion > placeQuadBlocks (const QuadBlockGrid &grid, const QuadBlockOptions &options)
 Greedily select axis-aligned mapped quad regions from approximately uniform usable grid bands.
 
SizingAuditReport auditMeshSizing (const MeshResult &, const SizingAuditOptions &={})
 Measure delivered cell sizes, edge floors and size transitions of a mixed mesh.
 
double resolutionRemovalImportance (double flatness, double actualSize, double targetSize)
 Rank a vertex for resolution-aware coarsening; lower values are tried first.
 

Variables

constexpr int kEdgeStride = 4
 Edge slots per cell in every flat per-edge array (== engine kMaxCellVerts).
 
constexpr int kInfilMaxParams = 5
 Widest positional parameter count (Horton: f0 fmin decay dry_time Fmax).
 

Detailed Description

The Qt-facing MeshKit API (meshkit::core_qt, meshkit::model_qt, meshkit::io_qt): mesh value types and cell attributes, the mesh generator, quad regions, matching and cleanup, mesh statistics, and the INP and 2DM mesh codecs.

Uses Qt value types (QVector, QPointF, QString); the planning, sizing and constraint facades delegate to the standard C++ implementations in meshkit and meshkit::plan.

Typedef Documentation

◆ ConstrainedDelaunay

The constrained Delaunay kernel on Qt storage (QVector, QPointF, QString); the same implementation as meshkit::ConstrainedDelaunay, which uses standard containers.

◆ EdgeVertexPair

using mesh::EdgeVertexPair = QPair<int, int>

Undirected mesh edge, as (min, max) vertex indices.

◆ MeshCell

Alias: a "triangle" row is any cell (triangle or quad).

Enumeration Type Documentation

◆ CoarseningOrder

enum class meshkit::CoarseningOrder
strong

Order in which terrain coarsening tries to remove free vertices.

◆ InfilDest

enum class mesh::InfilDest : int
strong

Destination of infiltrated water (engine Infil2DDest).

Enumerator
Lost 

Leaves the model.

SubcatchAquifer 

U3: recharges the containing subcatchment's aquifer.

Aquifer2D 

Legacy token, rejected by current engine validation; migrate ownership.

◆ InfilMethod

enum class mesh::InfilMethod : int
strong

Infiltration method.

Values mirror the engine's InfilModel plus an explicit None. Stored in files as the tokens returned by infilMethodToken().

Enumerator
None 

No infiltration method assigned.

Horton 

Horton.

ModHorton 

Modified Horton.

GreenAmpt 

Green-Ampt.

ModGreenAmpt 

Modified Green-Ampt.

CurveNumber 

SCS curve number.

Constant 

Constant infiltration rate.

◆ InfilProvenance

enum class mesh::InfilProvenance : int
strong

Where a cell's resolved parameters came from — drives the muted/italic "inherited" rendering in the attribute table and property panels, and is what undo must restore (GUI plan §3.5(3)).

Enumerator
None 

No model resolves for this cell.

Star 

From the '*' default row.

Tag 

From a tag default row.

Override 

From a per-cell override.

◆ MeshOutputMode

enum class mesh::MeshOutputMode
strong

Output strategy for the four 2D mesh sections.

External (default) keeps the main .inp clean and lets multiple SWMM models share a single mesh — the user-stated preference (2026-04-26). Inline is the fallback for callers who specifically want everything in one file.

Enumerator
External 

Write .2dm next to the .inp; reference via [2D_MESH_FILE].

Inline 

Inline the four sections directly in the .inp.

◆ PatchDisposition

enum class mesh::PatchDisposition
strong

Final outcome of one quad region in unified cell planning.

Enumerator
Triangles 

No patch is delivered; the region is meshed with triangles.

The default.

Accepted 

The mapped patch passed every check without repair.

Repaired 

The mapped patch passed after its station counts were refined.

RequiredFailure 

A required region could not be planned; the whole plan fails.

◆ QuadRegionMode

enum class mesh::QuadRegionMode
strong

Requested (or classified) cell strategy of a QuadRegion.

classifyQuadRegion() can return Mapped, Submapped or Free for a ring. MeshGenerator builds only mapped (transfinite) patches: every request other than TrianglesOnly is meshed with quads when the ring has four logical sides and with triangles otherwise; the outcome is reported as Mapped or TrianglesOnly in QuadRegionReport::resolved.

Enumerator
Auto 

classifyQuadRegion() decides: Mapped → Submapped → Free.

Mapped 

Four logical sides (polylines) → transfinite quads.

Needs 4 corners.

Submapped 

Exactly rectilinear ring. A classification only: MeshGenerator meshes it like Mapped.

Free 

Quad-dominant (cross-field lattice) candidate.

A classification only: MeshGenerator meshes it like Mapped.

TrianglesOnly 

Region ring is still a constraint loop, interior stays triangles.

◆ SizingCellFlag

enum mesh::SizingCellFlag : quint8

Per-cell bits in SizingAuditReport::cellFlags and SizingAuditExample::flags.

Enumerator
BelowTarget 

Nominal size below the advisory minimumTarget.

BelowEdgeFloor 

Shortest edge below the hard minimumEdge floor.

AboveMaximum 

Nominal size above the global maximumSize.

AboveLocalMaximum 

Nominal size above the cell's footprintMaximum bound.

TransitionExceeded 

Either cell of a shared face whose ratio exceeds adjacentRatio.

TouchesConstraint 

An edge is in MeshResult::boundaryEdges; not a violation.

◆ TerrainToleranceMode

enum class meshkit::TerrainToleranceMode
strong

How TerrainTolerancePolicy::tolerance() derives a footprint's terrain tolerance.

Function Documentation

◆ assessPlannedPatch()

PatchAssessment mesh::assessPlannedPatch ( const PatchMesh & p,
const PatchLimits & l )

Check a generated mapped patch cell by cell against acceptance limits.

The first argument is the patch, read only; it must have cells, and every cell must be a quad with in-range vertex indices, finite coordinates and a convex, positive-area shape. The second argument holds the limits, validated first: finite nonnegative values, minimumAngleDegrees below 180, a finite alongAngleDegrees, and alongSize and acrossSize either both positive or both zero. Checking stops at the first failing cell. Cancellation is polled every 1024 cells; callbacks run synchronously on the calling thread.

Returns
Owned assessment; reason names the first failure.

◆ auditConstraintSimplification()

ConstraintAuditReport mesh::auditConstraintSimplification ( const QVector< SimplificationFeature > & original,
const ConstraintSimplificationResult & candidate,
const ConstraintAuditOptions & options = {} )

Qt facade of meshkit::plan::auditConstraintSimplification(): converts the arguments to native copies, runs the native audit and converts the report back.

Per feature: valid policy; unchanged id, closed, role, marker, requiredInMesh and elevation presence; a strictly increasing source mapping; retained vertices and heights exactly equal to their sources; endpoints and ring closure kept; no Preserve-mode, fixed or above-maxTurnDegrees vertex removed; consistent removed count; ring orientation and area limits; XY/Z deviation and monotone projection of each removed vertex. Then source rings must not touch themselves and, when anything was removed, each new shortcut is checked against other output edges, pins and the original graph for crossings, collapsed distinct paths, lost junctions, swept pockets and minimumClearance.

Parameters
[in]originalFeatures given to simplifyConstraints(); read only, not retained.
[in]candidateIts result; must be ok with one feature and change per original.
[in]optionsPins, cancellation and limits; the callback runs synchronously.
Returns
Report; ok only when complete without violations. Some structural violations end the audit at once. Inputs are not modified; no IO.

◆ auditMeshConstraints()

ConstraintAuditReport mesh::auditMeshConstraints ( const QVector< SimplificationFeature > & constraints,
const MeshResult & mesh,
const ConstraintAuditOptions & options = {} )

Qt facade of meshkit::plan::auditMeshConstraints(): features and options are converted to native copies, the mesh is read through borrowed views during the call.

Each non-degenerate segment of a feature with requiredInMesh must be covered end to end, from its first to its last vertex, by a chain of delivered edges (mesh.boundaryEdges) lying on it within coordinateRoundoff, each with one or two incident cells and, for a nonzero feature marker, the same marker. Domain and Hole edges need their cells on the correct side; delivered endpoint z must match authored z to roundoff. Not a general cell-overlap proof.

Parameters
[in]constraintsSource features; Domain/Hole rings also define the inside used for side checks. Read only, not retained.
[in]meshDelivered mesh; must have ok set. Read only, not retained.
[in]optionsCancellation and limits; protectedPoints is not used.
Returns
Report; ok only when complete without violations. Invalid indices or geometry end the audit at once. Inputs are not modified; no IO.

◆ auditMeshSizing()

SizingAuditReport mesh::auditMeshSizing ( const MeshResult & mesh,
const SizingAuditOptions & options = {} )

Measure delivered cell sizes, edge floors and size transitions of a mixed mesh.

The first argument is the mesh, read only. It must be ok and nonempty. Every cell, triangle or quad, needs distinct in-range vertex indices with finite XY and a strictly convex counterclockwise shape; boundary edges need distinct in-range vertices; a face may be shared by at most two cells, which must traverse it in opposite directions. Only XY is used. The second argument holds the limits, budgets and callbacks; callbacks run synchronously on the calling thread.

Returns
Owned report. Invalid limits, mesh geometry or footprint bounds set error and leave valid false; cancellation or an exhausted budget also leave complete false.

◆ auditPatchInterfaces()

PatchInterfaceReport mesh::auditPatchInterfaces ( const MeshResult & m,
const QVector< MeshEdge > & edges,
double maximumRatio,
const std::function< bool()> & cancelled = {},
int maximumExamples = 64 )

Measure nominal-size ratios across delivered patch interface edges.

Nominal size is sqrt(4A / sqrt(3)) for a triangle and sqrt(A) for a quad, from the signed XY area, so every cell must be counterclockwise. An edge with two incident cells is a shared face; an edge with one is skipped. The parameters are unnamed in this declaration; the names below are the definition's.

Parameters
[in]mThe delivered mesh; read only.
[in]edgesPatch boundary edges as vertex index pairs into the mesh's vertices (direction and marker ignored); read only.
[in]maximumRatioLargest allowed ratio of the two nominal sizes; finite and >= 1.
[in]cancelledOptional poll, called synchronously about every 4096 cells.
[in]maximumExamplesViolations to report, clamped to [0, 1000]; those with the smallest cell indices are kept.
Returns
Owned report. ok is false with error set for an invalid ratio, edge or cell, a nonpositive cell area, a face with more than two cells, a boundary edge without any cell, or cancellation. Violations do not make ok false.

◆ buildEdgeTriangles()

QHash< EdgeVertexPair, QVector< int > > mesh::buildEdgeTriangles ( const MeshResult & mesh)
nodiscard

Build an owned undirected edge-to-incident-cell adjacency map.

Parameters
[in]meshBorrowed cell/vertex arrays, unchanged; every cell with any out-of-range ID is skipped.
Returns
Owned hash keyed by ordered endpoint IDs, values cell indices in input traversal order. Includes triangles and quads via the shared local-edge convention. Coincident/repeated endpoints and nonmanifold incidences are retained, not repaired; coordinates are not examined. Allocates map/vectors and retains no mesh references, safe concurrent stable-input reads.

Map every undirected edge to the triangles incident on it.

MeshResult stores no adjacency, and every pass that needs neighbours has so far rebuilt this by hand. Triangles with out-of-range indices are skipped. (meshminsizecleanup.cpp's Topo::build still has its own copy fused into a larger loop; converge them when that file is next touched.)

Here is the call graph for this function:
Here is the caller graph for this function:

◆ cellCentroid()

QPointF mesh::cellCentroid ( const MeshResult & mesh,
int cell )
nodiscard

Compute the planar area centroid using the shared cell fan geometry.

Parameters
[in]meshBorrowed stable geometry with finite nonfolded valid cells, unchanged.
[in]cellZero-based triangle/quad row index, bounds checked along with every vertex ID.
Returns
Owned project-CRS point; origin (0,0) on invalid indices, which is not an unambiguous missing sentinel. Triangles use vertex mean; zero-area quads fall back to vertex mean. No geometry repair, finite-coordinate validation, ownership retention or mutation.

Area centroid of cell cell (mesh::cellGeom — the vertex mean for a triangle, the area-weighted sub-triangle centroid for a quad). A null point for an out-of-range cell.

Here is the call graph for this function:

◆ cellContains()

bool mesh::cellContains ( const QVector< MeshVertex > & vertices,
const MeshTriangle & t,
const QPointF & p,
double eps = 0.0 )
inlinenoexcept

Test a point against the elevation-selected cell subtriangle fan using barycentric slack.

Parameters
[in]verticesStable valid referenced cell vertices in shared planar units.
[in]tValid cyclic triangle/nonfolded quad, preserved; cellGeom defines fan and diagonal.
[in]pFinite query point in same planar units, preserved.
[in]epsDimensionless nonnegative barycentric tolerance, default 0 includes triangle boundaries; negative values shrink allowable barycentric region, not validated.
Returns
True if any nondegenerate subtriangle has all barycentric coordinates>=-eps, false otherwise; abs(denominator)<1e-300 skips degenerate fan element. No Euclidean-distance tolerance, bounds/finite validation, allocation, ownership retention or mesh mutation; noexcept.

Point-in-cell test on the sub-triangle fan (barycentric per sub-triangle).

Here is the call graph for this function:

◆ cellCornerAngleDeg()

double mesh::cellCornerAngleDeg ( const QVector< MeshVertex > & v,
const MeshTriangle & t,
int i )
inline

Compute the unsigned corner angle of a triangle or quad.

Parameters
[in]vStable vertex storage containing every referenced cell index in range.
[in]tValid cyclic cell, preserved.
[in]iLocal corner in[0,t.vertexCount()), unchecked.
Returns
atan2(abs(cross),dot) angle in degrees[0,180] for finite representable edge products; does not distinguish reflex from convex angle, degeneracy/nonfinite values are not validated. Uses xy only, no allocation, ownership retention or mesh mutation.

Interior angle at corner i of a cell (degrees), triangles and quads.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ cellGeom()

CellGeom mesh::cellGeom ( const QVector< MeshVertex > & vertices,
const MeshTriangle & t )
inline

Compute triangle/quad subtriangles, positive fan area, area centroid and arithmetic mean elevation.

Parameters
[in]verticesStable vertex records with valid t indices, common planar units and consistent z units.
[in]tValid nonfolded cyclic cell, preserved; quads use stable elevation ordering to choose storage diagonal.
Returns
Owned geometry with area squared planar units, centroid planar units, zMean original vertical units, one or two subtriangles and quad diagonal case 1..3. Zero quad area falls back to vertex-mean centroid; triangle centroid always arithmetic. No bounds/finite/convexity validation, invalid/folded geometry can produce meaningless positive fan area or nonfinite fields. Constant local work, no heap allocation, ownership retention or mesh mutation; concurrent reads safe when inputs stable.

Geometry of cell t against vertices.

A quad is split along the Begnudelli & Sanders (2007) diagonal: with the vertices ordered by elevation n1 ≤ n2 ≤ n3 ≤ n4 — Case 1: n1,n4 opposite → sub-triangles (n1,n2,n4),(n1,n3,n4); Case 2: n1,n4 adjacent and n2 adjacent to n1 → (n1,n2,n4),(n2,n3,n4); Case 3 → (n1,n3,n4),(n2,n3,n4). The centroid is the area-weighted centroid of the two sub-triangles (a property of the polygon, independent of the diagonal).

Here is the call graph for this function:
Here is the caller graph for this function:

◆ cellIsConvex()

bool mesh::cellIsConvex ( const QVector< MeshVertex > & vertices,
const MeshTriangle & t )
inlinenoexcept

Check strict consistent quad turns, treating every triangle as convex without inspection.

Parameters
[in]verticesStable coordinates with valid quad vertex indices when t is a quad.
[in]tTriangle or cyclic quad, preserved.
Returns
True unconditionally for triangles; for quads true only when all four computed cross-products have matching nonzero sign, false for collinearity/mixed signs/NaN turn. No separate finite test, so caller supplies finite representable products. No allocation or mesh mutation, noexcept.

Convexity test for a quad (every consecutive cross product has the same non-zero sign). Triangles are trivially convex.

Here is the caller graph for this function:

◆ cellParamLabel()

QString mesh::cellParamLabel ( const QByteArray & key,
const QString & depthUnitLabel )
nodiscard

Build a display label using the registry and an optional project depth-unit suffix.

Parameters
[in]keyBorrowed case-sensitive parameter key, unchanged.
[in]depthUnitLabelBorrowed display unit text, normally UnitSystem::depthLabel(); no conversion occurs.
Returns
Owned translated spec label, with parenthesized unit only for lengthUnit entries and a nonempty unit label. Unknown keys fall back to QString::fromUtf8(key). Does not change registry or project data.

Full label for key including the unit suffix when the parameter is a length. depthUnitLabel comes from UnitSystem::depthLabel().

Here is the call graph for this function:

◆ cellParamSpec()

const CellParamSpec * mesh::cellParamSpec ( const QByteArray & key)
nodiscard

Find a registry specification by its case-sensitive stable byte key.

Parameters
[in]keyBorrowed key, unchanged; unknown/empty keys do not match.
Returns
Borrowed process-lifetime pointer into cellParamSpecs(), or null when unknown. Linear registry scan, lazy initialization may allocate; caller must not delete or mutate the result.

Look up one spec by key; returns nullptr when unknown.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ cellParamSpecs()

const QVector< CellParamSpec > & mesh::cellParamSpecs ( )
nodiscard

Return the immutable shared registry of mesh cell parameter/editor specifications.

Returns
Borrowed reference to a process-lifetime static vector in display order; never delete or mutate. Initialization is lazy and labels are translated once using the then-current application translators; later translator changes do not rebuild the vector. Includes disabled preview/snow/groundwater entries as well as editable parameters. First call allocates; subsequent reads retain stable spec addresses.

The registry, in display order. Stable for the process lifetime.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ cellParamValue()

double mesh::cellParamValue ( const MeshResult & mesh,
int tri,
const QByteArray & key )
nodiscard

Read a stored or inheritance-resolved cell parameter without substituting editor defaults.

Parameters
[in]meshBorrowed stable mesh and authoring-preview arrays, unchanged.
[in]triCell/preview index; ordinary parameters require [0,triangles.size()). Preview owner/weather keys instead validate only their corresponding preview array extent, so a preview may exist without a cell.
[in]keyBorrowed case-sensitive registry key; method-specific infiltration keys resolve override, region tag then wildcard, and unused method slots are unavailable.
Returns
Stored value, NaN for missing/out-of-range/unknown/unset/unused values, or numeric enum including -1 for infiltration None. Depth and infiltration values retain their stored project units, percentages are 0..100 by convention and owner/conflict codes are integers represented as doubles. Does not clamp, validate physical ranges, convert units, materialize overrides or write engine state.

Current value of key on triangle tri.

The infil.* keys resolve through mesh::resolveInfil (override → tag row → '*' row), so an inherited value reads back here exactly as the engine would see it; a parameter the resolved METHOD does not use returns NaN, which is what drives the attribute table's per-row column masking. infil.method returns the mesh::InfilMethod integer (-1 = None).

Here is the call graph for this function:

◆ cellSignedArea()

double mesh::cellSignedArea ( const QVector< MeshVertex > & vertices,
const MeshTriangle & t )
inlinenoexcept

Compute oriented polygon area in local coordinates to reduce projected-origin cancellation.

Parameters
[in]verticesStable planar coordinates in common units, every t index valid.
[in]tCyclic triangle/quad, preserved.
Returns
Half signed cross-sum in squared coordinate units, positive for CCW, negative for CW and zero for degenerate cells. No finite/overflow/index validation or coordinate scaling, noexcept allocation-free read-only work.

Signed area of the polygon (positive = counter-clockwise).

Here is the caller graph for this function:

◆ cellVelocity()

bool mesh::cellVelocity ( int cell,
int nv,
const float * flux,
const float * length,
const float * nx,
const float * ny,
double depth,
double dryDepth,
double & vx,
double & vy )
inlinenoexcept

Reconstruct cell velocity from edge discharge only when a usable wet depth is available.

Parameters
[in]cellNonnegative valid cell index, stride-four address arithmetic must fit int.
[in]nvNumber of real edges 3 or 4, no padding read.
[in]fluxNonnull stable flat outward volumetric fluxes m3/s, extent>=4*(cell+1).
[in]lengthNonnull stable equal-extent lengths metres.
[in]nxNonnull stable equal-extent outward unit-normal x components.
[in]nyNonnull stable equal-extent outward unit-normal y components.
[in]depthFinite positive hydraulic depth in metres; below dryDepth refuses.
[in]dryDepthDry threshold in metres; caller supplies nonnegative finite policy value, threshold equality is wet, depth<=0 always refuses.
[out]vxBorrowed x velocity m/s, set zero before validation; can be nonfinite if final division fails.
[out]vyBorrowed y velocity m/s, same policy, use distinct outputs.
Returns
True only for successful discharge reconstruction and both finite velocities; false for invalid/ dry depth, degenerate solve or nonfinite divided values. Early refusal leaves zero outputs, final nonfinite refusal does not restore zero. Arrays borrowed unchanged, no allocation or physical state update.

Velocity in SI m/s from outward volumetric edge flux. Never substitute specific discharge for velocity, or divide by a dry/non-finite depth.

Here is the call graph for this function:

◆ classifyQuadRegion()

QuadRegionMode mesh::classifyQuadRegion ( const QPolygonF & ring,
QVector< int > * corners,
double cornerTolDeg = 25.0,
double rectilinearTolDeg = 2.0 )

Heuristically classify normalized ring turns as Mapped, Submapped or Free.

Parameters
[in]ringBorrowed finite valid planar ring, unchanged; normalized CCW/open before evaluating turns.
[out]cornersOptional borrowed vector, cleared first; Mapped success fills four indices into the normalized ring, not necessarily original input positions. Other modes leave it empty.
[in]cornerTolDegFinite nonnegative degree tolerance, default 25. Mapped needs exactly four turns within inclusive 90+/-tolerance and all other absolute turns strictly below tolerance.
[in]rectilinearTolDegFinite nonnegative degree tolerance, default 2. Submapped accepts every absolute turn close to 90 or close to zero (straight-through vertices are allowed).
Returns
Mapped first, otherwise Submapped for rectilinear turns, otherwise Free including <3 corners. Does not validate simplicity, corner metadata, directional mesher feasibility or quality; allocates normalized/turn/output arrays, retains no pointers and changes no input geometry.

Auto-classification (plan §4.1) on the normalised ring.

Turning angle at each vertex (exterior angle, CCW positive): - exactly four vertices with turn in [90 − cornerTolDeg, 90 + cornerTolDeg] and every other |turn| < cornerTolDeg → Mapped (corners = those four, in ring order); - every turn within rectilinearTolDeg of ±90° or zero → Submapped; - otherwise Free. corners receives the Mapped corners when non-null (cleared otherwise).

◆ cleanupAndSmoothQuads()

QuadCleanupStats mesh::cleanupAndSmoothQuads ( MeshResult & mesh,
const QSet< int > & movable,
const QuadCleanupOptions & opts,
QVector< int > * vertexOldToNew )

Remove eligible quad doublets, improve valence diagonals, smooth movable xy and compact/reorder cells.

Parameters
[in,out]meshBorrowed exclusively mutable finite valid mesh. Caller protects domain/constraint/ coupled vertices by excluding them from movable; no automatic boundary, coupling or interface protection is inferred. All surviving cell IDs must remain valid for unchecked smoothing/compaction geometry reads.
[in]movableBorrowed vertex-ID set, unchanged; invalid IDs filtered and valid IDs processed sorted. Only these vertices can move/remove, but cell order and surviving vertex indices can change globally.
[in]optsBorrowed policy; negative topology/smoothing counts act as zero. Topology candidates must pass full quad bounds and CCW area. Smoothing checks orientation/convexity, incident min Jacobian, per-cell min(previous,configured quad floor/triangle .5), and no introduced/worsened active aspect cap; it does not independently enforce the angle bounds. Jacobi moves are rechecked together with reverts.
[out]vertexOldToNewOptional borrowed vector, identity at entry or old-to-compacted IDs with -1 for removed vertices. Caller-held index sets/views must be rebuilt afterward; output pointer not retained.
Returns
Owned operation counts, with no cancellation/error channel or exception rollback. Always stable reorders triangles before quads, even for empty movable/no topology work. Retained vertex z/attributes are copied while xy may move, so caller must resample/revalidate elevations. Boundary edges remap/drop with removed endpoints; coupling/infiltration cell keys remap through compaction/reorder, but removed cell records become -1 and colliding overrides use hash replacement. Run before authoring that metadata or reconcile it externally; other preview arrays are not remapped. Allocates working topology/output, invalidates array views, emits no layer signals, writes no files and does not synchronize engine state.

Run cleanup then smoothing. vertexOldToNew (optional) receives the vertex remap after doublet compaction (-1 = removed); identity when nothing was removed. Cells are rebuilt triangles-first afterwards.

Here is the call graph for this function:

◆ computeCellAreaStats()

CellAreaStats mesh::computeCellAreaStats ( const MeshResult & mesh)
nodiscard

Summarize unsigned fan areas of all index-valid triangle and quad rows.

Parameters
[in]meshBorrowed stable finite nonfolded geometry, unchanged; invalid-index rows are skipped, but valid-index zero-area rows remain in the sample.
Returns
Owned min/max/mean/median in squared project-CRS units and measured count; all-zero default when no rows qualify. Even-count median averages middle values. Finite/convexity checks are not performed, so caller must exclude invalid coordinates/folded cells. Allocates scratch area storage, no source mutation or engine state dependency.

Compute cell-area statistics over all triangles in mesh.

Area is triangleArea. Triangles referencing out-of-range vertex indices are skipped. Median of an even count is the average of the two middle values.

Here is the call graph for this function:

◆ computeCellLchar()

QVector< double > mesh::computeCellLchar ( const MeshResult & mesh)
nodiscard

Estimate the engine-style CFL characteristic length from cell geometry and interior faces.

Parameters
[in]meshBorrowed stable finite nonfolded geometry in consistent project-CRS units, unchanged; indices are checked, but full topology/finite validation is caller's responsibility.
Returns
Owned vector parallel to triangles, length units matching planar coordinates, zero for invalid-index cells. Faces with exactly two incidences contribute xi/max(abs(dc dot n),0.3*|dc|), with inverse zero below 1e-12; isolated cells use 2*area/longestEdge, otherwise sqrt(2*area/sum). Boundary/nonmanifold faces are omitted. Allocates scratch adjacency/geometry arrays; no hydraulic depth, coupling tier pins or runtime solver state is applied, so this is a geometric proxy only.

Per-cell L_char for mesh, indexed like mesh.triangles. Cells with invalid indices get 0.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ computeCflStats()

CflStats mesh::computeCflStats ( const MeshResult & mesh,
int ltsTiers = 4 )
nodiscard

Summarize positive geometric CFL lengths and a uniform-depth local-timestep work proxy.

Parameters
[in]meshBorrowed stable finite geometry in project-CRS units, unchanged.
[in]ltsTiersRequested work-proxy tier cap, clamped to [1,8], default 4.
Returns
Owned min/10th/50th/90th/max length statistics, dimensionless ratio and implied tier count, plus work sum(2^-tier)/minimum in inverse project length units. Percentiles use nearest rounded index, not interpolation. Invalid-index or nonpositive lengths are excluded; no valid sample returns default zeros. Interior/isolated diagnostics use raw two-incidence adjacency, not only positive-area samples. Assumes finite representable positive lengths for logarithms; no runtime wet/depth/boundary pin behavior is modeled. Allocates scratch arrays, no source or solver mutation.

Summarise computeCellLchar. ltsTiers mirrors the engine's [2D_OPTIONS] LTS_TIERS (1..8, default 4).

Here is the call graph for this function:

◆ computeGradingStats()

GradingStats mesh::computeGradingStats ( const MeshResult & mesh)
nodiscard

Summarize adjacent-cell size ratios, face orthogonality and minimum cell corner angles.

Parameters
[in]meshBorrowed stable finite nonfolded triangle/quad geometry, unchanged; invalid-index, nonpositive-area or nonpositive-longest-edge cells are excluded.
Returns
Owned dimensionless ratio distribution/histogram and degree angles; faces require exactly two valid incident cells. Size is longest edge; ratio median uses upper middle, P95 uses floor(0.95*n) capped at the last index. Orthogonality needs positive edge/chord lengths and can sample fewer faces. No-face ratio defaults are 1, no-cell minimum angle remains 180 degrees. Allocates adjacency/scratch arrays, does not alter topology or run the engine; nonfinite geometry is not comprehensively validated.
Here is the call graph for this function:

◆ computeQuadStats()

QuadStats mesh::computeQuadStats ( const MeshResult & mesh)
nodiscard

Summarize quad angles, quality, bed twist and interior quad-only vertex valence.

Parameters
[in]meshBorrowed stable geometry and boundaryEdges, unchanged; finite representable planar/z coordinates are required for meaningful results. Invalid vertex-index cells are skipped.
Returns
Owned metrics with angles in degrees, twist in project vertical units and dimensionless quality. Counts quad-classified rows even if nonconvex; zero-count quality/angle fields reset to zero. Rectangularity median averages the two middle values for even counts. Irregular vertices exclude boundaryEdge endpoints and any vertex touching a triangle. Allocates scratch vectors/sets, no mesh mutation or engine query; topology and finite geometry validity are not independently enforced.
Here is the call graph for this function:

◆ edgeEndpoints()

void mesh::edgeEndpoints ( const MeshTriangle & t,
int k,
int & a,
int & b )
inlinenoexcept

Resolve the ordered vertex IDs of one cell-local opposite-edge convention.

Parameters
[in]tValid cyclic triangle/quad, preserved, no vertex-coordinate lookup.
[in]kLocal edge in[0,t.vertexCount()), caller must not pass triangle padding3.
[out]aBorrowed reference overwritten with vertex((k+1)nv).
[out]bBorrowed reference overwritten with vertex((k+2)nv); caller should use distinct outputs.
Note
Retains stored orientation and index values without validation, noexcept constant work. No ownership transfer, allocation or topology mutation.

Endpoints (a, b) of local edge k of cell t: v[(k+1)nv], v[(k+2)nv].

Here is the caller graph for this function:

◆ edgeKey()

QPair< int, int > mesh::edgeKey ( int a,
int b )
inlinenoexcept

Normalize two endpoint identifiers into an undirected ordered key.

Parameters
[in]aFirst integer vertex identifier, any value including negative sentinel accepted.
[in]bSecond integer identifier, equal values allowed.
Returns
Owning (min(a,b),max(a,b)) pair, independent of orientation. Does not validate mesh bounds, self-edge geometry or connectivity; noexcept constant work, no allocation or shared state.

Unordered vertex-pair key used for locked edges: (min, max).

Here is the caller graph for this function:

◆ edgeSlot()

int mesh::edgeSlot ( int cell,
int e )
constexprnoexcept

Compute the flat stride-four slot for one cell-local edge.

Parameters
[in]cellNonnegative zero-based cell index; cell*4+e must fit int.
[in]eLocal edge[0,3] for storage addressing; triangle slot 3 is padding, not a real edge.
Returns
cell*kEdgeStride+e, unchecked arithmetic, no array access or ownership/state mutation.

Flat edge slot of local edge e of cell cell.

Here is the caller graph for this function:

◆ edgeSlotCount()

int mesh::edgeSlotCount ( int nCells)
constexprnoexcept

Calculate padded per-edge storage length for a cell count.

Parameters
[in]nCellsNonnegative cell count with 4*nCells representable in int.
Returns
Four slots per cell including unused triangle padding, no allocation or bounds checking.

Number of flat edge slots for nCells cells.

Here is the caller graph for this function:

◆ findFacingPairs()

QVector< FacingPair > mesh::findFacingPairs ( const QVector< QVector< QPointF > > & lines,
const QVector< QPair< QPointF, QPointF > > & obstacles,
const FacingPairOptions & opt )
nodiscard

Greedily identify near-parallel breakline runs facing across an unobstructed sampled strip.

Parameters
[in]linesBorrowed finite planar paths, unchanged; only consecutive edges exist, closed rings must repeat first point. Nonpositive-length segments skipped; sizes/grid/arc/station arithmetic must be representable and feasible. Coordinates/grid-cell floor plus neighboring loop increments must fit qint64.
[in]obstaclesBorrowed finite segment endpoints in the same CRS/units, unchanged; obstacle hit blocks a ray instead of becoming a bank. No polygon/volume clearance test is performed.
[in]optBorrowed policy with finite 0<minWidth<maxWidth and station>0; minStations>=2, finite nonnegative widthChange/endTrimFraction and maxAngleDeg normally [0,90] are caller's contract. Station counts, integer end trimming and sampling loops must be representable/feasible. Optional elevationAt executes synchronously in the same xy frame and consistent vertical units; NaN/nonfinite samples are unavailable, exceptions propagate and callback must not mutate inputs.
Returns
Owned pairs, longest post-trim A arc first (stable candidate ties), empty for checked invalid width/station policy or no qualifying runs. Casts both station normals to nearest positive hit within maxWidth, rejecting self/obstacle/too-near/nonparallel hits; runs need steady width, monotone B progression and untrimmed length>=three median widths. Trims both ends then needs minStations; optional trough test requires at least half stations finite and summed midpoint elevations strictly below both outside sums. Width is upper-middle median before end trimming, length is retained A arc; both bank outputs keep their own input direction, not necessarily common direction. Accepted arc intervals never overlap on either line (endpoint contact allowed), but no global Cartesian strip intersection/optimal pairing guarantee is added. Allocates station/index/candidate/output storage, retains no references, no mesh/engine/file edits.

Find facing pairs among lines (open polylines; a closed ring repeats its first point). From stations along each line a ray is cast both ways along the normal; the first thing it meets within maxWidth must be another line, near-parallel, at least minWidth away — an obstacles segment, or the same line, blocks it. Consecutive stations that meet the same line at a steadily changing separation form a run. Pairs come back longest first and never share a portion of a line.

◆ indexOfDefault()

int mesh::indexOfDefault ( const MeshResult & mesh,
const QString & tag )

Find the first exact case-sensitive default tag match.

Parameters
[in]meshBorrowed stable default rows, unchanged.
[in]tagBorrowed tag, compared without trimming or normalization; empty and * are allowed.
Returns
Zero-based first matching index or -1 when absent. Duplicate tags are not rejected. Linear read-only scan, no geometry or inheritance resolution.

Index of tag in MeshResult::infilDefaults, or -1.

Here is the caller graph for this function:

◆ infilDestFromToken()

InfilDest mesh::infilDestFromToken ( const QString & token,
bool * ok = nullptr )

Parse a retained destination token independently of current engine support.

Parameters
[in]tokenBorrowed complete case-insensitive token, surrounding whitespace ignored.
[out]okOptional borrowed flag, true for LOST/SUBCATCH_AQUIFER/AQUIFER_2D, false otherwise.
Returns
Recognized destination or Lost for unknown/empty input. AQUIFER_2D is recognized for legacy review/migration despite current validation rejection. No model existence or routing checks.

◆ infilDestHint()

QString mesh::infilDestHint ( InfilDest d)

Translate destination guidance without resolving any open model.

Parameters
[in]dDestination enum; unknown values use the Lost guidance.
Returns
Owned explanation: lost outflow, legacy subcatchment recharge, or obsolete Aquifer2D migration via groundwater ownership review. This is authoring guidance, not a runtime support/coverage result; no model handle, geometry lookup or state mutation is involved.

A one-sentence tooltip for destination d: where the water goes and what the choice needs.

The hint describes authoring guidance only; it does not inspect a model. Aquifer2D is retained for legacy-file migration and its hint directs users to the groundwater ownership review workflow.

◆ infilDestLabel()

QString mesh::infilDestLabel ( InfilDest d)

Translate the display label of a retained destination value.

Parameters
[in]dDestination enum, unchanged; unknown values use Lost.
Returns
Owned MeshInfil-context label. A 2D Aquifer label names a legacy enum, not a support guarantee; no model validation or routing mutation occurs.
Here is the caller graph for this function:

◆ infilDestLabels()

QStringList mesh::infilDestLabels ( )

Build translated destination labels in enum order Lost, SubcatchAquifer, Aquifer2D.

Returns
Owned three-label list indexed by enum integer, including the retained legacy Aquifer2D option. Does not filter unsupported choices or inspect model ownership; no model mutation.
Here is the call graph for this function:

◆ infilDestToken()

QString mesh::infilDestToken ( InfilDest d)

Encode a destination enum as its retained uppercase file token.

Parameters
[in]dDestination enum, unchanged.
Returns
Owned SUBCATCH_AQUIFER or AQUIFER_2D for those values, LOST for Lost or unknown values. Encoding AQUIFER_2D preserves legacy authoring data but does not imply current engine support; current validation rejects it as obsolete. No model mutation or availability check. "LOST", …

◆ infilMethodFromToken()

InfilMethod mesh::infilMethodFromToken ( const QString & token,
bool * ok = nullptr )

Parse a trimmed case-insensitive infiltration method token.

Parameters
[in]tokenBorrowed stable text, unchanged; complete token must match the file vocabulary.
[out]okOptional borrowed recognition flag, true for a known token including NONE, false otherwise.
Returns
Recognized method or None on unknown/empty input. Use ok to distinguish explicit NONE from failure. No parameter validation, unit conversion, ownership retention or model mutation.

◆ infilMethodLabel()

QString mesh::infilMethodLabel ( InfilMethod m)

Translate a display label for an infiltration method.

Parameters
[in]mMethod enum, unchanged; unknown values use the None label.
Returns
Owned MeshInfil-context label using current application translators, with no model mutation. Translated UI label
Here is the caller graph for this function:

◆ infilMethodLabels()

QStringList mesh::infilMethodLabels ( )

Build translated method labels in consecutive enum order from None through Constant.

Returns
Owned seven-label list; index 0 corresponds to enum -1, so enum value equals label index minus 1. Uses current translators on each call, allocates value storage and changes no model state. For EnumComboDelegate, in enum order
Here is the call graph for this function:
Here is the caller graph for this function:

◆ infilMethodToken()

QString mesh::infilMethodToken ( InfilMethod m)

Encode an infiltration method using the stable uppercase file vocabulary.

Parameters
[in]mMethod enum, unchanged.
Returns
Owned HORTON, MODIFIED_HORTON, GREEN_AMPT, MODIFIED_GREEN_AMPT, CURVE_NUMBER or CONSTANT; None and unknown enum values both return NONE. No validation, locale translation or mutation. "HORTON", "CURVE_NUMBER", "NONE", …

◆ infilParamCount()

int mesh::infilParamCount ( InfilMethod method)

Report serialized parameter-column width rather than number of active values.

Parameters
[in]methodInfiltration method, unknown/None values yield zero.
Returns
Five for Horton variants, three for Green-Ampt and Curve Number, one for Constant, zero otherwise. Curve Number's middle placeholder is included although infilUsesParam() rejects it. Read-only query.

Number of serialized positional columns for method, including unused placeholders.

◆ infilParamKey()

QByteArray mesh::infilParamKey ( InfilMethod method,
int slot )

Map an active model slot to its case-sensitive shared registry key.

Parameters
[in]methodModel enum, unchanged.
[in]slotZero-based positional slot, 0..4; unused/out-of-range combinations return empty.
Returns
Owned byte key such as infil.f0 or infil.dryTime, empty if unused/unknown. Drying time maps from Horton slot 3 and Curve Number slot 2. No registry mutation or numeric parameter access.

Registry key for positional slot slot under method, e.g. "infil.f0". Empty when unused.

This is the bridge to mesh::cellParamSpecs(): the attribute table registers one column per NAMED key (the union across methods) and masks per row via infilUsesParam().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ infilParamKeys()

const QVector< QByteArray > & mesh::infilParamKeys ( )

Return the immutable union of named infiltration parameter keys in registration order.

Returns
Borrowed process-lifetime vector, ten distinct case-sensitive keys; do not delete or mutate. Lazy static initialization may allocate once. Keys shared across methods appear once, so callers must use method-specific slot lookup instead of interpreting list positions as parameter slots.

Every named parameter key, in registration order. The attribute table and the assign dialog iterate this.

◆ infilParamLabel()

QString mesh::infilParamLabel ( InfilMethod method,
int slot )

Translate the model-specific label for an active positional parameter.

Parameters
[in]methodModel enum, unchanged.
[in]slotZero-based slot, valid only when infilUsesParam(method,slot) is true.
Returns
Owned MeshInfil-context label, empty for unused/out-of-range/unknown combinations. Labels distinguish method semantics, not values; no model mutation or unit conversion.

Display label for positional slot slot under method, e.g. ("Horton", 0) → "Max Rate (f0)". Empty when unused.

Here is the call graph for this function:

◆ infilSlotForKey()

int mesh::infilSlotForKey ( InfilMethod method,
const QByteArray & key )

Resolve a named parameter key to its position under one model.

Parameters
[in]methodModel enum used to interpret slot semantics, unchanged.
[in]keyBorrowed case-sensitive registry key; empty/unknown keys do not match.
Returns
Slot 0..4 when active for this method, -1 otherwise. No inheritance resolution, parameter validation or mutation; constant-size scan of the five slots.

Inverse of infilParamKey(): maps a registry key to the positional slot it occupies under method, or -1 when method does not use it.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ infilUsesParam()

bool mesh::infilUsesParam ( InfilMethod method,
int slot )

Check whether a model uses a zero-based positional parameter slot.

Parameters
[in]methodModel enum, unknown/None values use no slots.
[in]slotPosition 0..4; any outside position returns false.
Returns
True for all five Horton slots, first three Green-Ampt slots, Curve Number slots 0 and 2, or Constant slot 0; false otherwise. No parameter values read, validation or unit conversion.

True when method uses positional slot slot.

Drives the attribute table's per-row column masking: a cell whose method does not use a parameter renders "—" and refuses edits, exactly like MeshAttributeTableModel::rowIsBoundaryEdge() does for BC columns on interior edges.

Here is the caller graph for this function:

◆ initialConditionCounterpart()

QByteArray mesh::initialConditionCounterpart ( const QByteArray & key)
nodiscard

Name the alternative initial-condition key of key.

Returns
"initHgl" for "initDepth", "initDepth" for "initHgl", empty for every other key.

A cell's initial state is authored either as a depth or as a water-surface elevation. Edit commands use this to clear the one the user did not just set, so a cell never carries both.

◆ loadLookupTableCsv()

bool mesh::loadLookupTableCsv ( InfilLookupTable * table,
const QString & path,
QString * err )

Load the permissive unquoted classified-lookup CSV format into a fresh table value.

Parameters
[out]tableRequired borrowed destination; null returns false. Untouched when opening fails; reset after successful open and then populated incrementally, including a basename fallback name.
[in]pathBorrowed UTF-8 input pathname, unchanged.
[out]errOptional borrowed string, overwritten only on open failure; not cleared on success or null-destination refusal.
Returns
False only for null destination/open failure, true after parsing even empty/malformed content. Unknown-method/header rows are skipped; absent/unparseable parameters stay NaN, unknown destination falls back Lost, * key1 sets fallback and last fallback wins. KEY2 metadata or nine-or-more columns selects two-key parsing; no CSV quoting, physical validation or later read-error check is performed. Allocates owned entries, retains project-unit values and does not mutate any mesh or engine.

◆ makeBankPairPatch()

PatchMesh mesh::makeBankPairPatch ( const BankPairPatch & p,
QString * err = nullptr )

Build a conforming strip between two simple, disjoint banks.

Rejects ambiguous endpoint pairing, touching/crossing banks, folded cells, unrepresentable station geometry and unsafe subdivision counts.

◆ makeConstraintPreview()

ConstraintPreview mesh::makeConstraintPreview ( const QVector< SimplificationFeature > & original,
const ConstraintSimplificationResult & candidate,
const std::function< bool()> & cancelled = {},
int maximumVertices = 50000,
int maximumFeatures = 500 )

Build bounded display data comparing source features with a simplification candidate.

Reads its inputs only; it does not run or repeat the preparation audit.

Parameters
[in]originalSource features given to simplifyConstraints(); read only.
[in]candidateResult of simplifyConstraints() for original; read only. When it is not ok or its feature or change count differs from original, an empty default preview is returned without any error indication.
[in]cancelledOptional poll, called synchronously once per feature and about every 4096 visited vertices; returning true returns the partial preview with cancelled set.
[in]maximumVerticesDisplay vertex budget, clamped to [4, 250000]. Up to min(2000, maximumVertices / 10) go to removed-vertex markers; the rest is split evenly over the original and proposed paths of the displayed features, at least 2 points per path.
[in]maximumFeaturesDisplayed feature limit, clamped to at least 1 and at most min(5000, path budget / 4).
Returns
Owned preview. The unit labels are left empty for the caller to fill.

◆ makeMappedPatch() [1/2]

PatchMesh mesh::makeMappedPatch ( const QPolygonF & ring,
const QVector< int > & corners,
double h,
const QString & tag,
QString * err = nullptr )

Split a CCW ring at the four corners (ring vertex indices, ring order) into polyline sides, choose n = max(1, round(mean(len0, len2)/h)), m likewise from sides 1/3, and call the polyline overload.

◆ makeMappedPatch() [2/2]

PatchMesh mesh::makeMappedPatch ( const QPolygonF & ring,
const QVector< int > & corners,
double hAlong,
double hAcross,
double alongAngleDeg,
const QString & tag,
QString * err = nullptr )

Mapped patch with independent physical-axis spacing.

The axis is undirected, measured counterclockwise from +x in degrees. The opposite logical side pair most aligned with it receives hAlong; the other receives hAcross. Equal association scores are rejected. Ring rotation/reversal must not exchange the physical spacings. Widths use the ring's coordinate units.

◆ makeSweptPatch()

PatchMesh mesh::makeSweptPatch ( const SweptPatch & p,
QString * err = nullptr )

Sweep the centreline: (stations)×(across+1) vertices, (stations-1)×across quads.

Station and index counts are checked before allocation. Invalid or globally overlapping/touching offsets return an empty PatchMesh and a diagnostic identifying the affected stations.

◆ makeTransfinitePatch() [1/2]

PatchMesh mesh::makeTransfinitePatch ( const QVector< QVector< QPointF > > & sides,
int n,
int m,
const QString & tag,
QString * err = nullptr )

Transfinite (Coons) interpolation on four POLYLINE sides forming a loop: sides[0] runs c0→c1, sides[1] c1→c2, sides[2] c2→c3, sides[3] c3→c0 (each side's last point equals the next side's first).

Sides are arc-length parametrised; n subdivisions along sides 0/2, m along 1/3. Boundary vertices are placed ON the polylines (so the ring the caller emits as PSLG segments is exactly this patch's boundary loop). Returns an empty PatchMesh + *err on invalid input (side with < 2 points, endpoints not matching, n or m < 1, folded quad).

◆ makeTransfinitePatch() [2/2]

PatchMesh mesh::makeTransfinitePatch ( const StructuredPatch & p,
QString * err = nullptr )

Transfinite interpolation on the four straight sides.

The result has (n+1)×(m+1) vertices and n×m quads. On invalid input returns an empty PatchMesh and sets *err.

◆ makeTransfinitePatchAtStations()

PatchMesh mesh::makeTransfinitePatchAtStations ( const QVector< QVector< QPointF > > & sides,
const QString & tag,
QString * err = nullptr )

Coons patch whose boundary vertices are exactly the given side stations.

Parameters
[in]sidesFour cyclic polylines c0→c1, c1→c2, c2→c3, c3→c0, each with >= 2 finite points; sides 0/2 and 1/3 need equal point counts, and each side's last point must equal the next side's first exactly. n = sides[0].size() - 1, m = sides[1].size() - 1.
[in]tagCopied verbatim to the patch and every quad.
[out]errOptional; receives the diagnostic, or an empty string on success.
Returns
Patch of (n+1)(m+1) vertices and n·m CCW quads (either input winding), or an empty PatchMesh on invalid input or a folded/invalid result.

◆ maximumMatching()

QVector< int > mesh::maximumMatching ( int n,
const QVector< QPair< int, int > > & edges )

Compute an unweighted maximum-cardinality matching in an undirected general graph.

Parameters
[in]nNumber of vertices, normally nonnegative and feasible for int-indexed working arrays; n<=0 returns empty, n==1 returns one unmatched entry.
[in]edgesBorrowed endpoint pairs, unchanged; out-of-range, negative and self-loop pairs skipped, duplicate/reversed pairs are retained as adjacency incidences.
Returns
Owned length-max(0,n) mate array, -1 for unmatched, otherwise reciprocal partner index. Uses Edmonds blossom/augmenting paths; edge traversal/input order can choose among equal-cardinality solutions and no edge weight/geometry objective is used. Allocates graph/search state, no source mutation, ownership retention, cancellation or explicit resource-failure result.

Maximum-cardinality matching on a general graph — Edmonds' blossom algorithm. edges are unordered pairs in [0, n). Returns mate[i] (-1 = unmatched). Exposed for the brute-force cross-check test.

Here is the caller graph for this function:

◆ meanVertexIndexSpread()

double mesh::meanVertexIndexSpread ( const MeshResult & m)
nodiscard

Compute mean absolute index jump across each cell's consecutive cyclic corner pairs.

Parameters
[in]mBorrowed mesh, unchanged; stored identifiers need not index coordinates, but each integer difference must fit int before absolute value. Handles triangles and quads, irrespective of validity.
Returns
Dimensionless mean index spread, zero for no cells. Shared edges contribute once per incident cell, and no geometric distance/area weighting is used. Linear read-only traversal, no allocation.

Cheap locality proxy: mean |vi − vj| over the three vertex-index pairs of every triangle. O(nt), no allocation — safe to log on any mesh size.

Here is the call graph for this function:

◆ normalizeRingCCW()

QPolygonF mesh::normalizeRingCCW ( const QPolygonF & ring)

Copy a ring while dropping scale-fuzzy consecutive/closing duplicates and reversing negative area.

Parameters
[in]ringBorrowed finite planar points, unchanged; fuzzy coordinate tolerance is 1e-9 times max(1,largest absolute original coordinate), separately on x/y, so it depends on projected origin.
Returns
Owned open sequence without closing duplicate, CCW when nondegenerate negative area was reversed. Nonconsecutive duplicate IDs, self-crossings and zero-area/NaN geometry are not repaired or rejected. Allocates output, can remove near-distinct coordinates within tolerance, retains no source references.

Drop a closing duplicate, drop consecutive duplicates, make CCW.

◆ orderedPatchBoundary()

QPolygonF mesh::orderedPatchBoundary ( const PatchMesh & pm,
QString * err = nullptr )

Validate the complete patch and return its CCW boundary, without a repeated closing vertex.

Segment input orientation/order is immaterial. On failure returns an empty ring and sets err.

Here is the caller graph for this function:

◆ pairTrianglesIntoQuads()

QuadPairingStats mesh::pairTrianglesIntoQuads ( MeshResult & mesh,
const QVector< int > & cellIds,
const QVector< QuadTemplate > & templates,
const QSet< QPair< int, int > > & lockedEdges,
const QuadPairingOptions & opts,
QVector< int > * oldToNew )

Pair selected valid triangle rows into acceptable CCW quads, then rebuild engine cell order.

Parameters
[in,out]meshBorrowed exclusively mutable mesh, finite valid nonoverlapping geometry; vertex storage/coordinates are preserved, cells and selected index-keyed metadata can be replaced/remapped. Selected pairs should share coherent tag/material/initial-depth values; no equality check is performed.
[in]cellIdsBorrowed candidate old cell IDs, unchanged. Invalid/out-of-range/duplicate IDs, existing quads and triangles with invalid vertex IDs are skipped. Every other cell can still move during final reorder.
[in]templatesBorrowed cyclic four-output-vertex templates, unchanged. Invalid IDs/duplicates/ quality failures are skipped. Templates rank by score then input index; either triangulation diagonal may match.
[in]lockedEdgesBorrowed normalized edgeKey(min,max) set; pairing never removes these shared edges. No normalization is performed on supplied set keys, unmatched keys have no effect.
[in]optsBorrowed finite quality policy; enables residual maximum-cardinality blossom and up to five score-improving alternating-four-cycle polish passes. This is not maximum-weight optimization.
[out]oldToNewOptional borrowed vector, filled with identity at entry even for no-op; on rebuild maps each old cell to its new cell, both paired triangles to the same quad. No output pointer retained.
Returns
Owned counts, with no error/cancellation channel. No accepted pair leaves mesh unchanged; otherwise surviving triangles, existing quads then new quads are emitted, each new quad inheriting its chosen first source triangle's attributes. Coupling indices and infiltration override keys remap, but colliding override rows use ordinary hash replacement and other preview arrays are not remapped. Caller should pair before conflicting per-cell metadata exists/rebuild dependent state. Allocates adjacency/matching/output storage, invalidates cell-array views, no engine/file update or rollback on exceptions.

Pair the triangles cellIds (indices into mesh.triangles; every one must be a triangle) into quads. templates carry OUTPUT vertex ids. lockedEdges (mesh::edgeKey pairs) are never straddled. On return oldToNew (optional) maps every old cell index to its new index (a paired triangle maps to its quad). Region triangles that were not paired keep their tag/mannings/initDepth; a quad inherits them from its first triangle (tags of the two triangles are equal inside a region).

Here is the call graph for this function:

◆ placeQuadBlocks()

QVector< QuadRegion > mesh::placeQuadBlocks ( const QuadBlockGrid & grid,
const QuadBlockOptions & options )

Greedily select axis-aligned mapped quad regions from approximately uniform usable grid bands.

Parameters
[in]gridBorrowed stable grid with finite positive pitch/origin and valid storage extent, unchanged; nonfinite/nonpositive h entries are unusable. All logarithmic band indices, powers, spacing-to-cell ceil conversions and loop/product arithmetic must be representable.
[in]optionsBorrowed policy with finite bandRatio>1, feasible finite minSpacing and positive minQuadsPerSide recommended. maxBlocks<=0 produces no regions; nonpositive minimum spacing does not filter.
Returns
Owned open four-corner Mapped QuadRegions with explicit spacing/corner indices, empty on basic invalid grid/band policy or no eligible rectangles. Processes coarser two-adjacent bands first, up to four candidate passes per band, sorting rectangles largest-first then row/column within a pass. 3/4-cost chamfer/grid exclusion supplies clearance from unusable cells, grid edges and prior blocks; regions shrink to centered whole-spacing dimensions. No exact Euclidean feature clearance or final mesher-quality guarantee is added. Allocates bands/distances/candidate/output storage, retains no inputs and changes no grid/mesh/engine state; no cancellation or explicit resource-failure result.

Axis-aligned rectangles over nearly uniform usable cells, largest first, each at least minQuadsPerSide quads of its spacing per side, kept one spacing apart from each other. Each comes back as a Mapped QuadRegion whose spacing is its band's.

◆ planQuadRegions()

QuadPlan mesh::planQuadRegions ( const QVector< QuadRegion > & r,
const QuadPlanningGeometry & g,
const QuadPlanningOptions & o = {} )

Plan mapped quad patches for all regions jointly, before CDT construction.

The arguments, all read only, are the regions, the protecting source geometry and the options. A region is a candidate unless quads are disabled globally or by QuadRegionMode::TrianglesOnly, and only when its ring has at least three vertices, nonzero area and exactly four corners: QuadRegion::corners (strictly increasing ring indices) or, when empty, the vertices turning more than 30 degrees. Each side follows the ring between corners with every source vertex on it inserted; opposite sides and identical shared sides get one station count, at least ceil(length / spacing) and never fewer than their segments. Spacing is QuadRegion::spacing or defaultSize (directional spacing by side alignment), scaled down to limits.maximumSize over the ring's bounding box. A candidate is refused when excluded, outside the domain, inside a hole, fixed patch or triangles-only region, crossed or entered by source geometry, duplicating another boundary, or failing assessPlannedPatch(); repairable failures double the counts of its sides for up to maximumRepairRounds rounds. Required regions are processed first; finally a patch whose boundary vertex lies inside another patch's boundary edge is refused, the later one.

Returns
Owned plan. A refused optional region keeps PatchDisposition::Triangles with its reason. A refused required region, invalid settings or input, cancellation or an exhausted work, source-index, station or subdivision budget give ok false with error set and no patches. Callbacks run synchronously on the calling thread.

◆ pointInRegion()

bool mesh::pointInRegion ( const QPolygonF & ring,
const QVector< QPolygonF > & holes,
const QPointF & p )

Combine outer-ring parity with exclusion by every supplied hole-ring parity.

Parameters
[in]ringBorrowed finite planar outer ring, unchanged.
[in]holesBorrowed finite hole rings in the same frame, unchanged; no containment/disjointness validation.
[in]pBorrowed finite point, unchanged.
Returns
True when pointInRing(outer,p) and no pointInRing(hole,p), false otherwise. Exact edge behavior inherits strict crossing semantics, not a uniform distance-inclusive boundary rule. No allocation, geometry repair, source mutation or engine state lookup.

Inside ring and outside every ring of holes — the region's meshable interior. With no holes this is exactly pointInRing().

◆ pointInRing()

bool mesh::pointInRing ( const QPolygonF & ring,
const QPointF & p )

Test a point using a strict horizontal-ray odd-even crossing rule.

Parameters
[in]ringBorrowed finite planar ring, unchanged; scale-fuzzy closing duplicate ignored.
[in]pBorrowed finite query in the same planar units, unchanged.
Returns
Crossing parity, false for fewer than three open entries. Boundary classification follows strict crossings and is not uniformly inclusive; use the separate boundary helper where needed. No topology/finite validation, coordinate conversion, allocation or source mutation.

Odd-even point-in-polygon (closed ring, last == first optional).

◆ polylineIntersectsRect()

bool mesh::polylineIntersectsRect ( const QVector< QPointF > & path,
const QRectF & rect )

Test whether any consecutive path segment meets a normalized closed rectangle.

Parameters
[in]pathBorrowed finite planar coordinates, unchanged; at least two points required, zero-length segments still test as points. Parameter-interval arithmetic must remain representable.
[in]rectBorrowed finite rectangle in the same planar units, unchanged; normalized internally, zero-width/height normalized boxes return false.
Returns
True for any slab-clipped interval with enter<=leave, including boundary/axis-aligned contact, false otherwise. No spatial tolerance, allocation, geometry mutation or CRS conversion.

True when any segment of a finite-coordinate polyline intersects the closed rectangle, including boundary contact and axis-aligned paths. Fewer than two points or an empty rectangle returns false.

◆ quadAcceptable()

bool mesh::quadAcceptable ( const QuadQuality & q,
const QuadQualityBounds & b )
inline

Apply inclusive hard angle/Jacobian/aspect limits to a valid convex metric record.

Parameters
[in]qStable metrics with positive finite area and valid ranges, otherwise rejected.
[in]bFinite thresholds, angles degrees, minimum Jacobian and maximum aspect dimensionless; maxAspect<=0 disables aspect cap. Caller chooses meaningful angle/score limits; no automatic clamping.
Returns
False on invalid metric/nonfinite bound or minAngle below floor/maxAngle above ceiling/ Jacobian below floor/active aspect above cap; true otherwise, equality allowed. No metadata mutation, geometric repair, allocation or ownership transfer.

Hard acceptance test (finite valid geometry + convexity + unchanged angle bounds, SJ floor and aspect cap).

Here is the call graph for this function:
Here is the caller graph for this function:

◆ quadBlockGridFromField()

QuadBlockGrid mesh::quadBlockGridFromField ( const QRectF & r,
double pitch,
const std::function< double(const QRectF &)> & f,
const QVector< QVector< QPointF > > & b,
const std::function< bool()> & cancel,
qint64 cap )

Build a block grid from a size field over a rectangle, before any triangulation (Qt adapter over meshkit::plan::quadBlockGridFromField).

Parameters
[in]rArea to cover, mesh XY units; must have positive width and height. The grid starts at its top-left (minimum x, minimum y) corner with ceil(width / pitch) × ceil(height / pitch) cells.
[in]pitchCell side in mesh XY units; must be finite and > 0.
[in]fSize bound for one cell's box, called synchronously once per cell; a cell's h is 0.9 × the result when that is finite, > 0 and fits a float, else the cell is unusable (NaN). Must be non-empty: this adapter always wraps it, so an empty f throws std::bad_function_call instead of returning an invalid grid.
[in]bFeature polylines in the same units, sampled every half pitch; each sample marks its cell and the 8 neighbours unusable (repeat the first point to close a ring).
[in]cancelOptional; polled every 4096 cells or blocker samples.
[in]capUpper bound on cols × rows; must be >= 1.
Returns
The grid, or an invalid default grid on an invalid rectangle or pitch, cap < 1, too many cells or samples, a non-finite blocker coordinate or cancellation.

◆ quadBlockGridFromMesh()

QuadBlockGrid mesh::quadBlockGridFromMesh ( const MeshResult & mesh,
double pitch,
const QVector< QVector< QPointF > > & blockers )

Estimate local equilateral side lengths from triangles and mask existing quads/features.

Parameters
[in]meshBorrowed stable finite valid triangle/quad geometry, unchanged. Every cell vertex ID must be in range; area/centroid/products and grid coordinate-to-int conversions must be representable.
[in]pitchFinite positive background cell side in planar mesh units, feasible integer dimensions; nonpositive/NaN or no vertices returns invalid grid, but infinite pitch is caller-invalid, not rejected.
[in]blockersBorrowed finite feature paths in the same CRS/units, unchanged. Only consecutive segments are sampled, so repeat first point to close rings. Sample-step counts must fit int.
Returns
Owned row-major grid with unweighted mean triangle equivalent side sqrt(area/(sqrt(3)/4)) in planar units, NaN for blocked/no-sample cells. Triangle contributions use containing centers plus centroid bin, not area-weighted raster coverage. Existing quad bounding-box bins are blocked; feature samples at half-pitch steps mask their bins and 3x3 neighbors. Returns invalid if computed grid exceeds 64 million cells, after integer conversions; this is a cell-count cap, not a total memory-byte ceiling. Allocates sums/counts/masks/output, no source mutation, CRS conversion or engine interaction.

The local cell size of mesh on a grid of pitch, with every cell touched by blockers (domain and hole rings, constraint lines, break lines) or by an existing quad marked unusable.

◆ quadQuality() [1/2]

QuadQuality mesh::quadQuality ( const QPointF & a,
const QPointF & b,
const QPointF & c,
const QPointF & d )
inline

Measure one quadrilateral using cyclic corners and translation/scale-resistant planar arithmetic.

Parameters
[in]aFirst finite planar corner, used as local origin; same coordinate units as other corners.
[in]bSecond cyclic corner, preserved.
[in]cThird cyclic corner, preserved.
[in]dFourth cyclic corner, preserved; winding may be clockwise or counterclockwise.
Returns
Owned metrics: angles degrees, area squared coordinate units, other scores/ratios dimensionless. Invalid/nonfinite/zero-length or unrepresentable geometry returns default nonconvex metrics; concave or crossed finite geometry can return computed metrics with convex false. No index checks, allocations, coordinate mutation or physical simulation; valid opposite winding shares unsigned quality values.

Metrics for corners a,b,c,d in cyclic order. Coordinates and all metric values, including positive area, must remain representable. Invalid inputs return a non-convex result; CW and CCW valid quads share metrics.

Here is the caller graph for this function:

◆ quadQuality() [2/2]

QuadQuality mesh::quadQuality ( const QVector< MeshVertex > & vertices,
const MeshTriangle & t )
inline

Measure a quad cell through its borrowed vertex records.

Parameters
[in]verticesStable storage containing every t index in range, planar coordinates in common units.
[in]tQuad with four valid indices and v3>=0; triangle or invalid index use is unchecked.
Returns
quadQuality of its four cyclic xy positions, angles degrees/area squared units, invalid geometry nonconvex; z/material metadata ignored. No allocation, ownership retention or mesh mutation.

Metrics for a quad cell of mesh (t.v3 >= 0 required).

Here is the call graph for this function:

◆ quadRegionQualityBounds()

QuadQualityBounds mesh::quadRegionQualityBounds ( const QuadRegion & region,
QuadQualityBounds global )
inline

Copy global quality bounds and apply an explicitly nonnegative region aspect override.

Parameters
[in]regionBorrowed region policy, unchanged; aspectMax<0 inherits, zero disables aspect cap, positive values override. NaN compares false/inherits; infinity is copied and later finite checks reject it.
[in]globalBounds copied by value, only maxAspect can change.
Returns
Owned resulting bounds; no numeric validation, normalization, geometry access, state mutation or ownership retention. validateQuadRegion() performs the authoring range checks separately.

Resolve Free-region bounds. Only the aspect cap may override the global bounds; negative values inherit and zero explicitly disables it.

◆ quadScore()

double mesh::quadScore ( const QuadQuality & q,
const QuadQualityBounds & b )
inline

Rank valid convex quads by Jacobian, rectangularity and a soft aspect penalty.

Parameters
[in]qStable metrics, invalid ranges/nonconvex/nonfinite geometry scores zero.
[in]bFinite bounds; only positive maxAspect affects score, other finite hard thresholds are not applied here. Nonpositive maxAspect disables penalty.
Returns
Dimensionless clamped[0,1] product Jacobian*rectangularity*min(1,maxAspect/aspect) for active aspect cap, zero for invalid metrics/bounds. A positive score does not imply quadAcceptable. Read only, no allocation or smoothing/topology mutation.

Pairing / legacy tri-pair ranking in [0,1]: SJ · rectangularity · min(1, aspectMax/aspect). Perfect rectangles within the configured aspect cap tie squares; angle distortion penalizes rhombi and kites. Diagonal skew remains a diagnostic, not a ranking term. Invalid/non-convex quads score zero. Smoothing retains its separate SJ guard.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ reorderMeshHilbert()

void mesh::reorderMeshHilbert ( MeshResult * m)

Spatially permute cells within triangle/quad classes and renumber vertices by first use.

Parameters
[in,out]mOptional borrowed mesh, null or empty cells/vertices is a no-op. Requires every cell and boundary-edge vertex ID in range, finite representable geometry, and sizes fitting int.
Note
Uses 16-bit centroid Hilbert keys, stable-sorts ties, keeps triangles before quads and appends unused vertices in their original order. Moves complete vertex/cell records, remaps boundary endpoints and valid cellCouplings indices, preserving associated record attributes. Invalid coupling indices are retained. Other index-keyed metadata, including infiltration overrides and authoring-preview arrays, is not remapped: call before populating those or remap externally. Allocates temporary vectors, invalidates prior positional references/indices and offers no error result or failure rollback. No engine synchronization, file write or mesh ownership transfer; caller needs exclusive access.

Renumber triangles along a Hilbert curve of their centroids and vertices by first appearance; remaps triangle/boundary-edge/cell-coupling indices. No-op on an empty mesh.

Here is the call graph for this function:

◆ reorderTrianglesFirst()

QVector< int > mesh::reorderTrianglesFirst ( MeshResult & mesh)

Stable-partition cell rows into triangles followed by quads and remap selected cell metadata.

Parameters
[in,out]meshBorrowed exclusively mutable mesh. Copies complete cell records, preserves order within each class, replaces cell storage; vertex geometry and boundary edges remain unchanged.
Returns
Owned old-to-new map for every prior cell. Valid-range coupling indices/infiltration override keys are rewritten, invalid keys retained, and other index-keyed preview arrays are not remapped. Allocates replacement cells/map/hash, invalidates cell-array views, retains no external ownership; no engine/file update, geometry validation or cancellation.

Reorder cells triangles-first, stable within each class. Returns the old→new cell index map. Shared with meshquadmatch.

Here is the caller graph for this function:

◆ resampleRing()

QPolygonF mesh::resampleRing ( const QPolygonF & ring,
double h,
double keepTurnDeg = 0.0 )

Normalize a ring and insert equal-part subdivisions along all implicit closing edges.

Parameters
[in]ringBorrowed finite planar ring, unchanged; fuzzy duplicates are removed and winding normalized.
[in]hFinite positive target spacing in planar units; nonpositive/NaN returns normalized ring. For active resampling every lround(edgeLength/h), int narrowing and output count must be representable.
[in]keepTurnDegRetained compatibility parameter in degrees, currently ignored; every normalized original vertex survives regardless of turn.
Returns
Owned CCW/open ring, unchanged normalized input for <3 corners or disabled h. Parts use max(1,round(length/h)), so resulting edges are not guaranteed <=h. No simplification beyond normalization, quality/topology validation, coordinate conversion or source mutation; allocates output storage.

Resample a closed ring at spacing h: every edge is split into max(1, round(len/h)) equal parts; ring vertices whose |turn| >= keepTurnDeg are always kept, others are kept too (geometry is never simplified here — run pslg::simplifyPolyline first). Output is CCW, open (no closing duplicate).

◆ resolutionRemovalImportance()

double meshkit::resolutionRemovalImportance ( double flatness,
double actualSize,
double targetSize )
inline

Rank a vertex for resolution-aware coarsening; lower values are tried first.

Parameters
[in]flatnessStar flatness: the smallest cosine between a facet normal and the star's summed normal, clamped to [-1, 1]; 1 is flat.
[in]actualSizeCurrent local cell size in XY units; positive and finite.
[in]targetSizePrescribed target size in the same units; positive and finite.
Returns
sqrt(2 * (1 - flatness)) * actualSize / targetSize, dimensionless and >= 0; +infinity when flatness is nonfinite or a size is not positive and finite.

◆ resolveInfil()

ResolvedInfil mesh::resolveInfil ( const MeshResult & mesh,
int tri )

Resolve an owned infiltration specification while preserving its authoring provenance.

Engine D-I3 precedence: ‘override > tag row > ’*' row > none`.

Parameters
[in]meshBorrowed stable cell/default/override arrays, unchanged.
[in]triZero-based cell index, bounds checked before looking for an override.
Returns
Owned row with Override then first matching nonempty cell-tag default then first wildcard precedence, or default None/no provenance for invalid indices or no matching row. An explicit None stops inheritance and retains its source provenance. Parameters remain in project units, sourceTag is populated only for tag/wildcard rows. No physical validation, override materialization, unit conversion or engine mutation; borrowed references are not retained.

Resolve one triangle's infiltration per engine D-I3 precedence: ‘override > tag row > ’*' row > none`.

Reads MeshResult::infilOverrides, MeshResult::infilDefaults and the triangle's MeshTriangle::tag. Never mutates the mesh.

Provenance names the row's SOURCE, not whether a model ends up running: a tag row (or an override) spelling NONE still resolves to Tag / Override with an isNone() row. That distinction is load-bearing twice over — MeshSetTriangleInfilCommand::undo() uses it to decide between restoring a per-cell row and erasing the override back to inheritance, and the attribute table uses it to render a region-supplied "None" in the muted/italic inherited style rather than as a per-cell decision. The engine's own Infil2D::prov_ collapses those cases to NONE because it is solver-facing and only cares whether a kernel runs.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ ringIsSimple()

bool mesh::ringIsSimple ( const QPolygonF & ring)

Reject proper nonadjacent edge crossings using plain double orientation signs.

Parameters
[in]ringBorrowed finite planar sequence, unchanged; fuzzy closing duplicate ignored.
Returns
False for fewer than three open entries or a proper crossing, true otherwise. Endpoint touches, collinear overlaps, repeated nonconsecutive coordinates and zero-area degeneracy are not rejected; this is a limited crossing test, not a complete simple-polygon certificate. Quadratic read-only scan, no exact adaptive predicates, allocation or source mutation.

True when ring is simple (no proper self-intersection). O(n²).

◆ ringSignedArea()

double mesh::ringSignedArea ( const QPolygonF & ring)

Compute oriented shoelace area after translating corners to the first vertex.

Parameters
[in]ringBorrowed finite planar sequence, unchanged; closes implicitly, explicit duplicate allowed.
Returns
Signed squared coordinate units, positive CCW/negative CW, zero for fewer than three points. Translation reduces absolute-origin cancellation but does not validate representable products, polygon simplicity or nonzero area; folded rings can cancel. No allocation or source mutation.

Signed shoelace area (CCW positive).

◆ ringTurnDeg()

double mesh::ringTurnDeg ( const QPolygonF & ring,
int i )

Compute a signed exterior turn at one ring corner using adjacent edge cross/dot products.

Parameters
[in]ringBorrowed finite planar sequence, unchanged; fuzzy closing duplicate excluded.
[in]iCorner index, wrapped cyclically including negative values; modulo/addition must fit int.
Returns
atan2(cross,dot) in degrees, positive CCW/negative CW, zero for fewer than three open entries. Zero-length/nonfinite edge arithmetic is not separately rejected, no allocation or geometry mutation.

Exterior turning angle (degrees, CCW positive) at ring vertex i.

◆ rt0CellDischarge()

bool mesh::rt0CellDischarge ( int cell,
int nv,
const float * flux,
const float * length,
const float * nx,
const float * ny,
double & qx,
double & qy )
inlinenoexcept

Reconstruct planar specific discharge by least-squares fitting outward edge-normal discharge.

Parameters
[in]cellNonnegative cell index with representable cell*4 addressing.
[in]nvReal edge count 3 or 4, excludes triangle padding.
[in]fluxRequired nonnull stable flat array of at least 4*(cell+1) floats, outward-positive m3/s.
[in]lengthRequired nonnull equally sized edge lengths in metres; <=1e-12 skips an edge.
[in]nxRequired nonnull equally sized outward unit-normal x components, dimensionless.
[in]nyRequired nonnull equally sized outward unit-normal y components, dimensionless.
[out]qxBorrowed x discharge output in m2/s, assigned only after determinant passes.
[out]qyBorrowed y discharge output in m2/s, assigned only after determinant passes; use distinct outputs.
Returns
False when abs(normal-matrix determinant)<1e-12 or nonfinite, outputs untouched; true after solve, without a final finite-output check. Nonfinite flux/length ratios skipped, finite ratios clamped +/-10 m2/s; caller must provide meaningful normals. No array ownership retained, allocation or mutation, safe concurrent reads with stable inputs and disjoint outputs, noexcept.

RT0 least-squares specific discharge (m²/s) of one cell from its outward-positive normal edge fluxes (m³/s).

The engine's own reconstruction (SurfaceFluxCalculator::computeFaceVelocity): with nv outward unit normals n_e and normal speeds q_e = flux_e/length_e, solve the nv×2 least-squares system N·q ≈ b via the normal equations (NᵀN) q = Nᵀ b. |q_e| is clamped to 10 against wet/dry-front spikes and a non-finite q_e is skipped so it cannot poison the 2×2 solve. Divide by the cell depth for velocity. The per-edge arrays are the flat edgeSlot layout (cell's slots are read, nothing else).

Here is the call graph for this function:
Here is the caller graph for this function:

◆ saveLookupTableCsv()

bool mesh::saveLookupTableCsv ( const InfilLookupTable & table,
const QString & path,
QString * err )

Serialize classified infiltration entries and optional fallback to a QSaveFile CSV replacement.

Parameters
[in]tableBorrowed table, unchanged; names/keys/metadata must not contain commas/newlines that need CSV quoting, because this simple format performs no escaping. Parameters retain project units.
[in]pathBorrowed output pathname, parent directory must already be writable; unchanged.
[out]errOptional borrowed error string, overwritten on open/commit failure and left untouched on success. No source pointer retained.
Returns
True when commit succeeds, false on open/commit failure. Writes UTF-8, 12-significant-digit numeric fields and '-' for NaN, with all five slots retained even if unused. Non-None fallback writes as a * row; None fallback is omitted. No independent write-count/stream-status validation or physical parameter validation is performed. Existing destination replacement follows QSaveFile semantics.

CSV round-trip. Column order: key1[,key2],method,p0,p1,p2,p3,p4,dest, # comments, header row optional.

Here is the call graph for this function:

◆ simplifyConstraints()

ConstraintSimplificationResult mesh::simplifyConstraints ( const QVector< SimplificationFeature > & features,
const ConstraintSimplificationOptions & options = {} )

Remove redundant vertices from a collection of constraint features without moving any coordinate.

Every feature is validated first: its policy, its z count, equal elevations on a repeated closing vertex, finite coordinates and a total vertex count below INT_MAX - 3; then the protected points. When no feature is in Mode::Simplify with more than two vertices the input is returned unchanged with ok true. Otherwise the kept anchors are split recursively until every shortcut passes the XY/Z deviation, monotone-projection, crossing, junction, clearance and pocket checks against the original graph and protected points. Rings are then checked against their area limits and a final index checks the output shortcuts against each other.

Parameters
[in]featuresSource features in one planar frame; read only, copied into the result.
[in]optionsProtected points, cancellation and resource limits; the callback runs synchronously on the calling thread.
Returns
Owned result. ok is false with error set for invalid input or a shared graph that retraces a segment or has inconsistent shared chains or heights; cancellation sets cancelled. Exhausted work or workspace limits keep ok true and return the originals with every change marked budgetRetained.

◆ slotCell()

int mesh::slotCell ( int slot)
constexprnoexcept

Decode the owning cell index from a stride-four flat edge slot.

Parameters
[in]slotNonnegative flat slot in the relevant array range, unchecked.
Returns
slot/4 with integer division, no array lookup or validation; noexcept read-only arithmetic.

Cell / local edge of a flat slot.

Here is the caller graph for this function:

◆ slotLocal()

int mesh::slotLocal ( int slot)
constexprnoexcept

Decode local edge position from a stride-four flat slot.

Parameters
[in]slotNonnegative valid flat slot, unchecked.
Returns
slot%4 in[0,3]; triangle padding remains 3, not converted to an invalid edge sentinel. No geometry access or state mutation.
Here is the caller graph for this function:

◆ starDefault()

InfilRow mesh::starDefault ( const MeshResult & mesh)

Copy the first wildcard infiltration default, if present.

Parameters
[in]meshBorrowed stable defaults array, unchanged.
Returns
Owned first row whose case-sensitive tag is *, or a default None row when absent. Does not validate method/parameters or distinguish absent wildcard from an explicit None wildcard. Linear search, no mesh mutation or unit conversion.

Convenience: the '*' row from mesh, or a None row when absent.

Here is the call graph for this function:

◆ triangleArea()

double mesh::triangleArea ( const MeshResult & mesh,
int tri )
nodiscard

Measure positive fan area for a triangle or quadrilateral cell.

Parameters
[in]meshBorrowed stable geometry in consistent planar units, unchanged; valid cells should be finite and nonfolded. Index validation is performed but physical geometry is not repaired.
[in]triZero-based cell index, including quadrilateral rows despite the historical function name.
Returns
Area in squared project-CRS units, zero for an invalid cell index or any invalid vertex ID. Uses cellGeom()'s elevation-selected quad fan, so folded cells can produce misleading positive area and nonfinite coordinates can propagate. Constant work, no allocation or mesh mutation.

Unsigned area of triangle tri (|cross| / 2), in project CRS units². Returns 0 for an out-of-range triangle or one referencing out-of-range vertices.

The single definition of "cell area" in the GUI: the Metadata tab's statistics below and the Attribute Table's Cells column both read it, so a sliver hunted down by sorting the table is the same cell the min/max summary is reporting.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ triangleScaledJacobian()

double mesh::triangleScaledJacobian ( const QPointF & a,
const QPointF & b,
const QPointF & c )
inline

Compute the minimum orientation-normalized corner sine of a triangle.

Parameters
[in]aFirst planar vertex, finite coordinates and representable differences/products required.
[in]bSecond vertex in same coordinate units.
[in]cThird vertex in same coordinate units, winding may be either direction.
Returns
Dimensionless minimum corner sine capped above at 1, equilateral sqrt(3)/2, zero on a detected zero-length edge. Collinear geometry ordinarily yields zero; no finite-input/overflow validation, so callers must not use this as a general invalid-coordinate classifier. No mutation or allocation.

Minimum sine of a triangle's angles (1 is unattainable; equilateral = 0.866; right isosceles = 0.707). Used by the smoothing guard for the triangles that remain inside a quad region.

◆ unionQuad()

bool mesh::unionQuad ( const QVector< MeshVertex > & vertices,
const MeshTriangle & t1,
const MeshTriangle & t2,
MeshTriangle & quad )

Form and convexity-check a CCW quadrilateral candidate from two triangle records.

Parameters
[in]verticesBorrowed stable finite planar vertices, unchanged; relevant IDs are bounds checked, representable area/turn arithmetic is caller's responsibility.
[in]t1Borrowed first true triangle with valid distinct vertex IDs, unchanged; supplies tag, roughness and initial-depth attributes without testing equality to t2.
[in]t2Borrowed second true triangle sharing exactly two identifiers, unchanged.
[out]quadBorrowed output, untouched for early type/shared-ID/bounds refusal, but overwritten with a default-plus-t1-attributes candidate before convexity testing; final false can leave this candidate. Caller should not alias output with inputs if input preservation is required.
Returns
True only for a convex constructed quad (opposite winding reversed to CCW), false otherwise. No numeric quality-bound test, global topology certification, allocation, source mesh/engine mutation or pointer retention; caller discards output when false.

The CCW quad formed by two triangles sharing edge (p,q): returns false when they do not share exactly two vertices or the union is not a simple quad. quad receives v0..v3 (tag etc. copied from t1).

Here is the call graph for this function:
Here is the caller graph for this function:

◆ unitsHeaderIsSI()

bool mesh::unitsHeaderIsSI ( const QString & unitsHeader)
nodiscard

Recognize the retained metric-mesh header vocabulary without converting geometry.

Parameters
[in]unitsHeaderBorrowed header value, trimmed and compared case-insensitively, unchanged.
Returns
True only for SI (m), m, metre, metres, meter or meters; false for empty/unknown/imperial text. Internal whitespace/spelling is not normalized. This flag alone does not prove engine scaling: callers also consider FLOW_UNITS and lifecycle. No engine query, IO, coordinate conversion or state mutation.

True when unitsHeader (the verbatim ;; UNITS: value) declares a metric mesh, i.e. one the engine will NOT rescale.

Mirrors the engine's prescan2DUnitsHeader keyword set exactly — "SI (m)", "m", "metre(s)", "meter(s)", case-insensitive. Anything else, including an absent or explicitly imperial header, is not metric. Callers that need to know whether the engine converted the mesh to SI (issue #155) must apply this together with FLOW_UNITS: the engine scales only when FLOW_UNITS is US-customary AND this returns false.

◆ validate() [1/3]

QString mesh::validate ( const PatchMesh & pm)

Requires finite convex CCW quads, consistently shared cell edges, and one simple boundary matching exactly the outer cell edges.

Boundary crossings, remote touches, holes and disconnected pieces are rejected; an indexed boundary check avoids comparing every cell pair. Empty string = valid.

◆ validate() [2/3]

QString mesh::validate ( const StructuredPatch & p)

Input checks.

Empty string = valid.

◆ validate() [3/3]

QString mesh::validate ( const SweptPatch & p)

Check a swept patch's inputs and its representable station, cell and boundary counts.

Parameters
[in]pPatch to check, unchanged: >= 2 finite centreline points with no repeated consecutive point, finite width > 0, across >= 1 and finite along >= 0, in one XY unit.
Returns
Empty string when valid, otherwise the first diagnostic. Offset folding and global self-overlap are not checked here; makeSweptPatch() detects them after generation.

◆ validateQuadRegion()

QString mesh::validateQuadRegion ( const QuadRegion & r,
const QVector< QPolygonF > & domains,
const QVector< QPolygonF > & holes )

Check region authoring policy, normalized ring and sampled domain/hole containment.

Parameters
[in]rBorrowed region, unchanged. Finite aspect override must be negative/inherit, zero/unbounded or >=1. Directional spacing requires finite positive along/across lengths and finite angle, Auto/Mapped mode, no background flag or owned holes; isotropic spacing is used only when >0 without an explicit finite check.
[in]domainsBorrowed finite planar domain rings, unchanged; empty skips domain tests, background regions also skip them. Every normalized vertex plus area centroid must lie in exactly one same domain, with scale-fuzzy boundary counting inside.
[in]holesBorrowed finite excluded rings in the same units, unchanged. A vertex/centroid strictly inside a hole rejects, fuzzy boundary contact is allowed. r.holes is not otherwise geometrically validated here.
Returns
Owned first English error, empty when these checks pass. Requires >=3 normalized vertices, finite coordinates, no proper self-crossing and positive area; spacing requests require >=four target cells' area (directional includes roundoff allowance). Probe-only containment does not certify every edge or full polygon lies inside domain/outside holes, nor classify Auto into a guaranteed supported mesher. Allocates normalized ring/probes/diagnostics, no source mutation, engine validation or error rollback.

Validate one region: >= 3 distinct vertices, simple, area >= 4·h² (h = spacing when > 0, else skipped), every vertex inside exactly one of domains and outside every holes ring. Empty string = valid.

◆ validateQuadRegionsDisjoint()

QString mesh::validateQuadRegionsDisjoint ( const QVector< QuadRegion > & regions)

Check explicit region pairs for proper crossings or strictly interior sampled vertices.

Parameters
[in]regionsBorrowed finite region rings, unchanged; normalized to open CCW copies. Call individual validation separately; degenerate <3-corner rings are ignored by overlap testing.
Returns
First English region i overlaps region j using zero-based indices, or empty. Any pair containing a background region is skipped because explicit regions may be subtracted from backgrounds. Shared edges/ vertices are allowed under scale-fuzzy boundary tests. Identical coincident rings can pass because no proper crossing/strictly interior vertex exists, so this is not a full polygon-intersection-area proof. Quadratic pair/edge work with temporary rings, no input mutation, engine query or retained references.

Pairwise check: rings may share edges/vertices but no ring vertex of one may lie strictly inside another and edges may not properly cross. Returns the first offending pair as "region i overlaps region j", or "".

Variable Documentation

◆ kEdgeStride

int mesh::kEdgeStride = 4
constexpr

Edge slots per cell in every flat per-edge array (== engine kMaxCellVerts).

◆ kInfilMaxParams

int mesh::kInfilMaxParams = 5
inlineconstexpr

Widest positional parameter count (Horton: f0 fmin decay dry_time Fmax).