Search in sources :

Example 11 with TextColor

use of org.spongepowered.api.text.format.TextColor in project SpongeAPI by SpongePowered.

the class Text method of.

/**
 * Builds a {@link Text} from a given array of objects.
 *
 * <p>For instance, you can use this like
 * <code>Text.of(TextColors.DARK_AQUA, "Hi", TextColors.AQUA, "Bye")</code>
 * </p>
 *
 * <p>This will create the correct {@link Text} instance if the input object
 * is the input for one of the {@link Text} types or convert the object to a
 * string otherwise.</p>
 *
 * <p>For instances of type {@link TextRepresentable} (e.g. {@link Text},
 * {@link Builder}, ...) the formatting of appended text has priority over
 * the current formatting in the method, e.g. the following results in a
 * green, then yellow and at the end green again {@link Text}:</p>
 *
 * <code>Text.of(TextColors.GREEN, "Hello ", Text.of(TextColors.YELLOW,
 * "Spongie"), '!');</code>
 *
 * @param objects The object array
 * @return The built text object
 */
public static Text of(Object... objects) {
    // Shortcut for lonely TextRepresentables
    if (objects.length == 1 && objects[0] instanceof TextRepresentable) {
        return ((TextRepresentable) objects[0]).toText();
    }
    final Text.Builder builder = builder();
    TextFormat format = TextFormat.NONE;
    HoverAction<?> hoverAction = null;
    ClickAction<?> clickAction = null;
    ShiftClickAction<?> shiftClickAction = null;
    boolean changedFormat = false;
    for (Object obj : objects) {
        // Text formatting + actions
        if (obj instanceof TextFormat) {
            changedFormat = true;
            format = (TextFormat) obj;
        } else if (obj instanceof TextColor) {
            changedFormat = true;
            format = format.color((TextColor) obj);
        } else if (obj instanceof TextStyle) {
            changedFormat = true;
            format = format.style(obj.equals(TextStyles.RESET) ? TextStyles.NONE : format.getStyle().and((TextStyle) obj));
        } else if (obj instanceof TextAction) {
            changedFormat = true;
            if (obj instanceof HoverAction) {
                hoverAction = (HoverAction<?>) obj;
            } else if (obj instanceof ClickAction) {
                clickAction = (ClickAction<?>) obj;
            } else if (obj instanceof ShiftClickAction) {
                shiftClickAction = (ShiftClickAction<?>) obj;
            } else {
            // Unsupported TextAction
            }
        } else if (obj instanceof TextRepresentable) {
            // Special content
            changedFormat = false;
            Text.Builder childBuilder = ((TextRepresentable) obj).toText().toBuilder();
            // Merge format (existing format has priority)
            childBuilder.format(format.merge(childBuilder.format));
            // Overwrite text actions if *NOT* present
            if (childBuilder.clickAction == null) {
                childBuilder.clickAction = clickAction;
            }
            if (childBuilder.hoverAction == null) {
                childBuilder.hoverAction = hoverAction;
            }
            if (childBuilder.shiftClickAction == null) {
                childBuilder.shiftClickAction = shiftClickAction;
            }
            builder.append(childBuilder.build());
        } else {
            // Simple content
            changedFormat = false;
            Text.Builder childBuilder;
            if (obj instanceof String) {
                childBuilder = builder((String) obj);
            } else if (obj instanceof Translation) {
                childBuilder = builder((Translation) obj);
            } else if (obj instanceof Translatable) {
                childBuilder = builder(((Translatable) obj).getTranslation());
            } else if (obj instanceof Selector) {
                childBuilder = builder((Selector) obj);
            } else if (obj instanceof Score) {
                childBuilder = builder((Score) obj);
            } else {
                childBuilder = builder(String.valueOf(obj));
            }
            if (hoverAction != null) {
                childBuilder.onHover(hoverAction);
            }
            if (clickAction != null) {
                childBuilder.onClick(clickAction);
            }
            if (shiftClickAction != null) {
                childBuilder.onShiftClick(shiftClickAction);
            }
            builder.append(childBuilder.format(format).build());
        }
    }
    if (changedFormat) {
        // Did the formatting change without being applied to something?
        // Then just append an empty text with that formatting
        final Text.Builder childBuilder = builder();
        if (hoverAction != null) {
            childBuilder.onHover(hoverAction);
        }
        if (clickAction != null) {
            childBuilder.onClick(clickAction);
        }
        if (shiftClickAction != null) {
            childBuilder.onShiftClick(shiftClickAction);
        }
        builder.append(childBuilder.format(format).build());
    }
    if (builder.children.size() == 1) {
        // Single content, reduce Text depth
        return builder.children.get(0);
    }
    return builder.build();
}
Also used : Translation(org.spongepowered.api.text.translation.Translation) Translatable(org.spongepowered.api.text.translation.Translatable) TextAction(org.spongepowered.api.text.action.TextAction) Score(org.spongepowered.api.scoreboard.Score) HoverAction(org.spongepowered.api.text.action.HoverAction) TextStyle(org.spongepowered.api.text.format.TextStyle) ClickAction(org.spongepowered.api.text.action.ClickAction) ShiftClickAction(org.spongepowered.api.text.action.ShiftClickAction) ShiftClickAction(org.spongepowered.api.text.action.ShiftClickAction) TextFormat(org.spongepowered.api.text.format.TextFormat) TextColor(org.spongepowered.api.text.format.TextColor) Selector(org.spongepowered.api.text.selector.Selector)

Example 12 with TextColor

use of org.spongepowered.api.text.format.TextColor in project Almura by AlmuraDev.

the class IngameFarmersAlmanac method loadProperties.

@SuppressWarnings("unchecked")
private void loadProperties(World world, IBlockState blockState, BlockPos targetBlockPos) {
    final Hydration hydration = getHydrationDefinition(blockState).orElse(null);
    if (hydration != null) {
        this.addLineLabel(Text.of(TextColors.WHITE, "Hydrated by:"));
        hydration.blockStates().forEach(bs -> {
            this.addLineLabel(Text.of(TextColors.WHITE, "- ", TextColors.YELLOW, bs.block().getLocalizedName()), 2);
            bs.properties().forEach(property -> bs.value(property).ifPresent(stateValue -> {
                final String formattedValue;
                if (stateValue instanceof RangeStateValue) {
                    final RangeStateValue rangeStateValue = (RangeStateValue) stateValue;
                    formattedValue = numberFormat.format(rangeStateValue.min()) + "-" + numberFormat.format(rangeStateValue.max());
                } else {
                    final Comparable rawValue = stateValue.get((IProperty) property);
                    formattedValue = rawValue == null ? "" : rawValue.toString();
                }
                this.addLineLabel(this.getGenericPropertyText("- " + property.getName(), formattedValue), 6);
            }));
            // Todo: this MAX radius check, is it intended to be per block or per hydration or per crop?
            if (hydration.getMaxRadius() > 0) {
                // Range > 0 for only things such as water, never farmland.
                this.addLineLabel(this.getGenericPropertyText("- radius", String.valueOf(hydration.getMaxRadius())), 6);
                boolean found = false;
                for (final BlockPos.MutableBlockPos inRange : BlockPos.getAllInBoxMutable(targetBlockPos.add(-hydration.getMaxRadius(), -1, -hydration.getMaxRadius()), targetBlockPos.add(hydration.getMaxRadius(), -1, hydration.getMaxRadius()))) {
                    IBlockState inRangeState = null;
                    if (inRange.equals(targetBlockPos)) {
                        inRangeState = null;
                    } else {
                        inRangeState = world.getBlockState(inRange);
                    }
                    if (inRangeState != null && hydration.doesStateMatch(inRangeState)) {
                        found = true;
                    }
                }
                if (found) {
                    this.addLineLabel(Text.of(TextColors.WHITE, "- found: ", TextColors.DARK_GREEN, "Yes"), 6);
                } else {
                    this.addLineLabel(Text.of(TextColors.WHITE, "- found: ", TextColors.RED, "No"), 6);
                    this.growing = false;
                // ToDo: this design only allows for ONE hydration block to be used before this breaks.
                }
            }
        });
    }
    if (!message.irrigationPipe) {
        // Growth stage
        getGrowthStage(blockState).ifPresent(growthStage -> this.addLineLabel(this.getGenericPropertyText("Growth Stage", String.format("%d of %d", growthStage.getFirst() + 1, growthStage.getSecond() + 1))));
        getGrowthStage(blockState).ifPresent(growthStage -> readyForHarvest = growthStage.getFirst() == growthStage.getSecond());
        // Ground moisture
        final IBlockState moistureBlockStateTarget = blockState.getBlock() instanceof BlockCrops ? world.getBlockState(targetBlockPos.down()) : blockState;
        final int moistureLevel = getMoistureLevel(moistureBlockStateTarget);
        // Todo: theoretically this should work.
        final boolean isFertile = (moistureLevel > 0) || (hydration != null && growing);
        final TextColor fertileColor = isFertile ? TextColors.DARK_GREEN : TextColors.RED;
        this.addLineLabel(Text.of(TextColors.WHITE, "Soil Quality: ", fertileColor, isFertile ? "Fertile" : "Too dry"));
        if (isFertile) {
            final TextColor moistureColor = moistureLevel > 3 ? TextColors.DARK_GREEN : TextColors.YELLOW;
            this.addLineLabel(Text.of(TextColors.WHITE, "Moisture Level: ", moistureColor, moistureLevel), 2);
        } else {
            this.growing = false;
        }
        // Biome rain
        this.addLineLabel(Text.of(TextColors.WHITE, "Rain: ", message.biomeRainfall > 0.5 ? TextColors.DARK_GREEN : TextColors.GOLD, numberFormat.format(message.biomeRainfall)), 2);
    }
    // Ground temperature
    final DoubleRange temperatureRange = getTemperatureRange(world, blockState, targetBlockPos).orElse(null);
    if (temperatureRange != null) {
        TextColor temperatureColor = TextColors.DARK_GREEN;
        if (!MathUtil.withinRange(round(message.biomeTemperature, 2), temperatureRange.min(), temperatureRange.max())) {
            if (!message.hasAdditionalLightHeatSource) {
                this.growing = false;
                temperatureColor = TextColors.RED;
            } else {
                temperatureColor = TextColors.YELLOW;
            }
        }
        this.addLineLabel(Text.of(TextColors.WHITE, "Ground Temperature: ", temperatureColor, numberFormat.format(message.biomeTemperature)));
        this.addLineLabel(this.getGenericPropertyText("Required", String.format("%s-%s", numberFormat.format(temperatureRange.min()), numberFormat.format(temperatureRange.max()))), 2);
    } else {
        // Is a farmland block or an irrigation pipe
        this.addLineLabel(Text.of(TextColors.WHITE, "Ground Temperature: ", TextColors.DARK_GREEN, numberFormat.format(message.biomeTemperature)));
    }
    // Server light values, can't trust client world. lookups.
    final int sunlight = message.skyLight;
    final int areaLight = message.blockLight;
    final int combinedLightValue = message.combinedLight;
    final boolean isDaytime = message.isDaytime;
    final boolean canSeeSky = message.canSeeSky;
    // Area light value
    final DoubleRange lightRange = getLightRange(world, blockState, targetBlockPos).orElse(null);
    if (lightRange != null) {
        if (!MathUtil.withinRange(combinedLightValue, lightRange.min(), lightRange.max())) {
            if (// Its night time and the crop is NOT exposed to direct sunlight
            !isDaytime && !canSeeSky)
                this.growing = false;
        }
        TextColor combinedlightColor = MathUtil.withinRange(combinedLightValue, lightRange.min(), lightRange.max()) ? TextColors.DARK_GREEN : TextColors.RED;
        if (!isDaytime && canSeeSky) {
            // Night time and the crop IS exposed to direct sunlight.
            combinedlightColor = TextColors.YELLOW;
        }
        this.addLineLabel(Text.of(TextColors.WHITE, "Combined Light: ", combinedlightColor, String.valueOf(combinedLightValue)));
        if (!isDaytime && canSeeSky && !readyForHarvest) {
            this.addLineLabel(Text.of(TextColors.GRAY, "[Night Time Growth]"), 3);
        }
        this.addLineLabel(this.getGenericPropertyText("Required", String.format("%s-%s", numberFormat.format(lightRange.min()), numberFormat.format(lightRange.max()))), 2);
        this.addLineLabel(Text.of(TextColors.WHITE, "Sunlight: ", TextColors.YELLOW, String.valueOf(sunlight)), 4);
        this.addLineLabel(Text.of(TextColors.WHITE, "Area light: ", TextColors.YELLOW, String.valueOf(areaLight)), 4);
    } else {
        // is farmland
        this.addLineLabel(Text.of(TextColors.WHITE, "Combined Light: ", TextColors.DARK_GREEN, String.valueOf(combinedLightValue)));
    }
    if (!message.irrigationPipe) {
        // Can Die
        if (!(blockState.getBlock() instanceof BlockFarmland)) {
            if (!this.readyForHarvest) {
                if (String.valueOf(canRollback(blockState)).equalsIgnoreCase("true")) {
                    this.addLineLabel((Text.of(TextColors.WHITE, "Can Die: ", TextColors.RED, "Yes")));
                    canDie = true;
                } else {
                    this.addLineLabel((Text.of(TextColors.WHITE, "Can Die: ", TextColors.DARK_GREEN, "No")));
                    canDie = false;
                }
            }
        } else {
            this.cropStatusLabel.setVisible(false);
        }
        // Harvest Tool
        final String harvestTool = blockState.getBlock().getHarvestTool(blockState);
        if (harvestTool != null && !harvestTool.isEmpty()) {
            this.addLineLabel(this.getGenericPropertyText("Harvested by", harvestTool));
        }
    }
    if (message.hasAdditionalLightHeatSource) {
        this.addLineLabel(Text.of(TextColors.WHITE, "Special: "));
        this.addLineLabel(Text.of(TextColors.YELLOW, "Heat Lamp Found!"), 4);
    }
    if (message.irrigationPipe) {
        this.addLineLabel((Text.of(TextColors.WHITE, "Irrigation Water Range: ", TextColors.DARK_GREEN, "6")));
        this.cropStatusLabel.setVisible(false);
    } else {
        if (message.irrigationPipeNear) {
            this.addLineLabel((Text.of(TextColors.WHITE, "In-Range of Irrigation: ", TextColors.DARK_GREEN, "Yes")));
        } else {
            this.addLineLabel(Text.of(TextColors.WHITE, "In-Range of Irrigation: ", message.biomeRainfall > 0.5 ? TextColors.DARK_GREEN : TextColors.GOLD, "No"));
        }
    }
}
Also used : BlockCrops(net.minecraft.block.BlockCrops) BlockFarmland(net.minecraft.block.BlockFarmland) ClientboundWorldPositionInformationPacket(com.almuradev.almura.feature.complex.item.almanac.network.ClientboundWorldPositionInformationPacket) WorldClient(net.minecraft.client.multiplayer.WorldClient) UIComponent(net.malisis.core.client.gui.component.UIComponent) NumberFormat(java.text.NumberFormat) ItemStack(net.minecraft.item.ItemStack) RayTraceResult(net.minecraft.util.math.RayTraceResult) BigDecimal(java.math.BigDecimal) WorldType(net.minecraft.world.WorldType) IProperty(net.minecraft.block.properties.IProperty) Block(net.minecraft.block.Block) Text(org.spongepowered.api.text.Text) TextColor(org.spongepowered.api.text.format.TextColor) Minecraft(net.minecraft.client.Minecraft) Anchor(net.malisis.core.client.gui.Anchor) BasicScreen(net.malisis.core.client.gui.BasicScreen) BasicContainer(net.malisis.core.client.gui.component.container.BasicContainer) TextColors(org.spongepowered.api.text.format.TextColors) Growth(com.almuradev.content.type.block.type.crop.processor.growth.Growth) UIScrollBar(net.malisis.core.client.gui.component.control.UIScrollBar) UIButton(net.malisis.core.client.gui.component.interaction.UIButton) RangeStateValue(com.almuradev.content.type.block.state.value.RangeStateValue) CropBlockStateDefinition(com.almuradev.content.type.block.type.crop.state.CropBlockStateDefinition) IMixinBlockCrops(com.almuradev.almura.feature.complex.item.almanac.asm.interfaces.IMixinBlockCrops) UILabel(net.malisis.core.client.gui.component.decoration.UILabel) FontColors(net.malisis.core.util.FontColors) World(net.minecraft.world.World) TextFormatting(net.minecraft.util.text.TextFormatting) DecimalFormat(java.text.DecimalFormat) UIButtonBuilder(net.malisis.core.client.gui.component.interaction.button.builder.UIButtonBuilder) PropertyInteger(net.minecraft.block.properties.PropertyInteger) Hydration(com.almuradev.content.type.block.type.crop.processor.hydration.Hydration) BlockPos(net.minecraft.util.math.BlockPos) Tuple(org.spongepowered.api.util.Tuple) Mouse(org.lwjgl.input.Mouse) BasicForm(net.malisis.core.client.gui.component.container.BasicForm) IBlockState(net.minecraft.block.state.IBlockState) TextSerializers(org.spongepowered.api.text.serializer.TextSerializers) UIImage(net.malisis.core.client.gui.component.decoration.UIImage) MathUtil(com.almuradev.almura.shared.util.MathUtil) Optional(java.util.Optional) CropBlockImpl(com.almuradev.content.type.block.type.crop.CropBlockImpl) DoubleRange(com.almuradev.toolbox.util.math.DoubleRange) UISlimScrollbar(net.malisis.core.client.gui.component.control.UISlimScrollbar) IBlockState(net.minecraft.block.state.IBlockState) BlockCrops(net.minecraft.block.BlockCrops) IMixinBlockCrops(com.almuradev.almura.feature.complex.item.almanac.asm.interfaces.IMixinBlockCrops) BlockFarmland(net.minecraft.block.BlockFarmland) Hydration(com.almuradev.content.type.block.type.crop.processor.hydration.Hydration) RangeStateValue(com.almuradev.content.type.block.state.value.RangeStateValue) DoubleRange(com.almuradev.toolbox.util.math.DoubleRange) IProperty(net.minecraft.block.properties.IProperty) BlockPos(net.minecraft.util.math.BlockPos) TextColor(org.spongepowered.api.text.format.TextColor)

Example 13 with TextColor

use of org.spongepowered.api.text.format.TextColor in project modules-extra by CubeEngine.

the class MarketSignManager method getItemText.

private Text getItemText(MarketSignData data, boolean inEditMode) {
    TextColor color;
    String raw;
    ItemStack item = data.getItem();
    color = TextColors.DARK_RED;
    raw = "No Item";
    if (item != null) {
        color = TextColors.BLACK;
        raw = item.getTranslation().get();
        if (item.get(Keys.DISPLAY_NAME).isPresent()) {
            color = TextColors.DARK_AQUA;
            raw = item.get(Keys.DISPLAY_NAME).get().toPlain();
        }
        if (item.get(Keys.ITEM_LORE).isPresent() || (item.get(Keys.ITEM_ENCHANTMENTS).isPresent() && item.get(Keys.ITEM_ENCHANTMENTS).get().size() > 0)) {
            color = TextColors.DARK_AQUA;
        }
    }
    return Text.of(inEditMode ? DARK_PURPLE : color, raw);
}
Also used : TextColor(org.spongepowered.api.text.format.TextColor) ItemStack(org.spongepowered.api.item.inventory.ItemStack)

Example 14 with TextColor

use of org.spongepowered.api.text.format.TextColor in project LanternServer by LanternPowered.

the class ScoreboardIO method read.

public static Scoreboard read(Path worldFolder) throws IOException {
    DataView dataView = IOHelper.<DataView>read(worldFolder.resolve(SCOREBOARD_DATA), file -> {
        try {
            return NbtStreamUtils.read(Files.newInputStream(file), true);
        } catch (IOException e) {
            throw new IOException("Unable to access " + file.getFileName() + "!", e);
        }
    }).orElse(null);
    final Scoreboard.Builder scoreboardBuilder = Scoreboard.builder();
    if (dataView == null) {
        return scoreboardBuilder.build();
    }
    final Map<String, Objective> objectives = new HashMap<>();
    dataView = dataView.getView(DATA).orElseThrow(() -> new IllegalStateException("Unable to find the data compound."));
    dataView.getViewList(OBJECTIVES).ifPresent(list -> list.forEach(entry -> {
        final String name = entry.getString(NAME).get();
        final Text displayName = LanternTexts.fromLegacy(entry.getString(DISPLAY_NAME).get());
        final Criterion criterion = Sponge.getRegistry().getType(Criterion.class, entry.getString(CRITERION_NAME).get()).orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a criterion with id: {}, default to dummy.", entry.getString(CRITERION_NAME).get());
            return Criteria.DUMMY;
        });
        final ObjectiveDisplayMode objectiveDisplayMode = Sponge.getRegistry().getType(ObjectiveDisplayMode.class, entry.getString(DISPLAY_MODE).get()).orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a display mode with id: {}, default to integer.", entry.getString(CRITERION_NAME).get());
            return ObjectiveDisplayModes.INTEGER;
        });
        objectives.put(name, Objective.builder().name(name).displayName(displayName).criterion(criterion).objectiveDisplayMode(objectiveDisplayMode).build());
    }));
    dataView.getViewList(SCORES).ifPresent(list -> list.forEach(entry -> {
        // We have to keep all the entries to remain compatible with vanilla mc.
        if (entry.getInt(INVALID).orElse(0) > 0) {
            return;
        }
        final Text name = LanternTexts.fromLegacy(entry.getString(NAME).get());
        final int value = entry.getInt(SCORE).get();
        // TODO
        final boolean locked = entry.getInt(LOCKED).orElse(0) > 0;
        final String objectiveName = entry.getString(OBJECTIVE).get();
        Score score = null;
        Objective objective = objectives.get(objectiveName);
        if (objective != null) {
            score = addToObjective(objective, null, name, value);
        }
        final List<String> extraObjectives = entry.getStringList(EXTRA_OBJECTIVES).orElse(null);
        if (extraObjectives != null) {
            for (String extraObjective : extraObjectives) {
                objective = objectives.get(extraObjective);
                if (objective != null) {
                    score = addToObjective(objective, score, name, value);
                }
            }
        }
    }));
    final List<Team> teams = new ArrayList<>();
    dataView.getViewList(TEAMS).ifPresent(list -> list.forEach(entry -> {
        final Team.Builder builder = Team.builder().allowFriendlyFire(entry.getInt(ALLOW_FRIENDLY_FIRE).orElse(0) > 0).canSeeFriendlyInvisibles(entry.getInt(CAN_SEE_FRIENDLY_INVISIBLES).orElse(0) > 0).name(entry.getString(NAME).get()).displayName(LanternTexts.fromLegacy(entry.getString(DISPLAY_NAME).get())).prefix(LanternTexts.fromLegacy(entry.getString(PREFIX).get())).suffix(LanternTexts.fromLegacy(entry.getString(SUFFIX).get())).members(entry.getStringList(MEMBERS).get().stream().map(LanternTexts::fromLegacy).collect(Collectors.toSet()));
        entry.getString(NAME_TAG_VISIBILITY).ifPresent(value -> builder.nameTagVisibility(Sponge.getRegistry().getAllOf(Visibility.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a name tag visibility with id: {}, default to always.", value);
            return Visibilities.ALWAYS;
        })));
        entry.getString(DEATH_MESSAGE_VISIBILITY).ifPresent(value -> builder.deathTextVisibility(Sponge.getRegistry().getAllOf(Visibility.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a death message visibility with id: {}, default to always.", value);
            return Visibilities.ALWAYS;
        })));
        entry.getString(COLLISION_RULE).ifPresent(value -> builder.collisionRule(Sponge.getRegistry().getAllOf(CollisionRule.class).stream().filter(visibility -> visibility.getName().equals(value)).findFirst().orElseGet(() -> {
            Lantern.getLogger().warn("Unable to find a collision rule with id: {}, default to never.", value);
            return CollisionRules.NEVER;
        })));
        entry.getString(TEAM_COLOR).ifPresent(color -> {
            TextColor textColor = Sponge.getRegistry().getType(TextColor.class, color).orElseGet(() -> {
                Lantern.getLogger().warn("Unable to find a team color with id: {}, default to none.", color);
                return TextColors.NONE;
            });
            if (textColor != TextColors.NONE && textColor != TextColors.RESET) {
                builder.color(textColor);
            }
        });
        teams.add(builder.build());
    }));
    final Scoreboard scoreboard = scoreboardBuilder.objectives(new ArrayList<>(objectives.values())).teams(teams).build();
    dataView.getView(DISPLAY_SLOTS).ifPresent(displaySlots -> {
        for (DataQuery key : displaySlots.getKeys(false)) {
            final Matcher matcher = DISPLAY_SLOT_PATTERN.matcher(key.getParts().get(0));
            if (matcher.matches()) {
                final int internalId = Integer.parseInt(matcher.group(1));
                Lantern.getRegistry().getRegistryModule(DisplaySlotRegistryModule.class).get().getByInternalId(internalId).ifPresent(slot -> {
                    final Objective objective = objectives.get(displaySlots.getString(key).get());
                    if (objective != null) {
                        scoreboard.updateDisplaySlot(objective, slot);
                    }
                });
            }
        }
    });
    return scoreboard;
}
Also used : CollisionRule(org.spongepowered.api.scoreboard.CollisionRule) Visibility(org.spongepowered.api.scoreboard.Visibility) HashMap(java.util.HashMap) LanternTexts(org.lanternpowered.server.text.LanternTexts) DataQuery(org.spongepowered.api.data.DataQuery) LanternObjective(org.lanternpowered.server.scoreboard.LanternObjective) ArrayList(java.util.ArrayList) ObjectiveDisplayMode(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode) NbtStreamUtils(org.lanternpowered.server.data.persistence.nbt.NbtStreamUtils) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) TextColor(org.spongepowered.api.text.format.TextColor) Map(java.util.Map) Objective(org.spongepowered.api.scoreboard.objective.Objective) TextColors(org.spongepowered.api.text.format.TextColors) Path(java.nio.file.Path) Nullable(javax.annotation.Nullable) DisplaySlotRegistryModule(org.lanternpowered.server.game.registry.type.scoreboard.DisplaySlotRegistryModule) Iterator(java.util.Iterator) Files(java.nio.file.Files) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) Sponge(org.spongepowered.api.Sponge) DataContainer(org.spongepowered.api.data.DataContainer) Visibilities(org.spongepowered.api.scoreboard.Visibilities) Set(java.util.Set) LanternDisplaySlot(org.lanternpowered.server.scoreboard.LanternDisplaySlot) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) Team(org.spongepowered.api.scoreboard.Team) IOException(java.io.IOException) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) Collectors(java.util.stream.Collectors) Score(org.spongepowered.api.scoreboard.Score) Criteria(org.spongepowered.api.scoreboard.critieria.Criteria) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) List(java.util.List) DataView(org.spongepowered.api.data.DataView) CollisionRules(org.spongepowered.api.scoreboard.CollisionRules) Lantern(org.lanternpowered.server.game.Lantern) ObjectiveDisplayModes(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayModes) Pattern(java.util.regex.Pattern) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) ArrayList(java.util.ArrayList) List(java.util.List) Team(org.spongepowered.api.scoreboard.Team) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) DataQuery(org.spongepowered.api.data.DataQuery) TextColor(org.spongepowered.api.text.format.TextColor) ObjectiveDisplayMode(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode) CollisionRule(org.spongepowered.api.scoreboard.CollisionRule) Text(org.spongepowered.api.text.Text) IOException(java.io.IOException) DataView(org.spongepowered.api.data.DataView) LanternObjective(org.lanternpowered.server.scoreboard.LanternObjective) Objective(org.spongepowered.api.scoreboard.objective.Objective) Score(org.spongepowered.api.scoreboard.Score) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) DisplaySlotRegistryModule(org.lanternpowered.server.game.registry.type.scoreboard.DisplaySlotRegistryModule) Visibility(org.spongepowered.api.scoreboard.Visibility)

Example 15 with TextColor

use of org.spongepowered.api.text.format.TextColor in project LanternServer by LanternPowered.

the class ScoreboardIO method write.

public static void write(Path folder, Scoreboard scoreboard) throws IOException {
    final List<DataView> objectives = scoreboard.getObjectives().stream().map(objective -> DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED).set(NAME, objective.getName()).set(DISPLAY_NAME, ((LanternObjective) objective).getLegacyDisplayName()).set(CRITERION_NAME, objective.getCriterion().getId()).set(DISPLAY_MODE, objective.getDisplayMode().getId())).collect(Collectors.toList());
    final List<DataView> scores = new ArrayList<>();
    for (Score score : scoreboard.getScores()) {
        final Iterator<Objective> it = score.getObjectives().iterator();
        final DataView baseView = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED).set(NAME, ((LanternScore) score).getLegacyName()).set(SCORE, score.getScore());
        // TODO: Locked state
        final DataView mainView = baseView.copy().set(OBJECTIVE, it.next().getName());
        final List<String> extraObjectives = new ArrayList<>();
        while (it.hasNext()) {
            final String extraObjectiveName = it.next().getName();
            scores.add(baseView.copy().set(OBJECTIVE, extraObjectiveName).set(INVALID, (byte) 1));
            extraObjectives.add(extraObjectiveName);
        }
        if (!extraObjectives.isEmpty()) {
            mainView.set(EXTRA_OBJECTIVES, extraObjectives);
        }
    }
    final List<DataView> teams = new ArrayList<>();
    for (Team team : scoreboard.getTeams()) {
        final DataView container = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED).set(ALLOW_FRIENDLY_FIRE, (byte) (team.allowFriendlyFire() ? 1 : 0)).set(CAN_SEE_FRIENDLY_INVISIBLES, (byte) (team.canSeeFriendlyInvisibles() ? 1 : 0)).set(NAME_TAG_VISIBILITY, team.getNameTagVisibility().getName()).set(NAME, team.getName()).set(DISPLAY_NAME, ((LanternTeam) team).getLegacyDisplayName()).set(DEATH_MESSAGE_VISIBILITY, team.getDeathMessageVisibility().getName()).set(COLLISION_RULE, team.getCollisionRule().getName()).set(PREFIX, ((LanternTeam) team).getLegacyPrefix()).set(SUFFIX, ((LanternTeam) team).getLegacySuffix());
        final TextColor teamColor = team.getColor();
        if (teamColor != TextColors.NONE) {
            container.set(TEAM_COLOR, teamColor.getId());
        }
        final Set<Text> members = team.getMembers();
        container.set(MEMBERS, members.stream().map(LanternTexts::toLegacy).collect(Collectors.toList()));
        teams.add(container);
    }
    final DataContainer rootDataContainer = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED);
    final DataView dataView = rootDataContainer.createView(DATA).set(OBJECTIVES, objectives).set(SCORES, scores).set(TEAMS, teams);
    final DataView displaySlots = dataView.createView(DISPLAY_SLOTS);
    ((LanternScoreboard) scoreboard).getObjectivesInSlot().entrySet().forEach(entry -> displaySlots.set(DataQuery.of("slot_" + ((LanternDisplaySlot) entry.getKey()).getInternalId()), entry.getValue().getName()));
    IOHelper.write(folder.resolve(SCOREBOARD_DATA), file -> {
        NbtStreamUtils.write(rootDataContainer, Files.newOutputStream(file), true);
        return true;
    });
}
Also used : CollisionRule(org.spongepowered.api.scoreboard.CollisionRule) Visibility(org.spongepowered.api.scoreboard.Visibility) HashMap(java.util.HashMap) LanternTexts(org.lanternpowered.server.text.LanternTexts) DataQuery(org.spongepowered.api.data.DataQuery) LanternObjective(org.lanternpowered.server.scoreboard.LanternObjective) ArrayList(java.util.ArrayList) ObjectiveDisplayMode(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode) NbtStreamUtils(org.lanternpowered.server.data.persistence.nbt.NbtStreamUtils) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) TextColor(org.spongepowered.api.text.format.TextColor) Map(java.util.Map) Objective(org.spongepowered.api.scoreboard.objective.Objective) TextColors(org.spongepowered.api.text.format.TextColors) Path(java.nio.file.Path) Nullable(javax.annotation.Nullable) DisplaySlotRegistryModule(org.lanternpowered.server.game.registry.type.scoreboard.DisplaySlotRegistryModule) Iterator(java.util.Iterator) Files(java.nio.file.Files) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) Sponge(org.spongepowered.api.Sponge) DataContainer(org.spongepowered.api.data.DataContainer) Visibilities(org.spongepowered.api.scoreboard.Visibilities) Set(java.util.Set) LanternDisplaySlot(org.lanternpowered.server.scoreboard.LanternDisplaySlot) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) Team(org.spongepowered.api.scoreboard.Team) IOException(java.io.IOException) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) Collectors(java.util.stream.Collectors) Score(org.spongepowered.api.scoreboard.Score) Criteria(org.spongepowered.api.scoreboard.critieria.Criteria) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) List(java.util.List) DataView(org.spongepowered.api.data.DataView) CollisionRules(org.spongepowered.api.scoreboard.CollisionRules) Lantern(org.lanternpowered.server.game.Lantern) ObjectiveDisplayModes(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayModes) Pattern(java.util.regex.Pattern) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) ArrayList(java.util.ArrayList) Text(org.spongepowered.api.text.Text) DataView(org.spongepowered.api.data.DataView) LanternObjective(org.lanternpowered.server.scoreboard.LanternObjective) Objective(org.spongepowered.api.scoreboard.objective.Objective) Score(org.spongepowered.api.scoreboard.Score) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) DataContainer(org.spongepowered.api.data.DataContainer) LanternDisplaySlot(org.lanternpowered.server.scoreboard.LanternDisplaySlot) LanternTexts(org.lanternpowered.server.text.LanternTexts) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) Team(org.spongepowered.api.scoreboard.Team) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) TextColor(org.spongepowered.api.text.format.TextColor) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam)

Aggregations

TextColor (org.spongepowered.api.text.format.TextColor)21 Text (org.spongepowered.api.text.Text)9 TextStyle (org.spongepowered.api.text.format.TextStyle)6 TextColors (org.spongepowered.api.text.format.TextColors)4 List (java.util.List)3 Map (java.util.Map)3 Optional (java.util.Optional)3 Collectors (java.util.stream.Collectors)3 LanternDisplaySlot (org.lanternpowered.server.scoreboard.LanternDisplaySlot)3 Sponge (org.spongepowered.api.Sponge)3 Player (org.spongepowered.api.entity.living.player.Player)3 ItemStack (org.spongepowered.api.item.inventory.ItemStack)3 Score (org.spongepowered.api.scoreboard.Score)3 IOException (java.io.IOException)2 Files (java.nio.file.Files)2 Path (java.nio.file.Path)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Iterator (java.util.Iterator)2 Set (java.util.Set)2