Skip to content

Commit

Permalink
Port code
Browse files Browse the repository at this point in the history
  • Loading branch information
dhyces committed Jun 13, 2024
1 parent 19d6976 commit 80c04ab
Show file tree
Hide file tree
Showing 19 changed files with 67 additions and 34 deletions.
2 changes: 1 addition & 1 deletion common/src/main/java/dev/dhyces/trimmed/Trimmed.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
public class Trimmed {
public static final String MODID = "trimmed";
public static ResourceLocation id(String id) {
return new ResourceLocation(MODID, id);
return ResourceLocation.fromNamespaceAndPath(MODID, id);
}

public static final Logger LOGGER = LoggerFactory.getLogger("Trimmed");
Expand Down
14 changes: 10 additions & 4 deletions common/src/main/java/dev/dhyces/trimmed/TrimmedClient.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package dev.dhyces.trimmed;

import com.mojang.serialization.MapCodec;
import dev.dhyces.trimmed.api.client.TrimmedClientApiEntrypoint;
import dev.dhyces.trimmed.api.client.ClientKeyResolvers;
import dev.dhyces.trimmed.api.client.map.ClientMapKeys;
import dev.dhyces.trimmed.api.client.map.ClientMapTypes;
import dev.dhyces.trimmed.impl.ModApiConsumer;
import dev.dhyces.trimmed.impl.client.GameRegistryHolder;
import dev.dhyces.trimmed.impl.client.TrimmedClientRegistrationImpl;
import dev.dhyces.trimmed.impl.client.atlas.OpenPalettedPermutations;
import dev.dhyces.trimmed.impl.client.atlas.TrimmedSpriteSourceTypes;
import dev.dhyces.trimmed.impl.client.maps.KeyResolvers;
import dev.dhyces.trimmed.impl.client.models.override.ItemOverrideReloadListener;
Expand All @@ -20,15 +22,19 @@
import dev.dhyces.trimmed.impl.client.maps.manager.ClientMapManager;
import dev.dhyces.trimmed.modhelper.services.Services;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.atlas.SpriteSource;
import net.minecraft.client.renderer.texture.atlas.SpriteSourceType;
import net.minecraft.core.RegistryAccess;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.resources.ResourceManager;

import java.util.Collection;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;

public class TrimmedClient {
private static GameRegistryHolder staticAccess;
Expand All @@ -38,9 +44,6 @@ public static GameRegistryHolder getStaticHolder() {
}
return staticAccess;
}
public static boolean isSyncedAccess() {
return getStaticHolder().isSynced();
}

public static void init() {
KeyResolvers.register(Trimmed.id("texture"), ClientKeyResolvers.TEXTURE);
Expand All @@ -49,7 +52,6 @@ public static void init() {
ClientMapManager.registerBaseKey(ClientMapKeys.TRIM_MATERIAL_OVERRIDES);
ClientMapManager.registerBaseKey(ClientMapKeys.TRIM_OVERLAYS);
ModelSourceRegistry.init();
TrimmedSpriteSourceTypes.bootstrap();
ItemOverrideProviderRegistry.init();
}

Expand All @@ -60,6 +62,10 @@ public static void initApi() {
}
}

public static void registerSpriteSourceTypes(BiFunction<ResourceLocation, MapCodec<? extends SpriteSource>, SpriteSourceType> registrar) {
TrimmedSpriteSourceTypes.bootstrap(registrar);
}

public static void registerClientReloadListener(BiConsumer<String, PreparableReloadListener> eventConsumer) {
eventConsumer.accept("item_model_overrides", new ItemOverrideReloadListener());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public Optional<ModelResourceLocation> getModelLocation(ItemStack itemStack, @Nu
.map(ArmorTrim::material)
.flatMap(holder -> holder.unwrapKey().map(key -> key.location().withPath(holder.value().overrideArmorMaterials().getOrDefault(armorItem.getMaterial(), holder.value().assetName()))));
if (materialIdOptional.isPresent()) {
ResourceLocation id = new ResourceLocation(modelIdTemplate.process(s -> {
ResourceLocation id = ResourceLocation.parse(modelIdTemplate.process(s -> {
if (s.equals("material_suffix")) {
return materialIdOptional.get().getPath();
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,8 @@ public BaseTrimDatagenSuite makePattern(ResourceKey<TrimPattern> patternKey, Ite
config.altTranslations.forEach(altTranslation -> altTranslation.finish(translationKey));

if (config.mainTexture == null) {
patternTextures.add(new ResourceLocation(patternKey.location().getNamespace(), "trims/models/armor/" + patternKey.location().getPath()));
patternTextures.add(new ResourceLocation(patternKey.location().getNamespace(), "trims/models/armor/" + patternKey.location().getPath() + "_leggings"));
patternTextures.add(ResourceLocation.fromNamespaceAndPath(patternKey.location().getNamespace(), "trims/models/armor/" + patternKey.location().getPath()));
patternTextures.add(ResourceLocation.fromNamespaceAndPath(patternKey.location().getNamespace(), "trims/models/armor/" + patternKey.location().getPath() + "_leggings"));
} else {
patternTextures.add(config.mainTexture);
patternTextures.add(config.leggingsTexture);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public static <K, V> MapKey<K, V> of(MapType<K, V> mapType, ResourceLocation id)
baseKey = Trimmed.id(id.getPath().substring(0, firstSlashIndex));
subKey = id.withPath(s -> s.substring(firstSlashIndex+1));
} else {
baseKey = new ResourceLocation(id.getPath().substring(0, firstSlashIndex), id.getPath().substring(firstSlashIndex+1, secondSlashIndex));
baseKey = ResourceLocation.fromNamespaceAndPath(id.getPath().substring(0, firstSlashIndex), id.getPath().substring(firstSlashIndex+1, secondSlashIndex));
subKey = id.withPath(s -> s.substring(secondSlashIndex+1));
}
return fromBase(MapKey.baseKeyOf(mapType, baseKey), subKey);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ public final class CodecUtil {
if (s.contains("#")) {
String[] identifierModelSplit = s.split("#");
try {
ResourceLocation id = new ResourceLocation(identifierModelSplit[0]);
ResourceLocation id = ResourceLocation.parse(identifierModelSplit[0]);
return DataResult.success(new ModelResourceLocation(id, identifierModelSplit[1]));
} catch (Exception e) {
return DataResult.error(e::getMessage);
}
}
return DataResult.success(new ModelResourceLocation(new ResourceLocation(s), "inventory"));
return DataResult.success(new ModelResourceLocation(ResourceLocation.parse(s), "inventory"));
},
modelId -> modelId.getVariant().equals("inventory") ? modelId.getNamespace() + ":" + modelId.getPath() : modelId.toString()
modelId -> modelId.getVariant().equals("inventory") ? modelId.id().getNamespace() + ":" + modelId.id().getPath() : modelId.toString()
);

public static <K, V> LenientUnboundedMapCodec<K, V> lenientMapCodec(Codec<K> keyCodec, Codec<V> valueCodec, BiPredicate<DataResult<K>, V> skipFunction) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import java.util.List;

public class InfoToast implements Toast {
public static final ResourceLocation TEXTURE = new ResourceLocation("toast/advancement");
public static final ResourceLocation TEXTURE = ResourceLocation.withDefaultNamespace("toast/advancement");
private static final int MIDDLE_OF_TOAST = 24;
private final Component title;
private final List<FormattedCharSequence> messageLines;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public void run(ResourceManager pResourceManager, Output pOutput) {

@Override
public SpriteSourceType type() {
return TrimmedSpriteSourceTypes.OPEN_PALETTED_PERMUTATIONS;
return TrimmedSpriteSourceTypes.OPEN_PALETTED_PERMUTATIONS.get();
}

public record OptionalSupplier(boolean isRequired, Supplier<IntUnaryOperator> mapper) {}
Expand All @@ -95,7 +95,7 @@ public SpriteContents apply(SpriteResourceLoader spriteResourceLoader) {
return new SpriteContents(permutedId, new FrameSize(image.getWidth(), image.getHeight()), image, ResourceMetadata.EMPTY);
} catch (IOException e) {
if (optionalSupplier.isRequired) {
Trimmed.LOGGER.error("Could not create paletted image for " + permutedId);
Trimmed.LOGGER.error("Could not create paletted image for {}", permutedId);
}
} finally {
lazyLoadedImage.release();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
package dev.dhyces.trimmed.impl.client.atlas;

import com.mojang.serialization.MapCodec;
import dev.dhyces.trimmed.Trimmed;
import dev.dhyces.trimmed.impl.mixin.client.AtlasSourceManagerAccessor;
import net.minecraft.client.renderer.texture.atlas.SpriteSource;
import net.minecraft.client.renderer.texture.atlas.SpriteSourceType;
import net.minecraft.resources.ResourceLocation;

import java.util.function.BiFunction;
import java.util.function.Supplier;

public class TrimmedSpriteSourceTypes {
public static final SpriteSourceType OPEN_PALETTED_PERMUTATIONS = AtlasSourceManagerAccessor.invokeRegister("trimmed:open_paletted_permutations", OpenPalettedPermutations.CODEC);
private static SpriteSourceType openPalettedPermutationsRegistered;
public static final Supplier<SpriteSourceType> OPEN_PALETTED_PERMUTATIONS = () -> openPalettedPermutationsRegistered;

public static void bootstrap() {}
public static void bootstrap(BiFunction<ResourceLocation, MapCodec<? extends SpriteSource>, SpriteSourceType> registrar) {
openPalettedPermutationsRegistered = registrar.apply(Trimmed.id("open_paletted_permutations"), OpenPalettedPermutations.CODEC);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.entity.BannerPattern;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.entity.DecoratedPotPattern;
import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.chunk.status.ChunkStatus;
import net.minecraft.world.level.dimension.DimensionType;
Expand Down Expand Up @@ -123,7 +124,7 @@ public final class KeyResolvers {
public static final KeyResolver.Static<ResourceLocation> CUSTOM_STAT = registerStaticRegistry(BuiltInRegistries.CUSTOM_STAT);
public static final KeyResolver.Dynamic<DamageType> DAMAGE_TYPE = registerDynamicRegistry(Registries.DAMAGE_TYPE);
public static final KeyResolver.Static<MapCodec<? extends DensityFunction>> DENSITY_FUNCTION_TYPE = registerStaticRegistry(BuiltInRegistries.DENSITY_FUNCTION_TYPE);
public static final KeyResolver.Static<Enchantment> ENCHANTMENT = registerStaticRegistry(BuiltInRegistries.ENCHANTMENT);
public static final KeyResolver.Dynamic<Enchantment> ENCHANTMENT = registerDynamicRegistry(Registries.ENCHANTMENT);
public static final KeyResolver.Static<EntityType<?>> ENTITY_TYPE = registerStaticRegistry(BuiltInRegistries.ENTITY_TYPE);
public static final KeyResolver.Static<Feature<?>> FEATURE = registerStaticRegistry(BuiltInRegistries.FEATURE);
public static final KeyResolver.Static<FeatureSizeType<?>> FEATURE_SIZE_TYPE = registerStaticRegistry(BuiltInRegistries.FEATURE_SIZE_TYPE);
Expand All @@ -147,7 +148,7 @@ public final class KeyResolvers {
public static final KeyResolver.Static<MemoryModuleType<?>> MEMORY_MODULE_TYPE = registerStaticRegistry(BuiltInRegistries.MEMORY_MODULE_TYPE);
public static final KeyResolver.Static<MenuType<?>> MENU = registerStaticRegistry(BuiltInRegistries.MENU);
public static final KeyResolver.Static<MobEffect> MOB_EFFECT = registerStaticRegistry(BuiltInRegistries.MOB_EFFECT);
public static final KeyResolver.Static<PaintingVariant> PAINTING_VARIANT = registerStaticRegistry(BuiltInRegistries.PAINTING_VARIANT);
public static final KeyResolver.Dynamic<PaintingVariant> PAINTING_VARIANT = registerDynamicRegistry(Registries.PAINTING_VARIANT);
public static final KeyResolver.Static<ParticleType<?>> PARTICLE_TYPE = registerStaticRegistry(BuiltInRegistries.PARTICLE_TYPE);
public static final KeyResolver.Static<PlacementModifierType<?>> PLACEMENT_MODIFIER_TYPE = registerStaticRegistry(BuiltInRegistries.PLACEMENT_MODIFIER_TYPE);
public static final KeyResolver.Static<PoiType> POINT_OF_INTEREST_TYPE = registerStaticRegistry(BuiltInRegistries.POINT_OF_INTEREST_TYPE);
Expand All @@ -173,7 +174,7 @@ public final class KeyResolvers {
public static final KeyResolver.Static<TrunkPlacerType<?>> TRUNK_PLACER_TYPE = registerStaticRegistry(BuiltInRegistries.TRUNK_PLACER_TYPE);
public static final KeyResolver.Static<VillagerProfession> VILLAGER_PROFESSION = registerStaticRegistry(BuiltInRegistries.VILLAGER_PROFESSION);
public static final KeyResolver.Static<VillagerType> VILLAGER_TYPE = registerStaticRegistry(BuiltInRegistries.VILLAGER_TYPE);
public static final KeyResolver.Static<String> DECORATED_POT_PATTERNS = registerStaticRegistry(BuiltInRegistries.DECORATED_POT_PATTERNS);
public static final KeyResolver.Static<DecoratedPotPattern> DECORATED_POT_PATTERNS = registerStaticRegistry(BuiltInRegistries.DECORATED_POT_PATTERN);
public static final KeyResolver.Static<NumberFormatType<?>> NUMBER_FORMAT_TYPE = registerStaticRegistry(BuiltInRegistries.NUMBER_FORMAT_TYPE);
public static final KeyResolver.Static<ArmorMaterial> ARMOR_MATERIAL = registerStaticRegistry(BuiltInRegistries.ARMOR_MATERIAL);
public static final KeyResolver.Static<DataComponentType<?>> DATA_COMPONENT_TYPE = registerStaticRegistry(BuiltInRegistries.DATA_COMPONENT_TYPE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.model.loading.v1.PreparableModelLoadingPlugin;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.fabricmc.fabric.api.client.rendering.v1.AtlasSourceTypeRegistry;
import net.fabricmc.fabric.api.event.lifecycle.v1.CommonLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.resource.IdentifiableResourceReloadListener;
import net.fabricmc.fabric.api.resource.ResourceManagerHelper;
import net.minecraft.client.renderer.texture.atlas.SpriteSourceType;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.resources.PreparableReloadListener;
Expand All @@ -25,6 +27,11 @@ public class FabricTrimmedClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
TrimmedClient.init();
TrimmedClient.registerSpriteSourceTypes((id, codec) -> {
SpriteSourceType type = new SpriteSourceType(codec);
AtlasSourceTypeRegistry.register(id, type);
return type;
});
TrimmedClient.registerClientReloadListener((id, listener) -> {
ResourceManagerHelper.get(PackType.CLIENT_RESOURCES).registerReloadListener(new WrappedReloadListener(Trimmed.id(id), listener));
});
Expand All @@ -33,7 +40,7 @@ public void onInitializeClient() {
Map<ResourceLocation, NamedModel> modelMapByFileId = new Object2ObjectOpenHashMap<>();
for (NamedModel namedModel : data) {
// Need to add as ModelResourceLocations
pluginContext.addModels(namedModel.modelId());
pluginContext.addModels(namedModel.id());
// But the context ids are in regular ResourceLocations
modelMapByFileId.put(namedModel.id(), namedModel);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public class TrimDatagenSuite extends BaseTrimDatagenSuite {
public TrimDatagenSuite(FabricDataGenerator.Pack pack, String modid, @Nullable String mainLanguageCode) {
super(modid, (key, translation) -> {
if (mainLanguageCode != null) {
TRANSLATIONS.put(new ResourceLocation(modid, mainLanguageCode), Pair.of(key, translation));
TRANSLATIONS.put(ResourceLocation.fromNamespaceAndPath(modid, mainLanguageCode), Pair.of(key, translation));
}
});
pack.addProvider((output, registriesFuture) ->
Expand Down Expand Up @@ -127,6 +127,6 @@ public static TrimDatagenSuite create(FabricDataGenerator.Pack pack, String modi
* translations themselves.
*/
public void resolveTranslationsFor(String languageCode, FabricLanguageProvider.TranslationBuilder builder) {
TRANSLATIONS.get(new ResourceLocation(modid, languageCode)).forEach(pair -> builder.add(pair.getFirst(), pair.getSecond()));
TRANSLATIONS.get(ResourceLocation.fromNamespaceAndPath(modid, languageCode)).forEach(pair -> builder.add(pair.getFirst(), pair.getSecond()));
}
}
11 changes: 9 additions & 2 deletions neo/src/main/java/dev/dhyces/trimmed/NeoTrimmedClient.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dev.dhyces.trimmed;

import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.IEventBus;
Expand All @@ -8,6 +9,7 @@
import net.neoforged.neoforge.client.event.ClientPlayerNetworkEvent;
import net.neoforged.neoforge.client.event.ModelEvent;
import net.neoforged.neoforge.client.event.RegisterClientReloadListenersEvent;
import net.neoforged.neoforge.client.event.RegisterSpriteSourceTypesEvent;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.TagsUpdatedEvent;
import net.neoforged.neoforge.event.server.ServerStoppingEvent;
Expand All @@ -17,10 +19,11 @@
@SuppressWarnings("unused")
@Mod(value = Trimmed.MODID, dist = Dist.CLIENT)
public class NeoTrimmedClient {
private static Set<ResourceLocation> additionalGeneratedModels;
private static Set<ModelResourceLocation> additionalGeneratedModels;

public NeoTrimmedClient(IEventBus modBus, ModContainer container) {
TrimmedClient.init();
modBus.addListener(this::registerSpriteSourceTypes);
modBus.addListener(this::registerClientReloadListener);
modBus.addListener(this::addModels);

Expand All @@ -31,6 +34,10 @@ public NeoTrimmedClient(IEventBus modBus, ModContainer container) {
TrimmedClient.initApi();
}

private void registerSpriteSourceTypes(final RegisterSpriteSourceTypesEvent event) {
TrimmedClient.registerSpriteSourceTypes(event::register);
}

private void registerClientReloadListener(final RegisterClientReloadListenersEvent event) {
TrimmedClient.registerClientReloadListener((s, preparableReloadListener) -> event.registerReloadListener(preparableReloadListener));
TrimmedClient.injectListenersAtBeginning();
Expand All @@ -52,7 +59,7 @@ private void onLogout(final ClientPlayerNetworkEvent.LoggingOut event) {
TrimmedClient.resetSyncedStatus();
}

public static void setModels(Set<ResourceLocation> models) {
public static void setModels(Set<ModelResourceLocation> models) {
additionalGeneratedModels = models;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import it.unimi.dsi.fastutil.objects.*;
import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.resources.ResourceManager;
import org.spongepowered.asm.mixin.Mixin;
Expand All @@ -28,7 +29,7 @@ private static CompletableFuture<Map<ResourceLocation, BlockModel>> injectGenera
return original.thenCombineAsync(TrimmedClient.startGeneratingModels(resourceManager, executor),
(originalMap, generatedModels) -> {
Object2ObjectMap<ResourceLocation, BlockModel> newMap = new Object2ObjectOpenHashMap<>();
Set<ResourceLocation> generatedModelIds = new ObjectOpenHashSet<>();
Set<ModelResourceLocation> generatedModelIds = new ObjectOpenHashSet<>();
generatedModels.forEach(namedModel -> {
ResourceLocation path = namedModel.id().withPrefix("models/").withSuffix(".json");
if (!originalMap.containsKey(path)) {
Expand Down
Loading

0 comments on commit 80c04ab

Please sign in to comment.