use of org.spongepowered.api.data.DataContainer in project LanternServer by LanternPowered.
the class FlatGeneratorSettingsParser method fromString.
@Nullable
public static FlatGeneratorSettings fromString(@Nullable String value) {
if (value == null) {
return null;
}
// Split the value into parts
final List<String> parts = Lists.newArrayList(Splitter.on(';').split(value));
// Try to extract the version from the parts
int version = 0;
if (parts.size() > 1) {
version = Coerce.toInteger(parts.remove(0));
}
// Smaller then 0 is unknown? and 3 is the latest format version
if (version < 0 || version > 3) {
return null;
}
// The layers are stored in the first part
final String layersPart = parts.remove(0);
// The parsed layers
final List<FlatLayer> layers = new ArrayList<>();
// Can be empty if there are no layers
if (!layersPart.isEmpty()) {
// The separator that can be used to create a layer
// of x amount of blocks
final char depthSeparator = version >= 3 ? '*' : 'x';
Splitter.on(',').split(layersPart).forEach(s -> {
// The block type
BlockType blockType;
// The data value (optional)
int blockData = 0;
// The depth of the layer
int depth = 1;
// The depth separated by the depth separator followed by the block state
final List<String> parts1 = Lists.newArrayList(Splitter.on(depthSeparator).limit(2).split(s));
if (parts1.size() > 1) {
final Optional<Integer> optDepth = Coerce.asInteger(parts1.remove(0));
if (optDepth.isPresent()) {
depth = GenericMath.clamp(optDepth.get(), 0, 255);
if (depth <= 0) {
// Skip to the next layer
return;
}
}
}
String blockStatePart = parts1.get(0);
final int index = blockStatePart.lastIndexOf(':');
if (index > 0) {
Optional<Integer> optData = Coerce.asInteger(blockStatePart.substring(index + 1));
if (optData.isPresent()) {
blockData = GenericMath.clamp(optData.get(), 0, 15);
blockStatePart = blockStatePart.substring(0, index);
}
}
// Try to parse the block id as internal (int) id
final Optional<Integer> optId = Coerce.asInteger(blockStatePart);
if (optId.isPresent()) {
blockType = BlockRegistryModule.get().getStateByInternalId(optId.get()).orElse(BlockTypes.STONE.getDefaultState()).getType();
// Not an integer, try the catalog system
} else {
blockType = BlockRegistryModule.get().getById(blockStatePart).orElse(BlockTypes.STONE);
}
layers.add(new FlatLayer(BlockRegistryModule.get().getStateByTypeAndData(blockType, (byte) blockData).get(), depth));
});
}
// Try to parse the biome type if present
BiomeType biomeType = BiomeTypes.PLAINS;
if (!parts.isEmpty()) {
final String biomePart = parts.remove(0);
final Optional<Integer> optBiomeId = Coerce.asInteger(biomePart);
final Optional<BiomeType> optBiome;
if (optBiomeId.isPresent()) {
optBiome = BiomeRegistryModule.get().getByInternalId(optBiomeId.get());
} else {
optBiome = BiomeRegistryModule.get().getById(biomePart);
}
if (optBiome.isPresent()) {
biomeType = optBiome.get();
}
}
// Extra data (like structures)
final DataContainer extraData = DataContainer.createNew();
if (!parts.isEmpty()) {
final String extraPart = parts.remove(0);
if (!extraPart.isEmpty()) {
Splitter.on(',').split(extraPart).forEach(s -> {
String key = s;
// Check if there is extra data attached to the key
final int valuesIndex = s.indexOf('(');
if (valuesIndex != -1) {
// Separate the key from the values
key = s.substring(0, valuesIndex);
int endIndex = s.lastIndexOf(')');
if (endIndex == -1) {
endIndex = s.length();
}
// Get the values section from the string
s = s.substring(valuesIndex + 1, endIndex);
// Create the view to store the values
final DataView dataView = extraData.createView(DataQuery.of(key));
if (!s.isEmpty()) {
Splitter.on(' ').split(s).forEach(v -> {
final List<String> parts1 = Splitter.on('=').limit(2).splitToList(v);
// Must be greater then 1, otherwise it's invalid
if (parts1.size() > 1) {
// Currently, only integer values seem to be supported
dataView.set(DataQuery.of(parts1.get(0)), Coerce.toInteger(parts1.get(1)));
}
});
}
} else {
extraData.createView(DataQuery.of(key));
}
});
}
}
return new FlatGeneratorSettings(biomeType, layers, extraData);
}
use of org.spongepowered.api.data.DataContainer in project LanternServer by LanternPowered.
the class LanternParticleEffect method toContainer.
@Override
public DataContainer toContainer() {
final DataContainer dataContainer = DataContainer.createNew();
dataContainer.set(DataQueries.PARTICLE_TYPE, this.type);
dataContainer.set(DataQueries.PARTICLE_OPTIONS, this.options.entrySet().stream().map(entry -> DataContainer.createNew().set(DataQueries.PARTICLE_OPTION_KEY, entry.getKey()).set(DataQueries.PARTICLE_OPTION_VALUE, entry.getValue())).collect(Collectors.toList()));
return dataContainer;
}
use of org.spongepowered.api.data.DataContainer in project LanternServer by LanternPowered.
the class LanternGameProfile method toContainer.
@Override
public DataContainer toContainer() {
final DataContainer container = DataContainer.createNew().set(UNIQUE_ID, this.uniqueId.toString());
if (this.name != null) {
container.set(NAME, this.name);
}
if (!this.properties.isEmpty()) {
final DataContainer propertiesMap = DataContainer.createNew();
for (String key : this.properties.keySet()) {
final List<DataContainer> entries = new ArrayList<>();
for (ProfileProperty property : this.properties.get(key)) {
final DataContainer entry = DataContainer.createNew().set(VALUE, property.getValue());
property.getSignature().ifPresent(signature -> entry.set(SIGNATURE, signature));
entries.add(entry);
}
propertiesMap.set(DataQuery.of(key), entries);
}
container.set(PROPERTIES, propertiesMap);
}
return container;
}
use of org.spongepowered.api.data.DataContainer in project LanternServer by LanternPowered.
the class ProcessorPlayOutParticleEffect method toExtraItemData.
private static int[] toExtraItemData(ItemStack itemStack) {
final ObjectStore<LanternItemStack> store = ObjectStoreRegistry.get().get(LanternItemStack.class).get();
final DataContainer view = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
store.serialize((LanternItemStack) itemStack, view);
final int data = view.getInt(ItemStackStore.DATA).get();
final int internalId = ItemRegistryModule.get().getInternalId(itemStack.getType());
return new int[] { internalId, data };
}
use of org.spongepowered.api.data.DataContainer in project LanternServer by LanternPowered.
the class LanternWorldPropertiesIO method convert.
static LanternWorldProperties convert(LevelData levelData, WorldConfig worldConfig, boolean copyLevelSettingsToConfig) {
final LanternWorldProperties properties = new LanternWorldProperties(levelData.uniqueId, levelData.worldName, worldConfig);
final DataView dataView = levelData.worldData.getView(DATA).get();
final DataView spongeRootDataView = levelData.spongeWorldData;
final DataView spongeDataView;
if (spongeRootDataView != null) {
spongeDataView = spongeRootDataView.getView(DataQueries.SPONGE_DATA).orElse(null);
spongeDataView.remove(DataQueries.SPONGE_DATA);
} else {
spongeDataView = null;
}
final DataView lanternDataView = spongeDataView == null ? null : spongeDataView.getView(LANTERN).orElse(null);
properties.setLastPlayedTime(dataView.getLong(LAST_PLAYED).get());
properties.mapFeatures = dataView.getInt(MAP_FEATURES).get() > 0;
properties.setInitialized(dataView.getInt(INITIALIZED).get() > 0);
dataView.getInt(DIFFICULTY_LOCKED).ifPresent(v -> properties.setDifficultyLocked(v > 0));
final LanternWorldBorder border = properties.getWorldBorder();
dataView.getDouble(BORDER_CENTER_X).ifPresent(v -> border.centerX = v);
dataView.getDouble(BORDER_CENTER_Z).ifPresent(v -> border.centerZ = v);
dataView.getDouble(BORDER_SIZE_START).ifPresent(v -> border.diameterStart = v);
dataView.getDouble(BORDER_SIZE_END).ifPresent(v -> border.diameterEnd = v);
dataView.getLong(BORDER_SIZE_LERP_TIME).ifPresent(v -> border.lerpTime = v);
dataView.getDouble(BORDER_DAMAGE).ifPresent(v -> border.damage = v);
dataView.getDouble(BORDER_DAMAGE_THRESHOLD).ifPresent(v -> border.damageThreshold = v);
dataView.getInt(BORDER_WARNING_BLOCKS).ifPresent(v -> border.warningDistance = v);
dataView.getInt(BORDER_WARNING_TIME).ifPresent(v -> border.warningTime = v);
if (spongeRootDataView != null) {
properties.setAdditionalProperties(spongeRootDataView.copy().remove(DataQueries.SPONGE_DATA));
}
// Get the sponge properties
if (spongeDataView != null) {
// This can be null, this is provided in the lantern-server
final String dimensionTypeId = spongeDataView.getString(DIMENSION_TYPE).get();
if (dimensionTypeId.equalsIgnoreCase(OVERWORLD)) {
properties.setDimensionType(DimensionTypes.OVERWORLD);
} else if (dimensionTypeId.equalsIgnoreCase(NETHER)) {
properties.setDimensionType(DimensionTypes.NETHER);
} else if (dimensionTypeId.equalsIgnoreCase(END)) {
properties.setDimensionType(DimensionTypes.THE_END);
} else {
final DimensionType dimensionType = Sponge.getRegistry().getType(DimensionType.class, dimensionTypeId).orElse(null);
if (dimensionType == null) {
Lantern.getLogger().warn("Could not find a dimension type with id {} for the world {}, falling back to overworld...", dimensionTypeId, levelData.worldName);
}
properties.setDimensionType(dimensionType == null ? DimensionTypes.OVERWORLD : dimensionType);
}
PortalAgentType portalAgentType = null;
if (spongeDataView.contains(PORTAL_AGENT_TYPE)) {
final String portalAgentTypeId = spongeDataView.getString(PORTAL_AGENT_TYPE).get();
portalAgentType = Sponge.getRegistry().getType(PortalAgentType.class, portalAgentTypeId).orElse(null);
if (portalAgentType == null) {
Lantern.getLogger().warn("Could not find a portal agent type with id {} for the world {}, falling back to default...", portalAgentTypeId, levelData.worldName);
}
}
properties.setPortalAgentType(portalAgentType == null ? PortalAgentTypes.DEFAULT : portalAgentType);
spongeDataView.getInt(GENERATE_BONUS_CHEST).ifPresent(v -> properties.setGenerateBonusChest(v > 0));
spongeDataView.getInt(SERIALIZATION_BEHAVIOR).ifPresent(v -> properties.setSerializationBehavior(v == 0 ? SerializationBehaviors.MANUAL : v == 1 ? SerializationBehaviors.AUTOMATIC : SerializationBehaviors.NONE));
// Tracker
final Optional<List<DataView>> optTrackerUniqueIdViews = spongeDataView.getViewList(TRACKER_UUID_TABLE);
if (optTrackerUniqueIdViews.isPresent()) {
final List<DataView> trackerUniqueIdViews = optTrackerUniqueIdViews.get();
final Object2IntMap<UUID> trackerUniqueIds = properties.getTrackerIdAllocator().getUniqueIds();
final List<UUID> uniqueIdsByIndex = properties.getTrackerIdAllocator().getUniqueIdsByIndex();
for (DataView view : trackerUniqueIdViews) {
UUID uniqueId = null;
if (!view.isEmpty()) {
final long most = view.getLong(UUID_MOST).get();
final long least = view.getLong(UUID_LEAST).get();
uniqueId = new UUID(most, least);
trackerUniqueIds.put(uniqueId, uniqueIdsByIndex.size());
}
uniqueIdsByIndex.add(uniqueId);
}
}
}
// Weather
final WeatherData weatherData = properties.getWeatherData();
if (lanternDataView != null) {
final DataView weatherView = lanternDataView.getView(WEATHER).get();
final String weatherTypeId = weatherView.getString(WEATHER_TYPE).get();
final Optional<Weather> weatherType = Sponge.getRegistry().getType(Weather.class, weatherTypeId);
if (weatherType.isPresent()) {
weatherData.setWeather((LanternWeather) weatherType.get());
} else {
Lantern.getLogger().info("Unknown weather type: {}, the server will default to {}", weatherTypeId, weatherData.getWeather().getId());
}
weatherData.setRunningDuration(weatherView.getLong(WEATHER_RUNNING_DURATION).get());
weatherData.setRemainingDuration(weatherView.getLong(WEATHER_REMAINING_DURATION).get());
} else {
final boolean raining = dataView.getInt(RAINING).get() > 0;
final long rainTime = dataView.getLong(RAIN_TIME).get();
final boolean thundering = dataView.getInt(THUNDERING).get() > 0;
final long thunderTime = dataView.getLong(THUNDER_TIME).get();
final long clearWeatherTime = dataView.getLong(CLEAR_WEATHER_TIME).get();
if (thundering) {
weatherData.setWeather((LanternWeather) Weathers.THUNDER_STORM);
weatherData.setRemainingDuration(thunderTime);
} else if (raining) {
weatherData.setWeather((LanternWeather) Weathers.RAIN);
weatherData.setRemainingDuration(rainTime);
} else {
weatherData.setRemainingDuration(clearWeatherTime);
}
}
// Time
final TimeData timeData = properties.getTimeData();
final long age = dataView.getLong(AGE).get();
timeData.setAge(age);
final long time = dataView.getLong(TIME).orElse(age);
timeData.setDayTime(time);
if (lanternDataView != null && lanternDataView.contains(MOON_PHASE)) {
timeData.setMoonPhase(MoonPhase.valueOf(lanternDataView.getString(MOON_PHASE).get().toUpperCase()));
} else {
timeData.setMoonPhase(MoonPhase.values()[(int) (time / TimeUniverse.TICKS_IN_A_DAY) % 8]);
}
// Get the spawn position
final Optional<Integer> spawnX = dataView.getInt(SPAWN_X);
final Optional<Integer> spawnY = dataView.getInt(SPAWN_Y);
final Optional<Integer> spawnZ = dataView.getInt(SPAWN_Z);
if (spawnX.isPresent() && spawnY.isPresent() && spawnZ.isPresent()) {
properties.setSpawnPosition(new Vector3i(spawnX.get(), spawnY.get(), spawnZ.get()));
}
// Get the game rules
final DataView rulesView = dataView.getView(GAME_RULES).orElse(null);
if (rulesView != null) {
for (Entry<DataQuery, Object> en : rulesView.getValues(false).entrySet()) {
try {
properties.getRules().getOrCreateRule(RuleType.getOrCreate(en.getKey().toString(), RuleDataTypes.STRING, "")).setRawValue((String) en.getValue());
} catch (IllegalArgumentException e) {
Lantern.getLogger().warn("An error occurred while loading a game rule ({}) this one will be skipped", en.getKey().toString(), e);
}
}
}
if (copyLevelSettingsToConfig) {
worldConfig.getGeneration().setSeed(dataView.getLong(SEED).get());
worldConfig.setGameMode(GameModeRegistryModule.get().getByInternalId(dataView.getInt(GAME_MODE).get()).orElse(GameModes.SURVIVAL));
worldConfig.setHardcore(dataView.getInt(HARDCORE).get() > 0);
worldConfig.setDifficulty(DifficultyRegistryModule.get().getByInternalId(dataView.getInt(DIFFICULTY).get()).orElse(Difficulties.NORMAL));
if (dataView.contains(GENERATOR_NAME)) {
final String genName0 = dataView.getString(GENERATOR_NAME).get();
final String genName = genName0.indexOf(':') == -1 ? "minecraft:" + genName0 : genName0;
final GeneratorType generatorType = Sponge.getRegistry().getType(GeneratorType.class, genName).orElse(properties.getDimensionType().getDefaultGeneratorType());
DataContainer generatorSettings = null;
if (dataView.contains(GENERATOR_OPTIONS)) {
String options = dataView.getString(GENERATOR_OPTIONS).get();
String customSettings = null;
if (genName0.equalsIgnoreCase("flat")) {
customSettings = options;
// custom generator options to the flat generator
if (dataView.contains(GENERATOR_OPTIONS_EXTRA)) {
options = dataView.getString(GENERATOR_OPTIONS_EXTRA).get();
} else {
options = "";
}
}
if (!options.isEmpty()) {
try {
generatorSettings = JsonDataFormat.readContainer(options, false);
} catch (Exception e) {
Lantern.getLogger().warn("Unknown generator settings format \"{}\" for type {}, using defaults...", options, genName, e);
}
}
if (generatorSettings == null) {
generatorSettings = generatorType.getGeneratorSettings();
}
if (customSettings != null) {
generatorSettings.set(AbstractFlatGeneratorType.SETTINGS, customSettings);
}
} else {
generatorSettings = generatorType.getGeneratorSettings();
}
worldConfig.getGeneration().setGeneratorType(generatorType);
worldConfig.getGeneration().setGeneratorSettings(generatorSettings);
worldConfig.setLowHorizon(generatorType == GeneratorTypes.FLAT);
}
if (spongeDataView != null) {
spongeDataView.getInt(ENABLED).ifPresent(v -> worldConfig.setWorldEnabled(v > 0));
worldConfig.setKeepSpawnLoaded(spongeDataView.getInt(KEEP_SPAWN_LOADED).map(v -> v > 0).orElse(properties.getDimensionType().doesKeepSpawnLoaded()));
spongeDataView.getInt(LOAD_ON_STARTUP).ifPresent(v -> worldConfig.setKeepSpawnLoaded(v > 0));
spongeDataView.getStringList(GENERATOR_MODIFIERS).ifPresent(v -> {
final List<String> modifiers = worldConfig.getGeneration().getGenerationModifiers();
modifiers.clear();
modifiers.addAll(v);
properties.updateWorldGenModifiers(modifiers);
});
} else {
final LanternDimensionType dimensionType = properties.getDimensionType();
worldConfig.setKeepSpawnLoaded(dimensionType.doesKeepSpawnLoaded());
worldConfig.setDoesWaterEvaporate(dimensionType.doesWaterEvaporate());
}
}
return properties;
}
Aggregations