/// <summary> /// 插入一个poly和其对应的polyConnection的映射 /// </summary> /// <param name="A"></param> /// <param name="connection"></param> public void InsertNearPoly(int index, PolyConnection connection) { if (!nearPolys.ContainsKey(index)) { nearPolys.Add(index, new HashSet <PolyConnection>()); } if (!nearPolys[index].Contains(connection)) { nearPolys[index].Add(connection); } }
public void ProcessMeshToGraph() { Dictionary <Triangle, bool> visited = new Dictionary <Triangle, bool>(); foreach (Triangle tri in triangles) { visited.Add(tri, false); } Queue <Poly> processEdgeQueue = new Queue <Poly>(); int i = 0; componentCount = 0; int mergedCout = 0; while (triangles.Count > 0) { componentCount++; //整张图的联通分量计数++ Triangle tri = triangles.First(); //拿出一个三角形 tri.Index = i++; //为这个poly分配索引 visited[tri] = true; processEdgeQueue.Enqueue(tri); triangles.Remove(tri); foreach (GeoEdge e in tri.Edges) { if (edgeTriangleMap.ContainsKey(e.Index) && edgeTriangleMap[e.Index].Contains(tri)) { edgeTriangleMap[e.Index].Remove(tri);//移除这个三角形和它的边的映射 } } while (processEdgeQueue.Count > 0) { Poly poly = processEdgeQueue.Dequeue(); bool hasConnection = false; for (int j = 0; j < poly.Edges.Count; j++) {//对于这个多边形的每一条边 GeoEdge e = poly.Edges[j]; for (int k = 0; k < edgeTriangleMap[e.Index].Count; k++) {//如果有与之相连的其他三角形 Triangle t = edgeTriangleMap[e.Index][k]; if (triangles.Contains(t) && t != poly && PolyProcesser.HasSharedEdge(poly, t)) { GeoEdge sharedEdge = PolyProcesser.SharedEdge(poly, t); if (PolyProcesser.TryMerge(ref poly, t, ref sharedEdge)) //如果可以成功合并 { //这里ref Poly处理过后,里面就有t的边了 hasConnection = true; mergedCout++; } else {//相连但不可成功合并,说明是相连的多边形 if (!visited[t]) { processEdgeQueue.Enqueue(t); t.Index = i++; visited[t] = true; //设置polyConnection,这里polyConnection还不用计算Weight,因为可能poly和t的顶点都没有全部得到 PolyConnection con = new PolyConnection(poly.Index, t.Index, sharedEdge); if (!polyConnections.Contains(con)) { polyConnections.Add(con); InsertNearPoly(con.A, con); InsertNearPoly(con.B, con); } } } edgeTriangleMap[e.Index].Remove(t); triangles.Remove(t); } } } if (hasConnection) { processEdgeQueue.Enqueue(poly);//说明还有连接,可能这个poly还没有处理完 } else {//Poly没有连接了,说明处理完了,对poly做最后的处理 if (!polys.ContainsKey(poly.Index)) { polys.Add(poly.Index, poly); } } } } //对polyConnection计算权值 foreach (PolyConnection polyCon in polyConnections) { Vector3 pointA = CenterPoint(polys[polyCon.A].GetPoints()); Vector3 pointB = CenterPoint(polys[polyCon.B].GetPoints()); polyCon.Weight = Vector3.Distance(pointA, pointB); } Debug.Log("merged count :" + mergedCout); Debug.Log("component count :" + componentCount); }