| 1 | package net.minecraft.util.datafix.fixes;
|
| 2 |
|
| 3 | import com.mojang.datafixers.DSL;
|
| 4 | import com.mojang.datafixers.DataFix;
|
| 5 | import com.mojang.datafixers.OpticFinder;
|
| 6 | import com.mojang.datafixers.TypeRewriteRule;
|
| 7 | import com.mojang.datafixers.Typed;
|
| 8 | import com.mojang.datafixers.schemas.Schema;
|
| 9 | import com.mojang.datafixers.types.Type;
|
| 10 | import com.mojang.serialization.Dynamic;
|
| 11 | import com.mojang.serialization.DynamicOps;
|
| 12 | import java.util.Optional;
|
| 13 | import net.minecraft.util.Util;
|
| 14 | import net.minecraft.util.datafix.ExtraDataFixUtils;
|
| 15 | import net.minecraft.util.datafix.LegacyComponentDataFixUtils;
|
| 16 | import net.minecraft.util.datafix.schemas.NamespacedSchema;
|
| 17 |
|
| 18 | public class EntityCustomNameToComponentFix extends DataFix {
|
| 19 | public EntityCustomNameToComponentFix(final Schema outputSchema) {
|
| 20 | super(outputSchema, true);
|
| 21 | }
|
| 22 |
|
| 23 | @Override
|
| 24 | public TypeRewriteRule makeRule() {
|
| 25 | Type<?> entityType = this.getInputSchema().getType(References.ENTITY);
|
| 26 | Type<?> newEntityType = this.getOutputSchema().getType(References.ENTITY);
|
| 27 | OpticFinder<String> idF = DSL.fieldFinder("id", NamespacedSchema.namespacedString());
|
| 28 | OpticFinder<String> customNameF = (OpticFinder<String>)entityType.findField("CustomName");
|
| 29 | Type<?> newCustomNameType = newEntityType.findFieldType("CustomName");
|
| 30 | return this.fixTypeEverywhereTyped(
|
| 31 | "EntityCustomNameToComponentFix", entityType, newEntityType, entity -> fixEntity(entity, newEntityType, idF, customNameF, newCustomNameType)
|
| 32 | );
|
| 33 | }
|
| 34 |
|
| 35 | private static <T> Typed<?> fixEntity(
|
| 36 | final Typed<?> entity, final Type<?> newEntityType, final OpticFinder<String> idF, final OpticFinder<String> customNameF, final Type<T> newCustomNameType
|
| 37 | ) {
|
| 38 | Optional<String> customName = entity.getOptional(customNameF);
|
| 39 | if (customName.isEmpty()) {
|
| 40 | return ExtraDataFixUtils.cast(newEntityType, entity);
|
| 41 | }
|
| 42 |
|
| 43 | if (customName.get().isEmpty()) {
|
| 44 | return Util.writeAndReadTypedOrThrow(entity, newEntityType, dynamic -> dynamic.remove("CustomName"));
|
| 45 | }
|
| 46 |
|
| 47 | String id = entity.getOptional(idF).orElse("");
|
| 48 | Dynamic<?> component = fixCustomName(entity.getOps(), customName.get(), id);
|
| 49 | return entity.set(customNameF, Util.readTypedOrThrow(newCustomNameType, component));
|
| 50 | }
|
| 51 |
|
| 52 | private static <T> Dynamic<T> fixCustomName(final DynamicOps<T> ops, final String customName, final String id) {
|
| 53 | return "minecraft:commandblock_minecart".equals(id)
|
| 54 | ? new Dynamic<>(ops, ops.createString(customName))
|
| 55 | : LegacyComponentDataFixUtils.createPlainTextComponent(ops, customName);
|
| 56 | }
|
| 57 | }
|
| 58 |
|