Implement NoiseFunction2 cache

This commit is contained in:
dfsek
2020-11-21 16:14:09 -07:00
parent 4174dc9ab0
commit 1f8d9a710f
2 changed files with 50 additions and 6 deletions

View File

@@ -4,10 +4,12 @@ import com.dfsek.terra.generation.config.NoiseBuilder;
import org.polydev.gaea.math.FastNoiseLite;
import parsii.eval.Expression;
import java.util.HashMap;
import java.util.List;
public class NoiseFunction2 implements NoiseFunction {
private final FastNoiseLite gen;
private final Cache cache = new Cache();
public NoiseFunction2(long seed, NoiseBuilder builder) {
this.gen = builder.build((int) seed);
@@ -20,11 +22,34 @@ public class NoiseFunction2 implements NoiseFunction {
@Override
public double eval(List<Expression> list) {
return gen.getNoise(list.get(0).evaluate(), list.get(1).evaluate());
return cache.get(gen, (int) list.get(0).evaluate(), (int) list.get(1).evaluate());
}
/**
* Evaluate without cache. For testing.
*
* @param list Parameters.
* @return Result.
*/
public double evalNoCache(List<Expression> list) {
return gen.getNoise((int) list.get(0).evaluate(), (int) list.get(1).evaluate());
}
@Override
public boolean isNaturalFunction() {
return true;
}
private static class Cache {
private final HashMap<Long, Double> map = new HashMap<>();
public double get(FastNoiseLite noise, int x, int z) {
long key = (((long) x) << 32) + z;
return map.computeIfAbsent(key, k -> {
if(map.size() > 512) map.clear();
return noise.getNoise(x, z);
});
}
}
}