import java.util.ArrayList; public class ChunkManager { private static ArrayList> chunks; private static int width; private static int height; private static int chunks_x; private static int chunks_y; public static void init(int width, int height, int chunks_x, int chunks_y) { ChunkManager.width = width; ChunkManager.height = height; ChunkManager.chunks_x = chunks_x; ChunkManager.chunks_y = chunks_y; ChunkManager.chunks = new ArrayList>(chunks_x * chunks_y); ChunkManager.clear(); } public static void clear() { chunks.clear(); for (int i = 0; i < chunks_x * chunks_y; i++) { chunks.add(new ArrayList()); } } private static int[] to_chunk_coordinates(int x, int y) { return new int[] { (x * chunks_x) / width, (y * chunks_y) / height }; } private static int get_chunk_index(int x, int y) { return x + (y * chunks_x); } private static int wrap(int index, int max) { int normalized = index; while (normalized < 0) { normalized += max; } return normalized % max; } public static void register(PhysicsObject obj) { int[] chunk = to_chunk_coordinates((int)obj.x, (int)obj.y); int index = get_chunk_index(chunk[0], chunk[1]); chunks.get(index).add(obj); } public static ArrayList get_objects(int x, int y) { int[] chunk = to_chunk_coordinates(x, y); int[][] chunks = new int[][] { chunk, new int[] {wrap(chunk[0] + 1,chunks_x), chunk[1]}, new int[] {wrap(chunk[0] - 1,chunks_x), chunk[1]}, new int[] {wrap(chunk[0] + 1,chunks_x), wrap(chunk[1] + 1, chunks_y)}, new int[] {wrap(chunk[0] - 1,chunks_x), wrap(chunk[1] + 1, chunks_y)}, new int[] {wrap(chunk[0] + 1,chunks_x), wrap(chunk[1] - 1, chunks_y)}, new int[] {wrap(chunk[0] - 1,chunks_x), wrap(chunk[1] - 1, chunks_y)}, new int[] {chunk[0], wrap(chunk[1] + 1, chunks_y)}, new int[] {chunk[0], wrap(chunk[1] - 1, chunks_y)} }; ArrayList objects = new ArrayList(); for (int[] c : chunks) { int index = get_chunk_index(c[0], c[1]); objects.addAll(ChunkManager.chunks.get(index)); } return objects; } }