the refactoring continues

This commit is contained in:
Anuken 2022-02-22 13:33:55 -05:00
parent 370191407d
commit d4aff92fda
84 changed files with 337 additions and 268 deletions

View file

@ -89,7 +89,7 @@ public class EntityIO{
st("write.s($L)", revisions.peek().version);
//write uses most recent revision
for(RevisionField field : revisions.peek().fields){
io(field.type, "this." + field.name);
io(field.type, "this." + field.name, false);
}
}else{
//read revision
@ -107,7 +107,7 @@ public class EntityIO{
//add code for reading revision
for(RevisionField field : rev.fields){
//if the field doesn't exist, the result will be an empty string, it won't get assigned
io(field.type, presentFields.contains(field.name) ? "this." + field.name + " = " : "");
io(field.type, presentFields.contains(field.name) ? "this." + field.name + " = " : "", false);
}
}
@ -125,7 +125,7 @@ public class EntityIO{
if(write){
//write uses most recent revision
for(RevisionField field : revisions.peek().fields){
io(field.type, "this." + field.name);
io(field.type, "this." + field.name, true);
}
}else{
Revision rev = revisions.peek();
@ -147,12 +147,12 @@ public class EntityIO{
st(field.name + lastSuf + " = this." + field.name);
}
io(field.type, "this." + (sf ? field.name + targetSuf : field.name) + " = ");
io(field.type, "this." + (sf ? field.name + targetSuf : field.name) + " = ", true);
if(sl){
ncont("else" );
io(field.type, "");
io(field.type, "", true);
//just assign the two values so jumping does not occur on de-possession
if(sf){
@ -217,7 +217,7 @@ public class EntityIO{
econt();
}
private void io(String type, String field) throws Exception{
private void io(String type, String field, boolean network) throws Exception{
type = type.replace("mindustry.gen.", "");
type = replacements.get(type, type);
@ -229,8 +229,8 @@ public class EntityIO{
}else{
st(field + "mindustry.Vars.content.getByID(mindustry.ctype.ContentType.$L, read.s())", BaseProcessor.simpleName(type).toLowerCase().replace("type", ""));
}
}else if(serializer.writers.containsKey(type) && write){
st("$L(write, $L)", serializer.writers.get(type), field);
}else if((serializer.writers.containsKey(type) || (network && serializer.netWriters.containsKey(type))) && write){
st("$L(write, $L)", network ? serializer.getNetWriter(type, null) : serializer.writers.get(type), field);
}else if(serializer.mutatorReaders.containsKey(type) && !write && !field.replace(" = ", "").contains(" ") && !field.isEmpty()){
st("$L$L(read, $L)", field, serializer.mutatorReaders.get(type), field.replace(" = ", ""));
}else if(serializer.readers.containsKey(type) && !write){
@ -241,7 +241,7 @@ public class EntityIO{
if(write){
s("i", field + ".length");
cont("for(int INDEX = 0; INDEX < $L.length; INDEX ++)", field);
io(rawType, field + "[INDEX]");
io(rawType, field + "[INDEX]", network);
}else{
String fieldName = field.replace(" = ", "").replace("this.", "");
String lenf = fieldName + "_LENGTH";
@ -250,7 +250,7 @@ public class EntityIO{
st("$Lnew $L[$L]", field, type.replace("[]", ""), lenf);
}
cont("for(int INDEX = 0; INDEX < $L; INDEX ++)", lenf);
io(rawType, field.replace(" = ", "[INDEX] = "));
io(rawType, field.replace(" = ", "[INDEX] = "), network);
}
econt();
@ -262,7 +262,7 @@ public class EntityIO{
if(write){
s("i", field + ".size");
cont("for(int INDEX = 0; INDEX < $L.size; INDEX ++)", field);
io(generic, field + ".get(INDEX)");
io(generic, field + ".get(INDEX)", network);
}else{
String fieldName = field.replace(" = ", "").replace("this.", "");
String lenf = fieldName + "_LENGTH";
@ -271,7 +271,7 @@ public class EntityIO{
st("$L.clear()", field.replace(" = ", ""));
}
cont("for(int INDEX = 0; INDEX < $L; INDEX ++)", lenf);
io(generic, field.replace(" = ", "_ITEM = ").replace("this.", generic + " "));
io(generic, field.replace(" = ", "_ITEM = ").replace("this.", generic + " "), network);
if(!field.isEmpty()){
String temp = field.replace(" = ", "_ITEM").replace("this.", "");
st("if($L != null) $L.add($L)", temp, field.replace(" = ", ""), temp);

View file

@ -120,7 +120,7 @@ public class CallGenerator{
builder.addStatement("WRITE.$L($L)", typeName.equals("boolean") ? "bool" : typeName.charAt(0) + "", varName);
}else{
//else, try and find a serializer
String ser = serializer.writers.get(typeName.replace("mindustry.gen.", ""), SerializerResolver.locate(ent.element.e, var.mirror(), true));
String ser = serializer.getNetWriter(typeName.replace("mindustry.gen.", ""), SerializerResolver.locate(ent.element.e, var.mirror(), true));
if(ser == null){ //make sure a serializer exists!
BaseProcessor.err("No method to write class type: '" + typeName + "'", var);

View file

@ -16,7 +16,7 @@ public class TypeIOResolver{
* Maps fully qualified class names to their serializers.
*/
public static ClassSerializer resolve(BaseProcessor processor){
ClassSerializer out = new ClassSerializer(new ObjectMap<>(), new ObjectMap<>(), new ObjectMap<>());
ClassSerializer out = new ClassSerializer(new ObjectMap<>(), new ObjectMap<>(), new ObjectMap<>(), new ObjectMap<>());
for(Stype type : processor.types(TypeIOHandler.class)){
//look at all TypeIOHandler methods
Seq<Smethod> methods = type.methods();
@ -25,7 +25,10 @@ public class TypeIOResolver{
Seq<Svar> params = meth.params();
//2 params, second one is type, first is writer
if(params.size == 2 && params.first().tname().toString().equals("arc.util.io.Writes")){
out.writers.put(fix(params.get(1).tname().toString()), type.fullName() + "." + meth.name());
//Net suffix indicates that this should only be used for sync operations
ObjectMap<String, String> targetMap = meth.name().endsWith("Net") ? out.netWriters : out.writers;
targetMap.put(fix(params.get(1).tname().toString()), type.fullName() + "." + meth.name());
}else if(params.size == 1 && params.first().tname().toString().equals("arc.util.io.Reads") && !meth.isVoid()){
//1 param, one is reader, returns type
out.readers.put(fix(meth.retn().toString()), type.fullName() + "." + meth.name());
@ -47,12 +50,17 @@ public class TypeIOResolver{
/** Information about read/write methods for class types. */
public static class ClassSerializer{
public final ObjectMap<String, String> writers, readers, mutatorReaders;
public final ObjectMap<String, String> writers, readers, mutatorReaders, netWriters;
public ClassSerializer(ObjectMap<String, String> writers, ObjectMap<String, String> readers, ObjectMap<String, String> mutatorReaders){
public ClassSerializer(ObjectMap<String, String> writers, ObjectMap<String, String> readers, ObjectMap<String, String> mutatorReaders, ObjectMap<String, String> netWriters){
this.writers = writers;
this.readers = readers;
this.mutatorReaders = mutatorReaders;
this.netWriters = netWriters;
}
public String getNetWriter(String type, String fallback){
return netWriters.get(type, writers.get(type, fallback));
}
}
}

View file

@ -14,7 +14,6 @@ import mindustry.*;
import mindustry.annotations.Annotations.*;
import mindustry.core.GameState.*;
import mindustry.entities.*;
import mindustry.entities.units.*;
import mindustry.game.EventType.*;
import mindustry.game.*;
import mindustry.game.Teams.*;
@ -588,36 +587,6 @@ public class NetClient implements ApplicationListener{
void sync(){
if(timer.get(0, playerSyncTime)){
BuildPlan[] requests = null;
if(player.isBuilder()){
//limit to 10 to prevent buffer overflows
int usedRequests = Math.min(player.unit().plans().size, 10);
int totalLength = 0;
//prevent buffer overflow by checking config length
for(int i = 0; i < usedRequests; i++){
BuildPlan plan = player.unit().plans().get(i);
if(plan.config instanceof byte[] b){
totalLength += b.length;
}
if(plan.config instanceof String b){
totalLength += b.length();
}
if(totalLength > 500){
usedRequests = i + 1;
break;
}
}
requests = new BuildPlan[usedRequests];
for(int i = 0; i < usedRequests; i++){
requests[i] = player.unit().plans().get(i);
}
}
Unit unit = player.dead() ? Nulls.unit : player.unit();
int uid = player.dead() ? -1 : unit.id;
@ -632,7 +601,7 @@ public class NetClient implements ApplicationListener{
unit.vel.x, unit.vel.y,
player.unit().mineTile,
player.boosting, player.shooting, ui.chatfrag.shown(), control.input.isBuilding,
requests,
player.isBuilder() ? player.unit().plans : null,
Core.camera.position.x, Core.camera.position.y,
Core.camera.width, Core.camera.height
);

View file

@ -14,8 +14,8 @@ import mindustry.annotations.Annotations.*;
import mindustry.content.*;
import mindustry.core.GameState.*;
import mindustry.entities.units.*;
import mindustry.game.EventType.*;
import mindustry.game.*;
import mindustry.game.EventType.*;
import mindustry.game.Teams.*;
import mindustry.gen.*;
import mindustry.graphics.*;
@ -628,7 +628,7 @@ public class NetServer implements ApplicationListener{
float xVelocity, float yVelocity,
Tile mining,
boolean boosting, boolean shooting, boolean chatting, boolean building,
@Nullable BuildPlan[] requests,
@Nullable Queue<BuildPlan> plans,
float viewX, float viewY, float viewWidth, float viewHeight
){
NetConnection con = player.con;
@ -675,8 +675,8 @@ public class NetServer implements ApplicationListener{
player.unit().clearBuilding();
player.unit().updateBuilding(building);
if(requests != null){
for(BuildPlan req : requests){
if(plans != null){
for(BuildPlan req : plans){
if(req == null) continue;
Tile tile = world.tile(req.x, req.y);
if(tile == null || (!req.breaking && req.block == null)) continue;
@ -1049,7 +1049,6 @@ public class NetServer implements ApplicationListener{
if(Groups.player.size() > 0 && Core.settings.getBool("blocksync") && timer.get(timerBlockSync, blockSyncTime)){
writeBlockSnapshots();
}
}catch(IOException e){
Log.err(e);
}

View file

@ -183,7 +183,7 @@ abstract class BuilderComp implements Posc, Statusc, Teamc, Rotc{
Draw.reset();
Draw.mixcol(Color.white, 0.24f + Mathf.absin(Time.globalTime, 6f, 0.28f));
Draw.alpha(alpha);
request.block.drawRequestConfigTop(request, plans);
request.block.drawPlanConfigTop(request, plans);
}
}

View file

@ -73,6 +73,9 @@ abstract class BuildingComp implements Posc, Teamc, Healthc, Buildingc, Timerc,
transient boolean wasVisible; //used only by the block renderer when fog is on
transient float visualLiquid;
//TODO save efficiency too!
transient boolean consValid;
@Nullable PowerModule power;
@Nullable ItemModule items;
@Nullable LiquidModule liquids;
@ -80,7 +83,6 @@ abstract class BuildingComp implements Posc, Teamc, Healthc, Buildingc, Timerc,
public transient float healSuppressionTime = -1f;
public transient float lastHealTime = -120f * 10f;
private transient boolean consValid;
private transient float timeScale = 1f, timeScaleDuration;
private transient float dumpAccum;
@ -488,7 +490,7 @@ abstract class BuildingComp implements Posc, Teamc, Healthc, Buildingc, Timerc,
return BlockStatus.noOutput;
}
if(!consValid() || !productionValid()){
if(!consValid || !productionValid()){
return BlockStatus.noInput;
}
@ -1583,16 +1585,12 @@ abstract class BuildingComp implements Posc, Teamc, Healthc, Buildingc, Timerc,
}
}
//TODO
//TODO remove
public float efficiency(){
return efficiency;
}
//TODO probably should not have a shouldConsume() check?
public boolean consValid(){
return consValid && shouldConsume();
}
//TODO probably should not have a shouldConsume() check? should you even *use* consValid?
public void consume(){
for(Consume cons : block.consumers){
@ -1618,6 +1616,9 @@ abstract class BuildingComp implements Posc, Teamc, Healthc, Buildingc, Timerc,
/** Base efficiency. If this entity has non-buffered power, returns the power %, otherwise returns 1. */
private transient float efficiency = 1f;
//why?
transient float efficiencyMultiplier = 1f;
//TODO remove?
@Deprecated
private transient boolean consOptionalValid = false;
@ -1681,9 +1682,13 @@ abstract class BuildingComp implements Posc, Teamc, Healthc, Buildingc, Timerc,
//TODO test with overdraw, e.g. requesting 20/frame on a block with only 10 capacity
//- should lead to 50% efficiency, for example - make sure all blocks have, at minimum, 10x their capacity per frame - should last for a second at least
public void updateEfficiencyMultiplier(){
}
public void updateConsumption(){
//everything is valid when cheating
if(cheating()){
if(cheating() || !block.hasConsumers){
consValid = true;
consOptionalValid = true;
return;
@ -1706,6 +1711,7 @@ abstract class BuildingComp implements Posc, Teamc, Healthc, Buildingc, Timerc,
//assume efficiency is 1 for the calculations below
efficiency = 1f;
//average
//first pass: get the minimum efficiency of any consumer
for(var cons : nonOptional){
@ -1713,8 +1719,13 @@ abstract class BuildingComp implements Posc, Teamc, Healthc, Buildingc, Timerc,
//consValid &= cons.valid(self());
}
efficiencyMultiplier = 1f;
updateEfficiencyMultiplier();
//efficiency is now this minimum value
efficiency = minEfficiency;
consValid = efficiency > 0;
//second pass: update every consumer based on efficiency

View file

@ -244,20 +244,20 @@ public class Schematics implements Loadable{
Draw.rect(Tmp.tr1, buffer.getWidth()/2f, buffer.getHeight()/2f, buffer.getWidth(), -buffer.getHeight());
Draw.color();
Seq<BuildPlan> requests = schematic.tiles.map(t -> new BuildPlan(t.x, t.y, t.rotation, t.block, t.config));
Seq<BuildPlan> plans = schematic.tiles.map(t -> new BuildPlan(t.x, t.y, t.rotation, t.block, t.config));
Draw.flush();
//scale each request to fit schematic
Draw.trans().scale(resolution / tilesize, resolution / tilesize).translate(tilesize*1.5f, tilesize*1.5f);
//draw requests
requests.each(req -> {
plans.each(req -> {
req.animScale = 1f;
req.worldContext = false;
req.block.drawRequestRegion(req, requests);
req.block.drawPlanRegion(req, plans);
});
requests.each(req -> req.block.drawRequestConfigTop(req, requests));
plans.each(req -> req.block.drawPlanConfigTop(req, plans));
Draw.flush();
Draw.trans().idt();

View file

@ -196,7 +196,7 @@ public class SectorInfo{
var pads = indexer.getFlagged(state.rules.defaultTeam, BlockFlag.launchPad);
//disable export when launch pads are disabled, or there aren't any active ones
if(pads.size == 0 || !pads.contains(t -> t.consValid())){
if(pads.size == 0 || !pads.contains(t -> t.consValid)){
export.clear();
}

View file

@ -202,10 +202,10 @@ public class DesktopInput extends InputHandler{
//draw schematic requests
selectRequests.each(req -> {
req.animScale = 1f;
drawRequest(req);
drawPlan(req);
});
selectRequests.each(this::drawOverRequest);
selectRequests.each(this::drawOverPlan);
if(player.isBuilder()){
//draw things that may be placed soon
@ -215,23 +215,23 @@ public class DesktopInput extends InputHandler{
if(i == lineRequests.size - 1 && req.block.rotate){
drawArrow(block, req.x, req.y, req.rotation);
}
drawRequest(lineRequests.get(i));
drawPlan(lineRequests.get(i));
}
lineRequests.each(this::drawOverRequest);
lineRequests.each(this::drawOverPlan);
}else if(isPlacing()){
if(block.rotate && block.drawArrow){
drawArrow(block, cursorX, cursorY, rotation);
}
Draw.color();
boolean valid = validPlace(cursorX, cursorY, block, rotation);
drawRequest(cursorX, cursorY, block, rotation);
drawPlan(cursorX, cursorY, block, rotation);
block.drawPlace(cursorX, cursorY, rotation, valid);
if(block.saveConfig){
Draw.mixcol(!valid ? Pal.breakInvalid : Color.white, (!valid ? 0.4f : 0.24f) + Mathf.absin(Time.globalTime, 6f, 0.28f));
brequest.set(cursorX, cursorY, rotation, block);
brequest.config = block.lastConfig;
block.drawRequestConfig(brequest, allRequests());
block.drawPlanConfig(brequest, allRequests());
brequest.config = null;
Draw.reset();
}

View file

@ -952,22 +952,22 @@ public abstract class InputHandler implements InputProcessor, GestureListener{
}
}
protected void drawOverRequest(BuildPlan request){
protected void drawOverPlan(BuildPlan request){
boolean valid = validPlace(request.x, request.y, request.block, request.rotation);
Draw.reset();
Draw.mixcol(!valid ? Pal.breakInvalid : Color.white, (!valid ? 0.4f : 0.24f) + Mathf.absin(Time.globalTime, 6f, 0.28f));
Draw.alpha(1f);
request.block.drawRequestConfigTop(request, allSelectLines);
request.block.drawPlanConfigTop(request, allSelectLines);
Draw.reset();
}
protected void drawRequest(BuildPlan request){
protected void drawPlan(BuildPlan request){
request.block.drawPlan(request, allRequests(), validPlace(request.x, request.y, request.block, request.rotation));
}
/** Draws a placement icon for a specific block. */
protected void drawRequest(int x, int y, Block block, int rotation){
protected void drawPlan(int x, int y, Block block, int rotation){
brequest.set(x, y, rotation, block);
brequest.animScale = 1f;
block.drawPlan(brequest, allRequests(), validPlace(x, y, block, rotation));

View file

@ -327,7 +327,7 @@ public class MobileInput extends InputHandler implements GestureListener{
request.block.drawPlan(request, allRequests(), validPlace(request.x, request.y, request.block, request.rotation) && getRequest(request.x, request.y, request.block.size, null) == null);
drawSelected(request.x, request.y, request.block, Pal.accent);
}
lineRequests.each(this::drawOverRequest);
lineRequests.each(this::drawOverPlan);
}else if(mode == breaking){
drawBreakSelection(lineStartX, lineStartY, tileX, tileY);
}
@ -367,9 +367,9 @@ public class MobileInput extends InputHandler implements GestureListener{
}
Draw.reset();
drawRequest(request);
drawPlan(request);
if(!request.breaking){
drawOverRequest(request);
drawOverPlan(request);
}
//draw last placed request
@ -399,7 +399,7 @@ public class MobileInput extends InputHandler implements GestureListener{
}
@Override
protected void drawRequest(BuildPlan request){
protected void drawPlan(BuildPlan request){
if(request.tile() == null) return;
brequest.animScale = request.animScale = Mathf.lerpDelta(request.animScale, 1f, 0.1f);

View file

@ -310,18 +310,63 @@ public class TypeIO{
return content.block(read.s());
}
public static void writeRequest(Writes write, BuildPlan request){
write.b(request.breaking ? (byte)1 : 0);
write.i(Point2.pack(request.x, request.y));
if(!request.breaking){
write.s(request.block.id);
write.b((byte)request.rotation);
write.b(1); //always has config
writeObject(write, request.config);
/** @return the maximum acceptable amount of plans to send over the network */
public static int getMaxPlans(Queue<BuildPlan> plans){
//limit to 10 to prevent buffer overflows
int usedRequests = Math.min(plans.size, 10);
int totalLength = 0;
//prevent buffer overflow by checking config length
for(int i = 0; i < usedRequests; i++){
BuildPlan plan = plans.get(i);
if(plan.config instanceof byte[] b){
totalLength += b.length;
}
if(plan.config instanceof String b){
totalLength += b.length();
}
if(totalLength > 500){
usedRequests = i + 1;
break;
}
}
return usedRequests;
}
//on the network, plans must be capped by size
public static void writePlansQueueNet(Writes write, Queue<BuildPlan> plans){
int used = getMaxPlans(plans);
write.i(used);
for(int i = 0; i < used; i++){
writePlan(write, plans.get(i));
}
}
public static BuildPlan readRequest(Reads read){
public static Queue<BuildPlan> readPlansQueue(Reads read){
int used = read.i();
var out = new Queue<BuildPlan>();
for(int i = 0; i < used; i++){
out.add(readPlan(read));
}
return out;
}
public static void writePlan(Writes write, BuildPlan plan){
write.b(plan.breaking ? (byte)1 : 0);
write.i(Point2.pack(plan.x, plan.y));
if(!plan.breaking){
write.s(plan.block.id);
write.b((byte)plan.rotation);
write.b(1); //always has config
writeObject(write, plan.config);
}
}
public static BuildPlan readPlan(Reads read){
BuildPlan currentRequest;
byte type = read.b();
@ -348,18 +393,18 @@ public class TypeIO{
return currentRequest;
}
public static void writeRequests(Writes write, BuildPlan[] requests){
if(requests == null){
public static void writePlans(Writes write, BuildPlan[] plans){
if(plans == null){
write.s(-1);
return;
}
write.s((short)requests.length);
for(BuildPlan request : requests){
writeRequest(write, request);
write.s((short)plans.length);
for(BuildPlan request : plans){
writePlan(write, request);
}
}
public static BuildPlan[] readRequests(Reads read){
public static BuildPlan[] readPlans(Reads read){
short reqamount = read.s();
if(reqamount == -1){
return null;
@ -367,7 +412,7 @@ public class TypeIO{
BuildPlan[] reqs = new BuildPlan[reqamount];
for(int i = 0; i < reqamount; i++){
BuildPlan request = readRequest(read);
BuildPlan request = readPlan(read);
if(request != null){
reqs[i] = request;
}

View file

@ -295,7 +295,7 @@ public class SectorDamage{
}
//point defense turrets act as flat health right now
if(build.block instanceof PointDefenseTurret && build.consValid()){
if(build.block instanceof PointDefenseTurret && build.consValid){
sumHealth += 150f * build.timeScale();
}

View file

@ -643,18 +643,18 @@ public class Block extends UnlockableContent implements Senseable{
Draw.alpha(alpha);
float prevScale = Draw.scl;
Draw.scl *= plan.animScale;
drawRequestRegion(plan, list);
drawPlanRegion(plan, list);
Draw.scl = prevScale;
Draw.reset();
}
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
drawDefaultRequestRegion(plan, list);
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
drawDefaultPlanRegion(plan, list);
}
/** this is a different method so subclasses can call it even after overriding the base */
public void drawDefaultRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
TextureRegion reg = getRequestRegion(plan, list);
public void drawDefaultPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
TextureRegion reg = getPlanRegion(plan, list);
Draw.rect(reg, plan.drawx(), plan.drawy(), !rotate || !rotateDraw ? 0 : plan.rotation * 90);
if(plan.worldContext && player != null && teamRegion != null && teamRegion.found()){
@ -663,18 +663,18 @@ public class Block extends UnlockableContent implements Senseable{
Draw.color();
}
drawRequestConfig(plan, list);
drawPlanConfig(plan, list);
}
public TextureRegion getRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public TextureRegion getPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
return fullIcon;
}
public void drawRequestConfig(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanConfig(BuildPlan plan, Eachable<BuildPlan> list){
}
public void drawRequestConfigCenter(BuildPlan plan, Object content, String region, boolean cross){
public void drawPlanConfigCenter(BuildPlan plan, Object content, String region, boolean cross){
if(content == null){
if(cross){
Draw.rect("cross", plan.drawx(), plan.drawy());
@ -689,11 +689,11 @@ public class Block extends UnlockableContent implements Senseable{
Draw.color();
}
public void drawRequestConfigCenter(BuildPlan plan, Object content, String region){
drawRequestConfigCenter(plan, content, region, false);
public void drawPlanConfigCenter(BuildPlan plan, Object content, String region){
drawPlanConfigCenter(plan, content, region, false);
}
public void drawRequestConfigTop(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanConfigTop(BuildPlan plan, Eachable<BuildPlan> list){
}

View file

@ -56,7 +56,7 @@ public class Accelerator extends Block{
@Override
public void updateTile(){
super.updateTile();
heat = Mathf.lerpDelta(heat, consValid() ? 1f : 0f, 0.05f);
heat = Mathf.lerpDelta(heat, consValid ? 1f : 0f, 0.05f);
statusLerp = Mathf.lerpDelta(statusLerp, power.status, 0.05f);
}
@ -101,14 +101,14 @@ public class Accelerator extends Block{
@Override
public Cursor getCursor(){
return !state.isCampaign() || !consValid() ? SystemCursor.arrow : super.getCursor();
return !state.isCampaign() || !consValid ? SystemCursor.arrow : super.getCursor();
}
@Override
public void buildConfiguration(Table table){
deselect();
if(!state.isCampaign() || !consValid()) return;
if(!state.isCampaign() || !consValid) return;
ui.planet.showPlanetLaunch(state.rules.sector, sector -> {
//TODO cutscene, etc...

View file

@ -126,7 +126,7 @@ public class LaunchPad extends Block{
if(!state.isCampaign()) return;
//increment launchCounter then launch when full and base conditions are met
if((launchCounter += edelta()) >= launchTime && consValid() && items.total() >= itemCapacity){
if((launchCounter += edelta()) >= launchTime && consValid && items.total() >= itemCapacity){
//if there are item requirements, use those.
consume();
launchSound.at(x, y);

View file

@ -241,7 +241,7 @@ public class BuildTurret extends BaseTurret{
super.write(write);
write.f(rotation);
//TODO queue can be very large due to logic?
TypeIO.writeRequests(write, unit.plans().toArray(BuildPlan.class));
TypeIO.writePlans(write, unit.plans().toArray(BuildPlan.class));
}
@Override
@ -250,7 +250,7 @@ public class BuildTurret extends BaseTurret{
rotation = read.f();
unit.rotation(rotation);
unit.plans().clear();
var reqs = TypeIO.readRequests(read);
var reqs = TypeIO.readPlans(read);
if(reqs != null){
for(var req : reqs){
unit.plans().add(req);

View file

@ -51,7 +51,7 @@ public class Door extends Wall{
}
@Override
public TextureRegion getRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public TextureRegion getPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
return plan.config == Boolean.TRUE ? openRegion : region;
}

View file

@ -148,7 +148,7 @@ public class ForceProjector extends Block{
@Override
public void updateTile(){
boolean phaseValid = itemConsumer != null && itemConsumer.valid(this);
boolean phaseValid = itemConsumer != null && itemConsumer.efficiency(this) > 0;
phaseHeat = Mathf.lerpDelta(phaseHeat, Mathf.num(phaseValid), 0.1f);
@ -169,7 +169,7 @@ public class ForceProjector extends Block{
//TODO I hate this system
if(coolantConsumer != null){
if(coolantConsumer.valid(this)){
if(coolantConsumer.efficiency(this) > 0){
coolantConsumer.update(this);
scale *= (cooldownLiquid * (1f + (liquids.current().heatCapacity - 0.4f) * 0.9f));
}

View file

@ -79,7 +79,7 @@ public class MendProjector extends Block{
boolean canHeal = !checkSuppression();
smoothEfficiency = Mathf.lerpDelta(smoothEfficiency, efficiency(), 0.08f);
heat = Mathf.lerpDelta(heat, consValid() && canHeal ? 1f : 0f, 0.08f);
heat = Mathf.lerpDelta(heat, consValid && canHeal ? 1f : 0f, 0.08f);
charge += heat * delta();
phaseHeat = Mathf.lerpDelta(phaseHeat, Mathf.num(consOptionalValid()), 0.1f);

View file

@ -98,7 +98,7 @@ public class OverdriveProjector extends Block{
@Override
public void updateTile(){
smoothEfficiency = Mathf.lerpDelta(smoothEfficiency, efficiency(), 0.08f);
heat = Mathf.lerpDelta(heat, consValid() ? 1f : 0f, 0.08f);
heat = Mathf.lerpDelta(heat, consValid ? 1f : 0f, 0.08f);
charge += heat * Time.delta;
if(hasBoost){
@ -112,13 +112,13 @@ public class OverdriveProjector extends Block{
indexer.eachBlock(this, realRange, other -> other.block.canOverdrive, other -> other.applyBoost(realBoost(), reload + 1f));
}
if(timer(timerUse, useTime) && efficiency() > 0 && consValid()){
if(timer(timerUse, useTime) && efficiency() > 0 && consValid){
consume();
}
}
public float realBoost(){
return consValid() ? (speedBoost + phaseHeat * speedBoostPhase) * efficiency() : 0f;
return consValid ? (speedBoost + phaseHeat * speedBoostPhase) * efficiency() : 0f;
}
@Override

View file

@ -62,7 +62,7 @@ public class RegenProjector extends Block{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
drawer.drawPlan(this, plan, list);
}
@ -112,7 +112,7 @@ public class RegenProjector extends Block{
}
//TODO should warmup depend on didRegen?
warmup = Mathf.approachDelta(warmup, consValid() && didRegen ? 1f : 0f, 1f / 70f);
warmup = Mathf.approachDelta(warmup, consValid && didRegen ? 1f : 0f, 1f / 70f);
totalTime += warmup * Time.delta;
didRegen = false;
@ -121,7 +121,7 @@ public class RegenProjector extends Block{
return;
}
if(consValid()){
if(consValid){
if(consOptionalValid() && (optionalTimer += Time.delta) >= optionalUseTime){
consume();
optionalUseTime = 0f;

View file

@ -15,7 +15,7 @@ public class Thruster extends Wall{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(topRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
}

View file

@ -41,21 +41,18 @@ public class ContinuousLiquidTurret extends ContinuousTurret{
public void init(){
//TODO display ammoMultiplier.
consume(new ConsumeLiquidFilter(i -> ammoTypes.containsKey(i), liquidConsumed){
@Override
public boolean valid(Building build){
return build.liquids.currentAmount() >= use(build);
}
@Override
public void display(Stats stats){
}
@Override
protected float use(Building entity){
BulletType type = ammoTypes.get(entity.liquids.current());
return Math.min(amount * entity.edelta(), entity.block.liquidCapacity) / (type == null ? 1f : type.ammoMultiplier);
}
//TODO
//@Override
//protected float use(Building entity){
// BulletType type = ammoTypes.get(entity.liquids.current());
// return Math.min(amount * entity.edelta(), entity.block.liquidCapacity) / (type == null ? 1f : type.ammoMultiplier);
//}
});
super.init();

View file

@ -69,9 +69,9 @@ public class ItemTurret extends Turret{
}
@Override
public boolean valid(Building build){
public float efficiency(Building build){
//valid when there's any ammo in the turret
return build instanceof ItemTurretBuild it && !it.ammo.isEmpty();
return build instanceof ItemTurretBuild it && !it.ammo.isEmpty() ? 1f : 0f;
}
@Override

View file

@ -93,7 +93,7 @@ public class LaserTurret extends PowerTurret{
return;
}
if(reload <= 0 && (consValid() || cheating()) && !charging && shootWarmup >= minWarmup){
if(reload <= 0 && (consValid || cheating()) && !charging && shootWarmup >= minWarmup){
BulletType type = peekAmmo();
shoot(type);

View file

@ -69,9 +69,9 @@ public class PayloadTurret extends Turret{
}
@Override
public boolean valid(Building build){
public float efficiency(Building build){
//valid when there's any ammo in the turret
return build instanceof PayloadTurretBuild it && it.payloads.any();
return build instanceof PayloadTurretBuild it && it.payloads.any() ? 1f : 0f;
}
@Override

View file

@ -66,7 +66,7 @@ public class Conveyor extends Block implements Autotiler{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
int[] bits = getTiling(plan, list);
if(bits == null) return;

View file

@ -48,13 +48,13 @@ public class DirectionBridge extends Block{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(dirRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
}
@Override
public void drawRequestConfigTop(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanConfigTop(BuildPlan plan, Eachable<BuildPlan> list){
otherReq = null;
otherDst = range;
Point2 d = Geometry.d4(plan.rotation);

View file

@ -47,15 +47,15 @@ public class DirectionalUnloader extends Block{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(topRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
drawRequestConfig(plan, list);
drawPlanConfig(plan, list);
}
@Override
public void drawRequestConfig(BuildPlan plan, Eachable<BuildPlan> list){
drawRequestConfigCenter(plan, plan.config, "duct-unloader-center");
public void drawPlanConfig(BuildPlan plan, Eachable<BuildPlan> list){
drawPlanConfigCenter(plan, plan.config, "duct-unloader-center");
}
@Override

View file

@ -50,7 +50,7 @@ public class Duct extends Block implements Autotiler{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
int[] bits = getTiling(plan, list);
if(bits == null) return;

View file

@ -53,7 +53,7 @@ public class DuctRouter extends Block{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(topRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
}

View file

@ -61,7 +61,7 @@ public class ItemBridge extends Block{
}
@Override
public void drawRequestConfigTop(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanConfigTop(BuildPlan plan, Eachable<BuildPlan> list){
otherReq = null;
list.each(other -> {
if(other.block == this && plan != other && plan.config instanceof Point2 p && p.equals(other.x - plan.x, other.y - plan.y)){

View file

@ -153,7 +153,7 @@ public class MassDriver extends Block{
}
//skip when there's no power
if(!consValid()){
if(!consValid){
return;
}
@ -326,7 +326,7 @@ public class MassDriver extends Block{
}
protected boolean shooterValid(Building other){
return other instanceof MassDriverBuild entity && other.isValid() && other.consValid() && entity.block == block && entity.link == pos() && within(other, range);
return other instanceof MassDriverBuild entity && other.isValid() && other.consValid && entity.block == block && entity.link == pos() && within(other, range);
}
protected boolean linkValid(){

View file

@ -43,7 +43,7 @@ public class OverflowDuct extends Block{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(topRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
}

View file

@ -33,8 +33,8 @@ public class Sorter extends Block{
}
@Override
public void drawRequestConfig(BuildPlan plan, Eachable<BuildPlan> list){
drawRequestConfigCenter(plan, plan.config, "center", true);
public void drawPlanConfig(BuildPlan plan, Eachable<BuildPlan> list){
drawPlanConfigCenter(plan, plan.config, "center", true);
}
@Override

View file

@ -84,7 +84,7 @@ public class StackConveyor extends Block implements Autotiler{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
int[] bits = getTiling(plan, list);
if(bits == null) return;

View file

@ -38,7 +38,7 @@ public class HeatConductor extends Block{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
drawer.drawPlan(this, plan, list);
}

View file

@ -44,7 +44,7 @@ public class HeatProducer extends GenericCrafter{
super.updateTile();
//heat approaches target at the same speed regardless of efficiency
heat = Mathf.approachDelta(heat, heatOutput * efficiency() * Mathf.num(consValid()), warmupRate * delta());
heat = Mathf.approachDelta(heat, heatOutput * efficiency() * Mathf.num(consValid), warmupRate * delta());
}
@Override

View file

@ -97,7 +97,7 @@ public class Conduit extends LiquidBlock implements Autotiler{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
int[] bits = getTiling(plan, list);
if(bits == null) return;

View file

@ -484,7 +484,7 @@ public class LogicBlock extends Block{
}
if(enabled && executor.initialized()){
accumulator += edelta() * ipt * (consValid() ? 1 : 0);
accumulator += edelta() * ipt * (consValid ? 1 : 0);
if(accumulator > maxInstructionScale * ipt) accumulator = maxInstructionScale * ipt;

View file

@ -42,7 +42,7 @@ public abstract class BlockProducer extends PayloadBlock{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(outRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
Draw.rect(topRegion, plan.drawx(), plan.drawy());
@ -88,7 +88,7 @@ public abstract class BlockProducer extends PayloadBlock{
public void updateTile(){
super.updateTile();
var recipe = recipe();
boolean produce = recipe != null && consValid() && payload == null;
boolean produce = recipe != null && consValid && payload == null;
if(produce){
progress += buildSpeed * edelta();

View file

@ -60,7 +60,7 @@ public class PayloadLoader extends PayloadBlock{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(inRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
Draw.rect(outRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);

View file

@ -88,7 +88,7 @@ public class PayloadMassDriver extends PayloadBlock{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(baseRegion, plan.drawx(), plan.drawy());
Draw.rect(topRegion, plan.drawx(), plan.drawy());
Draw.rect(outRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
@ -188,7 +188,7 @@ public class PayloadMassDriver extends PayloadBlock{
!(
current instanceof PayloadDriverBuild entity &&
current.isValid() &&
entity.consValid() && entity.block == block &&
entity.consValid && entity.block == block &&
entity.link == pos() && within(current, range)
)){
waitingShooters.removeFirst();
@ -219,7 +219,7 @@ public class PayloadMassDriver extends PayloadBlock{
}
//skip when there's no power
if(!consValid()){
if(!consValid){
return;
}

View file

@ -37,8 +37,8 @@ public class PayloadRouter extends PayloadConveyor{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
super.drawRequestRegion(plan, list);
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
super.drawPlanRegion(plan, list);
Draw.rect(overRegion, plan.drawx(), plan.drawy());
}

View file

@ -66,7 +66,7 @@ public class PayloadSource extends PayloadBlock{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(outRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
Draw.rect(topRegion, plan.drawx(), plan.drawy());

View file

@ -56,7 +56,7 @@ public class PayloadVoid extends PayloadBlock{
@Override
public void updateTile(){
super.updateTile();
if(moveInPayload(false) && consValid()){
if(moveInPayload(false) && consValid){
payload = null;
incinerateEffect.at(this);
incinerateSound.at(this);

View file

@ -70,25 +70,25 @@ public class ConsumeGenerator extends PowerGenerator{
public class ConsumeGeneratorBuild extends GeneratorBuild{
public float warmup, totalTime;
public float itemMultiplier = 1f;
@Override
public void updateEfficiencyMultiplier(){
if(filterItem != null){
float m = filterItem.efficiencyMultiplier(this);
if(m > 0) efficiencyMultiplier = m;
}else if(filterLiquid != null){
float m = filterLiquid.efficiencyMultiplier(this);
if(m > 0) efficiencyMultiplier = m;
}
}
@Override
public void updateTile(){
boolean valid = consValid();
boolean valid = consValid;
warmup = Mathf.lerpDelta(warmup, enabled && valid ? 1f : 0f, 0.05f);
warmup = Mathf.lerpDelta(warmup, valid ? 1f : 0f, 0.05f);
float multiplier = 1f;
if(valid){
if(filterItem != null && filterItem.getConsumed(this) != null){
itemMultiplier = filterItem.efficiency(this);
}
//efficiency is added together
multiplier *= (itemMultiplier + (filterLiquid == null ? 0f : filterLiquid.efficiency(this)));
}
productionEfficiency = (valid ? 1f : 0f) * multiplier;
productionEfficiency = efficiency * efficiencyMultiplier;
totalTime += warmup * Time.delta;
//randomly produce the effect
@ -97,7 +97,7 @@ public class ConsumeGenerator extends PowerGenerator{
}
//take in items periodically
if(hasItems && valid && generateTime <= 0f && items.any()){
if(hasItems && valid && generateTime <= 0f){
consume();
consumeEffect.at(x + Mathf.range(generateEffectRange), y + Mathf.range(generateEffectRange));
generateTime = 1f;
@ -110,7 +110,7 @@ public class ConsumeGenerator extends PowerGenerator{
}
//generation time always goes down, but only at the end so consumeTriggerValid doesn't assume fake items
generateTime -= Math.min(1f / itemDuration * delta(), generateTime);
generateTime -= delta() / itemDuration;
}
@Override

View file

@ -76,7 +76,7 @@ public class ImpactReactor extends PowerGenerator{
@Override
public void updateTile(){
if(consValid() && power.status >= 0.99f){
if(consValid && power.status >= 0.99f){
boolean prevOut = getPowerProduction() <= consPower.requestedPower(this);
warmup = Mathf.lerpDelta(warmup, 1f, warmupSpeed * timeScale);

View file

@ -35,7 +35,7 @@ public class PowerDiode extends Block{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(fullIcon, plan.drawx(), plan.drawy());
Draw.rect(arrow, plan.drawx(), plan.drawy(), !rotate ? 0 : plan.rotation * 90);
}

View file

@ -57,7 +57,7 @@ public class PowerGenerator extends PowerDistributor{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
drawer.drawPlan(this, plan, list);
}

View file

@ -305,7 +305,7 @@ public class PowerNode extends PowerBlock{
}
@Override
public void drawRequestConfigTop(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanConfigTop(BuildPlan plan, Eachable<BuildPlan> list){
if(plan.config instanceof Point2[] ps){
setupColor(1f);
for(Point2 point : ps){

View file

@ -93,7 +93,7 @@ public class BeamDrill extends Block{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(topRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
}
@ -213,7 +213,7 @@ public class BeamDrill extends Block{
if(lasers[0] == null) updateLasers();
warmup = Mathf.approachDelta(warmup, Mathf.num(consValid()), 1f / 60f);
warmup = Mathf.approachDelta(warmup, Mathf.num(consValid), 1f / 60f);
lastItem = null;
boolean multiple = false;
int dx = Geometry.d4x(rotation), dy = Geometry.d4y(rotation), facingAmount = 0;

View file

@ -58,7 +58,7 @@ public class BurstDrill extends Drill{
smoothProgress = Mathf.lerpDelta(smoothProgress, progress / (drillTime - 20f), 0.1f);
if(items.total() <= itemCapacity - dominantItems && dominantItems > 0 && consValid()){
if(items.total() <= itemCapacity - dominantItems && dominantItems > 0 && consValid){
warmup = Mathf.approachDelta(warmup, progress / drillTime, 0.01f);
float speed = efficiency();

View file

@ -86,7 +86,7 @@ public class Drill extends Block{
}
@Override
public void drawRequestConfigTop(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanConfigTop(BuildPlan plan, Eachable<BuildPlan> list){
if(!plan.worldContext) return;
Tile tile = plan.tile();
if(tile == null) return;
@ -273,7 +273,7 @@ public class Drill extends Block{
timeDrilled += warmup * delta();
if(items.total() < itemCapacity && dominantItems > 0 && consValid()){
if(items.total() < itemCapacity && dominantItems > 0 && consValid){
float speed = 1f;

View file

@ -28,7 +28,7 @@ public class Fracker extends SolidPump{
@Override
public void updateTile(){
if(consValid()){
if(consValid){
if(accumulator >= itemUseTime){
consume();
accumulator -= itemUseTime;

View file

@ -119,7 +119,7 @@ public class GenericCrafter extends Block{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
drawer.drawPlan(this, plan, list);
}
@ -187,7 +187,7 @@ public class GenericCrafter extends Block{
@Override
public void updateTile(){
if(consValid()){
if(consValid){
progress += getProgressIncrease(craftTime);
warmup = Mathf.approachDelta(warmup, warmupTarget(), warmupSpeed);
@ -282,7 +282,7 @@ public class GenericCrafter extends Block{
@Override
public boolean shouldAmbientSound(){
return consValid();
return consValid;
}
@Override

View file

@ -28,7 +28,7 @@ public class Incinerator extends Block{
@Override
public void updateTile(){
heat = Mathf.approachDelta(heat, consValid() && efficiency() > 0.9f ? 1f : 0f, 0.04f);
heat = Mathf.approachDelta(heat, consValid && efficiency() > 0.9f ? 1f : 0f, 0.04f);
}
@Override

View file

@ -38,7 +38,7 @@ public class ItemIncinerator extends Block{
@Override
public BlockStatus status(){
return consValid() ? BlockStatus.active : BlockStatus.noInput;
return consValid ? BlockStatus.active : BlockStatus.noInput;
}
@Override
@ -62,7 +62,7 @@ public class ItemIncinerator extends Block{
@Override
public boolean acceptItem(Building source, Item item){
return consValid();
return consValid;
}
}
}

View file

@ -152,7 +152,7 @@ public class Pump extends LiquidBlock{
@Override
public void updateTile(){
if(consValid() && liquidDrop != null){
if(consValid && liquidDrop != null){
float maxPump = Math.min(liquidCapacity - liquids.get(liquidDrop), amount * pumpAmount * edelta());
liquids.add(liquidDrop, maxPump);

View file

@ -64,7 +64,7 @@ public class Separator extends Block{
@Override
public boolean shouldAmbientSound(){
return consValid();
return consValid;
}
@Override
@ -94,7 +94,7 @@ public class Separator extends Block{
public void updateTile(){
totalProgress += warmup * delta();
if(consValid()){
if(consValid){
progress += getProgressIncrease(craftTime);
warmup = Mathf.lerpDelta(warmup, 1f, 0.02f);
}else{

View file

@ -121,7 +121,7 @@ public class SolidPump extends Pump{
public void updateTile(){
float fraction = Math.max(validTiles + boost + (attribute == null ? 0 : attribute.env()), 0);
if(consValid() && typeLiquid() < liquidCapacity - 0.001f){
if(consValid && typeLiquid() < liquidCapacity - 0.001f){
float maxPump = Math.min(liquidCapacity - typeLiquid(), pumpAmount * delta() * fraction * efficiency());
liquids.add(result, maxPump);
lastPump = maxPump / Time.delta;

View file

@ -82,7 +82,7 @@ public class WallCrafter extends Block{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(topRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
}
@ -149,7 +149,7 @@ public class WallCrafter extends Block{
boolean cons = shouldConsume();
warmup = Mathf.approachDelta(warmup, Mathf.num(consValid()), 1f / 40f);
warmup = Mathf.approachDelta(warmup, Mathf.num(consValid), 1f / 40f);
float dx = Geometry.d4x(rotation) * 0.5f, dy = Geometry.d4y(rotation) * 0.5f;
float eff = getEfficiency(tile.x, tile.y, rotation, dest -> {

View file

@ -46,8 +46,8 @@ public class ItemSource extends Block{
}
@Override
public void drawRequestConfig(BuildPlan plan, Eachable<BuildPlan> list){
drawRequestConfigCenter(plan, plan.config, "center", true);
public void drawPlanConfig(BuildPlan plan, Eachable<BuildPlan> list){
drawPlanConfigCenter(plan, plan.config, "center", true);
}
@Override

View file

@ -46,8 +46,8 @@ public class LiquidSource extends Block{
}
@Override
public void drawRequestConfig(BuildPlan plan, Eachable<BuildPlan> list){
drawRequestConfigCenter(plan, plan.config, "center", true);
public void drawPlanConfig(BuildPlan plan, Eachable<BuildPlan> list){
drawPlanConfigCenter(plan, plan.config, "center", true);
}
@Override

View file

@ -47,8 +47,8 @@ public class Unloader extends Block{
}
@Override
public void drawRequestConfig(BuildPlan plan, Eachable<BuildPlan> list){
drawRequestConfigCenter(plan, plan.config, "unloader-center");
public void drawPlanConfig(BuildPlan plan, Eachable<BuildPlan> list){
drawPlanConfigCenter(plan, plan.config, "unloader-center");
}
@Override

View file

@ -37,7 +37,7 @@ public class Reconstructor extends UnitBlock{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(inRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
Draw.rect(outRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
@ -219,7 +219,7 @@ public class Reconstructor extends UnitBlock{
moveOutPayload();
}else{ //update progress
if(moveInPayload()){
if(consValid()){
if(consValid){
valid = true;
progress += edelta() * state.rules.unitBuildSpeed(team);
}

View file

@ -185,7 +185,7 @@ public class RepairPoint extends Block{
boolean healed = false;
if(target != null && consValid()){
if(target != null && consValid){
float angle = Angles.angle(x, y, target.x + offset.x, target.y + offset.y);
if(Angles.angleDist(angle, rotation) < 30f){
healed = true;

View file

@ -106,7 +106,7 @@ public class UnitAssembler extends PayloadBlock{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(plan.rotation >= 2 ? sideRegion2 : sideRegion1, plan.drawx(), plan.drawy(), plan.rotation * 90);
Draw.rect(topRegion, plan.drawx(), plan.drawy());
@ -261,7 +261,7 @@ public class UnitAssembler extends PayloadBlock{
@Override
public boolean shouldConsume(){
//liquid is only consumed when building is being done
return enabled && !wasOccupied && Units.canCreate(team, plan().unit) && consPayload.valid(this);
return enabled && !wasOccupied && Units.canCreate(team, plan().unit) && consPayload.efficiency(this) > 0;
}
@Override
@ -375,7 +375,7 @@ public class UnitAssembler extends PayloadBlock{
var plan = plan();
//check if all requirements are met
if(!wasOccupied && consValid() && Units.canCreate(team, plan.unit)){
if(!wasOccupied && consValid && Units.canCreate(team, plan.unit)){
warmup = Mathf.lerpDelta(warmup, efficiency(), 0.1f);
if((progress += edelta() * eff / plan.time) >= 1f){
@ -523,7 +523,7 @@ public class UnitAssembler extends PayloadBlock{
/** @return true if this block is ready to produce units, e.g. requirements met */
public boolean ready(){
return consValid() && !wasOccupied;
return consValid && !wasOccupied;
}
public void yeetPayload(Payload payload){

View file

@ -44,7 +44,7 @@ public class UnitAssemblerModule extends PayloadBlock{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(plan.rotation >= 2 ? sideRegion2 : sideRegion1, plan.drawx(), plan.drawy(), plan.rotation * 90);
Draw.rect(topRegion, plan.drawx(), plan.drawy());
@ -128,7 +128,7 @@ public class UnitAssemblerModule extends PayloadBlock{
findLink();
}
if(moveInPayload() && link != null && link.moduleFits(block, x, y, rotation) && !link.wasOccupied && link.acceptPayload(this, payload) && consValid()){
if(moveInPayload() && link != null && link.moduleFits(block, x, y, rotation) && !link.wasOccupied && link.acceptPayload(this, payload) && consValid){
link.yeetPayload(payload);
payload = null;
}

View file

@ -125,7 +125,7 @@ public class UnitFactory extends UnitBlock{
}
@Override
public void drawRequestRegion(BuildPlan plan, Eachable<BuildPlan> list){
public void drawPlanRegion(BuildPlan plan, Eachable<BuildPlan> list){
Draw.rect(region, plan.drawx(), plan.drawy());
Draw.rect(outRegion, plan.drawx(), plan.drawy(), plan.rotation * 90);
Draw.rect(topRegion, plan.drawx(), plan.drawy());
@ -244,7 +244,7 @@ public class UnitFactory extends UnitBlock{
currentPlan = -1;
}
if(consValid() && currentPlan != -1){
if(consValid && currentPlan != -1){
time += edelta() * speedScl * Vars.state.rules.unitBuildSpeed(team);
progress += edelta() * Vars.state.rules.unitBuildSpeed(team);
speedScl = Mathf.lerpDelta(speedScl, 1f, 0.05f);
@ -263,7 +263,7 @@ public class UnitFactory extends UnitBlock{
return;
}
if(progress >= plan.time && consValid()){
if(progress >= plan.time && consValid){
progress %= 1f;
Unit unit = plan.unit.create(team);

View file

@ -13,8 +13,7 @@ public abstract class Consume{
public boolean optional;
/** If true, this consumer will be displayed as a boost input. */
public boolean booster;
//TODO bad. I don't like it.
@Deprecated
/** If false, this consumer will still be checked, but it will need to updated manually. */
public boolean update = true;
/**
@ -34,7 +33,6 @@ public abstract class Consume{
return optional(true, true);
}
@Deprecated
public Consume update(boolean update){
this.update = update;
return this;
@ -52,11 +50,16 @@ public abstract class Consume{
public void update(Building build){}
/** @return efficiency multiplier based on input; overridden in subclasses. Returns 0 if not valid in subclasses. Should return fraction if needs are partially met. */
/** @return [0, 1] efficiency multiplier based on input. Returns 0 if not valid in subclasses. Should return fraction if needs are partially met. */
public float efficiency(Building build){
return 1f;
}
/** @return multiplier for efficiency - this can be above 1. Will not influence a building's base efficiency value. */
public float efficiencyMultiplier(Building build){
return 1f;
}
public void display(Stats stats){}
//TODO this should use efficiency instead - remove or deprecate

View file

@ -14,7 +14,8 @@ public class ConsumeItemCharged extends ConsumeItemFilter{
}
@Override
public float efficiency(Building build){
public float efficiencyMultiplier(Building build){
if(build.consumeTriggerValid()) return 1f;
var item = getConsumed(build);
return item == null ? 0f : item.charge;
}

View file

@ -13,7 +13,9 @@ public class ConsumeItemFlammable extends ConsumeItemFilter{
}
@Override
public float efficiency(Building build){
public float efficiencyMultiplier(Building build){
//TODO ugh
if(build.consumeTriggerValid()) return 1f;
var item = getConsumed(build);
return item == null ? 0f : item.flammability;
}

View file

@ -13,7 +13,8 @@ public class ConsumeItemRadioactive extends ConsumeItemFilter{
}
@Override
public float efficiency(Building build){
public float efficiencyMultiplier(Building build){
if(build.consumeTriggerValid()) return 1f;
var item = getConsumed(build);
return item == null ? 0f : item.radioactivity;
}

View file

@ -42,8 +42,7 @@ public class ConsumeLiquidFilter extends ConsumeLiquidBase{
@Override
public void update(Building build){
Liquid liq = getConsumed(build);
build.liquids.remove(liq, amount * build.edelta());
build.liquids.remove(getConsumed(build), amount * build.edelta());
}
@Override

View file

@ -13,8 +13,8 @@ public class ConsumeLiquidFlammable extends ConsumeLiquidFilter{
}
@Override
public float efficiency(Building build){
var item = getConsumed(build);
return item == null ? 0f : item.flammability * super.efficiency(build);
public float efficiencyMultiplier(Building build){
var liq = getConsumed(build);
return liq == null ? 0f : liq.flammability;
}
}

View file

@ -35,7 +35,7 @@ public class ConsumeLiquids extends Consume{
int i = 0;
for(var stack : liquids){
c.add(new ReqImage(stack.liquid.uiIcon,
() -> build.liquids.get(stack.liquid) >= stack.amount * build.delta())).size(Vars.iconMed).padRight(8);
() -> build.liquids.get(stack.liquid) > 0)).size(Vars.iconMed).padRight(8);
if(++i % 4 == 0) c.row();
}
}).left();
@ -44,13 +44,12 @@ public class ConsumeLiquids extends Consume{
@Override
public void update(Building build){
for(var stack : liquids){
build.liquids.remove(stack.liquid, Math.min(use(stack.amount, build), build.liquids.get(stack.liquid)));
build.liquids.remove(stack.liquid, stack.amount * build.edelta());
}
}
@Override
public float efficiency(Building build){
//TODO delta or edelta
float min = 1f, delta = build.edelta();
for(var stack : liquids){
min = Math.min(build.liquids.get(stack.liquid) / (stack.amount * delta), min);
@ -63,7 +62,4 @@ public class ConsumeLiquids extends Consume{
stats.add(booster ? Stat.booster : Stat.input, StatValues.liquids(1f, true, liquids));
}
protected float use(float amount, Building build){
return Math.min(amount * build.edelta(), build.block.liquidCapacity);
}
}

View file

@ -34,7 +34,7 @@ public class DrawBlock{
/** Draws the planned version of this block. */
public void drawPlan(Block block, BuildPlan plan, Eachable<BuildPlan> list){
block.drawDefaultRequestRegion(plan, list);
block.drawDefaultPlanRegion(plan, list);
}
/** Load any relevant texture regions. */

View file

@ -25,6 +25,9 @@ public class ItemModule extends BlockModule{
protected int total;
protected int takeRotation;
/** A value >0 in an index array indicates that a corresponding item is currently being consumed. 1 indicates an entire item. */
public float[] itemConsumption = new float[items.length];
private @Nullable WindowedMean[] flow;
public ItemModule copy(){

View file

@ -24,4 +24,4 @@ android.useAndroidX=true
#used for slow jitpack builds; TODO see if this actually works
org.gradle.internal.http.socketTimeout=100000
org.gradle.internal.http.connectionTimeout=100000
archash=01ac479043
archash=6fb037d33e

View file

@ -1,5 +1,6 @@
package power;
import arc.struct.*;
import arc.util.*;
import mindustry.*;
import mindustry.content.*;
@ -27,7 +28,7 @@ public class ConsumeGeneratorTests extends PowerTestFixture{
private Tile tile;
private ConsumeGeneratorBuild build;
private final float fakeItemDuration = 60f; //ticks
private final float maximumLiquidUsage = 0.5f;
private final float maximumLiquidUsage = 1f;
public void createGenerator(InputType inputType){
Vars.state = new GameState();
@ -36,6 +37,7 @@ public class ConsumeGeneratorTests extends PowerTestFixture{
powerProduction = 0.1f;
itemDuration = fakeItemDuration;
buildType = ConsumeGeneratorBuild::new;
liquidCapacity = 100f;
if(inputType != InputType.liquids){
consume(new ConsumeItemFlammable());
@ -51,6 +53,20 @@ public class ConsumeGeneratorTests extends PowerTestFixture{
build = (ConsumeGeneratorBuild)tile.build;
}
//require = 1
//provided = 0.25
//delta = 0.5 (half speed)
//scaled requirement = 1 * 0.5 = 0.5
//efficiency = provided / required = 0.25 / 0.5 = 0.5
//-> ???
//require = 1
//provided = 0.25
//delta = 1 (full speed)
//scaled requirement = 1 * 1 = 1
//efficiency = provided / required = 0.25
//-> makes sense, you're running at double speed without doubling input
/** Tests the consumption and efficiency when being supplied with liquids. */
@TestFactory
DynamicTest[] generatorWorksProperlyWithLiquidInput(){
@ -61,36 +77,54 @@ public class ConsumeGeneratorTests extends PowerTestFixture{
//InputType.any
};
ArrayList<DynamicTest> tests = new ArrayList<>();
for(InputType inputType : inputTypesToBeTested){
tests.add(dynamicTest("01", () -> simulateLiquidConsumption(inputType, Liquids.oil, 0.0f, "No liquids provided")));
tests.add(dynamicTest("02", () -> simulateLiquidConsumption(inputType, Liquids.oil, maximumLiquidUsage / 4.0f, "Low oil provided")));
tests.add(dynamicTest("03", () -> simulateLiquidConsumption(inputType, Liquids.oil, maximumLiquidUsage * 1.0f, "Sufficient oil provided")));
tests.add(dynamicTest("04", () -> simulateLiquidConsumption(inputType, Liquids.oil, maximumLiquidUsage * 2.0f, "Excess oil provided")));
// Note: The generator will decline any other liquid since it's not flammable
//TODO test with different delta values.
Seq<DynamicTest> tests = new Seq<>();
float[] deltas = {2f, 1f, 0.5f};
for(float d : deltas){
for(InputType inputType : inputTypesToBeTested){
tests.add(dynamicTest("01-delta" + d, () -> simulateLiquidConsumption(d, inputType, Liquids.oil, 0.0f, "No liquids provided")));
tests.add(dynamicTest("02-delta" + d, () -> simulateLiquidConsumption(d, inputType, Liquids.oil, maximumLiquidUsage / 4.0f, "Low oil provided")));
tests.add(dynamicTest("03-delta" + d, () -> simulateLiquidConsumption(d, inputType, Liquids.oil, maximumLiquidUsage * 1.0f, "Sufficient oil provided")));
tests.add(dynamicTest("04-delta" + d, () -> simulateLiquidConsumption(d, inputType, Liquids.oil, maximumLiquidUsage * 2.0f, "Excess oil provided")));
// Note: The generator will decline any other liquid since it's not flammable
}
}
DynamicTest[] testArray = new DynamicTest[tests.size()];
testArray = tests.toArray(testArray);
return testArray;
return tests.toArray(DynamicTest.class);
}
void simulateLiquidConsumption(InputType inputType, Liquid liquid, float availableLiquidAmount, String parameterDescription){
final float baseEfficiency = liquid.flammability;
final float expectedEfficiency = Math.min(1.0f, availableLiquidAmount / maximumLiquidUsage) * baseEfficiency;
final float expectedConsumptionPerTick = Math.min(maximumLiquidUsage, availableLiquidAmount);
final float expectedRemainingLiquidAmount = Math.max(0.0f, availableLiquidAmount - expectedConsumptionPerTick * Time.delta);
void simulateLiquidConsumption(float delta, InputType inputType, Liquid liquid, float availableLiquidAmount, String parameterDescription){
Time.setDeltaProvider(() -> delta);
float expectedConsumptionPerTick = Math.min(maximumLiquidUsage * Time.delta, availableLiquidAmount);
float expectedEfficiency = expectedConsumptionPerTick / (maximumLiquidUsage * Time.delta);
float expectedOutputEfficiency = expectedEfficiency * liquid.flammability;
//it should either consume:
//- the maximum amount used (maximumLiquidUsage) multiplied by speed (delta), or
//- the maximum available amount (availableLiquidAmount), since that's a hard cap
float expectedRemainingLiquidAmount = Math.max(0.0f, availableLiquidAmount - expectedConsumptionPerTick);
createGenerator(inputType);
assertTrue(build.acceptLiquid(null, liquid), inputType + " | " + parameterDescription + ": Liquids which will be declined by the generator don't need to be tested - The code won't be called for those cases.");
build.liquids.add(liquid, availableLiquidAmount);
//Placed:
//frame 0: run generator code, multiplier is set but nothing is valid so this is used
//- consumption code runs and consumes
//frame 1: efficiency is now 1, but the liquid filter consumer isn't valid anymore.
build.updateConsumption();
// Perform an update on the generator once - This should use up any resource up to the maximum liquid usage
build.updateTile();
build.update();
//reset
Time.setDeltaProvider(() -> 0.5f);
assertEquals(expectedEfficiency, build.efficiency(), inputType + " | " + parameterDescription + ": Base input efficiency mismatch.");
assertEquals(expectedRemainingLiquidAmount, build.liquids.get(liquid), inputType + " | " + parameterDescription + ": Remaining liquid amount mismatch.");
assertEquals(expectedEfficiency, build.productionEfficiency, inputType + " | " + parameterDescription + ": Efficiency mismatch.");
assertEquals(expectedOutputEfficiency, build.productionEfficiency, inputType + " | " + parameterDescription + ": Output production efficiency mismatch.");
}
/** Tests the consumption and efficiency when being supplied with items. */
@ -153,6 +187,7 @@ public class ConsumeGeneratorTests extends PowerTestFixture{
// Burn a single coal and test for the duration
build.items.add(Items.coal, 1);
//first frame update for some setup (consume checking is delayed)
build.update();
float expectedEfficiency = build.productionEfficiency;

View file

@ -133,7 +133,7 @@ public class PowerTests extends PowerTestFixture{
assertEquals(0.0f, consumerTile.build.power.status, Mathf.FLOAT_ROUNDING_ERROR);
if(consumerTile.block().consPower != null){
assertFalse(consumerTile.block().consPower.valid(consumerTile.build));
assertEquals(0f, consumerTile.block().consPower.efficiency(consumerTile.build));
}
}
}