Skip to content

Commit

Permalink
Change make using base renderer easier
Browse files Browse the repository at this point in the history
  • Loading branch information
zbx1425 committed Sep 29, 2023
1 parent 0598d92 commit 64864b1
Show file tree
Hide file tree
Showing 5 changed files with 113 additions and 116 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import mtr.mappings.Text;
import mtr.mappings.Utilities;
import mtr.mappings.UtilitiesClient;
import mtr.render.TrainRendererBase;
import mtr.sound.JonTrainSound;
import mtr.sound.TrainSoundBase;
import mtr.sound.bve.BveTrainSound;
Expand All @@ -39,72 +40,44 @@ public static void init(ResourceManager resourceManager) {
jsonConfig.get(CUSTOM_TRAINS_KEY).getAsJsonObject().entrySet().forEach(entry -> {
try {
final JsonObject jsonObject = entry.getValue().getAsJsonObject();

if (!jsonObject.has("script_files")) return;

final String name = getOrDefault(jsonObject, CUSTOM_TRAINS_NAME, entry.getKey(), JsonElement::getAsString);
final int color = getOrDefault(jsonObject, CUSTOM_TRAINS_COLOR, 0, jsonElement -> CustomResources.colorStringToInt(jsonElement.getAsString()));
if (!(jsonObject.has("script_files") || jsonObject.has("script_texts"))) return;
final String trainId = CUSTOM_TRAIN_ID_PREFIX + entry.getKey();

final String description = getOrDefault(jsonObject, CUSTOM_TRAINS_DESCRIPTION, "", JsonElement::getAsString);
final String wikipediaArticle = getOrDefault(jsonObject, CUSTOM_TRAINS_WIKIPEDIA_ARTICLE, "", JsonElement::getAsString);
final float riderOffset = getOrDefault(jsonObject, CUSTOM_TRAINS_RIDER_OFFSET, 0f, JsonElement::getAsFloat);

final String bveSoundBaseId = getOrDefault(jsonObject, CUSTOM_TRAINS_BVE_SOUND_BASE_ID, "", JsonElement::getAsString);
final int speedSoundCount = getOrDefault(jsonObject, CUSTOM_TRAINS_SPEED_SOUND_COUNT, 0, JsonElement::getAsInt);
final String speedSoundBaseId = getOrDefault(jsonObject, CUSTOM_TRAINS_SPEED_SOUND_BASE_ID, "", JsonElement::getAsString);
final String doorSoundBaseId = getOrDefault(jsonObject, CUSTOM_TRAINS_DOOR_SOUND_BASE_ID, null, JsonElement::getAsString);
final float doorCloseSoundTime = getOrDefault(jsonObject, CUSTOM_TRAINS_DOOR_CLOSE_SOUND_TIME, 0.5f, JsonElement::getAsFloat);
final boolean accelSoundAtCoast = getOrDefault(jsonObject, CUSTOM_TRAINS_ACCEL_SOUND_AT_COAST, false, JsonElement::getAsBoolean);
final boolean constPlaybackSpeed = getOrDefault(jsonObject, CUSTOM_TRAINS_CONST_PLAYBACK_SPEED, false, JsonElement::getAsBoolean);

final boolean useBveSound;
if (StringUtils.isEmpty(bveSoundBaseId)) {
useBveSound = false;
} else {
if (jsonObject.has(CUSTOM_TRAINS_BVE_SOUND_BASE_ID)) {
useBveSound = true;
} else if (jsonObject.has(CUSTOM_TRAINS_SPEED_SOUND_BASE_ID)) {
useBveSound = false;
} else {
useBveSound = false;
}
}
TrainProperties prevTrainProp = TrainClientRegistry.getTrainProperties(trainId);
if (prevTrainProp.baseTrainType.isEmpty()) return;

final boolean hasGangwayConnection = getOrDefault(jsonObject, "has_gangway_connection", false, JsonElement::getAsBoolean);
final boolean isJacobsBogie = getOrDefault(jsonObject, "is_jacobs_bogie", false, JsonElement::getAsBoolean);
final float bogiePosition = getOrDefault(jsonObject, "bogie_position", 0f, JsonElement::getAsFloat);

if (jsonObject.has("script_files")) {
final String newBaseTrainType = jsonObject.get("base_type").getAsString().toLowerCase(Locale.ROOT);
TrainSoundBase trainSound = useBveSound
? new BveTrainSound(new BveTrainSoundConfig(resourceManager, bveSoundBaseId))
: new JonTrainSound(speedSoundBaseId, new JonTrainSound.JonTrainSoundConfig(doorSoundBaseId, speedSoundCount, doorCloseSoundTime, accelSoundAtCoast, constPlaybackSpeed));

ScriptHolder scriptContext = new ScriptHolder();
Map<ResourceLocation, String> scripts = new Object2ObjectArrayMap<>();
if (jsonObject.has("script_texts")) {
JsonArray scriptTexts = jsonObject.get("script_texts").getAsJsonArray();
for (int i = 0; i < scriptTexts.size(); i++) {
scripts.put(new ResourceLocation("mtrsteamloco", "script_texts/" + trainId + "/" + i),
scriptTexts.get(i).getAsString());
}
ScriptHolder scriptContext = new ScriptHolder();
Map<ResourceLocation, String> scripts = new Object2ObjectArrayMap<>();
if (jsonObject.has("script_texts")) {
JsonArray scriptTexts = jsonObject.get("script_texts").getAsJsonArray();
for (int i = 0; i < scriptTexts.size(); i++) {
scripts.put(new ResourceLocation("mtrsteamloco", "script_texts/" + trainId + "/" + i),
scriptTexts.get(i).getAsString());
}
}
if (jsonObject.has("script_files")) {
JsonArray scriptFiles = jsonObject.get("script_files").getAsJsonArray();
for (int i = 0; i < scriptFiles.size(); i++) {
ResourceLocation scriptLocation = new ResourceLocation(scriptFiles.get(i).getAsString());
scripts.put(scriptLocation, ResourceUtil.readResource(resourceManager, scriptLocation));
}
scriptContext.load(scripts);

mtr.client.TrainClientRegistry.register(trainId, new TrainProperties(
newBaseTrainType, Text.literal(name),
description, wikipediaArticle, color,
riderOffset, riderOffset, bogiePosition, isJacobsBogie, hasGangwayConnection,
new ScriptedTrainRenderer(scriptContext),
trainSound
));
}
scriptContext.load(scripts);

boolean dummyBaseTrain = jsonObject.has("base_type");
String baseTrainType = dummyBaseTrain ? jsonObject.get("base_type").getAsString() : prevTrainProp.baseTrainType;
TrainRendererBase newRenderer = new ScriptedTrainRenderer(scriptContext, dummyBaseTrain ? null : prevTrainProp.renderer);

mtr.client.TrainClientRegistry.register(trainId, new TrainProperties(
baseTrainType, prevTrainProp.name,
prevTrainProp.description, prevTrainProp.wikipediaArticle, prevTrainProp.color,
prevTrainProp.riderOffset, prevTrainProp.riderOffsetDismounting,
bogiePosition, isJacobsBogie, prevTrainProp.hasGangwayConnection,
newRenderer, prevTrainProp.sound
));
} catch (Exception ex) {
Main.LOGGER.error("Reading scripted custom train", ex);
MtrModelRegistryUtil.recordLoadingError("Failed loading Scripted Custom Train", ex);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import mtr.client.ClientData;
import mtr.client.ICustomResources;
import mtr.client.TrainClientRegistry;
import mtr.client.TrainProperties;
import mtr.mappings.Utilities;
import mtr.mappings.UtilitiesClient;
import mtr.render.TrainRendererBase;
Expand Down Expand Up @@ -67,38 +68,46 @@ private static void reloadTail(ResourceManager manager, CallbackInfo ci) {

@Inject(at = @At("HEAD"), method = "readResource", cancellable = true)
private static void readResource(ResourceManager manager, String path, Consumer<JsonObject> callback, CallbackInfo ci) {
JsonObject dummyBbData = MtrModelRegistryUtil.createDummyBbDataPack(path, capturedTextureId, capturedFlipV, captureBbModelPreload);
if (path.toLowerCase(Locale.ROOT).endsWith(".obj") || path.contains("|")) {
JsonObject dummyBbData = MtrModelRegistryUtil.createDummyBbDataPack(path, capturedTextureId, capturedFlipV, captureBbModelPreload);
callback.accept(dummyBbData);
} else {
try {
UtilitiesClient.getResources(manager, new ResourceLocation(path)).forEach(resource -> {
try (final InputStream stream = Utilities.getInputStream(resource)) {
JsonObject modelObject = new JsonParser().parse(new InputStreamReader(stream, StandardCharsets.UTF_8)).getAsJsonObject();
if (path.toLowerCase(Locale.ROOT).endsWith(".bbmodel")) {
modelObject.add("dummyBbData", dummyBbData);
}
callback.accept(modelObject);
} catch (Exception e) { Main.LOGGER.error("On behalf of MTR: Parsing JSON " + path, e); }
try {
Utilities.closeResource(resource);
} catch (IOException e) { Main.LOGGER.error("On behalf of MTR: Closing resource " + path, e); }
});
} catch (Exception ignored) { }
return;
}

ResourceLocation location = new ResourceLocation(path);
try {
UtilitiesClient.getResources(manager, location).forEach(resource -> {
try (final InputStream stream = Utilities.getInputStream(resource)) {
JsonObject modelObject = new JsonParser().parse(new InputStreamReader(stream, StandardCharsets.UTF_8)).getAsJsonObject();
if (path.toLowerCase(Locale.ROOT).endsWith(".bbmodel")) {
JsonObject dummyBbData = MtrModelRegistryUtil.createDummyBbDataPack(path, capturedTextureId, capturedFlipV, captureBbModelPreload);
modelObject.add("dummyBbData", dummyBbData);
}
callback.accept(modelObject);
} catch (Exception e) { Main.LOGGER.error("On behalf of MTR: Parsing JSON " + path, e); }
try {
Utilities.closeResource(resource);
} catch (IOException e) { Main.LOGGER.error("On behalf of MTR: Closing resource " + path, e); }
});
} catch (Exception ignored) { }
ci.cancel();
}

@Unique private static String capturedTextureId = "";
@Unique private static boolean capturedFlipV = false;
@Unique private static boolean captureBbModelPreload = false;

@Inject(at = @At("RETURN"), method = "getOrDefault", remap = false)
@SuppressWarnings("unchecked")
@Inject(at = @At("RETURN"), method = "getOrDefault", remap = false, cancellable = true)
private static <T> void getOrDefault(JsonObject jsonObject, String key, T defaultValue, Function<JsonElement, T> function, CallbackInfoReturnable<T> cir) {
if (key.equals(ICustomResources.CUSTOM_TRAINS_TEXTURE_ID)) {
capturedTextureId = jsonObject.has(key) ? jsonObject.get(key).getAsString() : defaultValue.toString();
capturedFlipV = jsonObject.has("flipV") && jsonObject.get("flipV").getAsBoolean();
captureBbModelPreload = jsonObject.has("preloadBbModel") && jsonObject.get("preloadBbModel").getAsBoolean();
} else if (key.equals(ICustomResources.CUSTOM_TRAINS_BASE_TRAIN_TYPE)) {
if (jsonObject.has("base_type")) {
cir.setReturnValue((T)"minecart");
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,21 @@
public class ScriptedTrainRenderer extends TrainRendererBase {

private final ScriptHolder typeScripting;
private final TrainRendererBase baseRenderer;

private final TrainClient train;
private final TrainScriptContext trainScripting;

public ScriptedTrainRenderer(ScriptHolder typeScripting) {
public ScriptedTrainRenderer(ScriptHolder typeScripting, TrainRendererBase baseRenderer) {
this.typeScripting = typeScripting;
this.baseRenderer = baseRenderer;
this.train = null;
this.trainScripting = null;
}

private ScriptedTrainRenderer(ScriptedTrainRenderer base, TrainClient trainClient) {
this.typeScripting = base.typeScripting;
this.baseRenderer = base.baseRenderer == null ? null : base.baseRenderer.createTrainInstance(trainClient);
this.train = trainClient;
this.trainScripting = new TrainScriptContext(trainClient);
}
Expand Down Expand Up @@ -73,8 +77,8 @@ public void renderCar(int carIndex, double x, double y, double z, float yaw, flo
assert train != null && trainScripting != null;
boolean shouldRender = !RenderUtil.shouldSkipRenderTrain(train);

if (shouldRender && trainScripting.baseRenderer != null) {
trainScripting.baseRenderer.renderCar(carIndex, x, y, z, yaw, pitch, doorLeftOpen, doorRightOpen);
if (shouldRender && baseRenderer != null) {
baseRenderer.renderCar(carIndex, x, y, z, yaw, pitch, doorLeftOpen, doorRightOpen);
}

if (isTranslucentBatch) return;
Expand Down Expand Up @@ -122,8 +126,8 @@ public void renderConnection(Vec3 prevPos1, Vec3 prevPos2, Vec3 prevPos3, Vec3 p
assert train != null && trainScripting != null;
if (RenderUtil.shouldSkipRenderTrain(train)) return;

if (trainScripting.baseRenderer != null) {
trainScripting.baseRenderer.renderConnection(prevPos1, prevPos2, prevPos3, prevPos4, thisPos1, thisPos2, thisPos3, thisPos4, x, y, z, yaw, pitch);
if (baseRenderer != null) {
baseRenderer.renderConnection(prevPos1, prevPos2, prevPos3, prevPos4, thisPos1, thisPos2, thisPos3, thisPos4, x, y, z, yaw, pitch);
}

if (isTranslucentBatch) return;
Expand Down Expand Up @@ -152,8 +156,8 @@ public void renderBarrier(Vec3 prevPos1, Vec3 prevPos2, Vec3 prevPos3, Vec3 prev
assert train != null && trainScripting != null;
if (RenderUtil.shouldSkipRenderTrain(train)) return;

if (trainScripting.baseRenderer != null) {
trainScripting.baseRenderer.renderConnection(prevPos1, prevPos2, prevPos3, prevPos4, thisPos1, thisPos2, thisPos3, thisPos4, x, y, z, yaw, pitch);
if (baseRenderer != null) {
baseRenderer.renderConnection(prevPos1, prevPos2, prevPos3, prevPos4, thisPos1, thisPos2, thisPos3, thisPos4, x, y, z, yaw, pitch);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ public class TrainScriptContext extends AbstractScriptContext {
public TrainDrawCalls scriptResult;
private TrainDrawCalls scriptResultWriting;

public TrainRendererBase baseRenderer = null;

public TrainScriptContext(TrainClient train) {
this.scriptResult = new TrainDrawCalls(train.trainCars);
this.scriptResultWriting = new TrainDrawCalls(train.trainCars);
Expand Down Expand Up @@ -105,12 +103,4 @@ public void playAnnSound(ResourceLocation sound, float volume, float pitch) {
}
});
}

public void useBaseRenderer(String trainId) {
if (trainId == null || trainId.isEmpty()) {
baseRenderer = null;
return;
}
baseRenderer = TrainClientRegistry.getTrainProperties(trainId).renderer.createTrainInstance(train);
}
}
Loading

0 comments on commit 64864b1

Please sign in to comment.