mirror of
https://github.com/GTNewHorizons/StructureLib.git
synced 2026-11-20 03:59:34 +00:00
Implement autoplace (#6)
This commit is contained in:
1 parent
e8f5cd6489
commit
609e50428e
60 files changed
+3699
-702
No files matched your search
@@ -0,0 +1,47 @@
|
||||
package com.gtnewhorizon.structurelib.util;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.NoSuchElementException;
|
||||
import net.minecraft.inventory.IInventory;
|
||||
import net.minecraft.item.ItemStack;
|
||||
|
||||
public class InventoryIterable<Inv extends IInventory> implements Iterable<ItemStack> {
|
||||
private final Inv inv;
|
||||
private final int maxSlot;
|
||||
|
||||
public InventoryIterable(Inv inv) {
|
||||
this(inv, -1);
|
||||
}
|
||||
|
||||
InventoryIterable(Inv inv, int maxSlot) {
|
||||
this.inv = inv;
|
||||
this.maxSlot = maxSlot;
|
||||
}
|
||||
|
||||
public Inv getInventory() {
|
||||
return inv;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<ItemStack> iterator() {
|
||||
return new Iterator<ItemStack>() {
|
||||
private int ptr = 0;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return ptr < inv.getSizeInventory() && (maxSlot == -1 || ptr < maxSlot);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack next() {
|
||||
if (!hasNext()) throw new NoSuchElementException();
|
||||
return inv.getStackInSlot(ptr++);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
inv.setInventorySlotContents(ptr - 1, null);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
/**
|
||||
* Copyright (c) 2022, glee8e
|
||||
* This file is part of StructureLib.
|
||||
* <p>
|
||||
* StructureLib is free software; you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation; either version 2 of the License, or
|
||||
* (at your option) any later version.
|
||||
* <p>
|
||||
* StructureLib is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
* <p>
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Foobar; if not, write to the Free Software
|
||||
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
package com.gtnewhorizon.structurelib.util;
|
||||
|
||||
import com.gtnewhorizon.structurelib.util.InventoryUtility.ItemStackExtractor.APIType;
|
||||
import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.entity.player.EntityPlayerMP;
|
||||
import net.minecraft.entity.player.InventoryPlayer;
|
||||
import net.minecraft.init.Items;
|
||||
import net.minecraft.inventory.IInventory;
|
||||
import net.minecraft.inventory.InventoryEnderChest;
|
||||
import net.minecraft.item.ItemStack;
|
||||
|
||||
/**
|
||||
* This class is part of API, but is not stable. Use at your own risk.
|
||||
*/
|
||||
public class InventoryUtility {
|
||||
private static final SortedRegistry<ItemStackExtractor> stackExtractors = new SortedRegistry<>();
|
||||
private static final List<Predicate<? super EntityPlayerMP>> enableEnder = new CopyOnWriteArrayList<>();
|
||||
/**
|
||||
* The remove() of the Iterable returned must be implemented!
|
||||
*/
|
||||
private static final SortedRegistry<InventoryProvider<?>> inventoryProviders = new SortedRegistry<>();
|
||||
|
||||
static {
|
||||
inventoryProviders.register("5000-main-inventory", new InventoryProvider<InventoryIterable<InventoryPlayer>>() {
|
||||
@Override
|
||||
public InventoryIterable<InventoryPlayer> getInventory(EntityPlayerMP player) {
|
||||
return new InventoryIterable<>(player.inventory, player.inventory.mainInventory.length);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markDirty(InventoryIterable<InventoryPlayer> inv) {
|
||||
// player save its content using means other than inv.markDirty()
|
||||
// here we only need to sync it to client
|
||||
inv.getInventory().player.inventoryContainer.detectAndSendChanges();
|
||||
}
|
||||
});
|
||||
inventoryProviders.register(
|
||||
"7000-ender-inventory", new InventoryProvider<InventoryIterable<InventoryEnderChest>>() {
|
||||
@Override
|
||||
public InventoryIterable<InventoryEnderChest> getInventory(EntityPlayerMP player) {
|
||||
if (enableEnder.stream().anyMatch(p -> p.test(player)))
|
||||
return new InventoryIterable<>(player.getInventoryEnderChest());
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markDirty(InventoryIterable<InventoryEnderChest> inv) {
|
||||
// inv.getInventory().markDirty();
|
||||
// TODO this seems to be a noop
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void registerEnableEnderCondition(Predicate<? super EntityPlayerMP> predicate) {
|
||||
enableEnder.add(predicate);
|
||||
}
|
||||
|
||||
public static void registerStackExtractor(String key, ItemStackExtractor val) {
|
||||
if (Arrays.stream(APIType.values()).noneMatch(val::isAPIImplemented))
|
||||
throw new IllegalArgumentException("Must implement at least one API");
|
||||
stackExtractors.register(key, val);
|
||||
}
|
||||
|
||||
public static <Inv extends IInventory> void registerStackExtractor(
|
||||
String key, Function<ItemStack, ? extends Inv> extractor) {
|
||||
registerStackExtractor(key, newItemStackProvider(extractor));
|
||||
}
|
||||
|
||||
public static void registerInventoryProvider(String key, InventoryProvider<?> val) {
|
||||
inventoryProviders.register(key, val);
|
||||
}
|
||||
|
||||
public static <Inv extends IInventory> void registerInventoryProvider(
|
||||
String key, Function<EntityPlayerMP, ? extends Inv> extractor) {
|
||||
registerInventoryProvider(key, newInventoryProvider(extractor));
|
||||
}
|
||||
|
||||
public static Iterator<? extends ItemStackExtractor> getStackExtractors() {
|
||||
return stackExtractors.iterator();
|
||||
}
|
||||
|
||||
public static <Inv extends IInventory> InventoryProvider<InventoryIterable<Inv>> newInventoryProvider(
|
||||
Function<EntityPlayerMP, ? extends Inv> extractor) {
|
||||
return new InventoryProvider<InventoryIterable<Inv>>() {
|
||||
@Override
|
||||
public InventoryIterable<Inv> getInventory(EntityPlayerMP player) {
|
||||
Inv inv = extractor.apply(player);
|
||||
return inv != null ? new InventoryIterable<>(inv) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void markDirty(InventoryIterable<Inv> inv) {
|
||||
inv.getInventory().markDirty();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public static ItemStackExtractor newItemStackProvider(Function<ItemStack, ? extends IInventory> extractor) {
|
||||
return new ItemStackExtractor() {
|
||||
@Override
|
||||
public boolean isAPIImplemented(APIType type) {
|
||||
return type == APIType.MAIN;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int takeFromStack(
|
||||
Predicate<ItemStack> predicate,
|
||||
boolean simulate,
|
||||
int count,
|
||||
ItemStackCounter store,
|
||||
ItemStack stack,
|
||||
ItemStack filter,
|
||||
EntityPlayerMP player) {
|
||||
IInventory inv = extractor.apply(stack);
|
||||
if (inv == null) return 0;
|
||||
int found = takeFromInventory(
|
||||
new InventoryIterable<>(inv), predicate, simulate, count, store, filter, player, false);
|
||||
if (found > 0) inv.markDirty();
|
||||
return found;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* take count amount of stacks that matches given filter. might take partial amount of stuff, so simulation is suggested
|
||||
* if you ever need to take more than one.
|
||||
*
|
||||
* @param player source of stacks
|
||||
* @param predicate item stack filter
|
||||
* @param simulate whether to do removal
|
||||
* @param count let's hope int size is enough...
|
||||
* @return amount taken. never negative nor bigger than count...
|
||||
*/
|
||||
public static Map<ItemStack, Integer> takeFromInventory(
|
||||
EntityPlayerMP player, Predicate<ItemStack> predicate, boolean simulate, int count) {
|
||||
ItemStackCounterImpl store = new ItemStackCounterImpl();
|
||||
int sum = 0;
|
||||
for (InventoryProvider<?> provider : inventoryProviders) {
|
||||
sum += takeFromPlayer(player, predicate, simulate, count - sum, store, provider, null);
|
||||
if (sum >= count) return store.getStore();
|
||||
}
|
||||
return store.getStore();
|
||||
}
|
||||
|
||||
/**
|
||||
* take count amount of stacks that matches given filter. might take partial amount of stuff, so simulation is suggested
|
||||
* if you ever need to take more than one.
|
||||
*
|
||||
* @param player source of stacks
|
||||
* @param filter the precise type of item to extract. stackSize matters
|
||||
* @param simulate whether to do removal
|
||||
* @return amount taken. never negative nor bigger than count...
|
||||
*/
|
||||
public static int takeFromInventory(EntityPlayerMP player, ItemStack filter, boolean simulate) {
|
||||
int sum = 0;
|
||||
int count = filter.stackSize;
|
||||
ItemStackPredicate predicate = ItemStackPredicate.from(filter, NBTMode.EXACT);
|
||||
ItemStackCounterImpl store = new ItemStackCounterImpl();
|
||||
for (InventoryProvider<?> provider : inventoryProviders) {
|
||||
sum += takeFromPlayer(player, predicate, simulate, count - sum, store, provider, filter);
|
||||
if (sum >= count) return sum;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
// workaround java generics issue
|
||||
private static <R extends Iterable<ItemStack>> int takeFromPlayer(
|
||||
EntityPlayerMP player,
|
||||
Predicate<ItemStack> predicate,
|
||||
boolean simulate,
|
||||
int count,
|
||||
ItemStackCounterImpl store,
|
||||
InventoryProvider<R> provider,
|
||||
ItemStack filter) {
|
||||
R inv = provider.getInventory(player);
|
||||
if (inv == null) return 0;
|
||||
int taken = takeFromInventory(inv, predicate, simulate, count, store, filter, player, true);
|
||||
if (taken > 0) provider.markDirty(inv);
|
||||
return taken;
|
||||
}
|
||||
|
||||
/**
|
||||
* take count amount of stacks that matches given filter. Will do 1 level of recursion to try find more stacks....
|
||||
* e.g. from backpacks...
|
||||
*
|
||||
* @param inv source of stacks
|
||||
* @param predicate item stack filter
|
||||
* @param simulate whether to do removal
|
||||
* @param count let's hope int size is enough...
|
||||
* @param recursive do recursive lookup using {@link #getStackExtractors() stack extractors}
|
||||
* @return amount taken. never negative nor bigger than count...
|
||||
*/
|
||||
public static Map<ItemStack, Integer> takeFromInventory(
|
||||
Iterable<ItemStack> inv, Predicate<ItemStack> predicate, boolean simulate, int count, boolean recursive) {
|
||||
ItemStackCounterImpl store = new ItemStackCounterImpl();
|
||||
takeFromInventory(inv, predicate, simulate, count, store, null, null, recursive);
|
||||
return store.getStore();
|
||||
}
|
||||
|
||||
private static int takeFromInventory(
|
||||
@Nonnull Iterable<ItemStack> inv,
|
||||
@Nonnull Predicate<ItemStack> predicate,
|
||||
boolean simulate,
|
||||
int count,
|
||||
@Nonnull ItemStackCounter store,
|
||||
@Nullable ItemStack filter,
|
||||
@Nullable EntityPlayerMP player,
|
||||
boolean recursive) {
|
||||
int found = 0;
|
||||
ItemStack copiedFilter = null;
|
||||
if (filter != null) {
|
||||
copiedFilter = new ItemStack(filter.getItem(), filter.stackSize, Items.feather.getDamage(filter));
|
||||
copiedFilter.setTagCompound(filter.stackTagCompound);
|
||||
}
|
||||
for (Iterator<ItemStack> iterator = inv.iterator(); iterator.hasNext(); ) {
|
||||
ItemStack stack = iterator.next();
|
||||
// invalid stack
|
||||
if (stack == null || stack.getItem() == null || stack.stackSize <= 0) continue;
|
||||
|
||||
if (predicate.test(stack)) {
|
||||
found += stack.stackSize;
|
||||
if (found > count) {
|
||||
int surplus = found - count;
|
||||
store.add(stack, stack.stackSize - surplus);
|
||||
if (!simulate) {
|
||||
// leave the surplus in its place
|
||||
stack.stackSize = surplus;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
store.add(stack, stack.stackSize);
|
||||
if (!simulate) iterator.remove();
|
||||
if (found == count) return count;
|
||||
}
|
||||
if (!recursive) continue;
|
||||
for (ItemStackExtractor f : stackExtractors) {
|
||||
if (filter != null && f.isAPIImplemented(APIType.EXTRACT_ONE_STACK)) {
|
||||
copiedFilter.stackSize = count - found;
|
||||
found += f.getItem(stack, copiedFilter, simulate, player);
|
||||
} else {
|
||||
found += f.takeFromStack(predicate, simulate, count - found, store, stack, filter, player);
|
||||
}
|
||||
if (found >= count) return found;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
public interface OptimizedExtractor {
|
||||
/**
|
||||
* Extract a particular type of item. The extractor can choose to not return all items contained within this item
|
||||
* as long as it makes sense, but the author should inform the player of this.
|
||||
* <p>
|
||||
* Whether optimized extractor do recursive extraction is at the discretion of implementor.
|
||||
*
|
||||
* @param source from where an extraction should be attempted
|
||||
* @param toExtract stack to extract. should not be mutated! match the NBT tag using EXACT mode.
|
||||
* @param simulate true if only query but does not actually remove
|
||||
* @param player executor of extraction, or null if from a machine
|
||||
* @return amount extracted
|
||||
*/
|
||||
int extract(ItemStack source, ItemStack toExtract, boolean simulate, EntityPlayerMP player);
|
||||
}
|
||||
|
||||
public interface InventoryProvider<R extends Iterable<ItemStack>> {
|
||||
R getInventory(EntityPlayerMP player);
|
||||
|
||||
void markDirty(R inv);
|
||||
}
|
||||
|
||||
public interface ItemStackExtractor {
|
||||
enum APIType {
|
||||
MAIN,
|
||||
EXTRACT_ONE_STACK,
|
||||
}
|
||||
|
||||
boolean isAPIImplemented(APIType type);
|
||||
|
||||
/**
|
||||
* Extract a particular type of item. The extractor can choose to not return all items contained within this item
|
||||
* as long as it makes sense, but the author should inform the player of this.
|
||||
* <p>
|
||||
* Whether this method does recursive extraction is at the discretion of implementor.
|
||||
*
|
||||
* @param predicate the main filtering predicate. never null. It's assumed predicate always returns true on filter,
|
||||
* if that is not null
|
||||
* @param store where to store extracted items. Should increment the
|
||||
* @param source from where an extraction should be attempted
|
||||
* @param filter stack to extract. should not be mutated! match the NBT tag using EXACT mode. might be null.
|
||||
* @param simulate true if only query but does not actually remove
|
||||
* @param player executor of extraction, or null if from a machine
|
||||
* @return amount extracted, or -1 if this is not implemented
|
||||
*/
|
||||
int takeFromStack(
|
||||
Predicate<ItemStack> predicate,
|
||||
boolean simulate,
|
||||
int count,
|
||||
ItemStackCounter store,
|
||||
ItemStack source,
|
||||
ItemStack filter,
|
||||
EntityPlayerMP player);
|
||||
|
||||
/**
|
||||
* Extract a particular type of item. The extractor can choose to not return all items contained within this item
|
||||
* as long as it makes sense, but the author should inform the player of this.
|
||||
* <p>
|
||||
* Whether this method does recursive extraction is at the discretion of implementor.
|
||||
*
|
||||
* @param source from where an extraction should be attempted
|
||||
* @param toExtract stack to extract. should not be mutated! match the NBT tag using EXACT mode.
|
||||
* @param simulate true if only query but does not actually remove
|
||||
* @param player executor of extraction, or null if from a machine
|
||||
* @return amount extracted, or -1 if this is not implemented
|
||||
*/
|
||||
default int getItem(ItemStack source, ItemStack toExtract, boolean simulate, EntityPlayerMP player) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
static ItemStackExtractor createOnlyOptimized(@Nonnull OptimizedExtractor optimizedExtractor) {
|
||||
return new ItemStackExtractor() {
|
||||
@Override
|
||||
public boolean isAPIImplemented(APIType type) {
|
||||
return type == APIType.EXTRACT_ONE_STACK;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int takeFromStack(
|
||||
Predicate<ItemStack> predicate,
|
||||
boolean simulate,
|
||||
int count,
|
||||
ItemStackCounter store,
|
||||
ItemStack stack,
|
||||
ItemStack filter,
|
||||
EntityPlayerMP player) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItem(ItemStack source, ItemStack toExtract, boolean simulate, EntityPlayerMP player) {
|
||||
return optimizedExtractor.extract(source, toExtract, simulate, player);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public interface ItemStackCounter {
|
||||
/**
|
||||
* Add some amount of stack. Note stackSize is used instead of stack.stackSize.
|
||||
*/
|
||||
void add(ItemStack stack, int stackSize);
|
||||
}
|
||||
|
||||
private static class ItemStackCounterImpl implements ItemStackCounter {
|
||||
private final Map<ItemStack, Integer> store = new ItemStackMap<>();
|
||||
|
||||
@Override
|
||||
public void add(ItemStack stack, int stackSize) {
|
||||
if (stack == null || stack.getItem() == null || stackSize <= 0) throw new IllegalArgumentException();
|
||||
store.merge(stack, stackSize, Integer::sum);
|
||||
}
|
||||
|
||||
public Map<ItemStack, Integer> getStore() {
|
||||
return store;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.gtnewhorizon.structurelib.util;
|
||||
|
||||
import java.util.Iterator;
|
||||
import net.minecraft.item.ItemStack;
|
||||
|
||||
public class ItemStackArrayIterable implements Iterable<ItemStack> {
|
||||
private final ItemStack[] stacks;
|
||||
|
||||
public ItemStackArrayIterable(ItemStack[] stacks) {
|
||||
this.stacks = stacks;
|
||||
}
|
||||
|
||||
public ItemStack[] getStacks() {
|
||||
return stacks;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<ItemStack> iterator() {
|
||||
return new Iterator<ItemStack>() {
|
||||
private int ptr = 0;
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return ptr < stacks.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack next() {
|
||||
return stacks[ptr++];
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
stacks[ptr - 1] = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
/*
|
||||
* Copyright (c) 2021, glee8e, Code Chicken.
|
||||
*
|
||||
* This file is originally part of NotEnoughtItem by Code Chicken.
|
||||
* It is adapted to implement the standard Map interface by glease
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as published by
|
||||
* the Free Software Foundation, either version 2.1 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
package com.gtnewhorizon.structurelib.util;
|
||||
|
||||
import static net.minecraftforge.oredict.OreDictionary.WILDCARD_VALUE;
|
||||
|
||||
import com.google.common.base.Objects;
|
||||
import com.google.common.collect.Iterators;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.AbstractSet;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Set;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import net.minecraft.init.Items;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
|
||||
/**
|
||||
* A map class for ItemStack keys with wildcard damage/NBT. Optimised for lookup.
|
||||
* <p>
|
||||
* This map does NOT support null values or null keys! null will be silently ignored!
|
||||
* <p>
|
||||
* Originally created by CodeChicken for NotEnoughItems. Adapted to {@code Map<ItemStack, T>} interface by glee8e
|
||||
* @author CodeChiken
|
||||
* @author glee8e
|
||||
*/
|
||||
public final class ItemStackMap<T> extends AbstractMap<ItemStack, T> {
|
||||
public static final NBTTagCompound WILDCARD_TAG;
|
||||
|
||||
static {
|
||||
WILDCARD_TAG = new NBTTagCompound();
|
||||
WILDCARD_TAG.setBoolean("*", true);
|
||||
}
|
||||
|
||||
private final HashMap<Item, DetailMap> itemMap = new HashMap<>();
|
||||
private int size;
|
||||
|
||||
static ItemStack newItemStack(Item item, int size, int damage, NBTTagCompound tag) {
|
||||
ItemStack stack = new ItemStack(item, size, damage);
|
||||
stack.stackTagCompound = tag;
|
||||
return stack;
|
||||
}
|
||||
|
||||
static int actualDamage(ItemStack stack) {
|
||||
return Items.diamond.getDamage(stack);
|
||||
}
|
||||
|
||||
static int getKeyType(int damage, NBTTagCompound tag) {
|
||||
int i = 0;
|
||||
if (isWildcard(damage)) i = 1;
|
||||
if (isWildcard(tag)) i |= 2;
|
||||
return i;
|
||||
}
|
||||
|
||||
static ItemStack wildcard(Item item) {
|
||||
return newItemStack(item, 1, WILDCARD_VALUE, WILDCARD_TAG);
|
||||
}
|
||||
|
||||
static boolean isWildcard(int damage) {
|
||||
return damage == WILDCARD_VALUE;
|
||||
}
|
||||
|
||||
static boolean isWildcard(NBTTagCompound tag) {
|
||||
return tag != null && tag.getBoolean("*");
|
||||
}
|
||||
|
||||
@Override
|
||||
public T get(Object key) {
|
||||
if (!(key instanceof ItemStack)) return null;
|
||||
ItemStack stack = ((ItemStack) key);
|
||||
if (stack.getItem() == null) return null;
|
||||
DetailMap map = itemMap.get(stack.getItem());
|
||||
return map == null ? null : map.get(stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T put(ItemStack key, T value) {
|
||||
if (key == null || key.getItem() == null || value == null) return null;
|
||||
return itemMap.computeIfAbsent(key.getItem(), k -> new DetailMap()).put(key, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T remove(Object key) {
|
||||
if (!(key instanceof ItemStack)) return null;
|
||||
ItemStack stack = ((ItemStack) key);
|
||||
if (stack.getItem() == null) return null;
|
||||
DetailMap map = itemMap.get(stack.getItem());
|
||||
return map == null ? null : map.remove(stack);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean containsKey(Object key) {
|
||||
if (!(key instanceof ItemStack)) return false;
|
||||
ItemStack stack = ((ItemStack) key);
|
||||
if (stack.getItem() == null) return false;
|
||||
DetailMap map = itemMap.get(stack.getItem());
|
||||
return map != null && map.get(stack) != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
itemMap.clear();
|
||||
size = 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<Map.Entry<ItemStack, T>> entrySet() {
|
||||
return new SetView();
|
||||
}
|
||||
|
||||
private static class StackMetaKey {
|
||||
public final int damage;
|
||||
public final NBTTagCompound tag;
|
||||
|
||||
public StackMetaKey(int damage, NBTTagCompound tag) {
|
||||
this.damage = damage;
|
||||
this.tag = tag;
|
||||
}
|
||||
|
||||
public StackMetaKey(ItemStack key) {
|
||||
this(actualDamage(key), key.stackTagCompound);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(damage, tag);
|
||||
}
|
||||
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof StackMetaKey)) return false;
|
||||
StackMetaKey t = (StackMetaKey) o;
|
||||
return damage == t.damage && Objects.equal(tag, t.tag);
|
||||
}
|
||||
}
|
||||
|
||||
private static class DetailIter<T> implements Iterator<Map.Entry<ItemStack, T>> {
|
||||
private final Item owner;
|
||||
private final ItemStackMap<T>.DetailMap backing;
|
||||
|
||||
@Nullable
|
||||
private final Iterator<Map.Entry<Integer, T>> damageIter;
|
||||
|
||||
@Nullable
|
||||
private final Iterator<Map.Entry<NBTTagCompound, T>> tagIter;
|
||||
|
||||
@Nullable
|
||||
private final Iterator<Map.Entry<StackMetaKey, T>> metaIter;
|
||||
|
||||
private DetailIterState state = DetailIterState.NOT_STARTED;
|
||||
private boolean removed = false;
|
||||
|
||||
private DetailIter(Map.Entry<Item, ItemStackMap<T>.DetailMap> input) {
|
||||
this.owner = input.getKey();
|
||||
this.backing = input.getValue();
|
||||
damageIter =
|
||||
backing.damageMap != null ? backing.damageMap.entrySet().iterator() : null;
|
||||
tagIter = backing.tagMap != null ? backing.tagMap.entrySet().iterator() : null;
|
||||
metaIter = backing.metaMap != null ? backing.metaMap.entrySet().iterator() : null;
|
||||
}
|
||||
|
||||
private DetailIterState nextState() {
|
||||
switch (state) {
|
||||
case NOT_STARTED:
|
||||
if (backing.hasWildcard) return DetailIterState.WILDCARD;
|
||||
case WILDCARD:
|
||||
case DAMAGE:
|
||||
if (damageIter != null && damageIter.hasNext()) return DetailIterState.DAMAGE;
|
||||
case TAG:
|
||||
if (tagIter != null && tagIter.hasNext()) return DetailIterState.TAG;
|
||||
case META:
|
||||
if (metaIter != null && metaIter.hasNext()) return DetailIterState.META;
|
||||
case DONE:
|
||||
return DetailIterState.DONE;
|
||||
default:
|
||||
throw new IllegalStateException("Unexpected value: " + state);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void remove() {
|
||||
if (removed) throw new IllegalStateException("remove() called twice");
|
||||
state.remove(this);
|
||||
removed = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return nextState() != DetailIterState.DONE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map.Entry<ItemStack, T> next() {
|
||||
DetailIterState nextState = nextState();
|
||||
if (nextState == DetailIterState.DONE) throw new NoSuchElementException();
|
||||
state = nextState;
|
||||
removed = false;
|
||||
return nextState.get(this);
|
||||
}
|
||||
|
||||
private enum DetailIterState {
|
||||
NOT_STARTED {
|
||||
@Override
|
||||
<T> Map.Entry<ItemStack, T> get(DetailIter<T> iter) {
|
||||
throw new AssertionError("Should not call get on NOT_STARTED");
|
||||
}
|
||||
|
||||
@Override
|
||||
<T> void remove(DetailIter<T> iter) {
|
||||
throw new IllegalStateException("next() never called");
|
||||
}
|
||||
},
|
||||
WILDCARD {
|
||||
@Override
|
||||
<T> Map.Entry<ItemStack, T> get(DetailIter<T> iter) {
|
||||
return new Map.Entry<ItemStack, T>() {
|
||||
private final ItemStack key = wildcard(iter.owner);
|
||||
|
||||
@Override
|
||||
public ItemStack getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getValue() {
|
||||
return iter.backing.wildcard;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T setValue(T value) {
|
||||
return iter.backing.wildcard = value;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
<T> void remove(DetailIter<T> iter) {
|
||||
assert iter.backing.hasWildcard;
|
||||
iter.backing.wildcard = null;
|
||||
iter.backing.hasWildcard = false;
|
||||
}
|
||||
},
|
||||
DAMAGE {
|
||||
@Override
|
||||
<T> Map.Entry<ItemStack, T> get(DetailIter<T> iter) {
|
||||
assert iter.damageIter != null;
|
||||
Map.Entry<Integer, T> entry = iter.damageIter.next();
|
||||
return new ItemStackEntry<>(newItemStack(iter.owner, 1, entry.getKey(), WILDCARD_TAG), entry);
|
||||
}
|
||||
|
||||
@Override
|
||||
<T> void remove(DetailIter<T> iter) {
|
||||
assert iter.damageIter != null;
|
||||
iter.damageIter.remove();
|
||||
}
|
||||
},
|
||||
TAG {
|
||||
@Override
|
||||
<T> Map.Entry<ItemStack, T> get(DetailIter<T> iter) {
|
||||
assert iter.tagIter != null;
|
||||
Map.Entry<NBTTagCompound, T> entry = iter.tagIter.next();
|
||||
return new ItemStackEntry<>(newItemStack(iter.owner, 1, WILDCARD_VALUE, entry.getKey()), entry);
|
||||
}
|
||||
|
||||
@Override
|
||||
<T> void remove(DetailIter<T> iter) {
|
||||
assert iter.tagIter != null;
|
||||
iter.tagIter.remove();
|
||||
}
|
||||
},
|
||||
META {
|
||||
@Override
|
||||
<T> Map.Entry<ItemStack, T> get(DetailIter<T> iter) {
|
||||
assert iter.metaIter != null;
|
||||
Map.Entry<StackMetaKey, T> entry = iter.metaIter.next();
|
||||
return new ItemStackEntry<>(
|
||||
newItemStack(iter.owner, 1, entry.getKey().damage, entry.getKey().tag), entry);
|
||||
}
|
||||
|
||||
@Override
|
||||
<T> void remove(DetailIter<T> iter) {
|
||||
assert iter.metaIter != null;
|
||||
iter.metaIter.remove();
|
||||
}
|
||||
},
|
||||
DONE {
|
||||
@Override
|
||||
<T> Map.Entry<ItemStack, T> get(DetailIter<T> iter) {
|
||||
throw new AssertionError("Should not call get on DONE");
|
||||
}
|
||||
|
||||
@Override
|
||||
<T> void remove(DetailIter<T> iter) {
|
||||
throw new AssertionError("Should not call remove on DONE");
|
||||
}
|
||||
};
|
||||
|
||||
abstract <T> Map.Entry<ItemStack, T> get(DetailIter<T> iter);
|
||||
|
||||
abstract <T> void remove(DetailIter<T> iter);
|
||||
|
||||
private static class ItemStackEntry<T> implements Map.Entry<ItemStack, T> {
|
||||
private final ItemStack key;
|
||||
private final Map.Entry<?, T> entry;
|
||||
|
||||
public ItemStackEntry(ItemStack key, Map.Entry<?, T> entry) {
|
||||
this.key = key;
|
||||
this.entry = entry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ItemStack getKey() {
|
||||
return key;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T getValue() {
|
||||
return entry.getValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
public T setValue(T value) {
|
||||
return entry.setValue(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class DetailMap {
|
||||
private boolean hasWildcard;
|
||||
private T wildcard;
|
||||
private HashMap<Integer, T> damageMap;
|
||||
private HashMap<NBTTagCompound, T> tagMap;
|
||||
private HashMap<StackMetaKey, T> metaMap;
|
||||
private int size;
|
||||
|
||||
public T get(ItemStack key) {
|
||||
if (wildcard != null) return wildcard;
|
||||
|
||||
if (damageMap != null) {
|
||||
final T ret = damageMap.get(actualDamage(key));
|
||||
if (ret != null) return ret;
|
||||
}
|
||||
if (tagMap != null) {
|
||||
final T ret = tagMap.get(key.stackTagCompound);
|
||||
if (ret != null) return ret;
|
||||
}
|
||||
if (metaMap != null) return metaMap.get(new StackMetaKey(key));
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public T put(ItemStack key, T value) {
|
||||
try {
|
||||
switch (getKeyType(actualDamage(key), key.stackTagCompound)) {
|
||||
case 0:
|
||||
if (metaMap == null) metaMap = new HashMap<>();
|
||||
return metaMap.put(new StackMetaKey(key), value);
|
||||
case 1:
|
||||
if (tagMap == null) tagMap = new HashMap<>();
|
||||
return tagMap.put(key.stackTagCompound, value);
|
||||
case 2:
|
||||
if (damageMap == null) damageMap = new HashMap<>();
|
||||
return damageMap.put(actualDamage(key), value);
|
||||
case 3:
|
||||
T ret = wildcard;
|
||||
wildcard = value;
|
||||
hasWildcard = true;
|
||||
return ret;
|
||||
}
|
||||
} finally {
|
||||
updateSize();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public T remove(ItemStack key) {
|
||||
try {
|
||||
switch (getKeyType(actualDamage(key), key.stackTagCompound)) {
|
||||
case 0:
|
||||
return metaMap != null ? metaMap.remove(new StackMetaKey(key)) : null;
|
||||
case 1:
|
||||
return tagMap != null ? tagMap.remove(key.stackTagCompound) : null;
|
||||
case 2:
|
||||
return damageMap != null ? damageMap.remove(actualDamage(key)) : null;
|
||||
case 3:
|
||||
T ret = wildcard;
|
||||
wildcard = null;
|
||||
hasWildcard = false;
|
||||
return ret;
|
||||
}
|
||||
} finally {
|
||||
updateSize();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void updateSize() {
|
||||
int newSize = (hasWildcard ? 1 : 0)
|
||||
+ (metaMap != null ? metaMap.size() : 0)
|
||||
+ (tagMap != null ? tagMap.size() : 0)
|
||||
+ (damageMap != null ? damageMap.size() : 0);
|
||||
|
||||
if (newSize != size) {
|
||||
ItemStackMap.this.size += newSize - size;
|
||||
size = newSize;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class SetView extends AbstractSet<Map.Entry<ItemStack, T>> {
|
||||
@Override
|
||||
public boolean contains(Object o) {
|
||||
if (!(o instanceof Map.Entry)) return false;
|
||||
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
|
||||
return java.util.Objects.equals(get(entry.getKey()), entry.getValue());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(Map.Entry<ItemStack, T> itemStackTEntry) {
|
||||
return itemStackTEntry.getKey() != null
|
||||
&& itemStackTEntry.getValue() != null
|
||||
&& put(itemStackTEntry.getKey(), itemStackTEntry.getValue()) == null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object o) {
|
||||
if (!(o instanceof Map.Entry)) return false;
|
||||
Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o;
|
||||
return ItemStackMap.this.remove(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
@Override
|
||||
public Iterator<Map.Entry<ItemStack, T>> iterator() {
|
||||
return Iterators.concat(Iterators.transform(itemMap.entrySet().iterator(), DetailIter::new));
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return size;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.gtnewhorizon.structurelib.util;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.init.Items;
|
||||
import net.minecraft.item.Item;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.nbt.NBTBase;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
|
||||
public final class ItemStackPredicate implements Predicate<ItemStack> {
|
||||
public static ItemStackPredicate from(Item item) {
|
||||
return new ItemStackPredicate(item);
|
||||
}
|
||||
|
||||
public static ItemStackPredicate from(ItemStack itemStack) {
|
||||
return new ItemStackPredicate(itemStack.getItem()).setMeta(Items.feather.getDamage(itemStack));
|
||||
}
|
||||
|
||||
public static ItemStackPredicate from(ItemStack itemStack, NBTMode mode) {
|
||||
return new ItemStackPredicate(itemStack.getItem())
|
||||
.setMeta(Items.feather.getDamage(itemStack))
|
||||
.setTag(mode, itemStack.stackTagCompound);
|
||||
}
|
||||
|
||||
public static ItemStackPredicate from(Block block) {
|
||||
return new ItemStackPredicate(Item.getItemFromBlock(block));
|
||||
}
|
||||
|
||||
private final Item item;
|
||||
private int meta = -1;
|
||||
|
||||
private NBTTagCompound tag;
|
||||
private NBTMode mode = NBTMode.IGNORE;
|
||||
|
||||
private ItemStackPredicate(Item item) {
|
||||
this.item = item;
|
||||
}
|
||||
|
||||
public ItemStackPredicate ignoreMeta() {
|
||||
this.meta = -1;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemStackPredicate setMeta(int meta) {
|
||||
this.meta = meta;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ItemStackPredicate setTag(NBTMode mode, NBTTagCompound tag) {
|
||||
this.mode = mode;
|
||||
this.tag = tag;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean test(ItemStack itemStack) {
|
||||
if (item != null) if (itemStack.getItem() != item) return false;
|
||||
if (meta != -1) if (Items.feather.getDamage(itemStack) != meta) return false;
|
||||
return mode.test(tag, itemStack.stackTagCompound);
|
||||
}
|
||||
|
||||
public enum NBTMode implements BiPredicate<NBTTagCompound, NBTTagCompound> {
|
||||
IGNORE {
|
||||
@Override
|
||||
public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) {
|
||||
return true;
|
||||
}
|
||||
},
|
||||
IN {
|
||||
@Override
|
||||
public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) {
|
||||
if (lhs == null || lhs.hasNoTags()) return true;
|
||||
if (rhs == null || rhs.hasNoTags()) return false;
|
||||
for (String key : MiscUtils.getTagKeys(lhs)) {
|
||||
if (!rhs.hasKey(key, lhs.func_150299_b(key))) return false;
|
||||
NBTBase tag = lhs.getTag(key);
|
||||
if (tag instanceof NBTTagCompound) {
|
||||
if (!test((NBTTagCompound) tag, rhs.getCompoundTag(key))) return false;
|
||||
} else {
|
||||
if (!tag.equals(rhs.getTag(key))) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
},
|
||||
EXACT {
|
||||
@Override
|
||||
public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) {
|
||||
if (lhs != null && lhs.hasNoTags()) lhs = null;
|
||||
if (rhs != null && rhs.hasNoTags()) rhs = null;
|
||||
return Objects.equals(lhs, rhs);
|
||||
}
|
||||
},
|
||||
IGNORE_KNOWN_INSIGNIFICANT_TAGS {
|
||||
@Override
|
||||
public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) {
|
||||
// fast path for empty tags
|
||||
if (rhs == null || rhs.hasNoTags()) return lhs == null || lhs.hasNoTags();
|
||||
// TODO make an implementation without copying a potentially huge tag
|
||||
rhs = (NBTTagCompound) rhs.copy();
|
||||
for (String s : KNOWN_INSIGNIFICANT_TAGS) rhs.removeTag(s);
|
||||
return EXACT.test(lhs, rhs);
|
||||
}
|
||||
};
|
||||
private static final String[] KNOWN_INSIGNIFICANT_TAGS = {
|
||||
"display", // TODO expand/refine this
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.gtnewhorizon.structurelib.util;
|
||||
|
||||
import java.util.Set;
|
||||
import net.minecraft.nbt.NBTTagCompound;
|
||||
|
||||
/**
|
||||
* not related to a certain mod!
|
||||
*/
|
||||
public class MiscUtils {
|
||||
private MiscUtils() {}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Set<String> getTagKeys(NBTTagCompound tag) {
|
||||
return tag.func_150296_c();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.gtnewhorizon.structurelib.util;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class SortedRegistry<V> implements Iterable<V> {
|
||||
private final NavigableMap<String, V> store = new TreeMap<>();
|
||||
/**
|
||||
* Store stuff in an array for faster iteration access than a red black tree
|
||||
*/
|
||||
private List<V> baked = Collections.emptyList();
|
||||
|
||||
public void register(String key, V val) {
|
||||
if (key == null || val == null) throw new NullPointerException();
|
||||
V old = store.putIfAbsent(key, val);
|
||||
if (old != null) {
|
||||
throw new IllegalArgumentException("Duplicate key: " + key);
|
||||
}
|
||||
// TODO allow a user to edit the order with a configuration file
|
||||
baked = new ArrayList<>(store.values());
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return store.size();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return store.isEmpty();
|
||||
}
|
||||
|
||||
public boolean containsKey(String key) {
|
||||
return store.containsKey(key);
|
||||
}
|
||||
|
||||
public boolean containsValue(V value) {
|
||||
return store.containsValue(value);
|
||||
}
|
||||
|
||||
public V get(String key) {
|
||||
return store.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Iterator<V> iterator() {
|
||||
return baked.iterator();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void forEach(Consumer<? super V> action) {
|
||||
baked.forEach(action);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Spliterator<V> spliterator() {
|
||||
return baked.spliterator();
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,9 @@ public class Vec3Impl implements Comparable<Vec3Impl> {
|
||||
}
|
||||
|
||||
public Vec3Impl offset(ForgeDirection facing, int n) {
|
||||
return n == 0 ? this : new Vec3Impl(val0 + facing.offsetX * n, val1 + facing.offsetY * n, val2 + facing.offsetZ * n);
|
||||
return n == 0
|
||||
? this
|
||||
: new Vec3Impl(val0 + facing.offsetX * n, val1 + facing.offsetY * n, val2 + facing.offsetZ * n);
|
||||
}
|
||||
|
||||
public Vec3Impl add(Vec3Impl pos) {
|
||||
@@ -77,8 +79,10 @@ public class Vec3Impl implements Comparable<Vec3Impl> {
|
||||
}
|
||||
|
||||
public Vec3Impl crossProduct(Vec3Impl vec) {
|
||||
return new Vec3Impl(val1 * vec.val2 - val2 * vec.val1, val2 * vec.val0 - val0 * vec.val2,
|
||||
val0 * vec.val1 - val1 * vec.val0);
|
||||
return new Vec3Impl(
|
||||
val1 * vec.val2 - val2 * vec.val1,
|
||||
val2 * vec.val0 - val0 * vec.val2,
|
||||
val0 * vec.val1 - val1 * vec.val0);
|
||||
}
|
||||
|
||||
public boolean withinDistance(Vec3Impl to, double distance) {
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
package com.gtnewhorizon.structurelib.util;
|
||||
/*
|
||||
A subclass of java.util.random that implements the Xorshift random number
|
||||
generator
|
||||
<p>
|
||||
- it is 30% faster than the generator from Java's library - it produces
|
||||
random sequences of higher quality than java.util.Random - this class also
|
||||
provides a clone() function
|
||||
<p>
|
||||
Usage: XSRandom rand = new XSRandom(); //Instantiation x = rand.nextInt();
|
||||
//pull a random number
|
||||
<p>
|
||||
To use the class in legacy code, you may also instantiate an XSRandom object
|
||||
and assign it to a java.util.Random object: java.util.Random rand = new
|
||||
XSRandom();
|
||||
<p>
|
||||
for an explanation of the algorithm, see
|
||||
http://demesos.blogspot.com/2011/09/pseudo-random-number-generators.html
|
||||
A subclass of java.util.random that implements the Xorshift random number
|
||||
generator
|
||||
<p>
|
||||
- it is 30% faster than the generator from Java's library - it produces
|
||||
random sequences of higher quality than java.util.Random - this class also
|
||||
provides a clone() function
|
||||
<p>
|
||||
Usage: XSRandom rand = new XSRandom(); //Instantiation x = rand.nextInt();
|
||||
//pull a random number
|
||||
<p>
|
||||
To use the class in legacy code, you may also instantiate an XSRandom object
|
||||
and assign it to a java.util.Random object: java.util.Random rand = new
|
||||
XSRandom();
|
||||
<p>
|
||||
for an explanation of the algorithm, see
|
||||
http://demesos.blogspot.com/2011/09/pseudo-random-number-generators.html
|
||||
|
||||
@author Wilfried Elmenreich University of Klagenfurt/Lakeside Labs
|
||||
* http://www.elmenreich.tk
|
||||
* <p>
|
||||
* This code is released under the GNU Lesser General Public License Version 3
|
||||
* http://www.gnu.org/licenses/lgpl-3.0.txt
|
||||
*/
|
||||
@author Wilfried Elmenreich University of Klagenfurt/Lakeside Labs
|
||||
* http://www.elmenreich.tk
|
||||
* <p>
|
||||
* This code is released under the GNU Lesser General Public License Version 3
|
||||
* http://www.gnu.org/licenses/lgpl-3.0.txt
|
||||
*/
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
@@ -40,7 +40,7 @@ public class XSTR extends Random {
|
||||
private static final long GAMMA = 0x9e3779b97f4a7c15L;
|
||||
private static final int PROBE_INCREMENT = 0x9e3779b9;
|
||||
private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
|
||||
private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
|
||||
private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
|
||||
private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f / (1 << 24)
|
||||
private static final AtomicLong seedUniquifier = new AtomicLong(8682522807148012L);
|
||||
public static final XSTR XSTR_INSTANCE = new XSTR() {
|
||||
@@ -53,9 +53,9 @@ public class XSTR extends Random {
|
||||
};
|
||||
|
||||
/*
|
||||
MODIFIED BY: Robotia
|
||||
Modification: Implemented Random class seed generator
|
||||
*/
|
||||
MODIFIED BY: Robotia
|
||||
Modification: Implemented Random class seed generator
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a new pseudo random number generator. The seed is initialized to
|
||||
@@ -226,9 +226,9 @@ public class XSTR extends Random {
|
||||
*/
|
||||
@Override
|
||||
public int nextInt(int bound) {
|
||||
//if (bound <= 0) {
|
||||
//throw new RuntimeException("BadBound");
|
||||
//}
|
||||
// if (bound <= 0) {
|
||||
// throw new RuntimeException("BadBound");
|
||||
// }
|
||||
|
||||
/*int r = next(31);
|
||||
int m = bound - 1;
|
||||
@@ -242,7 +242,7 @@ public class XSTR extends Random {
|
||||
;
|
||||
}
|
||||
return r;*/
|
||||
//speedup, new nextInt ~+40%
|
||||
// speedup, new nextInt ~+40%
|
||||
long last = seed ^ seed << 21;
|
||||
last ^= last >>> 35;
|
||||
last ^= last << 4;
|
||||
@@ -270,7 +270,9 @@ public class XSTR extends Random {
|
||||
@Override
|
||||
public void nextBytes(byte[] bytes_arr) {
|
||||
for (int iba = 0, lenba = bytes_arr.length; iba < lenba; ) {
|
||||
for (int rndba = nextInt(), nba = Math.min(lenba - iba, Integer.SIZE / Byte.SIZE); nba-- > 0; rndba >>= Byte.SIZE) {
|
||||
for (int rndba = nextInt(), nba = Math.min(lenba - iba, Integer.SIZE / Byte.SIZE);
|
||||
nba-- > 0;
|
||||
rndba >>= Byte.SIZE) {
|
||||
bytes_arr[iba++] = (byte) rndba;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user