Implmentacja A*

This commit is contained in:
Jakub Łangowski 2021-04-25 17:52:21 +02:00
parent 5157efea48
commit ec76aedd82
20 changed files with 848 additions and 464 deletions

View File

@ -53,7 +53,7 @@
</PropertyGroup>
<ItemGroup>
<Compile Include="Assets\Logic\UI\UIInventoryManager.cs" />
<Compile Include="Assets\Logic\Agent\FringeNodes.cs" />
<Compile Include="Assets\Logic\Agent\FringeNode.cs" />
<Compile Include="Assets\Logic\Agent\Waitress.cs" />
<Compile Include="Assets\Logic\Data\Ingredient.cs" />
<Compile Include="Assets\Logic\Utils\FloatComparer.cs" />
@ -61,6 +61,7 @@
<Compile Include="Assets\Logic\SceneContext.cs" />
<Compile Include="Assets\Logic\Data\Money.cs" />
<Compile Include="Assets\Logic\Data\Customer.cs" />
<Compile Include="Assets\Logic\Agent\FringeNodeHeap.cs" />
<Compile Include="Assets\Logic\Agent\PathFinder.cs" />
<Compile Include="Assets\Logic\UIManager.cs" />
<Compile Include="Assets\Logic\Data\Food.cs" />
@ -69,6 +70,7 @@
<Compile Include="Assets\Logic\Agent\State.cs" />
<Compile Include="Assets\Logic\Utils\Randomizer.cs" />
<Compile Include="Assets\Logic\AgentManager.cs" />
<Compile Include="Assets\Logic\Utils\Heap.cs" />
<Compile Include="Assets\Logic\KitchenTableManager.cs" />
<Compile Include="Assets\Logic\UI\UIQueueManager.cs" />
<Compile Include="Assets\Logic\UI\UIQueue.cs" />

View File

@ -0,0 +1,78 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: NodeExplored_Mat
m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 0.18903318, g: 0.8773585, b: 0.16967781, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
m_BuildTextureStacks: []

View File

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9ac24eaf07a787147878b53b3ef377bc
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

View File

@ -7,7 +7,7 @@ Material:
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Node_mat
m_Name: Node_Mat
m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords:
m_LightmapFlags: 4

View File

@ -0,0 +1,34 @@
using Logic.Utils;
namespace Logic.Agent
{
public class FringeNode: IHeapItem<FringeNode>
{
public readonly State State;
public FringeNode Parent;
public AgentAction Action;
public float HCost;
public float GCost;
public int HeapIndex { get; set; }
public FringeNode(State state)
{
State = state;
}
public float FCost => GCost + HCost;
public int CompareTo(FringeNode other)
{
int compare = FCost.CompareTo(other.FCost);
if (compare == 0)
{
compare = HCost.CompareTo(other.HCost);
}
return -compare;
}
}
}

View File

@ -0,0 +1,31 @@
using Logic.Utils;
namespace Logic.Agent
{
public class FringeNodeHeap: Heap<FringeNode>
{
public FringeNodeHeap(int maxHeapSize) : base(maxHeapSize) { }
public bool Contains(FringeNode item)
{
foreach (FringeNode fringeNode in Items)
{
if (fringeNode != null && fringeNode.State.Equals(item.State))
return true;
}
return false;
}
public FringeNode GetItem(FringeNode item)
{
foreach (FringeNode fringeNode in Items)
{
if (fringeNode != null && fringeNode.State.Equals(item.State))
return fringeNode;
}
return null;
}
}
}

View File

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 34a52f0a39ad4d9faf3238d9cd5dd6bc
timeCreated: 1619354659

View File

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Logic.Agent;
namespace Assets.Logic.Agent
{
public class FringeNodes
{
public FringeNodes(State state)
{
State = state;
}
public State State;
public FringeNodes Parent;
public AgentAction Action;
}
}

View File

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.Logic.Agent;
using Logic.Graph;
using UnityEngine;
@ -9,10 +8,72 @@ namespace Logic.Agent
{
public class PathFinder : MonoBehaviour
{
public Stack<AgentAction> GraphSearch(Queue<FringeNodes> fringe, HashSet<FringeNodes> explored, State iState, State goalState)
public Stack<AgentAction> GraphSearchWithCost(FringeNodeHeap fringe, HashSet<FringeNode> explored, State iState, State goalState)
{
Stack<AgentAction> stack = new Stack<AgentAction>();
fringe.Enqueue(new FringeNodes(iState));
fringe.Enqueue(new FringeNode(iState));
while (fringe.Count != 0)
{
var elem = fringe.Dequeue();
if (goalTest(elem.State, goalState))
{
while (!elem.State.Equals(iState))
{
elem.State.AgentPosition.MarkAsPath();
stack.Push(elem.Action);
elem = elem.Parent;
}
return stack;
}
explored.Add(elem);
foreach (Tuple<State, AgentAction> successor in Succ(elem.State))
{
var x = new FringeNode(successor.Item1)
{
Parent = elem,
Action = successor.Item2,
HCost = GETDistanceBetweenStates(successor.Item1, goalState),
GCost = GETDistanceBetweenStates(elem.State, successor.Item1) + elem.GCost + successor.Item1.AgentPosition.GETNodeCost()
};
if (!fringe.Contains(x) && !explored.Any(z => z.State.Equals(successor.Item1)))
{
fringe.Enqueue(x);
x.State.AgentPosition.MarkAsExplored();
}
else if (fringe.Contains(x) && fringe.GetItem(x).FCost > x.FCost)
{
fringe.UpdateItem(x, fringe.GetItem(x).HeapIndex);
}
}
}
return stack;
}
private float GETDistanceBetweenStates(State state1, State state2)
{
var state1Pos = state1.AgentPosition.transform.position;
var state2Pos = state2.AgentPosition.transform.position;
float distX = Mathf.Abs(state1Pos.x - state2Pos.x);
float distY = Mathf.Abs(state1Pos.z - state2Pos.z);
if (state1.AgentRotation != state2.AgentRotation)
{
return distX + distY + SceneContext.Instance.rotationCost;
}
return distX + distY;
}
public Stack<AgentAction> GraphSearch(Queue<FringeNode> fringe, HashSet<FringeNode> explored, State iState, State goalState)
{
Stack<AgentAction> stack = new Stack<AgentAction>();
fringe.Enqueue(new FringeNode(iState));
while (fringe.Count != 0)
{
var elem = fringe.Dequeue();
@ -34,8 +95,9 @@ namespace Logic.Agent
if (fringe.Any(z =>
z.State.Equals(successor.Item1)) || explored.Any(z => z.State.Equals(successor.Item1)))
continue;
var x = new FringeNodes(successor.Item1) {Parent = elem, Action = successor.Item2};
var x = new FringeNode(successor.Item1) {Parent = elem, Action = successor.Item2};
fringe.Enqueue(x);
x.State.AgentPosition.MarkAsExplored();
}
}

View File

@ -1,7 +1,6 @@
using Logic.Graph;
using System;
namespace Assets.Logic.Agent
namespace Logic.Agent
{
public enum Rotation
{

View File

@ -2,8 +2,8 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Assets.Logic.Agent;
using Logic.Graph;
using Logic.Utils;
using UnityEngine;
using Debug = UnityEngine.Debug;
@ -17,11 +17,9 @@ namespace Logic.Agent
}
public class Waitress : MonoBehaviour
{
//[SerializeField] private Node currentNode;
public Node StartNode;
public Node startNode;
[SerializeField] private bool isFollowingPath;
[SerializeField] private bool canMove = true;
//private Node _previousNode;
private State _currentState;
private State _previousState;
private PathFinder _pathFinder;
@ -29,12 +27,8 @@ namespace Logic.Agent
void Awake()
{
_pathFinder = GetComponent<PathFinder>();
_currentState = new State();
_currentState.AgentPosition = StartNode;
_currentState.AgentRotation = Rotation.Top;
_previousState = new State();
_previousState.AgentPosition = StartNode;
_previousState.AgentRotation = Rotation.Top;
_currentState = new State {AgentPosition = startNode, AgentRotation = Rotation.Top};
_previousState = new State {AgentPosition = startNode, AgentRotation = Rotation.Top};
}
void Update()
@ -74,12 +68,30 @@ namespace Logic.Agent
goalState.AgentPosition = table;
goalState.AgentRotation = Rotation.Right;
Stack<AgentAction> actions = _pathFinder.GraphSearch(new Queue<FringeNodes>(), new HashSet<FringeNodes>(),
_currentState, goalState);
Stack<AgentAction> actions;
if (SceneContext.Instance.useAStar)
{
var priorityQueue = new FringeNodeHeap(SceneContext.Instance.map.Count * 4);
actions = _pathFinder.GraphSearchWithCost(priorityQueue, new HashSet<FringeNode>(), _currentState, goalState);
}
else
{
actions = _pathFinder.GraphSearch(new Queue<FringeNode>(), new HashSet<FringeNode>(), _currentState, goalState);
}
if (actions.Count > 0)
{
StartCoroutine(ExecuteActions(actions));
}
}
private void ClearMap()
{
foreach (Node node in SceneContext.Instance.map)
{
node.ClearPathMark();
}
}
private IEnumerator ExecuteActions(Stack<AgentAction> actions)
@ -118,18 +130,16 @@ namespace Logic.Agent
: Rotation.Left;
break;
case AgentAction.GoForward:
StartCoroutine(
RunToAnotherNode(_currentState.AgentPosition.FindNode(_currentState.AgentRotation)));
StartCoroutine(RunToAnotherNode(_currentState.AgentPosition.FindNode(_currentState.AgentRotation)));
break;
}
//node.Item2?.Invoke();
}
yield return new WaitForEndOfFrame();
}
isFollowingPath = false;
ClearMap();
}
private IEnumerator RotateLeft()
@ -160,7 +170,7 @@ namespace Logic.Agent
float i = 0;
while (i <= 1)
{
Debug.Log(i);
// Debug.Log(i);
transform.rotation = Quaternion.Slerp(startRotation, targetRotation, i);
yield return new WaitForEndOfFrame();
i += Time.deltaTime*3;

View File

@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Assets.Logic.Agent;
using Logic.Agent;
using Logic.Utils;
using UnityEngine;
@ -12,12 +12,10 @@ namespace Logic.Graph
public List<Node> neighbors;
[SerializeField] private Material nodeMat;
[SerializeField] private Material pathMat;
[SerializeField] private Material exploredMat;
[SerializeField] private bool debug = false;
[SerializeField] private int movementPenalty = 0;
[SerializeField] private int hCost;
[SerializeField] private int gCost;
public int FCost => gCost + hCost;
[SerializeField] private float movementPenalty;
private readonly float _maxRayRange = 0.75f;
private readonly float _maxTableRayRange = 0.5f;
@ -34,8 +32,14 @@ namespace Logic.Graph
{
_renderer = GetComponent<Renderer>();
InitializeNeighbours();
movementPenalty += SceneContext.Instance.nodeBaseCost;
}
public float GETNodeCost()
{
return movementPenalty;
}
public void MarkAsPath()
{
if (!gameObject.CompareTag("Table"))
@ -44,6 +48,14 @@ namespace Logic.Graph
}
}
public void MarkAsExplored()
{
if (!gameObject.CompareTag("Table"))
{
_renderer.material = exploredMat;
}
}
public void ClearPathMark()
{
if (!gameObject.CompareTag("Table"))
@ -67,11 +79,11 @@ namespace Logic.Graph
case Rotation.Top:
return neighbors.FirstOrDefault(x =>
x.transform.position.x.IsEq(transform.position.x) &&
x.transform.position.z.IsEq(transform.position.z + 1.25f));
x.transform.position.z.IsEq(transform.position.z + 1));
case Rotation.Bottom:
return neighbors.FirstOrDefault(x =>
x.transform.position.x.IsEq(transform.position.x) &&
x.transform.position.z.IsEq(transform.position.z - 1.25f));
x.transform.position.z.IsEq(transform.position.z - 1));
default:
return null;
}
@ -176,7 +188,6 @@ namespace Logic.Graph
}
}
}
}

View File

@ -10,6 +10,9 @@ namespace Logic
{
public List<Node> map;
public ObstacleData[] obstacles;
public float nodeBaseCost;
public float rotationCost;
public bool useAStar = true;
public static SceneContext Instance;
void Awake()

110
Assets/Logic/Utils/Heap.cs Normal file
View File

@ -0,0 +1,110 @@
using System;
namespace Logic.Utils
{
public class Heap<T> where T : IHeapItem<T>
{
protected readonly T[] Items;
private int _currentItemCount;
protected Heap(int maxHeapSize)
{
Items = new T[maxHeapSize];
}
public void Enqueue(T item)
{
item.HeapIndex = _currentItemCount;
Items[_currentItemCount] = item;
SortUp(item);
_currentItemCount++;
}
public T Dequeue()
{
T firstItem = Items[0];
_currentItemCount--;
Items[0] = Items[_currentItemCount];
Items[0].HeapIndex = 0;
SortDown(Items[0]);
return firstItem;
}
public void UpdateItem(T item, int index)
{
item.HeapIndex = index;
Items[index] = item;
SortUp(item);
}
public int Count => _currentItemCount;
private void SortDown(T item)
{
while (true)
{
int childIndexLeft = item.HeapIndex * 2 + 1;
int childIndexRight = item.HeapIndex * 2 + 2;
int swapIndex = 0;
if (childIndexLeft < _currentItemCount)
{
swapIndex = childIndexLeft;
if (childIndexRight < _currentItemCount)
{
if (Items[childIndexLeft].CompareTo(Items[childIndexRight]) < 0)
{
swapIndex = childIndexRight;
}
}
if (item.CompareTo(Items[swapIndex]) < 0)
{
Swap(item, Items[swapIndex]);
}
else
{
return;
}
}
else
{
return;
}
}
}
private void SortUp(T item)
{
int parentIndex = (item.HeapIndex - 1) / 2;
while (true)
{
T parentItem = Items[parentIndex];
if (item.CompareTo(parentItem) > 0)
{
Swap(item, parentItem);
}
else
{
break;
}
parentIndex = (item.HeapIndex - 1) / 2;
}
}
private void Swap(T itemA, T itemB)
{
Items[itemA.HeapIndex] = itemB;
Items[itemB.HeapIndex] = itemA;
int itemAIndex = itemA.HeapIndex;
itemA.HeapIndex = itemB.HeapIndex;
itemB.HeapIndex = itemAIndex;
}
}
public interface IHeapItem<T> : IComparable<T>
{
int HeapIndex { get; set; }
}
}

View File

@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 92f8dbe7c78e4a119f67c2ce3b6a4b5f
timeCreated: 1619189961

View File

@ -11,7 +11,6 @@ GameObject:
- component: {fileID: 6453329937250285970}
- component: {fileID: 8315836113623620561}
- component: {fileID: 7059161905270609152}
- component: {fileID: 2089487727296566617}
m_Layer: 9
m_Name: BarObstacle
m_TagString: Untagged
@ -46,22 +45,9 @@ BoxCollider:
m_IsTrigger: 0
m_Enabled: 1
serializedVersion: 2
m_Size: {x: 1, y: 1.1, z: 1.1}
m_Size: {x: 1, y: 1, z: 1}
m_Center: {x: 0, y: 0, z: 0}
--- !u!114 &7059161905270609152
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 4775359161287261870}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: d9978794eb6647e2972119f5cdf214d6, type: 3}
m_Name:
m_EditorClassIdentifier:
obstacleType: 0
--- !u!114 &2089487727296566617
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
@ -101,7 +87,7 @@ Transform:
m_GameObject: {fileID: 7458537012890967998}
m_LocalRotation: {x: -0, y: -0, z: 0.7071069, w: 0.70710677}
m_LocalPosition: {x: -0.000000017881, y: 0, z: -0.003}
m_LocalScale: {x: 0.34042966, y: 1, z: 1}
m_LocalScale: {x: 0.32, y: 1, z: 1}
m_Children: []
m_Father: {fileID: 6453329937250285970}
m_RootOrder: 1
@ -182,7 +168,7 @@ Transform:
m_GameObject: {fileID: 8706372573158961954}
m_LocalRotation: {x: -0, y: -0, z: 0.7071069, w: 0.70710677}
m_LocalPosition: {x: -0.00000059678, y: -0.00000044656, z: -0.50938}
m_LocalScale: {x: 0.33080274, y: 1, z: 0.50625}
m_LocalScale: {x: 0.315, y: 1, z: 0.50625}
m_Children: []
m_Father: {fileID: 6453329937250285970}
m_RootOrder: 0

View File

@ -46,15 +46,12 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: c774c22d330c32f48bfaca0426c29ad5, type: 3}
m_Name:
m_EditorClassIdentifier:
neighbors: []
nodeMat: {fileID: 2100000, guid: bc3e8f6bac7842c4ab76e3b39f31a353, type: 2}
pathMat: {fileID: 2100000, guid: 1293cff8126771046a5a69f1aa772d65, type: 2}
neighbors: []
maxRange: 0.75
maxSphereRange: 0.25
exploredMat: {fileID: 2100000, guid: 9ac24eaf07a787147878b53b3ef377bc, type: 2}
debug: 0
movementPenalty: 0
hCost: 0
gCost: 0
--- !u!23 &5273760715526374001
MeshRenderer:
m_ObjectHideFlags: 0

View File

@ -186,7 +186,7 @@ Transform:
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 2381946650362024112}
m_LocalRotation: {x: -0.00000019949603, y: 0.7071068, z: 0.7071068, w: 0.00000019949603}
m_LocalPosition: {x: 0, y: -0.018, z: 0.425}
m_LocalPosition: {x: 0, y: 0.003, z: 0.301}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 7930305233008882851}
@ -336,11 +336,12 @@ MonoBehaviour:
m_Script: {fileID: 11500000, guid: 682c70c355804410af55074b0d8c0a88, type: 3}
m_Name:
m_EditorClassIdentifier:
neighbors: []
nodeMat: {fileID: 0}
pathMat: {fileID: 0}
neighbors: []
maxRange: 0.1
exploredMat: {fileID: 0}
debug: 0
movementPenalty: 0
recipePrefab: {fileID: 1685343955664076, guid: 72653085a6b827f48b10b434c7972f1c, type: 3}
moneyPrefab: {fileID: 1950871307682000, guid: 01348926c7cbb3347a006c37204131c3, type: 3}
spawnPoint: {fileID: 5331314718952806374}
@ -702,7 +703,7 @@ Transform:
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 8350420071825697581}
m_LocalRotation: {x: -0.7071068, y: 0, z: 0, w: 0.7071068}
m_LocalPosition: {x: 0, y: -0.01, z: -0.376}
m_LocalPosition: {x: 0, y: 0.016, z: -0.218}
m_LocalScale: {x: 1, y: 1, z: 1}
m_Children:
- {fileID: 6488503019443644745}

File diff suppressed because it is too large Load Diff