+
+// Returns closest vertex in world space and distance
+// a and b define the line in 3d space
+std::pair<glm::vec3, float> Model::closestVertex(Model::Node &n, glm::vec3 a, glm::vec3 b, glm::mat4 parentTrans) const {
+ float closestDist = FLT_MAX;
+ glm::vec3 closestVert;
+
+ for (int i = 0; i < n.ai.mNumMeshes; i++) {
+ int meshIdx = n.ai.mMeshes[i];
+ const aiMesh &mesh = meshes[meshIdx].ai;
+
+ for (int j = 0; j < mesh.mNumVertices; j++) {
+ if (mesh.HasNormals()) {
+ auto n = aiVector3DToVec3(mesh.mNormals[j]);
+ if (glm::dot(n, glm::normalize(b - a)) > 0)
+ continue;
+ }
+ glm::vec4 vPos = glm::vec4(aiVector3DToVec3(mesh.mVertices[j]), 1);
+ // Move from model space -> world space
+ vPos = parentTrans * aiMatrixToMat4(n.ai.mTransformation) * vPos;
+ float dist = glm::distance(glm::vec3(vPos),
+ glm::closestPointOnLine(glm::vec3(vPos), a, b));
+ if (dist < closestDist) {
+ closestVert = glm::vec3(vPos);
+ closestDist = dist;
+ }
+ }
+ }
+
+ for (auto child: n.getChildren()) {
+ auto childRes = closestVertex(*child, a, b, parentTrans * aiMatrixToMat4(n.ai.mTransformation));
+ if (childRes.second < closestDist) {
+ closestVert = childRes.first;
+ closestDist = childRes.second;
+ }
+ }
+
+ return { closestVert, closestDist };
+}