mercredi 20 juillet 2016

Java random probability based on the size of a value?

Ok so I have made an engine using openGL, and i'd like to be able to read in an entity map (An image where the strength of a colour (say green) represents the chance of an entity spawning at that location).

So far, I have the following for reading in the image and retrieving the graan values.

BufferedImage image = null;
    try { image = ImageIO.read(Class.class.getResourceAsStream("/res/textures/world/treemap.png"));
    } catch (IOException e) { e.printStackTrace(); }
    if (image != null) {
        int width = image.getWidth();
        int height = width;
        BufferedImage after = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        AffineTransform at = new AffineTransform();
        double scale = WORLD_SIZE / width;
        at.scale(scale, scale);
        AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
        after = scaleOp.filter(image, after);
        width = height = after.getWidth();
        int[] values = new int[width * height];
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int green = new Color(after.getRGB(x, y)).getGreen();
                values[x + y * width] = green;
            }
        }
        // Generate trees based on size and position of green value
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                int treeNum = values[x + y * width] / 10;
                // Generate based on size of treeNum
                entities.add(new Entity(fern, new Vector3f(x, terrain.getHeightOfTerrain(x, -y), -y), 0, 0, 0, new Random(1000000).nextFloat() * 1.3f + 0.9f));
            }
        }

    } else entities.addAll(generateEntities(fern, 60, WORLD_SIZE, WORLD_SIZE, 0, 0, (WORLD_SIZE/3)*2, (WORLD_SIZE/3)*2, 3, -4, new Vector3f(1, 0.9f, 0), new Vector3f(0,1,0)));

Here is the image: Tree map drawn based on the terrain heightmap

My problem: This code works and generates a tree at every coordinate on the image. However, I'd like the trees to be created based on the size of the values stored in the values array (which holds the green channel values). So the larger the value, the higher the chance of a tree being spawned. The idea is to try and create a forest.

Thanks for your help!




Aucun commentaire:

Enregistrer un commentaire