Add MrGameEng.Pathfinding and MrGameEng.Collisions modules
CI / build-test (push) Failing after 1m5s
CI / build-test (push) Failing after 1m5s
Pathfinding (depends on Core only): GridPathfinder with A* (octile/
Manhattan heuristic), Dijkstra and BFS over a game-implemented
IPathGrid; 4/8 connectivity, diagonals never cut corners. FlowField +
FlowFieldBuilder (multi-source Dijkstra) give crowds O(1) steering per
agent per frame. All buffers are grid-sized once and invalidated by a
generation stamp - repeated queries allocate nothing and clear nothing.
Collisions (Graphics exception: Transform2D, RectF): Collider component
(circle/AABB, offset, two-way layer masks), CollisionWorld - a uniform
spatial hash on flat arrays rebuilt from scratch each tick (O(n) for
movers, zero alloc after warm-up, deterministic pair order), pair
collection, QueryAabb and closest-hit Raycast. scene.UseCollisions()
registers CollisionSystem after movement systems.
30 new tests (string-map mazes, cost weighting, corner cutting, flow
descent; pair/mask/query/raycast). Sample gains a PathfindingScene
('path' console command): click to set the goal, 250 agents follow the
flow field, the A* path is highlighted, colliding agents flash red.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
b3415120c3
commit
a395e58458
@@ -21,13 +21,17 @@ renderer, camera, sprites), `Input`, `Audio`, `Assets` (runtime loading, no cont
|
||||
pipeline), `Assets.Generator` (Roslyn source generator for typed asset handles),
|
||||
`Atlases` (texture-atlas builder + runtime loader; CLI wrapper in `tools/MrGameEng.AtlasTool`),
|
||||
`Tilemaps` (code-built tile grids rendered through the batcher; `scene.UseTilemaps()`
|
||||
after `UseRenderer2D()`), `UI` (Myra integration: `scene.UseUI()` after `UseRenderer2D()`),
|
||||
after `UseRenderer2D()`), `Pathfinding` (grid A*/Dijkstra/BFS and flow fields over a
|
||||
game-implemented `IPathGrid`; Core-only, owns no world data), `Collisions` (`Collider`
|
||||
component, spatial hash rebuilt per tick, pairs/queries/raycast; `scene.UseCollisions()`
|
||||
after movement systems), `UI` (Myra integration: `scene.UseUI()` after `UseRenderer2D()`),
|
||||
`DevConsole` (in-game console capturing `Core.Log`; `scene.UseDevConsole()` last in OnLoad).
|
||||
Dependency rule: every module may depend only on `Core`; `Core` depends only on
|
||||
MonoGame and Friflo.Engine.ECS. `Assets.Generator` is a netstandard2.0 analyzer.
|
||||
Documented exceptions: Myra renders with its own SpriteBatch internally; `Atlases`
|
||||
depends on `Graphics` (Texture2DRegion) and `Assets` (loader registration);
|
||||
`Tilemaps` depends on `Graphics` (regions, layers, renderer).
|
||||
`Tilemaps` depends on `Graphics` (regions, layers, renderer);
|
||||
`Collisions` depends on `Graphics` (Transform2D, RectF).
|
||||
|
||||
## Commands
|
||||
|
||||
|
||||
@@ -49,6 +49,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Tilemaps", "src\M
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Tilemaps.Tests", "tests\MrGameEng.Tilemaps.Tests\MrGameEng.Tilemaps.Tests.csproj", "{10B318BB-BB00-4A9D-8AF3-D36C570B6286}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Pathfinding", "src\MrGameEng.Pathfinding\MrGameEng.Pathfinding.csproj", "{84064C54-688F-4A58-9EC6-BFD478816306}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Collisions", "src\MrGameEng.Collisions\MrGameEng.Collisions.csproj", "{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Pathfinding.Tests", "tests\MrGameEng.Pathfinding.Tests\MrGameEng.Pathfinding.Tests.csproj", "{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MrGameEng.Collisions.Tests", "tests\MrGameEng.Collisions.Tests\MrGameEng.Collisions.Tests.csproj", "{B8C132F5-C4C8-4931-B0CE-885811F44DB0}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -287,6 +295,54 @@ Global
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Release|x64.Build.0 = Release|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286}.Release|x86.Build.0 = Release|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Release|x64.Build.0 = Release|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306}.Release|x86.Build.0 = Release|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|x64.Build.0 = Release|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC}.Release|x86.Build.0 = Release|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|x64.Build.0 = Release|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3}.Release|x86.Build.0 = Release|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@@ -311,5 +367,9 @@ Global
|
||||
{1951D50B-122A-45B5-9356-F186A3CBC974} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
{43FCB103-4EBA-464D-BF39-9F1FA83E52E9} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{10B318BB-BB00-4A9D-8AF3-D36C570B6286} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
{84064C54-688F-4A58-9EC6-BFD478816306} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{E069CBFD-F4FA-4400-84AE-090F9B81BDFC} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B}
|
||||
{D9FFA22D-0CFF-4A1E-AD56-BA4BD00526B3} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
{B8C132F5-C4C8-4931-B0CE-885811F44DB0} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
@@ -35,6 +35,8 @@
|
||||
| `MrGameEng.Assets.Generator` | Roslyn incremental source generator: классы с типизированными хендлами ресурсов |
|
||||
| `MrGameEng.Atlases` | Текстурные атласы: офлайн-сборка из дерева картинок (`AtlasBuilder`) и рантайм-загрузка (`TextureAtlas`); CLI — `tools/MrGameEng.AtlasTool` |
|
||||
| `MrGameEng.Tilemaps` | Тайловые карты, создаваемые кодом: `TileGrid` + `TileSet` + компонент `Tilemap`, отрисовка видимых клеток через батчер |
|
||||
| `MrGameEng.Pathfinding` | Поиск пути по гриду: A*, Dijkstra, BFS и flow fields для толп; чистая логика без зависимостей |
|
||||
| `MrGameEng.Collisions` | Определение столкновений: компонент `Collider`, spatial hash, пары/запросы/raycast |
|
||||
| `MrGameEng.UI` | Игровой UI на [Myra](https://github.com/rds1983/Myra): `Desktop` на сцену, виджеты, скининг |
|
||||
| `MrGameEng.DevConsole` | Ингейм-консоль разработчика: логи `Log`, команды, история, автодополнение |
|
||||
|
||||
@@ -183,6 +185,41 @@ CLI-обёртка: `dotnet run --project tools/MrGameEng.AtlasTool -- <исто
|
||||
от экрана, а не от размера грида. Тайлы батчатся со спрайтами по обычному порядку
|
||||
слой → depth → текстура: пол из одной текстуры атласа — один draw call.
|
||||
|
||||
## Поиск пути
|
||||
|
||||
`MrGameEng.Pathfinding` — алгоритмы поиска пути по гриду; зависит только от Core
|
||||
и не владеет данными мира — игра реализует `IPathGrid` (Width/Height,
|
||||
`IsPassable`, `Cost ≥ 1`) поверх своего рельефа или `TileGrid`.
|
||||
|
||||
- `GridPathfinder.FindPath(start, goal, path, algorithm)` — **A\*** (octile/Manhattan
|
||||
эвристика), **Dijkstra** (с учётом цены клеток) и **BFS** (быстрейший для
|
||||
равномерных гридов, цену игнорирует). Связность 4 или 8; диагонали никогда
|
||||
не срезают углы.
|
||||
- `FlowFieldBuilder.Build(goals, field)` — multi-source Dijkstra строит **flow field**:
|
||||
дистанция + нормализованное направление на клетку. Толпа любого размера дальше
|
||||
стоит O(1) на агента в кадр — основной инструмент для масс агентов (LittleSim).
|
||||
- Оптимизация под ECS: все буферы созданы один раз под размер грида и
|
||||
инвалидируются generation-штампом — повторные запросы не аллоцируют и не чистят
|
||||
массивы. Один экземпляр на систему; результаты детерминированы.
|
||||
|
||||
## Коллизии
|
||||
|
||||
`MrGameEng.Collisions` — определение столкновений (без разрешения физики — она в бэклоге):
|
||||
|
||||
- Компонент `Collider` (`struct : IComponent`): круг или AABB (без вращения),
|
||||
`Offset`, битовые маски `Layer`/`CollidesWith` (пара регистрируется, только если
|
||||
маски согласны в обе стороны). Создание через `Collider.Circle(r)` / `Collider.Box(w,h)`.
|
||||
- `CollisionWorld` — uniform spatial hash на плоских массивах (головы бакетов +
|
||||
связные списки индексов), **перестраивается с нуля каждый тик** за O(n): для
|
||||
движущихся сущностей это дешевле инкрементальных обновлений. Ноль аллокаций
|
||||
после прогрева; порядок пар детерминирован (порядок чанков Friflo).
|
||||
- `scene.UseCollisions(cellSize)` добавляет `CollisionSystem` — регистрируй её
|
||||
**после** систем движения; системы, читающие `world.Pairs`, — после неё.
|
||||
- Запросы для игровых систем: `Pairs` (пересекающиеся пары кадра),
|
||||
`QueryAabb(rect, span)`, `Raycast(from, to, mask)` (ближайшее попадание).
|
||||
- `cellSize` подбирается под типичный размер коллайдера; крупные коллайдеры
|
||||
занимают несколько ячеек — корректность не страдает, страдает константа.
|
||||
|
||||
## Рендеринг
|
||||
|
||||
`SpriteBatch` в движке **не используется** — в `MrGameEng.Graphics` свой батчер,
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Assets\MrGameEng.Assets.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Atlases\MrGameEng.Atlases.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Tilemaps\MrGameEng.Tilemaps.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Pathfinding\MrGameEng.Pathfinding.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Collisions\MrGameEng.Collisions.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.UI\MrGameEng.UI.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.DevConsole\MrGameEng.DevConsole.csproj" />
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Assets.Generator\MrGameEng.Assets.Generator.csproj"
|
||||
|
||||
@@ -168,6 +168,13 @@ public sealed class MainScene : Scene
|
||||
}
|
||||
});
|
||||
console.Register("beep", "play the beep sound", (_, _) => audio.Play(beep));
|
||||
console.Register("path", "switch to the pathfinding & collisions demo", (_, _) =>
|
||||
{
|
||||
if (!Context.Scenes.IsTransitioning)
|
||||
{
|
||||
Context.Scenes.Switch(new PathfindingScene(), Transition.Fade(0.6f));
|
||||
}
|
||||
});
|
||||
console.Register("atlas", "list texture atlas regions", (c, _) =>
|
||||
{
|
||||
c.WriteLine($"atlas '{atlas.Name}': {atlas.Pages.Count} page(s), {atlas.Regions.Count} region(s)");
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Friflo.Engine.ECS.Systems;
|
||||
using Microsoft.Xna.Framework;
|
||||
using MrGameEng.Assets;
|
||||
using MrGameEng.Collisions;
|
||||
using MrGameEng.Core;
|
||||
using MrGameEng.DevConsole;
|
||||
using MrGameEng.Graphics;
|
||||
using MrGameEng.Input;
|
||||
using MrGameEng.Pathfinding;
|
||||
using MrGameEng.UI;
|
||||
|
||||
namespace MrGameEng.Sample.Scenes;
|
||||
|
||||
/// <summary>
|
||||
/// Демо поиска пути и коллизий: ЛКМ ставит цель — толпа агентов стекается к ней по
|
||||
/// flow field, жёлтым подсвечен A*-путь из левого верхнего угла, столкнувшиеся агенты
|
||||
/// вспыхивают красным. Tab/'main' — назад.
|
||||
/// </summary>
|
||||
public sealed class PathfindingScene : Scene
|
||||
{
|
||||
private const int CellsX = 64;
|
||||
private const int CellsY = 36;
|
||||
private const int CellSize = 20;
|
||||
private const int AgentCount = 250;
|
||||
private static readonly Point AStarStart = new(1, 1);
|
||||
|
||||
private readonly WallGrid _grid = new(CellsX, CellsY, seed: 99);
|
||||
private readonly FlowField _field = new();
|
||||
private readonly List<Point> _path = [];
|
||||
private readonly List<Entity> _pathMarkers = [];
|
||||
private FlowFieldBuilder _builder = null!;
|
||||
private GridPathfinder _pathfinder = null!;
|
||||
private Texture2DRegion _white = null!;
|
||||
private Entity _goalMarker;
|
||||
|
||||
/// <summary>Состояние агента: время красной вспышки после столкновения.</summary>
|
||||
private struct AgentState : IComponent
|
||||
{
|
||||
public float Flash;
|
||||
}
|
||||
|
||||
protected override void OnLoad()
|
||||
{
|
||||
var assets = Context.Services.GetOrDefault<AssetManager>() ?? Context.UseAssets();
|
||||
var input = this.UseInput();
|
||||
var actions = SampleInput.CreateActions(input);
|
||||
var renderer = this.UseRenderer2D(new Renderer2DOptions { VirtualResolution = new Point(1280, 720) });
|
||||
SampleLayers.EnsureRegistered(renderer);
|
||||
|
||||
var shapesTexture = assets.Load(GameAssets.Textures.Shapes);
|
||||
_white = new Texture2DRegion(shapesTexture, new Rectangle(40, 41, 14, 14)); // жёлтый квадрат как "белый" регион
|
||||
_builder = new FlowFieldBuilder(_grid);
|
||||
_pathfinder = new GridPathfinder(_grid);
|
||||
|
||||
// Стены.
|
||||
for (var y = 0; y < CellsY; y++)
|
||||
{
|
||||
for (var x = 0; x < CellsX; x++)
|
||||
{
|
||||
if (!_grid.IsPassable(x, y))
|
||||
{
|
||||
var sprite = new Sprite(_white) { Color = new Color(70, 74, 84), Depth = 0f };
|
||||
Store.CreateEntity(CellTransform(x, y), sprite);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Агенты на проходимых клетках.
|
||||
var random = new Random(7);
|
||||
for (var i = 0; i < AgentCount; i++)
|
||||
{
|
||||
var cell = RandomPassableCell(random);
|
||||
var sprite = new Sprite(_white) { Color = new Color(120, 180, 255), Depth = 1f };
|
||||
sprite.CenterOrigin();
|
||||
Store.CreateEntity(
|
||||
new Transform2D(CellCenter(cell), scale: new Vector2(0.45f)),
|
||||
sprite,
|
||||
new AgentState(),
|
||||
Collider.Circle(4f));
|
||||
}
|
||||
|
||||
// Маркер цели.
|
||||
var goalSprite = new Sprite(_white) { Color = new Color(80, 220, 120), Depth = 0.6f };
|
||||
_goalMarker = Store.CreateEntity(CellTransform(0, 0), goalSprite);
|
||||
|
||||
var world = this.UseCollisions(cellSize: 16f);
|
||||
|
||||
UpdateSystems.Add(new ClickTargetSystem(this, input, renderer));
|
||||
UpdateSystems.Add(new AgentSteerSystem(this));
|
||||
UpdateSystems.Add(new CollisionFlashSystem(world));
|
||||
UpdateSystems.Add(new FlashDecaySystem());
|
||||
UpdateSystems.Add(new SceneHotkeysSystem(Context, actions, () => new MainScene(), Transition.Fade(0.6f)));
|
||||
|
||||
var desktop = this.UseUI();
|
||||
var label = new Myra.Graphics2D.UI.Label
|
||||
{
|
||||
Text = "ЛКМ — цель: толпа идёт по flow field, жёлтое — путь A*.\nСтолкновения агентов подсвечиваются красным. Tab — назад.",
|
||||
};
|
||||
desktop.Root = new Myra.Graphics2D.UI.VerticalStackPanel { Left = 12, Top = 12 };
|
||||
((Myra.Graphics2D.UI.VerticalStackPanel)desktop.Root).Widgets.Add(label);
|
||||
|
||||
this.UseDevConsole();
|
||||
|
||||
SetGoal(new Point(CellsX / 2, CellsY / 2));
|
||||
}
|
||||
|
||||
private void SetGoal(Point goal)
|
||||
{
|
||||
if (!_grid.IsPassable(goal.X, goal.Y))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_builder.Build([goal], _field);
|
||||
_goalMarker.GetComponent<Transform2D>().Position = CellTopLeft(goal);
|
||||
|
||||
foreach (var marker in _pathMarkers)
|
||||
{
|
||||
marker.DeleteEntity();
|
||||
}
|
||||
|
||||
_pathMarkers.Clear();
|
||||
if (_pathfinder.FindPath(AStarStart, goal, _path))
|
||||
{
|
||||
foreach (var cell in _path)
|
||||
{
|
||||
var sprite = new Sprite(_white) { Color = new Color(240, 210, 60) * 0.55f, Depth = 0.5f };
|
||||
_pathMarkers.Add(Store.CreateEntity(CellTransform(cell.X, cell.Y), sprite));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Transform2D CellTransform(int x, int y) =>
|
||||
new(CellTopLeft(new Point(x, y)), scale: new Vector2(CellSize / 14f));
|
||||
|
||||
private static Vector2 CellTopLeft(Point cell) => new(cell.X * CellSize, cell.Y * CellSize);
|
||||
|
||||
private static Vector2 CellCenter(Point cell) =>
|
||||
new(cell.X * CellSize + CellSize / 2f, cell.Y * CellSize + CellSize / 2f);
|
||||
|
||||
private Point RandomPassableCell(Random random)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var cell = new Point(random.Next(CellsX), random.Next(CellsY));
|
||||
if (_grid.IsPassable(cell.X, cell.Y))
|
||||
{
|
||||
return cell;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Случайные прямоугольные стены; старт A* и центр всегда свободны.</summary>
|
||||
private sealed class WallGrid : IPathGrid
|
||||
{
|
||||
private readonly bool[,] _walls;
|
||||
|
||||
public WallGrid(int width, int height, int seed)
|
||||
{
|
||||
Width = width;
|
||||
Height = height;
|
||||
_walls = new bool[width, height];
|
||||
var random = new Random(seed);
|
||||
for (var i = 0; i < 70; i++)
|
||||
{
|
||||
var w = random.Next(1, 7);
|
||||
var h = random.Next(1, 7);
|
||||
var x0 = random.Next(width - w);
|
||||
var y0 = random.Next(height - h);
|
||||
for (var y = y0; y < y0 + h; y++)
|
||||
{
|
||||
for (var x = x0; x < x0 + w; x++)
|
||||
{
|
||||
_walls[x, y] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var y = 0; y < 3; y++)
|
||||
{
|
||||
for (var x = 0; x < 3; x++)
|
||||
{
|
||||
_walls[AStarStart.X + x, AStarStart.Y + y] = false;
|
||||
_walls[width / 2 + x - 1, height / 2 + y - 1] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int Width { get; }
|
||||
|
||||
public int Height { get; }
|
||||
|
||||
public bool IsPassable(int x, int y) => !_walls[x, y];
|
||||
|
||||
public float Cost(int x, int y) => 1f;
|
||||
}
|
||||
|
||||
private sealed class ClickTargetSystem(PathfindingScene scene, InputManager input, Renderer2D renderer) : BaseSystem
|
||||
{
|
||||
protected override void OnUpdateGroup()
|
||||
{
|
||||
if (!input.IsMousePressed(MouseButton.Left))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var world = renderer.ScreenToWorld(input.MousePosition.ToVector2());
|
||||
var cell = new Point((int)(world.X / CellSize), (int)(world.Y / CellSize));
|
||||
if (cell.X >= 0 && cell.X < CellsX && cell.Y >= 0 && cell.Y < CellsY)
|
||||
{
|
||||
scene.SetGoal(cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class AgentSteerSystem(PathfindingScene scene) : QuerySystem<Transform2D, AgentState>
|
||||
{
|
||||
private const float Speed = 70f;
|
||||
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
var delta = Tick.deltaTime;
|
||||
var field = scene._field;
|
||||
foreach (var (transforms, _, _) in Query.Chunks)
|
||||
{
|
||||
var t = transforms.Span;
|
||||
for (var i = 0; i < t.Length; i++)
|
||||
{
|
||||
ref var position = ref t[i].Position;
|
||||
var cx = Math.Clamp((int)(position.X / CellSize), 0, CellsX - 1);
|
||||
var cy = Math.Clamp((int)(position.Y / CellSize), 0, CellsY - 1);
|
||||
if (!field.IsReachable(cx, cy) || field.DistanceAt(cx, cy) <= 0.6f)
|
||||
{
|
||||
continue; // недостижимо или уже у цели
|
||||
}
|
||||
|
||||
position += field.DirectionAt(cx, cy) * (Speed * delta);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class CollisionFlashSystem(CollisionWorld world) : BaseSystem
|
||||
{
|
||||
protected override void OnUpdateGroup()
|
||||
{
|
||||
foreach (var pair in world.Pairs)
|
||||
{
|
||||
Flash(pair.A);
|
||||
Flash(pair.B);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Flash(Entity entity)
|
||||
{
|
||||
if (entity.HasComponent<AgentState>())
|
||||
{
|
||||
entity.GetComponent<AgentState>().Flash = 0.25f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FlashDecaySystem : QuerySystem<AgentState, Sprite>
|
||||
{
|
||||
private static readonly Color Calm = new(120, 180, 255);
|
||||
private static readonly Color Hit = new(235, 70, 60);
|
||||
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
var delta = Tick.deltaTime;
|
||||
foreach (var (states, sprites, _) in Query.Chunks)
|
||||
{
|
||||
var a = states.Span;
|
||||
var s = sprites.Span;
|
||||
for (var i = 0; i < a.Length; i++)
|
||||
{
|
||||
a[i].Flash = Math.Max(0f, a[i].Flash - delta);
|
||||
s[i].Color = a[i].Flash > 0f ? Hit : Calm;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Microsoft.Xna.Framework;
|
||||
|
||||
namespace MrGameEng.Collisions;
|
||||
|
||||
/// <summary>Shape of a <see cref="Collider"/>.</summary>
|
||||
public enum ColliderShape : byte
|
||||
{
|
||||
/// <summary>Circle of <see cref="Collider.Radius"/>.</summary>
|
||||
Circle,
|
||||
|
||||
/// <summary>Axis-aligned box of <see cref="Collider.HalfExtents"/>. Does not rotate with the entity.</summary>
|
||||
Box,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collision shape component. Create via <see cref="Circle"/> or <see cref="Box"/> —
|
||||
/// the struct default has no size and collides with nothing.
|
||||
/// Positions come from <c>Transform2D</c>; <see cref="Offset"/> shifts the shape
|
||||
/// relative to it (entity scale and rotation are not applied to collider shapes).
|
||||
/// </summary>
|
||||
public struct Collider : IComponent
|
||||
{
|
||||
/// <summary>Shape kind.</summary>
|
||||
public ColliderShape Shape;
|
||||
|
||||
/// <summary>Circle radius in world units (<see cref="ColliderShape.Circle"/> only).</summary>
|
||||
public float Radius;
|
||||
|
||||
/// <summary>Half extents of the box (<see cref="ColliderShape.Box"/> only).</summary>
|
||||
public Vector2 HalfExtents;
|
||||
|
||||
/// <summary>Shape center offset from the entity's transform position.</summary>
|
||||
public Vector2 Offset;
|
||||
|
||||
/// <summary>Bit mask of layers this collider belongs to.</summary>
|
||||
public uint Layer;
|
||||
|
||||
/// <summary>Bit mask of layers this collider collides with. A pair is reported only when the masks agree both ways.</summary>
|
||||
public uint CollidesWith;
|
||||
|
||||
/// <summary>Creates a circle collider on layer 1 colliding with everything.</summary>
|
||||
public static Collider Circle(float radius, Vector2 offset = default) => new()
|
||||
{
|
||||
Shape = ColliderShape.Circle,
|
||||
Radius = radius,
|
||||
Offset = offset,
|
||||
Layer = 1,
|
||||
CollidesWith = uint.MaxValue,
|
||||
};
|
||||
|
||||
/// <summary>Creates a box collider on layer 1 colliding with everything.</summary>
|
||||
public static Collider Box(float width, float height, Vector2 offset = default) => new()
|
||||
{
|
||||
Shape = ColliderShape.Box,
|
||||
HalfExtents = new Vector2(width / 2f, height / 2f),
|
||||
Offset = offset,
|
||||
Layer = 1,
|
||||
CollidesWith = uint.MaxValue,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Friflo.Engine.ECS.Systems;
|
||||
using MrGameEng.Core;
|
||||
using MrGameEng.Graphics;
|
||||
|
||||
namespace MrGameEng.Collisions;
|
||||
|
||||
/// <summary>
|
||||
/// Rebuilds the <see cref="CollisionWorld"/> from every entity that has both
|
||||
/// <c>Transform2D</c> and <see cref="Collider"/>. Register it <b>after</b> movement
|
||||
/// systems so pairs reflect this tick's final positions.
|
||||
/// </summary>
|
||||
public sealed class CollisionSystem : QuerySystem<Transform2D, Collider>
|
||||
{
|
||||
private readonly CollisionWorld _world;
|
||||
|
||||
/// <summary>Creates the system for <paramref name="world"/>.</summary>
|
||||
public CollisionSystem(CollisionWorld world) => _world = world;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
_world.BeginRebuild();
|
||||
foreach (var (transforms, colliders, entities) in Query.Chunks)
|
||||
{
|
||||
var t = transforms.Span;
|
||||
var c = colliders.Span;
|
||||
for (var i = 0; i < t.Length; i++)
|
||||
{
|
||||
_world.Add(entities.EntityAt(i), in t[i], in c[i]);
|
||||
}
|
||||
}
|
||||
|
||||
_world.EndRebuild();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Wires collision detection into a <see cref="Scene"/>.</summary>
|
||||
public static class SceneCollisionsExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the shared <see cref="CollisionWorld"/> service (created on first use with
|
||||
/// <paramref name="cellSize"/>) and adds <see cref="CollisionSystem"/> to this scene's
|
||||
/// update phase. Call from <c>OnLoad</c> <b>after</b> adding movement systems; read
|
||||
/// <see cref="CollisionWorld.Pairs"/> from systems registered later.
|
||||
/// </summary>
|
||||
public static CollisionWorld UseCollisions(this Scene scene, float cellSize = 64f)
|
||||
{
|
||||
var services = scene.Context.Services;
|
||||
var world = services.GetOrDefault<CollisionWorld>();
|
||||
if (world is null)
|
||||
{
|
||||
world = new CollisionWorld(cellSize);
|
||||
services.Add(world);
|
||||
}
|
||||
|
||||
scene.UpdateSystems.Add(new CollisionSystem(world));
|
||||
return world;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Microsoft.Xna.Framework;
|
||||
using MrGameEng.Graphics;
|
||||
|
||||
namespace MrGameEng.Collisions;
|
||||
|
||||
/// <summary>A pair of entities whose colliders overlap this frame.</summary>
|
||||
public readonly record struct CollisionPair(Entity A, Entity B);
|
||||
|
||||
/// <summary>Result of a <see cref="CollisionWorld.Raycast"/>.</summary>
|
||||
public readonly record struct RaycastHit(Entity Entity, Vector2 Point, float Fraction);
|
||||
|
||||
/// <summary>
|
||||
/// Broad + narrow phase collision detection over a uniform spatial hash, rebuilt from
|
||||
/// scratch every tick by <see cref="CollisionSystem"/> — O(n) for moving entities, flat
|
||||
/// arrays only, no allocations after warm-up. Overlapping pairs are collected into
|
||||
/// <see cref="Pairs"/> (deterministic order); ad-hoc area/ray queries are available to
|
||||
/// game systems at any point after the rebuild.
|
||||
/// </summary>
|
||||
public sealed class CollisionWorld
|
||||
{
|
||||
private struct Entry
|
||||
{
|
||||
public Entity Entity;
|
||||
public Vector2 Center;
|
||||
public RectF Aabb;
|
||||
public float Radius;
|
||||
public Vector2 HalfExtents;
|
||||
public uint Layer;
|
||||
public uint CollidesWith;
|
||||
public ColliderShape Shape;
|
||||
}
|
||||
|
||||
private readonly float _cellSize;
|
||||
private Entry[] _entries = new Entry[256];
|
||||
private int _count;
|
||||
|
||||
// Spatial hash: головы бакетов + связные списки вставок (по индексу записи на ячейку).
|
||||
private int[] _bucketHeads = new int[512];
|
||||
private int[] _cellNext = new int[1024];
|
||||
private int[] _cellEntry = new int[1024];
|
||||
private int _cellCount;
|
||||
|
||||
private int[] _testedStamp = new int[256];
|
||||
private CollisionPair[] _pairs = new CollisionPair[256];
|
||||
private int _pairCount;
|
||||
|
||||
/// <summary>Creates a world. <paramref name="cellSize"/> should match typical collider size.</summary>
|
||||
public CollisionWorld(float cellSize = 64f)
|
||||
{
|
||||
if (cellSize <= 0f)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(cellSize));
|
||||
}
|
||||
|
||||
_cellSize = cellSize;
|
||||
}
|
||||
|
||||
/// <summary>Pairs found by the last rebuild.</summary>
|
||||
public ReadOnlySpan<CollisionPair> Pairs => _pairs.AsSpan(0, _pairCount);
|
||||
|
||||
/// <summary>Colliders registered in the last rebuild.</summary>
|
||||
public int Count => _count;
|
||||
|
||||
/// <summary>Starts a rebuild. Called by <see cref="CollisionSystem"/> once per tick.</summary>
|
||||
public void BeginRebuild()
|
||||
{
|
||||
_count = 0;
|
||||
_cellCount = 0;
|
||||
_pairCount = 0;
|
||||
}
|
||||
|
||||
/// <summary>Registers one collider. Order of registration defines pair order (keep it deterministic).</summary>
|
||||
public void Add(Entity entity, in Transform2D transform, in Collider collider)
|
||||
{
|
||||
if (_count == _entries.Length)
|
||||
{
|
||||
Array.Resize(ref _entries, _entries.Length * 2);
|
||||
Array.Resize(ref _testedStamp, _entries.Length);
|
||||
}
|
||||
|
||||
var center = transform.Position + collider.Offset;
|
||||
var half = collider.Shape == ColliderShape.Circle
|
||||
? new Vector2(collider.Radius)
|
||||
: collider.HalfExtents;
|
||||
|
||||
_entries[_count++] = new Entry
|
||||
{
|
||||
Entity = entity,
|
||||
Center = center,
|
||||
Aabb = new RectF(center.X - half.X, center.Y - half.Y, half.X * 2f, half.Y * 2f),
|
||||
Radius = collider.Radius,
|
||||
HalfExtents = collider.HalfExtents,
|
||||
Layer = collider.Layer,
|
||||
CollidesWith = collider.CollidesWith,
|
||||
Shape = collider.Shape,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Builds the hash and collects all overlapping pairs.</summary>
|
||||
public void EndRebuild()
|
||||
{
|
||||
BuildHash();
|
||||
CollectPairs();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes entities whose colliders overlap <paramref name="area"/> into
|
||||
/// <paramref name="results"/>; returns the count (truncated to the span length).
|
||||
/// </summary>
|
||||
public int QueryAabb(in RectF area, Span<Entity> results)
|
||||
{
|
||||
var found = 0;
|
||||
var minX = CellOf(area.Left);
|
||||
var maxX = CellOf(area.Right);
|
||||
var minY = CellOf(area.Top);
|
||||
var maxY = CellOf(area.Bottom);
|
||||
var stamp = -1; // запросы используют отрицательные штампы, чтобы не портить пары
|
||||
|
||||
for (var cy = minY; cy <= maxY; cy++)
|
||||
{
|
||||
for (var cx = minX; cx <= maxX; cx++)
|
||||
{
|
||||
for (var i = _bucketHeads[Bucket(cx, cy)]; i >= 0; i = _cellNext[i])
|
||||
{
|
||||
var entryIndex = _cellEntry[i];
|
||||
if (_testedStamp[entryIndex] == stamp)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_testedStamp[entryIndex] = stamp;
|
||||
if (_entries[entryIndex].Aabb.Intersects(area))
|
||||
{
|
||||
if (found == results.Length)
|
||||
{
|
||||
return found;
|
||||
}
|
||||
|
||||
results[found++] = _entries[entryIndex].Entity;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ResetQueryStamps();
|
||||
return found;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Casts a segment and returns the closest hit among colliders whose
|
||||
/// <see cref="Collider.Layer"/> intersects <paramref name="mask"/>.
|
||||
/// </summary>
|
||||
public bool Raycast(Vector2 from, Vector2 to, out RaycastHit hit, uint mask = uint.MaxValue)
|
||||
{
|
||||
hit = default;
|
||||
var bestFraction = float.MaxValue;
|
||||
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
ref readonly var entry = ref _entries[i];
|
||||
if ((entry.Layer & mask) == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
float fraction;
|
||||
var found = entry.Shape == ColliderShape.Circle
|
||||
? RaySegmentCircle(from, to, entry.Center, entry.Radius, out fraction)
|
||||
: RaySegmentAabb(from, to, entry.Aabb, out fraction);
|
||||
|
||||
if (found && fraction < bestFraction)
|
||||
{
|
||||
bestFraction = fraction;
|
||||
hit = new RaycastHit(entry.Entity, Vector2.Lerp(from, to, fraction), fraction);
|
||||
}
|
||||
}
|
||||
|
||||
return bestFraction <= 1f;
|
||||
}
|
||||
|
||||
private void BuildHash()
|
||||
{
|
||||
var buckets = _bucketHeads.Length;
|
||||
while (buckets < _count * 2)
|
||||
{
|
||||
buckets *= 2;
|
||||
}
|
||||
|
||||
if (buckets != _bucketHeads.Length)
|
||||
{
|
||||
_bucketHeads = new int[buckets];
|
||||
}
|
||||
|
||||
Array.Fill(_bucketHeads, -1);
|
||||
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
ref readonly var aabb = ref _entries[i].Aabb;
|
||||
var minX = CellOf(aabb.Left);
|
||||
var maxX = CellOf(aabb.Right);
|
||||
var minY = CellOf(aabb.Top);
|
||||
var maxY = CellOf(aabb.Bottom);
|
||||
for (var cy = minY; cy <= maxY; cy++)
|
||||
{
|
||||
for (var cx = minX; cx <= maxX; cx++)
|
||||
{
|
||||
if (_cellCount == _cellNext.Length)
|
||||
{
|
||||
Array.Resize(ref _cellNext, _cellNext.Length * 2);
|
||||
Array.Resize(ref _cellEntry, _cellEntry.Length * 2);
|
||||
}
|
||||
|
||||
var bucket = Bucket(cx, cy);
|
||||
_cellEntry[_cellCount] = i;
|
||||
_cellNext[_cellCount] = _bucketHeads[bucket];
|
||||
_bucketHeads[bucket] = _cellCount;
|
||||
_cellCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
_testedStamp[i] = int.MinValue;
|
||||
}
|
||||
}
|
||||
|
||||
private void CollectPairs()
|
||||
{
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
ref readonly var a = ref _entries[i];
|
||||
var minX = CellOf(a.Aabb.Left);
|
||||
var maxX = CellOf(a.Aabb.Right);
|
||||
var minY = CellOf(a.Aabb.Top);
|
||||
var maxY = CellOf(a.Aabb.Bottom);
|
||||
|
||||
for (var cy = minY; cy <= maxY; cy++)
|
||||
{
|
||||
for (var cx = minX; cx <= maxX; cx++)
|
||||
{
|
||||
for (var c = _bucketHeads[Bucket(cx, cy)]; c >= 0; c = _cellNext[c])
|
||||
{
|
||||
var j = _cellEntry[c];
|
||||
if (j <= i || _testedStamp[j] == i)
|
||||
{
|
||||
continue; // только пары (i, j>i), каждая один раз
|
||||
}
|
||||
|
||||
_testedStamp[j] = i;
|
||||
ref readonly var b = ref _entries[j];
|
||||
if ((a.Layer & b.CollidesWith) == 0 || (b.Layer & a.CollidesWith) == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Overlaps(in a, in b))
|
||||
{
|
||||
if (_pairCount == _pairs.Length)
|
||||
{
|
||||
Array.Resize(ref _pairs, _pairs.Length * 2);
|
||||
}
|
||||
|
||||
_pairs[_pairCount++] = new CollisionPair(a.Entity, b.Entity);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool Overlaps(in Entry a, in Entry b)
|
||||
{
|
||||
if (a.Shape == ColliderShape.Circle && b.Shape == ColliderShape.Circle)
|
||||
{
|
||||
var sum = a.Radius + b.Radius;
|
||||
return Vector2.DistanceSquared(a.Center, b.Center) <= sum * sum;
|
||||
}
|
||||
|
||||
if (a.Shape == ColliderShape.Box && b.Shape == ColliderShape.Box)
|
||||
{
|
||||
return a.Aabb.Intersects(b.Aabb);
|
||||
}
|
||||
|
||||
// circle vs box
|
||||
ref readonly var circle = ref a.Shape == ColliderShape.Circle ? ref a : ref b;
|
||||
ref readonly var box = ref a.Shape == ColliderShape.Circle ? ref b : ref a;
|
||||
var nearest = new Vector2(
|
||||
Math.Clamp(circle.Center.X, box.Aabb.Left, box.Aabb.Right),
|
||||
Math.Clamp(circle.Center.Y, box.Aabb.Top, box.Aabb.Bottom));
|
||||
return Vector2.DistanceSquared(circle.Center, nearest) <= circle.Radius * circle.Radius;
|
||||
}
|
||||
|
||||
private static bool RaySegmentCircle(Vector2 from, Vector2 to, Vector2 center, float radius, out float fraction)
|
||||
{
|
||||
fraction = 0f;
|
||||
var d = to - from;
|
||||
var f = from - center;
|
||||
var a = Vector2.Dot(d, d);
|
||||
if (a <= float.Epsilon)
|
||||
{
|
||||
return f.LengthSquared() <= radius * radius;
|
||||
}
|
||||
|
||||
var b = 2f * Vector2.Dot(f, d);
|
||||
var c = Vector2.Dot(f, f) - radius * radius;
|
||||
var discriminant = b * b - 4f * a * c;
|
||||
if (discriminant < 0f)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var sqrt = MathF.Sqrt(discriminant);
|
||||
var t = (-b - sqrt) / (2f * a);
|
||||
if (t < 0f)
|
||||
{
|
||||
t = (-b + sqrt) / (2f * a); // старт внутри круга
|
||||
}
|
||||
|
||||
if (t < 0f || t > 1f)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
fraction = t;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool RaySegmentAabb(Vector2 from, Vector2 to, in RectF aabb, out float fraction)
|
||||
{
|
||||
fraction = 0f;
|
||||
var d = to - from;
|
||||
var tMin = 0f;
|
||||
var tMax = 1f;
|
||||
|
||||
for (var axis = 0; axis < 2; axis++)
|
||||
{
|
||||
var origin = axis == 0 ? from.X : from.Y;
|
||||
var direction = axis == 0 ? d.X : d.Y;
|
||||
var min = axis == 0 ? aabb.Left : aabb.Top;
|
||||
var max = axis == 0 ? aabb.Right : aabb.Bottom;
|
||||
|
||||
if (Math.Abs(direction) < float.Epsilon)
|
||||
{
|
||||
if (origin < min || origin > max)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var t1 = (min - origin) / direction;
|
||||
var t2 = (max - origin) / direction;
|
||||
if (t1 > t2)
|
||||
{
|
||||
(t1, t2) = (t2, t1);
|
||||
}
|
||||
|
||||
tMin = Math.Max(tMin, t1);
|
||||
tMax = Math.Min(tMax, t2);
|
||||
if (tMin > tMax)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fraction = tMin;
|
||||
return true;
|
||||
}
|
||||
|
||||
private void ResetQueryStamps()
|
||||
{
|
||||
for (var i = 0; i < _count; i++)
|
||||
{
|
||||
if (_testedStamp[i] < 0)
|
||||
{
|
||||
_testedStamp[i] = int.MinValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int CellOf(float coordinate) => (int)MathF.Floor(coordinate / _cellSize);
|
||||
|
||||
private int Bucket(int cellX, int cellY) =>
|
||||
(int)(((uint)(cellX * 73856093 ^ cellY * 19349663)) & (uint)(_bucketHeads.Length - 1));
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MrGameEng.Core\MrGameEng.Core.csproj" />
|
||||
<ProjectReference Include="..\MrGameEng.Graphics\MrGameEng.Graphics.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,244 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
|
||||
namespace MrGameEng.Pathfinding;
|
||||
|
||||
/// <summary>
|
||||
/// A flow field: per-cell distance to the nearest goal and a normalized direction to follow.
|
||||
/// Built once per goal change by <see cref="FlowFieldBuilder"/>, then any number of agents
|
||||
/// steer by an O(1) lookup per frame — the tool of choice for crowds heading to shared targets.
|
||||
/// </summary>
|
||||
public sealed class FlowField
|
||||
{
|
||||
/// <summary>Grid width in cells.</summary>
|
||||
public int Width { get; private set; }
|
||||
|
||||
/// <summary>Grid height in cells.</summary>
|
||||
public int Height { get; private set; }
|
||||
|
||||
internal float[] Distances = [];
|
||||
internal Vector2[] Directions = [];
|
||||
|
||||
/// <summary>Cost-weighted distance to the nearest goal; <see cref="float.PositiveInfinity"/> when unreachable.</summary>
|
||||
public float DistanceAt(int x, int y) => Distances[y * Width + x];
|
||||
|
||||
/// <summary>Normalized direction toward the nearest goal; <see cref="Vector2.Zero"/> at goals and unreachable cells.</summary>
|
||||
public Vector2 DirectionAt(int x, int y) => Directions[y * Width + x];
|
||||
|
||||
/// <summary>True when a path to a goal exists from this cell.</summary>
|
||||
public bool IsReachable(int x, int y) => !float.IsPositiveInfinity(Distances[y * Width + x]);
|
||||
|
||||
internal void EnsureSize(int width, int height)
|
||||
{
|
||||
Width = width;
|
||||
Height = height;
|
||||
var size = width * height;
|
||||
if (Distances.Length < size)
|
||||
{
|
||||
Distances = new float[size];
|
||||
Directions = new Vector2[size];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds <see cref="FlowField"/>s with a multi-source Dijkstra over an <see cref="IPathGrid"/>.
|
||||
/// Buffers are reused between builds (no allocations after warm-up). One instance per system.
|
||||
/// </summary>
|
||||
public sealed class FlowFieldBuilder
|
||||
{
|
||||
private static readonly int[] OffsetX = [1, -1, 0, 0, 1, 1, -1, -1];
|
||||
private static readonly int[] OffsetY = [0, 0, 1, -1, 1, -1, 1, -1];
|
||||
private const float DiagonalCost = 1.4142135f;
|
||||
|
||||
private readonly IPathGrid _grid;
|
||||
private readonly GridConnectivity _connectivity;
|
||||
private readonly int _width;
|
||||
private readonly int _height;
|
||||
private readonly int[] _closedStamp;
|
||||
private int[] _heapNodes;
|
||||
private float[] _heapPriorities;
|
||||
private int _generation;
|
||||
private int _heapCount;
|
||||
|
||||
/// <summary>Creates a builder bound to <paramref name="grid"/>.</summary>
|
||||
public FlowFieldBuilder(IPathGrid grid, GridConnectivity connectivity = GridConnectivity.Eight)
|
||||
{
|
||||
_grid = grid;
|
||||
_connectivity = connectivity;
|
||||
_width = grid.Width;
|
||||
_height = grid.Height;
|
||||
var size = _width * _height;
|
||||
_closedStamp = new int[size];
|
||||
_heapNodes = new int[size + 1];
|
||||
_heapPriorities = new float[size + 1];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fills <paramref name="field"/> with distances and directions toward the nearest of
|
||||
/// <paramref name="goals"/>. Impassable goals are ignored; with no valid goal the whole
|
||||
/// field is unreachable.
|
||||
/// </summary>
|
||||
public void Build(ReadOnlySpan<Point> goals, FlowField field)
|
||||
{
|
||||
field.EnsureSize(_width, _height);
|
||||
var distances = field.Distances;
|
||||
var directions = field.Directions;
|
||||
Array.Fill(distances, float.PositiveInfinity, 0, _width * _height);
|
||||
|
||||
_generation++;
|
||||
_heapCount = 0;
|
||||
|
||||
foreach (var goal in goals)
|
||||
{
|
||||
if (goal.X >= 0 && goal.X < _width && goal.Y >= 0 && goal.Y < _height &&
|
||||
_grid.IsPassable(goal.X, goal.Y))
|
||||
{
|
||||
var index = goal.Y * _width + goal.X;
|
||||
distances[index] = 0f;
|
||||
HeapPush(index, 0f);
|
||||
}
|
||||
}
|
||||
|
||||
var directionCount = (int)_connectivity;
|
||||
while (_heapCount > 0)
|
||||
{
|
||||
var current = HeapPop();
|
||||
if (_closedStamp[current] == _generation)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_closedStamp[current] = _generation;
|
||||
var cx = current % _width;
|
||||
var cy = current / _width;
|
||||
|
||||
for (var d = 0; d < directionCount; d++)
|
||||
{
|
||||
var nx = cx + OffsetX[d];
|
||||
var ny = cy + OffsetY[d];
|
||||
if (!Walkable(cx, cy, nx, ny, d))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var neighbor = ny * _width + nx;
|
||||
var tentative = distances[current] + (d < 4 ? 1f : DiagonalCost) * _grid.Cost(nx, ny);
|
||||
if (tentative < distances[neighbor])
|
||||
{
|
||||
distances[neighbor] = tentative;
|
||||
HeapPush(neighbor, tentative);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Направление — к соседу с минимальной дистанцией (с учётом запрета срезать углы).
|
||||
for (var y = 0; y < _height; y++)
|
||||
{
|
||||
for (var x = 0; x < _width; x++)
|
||||
{
|
||||
var index = y * _width + x;
|
||||
directions[index] = Vector2.Zero;
|
||||
if (float.IsPositiveInfinity(distances[index]) || distances[index] == 0f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var best = distances[index];
|
||||
var bestDx = 0;
|
||||
var bestDy = 0;
|
||||
for (var d = 0; d < directionCount; d++)
|
||||
{
|
||||
var nx = x + OffsetX[d];
|
||||
var ny = y + OffsetY[d];
|
||||
if (!Walkable(x, y, nx, ny, d))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var distance = distances[ny * _width + nx];
|
||||
if (distance < best)
|
||||
{
|
||||
best = distance;
|
||||
bestDx = OffsetX[d];
|
||||
bestDy = OffsetY[d];
|
||||
}
|
||||
}
|
||||
|
||||
if (bestDx != 0 || bestDy != 0)
|
||||
{
|
||||
directions[index] = Vector2.Normalize(new Vector2(bestDx, bestDy));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool Walkable(int fromX, int fromY, int toX, int toY, int direction)
|
||||
{
|
||||
if (toX < 0 || toX >= _width || toY < 0 || toY >= _height || !_grid.IsPassable(toX, toY))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return direction < 4 || (_grid.IsPassable(toX, fromY) && _grid.IsPassable(fromX, toY));
|
||||
}
|
||||
|
||||
private void HeapPush(int node, float priority)
|
||||
{
|
||||
if (_heapCount + 1 == _heapNodes.Length)
|
||||
{
|
||||
Array.Resize(ref _heapNodes, _heapNodes.Length * 2);
|
||||
Array.Resize(ref _heapPriorities, _heapPriorities.Length * 2);
|
||||
}
|
||||
|
||||
var i = ++_heapCount;
|
||||
while (i > 1 && _heapPriorities[i >> 1] > priority)
|
||||
{
|
||||
_heapNodes[i] = _heapNodes[i >> 1];
|
||||
_heapPriorities[i] = _heapPriorities[i >> 1];
|
||||
i >>= 1;
|
||||
}
|
||||
|
||||
_heapNodes[i] = node;
|
||||
_heapPriorities[i] = priority;
|
||||
}
|
||||
|
||||
private int HeapPop()
|
||||
{
|
||||
var top = _heapNodes[1];
|
||||
var lastNode = _heapNodes[_heapCount];
|
||||
var lastPriority = _heapPriorities[_heapCount];
|
||||
_heapCount--;
|
||||
|
||||
var i = 1;
|
||||
while (true)
|
||||
{
|
||||
var child = i << 1;
|
||||
if (child > _heapCount)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (child < _heapCount && _heapPriorities[child + 1] < _heapPriorities[child])
|
||||
{
|
||||
child++;
|
||||
}
|
||||
|
||||
if (_heapPriorities[child] >= lastPriority)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
_heapNodes[i] = _heapNodes[child];
|
||||
_heapPriorities[i] = _heapPriorities[child];
|
||||
i = child;
|
||||
}
|
||||
|
||||
if (_heapCount > 0)
|
||||
{
|
||||
_heapNodes[i] = lastNode;
|
||||
_heapPriorities[i] = lastPriority;
|
||||
}
|
||||
|
||||
return top;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
|
||||
namespace MrGameEng.Pathfinding;
|
||||
|
||||
/// <summary>Algorithm used by <see cref="GridPathfinder.FindPath"/>.</summary>
|
||||
public enum PathAlgorithm
|
||||
{
|
||||
/// <summary>Best general choice: cost-aware, goal-directed (octile/Manhattan heuristic).</summary>
|
||||
AStar,
|
||||
|
||||
/// <summary>Cost-aware without a heuristic. Slower than A*, useful as a reference.</summary>
|
||||
Dijkstra,
|
||||
|
||||
/// <summary>Fastest for uniform-cost grids; ignores <see cref="IPathGrid.Cost"/>.</summary>
|
||||
BreadthFirst,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Grid pathfinder with A*, Dijkstra and BFS over an <see cref="IPathGrid"/>.
|
||||
/// All working buffers are sized to the grid once and invalidated by a generation stamp,
|
||||
/// so repeated queries allocate nothing and never clear arrays. One instance per system
|
||||
/// (not thread-safe); results are deterministic for identical inputs.
|
||||
/// </summary>
|
||||
public sealed class GridPathfinder
|
||||
{
|
||||
private static readonly int[] OffsetX = [1, -1, 0, 0, 1, 1, -1, -1];
|
||||
private static readonly int[] OffsetY = [0, 0, 1, -1, 1, -1, 1, -1];
|
||||
private const float DiagonalCost = 1.4142135f;
|
||||
|
||||
private readonly IPathGrid _grid;
|
||||
private readonly GridConnectivity _connectivity;
|
||||
private readonly int _width;
|
||||
private readonly int _height;
|
||||
|
||||
private readonly float[] _gScore;
|
||||
private readonly int[] _cameFrom;
|
||||
private readonly int[] _openStamp;
|
||||
private readonly int[] _closedStamp;
|
||||
private int[] _heapNodes;
|
||||
private float[] _heapPriorities;
|
||||
private readonly int[] _bfsQueue;
|
||||
private int _generation;
|
||||
private int _heapCount;
|
||||
|
||||
/// <summary>Creates a pathfinder bound to <paramref name="grid"/>.</summary>
|
||||
public GridPathfinder(IPathGrid grid, GridConnectivity connectivity = GridConnectivity.Eight)
|
||||
{
|
||||
_grid = grid;
|
||||
_connectivity = connectivity;
|
||||
_width = grid.Width;
|
||||
_height = grid.Height;
|
||||
var size = _width * _height;
|
||||
_gScore = new float[size];
|
||||
_cameFrom = new int[size];
|
||||
_openStamp = new int[size];
|
||||
_closedStamp = new int[size];
|
||||
_heapNodes = new int[size + 1];
|
||||
_heapPriorities = new float[size + 1];
|
||||
_bfsQueue = new int[size];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds a path from <paramref name="start"/> to <paramref name="goal"/> (both inclusive)
|
||||
/// and writes it into <paramref name="path"/>. Returns false when no path exists;
|
||||
/// the list is cleared either way.
|
||||
/// </summary>
|
||||
public bool FindPath(Point start, Point goal, List<Point> path, PathAlgorithm algorithm = PathAlgorithm.AStar)
|
||||
{
|
||||
path.Clear();
|
||||
if (!InBounds(start) || !InBounds(goal) ||
|
||||
!_grid.IsPassable(start.X, start.Y) || !_grid.IsPassable(goal.X, goal.Y))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (start == goal)
|
||||
{
|
||||
path.Add(start);
|
||||
return true;
|
||||
}
|
||||
|
||||
return algorithm == PathAlgorithm.BreadthFirst
|
||||
? BreadthFirst(start, goal, path)
|
||||
: WeightedSearch(start, goal, path, useHeuristic: algorithm == PathAlgorithm.AStar);
|
||||
}
|
||||
|
||||
private bool WeightedSearch(Point start, Point goal, List<Point> path, bool useHeuristic)
|
||||
{
|
||||
_generation++;
|
||||
_heapCount = 0;
|
||||
|
||||
var startIndex = Index(start.X, start.Y);
|
||||
var goalIndex = Index(goal.X, goal.Y);
|
||||
_gScore[startIndex] = 0f;
|
||||
_cameFrom[startIndex] = -1;
|
||||
_openStamp[startIndex] = _generation;
|
||||
HeapPush(startIndex, useHeuristic ? Heuristic(start.X, start.Y, goal) : 0f);
|
||||
|
||||
var directions = (int)_connectivity;
|
||||
while (_heapCount > 0)
|
||||
{
|
||||
var current = HeapPop();
|
||||
if (current == goalIndex)
|
||||
{
|
||||
Reconstruct(goalIndex, path);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_closedStamp[current] == _generation)
|
||||
{
|
||||
continue; // устаревшая запись кучи
|
||||
}
|
||||
|
||||
_closedStamp[current] = _generation;
|
||||
var cx = current % _width;
|
||||
var cy = current / _width;
|
||||
|
||||
for (var d = 0; d < directions; d++)
|
||||
{
|
||||
var nx = cx + OffsetX[d];
|
||||
var ny = cy + OffsetY[d];
|
||||
if (!Walkable(cx, cy, nx, ny, d))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var neighbor = Index(nx, ny);
|
||||
if (_closedStamp[neighbor] == _generation)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var stepCost = (d < 4 ? 1f : DiagonalCost) * _grid.Cost(nx, ny);
|
||||
var tentative = _gScore[current] + stepCost;
|
||||
if (_openStamp[neighbor] == _generation && tentative >= _gScore[neighbor])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_gScore[neighbor] = tentative;
|
||||
_cameFrom[neighbor] = current;
|
||||
_openStamp[neighbor] = _generation;
|
||||
HeapPush(neighbor, tentative + (useHeuristic ? Heuristic(nx, ny, goal) : 0f));
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool BreadthFirst(Point start, Point goal, List<Point> path)
|
||||
{
|
||||
_generation++;
|
||||
var head = 0;
|
||||
var tail = 0;
|
||||
|
||||
var startIndex = Index(start.X, start.Y);
|
||||
var goalIndex = Index(goal.X, goal.Y);
|
||||
_cameFrom[startIndex] = -1;
|
||||
_openStamp[startIndex] = _generation;
|
||||
_bfsQueue[tail++] = startIndex;
|
||||
|
||||
var directions = (int)_connectivity;
|
||||
while (head < tail)
|
||||
{
|
||||
var current = _bfsQueue[head++];
|
||||
if (current == goalIndex)
|
||||
{
|
||||
Reconstruct(goalIndex, path);
|
||||
return true;
|
||||
}
|
||||
|
||||
var cx = current % _width;
|
||||
var cy = current / _width;
|
||||
for (var d = 0; d < directions; d++)
|
||||
{
|
||||
var nx = cx + OffsetX[d];
|
||||
var ny = cy + OffsetY[d];
|
||||
if (!Walkable(cx, cy, nx, ny, d))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var neighbor = Index(nx, ny);
|
||||
if (_openStamp[neighbor] == _generation)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_openStamp[neighbor] = _generation;
|
||||
_cameFrom[neighbor] = current;
|
||||
_bfsQueue[tail++] = neighbor;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>True when the move is in bounds, passable and does not cut a corner.</summary>
|
||||
private bool Walkable(int fromX, int fromY, int toX, int toY, int direction)
|
||||
{
|
||||
if (toX < 0 || toX >= _width || toY < 0 || toY >= _height || !_grid.IsPassable(toX, toY))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (direction >= 4)
|
||||
{
|
||||
// Диагональ разрешена только если обе ортогональные клетки проходимы.
|
||||
if (!_grid.IsPassable(toX, fromY) || !_grid.IsPassable(fromX, toY))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private float Heuristic(int x, int y, Point goal)
|
||||
{
|
||||
var dx = Math.Abs(x - goal.X);
|
||||
var dy = Math.Abs(y - goal.Y);
|
||||
return _connectivity == GridConnectivity.Four
|
||||
? dx + dy
|
||||
: Math.Max(dx, dy) + (DiagonalCost - 1f) * Math.Min(dx, dy);
|
||||
}
|
||||
|
||||
private void Reconstruct(int goalIndex, List<Point> path)
|
||||
{
|
||||
for (var index = goalIndex; index >= 0; index = _cameFrom[index])
|
||||
{
|
||||
path.Add(new Point(index % _width, index / _width));
|
||||
}
|
||||
|
||||
path.Reverse();
|
||||
}
|
||||
|
||||
private bool InBounds(Point p) => p.X >= 0 && p.X < _width && p.Y >= 0 && p.Y < _height;
|
||||
|
||||
private int Index(int x, int y) => y * _width + x;
|
||||
|
||||
private void HeapPush(int node, float priority)
|
||||
{
|
||||
// Ленивая вставка кладёт узел повторно при улучшении пути — куче нужен запас.
|
||||
if (_heapCount + 1 == _heapNodes.Length)
|
||||
{
|
||||
Array.Resize(ref _heapNodes, _heapNodes.Length * 2);
|
||||
Array.Resize(ref _heapPriorities, _heapPriorities.Length * 2);
|
||||
}
|
||||
|
||||
var i = ++_heapCount;
|
||||
while (i > 1 && _heapPriorities[i >> 1] > priority)
|
||||
{
|
||||
_heapNodes[i] = _heapNodes[i >> 1];
|
||||
_heapPriorities[i] = _heapPriorities[i >> 1];
|
||||
i >>= 1;
|
||||
}
|
||||
|
||||
_heapNodes[i] = node;
|
||||
_heapPriorities[i] = priority;
|
||||
}
|
||||
|
||||
private int HeapPop()
|
||||
{
|
||||
var top = _heapNodes[1];
|
||||
var lastNode = _heapNodes[_heapCount];
|
||||
var lastPriority = _heapPriorities[_heapCount];
|
||||
_heapCount--;
|
||||
|
||||
var i = 1;
|
||||
while (true)
|
||||
{
|
||||
var child = i << 1;
|
||||
if (child > _heapCount)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (child < _heapCount && _heapPriorities[child + 1] < _heapPriorities[child])
|
||||
{
|
||||
child++;
|
||||
}
|
||||
|
||||
if (_heapPriorities[child] >= lastPriority)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
_heapNodes[i] = _heapNodes[child];
|
||||
_heapPriorities[i] = _heapPriorities[child];
|
||||
i = child;
|
||||
}
|
||||
|
||||
if (_heapCount > 0)
|
||||
{
|
||||
_heapNodes[i] = lastNode;
|
||||
_heapPriorities[i] = lastPriority;
|
||||
}
|
||||
|
||||
return top;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace MrGameEng.Pathfinding;
|
||||
|
||||
/// <summary>Neighbor connectivity of a grid.</summary>
|
||||
public enum GridConnectivity
|
||||
{
|
||||
/// <summary>Orthogonal moves only.</summary>
|
||||
Four = 4,
|
||||
|
||||
/// <summary>Orthogonal and diagonal moves. Diagonals never cut corners.</summary>
|
||||
Eight = 8,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A grid the pathfinding algorithms operate on. The game implements this over its own
|
||||
/// world representation (terrain cells, a <c>TileGrid</c>, …) — the pathfinding module
|
||||
/// never owns world data.
|
||||
/// </summary>
|
||||
public interface IPathGrid
|
||||
{
|
||||
/// <summary>Grid width in cells.</summary>
|
||||
int Width { get; }
|
||||
|
||||
/// <summary>Grid height in cells.</summary>
|
||||
int Height { get; }
|
||||
|
||||
/// <summary>True when the cell can be entered. Out-of-range cells are never queried.</summary>
|
||||
bool IsPassable(int x, int y);
|
||||
|
||||
/// <summary>
|
||||
/// Cost multiplier for entering the cell, <b>must be ≥ 1</b> (1 = normal terrain,
|
||||
/// 3 = swamp three times slower, …). Used by A* and Dijkstra; ignored by BFS.
|
||||
/// </summary>
|
||||
float Cost(int x, int y);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\MrGameEng.Core\MrGameEng.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,185 @@
|
||||
using Friflo.Engine.ECS;
|
||||
using Microsoft.Xna.Framework;
|
||||
using MrGameEng.Core;
|
||||
using MrGameEng.Graphics;
|
||||
using Xunit;
|
||||
|
||||
namespace MrGameEng.Collisions.Tests;
|
||||
|
||||
public class CollisionWorldTests
|
||||
{
|
||||
private sealed class CollisionScene : Scene
|
||||
{
|
||||
public CollisionWorld World = null!;
|
||||
|
||||
protected override void OnLoad() => World = this.UseCollisions(cellSize: 32f);
|
||||
}
|
||||
|
||||
private static (EngineContext Context, CollisionScene Scene) CreateScene()
|
||||
{
|
||||
var context = new EngineContext();
|
||||
var scene = new CollisionScene();
|
||||
context.Scenes.Switch(scene);
|
||||
context.Scenes.Update(context.Clock); // применяет переключение и первый тик
|
||||
return (context, scene);
|
||||
}
|
||||
|
||||
private static Entity Spawn(Scene scene, Vector2 position, in Collider collider) =>
|
||||
scene.Store.CreateEntity(Transform2D.At(position), collider);
|
||||
|
||||
private static void Tick(EngineContext context)
|
||||
{
|
||||
context.Clock.Advance(0.016f);
|
||||
context.Scenes.Update(context.Clock);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void OverlappingCircles_ProduceOnePair()
|
||||
{
|
||||
var (context, scene) = CreateScene();
|
||||
var a = Spawn(scene, new Vector2(0f, 0f), Collider.Circle(10f));
|
||||
var b = Spawn(scene, new Vector2(15f, 0f), Collider.Circle(10f));
|
||||
Spawn(scene, new Vector2(100f, 100f), Collider.Circle(10f)); // далёкий — без пар
|
||||
|
||||
Tick(context);
|
||||
|
||||
var pair = Assert.Single(scene.World.Pairs.ToArray());
|
||||
Assert.True((pair.A == a && pair.B == b) || (pair.A == b && pair.B == a));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SeparatedCircles_NoPairs()
|
||||
{
|
||||
var (context, scene) = CreateScene();
|
||||
Spawn(scene, new Vector2(0f, 0f), Collider.Circle(5f));
|
||||
Spawn(scene, new Vector2(11f, 0f), Collider.Circle(5f));
|
||||
|
||||
Tick(context);
|
||||
|
||||
Assert.Equal(0, scene.World.Pairs.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CircleAndBox_Overlap_DetectedBothWays()
|
||||
{
|
||||
var (context, scene) = CreateScene();
|
||||
Spawn(scene, new Vector2(0f, 0f), Collider.Box(20f, 20f));
|
||||
Spawn(scene, new Vector2(14f, 0f), Collider.Circle(5f)); // касается правой грани
|
||||
|
||||
Tick(context);
|
||||
|
||||
Assert.Equal(1, scene.World.Pairs.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CornerCircle_DoesNotTouchBox()
|
||||
{
|
||||
var (context, scene) = CreateScene();
|
||||
Spawn(scene, new Vector2(0f, 0f), Collider.Box(20f, 20f));
|
||||
// Угол бокса (10,10); круг r=5 в (16,16): расстояние до угла ~8.49 > 5.
|
||||
Spawn(scene, new Vector2(16f, 16f), Collider.Circle(5f));
|
||||
|
||||
Tick(context);
|
||||
|
||||
Assert.Equal(0, scene.World.Pairs.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LayerMasks_FilterPairs()
|
||||
{
|
||||
var (context, scene) = CreateScene();
|
||||
var ghost = Collider.Circle(10f);
|
||||
ghost.Layer = 0b10;
|
||||
ghost.CollidesWith = 0b10; // призраки сталкиваются только с призраками
|
||||
|
||||
var wall = Collider.Circle(10f);
|
||||
wall.Layer = 0b01;
|
||||
wall.CollidesWith = 0b01;
|
||||
|
||||
Spawn(scene, new Vector2(0f, 0f), ghost);
|
||||
Spawn(scene, new Vector2(5f, 0f), wall);
|
||||
|
||||
Tick(context);
|
||||
|
||||
Assert.Equal(0, scene.World.Pairs.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MovingApart_PairDisappearsNextTick()
|
||||
{
|
||||
var (context, scene) = CreateScene();
|
||||
Spawn(scene, new Vector2(0f, 0f), Collider.Circle(10f));
|
||||
var mover = Spawn(scene, new Vector2(5f, 0f), Collider.Circle(10f));
|
||||
|
||||
Tick(context);
|
||||
Assert.Equal(1, scene.World.Pairs.Length);
|
||||
|
||||
mover.GetComponent<Transform2D>().Position = new Vector2(100f, 0f);
|
||||
Tick(context);
|
||||
Assert.Equal(0, scene.World.Pairs.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LargeCluster_AllTouchingPairsFound_OnceEach()
|
||||
{
|
||||
var (context, scene) = CreateScene();
|
||||
// Цепочка из 10 кругов: касаются только соседи → ровно 9 пар.
|
||||
for (var i = 0; i < 10; i++)
|
||||
{
|
||||
Spawn(scene, new Vector2(i * 18f, 0f), Collider.Circle(10f));
|
||||
}
|
||||
|
||||
Tick(context);
|
||||
|
||||
Assert.Equal(9, scene.World.Pairs.Length);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void QueryAabb_ReturnsOnlyEntitiesInArea()
|
||||
{
|
||||
var (context, scene) = CreateScene();
|
||||
var inside = Spawn(scene, new Vector2(10f, 10f), Collider.Circle(5f));
|
||||
Spawn(scene, new Vector2(200f, 200f), Collider.Circle(5f));
|
||||
|
||||
Tick(context);
|
||||
|
||||
Span<Entity> results = new Entity[8];
|
||||
var found = scene.World.QueryAabb(new RectF(0f, 0f, 50f, 50f), results);
|
||||
|
||||
Assert.Equal(1, found);
|
||||
Assert.Equal(inside, results[0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Raycast_HitsClosestCollider_AndRespectsMask()
|
||||
{
|
||||
var (context, scene) = CreateScene();
|
||||
var near = Collider.Circle(5f);
|
||||
near.Layer = 0b01;
|
||||
var far = Collider.Circle(5f);
|
||||
far.Layer = 0b10;
|
||||
|
||||
var nearEntity = Spawn(scene, new Vector2(30f, 0f), near);
|
||||
var farEntity = Spawn(scene, new Vector2(60f, 0f), far);
|
||||
|
||||
Tick(context);
|
||||
|
||||
Assert.True(scene.World.Raycast(new Vector2(0f, 0f), new Vector2(100f, 0f), out var hit));
|
||||
Assert.Equal(nearEntity, hit.Entity);
|
||||
Assert.Equal(25f, hit.Point.X, 1);
|
||||
|
||||
Assert.True(scene.World.Raycast(new Vector2(0f, 0f), new Vector2(100f, 0f), out hit, mask: 0b10));
|
||||
Assert.Equal(farEntity, hit.Entity);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Raycast_Miss_ReturnsFalse()
|
||||
{
|
||||
var (context, scene) = CreateScene();
|
||||
Spawn(scene, new Vector2(0f, 50f), Collider.Box(10f, 10f));
|
||||
|
||||
Tick(context);
|
||||
|
||||
Assert.False(scene.World.Raycast(new Vector2(0f, 0f), new Vector2(100f, 0f), out _));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit.v3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Collisions\MrGameEng.Collisions.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,101 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
using Xunit;
|
||||
|
||||
namespace MrGameEng.Pathfinding.Tests;
|
||||
|
||||
public class FlowFieldTests
|
||||
{
|
||||
[Fact]
|
||||
public void Build_DistancesGrowFromGoal_DirectionsDescend()
|
||||
{
|
||||
var grid = new TestGrid(
|
||||
".....",
|
||||
".###.",
|
||||
".....");
|
||||
var builder = new FlowFieldBuilder(grid);
|
||||
var field = new FlowField();
|
||||
|
||||
builder.Build([new Point(0, 0)], field);
|
||||
|
||||
Assert.Equal(0f, field.DistanceAt(0, 0));
|
||||
Assert.True(field.DistanceAt(4, 2) > field.DistanceAt(1, 0));
|
||||
|
||||
// Из любой достижимой не-целевой клетки направление ведёт к клетке с меньшей дистанцией.
|
||||
for (var y = 0; y < grid.Height; y++)
|
||||
{
|
||||
for (var x = 0; x < grid.Width; x++)
|
||||
{
|
||||
if (!grid.IsPassable(x, y) || !field.IsReachable(x, y) || field.DistanceAt(x, y) == 0f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var direction = field.DirectionAt(x, y);
|
||||
Assert.NotEqual(Vector2.Zero, direction);
|
||||
var nx = x + Math.Sign(MathF.Round(direction.X * 10f));
|
||||
var ny = y + Math.Sign(MathF.Round(direction.Y * 10f));
|
||||
Assert.True(field.DistanceAt(nx, ny) < field.DistanceAt(x, y),
|
||||
$"direction at ({x},{y}) does not descend");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_UnreachablePocket_IsFlagged()
|
||||
{
|
||||
var grid = new TestGrid(
|
||||
"..#..",
|
||||
"..#..",
|
||||
"..#..");
|
||||
var builder = new FlowFieldBuilder(grid);
|
||||
var field = new FlowField();
|
||||
|
||||
builder.Build([new Point(0, 1)], field);
|
||||
|
||||
Assert.False(field.IsReachable(4, 1));
|
||||
Assert.Equal(Vector2.Zero, field.DirectionAt(4, 1));
|
||||
Assert.True(field.IsReachable(1, 2));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_MultipleGoals_EachCellFlowsToNearest()
|
||||
{
|
||||
var grid = new TestGrid("..........");
|
||||
var builder = new FlowFieldBuilder(grid);
|
||||
var field = new FlowField();
|
||||
|
||||
builder.Build([new Point(0, 0), new Point(9, 0)], field);
|
||||
|
||||
Assert.True(field.DirectionAt(2, 0).X < 0f); // ближе к левой цели
|
||||
Assert.True(field.DirectionAt(7, 0).X > 0f); // ближе к правой
|
||||
Assert.Equal(0f, field.DistanceAt(9, 0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_Rebuild_OverwritesPreviousField()
|
||||
{
|
||||
var grid = new TestGrid(".....");
|
||||
var builder = new FlowFieldBuilder(grid);
|
||||
var field = new FlowField();
|
||||
|
||||
builder.Build([new Point(0, 0)], field);
|
||||
Assert.True(field.DirectionAt(4, 0).X < 0f);
|
||||
|
||||
builder.Build([new Point(4, 0)], field);
|
||||
Assert.True(field.DirectionAt(0, 0).X > 0f);
|
||||
Assert.Equal(0f, field.DistanceAt(4, 0));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Build_NoValidGoals_EverythingUnreachable()
|
||||
{
|
||||
var grid = new TestGrid(".#.");
|
||||
var builder = new FlowFieldBuilder(grid);
|
||||
var field = new FlowField();
|
||||
|
||||
builder.Build([new Point(1, 0)], field); // цель — стена
|
||||
|
||||
Assert.False(field.IsReachable(0, 0));
|
||||
Assert.False(field.IsReachable(2, 0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
using Microsoft.Xna.Framework;
|
||||
using Xunit;
|
||||
|
||||
namespace MrGameEng.Pathfinding.Tests;
|
||||
|
||||
public class GridPathfinderTests
|
||||
{
|
||||
private static List<Point> Path(IPathGrid grid, Point start, Point goal,
|
||||
PathAlgorithm algorithm = PathAlgorithm.AStar,
|
||||
GridConnectivity connectivity = GridConnectivity.Eight)
|
||||
{
|
||||
var pathfinder = new GridPathfinder(grid, connectivity);
|
||||
var path = new List<Point>();
|
||||
Assert.True(pathfinder.FindPath(start, goal, path, algorithm));
|
||||
return path;
|
||||
}
|
||||
|
||||
private static void AssertValidPath(IPathGrid grid, List<Point> path, Point start, Point goal)
|
||||
{
|
||||
Assert.Equal(start, path[0]);
|
||||
Assert.Equal(goal, path[^1]);
|
||||
for (var i = 0; i < path.Count; i++)
|
||||
{
|
||||
Assert.True(grid.IsPassable(path[i].X, path[i].Y), $"impassable cell {path[i]}");
|
||||
if (i > 0)
|
||||
{
|
||||
var dx = Math.Abs(path[i].X - path[i - 1].X);
|
||||
var dy = Math.Abs(path[i].Y - path[i - 1].Y);
|
||||
Assert.True(dx <= 1 && dy <= 1 && dx + dy > 0, $"non-adjacent step {path[i - 1]} -> {path[i]}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(PathAlgorithm.AStar)]
|
||||
[InlineData(PathAlgorithm.Dijkstra)]
|
||||
[InlineData(PathAlgorithm.BreadthFirst)]
|
||||
public void FindPath_OpenField_StraightLine(PathAlgorithm algorithm)
|
||||
{
|
||||
var grid = new TestGrid(
|
||||
".....",
|
||||
".....",
|
||||
".....");
|
||||
|
||||
var path = Path(grid, new Point(0, 1), new Point(4, 1), algorithm);
|
||||
|
||||
AssertValidPath(grid, path, new Point(0, 1), new Point(4, 1));
|
||||
Assert.Equal(5, path.Count); // прямая, без лишних шагов
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(PathAlgorithm.AStar)]
|
||||
[InlineData(PathAlgorithm.Dijkstra)]
|
||||
[InlineData(PathAlgorithm.BreadthFirst)]
|
||||
public void FindPath_WallsForceDetour(PathAlgorithm algorithm)
|
||||
{
|
||||
var grid = new TestGrid(
|
||||
".....",
|
||||
"####.",
|
||||
".....");
|
||||
|
||||
var path = Path(grid, new Point(0, 0), new Point(0, 2), algorithm);
|
||||
|
||||
AssertValidPath(grid, path, new Point(0, 0), new Point(0, 2));
|
||||
Assert.Contains(new Point(4, 1), path); // единственный проход
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindPath_NoRoute_ReturnsFalse()
|
||||
{
|
||||
var grid = new TestGrid(
|
||||
".#.",
|
||||
".#.",
|
||||
".#.");
|
||||
var pathfinder = new GridPathfinder(grid);
|
||||
var path = new List<Point>();
|
||||
|
||||
Assert.False(pathfinder.FindPath(new Point(0, 0), new Point(2, 0), path));
|
||||
Assert.Empty(path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindPath_StartEqualsGoal_SinglePoint()
|
||||
{
|
||||
var grid = new TestGrid("...");
|
||||
|
||||
var path = Path(grid, new Point(1, 0), new Point(1, 0));
|
||||
|
||||
Assert.Equal([new Point(1, 0)], path);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindPath_DiagonalNeverCutsCorners()
|
||||
{
|
||||
var grid = new TestGrid(
|
||||
".#",
|
||||
"#.");
|
||||
var pathfinder = new GridPathfinder(grid, GridConnectivity.Eight);
|
||||
var path = new List<Point>();
|
||||
|
||||
// Диагональ (0,0)->(1,1) зажата стенами — пути нет.
|
||||
Assert.False(pathfinder.FindPath(new Point(0, 0), new Point(1, 1), path));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindPath_FourConnectivity_NoDiagonalSteps()
|
||||
{
|
||||
var grid = new TestGrid(
|
||||
"...",
|
||||
"...",
|
||||
"...");
|
||||
|
||||
var path = Path(grid, new Point(0, 0), new Point(2, 2), connectivity: GridConnectivity.Four);
|
||||
|
||||
Assert.Equal(5, path.Count); // манхэттен: 4 шага
|
||||
for (var i = 1; i < path.Count; i++)
|
||||
{
|
||||
var dx = Math.Abs(path[i].X - path[i - 1].X);
|
||||
var dy = Math.Abs(path[i].Y - path[i - 1].Y);
|
||||
Assert.Equal(1, dx + dy);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(PathAlgorithm.AStar)]
|
||||
[InlineData(PathAlgorithm.Dijkstra)]
|
||||
public void FindPath_CostAware_AvoidsExpensiveTerrain(PathAlgorithm algorithm)
|
||||
{
|
||||
// Прямой путь через болото (цена 9) дороже обхода по краю.
|
||||
var grid = new TestGrid(
|
||||
".....",
|
||||
".999.",
|
||||
".....");
|
||||
|
||||
var path = Path(grid, new Point(0, 1), new Point(4, 1), algorithm);
|
||||
|
||||
Assert.DoesNotContain(path, p => grid.Cost(p.X, p.Y) > 1f);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindPath_BreadthFirst_IgnoresCosts()
|
||||
{
|
||||
var grid = new TestGrid(
|
||||
".....",
|
||||
".999.",
|
||||
".....");
|
||||
|
||||
var path = Path(grid, new Point(0, 1), new Point(4, 1), PathAlgorithm.BreadthFirst);
|
||||
|
||||
Assert.Equal(5, path.Count); // идёт напрямик через дорогие клетки
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindPath_ReusedInstance_GivesCleanResults()
|
||||
{
|
||||
var grid = new TestGrid(
|
||||
".....",
|
||||
".###.",
|
||||
".....");
|
||||
var pathfinder = new GridPathfinder(grid);
|
||||
var path = new List<Point>();
|
||||
|
||||
Assert.True(pathfinder.FindPath(new Point(0, 0), new Point(4, 2), path));
|
||||
var first = path.ToArray();
|
||||
Assert.True(pathfinder.FindPath(new Point(0, 0), new Point(4, 2), path));
|
||||
|
||||
Assert.Equal(first, path); // generation-сброс не оставляет мусора между запросами
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FindPath_AStarMatchesDijkstraCost()
|
||||
{
|
||||
var grid = new TestGrid(
|
||||
"..3..",
|
||||
".#3#.",
|
||||
"..3..",
|
||||
".###.",
|
||||
".....");
|
||||
var start = new Point(0, 0);
|
||||
var goal = new Point(4, 4);
|
||||
|
||||
var aStar = Path(grid, start, goal, PathAlgorithm.AStar);
|
||||
var dijkstra = Path(grid, start, goal, PathAlgorithm.Dijkstra);
|
||||
|
||||
Assert.Equal(PathCost(grid, dijkstra), PathCost(grid, aStar), 3);
|
||||
}
|
||||
|
||||
private static float PathCost(IPathGrid grid, List<Point> path)
|
||||
{
|
||||
var total = 0f;
|
||||
for (var i = 1; i < path.Count; i++)
|
||||
{
|
||||
var diagonal = path[i].X != path[i - 1].X && path[i].Y != path[i - 1].Y;
|
||||
total += (diagonal ? 1.4142135f : 1f) * grid.Cost(path[i].X, path[i].Y);
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<OutputType>Exe</OutputType>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||
<PackageReference Include="xunit.v3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\MrGameEng.Pathfinding\MrGameEng.Pathfinding.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,23 @@
|
||||
using MrGameEng.Pathfinding;
|
||||
|
||||
namespace MrGameEng.Pathfinding.Tests;
|
||||
|
||||
/// <summary>Грид из строк: '#' — стена, '.' — клетка с ценой 1, '2'..'9' — клетка с этой ценой.</summary>
|
||||
public sealed class TestGrid : IPathGrid
|
||||
{
|
||||
private readonly string[] _rows;
|
||||
|
||||
public TestGrid(params string[] rows) => _rows = rows;
|
||||
|
||||
public int Width => _rows[0].Length;
|
||||
|
||||
public int Height => _rows.Length;
|
||||
|
||||
public bool IsPassable(int x, int y) => _rows[y][x] != '#';
|
||||
|
||||
public float Cost(int x, int y)
|
||||
{
|
||||
var cell = _rows[y][x];
|
||||
return cell is >= '2' and <= '9' ? cell - '0' : 1f;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user