1
This commit is contained in:
82
Src/Unity/Scripts/Quadtree/QuadTreeService.cs
Normal file
82
Src/Unity/Scripts/Quadtree/QuadTreeService.cs
Normal file
@@ -0,0 +1,82 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.Remoting;
|
||||
using BITKit;
|
||||
using BITKit.Entities;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Unity.Collections;
|
||||
using Unity.Jobs;
|
||||
using Unity.Mathematics;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Jobs;
|
||||
|
||||
namespace Net.BITKit.Quadtree
|
||||
{
|
||||
public abstract class QuadTreeService
|
||||
{
|
||||
public readonly Quadtree Quadtree = new(default,new float2(2048,2048));
|
||||
}
|
||||
public class QuadTreeService<T>:QuadTreeService,IDisposable where T : class
|
||||
{
|
||||
private readonly IEntitiesService _entitiesService;
|
||||
private readonly ConcurrentDictionary<int, Transform> _transforms = new();
|
||||
private readonly ITicker _ticker;
|
||||
public QuadTreeService(IEntitiesService entitiesService, ITicker ticker)
|
||||
{
|
||||
_entitiesService = entitiesService;
|
||||
_ticker = ticker;
|
||||
|
||||
_entitiesService.OnAdd += OnAdd;
|
||||
_entitiesService.OnRemove += OnRemove;
|
||||
|
||||
foreach (var (entity,t) in _entitiesService.QueryComponents<IEntity,T>())
|
||||
{
|
||||
OnAdd(entity,t);
|
||||
}
|
||||
|
||||
_ticker.Add(OnTick);
|
||||
}
|
||||
|
||||
private void OnTick(float obj)
|
||||
{
|
||||
foreach (var (id,transform) in _transforms)
|
||||
{
|
||||
Quadtree.Remove(id);
|
||||
Quadtree.Insert(id,((float3)transform.position).xz);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnRemove(IEntity obj)
|
||||
{
|
||||
_transforms.TryRemove(obj.Id,out _);
|
||||
Quadtree.Remove(obj.Id);
|
||||
}
|
||||
|
||||
private void OnAdd(IEntity obj)
|
||||
{
|
||||
if (obj.ServiceProvider.GetService<T>() is { } t)
|
||||
{
|
||||
OnAdd(obj,t);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnAdd(IEntity entity, T t)
|
||||
{
|
||||
_transforms.TryAdd(entity.Id, entity.ServiceProvider.GetRequiredService<Transform>());
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_entitiesService.OnAdd -= OnAdd;
|
||||
_entitiesService.OnRemove -= OnRemove;
|
||||
|
||||
_ticker.Remove(OnTick);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
Reference in New Issue
Block a user