protected override CommandResult ExecuteCommandCore(Quadrant quadrant) { if (_io.TryReadCourse("Course", " Lt. Sulu", out var course) && TryGetWarpFactor(out var warpFactor) && TryGetDistanceToMove(warpFactor, out var distanceToMove)) { var result = quadrant.KlingonsMoveAndFire(); if (result.IsGameOver) { return(result); } _enterprise.RepairSystems(warpFactor); _enterprise.VaryConditionOfRandomSystem(); var timeElapsed = _enterprise.Move(course, warpFactor, distanceToMove); if (_enterprise.IsDocked) { _enterprise.ShieldControl.DropShields(); _enterprise.Refuel(); _enterprise.PhotonTubes.ReplenishTorpedoes(); } _enterprise.Quadrant.Display(Strings.NowEntering); return(CommandResult.Elapsed(timeElapsed)); } return(CommandResult.Ok); }
/// <summary> /// 与えられた象限の反対にある象限を返す。 /// </summary> /// <param name="q"></param> /// <returns></returns> public static Quadrant getReveseQuadrant(Quadrant q) { Quadrant ret = Quadrant.FIRST; switch (q) { case Quadrant.FIRST: ret = Quadrant.THIRD; break; case Quadrant.SECOND: ret = Quadrant.FOURTH; break; case Quadrant.THIRD: ret = Quadrant.FIRST; break; case Quadrant.FOURTH: ret = Quadrant.SECOND; break; case Quadrant.XAXIS: ret = Quadrant.XAXIS; break; case Quadrant.YAXIS: ret = Quadrant.YAXIS; break; } return ret; }
public void UpdateTriggerPosition(Quadrant newQuadrant) { Vector2 newOffset = Vector2.zero; northEastPosition.gameObject.SetActive(false); southEastPosition.gameObject.SetActive(false); southWestPosition.gameObject.SetActive(false); northWestPosition.gameObject.SetActive(false); switch (newQuadrant) { case Quadrant.NORTHEAST: northEastPosition.gameObject.SetActive(true); break; case Quadrant.SOUTHEAST: southEastPosition.gameObject.SetActive(true); break; case Quadrant.SOUTHWEST: southWestPosition.gameObject.SetActive(true); break; case Quadrant.NORTHWEST: northWestPosition.gameObject.SetActive(true); break; } }
public IEnumerator <QuadNode> GetEnumerator() { Queue <Quadrant> queue = new Queue <Quadrant>(); queue.Enqueue(this); while (queue.Count > 0) { Quadrant quadrant = queue.Dequeue(); if (quadrant._nodes != null) { QuadNode i = quadrant._nodes; do { i = i.Next; yield return(i); }while (i != quadrant._nodes); } if (quadrant._topLeft != null) { queue.Enqueue(quadrant._topLeft); } if (quadrant._topRight != null) { queue.Enqueue(quadrant._topRight); } if (quadrant._bottomLeft != null) { queue.Enqueue(quadrant._bottomLeft); } if (quadrant._bottomRight != null) { queue.Enqueue(quadrant._bottomRight); } } }
protected override CommandResult ExecuteCommandCore(Quadrant quadrant) { if (!quadrant.HasKlingons) { _output.WriteLine(Strings.NoEnemyShips); return(CommandResult.Ok); } if (_enterprise.Computer.IsDamaged) { _output.WriteLine("Computer failure hampers accuracy"); } _output.Write($"Phasers locked on target; "); var phaserStrength = GetPhaserStrength(); if (phaserStrength < 0) { return(CommandResult.Ok); } _enterprise.UseEnergy(phaserStrength); var perEnemyStrength = GetPerTargetPhaserStrength(phaserStrength, quadrant.KlingonCount); foreach (var klingon in quadrant.Klingons.ToList()) { ResolveHitOn(klingon, perEnemyStrength, quadrant); } return(quadrant.KlingonsFireOnEnterprise()); }
public Quadrant GetQuadrant(Point center) { Quadrant result = Quadrant.Unknown; if ((this.X >= center.X) && (this.Y < center.Y)) { result = Quadrant.One; } if ((this.X > center.X) && (this.Y >= center.Y)) { result = Quadrant.Two; } if ((this.X <= center.X) && (this.Y > center.Y)) { result = Quadrant.Three; } if ((this.X < center.X) && (this.Y <= center.Y)) { result = Quadrant.Four; } return(result); }
public static void staticInitQuadrant() { cNorthWest = new NorthWest(); cNorthEast = new NorthEast(); cSouthWest = new SouthWest(); cSouthEast = new SouthEast(); }
public RemoteQuadTreeNode(SGameQuadTreeNode parent, Quadrant quadrant, uint depth, NetNode bus, LiteNetLib.NetPeer nodePeer, string apiUrl) : base(parent, quadrant, depth) { this.Bus = bus; this.NodePeer = nodePeer; this.ApiUrl = ApiUrl; }
private Quadrant getQuadrant() { Quadrant x_quad = Quadrant.MIDDLE , y_quad = Quadrant.MIDDLE; if (this.transform.position.x < 10) { x_quad = Quadrant.LEFT; } else if (this.transform.position.x > 70) { x_quad = Quadrant.RIGHT; } if (this.transform.position.y < 10) { y_quad = Quadrant.BOTTOM; } else if (this.transform.position.y > 50) { y_quad = Quadrant.TOP; } return(addQuadrants(x_quad, y_quad)); }
public QuadVertex() { m_DeltaI = 0.0; m_DeltaJ = 0.0; m_Quadrant = Quadrant.All; m_Length = 0.0; }
void Update() { PuckQuadrant = GetPuckQuadrant(); Player1ScoreText.text = Player1Score.ToString(); Player2ScoreText.text = Player2Score.ToString(); }
public CombatBodyPart RollBodyPart(Quadrant quadrant) { var idx = (int)quadrant.GetIndex(); var bodyParts = Quadrants[idx]; var total = bodyParts.Sum(i => i.Probability); if (total == 0.0f) { return(CombatBodyPart.Undefined); } var rng = ThreadSafeRandom.Next(0.0f, total); var totalProbability = 0.0f; foreach (var bodyPart in bodyParts) { totalProbability += bodyPart.Probability; if (rng < totalProbability) { return((CombatBodyPart)bodyPart.BodyPart); } } return(CombatBodyPart.Undefined); }
private static List <int> m_mapPointCountList; //4个象限的mapPoint /// <summary> /// 通过象限获取对应的mapPoint /// </summary> /// <param name="_quadrant"></param> /// <returns></returns> private static int[,] GetMapPointMatrix(Quadrant _quadrant) { int index = (int)_quadrant; if (m_mapPointList == null) { int[,] mapPointOne = new int[DEFAULT_LENGTH, DEFAULT_LENGTH]; int[,] mapPointTwo = new int[DEFAULT_LENGTH, DEFAULT_LENGTH]; int[,] mapPointThree = new int[DEFAULT_LENGTH, DEFAULT_LENGTH]; int[,] mapPointFour = new int[DEFAULT_LENGTH, DEFAULT_LENGTH]; m_mapPointList = new List <int[, ]>(); m_mapPointList.Add(mapPointOne); m_mapPointList.Add(mapPointTwo); m_mapPointList.Add(mapPointThree); m_mapPointList.Add(mapPointFour); m_mapPointCountList = new List <int>(); m_mapPointCountList.Add(DEFAULT_LENGTH); m_mapPointCountList.Add(DEFAULT_LENGTH); m_mapPointCountList.Add(DEFAULT_LENGTH); m_mapPointCountList.Add(DEFAULT_LENGTH); } return(m_mapPointList[index]); }
/// <summary> /// Gets the depth of the tree rooted at this quadrant. For efficiency, /// this performs no locking. Because of this, the return value should be /// regarded as an approximation. /// </summary> int GetApproximateLargestSubdivisionLevel(Quadrant quadrant) { if (quadrant.IsLeaf) { return(0); } int maxLevel = 1; for (int childIdx = 0; childIdx < 4; ++childIdx) { try { int childLevel = 1 + GetApproximateLargestSubdivisionLevel(quadrant.GetChild(childIdx)); if (childLevel > maxLevel) { maxLevel = childLevel; } } catch (ApplicationException) { // This can happen if the quadrant becomes a leaf due to // a join operation (since we didn't lock it). break; } } return(maxLevel); }
void SubdivideWithoutLocking(Quadrant quadrant) { if (quadrant.SubdivisionLevel >= maxSubdivisionLevel) { return; } if (quadrant.Data.Count <= maxLeafCapacity) { return; } if (!quadrant.TrySubdivide()) { return; } for (int childIdx = 0; childIdx < 4; ++childIdx) { Quadrant child = quadrant.GetChild(childIdx); foreach (var datum in child.Data) { elementsToNodes[datum] = child; } if (child.Data.Count > maxLeafCapacity) { SubdivideWithoutLocking(child); } } }
private void DrawSelectionPlaneReferenceLines(Quadrant quadrant, Transform transform) { Color originalColor = Handles.color; Color lineColor = GridSettings.instance.planeReferenceStyle == ReferenceLineStyle.SingleColor ? GridSettings.instance.planeReferenceColor : GetAxisColor(m_axis); lineColor.a = 1f; Handles.color = lineColor; Vector3 gridPosition = m_gridData.WorldToGridPosition(transform.position); float aStart = ((quadrant & Quadrant.QE) != 0) ? -m_gridData.gridOrigin.GetComponent(aAxis) : 0f; float bStart = ((quadrant & Quadrant.QW) != 0) ? -m_gridData.gridOrigin.GetComponent(bAxis) : 0f; float aEnd = ((quadrant & Quadrant.QE) != 0) ? 0f : m_gridData.gridSize - m_gridData.gridOrigin.GetComponent(aAxis); float bEnd = ((quadrant & Quadrant.QW) != 0) ? 0f : m_gridData.gridSize - m_gridData.gridOrigin.GetComponent(bAxis); Vector3 start = gridPosition.GetComponentVector(m_axis) + AxisUtil.GetVector(aAxis) * aStart; Vector3 end = gridPosition.GetComponentVector(m_axis) + AxisUtil.GetVector(aAxis) * aEnd; Handles.DrawLine(start, end); start = gridPosition.GetComponentVector(m_axis) + AxisUtil.GetVector(bAxis) * bStart; end = gridPosition.GetComponentVector(m_axis) + AxisUtil.GetVector(bAxis) * bEnd; Handles.DrawLine(start, end); Handles.color = originalColor; }
/** * Sum the perimeter of all white leaves in the two specified * quadrants of the sub quad tree rooted at this node. Since * this is a grey node, we just recursively call this routine * on the appropriate children (that may be white nodes). * * @param quad1 the first specified quadrant * @param quad2 the second specified quadrant * @param size the size of the image represented by this node * @return the perimeter of the adjacent nodes */ public override int sumAdjacent(Quadrant quad1, Quadrant quad2, int size) { QuadTreeNode child1 = quad1.child(this); QuadTreeNode child2 = quad2.child(this); size = size / 2; return child1.sumAdjacent(quad1, quad2, size) + child2.sumAdjacent(quad1, quad2, size); }
bool Join(Quadrant quadrant) { // Always lock from top to bottom to avoid deadlocking. quadrant.Lock.EnterExclusiveLock(); try { if (!quadrant.TryJoin(maxLeafCapacity)) { return(false); } foreach (var datum in quadrant.Data) { elementsToNodes[datum] = quadrant; } if (quadrant.Parent != null && quadrant.Data.Count < minLeafCapacity) { candidatesForJoin.TryAdd(quadrant.Parent); } return(true); } finally { quadrant.Lock.ExitExclusiveLock(); } }
/// <summary> /// Returns a body part for a creature defender /// </summary> public void GetBodyPart(Creature defender, Quadrant quadrant) { // get cached body parts table var bodyParts = Creature.GetBodyParts(defender.WeenieClassId); // rng roll for body part var bodyPart = bodyParts.RollBodyPart(quadrant); if (bodyPart == CombatBodyPart.Undefined) { log.Debug($"DamageEvent.GetBodyPart({defender?.Name} ({defender?.Guid}) ) - couldn't find body part for wcid {defender.WeenieClassId}, Quadrant {quadrant}"); Evaded = true; return; } //Console.WriteLine($"AttackHeight: {AttackHeight}, Quadrant: {quadrant & FrontBack}{quadrant & LeftRight}, AttackPart: {bodyPart}"); defender.Biota.PropertiesBodyPart.TryGetValue(bodyPart, out var value); PropertiesBodyPart = new KeyValuePair <CombatBodyPart, PropertiesBodyPart>(bodyPart, value); // select random body part @ current attack height /*BiotaPropertiesBodyPart = BodyParts.GetBodyPart(defender, attackHeight); * * if (BiotaPropertiesBodyPart == null) * { * Evaded = true; * return; * }*/ CreaturePart = new Creature_BodyPart(defender, PropertiesBodyPart); }
public bool IsInQuadrant(Quadrant q) { // check for easy short circuit if (q == Quadrant.All) { return(true); } if ((q & Quadrant.NorthEast) > 0 && PositionX > xyMidPoint && PositionY > xyMidPoint) { return(true); } if ((q & Quadrant.NorthWest) > 0 && PositionX <= xyMidPoint && PositionY > xyMidPoint) { return(true); } if ((q & Quadrant.SouthEast) > 0 && PositionX <= xyMidPoint && PositionY <= xyMidPoint) { return(true); } if ((q & Quadrant.SouthWest) > 0 && PositionX <= xyMidPoint && PositionY <= xyMidPoint) { return(true); } return(false); }
// Create four new Quadrants inside current Quadrant private void Split(QuadrantSize size, QuadrantSize minSize) { bottomLeft = new Quadrant(size, minSize, Vector2Int.zero, this, "0"); bottomRight = new Quadrant(size, minSize, Vector2Int.right, this, "1"); topLeft = new Quadrant(size, minSize, Vector2Int.up, this, "2"); topRight = new Quadrant(size, minSize, Vector2Int.one, this, "3"); }
/// <summary> /// Switches a shared lock on a quadrant to an exclusive lock, returning /// true if the quadrant was not disconnected and kept the same leaf status /// in between the two operations. Also acquires a shared lock on the /// quadrant's parent. If the method returns false, it releases the lock /// on the given quadrant and its parent. /// </summary> /// <remarks> /// This method acquires a lock on the parent before acquiring a lock /// on <paramref name="quadrant"/> to avoid a deadlock with the join /// operation, which acquires a lock on a parent first and then on /// all of its children. /// </remarks> /// <returns><c>true</c>, if the quadrant did not become disconnected or /// changed from a leaf to a non-leaf or vice-versa, <c>false</c> otherwise /// (in which case the lock was released and the parent is not locked).</returns> /// <param name="quadrant">The non-root quadrant for which the current thread /// holds a shared lock. If this method returns true, the current thread /// will hold an exclusive lock on this and a shared lock on its parent. /// Otherwise, the thread will hold no lock on this or its parent.</param> bool SwitchSharedLockToExclusiveLockAndLockParent(Quadrant quadrant) { Debug.Assert(quadrant.Lock.ThreadOwnsSharedLock); Debug.Assert(!quadrant.IsDisconnected); bool wasLeaf = quadrant.IsLeaf; Quadrant parent = quadrant.Parent; Debug.Assert(parent != null, "Quadrant should have a parent."); quadrant.Lock.ExitSharedLock(); parent.Lock.EnterSharedLock(); quadrant.Lock.EnterExclusiveLock(); // After releasing the shared lock, the quadrant could have been // joined into its parent, or the quadrant could have subdivided. if (quadrant.IsDisconnected || (quadrant.IsLeaf != wasLeaf)) { quadrant.Lock.ExitExclusiveLock(); parent.Lock.ExitSharedLock(); return(false); } return(true); }
protected override CommandResult ExecuteCommandCore(Quadrant quadrant) { if (!_input.TryGetCourse("Photon torpedo course", "Ensign Chekov", out var course)) { return(CommandResult.Ok); } TorpedoCount -= 1; var isHit = false; _output.WriteLine("Torpedo track:"); foreach (var sector in course.GetSectorsFrom(_enterprise.SectorCoordinates)) { _output.WriteLine($" {sector}"); if (quadrant.TorpedoCollisionAt(sector, out var message, out var gameOver)) { _output.WriteLine(message); isHit = true; if (gameOver) { return(CommandResult.GameOver); } break; } } if (!isHit) { _output.WriteLine("Torpedo missed!"); } return(quadrant.KlingonsFireOnEnterprise()); }
/// <summary> /// Insert a node with given bounds into this QuadTree. /// </summary> /// <param name="node">The node to insert</param> /// <param name="bounds">The bounds of this node</param> public void Insert(T node, Rect bounds) { if (_bounds.Width == 0 || _bounds.Height == 0) { // todo: localize. throw new InvalidOperationException("You must set a non-zero bounds on the QuadTree first"); } if (bounds.Width == 0 || bounds.Height == 0) { // todo: localize. throw new InvalidOperationException("Inserted node must have a non-zero width and height"); } if (_root == null) { _root = new Quadrant(null, _bounds); } Quadrant parent = _root.Insert(node, bounds); if (_table == null) { _table = new Dictionary <T, Quadrant>(); } _table[node] = parent; }
/// <summary> /// Finds the index of the last point in a monotone chain /// starting at a given point. /// Any repeated points (0-length segments) will be included /// in the monotone chain returned. /// </summary> /// <param name="pts">The coordinates</param> /// <param name="start">The start index</param> /// <returns> /// The index of the last point in the monotone chain starting at <c>start</c>. /// </returns> private static int FindChainEnd(Coordinate[] pts, int start) { int safeStart = start; // skip any zero-length segments at the start of the sequence // (since they cannot be used to establish a quadrant) while (safeStart < pts.Length - 1 && pts[safeStart].Equals2D(pts[safeStart + 1])) { safeStart++; } // check if there are NO non-zero-length segments if (safeStart >= pts.Length - 1) { return(pts.Length - 1); } // determine overall quadrant for chain (which is the starting quadrant) var chainQuad = new Quadrant(pts[safeStart], pts[safeStart + 1]); int last = start + 1; while (last < pts.Length) { // skip zero-length segments, but include them in the chain if (!pts[last - 1].Equals2D(pts[last])) { // compute quadrant for next possible segment in chain var quad = new Quadrant(pts[last - 1], pts[last]); if (quad != chainQuad) { break; } } last++; } return(last - 1); }
private Quadrant getLineQuadrant(Point beginp, Point endp) { Quadrant tempQuadrant = Quadrant.None; if (beginp.X < endp.X && beginp.Y >= endp.Y) { tempQuadrant = Quadrant.First; } if (beginp.X <= endp.X && beginp.Y < endp.Y) { tempQuadrant = Quadrant.Second; } if (beginp.X > endp.X && beginp.Y <= endp.Y) { tempQuadrant = Quadrant.Third; } if (beginp.X >= endp.X && beginp.Y > endp.Y) { tempQuadrant = Quadrant.Forth; } return(tempQuadrant); }
private Quadrant getQuadrant() { Quadrant x_quad = Quadrant.MIDDLE , y_quad = Quadrant.MIDDLE; var elementScreenPos = Camera.main.WorldToScreenPoint(this.transform.position); if (elementScreenPos.x < Screen.width * .15f) { x_quad = Quadrant.LEFT; } else if (elementScreenPos.x > Screen.width * .85f) { x_quad = Quadrant.RIGHT; } if (elementScreenPos.y < Screen.height * .15f) { y_quad = Quadrant.BOTTOM; } else if (elementScreenPos.y > Screen.height * .85f) { y_quad = Quadrant.TOP; } return(addQuadrants(x_quad, y_quad)); }
public void setActions(List <Action> actions, IActionReceiver receiver = null) { this.actions = actions; this.quadrant = getQuadrant(); this.receiver = receiver; regenerate(); }
private void FunctionCalcBoundariesSync(Quadrant map, GregorianDateTime date) { GCLog.Write("Ekadasi Boundaries Calculation START"); RootArray = null; CalculationFinished = false; GregorianDateTime dt = new GregorianDateTime(date); dt.PreviousDay(); dt.PreviousDay(); GCLocation loc = new GCLocation(); TTimeZone tz = new TTimeZone(); loc.Latitude = 0; loc.Longitude = 0; loc.TimeZone = tz; TResultCalendar cal = new TResultCalendar(); cal.EkadasiOnly = true; List <Quadrant> quandrantList = new List <Quadrant>(); quandrantList.Add(map); QuadrantArray qa; map = null; int count = 0, maxCount = 2000; while (quandrantList.Count > 0) { map = quandrantList[0]; quandrantList.RemoveAt(0); if (stopRequested) { break; } map.Details = CalculateQuadrantArray(map, dt, loc, cal, quandrantList); if (RootArray == null) { RootArray = map.Details; } // for testing count++; if (count >= maxCount) { break; } } CalculationFinished = true; GCLog.Write("Ekadasi Boundaries Calculation END"); StopMethodDelegate stopMethod = new StopMethodDelegate(PerformeStop); this.Invoke(stopMethod); }
/// <summary> /// Insert a node with given bounds into this QuadTree. /// </summary> /// <param name="node">The node to insert</param> /// <param name="bounds">The bounds of this node</param> public void Insert(T node, Rect bounds) { if (this.bounds.Width == 0 || this.bounds.Height == 0) { Debug.LogError("BoundsMustBeNonZero!"); } if (bounds.Width == 0 || bounds.Height == 0) { Debug.LogError("BoundsMustBeNonZero!"); } if (this.root == null) { this.root = new Quadrant(null, this.bounds); } Quadrant parent = this.root.Insert(node, bounds); if (this.table == null) { this.table = new Dictionary <T, Quadrant>(); } this.table[node] = parent; }
private Quadrant GetRectangleFromPoints(IList <Vector2> points) { var quadrant = new Quadrant() { LeftMost = new Vector2(float.MaxValue, 0), RightMost = new Vector2(float.MinValue, 0), TopMost = new Vector2(0, float.MinValue), BottomMost = new Vector2(0, float.MaxValue), }; for (int i = 0; i < points.Count; i++) { var point = points[i]; if (point.X < quadrant.LeftMost.X) { quadrant.LeftMost = point; } if (point.X > quadrant.RightMost.X) { quadrant.RightMost = point; } if (point.Y > quadrant.TopMost.Y) { quadrant.TopMost = point; } if (point.Y < quadrant.BottomMost.Y) { quadrant.BottomMost = point; } } return(quadrant); }
public PopulateQuadrant(PopulateRadarData populateRadarData, QuadrantData quadrantData, RandomPositionProvider positionProvider) { this.populateRadarData = populateRadarData; this.quadrantData = quadrantData; this.quadrant = quadrantData.Quadrant; this.positionProvider = positionProvider; }
/// <summary> /// Determines which side of a line a horizontal line segment lies on. /// Used in point in polygon. /// </summary> /// <param name="hr">The horizontal line segment</param> /// <returns>Code indicating the position of the horizontal segment with respect to this line. /// Side.Left if the horizontal segment is to the left of this line; Side.Right if to the /// right of this line; Side.Unknown if the side cannot be determined (this line is /// horizontal). /// </returns> internal override Side GetSide(HorizontalRay hr) { // Express the end of the horizontal in a local system with // the same origin as the circle this arc lies on. IPosition center = m_Circle.Center; QuadVertex pos = new QuadVertex(center, hr.End); Quadrant quad = pos.Quadrant; // Assign the side code, assuming the arc is clockwise. Side result = (quad == Quadrant.NE || quad == Quadrant.SE ? Side.Right : Side.Left); // If the horizontal is apparently to the right of the curve, // but the location in question coincides with the extreme // north point of the circle, reverse the side (it's OK in // the extreme south). if (result == Side.Right) { double maxnorth = center.Y + Circle.Radius; if (Math.Abs(maxnorth - hr.Y) < Constants.TINY) { result = Side.Left; } } // If the arc actually goes anti-clockwise, reverse the side. if (!m_IsClockwise) { result = (result == Side.Left ? Side.Right : Side.Left); } return(result); }
public AxisAlignedRectangle Split(Quadrant quadrant) { Vector2 quarterSize = Size / 4; Vector2 halfSize = Size / 2; Vector2 center = Position; switch (quadrant) { case Quadrant.BottomLeft: center += new Vector2(-quarterSize.x, -quarterSize.y); break; case Quadrant.TopLeft: center += new Vector2(-quarterSize.x, quarterSize.y); break; case Quadrant.BottomRight: center += new Vector2(quarterSize.x, -quarterSize.y); break; case Quadrant.TopRight: center += new Vector2(quarterSize.x, quarterSize.y); break; } return new AxisAlignedRectangle(center, halfSize); }
/** * Create a node in the quad tree. * * @param childType if there's a parent, the type of child * @param nw the node represent the northwest quadrant * @param ne the node represent the northeast quadrant * @param sw the node represent the southwest quadrant * @param se the node represent the southeast quadrant */ private QuadTreeNode(Quadrant quad, QuadTreeNode nw, QuadTreeNode ne, QuadTreeNode sw, QuadTreeNode se, QuadTreeNode parent) { this.quadrant = quad; this.nw = nw; this.ne = ne; this.sw = sw; this.se = se; this.parent = parent; }
private Bitmap ChangeAndRender(MainTile tile, Quadrant.Quadrant q) { var ntile = tile.ChangeQuadrant(tile.Quadrant, q); return ntile.ToQuantified(ntile.ElementStepX, ntile.ElementStepY, ntile.ElementStepX, ntile.ElementStepY, ntile.RefOffsetX, ntile.RefOffsetY) .RenderImage(5000, 5000, new RectangleF(-2000, -2000, 4000, 4000), ScaleMode.STRETCH, new QuantifiedRenderer<IContextual<SubTile>>( (z, s) => z.Context.ToBitmap((int)s.Width, (int)s.Height, ntile), Pens.Blue, Pens.Red), null ).Item; }
private Quadrant addQuadrants(Quadrant q1, Quadrant q2) { Quadrant ret = Quadrant.MIDDLE; switch (q1) { case Quadrant.MIDDLE: switch (q2) { case Quadrant.MIDDLE: ret = Quadrant.MIDDLE; break; case Quadrant.TOP: ret = Quadrant.TOP; break; case Quadrant.BOTTOM: ret = Quadrant.BOTTOM; break; default: ret = Quadrant.MIDDLE; break; } break; case Quadrant.LEFT: switch (q2) { case Quadrant.MIDDLE: ret = Quadrant.LEFT; break; case Quadrant.TOP: ret = Quadrant.TOP_LEFT; break; case Quadrant.BOTTOM: ret = Quadrant.BOTTOM_LEFT; break; default: ret = Quadrant.LEFT; break; } break; case Quadrant.RIGHT: switch (q2) { case Quadrant.MIDDLE: ret = Quadrant.RIGHT; break; case Quadrant.TOP: ret = Quadrant.TOP_RIGHT; break; case Quadrant.BOTTOM: ret = Quadrant.BOTTOM_RIGHT; break; default: ret = Quadrant.RIGHT; break; } break; } return ret; }
public BlipPosition GetRandomPosition(Quadrant quadrant, Circle circle) { var availableBlipPoisitions = this.postitionData[quadrant] .Single(item => item.Circle == circle) .Positions .Where(position => !position.IsUsed).ToArray(); var next = this.random.Next(0, availableBlipPoisitions.Length); var selectedPosition = availableBlipPoisitions[next]; selectedPosition.IsUsed = true; return selectedPosition; }
public bool NextToQuadrant(Quadrant quad) { bool returnable = false; for(int i = X; i < width; i++) { if(quad.IsInQuadrant(i, Y-1) || quad.IsInQuadrant(i, Y+1)) { returnable = true; } } for(int j = Y; j < height; j++) { if(quad.IsInQuadrant(X-1, j) || quad.IsInQuadrant(X+1, j)) { returnable = true; } } return returnable; }
public TerrainNode(TerrainNode parent, Quadrant quad, LatLon bl, LatLon tl, LatLon tr, LatLon br) { Parent = parent; Quadrant = quad; corners = new LatLon[4] { bl, tl, tr, br }; latLonExtents = new Extent(BL.Longitude, BL.Latitude, TR.Longitude, TR.Latitude); var mercBL = RenderWGS84.ToGoogleBing(BL.Longitude, BL.Latitude); var mercTR = RenderWGS84.ToGoogleBing(TR.Longitude, TR.Latitude); meterExtents = new Extent(mercBL.X, mercBL.Y, mercTR.X, mercTR.Y); center = LatLon.Average(corners); splitDepth = 0; Vector3D[] transformed = transformCorners(); this.aabb = BoundingBox.FromPoints(transformed.Select(vec => vec.ToVector3()).ToArray()); generateSplitBox(); }
/// <summary> /// Cuenta el numero de pixeles negros en el cuadrante indicado por /// <c>q</c>. /// </summary> /// <remarks> /// Si la imagen tiene un numero impar de pixeles se incluye la fila /// o columna central, segun el caso. /// </remarks> /// <param name="image">Imagen sobre la que se trabaja</param> /// <param name="q">Cuadrante a analizar</param> /// <returns>Numero de pixeles negros</returns> public static int NumBlackPixelsInQuadrant(FloatBitmap image, Quadrant q) { int n=0; int width = image.Width; int height = image.Height; int halfWidth = width/2; int halfHeight = height/2; switch(q) { case(Quadrant.NW): n=NumPixelsInArea(image,FloatBitmap.Black, 0,0, halfWidth,halfHeight); break; case(Quadrant.NE): n=NumPixelsInArea(image,FloatBitmap.Black, halfWidth,0, width,halfHeight); break; case(Quadrant.SW): n=NumPixelsInArea(image,FloatBitmap.Black, 0,halfHeight, halfWidth,height); break; case(Quadrant.SE): n=NumPixelsInArea(image,FloatBitmap.Black, halfWidth,halfHeight, width,height); break; } return n; }
// Use this for initialization void Start() { #region initialization // NOTICE : DOM // the following is now needed // due to the prefab of 'MainObject' GameObject mainObject = GameObject.FindGameObjectsWithTag("MainObject")[0]; if (GameObject.FindGameObjectsWithTag("MainObject").Length > 1) { GameObject[] mainObjectList = GameObject.FindGameObjectsWithTag("MainObject"); for (int i = 0; i < mainObjectList.Length; ++i) { if (mainObjectList[i].GetComponent<GameStateManager>().objectSaved) mainObject = mainObjectList[i]; } } // Ensures all necessary scripts are added for the MainObject gameStateManagerRef = mainObject.GetComponent<GameStateManager>(); gameStateManagerRef.EnsureCoreScriptsAdded(); gameStateManagerRef.EnsureScriptAdded("TouchController"); soundManagerRef = mainObject.GetComponent<SoundManager>(); screenManagerRef = mainObject.GetComponent<ScreenManager>(); #region initialize references backsidePivotReference = GameObject.Find("backsidepivot"); coverupPivotReference = GameObject.Find ("coveruppivot"); tornBacksidePieceReference = GameObject.Find ("tornBacksidePiece"); //sets the reference of the touchcontroller to the touchcontroller script. touchController = mainObject.GetComponent<TouchController>(); //sets the reference of the backsidesideReference to the backside or "fold" backsideReference = backsidePivotReference.transform.FindChild("backside").gameObject; backSideInitialColor = backsideReference.GetComponent<MeshRenderer>().material.color; //sets the reference of the backsideCollisionReference to the platforms on the back of the paper. backsideCollisionReference = GameObject.FindGameObjectsWithTag("FoldPlatform"); //sets the camera reference to the main camera cameraReference = GameObject.Find("Main Camera"); //sets the player reference to the player playerReference = GameObject.Find("Player_Prefab"); //sets the backgroundTransform to the transform of the background paper. origBackground = GameObject.FindGameObjectWithTag("background"); backgroundTransform = origBackground.transform; //sets backgroundBounds to the bounds of the background paper backgroundBounds = backgroundTransform.GetComponent<MeshFilter>().mesh.bounds; //sets changeMeshScript to the ChangeMeshScript which removes and restores triangles. changeMeshScript = this.GetComponent<ChangeMeshScript>(); tearReference = GameObject.Find("Tear_Manager").GetComponent<TearManager>(); coverupReference = coverupPivotReference.transform.FindChild("coverup").gameObject; tearPaperMesh = GameObject.Find("backside").GetComponent<MeshFilter>().mesh; unfoldCollisionReference = GameObject.Find("Player_Prefab").GetComponent<UnfoldCollision>(); shadowReference = GameObject.Find("shadow"); rayTraceBlockRef = GameObject.Find("rayTraceBlocker"); paperBorderInsideRef = GameObject.Find("paper_border_inside"); paperBorderOutsideRef = GameObject.Find("paper_border_outside"); worldCollisionRef = mainObject.GetComponent<WorldCollision>(); backsideTriangles = tearPaperMesh.triangles; #endregion //sets original position and rotation to its starting position and rotation foldOriginalRotation = backsidePivotReference.transform.rotation; foldOriginalPosition = backsidePivotReference.transform.position; //sets starting position coverup's starting position coverupStartingPosition = coverupPivotReference.transform.position; //sets coverup's original position to the vector required for the tranforms to work properly coverupOriginalPosition = new Vector3(0,0,-3); //sets coverup's original rotation to its starting rotation coverupOriginalRotation = coverupPivotReference.transform.rotation; coverupPrefab = coverupPivotReference.transform; foldPrefab = backsidePivotReference.transform; //initializes variables to defaults. fingerList = new List<Vector2>(); backgroundObjMax = new Vector2(); backgroundObjMin = new Vector2(); posModifier = new Vector3(); posModLastValid = new Vector3(); unfoldPosModifier = new Vector3(); foldTmpZLayer = GVariables.zFoldLayer - 1; coverupTmpZLayer = GVariables.zCoverLayer -1; prevMousestate = false; currMouseState = false; firstTouch = false; isFolded = false; overPlayer = false; needsToUnfold = false; isOffPaper = true; backsideIsInstantiated = false; currentlyFolding = false; missingTriangles = new List<Vector3>(); //changeMeshScript.GrabUpdatedPlatforms("FoldPlatform"); deletedTri = new int[0]; startingQuadrant = Quadrant.NONE; currentQuadrant = Quadrant.NONE; foldEdge = Edge.BuildManifoldEdges(backsideReference.GetComponent<MeshFilter>().mesh); guiEnable = false; blah = false; foldInput = false; prevFoldInput = false; #endregion }
/** * Construct a <tt>grey</tt> image node. * * @param quadrant the quadrant that this node represents * @param parent the parent node in the quad tree. */ public GreyNode(Quadrant quadrant, QuadTreeNode parent) : base(quadrant, parent) { ;}
public HemisphereTerrainNode(HemisphereTerrainNode parent, Quadrant quad, LatLon bl, LatLon tr) : base(parent, quad, bl, tr) { }
private void Swap(Quadrant i, Quadrant j) { int x = count[(int)i]; count[(int)i] = count[(int)j]; count[(int)j] = x; }
// Parses a game state from a string. On success, returns 1. On failure, // returns 0. private int ParseGameState(string boardLayout) { List<Fleet> fleetbuilder = new List<Fleet>(); List<Planet> planetBuilder = new List<Planet>(); Dictionary<int, EditablePlayer> playerBuilder = new Dictionary<int, EditablePlayer>(); int planetID = 0; string[] lines = boardLayout.Replace("\r", "").Split('\n'); for (int i = 0; i < lines.Length; ++i) { string line = lines[i]; int commentBegin = line.IndexOf('#'); if (commentBegin >= 0) { line = line.Substring(0, commentBegin); } if (line.Trim().Length == 0) { continue; } string[] tokens = line.Split(' '); if (tokens.Length == 0) { continue; } switch (tokens[0]) { default: break; case "P": case "p": #region Add planet { if (tokens.Length != 6) { return 0; } Planet planet = BuildPlanet(planetID++, tokens); planetBuilder.Add(planet); EditablePlayer player = EnsurePlayer(playerBuilder, planet.Owner); player.Planets.Add(planet); player.ShipsOnBase += planet.NumShips; player.ShipsHeavyPoint.X += planet.X * (double)planet.NumShips; player.ShipsHeavyPoint.Y += planet.Y * (double)planet.NumShips; int wishId = WishList.IndexOf(planet.PlanetID); if (wishId > -1) { if (planet.IsMine) { WishList.RemoveAt(wishId); } else { planet.IsOnWishList = true; } } #endregion } break; case "F": case "f": { #region AddFleet if (tokens.Length != 7) { return 0; } Fleet fleet = BuildFleet(tokens); EditablePlayer player = EnsurePlayer(playerBuilder, fleet.Owner); player.Fleets.Add(fleet); player.Targets.Add(fleet.DestinationPlanet); fleetbuilder.Add(fleet); player.ShipsInTransit += fleet.NumShips; #endregion } break; } } AllPlanetsOnPlanetId = planetBuilder.ToDictionary(item => item.PlanetID); //That's me EditablePlayer personalityBuilder = EnsurePlayer(playerBuilder, 1); Me = new Player(personalityBuilder.Fleets, personalityBuilder.Planets, personalityBuilder.Targets); Me.ShipCountInBase = personalityBuilder.ShipsOnBase; Me.ShipCountInTransit = personalityBuilder.ShipsInTransit; EditablePlayer neutralityBuilder = EnsurePlayer(playerBuilder, 0); Neutral = new Player(neutralityBuilder.Fleets, neutralityBuilder.Planets, personalityBuilder.Targets); Neutral.ShipCountInBase = neutralityBuilder.ShipsOnBase; Neutral.ShipCountInTransit = neutralityBuilder.ShipsInTransit; All = new Player(fleetbuilder, planetBuilder, new List<int>()); foreach (EditablePlayer player in playerBuilder.Values) { TotalFleetCount += player.ShipsOnBase + player.ShipsInTransit; } foreach (Fleet attackForce in All.Fleets) { Planet target = AllPlanetsOnPlanetId[attackForce.DestinationPlanet]; if (target.Owner != attackForce.Owner) { target.IsUnderAttack = true; } target.AddArmada(attackForce); //EditablePlayer player = EnsurePlayer(playerBuilder, target.PlanetID); //player.ShipsHeavyPoint.X += target.X * attackForce.NumShips; //player.ShipsHeavyPoint.Y += target.Y * attackForce.NumShips; } EditablePlayer enemy = EnsurePlayer(playerBuilder, 2); EnemyShipFocus = enemy.ShipsHeavyPoint.Calculate(enemy.ShipsInTransit + enemy.ShipsOnBase); EditablePlayer me = EnsurePlayer(playerBuilder, 1); OwnShipFocus = me.ShipsHeavyPoint.Calculate(me.ShipsOnBase); DeterminePlanetStrengthOnFleetArrival(); if (TravelMap == null) { TravelMap = PlanetaryTravelRouteDictionary.Create(planetBuilder); Universe.InitialTotalFleetSize = TotalFleetCount; Universe.InitialFleetToPlanetRatio = (Universe.InitialTotalFleetSize - 200) / (double)(All.Planets.Count - 2); Universe.Difficulty = (Universe.InitialFleetToPlanetRatio - 30) / 5; FannyHeirdooBot.strategy = new DefensiveBotStrategy(); } if (Universe.TurnCount % 15 == 0) { WishList.Clear(); } return 1; }
// Update is called once per frame void Update() { // Added by Dom // Ensures my own boolean for currently folding // is set false accordinly if (currentlyFolding && ((!Input.GetMouseButton(1) && !gameStateManagerRef.OnMobileDevice()) || ((gameStateManagerRef.GetInputManager().GetcurrPressState().Equals(InputManager.PressState.UP) || gameStateManagerRef.GetInputManager().GetcurrPressState().Equals(InputManager.PressState.JUST_RELEASED)) && gameStateManagerRef.OnMobileDevice()))) { currentlyFolding = false; } if(Input.GetKey(KeyCode.P) || (gameStateManagerRef.OnMobileDevice())){ guiEnable = true; } else{ guiEnable = false; } // if (GVariables.TearPieceCoveringFold) // { // backsideReference.GetComponent<MeshRenderer>().material.color = Color.gray; // } // else // { // backsideReference.GetComponent<MeshRenderer>().material.color = backSideInitialColor; // } //foldInput = false; if (tearReference.HaveTornOnce && !backsideIsInstantiated) { GameObject[] tempBackgroundObjs; tornPieceReference = GameObject.Find("paper_CuttPieceOfPaper"); tempBackgroundObjs = GameObject.FindGameObjectsWithTag("background"); foreach(GameObject temp in tempBackgroundObjs){ if(temp.name == "paper_LargerPiece"){ // missingTriangles = changeMeshScript.DeletePlatformsFromMissingTriangles(backsideTriangles, // temp.GetComponent<MeshFilter>().mesh.triangles, backsideReference.transform, "FoldPlatform"); tornBackground = temp; tearPaperMesh = temp.GetComponent<MeshFilter>().mesh; // changeMeshScript.GrabPlatformsInWorld("FoldPlatform"); // changeMeshScript.GrabPlatformsInWorld("Platform"); } else if( temp.name == "paper_CuttPieceOfPaper") { deletedTri = temp.GetComponent<MeshFilter>().mesh.triangles; } } //changeMeshScript.DeletePlatformsFromMissingTriangles(deletedTri, // backsideReference.transform ,"FoldPlatform"); //changeMeshScript.UpdateAfterTear("FoldPlatform"); //changeMeshScript.UpdateAfterTear("Platform"); backsideIsInstantiated = true; backsideReference.GetComponent<MeshFilter>().mesh = tearPaperMesh; backsideReference.GetComponent<MeshCollider>().sharedMesh = tearPaperMesh; shadowReference.GetComponent<MeshCollider>().sharedMesh = tearPaperMesh; rayTraceBlockRef.GetComponent<MeshCollider>().sharedMesh = tearPaperMesh; shadowReference.GetComponent<MeshFilter>().mesh = tearPaperMesh; rayTraceBlockRef.GetComponent<MeshFilter>().mesh = tearPaperMesh; paperBorderInsideRef.GetComponent<MeshCollider>().sharedMesh = tearPaperMesh; paperBorderInsideRef.GetComponent<MeshFilter>().mesh = tearPaperMesh; paperBorderOutsideRef.GetComponent<MeshCollider>().sharedMesh = tearPaperMesh; paperBorderOutsideRef.GetComponent<MeshFilter>().mesh = tearPaperMesh; backsideTriangles = tearPaperMesh.triangles; tornBacksidePieceReference.GetComponent<MeshFilter>().mesh = tornPieceReference.GetComponent<MeshFilter>().mesh; // tornBacksidePieceReference.GetComponent<MeshCollider>().sharedMesh = // tornPieceReference.GetComponent<MeshFilter>().mesh; tearInitialColor = new Color(0.8f, 0.8f, 0.8f, 1.0f); firstFoldAfterTear = true; foldEdge = Edge.BuildManifoldEdges(tearPaperMesh); // changeMeshScript.PrintColliderEnabled(); // changeMeshScript.ReapplyChanges(); // changeMeshScript.PrintColliderEnabled(); } //Try to set logic accordingly when on a tearing level try { if(((Input.GetMouseButton(1) || (gameStateManagerRef.GetInputManager().GetFingerGesture().Equals(InputManager.FingerGesture.FOLD) && touchController.ReturnTouchType() != TouchType.NONE)) && !tearReference.GetComponent<TearManager>().PlayerMovingPlatformState) && ( prevFoldInput || (!playerReference.GetComponent<TWCharacterController>().qDown && !playerReference.GetComponent<TWCharacterController>().eDown && !playerReference.GetComponent<TWCharacterController>().getFalling() ))) { foldInput = true; } else { foldInput = false; } } catch { //This logic will be hit on NON - Tearing levels if(Input.GetMouseButton(1)) { foldInput = true; } } //gets the current touch type from the touch controller touchType = touchController.ReturnTouchType(); //gets the current finger positions from the touch controller fingerList = touchController.GetFingerPositions(); //initializes three new vectors, one for each of the two fingers needed for folding, //and one for the average finger position. Vector3 fingerPosition1 = new Vector3(); Vector3 fingerPosition2 = new Vector3(); avgFingerPos = new Vector3(); //if there are 2 fingers on the screen, //set the finger positions to the corresponding world positions, //then finds the average of the two positions. /*if(fingerList.Count == 2) { fingerPosition1 = Camera.main.ScreenToWorldPoint(fingerList[0]); fingerPosition2 = Camera.main.ScreenToWorldPoint(fingerList[1]); avgFingerPos.x = (fingerPosition1.x+fingerPosition2.x)/2; avgFingerPos.y = (fingerPosition1.y+fingerPosition2.y)/2; avgFingerPos.z = -1; lastFingerPosition = avgFingerPos; }*/ //or if the right mouse button is down, //sets the average finger position to the world coordinates of the mouse position, //also sets currMouse state to true, so we know if the mouse is pressed down. if(foldInput){ avgFingerPos = Camera.main.ScreenToWorldPoint(Input.mousePosition); avgFingerPos.z = -1; currMouseState = true; lastFingerPosition = avgFingerPos; } //if the right mouse button is not pressed, set currMouseState to false, //so we know we arn't using the mouse. if(!foldInput){ currMouseState = false; } //if we are not touching the screen, and not clicking the right mouse button... if(touchType == TouchType.NONE && !foldInput) { //if the last state was a 2 finger touch, or the right mouse button was pressed, and had just been folding, if((prevFoldInput || prevMousestate) && firstTouch) { //set firstTouch back to false so we know we are done folding, and can now unfold or refold firstTouch = false; currentQuadrant = Quadrant.NONE; //if the fold is over the player, unfold. if(unfoldCollisionReference.getOverPlayer()) { blah = true; needsToUnfold = true; foldSmoothPosition = new Vector3(lastFingerPosition.x -origin.x + posModifier.x, lastFingerPosition.y - origin.y + posModifier.y, foldTmpZLayer); startDampTime = Time.time; coverupSmoothPosition = lastFingerPosition - origin + posModifier; coverupSmoothPosition.z = coverupTmpZLayer; } //if the fold is not over the player... else{ setDownFold(); } } } //if there are two fingers on the screen or right mouse button is pressed... else if(foldInput && !needsToUnfold) { //if this is the first touch to start a fold.. if(!firstTouch) { HandleScreenChanges(); if(!unfoldCollisionReference.getOverPlayer() && !GVariables.TearPieceCoveringFold) { //if the paper is not already folded and the user's fingers are on the fold border... if(onFoldBorder(avgFingerPos) && !isFolded) { //set the position to its original position, so the transforms work properly backsidePivotReference.transform.position = foldOriginalPosition; foreach(Transform child in transform) { origin = avgFingerPos; origin.z = 0; } //sets first touch to true so we know we are now folding. firstTouch = true; //brings back and removed triangles in platforms. changeMeshScript.RevertChanges(); //set the unfold position using where the fold started, so we know where to unfold to if the fold is invalid. foldUnfoldPosition = findUnfoldPosition(avgFingerPos, unfoldReference) - origin; //set the coverup unfold position using where the fold started, so we know where to unfold to if the fold is invalid. coverupUnfoldPosition = findUnfoldPosition(avgFingerPos, unfoldReference); coverupUnfoldPosition = new Vector3(coverupUnfoldPosition.x - origin.x, coverupUnfoldPosition.y - origin.y, coverupTmpZLayer); posModifier = Vector3.zero; firstTouchPosition = avgFingerPos; justUnfolded = false; startingQuadrant = ReturnSidePressed(avgFingerPos); currentQuadrant = startingQuadrant; } //else if the paper is folded, and the user's fingers are on the edge of the fold... else if(onUnfoldBorder(avgFingerPos) && isFolded) { isUnfoldingOnPaper = true; //sets first touch to true so we know we are folding. firstTouch = true; //brings back and removed triangles in platforms. changeMeshScript.RevertChanges(); //sets the unfold position to the last valid position (the last fold position) so it will unfold to the proper position if the fold is invalid foldUnfoldPosition = foldLastValidPos; //sets the unfold position to the last valid position (the last fold position) so it will unfold to the proper position if the fold is invalid coverupUnfoldPosition = coverupLastValidPos; posModifier = findPositionOffset(); justUnfolded = false; } //gets the position of the user's fingers when they first start the fold. } } //if the first touch of the fold already happened and we are folding... if(firstTouch && (!gameStateManagerRef.OnMobileDevice() || gameStateManagerRef.GetInputManager().GetFingerGesture().Equals(InputManager.FingerGesture.FOLD))) { //sets the finger position as the average finger position offset by the origin, //so we can get a position relative to the origin of the fold. currentQuadrant = ReturnSidePressed(avgFingerPos); fingerPos = avgFingerPos - origin+ posModifier - unfoldPosModifier; //if the finger positions are 0, return becuase it can mess up calculations if (fingerPos.x == 0 && fingerPos.y == 0) { return; } //if the user's fingers are on the paper background, do the transforms normally, //and set the isOffPaper bool to false so we know it is on the paper //float distance = Mathf.Sqrt(Mathf.Pow((firstTouchPosition.x - avgFingerPos.x),2f)+Mathf.Pow((firstTouchPosition.y-avgFingerPos.y),2f)); if(!offPaper(avgFingerPos) || currentQuadrant != startingQuadrant){ currentlyFolding = true; DoFoldTransforms(); DoCoverupTransforms(); isOffPaper = false; //if (!soundManagerRef.IsAudioPlaying("paperFold1", "SFX")) //{ // soundManagerRef.PlayAudio("paperFold1", "SFX"); //} //else soundManagerRef.StopSound("paperFold1", "SFX"); } //else if te user's fingers are off the paper, set the position and rotation back to defaults, //to give the illusion of completely unfolding. Also sets the isOffPaper bool to true, //so we know they are off the paper. else{ currentlyFolding = false; isUnfoldingOnPaper = false; backsidePivotReference.transform.position = foldOriginalPosition; backsidePivotReference.transform.rotation = foldOriginalRotation; coverupPivotReference.transform.position = coverupStartingPosition; coverupPivotReference.transform.rotation = coverupOriginalRotation; isOffPaper = true; isFolded = false; firstTouch = false; //prevTouchType = TouchType.NONE; prevMousestate = false; currentQuadrant = Quadrant.NONE; prevFoldInput = false; } } } // Debug.Log("FoldSmooth: " + foldSmoothPosition); // Debug.Log("FoldUnfold: " + foldUnfoldPosition); //If we need to unfold the paper... if(needsToUnfold) { //use smooth damp to get a smooth unfold for fold. foldSmoothPosition = Vector3.SmoothDamp(foldSmoothPosition, foldUnfoldPosition, ref velocity, .3f); //Do the transforms on the smooth position, which is the DoFoldTransforms function without the rotations backsidePivotReference.transform.position = (new Vector3(foldSmoothPosition.x + origin.x, foldSmoothPosition.y+ origin.y, 0)); //use smooth damp to get a smooth unfold for coverup. coverupSmoothPosition = Vector3.SmoothDamp(coverupSmoothPosition, coverupUnfoldPosition, ref velocity, .3f); //Do the transforms on the smooth position for coverup coverupPivotReference.transform.position = coverupOriginalPosition; coverupPivotReference.transform.position = new Vector3(origin.x + (coverupSmoothPosition.x)/2, origin.y + (coverupSmoothPosition.y)/2, coverupTmpZLayer); // if (isUnfoldingOnPaper) // { // backsidePivotReference.transform.rotation = foldOriginalRotation; // float angleInDegrees = Mathf.Rad2Deg * (2 * Mathf.Atan2(foldSmoothPosition.y, foldSmoothPosition.x)); // backsidePivotReference.transform.Rotate(Vector3.forward, angleInDegrees); // // coverupPivotReference.transform.rotation = coverupOriginalRotation; // angleInDegrees = Mathf.Rad2Deg * Mathf.Atan2(coverupSmoothPosition.y, coverupSmoothPosition.x); // coverupPivotReference.transform.Rotate(Vector3.forward, angleInDegrees); // } backsidePivotReference.transform.Translate(new Vector3(0, 0, 0)); backsidePivotReference.transform.Translate (new Vector3(origin.x, -origin.y, foldTmpZLayer)); // do the transformations on the smooth rotation for backside and coverup backsidePivotReference.transform.rotation = foldOriginalRotation; float angleInDegrees2 = Mathf.Rad2Deg * (2 * Mathf.Atan2(foldSmoothPosition.y, foldSmoothPosition.x)); backsidePivotReference.transform.Rotate(Vector3.forward, angleInDegrees2); coverupPivotReference.transform.rotation = coverupOriginalRotation; angleInDegrees2 = Mathf.Rad2Deg * Mathf.Atan2(coverupSmoothPosition.y, coverupSmoothPosition.x); coverupPivotReference.transform.Rotate(Vector3.forward, angleInDegrees2); //if the smooth position is off the paper, set needsToUnfold to false so we know we no longer need to unfold, //and set the position and rotation back to dafault positions. since it is off the paper, set isFolded to false. //if(foldSmoothPosition.x <= -6 -origin.x ||foldSmoothPosition.x >= 6 -origin.x || foldSmoothPosition.y <=-4 -origin.y|| foldSmoothPosition.y >=4-origin.y){ //float dist = Mathf.Sqrt(Mathf.Pow((foldUnfoldPosition.x - foldSmoothPosition.x),2f)+Mathf.Pow((foldUnfoldPosition.y-foldSmoothPosition.y),2f)); if(offPaper(foldSmoothPosition + origin) && currentQuadrant == startingQuadrant){ needsToUnfold = false; backsidePivotReference.transform.position = foldOriginalPosition; backsidePivotReference.transform.rotation = foldOriginalRotation; coverupPivotReference.transform.position = coverupStartingPosition; coverupPivotReference.transform.rotation = coverupOriginalRotation; isFolded = false; isUnfoldingOnPaper = false; justUnfolded = true; } //if the smooth damp doesn't bring it off the paper (bringing back to a folded position), have the smooth damp end when the time //runs out. Check if the fold is on the paper or not so we know if it is folded. else if(Time.time - startDampTime > 0.8F){ isUnfoldingOnPaper = false; needsToUnfold = false; justUnfolded = true; Vector3 tempVec = foldSmoothPosition + origin; //Debug.Log("When is this called?"); if(!offPaper(tempVec)){ isOffPaper = false; lastFingerPosition = tempVec; setDownFold(); } else{ //Debug.Log("This one too?"); // failsafe for if/when the fold never completely makes it back off the paper backsidePivotReference.transform.position = foldOriginalPosition; backsidePivotReference.transform.rotation = foldOriginalRotation; coverupPivotReference.transform.position = coverupStartingPosition; coverupPivotReference.transform.rotation = coverupOriginalRotation; isOffPaper = true; isFolded = false; } } } //sets the previous touch and mouse states to the current ones. // // PLEASE DO NOT TOUCH TORN PIECE MATERIAL HERE -> J.C. // //prevTouchType = touchType; prevMousestate = currMouseState; prevFoldInput = foldInput; if(unfoldCollisionReference.getOverPlayer()){ backsideReference.GetComponent<MeshRenderer>().material.color = Color.gray; } else if(tearReference.HaveTornOnce){ if(GVariables.TearPieceCoveringFold){ //tornPieceReference.GetComponent<MeshRenderer>().material.color = tearInitialColor; backsideReference.GetComponent<MeshRenderer>().material.color = Color.gray; } else if(GVariables.FoldPieceCoveringTear){ backsideReference.GetComponent<MeshRenderer>().material.color = backSideInitialColor; //tornPieceReference.GetComponent<MeshRenderer>().material.color = Color.gray; } else{ //tornPieceReference.GetComponent<MeshRenderer>().material.color = tearInitialColor; backsideReference.GetComponent<MeshRenderer>().material.color = backSideInitialColor; } } else{ backsideReference.GetComponent<MeshRenderer>().material.color = backSideInitialColor; } }
protected TerrainNode(TerrainNode parent, Quadrant quad, LatLon bl, LatLon tl, LatLon tr, LatLon br, int splitD) : this(parent, quad, bl, tl, tr, br) { this.splitDepth = splitD; }
/// <summary> /// create a new heightField that has the same LOD as the source, /// and 1/4 the area of the source. Height points are copied from one /// quadrant of the source. /// If the heightField needs to be higher LOD, it will be adjusted /// later and the required points will be generated. /// </summary> /// <param name="t"></param> /// <param name="src"></param> /// <param name="quad"></param> public HeightField(Tile t, HeightField src, Quadrant quad) : base() { tile = t; // in this case we will make the new heightField have the same LOD as // the source. The LOD will be adjusted upward later if necessary. Init(src.metersPerSample); Debug.Assert((numSamples * metersPerSample * 2) == ( src.metersPerSample * src.numSamples), "creating heightfield from source that is not next lower LOD"); int xoff = 0; int zoff = 0; switch ( quad ) { case Quadrant.Northeast: xoff = src.numSamples / 2; zoff = 0; break; case Quadrant.Northwest: xoff = 0; zoff = 0; break; case Quadrant.Southeast: xoff = src.numSamples / 2; zoff = src.numSamples / 2; break; case Quadrant.Southwest: xoff = 0; zoff = src.numSamples / 2; break; } // copy from the source heightMap this.CopyHeightFieldScaleUp(src.heightMap, 1, xoff, zoff, src.numSamples); // compute the min and max extents of this heightField, since nobody else is // going to do it. // XXX - do we need to do this? minHeight = float.MaxValue; maxHeight = float.MinValue; foreach ( float h in heightMap ) { if ( h < minHeight ) { minHeight = h; } if ( h > maxHeight ) { maxHeight = h; } } // generate the height points that were not filled in above //WorldManager.Instance.TerrainGenerator.GenerateHeightField(location, Size, metersPerSample, // heightMap, out minHeight, out maxHeight, src.metersPerSample); UpdateBounds(); }
public IEnumerable<Thing> GetByQuadrant(Quadrant quadrant) { using (var connection = connectionFactory.Connect()) { return connection.Select<Thing>("Quadrantid = {0}", quadrant); } }
/** * Create an image which is represented using a QuadTreeNode. * * @param size size of image * @param center_x x coordinate of center * @param center_y; y coordinate of center * @param parent parent quad tree node * @param quadrant the quadrant that the sub tree is in * @param level the level of the tree */ public static QuadTreeNode createTree(int size, int center_x, int center_y, QuadTreeNode parent, Quadrant quadrant, int level) { QuadTreeNode node; int intersect = checkIntersect(center_x, center_y, size); size = size / 2; if(intersect == 0 && size < 512) { node = new WhiteNode(quadrant, parent); } else if(intersect == 2) { node = new BlackNode(quadrant, parent); } else { if(level == 0) { node = new BlackNode(quadrant, parent); } else { node = new GreyNode(quadrant, parent); QuadTreeNode sw = createTree(size, center_x - size, center_y - size, node, Quadrant.cSouthWest, level - 1); QuadTreeNode se = createTree(size, center_x + size, center_y - size, node, Quadrant.cSouthEast, level - 1); QuadTreeNode ne = createTree(size, center_x + size, center_y + size, node, Quadrant.cNorthEast, level - 1); QuadTreeNode nw = createTree(size, center_x - size, center_y + size, node, Quadrant.cNorthWest, level - 1); node.setChildren(nw, ne, sw, se); } } return node; }
/** * Sum the perimeter of all white leaves in the two specified * quadrants of the sub quad tree rooted at this node. * * @param quad1 the first specified quadrant * @param quad2 the second specified quadrant * @param size the size of the image represented by this node. * @return the perimeter of the adjacent nodes */ abstract public int sumAdjacent(Quadrant quad1, Quadrant quad2, int size);
public void setActions(List<Action> actions) { this.actions = actions; this.quadrant = getQuadrant (); regenerate (); }
/// <summary> /// Creates new <c>Orientation</c> based on the supplied horizontal ray. /// </summary> /// <param name="hr"></param> internal Orientation(HorizontalRay hr) { // Remember the stuff we were supplied (since we are not starting // with a divider, it has to be null). m_Divider = null; m_IsStart = false; // The horizontal segment is ALWAYS at the very start of the // north-west quadrant. m_Quadrant = Quadrant.NW; // Convert the deltas into the IJ coordinate system for the // north-west quadrant (the angle defined with I/J should // evaluate to zero, since the horizontal segment is at the // start of the quadrant). m_DeltaI = 0.0; m_DeltaJ = hr.EndX - hr.StartX; }
public void ResetFold() { // UnityEngine.Debug.Log("STUFF"); changeMeshScript.RevertWorld(); // GameObject[] tempArray = GameObject.FindGameObjectsWithTag("background"); // foreach(GameObject g in tempArray) // { // if(origBackground.Equals(g)) // { //// origBackground.GetComponent<MeshRenderer>().enabled = true; //// origBackground.GetComponent<MeshCollider>().enabled = true; //// g.SetActive(true); // } // else // { // //g.transform.position = gameObject.transform.position; // // g.SetActive(false); // } // } if(tearReference.MainWorldCutPaper != null) { tearReference.MainWorldCutPaper.transform.position = origBackground.transform.position; tearReference.MainWorldCutPaper.transform.rotation = origBackground.transform.rotation; } prevMousestate = false; currMouseState = false; firstTouch = false; isFolded = false; overPlayer = false; needsToUnfold = false; isOffPaper = true; backsideIsInstantiated = false; missingTriangles = new List<Vector3>(); firstFoldAfterTear = false; //changeMeshScript.GrabUpdatedPlatforms("FoldPlatform"); deletedTri = new int[0]; backsideIsInstantiated = false; currentlyFolding = false; GVariables.FoldPieceCoveringTear = false; GVariables.TearPieceCoveringFold = false; backsidePivotReference.transform.position = foldOriginalPosition; backsidePivotReference.transform.rotation = foldOriginalRotation; coverupPivotReference.transform.position = coverupStartingPosition; coverupPivotReference.transform.rotation = coverupOriginalRotation; //tearReference.DeathReset(); backsideReference.GetComponent<MeshCollider>().sharedMesh = origBackground.GetComponent<MeshFilter>().mesh; backsideReference.GetComponent<MeshFilter>().mesh = origBackground.GetComponent<MeshFilter>().mesh; backsideTriangles = backsideReference.GetComponent<MeshFilter>().mesh.triangles; shadowReference.GetComponent<MeshCollider>().sharedMesh = backsideReference.GetComponent<MeshFilter>().mesh; rayTraceBlockRef.GetComponent<MeshCollider>().sharedMesh = backsideReference.GetComponent<MeshFilter>().mesh; shadowReference.GetComponent<MeshFilter>().mesh = backsideReference.GetComponent<MeshFilter>().mesh; rayTraceBlockRef.GetComponent<MeshFilter>().mesh = backsideReference.GetComponent<MeshFilter>().mesh; paperBorderInsideRef.GetComponent<MeshCollider>().sharedMesh = backsideReference.GetComponent<MeshFilter>().mesh; paperBorderInsideRef.GetComponent<MeshFilter>().mesh = backsideReference.GetComponent<MeshFilter>().mesh; paperBorderOutsideRef.GetComponent<MeshCollider>().sharedMesh = backsideReference.GetComponent<MeshFilter>().mesh; paperBorderOutsideRef.GetComponent<MeshFilter>().mesh = backsideReference.GetComponent<MeshFilter>().mesh; startingQuadrant = Quadrant.NONE; currentQuadrant = Quadrant.NONE; foldEdge = Edge.BuildManifoldEdges(backsideReference.GetComponent<MeshFilter>().mesh); unfoldCollisionReference.restart(); blah = false; foldInput = false; prevFoldInput = false; }
/// <summary> /// Defines orientation info. /// </summary> /// <param name="orient">The orientation position.</param> void SetOrient(IPosition orient) { if (m_Divider==null) return; // Get the position of the point that the divider meets. IPointGeometry loc = (m_IsStart ? m_Divider.From : m_Divider.To); // Figure out the deltas of the orientation point with respect to the point. double dx = orient.X - loc.X; double dy = orient.Y - loc.Y; // What quadrant are we in? m_Quadrant = WhatQuadrant(dx,dy); // Convert the deltas into an IJ coordinate system. When we // calculate I/J, it will always give us tan(angle) in each // successive quadrant, with the start of the quadrant resulting // in an angle of zero, and the end of the quadrant resulting in // an angle just less than infinity. switch (m_Quadrant) { case Quadrant.NE: { m_DeltaI = dx; m_DeltaJ = dy; return; } case Quadrant.SE: { m_DeltaI = -dy; m_DeltaJ = dx; return; } case Quadrant.SW: { m_DeltaI = -dx; m_DeltaJ = -dy; return; } case Quadrant.NW: { m_DeltaI = dy; m_DeltaJ = -dx; return; } } string msg = String.Format("Orientation.SetOrient - Quadrant error at {0:0.0000}N {1:0.0000}E", loc.Y, loc.X); throw new Exception(msg); }
static List<Quadrant> SpacialPartition(int mapSize, double splitChance, double roomChance, PseudoRandom rnd) { Quadrant first = new Quadrant(0,0, mapSize, mapSize, 0, 0); List<Quadrant> next = first.QuarterQuadrant(rnd, roomChance); List<Quadrant> final = new List<Quadrant>(); while(next.Count != 0) { int index = 0; double split = Math.Round(rnd.Next(), 2); if(split < splitChance) { List<Quadrant> subs = next[index].QuarterQuadrant(rnd, roomChance); if(subs.Count == 0) { final.Add(next[index]); } else { next.AddRange(subs); } } else { final.Add(next[index]); } next.RemoveAt(index); } return final; }
/** * Create a leaf node in the Quad Tree. * * @param childType if there's a parent, the type of child this node represents * @param parent the parent quad tree node */ public QuadTreeNode(Quadrant quad, QuadTreeNode parent) : this(quad, null, null, null, null, parent) { ;}