diff --git a/src/roadtrip/model/AbstractProceduralBlock.java b/src/roadtrip/model/AbstractProceduralBlock.java new file mode 100644 index 0000000..909cf9b --- /dev/null +++ b/src/roadtrip/model/AbstractProceduralBlock.java @@ -0,0 +1,50 @@ +package roadtrip.model; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.Random; + +/** + * Created by dejvino on 21.01.2017. + */ +public abstract class AbstractProceduralBlock implements ProceduralBlock +{ + private long seed; + + public AbstractProceduralBlock(long seed) + { + this.seed = seed; + } + + @Override + public long getBlockSeed() + { + return seed; + } + + @Override + public Random getBlockRandom() + { + return new Random(seed); + } + + @Override + public long getSubBlockSeed(String subBlockKey) + { + return (String.valueOf(seed) + "::" + subBlockKey).hashCode(); + } + + @Override + public T getSubBlock(String subBlockKey, Class subBlockClass) + { + if (subBlockClass == null) throw new NullPointerException("subBlockClass"); + try { + Constructor constructor = subBlockClass.getConstructor(Long.class); + return constructor.newInstance(getSubBlockSeed(subBlockKey)); + } catch (NoSuchMethodException e) { + throw new IllegalArgumentException("Class " + subBlockClass + " does not have the default constructor with a single 'long' parameter.", e); + } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { + throw new IllegalArgumentException("Unable to instantiate sub-block.", e); + } + } +} diff --git a/src/roadtrip/model/ProceduralBlock.java b/src/roadtrip/model/ProceduralBlock.java new file mode 100644 index 0000000..a2e0720 --- /dev/null +++ b/src/roadtrip/model/ProceduralBlock.java @@ -0,0 +1,39 @@ +package roadtrip.model; + +import java.util.Random; + +/** + * Created by dejvino on 21.01.2017. + */ +public interface ProceduralBlock +{ + /** + * The main PRNG seed defining this block's content. + * @return Seed value. + */ + long getBlockSeed(); + + /** + * Random generator initialized with the block's seed. + * + * @return fresh PRNG. + */ + Random getBlockRandom(); + + /** + * Provides a seed to be used with a sub-block with a given key (identifier). + * + * @param subBlockKey + * @return Sub-block seed. + */ + long getSubBlockSeed(String subBlockKey); + + /** + * Provides a sub-block of the given class. The sub-block's seed is based on this block's seed. + * + * @param subBlockClass + * @param + * @return Newly added sub-block. + */ + T getSubBlock(String subBlockKey, Class subBlockClass); +}