void FloodNode(int x, int y, int startX, int startY, int radius) { int distanceX = Mathf.Abs(startX - x); int distanceY = Mathf.Abs(startY - y); if (distanceX > radius || distanceY > radius) { return; } if (MapBuilder.CollisionMap[x, y] != 0) { return; } int packed = x + (y << 16); if (!distinctCheck_.Contains(packed)) { int distance = distanceX + distanceY; var node = new CoverNode { x = x, y = y, distance = distance }; reachableNodes_.Add(node); floodFillStack_.Push(node); distinctCheck_.Add(packed); } }
public CoverNode <T> AddRectangle(SpatialObj <T> rect, bool reorganize = true) { CoverNode <T> deepest_field = FindContainingField(rect, rootNode); if (deepest_field.IsFull() && !deepest_field.HasChildren()) { PartitionField(deepest_field); CoverNode <T> node = AddRectangle(rect); if (reorganize) { ReorganizeOverflownNodes(); } if (node != null) { return(node); } } else { bool overflown = deepest_field.StoreRectangle(rect); } if (deepest_field != null) { Count += 1; } return(deepest_field); }
public CoverFieldTreeStructure(Rectangle bounds, int capacity, double p_value) { pVal = Math.Max(0.0, Math.Min(1.0, p_value)); Bounds = bounds; Capacity = capacity; rootNode = new CoverNode <T>(bounds, capacity, 0, pVal, null); }
public void HideBackground(UpdateEvent e, CoverNode cover) { if (Time.frameCount == this.updateBgAtFrame) { this.UpgradeBackground(cover.battleScreenCover); } }
public List <SpatialObj <T> > WindowQuery(Rectangle window) { // Finds objects within a Rectangular range (window) List <SpatialObj <T> > answer = new List <SpatialObj <T> >(); Queue <CoverNode <T> > searching_nodes = new Queue <CoverNode <T> >(); searching_nodes.Enqueue(rootNode); while (searching_nodes.Count > 0) { CoverNode <T> current_node = searching_nodes.Dequeue(); if (current_node.IntersectsWith(window)) { answer.AddRange(current_node.GetRangeQueryObj(window)); if (current_node.HasChildren()) { foreach (CoverNode <T> child in current_node.GetChildren()) { if (!searching_nodes.Contains(child)) { searching_nodes.Enqueue(child); } } } } } return(answer); }
private SpatialObj <T> RemoveRectangle(SpatialObj <T> rect, CoverNode <T> node) { if (node.DeleteRectangle(rect)) { Count -= 1; } MergeEmptyChildren(node); return(rect); }
public CoverData(bool foundCover, Vector3 hidingPosition, Vector3 firingPosition, bool isDynamicCover, CoverNode coverNode) { this.foundCover = foundCover; this.hidingPosition = hidingPosition; this.firingPosition = firingPosition; this.isDynamicCover = isDynamicCover; this.coverNode = coverNode; }
public Tuple <CoverNode <T>, SpatialObj <T> > IncrementalNNFindNext() { if (incrNN_queue is null) { return(null); } while (incrNN_queue.Count > 0) { NodeOrObj current_element = incrNN_queue.Dequeue(); while (incrNN_queue.Count > 0 && incrNN_queue.First().Equals(current_element)) { incrNN_queue.Dequeue(); } if (current_element.IsObj()) { return(Tuple.Create(current_element.GetNode(), current_element.GetObj())); } else { CoverNode <T> current_node = current_element.GetNode(); double current_dist = current_node.GetDistanceToPointSq(incrNN_origin); if (!current_node.IsEmpty()) { foreach (SpatialObj <T> obj in current_node.GetAllObjects()) { double distance = obj.boundingBox.GetDistanceSqToPoint(incrNN_origin); if (distance >= current_dist) { NodeOrObj obj_nodeOrObj = new NodeOrObj(); obj_nodeOrObj.SetNode(current_node); obj_nodeOrObj.SetObj(obj); incrNN_queue.Enqueue(obj_nodeOrObj, (float)distance); } } } if (current_node.HasChildren()) { foreach (CoverNode <T> child_node in current_node.GetChildren()) { double distance = child_node.GetDistanceToPointSq(incrNN_origin); if (distance >= current_dist) { NodeOrObj node_nodeOrObj = new NodeOrObj(); node_nodeOrObj.SetNode(child_node); incrNN_queue.Enqueue(node_nodeOrObj, (float)distance); } } } } } return(null); }
private void MergeEmptyChildren(CoverNode <T> node) { if (node.HasChildren() && node.AreExistingChildrenEmpty()) { node.MergeEmptyChildren(); } if (node.IsRootNode() || !node.IsEmpty() || node.HasChildren()) { return; } MergeEmptyChildren(node.GetParent()); }
private Dictionary <CoverNode <T>, SpatialObj <T> > FindNearestRectToPoint(Point p, CoverNode <T> node) { Dictionary <CoverNode <T>, SpatialObj <T> > answer_dict = new Dictionary <CoverNode <T>, SpatialObj <T> >(); SimplePriorityQueue <CoverNode <T> > searching_nodes = new SimplePriorityQueue <CoverNode <T> >(); searching_nodes.Enqueue(node, 0); SpatialObj <T> answer = default(SpatialObj <T>); CoverNode <T> answer_node = null; bool used = false; double min_distance_sq = rootNode.GetMaxDistance(); while (searching_nodes.Count > 0) { CoverNode <T> current_node = searching_nodes.Dequeue(); Dictionary <SpatialObj <T>, double> nearest_rect = current_node.GetNearestRectangle(p); if (nearest_rect.Count > 0) { foreach (KeyValuePair <SpatialObj <T>, double> entry in nearest_rect) { if (entry.Value <= min_distance_sq || entry.Value < Statics.EPSILON) { min_distance_sq = entry.Value; answer = entry.Key; answer_node = current_node; used = false; if (min_distance_sq < Statics.EPSILON) { answer_dict.Add(answer_node, answer); used = true; } } } } if (current_node.HasChildren()) { foreach (CoverNode <T> child in current_node.GetChildren()) { double field_dist = child.GetDistanceToPointSq(p); if (field_dist <= min_distance_sq) { searching_nodes.Enqueue(child, (float)field_dist); } } } } if (!used) { answer_dict.Add(answer_node, answer); } return(answer_dict); }
// Start is called before the first frame update void Start() { terrain_manager = terrain_manager_game_object.GetComponent <TerrainManager>(); gridNoX = terrain_manager.myInfo.x_N; gridNoZ = terrain_manager.myInfo.z_N; grid = new CoverNode[gridNoX, gridNoZ]; graph_indeces = new List <List <int> >(); coverNodes = new List <CoverNode>(); cars = new List <GameObject>(GameObject.FindGameObjectsWithTag("Player")); this.numberOfGridCells = gridNoX * gridNoZ; this.numberOfObstacles = 0; for (int i = 0; i < gridNoX; ++i) { for (int j = 0; j < gridNoZ; ++j) { bool isObstacle = terrain_manager.myInfo.traversability[i, j] > 0.5f; if (isObstacle) { numberOfObstacles++; graph_indeces.Add(new List <int>()); } else { List <int> neighbours = GetNeighbours(i, j); graph_indeces.Add(neighbours); } grid[i, j] = new CoverNode(new Vector3(terrain_manager.myInfo.get_x_pos(i), 0.5f, terrain_manager.myInfo.get_z_pos(j)), isObstacle, Get1Dindex(i, j), i, j); } } InitCostMatrix(); if (Is_P2) { // P2 createMSC(); } else { // P3 getTurretsPositions(); } SaveProblemCostMatrixToFile(); if (recompute) { string python_result = SolveWithPython(); Debug.Log(python_result); } //Debug.LogError(string.Format("Python output: {0}", python_result)); ReadSolutionFile(); }
CoverData FindAdvancingCover(Vector3 targetTransformPos, Transform transformToDefend) { var i = 0; var myPos = myTransform.position; CoverNode currentCoverNodeScript = null; //Will find closest cover that is nearer than the last one we have if possible. //If not, we'll move to the target. Vector3 posToAdvanceTo; posToAdvanceTo = transformToDefend ? transformToDefend.position : targetTransformPos; var distBetweenMeAndTarget = Vector3.SqrMagnitude(myPos - posToAdvanceTo) - minDistToAdvance; var closestDistBetweenMeAndCover = distBetweenMeAndTarget; for (i = 0; i < coverNodes.Length; i++) { if (!coverNodes[i].isOccupied()) { float sqrDistBetweenNodeAndTargetPos = Vector3.SqrMagnitude(coverNodes[i].GetPosition() - posToAdvanceTo); //Check if we'll be closer to target than we stand now if (sqrDistBetweenNodeAndTargetPos < distBetweenMeAndTarget) { //Check if this node is closest to us if (Vector3.SqrMagnitude(coverNodes[i].GetPosition() - myPos) < closestDistBetweenMeAndCover) { //Check if node is safe if (coverNodes[i].ValidCoverCheck(targetTransformPos)) { closestDistBetweenMeAndCover = sqrDistBetweenNodeAndTargetPos; currentCoverNodeScript = coverNodes[i]; } } } } } if (currentCoverNodeScript != null) { lastCoverPos = currentCoverNodeScript.GetPosition(); return(new CoverData(true, currentCoverNodeScript.GetPosition(), currentCoverNodeScript.GetSightNodePosition(), false, currentCoverNodeScript)); } //Dynamic advancing cover is NOT supported return(new CoverData()); }
void Start() { angle = angle / 57;//convertimos a radianes //Buscamos los nodos del grafo Node[] nodes = graphComponent.graph.nodes; //obstaculos GameObject[] obstacles = GameObject.FindGameObjectsWithTag("Obstacle"); obstaclesData = new obstacle_data[obstacles.Length]; for (int k = 0; k < obstacles.Length; k++) { obstaclesData[k] = obstacles[k].GetComponent <obstacle_data>(); } // CREAMOS UN ARREGLO CON LOS NODOS CON VALOR DE CALIDAD PARA CUBRIRSE CoverNode[] coverNodesArray = new CoverNode[nodes.Length]; float coverQuality; for (int i = 0; i < nodes.Length; i++) { coverQuality = GetCoverQuality(nodes[i], iterations); coverNodesArray[i] = new CoverNode(nodes[i], coverQuality); } // ordenamos por calidad descendentemente coverNodesArray = coverNodesArray.OrderBy(node => - node.coverQuality).ToArray(); // tomamos solo los primeros 10 coverNodesArray = coverNodesArray.Take(30).ToArray(); // agregamos todos los nodos a la lista que usaran los componentes que lo necesiten // por eso usamos una lista para que no de problemas el tiempo de update, start foreach (var node in coverNodesArray) { coverNodes.Add(node); } //Debugging // foreach(var node in coverNodes){ // Debug.Log(node.coverQuality); // node.node.DrawTriangle(10f); // } }
public SpatialObj <T> FindNearestObjAndRemove(Point p) { SpatialObj <T> obj = default(SpatialObj <T>); CoverNode <T> node = null; foreach (KeyValuePair <CoverNode <T>, SpatialObj <T> > entry in FindNearestRectToPoint(p, rootNode)) { obj = entry.Value; node = entry.Key; } if (node != null) { return(RemoveRectangle(obj, node)); } return(obj); }
public bool IsCoveredBy(CoverNode node) { foreach (Vector3 cornerPositon in cornerPositions) { float distance = (cornerPositon - node.position).magnitude; Vector3 direction = (cornerPositon - node.position).normalized; RaycastHit hit; int layer_mask = LayerMask.GetMask("CubeWalls"); // Does the ray intersect any objects excluding the player layer if (Physics.Raycast(node.position + direction, direction, out hit, distance, layer_mask)) { return(false); } } return(true); }
public SpatialObj <T> RemoveObject(SpatialObj <T> rect) { CoverNode <T> node = null; foreach (KeyValuePair <CoverNode <T>, SpatialObj <T> > entry in FindNearestRectToPoint(rect.boundingBox.Center, rootNode)) { if (entry.Value.Equals(rect)) { node = entry.Key; } } if (node != null) { return(RemoveRectangle(rect, node)); } return(rect); }
void getCover_Enter() { node = CoverNodeManager.current.FindClosestTarget(gameObject.transform.position, tag); if (node != null) { // Debug.Log(node); // enviar al nodo que esta asignado CoverNode temp = node.GetComponent <CoverNode>(); if (temp != null) { temp.setOccupied(true); fsm.ChangeState(States.goToCover); } } else { fsm.ChangeState(States.Wander); } }
CoverData FindRandomCover(Vector3 targetTransformPos, Transform transformToDefend) { var i = 0; CoverNode currentCoverNodeScript = null; var availableCoverNodeScripts = new List <CoverNode>(); //Fill a list with potential nodes for (i = 0; i < coverNodes.Length; i++) { if (!coverNodes[i].isOccupied()) { if (coverNodes[i].ValidCoverCheck(targetTransformPos) && (!transformToDefend || Vector3.SqrMagnitude(coverNodes[i].GetPosition() - transformToDefend.position) < defendingDistSquared)) { availableCoverNodeScripts.Add(coverNodes[i]); } } } if (availableCoverNodeScripts.Count > 0) { //Pick a random node currentCoverNodeScript = availableCoverNodeScripts[Random.Range(0, availableCoverNodeScripts.Count)]; lastCoverPos = currentCoverNodeScript.GetPosition(); return(new CoverData(true, currentCoverNodeScript.GetPosition(), currentCoverNodeScript.GetSightNodePosition(), false, currentCoverNodeScript)); } //Only bother with dynamic cover if we need it if (shouldUseDynamicCover && !AIController.Instance.usePerformanceMode) { return(FindDynamicCover(targetTransformPos, transformToDefend)); } return(new CoverData()); }
public GameObject FindClosestTarget(Vector3 position, string tag) { // return nodes // .OrderBy(o => (o.transform.position - position).sqrMagnitude) // .FirstOrDefault(); GameObject closest = null; float distance = Mathf.Infinity; foreach (GameObject go in nodes) { // verificar si el gameobject no esta asignado CoverNode temp = go.GetComponent <CoverNode>(); if (temp != null) { if (temp.tag == tag) { if (temp.isOccupied()) { continue; } Vector3 diff = go.transform.position - position; float curDistance = diff.sqrMagnitude; if (curDistance < distance) { closest = go; distance = curDistance; } } } } return(closest); }
private void ReorganizeNode(CoverNode <T> node) { // After adding objects and creating new partitions, checks to see if any of the upper level objects can go deeper into the tree. Queue <CoverNode <T> > all_nodes = new Queue <CoverNode <T> >(); all_nodes.Enqueue(node); while (all_nodes.Count > 0) { List <SpatialObj <T> > rects_removed = new List <SpatialObj <T> >(); CoverNode <T> current_node = all_nodes.Dequeue(); foreach (SpatialObj <T> rect in current_node.GetOverflowObjs()) { CoverNode <T> deepest_field = FindContainingField(rect, current_node); if (!deepest_field.Equals(current_node)) { bool overflown = deepest_field.StoreRectangle(rect); rects_removed.Add(rect); } } if (rects_removed.Count > 0) { current_node.DeleteRectangles(rects_removed, true); } if (current_node.HasChildren()) { foreach (CoverNode <T> child in current_node.GetChildren()) { all_nodes.Enqueue(child); } } } }
public CoverNode <T> FindContainingField(SpatialObj <T> rect, CoverNode <T> starting_node) { if (starting_node.IsPointInNode(rect.boundingBox.Center)) { bool contained_in_node = starting_node.IsObjectInNode(rect); if (contained_in_node && !starting_node.CanSink(rect)) { return(starting_node); } foreach (CoverNode <T> child in starting_node.GetChildren()) { var potential_node = FindContainingField(rect, child); if (potential_node != null) { return(potential_node); } } if (contained_in_node) { return(starting_node); } } return(null); }
public GameObject FindFreeNode(Vector3 position) { GameObject free = null; foreach (GameObject go in nodes) { // verificar si el gameobject no esta asignado CoverNode temp = go.GetComponent <CoverNode>(); if (temp != null) { if (temp.isOccupied()) { continue; } else { free = go; } } } return(free); }
private void PartitionField(CoverNode <T> node) { node.CreateChildren(); }
void createGraph(GraphOfNodes graphNodes, Dictionary <int, int> SubjectIdLevelMapping, GraphClient client) { List <GraphNode> lst_graphNodes = graphNodes.GraphNodes; Dictionary <GraphNode, List <GraphNode> > lst_relationships = graphNodes.ParentToChildrenMap; if (lst_graphNodes == null || lst_relationships == null) { return; } Dictionary <TermNode, NodeReference <Neo4jTermNode> > m_term_nodes = new Dictionary <TermNode, NodeReference <Neo4jTermNode> >(); Dictionary <CoverNode, NodeReference <Neo4jCoverNode> > m_cover_nodes = new Dictionary <CoverNode, NodeReference <Neo4jCoverNode> >(); //Add Nodes foreach (GraphNode node in lst_graphNodes) { if (node is TermNode) { TermNode term_node = (TermNode)node; //term_node.ded; int id = node.Subject.ID; Neo4jTermNode tn = new Neo4jTermNode(); tn.NodeID = id; tn.NumberOfBuildings = term_node.PrimarySubject.Schedule.ActNumOfBldgs; tn.IsPerRisk = term_node.IsPerRisk; tn.Level = SubjectIdLevelMapping[id]; if (term_node.Deductibles.GetDedList() != null && term_node.Deductibles.GetDedList().Count != 0) { tn.Deductible = term_node.Deductibles.GetDedList().First().Amount; } if (term_node.Limits.GetLimList() != null && term_node.Limits.GetLimList().Count != 0) { tn.Limit = term_node.Limits.GetLimList().First().Amount; } var ref1 = client.Create(tn); m_term_nodes.Add(term_node, (NodeReference <Neo4jTermNode>)ref1); } else if (node is CoverNode) { CoverNode cover_node = (CoverNode)node; //term_node.ded; string coverName = cover_node.CoverName; Neo4jCoverNode cn = new Neo4jCoverNode(); cn.Name = coverName; cn.IsPerRisk = cover_node.IsPerRisk; cn.Level = SubjectIdLevelMapping[cover_node.Subject.ID]; var ref1 = client.Create(cn); m_cover_nodes.Add(cover_node, (NodeReference <Neo4jCoverNode>)ref1); } } //Add relationships foreach (KeyValuePair <GraphNode, List <GraphNode> > rel in lst_relationships) { //Parent is term Node if (rel.Key is TermNode) { NodeReference <Neo4jTermNode> parentTermNode; m_term_nodes.TryGetValue(rel.Key as TermNode, out parentTermNode); List <GraphNode> lst_childnodes = rel.Value; foreach (GraphNode child in lst_childnodes) { NodeReference <Neo4jTermNode> childGraphTermNode; m_term_nodes.TryGetValue(child as TermNode, out childGraphTermNode); if (child != null) { client.CreateRelationship <Neo4jTermNode, TermChildRelationship>(parentTermNode, new TermChildRelationship(childGraphTermNode)); } } } //Parent is Cover Node else if (rel.Key is CoverNode) { NodeReference <Neo4jCoverNode> parentTermNode; m_cover_nodes.TryGetValue(rel.Key as CoverNode, out parentTermNode); List <GraphNode> lst_childnodes = rel.Value; foreach (GraphNode child in lst_childnodes) { if (child is TermNode) { NodeReference <Neo4jTermNode> childGraphTermNode; m_term_nodes.TryGetValue(child as TermNode, out childGraphTermNode); if (child != null) { client.CreateRelationship <Neo4jCoverNode, CoverChildRelationship>(parentTermNode, new CoverChildRelationship(childGraphTermNode)); } } else if (child is CoverNode) { NodeReference <Neo4jCoverNode> childGraphCoverNode; m_cover_nodes.TryGetValue(child as CoverNode, out childGraphCoverNode); if (child != null) { client.CreateRelationship <Neo4jCoverNode, DerivedCoverChildRelationship>(parentTermNode, new DerivedCoverChildRelationship(childGraphCoverNode)); } } else { throw new NotSupportedException("Can only handle nodes of type term and cover"); } } } } // Create entities //var refA = client.Create(new Person() { Name = "Person A" }); //var refB = client.Create(new Person() { Name = "Person B" }); //var refC = client.Create(new Person() { Name = "Person C" }); //var refD = client.Create(new Person() { Name = "Person D" }); //// Create relationships //client.CreateRelationship(refA, new KnowsRelationship(refB)); //client.CreateRelationship(refB, new KnowsRelationship(refC)); //client.CreateRelationship(refB, new HatesRelationship(refD), new HatesData("Crazy guy"))); //client.CreateRelationship(refC, new HatesRelationship(refD), new HatesData("Don't know why..."))); //client.CreateRelationship(refD, new KnowsRelationship(refA)); }
// ------------------------------------------------- DefineCover public override void DefineCover () { CoverNode [] nodes = new CoverNode [nApexes + 1]; PointF [] pts = Apexes; for (int i = 0; i < nApexes; i++) { nodes [i] = new CoverNode (i, pts [i], pts [(i + 1) % nApexes], 5, Cursors .Hand); } nodes [nApexes] = new CoverNode (nApexes, Apexes); cover = new Cover (nodes); }
// ------------------------------------------------- DefineCover public override void DefineCover () { if (bResizable) { int nOnPerimeter = Convert .ToInt32 ((2 * Math .PI * radius) / distanceNeighbours); CoverNode [] nodes; int iBig, iStartOnBorder; if (str .Length > 0) { nodes = new CoverNode [2 + nOnPerimeter]; iBig = 1; iStartOnBorder = 2; } else { nodes = new CoverNode [1 + nOnPerimeter]; iBig = 0; iStartOnBorder = 1; } if (str .Length > 0) { SizeF sizef = Auxi_Geometry .MeasureString (form, str, font); Point [] corners = Auxi_Geometry .TextCorners (sizef .Width, sizef .Height, angle, ptCenter, TextBasis .M); PointF [] cornersF = new PointF [corners .Length]; for (int i = 0; i < corners .Length; i++) { cornersF [i] = new PointF (corners [i] .X, corners [i] .Y); } nodes [0] = new CoverNode (0, cornersF, Cursors .Hand); } nodes [iBig] = new CoverNode (iBig, ptCenter, radius - nrSmall + 1, Cursors .SizeAll); for (int i = 0; i < nOnPerimeter; i++) { nodes [iStartOnBorder + i] = new CoverNode (iStartOnBorder +i, Auxi_Geometry .PointToPoint (ptCenter, 2 * Math .PI * i / nOnPerimeter, radius), nrSmall); nodes [iStartOnBorder + i] .Clearance = false; } cover = new Cover (nodes); } else { if (str .Length > 0) { SizeF sizef = Auxi_Geometry .MeasureString (form, str, font); Point [] corners = Auxi_Geometry .TextCorners (sizef .Width, sizef .Height, angle, ptCenter, TextBasis .M); PointF [] cornersF = new PointF [corners .Length]; for (int i = 0; i < corners .Length; i++) { cornersF [i] = new PointF (corners [i] .X, corners [i] .Y); } CoverNode [] nodes = new CoverNode [2] {new CoverNode (0, cornersF, Cursors.Hand), new CoverNode (1, ptCenter, radius) }; cover = new Cover (nodes); } else { cover = new Cover (new PointF [] { ptCenter }, radius); cover .SetCursor (Cursors .SizeAll); } } }
// ------------------------------------------------- DefineCover public override void DefineCover () { CoverNode node = new CoverNode (0, center, radius, Cursors .SizeAll); cover = new Cover (new CoverNode [] { node }); }
// ------------------------------------------------- DefineCover public override void DefineCover () { CoverNode [] ca = new CoverNode [10]; for (int i = 0; i < 9; i++) { ca [i] = new CoverNode (i, pts [i], nRadius); } ca [9] = new CoverNode (9, Frame); cover = new Cover (ca); }
public void SetNode(CoverNode <T> n) { node = n; isNode = true; }
// ------------------------------------------------- DefineCover public override void DefineCover () { CoverNode [] nodes = new CoverNode [nApexes + 1]; for (int i = 0; i < nApexes; i++) { nodes [i] = new CoverNode (i, pts [i], pts [(i + 1) % pts .Length], 3, Cursors .Hand); } nodes [nApexes] = new CoverNode (nApexes, pts); cover = new Cover (nodes); }
//Agent will try and find cover that is within a given range of the target. CoverData FindCoverWithinCombatRange(Vector3 targetTransformPos, Transform transformToDefend) { var i = 0; var myPos = myTransform.position; CoverNode currentCoverNode = null; var closestDistSquared = maxDistToCover; //We will take cover outside of the desired range if we can't find any within. var foundCoverWithinAcceptableRange = false; for (i = 0; i < coverNodes.Length; i++) { //Check if the node we are checking is occupied and within acceptable distances to key points if (!coverNodes[i].isOccupied() && coverNodeGroup == coverNodes[i].coverNodeGroup && Vector3.SqrMagnitude(coverNodes[i].GetPosition() - lastCoverPos) > minDistBetweenLastCoverSquared && (!transformToDefend || Vector3.SqrMagnitude(coverNodes[i].GetPosition() - transformToDefend.position) < defendingDistSquared)) { print("final?"); var distToTargetSquared = Vector3.SqrMagnitude(coverNodes[i].GetPosition() - targetTransformPos); var nodeCheckingNowDistSquared = Vector3.SqrMagnitude(myPos - coverNodes[i].GetPosition()); //Check for line of sight if (coverNodes[i].ValidCoverCheck(targetTransformPos)) { print("Check complete?"); //Prefer nodes within othe agent's combat range if (minCoverDistSqrd < distToTargetSquared && maxCoverDistSqrd > distToTargetSquared) { if (!foundCoverWithinAcceptableRange || (nodeCheckingNowDistSquared < closestDistSquared)) { closestDistSquared = nodeCheckingNowDistSquared; currentCoverNode = coverNodes[i]; foundCoverWithinAcceptableRange = true; } } //Check if this is the closest so far else if (!foundCoverWithinAcceptableRange && nodeCheckingNowDistSquared < closestDistSquared) { closestDistSquared = nodeCheckingNowDistSquared; currentCoverNode = coverNodes[i]; } } } } //pass the data to the script that asked for cover if (currentCoverNode != null) { lastCoverPos = currentCoverNode.GetPosition(); return(new CoverData(true, currentCoverNode.GetPosition(), currentCoverNode.GetSightNodePosition(), false, currentCoverNode)); } //Only bother with dynamic cover if we need it if (shouldUseDynamicCover && !AIController.Instance.usePerformanceMode) { return(FindDynamicCover(targetTransformPos, transformToDefend)); } return(new CoverData()); }
public static void _BuildGraphFromIR(string ir) { HashSet <Contract> contracts = new HashSet <Contract>(); string separator = ","; _Contract currentContract = null; int nCovers = 0; int nodeExtnId = 0; CoverNode currentCoverNode = null; bool processingCovers = false; HashSet <CoverNode> coverNodes = null; int pValueType = -1; bool _hasPercentCover = false; bool _hasPercentAffected = false; int nNodes = 0; bool processingNodes = false; HashSet <TermNode> nodes = null; TermNode currentTermNode = null; //string[] lines = Regex.Split(ir, System.Environment.NewLine).ToList().Where(s => !string.IsNullOrEmpty(s)).ToArray<string>(); //int c = 0; //while (true) //{ // if (c >= lines.Length) // break; // string line = lines[c]; // string[] values = Regex.Split(line, separator); // if (values == null || values.Length == 0) // { // c++; // continue; // } // //Trim values // for (int j = 0; j < values.Length; j++) // { // values[j] = values[j].Trim(); // } //} foreach (string line in Regex.Split(ir, System.Environment.NewLine).ToList().Where(s => !string.IsNullOrEmpty(s))) { string[] values = Regex.Split(line, separator); if (values == null || values.Length == 0) { continue; } //Trim values for (int i = 0; i < values.Length; i++) { values[i] = values[i].Trim(); } if (values[0].Equals(";")) { if (currentContract != null) { if (currentCoverNode != null) { coverNodes.Add(currentCoverNode); currentCoverNode = null; } // add covers to contract foreach (CoverNode coverNode in coverNodes) { currentContract.AddCoverNode(coverNode); } contracts.Add(currentContract); } currentContract = null; continue; } if (values[0].Equals("CONTRACT")) { if (currentContract != null) { if (currentCoverNode != null) { coverNodes.Add(currentCoverNode); currentCoverNode = null; } // add covers to contract foreach (CoverNode coverNode in coverNodes) { currentContract.AddCoverNode(coverNode); } contracts.Add(currentContract); } currentContract = new Primary(values[1]); currentContract.Subject = new Subject(new Schedule(), new HashSet <ICauseOfLoss>(), new HashSet <string>(), false); currentContract.Initialize(); continue; } if (values[0].Equals("nCover")) { nCovers = int.Parse(values[1]); processingCovers = true; continue; } if (processingCovers) { if (coverNodes == null) { coverNodes = new HashSet <CoverNode>(); } if (values[0].Equals("PARENT")) { if (currentCoverNode != null) { coverNodes.Add(currentCoverNode); } if (pValueType == 1) { _hasPercentCover = true; } else if (pValueType == 2) { _hasPercentAffected = true; } currentCoverNode = new CoverNode(); currentCoverNode.ExtnId = (nodeExtnId++).ToString(); currentCoverNode.parentId = values[1]; continue; } if (values[0].Equals("nChild")) { currentCoverNode.nChild = int.Parse(values[1]); continue; } if (values[0].Equals("CHILD")) { currentCoverNode.vSubCover.Add(values[1]); continue; } if (values[0].Equals("SHARE")) { currentCoverNode.Share = double.Parse(values[1]); // ? *= 0.01 continue; } if (values[0].Equals("OCCLIM")) { currentCoverNode.Limit = double.Parse(values[1]); continue; } if (values[0].Equals("AGGLIM")) { currentCoverNode.AggLimit = double.Parse(values[1]); continue; } if (values[0].Equals("OCCLIMPC")) { currentCoverNode.m_limitPC = double.Parse(values[1]); pValueType = 1; continue; } if (values[0].Equals("AGGLIMPC")) { currentCoverNode.m_agglimitPC = double.Parse(values[1]); pValueType = 1; continue; } if (values[0].Equals("OCCLIMPA")) { currentCoverNode.m_limitPA = double.Parse(values[1]); pValueType = 2; continue; } if (values[0].Equals("AGGLIMPA")) { currentCoverNode.m_agglimitPA = double.Parse(values[1]); pValueType = 2; continue; } if (values[0].Equals("OCCATT")) { currentCoverNode.Attach = double.Parse(values[1]); continue; } if (values[0].Equals("AGGATT")) { currentCoverNode.m_aggach = double.Parse(values[1]); continue; } if (values[0].Equals("OCCATTPC")) { currentCoverNode.m_attachPC = double.Parse(values[1]); pValueType = 1; continue; } if (values[0].Equals("AGGATTPC")) { currentCoverNode.m_aggachPC = double.Parse(values[1]); pValueType = 1; continue; } if (values[0].Equals("OCCATTPA")) { currentCoverNode.m_attachPA = double.Parse(values[1]); pValueType = 2; continue; } if (values[0].Equals("AGGATTPA")) { currentCoverNode.m_aggachPA = double.Parse(values[1]); pValueType = 2; continue; } if (values[0].Equals("SETS")) { if (values[1].Equals("MAX")) { currentCoverNode._setsType = (int)ContractEntry.COVER_SETS_MAX; } else if (values[1].Equals("MIN")) { currentCoverNode._setsType = (int)ContractEntry.COVER_SETS_MIN; } else if (values[1].Equals("SUM")) { currentCoverNode._setsType = (int)ContractEntry.COVER_SETS_SUM; } continue; } if (values[0].Equals("PAY")) { currentCoverNode._payfType = (int)ContractEntry.COVER_PAY; currentCoverNode._pay = double.Parse(values[1]); continue; } if (values[0].Equals("PAYF")) { // TODO : _pay? if (values[1].Equals("MAX")) { currentCoverNode._payfType = (int)ContractEntry.COVER_PAYF_MAX; } else if (values[1].Equals("MIN")) { currentCoverNode._payfType = (int)ContractEntry.COVER_PAYF_MIN; } continue; } if (values[0].Equals("PAYP")) { currentCoverNode._payfType = (int)ContractEntry.COVER_PAYP; currentCoverNode._pay = double.Parse(values[1]) * 0.01; continue; } if (values[0].Equals("PAYFP")) { // TODO : _pay? if (values[1].Equals("MAX")) { currentCoverNode._payfType = (int)ContractEntry.COVER_PAYFP_MAX; } else if (values[1].Equals("MIN")) { currentCoverNode._payfType = (int)ContractEntry.COVER_PAYFP_MIN; } continue; } if (values[0].Equals("nNode")) { coverNodes.Add(currentCoverNode); currentCoverNode = null; processingCovers = false; processingNodes = true; nNodes = int.Parse(values[1]); currentContract.nNodes = nNodes; if (pValueType == 1) { _hasPercentCover = true; } else if (pValueType == 2) { _hasPercentAffected = true; } continue; } } if (processingNodes) { if (nodes == null) { nodes = new HashSet <TermNode>(); } if (values[0].Equals("PARENT")) { if (currentTermNode != null) { nodes.Add(currentTermNode); } currentTermNode = new TermNode(); currentTermNode.ExtnId = (nodeExtnId++).ToString(); for (int k = 1; k < values.Length; k++) { currentTermNode.AddParentIdx(values[k]); } continue; } } } if (currentContract != null) { if (currentCoverNode != null) { coverNodes.Add(currentCoverNode); currentCoverNode = null; } // add covers to contract foreach (CoverNode coverNode in coverNodes) { currentContract.AddCoverNode(coverNode); } contracts.Add(currentContract); } }
public void Show(ShowCoverEvent e, CoverNode cover) { this.ShowCover(cover.battleScreenCover, true); }
// ------------------------------------------------- DefineCover public override void DefineCover () { CoverNode [] nodes; PointF [] pts; switch (type) { case PolygonType .NonResizable: cover = new Cover (new CoverNode [] { new CoverNode (0, Apexes) }); break; case PolygonType .ZoomByApexes: nodes = new CoverNode [nApexes + 1]; pts = Apexes; for (int i = 0; i < nApexes; i++) { nodes [i] = new CoverNode (i, pts [i], 5); } nodes [nApexes] = new CoverNode (nApexes, Apexes); cover = new Cover (nodes); break; case PolygonType .ZoomByBorder: nodes = new CoverNode [nApexes + 1]; pts = Apexes; for (int i = 0; i < nApexes; i++) { nodes [i] = new CoverNode (i, pts [i], pts [(i + 1) % nApexes], 5, Cursors .Hand); } nodes [nApexes] = new CoverNode (nApexes, Apexes); cover = new Cover (nodes); break; } }
// ------------------------------------------------- DefineCover // order of nodes: circles at the ends of segments [0, pts .Length - 1] // strips between the consecutive ends of segments [pts .Length - 1, 2 * (pts .Length - 1)] // public override void DefineCover () { CoverNode [] ca = new CoverNode [pts .Length + (pts .Length - 1)]; for (int i = 0; i < pts .Length; i++) { ca [i] = new CoverNode (i, pts [i], 5); } for (int i = 0; i < pts .Length - 1; i++) { ca [pts .Length + i] = new CoverNode (pts .Length + i, pts [i], pts [i + 1]); } cover = new Cover (ca); }
//Used to set variables once cover is found. void SetCover(Vector3 newCoverPos, Vector3 newCoverFiringSpot, bool isDynamicCover, CoverNode newCoverNodeScript) { timeTilNoCoverCharge = maxTimeTilNoCoverCharge; aiAgent.currentCoverNodePos = newCoverPos; aiAgent.currentCoverNodeFiringPos = newCoverFiringSpot; navInterface.SetStoppingDistance(0); if (isDynamicCover) { foundDynamicCover = true; AIController.Instance.AddACoverSpot(aiAgent.currentCoverNodeFiringPos); } else { aiAgent.currentCoverNode = newCoverNodeScript; aiAgent.currentCoverNode.setOccupied(true); if (aiAgent.useAdvancedCover) { // aiAnimation.StartAdvancedCover(aiAgent.currentCoverNode.advancedCoverDirection, aiAgent.currentCoverNode.faceDir); } } }
// ------------------------------------------------- DefineCover // nodes on dots (except two end points) - to move them // nodes on segments - to give information (via cursor shape) that they can be clicked to add the new dot; these nodes are not movable !!! public override void DefineCover() { int nCircles = pts.Count - 2; int nStrips = pts.Count - 1; int nNodes = nCircles + nStrips; CoverNode[] nodes = new CoverNode[nNodes]; for (int i = 0; i < nCircles; i++) { nodes[i] = new CoverNode(i, pts[i + 1], halfsize, Cursors.Hand); } int j0 = nCircles; for (int i = 0; i < nStrips; i++) { nodes[j0 + i] = new CoverNode(j0 + i, pts[i], pts[i + 1], Behaviour.Frozen, Cursors.Hand); } cover = new Cover(nodes); }
// ------------------------------------------------- DefineCover public override void DefineCover () { Rectangle rc = new Rectangle (ptCenter .X - halfside, ptCenter .Y - halfside, 2 * halfside, 2 * halfside); if (str .Length > 0) { SizeF sizef = Auxi_Geometry .MeasureString (form, str, font); Point [] corners = Auxi_Geometry .TextCorners (sizef .Width, sizef .Height, angle, ptCenter, TextBasis .M); PointF [] cornersF = new PointF [corners .Length]; for (int i = 0; i < corners .Length; i++) { cornersF [i] = new PointF (corners [i] .X, corners [i] .Y); } CoverNode [] nodes = new CoverNode [2] {new CoverNode (0, cornersF, Cursors.Hand), new CoverNode (1, rc) }; //Auxi_Geometry .CornersOfRectangle (rc) cover = new Cover (nodes); } else { cover = new Cover (rc, Resizing .None); } }
// ------------------------------------------------- DefineCover // order of nodes: // [ApexNum] - circular nodes in apexes // 1 - circular node in ptCenter // [ApexNum] - strip nodes, covering each segment of the perimeter // [ApexNum] - big triangular nodes // public override void DefineCover () { CoverNode [] nodes = new CoverNode [3 * ApexNum + 1]; for (int i = 0; i < ApexNum; i++) { nodes [i] = new CoverNode (i, ptApex [i], 6); } nodes [ApexNum] = new CoverNode (ApexNum, ptCenter, 6); int k0 = ApexNum + 1; for (int i = 0; i < ApexNum; i++) { nodes [k0 + i] = new CoverNode (k0 + i, ptApex [i], ptApex [(i + 1) % ApexNum], Cursors .Hand); } k0 = 2 * ApexNum + 1; for (int i = 0; i < ApexNum; i++) { PointF [] pts = new PointF [3] { ptApex [i], ptApex [(i + 1) % ApexNum], ptCenter }; nodes [k0 + i] = new CoverNode (k0 + i, pts); } cover = new Cover (nodes); }
// ------------------------------------------------- DefineCover // order of nodes: 4 on corners (LT, RT, RB, LB), 0, 1, 2, 3 // 1 on ridge, 4 // 4 strips on sides (left, top, right, bottom) 5, 6, 7, 8 // 1 polygon node (pentagon) to fill the inner area 9 public override void DefineCover () { CoverNode [] nodes = new CoverNode [4 + 1 + 4 + 1]; int nr = 5; nodes [0] = new CoverNode (0, new PointF (rcHouse .Left, rcHouse .Top), nr, Cursors .SizeNWSE); nodes [1] = new CoverNode (1, new PointF (rcHouse .Right, rcHouse .Top), nr, Cursors .SizeNESW); nodes [2] = new CoverNode (2, new PointF (rcHouse .Right, rcHouse .Bottom), nr, Cursors .SizeNWSE); nodes [3] = new CoverNode (3, new PointF (rcHouse .Left, rcHouse .Bottom), nr, Cursors .SizeNESW); nodes [4] = new CoverNode (4, ptRidge, nr); nodes [5] = new CoverNode (5, new PointF [] {new PointF (rcHouse .Left, rcHouse .Top), new PointF (rcHouse .Left, rcHouse .Bottom)}, MovementFreedom .WE, Cursors .SizeWE); nodes [6] = new CoverNode (6, new PointF [] {new PointF (rcHouse .Left, rcHouse .Top), new PointF (rcHouse .Right, rcHouse .Top)}, MovementFreedom .NS, Cursors .SizeNS); nodes [7] = new CoverNode (7, new PointF [] {new PointF (rcHouse .Right, rcHouse .Top), new PointF (rcHouse .Right, rcHouse .Bottom)}, MovementFreedom .WE, Cursors .SizeWE); nodes [8] = new CoverNode (8, new PointF [] {new PointF (rcHouse .Left, rcHouse .Bottom), new PointF (rcHouse .Right, rcHouse .Bottom)}, MovementFreedom .NS, Cursors .SizeNS); nodes [9] = new CoverNode (9, new PointF [] {new PointF (rcHouse .Left, rcHouse .Top), ptRidge, new PointF (rcHouse .Right, rcHouse .Top), new PointF (rcHouse .Right, rcHouse .Bottom), new PointF (rcHouse .Left, rcHouse .Bottom) }); cover = new Cover (nodes); }
// ------------------------------------------------- DefineCover public override void DefineCover () { CoverNode node = new CoverNode (0, Auxi_Geometry .CornersOfRectangle (rc)); node .Clearance = true; cover = new Cover (new CoverNode [] { node }); }
// ------------------------------------------------- DefineCover // order of nodes: // [0 - (nApexes - 1)] strip nodes, covering each segment of the inner border // [nApexes - (2*nApexes - 1)] strip nodes, covering each segment of the outer border // [2*nApexes - (3*nApexes - 1)] big polygon nodes // public override void DefineCover () { ApexPoints (ref ptsIn, ref ptsOut); CoverNode [] ca = new CoverNode [3 * nApexes]; for (int i = 0; i < nApexes; i++) { ca [i] = new CoverNode (i, ptsIn [i], ptsIn [(i + 1) % nApexes], Cursors .Hand); } for (int i = 0; i < nApexes; i++) { ca [nApexes + i] = new CoverNode (nApexes + i, ptsOut [i], ptsOut [(i + 1) % nApexes], Cursors .Hand); } for (int i = 0; i < nApexes; i++) { int i1 = (i + 1) % nApexes; ca [2 * nApexes + i] = new CoverNode (2 * nApexes + i, new PointF [] { ptsIn [i], ptsIn [i1], ptsOut [i1], ptsOut [i] }); } cover = new Cover (ca); }
// New version private void createMSC() { // Mark all nodes that are covered at the start int numberOfNodesCoveredAtStart = 0; foreach (GameObject car in cars) { int i = terrain_manager.myInfo.get_i_index(car.transform.position.x); int j = terrain_manager.myInfo.get_j_index(car.transform.position.z); CoverNode carNode = grid[i, j]; //if (numberOfNodesCoveredAtStart > 0 && coverNodes.Count == 0) //{ // coverNodes.Add(carNode); //} for (int s = 0; s < gridNoX; ++s) { for (int t = 0; t < gridNoZ; ++t) { if (grid[s, t].isCovered || grid[s, t].isObstacle) { continue; } if (grid[s, t].IsCoveredBy(carNode)) { grid[s, t].isCovered = true; numberOfNodesCoveredAtStart++; } } } } // Greedy algorithm int cellsCovered = numberOfObstacles + numberOfNodesCoveredAtStart; while (cellsCovered < numberOfGridCells) { int maxNumberCovered = 0; Vector2 maxCoverNodeIndex = new Vector2(); List <Vector2> equally_covering_nodes = new List <Vector2>(); // Find the node that covers the most of other uncovered nodes // And that is closest to existing covering nodes for (int i = 0; i < gridNoX; ++i) { for (int j = 0; j < gridNoZ; ++j) { if (grid[i, j].isObstacle) { continue; } if (!grid[i, j].isCovered) { continue; } int numberCovered = 0; for (int s = 0; s < gridNoX; ++s) { for (int t = 0; t < gridNoZ; ++t) { if (grid[s, t].isCovered || grid[s, t].isObstacle) { continue; } if (grid[s, t].IsCoveredBy(grid[i, j])) { numberCovered++; } } } // If the node is equally good to the bests found so far, add to the list if (numberCovered == maxNumberCovered) { maxCoverNodeIndex = new Vector2(i, j); equally_covering_nodes.Add(maxCoverNodeIndex); } // Otherwise, empty the list and add this new best node if (numberCovered > maxNumberCovered) { maxNumberCovered = numberCovered; maxCoverNodeIndex = new Vector2(i, j); equally_covering_nodes.Clear(); equally_covering_nodes.Add(maxCoverNodeIndex); } } } // Find the best node from the list of those found previously if (coverNodes.Count > 0) { int min_dist = int.MaxValue, dist; for (int i = 0; i < equally_covering_nodes.Count; i++) { int index_node = (int)(equally_covering_nodes[i].x * gridNoZ + equally_covering_nodes[i].y); foreach (var covering_node in coverNodes) { dist = cost_matrix[covering_node.ij][index_node]; if (dist < min_dist) { min_dist = dist; maxCoverNodeIndex = equally_covering_nodes[i]; } } } } cellsCovered += maxNumberCovered; coverNodes.Add(grid[(int)maxCoverNodeIndex.x, (int)maxCoverNodeIndex.y]); for (int i = 0; i < gridNoX; ++i) { for (int j = 0; j < gridNoZ; ++j) { if (grid[i, j].IsCoveredBy(grid[(int)maxCoverNodeIndex.x, (int)maxCoverNodeIndex.y])) { grid[i, j].isCovered = true; } } } } }
// ------------------------------------------------- DefineCover public override void DefineCover () { int nOnPerimeter = Convert .ToInt32 ((2 * Math .PI * radius) / distanceNeighbours); CoverNode [] nodes = new CoverNode [nOnPerimeter + 1]; nodes [0] = new CoverNode (0, ptCenter, radius - nrSmall + 1, Cursors .SizeAll); for (int i = 1; i <= nOnPerimeter; i++) { nodes [i] = new CoverNode (i, Auxi_Geometry .PointToPoint (ptCenter, 2 * Math .PI * (i - 1) / nOnPerimeter, radius), nrSmall); nodes [i] .Clearance = false; } cover = new Cover (nodes); }
// ------------------------------------------------- DefineCover public override void DefineCover () { CoverNode [] nodes = new CoverNode [nNodesOnOuter + nNodesOnInner + nNodesPoly]; PointF [] ptOuter = new PointF [nNodesOnOuter]; for (int i = 0; i < nNodesOnOuter; i++) { ptOuter [i] = Auxi_Geometry .PointToPoint (ptCenter, 2 * Math .PI * i / nNodesOnOuter, nrOuter); } for (int i = 0; i < nNodesOnOuter; i++) { nodes [i] = new CoverNode (i, ptOuter [i], nrSmall); } for (int i = 0; i < nNodesOnInner; i++) { nodes [nNodesOnOuter + i] = new CoverNode (nNodesOnOuter + i, Auxi_Geometry .PointToPoint (ptCenter, 2 * Math .PI * i / nNodesOnInner, nrInner), nrSmall); } double ratioRadiuses = (double) nrInner / nrOuter; int nSmall = nNodesOnOuter + nNodesOnInner; PointF p0_in, p1_in, p0_out, p1_out; for (int i = 0; i < nNodesPoly; i++) { int jOutPt = (i * 2) % nNodesOnOuter; p0_out = ptOuter [jOutPt]; p1_out = ptOuter [(jOutPt + 2) % nNodesOnOuter]; p0_in = Auxi_Geometry .PointOnLine (ptCenter, p0_out, ratioRadiuses); p1_in = Auxi_Geometry .PointOnLine (ptCenter, p1_out, ratioRadiuses); nodes [nSmall + i] = new CoverNode (nSmall + i, new PointF [] { p0_in, p0_out, p1_out, p1_in }); } cover = new Cover (nodes); cover .SetClearance (NodeShape .Circle, false); }
// ------------------------------------------------- DefineCover public override void DefineCover () { CoverNode [] nodes = new CoverNode [4 + 1 + 4 + 1]; int nr = 5; nodes [0] = new CoverNode (0, ptLT, nr); nodes [1] = new CoverNode (1, ptRT, nr); nodes [2] = new CoverNode (2, ptRB, nr); nodes [3] = new CoverNode (3, ptLB, nr); nodes [4] = new CoverNode (4, ptRidge, nr); nodes [5] = new CoverNode (5, new PointF [] { ptLT, ptLB }, Cursors .Hand); nodes [6] = new CoverNode (6, new PointF [] { ptLT, ptRT }, Cursors .Hand); nodes [7] = new CoverNode (7, new PointF [] { ptRT, ptRB }, Cursors .Hand); nodes [8] = new CoverNode (8, new PointF [] { ptLB, ptRB }, Cursors .Hand); nodes [9] = new CoverNode (9, new PointF [] { ptLT, ptRidge, ptRT, ptRB, ptLB }); cover = new Cover (nodes); }