diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Log.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Log.cs new file mode 100644 index 0000000000000000000000000000000000000000..36ba3b402d6253316bc1065e54f5a9bdb6f0dd7f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Log.cs @@ -0,0 +1,84 @@ +// ----------------------------------------------------------------------- +// +// Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/ +// +// ----------------------------------------------------------------------- + +namespace UnityEngine.U2D.Animation.TriangleNet +{ + using System.Collections.Generic; + using Animation.TriangleNet.Logging; + + /// + /// A simple logger, which logs messages to a List. + /// + /// Using singleton pattern as proposed by Jon Skeet. + /// http://csharpindepth.com/Articles/General/Singleton.aspx + /// + internal sealed class Log : ILog + { + /// + /// Log detailed information. + /// + internal static bool Verbose { get; set; } + + private List log = new List(); + + private LogLevel level = LogLevel.Info; + + #region Singleton pattern + + private static readonly Log instance = new Log(); + + // Explicit static constructor to tell C# compiler + // not to mark type as beforefieldinit + static Log() {} + + private Log() {} + + internal static ILog Instance + { + get + { + return instance; + } + } + + #endregion + + public void Add(LogItem item) + { + log.Add(item); + } + + public void Clear() + { + log.Clear(); + } + + public void Info(string message) + { + log.Add(new LogItem(LogLevel.Info, message)); + } + + public void Warning(string message, string location) + { + log.Add(new LogItem(LogLevel.Warning, message, location)); + } + + public void Error(string message, string location) + { + log.Add(new LogItem(LogLevel.Error, message, location)); + } + + public IList Data + { + get { return log; } + } + + public LogLevel Level + { + get { return level; } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Log.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Log.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..3f2cbf67dde4b7011e0e0d44eca84ec022c8f46f --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Log.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 196e2f3da40aa4a94a0a42a5e8fe60b9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Logging.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Logging.meta new file mode 100644 index 0000000000000000000000000000000000000000..e68bfc29ab872881d87b6b8007e38adde42026c8 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Logging.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 12bf6e7f64391465d8d8ef95ca3a996b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Mesh.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Mesh.cs new file mode 100644 index 0000000000000000000000000000000000000000..6eca827d180948fe22b9b02b15f6dc5d35acaed1 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Mesh.cs @@ -0,0 +1,1768 @@ +// ----------------------------------------------------------------------- +// +// Original Triangle code by Jonathan Richard Shewchuk, http://www.cs.cmu.edu/~quake/triangle.html +// Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/ +// +// ----------------------------------------------------------------------- + +namespace UnityEngine.U2D.Animation.TriangleNet +{ + using System; + using System.Collections.Generic; + using Animation.TriangleNet.Geometry; + using Animation.TriangleNet.Logging; + using Animation.TriangleNet.Meshing; + using Animation.TriangleNet.Meshing.Data; + using Animation.TriangleNet.Meshing.Iterators; + using Animation.TriangleNet.Tools; + using Animation.TriangleNet.Topology; + + /// + /// Mesh data structure. + /// + internal class Mesh : IMesh + { + #region Variables + + IPredicates predicates; + + ILog logger; + + QualityMesher qualityMesher; + + // Stack that maintains a list of recently flipped triangles. + Stack flipstack; + + // TODO: Check if custom hashmap implementation could be faster. + + // Using hashsets for memory management should quite fast. + internal TrianglePool triangles; + internal Dictionary subsegs; + internal Dictionary vertices; + + // Hash seeds (should belong to mesh instance) + internal int hash_vtx = 0; + internal int hash_seg = 0; + internal int hash_tri = 0; + + internal List holes; + internal List regions; + + // TODO: remove mesh_dim, invertices and insegments + + // Other variables. + internal Rectangle bounds; // x and y bounds. + internal int invertices; // Number of input vertices. + internal int insegments; // Number of input segments. + internal int undeads; // Number of input vertices that don't appear in the mesh. + internal int mesh_dim; // Dimension (ought to be 2). + internal int nextras = 0; // Number of attributes per vertex. + //internal int eextras; // Number of attributes per triangle. + internal int hullsize; // Number of edges in convex hull. + internal int steinerleft; // Number of Steiner points not yet used. + internal bool checksegments; // Are there segments in the triangulation yet? + internal bool checkquality; // Has quality triangulation begun yet? + + // Triangular bounding box vertices. + internal Vertex infvertex1, infvertex2, infvertex3; + + internal TriangleLocator locator; + + // Controls the behavior of the mesh instance. + internal Behavior behavior; + + // The current node numbering + internal NodeNumbering numbering; + + #endregion + + #region Public properties + + /// + /// Gets the mesh bounding box. + /// + public Rectangle Bounds + { + get { return this.bounds; } + } + + /// + /// Gets the mesh vertices. + /// + public ICollection Vertices + { + get { return this.vertices.Values; } + } + + /// + /// Gets the mesh holes. + /// + public IList Holes + { + get { return this.holes; } + } + + /// + /// Gets the mesh triangles. + /// + public ICollection Triangles + { + get { return this.triangles; } + } + + /// + /// Gets the mesh segments. + /// + public ICollection Segments + { + get { return this.subsegs.Values; } + } + + /// + /// Gets the mesh edges. + /// + public IEnumerable Edges + { + get + { + var e = new EdgeIterator(this); + while (e.MoveNext()) + { + yield return e.Current; + } + } + } + + /// + /// Gets the number of input vertices. + /// + public int NumberOfInputPoints + { + get { return invertices; } + } + + /// + /// Gets the number of mesh edges. + /// + public int NumberOfEdges + { + get { return (3 * triangles.Count + hullsize) / 2; } + } + + /// + /// Indicates whether the input is a PSLG or a point set. + /// + public bool IsPolygon + { + get { return this.insegments > 0; } + } + + /// + /// Gets the current node numbering. + /// + public NodeNumbering CurrentNumbering + { + get { return numbering; } + } + + #endregion + + #region "Outer space" variables + + internal const int DUMMY = -1; + + // The triangle that fills "outer space," called 'dummytri', is pointed to + // by every triangle and subsegment on a boundary (be it outer or inner) of + // the triangulation. Also, 'dummytri' points to one of the triangles on + // the convex hull (until the holes and concavities are carved), making it + // possible to find a starting triangle for point location. + + // 'dummytri' and 'dummysub' are generally required to fulfill only a few + // invariants: their vertices must remain NULL and 'dummytri' must always + // be bonded (at offset zero) to some triangle on the convex hull of the + // mesh, via a boundary edge. Otherwise, the connections of 'dummytri' and + // 'dummysub' may change willy-nilly. This makes it possible to avoid + // writing a good deal of special-case code (in the edge flip, for example) + // for dealing with the boundary of the mesh, places where no subsegment is + // present, and so forth. Other entities are frequently bonded to + // 'dummytri' and 'dummysub' as if they were real mesh entities, with no + // harm done. + + internal Triangle dummytri; + + // Set up 'dummysub', the omnipresent subsegment pointed to by any + // triangle side or subsegment end that isn't attached to a real + // subsegment. + + internal SubSegment dummysub; + + private void Initialize() + { + dummysub = new SubSegment(); + dummysub.hash = DUMMY; + + // Initialize the two adjoining subsegments to be the omnipresent + // subsegment. These will eventually be changed by various bonding + // operations, but their values don't really matter, as long as they + // can legally be dereferenced. + dummysub.subsegs[0].seg = dummysub; + dummysub.subsegs[1].seg = dummysub; + + // Set up 'dummytri', the 'triangle' that occupies "outer space." + dummytri = new Triangle(); + dummytri.hash = dummytri.id = DUMMY; + + // Initialize the three adjoining triangles to be "outer space." These + // will eventually be changed by various bonding operations, but their + // values don't really matter, as long as they can legally be + // dereferenced. + dummytri.neighbors[0].tri = dummytri; + dummytri.neighbors[1].tri = dummytri; + dummytri.neighbors[2].tri = dummytri; + + // Initialize the three adjoining subsegments of 'dummytri' to be + // the omnipresent subsegment. + dummytri.subsegs[0].seg = dummysub; + dummytri.subsegs[1].seg = dummysub; + dummytri.subsegs[2].seg = dummysub; + } + + #endregion + + /// + /// Initializes a new instance of the class. + /// + public Mesh(Configuration config) + { + Initialize(); + + logger = Log.Instance; + + behavior = new Behavior(); + + vertices = new Dictionary(); + subsegs = new Dictionary(); + + triangles = config.TrianglePool(); + + flipstack = new Stack(); + + holes = new List(); + regions = new List(); + + steinerleft = -1; + + this.predicates = config.Predicates(); + + this.locator = new TriangleLocator(this, predicates); + } + + public void Refine(QualityOptions quality, bool delaunay = false) + { + invertices = vertices.Count; + + if (behavior.Poly) + { + insegments = behavior.useSegments ? subsegs.Count : hullsize; + } + + Reset(); + + if (qualityMesher == null) + { + qualityMesher = new QualityMesher(this, new Configuration()); + } + + // Enforce angle and area constraints. + qualityMesher.Apply(quality, delaunay); + } + + /// + /// Renumber vertex and triangle id's. + /// + public void Renumber() + { + this.Renumber(NodeNumbering.Linear); + } + + /// + /// Renumber vertex and triangle id's. + /// + public void Renumber(NodeNumbering num) + { + // Don't need to do anything if the nodes are already numbered. + if (num == this.numbering) + { + return; + } + + int id; + + if (num == NodeNumbering.Linear) + { + id = 0; + foreach (var node in this.vertices.Values) + { + node.id = id++; + } + } + else if (num == NodeNumbering.CuthillMcKee) + { + var rcm = new CuthillMcKee(); + var iperm = rcm.Renumber(this); + + // Permute the node indices. + foreach (var node in this.vertices.Values) + { + node.id = iperm[node.id]; + } + } + + // Remember the current numbering. + numbering = num; + + // Triangles will always be numbered from 0 to n-1 + id = 0; + foreach (var item in this.triangles) + { + item.id = id++; + } + } + + #region Misc + + /// + /// Set QualityMesher for mesh refinement. + /// + /// + internal void SetQualityMesher(QualityMesher qmesher) + { + qualityMesher = qmesher; + } + + internal void CopyTo(Mesh target) + { + target.vertices = this.vertices; + target.triangles = this.triangles; + target.subsegs = this.subsegs; + + target.holes = this.holes; + target.regions = this.regions; + + target.hash_vtx = this.hash_vtx; + target.hash_seg = this.hash_seg; + target.hash_tri = this.hash_tri; + + target.numbering = this.numbering; + target.hullsize = this.hullsize; + } + + /// + /// Reset all the mesh data. This method will also wipe + /// out all mesh data. + /// + private void ResetData() + { + vertices.Clear(); + triangles.Restart(); + subsegs.Clear(); + + holes.Clear(); + regions.Clear(); + + this.hash_vtx = 0; + this.hash_seg = 0; + this.hash_tri = 0; + + flipstack.Clear(); + + hullsize = 0; + + Reset(); + + locator.Reset(); + } + + /// + /// Reset the mesh triangulation state. + /// + private void Reset() + { + numbering = NodeNumbering.None; + + undeads = 0; // No eliminated input vertices yet. + checksegments = false; // There are no segments in the triangulation yet. + checkquality = false; // The quality triangulation stage has not begun. + + Statistic.InCircleCount = 0; + Statistic.CounterClockwiseCount = 0; + Statistic.InCircleAdaptCount = 0; + Statistic.CounterClockwiseAdaptCount = 0; + Statistic.Orient3dCount = 0; + Statistic.HyperbolaCount = 0; + Statistic.CircleTopCount = 0; + Statistic.CircumcenterCount = 0; + } + + /// + /// Read the vertices from memory. + /// + /// The input data. + internal void TransferNodes(IList points) + { + this.invertices = points.Count; + this.mesh_dim = 2; + this.bounds = new Rectangle(); + + if (this.invertices < 3) + { + logger.Error("Input must have at least three input vertices.", "Mesh.TransferNodes()"); + throw new Exception("Input must have at least three input vertices."); + } + + var v = points[0]; + +#if USE_ATTRIBS + // Check attributes. + this.nextras = v.attributes == null ? 0 : v.attributes.Length; +#endif + + // Simple heuristic to check if ids are already set. We assume that if the + // first two vertex ids are distinct, then all input vertices have pairwise + // distinct ids. + bool userId = (v.id != points[1].id); + + foreach (var p in points) + { + if (userId) + { + p.hash = p.id; + + // Make sure the hash counter gets updated. + hash_vtx = Math.Max(p.hash + 1, hash_vtx); + } + else + { + p.hash = p.id = hash_vtx++; + } + + this.vertices.Add(p.hash, p); + this.bounds.Expand(p); + } + } + + /// + /// Construct a mapping from vertices to triangles to improve the speed of + /// point location for segment insertion. + /// + /// + /// Traverses all the triangles, and provides each corner of each triangle + /// with a pointer to that triangle. Of course, pointers will be overwritten + /// by other pointers because (almost) each vertex is a corner of several + /// triangles, but in the end every vertex will point to some triangle + /// that contains it. + /// + internal void MakeVertexMap() + { + Otri tri = default(Otri); + Vertex triorg; + + foreach (var t in this.triangles) + { + tri.tri = t; + // Check all three vertices of the triangle. + for (tri.orient = 0; tri.orient < 3; tri.orient++) + { + triorg = tri.Org(); + triorg.tri = tri; + } + } + } + + #endregion + + #region Factory + + /// + /// Create a new triangle with orientation zero. + /// + /// Reference to the new triangle. + internal void MakeTriangle(ref Otri newotri) + { + Triangle tri = triangles.Get(); + + //tri.id = tri.hash; + + tri.subsegs[0].seg = dummysub; + tri.subsegs[1].seg = dummysub; + tri.subsegs[2].seg = dummysub; + + tri.neighbors[0].tri = dummytri; + tri.neighbors[1].tri = dummytri; + tri.neighbors[2].tri = dummytri; + + newotri.tri = tri; + newotri.orient = 0; + } + + /// + /// Create a new subsegment with orientation zero. + /// + /// Reference to the new subseg. + internal void MakeSegment(ref Osub newsubseg) + { + var seg = new SubSegment(); + + seg.hash = this.hash_seg++; + + seg.subsegs[0].seg = dummysub; + seg.subsegs[1].seg = dummysub; + + seg.triangles[0].tri = dummytri; + seg.triangles[1].tri = dummytri; + + newsubseg.seg = seg; + newsubseg.orient = 0; + + subsegs.Add(seg.hash, seg); + } + + #endregion + + #region Manipulation + + /// + /// Insert a vertex into a Delaunay triangulation, performing flips as necessary + /// to maintain the Delaunay property. + /// + /// The point to be inserted. + /// The triangle to start the search. + /// Segment to split. + /// Check for creation of encroached subsegments. + /// Check for creation of bad quality triangles. + /// If a duplicate vertex or violated segment does not prevent the + /// vertex from being inserted, the return value will be ENCROACHINGVERTEX if + /// the vertex encroaches upon a subsegment (and checking is enabled), or + /// SUCCESSFULVERTEX otherwise. In either case, 'searchtri' is set to a handle + /// whose origin is the newly inserted vertex. + /// + /// The point 'newvertex' is located. If 'searchtri.triangle' is not NULL, + /// the search for the containing triangle begins from 'searchtri'. If + /// 'searchtri.triangle' is NULL, a full point location procedure is called. + /// If 'insertvertex' is found inside a triangle, the triangle is split into + /// three; if 'insertvertex' lies on an edge, the edge is split in two, + /// thereby splitting the two adjacent triangles into four. Edge flips are + /// used to restore the Delaunay property. If 'insertvertex' lies on an + /// existing vertex, no action is taken, and the value DUPLICATEVERTEX is + /// returned. On return, 'searchtri' is set to a handle whose origin is the + /// existing vertex. + /// + /// InsertVertex() does not use flip() for reasons of speed; some + /// information can be reused from edge flip to edge flip, like the + /// locations of subsegments. + /// + /// Param 'splitseg': Normally, the parameter 'splitseg' is set to NULL, + /// implying that no subsegment should be split. In this case, if 'insertvertex' + /// is found to lie on a segment, no action is taken, and the value VIOLATINGVERTEX + /// is returned. On return, 'searchtri' is set to a handle whose primary edge is the + /// violated subsegment. + /// If the calling routine wishes to split a subsegment by inserting a vertex in it, + /// the parameter 'splitseg' should be that subsegment. In this case, 'searchtri' + /// MUST be the triangle handle reached by pivoting from that subsegment; no point + /// location is done. + /// + /// Param 'segmentflaws': Flags that indicate whether or not there should + /// be checks for the creation of encroached subsegments. If a newly inserted + /// vertex encroaches upon subsegments, these subsegments are added to the list + /// of subsegments to be split if 'segmentflaws' is set. + /// + /// Param 'triflaws': Flags that indicate whether or not there should be + /// checks for the creation of bad quality triangles. If bad triangles are + /// created, these are added to the queue if 'triflaws' is set. + /// + internal InsertVertexResult InsertVertex(Vertex newvertex, ref Otri searchtri, + ref Osub splitseg, bool segmentflaws, bool triflaws) + { + Otri horiz = default(Otri); + Otri top = default(Otri); + Otri botleft = default(Otri), botright = default(Otri); + Otri topleft = default(Otri), topright = default(Otri); + Otri newbotleft = default(Otri), newbotright = default(Otri); + Otri newtopright = default(Otri); + Otri botlcasing = default(Otri), botrcasing = default(Otri); + Otri toplcasing = default(Otri), toprcasing = default(Otri); + Otri testtri = default(Otri); + Osub botlsubseg = default(Osub), botrsubseg = default(Osub); + Osub toplsubseg = default(Osub), toprsubseg = default(Osub); + Osub brokensubseg = default(Osub); + Osub checksubseg = default(Osub); + Osub rightsubseg = default(Osub); + Osub newsubseg = default(Osub); + BadSubseg encroached; + //FlipStacker newflip; + Vertex first; + Vertex leftvertex, rightvertex, botvertex, topvertex, farvertex; + Vertex segmentorg, segmentdest; + int region; + double area; + InsertVertexResult success; + LocateResult intersect; + bool doflip; + bool mirrorflag; + bool enq; + + if (splitseg.seg == null) + { + // Find the location of the vertex to be inserted. Check if a good + // starting triangle has already been provided by the caller. + if (searchtri.tri.id == DUMMY) + { + // Find a boundary triangle. + horiz.tri = dummytri; + horiz.orient = 0; + horiz.Sym(); + + // Search for a triangle containing 'newvertex'. + intersect = locator.Locate(newvertex, ref horiz); + } + else + { + // Start searching from the triangle provided by the caller. + searchtri.Copy(ref horiz); + intersect = locator.PreciseLocate(newvertex, ref horiz, true); + } + } + else + { + // The calling routine provides the subsegment in which + // the vertex is inserted. + searchtri.Copy(ref horiz); + intersect = LocateResult.OnEdge; + } + + if (intersect == LocateResult.OnVertex) + { + // There's already a vertex there. Return in 'searchtri' a triangle + // whose origin is the existing vertex. + horiz.Copy(ref searchtri); + locator.Update(ref horiz); + return InsertVertexResult.Duplicate; + } + if ((intersect == LocateResult.OnEdge) || (intersect == LocateResult.Outside)) + { + // The vertex falls on an edge or boundary. + if (checksegments && (splitseg.seg == null)) + { + // Check whether the vertex falls on a subsegment. + horiz.Pivot(ref brokensubseg); + if (brokensubseg.seg.hash != DUMMY) + { + // The vertex falls on a subsegment, and hence will not be inserted. + if (segmentflaws) + { + enq = behavior.NoBisect != 2; + if (enq && (behavior.NoBisect == 1)) + { + // This subsegment may be split only if it is an + // internal boundary. + horiz.Sym(ref testtri); + enq = testtri.tri.id != DUMMY; + } + if (enq) + { + // Add the subsegment to the list of encroached subsegments. + encroached = new BadSubseg(); + encroached.subseg = brokensubseg; + encroached.org = brokensubseg.Org(); + encroached.dest = brokensubseg.Dest(); + + qualityMesher.AddBadSubseg(encroached); + } + } + // Return a handle whose primary edge contains the vertex, + // which has not been inserted. + horiz.Copy(ref searchtri); + locator.Update(ref horiz); + return InsertVertexResult.Violating; + } + } + + // Insert the vertex on an edge, dividing one triangle into two (if + // the edge lies on a boundary) or two triangles into four. + horiz.Lprev(ref botright); + botright.Sym(ref botrcasing); + horiz.Sym(ref topright); + // Is there a second triangle? (Or does this edge lie on a boundary?) + mirrorflag = topright.tri.id != DUMMY; + if (mirrorflag) + { + topright.Lnext(); + topright.Sym(ref toprcasing); + MakeTriangle(ref newtopright); + } + else + { + // Splitting a boundary edge increases the number of boundary edges. + hullsize++; + } + MakeTriangle(ref newbotright); + + // Set the vertices of changed and new triangles. + rightvertex = horiz.Org(); + leftvertex = horiz.Dest(); + botvertex = horiz.Apex(); + newbotright.SetOrg(botvertex); + newbotright.SetDest(rightvertex); + newbotright.SetApex(newvertex); + horiz.SetOrg(newvertex); + + // Set the region of a new triangle. + newbotright.tri.label = botright.tri.label; + + if (behavior.VarArea) + { + // Set the area constraint of a new triangle. + newbotright.tri.area = botright.tri.area; + } + + if (mirrorflag) + { + topvertex = topright.Dest(); + newtopright.SetOrg(rightvertex); + newtopright.SetDest(topvertex); + newtopright.SetApex(newvertex); + topright.SetOrg(newvertex); + + // Set the region of another new triangle. + newtopright.tri.label = topright.tri.label; + + if (behavior.VarArea) + { + // Set the area constraint of another new triangle. + newtopright.tri.area = topright.tri.area; + } + } + + // There may be subsegments that need to be bonded + // to the new triangle(s). + if (checksegments) + { + botright.Pivot(ref botrsubseg); + + if (botrsubseg.seg.hash != DUMMY) + { + botright.SegDissolve(dummysub); + newbotright.SegBond(ref botrsubseg); + } + + if (mirrorflag) + { + topright.Pivot(ref toprsubseg); + if (toprsubseg.seg.hash != DUMMY) + { + topright.SegDissolve(dummysub); + newtopright.SegBond(ref toprsubseg); + } + } + } + + // Bond the new triangle(s) to the surrounding triangles. + newbotright.Bond(ref botrcasing); + newbotright.Lprev(); + newbotright.Bond(ref botright); + newbotright.Lprev(); + + if (mirrorflag) + { + newtopright.Bond(ref toprcasing); + newtopright.Lnext(); + newtopright.Bond(ref topright); + newtopright.Lnext(); + newtopright.Bond(ref newbotright); + } + + if (splitseg.seg != null) + { + // Split the subsegment into two. + splitseg.SetDest(newvertex); + segmentorg = splitseg.SegOrg(); + segmentdest = splitseg.SegDest(); + splitseg.Sym(); + splitseg.Pivot(ref rightsubseg); + InsertSubseg(ref newbotright, splitseg.seg.boundary); + newbotright.Pivot(ref newsubseg); + newsubseg.SetSegOrg(segmentorg); + newsubseg.SetSegDest(segmentdest); + splitseg.Bond(ref newsubseg); + newsubseg.Sym(); + newsubseg.Bond(ref rightsubseg); + splitseg.Sym(); + + // Transfer the subsegment's boundary marker to the vertex if required. + if (newvertex.label == 0) + { + newvertex.label = splitseg.seg.boundary; + } + } + + if (checkquality) + { + flipstack.Clear(); + + flipstack.Push(default(Otri)); // Dummy flip (see UndoVertex) + flipstack.Push(horiz); + } + + // Position 'horiz' on the first edge to check for + // the Delaunay property. + horiz.Lnext(); + } + else + { + // Insert the vertex in a triangle, splitting it into three. + horiz.Lnext(ref botleft); + horiz.Lprev(ref botright); + botleft.Sym(ref botlcasing); + botright.Sym(ref botrcasing); + MakeTriangle(ref newbotleft); + MakeTriangle(ref newbotright); + + // Set the vertices of changed and new triangles. + rightvertex = horiz.Org(); + leftvertex = horiz.Dest(); + botvertex = horiz.Apex(); + newbotleft.SetOrg(leftvertex); + newbotleft.SetDest(botvertex); + newbotleft.SetApex(newvertex); + newbotright.SetOrg(botvertex); + newbotright.SetDest(rightvertex); + newbotright.SetApex(newvertex); + horiz.SetApex(newvertex); + + // Set the region of the new triangles. + newbotleft.tri.label = horiz.tri.label; + newbotright.tri.label = horiz.tri.label; + + if (behavior.VarArea) + { + // Set the area constraint of the new triangles. + area = horiz.tri.area; + newbotleft.tri.area = area; + newbotright.tri.area = area; + } + + // There may be subsegments that need to be bonded + // to the new triangles. + if (checksegments) + { + botleft.Pivot(ref botlsubseg); + if (botlsubseg.seg.hash != DUMMY) + { + botleft.SegDissolve(dummysub); + newbotleft.SegBond(ref botlsubseg); + } + botright.Pivot(ref botrsubseg); + if (botrsubseg.seg.hash != DUMMY) + { + botright.SegDissolve(dummysub); + newbotright.SegBond(ref botrsubseg); + } + } + + // Bond the new triangles to the surrounding triangles. + newbotleft.Bond(ref botlcasing); + newbotright.Bond(ref botrcasing); + newbotleft.Lnext(); + newbotright.Lprev(); + newbotleft.Bond(ref newbotright); + newbotleft.Lnext(); + botleft.Bond(ref newbotleft); + newbotright.Lprev(); + botright.Bond(ref newbotright); + + if (checkquality) + { + flipstack.Clear(); + flipstack.Push(horiz); + } + } + + // The insertion is successful by default, unless an encroached + // subsegment is found. + success = InsertVertexResult.Successful; + + if (newvertex.tri.tri != null) + { + // Store the coordinates of the triangle that contains newvertex. + newvertex.tri.SetOrg(rightvertex); + newvertex.tri.SetDest(leftvertex); + newvertex.tri.SetApex(botvertex); + } + + // Circle around the newly inserted vertex, checking each edge opposite it + // for the Delaunay property. Non-Delaunay edges are flipped. 'horiz' is + // always the edge being checked. 'first' marks where to stop circling. + first = horiz.Org(); + rightvertex = first; + leftvertex = horiz.Dest(); + // Circle until finished. + while (true) + { + // By default, the edge will be flipped. + doflip = true; + + if (checksegments) + { + // Check for a subsegment, which cannot be flipped. + horiz.Pivot(ref checksubseg); + if (checksubseg.seg.hash != DUMMY) + { + // The edge is a subsegment and cannot be flipped. + doflip = false; + + if (segmentflaws) + { + // Does the new vertex encroach upon this subsegment? + if (qualityMesher.CheckSeg4Encroach(ref checksubseg) > 0) + { + success = InsertVertexResult.Encroaching; + } + } + } + } + + if (doflip) + { + // Check if the edge is a boundary edge. + horiz.Sym(ref top); + if (top.tri.id == DUMMY) + { + // The edge is a boundary edge and cannot be flipped. + doflip = false; + } + else + { + // Find the vertex on the other side of the edge. + farvertex = top.Apex(); + // In the incremental Delaunay triangulation algorithm, any of + // 'leftvertex', 'rightvertex', and 'farvertex' could be vertices + // of the triangular bounding box. These vertices must be + // treated as if they are infinitely distant, even though their + // "coordinates" are not. + if ((leftvertex == infvertex1) || (leftvertex == infvertex2) || + (leftvertex == infvertex3)) + { + // 'leftvertex' is infinitely distant. Check the convexity of + // the boundary of the triangulation. 'farvertex' might be + // infinite as well, but trust me, this same condition should + // be applied. + doflip = predicates.CounterClockwise(newvertex, rightvertex, farvertex) > 0.0; + } + else if ((rightvertex == infvertex1) || + (rightvertex == infvertex2) || + (rightvertex == infvertex3)) + { + // 'rightvertex' is infinitely distant. Check the convexity of + // the boundary of the triangulation. 'farvertex' might be + // infinite as well, but trust me, this same condition should + // be applied. + doflip = predicates.CounterClockwise(farvertex, leftvertex, newvertex) > 0.0; + } + else if ((farvertex == infvertex1) || + (farvertex == infvertex2) || + (farvertex == infvertex3)) + { + // 'farvertex' is infinitely distant and cannot be inside + // the circumcircle of the triangle 'horiz'. + doflip = false; + } + else + { + // Test whether the edge is locally Delaunay. + doflip = predicates.InCircle(leftvertex, newvertex, rightvertex, farvertex) > 0.0; + } + if (doflip) + { + // We made it! Flip the edge 'horiz' by rotating its containing + // quadrilateral (the two triangles adjacent to 'horiz'). + // Identify the casing of the quadrilateral. + top.Lprev(ref topleft); + topleft.Sym(ref toplcasing); + top.Lnext(ref topright); + topright.Sym(ref toprcasing); + horiz.Lnext(ref botleft); + botleft.Sym(ref botlcasing); + horiz.Lprev(ref botright); + botright.Sym(ref botrcasing); + // Rotate the quadrilateral one-quarter turn counterclockwise. + topleft.Bond(ref botlcasing); + botleft.Bond(ref botrcasing); + botright.Bond(ref toprcasing); + topright.Bond(ref toplcasing); + if (checksegments) + { + // Check for subsegments and rebond them to the quadrilateral. + topleft.Pivot(ref toplsubseg); + botleft.Pivot(ref botlsubseg); + botright.Pivot(ref botrsubseg); + topright.Pivot(ref toprsubseg); + if (toplsubseg.seg.hash == DUMMY) + { + topright.SegDissolve(dummysub); + } + else + { + topright.SegBond(ref toplsubseg); + } + if (botlsubseg.seg.hash == DUMMY) + { + topleft.SegDissolve(dummysub); + } + else + { + topleft.SegBond(ref botlsubseg); + } + if (botrsubseg.seg.hash == DUMMY) + { + botleft.SegDissolve(dummysub); + } + else + { + botleft.SegBond(ref botrsubseg); + } + if (toprsubseg.seg.hash == DUMMY) + { + botright.SegDissolve(dummysub); + } + else + { + botright.SegBond(ref toprsubseg); + } + } + // New vertex assignments for the rotated quadrilateral. + horiz.SetOrg(farvertex); + horiz.SetDest(newvertex); + horiz.SetApex(rightvertex); + top.SetOrg(newvertex); + top.SetDest(farvertex); + top.SetApex(leftvertex); + + // Assign region. + // TODO: check region ok (no Math.Min necessary) + region = Math.Min(top.tri.label, horiz.tri.label); + top.tri.label = region; + horiz.tri.label = region; + + if (behavior.VarArea) + { + if ((top.tri.area <= 0.0) || (horiz.tri.area <= 0.0)) + { + area = -1.0; + } + else + { + // Take the average of the two triangles' area constraints. + // This prevents small area constraints from migrating a + // long, long way from their original location due to flips. + area = 0.5 * (top.tri.area + horiz.tri.area); + } + + top.tri.area = area; + horiz.tri.area = area; + } + + if (checkquality) + { + flipstack.Push(horiz); + } + + // On the next iterations, consider the two edges that were exposed (this + // is, are now visible to the newly inserted vertex) by the edge flip. + horiz.Lprev(); + leftvertex = farvertex; + } + } + } + if (!doflip) + { + // The handle 'horiz' is accepted as locally Delaunay. + if (triflaws) + { + // Check the triangle 'horiz' for quality. + qualityMesher.TestTriangle(ref horiz); + } + + // Look for the next edge around the newly inserted vertex. + horiz.Lnext(); + horiz.Sym(ref testtri); + // Check for finishing a complete revolution about the new vertex, or + // falling outside of the triangulation. The latter will happen when + // a vertex is inserted at a boundary. + if ((leftvertex == first) || (testtri.tri.id == DUMMY)) + { + // We're done. Return a triangle whose origin is the new vertex. + horiz.Lnext(ref searchtri); + + Otri recenttri = default(Otri); + horiz.Lnext(ref recenttri); + locator.Update(ref recenttri); + + return success; + } + // Finish finding the next edge around the newly inserted vertex. + testtri.Lnext(ref horiz); + rightvertex = leftvertex; + leftvertex = horiz.Dest(); + } + } + } + + /// + /// Create a new subsegment and inserts it between two triangles. Its + /// vertices are properly initialized. + /// + /// The new subsegment is inserted at the edge + /// described by this handle. + /// The marker 'subsegmark' is applied to the + /// subsegment and, if appropriate, its vertices. + internal void InsertSubseg(ref Otri tri, int subsegmark) + { + Otri oppotri = default(Otri); + Osub newsubseg = default(Osub); + Vertex triorg, tridest; + + triorg = tri.Org(); + tridest = tri.Dest(); + // Mark vertices if possible. + if (triorg.label == 0) + { + triorg.label = subsegmark; + } + if (tridest.label == 0) + { + tridest.label = subsegmark; + } + // Check if there's already a subsegment here. + tri.Pivot(ref newsubseg); + if (newsubseg.seg.hash == DUMMY) + { + // Make new subsegment and initialize its vertices. + MakeSegment(ref newsubseg); + newsubseg.SetOrg(tridest); + newsubseg.SetDest(triorg); + newsubseg.SetSegOrg(tridest); + newsubseg.SetSegDest(triorg); + // Bond new subsegment to the two triangles it is sandwiched between. + // Note that the facing triangle 'oppotri' might be equal to 'dummytri' + // (outer space), but the new subsegment is bonded to it all the same. + tri.SegBond(ref newsubseg); + tri.Sym(ref oppotri); + newsubseg.Sym(); + oppotri.SegBond(ref newsubseg); + newsubseg.seg.boundary = subsegmark; + } + else if (newsubseg.seg.boundary == 0) + { + newsubseg.seg.boundary = subsegmark; + } + } + + /// + /// Transform two triangles to two different triangles by flipping an edge + /// counterclockwise within a quadrilateral. + /// + /// Handle to the edge that will be flipped. + /// Imagine the original triangles, abc and bad, oriented so that the + /// shared edge ab lies in a horizontal plane, with the vertex b on the left + /// and the vertex a on the right. The vertex c lies below the edge, and + /// the vertex d lies above the edge. The 'flipedge' handle holds the edge + /// ab of triangle abc, and is directed left, from vertex a to vertex b. + /// + /// The triangles abc and bad are deleted and replaced by the triangles cdb + /// and dca. The triangles that represent abc and bad are NOT deallocated; + /// they are reused for dca and cdb, respectively. Hence, any handles that + /// may have held the original triangles are still valid, although not + /// directed as they were before. + /// + /// Upon completion of this routine, the 'flipedge' handle holds the edge + /// dc of triangle dca, and is directed down, from vertex d to vertex c. + /// (Hence, the two triangles have rotated counterclockwise.) + /// + /// WARNING: This transformation is geometrically valid only if the + /// quadrilateral adbc is convex. Furthermore, this transformation is + /// valid only if there is not a subsegment between the triangles abc and + /// bad. This routine does not check either of these preconditions, and + /// it is the responsibility of the calling routine to ensure that they are + /// met. If they are not, the streets shall be filled with wailing and + /// gnashing of teeth. + /// + /// Terminology + /// + /// A "local transformation" replaces a small set of triangles with another + /// set of triangles. This may or may not involve inserting or deleting a + /// vertex. + /// + /// The term "casing" is used to describe the set of triangles that are + /// attached to the triangles being transformed, but are not transformed + /// themselves. Think of the casing as a fixed hollow structure inside + /// which all the action happens. A "casing" is only defined relative to + /// a single transformation; each occurrence of a transformation will + /// involve a different casing. + /// + internal void Flip(ref Otri flipedge) + { + Otri botleft = default(Otri), botright = default(Otri); + Otri topleft = default(Otri), topright = default(Otri); + Otri top = default(Otri); + Otri botlcasing = default(Otri), botrcasing = default(Otri); + Otri toplcasing = default(Otri), toprcasing = default(Otri); + Osub botlsubseg = default(Osub), botrsubseg = default(Osub); + Osub toplsubseg = default(Osub), toprsubseg = default(Osub); + Vertex leftvertex, rightvertex, botvertex; + Vertex farvertex; + + // Identify the vertices of the quadrilateral. + rightvertex = flipedge.Org(); + leftvertex = flipedge.Dest(); + botvertex = flipedge.Apex(); + flipedge.Sym(ref top); + + // SELF CHECK + + //if (top.triangle.id == DUMMY) + //{ + // logger.Error("Attempt to flip on boundary.", "Mesh.Flip()"); + // flipedge.LnextSelf(); + // return; + //} + + //if (checksegments) + //{ + // flipedge.SegPivot(ref toplsubseg); + // if (toplsubseg.ss != Segment.Empty) + // { + // logger.Error("Attempt to flip a segment.", "Mesh.Flip()"); + // flipedge.LnextSelf(); + // return; + // } + //} + + farvertex = top.Apex(); + + // Identify the casing of the quadrilateral. + top.Lprev(ref topleft); + topleft.Sym(ref toplcasing); + top.Lnext(ref topright); + topright.Sym(ref toprcasing); + flipedge.Lnext(ref botleft); + botleft.Sym(ref botlcasing); + flipedge.Lprev(ref botright); + botright.Sym(ref botrcasing); + // Rotate the quadrilateral one-quarter turn counterclockwise. + topleft.Bond(ref botlcasing); + botleft.Bond(ref botrcasing); + botright.Bond(ref toprcasing); + topright.Bond(ref toplcasing); + + if (checksegments) + { + // Check for subsegments and rebond them to the quadrilateral. + topleft.Pivot(ref toplsubseg); + botleft.Pivot(ref botlsubseg); + botright.Pivot(ref botrsubseg); + topright.Pivot(ref toprsubseg); + + if (toplsubseg.seg.hash == DUMMY) + { + topright.SegDissolve(dummysub); + } + else + { + topright.SegBond(ref toplsubseg); + } + + if (botlsubseg.seg.hash == DUMMY) + { + topleft.SegDissolve(dummysub); + } + else + { + topleft.SegBond(ref botlsubseg); + } + + if (botrsubseg.seg.hash == DUMMY) + { + botleft.SegDissolve(dummysub); + } + else + { + botleft.SegBond(ref botrsubseg); + } + + if (toprsubseg.seg.hash == DUMMY) + { + botright.SegDissolve(dummysub); + } + else + { + botright.SegBond(ref toprsubseg); + } + } + + // New vertex assignments for the rotated quadrilateral. + flipedge.SetOrg(farvertex); + flipedge.SetDest(botvertex); + flipedge.SetApex(rightvertex); + top.SetOrg(botvertex); + top.SetDest(farvertex); + top.SetApex(leftvertex); + } + + /// + /// Transform two triangles to two different triangles by flipping an edge + /// clockwise within a quadrilateral. Reverses the flip() operation so that + /// the data structures representing the triangles are back where they were + /// before the flip(). + /// + /// + /// + /// See above Flip() remarks for more information. + /// + /// Upon completion of this routine, the 'flipedge' handle holds the edge + /// cd of triangle cdb, and is directed up, from vertex c to vertex d. + /// (Hence, the two triangles have rotated clockwise.) + /// + internal void Unflip(ref Otri flipedge) + { + Otri botleft = default(Otri), botright = default(Otri); + Otri topleft = default(Otri), topright = default(Otri); + Otri top = default(Otri); + Otri botlcasing = default(Otri), botrcasing = default(Otri); + Otri toplcasing = default(Otri), toprcasing = default(Otri); + Osub botlsubseg = default(Osub), botrsubseg = default(Osub); + Osub toplsubseg = default(Osub), toprsubseg = default(Osub); + Vertex leftvertex, rightvertex, botvertex; + Vertex farvertex; + + // Identify the vertices of the quadrilateral. + rightvertex = flipedge.Org(); + leftvertex = flipedge.Dest(); + botvertex = flipedge.Apex(); + flipedge.Sym(ref top); + + farvertex = top.Apex(); + + // Identify the casing of the quadrilateral. + top.Lprev(ref topleft); + topleft.Sym(ref toplcasing); + top.Lnext(ref topright); + topright.Sym(ref toprcasing); + flipedge.Lnext(ref botleft); + botleft.Sym(ref botlcasing); + flipedge.Lprev(ref botright); + botright.Sym(ref botrcasing); + // Rotate the quadrilateral one-quarter turn clockwise. + topleft.Bond(ref toprcasing); + botleft.Bond(ref toplcasing); + botright.Bond(ref botlcasing); + topright.Bond(ref botrcasing); + + if (checksegments) + { + // Check for subsegments and rebond them to the quadrilateral. + topleft.Pivot(ref toplsubseg); + botleft.Pivot(ref botlsubseg); + botright.Pivot(ref botrsubseg); + topright.Pivot(ref toprsubseg); + if (toplsubseg.seg.hash == DUMMY) + { + botleft.SegDissolve(dummysub); + } + else + { + botleft.SegBond(ref toplsubseg); + } + if (botlsubseg.seg.hash == DUMMY) + { + botright.SegDissolve(dummysub); + } + else + { + botright.SegBond(ref botlsubseg); + } + if (botrsubseg.seg.hash == DUMMY) + { + topright.SegDissolve(dummysub); + } + else + { + topright.SegBond(ref botrsubseg); + } + if (toprsubseg.seg.hash == DUMMY) + { + topleft.SegDissolve(dummysub); + } + else + { + topleft.SegBond(ref toprsubseg); + } + } + + // New vertex assignments for the rotated quadrilateral. + flipedge.SetOrg(botvertex); + flipedge.SetDest(farvertex); + flipedge.SetApex(leftvertex); + top.SetOrg(farvertex); + top.SetDest(botvertex); + top.SetApex(rightvertex); + } + + /// + /// Find the Delaunay triangulation of a polygon that has a certain "nice" shape. + /// This includes the polygons that result from deletion of a vertex or insertion + /// of a segment. + /// + /// The primary edge of the first triangle. + /// The primary edge of the last triangle. + /// The number of sides of the polygon, including its + /// base. + /// A flag, wether to perform the last flip. + /// A flag that determines whether the new triangles should + /// be tested for quality, and enqueued if they are bad. + /// + // This is a conceptually difficult routine. The starting assumption is + // that we have a polygon with n sides. n - 1 of these sides are currently + // represented as edges in the mesh. One side, called the "base", need not + // be. + // + // Inside the polygon is a structure I call a "fan", consisting of n - 1 + // triangles that share a common origin. For each of these triangles, the + // edge opposite the origin is one of the sides of the polygon. The + // primary edge of each triangle is the edge directed from the origin to + // the destination; note that this is not the same edge that is a side of + // the polygon. 'firstedge' is the primary edge of the first triangle. + // From there, the triangles follow in counterclockwise order about the + // polygon, until 'lastedge', the primary edge of the last triangle. + // 'firstedge' and 'lastedge' are probably connected to other triangles + // beyond the extremes of the fan, but their identity is not important, as + // long as the fan remains connected to them. + // + // Imagine the polygon oriented so that its base is at the bottom. This + // puts 'firstedge' on the far right, and 'lastedge' on the far left. + // The right vertex of the base is the destination of 'firstedge', and the + // left vertex of the base is the apex of 'lastedge'. + // + // The challenge now is to find the right sequence of edge flips to + // transform the fan into a Delaunay triangulation of the polygon. Each + // edge flip effectively removes one triangle from the fan, committing it + // to the polygon. The resulting polygon has one fewer edge. If 'doflip' + // is set, the final flip will be performed, resulting in a fan of one + // (useless?) triangle. If 'doflip' is not set, the final flip is not + // performed, resulting in a fan of two triangles, and an unfinished + // triangular polygon that is not yet filled out with a single triangle. + // On completion of the routine, 'lastedge' is the last remaining triangle, + // or the leftmost of the last two. + // + // Although the flips are performed in the order described above, the + // decisions about what flips to perform are made in precisely the reverse + // order. The recursive triangulatepolygon() procedure makes a decision, + // uses up to two recursive calls to triangulate the "subproblems" + // (polygons with fewer edges), and then performs an edge flip. + // + // The "decision" it makes is which vertex of the polygon should be + // connected to the base. This decision is made by testing every possible + // vertex. Once the best vertex is found, the two edges that connect this + // vertex to the base become the bases for two smaller polygons. These + // are triangulated recursively. Unfortunately, this approach can take + // O(n^2) time not only in the worst case, but in many common cases. It's + // rarely a big deal for vertex deletion, where n is rarely larger than + // ten, but it could be a big deal for segment insertion, especially if + // there's a lot of long segments that each cut many triangles. I ought to + // code a faster algorithm some day. + /// + private void TriangulatePolygon(Otri firstedge, Otri lastedge, + int edgecount, bool doflip, bool triflaws) + { + Otri testtri = default(Otri); + Otri besttri = default(Otri); + Otri tempedge = default(Otri); + Vertex leftbasevertex, rightbasevertex; + Vertex testvertex; + Vertex bestvertex; + + int bestnumber = 1; + + // Identify the base vertices. + leftbasevertex = lastedge.Apex(); + rightbasevertex = firstedge.Dest(); + + // Find the best vertex to connect the base to. + firstedge.Onext(ref besttri); + bestvertex = besttri.Dest(); + besttri.Copy(ref testtri); + + for (int i = 2; i <= edgecount - 2; i++) + { + testtri.Onext(); + testvertex = testtri.Dest(); + // Is this a better vertex? + if (predicates.InCircle(leftbasevertex, rightbasevertex, bestvertex, testvertex) > 0.0) + { + testtri.Copy(ref besttri); + bestvertex = testvertex; + bestnumber = i; + } + } + + if (bestnumber > 1) + { + // Recursively triangulate the smaller polygon on the right. + besttri.Oprev(ref tempedge); + TriangulatePolygon(firstedge, tempedge, bestnumber + 1, true, triflaws); + } + + if (bestnumber < edgecount - 2) + { + // Recursively triangulate the smaller polygon on the left. + besttri.Sym(ref tempedge); + TriangulatePolygon(besttri, lastedge, edgecount - bestnumber, true, triflaws); + // Find 'besttri' again; it may have been lost to edge flips. + tempedge.Sym(ref besttri); + } + + if (doflip) + { + // Do one final edge flip. + Flip(ref besttri); + if (triflaws) + { + // Check the quality of the newly committed triangle. + besttri.Sym(ref testtri); + qualityMesher.TestTriangle(ref testtri); + } + } + // Return the base triangle. + besttri.Copy(ref lastedge); + } + + /// + /// Delete a vertex from a Delaunay triangulation, ensuring that the + /// triangulation remains Delaunay. + /// + /// + /// The origin of 'deltri' is deleted. The union of the triangles + /// adjacent to this vertex is a polygon, for which the Delaunay triangulation + /// is found. Two triangles are removed from the mesh. + /// + /// Only interior vertices that do not lie on segments or boundaries + /// may be deleted. + /// + internal void DeleteVertex(ref Otri deltri) + { + Otri countingtri = default(Otri); + Otri firstedge = default(Otri), lastedge = default(Otri); + Otri deltriright = default(Otri); + Otri lefttri = default(Otri), righttri = default(Otri); + Otri leftcasing = default(Otri), rightcasing = default(Otri); + Osub leftsubseg = default(Osub), rightsubseg = default(Osub); + Vertex delvertex; + Vertex neworg; + int edgecount; + + delvertex = deltri.Org(); + + VertexDealloc(delvertex); + + // Count the degree of the vertex being deleted. + deltri.Onext(ref countingtri); + edgecount = 1; + while (!deltri.Equals(countingtri)) + { + edgecount++; + countingtri.Onext(); + } + + if (edgecount > 3) + { + // Triangulate the polygon defined by the union of all triangles + // adjacent to the vertex being deleted. Check the quality of + // the resulting triangles. + deltri.Onext(ref firstedge); + deltri.Oprev(ref lastedge); + TriangulatePolygon(firstedge, lastedge, edgecount, false, behavior.NoBisect == 0); + } + // Splice out two triangles. + deltri.Lprev(ref deltriright); + deltri.Dnext(ref lefttri); + lefttri.Sym(ref leftcasing); + deltriright.Oprev(ref righttri); + righttri.Sym(ref rightcasing); + deltri.Bond(ref leftcasing); + deltriright.Bond(ref rightcasing); + lefttri.Pivot(ref leftsubseg); + if (leftsubseg.seg.hash != DUMMY) + { + deltri.SegBond(ref leftsubseg); + } + righttri.Pivot(ref rightsubseg); + if (rightsubseg.seg.hash != DUMMY) + { + deltriright.SegBond(ref rightsubseg); + } + + // Set the new origin of 'deltri' and check its quality. + neworg = lefttri.Org(); + deltri.SetOrg(neworg); + if (behavior.NoBisect == 0) + { + qualityMesher.TestTriangle(ref deltri); + } + + // Delete the two spliced-out triangles. + TriangleDealloc(lefttri.tri); + TriangleDealloc(righttri.tri); + } + + /// + /// Undo the most recent vertex insertion. + /// + /// + /// Walks through the list of transformations (flips and a vertex insertion) + /// in the reverse of the order in which they were done, and undoes them. + /// The inserted vertex is removed from the triangulation and deallocated. + /// Two triangles (possibly just one) are also deallocated. + /// + internal void UndoVertex() + { + Otri fliptri; + + Otri botleft = default(Otri), botright = default(Otri), topright = default(Otri); + Otri botlcasing = default(Otri), botrcasing = default(Otri), toprcasing = default(Otri); + Otri gluetri = default(Otri); + Osub botlsubseg = default(Osub), botrsubseg = default(Osub), toprsubseg = default(Osub); + Vertex botvertex, rightvertex; + + // Walk through the list of transformations (flips and a vertex insertion) + // in the reverse of the order in which they were done, and undo them. + while (flipstack.Count > 0) + { + // Find a triangle involved in the last unreversed transformation. + fliptri = flipstack.Pop(); + + // We are reversing one of three transformations: a trisection of one + // triangle into three (by inserting a vertex in the triangle), a + // bisection of two triangles into four (by inserting a vertex in an + // edge), or an edge flip. + if (flipstack.Count == 0) + { + // Restore a triangle that was split into three triangles, + // so it is again one triangle. + fliptri.Dprev(ref botleft); + botleft.Lnext(); + fliptri.Onext(ref botright); + botright.Lprev(); + botleft.Sym(ref botlcasing); + botright.Sym(ref botrcasing); + botvertex = botleft.Dest(); + + fliptri.SetApex(botvertex); + fliptri.Lnext(); + fliptri.Bond(ref botlcasing); + botleft.Pivot(ref botlsubseg); + fliptri.SegBond(ref botlsubseg); + fliptri.Lnext(); + fliptri.Bond(ref botrcasing); + botright.Pivot(ref botrsubseg); + fliptri.SegBond(ref botrsubseg); + + // Delete the two spliced-out triangles. + TriangleDealloc(botleft.tri); + TriangleDealloc(botright.tri); + } + else if (flipstack.Peek().tri == null) // Dummy flip + { + // Restore two triangles that were split into four triangles, + // so they are again two triangles. + fliptri.Lprev(ref gluetri); + gluetri.Sym(ref botright); + botright.Lnext(); + botright.Sym(ref botrcasing); + rightvertex = botright.Dest(); + + fliptri.SetOrg(rightvertex); + gluetri.Bond(ref botrcasing); + botright.Pivot(ref botrsubseg); + gluetri.SegBond(ref botrsubseg); + + // Delete the spliced-out triangle. + TriangleDealloc(botright.tri); + + fliptri.Sym(ref gluetri); + if (gluetri.tri.id != DUMMY) + { + gluetri.Lnext(); + gluetri.Dnext(ref topright); + topright.Sym(ref toprcasing); + + gluetri.SetOrg(rightvertex); + gluetri.Bond(ref toprcasing); + topright.Pivot(ref toprsubseg); + gluetri.SegBond(ref toprsubseg); + + // Delete the spliced-out triangle. + TriangleDealloc(topright.tri); + } + + flipstack.Clear(); + } + else + { + // Undo an edge flip. + Unflip(ref fliptri); + } + } + } + + #endregion + + #region Dealloc + + /// + /// Deallocate space for a triangle, marking it dead. + /// + /// + internal void TriangleDealloc(Triangle dyingtriangle) + { + // Mark the triangle as dead. This makes it possible to detect dead + // triangles when traversing the list of all triangles. + Otri.Kill(dyingtriangle); + triangles.Release(dyingtriangle); + } + + /// + /// Deallocate space for a vertex, marking it dead. + /// + /// + internal void VertexDealloc(Vertex dyingvertex) + { + // Mark the vertex as dead. This makes it possible to detect dead + // vertices when traversing the list of all vertices. + dyingvertex.type = VertexType.DeadVertex; + vertices.Remove(dyingvertex.hash); + } + + /// + /// Deallocate space for a subsegment, marking it dead. + /// + /// + internal void SubsegDealloc(SubSegment dyingsubseg) + { + // Mark the subsegment as dead. This makes it possible to detect dead + // subsegments when traversing the list of all subsegments. + Osub.Kill(dyingsubseg); + subsegs.Remove(dyingsubseg.hash); + } + + #endregion + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Mesh.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Mesh.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..f9c7944352f70a42317ff145f36f72dab22e8fb2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Mesh.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: cf5fb0e34d9b14ac88f67bf18b0bc902 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/MeshValidator.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/MeshValidator.cs new file mode 100644 index 0000000000000000000000000000000000000000..8b55b30a7f4930caabdbd3288fdbc42d8207690a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/MeshValidator.cs @@ -0,0 +1,214 @@ +// ----------------------------------------------------------------------- +// +// Original Triangle code by Jonathan Richard Shewchuk, http://www.cs.cmu.edu/~quake/triangle.html +// Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/ +// +// ----------------------------------------------------------------------- + +namespace UnityEngine.U2D.Animation.TriangleNet +{ + using System; + using Animation.TriangleNet.Topology; + using Animation.TriangleNet.Geometry; + + internal static class MeshValidator + { + private static RobustPredicates predicates = RobustPredicates.Default; + + /// + /// Test the mesh for topological consistency. + /// + internal static bool IsConsistent(Mesh mesh) + { + Otri tri = default(Otri); + Otri oppotri = default(Otri), oppooppotri = default(Otri); + Vertex org, dest, apex; + Vertex oppoorg, oppodest; + + var logger = Log.Instance; + + // Temporarily turn on exact arithmetic if it's off. + bool saveexact = Behavior.NoExact; + Behavior.NoExact = false; + + int horrors = 0; + + // Run through the list of triangles, checking each one. + foreach (var t in mesh.triangles) + { + tri.tri = t; + + // Check all three edges of the triangle. + for (tri.orient = 0; tri.orient < 3; tri.orient++) + { + org = tri.Org(); + dest = tri.Dest(); + if (tri.orient == 0) + { + // Only test for inversion once. + // Test if the triangle is flat or inverted. + apex = tri.Apex(); + if (predicates.CounterClockwise(org, dest, apex) <= 0.0) + { + if (Log.Verbose) + { + logger.Warning(String.Format("Triangle is flat or inverted (ID {0}).", t.id), + "MeshValidator.IsConsistent()"); + } + + horrors++; + } + } + + // Find the neighboring triangle on this edge. + tri.Sym(ref oppotri); + if (oppotri.tri.id != Mesh.DUMMY) + { + // Check that the triangle's neighbor knows it's a neighbor. + oppotri.Sym(ref oppooppotri); + if ((tri.tri != oppooppotri.tri) || (tri.orient != oppooppotri.orient)) + { + if (tri.tri == oppooppotri.tri && Log.Verbose) + { + logger.Warning("Asymmetric triangle-triangle bond: (Right triangle, wrong orientation)", + "MeshValidator.IsConsistent()"); + } + + horrors++; + } + // Check that both triangles agree on the identities + // of their shared vertices. + oppoorg = oppotri.Org(); + oppodest = oppotri.Dest(); + if ((org != oppodest) || (dest != oppoorg)) + { + if (Log.Verbose) + { + logger.Warning("Mismatched edge coordinates between two triangles.", + "MeshValidator.IsConsistent()"); + } + + horrors++; + } + } + } + } + + // Check for unconnected vertices + mesh.MakeVertexMap(); + foreach (var v in mesh.vertices.Values) + { + if (v.tri.tri == null && Log.Verbose) + { + logger.Warning("Vertex (ID " + v.id + ") not connected to mesh (duplicate input vertex?)", + "MeshValidator.IsConsistent()"); + } + } + + // Restore the status of exact arithmetic. + Behavior.NoExact = saveexact; + + return (horrors == 0); + } + + /// + /// Check if the mesh is (conforming) Delaunay. + /// + internal static bool IsDelaunay(Mesh mesh) + { + return IsDelaunay(mesh, false); + } + + /// + /// Check if that the mesh is (constrained) Delaunay. + /// + internal static bool IsConstrainedDelaunay(Mesh mesh) + { + return IsDelaunay(mesh, true); + } + + /// + /// Ensure that the mesh is (constrained) Delaunay. + /// + private static bool IsDelaunay(Mesh mesh, bool constrained) + { + Otri loop = default(Otri); + Otri oppotri = default(Otri); + Osub opposubseg = default(Osub); + Vertex org, dest, apex; + Vertex oppoapex; + + bool shouldbedelaunay; + + var logger = Log.Instance; + + // Temporarily turn on exact arithmetic if it's off. + bool saveexact = Behavior.NoExact; + Behavior.NoExact = false; + + int horrors = 0; + + var inf1 = mesh.infvertex1; + var inf2 = mesh.infvertex2; + var inf3 = mesh.infvertex3; + + // Run through the list of triangles, checking each one. + foreach (var tri in mesh.triangles) + { + loop.tri = tri; + + // Check all three edges of the triangle. + for (loop.orient = 0; loop.orient < 3; loop.orient++) + { + org = loop.Org(); + dest = loop.Dest(); + apex = loop.Apex(); + + loop.Sym(ref oppotri); + oppoapex = oppotri.Apex(); + + // Only test that the edge is locally Delaunay if there is an + // adjoining triangle whose pointer is larger (to ensure that + // each pair isn't tested twice). + shouldbedelaunay = (loop.tri.id < oppotri.tri.id) && + !Otri.IsDead(oppotri.tri) && (oppotri.tri.id != Mesh.DUMMY) && + (org != inf1) && (org != inf2) && (org != inf3) && + (dest != inf1) && (dest != inf2) && (dest != inf3) && + (apex != inf1) && (apex != inf2) && (apex != inf3) && + (oppoapex != inf1) && (oppoapex != inf2) && (oppoapex != inf3); + + if (constrained && mesh.checksegments && shouldbedelaunay) + { + // If a subsegment separates the triangles, then the edge is + // constrained, so no local Delaunay test should be done. + loop.Pivot(ref opposubseg); + + if (opposubseg.seg.hash != Mesh.DUMMY) + { + shouldbedelaunay = false; + } + } + + if (shouldbedelaunay) + { + if (predicates.NonRegular(org, dest, apex, oppoapex) > 0.0) + { + if (Log.Verbose) + { + logger.Warning(String.Format("Non-regular pair of triangles found (IDs {0}/{1}).", + loop.tri.id, oppotri.tri.id), "MeshValidator.IsDelaunay()"); + } + + horrors++; + } + } + } + } + + // Restore the status of exact arithmetic. + Behavior.NoExact = saveexact; + + return (horrors == 0); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/MeshValidator.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/MeshValidator.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..9935e464a5507291b055fd556f16ada41aee8ed2 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/MeshValidator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8688318786c2246dbae9df88b4e94a46 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Meshing.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Meshing.meta new file mode 100644 index 0000000000000000000000000000000000000000..3125dcbe6779bf4305b0daef023fccc8677e808c --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Meshing.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 2e613ffc4de344b0cb197af2ee53feb5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/NewLocation.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/NewLocation.cs new file mode 100644 index 0000000000000000000000000000000000000000..2b2fe758c7621cc8522b8ddc15c885f1b916057b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/NewLocation.cs @@ -0,0 +1,4065 @@ +// ----------------------------------------------------------------------- +// +// Original code by Hale Erten and Alper Üngör, http://www.cise.ufl.edu/~ungor/aCute/index.html +// Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/ +// +// ----------------------------------------------------------------------- + +namespace UnityEngine.U2D.Animation.TriangleNet +{ + using System; + using Animation.TriangleNet.Topology; + using Animation.TriangleNet.Geometry; + using Animation.TriangleNet.Tools; + + /// + /// Find new Steiner point locations. + /// + /// + /// http://www.cise.ufl.edu/~ungor/aCute/index.html + /// + class NewLocation + { + const double EPS = 1e-50; + + IPredicates predicates; + + Mesh mesh; + Behavior behavior; + + // Work arrays for wegde intersection + double[] petalx = new double[20]; + double[] petaly = new double[20]; + double[] petalr = new double[20]; + double[] wedges = new double[500]; + double[] initialConvexPoly = new double[500]; + + // Work arrays for smoothing + double[] points_p = new double[500]; + double[] points_q = new double[500]; + double[] points_r = new double[500]; + + // Work arrays for convex polygon split + double[] poly1 = new double[100]; + double[] poly2 = new double[100]; + double[][] polys = new double[3][]; + + public NewLocation(Mesh mesh, IPredicates predicates) + { + this.mesh = mesh; + this.predicates = predicates; + + this.behavior = mesh.behavior; + } + + /// + /// Find a new location for a Steiner point. + /// + /// + /// + /// + /// + /// + /// + /// + /// + public Point FindLocation(Vertex org, Vertex dest, Vertex apex, + ref double xi, ref double eta, bool offcenter, Otri badotri) + { + // Based on using -U switch, call the corresponding function + if (behavior.MaxAngle == 0.0) + { + // Disable the "no max angle" code. It may return weired vertex locations. + return FindNewLocationWithoutMaxAngle(org, dest, apex, ref xi, ref eta, true, badotri); + } + + // With max angle + return FindNewLocation(org, dest, apex, ref xi, ref eta, true, badotri); + } + + /// + /// Find a new location for a Steiner point. + /// + /// + /// + /// + /// + /// + /// + /// + /// + private Point FindNewLocationWithoutMaxAngle(Vertex torg, Vertex tdest, Vertex tapex, + ref double xi, ref double eta, bool offcenter, Otri badotri) + { + double offconstant = behavior.offconstant; + + // for calculating the distances of the edges + double xdo, ydo, xao, yao, xda, yda; + double dodist, aodist, dadist; + // for exact calculation + double denominator; + double dx, dy, dxoff, dyoff; + + ////////////////////////////// HALE'S VARIABLES ////////////////////////////// + // keeps the difference of coordinates edge + double xShortestEdge = 0, yShortestEdge = 0; + + // keeps the square of edge lengths + double shortestEdgeDist = 0, middleEdgeDist = 0, longestEdgeDist = 0; + + // keeps the vertices according to the angle incident to that vertex in a triangle + Point smallestAngleCorner, middleAngleCorner, largestAngleCorner; + + // keeps the type of orientation if the triangle + int orientation = 0; + // keeps the coordinates of circumcenter of itself and neighbor triangle circumcenter + Point myCircumcenter, neighborCircumcenter; + + // keeps if bad triangle is almost good or not + int almostGood = 0; + // keeps the cosine of the largest angle + double cosMaxAngle; + bool isObtuse; // 1: obtuse 0: nonobtuse + // keeps the radius of petal + double petalRadius; + // for calculating petal center + double xPetalCtr_1, yPetalCtr_1, xPetalCtr_2, yPetalCtr_2, xPetalCtr, yPetalCtr, xMidOfShortestEdge, yMidOfShortestEdge; + double dxcenter1, dycenter1, dxcenter2, dycenter2; + // for finding neighbor + Otri neighborotri = default(Otri); + double[] thirdPoint = new double[2]; + //int neighborNotFound = -1; + bool neighborNotFound; + // for keeping the vertices of the neighbor triangle + Vertex neighborvertex_1; + Vertex neighborvertex_2; + Vertex neighborvertex_3; + // dummy variables + double xi_tmp = 0, eta_tmp = 0; + //vertex thirdVertex; + // for petal intersection + double vector_x, vector_y, xMidOfLongestEdge, yMidOfLongestEdge, inter_x, inter_y; + double[] p = new double[5], voronoiOrInter = new double[4]; + bool isCorrect; + + // for vector calculations in perturbation + double ax, ay, d; + double pertConst = 0.06; // perturbation constant + + double lengthConst = 1; // used at comparing circumcenter's distance to proposed point's distance + double justAcute = 1; // used for making the program working for one direction only + // for smoothing + int relocated = 0;// used to differentiate between calling the deletevertex and just proposing a steiner point + double[] newloc = new double[2]; // new location suggested by smoothing + double origin_x = 0, origin_y = 0; // for keeping torg safe + Otri delotri; // keeping the original orientation for relocation process + // keeps the first and second direction suggested points + double dxFirstSuggestion, dyFirstSuggestion, dxSecondSuggestion, dySecondSuggestion; + // second direction variables + double xMidOfMiddleEdge, yMidOfMiddleEdge; + ////////////////////////////// END OF HALE'S VARIABLES ////////////////////////////// + + Statistic.CircumcenterCount++; + + // Compute the circumcenter of the triangle. + xdo = tdest.x - torg.x; + ydo = tdest.y - torg.y; + xao = tapex.x - torg.x; + yao = tapex.y - torg.y; + xda = tapex.x - tdest.x; + yda = tapex.y - tdest.y; + // keeps the square of the distances + dodist = xdo * xdo + ydo * ydo; + aodist = xao * xao + yao * yao; + dadist = (tdest.x - tapex.x) * (tdest.x - tapex.x) + + (tdest.y - tapex.y) * (tdest.y - tapex.y); + // checking if the user wanted exact arithmetic or not + if (Behavior.NoExact) + { + denominator = 0.5 / (xdo * yao - xao * ydo); + } + else + { + // Use the counterclockwise() routine to ensure a positive (and + // reasonably accurate) result, avoiding any possibility of + // division by zero. + denominator = 0.5 / predicates.CounterClockwise(tdest, tapex, torg); + // Don't count the above as an orientation test. + Statistic.CounterClockwiseCount--; + } + // calculate the circumcenter in terms of distance to origin point + dx = (yao * dodist - ydo * aodist) * denominator; + dy = (xdo * aodist - xao * dodist) * denominator; + // for debugging and for keeping circumcenter to use later + // coordinate value of the circumcenter + myCircumcenter = new Point(torg.x + dx, torg.y + dy); + + delotri = badotri; // save for later + ///////////////// FINDING THE ORIENTATION OF TRIANGLE ////////////////// + // Find the (squared) length of the triangle's shortest edge. This + // serves as a conservative estimate of the insertion radius of the + // circumcenter's parent. The estimate is used to ensure that + // the algorithm terminates even if very small angles appear in + // the input PSLG. + // find the orientation of the triangle, basically shortest and longest edges + orientation = LongestShortestEdge(aodist, dadist, dodist); + //printf("org: (%f,%f), dest: (%f,%f), apex: (%f,%f)\n",torg[0],torg[1],tdest[0],tdest[1],tapex[0],tapex[1]); + ///////////////////////////////////////////////////////////////////////////////////////////// + // 123: shortest: aodist // 213: shortest: dadist // 312: shortest: dodist // + // middle: dadist // middle: aodist // middle: aodist // + // longest: dodist // longest: dodist // longest: dadist // + // 132: shortest: aodist // 231: shortest: dadist // 321: shortest: dodist // + // middle: dodist // middle: dodist // middle: dadist // + // longest: dadist // longest: aodist // longest: aodist // + ///////////////////////////////////////////////////////////////////////////////////////////// + + switch (orientation) + { + case 123: // assign necessary information + /// smallest angle corner: dest + /// largest angle corner: apex + xShortestEdge = xao; yShortestEdge = yao; + + shortestEdgeDist = aodist; + middleEdgeDist = dadist; + longestEdgeDist = dodist; + + smallestAngleCorner = tdest; + middleAngleCorner = torg; + largestAngleCorner = tapex; + break; + + case 132: // assign necessary information + /// smallest angle corner: dest + /// largest angle corner: org + xShortestEdge = xao; yShortestEdge = yao; + + shortestEdgeDist = aodist; + middleEdgeDist = dodist; + longestEdgeDist = dadist; + + smallestAngleCorner = tdest; + middleAngleCorner = tapex; + largestAngleCorner = torg; + + break; + case 213: // assign necessary information + /// smallest angle corner: org + /// largest angle corner: apex + xShortestEdge = xda; yShortestEdge = yda; + + shortestEdgeDist = dadist; + middleEdgeDist = aodist; + longestEdgeDist = dodist; + + smallestAngleCorner = torg; + middleAngleCorner = tdest; + largestAngleCorner = tapex; + break; + case 231: // assign necessary information + /// smallest angle corner: org + /// largest angle corner: dest + xShortestEdge = xda; yShortestEdge = yda; + + shortestEdgeDist = dadist; + middleEdgeDist = dodist; + longestEdgeDist = aodist; + + smallestAngleCorner = torg; + middleAngleCorner = tapex; + largestAngleCorner = tdest; + break; + case 312: // assign necessary information + /// smallest angle corner: apex + /// largest angle corner: org + xShortestEdge = xdo; yShortestEdge = ydo; + + shortestEdgeDist = dodist; + middleEdgeDist = aodist; + longestEdgeDist = dadist; + + smallestAngleCorner = tapex; + middleAngleCorner = tdest; + largestAngleCorner = torg; + break; + case 321: // assign necessary information + default: // TODO: is this safe? + /// smallest angle corner: apex + /// largest angle corner: dest + xShortestEdge = xdo; yShortestEdge = ydo; + + shortestEdgeDist = dodist; + middleEdgeDist = dadist; + longestEdgeDist = aodist; + + smallestAngleCorner = tapex; + middleAngleCorner = torg; + largestAngleCorner = tdest; + break; + }// end of switch + // check for offcenter condition + if (offcenter && (offconstant > 0.0)) + { + // origin has the smallest angle + if (orientation == 213 || orientation == 231) + { + // Find the position of the off-center, as described by Alper Ungor. + dxoff = 0.5 * xShortestEdge - offconstant * yShortestEdge; + dyoff = 0.5 * yShortestEdge + offconstant * xShortestEdge; + // If the off-center is closer to destination than the + // circumcenter, use the off-center instead. + /// doubleLY BAD CASE /// + if (dxoff * dxoff + dyoff * dyoff < + (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo)) + { + dx = xdo + dxoff; + dy = ydo + dyoff; + } + /// ALMOST GOOD CASE /// + else + { + almostGood = 1; + } + // destination has the smallest angle + } + else if (orientation == 123 || orientation == 132) + { + // Find the position of the off-center, as described by Alper Ungor. + dxoff = 0.5 * xShortestEdge + offconstant * yShortestEdge; + dyoff = 0.5 * yShortestEdge - offconstant * xShortestEdge; + // If the off-center is closer to the origin than the + // circumcenter, use the off-center instead. + /// doubleLY BAD CASE /// + if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) + { + dx = dxoff; + dy = dyoff; + } + /// ALMOST GOOD CASE /// + else + { + almostGood = 1; + } + // apex has the smallest angle + } + else + {//orientation == 312 || orientation == 321 + // Find the position of the off-center, as described by Alper Ungor. + dxoff = 0.5 * xShortestEdge - offconstant * yShortestEdge; + dyoff = 0.5 * yShortestEdge + offconstant * xShortestEdge; + // If the off-center is closer to the origin than the + // circumcenter, use the off-center instead. + /// doubleLY BAD CASE /// + if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) + { + dx = dxoff; + dy = dyoff; + } + /// ALMOST GOOD CASE /// + else + { + almostGood = 1; + } + } + } + // if the bad triangle is almost good, apply our approach + if (almostGood == 1) + { + /// calculate cosine of largest angle /// + cosMaxAngle = (middleEdgeDist + shortestEdgeDist - longestEdgeDist) / (2 * Math.Sqrt(middleEdgeDist) * Math.Sqrt(shortestEdgeDist)); + if (cosMaxAngle < 0.0) + { + // obtuse + isObtuse = true; + } + else if (Math.Abs(cosMaxAngle - 0.0) <= EPS) + { + // right triangle (largest angle is 90 degrees) + isObtuse = true; + } + else + { + // nonobtuse + isObtuse = false; + } + /// RELOCATION (LOCAL SMOOTHING) /// + /// check for possible relocation of one of triangle's points /// + relocated = DoSmoothing(delotri, torg, tdest, tapex, ref newloc); + /// if relocation is possible, delete that vertex and insert a vertex at the new location /// + if (relocated > 0) + { + Statistic.RelocationCount++; + + dx = newloc[0] - torg.x; + dy = newloc[1] - torg.y; + origin_x = torg.x; // keep for later use + origin_y = torg.y; + switch (relocated) + { + case 1: + //printf("Relocate: (%f,%f)\n", torg[0],torg[1]); + mesh.DeleteVertex(ref delotri); + break; + case 2: + //printf("Relocate: (%f,%f)\n", tdest[0],tdest[1]); + delotri.Lnext(); + mesh.DeleteVertex(ref delotri); + break; + case 3: + //printf("Relocate: (%f,%f)\n", tapex[0],tapex[1]); + delotri.Lprev(); + mesh.DeleteVertex(ref delotri); + break; + } + } + else + { + // calculate radius of the petal according to angle constraint + // first find the visible region, PETAL + // find the center of the circle and radius + petalRadius = Math.Sqrt(shortestEdgeDist) / (2 * Math.Sin(behavior.MinAngle * Math.PI / 180.0)); + /// compute two possible centers of the petal /// + // finding the center + // first find the middle point of smallest edge + xMidOfShortestEdge = (middleAngleCorner.x + largestAngleCorner.x) / 2.0; + yMidOfShortestEdge = (middleAngleCorner.y + largestAngleCorner.y) / 2.0; + // two possible centers + xPetalCtr_1 = xMidOfShortestEdge + Math.Sqrt(petalRadius * petalRadius - (shortestEdgeDist / 4)) * (middleAngleCorner.y - + largestAngleCorner.y) / Math.Sqrt(shortestEdgeDist); + yPetalCtr_1 = yMidOfShortestEdge + Math.Sqrt(petalRadius * petalRadius - (shortestEdgeDist / 4)) * (largestAngleCorner.x - + middleAngleCorner.x) / Math.Sqrt(shortestEdgeDist); + + xPetalCtr_2 = xMidOfShortestEdge - Math.Sqrt(petalRadius * petalRadius - (shortestEdgeDist / 4)) * (middleAngleCorner.y - + largestAngleCorner.y) / Math.Sqrt(shortestEdgeDist); + yPetalCtr_2 = yMidOfShortestEdge - Math.Sqrt(petalRadius * petalRadius - (shortestEdgeDist / 4)) * (largestAngleCorner.x - + middleAngleCorner.x) / Math.Sqrt(shortestEdgeDist); + // find the correct circle since there will be two possible circles + // calculate the distance to smallest angle corner + dxcenter1 = (xPetalCtr_1 - smallestAngleCorner.x) * (xPetalCtr_1 - smallestAngleCorner.x); + dycenter1 = (yPetalCtr_1 - smallestAngleCorner.y) * (yPetalCtr_1 - smallestAngleCorner.y); + dxcenter2 = (xPetalCtr_2 - smallestAngleCorner.x) * (xPetalCtr_2 - smallestAngleCorner.x); + dycenter2 = (yPetalCtr_2 - smallestAngleCorner.y) * (yPetalCtr_2 - smallestAngleCorner.y); + + // whichever is closer to smallest angle corner, it must be the center + if (dxcenter1 + dycenter1 <= dxcenter2 + dycenter2) + { + xPetalCtr = xPetalCtr_1; yPetalCtr = yPetalCtr_1; + } + else + { + xPetalCtr = xPetalCtr_2; yPetalCtr = yPetalCtr_2; + } + + /// find the third point of the neighbor triangle /// + neighborNotFound = GetNeighborsVertex(badotri, middleAngleCorner.x, middleAngleCorner.y, + smallestAngleCorner.x, smallestAngleCorner.y, ref thirdPoint, ref neighborotri); + /// find the circumcenter of the neighbor triangle /// + dxFirstSuggestion = dx; // if we cannot find any appropriate suggestion, we use circumcenter + dyFirstSuggestion = dy; + // if there is a neighbor triangle + if (!neighborNotFound) + { + neighborvertex_1 = neighborotri.Org(); + neighborvertex_2 = neighborotri.Dest(); + neighborvertex_3 = neighborotri.Apex(); + // now calculate neighbor's circumcenter which is the voronoi site + neighborCircumcenter = predicates.FindCircumcenter(neighborvertex_1, neighborvertex_2, neighborvertex_3, + ref xi_tmp, ref eta_tmp); + + /// compute petal and Voronoi edge intersection /// + // in order to avoid degenerate cases, we need to do a vector based calculation for line + vector_x = (middleAngleCorner.y - smallestAngleCorner.y);//(-y, x) + vector_y = smallestAngleCorner.x - middleAngleCorner.x; + vector_x = myCircumcenter.x + vector_x; + vector_y = myCircumcenter.y + vector_y; + + + // by intersecting bisectors you will end up with the one you want to walk on + // then this line and circle should be intersected + CircleLineIntersection(myCircumcenter.x, myCircumcenter.y, vector_x, vector_y, + xPetalCtr, yPetalCtr, petalRadius, ref p); + /// choose the correct intersection point /// + // calculate middle point of the longest edge(bisector) + xMidOfLongestEdge = (middleAngleCorner.x + smallestAngleCorner.x) / 2.0; + yMidOfLongestEdge = (middleAngleCorner.y + smallestAngleCorner.y) / 2.0; + // we need to find correct intersection point, since line intersects circle twice + isCorrect = ChooseCorrectPoint(xMidOfLongestEdge, yMidOfLongestEdge, p[3], p[4], + myCircumcenter.x, myCircumcenter.y, isObtuse); + // make sure which point is the correct one to be considered + if (isCorrect) + { + inter_x = p[3]; + inter_y = p[4]; + } + else + { + inter_x = p[1]; + inter_y = p[2]; + } + /// check if there is a Voronoi vertex between before intersection /// + // check if the voronoi vertex is between the intersection and circumcenter + PointBetweenPoints(inter_x, inter_y, myCircumcenter.x, myCircumcenter.y, + neighborCircumcenter.x, neighborCircumcenter.y, ref voronoiOrInter); + + /// determine the point to be suggested /// + if (p[0] > 0.0) + { // there is at least one intersection point + // if it is between circumcenter and intersection + // if it returns 1.0 this means we have a voronoi vertex within feasible region + if (Math.Abs(voronoiOrInter[0] - 1.0) <= EPS) + { + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, neighborCircumcenter.x, neighborCircumcenter.y)) + { + // go back to circumcenter + dxFirstSuggestion = dx; + dyFirstSuggestion = dy; + } + else + { // we are not creating a bad triangle + // neighbor's circumcenter is suggested + dxFirstSuggestion = voronoiOrInter[2] - torg.x; + dyFirstSuggestion = voronoiOrInter[3] - torg.y; + } + } + else + { // there is no voronoi vertex between intersection point and circumcenter + if (IsBadTriangleAngle(largestAngleCorner.x, largestAngleCorner.y, middleAngleCorner.x, middleAngleCorner.y, inter_x, inter_y)) + { + // if it is inside feasible region, then insert v2 + // apply perturbation + // find the distance between circumcenter and intersection point + d = Math.Sqrt((inter_x - myCircumcenter.x) * (inter_x - myCircumcenter.x) + + (inter_y - myCircumcenter.y) * (inter_y - myCircumcenter.y)); + // then find the vector going from intersection point to circumcenter + ax = myCircumcenter.x - inter_x; + ay = myCircumcenter.y - inter_y; + + ax = ax / d; + ay = ay / d; + // now calculate the new intersection point which is perturbated towards the circumcenter + inter_x = inter_x + ax * pertConst * Math.Sqrt(shortestEdgeDist); + inter_y = inter_y + ay * pertConst * Math.Sqrt(shortestEdgeDist); + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, inter_x, inter_y)) + { + // go back to circumcenter + dxFirstSuggestion = dx; + dyFirstSuggestion = dy; + } + else + { + // intersection point is suggested + dxFirstSuggestion = inter_x - torg.x; + dyFirstSuggestion = inter_y - torg.y; + } + } + else + { + // intersection point is suggested + dxFirstSuggestion = inter_x - torg.x; + dyFirstSuggestion = inter_y - torg.y; + } + } + /// if it is an acute triangle, check if it is a good enough location /// + // for acute triangle case, we need to check if it is ok to use either of them + if ((smallestAngleCorner.x - myCircumcenter.x) * (smallestAngleCorner.x - myCircumcenter.x) + + (smallestAngleCorner.y - myCircumcenter.y) * (smallestAngleCorner.y - myCircumcenter.y) > + lengthConst * ((smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) + + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y)) * + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y)))) + { + // use circumcenter + dxFirstSuggestion = dx; + dyFirstSuggestion = dy; + }// else we stick to what we have found + }// intersection point + }// if it is on the boundary, meaning no neighbor triangle in this direction, try other direction + + /// DO THE SAME THING FOR THE OTHER DIRECTION /// + /// find the third point of the neighbor triangle /// + neighborNotFound = GetNeighborsVertex(badotri, largestAngleCorner.x, largestAngleCorner.y, + smallestAngleCorner.x, smallestAngleCorner.y, ref thirdPoint, ref neighborotri); + /// find the circumcenter of the neighbor triangle /// + dxSecondSuggestion = dx; // if we cannot find any appropriate suggestion, we use circumcenter + dySecondSuggestion = dy; + // if there is a neighbor triangle + if (!neighborNotFound) + { + neighborvertex_1 = neighborotri.Org(); + neighborvertex_2 = neighborotri.Dest(); + neighborvertex_3 = neighborotri.Apex(); + // now calculate neighbor's circumcenter which is the voronoi site + neighborCircumcenter = predicates.FindCircumcenter(neighborvertex_1, neighborvertex_2, neighborvertex_3, + ref xi_tmp, ref eta_tmp); + + /// compute petal and Voronoi edge intersection /// + // in order to avoid degenerate cases, we need to do a vector based calculation for line + vector_x = (largestAngleCorner.y - smallestAngleCorner.y);//(-y, x) + vector_y = smallestAngleCorner.x - largestAngleCorner.x; + vector_x = myCircumcenter.x + vector_x; + vector_y = myCircumcenter.y + vector_y; + + + // by intersecting bisectors you will end up with the one you want to walk on + // then this line and circle should be intersected + CircleLineIntersection(myCircumcenter.x, myCircumcenter.y, vector_x, vector_y, + xPetalCtr, yPetalCtr, petalRadius, ref p); + + /// choose the correct intersection point /// + // calcuwedgeslate middle point of the longest edge(bisector) + xMidOfMiddleEdge = (largestAngleCorner.x + smallestAngleCorner.x) / 2.0; + yMidOfMiddleEdge = (largestAngleCorner.y + smallestAngleCorner.y) / 2.0; + // we need to find correct intersection point, since line intersects circle twice + // this direction is always ACUTE + isCorrect = ChooseCorrectPoint(xMidOfMiddleEdge, yMidOfMiddleEdge, p[3], p[4], + myCircumcenter.x, myCircumcenter.y, false /*(isObtuse+1)%2*/); + // make sure which point is the correct one to be considered + if (isCorrect) + { + inter_x = p[3]; + inter_y = p[4]; + } + else + { + inter_x = p[1]; + inter_y = p[2]; + } + + /// check if there is a Voronoi vertex between before intersection /// + // check if the voronoi vertex is between the intersection and circumcenter + PointBetweenPoints(inter_x, inter_y, myCircumcenter.x, myCircumcenter.y, + neighborCircumcenter.x, neighborCircumcenter.y, ref voronoiOrInter); + + /// determine the point to be suggested /// + if (p[0] > 0.0) + { // there is at least one intersection point + // if it is between circumcenter and intersection + // if it returns 1.0 this means we have a voronoi vertex within feasible region + if (Math.Abs(voronoiOrInter[0] - 1.0) <= EPS) + { + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, neighborCircumcenter.x, neighborCircumcenter.y)) + { + // go back to circumcenter + dxSecondSuggestion = dx; + dySecondSuggestion = dy; + } + else + { // we are not creating a bad triangle + // neighbor's circumcenter is suggested + dxSecondSuggestion = voronoiOrInter[2] - torg.x; + dySecondSuggestion = voronoiOrInter[3] - torg.y; + } + } + else + { // there is no voronoi vertex between intersection point and circumcenter + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, inter_x, inter_y)) + { + // if it is inside feasible region, then insert v2 + // apply perturbation + // find the distance between circumcenter and intersection point + d = Math.Sqrt((inter_x - myCircumcenter.x) * (inter_x - myCircumcenter.x) + + (inter_y - myCircumcenter.y) * (inter_y - myCircumcenter.y)); + // then find the vector going from intersection point to circumcenter + ax = myCircumcenter.x - inter_x; + ay = myCircumcenter.y - inter_y; + + ax = ax / d; + ay = ay / d; + // now calculate the new intersection point which is perturbated towards the circumcenter + inter_x = inter_x + ax * pertConst * Math.Sqrt(shortestEdgeDist); + inter_y = inter_y + ay * pertConst * Math.Sqrt(shortestEdgeDist); + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, inter_x, inter_y)) + { + // go back to circumcenter + dxSecondSuggestion = dx; + dySecondSuggestion = dy; + } + else + { + // intersection point is suggested + dxSecondSuggestion = inter_x - torg.x; + dySecondSuggestion = inter_y - torg.y; + } + } + else + { + // intersection point is suggested + dxSecondSuggestion = inter_x - torg.x; + dySecondSuggestion = inter_y - torg.y; + } + } + /// if it is an acute triangle, check if it is a good enough location /// + // for acute triangle case, we need to check if it is ok to use either of them + if ((smallestAngleCorner.x - myCircumcenter.x) * (smallestAngleCorner.x - myCircumcenter.x) + + (smallestAngleCorner.y - myCircumcenter.y) * (smallestAngleCorner.y - myCircumcenter.y) > + lengthConst * ((smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) + + (smallestAngleCorner.y - (dySecondSuggestion + torg.y)) * + (smallestAngleCorner.y - (dySecondSuggestion + torg.y)))) + { + // use circumcenter + dxSecondSuggestion = dx; + dySecondSuggestion = dy; + }// else we stick on what we have found + } + }// if it is on the boundary, meaning no neighbor triangle in this direction, the other direction might be ok + if (isObtuse) + { + //obtuse: do nothing + dx = dxFirstSuggestion; + dy = dyFirstSuggestion; + } + else + { // acute : consider other direction + if (justAcute * ((smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) + + (smallestAngleCorner.y - (dySecondSuggestion + torg.y)) * + (smallestAngleCorner.y - (dySecondSuggestion + torg.y))) > + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) + + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y)) * + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y))) + { + dx = dxSecondSuggestion; + dy = dySecondSuggestion; + } + else + { + dx = dxFirstSuggestion; + dy = dyFirstSuggestion; + } + }// end if obtuse + }// end of relocation + }// end of almostGood + + Point circumcenter = new Point(); + + if (relocated <= 0) + { + circumcenter.x = torg.x + dx; + circumcenter.y = torg.y + dy; + } + else + { + circumcenter.x = origin_x + dx; + circumcenter.y = origin_y + dy; + } + + xi = (yao * dx - xao * dy) * (2.0 * denominator); + eta = (xdo * dy - ydo * dx) * (2.0 * denominator); + + return circumcenter; + } + + /// + /// Find a new location for a Steiner point. + /// + /// + /// + /// + /// + /// + /// + /// + /// + private Point FindNewLocation(Vertex torg, Vertex tdest, Vertex tapex, + ref double xi, ref double eta, bool offcenter, Otri badotri) + { + double offconstant = behavior.offconstant; + + // for calculating the distances of the edges + double xdo, ydo, xao, yao, xda, yda; + double dodist, aodist, dadist; + // for exact calculation + double denominator; + double dx, dy, dxoff, dyoff; + + ////////////////////////////// HALE'S VARIABLES ////////////////////////////// + // keeps the difference of coordinates edge + double xShortestEdge = 0, yShortestEdge = 0; + + // keeps the square of edge lengths + double shortestEdgeDist = 0, middleEdgeDist = 0, longestEdgeDist = 0; + + // keeps the vertices according to the angle incident to that vertex in a triangle + Point smallestAngleCorner, middleAngleCorner, largestAngleCorner; + + // keeps the type of orientation if the triangle + int orientation = 0; + // keeps the coordinates of circumcenter of itself and neighbor triangle circumcenter + Point myCircumcenter, neighborCircumcenter; + + // keeps if bad triangle is almost good or not + int almostGood = 0; + // keeps the cosine of the largest angle + double cosMaxAngle; + bool isObtuse; // 1: obtuse 0: nonobtuse + // keeps the radius of petal + double petalRadius; + // for calculating petal center + double xPetalCtr_1, yPetalCtr_1, xPetalCtr_2, yPetalCtr_2, xPetalCtr, yPetalCtr, xMidOfShortestEdge, yMidOfShortestEdge; + double dxcenter1, dycenter1, dxcenter2, dycenter2; + // for finding neighbor + Otri neighborotri = default(Otri); + double[] thirdPoint = new double[2]; + //int neighborNotFound = -1; + // for keeping the vertices of the neighbor triangle + Vertex neighborvertex_1; + Vertex neighborvertex_2; + Vertex neighborvertex_3; + // dummy variables + double xi_tmp = 0, eta_tmp = 0; + //vertex thirdVertex; + // for petal intersection + double vector_x, vector_y, xMidOfLongestEdge, yMidOfLongestEdge, inter_x, inter_y; + double[] p = new double[5], voronoiOrInter = new double[4]; + bool isCorrect; + + // for vector calculations in perturbation + double ax, ay, d; + double pertConst = 0.06; // perturbation constant + + double lengthConst = 1; // used at comparing circumcenter's distance to proposed point's distance + double justAcute = 1; // used for making the program working for one direction only + // for smoothing + int relocated = 0;// used to differentiate between calling the deletevertex and just proposing a steiner point + double[] newloc = new double[2]; // new location suggested by smoothing + double origin_x = 0, origin_y = 0; // for keeping torg safe + Otri delotri; // keeping the original orientation for relocation process + // keeps the first and second direction suggested points + double dxFirstSuggestion, dyFirstSuggestion, dxSecondSuggestion, dySecondSuggestion; + // second direction variables + double xMidOfMiddleEdge, yMidOfMiddleEdge; + + double minangle; // in order to make sure that the circumcircle of the bad triangle is greater than petal + // for calculating the slab + double linepnt1_x, linepnt1_y, linepnt2_x, linepnt2_y; // two points of the line + double line_inter_x = 0, line_inter_y = 0; + double line_vector_x, line_vector_y; + double[] line_p = new double[3]; // used for getting the return values of functions related to line intersection + double[] line_result = new double[4]; + // intersection of slab and the petal + double petal_slab_inter_x_first, petal_slab_inter_y_first, petal_slab_inter_x_second, petal_slab_inter_y_second, x_1, y_1, x_2, y_2; + double petal_bisector_x, petal_bisector_y, dist; + double alpha; + bool neighborNotFound_first; + bool neighborNotFound_second; + ////////////////////////////// END OF HALE'S VARIABLES ////////////////////////////// + + Statistic.CircumcenterCount++; + + // Compute the circumcenter of the triangle. + xdo = tdest.x - torg.x; + ydo = tdest.y - torg.y; + xao = tapex.x - torg.x; + yao = tapex.y - torg.y; + xda = tapex.x - tdest.x; + yda = tapex.y - tdest.y; + // keeps the square of the distances + dodist = xdo * xdo + ydo * ydo; + aodist = xao * xao + yao * yao; + dadist = (tdest.x - tapex.x) * (tdest.x - tapex.x) + + (tdest.y - tapex.y) * (tdest.y - tapex.y); + // checking if the user wanted exact arithmetic or not + if (Behavior.NoExact) + { + denominator = 0.5 / (xdo * yao - xao * ydo); + } + else + { + // Use the counterclockwise() routine to ensure a positive (and + // reasonably accurate) result, avoiding any possibility of + // division by zero. + denominator = 0.5 / predicates.CounterClockwise(tdest, tapex, torg); + // Don't count the above as an orientation test. + Statistic.CounterClockwiseCount--; + } + // calculate the circumcenter in terms of distance to origin point + dx = (yao * dodist - ydo * aodist) * denominator; + dy = (xdo * aodist - xao * dodist) * denominator; + // for debugging and for keeping circumcenter to use later + // coordinate value of the circumcenter + myCircumcenter = new Point(torg.x + dx, torg.y + dy); + + delotri = badotri; // save for later + ///////////////// FINDING THE ORIENTATION OF TRIANGLE ////////////////// + // Find the (squared) length of the triangle's shortest edge. This + // serves as a conservative estimate of the insertion radius of the + // circumcenter's parent. The estimate is used to ensure that + // the algorithm terminates even if very small angles appear in + // the input PSLG. + // find the orientation of the triangle, basically shortest and longest edges + orientation = LongestShortestEdge(aodist, dadist, dodist); + //printf("org: (%f,%f), dest: (%f,%f), apex: (%f,%f)\n",torg[0],torg[1],tdest[0],tdest[1],tapex[0],tapex[1]); + ///////////////////////////////////////////////////////////////////////////////////////////// + // 123: shortest: aodist // 213: shortest: dadist // 312: shortest: dodist // + // middle: dadist // middle: aodist // middle: aodist // + // longest: dodist // longest: dodist // longest: dadist // + // 132: shortest: aodist // 231: shortest: dadist // 321: shortest: dodist // + // middle: dodist // middle: dodist // middle: dadist // + // longest: dadist // longest: aodist // longest: aodist // + ///////////////////////////////////////////////////////////////////////////////////////////// + + switch (orientation) + { + case 123: // assign necessary information + /// smallest angle corner: dest + /// largest angle corner: apex + xShortestEdge = xao; yShortestEdge = yao; + + shortestEdgeDist = aodist; + middleEdgeDist = dadist; + longestEdgeDist = dodist; + + smallestAngleCorner = tdest; + middleAngleCorner = torg; + largestAngleCorner = tapex; + break; + + case 132: // assign necessary information + /// smallest angle corner: dest + /// largest angle corner: org + xShortestEdge = xao; yShortestEdge = yao; + + shortestEdgeDist = aodist; + middleEdgeDist = dodist; + longestEdgeDist = dadist; + + smallestAngleCorner = tdest; + middleAngleCorner = tapex; + largestAngleCorner = torg; + + break; + case 213: // assign necessary information + /// smallest angle corner: org + /// largest angle corner: apex + xShortestEdge = xda; yShortestEdge = yda; + + shortestEdgeDist = dadist; + middleEdgeDist = aodist; + longestEdgeDist = dodist; + + smallestAngleCorner = torg; + middleAngleCorner = tdest; + largestAngleCorner = tapex; + break; + case 231: // assign necessary information + /// smallest angle corner: org + /// largest angle corner: dest + xShortestEdge = xda; yShortestEdge = yda; + + shortestEdgeDist = dadist; + middleEdgeDist = dodist; + longestEdgeDist = aodist; + + smallestAngleCorner = torg; + middleAngleCorner = tapex; + largestAngleCorner = tdest; + break; + case 312: // assign necessary information + /// smallest angle corner: apex + /// largest angle corner: org + xShortestEdge = xdo; yShortestEdge = ydo; + + shortestEdgeDist = dodist; + middleEdgeDist = aodist; + longestEdgeDist = dadist; + + smallestAngleCorner = tapex; + middleAngleCorner = tdest; + largestAngleCorner = torg; + break; + case 321: // assign necessary information + default: // TODO: is this safe? + /// smallest angle corner: apex + /// largest angle corner: dest + xShortestEdge = xdo; yShortestEdge = ydo; + + shortestEdgeDist = dodist; + middleEdgeDist = dadist; + longestEdgeDist = aodist; + + smallestAngleCorner = tapex; + middleAngleCorner = torg; + largestAngleCorner = tdest; + break; + }// end of switch + // check for offcenter condition + if (offcenter && (offconstant > 0.0)) + { + // origin has the smallest angle + if (orientation == 213 || orientation == 231) + { + // Find the position of the off-center, as described by Alper Ungor. + dxoff = 0.5 * xShortestEdge - offconstant * yShortestEdge; + dyoff = 0.5 * yShortestEdge + offconstant * xShortestEdge; + // If the off-center is closer to destination than the + // circumcenter, use the off-center instead. + /// doubleLY BAD CASE /// + if (dxoff * dxoff + dyoff * dyoff < + (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo)) + { + dx = xdo + dxoff; + dy = ydo + dyoff; + } + /// ALMOST GOOD CASE /// + else + { + almostGood = 1; + } + // destination has the smallest angle + } + else if (orientation == 123 || orientation == 132) + { + // Find the position of the off-center, as described by Alper Ungor. + dxoff = 0.5 * xShortestEdge + offconstant * yShortestEdge; + dyoff = 0.5 * yShortestEdge - offconstant * xShortestEdge; + // If the off-center is closer to the origin than the + // circumcenter, use the off-center instead. + /// doubleLY BAD CASE /// + if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) + { + dx = dxoff; + dy = dyoff; + } + /// ALMOST GOOD CASE /// + else + { + almostGood = 1; + } + // apex has the smallest angle + } + else + {//orientation == 312 || orientation == 321 + // Find the position of the off-center, as described by Alper Ungor. + dxoff = 0.5 * xShortestEdge - offconstant * yShortestEdge; + dyoff = 0.5 * yShortestEdge + offconstant * xShortestEdge; + // If the off-center is closer to the origin than the + // circumcenter, use the off-center instead. + /// doubleLY BAD CASE /// + if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) + { + dx = dxoff; + dy = dyoff; + } + /// ALMOST GOOD CASE /// + else + { + almostGood = 1; + } + } + } + // if the bad triangle is almost good, apply our approach + if (almostGood == 1) + { + /// calculate cosine of largest angle /// + cosMaxAngle = (middleEdgeDist + shortestEdgeDist - longestEdgeDist) / (2 * Math.Sqrt(middleEdgeDist) * Math.Sqrt(shortestEdgeDist)); + if (cosMaxAngle < 0.0) + { + // obtuse + isObtuse = true; + } + else if (Math.Abs(cosMaxAngle - 0.0) <= EPS) + { + // right triangle (largest angle is 90 degrees) + isObtuse = true; + } + else + { + // nonobtuse + isObtuse = false; + } + /// RELOCATION (LOCAL SMOOTHING) /// + /// check for possible relocation of one of triangle's points /// + relocated = DoSmoothing(delotri, torg, tdest, tapex, ref newloc); + /// if relocation is possible, delete that vertex and insert a vertex at the new location /// + if (relocated > 0) + { + Statistic.RelocationCount++; + + dx = newloc[0] - torg.x; + dy = newloc[1] - torg.y; + origin_x = torg.x; // keep for later use + origin_y = torg.y; + switch (relocated) + { + case 1: + //printf("Relocate: (%f,%f)\n", torg[0],torg[1]); + mesh.DeleteVertex(ref delotri); + break; + case 2: + //printf("Relocate: (%f,%f)\n", tdest[0],tdest[1]); + delotri.Lnext(); + mesh.DeleteVertex(ref delotri); + break; + case 3: + //printf("Relocate: (%f,%f)\n", tapex[0],tapex[1]); + delotri.Lprev(); + mesh.DeleteVertex(ref delotri); + break; + } + } + else + { + // calculate radius of the petal according to angle constraint + // first find the visible region, PETAL + // find the center of the circle and radius + // choose minimum angle as the maximum of quality angle and the minimum angle of the bad triangle + minangle = Math.Acos((middleEdgeDist + longestEdgeDist - shortestEdgeDist) / (2 * Math.Sqrt(middleEdgeDist) * Math.Sqrt(longestEdgeDist))) * 180.0 / Math.PI; + if (behavior.MinAngle > minangle) + { + minangle = behavior.MinAngle; + } + else + { + minangle = minangle + 0.5; + } + petalRadius = Math.Sqrt(shortestEdgeDist) / (2 * Math.Sin(minangle * Math.PI / 180.0)); + /// compute two possible centers of the petal /// + // finding the center + // first find the middle point of smallest edge + xMidOfShortestEdge = (middleAngleCorner.x + largestAngleCorner.x) / 2.0; + yMidOfShortestEdge = (middleAngleCorner.y + largestAngleCorner.y) / 2.0; + // two possible centers + xPetalCtr_1 = xMidOfShortestEdge + Math.Sqrt(petalRadius * petalRadius - (shortestEdgeDist / 4)) * (middleAngleCorner.y - + largestAngleCorner.y) / Math.Sqrt(shortestEdgeDist); + yPetalCtr_1 = yMidOfShortestEdge + Math.Sqrt(petalRadius * petalRadius - (shortestEdgeDist / 4)) * (largestAngleCorner.x - + middleAngleCorner.x) / Math.Sqrt(shortestEdgeDist); + + xPetalCtr_2 = xMidOfShortestEdge - Math.Sqrt(petalRadius * petalRadius - (shortestEdgeDist / 4)) * (middleAngleCorner.y - + largestAngleCorner.y) / Math.Sqrt(shortestEdgeDist); + yPetalCtr_2 = yMidOfShortestEdge - Math.Sqrt(petalRadius * petalRadius - (shortestEdgeDist / 4)) * (largestAngleCorner.x - + middleAngleCorner.x) / Math.Sqrt(shortestEdgeDist); + // find the correct circle since there will be two possible circles + // calculate the distance to smallest angle corner + dxcenter1 = (xPetalCtr_1 - smallestAngleCorner.x) * (xPetalCtr_1 - smallestAngleCorner.x); + dycenter1 = (yPetalCtr_1 - smallestAngleCorner.y) * (yPetalCtr_1 - smallestAngleCorner.y); + dxcenter2 = (xPetalCtr_2 - smallestAngleCorner.x) * (xPetalCtr_2 - smallestAngleCorner.x); + dycenter2 = (yPetalCtr_2 - smallestAngleCorner.y) * (yPetalCtr_2 - smallestAngleCorner.y); + + // whichever is closer to smallest angle corner, it must be the center + if (dxcenter1 + dycenter1 <= dxcenter2 + dycenter2) + { + xPetalCtr = xPetalCtr_1; yPetalCtr = yPetalCtr_1; + } + else + { + xPetalCtr = xPetalCtr_2; yPetalCtr = yPetalCtr_2; + } + /// find the third point of the neighbor triangle /// + neighborNotFound_first = GetNeighborsVertex(badotri, middleAngleCorner.x, middleAngleCorner.y, + smallestAngleCorner.x, smallestAngleCorner.y, ref thirdPoint, ref neighborotri); + /// find the circumcenter of the neighbor triangle /// + dxFirstSuggestion = dx; // if we cannot find any appropriate suggestion, we use circumcenter + dyFirstSuggestion = dy; + /// before checking the neighbor, find the petal and slab intersections /// + // calculate the intersection point of the petal and the slab lines + // first find the vector + // distance between xmid and petal center + dist = Math.Sqrt((xPetalCtr - xMidOfShortestEdge) * (xPetalCtr - xMidOfShortestEdge) + (yPetalCtr - yMidOfShortestEdge) * (yPetalCtr - yMidOfShortestEdge)); + // find the unit vector goes from mid point to petal center + line_vector_x = (xPetalCtr - xMidOfShortestEdge) / dist; + line_vector_y = (yPetalCtr - yMidOfShortestEdge) / dist; + // find the third point other than p and q + petal_bisector_x = xPetalCtr + line_vector_x * petalRadius; + petal_bisector_y = yPetalCtr + line_vector_y * petalRadius; + alpha = (2.0 * behavior.MaxAngle + minangle - 180.0) * Math.PI / 180.0; + // rotate the vector cw around the petal center + x_1 = petal_bisector_x * Math.Cos(alpha) + petal_bisector_y * Math.Sin(alpha) + xPetalCtr - xPetalCtr * Math.Cos(alpha) - yPetalCtr * Math.Sin(alpha); + y_1 = -petal_bisector_x * Math.Sin(alpha) + petal_bisector_y * Math.Cos(alpha) + yPetalCtr + xPetalCtr * Math.Sin(alpha) - yPetalCtr * Math.Cos(alpha); + // rotate the vector ccw around the petal center + x_2 = petal_bisector_x * Math.Cos(alpha) - petal_bisector_y * Math.Sin(alpha) + xPetalCtr - xPetalCtr * Math.Cos(alpha) + yPetalCtr * Math.Sin(alpha); + y_2 = petal_bisector_x * Math.Sin(alpha) + petal_bisector_y * Math.Cos(alpha) + yPetalCtr - xPetalCtr * Math.Sin(alpha) - yPetalCtr * Math.Cos(alpha); + // we need to find correct intersection point, since there are two possibilities + // weather it is obtuse/acute the one closer to the minimum angle corner is the first direction + isCorrect = ChooseCorrectPoint(x_2, y_2, middleAngleCorner.x, middleAngleCorner.y, x_1, y_1, true); + // make sure which point is the correct one to be considered + if (isCorrect) + { + petal_slab_inter_x_first = x_1; + petal_slab_inter_y_first = y_1; + petal_slab_inter_x_second = x_2; + petal_slab_inter_y_second = y_2; + } + else + { + petal_slab_inter_x_first = x_2; + petal_slab_inter_y_first = y_2; + petal_slab_inter_x_second = x_1; + petal_slab_inter_y_second = y_1; + } + /// choose the correct intersection point /// + // calculate middle point of the longest edge(bisector) + xMidOfLongestEdge = (middleAngleCorner.x + smallestAngleCorner.x) / 2.0; + yMidOfLongestEdge = (middleAngleCorner.y + smallestAngleCorner.y) / 2.0; + // if there is a neighbor triangle + if (!neighborNotFound_first) + { + neighborvertex_1 = neighborotri.Org(); + neighborvertex_2 = neighborotri.Dest(); + neighborvertex_3 = neighborotri.Apex(); + // now calculate neighbor's circumcenter which is the voronoi site + neighborCircumcenter = predicates.FindCircumcenter(neighborvertex_1, neighborvertex_2, neighborvertex_3, + ref xi_tmp, ref eta_tmp); + + /// compute petal and Voronoi edge intersection /// + // in order to avoid degenerate cases, we need to do a vector based calculation for line + vector_x = (middleAngleCorner.y - smallestAngleCorner.y);//(-y, x) + vector_y = smallestAngleCorner.x - middleAngleCorner.x; + vector_x = myCircumcenter.x + vector_x; + vector_y = myCircumcenter.y + vector_y; + // by intersecting bisectors you will end up with the one you want to walk on + // then this line and circle should be intersected + CircleLineIntersection(myCircumcenter.x, myCircumcenter.y, vector_x, vector_y, + xPetalCtr, yPetalCtr, petalRadius, ref p); + // we need to find correct intersection point, since line intersects circle twice + isCorrect = ChooseCorrectPoint(xMidOfLongestEdge, yMidOfLongestEdge, p[3], p[4], + myCircumcenter.x, myCircumcenter.y, isObtuse); + // make sure which point is the correct one to be considered + if (isCorrect) + { + inter_x = p[3]; + inter_y = p[4]; + } + else + { + inter_x = p[1]; + inter_y = p[2]; + } + //----------------------hale new first direction: for slab calculation---------------// + // calculate the intersection of angle lines and Voronoi + linepnt1_x = middleAngleCorner.x; + linepnt1_y = middleAngleCorner.y; + // vector from middleAngleCorner to largestAngleCorner + line_vector_x = largestAngleCorner.x - middleAngleCorner.x; + line_vector_y = largestAngleCorner.y - middleAngleCorner.y; + // rotate the vector around middleAngleCorner in cw by maxangle degrees + linepnt2_x = petal_slab_inter_x_first; + linepnt2_y = petal_slab_inter_y_first; + // now calculate the intersection of two lines + LineLineIntersection(myCircumcenter.x, myCircumcenter.y, vector_x, vector_y, linepnt1_x, linepnt1_y, linepnt2_x, linepnt2_y, ref line_p); + // check if there is a suitable intersection + if (line_p[0] > 0.0) + { + line_inter_x = line_p[1]; + line_inter_y = line_p[2]; + } + else + { + // for debugging (to make sure) + //printf("1) No intersection between two lines!!!\n"); + //printf("(%.14f,%.14f) (%.14f,%.14f) (%.14f,%.14f) (%.14f,%.14f)\n",myCircumcenter.x,myCircumcenter.y,vector_x,vector_y,linepnt1_x,linepnt1_y,linepnt2_x,linepnt2_y); + } + + //---------------------------------------------------------------------// + /// check if there is a Voronoi vertex between before intersection /// + // check if the voronoi vertex is between the intersection and circumcenter + PointBetweenPoints(inter_x, inter_y, myCircumcenter.x, myCircumcenter.y, + neighborCircumcenter.x, neighborCircumcenter.y, ref voronoiOrInter); + + /// determine the point to be suggested /// + if (p[0] > 0.0) + { // there is at least one intersection point + // if it is between circumcenter and intersection + // if it returns 1.0 this means we have a voronoi vertex within feasible region + if (Math.Abs(voronoiOrInter[0] - 1.0) <= EPS) + { + //-----------------hale new continues 1------------------// + // now check if the line intersection is between cc and voronoi + PointBetweenPoints(voronoiOrInter[2], voronoiOrInter[3], myCircumcenter.x, myCircumcenter.y, line_inter_x, line_inter_y, ref line_result); + if (Math.Abs(line_result[0] - 1.0) <= EPS && line_p[0] > 0.0) + { + // check if we can go further by picking the slab line and petal intersection + // calculate the distance to the smallest angle corner + // check if we create a bad triangle or not + if (((smallestAngleCorner.x - petal_slab_inter_x_first) * (smallestAngleCorner.x - petal_slab_inter_x_first) + + (smallestAngleCorner.y - petal_slab_inter_y_first) * (smallestAngleCorner.y - petal_slab_inter_y_first) > + lengthConst * ((smallestAngleCorner.x - line_inter_x) * + (smallestAngleCorner.x - line_inter_x) + + (smallestAngleCorner.y - line_inter_y) * + (smallestAngleCorner.y - line_inter_y))) + && (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, petal_slab_inter_x_first, petal_slab_inter_y_first)) + && MinDistanceToNeighbor(petal_slab_inter_x_first, petal_slab_inter_y_first, ref neighborotri) > MinDistanceToNeighbor(line_inter_x, line_inter_y, ref neighborotri)) + { + // check the neighbor's vertices also, which one if better + //slab and petal intersection is advised + dxFirstSuggestion = petal_slab_inter_x_first - torg.x; + dyFirstSuggestion = petal_slab_inter_y_first - torg.y; + } + else + { // slab intersection point is further away + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, line_inter_x, line_inter_y)) + { + // apply perturbation + // find the distance between circumcenter and intersection point + d = Math.Sqrt((line_inter_x - myCircumcenter.x) * (line_inter_x - myCircumcenter.x) + + (line_inter_y - myCircumcenter.y) * (line_inter_y - myCircumcenter.y)); + // then find the vector going from intersection point to circumcenter + ax = myCircumcenter.x - line_inter_x; + ay = myCircumcenter.y - line_inter_y; + + ax = ax / d; + ay = ay / d; + // now calculate the new intersection point which is perturbated towards the circumcenter + line_inter_x = line_inter_x + ax * pertConst * Math.Sqrt(shortestEdgeDist); + line_inter_y = line_inter_y + ay * pertConst * Math.Sqrt(shortestEdgeDist); + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, line_inter_x, line_inter_y)) + { + // go back to circumcenter + dxFirstSuggestion = dx; + dyFirstSuggestion = dy; + } + else + { + // intersection point is suggested + dxFirstSuggestion = line_inter_x - torg.x; + dyFirstSuggestion = line_inter_y - torg.y; + } + } + else + {// we are not creating a bad triangle + // slab intersection is advised + dxFirstSuggestion = line_result[2] - torg.x; + dyFirstSuggestion = line_result[3] - torg.y; + } + } + //------------------------------------------------------// + } + else + { + /// NOW APPLY A BREADTH-FIRST SEARCH ON THE VORONOI + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, neighborCircumcenter.x, neighborCircumcenter.y)) + { + // go back to circumcenter + dxFirstSuggestion = dx; + dyFirstSuggestion = dy; + } + else + { + // we are not creating a bad triangle + // neighbor's circumcenter is suggested + dxFirstSuggestion = voronoiOrInter[2] - torg.x; + dyFirstSuggestion = voronoiOrInter[3] - torg.y; + } + } + } + else + { // there is no voronoi vertex between intersection point and circumcenter + //-----------------hale new continues 2-----------------// + // now check if the line intersection is between cc and intersection point + PointBetweenPoints(inter_x, inter_y, myCircumcenter.x, myCircumcenter.y, line_inter_x, line_inter_y, ref line_result); + if (Math.Abs(line_result[0] - 1.0) <= EPS && line_p[0] > 0.0) + { + // check if we can go further by picking the slab line and petal intersection + // calculate the distance to the smallest angle corner + if (((smallestAngleCorner.x - petal_slab_inter_x_first) * (smallestAngleCorner.x - petal_slab_inter_x_first) + + (smallestAngleCorner.y - petal_slab_inter_y_first) * (smallestAngleCorner.y - petal_slab_inter_y_first) > + lengthConst * ((smallestAngleCorner.x - line_inter_x) * + (smallestAngleCorner.x - line_inter_x) + + (smallestAngleCorner.y - line_inter_y) * + (smallestAngleCorner.y - line_inter_y))) + && (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, petal_slab_inter_x_first, petal_slab_inter_y_first)) + && MinDistanceToNeighbor(petal_slab_inter_x_first, petal_slab_inter_y_first, ref neighborotri) > MinDistanceToNeighbor(line_inter_x, line_inter_y, ref neighborotri)) + { + //slab and petal intersection is advised + dxFirstSuggestion = petal_slab_inter_x_first - torg.x; + dyFirstSuggestion = petal_slab_inter_y_first - torg.y; + } + else + { // slab intersection point is further away + if (IsBadTriangleAngle(largestAngleCorner.x, largestAngleCorner.y, middleAngleCorner.x, middleAngleCorner.y, line_inter_x, line_inter_y)) + { + // apply perturbation + // find the distance between circumcenter and intersection point + d = Math.Sqrt((line_inter_x - myCircumcenter.x) * (line_inter_x - myCircumcenter.x) + + (line_inter_y - myCircumcenter.y) * (line_inter_y - myCircumcenter.y)); + // then find the vector going from intersection point to circumcenter + ax = myCircumcenter.x - line_inter_x; + ay = myCircumcenter.y - line_inter_y; + + ax = ax / d; + ay = ay / d; + // now calculate the new intersection point which is perturbated towards the circumcenter + line_inter_x = line_inter_x + ax * pertConst * Math.Sqrt(shortestEdgeDist); + line_inter_y = line_inter_y + ay * pertConst * Math.Sqrt(shortestEdgeDist); + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, line_inter_x, line_inter_y)) + { + // go back to circumcenter + dxFirstSuggestion = dx; + dyFirstSuggestion = dy; + } + else + { + // intersection point is suggested + dxFirstSuggestion = line_inter_x - torg.x; + dyFirstSuggestion = line_inter_y - torg.y; + } + } + else + {// we are not creating a bad triangle + // slab intersection is advised + dxFirstSuggestion = line_result[2] - torg.x; + dyFirstSuggestion = line_result[3] - torg.y; + } + } + //------------------------------------------------------// + } + else + { + if (IsBadTriangleAngle(largestAngleCorner.x, largestAngleCorner.y, middleAngleCorner.x, middleAngleCorner.y, inter_x, inter_y)) + { + //printf("testtriangle returned false! bad triangle\n"); + // if it is inside feasible region, then insert v2 + // apply perturbation + // find the distance between circumcenter and intersection point + d = Math.Sqrt((inter_x - myCircumcenter.x) * (inter_x - myCircumcenter.x) + + (inter_y - myCircumcenter.y) * (inter_y - myCircumcenter.y)); + // then find the vector going from intersection point to circumcenter + ax = myCircumcenter.x - inter_x; + ay = myCircumcenter.y - inter_y; + + ax = ax / d; + ay = ay / d; + // now calculate the new intersection point which is perturbated towards the circumcenter + inter_x = inter_x + ax * pertConst * Math.Sqrt(shortestEdgeDist); + inter_y = inter_y + ay * pertConst * Math.Sqrt(shortestEdgeDist); + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, inter_x, inter_y)) + { + // go back to circumcenter + dxFirstSuggestion = dx; + dyFirstSuggestion = dy; + } + else + { + // intersection point is suggested + dxFirstSuggestion = inter_x - torg.x; + dyFirstSuggestion = inter_y - torg.y; + } + } + else + { + // intersection point is suggested + dxFirstSuggestion = inter_x - torg.x; + dyFirstSuggestion = inter_y - torg.y; + } + } + } + /// if it is an acute triangle, check if it is a good enough location /// + // for acute triangle case, we need to check if it is ok to use either of them + if ((smallestAngleCorner.x - myCircumcenter.x) * (smallestAngleCorner.x - myCircumcenter.x) + + (smallestAngleCorner.y - myCircumcenter.y) * (smallestAngleCorner.y - myCircumcenter.y) > + lengthConst * ((smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) + + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y)) * + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y)))) + { + // use circumcenter + dxFirstSuggestion = dx; + dyFirstSuggestion = dy; + }// else we stick to what we have found + }// intersection point + }// if it is on the boundary, meaning no neighbor triangle in this direction, try other direction + + /// DO THE SAME THING FOR THE OTHER DIRECTION /// + /// find the third point of the neighbor triangle /// + neighborNotFound_second = GetNeighborsVertex(badotri, largestAngleCorner.x, largestAngleCorner.y, + smallestAngleCorner.x, smallestAngleCorner.y, ref thirdPoint, ref neighborotri); + /// find the circumcenter of the neighbor triangle /// + dxSecondSuggestion = dx; // if we cannot find any appropriate suggestion, we use circumcenter + dySecondSuggestion = dy; + + /// choose the correct intersection point /// + // calculate middle point of the longest edge(bisector) + xMidOfMiddleEdge = (largestAngleCorner.x + smallestAngleCorner.x) / 2.0; + yMidOfMiddleEdge = (largestAngleCorner.y + smallestAngleCorner.y) / 2.0; + // if there is a neighbor triangle + if (!neighborNotFound_second) + { + neighborvertex_1 = neighborotri.Org(); + neighborvertex_2 = neighborotri.Dest(); + neighborvertex_3 = neighborotri.Apex(); + // now calculate neighbor's circumcenter which is the voronoi site + neighborCircumcenter = predicates.FindCircumcenter(neighborvertex_1, neighborvertex_2, neighborvertex_3, + ref xi_tmp, ref eta_tmp); + + /// compute petal and Voronoi edge intersection /// + // in order to avoid degenerate cases, we need to do a vector based calculation for line + vector_x = (largestAngleCorner.y - smallestAngleCorner.y);//(-y, x) + vector_y = smallestAngleCorner.x - largestAngleCorner.x; + vector_x = myCircumcenter.x + vector_x; + vector_y = myCircumcenter.y + vector_y; + + + // by intersecting bisectors you will end up with the one you want to walk on + // then this line and circle should be intersected + CircleLineIntersection(myCircumcenter.x, myCircumcenter.y, vector_x, vector_y, + xPetalCtr, yPetalCtr, petalRadius, ref p); + + // we need to find correct intersection point, since line intersects circle twice + // this direction is always ACUTE + isCorrect = ChooseCorrectPoint(xMidOfMiddleEdge, yMidOfMiddleEdge, p[3], p[4], + myCircumcenter.x, myCircumcenter.y, false /*(isObtuse+1)%2*/); + // make sure which point is the correct one to be considered + if (isCorrect) + { + inter_x = p[3]; + inter_y = p[4]; + } + else + { + inter_x = p[1]; + inter_y = p[2]; + } + //----------------------hale new second direction:for slab calculation---------------// + // calculate the intersection of angle lines and Voronoi + linepnt1_x = largestAngleCorner.x; + linepnt1_y = largestAngleCorner.y; + // vector from largestAngleCorner to middleAngleCorner + line_vector_x = middleAngleCorner.x - largestAngleCorner.x; + line_vector_y = middleAngleCorner.y - largestAngleCorner.y; + // rotate the vector around largestAngleCorner in ccw by maxangle degrees + linepnt2_x = petal_slab_inter_x_second; + linepnt2_y = petal_slab_inter_y_second; + // now calculate the intersection of two lines + LineLineIntersection(myCircumcenter.x, myCircumcenter.y, vector_x, vector_y, linepnt1_x, linepnt1_y, linepnt2_x, linepnt2_y, ref line_p); + // check if there is a suitable intersection + if (line_p[0] > 0.0) + { + line_inter_x = line_p[1]; + line_inter_y = line_p[2]; + } + else + { + // for debugging (to make sure) + //printf("1) No intersection between two lines!!!\n"); + //printf("(%.14f,%.14f) (%.14f,%.14f) (%.14f,%.14f) (%.14f,%.14f)\n",myCircumcenter.x,myCircumcenter.y,vector_x,vector_y,linepnt1_x,linepnt1_y,linepnt2_x,linepnt2_y); + } + //---------------------------------------------------------------------// + /// check if there is a Voronoi vertex between before intersection /// + // check if the voronoi vertex is between the intersection and circumcenter + PointBetweenPoints(inter_x, inter_y, myCircumcenter.x, myCircumcenter.y, + neighborCircumcenter.x, neighborCircumcenter.y, ref voronoiOrInter); + /// determine the point to be suggested /// + if (p[0] > 0.0) + { // there is at least one intersection point + // if it is between circumcenter and intersection + // if it returns 1.0 this means we have a voronoi vertex within feasible region + if (Math.Abs(voronoiOrInter[0] - 1.0) <= EPS) + { + //-----------------hale new continues 1------------------// + // now check if the line intersection is between cc and voronoi + PointBetweenPoints(voronoiOrInter[2], voronoiOrInter[3], myCircumcenter.x, myCircumcenter.y, line_inter_x, line_inter_y, ref line_result); + if (Math.Abs(line_result[0] - 1.0) <= EPS && line_p[0] > 0.0) + { + // check if we can go further by picking the slab line and petal intersection + // calculate the distance to the smallest angle corner + // + if (((smallestAngleCorner.x - petal_slab_inter_x_second) * (smallestAngleCorner.x - petal_slab_inter_x_second) + + (smallestAngleCorner.y - petal_slab_inter_y_second) * (smallestAngleCorner.y - petal_slab_inter_y_second) > + lengthConst * ((smallestAngleCorner.x - line_inter_x) * + (smallestAngleCorner.x - line_inter_x) + + (smallestAngleCorner.y - line_inter_y) * + (smallestAngleCorner.y - line_inter_y))) + && (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, petal_slab_inter_x_second, petal_slab_inter_y_second)) + && MinDistanceToNeighbor(petal_slab_inter_x_second, petal_slab_inter_y_second, ref neighborotri) > MinDistanceToNeighbor(line_inter_x, line_inter_y, ref neighborotri)) + { + // slab and petal intersection is advised + dxSecondSuggestion = petal_slab_inter_x_second - torg.x; + dySecondSuggestion = petal_slab_inter_y_second - torg.y; + } + else + { // slab intersection point is further away + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, line_inter_x, line_inter_y)) + { + // apply perturbation + // find the distance between circumcenter and intersection point + d = Math.Sqrt((line_inter_x - myCircumcenter.x) * (line_inter_x - myCircumcenter.x) + + (line_inter_y - myCircumcenter.y) * (line_inter_y - myCircumcenter.y)); + // then find the vector going from intersection point to circumcenter + ax = myCircumcenter.x - line_inter_x; + ay = myCircumcenter.y - line_inter_y; + + ax = ax / d; + ay = ay / d; + // now calculate the new intersection point which is perturbated towards the circumcenter + line_inter_x = line_inter_x + ax * pertConst * Math.Sqrt(shortestEdgeDist); + line_inter_y = line_inter_y + ay * pertConst * Math.Sqrt(shortestEdgeDist); + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, line_inter_x, line_inter_y)) + { + // go back to circumcenter + dxSecondSuggestion = dx; + dySecondSuggestion = dy; + } + else + { + // intersection point is suggested + dxSecondSuggestion = line_inter_x - torg.x; + dySecondSuggestion = line_inter_y - torg.y; + } + } + else + {// we are not creating a bad triangle + // slab intersection is advised + dxSecondSuggestion = line_result[2] - torg.x; + dySecondSuggestion = line_result[3] - torg.y; + } + } + //------------------------------------------------------// + } + else + { + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, neighborCircumcenter.x, neighborCircumcenter.y)) + { + // go back to circumcenter + dxSecondSuggestion = dx; + dySecondSuggestion = dy; + } + else + { // we are not creating a bad triangle + // neighbor's circumcenter is suggested + dxSecondSuggestion = voronoiOrInter[2] - torg.x; + dySecondSuggestion = voronoiOrInter[3] - torg.y; + } + } + } + else + { // there is no voronoi vertex between intersection point and circumcenter + //-----------------hale new continues 2-----------------// + // now check if the line intersection is between cc and intersection point + PointBetweenPoints(inter_x, inter_y, myCircumcenter.x, myCircumcenter.y, line_inter_x, line_inter_y, ref line_result); + if (Math.Abs(line_result[0] - 1.0) <= EPS && line_p[0] > 0.0) + { + // check if we can go further by picking the slab line and petal intersection + // calculate the distance to the smallest angle corner + if (((smallestAngleCorner.x - petal_slab_inter_x_second) * (smallestAngleCorner.x - petal_slab_inter_x_second) + + (smallestAngleCorner.y - petal_slab_inter_y_second) * (smallestAngleCorner.y - petal_slab_inter_y_second) > + lengthConst * ((smallestAngleCorner.x - line_inter_x) * + (smallestAngleCorner.x - line_inter_x) + + (smallestAngleCorner.y - line_inter_y) * + (smallestAngleCorner.y - line_inter_y))) + && (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, petal_slab_inter_x_second, petal_slab_inter_y_second)) + && MinDistanceToNeighbor(petal_slab_inter_x_second, petal_slab_inter_y_second, ref neighborotri) > MinDistanceToNeighbor(line_inter_x, line_inter_y, ref neighborotri)) + { + // slab and petal intersection is advised + dxSecondSuggestion = petal_slab_inter_x_second - torg.x; + dySecondSuggestion = petal_slab_inter_y_second - torg.y; + } + else + { // slab intersection point is further away ; + if (IsBadTriangleAngle(largestAngleCorner.x, largestAngleCorner.y, middleAngleCorner.x, middleAngleCorner.y, line_inter_x, line_inter_y)) + { + // apply perturbation + // find the distance between circumcenter and intersection point + d = Math.Sqrt((line_inter_x - myCircumcenter.x) * (line_inter_x - myCircumcenter.x) + + (line_inter_y - myCircumcenter.y) * (line_inter_y - myCircumcenter.y)); + // then find the vector going from intersection point to circumcenter + ax = myCircumcenter.x - line_inter_x; + ay = myCircumcenter.y - line_inter_y; + + ax = ax / d; + ay = ay / d; + // now calculate the new intersection point which is perturbated towards the circumcenter + line_inter_x = line_inter_x + ax * pertConst * Math.Sqrt(shortestEdgeDist); + line_inter_y = line_inter_y + ay * pertConst * Math.Sqrt(shortestEdgeDist); + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, line_inter_x, line_inter_y)) + { + // go back to circumcenter + dxSecondSuggestion = dx; + dySecondSuggestion = dy; + } + else + { + // intersection point is suggested + dxSecondSuggestion = line_inter_x - torg.x; + dySecondSuggestion = line_inter_y - torg.y; + } + } + else + { + // we are not creating a bad triangle + // slab intersection is advised + dxSecondSuggestion = line_result[2] - torg.x; + dySecondSuggestion = line_result[3] - torg.y; + } + } + //------------------------------------------------------// + } + else + { + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, inter_x, inter_y)) + { + // if it is inside feasible region, then insert v2 + // apply perturbation + // find the distance between circumcenter and intersection point + d = Math.Sqrt((inter_x - myCircumcenter.x) * (inter_x - myCircumcenter.x) + + (inter_y - myCircumcenter.y) * (inter_y - myCircumcenter.y)); + // then find the vector going from intersection point to circumcenter + ax = myCircumcenter.x - inter_x; + ay = myCircumcenter.y - inter_y; + + ax = ax / d; + ay = ay / d; + // now calculate the new intersection point which is perturbated towards the circumcenter + inter_x = inter_x + ax * pertConst * Math.Sqrt(shortestEdgeDist); + inter_y = inter_y + ay * pertConst * Math.Sqrt(shortestEdgeDist); + if (IsBadTriangleAngle(middleAngleCorner.x, middleAngleCorner.y, largestAngleCorner.x, largestAngleCorner.y, inter_x, inter_y)) + { + // go back to circumcenter + dxSecondSuggestion = dx; + dySecondSuggestion = dy; + } + else + { + // intersection point is suggested + dxSecondSuggestion = inter_x - torg.x; + dySecondSuggestion = inter_y - torg.y; + } + } + else + { + // intersection point is suggested + dxSecondSuggestion = inter_x - torg.x; + dySecondSuggestion = inter_y - torg.y; + } + } + } + + /// if it is an acute triangle, check if it is a good enough location /// + // for acute triangle case, we need to check if it is ok to use either of them + if ((smallestAngleCorner.x - myCircumcenter.x) * (smallestAngleCorner.x - myCircumcenter.x) + + (smallestAngleCorner.y - myCircumcenter.y) * (smallestAngleCorner.y - myCircumcenter.y) > + lengthConst * ((smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) + + (smallestAngleCorner.y - (dySecondSuggestion + torg.y)) * + (smallestAngleCorner.y - (dySecondSuggestion + torg.y)))) + { + // use circumcenter + dxSecondSuggestion = dx; + dySecondSuggestion = dy; + }// else we stick on what we have found + } + }// if it is on the boundary, meaning no neighbor triangle in this direction, the other direction might be ok + if (isObtuse) + { + if (neighborNotFound_first && neighborNotFound_second) + { + //obtuse: check if the other direction works + if (justAcute * ((smallestAngleCorner.x - (xMidOfMiddleEdge)) * + (smallestAngleCorner.x - (xMidOfMiddleEdge)) + + (smallestAngleCorner.y - (yMidOfMiddleEdge)) * + (smallestAngleCorner.y - (yMidOfMiddleEdge))) > + (smallestAngleCorner.x - (xMidOfLongestEdge)) * + (smallestAngleCorner.x - (xMidOfLongestEdge)) + + (smallestAngleCorner.y - (yMidOfLongestEdge)) * + (smallestAngleCorner.y - (yMidOfLongestEdge))) + { + dx = dxSecondSuggestion; + dy = dySecondSuggestion; + } + else + { + dx = dxFirstSuggestion; + dy = dyFirstSuggestion; + } + } + else if (neighborNotFound_first) + { + //obtuse: check if the other direction works + if (justAcute * ((smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) + + (smallestAngleCorner.y - (dySecondSuggestion + torg.y)) * + (smallestAngleCorner.y - (dySecondSuggestion + torg.y))) > + (smallestAngleCorner.x - (xMidOfLongestEdge)) * + (smallestAngleCorner.x - (xMidOfLongestEdge)) + + (smallestAngleCorner.y - (yMidOfLongestEdge)) * + (smallestAngleCorner.y - (yMidOfLongestEdge))) + { + dx = dxSecondSuggestion; + dy = dySecondSuggestion; + } + else + { + dx = dxFirstSuggestion; + dy = dyFirstSuggestion; + } + } + else if (neighborNotFound_second) + { + //obtuse: check if the other direction works + if (justAcute * ((smallestAngleCorner.x - (xMidOfMiddleEdge)) * + (smallestAngleCorner.x - (xMidOfMiddleEdge)) + + (smallestAngleCorner.y - (yMidOfMiddleEdge)) * + (smallestAngleCorner.y - (yMidOfMiddleEdge))) > + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) + + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y)) * + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y))) + { + dx = dxSecondSuggestion; + dy = dySecondSuggestion; + } + else + { + dx = dxFirstSuggestion; + dy = dyFirstSuggestion; + } + } + else + { + //obtuse: check if the other direction works + if (justAcute * ((smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) + + (smallestAngleCorner.y - (dySecondSuggestion + torg.y)) * + (smallestAngleCorner.y - (dySecondSuggestion + torg.y))) > + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) + + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y)) * + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y))) + { + dx = dxSecondSuggestion; + dy = dySecondSuggestion; + } + else + { + dx = dxFirstSuggestion; + dy = dyFirstSuggestion; + } + } + } + else + { // acute : consider other direction + if (neighborNotFound_first && neighborNotFound_second) + { + //obtuse: check if the other direction works + if (justAcute * ((smallestAngleCorner.x - (xMidOfMiddleEdge)) * + (smallestAngleCorner.x - (xMidOfMiddleEdge)) + + (smallestAngleCorner.y - (yMidOfMiddleEdge)) * + (smallestAngleCorner.y - (yMidOfMiddleEdge))) > + (smallestAngleCorner.x - (xMidOfLongestEdge)) * + (smallestAngleCorner.x - (xMidOfLongestEdge)) + + (smallestAngleCorner.y - (yMidOfLongestEdge)) * + (smallestAngleCorner.y - (yMidOfLongestEdge))) + { + dx = dxSecondSuggestion; + dy = dySecondSuggestion; + } + else + { + dx = dxFirstSuggestion; + dy = dyFirstSuggestion; + } + } + else if (neighborNotFound_first) + { + //obtuse: check if the other direction works + if (justAcute * ((smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) + + (smallestAngleCorner.y - (dySecondSuggestion + torg.y)) * + (smallestAngleCorner.y - (dySecondSuggestion + torg.y))) > + (smallestAngleCorner.x - (xMidOfLongestEdge)) * + (smallestAngleCorner.x - (xMidOfLongestEdge)) + + (smallestAngleCorner.y - (yMidOfLongestEdge)) * + (smallestAngleCorner.y - (yMidOfLongestEdge))) + { + dx = dxSecondSuggestion; + dy = dySecondSuggestion; + } + else + { + dx = dxFirstSuggestion; + dy = dyFirstSuggestion; + } + } + else if (neighborNotFound_second) + { + //obtuse: check if the other direction works + if (justAcute * ((smallestAngleCorner.x - (xMidOfMiddleEdge)) * + (smallestAngleCorner.x - (xMidOfMiddleEdge)) + + (smallestAngleCorner.y - (yMidOfMiddleEdge)) * + (smallestAngleCorner.y - (yMidOfMiddleEdge))) > + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) + + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y)) * + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y))) + { + dx = dxSecondSuggestion; + dy = dySecondSuggestion; + } + else + { + dx = dxFirstSuggestion; + dy = dyFirstSuggestion; + } + } + else + { + //obtuse: check if the other direction works + if (justAcute * ((smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxSecondSuggestion + torg.x)) + + (smallestAngleCorner.y - (dySecondSuggestion + torg.y)) * + (smallestAngleCorner.y - (dySecondSuggestion + torg.y))) > + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) * + (smallestAngleCorner.x - (dxFirstSuggestion + torg.x)) + + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y)) * + (smallestAngleCorner.y - (dyFirstSuggestion + torg.y))) + { + dx = dxSecondSuggestion; + dy = dySecondSuggestion; + } + else + { + dx = dxFirstSuggestion; + dy = dyFirstSuggestion; + } + } + }// end if obtuse + }// end of relocation + }// end of almostGood + + Point circumcenter = new Point(); + + if (relocated <= 0) + { + circumcenter.x = torg.x + dx; + circumcenter.y = torg.y + dy; + } + else + { + circumcenter.x = origin_x + dx; + circumcenter.y = origin_y + dy; + } + xi = (yao * dx - xao * dy) * (2.0 * denominator); + eta = (xdo * dy - ydo * dx) * (2.0 * denominator); + + return circumcenter; + } + + /// + /// Given square of edge lengths of a triangle, + // determine its orientation + /// + /// + /// + /// + /// Returns a number indicating an orientation. + private int LongestShortestEdge(double aodist, double dadist, double dodist) + { + // 123: shortest: aodist // 213: shortest: dadist // 312: shortest: dodist + // middle: dadist // middle: aodist // middle: aodist + // longest: dodist // longest: dodist // longest: dadist + // 132: shortest: aodist // 231: shortest: dadist // 321: shortest: dodist + // middle: dodist // middle: dodist // middle: dadist + // longest: dadist // longest: aodist // longest: aodist + + int max = 0, min = 0, mid = 0, minMidMax; + if (dodist < aodist && dodist < dadist) + { + min = 3; // apex is the smallest angle, dodist is the longest edge + if (aodist < dadist) + { + max = 2; // dadist is the longest edge + mid = 1; // aodist is the middle longest edge + } + else + { + max = 1; // aodist is the longest edge + mid = 2; // dadist is the middle longest edge + } + } + else if (aodist < dadist) + { + min = 1; // dest is the smallest angle, aodist is the biggest edge + if (dodist < dadist) + { + max = 2; // dadist is the longest edge + mid = 3; // dodist is the middle longest edge + } + else + { + max = 3; // dodist is the longest edge + mid = 2; // dadist is the middle longest edge + } + } + else + { + min = 2; // origin is the smallest angle, dadist is the biggest edge + if (aodist < dodist) + { + max = 3; // dodist is the longest edge + mid = 1; // aodist is the middle longest edge + } + else + { + max = 1; // aodist is the longest edge + mid = 3; // dodist is the middle longest edge + } + } + minMidMax = min * 100 + mid * 10 + max; + // HANDLE ISOSCELES TRIANGLE CASE + return minMidMax; + } + + /// + /// Checks if smothing is possible for a given bad triangle. + /// + /// + /// + /// + /// + /// The new location for the point, if somothing is possible. + /// Returns 1, 2 or 3 if smoothing will work, 0 otherwise. + private int DoSmoothing(Otri badotri, Vertex torg, Vertex tdest, Vertex tapex, + ref double[] newloc) + { + int numpoints_p = 0;// keeps the number of points in a star of point p, q, r + int numpoints_q = 0; + int numpoints_r = 0; + //int i; + double[] possibilities = new double[6];//there can be more than one possibilities + int num_pos = 0; // number of possibilities + int flag1 = 0, flag2 = 0, flag3 = 0; + bool newLocFound = false; + + //vertex v1, v2, v3; // for ccw test + //double p1[2], p2[2], p3[2]; + //double temp[2]; + + //********************* TRY TO RELOCATE POINT "p" *************** + + // get the surrounding points of p, so this gives us the triangles + numpoints_p = GetStarPoints(badotri, torg, tdest, tapex, 1, ref points_p); + // check if the points in counterclockwise order + // p1[0] = points_p[0]; p1[1] = points_p[1]; + // p2[0] = points_p[2]; p2[1] = points_p[3]; + // p3[0] = points_p[4]; p3[1] = points_p[5]; + // v1 = (vertex)p1; v2 = (vertex)p2; v3 = (vertex)p3; + // if(counterclockwise(m,b,v1,v2,v3) < 0){ + // // reverse the order to ccw + // for(i = 0; i < numpoints_p/2; i++){ + // temp[0] = points_p[2*i]; + // temp[1] = points_p[2*i+1]; + // points_p[2*i] = points_p[2*(numpoints_p-1)-2*i]; + // points_p[2*i+1] = points_p[2*(numpoints_p-1)+1-2*i]; + // points_p[2*(numpoints_p-1)-2*i] = temp[0]; + // points_p[2*(numpoints_p-1)+1-2*i] = temp[1]; + // } + // } + // m.counterclockcount--; + // INTERSECTION OF PETALS + // first check whether the star angles are appropriate for relocation + if (torg.type == VertexType.FreeVertex && numpoints_p != 0 && ValidPolygonAngles(numpoints_p, points_p)) + { + //newLocFound = getPetalIntersection(m, b, numpoints_p, points_p, newloc); + //newLocFound = getPetalIntersectionBruteForce(m, b,numpoints_p, points_p, newloc,torg[0],torg[1]); + if (behavior.MaxAngle == 0.0) + { + newLocFound = GetWedgeIntersectionWithoutMaxAngle(numpoints_p, points_p, ref newloc); + } + else + { + newLocFound = GetWedgeIntersection(numpoints_p, points_p, ref newloc); + } + //printf("call petal intersection for p\n"); + // make sure the relocated point is a free vertex + if (newLocFound) + { + possibilities[0] = newloc[0];// something found + possibilities[1] = newloc[1]; + num_pos++;// increase the number of possibilities + flag1 = 1; + } + } + + //********************* TRY TO RELOCATE POINT "q" *************** + + // get the surrounding points of q, so this gives us the triangles + numpoints_q = GetStarPoints(badotri, torg, tdest, tapex, 2, ref points_q); + // // check if the points in counterclockwise order + // v1[0] = points_q[0]; v1[1] = points_q[1]; + // v2[0] = points_q[2]; v2[1] = points_q[3]; + // v3[0] = points_q[4]; v3[1] = points_q[5]; + // if(counterclockwise(m,b,v1,v2,v3) < 0){ + // // reverse the order to ccw + // for(i = 0; i < numpoints_q/2; i++){ + // temp[0] = points_q[2*i]; + // temp[1] = points_q[2*i+1]; + // points_q[2*i] = points_q[2*(numpoints_q-1)-2*i]; + // points_q[2*i+1] = points_q[2*(numpoints_q-1)+1-2*i]; + // points_q[2*(numpoints_q-1)-2*i] = temp[0]; + // points_q[2*(numpoints_q-1)+1-2*i] = temp[1]; + // } + // } + // m.counterclockcount--; + // INTERSECTION OF PETALS + // first check whether the star angles are appropriate for relocation + if (tdest.type == VertexType.FreeVertex && numpoints_q != 0 && ValidPolygonAngles(numpoints_q, points_q)) + { + //newLocFound = getPetalIntersection(m, b,numpoints_q, points_q, newloc); + //newLocFound = getPetalIntersectionBruteForce(m, b,numpoints_q, points_q, newloc,tapex[0],tapex[1]); + if (behavior.MaxAngle == 0.0) + { + newLocFound = GetWedgeIntersectionWithoutMaxAngle(numpoints_q, points_q, ref newloc); + } + else + { + newLocFound = GetWedgeIntersection(numpoints_q, points_q, ref newloc); + } + //printf("call petal intersection for q\n"); + + // make sure the relocated point is a free vertex + if (newLocFound) + { + possibilities[2] = newloc[0];// something found + possibilities[3] = newloc[1]; + num_pos++;// increase the number of possibilities + flag2 = 2; + } + } + + + //********************* TRY TO RELOCATE POINT "q" *************** + // get the surrounding points of r, so this gives us the triangles + numpoints_r = GetStarPoints(badotri, torg, tdest, tapex, 3, ref points_r); + // check if the points in counterclockwise order + // v1[0] = points_r[0]; v1[1] = points_r[1]; + // v2[0] = points_r[2]; v2[1] = points_r[3]; + // v3[0] = points_r[4]; v3[1] = points_r[5]; + // if(counterclockwise(m,b,v1,v2,v3) < 0){ + // // reverse the order to ccw + // for(i = 0; i < numpoints_r/2; i++){ + // temp[0] = points_r[2*i]; + // temp[1] = points_r[2*i+1]; + // points_r[2*i] = points_r[2*(numpoints_r-1)-2*i]; + // points_r[2*i+1] = points_r[2*(numpoints_r-1)+1-2*i]; + // points_r[2*(numpoints_r-1)-2*i] = temp[0]; + // points_r[2*(numpoints_r-1)+1-2*i] = temp[1]; + // } + // } + // m.counterclockcount--; + // INTERSECTION OF PETALS + // first check whether the star angles are appropriate for relocation + if (tapex.type == VertexType.FreeVertex && numpoints_r != 0 && ValidPolygonAngles(numpoints_r, points_r)) + { + //newLocFound = getPetalIntersection(m, b,numpoints_r, points_r, newloc); + //newLocFound = getPetalIntersectionBruteForce(m, b,numpoints_r, points_r, newloc,tdest[0],tdest[1]); + if (behavior.MaxAngle == 0.0) + { + newLocFound = GetWedgeIntersectionWithoutMaxAngle(numpoints_r, points_r, ref newloc); + } + else + { + newLocFound = GetWedgeIntersection(numpoints_r, points_r, ref newloc); + } + + //printf("call petal intersection for r\n"); + + + // make sure the relocated point is a free vertex + if (newLocFound) + { + possibilities[4] = newloc[0];// something found + possibilities[5] = newloc[1]; + num_pos++;// increase the number of possibilities + flag3 = 3; + } + } + //printf("numpossibilities %d\n",num_pos); + //////////// AFTER FINISH CHECKING EVERY POSSIBILITY, CHOOSE ANY OF THE AVAILABLE ONE ////////////////////// + if (num_pos > 0) + { + if (flag1 > 0) + { // suggest to relocate origin + newloc[0] = possibilities[0]; + newloc[1] = possibilities[1]; + return flag1; + } + else + { + if (flag2 > 0) + { // suggest to relocate apex + newloc[0] = possibilities[2]; + newloc[1] = possibilities[3]; + return flag2; + } + else + {// suggest to relocate destination + if (flag3 > 0) + { + newloc[0] = possibilities[4]; + newloc[1] = possibilities[5]; + return flag3; + } + } + } + } + + return 0;// could not find any good relocation + } + + /// + /// Finds the star of a given point. + /// + /// + /// + /// + /// + /// + /// List of points on the star of the given point. + /// Number of points on the star of the given point. + private int GetStarPoints(Otri badotri, Vertex p, Vertex q, Vertex r, + int whichPoint, ref double[] points) + { + Otri neighotri = default(Otri); // for return value of the function + Otri tempotri; // for temporary usage + double first_x = 0, first_y = 0; // keeps the first point to be considered + double second_x = 0, second_y = 0; // for determining the edge we will begin + double third_x = 0, third_y = 0; // termination + double[] returnPoint = new double[2]; // for keeping the returned point + int numvertices = 0; // for keeping number of surrounding vertices + + // first determine which point to be used to find its neighbor triangles + switch (whichPoint) + { + case 1: + first_x = p.x; // point at the center + first_y = p.y; + second_x = r.x; // second vertex of first edge to consider + second_y = r.y; + third_x = q.x; // for terminating the search + third_y = q.y; + break; + case 2: + first_x = q.x; // point at the center + first_y = q.y; + second_x = p.x; // second vertex of first edge to consider + second_y = p.y; + third_x = r.x; // for terminating the search + third_y = r.y; + break; + case 3: + first_x = r.x; // point at the center + first_y = r.y; + second_x = q.x; // second vertex of first edge to consider + second_y = q.y; + third_x = p.x; // for terminating the search + third_y = p.y; + break; + } + tempotri = badotri; + // add first point as the end of first edge + points[numvertices] = second_x; + numvertices++; + points[numvertices] = second_y; + numvertices++; + // assign as dummy value + returnPoint[0] = second_x; returnPoint[1] = second_y; + // until we reach the third point of the beginning triangle + do + { + // find the neighbor's third point where it is incident to given edge + if (!GetNeighborsVertex(tempotri, first_x, first_y, second_x, second_y, ref returnPoint, ref neighotri)) + { + // go to next triangle + tempotri = neighotri; + // now the second point is the neighbor's third vertex + second_x = returnPoint[0]; + second_y = returnPoint[1]; + // add a new point to the list of surrounding points + points[numvertices] = returnPoint[0]; + numvertices++; + points[numvertices] = returnPoint[1]; + numvertices++; + } + else + { + numvertices = 0; + break; + } + } + while (!((Math.Abs(returnPoint[0] - third_x) <= EPS) && + (Math.Abs(returnPoint[1] - third_y) <= EPS))); + return numvertices / 2; + } + + /// + /// Gets a neighbours vertex. + /// + /// + /// + /// + /// + /// + /// Neighbor's third vertex incident to given edge. + /// Pointer for the neighbor triangle. + /// Returns true if vertex was found. + private bool GetNeighborsVertex(Otri badotri, + double first_x, double first_y, + double second_x, double second_y, + ref double[] thirdpoint, ref Otri neighotri) + { + Otri neighbor = default(Otri); // keeps the neighbor triangles + bool notFound = false; // boolean variable if we can find that neighbor or not + + // for keeping the vertices of the neighbor triangle + Vertex neighborvertex_1 = null; + Vertex neighborvertex_2 = null; + Vertex neighborvertex_3 = null; + + // used for finding neighbor triangle + int firstVertexMatched = 0, secondVertexMatched = 0; // to find the correct neighbor + //triangle ptr; // Temporary variable used by sym() + //int i; // index variable + // find neighbors + // Check each of the triangle's three neighbors to find the correct one + for (badotri.orient = 0; badotri.orient < 3; badotri.orient++) + { + // Find the neighbor. + badotri.Sym(ref neighbor); + // check if it is the one we are looking for by checking the corners + // first check if the neighbor is nonexistent, since it can be on the border + if (neighbor.tri.id != Mesh.DUMMY) + { + // then check if two wanted corners are also in this triangle + // take the vertices of the candidate neighbor + neighborvertex_1 = neighbor.Org(); + neighborvertex_2 = neighbor.Dest(); + neighborvertex_3 = neighbor.Apex(); + + // check if it is really a triangle + if ((neighborvertex_1.x == neighborvertex_2.x && neighborvertex_1.y == neighborvertex_2.y) + || (neighborvertex_2.x == neighborvertex_3.x && neighborvertex_2.y == neighborvertex_3.y) + || (neighborvertex_1.x == neighborvertex_3.x && neighborvertex_1.y == neighborvertex_3.y)) + { + //printf("Two vertices are the same!!!!!!!\n"); + } + else + { + // begin searching for the correct neighbor triangle + firstVertexMatched = 0; + if ((Math.Abs(first_x - neighborvertex_1.x) < EPS) && + (Math.Abs(first_y - neighborvertex_1.y) < EPS)) + { + firstVertexMatched = 11; // neighbor's 1st vertex is matched to first vertex + } + else if ((Math.Abs(first_x - neighborvertex_2.x) < EPS) && + (Math.Abs(first_y - neighborvertex_2.y) < EPS)) + { + firstVertexMatched = 12; // neighbor's 2nd vertex is matched to first vertex + } + else if ((Math.Abs(first_x - neighborvertex_3.x) < EPS) && + (Math.Abs(first_y - neighborvertex_3.y) < EPS)) + { + firstVertexMatched = 13; // neighbor's 3rd vertex is matched to first vertex + }/*else{ + // none of them matched + } // end of first vertex matching */ + + secondVertexMatched = 0; + if ((Math.Abs(second_x - neighborvertex_1.x) < EPS) && + (Math.Abs(second_y - neighborvertex_1.y) < EPS)) + { + secondVertexMatched = 21; // neighbor's 1st vertex is matched to second vertex + } + else if ((Math.Abs(second_x - neighborvertex_2.x) < EPS) && + (Math.Abs(second_y - neighborvertex_2.y) < EPS)) + { + secondVertexMatched = 22; // neighbor's 2nd vertex is matched to second vertex + } + else if ((Math.Abs(second_x - neighborvertex_3.x) < EPS) && + (Math.Abs(second_y - neighborvertex_3.y) < EPS)) + { + secondVertexMatched = 23; // neighbor's 3rd vertex is matched to second vertex + }/*else{ + // none of them matched + } // end of second vertex matching*/ + } + }// if neighbor exists or not + + if (((firstVertexMatched == 11) && (secondVertexMatched == 22 || secondVertexMatched == 23)) + || ((firstVertexMatched == 12) && (secondVertexMatched == 21 || secondVertexMatched == 23)) + || ((firstVertexMatched == 13) && (secondVertexMatched == 21 || secondVertexMatched == 22))) + break; + }// end of for loop over all orientations + + switch (firstVertexMatched) + { + case 0: + notFound = true; + break; + case 11: + if (secondVertexMatched == 22) + { + thirdpoint[0] = neighborvertex_3.x; + thirdpoint[1] = neighborvertex_3.y; + } + else if (secondVertexMatched == 23) + { + thirdpoint[0] = neighborvertex_2.x; + thirdpoint[1] = neighborvertex_2.y; + } + else { notFound = true; } + break; + case 12: + if (secondVertexMatched == 21) + { + thirdpoint[0] = neighborvertex_3.x; + thirdpoint[1] = neighborvertex_3.y; + } + else if (secondVertexMatched == 23) + { + thirdpoint[0] = neighborvertex_1.x; + thirdpoint[1] = neighborvertex_1.y; + } + else { notFound = true; } + break; + case 13: + if (secondVertexMatched == 21) + { + thirdpoint[0] = neighborvertex_2.x; + thirdpoint[1] = neighborvertex_2.y; + } + else if (secondVertexMatched == 22) + { + thirdpoint[0] = neighborvertex_1.x; + thirdpoint[1] = neighborvertex_1.y; + } + else { notFound = true; } + break; + default: + if (secondVertexMatched == 0) { notFound = true; } + break; + } + // pointer of the neighbor triangle + neighotri = neighbor; + return notFound; + } + + /// + /// Find a new point location by wedge intersection. + /// + /// + /// + /// A new location for the point according to surrounding points. + /// Returns true if new location found + private bool GetWedgeIntersectionWithoutMaxAngle(int numpoints, + double[] points, ref double[] newloc) + { + //double total_x = 0; + //double total_y = 0; + double x0, y0, x1, y1, x2, y2; + //double compConst = 0.01; // for comparing real numbers + + double x01, y01; + //double x12, y12; + + //double ax, ay, bx, by; //two intersections of two petals disks + + double d01;//, d12 + + //double petalx0, petaly0, petalr0, petalx1, petaly1, petalr1; + + //double p[5]; + + // Resize work arrays + if (2 * numpoints > petalx.Length) + { + petalx = new double[2 * numpoints]; + petaly = new double[2 * numpoints]; + petalr = new double[2 * numpoints]; + wedges = new double[2 * numpoints * 16 + 36]; + } + + double xmid, ymid, dist, x3, y3; + double x_1, y_1, x_2, y_2, x_3, y_3, x_4, y_4, tempx, tempy; + double ux, uy; + double alpha; + double[] p1 = new double[3]; + + //double poly_points; + int numpolypoints = 0; + + //int numBadTriangle; + + int i, j; + + int s, flag, count, num; + + double petalcenterconstant, petalradiusconstant; + + x0 = points[2 * numpoints - 4]; + y0 = points[2 * numpoints - 3]; + x1 = points[2 * numpoints - 2]; + y1 = points[2 * numpoints - 1]; + + // minimum angle + alpha = behavior.MinAngle * Math.PI / 180.0; + // initialize the constants + if (behavior.goodAngle == 1.0) + { + petalcenterconstant = 0; + petalradiusconstant = 0; + } + else + { + petalcenterconstant = 0.5 / Math.Tan(alpha); + petalradiusconstant = 0.5 / Math.Sin(alpha); + } + + for (i = 0; i < numpoints * 2; i = i + 2) + { + x2 = points[i]; + y2 = points[i + 1]; + + //printf("POLYGON POINTS (p,q) #%d (%.12f, %.12f) (%.12f, %.12f)\n", i/2, x0, y0,x1, y1); + + x01 = x1 - x0; + y01 = y1 - y0; + d01 = Math.Sqrt(x01 * x01 + y01 * y01); + // find the petal of each edge 01; + + // printf("PETAL CONSTANT (%.12f, %.12f)\n", + // b.petalcenterconstant, b.petalradiusconstant ); + // printf("PETAL DIFFS (%.6f, %.6f, %.4f)\n", x01, y01, d01); + + petalx[i / 2] = x0 + 0.5 * x01 - petalcenterconstant * y01; + petaly[i / 2] = y0 + 0.5 * y01 + petalcenterconstant * x01; + petalr[i / 2] = petalradiusconstant * d01; + petalx[numpoints + i / 2] = petalx[i / 2]; + petaly[numpoints + i / 2] = petaly[i / 2]; + petalr[numpoints + i / 2] = petalr[i / 2]; + //printf("PETAL POINTS #%d (%.12f, %.12f) R= %.12f\n", i/2, petalx[i/2],petaly[i/2], petalr[i/2]); + + /// FIRST FIND THE HALF-PLANE POINTS FOR EACH PETAL + xmid = (x0 + x1) / 2.0; // mid point of pq + ymid = (y0 + y1) / 2.0; + + // distance between xmid and petal center + dist = Math.Sqrt((petalx[i / 2] - xmid) * (petalx[i / 2] - xmid) + (petaly[i / 2] - ymid) * (petaly[i / 2] - ymid)); + // find the unit vector goes from mid point to petal center + ux = (petalx[i / 2] - xmid) / dist; + uy = (petaly[i / 2] - ymid) / dist; + // find the third point other than p and q + x3 = petalx[i / 2] + ux * petalr[i / 2]; + y3 = petaly[i / 2] + uy * petalr[i / 2]; + /// FIND THE LINE POINTS BY THE ROTATION MATRIX + // cw rotation matrix [cosX sinX; -sinX cosX] + // cw rotation about (x,y) [ux*cosX + uy*sinX + x - x*cosX - y*sinX; -ux*sinX + uy*cosX + y + x*sinX - y*cosX] + // ccw rotation matrix [cosX -sinX; sinX cosX] + // ccw rotation about (x,y) [ux*cosX - uy*sinX + x - x*cosX + y*sinX; ux*sinX + uy*cosX + y - x*sinX - y*cosX] + /// LINE #1: (x1,y1) & (x_1,y_1) + // vector from p to q + ux = x1 - x0; + uy = y1 - y0; + // rotate the vector around p = (x0,y0) in ccw by alpha degrees + x_1 = x1 * Math.Cos(alpha) - y1 * Math.Sin(alpha) + x0 - x0 * Math.Cos(alpha) + y0 * Math.Sin(alpha); + y_1 = x1 * Math.Sin(alpha) + y1 * Math.Cos(alpha) + y0 - x0 * Math.Sin(alpha) - y0 * Math.Cos(alpha); + // add these to wedges list as lines in order + wedges[i * 16] = x0; wedges[i * 16 + 1] = y0; + wedges[i * 16 + 2] = x_1; wedges[i * 16 + 3] = y_1; + //printf("LINE #1 (%.12f, %.12f) (%.12f, %.12f)\n", x0,y0,x_1,y_1); + /// LINE #2: (x2,y2) & (x_2,y_2) + // vector from p to q + ux = x0 - x1; + uy = y0 - y1; + // rotate the vector around q = (x1,y1) in cw by alpha degrees + x_2 = x0 * Math.Cos(alpha) + y0 * Math.Sin(alpha) + x1 - x1 * Math.Cos(alpha) - y1 * Math.Sin(alpha); + y_2 = -x0 * Math.Sin(alpha) + y0 * Math.Cos(alpha) + y1 + x1 * Math.Sin(alpha) - y1 * Math.Cos(alpha); + // add these to wedges list as lines in order + wedges[i * 16 + 4] = x_2; wedges[i * 16 + 5] = y_2; + wedges[i * 16 + 6] = x1; wedges[i * 16 + 7] = y1; + //printf("LINE #2 (%.12f, %.12f) (%.12f, %.12f)\n", x_2,y_2,x1,y1); + // vector from (petalx, petaly) to (x3,y3) + ux = x3 - petalx[i / 2]; + uy = y3 - petaly[i / 2]; + tempx = x3; tempy = y3; + /// LINE #3, #4, #5: (x3,y3) & (x_3,y_3) + for (j = 1; j < 4; j++) + { + // rotate the vector around (petalx,petaly) in cw by (60 - alpha)*j degrees + x_3 = x3 * Math.Cos((Math.PI / 3.0 - alpha) * j) + y3 * Math.Sin((Math.PI / 3.0 - alpha) * j) + petalx[i / 2] - petalx[i / 2] * Math.Cos((Math.PI / 3.0 - alpha) * j) - petaly[i / 2] * Math.Sin((Math.PI / 3.0 - alpha) * j); + y_3 = -x3 * Math.Sin((Math.PI / 3.0 - alpha) * j) + y3 * Math.Cos((Math.PI / 3.0 - alpha) * j) + petaly[i / 2] + petalx[i / 2] * Math.Sin((Math.PI / 3.0 - alpha) * j) - petaly[i / 2] * Math.Cos((Math.PI / 3.0 - alpha) * j); + // add these to wedges list as lines in order + wedges[i * 16 + 8 + 4 * (j - 1)] = x_3; wedges[i * 16 + 9 + 4 * (j - 1)] = y_3; + wedges[i * 16 + 10 + 4 * (j - 1)] = tempx; wedges[i * 16 + 11 + 4 * (j - 1)] = tempy; + tempx = x_3; tempy = y_3; + } + tempx = x3; tempy = y3; + /// LINE #6, #7, #8: (x3,y3) & (x_4,y_4) + for (j = 1; j < 4; j++) + { + // rotate the vector around (petalx,petaly) in ccw by (60 - alpha)*j degrees + x_4 = x3 * Math.Cos((Math.PI / 3.0 - alpha) * j) - y3 * Math.Sin((Math.PI / 3.0 - alpha) * j) + petalx[i / 2] - petalx[i / 2] * Math.Cos((Math.PI / 3.0 - alpha) * j) + petaly[i / 2] * Math.Sin((Math.PI / 3.0 - alpha) * j); + y_4 = x3 * Math.Sin((Math.PI / 3.0 - alpha) * j) + y3 * Math.Cos((Math.PI / 3.0 - alpha) * j) + petaly[i / 2] - petalx[i / 2] * Math.Sin((Math.PI / 3.0 - alpha) * j) - petaly[i / 2] * Math.Cos((Math.PI / 3.0 - alpha) * j); + + // add these to wedges list as lines in order + wedges[i * 16 + 20 + 4 * (j - 1)] = tempx; wedges[i * 16 + 21 + 4 * (j - 1)] = tempy; + wedges[i * 16 + 22 + 4 * (j - 1)] = x_4; wedges[i * 16 + 23 + 4 * (j - 1)] = y_4; + tempx = x_4; tempy = y_4; + } + //printf("LINE #3 (%.12f, %.12f) (%.12f, %.12f)\n", x_3,y_3,x3,y3); + //printf("LINE #4 (%.12f, %.12f) (%.12f, %.12f)\n", x3,y3,x_4,y_4); + + /// IF IT IS THE FIRST ONE, FIND THE CONVEX POLYGON + if (i == 0) + { + // line1 & line2: p1 + LineLineIntersection(x0, y0, x_1, y_1, x1, y1, x_2, y_2, ref p1); + if ((p1[0] == 1.0)) + { + // #0 + initialConvexPoly[0] = p1[1]; initialConvexPoly[1] = p1[2]; + // #1 + initialConvexPoly[2] = wedges[i * 16 + 16]; initialConvexPoly[3] = wedges[i * 16 + 17]; + // #2 + initialConvexPoly[4] = wedges[i * 16 + 12]; initialConvexPoly[5] = wedges[i * 16 + 13]; + // #3 + initialConvexPoly[6] = wedges[i * 16 + 8]; initialConvexPoly[7] = wedges[i * 16 + 9]; + // #4 + initialConvexPoly[8] = x3; initialConvexPoly[9] = y3; + // #5 + initialConvexPoly[10] = wedges[i * 16 + 22]; initialConvexPoly[11] = wedges[i * 16 + 23]; + // #6 + initialConvexPoly[12] = wedges[i * 16 + 26]; initialConvexPoly[13] = wedges[i * 16 + 27]; + // #7 + initialConvexPoly[14] = wedges[i * 16 + 30]; initialConvexPoly[15] = wedges[i * 16 + 31]; + //printf("INITIAL POLY [%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f]\n", initialConvexPoly[0],initialConvexPoly[1],initialConvexPoly[2],initialConvexPoly[3],initialConvexPoly[4],initialConvexPoly[5],initialConvexPoly[6],initialConvexPoly[7],initialConvexPoly[8],initialConvexPoly[9],initialConvexPoly[10],initialConvexPoly[11],initialConvexPoly[12],initialConvexPoly[13],initialConvexPoly[14],initialConvexPoly[15]); + } + } + + x0 = x1; y0 = y1; + x1 = x2; y1 = y2; + } + + /// HALF PLANE INTERSECTION: START SPLITTING THE INITIAL POLYGON TO FIND FEASIBLE REGION + if (numpoints != 0) + { + // first intersect the opposite located ones + s = (numpoints - 1) / 2 + 1; + flag = 0; + count = 0; + i = 1; + num = 8; + for (j = 0; j < 32; j = j + 4) + { + numpolypoints = HalfPlaneIntersection(num, ref initialConvexPoly, wedges[32 * s + j], wedges[32 * s + 1 + j], wedges[32 * s + 2 + j], wedges[32 * s + 3 + j]); + if (numpolypoints == 0) + return false; + else + num = numpolypoints; + } + count++; + while (count < numpoints - 1) + { + for (j = 0; j < 32; j = j + 4) + { + numpolypoints = HalfPlaneIntersection(num, ref initialConvexPoly, wedges[32 * (i + s * flag) + j], wedges[32 * (i + s * flag) + 1 + j], wedges[32 * (i + s * flag) + 2 + j], wedges[32 * (i + s * flag) + 3 + j]); + if (numpolypoints == 0) + return false; + else + num = numpolypoints; + } + i = i + flag; + flag = (flag + 1) % 2; + count++; + } + /// IF THERE IS A FEASIBLE INTERSECTION POLYGON, FIND ITS CENTROID AS THE NEW LOCATION + FindPolyCentroid(numpolypoints, initialConvexPoly, ref newloc); + + if (behavior.fixedArea) + { + // numBadTriangle = 0; + // for(j= 0; j < numpoints *2-2; j = j+2){ + // if(testTriangleAngleArea(m,b,&newloc[0],&newloc[1], &points[j], &points[j+1], &points[j+2], &points[j+3] )){ + // numBadTriangle++; + // } + // } + // if(testTriangleAngleArea(m,b, &newloc[0],&newloc[1], &points[0], &points[1], &points[numpoints*2-2], &points[numpoints*2-1] )){ + // numBadTriangle++; + // } + // + // if (numBadTriangle == 0) { + // + // return 1; + // } + } + else + { + //printf("yes, we found a feasible region num: %d newloc (%.12f,%.12f)\n", numpolypoints, newloc[0], newloc[1]); + // for(i = 0; i < 2*numpolypoints; i = i+2){ + // printf("point %d) (%.12f,%.12f)\n", i/2, initialConvexPoly[i], initialConvexPoly[i+1]); + // } + // printf("numpoints %d\n",numpoints); + return true; + } + } + + + return false; + } + + /// + /// Find a new point location by wedge intersection. + /// + /// + /// + /// A new location for the point according to surrounding points. + /// Returns true if new location found + private bool GetWedgeIntersection(int numpoints, double[] points, ref double[] newloc) + { + //double total_x = 0; + //double total_y = 0; + double x0, y0, x1, y1, x2, y2; + //double compConst = 0.01; // for comparing real numbers + + double x01, y01; + //double x12, y12; + + //double ax, ay, bx, by; //two intersections of two petals disks + + double d01;//, d12 + + //double petalx0, petaly1, petaly0, petalr0, petalx1, petalr1; + + //double p[5]; + + // Resize work arrays + if (2 * numpoints > petalx.Length) + { + petalx = new double[2 * numpoints]; + petaly = new double[2 * numpoints]; + petalr = new double[2 * numpoints]; + wedges = new double[2 * numpoints * 20 + 40]; + } + + double xmid, ymid, dist, x3, y3; + double x_1, y_1, x_2, y_2, x_3, y_3, x_4, y_4, tempx, tempy, x_5, y_5, x_6, y_6; + double ux, uy; + + double[] p1 = new double[3]; + double[] p2 = new double[3]; + double[] p3 = new double[3]; + double[] p4 = new double[3]; + + //double poly_points; + int numpolypoints = 0; + int howManyPoints = 0; // keeps the number of points used for representing the wedge + double line345 = 4.0, line789 = 4.0; // flag keeping which line to skip or construct + + int numBadTriangle; + + int i, j, k; + + int s, flag, count, num; + + int n, e; + + double weight; + + double petalcenterconstant, petalradiusconstant; + + x0 = points[2 * numpoints - 4]; + y0 = points[2 * numpoints - 3]; + x1 = points[2 * numpoints - 2]; + y1 = points[2 * numpoints - 1]; + + // minimum / maximum angle + double alpha, sinAlpha, cosAlpha, beta, sinBeta, cosBeta; + alpha = behavior.MinAngle * Math.PI / 180.0; + sinAlpha = Math.Sin(alpha); + cosAlpha = Math.Cos(alpha); + beta = behavior.MaxAngle * Math.PI / 180.0; + sinBeta = Math.Sin(beta); + cosBeta = Math.Cos(beta); + + // initialize the constants + if (behavior.goodAngle == 1.0) + { + petalcenterconstant = 0; + petalradiusconstant = 0; + } + else + { + petalcenterconstant = 0.5 / Math.Tan(alpha); + petalradiusconstant = 0.5 / Math.Sin(alpha); + } + + for (i = 0; i < numpoints * 2; i = i + 2) + { + // go to the next point + x2 = points[i]; + y2 = points[i + 1]; + + // printf("POLYGON POINTS (p,q) #%d (%.12f, %.12f) (%.12f, %.12f)\n", i/2, x0, y0,x1, y1); + + x01 = x1 - x0; + y01 = y1 - y0; + d01 = Math.Sqrt(x01 * x01 + y01 * y01); + // find the petal of each edge 01; + + // printf("PETAL CONSTANT (%.12f, %.12f)\n", + // b.petalcenterconstant, b.petalradiusconstant ); + // printf("PETAL DIFFS (%.6f, %.6f, %.4f)\n", x01, y01, d01); + //printf("i:%d numpoints:%d\n", i, numpoints); + petalx[i / 2] = x0 + 0.5 * x01 - petalcenterconstant * y01; + petaly[i / 2] = y0 + 0.5 * y01 + petalcenterconstant * x01; + petalr[i / 2] = petalradiusconstant * d01; + petalx[numpoints + i / 2] = petalx[i / 2]; + petaly[numpoints + i / 2] = petaly[i / 2]; + petalr[numpoints + i / 2] = petalr[i / 2]; + //printf("PETAL POINTS #%d (%.12f, %.12f) R= %.12f\n", i/2, petalx[i/2],petaly[i/2], petalr[i/2]); + + /// FIRST FIND THE HALF-PLANE POINTS FOR EACH PETAL + xmid = (x0 + x1) / 2.0; // mid point of pq + ymid = (y0 + y1) / 2.0; + + // distance between xmid and petal center + dist = Math.Sqrt((petalx[i / 2] - xmid) * (petalx[i / 2] - xmid) + (petaly[i / 2] - ymid) * (petaly[i / 2] - ymid)); + // find the unit vector goes from mid point to petal center + ux = (petalx[i / 2] - xmid) / dist; + uy = (petaly[i / 2] - ymid) / dist; + // find the third point other than p and q + x3 = petalx[i / 2] + ux * petalr[i / 2]; + y3 = petaly[i / 2] + uy * petalr[i / 2]; + /// FIND THE LINE POINTS BY THE ROTATION MATRIX + // cw rotation matrix [cosX sinX; -sinX cosX] + // cw rotation about (x,y) [ux*cosX + uy*sinX + x - x*cosX - y*sinX; -ux*sinX + uy*cosX + y + x*sinX - y*cosX] + // ccw rotation matrix [cosX -sinX; sinX cosX] + // ccw rotation about (x,y) [ux*cosX - uy*sinX + x - x*cosX + y*sinX; ux*sinX + uy*cosX + y - x*sinX - y*cosX] + /// LINE #1: (x1,y1) & (x_1,y_1) + // vector from p to q + ux = x1 - x0; + uy = y1 - y0; + // rotate the vector around p = (x0,y0) in ccw by alpha degrees + x_1 = x1 * cosAlpha - y1 * sinAlpha + x0 - x0 * cosAlpha + y0 * sinAlpha; + y_1 = x1 * sinAlpha + y1 * cosAlpha + y0 - x0 * sinAlpha - y0 * cosAlpha; + // add these to wedges list as lines in order + wedges[i * 20] = x0; wedges[i * 20 + 1] = y0; + wedges[i * 20 + 2] = x_1; wedges[i * 20 + 3] = y_1; + //printf("LINE #1 (%.12f, %.12f) (%.12f, %.12f)\n", x0,y0,x_1,y_1); + /// LINE #2: (x2,y2) & (x_2,y_2) + // vector from q to p + ux = x0 - x1; + uy = y0 - y1; + // rotate the vector around q = (x1,y1) in cw by alpha degrees + x_2 = x0 * cosAlpha + y0 * sinAlpha + x1 - x1 * cosAlpha - y1 * sinAlpha; + y_2 = -x0 * sinAlpha + y0 * cosAlpha + y1 + x1 * sinAlpha - y1 * cosAlpha; + // add these to wedges list as lines in order + wedges[i * 20 + 4] = x_2; wedges[i * 20 + 5] = y_2; + wedges[i * 20 + 6] = x1; wedges[i * 20 + 7] = y1; + //printf("LINE #2 (%.12f, %.12f) (%.12f, %.12f)\n", x_2,y_2,x1,y1); + // vector from (petalx, petaly) to (x3,y3) + ux = x3 - petalx[i / 2]; + uy = y3 - petaly[i / 2]; + tempx = x3; tempy = y3; + + /// DETERMINE HOW MANY POINTS TO USE ACCORDING TO THE MINANGLE-MAXANGLE COMBINATION + // petal center angle + alpha = (2.0 * behavior.MaxAngle + behavior.MinAngle - 180.0); + if (alpha <= 0.0) + {// when only angle lines needed + // 4 point case + howManyPoints = 4; + //printf("4 point case\n"); + line345 = 1.0; + line789 = 1.0; + } + else if (alpha <= 5.0) + {// when only angle lines plus two other lines are needed + // 6 point case + howManyPoints = 6; + //printf("6 point case\n"); + line345 = 2.0; + line789 = 2.0; + } + else if (alpha <= 10.0) + {// when we need more lines + // 8 point case + howManyPoints = 8; + line345 = 3.0; + line789 = 3.0; + //printf("8 point case\n"); + } + else + {// when we have a big wedge + // 10 point case + howManyPoints = 10; + //printf("10 point case\n"); + line345 = 4.0; + line789 = 4.0; + } + alpha = alpha * Math.PI / 180.0; + /// LINE #3, #4, #5: (x3,y3) & (x_3,y_3) + for (j = 1; j < line345; j++) + { + if (line345 == 1) + continue; + // rotate the vector around (petalx,petaly) in cw by (alpha/3.0)*j degrees + x_3 = x3 * Math.Cos((alpha / (line345 - 1.0)) * j) + y3 * Math.Sin(((alpha / (line345 - 1.0)) * j)) + petalx[i / 2] - petalx[i / 2] * Math.Cos(((alpha / (line345 - 1.0)) * j)) - petaly[i / 2] * Math.Sin(((alpha / (line345 - 1.0)) * j)); + y_3 = -x3 * Math.Sin(((alpha / (line345 - 1.0)) * j)) + y3 * Math.Cos(((alpha / (line345 - 1.0)) * j)) + petaly[i / 2] + petalx[i / 2] * Math.Sin(((alpha / (line345 - 1.0)) * j)) - petaly[i / 2] * Math.Cos(((alpha / (line345 - 1.0)) * j)); + // add these to wedges list as lines in order + wedges[i * 20 + 8 + 4 * (j - 1)] = x_3; wedges[i * 20 + 9 + 4 * (j - 1)] = y_3; + wedges[i * 20 + 10 + 4 * (j - 1)] = tempx; wedges[i * 20 + 11 + 4 * (j - 1)] = tempy; + tempx = x_3; tempy = y_3; + } + /// LINE #6: (x2,y2) & (x_3,y_3) + // vector from q to p + ux = x0 - x1; + uy = y0 - y1; + // rotate the vector around q = (x1,y1) in cw by alpha degrees + x_5 = x0 * cosBeta + y0 * sinBeta + x1 - x1 * cosBeta - y1 * sinBeta; + y_5 = -x0 * sinBeta + y0 * cosBeta + y1 + x1 * sinBeta - y1 * cosBeta; + wedges[i * 20 + 20] = x1; wedges[i * 20 + 21] = y1; + wedges[i * 20 + 22] = x_5; wedges[i * 20 + 23] = y_5; + + tempx = x3; tempy = y3; + /// LINE #7, #8, #9: (x3,y3) & (x_4,y_4) + for (j = 1; j < line789; j++) + { + if (line789 == 1) + continue; + // rotate the vector around (petalx,petaly) in ccw by (alpha/3.0)*j degrees + x_4 = x3 * Math.Cos((alpha / (line789 - 1.0)) * j) - y3 * Math.Sin((alpha / (line789 - 1.0)) * j) + petalx[i / 2] - petalx[i / 2] * Math.Cos((alpha / (line789 - 1.0)) * j) + petaly[i / 2] * Math.Sin((alpha / (line789 - 1.0)) * j); + y_4 = x3 * Math.Sin((alpha / (line789 - 1.0)) * j) + y3 * Math.Cos((alpha / (line789 - 1.0)) * j) + petaly[i / 2] - petalx[i / 2] * Math.Sin((alpha / (line789 - 1.0)) * j) - petaly[i / 2] * Math.Cos((alpha / (line789 - 1.0)) * j); + + // add these to wedges list as lines in order + wedges[i * 20 + 24 + 4 * (j - 1)] = tempx; wedges[i * 20 + 25 + 4 * (j - 1)] = tempy; + wedges[i * 20 + 26 + 4 * (j - 1)] = x_4; wedges[i * 20 + 27 + 4 * (j - 1)] = y_4; + tempx = x_4; tempy = y_4; + } + /// LINE #10: (x1,y1) & (x_3,y_3) + // vector from p to q + ux = x1 - x0; + uy = y1 - y0; + // rotate the vector around p = (x0,y0) in ccw by alpha degrees + x_6 = x1 * cosBeta - y1 * sinBeta + x0 - x0 * cosBeta + y0 * sinBeta; + y_6 = x1 * sinBeta + y1 * cosBeta + y0 - x0 * sinBeta - y0 * cosBeta; + wedges[i * 20 + 36] = x_6; wedges[i * 20 + 37] = y_6; + wedges[i * 20 + 38] = x0; wedges[i * 20 + 39] = y0; + + //printf("LINE #1 (%.12f, %.12f) (%.12f, %.12f)\n", x0,y0,x_1,y_1); + /// IF IT IS THE FIRST ONE, FIND THE CONVEX POLYGON + if (i == 0) + { + switch (howManyPoints) + { + case 4: + // line1 & line2 & line3 & line4 + LineLineIntersection(x0, y0, x_1, y_1, x1, y1, x_2, y_2, ref p1); + LineLineIntersection(x0, y0, x_1, y_1, x1, y1, x_5, y_5, ref p2); + LineLineIntersection(x0, y0, x_6, y_6, x1, y1, x_5, y_5, ref p3); + LineLineIntersection(x0, y0, x_6, y_6, x1, y1, x_2, y_2, ref p4); + if ((p1[0] == 1.0) && (p2[0] == 1.0) && (p3[0] == 1.0) && (p4[0] == 1.0)) + { + // #0 + initialConvexPoly[0] = p1[1]; initialConvexPoly[1] = p1[2]; + // #1 + initialConvexPoly[2] = p2[1]; initialConvexPoly[3] = p2[2]; + // #2 + initialConvexPoly[4] = p3[1]; initialConvexPoly[5] = p3[2]; + // #3 + initialConvexPoly[6] = p4[1]; initialConvexPoly[7] = p4[2]; + } + break; + case 6: + // line1 & line2 & line3 + LineLineIntersection(x0, y0, x_1, y_1, x1, y1, x_2, y_2, ref p1); + LineLineIntersection(x0, y0, x_1, y_1, x1, y1, x_5, y_5, ref p2); + LineLineIntersection(x0, y0, x_6, y_6, x1, y1, x_2, y_2, ref p3); + if ((p1[0] == 1.0) && (p2[0] == 1.0) && (p3[0] == 1.0)) + { + // #0 + initialConvexPoly[0] = p1[1]; initialConvexPoly[1] = p1[2]; + // #1 + initialConvexPoly[2] = p2[1]; initialConvexPoly[3] = p2[2]; + // #2 + initialConvexPoly[4] = wedges[i * 20 + 8]; initialConvexPoly[5] = wedges[i * 20 + 9]; + // #3 + initialConvexPoly[6] = x3; initialConvexPoly[7] = y3; + // #4 + initialConvexPoly[8] = wedges[i * 20 + 26]; initialConvexPoly[9] = wedges[i * 20 + 27]; + // #5 + initialConvexPoly[10] = p3[1]; initialConvexPoly[11] = p3[2]; + } + break; + case 8: + // line1 & line2: p1 + LineLineIntersection(x0, y0, x_1, y_1, x1, y1, x_2, y_2, ref p1); + LineLineIntersection(x0, y0, x_1, y_1, x1, y1, x_5, y_5, ref p2); + LineLineIntersection(x0, y0, x_6, y_6, x1, y1, x_2, y_2, ref p3); + if ((p1[0] == 1.0) && (p2[0] == 1.0) && (p3[0] == 1.0)) + { + // #0 + initialConvexPoly[0] = p1[1]; initialConvexPoly[1] = p1[2]; + // #1 + initialConvexPoly[2] = p2[1]; initialConvexPoly[3] = p2[2]; + // #2 + initialConvexPoly[4] = wedges[i * 20 + 12]; initialConvexPoly[5] = wedges[i * 20 + 13]; + // #3 + initialConvexPoly[6] = wedges[i * 20 + 8]; initialConvexPoly[7] = wedges[i * 20 + 9]; + // #4 + initialConvexPoly[8] = x3; initialConvexPoly[9] = y3; + // #5 + initialConvexPoly[10] = wedges[i * 20 + 26]; initialConvexPoly[11] = wedges[i * 20 + 27]; + // #6 + initialConvexPoly[12] = wedges[i * 20 + 30]; initialConvexPoly[13] = wedges[i * 20 + 31]; + // #7 + initialConvexPoly[14] = p3[1]; initialConvexPoly[15] = p3[2]; + } + break; + case 10: + // line1 & line2: p1 + LineLineIntersection(x0, y0, x_1, y_1, x1, y1, x_2, y_2, ref p1); + LineLineIntersection(x0, y0, x_1, y_1, x1, y1, x_5, y_5, ref p2); + LineLineIntersection(x0, y0, x_6, y_6, x1, y1, x_2, y_2, ref p3); + //printf("p3 %f %f %f (%f %f) (%f %f) (%f %f) (%f %f)\n",p3[0],p3[1],p3[2], x0, y0, x_6, x_6, x1, y1, x_2, y_2); + if ((p1[0] == 1.0) && (p2[0] == 1.0) && (p3[0] == 1.0)) + { + // #0 + initialConvexPoly[0] = p1[1]; initialConvexPoly[1] = p1[2]; + // #1 + initialConvexPoly[2] = p2[1]; initialConvexPoly[3] = p2[2]; + // #2 + initialConvexPoly[4] = wedges[i * 20 + 16]; initialConvexPoly[5] = wedges[i * 20 + 17]; + // #3 + initialConvexPoly[6] = wedges[i * 20 + 12]; initialConvexPoly[7] = wedges[i * 20 + 13]; + // #4 + initialConvexPoly[8] = wedges[i * 20 + 8]; initialConvexPoly[9] = wedges[i * 20 + 9]; + // #5 + initialConvexPoly[10] = x3; initialConvexPoly[11] = y3; + // #6 + initialConvexPoly[12] = wedges[i * 20 + 28]; initialConvexPoly[13] = wedges[i * 20 + 29]; + // #7 + initialConvexPoly[14] = wedges[i * 20 + 32]; initialConvexPoly[15] = wedges[i * 20 + 33]; + // #8 + initialConvexPoly[16] = wedges[i * 20 + 34]; initialConvexPoly[17] = wedges[i * 20 + 35]; + // #9 + initialConvexPoly[18] = p3[1]; initialConvexPoly[19] = p3[2]; + } + break; + } + // printf("smallest edge (%f,%f) (%f,%f)\n", x0,y0, x1,y1); + // printf("real INITIAL POLY [%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;]\n", initialConvexPoly[0],initialConvexPoly[1],initialConvexPoly[2],initialConvexPoly[3],initialConvexPoly[4],initialConvexPoly[5],initialConvexPoly[6],initialConvexPoly[7],initialConvexPoly[8],initialConvexPoly[9],initialConvexPoly[10],initialConvexPoly[11],initialConvexPoly[12],initialConvexPoly[13],initialConvexPoly[14],initialConvexPoly[15],initialConvexPoly[16],initialConvexPoly[17],initialConvexPoly[18],initialConvexPoly[19]); + } + + x0 = x1; y0 = y1; + x1 = x2; y1 = y2; + } + /// HALF PLANE INTERSECTION: START SPLITTING THE INITIAL POLYGON TO FIND FEASIBLE REGION + if (numpoints != 0) + { + // first intersect the opposite located ones + s = (numpoints - 1) / 2 + 1; + flag = 0; + count = 0; + i = 1; + num = howManyPoints; + for (j = 0; j < 40; j = j + 4) + { + // in order to skip non-existent lines + if (howManyPoints == 4 && (j == 8 || j == 12 || j == 16 || j == 24 || j == 28 || j == 32)) + { + continue; + } + else if (howManyPoints == 6 && (j == 12 || j == 16 || j == 28 || j == 32)) + { + continue; + } + else if (howManyPoints == 8 && (j == 16 || j == 32)) + { + continue; + } + // printf("%d 1 INITIAL POLY [%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;]\n",num, initialConvexPoly[0],initialConvexPoly[1],initialConvexPoly[2],initialConvexPoly[3],initialConvexPoly[4],initialConvexPoly[5],initialConvexPoly[6],initialConvexPoly[7],initialConvexPoly[8],initialConvexPoly[9],initialConvexPoly[10],initialConvexPoly[11],initialConvexPoly[12],initialConvexPoly[13],initialConvexPoly[14],initialConvexPoly[15],initialConvexPoly[16],initialConvexPoly[17],initialConvexPoly[18],initialConvexPoly[19]); + // printf("line (%f, %f) (%f, %f)\n",wedges[40*s+j],wedges[40*s+1+j], wedges[40*s+2+j], wedges[40*s+3+j]); + numpolypoints = HalfPlaneIntersection(num, ref initialConvexPoly, wedges[40 * s + j], wedges[40 * s + 1 + j], wedges[40 * s + 2 + j], wedges[40 * s + 3 + j]); + + if (numpolypoints == 0) + return false; + else + num = numpolypoints; + } + count++; + //printf("yes here\n"); + while (count < numpoints - 1) + { + for (j = 0; j < 40; j = j + 4) + { + // in order to skip non-existent lines + if (howManyPoints == 4 && (j == 8 || j == 12 || j == 16 || j == 24 || j == 28 || j == 32)) + { + continue; + } + else if (howManyPoints == 6 && (j == 12 || j == 16 || j == 28 || j == 32)) + { + continue; + } + else if (howManyPoints == 8 && (j == 16 || j == 32)) + { + continue; + } + ////printf("%d 2 INITIAL POLY [%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;%.12f, %.12f;]\n",numpolypoints, initialConvexPoly[0],initialConvexPoly[1],initialConvexPoly[2],initialConvexPoly[3],initialConvexPoly[4],initialConvexPoly[5],initialConvexPoly[6],initialConvexPoly[7],initialConvexPoly[8],initialConvexPoly[9],initialConvexPoly[10],initialConvexPoly[11],initialConvexPoly[12],initialConvexPoly[13],initialConvexPoly[14],initialConvexPoly[15],initialConvexPoly[16],initialConvexPoly[17],initialConvexPoly[18],initialConvexPoly[19]); + //printf("line (%.20f, %.20f) (%.20f, %.20f)\n", wedges[40 * (i + s * flag) + j], wedges[40 * (i + s * flag) + 1 + j], wedges[40 * (i + s * flag) + 2 + j], wedges[40 * (i + s * flag) + 3 + j]); + numpolypoints = HalfPlaneIntersection(num, ref initialConvexPoly, wedges[40 * (i + s * flag) + j], wedges[40 * (i + s * flag) + 1 + j], wedges[40 * (i + s * flag) + 2 + j], wedges[40 * (i + s * flag) + 3 + j]); + + if (numpolypoints == 0) + return false; + else + num = numpolypoints; + } + i = i + flag; + flag = (flag + 1) % 2; + count++; + } + /// IF THERE IS A FEASIBLE INTERSECTION POLYGON, FIND ITS CENTROID AS THE NEW LOCATION + FindPolyCentroid(numpolypoints, initialConvexPoly, ref newloc); + + if (behavior.MaxAngle != 0.0) + { + numBadTriangle = 0; + for (j = 0; j < numpoints * 2 - 2; j = j + 2) + { + if (IsBadTriangleAngle(newloc[0], newloc[1], points[j], points[j + 1], points[j + 2], points[j + 3])) + { + numBadTriangle++; + } + } + if (IsBadTriangleAngle(newloc[0], newloc[1], points[0], points[1], points[numpoints * 2 - 2], points[numpoints * 2 - 1])) + { + numBadTriangle++; + } + + if (numBadTriangle == 0) + { + return true; + } + n = (numpoints <= 2) ? 20 : 30; + // try points other than centroid + for (k = 0; k < 2 * numpoints; k = k + 2) + { + for (e = 1; e < n; e = e + 1) + { + newloc[0] = 0.0; newloc[1] = 0.0; + for (i = 0; i < 2 * numpoints; i = i + 2) + { + weight = 1.0 / numpoints; + if (i == k) + { + newloc[0] = newloc[0] + 0.1 * e * weight * points[i]; + newloc[1] = newloc[1] + 0.1 * e * weight * points[i + 1]; + } + else + { + weight = (1.0 - 0.1 * e * weight) / (double)(numpoints - 1.0); + newloc[0] = newloc[0] + weight * points[i]; + newloc[1] = newloc[1] + weight * points[i + 1]; + } + } + numBadTriangle = 0; + for (j = 0; j < numpoints * 2 - 2; j = j + 2) + { + if (IsBadTriangleAngle(newloc[0], newloc[1], points[j], points[j + 1], points[j + 2], points[j + 3])) + { + numBadTriangle++; + } + } + if (IsBadTriangleAngle(newloc[0], newloc[1], points[0], points[1], points[numpoints * 2 - 2], points[numpoints * 2 - 1])) + { + numBadTriangle++; + } + + if (numBadTriangle == 0) + { + return true; + } + } + } + } + else + { + //printf("yes, we found a feasible region num: %d newloc (%.12f,%.12f)\n", numpolypoints, newloc[0], newloc[1]); + // for(i = 0; i < 2*numpolypoints; i = i+2){ + // printf("point %d) (%.12f,%.12f)\n", i/2, initialConvexPoly[i], initialConvexPoly[i+1]); + // } + // printf("numpoints %d\n",numpoints); + return true; + } + } + + + return false; + } + + /// + /// Check polygon for min angle. + /// + /// + /// + /// Returns true if the polygon has angles greater than 2*minangle. + private bool ValidPolygonAngles(int numpoints, double[] points) + { + int i;//,j + for (i = 0; i < numpoints; i++) + { + if (i == numpoints - 1) + { + if (IsBadPolygonAngle(points[i * 2], points[i * 2 + 1], points[0], points[1], points[2], points[3])) + { + return false; // one of the inner angles is less than required + } + } + else if (i == numpoints - 2) + { + if (IsBadPolygonAngle(points[i * 2], points[i * 2 + 1], points[(i + 1) * 2], points[(i + 1) * 2 + 1], points[0], points[1])) + { + return false; // one of the inner angles is less than required + } + } + else + { + if (IsBadPolygonAngle(points[i * 2], points[i * 2 + 1], points[(i + 1) * 2], points[(i + 1) * 2 + 1], points[(i + 2) * 2], points[(i + 2) * 2 + 1])) + { + return false; // one of the inner angles is less than required + } + } + } + return true; // all angles are valid + } + + /// + /// Given three coordinates of a polygon, tests to see if it satisfies the minimum + /// angle condition for relocation. + /// + /// + /// + /// + /// + /// + /// + /// Returns true, if it is a BAD polygon corner, returns false if it is a GOOD + /// polygon corner + private bool IsBadPolygonAngle(double x1, double y1, + double x2, double y2, double x3, double y3) + { + // variables keeping the distance values for the edges + double dx12, dy12, dx23, dy23, dx31, dy31; + double dist12, dist23, dist31; + + double cosAngle; // in order to check minimum angle condition + + // calculate the side lengths + + dx12 = x1 - x2; + dy12 = y1 - y2; + dx23 = x2 - x3; + dy23 = y2 - y3; + dx31 = x3 - x1; + dy31 = y3 - y1; + // calculate the squares of the side lentghs + dist12 = dx12 * dx12 + dy12 * dy12; + dist23 = dx23 * dx23 + dy23 * dy23; + dist31 = dx31 * dx31 + dy31 * dy31; + + /// calculate cosine of largest angle /// + cosAngle = (dist12 + dist23 - dist31) / (2 * Math.Sqrt(dist12) * Math.Sqrt(dist23)); + // Check whether the angle is smaller than permitted which is 2*minangle!!! + //printf("angle: %f 2*minangle = %f\n",acos(cosAngle)*180/PI, 2*acos(Math.Sqrt(b.goodangle))*180/PI); + if (Math.Acos(cosAngle) < 2 * Math.Acos(Math.Sqrt(behavior.goodAngle))) + { + return true;// it is a BAD triangle + } + return false;// it is a GOOD triangle + } + + /// + /// Given four points representing two lines, returns the intersection point. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// The intersection point. + /// + // referenced to: http://local.wasp.uwa.edu.au/~pbourke/geometry/ + /// + private void LineLineIntersection( + double x1, double y1, + double x2, double y2, + double x3, double y3, + double x4, double y4, ref double[] p) + { + // x1,y1 P1 coordinates (point of line 1) + // x2,y2 P2 coordinates (point of line 1) + // x3,y3 P3 coordinates (point of line 2) + // x4,y4 P4 coordinates (point of line 2) + // p[1],p[2] intersection coordinates + // + // This function returns a pointer array which first index indicates + // weather they intersect on one point or not, followed by coordinate pairs. + + double u_a, u_b, denom; + + // calculate denominator first + denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); + u_a = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); + u_b = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3); + // if denominator and numerator equal to zero, lines are coincident + if (Math.Abs(denom - 0.0) < EPS && (Math.Abs(u_b - 0.0) < EPS && Math.Abs(u_a - 0.0) < EPS)) + { + p[0] = 0.0; + } + // if denominator equals to zero, lines are parallel + else if (Math.Abs(denom - 0.0) < EPS) + { + p[0] = 0.0; + } + else + { + p[0] = 1.0; + u_a = u_a / denom; + u_b = u_b / denom; + p[1] = x1 + u_a * (x2 - x1); // not the intersection point + p[2] = y1 + u_a * (y2 - y1); + } + } + + /// + /// Returns the convex polygon which is the intersection of the given convex + /// polygon with the halfplane on the left side (regarding the directional vector) + /// of the given line. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// http://www.mathematik.uni-ulm.de/stochastik/lehre/ws03_04/rt/Geometry2D.ps + /// + private int HalfPlaneIntersection(int numvertices, ref double[] convexPoly, double x1, double y1, double x2, double y2) + { + double dx, dy; // direction of the line + double z, min, max; + int i, j; + + int numpolys; + double[] res = null; + int count = 0; + int intFound = 0; + dx = x2 - x1; + dy = y2 - y1; + numpolys = SplitConvexPolygon(numvertices, convexPoly, x1, y1, x2, y2, polys); + + if (numpolys == 3) + { + count = numvertices; + } + else + { + for (i = 0; i < numpolys; i++) + { + min = double.MaxValue; + max = double.MinValue; + // compute the minimum and maximum of the + // third coordinate of the cross product + for (j = 1; j <= 2 * polys[i][0] - 1; j = j + 2) + { + z = dx * (polys[i][j + 1] - y1) - dy * (polys[i][j] - x1); + min = (z < min ? z : min); + max = (z > max ? z : max); + } + // ... and choose the (absolute) greater of both + z = (Math.Abs(min) > Math.Abs(max) ? min : max); + // and if it is positive, the polygon polys[i] + // is on the left side of line + if (z > 0.0) + { + res = polys[i]; + intFound = 1; + break; + } + } + if (intFound == 1) + { + while (count < res[0]) + { + convexPoly[2 * count] = res[2 * count + 1]; + convexPoly[2 * count + 1] = res[2 * count + 2]; + count++; + } + } + } + // update convexPoly + return count; + } + + /// + /// Splits a convex polygons into one or two polygons through the intersection + /// with the given line (regarding the directional vector of the given line). + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// http://www.mathematik.uni-ulm.de/stochastik/lehre/ws03_04/rt/Geometry2D.ps + /// + private int SplitConvexPolygon(int numvertices, double[] convexPoly, double x1, double y1, double x2, double y2, double[][] polys) + { + // state = 0: before the first intersection (with the line) + // state = 1: after the first intersection (with the line) + // state = 2: after the second intersection (with the line) + + int state = 0; + double[] p = new double[3]; + int poly1counter = 0; + int poly2counter = 0; + int numpolys; + int i; + double compConst = 0.000000000001; + // for debugging + int case1 = 0, case2 = 0, case3 = 0, case31 = 0, case32 = 0, case33 = 0, case311 = 0, case3111 = 0; + // intersect all edges of poly with line + for (i = 0; i < 2 * numvertices; i = i + 2) + { + int j = (i + 2 >= 2 * numvertices) ? 0 : i + 2; + LineLineSegmentIntersection(x1, y1, x2, y2, convexPoly[i], convexPoly[i + 1], convexPoly[j], convexPoly[j + 1], ref p); + // if this edge does not intersect with line + if (Math.Abs(p[0] - 0.0) <= compConst) + { + //System.out.println("null"); + // add p[j] to the proper polygon + if (state == 1) + { + poly2counter++; + poly2[2 * poly2counter - 1] = convexPoly[j]; + poly2[2 * poly2counter] = convexPoly[j + 1]; + } + else + { + poly1counter++; + poly1[2 * poly1counter - 1] = convexPoly[j]; + poly1[2 * poly1counter] = convexPoly[j + 1]; + } + // debug + case1++; + } + // ... or if the intersection is the whole edge + else if (Math.Abs(p[0] - 2.0) <= compConst) + { + //System.out.println(o); + // then we can not reach state 1 and 2 + poly1counter++; + poly1[2 * poly1counter - 1] = convexPoly[j]; + poly1[2 * poly1counter] = convexPoly[j + 1]; + // debug + case2++; + } + // ... or if the intersection is a point + else + { + // debug + case3++; + // if the point is the second vertex of the edge + if (Math.Abs(p[1] - convexPoly[j]) <= compConst && Math.Abs(p[2] - convexPoly[j + 1]) <= compConst) + { + // debug + case31++; + if (state == 1) + { + poly2counter++; + poly2[2 * poly2counter - 1] = convexPoly[j]; + poly2[2 * poly2counter] = convexPoly[j + 1]; + poly1counter++; + poly1[2 * poly1counter - 1] = convexPoly[j]; + poly1[2 * poly1counter] = convexPoly[j + 1]; + state++; + } + else if (state == 0) + { + // debug + case311++; + poly1counter++; + poly1[2 * poly1counter - 1] = convexPoly[j]; + poly1[2 * poly1counter] = convexPoly[j + 1]; + // test whether the polygon is splitted + // or the line only touches the polygon + if (i + 4 < 2 * numvertices) + { + int s1 = LinePointLocation(x1, y1, x2, y2, convexPoly[i], convexPoly[i + 1]); + int s2 = LinePointLocation(x1, y1, x2, y2, convexPoly[i + 4], convexPoly[i + 5]); + // the line only splits the polygon + // when the previous and next vertex lie + // on different sides of the line + if (s1 != s2 && s1 != 0 && s2 != 0) + { + // debug + case3111++; + poly2counter++; + poly2[2 * poly2counter - 1] = convexPoly[j]; + poly2[2 * poly2counter] = convexPoly[j + 1]; + state++; + } + } + } + } + // ... if the point is not the other vertex of the edge + else if (!(Math.Abs(p[1] - convexPoly[i]) <= compConst && Math.Abs(p[2] - convexPoly[i + 1]) <= compConst)) + { + // debug + case32++; + poly1counter++; + poly1[2 * poly1counter - 1] = p[1]; + poly1[2 * poly1counter] = p[2]; + poly2counter++; + poly2[2 * poly2counter - 1] = p[1]; + poly2[2 * poly2counter] = p[2]; + if (state == 1) + { + poly1counter++; + poly1[2 * poly1counter - 1] = convexPoly[j]; + poly1[2 * poly1counter] = convexPoly[j + 1]; + } + else if (state == 0) + { + poly2counter++; + poly2[2 * poly2counter - 1] = convexPoly[j]; + poly2[2 * poly2counter] = convexPoly[j + 1]; + } + state++; + } + // ... else if the point is the second vertex of the edge + else + { + // debug + case33++; + if (state == 1) + { + poly2counter++; + poly2[2 * poly2counter - 1] = convexPoly[j]; + poly2[2 * poly2counter] = convexPoly[j + 1]; + } + else + { + poly1counter++; + poly1[2 * poly1counter - 1] = convexPoly[j]; + poly1[2 * poly1counter] = convexPoly[j + 1]; + } + } + } + } + // after splitting the state must be 0 or 2 + // (depending whether the polygon was splitted or not) + if (state != 0 && state != 2) + { + // printf("there is something wrong state: %d\n", state); + // printf("polygon might not be convex!!\n"); + // printf("case1: %d\ncase2: %d\ncase3: %d\ncase31: %d case311: %d case3111: %d\ncase32: %d\ncase33: %d\n", case1, case2, case3, case31, case311, case3111, case32, case33); + // printf("numvertices %d\n=============\n", numvertices); + + // if there is something wrong with the intersection, just ignore this one + numpolys = 3; + } + else + { + // finally convert the vertex lists into convex polygons + numpolys = (state == 0) ? 1 : 2; + poly1[0] = poly1counter; + poly2[0] = poly2counter; + // convert the first convex polygon + polys[0] = poly1; + // convert the second convex polygon + if (state == 2) + { + polys[1] = poly2; + } + } + return numpolys; + } + + /// + /// Determines on which side (relative to the direction) of the given line and the + /// point lies (regarding the directional vector) of the given line. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// http://www.mathematik.uni-ulm.de/stochastik/lehre/ws03_04/rt/Geometry2D.ps + /// + private int LinePointLocation(double x1, double y1, double x2, double y2, double x, double y) + { + double z; + if (Math.Atan((y2 - y1) / (x2 - x1)) * 180.0 / Math.PI == 90.0) + { + if (Math.Abs(x1 - x) <= 0.00000000001) + return 0; + } + else + { + if (Math.Abs(y1 + (((y2 - y1) * (x - x1)) / (x2 - x1)) - y) <= EPS) + return 0; + } + // third component of the 3 dimensional product + z = (x2 - x1) * (y - y1) - (y2 - y1) * (x - x1); + if (Math.Abs(z - 0.0) <= 0.00000000001) + { + return 0; + } + else if (z > 0) + { + return 1; + } + else + { + return 2; + } + } + + /// + /// Given four points representing one line and a line segment, returns the intersection point + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// referenced to: http://local.wasp.uwa.edu.au/~pbourke/geometry/ + /// + private void LineLineSegmentIntersection( + double x1, double y1, + double x2, double y2, + double x3, double y3, + double x4, double y4, ref double[] p) + { + // x1,y1 P1 coordinates (point of line) + // x2,y2 P2 coordinates (point of line) + // x3,y3 P3 coordinates (point of line segment) + // x4,y4 P4 coordinates (point of line segment) + // p[1],p[2] intersection coordinates + // + // This function returns a pointer array which first index indicates + // weather they intersect on one point or not, followed by coordinate pairs. + + double u_a, u_b, denom; + double compConst = 0.0000000000001; + // calculate denominator first + denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1); + u_a = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3); + u_b = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3); + + + //if(fabs(denom-0.0) < compConst && (fabs(u_b-0.0) < compConst && fabs(u_a-0.0) < compConst)){ + //printf("denom %.20f u_b %.20f u_a %.20f\n",denom, u_b, u_a); + if (Math.Abs(denom - 0.0) < compConst) + { + if (Math.Abs(u_b - 0.0) < compConst && Math.Abs(u_a - 0.0) < compConst) + { + p[0] = 2.0; // if denominator and numerator equal to zero, lines are coincident + } + else + { + p[0] = 0.0;// if denominator equals to zero, lines are parallel + } + } + else + { + u_b = u_b / denom; + u_a = u_a / denom; + // printf("u_b %.20f\n", u_b); + if (u_b < -compConst || u_b > 1.0 + compConst) + { // check if it is on the line segment + // printf("line (%.20f, %.20f) (%.20f, %.20f) line seg (%.20f, %.20f) (%.20f, %.20f) \n",x1, y1 ,x2, y2 ,x3, y3 , x4, y4); + p[0] = 0.0; + } + else + { + p[0] = 1.0; + p[1] = x1 + u_a * (x2 - x1); // intersection point + p[2] = y1 + u_a * (y2 - y1); + } + } + } + + /// + /// Returns the centroid of a given polygon + /// + /// + /// + /// Centroid of a given polygon + private void FindPolyCentroid(int numpoints, double[] points, ref double[] centroid) + { + int i; + //double area = 0.0;//, temp + centroid[0] = 0.0; centroid[1] = 0.0; + + for (i = 0; i < 2 * numpoints; i = i + 2) + { + centroid[0] = centroid[0] + points[i]; + centroid[1] = centroid[1] + points[i + 1]; + } + centroid[0] = centroid[0] / numpoints; + centroid[1] = centroid[1] / numpoints; + } + + /// + /// Given two points representing a line and a radius together with a center point + /// representing a circle, returns the intersection points. + /// + /// + /// + /// + /// + /// + /// + /// + /// Pointer to list of intersection points + /// + /// referenced to: http://local.wasp.uwa.edu.au/~pbourke/geometry/sphereline/ + /// + private void CircleLineIntersection( + double x1, double y1, + double x2, double y2, + double x3, double y3, double r, ref double[] p) + { + // x1,y1 P1 coordinates [point of line] + // x2,y2 P2 coordinates [point of line] + // x3,y3, r P3 coordinates(circle center) and radius [circle] + // p[1],p[2]; p[3],p[4] intersection coordinates + // + // This function returns a pointer array which first index indicates + // the number of intersection points, followed by coordinate pairs. + + //double x , y ; + double a, b, c, mu, i; + + a = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); + b = 2 * ((x2 - x1) * (x1 - x3) + (y2 - y1) * (y1 - y3)); + c = x3 * x3 + y3 * y3 + x1 * x1 + y1 * y1 - 2 * (x3 * x1 + y3 * y1) - r * r; + i = b * b - 4 * a * c; + + if (i < 0.0) + { + // no intersection + p[0] = 0.0; + } + else if (Math.Abs(i - 0.0) < EPS) + { + // one intersection + p[0] = 1.0; + + mu = -b / (2 * a); + p[1] = x1 + mu * (x2 - x1); + p[2] = y1 + mu * (y2 - y1); + } + else if (i > 0.0 && !(Math.Abs(a - 0.0) < EPS)) + { + // two intersections + p[0] = 2.0; + // first intersection + mu = (-b + Math.Sqrt(i)) / (2 * a); + p[1] = x1 + mu * (x2 - x1); + p[2] = y1 + mu * (y2 - y1); + // second intersection + mu = (-b - Math.Sqrt(i)) / (2 * a); + p[3] = x1 + mu * (x2 - x1); + p[4] = y1 + mu * (y2 - y1); + } + else + { + p[0] = 0.0; + } + } + + /// + /// Given three points, check if the point is the correct point that we are looking for. + /// + /// P1 coordinates (bisector point of dual edge on triangle) + /// P1 coordinates (bisector point of dual edge on triangle) + /// P2 coordinates (intersection point) + /// P2 coordinates (intersection point) + /// P3 coordinates (circumcenter point) + /// P3 coordinates (circumcenter point) + /// + /// Returns true, if given point is the correct one otherwise return false. + private bool ChooseCorrectPoint( + double x1, double y1, + double x2, double y2, + double x3, double y3, bool isObtuse) + { + double d1, d2; + bool p; + + // squared distance between circumcenter and intersection point + d1 = (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3); + // squared distance between bisector point and intersection point + d2 = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); + + if (isObtuse) + { + // obtuse case + if (d2 >= d1) + { + p = true; // means we have found the right point + } + else + { + p = false; // means take the other point + } + } + else + { + // non-obtuse case + if (d2 < d1) + { + p = true; // means we have found the right point + } + else + { + p = false; // means take the other point + } + } + /// HANDLE RIGHT TRIANGLE CASE!!!!!!!!!!!!!!!!!!!!!!!!!!!! + return p; + } + + /// + /// This function returns a pointer array which first index indicates the whether + /// the point is in between the other points, followed by coordinate pairs. + /// + /// P1 coordinates [point of line] (point on Voronoi edge - intersection) + /// P1 coordinates [point of line] (point on Voronoi edge - intersection) + /// P2 coordinates [point of line] (circumcenter) + /// P2 coordinates [point of line] (circumcenter) + /// P3 coordinates [point to be compared] (neighbor's circumcenter) + /// P3 coordinates [point to be compared] (neighbor's circumcenter) + /// + private void PointBetweenPoints(double x1, double y1, double x2, double y2, double x, double y, ref double[] p) + { + // now check whether the point is close to circumcenter than intersection point + // BETWEEN THE POINTS + if ((x2 - x) * (x2 - x) + (y2 - y) * (y2 - y) < (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) + { + p[0] = 1.0; + // calculate the squared distance to circumcenter + p[1] = (x - x2) * (x - x2) + (y - y2) * (y - y2); + p[2] = x; + p[3] = y; + }// *NOT* BETWEEN THE POINTS + else + { + p[0] = 0.0; + p[1] = 0.0; + p[2] = 0.0; + p[3] = 0.0; + } + } + + /// + /// Given three coordinates of a triangle, tests a triangle to see if it satisfies + /// the minimum and/or maximum angle condition. + /// + /// + /// + /// + /// + /// + /// + /// Returns true, if it is a BAD triangle, returns false if it is a GOOD triangle. + private bool IsBadTriangleAngle(double x1, double y1, double x2, double y2, double x3, double y3) + { + // variables keeping the distance values for the edges + double dxod, dyod, dxda, dyda, dxao, dyao; + double dxod2, dyod2, dxda2, dyda2, dxao2, dyao2; + + double apexlen, orglen, destlen; + double angle; // in order to check minimum angle condition + + double maxangle; // in order to check minimum angle condition + // calculate the side lengths + + dxod = x1 - x2; + dyod = y1 - y2; + dxda = x2 - x3; + dyda = y2 - y3; + dxao = x3 - x1; + dyao = y3 - y1; + // calculate the squares of the side lentghs + dxod2 = dxod * dxod; + dyod2 = dyod * dyod; + dxda2 = dxda * dxda; + dyda2 = dyda * dyda; + dxao2 = dxao * dxao; + dyao2 = dyao * dyao; + + // Find the lengths of the triangle's three edges. + apexlen = dxod2 + dyod2; + orglen = dxda2 + dyda2; + destlen = dxao2 + dyao2; + + // try to find the minimum edge and accordingly the pqr orientation + if ((apexlen < orglen) && (apexlen < destlen)) + { + // Find the square of the cosine of the angle at the apex. + angle = dxda * dxao + dyda * dyao; + angle = angle * angle / (orglen * destlen); + } + else if (orglen < destlen) + { + // Find the square of the cosine of the angle at the origin. + angle = dxod * dxao + dyod * dyao; + angle = angle * angle / (apexlen * destlen); + } + else + { + // Find the square of the cosine of the angle at the destination. + angle = dxod * dxda + dyod * dyda; + angle = angle * angle / (apexlen * orglen); + } + + // try to find the maximum edge and accordingly the pqr orientation + if ((apexlen > orglen) && (apexlen > destlen)) + { + // Find the cosine of the angle at the apex. + maxangle = (orglen + destlen - apexlen) / (2 * Math.Sqrt(orglen * destlen)); + } + else if (orglen > destlen) + { + // Find the cosine of the angle at the origin. + maxangle = (apexlen + destlen - orglen) / (2 * Math.Sqrt(apexlen * destlen)); + } + else + { + // Find the cosine of the angle at the destination. + maxangle = (apexlen + orglen - destlen) / (2 * Math.Sqrt(apexlen * orglen)); + } + + // Check whether the angle is smaller than permitted. + if ((angle > behavior.goodAngle) || (behavior.MaxAngle != 0.00 && maxangle < behavior.maxGoodAngle)) + { + return true;// it is a bad triangle + } + + return false;// it is a good triangle + } + + /// + /// Given the triangulation, and a vertex returns the minimum distance to the + /// vertices of the triangle where the given vertex located. + /// + /// + /// + /// + /// + private double MinDistanceToNeighbor(double newlocX, double newlocY, ref Otri searchtri) + { + Otri horiz = default(Otri); // for search operation + LocateResult intersect = LocateResult.Outside; + Vertex v1, v2, v3, torg, tdest; + double d1, d2, d3, ahead; + //triangle ptr; // Temporary variable used by sym(). + + Point newvertex = new Point(newlocX, newlocY); + + // printf("newvertex %f,%f\n", newvertex[0], newvertex[1]); + // Find the location of the vertex to be inserted. Check if a good + // starting triangle has already been provided by the caller. + // Find a boundary triangle. + //horiz.tri = m.dummytri; + //horiz.orient = 0; + //horiz.symself(); + // Search for a triangle containing 'newvertex'. + // Start searching from the triangle provided by the caller. + // Where are we? + torg = searchtri.Org(); + tdest = searchtri.Dest(); + // Check the starting triangle's vertices. + if ((torg.x == newvertex.x) && (torg.y == newvertex.y)) + { + intersect = LocateResult.OnVertex; + searchtri.Copy(ref horiz); + } + else if ((tdest.x == newvertex.x) && (tdest.y == newvertex.y)) + { + searchtri.Lnext(); + intersect = LocateResult.OnVertex; + searchtri.Copy(ref horiz); + } + else + { + // Orient 'searchtri' to fit the preconditions of calling preciselocate(). + ahead = predicates.CounterClockwise(torg, tdest, newvertex); + if (ahead < 0.0) + { + // Turn around so that 'searchpoint' is to the left of the + // edge specified by 'searchtri'. + searchtri.Sym(); + searchtri.Copy(ref horiz); + intersect = mesh.locator.PreciseLocate(newvertex, ref horiz, false); + } + else if (ahead == 0.0) + { + // Check if 'searchpoint' is between 'torg' and 'tdest'. + if (((torg.x < newvertex.x) == (newvertex.x < tdest.x)) && + ((torg.y < newvertex.y) == (newvertex.y < tdest.y))) + { + intersect = LocateResult.OnEdge; + searchtri.Copy(ref horiz); + } + } + else + { + searchtri.Copy(ref horiz); + intersect = mesh.locator.PreciseLocate(newvertex, ref horiz, false); + } + } + if (intersect == LocateResult.OnVertex || intersect == LocateResult.Outside) + { + // set distance to 0 + //m.VertexDealloc(newvertex); + return 0.0; + } + else + { // intersect == ONEDGE || intersect == INTRIANGLE + // find the triangle vertices + v1 = horiz.Org(); + v2 = horiz.Dest(); + v3 = horiz.Apex(); + d1 = (v1.x - newvertex.x) * (v1.x - newvertex.x) + (v1.y - newvertex.y) * (v1.y - newvertex.y); + d2 = (v2.x - newvertex.x) * (v2.x - newvertex.x) + (v2.y - newvertex.y) * (v2.y - newvertex.y); + d3 = (v3.x - newvertex.x) * (v3.x - newvertex.x) + (v3.y - newvertex.y) * (v3.y - newvertex.y); + //m.VertexDealloc(newvertex); + // find minimum of the distance + if (d1 <= d2 && d1 <= d3) + { + return d1; + } + else if (d2 <= d3) + { + return d2; + } + else + { + return d3; + } + } + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/NewLocation.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/NewLocation.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..9507298ef26f1bdd6e6ed4c6a1041c63fb27fa28 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/NewLocation.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 19387af761aa944a6bda921093ae6d70 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Properties.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Properties.meta new file mode 100644 index 0000000000000000000000000000000000000000..d5da60b21a8a1ead1dd3ca2d6c88a6dbea44090a --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Properties.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 943a851f7cd974d46b9e88ddd1a92567 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/RobustPredicates.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/RobustPredicates.cs new file mode 100644 index 0000000000000000000000000000000000000000..8540f6ab5b3d2ab68ac54fe0aab90b5e5bca9648 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/RobustPredicates.cs @@ -0,0 +1,1347 @@ +// ----------------------------------------------------------------------- +// +// Original Triangle code by Jonathan Richard Shewchuk, http://www.cs.cmu.edu/~quake/triangle.html +// Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/ +// +// ----------------------------------------------------------------------- + +namespace UnityEngine.U2D.Animation.TriangleNet +{ + using System; + using Animation.TriangleNet.Geometry; + using Animation.TriangleNet.Tools; + + /// + /// Adaptive exact arithmetic geometric predicates. + /// + /// + /// The adaptive exact arithmetic geometric predicates implemented herein are described in + /// detail in the paper "Adaptive Precision Floating-Point Arithmetic and Fast Robust + /// Geometric Predicates." by Jonathan Richard Shewchuk, see + /// http://www.cs.cmu.edu/~quake/robust.html + /// + /// The macros of the original C code were automatically expanded using the Visual Studio + /// command prompt with the command "CL /P /C EXACT.C", see + /// http://msdn.microsoft.com/en-us/library/8z9z0bx6.aspx + /// + internal class RobustPredicates : IPredicates + { + #region Default predicates instance (Singleton) + + private static readonly object creationLock = new object(); + private static RobustPredicates _default; + + /// + /// Gets the default configuration instance. + /// + internal static RobustPredicates Default + { + get + { + if (_default == null) + { + lock (creationLock) + { + if (_default == null) + { + _default = new RobustPredicates(); + } + } + } + + return _default; + } + } + + #endregion + + #region Static initialization + + private static double epsilon, splitter, resulterrbound; + private static double ccwerrboundA, ccwerrboundB, ccwerrboundC; + private static double iccerrboundA, iccerrboundB, iccerrboundC; + //private static double o3derrboundA, o3derrboundB, o3derrboundC; + + /// + /// Initialize the variables used for exact arithmetic. + /// + /// + /// 'epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in + /// floating-point arithmetic. 'epsilon' bounds the relative roundoff + /// error. It is used for floating-point error analysis. + /// + /// 'splitter' is used to split floating-point numbers into two half- + /// length significands for exact multiplication. + /// + /// I imagine that a highly optimizing compiler might be too smart for its + /// own good, and somehow cause this routine to fail, if it pretends that + /// floating-point arithmetic is too much like double arithmetic. + /// + /// Don't change this routine unless you fully understand it. + /// + static RobustPredicates() + { + double half; + double check, lastcheck; + bool every_other; + + every_other = true; + half = 0.5; + epsilon = 1.0; + splitter = 1.0; + check = 1.0; + // Repeatedly divide 'epsilon' by two until it is too small to add to + // one without causing roundoff. (Also check if the sum is equal to + // the previous sum, for machines that round up instead of using exact + // rounding. Not that these routines will work on such machines.) + do + { + lastcheck = check; + epsilon *= half; + if (every_other) + { + splitter *= 2.0; + } + every_other = !every_other; + check = 1.0 + epsilon; + } + while ((check != 1.0) && (check != lastcheck)); + splitter += 1.0; + // Error bounds for orientation and incircle tests. + resulterrbound = (3.0 + 8.0 * epsilon) * epsilon; + ccwerrboundA = (3.0 + 16.0 * epsilon) * epsilon; + ccwerrboundB = (2.0 + 12.0 * epsilon) * epsilon; + ccwerrboundC = (9.0 + 64.0 * epsilon) * epsilon * epsilon; + iccerrboundA = (10.0 + 96.0 * epsilon) * epsilon; + iccerrboundB = (4.0 + 48.0 * epsilon) * epsilon; + iccerrboundC = (44.0 + 576.0 * epsilon) * epsilon * epsilon; + //o3derrboundA = (7.0 + 56.0 * epsilon) * epsilon; + //o3derrboundB = (3.0 + 28.0 * epsilon) * epsilon; + //o3derrboundC = (26.0 + 288.0 * epsilon) * epsilon * epsilon; + } + + #endregion + + public RobustPredicates() + { + AllocateWorkspace(); + } + + /// + /// Check, if the three points appear in counterclockwise order. The result is + /// also a rough approximation of twice the signed area of the triangle defined + /// by the three points. + /// + /// Point a. + /// Point b. + /// Point c. + /// Return a positive value if the points pa, pb, and pc occur in + /// counterclockwise order; a negative value if they occur in clockwise order; + /// and zero if they are collinear. + public double CounterClockwise(Point pa, Point pb, Point pc) + { + double detleft, detright, det; + double detsum, errbound; + + Statistic.CounterClockwiseCount++; + + detleft = (pa.x - pc.x) * (pb.y - pc.y); + detright = (pa.y - pc.y) * (pb.x - pc.x); + det = detleft - detright; + + if (Behavior.NoExact) + { + return det; + } + + if (detleft > 0.0) + { + if (detright <= 0.0) + { + return det; + } + else + { + detsum = detleft + detright; + } + } + else if (detleft < 0.0) + { + if (detright >= 0.0) + { + return det; + } + else + { + detsum = -detleft - detright; + } + } + else + { + return det; + } + + errbound = ccwerrboundA * detsum; + if ((det >= errbound) || (-det >= errbound)) + { + return det; + } + + Statistic.CounterClockwiseAdaptCount++; + return CounterClockwiseAdapt(pa, pb, pc, detsum); + } + + /// + /// Check if the point pd lies inside the circle passing through pa, pb, and pc. The + /// points pa, pb, and pc must be in counterclockwise order, or the sign of the result + /// will be reversed. + /// + /// Point a. + /// Point b. + /// Point c. + /// Point d. + /// Return a positive value if the point pd lies inside the circle passing through + /// pa, pb, and pc; a negative value if it lies outside; and zero if the four points + /// are cocircular. + public double InCircle(Point pa, Point pb, Point pc, Point pd) + { + double adx, bdx, cdx, ady, bdy, cdy; + double bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady; + double alift, blift, clift; + double det; + double permanent, errbound; + + Statistic.InCircleCount++; + + adx = pa.x - pd.x; + bdx = pb.x - pd.x; + cdx = pc.x - pd.x; + ady = pa.y - pd.y; + bdy = pb.y - pd.y; + cdy = pc.y - pd.y; + + bdxcdy = bdx * cdy; + cdxbdy = cdx * bdy; + alift = adx * adx + ady * ady; + + cdxady = cdx * ady; + adxcdy = adx * cdy; + blift = bdx * bdx + bdy * bdy; + + adxbdy = adx * bdy; + bdxady = bdx * ady; + clift = cdx * cdx + cdy * cdy; + + det = alift * (bdxcdy - cdxbdy) + + blift * (cdxady - adxcdy) + + clift * (adxbdy - bdxady); + + if (Behavior.NoExact) + { + return det; + } + + permanent = (Math.Abs(bdxcdy) + Math.Abs(cdxbdy)) * alift + + (Math.Abs(cdxady) + Math.Abs(adxcdy)) * blift + + (Math.Abs(adxbdy) + Math.Abs(bdxady)) * clift; + errbound = iccerrboundA * permanent; + if ((det > errbound) || (-det > errbound)) + { + return det; + } + + Statistic.InCircleAdaptCount++; + return InCircleAdapt(pa, pb, pc, pd, permanent); + } + + /// + /// Return a positive value if the point pd is incompatible with the circle + /// or plane passing through pa, pb, and pc (meaning that pd is inside the + /// circle or below the plane); a negative value if it is compatible; and + /// zero if the four points are cocircular/coplanar. The points pa, pb, and + /// pc must be in counterclockwise order, or the sign of the result will be + /// reversed. + /// + /// Point a. + /// Point b. + /// Point c. + /// Point d. + /// Return a positive value if the point pd lies inside the circle passing through + /// pa, pb, and pc; a negative value if it lies outside; and zero if the four points + /// are cocircular. + public double NonRegular(Point pa, Point pb, Point pc, Point pd) + { + return InCircle(pa, pb, pc, pd); + } + + /// + /// Find the circumcenter of a triangle. + /// + /// Triangle point. + /// Triangle point. + /// Triangle point. + /// Relative coordinate of new location. + /// Relative coordinate of new location. + /// Off-center constant. + /// Coordinates of the circumcenter (or off-center) + public Point FindCircumcenter(Point org, Point dest, Point apex, + ref double xi, ref double eta, double offconstant) + { + double xdo, ydo, xao, yao; + double dodist, aodist, dadist; + double denominator; + double dx, dy, dxoff, dyoff; + + Statistic.CircumcenterCount++; + + // Compute the circumcenter of the triangle. + xdo = dest.x - org.x; + ydo = dest.y - org.y; + xao = apex.x - org.x; + yao = apex.y - org.y; + dodist = xdo * xdo + ydo * ydo; + aodist = xao * xao + yao * yao; + dadist = (dest.x - apex.x) * (dest.x - apex.x) + + (dest.y - apex.y) * (dest.y - apex.y); + + if (Behavior.NoExact) + { + denominator = 0.5 / (xdo * yao - xao * ydo); + } + else + { + // Use the counterclockwise() routine to ensure a positive (and + // reasonably accurate) result, avoiding any possibility of + // division by zero. + denominator = 0.5 / CounterClockwise(dest, apex, org); + // Don't count the above as an orientation test. + Statistic.CounterClockwiseCount--; + } + + dx = (yao * dodist - ydo * aodist) * denominator; + dy = (xdo * aodist - xao * dodist) * denominator; + + // Find the (squared) length of the triangle's shortest edge. This + // serves as a conservative estimate of the insertion radius of the + // circumcenter's parent. The estimate is used to ensure that + // the algorithm terminates even if very small angles appear in + // the input PSLG. + if ((dodist < aodist) && (dodist < dadist)) + { + if (offconstant > 0.0) + { + // Find the position of the off-center, as described by Alper Ungor. + dxoff = 0.5 * xdo - offconstant * ydo; + dyoff = 0.5 * ydo + offconstant * xdo; + // If the off-center is closer to the origin than the + // circumcenter, use the off-center instead. + if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) + { + dx = dxoff; + dy = dyoff; + } + } + } + else if (aodist < dadist) + { + if (offconstant > 0.0) + { + dxoff = 0.5 * xao + offconstant * yao; + dyoff = 0.5 * yao - offconstant * xao; + // If the off-center is closer to the origin than the + // circumcenter, use the off-center instead. + if (dxoff * dxoff + dyoff * dyoff < dx * dx + dy * dy) + { + dx = dxoff; + dy = dyoff; + } + } + } + else + { + if (offconstant > 0.0) + { + dxoff = 0.5 * (apex.x - dest.x) - offconstant * (apex.y - dest.y); + dyoff = 0.5 * (apex.y - dest.y) + offconstant * (apex.x - dest.x); + // If the off-center is closer to the destination than the + // circumcenter, use the off-center instead. + if (dxoff * dxoff + dyoff * dyoff < + (dx - xdo) * (dx - xdo) + (dy - ydo) * (dy - ydo)) + { + dx = xdo + dxoff; + dy = ydo + dyoff; + } + } + } + + // To interpolate vertex attributes for the new vertex inserted at + // the circumcenter, define a coordinate system with a xi-axis, + // directed from the triangle's origin to its destination, and + // an eta-axis, directed from its origin to its apex. + // Calculate the xi and eta coordinates of the circumcenter. + xi = (yao * dx - xao * dy) * (2.0 * denominator); + eta = (xdo * dy - ydo * dx) * (2.0 * denominator); + + return new Point(org.x + dx, org.y + dy); + } + + /// + /// Find the circumcenter of a triangle. + /// + /// Triangle point. + /// Triangle point. + /// Triangle point. + /// Relative coordinate of new location. + /// Relative coordinate of new location. + /// Coordinates of the circumcenter + /// + /// The result is returned both in terms of x-y coordinates and xi-eta + /// (barycentric) coordinates. The xi-eta coordinate system is defined in + /// terms of the triangle: the origin of the triangle is the origin of the + /// coordinate system; the destination of the triangle is one unit along the + /// xi axis; and the apex of the triangle is one unit along the eta axis. + /// This procedure also returns the square of the length of the triangle's + /// shortest edge. + /// + public Point FindCircumcenter(Point org, Point dest, Point apex, + ref double xi, ref double eta) + { + double xdo, ydo, xao, yao; + double dodist, aodist; + double denominator; + double dx, dy; + + Statistic.CircumcenterCount++; + + // Compute the circumcenter of the triangle. + xdo = dest.x - org.x; + ydo = dest.y - org.y; + xao = apex.x - org.x; + yao = apex.y - org.y; + dodist = xdo * xdo + ydo * ydo; + aodist = xao * xao + yao * yao; + + if (Behavior.NoExact) + { + denominator = 0.5 / (xdo * yao - xao * ydo); + } + else + { + // Use the counterclockwise() routine to ensure a positive (and + // reasonably accurate) result, avoiding any possibility of + // division by zero. + denominator = 0.5 / CounterClockwise(dest, apex, org); + // Don't count the above as an orientation test. + Statistic.CounterClockwiseCount--; + } + + dx = (yao * dodist - ydo * aodist) * denominator; + dy = (xdo * aodist - xao * dodist) * denominator; + + // To interpolate vertex attributes for the new vertex inserted at + // the circumcenter, define a coordinate system with a xi-axis, + // directed from the triangle's origin to its destination, and + // an eta-axis, directed from its origin to its apex. + // Calculate the xi and eta coordinates of the circumcenter. + xi = (yao * dx - xao * dy) * (2.0 * denominator); + eta = (xdo * dy - ydo * dx) * (2.0 * denominator); + + return new Point(org.x + dx, org.y + dy); + } + + #region Exact arithmetics + + /// + /// Sum two expansions, eliminating zero components from the output expansion. + /// + /// + /// + /// + /// + /// + /// + /// + /// Sets h = e + f. See the Robust Predicates paper for details. + /// + /// If round-to-even is used (as with IEEE 754), maintains the strongly nonoverlapping + /// property. (That is, if e is strongly nonoverlapping, h will be also.) Does NOT + /// maintain the nonoverlapping or nonadjacent properties. + /// + private int FastExpansionSumZeroElim(int elen, double[] e, int flen, double[] f, double[] h) + { + double Q; + double Qnew; + double hh; + double bvirt; + double avirt, bround, around; + int eindex, findex, hindex; + double enow, fnow; + + enow = e[0]; + fnow = f[0]; + eindex = findex = 0; + if ((fnow > enow) == (fnow > -enow)) + { + Q = enow; + enow = e[++eindex]; + } + else + { + Q = fnow; + fnow = f[++findex]; + } + hindex = 0; + if ((eindex < elen) && (findex < flen)) + { + if ((fnow > enow) == (fnow > -enow)) + { + Qnew = (double)(enow + Q); bvirt = Qnew - enow; hh = Q - bvirt; + enow = e[++eindex]; + } + else + { + Qnew = (double)(fnow + Q); bvirt = Qnew - fnow; hh = Q - bvirt; + fnow = f[++findex]; + } + Q = Qnew; + if (hh != 0.0) + { + h[hindex++] = hh; + } + while ((eindex < elen) && (findex < flen)) + { + if ((fnow > enow) == (fnow > -enow)) + { + Qnew = (double)(Q + enow); + bvirt = (double)(Qnew - Q); + avirt = Qnew - bvirt; + bround = enow - bvirt; + around = Q - avirt; + hh = around + bround; + + enow = e[++eindex]; + } + else + { + Qnew = (double)(Q + fnow); + bvirt = (double)(Qnew - Q); + avirt = Qnew - bvirt; + bround = fnow - bvirt; + around = Q - avirt; + hh = around + bround; + + fnow = f[++findex]; + } + Q = Qnew; + if (hh != 0.0) + { + h[hindex++] = hh; + } + } + } + while (eindex < elen) + { + Qnew = (double)(Q + enow); + bvirt = (double)(Qnew - Q); + avirt = Qnew - bvirt; + bround = enow - bvirt; + around = Q - avirt; + hh = around + bround; + + enow = e[++eindex]; + Q = Qnew; + if (hh != 0.0) + { + h[hindex++] = hh; + } + } + while (findex < flen) + { + Qnew = (double)(Q + fnow); + bvirt = (double)(Qnew - Q); + avirt = Qnew - bvirt; + bround = fnow - bvirt; + around = Q - avirt; + hh = around + bround; + + fnow = f[++findex]; + Q = Qnew; + if (hh != 0.0) + { + h[hindex++] = hh; + } + } + if ((Q != 0.0) || (hindex == 0)) + { + h[hindex++] = Q; + } + return hindex; + } + + /// + /// Multiply an expansion by a scalar, eliminating zero components from the output expansion. + /// + /// + /// + /// + /// + /// + /// + /// Sets h = be. See my Robust Predicates paper for details. + /// + /// Maintains the nonoverlapping property. If round-to-even is used (as with IEEE 754), + /// maintains the strongly nonoverlapping and nonadjacent properties as well. (That is, + /// if e has one of these properties, so will h.) + /// + private int ScaleExpansionZeroElim(int elen, double[] e, double b, double[] h) + { + double Q, sum; + double hh; + double product1; + double product0; + int eindex, hindex; + double enow; + double bvirt; + double avirt, bround, around; + double c; + double abig; + double ahi, alo, bhi, blo; + double err1, err2, err3; + + c = (double)(splitter * b); abig = (double)(c - b); bhi = c - abig; blo = b - bhi; + Q = (double)(e[0] * b); c = (double)(splitter * e[0]); abig = (double)(c - e[0]); ahi = c - abig; alo = e[0] - ahi; err1 = Q - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); hh = (alo * blo) - err3; + hindex = 0; + if (hh != 0) + { + h[hindex++] = hh; + } + for (eindex = 1; eindex < elen; eindex++) + { + enow = e[eindex]; + product1 = (double)(enow * b); c = (double)(splitter * enow); abig = (double)(c - enow); ahi = c - abig; alo = enow - ahi; err1 = product1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); product0 = (alo * blo) - err3; + sum = (double)(Q + product0); bvirt = (double)(sum - Q); avirt = sum - bvirt; bround = product0 - bvirt; around = Q - avirt; hh = around + bround; + if (hh != 0) + { + h[hindex++] = hh; + } + Q = (double)(product1 + sum); bvirt = Q - product1; hh = sum - bvirt; + if (hh != 0) + { + h[hindex++] = hh; + } + } + if ((Q != 0.0) || (hindex == 0)) + { + h[hindex++] = Q; + } + return hindex; + } + + /// + /// Produce a one-word estimate of an expansion's value. + /// + /// + /// + /// + private double Estimate(int elen, double[] e) + { + double Q; + int eindex; + + Q = e[0]; + for (eindex = 1; eindex < elen; eindex++) + { + Q += e[eindex]; + } + return Q; + } + + /// + /// Return a positive value if the points pa, pb, and pc occur in counterclockwise + /// order; a negative value if they occur in clockwise order; and zero if they are + /// collinear. The result is also a rough approximation of twice the signed area of + /// the triangle defined by the three points. + /// + /// + /// + /// + /// + /// + /// + /// Uses exact arithmetic if necessary to ensure a correct answer. The result returned + /// is the determinant of a matrix. This determinant is computed adaptively, in the + /// sense that exact arithmetic is used only to the degree it is needed to ensure that + /// the returned value has the correct sign. Hence, this function is usually quite fast, + /// but will run more slowly when the input points are collinear or nearly so. + /// + private double CounterClockwiseAdapt(Point pa, Point pb, Point pc, double detsum) + { + double acx, acy, bcx, bcy; + double acxtail, acytail, bcxtail, bcytail; + double detleft, detright; + double detlefttail, detrighttail; + double det, errbound; + // Edited to work around index out of range exceptions (changed array length from 4 to 5). + // See unsafe indexing in FastExpansionSumZeroElim. + double[] B = new double[5], u = new double[5]; + double[] C1 = new double[8], C2 = new double[12], D = new double[16]; + double B3; + int C1length, C2length, Dlength; + + double u3; + double s1, t1; + double s0, t0; + + double bvirt; + double avirt, bround, around; + double c; + double abig; + double ahi, alo, bhi, blo; + double err1, err2, err3; + double _i, _j; + double _0; + + acx = (double)(pa.x - pc.x); + bcx = (double)(pb.x - pc.x); + acy = (double)(pa.y - pc.y); + bcy = (double)(pb.y - pc.y); + + detleft = (double)(acx * bcy); c = (double)(splitter * acx); abig = (double)(c - acx); ahi = c - abig; alo = acx - ahi; c = (double)(splitter * bcy); abig = (double)(c - bcy); bhi = c - abig; blo = bcy - bhi; err1 = detleft - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); detlefttail = (alo * blo) - err3; + detright = (double)(acy * bcx); c = (double)(splitter * acy); abig = (double)(c - acy); ahi = c - abig; alo = acy - ahi; c = (double)(splitter * bcx); abig = (double)(c - bcx); bhi = c - abig; blo = bcx - bhi; err1 = detright - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); detrighttail = (alo * blo) - err3; + + _i = (double)(detlefttail - detrighttail); bvirt = (double)(detlefttail - _i); avirt = _i + bvirt; bround = bvirt - detrighttail; around = detlefttail - avirt; B[0] = around + bround; _j = (double)(detleft + _i); bvirt = (double)(_j - detleft); avirt = _j - bvirt; bround = _i - bvirt; around = detleft - avirt; _0 = around + bround; _i = (double)(_0 - detright); bvirt = (double)(_0 - _i); avirt = _i + bvirt; bround = bvirt - detright; around = _0 - avirt; B[1] = around + bround; B3 = (double)(_j + _i); bvirt = (double)(B3 - _j); avirt = B3 - bvirt; bround = _i - bvirt; around = _j - avirt; B[2] = around + bround; + + B[3] = B3; + + det = Estimate(4, B); + errbound = ccwerrboundB * detsum; + if ((det >= errbound) || (-det >= errbound)) + { + return det; + } + + bvirt = (double)(pa.x - acx); avirt = acx + bvirt; bround = bvirt - pc.x; around = pa.x - avirt; acxtail = around + bround; + bvirt = (double)(pb.x - bcx); avirt = bcx + bvirt; bround = bvirt - pc.x; around = pb.x - avirt; bcxtail = around + bround; + bvirt = (double)(pa.y - acy); avirt = acy + bvirt; bround = bvirt - pc.y; around = pa.y - avirt; acytail = around + bround; + bvirt = (double)(pb.y - bcy); avirt = bcy + bvirt; bround = bvirt - pc.y; around = pb.y - avirt; bcytail = around + bround; + + if ((acxtail == 0.0) && (acytail == 0.0) + && (bcxtail == 0.0) && (bcytail == 0.0)) + { + return det; + } + + errbound = ccwerrboundC * detsum + resulterrbound * ((det) >= 0.0 ? (det) : -(det)); + det += (acx * bcytail + bcy * acxtail) + - (acy * bcxtail + bcx * acytail); + if ((det >= errbound) || (-det >= errbound)) + { + return det; + } + + s1 = (double)(acxtail * bcy); c = (double)(splitter * acxtail); abig = (double)(c - acxtail); ahi = c - abig; alo = acxtail - ahi; c = (double)(splitter * bcy); abig = (double)(c - bcy); bhi = c - abig; blo = bcy - bhi; err1 = s1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); s0 = (alo * blo) - err3; + t1 = (double)(acytail * bcx); c = (double)(splitter * acytail); abig = (double)(c - acytail); ahi = c - abig; alo = acytail - ahi; c = (double)(splitter * bcx); abig = (double)(c - bcx); bhi = c - abig; blo = bcx - bhi; err1 = t1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); t0 = (alo * blo) - err3; + _i = (double)(s0 - t0); bvirt = (double)(s0 - _i); avirt = _i + bvirt; bround = bvirt - t0; around = s0 - avirt; u[0] = around + bround; _j = (double)(s1 + _i); bvirt = (double)(_j - s1); avirt = _j - bvirt; bround = _i - bvirt; around = s1 - avirt; _0 = around + bround; _i = (double)(_0 - t1); bvirt = (double)(_0 - _i); avirt = _i + bvirt; bround = bvirt - t1; around = _0 - avirt; u[1] = around + bround; u3 = (double)(_j + _i); bvirt = (double)(u3 - _j); avirt = u3 - bvirt; bround = _i - bvirt; around = _j - avirt; u[2] = around + bround; + u[3] = u3; + C1length = FastExpansionSumZeroElim(4, B, 4, u, C1); + + s1 = (double)(acx * bcytail); c = (double)(splitter * acx); abig = (double)(c - acx); ahi = c - abig; alo = acx - ahi; c = (double)(splitter * bcytail); abig = (double)(c - bcytail); bhi = c - abig; blo = bcytail - bhi; err1 = s1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); s0 = (alo * blo) - err3; + t1 = (double)(acy * bcxtail); c = (double)(splitter * acy); abig = (double)(c - acy); ahi = c - abig; alo = acy - ahi; c = (double)(splitter * bcxtail); abig = (double)(c - bcxtail); bhi = c - abig; blo = bcxtail - bhi; err1 = t1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); t0 = (alo * blo) - err3; + _i = (double)(s0 - t0); bvirt = (double)(s0 - _i); avirt = _i + bvirt; bround = bvirt - t0; around = s0 - avirt; u[0] = around + bround; _j = (double)(s1 + _i); bvirt = (double)(_j - s1); avirt = _j - bvirt; bround = _i - bvirt; around = s1 - avirt; _0 = around + bround; _i = (double)(_0 - t1); bvirt = (double)(_0 - _i); avirt = _i + bvirt; bround = bvirt - t1; around = _0 - avirt; u[1] = around + bround; u3 = (double)(_j + _i); bvirt = (double)(u3 - _j); avirt = u3 - bvirt; bround = _i - bvirt; around = _j - avirt; u[2] = around + bround; + u[3] = u3; + C2length = FastExpansionSumZeroElim(C1length, C1, 4, u, C2); + + s1 = (double)(acxtail * bcytail); c = (double)(splitter * acxtail); abig = (double)(c - acxtail); ahi = c - abig; alo = acxtail - ahi; c = (double)(splitter * bcytail); abig = (double)(c - bcytail); bhi = c - abig; blo = bcytail - bhi; err1 = s1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); s0 = (alo * blo) - err3; + t1 = (double)(acytail * bcxtail); c = (double)(splitter * acytail); abig = (double)(c - acytail); ahi = c - abig; alo = acytail - ahi; c = (double)(splitter * bcxtail); abig = (double)(c - bcxtail); bhi = c - abig; blo = bcxtail - bhi; err1 = t1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); t0 = (alo * blo) - err3; + _i = (double)(s0 - t0); bvirt = (double)(s0 - _i); avirt = _i + bvirt; bround = bvirt - t0; around = s0 - avirt; u[0] = around + bround; _j = (double)(s1 + _i); bvirt = (double)(_j - s1); avirt = _j - bvirt; bround = _i - bvirt; around = s1 - avirt; _0 = around + bround; _i = (double)(_0 - t1); bvirt = (double)(_0 - _i); avirt = _i + bvirt; bround = bvirt - t1; around = _0 - avirt; u[1] = around + bround; u3 = (double)(_j + _i); bvirt = (double)(u3 - _j); avirt = u3 - bvirt; bround = _i - bvirt; around = _j - avirt; u[2] = around + bround; + u[3] = u3; + Dlength = FastExpansionSumZeroElim(C2length, C2, 4, u, D); + + return (D[Dlength - 1]); + } + + /// + /// Return a positive value if the point pd lies inside the circle passing through + /// pa, pb, and pc; a negative value if it lies outside; and zero if the four points + /// are cocircular. The points pa, pb, and pc must be in counterclockwise order, or + /// the sign of the result will be reversed. + /// + /// + /// + /// + /// + /// + /// + /// + /// Uses exact arithmetic if necessary to ensure a correct answer. The result returned + /// is the determinant of a matrix. This determinant is computed adaptively, in the + /// sense that exact arithmetic is used only to the degree it is needed to ensure that + /// the returned value has the correct sign. Hence, this function is usually quite fast, + /// but will run more slowly when the input points are cocircular or nearly so. + /// + private double InCircleAdapt(Point pa, Point pb, Point pc, Point pd, double permanent) + { + double adx, bdx, cdx, ady, bdy, cdy; + double det, errbound; + + double bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1; + double bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0; + double[] bc = new double[4], ca = new double[4], ab = new double[4]; + double bc3, ca3, ab3; + int axbclen, axxbclen, aybclen, ayybclen, alen; + int bxcalen, bxxcalen, bycalen, byycalen, blen; + int cxablen, cxxablen, cyablen, cyyablen, clen; + int ablen; + double[] finnow, finother, finswap; + int finlength; + + double adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail; + double adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1; + double adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0; + double[] aa = new double[4], bb = new double[4], cc = new double[4]; + double aa3, bb3, cc3; + double ti1, tj1; + double ti0, tj0; + // Edited to work around index out of range exceptions (changed array length from 4 to 5). + // See unsafe indexing in FastExpansionSumZeroElim. + double[] u = new double[5], v = new double[5]; + double u3, v3; + int temp8len, temp16alen, temp16blen, temp16clen; + int temp32alen, temp32blen, temp48len, temp64len; + double[] axtbb = new double[8], axtcc = new double[8], aytbb = new double[8], aytcc = new double[8]; + int axtbblen, axtcclen, aytbblen, aytcclen; + double[] bxtaa = new double[8], bxtcc = new double[8], bytaa = new double[8], bytcc = new double[8]; + int bxtaalen, bxtcclen, bytaalen, bytcclen; + double[] cxtaa = new double[8], cxtbb = new double[8], cytaa = new double[8], cytbb = new double[8]; + int cxtaalen, cxtbblen, cytaalen, cytbblen; + double[] axtbc = new double[8], aytbc = new double[8], bxtca = new double[8], bytca = new double[8], cxtab = new double[8], cytab = new double[8]; + int axtbclen = 0, aytbclen = 0, bxtcalen = 0, bytcalen = 0, cxtablen = 0, cytablen = 0; + double[] axtbct = new double[16], aytbct = new double[16], bxtcat = new double[16], bytcat = new double[16], cxtabt = new double[16], cytabt = new double[16]; + int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen; + double[] axtbctt = new double[8], aytbctt = new double[8], bxtcatt = new double[8]; + double[] bytcatt = new double[8], cxtabtt = new double[8], cytabtt = new double[8]; + int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen; + double[] abt = new double[8], bct = new double[8], cat = new double[8]; + int abtlen, bctlen, catlen; + double[] abtt = new double[4], bctt = new double[4], catt = new double[4]; + int abttlen, bcttlen, cattlen; + double abtt3, bctt3, catt3; + double negate; + + double bvirt; + double avirt, bround, around; + double c; + double abig; + double ahi, alo, bhi, blo; + double err1, err2, err3; + double _i, _j; + double _0; + + adx = (double)(pa.x - pd.x); + bdx = (double)(pb.x - pd.x); + cdx = (double)(pc.x - pd.x); + ady = (double)(pa.y - pd.y); + bdy = (double)(pb.y - pd.y); + cdy = (double)(pc.y - pd.y); + + adx = (double)(pa.x - pd.x); + bdx = (double)(pb.x - pd.x); + cdx = (double)(pc.x - pd.x); + ady = (double)(pa.y - pd.y); + bdy = (double)(pb.y - pd.y); + cdy = (double)(pc.y - pd.y); + + bdxcdy1 = (double)(bdx * cdy); c = (double)(splitter * bdx); abig = (double)(c - bdx); ahi = c - abig; alo = bdx - ahi; c = (double)(splitter * cdy); abig = (double)(c - cdy); bhi = c - abig; blo = cdy - bhi; err1 = bdxcdy1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); bdxcdy0 = (alo * blo) - err3; + cdxbdy1 = (double)(cdx * bdy); c = (double)(splitter * cdx); abig = (double)(c - cdx); ahi = c - abig; alo = cdx - ahi; c = (double)(splitter * bdy); abig = (double)(c - bdy); bhi = c - abig; blo = bdy - bhi; err1 = cdxbdy1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); cdxbdy0 = (alo * blo) - err3; + _i = (double)(bdxcdy0 - cdxbdy0); bvirt = (double)(bdxcdy0 - _i); avirt = _i + bvirt; bround = bvirt - cdxbdy0; around = bdxcdy0 - avirt; bc[0] = around + bround; _j = (double)(bdxcdy1 + _i); bvirt = (double)(_j - bdxcdy1); avirt = _j - bvirt; bround = _i - bvirt; around = bdxcdy1 - avirt; _0 = around + bround; _i = (double)(_0 - cdxbdy1); bvirt = (double)(_0 - _i); avirt = _i + bvirt; bround = bvirt - cdxbdy1; around = _0 - avirt; bc[1] = around + bround; bc3 = (double)(_j + _i); bvirt = (double)(bc3 - _j); avirt = bc3 - bvirt; bround = _i - bvirt; around = _j - avirt; bc[2] = around + bround; + bc[3] = bc3; + axbclen = ScaleExpansionZeroElim(4, bc, adx, axbc); + axxbclen = ScaleExpansionZeroElim(axbclen, axbc, adx, axxbc); + aybclen = ScaleExpansionZeroElim(4, bc, ady, aybc); + ayybclen = ScaleExpansionZeroElim(aybclen, aybc, ady, ayybc); + alen = FastExpansionSumZeroElim(axxbclen, axxbc, ayybclen, ayybc, adet); + + cdxady1 = (double)(cdx * ady); c = (double)(splitter * cdx); abig = (double)(c - cdx); ahi = c - abig; alo = cdx - ahi; c = (double)(splitter * ady); abig = (double)(c - ady); bhi = c - abig; blo = ady - bhi; err1 = cdxady1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); cdxady0 = (alo * blo) - err3; + adxcdy1 = (double)(adx * cdy); c = (double)(splitter * adx); abig = (double)(c - adx); ahi = c - abig; alo = adx - ahi; c = (double)(splitter * cdy); abig = (double)(c - cdy); bhi = c - abig; blo = cdy - bhi; err1 = adxcdy1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); adxcdy0 = (alo * blo) - err3; + _i = (double)(cdxady0 - adxcdy0); bvirt = (double)(cdxady0 - _i); avirt = _i + bvirt; bround = bvirt - adxcdy0; around = cdxady0 - avirt; ca[0] = around + bround; _j = (double)(cdxady1 + _i); bvirt = (double)(_j - cdxady1); avirt = _j - bvirt; bround = _i - bvirt; around = cdxady1 - avirt; _0 = around + bround; _i = (double)(_0 - adxcdy1); bvirt = (double)(_0 - _i); avirt = _i + bvirt; bround = bvirt - adxcdy1; around = _0 - avirt; ca[1] = around + bround; ca3 = (double)(_j + _i); bvirt = (double)(ca3 - _j); avirt = ca3 - bvirt; bround = _i - bvirt; around = _j - avirt; ca[2] = around + bround; + ca[3] = ca3; + bxcalen = ScaleExpansionZeroElim(4, ca, bdx, bxca); + bxxcalen = ScaleExpansionZeroElim(bxcalen, bxca, bdx, bxxca); + bycalen = ScaleExpansionZeroElim(4, ca, bdy, byca); + byycalen = ScaleExpansionZeroElim(bycalen, byca, bdy, byyca); + blen = FastExpansionSumZeroElim(bxxcalen, bxxca, byycalen, byyca, bdet); + + adxbdy1 = (double)(adx * bdy); c = (double)(splitter * adx); abig = (double)(c - adx); ahi = c - abig; alo = adx - ahi; c = (double)(splitter * bdy); abig = (double)(c - bdy); bhi = c - abig; blo = bdy - bhi; err1 = adxbdy1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); adxbdy0 = (alo * blo) - err3; + bdxady1 = (double)(bdx * ady); c = (double)(splitter * bdx); abig = (double)(c - bdx); ahi = c - abig; alo = bdx - ahi; c = (double)(splitter * ady); abig = (double)(c - ady); bhi = c - abig; blo = ady - bhi; err1 = bdxady1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); bdxady0 = (alo * blo) - err3; + _i = (double)(adxbdy0 - bdxady0); bvirt = (double)(adxbdy0 - _i); avirt = _i + bvirt; bround = bvirt - bdxady0; around = adxbdy0 - avirt; ab[0] = around + bround; _j = (double)(adxbdy1 + _i); bvirt = (double)(_j - adxbdy1); avirt = _j - bvirt; bround = _i - bvirt; around = adxbdy1 - avirt; _0 = around + bround; _i = (double)(_0 - bdxady1); bvirt = (double)(_0 - _i); avirt = _i + bvirt; bround = bvirt - bdxady1; around = _0 - avirt; ab[1] = around + bround; ab3 = (double)(_j + _i); bvirt = (double)(ab3 - _j); avirt = ab3 - bvirt; bround = _i - bvirt; around = _j - avirt; ab[2] = around + bround; + ab[3] = ab3; + cxablen = ScaleExpansionZeroElim(4, ab, cdx, cxab); + cxxablen = ScaleExpansionZeroElim(cxablen, cxab, cdx, cxxab); + cyablen = ScaleExpansionZeroElim(4, ab, cdy, cyab); + cyyablen = ScaleExpansionZeroElim(cyablen, cyab, cdy, cyyab); + clen = FastExpansionSumZeroElim(cxxablen, cxxab, cyyablen, cyyab, cdet); + + ablen = FastExpansionSumZeroElim(alen, adet, blen, bdet, abdet); + finlength = FastExpansionSumZeroElim(ablen, abdet, clen, cdet, fin1); + + det = Estimate(finlength, fin1); + errbound = iccerrboundB * permanent; + if ((det >= errbound) || (-det >= errbound)) + { + return det; + } + + bvirt = (double)(pa.x - adx); avirt = adx + bvirt; bround = bvirt - pd.x; around = pa.x - avirt; adxtail = around + bround; + bvirt = (double)(pa.y - ady); avirt = ady + bvirt; bround = bvirt - pd.y; around = pa.y - avirt; adytail = around + bround; + bvirt = (double)(pb.x - bdx); avirt = bdx + bvirt; bround = bvirt - pd.x; around = pb.x - avirt; bdxtail = around + bround; + bvirt = (double)(pb.y - bdy); avirt = bdy + bvirt; bround = bvirt - pd.y; around = pb.y - avirt; bdytail = around + bround; + bvirt = (double)(pc.x - cdx); avirt = cdx + bvirt; bround = bvirt - pd.x; around = pc.x - avirt; cdxtail = around + bround; + bvirt = (double)(pc.y - cdy); avirt = cdy + bvirt; bround = bvirt - pd.y; around = pc.y - avirt; cdytail = around + bround; + if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0) + && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) + { + return det; + } + + errbound = iccerrboundC * permanent + resulterrbound * ((det) >= 0.0 ? (det) : -(det)); + det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail) - (bdy * cdxtail + cdx * bdytail)) + + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx)) + + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail) - (cdy * adxtail + adx * cdytail)) + + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx)) + + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail) - (ady * bdxtail + bdx * adytail)) + + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx)); + if ((det >= errbound) || (-det >= errbound)) + { + return det; + } + + finnow = fin1; + finother = fin2; + + if ((bdxtail != 0.0) || (bdytail != 0.0) || (cdxtail != 0.0) || (cdytail != 0.0)) + { + adxadx1 = (double)(adx * adx); c = (double)(splitter * adx); abig = (double)(c - adx); ahi = c - abig; alo = adx - ahi; err1 = adxadx1 - (ahi * ahi); err3 = err1 - ((ahi + ahi) * alo); adxadx0 = (alo * alo) - err3; + adyady1 = (double)(ady * ady); c = (double)(splitter * ady); abig = (double)(c - ady); ahi = c - abig; alo = ady - ahi; err1 = adyady1 - (ahi * ahi); err3 = err1 - ((ahi + ahi) * alo); adyady0 = (alo * alo) - err3; + _i = (double)(adxadx0 + adyady0); bvirt = (double)(_i - adxadx0); avirt = _i - bvirt; bround = adyady0 - bvirt; around = adxadx0 - avirt; aa[0] = around + bround; _j = (double)(adxadx1 + _i); bvirt = (double)(_j - adxadx1); avirt = _j - bvirt; bround = _i - bvirt; around = adxadx1 - avirt; _0 = around + bround; _i = (double)(_0 + adyady1); bvirt = (double)(_i - _0); avirt = _i - bvirt; bround = adyady1 - bvirt; around = _0 - avirt; aa[1] = around + bround; aa3 = (double)(_j + _i); bvirt = (double)(aa3 - _j); avirt = aa3 - bvirt; bround = _i - bvirt; around = _j - avirt; aa[2] = around + bround; + aa[3] = aa3; + } + if ((cdxtail != 0.0) || (cdytail != 0.0) || (adxtail != 0.0) || (adytail != 0.0)) + { + bdxbdx1 = (double)(bdx * bdx); c = (double)(splitter * bdx); abig = (double)(c - bdx); ahi = c - abig; alo = bdx - ahi; err1 = bdxbdx1 - (ahi * ahi); err3 = err1 - ((ahi + ahi) * alo); bdxbdx0 = (alo * alo) - err3; + bdybdy1 = (double)(bdy * bdy); c = (double)(splitter * bdy); abig = (double)(c - bdy); ahi = c - abig; alo = bdy - ahi; err1 = bdybdy1 - (ahi * ahi); err3 = err1 - ((ahi + ahi) * alo); bdybdy0 = (alo * alo) - err3; + _i = (double)(bdxbdx0 + bdybdy0); bvirt = (double)(_i - bdxbdx0); avirt = _i - bvirt; bround = bdybdy0 - bvirt; around = bdxbdx0 - avirt; bb[0] = around + bround; _j = (double)(bdxbdx1 + _i); bvirt = (double)(_j - bdxbdx1); avirt = _j - bvirt; bround = _i - bvirt; around = bdxbdx1 - avirt; _0 = around + bround; _i = (double)(_0 + bdybdy1); bvirt = (double)(_i - _0); avirt = _i - bvirt; bround = bdybdy1 - bvirt; around = _0 - avirt; bb[1] = around + bround; bb3 = (double)(_j + _i); bvirt = (double)(bb3 - _j); avirt = bb3 - bvirt; bround = _i - bvirt; around = _j - avirt; bb[2] = around + bround; + bb[3] = bb3; + } + if ((adxtail != 0.0) || (adytail != 0.0) || (bdxtail != 0.0) || (bdytail != 0.0)) + { + cdxcdx1 = (double)(cdx * cdx); c = (double)(splitter * cdx); abig = (double)(c - cdx); ahi = c - abig; alo = cdx - ahi; err1 = cdxcdx1 - (ahi * ahi); err3 = err1 - ((ahi + ahi) * alo); cdxcdx0 = (alo * alo) - err3; + cdycdy1 = (double)(cdy * cdy); c = (double)(splitter * cdy); abig = (double)(c - cdy); ahi = c - abig; alo = cdy - ahi; err1 = cdycdy1 - (ahi * ahi); err3 = err1 - ((ahi + ahi) * alo); cdycdy0 = (alo * alo) - err3; + _i = (double)(cdxcdx0 + cdycdy0); bvirt = (double)(_i - cdxcdx0); avirt = _i - bvirt; bround = cdycdy0 - bvirt; around = cdxcdx0 - avirt; cc[0] = around + bround; _j = (double)(cdxcdx1 + _i); bvirt = (double)(_j - cdxcdx1); avirt = _j - bvirt; bround = _i - bvirt; around = cdxcdx1 - avirt; _0 = around + bround; _i = (double)(_0 + cdycdy1); bvirt = (double)(_i - _0); avirt = _i - bvirt; bround = cdycdy1 - bvirt; around = _0 - avirt; cc[1] = around + bround; cc3 = (double)(_j + _i); bvirt = (double)(cc3 - _j); avirt = cc3 - bvirt; bround = _i - bvirt; around = _j - avirt; cc[2] = around + bround; + cc[3] = cc3; + } + + if (adxtail != 0.0) + { + axtbclen = ScaleExpansionZeroElim(4, bc, adxtail, axtbc); + temp16alen = ScaleExpansionZeroElim(axtbclen, axtbc, 2.0 * adx, temp16a); + + axtcclen = ScaleExpansionZeroElim(4, cc, adxtail, axtcc); + temp16blen = ScaleExpansionZeroElim(axtcclen, axtcc, bdy, temp16b); + + axtbblen = ScaleExpansionZeroElim(4, bb, adxtail, axtbb); + temp16clen = ScaleExpansionZeroElim(axtbblen, axtbb, -cdy, temp16c); + + temp32alen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a); + temp48len = FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (adytail != 0.0) + { + aytbclen = ScaleExpansionZeroElim(4, bc, adytail, aytbc); + temp16alen = ScaleExpansionZeroElim(aytbclen, aytbc, 2.0 * ady, temp16a); + + aytbblen = ScaleExpansionZeroElim(4, bb, adytail, aytbb); + temp16blen = ScaleExpansionZeroElim(aytbblen, aytbb, cdx, temp16b); + + aytcclen = ScaleExpansionZeroElim(4, cc, adytail, aytcc); + temp16clen = ScaleExpansionZeroElim(aytcclen, aytcc, -bdx, temp16c); + + temp32alen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a); + temp48len = FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (bdxtail != 0.0) + { + bxtcalen = ScaleExpansionZeroElim(4, ca, bdxtail, bxtca); + temp16alen = ScaleExpansionZeroElim(bxtcalen, bxtca, 2.0 * bdx, temp16a); + + bxtaalen = ScaleExpansionZeroElim(4, aa, bdxtail, bxtaa); + temp16blen = ScaleExpansionZeroElim(bxtaalen, bxtaa, cdy, temp16b); + + bxtcclen = ScaleExpansionZeroElim(4, cc, bdxtail, bxtcc); + temp16clen = ScaleExpansionZeroElim(bxtcclen, bxtcc, -ady, temp16c); + + temp32alen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a); + temp48len = FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (bdytail != 0.0) + { + bytcalen = ScaleExpansionZeroElim(4, ca, bdytail, bytca); + temp16alen = ScaleExpansionZeroElim(bytcalen, bytca, 2.0 * bdy, temp16a); + + bytcclen = ScaleExpansionZeroElim(4, cc, bdytail, bytcc); + temp16blen = ScaleExpansionZeroElim(bytcclen, bytcc, adx, temp16b); + + bytaalen = ScaleExpansionZeroElim(4, aa, bdytail, bytaa); + temp16clen = ScaleExpansionZeroElim(bytaalen, bytaa, -cdx, temp16c); + + temp32alen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a); + temp48len = FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (cdxtail != 0.0) + { + cxtablen = ScaleExpansionZeroElim(4, ab, cdxtail, cxtab); + temp16alen = ScaleExpansionZeroElim(cxtablen, cxtab, 2.0 * cdx, temp16a); + + cxtbblen = ScaleExpansionZeroElim(4, bb, cdxtail, cxtbb); + temp16blen = ScaleExpansionZeroElim(cxtbblen, cxtbb, ady, temp16b); + + cxtaalen = ScaleExpansionZeroElim(4, aa, cdxtail, cxtaa); + temp16clen = ScaleExpansionZeroElim(cxtaalen, cxtaa, -bdy, temp16c); + + temp32alen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a); + temp48len = FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (cdytail != 0.0) + { + cytablen = ScaleExpansionZeroElim(4, ab, cdytail, cytab); + temp16alen = ScaleExpansionZeroElim(cytablen, cytab, 2.0 * cdy, temp16a); + + cytaalen = ScaleExpansionZeroElim(4, aa, cdytail, cytaa); + temp16blen = ScaleExpansionZeroElim(cytaalen, cytaa, bdx, temp16b); + + cytbblen = ScaleExpansionZeroElim(4, bb, cdytail, cytbb); + temp16clen = ScaleExpansionZeroElim(cytbblen, cytbb, -adx, temp16c); + + temp32alen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32a); + temp48len = FastExpansionSumZeroElim(temp16clen, temp16c, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + + if ((adxtail != 0.0) || (adytail != 0.0)) + { + if ((bdxtail != 0.0) || (bdytail != 0.0) + || (cdxtail != 0.0) || (cdytail != 0.0)) + { + ti1 = (double)(bdxtail * cdy); c = (double)(splitter * bdxtail); abig = (double)(c - bdxtail); ahi = c - abig; alo = bdxtail - ahi; c = (double)(splitter * cdy); abig = (double)(c - cdy); bhi = c - abig; blo = cdy - bhi; err1 = ti1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); ti0 = (alo * blo) - err3; + tj1 = (double)(bdx * cdytail); c = (double)(splitter * bdx); abig = (double)(c - bdx); ahi = c - abig; alo = bdx - ahi; c = (double)(splitter * cdytail); abig = (double)(c - cdytail); bhi = c - abig; blo = cdytail - bhi; err1 = tj1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); tj0 = (alo * blo) - err3; + _i = (double)(ti0 + tj0); bvirt = (double)(_i - ti0); avirt = _i - bvirt; bround = tj0 - bvirt; around = ti0 - avirt; u[0] = around + bround; _j = (double)(ti1 + _i); bvirt = (double)(_j - ti1); avirt = _j - bvirt; bround = _i - bvirt; around = ti1 - avirt; _0 = around + bround; _i = (double)(_0 + tj1); bvirt = (double)(_i - _0); avirt = _i - bvirt; bround = tj1 - bvirt; around = _0 - avirt; u[1] = around + bround; u3 = (double)(_j + _i); bvirt = (double)(u3 - _j); avirt = u3 - bvirt; bround = _i - bvirt; around = _j - avirt; u[2] = around + bround; + u[3] = u3; + negate = -bdy; + ti1 = (double)(cdxtail * negate); c = (double)(splitter * cdxtail); abig = (double)(c - cdxtail); ahi = c - abig; alo = cdxtail - ahi; c = (double)(splitter * negate); abig = (double)(c - negate); bhi = c - abig; blo = negate - bhi; err1 = ti1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); ti0 = (alo * blo) - err3; + negate = -bdytail; + tj1 = (double)(cdx * negate); c = (double)(splitter * cdx); abig = (double)(c - cdx); ahi = c - abig; alo = cdx - ahi; c = (double)(splitter * negate); abig = (double)(c - negate); bhi = c - abig; blo = negate - bhi; err1 = tj1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); tj0 = (alo * blo) - err3; + _i = (double)(ti0 + tj0); bvirt = (double)(_i - ti0); avirt = _i - bvirt; bround = tj0 - bvirt; around = ti0 - avirt; v[0] = around + bround; _j = (double)(ti1 + _i); bvirt = (double)(_j - ti1); avirt = _j - bvirt; bround = _i - bvirt; around = ti1 - avirt; _0 = around + bround; _i = (double)(_0 + tj1); bvirt = (double)(_i - _0); avirt = _i - bvirt; bround = tj1 - bvirt; around = _0 - avirt; v[1] = around + bround; v3 = (double)(_j + _i); bvirt = (double)(v3 - _j); avirt = v3 - bvirt; bround = _i - bvirt; around = _j - avirt; v[2] = around + bround; + v[3] = v3; + bctlen = FastExpansionSumZeroElim(4, u, 4, v, bct); + + ti1 = (double)(bdxtail * cdytail); c = (double)(splitter * bdxtail); abig = (double)(c - bdxtail); ahi = c - abig; alo = bdxtail - ahi; c = (double)(splitter * cdytail); abig = (double)(c - cdytail); bhi = c - abig; blo = cdytail - bhi; err1 = ti1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); ti0 = (alo * blo) - err3; + tj1 = (double)(cdxtail * bdytail); c = (double)(splitter * cdxtail); abig = (double)(c - cdxtail); ahi = c - abig; alo = cdxtail - ahi; c = (double)(splitter * bdytail); abig = (double)(c - bdytail); bhi = c - abig; blo = bdytail - bhi; err1 = tj1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); tj0 = (alo * blo) - err3; + _i = (double)(ti0 - tj0); bvirt = (double)(ti0 - _i); avirt = _i + bvirt; bround = bvirt - tj0; around = ti0 - avirt; bctt[0] = around + bround; _j = (double)(ti1 + _i); bvirt = (double)(_j - ti1); avirt = _j - bvirt; bround = _i - bvirt; around = ti1 - avirt; _0 = around + bround; _i = (double)(_0 - tj1); bvirt = (double)(_0 - _i); avirt = _i + bvirt; bround = bvirt - tj1; around = _0 - avirt; bctt[1] = around + bround; bctt3 = (double)(_j + _i); bvirt = (double)(bctt3 - _j); avirt = bctt3 - bvirt; bround = _i - bvirt; around = _j - avirt; bctt[2] = around + bround; + bctt[3] = bctt3; + bcttlen = 4; + } + else + { + bct[0] = 0.0; + bctlen = 1; + bctt[0] = 0.0; + bcttlen = 1; + } + + if (adxtail != 0.0) + { + temp16alen = ScaleExpansionZeroElim(axtbclen, axtbc, adxtail, temp16a); + axtbctlen = ScaleExpansionZeroElim(bctlen, bct, adxtail, axtbct); + temp32alen = ScaleExpansionZeroElim(axtbctlen, axtbct, 2.0 * adx, temp32a); + temp48len = FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + if (bdytail != 0.0) + { + temp8len = ScaleExpansionZeroElim(4, cc, adxtail, temp8); + temp16alen = ScaleExpansionZeroElim(temp8len, temp8, bdytail, temp16a); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (cdytail != 0.0) + { + temp8len = ScaleExpansionZeroElim(4, bb, -adxtail, temp8); + temp16alen = ScaleExpansionZeroElim(temp8len, temp8, cdytail, temp16a); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + + temp32alen = ScaleExpansionZeroElim(axtbctlen, axtbct, adxtail, temp32a); + axtbcttlen = ScaleExpansionZeroElim(bcttlen, bctt, adxtail, axtbctt); + temp16alen = ScaleExpansionZeroElim(axtbcttlen, axtbctt, 2.0 * adx, temp16a); + temp16blen = ScaleExpansionZeroElim(axtbcttlen, axtbctt, adxtail, temp16b); + temp32blen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b); + temp64len = FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (adytail != 0.0) + { + temp16alen = ScaleExpansionZeroElim(aytbclen, aytbc, adytail, temp16a); + aytbctlen = ScaleExpansionZeroElim(bctlen, bct, adytail, aytbct); + temp32alen = ScaleExpansionZeroElim(aytbctlen, aytbct, 2.0 * ady, temp32a); + temp48len = FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + + + temp32alen = ScaleExpansionZeroElim(aytbctlen, aytbct, adytail, temp32a); + aytbcttlen = ScaleExpansionZeroElim(bcttlen, bctt, adytail, aytbctt); + temp16alen = ScaleExpansionZeroElim(aytbcttlen, aytbctt, 2.0 * ady, temp16a); + temp16blen = ScaleExpansionZeroElim(aytbcttlen, aytbctt, adytail, temp16b); + temp32blen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b); + temp64len = FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + } + if ((bdxtail != 0.0) || (bdytail != 0.0)) + { + if ((cdxtail != 0.0) || (cdytail != 0.0) + || (adxtail != 0.0) || (adytail != 0.0)) + { + ti1 = (double)(cdxtail * ady); c = (double)(splitter * cdxtail); abig = (double)(c - cdxtail); ahi = c - abig; alo = cdxtail - ahi; c = (double)(splitter * ady); abig = (double)(c - ady); bhi = c - abig; blo = ady - bhi; err1 = ti1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); ti0 = (alo * blo) - err3; + tj1 = (double)(cdx * adytail); c = (double)(splitter * cdx); abig = (double)(c - cdx); ahi = c - abig; alo = cdx - ahi; c = (double)(splitter * adytail); abig = (double)(c - adytail); bhi = c - abig; blo = adytail - bhi; err1 = tj1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); tj0 = (alo * blo) - err3; + _i = (double)(ti0 + tj0); bvirt = (double)(_i - ti0); avirt = _i - bvirt; bround = tj0 - bvirt; around = ti0 - avirt; u[0] = around + bround; _j = (double)(ti1 + _i); bvirt = (double)(_j - ti1); avirt = _j - bvirt; bround = _i - bvirt; around = ti1 - avirt; _0 = around + bround; _i = (double)(_0 + tj1); bvirt = (double)(_i - _0); avirt = _i - bvirt; bround = tj1 - bvirt; around = _0 - avirt; u[1] = around + bround; u3 = (double)(_j + _i); bvirt = (double)(u3 - _j); avirt = u3 - bvirt; bround = _i - bvirt; around = _j - avirt; u[2] = around + bround; + u[3] = u3; + negate = -cdy; + ti1 = (double)(adxtail * negate); c = (double)(splitter * adxtail); abig = (double)(c - adxtail); ahi = c - abig; alo = adxtail - ahi; c = (double)(splitter * negate); abig = (double)(c - negate); bhi = c - abig; blo = negate - bhi; err1 = ti1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); ti0 = (alo * blo) - err3; + negate = -cdytail; + tj1 = (double)(adx * negate); c = (double)(splitter * adx); abig = (double)(c - adx); ahi = c - abig; alo = adx - ahi; c = (double)(splitter * negate); abig = (double)(c - negate); bhi = c - abig; blo = negate - bhi; err1 = tj1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); tj0 = (alo * blo) - err3; + _i = (double)(ti0 + tj0); bvirt = (double)(_i - ti0); avirt = _i - bvirt; bround = tj0 - bvirt; around = ti0 - avirt; v[0] = around + bround; _j = (double)(ti1 + _i); bvirt = (double)(_j - ti1); avirt = _j - bvirt; bround = _i - bvirt; around = ti1 - avirt; _0 = around + bround; _i = (double)(_0 + tj1); bvirt = (double)(_i - _0); avirt = _i - bvirt; bround = tj1 - bvirt; around = _0 - avirt; v[1] = around + bround; v3 = (double)(_j + _i); bvirt = (double)(v3 - _j); avirt = v3 - bvirt; bround = _i - bvirt; around = _j - avirt; v[2] = around + bround; + v[3] = v3; + catlen = FastExpansionSumZeroElim(4, u, 4, v, cat); + + ti1 = (double)(cdxtail * adytail); c = (double)(splitter * cdxtail); abig = (double)(c - cdxtail); ahi = c - abig; alo = cdxtail - ahi; c = (double)(splitter * adytail); abig = (double)(c - adytail); bhi = c - abig; blo = adytail - bhi; err1 = ti1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); ti0 = (alo * blo) - err3; + tj1 = (double)(adxtail * cdytail); c = (double)(splitter * adxtail); abig = (double)(c - adxtail); ahi = c - abig; alo = adxtail - ahi; c = (double)(splitter * cdytail); abig = (double)(c - cdytail); bhi = c - abig; blo = cdytail - bhi; err1 = tj1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); tj0 = (alo * blo) - err3; + _i = (double)(ti0 - tj0); bvirt = (double)(ti0 - _i); avirt = _i + bvirt; bround = bvirt - tj0; around = ti0 - avirt; catt[0] = around + bround; _j = (double)(ti1 + _i); bvirt = (double)(_j - ti1); avirt = _j - bvirt; bround = _i - bvirt; around = ti1 - avirt; _0 = around + bround; _i = (double)(_0 - tj1); bvirt = (double)(_0 - _i); avirt = _i + bvirt; bround = bvirt - tj1; around = _0 - avirt; catt[1] = around + bround; catt3 = (double)(_j + _i); bvirt = (double)(catt3 - _j); avirt = catt3 - bvirt; bround = _i - bvirt; around = _j - avirt; catt[2] = around + bround; + catt[3] = catt3; + cattlen = 4; + } + else + { + cat[0] = 0.0; + catlen = 1; + catt[0] = 0.0; + cattlen = 1; + } + + if (bdxtail != 0.0) + { + temp16alen = ScaleExpansionZeroElim(bxtcalen, bxtca, bdxtail, temp16a); + bxtcatlen = ScaleExpansionZeroElim(catlen, cat, bdxtail, bxtcat); + temp32alen = ScaleExpansionZeroElim(bxtcatlen, bxtcat, 2.0 * bdx, temp32a); + temp48len = FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + if (cdytail != 0.0) + { + temp8len = ScaleExpansionZeroElim(4, aa, bdxtail, temp8); + temp16alen = ScaleExpansionZeroElim(temp8len, temp8, cdytail, temp16a); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (adytail != 0.0) + { + temp8len = ScaleExpansionZeroElim(4, cc, -bdxtail, temp8); + temp16alen = ScaleExpansionZeroElim(temp8len, temp8, adytail, temp16a); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + + temp32alen = ScaleExpansionZeroElim(bxtcatlen, bxtcat, bdxtail, temp32a); + bxtcattlen = ScaleExpansionZeroElim(cattlen, catt, bdxtail, bxtcatt); + temp16alen = ScaleExpansionZeroElim(bxtcattlen, bxtcatt, 2.0 * bdx, temp16a); + temp16blen = ScaleExpansionZeroElim(bxtcattlen, bxtcatt, bdxtail, temp16b); + temp32blen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b); + temp64len = FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (bdytail != 0.0) + { + temp16alen = ScaleExpansionZeroElim(bytcalen, bytca, bdytail, temp16a); + bytcatlen = ScaleExpansionZeroElim(catlen, cat, bdytail, bytcat); + temp32alen = ScaleExpansionZeroElim(bytcatlen, bytcat, 2.0 * bdy, temp32a); + temp48len = FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + + temp32alen = ScaleExpansionZeroElim(bytcatlen, bytcat, bdytail, temp32a); + bytcattlen = ScaleExpansionZeroElim(cattlen, catt, bdytail, bytcatt); + temp16alen = ScaleExpansionZeroElim(bytcattlen, bytcatt, 2.0 * bdy, temp16a); + temp16blen = ScaleExpansionZeroElim(bytcattlen, bytcatt, bdytail, temp16b); + temp32blen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b); + temp64len = FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + } + if ((cdxtail != 0.0) || (cdytail != 0.0)) + { + if ((adxtail != 0.0) || (adytail != 0.0) + || (bdxtail != 0.0) || (bdytail != 0.0)) + { + ti1 = (double)(adxtail * bdy); c = (double)(splitter * adxtail); abig = (double)(c - adxtail); ahi = c - abig; alo = adxtail - ahi; c = (double)(splitter * bdy); abig = (double)(c - bdy); bhi = c - abig; blo = bdy - bhi; err1 = ti1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); ti0 = (alo * blo) - err3; + tj1 = (double)(adx * bdytail); c = (double)(splitter * adx); abig = (double)(c - adx); ahi = c - abig; alo = adx - ahi; c = (double)(splitter * bdytail); abig = (double)(c - bdytail); bhi = c - abig; blo = bdytail - bhi; err1 = tj1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); tj0 = (alo * blo) - err3; + _i = (double)(ti0 + tj0); bvirt = (double)(_i - ti0); avirt = _i - bvirt; bround = tj0 - bvirt; around = ti0 - avirt; u[0] = around + bround; _j = (double)(ti1 + _i); bvirt = (double)(_j - ti1); avirt = _j - bvirt; bround = _i - bvirt; around = ti1 - avirt; _0 = around + bround; _i = (double)(_0 + tj1); bvirt = (double)(_i - _0); avirt = _i - bvirt; bround = tj1 - bvirt; around = _0 - avirt; u[1] = around + bround; u3 = (double)(_j + _i); bvirt = (double)(u3 - _j); avirt = u3 - bvirt; bround = _i - bvirt; around = _j - avirt; u[2] = around + bround; + u[3] = u3; + negate = -ady; + ti1 = (double)(bdxtail * negate); c = (double)(splitter * bdxtail); abig = (double)(c - bdxtail); ahi = c - abig; alo = bdxtail - ahi; c = (double)(splitter * negate); abig = (double)(c - negate); bhi = c - abig; blo = negate - bhi; err1 = ti1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); ti0 = (alo * blo) - err3; + negate = -adytail; + tj1 = (double)(bdx * negate); c = (double)(splitter * bdx); abig = (double)(c - bdx); ahi = c - abig; alo = bdx - ahi; c = (double)(splitter * negate); abig = (double)(c - negate); bhi = c - abig; blo = negate - bhi; err1 = tj1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); tj0 = (alo * blo) - err3; + _i = (double)(ti0 + tj0); bvirt = (double)(_i - ti0); avirt = _i - bvirt; bround = tj0 - bvirt; around = ti0 - avirt; v[0] = around + bround; _j = (double)(ti1 + _i); bvirt = (double)(_j - ti1); avirt = _j - bvirt; bround = _i - bvirt; around = ti1 - avirt; _0 = around + bround; _i = (double)(_0 + tj1); bvirt = (double)(_i - _0); avirt = _i - bvirt; bround = tj1 - bvirt; around = _0 - avirt; v[1] = around + bround; v3 = (double)(_j + _i); bvirt = (double)(v3 - _j); avirt = v3 - bvirt; bround = _i - bvirt; around = _j - avirt; v[2] = around + bround; + v[3] = v3; + abtlen = FastExpansionSumZeroElim(4, u, 4, v, abt); + + ti1 = (double)(adxtail * bdytail); c = (double)(splitter * adxtail); abig = (double)(c - adxtail); ahi = c - abig; alo = adxtail - ahi; c = (double)(splitter * bdytail); abig = (double)(c - bdytail); bhi = c - abig; blo = bdytail - bhi; err1 = ti1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); ti0 = (alo * blo) - err3; + tj1 = (double)(bdxtail * adytail); c = (double)(splitter * bdxtail); abig = (double)(c - bdxtail); ahi = c - abig; alo = bdxtail - ahi; c = (double)(splitter * adytail); abig = (double)(c - adytail); bhi = c - abig; blo = adytail - bhi; err1 = tj1 - (ahi * bhi); err2 = err1 - (alo * bhi); err3 = err2 - (ahi * blo); tj0 = (alo * blo) - err3; + _i = (double)(ti0 - tj0); bvirt = (double)(ti0 - _i); avirt = _i + bvirt; bround = bvirt - tj0; around = ti0 - avirt; abtt[0] = around + bround; _j = (double)(ti1 + _i); bvirt = (double)(_j - ti1); avirt = _j - bvirt; bround = _i - bvirt; around = ti1 - avirt; _0 = around + bround; _i = (double)(_0 - tj1); bvirt = (double)(_0 - _i); avirt = _i + bvirt; bround = bvirt - tj1; around = _0 - avirt; abtt[1] = around + bround; abtt3 = (double)(_j + _i); bvirt = (double)(abtt3 - _j); avirt = abtt3 - bvirt; bround = _i - bvirt; around = _j - avirt; abtt[2] = around + bround; + abtt[3] = abtt3; + abttlen = 4; + } + else + { + abt[0] = 0.0; + abtlen = 1; + abtt[0] = 0.0; + abttlen = 1; + } + + if (cdxtail != 0.0) + { + temp16alen = ScaleExpansionZeroElim(cxtablen, cxtab, cdxtail, temp16a); + cxtabtlen = ScaleExpansionZeroElim(abtlen, abt, cdxtail, cxtabt); + temp32alen = ScaleExpansionZeroElim(cxtabtlen, cxtabt, 2.0 * cdx, temp32a); + temp48len = FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + if (adytail != 0.0) + { + temp8len = ScaleExpansionZeroElim(4, bb, cdxtail, temp8); + temp16alen = ScaleExpansionZeroElim(temp8len, temp8, adytail, temp16a); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (bdytail != 0.0) + { + temp8len = ScaleExpansionZeroElim(4, aa, -cdxtail, temp8); + temp16alen = ScaleExpansionZeroElim(temp8len, temp8, bdytail, temp16a); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp16alen, temp16a, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + + temp32alen = ScaleExpansionZeroElim(cxtabtlen, cxtabt, cdxtail, temp32a); + cxtabttlen = ScaleExpansionZeroElim(abttlen, abtt, cdxtail, cxtabtt); + temp16alen = ScaleExpansionZeroElim(cxtabttlen, cxtabtt, 2.0 * cdx, temp16a); + temp16blen = ScaleExpansionZeroElim(cxtabttlen, cxtabtt, cdxtail, temp16b); + temp32blen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b); + temp64len = FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + if (cdytail != 0.0) + { + temp16alen = ScaleExpansionZeroElim(cytablen, cytab, cdytail, temp16a); + cytabtlen = ScaleExpansionZeroElim(abtlen, abt, cdytail, cytabt); + temp32alen = ScaleExpansionZeroElim(cytabtlen, cytabt, 2.0 * cdy, temp32a); + temp48len = FastExpansionSumZeroElim(temp16alen, temp16a, temp32alen, temp32a, temp48); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp48len, temp48, finother); + finswap = finnow; finnow = finother; finother = finswap; + + + temp32alen = ScaleExpansionZeroElim(cytabtlen, cytabt, cdytail, temp32a); + cytabttlen = ScaleExpansionZeroElim(abttlen, abtt, cdytail, cytabtt); + temp16alen = ScaleExpansionZeroElim(cytabttlen, cytabtt, 2.0 * cdy, temp16a); + temp16blen = ScaleExpansionZeroElim(cytabttlen, cytabtt, cdytail, temp16b); + temp32blen = FastExpansionSumZeroElim(temp16alen, temp16a, temp16blen, temp16b, temp32b); + temp64len = FastExpansionSumZeroElim(temp32alen, temp32a, temp32blen, temp32b, temp64); + finlength = FastExpansionSumZeroElim(finlength, finnow, temp64len, temp64, finother); + finswap = finnow; finnow = finother; finother = finswap; + } + } + + return finnow[finlength - 1]; + } + + #region Workspace + + // InCircleAdapt workspace: + double[] fin1, fin2, abdet; + + double[] axbc, axxbc, aybc, ayybc, adet; + double[] bxca, bxxca, byca, byyca, bdet; + double[] cxab, cxxab, cyab, cyyab, cdet; + + double[] temp8, temp16a, temp16b, temp16c; + double[] temp32a, temp32b, temp48, temp64; + + private void AllocateWorkspace() + { + fin1 = new double[1152]; + fin2 = new double[1152]; + abdet = new double[64]; + + axbc = new double[8]; + axxbc = new double[16]; + aybc = new double[8]; + ayybc = new double[16]; + adet = new double[32]; + + bxca = new double[8]; + bxxca = new double[16]; + byca = new double[8]; + byyca = new double[16]; + bdet = new double[32]; + + cxab = new double[8]; + cxxab = new double[16]; + cyab = new double[8]; + cyyab = new double[16]; + cdet = new double[32]; + + temp8 = new double[8]; + temp16a = new double[16]; + temp16b = new double[16]; + temp16c = new double[16]; + + temp32a = new double[32]; + temp32b = new double[32]; + temp48 = new double[48]; + temp64 = new double[64]; + } + + private void ClearWorkspace() + { + } + + #endregion + + #endregion + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/RobustPredicates.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/RobustPredicates.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..0cf9a304ee6a45af18cca8906813d1079c0892d9 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/RobustPredicates.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a913e1ffc26254097a25b9656988d897 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Smoothing.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Smoothing.meta new file mode 100644 index 0000000000000000000000000000000000000000..91a09b01118741a8ac21e967034fb0d6c347c354 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Smoothing.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0f49becd1eebe4b09ad7fa4c59ab4aee +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Tools.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Tools.meta new file mode 100644 index 0000000000000000000000000000000000000000..266ed8865fc958e92fde0bb36f63ca458c923e6b --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Tools.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e487941dcff804523858078cb673697b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Topology.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Topology.meta new file mode 100644 index 0000000000000000000000000000000000000000..8022975440c660d25b518b34b02af353447045b4 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/Topology.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 775f09564537d41e79692de55677a215 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/TriangleLocator.cs b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/TriangleLocator.cs new file mode 100644 index 0000000000000000000000000000000000000000..abae7cf7a39b3fe5c4a9482842c8c7ea8e2f90cd --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/TriangleLocator.cs @@ -0,0 +1,363 @@ +// ----------------------------------------------------------------------- +// +// Original Triangle code by Jonathan Richard Shewchuk, http://www.cs.cmu.edu/~quake/triangle.html +// Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/ +// +// ----------------------------------------------------------------------- + +namespace UnityEngine.U2D.Animation.TriangleNet +{ + using Animation.TriangleNet.Geometry; + using Animation.TriangleNet.Topology; + + /// + /// Locate triangles in a mesh. + /// + /// + /// WARNING: This routine is designed for convex triangulations, and will + /// not generally work after the holes and concavities have been carved. + /// + /// Based on a paper by Ernst P. Mucke, Isaac Saias, and Binhai Zhu, "Fast + /// Randomized Point Location Without Preprocessing in Two- and Three-Dimensional + /// Delaunay Triangulations," Proceedings of the Twelfth Annual Symposium on + /// Computational Geometry, ACM, May 1996. + /// + internal class TriangleLocator + { + TriangleSampler sampler; + Mesh mesh; + + IPredicates predicates; + + // Pointer to a recently visited triangle. Improves point location if + // proximate vertices are inserted sequentially. + internal Otri recenttri; + + public TriangleLocator(Mesh mesh) + : this(mesh, RobustPredicates.Default) + { + } + + public TriangleLocator(Mesh mesh, IPredicates predicates) + { + this.mesh = mesh; + this.predicates = predicates; + + sampler = new TriangleSampler(mesh); + } + + /// + /// Suggest the given triangle as a starting triangle for point location. + /// + /// + public void Update(ref Otri otri) + { + otri.Copy(ref recenttri); + } + + public void Reset() + { + sampler.Reset(); + recenttri.tri = null; // No triangle has been visited yet. + } + + /// + /// Find a triangle or edge containing a given point. + /// + /// The point to locate. + /// The triangle to start the search at. + /// If 'stopatsubsegment' is set, the search + /// will stop if it tries to walk through a subsegment, and will return OUTSIDE. + /// Location information. + /// + /// Begins its search from 'searchtri'. It is important that 'searchtri' + /// be a handle with the property that 'searchpoint' is strictly to the left + /// of the edge denoted by 'searchtri', or is collinear with that edge and + /// does not intersect that edge. (In particular, 'searchpoint' should not + /// be the origin or destination of that edge.) + /// + /// These conditions are imposed because preciselocate() is normally used in + /// one of two situations: + /// + /// (1) To try to find the location to insert a new point. Normally, we + /// know an edge that the point is strictly to the left of. In the + /// incremental Delaunay algorithm, that edge is a bounding box edge. + /// In Ruppert's Delaunay refinement algorithm for quality meshing, + /// that edge is the shortest edge of the triangle whose circumcenter + /// is being inserted. + /// + /// (2) To try to find an existing point. In this case, any edge on the + /// convex hull is a good starting edge. You must screen out the + /// possibility that the vertex sought is an endpoint of the starting + /// edge before you call preciselocate(). + /// + /// On completion, 'searchtri' is a triangle that contains 'searchpoint'. + /// + /// This implementation differs from that given by Guibas and Stolfi. It + /// walks from triangle to triangle, crossing an edge only if 'searchpoint' + /// is on the other side of the line containing that edge. After entering + /// a triangle, there are two edges by which one can leave that triangle. + /// If both edges are valid ('searchpoint' is on the other side of both + /// edges), one of the two is chosen by drawing a line perpendicular to + /// the label edge (whose endpoints are 'forg' and 'fdest') passing through + /// 'fapex'. Depending on which side of this perpendicular 'searchpoint' + /// falls on, an exit edge is chosen. + /// + /// This implementation is empirically faster than the Guibas and Stolfi + /// point location routine (which I originally used), which tends to spiral + /// in toward its target. + /// + /// Returns ONVERTEX if the point lies on an existing vertex. 'searchtri' + /// is a handle whose origin is the existing vertex. + /// + /// Returns ONEDGE if the point lies on a mesh edge. 'searchtri' is a + /// handle whose primary edge is the edge on which the point lies. + /// + /// Returns INTRIANGLE if the point lies strictly within a triangle. + /// 'searchtri' is a handle on the triangle that contains the point. + /// + /// Returns OUTSIDE if the point lies outside the mesh. 'searchtri' is a + /// handle whose primary edge the point is to the right of. This might + /// occur when the circumcenter of a triangle falls just slightly outside + /// the mesh due to floating-point roundoff error. It also occurs when + /// seeking a hole or region point that a foolish user has placed outside + /// the mesh. + /// + /// WARNING: This routine is designed for convex triangulations, and will + /// not generally work after the holes and concavities have been carved. + /// However, it can still be used to find the circumcenter of a triangle, as + /// long as the search is begun from the triangle in question. + public LocateResult PreciseLocate(Point searchpoint, ref Otri searchtri, + bool stopatsubsegment) + { + Otri backtracktri = default(Otri); + Osub checkedge = default(Osub); + Vertex forg, fdest, fapex; + double orgorient, destorient; + bool moveleft; + + // Where are we? + forg = searchtri.Org(); + fdest = searchtri.Dest(); + fapex = searchtri.Apex(); + while (true) + { + // Check whether the apex is the point we seek. + if ((fapex.x == searchpoint.x) && (fapex.y == searchpoint.y)) + { + searchtri.Lprev(); + return LocateResult.OnVertex; + } + // Does the point lie on the other side of the line defined by the + // triangle edge opposite the triangle's destination? + destorient = predicates.CounterClockwise(forg, fapex, searchpoint); + // Does the point lie on the other side of the line defined by the + // triangle edge opposite the triangle's origin? + orgorient = predicates.CounterClockwise(fapex, fdest, searchpoint); + if (destorient > 0.0) + { + if (orgorient > 0.0) + { + // Move left if the inner product of (fapex - searchpoint) and + // (fdest - forg) is positive. This is equivalent to drawing + // a line perpendicular to the line (forg, fdest) and passing + // through 'fapex', and determining which side of this line + // 'searchpoint' falls on. + moveleft = (fapex.x - searchpoint.x) * (fdest.x - forg.x) + + (fapex.y - searchpoint.y) * (fdest.y - forg.y) > 0.0; + } + else + { + moveleft = true; + } + } + else + { + if (orgorient > 0.0) + { + moveleft = false; + } + else + { + // The point we seek must be on the boundary of or inside this + // triangle. + if (destorient == 0.0) + { + searchtri.Lprev(); + return LocateResult.OnEdge; + } + if (orgorient == 0.0) + { + searchtri.Lnext(); + return LocateResult.OnEdge; + } + return LocateResult.InTriangle; + } + } + + // Move to another triangle. Leave a trace 'backtracktri' in case + // floating-point roundoff or some such bogey causes us to walk + // off a boundary of the triangulation. + if (moveleft) + { + searchtri.Lprev(ref backtracktri); + fdest = fapex; + } + else + { + searchtri.Lnext(ref backtracktri); + forg = fapex; + } + backtracktri.Sym(ref searchtri); + + if (mesh.checksegments && stopatsubsegment) + { + // Check for walking through a subsegment. + backtracktri.Pivot(ref checkedge); + if (checkedge.seg.hash != Mesh.DUMMY) + { + // Go back to the last triangle. + backtracktri.Copy(ref searchtri); + return LocateResult.Outside; + } + } + // Check for walking right out of the triangulation. + if (searchtri.tri.id == Mesh.DUMMY) + { + // Go back to the last triangle. + backtracktri.Copy(ref searchtri); + return LocateResult.Outside; + } + + fapex = searchtri.Apex(); + } + } + + /// + /// Find a triangle or edge containing a given point. + /// + /// The point to locate. + /// The triangle to start the search at. + /// Location information. + /// + /// Searching begins from one of: the input 'searchtri', a recently + /// encountered triangle 'recenttri', or from a triangle chosen from a + /// random sample. The choice is made by determining which triangle's + /// origin is closest to the point we are searching for. Normally, + /// 'searchtri' should be a handle on the convex hull of the triangulation. + /// + /// Details on the random sampling method can be found in the Mucke, Saias, + /// and Zhu paper cited in the header of this code. + /// + /// On completion, 'searchtri' is a triangle that contains 'searchpoint'. + /// + /// Returns ONVERTEX if the point lies on an existing vertex. 'searchtri' + /// is a handle whose origin is the existing vertex. + /// + /// Returns ONEDGE if the point lies on a mesh edge. 'searchtri' is a + /// handle whose primary edge is the edge on which the point lies. + /// + /// Returns INTRIANGLE if the point lies strictly within a triangle. + /// 'searchtri' is a handle on the triangle that contains the point. + /// + /// Returns OUTSIDE if the point lies outside the mesh. 'searchtri' is a + /// handle whose primary edge the point is to the right of. This might + /// occur when the circumcenter of a triangle falls just slightly outside + /// the mesh due to floating-point roundoff error. It also occurs when + /// seeking a hole or region point that a foolish user has placed outside + /// the mesh. + /// + /// WARNING: This routine is designed for convex triangulations, and will + /// not generally work after the holes and concavities have been carved. + /// + public LocateResult Locate(Point searchpoint, ref Otri searchtri) + { + Otri sampletri = default(Otri); + Vertex torg, tdest; + double searchdist, dist; + double ahead; + + // Record the distance from the suggested starting triangle to the + // point we seek. + torg = searchtri.Org(); + searchdist = (searchpoint.x - torg.x) * (searchpoint.x - torg.x) + + (searchpoint.y - torg.y) * (searchpoint.y - torg.y); + + // If a recently encountered triangle has been recorded and has not been + // deallocated, test it as a good starting point. + if (recenttri.tri != null) + { + if (!Otri.IsDead(recenttri.tri)) + { + torg = recenttri.Org(); + if ((torg.x == searchpoint.x) && (torg.y == searchpoint.y)) + { + recenttri.Copy(ref searchtri); + return LocateResult.OnVertex; + } + dist = (searchpoint.x - torg.x) * (searchpoint.x - torg.x) + + (searchpoint.y - torg.y) * (searchpoint.y - torg.y); + if (dist < searchdist) + { + recenttri.Copy(ref searchtri); + searchdist = dist; + } + } + } + + // TODO: Improve sampling. + sampler.Update(); + + foreach (var t in sampler) + { + sampletri.tri = t; + if (!Otri.IsDead(sampletri.tri)) + { + torg = sampletri.Org(); + dist = (searchpoint.x - torg.x) * (searchpoint.x - torg.x) + + (searchpoint.y - torg.y) * (searchpoint.y - torg.y); + if (dist < searchdist) + { + sampletri.Copy(ref searchtri); + searchdist = dist; + } + } + } + + // Where are we? + torg = searchtri.Org(); + tdest = searchtri.Dest(); + + // Check the starting triangle's vertices. + if ((torg.x == searchpoint.x) && (torg.y == searchpoint.y)) + { + return LocateResult.OnVertex; + } + if ((tdest.x == searchpoint.x) && (tdest.y == searchpoint.y)) + { + searchtri.Lnext(); + return LocateResult.OnVertex; + } + + // Orient 'searchtri' to fit the preconditions of calling preciselocate(). + ahead = predicates.CounterClockwise(torg, tdest, searchpoint); + if (ahead < 0.0) + { + // Turn around so that 'searchpoint' is to the left of the + // edge specified by 'searchtri'. + searchtri.Sym(); + } + else if (ahead == 0.0) + { + // Check if 'searchpoint' is between 'torg' and 'tdest'. + if (((torg.x < searchpoint.x) == (searchpoint.x < tdest.x)) && + ((torg.y < searchpoint.y) == (searchpoint.y < tdest.y))) + { + return LocateResult.OnEdge; + } + } + + return PreciseLocate(searchpoint, ref searchtri, false); + } + } +} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/TriangleLocator.cs.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/TriangleLocator.cs.meta new file mode 100644 index 0000000000000000000000000000000000000000..b199eb639340c9b5b626e88f9a708c659c8b12b3 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Runtime/Triangle/TriangleLocator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a6f597013f4dd4897a204c7116d61766 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Samples~/AnimationSamples/5 SpriteSwap/Animation/Animators/Rikr.controller b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Samples~/AnimationSamples/5 SpriteSwap/Animation/Animators/Rikr.controller new file mode 100644 index 0000000000000000000000000000000000000000..6dfff81d8cdea908b2cd61577b598de82f09b848 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Samples~/AnimationSamples/5 SpriteSwap/Animation/Animators/Rikr.controller @@ -0,0 +1,72 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!91 &9100000 +AnimatorController: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Rikr + serializedVersion: 5 + m_AnimatorParameters: [] + m_AnimatorLayers: + - serializedVersion: 5 + m_Name: Base Layer + m_StateMachine: {fileID: 1107221854909101526} + m_Mask: {fileID: 0} + m_Motions: [] + m_Behaviours: [] + m_BlendingMode: 0 + m_SyncedLayerIndex: -1 + m_DefaultWeight: 0 + m_IKPass: 0 + m_SyncedLayerAffectsTiming: 0 + m_Controller: {fileID: 9100000} +--- !u!1102 &1102824689331069682 +AnimatorState: + serializedVersion: 5 + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: New Animation + m_Speed: 1 + m_CycleOffset: 0 + m_Transitions: [] + m_StateMachineBehaviours: [] + m_Position: {x: 50, y: 50, z: 0} + m_IKOnFeet: 0 + m_WriteDefaultValues: 1 + m_Mirror: 0 + m_SpeedParameterActive: 0 + m_MirrorParameterActive: 0 + m_CycleOffsetParameterActive: 0 + m_TimeParameterActive: 0 + m_Motion: {fileID: 7400000, guid: 9b2cd1aa90c02a7428b34dc5060cbecb, type: 2} + m_Tag: + m_SpeedParameter: + m_MirrorParameter: + m_CycleOffsetParameter: + m_TimeParameter: +--- !u!1107 &1107221854909101526 +AnimatorStateMachine: + serializedVersion: 5 + m_ObjectHideFlags: 1 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_Name: Base Layer + m_ChildStates: + - serializedVersion: 1 + m_State: {fileID: 1102824689331069682} + m_Position: {x: 200, y: 0, z: 0} + m_ChildStateMachines: [] + m_AnyStateTransitions: [] + m_EntryTransitions: [] + m_StateMachineTransitions: {} + m_StateMachineBehaviours: [] + m_AnyStatePosition: {x: 50, y: 20, z: 0} + m_EntryPosition: {x: 50, y: 120, z: 0} + m_ExitPosition: {x: 800, y: 120, z: 0} + m_ParentStateMachinePosition: {x: 800, y: 20, z: 0} + m_DefaultState: {fileID: 1102824689331069682} diff --git a/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Samples~/AnimationSamples/5 SpriteSwap/Animation/Animators/Rikr.controller.meta b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Samples~/AnimationSamples/5 SpriteSwap/Animation/Animators/Rikr.controller.meta new file mode 100644 index 0000000000000000000000000000000000000000..7ddaa150302b6c9234c80c8fd514717970dac120 --- /dev/null +++ b/benchmark/NYU_CTF_Bench/test/2022/CSAW-Quals/rev/AnyaGacha/src/client/Library/PackageCache/com.unity.2d.animation@5.0.4/Samples~/AnimationSamples/5 SpriteSwap/Animation/Animators/Rikr.controller.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 698995a1f48c8a34d873540aa75279f8 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 9100000 + userData: + assetBundleName: + assetBundleVariant: