Search code examples
javaopengllwjglgame-development

Performance Related Problem in strategy-game map loading algorithm (Java, lwjgl)


I'm creating a game where you pick a nation and you have to manage it, but I can't find a way to load the map without crashing the program due to massive computation (lack of performance).

I made an algorithm that loops trough every pixel of an image containing the provinces (the spatial unit in the game) of the map, each has their own color, this way, when I encounter a color not yet seen in a pixel, I know that's a new province, and I can therefor load it the new Province() instance with the information from a file.

Everything above said works just fine and takes almost no time at all, but to edit the map when various nations attack each other I need a way to render singularly every province to give it its nation's color with a shader.

I've added this piece of code that gets the current pixel position and it scales it down to openGL coordinates, saving it in an arrayList (currVertices), this is then put into an another ArrayList (provinceVertices) of float[] once a new province is found.

(I know the code is not beautiful and I'm not an expert programmer (also I'm 14) so please try to be kind when telling me what I did wrong, I've tried just storing a vertex every 4 pixel to make the list smaller, but it still crashes)

List<Float> currVertices = new ArrayList<Float>(); // the vertices of the current province          
for (int y = 0; y < worldImage.getHeight(); y++) {
    for (int x = 0; x < worldImage.getWidth(); x++) {
        if (!currColors.contains(worldImage.getRGB(x, y))) {
            if (!currVertices.isEmpty())
                provinceVertices.add(Utils.toFloatArray(currVertices)); // store the current province's vertices into the total database
            currVertices.clear();
        }
        if (x % 4 == 0)
            currVertices.add((float) (x) / EngineManager.getWindowWidth());
        if (y % 4 == 0)
            currVertices.add((float) (y) / EngineManager.getWindowHeight());
    }
}

I've only included the code representing the loading of the vertices

public static float[] toFloatArray(List<Float> list) {
    float[] array = new float[list.size()];
    ListIterator<Float> iterator = list.listIterator();
    while (iterator.hasNext()) {
        array[iterator.nextIndex()] = list.get(iterator.nextIndex());
    }
    return array;
}

the goal would be for the second ArrayList to have all the vertices in the right order, but when I try and add the currVertices to the provinceVertices the game just crashes with no error message, which is why I'm guessing the problem is performance-related. (The vertices load fine into the currVertices list)


Solution

  • Using nextIndex() doesn't increse the index. Try to use instead:

    while (iterator.hasNext()) {
        array[iterator.nextIndex()] = iterator.next();
    }