Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generify Palettes Implementation #3178

Merged
merged 3 commits into from
Nov 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.block;

import static com.google.common.base.Preconditions.checkNotNull;

import net.minecraft.block.Block;
import net.minecraft.state.IProperty;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockStateMatcher;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.state.StateProperty;
import org.spongepowered.api.util.Tuple;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

public class BlockStateSerializerDeserializer {

@SuppressWarnings({"rawtypes", "unchecked"})
private static final Function<Map.Entry<IProperty<?>, Comparable<?>>, String> MAP_ENTRY_TO_STRING = p_apply_1_ -> {
if (p_apply_1_ == null) {
return "<NULL>";
} else {
final IProperty iproperty = p_apply_1_.getKey();
return iproperty.getName() + "=" + iproperty.getName(p_apply_1_.getValue());
}
};

public static String serialize(final BlockState state) {
final StringBuilder stringbuilder = new StringBuilder();
stringbuilder.append(Registry.BLOCK.getKey((Block) state.getType()).toString());
if (!((net.minecraft.block.BlockState) state).getValues().isEmpty()) {
stringbuilder.append('[');
stringbuilder.append(
((net.minecraft.block.BlockState) state).getValues()
.entrySet()
.stream()
.map(BlockStateSerializerDeserializer.MAP_ENTRY_TO_STRING)
.collect(Collectors.joining(","))
);
stringbuilder.append(']');
}

return stringbuilder.toString();
}

@SuppressWarnings({"rawtypes", "unchecked"})
public static Optional<BlockState> deserialize(final String string) {
final String state = checkNotNull(string, "Id cannot be null!").toLowerCase(Locale.ENGLISH);
if (state.contains("[")) {
final String[] split = state.split("\\[");
final ResourceLocation key = ResourceLocation.tryCreate(split[0]);
return Registry.BLOCK.getValue(key)
.flatMap(block -> {
final Collection<IProperty<?>> properties = block.getStateContainer().getProperties();
final String propertyValues = split[1].replace("[", "").replace("]", "");
if (properties.isEmpty()) {
throw new IllegalArgumentException("The properties cannot be specified and empty (omit [] if there are no properties)");
}
final String[] propertyValuePairs = propertyValues.split(",");
final List<? extends Tuple<? extends IProperty<?>, ?>> propertyValuesFound = Arrays.stream(propertyValuePairs)
.map(propertyValue -> propertyValue.split("="))
.filter(pair -> pair.length == 2)
.map(pair -> Optional.ofNullable(block.getStateContainer().getProperty(pair[0]))
.flatMap(property -> property.parseValue(pair[1]).map(value -> Tuple.of(property, value))))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
final BlockStateMatcher.Builder matcher = BlockState.matcher((BlockType) block);
propertyValuesFound.forEach(tuple -> matcher.property((StateProperty) tuple.getFirst(), (Comparable) tuple.getSecond()));

return matcher.build()
.getCompatibleStates()
.stream()
.findFirst();
});

}
final ResourceLocation block = ResourceLocation.tryCreate(string);
return (Optional<BlockState>) (Optional) Registry.BLOCK.getValue(block).map(Block::getDefaultState);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,12 @@
import org.spongepowered.api.item.inventory.type.ViewableInventory;
import org.spongepowered.api.item.merchant.TradeOffer;
import org.spongepowered.api.item.merchant.TradeOfferGenerator;
import org.spongepowered.api.item.recipe.cooking.CookingRecipe;
import org.spongepowered.api.item.recipe.crafting.Ingredient;
import org.spongepowered.api.item.recipe.crafting.ShapedCraftingRecipe;
import org.spongepowered.api.item.recipe.crafting.ShapelessCraftingRecipe;
import org.spongepowered.api.item.recipe.crafting.SpecialCraftingRecipe;
import org.spongepowered.api.item.recipe.single.StoneCutterRecipe;
import org.spongepowered.api.item.recipe.cooking.CookingRecipe;
import org.spongepowered.api.placeholder.PlaceholderComponent;
import org.spongepowered.api.placeholder.PlaceholderContext;
import org.spongepowered.api.placeholder.PlaceholderParser;
Expand All @@ -106,12 +106,13 @@
import org.spongepowered.api.world.WorldBorder;
import org.spongepowered.api.world.biome.VirtualBiomeType;
import org.spongepowered.api.world.explosion.Explosion;
import org.spongepowered.api.world.schematic.PaletteType;
import org.spongepowered.common.advancement.SpongeAdvancementBuilder;
import org.spongepowered.common.advancement.criterion.SpongeCriterionBuilder;
import org.spongepowered.common.advancement.SpongeDisplayInfoBuilder;
import org.spongepowered.common.advancement.SpongeFilteredTriggerBuilder;
import org.spongepowered.common.advancement.criterion.SpongeScoreCriterionBuilder;
import org.spongepowered.common.advancement.SpongeTriggerBuilder;
import org.spongepowered.common.advancement.criterion.SpongeCriterionBuilder;
import org.spongepowered.common.advancement.criterion.SpongeScoreCriterionBuilder;
import org.spongepowered.common.ban.SpongeBanBuilder;
import org.spongepowered.common.block.SpongeBlockSnapshotBuilder;
import org.spongepowered.common.block.SpongeBlockStateBuilder;
Expand Down Expand Up @@ -165,12 +166,12 @@
import org.spongepowered.common.item.generation.SpongeItemStackGenerator;
import org.spongepowered.common.item.merchant.SpongeTradeOfferBuilder;
import org.spongepowered.common.item.merchant.SpongeTradeOfferGenerator;
import org.spongepowered.common.item.recipe.ingredient.SpongeIngredientBuilder;
import org.spongepowered.common.item.recipe.cooking.SpongeCookingRecipeBuilder;
import org.spongepowered.common.item.recipe.crafting.custom.SpongeSpecialCraftingRecipeBuilder;
import org.spongepowered.common.item.recipe.crafting.shaped.SpongeShapedCraftingRecipeBuilder;
import org.spongepowered.common.item.recipe.crafting.shapeless.SpongeShapelessCraftingRecipeBuilder;
import org.spongepowered.common.item.recipe.crafting.custom.SpongeSpecialCraftingRecipeBuilder;
import org.spongepowered.common.item.recipe.ingredient.SpongeIngredientBuilder;
import org.spongepowered.common.item.recipe.stonecutting.SpongeStoneCutterRecipeBuilder;
import org.spongepowered.common.item.recipe.cooking.SpongeCookingRecipeBuilder;
import org.spongepowered.common.placeholder.SpongePlaceholderComponentBuilder;
import org.spongepowered.common.placeholder.SpongePlaceholderContextBuilder;
import org.spongepowered.common.placeholder.SpongePlaceholderParserBuilder;
Expand All @@ -183,6 +184,7 @@
import org.spongepowered.common.world.SpongeWorldArchetypeBuilder;
import org.spongepowered.common.world.biome.SpongeVirtualBiomeTypeBuilder;
import org.spongepowered.common.world.border.SpongeWorldBorderBuilder;
import org.spongepowered.common.world.schematic.SpongePaletteTypeBuilder;

import java.util.Map;
import java.util.function.Supplier;
Expand Down Expand Up @@ -304,6 +306,7 @@ public void registerDefaultBuilders() {
.register(MutableDataProviderBuilder.class, DataProviderRegistrator.SpongeMutableDataProviderBuilder::new)
.register(ImmutableDataProviderBuilder.class, DataProviderRegistrator.SpongeImmutableDataProviderBuilder::new)
.register(Query.Builder.class, SpongeQueryBuilder::new)
.register(PaletteType.Builder.class, SpongePaletteTypeBuilder::new)
;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@
import org.spongepowered.api.world.dimension.DimensionType;
import org.spongepowered.api.world.dimension.DimensionTypes;
import org.spongepowered.api.world.portal.PortalType;
import org.spongepowered.api.world.schematic.PaletteType;
import org.spongepowered.api.world.teleport.TeleportHelperFilter;
import org.spongepowered.api.world.weather.Weather;
import org.spongepowered.common.accessor.util.registry.SimpleRegistryAccessor;
Expand Down Expand Up @@ -200,6 +201,7 @@
import org.spongepowered.common.registry.builtin.sponge.MovementTypeStreamGenerator;
import org.spongepowered.common.registry.builtin.sponge.MusicDiscStreamGenerator;
import org.spongepowered.common.registry.builtin.sponge.NotePitchStreamGenerator;
import org.spongepowered.common.registry.builtin.sponge.PaletteTypeStreamGenerator;
import org.spongepowered.common.registry.builtin.sponge.ParrotTypeStreamGenerator;
import org.spongepowered.common.registry.builtin.sponge.ParticleOptionStreamGenerator;
import org.spongepowered.common.registry.builtin.sponge.PhaseTypeRegistrar;
Expand Down Expand Up @@ -564,6 +566,7 @@ public void registerDefaultRegistries() {
.generateRegistry(MooshroomType.class, ResourceKey.minecraft("mooshroom_type"), Arrays.stream(MooshroomEntity.Type.values()), true, false)
.generateRegistry(MovementType.class, ResourceKey.sponge("movement_type"), MovementTypeStreamGenerator.stream(), true, true)
.generateRegistry(MusicDisc.class, ResourceKey.minecraft("music_disc"), MusicDiscStreamGenerator.stream(), true, false)
.generateRegistry(PaletteType.class, ResourceKey.sponge("palette"), PaletteTypeStreamGenerator.stream(), true, true)
.generateRegistry(PandaGene.class, ResourceKey.minecraft("panda_gene"), Arrays.stream(PandaEntity.Type.values()), true, false)
.generateRegistry(ParticleOption.class, ResourceKey.sponge("particle_option"), ParticleOptionStreamGenerator.stream(), true, false)
.generateRegistry(PhantomPhase.class, ResourceKey.minecraft("phantom_phase"), Arrays.stream(PhantomEntity.AttackPhase.values()), true, false)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.registry.builtin.sponge;

import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.biome.Biome;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.world.biome.BiomeType;
import org.spongepowered.api.world.biome.VirtualBiomeType;
import org.spongepowered.api.world.schematic.PaletteType;
import org.spongepowered.api.world.schematic.PaletteTypes;
import org.spongepowered.common.block.BlockStateSerializerDeserializer;
import org.spongepowered.common.world.schematic.GlobalPalette;
import org.spongepowered.common.world.schematic.MutableBimapPalette;
import org.spongepowered.common.world.schematic.SpongePaletteType;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

public final class PaletteTypeStreamGenerator {

private PaletteTypeStreamGenerator() {
}

@SuppressWarnings({"rawtypes", "unchecked"})
public static Stream<PaletteType> stream() {
final List<PaletteType> paletteTypes = new ArrayList<>();
paletteTypes.add(new SpongePaletteType<BlockState>(
ResourceKey.sponge("global_block_palette"),
GlobalPalette::getBlockPalette,
BlockStateSerializerDeserializer::serialize,
BlockStateSerializerDeserializer::deserialize
));
paletteTypes.add(new SpongePaletteType<>(
ResourceKey.sponge("block_state_palette"),
() -> new MutableBimapPalette<>(PaletteTypes.BLOCK_STATE_PALETTE.get()),
BlockStateSerializerDeserializer::serialize,
BlockStateSerializerDeserializer::deserialize
));
paletteTypes.add(new SpongePaletteType<BiomeType>(
ResourceKey.sponge("global_biome_palette"),
GlobalPalette::getBiomePalette,
(type) -> {
final ResourceLocation key = Registry.BIOME.getKey((Biome) (
type instanceof VirtualBiomeType
? ((VirtualBiomeType) type).getPersistedType()
: type
));
if (key == null) {
return "minecraft:plains";
}
return key.toString();
},
(id) -> (Optional<BiomeType>) (Optional) Registry.BIOME.getValue(ResourceLocation.tryCreate(id))
));
paletteTypes.add(new SpongePaletteType<>(
ResourceKey.sponge("biome_palette"),
() -> new MutableBimapPalette<>(PaletteTypes.BIOME_PALETTE.get()),
(type) -> {
final ResourceLocation key = Registry.BIOME.getKey((Biome) (
type instanceof VirtualBiomeType
? ((VirtualBiomeType) type).getPersistedType()
: type
));
if (key == null) {
return "minecraft:plains";
}
return key.toString();
},
(id) -> (Optional<BiomeType>) (Optional) Registry.BIOME.getValue(ResourceLocation.tryCreate(id))
));

return paletteTypes.stream();
}


}
60 changes: 60 additions & 0 deletions src/main/java/org/spongepowered/common/util/MemoizedSupplier.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.util;


import java.util.Objects;
import java.util.function.Supplier;

public class MemoizedSupplier<T> implements Supplier<T> {

public static <V> Supplier<V> memoize(final Supplier<V> supplier) {
return new MemoizedSupplier<>(supplier);
}

final Supplier<T> delegate;
transient volatile boolean initialized;
transient T value;

private MemoizedSupplier(final Supplier<T> delegate) {
this.delegate = Objects.requireNonNull(delegate);
}

@Override
public T get() {
if (!this.initialized) {
synchronized (this) {
if (!this.initialized) {
final T t = this.delegate.get();
this.value = t;
this.initialized = true;
return t;
}
}
}
return this.value;
}

}