EnergyStorage

EnergyStorage

A lightweight and extensible energy API for Hytale that provides a unified system to store, transfer, and manage energy across blocks, machines, and mods.

1.2 тысяча загрузок
Обновлён 10 дней назад

Описание

EnergyStorage API

Хранение энергии API - это легкая библиотека, ориентированная на разработчиков для модов Hytale. Он обеспечивает полнофункциональную, основанную на компонентах энергетическую систему, которую другие моды могут легко интегрировать в свои машины, блоки, объекты или пользовательские системы геймплея. Этот мод делает не Добавьте игровой контент самостоятельно. Вместо этого он раскрывает чистый и расширяемый API, построенный вокруг официального Hytale. компонент системы ECSОбеспечение максимальной совместимости и стабильности между модами. Используйте эту библиотеку, когда вы хотите дать своим машинам возможность хранить, получать или извлекать энергию предсказуемым и стандартизированным способом.


Особенности

  • ЭнергохранилищеБлоккомпонент Использование официального сервиса Hytale компонент системы ECS
  • Компонент EnergyStorageEntity Использование официального сервиса Hytale компонент системы ECS
  • Автоматическая сериализация и валидация
  • Конфигурируемая емкость, максимальный прием и максимальный коэффициент извлечения
  • Безопасная и детерминированная логика передачи энергии
  • Разработан как общая зависимость для других модов

Установить как depedencie

репозитории {
Дровосекhttps://cursemaven.com")
?

зависимости {
CompileOnly (libs.jetbrains.annotations)
CompileOnly (libs.jspecify)

RuntimeOnly (libs.bettermodlist)

//-реализация("curse.maven:EnergyStorage-1429355:7515395")
// или
//implementation(files("libs/EnergyStorage-1.0.5.jar"))
?

Примеры использования

1. Добавление энергетического компонента в блок-сущность

  • энергосберегающий - Количество энергии, первоначально хранящейся в машине при ее создании.
  • Max Energy - Максимальная мощность, которую может выдержать машина.
  • Макс получает - Максимальное количество энергии, которое машина может получить за клеща (устанавливается до 0, чтобы отключить прием).
  • MaxExtract - Максимальное количество энергии, которое машина может извлечь на клеща (устанавливается до 0, чтобы отключить извлечение).

Добавление компонента

"Компоненты": {
«Энергосберегающий компонент»: {
«Энергетика»: 0,
"МаксЭнерго": 80000,
"MaxReceive": 0,
«Максэкстракт»: 1000
?
?

SolarGenerator.json

{
"Свойства перевода": {
"Имя": "items.Solar_Generator.name"
?
"Уровень предмета": 10,
"MaxStack": 100,
"Icon": "Icons/ItemsGenerated/Solar_Generator_Block.png",
"Категории": [
"Блоки.Рокс"
]
«PlayerAnimationsId»: «Блок»,
"Сет": "Солнечный генератор",
"BlockType":
"Государство":
"Материал": "Солид",
"DrawType": "Куб",
"Группа": "Камень",
"Флаги":
"VariantRotation": "NESW",
"Собрание": {
"Прорыв": {
"GatherType": "Рокс",
«ItemId»: «SolarGenerator»
?
?
"Взаимодействия":
"Использовать": {
"Взаимодействия": []
?
?
«BlockEntity»: {
"Компоненты": {
«Энергосберегающий компонент»: {
«Энергетика»: 0,
"МаксЭнерго": 80000,
"MaxReceive": 0,
«Максэкстракт»: 1000
?
"examplemod:solar_generator": {
"ProductionPerTick": 80,
Требуется дневной свет: правда
?
?
?
"BlockParticleSetId": "Камень",
"Цвет частиц": "#737055",
"BlockSoundSetId": "Камень",
"Алиас":
"камень",
"Стоун00"
]
"BlockBreakingDecalId": "Breaking_Decals_Rock",
"Текстуры":
{
"Вверх": "BlockTextures/SolarGenerator/top.png",
"Side": "BlockTextures/SolarGenerator/side.png",
«Down»: «BlockTextures/SolarGenerator/bottom.png»
?
]
?
"Ресурсные типы":
{
"Ид": "Рок"
?
{
Название: Rock_Stone
?
]
"Тэги": {
"Тип":
"Рок"
]
?
"ItemSoundSetId": "ISS_Blocks_Stone"
?

Пример Mod.java

пакет dev.zkiller.exemplemod;

Импорт com.hypixel.hytale.component.ComponentType
Импорт com.hypixel.hytale.logger.HytaleLogger
импортировать com.hypixel.hytale.server.core.plugin.JavaPlugin;
импорт com.hypixel.hytale.server.core.plugin.JavaPluginInit;
импортировать com.hypixel.hytale.server.core.universe.world.storage.ChunkStore;
импортировать dev.zkiller.examplemod.generators.solar.SolarGeneratorComponent;
импортировать dev.zkiller.examplemod.generators.solar.SolarGeneratorSystem;

Импорт javax.annotation.Nonnull

Пример общественного класса Мод расширяется Java-плагин {

частный статический экземпляр ExampleMod;
Частный статический финал HytaleLogger LOGGER = HytaleLogger.forEnclosingClass();

Private ComponentType<ChunkStore, Компонент SolarGenerator> солнечный генератор тип;

Публичный ПримерMod(@Nonnull JavaPluginInit init)
Super(init);
Пример = это;
?

@Override
Защищенная установка void() {

Этот.solarGeneratorType = этот.getChunkStoreRegistry().registerComponent()
SolarGeneratorComponent.class
"examplemod:solar_generator"
SolarGeneratorComonent.CODEC
);

Этот.getChunkStoreRegistry(.registerSystem)
SolarGeneratorSystem (этот.solarGeneratorType)
);

LOGGER.atInfo(.log)("Успешно зарегистрирован компонент и система Солнечного генератора!");
?

Публичный статический ПримерMod getInstance()
возвратный экземпляр;
?

Публичный компонент Type<ChunkStore, SolarGeneratorComponent> getSolarGeneratorType()
Возвращение Солнца генератор тип;
?
?

SolarGeneratorComonent.java

пакет dev.zkiller.examplemod.generators.solar;

импортировать com.hypixel.hytale.codec.Codec;
импортировать com.hypixel.hytale.codec.KeyedCodec;
импортировать com.hypixel.hytale.codec.builder.BuilderCodec;
Импорт com.hypixel.hytale.codec.validation. валидаторы;
импортировать com.hypixel.hytale.component.Component;
импортировать com.hypixel.hytale.server.core.universe.world.storage.ChunkStore;

Импорт javax.annotation.Nonnull
Импорт javax.annotation Нулевой;

Публичный финальный класс SolarGeneratorComponent Компонент <ChunkStore> {

Долгое общественное производство PerTick = 80;

@Nonnull
Публичный статический финальный BuilderCodec<SolarGeneratorComponent> Кодек =
BuilderCodec.builder (SolarGeneratorComponent.class, SolarGeneratorComponent::new)

.append(новый KeyedCodec<>("ProductionPerTick", Codec.LONG),
(c, v) -> c. производство PerTick = v,
c -> c.productionPerTick
.addValidator(Validators.GreaterThanOrEqual(0L))
.documentation («Энергия, производимая на клеща»).
.add()
.build();

Общественный компонент SolarGenerator()

публичный компонент SolarGeneratorComponent (другой компонент SolarGenerator)
Это. productionPerTick = other.productionPerTick;
?

@Nullable
@Override
Публичный компонент <ChunkStore> клон() {
возврат нового компонента SolarGenerator (это);
?
?

SolarGeneratorSystem.java

пакет dev.zkiller.exemplemod.generators.solar;

импортировать com.hypixel.hytale.component.*;
Импорт com.hypixel.hytale.component.query. запрос;
Импорт com.hypixel.hytale.component.system.tick.EntityTickingSystem
импортировать com.hypixel.hytale.server.core.universe.world.storage.ChunkStore;
импортировать dev.zkiller.energystorage.components.EnergyStorageBlockComponent;

Импорт javax.annotation.Nonnull

Общественный финальный класс SolarGeneratorSystem расширяет EntityTickingSystem {

Частный финальный компонент Тип <Чунк-Стор, Компонент SolarGenerator> солнечный тип;

Public SolarGeneratorSystem (ComponentType<ChunkStore, SolarGeneratorComponent> SolarType)
солнце Тип = солнечный тип;
?

@Nonnull
@Override
Публичный запрос <ChunkStore> getQuery() {
// Le système ne tick que les entités ayant un SolarGeneratorComponent + EnergyStorageBlockComponent
возврат Query.and (EnergyStorageBlockComponent.getComponentType(), this.solarType);
?

@Override
публичный пустой клещ
Поплавок dt,
Инт индекс,
@Nonnull ArchetypeChunk<ChunkStore> кусок,
@Nonnull Store<ChunkStore> магазин,
@Nonnull CommandBuffer<ChunkStore> смд
) {
SolarGeneratorComponent Solar = chunk.getComponent (index, this.solarType);
EnergyStorageBlockComponent Energy = chunk.getComponent (индекс, EnergyStorageBlockComponent.getComponentType());
если (солнечный == нуль | | энергия == нуль) возврат;

Длительное производство = солнечная энергия. производство PerTick;

Длинная вставка = energy.receiveEnergyInternal (производится, ложно);

// Консоль Debug
System.out.println[Пример Мод] Вставлено: "+ вставлено +
FE | Хранится: + energy.getEnergyStored() +
"/" + energy.getMaxEnergyStored());
?
?

?️ Для кого это?

Эта библиотека предназначена исключительно для разработчиков, которые хотят:

  • Постройте машины, которые хранят или передают энергию
  • Создание систем автоматизации
  • Внедрить генераторы, батареи, кабели или энергетические сети
  • Общий энергетический стандарт для нескольких модов

Если вашему моду нужна энергия, этот API дает вам чистую, стабильную основу.

Показать оригинальное описание (English)

📦 EnergyStorage API

Energy Storage API is a lightweight developer‑focused library for Hytale mods. It provides a fully‑featured, component‑based energy system that other mods can easily integrate into their machines, blocks, entities, or custom gameplay systems. This mod does not add gameplay content by itself. Instead, it exposes a clean and extensible API built around Hytale’s official Component systems ECS, ensuring maximum compatibility and stability across mods. Use this library when you want to give your machines the ability to store, receive, or extract energy in a predictable and standardized way.


⚡ Features

  • EnergyStorageBlockComponent using Hytale’s official Component systems ECS
  • EnergyStorageEntityComponent using Hytale’s official Component systems ECS
  • Automatic serialization and validation
  • Configurable capacity, max receive, and max extract rates
  • Safe and deterministic energy transfer logic
  • Designed as a shared dependency for other mods

🧩 Install as depedencie

repositories {
    maven ("https://cursemaven.com")
}

dependencies {
    compileOnly(libs.jetbrains.annotations)
    compileOnly(libs.jspecify)

    runtimeOnly(libs.bettermodlist)

    //implementation("curse.maven:EnergyStorage-1429355:7515395")
    // or
    //implementation(files("libs/EnergyStorage-1.0.5.jar"))
}

🧩 Usage Examples

1. Adding an Energy Component to a Block Entity

  • EnergyStored - The amount of energy initially stored in the machine when it is created.
  • MaxEnergy - The maximum energy capacity the machine can hold.
  • MaxReceive - - The maximum amount of energy the machine can receive per tick (set to 0 to disable receiving).
  • MaxExtract - - The maximum amount of energy the machine can extract per tick (set to 0 to disable extracting).

Adding Component

"Components": {
    "EnergyStorageComponent": {
    "EnergyStored": 0,
    "MaxEnergy": 80000,
    "MaxReceive": 0,
    "MaxExtract": 1000
  }
}

SolarGenerator.json

{
  "TranslationProperties": {
    "Name": "items.Solar_Generator.name"
  },
  "ItemLevel": 10,
  "MaxStack": 100,
  "Icon": "Icons/ItemsGenerated/Solar_Generator_Block.png",
  "Categories": [
    "Blocks.Rocks"
  ],
  "PlayerAnimationsId": "Block",
  "Set": "SolarGenerator",
  "BlockType": {
    "State": {},
    "Material": "Solid",
    "DrawType": "Cube",
    "Group": "Stone",
    "Flags": {},
    "VariantRotation": "NESW",
    "Gathering": {
      "Breaking": {
        "GatherType": "Rocks",
        "ItemId": "SolarGenerator"
      }
    },
    "Interactions":{
      "Use": {
        "Interactions": []
      }
    },
    "BlockEntity": {
      "Components": {
        "EnergyStorageComponent": {
          "EnergyStored": 0,
          "MaxEnergy": 80000,
          "MaxReceive": 0,
          "MaxExtract": 1000
        },
        "examplemod:solar_generator": {
          "ProductionPerTick": 80,
          "RequiresDaylight": true
        }
      }
    },
    "BlockParticleSetId": "Stone",
    "ParticleColor": "#737055",
    "BlockSoundSetId": "Stone",
    "Aliases": [
      "stone",
      "stone00"
    ],
    "BlockBreakingDecalId": "Breaking_Decals_Rock",
    "Textures": [
      {
        "Up": "BlockTextures/SolarGenerator/top.png",
        "Side": "BlockTextures/SolarGenerator/side.png",
        "Down": "BlockTextures/SolarGenerator/bottom.png"
      }
    ]
  },
  "ResourceTypes": [
    {
      "Id": "Rock"
    },
    {
      "Id": "Rock_Stone"
    }
  ],
  "Tags": {
    "Type": [
      "Rock"
    ]
  },
  "ItemSoundSetId": "ISS_Blocks_Stone"
}

ExampleMod.java

package dev.zkiller.exemplemod;

import com.hypixel.hytale.component.ComponentType;
import com.hypixel.hytale.logger.HytaleLogger;
import com.hypixel.hytale.server.core.plugin.JavaPlugin;
import com.hypixel.hytale.server.core.plugin.JavaPluginInit;
import com.hypixel.hytale.server.core.universe.world.storage.ChunkStore;
import dev.zkiller.examplemod.generators.solar.SolarGeneratorComponent;
import dev.zkiller.examplemod.generators.solar.SolarGeneratorSystem;

import javax.annotation.Nonnull;

public class ExampleMod extends JavaPlugin {

    private static ExampleMod instance;
    private static final HytaleLogger LOGGER = HytaleLogger.forEnclosingClass();

    private ComponentType<ChunkStore, SolarGeneratorComponent> solarGeneratorType;

    public ExampleMod(@Nonnull JavaPluginInit init) {
        super(init);
        instance = this;
    }

    @Override
    protected void setup() {

        this.solarGeneratorType = this.getChunkStoreRegistry().registerComponent(
                SolarGeneratorComponent.class,
                "examplemod:solar_generator",
                SolarGeneratorComponent.CODEC
        );

        this.getChunkStoreRegistry().registerSystem(
                new SolarGeneratorSystem(this.solarGeneratorType)
        );

        LOGGER.atInfo().log("Solar Generator component and system registered successfully!");
    }

    public static ExampleMod getInstance() {
        return instance;
    }

    public ComponentType<ChunkStore, SolarGeneratorComponent> getSolarGeneratorType() {
        return solarGeneratorType;
    }
}

SolarGeneratorComponent.java

package dev.zkiller.examplemod.generators.solar;

import com.hypixel.hytale.codec.Codec;
import com.hypixel.hytale.codec.KeyedCodec;
import com.hypixel.hytale.codec.builder.BuilderCodec;
import com.hypixel.hytale.codec.validation.Validators;
import com.hypixel.hytale.component.Component;
import com.hypixel.hytale.server.core.universe.world.storage.ChunkStore;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public final class SolarGeneratorComponent implements Component<ChunkStore> {

    public long productionPerTick = 80;

    @Nonnull
    public static final BuilderCodec<SolarGeneratorComponent> CODEC =
            BuilderCodec.builder(SolarGeneratorComponent.class, SolarGeneratorComponent::new)

                    .append(new KeyedCodec<>("ProductionPerTick", Codec.LONG),
                            (c, v) -> c.productionPerTick = v,
                            c -> c.productionPerTick)
                    .addValidator(Validators.greaterThanOrEqual(0L))
                    .documentation("Energy produced per tick.")
                    .add()
                    .build();

    public SolarGeneratorComponent() {}

    public SolarGeneratorComponent(SolarGeneratorComponent other) {
        this.productionPerTick = other.productionPerTick;
    }

    @Nullable
    @Override
    public Component<ChunkStore> clone() {
        return new SolarGeneratorComponent(this);
    }
}

SolarGeneratorSystem.java

package dev.zkiller.exemplemod.generators.solar;

import com.hypixel.hytale.component.*;
import com.hypixel.hytale.component.query.Query;
import com.hypixel.hytale.component.system.tick.EntityTickingSystem;
import com.hypixel.hytale.server.core.universe.world.storage.ChunkStore;
import dev.zkiller.energystorage.components.EnergyStorageBlockComponent;

import javax.annotation.Nonnull;

public final class SolarGeneratorSystem extends EntityTickingSystem<ChunkStore> {

    private final ComponentType<ChunkStore, SolarGeneratorComponent> solarType;

    public SolarGeneratorSystem(ComponentType<ChunkStore, SolarGeneratorComponent> solarType) {
        this.solarType = solarType;
    }

    @Nonnull
    @Override
    public Query<ChunkStore> getQuery() {
        // Le système ne tick que les entités ayant un SolarGeneratorComponent + EnergyStorageBlockComponent
        return Query.and(EnergyStorageBlockComponent.getComponentType(), this.solarType);
    }

    @Override
    public void tick(
            float dt,
            int index,
            @Nonnull ArchetypeChunk<ChunkStore> chunk,
            @Nonnull Store<ChunkStore> store,
            @Nonnull CommandBuffer<ChunkStore> cmd
    ) {
        SolarGeneratorComponent solar = chunk.getComponent(index, this.solarType);
        EnergyStorageBlockComponent energy = chunk.getComponent(index, EnergyStorageBlockComponent.getComponentType());
        if (solar == null || energy == null) return;

        long produced = solar.productionPerTick;

        long inserted = energy.receiveEnergyInternal(produced, false);

        // Console Debug
        System.out.println("[ExampleMod] Inserted: " + inserted +
                " FE | Stored: " + energy.getEnergyStored() +
                "/" + energy.getMaxEnergyStored());
    }
}

🛠️ Who Is This For?

This library is intended exclusively for developers who want to:

  • Build machines that store or transfer energy
  • Create automation systems
  • Implement generators, batteries, cables, or power networks
  • Share a common energy standard across multiple mod

If your mod needs energy, this API gives you a clean, stable foundation.

Последние версии

EnergyStorage-1.0.5.jar

Early Access 24.01.2026 31.5 КБ
Скачать

EnergyStorage-1.0.4.jar

Early Access 17.01.2026 29.1 КБ
Скачать

EnergyStorage-1.0.3.jar

Early Access 17.01.2026 30.4 КБ
Скачать

EnergyStorage-1.0.2.jar

Early Access 15.01.2026 6.1 КБ
Скачать

EnergyStorage-1.0.1.jar

Early Access 14.01.2026 5.7 КБ
Скачать