From f2da49d7329fa28c2e8d8ba9baa08cc0a92a06c0 Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Sun, 18 Feb 2024 20:41:21 +0100
Subject: [PATCH 01/20] Initial CraftTweaker compat
---
build.gradle | 11 ++++++++++-
gradle.properties | 3 ++-
.../destroy/chemistry/index/DestroyMolecules.java | 10 +++++++++-
.../destroy/chemistry/index/DestroyReactions.java | 10 +++++++++-
4 files changed, 30 insertions(+), 4 deletions(-)
diff --git a/build.gradle b/build.gradle
index d68ff7afa..6af35eea4 100644
--- a/build.gradle
+++ b/build.gradle
@@ -115,6 +115,11 @@ repositories {
url = "https://maven.jaackson.me"
}
+ maven {
+ url = 'https://maven.blamejared.com'
+ name = 'BlameJared Maven'
+ }
+
exclusiveContent {
forRepository {
maven {
@@ -176,7 +181,11 @@ dependencies {
compileOnly fg.deobf("com.teamabnormals:blueprint:${minecraft_version}-${blueprint_version}")
implementation fg.deobf("com.teamabnormals:blueprint:${minecraft_version}-${blueprint_version}")
-
+ // CraftTweaker
+ var tweaker = "com.blamejared.crafttweaker:CraftTweaker-forge-${minecraft_version}:${crafttweaker_version}"
+ compileOnly fg.deobf(tweaker)
+ annotationProcessor(tweaker)
+ compileOnly("com.blamejared.crafttweaker:CraftTweaker-common-${minecraft_version}:${crafttweaker_version}")
// ANNOTATION PROCESSORS
annotationProcessor "org.spongepowered:mixin:${mixin_version}:processor"
diff --git a/gradle.properties b/gradle.properties
index 48a71a10b..7ab4087fd 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -21,4 +21,5 @@ flywheel_version = 0.6.10-7
registrate_version = MC1.20-1.3.3
jei_version = 15.2.0.22
farmersdelight_version = 4638874
-blueprint_version = 7.0.0
\ No newline at end of file
+blueprint_version = 7.0.0
+crafttweaker_version = 14.0.34
\ No newline at end of file
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java
index e3611b65c..24c5d6bca 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java
@@ -1,5 +1,7 @@
package com.petrolpark.destroy.chemistry.index;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
import com.petrolpark.destroy.Destroy;
import com.petrolpark.destroy.chemistry.Element;
import com.petrolpark.destroy.chemistry.Formula;
@@ -9,9 +11,14 @@
import com.petrolpark.destroy.chemistry.Molecule.MoleculeBuilder;
import net.minecraft.ChatFormatting;
+import org.openzen.zencode.java.ZenCodeType;
+@ZenRegister
+@ZenCodeType.Name("mods.destroy.Molecules")
+@Document("mods/destroy/Molecules")
public final class DestroyMolecules {
+ @ZenCodeType.Field
public static final Molecule
ACETAMIDE = builder()
@@ -1100,7 +1107,8 @@ public final class DestroyMolecules {
.charge(1)
.build();
- private static final MoleculeBuilder builder() {
+ @ZenCodeType.Method("create")
+ public static MoleculeBuilder builder() {
return new MoleculeBuilder(Destroy.MOD_ID);
};
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java
index d29c67f43..25e515a84 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java
@@ -1,5 +1,7 @@
package com.petrolpark.destroy.chemistry.index;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
import com.petrolpark.destroy.Destroy;
import com.petrolpark.destroy.advancement.DestroyAdvancements;
import com.petrolpark.destroy.block.DestroyBlocks;
@@ -13,9 +15,14 @@
import com.simibubi.create.AllTags;
import net.minecraft.world.item.Items;
+import org.openzen.zencode.java.ZenCodeType;
+@ZenRegister
+@ZenCodeType.Name("mods.destroy.Reactions")
+@Document("mods/destroy/Reactions")
public class DestroyReactions {
+ @ZenCodeType.Field
public static final Reaction
ABS_COPOLYMERIZATION = builder()
@@ -734,7 +741,8 @@ public class DestroyReactions {
builder().acid(DestroyMolecules.SULFURIC_ACID, DestroyMolecules.HYDROGENSULFATE, -2.18f);
};
- private static ReactionBuilder builder() {
+ @ZenCodeType.Method("create")
+ public static ReactionBuilder builder() {
return new ReactionBuilder(Destroy.MOD_ID);
};
From ddedfac82e280f0281786123072094ecfd53c1da Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Sun, 18 Feb 2024 22:58:36 +0100
Subject: [PATCH 02/20] Moved CraftTweaker into its own package
---
.../chemistry/index/DestroyMolecules.java | 4 ----
.../chemistry/index/DestroyReactions.java | 11 ++--------
.../compat/crafttweaker/MoleculeManager.java | 22 +++++++++++++++++++
.../compat/crafttweaker/ReactionManager.java | 21 ++++++++++++++++++
4 files changed, 45 insertions(+), 13 deletions(-)
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/MoleculeManager.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/ReactionManager.java
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java
index 24c5d6bca..a4ce75f9f 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java
@@ -13,12 +13,8 @@
import net.minecraft.ChatFormatting;
import org.openzen.zencode.java.ZenCodeType;
-@ZenRegister
-@ZenCodeType.Name("mods.destroy.Molecules")
-@Document("mods/destroy/Molecules")
public final class DestroyMolecules {
- @ZenCodeType.Field
public static final Molecule
ACETAMIDE = builder()
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java
index 25e515a84..893caadfb 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java
@@ -1,7 +1,5 @@
package com.petrolpark.destroy.chemistry.index;
-import com.blamejared.crafttweaker.api.annotation.ZenRegister;
-import com.blamejared.crafttweaker_annotations.annotations.Document;
import com.petrolpark.destroy.Destroy;
import com.petrolpark.destroy.advancement.DestroyAdvancements;
import com.petrolpark.destroy.block.DestroyBlocks;
@@ -13,16 +11,12 @@
import com.petrolpark.destroy.item.DestroyItems;
import com.simibubi.create.AllItems;
import com.simibubi.create.AllTags;
-
import net.minecraft.world.item.Items;
import org.openzen.zencode.java.ZenCodeType;
-@ZenRegister
-@ZenCodeType.Name("mods.destroy.Reactions")
-@Document("mods/destroy/Reactions")
+
public class DestroyReactions {
- @ZenCodeType.Field
public static final Reaction
ABS_COPOLYMERIZATION = builder()
@@ -741,8 +735,7 @@ public class DestroyReactions {
builder().acid(DestroyMolecules.SULFURIC_ACID, DestroyMolecules.HYDROGENSULFATE, -2.18f);
};
- @ZenCodeType.Method("create")
- public static ReactionBuilder builder() {
+ private static ReactionBuilder builder() {
return new ReactionBuilder(Destroy.MOD_ID);
};
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/MoleculeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/MoleculeManager.java
new file mode 100644
index 000000000..7fff184f1
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/MoleculeManager.java
@@ -0,0 +1,22 @@
+package com.petrolpark.destroy.compat.crafttweaker;
+
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.chemistry.Molecule;
+import com.petrolpark.destroy.chemistry.Reaction;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@ZenCodeType.Name("mods.destroy.Reactions")
+@Document("mods/destroy/Reactions")
+public class MoleculeManager {
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder create() {
+ return new Molecule.MoleculeBuilder("crafttweaker");
+ }
+
+ @ZenCodeType.Method
+ public static Molecule getMoleculeById(String moleculeId) {
+ return Molecule.MOLECULES.get(moleculeId);
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/ReactionManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/ReactionManager.java
new file mode 100644
index 000000000..14a7c1bc5
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/ReactionManager.java
@@ -0,0 +1,21 @@
+package com.petrolpark.destroy.compat.crafttweaker;
+
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.chemistry.Reaction;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@ZenCodeType.Name("mods.destroy.Reactions")
+@Document("mods/destroy/Reactions")
+public class ReactionManager {
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder create() {
+ return new Reaction.ReactionBuilder("crafttweaker");
+ }
+
+ @ZenCodeType.Method
+ public static Reaction getReactionById(String reactionId) {
+ return Reaction.REACTIONS.get(reactionId);
+ }
+}
From 5ab1cfd0edeb965f3e2b44de2b50e0127b25e470 Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Sun, 18 Feb 2024 23:45:51 +0100
Subject: [PATCH 03/20] Tiden code up a bit
---
.../petrolpark/destroy/chemistry/Group.java | 6 +-
.../destroy/chemistry/Molecule.java | 83 +++++++++----------
.../destroy/chemistry/Reaction.java | 56 ++++++-------
.../genericreaction/AlcoholDehydration.java | 2 +-
.../genericreaction/AlkeneHydrolysis.java | 2 -
.../compat/jei/category/ReactionCategory.java | 2 +-
6 files changed, 72 insertions(+), 79 deletions(-)
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Group.java b/src/main/java/com/petrolpark/destroy/chemistry/Group.java
index c93df9b10..f9f45dc9b 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Group.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Group.java
@@ -29,7 +29,7 @@ public Group() {
* Get the {@link GenericReaction Generic Reactions} in which the given functional Group participates.
* @param group
*/
- public static final Set getReactionsOf(Group> group) {
+ public static Set getReactionsOf(Group> group) {
return groupTypesAndReactions.get(group.getType());
};
@@ -37,9 +37,9 @@ public static final Set getReactionsOf(Group> group) {
/**
* Get the {@link GenericReaction Generic Reactions} which the functional Group identified by the given ID participates in.
- * @param ID The {@link Group#getID String ID} of the functional Group.
+ * @param type ID of the group
*/
- public static final Set getReactionsOfGroupByID(GroupType> type) {
+ public static Set getReactionsOfGroupByID(GroupType> type) {
return groupTypesAndReactions.get(type);
};
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java b/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
index b451b9d0e..faebac777 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
@@ -1,11 +1,5 @@
package com.petrolpark.destroy.chemistry;
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
import javax.annotation.Nullable;
@@ -57,9 +51,9 @@ public class Molecule implements INameableProduct {
/**
* The name space of the mod by which this Molecule was defined.
*/
- public final String nameSpace;
+ public final String namespace;
/**
- * The {@link Molecule#getFullID ID} of this Molecule, not including its {@link Molecule#nameSpace name space}.
+ * The {@link Molecule#getFullID ID} of this Molecule, not including its {@link Molecule#namespace name space}.
*/
private String id;
@@ -105,16 +99,16 @@ public class Molecule implements INameableProduct {
/**
* The {@link MoleculeTag tags} which apply to this Molecule.
*/
- private Set tags;
+ private final Set tags;
/**
* The specific {@link Reaction Reactions} in which this Molecule is a {@link Reaction#getReactants reactant}.
*/
- private List reactantReactions;
+ private final List reactantReactions;
/**
* The specific {@link Reaction Reactions} in which this Molecule is a {@link Reaction#getProducts product}.
*/
- private List productReactions;
+ private final List productReactions;
// DISPLAY PROPERTIES
@@ -144,7 +138,7 @@ public class Molecule implements INameableProduct {
private MoleculeRenderer renderer;
private Molecule(String nameSpace) {
- this.nameSpace = nameSpace;
+ this.namespace = nameSpace;
id = null;
structure = null;
@@ -199,7 +193,7 @@ public String getFullID() {
*/
return structure.serialize();
} else {
- return nameSpace+":"+id;
+ return namespace +":"+id;
}
};
@@ -307,8 +301,8 @@ public Set getAtoms() {
};
/**
- * Whether this Molecule is {@link MoleculeTag tagged} as being {@link DestroyMolecules.Tags.HYPOTHETICAL hypothetical}.
- * This is typically any {@link Group#getExampleMolecule exemplar Molecule} for a {@link Group functional Group},
+ * Whether this Molecule is {@link MoleculeTag tagged} as being {@link DestroyMolecules.Tags#HYPOTHETICAL hypothetical}.
+ * This is typically any exemplar Molecule for a {@link Group functional Group},
* something than contains {@link Element#R_GROUP R-groups}, or a Molecule that can't actually exist.
*/
public boolean isHypothetical() {
@@ -317,7 +311,7 @@ public boolean isHypothetical() {
/**
* Get all the {@link MoleculeTag tags} this Molecule has.
- * @return
+ * @return Molecule tags
*/
public ImmutableSet getTags() {
return ImmutableSet.copyOf(tags);
@@ -337,7 +331,7 @@ public boolean hasTag(MoleculeTag tag) {
* @see Molecule What a novel Molecule is
*/
public boolean isNovel() {
- return this.nameSpace == "novel";
+ return this.namespace == "novel";
};
/**
@@ -432,7 +426,7 @@ public List getProductReactions() {
};
/**
- * Get the {@link Molecule#name display name} of this Molecule.
+ * Get the display name of this Molecule.
* @param iupac Whether to use the IUPAC systematic name rather than the common one
*/
@Override
@@ -443,7 +437,7 @@ public Component getName(boolean iupac) {
public String getTranslationKey(boolean iupac) {
if (isNovel()) return "destroy.chemical.unknown";
- String key = nameSpace + ".chemical." + translationKey;
+ String key = namespace + ".chemical." + translationKey;
String iupacKey = key + ".iupac";
if (iupac && I18n.exists(iupacKey)) {
key = iupacKey;
@@ -543,7 +537,7 @@ public MoleculeRenderer getRenderer() {
* A class for constructing {@link Molecule Molecules}. This is typically used for:
* - Declaring known Molecules ({@link DestroyMolecules example})
* - Constructing novel Molecules for {@link com.petrolpark.destroy.chemistry.genericreaction.GenericReaction Generic Reactions}
- * ({@link com.petrolpark.destroy.chemistry.index.genericreaction.HydroxideSubstitutions#generateReaction example}).
+ * ({@link com.petrolpark.destroy.chemistry.index.genericreaction.AlcoholDehydration#generateReaction example}).
*
* Use {@code build()} to build get the Molecule.
*/
@@ -561,13 +555,13 @@ public static class MoleculeBuilder {
/**
* A {@link Molecule} constructor.
- * @param nameSpace The {@link Molecule#nameSpace name space} to which all Molecules constructed with this builder will belong
+ * @param nameSpace The {@link Molecule#namespace name space} to which all Molecules constructed with this builder will belong
* @throws IllegalArgumentException If a {@link Molecule#FORBIDDEN_NAMESPACES forbidden name space} is used, for example {@code novel}.
*/
public MoleculeBuilder(String nameSpace) {
molecule = new Molecule(nameSpace);
if (FORBIDDEN_NAMESPACES.contains(nameSpace)) {
- throw e("Cannot use name space '"+nameSpace+"'.");
+ error("Cannot use name space '" + nameSpace + "'.");
};
NAMESPACES.add(nameSpace);
molecule.charge = 0; //default
@@ -600,7 +594,8 @@ public MoleculeBuilder structure(Formula structure) {
molecule.structure = structure;
return this;
} catch (FormulaModificationException e) {
- throw e("Cannot use structure.", e);
+ error("Cannot use structure.", e);
+ return null;
}
};
@@ -630,7 +625,7 @@ public MoleculeBuilder charge(int charge) {
/**
* Set the {@link Molecule#boilingPoint boiling point} in degrees Celsius.
- * If not supplied, the boiling point will be very loosely {@link MoleculeBuilder#calculateBoilingPoint estimated}, but setting one is recommended.
+ * If not supplied, the boiling point will be very loosely given value, but setting one is recommended.
* @param boilingPoint In degrees Celcius
* @return This Molecule Builder
*/
@@ -640,7 +635,7 @@ public MoleculeBuilder boilingPoint(float boilingPoint) {
/**
* Set the {@link Molecule#boilingPoint boiling point} in kelvins.
- * If not supplied, the boiling point will be very loosely {@link MoleculeBuilder#calculateBoilingPoint estimated}, but setting one is recommended.
+ * If not supplied, the boiling point will be very loosely {@link MoleculeBuilder#boilingPoint estimated}, but setting one is recommended.
* @param boilingPoint In kelvins
* @return This Molecule Builder
*/
@@ -652,7 +647,7 @@ public MoleculeBuilder boilingPointInKelvins(float boilingPoint) {
/**
* Set the {@link Molecule#dipoleMoment dipole moment} of this Molecule.
- * If not supplied, a dipole moment will be very loosely {@link MoleculeBuilder#calculateDipoleMoment estimated}, but setting one is recommended.
+ * If not supplied, a dipole moment will be very loosely given value, but setting one is recommended.
* @return This Molecule Builder
*/
public MoleculeBuilder dipoleMoment(int dipoleMoment) {
@@ -674,11 +669,11 @@ public MoleculeBuilder specificHeatCapacity(float specificHeatCapacity) {
/**
* Set the {@link Molecule#molarHeatCapacity molar heat capacity} for this Molecule,
* in joules per mole-kelvin.
- * @param molarHeatCapacity
+ * @param molarHeatCapacity New capacity
* @return This Molecule Builder
*/
public MoleculeBuilder molarHeatCapacity(float molarHeatCapacity) {
- if (molarHeatCapacity <= 0f) throw e("Molar heat capacity must be greater than 0.");
+ if (molarHeatCapacity <= 0f) error("Molar heat capacity must be greater than 0.");
molecule.molarHeatCapacity = molarHeatCapacity;
hasForcedMolarHeatCapacity = true;
return this;
@@ -691,7 +686,7 @@ public MoleculeBuilder molarHeatCapacity(float molarHeatCapacity) {
* @return This Molecule Builder
*/
public MoleculeBuilder latentHeat(float latentHeat) {
- if (latentHeat <= 0f) throw e("Latent heat of fusion must be greater than 0.");
+ if (latentHeat <= 0f) error("Latent heat of fusion must be greater than 0.");
molecule.latentHeat = latentHeat;
hasForcedLatentHeat = true;
return this;
@@ -743,7 +738,7 @@ public MoleculeBuilder tag(MoleculeTag ...tags) {
* This is the only safe way to declare a Molecule.
* @return A new Molecule instance
* @throws IllegalArgumentException If the Molecule's {@link Formula structure} was not {@link MoleculeBuilder#structure declared},
- * or it is not novel and the {@link Molecule#nameSpace name space} was not declared.
+ * or it is not novel and the {@link Molecule#namespace name space} was not declared.
*/
public Molecule build() {
@@ -751,12 +746,12 @@ public Molecule build() {
molecule.translationKey = translationKey;
if (molecule.structure == null) {
- throw e("Molecule's structure has not been declared.");
+ error("Molecule's structure has not been declared.");
};
- if (molecule.getAtoms().size() >= 100) throw e("Molecule has too many Atoms");
-
- if (molecule.nameSpace == "novel") {
+ if (molecule.getAtoms().size() >= 100) error("Molecule has too many Atoms");
+ boolean isNovelNamespace = Objects.equals(molecule.namespace, "novel");
+ if (isNovelNamespace) {
Molecule equivalentMolecule = molecule.getEquivalent();
if (equivalentMolecule != molecule) {
return equivalentMolecule;
@@ -780,11 +775,11 @@ public Molecule build() {
molecule.refreshFunctionalGroups();
molecule.structure.updateSideChainStructures();
- if (molecule.nameSpace != "novel") {
+ if (!isNovelNamespace) {
if (molecule.id == null) {
- throw e("Molecule's ID has not been declared.");
+ error("Molecule's ID has not been declared.");
} else {
- MOLECULES.put(molecule.nameSpace+":"+molecule.id, molecule);
+ MOLECULES.put(molecule.namespace +":"+molecule.id, molecule);
};
};
@@ -835,7 +830,7 @@ private static int estimateDipoleMoment(Molecule molecule) {
return 0;
};
- public class MoleculeConstructionException extends ChemistryException {
+ public static class MoleculeConstructionException extends ChemistryException {
private MoleculeConstructionException(String message) {
super(message);
@@ -847,16 +842,16 @@ private MoleculeConstructionException(String message, Throwable e) {
};
- private MoleculeConstructionException e(String message) {
- return new MoleculeConstructionException(addInfoToMessage(message));
+ private void error(String message) {
+ throw new MoleculeConstructionException(addInfoToMessage(message));
};
- private MoleculeConstructionException e(String message, Throwable e) {
- return new MoleculeConstructionException(addInfoToMessage(message), e);
+ private void error(String message, Throwable e) {
+ throw new MoleculeConstructionException(addInfoToMessage(message), e);
};
private String addInfoToMessage(String message) {
- String id = molecule.id == null ? "Unknown ID" : molecule.nameSpace + ":" + molecule.id;
+ String id = molecule.id == null ? "Unknown ID" : molecule.namespace + ":" + molecule.id;
return "Problem building Molecule (" + id + "): " + message;
};
};
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
index abbad2f18..5be7f64e7 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
@@ -30,7 +30,7 @@ public class Reaction {
public static final Float GAS_CONSTANT = 8.3145f;
/**
- * The set of all Reactions known to Destroy, indexed by their {@link id IDs}.
+ * The set of all Reactions known to Destroy, indexed by their {@link Reaction#id IDs}.
*/
public static final Map REACTIONS = new HashMap<>();
@@ -78,9 +78,9 @@ public static ReactionBuilder generatedReactionBuilder() {
* The namespace of the mod by which this Reaction was declared, or {@code novel} if this was generated
* by a {@link com.petrolpark.destroy.chemistry.genericreaction.GenericReaction Reaction generator}.
*/
- private String nameSpace;
+ private final String namespace;
/**
- * The ID of this reaction, not including its {@link Reaction#nameSpace name space}, and {@code null} if this
+ * The ID of this reaction, not including its {@link Reaction#namespace name space}, and {@code null} if this
* Reaction was generated by a {@link com.petrolpark.destroy.chemistry.genericreaction.GenericReaction Reaction
* generator}.
* @see Reaction#getId The getter for this field
@@ -116,7 +116,7 @@ public static Reaction get(String reactionId) {
};
private Reaction(String nameSpace) {
- this.nameSpace = nameSpace;
+ this.namespace = nameSpace;
};
/**
@@ -242,7 +242,7 @@ public String getId() {
* }, for example {@code destroy:chloroform_fluorination}.
*/
public String getFullId() {
- return nameSpace + ":" + id;
+ return namespace + ":" + id;
};
/**
@@ -273,8 +273,8 @@ public Optional getReverseReactionForDisplay() {
* The name space of the mod by which this Reaction was defined.
* @return {@code "novel"} if this was generated automatically by a {@link com.petrolpark.destroy.chemistry.genericreaction.GenericReaction Reaction generator}.
*/
- public String getNameSpace() {
- return nameSpace;
+ public String getNamespace() {
+ return namespace;
};
/**
@@ -358,7 +358,7 @@ public ReactionBuilder(String namespace) {
};
private void checkNull(Molecule molecule) {
- if (molecule == null) throw e("Molecules cannot be null");
+ if (molecule == null) error("Molecules cannot be null");
};
/**
@@ -407,7 +407,7 @@ public ReactionBuilder addReactant(Molecule molecule, int ratio, int order) {
* @see ReactionBuilder#addCatalyst(Molecule, int) Adding order with respect to a Molecule that is not a reactant (i.e. a catalyst)
*/
public ReactionBuilder setOrder(Molecule molecule, int order) {
- if (!reaction.reactants.keySet().contains(molecule)) throw e("Cannot modify order of a Molecule ("+ molecule.getFullID() +") that is not a reactant.");
+ if (!reaction.reactants.keySet().contains(molecule)) error("Cannot modify order of a Molecule ("+ molecule.getFullID() +") that is not a reactant.");
addCatalyst(molecule, order);
return this;
};
@@ -422,7 +422,7 @@ public ReactionBuilder setOrder(Molecule molecule, int order) {
* @see ReactionBuilder#addSimpleItemTagReactant Adding an Item Tag as a Reactant
*/
public ReactionBuilder addItemReactant(IItemReactant itemReactant, float moles) {
- if (reaction.molesPerItem != 0f && reaction.molesPerItem != moles) throw e("The number of moles of Reaction which occur when all Item Requirements are met is constant for a Reaction, not individual per Item Reactant. The same number must be supplied each time an Item Reactant is added.");
+ if (reaction.molesPerItem != 0f && reaction.molesPerItem != moles) error("The number of moles of Reaction which occur when all Item Requirements are met is constant for a Reaction, not individual per Item Reactant. The same number must be supplied each time an Item Reactant is added.");
reaction.molesPerItem = moles;
reaction.itemReactants.add(itemReactant);
return this;
@@ -589,7 +589,7 @@ public ReactionBuilder enthalpyChange(float enthalpyChange) {
* @return This Reaction Builder
*/
public ReactionBuilder withResult(float moles, BiFunction reactionresultFactory) {
- if (reaction.result != null) throw e("Reaction already has a Reaction Result. Use a CombinedReactionResult to have multiple.");
+ if (reaction.result != null) error("Reaction already has a Reaction Result. Use a CombinedReactionResult to have multiple.");
reaction.result = reactionresultFactory.apply(moles, reaction);
return this;
};
@@ -605,7 +605,7 @@ public ReactionBuilder withResult(float moles, BiFunction reverseReactionModifier) {
- if (generated) throw e("Generated Reactions cannot be reversible. Add another Generic Reaction instead.");
+ if (generated) error("Generated Reactions cannot be reversible. Add another Generic Reaction instead.");
reaction.displayAsReversible = true;
ReactionBuilder reverseBuilder = new ReactionBuilder(namespace);
for (Entry reactant : reaction.reactants.entrySet()) {
@@ -657,7 +657,7 @@ public ReactionBuilder reverseReaction(Consumer reverseReaction
reverseBuilder.addReactant(product.getKey(), product.getValue());
};
for (Entry rateAffecter : reaction.orders.entrySet()) {
- if (reaction.reactants.keySet().contains(rateAffecter.getKey())) continue; // Ignore reactants, only add catalysts
+ if (reaction.reactants.containsKey(rateAffecter.getKey())) continue; // Ignore reactants, only add catalysts
reverseBuilder.addCatalyst(rateAffecter.getKey(), rateAffecter.getValue());
};
reaction.reverseReaction = reverseBuilder.reaction; // Set this so JEI knows
@@ -680,7 +680,7 @@ public ReactionBuilder reverseReaction(Consumer reverseReaction
reaction.activationEnergy - reaction.enthalpyChange != reverseBuilder.reaction.activationEnergy
|| reaction.enthalpyChange != -reverseBuilder.reaction.enthalpyChange
) {
- throw e("Activation energies and enthalpy changes for reversible Reactions must obey Hess' Law");
+ error("Activation energies and enthalpy changes for reversible Reactions must obey Hess' Law");
};
reverseBuilder.build();
@@ -690,7 +690,7 @@ public ReactionBuilder reverseReaction(Consumer reverseReaction
public Reaction build() {
if (reaction.id == null && !generated) {
- throw e("Reaction is missing an ID.");
+ error("Reaction is missing an ID.");
};
if (!hasForcedActivationEnergy) {
@@ -721,7 +721,7 @@ public Reaction build() {
return reaction;
};
- public class ReactionConstructionException extends ChemistryException {
+ public static class ReactionConstructionException extends ChemistryException {
public ReactionConstructionException(String message) {
super(message);
@@ -729,24 +729,24 @@ public ReactionConstructionException(String message) {
};
- private ReactionConstructionException e(String message) {
- String id = reaction.id == null ? reactionString() : reaction.nameSpace + ":" + reaction.id;
- return new ReactionConstructionException("Problem generating reation ("+ id + "): " + message);
+ private void error(String message) {
+ String id = reaction.id == null ? reactionString() : reaction.namespace + ":" + reaction.id;
+ throw new ReactionConstructionException("Problem generating reaction (" + id + "): " + message);
};
private String reactionString() {
- String reactionString = "";
+ StringBuilder reactionString = new StringBuilder();
for (Molecule reactant : reaction.reactants.keySet()) {
- reactionString += reactant.getSerlializedMolecularFormula(false);
- reactionString += " + ";
+ reactionString.append(reactant.getSerlializedMolecularFormula(false));
+ reactionString.append(" + ");
};
- reactionString = reactionString.substring(0, reactionString.length() - 3) + " => ";
+ reactionString = new StringBuilder(reactionString.substring(0, reactionString.length() - 3) + " => ");
for (Molecule product : reaction.products.keySet()) {
- reactionString += product.getSerlializedMolecularFormula(false);
- reactionString += " + ";
+ reactionString.append(product.getSerlializedMolecularFormula(false));
+ reactionString.append(" + ");
};
- reactionString = reactionString.substring(0, reactionString.length() - 3);
- return reactionString;
+ reactionString = new StringBuilder(reactionString.substring(0, reactionString.length() - 3));
+ return reactionString.toString();
};
};
}
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/index/genericreaction/AlcoholDehydration.java b/src/main/java/com/petrolpark/destroy/chemistry/index/genericreaction/AlcoholDehydration.java
index 5ef4e029a..c8b48fb88 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/index/genericreaction/AlcoholDehydration.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/index/genericreaction/AlcoholDehydration.java
@@ -32,7 +32,7 @@ public Reaction generateReaction(GenericReactant reactant) {
for (Atom carbon : structure.moveTo(alcohol.carbon).getBondedAtomsOfElement(Element.CARBON)) {
List hydrogens = structure.moveTo(carbon).getBondedAtomsOfElement(Element.HYDROGEN);
List carbons = structure.getBondedAtomsOfElement(Element.CARBON);
- if (hydrogens.size() + carbons.size() != 4 || hydrogens.size() == 0) continue; // Don't form from non-sp3 alkyl carbons
+ if (hydrogens.size() + carbons.size() != 4 || hydrogens.isEmpty()) continue; // Don't form from non-sp3 alkyl carbons
Formula productStructure = structure.shallowCopy();
productStructure
.remove(hydrogens.get(0))
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/index/genericreaction/AlkeneHydrolysis.java b/src/main/java/com/petrolpark/destroy/chemistry/index/genericreaction/AlkeneHydrolysis.java
index 0d8889a52..6f383d0d9 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/index/genericreaction/AlkeneHydrolysis.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/index/genericreaction/AlkeneHydrolysis.java
@@ -29,6 +29,4 @@ public void transform(ReactionBuilder builder) {
.addCatalyst(DestroyMolecules.SULFURIC_ACID, 1)
.activationEnergy(200f);
};
-
-
};
diff --git a/src/main/java/com/petrolpark/destroy/compat/jei/category/ReactionCategory.java b/src/main/java/com/petrolpark/destroy/compat/jei/category/ReactionCategory.java
index a7fe58994..7e0130188 100644
--- a/src/main/java/com/petrolpark/destroy/compat/jei/category/ReactionCategory.java
+++ b/src/main/java/com/petrolpark/destroy/compat/jei/category/ReactionCategory.java
@@ -88,7 +88,7 @@ public Collection getHoverableTexts(ReactionRecipe reci
protected String getTranslationKey(ReactionRecipe recipe) {
Reaction reaction = recipe.getReaction();
- return reaction.getNameSpace() + ".reaction." + reaction.getId();
+ return reaction.getNamespace() + ".reaction." + reaction.getId();
};
@Override
From b53b72056d64921b8bb123c99301168dff2f1de9 Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Mon, 19 Feb 2024 14:00:23 +0100
Subject: [PATCH 04/20] Optimised some parts to use primitive types instead of
wrappers
---
.../block/entity/PollutometerBlockEntity.java | 2 +-
.../petrolpark/destroy/chemistry/Atom.java | 2 +-
.../petrolpark/destroy/chemistry/Element.java | 2 +-
.../petrolpark/destroy/chemistry/Formula.java | 10 ++++----
.../petrolpark/destroy/chemistry/Mixture.java | 2 +-
.../destroy/chemistry/Molecule.java | 10 ++++----
.../destroy/chemistry/Reaction.java | 23 ++++++-------------
.../chemistry/index/DestroyReactions.java | 2 --
.../chemistry/index/group/CarbonylGroup.java | 2 +-
.../destroy/chemistry/serializer/Edge.java | 3 +--
.../destroy/chemistry/serializer/Node.java | 13 ++++-------
.../renderer/SeismometerItemRenderer.java | 2 +-
.../com/petrolpark/destroy/util/vat/Vat.java | 13 ++---------
13 files changed, 31 insertions(+), 55 deletions(-)
diff --git a/src/main/java/com/petrolpark/destroy/block/entity/PollutometerBlockEntity.java b/src/main/java/com/petrolpark/destroy/block/entity/PollutometerBlockEntity.java
index 3d9fd58f6..2c01298e3 100644
--- a/src/main/java/com/petrolpark/destroy/block/entity/PollutometerBlockEntity.java
+++ b/src/main/java/com/petrolpark/destroy/block/entity/PollutometerBlockEntity.java
@@ -56,7 +56,7 @@ public PollutionType getPollutionType() {
return pollutionType;
};
- private void setPollutionType(Integer pollutionTypeIndex) {
+ private void setPollutionType(int pollutionTypeIndex) {
this.pollutionType = PollutionType.values()[pollutionTypeIndex];
};
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Atom.java b/src/main/java/com/petrolpark/destroy/chemistry/Atom.java
index 337d73835..076bfc5ad 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Atom.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Atom.java
@@ -46,7 +46,7 @@ public PartialModel getPartial() {
/**
* Whether this is Atom is a {@link Element#HYDROGEN Hydrogen}.
*/
- public Boolean isHydrogen() {
+ public boolean isHydrogen() {
return element == Element.HYDROGEN;
};
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Element.java b/src/main/java/com/petrolpark/destroy/chemistry/Element.java
index 9a7e13e01..4f12cc04f 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Element.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Element.java
@@ -70,7 +70,7 @@ public Float getElectronegativity() {
return this.electronegativity;
};
;
- public Boolean isValidValency(double valency) {
+ public boolean isValidValency(double valency) {
for (double possibleValency : valencies) {
if (Math.abs(possibleValency - valency) < 0.000001d) return true;
};
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Formula.java b/src/main/java/com/petrolpark/destroy/chemistry/Formula.java
index 420104182..cd33ef959 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Formula.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Formula.java
@@ -274,7 +274,7 @@ public static Formula joinFormulae(Formula formula1, Formula formula2, BondType
* @see Formula#startingAtom How sub-Formulae are added
* @see Formula#joinFormulae Connecting Formulae of which you are unaware of the specific structure of each Formula, such as in {@link GenericReaction Generic Reactions}
*/
- public Formula addGroup(Formula group, Boolean isSideGroup, BondType bondType) {
+ public Formula addGroup(Formula group, boolean isSideGroup, BondType bondType) {
if (topology.atomsAndLocations.stream().anyMatch(pair -> pair.getSecond() == currentAtom)) {
throw new FormulaModificationException(this, "Cannot modify Atoms in cycle");
};
@@ -801,7 +801,7 @@ private static Branch getMaximumBranch(Atom startAtom, Map> str
Branch maximumBranch = new Branch(currentNode);
- Boolean nodesAdded = true;
+ boolean nodesAdded = true;
while (nodesAdded) {
nodesAdded = false;
Map connectedUnvisitedNodesAndTheirBondTypes = new HashMap<>();
@@ -920,7 +920,7 @@ private static void addBondBetweenAtoms(Map> structureToMutate,
private static Formula groupFromString(List symbols) {
Formula formula = Formula.nothing();
- Boolean hasFormulaBeenInstantiated = false;
+ boolean hasFormulaBeenInstantiated = false;
BondType nextAtomBond = BondType.SINGLE;
@@ -943,7 +943,7 @@ private static Formula groupFromString(List symbols) {
List subSymbols = new ArrayList<>();
while (brackets > 0) { //Keep going until the closing bracket is found
i++; //move to next Atom
- Boolean added = false;
+ boolean added = false;
for (int j = 0; j < symbols.get(i).length(); j++) {
char c = symbols.get(i).charAt(j);
if (c == ')') {
@@ -968,7 +968,7 @@ private static Formula groupFromString(List symbols) {
symbol = symbols.get(i);
};
- Boolean stripBond = true; //start by assuming by a =/#/~ will have to be taken off the end of the Symbol
+ boolean stripBond = true; //start by assuming by a =/#/~ will have to be taken off the end of the Symbol
nextAtomBond = BondType.SINGLE; //start by assuming the next Bond will be single
switch (symbol.charAt(symbol.length() - 1)) {
case '=':
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java b/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
index 37e3b8f8a..887ab3d99 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
@@ -954,7 +954,7 @@ private void refreshPossibleReactions() {
* This checks if all necessary Reactants were present before proceeding, however this leads to some infinite loops
* where one half of a reversible Reaction would happen one tick, then the other one the next, etc.
*/
- Boolean reactionHasAllReactants = true;
+ boolean reactionHasAllReactants = true;
for (Molecule necessaryReactantOrCatalyst : reaction.getOrders().keySet()) {
if (getConcentrationOf(necessaryReactantOrCatalyst) == 0) {
reactionHasAllReactants = false;
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java b/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
index faebac777..4119b7783 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
@@ -545,11 +545,11 @@ public static class MoleculeBuilder {
private Molecule molecule;
- private Boolean hasForcedDensity = false; // Whether this molecule has a custom density or it should be calculated
- private Boolean hasForcedBoilingPoint = false; // Whether this molecule has a custom boiling point or it should be calculated
- private Boolean hasForcedDipoleMoment = false; // Whether this molecule has a forced dipole moment or it should be calculated
- private Boolean hasForcedMolarHeatCapacity = false; // Whether this molecule has a forced specific heat capacity or it should be calculated
- private Boolean hasForcedLatentHeat = false; // Whether this molecule has a forced latent heat of fusion or it should be calculated
+ private boolean hasForcedDensity = false; // Whether this molecule has a custom density or it should be calculated
+ private boolean hasForcedBoilingPoint = false; // Whether this molecule has a custom boiling point or it should be calculated
+ private boolean hasForcedDipoleMoment = false; // Whether this molecule has a forced dipole moment or it should be calculated
+ private boolean hasForcedMolarHeatCapacity = false; // Whether this molecule has a forced specific heat capacity or it should be calculated
+ private boolean hasForcedLatentHeat = false; // Whether this molecule has a forced latent heat of fusion or it should be calculated
private String translationKey;
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
index 5be7f64e7..7576f23f2 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
@@ -1,11 +1,6 @@
package com.petrolpark.destroy.chemistry;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Optional;
-import java.util.Set;
+import java.util.*;
import java.util.Map.Entry;
import java.util.function.BiFunction;
import java.util.function.Consumer;
@@ -122,15 +117,15 @@ private Reaction(String nameSpace) {
/**
* Whether this Molecule gets consumed in this Reaction (does not include catalysts).
*/
- public Boolean containsReactant(Molecule molecule) {
+ public boolean containsReactant(Molecule molecule) {
return this.reactants.keySet().contains(molecule);
};
/**
* Whether this Molecule is created in this Reaction.
*/
- public Boolean containsProduct(Molecule molecule) {
- return this.products.keySet().contains(molecule);
+ public boolean containsProduct(Molecule molecule) {
+ return this.products.containsKey(molecule);
};
/**
@@ -282,7 +277,7 @@ public String getNamespace() {
* @param reactant
* @return {@code 0} if this Molecule is not a reactant
*/
- public Integer getReactantMolarRatio(Molecule reactant) {
+ public int getReactantMolarRatio(Molecule reactant) {
if (!reactants.keySet().contains(reactant)) {
return 0;
} else {
@@ -295,12 +290,8 @@ public Integer getReactantMolarRatio(Molecule reactant) {
* @param product
* @return {@code 0} if this Molecule is not a product
*/
- public Integer getProductMolarRatio(Molecule product) {
- if (!products.keySet().contains(product)) {
- return 0;
- } else {
- return products.get(product);
- }
+ public int getProductMolarRatio(Molecule product) {
+ return Objects.requireNonNullElse(products.get(product), 0);
};
/**
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java
index 893caadfb..4ff178f39 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyReactions.java
@@ -12,8 +12,6 @@
import com.simibubi.create.AllItems;
import com.simibubi.create.AllTags;
import net.minecraft.world.item.Items;
-import org.openzen.zencode.java.ZenCodeType;
-
public class DestroyReactions {
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/index/group/CarbonylGroup.java b/src/main/java/com/petrolpark/destroy/chemistry/index/group/CarbonylGroup.java
index dcb56ce2b..a63b6c405 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/index/group/CarbonylGroup.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/index/group/CarbonylGroup.java
@@ -15,7 +15,7 @@ public class CarbonylGroup extends Group {
*/
public final boolean isKetone;
- public CarbonylGroup(Atom carbon, Atom oxygen, Boolean isKetone) {
+ public CarbonylGroup(Atom carbon, Atom oxygen, boolean isKetone) {
super();
this.carbon = carbon;
this.oxygen = oxygen;
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/serializer/Edge.java b/src/main/java/com/petrolpark/destroy/chemistry/serializer/Edge.java
index d15b14161..bf0308858 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/serializer/Edge.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/serializer/Edge.java
@@ -6,13 +6,12 @@ public class Edge {
public BondType bondType;
private Node srcNode;
private Node destNode;
- public Boolean marked;
+ public boolean marked = false;
public Edge(Node srcNode, Node destNode, BondType bondType) {
this.srcNode = srcNode;
this.destNode = destNode;
this.bondType = bondType;
- marked = false;
};
public Node getSourceNode() {
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/serializer/Node.java b/src/main/java/com/petrolpark/destroy/chemistry/serializer/Node.java
index 36c131986..e111d7627 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/serializer/Node.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/serializer/Node.java
@@ -12,22 +12,19 @@
import com.petrolpark.destroy.chemistry.Bond.BondType;
public class Node {
- private Atom atom;
- public Boolean visited;
- private List edges;
+ private final Atom atom;
+ public boolean visited = false;
private Branch branch;
- private Map sideBranches;
+ private final List edges = new ArrayList<>();
+ private final Map sideBranches = new HashMap<>();
public Node(Atom atom) {
this.atom = atom;
- visited = false;
- edges = new ArrayList<>();
- sideBranches = new HashMap<>();
};
public String serialize() {
String string = getAtom().getElement().getSymbol();
- Boolean isTerminal = true;
+ boolean isTerminal = true;
Edge nextEdge = null;
for (Edge edge : edges) {
if (edge.getSourceNode() == this) {
diff --git a/src/main/java/com/petrolpark/destroy/item/renderer/SeismometerItemRenderer.java b/src/main/java/com/petrolpark/destroy/item/renderer/SeismometerItemRenderer.java
index be7eda181..2da21aba4 100644
--- a/src/main/java/com/petrolpark/destroy/item/renderer/SeismometerItemRenderer.java
+++ b/src/main/java/com/petrolpark/destroy/item/renderer/SeismometerItemRenderer.java
@@ -31,7 +31,7 @@ public class SeismometerItemRenderer extends CustomRenderedItemModelRenderer {
private Boolean spike;
private static int spikeNextPage; // Whether the next page to be shown should have a spike on it
- private static LerpedFloat angle;
+ private static final LerpedFloat angle;
static {
angle = LerpedFloat.angular().startWithValue(0d);
diff --git a/src/main/java/com/petrolpark/destroy/util/vat/Vat.java b/src/main/java/com/petrolpark/destroy/util/vat/Vat.java
index 83195ce65..e50d7f1d3 100644
--- a/src/main/java/com/petrolpark/destroy/util/vat/Vat.java
+++ b/src/main/java/com/petrolpark/destroy/util/vat/Vat.java
@@ -1,10 +1,6 @@
package com.petrolpark.destroy.util.vat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Optional;
+import java.util.*;
import javax.annotation.Nullable;
@@ -95,12 +91,7 @@ public static Optional tryConstruct(Level level, BlockPos pos, BlockPos con
EnumMap dimensions = new EnumMap<>(Direction.class) {
@Override
public Integer get(Object key) {
- Integer value = super.get(key);
- if (value == null) {
- return 0;
- } else {
- return value;
- }
+ return Objects.requireNonNullElse(super.get(key), 0);
};
};
From 82d9469a843bda5e3860c7f34b13b332cb266413 Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Mon, 19 Feb 2024 15:46:51 +0100
Subject: [PATCH 05/20] Optimised Map operations
---
.../behaviour/ExtendedBasinBehaviour.java | 10 +-
.../level/pollution/LevelPollution.java | 8 +-
.../petrolpark/destroy/chemistry/Element.java | 14 +-
.../petrolpark/destroy/chemistry/Formula.java | 69 +++++----
.../petrolpark/destroy/chemistry/Mixture.java | 136 +++++++++---------
.../destroy/chemistry/Reaction.java | 12 +-
.../destroy/chemistry/ReadOnlyMixture.java | 8 +-
.../chemistry/index/DestroyGroupFinder.java | 1 +
.../destroy/recipe/ReactionInBasinRecipe.java | 24 ++--
.../petrolpark/destroy/util/CropMutation.java | 42 +++---
.../world/explosion/SmartExplosion.java | 30 ++--
11 files changed, 163 insertions(+), 191 deletions(-)
diff --git a/src/main/java/com/petrolpark/destroy/block/entity/behaviour/ExtendedBasinBehaviour.java b/src/main/java/com/petrolpark/destroy/block/entity/behaviour/ExtendedBasinBehaviour.java
index 6e7f9ccfc..b1f8602c5 100644
--- a/src/main/java/com/petrolpark/destroy/block/entity/behaviour/ExtendedBasinBehaviour.java
+++ b/src/main/java/com/petrolpark/destroy/block/entity/behaviour/ExtendedBasinBehaviour.java
@@ -53,10 +53,12 @@ public void tick() {
};
public void enactReactionResults(BasinBlockEntity basin) {
-
- for (ReactionResult result : reactionResults.keySet()) {
- for (int i = 0; i < reactionResults.get(result); i++) result.onBasinReaction(basin.getLevel(), basin);
- };
+ for(Map.Entry reactionEntry : reactionResults.entrySet()) {
+ ReactionResult result = reactionEntry.getKey();
+ for(int i = 0; i < reactionEntry.getValue(); i++) {
+ result.onBasinReaction(basin.getLevel(), basin);
+ }
+ }
reactionResults.clear();
if (!evaporatedFluid.isEmpty()) {
diff --git a/src/main/java/com/petrolpark/destroy/capability/level/pollution/LevelPollution.java b/src/main/java/com/petrolpark/destroy/capability/level/pollution/LevelPollution.java
index 48bc64edf..8ca00b7a2 100644
--- a/src/main/java/com/petrolpark/destroy/capability/level/pollution/LevelPollution.java
+++ b/src/main/java/com/petrolpark/destroy/capability/level/pollution/LevelPollution.java
@@ -123,9 +123,7 @@ public void saveNBTData(CompoundTag tag) {
};
public void loadNBTData(CompoundTag tag) {
- levels.keySet().forEach((pollutionType) -> {
- levels.replace(pollutionType, tag.getInt(pollutionType.name()));
- });
+ levels.replaceAll((pollutionType, level) -> tag.getInt(pollutionType.name()));
hasPollutionEverBeenMaxed = tag.getBoolean("EverMaxed");
hasPollutionEverBeenFullyReduced = tag.getBoolean("EverReduced");
updateTemperature();
@@ -135,8 +133,8 @@ public void updateTemperature() {
outdoorTemperature = 289f;
if (!PollutionHelper.pollutionEnabled() || !DestroyAllConfigs.SERVER.pollution.temperatureAffected.get()) return;
outdoorTemperature +=
- (levels.get(PollutionType.GREENHOUSE) / PollutionType.GREENHOUSE.max) * 20f
- + (levels.get(PollutionType.OZONE_DEPLETION) / PollutionType.OZONE_DEPLETION.max) * 4f;
+ ((float) levels.get(PollutionType.GREENHOUSE) / PollutionType.GREENHOUSE.max) * 20f
+ + ((float) levels.get(PollutionType.OZONE_DEPLETION) / PollutionType.OZONE_DEPLETION.max) * 4f;
};
/**
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Element.java b/src/main/java/com/petrolpark/destroy/chemistry/Element.java
index 4f12cc04f..6f3b3c347 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Element.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Element.java
@@ -37,20 +37,20 @@ public enum Element {
//LEAD("Pb", 207.20f, 1.8f)
;
- private String symbol;
- private Float mass;
- private Float electronegativity;
- private double[] valencies;
+ private final String symbol;
+ private final float mass;
+ private final float electronegativity;
+ private final double[] valencies;
- private Function geometryOverride;
+ private final Function geometryOverride;
private PartialModel partial;
- private Element(String symbol, Float mass, Float electronegativity, double[] valencies) {
+ Element(String symbol, Float mass, Float electronegativity, double[] valencies) {
this(symbol, mass, electronegativity, valencies, null);
};
- private Element(String symbol, Float mass, Float electronegativity, double[] valencies, Function geometryOverride) {
+ Element(String symbol, Float mass, Float electronegativity, double[] valencies, Function geometryOverride) {
this.symbol = symbol;
this.mass = mass;
this.electronegativity = electronegativity;
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Formula.java b/src/main/java/com/petrolpark/destroy/chemistry/Formula.java
index cd33ef959..c9c1dd7fe 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Formula.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Formula.java
@@ -492,8 +492,10 @@ public void updateSideChainStructures() {
if (structure.get(atom) == null) continue checkAllAtomsInSideChain; // If this Atom has no Bonds, don't do anything
addAllBondsForAtom: for (Bond bond : structure.get(atom)) {
Atom potentialNewAtom = bond.getDestinationAtom();
- if (topology.formula.structure.keySet().contains(potentialNewAtom)) continue addAllBondsForAtom; // Don't add Bonds to Atoms which are part of the Topology (and therefore not part of the side branch)
- if (!sideChainFormula.structure.keySet().contains(potentialNewAtom)) newSideChainFormula.structure.put(potentialNewAtom, structure.get(potentialNewAtom)); // Add any as-of-yet unknown Atoms to the side branch's structure
+ if (topology.formula.structure.containsKey(potentialNewAtom)) continue addAllBondsForAtom; // Don't add Bonds to Atoms which are part of the Topology (and therefore not part of the side branch)
+ if (!sideChainFormula.structure.containsKey(potentialNewAtom)) {
+ newSideChainFormula.structure.put(potentialNewAtom, structure.get(potentialNewAtom)); // Add any as-of-yet unknown Atoms to the side branch's structure
+ }
bonds.add(bond);
};
newSideChainFormula.structure.put(atom, bonds);
@@ -772,14 +774,15 @@ public Branch getRenderBranch() {
*/
private static Map> shallowCopyStructure(Map> structureToCopy) {
Map> newStructure = new HashMap<>();
- for (Atom atom : structureToCopy.keySet()) {
- List oldBonds = structureToCopy.get(atom);
- List newBonds = new ArrayList<>();
+ for(Entry> moleculeEntry : structureToCopy.entrySet()) {
+ Atom atom = moleculeEntry.getKey();
+ List oldBonds = moleculeEntry.getValue();
+ List newBonds = new ArrayList<>(oldBonds.size());
for (Bond oldBond : oldBonds) {
newBonds.add(new Bond(atom, oldBond.getDestinationAtom(), oldBond.getType()));
};
newStructure.put(atom, newBonds);
- };
+ }
return newStructure;
};
@@ -813,16 +816,17 @@ private static Branch getMaximumBranch(Atom startAtom, Map> str
};
if (connectedUnvisitedNodesAndTheirBondTypes.size() == 1) {
- Node onlyNode = connectedUnvisitedNodesAndTheirBondTypes.keySet().iterator().next();
- maximumBranch.add(onlyNode, connectedUnvisitedNodesAndTheirBondTypes.get(onlyNode));
+ Entry nodeEntry = connectedUnvisitedNodesAndTheirBondTypes.entrySet().iterator().next();
+ Node onlyNode = nodeEntry.getKey();
+ maximumBranch.add(onlyNode, nodeEntry.getValue());
currentNode = onlyNode;
nodesAdded = true;
- } else if (connectedUnvisitedNodesAndTheirBondTypes.size() != 0) {
+ } else if (!connectedUnvisitedNodesAndTheirBondTypes.isEmpty()) {
Map connectedBranchesAndTheirBondTypes = new HashMap<>();
- for (Node node : connectedUnvisitedNodesAndTheirBondTypes.keySet()) {
-
+ for(Entry nodeBondEntry : connectedUnvisitedNodesAndTheirBondTypes.entrySet()) {
+ Node node = nodeBondEntry.getKey();
Map> newStructure = shallowCopyStructure(structure); // Create a new Structure which does not include the current Node
Bond bondToRemove = null;
for (Bond bond : structure.get(node.getAtom())) {
@@ -836,15 +840,13 @@ private static Branch getMaximumBranch(Atom startAtom, Map> str
};
newStructure.remove(currentNode.getAtom());
-
+
Branch branch = getMaximumBranch(node.getAtom(), newStructure);
- connectedBranchesAndTheirBondTypes.put(branch, connectedUnvisitedNodesAndTheirBondTypes.get(node));
- };
+ connectedBranchesAndTheirBondTypes.put(branch, nodeBondEntry.getValue());
+ }
List orderedConnectedBranches = new ArrayList<>(connectedBranchesAndTheirBondTypes.keySet());
- Collections.sort(orderedConnectedBranches, (b1, b2) -> {
- return b2.getMass().compareTo(b1.getMass());
- });
+ orderedConnectedBranches.sort((b1, b2) -> b2.getMass().compareTo(b1.getMass()));
Branch biggestBranch = orderedConnectedBranches.get(0);
maximumBranch.add(biggestBranch, connectedBranchesAndTheirBondTypes.get(biggestBranch));
@@ -854,10 +856,7 @@ private static Branch getMaximumBranch(Atom startAtom, Map> str
for (Branch sideBranch : orderedConnectedBranches) {
currentNode.addSideBranch(sideBranch, connectedBranchesAndTheirBondTypes.get(sideBranch));
};
-
- } else {
-
- };
+ }
};
return maximumBranch;
@@ -1003,9 +1002,9 @@ private static Formula groupFromString(List symbols) {
hasFormulaBeenInstantiated = true;
};
- for (Formula group : groupsToAdd.keySet()) { //add all side Groups to the current Atom
- formula.addGroup(group, true, groupsToAdd.get(group));
- };
+ for(Entry groupEntry : groupsToAdd.entrySet()) {
+ formula.addGroup(groupEntry.getKey(), true, groupEntry.getValue());
+ }
i++; //move to the next Atom
};
@@ -1028,17 +1027,17 @@ private static BondType trailingBondType(String symbol) {
*/
private static Map> stripHydrogens(Map> structure) {
Map> newStructure = new HashMap<>();
- for (Atom atom : structure.keySet()) {
- List bondsToAdd = new ArrayList<>();
- for (Bond bond : structure.get(atom)) {
- if (!bond.getDestinationAtom().isHydrogen()) {
- bondsToAdd.add(bond);
- };
- };
- if (!atom.isHydrogen()) {
- newStructure.put(atom, bondsToAdd);
- };
- };
+ for(Entry> moleculeEntry : structure.entrySet()) {
+ Atom atom = moleculeEntry.getKey();
+ if(atom.isHydrogen()) continue;
+ List bondStructure = moleculeEntry.getValue();
+ List bondsToAdd = new ArrayList<>(bondStructure.size());
+ for(Bond bond : bondStructure) {
+ if(bond.getDestinationAtom().isHydrogen()) continue;
+ bondsToAdd.add(bond);
+ }
+ newStructure.put(atom, bondsToAdd);
+ }
return newStructure;
};
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java b/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
index 887ab3d99..a4d69a4f9 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
@@ -27,6 +27,7 @@
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.world.item.ItemStack;
+import org.checkerframework.checker.units.qual.A;
public class Mixture extends ReadOnlyMixture {
@@ -52,7 +53,7 @@ public class Mixture extends ReadOnlyMixture {
/**`
* Every {@link Molecule} in this Mixture that has a {@link Group functional Group}, indexed by the {@link Group#getType Type} of that Group.
- * Molecules are stored as {@link com.petrolpark.destroy.chemistry.genericReaction.GenericReactant Generic Reactants}.
+ * Molecules are stored as {@link com.petrolpark.destroy.chemistry.genericreaction.GenericReactant Generic Reactants}.
* Molecules which have multiple of the same Group are indexed for each occurence of the Group.
*/
protected Map, List>> groupIDsAndMolecules;
@@ -230,7 +231,7 @@ public List getContents(boolean excludeNovel) {
* @return A new Mixture instance
*/
public static Mixture mix(Map mixtures) {
- if (mixtures.size() == 0) return new Mixture();
+ if (mixtures.isEmpty()) return new Mixture();
if (mixtures.size() == 1) return mixtures.keySet().iterator().next();
Mixture resultMixture = new Mixture();
Map moleculesAndMoles = new HashMap<>(); // A Map of all Molecules to their quantity in moles (not their concentration)
@@ -247,12 +248,12 @@ public static Mixture mix(Map mixtures) {
Molecule molecule = entry.getKey();
float concentration = entry.getValue();
moleculesAndMoles.merge(molecule, concentration * amount, (m1, m2) -> m1 + m2); // Add the Molecule to the map if it's a new one, or increase the existing molar quantity otherwise
- totalEnergy += molecule.getMolarHeatCapacity() * concentration * mixture.temperature * amount; // Add all the energy that would be required to raise this Molecule from 0K to its current temperature
- totalEnergy += molecule.getLatentHeat() * concentration * mixture.states.get(molecule) * amount; // Add all the energy that would be required to vaporise this Molecule, if necessary
+ totalEnergy += (float) (molecule.getMolarHeatCapacity() * concentration * mixture.temperature * amount); // Add all the energy that would be required to raise this Molecule from 0K to its current temperature
+ totalEnergy += (float) (molecule.getLatentHeat() * concentration * mixture.states.get(molecule) * amount); // Add all the energy that would be required to vaporise this Molecule, if necessary
};
for (Entry entry : mixture.reactionResults.entrySet()) {
- reactionResultsAndMoles.merge(entry.getKey(), entry.getValue() * amount, (r1, r2) -> r1 + r2); // Same for Reaction Results
+ reactionResultsAndMoles.merge(entry.getKey(), entry.getValue() * amount, Double::sum); // Same for Reaction Results
};
};
@@ -359,12 +360,11 @@ public void reactForTick(ReactionContext context, int cycles) {
};
// Check now if we have actually reached equilibrium or if that was a false assumption at the start
- for (Molecule molecule : oldContents.keySet()) {
- if (!areVeryClose(oldContents.get(molecule), getConcentrationOf(molecule))) { // If there's something that has changed concentration noticeably in this tick...
- equilibrium = false; // ...we cannot have reached equilibrium
- };
- };
-
+ for(Entry moleculeEntry : oldContents.entrySet()) {
+ if(areVeryClose(moleculeEntry.getValue(), getConcentrationOf(moleculeEntry.getKey()))) continue;
+ equilibrium = false;
+ break;
+ }
if (shouldRefreshPossibleReactions) { // If we added a new Molecule at any point
refreshPossibleReactions();
};
@@ -393,7 +393,7 @@ public void reactForTick(ReactionContext context, int cycles) {
/**
* Add or take heat from this Mixture. This will boil/condense Molecules and change the temperature.
- * @param energy In joules per bucket
+ * @param energyDensity In joules per bucket
*/
public void heat(float energyDensity) {
float volumetricHeatCapacity = getVolumetricHeatCapacity();
@@ -421,7 +421,7 @@ public void heat(float energyDensity) {
heat(energyDensity - energyRequiredToFullyBoil); // Continue heating
} else { // If there is no leftover energy and the Molecule is still boiling
float boiled = energyDensity / (molecule.getLatentHeat() * getConcentrationOf(molecule)); // The proportion of all of the Molecule which is additionally boiled
- states.merge(molecule, boiled, (f1, f2) -> f1 + f2);
+ states.merge(molecule, boiled, Float::sum);
};
equilibrium = false; // Equilibrium is broken when a Molecule evaporates
@@ -460,9 +460,9 @@ public void heat(float energyDensity) {
};
/**
- * Enact all {@link Reactions} that {@link Reaction#getItemReactants involve Item Stacks}. This does not just
+ * Enact all {@link Reaction}s that {@link Reaction#getItemReactants involve Item Stacks}. This does not just
* include dissolutions, but Item-catalyzed Reactions too.
- * @param availableStacks The Item Stacks available to this Mixture. This Stacks in this List will be modified
+ * @param context Context of the reaction, contains the Item Stacks available to this Mixture. This Stacks in this List will be modified
* @param volume The amount of this Mixture there is, in buckets
*/
public void dissolveItems(ReactionContext context, double volume) {
@@ -479,8 +479,7 @@ public void dissolveItems(ReactionContext context, double volume) {
if (orderedReactions.isEmpty()) return; // Don't go any further if there aren't any items to dissolve
- Collections.sort(possibleReactions, (r1, r2) -> ((Float)calculateReactionRate(r1, context)).compareTo(calculateReactionRate(r2, context))); // Order the list of Item-consuming Reactions by rate, in case multiple of them want the same Item
-
+ possibleReactions.sort((r1, r2) -> Float.compare(calculateReactionRate(r1, context), calculateReactionRate(r2, context))); // Order the list of Item-consuming Reactions by rate, in case multiple of them want the same Item
tryEachReaction: for (Reaction reaction : orderedReactions) {
/*
@@ -509,15 +508,13 @@ public void dissolveItems(ReactionContext context, double volume) {
for (IItemReactant itemReactant : reaction.getItemReactants()) {
boolean validItemFound = false; // Start by assuming we haven't yet come across the right Stack
- for (ItemStack stackCopy : copiesAndStacks.keySet()) {
- if (itemReactant.isItemValid(stackCopy)) {
- validItemFound = true; // We have now found the right Stack
- if (!itemReactant.isCatalyst()) { // If this Item gets used up
- itemReactant.consume(stackCopy); // Consume the Stack copy so we know for future simulations that it can't be used
- reactantsAndStacks.put(itemReactant, copiesAndStacks.get(stackCopy)); // Store the actual Item Stack to be consumed later
- };
- };
- };
+ for(Entry stackToCopy : copiesAndStacks.entrySet()) {
+ ItemStack stackCopy = stackToCopy.getKey();
+ if(!itemReactant.isItemValid(stackCopy)) continue;
+ validItemFound = true;
+ itemReactant.consume(stackCopy);
+ reactantsAndStacks.put(itemReactant, stackToCopy.getValue());
+ }
if (!validItemFound) continue tryEachReaction; // If the simulation was a failure, move onto the next Reaction.
};
@@ -734,14 +731,13 @@ public ReactionInBasinResult reactInBasin(int volume, List availableS
public Map getCompletedResults(double volumeInBuckets) {
Map results = new HashMap<>();
if (reactionResults.isEmpty()) return results;
- for (ReactionResult result : reactionResults.keySet()) {
-
- if (result.isOneOff()) {
+ for(Entry reactionEntry : reactionResults.entrySet()) {
+ ReactionResult result = reactionEntry.getKey();
+ if(result.isOneOff()) {
results.put(result, 1);
continue;
- };
-
- Float molesPerBucketOfReaction = reactionResults.get(result);
+ }
+ float molesPerBucketOfReaction = reactionEntry.getValue();
int numberOfResult = (int) (volumeInBuckets * molesPerBucketOfReaction / result.getRequiredMoles());
if (numberOfResult == 0) continue;
@@ -749,7 +745,7 @@ public Map getCompletedResults(double volumeInBuckets)
reactionResults.replace(result, molesPerBucketOfReaction - numberOfResult * result.getRequiredMoles() / (float)volumeInBuckets);
results.put(result, numberOfResult);
- };
+ }
// reactionResults.keySet().removeIf(result -> { // Remove any one-off Results and Results which have run out
// return result.isOneOff() || areVeryClose(reactionResults.get(result), 0f);
// });
@@ -810,7 +806,7 @@ private boolean internalAddMolecule(Molecule molecule, float concentration, bool
if (!molecule.isNovel()) super.addMolecule(molecule, concentration);
List> functionalGroups = molecule.getFunctionalGroups();
- if (functionalGroups.size() != 0) {
+ if (!functionalGroups.isEmpty()) {
for (Group group : functionalGroups) { // Unparameterised raw type
addGroupToMixture(molecule, group); // Unchecked conversion
};
@@ -843,10 +839,8 @@ private boolean internalAddMolecule(Molecule molecule, float concentration, bool
private > void addGroupToMixture(Molecule molecule, G group) {
GroupType groupType = group.getType();
- if (!groupIDsAndMolecules.containsKey(groupType)) {
- groupIDsAndMolecules.put(groupType, new ArrayList<>());
- };
- groupIDsAndMolecules.get(groupType).add(new GenericReactant<>(molecule, group));
+ groupIDsAndMolecules.computeIfAbsent(groupType, g -> new ArrayList<>())
+ .add(new GenericReactant<>(molecule, group));
};
/**
@@ -882,7 +876,7 @@ private Mixture removeMolecule(Molecule molecule) {
* @param shouldRefreshReactions Whether to alter the possible {@link Reaction Reactions} in the case that a new Molecule is added to the Mixture (should almost always be {@code true})
*/
private Mixture changeConcentrationOf(Molecule molecule, float change, boolean shouldRefreshReactions) {
- Float currentConcentration = getConcentrationOf(molecule);
+ float currentConcentration = getConcentrationOf(molecule);
if (!contents.containsKey(molecule) && change > 0f) internalAddMolecule(molecule, change, shouldRefreshReactions);
@@ -901,55 +895,55 @@ private Mixture changeConcentrationOf(Molecule molecule, float change, boolean s
*/
private float calculateReactionRate(Reaction reaction, ReactionContext context) {
float rate = reaction.getRateConstant(temperature) / (float) TICKS_PER_SECOND;
- for (Molecule molecule : reaction.getOrders().keySet()) {
- rate *= (float)Math.pow(getConcentrationOf(molecule), reaction.getOrders().get(molecule));
- };
+ for(Entry moleculeEntry : reaction.getOrders().entrySet()) {
+ rate *= (float) Math.pow(getConcentrationOf(moleculeEntry.getKey()), moleculeEntry.getValue());
+ }
if (reaction.needsUV()) rate *= context.UVPower;
return rate;
};
/**
- * Determine all {@link Reaction Reactions} - including {@link GenericReactions Generic Reactions} that are possible with the {@link Molecule Molecules} in this Mixture,
+ * Determine all {@link Reaction Reactions} - including {@link GenericReaction Generic Reactions} that are possible with the {@link Molecule Molecules} in this Mixture,
* and update the {@link Mixture#possibleReactions stored possible Reactions} accordingly.
* This should be called whenever new Molecules have been {@link Mixture#addMolecule added} to the Mixture, or a Molecule has been removed entirely, but rarely otherwise.
*/
private void refreshPossibleReactions() {
- possibleReactions = new ArrayList<>();
+ ArrayList possibleReactions = new ArrayList<>();
Set newPossibleReactions = new HashSet<>();
// Generate specific Generic Reactions
- for (GroupType> groupType : groupIDsAndMolecules.keySet()) { // Only search for Generic Reactions of Groups present in this Molecule
- checkEachGenericReaction: for (GenericReaction genericReaction : Group.getReactionsOfGroupByID(groupType)) {
-
- if (genericReaction.involvesSingleGroup()) { // Generic Reactions involving only one functional Group
- newPossibleReactions.addAll(specifySingleGroupGenericReactions(genericReaction, groupIDsAndMolecules.get(groupType)));
-
- } else { // Generic Reactions involving two functional Groups
- if (!(genericReaction instanceof DoubleGroupGenericReaction, ?> dggr)) continue checkEachGenericReaction; // This check should never fail
- if (groupType != dggr.getFirstGroupType()) continue checkEachGenericReaction; // Only generate Reactions when we're dealing with the first Group type
-
- GroupType> secondGroupType = dggr.getSecondGroupType();
- if (!groupIDsAndMolecules.keySet().contains(secondGroupType)) continue checkEachGenericReaction; // We can't do this generic reaction if we only have one group type
-
- List, GenericReactant>>> reactantPairs = new ArrayList<>();
- for (GenericReactant> firstGenericReactant : groupIDsAndMolecules.get(groupType)) {
- for (GenericReactant> secondGenericReactant : groupIDsAndMolecules.get(secondGroupType)) {
- reactantPairs.add(Pair.of(firstGenericReactant, secondGenericReactant));
- };
+ for(Entry, List>> reactionEntry : groupIDsAndMolecules.entrySet()) {
+ GroupType> groupType = reactionEntry.getKey();
+ List> reactants = reactionEntry.getValue();
+ for(GenericReaction genericReaction : Group.getReactionsOfGroupByID(groupType)) {
+ if(genericReaction.involvesSingleGroup()) {
+ newPossibleReactions.addAll(specifySingleGroupGenericReactions(genericReaction, reactants));
+ continue;
+ }
+
+ if (!(genericReaction instanceof DoubleGroupGenericReaction, ?> dggr)) continue; // This check should never fail
+ if (groupType != dggr.getFirstGroupType()) continue; // Only generate Reactions when we're dealing with the first Group type
+
+ GroupType> secondGroupType = dggr.getSecondGroupType();
+ List> secondGroupReactants = groupIDsAndMolecules.get(secondGroupType);
+ if (secondGroupReactants == null) continue; // We can't do this generic reaction if we only have one group type
+
+ List, GenericReactant>>> reactantPairs = new ArrayList<>();
+ for (GenericReactant> firstGenericReactant : groupIDsAndMolecules.get(groupType)) {
+ for (GenericReactant> secondGenericReactant : secondGroupReactants) {
+ reactantPairs.add(Pair.of(firstGenericReactant, secondGenericReactant));
};
-
- newPossibleReactions.addAll(specifyDoubleGroupGenericReactions(dggr, reactantPairs));
};
- };
- };
+
+ newPossibleReactions.addAll(specifyDoubleGroupGenericReactions(dggr, reactantPairs));
+ }
+ }
//All Reactions
for (Molecule possibleReactant : contents.keySet()) {
newPossibleReactions.addAll(possibleReactant.getReactantReactions());
};
for (Reaction reaction : newPossibleReactions) {
- //possibleReactions.add(reaction);
-
/*
* This checks if all necessary Reactants were present before proceeding, however this leads to some infinite loops
* where one half of a reversible Reaction would happen one tick, then the other one the next, etc.
@@ -966,6 +960,8 @@ private void refreshPossibleReactions() {
};
};
+ this.possibleReactions = possibleReactions;
+
};
/**
@@ -974,8 +970,8 @@ private void refreshPossibleReactions() {
*
* For example, if the Generic Reaction supplied is the {@link com.petrolpark.destroy.chemistry.index.genericreaction.AlkeneHydrolysis hydration of an alkene},
* and reactants includes {@code destroy:ethene}, the returned collection will include a Reaction with {@code destroy:ethene} and {@code destroy:water} as reactants,
- * {@code destroy:ethanol} as a product, and all the appropriate rate constants and catalysts as defined in the {@link com.petrolpark.destroy.chemistry.index.AlkeneHydrolysis.AlkeneHydration#generateReaction generator}.
- *
+ * {@code destroy:ethanol} as a product, and all the appropriate rate constants and catalysts as defined in the {@link com.petrolpark.destroy.chemistry.index.genericreaction.AlkeneHydrolysis#generateReaction generator}.
+ *
* @param G The Group to which this Generic Reaction applies
* @param genericReaction
* @param reactants All {@link GenericReactant Reactants} that have the Group
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
index 7576f23f2..2e4e6d792 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
@@ -118,7 +118,7 @@ private Reaction(String nameSpace) {
* Whether this Molecule gets consumed in this Reaction (does not include catalysts).
*/
public boolean containsReactant(Molecule molecule) {
- return this.reactants.keySet().contains(molecule);
+ return this.reactants.containsKey(molecule);
};
/**
@@ -278,11 +278,7 @@ public String getNamespace() {
* @return {@code 0} if this Molecule is not a reactant
*/
public int getReactantMolarRatio(Molecule reactant) {
- if (!reactants.keySet().contains(reactant)) {
- return 0;
- } else {
- return reactants.get(reactant);
- }
+ return reactants.getOrDefault(reactant, 0);
};
/**
@@ -291,7 +287,7 @@ public int getReactantMolarRatio(Molecule reactant) {
* @return {@code 0} if this Molecule is not a product
*/
public int getProductMolarRatio(Molecule product) {
- return Objects.requireNonNullElse(products.get(product), 0);
+ return products.getOrDefault(product, 0);
};
/**
@@ -398,7 +394,7 @@ public ReactionBuilder addReactant(Molecule molecule, int ratio, int order) {
* @see ReactionBuilder#addCatalyst(Molecule, int) Adding order with respect to a Molecule that is not a reactant (i.e. a catalyst)
*/
public ReactionBuilder setOrder(Molecule molecule, int order) {
- if (!reaction.reactants.keySet().contains(molecule)) error("Cannot modify order of a Molecule ("+ molecule.getFullID() +") that is not a reactant.");
+ if (!reaction.reactants.containsKey(molecule)) error("Cannot modify order of a Molecule ("+ molecule.getFullID() +") that is not a reactant.");
addCatalyst(molecule, order);
return this;
};
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/ReadOnlyMixture.java b/src/main/java/com/petrolpark/destroy/chemistry/ReadOnlyMixture.java
index 8865e6ee7..b8570ef78 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/ReadOnlyMixture.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/ReadOnlyMixture.java
@@ -180,11 +180,7 @@ public boolean isEmpty() {
* @return 0 if the Mixture does not contain the given Molecule
*/
public float getConcentrationOf(Molecule molecule) {
- if (contents.containsKey(molecule)) {
- return contents.get(molecule);
- } else {
- return 0f;
- }
+ return contents.getOrDefault(molecule, 0f);
};
/**
@@ -289,7 +285,7 @@ public List getContentsTooltip(boolean iupac, boolean monospace, bool
int i = 0;
List tooltip = new ArrayList<>();
List molecules = new ArrayList<>(contents.keySet());
- Collections.sort(molecules, (m1, m2) -> contents.get(m2).compareTo(contents.get(m1)));
+ molecules.sort((m1, m2) -> contents.get(m2).compareTo(contents.get(m1)));
Function quantityTranslator = q -> DestroyLang.translate(useMoles ? "tooltip.mixture_contents.moles" : "tooltip.mixture_contents.concentration", concentrationFormatter.format(q)).string();
int quantityLabelLength = quantityTranslator.apply(0f).length() + 2;
for (Molecule molecule : molecules) {
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyGroupFinder.java b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyGroupFinder.java
index 7fb2e67ce..1ee6b8d8b 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyGroupFinder.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyGroupFinder.java
@@ -32,6 +32,7 @@ public List> findGroups(Map> structure) {
List carbonsToIgnore = new ArrayList<>();
List carbonsToIgnoreForAlkenes = new ArrayList<>();
+ // this is scary
for (Atom carbon : structure.keySet()) {
if (carbon.getElement() != Element.CARBON || carbonsToIgnore.contains(carbon)) {
diff --git a/src/main/java/com/petrolpark/destroy/recipe/ReactionInBasinRecipe.java b/src/main/java/com/petrolpark/destroy/recipe/ReactionInBasinRecipe.java
index 60117a0cd..904a7e0d6 100644
--- a/src/main/java/com/petrolpark/destroy/recipe/ReactionInBasinRecipe.java
+++ b/src/main/java/com/petrolpark/destroy/recipe/ReactionInBasinRecipe.java
@@ -114,7 +114,7 @@ public static ReactionInBasinRecipe create(Collection availableFluid
Map reactionResults = new HashMap<>();
- gatherReactionResults(result.reactionresults(), reactionResults, builder); // Gather all
+ gatherReactionResults(result.reactionResults(), reactionResults, builder); // Gather all
ExtendedBasinBehaviour behaviour = basin.getBehaviour(ExtendedBasinBehaviour.TYPE);
behaviour.setReactionResults(reactionResults); // Schedule the Reaction Results to occur once the Mixing has finished
@@ -132,19 +132,23 @@ public static ReactionInBasinRecipe create(Collection availableFluid
};
private static void gatherReactionResults(Map resultsOfReaction, Map resultsToEnact, ProcessingRecipeBuilder builder) {
- for (ReactionResult reactionresult : resultsOfReaction.keySet()) {
- if (reactionresult instanceof CombinedReactionResult combinedResult) {
+ for(Map.Entry resultEntry : resultsOfReaction.entrySet()) {
+ ReactionResult reactionResult = resultEntry.getKey();
+ if (reactionResult instanceof CombinedReactionResult combinedResult) {
Map childMap = new HashMap<>();
for (ReactionResult childResult : combinedResult.getChildren()) {
childMap.put(childResult, resultsOfReaction.get(combinedResult));
};
gatherReactionResults(childMap, resultsToEnact, builder);
- } else if (reactionresult instanceof PrecipitateReactionResult precipitationResult) {
+ continue;
+ }
+ if (reactionResult instanceof PrecipitateReactionResult precipitationResult) {
builder.output(precipitationResult.getPrecipitate());
- } else { // Don't deal with precipitations in the normal way
- resultsToEnact.put(reactionresult, resultsOfReaction.get(reactionresult));
- };
- };
+ continue;
+ }
+ // Don't deal with precipitations in the normal way
+ resultsToEnact.put(reactionResult, resultEntry.getValue());
+ }
};
@Override
@@ -155,9 +159,9 @@ protected int getMaxFluidInputCount() {
/**
* The outcome of {@link com.petrolpark.destroy.chemistry.Reaction reacting} a {@link com.petrolpark.destroy.chemistry.Reaction Mixture} in a Basin.
* @param ticks The number of ticks it took for the Mixture to reach equilibrium
- * @param reactionresults The {@link com.petrolpark.destroy.chemistry.ReactionResult results} of Reacting this Mixture
+ * @param reactionResults The {@link com.petrolpark.destroy.chemistry.ReactionResult results} of Reacting this Mixture
* @param amount The amount (in mB) of resultant Mixture
*/
- public static record ReactionInBasinResult(int ticks, Map reactionresults, int amount) {};
+ public record ReactionInBasinResult(int ticks, Map reactionResults, int amount) {};
};
diff --git a/src/main/java/com/petrolpark/destroy/util/CropMutation.java b/src/main/java/com/petrolpark/destroy/util/CropMutation.java
index 8e1a6cd75..bb084e904 100644
--- a/src/main/java/com/petrolpark/destroy/util/CropMutation.java
+++ b/src/main/java/com/petrolpark/destroy/util/CropMutation.java
@@ -4,10 +4,7 @@
import com.simibubi.create.AllTags;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.function.Supplier;
import net.minecraft.world.level.block.Block;
@@ -67,35 +64,28 @@ private CropMutation(BlockState crop) { //used for when no Mutation occurs
* Let the system know that this Mutation exists.
*/
private void register() {
- if (!MUTATIONS.keySet().contains(startCrop.get())) {
- MUTATIONS.put(startCrop.get(), new ArrayList<>());
- };
- MUTATIONS.get(startCrop.get()).add(this);
+ MUTATIONS.computeIfAbsent(startCrop.get(), e -> new ArrayList<>()).add(this);
};
public static CropMutation getMutation(BlockState cropBlockState, BlockState blockUnder) {
Block cropBlock = cropBlockState.getBlock();
CropMutation mutation = null;
- checkAllEntries: for (Block crop : MUTATIONS.keySet()) {
- if (crop == cropBlock) {
- for (CropMutation possibleMutation : MUTATIONS.get(crop)) {
- if (possibleMutation.oreSpecific) {
- Supplier ore = possibleMutation.ore;
- if (ore != null && blockUnder.is(ore.get())) { // This is the bit it thinks is null
- mutation = possibleMutation;
- break checkAllEntries; // Prioritize Ore-specific Mutations
- };
- } else {
- mutation = possibleMutation;
- };
+ checker: for(Map.Entry> mutationEntry : MUTATIONS.entrySet()) {
+ Block crop = mutationEntry.getKey();
+ if(!crop.equals(cropBlock)) continue;
+ for(CropMutation possibleMutation : mutationEntry.getValue()) {
+ if(!possibleMutation.oreSpecific) {
+ mutation = possibleMutation;
+ continue;
+ }
+ Supplier ore = possibleMutation.ore;
+ if (ore != null && blockUnder.is(ore.get())) { // This is the bit it thinks is null
+ mutation = possibleMutation;
+ break checker; // Prioritize Ore-specific Mutations
};
- };
- };
- if (mutation == null) {
- return new CropMutation(cropBlockState);
- } else {
- return mutation;
+ }
}
+ return Objects.requireNonNullElse(mutation, new CropMutation(cropBlockState));
};
public Supplier getStartCropSupplier() {
diff --git a/src/main/java/com/petrolpark/destroy/world/explosion/SmartExplosion.java b/src/main/java/com/petrolpark/destroy/world/explosion/SmartExplosion.java
index acf96520e..85bb7b075 100644
--- a/src/main/java/com/petrolpark/destroy/world/explosion/SmartExplosion.java
+++ b/src/main/java/com/petrolpark/destroy/world/explosion/SmartExplosion.java
@@ -1,13 +1,6 @@
package com.petrolpark.destroy.world.explosion;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
+import java.util.*;
import java.util.Map.Entry;
import javax.annotation.Nullable;
@@ -87,7 +80,7 @@ public void explode() {
ExplosionResult result = getExplosionResult(); // 'Do' the Explosion
toBlow.addAll(result.blocksToDestroy()); // Mark all the Exploded Block States for removal
- List entities = result.entities().keySet().stream().toList();
+ List entities = new ArrayList<>(result.entities().keySet()); // a small fix, .toList() generates an immutable collection
ForgeEventFactory.onExplosionDetonate(level, this, entities, radius * 2); // Allow events to modify affected entities
for (Entity entity : entities) { // Explode each Entity
explodeEntity(entity, result.entities().get(entity));
@@ -308,15 +301,12 @@ private void addBlockDrops(BlockPos pos, List stacks) {
};
/**
- * @param blocksToDestroy The Blocks which this Explosion should remove
- * @param entities The Entities this Explosion should affect mapped to how strongly they are affected:
- * {@code 0} is not affected at all and {@code 1} is as if they were standing directly next
- * to the center of Explosion with nothing in the way
- */
- public static record ExplosionResult(Collection blocksToDestroy, Map entities) {
- public ExplosionResult {
- Objects.requireNonNullElse(blocksToDestroy, List.of());
- Objects.requireNonNullElse(entities, Map.of());
- };
- };
+ *
+ */
+ public record ExplosionResult(Collection blocksToDestroy, Map entities) {
+ public ExplosionResult(Collection blocksToDestroy, Map entities) {
+ this.blocksToDestroy = Objects.requireNonNullElse(blocksToDestroy, new ArrayList<>());
+ this.entities = Objects.requireNonNullElse(entities, new HashMap<>());
+ }
+ }
};
From b34ded0203eda4724e0b7621e4a65a4e7e6b0794 Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Tue, 20 Feb 2024 16:47:56 +0100
Subject: [PATCH 06/20] You can create chemical reactions and create your own
molecules with ZenScript
---
.../behaviour/ExtendedBasinBehaviour.java | 2 +-
.../petrolpark/destroy/chemistry/Formula.java | 10 +-
.../destroy/chemistry/IItemReactant.java | 16 +-
.../petrolpark/destroy/chemistry/Mixture.java | 3 +-
.../destroy/chemistry/Molecule.java | 14 +-
.../destroy/chemistry/Reaction.java | 14 +-
.../SingleGroupGenericReaction.java | 3 +-
.../chemistry/index/DestroyMolecules.java | 2 -
.../compat/crafttweaker/CTDestroy.java | 12 ++
.../crafttweaker/CTMoleculeManager.java | 49 +++++
.../crafttweaker/CTReactionManager.java | 37 ++++
.../compat/crafttweaker/MoleculeManager.java | 22 --
.../compat/crafttweaker/ReactionManager.java | 21 --
.../action/AddMoleculeAction.java | 31 +++
.../action/AddReactionAction.java | 33 +++
.../crafttweaker/action/DestroyAction.java | 16 ++
.../action/RemoveMoleculeAction.java | 31 +++
.../action/RemoveReactionAction.java | 39 ++++
.../compat/crafttweaker/natives/CTAtom.java | 30 +++
.../crafttweaker/natives/CTElement.java | 59 +++++
.../crafttweaker/natives/CTFormula.java | 152 +++++++++++++
.../crafttweaker/natives/CTMolecule.java | 170 +++++++++++++++
.../natives/CTMoleculeBuilder.java | 98 +++++++++
.../crafttweaker/natives/CTReaction.java | 201 ++++++++++++++++++
.../natives/CTReactionBuilder.java | 141 ++++++++++++
.../compat/jei/category/ReactionCategory.java | 2 +-
.../destroy/recipe/ReactionRecipe.java | 7 +
.../petrolpark/destroy/util/DestroyLang.java | 25 +--
.../com/petrolpark/destroy/util/vat/Vat.java | 4 +-
.../world/explosion/SmartExplosion.java | 2 +-
30 files changed, 1157 insertions(+), 89 deletions(-)
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTReactionManager.java
delete mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/MoleculeManager.java
delete mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/ReactionManager.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddMoleculeAction.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddReactionAction.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/DestroyAction.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveMoleculeAction.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveReactionAction.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTAtom.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTElement.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTFormula.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMolecule.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMoleculeBuilder.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTReaction.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTReactionBuilder.java
diff --git a/src/main/java/com/petrolpark/destroy/block/entity/behaviour/ExtendedBasinBehaviour.java b/src/main/java/com/petrolpark/destroy/block/entity/behaviour/ExtendedBasinBehaviour.java
index b1f8602c5..9c9db76d4 100644
--- a/src/main/java/com/petrolpark/destroy/block/entity/behaviour/ExtendedBasinBehaviour.java
+++ b/src/main/java/com/petrolpark/destroy/block/entity/behaviour/ExtendedBasinBehaviour.java
@@ -105,7 +105,7 @@ public void write(CompoundTag nbt, boolean clientPacket) {
nbt.put("Results", NBTHelper.writeCompoundList(reactionResults.entrySet(), entry -> {
CompoundTag resultTag = new CompoundTag();
- resultTag.putString("Result", entry.getKey().getReaction().getFullId());
+ resultTag.putString("Result", entry.getKey().getReaction().getFullID());
resultTag.putInt("Count", entry.getValue());
return resultTag;
}));
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Formula.java b/src/main/java/com/petrolpark/destroy/chemistry/Formula.java
index c9c1dd7fe..47be267fa 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Formula.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Formula.java
@@ -748,14 +748,14 @@ public Formula shallowCopy() {
* @param isCarbanion
* @see Molecule#getCarbocationStability The wrapper for this Method
*/
- public Float getCarbocationStability(Atom carbon, boolean isCarbanion) {
- Float totalElectronegativity = 0f;
+ public float getCarbocationStability(Atom carbon, boolean isCarbanion) {
+ float totalElectronegativity = 0f;
for (Bond bond : structure.get(carbon)) {
totalElectronegativity += bond.getDestinationAtom().getElement().getElectronegativity() * bond.getType().getEquivalent();
};
- Float relativeElectronegativity = totalElectronegativity - (Element.CARBON.getElectronegativity() * 4);
- Float relativeStability = 1f + ((float)Math.pow(relativeElectronegativity, 4) / (float)Math.abs(relativeElectronegativity));
- return isCarbanion ^ relativeElectronegativity < 0 ? 1f / (Float)relativeStability : (Float)relativeStability;
+ float relativeElectronegativity = totalElectronegativity - (Element.CARBON.getElectronegativity() * 4);
+ float relativeStability = 1f + ((float)Math.pow(relativeElectronegativity, 4) / Math.abs(relativeElectronegativity));
+ return isCarbanion ^ relativeElectronegativity < 0 ? 1f / relativeStability : relativeStability;
};
/**
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/IItemReactant.java b/src/main/java/com/petrolpark/destroy/chemistry/IItemReactant.java
index 20fc8f891..99acd1158 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/IItemReactant.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/IItemReactant.java
@@ -16,7 +16,7 @@ public interface IItemReactant {
* This should return {@code true} if the Item Stack is a valid reactant for this {@link Reaction}.
* @param stack
*/
- public boolean isItemValid(ItemStack stack);
+ boolean isItemValid(ItemStack stack);
/**
* Deal with 'consuming' this Item Stack - usually, this will involve shrinking the Stack by one,
@@ -24,7 +24,7 @@ public interface IItemReactant {
* untouched. If this is a {@link IItemReactant#isCatalyst catalyst}, this method is not called.
* @param stack
*/
- public default void consume(ItemStack stack) {
+ default void consume(ItemStack stack) {
stack.shrink(1);
};
@@ -32,17 +32,17 @@ public default void consume(ItemStack stack) {
* Get the List of Item Stacks through which the JEI slot should cycle. For Tag Reactants for
* example, this should be a List of all Item Stacks in that Tag.
*/
- public List getDisplayedItemStacks();
+ List getDisplayedItemStacks();
/**
* Whether this Item Reactant is a catalyst. If so, it will not be consumed, but just required
* for the {@link Reaction} to occur.
*/
- public default boolean isCatalyst() {
+ default boolean isCatalyst() {
return false;
};
- public class SimpleItemReactant implements IItemReactant {
+ class SimpleItemReactant implements IItemReactant {
protected final Supplier- item;
@@ -62,7 +62,7 @@ public List getDisplayedItemStacks() {
};
- public class SimpleItemCatalyst extends SimpleItemReactant {
+ class SimpleItemCatalyst extends SimpleItemReactant {
public SimpleItemCatalyst(Supplier
- item) {
super(item);
@@ -78,7 +78,7 @@ public boolean isCatalyst() {
};
- public class SimpleItemTagReactant implements IItemReactant {
+ class SimpleItemTagReactant implements IItemReactant {
protected final TagKey
- tag;
@@ -101,7 +101,7 @@ public List getDisplayedItemStacks() {
};
- public class SimpleItemTagCatalyst extends SimpleItemTagReactant {
+ class SimpleItemTagCatalyst extends SimpleItemTagReactant {
public SimpleItemTagCatalyst(TagKey
- tag) {
super(tag);
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java b/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
index a4d69a4f9..fc1be80be 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
@@ -27,7 +27,6 @@
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.Tag;
import net.minecraft.world.item.ItemStack;
-import org.checkerframework.checker.units.qual.A;
public class Mixture extends ReadOnlyMixture {
@@ -173,7 +172,7 @@ public CompoundTag writeNBT() {
if (!reactionResults.isEmpty()) {
tag.put("Results", NBTHelper.writeCompoundList(reactionResults.entrySet(), entry -> {
CompoundTag resultTag = new CompoundTag();
- resultTag.putString("Result", entry.getKey().getReaction().getFullId());
+ resultTag.putString("Result", entry.getKey().getReaction().getFullID());
resultTag.putFloat("MolesPerBucket", entry.getValue());
return resultTag;
}));
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java b/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
index 4119b7783..23029e368 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
@@ -1,5 +1,6 @@
package com.petrolpark.destroy.chemistry;
import java.util.*;
+import java.util.function.Consumer;
import javax.annotation.Nullable;
@@ -331,7 +332,7 @@ public boolean hasTag(MoleculeTag tag) {
* @see Molecule What a novel Molecule is
*/
public boolean isNovel() {
- return this.namespace == "novel";
+ return Objects.equals(this.namespace, "novel");
};
/**
@@ -387,7 +388,7 @@ public String getStructuralFormula() {
* @param isCarbanion Whether this calculation should be inverted (to calculate the relative stability of a carbanion)
* @return A value typically from 0-216
*/
- public Float getCarbocationStability(Atom carbon, boolean isCarbanion) {
+ public float getCarbocationStability(Atom carbon, boolean isCarbanion) {
return structure.getCarbocationStability(carbon, isCarbanion);
};
@@ -779,10 +780,9 @@ public Molecule build() {
if (molecule.id == null) {
error("Molecule's ID has not been declared.");
} else {
- MOLECULES.put(molecule.namespace +":"+molecule.id, molecule);
+ MOLECULES.put(molecule.getFullID(), molecule);
};
};
-
return molecule;
};
@@ -799,7 +799,7 @@ private float calculateMass() {
* Very loosely estimate the density of an organic molecule.
* @return A density in kilograms per metre cubed
*/
- private static final float estimateDensity(Molecule molecule) {
+ private static float estimateDensity(Molecule molecule) {
return 1000f; // Assume the density is similar to water, which is true for a lot of organic molecules.
};
@@ -865,5 +865,9 @@ public String toString() {
return MoreObjects.toStringHelper(this).add("ID", getFullID()).toString();
};
+ @Override
+ public int hashCode() {
+ return getFullID().hashCode();
+ }
};
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
index 2e4e6d792..f9a1d79c7 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
@@ -102,7 +102,7 @@ public static ReactionBuilder generatedReactionBuilder() {
private Reaction reverseReaction;
/**
- * Get the Reaction with the given {@link Reaction#getFullId ID}.
+ * Get the Reaction with the given {@link Reaction#getFullID ID}.
* @param reactionId In the format {@code :}
* @return {@code null} if no Reaction exists with that ID
*/
@@ -226,7 +226,7 @@ public ReactionResult getResult() {
* also acts as its translation key. {@code .reaction.} should hold
* the name of this Reaction, and {@code .reaction..description}
* should hold the description of this Reaction.
- * @see Reaction#getFullId Get the full ID
+ * @see Reaction#getFullID Get the full ID
*/
public String getId() {
return id;
@@ -236,7 +236,7 @@ public String getId() {
* Get the fully unique ID for this Reaction, in the format {@code :
* }, for example {@code destroy:chloroform_fluorination}.
*/
- public String getFullId() {
+ public String getFullID() {
return namespace + ":" + id;
};
@@ -702,12 +702,13 @@ public Reaction build() {
for (Molecule product : reaction.products.keySet()) {
product.addProductReaction(reaction);
};
- REACTIONS.put(reaction.getFullId(), reaction);
+ REACTIONS.put(reaction.getFullID(), reaction);
};
return reaction;
};
+
public static class ReactionConstructionException extends ChemistryException {
public ReactionConstructionException(String message) {
@@ -736,4 +737,9 @@ private String reactionString() {
return reactionString.toString();
};
};
+
+ @Override
+ public int hashCode() {
+ return getFullID().hashCode();
+ }
}
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/genericreaction/SingleGroupGenericReaction.java b/src/main/java/com/petrolpark/destroy/chemistry/genericreaction/SingleGroupGenericReaction.java
index 7d982a36d..6f1fe8460 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/genericreaction/SingleGroupGenericReaction.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/genericreaction/SingleGroupGenericReaction.java
@@ -1,5 +1,6 @@
package com.petrolpark.destroy.chemistry.genericreaction;
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
import com.petrolpark.destroy.Destroy;
import com.petrolpark.destroy.chemistry.Atom;
import com.petrolpark.destroy.chemistry.Element;
@@ -17,7 +18,7 @@ public abstract class SingleGroupGenericReaction> extends Gen
public SingleGroupGenericReaction(ResourceLocation id, GroupType type) {
super(id);
- this.type = type;;
+ this.type = type;
Group.groupTypesAndReactions.get(type).add(this);
GENERIC_REACTIONS.add(this); // Add this to the list of all known Generic Reactions
};
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java
index a4ce75f9f..a1ada2e86 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/index/DestroyMolecules.java
@@ -14,7 +14,6 @@
import org.openzen.zencode.java.ZenCodeType;
public final class DestroyMolecules {
-
public static final Molecule
ACETAMIDE = builder()
@@ -1103,7 +1102,6 @@ public final class DestroyMolecules {
.charge(1)
.build();
- @ZenCodeType.Method("create")
public static MoleculeBuilder builder() {
return new MoleculeBuilder(Destroy.MOD_ID);
};
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
new file mode 100644
index 000000000..0236ec3d1
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
@@ -0,0 +1,12 @@
+package com.petrolpark.destroy.compat.crafttweaker;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import org.apache.logging.log4j.Logger;
+
+public class CTDestroy {
+ private static final Logger logger = CraftTweakerAPI.getLogger("Destroy");
+
+ public static Logger getLogger() {
+ return logger;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java
new file mode 100644
index 000000000..02ba28699
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java
@@ -0,0 +1,49 @@
+package com.petrolpark.destroy.compat.crafttweaker;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.annotation.BracketResolver;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.chemistry.Element;
+import com.petrolpark.destroy.chemistry.Molecule;
+import com.petrolpark.destroy.chemistry.MoleculeTag;
+import com.petrolpark.destroy.chemistry.index.DestroyMolecules;
+import com.petrolpark.destroy.compat.crafttweaker.action.AddMoleculeAction;
+import com.petrolpark.destroy.compat.crafttweaker.action.RemoveMoleculeAction;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@ZenCodeType.Name("mods.destroy.Molecules")
+@Document("mods/destroy/Molecules")
+public class CTMoleculeManager {
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder create(String id) {
+ return new Molecule.MoleculeBuilder("crafttweaker")
+ .id(id);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule getMoleculeById(String moleculeId) {
+ return Molecule.MOLECULES.get(moleculeId);
+ }
+
+ @ZenCodeType.Method
+ public static void removeMolecule(Molecule molecule) {
+ CraftTweakerAPI.apply(new RemoveMoleculeAction(molecule));
+ }
+
+ @ZenCodeType.Method
+ @BracketResolver("molecule")
+ public static Object getMolecule(String tokens) {
+ if(tokens.startsWith("tag:")) {
+ return MoleculeTag.MOLECULE_TAGS.get(tokens.replaceFirst("tag:", ""));
+ }
+ return getMoleculeById(tokens);
+ }
+
+ @ZenCodeType.Method
+ @BracketResolver("element")
+ public static Element getElement(String tokens) {
+ return Element.valueOf(tokens.toUpperCase());
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTReactionManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTReactionManager.java
new file mode 100644
index 000000000..86ccd6272
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTReactionManager.java
@@ -0,0 +1,37 @@
+package com.petrolpark.destroy.compat.crafttweaker;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.annotation.BracketResolver;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.chemistry.Reaction;
+import com.petrolpark.destroy.compat.crafttweaker.action.RemoveMoleculeAction;
+import com.petrolpark.destroy.compat.crafttweaker.action.RemoveReactionAction;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@ZenCodeType.Name("mods.destroy.Reactions")
+@Document("mods/destroy/Reactions")
+public class CTReactionManager {
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder create(String id) {
+ return new Reaction.ReactionBuilder("crafttweaker")
+ .id(id);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction getReactionById(String reactionId) {
+ return Reaction.REACTIONS.get(reactionId);
+ }
+
+ @ZenCodeType.Method
+ public static void removeReaction(Reaction reaction) {
+ CraftTweakerAPI.apply(new RemoveReactionAction(reaction));
+ }
+
+ @ZenCodeType.Method
+ @BracketResolver("reaction")
+ public static Reaction getReaction(String tokens) {
+ return getReactionById(tokens);
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/MoleculeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/MoleculeManager.java
deleted file mode 100644
index 7fff184f1..000000000
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/MoleculeManager.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.petrolpark.destroy.compat.crafttweaker;
-
-import com.blamejared.crafttweaker.api.annotation.ZenRegister;
-import com.blamejared.crafttweaker_annotations.annotations.Document;
-import com.petrolpark.destroy.chemistry.Molecule;
-import com.petrolpark.destroy.chemistry.Reaction;
-import org.openzen.zencode.java.ZenCodeType;
-
-@ZenRegister
-@ZenCodeType.Name("mods.destroy.Reactions")
-@Document("mods/destroy/Reactions")
-public class MoleculeManager {
- @ZenCodeType.Method
- public static Molecule.MoleculeBuilder create() {
- return new Molecule.MoleculeBuilder("crafttweaker");
- }
-
- @ZenCodeType.Method
- public static Molecule getMoleculeById(String moleculeId) {
- return Molecule.MOLECULES.get(moleculeId);
- }
-}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/ReactionManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/ReactionManager.java
deleted file mode 100644
index 14a7c1bc5..000000000
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/ReactionManager.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.petrolpark.destroy.compat.crafttweaker;
-
-import com.blamejared.crafttweaker.api.annotation.ZenRegister;
-import com.blamejared.crafttweaker_annotations.annotations.Document;
-import com.petrolpark.destroy.chemistry.Reaction;
-import org.openzen.zencode.java.ZenCodeType;
-
-@ZenRegister
-@ZenCodeType.Name("mods.destroy.Reactions")
-@Document("mods/destroy/Reactions")
-public class ReactionManager {
- @ZenCodeType.Method
- public static Reaction.ReactionBuilder create() {
- return new Reaction.ReactionBuilder("crafttweaker");
- }
-
- @ZenCodeType.Method
- public static Reaction getReactionById(String reactionId) {
- return Reaction.REACTIONS.get(reactionId);
- }
-}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddMoleculeAction.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddMoleculeAction.java
new file mode 100644
index 000000000..9ea8ca110
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddMoleculeAction.java
@@ -0,0 +1,31 @@
+package com.petrolpark.destroy.compat.crafttweaker.action;
+
+import com.petrolpark.destroy.chemistry.Molecule;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+
+public class AddMoleculeAction extends DestroyAction {
+ private final Molecule molecule;
+
+ public AddMoleculeAction(Molecule molecule) {
+ this.molecule = molecule;
+ }
+ @Override
+ public void undo() {
+ Molecule.MOLECULES.remove(molecule.getFullID());
+ }
+
+ @Override
+ public String describeUndo() {
+ return "Unregisters the Molecule from the registry and makes it invisible for the reactions";
+ }
+
+ @Override
+ public void apply() {
+ CTDestroy.getLogger().info("Registered " + molecule.getFullID());
+ }
+
+ @Override
+ public String describe() {
+ return "Adds a Molecule to the registry and makes it visible for the reactions";
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddReactionAction.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddReactionAction.java
new file mode 100644
index 000000000..1c3447150
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddReactionAction.java
@@ -0,0 +1,33 @@
+package com.petrolpark.destroy.compat.crafttweaker.action;
+
+import com.petrolpark.destroy.chemistry.Reaction;
+import com.petrolpark.destroy.compat.jei.category.ReactionCategory;
+import com.petrolpark.destroy.recipe.ReactionRecipe;
+
+public class AddReactionAction extends DestroyAction {
+ private final Reaction reaction;
+
+ public AddReactionAction(Reaction reaction) {
+ this.reaction = reaction;
+ }
+ @Override
+ public void undo() {
+ Reaction.REACTIONS.remove(reaction.getFullID());
+ ReactionCategory.RECIPES.remove(reaction);
+ }
+
+ @Override
+ public String describe() {
+ return "Adds a reaction to the registry and makes it available to do in a vat";
+ }
+
+ @Override
+ public String describeUndo() {
+ return "Unregisters the reaction and makes it impossible to make in a vat";
+ }
+
+ @Override
+ public void apply() {
+ if (reaction.includeInJei()) ReactionCategory.RECIPES.put(reaction, ReactionRecipe.create("crafttweaker", reaction));
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/DestroyAction.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/DestroyAction.java
new file mode 100644
index 000000000..4e95c7b80
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/DestroyAction.java
@@ -0,0 +1,16 @@
+package com.petrolpark.destroy.compat.crafttweaker.action;
+
+import com.blamejared.crafttweaker.api.action.base.IUndoableAction;
+
+public abstract class DestroyAction implements IUndoableAction {
+
+ @Override
+ public String describe() {
+ return "An internal Destroy action";
+ }
+
+ @Override
+ public String systemName() {
+ return "Destroy";
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveMoleculeAction.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveMoleculeAction.java
new file mode 100644
index 000000000..334347b30
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveMoleculeAction.java
@@ -0,0 +1,31 @@
+package com.petrolpark.destroy.compat.crafttweaker.action;
+
+import com.petrolpark.destroy.chemistry.Molecule;
+
+public class RemoveMoleculeAction extends DestroyAction {
+
+ private final Molecule molecule;
+
+ public RemoveMoleculeAction(Molecule molecule) {
+ this.molecule = molecule;
+ }
+ @Override
+ public void undo() {
+ Molecule.MOLECULES.put(molecule.getFullID(), molecule);
+ }
+
+ @Override
+ public String describe() {
+ return "Removes the molecule from the registry and makes it unavailable for the vat reactions";
+ }
+
+ @Override
+ public String describeUndo() {
+ return "Adds the molecule back and makes it available for the reactions";
+ }
+
+ @Override
+ public void apply() {
+ Molecule.MOLECULES.remove(molecule.getFullID());
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveReactionAction.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveReactionAction.java
new file mode 100644
index 000000000..c8a9e7bdf
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveReactionAction.java
@@ -0,0 +1,39 @@
+package com.petrolpark.destroy.compat.crafttweaker.action;
+
+import com.petrolpark.destroy.chemistry.Reaction;
+import com.petrolpark.destroy.compat.jei.category.ReactionCategory;
+import com.petrolpark.destroy.recipe.ReactionRecipe;
+
+public class RemoveReactionAction extends DestroyAction {
+ private final Reaction reaction;
+ private final ReactionRecipe reactionRecipe;
+
+ public RemoveReactionAction(Reaction reaction) {
+ this.reaction = reaction;
+ this.reactionRecipe = ReactionCategory.RECIPES.get(reaction);
+ }
+
+ @Override
+ public void undo() {
+ Reaction.REACTIONS.put(reaction.getFullID(), reaction);
+ if(reactionRecipe != null) {
+ ReactionCategory.RECIPES.put(reaction, reactionRecipe);
+ }
+ }
+
+ @Override
+ public String describe() {
+ return "Removes the reaction from the registry";
+ }
+
+ @Override
+ public String describeUndo() {
+ return "Adds the reaction back into the registry";
+ }
+
+ @Override
+ public void apply() {
+ Reaction.REACTIONS.remove(reaction.getFullID());
+ ReactionCategory.RECIPES.remove(reaction);
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTAtom.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTAtom.java
new file mode 100644
index 000000000..45088019c
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTAtom.java
@@ -0,0 +1,30 @@
+package com.petrolpark.destroy.compat.crafttweaker.natives;
+
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
+import com.jozufozu.flywheel.core.PartialModel;
+import com.petrolpark.destroy.chemistry.Atom;
+import com.petrolpark.destroy.chemistry.Element;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@Document("mods/destroy/Atom")
+@NativeTypeRegistration(value = Atom.class, zenCodeName = "mods.destroy.Atom")
+public class CTAtom {
+
+ @ZenCodeType.Method
+ public static Element getElement(Atom internal) {
+ return internal.getElement();
+ }
+
+ @ZenCodeType.Method
+ public static PartialModel getPartial(Atom internal) {
+ return internal.getPartial();
+ }
+
+ @ZenCodeType.Method
+ public static boolean isHydrogen(Atom internal) {
+ return internal.isHydrogen();
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTElement.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTElement.java
new file mode 100644
index 000000000..99a38b5be
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTElement.java
@@ -0,0 +1,59 @@
+package com.petrolpark.destroy.compat.crafttweaker.natives;
+
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
+import com.jozufozu.flywheel.core.PartialModel;
+import com.petrolpark.destroy.chemistry.Element;
+import com.petrolpark.destroy.client.gui.MoleculeRenderer;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@Document("mods/destroy/Element")
+@NativeTypeRegistration(value = Element.class, zenCodeName = "mods.destroy.Element")
+public class CTElement {
+ @ZenCodeType.Method
+ public static String getSymbol(Element internal) {
+ return internal.getSymbol();
+ }
+
+ @ZenCodeType.Method
+ public static Float getMass(Element internal) {
+ return internal.getMass();
+ }
+
+ @ZenCodeType.Method
+ public static Float getElectronegativity(Element internal) {
+ return internal.getElectronegativity();
+ }
+
+ @ZenCodeType.Method
+ public static boolean isValidValency(Element internal, double valency) {
+ return internal.isValidValency(valency);
+ }
+
+ @ZenCodeType.Method
+ public static double getNextLowestValency(Element internal, double valency) {
+ return internal.getNextLowestValency(valency);
+ }
+
+ @ZenCodeType.Method
+ public static double getMaxValency(Element internal) {
+ return internal.getMaxValency();
+ }
+
+ @ZenCodeType.Method
+ public static MoleculeRenderer.Geometry getGeometry(Element internal, int connections) {
+ return internal.getGeometry(connections);
+ }
+
+ @ZenCodeType.Method
+ public static PartialModel getPartial(Element internal) {
+ return internal.getPartial();
+ }
+
+ @ZenCodeType.Method
+ public static void setPartial(Element internal, PartialModel partial) {
+ internal.setPartial(partial);
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTFormula.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTFormula.java
new file mode 100644
index 000000000..be476c56f
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTFormula.java
@@ -0,0 +1,152 @@
+package com.petrolpark.destroy.compat.crafttweaker.natives;
+
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.blamejared.crafttweaker_annotations.annotations.NativeConstructor;
+import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
+import com.petrolpark.destroy.chemistry.Atom;
+import com.petrolpark.destroy.chemistry.Bond;
+import com.petrolpark.destroy.chemistry.Element;
+import com.petrolpark.destroy.chemistry.Formula;
+import org.openzen.zencode.java.ZenCodeType;
+
+import java.util.List;
+import java.util.Set;
+
+@ZenRegister
+@Document("mods/destroy/Formula")
+@NativeTypeRegistration(
+ value = Formula.class,
+ zenCodeName = "mods.destroy.Formula",
+ constructors = {
+ @NativeConstructor({
+ @NativeConstructor.ConstructorParameter(type = Atom.class, name = "startingAtom")
+ })
+ }
+)
+public class CTFormula {
+ @ZenCodeType.Method
+ public static Formula moveTo(Formula internal, Atom atom) {
+ return internal.moveTo(atom);
+ }
+
+ @ZenCodeType.Method
+ public static Formula setStartingAtom(Formula internal, Atom atom) {
+ return internal.setStartingAtom(atom);
+ }
+
+ @ZenCodeType.StaticExpansionMethod
+ public static Formula atom(Element element) {
+ return Formula.atom(element);
+ }
+
+ @ZenCodeType.StaticExpansionMethod
+ public static Formula carbonChain(int length) {
+ return Formula.carbonChain(length);
+ }
+
+ @ZenCodeType.StaticExpansionMethod
+ public static Formula alcohol() {
+ return Formula.alcohol();
+ }
+
+ @ZenCodeType.Method
+ public static Formula addAtom(Formula internal, Element element) {
+ return internal.addAtom(element);
+ }
+
+ @ZenCodeType.Method
+ public static Formula addAtom(Formula internal, Element element, Bond.BondType bondType) {
+ return internal.addAtom(element, bondType);
+ }
+
+ @ZenCodeType.Method
+ public static Formula addAtom(Formula internal, Atom atom) {
+ return internal.addAtom(atom);
+ }
+
+ @ZenCodeType.Method
+ public static Formula addAtom(Formula internal, Atom atom, Bond.BondType bondType) {
+ return internal.addAtom(atom, bondType);
+ }
+
+ @ZenCodeType.Method
+ public static Formula addGroup(Formula internal, Formula group) {
+ return internal.addGroup(group);
+ }
+
+ @ZenCodeType.Method
+ public static Formula addGroup(Formula internal, Formula group, boolean isSideGroup) {
+ return internal.addGroup(group, isSideGroup);
+ }
+
+ @ZenCodeType.Method
+ public static Formula joinFormulae(Formula formula1, Formula formula2, Bond.BondType bondType) {
+ return Formula.joinFormulae(formula1, formula2, bondType);
+ }
+
+ @ZenCodeType.Method
+ public static Formula addGroup(Formula internal, Formula group, boolean isSideGroup, Bond.BondType bondType) {
+ return internal.addGroup(group, isSideGroup, bondType);
+ }
+
+ @ZenCodeType.Method
+ public static boolean isCyclic(Formula internal) {
+ return internal.isCyclic();
+ }
+
+ @ZenCodeType.Method
+ public static Formula remove(Formula internal, Atom atom) {
+ return internal.remove(atom);
+ }
+
+ @ZenCodeType.Method
+ public static Formula replace(Formula internal, Atom oldAtom, Atom newAtom) {
+ return internal.replace(oldAtom, newAtom);
+ }
+
+ @ZenCodeType.Method
+ public static Formula replaceBondTo(Formula internal, Atom otherAtom, Bond.BondType bondType) {
+ return internal.replaceBondTo(otherAtom, bondType);
+ }
+
+ @ZenCodeType.Method
+ public static Formula addCarbonyl(Formula internal) {
+ return internal.addCarbonyl();
+ }
+
+ @ZenCodeType.Method
+ public static Formula addAllHydrogens(Formula internal) {
+ return internal.addAllHydrogens();
+ }
+
+ @ZenCodeType.Method
+ public static Set getAllAtoms(Formula internal) {
+ return internal.getAllAtoms();
+ }
+
+ @ZenCodeType.Method
+ public static List getBondedAtomsOfElement(Formula internal, Element element) {
+ return internal.getBondedAtomsOfElement(element);
+ }
+
+ @ZenCodeType.Method
+ public static double getTotalBonds(Formula internal, List bonds) {
+ return internal.getTotalBonds(bonds);
+ }
+
+ @ZenCodeType.Method
+ public static String toString(Formula internal) {
+ return internal.serialize();
+ }
+
+ @ZenCodeType.StaticExpansionMethod
+ public static Formula deserialize(String FROWNSstring) {
+ return Formula.deserialize(FROWNSstring);
+ }
+
+ @ZenCodeType.Method
+ public static float getCarbocationStability(Formula internal, Atom carbon, boolean isCarbanion) {
+ return internal.getCarbocationStability(carbon, isCarbanion);
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMolecule.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMolecule.java
new file mode 100644
index 000000000..dbdb0846b
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMolecule.java
@@ -0,0 +1,170 @@
+package com.petrolpark.destroy.compat.crafttweaker.natives;
+
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
+import com.petrolpark.destroy.chemistry.Atom;
+import com.petrolpark.destroy.chemistry.Molecule;
+import com.petrolpark.destroy.chemistry.MoleculeTag;
+import com.petrolpark.destroy.chemistry.Reaction;
+import net.minecraft.network.chat.Component;
+import org.openzen.zencode.java.ZenCodeType;
+
+import java.util.List;
+import java.util.Set;
+
+@ZenRegister
+@Document("mods/destroy/Molecule")
+@NativeTypeRegistration(value = Molecule.class, zenCodeName = "mods.destroy.Molecule")
+public class CTMolecule {
+
+ @ZenCodeType.Method
+ public static Molecule getEquivalent(Molecule internal) {
+ return internal.getEquivalent();
+ }
+
+ @ZenCodeType.Method
+ public static String getFROWNSCode(Molecule internal) {
+ return internal.getFROWNSCode();
+ }
+
+ @ZenCodeType.Method
+ public static int getCharge(Molecule internal) {
+ return internal.getCharge();
+ }
+
+ @ZenCodeType.Method
+ public static float getMass(Molecule internal) {
+ return internal.getMass();
+ }
+
+ @ZenCodeType.Method
+ public static float getDensity(Molecule internal) {
+ return internal.getDensity();
+ }
+
+ @ZenCodeType.Method
+ public static float getPureConcentration(Molecule internal) {
+ return internal.getPureConcentration();
+ }
+
+ @ZenCodeType.Method
+ public static float getBoilingPoint(Molecule internal) {
+ return internal.getBoilingPoint();
+ }
+
+ @ZenCodeType.Method
+ public static float getDipoleMoment(Molecule internal) {
+ return internal.getDipoleMoment();
+ }
+
+ @ZenCodeType.Method
+ public static float getMolarHeatCapacity(Molecule internal) {
+ return internal.getMolarHeatCapacity();
+ }
+
+ @ZenCodeType.Method
+ public static float getLatentHeat(Molecule internal) {
+ return internal.getLatentHeat();
+ }
+
+ @ZenCodeType.Method
+ public static boolean isCyclic(Molecule internal) {
+ return internal.isCyclic();
+ }
+
+ @ZenCodeType.Method
+ public static Set getAtoms(Molecule internal) {
+ return internal.getAtoms();
+ }
+
+ @ZenCodeType.Method
+ public static boolean isHypothetical(Molecule internal) {
+ return internal.isHypothetical();
+ }
+
+ @ZenCodeType.Method
+ public static Set getTags(Molecule internal) {
+ return internal.getTags();
+ }
+
+ @ZenCodeType.Method
+ public static boolean hasTag(Molecule internal, MoleculeTag tag) {
+ return internal.hasTag(tag);
+ }
+
+ @ZenCodeType.Method
+ public static boolean isNovel(Molecule internal) {
+ return internal.isNovel();
+ }
+
+ @ZenCodeType.Method
+ public static String getStructuralFormula(Molecule internal) {
+ return internal.getStructuralFormula();
+ }
+
+ @ZenCodeType.Method
+
+ public static float getCarbocationStability(Molecule internal, Atom carbon, boolean isCarbanion) {
+ return internal.getCarbocationStability(carbon, isCarbanion);
+ }
+
+ @ZenCodeType.Method
+ public static String getTranslationKey(Molecule internal, boolean iupac) {
+ return internal.getTranslationKey(iupac);
+ }
+
+ @ZenCodeType.Method
+ public static int getColor(Molecule internal) {
+ return internal.getColor();
+ }
+
+ @ZenCodeType.Method
+ public static boolean isColorless(Molecule internal) {
+ return internal.isColorless();
+ }
+
+ @ZenCodeType.Method
+ public static Component getName(Molecule internal, boolean iupac) {
+ return internal.getName(iupac);
+ }
+
+ @ZenCodeType.Method
+ public static String getId(Molecule internal) {
+ return internal.getFullID();
+ }
+
+ @ZenCodeType.Method
+ public static void addReactantReaction(Molecule internal, Reaction reaction) {
+ internal.addReactantReaction(reaction);
+ }
+
+ /**
+ * Mark this Molecule as being a necessary reactant in the given {@link Reaction}.
+ * There should never be any need to call this method (it is done automatically when {@link Reaction.ReactionBuilder#build building} a Reaction).
+ * @param reaction
+ */
+
+ @ZenCodeType.Method
+ public static void addProductReaction(Molecule internal, Reaction reaction) {
+ internal.addProductReaction(reaction);
+ }
+
+ /**
+ * Get the list of {@link Reaction Reactions} of which this Molecule is a necessary Reactant.
+ * @return List of Reactions ordered by declaration
+ */
+ @ZenCodeType.Method
+ public static List getReactantReactions(Molecule internal) {
+ return internal.getReactantReactions();
+ }
+
+ /**
+ * Get the list of {@link Reaction Reactions} by which this Molecule is made.
+ * @return List of Reactions ordered by declaration
+ */
+ @ZenCodeType.Method
+ public static List getProductReactions(Molecule internal) {
+ return internal.getProductReactions();
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMoleculeBuilder.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMoleculeBuilder.java
new file mode 100644
index 000000000..6a92ed010
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMoleculeBuilder.java
@@ -0,0 +1,98 @@
+package com.petrolpark.destroy.compat.crafttweaker.natives;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
+import com.petrolpark.destroy.chemistry.Formula;
+import com.petrolpark.destroy.chemistry.Molecule;
+import com.petrolpark.destroy.chemistry.MoleculeTag;
+import com.petrolpark.destroy.compat.crafttweaker.action.AddMoleculeAction;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@Document("mods/destroy/MoleculeBuilder")
+@NativeTypeRegistration(value = Molecule.MoleculeBuilder.class, zenCodeName = "mods.destroy.MoleculeBuilder")
+public class CTMoleculeBuilder {
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder id(Molecule.MoleculeBuilder internal, String id) {
+ return internal.id(id);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder formula(Molecule.MoleculeBuilder internal, String formula) {
+ return internal.structure(Formula.deserialize(formula));
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder structure(Molecule.MoleculeBuilder internal, Formula formula) {
+ return internal.structure(formula);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder density(Molecule.MoleculeBuilder internal, float density) {
+ return internal.density(density);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder charge(Molecule.MoleculeBuilder internal, int charge) {
+ return internal.charge(charge);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder boilingPoint(Molecule.MoleculeBuilder internal, float boilingPoint) {
+ return internal.boilingPoint(boilingPoint);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder boilingPointInKelvins(Molecule.MoleculeBuilder internal, float boilingPoint) {
+ return internal.boilingPointInKelvins(boilingPoint);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder dipoleMoment(Molecule.MoleculeBuilder internal, int dipoleMoment) {
+ return internal.dipoleMoment(dipoleMoment);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder specificHeatCapacity(Molecule.MoleculeBuilder internal, float specificHeatCapacity) {
+ return internal.specificHeatCapacity(specificHeatCapacity);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder molarHeatCapacity(Molecule.MoleculeBuilder internal, float molarHeatCapacity) {
+ return internal.molarHeatCapacity(molarHeatCapacity);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder latentHeat(Molecule.MoleculeBuilder internal, float latentHeat) {
+ return internal.latentHeat(latentHeat);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder translationKey(Molecule.MoleculeBuilder internal, String translationKey) {
+ return internal.translationKey(translationKey);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder color(Molecule.MoleculeBuilder internal, int color) {
+ return internal.color(color);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder hypothetical(Molecule.MoleculeBuilder internal) {
+ return internal.hypothetical();
+ }
+
+ @ZenCodeType.Method
+ public static Molecule.MoleculeBuilder tag(Molecule.MoleculeBuilder internal, MoleculeTag... tags) {
+ return internal.tag(tags);
+ }
+
+ @ZenCodeType.Method
+ public static Molecule build(Molecule.MoleculeBuilder internal) {
+ Molecule result = internal.build();
+ CraftTweakerAPI.apply(new AddMoleculeAction(result));
+ return result;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTReaction.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTReaction.java
new file mode 100644
index 000000000..1c483c110
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTReaction.java
@@ -0,0 +1,201 @@
+package com.petrolpark.destroy.compat.crafttweaker.natives;
+
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
+import com.petrolpark.destroy.chemistry.IItemReactant;
+import com.petrolpark.destroy.chemistry.Molecule;
+import com.petrolpark.destroy.chemistry.Reaction;
+import com.petrolpark.destroy.chemistry.ReactionResult;
+import org.openzen.zencode.java.ZenCodeType;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+@ZenRegister
+@Document("mods/destroy/Reaction")
+@NativeTypeRegistration(value = Reaction.class, zenCodeName = "mods.destroy.Reaction")
+public class CTReaction {
+
+ /**
+ * Whether this Molecule gets consumed in this Reaction (does not include catalysts).
+ *
+ * @param molecule
+ */
+ @ZenCodeType.Method
+ public static boolean containsReactant(Reaction internal, Molecule molecule) {
+ return internal.containsReactant(molecule);
+ }
+
+ /**
+ * Whether this Molecule is created in this Reaction.
+ *
+ * @param molecule
+ */
+ @ZenCodeType.Method
+ public static boolean containsProduct(Reaction internal, Molecule molecule) {
+ return internal.containsProduct(molecule);
+ }
+
+ /**
+ * All Molecules which are consumed in this Reaction (but not their molar ratios).
+ */
+ @ZenCodeType.Method
+ public static Set getReactants(Reaction internal) {
+ return internal.getReactants();
+ }
+
+ /**
+ * Whether this Reaction needs any Item Stack as a {@link IItemReactant reactant}. Even if this is
+ * {@code true}, the Reaction may still have {@link IItemReactant#isCatalyst Item Stack catalysts}.
+ */
+ @ZenCodeType.Method
+ public static boolean consumesItem(Reaction internal) {
+ return internal.consumesItem();
+ }
+
+ /**
+ * Get the {@link IItemReactant required Items} for this Reaction.
+ */
+ @ZenCodeType.Method
+ public static List getItemReactants(Reaction internal) {
+ return internal.getItemReactants();
+ }
+
+ @ZenCodeType.Method
+ public static float getMolesPerItem(Reaction internal) {
+ return internal.getMolesPerItem();
+ }
+
+ /**
+ * Whether this Reaction needs UV light to proceed.
+ */
+ @ZenCodeType.Method
+ public static boolean needsUV(Reaction internal) {
+ return internal.needsUV();
+ }
+
+ /**
+ * All Molecules which are created in this Reaction (but not their molar ratios).
+ */
+ @ZenCodeType.Method
+ public static Set getProducts(Reaction internal) {
+ return internal.getProducts();
+ }
+ @ZenCodeType.Method
+ public static float getActivationEnergy(Reaction internal) {
+ return internal.getActivationEnergy();
+ }
+ @ZenCodeType.Method
+ public static float getPreexponentialFactor(Reaction internal) {
+ return internal.getPreexponentialFactor();
+ }
+
+ /**
+ * The rate constant of this Reaction at the given temperature.
+ *
+ * @param temperature (in kelvins).
+ */
+ @ZenCodeType.Method
+ public static float getRateConstant(Reaction internal, float temperature) {
+ return internal.getRateConstant(temperature);
+ }
+
+ @ZenCodeType.Method
+ public static float getEnthalpyChange(Reaction internal) {
+ return internal.getEnthalpyChange();
+ }
+
+ /**
+ * Whether this Reaction has a {@link ReactionResult Result}.
+ */
+ @ZenCodeType.Method
+ public static boolean hasResult(Reaction internal) {
+ return internal.hasResult();
+ }
+
+ /**
+ * The {@link ReactionResult Result} of this Reaction, which occurs once a set
+ * number of moles of Reaction have occured.
+ *
+ * @return {@code null} if this Reaction has no result.
+ */
+ @ZenCodeType.Method
+ public static ReactionResult getResult(Reaction internal) {
+ return internal.getResult();
+ }
+
+ /**
+ * Get the fully unique ID for this Reaction, in the format {@code :
+ * }, for example {@code destroy:chloroform_fluorination}.
+ */
+ @ZenCodeType.Method
+ public static String getFullID(Reaction internal) {
+ return internal.getFullID();
+ }
+
+ /**
+ * Whether this Reaction should be displayed in the list of Reactions in JEI.
+ */
+ @ZenCodeType.Method
+ public static boolean includeInJei(Reaction internal) {
+ return internal.includeInJei();
+ }
+
+ /**
+ * Whether this Reaction should be displayed in JEI with an equilibrium arrow rather than a normal one.
+ */
+ @ZenCodeType.Method
+ public static boolean displayAsReversible(Reaction internal) {
+ return internal.displayAsReversible();
+ }
+
+ /**
+ * If this is the 'forward' half of a reversible Reaction, this contains the reverse Reaction. This is so JEI
+ * knows the products of the forward Reaction are the reactants of the reverse, and vice versa. If this is not
+ * part of a reversible Reaction, this is empty. This is just for display; if a Reaction has a reverse and is needed
+ * for logic (e.g. Reacting in a Mixture) it should not be accessed in this way.
+ */
+ @ZenCodeType.Method
+ public static Optional getReverseReactionForDisplay(Reaction internal) {
+ return internal.getReverseReactionForDisplay();
+ }
+
+ /**
+ * Get the stoichometric ratio of this {@link Molecule reactant} or catalyst in this Reaction.
+ *
+ * @param reactant
+ * @return {@code 0} if this Molecule is not a reactant
+ */
+ @ZenCodeType.Method
+ public static int getReactantMolarRatio(Reaction internal, Molecule reactant) {
+ return internal.getReactantMolarRatio(reactant);
+ }
+
+ /**
+ * Get the stoichometric ratio of this {@link Molecule product} in this Reaction.
+ *
+ * @param product
+ * @return {@code 0} if this Molecule is not a product
+ */
+ @ZenCodeType.Method
+ public static int getProductMolarRatio(Reaction internal, Molecule product) {
+ return internal.getProductMolarRatio(product);
+ }
+
+ /**
+ * Get every {@link Molecule reactant} and catalyst in this Reaction, mapped to their
+ * orders in the rate equation.
+ */
+ @ZenCodeType.Method
+ public static Map getOrders(Reaction internal) {
+ return internal.getOrders();
+ }
+
+ @ZenCodeType.Method
+ public static String getID(Reaction internal) {
+ return internal.getFullID();
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTReactionBuilder.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTReactionBuilder.java
new file mode 100644
index 000000000..1229b7345
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTReactionBuilder.java
@@ -0,0 +1,141 @@
+package com.petrolpark.destroy.compat.crafttweaker.natives;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
+import com.petrolpark.destroy.chemistry.IItemReactant;
+import com.petrolpark.destroy.chemistry.Molecule;
+import com.petrolpark.destroy.chemistry.Reaction;
+import com.petrolpark.destroy.chemistry.ReactionResult;
+import com.petrolpark.destroy.compat.crafttweaker.action.AddReactionAction;
+import net.minecraft.world.item.Item;
+import org.openzen.zencode.java.ZenCodeType;
+
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.Supplier;
+
+
+// todo: TagKey compat
+@ZenRegister
+@Document("mods/destroy/ReactionBuilder")
+@NativeTypeRegistration(value = Reaction.ReactionBuilder.class, zenCodeName = "mods.destroy.ReactionBuilder")
+public class CTReactionBuilder {
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder addReactant(Reaction.ReactionBuilder internal, Molecule molecule) {
+ return internal.addReactant(molecule);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder addReactant(Reaction.ReactionBuilder internal, Molecule molecule, int ratio) {
+ return internal.addReactant(molecule, ratio);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder addReactant(Reaction.ReactionBuilder internal, Molecule molecule, int ratio, int order) {
+ return internal.addReactant(molecule, ratio, order);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder setOrder(Reaction.ReactionBuilder internal, Molecule molecule, int order) {
+ return internal.setOrder(molecule, order);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder addItemReactant(Reaction.ReactionBuilder internal, IItemReactant itemReactant, float moles) {
+ return internal.addItemReactant(itemReactant, moles);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder addSimpleItemReactant(Reaction.ReactionBuilder internal, Supplier
- item, float moles) {
+ return internal.addSimpleItemReactant(item, moles);
+ }
+
+// @ZenCodeType.Method
+// public static Reaction.ReactionBuilder addSimpleItemTagReactant(Reaction.ReactionBuilder internal, TagKey
- tag, float moles) {
+// return internal.addSimpleItemTagReactant(tag, moles);
+// }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder addSimpleItemCatalyst(Reaction.ReactionBuilder internal, Supplier
- item, float moles) {
+ return internal.addSimpleItemCatalyst(item, moles);
+ }
+
+// @ZenCodeType.Method
+// public static Reaction.ReactionBuilder addSimpleItemTagCatalyst(Reaction.ReactionBuilder internal, TagKey
- tag, float moles) {
+// return internal.addSimpleItemTagCatalyst(tag, moles);
+// }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder requireUV(Reaction.ReactionBuilder internal) {
+ return internal.requireUV();
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder addProduct(Reaction.ReactionBuilder internal, Molecule molecule) {
+ return internal.addProduct(molecule);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder addProduct(Reaction.ReactionBuilder internal, Molecule molecule, int ratio) {
+ return internal.addProduct(molecule, ratio);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder addCatalyst(Reaction.ReactionBuilder internal, Molecule molecule, int order) {
+ return internal.addCatalyst(molecule, order);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder dontIncludeInJei(Reaction.ReactionBuilder internal) {
+ return internal.dontIncludeInJei();
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder displayAsReversible(Reaction.ReactionBuilder internal) {
+ return internal.displayAsReversible();
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder id(Reaction.ReactionBuilder internal, String id) {
+ return internal.id(id);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder preexponentialFactor(Reaction.ReactionBuilder internal, float preexponentialFactor) {
+ return internal.preexponentialFactor(preexponentialFactor);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder activationEnergy(Reaction.ReactionBuilder internal, float activationEnergy) {
+ return internal.activationEnergy(activationEnergy);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder enthalpyChange(Reaction.ReactionBuilder internal, float enthalpyChange) {
+ return internal.enthalpyChange(enthalpyChange);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder withResult(Reaction.ReactionBuilder internal, float moles, BiFunction reactionresultFactory) {
+ return internal.withResult(moles, reactionresultFactory);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction acid(Reaction.ReactionBuilder internal, Molecule acid, Molecule conjugateBase, float pKa) {
+ return internal.acid(acid, conjugateBase, pKa);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction.ReactionBuilder reverseReaction(Reaction.ReactionBuilder internal, Consumer reverseReactionModifier) {
+ return internal.reverseReaction(reverseReactionModifier);
+ }
+
+ @ZenCodeType.Method
+ public static Reaction build(Reaction.ReactionBuilder internal) {
+ Reaction result = internal.build();
+ CraftTweakerAPI.apply(new AddReactionAction(result));
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/petrolpark/destroy/compat/jei/category/ReactionCategory.java b/src/main/java/com/petrolpark/destroy/compat/jei/category/ReactionCategory.java
index 7e0130188..b08c27c91 100644
--- a/src/main/java/com/petrolpark/destroy/compat/jei/category/ReactionCategory.java
+++ b/src/main/java/com/petrolpark/destroy/compat/jei/category/ReactionCategory.java
@@ -97,7 +97,7 @@ public Palette getPaletteForBoxes() {
};
private static void tooManyMoleculesWarning(boolean reactants, Reaction reaction) {
- Destroy.LOGGER.warn("Reaction '"+reaction.getFullId()+"' has too many " + (reactants ? "reactants" : "products") + " to fit on JEI.");
+ Destroy.LOGGER.warn("Reaction '"+reaction.getFullID()+"' has too many " + (reactants ? "reactants" : "products") + " to fit on JEI.");
};
@Override
diff --git a/src/main/java/com/petrolpark/destroy/recipe/ReactionRecipe.java b/src/main/java/com/petrolpark/destroy/recipe/ReactionRecipe.java
index c557e7b45..2cfe88951 100644
--- a/src/main/java/com/petrolpark/destroy/recipe/ReactionRecipe.java
+++ b/src/main/java/com/petrolpark/destroy/recipe/ReactionRecipe.java
@@ -9,6 +9,7 @@
import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder.ProcessingRecipeParams;
+import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.Level;
import net.minecraftforge.items.wrapper.RecipeWrapper;
@@ -28,6 +29,12 @@ public static ReactionRecipe create(Reaction reaction) {
return recipe;
};
+ public static ReactionRecipe create(String namespace, Reaction reaction) {
+ ReactionRecipe recipe = new ProcessingRecipeBuilder<>(ReactionRecipe::new, new ResourceLocation(namespace, "reaction_"+counter++)).build();
+ recipe.reaction = reaction;
+ return recipe;
+ };
+
public Reaction getReaction() {
return reaction;
};
diff --git a/src/main/java/com/petrolpark/destroy/util/DestroyLang.java b/src/main/java/com/petrolpark/destroy/util/DestroyLang.java
index 80f97636e..abce92b81 100644
--- a/src/main/java/com/petrolpark/destroy/util/DestroyLang.java
+++ b/src/main/java/com/petrolpark/destroy/util/DestroyLang.java
@@ -33,14 +33,14 @@
@MoveToPetrolparkLibrary
public class DestroyLang {
- private static DecimalFormat df = new DecimalFormat();
+ private static final DecimalFormat df = new DecimalFormat();
static {
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
};
- private static String[] subscriptNumbers = new String[]{"\u2080", "\u2081", "\u2082", "\u2083", "\u2084", "\u2085", "\u2086", "\u2087", "\u2088", "\u2089"};
- private static String[] superscriptNumbers = new String[]{"\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079"};
+ private static final String[] subscriptNumbers = new String[]{"\u2080", "\u2081", "\u2082", "\u2083", "\u2084", "\u2085", "\u2086", "\u2087", "\u2088", "\u2089"};
+ private static final String[] superscriptNumbers = new String[]{"\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079"};
public static LangBuilder builder() {
return new LangBuilder(Destroy.MOD_ID);
@@ -156,13 +156,10 @@ public static MutableComponent barMeterComponent(int value, int maxValue, int to
* @param fluidTag The NBT of the Fluid Stack
*/
public static List mixtureIngredientTooltip(CompoundTag fluidTag) {
- List tooltip = new ArrayList<>();
MixtureFluidIngredientSubType> fluidIngredientType = MixtureFluidIngredient.MIXTURE_FLUID_INGREDIENT_SUBTYPES.get(fluidTag.getString("MixtureFluidIngredientSubtype"));
- tooltip.addAll(fluidIngredientType.getDescription(fluidTag));
-
- return tooltip;
+ return new ArrayList<>(fluidIngredientType.getDescription(fluidTag));
};
private static final float pressureMin = 0f;
@@ -253,15 +250,15 @@ public static String toSubscript(int value) {
* @param value Should only be passed strings containing numbers, {@code +} and {@code -}.
*/
public static String toSuperscript(String value) {
- String string = "";
+ StringBuilder string = new StringBuilder();
for (char c : value.toCharArray()) {
- if (c == '-') string += "\u207b";
- if (c == '+') string += "\u207a";
+ if (c == '-') string.append("\u207b");
+ if (c == '+') string.append("\u207a");
try {
- string += superscriptNumbers[Integer.valueOf(String.valueOf(c))];
+ string.append(superscriptNumbers[Integer.parseInt(String.valueOf(c))]);
} catch (Throwable e) {};
};
- return string;
+ return string.toString();
};
public static enum TemperatureUnit {
@@ -276,8 +273,8 @@ public static enum TemperatureUnit {
df.setMaximumFractionDigits(1);
};
- private UnaryOperator conversionFromKelvins;
- private String symbol;
+ private final UnaryOperator conversionFromKelvins;
+ private final String symbol;
TemperatureUnit(UnaryOperator conversionFromKelvins, String symbol) {
this.conversionFromKelvins = conversionFromKelvins;
diff --git a/src/main/java/com/petrolpark/destroy/util/vat/Vat.java b/src/main/java/com/petrolpark/destroy/util/vat/Vat.java
index e50d7f1d3..b6f10e1c7 100644
--- a/src/main/java/com/petrolpark/destroy/util/vat/Vat.java
+++ b/src/main/java/com/petrolpark/destroy/util/vat/Vat.java
@@ -38,8 +38,8 @@ public class Vat {
VatMaterial.registerDestroyVatMaterials();
};
- private BlockPos lowerCorner;
- private BlockPos upperCorner;
+ private final BlockPos lowerCorner;
+ private final BlockPos upperCorner;
private ImmutableList sides; // NOT synced server/client
diff --git a/src/main/java/com/petrolpark/destroy/world/explosion/SmartExplosion.java b/src/main/java/com/petrolpark/destroy/world/explosion/SmartExplosion.java
index 85bb7b075..434ada5aa 100644
--- a/src/main/java/com/petrolpark/destroy/world/explosion/SmartExplosion.java
+++ b/src/main/java/com/petrolpark/destroy/world/explosion/SmartExplosion.java
@@ -65,7 +65,7 @@ public class SmartExplosion extends Explosion {
public SmartExplosion(Level level, @Nullable Entity source, @Nullable DamageSource damageSource, @Nullable ExplosionDamageCalculator damageCalculator, Vec3 position, float radius, float smoothness) {
super(level, source, damageSource, damageCalculator, position.x, position.y, position.z, radius, false, Explosion.BlockInteraction.KEEP);
this.position = position;
- this.smoothness = smoothness > 1f ? 1f : smoothness;
+ this.smoothness = Math.min(smoothness, 1f);
stacksToCreate = new HashMap<>();
};
From 662ab8188cba67533103f1191ea9ec77ff24fffb Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Wed, 21 Feb 2024 17:39:35 +0100
Subject: [PATCH 07/20] Created recipe handlers and 1 manager to test Also
removed redudant code in the original recipe classes More collection
optimisations
---
gradle.properties | 2 +-
.../compat/crafttweaker/CTDestroy.java | 115 +++++++++++++
.../reactionresult/CTReactionResult.java | 4 +
.../recipes/handler/AgingRecipeHandler.java | 36 +++++
.../handler/CentrifugationRecipeHandler.java | 64 ++++++++
.../handler/ChargingRecipeHandler.java | 51 ++++++
.../handler/DistillationRecipeHandler.java | 66 ++++++++
.../handler/ElectrolysisRecipeHandler.java | 13 ++
.../handler/IDestroyRecipeHandler.java | 130 +++++++++++++++
.../manager/DistillationRecipeManager.java | 41 +++++
.../manager/IDestroyRecipeManager.java | 48 ++++++
.../accessor/FluidTagIngredientAccessor.java | 16 ++
.../destroy/recipe/AgingRecipe.java | 8 +-
.../destroy/recipe/CentrifugationRecipe.java | 2 +-
.../destroy/recipe/ChargingRecipe.java | 19 ++-
.../destroy/recipe/ObliterationRecipe.java | 12 ++
.../destroy/util/DistillationTower.java | 9 +-
src/main/resources/destroy.mixins.json | 153 +++++++++---------
18 files changed, 693 insertions(+), 96 deletions(-)
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/reactionresult/CTReactionResult.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/AgingRecipeHandler.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/ChargingRecipeHandler.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/DistillationRecipeHandler.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/ElectrolysisRecipeHandler.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/IDestroyRecipeHandler.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/DistillationRecipeManager.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/IDestroyRecipeManager.java
create mode 100644 src/main/java/com/petrolpark/destroy/mixin/accessor/FluidTagIngredientAccessor.java
diff --git a/gradle.properties b/gradle.properties
index 7ab4087fd..f4bed9f63 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -22,4 +22,4 @@ registrate_version = MC1.20-1.3.3
jei_version = 15.2.0.22
farmersdelight_version = 4638874
blueprint_version = 7.0.0
-crafttweaker_version = 14.0.34
\ No newline at end of file
+crafttweaker_version = 14.0.16
\ No newline at end of file
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
index 0236ec3d1..c1c66353e 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
@@ -1,12 +1,127 @@
package com.petrolpark.destroy.compat.crafttweaker;
import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.item.IItemStack;
+import com.blamejared.crafttweaker.api.recipe.component.IRecipeComponent;
+import com.blamejared.crafttweaker.api.tag.CraftTweakerTagRegistry;
+import com.blamejared.crafttweaker.api.tag.type.KnownTag;
+import com.blamejared.crafttweaker.api.util.GenericUtil;
+import com.blamejared.crafttweaker.api.util.IngredientUtil;
+import com.blamejared.crafttweaker.api.util.random.Percentaged;
+import com.google.gson.reflect.TypeToken;
+import com.petrolpark.destroy.mixin.accessor.FluidTagIngredientAccessor;
+import com.simibubi.create.content.processing.recipe.HeatCondition;
+import com.simibubi.create.content.processing.recipe.ProcessingOutput;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipe;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import com.simibubi.create.foundation.fluid.FluidIngredient;
+import net.minecraft.core.NonNullList;
+import net.minecraft.core.registries.Registries;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.tags.TagKey;
+import net.minecraft.world.Container;
+import net.minecraft.world.level.material.Fluid;
+import net.minecraftforge.fluids.FluidStack;
import org.apache.logging.log4j.Logger;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
public class CTDestroy {
private static final Logger logger = CraftTweakerAPI.getLogger("Destroy");
public static Logger getLogger() {
return logger;
}
+
+
+ // Taken from MIT licensed code https://github.com/jaredlll08/CreateTweaker/blob/1.20.1/forge/src/main/java/com/blamejared/createtweaker/services/ForgePlatformService.java
+ public static FluidIngredient mapFluidIngredients(CTFluidIngredient ingredient) {
+ return ingredient.mapTo(CTDestroy::fromFluidStack, CTDestroy::fromTag, stream -> {
+ throw new IllegalArgumentException("Unable to use a compound ingredient for Create!");
+ });
+ }
+
+ private static FluidIngredient fromFluidStack(IFluidStack stack) {
+ return FluidIngredient.fromFluidStack(stack.getInternal());
+ }
+
+
+ public static Percentaged mapProcessingResult(ProcessingOutput result) {
+ return IItemStack.of(result.getStack()).percent(result.getChance() * 100);
+ }
+
+ public static ProcessingOutput mapPercentagedToProcessingOutput(Percentaged stack) {
+ return new ProcessingOutput(stack.getData().getInternal(), (float) stack.getPercentage());
+ }
+
+ public static > ProcessingRecipeBuilder withFluidOutputs(ProcessingRecipeBuilder builder, List fluidOutputs) {
+
+ builder.withFluidOutputs(fluidOutputs.stream()
+ .map(IFluidStack::getInternal)
+ .collect(Collectors.toCollection(NonNullList::create)));
+ return builder;
+ }
+
+ public static ProcessingRecipeBuilder> output(ProcessingRecipeBuilder> builder, IFluidStack output) {
+
+ return GenericUtil.uncheck(builder.output(output. getInternal()));
+ }
+
+ public static FluidIngredient fromTag(TagKey tag, int amount) {
+ return FluidIngredient.fromTag(tag, amount);
+ }
+
+ public static CTFluidIngredient mapFluidIngredientsToCT(FluidIngredient ingredient) {
+ if(ingredient instanceof FluidIngredient.FluidTagIngredient fti) {
+ KnownTag tag = CraftTweakerTagRegistry.INSTANCE.knownTagManager(Registries.FLUID)
+ .tag(((FluidTagIngredientAccessor) fti).destroy$getTag());
+ return new CTFluidIngredient.FluidTagWithAmountIngredient(tag.asTagWithAmount());
+ }
+ Optional reduce = ingredient.getMatchingFluidStacks()
+ .stream()
+ .map(IFluidStack::of)
+ .map(IFluidStack::asFluidIngredient)
+ .reduce(CTFluidIngredient::asCompound);
+ return reduce.orElseThrow();
+ }
+
+ public static > boolean doFluidIngredientsConflict(T first, T second) {
+ return IngredientUtil.doIngredientsConflict(first.getFluidIngredients(),
+ second.getFluidIngredients(),
+ FluidIngredient.EMPTY::equals,
+ fluidIngredient -> fluidIngredient.getMatchingFluidStacks().toArray(FluidStack[]::new),
+ FluidStack::containsFluid);
+ }
+
+ public static Stream streamFluidResults(ProcessingRecipe> recipe) {
+ return recipe.getFluidResults()
+ .stream()
+ .map(IFluidStack::of);
+ }
+ public static List getRecipeFluidResults(ProcessingRecipe> recipe) {
+ return streamFluidResults(recipe).toList();
+ }
+
+ public static List getMatchingFluidStacks(FluidIngredient ingredient) {
+ return ingredient.getMatchingFluidStacks()
+ .stream()
+ .map(IFluidStack::of)
+ .collect(Collectors.toList());
+ }
+
+ public static final class RecipeInput {
+ public static final IRecipeComponent HEAT = IRecipeComponent.simple(
+ new ResourceLocation("crafttweaker", "input/heat"),
+ new TypeToken<>() {},
+ Objects::equals
+ );
+
+ private RecipeInput() {}
+ }
}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/reactionresult/CTReactionResult.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/reactionresult/CTReactionResult.java
new file mode 100644
index 000000000..a18b44889
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/reactionresult/CTReactionResult.java
@@ -0,0 +1,4 @@
+package com.petrolpark.destroy.compat.crafttweaker.natives.reactionresult;
+
+public class CTReactionResult {
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/AgingRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/AgingRecipeHandler.java
new file mode 100644
index 000000000..135292278
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/AgingRecipeHandler.java
@@ -0,0 +1,36 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.handler;
+
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.recipe.handler.IRecipeHandler;
+import com.blamejared.crafttweaker.api.recipe.manager.base.IRecipeManager;
+import com.blamejared.crafttweaker.api.util.random.Percentaged;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+import com.petrolpark.destroy.recipe.AgingRecipe;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+
+import java.util.stream.Collectors;
+
+@IRecipeHandler.For(AgingRecipe.class)
+public class AgingRecipeHandler implements IDestroyRecipeHandler {
+
+ @Override
+ public String dumpToCommandString(IRecipeManager super AgingRecipe> manager, AgingRecipe recipe) {
+ return String.format(
+ ".addRecipe(\"%s\", [%s], %s, %s, %s);",
+ recipe.getId(),
+ IFluidStack.of(recipe.getRequiredFluid()).getCommandString(),
+ IFluidStack.of(recipe.getFluidResults().get(0)).getCommandString(),
+ recipe.getRollableResults()
+ .stream()
+ .map(CTDestroy::mapProcessingResult)
+ .map(Percentaged::getCommandString)
+ .collect(Collectors.joining(", ")),
+ recipe.getProcessingDuration()
+ );
+ }
+
+ @Override
+ public ProcessingRecipeBuilder.ProcessingRecipeFactory factory() {
+ return AgingRecipe::new;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java
new file mode 100644
index 000000000..c59009bf9
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java
@@ -0,0 +1,64 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.handler;
+
+import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.recipe.component.BuiltinRecipeComponents;
+import com.blamejared.crafttweaker.api.recipe.component.IDecomposedRecipe;
+import com.blamejared.crafttweaker.api.recipe.handler.IRecipeHandler;
+import com.blamejared.crafttweaker.api.recipe.manager.base.IRecipeManager;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+import com.petrolpark.destroy.recipe.CentrifugationRecipe;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import net.minecraft.core.NonNullList;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraftforge.fluids.FluidStack;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+@IRecipeHandler.For(CentrifugationRecipe.class)
+public class CentrifugationRecipeHandler implements IDestroyRecipeHandler {
+
+ @Override
+ public String dumpToCommandString(IRecipeManager super CentrifugationRecipe> manager, CentrifugationRecipe recipe) {
+ return String.format(
+ ".addRecipe(\"%s\", , %s, [%s]);",
+ recipe.getId(),
+ recipe.getRequiredHeat().name().toLowerCase(Locale.ENGLISH),
+ recipe.getRequiredFluid(),
+ recipe.getFluidResults()
+ .stream()
+ .map(fluid -> IFluidStack.of(fluid).getCommandString())
+ .collect(Collectors.joining(", "))
+ );
+ }
+
+ @Override
+ public Optional decompose(IRecipeManager super CentrifugationRecipe> manager, CentrifugationRecipe recipe) {
+ List results = new ArrayList<>(2);
+ for(FluidStack fluidResult : recipe.getFluidResults()) {
+ results.add(IFluidStack.of(fluidResult));
+ }
+ IDecomposedRecipe result = IDecomposedRecipe.builder()
+ .with(BuiltinRecipeComponents.Input.FLUID_INGREDIENTS, List.of(IFluidStack.of(recipe.getRequiredFluid()).asFluidIngredient()))
+ .with(BuiltinRecipeComponents.Output.FLUIDS, results)
+ .build();
+ return Optional.of(result);
+ }
+
+ @Override
+ public Optional recompose(IRecipeManager super CentrifugationRecipe> manager, ResourceLocation name, IDecomposedRecipe recipe) {
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(factory(), name);
+ CTFluidIngredient source = recipe.getOrThrow(BuiltinRecipeComponents.Input.FLUID_INGREDIENTS).get(0);
+ builder.withFluidIngredients(CTDestroy.mapFluidIngredients(source));
+ CTDestroy.withFluidOutputs(builder, recipe.getOrThrow(BuiltinRecipeComponents.Output.FLUIDS));
+ return Optional.of(builder.build());
+ }
+ @Override
+ public ProcessingRecipeBuilder.ProcessingRecipeFactory factory() {
+ return CentrifugationRecipe::new;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/ChargingRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/ChargingRecipeHandler.java
new file mode 100644
index 000000000..d554b3b10
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/ChargingRecipeHandler.java
@@ -0,0 +1,51 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.handler;
+
+import com.blamejared.crafttweaker.api.ingredient.IIngredient;
+import com.blamejared.crafttweaker.api.recipe.component.BuiltinRecipeComponents;
+import com.blamejared.crafttweaker.api.recipe.component.IDecomposedRecipe;
+import com.blamejared.crafttweaker.api.recipe.handler.IRecipeHandler;
+import com.blamejared.crafttweaker.api.recipe.manager.base.IRecipeManager;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+import com.petrolpark.destroy.recipe.ChargingRecipe;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import net.minecraft.core.NonNullList;
+import net.minecraft.resources.ResourceLocation;
+
+import java.util.List;
+import java.util.Optional;
+
+@IRecipeHandler.For(ChargingRecipe.class)
+public class ChargingRecipeHandler implements IDestroyRecipeHandler {
+
+ @Override
+ public String dumpToCommandString(IRecipeManager super ChargingRecipe> iRecipeManager, ChargingRecipe recipe) {
+ return String.format(
+ ".addRecipe(\"%s\", %s, %s);",
+ recipe.getId(),
+ IIngredient.fromIngredient(recipe.getInput()).getCommandString(),
+ CTDestroy.mapProcessingResult(recipe.getResult()).getCommandString()
+ );
+ }
+
+ @Override
+ public Optional decompose(IRecipeManager super ChargingRecipe> manager, ChargingRecipe recipe) {
+ IDecomposedRecipe result = IDecomposedRecipe.builder()
+ .with(BuiltinRecipeComponents.Input.INGREDIENTS, List.of(IIngredient.fromIngredient(recipe.getInput())))
+ .with(BuiltinRecipeComponents.Output.CHANCED_ITEMS, List.of(CTDestroy.mapProcessingResult(recipe.getResult())))
+ .build();
+ return Optional.of(result);
+ }
+
+ @Override
+ public Optional recompose(IRecipeManager super ChargingRecipe> manager, ResourceLocation name, IDecomposedRecipe recipe) {
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(factory(), name);
+ builder.withItemIngredients(recipe.getOrThrow(BuiltinRecipeComponents.Input.INGREDIENTS).get(0).asVanillaIngredient());
+ builder.withItemOutputs(CTDestroy.mapPercentagedToProcessingOutput(recipe.getOrThrow(BuiltinRecipeComponents.Output.CHANCED_ITEMS).get(0)));
+ return Optional.of(builder.build());
+ }
+
+ @Override
+ public ProcessingRecipeBuilder.ProcessingRecipeFactory factory() {
+ return ChargingRecipe::new;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/DistillationRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/DistillationRecipeHandler.java
new file mode 100644
index 000000000..79dc4687f
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/DistillationRecipeHandler.java
@@ -0,0 +1,66 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.handler;
+
+import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.recipe.component.BuiltinRecipeComponents;
+import com.blamejared.crafttweaker.api.recipe.component.IDecomposedRecipe;
+import com.blamejared.crafttweaker.api.recipe.handler.IRecipeHandler;
+import com.blamejared.crafttweaker.api.recipe.manager.base.IRecipeManager;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+import com.petrolpark.destroy.recipe.DistillationRecipe;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import net.minecraft.core.NonNullList;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraftforge.fluids.FluidStack;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+@IRecipeHandler.For(DistillationRecipe.class)
+public class DistillationRecipeHandler implements IDestroyRecipeHandler {
+ @Override
+ public String dumpToCommandString(IRecipeManager super DistillationRecipe> manager, DistillationRecipe recipe) {
+ return String.format(
+ ".addRecipe(\"%s\", , %s, [%s]);",
+ recipe.getId(),
+ recipe.getRequiredHeat().name().toLowerCase(Locale.ENGLISH),
+ recipe.getRequiredFluid(),
+ recipe.getFluidResults()
+ .stream()
+ .map(fluid -> IFluidStack.of(fluid).getCommandString())
+ .collect(Collectors.joining(", "))
+ );
+ }
+
+ @Override
+ public Optional decompose(IRecipeManager super DistillationRecipe> manager, DistillationRecipe recipe) {
+ List results = new ArrayList<>(recipe.getFractions());
+ for(FluidStack fluidResult : recipe.getFluidResults()) {
+ results.add(IFluidStack.of(fluidResult));
+ }
+ IDecomposedRecipe result = IDecomposedRecipe.builder()
+ .with(BuiltinRecipeComponents.Input.FLUID_INGREDIENTS, List.of(IFluidStack.of(recipe.getRequiredFluid()).asFluidIngredient()))
+ .with(BuiltinRecipeComponents.Output.FLUIDS, results)
+ .build();
+ return Optional.of(result);
+ }
+
+ @Override
+ public Optional recompose(IRecipeManager super DistillationRecipe> manager, ResourceLocation name, IDecomposedRecipe recipe) {
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(factory(), name);
+ CTFluidIngredient source = recipe
+ .getOrThrow(BuiltinRecipeComponents.Input.FLUID_INGREDIENTS)
+ .get(0);
+ builder.withFluidIngredients(CTDestroy.mapFluidIngredients(source));
+ CTDestroy.withFluidOutputs(builder, recipe.getOrThrow(BuiltinRecipeComponents.Output.FLUIDS));
+ return Optional.of(builder.build());
+ }
+
+ @Override
+ public ProcessingRecipeBuilder.ProcessingRecipeFactory factory() {
+ return DistillationRecipe::new;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/ElectrolysisRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/ElectrolysisRecipeHandler.java
new file mode 100644
index 000000000..3e5301965
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/ElectrolysisRecipeHandler.java
@@ -0,0 +1,13 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.handler;
+
+import com.blamejared.crafttweaker.api.recipe.handler.IRecipeHandler;
+import com.petrolpark.destroy.recipe.ElectrolysisRecipe;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+
+@IRecipeHandler.For(ElectrolysisRecipe.class)
+public class ElectrolysisRecipeHandler implements IDestroyRecipeHandler {
+ @Override
+ public ProcessingRecipeBuilder.ProcessingRecipeFactory factory() {
+ return ElectrolysisRecipe::new;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/IDestroyRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/IDestroyRecipeHandler.java
new file mode 100644
index 000000000..8a5a46183
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/IDestroyRecipeHandler.java
@@ -0,0 +1,130 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.handler;
+
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.ingredient.IIngredient;
+import com.blamejared.crafttweaker.api.item.IItemStack;
+import com.blamejared.crafttweaker.api.recipe.component.BuiltinRecipeComponents;
+import com.blamejared.crafttweaker.api.recipe.component.IDecomposedRecipe;
+import com.blamejared.crafttweaker.api.recipe.handler.IRecipeHandler;
+import com.blamejared.crafttweaker.api.recipe.manager.base.IRecipeManager;
+import com.blamejared.crafttweaker.api.util.IngredientUtil;
+import com.blamejared.crafttweaker.api.util.random.Percentaged;
+import com.mojang.datafixers.util.Either;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipe;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import net.minecraft.core.NonNullList;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.world.item.crafting.Recipe;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public interface IDestroyRecipeHandler> extends IRecipeHandler {
+
+ default String getRecipeTypeName() {
+ return null;
+ }
+
+ @Override
+ default String dumpToCommandString(IRecipeManager super T> iRecipeManager, T recipe) {
+ Either>, IFluidStack> result;
+ List fluidResults = CTDestroy.getRecipeFluidResults(recipe);
+ if(!fluidResults.isEmpty()) {
+ result = Either.right(fluidResults.get(0));
+ } else {
+ result = Either.left(recipe.getRollableResults()
+ .stream()
+ .map(CTDestroy::mapProcessingResult));
+ }
+
+ return String.format(".addRecipe(\"%s\", , [%s], [%s], [%s], [%s]);",
+ recipe.getId(),
+ recipe.getRequiredHeat().name().toLowerCase(Locale.ENGLISH),
+ result.map(results -> results.map(Percentaged::getCommandString)
+ .collect(Collectors.joining(", ")), IFluidStack::getCommandString),
+ recipe.getIngredients()
+ .stream()
+ .map(IIngredient::fromIngredient)
+ .map(IIngredient::getCommandString)
+ .collect(Collectors.joining(", ")),
+ recipe.getFluidIngredients()
+ .stream()
+ .map(CTDestroy::getMatchingFluidStacks)
+ .flatMap(Collection::stream)
+ .map(IFluidStack::getCommandString)
+ .collect(Collectors.joining(", ")),
+ CTDestroy.streamFluidResults(recipe)
+ .map(IFluidStack::getCommandString)
+ .collect(Collectors.joining(", "))
+ );
+ }
+ @Override
+ default > boolean doesConflict(IRecipeManager super T> manager, T firstRecipe, U secondRecipe) {
+ if(isGoodRecipe(firstRecipe, secondRecipe)) {
+ final T second = (T) secondRecipe;
+ if(firstRecipe.getIngredients().size() != second.getIngredients().size() || !firstRecipe.getRequiredHeat()
+ .equals(second.getRequiredHeat())) {
+ return false;
+ }
+ return IngredientUtil.doIngredientsConflict(firstRecipe.getIngredients(), secondRecipe.getIngredients())
+ && CTDestroy.doFluidIngredientsConflict(firstRecipe, second);
+
+ }
+
+ return false;
+ }
+
+ default boolean isGoodRecipe(Recipe> self, Recipe> other) {
+ return other.getClass().isAssignableFrom(self.getClass());
+ }
+
+ default Optional decompose(IRecipeManager super T> manager, T recipe) {
+ return Optional.of(IDecomposedRecipe.builder()
+ .with(BuiltinRecipeComponents.Input.INGREDIENTS, recipe.getIngredients()
+ .stream()
+ .map(IIngredient::fromIngredient)
+ .toList())
+ .with(BuiltinRecipeComponents.Output.CHANCED_ITEMS, recipe.getRollableResults()
+ .stream()
+ .map(CTDestroy::mapProcessingResult)
+ .toList())
+ .with(BuiltinRecipeComponents.Input.FLUID_INGREDIENTS, recipe.getFluidIngredients()
+ .stream()
+ .map(CTDestroy::mapFluidIngredientsToCT)
+ .toList())
+ .with(BuiltinRecipeComponents.Output.FLUIDS, CTDestroy.getRecipeFluidResults(recipe)
+ .stream()
+ .toList())
+ .with(BuiltinRecipeComponents.Processing.TIME, recipe.getProcessingDuration())
+ .with(CTDestroy.RecipeInput.HEAT, recipe.getRequiredHeat())
+ .build()
+ );
+ }
+
+ default Optional recompose(IRecipeManager super T> manager, ResourceLocation name, IDecomposedRecipe recipe) {
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(factory(), name);
+ builder.withItemIngredients(recipe.getOrThrow(BuiltinRecipeComponents.Input.INGREDIENTS)
+ .stream()
+ .map(IIngredient::asVanillaIngredient)
+ .collect(Collectors.toCollection(NonNullList::create)));
+ builder.withItemOutputs(recipe.getOrThrow(BuiltinRecipeComponents.Output.CHANCED_ITEMS)
+ .stream()
+ .map(CTDestroy::mapPercentagedToProcessingOutput)
+ .collect(Collectors.toCollection(NonNullList::create)));
+ builder.withFluidIngredients(recipe.getOrThrow(BuiltinRecipeComponents.Input.FLUID_INGREDIENTS)
+ .stream()
+ .map(CTDestroy::mapFluidIngredients)
+ .collect(Collectors.toCollection(NonNullList::create)));
+ CTDestroy.withFluidOutputs(builder, recipe.getOrThrow(BuiltinRecipeComponents.Output.FLUIDS));
+ builder.duration(recipe.getOrThrowSingle(BuiltinRecipeComponents.Processing.TIME));
+ builder.requiresHeat(recipe.getOrThrowSingle(CTDestroy.RecipeInput.HEAT));
+ return Optional.of(builder.build());
+ }
+
+ ProcessingRecipeBuilder.ProcessingRecipeFactory factory();
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/DistillationRecipeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/DistillationRecipeManager.java
new file mode 100644
index 000000000..d1e04a358
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/DistillationRecipeManager.java
@@ -0,0 +1,41 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.manager;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.action.recipe.ActionAddRecipe;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.platform.Services;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+import com.petrolpark.destroy.recipe.DestroyRecipeTypes;
+import com.petrolpark.destroy.recipe.DistillationRecipe;
+import com.simibubi.create.AllRecipeTypes;
+import com.simibubi.create.content.processing.recipe.HeatCondition;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import net.minecraft.resources.ResourceLocation;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@Document("mods/destroy/DistillationManager")
+@ZenCodeType.Name("mods.destroy.DistillationManager")
+public class DistillationRecipeManager implements IDestroyRecipeManager {
+
+ // todo: specify that it does not allow mixtures as fluids
+ @ZenCodeType.Method
+ public void addRecipe(String name, HeatCondition heat, CTFluidIngredient input, IFluidStack[] fractions) {
+ name = fixRecipeName(name);
+ ResourceLocation resourceLocation = new ResourceLocation("crafttweaker", name);
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(getSerializer().getFactory(), resourceLocation);
+ builder.withFluidIngredients(CTDestroy.mapFluidIngredients(input));
+ for(IFluidStack fraction : fractions) {
+ CTDestroy.output(builder, fraction);
+ }
+ builder.requiresHeat(heat);
+ CraftTweakerAPI.apply(new ActionAddRecipe<>(this, builder.build()));
+ }
+ @Override
+ public DestroyRecipeTypes getDestroyRecipeType() {
+ return DestroyRecipeTypes.DISTILLATION;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/IDestroyRecipeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/IDestroyRecipeManager.java
new file mode 100644
index 000000000..157a368e2
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/IDestroyRecipeManager.java
@@ -0,0 +1,48 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.manager;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.action.recipe.ActionAddRecipe;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker.api.recipe.manager.base.IRecipeManager;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.recipe.DestroyRecipeTypes;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipe;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeSerializer;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.world.item.crafting.RecipeType;
+import org.openzen.zencode.java.ZenCodeType;
+
+import java.util.function.Consumer;
+
+@ZenRegister
+@ZenCodeType.Name("mods.destroy.IDestroyRecipeManager")
+@Document("mods/destroy/IDestroyRecipeManager")
+public interface IDestroyRecipeManager > extends IRecipeManager {
+ default ProcessingRecipeSerializer getSerializer() {
+ return getDestroyRecipeType().getSerializer();
+ }
+
+ /**
+ * Registers a recipe using a builder approach.
+ *
+ * @param name The name of the recipe.
+ * @param recipeBuilder The recipe builder.
+ */
+ @ZenCodeType.Method
+ default void registerRecipe(String name, Consumer> recipeBuilder) {
+ name = fixRecipeName(name);
+ ResourceLocation recipeId = new ResourceLocation("crafttweaker", name);
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(getSerializer().getFactory(), recipeId);
+ recipeBuilder.accept(builder);
+ CraftTweakerAPI.apply(new ActionAddRecipe<>(this, builder.build(), ""));
+ }
+
+
+ DestroyRecipeTypes getDestroyRecipeType();
+
+ @Override
+ default RecipeType getRecipeType() {
+ return getDestroyRecipeType().getType();
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/mixin/accessor/FluidTagIngredientAccessor.java b/src/main/java/com/petrolpark/destroy/mixin/accessor/FluidTagIngredientAccessor.java
new file mode 100644
index 000000000..3c6dcf972
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/mixin/accessor/FluidTagIngredientAccessor.java
@@ -0,0 +1,16 @@
+package com.petrolpark.destroy.mixin.accessor;
+
+import com.simibubi.create.foundation.fluid.FluidIngredient;
+import net.minecraft.tags.TagKey;
+import net.minecraft.world.level.material.Fluid;
+import org.spongepowered.asm.mixin.Mixin;
+import org.spongepowered.asm.mixin.gen.Accessor;
+
+@Mixin(value = FluidIngredient.FluidTagIngredient.class, remap = false)
+public interface FluidTagIngredientAccessor {
+ @Accessor(
+ remap = false,
+ value = "tag"
+ )
+ TagKey destroy$getTag();
+}
diff --git a/src/main/java/com/petrolpark/destroy/recipe/AgingRecipe.java b/src/main/java/com/petrolpark/destroy/recipe/AgingRecipe.java
index 1a1dfa285..167365970 100644
--- a/src/main/java/com/petrolpark/destroy/recipe/AgingRecipe.java
+++ b/src/main/java/com/petrolpark/destroy/recipe/AgingRecipe.java
@@ -14,12 +14,7 @@ public AgingRecipe(ProcessingRecipeParams params) {
@Override
protected int getMaxInputCount() {
return 2;
- };
-
- @Override
- protected int getMaxOutputCount() {
- return 0;
- };
+ }
@Override
protected int getMaxFluidOutputCount() {
@@ -35,5 +30,4 @@ public boolean matches(RecipeWrapper pContainer, Level level) {
public String getRecipeTypeName() {
return "aging";
};
-
}
diff --git a/src/main/java/com/petrolpark/destroy/recipe/CentrifugationRecipe.java b/src/main/java/com/petrolpark/destroy/recipe/CentrifugationRecipe.java
index 5e21b3882..d4b797d93 100644
--- a/src/main/java/com/petrolpark/destroy/recipe/CentrifugationRecipe.java
+++ b/src/main/java/com/petrolpark/destroy/recipe/CentrifugationRecipe.java
@@ -21,7 +21,7 @@ public FluidStack getLightOutputFluid() {
};
private void checkForValidOutputs() {
- if (fluidResults.isEmpty() || fluidResults.size() != 2) throw new IllegalStateException("Centrifugation Recipe " + id + " contains the wrong number of output fluids.");
+ if (fluidResults.size() != 2) throw new IllegalStateException("Centrifugation Recipe " + id + " contains the wrong number of output fluids.");
};
@Override
diff --git a/src/main/java/com/petrolpark/destroy/recipe/ChargingRecipe.java b/src/main/java/com/petrolpark/destroy/recipe/ChargingRecipe.java
index 24ee6ce5e..98ef8650a 100644
--- a/src/main/java/com/petrolpark/destroy/recipe/ChargingRecipe.java
+++ b/src/main/java/com/petrolpark/destroy/recipe/ChargingRecipe.java
@@ -8,11 +8,13 @@
import com.petrolpark.destroy.compat.jei.category.AssemblyChargingSubCategory;
import com.petrolpark.destroy.util.DestroyLang;
import com.simibubi.create.compat.jei.category.sequencedAssembly.SequencedAssemblySubCategory;
+import com.simibubi.create.content.processing.recipe.ProcessingOutput;
import com.simibubi.create.content.processing.recipe.ProcessingRecipe;
import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder.ProcessingRecipeParams;
import com.simibubi.create.content.processing.sequenced.IAssemblyRecipe;
import net.minecraft.network.chat.Component;
+import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.Level;
@@ -36,16 +38,21 @@ protected int getMaxOutputCount() {
return 1;
};
+ public Ingredient getInput() {
+ if(ingredients.isEmpty()) return null;
+ return ingredients.get(0);
+ }
+
+ public ProcessingOutput getResult() {
+ if(results.isEmpty()) return null;
+ return results.get(0);
+ }
+
@Override
public boolean matches(RecipeWrapper inv, Level level) {
if (inv.isEmpty()) return false;
return ingredients.get(0).test(inv.getItem(0));
- };
-
- @Override
- protected boolean canSpecifyDuration() {
- return false;
- };
+ };;
@Override
@OnlyIn(Dist.CLIENT)
diff --git a/src/main/java/com/petrolpark/destroy/recipe/ObliterationRecipe.java b/src/main/java/com/petrolpark/destroy/recipe/ObliterationRecipe.java
index 0c8d72836..7e9f178d8 100644
--- a/src/main/java/com/petrolpark/destroy/recipe/ObliterationRecipe.java
+++ b/src/main/java/com/petrolpark/destroy/recipe/ObliterationRecipe.java
@@ -1,8 +1,10 @@
package com.petrolpark.destroy.recipe;
+import com.simibubi.create.content.processing.recipe.ProcessingOutput;
import com.simibubi.create.content.processing.recipe.ProcessingRecipe;
import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder.ProcessingRecipeParams;
+import net.minecraft.world.item.crafting.Ingredient;
import net.minecraft.world.level.Level;
import net.minecraftforge.items.wrapper.RecipeWrapper;
@@ -30,5 +32,15 @@ protected int getMaxInputCount() {
protected int getMaxOutputCount() {
return 1;
};
+
+ public Ingredient getInput() {
+ if(ingredients.isEmpty()) return null;
+ return ingredients.get(0);
+ }
+
+ public ProcessingOutput getResult() {
+ if(results.isEmpty()) return null;
+ return results.get(0);
+ }
};
diff --git a/src/main/java/com/petrolpark/destroy/util/DistillationTower.java b/src/main/java/com/petrolpark/destroy/util/DistillationTower.java
index a4ca8076a..18a2bcd95 100644
--- a/src/main/java/com/petrolpark/destroy/util/DistillationTower.java
+++ b/src/main/java/com/petrolpark/destroy/util/DistillationTower.java
@@ -124,10 +124,9 @@ public void findRecipe(Level level) {
if (lastRecipe == null || !lastRecipe.getRequiredFluid().test(inputTank.getFluid())) { // If the Recipe has changed
List> possibleRecipes = RecipeFinder.get(distillationRecipeKey, level, r -> r.getType() == DestroyRecipeTypes.DISTILLATION.getType()).stream().filter(r -> {
DistillationRecipe recipe = (DistillationRecipe) r;
- if (!recipe.getRequiredFluid().test(inputTank.getFluid())) return false; // If there is insufficient input Fluid
- return true;
- }).collect(Collectors.toList());
- if (possibleRecipes.size() >= 1) {
+ return recipe.getRequiredFluid().test(inputTank.getFluid()); // If there is insufficient input Fluid
+ }).toList();
+ if (!possibleRecipes.isEmpty()) {
lastRecipe = (DistillationRecipe)possibleRecipes.get(0);
} else {
lastRecipe = null;
@@ -222,7 +221,7 @@ public boolean process() {
* @param mixture The Mixture being distilled
* @param mixtureAmount The amount (in mB) of this Mixture
* @param numberOfFractions The maximum number of fractions this should be separated into, not including any possible residue
- * @param heatLevel The Heat Level of the Blaze Burner (or lack thereof) which is heating the controller Bubble Cap
+// * @param heatLevel The Heat Level of the Blaze Burner (or lack thereof) which is heating the controller Bubble Cap
* @return A list of Fluid Stacks of maximum size {@code numberOfFractions + 1}, with the first being the residue, and the rest being subsequent fractions
*/
private List getFractionsOfMixture(ReadOnlyMixture mixture, int mixtureAmount, int numberOfFractions) {
diff --git a/src/main/resources/destroy.mixins.json b/src/main/resources/destroy.mixins.json
index 186ff7ea8..385dbadaf 100644
--- a/src/main/resources/destroy.mixins.json
+++ b/src/main/resources/destroy.mixins.json
@@ -1,78 +1,79 @@
{
- "required": "true",
- "package": "com.petrolpark.destroy.mixin",
- "compatibilityLevel": "JAVA_17",
- "refmap": "destroy.refmap.json",
- "plugin": "com.petrolpark.destroy.mixin.plugin.DestroyMixinPlugin",
- "mixins": [
- "accessor.AbstractVillagerAccessor",
- "accessor.AgeableMobAccessor",
- "accessor.BasinOperatingBlockEntityAccessor",
- "accessor.DepotBehaviourAccessor",
- "accessor.FluidIngredientAccessor",
- "accessor.FluidNetworkAccessor",
- "accessor.MenuRowsAccessor",
- "accessor.PipeConnectionAccessor",
- "accessor.PonderTagScreenAccessor",
- "accessor.ProcessingRecipeParamsAccessor",
- "accessor.RotationPropagatorAccessor",
- "accessor.SimpleRenderElementAccessor",
- "accessor.TooltipRendererAccessor",
- "accessor.ValueSettingsPacketAccessor",
- "accessor.VillagerAccessor",
- "BasinBlockEntityMixin",
- "BasinCategoryMixin",
- "BeltInventoryMixin",
- "BlockMixin",
- "ConnectivityHandlerMixin",
- "ContraptionMixin",
- "CreateRecipeCategoryMixin",
- "CuttingBoardMixin",
- "DepotBehaviourMixin",
- "CreateJEIMixin",
- "DestroyFrictionModifier",
- "DirectBeltInputBehaviourMixin",
- "EjectorBlockEntityMixin",
- "FluidIngredientMixin",
- "FluidNetworkMixin",
- "FluidTankBlockEntityMixin",
- "HeatConditionMixin",
- "HeatLevelMixin",
- "ItemDrainBlockMixin",
- "KineticBlockEntityMixin",
- "MechanicalMixerBlockEntityMixin",
- "MixingCategoryMixin",
- "PackingCategoryMixin",
- "PipeConnectionMixin",
- "PonderTagScreenMixin",
- "PonderUIMixin",
- "RotationPropagatorMixin",
- "SchematicannonInventoryMixin",
- "ServerAdvancementManagerMixin",
- "SharedDepotBlockMethodsMixin",
- "SoundEntryBuilderMixin",
- "SplashingTypeMixin",
- "SpoutBlockMixin",
- "TooltipRendererMixin",
- "TransportedItemStackMixin",
- "ValueSettingsClientMixin",
- "ValueSettingsPacketMixin",
- "VanillaFluidTargetsMixin",
- "VillagerMixin"
- ],
- "client": [
- "accessor.ItemRendererAccessor",
- "ClientComponentTooltipMixin",
- "EffectRenderingInventoryScreenMixin",
- "GuiMixin",
- "HeartTypeMixin",
- "ItemRendererMixin",
- "LevelRendererMixin",
- "MultiPlayerGameModeMixin",
- "ProcessingRecipeMixin"
- ],
- "injectors": {
- "defaultRequire": 1
- },
- "minVersion": "0.8"
+ "required": "true",
+ "package": "com.petrolpark.destroy.mixin",
+ "compatibilityLevel": "JAVA_17",
+ "refmap": "destroy.refmap.json",
+ "plugin": "com.petrolpark.destroy.mixin.plugin.DestroyMixinPlugin",
+ "mixins": [
+ "BasinBlockEntityMixin",
+ "BasinCategoryMixin",
+ "BeltInventoryMixin",
+ "BlockMixin",
+ "ConnectivityHandlerMixin",
+ "ContraptionMixin",
+ "CreateJEIMixin",
+ "CreateRecipeCategoryMixin",
+ "CuttingBoardMixin",
+ "DepotBehaviourMixin",
+ "DestroyFrictionModifier",
+ "DirectBeltInputBehaviourMixin",
+ "EjectorBlockEntityMixin",
+ "FluidIngredientMixin",
+ "FluidNetworkMixin",
+ "FluidTankBlockEntityMixin",
+ "HeatConditionMixin",
+ "HeatLevelMixin",
+ "ItemDrainBlockMixin",
+ "KineticBlockEntityMixin",
+ "MechanicalMixerBlockEntityMixin",
+ "MixingCategoryMixin",
+ "PackingCategoryMixin",
+ "PipeConnectionMixin",
+ "PonderTagScreenMixin",
+ "PonderUIMixin",
+ "RotationPropagatorMixin",
+ "SchematicannonInventoryMixin",
+ "ServerAdvancementManagerMixin",
+ "SharedDepotBlockMethodsMixin",
+ "SoundEntryBuilderMixin",
+ "SplashingTypeMixin",
+ "SpoutBlockMixin",
+ "TooltipRendererMixin",
+ "TransportedItemStackMixin",
+ "ValueSettingsClientMixin",
+ "ValueSettingsPacketMixin",
+ "VanillaFluidTargetsMixin",
+ "VillagerMixin",
+ "accessor.AbstractVillagerAccessor",
+ "accessor.AgeableMobAccessor",
+ "accessor.BasinOperatingBlockEntityAccessor",
+ "accessor.DepotBehaviourAccessor",
+ "accessor.FluidIngredientAccessor",
+ "accessor.FluidNetworkAccessor",
+ "accessor.FluidTagIngredientAccessor",
+ "accessor.MenuRowsAccessor",
+ "accessor.PipeConnectionAccessor",
+ "accessor.PonderTagScreenAccessor",
+ "accessor.ProcessingRecipeParamsAccessor",
+ "accessor.RotationPropagatorAccessor",
+ "accessor.SimpleRenderElementAccessor",
+ "accessor.TooltipRendererAccessor",
+ "accessor.ValueSettingsPacketAccessor",
+ "accessor.VillagerAccessor"
+ ],
+ "client": [
+ "ClientComponentTooltipMixin",
+ "EffectRenderingInventoryScreenMixin",
+ "GuiMixin",
+ "HeartTypeMixin",
+ "ItemRendererMixin",
+ "LevelRendererMixin",
+ "MultiPlayerGameModeMixin",
+ "ProcessingRecipeMixin",
+ "accessor.ItemRendererAccessor"
+ ],
+ "injectors": {
+ "defaultRequire": 1
+ },
+ "minVersion": "0.8"
}
\ No newline at end of file
From b5fa166ff5c36cab931f3dd44de8f25fcbc376b5 Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Wed, 21 Feb 2024 20:49:12 +0100
Subject: [PATCH 08/20] Exposed Mixture and the way to create them to
CraftTweaker Fixed recipe string dumps Implemented AgingRecipeManager
---
.../petrolpark/destroy/chemistry/Mixture.java | 2 +-
.../destroy/chemistry/ReadOnlyMixture.java | 18 +-
.../crafttweaker/natives/CTMixture.java | 202 ++++++++++++++++++
.../recipes/handler/AgingRecipeHandler.java | 11 +-
.../handler/CentrifugationRecipeHandler.java | 4 +-
.../handler/DistillationRecipeHandler.java | 22 +-
.../recipes/manager/AgingRecipeHandler.java | 40 ++++
.../manager/DistillationRecipeManager.java | 8 +-
.../ConcentrationRangeFluidIngredient.java | 13 +-
.../ingredient/MoleculeFluidIngredient.java | 2 +-
.../MoleculeTagFluidIngredient.java | 2 +-
.../RefrigerantDummyFluidIngredient.java | 3 +-
.../fluid/ingredient/SaltFluidIngredient.java | 16 +-
.../destroy/recipe/AgingRecipe.java | 5 +
14 files changed, 307 insertions(+), 41 deletions(-)
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/AgingRecipeHandler.java
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java b/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
index fc1be80be..520acfadb 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Mixture.java
@@ -577,7 +577,7 @@ public void scale(float volumeIncreaseFactor) {
reactionResults.replaceAll((reactionResult, molesPerBucket) -> molesPerBucket / volumeIncreaseFactor);
};
- public static record Phases(Mixture gasMixture, Double gasVolume, Mixture liquidMixture, Double liquidVolume) {};
+ public record Phases(Mixture gasMixture, Double gasVolume, Mixture liquidMixture, Double liquidVolume) {};
/**
* Get two new Mixtures from one - one containing all gas, one containing all liquid.
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/ReadOnlyMixture.java b/src/main/java/com/petrolpark/destroy/chemistry/ReadOnlyMixture.java
index b8570ef78..9c5b17c71 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/ReadOnlyMixture.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/ReadOnlyMixture.java
@@ -1,12 +1,8 @@
package com.petrolpark.destroy.chemistry;
import java.text.DecimalFormat;
-import java.util.ArrayList;
-import java.util.Collections;
+import java.util.*;
import java.util.function.Function;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Predicate;
import java.util.function.Supplier;
@@ -79,12 +75,14 @@ public class ReadOnlyMixture {
*/
protected Map states;
+ public static final float BASE_TEMPERATURE = 298f;
+
public ReadOnlyMixture() {
translationKey = "";
contents = new HashMap<>();
- temperature = 298f;
+ temperature = BASE_TEMPERATURE;
states = new HashMap<>();
};
@@ -94,7 +92,7 @@ public ReadOnlyMixture() {
*/
public CompoundTag writeNBT() {
CompoundTag compound = new CompoundTag();
- if (translationKey != "" && translationKey != null) {
+ if (!Objects.equals(translationKey, "") && translationKey != null) {
compound.putString("TranslationKey", translationKey);
};
compound.putFloat("Temperature", temperature);
@@ -265,10 +263,10 @@ public List getContents(boolean excludeNovel) {
* (Used for debugging).
*/
public String getContentsString() {
- String string = "";
- if (contents.isEmpty()) return string;
+ StringBuilder string = new StringBuilder();
+ if (contents.isEmpty()) return string.toString();
for (Entry entry : contents.entrySet()) {
- string += entry.getKey().getFullID() + " (" + entry.getValue() + "M), ";
+ string.append(entry.getKey().getFullID()).append(" (").append(entry.getValue()).append("M), ");
};
return string.substring(0, string.length() - 2);
};
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
new file mode 100644
index 000000000..ecf5b6da0
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
@@ -0,0 +1,202 @@
+package com.petrolpark.destroy.compat.crafttweaker.natives;
+
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.ingredient.IIngredient;
+import com.blamejared.crafttweaker.api.util.random.Percentaged;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
+import com.petrolpark.destroy.chemistry.Mixture;
+import com.petrolpark.destroy.chemistry.Molecule;
+import com.petrolpark.destroy.chemistry.MoleculeTag;
+import com.petrolpark.destroy.chemistry.ReadOnlyMixture;
+import com.petrolpark.destroy.fluid.DestroyFluids;
+import com.petrolpark.destroy.fluid.ingredient.*;
+import com.simibubi.create.foundation.fluid.FluidIngredient;
+import net.minecraft.nbt.CompoundTag;
+import net.minecraft.network.chat.Component;
+import net.minecraftforge.fluids.FluidStack;
+import org.jetbrains.annotations.Nullable;
+import org.openzen.zencode.java.ZenCodeType;
+
+import java.text.DecimalFormat;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.OptionalInt;
+import java.util.function.Predicate;
+
+@ZenRegister
+@Document("mods/destroy/Mixture")
+@NativeTypeRegistration(value = Mixture.class, zenCodeName = "mods.destroy.Mixture")
+public class CTMixture {
+ /**
+ *
+ * @param data data of molecules and concentration
+ * @param temperature In kelvins, 0 for unspecified
+ * @return
+ */
+ @ZenCodeType.StaticExpansionMethod
+ public static Mixture create(List> data, @ZenCodeType.OptionalFloat(0) float temperature, @ZenCodeType.OptionalString String translationKey) {
+ Mixture mixture = new Mixture();
+ for(Percentaged moleculePercentage : data) {
+ mixture.addMolecule(moleculePercentage.getData(), (float) moleculePercentage.getPercentage());
+ }
+ mixture.setTemperature(ReadOnlyMixture.BASE_TEMPERATURE);
+ if(!"".equals(translationKey)) {
+ mixture.setTranslationKey(translationKey);
+ }
+ return mixture;
+ }
+
+ @ZenCodeType.StaticExpansionMethod
+ public static IFluidStack createMixtureStack(Mixture mixture, @ZenCodeType.OptionalInt(1000) int amount) {
+ FluidStack fluidStack = new FluidStack(DestroyFluids.MIXTURE.get(), amount);
+ fluidStack.getOrCreateTag().put("Mixture", mixture.writeNBT());
+ return IFluidStack.of(fluidStack);
+ }
+
+ @ZenCodeType.StaticExpansionMethod
+ public static CTFluidIngredient createMoleculeFluidIngredient(Molecule molecule, float concentration, @ZenCodeType.OptionalInt(1000) int amount) {
+ MoleculeFluidIngredient result = new MoleculeFluidIngredient();
+ result.molecule = molecule;
+ result.setConcentrations(concentration);
+ FluidStack fluidStack = new FluidStack(DestroyFluids.MIXTURE.get(), amount);
+ result.addNBT(fluidStack.getOrCreateTag());
+ return new CTFluidIngredient.FluidStackIngredient(IFluidStack.of(fluidStack));
+ }
+
+ @ZenCodeType.StaticExpansionMethod
+ public static CTFluidIngredient createSaltFluidIngredient(Molecule cation, Molecule anion, float concentration, @ZenCodeType.OptionalInt(1000) int amount) {
+ SaltFluidIngredient result = new SaltFluidIngredient();
+ result.cation = cation;
+ result.anion = anion;
+ result.setConcentrations(concentration);
+ FluidStack fluidStack = new FluidStack(DestroyFluids.MIXTURE.get(), amount);
+ result.addNBT(fluidStack.getOrCreateTag());
+ return new CTFluidIngredient.FluidStackIngredient(IFluidStack.of(fluidStack));
+ }
+
+ @ZenCodeType.StaticExpansionMethod
+ public static CTFluidIngredient createMoleculeTagFluidIngredient(MoleculeTag tag, float concentration, @ZenCodeType.OptionalInt(1000) int amount) {
+ MoleculeTagFluidIngredient result = new MoleculeTagFluidIngredient();
+ result.tag = tag;
+ result.setConcentrations(concentration);
+ FluidStack fluidStack = new FluidStack(DestroyFluids.MIXTURE.get(), amount);
+ result.addNBT(fluidStack.getOrCreateTag());
+ return new CTFluidIngredient.FluidStackIngredient(IFluidStack.of(fluidStack));
+ }
+
+ @ZenCodeType.StaticExpansionMethod
+ public static CTFluidIngredient createIonFluidIngredient(float concentration, @ZenCodeType.OptionalInt(1000) int amount) {
+ IonFluidIngredient result = new IonFluidIngredient();
+ result.setConcentrations(concentration);
+ FluidStack fluidStack = new FluidStack(DestroyFluids.MIXTURE.get(), amount);
+ result.addNBT(fluidStack.getOrCreateTag());
+ return new CTFluidIngredient.FluidStackIngredient(IFluidStack.of(fluidStack));
+ }
+
+// private static Mixture internal, ;
+
+ @ZenCodeType.StaticExpansionMethod
+ public static Mixture pure(Molecule molecule) {
+ return Mixture.pure(molecule);
+ }
+
+ @ZenCodeType.StaticExpansionMethod
+ public static Mixture mix(Map mixtures) {
+ return Mixture.mix(mixtures);
+ }
+
+ @ZenCodeType.Method
+ @ZenCodeType.Setter("temperature")
+ public static Mixture setTemperature(Mixture internal, float temperature) {
+ return internal.setTemperature(temperature);
+ }
+
+ @ZenCodeType.Method
+ public static Mixture addMolecule(Mixture internal, Molecule molecule, float concentration) {
+ return internal.addMolecule(molecule, concentration);
+ }
+
+ @ZenCodeType.Method
+ public static List getContents(Mixture internal, boolean excludeNovel) {
+ return internal.getContents(excludeNovel);
+ }
+
+ @ZenCodeType.Method
+ public static float getConcentrationOf(Mixture internal, Molecule molecule) {
+ return internal.getConcentrationOf(molecule);
+ }
+
+ @ZenCodeType.Method
+ public static boolean isAtEquilibrium(Mixture internal) {
+ return internal.isAtEquilibrium();
+ }
+
+ @ZenCodeType.Method
+ public static void disturbEquilibrium(Mixture internal) {
+ internal.disturbEquilibrium();
+ }
+
+ @ZenCodeType.Method
+ public static void heat(Mixture internal, float energyDensity) {
+ internal.heat(energyDensity);
+ }
+
+ @ZenCodeType.Method
+ public static void scale(Mixture internal, float volumeIncreaseFactor) {
+ internal.scale(volumeIncreaseFactor);
+ }
+
+ @ZenCodeType.Method
+ public static float getVolumetricHeatCapacity(Mixture internal) {
+ return internal.getVolumetricHeatCapacity();
+ }
+
+ @ZenCodeType.Method
+ public static int getColor(Mixture internal) {
+ return internal.getColor();
+ }
+
+ @ZenCodeType.Method
+ public static void setTranslationKey(Mixture internal, String translationKey) {
+ internal.setTranslationKey(translationKey);
+ }
+
+ @ZenCodeType.Method
+ public static float getTemperature(Mixture internal) {
+ return internal.getTemperature();
+ }
+
+ @ZenCodeType.Method
+ public static boolean isEmpty(Mixture internal) {
+ return internal.isEmpty();
+ }
+
+ @ZenCodeType.Method
+ public static float getTotalConcentration(Mixture internal) {
+ return internal.getTotalConcentration();
+ }
+
+ @ZenCodeType.Method
+ public static boolean hasUsableMolecule(Mixture internal, Molecule molecule, float minConcentration, float maxConcentration, @Nullable Predicate ignore) {
+ return internal.hasUsableMolecule(molecule, minConcentration, maxConcentration, ignore);
+ }
+
+ @ZenCodeType.Method
+ public static boolean hasUsableMolecules(Mixture internal, Predicate molecules, float minConcentration, float maxConcentration, @Nullable Predicate ignore) {
+ return internal.hasUsableMolecules(molecules, minConcentration, maxConcentration, ignore);
+ }
+
+ @ZenCodeType.Method
+ public static String getContentsString(Mixture internal) {
+ return internal.getContentsString();
+ }
+
+ @ZenCodeType.Method
+ public static List getContentsTooltip(Mixture internal, boolean iupac, boolean monospace, boolean useMoles, int amount, DecimalFormat concentrationFormatter) {
+ return internal.getContentsTooltip(iupac, monospace, useMoles, amount, concentrationFormatter);
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/AgingRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/AgingRecipeHandler.java
index 135292278..4a38bdbbd 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/AgingRecipeHandler.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/AgingRecipeHandler.java
@@ -1,6 +1,7 @@
package com.petrolpark.destroy.compat.crafttweaker.recipes.handler;
import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.ingredient.IIngredient;
import com.blamejared.crafttweaker.api.recipe.handler.IRecipeHandler;
import com.blamejared.crafttweaker.api.recipe.manager.base.IRecipeManager;
import com.blamejared.crafttweaker.api.util.random.Percentaged;
@@ -16,15 +17,15 @@ public class AgingRecipeHandler implements IDestroyRecipeHandler {
@Override
public String dumpToCommandString(IRecipeManager super AgingRecipe> manager, AgingRecipe recipe) {
return String.format(
- ".addRecipe(\"%s\", [%s], %s, %s, %s);",
+ ".addRecipe(\"%s\", %s, [%s], %s, %s);",
recipe.getId(),
IFluidStack.of(recipe.getRequiredFluid()).getCommandString(),
- IFluidStack.of(recipe.getFluidResults().get(0)).getCommandString(),
- recipe.getRollableResults()
+ recipe.getIngredients()
.stream()
- .map(CTDestroy::mapProcessingResult)
- .map(Percentaged::getCommandString)
+ .map(IIngredient::fromIngredient)
+ .map(IIngredient::getCommandString)
.collect(Collectors.joining(", ")),
+ IFluidStack.of(recipe.getResult()).getCommandString(),
recipe.getProcessingDuration()
);
}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java
index c59009bf9..51f91efb9 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java
@@ -28,7 +28,9 @@ public String dumpToCommandString(IRecipeManager super CentrifugationRecipe> m
".addRecipe(\"%s\", , %s, [%s]);",
recipe.getId(),
recipe.getRequiredHeat().name().toLowerCase(Locale.ENGLISH),
- recipe.getRequiredFluid(),
+ CTDestroy.getMatchingFluidStacks(recipe.getRequiredFluid()).stream()
+ .map(IFluidStack::getCommandString)
+ .collect(Collectors.joining(", ")),
recipe.getFluidResults()
.stream()
.map(fluid -> IFluidStack.of(fluid).getCommandString())
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/DistillationRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/DistillationRecipeHandler.java
index 79dc4687f..60587f059 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/DistillationRecipeHandler.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/DistillationRecipeHandler.java
@@ -2,6 +2,7 @@
import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.ingredient.IIngredient;
import com.blamejared.crafttweaker.api.recipe.component.BuiltinRecipeComponents;
import com.blamejared.crafttweaker.api.recipe.component.IDecomposedRecipe;
import com.blamejared.crafttweaker.api.recipe.handler.IRecipeHandler;
@@ -13,10 +14,7 @@
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Optional;
+import java.util.*;
import java.util.stream.Collectors;
@IRecipeHandler.For(DistillationRecipe.class)
@@ -25,13 +23,15 @@ public class DistillationRecipeHandler implements IDestroyRecipeHandler manager, DistillationRecipe recipe) {
return String.format(
".addRecipe(\"%s\", , %s, [%s]);",
- recipe.getId(),
- recipe.getRequiredHeat().name().toLowerCase(Locale.ENGLISH),
- recipe.getRequiredFluid(),
- recipe.getFluidResults()
- .stream()
- .map(fluid -> IFluidStack.of(fluid).getCommandString())
- .collect(Collectors.joining(", "))
+ recipe.getId(),
+ recipe.getRequiredHeat().name().toLowerCase(Locale.ENGLISH),
+ CTDestroy.getMatchingFluidStacks(recipe.getRequiredFluid()).stream()
+ .map(IFluidStack::getCommandString)
+ .collect(Collectors.joining(", ")),
+ recipe.getFluidResults()
+ .stream()
+ .map(fluid -> IFluidStack.of(fluid).getCommandString())
+ .collect(Collectors.joining(", "))
);
}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/AgingRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/AgingRecipeHandler.java
new file mode 100644
index 000000000..b503609e7
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/AgingRecipeHandler.java
@@ -0,0 +1,40 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.manager;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.action.recipe.ActionAddRecipe;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.ingredient.IIngredient;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+import com.petrolpark.destroy.recipe.AgingRecipe;
+import com.petrolpark.destroy.recipe.DestroyRecipeTypes;
+import com.petrolpark.destroy.recipe.DistillationRecipe;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import net.minecraft.resources.ResourceLocation;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@Document("mods/destroy/AgingManager")
+@ZenCodeType.Name("mods.destroy.AgingManager")
+public class AgingRecipeHandler implements IDestroyRecipeManager {
+
+ @ZenCodeType.Method
+ public void addRecipe(String name, CTFluidIngredient input, IIngredient[] items, IFluidStack result) {
+ name = fixRecipeName(name);
+ ResourceLocation resourceLocation = new ResourceLocation("crafttweaker", name);
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(getSerializer().getFactory(), resourceLocation);
+ builder.withFluidIngredients(CTDestroy.mapFluidIngredients(input));
+ for(IIngredient itemIngredient : items) {
+ builder.require(itemIngredient.asVanillaIngredient());
+ }
+ CTDestroy.output(builder, result);
+ CraftTweakerAPI.apply(new ActionAddRecipe<>(this, builder.build()));
+ }
+
+ @Override
+ public DestroyRecipeTypes getDestroyRecipeType() {
+ return DestroyRecipeTypes.AGING;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/DistillationRecipeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/DistillationRecipeManager.java
index d1e04a358..adb10273f 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/DistillationRecipeManager.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/DistillationRecipeManager.java
@@ -21,7 +21,13 @@
@ZenCodeType.Name("mods.destroy.DistillationManager")
public class DistillationRecipeManager implements IDestroyRecipeManager {
- // todo: specify that it does not allow mixtures as fluids
+ /**
+ * Adds recipe to the destillation tower
+ * @param name Name of the recipe
+ * @param heat Heat required
+ * @param input Input fluid (DOES NOT ALLOW MIXTURES)
+ * @param fractions How much of other fluids should be created per 1 mB of input fluid
+ */
@ZenCodeType.Method
public void addRecipe(String name, HeatCondition heat, CTFluidIngredient input, IFluidStack[] fractions) {
name = fixRecipeName(name);
diff --git a/src/main/java/com/petrolpark/destroy/fluid/ingredient/ConcentrationRangeFluidIngredient.java b/src/main/java/com/petrolpark/destroy/fluid/ingredient/ConcentrationRangeFluidIngredient.java
index 04e4cefdc..b7190050d 100644
--- a/src/main/java/com/petrolpark/destroy/fluid/ingredient/ConcentrationRangeFluidIngredient.java
+++ b/src/main/java/com/petrolpark/destroy/fluid/ingredient/ConcentrationRangeFluidIngredient.java
@@ -19,8 +19,8 @@ public abstract class ConcentrationRangeFluidIngredient getType() {
diff --git a/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeTagFluidIngredient.java b/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeTagFluidIngredient.java
index 4a2befcc0..c9f1fd37d 100644
--- a/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeTagFluidIngredient.java
+++ b/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeTagFluidIngredient.java
@@ -23,7 +23,7 @@ public class MoleculeTagFluidIngredient extends ConcentrationRangeFluidIngredien
public static final Type TYPE = new Type();
- protected MoleculeTag tag;
+ public MoleculeTag tag;
public MoleculeTagFluidIngredient(MoleculeTag tag, float minConc, float maxConc) {
this.tag = tag;
diff --git a/src/main/java/com/petrolpark/destroy/fluid/ingredient/RefrigerantDummyFluidIngredient.java b/src/main/java/com/petrolpark/destroy/fluid/ingredient/RefrigerantDummyFluidIngredient.java
index 3d7ca9c44..b4d887b37 100644
--- a/src/main/java/com/petrolpark/destroy/fluid/ingredient/RefrigerantDummyFluidIngredient.java
+++ b/src/main/java/com/petrolpark/destroy/fluid/ingredient/RefrigerantDummyFluidIngredient.java
@@ -45,8 +45,7 @@ public String getMixtureFluidIngredientSubtype() {
@Override
public List getDescription(CompoundTag fluidTag) {
- List tooltip = new ArrayList<>();
- tooltip.addAll(TooltipHelper.cutStringTextComponent(DestroyLang.translate("tooltip.mixture_ingredient.molecule_tag_1").string(), Palette.GRAY_AND_WHITE));
+ List tooltip = new ArrayList<>(TooltipHelper.cutStringTextComponent(DestroyLang.translate("tooltip.mixture_ingredient.molecule_tag_1").string(), Palette.GRAY_AND_WHITE));
tooltip.add(DestroyMolecules.Tags.REFRIGERANT.getFormattedName());
tooltip.addAll(TooltipHelper.cutStringTextComponent(DestroyLang.translate("tooltip.mixture_ingredient.refrigerants").string(), Palette.GRAY_AND_WHITE));
return tooltip;
diff --git a/src/main/java/com/petrolpark/destroy/fluid/ingredient/SaltFluidIngredient.java b/src/main/java/com/petrolpark/destroy/fluid/ingredient/SaltFluidIngredient.java
index 3e069358d..0791cafd0 100644
--- a/src/main/java/com/petrolpark/destroy/fluid/ingredient/SaltFluidIngredient.java
+++ b/src/main/java/com/petrolpark/destroy/fluid/ingredient/SaltFluidIngredient.java
@@ -25,8 +25,8 @@ public class SaltFluidIngredient extends ConcentrationRangeFluidIngredient getType() {
@@ -42,7 +42,17 @@ public void addNBT(CompoundTag fluidTag) {
@Override
protected boolean testMixture(Mixture mixture) {
- return mixture.hasUsableMolecule(cation, minConcentration * cation.getCharge(), maxConcentration * cation.getCharge(), (molecule) -> molecule == anion) && mixture.hasUsableMolecule(anion, minConcentration * -anion.getCharge(), maxConcentration * -anion.getCharge(), (molecule) -> molecule == cation);
+ return mixture.hasUsableMolecule(
+ cation,
+ minConcentration * cation.getCharge(),
+ maxConcentration * cation.getCharge(),
+ (molecule) -> molecule == anion
+ ) && mixture.hasUsableMolecule(
+ anion,
+ minConcentration * -anion.getCharge(),
+ maxConcentration * -anion.getCharge(),
+ (molecule) -> molecule == cation
+ );
};
@Override
diff --git a/src/main/java/com/petrolpark/destroy/recipe/AgingRecipe.java b/src/main/java/com/petrolpark/destroy/recipe/AgingRecipe.java
index 167365970..4e016f488 100644
--- a/src/main/java/com/petrolpark/destroy/recipe/AgingRecipe.java
+++ b/src/main/java/com/petrolpark/destroy/recipe/AgingRecipe.java
@@ -3,6 +3,7 @@
import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder.ProcessingRecipeParams;
import net.minecraft.world.level.Level;
+import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.items.wrapper.RecipeWrapper;
public class AgingRecipe extends SingleFluidRecipe {
@@ -11,6 +12,10 @@ public AgingRecipe(ProcessingRecipeParams params) {
super(DestroyRecipeTypes.AGING, params);
};
+ public FluidStack getResult() {
+ return fluidResults.get(0);
+ }
+
@Override
protected int getMaxInputCount() {
return 2;
From 4940bdfbaf482aef46385819bd5e456dfba9f116 Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Thu, 22 Feb 2024 01:31:44 +0100
Subject: [PATCH 09/20] Proper NBT of mixtures for recipes
---
build.gradle | 2 +-
.../destroy/chemistry/Molecule.java | 8 ++++
.../destroy/chemistry/Reaction.java | 40 +++++++++++++++----
.../crafttweaker/CTMoleculeManager.java | 11 +++--
.../crafttweaker/CTReactionManager.java | 1 +
.../action/AddReactionAction.java | 2 +-
.../action/RemoveReactionAction.java | 4 +-
.../crafttweaker/natives/CTMixture.java | 36 ++++++++++++++---
.../crafttweaker/natives/CTMolecule.java | 16 ++++++++
9 files changed, 98 insertions(+), 22 deletions(-)
diff --git a/build.gradle b/build.gradle
index 6af35eea4..972d3aa30 100644
--- a/build.gradle
+++ b/build.gradle
@@ -183,7 +183,7 @@ dependencies {
// CraftTweaker
var tweaker = "com.blamejared.crafttweaker:CraftTweaker-forge-${minecraft_version}:${crafttweaker_version}"
- compileOnly fg.deobf(tweaker)
+ implementation fg.deobf(tweaker)
annotationProcessor(tweaker)
compileOnly("com.blamejared.crafttweaker:CraftTweaker-common-${minecraft_version}:${crafttweaker_version}")
// ANNOTATION PROCESSORS
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java b/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
index 23029e368..0cc4125da 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
@@ -410,6 +410,14 @@ public void addProductReaction(Reaction reaction) {
if (reaction.containsProduct(this)) productReactions.add(reaction);
};
+ public void removeProductReaction(Reaction reaction) {
+ productReactions.remove(reaction);
+ }
+
+ public void removeReactantReaction(Reaction reaction) {
+ reactantReactions.remove(reaction);
+ }
+
/**
* Get the list of {@link Reaction Reactions} of which this Molecule is a necessary Reactant.
* @return List of Reactions ordered by declaration
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
index f9a1d79c7..152cea652 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
@@ -696,14 +696,8 @@ public Reaction build() {
};
if (!generated) {
- for (Molecule reactant : reaction.reactants.keySet()) {
- reactant.addReactantReaction(reaction);
- };
- for (Molecule product : reaction.products.keySet()) {
- product.addProductReaction(reaction);
- };
- REACTIONS.put(reaction.getFullID(), reaction);
- };
+ unregisterReaction(reaction);
+ }
return reaction;
};
@@ -738,6 +732,36 @@ private String reactionString() {
};
};
+ public static void registerReaction(Reaction reaction) {
+ if(reaction == null) {
+ Destroy.LOGGER.warn("Tried to register a null reaction");
+ return;
+ }
+ Reaction.REACTIONS.put(reaction.getFullID(), reaction);
+ for(Molecule product : reaction.getProducts()) {
+ product.addProductReaction(reaction);
+ }
+
+ for(Molecule reactant : reaction.getReactants()) {
+ reactant.addReactantReaction(reaction);
+ }
+ }
+
+ public static void unregisterReaction(Reaction reaction) {
+ if(reaction == null) {
+ Destroy.LOGGER.warn("Tried to unregister a null reaction");
+ return;
+ }
+ Reaction.REACTIONS.remove(reaction.getFullID());
+ for(Molecule product : reaction.products.keySet()) {
+ product.removeProductReaction(reaction);
+ }
+
+ for(Molecule reactant : reaction.reactants.keySet()) {
+ reactant.removeReactantReaction(reaction);
+ }
+ }
+
@Override
public int hashCode() {
return getFullID().hashCode();
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java
index 02ba28699..83d798531 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java
@@ -34,13 +34,16 @@ public static void removeMolecule(Molecule molecule) {
@ZenCodeType.Method
@BracketResolver("molecule")
- public static Object getMolecule(String tokens) {
- if(tokens.startsWith("tag:")) {
- return MoleculeTag.MOLECULE_TAGS.get(tokens.replaceFirst("tag:", ""));
- }
+ public static Molecule getMolecule(String tokens) {
return getMoleculeById(tokens);
}
+ @ZenCodeType.Method
+ @BracketResolver("moleculetag")
+ public static MoleculeTag getMoleculeTag(String tokens) {
+ return MoleculeTag.MOLECULE_TAGS.get(tokens);
+ }
+
@ZenCodeType.Method
@BracketResolver("element")
public static Element getElement(String tokens) {
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTReactionManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTReactionManager.java
index 86ccd6272..61b0170ab 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTReactionManager.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTReactionManager.java
@@ -4,6 +4,7 @@
import com.blamejared.crafttweaker.api.annotation.BracketResolver;
import com.blamejared.crafttweaker.api.annotation.ZenRegister;
import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.chemistry.Molecule;
import com.petrolpark.destroy.chemistry.Reaction;
import com.petrolpark.destroy.compat.crafttweaker.action.RemoveMoleculeAction;
import com.petrolpark.destroy.compat.crafttweaker.action.RemoveReactionAction;
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddReactionAction.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddReactionAction.java
index 1c3447150..f33ae1347 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddReactionAction.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddReactionAction.java
@@ -12,7 +12,7 @@ public AddReactionAction(Reaction reaction) {
}
@Override
public void undo() {
- Reaction.REACTIONS.remove(reaction.getFullID());
+ Reaction.unregisterReaction(reaction);
ReactionCategory.RECIPES.remove(reaction);
}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveReactionAction.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveReactionAction.java
index c8a9e7bdf..61ce6bf09 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveReactionAction.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveReactionAction.java
@@ -15,7 +15,7 @@ public RemoveReactionAction(Reaction reaction) {
@Override
public void undo() {
- Reaction.REACTIONS.put(reaction.getFullID(), reaction);
+ Reaction.registerReaction(reaction);
if(reactionRecipe != null) {
ReactionCategory.RECIPES.put(reaction, reactionRecipe);
}
@@ -33,7 +33,7 @@ public String describeUndo() {
@Override
public void apply() {
- Reaction.REACTIONS.remove(reaction.getFullID());
+ Reaction.unregisterReaction(reaction);
ReactionCategory.RECIPES.remove(reaction);
}
}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
index ecf5b6da0..d6f2d34a8 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
@@ -1,5 +1,6 @@
package com.petrolpark.destroy.compat.crafttweaker.natives;
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
import com.blamejared.crafttweaker.api.annotation.ZenRegister;
import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
import com.blamejared.crafttweaker.api.fluid.IFluidStack;
@@ -7,10 +8,13 @@
import com.blamejared.crafttweaker.api.util.random.Percentaged;
import com.blamejared.crafttweaker_annotations.annotations.Document;
import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
+import com.petrolpark.destroy.Destroy;
+import com.petrolpark.destroy.block.DestroyCauldronInteractions;
import com.petrolpark.destroy.chemistry.Mixture;
import com.petrolpark.destroy.chemistry.Molecule;
import com.petrolpark.destroy.chemistry.MoleculeTag;
import com.petrolpark.destroy.chemistry.ReadOnlyMixture;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
import com.petrolpark.destroy.fluid.DestroyFluids;
import com.petrolpark.destroy.fluid.ingredient.*;
import com.simibubi.create.foundation.fluid.FluidIngredient;
@@ -19,6 +23,7 @@
import net.minecraftforge.fluids.FluidStack;
import org.jetbrains.annotations.Nullable;
import org.openzen.zencode.java.ZenCodeType;
+import org.openzen.zenscript.codemodel.OperatorType;
import java.text.DecimalFormat;
import java.util.List;
@@ -57,14 +62,23 @@ public static IFluidStack createMixtureStack(Mixture mixture, @ZenCodeType.Optio
return IFluidStack.of(fluidStack);
}
+ @ZenCodeType.StaticExpansionMethod
+ public static CTFluidIngredient createMoleculeFluidIngredient(Percentaged moleculeData, @ZenCodeType.OptionalInt(1000) int amount) {
+ return createMoleculeFluidIngredient(moleculeData.getData(), (float) moleculeData.getPercentage(), amount);
+ }
+
@ZenCodeType.StaticExpansionMethod
public static CTFluidIngredient createMoleculeFluidIngredient(Molecule molecule, float concentration, @ZenCodeType.OptionalInt(1000) int amount) {
- MoleculeFluidIngredient result = new MoleculeFluidIngredient();
- result.molecule = molecule;
- result.setConcentrations(concentration);
- FluidStack fluidStack = new FluidStack(DestroyFluids.MIXTURE.get(), amount);
- result.addNBT(fluidStack.getOrCreateTag());
- return new CTFluidIngredient.FluidStackIngredient(IFluidStack.of(fluidStack));
+ MoleculeFluidIngredient ingredient = new MoleculeFluidIngredient();
+ ingredient.molecule = molecule;
+ ingredient.setConcentrations(concentration);
+ ReadOnlyMixture resulting = ingredient.getMixtureOfRightConcentration(molecule);
+ CompoundTag tag = new CompoundTag();
+ ingredient.addNBT(tag);
+ tag.put("Mixture", resulting.writeNBT());
+ tag.putString("MixtureFluidIngredientSubtype", ingredient.getType().getMixtureFluidIngredientSubtype());
+ IFluidStack stack = IFluidStack.ofMutable(DestroyFluids.MIXTURE.get(), amount, tag);
+ return new CTFluidIngredient.FluidStackIngredient(stack);
}
@ZenCodeType.StaticExpansionMethod
@@ -199,4 +213,14 @@ public static String getContentsString(Mixture internal) {
public static List getContentsTooltip(Mixture internal, boolean iupac, boolean monospace, boolean useMoles, int amount, DecimalFormat concentrationFormatter) {
return internal.getContentsTooltip(iupac, monospace, useMoles, amount, concentrationFormatter);
}
+
+ @ZenCodeType.Operator(ZenCodeType.OperatorType.MUL)
+ public static IFluidStack mulMod(Mixture internal, int amount) {
+ return createMixtureStack(internal, amount);
+ }
+
+ @ZenCodeType.Caster(implicit = true)
+ public static IFluidStack castToFluid(Mixture expanded) {
+ return mulMod(expanded, 1000);
+ }
}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMolecule.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMolecule.java
index dbdb0846b..e61481fca 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMolecule.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMolecule.java
@@ -1,6 +1,7 @@
package com.petrolpark.destroy.compat.crafttweaker.natives;
import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker.api.util.random.Percentaged;
import com.blamejared.crafttweaker_annotations.annotations.Document;
import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
import com.petrolpark.destroy.chemistry.Atom;
@@ -167,4 +168,19 @@ public static List getReactantReactions(Molecule internal) {
public static List getProductReactions(Molecule internal) {
return internal.getProductReactions();
}
+
+ @ZenCodeType.Getter("commandString")
+ public static String getCommandString(Molecule expanded) {
+ return "".formatted(expanded.getFullID());
+ }
+
+ @ZenCodeType.Operator(ZenCodeType.OperatorType.MUL)
+ public static Percentaged opMul(Molecule expanded, double amount) {
+ return new Percentaged<>(expanded, amount, CTMolecule::getCommandString);
+ }
+
+ @ZenCodeType.Caster(implicit = true)
+ public static Percentaged castPercentaged(Molecule expanded) {
+ return opMul(expanded, 100.0D);
+ }
}
From 92afdea04947bdf3efe10c07ee5a6df333040087 Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Thu, 22 Feb 2024 16:03:39 +0100
Subject: [PATCH 10/20] Fixed a crash if right clicking on decorative sides of
the vat
---
.../crafttweaker/natives/CTMixture.java | 56 +++----
.../destroy/events/DestroyCommonEvents.java | 1 +
.../MechanicalMixerBlockEntityMixin.java | 155 ++++++++++++------
3 files changed, 132 insertions(+), 80 deletions(-)
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
index d6f2d34a8..611168f2a 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
@@ -1,15 +1,11 @@
package com.petrolpark.destroy.compat.crafttweaker.natives;
-import com.blamejared.crafttweaker.api.CraftTweakerAPI;
import com.blamejared.crafttweaker.api.annotation.ZenRegister;
import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
import com.blamejared.crafttweaker.api.fluid.IFluidStack;
-import com.blamejared.crafttweaker.api.ingredient.IIngredient;
import com.blamejared.crafttweaker.api.util.random.Percentaged;
import com.blamejared.crafttweaker_annotations.annotations.Document;
import com.blamejared.crafttweaker_annotations.annotations.NativeTypeRegistration;
-import com.petrolpark.destroy.Destroy;
-import com.petrolpark.destroy.block.DestroyCauldronInteractions;
import com.petrolpark.destroy.chemistry.Mixture;
import com.petrolpark.destroy.chemistry.Molecule;
import com.petrolpark.destroy.chemistry.MoleculeTag;
@@ -17,19 +13,15 @@
import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
import com.petrolpark.destroy.fluid.DestroyFluids;
import com.petrolpark.destroy.fluid.ingredient.*;
-import com.simibubi.create.foundation.fluid.FluidIngredient;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.Component;
import net.minecraftforge.fluids.FluidStack;
import org.jetbrains.annotations.Nullable;
import org.openzen.zencode.java.ZenCodeType;
-import org.openzen.zenscript.codemodel.OperatorType;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
-import java.util.Objects;
-import java.util.OptionalInt;
import java.util.function.Predicate;
@ZenRegister
@@ -73,45 +65,49 @@ public static CTFluidIngredient createMoleculeFluidIngredient(Molecule molecule,
ingredient.molecule = molecule;
ingredient.setConcentrations(concentration);
ReadOnlyMixture resulting = ingredient.getMixtureOfRightConcentration(molecule);
- CompoundTag tag = new CompoundTag();
- ingredient.addNBT(tag);
+ CompoundTag tag = getTag(ingredient);
tag.put("Mixture", resulting.writeNBT());
- tag.putString("MixtureFluidIngredientSubtype", ingredient.getType().getMixtureFluidIngredientSubtype());
IFluidStack stack = IFluidStack.ofMutable(DestroyFluids.MIXTURE.get(), amount, tag);
+ CTDestroy.getLogger().info(tag.toString());
return new CTFluidIngredient.FluidStackIngredient(stack);
}
@ZenCodeType.StaticExpansionMethod
public static CTFluidIngredient createSaltFluidIngredient(Molecule cation, Molecule anion, float concentration, @ZenCodeType.OptionalInt(1000) int amount) {
- SaltFluidIngredient result = new SaltFluidIngredient();
- result.cation = cation;
- result.anion = anion;
- result.setConcentrations(concentration);
- FluidStack fluidStack = new FluidStack(DestroyFluids.MIXTURE.get(), amount);
- result.addNBT(fluidStack.getOrCreateTag());
- return new CTFluidIngredient.FluidStackIngredient(IFluidStack.of(fluidStack));
+ SaltFluidIngredient ingredient = new SaltFluidIngredient();
+ ingredient.cation = cation;
+ ingredient.anion = anion;
+ ingredient.setConcentrations(concentration);
+ CompoundTag tag = getTag(ingredient);
+ IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, tag);
+ return new CTFluidIngredient.FluidStackIngredient(stack);
}
@ZenCodeType.StaticExpansionMethod
public static CTFluidIngredient createMoleculeTagFluidIngredient(MoleculeTag tag, float concentration, @ZenCodeType.OptionalInt(1000) int amount) {
- MoleculeTagFluidIngredient result = new MoleculeTagFluidIngredient();
- result.tag = tag;
- result.setConcentrations(concentration);
- FluidStack fluidStack = new FluidStack(DestroyFluids.MIXTURE.get(), amount);
- result.addNBT(fluidStack.getOrCreateTag());
- return new CTFluidIngredient.FluidStackIngredient(IFluidStack.of(fluidStack));
+ MoleculeTagFluidIngredient ingredient = new MoleculeTagFluidIngredient();
+ ingredient.tag = tag;
+ ingredient.setConcentrations(concentration);
+ CompoundTag resultTag = getTag(ingredient);
+ IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, resultTag);
+ return new CTFluidIngredient.FluidStackIngredient(stack);
}
@ZenCodeType.StaticExpansionMethod
public static CTFluidIngredient createIonFluidIngredient(float concentration, @ZenCodeType.OptionalInt(1000) int amount) {
- IonFluidIngredient result = new IonFluidIngredient();
- result.setConcentrations(concentration);
- FluidStack fluidStack = new FluidStack(DestroyFluids.MIXTURE.get(), amount);
- result.addNBT(fluidStack.getOrCreateTag());
- return new CTFluidIngredient.FluidStackIngredient(IFluidStack.of(fluidStack));
+ IonFluidIngredient ingredient = new IonFluidIngredient();
+ ingredient.setConcentrations(concentration);
+ CompoundTag tag = getTag(ingredient);
+ IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, tag);
+ return new CTFluidIngredient.FluidStackIngredient(stack);
}
-// private static Mixture internal, ;
+ private static CompoundTag getTag(MixtureFluidIngredient> ingredient) {
+ CompoundTag tag = new CompoundTag();
+ ingredient.addNBT(tag);
+ tag.putString("MixtureFluidIngredientSubtype", ingredient.getType().getMixtureFluidIngredientSubtype());
+ return tag;
+ }
@ZenCodeType.StaticExpansionMethod
public static Mixture pure(Molecule molecule) {
diff --git a/src/main/java/com/petrolpark/destroy/events/DestroyCommonEvents.java b/src/main/java/com/petrolpark/destroy/events/DestroyCommonEvents.java
index 188cf34da..11900e442 100644
--- a/src/main/java/com/petrolpark/destroy/events/DestroyCommonEvents.java
+++ b/src/main/java/com/petrolpark/destroy/events/DestroyCommonEvents.java
@@ -593,6 +593,7 @@ public static void onRightClickBlock(PlayerInteractEvent.RightClickBlock event)
// Fill Test Tubes from any Fluid-containing block
if (stack.getItem() instanceof TestTubeItem && TestTubeItem.isEmpty(stack) && player.isCreative()) {
BlockEntity be = level.getBlockEntity(pos);
+ if(be == null) return; // fix a crash
if (!(be instanceof VatSideBlockEntity) && !(be instanceof VatControllerBlockEntity) && be.getCapability(ForgeCapabilities.FLUID_HANDLER, event.getFace()).map(handler -> {
FluidStack drained = handler.drain(200, FluidAction.SIMULATE);
if (DestroyFluids.isMixture(drained)) {
diff --git a/src/main/java/com/petrolpark/destroy/mixin/MechanicalMixerBlockEntityMixin.java b/src/main/java/com/petrolpark/destroy/mixin/MechanicalMixerBlockEntityMixin.java
index 9551be355..de3622e75 100644
--- a/src/main/java/com/petrolpark/destroy/mixin/MechanicalMixerBlockEntityMixin.java
+++ b/src/main/java/com/petrolpark/destroy/mixin/MechanicalMixerBlockEntityMixin.java
@@ -2,11 +2,20 @@
import java.util.ArrayList;
import java.util.List;
+import java.util.Optional;
+import com.simibubi.create.content.fluids.potion.PotionMixingRecipes;
+import com.simibubi.create.content.kinetics.mixer.MixingRecipe;
+import com.simibubi.create.content.processing.basin.BasinBlockEntity;
+import com.simibubi.create.content.processing.basin.BasinOperatingBlockEntity;
+import com.simibubi.create.infrastructure.config.AllConfigs;
+import net.minecraft.core.BlockPos;
+import net.minecraft.world.level.block.entity.BlockEntityType;
+import net.minecraft.world.level.block.state.BlockState;
import org.spongepowered.asm.mixin.Mixin;
-import org.spongepowered.asm.mixin.injection.At;
-import org.spongepowered.asm.mixin.injection.Inject;
-import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
+import org.spongepowered.asm.mixin.Overwrite;
+import org.spongepowered.asm.mixin.Shadow;
+import org.spongepowered.asm.mixin.Unique;
import com.petrolpark.destroy.fluid.DestroyFluids;
import com.petrolpark.destroy.mixin.accessor.BasinOperatingBlockEntityAccessor;
@@ -22,54 +31,100 @@
import net.minecraftforge.items.IItemHandler;
@Mixin(MechanicalMixerBlockEntity.class)
-public class MechanicalMixerBlockEntityMixin {
-
+public abstract class MechanicalMixerBlockEntityMixin extends BasinOperatingBlockEntity {
+
+ @Shadow public boolean running;
+
+ public MechanicalMixerBlockEntityMixin(BlockEntityType> typeIn, BlockPos pos, BlockState state) {
+ super(typeIn, pos, state);
+ }
+
/**
* Injection into {@link com.simibubi.create.content.contraptions.components.mixer.MechanicalMixerBlockEntity Mechanical Mixers}
* to allow them to recognise Mixtures that are able to React.
- * @see com.petrolpark.destroy.recipe.ReactionInBasinRecipe Reactions in Basins
+ *
+ * @return
+ * @see ReactionInBasinRecipe Reactions in Basins
+ * @author petrolpark
+ * @reason Properly handle recipes which involve mixtures
*/
- @Inject(
- method = "getMatchingRecipes()Ljava/util/List;",
- at = @At("HEAD"),
- cancellable = true,
- remap = false
-
- )
- public void inGetMatchingRecipes(CallbackInfoReturnable
>> ci) {
-
- ((BasinOperatingBlockEntityAccessor)this).invokeGetBasin().ifPresent(basin -> {
-
- if (!basin.hasLevel()) return;
-
- IFluidHandler fluidHandler = basin.getCapability(ForgeCapabilities.FLUID_HANDLER).orElse(null);
- IItemHandler itemHandler = basin.getCapability(ForgeCapabilities.ITEM_HANDLER).orElse(null);
- if (fluidHandler == null || itemHandler == null) return;
-
- boolean containsOnlyMixtures = true;
- List availableItemStacks = new ArrayList<>();
- List availableFluidStacks = new ArrayList<>(); // All (Mixture) Fluid Stacks in this Basin
-
- for (int tank = 0; tank < fluidHandler.getTanks(); tank++) {
- FluidStack fluidStack = fluidHandler.getFluidInTank(tank);
- if (DestroyFluids.isMixture(fluidStack)) {
- availableFluidStacks.add(fluidStack);
- } else if (!fluidStack.isEmpty()) {
- containsOnlyMixtures = false;
- };
- };
-
- if (!containsOnlyMixtures) return; // If there are Fluids other than Mixtures, don't bother Reacting
- if (availableFluidStacks.size() <= 0) return; // If there are no Mixtures, don't bother Reacting
-
- for (int slot = 0; slot < itemHandler.getSlots(); slot++) {
- availableItemStacks.add(itemHandler.getStackInSlot(slot));
- };
-
- // Only return this if there is definitely a Reaction possible
- ReactionInBasinRecipe recipe = ReactionInBasinRecipe.create(availableFluidStacks, availableItemStacks, basin);
- if (!(recipe == null) && BasinRecipe.match(basin, recipe)) ci.setReturnValue(List.of(recipe)); // It thinks basin.getLevel() might be null
- });
- };
-
-};
+ @Overwrite(remap = false)
+ public List> getMatchingRecipes() {
+ List> matchingRecipes = super.getMatchingRecipes();
+ List> basinReactions = destroy$getBasinReactionRecipes();
+ List> together = new ArrayList<>(matchingRecipes.size() + basinReactions.size());
+ together.addAll(matchingRecipes);
+ together.addAll(basinReactions);
+ if (!AllConfigs.server().recipes.allowBrewingInMixer.get())
+ return together;
+
+ Optional basin = getBasin();
+ if (basin.isEmpty())
+ return together;
+
+ BasinBlockEntity basinBlockEntity = basin.get();
+
+ IItemHandler availableItems = basinBlockEntity
+ .getCapability(ForgeCapabilities.ITEM_HANDLER)
+ .orElse(null);
+ if (availableItems == null) {
+ return together;
+ }
+
+ for (int i = 0; i < availableItems.getSlots(); i++) {
+ ItemStack stack = availableItems.getStackInSlot(i);
+ if (stack.isEmpty())
+ continue;
+
+ List list = PotionMixingRecipes.BY_ITEM.get(stack.getItem());
+ if (list == null)
+ continue;
+ for (MixingRecipe mixingRecipe : list)
+ if (matchBasinRecipe(mixingRecipe))
+ matchingRecipes.add(mixingRecipe);
+ }
+
+ return together;
+ }
+
+ @Unique
+ public List> destroy$getBasinReactionRecipes() {
+
+ BasinBlockEntity basin = ((BasinOperatingBlockEntityAccessor) this).invokeGetBasin().orElse(null);
+ if(basin == null) return List.of();
+ if (!basin.hasLevel()) return List.of();
+
+ // ignore IDE warnings here
+ IFluidHandler fluidHandler = basin.getCapability(ForgeCapabilities.FLUID_HANDLER).orElse(null);
+ IItemHandler itemHandler = basin.getCapability(ForgeCapabilities.ITEM_HANDLER).orElse(null);
+ if(fluidHandler == null || itemHandler == null) return List.of();
+ boolean containsOnlyMixtures = true;
+ List availableItemStacks = new ArrayList<>();
+ List availableFluidStacks = new ArrayList<>(); // All (Mixture) Fluid Stacks in this Basin
+
+ for (int tank = 0; tank < fluidHandler.getTanks(); tank++) {
+ FluidStack fluidStack = fluidHandler.getFluidInTank(tank);
+ if (DestroyFluids.isMixture(fluidStack)) {
+ availableFluidStacks.add(fluidStack);
+ } else if (!fluidStack.isEmpty()) {
+ containsOnlyMixtures = false;
+ }
+ }
+
+ if (!containsOnlyMixtures) return List.of(); // If there are Fluids other than Mixtures, don't bother Reacting
+ if (availableFluidStacks.isEmpty()) return List.of(); // If there are no Mixtures, don't bother Reacting
+
+ for (int slot = 0; slot < itemHandler.getSlots(); slot++) {
+ availableItemStacks.add(itemHandler.getStackInSlot(slot));
+ }
+
+ // Only return this if there is definitely a Reaction possible
+ ReactionInBasinRecipe recipe = ReactionInBasinRecipe.create(availableFluidStacks, availableItemStacks, basin);
+ if(recipe == null) return List.of();
+ if (BasinRecipe.match(basin, recipe)) {
+ return List.of(recipe);
+ }
+ return List.of();
+ }
+
+}
From 36c4574feb7e18ae43c1d865072d39bfe48353a7 Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Thu, 22 Feb 2024 19:19:53 +0100
Subject: [PATCH 11/20] fixed horrendous russian translation
---
.../crafttweaker/natives/CTMixture.java | 2 +-
.../ingredient/MoleculeFluidIngredient.java | 1 +
.../destroy/mixin/FluidIngredientMixin.java | 8 +++
.../destroy/mixin/HeatConditionMixin.java | 2 +-
.../resources/assets/destroy/lang/en_us.json | 2 +-
.../resources/assets/destroy/lang/ru_ru.json | 66 +++++++++----------
6 files changed, 45 insertions(+), 36 deletions(-)
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
index 611168f2a..159beadaf 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
@@ -67,7 +67,7 @@ public static CTFluidIngredient createMoleculeFluidIngredient(Molecule molecule,
ReadOnlyMixture resulting = ingredient.getMixtureOfRightConcentration(molecule);
CompoundTag tag = getTag(ingredient);
tag.put("Mixture", resulting.writeNBT());
- IFluidStack stack = IFluidStack.ofMutable(DestroyFluids.MIXTURE.get(), amount, tag);
+ IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, tag);
CTDestroy.getLogger().info(tag.toString());
return new CTFluidIngredient.FluidStackIngredient(stack);
}
diff --git a/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeFluidIngredient.java b/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeFluidIngredient.java
index b28e29577..c218c4112 100644
--- a/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeFluidIngredient.java
+++ b/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeFluidIngredient.java
@@ -7,6 +7,7 @@
import com.petrolpark.destroy.chemistry.Mixture;
import com.petrolpark.destroy.chemistry.Molecule;
import com.petrolpark.destroy.chemistry.ReadOnlyMixture;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
import com.petrolpark.destroy.config.DestroyAllConfigs;
import com.petrolpark.destroy.fluid.ingredient.mixturesubtype.MixtureFluidIngredientSubType;
import com.petrolpark.destroy.util.DestroyLang;
diff --git a/src/main/java/com/petrolpark/destroy/mixin/FluidIngredientMixin.java b/src/main/java/com/petrolpark/destroy/mixin/FluidIngredientMixin.java
index 7d8da293b..56a7cb2fa 100644
--- a/src/main/java/com/petrolpark/destroy/mixin/FluidIngredientMixin.java
+++ b/src/main/java/com/petrolpark/destroy/mixin/FluidIngredientMixin.java
@@ -88,6 +88,10 @@ public static FluidIngredient deserialize(@Nullable JsonElement je) {
return ingredient;
};
+ /**
+ * @author
+ * @reason
+ */
@Overwrite(remap = false)
public void write(FriendlyByteBuf buffer) {
FluidIngredient $this = (FluidIngredient)(Object)this;
@@ -105,6 +109,10 @@ public void write(FriendlyByteBuf buffer) {
((FluidIngredientAccessor)this).invokeWriteInternal(buffer);
};
+ /**
+ * @author
+ * @reason
+ */
@Overwrite(remap = false)
public static FluidIngredient read(FriendlyByteBuf buffer) {
String ingredientType = buffer.readUtf();
diff --git a/src/main/java/com/petrolpark/destroy/mixin/HeatConditionMixin.java b/src/main/java/com/petrolpark/destroy/mixin/HeatConditionMixin.java
index ba4b182d5..677e22f31 100644
--- a/src/main/java/com/petrolpark/destroy/mixin/HeatConditionMixin.java
+++ b/src/main/java/com/petrolpark/destroy/mixin/HeatConditionMixin.java
@@ -57,7 +57,7 @@ public abstract class HeatConditionMixin {
public void inTestBlazeBurner(HeatLevel heatLevel, CallbackInfoReturnable ci) {
HeatCondition thisHeatCondition = (HeatCondition) (Object) (this);
if (thisHeatCondition == COOLED) {
- ci.setReturnValue(heatLevel.name() == "FROSTING");
+ ci.setReturnValue(heatLevel.name().equals("FROSTING"));
};
};
};
diff --git a/src/main/resources/assets/destroy/lang/en_us.json b/src/main/resources/assets/destroy/lang/en_us.json
index 976307a42..9ef0d8ae6 100644
--- a/src/main/resources/assets/destroy/lang/en_us.json
+++ b/src/main/resources/assets/destroy/lang/en_us.json
@@ -45,7 +45,7 @@
"advancement.destroy.mechanical_hands": "Ruler of Everything",
"advancement.destroy.mechanical_hands.description": "Hear the flibbity jibbity jibber jabber",
"advancement.destroy.meth": "Don't Do That Please",
- "advancement.destroy.meth.description": "Attempt to make friends with the FBI",
+ "advancement.destroy.meth.description": "Attempt to make friends with the DEA",
"advancement.destroy.ostwald_process": "Ostwald Process",
"advancement.destroy.ostwald_process.description": "Create Nitric Acid with a Rhodium catalyst in a Vat",
"advancement.destroy.plastic": "The Plastic Age",
diff --git a/src/main/resources/assets/destroy/lang/ru_ru.json b/src/main/resources/assets/destroy/lang/ru_ru.json
index f63658e09..8d62222a5 100644
--- a/src/main/resources/assets/destroy/lang/ru_ru.json
+++ b/src/main/resources/assets/destroy/lang/ru_ru.json
@@ -45,7 +45,7 @@
"advancement.destroy.mechanical_hands":"Повелитель всего сущего",
"advancement.destroy.mechanical_hands.description":"Послушайте болтовню джиббита джибби джаббера",
"advancement.destroy.meth":"Не делайте этого, пожалуйста",
- "advancement.destroy.meth.description":"Попытайтесь подружиться с ФБР",
+ "advancement.destroy.meth.description":"Попытайтесь подружиться с УБН",
"advancement.destroy.ostwald_process":"Процесс Оствальда",
"advancement.destroy.ostwald_process.description":"Создайте азотную кислоту с помощью родиевого катализатора в чане",
"advancement.destroy.plastic":"Пластиковый век",
@@ -64,7 +64,7 @@
"advancement.destroy.urinate.description":"Помочитесь склонившись над чаном в состоянии алкогольного опьянения",
"advancement.destroy.vat":"Чаны мои Чаны",
"advancement.destroy.vat.description":"Проведите химическую реакцию в чане",
- "advancement.destroy.very_drunk":"28% концентрации алкого в крови, ты действовал наверняка, да?",
+ "advancement.destroy.very_drunk":"28% концентрации алкоголя в крови, ты действовал наверняка, да?",
"advancement.destroy.very_drunk.description":"Достигните 10 уровня опьянения",
"badge.destroy.patreon_1":"Дама Разрушения",
@@ -83,7 +83,7 @@
"badge.petrolpark.content_creator":"Демонетизирован",
"badge.petrolpark.content_creator.description":"Подарите Destroy бесплатное продвижение, представив его в качестве создателя контента",
"badge.petrolpark.developer":"Разработчик",
- "badge.petrolpark.developer.description":"Поучавствейте в создании кода или изображений для Destroy",
+ "badge.petrolpark.developer.description":"Поучаствуйте в создании кода или изображений для Destroy",
"badge.petrolpark.early_bird":"Ранняя Пташка, Добытчик Червей",
"badge.petrolpark.early_bird.description":"Станьте одним из первых 1000 игроков, которые сыграют в крупное обновление для Destroy",
"badge.petrolpark.nitro":"CH₃NO₂",
@@ -102,7 +102,7 @@
"block.destroy.anfo_block.tooltip.summary":"Взрывчатка _идеальна_ для добычи _руды_.",
"block.destroy.anfo_block.tooltip.condition1":"При взрыве",
"block.destroy.anfo_block.tooltip.behaviour1":"Наносит _минимальный урон_ существам и взрывает _только_ камень и землю, оставляя руды и все полезное _нетронутыми_.",
- "block.destroy.bubble_cap":"Емкость для дистиляции",
+ "block.destroy.bubble_cap":"Емкость для дистилляции",
"block.destroy.blacklight":"Тёмный свет",
"block.destroy.centrifuge":"Центрифуга",
"block.destroy.coaxial_gear":"Коаксиальная шестерёнка",
@@ -141,7 +141,7 @@
"block.destroy.palladium_block":"Палладиевый блок",
"block.destroy.picric_acid_block":"Блок пикриновой кислоты",
"block.destroy.picric_acid_block.tooltip":"PICRIC_ACID_BLOCK",
- "block.destroy.picric_acid_block.tooltip.summary":"Это _мощное взрывчатое вещество_ может сдетонировать даже _под водой_.",
+ "block.destroy.picric_acid_block.tooltip.summary":"Это _мощное взрывчатое вещество_ может взрываться даже _под водой_.",
"block.destroy.planetary_gearset":"Планетарный редуктор",
"block.destroy.platinum_block":"Платиновый блок",
"block.destroy.pollutometer":"Датчик загрязнения",
@@ -369,7 +369,7 @@
"destroy.chemistry.acid":"Кислоты - это вещества, которые могут отдавать ионы водорода ({протоны, destroy:proton}) другим веществам. Они реагируют с {основаниями, destroy:base}.",
"destroy.chemistry.addition":"Реакция сложения — это реакция, в которой группа прибавляется к {молекуле, destroy:molecule}.",
"destroy.chemistry.addition_elimination":"Реакция сложения-вычитания - это реакция, в которой одна группа вычитается из {молекулы, destroy:molecule}, и только потом прибавляется другая. Это не похоже на {подстановку, destroy:substitution}, где оба случая происходят одновременно.",
- "destroy.chemistry.addition_polymer":"Прибавление {полимера, destroy:polymer} не {конденсирует, destroy:condensation_polymer} побочный продукт, и часто протекает через {механизм, destroy:mechanism} {свободного радикала, destroy:radical}.".
+ "destroy.chemistry.addition_polymer":"Прибавление {полимера, destroy:polymer} не {конденсирует, destroy:condensation_polymer} побочный продукт, и часто протекает через {механизм, destroy:mechanism} {свободного радикала, destroy:radical}.",
"destroy.chemistry.aldehyde":"Альдегид — это вещество [destroy:carbonyl], в котором карбонильный углерод {связан, destroy:bond} как минимум с одним водородом, в отличие от {кетона, destroy:ketone}.",
"destroy.chemistry.alkane":"Алканы представляют собой группу {молекул, destroy:molecule}, содержащих только углерод и водород, и имеющие только одиночные {связи, destroy:bond}.",
"destroy.chemistry.aqua_regia":"В переводе с латыни «королевская вода», царская водка представляет собой смесь [destroy:nitric_acid] и [destroy:hydrochloric_acid], которая может {растворять, destroy:solution} {благородные, destroy:inert} металлы, например золото.",
@@ -457,23 +457,23 @@
"destroy.mixture.supersaturated":"Перенасыщение %1$s",
"destroy.molecule_tag.abundant_in_air":"\uED00\uED00 в изобилии содержится в воздухе",
- "destroy.molecule_tag.acutely_toxic":"\uED01 Высокотоксичное",
+ "destroy.molecule_tag.acutely_toxic":"\uED01 Токсичен",
"destroy.molecule_tag.acid_rain":"\uED02 Отравляет осадки",
- "destroy.molecule_tag.bleach":"\uED03 Отбеливающее",
- "destroy.molecule_tag.carcinogen":"\uED04 Канцерогенное",
- "destroy.molecule_tag.fragrant":"\uED05 Ароматное",
- "destroy.molecule_tag.greenhouse":"\uED06 это Парниковый газ",
+ "destroy.molecule_tag.bleach":"\uED03 Отбеливатель",
+ "destroy.molecule_tag.carcinogen":"\uED04 Канцероген",
+ "destroy.molecule_tag.fragrant":"\uED05 Ароматизатор",
+ "destroy.molecule_tag.greenhouse":"\uED06 Парниковый газ",
"destroy.molecule_tag.hypothetical":"\uED07 Гипотетическое",
- "destroy.molecule_tag.ozone_depleter":"\uED08 Озоноразрушающее",
- "destroy.molecule_tag.plasticizer":"\uED09 это Пластификатор",
- "destroy.molecule_tag.refrigerant":"\uED0A это Хладагент",
- "destroy.molecule_tag.smelly":"\uED0B Вонючее",
- "destroy.molecule_tag.smog":"\uED0C Смогообразующее",
- "destroy.molecule_tag.solvent":"\uED0D Растворяющее",
+ "destroy.molecule_tag.ozone_depleter":"\uED08 Разрушитель озонового слоя",
+ "destroy.molecule_tag.plasticizer":"\uED09 Полимер",
+ "destroy.molecule_tag.refrigerant":"\uED0A Хладагент",
+ "destroy.molecule_tag.smelly":"\uED0B Вонючий",
+ "destroy.molecule_tag.smog":"\uED0C Смог",
+ "destroy.molecule_tag.solvent":"\uED0D Растворитель",
"destroy.ponder.tag.chemistry":"Химия",
"destroy.ponder.tag.chemistry.description":"Компоненты, которые можно использовать для манипулирования смесями",
- "destroy.ponder.tag.destroy":"Уничтожьте машины",
+ "destroy.ponder.tag.destroy":"Механизмы Destroy",
"destroy.ponder.tag.destroy.description":"Компоненты и диковинки, добавленные Destroy",
"destroy.ponder.tag.vat_side_blocks":"Материалы для чанов",
"destroy.ponder.tag.vat_side_blocks.description":"Блоки, из которых можно построить чаны",
@@ -481,12 +481,12 @@
"destroy.ponder.aging_barrel.text_1":"Бочки для выдержки, как и чаши могут быть наполнены жидкостями и предметами.",
"destroy.ponder.aging_barrel.text_2":"В течение длительного времени бочка для выдержки будет производить жидкость.",
"destroy.ponder.aging_barrel.text_3":"Бочка для выдержки также является рабочим местом Трактирщика, который продает дрожжи на уровне Ученика.",
- "destroy.ponder.bubble_cap_generic.header":"Дистилляция жидкостей с помощью емкости для дистиляции",
- "destroy.ponder.bubble_cap_generic.text_1":"Вертикально сложенные блоки емкости для дистиляции создают дистилляционную башню.",
+ "destroy.ponder.bubble_cap_generic.header":"Дистилляция жидкостей с помощью емкости для дистилляции",
+ "destroy.ponder.bubble_cap_generic.text_1":"Вертикально сложенные блоки емкости для дистилляции создают дистилляционную башню.",
"destroy.ponder.bubble_cap_generic.text_2":"Дистилляционные башни будут автоматически дистиллировать жидкости в самой нижней крышке (теплообменнике).",
"destroy.ponder.bubble_cap_generic.text_3":"Чем выше температура кипения жидкости, тем дальше вверх по башне она пройдет.",
"destroy.ponder.bubble_cap_generic.text_4":"Для некоторых рецептов дистилляции требуется нагреватель под теплообменником.",
- "destroy.ponder.bubble_cap_mixtures.header":"Разделение смесей с помощью емкостей для дистиляции",
+ "destroy.ponder.bubble_cap_mixtures.header":"Разделение смесей с помощью емкостей для дистилляции",
"destroy.ponder.bubble_cap_mixtures.text_1":"Дистилляционные башни будут дистиллировать любые смеси.",
"destroy.ponder.bubble_cap_mixtures.text_2":"Вы можете увидеть температуру теплообменника с помощью инженерных очков.",
"destroy.ponder.bubble_cap_mixtures.text_3":"Его можно увеличить с помощью Горелки всполоха.",
@@ -809,7 +809,7 @@
"destroy.tooltip.basin.too_full.title": "Переполнен:",
"destroy.tooltip.basin.too_full": "Эта чаша _переполнится_, если в ней пройдет реакция. Вместо неё попробуйте _чан_.",
"destroy.tooltip.bubble_cap.input_tank": "Теплообменник:",
- "destroy.tooltip.bubble_cap.output_tank": "Емкость для дестилляции:",
+ "destroy.tooltip.bubble_cap.output_tank": "Емкость для дистилляции:",
"destroy.tooltip.bubble_cap.reboiler": "Теплообменник",
"destroy.tooltip.bubble_cap.reboiler_temperature": "Температура теплообменника: %1$s",
"destroy.tooltip.centrifuge.lubrication": "Смазка:",
@@ -902,7 +902,7 @@
"effect.destroy.fragrance": "Аромат",
"effect.destroy.fragrance.description": "Убирает эффект _пахучих химикатов_ с пользователя.",
"effect.destroy.hangover": "Похмелье",
- "effect.destroy.hangover.description": "Наносит урон кажый раз, когда слышен _грумкий шум_; снимается _аспирином_.",
+ "effect.destroy.hangover.description": "Наносит урон каждый раз, когда слышен _громкий шум_; снимается _аспирином_.",
"effect.destroy.inebriation": "Опьянение",
"effect.destroy.inebriation.description": "Делает ходьбу _слегка неуправляемой_; более высокие уровни также вызывают тошноту, слепоту и в конечно итоге, _алкогольное отравление_. В состоянии алкогольного опьянения, вы можете _справить нужду_ в _чан_.",
"effect.destroy.baby_blue_high": "Кайф",
@@ -928,7 +928,7 @@
"fluid.destroy.molten_cinnabar": "Расплавленная киноварь",
"fluid.destroy.molten_sulfur": "Расплавленная сера",
"fluid.destroy.napalm_sundae": "Напалмовый Сандей",
- "fluid.destroy.once_distilled_moonshine": "Одноперегонный самогон",
+ "fluid.destroy.once_distilled_moonshine": "Самогон (1 перегонка)",
"fluid.destroy.perfume": "Духи",
"fluid.destroy.skimmed_milk": "Обезжиренное молоко",
"fluid.destroy.sodium_amalgam": "Амальгама натрия",
@@ -1016,7 +1016,7 @@
"item.destroy.crushed_raw_rhodium": "Дроблённый сырой родий",
"item.destroy.diamond_infused_beetroot": "Наполненная алмазом свекла",
"item.destroy.diamond_infused_beetroot.tooltip": "DIAMOND-INFUSED_BEETROOT",
- "item.destroy.diamond_infused_beetroot.tooltip.summary": "Наполненная _тысячами твёрдых как камень осколков_, которые превосходно _разрывают_ слизистую оболчку желудка.",
+ "item.destroy.diamond_infused_beetroot.tooltip.summary": "Наполненная _тысячами твёрдых как камень осколков_, которые превосходно _разрывают_ слизистую оболочку желудка.",
"item.destroy.diamond_infused_beetroot.tooltip.condition1": "При использовании в качестве боеприпасов для картофельной пушки",
"item.destroy.diamond_infused_beetroot.tooltip.behaviour1": "Поражает цель _отравлением_.",
"item.destroy.diamond_infused_beetroot_ashes": "Наполненный алмазом пепел свеклы",
@@ -1051,7 +1051,7 @@
"item.destroy.gold_infused_beetroot.tooltip.summary": "Золото не _тускнеет_, так же как и эта _свекла_.",
"item.destroy.gold_infused_beetroot.tooltip.condition1": "При использовании в качестве боеприпасов для картофельной пушки",
"item.destroy.gold_infused_beetroot.tooltip.behaviour1": "Поражает цель _регенерацией_.",
- "item.destroy.gold_infused_beetroot_ashes": "Наполнненый золотом пепел свеклы",
+ "item.destroy.gold_infused_beetroot_ashes": "Наполненный золотом пепел свеклы",
"item.destroy.hazmat_leggings": "Поножи химзащиты",
"item.destroy.hazmat_leggings.tooltip": "HAZMAT_LEGGINGS",
"item.destroy.hazmat_leggings.tooltip.summary": "В купе с _противогазом_, _костюмом химзащиты_ и _поножами химзащиты_, они защищают владельца от опасных веществ.",
@@ -1076,17 +1076,17 @@
"item.destroy.iron_infused_beetroot.tooltip.summary": "Научное название _свеклы_ - _Beta Vulgaris_. Но не этой. Это _Alpha Bulgaris_.",
"item.destroy.iron_infused_beetroot.tooltip.condition1": "При использовании в качестве боеприпасов для картофельной пушки",
"item.destroy.iron_infused_beetroot.tooltip.behaviour1": "Поражает цель _сопротивлением_.",
- "item.destroy.iron_infused_beetroot_ashes": "Наполнненый железом пепел свеклы",
+ "item.destroy.iron_infused_beetroot_ashes": "Наполненный железом пепел свеклы",
"item.destroy.iron_powder": "Железная пыль",
"item.destroy.lapis_infused_beetroot": "Наполненная лазуритом свекла",
"item.destroy.lapis_infused_beetroot.tooltip": "LAPIS-INFUSED_BEETROOT",
"item.destroy.lapis_infused_beetroot.tooltip.summary": "Наполнена _магией богини_.",
"item.destroy.lapis_infused_beetroot.tooltip.condition1": "При использовании в качестве боеприпасов для картофельной пушки",
"item.destroy.lapis_infused_beetroot.tooltip.behaviour1": "Поражает цель _свечением_.",
- "item.destroy.lapis_infused_beetroot_ashes": "Наплолненный лазуритом пепел свеклы",
+ "item.destroy.lapis_infused_beetroot_ashes": "Наполненный лазуритом пепел свеклы",
"item.destroy.logo": "Destroy",
"item.destroy.logo.tooltip": "DESTROY",
- "item.destroy.logo.tooltip.summary": "Химия и Резнья",
+ "item.destroy.logo.tooltip.summary": "Химия и Резня",
"item.destroy.magic_beetroot_seeds": "Волшебные семена свеклы",
"item.destroy.magic_beetroot_seeds.tooltip": "MAGIC_BEETROOT_SEEDS",
"item.destroy.magic_beetroot_seeds.tooltip.summary": "Вырастает в случайную _наполненную свеклу_.",
@@ -1110,7 +1110,7 @@
"item.destroy.nickel_powder": "Никелевая пыль",
"item.destroy.nitrocellulose": "Нитроцеллюлоза",
"item.destroy.nylon": "Нейлон",
- "item.destroy.once_distilled_moonshine_bottle": "Бутылка одноперегонного самогона",
+ "item.destroy.once_distilled_moonshine_bottle": "Бутылка самогона (1 перегонка)",
"item.destroy.palladium_ingot": "Палладиевый слиток",
"item.destroy.palladium_powder": "Палладиевая пыль",
"item.destroy.palladium_on_carbon": "Углеродистый палладий",
@@ -1130,7 +1130,7 @@
"REMOVEDitem.destroy.playwell.tooltip.behaviour1": "_Житель_ построит _ЛЕГ-_ кхм, _игрушечный_ домик (ему было бы _очень грустно_, если бы он сломался).",
"item.destroy.polyethene_terephthalate": "ПЭТ",
"item.destroy.polyethene": "Полиэтилен",
- "item.destroy.polypropene": "Полиропилен",
+ "item.destroy.polypropene": "Полипропилен",
"item.destroy.polystyrene": "Полистирол",
"item.destroy.polystyrene_butadiene": "СКС",
"item.destroy.polytetrafluoroethene": "ПТФЭ",
@@ -1182,7 +1182,7 @@
"item.destroy.thermite_brownie.tooltip": "THERMITE_BROWNIE",
"item.destroy.thermite_brownie.tooltip.summary": "Этот брауни даже острее обычного. _Горелки Всполоха_ в шоки.",
"item.destroy.thrice_distilled_moonshine_bottle": "Бутылка самогона тройной перегонки",
- "item.destroy.tnt_tablet": "ТНТ таблетка",
+ "item.destroy.tnt_tablet": "Тротиловая таблетка",
"item.destroy.touch_powder": "Йодистый азот",
"item.destroy.touch_powder.tooltip": "TOUCH_POWDER",
"item.destroy.touch_powder.tooltip.summary": "_Чрезвычайно чувствительная_ взрывчатка, которая может взорваться если хоть немного её _коснуться_. Полезна вместе с _Сейсмографом_.",
@@ -1196,7 +1196,7 @@
"item.destroy.unprocessed_conversion_catalyst": "Незаконченный катализатор конверсии",
"item.destroy.unprocessed_mashed_potato": "Незаконченное картофельное пюре",
"item.destroy.unprocessed_napalm_sundae": "Незаконченный Сандей с напалмом",
- "item.destroy.unseasoned_fries": "Неприправлено приготовленная картошка-фри (ты серьезно?)",
+ "item.destroy.unseasoned_fries": "Картошка-фри без приправы (ты серьезно?)",
"item.destroy.urine_bottle": "Бутылка мочи",
"item.destroy.urine_bottle.tooltip": "BOTTLE_OF_URINE",
"item.destroy.urine_bottle.tooltip.summary": "_Фу!_ Однако... это хороший источник _аммиака_. Для получения _присядьте_ над _котлом с водой_ в состоянии алкогольного опьянения...",
From 045d69a3e82233ca4fef8d67ec544296dc7a96be Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Fri, 23 Feb 2024 14:02:14 +0100
Subject: [PATCH 12/20] finally made custom recipes work with mixtures (rip 8
hours of my life :( )
---
build.gradle | 5 +++
.../crafttweaker/natives/CTMixture.java | 11 ++----
.../fluid/ingredient/IonFluidIngredient.java | 2 +-
.../ingredient/MoleculeFluidIngredient.java | 14 ++++++-
.../MoleculeTagFluidIngredient.java | 11 +++++-
.../fluid/ingredient/SaltFluidIngredient.java | 12 +++++-
.../MixtureFluidIngredientSubType.java | 7 ++++
.../destroy/mixin/FluidIngredientMixin.java | 39 ++++++++++++++-----
src/main/resources/destroy.mixins.json | 2 +-
9 files changed, 79 insertions(+), 24 deletions(-)
diff --git a/build.gradle b/build.gradle
index 972d3aa30..a60be42f0 100644
--- a/build.gradle
+++ b/build.gradle
@@ -120,6 +120,10 @@ repositories {
name = 'BlameJared Maven'
}
+ maven {
+ url = 'https://www.jitpack.io'
+ }
+
exclusiveContent {
forRepository {
maven {
@@ -187,6 +191,7 @@ dependencies {
annotationProcessor(tweaker)
compileOnly("com.blamejared.crafttweaker:CraftTweaker-common-${minecraft_version}:${crafttweaker_version}")
// ANNOTATION PROCESSORS
+// implementation fg.deobf("com.blamejared:CreateTweaker:1.0.0.12")
annotationProcessor "org.spongepowered:mixin:${mixin_version}:processor"
}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
index 159beadaf..7b16f9323 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/natives/CTMixture.java
@@ -64,9 +64,7 @@ public static CTFluidIngredient createMoleculeFluidIngredient(Molecule molecule,
MoleculeFluidIngredient ingredient = new MoleculeFluidIngredient();
ingredient.molecule = molecule;
ingredient.setConcentrations(concentration);
- ReadOnlyMixture resulting = ingredient.getMixtureOfRightConcentration(molecule);
CompoundTag tag = getTag(ingredient);
- tag.put("Mixture", resulting.writeNBT());
IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, tag);
CTDestroy.getLogger().info(tag.toString());
return new CTFluidIngredient.FluidStackIngredient(stack);
@@ -78,8 +76,7 @@ public static CTFluidIngredient createSaltFluidIngredient(Molecule cation, Molec
ingredient.cation = cation;
ingredient.anion = anion;
ingredient.setConcentrations(concentration);
- CompoundTag tag = getTag(ingredient);
- IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, tag);
+ IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, getTag(ingredient));
return new CTFluidIngredient.FluidStackIngredient(stack);
}
@@ -88,8 +85,7 @@ public static CTFluidIngredient createMoleculeTagFluidIngredient(MoleculeTag tag
MoleculeTagFluidIngredient ingredient = new MoleculeTagFluidIngredient();
ingredient.tag = tag;
ingredient.setConcentrations(concentration);
- CompoundTag resultTag = getTag(ingredient);
- IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, resultTag);
+ IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, getTag(ingredient));
return new CTFluidIngredient.FluidStackIngredient(stack);
}
@@ -97,8 +93,7 @@ public static CTFluidIngredient createMoleculeTagFluidIngredient(MoleculeTag tag
public static CTFluidIngredient createIonFluidIngredient(float concentration, @ZenCodeType.OptionalInt(1000) int amount) {
IonFluidIngredient ingredient = new IonFluidIngredient();
ingredient.setConcentrations(concentration);
- CompoundTag tag = getTag(ingredient);
- IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, tag);
+ IFluidStack stack = IFluidStack.of(DestroyFluids.MIXTURE.get(), amount, getTag(ingredient));
return new CTFluidIngredient.FluidStackIngredient(stack);
}
diff --git a/src/main/java/com/petrolpark/destroy/fluid/ingredient/IonFluidIngredient.java b/src/main/java/com/petrolpark/destroy/fluid/ingredient/IonFluidIngredient.java
index 2008b5842..0b67bce02 100644
--- a/src/main/java/com/petrolpark/destroy/fluid/ingredient/IonFluidIngredient.java
+++ b/src/main/java/com/petrolpark/destroy/fluid/ingredient/IonFluidIngredient.java
@@ -40,7 +40,7 @@ public List getExampleMixtures() {
return List.of(mixture);
};
- protected static class Type extends MoleculeFluidIngredient.Type {
+ public static class Type extends MoleculeFluidIngredient.Type {
@Override
public IonFluidIngredient getNew() {
diff --git a/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeFluidIngredient.java b/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeFluidIngredient.java
index c218c4112..3a69d785e 100644
--- a/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeFluidIngredient.java
+++ b/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeFluidIngredient.java
@@ -70,12 +70,22 @@ public List getExampleMixtures() {
return List.of(getMixtureOfRightConcentration(molecule));
};
- protected static class Type extends MixtureFluidIngredientSubType {
+ public static class Type extends MixtureFluidIngredientSubType {
@Override
public MoleculeFluidIngredient getNew() {
return new MoleculeFluidIngredient();
- };
+ }
+
+ @Override
+ public MoleculeFluidIngredient fromNBT(CompoundTag tag) {
+ MoleculeFluidIngredient result = new MoleculeFluidIngredient();
+ result.molecule = Molecule.getMolecule(tag.getString("MoleculeRequired"));
+ result.minConcentration = tag.getFloat("MinimumConcentration");
+ result.maxConcentration = tag.getFloat("MaximumConcentration");
+ return result;
+ }
+
@Override
public String getMixtureFluidIngredientSubtype() {
diff --git a/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeTagFluidIngredient.java b/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeTagFluidIngredient.java
index c9f1fd37d..198e5b6d6 100644
--- a/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeTagFluidIngredient.java
+++ b/src/main/java/com/petrolpark/destroy/fluid/ingredient/MoleculeTagFluidIngredient.java
@@ -82,13 +82,22 @@ public List getExampleMixtures() {
return MoleculeTag.MOLECULES_WITH_TAGS.get(tag).stream().map(this::getMixtureOfRightConcentration).toList();
};
- protected static class Type extends MixtureFluidIngredientSubType {
+ public static class Type extends MixtureFluidIngredientSubType {
@Override
public MoleculeTagFluidIngredient getNew() {
return new MoleculeTagFluidIngredient();
};
+ @Override
+ public MoleculeTagFluidIngredient fromNBT(CompoundTag tag) {
+ MoleculeTagFluidIngredient result = new MoleculeTagFluidIngredient();
+ result.tag = MoleculeTag.MOLECULE_TAGS.get(tag.getString("MoleculeTag"));
+ result.minConcentration = tag.getFloat("MinimumConcentration");
+ result.maxConcentration = tag.getFloat("MaximumConcentration");
+ return result;
+ }
+
@Override
public String getMixtureFluidIngredientSubtype() {
return "mixtureFluidWithTaggedMolecules";
diff --git a/src/main/java/com/petrolpark/destroy/fluid/ingredient/SaltFluidIngredient.java b/src/main/java/com/petrolpark/destroy/fluid/ingredient/SaltFluidIngredient.java
index 0791cafd0..a6050154f 100644
--- a/src/main/java/com/petrolpark/destroy/fluid/ingredient/SaltFluidIngredient.java
+++ b/src/main/java/com/petrolpark/destroy/fluid/ingredient/SaltFluidIngredient.java
@@ -96,13 +96,23 @@ public List getExampleMixtures() {
return List.of(mixture);
};
- protected static class Type extends MixtureFluidIngredientSubType {
+ public static class Type extends MixtureFluidIngredientSubType {
@Override
public SaltFluidIngredient getNew() {
return new SaltFluidIngredient();
};
+ @Override
+ public SaltFluidIngredient fromNBT(CompoundTag tag) {
+ SaltFluidIngredient result = new SaltFluidIngredient();
+ result.cation = Molecule.getMolecule(tag.getString("RequiredCation"));
+ result.anion = Molecule.getMolecule(tag.getString("RequiredAnion"));
+ result.minConcentration = tag.getFloat("MinimumConcentration");
+ result.maxConcentration = tag.getFloat("MaximumConcentration");
+ return result;
+ }
+
@Override
public String getMixtureFluidIngredientSubtype() {
return "mixtureFluidWithSalt";
diff --git a/src/main/java/com/petrolpark/destroy/fluid/ingredient/mixturesubtype/MixtureFluidIngredientSubType.java b/src/main/java/com/petrolpark/destroy/fluid/ingredient/mixturesubtype/MixtureFluidIngredientSubType.java
index 34904d295..2f89411bf 100644
--- a/src/main/java/com/petrolpark/destroy/fluid/ingredient/mixturesubtype/MixtureFluidIngredientSubType.java
+++ b/src/main/java/com/petrolpark/destroy/fluid/ingredient/mixturesubtype/MixtureFluidIngredientSubType.java
@@ -13,6 +13,13 @@ public abstract class MixtureFluidIngredientSubType cir) {
+ CompoundTag tag = fluidStack.getTag();
+ if(tag == null) return;
+ String subtypeName = tag.getString("MixtureFluidIngredientSubtype");
+ if(subtypeName.isEmpty()) return;
+ MixtureFluidIngredientSubType> subtype = MixtureFluidIngredient.MIXTURE_FLUID_INGREDIENT_SUBTYPES.get(subtypeName);
+ if(subtype == null) return;
+ cir.setReturnValue(subtype.fromNBT(tag));
+ }
};
diff --git a/src/main/resources/destroy.mixins.json b/src/main/resources/destroy.mixins.json
index 385dbadaf..dc80bc1e9 100644
--- a/src/main/resources/destroy.mixins.json
+++ b/src/main/resources/destroy.mixins.json
@@ -1,5 +1,5 @@
{
- "required": "true",
+ "required": true,
"package": "com.petrolpark.destroy.mixin",
"compatibilityLevel": "JAVA_17",
"refmap": "destroy.refmap.json",
From cf8dc9a7c7dd4931d1d8546753408713eb5f2f93 Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Fri, 23 Feb 2024 15:07:14 +0100
Subject: [PATCH 13/20] All recipe managers are implemented
---
build.gradle | 4 +
.../compat/crafttweaker/CTDestroy.java | 4 +
.../handler/CentrifugationRecipeHandler.java | 8 +-
.../handler/IDestroyRecipeHandler.java | 5 +-
.../manager/CentrifugationRecipeManager.java | 39 ++++++
.../manager/ChargingRecipeManager.java | 39 ++++++
.../manager/ElectrolysisRecipeManager.java | 130 ++++++++++++++++++
7 files changed, 224 insertions(+), 5 deletions(-)
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/CentrifugationRecipeManager.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/ChargingRecipeManager.java
create mode 100644 src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/ElectrolysisRecipeManager.java
diff --git a/build.gradle b/build.gradle
index a60be42f0..631fa8f6b 100644
--- a/build.gradle
+++ b/build.gradle
@@ -211,6 +211,10 @@ jar {
}
}
+javadoc {
+ options.encoding = 'UTF-8'
+}
+
// Example configuration to allow publishing using the maven-publish plugin
// This is the preferred method to reobfuscate your jar file
jar.finalizedBy('reobfJar')
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
index c1c66353e..0f970d7f7 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
@@ -60,6 +60,10 @@ public static ProcessingOutput mapPercentagedToProcessingOutput(Percentaged> ProcessingRecipeBuilder withFluidOutputs(ProcessingRecipeBuilder builder, List fluidOutputs) {
builder.withFluidOutputs(fluidOutputs.stream()
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java
index 51f91efb9..8e50614a4 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/CentrifugationRecipeHandler.java
@@ -25,16 +25,16 @@ public class CentrifugationRecipeHandler implements IDestroyRecipeHandler manager, CentrifugationRecipe recipe) {
return String.format(
- ".addRecipe(\"%s\", , %s, [%s]);",
+ ".addRecipe(\"%s\", %s, [%s], %s);",
recipe.getId(),
- recipe.getRequiredHeat().name().toLowerCase(Locale.ENGLISH),
CTDestroy.getMatchingFluidStacks(recipe.getRequiredFluid()).stream()
.map(IFluidStack::getCommandString)
.collect(Collectors.joining(", ")),
recipe.getFluidResults()
.stream()
.map(fluid -> IFluidStack.of(fluid).getCommandString())
- .collect(Collectors.joining(", "))
+ .collect(Collectors.joining(", ")),
+ recipe.getProcessingDuration()
);
}
@@ -47,6 +47,7 @@ public Optional decompose(IRecipeManager super Centrifugati
IDecomposedRecipe result = IDecomposedRecipe.builder()
.with(BuiltinRecipeComponents.Input.FLUID_INGREDIENTS, List.of(IFluidStack.of(recipe.getRequiredFluid()).asFluidIngredient()))
.with(BuiltinRecipeComponents.Output.FLUIDS, results)
+ .with(BuiltinRecipeComponents.Processing.TIME, recipe.getProcessingDuration())
.build();
return Optional.of(result);
}
@@ -57,6 +58,7 @@ public Optional recompose(IRecipeManager super Centrifug
CTFluidIngredient source = recipe.getOrThrow(BuiltinRecipeComponents.Input.FLUID_INGREDIENTS).get(0);
builder.withFluidIngredients(CTDestroy.mapFluidIngredients(source));
CTDestroy.withFluidOutputs(builder, recipe.getOrThrow(BuiltinRecipeComponents.Output.FLUIDS));
+ builder.duration(recipe.getOrThrow(BuiltinRecipeComponents.Processing.TIME).get(0));
return Optional.of(builder.build());
}
@Override
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/IDestroyRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/IDestroyRecipeHandler.java
index 8a5a46183..d961290fc 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/IDestroyRecipeHandler.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/handler/IDestroyRecipeHandler.java
@@ -42,7 +42,7 @@ default String dumpToCommandString(IRecipeManager super T> iRecipeManager, T r
.map(CTDestroy::mapProcessingResult));
}
- return String.format(".addRecipe(\"%s\", , [%s], [%s], [%s], [%s]);",
+ return String.format(".addRecipe(\"%s\", , [%s], [%s], [%s], [%s], %s);",
recipe.getId(),
recipe.getRequiredHeat().name().toLowerCase(Locale.ENGLISH),
result.map(results -> results.map(Percentaged::getCommandString)
@@ -60,7 +60,8 @@ default String dumpToCommandString(IRecipeManager super T> iRecipeManager, T r
.collect(Collectors.joining(", ")),
CTDestroy.streamFluidResults(recipe)
.map(IFluidStack::getCommandString)
- .collect(Collectors.joining(", "))
+ .collect(Collectors.joining(", ")),
+ recipe.getProcessingDuration()
);
}
@Override
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/CentrifugationRecipeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/CentrifugationRecipeManager.java
new file mode 100644
index 000000000..48618332d
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/CentrifugationRecipeManager.java
@@ -0,0 +1,39 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.manager;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.action.recipe.ActionAddRecipe;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+import com.petrolpark.destroy.recipe.CentrifugationRecipe;
+import com.petrolpark.destroy.recipe.DestroyRecipeTypes;
+import com.petrolpark.destroy.recipe.DistillationRecipe;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import net.minecraft.resources.ResourceLocation;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@Document("mods/destroy/CentrifugationManager")
+@ZenCodeType.Name("mods.destroy.CentrifugationManager")
+public class CentrifugationRecipeManager implements IDestroyRecipeManager {
+
+ @ZenCodeType.Method
+ public void addRecipe(String name, CTFluidIngredient input, IFluidStack[] output, @ZenCodeType.OptionalInt(1200) int processingTime) {
+ name = fixRecipeName(name);
+ ResourceLocation resourceLocation = new ResourceLocation("crafttweaker", name);
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(getSerializer().getFactory(), resourceLocation);
+ builder.withFluidIngredients(CTDestroy.mapFluidIngredients(input));
+ for(IFluidStack fraction : output) {
+ CTDestroy.output(builder, fraction);
+ }
+ builder.duration(processingTime);
+ CraftTweakerAPI.apply(new ActionAddRecipe<>(this, builder.build()));
+ }
+
+ @Override
+ public DestroyRecipeTypes getDestroyRecipeType() {
+ return DestroyRecipeTypes.CENTRIFUGATION;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/ChargingRecipeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/ChargingRecipeManager.java
new file mode 100644
index 000000000..b1be9a281
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/ChargingRecipeManager.java
@@ -0,0 +1,39 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.manager;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.action.recipe.ActionAddRecipe;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.ingredient.IIngredient;
+import com.blamejared.crafttweaker.api.item.IItemStack;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+import com.petrolpark.destroy.recipe.CentrifugationRecipe;
+import com.petrolpark.destroy.recipe.ChargingRecipe;
+import com.petrolpark.destroy.recipe.DestroyRecipeTypes;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.world.item.crafting.Ingredient;
+import org.openzen.zencode.java.ZenCodeType;
+
+@ZenRegister
+@Document("mods/destroy/ChargingManager")
+@ZenCodeType.Name("mods.destroy.ChargingManager")
+public class ChargingRecipeManager implements IDestroyRecipeManager {
+
+ @ZenCodeType.Method
+ public void addRecipe(String name, IIngredient input, IItemStack output) {
+ name = fixRecipeName(name);
+ ResourceLocation resourceLocation = new ResourceLocation("crafttweaker", name);
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(getSerializer().getFactory(), resourceLocation);
+ builder.withItemIngredients(input.asVanillaIngredient());
+ builder.withItemOutputs(CTDestroy.mapItemStackToProcessingOutput(output));
+ CraftTweakerAPI.apply(new ActionAddRecipe<>(this, builder.build()));
+ }
+
+ @Override
+ public DestroyRecipeTypes getDestroyRecipeType() {
+ return DestroyRecipeTypes.CHARGING;
+ }
+}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/ElectrolysisRecipeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/ElectrolysisRecipeManager.java
new file mode 100644
index 000000000..520a772bb
--- /dev/null
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/ElectrolysisRecipeManager.java
@@ -0,0 +1,130 @@
+package com.petrolpark.destroy.compat.crafttweaker.recipes.manager;
+
+import com.blamejared.crafttweaker.api.CraftTweakerAPI;
+import com.blamejared.crafttweaker.api.action.recipe.ActionAddRecipe;
+import com.blamejared.crafttweaker.api.annotation.ZenRegister;
+import com.blamejared.crafttweaker.api.fluid.CTFluidIngredient;
+import com.blamejared.crafttweaker.api.fluid.IFluidStack;
+import com.blamejared.crafttweaker.api.ingredient.IIngredient;
+import com.blamejared.crafttweaker.api.ingredient.IIngredientWithAmount;
+import com.blamejared.crafttweaker.api.item.IItemStack;
+import com.blamejared.crafttweaker.api.util.random.Percentaged;
+import com.blamejared.crafttweaker_annotations.annotations.Document;
+import com.petrolpark.destroy.compat.crafttweaker.CTDestroy;
+import com.petrolpark.destroy.recipe.ChargingRecipe;
+import com.petrolpark.destroy.recipe.DestroyRecipeTypes;
+import com.petrolpark.destroy.recipe.ElectrolysisRecipe;
+import com.simibubi.create.content.processing.recipe.HeatCondition;
+import com.simibubi.create.content.processing.recipe.ProcessingRecipeBuilder;
+import com.simibubi.create.foundation.fluid.FluidIngredient;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.world.item.crafting.Ingredient;
+import org.openzen.zencode.java.ZenCodeType;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+@ZenRegister
+@Document("mods/destroy/ElectrolysisManager")
+@ZenCodeType.Name("mods.destroy.ElectrolysisManager")
+public class ElectrolysisRecipeManager implements IDestroyRecipeManager {
+
+ /**
+ * Adds a mixing recipe that outputs ItemStacks.
+ *
+ * @param name The name of the recipe.
+ * @param heat The required heat of the recipe.
+ * @param outputs The output ItemStacks of the recipe.
+ * @param itemInputs The item inputs of the recipe.
+ * @param fluidInputs The optional fluid inputs of the recipe.
+ * @param duration The duration of the recipe in ticks.
+ *
+ * @docParam name "mixed"
+ * @docParam heat
+ * @docParam outputs [ % 50, , ( * 2) % 12]
+ * @docParam itemInputs [ * 2]
+ * @docParam fluidInputs [ * 250]
+ * @docParam duration 200
+ */
+ @ZenCodeType.Method
+ public void addRecipe(String name, HeatCondition heat, Percentaged[] outputs, IIngredientWithAmount[] itemInputs, @ZenCodeType.Optional("[] as crafttweaker.api.fluid.FluidIngredient[]") CTFluidIngredient[] fluidInputs, @ZenCodeType.OptionalInt(100) int duration) {
+
+ name = fixRecipeName(name);
+ ResourceLocation resourceLocation = new ResourceLocation("crafttweaker", name);
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(getSerializer().getFactory(), resourceLocation);
+ for(Percentaged output : outputs) {
+
+ builder.output((float) output.getPercentage(), output.getData().getInternal());
+ }
+
+ List ingredients = new ArrayList<>();
+ for(IIngredientWithAmount iIngredientWithAmount : itemInputs) {
+ for(int i = 0; i < iIngredientWithAmount.getAmount(); i++) {
+ ingredients.add(iIngredientWithAmount.getIngredient()
+ .asVanillaIngredient());
+ }
+ }
+ builder.withItemIngredients(ingredients.toArray(new Ingredient[0]));
+ if(fluidInputs != null && fluidInputs.length != 0) {
+ builder.withFluidIngredients(Arrays.stream(fluidInputs)
+ .map(CTDestroy::mapFluidIngredients)
+ .toArray(FluidIngredient[]::new));
+ }
+ builder.requiresHeat(heat);
+
+ builder.duration(duration);
+ CraftTweakerAPI.apply(new ActionAddRecipe<>(this, builder.build()));
+ }
+
+ /**
+ * Adds a mixing recipe that outputs FluidStacks.
+ *
+ * @param name The name of the recipe.
+ * @param heat The required heat of the recipe.
+ * @param outputs The output FluidStacks of the recipe.
+ * @param itemInputs The item inputs of the recipe.
+ * @param fluidInputs The optional fluid inputs of the recipe.
+ * @param duration The duration of the recipe in ticks.
+ *
+ * @docParam name "fluid_mixed"
+ * @docParam heat
+ * @docParam outputs [ * 200]
+ * @docParam itemInputs [ * 2]
+ * @docParam fluidInputs [ * 250]
+ * @docParam duration 200
+ */
+ @ZenCodeType.Method
+ public void addRecipe(String name, HeatCondition heat, IFluidStack[] outputs, IIngredientWithAmount[] itemInputs, @ZenCodeType.Optional("[] as crafttweaker.api.fluid.FluidIngredient[]") CTFluidIngredient[] fluidInputs, @ZenCodeType.OptionalInt(100) int duration) {
+
+ name = fixRecipeName(name);
+ ResourceLocation resourceLocation = new ResourceLocation("crafttweaker", name);
+ ProcessingRecipeBuilder builder = new ProcessingRecipeBuilder<>(getSerializer().getFactory(), resourceLocation);
+
+ for(IFluidStack output : outputs) {
+ CTDestroy.output(builder, output);
+ }
+
+ List ingredients = new ArrayList<>(itemInputs.length);
+ for(IIngredientWithAmount iIngredientWithAmount : itemInputs) {
+ for(int i = 0; i < iIngredientWithAmount.getAmount(); i++) {
+ ingredients.add(iIngredientWithAmount.getIngredient()
+ .asVanillaIngredient());
+ }
+ }
+ builder.withItemIngredients(ingredients.toArray(new Ingredient[0]));
+ if(fluidInputs != null) {
+ builder.withFluidIngredients(Arrays.stream(fluidInputs)
+ .map(CTDestroy::mapFluidIngredients)
+ .toArray(FluidIngredient[]::new));
+ }
+ builder.requiresHeat(heat);
+
+ builder.duration(duration);
+ CraftTweakerAPI.apply(new ActionAddRecipe<>(this, builder.build()));
+ }
+ @Override
+ public DestroyRecipeTypes getDestroyRecipeType() {
+ return DestroyRecipeTypes.ELECTROLYSIS;
+ }
+}
From 4890d76acd6317ef9e8f2e4b8e4557ec4bb6d88c Mon Sep 17 00:00:00 2001
From: SashaSemenishchev
Date: Fri, 23 Feb 2024 16:00:31 +0100
Subject: [PATCH 14/20] Proper registry handling of the molecule to make
removing/adding logic more reasonable
---
.../destroy/chemistry/Molecule.java | 20 ++++++++++
.../destroy/chemistry/Reaction.java | 20 +++++++++-
.../compat/crafttweaker/CTDestroy.java | 1 -
.../crafttweaker/CTMoleculeManager.java | 37 +++++++++++++++++--
.../action/AddMoleculeAction.java | 2 +-
.../action/RemoveMoleculeAction.java | 4 +-
.../recipes/manager/AgingRecipeHandler.java | 16 +++++++-
.../manager/CentrifugationRecipeManager.java | 16 ++++++++
.../manager/ChargingRecipeManager.java | 10 +++++
.../manager/DistillationRecipeManager.java | 15 ++++++--
.../manager/ElectrolysisRecipeManager.java | 10 ++---
.../manager/IDestroyRecipeManager.java | 13 ++++++-
12 files changed, 144 insertions(+), 20 deletions(-)
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java b/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
index 0cc4125da..8b4201f2b 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Molecule.java
@@ -542,6 +542,26 @@ public MoleculeRenderer getRenderer() {
return renderer;
};
+ public static void addMolecule(Molecule molecule) {
+ MOLECULES.put(molecule.getFullID(), molecule);
+ for(Reaction reaction : molecule.reactantReactions) {
+ Reaction.addReaction(reaction);
+ }
+ for(Reaction reaction : molecule.productReactions) {
+ Reaction.addReaction(reaction);
+ }
+ }
+
+ public static void removeMolecule(Molecule molecule) {
+ MOLECULES.remove(molecule.getFullID());
+ for(Reaction reaction : molecule.reactantReactions) {
+ Reaction.removeReaction(reaction);
+ }
+ for(Reaction reaction : molecule.productReactions) {
+ Reaction.removeReaction(reaction);
+ }
+ }
+
/**
* A class for constructing {@link Molecule Molecules}. This is typically used for:
* - Declaring known Molecules ({@link DestroyMolecules example})
diff --git a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
index 152cea652..b1947881f 100644
--- a/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
+++ b/src/main/java/com/petrolpark/destroy/chemistry/Reaction.java
@@ -737,7 +737,7 @@ public static void registerReaction(Reaction reaction) {
Destroy.LOGGER.warn("Tried to register a null reaction");
return;
}
- Reaction.REACTIONS.put(reaction.getFullID(), reaction);
+ addReaction(reaction);
for(Molecule product : reaction.getProducts()) {
product.addProductReaction(reaction);
}
@@ -752,7 +752,7 @@ public static void unregisterReaction(Reaction reaction) {
Destroy.LOGGER.warn("Tried to unregister a null reaction");
return;
}
- Reaction.REACTIONS.remove(reaction.getFullID());
+ removeReaction(reaction);
for(Molecule product : reaction.products.keySet()) {
product.removeProductReaction(reaction);
}
@@ -762,6 +762,22 @@ public static void unregisterReaction(Reaction reaction) {
}
}
+ /**
+ * Makes reaction visible to the rest of the code. Does nothing else
+ * @param reaction Reaction to make visible
+ */
+ public static void addReaction(Reaction reaction) {
+ REACTIONS.put(reaction.getFullID(), reaction);
+ }
+
+ /**
+ * Makes reaction not possible to do in a vat. Does nothing else
+ * @param reaction Reaction to make invisible
+ */
+ public static void removeReaction(Reaction reaction) {
+ REACTIONS.remove(reaction.getFullID());
+ }
+
@Override
public int hashCode() {
return getFullID().hashCode();
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
index 0f970d7f7..89e0c54ac 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTDestroy.java
@@ -51,7 +51,6 @@ private static FluidIngredient fromFluidStack(IFluidStack stack) {
return FluidIngredient.fromFluidStack(stack.getInternal());
}
-
public static Percentaged mapProcessingResult(ProcessingOutput result) {
return IItemStack.of(result.getStack()).percent(result.getChance() * 100);
}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java
index 83d798531..78253746f 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/CTMoleculeManager.java
@@ -7,26 +7,57 @@
import com.petrolpark.destroy.chemistry.Element;
import com.petrolpark.destroy.chemistry.Molecule;
import com.petrolpark.destroy.chemistry.MoleculeTag;
-import com.petrolpark.destroy.chemistry.index.DestroyMolecules;
-import com.petrolpark.destroy.compat.crafttweaker.action.AddMoleculeAction;
import com.petrolpark.destroy.compat.crafttweaker.action.RemoveMoleculeAction;
import org.openzen.zencode.java.ZenCodeType;
+/**
+ * Use Molecules to manage molecules of the mod. Use bracket handler to query
+ * a molecule. Example:
+ *
+ * When creating a molecule, you may want to specify how does the molecule impact the environment, use
+ * bracket handler. Example: (specifies that the molecule is toxic)
+ *
+ * Use {@link CTMoleculeManager#create(String)} to create a {@link com.petrolpark.destroy.compat.crafttweaker.natives.CTMoleculeBuilder}
+ * if you want to create your own molecule
+ *
+ * Use {@link CTMoleculeManager#removeMolecule(Molecule)} to remove a molecule (all reactions involving this molecule will also be removed)
+ */
@ZenRegister
@ZenCodeType.Name("mods.destroy.Molecules")
@Document("mods/destroy/Molecules")
public class CTMoleculeManager {
+
+ /**
+ * Creates a molecule builder. Call .build() to build the molecule
+ * @param id ID of the new molecule
+ * @return The {@link com.petrolpark.destroy.compat.crafttweaker.natives.CTMoleculeBuilder}
+ *
+ * @docParam "tellurium_copper"
+ */
@ZenCodeType.Method
public static Molecule.MoleculeBuilder create(String id) {
return new Molecule.MoleculeBuilder("crafttweaker")
.id(id);
}
+ /**
+ * Gets a molecule by full ID
+ * @param moleculeId Molecule ID to search
+ * @return A {@link com.petrolpark.destroy.compat.crafttweaker.natives.CTMolecule} which was found by ID or null if molecule doesn't exist
+ *
+ * @docParam moleculeId "destroy:water"
+ */
@ZenCodeType.Method
public static Molecule getMoleculeById(String moleculeId) {
- return Molecule.MOLECULES.get(moleculeId);
+ return Molecule.getMolecule(moleculeId);
}
+ /**
+ * Removes this molecule from registry. This makes all reactions involving this molecule to unregister as well.
+ * @param molecule {@link com.petrolpark.destroy.compat.crafttweaker.natives.CTMolecule} to remove
+ *
+ * @docParam molecule
+ */
@ZenCodeType.Method
public static void removeMolecule(Molecule molecule) {
CraftTweakerAPI.apply(new RemoveMoleculeAction(molecule));
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddMoleculeAction.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddMoleculeAction.java
index 9ea8ca110..87892a00f 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddMoleculeAction.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/AddMoleculeAction.java
@@ -11,7 +11,7 @@ public AddMoleculeAction(Molecule molecule) {
}
@Override
public void undo() {
- Molecule.MOLECULES.remove(molecule.getFullID());
+ Molecule.removeMolecule(molecule);
}
@Override
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveMoleculeAction.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveMoleculeAction.java
index 334347b30..8d9e1c8ec 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveMoleculeAction.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/action/RemoveMoleculeAction.java
@@ -11,7 +11,7 @@ public RemoveMoleculeAction(Molecule molecule) {
}
@Override
public void undo() {
- Molecule.MOLECULES.put(molecule.getFullID(), molecule);
+ Molecule.addMolecule(molecule);
}
@Override
@@ -26,6 +26,6 @@ public String describeUndo() {
@Override
public void apply() {
- Molecule.MOLECULES.remove(molecule.getFullID());
+ Molecule.removeMolecule(molecule);
}
}
diff --git a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/AgingRecipeHandler.java b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/AgingRecipeHandler.java
index b503609e7..b468b60a5 100644
--- a/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/AgingRecipeHandler.java
+++ b/src/main/java/com/petrolpark/destroy/compat/crafttweaker/recipes/manager/AgingRecipeHandler.java
@@ -20,8 +20,22 @@
@ZenCodeType.Name("mods.destroy.AgingManager")
public class AgingRecipeHandler implements IDestroyRecipeManager