18.2 Overview of the redesign

This section describes the ongoing redesign of NekMesh relative to the master branch. It is intended as an orientation guide for developers who know the old code base and need to understand what has moved, what has been ported, and what is temporarily disabled. The subsequent sections of this document describe the design as it now stands.

18.2.1 Motivation

Historically NekMesh maintained its own mesh data structures (Node, Edge, Face, Element, Composite) which duplicated, but were not interoperable with, the SpatialDomains geometry objects (PointGeom, SegGeom, TriGeom/QuadGeom, TetGeom, PrismGeom, …) used by the solvers. Every NekMesh run therefore ended in a translation step: the NekMesh representation was converted into geometry objects (or serialised to XML) before it could be used. This had three consequences:

  1. Duplication. Connectivity, curvature and high-order node handling were implemented twice, in two conventions that had to be kept in sync.

  2. Cost. Large industrial meshes were held twice in memory, and the conversion between representations dominated the runtime of several modules.

  3. No pipelining. Because NekMesh objects were not geometry objects, a mesh could not be handed straight to a solver, nor could a solver-side MeshGraph be fed back into a process module.

The redesign removes the duplication by making SpatialDomains the single mesh representation: NekMesh now operates directly on a MeshGraph. This enables an in-memory, MPI-parallel meshing pipeline (mesh → process → solve) without file round-trips.

18.2.2 Summary of the data structure changes

Table 18.1 maps each of the old NekMesh structures onto its replacement. The rest of this section explains each entry in turn.





Was

Is now

Note




NodeSharedPtr

SpatialDomains::PointGeom*

owned by the graph, passed by raw pointer

EdgeSharedPtr

SpatialDomains::SegGeom*

Edge.cpp/.h out of the build

FaceSharedPtr

SpatialDomains::Geometry2D*

Face.cpp/.h out of the build

Element (owns nodes)

Geometry/Geometry2D/Geometry3D

Element is now only a shape-level builder

Mesh::m_node, m_vertexSet, m_numNodes

MeshGraph point-geometry map

GetGeomMap<PointGeom>()

Mesh::m_element (ElementMap)

MeshGraph per-shape geometry maps

GetGeomMap<T>(), keyed by global ID

Mesh::m_composite (CompositeMap)

Mesh::m_elementTags

array<unordered_map<Geometry*,int>,4>

Mesh::m_edgeSet, m_faceSet (EdgeSet/FaceSet of shared pointers)

EdgeMap, FaceMap (hash maps to SegGeom*/Geometry2D*)

same hashing, non-owning

Mesh::m_expDim, m_spaceDim

MeshGraph::GetMeshDimension(), GetSpaceDimension()

dimensions live with the graph

Mesh::m_cad

MeshGraph / SpatialDomains::CADSystem

see the CAD subsection below

(no equivalent)

SpatialDomains::EntityHolder

owns geometry not yet in the graph

(no equivalent)

ElmtIds

explicit, deterministic IDs on creation





Table 18.1 Correspondence between the old NekMesh mesh structures and the new SpatialDomains-based ones.

The changes fall into four groups, in decreasing order of impact on calling code:

  1. Representation. Nodes, edges, faces and elements are now geometry objects. Any code that dereferenced node->m_x or iterated el->GetVertexList() must be rewritten against the Geometry interface.

  2. Ownership. The MeshGraph owns every entity through unique_ptr_objpool; everybody else holds raw pointers. Shared-pointer reference counting no longer keeps entities alive, so lifetime is now explicit.

  3. Identity. Entities are addressed by global ID within the graph’s maps rather than by pointer identity within a set, and IDs can be pinned at creation.

  4. Grouping. Composites are replaced by a geometry-to-tag map, one per dimension.

18.2.3 The single data structure

The central change is in MeshElements/Mesh.h. The old Mesh class owned m_node, m_vertexSet, m_element, m_composite and friends. The new Mesh owns essentially one thing:

1class Mesh 
2{ 
3public: 
4    /// Mesh graph shared ptr storing the geometry info 
5    SpatialDomains::MeshGraphSharedPtr m_meshGraph; 
6    /// Array by dimension of maps of all elements and boundary 
7    /// surfaces to their tags. 
8    std::array<GeomTagMap, 4> m_elementTags; 
9    /// Map of element edges / faces. 
10    EdgeMap m_edgeSet; 
11    FaceMap m_faceSet; 
12    ... 
13    /// Information handed from one module to another. 
14    ModuleContext &GetContext(); 
15private: 
16    ModuleContext m_context; 
17};

Taking each member in turn:

ModuleContext — payloads between modules

NekMesh.cpp builds a pipeline of modules and runs them in sequence, and some of them need to hand something to a later one that is not mesh data: vertex normals read from a .ply file and consumed by the spherigon module, the octree built by loadoctree and used by surface meshing, the coarse elements ProcessBL keeps so that a boundary layer can later be regenerated. Historically each of these was a member of Mesh (m_vertexNormals, m_octree, m_macroElements, …), which put single-module concerns in the one class every module includes, and gave the payload no clear owner or lifetime.

ModuleContext (NekMesh/Module/ModuleContext.h), reached through Mesh::GetContext(), is a store keyed on the payload’s own type:

1// Producer, in the module that has the information: 
2m_mesh->GetContext().Get<VertexNormals>().normals[vert] = {nx, ny, nz}; 
3 
4// Consumer, in a module that may or may not be given it: 
5if (VertexNormals *vn = m_mesh->GetContext().TryGet<VertexNormals>()) 
6{ 
7    ... 
8}

Set<T> replaces a payload, Get<T> constructs one if absent or stale, TryGet<T> returns nullptr in that case instead, and Remove<T> drops one. The distinction matters to a consumer that must tell “nothing was supplied” from “something was supplied and is empty”, which a size() == 0 test cannot do. The key is std::type_index, so there are no string names to keep in sync and a typo is a compile error; entries are held as shared_ptr<void>, which (unlike unique_ptr<void> or std::any) retains the concrete deleter, so the payload type need only be complete where it is used.

The payload types themselves are small structs declared next to the context: VertexNormals and SpherigonSurfs (Module/SurfaceHints.h) and MacroElements (Module/MacroElements.h), the last of which wraps an EntityHolder — a plain owning container of unique pointers, one vector per geometry type, for entities that must stay alive while not part of the graph.

Staleness. A payload that refers to mesh entities is invalidated when those entities may have gone. Module::RemoveOrphanedEntities() calls ModuleContext::Invalidate(), which bumps a generation counter; TryGet<T> compares generations and reports a payload stored before the last invalidation as absent. This is deliberately coarse — “the mesh changed, discard” — because testing whether a particular entity survived would cost more than rebuilding the payload. Renumbering, by contrast, is deliberately not an invalidation: keying a payload on geometry pointers rather than on global IDs is precisely what lets it survive one.

Not every payload wants that, and the trait PayloadFollowsEntities<T> says so. It defaults to true_type, the safe answer, and is specialised for the octree:

1template <> struct PayloadFollowsEntities<Octree> : std::false_type {};

because the octree is built from the CAD, not from mesh entities, and would otherwise be thrown away the first time a module tidied up the graph — during mesh generation, before anything had used it. The check is an if constexpr in TryGet<T>, so an exempt payload costs nothing.

When to use it rather than SpatialDomains. The question to ask is whether the payload must react to the destruction of an individual entity. CAD associations must — a link from a geometry to the CAD curve it sits on has to disappear with that geometry — so they live in SpatialDomains as CADAssociation, whose Remove() is called from the geometry destructor. Everything for which the coarse “mesh changed” answer is enough belongs in the context, where it stays out of SpatialDomains and out of Mesh.

Element and the element factory

Element used to be the mesh element: it owned m_vertex, m_edge, m_face and m_volumeNodes, and held m_geom as a lazily-built by-product for output. That relationship is now inverted. The geometry object is the element, and Element is reduced to a shape-level helper that builds and queries it. Its remaining state is just m_id, m_dim, m_conf, m_tag, m_taglist, m_curveType, m_boundaryLinks and m_geom; the four node/edge/face containers and the m_edgeLink/m_faceLink boundary back-pointers are gone, the latter being expressed by the m_elementTags lookup instead.

The factory signature reflects the inversion. It used to construct an Element from nodes,

1// old 
2typedef LibUtilities::NekFactory<LibUtilities::ShapeType, Element, 
3    ElmtConfig, std::vector<NodeSharedPtr>, std::vector<int>> 
4    ElementFactory;

whereas it now produces a SpatialDomains::Geometry* directly:

1// new 
2typedef LibUtilities::NekFactoryBase< 
3    LibUtilities::ShapeType, SpatialDomains::Geometry, 
4    SpatialDomains::Geometry *, 
5    std::vector<SpatialDomains::PointGeom *> &, 
6    SpatialDomains::MeshGraphSharedPtr &, EdgeMap &, FaceMap &, 
7    ElmtConfig &, std::set<int> *, std::unordered_set<int> *, 
8    std::unordered_set<int> *, ElmtIds *> ElementFactory;

Reading the argument list left to right:

The convenience wrapper CreateElementLite() covers the common case — a linear element with automatic IDs and no filters:

1SpatialDomains::Geometry *CreateElementLite( 
2    LibUtilities::ShapeType type, 
3    std::vector<SpatialDomains::PointGeom *> &nodeList, 
4    SpatialDomains::MeshGraphSharedPtr &meshGraph, 
5    EdgeMap &edgeMap, FaceMap &faceMap);

Two free functions, GetCurvedNodesTri() and GetCurvedNodesQuad(), assemble the full high-order node list of a 2D entity from its vertices, edge curves and interior face nodes, in the NekMesh ordering of section 18.3.3.

High-order representation and MakeOrder

Order elevation has moved down into SpatialDomains. The new Geometry::MakeOrder(order, pType) returns the curve and the newly created interior points,

1std::pair<CurveUniquePtr, std::vector<PointGeomUniquePtr>> 
2    MakeOrder(int order, const LibUtilities::PointsType pType);

and is implemented per shape (SegGeom, TriGeom, QuadGeom, TetGeom, PrismGeom, HexGeom). Two properties are new: the implementation no longer requires a MeshGraph, and elevation proceeds bottom-up — edge curves are generated first, face curves are filled from the edge curves, and volume nodes last — so that shared entities are curved exactly once and consistently. Two supporting additions are Geometry::GetNumFacets() / GetFacet(i), which give dimension-generic access to a geometry’s sub-entities (vertices in 1D, edges in 2D, faces in 3D), and Geometry::ResetLite(), a cheap reset that invalidates a geometry without rebuilding its mapping data. Consistent v_Reset/FillGeom behaviour across all shapes is what allows a mesh to be handed on to a solver in-memory after a module has modified it.

18.2.4 Common operations: before and after

The tables below give the idiom for each of the operations that modules perform most often, as written on master and as written now. They are grouped by theme: traversal and access (table 18.2), creation, ownership and identity (table 18.3), and CAD, evaluation and pipeline (table 18.4). graph below abbreviates m_mesh->m_meshGraph.





Operation

Before

Now




Loop over all elements

for (auto &el : m_mesh->m_element[m_mesh->m_expDim])

for (auto &[id, geom] : graph->GetGeomMap<SD::TetGeom>()) — one loop per shape type present




Loop over boundary elements

for (auto &el : m_mesh->m_element[m_expDim - 1])

for (auto &[geom, tag] : m_mesh->m_elementTags[dim])




Loop over a composite

m_mesh->m_composite[id]->m_items

filter m_elementTags[dim] on tag, or graph->GetComposites()




Test boundary membership

element had a non-empty m_edgeLink/m_faceLink

m_mesh->IsBoundary(geom, dim) (equivalently a find() in m_elementTags[dim])




Mesh / space dimension

m_mesh->m_expDim, m_mesh->m_spaceDim

graph->GetMeshDimension(), graph->GetSpaceDimension()




Element vertices

el->GetVertexList() → vector<NodeSharedPtr>

geom->GetVertex(i) → PointGeom*, count from GetNumVerts()




Element edges / faces

el->GetEdgeList(), el->GetFaceList()

geom->GetEdge(i), geom->GetFace(i); generically GetNumFacets() / GetFacet(i)




Vertex coordinates

node->m_x, m_y, m_z

pt->GetCoords(x, y, z)




Find shared edge / face

m_mesh->m_edgeSet.find(edge) on an EdgeSharedPtr

m_mesh->m_edgeSet.find({vid0, vid1}) keyed on vertex IDs, returning SegGeom*




Neighbours of a face

face->m_elLink[j].first.lock()

graph->GetAllFaceToElMap() (populated via PopulateFaceToElMap())




Recover concrete shape

el->GetConf().m_e / GetShapeType(), element already typed

switch (geom->GetShapeType()) then static_cast<SD::TriGeom*>(geom)




Identify a shape

Same

LibUtilities::ShapeType (eTriangle, ePrism, …) is still the key everywhere




Describe an element’s order and curvature

Same

ElmtConfig: m_order, m_faceNodes, m_volumeNodes, m_edgeCurveType




Vertex node ordering

Same

the collapsed-point, prism and pyramid rules of section 18.3.2 are unchanged, as is the high-order ordering of section 18.3.3





Table 18.2 Traversal and access idioms. SD abbreviates SpatialDomains. Rows marked Same are unchanged from master and are listed because they remain in common use.





Operation

Before

Now




Create a vertex

make_shared<Node>(id,x,y,z) then m_node.push_back() and m_vertexSet.insert()

ObjPoolManager<SD::PointGeom>::AllocateUniquePtr(...) then graph->AddGeom<SD::PointGeom>(id, std::move(p))




Create an element

GetElementFactory().CreateInstance(elType, conf, nodeList, tags) → ElementSharedPtr

same factory, but → SD::Geometry*, taking graph, EdgeMap, FaceMap and ElmtIds*; CreateElementLite() for the linear case




Register an element

m_mesh->m_element[E->GetDim()].push_back(E)

done inside the factory, via graph->AddGeom<T>(); bulk insertion with BulkAddGeom<T>()




Remove an element

erase from m_element[dim]; the shared pointer freed it

graph->ExtractGeom<T>(id, /*erase*/ true), which returns ownership to the caller (often into an EntityHolder)




Keep an entity alive off-graph

reference counting did it implicitly

park it in an EntityHolder (e.g. GetContext().Get<MacroElements>().entities)




Entity ID

node->m_id, edge->m_id, el->GetId()

geom->GetGlobalID(), geom->SetGlobalID(id)




Choose IDs on creation

not possible; assigned on insertion

pass an ElmtIds{edges, faces, elmt}; nullptr for automatic




Renumber after edits

reassign m_id while re-walking the sets

consolidateIDs<T>(), which rebuilds the shape’s geom map and the matching curve map




Composite / tag of an entity

el->GetTagList() → vector<int>

m_mesh->m_elementTags[dim][geom] → int




Edge / face curvature

edge->m_edgeNodes, face->m_faceNodes, el->GetVolumeNodes()

graph->GetCurvedEdges()[id], GetCurvedFaces()[id], each a Curve with m_points; read back with geom->GetCurve()




Register a module

Same

GetModuleFactory().RegisterCreatorFunction(ModuleKey(eProcessModule, "name"), create, ...)




Declare and read options

Same

m_config["key"] = ConfigOption(...) in the constructor, then m_config["key"].as<T>() and .beenSet




Report to the user

Same

m_log(VERBOSE), m_log(WARNING), m_log(FATAL)




Assert

Same

ASSERTL0 / NEKERROR





Table 18.3 Creation, ownership and identity idioms. Rows marked Same are unchanged from master.





Operation

Before

Now




Reach the CAD model

m_mesh->m_cad

graph->GetCAD()




Fetch a CAD entity

m_mesh->m_cad->GetSurf(i), GetCurve(i), GetVert(i)

graph->GetCAD()->GetSurf(i), etc. — same interface, now in SpatialDomains




Project a point to a surface

Same

s->locuv(in, dist) then s->P(uv); the bounded overload locuv(loc, dist, umin, umax, vmin, vmax) is now also used, to restrict the search




Query a CAD entity

Same

N() (normal), D1()/D2() (derivatives), GetBounds(), IsPlanar()




Build geometry for evaluation

el->GetGeom(m_spaceDim, holder) — constructed on demand

the entity is the geometry; no conversion step




Geometric factors / Jacobian

Same

geom->GetXmap()->GetPointsKeys(), geom->GenGeomFactors(p), gfac->GetDeriv(p) — this path was already SpatialDomains




Integrate over an element

Same

geom->GetXmap()->Integral(jac), GetTotPoints()




Refresh after moving nodes

rebuild the element’s geometry

geom->FillGeom() and geom->Reset(), or ResetLite() when the mapping data need not be rebuilt




Elevate order

Mesh::MakeOrder() walking elements and requiring a MeshGraph

Geometry::MakeOrder(order, pType) per shape, bottom-up, with no MeshGraph dependency





Table 18.4 CAD, evaluation and pipeline idioms.

18.2.5 CAD association: where the links now live

A separate point, easily missed: geometry objects carry no CAD back-pointer. m_parentCAD is commented out in SegGeom, TriGeom and QuadGeom, and PointGeom has no equivalent of the old Node::SetCADSurf / GetCADSurfInfo. The association is instead held by the MeshGraph in a set of maps from mesh entity to CAD entity (SpatialDomains/MeshGraph.h):

Table 18.5 gives the translation used when porting CurveMesh, which is representative of the mesh generation modules generally.




Before

Now



node->SetCADCurve(c, t)

graph->SetVertToCADCurve(pt, {c, t})



node->SetCADSurf(s, uv)

graph->SetVertToCADSurf(pt, {s, {u,v}})



node->GetCADCurveInfo(id)

graph->GetVertToCADCurveT(pt, id)



node->GetCADSurfInfo(id)

graph->GetVertToCADSurfUV(pt, id)



edge->m_parentCAD = c

graph->SetEdgeToCADCurve(seg, c)



new Node(m_numNodes++, x, y, z)

ObjPoolManager<PointGeom>::AllocateUniquePtr(...) then graph->AddGeom<PointGeom>(id, std::move(pt))



new Edge(n1, n2) then m_edgeSet.insert(e)

CreateElementLite(eSegment, ns, graph, edgeSet, faceSet) — registers with the graph and the edge map in one step



m_edgeSet.erase(edge)

m_edgeSet.erase({vid0, vid1}) — keyed on vertex ids



node->GetLoc()

pt->GetCoords(x, y, z)



cadVert->GetNode()

no equivalent; see the note below




Table 18.5 CAD/mesh association commands. graph abbreviates m_mesh->m_meshGraph and pt a PointGeom*.

18.2.6 CAD moves into SpatialDomains

The whole CAD abstraction has been lifted out of library/NekMesh/CADSystem into library/SpatialDomains/CADSystem, so that geometry objects themselves — not just NekMesh — can carry a CAD association:

SpatialDomains/MeshGraph.h now includes CADSystem/CADSystem.h directly. The corresponding NekMesh sources are commented out of the NekMesh build, and NekMesh gains a dependency on SpatialDomains.

ProcessProjectCAD has been substantially rewritten on top of this (CAD reconstruction): it now keys its work off PointGeom* and Geometry3D* rather than nodes and elements, and separates the association stages into LinkVertexToCAD, LinkEdgeToCAD and LinkFaceToCAD, with boost::geometry R-trees for proximity search and a lockedNodes set recording vertices whose CAD projection failed (these are linearised rather than curved). HOSurfaceMesh has been reworked in step with it, for both quadrilateral and triangular face nodes.

18.2.7 Parallel modules

Because the mesh is now a MeshGraph, modules can be run under MPI on a partitioned mesh. Mesh::m_comm holds the communicator, and the ported modules test m_comm->GetSize() > 1 to switch on the parallel path, exchanging the entities they have modified across ranks (for example via GatherUnion of cleared edge/face IDs and AllReduce on the iteration termination flag in ProcessLinear). At present:

18.2.8 Module status

The port is incomplete by design: modules are being brought over to the new data structure one at a time, and those not yet converted are commented out of library/NekMesh/CMakeLists.txt rather than deleted. Table 18.6 summarises the state at the time of writing.





Kind

Ported

Not yet ported (disabled)




Input

InputGmsh, InputNekpp, InputStar, InputPly, InputSwan

InputNek, InputNek5000, InputSem, InputStarTec, InputMCF, InputVtk




Process

ProcessBL, ProcessLinear, ProcessProjectCAD, ProcessCombine, ProcessExtractSurf, ProcessExtrude, ProcessJac, ProcessScale, ProcessCheckConnectivity (new)

ProcessVarOpti, ProcessCurve, ProcessCurvedEdges, ProcessCyl, ProcessDetectSurf, ProcessPerAlign, ProcessSpherigon, ProcessTetSplit, ProcessInsertSurface, ProcessRevolve, ProcessLinkCheck, ProcessOptiExtract, ProcessScalar, ProcessExtractTetPrismInterface




Output

OutputNekpp (XML and parallel HDF5), OutputGmsh

OutputSTL, OutputVtk




Generation

—

Octree, SurfaceMesh/CurveMesh/FaceMesh, VolumeMesh/TetMesh/BLMesh, 2DGenerator, Triangle/TetGen interfaces





Table 18.6 Status of NekMesh modules under the new MeshGraph-based data structure. Disabled modules are commented out of the build, not removed.

ProcessCheckConnectivity is a new module which verifies the connectivity of all elements and reports orphaned geometry — a useful consistency check while modules are being ported.

18.2.9 Behavioural changes to be aware of coming from SpatialDomains