use of network.rs485.logisticspipes.connection.Adjacent in project LogisticsPipes by RS485.
the class PipeItemsProviderLogistics method getAllItems.
@Override
public void getAllItems(Map<ItemIdentifier, Integer> items, List<IFilter> filters) {
if (!isEnabled()) {
return;
}
HashMap<ItemIdentifier, Integer> addedItems = new HashMap<>();
WorldCoordinatesWrapper worldCoordinates = new WorldCoordinatesWrapper(container);
//@formatter:off
Iterator<Map<ItemIdentifier, Integer>> iterator = worldCoordinates.getConnectedAdjacentTileEntities(ConnectionPipeType.ITEM).filter(adjacent -> adjacent.tileEntity instanceof IInventory).filter(adjacent -> !SimpleServiceLocator.pipeInformationManager.isItemPipe(adjacent.tileEntity)).map(adjacent -> getAdaptedInventoryUtil(adjacent).getItemsAndCount()).iterator();
outer: while (iterator.hasNext()) {
Iterator<Entry<ItemIdentifier, Integer>> entryIterator = iterator.next().entrySet().stream().filter(currentItem -> !items.containsKey(currentItem.getKey())).filter(currentItem -> !hasFilter() || (!isExcludeFilter() || !itemIsFiltered(currentItem.getKey())) && (isExcludeFilter() || itemIsFiltered(currentItem.getKey()))).iterator();
while (entryIterator.hasNext()) {
Entry<ItemIdentifier, Integer> next = entryIterator.next();
for (IFilter filter : filters) {
if (filter.isBlocked() == filter.isFilteredItem(next.getKey().getUndamaged()) || filter.blockProvider()) {
continue outer;
}
}
Integer addedAmount = addedItems.get(next.getKey());
if (addedAmount == null) {
addedItems.put(next.getKey(), next.getValue());
} else {
addedItems.put(next.getKey(), addedAmount + next.getValue());
}
}
}
// reduce what has been reserved, add.
for (Entry<ItemIdentifier, Integer> item : addedItems.entrySet()) {
int remaining = item.getValue() - _orderManager.totalItemsCountInOrders(item.getKey());
if (remaining < 1) {
continue;
}
items.put(item.getKey(), remaining);
}
}
use of network.rs485.logisticspipes.connection.Adjacent in project LogisticsPipes by RS485.
the class PipeItemsProviderLogistics method sendStack.
private int sendStack(ItemIdentifierStack stack, int maxCount, int destination, IAdditionalTargetInformation info) {
ItemIdentifier item = stack.getItem();
WorldCoordinatesWrapper worldCoordinates = new WorldCoordinatesWrapper(container);
//@formatter:off
Iterator<Pair<IInventoryUtil, ForgeDirection>> iterator = worldCoordinates.getConnectedAdjacentTileEntities(ConnectionPipeType.ITEM).filter(adjacent -> adjacent.tileEntity instanceof IInventory).filter(adjacent -> !SimpleServiceLocator.pipeInformationManager.isItemPipe(adjacent.tileEntity)).map(adjacent -> new Pair<>(getAdaptedInventoryUtil(adjacent), adjacent.direction)).iterator();
while (iterator.hasNext()) {
Pair<IInventoryUtil, ForgeDirection> next = iterator.next();
int available = next.getValue1().itemCount(item);
if (available == 0) {
continue;
}
int wanted = Math.min(available, stack.getStackSize());
wanted = Math.min(wanted, maxCount);
wanted = Math.min(wanted, item.getMaxStackSize());
IRouter dRtr = SimpleServiceLocator.routerManager.getRouterUnsafe(destination, false);
if (dRtr == null) {
_orderManager.sendFailed();
return 0;
}
SinkReply reply = LogisticsManager.canSink(dRtr, null, true, stack.getItem(), null, true, false);
boolean defersend = false;
if (reply != null) {
// some pipes are not aware of the space in the adjacent inventory, so they return null
if (reply.maxNumberOfItems < wanted) {
wanted = reply.maxNumberOfItems;
if (wanted <= 0) {
_orderManager.deferSend();
return 0;
}
defersend = true;
}
}
if (!canUseEnergy(wanted * neededEnergy())) {
return -1;
}
ItemStack removed = next.getValue1().getMultipleItems(item, wanted);
if (removed == null || removed.stackSize == 0) {
continue;
}
int sent = removed.stackSize;
useEnergy(sent * neededEnergy());
IRoutedItem routedItem = SimpleServiceLocator.routedItemHelper.createNewTravelItem(removed);
routedItem.setDestination(destination);
routedItem.setTransportMode(TransportMode.Active);
routedItem.setAdditionalTargetInformation(info);
super.queueRoutedItem(routedItem, next.getValue2());
_orderManager.sendSuccessfull(sent, defersend, routedItem);
return sent;
}
_orderManager.sendFailed();
return 0;
}
use of network.rs485.logisticspipes.connection.Adjacent in project LogisticsPipes by RS485.
the class PipeTransportLayer method itemArrived.
@Override
public EnumFacing itemArrived(IRoutedItem item, EnumFacing denied) {
if (item.getItemIdentifierStack() != null) {
_trackStatistics.recievedItem(item.getItemIdentifierStack().getStackSize());
}
// 1st prio, deliver to adjacent inventories
LinkedList<EnumFacing> possibleEnumFacing = new LinkedList<>();
for (NeighborTileEntity<TileEntity> adjacent : routedPipe.getAvailableAdjacent().inventories()) {
if (_router.isRoutedExit(adjacent.getDirection())) {
continue;
}
if (denied != null && denied.equals(adjacent.getDirection())) {
continue;
}
CoreRoutedPipe pipe = _router.getPipe();
if (pipe != null) {
if (pipe.isLockedExit(adjacent.getDirection())) {
continue;
}
}
possibleEnumFacing.add(adjacent.getDirection());
}
if (possibleEnumFacing.size() != 0) {
return possibleEnumFacing.get(routedPipe.getWorld().rand.nextInt(possibleEnumFacing.size()));
}
// 2nd prio, deliver to non-routed exit
new WorldCoordinatesWrapper(routedPipe.container).connectedTileEntities().stream().filter(neighbor -> {
if (_router.isRoutedExit(neighbor.getDirection()))
return false;
final CoreRoutedPipe routerPipe = _router.getPipe();
return routerPipe == null || !routerPipe.isLockedExit(neighbor.getDirection());
}).forEach(neighbor -> possibleEnumFacing.add(neighbor.getDirection()));
if (possibleEnumFacing.size() == 0) {
// last resort, drop item
return null;
} else {
return possibleEnumFacing.get(routedPipe.getWorld().rand.nextInt(possibleEnumFacing.size()));
}
}
use of network.rs485.logisticspipes.connection.Adjacent in project LogisticsPipes by RS485.
the class ModuleCrafter method enabledUpdateEntity.
public void enabledUpdateEntity() {
final IPipeServiceProvider service = _service;
if (service == null)
return;
if (service.getItemOrderManager().hasOrders(ResourceType.CRAFTING, ResourceType.EXTRA)) {
if (service.isNthTick(6)) {
cacheAreAllOrderesToBuffer();
}
if (service.getItemOrderManager().isFirstOrderWatched()) {
TileEntity tile = lastAccessedCrafter.get();
if (tile != null) {
service.getItemOrderManager().setMachineProgress(SimpleServiceLocator.machineProgressProvider.getProgressForTile(tile));
} else {
service.getItemOrderManager().setMachineProgress((byte) 0);
}
}
} else {
cachedAreAllOrderesToBuffer = false;
}
if (!service.isNthTick(6)) {
return;
}
final List<NeighborTileEntity<TileEntity>> adjacentInventories = service.getAvailableAdjacent().inventories();
if (!service.getItemOrderManager().hasOrders(ResourceType.CRAFTING, ResourceType.EXTRA)) {
final ISlotUpgradeManager upgradeManager = Objects.requireNonNull(getUpgradeManager());
if (upgradeManager.getCrafterCleanup() > 0) {
adjacentInventories.stream().map(neighbor -> extractFiltered(neighbor, cleanupInventory, cleanupModeIsExclude.getValue(), upgradeManager.getCrafterCleanup() * 3)).filter(stack -> !stack.isEmpty()).findFirst().ifPresent(extracted -> {
service.queueRoutedItem(SimpleServiceLocator.routedItemHelper.createNewTravelItem(extracted), EnumFacing.UP);
service.getCacheHolder().trigger(CacheTypes.Inventory);
});
}
return;
}
if (adjacentInventories.size() < 1) {
if (service.getItemOrderManager().hasOrders(ResourceType.CRAFTING, ResourceType.EXTRA)) {
service.getItemOrderManager().sendFailed();
}
return;
}
List<ItemIdentifierStack> wanteditem = getCraftedItems();
if (wanteditem == null || wanteditem.isEmpty()) {
return;
}
service.spawnParticle(Particles.VioletParticle, 2);
int itemsleft = itemsToExtract();
int stacksleft = stacksToExtract();
while (itemsleft > 0 && stacksleft > 0 && (service.getItemOrderManager().hasOrders(ResourceType.CRAFTING, ResourceType.EXTRA))) {
LogisticsItemOrder nextOrder = service.getItemOrderManager().peekAtTopRequest(ResourceType.CRAFTING, // fetch but not remove.
ResourceType.EXTRA);
int maxtosend = Math.min(itemsleft, nextOrder.getResource().stack.getStackSize());
maxtosend = Math.min(nextOrder.getResource().getItem().getMaxStackSize(), maxtosend);
// retrieve the new crafted items
ItemStack extracted = ItemStack.EMPTY;
// there has to be at least one adjacentCrafter at this point; adjacent wont stay null
NeighborTileEntity<TileEntity> adjacent = null;
for (NeighborTileEntity<TileEntity> adjacentCrafter : adjacentInventories) {
adjacent = adjacentCrafter;
extracted = extract(adjacent, nextOrder.getResource(), maxtosend);
if (!extracted.isEmpty()) {
break;
}
}
if (extracted.isEmpty()) {
service.getItemOrderManager().deferSend();
break;
}
service.getCacheHolder().trigger(CacheTypes.Inventory);
Objects.requireNonNull(adjacent);
lastAccessedCrafter = new WeakReference<>(adjacent.getTileEntity());
// send the new crafted items to the destination
ItemIdentifier extractedID = ItemIdentifier.get(extracted);
while (!extracted.isEmpty()) {
if (isExtractedMismatch(nextOrder, extractedID)) {
LogisticsItemOrder startOrder = nextOrder;
if (service.getItemOrderManager().hasOrders(ResourceType.CRAFTING, ResourceType.EXTRA)) {
do {
service.getItemOrderManager().deferSend();
nextOrder = service.getItemOrderManager().peekAtTopRequest(ResourceType.CRAFTING, ResourceType.EXTRA);
} while (isExtractedMismatch(nextOrder, extractedID) && startOrder != nextOrder);
}
if (startOrder == nextOrder) {
int numtosend = Math.min(extracted.getCount(), extractedID.getMaxStackSize());
if (numtosend == 0) {
break;
}
stacksleft -= 1;
itemsleft -= numtosend;
ItemStack stackToSend = extracted.splitStack(numtosend);
// Route the unhandled item
service.sendStack(stackToSend, -1, ItemSendMode.Normal, null, adjacent.getDirection());
continue;
}
}
int numtosend = Math.min(extracted.getCount(), extractedID.getMaxStackSize());
numtosend = Math.min(numtosend, nextOrder.getResource().stack.getStackSize());
if (numtosend == 0) {
break;
}
stacksleft -= 1;
itemsleft -= numtosend;
ItemStack stackToSend = extracted.splitStack(numtosend);
if (nextOrder.getDestination() != null) {
SinkReply reply = LogisticsManager.canSink(stackToSend, nextOrder.getDestination().getRouter(), null, true, ItemIdentifier.get(stackToSend), null, true, false);
boolean defersend = (reply == null || reply.bufferMode != BufferMode.NONE || reply.maxNumberOfItems < 1);
IRoutedItem item = SimpleServiceLocator.routedItemHelper.createNewTravelItem(stackToSend);
item.setDestination(nextOrder.getDestination().getRouter().getSimpleID());
item.setTransportMode(TransportMode.Active);
item.setAdditionalTargetInformation(nextOrder.getInformation());
service.queueRoutedItem(item, adjacent.getDirection());
service.getItemOrderManager().sendSuccessfull(stackToSend.getCount(), defersend, item);
} else {
service.sendStack(stackToSend, -1, ItemSendMode.Normal, nextOrder.getInformation(), adjacent.getDirection());
service.getItemOrderManager().sendSuccessfull(stackToSend.getCount(), false, null);
}
if (service.getItemOrderManager().hasOrders(ResourceType.CRAFTING, ResourceType.EXTRA)) {
nextOrder = service.getItemOrderManager().peekAtTopRequest(ResourceType.CRAFTING, // fetch but not remove.
ResourceType.EXTRA);
}
}
}
}
use of network.rs485.logisticspipes.connection.Adjacent in project LogisticsPipes by RS485.
the class ServerRouter method recheckAdjacent.
/**
* Rechecks the piped connection to all adjacent routers as well as discover
* new ones.
*/
private boolean recheckAdjacent() {
connectionNeedsChecking = 0;
if (LogisticsPipes.isDEBUG()) {
causedBy.clear();
}
if (getPipe() != null) {
/*
if (getPipe().getDebug() != null && getPipe().getDebug().debugThisPipe) {
Info info = StackTraceUtil.addTraceInformation("(" + getPipe().getX() + ", " + getPipe().getY() + ", " + getPipe().getZ() + ")");
StackTraceUtil.printTrace();
info.end();
}
*/
getPipe().spawnParticle(Particles.LightRedParticle, 5);
}
LPTickHandler.adjChecksDone++;
boolean adjacentChanged = false;
CoreRoutedPipe thisPipe = getPipe();
if (thisPipe == null) {
return false;
}
HashMap<CoreRoutedPipe, ExitRoute> adjacent;
List<Pair<ILogisticsPowerProvider, List<IFilter>>> power;
List<Pair<ISubSystemPowerProvider, List<IFilter>>> subSystemPower;
PathFinder finder = new PathFinder(thisPipe.container, Configs.LOGISTICS_DETECTION_COUNT, Configs.LOGISTICS_DETECTION_LENGTH, localChangeListener);
power = finder.powerNodes;
subSystemPower = finder.subPowerProvider;
adjacent = finder.result;
Map<EnumFacing, List<CoreRoutedPipe>> pipeDirections = new HashMap<>();
for (Entry<CoreRoutedPipe, ExitRoute> entry : adjacent.entrySet()) {
List<CoreRoutedPipe> list = pipeDirections.computeIfAbsent(entry.getValue().exitOrientation, k -> new ArrayList<>());
list.add(entry.getKey());
}
pipeDirections.entrySet().stream().filter(entry -> entry.getValue().size() > Configs.MAX_UNROUTED_CONNECTIONS).forEach(entry -> entry.getValue().forEach(adjacent::remove));
listenedPipes.stream().filter(list -> !finder.listenedPipes.contains(list)).forEach(list -> list.remove(localChangeListener));
listenedPipes = finder.listenedPipes;
for (CoreRoutedPipe pipe : adjacent.keySet()) {
if (pipe.stillNeedReplace()) {
return false;
}
}
boolean[] oldSideDisconnected = sideDisconnected;
sideDisconnected = new boolean[6];
checkSecurity(adjacent);
boolean changed = false;
for (int i = 0; i < 6; i++) {
changed |= sideDisconnected[i] != oldSideDisconnected[i];
}
if (changed) {
CoreRoutedPipe pipe = getPipe();
if (pipe != null) {
pipe.getWorld().markAndNotifyBlock(pipe.getPos(), pipe.getWorld().getChunkFromBlockCoords(pipe.getPos()), pipe.getWorld().getBlockState(pipe.getPos()), pipe.getWorld().getBlockState(pipe.getPos()), 3);
pipe.refreshConnectionAndRender(false);
}
adjacentChanged = true;
}
if (_adjacent.size() != adjacent.size()) {
adjacentChanged = true;
}
for (CoreRoutedPipe pipe : _adjacent.keySet()) {
if (!adjacent.containsKey(pipe)) {
adjacentChanged = true;
break;
}
}
if (_powerAdjacent != null) {
if (power == null) {
adjacentChanged = true;
} else {
for (Pair<ILogisticsPowerProvider, List<IFilter>> provider : _powerAdjacent) {
if (!power.contains(provider)) {
adjacentChanged = true;
break;
}
}
}
}
if (power != null) {
if (_powerAdjacent == null) {
adjacentChanged = true;
} else {
for (Pair<ILogisticsPowerProvider, List<IFilter>> provider : power) {
if (!_powerAdjacent.contains(provider)) {
adjacentChanged = true;
break;
}
}
}
}
if (_subSystemPowerAdjacent != null) {
if (subSystemPower == null) {
adjacentChanged = true;
} else {
for (Pair<ISubSystemPowerProvider, List<IFilter>> provider : _subSystemPowerAdjacent) {
if (!subSystemPower.contains(provider)) {
adjacentChanged = true;
break;
}
}
}
}
if (subSystemPower != null) {
if (_subSystemPowerAdjacent == null) {
adjacentChanged = true;
} else {
for (Pair<ISubSystemPowerProvider, List<IFilter>> provider : subSystemPower) {
if (!_subSystemPowerAdjacent.contains(provider)) {
adjacentChanged = true;
break;
}
}
}
}
for (Entry<CoreRoutedPipe, ExitRoute> pipe : adjacent.entrySet()) {
ExitRoute oldExit = _adjacent.get(pipe.getKey());
if (oldExit == null) {
adjacentChanged = true;
break;
}
ExitRoute newExit = pipe.getValue();
if (!newExit.equals(oldExit)) {
adjacentChanged = true;
break;
}
}
if (!oldTouchedPipes.equals(finder.touchedPipes)) {
CacheHolder.clearCache(oldTouchedPipes);
CacheHolder.clearCache(finder.touchedPipes);
oldTouchedPipes = finder.touchedPipes;
BitSet visited = new BitSet(ServerRouter.getBiggestSimpleID());
visited.set(getSimpleID());
act(visited, new floodClearCache());
}
if (adjacentChanged) {
HashMap<ServerRouter, ExitRoute> adjacentRouter = new HashMap<>();
EnumSet<EnumFacing> routedexits = EnumSet.noneOf(EnumFacing.class);
EnumMap<EnumFacing, Integer> subpowerexits = new EnumMap<>(EnumFacing.class);
for (Entry<CoreRoutedPipe, ExitRoute> pipe : adjacent.entrySet()) {
adjacentRouter.put((ServerRouter) pipe.getKey().getRouter(), pipe.getValue());
if ((pipe.getValue().connectionDetails.contains(PipeRoutingConnectionType.canRouteTo) || pipe.getValue().connectionDetails.contains(PipeRoutingConnectionType.canRequestFrom) && !routedexits.contains(pipe.getValue().exitOrientation))) {
routedexits.add(pipe.getValue().exitOrientation);
}
if (!subpowerexits.containsKey(pipe.getValue().exitOrientation) && pipe.getValue().connectionDetails.contains(PipeRoutingConnectionType.canPowerSubSystemFrom)) {
subpowerexits.put(pipe.getValue().exitOrientation, PathFinder.messureDistanceToNextRoutedPipe(getLPPosition(), pipe.getValue().exitOrientation, pipe.getKey().getWorld()));
}
}
_adjacent = Collections.unmodifiableMap(adjacent);
_adjacentRouter_Old = _adjacentRouter;
_adjacentRouter = Collections.unmodifiableMap(adjacentRouter);
if (power != null) {
_powerAdjacent = Collections.unmodifiableList(power);
} else {
_powerAdjacent = null;
}
if (subSystemPower != null) {
_subSystemPowerAdjacent = Collections.unmodifiableList(subSystemPower);
} else {
_subSystemPowerAdjacent = null;
}
_routedExits = routedexits;
_subPowerExits = subpowerexits;
SendNewLSA();
}
return adjacentChanged;
}
Aggregations