Adding chipmunk implementation for physics adaptor
[platform/core/uifw/dali-toolkit.git] / dali-scene3d / internal / algorithm / path-finder-spfa.cpp
1 /*
2  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 // CLASS HEADER
18 #include <dali-scene3d/internal/algorithm/path-finder-spfa.h>
19
20 // EXTERNAL INCLUDES
21 #include <dali/public-api/common/vector-wrapper.h>
22 #include <limits>
23
24 // INTERNAL INCLUDES
25 #include <dali-scene3d/internal/algorithm/path-finder-waypoint-data.h>
26 #include <dali-scene3d/public-api/algorithm/path-finder-waypoint.h>
27
28 using WayPointList = Dali::Scene3D::Algorithm::WayPointList;
29
30 namespace Dali::Scene3D::Internal::Algorithm
31 {
32 PathFinderAlgorithmSPFA::PathFinderAlgorithmSPFA(Dali::Scene3D::Algorithm::NavigationMesh& navMesh)
33 : mNavigationMesh(&GetImplementation(navMesh))
34 {
35   PrepareData();
36 }
37
38 PathFinderAlgorithmSPFA::~PathFinderAlgorithmSPFA() = default;
39
40 Scene3D::Algorithm::WayPointList PathFinderAlgorithmSPFA::FindPath(const Dali::Vector3& positionFrom, const Dali::Vector3& positionTo)
41 {
42   Dali::Vector3 outPosFrom;
43   FaceIndex     polyIndexFrom;
44   auto          result = mNavigationMesh->FindFloor(positionFrom, outPosFrom, polyIndexFrom);
45
46   Scene3D::Algorithm::WayPointList waypoints;
47
48   if(result)
49   {
50     Dali::Vector3 outPosTo;
51     FaceIndex     polyIndexTo;
52     result = mNavigationMesh->FindFloor(positionTo, outPosTo, polyIndexTo);
53
54     if(result)
55     {
56       // Get waypoints
57       waypoints = FindPath(polyIndexFrom, polyIndexTo);
58
59       // replace first and last waypoint
60       auto& wpFrom = static_cast<WayPointData&>(waypoints[0]);
61       auto& wpTo   = static_cast<WayPointData&>(waypoints.back());
62
63       Vector2 fromCenter(wpFrom.point3d.x, wpFrom.point3d.y);
64       wpFrom.point3d = outPosFrom;
65       wpFrom.point2d = fromCenter - Vector2(outPosFrom.x, outPosFrom.y);
66
67       Vector2 toCenter(wpTo.point3d.x, wpTo.point3d.y);
68       wpTo.point3d = outPosTo;
69       wpTo.point2d = toCenter - Vector2(outPosTo.x, outPosTo.y);
70       wpTo.point3d = outPosTo;
71     }
72   }
73
74   // Returns waypoints with non-zero size of empty vector in case of failure (no path to be found)
75   return waypoints;
76 }
77
78 Scene3D::Algorithm::WayPointList PathFinderAlgorithmSPFA::FindPath(FaceIndex sourcePolyIndex, FaceIndex targetPolyIndex)
79 {
80   auto                   nodeCount = uint32_t(mNodes.size());
81   std::vector<float>     dist;
82   std::vector<FaceIndex> prev;
83   std::vector<bool>      queued;
84
85   dist.resize(mNodes.size());
86   prev.resize(mNodes.size());
87   queued.resize(mNodes.size());
88
89   std::list<FaceIndex> nodeQueue;
90
91   [[maybe_unused]] auto sourcePos = Dali::Vector3(Face(sourcePolyIndex)->center);
92
93   for(auto i = 0u; i < nodeCount; ++i)
94   {
95     dist[i]   = std::numeric_limits<float>::infinity();
96     prev[i]   = Scene3D::Algorithm::NavigationMesh::NULL_FACE; // set prev to null polygon
97     queued[i] = false;
98   }
99
100   // Set distance of source
101   dist[sourcePolyIndex]   = 0.0f;
102   queued[sourcePolyIndex] = true;
103   nodeQueue.push_back(sourcePolyIndex);
104
105   while(!nodeQueue.empty())
106   {
107     // find minimum distance
108     auto minDistIndex = nodeQueue.front();
109     nodeQueue.pop_front();
110     queued[minDistIndex] = false;
111
112     // Skip operator when minDistIndex is target
113     if(minDistIndex == targetPolyIndex)
114     {
115       continue;
116     }
117
118     // check the neighbours
119     for(auto i = 0u; i < 3; ++i)
120     {
121       auto nIndex = mNodes[minDistIndex].faces[i];
122       if(nIndex != Scene3D::Algorithm::NavigationMesh::NULL_FACE)
123       {
124         auto alt = dist[minDistIndex] + mNodes[minDistIndex].weight[i];
125         if(alt < dist[nIndex])
126         {
127           dist[nIndex] = alt;
128           prev[nIndex] = minDistIndex;
129
130           if(!queued[nIndex])
131           {
132             queued[nIndex] = true;
133             if(!nodeQueue.empty() && dist[nIndex] < dist[nodeQueue.front()])
134             {
135               nodeQueue.push_front(nIndex);
136             }
137             else
138             {
139               nodeQueue.push_back(nIndex);
140             }
141           }
142         }
143       }
144     }
145   }
146
147   // Compute distances for each node back to the source
148   auto                 u = targetPolyIndex;
149   std::list<FaceIndex> q;
150   if(prev[u] != Scene3D::Algorithm::NavigationMesh::NULL_FACE || u == sourcePolyIndex)
151   {
152     while(u != Scene3D::Algorithm::NavigationMesh::NULL_FACE)
153     {
154       q.push_front(u);
155       u = prev[u];
156     }
157   }
158
159   WayPointList waypoints;
160   waypoints.resize(q.size());
161
162   if(q.size() == 0)
163   {
164     // Fail to found path. Return empty list.
165     return waypoints;
166   }
167
168   auto index = 0u;
169   auto prevN = 0u;
170   for(auto n : q)
171   {
172     auto& wp     = static_cast<WayPointData&>(waypoints[index]);
173     wp.face      = mNavigationMesh->GetFace(n);
174     wp.nodeIndex = n;
175
176     wp.edge = nullptr;
177     // set the common edge with previous node
178     if(index > 0)
179     {
180       const auto& node = mNodes[prevN];
181       for(auto i = 0u; i < 3; ++i)
182       {
183         if(node.faces[i] == wp.nodeIndex)
184         {
185           wp.edge = mNavigationMesh->GetEdge(node.edges[i]);
186           break;
187         }
188       }
189     }
190
191     prevN = n;
192     index++;
193   }
194
195   return OptimizeWaypoints(waypoints);
196 }
197
198 void PathFinderAlgorithmSPFA::PrepareData()
199 {
200   // Build the list structure connecting the nodes
201   auto faceCount = mNavigationMesh->GetFaceCount();
202
203   mNodes.resize(faceCount);
204
205   // for each face build the list
206   // TODO : Currently, we are assume that FaceNodeIndex is matched with FaceIndex 1:1. This might be changed in future.
207   for(FaceNodeIndex i = 0u; i < faceCount; ++i)
208   {
209     auto&       node = mNodes[i];
210     const auto* face = mNavigationMesh->GetFace(i);
211     auto        c0   = Dali::Vector3(face->center);
212
213     // for each edge add neighbouring face and compute distance to set the weight of node
214     for(auto edgeIndex = 0u; edgeIndex < 3; ++edgeIndex)
215     {
216       const auto* edge = mNavigationMesh->GetEdge(face->edge[edgeIndex]);
217       auto        p1   = edge->face[0];
218       auto        p2   = edge->face[1];
219
220       // One of faces is current face so ignore it
221       auto p                = ((p1 != i) ? p1 : p2);
222       node.faces[edgeIndex] = p;
223       if(p != ::Dali::Scene3D::Algorithm::NavigationMesh::NULL_FACE)
224       {
225         node.edges[edgeIndex]  = face->edge[edgeIndex];
226         auto c1                = Dali::Vector3(mNavigationMesh->GetFace(p)->center);
227         node.weight[edgeIndex] = (c1 - c0).Length();
228       }
229     }
230   }
231 }
232
233 [[maybe_unused]] static float ccw(const Dali::Vector2& A, const Dali::Vector2& B, const Dali::Vector2& C)
234 {
235   return (C.y - A.y) * (B.x - A.x) > (B.y - A.y) * (C.x - A.x);
236 }
237
238 [[maybe_unused]] static bool intersect(const Dali::Vector2& A, const Dali::Vector2& B, const Dali::Vector2& C, const Dali::Vector2& D)
239 {
240   return ccw(A, C, D) != ccw(B, C, D) && ccw(A, B, C) != ccw(A, B, D);
241 }
242
243 Scene3D::Algorithm::WayPointList PathFinderAlgorithmSPFA::OptimizeWaypoints(WayPointList& waypoints) const
244 {
245   WayPointList optimizedWaypoints;
246   optimizedWaypoints.emplace_back(waypoints[0]);
247   optimizedWaypoints.reserve(waypoints.size());
248
249   auto startIndex = 1u;
250
251   bool finished = false;
252   for(auto j = 0; !finished; ++j)
253   {
254     auto&       startWaypoint     = optimizedWaypoints.back();
255     const auto& startWaypointData = static_cast<const WayPointData&>(startWaypoint);
256
257     // add new-last waypoint which will be overriden as long as intersection takes place
258     optimizedWaypoints.emplace_back();
259     for(auto wpIndex = startIndex; wpIndex < waypoints.size(); ++wpIndex)
260     {
261       if(wpIndex == waypoints.size() - 1)
262       {
263         optimizedWaypoints.back() = waypoints.back();
264         finished                  = true;
265         continue;
266       }
267       // Points between centres of faces
268
269       const auto& wpData = static_cast<const WayPointData&>(waypoints[wpIndex]);
270
271       auto Pa0 = Dali::Vector2(startWaypointData.face->center[0], startWaypointData.face->center[1]);
272       auto Pa1 = Dali::Vector2(wpData.face->center[0], wpData.face->center[1]);
273
274       bool doesIntersect = true;
275       for(auto i = startIndex; i < wpIndex; ++i)
276       {
277         const auto& wp = static_cast<WayPointData&>(waypoints[i]);
278         // Skip starting waypoint
279         if(wp.face == startWaypointData.face)
280         {
281           continue;
282         }
283         auto Pb0  = mNavigationMesh->GetVertex(wp.edge->vertex[0]);
284         auto Pb1  = mNavigationMesh->GetVertex(wp.edge->vertex[1]);
285         auto vPb0 = Dali::Vector2(Pb0->x, Pb0->y);
286         auto vPb1 = Dali::Vector2(Pb1->x, Pb1->y);
287
288         doesIntersect = intersect(Pa0, Pa1, vPb0, vPb1);
289         if(!doesIntersect)
290         {
291           break;
292         }
293       }
294
295       if(!doesIntersect)
296       {
297         optimizedWaypoints.back() = waypoints[wpIndex - 1];
298         startIndex                = wpIndex - 1;
299         break;
300       }
301     }
302   }
303
304   for(auto& wp : optimizedWaypoints)
305   {
306     auto& wpData   = static_cast<WayPointData&>(wp);
307     wpData.point3d = mNavigationMesh->PointLocalToScene(Dali::Vector3(wpData.face->center));
308     wpData.point2d = Vector2::ZERO;
309   }
310
311   return optimizedWaypoints;
312 }
313 } // namespace Dali::Scene3D::Internal::Algorithm