summaryrefslogtreecommitdiff
path: root/marching/Assets/Scripts/Physics/Quadtree.cs
blob: af7a0054016a31b96b57221f7ab4684425ff9792 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Unity.VisualScripting;
using UnityEngine;

namespace mh
{

    public interface IQuadTreeObject
    {
        public Vector4 bound { get; }
    }

    public class Quadtree
    {
        public const int kMaxObjectsPerBlock = 4;
        public const int kMaxLevel = 20;

        private int m_Level;
        private Vector4 m_Bounds; // x,y,z,w => posx,posy,width,height 
        private Quadtree[] m_SubTrees; // 从右上角开始逆时针索引
        private List<IQuadTreeObject> m_Objects; // 当前层能容纳,但任何一个子树都无法容纳的对象

        public float x { get { return m_Bounds.x; } }
        public float y { get { return m_Bounds.y; } }
        public float w { get { return m_Bounds.z; } }
        public float h { get { return m_Bounds.w; } }
        public float halfW { get { return w / 2; } }
        public float halfH { get { return h / 2; } }
        public float left { get { return x - halfW; } }
        public float right { get { return x + halfW; } }
        public float top { get { return y + halfH; } }
        public float bottom { get { return y - halfH; } }

        private static Queue<List<IQuadTreeObject>> m_QuadtreeObjPool = new Queue<List<IQuadTreeObject>>();

        private static Queue<Quadtree> m_QuadtreePool = new Queue<Quadtree>();

        private Quadtree QueryQuadtree(int level, Vector4 bounds)
        {
            if(m_QuadtreePool.Count == 0)
            {
                return new Quadtree(level, bounds);
            }
            Quadtree tree = m_QuadtreePool.Dequeue();
            tree.m_Level = level;
            tree.m_Bounds = bounds;
            if (tree.m_Objects == null)
                tree.m_Objects = QueryQuadtreeObjList();
            return tree;
        }

        private void RecycleQuadtree(ref Quadtree tree)
        {
            tree.Clear();
            m_QuadtreePool.Enqueue(tree);   
            tree = null;
        }

        private List<IQuadTreeObject> QueryQuadtreeObjList()
        {
            if(m_QuadtreeObjPool.Count == 0)
            {
                return new List<IQuadTreeObject>();
            }    
            List<IQuadTreeObject> list = m_QuadtreeObjPool.Dequeue();
            return list;
        }

        private void RecycleQuadtreeObjList(ref List<IQuadTreeObject> list)
        {
            list.Clear();
            m_QuadtreeObjPool.Enqueue(list);
            list = null;
        }

        public Quadtree(int level, Vector4 bounds)
        {
            m_Level = level;
            m_Bounds = bounds;
            m_SubTrees = new Quadtree[4];
            m_Objects = QueryQuadtreeObjList();
        }

        public void Rebound(Vector4 bounds)
        {
            m_Bounds = bounds;
        }

        public void Clear(bool clearObjectList = true)
        {
            if (clearObjectList)
                RecycleQuadtreeObjList(ref m_Objects);
            else
                m_Objects.Clear();
            for (int i = 0; i < m_SubTrees.Length; i++)
            {
                if (m_SubTrees[i] != null)
                {
                    //m_SubTrees[i].Clear();
                    //m_SubTrees[i] = null;
                    RecycleQuadtree(ref m_SubTrees[i]);
                }
            }
        }

        public void Split()
        {
            float subWidth = (m_Bounds.z / 2);
            float subHeight = (m_Bounds.w / 2);
            float x = m_Bounds.x;
            float y = m_Bounds.y;
            m_SubTrees[0] = QueryQuadtree(m_Level + 1, new Vector4(x + subWidth / 2, y + subHeight / 2, subWidth, subHeight));
            m_SubTrees[1] = QueryQuadtree(m_Level + 1, new Vector4(x - subWidth / 2, y + subHeight / 2, subWidth, subHeight));
            m_SubTrees[2] = QueryQuadtree(m_Level + 1, new Vector4(x - subWidth / 2, y - subHeight / 2, subWidth, subHeight));
            m_SubTrees[3] = QueryQuadtree(m_Level + 1, new Vector4(x + subWidth / 2, y - subHeight / 2, subWidth, subHeight));
        }

        // x, y, z, w
        /// <summary>
        /// -1表示没法完全放在一个subTree: subtree交界或者整个越界
        /// </summary>
        /// <param name="bound"></param>
        /// <returns></returns>
        public int GetSubtreeIndex(Vector4 bound)
        {
            float halfw = bound.z / 2;
            float halfh = bound.w / 2;
            float lowerx = bound.x - halfw; 
            float higherx = bound.x + halfw;    
            float lowery = bound.y - halfh;
            float highery = bound.y + halfh;
            bool bFitInLeft = lowerx >= left && higherx <= x;
            bool bFitInRight = lowerx >= x && higherx <= right;
            bool bFitInTop = lowery >= y && highery <= top;
            bool bFitInBottom = lowery >= bottom && highery <= y;
            if (bFitInRight && bFitInTop) return 0;
            if (bFitInLeft && bFitInTop) return 1;
            if (bFitInLeft && bFitInBottom) return 2;
            if (bFitInRight && bFitInBottom) return 3;
            return -1;
        }

        public void Insert(IQuadTreeObject obj)
        {
            int index = GetSubtreeIndex(obj.bound);
            if(index != -1)
            {
                if (m_SubTrees[0] == null) Split();
                m_SubTrees[index].Insert(obj);
                return;
            }

            //if (m_SubTrees[0] != null)
            //{
            //    if (index != -1)
            //    {
            //        m_SubTrees[index].Insert(obj);
            //        return;
            //    }
            //}

            m_Objects.Add(obj);

            if(m_Objects.Count > kMaxObjectsPerBlock && m_Level < kMaxLevel) // 本层满了之后重新排布层内对象
            {
                if (m_SubTrees[0] == null) Split();

                for(int i = m_Objects.Count - 1; i >= 0; i--) 
                {
                    index = GetSubtreeIndex(m_Objects[i].bound);
                    if(index != -1) 
                    {
                        IQuadTreeObject o = m_Objects[i];
                        m_Objects.RemoveAt(i);
                        m_SubTrees[index].Insert(o);
                    }
                }
            }

          // Debug.Log(m_Objects.Count);
        }

        /// <summary>
        /// 获得可能和obj碰撞的对象(不包括自己)
        /// </summary>
        /// <param name="returnObjs"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Retrieve(ref List<IQuadTreeObject> returnObjs, IQuadTreeObject obj)
        {
            int index = GetSubtreeIndex(obj.bound);
            returnObjs.AddRange(m_Objects);
            if (index != -1 && m_SubTrees[0] != null)
            {
                m_SubTrees[index].Retrieve(ref returnObjs, obj);
            }
            if(returnObjs.Contains(obj))
            {
                returnObjs.Remove(obj);
            }
            return returnObjs.Count > 0;
        }

        public void Iterate(System.Action<Quadtree> action)
        {
            action?.Invoke(this);
            m_SubTrees[0]?.Iterate(action);
            m_SubTrees[1]?.Iterate(action);
            m_SubTrees[2]?.Iterate(action);
            m_SubTrees[3]?.Iterate(action);
        }

    }
}