Clean up ddutils and bug fixes

- Removed unused utils
 - Use Java 8 streams API
 - Fix calculation of pocket id from coordinates
 - Fix /pocket tab completion and null pointer
This commit is contained in:
Runemoro 2017-12-27 18:31:04 -05:00
parent 0bbc2e4ebb
commit 2e5217a17c
10 changed files with 66 additions and 219 deletions

View file

@ -8,7 +8,7 @@ import java.util.List;
public final class I18nUtils {
@SideOnly(Side.CLIENT)
public static void translateAndAdd(String key, List<String> list) { // TODO: move to utils?
public static void translateAndAdd(String key, List<String> list) {
int i = 0;
while (I18n.hasKey(key + Integer.toString(i))) {
list.add(I18n.format(key + Integer.toString(i)));

View file

@ -1,56 +0,0 @@
package org.dimdev.ddutils;
import java.util.ArrayList;
import java.util.List;
/**
* @author Robijnvogel
*/
public final class StringUtils {
public static char flipCase(char in) {
if (Character.isUpperCase(in)) {
return Character.toLowerCase(in);
} else {
return Character.toUpperCase(in);
}
}
public static List<String> getAsStringList(Integer[] integers) {
List<String> list = new ArrayList<>();
for (int integer : integers) {
list.add(String.valueOf(integer));
}
return list;
}
public static List<String> getMatchingStrings(String template, List<String> comparables, boolean caseSensitive) {
if (template.equals("")) {
return comparables;
}
List<String> results = new ArrayList<>();
for (String comparable : comparables) {
if (isStartOfString(template, comparable, caseSensitive)) {
results.add(comparable);
}
}
return results;
}
public static boolean isStartOfString(String template, String comparable, boolean caseSensitive) {
if (comparable.length() < template.length()) {
return false;
} else if (template.equals("")) {
return true;
}
for (int i = 0; i < template.length(); i++) {
char tChar = template.charAt(i);
char cChar = comparable.charAt(i);
if (tChar != cChar && !caseSensitive && flipCase(tChar) == cChar) {
return false;
}
}
return true;
}
}

View file

@ -32,15 +32,14 @@ public final class GridUtils {
* @param pos The location on the grid
* @return The location on the grid
*/
public static int posToNum(GridPos pos) { // TODO: comments
public static int posToNum(GridPos pos) {
int x = pos.getX();
int z = pos.getZ();
if (x >= z) {
return x * x + z;
} else {
return (z + 2) * z - z;
if (x >= z) { // First side
return x * x + z; // (number of points in the square x * x) + (z points on the top layer)
} else { // Second side
return (z + 1) * z + z - x; // (number of points in the rectangle (z + 1) * z) + (z - x points on the top layer)
}
}
// TODO: add more modes: hexagonal sphere packing and maybe spiral, triangle
}

View file

@ -1,106 +0,0 @@
package org.dimdev.ddutils.math;
import java.util.Random;
/**
* @author Robijnvogel
*/
public final class RandomUtils { // These utils aren't being used by DimDoors!
/**
* Compares the integers in two arrays and returns true if any integer in
* the first set is within range 0 to {@code difference} - 1 of any integer
* in the second array.
*
* @param set1 the first integer array to compare
* @param difference see method description
* @param set2 the second integer array to compare
* @return {@code (\exists i, j; ; abs(set1[i] - set2[j]) < difference }
* @throws IllegalArgumentException if precondition is violated
* @pre difference >= 0
*/
public static boolean withinDistanceOf(int[] set1, int difference, int[] set2) throws IllegalArgumentException {
if (difference < 0) throw new IllegalArgumentException("Difference must be larger than 0");
for (int e1 : set1) {
for (int e2 : set2) {
if (Math.max(e1, e2) - Math.min(e1, e2) < difference) return true;
}
}
return false;
}
/**
* Returns the sum of the values of all integer elements in an integer array
*
* @param intArray the integers to calculate the sum of
* @param flag this flag is meant to check if all elements in the array must
* be positive (0), negative(1), or it doesn't matter (anything else)
* @return {@code sum(i = 0; intArray.has(i); intArray[i]) }
* @throws IllegalArgumentException if precondition is violated
* @pre {@code (flag != 0 && flag != 1) || (flag == 0 && (\forall i; intArray.has(i); i >= 0)) || (flag == 1 && (\forall i; intArray.has(i); i <= 0))}
*/
public static int arraySum(int[] intArray, short flag) {
int r = 0;
for (int i : intArray) { //check flag
if (flag == 0 && i < 0) {
throw new IllegalArgumentException("all integers in array must be positive");
} else if (flag == 1 && i > 0) {
throw new IllegalArgumentException("all integers in array must be negative");
}
r += i;
}
return r;
}
/**
* Returns either true or false, based on a weighted random, taking in
* account the parameters as the weights for true and false as outcomes. For
* instance: (2, 3) should return true in 40% of the cases and false in 60%
* of the cases.
*
* @param trueWeight the chance weight that this method will return true
* @param falseWeight the chance weight that this method will return false
* @return true or false
* @throws IllegalArgumentException if precondition is violated
* @pre {@code trueWeight > 0 && falseWeight > 0}
*/
public static boolean weightedBoolean(int trueWeight, int falseWeight) {
if (trueWeight <= 0 || falseWeight <= 0) {
throw new IllegalArgumentException("Either of both weights were 0 or lower. Both should be at least 1.");
}
Random random = new Random();
return random.nextInt(trueWeight + falseWeight) < trueWeight;
}
/**
* This method returns the sum of {@code base} and a random element of
* {@code transformations} the weight of each of the entries in
*
* @param base the base value to transform from
* @param transformations the possible transformations
* @param weights the chance-weight of those transformations
* @return the sum of {@code base} and the value of an element in
* {@code transformations}
* @throws IllegalArgumentException if precondition is violated
* @pre {@code transformations.length = weights.length} && {@code (\forall i; intArray.has(i); i >= 0)}
* && {@code MathUtils.arraySum(weights, 1) > 0}
*/
public static int transformRandomly(int base, int[] transformations, int[] weights) {
if (transformations.length != weights.length) {
throw new IllegalArgumentException("pre was violated, transformations.length != weights.length");
}
Random random = new Random();
int weightSum = arraySum(weights, (short) 0);
if (weightSum <= 0) {
throw new IllegalArgumentException("pre was violated, RandomUtils.arraySum(weights, 1) <= 0");
}
int choice = random.nextInt(weightSum);
for (int i = 0; i < weights.length; i++) {
choice -= weights[i];
if (choice < 0) {
return base + transformations[i];
}
}
throw new IllegalStateException("");
}
}

View file

@ -2,23 +2,18 @@ package org.dimdev.ddutils.nbt;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.math.Vec3i;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public final class NBTUtils { // TODO: make these fill rather than return a map
public static Map<String, Integer> readMapStringInteger(NBTTagCompound nbt) {
HashMap<String, Integer> map = new HashMap<>();
for (String str : nbt.getKeySet()) {
map.put(str, nbt.getInteger(str));
}
return map;
}
public static BiMap<String, Integer> readBiMapStringInteger(NBTTagCompound nbt) {
BiMap<String, Integer> map = HashBiMap.create();
public final class NBTUtils {
public static <T extends Map<String, Integer>> T readMapStringInteger(NBTTagCompound nbt, T map) {
for (String str : nbt.getKeySet()) {
map.put(str, nbt.getInteger(str));
}
@ -33,6 +28,11 @@ public final class NBTUtils { // TODO: make these fill rather than return a map
return tagCompound;
}
public static <T extends INBTStorable> T readNBTStorable(T obj, NBTTagCompound nbt) {
obj.readFromNBT(nbt);
return obj;
}
public static Vec3i readVec3i(NBTTagCompound nbt) {
return new Vec3i(nbt.getInteger("x"), nbt.getInteger("y"), nbt.getInteger("z"));
}

View file

@ -211,12 +211,16 @@ public class SchematicHandler { // TODO: make this more general (not dimdoors-re
// LOADING CODE ENDS HERE </editor-fold>
public ArrayList<String> getTemplateGroups() {
return new ArrayList<>(nameMap.keySet());
public Set<String> getTemplateGroups() {
return nameMap.keySet();
}
public ArrayList<String> getTemplateNames(String group) {
return new ArrayList<>(nameMap.get(group).keySet()); // TODO: null pointer here
public Set<String> getTemplateNames(String group) {
if (nameMap.containsKey(group)) {
return nameMap.get(group).keySet();
} else {
return new HashSet<>();
}
}
/**

View file

@ -2,9 +2,11 @@ package org.dimdev.dimdoors.shared.commands;
import org.dimdev.dimdoors.DimDoors;
import org.dimdev.ddutils.Location;
import org.dimdev.ddutils.StringUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.dimdev.ddutils.TeleportUtils;
@ -78,9 +80,12 @@ public class CommandDimTeleport extends CommandBase { // TODO: localization
@Override
public List<String> getTabCompletions(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos) {
if (args.length == 1) {
List<String> list = StringUtils.getAsStringList(DimensionManager.getIDs());
return StringUtils.getMatchingStrings(args[0], list, false);
return Arrays.stream(DimensionManager.getIDs())
.map(Object::toString)
.filter(s -> s.toLowerCase().startsWith(args[0].toLowerCase()))
.collect(Collectors.toList());
} else {
return new ArrayList<>();
}
return new ArrayList<>();
}
}

View file

@ -5,7 +5,6 @@ import org.dimdev.dimdoors.shared.*;
import org.dimdev.dimdoors.shared.pockets.*;
import org.dimdev.dimdoors.shared.rifts.TileEntityRift;
import org.dimdev.ddutils.Location;
import org.dimdev.ddutils.StringUtils;
import org.dimdev.ddutils.TeleportUtils;
import org.dimdev.ddutils.WorldUtils;
import org.dimdev.dimdoors.shared.world.DimDoorDimensions;
@ -20,6 +19,7 @@ import net.minecraft.util.text.TextComponentString;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class CommandPocket extends CommandBase {
@ -110,16 +110,18 @@ public class CommandPocket extends CommandBase {
List<String> list = new ArrayList<>();
switch (args.length) {
case 1:
list = SchematicHandler.INSTANCE.getTemplateGroups();
list = new ArrayList<>(SchematicHandler.INSTANCE.getTemplateGroups());
break;
case 2:
list = SchematicHandler.INSTANCE.getTemplateNames(args[0]);
list = new ArrayList<>(SchematicHandler.INSTANCE.getTemplateNames(args[0]));
break;
case 3:
list.add("true");
list.add("false");
break;
}
return StringUtils.getMatchingStrings(args[0], list, false);
return list.stream()
.filter(s -> s.toLowerCase().startsWith(args[args.length - 1].toLowerCase()))
.collect(Collectors.toList());
}
}

View file

@ -1,5 +1,6 @@
package org.dimdev.dimdoors.shared.pockets;
import org.dimdev.ddutils.nbt.INBTStorable;
import org.dimdev.dimdoors.shared.VirtualLocation;
import org.dimdev.dimdoors.shared.rifts.*;
import org.dimdev.dimdoors.shared.tileentities.TileEntityEntranceRift;
@ -14,7 +15,7 @@ import net.minecraft.nbt.*;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
public class Pocket { // TODO: better visibilities
public class Pocket implements INBTStorable{ // TODO: better visibilities
@Getter private int id;
@Getter private int x; // Grid x TODO: rename to gridX and gridY
@ -26,9 +27,9 @@ public class Pocket { // TODO: better visibilities
@Getter int dimID; // Not saved
private Pocket() {}
public Pocket() {}
Pocket(int id, int dimID, int x, int z) {
public Pocket(int id, int dimID, int x, int z) {
this.id = id;
this.dimID = dimID;
this.x = x;
@ -36,35 +37,33 @@ public class Pocket { // TODO: better visibilities
riftLocations = new ArrayList<>();
}
static Pocket readFromNBT(NBTTagCompound nbt) {
Pocket pocket = new Pocket();
pocket.id = nbt.getInteger("id");
pocket.x = nbt.getInteger("x");
pocket.z = nbt.getInteger("z");
pocket.size = nbt.getInteger("size");
if (nbt.hasKey("virtualLocation")) pocket.virtualLocation = VirtualLocation.readFromNBT(nbt.getCompoundTag("virtualLocation"));
if (nbt.hasKey("entrance")) pocket.entrance = Location.readFromNBT(nbt.getCompoundTag("entrance"));
@Override
public /*static Pocket*/ void readFromNBT(NBTTagCompound nbt) {
id = nbt.getInteger("id");
x = nbt.getInteger("x");
z = nbt.getInteger("z");
size = nbt.getInteger("size");
if (nbt.hasKey("virtualLocation")) virtualLocation = VirtualLocation.readFromNBT(nbt.getCompoundTag("virtualLocation"));
if (nbt.hasKey("entrance")) entrance = Location.readFromNBT(nbt.getCompoundTag("entrance"));
pocket.riftLocations = new ArrayList<>();
riftLocations = new ArrayList<>();
NBTTagList riftLocationsNBT = (NBTTagList) nbt.getTag("riftLocations");
for (NBTBase riftLocationNBT : riftLocationsNBT) {
pocket.riftLocations.add(Location.readFromNBT((NBTTagCompound) riftLocationNBT));
riftLocations.add(Location.readFromNBT((NBTTagCompound) riftLocationNBT));
}
return pocket;
}
static NBTBase writeToNBT(Pocket pocket) {
NBTTagCompound nbt = new NBTTagCompound();
nbt.setInteger("id", pocket.id);
nbt.setInteger("x", pocket.x);
nbt.setInteger("z", pocket.z);
nbt.setInteger("size", pocket.size);
if (pocket.virtualLocation != null) nbt.setTag("virtualLocation", pocket.virtualLocation.writeToNBT());
if (pocket.entrance != null) nbt.setTag("entrance", Location.writeToNBT(pocket.entrance));
@Override
public /*static*/ NBTTagCompound writeToNBT(NBTTagCompound nbt) {
nbt.setInteger("id", id);
nbt.setInteger("x", x);
nbt.setInteger("z", z);
nbt.setInteger("size", size);
if (virtualLocation != null) nbt.setTag("virtualLocation", virtualLocation.writeToNBT());
if (entrance != null) nbt.setTag("entrance", Location.writeToNBT(entrance));
NBTTagList riftLocationsNBT = new NBTTagList();
for (Location loc : pocket.riftLocations) {
for (Location loc : riftLocations) {
riftLocationsNBT.appendTag(Location.writeToNBT(loc));
}
nbt.setTag("riftLocations", riftLocationsNBT);

View file

@ -87,14 +87,14 @@ public class PocketRegistry extends WorldSavedData { // TODO: unregister pocket
maxPocketSize = nbt.getInteger("maxPocketSize");
privatePocketSize = nbt.getInteger("privatePocketSize");
publicPocketSize = nbt.getInteger("publicPocketSize");
privatePocketMap = NBTUtils.readBiMapStringInteger(nbt.getCompoundTag("privatePocketMap"));
privatePocketMap = NBTUtils.readMapStringInteger(nbt.getCompoundTag("privatePocketMap"), HashBiMap.create());
nextID = nbt.getInteger("nextID");
pockets = new HashMap<>();
NBTTagList pocketsNBT = (NBTTagList) nbt.getTag("pockets");
for (NBTBase pocketNBT : pocketsNBT) { // TODO: convert to map to be able to skip IDs efficiently
NBTTagCompound pocketNBTC = (NBTTagCompound) pocketNBT;
pockets.put(pocketNBTC.getInteger("id"), Pocket.readFromNBT(pocketNBTC));
pockets.put(pocketNBTC.getInteger("id"), NBTUtils.readNBTStorable(new Pocket(), (NBTTagCompound) pocketNBT));
}
for (Pocket pocket : pockets.values()) {
@ -133,7 +133,7 @@ public class PocketRegistry extends WorldSavedData { // TODO: unregister pocket
NBTTagList pocketsNBT = new NBTTagList();
for (Map.Entry<Integer, Pocket> pocketEntry : pockets.entrySet()) {
if (pocketEntry.getValue() == null) continue;
NBTTagCompound pocketNBT = (NBTTagCompound) Pocket.writeToNBT(pocketEntry.getValue());
NBTTagCompound pocketNBT = (NBTTagCompound) pocketEntry.getValue().writeToNBT(new NBTTagCompound());
pocketNBT.setInteger("id", pocketEntry.getKey()); // TODO: store separately?
pocketsNBT.appendTag(pocketNBT);
}