BITKit/Src/Unity/Scripts/WorldChunk/ChunkObject.cs

98 lines
2.5 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using Quadtree;
using UnityEngine;
namespace BITKit.OpenWorld
{
public class ChunkObject : MonoBehaviour, IWorldChunkObject
{
[SerializeField, ReadOnly] private int _lod = -1;
[SerializeField, ReadOnly] private int id;
public Bounds GetBounds() => _bounds;
private Bounds _bounds;
public Node<IWorldChunkObject> ParentNode { get; set; }
public void QuadTree_Root_Initialized(IQuadtreeRoot<IWorldChunkObject, Node<IWorldChunkObject>> root)
{
}
public int Id
{
get => id;
set => id = value;
}
public int Lod
{
get => _lod;
set => OnLodChanged(_lod, _lod = value);
}
protected virtual void Start()
{
CalculateBounds();
UnityWorldChunkService.Singleton.Register(this);
destroyCancellationToken.Register(Dispose);
}
private void Dispose()
{
UnityWorldChunkService.Singleton.Unregister(this);
}
protected virtual void OnLodChanged(int oldLod, int newLod)
{
}
private void OnDrawGizmosSelected()
{
if (_bounds.size.magnitude is 0)
CalculateBounds();
Gizmos.color = Color.red;
Gizmos.DrawWireCube(_bounds.center, _bounds.size);
}
#if UNITY_EDITOR
[BIT]
#endif
public void CalculateBounds()
{
if (TryGetComponent<Collider>(out var _collider))
{
_bounds = _collider.bounds;
return;
}
_bounds = new Bounds();
var colliders = GetComponentsInChildren<Collider>();
if (colliders.Length is 0)
{
Debug.LogWarning($"{gameObject.name}:No collider found");
return;
}
var reference = colliders.First();
_bounds = reference.bounds;
foreach (var x in colliders)
{
_bounds.Encapsulate(x.bounds);
if (x.bounds.size.sqrMagnitude > 64)
{
Debug.LogWarning(
$"{x.gameObject.name}:Size is too large, please check the size of the collider");
}
}
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
}
}
}