use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.
the class LanternWorldPropertiesIO method convert.
static LevelData convert(LanternWorldProperties properties, @Nullable Integer dimensionId, @Nullable BitSet dimensionMap) {
final DataContainer rootContainer = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
final DataView dataView = rootContainer.createView(DATA);
final DataContainer spongeRootContainer = properties.getAdditionalProperties().copy();
final DataView spongeContainer = spongeRootContainer.createView(DataQueries.SPONGE_DATA);
final DataView lanternDataView = spongeContainer.createView(LANTERN);
dataView.set(SEED, properties.getSeed());
dataView.set(VERSION, CURRENT_VERSION);
final DataView rulesView = dataView.createView(GAME_RULES);
for (Entry<String, String> en : properties.getGameRules().entrySet()) {
rulesView.set(DataQuery.of(en.getKey()), en.getValue());
}
// Weather
final WeatherData weatherData = properties.getWeatherData();
final boolean raining = properties.isRaining();
final boolean thunderStorm = properties.isThundering();
dataView.set(RAINING, (byte) (properties.isRaining() ? 1 : 0));
dataView.set(RAIN_TIME, properties.getRainTime());
dataView.set(THUNDERING, (byte) (properties.isThundering() ? 1 : 0));
dataView.set(THUNDER_TIME, properties.getThunderTime());
dataView.set(HARDCORE, (byte) (properties.isHardcore() ? 1 : 0));
dataView.set(CLEAR_WEATHER_TIME, raining || thunderStorm ? 0 : weatherData.getRemainingDuration());
final DataView weatherDataView = lanternDataView.createView(WEATHER);
weatherDataView.set(WEATHER_TYPE, weatherData.getWeather().getId());
weatherDataView.set(WEATHER_REMAINING_DURATION, weatherData.getRemainingDuration());
weatherDataView.set(WEATHER_RUNNING_DURATION, weatherData.getRunningDuration());
// Time
final TimeData timeData = properties.getTimeData();
dataView.set(TIME, timeData.getDayTime());
dataView.set(AGE, timeData.getAge());
lanternDataView.set(MOON_PHASE, timeData.getMoonPhase().toString().toLowerCase());
dataView.set(LAST_PLAYED, properties.getLastPlayedTime());
dataView.set(SIZE_ON_DISK, 0L);
dataView.set(INITIALIZED, (byte) (properties.isInitialized() ? 1 : 0));
String generatorId = properties.getGeneratorType().getId();
if (generatorId.startsWith("minecraft:")) {
generatorId = generatorId.replaceFirst("minecraft:", "");
}
dataView.set(GENERATOR_NAME, generatorId);
// The default world generator has a version of one
dataView.set(GENERATOR_VERSION, generatorId.equalsIgnoreCase("default") ? 1 : 0);
// The flat world generator has a different settings format
if (generatorId.equalsIgnoreCase("flat")) {
dataView.set(GENERATOR_OPTIONS, properties.getGeneratorSettings().getString(AbstractFlatGeneratorType.SETTINGS).get());
try {
dataView.set(GENERATOR_OPTIONS_EXTRA, JsonDataFormat.writeAsString(properties.getGeneratorSettings().copy().remove(AbstractFlatGeneratorType.SETTINGS)));
} catch (IOException e) {
throw new IllegalStateException(e);
}
} else {
dataView.set(GENERATOR_OPTIONS, properties.getGeneratorSettings());
}
dataView.set(DIFFICULTY, ((LanternDifficulty) properties.getDifficulty()).getInternalId());
dataView.set(DIFFICULTY_LOCKED, (byte) (properties.isDifficultyLocked() ? 1 : 0));
dataView.set(GAME_MODE, ((LanternGameMode) properties.getGameMode()).getInternalId());
dataView.set(MAP_FEATURES, (byte) (properties.mapFeatures ? 1 : 0));
final LanternWorldBorder border = properties.getWorldBorder();
dataView.set(BORDER_CENTER_X, border.centerX);
dataView.set(BORDER_CENTER_Z, border.centerZ);
dataView.set(BORDER_DAMAGE, border.damage);
dataView.set(BORDER_DAMAGE_THRESHOLD, border.damageThreshold);
dataView.set(BORDER_SIZE_END, border.diameterEnd);
dataView.set(BORDER_SIZE_START, border.getDiameter());
dataView.set(BORDER_SIZE_LERP_TIME, border.getTimeRemaining());
dataView.set(BORDER_WARNING_BLOCKS, border.warningDistance);
dataView.set(BORDER_WARNING_TIME, border.warningTime);
final Vector3i spawn = properties.getSpawnPosition();
dataView.set(SPAWN_X, spawn.getX());
dataView.set(SPAWN_Y, spawn.getY());
dataView.set(SPAWN_Z, spawn.getZ());
spongeContainer.set(GENERATE_BONUS_CHEST, (byte) (properties.doesGenerateBonusChest() ? 1 : 0));
spongeContainer.set(DIMENSION_TYPE, properties.getDimensionType().getId());
spongeContainer.set(PORTAL_AGENT_TYPE, properties.getPortalAgentType().getId());
spongeContainer.set(GENERATOR_MODIFIERS, properties.generatorModifiers.stream().map(CatalogType::getId).collect(Collectors.toList()));
// Serialization behavior
short serializationBehaviorId = 1;
if (properties.getSerializationBehavior() == SerializationBehaviors.MANUAL) {
serializationBehaviorId = 0;
} else if (properties.getSerializationBehavior() == SerializationBehaviors.NONE) {
serializationBehaviorId = -1;
}
spongeContainer.set(SERIALIZATION_BEHAVIOR, serializationBehaviorId);
// Tracker
final List<DataView> trackerUniqueIdViews = new ArrayList<>();
final List<UUID> uniqueIdsByIndex = properties.getTrackerIdAllocator().getUniqueIdsByIndex();
for (UUID uniqueId : uniqueIdsByIndex) {
final DataView uniqueIdView = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
if (uniqueId != null) {
uniqueIdView.set(UUID_MOST, uniqueId.getMostSignificantBits());
uniqueIdView.set(UUID_LEAST, uniqueId.getLeastSignificantBits());
}
trackerUniqueIdViews.add(uniqueIdView);
}
spongeContainer.set(TRACKER_UUID_TABLE, trackerUniqueIdViews);
return new LevelData(properties.getWorldName(), properties.getUniqueId(), rootContainer, spongeRootContainer, dimensionId, dimensionMap);
}
use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.
the class AnvilChunkIOService method write.
@Override
public void write(LanternChunk chunk) throws IOException {
final int x = chunk.getX();
final int z = chunk.getZ();
final RegionFile region = this.cache.getRegionFileByChunk(x, z);
final int regionX = x & REGION_MASK;
final int regionZ = z & REGION_MASK;
final DataContainer rootView = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
final DataView levelDataView = rootView.createView(LEVEL);
// Core properties
levelDataView.set(VERSION, (byte) 1);
levelDataView.set(X, chunk.getX());
levelDataView.set(Z, chunk.getZ());
levelDataView.set(TERRAIN_POPULATED, (byte) (chunk.isPopulated() ? 1 : 0));
levelDataView.set(LIGHT_POPULATED, (byte) (chunk.isLightPopulated() ? 1 : 0));
levelDataView.set(LAST_UPDATE, 0L);
levelDataView.set(INHABITED_TIME, chunk.getLongInhabitedTime());
// Chunk sections
final ChunkSectionSnapshot[] sections = chunk.getSectionSnapshots(true);
final List<DataView> sectionDataViews = new ArrayList<>();
final List<DataView> tileEntityDataViews = new ArrayList<>();
for (byte i = 0; i < sections.length; ++i) {
final ChunkSectionSnapshot section = sections[i];
if (section == null) {
continue;
}
final DataContainer sectionDataView = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
sectionDataView.set(Y, i);
final byte[] rawTypes = new byte[section.types.length];
final short[] types = section.types;
NibbleArray extTypes = null;
final NibbleArray data = new NibbleArray(rawTypes.length);
for (int j = 0; j < rawTypes.length; j++) {
rawTypes[j] = (byte) ((types[j] >> 4) & 0xff);
byte extType = (byte) (types[j] >> 12);
if (extType != 0) {
if (extTypes == null) {
extTypes = new NibbleArray(rawTypes.length);
}
extTypes.set(j, extType);
}
data.set(j, (byte) (types[j] & 0xf));
}
sectionDataView.set(BLOCKS, rawTypes);
if (extTypes != null) {
sectionDataView.set(BLOCKS_EXTRA, extTypes.getPackedArray());
}
sectionDataView.set(DATA, data.getPackedArray());
sectionDataView.set(BLOCK_LIGHT, section.lightFromBlock);
final byte[] lightFromSky = section.lightFromSky;
if (lightFromSky != null) {
sectionDataView.set(SKY_LIGHT, lightFromSky);
}
sectionDataViews.add(sectionDataView);
// noinspection unchecked
final ObjectSerializer<LanternTileEntity> tileEntitySerializer = ObjectSerializerRegistry.get().get(LanternTileEntity.class).get();
// Serialize the tile entities
for (Short2ObjectMap.Entry<LanternTileEntity> tileEntityEntry : section.tileEntities.short2ObjectEntrySet()) {
if (!tileEntityEntry.getValue().isValid()) {
continue;
}
final DataView dataView = tileEntitySerializer.serialize(tileEntityEntry.getValue());
final short pos = tileEntityEntry.getShortKey();
dataView.set(TILE_ENTITY_X, x * 16 + (pos & 0xf));
dataView.set(TILE_ENTITY_Y, (i << 4) | (pos >> 8));
dataView.set(TILE_ENTITY_Z, z * 16 + ((pos >> 4) & 0xf));
tileEntityDataViews.add(dataView);
}
}
levelDataView.set(TILE_ENTITIES, tileEntityDataViews);
levelDataView.set(SECTIONS, sectionDataViews);
levelDataView.set(HEIGHT_MAP, chunk.getHeightMap());
// noinspection unchecked
final Short2ObjectMap<LanternChunk.TrackerData>[] trackerData = chunk.getTrackerData().getRawObjects();
final List<DataView> trackerDataViews = new ArrayList<>();
for (int i = 0; i < trackerData.length; i++) {
final Short2ObjectMap<LanternChunk.TrackerData> trackerDataSection = trackerData[i];
for (Short2ObjectMap.Entry<LanternChunk.TrackerData> entry : trackerDataSection.short2ObjectEntrySet()) {
// index = y << 8 | z << 4 | x
int index = entry.getShortKey() & 0xffff;
// Convert the index to the column based system
// index = z << 12 | y << 4 | x
index = ((index >> 4) & 0xf) << 12 | i << 8 | (index >> 4) & 0xf0 | index & 0xf;
final DataView trackerDataView = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
trackerDataView.set(TRACKER_BLOCK_POS, (short) index);
trackerDataView.set(TRACKER_ENTRY_NOTIFIER, entry.getValue().getNotifierId());
trackerDataView.set(TRACKER_ENTRY_CREATOR, entry.getValue().getCreatorId());
trackerDataViews.add(trackerDataView);
}
}
if (!trackerDataViews.isEmpty()) {
levelDataView.createView(DataQueries.SPONGE_DATA).set(TRACKER_DATA_TABLE, trackerDataViews);
}
final short[] biomes = chunk.getBiomes();
final byte[] biomes0 = new byte[biomes.length];
byte[] biomes1 = null;
for (int i = 0; i < biomes.length; i++) {
biomes0[i] = (byte) (biomes[i] & 0xff);
byte value = (byte) ((biomes[i] >> 4) & 0xff);
if (value != 0) {
if (biomes1 == null) {
biomes1 = new byte[biomes0.length];
}
biomes1[i] = value;
}
}
levelDataView.set(BIOMES, biomes0);
if (biomes1 != null) {
levelDataView.set(BIOMES_EXTRA, biomes1);
}
// noinspection unchecked
final List<LanternEntity> entities = new ArrayList(chunk.getEntities(entity -> !(entity instanceof Player)));
final ObjectSerializer<LanternEntity> entitySerializer = ObjectSerializerRegistry.get().get(LanternEntity.class).get();
final List<DataView> entityViews = new ArrayList<>();
for (LanternEntity entity : entities) {
if (entity.getRemoveState() == LanternEntity.RemoveState.DESTROYED) {
continue;
}
final DataView entityView = entitySerializer.serialize(entity);
entityViews.add(entityView);
}
levelDataView.set(ENTITIES, entityViews);
try (NbtDataContainerOutputStream nbt = new NbtDataContainerOutputStream(region.getChunkDataOutputStream(regionX, regionZ))) {
nbt.write(rootView);
nbt.flush();
}
}
use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.
the class InventorySnapshotSerializer method serialize.
public static List<DataView> serialize(InventorySnapshot inventorySnapshot) {
final ObjectSerializer<LanternItemStack> itemStackSerializer = ObjectSerializerRegistry.get().get(LanternItemStack.class).get();
final List<DataView> itemViews = new ArrayList<>();
for (Int2ObjectMap.Entry<ItemStackSnapshot> entry : inventorySnapshot.getItemStackSnapshots().int2ObjectEntrySet()) {
final DataView itemView = itemStackSerializer.serialize((LanternItemStack) entry.getValue().createStack());
// noinspection ConstantConditions
itemView.set(SLOT, (byte) entry.getIntKey());
itemViews.add(itemView);
}
return itemViews;
}
use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.
the class UserStore method serializePlayerInventory.
private static List<DataView> serializePlayerInventory(AbstractUserInventory<?> inventory) {
final List<DataView> itemViews = new ArrayList<>();
final LanternMainPlayerInventory mainInventory = inventory.getMain();
final LanternPlayerEquipmentInventory equipmentInventory = inventory.getEquipment();
final AbstractSlot offHandSlot = inventory.getOffhand();
Iterable<Slot> slots = mainInventory.slots();
for (Slot slot : slots) {
serializeSlot(mainInventory, slot, 0, ItemStackStore.INSTANCE, itemViews);
}
slots = equipmentInventory.slots();
for (Slot slot : slots) {
serializeSlot(equipmentInventory, slot, 100, ItemStackStore.INSTANCE, itemViews);
}
serializeSlot(150, offHandSlot, ItemStackStore.INSTANCE, itemViews);
return itemViews;
}
use of org.spongepowered.api.data.DataView in project LanternServer by LanternPowered.
the class UserStore method serializeValues.
@Override
public void serializeValues(T player, SimpleValueContainer valueContainer, DataView dataView) {
valueContainer.remove(Keys.IS_SPRINTING);
valueContainer.remove(Keys.IS_SNEAKING);
valueContainer.remove(LanternKeys.ACTIVE_HAND);
final DataView abilities = dataView.createView(ABILITIES);
abilities.set(FLYING, (byte) (valueContainer.remove(Keys.IS_FLYING).orElse(false) ? 1 : 0));
abilities.set(FLYING_SPEED, valueContainer.remove(Keys.FLYING_SPEED).orElse(0.1).floatValue());
abilities.set(CAN_FLY, (byte) (valueContainer.remove(Keys.CAN_FLY).orElse(false) ? 1 : 0));
final DataView spongeData = getOrCreateView(dataView, DataQueries.EXTENDED_SPONGE_DATA);
spongeData.set(FIRST_DATE_PLAYED, valueContainer.remove(Keys.FIRST_DATE_PLAYED).orElse(Instant.now()).toEpochMilli());
spongeData.set(LAST_DATE_PLAYED, valueContainer.remove(Keys.LAST_DATE_PLAYED).orElse(Instant.now()).toEpochMilli());
spongeData.set(UNIQUE_ID, player.getUniqueId().toString());
spongeData.set(Queries.CONTENT_VERSION, 1);
final Map<UUID, RespawnLocation> respawnLocations = valueContainer.remove(Keys.RESPAWN_LOCATIONS).get();
final List<DataView> respawnLocationViews = new ArrayList<>();
for (RespawnLocation respawnLocation : respawnLocations.values()) {
Lantern.getWorldManager().getWorldDimensionId(respawnLocation.getWorldUniqueId()).ifPresent(dimensionId -> {
// Overworld respawn location is saved in the root container
if (dimensionId == 0) {
serializeRespawnLocationTo(dataView, respawnLocation);
} else {
respawnLocationViews.add(serializeRespawnLocationTo(DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED), respawnLocation).set(RESPAWN_LOCATIONS_DIMENSION, dimensionId));
}
});
}
dataView.set(RESPAWN_LOCATIONS, respawnLocationViews);
dataView.set(GAME_MODE, ((LanternGameMode) valueContainer.remove(Keys.GAME_MODE).orElse(GameModes.NOT_SET)).getInternalId());
dataView.set(SELECTED_ITEM_SLOT, player.getInventory().getHotbar().getSelectedSlotIndex());
dataView.set(SCORE, valueContainer.remove(LanternKeys.SCORE).get());
// Serialize the player inventory
dataView.set(INVENTORY, serializePlayerInventory(player.getInventory()));
// Serialize the ender chest inventory
dataView.set(ENDER_CHEST_INVENTORY, serializeEnderChest(player.getEnderChestInventory()));
final DataView recipeBook = dataView.createView(RECIPE_BOOK);
recipeBook.set(RECIPE_BOOK_FILTER_ACTIVE, (byte) (valueContainer.remove(LanternKeys.RECIPE_BOOK_FILTER_ACTIVE).orElse(false) ? 1 : 0));
recipeBook.set(RECIPE_BOOK_GUI_OPEN, (byte) (valueContainer.remove(LanternKeys.RECIPE_BOOK_GUI_OPEN).orElse(false) ? 1 : 0));
valueContainer.remove(LanternKeys.OPEN_ADVANCEMENT_TREE).ifPresent(o -> {
if (o.isPresent()) {
dataView.set(OPEN_ADVANCEMENT_TREE, o.get().getId());
}
});
super.serializeValues(player, valueContainer, dataView);
}
Aggregations