aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/common/tileentities/GTMTE_LapotronicSuperCapacitor.java
blob: b499e4a941462863caa4e56b0a9f30fb7b879f64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package common.tileentities;

import com.github.technus.tectech.thing.metaTileEntity.hatch.GT_MetaTileEntity_Hatch_DynamoMulti;
import com.github.technus.tectech.thing.metaTileEntity.hatch.GT_MetaTileEntity_Hatch_EnergyMulti;
import common.Blocks;
import gregtech.api.enums.Dyes;
import gregtech.api.enums.Textures.BlockIcons;
import gregtech.api.gui.GT_GUIContainer_MultiMachine;
import gregtech.api.interfaces.ITexture;
import gregtech.api.interfaces.metatileentity.IMetaTileEntity;
import gregtech.api.interfaces.tileentity.IGregTechTileEntity;
import gregtech.api.metatileentity.implementations.GT_MetaTileEntity_Hatch;
import gregtech.api.metatileentity.implementations.GT_MetaTileEntity_Hatch_Dynamo;
import gregtech.api.metatileentity.implementations.GT_MetaTileEntity_Hatch_Energy;
import gregtech.api.metatileentity.implementations.GT_MetaTileEntity_MultiBlockBase;
import gregtech.api.objects.GT_RenderedTexture;
import net.minecraft.block.Block;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumChatFormatting;
import net.minecraftforge.common.util.ForgeDirection;
import org.lwjgl.input.Keyboard;
import util.MultiBlockTooltipBuilder;
import util.Vector3i;
import util.Vector3ic;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;

public class GTMTE_LapotronicSuperCapacitor extends GT_MetaTileEntity_MultiBlockBase {
	
	private final static String glassNameBorosilicate = "BW_GlasBlocks";
	private static final Block LSC_PART = Blocks.lscLapotronicEnergyUnit;
	private static final int CASING_META = 0;
	private static final int CASING_TEXTURE_ID = 62;

	private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);
	private static final BigDecimal PASSIVE_DISCHARGE_FACTOR_PER_TICK =
			BigDecimal.valueOf(0.01D / 1728000.0D); // The magic number is ticks per 24 hours

	private final ArrayList<GT_MetaTileEntity_Hatch_EnergyMulti> mEnergyHatchesTT = new ArrayList<>();
	private final ArrayList<GT_MetaTileEntity_Hatch_DynamoMulti> mDynamoHatchesTT = new ArrayList<>();
	// Count the amount of capacitors of each tier in each slot (translate with meta - 1)
	private final int[] capacitors = new int[6];
	private BigInteger capacity = BigInteger.ZERO;
	private BigInteger stored = BigInteger.ZERO;
	private BigInteger passiveDischargeAmount = BigInteger.ZERO;

	public GTMTE_LapotronicSuperCapacitor(int aID, String aName, String aNameRegional) {
		super(aID, aName, aNameRegional);
	}

	public GTMTE_LapotronicSuperCapacitor(String aName) {
		super(aName);
	}
	
	@Override
	public IMetaTileEntity newMetaEntity(IGregTechTileEntity var1) {
		return new GTMTE_LapotronicSuperCapacitor(super.mName);
	}
	
	@Override
	public String[] getDescription() {
		final MultiBlockTooltipBuilder b = new MultiBlockTooltipBuilder();
		b.addInfo("Power storage structure!")
				.addInfo("Looses energy equal to 1% of the total capacity every 24 hours.")
				.addInfo("EXCEPTION: (Really) Ultimate Capacitors only count as Lapotronic Capacitors (UV) for the")
				.addInfo("purpose of passive loss calculation. The full capacity is counted towards the actual power capacity.")
				.addSeparator()
				.addInfo("Glass shell has to be Tier - 2 of the highest capacitor tier")
				.addInfo("Modular height of 4 to 18 blocks.")
				.addSeparator()
				.beginStructureBlock(5, 4, 5)
				.addController("Front Bottom Center")
				.addDynamoHatch("Instead of any casing")
				.addEnergyHatch("Instead of any casing")
				.addOtherStructurePart("Lapotronic Capacitor Base", "5x2x5 base (at least 17x)")
				.addOtherStructurePart("Lapotronic Capacitor, (Really) Ultimate Capacitor", "Center 3x(1-15)x3 above base (9-135 blocks)")
				.addOtherStructurePart("Borosilicate Glass", "41-265x, Encase capacitor pillar")
				.addMaintenanceHatch("Instead of any casing")
				.signAndFinalize("Kekzdealer");
		if(!Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
			return b.getInformation();
		} else {
			return b.getStructureInformation();
		}
	}
	
	@Override
	public ITexture[] getTexture(IGregTechTileEntity aBaseMetaTileEntity, byte aSide, byte aFacing, byte aColorIndex,
			boolean aActive, boolean aRedstone) {
		ITexture[] sTexture = new ITexture[]{new GT_RenderedTexture(BlockIcons.MACHINE_CASING_FUSION_GLASS,
				Dyes.getModulation(-1, Dyes._NULL.mRGBa))};
		if (aSide == aFacing && aActive) {
			sTexture = new ITexture[]{new GT_RenderedTexture(BlockIcons.MACHINE_CASING_FUSION_GLASS_YELLOW,
					Dyes.getModulation(-1, Dyes._NULL.mRGBa))};
		}
		return sTexture;
	}
	
	public Object getClientGUI(int aID, InventoryPlayer aPlayerInventory, IGregTechTileEntity aBaseMetaTileEntity) {
		return new GT_GUIContainer_MultiMachine(aPlayerInventory, aBaseMetaTileEntity, this.getLocalName(),
				"MultiblockDisplay.png");
	}
	
	@Override
	public boolean isCorrectMachinePart(ItemStack stack) {
		return true;
	}
	
	@Override
	public boolean checkRecipe(ItemStack stack) {
		this.mProgresstime = 1;
		this.mMaxProgresstime = 1;
		this.mEUt = 0;
		this.mEfficiencyIncrease = 10000;
		return true;
	}

	public Vector3ic rotateOffsetVector(Vector3ic forgeDirection, int x, int y, int z) {
		final Vector3i offset = new Vector3i();

		// either direction on z-axis
		if (forgeDirection.x() == 0 && forgeDirection.z() == -1) {
			offset.x = x;
			offset.y = y;
			offset.z = z;
		}
		if (forgeDirection.x() == 0 && forgeDirection.z() == 1) {
			offset.x = -x;
			offset.y = y;
			offset.z = -z;
		}
		// either direction on x-axis
		if (forgeDirection.x() == -1 && forgeDirection.z() == 0) {
			offset.x = z;
			offset.y = y;
			offset.z = -x;
		}
		if (forgeDirection.x() == 1 && forgeDirection.z() == 0) {
			offset.x = -z;
			offset.y = y;
			offset.z = x;
		}
		// either direction on y-axis
		if (forgeDirection.y() == -1) {
			offset.x = x;
			offset.y = z;
			offset.z = y;
		}

		return offset;
	}
	
	@Override
	public boolean checkMachine(IGregTechTileEntity thisController, ItemStack guiSlotItem) {
		// Figure out the vector for the direction the back face of the controller is facing
		final Vector3ic forgeDirection = new Vector3i(
				ForgeDirection.getOrientation(thisController.getBackFacing()).offsetX,
				ForgeDirection.getOrientation(thisController.getBackFacing()).offsetY,
				ForgeDirection.getOrientation(thisController.getBackFacing()).offsetZ
				);
		boolean formationChecklist = true;
		int minCasingAmount = 16;
		int firstGlassMeta = -1;
		// Reset capacitor counts
		Arrays.fill(capacitors, 0);
		// Clear TT hatches
		mEnergyHatchesTT.clear();
		mDynamoHatchesTT.clear();

		// Capacitor base
		for(int Y = 0; Y <= 1; Y++) {
			for(int X = -2; X <= 2; X++) {
				for(int Z = 0; Z >= -4; Z--) {
					if(X == 0 && Y == 0 && Z == 0) {
						continue; // Skip controller
					}
					
					final Vector3ic offset = rotateOffsetVector(forgeDirection, X, Y, Z);
					final IGregTechTileEntity currentTE =
							thisController.getIGregTechTileEntityOffset(offset.x(), offset.y(), offset.z());
					
					// Tries to add TE as either of those kinds of hatches.
					// The number is the texture index number for the texture that needs to be painted over the hatch texture
					if (   !super.addMaintenanceToMachineList(currentTE, CASING_TEXTURE_ID)
						&& !this.addEnergyInputToMachineList(currentTE, CASING_TEXTURE_ID)
						&& !this.addDynamoToMachineList(currentTE, CASING_TEXTURE_ID)) {
						
						// If it's not a hatch, is it the right casing for this machine? Check block and block meta.
						if ((thisController.getBlockOffset(offset.x(), offset.y(), offset.z()) == LSC_PART) 
								&& (thisController.getMetaIDOffset(offset.x(), offset.y(), offset.z()) == CASING_META)) {
							// Seems to be valid casing. Decrement counter.
							minCasingAmount--;
						} else {
							formationChecklist = false;
						}
					}
				}
			}
		}
		// Capacitor units
		int firstGlassHeight = 3; // Initialize at basic height (-1 because it's an offset)
		for(int X = -1; X <= 1; X++) {
			for(int Z = -1; Z >= -2; Z--) {
				// Y has to be the innermost loop to properly deal with the dynamic height.
				// This way each "pillar" of capacitors is checked from bottom to top until it hits glass.
				for(int Y = 2; Y <= 17; Y++) {
					final Vector3ic offset = rotateOffsetVector(forgeDirection, X, Y, Z);

					final int meta = thisController.getMetaIDOffset(offset.x(), offset.y(), offset.z());
					if(thisController.getBlockOffset(offset.x(), offset.y(), offset.z()) == LSC_PART && (meta > 0)) {
						// Add capacity
						if(meta <= 4){
							final long c = (long) (100000000L * Math.pow(10, meta - 1));
							capacity = capacity.add(BigInteger.valueOf(c));
						} else if(meta <= 6){
							capacity = capacity.add(BigInteger.valueOf(Long.MAX_VALUE));
						}
						capacitors[meta - 1]++;
					} else if(thisController.getBlockOffset(offset.x(), offset.y(), offset.z()).getUnlocalizedName().equals(glassNameBorosilicate)){
						firstGlassHeight = Y;
						break;
					} else {
						formationChecklist = false;
						break;
					}
				}
			}
		}
		// Glass shell
		// Make Y the outermost loop, so each layer is checked completely before moving up
		for(int Y = 2; Y <= firstGlassHeight; Y++) {
			for(int X = -2; X <= 2; X++) {
				for(int Z = 0; Z >= -4; Z--) {
					final Vector3ic offset = rotateOffsetVector(forgeDirection, X, Y, Z);
					// Check only outer ring, except when on roof height
					if(Y < firstGlassHeight){
						if((X == -2 || X == 2) && (Z == -1 || Z == 4)){
							if(!thisController.getBlockOffset(offset.x(), offset.y(), offset.z()).getUnlocalizedName().equals(glassNameBorosilicate)){
								formationChecklist = false;
							} else {
								final int meta = thisController.getMetaIDOffset(offset.x(), offset.y(), offset.z());
								if(firstGlassMeta == -1){
									firstGlassMeta = meta;
								} else if(meta != firstGlassMeta){
									formationChecklist = false;
								}
							}
						}
					} else {
						if (!thisController.getBlockOffset(offset.x(), offset.y(), offset.z()).getUnlocalizedName().equals(glassNameBorosilicate)) {
							formationChecklist = false;
						}
					}
				}
			}
		}

		if(minCasingAmount > 0){
			formationChecklist = false;
		}

		// Make sure glass tier is T-2 of the highest tier capacitor in the structure
		// Count down from the highest tier until an entry is found
		for(int highestCapacitor = capacitors.length - 1; highestCapacitor >= 0; highestCapacitor--){
			if(capacitors[highestCapacitor] > 0){
				formationChecklist = firstGlassMeta >= capacitors[highestCapacitor] - 2;
			}
		}

		// Calculate total capacity
		capacity = BigInteger.ZERO;
		for(int i = 0; i < capacitors.length; i++){
			if(i <= 3){
				final long c = (long) (100000000L * Math.pow(10, i));
				capacity = capacity.add(
						BigInteger.valueOf(c).multiply(BigInteger.valueOf(capacitors[i])));
			} else {
				capacity = capacity.add(
						MAX_LONG.multiply(BigInteger.valueOf(capacitors[i])));
			}
		}
		// Calculate how much energy to void each tick
		passiveDischargeAmount = new BigDecimal(capacity).multiply(PASSIVE_DISCHARGE_FACTOR_PER_TICK).toBigInteger();

		return formationChecklist;
	}

	@Override
	public boolean addEnergyInputToMachineList(IGregTechTileEntity te, int aBaseCasingIndex) {
		if (te == null) {
			return false;
		} else {
			final IMetaTileEntity mte = te.getMetaTileEntity();
			if (mte instanceof GT_MetaTileEntity_Hatch_Energy) {
				// Add GT hatches
				((GT_MetaTileEntity_Hatch) mte).updateTexture(aBaseCasingIndex);
				return super.mEnergyHatches.add((GT_MetaTileEntity_Hatch_Energy) mte);
			} else if(mte instanceof GT_MetaTileEntity_Hatch_EnergyMulti){
				// Add TT hatches
				((GT_MetaTileEntity_Hatch) mte).updateTexture(aBaseCasingIndex);
				return mEnergyHatchesTT.add((GT_MetaTileEntity_Hatch_EnergyMulti) mte);
			} else {
				return false;
			}
		}
	}

	@Override
	public boolean addDynamoToMachineList(IGregTechTileEntity te, int aBaseCasingIndex) {
		if (te == null) {
			return false;
		} else {
			final IMetaTileEntity mte = te.getMetaTileEntity();
			if (mte instanceof GT_MetaTileEntity_Hatch_Dynamo) {
				// Add GT hatches
				((GT_MetaTileEntity_Hatch) mte).updateTexture(aBaseCasingIndex);
				return super.mDynamoHatches.add((GT_MetaTileEntity_Hatch_Dynamo) mte);
			} else if(mte instanceof GT_MetaTileEntity_Hatch_DynamoMulti){
				// Add TT hatches
				((GT_MetaTileEntity_Hatch) mte).updateTexture(aBaseCasingIndex);
				return mDynamoHatchesTT.add((GT_MetaTileEntity_Hatch_DynamoMulti) mte);
			} else {
				return false;
			}
		}
	}

	@Override
	public boolean onRunningTick(ItemStack stack){
		// Draw energy from GT hatches
		for(GT_MetaTileEntity_Hatch_Energy eHatch : super.mEnergyHatches) {
			if(eHatch == null || eHatch.getBaseMetaTileEntity().isInvalidTileEntity()) {
				continue;
			}
			final BigInteger remcapActual = capacity.subtract(stored);
			final BigInteger recampLimited = (MAX_LONG.compareTo(remcapActual) <= 0) ? remcapActual : MAX_LONG;
			final long power = Math.min(eHatch.maxEUInput() * eHatch.maxAmperesIn(), recampLimited.longValue());
			if(power <= eHatch.getEUVar()) {
				eHatch.setEUVar(eHatch.getEUVar() - power);
				stored = stored.add(BigInteger.valueOf(power));
			}
		}
		// Output energy to GT hatches
		for(GT_MetaTileEntity_Hatch_Dynamo eDynamo : super.mDynamoHatches){
			if(eDynamo == null || eDynamo.getBaseMetaTileEntity().isInvalidTileEntity()){
				continue;
			}
			final BigInteger remStoredLimited = (MAX_LONG.compareTo(stored) <= 0) ? stored : MAX_LONG;
			final long power = Math.min(eDynamo.maxEUOutput() * eDynamo.maxAmperesOut(), remStoredLimited.longValue());
			if(eDynamo.getEUVar() <= eDynamo.maxEUStore() - power) {
				eDynamo.setEUVar(eDynamo.getEUVar() + power);
				stored = stored.subtract(BigInteger.valueOf(power));
			}
		}
		// Draw energy from TT hatches
		for(GT_MetaTileEntity_Hatch_EnergyMulti eHatch : mEnergyHatchesTT) {
			if(eHatch == null || eHatch.getBaseMetaTileEntity().isInvalidTileEntity()) {
				continue;
			}
			final BigInteger remcapActual = capacity.subtract(stored);
			final BigInteger recampLimited = (MAX_LONG.compareTo(remcapActual) <= 0) ? remcapActual : MAX_LONG;
			final long power = Math.min(eHatch.maxEUInput() * eHatch.maxAmperesIn(), recampLimited.longValue());
			if(power <= eHatch.getEUVar()) {
				eHatch.setEUVar(eHatch.getEUVar() - power);
				stored = stored.add(BigInteger.valueOf(power));
			}
		}
		// Output energy to TT hatches
		for(GT_MetaTileEntity_Hatch_DynamoMulti eDynamo : mDynamoHatchesTT){
			if(eDynamo == null || eDynamo.getBaseMetaTileEntity().isInvalidTileEntity()){
				continue;
			}
			final BigInteger remStoredLimited = (MAX_LONG.compareTo(stored) <= 0) ? stored : MAX_LONG;
			final long power = Math.min(eDynamo.maxEUOutput() * eDynamo.maxAmperesOut(), remStoredLimited.longValue());
			if(eDynamo.getEUVar() <= eDynamo.maxEUStore() - power) {
				eDynamo.setEUVar(eDynamo.getEUVar() + power);
				stored = stored.subtract(BigInteger.valueOf(power));
			}
		}
		// Loose some energy
		stored = stored.subtract(passiveDischargeAmount);
		stored = (stored.compareTo(BigInteger.ZERO) <= 0) ? BigInteger.ZERO : stored;

		return true;
	}

	@Override
	public String[] getInfoData() {
		final ArrayList<String> ll = new ArrayList<>();
		ll.add(EnumChatFormatting.YELLOW + "Operational Data:" + EnumChatFormatting.RESET);
		ll.add("Used Capacity: " + NumberFormat.getNumberInstance().format(stored) + "EU");
		ll.add("Total Capacity: " + NumberFormat.getNumberInstance().format(capacity) + "EU");
		ll.add("Running Cost: " + NumberFormat.getNumberInstance().format(passiveDischargeAmount) + "EU/t");
		ll.add("Maintenance Status: " + ((super.getRepairStatus() == super.getIdealStatus())
				? EnumChatFormatting.GREEN + "Working perfectly" + EnumChatFormatting.RESET
				: EnumChatFormatting.RED + "Has Problems" + EnumChatFormatting.RESET));
		ll.add("---------------------------------------------");

		final String[] a = new String[ll.size()];
		return ll.toArray(a);
	}

	@Override
	public void saveNBTData(NBTTagCompound nbt) {
		nbt = (nbt == null) ? new NBTTagCompound() : nbt;

		nbt.setByteArray("capacity", capacity.toByteArray());
		nbt.setByteArray("stored", stored.toByteArray());
		nbt.setByteArray("passiveDischargeAmount", passiveDischargeAmount.toByteArray());

		super.saveNBTData(nbt);
	}

	@Override
	public void loadNBTData(NBTTagCompound nbt) {
		nbt = (nbt == null) ? new NBTTagCompound() : nbt;

		capacity = new BigInteger(nbt.getByteArray("capacity"));
		stored = new BigInteger(nbt.getByteArray("stored"));
		passiveDischargeAmount = new BigInteger(nbt.getByteArray("passiveDischargeAmount"));

		super.loadNBTData(nbt);
	}

	@Override
	public boolean isGivingInformation() {
		return true;
	}

	@Override
	public int getMaxEfficiency(ItemStack stack) { return 10000; }

	@Override
	public int getPollutionPerTick(ItemStack stack) { return 0; }

	@Override
	public int getDamageToComponent(ItemStack stack) { return 0; }

	@Override
	public boolean explodesOnComponentBreak(ItemStack stack) { return false; }
	
}