Add builder GUI, stricter checks, GPL-3 license and English comments

- GUI (phases 7-8): BuilderScreen, Panel, NumberSlider, CycleButton, BuilderUi
  keybinds (Right Shift menu, P pause macro), lang entries, README
- ConfigStore.loadOrEmpty/saveQuietly; BuildSettings.Range; BuilderFeature
  settings()/stage()/togglePause()
- Checks: ~60 Checkstyle rules (errors), PMD with 7 categories, checkArchitecture
  (layer rules + max 4 files per package, with baseline), javac -Xlint:all -Werror,
  rule rejecting non-English comments
- File length limit raised to 250 lines
- License: GPL-3.0-only (LICENSE, fabric.mod.json)
- All code comments and log messages translated to English
This commit is contained in:
Loki 2026-10-31 14:31:39 +01:00
parent b26dfbbade
commit d9df098064
Signed by: boba
GPG key ID: 253067914055423B
130 changed files with 1779 additions and 267 deletions

View file

@ -6,10 +6,12 @@ import dev.loki.satura.core.command.builtin.HelpCommand;
import dev.loki.satura.core.config.ConfigStore;
import dev.loki.satura.core.event.EventBus;
import dev.loki.satura.feature.builder.BuilderFeature;
import dev.loki.satura.gui.BuilderUi;
import dev.loki.satura.render.RenderDebug;
import dev.loki.satura.render.Renderer;
import dev.loki.satura.render.world.Marks;
import dev.loki.satura.render.world.SelectionRenderer;
import dev.loki.satura.util.ActionBarOut;
import dev.loki.satura.util.ChatOut;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
@ -18,7 +20,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Точка входа клиента. Только сборка компонентов — вся логика в feature-пакетах.
* Client entry point. Only wires components together; all logic lives in the feature packages.
*/
public final class SaturaClient implements ClientModInitializer {
@ -39,6 +41,7 @@ public final class SaturaClient implements ClientModInitializer {
RenderDebug.installIfEnabled(Renderer.shared());
new SelectionRenderer(() -> new Marks(builder.selection().pos1(), builder.selection().pos2()),
SELECTION_SEE_THROUGH).register();
new BuilderUi(builder, new ActionBarOut()).register();
LOG.info("[satura] client init");
}
}

View file

@ -4,7 +4,7 @@ import dev.loki.satura.core.command.CommandRegistry;
import dev.loki.satura.core.config.ConfigStore;
import dev.loki.satura.core.event.EventBus;
/** Собранное ядро; доступ для миксинов (они не могут получить зависимости через конструктор). */
/** Assembled core; exposed to mixins (they cannot receive dependencies through a constructor). */
public record CoreServices(EventBus events, CommandRegistry commands, ConfigStore config) {
private static CoreServices current;
@ -13,7 +13,7 @@ public record CoreServices(EventBus events, CommandRegistry commands, ConfigStor
current = services;
}
/** Ядро или null, если мод ещё не инициализирован. */
/** The core, or null if the mod is not initialized yet. */
public static CoreServices get() {
return current;
}

View file

@ -3,7 +3,7 @@ package dev.loki.satura.core.command;
import java.util.List;
import java.util.function.Consumer;
/** Чат-команда с префиксом {@code .}. */
/** Chat command with the {@code .} prefix. */
public interface Command {
String name();
@ -11,17 +11,17 @@ public interface Command {
String description();
/**
* Выполнить команду.
* Execute the command.
*
* @param args токены после имени
* @param reply куда писать ответ пользователю
* @param args tokens after the name
* @param reply where to write the reply for the user
*/
void execute(List<String> args, Consumer<String> reply);
/**
* Кандидаты для последнего (редактируемого) токена.
* Candidates for the last (currently edited) token.
*
* @param args токены после имени; последний — недописанный (может быть пустым)
* @param args tokens after the name; the last one is unfinished (may be empty)
*/
default List<String> suggest(List<String> args) {
return List.of();

View file

@ -3,7 +3,7 @@ package dev.loki.satura.core.command;
import java.util.ArrayList;
import java.util.List;
/** Разбиение строки на токены по пробелам; кавычки группируют; хвостовой пробел даёт пустой токен. */
/** Splits a line into tokens by spaces; quotes group; a trailing space yields an empty token. */
final class CommandParser {
private static final char QUOTE = '"';

View file

@ -8,7 +8,7 @@ import java.util.Map;
import java.util.TreeMap;
import java.util.function.Consumer;
/** Реестр команд: регистрация, выполнение строки и подсказки. */
/** Command registry: registration, line execution and suggestions. */
@SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidCatchingGenericException"})
public final class CommandRegistry {
@ -29,7 +29,7 @@ public final class CommandRegistry {
return commands.values();
}
/** Выполняет строку без префикса, например {@code "help"}. */
/** Executes a line without the prefix, e.g. {@code "help"}. */
public void execute(String line) {
List<String> tokens = CommandParser.tokenize(line.strip());
Command command = commands.get(tokens.get(0).toLowerCase(Locale.ROOT));
@ -44,7 +44,7 @@ public final class CommandRegistry {
}
}
/** Подсказки для текста до курсора (с префиксом). */
/** Suggestions for the text before the cursor (with the prefix). */
public List<String> suggest(String toCursor) {
String body = toCursor.startsWith(SuggestHelper.PREFIX)
? toCursor.substring(SuggestHelper.PREFIX.length()) : toCursor;

View file

@ -3,7 +3,7 @@ package dev.loki.satura.core.command;
import java.util.List;
import java.util.Locale;
/** Фильтрация подсказок по префиксу и позиция начала редактируемого токена. */
/** Suggestion filtering by prefix and the start position of the edited token. */
public final class SuggestHelper {
public static final String PREFIX = ".";

View file

@ -6,7 +6,7 @@ import dev.loki.satura.core.command.SuggestHelper;
import java.util.List;
import java.util.function.Consumer;
/** {@code .help} — список зарегистрированных команд. */
/** {@code .help} — list of registered commands. */
public final class HelpCommand implements Command {
private final CommandRegistry registry;

View file

@ -11,10 +11,14 @@ import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Хранение профилей как json-файлов в каталоге (config/satura/). */
/** Stores profiles as json files in a directory (config/satura/). */
@SuppressWarnings("PMD.GuardLogStatement")
public final class ConfigStore {
private static final Logger LOG = LoggerFactory.getLogger(ConfigStore.class);
private static final String EXTENSION = ".json";
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
@ -41,6 +45,26 @@ public final class ConfigStore {
}
}
/** Loads the profile or an empty default; read errors never propagate to the caller. */
@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.CloseResource"})
public Profile loadOrEmpty(final String name) {
try {
return load(name).orElse(Profile.empty(name));
} catch (IOException | RuntimeException e) {
LOG.warn("[satura] profile {} not loaded: {}", name, e.toString());
return Profile.empty(name);
}
}
/** Saves the profile, swallowing I/O errors (for GUI/click handlers that cannot throw). */
public void saveQuietly(final Profile profile) {
try {
save(profile);
} catch (IOException e) {
LOG.warn("[satura] profile {} not saved: {}", profile.name(), e.toString());
}
}
public List<String> list() throws IOException {
if (!Files.isDirectory(dir)) {
return List.of();

View file

@ -4,10 +4,10 @@ import java.util.HashMap;
import java.util.Map;
/**
* Иммутабельный профиль настроек.
* Immutable settings profile.
*
* @param name имя профиля (имя файла)
* @param settings ключ → значение
* @param name profile name (file name)
* @param settings key → value
*/
@SuppressWarnings("PMD.LooseCoupling")
public record Profile(String name, Map<String, String> settings) {

View file

@ -1,6 +1,6 @@
package dev.loki.satura.core.event;
/** Событие, обработку которого можно отменить; после отмены цепочка слушателей прерывается. */
/** An event whose handling can be cancelled; once cancelled, the listener chain is interrupted. */
public interface Cancellable extends Event {
boolean isCancelled();

View file

@ -1,5 +1,5 @@
package dev.loki.satura.core.event;
/** Маркер события. Тип события = его класс. */
/** Event marker. The event type is its class. */
public interface Event {
}

View file

@ -7,7 +7,7 @@ import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
/** Шина событий: подписка с приоритетами, отписка, остановка цепочки на отменённом событии. */
/** Event bus: prioritized subscription, unsubscription, chain stops on a cancelled event. */
@SuppressWarnings("PMD.LooseCoupling")
public final class EventBus {

View file

@ -3,12 +3,12 @@ package dev.loki.satura.core.event;
import java.util.function.Consumer;
/**
* Подписка на событие. Меньший priority вызывается раньше.
* Event subscription. A lower priority is called earlier.
*
* @param type класс события
* @param priority порядок вызова
* @param handler обработчик
* @param <T> тип события
* @param type event class
* @param priority call order
* @param handler handler
* @param <T> event type
*/
public record Listener<T extends Event>(Class<T> type, int priority, Consumer<T> handler) {

View file

@ -3,6 +3,6 @@ package dev.loki.satura.core.event.world;
import dev.loki.satura.core.event.Event;
import net.minecraft.util.math.BlockPos;
/** В клиентском мире изменился блок. */
/** A block changed in the client world. */
public record BlockChangeEvent(BlockPos pos) implements Event {
}

View file

@ -13,11 +13,16 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
/** Настройки билдера; читаются из {@link Profile} и в него же сериализуются. */
/** Builder settings; read from and serialized back into a {@link Profile}. */
@SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidFieldNameMatchingMethodName"})
public final class BuildSettings {
/** Range and current value of a strategy parameter, for a GUI slider. */
public record Range(double min, double max, double step, double value) {
}
static final String KEY_BLOCK = "block";
static final String KEY_SHAPE = "shape";
static final String KEY_LAYERS = "layers";
@ -87,7 +92,7 @@ public final class BuildSettings {
strategy = id;
}
/** Слоёв за проход: значение опции стратегии bandLayers, если она её объявляет. */
/** Layers per pass: the strategy's bandLayers option value, if it declares one. */
public int layers() {
final PlaceStrategy s = strategy();
return s.options().contains(CommonOptions.BAND_LAYERS)
@ -105,6 +110,12 @@ public final class BuildSettings {
return strategy().options().stream().map(Option::key).toList();
}
/** Range of a current-strategy parameter; empty if the strategy does not declare it. */
public Optional<Range> optionRange(final String key) {
return strategy().options().stream().filter(o -> o.key().equals(key)).findFirst()
.map(o -> new Range(o.min(), o.max(), o.step(), strategy().values().get(o)));
}
public void setOption(final String key, final String value) {
final double number;
try {

View file

@ -22,22 +22,17 @@ import dev.loki.satura.interaction.place.support.Cooldown;
import dev.loki.satura.interaction.place.support.SupportFinder;
import dev.loki.satura.util.ActionBarOut;
import dev.loki.satura.util.ChatOut;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import net.minecraft.client.MinecraftClient;
import net.minecraft.util.math.BlockPos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Фасад фичи «авто-билдер»: единственная точка входа для GUI, команд и рендера. */
@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.GuardLogStatement"})
/** Facade of the auto-builder feature: the single entry point for GUI, commands and rendering. */
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.LooseCoupling"})
public final class BuilderFeature implements BuildControl {
private static final Logger LOG = LoggerFactory.getLogger(BuilderFeature.class);
private final Selection current = new Selection();
private final BuildSettings settings;
private final EngineAssembler assembler;
@ -56,7 +51,7 @@ public final class BuilderFeature implements BuildControl {
commands.register(new BuildCommand(this));
}
/** Фасад на клиенте Minecraft; ходок «нет» (мост Baritone подключается через перегрузку). */
/** Facade on the Minecraft client; no walker (the Baritone bridge is attached through an overload). */
public static BuilderFeature create(final CommandRegistry commands, final EventBus events,
final ConfigStore store) {
return create(commands, events, store, new NoWalker());
@ -68,17 +63,16 @@ public final class BuilderFeature implements BuildControl {
final MinecraftClient client = MinecraftClient.getInstance();
final BlockPlacer placer = new BlockPlacer(new SupportFinder(), new Cooldown());
final List<PlaceStrategy> strategies = List.of(new BandStack(placer), new ColumnDrop(placer));
final Profile profile = load(store);
return new BuilderFeature(commands, () -> client.player == null ? null : client.player.getBlockPos(),
new EngineAssembler(client, events, walker, new ChatOut(), new ActionBarOut()),
new BuildSettings(profile, strategies), p -> save(store, p));
new BuildSettings(store.loadOrEmpty(Profile.DEFAULT_NAME), strategies), store::saveQuietly);
}
public Selection selection() {
return current;
}
/** Вызывать каждый клиентский тик. */
/** Call on every client tick. */
public void tick() {
if (engine != null) {
engine.tick();
@ -119,6 +113,24 @@ public final class BuilderFeature implements BuildControl {
return engine == null ? "IDLE" : engine.snapshot().describe();
}
/** Session stage, for GUI labels (the Pause/Resume button). */
public Stage stage() {
return engine == null ? Stage.IDLE : engine.stage();
}
/** Settings for reading from the GUI; changes only via {@link BuildControl} methods. */
public BuildSettings settings() {
return settings;
}
/** Macro key: pause/resume the current build. */
public String togglePause() {
if (engine == null) {
return "билд не запущен";
}
return engine.stage() == Stage.PAUSED ? resume() : pause();
}
@Override
public String setBlock(final String id) {
assembler.blocks().resolve(id);
@ -180,21 +192,4 @@ public final class BuilderFeature implements BuildControl {
persist.accept(settings.toProfile(Profile.DEFAULT_NAME));
return message;
}
private static Profile load(final ConfigStore store) {
try {
return store.load(Profile.DEFAULT_NAME).orElse(Profile.empty(Profile.DEFAULT_NAME));
} catch (IOException | RuntimeException e) {
LOG.warn("[satura] профиль не загружен: {}", e.toString());
return Profile.empty(Profile.DEFAULT_NAME);
}
}
private static void save(final ConfigStore store, final Profile profile) {
try {
store.save(profile);
} catch (IOException e) {
LOG.warn("[satura] профиль не сохранён: {}", e.toString());
}
}
}

View file

@ -22,8 +22,8 @@ import java.util.random.RandomGenerator;
import net.minecraft.block.Block;
import net.minecraft.client.MinecraftClient;
/** Thin assembler of the engine from settings and the Minecraft client. */
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
/** Тонкий сборщик движка из настроек и клиента Minecraft. */
public final class EngineAssembler {
private final MinecraftClient client;

View file

@ -5,8 +5,9 @@ import net.fabricmc.loader.api.FabricLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Мост к Baritone (Aethereal): только рефлексия, любая ошибка отключает мост одной записью в лог. */
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.AvoidCatchingGenericException", "PMD.GuardLogStatement"})
/** Bridge to Baritone (Aethereal): reflection only; any error disables the bridge with a single log entry. */
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.AvoidCatchingGenericException",
"PMD.GuardLogStatement"})
public final class BaritoneBridge implements WalkerPort {
static final String MOD_ID = "baritone-meteor";

View file

@ -5,7 +5,7 @@ import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
/** Кэш рефлексивных дескрипторов Baritone API; создаётся один раз. */
/** Cache of reflective Baritone API descriptors; created once. */
final class BaritoneLink {
private static final String PKG = "baritone.api.";

View file

@ -1,9 +1,9 @@
package dev.loki.satura.feature.builder.baritone;
/** Порт перемещения: движок видит только его, а не Baritone. */
/** Movement port: the engine sees only this, not Baritone. */
public interface WalkerPort {
/** Начать путь к точке (x, z); false — ходок недоступен или команда не принята. */
/** Start a path to point (x, z); false if the walker is unavailable or the command was rejected. */
boolean walkTo(double x, double z);
void cancel();

View file

@ -8,7 +8,7 @@ import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/** {@code .build} — диспетчер подкоманд. */
/** {@code .build} — subcommand dispatcher. */
@SuppressWarnings("PMD.LooseCoupling")
public final class BuildCommand implements Command {

View file

@ -2,7 +2,7 @@ package dev.loki.satura.feature.builder.commands;
import java.util.List;
/** Что команды {@code .build} умеют просить у фичи. Ошибки — исключения с текстом для пользователя. */
/** What the {@code .build} commands can ask of the feature. Errors are exceptions with user-facing text. */
public interface BuildControl {
String start();

View file

@ -2,7 +2,7 @@ package dev.loki.satura.feature.builder.commands;
import java.util.List;
/** Набор подкоманд {@code .build}, привязанных к {@link BuildControl}. */
/** Set of {@code .build} subcommands bound to {@link BuildControl}. */
final class BuildSubs {
private static final int SET_ARGS = 2;

View file

@ -5,11 +5,11 @@ import java.util.function.Function;
import java.util.function.Supplier;
/**
* Подкоманда {@code .build <name>}.
* Subcommand {@code .build <name>}.
*
* @param usage справка по аргументам
* @param options кандидаты для подсказки по токену номер index (после имени)
* @param run выполнить с аргументами после имени, вернуть ответ
* @param usage argument help text
* @param options suggestion candidates for the token at index (after the name)
* @param run execute with the arguments after the name, return the reply
*/
public record SubCommand(String name, String usage, Function<Integer, List<String>> options,
Function<List<String>, String> run) {

View file

@ -8,11 +8,11 @@ import dev.loki.satura.interaction.inventory.HotbarRefill;
import dev.loki.satura.interaction.place.PlaceResult;
import java.util.Optional;
@SuppressWarnings("PMD.CompareObjectsWithEquals")
/**
* Тик билдера: planner → стратегия → пополнение хотбара. Паузы (экран, смерть, смена мира)
* снимаются сами, «нет блоков» — только вручную. Дыры чинятся ремонтными проходами.
* Builder tick: planner → strategy → hotbar refill. Pauses (screen, death, world change)
* lift on their own, "no blocks" only manually. Holes are fixed by repair passes.
*/
@SuppressWarnings("PMD.CompareObjectsWithEquals")
public final class BuildEngine {
public static final int PROGRESS_INTERVAL_TICKS = 20;
@ -37,7 +37,7 @@ public final class BuildEngine {
session.start();
}
/** Ручная пауза: авто-резюм не сработает. */
/** Manual pause: auto-resume will not trigger. */
public void pause() {
if (session.stage() == Stage.BUILD || session.stage() == Stage.PAUSED) {
session.pause("пауза", false);

View file

@ -5,17 +5,17 @@ import java.util.Locale;
import java.util.Optional;
import net.minecraft.util.math.BlockPos;
/** Session state: stage, pause reason, position, counters and statistics (progress comes from ColumnCache). */
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.NullAssignment"})
/** Состояние сессии: этап, причина паузы, позиция, счётчики и статистика (прогресс — из ColumnCache). */
public final class BuildSession {
private static final long MAX_STEP_MS = 250;
private static final double MS_PER_SECOND = 1000.0;
/**
* Снимок статистики.
* Statistics snapshot.
*
* @param holes колонны, которые не удалось достроить
* @param holes columns that could not be completed
*/
public record Snapshot(Stage stage, String reason, int done, int total, double percent, int holes,
int placed, int failed, double blocksPerSecond, Optional<BlockPos> column) {
@ -80,7 +80,7 @@ public final class BuildSession {
column = null;
}
/** Учёт времени: считается только время в BUILD, паузы не входят. */
/** Time accounting: only time in BUILD counts, pauses are excluded. */
public void advance(final long nowMs) {
if (stage == Stage.BUILD && lastTickMs >= 0) {
activeMs += Math.min(nowMs - lastTickMs, MAX_STEP_MS);

View file

@ -5,8 +5,8 @@ import java.util.HashSet;
import java.util.Set;
import net.minecraft.util.math.BlockPos;
/** Holes: columns that could not be completed; skipping, failure counters and repair passes. */
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
/** Дыры: колонны, которые не удалось достроить; пропуск, счётчики отказов и ремонтные проходы. */
public final class RepairTracker {
public static final int MAX_FAILURES = 3;
@ -37,7 +37,7 @@ public final class RepairTracker {
return passes;
}
/** Сбрасывает счётчики, если сменилась колонна или прибавился прогресс. */
/** Resets counters when the column changed or progress was made. */
public void observe(final BlockPos target, final int done) {
if (!target.equals(column) || done != lastDone) {
column = target;
@ -47,12 +47,12 @@ public final class RepairTracker {
}
}
/** Отказ стратегии; true — лимит исчерпан. */
/** Strategy failure; true when the limit is exhausted. */
public boolean failure() {
return ++failures >= MAX_FAILURES;
}
/** Ожидание без прогресса; true — колонна зависла. */
/** Waiting without progress; true when the column is stuck. */
public boolean stall() {
return ++waits >= STALL_TICKS;
}
@ -61,7 +61,7 @@ public final class RepairTracker {
skipped.add(target.withY(0));
}
/** Ремонтный проход: вернуть пропущенные колонны в план; false — дыр нет или проходы кончились. */
/** Repair pass: put skipped columns back into the plan; false when there are no holes or passes ran out. */
public boolean startRepair(final Planner planner) {
if (skipped.isEmpty() || passes >= maxPasses) {
return false;

View file

@ -1,6 +1,6 @@
package dev.loki.satura.feature.builder.engine;
/** Этап сессии. TRANSIT и SUPPLY — точки расширения (переход к области, вылазка за блоками). */
/** Session stage. TRANSIT and SUPPLY are extension points (travel to the area, supply run). */
public enum Stage {
IDLE,
BUILD,

View file

@ -13,10 +13,10 @@ import dev.loki.satura.interaction.place.PlaceStrategy;
import java.util.function.Consumer;
/**
* Все зависимости движка (собираются снаружи, движок ничего не создаёт сам).
* All engine dependencies (assembled outside; the engine creates nothing itself).
*
* @param chat сообщения пользователю
* @param bar строка прогресса (actionBar)
* @param chat messages to the user
* @param bar progress line (actionBar)
*/
@SuppressWarnings("PMD.ExcessiveParameterList")
public record EngineDeps(Planner planner, ColumnCache cache, RepairTracker tracker, PlaceStrategy strategy,

View file

@ -2,12 +2,12 @@ package dev.loki.satura.feature.builder.engine.host;
import java.util.Optional;
/** Состояние игры, влияющее на работу движка; отделяет движок от клиента Minecraft. */
/** Game state affecting the engine; decouples the engine from the Minecraft client. */
public interface GameState {
/** Причина, по которой строить сейчас нельзя (экран, смерть, нет мира); пусто — можно. */
/** Reason why building is not possible now (screen, death, no world); empty when it is possible. */
Optional<String> blockReason();
/** Токен текущего мира: смена токена = смена мира. */
/** Token of the current world: a token change means a world change. */
Object worldToken();
}

View file

@ -8,7 +8,7 @@ import net.minecraft.item.BlockItem;
import net.minecraft.registry.Registries;
import net.minecraft.util.Identifier;
/** Поиск блоков: по ID из реестра или по предмету в основной руке. */
/** Block lookup: by registry ID or by the item in the main hand. */
public final class MinecraftBlocks {
public static final String HAND = "hand";
@ -19,7 +19,7 @@ public final class MinecraftBlocks {
this.client = client;
}
/** Блок по ID ({@code stone} или {@code minecraft:stone}) либо из руки при {@link #HAND}. */
/** Block by ID ({@code stone} or {@code minecraft:stone}) or from the hand for {@link #HAND}. */
public Block resolve(final String id) {
if (HAND.equalsIgnoreCase(id)) {
return fromHand();

View file

@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.engine.host;
import java.util.Optional;
import net.minecraft.client.MinecraftClient;
/** Тонкий адаптер {@link GameState} к клиенту Minecraft. */
/** Thin adapter of {@link GameState} to the Minecraft client. */
public final class MinecraftGameState implements GameState {
private final MinecraftClient client;

View file

@ -1,6 +1,6 @@
package dev.loki.satura.feature.builder.engine.walk;
/** Ходок «нет»: ничего не умеет. */
/** Null walker: does nothing. */
public final class NoWalker implements Walker {
@Override
@ -10,6 +10,6 @@ public final class NoWalker implements Walker {
@Override
public void cancel() {
// нечего отменять
// nothing to cancel
}
}

View file

@ -1,9 +1,9 @@
package dev.loki.satura.feature.builder.engine.walk;
/** Ходок для наземных стратегий (S5/S6); мост к Baritone подключается позже. */
/** Walker for ground strategies (S5/S6); the Baritone bridge is attached later. */
public interface Walker {
/** Начать путь к точке (x, z); false — ходок недоступен или команда не принята. */
/** Start a path to point (x, z); false if the walker is unavailable or the command was rejected. */
boolean walkTo(double x, double z);
void cancel();

View file

@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan;
import java.util.List;
import net.minecraft.util.math.BlockPos;
/** Колонна с ещё не построенными ячейками текущего Y-окна (по возрастанию Y). */
/** Column with not yet built cells of the current Y window (ascending Y). */
public record ColumnTarget(BlockPos column, List<BlockPos> cells) {
public ColumnTarget {

View file

@ -8,7 +8,7 @@ import java.util.Optional;
import java.util.function.Predicate;
import net.minecraft.util.math.BlockPos;
/** Режет область на Y-окна и отдаёт следующую недостроенную колонну по змейке. */
/** Slices the area into Y windows and returns the next unfinished column in snake order. */
public final class Planner {
public static final int MIN_BAND_LAYERS = 1;
@ -31,7 +31,7 @@ public final class Planner {
this.bandFloor = area.min().getY();
}
/** Следующая цель; окно сдвигается вверх, когда текущее достроено. Пусто = всё готово. */
/** Next target; the window moves up once the current one is complete. Empty = all done. */
public Optional<ColumnTarget> next() {
final int top = area.max().getY();
while (bandFloor <= top) {
@ -47,12 +47,12 @@ public final class Planner {
return Optional.empty();
}
/** Нижний Y текущего окна. */
/** Lowest Y of the current window. */
public int bandStart() {
return bandFloor;
}
/** Вернуться к нижнему окну (для ремонтного прохода). */
/** Go back to the lowest window (for a repair pass). */
public void reset() {
bandFloor = area.min().getY();
}

View file

@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape;
import dev.loki.satura.feature.builder.selection.Area;
import net.minecraft.util.math.BlockPos;
/** Сплошной параллелепипед. */
/** Solid cuboid. */
public final class BoxShape implements Shape {
@Override

View file

@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape;
import dev.loki.satura.feature.builder.selection.Area;
import net.minecraft.util.math.BlockPos;
/** Шахматка: чётность x+z относительно угла min области. */
/** Checkerboard: parity of x+z relative to the area's min corner. */
public final class CheckerShape implements Shape {
@Override

View file

@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape;
import dev.loki.satura.feature.builder.selection.Area;
import net.minecraft.util.math.BlockPos;
/** Какие ячейки области нужно строить. */
/** Which cells of the area must be built. */
public interface Shape {
boolean includes(Area area, BlockPos pos);

View file

@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.plan.shape;
import dev.loki.satura.feature.builder.selection.Area;
import net.minecraft.util.math.BlockPos;
/** Только внешний периметр (стены) по всей высоте. */
/** Outer perimeter only (walls) over the full height. */
public final class WallsShape implements Shape {
@Override

View file

@ -2,7 +2,7 @@ package dev.loki.satura.feature.builder.scan;
import net.minecraft.util.math.BlockPos;
/** Источник состояния блоков; отделяет подсчёт от клиента Minecraft. */
/** Source of block states; decouples counting from the Minecraft client. */
public interface BlockProbe {
boolean isFilled(BlockPos pos);

View file

@ -5,7 +5,7 @@ import dev.loki.satura.feature.builder.selection.Area;
import java.util.Arrays;
import net.minecraft.util.math.BlockPos;
/** Инкрементальные счётчики заполненности по колоннам области (вместо полного X*Y*Z-скана). */
/** Incremental per-column fill counters of the area (instead of a full X*Y*Z scan). */
public final class ColumnCache {
private static final double PERCENT_FULL = 100.0;
@ -28,7 +28,7 @@ public final class ColumnCache {
fullRescan();
}
/** Полный пересчёт всей области. */
/** Full recount of the whole area. */
public void fullRescan() {
doneTotal = 0;
requiredTotal = 0;
@ -39,7 +39,7 @@ public final class ColumnCache {
}
}
/** Пересчитывает только колонну изменённого блока; вне области — игнор. */
/** Recounts only the column of the changed block; ignored outside the area. */
public void onBlockChanged(final BlockPos pos) {
if (area.contains(pos)) {
recount(pos.getX(), pos.getZ());
@ -62,12 +62,12 @@ public final class ColumnCache {
return requiredTotal - doneTotal;
}
/** Построено клеток формы в колонне (x, z). */
/** Shape cells already built in column (x, z). */
public int builtIn(final int x, final int z) {
return built[index(x, z)];
}
/** Осталось построить в колонне (x, z). */
/** Cells still to build in column (x, z). */
public int remainingIn(final int x, final int z) {
final int i = index(x, z);
return required[i] - built[i];

View file

@ -5,7 +5,7 @@ import net.minecraft.block.BlockState;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.util.math.BlockPos;
/** Заполнено = не воздух и не заменяемое (трава, вода и т.п.). Мир берётся лениво. */
/** Filled = not air and not replaceable (grass, water, etc.). The world is obtained lazily. */
@SuppressWarnings("PMD.CloseResource")
public final class WorldBlockProbe implements BlockProbe {

View file

@ -4,7 +4,7 @@ import java.util.ArrayList;
import java.util.List;
import net.minecraft.util.math.BlockPos;
/** Прямоугольная область мира (границы включительно). */
/** Rectangular world area (bounds inclusive). */
public record Area(BlockPos min, BlockPos max) {
private static final int EVEN_DIVISOR = 2;
@ -18,9 +18,13 @@ public record Area(BlockPos min, BlockPos max) {
}
public boolean contains(BlockPos p) {
return p.getX() >= min.getX() && p.getX() <= max.getX()
&& p.getY() >= min.getY() && p.getY() <= max.getY()
&& p.getZ() >= min.getZ() && p.getZ() <= max.getZ();
return within(p.getX(), min.getX(), max.getX())
&& within(p.getY(), min.getY(), max.getY())
&& within(p.getZ(), min.getZ(), max.getZ());
}
private static boolean within(int v, int lo, int hi) {
return v >= lo && v <= hi;
}
public long volume() {
@ -39,7 +43,7 @@ public record Area(BlockPos min, BlockPos max) {
return max.getZ() - min.getZ() + 1;
}
/** Колонны на y = min.y: ряды по z, чётные ряды по x вверх, нечётные вниз. */
/** Columns at y = min.y: rows along z, even rows go up along x, odd rows go down. */
public List<BlockPos> columns() {
int sx = sizeX();
int sz = sizeZ();

View file

@ -7,7 +7,7 @@ import java.util.function.Consumer;
import java.util.function.Supplier;
import net.minecraft.util.math.BlockPos;
/** {@code .pos1} / {@code .pos2} — запомнить позицию ног игрока. */
/** {@code .pos1} / {@code .pos2} — remember the player's feet position. */
public final class PosCommand implements Command {
private final String label;

View file

@ -4,7 +4,7 @@ import dev.loki.satura.core.command.Command;
import java.util.List;
import java.util.function.Consumer;
/** {@code .sel clear} — сбросить выделение. */
/** {@code .sel clear} — reset the selection. */
public final class SelCommand implements Command {
private static final String CLEAR = "clear";

View file

@ -3,7 +3,7 @@ package dev.loki.satura.feature.builder.selection;
import java.util.Optional;
import net.minecraft.util.math.BlockPos;
/** Две точки выделения; область существует, когда заданы обе. */
/** Two selection points; the area exists once both are set. */
public final class Selection {
private Optional<BlockPos> first = Optional.empty();

View file

@ -0,0 +1,53 @@
package dev.loki.satura.gui;
import dev.loki.satura.feature.builder.BuilderFeature;
import dev.loki.satura.gui.screen.BuilderScreen;
import java.util.function.Consumer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.util.Identifier;
import org.lwjgl.glfw.GLFW;
/**
* Mod keys (Satura category, configurable in the vanilla Controls screen):
* Right Shift opens/closes the menu, the pause macro uses the key from the settings.
*/
public final class BuilderUi {
private static final Identifier CATEGORY_ID = Identifier.of("satura", "main");
private static final KeyBinding.Category CATEGORY = KeyBinding.Category.create(CATEGORY_ID);
private static final String KEY_MENU = "key.satura.open_menu";
private static final String KEY_TOGGLE = "key.satura.toggle";
private final BuilderFeature builder;
private final Consumer<String> bar;
private final KeyBinding openMenu;
private final KeyBinding toggleBuild;
public BuilderUi(final BuilderFeature builder, final Consumer<String> bar) {
this.builder = builder;
this.bar = bar;
this.openMenu = KeyBindingHelper.registerKeyBinding(
new KeyBinding(KEY_MENU, GLFW.GLFW_KEY_RIGHT_SHIFT, CATEGORY));
this.toggleBuild = KeyBindingHelper.registerKeyBinding(
new KeyBinding(KEY_TOGGLE, GLFW.GLFW_KEY_P, CATEGORY));
}
/** Subscribes to client ticks; call once during initialization. */
public void register() {
ClientTickEvents.END_CLIENT_TICK.register(this::tick);
}
private void tick(final MinecraftClient client) {
while (openMenu.wasPressed()) {
if (client.currentScreen == null) {
client.setScreen(new BuilderScreen(builder, openMenu));
}
}
while (toggleBuild.wasPressed()) {
bar.accept(builder.togglePause());
}
}
}

View file

@ -0,0 +1,201 @@
package dev.loki.satura.gui.screen;
import dev.loki.satura.feature.builder.BuildSettings;
import dev.loki.satura.feature.builder.BuilderFeature;
import dev.loki.satura.feature.builder.engine.Stage;
import dev.loki.satura.feature.builder.plan.Planner;
import dev.loki.satura.gui.widget.CycleButton;
import dev.loki.satura.gui.widget.NumberSlider;
import dev.loki.satura.render.Renderer;
import dev.loki.satura.render.Theme;
import java.util.Optional;
import java.util.function.Supplier;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.client.input.KeyInput;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.text.Text;
import net.minecraft.util.math.BlockPos;
/** Builder screen: selection, start/pause/stop, shape, layers, delay, block, status line. */
@SuppressWarnings("PMD.AvoidCatchingGenericException")
public final class BuilderScreen extends Screen {
private static final int FIXED_ROWS = 5;
private static final int NOTICE_TICKS = 100;
private static final int MAX_BLOCK_LEN = 64;
private static final int POS1 = 1;
private static final int POS2 = 2;
private static final String OPT_DELAY = "delayMs";
private static final String LANG_POS1 = "satura.gui.pos1";
private static final String LANG_POS2 = "satura.gui.pos2";
private static final String LANG_PAUSE = "satura.gui.pause";
private static final String LANG_RESUME = "satura.gui.resume";
private final BuilderFeature builder;
private final KeyBinding openMenu;
private Panel panel;
private ButtonWidget pos1Button;
private ButtonWidget pos2Button;
private ButtonWidget pauseButton;
private TextFieldWidget blockField;
private Text notice = Text.empty();
private int noticeTicks;
public BuilderScreen(final BuilderFeature builder, final KeyBinding openMenu) {
super(Text.translatable("satura.title"));
this.builder = builder;
this.openMenu = openMenu;
}
@Override
protected void init() {
final Optional<BuildSettings.Range> delay = builder.settings().optionRange(OPT_DELAY);
panel = new Panel(width, height, FIXED_ROWS + (delay.isPresent() ? 1 : 0));
final int inner = panel.inner();
final int left = panel.left();
final int half = (inner - Panel.GAP) / 2;
final int third = (inner - Panel.GAP * 2) / 3;
int y = panel.top() + Panel.PAD + Panel.TITLE_H + Panel.GAP;
pos1Button = addDrawableChild(button(LANG_POS1, () -> capture(POS1), left, y, half));
pos2Button = addDrawableChild(button(LANG_POS2, () -> capture(POS2), left + half + Panel.GAP, y, half));
y += Panel.WIDGET_H + Panel.GAP;
addDrawableChild(button("satura.gui.start", () -> run(builder::start), left, y, third));
pauseButton = addDrawableChild(button(LANG_PAUSE,
() -> run(() -> builder.stage() == Stage.PAUSED ? builder.resume() : builder.pause()),
left + third + Panel.GAP, y, third));
addDrawableChild(button("satura.gui.stop", () -> run(builder::stop),
left + (third + Panel.GAP) * 2, y, third));
y += Panel.WIDGET_H + Panel.GAP;
addDrawableChild(new CycleButton(left, y, inner, Panel.WIDGET_H, "satura.gui.shape",
builder.shapeIds(), builder.settings().shapeId(), id -> run(() -> builder.setShape(id))));
y += Panel.WIDGET_H + Panel.GAP;
addDrawableChild(new NumberSlider(left, y, inner, Panel.WIDGET_H,
new NumberSlider.Spec(Planner.MIN_BAND_LAYERS, Planner.MAX_BAND_LAYERS, 1,
builder.settings().layers()),
v -> Text.translatable("satura.gui.layers", formatInt(v)),
v -> run(() -> builder.setLayers((int) Math.round(v)))));
y += Panel.WIDGET_H + Panel.GAP;
if (delay.isPresent()) {
final BuildSettings.Range r = delay.get();
addDrawableChild(new NumberSlider(left, y, inner, Panel.WIDGET_H,
new NumberSlider.Spec(r.min(), r.max(), r.step(), r.value()),
v -> Text.translatable("satura.gui.delay", formatInt(v)),
v -> run(() -> builder.setOption(OPT_DELAY, formatInt(v)))));
y += Panel.WIDGET_H + Panel.GAP;
}
blockField = new TextFieldWidget(textRenderer, left, y, inner, Panel.WIDGET_H,
Text.translatable("satura.gui.block"));
blockField.setMaxLength(MAX_BLOCK_LEN);
blockField.setText(builder.settings().block());
addSelectableChild(blockField);
}
@Override
public void tick() {
if (noticeTicks > 0) {
noticeTicks--;
}
pos1Button.setMessage(posLabel(LANG_POS1, builder.selection().pos1()));
pos2Button.setMessage(posLabel(LANG_POS2, builder.selection().pos2()));
pauseButton.setMessage(Text.translatable(
builder.stage() == Stage.PAUSED ? LANG_RESUME : LANG_PAUSE));
}
@Override
public void render(final DrawContext context, final int mouseX, final int mouseY, final float delta) {
super.render(context, mouseX, mouseY, delta);
context.drawCenteredTextWithShadow(textRenderer, title, width / 2,
panel.top() + Panel.PAD, Theme.TEXT);
final String status = trim(builder.status());
context.drawTextWithShadow(textRenderer, trim(notice.getString()),
panel.left(), panel.statusY(), Theme.ACCENT_HOVER);
context.drawTextWithShadow(textRenderer, status,
panel.left(), panel.statusY() + Panel.LINE_H, Theme.TEXT_MUTED);
}
@Override
public void renderBackground(final DrawContext context, final int mouseX, final int mouseY,
final float delta) {
super.renderBackground(context, mouseX, mouseY, delta);
panel.paint(Renderer.shared());
}
@Override
public boolean keyPressed(final KeyInput input) {
if (openMenu.matchesKey(input)) {
close();
return true;
}
if (blockField.isFocused() && input.isEnter()) {
commitBlock();
return true;
}
return super.keyPressed(input);
}
@Override
public void removed() {
commitBlock();
super.removed();
}
@Override
public boolean shouldPause() {
return false;
}
private void run(final Supplier<String> action) {
try {
showNotice(action.get());
} catch (RuntimeException e) {
showNotice(e.getMessage() == null ? "ошибка" : e.getMessage());
}
}
private void showNotice(final String text) {
notice = Text.literal(text);
noticeTicks = NOTICE_TICKS;
}
private void commitBlock() {
final String id = blockField.getText().strip();
if (!id.isEmpty() && !id.equals(builder.settings().block())) {
run(() -> builder.setBlock(id));
}
}
private void capture(final int which) {
if (client.player == null) {
showNotice("зайди в мир");
return;
}
final BlockPos pos = client.player.getBlockPos();
if (which == POS1) {
builder.selection().setPos1(pos);
} else {
builder.selection().setPos2(pos);
}
showNotice("Pos" + which + ": " + pos.toShortString());
}
private Text posLabel(final String key, final Optional<BlockPos> pos) {
return Text.translatable(key, pos.<String>map(BlockPos::toShortString).orElse("-"));
}
private static String formatInt(final double value) {
return String.valueOf(Math.round(value));
}
private String trim(final String text) {
return textRenderer.trimToWidth(text, Panel.WIDTH - Panel.PAD * 2);
}
private static ButtonWidget button(final String key, final Runnable action,
final int x, final int y, final int w) {
return ButtonWidget.builder(Text.translatable(key), b -> action.run())
.dimensions(x, y, w, Panel.WIDGET_H).build();
}
}

View file

@ -0,0 +1,62 @@
package dev.loki.satura.gui.screen;
import dev.loki.satura.render.Renderer;
import dev.loki.satura.render.Theme;
import dev.loki.satura.render.geom.Bounds;
/** Geometry and drawing of the screen's dark panel (blur, backdrop, outline). */
final class Panel {
static final int WIDTH = 240;
static final int PAD = 10;
static final int WIDGET_H = 20;
static final int GAP = 4;
static final int TITLE_H = 14;
static final int LINE_H = 11;
static final int STATUS_ROWS = 2;
private static final float BLUR_STRENGTH = 1.0f;
private final int screenW;
private final int screenH;
private final int rows;
Panel(final int screenW, final int screenH, final int rows) {
this.screenW = screenW;
this.screenH = screenH;
this.rows = rows;
}
/** Left edge of the content (padding already applied). */
int left() {
return (screenW - WIDTH) / 2 + PAD;
}
int inner() {
return WIDTH - PAD * 2;
}
int top() {
return (screenH - height()) / 2;
}
int height() {
return PAD + TITLE_H + GAP + rows * (WIDGET_H + GAP) + GAP + STATUS_ROWS * LINE_H + PAD;
}
/** Y of the first status line (at the bottom of the panel). */
int statusY() {
return top() + height() - PAD - STATUS_ROWS * LINE_H;
}
Bounds bounds() {
return new Bounds((screenW - WIDTH) / 2f, top(), WIDTH, height());
}
/** Draws the panel backdrop; called after the vanilla background, before the widgets. */
void paint(final Renderer renderer) {
final Bounds b = bounds();
renderer.blur(b, Theme.RADIUS, BLUR_STRENGTH);
renderer.rect(b, Theme.RADIUS, Theme.PANEL);
renderer.outline(b, Theme.RADIUS, Theme.BORDER_WIDTH, Theme.BORDER);
}
}

View file

@ -0,0 +1,49 @@
package dev.loki.satura.gui.widget;
import java.util.List;
import java.util.function.Consumer;
import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.client.input.AbstractInput;
/**
* Cycle button: a click steps through the values and hands the chosen one to the owner.
* The label is a translatable string with {@code %s} in place of the value. Rendering is vanilla
* (inherited from ButtonWidget.Text).
*/
public final class CycleButton extends ButtonWidget.Text {
private final List<String> values;
private final String labelKey;
private final Consumer<String> onChange;
private int index;
public CycleButton(final int x, final int y, final int width, final int height,
final String labelKey, final List<String> values,
final String initial, final Consumer<String> onChange) {
super(x, y, width, height, net.minecraft.text.Text.empty(), b -> { }, DEFAULT_NARRATION_SUPPLIER);
if (values.isEmpty()) {
throw new IllegalArgumentException("cycle without values: " + labelKey);
}
this.values = List.copyOf(values);
this.labelKey = labelKey;
this.onChange = onChange;
this.index = Math.max(0, this.values.indexOf(initial));
refresh();
}
/** Currently selected value. */
public String value() {
return values.get(index);
}
@Override
public void onPress(final AbstractInput input) {
index = (index + 1) % values.size();
refresh();
onChange.accept(values.get(index));
}
private void refresh() {
setMessage(net.minecraft.text.Text.translatable(labelKey, values.get(index)));
}
}

View file

@ -0,0 +1,56 @@
package dev.loki.satura.gui.widget;
import java.util.function.Consumer;
import java.util.function.DoubleFunction;
import net.minecraft.client.gui.widget.SliderWidget;
import net.minecraft.text.Text;
/** Number slider (int/float) with a step; range, label and receiver are set by the owner. */
public final class NumberSlider extends SliderWidget {
private static final double NO_STEP = 0.0;
/** Slider range: bounds, step (0 = continuous) and the initial value. */
public record Spec(double min, double max, double step, double initial) {
}
private final double min;
private final double max;
private final double step;
private final DoubleFunction<Text> label;
private final Consumer<Double> onChange;
public NumberSlider(final int x, final int y, final int width, final int height, final Spec spec,
final DoubleFunction<Text> label, final Consumer<Double> onChange) {
super(x, y, width, height, Text.empty(), normalized(spec.min(), spec.max(), spec.initial()));
this.min = spec.min();
this.max = spec.max();
this.step = spec.step();
this.label = label;
this.onChange = onChange;
updateMessage();
}
/** Current value in range units (step applied). */
public double current() {
final double raw = min + (max - min) * value;
return step == NO_STEP ? raw : Math.round(raw / step) * step;
}
@Override
protected void updateMessage() {
setMessage(label.apply(current()));
}
@Override
protected void applyValue() {
onChange.accept(current());
}
private static double normalized(final double min, final double max, final double value) {
if (max <= min) {
return 0.0;
}
return Math.clamp((value - min) / (max - min), 0.0, 1.0);
}
}

View file

@ -3,12 +3,12 @@ package dev.loki.satura.interaction.click;
import java.util.random.RandomGenerator;
/**
* Настройки темпа кликов по контейнерам.
* Pacing settings for container clicks.
*
* @param minDelayMs базовая пауза между кликами
* @param jitter доля случайного разброса паузы (0.3 = плюс-минус 30%)
* @param confirmTimeoutMs сколько ждать подтверждения клика до повтора
* @param maxAttempts сколько раз кликнуть, прежде чем сдаться
* @param minDelayMs base pause between clicks
* @param jitter random spread share of the pause (0.3 = plus or minus 30%)
* @param confirmTimeoutMs how long to wait for click confirmation before retrying
* @param maxAttempts how many times to click before giving up
*/
public record ClickConfig(long minDelayMs, double jitter, long confirmTimeoutMs, int maxAttempts) {
@ -30,7 +30,7 @@ public record ClickConfig(long minDelayMs, double jitter, long confirmTimeoutMs,
return new ClickConfig(delayMs, jitter, confirmTimeoutMs, maxAttempts);
}
/** Следующая пауза: minDelayMs * (1 +- jitter), равномерно. */
/** Next pause: minDelayMs * (1 +- jitter), uniformly distributed. */
public long nextDelay(RandomGenerator random) {
double factor = 1 + jitter * (2 * random.nextDouble() - 1);
return Math.round(minDelayMs * factor);

View file

@ -5,8 +5,8 @@ import java.util.Deque;
import java.util.random.RandomGenerator;
/**
* Единая очередь контейнерных кликов: пауза с джиттером между кликами и подтверждение
* каждого клика по синхронизации слотов (таймаут, повтор). Тикается владельцем раз в тик.
* Single queue of container clicks: jittered pause between clicks and confirmation
* of every click via slot sync (timeout, retry). Ticked by the owner once per tick.
*/
public final class ClickScheduler {
@ -42,7 +42,7 @@ public final class ClickScheduler {
return queue.size() + (current == null ? 0 : 1);
}
/** Отложить следующий клик минимум на delayMs (пауза «человека» после открытия экрана). */
/** Delay the next click by at least delayMs (a "human" pause after a screen opens). */
public void delayNext(long delayMs) {
nextClickAt = Math.max(nextClickAt, clock.nowMillis() + delayMs);
}

View file

@ -4,15 +4,15 @@ import java.util.function.BooleanSupplier;
import java.util.function.Consumer;
/**
* Один клик по контейнеру.
* A single container click.
*
* @param click действие клика (вызов clickSlot)
* @param confirmed true, когда результат клика виден в слотах (синхронизация пришла)
* @param onDone итог задачи
* @param click click action (the clickSlot call)
* @param confirmed true when the click result is visible in the slots (sync arrived)
* @param onDone task outcome
*/
public record ClickTask(Runnable click, BooleanSupplier confirmed, Consumer<Outcome> onDone) {
/** Итог задачи. */
/** Task outcome. */
public enum Outcome { CONFIRMED, FAILED }
public static ClickTask of(Runnable click, BooleanSupplier confirmed) {

View file

@ -1,6 +1,6 @@
package dev.loki.satura.interaction.click;
/** Источник времени; подменяется в тестах. */
/** Time source; replaced in tests. */
@FunctionalInterface
public interface Clock {

View file

@ -4,15 +4,15 @@ import dev.loki.satura.interaction.click.ClickScheduler;
import dev.loki.satura.interaction.click.ClickTask;
/**
* Пополнение хотбара: когда в выбранном слоте осталось не больше порога, самый полный стак
* из инвентаря меняется с пустеющим слотом хотбара (SWAP) через общий ClickScheduler.
* Hotbar refill: when the selected slot holds no more than the threshold, the fullest stack
* from the inventory is swapped with the emptying hotbar slot (SWAP) via the shared ClickScheduler.
*/
public final class HotbarRefill {
/** Порог: слот с таким или меньшим числом блоков считается пустым. */
/** Threshold: a slot with this many blocks or fewer counts as empty. */
public static final int LOW = 2;
/** Состояние пополнения. */
/** Refill state. */
public enum State { READY, REFILLING, EMPTY }
private final InventoryView inventory;
@ -30,7 +30,7 @@ public final class HotbarRefill {
this.planner = new RefillPlanner(low);
}
/** Один тик логики; сам планировщик кликов тикает владелец. */
/** One logic tick; the owner ticks the click scheduler itself. */
public State tick() {
if (swapPending) {
return State.REFILLING;

View file

@ -1,18 +1,18 @@
package dev.loki.satura.interaction.inventory;
/** Вид на инвентарь игрока относительно целевого предмета. Слоты 0-8 хотбар, 9-35 инвентарь. */
/** View of the player's inventory relative to the target item. Slots 0-8 hotbar, 9-35 inventory. */
public interface InventoryView {
int SLOTS = 36;
int HOTBAR_SIZE = 9;
/** Сколько целевых предметов в слоте (0, если слот пуст или там другое). */
/** How many target items are in the slot (0 if empty or holds something else). */
int count(int slot);
int selectedSlot();
void select(int slot);
/** Клик SWAP: стак из слота инвентаря src меняется местами со слотом хотбара hotbarSlot. */
/** SWAP click: the stack from inventory slot src is swapped with hotbar slot hotbarSlot. */
void swapToHotbar(int src, int hotbarSlot);
}

View file

@ -7,7 +7,7 @@ import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemStack;
import net.minecraft.screen.slot.SlotActionType;
/** Тонкий адаптер к клиенту Minecraft: инвентарь игрока относительно одного блока. */
/** Thin adapter to the Minecraft client: the player's inventory relative to one block. */
public final class MinecraftInventoryView implements InventoryView {
private final MinecraftClient client;

View file

@ -1,13 +1,13 @@
package dev.loki.satura.interaction.inventory;
/** Чистый выбор действия по заполненности слотов. */
/** Pure action choice based on slot fill levels. */
public final class RefillPlanner {
/** Тип решения. */
/** Decision type. */
public enum Kind { READY, SELECT, SWAP, EMPTY }
/**
* Решение: SELECT - выбрать хотбар-слот from; SWAP - обменять from (инвентарь) на to (хотбар).
* Decision: SELECT - select hotbar slot from; SWAP - swap from (inventory) with to (hotbar).
*/
public record Decision(Kind kind, int from, int to) {

View file

@ -1,6 +1,6 @@
package dev.loki.satura.interaction.movement;
/** Чистая математика углов (градусы, система Minecraft). */
/** Pure angle math (degrees, Minecraft convention). */
public final class Angles {
private static final float FULL_TURN = 360f;
@ -33,7 +33,7 @@ public final class Angles {
return Math.max(-limit, Math.min(limit, value));
}
/** Шаг от current к target не больше maxStep по кратчайшей дуге. */
/** Step from current towards target of at most maxStep along the shortest arc. */
public static float approachYaw(float current, float target, float maxStep) {
return current + clamp(wrap(target - current), maxStep);
}

View file

@ -2,7 +2,7 @@ package dev.loki.satura.interaction.movement;
import dev.loki.satura.interaction.movement.io.PlayerPose;
/** Управление взглядом: плавный доворот с клампом °/тик и мгновенный взгляд вниз. */
/** Look control: smooth turn clamped in degrees/tick and an instant look down. */
public final class LookController {
public static final float MAX_YAW_STEP = 25f;
@ -16,7 +16,7 @@ public final class LookController {
this.pose = pose;
}
/** Доворот к точке за один тик; true, когда взгляд уже на цели. */
/** Turn towards a point in one tick; true when already looking at the target. */
public boolean lookAtSmooth(double x, double y, double z) {
double dx = x - pose.x();
double dz = z - pose.z();
@ -34,7 +34,7 @@ public final class LookController {
return false;
}
/** Мгновенно смотреть строго вниз (для стратегий столбика/пола). */
/** Instantly look straight down (for pillar/floor strategies). */
public void lookDown() {
pose.setPitch(DOWN_PITCH);
}

View file

@ -3,7 +3,7 @@ package dev.loki.satura.interaction.movement;
import dev.loki.satura.interaction.movement.io.KeyInput;
import dev.loki.satura.interaction.movement.io.PlayerPose;
/** Ходьба к точке фейк-клавишами: кламп поворота, прыжок на препятствии, сайдстеп при застревании. */
/** Walking to a point with fake keys: turn clamp, jump at obstacles, sidestep when stuck. */
public final class MovementController {
public static final float MAX_TURN_STEP = 35f;
@ -42,7 +42,7 @@ public final class MovementController {
keys.setJump(true);
}
/** Один тик ходьбы к (x, z); true, когда дошли (клавиши отпущены). */
/** One walking tick towards (x, z); true on arrival (keys released). */
public boolean walkTo(double x, double z) {
double dx = x - pose.x();
double dz = z - pose.z();

View file

@ -1,6 +1,6 @@
package dev.loki.satura.interaction.movement.io;
/** Фейковые клавиши движения. */
/** Fake movement keys. */
public interface KeyInput {
void setForward(boolean pressed);

View file

@ -2,7 +2,7 @@ package dev.loki.satura.interaction.movement.io;
import net.minecraft.client.MinecraftClient;
/** Адаптер клавиш к настройкам клиента Minecraft. */
/** Adapter of keys to the Minecraft client options. */
public final class MinecraftKeyInput implements KeyInput {
private final MinecraftClient client;

View file

@ -3,7 +3,7 @@ package dev.loki.satura.interaction.movement.io;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
/** Адаптер позы к ClientPlayerEntity; без игрока (мир не загружен) работает как заглушка. */
/** Adapter of the pose to ClientPlayerEntity; without a player (world not loaded) acts as a stub. */
public final class MinecraftPlayerPose implements PlayerPose {
private final MinecraftClient client;

View file

@ -1,6 +1,6 @@
package dev.loki.satura.interaction.movement.io;
/** Положение и взгляд игрока (градусы по Minecraft: yaw 0 = юг, pitch + вниз). */
/** Player position and look direction (Minecraft degrees: yaw 0 = south, positive pitch = down). */
public interface PlayerPose {
double x();

View file

@ -4,29 +4,29 @@ import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
/** Всё, чем стратегия касается игры. Узкий интерфейс, чтобы логику можно было тестировать фейком. */
/** Everything a strategy touches in the game. A narrow interface so the logic can be tested with a fake. */
public interface PlaceContext {
/** Позиция ног игрока. */
/** Player's feet position. */
Vec3d feetPos();
/** Позиция глаз игрока. */
/** Player's eye position. */
Vec3d eyePos();
/** Годится ли блок как опора. */
/** Whether the block is usable as a support. */
boolean isSolid(BlockPos pos);
/** Клик ПКМ по блоку; true - клиент принял действие. */
/** Right-click on a block; true if the client accepted the action. */
boolean interact(BlockHitResult hit);
void swing();
/** Мгновенно взгляд строго вниз. */
/** Instantly look straight down. */
void lookDown();
void setVelocity(double x, double y, double z);
/** Включить полёт, если он разрешён. */
/** Enable flight if it is allowed. */
void enableFlight();
long nowMs();

View file

@ -1,11 +1,11 @@
package dev.loki.satura.interaction.place;
/** Итог одного тика стратегии. */
/** Outcome of a single strategy tick. */
public enum PlaceResult {
/** Блок поставлен в этом тике. */
/** A block was placed this tick. */
PLACED,
/** Ничего не делали: летим, кулдаун, ждём ответ сервера. */
/** Did nothing: flying, cooldown, waiting for the server reply. */
WAIT,
/** Цель сейчас не поставить (нет опоры / вне досягаемости): движок вправе пересчитать цель. */
/** The target cannot be placed now (no support / out of reach): the engine may pick another target. */
FAILED
}

View file

@ -5,19 +5,19 @@ import dev.loki.satura.interaction.place.option.Option;
import dev.loki.satura.interaction.place.option.OptionValues;
import java.util.List;
/** Способ ставить блоки в колонну. Движок вызывает {@link #tick} каждый тик, пока колонна не достроена. */
/** A way to place blocks into a column. The engine calls {@link #tick} every tick until the column is complete. */
public interface PlaceStrategy {
/** Стабильный ключ для конфига. */
/** Stable key for the config. */
String id();
/** Название для GUI. */
/** Display name for the GUI. */
String label();
/** Объявление параметров; GUI рисует их генерично. */
/** Parameter declarations; the GUI renders them generically. */
List<Option> options();
/** Текущие значения параметров (живые - GUI может менять). */
/** Current parameter values (live: the GUI may change them). */
OptionValues values();
PlaceResult tick(PlaceContext ctx, ColumnTarget target);

View file

@ -6,8 +6,8 @@ import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3d;
/**
* Один клик: ставим блок в {@code target}, кликая по грани {@code face} опоры {@code support}.
* {@code standPos} - откуда кликать (может быть {@code null}, если стратегии это не важно).
* One click: place a block at {@code target} by clicking face {@code face} of the support {@code support}.
* {@code standPos} is where to click from (may be {@code null} if the strategy does not care).
*/
public record Placement(BlockPos target, BlockPos support, Direction face, Vec3d hitVec, Vec3d standPos) {

View file

@ -8,7 +8,7 @@ import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
/** Реальный игрок и мир за интерфейсом {@link PlaceContext}. Клиент передаётся в конструктор. */
/** The real player and world behind {@link PlaceContext}. The client is passed to the constructor. */
public final class MinecraftPlaceContext implements PlaceContext {
private static final float PITCH_DOWN = 90.0F;

View file

@ -2,7 +2,7 @@ package dev.loki.satura.interaction.place.option;
import dev.loki.satura.feature.builder.plan.Planner;
/** Параметры, общие для нескольких стратегий (значения по yatwinkle BaseBuilder). */
/** Parameters shared by several strategies (values follow yatwinkle BaseBuilder). */
@SuppressWarnings("PMD.DataClass")
public final class CommonOptions {

View file

@ -1,6 +1,6 @@
package dev.loki.satura.interaction.place.option;
/** Описание параметра стратегии. Для BOOL: min=0, max=1. */
/** Description of a strategy parameter. For BOOL: min=0, max=1. */
public record Option(String key, String label, OptionType type,
double min, double max, double step, double def) {

View file

@ -1,6 +1,6 @@
package dev.loki.satura.interaction.place.option;
/** Вид виджета для параметра. */
/** Widget kind for a parameter. */
public enum OptionType {
INT,
DOUBLE,

View file

@ -4,7 +4,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** Значения параметров стратегии по ключам; всегда в пределах диапазона опции. */
/** Strategy parameter values by key; always within the option's range. */
@SuppressWarnings("PMD.LooseCoupling")
public final class OptionValues {
@ -29,7 +29,7 @@ public final class OptionValues {
return get(option) >= 1.0;
}
/** Записать значение по ключу; false - такого параметра нет. */
/** Set the value by key; false if there is no such parameter. */
public boolean set(final String key, final double value) {
final Option option = known.get(key);
if (option == null) {

View file

@ -10,7 +10,7 @@ import dev.loki.satura.interaction.place.option.OptionValues;
import dev.loki.satura.interaction.place.support.BlockPlacer;
import java.util.List;
/** S2: за один визит колонны ставим 1..3 слоя подряд снизу вверх (yatwinkle bandLayers). */
/** S2: place 1..3 layers in a row from bottom to top per column visit (yatwinkle bandLayers). */
public final class BandStack implements PlaceStrategy {
private static final List<Option> DECLARED = List.of(

View file

@ -10,7 +10,7 @@ import dev.loki.satura.interaction.place.option.OptionValues;
import dev.loki.satura.interaction.place.support.BlockPlacer;
import java.util.List;
/** S1: полёт над слоем, pitch=90, по одному слою за визит колонны (yatwinkle без bandLayers). */
/** S1: fly above the layer, pitch=90, one layer per column visit (yatwinkle without bandLayers). */
public final class ColumnDrop implements PlaceStrategy {
private static final List<Option> DECLARED = List.of(

View file

@ -12,12 +12,12 @@ import java.util.function.IntSupplier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
/** Ядро yatwinkle-стиля: висим над колонной, смотрим вниз, ставим слои band снизу вверх. */
/** Core of the yatwinkle style: hover above the column, look down, place band layers bottom to top. */
final class ColumnPlacing {
/** Запас: глаза 1.62 + ~0.08 (yatwinkle {@code layerY + reach - 1.7}). */
/** Margin: eyes 1.62 + ~0.08 (yatwinkle {@code layerY + reach - 1.7}). */
static final double EYE_MARGIN = 1.7;
/** Столько тиков не повторяем клик в ту же ячейку, пока сервер не ответил. */
/** For this many ticks we do not repeat a click on the same cell until the server replies. */
static final int PENDING_TTL_TICKS = 2;
private static final double FEET_EPS = 0.1;
private static final double CENTER = 0.5;
@ -68,7 +68,7 @@ final class ColumnPlacing {
return result;
}
/** Ячейки окна: от самой нижней до {@code layers} слоёв вверх (cells - по возрастанию Y). */
/** Window cells: from the lowest up to {@code layers} layers (cells are in ascending Y). */
static List<BlockPos> band(final List<BlockPos> cells, final int layers) {
final List<BlockPos> band = new ArrayList<>();
if (cells.isEmpty()) {

View file

@ -3,7 +3,7 @@ package dev.loki.satura.interaction.place.strategy;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
/** Скорость полёта setVelocity как в yatwinkle BaseBuilder.flyTo: прямой вектор к точке, без физики клавиш. */
/** setVelocity flight speed as in yatwinkle BaseBuilder.flyTo: straight vector to the point, no key physics. */
final class FlightControl {
private static final double ARRIVE_EPS = 0.05;
@ -26,7 +26,7 @@ final class FlightControl {
return new Vec3d(vx, vy, vz);
}
/** Высота полёта: min(bandTop+hover, layerY+reach-1.7), но не ниже верха слоя (чтобы не стоять в блоке). */
/** Flight height: min(bandTop+hover, layerY+reach-1.7), but not below the layer top (no standing in a block). */
static double height(final int layerY, final int bandTop, final double hover,
final double reach, final double eyeMargin) {
final double capped = Math.min(bandTop + hover, layerY + reach - eyeMargin);

View file

@ -6,7 +6,7 @@ import dev.loki.satura.interaction.place.Placement;
import java.util.Optional;
import net.minecraft.util.math.BlockPos;
/** Общая часть всех стратегий: кулдаун, поиск опоры, клик и взмах руки. */
/** Common part of all strategies: cooldown, support lookup, click and hand swing. */
public final class BlockPlacer {
private final SupportFinder finder;
@ -17,7 +17,7 @@ public final class BlockPlacer {
this.cooldown = cooldown;
}
/** WAIT - кулдаун; FAILED - нет опоры в досягаемости или клиент отклонил клик; иначе PLACED. */
/** WAIT - cooldown; FAILED - no support in reach or the client rejected the click; otherwise PLACED. */
public PlaceResult place(final PlaceContext ctx, final BlockPos target,
final double reach, final long delayMs) {
final long now = ctx.nowMs();

View file

@ -1,6 +1,6 @@
package dev.loki.satura.interaction.place.support;
/** Кулдаун между постановками в миллисекундах. */
/** Cooldown between placements in milliseconds. */
public final class Cooldown {
private long lastMs = Long.MIN_VALUE / 2;

View file

@ -7,10 +7,10 @@ import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3d;
/** Выбор опоры: сначала снизу, затем остальные 5 направлений (кроме низа). */
/** Support selection: below first, then the other 5 directions. */
public final class SupportFinder {
/** Клик по боковой грани чуть ниже верха блока, чтобы не попасть в стык. */
/** Click a side face slightly below the block top so as not to hit the seam. */
public static final double SIDE_CLICK_Y = 0.94;
private static final double HALF = 0.5;
@ -30,7 +30,7 @@ public final class SupportFinder {
return Optional.empty();
}
/** Порядок осмотра соседей цели: DOWN, затем UP и 4 стороны. */
/** Order in which target neighbours are inspected: DOWN, then UP and the 4 sides. */
static Direction[] searchOrder() {
return new Direction[] {
Direction.DOWN, Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST, Direction.UP

View file

@ -14,6 +14,7 @@ import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ChatInputSuggestor.class)
@SuppressWarnings({"PMD.AvoidDollarSigns", "PMD.MethodNamingConventions"})
public abstract class ChatInputSuggestorMixin {
@Shadow @Final TextFieldWidget textField;

View file

@ -10,7 +10,8 @@ import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(ChatScreen.class)
@SuppressWarnings("PMD.AbstractClassWithoutAbstractMethod")
@SuppressWarnings({"PMD.AbstractClassWithoutAbstractMethod", "PMD.AvoidDollarSigns",
"PMD.MethodNamingConventions"})
public abstract class ChatScreenMixin {
@Inject(method = "sendMessage", at = @At("HEAD"), cancellable = true)

View file

@ -4,7 +4,7 @@ import dev.loki.satura.render.geom.Bounds;
import dev.loki.satura.render.msdf.MsdfFont;
import dev.loki.satura.render.msdf.MsdfFonts;
/** Тестовая отрисовка возможностей рендера; только при -Dsatura.renderDebug=true. */
/** Test drawing of render capabilities; only with -Dsatura.renderDebug=true. */
public final class RenderDebug {
private static final String FLAG = "satura.renderDebug";

View file

@ -4,8 +4,8 @@ import java.util.ArrayList;
import java.util.List;
/**
* Очереди отрисовки "поверх GUI": постоянные оверлеи и разовые задачи на кадр.
* Вызывается из GameRenderer после того, как ванильный GUI уже нарисован.
* Draw queues "above the GUI": persistent overlays and one-off per-frame tasks.
* Called from GameRenderer after the vanilla GUI has already been drawn.
*/
public final class RenderHooks {

View file

@ -18,9 +18,9 @@ import net.minecraft.client.MinecraftClient;
import net.minecraft.util.Identifier;
/**
* Фасад рендера: скруглённые прямоугольники, обводка, свечение, тень, блюр, текстуры, MSDF-текст, scissor.
* Координаты — GUI (как у DrawContext), цвета — ARGB int. Рисует прямо в главный фреймбуфер,
* поэтому для отображения поверх ванильного GUI вызывать из {@link #onFrame} / {@link #defer}.
* Render facade: rounded rectangles, outline, glow, shadow, blur, textures, MSDF text, scissor.
* Coordinates are GUI (like DrawContext), colors are ARGB int. Draws straight into the main framebuffer,
* so to render above the vanilla GUI call it from {@link #onFrame} / {@link #defer}.
*/
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
public final class Renderer {
@ -119,12 +119,12 @@ public final class Renderer {
scissor.pop();
}
/** Постоянный оверлей: вызывается каждый кадр поверх всего GUI. */
/** Persistent overlay: called every frame above the whole GUI. */
public void onFrame(Runnable overlay) {
hooks.addOverlay(overlay);
}
/** Разовая задача: выполнится в конце текущего кадра поверх GUI (для вызова из HUD/Screen). */
/** One-off task: runs at the end of the current frame above the GUI (for calls from HUD/Screen). */
public void defer(Runnable task) {
hooks.defer(task);
}

View file

@ -1,6 +1,6 @@
package dev.loki.satura.render;
/** Палитра и размеры оформления (минимализм): цвета ARGB, радиусы в GUI-единицах. */
/** Palette and styling sizes (minimalism): ARGB colors, radii in GUI units. */
@SuppressWarnings("PMD.DataClass")
public final class Theme {

View file

@ -5,7 +5,7 @@ import dev.loki.satura.render.gpu.UniformData;
import java.nio.ByteBuffer;
import org.joml.Matrix4f;
/** Запись юниформа BlurData для промежуточных проходов и финального вывода. */
/** Writes the BlurData uniform for intermediate passes and the final output. */
final class BlurData {
static final int SIZE = 256;

View file

@ -32,8 +32,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Блюр фона под прямоугольником: копия кадра, даунсэмпл, N проходов размытия, вывод со скруглением.
* Размытие пересчитывается раз в кадр, остальные вызовы переиспользуют результат.
* Background blur under a rectangle: frame copy, downsample, N blur passes, output with rounding.
* The blur is recomputed once per frame; other calls reuse the result.
*/
@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.InvalidLogMessageFormat", "PMD.CloseResource"})
public final class BlurPipeline {

View file

@ -5,7 +5,7 @@ import com.mojang.blaze3d.textures.GpuTexture;
import com.mojang.blaze3d.textures.GpuTextureView;
import com.mojang.blaze3d.textures.TextureFormat;
/** Текстуры блюра: копия кадра полного размера и два буфера половинного размера (ping-pong). */
/** Blur textures: a full-size frame copy and two half-size buffers (ping-pong). */
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.NullAssignment"})
final class BlurTargets {
@ -19,7 +19,7 @@ final class BlurTargets {
private int width;
private int height;
/** Пересоздаёт текстуры при смене размера; true — если пересоздали. */
/** Recreates the textures on a size change; true if they were recreated. */
boolean ensure(int fbWidth, int fbHeight) {
if (copy != null && fbWidth == width && fbHeight == height) {
return false;

View file

@ -1,6 +1,6 @@
package dev.loki.satura.render.color;
/** Утилиты над цветами в формате ARGB (int). */
/** Utilities over ARGB (int) colors. */
public final class Colors {
public static final int WHITE = 0xFFFFFFFF;
@ -14,7 +14,7 @@ public final class Colors {
private Colors() {
}
/** Приводит набор из 0..9 цветов к сетке 9 точек (недостающие повторяют последний). */
/** Expands a set of 0..9 colors to a 9-point grid (missing ones repeat the last). */
public static int[] toGrid(int... colors) {
int[] grid = new int[GRID_SIZE];
for (int i = 0; i < GRID_SIZE; i++) {

View file

@ -1,6 +1,6 @@
package dev.loki.satura.render.geom;
/** Прямоугольник в GUI-координатах (как у DrawContext). */
/** Rectangle in GUI coordinates (like DrawContext). */
public record Bounds(float x, float y, float width, float height) {
public float right() {

View file

@ -1,6 +1,6 @@
package dev.loki.satura.render.geom;
/** Радиусы скругления углов. */
/** Corner rounding radii. */
public record Radii(float topLeft, float topRight, float bottomRight, float bottomLeft) {
public static final Radii NONE = all(0f);

View file

@ -2,7 +2,7 @@ package dev.loki.satura.render.gpu;
import com.mojang.blaze3d.systems.RenderPass;
/** Источник текущей области отсечения для проходов рендера. */
/** Source of the current scissor area for render passes. */
@FunctionalInterface
public interface ScissorSource {

View file

@ -22,8 +22,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Шейдерный проход без вершинных буферов: шейдеры satura:{name}_vertex/_fragment,
* N юниформ-буферов, необязательный Sampler0. Создаётся лениво при первой отрисовке.
* Shader pass without vertex buffers: shaders satura:{name}_vertex/_fragment,
* N uniform buffers, optional Sampler0. Created lazily on the first draw.
*/
@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.InvalidLogMessageFormat", "PMD.NullAssignment"})
public final class ShaderPass {
@ -33,7 +33,7 @@ public final class ShaderPass {
private static final String SAMPLER = "Sampler0";
private static final int VERTICES_PER_QUAD = 6;
/** Именованный юниформ-буфер заданного размера. */
/** Named uniform buffer of the given size. */
public record Slot(String name, int size) {
}

View file

@ -4,7 +4,7 @@ import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.joml.Matrix4f;
/** Запись std140-юниформов: матрица, vec4, ARGB-цвет. Буфер переиспользуется между кадрами. */
/** Writes std140 uniforms: matrix, vec4, ARGB color. The buffer is reused between frames. */
public final class UniformData {
private static final float CHANNEL_MAX = 255f;

View file

@ -4,7 +4,7 @@ import net.minecraft.client.MinecraftClient;
import net.minecraft.client.util.Window;
import org.joml.Matrix4f;
/** GUI-координаты окна: те же, что у DrawContext (с учётом масштаба GUI). */
/** Window GUI coordinates: the same as DrawContext (taking GUI scale into account). */
public final class Viewport {
private static final float DEPTH_NEAR = -1000f;
@ -22,7 +22,7 @@ public final class Viewport {
return window().getFramebufferHeight();
}
/** Пикселей фреймбуфера в одной GUI-единице. */
/** Framebuffer pixels per GUI unit. */
public float pixelScale() {
return window().getFramebufferWidth() / (float) Math.max(1, width());
}

View file

@ -4,18 +4,18 @@ import com.mojang.blaze3d.textures.GpuTexture;
import com.mojang.blaze3d.textures.GpuTextureView;
import java.util.Map;
/** MSDF-шрифт: метрики, глифы и текстура-атлас. Размеры глифов — в em. */
/** MSDF font: metrics, glyphs and the atlas texture. Glyph sizes are in em. */
@SuppressWarnings("PMD.LooseCoupling")
public record MsdfFont(String name, Metrics metrics, Map<Integer, Glyph> glyphs,
GpuTexture texture, GpuTextureView view) {
private static final int FALLBACK_CODEPOINT = '?';
/** Общие метрики шрифта. */
/** Common font metrics. */
public record Metrics(float emSize, float lineHeight, float ascender, float descender, float pxRange) {
}
/** Один глиф: смещения/размеры в em, UV в атласе. */
/** A single glyph: offsets/sizes in em, UV in the atlas. */
public record Glyph(float advance, float width, float height, float bearingX, float bearingY,
float u0, float v0, float u1, float v1) {

Some files were not shown because too many files have changed in this diff Show more