Fastest way to remember already calculated coordinates - Java

Viewed 60

so I am trying to make 3d game in java. I have made rendering work and now I am thinking about what is the fastest way to remember and check if coordinate has already been calculated?

For example, I have a cube, which has 8 corners, my game calculates each corner 3 times (24 in total) because every corner is being shared with 3 faces.

So, what is the fastest way to store and check if coordinates are already calculated?

Also, I have tried searching for this already but couldn't find results. If there is question like this already answer.

Thank you.

2 Answers

Make sure your coordinate class overrides hashCode() and equals(Object) and store each coordinate you've already rendered in a HashSet.

If you see this starts taking too much memory, you could try and use some sort of LRU cache.

You can use a HashMap to with your own 3D point value object as the key and the calculated result type as the value.

class Point3D {
    private final double x, y, z;
    public Point3D(final double x, final double y, final double z) {
        this.x=x;
        this.y=y;
        this.z=z;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        long temp;
        temp = Double.doubleToLongBits(x);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        temp = Double.doubleToLongBits(y);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        temp = Double.doubleToLongBits(z);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Point3D other = (Point3D) obj;
        if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x))
            return false;
        if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y))
            return false;
        if (Double.doubleToLongBits(z) != Double.doubleToLongBits(other.z))
            return false;
        return true;
    }
}
public class Main{
    public static void main(String[] args){
        final Map<Point3D, Result> cache = new HashMap<>();
        cache.put(new Point3D(0, 0, 1), new Result(...));
    }
}
Related