Suppose I have a 2D mesh consisting of nonoverlapping triangles $\{T_k\}_{k=1}^N$, and a set of points $\{p_i\}_{i=1}^M \subset \cup_{k=1}^N T_K$. What is the best way to determine which triangle each of the points lies in?
For example, in the following image we have $p_1 \in T_2$, $p_2 \in T_4$, $p_3 \in T_2$, so I would like a function $f$ that returns the list $f(p_1,p_2,p_3)=[2,4,2]$.
Matlab has the function pointlocation which does what I want for Delaunay meshes, but it fails for general meshes.
My first (dumb) thought is, for all nodes $p_i$, loop through all the triangles to find out which triangle $p_i$ is in. However, this is is extremely inefficient - you might have to loop through every triangle for every point, so it could take $O(N \cdot M)$ work.
My next thought is, for all points $p_i$, find the nearest mesh node via nearest-neighbor search, then look through triangles attached to that nearest node. In this case, the work would be $O(a\cdot M\cdot log(N))$, where $a$ is the maximum number of triangles attached to any node in the mesh. There are a couple solvable but annoying issues with this approach,
- It requires implementing an efficient nearest-neighbor search (or finding a library that has it), which could be a nontrivial task.
- It requires storing a list of which triangles are attached to each node, which my code is currently not set up for - right now there is just a list of node coordinates and a list of elements.
Altogether it seems inelegant, and I think there should be a better way. This must be a problem that arises a lot, so I was wondering if anyone could recommend the best way to approach finding what triangles the nodes are in, either theoretically or in terms of available libraries.
Thanks!