Nowadays large part of the time needed to perform a numerical simulation is spent in preprocessing, especially in the geometry cleaning operations and mesh generation. Furthermore, these operations are not easy to automatize because they depend strongly on each geometrical model and they often need human interaction. Many of these operations are needed to obtain a watertight geometry. Even with a clean geometry, classical unstructured meshing methods (like Delaunay or Advancing Front based ones) present critical weak points like the need of a given quality in the boundary mesh or a relatively smooth size transition. These aspects decrease their robustness and imply an extra effort in order to reach the final mesh. Octree based meshers try to relax some of these requirements.
In the present work an octree based mesher for unstructured tetrahedra is presented. The proposed mesher ensures the mesh generation avoiding most of the geometry cleaning operations. It is based in the following steps: fit an octree onto the model, refine it following given criteria, apply a tetrahedra pattern to the octree cells and adapt the tetrahedra close to the contours in order to represent accurately the boundary shape. An important and innovative aspect of the proposed algorithm is it ensures the final mesh preserves the topology and the geometric features of the original model.
The method uses a Ray Casting based algorithm for the identification of the inner and outer parts of the volumes involved in the model. This technique allows the mesh generation of volumes even with nonwatertight boundaries, and also opens the use of the mesher for immersed methods only applying slight modifications to the algorithm.
The main advantages of the presented mesher are: robustness, no need for watertight boundaries, independent on the contour mesh quality, preservation of geometrical features (corners and ridges), original geometric topology guaranteed, accurate representation of the contours, valid for immersed methods, and fast performance. A lot of time in the preprocessing part of the numerical simulation is saved thanks to the robustness of the mesher, which allows skipping most of the geometry cleaning operations.
A shared memory parallel implementation of the algorithm has been done. The effectiveness of the algorithm and its implementation has been verified by some validation examples.
En l'actualitat gran part del temps emprat per córrer una simulació numerica esta dedicat al preprocés, especialment a les operacions de neteja de geometria i generació de malla. A més, aquestes operacions no són facils d'automatitzar degut a la seva forta dependencia del model geometric i sovint necessiten d'interacció humana. Moltes d'aquestes operacions són necessaries per aconseguir una definició topologicament hermetica de la geometria. Inclús amb una geometria neta, els metodes classics de mallat (com els basats en Delaunay o avancament frontal) presenten punts febles crítics com la necessitat d'una certa qualitat de les malles de contorn o una transició de mides relativament suau. Aquests aspectes disminueixen la seva robustesa i impliquen un esforc extra a l'hora d'obtenir la malla final. Els metodes de mallat basats en estructures octree relaxen alguns d'aquests requeriments.
En aquest treball es presenta un mallador basat en octree per tetraedres no estructurats. Un dels aspectes claus d'aquest mallador és que garanteix la generació de malla evitant moltes de les operacions de neteja de geometria. Es basa en els següents passos: encaixar un octree al model, refinarlo seguint certs criteris, aplicar un patró de tetraedres a les celles de l'octree i adaptarlos a les zones properes als contorns a fi i efecte de representar acuradament la forma del domini. Un aspecte important i innovador de l'algorisme proposat és que manté la topologia del model a la malla final i preserva les seves característiques geometriques.
El metode presentat utilitza un algorisme basat en la tecnica Ray Casting per la identificació de les parts interiors i exteriors dels volums del model. Aquesta tecnica permet la generació de malla de volums inclús amb contorns que no tanquen hermeticament, i també obre l'ús del mallador a metodes immersed aplicant només petites modificacions a l'algorisme.
Els principals avantatges del mallador presentat són: robustesa, no necessitat de definicions hermetiques dels contorns, independent de la qualitat de la malla de contorn, preservació de característiques geometriques (cantonades i arestes abruptes), topologia original de la geometria garantida, representació precisa dels contorns, valid per metodes immersed i rapid rendiment. L'ús del mallador estalvia molt de temps en la part del preprocés de la simulació numerica gracies a la seva robustesa que permet obviar la majoria d'operacions de neteja de geometria.
S'ha dut a terme una implementació parallela amb memoria compartida de l'algorisme. L'efectivitat del mateix i la seva implementació ha estat verificada mitjancant exemples de validació.
Numerical simulations try to reproduce virtually a physical behavior by solving given equations in a specific domain. They are nowadays essential to understand some complex physical problems in scientific and engineering field. Although experimental setups can be build to study the specific behavior of a given phenomena, sometimes it is hard for these experiments (or even impossible depending on the scale of the tackled problem) to represent it accurately. The increasing advances in terms of computer science technology allow to treat larger and larger problems virtually (in the computer), so each time more and more numerical methods have been developed in the scientific field in order to capture the physics of complex problems.
Together with these developments, the adoption of numerical simulations in industrial processes has became a reality, as it can save a lot of time and effort when evaluating possible solutions for a given problem. The use of numerical simulation tools by the industry requires a software with very high level of robustness, efficiency and performance.
The process to run a numerical simulation involves three main parts: preprocessing, calculation and postprocessing. The preprocessing part includes all the operations needed to define and discretize the geometrical domain, assign the required data to it so that the solver can solve the corresponding equations representing a given physical problem (in the calculation part). The postprocessing part tries to analyze and visualize the results from the solver in a smart way so that they can be correctly interpreted. This monography is focused on the preprocessing part of the numerical simulations, and specifically on the discretization of the geometrical domain.
The preprocessing operations can be summarized as follows:
The presented work proposes a new algorithm for mesh generation: a mesh generator (or simply a mesher). For designing a mesh generator, the basic requirements to be covered must be very clear. Missing the right requirements for the numerical simulation may lead to several limitations in the use of the mesher. There are three basic requirements to be covered by any mesh generator:
Often, a mesh generator is focused in one type of mesh. Different kinds of meshes can be identified depending on their nature:
In this monography 3D unstructured isotropic conformal tetrahedral meshes are considered. Both embedded and bodyfitted cases will be covered.
In industrial simulations, the preprocessing operations represent the most time consuming part of the whole process. Among the preprocessing operations, the geometry cleaning and mesh generation parts are the ones which consume more time, due to their specific characteristics:
Figure 1: Example of a 3D input boundary (represented with a mesh) where the quality of the triangles is very bad. 
Much effort has to be spent in order to generate a volume mesh of a complex geometry considering the existing meshing algorithms. Some of them are really fast and robust, but they require several geometry cleaning operations. If the time needed for them is added to the total meshing time, they became not so fast in practice. Contribute to reduce this extra effort is the motivation of this monography.
The main objective of this monography is to develop an algorithm for isotropic unstructured volume mesh generation robust enough to be able to generate a mesh from noncleaned input geometries, using as less input data as possible. This will lead to a drastic reduction of the time consumed in the preprocessing part, and will overcome the actual bottleneck in the whole simulation process.
The mesh generator must be flexible enough in terms of mesh adaptation to the solver requirements considering specific input data. The idea in this work is that the algorithm should be able to generate always a mesh from a given geometrical domain, almost without any specific meshing property assigned to it.
The meshing algorithm presented in this monography has been designed with the following objectives in mind:
These characteristics lead to a set of requirements to be covered by the meshing algorithm developed in this monography. The main ones are: robust and fast mesh generation, and ability to mesh from nonwatertight geometries. The explanation of all the requirements covered by the new mesher is detailed below in Sections 1.2.1, 1.2.2, and 1.2.3.
In this section, the requirements of the mesher developed in the monography regarding its behavior are detailed:
This section focuses on the requirements to be covered by the mesher concerning the input data:
Figure 2: Example of a 2D non watertight input boundary with gaps and overlapping entities. 
Although the mesher should generate a mesh from a noncleaned input geometry, some minimum criteria concerning topology or shape definition may be needed.
While mesh entities are simpler to be defined, CAD entities are a more precise way of defining a geometry. Meshes often loose continuity in the geometrical definition depending on the smoothness or curvature of the shape to be represented. It also has to be considered that, almost always, the mesh presents a chordal error compared to the smooth original geometry (the chordal error is the distance between a point on the mesh and the original smooth shape the mesh is trying to represent). In the Figure 3 a graphical representation of this chordal error is shown.
The simpler definition and treatment of mesh entities has made them the most common used as input for the existing volume meshers. There are cases where a surface (or a line) cannot be meshed because of its bad parametrization. In these cases, a volume mesher requiring a mesh as input cannot be used. This is the reason why the proposed volume meshing algorithm should be prepared to get as input data mesh entities, as well as NURBS surfaces and curves. Actually, it should be prepared not only to get these kinds of entities as an input, but also to work with them in the geometrical operations needed during the whole meshing process. The methodology presented in this monography is prepared to work either with CAD and mesh entities. Hence, the general form of geometrical entities will be used to refer the input entities defining the contours of the domain. Only if some specific operation is needed for just one of the representations it will be specified if the geometrical entity is a CAD or a mesh one. Following this duality, in this document a single term will be used to refer the different natures of geometrical entities:
The requirements to be covered by the mesher regarding the final mesh generated are:
A special case which evidences the importance of maintaining the initial topology is the situation where the domain has very thin parts representing relevant details of it. A 2D case of this kind is shown in Figure 5, where a thin channellike part can be identified in a surface (Figure 5(a)). Independently on the mesh desired size required by the simulation, the mesher must generate elements small enough not to close this channellike zone, as the mesh shown in Figure 5(b). The mesh depicted in Figure 5(c) is not acceptable, as it does not preserve the topology of the domain.
 
Figure 5: Example of surface mesh preserving or not the topology of the initial domain. (a) 2D geometrical domain formed by two surfaces (colored as blue and gray). (b) Mesh of the surfaces preserving the topology of the initial domain. (c) Mesh of the surfaces not preserving the topology of the initial domain. 
Note that this requirement is not as hard as the typical constrained condition in the boundaries of the domain. Especially when the input data for a mesher is a surface mesh, it is common to require the mesher to be constrained at the boundary. This means that the contour mesh of the final tetrahedral mesh (the triangles representing the skin of the generated tetrahedra) must be topologically identical to the input surface mesh defining the contours of the domain.
 
Figure 6: (a) Contour mesh of a volume with a set of triangles highlighted in red representing the region . (b) A partially constrained tetrahedra mesh generated from the contour mesh shown in (a) where the highlighted set of tetrahedra faces corresponds to the region . (c) A not constrained tetrahedra mesh of the contour mesh shown in (a) (it cannot be identified a set of tetrahedra faces representing the region ). 
In Figure 6(a) an example of the contour of a volume is shown, where a set of surface entities (in this case triangles)are colored in red. Let us call the region represented by those triangles. If the simulation requires a set of triangles representing the region , the mesh generator should provide with a tetrahedral mesh whose skin should have a set of triangles representing that region, but it is not needed for those triangles to be identical as the ones in the input geometry. A tetrahedral mesh accomplishing this criterion is shown in Figure 6(b). A totally unconstrained mesh is depicted in Figure 6(c), where it cannot be identified a set of triangles corresponding to the region . It is obvious that the mesh in Figure 6(b) is not constrained with the input boundary shown in Figure 6(a), as the triangles representing the region are different. However, it can be seen that the requirement of maintaining a representative topology of the surface and line entities of the input data allows a bijective relationship between groups of surface and line entities in the input data and surface and line mesh elements in the final mesh. This requirement is enough to allow an automatic assignment of data from the input boundary geometry to the final mesh entities.
(a)  (b) 
Figure 7: (a) View of a part of the contours of a mechanical piece. (b) Tetrahedral mesh of the mechanical part generated without preserving the sharp edges of the input geometry. 
In terms of the mesher, this requirement means that it should be partially constrained to some line entities from the input geometrical data, and must include fixed nodes in the final mesh (corresponding to specific point entities in the input data). In this context, partially constrained means that if some specific line elements in the input geometrical data must be preserved, a collection of edges from the final mesh should follow the path of those line elements. This is not as restrictive as totally constrained condition.
As it will be explained later on (Section 3.1), the strategy to cover this requirement will be also useful to reach the requirement of maintaining a representative lines and surfaces topology.
(a)  (b) 
Figure 8: (a) Zoom of a patch of surfaces representing a mechanical part. (b) Triangle mesh of the patch of surfaces shown in (a). 
Even when the sizes of the input entities are related to the representative size of a specific shape to be represented, the user may desire a bigger mesh size to skip the representation of given details because they are not of interest for the simulation. Instead of forcing the user to modify the input geometry which defines the domain, this requirement makes the mesher skip the detail within the mesh generation process.
The accomplishment of this requirement will let the user to define a desired mesh size distribution in the final mesh just because of the simulation requirements, and not because of the initial way of defining the geometry. In terms of the mesher, this requirement means that it should be able to skip some of the line and point entities from the input geometrical definition of the domain. The entities to be skipped should be defined automatically following some given criterion, or by the user.
Although the main objectives of the monography are related to volume meshing, there is a secondary objective for the new mesher, which is to be able to mesh 3D surfaces and lines which are not boundary of any volume accomplishing the requirements defined above. This capability would give several advantages to the method:
Figure 9: 2D example of a surface mesh (gray lines) conformal with an inner line of the surface (dotted line). 
(a)  (b) 
Figure 10: (a) Example of a model containing two volumes (in blue) and a surface (in grey) connecting them. (b) A conformal mesh of the model considering the volumes and the surface mesh. 
The monography is structured in the following chapters:
It is highlighted that, although the meshing algorithms presented are directly applied to volume meshing, most of the geometrical operations are applicable (with slight modifications) to surface meshing in 2D cases. Taking into account that some concepts are much more clear to understand from a 2D scheme (especially when dealing with geometry), in this monography 2D examples are used sometimes to illustrate some of the concepts explained.
In this monography isotropic volume meshers are considered. Isotropic meshers can be defined as the ones trying to generate elements as much regular as possible, understanding a regular element as the one whose edges have the same length.
There are two main families of meshers depending on the kind of mesh they generate: structured and unstructured [10]. Actually, a third kind of meshers can be classified as semistructured ones. A structured mesh is defined as a mesh which all inner nodes have the same degree (the degree of a node is the number of elements owning it), while the nodes of an unstructured mesh have different degrees. Semistructured meshes can only be applied to topologically prismatic geometries, and they basically repeat the structure of an unstructured mesh (in the tops of the prismatic shape) in different layers following the structured direction. An example of this kinds of mesh is shown in Figure 11.
Unstructured meshers [11,5,12] can be divided in three main families: advancing front, Delaunay and space decomposition methods.
In the following sections, the main characteristics of these methods as well as their main advantages and drawbacks are detailed, focusing on the requirements defined in section 1.2. The aim of this chapter is to highlight which of those requirements are covered by each meshing method, so the algorithms are not deeply detailed and only their main characteristics are pointed out.
 
Figure 11: Examples of different types of mesh(a) Structured triangle mesh. (b) Unstructured triangle mesh. (b) Semistructured prism mesh. 
Structured and semistructured meshers often get as input data the position of the nodes in the contours of the domain, and generate the inner nodes positions from a given interpolation [10,12,4]. The quality of the final mesh obtained is directly related to the kind of interpolation used and the degree of distortion of the contours of the domain, so a minimum level of element quality cannot be guaranteed for arbitrary domains. However, for good shaped volumes and uniform sizes distributions these methods provide with very good quality meshes.
The main advantages of structured meshers are:
On the other hand, these meshers have some important drawbacks:
Figure 12: Example of a 2D structured quadrilateral mesh with a nonuniform size distribution. A high level of element distortion can be appreciated. 
The advancing front method [14,15,16,17] is a common technique for generating unstructured meshes. It gets a closed and oriented mesh of the boundary of the domain as input and mesh its inner part. The surface elements of this mesh are the ones in the active front, and the algorithm can be summarized with the following points:
Although the advancing front is mainly used for generation of tetrahedral (or triangle in 2D) elements, some adaptations of the method have been done to generate other types of elements [18], and even for generating particles for DEM simulations [19]. The present work is focused in tetrahedra mesh generation. There are several possible implementations of the advancing front method [11] depending on the way of creating the new elements from a face of the front, the way of considering the mesh desired size in the inner part of the domain, or the order in which the faces of the front are processed, among others. In special, much work have been done in order to improve the efficiency in evaluating the desired mesh size in a specific region of the domain, and control a smooth size transition in the final mesh. This is one of the strong points of advancing front techniques, as the creation of each element can fit very well the desired mesh requirements. Different approaches use a background grid to set the mesh desired size [16,15,20,21], or sources from which the desired mesh size vary following a given function [22], which provides with a very smooth transition between element sizes. A combination of different methods can be used in order to improve accuracy and reach an efficient implementation of the method [23]. However, independent of the implementation, one can identify some general advantages and disadvantages of advancing front based techniques. The main advantages are:
The main drawbacks of the advancing front method are:
A Delaunay mesh is defined as a mesh which elements accomplish the Delaunay condition: the circumcircle (in 2D case) or the circumscribed sphere (in 3D case) of any element has no node from the mesh inside [10]. Given a cloud of points, a Delaunay triangulation can always be created from their Dirichlet tesselation connecting them with a set of triangles (in 2D) or tetrahedra (in 3D) without adding any extra node [10].
The Delaunay meshing methods [12,25,5,11] depart from the contour of the domain and generate the Delaunay triangulation of its nodes. This mesh is the convex hull of the domain to be meshed. Although it is already a mesh, its elements may have a low quality, or may not fit with the desired mesh size in that region of the domain: these are the bad elements. The following strategy is applied recursively to all the bad elements:
This procedure leads to a Delaunay mesh (accomplishing the Delaunay condition), but this does not guarantee a given level of quality by itself. Often, some elements can present very low quality (especially in 3D cases). These elements may have null volume and are called slivers. Even if its volume is equal to zero, they can accomplish the Delaunay condition. For this reason, it is common to relax the Delaunay condition in some regions in order to avoid quality problems [27].
The main advantages of this method are:
The main drawbacks of the Delaunay method are:
Space decompositionbased methods follow a different philosophy than the methods explained before. To generate the mesh, they basically subdivide the space into cells providing with a spacial decomposition covering the space where the domain is (overlapping the domain). These cells can be thought in a general way, but it is common to use one of the following main structures which govern their configuration:
(a)  (b) 
Figure 13: 2D examples of typical structures used in space decomposition based meshing algorithms. (a) Bin. (b) Quadtree. 
The bin structure is suitable for homogeneous discretizations. It is common to use an octree structure as the regular grid (which gives the name of the family of methods), because it is more flexible for mesh generation purposes, as domains to be meshed and desired mesh sizes are commonly nonhomogeneous. Octreebased meshers were pioneered by Yerry and Shephard in [35] and, since then, several approaches have been proposed [36,37,38,39,40,41,42].
The octree structure was thought for the first time for space searching purposes [34], and the specific topology of the spatial decomposition it represents (detailed in Section 3.2) gives several advantages for mesh generation. Somehow, an octree can be considered a mesh itself (it can be thought as a nonconformal hexahedra mesh), so it is really natural to build a mesh from it.
Although several algorithms have been proposed parting from the octreebased family of methods, almost all of them follow three main steps:
Concerning the first step, as it has been pointed out before, the octree is the most common structure used for the space decomposition. From the theoretical point of view, all octrees are similar, but depending on the way the octree will be used, different implementations have been proposed by several authors [43,34] in order to improve the efficiency of the octree, the performance for searching processes, the optimization considering the memory needed to store it, etc... More details on the implementation of the octree are presented in Section 6.2.
The generation of the elements of the final mesh from the octree is a simple process. It is based in creating the mesh elements directly from the octree cells (the definition of octree cell, as well as other octree related basic concepts are explained in detail in Section 3.2). Some of the existing methods apply different splitting patterns from the cells to get tetrahedra [35,44,37]. Other methods can get directly the cells of the octree as hexahedra elements of the final mesh (in cases where the final mesh is not needed to be conformal), or create transition elements when two neighbors present hanging nodes [42]. [40] proposes a different approach: create special cells where the octree is refined (where the neighbor elements are not conformal) and build the dual of the octree. The cells of it are directly the elements of the final mesh. With this approach a final mesh of conformal hexahedra is obtained automatically.
The key difference of each method remains in the third step, which is the most complex one. As the octree is a regular space decomposition, their cells do not fit exactly the contours of the domain to be meshed. Getting only the elements coming from the cells which are in the inner part of the domain (or even the ones intersecting its boundaries), the contours of the final mesh are staircaselike, so they are not able to represent smooth shapes with a given curvature.
Considering the inner cells (the ones totally inside a volume) and the interface ones (the ones colliding with the contours of a volume), different strategies have been proposed to fit the contours:
Although these methods achieve the smooth representation of the contours, they have to follow specific strategies to preserve the geometrical features (corners or sharp edges). [41] proposes a retetrahedralization of the octants of the octree containing sharp edges using advancing front or Delaunay technique, taking into account the intersection points between the sharp edges and the octree cells. [40] follows a strategy based on detecting which triangle from the input boundary the final nodes lay onto, and assuming that if two nodes lie onto two triangles connected by a sharp edge, there should be a sharp edge between those nodes of the final mesh. This strategy is not so robust, as it assumes that the sizes of the final elements is quite similar to the sizes of the triangles of the contour, so the triangles where two neighbor nodes of the final mesh lie onto are supposed to be neighbors connected by an edge. This is not a general situation.
As it has been explained, several approaches have been proposed departing from the octreebased family of methods. Although each approach has its own characteristics, some common advantages can be detected:
The main drawbacks of octreebased methods are:
The strategy chosen in this work to cover all the requirements described in Section 1.2 is to develop an octreebased mesher. The election of an octreebased mesher in this work has been made taking into account the main advantages and disadvantages of the different methods:
As explained in Section 1.2.4, although the main objective of this work is to develop a new volume mesher, the methodology proposed is applicable to generate meshes of 3D surfaces and lines not belonging to any volume. The case of lines is automatically solved with the special treatment of line elements in the volume mesher (Section 5.3.1), and some adaptations are maid to the volume mesher in order to mesh surfaces as it is explained on Section 5.3.10.
This chapter focuses on defining the different concepts involved in the proposed meshing algorithm, as well as some auxiliary algorithms needed to understand it. The following concepts will be described:
The essential input for the mesher is the geometrical definition of the boundaries of each volume of the domain. As indicated in Section 1.2.2, this definition can be carried out using CAD or mesh entities. In this document the general concepts of surface, line and point entities will be used for both representations.
At this point, it has to be commented that the mesher considers the outer part of the domain as another volume to be meshed. It takes the name of outer volume, or volume number zero. Of course, the outer volume extends until infinite and it has no sense to consider it as a closed volume, so it is treated in a special manner. Later on it will be explained in more detail how the mesher deals with it.
Together with the surface entities an extra information is needed: the identification of the volumes each surface entity is interfacing. Note that considering the outer part of the domain as a virtual volume, all the surface entities defining the domain are interfacing two volumes. It may have sense for a surface entity to interface more than two volumes, but this would imply overlapping definitions of the 3D space (parts of space belonging to more than one volume). These kinds of topology are not considered in the present work.
Apart from the geometrical definition of the boundaries of each volume of the domain, extra information can be given to the mesher in order to specify some characteristics of the final mesh. It is important to note that this extra information is optional, as the mesher should generate the mesh of the domain with or without it. This information is given by the mesh size entities, the forced point entities, the forced line entities and the general parameters. Hereafter the characteristics of these data are detailed:
(a)  (b) 
Figure 14: (a) Contours of a volume highlighting some of its forced line entities. (b) View of the tetrahedra mesh of the volume highlighting the sharp edges corresponding to the forced line entities in (a). 
Apart from all these data, extra information can be attached to the entities defining the input boundaries: the external data. The external data can be of any nature and it has no relevance for the meshing process, but the mesher will transfer it to the corresponding entities of the final mesh. As an example, if a surface entity defining part of the boundary of a volume has some external information, the nodes of the final mesh placed on that surface entity, or the faces of the tetrahedra with all its nodes onto it will have the same external data attached to them.
To prepare all the data needed for a numerical simulation it is common to use a software tool: the preprocessor. As explained in Chapter 1, part of these data is the mesh representing the geometry of the domain. As the geometry of the domain is often provided in a CAD format, preprocessors typically are forced to work with CAD data and generate the meshes for the simulation. This is the reason why preprocessors are often CAD systems, and they include several meshers inside.
From the point of view of a general preprocessor or a CAD system willing to use the presented mesher, there are some interesting aspects to be considered. Typically the geometrical entities inside these systems have several information attached related with the simulation data (boundary conditions, material properties, etc...) or to the CAD system structures (layers grouping the entities, topological information, etc...). This information must be transferred to the generated mesh, which implies the following requirement for the mesher: it should return specific meshes representing given geometrical entities (not only volumes, but also curves and surfaces).
The mesher should provide not only with the tetrahedra generated, but also with triangular meshes (made of triangles which are faces of the tetrahedra) and linear meshes (made of linear elements which are edges of the tetrahedra). Actually point entities can also be identified with a final node in the mesh, just by setting the corresponding point entity as a forced point entity.
The way to make the mesher returns (apart from the tetrahedra meshes of the volumes of the domain) the mesh of some line or surface entities from the input data is explained hereafter.
How to get the mesh of a line entity:
How to get the mesh of a surface entity:
Following this mechanism, the preprocessor can obtain not only the mesh of the volumes of the domain, but also the mesh of any line or surface entity. Once a mesh of an entity can be identified, all the information of the input entity can be transferred to the corresponding part of the final mesh.
As the octree is a key structure in the proposed mesher, a brief introduction is given in this section to highlight its characteristics.
 
Figure 15: Example of a quadtree structure. (a) The root cell of a quadtree. (b) Root cell subdivided in 4 cells. (c) Example of a quadtree refined 4 levels. 
An octree (quadtree in the 2D case) is basically a hierarchical spatial structure that partitions the space [34]. The basic structure of an octree is the cell, which is a cubic portion of space (square in the 2D case). Actually, the cell can be a parallelepiped (or parallelogram in 2D). In this work the octree used is an homogeneous one, which implies that the cells are regular parallelepipeds (cubes). From a first cell which is the bounding box of the space to be partitioned (the so called root of the octree), a successive subdivision can be performed, where each cell is subdivided in eight cells (four in 2D case). These eight cells are the sons of the cell they come from, which is their father. Cells with no sons are called leaves.
In the Figure 15 a graphical view of the root of a quadtree and different levels of refinement are shown.
Considering the root of the octree, it can be equilateral or not. This, together with the way the cells are subdivided, leads to different configurations of the octree (Figure 16). In particular, for notation purposes, an octree accomplishing the following two properties receives the name of isotropic octree:
To fix the notation, some interesting concepts related with the octree are detailed hereafter:
As explained in previous sections, the octree structure was thought for the first time for space searching purposes [34]. In this section, the adaptations to the octree structure done in order to use it for mesh generation and its main properties to understand the algorithm are explained.
The decision of using the octree for isotropic mesh generation leads to use an isotropic octree. This decision has an important relevance at the time of implementing the algorithm (as it will be seen in Section 6.2).
The proposed meshing algorithm should be valid using other kinds of octree (like the analogous quadtree examples shown in Figures 16(a) and (b)), but it would lead to non isotropic meshes.
 
Figure 16: Different kinds of quadtree. (a) Quadtree with a nonequilateral root, with a equidistant cell division criterion. (b) Quadtree with an equilateral root, with a nonequidistant cell division criterion. (c) Isotropic nonbalanced quadtree. (d) Isotropic balanced quadtree. 
Another important characteristic of the octree chosen for the method is the so called constrained two to one condition. This is a widely used condition in octree based meshers, and limits the number of neighbors of a cell. The two to one name comes from the two dimensional case (quadtree), and limits the maximum number of neighbors of a cell to two. In the octree case (3D), this condition implies that a cell cannot have more than four neighbor cells by face, or two by edge. In the present document an octree accomplishing the constrained two to one condition is referred as a balanced octree. Two configurations of an isotropic quadtree (nonbalanced and balanced) are shown in Figures 16(c) and (d).
The main reason to use a balanced octree for the proposed meshing algorithm is to simplify the patterns to build the tetrahedra from the octree cells, ensure a better quality in the final tetrahedra and avoid a very strong sizes transitions in the final mesh. The tetrahedra generation process from the octree has the following characteristic: the more difference between sizes of neighbor cells, the worse aspect ratio will have the tetrahedra generated from them.
As it has been pointed out in previous sections, octree cells are the result of the space partitioning by the octree structure. Besides this, they have some information attached as the input boundary entities colliding with them.
Figure 17: 2D example where the three kinds of cells can be identified. The black curved line defines the contours of a domain formed by two surfaces (which are in contact), and the light gray lines represent the octree. Outer cells are the white ones, interface cells are marked with dots, and inner cells are colored in gray. 
In the frame of this work, the octree cells are classified in three categories:
Figure 17 shows a 2D example where the three kinds of cells can be identified.
As it is explained in Section 3.3.3, tetrahedral elements will be generated following a pattern from the octree. The nodes of these tetrahedra are called octree nodes and they are assigned to some predefined positions in space: the octree positions. Each cell has 27 octree positions corresponding to the vertices of the cell (8), the center of the cell (1), the center of its edges (12) and the center of its faces (6). A graphical view of the octree positions of a cell is shown in Figure 18.
Figure 18: Octree positions of an octree cell. The cell is represented by the black lines. 
It has to be noted that an octree position can be shared by more than one cell, as it can be seen in Figure 19.
Figure 19: Linear octree positions of a part of an octree. White dots are center of cells, and black dots correspond to vertices of cells. 
The linear positions of an octree cell are defined as the ones corresponding to the vertices and the center of the cell. The other positions are called quadratic positions. As an extension, the term of linear or quadratic octree node can be used to refer an octree node associated to a linear or quadratic cell position.
When referring to the whole octree, a linear position (or octree node) is the one which is linear in some cell. It has to be noted that an octree node can be linear regarding one cell, but quadratic from the point of view of another cell containing it. The linear octree positions of a part of an octree are shown in Figure 19 as an example.
It is important to note that not all the octree positions are forced to have an octree node associated, but all the octree nodes are linked to an octree position.
In Section 5.3.2 the concept of forced node is introduced. It basically corresponds to a node linked to an octree position, but occupying a different position in space.
Parting from a given octree configuration, there are several possible tetrahedra patterns to be applied in order to split it. One important consideration is that the pattern chosen must fill the space with tetrahedra in a conformal way: it must not leave hanging nodes. A hanging node is a node lying on an element not being a vertex of it (it is on an edge or a face).
The option chosen in this work is based on the body centered cubic (BCC) lattice, which lead to a spacefilling tetrahedra [45]. The use of BCC patterns linked to octree structures is quite natural considering the spacial distribution of the octree, and was proposed by [DBLP:conf/imr/Fuchs98,NME:NME616]. This option fills the space in a conformal way with a set of identical high quality tetrahedra: dihedral angles are or degrees, and edge lengths are 1 and times the cell size. This provides the tetrahedra with an edge ratio of (the ratio of the longest and shortest edges of the element).
A BCC lattice based pattern is local in the sense that each tetrahedra generated only depends on one cell and one of its neighbor. A pattern only depending on each cell (independent from the neighbor ones) would be more efficient for parallelization. However, this kind of patterns often provides with a lower quality tetrahedra (although their quality is acceptable) and a larger number of them [46].
The BCC lattice is defined in a regular grid (an octree with all its leaves equalsided). As the octree used in the proposed method is not regular (it has leaf cells in different levels), other tetrahedra patterns must be defined.
To reach a tetrahedra mesh with no hanging nodes, all the linear octree nodes are used, and (in case they exist) the forced nodes linked to quadratic positions (forced nodes are defined in Section 5.3.2).
Basically, the tetrahedra pattern proposed focuses the tetrahedra generation cell by cell, and focusing on one cell, using its six faces independently. The only information required to generate the tetrahedra from a face of a cell is: the octree nodes of the face , the center octree node of the cell and the neighbor cell of from the face , denoted by .
As explained previously, the octree used is balanced (it accomplishes the constrained two to one condition). This ensures that the level of is one less, equal, or one more than the level of . These three configurations lead to the different tetrahedra patterns:
(a)  (b) 
(c)  (d) 
Figure 20: Tetrahedra pattern in case where cell has the same level as . Tetrahedra generated from edge () of common face between and in different situations. (a) No quadratic octree nodes involved: one tetrahedron is generated (). (b) Octree node in the center of face : two tetrahedra are generated( and ). (c) Octree node in the center of edge : two tetrahedra are generated( and ). (d) Octree nodes in the center of face and edge : four tetrahedra are generated(, , and ). 
The minimum dihedral angle of the tetrahedra generated in this configuration is degrees, and it occurs when some node in a quadratic position is used.
This case involves the creation of tetrahedra in two cells. Hence, only one of them should create them to avoid repetitions. The criteria used is that cell creates the tetrahedra only if it is lower than , otherwise the tetrahedra will be created by . Considering two leaves ( and ), is lower than if the coordinate of the center of is lower than the coordinate of the center of . If the coordinates are equal, the coordinate is checked, and if it is also equal, the coordinate is used to compare the cells. It has to be noted that, because of the characteristics of the octree structure, there cannot be two leaves with their centers in the same position.
The minimum dihedral angle of the tetrahedra in this configuration is degrees.
(a)  (b) 
Figure 21: Tetrahedra pattern in case where cell has different level than . (a) is bigger than : 8 tetrahedra are generated (, , , , , , and ). (b) is smaller than : two tetrahedra are generated( and ). 
The minimum dihedral angle of the tetrahedra in this configuration is degrees.
It can be seen that the quality of the tetrahedra generated using these patterns depends on the configuration chosen, but it is always very good: the minimum dihedral angle of any tetrahedra coming from this predefined patterns is degrees.
The case where a cell has no neighbor by one of its faces occurs in the cells in contact with the boundaries of the octree root. This case is not considered because the building of the octree root (Section 5.2.3) ensures these kind of cells are totally out of the domain to be meshed, so they are not used to generate any tetrahedron.
Geometrical intersections play a key role in the new meshing algorithm and affect several parts of it. This section focuses in defining how this intersections are considered. Their treatment has special interest when the input boundaries are nonwatertight.
The intersection operation involved in the algorithm is typically the one between a segment and the surface entities defining the contours of a volume. This segment is understood as a portion of a straight line between two points. Depending on the part of the algorithm, it could be referred with different names such as edge (when talking about tetrahedra or triangle edges) or ray (when talking about ray casting operations). In this document some figures are based in 2D examples for clarity purposes. The equivalent intersection operation in these cases is between segment and line entities defining the input boundaries.
 
Figure 22: Types of intersections between a segment and a surface entity. Crosses are the intersection points. (a) No intersection. (b) type intersection. (c) type intersection. (d) type intersection. (e) and (f) type intersection; the red thick part of the segment is coplanar with the surface entity. 
Five situations are distinguished when evaluating the intersection between a segment and a surface entity (a graphical interpretation of these cases using simple examples is depicted in Figure 22):
Analytically, the type of intersection has an infinite number of intersection points. As it will be seen in further sections, these intersection types only take relevance in the node coloring process (Section 4), that determines inside which volume a node is. For this reason the treatment of type intersections is detailed in Section 4.2.
Types , and have only one intersection point. However, as the contours of a volume may be formed by more than one surface entity, each intersection may involve a different number of intersection points (one for each intersected surface entity). This situation is illustrated in the 2D examples of Figure 23 (as a 2D example, line entities play the role of surface entities in 3D). In Figure 23(b) a intersection type has two intersection points (one for each intersected line entity), as well as in Figure 23(c) with the type intersection.
 
Figure 23: Line entities enclosing surface intersected by a segment (bounded by two dots) presenting different intersection types. Intersected line entities are drawn in dotted line. (a) intersection type. (b) intersection type. (c) intersection type. 
These cases are characterized by the fact that all the involved intersection points are really close one from each other. Theoretically, all the intersection points should be in the exact same position, but because of the tolerances involved in the numerical computation of intersections this cannot be guaranteed. The tolerance is defined in order to determine if a collection of close intersection points corresponds to the same intersection: if all of them are within a distance lower than , they are collapsed into a multiple intersection point (MIP). The value of is a portion of the model bounding box size:

(3.1) 
being the length of the minimum side of the model bounding box, and a real value between zero and one. The value used in the present work for is detailed in Section 6.7.
The position of the MIP corresponding to a collection of intersection points is the mean position between all of them. In the present work, when evaluating the intersection point between a segment and the contours of a volume, in cases where there are intersection points close enough, their MIP is considered instead of them. This matches with the theoretical number of intersection points corresponding to each intersection type: and intersection types have only one intersection point (a MIP).
For nonwatertight geometries, special cases may be treated when evaluating the intersection between a segment and the contours of a volume. There are basically two specific intersection types (a 2D example of this cases is depicted in Figure 24):
(a)  (b) 
Figure 24: Intersection between a segment and the line entities enclosing surface A in nonwatertight situations: (a) overlap (W intersection type) and (b) gap (G intersection type). 
For the W intersections type, the corresponding MIP of the intersection points involved is considered. For this purpose, in cases where nonwatertight geometries define the domain, takes the value of . This parameter must be provided in the input data and is a characteristic length of the gaps and the overlappings of the model. must be an upper limit of the distance between overlapping entities. The MIP corresponding to the 2D example of Figure 24(a) is shown in Figure 25(a).
G intersections do not provide with any intersection point. However, as it will be seen in further sections, there are cases where the extremes of a segment are known to be inside different volumes. Situations where both extremes belong to different volumes indicate that there should be an intersection point although it is not detected. In this cases the gap intersection point (GIP) is created. Considering the surface entities surrounding the segment, the closest point from each surface entity to the segment can be computed. The GIP takes the position of the closest one. The GIP corresponding to the 2D example of Figure 24(b) is shown in Figure 25(b).
(a)  (b) 
Figure 25: Treatment of intersections of nonwatertight geometries depicted in Figure 24. (a) MIP corresponding to the W intersection depicted in Figure 24(a). (b) GIP corresponding to the G intersection shown in Figure 24(b). 
In the present work, the intersection point between a segment and the contours of a volume could be a single intersection point, a MIP or a GIP.
As explained in Section 2.5, space decomposition meshing methods use a regular grid (in our case, an octree) over the domain to be meshed. The regular grid is larger than the domain, so at some point of the algorithm, this family of methods are forced to use a strategy to know if a given position of the grid is inside or outside the domain.
The coloring operation consists in determining where the entities are in the topological sense. This is, to determine whether each entity is inside a volume, out of the domain or laying on an interface entity between volumes. Applied to points, this operation is known in the literature as the pointinpolygon (PIP) problem [47,48,49].
In the presented meshing method, the coloring operation is applied to nodes (the case explained in this section) and to tetrahedra (as explained in Section 5.3.7).
This is one of the key points of the meshing algorithm, as it is not obvious to determine if a point in the space is inside a volume or not when the contours of the volume are nonwatertight. Actually, if the contour of the volume has gaps, the concept of interior or exterior of the volume is not even defined from the topological point of view.
It has to be noted that several existing octreebased methods are focus on meshing a domain formed by a single volume. In this work arbitrary domains with several volumes are meshed at once, so coloring a node is not reduced to identify if it is inside or outside the domain: it has to be determined inside which volume (or interface entity) is.
There are several ways of coloring points considering a watertight definition of the volumes. These cases have some clear advantages as the contours of each volume can be oriented coherently (towards the interior or the exterior of the volume). This orientation provides with valuable information at the time of determining if a point near the contour entity is inside or outside the volume.
However, this work is focused on nonwatertight geometries. This implies that a coherent orientation of the contours of a volume cannot be guaranteed. To deal with such geometries it is common to work with a voxelization of the model [50,51,52]. These strategies aim to converting the nonwatertight geometries into watertight ones in order to be able to apply the coloring strategies of points. A voxel representation of a model is a regular grid (typically axis aligned and isotropic) where each voxel contains a topological information. In the case of study, it contains the color of the voxel. If a voxel is intersected by a surface entity it has the color of that surface (lets call it a contour voxel), otherwise it has the color of the volume it is into (inner voxel), or the color of the outer part of the domain if it is not inside any volume (outer voxel). All the points inside an inner voxel can be considered as interior to the corresponding volume. An example of voxelized 2D model is shown in Figure 26.
 
Figure 26: Example of three voxelizations of a 2D model. The model has a gap in its contour and it is represented by the black curved line. Contour voxels are drawn in red. (a) The size of the voxels is large enough to close the gap of the domain: the topology of the voxelized model is watertight. (b) The size of the voxels is too small, so the gap of the domain is not closed. (c) The size of the voxels is too large: the gap is closed, but the final topology does not represent correctly the domain. 
The advantage of working with voxelized models is that, depending on the size of the voxel, the topology of nonwatertight geometries can be improved. If the gaps of the input boundary or the distance between overlapped contour entities is lower than the voxel size, the voxeled model may close the gaps or join the overlapped entities. This situation is shown in Figure 26(a), where the voxelized model presents a closed set of inner voxels (with no gap in its contour). As a drawback, the voxelized model can neglect some important topological information of the domain: the topology of the voxelized model shown in Figure 26(b) represents exactly the topology of the model (with its gap). Despite the size of voxels used in Figure 26(c) is large enough to close the gap (which is desirable), it represents an undesired topology, as it includes different sets of unconnected inner voxels.
The problem is that the voxel size needed to represent correctly the topology of the model cannot be estimated a priori and it may not be valid for the whole domain. Figure 26 shows that three different voxel sizes lead to three different topologies of the same domain.
If the voxelized model is watertight, one strategy for the coloring of the voxels is by propagation [50]. This strategy consists in the following steps:
This propagation method is totally robust in watertight representations and has the advantage of solving very few times (one for each volume) the PIP problem, which can be computationally expensive. However, it has the drawback that is not naturally parallelizable. Only the voxels which are neighbour of a determined voxel (a voxel with a known color) can be colored at a time.
Voxelizing the model can help the coloring strategy as it can make the model watertight, enabling the use of the propagation method (which requires the solving of PIP problem only in a few points). However, it has been seen that even the voxelized model may be nonwatertight. In this case the color propagation cannot be done, so the PIP problem has to be solved for each one of the points to be colored (in our case, the octree nodes).
The solution chosen in this work for coloring the octree nodes is based on the ray casting technique. The ray casting algorithm was first developed by Arthur Appel for rendering purposes in 1968 [53]. It proposes a solution for determining the visibility of a 3D object from a given point of view, and uses this information to paint a representation of the 3D object in a 2D image (made of pixels). The idea behind ray casting is to shoot rays (straight lines) from the point of view (one per pixel) and find the closest part of the object intersecting the ray. The algorithm needs to compute first all the intersections between a ray and the contours of the object (surface entities), and then get the closest to the point of view.
Figure 27: 2D example of the ray casting technique to solve the PIP problem. Point is considered outside of the polygon because ray has an even number of intersection points (2). Points and are considered inside of the polygon because rays and have an odd number of intersection points (1 and 3 respectively). 
Despite the first applications of ray casting were focused on rendering of 3D objects, its use has been generalized for several purposes following the philosophy of analyzing the intersection points between the ray and given 3D objects.
A common use of the technique is to solve the PIP problem. Among the several existing methods to solve this problem [47,48,49], a classical approach is the ray intersection method [47]. It consists in tracing a random ray from the point of analysis and compute the number of intersections between it and the contours surface entities. If the number is even, the point is outside the domain, and if it is odd, it is inside.
A 2D example illustrating the application of ray casting technique to solve the PIP problem is depicted in Figure 27. In this example, is considered outside of the polygon because the ray has two intersection points (an even number). Points and are considered inside of the polygon because their rays ( and ) have an odd number of intersection points (1 and 3 respectively).
As pointed out previously, in the present work the coloring process of a node must identify not only if it is inside or outside the domain, but also the specific volume of the domain it is into. To fit this requirement, the ray casting method in this work focuses more on the topological information of each intersection rather than in the number of them. Following this philosophy, the proposed method consists in tracing rays in space and take care about the intersection of these rays with the contours of the volumes: if a ray intersects the interface between volumes A and B, it can be ensured that, near the intersection point, at one side of the intersection point the ray will be inside A, whereas at the other side it will be inside B. Following this principle, if we move along a ray from a point which color is known, we can color all the points of the ray just looking at the intersections of it with the contours of the volumes. Figure 28 shows a 2D example where a ray beginning in the outer part of the domain is colored in different parts corresponding to the contours it is intersecting.
Figure 28: A 2D example of coloring parts of a ray (represented by the black arrow). The black dot is the beginning of the ray which color is known: . The crosses are the intersection points between the ray and the contours of the surfaces A and B (which are the ones forming the domain). In the upper line the color of the different parts of the ray is shown. 
It is important to note that the presented technique only need the topological information of the surface entities: which volumes they are intersecting. Other techniques require the use of normal vectors in some points, or a given connectivity among the surface entities defining the contours of the domain. This is crucial considering the proposed algorithm must work with nonwatertight definitions of the volumes. In these cases it is not obvious to define the oriented normal of a surface entity pointing towards the inner or the outer part of a volume.
The ray casting technique presents some pathological configurations [49] for the PIP problem. One of these is the case when the intersection between the ray and the volume boundaries is done tangentially (T type intersection defined in Section 3.4). In this situation the ray intersects the boundaries of the geometry, but both sides of the intersection are in the same volume. To solve this problem, this kind of intersections (tangentially to the boundaries of the volumes) are not taken into account for coloring the regions of the ray. Figure 29(a) shows an example of this pathological case: both sides of the ray from the dark intersection point are inside surface B, although there is an intersection point.
Another pathological configuration occurs when the intersection point is a point of the boundary interfacing more than two volumes (in 2D case, more than two surfaces). This is the case shown in Figure 29(b). For notation purposes, this kind of intersections are referred as a M intersection type.
If a intersection is detected in a ray, a color has to be chosen for the following part of the ray (from the intersection point on). The strategy followed to decide this color is explained in the Implementation chapter (Section 4.3.1). It is based on a try and error approach considering all the possible colors.
(a)  (b) 
Figure 29: 2D examples of pathological configurations for the ray casting technique. (a) Both sides of the ray from the dark cross intersection are colored equally (surface B) although there is an intersection point because the ray is tangent to the contours in it. (b) M point is interface between surface A, B and (outer part of the domain), so the color of the right part of the ray cannot be set. 
The case of coplanar intersections ( and intersection types defined in Section 3.4) presents also a pathological configuration for the ray casting technique. In these cases, the part of the ray coplanar with the boundaries must be colored with the color of the interface itself. In this case, the color does not correspond to a volume, but to an interface between volumes. 2D examples for and intersection types between the ray and the boundaries of a model is depicted in Figure 30. The end point of the coplanar part of the ray is considered as an point from the coloring point of view.
(a)  (b) 
Figure 30: 2D examples of coplanar intersections of the ray. (a) intersection type. The color at the right part of the point could be or zero. (b) intersection type. The color at the right part of the point could be , or zero. 
For nonwatertight contours of the domain volumes, two more pathological configurations affect the ray casting technique. They are related to the possible gaps and overlapping entities in the contours (G and W intersection types defined in Section 3.4):
(a)  (b) 
Figure 31: 2D examples of pathological configurations for the ray casting technique with nonwatertight domains. (a) G type intersection of the ray. The part of the ray inside the surface A is not colored as A because the ray has not intersected its boundary entities. (b) W type intersection of the ray. The part of the ray inside surface A is colored as zero because the ray intersects two times the boundary in the same region (crosses). 
Both pathological cases (gaps and overlappings greater than ) can lead to set the ray as invalid. An invalid ray is a ray with some coloring contradictions. There are two kinds of contradictions, depicted in Figure 32(a) and (b):
 
Figure 32: Types of invalid rays (crosses are intersection points). (a) The last part of the ray is colored as , but it should be zero.(b) At the dark cross intersection point the ray should arrive with color or , as these are its interfacing surfaces, but its color is zero. (c) Rays to be canceled because they provide with different colors to a given position. 
Situations of invalid rays can also happen even if the contours of the domain are watertight, taking into account that the intersection operations in 3D are done numerically, so they depend on tolerances. Some specific configurations of the ray and the contours may lead to an invalid ray.
A special kind of rays are the Cartesian rays, which are straight and parallel to the , and directions. The ray casting technique can be applied to any kind of ray, but in the proposed algorithm Cartesian rays are used because they simplify the intersection operations, and they take profit on the spacial distribution of the nodes provided by the octree structure (this aspect will be seen in more detail in Section 4.3).
Taking into account that the domain to be meshed is totally inside its bounding box, the octree nodes which are outside it can be directly colored as zero (they are out of the domain) without the need of any coloring process. All the other octree nodes are colored using rays which begin out of the model bounding box, so as the color of the initial point of the ray is known: zero. The color of a node is directly the color of the part of the ray the node is into.
As there are situations in which a ray is considered as invalid to color a point because of a pathological configuration, the following strategy is applied in order to color all the octree nodes:
Figure 33: A 2D example of local ray casting. A non watertight representation of surface A is shown. The two Cartesian rays passing by the black dot (drawn with dotted arrows) are not valid. The color of the white dot is known (inside surface A). As the ray from the white dot to the black one has no intersection with the boundaries of the domain, the color of the black dot is also set to A. 
This strategy have been proved in several examples, and it solves successfully the coloring process for the octree nodes with pathological configurations for the ray casting technique. The use of three rays for each node provides with a redundancy minimizing the possible effect of an invalid undetected ray.
This section is focused in the implementation of the algorithm explained in Section 4.2.2 for nodes coloring. It requires three Cartesian rays for each one of the nodes in order to color them (determine where they are topologically). Applying this algorithm to a general cloud of nodes would imply to compute the intersections of rays. However, as the nodes of the tetrahedra mesh treated in this work are octree nodes, most of them are placed on regular positions in space, aligned with the Cartesian directions. To take advantage on this configuration, one ray can be used in the coloring of several nodes: all the ones aligned with a Cartesian direction. Following this strategy an important time saving is achieved in the nodes coloring operation.
It is important to note that only the nodes with unknown color must be colored following the presented algorithm. The octree nodes with known color before the coloring operation are:
A 2D example of the rays used to color the nodes of a given configuration of a quadtree is shown in Figure 34. In the example, there are nodes to be colored and rays are used ( for direction and for direction).
 
Figure 34: Rays used to color the quadtree nodes of a 2D example. The contour of the domain is the solid black line and the dotted line represents its bounding box. Rays are represented with red arrows. (a) Quadtree configuration with all the octree nodes represented. The black nodes are forced nodes. (b) The rays used in direction to color the nodes. Only the nodes to be colored are plotted in order to clarify the figure. (c) The rays used in direction. 
The implementation of the coloring operation is based in the following steps:
In this section the strategy followed to solve the pathological situations for the ray casting technique defined in Section 4.2 is detailed. These situations are related with the , , , and intersection types and the intersection points.
In all these situations the intersection point is a (Section 3.4). Actually, the intersection type (situation where the ray passes through a gap in the boundaries) involves a , but this kind of intersections is not solved in the present approach because trying to find the corresponding to all the parts of the ray not intersecting the input boundaries would be too computationally expensive. Leaving this situation as unsolved could lead to rays declared as valid, but giving wrong information in terms of coloring. It has to be noted that if this situation occurs, it does not mean necessary that an invalid color will be assigned to the nodes. As the three Cartesian rays passing by a node contribute to the decision of its color, only in cases where the three rays are considered valid, provides with wrong information and this information is compatible (within the three rays), the color of the node would be wrong. This is a rather improbable situation, which have never happened in the examples run in this work.
A MIP in a ray indicates the presence of a pathological configuration. Each intersection point has the information of the two volumes interfaced by the surface entity where it is (the interfacing volumes of the intersection point). The interfacing volumes of a MIP are the union of the interfacing volumes of each intersection point involved, so a MIP can have two or more interfacing volumes.
In Section 4.2 the situation of intersection types (coplanar ones) is explained. They correspond to a intersection point at the end part of the coplanar part of the ray. Considering that the presented algorithm uses linear triangle elements as surface entities for defining the boundaries of the domain, the situation where the ray is coplanar can be detected easily. If geometrical surface representations (line NURBS) are used for defining the contours of the volumes, solve this situations becomes much more difficult. For coloring purposes, the coplanar part of the ray takes no relevance, as it is ensured there will be no node to be colored there. If a node is so close to a surface entity it is a forced node in interface (Section 5.3.2), so its color is already set without the need of ray casting technique. The problematic situation comes at the time to color the following part of the ray (next to the coplanar one), where a color have to be assigned among the corresponding interfacing volumes.
When a MIP (a pathological configuration) is detected, its type has to be determined (, , or ) in order to apply the right strategy to color the following parts of the ray from that point on. For this purpose, a sort of auxiliary local rays are built: the surrounding segments. These are segments parallel to the ray at a distance of it. In the present implementation, a number of surrounding segments has been chosen following the Cartesian directions. Longitudinally, the surrounding segments are centered in the MIP position and have a length of , being the distance to the closest intersection point of MIP (in the ray). An example of the surrounding segments of a ray is shown in Figure 35. In this example the ray intersects two triangles by its contour edge, so it is a intersection type.
Figure 35: Surrounding segments of a ray around a MIP. The two triangles represent a part of the input boundaries. The black dot is the MIP and the white ones are the intersection points between the surrounding segments and the input boundaries. The black cross is the nearest intersection point of the ray to the MIP. 
Then, the intersection points between the surrounding segments and the input boundaries are computed. Considering them and the MIP interfacing volumes, the following cases should be accounted for distinguishing the type of pathological configuration:
Actually, cases IIIa and IIIb could be merged, as case IIIb is included in IIIa. The differentiation has been made only to highlight that a intersection type always implies a MIP, and the one can present a MIP or not in the surrounding segments. This is not relevant because the treatment of and intersection types is analogous for coloring purposes.
A graphical interpretation of these cases in a 2D example is illustrated in Table 4.3.1. As a 2D cases, only two surrounding segments take sense for a MIP.
Case I: there are three interfacing surfaces (, and zero) involved in the intersection points of the surrounding segments. intersection type.  
Case II: all the intersected entities have the same interfacing surfaces ( and zero), and there is one surrounding segment with no intersection. intersection type.  
Case IIIa: each of the surrounding segments intersects the boundaries in one point and all the interfacing surfaces are the same ( and zero). intersection type.  
Case IIIb: all the surrounding segments can create a MIP (its intersection points are closer than ) and all the interfacing surfaces are the same ( and zero). intersection type.  
Case IIIc: Some surrounding segment has more than one intersection point. intersection type. 
Different cases for surrounding segments for identification of intersection types corresponding to a MIP (white dot) in a 2D example.
Once the type of pathological intersection has been determined, the following strategy is carried out to color the following part of the ray (the one next to the MIP):
There is one situation not solved by the presented strategy. It is a mix between the and the intersection types. It occurs when the ray passes tangentially to two parts of the boundaries of a volume at the same point. A 2D example of this situation is shown in Figure 36. If the corresponding surrounding segments have one MIP each one, it corresponds to the case IIIb, so the intersection would be considered as and the color of the ray would change when it should remain with the same color (as if it was a intersection).
Figure 36: Pathological situation where the analysis of the surrounding segments can lead to erroneous classification of intersection type if . 
As explained in previous sections, this work proposes a meshing algorithm for body fitted meshes and for embedded ones. The later ones are used in embedded and immersed methods, and require for the nodes of the mesh their distance to the input boundaries in addition to their color (Section 5.2). This section focuses in the computation of these distances for the embedded meshing algorithm.
As explained in Section 5.2.1, the computation of distances from the nodes of the tetrahedra mesh to the input boundaries for embedded methods takes advantage on the ray casting technique used in the coloring algorithm. This is mainly because the Manhattan distance [54] has been chosen for approximating the distance for far nodes (nodes further than a given distance of the boundaries of the domain). The Manhattan distance between two points is the sum of the distances of the three Cartesian components of the vector defined by the points. As the rays used in the coloring algorithm are Cartesian, its use fits perfectly for this purpose.
To improve the efficiency in a parallel implementation of the method, each ray contributes with a distance to the nodes it passes through. This implies each node has three contributions of distances, as each node has three rays passing trough it (one for each direction: , and ).
The process of computing the distances from the nodes of the tetrahedra mesh to the input boundaries follows the steps detailed hereafter:

(4.1) 

(4.2) 
where is the distance between nodes and . Note that, as the nodes are aligned in the ray, the distance between them is directly the difference between their coordinates corresponding to the ray direction.
Considering each node of the ray, its distance contribution is set to the minimum between , and .
 
Figure 37: 2D example for computation of distances to the boundaries. (a) Surface representing the domain. The surface is a square with a squared hole inside. (b) Isolines of distance to the boundaries of the surface when only one propagation and update operation have been done. (c) Isolines of distance performing the propagation and update operation two times. 
This chapter present the octreebased mesher developed in this monography.
One of the requirements defined in Section 1.2.3 refers to the immersed [6] and embedded [7] methods. This family of methods uses the so called embedded meshes. An embedded mesh is a mesh of a part of the 3D space containing in its interior the domain to be simulated, but the mesh is not limited to the inner part of the domain and, furthermore, does not fit the contours of it. The effect of the contours of the domain in the results of the numerical simulation to be run is captured by the assignment of special boundary conditions in the mesh elements and nodes. Because of its nature, it takes no sense to talk about preserving features or topology preservation for embedded mesh generation.
On the other hand, there are the bodyfitted meshes, which must capture precisely all the contours of the domain. They need a faithful representation of the boundaries preserving the geometrical features, the topology of the volumes of the domain, and forcing the nodes and elements to follow the shape of their contours.
The algorithm proposed in this monography considers the embedded meshing as a particular case of mesh generation where there is no need to apply any strategy for preserving geometrical features or volume topology. In this sense, the generation of embedded meshes will be easier than the generation of bodyfitted ones.
The detailed explanation of the meshing algorithm requires the definitions of specific concepts and auxiliary algorithms explained in Chapter 3. In Sections 5.2 and 5.3 the meshing algorithm itself is presented for embedded and bodyfitted meshes.
As a general view, the main steps of the mesher are pointed out hereafter. Let us consider that the input data for the mesher is the definition of the contours of the volumes of the domain to be meshed (from now on, input boundaries) and a given list of parameters (detailed in Section 3.1). The new embedded meshing algorithm can be summarized in five steps:
The first three steps are directly related to the octree structure. The two other ones involve mesh operations that can be applied to any unstructured tetrahedra mesh independently on its generation method, although the octree structure can be used as an auxiliary tool in order to improve the efficiency of the algorithms. They are detailed in Chapter 4 and Section 5.2.1.
Concerning the bodyfitted mesher, the four first steps are the same ones as for the embedded mesher (adding some extra refinement criteria to refine the octree in the second step), and the fifth step is replaced by the following three ones:
All these specific steps related to the bodyfitted mesher are also applicable to any unstructured mesh, independently on the generation method chosen.
An important aspect of the new mesher is that it generates the mesh of the whole domain at once, including all the volumes which are part of it. Other existing meshers are designed to generate the mesh of just one volume, so they generate the mesh of the whole domain on a volume by volume manner.
One of the objectives of the presented meshing algorithm is to generate meshes for embedded methods. This section is focused in the specific aspects of the algorithm for this kind of methods.
The main characteristic of embedded methods is that the mesh used is not bodyfitted, and its nodes have the information of:
Knowing if a node is inside or outside a volume is solved by the proposed coloring algorithm (Chapter 4), and the computation of distances also takes profit of that algorithm, as explained in the following section. Furthermore, it is common to apply these methods to domains where only one volume is involved, so only two colors take part: inside and outside.
Embedded meshes are mainly used in Computational Fluid Dynamics (CFD) simulations, where the behaviour of a fluid around solid bodies is studied. If the solid bodies are in movement, rather than remeshing the whole domain at each time step, this family of methods maintains the volume mesh static and updates the nodes information (color and distance).
The distance function plays a key role in embedded methodology in order to apply the boundary conditions. It is common to combine the coloring and distance function into one signed distance function where negative distance indicates inside and positive distance indicates outside nodes. A direct result of this definition is the fact that the isosurface representing the zero distance defines the approximated embedded boundary condition, as shown in Figure 38.
(a)  (b) 
Figure 38: (a) Surface entities defining a cube. (b) The cube representation via a zero isosurface of the distance function in the tetrahedral embedded mesh generated. 
To ensure the accuracy of the method the distance near the boundary and especially in cut elements must be calculated exactly. For the nodes far from the boundary the exactness of the distance becomes less important so, in order to reduce the computational cost, it is convenient to calculate the exact distance only for the points inside a given distance range from the boundary, and leave the rest with a maximum value (an upper distance limit). However, in cases with moving boundaries one may convect the distance function given the interface motion. In this procedure, having sharp gradients in distance functions can lead to numerical error and having a constant maximum distance near the boundary may affect the convergence and results. In order to deal with this problem an approximation of the distance function from a given distance of the boundary would be interesting.
In this work the exact Euclidean distance is calculated for the octree nodes belonging to the interface leaves. For the rest of them the Manhattan distance [54] is computed. It is an estimation of the exact distance given by Equation 5.1:

(5.1) 
where is the Manhattan distance between positions and , and represents the coordinate of the vector. is the dimension of the space considered, in this case: three.
The Manhattan distance provides with the desired continuity and smoothness of the distance function in order to deal with moving objects with minimum distance calculation overhead. The reason to use this distance measure is to take profit on the coloring algorithm, as explained in Section 4.3. Cartesian rays are used for the coloring of the nodes, so using the distances onto the rays provides directly with the Manhattan distance.
As explained in Section 5.1, one of the main steps of the meshing process is refine the octree following given criteria. The basic idea is that the octree must be refined in such a way that the application of the further steps of the meshing process ensures the accomplishment of the requirements to be covered.
In this section all the refinement criteria (RC) needed for embedded meshes are defined. It is important to highlight that all the octree refinement criteria defined in this section (the ones needed for embedded meshes) only depend on the desired mesh sizes and the topology of the octree itself (the balance criterion). This implies that the application of these refinement criteria does not need to consider the input boundaries. For notation purposes, the collection of all the refinement criteria defined in this section is called size refinement criteria.
Let us consider the bounding box of the model (). It is a parallelepiped with its faces parallel to the Cartesian axes (note that is not needed to be coincident with the octree root). is defined as the length of the smaller side of .
For given desired mesh sizes (via mesh size points or general mesh size parameter), lets define as the maximum of the desired mesh sizes entered in the input data. Then, is defined by Equation 5.2:

(5.2) 
If no size has been introduced in the input data, then is directly .
It has to be noted that because of the tetrahedra pattern definition (Section 3.3.3), tetrahedra sizes are directly related to the octree cells sizes. Actually, the size of the edges of the tetrahedra generated from a cell is always equal or smaller than the cell size. Refining the octree implies dividing by two some of the cells, reducing accordingly the corresponding tetrahedra size. This aspect makes impossible to reach exactly a given size for a tetrahedron. The algorithm tends to fit it by subdividing cells until their size is close to the desired one approximating it above or below. To incorporate in the algorithm the difference between the desired mesh size and the cell size and avoid an excessive level of refinement, the parameter is defined. This is a real value ranging between 1 and 2. The value used for is specified in Section 6.7.
Considering the isotropic octree structure, the longest edge of the final mesh of the model must be always smaller than . This leads to the first refinement criterion:
RC 1: If an octree cell collides with and its size is greater than , the cell must be subdivided.
In order to account with the possible desired mesh sizes required by the simulation defined with the mesh size entities, the following refinement criterion is defined:
RC 2: If an octree cell collides with a mesh size entity with a desired size and its size is greater than , the cell must be subdivided.
At this point the concept of generalized mesh size points needs to be introduced. To make easier the implementation of the method, and to automatize the methodology, the use of points instead of generic entities (lines, surface and volume ones) helps. The idea is to replace (only for mesh size purposes) each mesh size entity by a collection of mesh size points with the same desired mesh size: its generalized mesh size points. Actually only mesh size lines, surfaces and volumes are involved in this process, as the mesh size points are already points.
If we consider a mesh size entity with a desired mesh size , its generalized mesh size points are located onto the mesh size entity in such a way that there is no point onto the entity further than from a generalized mesh size point. An example of the generalized mesh size points of a surface mesh size entity (a triangle) is shown in Figure 39.
Figure 39: Representation of a surface mesh size entity (a triangle) with a set of its generalized mesh size points (black dots). It can be seen that all the coordinates inside the triangle have at least one mesh size point closer than . 
It has to be noted that, following this definition, there can be infinite sets of generalized mesh size points. The process used to obtain them is detailed in Section 6.3.
The implementation of the mesh size entities criterion is simplified if the generalized mesh size points are considered instead of the mesh size entities.
For a given mesh size desired for each volume (considering as the desired size for the ith volume) the following criterion is defined:
RC 3: If an octree cell is an inner cell of the ith volume and its size is greater than , the cell must be subdivided.
The following refinement criterion is widely used in octree based meshers. It limits the number of neighbors of one cell, and it is often referred as constrained two to one condition (Section 3.3). It is an essential criterion for the pattern used for the creation of tetrahedra from the octree leaves:
RC 4: If an octree cell has more than four neighbor cells by face or two by edge, the cell must be subdivided.
The balance criterion gives an upper limit for the size transition: as the size of two neighbor cells differs (at maximum) by a factor of 2, the difference between the size of the tetrahedra generated from those cells is bounded as well. However, it may be required for the final mesh to present a more smooth size transition between regions with small and large elements.
Considering the desired mesh size for given regions of the domain (from the input data), and a given size transition function, an envelope function can be defined to set an upper limit for the element size allowed in each position of the space . The definition if this function is detailed in Section 6.4, and leads to the following refinement criterion:
RC 5: Being the center of an octree cell, if the size of the cell is greater than , the cell must be subdivided.
As explained in Section 3.2, the octree root is the bounding box of the octree. Clearly it should contain totally the domain to be meshed in its interior, but considering the meshing process, it has to accomplish some other requirements.
For the creation of the octree root, the extended bounding box of the model is needed (from now on ). is the minimum bounding box containing the bonding box of the model and all the generalized mesh size points. It has to be noted that the mesh size entities can be outside the domain. The octree root is built centered in the center of , and with a size equal to the maximum size of plus (Equation 5.2). This offset of the octree root with respect to is needed to ensure the tetrahedra creation by the tetrahedra pattern, considering that in some cases this creation involves one cell and its neighbor. A graphical 2D example (quadtree instead of octree) of the and the octree root is shown in Figure 40.
Figure 40: 2D example where the domain is the solid surface. Black dots are the generalized mesh size points. The bounding box of the model is represented by the dotted line. The is the gray line, and the quadtree root is the black square. 
Hereafter, the steps of the meshing algorithm for embedded meshes are presented.
A 2D example of the algorithm is depicted in Table 5.2.4, where each step is illustrated by a figure. The model is formed by two surfaces in contact (drawn in orange and blue), and it contains only two mesh size points (represented by a cross in the figures) in the input data.
1 Process input data and create the octree root. The crosses are the mesh size points. The arrow beside each mesh size point represents its associated size. The octree root is the black square, and the of the model is drawn with dotted lines. in this example coincides with , as it is the largest size coming from the generalized mesh size points, and it is smaller than .  
2 Refine the octree accomplishing the size refinement criteria. In this example the size transition factor is equal to one (the transition corresponds to the constrained two to one condition) to make the figure clearer.  
3 Classify the input boundary entities into the octree. It is important to note that, until now, the input boundaries only have been considered to build the bounding box of the model, but they have not been implied in the octree refinement process.  
4 Create and color the linear octree nodes and compute the distances to the input boundaries. The nodes of the figure are painted with the corresponding color: orange or blue if they are inside the corresponding surface, black if they are onto the input boundaries, and white if the are outside the domain.  
5 Apply the tetrahedra pattern. It can be appreciated in this figure that the final tetrahedra (triangles in this 2D case) are not bodyfitted, as they do not preserve the original shape of the domain. 
Steps followed by the embedded meshing algorithm applied to a 2D example with two surfaces and two mesh size points.
The concept of bodyfitted mesh is applied to a mesh which contours represent precisely the shape of the contours of the domain. Considering the presented algorithm is a volume mesher generating a bodyfitted mesh implies, from the geometrical point of view, that the final tetrahedra mesh must take into account lower level entities: point, line and surface ones.
The adaptation of the final mesh to the surface entities defining the different volumes of the domain plays a key role to ensure the preservation of the topology of the model and the accuracy of the mesh near the contours. This process is detailed in Section 5.3.6.
In the literature, the concept of geometrical features is used to refer the point and line entities relevant for the shape definition of the model, which must be preserved in the final tetrahedra mesh. Point entities to be preserved are the ones where the surface normal has multiple discontinuities and are referred as corners. Line entities to be preserved are the ones shared by two surfaces forming a sharp angle in it and are referred as ridges.
An example of two meshes of the same model (one preserving and the other one not preserving the geometrical features) is shown in Figure 41.
(a) Geometrical model.  (b) Non bodyfitted mesh. 
(c) Bodyfitted mesh.  
Figure 41: Example of bodyfitted and non bodyfitted mesh of a geometrical model of a cone. The non bodyfitted mesh does not preserve the apex of the cone (corner), nor the line entities (ridges) defining its base. 
The preservation of the geometrical features is one of the weak points of the octreebased meshers. As these family of meshers are based in a regular grid (the octree) rather than in the shape of the domain, when the shape of the domain has specific distorted regions in comparison with the octree cells, some strategy has to be followed. One can think that refining the octree in those regions should solve the problem, but this is not true, as some configurations can lead to an infinite refinement process. This is because the geometrical problems governed by angles are reproduced exactly in all the refinement levels.
In this work, not only the geometrical features are taken into account to be preserved in the final mesh, but also forced point and forced line entities coming from the input data, needed to preserve the topology of the model or to provide with specific attached data to the final mesh entities. The generalized concept of forced edges and forced nodes (detailed in Sections 5.3.1 and 5.3.2) is used to include all the line and point entities to be preserved, independently on its purpose: preservation of topology or preservation of geometrical features.
In case the input data for the mesher has forced line entities (from the input data), or a minimum angle for sharp edges is defined, the so called forced edges must be created. These are edges the final tetrahedra mesh will preserve. Forced edges plays a key role for preserving sharp edges and representative surface and line topology.
 
Figure 42: (a) Contours of a volume with some of its sharp edges highlighted. (b) Constrained tetrahedra mesh of the volume highlighting the sharp edges corresponding to the ones in figure (a).(c) Partially constrained tetrahedra mesh of the volume highlighting the sharp edges corresponding to the ones in figure (a). 
At this point it has to be noted that the mesher is partially constrained. In this context, the term partially constrained means that if there are some forced line entities to be preserved, a collection of edges from the final mesh should follow the path of those line entities. This is not as restrictive as totally constrained condition, which would force to have as much edges in the final mesh as the number of forced line entities, and bounded (each one of the edge) by the same nodes bounding the forced line entities.
This difference can be appreciated in the Figure 42, where the definition of a domain is shown with some of its sharp edges highlighted (Figure 42(a)), and two different final meshes of the domain being partially or totally constrained are shown. In this example forced edges come only from the sharp edges of the domain. As it can be seen in Figure 42(b), generating a totally constrained mesh yields a mesh with the same sharp edges present in the input data. In Figure 42(c) it can be appreciated that a different number of edges are generated to represent the initial forced edges: generating a partially constrained mesh, a collection of sharp edges follows the path of the sharp edges present in the input data, so as the shape of the domain to be meshed is well captured.
The creation of the forced edges is based on three steps: identification of the base line entities, creation of the polyline entities and linear mesh generation from the polyline entities:
Note that the base line entities is a collection of line entities in the space, and they can be related or not to the input boundaries of the domain.
In case of non watertight input boundaries, a previous collapse of nodes and edges may be done to the input boundaries in order to be able to capture the sharp edges, as two surface entities forming a sharp edge may not be in contact topologically. This aspect is treated later on.
The result of this clustering operation leads to a collection of polyline entities having each one of them one or more base line entities. Two point entities can be identified as extremes of each polyline entity.
The polyline entities corresponding to the base line entities shown in Figure 43(a) are depicted in Figure 43(b). In this example base line entities and are not part of the same polyline entity because they form a small angle in the common point (smaller than an hypothetical maximum angle for sharp edges).
 
Figure 43: Example illustrating the entities involved in the creation of the forced edges. (a) A collection of base line entities , , , , , , , and . (b) The polyline entities , , , and created from the base line entities shown in Figure (a) considering the angle between and smaller than the maximum angle for sharp edges (from in input data). (c) A possible distribution of forced edges (shown in dotted line) created from the polylines present in Figure (b). 
The discretization of the polyline entities can be done using any mesh generation method. This linear mesh will be used only auxiliary (it will not be part of the final mesh) and its quality is not relevant more than providing a sort of sizes distribution in the octree. In this work a simple recursive splitting method is used to generate the mesh of each polyline entity. The method creates one linear element using the two extreme nodes of the polyline entity, and subdivide it recursively until all the elements accomplish with the three criteria defined above. It has to be considered that each new edge node created when an element is subdivided is mapped onto the polyline entity in order to capture well the shape of it.
The forced edges are directly the elements of the meshes generated from the polyline entities.
Note that the two first steps refer to line entities in general, without specifying if they are CAD or mesh entities. The forced edges created in the third step are always mesh entities.
For notation purposes, the extreme nodes of a forced edge are called edge nodes. Each forced edge has two (and only two) edge nodes, and each edge node can belong to more than one forced edge.
It will be seen later on that the octree cells near a forced edge should have a similar size to it not to produce too distorted tetrahedra. To reach this goal, the forced edge condition has been defined:
Forced Edge ConditionForced Edge Condition
Condition 1: Being cell A the octree leaf containing one edge node of a forced edge, and cell B the octree leaf containing the other edge node of the forced edge, the degree of neighborhood between A and B must be lower or equal than two.
Considering a given configuration of the octree, all the forced edges must accomplish the Forced Edge Condition. If a forced edge violates it, it must be subdivided in other forced edges until all of them accomplish it. The split of the edge is done by its middle point. It has to be taken into account that the subdivision of a forced edge implies the creation of new edge nodes. These ones are mapped onto the polyline entity where the forced edge comes from to yield a better approximation of the shape.
There are some pathological situations for forced edges that can occur due to given configurations of input boundaries:
A possible strategy to solve the first situation is to collapse the line entities with a length lower than a given tolerance, or directly exclude these small ones as forced line entities. Collapsing the small line entities may not solve the problem, because they may belong to a longer polyline entity (also fake) which won't be collapsed. The option of not considering the small line entities also may fail, because there may be some cases where a relevant polyline entity is formed by very small line entities.
For the second situation, a possible solution may be to collapse the line entities which are close enough one from each other. However, these geometrical operations are not trivial in some 3D configurations.
In order to detect the sharp line entities, only the ones belonging to two, and only two, surface entities are considered. Cases where more than two surface entities share a line may be important for the topological definition of the domain. In these cases, the corresponding line entity should be set as forced line entity in the input data, not in the sharp edges detection process. The edges surrounding a gap (in case of nonwatertight boundaries) are not considered to be preserved.
These automatic strategies may not solve all the pathological situations that can occur in the input boundaries. Hence, it may be needed to preprocess them in order to specify the desired forced line entities following given criteria to accomplish the simulation requirements. This is the case of the example shown in Figure 44. The input boundaries of this example are depicted in Figure 44(a). As it can be seen, there are very thin triangles. The normal vector of these triangles is not well computed numerically. When comparing the normal vector of two adjacent triangles, some edges which are not sharp are detected as so. It is the case of the small edges depicted in Figure 44(b).
 
Figure 44: (a) Input boundaries (triangles) of a part of an example model of a mechanical piece. (b) Zoom view of Figure (a), where the shape is smooth enough not to present sharp edges. (c) Same view of (b), showing only the sharp line entities (black lines) automatically detected considering the normal vectors of the triangles of the boundaries (dotted lines surround them in order to highlight their position). As there are very thin triangles, some normal is not well computed, so some of the detected sharp line entities are fake. 
In this example, some of the fake sharp edges (forced line entities) are connected creating the corresponding polyline entity. These polyline entities are not so small, so collapsing the nodes of the small forced line entities will not eliminate these fake ridges: the polyline entity would remain, but with less forced line entities. A possible solution here is to consider only the polyline entities longer than a given tolerance (as the polyline entities useful to define the shape of the domain are much more longer). However, this strategy cannot be applied in general. Some models may not have a so clear separation between the lengths of relevant and not relevant sharp entities.
In cases where the 3D model is not very complex, another option could be to select manually a priori the line entities to be forced ones.
In conclusion: Depending on the quality of the input boundaries of the domain, more information may be needed in order to identify clearly the forced line entities to be preserved by the mesher. In these cases, the geometrical definition of the domain is not enough to set the appropriate forced edges.
The forced nodes are octree nodes (linked to an octree position) with a prescribed position in space: the forced position. The forced position of a forced node is not coincident with the octree position it is linked to. There are three kinds of forced nodes:

(5.3) 
where is a real positive value. The value of must be lower than , otherwise it could lead to inverted tetrahedra (with negative jacobian) when applying the tetrahedra pattern (Section 3.3.3). The tuning of this value is explained in Section 6.7.
The forced position of a forced interface node is the of the octree node it is generated from. It is important to note that the definition of the forced interface nodes depends on the size of the octree cells, so an octree node can be considered as a forced interface node or not depending on the size of the cells surrounding it. It can be seen that refining an octree can lead to the creation or deletion of some forced interface node.
It will be seen in Section 5.3.3 that the forced nodes are involved in an octree refinement criterion (RC 6). To anticipate the general idea, each forced node is linked to an octree position, and each octree position cannot have more than one forced node associated. So if two forced nodes are very close one from each other, the octree cell containing them should have a size similar to the distance between them. This could lead to an excessive level of refinement of the octree, specially in cases where there are nonwatertight definitions of the boundaries.
In extreme cases where the forced nodes can be almost exactly in the same position, the refinement criteria could lead to an infinite level of refinement. To solve this problem, the forced nodes which are closer than a given tolerance (a portion of the mesh desired size) are collapsed. It has to be considered that if two forced nodes are collapsed and they belong to a forced edge, it must be collapsed as well.
All the size refinement criteria (the ones applied for embedded meshes, detailed in Section 5.2.2) are also applicable to bodyfitted meshes, as they are based on the desired mesh size.
In this section the specific refinement criteria (RC) needed for bodyfitted meshes are defined. Some of them may not be applied in the meshing process depending on the input parameters.
These refinement criteria are a key point for the bodyfitted mesher, as they ensure the geometrical features of the domain and its topology will be preserved by the tetrahedra generated from the octree.
The following criterion refers to the forced nodes. As it has been explained in Section 5.3.2, each forced node is associated to an octree cell position.
RC 6: If an octree cell has a forced node inside, and the octree position associated to that forced node is occupied by another forced node, the cell must be subdivided.
In order to ensure that this refinement criterion does not lead to an infinite level of refinement, the distance between forced nodes must be greater than a minimum value, corresponding to the minimum cell size allowed in the octree. The fulfillment of this condition involves a treatment of the forced nodes before the refinement criterion: if two forced nodes are closer than the minimum cell size allowed in the octree they are collapsed into one. If they are part of a forced edge, the forced edge is also collapsed.
For the refinement criteria defined hereafter, the tetrahedra created from the octree following the tetrahedra pattern are considered. For this reason, these criteria only take sense if the RC 4(balance) and RC 6(forced nodes) are accomplished. From now on the concept of the tetrahedra created from an octree cell is used to refer the tetrahedra result from applying to the cell the patterns defined in Section 3.3.3.
The quality of the tetrahedra generated from cells without forced nodes is very high (and it can be evaluated a priori), but the presence of forced nodes implies that their positions in space are not the octree positions, so the tetrahedra generated may be distorted.
Figure 45: Tetrahedron with the local node numeration following the right hand rule. Vectors involved in the definition of an inverted tetrahedron are depicted. 
The concept of inverted tetrahedron must be defined at this point in order to introduce the following refinement criterion. Considering a tetrahedron with its nodes , , and sorted in a given way (as the tetrahedron depicted in Figure 45), it is inverted if the scalar product of x by is negative. , , and are vectors aligned with the directions , and respectively, oriented from towards the other nodes. In the case where the scalar product is null, the tetrahedron has zero volume and receives the name of sliver.
RC 7: If a tetrahedron created from an octree cell is inverted or a sliver, the cell must be subdivided.
The following refinement criteria are the basis to ensure the preservation of the topology for the mesher. Some auxiliary definitions are needed here. If we consider an edge of a tetrahedra generated from a cell, a limit distance of the edge is defined as

(5.4) 
where is the length of the edge and is a real value between zero and one (the value taken for this parameter is detailed in Section 6.7).
The so called intersection points of an edge are the intersection points between the edge and the input boundaries. As an intersection operation between an edge and surface entities, the following situations must be considered (see also Section 3.4):
If we define the portion of a given volume enclosed in an octree cell delimited by the input boundaries and the cell faces, the interface cells can have several portions of volumes. Let us name face limit surfaces to the boundaries of these portions of volumes laying onto the the cell faces. An example of the portions of volumes of a cell is shown in Figure 46.
Figure 46: Example of portions of volumes enclosed in an octree cell. Volume lies onto one face of the cell creating one face limit surface, volume does not lay onto any face of the cell, volume lies onto three faces of the cell creating three connected face limit surfaces, and volume lies onto two faces of the cell creating two unconnected face limit surfaces. 
RC 8: This criterion is split in three levels:
then the cell must be subdivided.
The implementation of these refinement criteria is detailed in Section 6.5.
Examples of different configurations of an edge fulfilling the refinement criterion 8(a) are shown in Figure 47.
(a)  (b) 
(c)  (d) 
Figure 47: Different configurations of the edge that force the refinement of the octree in order to accomplish the refinement criterion 8(a). Dotted line represents the input boundaries and crosses are the intersection points between the edge and the input boundaries. (a) Both and nodes are forced nodes and there are more than one intersection point. (b) is a forced node ( could be forced node or not), and there is an intersection point closer than to it. (c) there are two intersection points and the distance between them is lower than . (d) There are more than two intersection points. 
An example of a pathological configuration where the refinement criterion 8(b) is needed is the portion of volume of Figure 46. On the other hand, the portion of volume of the same figure evidences the need for the fulfillment of the criterion 8(c) in order to preserve the topology of the input data.
Hereafter, the steps of the meshing algorithm for bodyfitted meshes are presented:
This step implies the coloring of the appearing octree nodes. RC 4 (balance) has to be also taken into account during this refinement process, as it is mandatory for the tetrahedra generation following the given patterns.
From now on, the octree structure is frozen in the sense that its cells will not be refined any more.
Note that the refinement process involved in the fifth step is an iterative process. Every time an octree cell is subdivided, several aspects have to be considered in the new configuration of the octree:
All this aspects may force the subdivision of other cells due to the other refinement criteria, so an iterative process is required in order to achieve an octree configuration where all the refinement criteria are accomplished. However, in our experience, few iterations are enough for satisfying all of them. The implementation of the algorithm is detailed in Section 6.5.
Another important characteristic of the algorithm is that the first six steps are based on the octree, while from the seventh step onwards, the operations are applied to the unstructured tetrahedra mesh.
A graphical example of the steps of the meshing process is shown in Table 5.3.4 using a 2D model to make the figures more understandable. In the first figure, the offset between and the octree root should be equal to , but it has been put smaller to make the following figures clearer.
It also has to be considered that some of the parts of the algorithm are intrinsically 3D (such as the process to preserve forced edges), so they cannot be illustrated with a 2D model. This example is formed by two surfaces and it has no mesh size information in the input data. It is important to note the presented algorithm is able to generate a bodyfitted mesh with the only information of the input boundaries.
1 Process input data and create the octree root. The red small squares represent forced points. The octree root is the black square, and the of the model is represented with dotted lines. In this example coincides with the minimum side of the model bounding box (), as there are no mesh size points.  
2 Refine the octree accomplishing the size refinement criteria. As there are no mesh size point in the model, the octree is refined uniformly with .  
3 Classify the input boundary entities into the octree. It is important to note that until now, the input boundaries only have been considered to build the bounding box of the model, but they have not been implied in the octree refinement process.  
4 Color the octree nodes and set forced interface points. The nodes of the figure are painted with the corresponding color: orange or blue if they are inside the corresponding surface, black if they are close enough to the contour entities to be forced interface nodes. Nodes outside the domain are white.  
5 Refine the octree according with the bodyfitted refinement criteria. It can be appreciated that the octree refinement process leads to the creation of new octree nodes. Some of them become forced isolated nodes (red ones) or forced interface nodes (black ones). The arrows indicates the forced position of each forced node.  
6 Apply the tetrahedra pattern. The tetrahedra are generated from the octree nodes. From this step on, the operations are performed to the corresponding tetrahedra mesh rather than the octree one.  
7 Preserve geometric features. At this point forced nodes are moved into their forced positions. As a 2D example, only the moving of forced nodes can be appreciated in the figure (the preservation of edges has no sense in 2D).  
8 Surface fitting process. This is the last step of the process which ensures the final mesh could represent the original topology of the input boundaries.  
9 Tetrahedra coloring and identification of skin mesh. Elements owning to the orange or blue surface are painted accordingly in the figure. After this process the outer elements can be deleted.  
10 Makeup and smoothing. In this step some mesh editing operations are done in order to improve the mesh quality. 
Steps followed by the bodyfitted meshing algorithm applied to a 2D example with two surfaces with no mesh size assigned.
The preservation of geometrical features (corners and ridges) lies on the preservation of forced nodes (Section 5.3.2) and forced edges (Section 5.3.1).
The operations described in this section are performed after the creation of tetrahedra from the octree leaves following the tetrahedra pattern (Section 3.3.3), so at this point there are forced nodes, forced edges and a tetrahedra mesh got directly from the octree cells. This tetrahedra mesh covers the domain to be meshed, but does not preserve the geometrical features and does not fit the surface entities representing the interfaces between volumes (there are nodes outside the domain and tetrahedra with edges crossing volume interfaces). The aim of this process is that the tetrahedra mesh has nodes in the corresponding positions of the forced nodes, and edges corresponding to the forced edges.
Each forced node has an octree node associated to it. The process of preserving the forced nodes is reduced to move the corresponding octree nodes to the position of its forced node.
(a)  (b) 
Figure 48: Process of splitting a forced edge by inserting a node onto its base line. (a) Forced edge to be split by the node ; the dotted line is the base line of the forced edge. (b) Forced edges and result from splitting the forced edge by the node ; dotted lines are the corresponding base lines of the forced edges. 
Concerning forced edges, the goal is to force the tetrahedra mesh to have edges coincident with them. As explained in Section 5.3.1, the forced edges are obtained as a linear mesh from the polyline entities. The portion of polyline entity enclosed between the extreme nodes of a forced edge can be defined as the base line of the forced edge. Note that this is a pure notation, as the polyline is made of generic line entities (in mesh or geometrical format). For notation purposes, a forced edge will be defined by its extreme nodes: the forced edge is the one which extreme nodes are node and node . The same notation is used for a generic edge of a tetrahedron.
From now on the concept of fitting the tetrahedra mesh to the forced edges is used to define the process of having an edge of the tetrahedra mesh for each forced edge. To achieve this goal a splitting process of forced edges and tetrahedra is proposed. This process involves three basic operations:
 
Figure 49: Process of splitting tetrahedra by a node. (a) Edge to be split by the node , with its surrounding tetrahedra around (4 in this example). (b) 8 tetrahedra result from splitting the edge by the node . (c) Face to be split by the node , with the two tetrahedra sharing the face. (d) 6 tetrahedra result from splitting the face by the node . 
Hereafter the process needed for fitting the tetrahedra mesh to the forced edges is detailed. For each forced edge we check whether nodes and are nodes of a same tetrahedra or not. In case they are, the tetrahedra mesh has an edge coincident with the forced edge, so the objective is already achieved. In case there is no tetrahedra containing nodes and , the following procedure must be considered (a graphical example of the steps followed to fit the tetrahedra mesh with a forced edge is shown in Table 5.3.5):
Figure 50: Entities involved in the process of making the tetrahedra mesh to have an edge coincident with a forced edge. Red line is the forced edge and the dotted red line is its base line. The tetrahedron is the tetrahedron surrounding node which opposite face with respect to () is intersected by the base line. Face is the (drawn in yellow). is the intersection point between the base line and . The closest node of to is , and the closest edge from to is the edge . 
Note that the nodes created in this process are not octree nodes, as they are not related with any octree position. Furthermore, these nodes do not need any coloring algorithm, as they lay on a interface entity.
(a) Initial configuration of the forced edge (red line) with its surrounding tetrahedra (in blue), and its base line (dotted red curved line).  
(b) Find the tetrahedra () owning node which opposite face to it () intersects the base line of forced edge . is the intersection point.  
(c) As is not close enough to , or , and neither to the edges of face , create the node in the position of and split the face and the forced edge by the node . Now the forced edge is already an edge of the tetrahedra mesh.  
(d) Proceed the treatment of forced edge . Find the tetrahedra () owning node which opposite face to it () intersects the base line of forced edge. is the intersection point.  
(e) As is close enough to (closer than times the minimum edge of ), move to the position of and split forced edge by node . Now the forced edge is already an edge of the mesh.  
(f) Proceed the treatment of forced edge . Find the tetrahedra () owning node which opposite face to it () intersects the base line of forced edge. is the intersection point.  
(g) As is close enough to edge (closer than times the minimum edge of ), creation of node in the position of and split of edge and the forced edge by the node . Now the forced edges and are edges of the mesh, so the process is finished.  
(h) Final configuration of the tetrahedra with the new forced edges created: , , and . 
Example of the process to fit a tetrahedral mesh with the forced edge .
This section describes the process of fitting the tetrahedra mesh into the volumes of the domain to be meshed, representing their interface surfaces accurately (from now on surface fitting process). The methodology presented is applied to the tetrahedra mesh (come from the tetrahedra pattern defined in Section 3.3.3), in which the process of preserving geometrical features (defined in Section 5.3.5) has been carried out. Some of the nodes of the mesh are forced nodes (fixed in a position in space) and some of its edges are coincident with the forced edges. The process defined from now on preserves the forced nodes as well as the edges corresponding to the forced edges.
The surface fitting process is based on the isosurface stuffing method published in [37] (from now on isostuffing method). However, it has some differences, as its objectives and restrictions are different:
An example of tetrahedra mesh generated using the isostuffing method is shown in Figure 51. It can be appreciated that the sharp edges relevant for the definition of the shape of the model are not preserved by the mesher.
(a)  (b) 
Figure 51: Example of a 3D model of a mechanical piece (a) and a tetrahedra mesh of it generated using the isostuffing method (b). 
The surface fitting process is based on the edges of the tetrahedra mesh which are not forced edges: the isoedges. It consists in the following steps:
Some of the edges can intersect more than one time the input boundaries, but not more than two due to the topology criterion (a). In these cases with two intersections only one of them is taken into account (no matter which one). From now on we only take care of the edges intersecting the input boundaries; the ones that do not intersect them are taken out from the isoedges.

where the distance between and , and the length of the edge . The parameter is a real value between zero and one. The value used in the algorithm is explained in Section 6.7. This process of moving the node is only performed if the resulting configuration does not generate poor quality tetrahedra.
Moving a node implies to recompute the possible intersection points of all its connected edges, as one of their extremes is moved. This leads to an iterative process where new edges can be added to the isoedges, and some existing one can be taken out (the ones with no intersection point). A 2D example of a situation where the movement of a node creates a new intersection point is shown in Figure 52.
(a)  (b) 
Figure 52: 2D example of creation of a new intersection point when moving a node. Black line represents the input boundaries, and part of the triangle mesh is shown in blue. (a) Initial configuration: node is close enough to intersection point , so it is moved. (b) Final configuration after moving : the new intersection point has appeared. 
(a) Initial configuration of the mesh before surface fitting process.  (b) Detection of the intersection points (red dots). Nodes and are close enough to its closest intersection points (red circumferences) to be moved. 
(c) Mesh configuration after moving points and . Some intersection point have disappeared and a new one have appeared. Light gray lines represent the mesh in the previous step.  (d) Splitting process by the intersection points. Dotted lines are the new edges created. There is an edge with two intersection points ( and ). Node has been used for the splitting ( could be used as well). Edges in gray represent outer edges with no intersections. 
(e) Second iteration. As there are no nodes to be moved, edges with intersections are split. There is an edge with three intersection points. Point is chosen (arbitrarily) for the splitting.  (f) Final configuration of the mesh. 
The accomplishment of the topology criterion (a) allows the presence of edges intersecting twice the domain in the mesh coming from the tetrahedra pattern. For this reason the moving and splitting process has to be applied the second time to the isoedges (step 4). The involved isoedges this second time have at least one of their nodes onto the input boundaries (as they have already been processed the first time).
A 2D example applying two times the process of moving nodes and splitting edges is shown in Table 1.
(a)  (b) 
Figure 53: Example of mesh generated applying (a) or not applying (b) the process of moving nodes and splitting edges the third time. It can be appreciated in Figure (a) that the topology of the mesh near a forced edge does not represent well the topology of the domain. 
For pathological situations, applying a third time the process of moving nodes and splitting edges is needed (step 5). These pathological situations happen when some of the new edges created in the previous steps has an intersection point relevant for the topology of the mesh. These cases occur near sharp edges, so the isoedges involved are only the ones connected to a forced node in edge. An example is shown in Figure 53, where the difference between applying or not the moving and splitting process the third time can be appreciated. If there were not forced edges it will not be needed to repeat a third time the moving and splitting operations, because a set of tetrahedra would already represent topologically well each volume of the domain.
One can think about repeating the process of moving nodes and splitting edges as many times as needed until the mesh does not present any intersection point. This is not feasible as it could lead to almost infinite loops (in some configurations with curved input boundaries). Also, each time it is applied, the new elements will have worse quality.
As explained before, the process of moving nodes may create new intersection points. Also the splitting process can create more of them, as it implies the creation of new tetrahedra with the corresponding new edges. The new edges created may have more than two intersections with the input boundaries, but these intersection points are not relevant to preserve the topology of the volumes, so it is not needed to take them into account.
A 2D example of the described surface fitting process is depicted in Table 1. In this example, the process of moving and splitting could be repeated more times, as there are more intersection points (in edge of the mesh shown in (f)). However, the topology of the input boundaries is already well represented, so no more iterations are needed.
Once the surface fitting and preserving features operations have been performed, the mesh is in the following situation: it is ensured that the tetrahedra represent the topology of the input boundaries, and all the nodes of the mesh are colored (it is known if they are inside a volume or onto interfaces between volumes). Now the operation of tetrahedra coloring must be done: this is, assign a volume to each one of the tetrahedra. In this work the concept of assigning a color to an entity is used to determine inside which volume the entity is, so color and volume are used indistinctly.
The tetrahedra to be colored can present two basic situations:
Tetrahedra presenting the first situation are obvious to be colored. Because of the topological refinement criteria and the surface fitting properties, it is ensured that there is no edge of the the tetrahedra with nodes inside different volumes. This implies the tetrahedra belongs to the same volume of the inner node.
The second situation (interface tetrahedra) is much more complicated to solve. It has to be noted that each node of an interface tetrahedra is interfacing a number of volumes; they are the so called possible volumes of a node. Considering the forced edges lying on an interface between volumes, the concept of possible volumes of a forced edge can be defined analogously as for the nodes.
The possible volumes of each tetrahedron are clearly identified: they are the volumes which are interfaced by all the nodes of the tetrahedron. There are some configurations under which the color of an interface tetrahedron can be determined. This is the case where the tetrahedron has only one possible volume. The rest of interface tetrahedra are considered as undetermined ones; these are the cases that must be solved.
Figure 54: 2D example of a triangle mesh of two surfaces: A (blue) and B (orange). Elements containing node are directly colored as , as is a inner node to A. The other triangles are interface elements. Elements and are undetermined, as they have two possible colors: and (exterior). 
A 2D example of these different types of elements (in terms of coloring process) is shown in Figure 54. Here the mesh for two surfaces ( in blue and in orange) is shown. All elements containing node belong to surface , as is an inner node to . The other elements are interface ones. The possible colors of each one of the interface nodes are listed in Table 2 (note that the outer part of the domain is considered as color zero):
Node  Possible colors 
E  , 
F  , , 
G  , 
H  , 
J  , 
K  , 
L  , 
N  , 
P  , , 
Considering the interface elements, their possible volumes can be easily gotten analyzing the common possible volumes of each one of their nodes. They are depicted in Table 3.
Element  Possible colors 
ELF  
FLG  
HGJ  , 
JPK  , 
JLP 
It can be seen that the elements and are undetermined in this example, as they can belong (topologically) to surface or the outer part of the domain indistinctly.
As each undetermined tetrahedron has more than one possible volume, there are several possible configurations of colors for them. A configuration is understood as the assignment of a color to each one of the undetermined tetrahedra. It has to be noted that the triangles of the skin meshes of each volume are the faces of the tetrahedra shared by tetrahedra of different color, so each configuration of colors lead to a different tetrahedra skin mesh. Taking care about the topology of the input boundaries, the final configuration of colors has to accomplish the following conditions to be considered as valid:
The accomplishment of these conditions can reduce to one the possible colors of some tetrahedra. In this cases, these ones would not be undetermined. However, other tetrahedra may remain undetermined.
A good 2D example of undetermined elements considering only two different colors (interior and exterior) is shown in the (f) figure of Table 1 (see page current). The triangles , , , , , and have all their nodes in the boundaries. , and are not undetermined elements, as they can only be colored as inside the surface taking into account the first condition defined above: if they were colored as outside, nodes , and respectively won't have any element inside the surface, and they are nodes interfacing the surface and the outer part. Then, in this example, the elements , , and are the undetermined ones. These elements could be colored as interior or exterior each of them, and both situations may lead to topologically correct meshes. This example shows that the problem of coloring the undetermined tetrahedra has more than one solution, and it is not obvious (actually, in some cases it is impossible) to determine whether a solution is better or worse than another.
(a)  (b) 
Figure 55: 2D examples of pathological configurations for element coloring. Both cases are taken from the mesh shown in (f) figure of Table 1. (a) The element is a triangle of the surface, but its center (white dot) is outside it. (b) The element could be colored as inside or outside of the surface; the oriented normal vectors in nodes , and does not point to the center of the element. Black arrows are the oriented normal vectors towards the surface, and the white dot is the center of the triangle. 
A possible strategy for the tetrahedra coloring should be to assign the tetrahedra the color of their center using the node coloring technique explained in Chapter 4, but this can lead to wrong decisions as there are several pathological configurations where the center of an element of a volume is not inside it. This is the case of triangle in (f) figure of Table 1. A zoom of this triangle is shown in Figure 55(a): is topologically a triangle of the surface , but its center is outside it.
Another possible strategy for undetermined tetrahedra should be take care about the normal vectors of the interface surface entities in the nodes of the tetrahedra. This normal vector can be oriented in the sense that it can be determined which volume it is pointing to (between the volumes interfaced by the surface entity). The notation oriented normal to a volume V is used from now on to indicate the normal vector of a surface entity pointing towards the volume V.
The computation of the normal of a surface of the volume is not obvious taking into account that the contours of the domain can be nonwatertight. We are leaving this aspect unsolved by now, and let us suppose the oriented normal vectors can be created. One could think about situations which the oriented normal vectors can determine whether the color of a tetrahedron is one or another depending on where they are pointing to. For example: the cases where the four normal vectors of an interface tetrahedron (one for each node) oriented to a given volume are pointing at the center of the tetrahedron could be considered as determined: the color of the tetrahedron should be the volume one. (In this context, point to the center of a tetrahedron means that the center is in the semispace defined by the oriented normal vector).
Unfortunately, not all the tetrahedra accomplish with this condition, so there may still be some undetermined tetrahedron. This is the case presented in Figure 55(b): it is a 2D case where it can be seen that the oriented normal vectors to the surface in the nodes of the element are not leaving the center of the element in the same semispace.
Furthermore, the same topological situations can be represented by different volume boundaries which present a drastically different configuration of normal vectors in the nodes of the elements. This is the case shown in Figure 56, where different interfaces between surface and present the same element with the normal vectors in two of its nodes identical, and the third normal different for each shape of the boundaries. This 2D example demonstrates that the process of tetrahedra coloring cannot be based on the normal vectors of the interface entities in the nodes of the elements. It has to be taken into account that in 3D the possible configurations are much more complicated than in 2D.
(a)  (b)  (c) 
(d)  
Figure 56: 2D example. The black curved line represent the interface between surfaces and . (a), (b), (c) and (d) represent different shapes of the interface. In all the cases an undetermined triangle is depicted and the vectors are the normal vectors pointing to surface . As it can be seen, in all the cases the element should be colored as inside surface . The normal vectors in two of the nodes are identical for all the cases, and the third (the upper one) is different in all of them. 
The reason why the two strategies defined above fail is they are based on geometrical conditions, and the problem to solve is more topological than geometrical. The color of an undetermined tetrahedron is independent on the percentage of the element inside or outside a volume: it is determined for topological conditions (the ones defined previously). To take care about the topology, a strategy is proposed to color the undetermined tetrahedra starting from the tetrahedra with known color. It is based in the following proposition:
Proposition 1: Considering an undetermined element and an element of color which is neighbor of by face . Being the node of opposite to face , if there is a point inside volume laying on face , and a continuous curve in space from to completely inside element with no intersection with the boundaries of A, then the color of is .
A graphical view of this proposition in a 2D case is shown in Figure 57. In this example the element is undetermined, as all its nodes are on the interface between surface and the outer part of the domain. All the other elements are fully determined (they belong to surface ), as they contain node , which is inner to . Point is inner to , and it lays on the face shared by elements and . As it exists a continuous curve (shown in dotted red line) from to , totally inner to element and with no intersections with the boundaries of , element can be considered inner to surface . It has to be noted that this process imply the coloring process of point , which is done following the algorithm described in Chapter 4.
Figure 57: Graphical interpretation of Proposition 1 in a 2D example. The black line represents the contour of surface , and its triangle mesh is represented by blue lines. 
Proposition 1 is used to color the undetermined tetrahedra (the implementation of the algorithm is detailed in Section 6.5). However, it cannot be applied in some cases as the ones where an undetermined tetrahedron has no neighbor by face with a determined color, or the cases where the points in the common face are onto a surface entity (they are not inner to a volume), or the coloring process of these points fails. Another case where the proposition cannot be applied is when the volumes involved are nonwatertight. For this reason, it has to be planned that after this coloring process some undetermined tetrahedra can still remain. From now on the methodology to color the remained undetermined tetrahedra is explained.
As it can be seen, the coloring of one tetrahedron can affect the coloring of its neighbors, as the skin of the tetrahedra changes and can affect the manifold condition of each node. However, each tetrahedron affects only to its neighbors, so there can be defined different clusters of undetermined tetrahedra which are independent one from each other; these clusters are made by the undetermined tetrahedra connected at least by one node. As an example, the clusters of undetermined tetrahedra of the mesh in figure (f) of Table 1 are identified in Figure 58. As these clusters are independent one from each other, the methodology presented can be applied on a cluster by cluster manner.
Figure 58: Two clusters of undetermined elements (blue and orange) of the mesh shown in (f) figure of Table 1. 
Considering all the undetermined tetrahedra of a cluster, each of them has its possible colors. All the possible color configurations can be obtained, and each one of these configurations implies a different skin mesh of each volume's tetrahedra. Checking the topological conditions that must be accomplished (detailed previously in this section) for the final mesh, some of the configurations are not valid, and some of them are valid. For the tetrahedra coloring purposes, any one of the valid configurations is set as the solution.
As an example, lets see the case of the orange cluster of undetermined elements shown in Figure 58. It is made of two elements: and . Each of them has two possible colors: inside or outside the surface. All the different configurations are shown in Figure 59. The configuration shown in Figure 59(a) is not valid because the topology of the final mesh is not the same as the one of the surface it is representing (the mesh has two unconnected sets of elements). The configurations of Figure 59(b) and (c) are not valid because they have nonmanifold nodes in regions where the contour of the surface is manifold (node in case (b) and node in case (c)). The only valid configuration is the one shown in Figure 59(d).
 
Figure 59: Zoom of the orange cluster of elements in Figure 58. All the possible configurations taking into account the different colors (inside or outside the surface) of elements and .(a) Both elements are outside the surface. (b) is outside and inside. (c) is inside and outside. (d) Both elements are inside. 
The makeup and smoothing operations are used to improve the quality of the mesh once it has been generated. Makeup operations are the ones changing the topology of the mesh, and smoothing process only implies movement of the nodes, maintaining the original connectivity of the elements.
The acceptable quality of the mesh elements is a relative parameter, as the mesher aims to be applied to different kinds of numerical simulations, and they are applicable in different ranges of qualities for the elements [5]. A clear example of this is the boundary layer meshes, which elements should have an aspect ratio higher than 10000 in some cases; such distorted elements are not valid for standard FEM analysis. However, almost all the methods require noninverted elements. This means that the Jacobian of the transformation of the element (from the parametric to the 3D space) should be positive. This lead to require, at least, a strictly positive Jacobian in the elements of the final mesh. A graphical interpretation of an inverted element is provided in Section 5.3.3.
In this section there are references to tetrahedra, triangles and edges. Edges are edges of the tetrahedra elements, and triangles are considered as the faces of the tetrahedra interfacing tetrahedra of different color. Thus, each volume tetrahedra mesh is surrounded by a triangle mesh.
Considering the mesh generated may have forced nodes and forced edges, there are some restrictions to be applied to the makeup and smoothing operations:
From now on, the operations involving the collapse of an edge, or the movement of a node are only applied to the entities not violating these restrictions. It has to be taken into account that the collapse operation involves the deletion of one of the two nodes involved.
The elements obtained from the tetrahedra pattern defined in Section 3.3.3 have very good quality if the nodes are in the octree positions (see Section 3.3.2), so the makeup and smoothing operations are only needed for the tetrahedra containing a forced node, the ones coming from interface cells and the ones resulting from surface fitting or preserving features operations.
The parameters and (Section 5.3.5) try to guarantee a minimum quality in the tetrahedra resulting from the preserving features process, and tries to do the same for surface fitting operations. However, some configurations of the mesh and the input boundaries may lead to low quality elements. This situation often causes the presence of small edges in the mesh. An example of these small edges is shown in Figure 60(a). To improve the quality of the elements surrounding these small edges, an edge collapsing step is performed (makeup operation). Taking into account that the octree cell containing each node gives an idea of the mesh size required for the mesh in that region (because of the user desired sizes or as a result of a topological refinement process), the edges smaller than a given portion of the size of the cell they are inside are collapsed. An edge is collapsed if it does not violate the restrictions defined at the beginning of this section and

(5.5) 
where is the size of the smaller octree cell between the ones where the extreme nodes of the edge are inside, the length of the edge and is a real value greater than zero. Its value is discussed in Section 6.7.
(a)  (b) 
Figure 60: Example of a mesh (a) before and (b) after the makeup and smoothing process. 
The smoothing operation applied consists in a Laplacianlike smoothing that displaces a node into a position such that its surrounding elements improve their quality. The smoothing process is applied on a node by node basis, and follows these steps:
This process implies the definition of a quality measure of the elements, as well as a procedure to obtain the candidate position. As a quality measure, the minimum dihedral angle of the tetrahedra has been chosen, considering that a tetrahedra is worse than another one if it has a lower minimum dihedral angle. The election of the candidate position is explained later on.
It has to be noted that the mesh can have three kinds of elements: tetrahedra, triangles and linear elements (corresponding to the forced edges). All the nodes have tetrahedra around them, but only some of them have triangle or linear (1D) elements. Taking into account the restrictions defined in the beginning of this section, the degrees of freedom for moving a node are restricted by its nature: if it is a forced node in edge, it can only move along the polyline entity corresponding to the forced edge, and if it is a forced interface node it must lay on the surface entity it belongs to. This aspect governs the candidate position for each node:
As the movement of a node affects the quality of all its surrounding elements, the smoothing operation is thought as an iterative process where several loops over all the nodes are performed in order to improve the quality of the mesh.
Apart from edge collapsing and nodes smoothing, the edge flipping operation (a makeup operation) is performed in the mesh [55]. The cases 2 to 3, 3 to 2, 4 to 4 and 5 to 6 are implemented. These operations imply the removal of a face (the first case) creating an edge, or the removal of an edge (the other cases) creating some extra faces. Apart from the pathological configurations described in [55] which determine the situations where the edge flipping cannot be made, some topological configurations must be considered in order not to invalidate the topology of the mesh generated. In particular, the following restrictions are considered:
The collapse, edge flipping and smoothing operations are applied in a sequential iterative manner to account for the updated configurations of the mesh each time. A maximum of four iterations is set in the present work. The result of applying them to the mesh shown in Figure 60(a) is depicted in Figure 60(b). In Chapter 7 several examples are shown indicating the mesh quality before and after the makeup and smoothing operations.
This section focuses in the analysis of the quality of the final mesh generated by the new mesher.
For the embedded mesher, the quality of the mesh is totally guaranteed, as all the tetrahedra come directly from the predefined patterns. However, for the bodyfitted mesher, it has to be considered that a bodyfitted mesh is forced to respect the boundaries of the domain. If a part of the domain is bounded forming a very small dihedral angle, the tetrahedra representing it will have the same dihedral angle. This limits the scope of minimum quality guarantee to the inner parts of the domain, or the boundaries which are relatively smooth.
The tetrahedra of the inner parts of the domain come directly from the predefined patterns, so they have a very good quality. Their minimum dihedral angle is degrees (Section 3.3.3). For the tetrahedra near the boundaries there are several aspects that make impossible to ensure a minimum quality for the elements in the final mesh:
For all these aspects, although the makeup and smoothing operations described in Section 5.3.8 reach an acceptable quality for the meshes generated, a given minimum element quality cannot be guaranteed theoretically.
As explained in Section 1.2.4, a secondary objective of the present work is to be able to apply the octree mesher to the meshing of surfaces not belonging to any volume. In this section the concept of inner surface is used to refer a surface entity not belonging topologically to the boundaries of a volume. It can be inside or outside a volume. From the mesher point of view this difference takes no sense as the outer part of the model is considered as volume zero.
Taking into account the new mesher can provide with the surface mesh corresponding to the boundaries of a volume, it could seem that it can be applied directly to an inner surface. Actually, after the surface fitting process there are tetrahedra at both sides of the inner surfaces that conform to them. However, the faces of the tetrahedra which form the triangle mesh of the inner surface cannot be detected in the same way as the surface entities boundary of a volume (regural surface entities).
Extracting the surface mesh of a regular surface entity is automatic after the process of tetrahedra coloring (described in Section 5.3.7): the triangles of the surface entities are the faces of the tetrahedra interfacing two tetrahedra of different color. In the case of inner surfaces, tetrahedra at both sides of the triangles have the same color, so the same strategy cannot be applied. Some modifications have to be performed in order to detect the triangle mesh of an inner surface.
At the time of extracting the surface meshes of the inner surfaces all the tetrahedra have been generated, the processes for preserving geometrical features and surface fitting have been carried out, and the tetrahedra have been colored. At this point, there are already tetrahedra faces corresponding to the triangles of the inner surface mesh, but they have to be detected. This situation is illustrated in Figure 61(a) using a 2D example (an inner line and the surrounding triangles is used instead of an inner surface and the surrounding tetrahedra).
(a)  (b) 
(c)  (d) 
Figure 61: 2D example of the steps for detecting the line elements of an inner line. (a) Initial configuration: elements at both sizes of the inner line. Thick black line is the inner line and the mesh is in blue. Black dots are forced nodes in interface or in edge. (b) All the candidate 1D linear elements in dotted black lines. (c) Candidate 1D linear elements (in black) accomplishing the topological properties set to definitive. (d) Final mesh (in black) for the inner line once the remaining invalid candidate linear elements have been discarded by Proposition 2. 
A first consideration must be done: all the triangles in the mesh of a surface entity have their nodes laying on it. This means that the nodes of those triangles are forced nodes in interface or in edge. The tetrahedra faces with this characteristics (all their nodes being forced nodes in interface or in edge) are called candidate triangles. In Figure 61(b) the candidate linear elements (in 2D there are candidate 1D linear elements instead of candidate triangles) of the configuration shown in Figure 61(a) are depicted in dotted lines.
Considering all the candidate triangles of an inner surface, some topological properties analogous to the ones made in the tetrahedra coloring strategy can be done. If a node is inside a surface entity, the surface mesh around it must be manifold (let us call it a manifold node). This implies that there should be a closed loop of triangles surrounding it in the mesh of the surface entity. If there are a closed loop of candidate triangles around a manifold node, and they are the only candidate triangles containing the node, they can be set as valid (triangles belonging to the inner surface final mesh). Also the requirement for every forced node in interface or in edge to belong at least to one triangle of the final mesh can be used: if one of these nodes belongs to one candidate triangle only, this one must be valid. For the case shown in Figure 61(a), the candidate elements set as valid considering these topological properties are depicted in Figure 61(c).
However, this topological properties may not solve the problem of detecting all the triangles of an inner surface mesh, as there are nodes which are not needed to be manifold (the ones in edges), and there may be triangle configurations around manifold nodes which are not manifold. This leads to the need for another strategy to detect the right triangles among all the candidate ones. The strategy proposed is based on disregarding the wrong candidate triangles, rather than detecting the right ones, using Proposition 2. It is based on Proposition 1 (defined in section 5.3.7 for tetrahedra coloring), but with slight modifications:
Proposition 2: Consider a candidate triangle of an inner surface and the two tetrahedra around it and . Being and the nodes of and not belonging to , if there is a point inside triangle and a continuous curve in space from to passing through completely inside the union of and with no intersection with , the candidate triangle is invalid.
A graphical view of this proposition(using a 2D case) is shown in Figure 62.
(a)  (b) 
Figure 62: Graphical interpretation of Proposition 2 in a 2D example. Black line represents the inner line (). Triangle mesh is represented by blue lines and the candidate linear element to be checked () is the dotted line. (a) The candidate linear element is invalid, because there is a curve (in red) not intersecting the inner line. (b) The candidate 1D linear element cannot be set as invalid because all the possible curves intersect the inner line. 
In Figure 62(a) the candidate 1D linear element is set as invalid because there is a curve (drawn in red) accomplishing Proposition 2. Figure 62(b) shows that there could not be any curve accomplishing the proposition, so the candidate linear element cannot be set as invalid.
Once all the invalid candidate triangles are disregarded using Proposition 2, the rest of the candidate triangles are the ones corresponding to the final mesh of the inner surface (Figure 10(d)).
Note that this proposition can set as invalid some correct triangle in some cases, specially when the the surface entities are curved. Some improvements should be applied to the algorithm to be more robust in some pathological configurations.
The implementation of the algorithm defined for extracting the mesh of an inner surface is detailed in Section 6.5.4.
This chapter details all the implementation aspects relevant for the meshing algorithm described in the previous chapters. The specific implementation of the ray casting technique used for the nodes coloring is explained in Section 4.3, as it can be considered as an independent process.
It is important to note that implementation matters do not affect the result of an algorithm, but they affect its performance and efficiency. In this sense, the implementation of a meshing algorithm is crucial if it has to be applied to industrial problems with complex geometries, or to generate really large meshes. A bad implementation can lead to unaffordable problems in terms of memory and computational time.
The algorithm has been implemented as a static library. Although the implementation of the mesher is done taking into account the GiD pre and postprocessing system [56,57,58] for getting the input data and the visualization of the meshes, its connection to GiD has been done as an external library, by a general interface specially designed to make it accessible for other programs. It is really important to provide access to the mesher as a library, as some numerical simulations require interaction with the mesher during the simulation itself (i.e. for optimization loops or in remeshing processes).
The implementation of the new algorithm has been carried out paying special attention to saving as much memory as possible, and trying to improve its performance taking into account shared memory parallel processing (Section 6.6).
One important characteristic common to many meshing algorithms is that they need an extra memory to generate the mesh compared to the memory needed to store the mesh once it has been generated. This leads to the need of memory saving strategies in the implementation of the mesher:
(a)  (b) 
Figure 63: 2D example of a thin model (the solid surface) with its bounding box (dotted line) and the quadtree (black lines). Cells out of the bounding box are marked with points. (a) Quadtree refined considering only the cells colliding the model bounding box. It can be appreciated that the quadtree is not balanced out of it. (b) Quadree refined considering all its cells. 
Depending on the aspect ratio of the bounding box of the model, this strategy can save a lot of memory. This is the case of very thin models in some direction (like the 2D example depicted in Figure 63) where, actually, the main part of the octree root is out of the bounding box of the model. Not considering the refinement criteria of the octree out of the model bounding box (like, for instance, the balance criterion) can reduce drastically the number of cells of it, as it can be seen in Figure 63. It can be appreciated that the quadtree refined considering all the cells (b) has much more cells than considering only the cells colliding the model bounding box (a).
The flowchart of the bodyfitted algorithm illustrating this process can be seen in Figure 69.
Considering the input data, the meshing algorithm is designed in a way that the input boundaries can be mesh or geometrical entities. The only operations required for them to be used in the algorithm are:
The algorithm has been implemented considering only mesh entities for the definition of the input boundaries. This simplify much the geometrical operations defined above.
The octree is the key structure of the presented algorithm. As mentioned in previous sections, it is not only used for generating the tetrahedra, but also for searching purposes. Actually, octrees were created originally for this topic, so it is natural to take advantage from on its characteristics in this field.
The main operation the octree is designed for is to find the leaf containing a coordinate in space. For this purpose, beginning from the octree root, the given coordinate is analyzed to evaluate which of its children contains it (considering the uniform subdivision of a cell, determining in which octant of a cell the coordinate is represents an inexpensive process). If the child is not an octree leaf, the process is repeated (with itself instead of the octree root) until an octree leaf is reached. This process can be seen as going downstream by the octree structure, and often implies the use of recursive functions (the same function applied to a cell is applied to its child). The use of recursive functions is not desirable because it decreases the performance of the algorithm due to the function call overhead.
In order to achieve a good performance, a very efficient implementation of the octree has been carried out based on [43] work. This octree has the peculiarity that works in the normalized unitary space xx. This is required because it uses the binary representation of all the coordinates involved in the process casted to integer: the so called key of the coordinate.
From a given coordinate in the normalized space, the following steps are performed in order to find the octree leaf containing it: