Developer API
On this page(14)
SnGens exposes a public developer API for other plugins: custom Bukkit events, a read-only
query service, and two extension points, one for sell multipliers and one for generator bonuses. The API lives in the com.sn.sngens.api
package inside the plugin jar. There is no separate artifact.
Only com.sn.sngens.api is a stable, kept contract. Everything else in the jar is obfuscated
and internal. Do not call it.
Getting the jar
-
Download the latest release jar.
-
Install it into your local Maven repository:
mvn install:install-file -Dfile=SnGens-<version>.jar -DgroupId=com.sn \ -DartifactId=SnGens -Dversion=<version> -Dpackaging=jar -
Depend on it with
providedscope. Never shade it.
<dependency>
<groupId>com.sn</groupId>
<artifactId>SnGens</artifactId>
<version><!-- the version you installed --></version>
<scope>provided</scope>
</dependency>Gradle users can drop the jar in libs/ and use compileOnly files("libs/SnGens-<version>.jar")
instead.
Quick start
Declare the dependency in your plugin.yml:
depend: [SnGens] # or softdepend if the integration is optionalResolve the API when you need it:
import com.sn.sngens.api.SnGensAPI;
import com.sn.sngens.api.SnGensProvider;
SnGensAPI api = SnGensProvider.get();
if (api != null) {
int placed = api.getPlacedCount(player.getUniqueId());
}SnGensProvider.isAvailable() is a boolean shortcut for the same check. The facade is
registered with the Bukkit services manager at the very end of SnGens' startup, so with
depend it is ready in your own onEnable.
Resolve the reference when you need it. Do not cache it across a SnGens reload.
Master switch
API events can be disabled by the server owner with api-events.enabled: false in
config.yml. No event is then dispatched at all, and cancellable events behave as if nothing
cancelled them, so gameplay is unaffected. The query service and the extension point stay
available either way.
Events
All events live in com.sn.sngens.api.event, extend org.bukkit.event.Event and carry the
usual static getHandlerList().
Cancellable events fire before the action. Cancelling aborts it cleanly, with no money taken and no items lost.
| Event | Fired when | Cancel effect |
|---|---|---|
GeneratorPlaceEvent | A player places a generator | The generator is not placed |
HopperPlaceEvent | A player places an infinite hopper | The hopper is not placed |
GeneratorUpgradeEvent | A player upgrades one generator | No upgrade, no charge |
GeneratorBulkUpgradeEvent | A bulk upgrade runs from the menu | The whole batch is aborted |
GeneratorBreakEvent | A generator is broken or removed | The generator stays |
GeneratorStackChangeEvent | A player deposits, withdraws or buys generators in a stack, or picks up one generator of a stack | The stack, inventory and balance stay as they were |
GeneratorRepairEvent | A player repairs the broken generators of a block: a click, the stack menu, or once per block from /gens repair | It stays broken and is not charged |
GeneratorSellEvent | Any sale, before the deposit | No payout, no items consumed |
CollectorSellEvent | A collector's contents are sold | The contents stay stored |
CollectorUpgradeEvent | A player buys the next level of a collector | No level, no charge |
SellwandPreUseEvent | A sellwand is swung at a block | Nothing is sold, no use is spent |
BuildWandUseEvent | A build wand preview is confirmed | Nothing is built, no charge, no use spent |
UpgradeWandUseEvent | An upgrade wand is swung, free or radius | No upgrade, no charge, no use spent |
AdminWandSelectEvent | The admin region wand sets a corner | The previous selection is kept |
SlotTransferEvent | Stored generator slots are about to move between two players | The transfer is refused, nothing moves |
SellMultiplierTransferEvent | Part of a stored sell multiplier is about to move between two players | The transfer is refused, nothing moves |
The two transfer events carry UUIDs, because either player may be offline. They fire on the sender's region thread while the sender is online, and on the global thread otherwise.
Notification events fire after the fact. They cannot be cancelled.
| Event | Fired when | Thread |
|---|---|---|
SellwandUseEvent | A sellwand swing completed | Main or region thread |
GeneratorCorruptEvent | Generators of a block broke in a corruption wave, once per block | Main or region thread |
GeneratorUpgradedEvent | A generator upgrade committed and its charge was accepted | Main or region thread |
GeneratorDropsSoldEvent | A sale of generator drops was committed and paid | Main or region thread |
ServerEventStartEvent | A server wide event started | Delivered on the main thread |
ServerEventEndEvent | A server wide event ended | Delivered on the main thread |
TopUpdateEvent | The leaderboard finished recomputing | Delivered on the main thread |
RefundIssuedEvent | Generators were added to a player's vault | Delivered on the main thread |
StorageRefundIssuedEvent | Collectors or hoppers were added to a player's vault | Delivered on the main thread |
The last five originate off the main thread inside SnGens, but the plugin hops through its Folia aware scheduler before dispatching, so your listener always runs on the main thread and can touch the Bukkit API freely.
For a pickup, RefundIssuedEvent fires once the vault write is confirmed. A pickup aborted
by a failed write leaves the generators placed and fires nothing.
RefundIssuedEvent stays generator only. When an island kick, leave, ban or disband also
removes the player's collectors and hoppers, those arrive as a separate
StorageRefundIssuedEvent, so a generator listener never sees an empty id list.
Collectors keep their bought level in the vault. StorageRefundIssuedEvent#getCollectorLevels()
breaks getCollectorCount() down by level, as a map of level to count in ascending order. An
admin pickup of an offline owner's collectors fires the same event.
Listen like any Bukkit event:
@EventHandler
public void onUpgrade(GeneratorUpgradeEvent event) {
Player player = event.getPlayer();
getLogger().info(player.getName()
+ " upgrades " + event.getGenerator().generatorId()
+ " into " + event.getToGeneratorId()
+ " for " + event.getCost());
}@EventHandler
public void onHopperPlace(HopperPlaceEvent event) {
if (event.getLocation().getWorld().getName().equals("pvp_arena")) {
event.setCancelled(true);
event.getPlayer().sendMessage("You cannot place hoppers here.");
}
}GeneratorSellEvent#getContext() returns a SellContext with the item count, the base value,
the effective multiplier, the final amount and the source of the sale
(PLAYER_INVENTORY, SELLWAND, COLLECTOR, HOPPER, OTHER).
@EventHandler
public void onSell(GeneratorSellEvent event) {
SellContext c = event.getContext();
if (c.source() == SellSource.SELLWAND && c.finalAmount() > 1_000_000) {
event.setCancelled(true);
}
}GeneratorUpgradeEvent fires once per hop. A multi level upgrade through the API fires all of
them before anything is charged. An event that you did not cancel is a proposal, not a commit.
A later hop can still be cancelled, and the upgrade can still be refused after the events. No
compensating event follows, so spend a quota against a state you can verify afterwards.
CollectorUpgradeEvent fires after the balance check and before any economy is charged. A level
N collector absorbs a (2N-1)x(2N-1) chunk square around its own chunk.
| Getter | Returns |
|---|---|
getPlayer() | The player buying the level, who also pays |
getCollectorId() | The collector's unique id |
getOwner() | The collector's owner |
getLocation() | A copy of the collector block location |
getFromLevel() | The current level |
getToLevel() | The level being bought |
getCosts() | Economy id to amount, in config order. Empty for a free level |
The ids in getCosts() come from economies in SnGens' config.yml, and vault is the Vault
economy. The player can be an admin upgrading someone else's collector, so compare getOwner().
Like GeneratorUpgradeEvent, an event you did not cancel is a proposal, not a commit. An
economy can still refuse the charge, or the collector can be removed first. No compensating
event follows. The event is delivered on the global region thread, which is the main thread on
Paper.
@EventHandler
public void onCollectorUpgrade(CollectorUpgradeEvent event) {
if (event.getToLevel() > 2 && !event.getPlayer().hasPermission("myserver.bigcollectors")) {
event.setCancelled(true); // nothing is charged
event.getPlayer().sendMessage("Level 3 collectors are for ranked players.");
}
}Wand swings are vetoed through their own event, not through the generator ones. A build wand
places its whole line in one batch and an upgrade wand upgrades its whole square in one batch,
so neither fires GeneratorPlaceEvent, GeneratorUpgradeEvent or
GeneratorBulkUpgradeEvent. Cancel BuildWandUseEvent or UpgradeWandUseEvent to stop them.
@EventHandler
public void onBuildWand(BuildWandUseEvent event) {
for (Location target : event.getTargets()) {
if (myRegionPlugin.isProtected(target)) {
event.setCancelled(true);
event.getPlayer().sendMessage("You cannot build into that region.");
return;
}
}
}SellwandPreUseEvent fires the moment the wand is swung, before SnGens looks at what the
clicked block holds, so it vetoes the swing whatever the target is: a chest, a collector, an
infinite hopper or a display shop. SellwandUseEvent is its notification counterpart and only
fires once a sale actually went through.
GeneratorDropsSoldEvent tells you what a sale was made of. It fires once per committed sale, after
the money is deposited, on the same thread as GeneratorSellEvent. It covers /sell, hand sell,
sellwand swings on containers, collectors, infinite hoppers and display shops. A collector's sell all
and its single entry sale fire it too.
It never fires for a sale that GeneratorSellEvent or CollectorSellEvent cancelled. It also stays
silent for a sale that sold nothing, and while api-events.enabled is false.
| Getter | Returns |
|---|---|
getPlayer() | The player who made the sale |
getSource() | The SellSource of the sale |
getSoldByGenerator() | An unmodifiable map of generator id to items sold |
getUnresolvedItems() | Items sold that no loaded generator defines |
getTotalItems() | Every item sold, resolved and unresolved |
The map keys are the ids written in generators.yml. When two generators define the same drop
item, the one with the lowest tier in the upgrade chain owns it.
@EventHandler
public void onDropsSold(GeneratorDropsSoldEvent event) {
long points = event.getUnresolvedItems();
for (Map.Entry<String, Long> sold : event.getSoldByGenerator().entrySet()) {
int tier = api.getGeneratorType(sold.getKey()).map(GeneratorTypeView::tier).orElse(1);
points += sold.getValue() * Math.max(1, tier);
}
event.getPlayer().sendMessage("+" + points + " points for " + event.getTotalItems() + " items");
}Event payloads are read-only. To influence the money a sale pays, use the extension point below instead of looking for setters.
Query service
Synchronous methods read in-memory state. Call them on the main thread.
| Method | Returns | Notes |
|---|---|---|
getPlayerProfile(UUID) | PlayerGensProfile | Placed count, max slots, stored multiplier, hide-stats flag, online flag |
getPlacedCount(UUID) | int | Generators currently placed |
getMaxSlots(UUID) | int | Slot allowance. Permission bonuses only count while the player is online |
getEffectiveSellMultiplier(Player) | double | The fully resolved multiplier for a sale |
getSlotBreakdown(UUID) | Optional<SlotBreakdown> | Slots split into base, permission and stored, plus the transferable amount |
getSellMultiplierBreakdown(UUID) | Optional<SellMultiplierBreakdown> | Stored multiplier, its transfer floor and the transferable part |
getGeneratorBonuses(UUID) | GensBonus | Speed, tier, drop and lucky bonuses the next generator run applies, including providers and global bonuses. EMPTY when offline. Safe from any thread |
getGeneratorAt(Location) | Optional<GeneratorView> | Empty when the block is not a generator |
isGenerator(Location) | boolean | Cheap existence check |
getGeneratorTypes() | List<GeneratorTypeView> | Every type in generators.yml: the upgrade chain first, in order, then any type outside it |
getGeneratorType(String) | Optional<GeneratorTypeView> | One type by its id |
getGeneratorId(ItemStack) | Optional<String> | The type a generator item is. Empty for any other item |
createGeneratorItem(String, int) | Optional<ItemStack> | The item /gens give hands out. Empty for an unknown id or an amount below 1 |
getPlacedHopperCount(UUID) | int | Infinite hoppers placed by that owner |
getTotalPlacedHoppers() | int | Infinite hoppers placed server wide |
getOwnerHoppers(UUID) | List<HopperView> | Every hopper that owner placed, with its contents |
getIslandHoppers(UUID) | List<HopperView> | The same for every member of that player's island |
getPlacedCollectorCount(UUID) | int | Collectors placed by that owner |
getTotalPlacedCollectors() | int | Collectors placed server wide |
getOwnerCollectors(UUID) | List<CollectorView> | Every collector that owner placed, with its contents and level |
getIslandCollectors(UUID) | List<CollectorView> | The same for every member of that player's island |
getActiveServerEvent() | Optional<ServerEventView> | Empty between events |
getTopSnapshot() | List<TopEntryView> | The last computed leaderboard |
getRank(UUID) | OptionalInt | Rank of a player or an island |
getValue(UUID) | OptionalDouble | Value of a player or an island |
isIslandModeAvailable() | boolean | Whether the skyblock integration is active |
getWand(ItemStack) | Optional<WandView> | Empty when the item is not a SnGens wand |
createSellwand(double, int) | Optional<ItemStack> | Multiplier and uses. Pass -1 uses for unlimited |
createBuildWand(int, int) | Optional<ItemStack> | Line length and uses |
createFreeUpgradeWand(int) | Optional<ItemStack> | Uses |
createRadiusUpgradeWand(int, int) | Optional<ItemStack> | Radius and uses. The radius must be odd |
createAdminWand() | ItemStack | The staff region selector |
getUpgradePath(String) | List<UpgradeStepView> | Every tier reachable after that type, in chain order |
quoteUpgrade(String, int) | Optional<UpgradeQuote> | Price of climbing N tiers. Capped at the end of the chain |
quoteUpgradeTo(String, String) | Optional<UpgradeQuote> | Price of reaching an exact tier. Empty when it is not ahead |
getApiVersion() | String | The API contract version |
api.getGeneratorAt(block.getLocation())
.ifPresent(view -> player.sendMessage("Generator: " + view.displayName()));
for (HopperView hopper : api.getOwnerHoppers(player.getUniqueId())) {
for (StoredItemView stored : hopper.contents()) {
// stored.item() is a decoded ItemStack, ready for a menu icon
menu.addIcon(stored.item(), stored.amount(), stored.totalValue());
}
}Hoppers and collectors are held in memory in full, so these listings need no database read and no chunk scanning. You can call them straight from a menu open.
Asynchronous methods hit the database, so they also see generators in unloaded chunks.
| Method | Returns | Notes |
|---|---|---|
getIslandGeneratorStats(UUID) | CompletableFuture<IslandGeneratorStats> | Folds in every island member, or falls back to the single owner |
getOwnerGeneratorCount(UUID) | CompletableFuture<Long> | Total generators of one owner |
getOwnerGeneratorValue(UUID) | CompletableFuture<Double> | Total value of one owner |
getOwnerGenerators(UUID) | CompletableFuture<List<GeneratorView>> | Every generator that owner placed, including unloaded chunks |
getIslandGenerators(UUID) | CompletableFuture<List<GeneratorView>> | The same for every member of that player's island |
CompletableFuture results complete on an async thread. Hop back to the main thread before
touching the Bukkit API.
api.getIslandGeneratorStats(player.getUniqueId()).thenAccept(stats ->
Bukkit.getScheduler().runTask(this, () ->
player.sendMessage("Island: " + stats.totalCount()
+ " generators worth " + stats.totalValue())));Upgrades
The query service only reads. These four methods change the world, so they get their own rules. Call them on the main thread. On Folia, call them on the region thread that owns the location.
| Method | Returns | Notes |
|---|---|---|
simulateUpgrade(Player, Location, int) | UpgradeResult | Dry run of the same climb. Nothing is charged |
simulateUpgradeTo(Player, Location, String) | UpgradeResult | Dry run up to an exact tier |
upgradeGenerator(Player, Location, int) | UpgradeResult | Climbs up to N tiers and charges once |
upgradeGeneratorTo(Player, Location, String) | UpgradeResult | Climbs to an exact tier and charges once |
An upgrade is all or nothing. Either every level applies and the total is charged once, or
nothing changes at all. One GeneratorUpgradeEvent fires per hop, and all of them fire before
any money moves. Cancelling any hop refuses the whole request with CANCELLED and charges
nothing.
Those per-hop listeners run arbitrary code. SnGens looks the generator up again after the
events and honours the withdrawal result. A listener that removes or changes the generator,
or that drains the actor's balance, yields BUSY, NOT_A_GENERATOR or NOT_ENOUGH_MONEY
with nothing changed and nothing charged.
SnGens reads the block once more after the charge, because the charge is third party code too.
If the generator changed in that window, the player gets the money back and the call refuses.
The status is BUSY or NOT_A_GENERATOR, and charged stays 0. A climb whose total is 0
never calls the economy at all.
A dry run stops before the per-hop events. simulateUpgrade and simulateUpgradeTo fire
nothing, so a simulation never returns CANCELLED. Treat a clean simulation as "would succeed
right now", not as a reservation.
You identify a generator by its location. Any location inside the block matches, because
decimals, yaw and pitch are ignored. So player.getLocation() of a standing player works as
well as the GeneratorView#location() you get from the listings above. The same holds for
getGeneratorAt and isGenerator.
SnGens sends no chat message and plays no sound on this path. Render the result yourself.
These methods do not consume the island's daily upgrade uses, and they do not require the island leader. Access is the owner or an island mate, exactly like a shift + right click upgrade. Gate them yourself if your menu needs a stricter rule.
api.getGeneratorAt(loc).ifPresent(gen -> {
api.quoteUpgradeTo(gen.generatorId(), "diamond_generator")
.ifPresent(quote -> player.sendMessage("Diamond costs " + quote.totalCost()
+ " over " + quote.levels() + " levels"));
UpgradeResult result = api.upgradeGenerator(player, loc, 2);
if (result.success()) {
player.sendMessage("Now " + result.toGeneratorId() + ", paid " + result.charged());
} else if (result.status() == UpgradeStatus.NOT_ENOUGH_MONEY) {
player.sendMessage("You need " + result.totalCost());
}
});Transfers
These two methods move what a player owns to another player. Both players may be offline.
| Method | Returns | Notes |
|---|---|---|
transferSlots(UUID, UUID, int) | CompletableFuture<TransferResult> | Moves stored generator slots from the first player to the second |
transferSellMultiplier(UUID, UUID, double) | CompletableFuture<TransferResult> | Moves part of the stored sell multiplier |
Only stored values move. Base slots, sngens.max.<n> permission slots and every other
multiplier source stay with their owner. So rank slots can never reach another account.
SnGens checks and writes in one step. For an online sender, that step runs on the sender's own thread, where their generator placements also run. The sender cannot place a generator in between and end up above the limit.
A transfer is refused, with nothing changed, when:
- the sender does not store that much, or their multiplier would drop below
player-defaults.multiplier - the sender would keep more generators placed than slots
- the receiver would pass an enabled
player-generator-limitorplayer-multiplier-limit - either player already has a transfer running, or a listener cancelled the event
While the sender is offline, SnGens cannot read their permission slots. The free slot check
then counts only base and stored slots. Call getSlotBreakdown(uuid) and read
transferable() for the exact amount the sender side accepts right now.
Both rows are saved in one database transaction before the future completes. A success completes on an async thread. A refusal may complete on the calling thread or on the sender's thread. Always hop back before you touch the Bukkit API. SnGens sends no chat message, so render the result yourself.
UUID from = sender.getUniqueId();
api.getSlotBreakdown(from).ifPresent(b ->
sender.sendMessage("You can transfer up to " + b.transferable() + " slots"));
api.transferSlots(from, target.getUniqueId(), 5).thenAccept(result ->
Bukkit.getScheduler().runTask(this, () -> {
switch (result.status()) {
case SUCCESS -> sender.sendMessage("Sent 5 slots, you keep " + (int) result.fromStored());
case NOT_ENOUGH_FREE_SLOTS -> sender.sendMessage("Pick some generators up first");
case BELOW_MINIMUM -> sender.sendMessage("You do not have that many transferable slots");
default -> sender.sendMessage("Transfer refused: " + result.status());
}
}));The transfer events have no setter for the amount. To charge a tax, check the balance in the
listener and cancel when the player cannot pay. Take the money once the result reports
SUCCESS, because the transfer is validated again after the listeners.
A SlotBreakdown splits the slots into base, permission and stored. permission reads
0 while the player is offline. In both breakdowns, limit is -1 when that cap is disabled.
On SUCCESS, a TransferResult carries the stored values right after the transfer in
fromStored and toStored. On a refusal they are the current values. amount is always the
amount you asked for.
TransferStatus reports why a transfer succeeded or was refused:
| Status | Meaning |
|---|---|
SUCCESS | The amount moved |
INVALID_REQUEST | A null player id, or an amount that is not a positive finite number |
SAME_PLAYER | The sender and the receiver are the same player |
UNKNOWN_PLAYER | One of the players never joined since SnGens was installed |
BELOW_MINIMUM | The sender does not own that much: more slots than stored, or a multiplier below player-defaults.multiplier |
NOT_ENOUGH_FREE_SLOTS | Slots only. The sender would keep more generators placed than slots |
TARGET_LIMIT | The receiver would pass an enabled player-generator-limit or player-multiplier-limit, or its stored value is not valid. For slots, only base and stored slots count |
BUSY | One of the players already has a transfer running, or the server is stopping. Retry later |
CANCELLED | A SlotTransferEvent or SellMultiplierTransferEvent listener cancelled the transfer |
Views
Every returned object is an immutable snapshot. Location and ItemStack values are cloned,
so mutating them never affects SnGens.
| View | Fields |
|---|---|
GeneratorView | owner, location, generatorId, displayName, corrupted, nextGeneratorId, upgradeCost, drops, stackAmount, brokenAmount |
DropView | id, chance, item, sellValue, commands |
PlayerGensProfile | uuid, placedCount, maxSlots, sellMultiplier, hideStats, online |
IslandGeneratorStats | islandId, members, totalCount, countByType, totalValue |
ServerEventView | id, type, displayName, remainingSeconds |
TopEntryView | rank, scopeId, headOwner, displayName, value |
SellContext | itemCount, baseValue, effectiveMultiplier, finalAmount, source |
HopperView | id, owner, location, maxTypes, slotsUsed, totalItems, contents, estimatedValue, createdAt, updatedAt |
CollectorView | id, owner, location, totalItems, slotsUsed, contents, estimatedValue, createdAt, updatedAt, level, effectiveLevel, areaSide |
StoredItemView | key, item, amount, unitValue, totalValue |
WandView | type, uses, unlimited, sellMultiplier, distance, radius |
UpgradeStepView | level, fromGeneratorId, toGeneratorId, toDisplayName, cost, cumulativeCost |
UpgradeQuote | fromGeneratorId, toGeneratorId, levels, totalCost, capped, steps |
UpgradeResult | status, success, dryRun, fromGeneratorId, toGeneratorId, levels, totalCost, charged, failedRequirements |
SlotBreakdown | uuid, online, placed, base, permission, stored, limit, max, transferable, free |
SellMultiplierBreakdown | uuid, stored, minimum, limit, transferable |
TransferResult | status, success, from, to, amount, fromStored, toStored |
GeneratorTypeView | id, displayName, tier, nextGeneratorId, upgradeCost, shopPrice, item |
A HopperView or CollectorView is a snapshot taken when you asked for it. Both keep
absorbing items afterwards, so query again on each menu refresh instead of caching.
On a CollectorView, level() is the level bought, and it stays as bought when the server
lowers max-level. effectiveLevel() is that level capped by the current max-level.
areaSide() is 2 * effectiveLevel() - 1, the side of the chunk square the collector absorbs.
for (CollectorView collector : api.getOwnerCollectors(player.getUniqueId())) {
player.sendMessage("Level " + collector.level() + ", collecting "
+ collector.areaSide() + "x" + collector.areaSide() + " chunks");
}A WandView reports one of five types: SELLWAND, BUILDWAND, UPGRADEWAND_FREE,
UPGRADEWAND_RADIUS, ADMINWAND. Read type() first, then only the field that belongs to
it. The others stay at zero. uses() is -1 on an unlimited wand, and the admin wand has no
counter so it always reports -1.
ItemStack held = player.getInventory().getItemInMainHand();
api.getWand(held).ifPresent(wand -> {
if (wand.type() == WandType.SELLWAND) {
player.sendMessage("Sellwand x" + wand.sellMultiplier()
+ (wand.unlimited() ? " (unlimited)" : ", " + wand.uses() + " uses left"));
}
});A tier's configured upgrade-cost is the price of leaving it. So an UpgradeStepView prices
a hop by its origin tier, never by the tier it reaches. cumulativeCost is the running total
up to and including that hop.
An UpgradeQuote always covers at least one tier. A type that is already the last tier of the
chain yields no quote at all. capped is true when you asked for more levels than the chain
still had, and levels is then the shorter, real figure.
An UpgradeResult is refused or applied, never half applied. On any status other than
SUCCESS, toGeneratorId equals fromGeneratorId, levels is 0 and charged is 0.
totalCost still carries the quoted total when the chain resolved, so NOT_ENOUGH_MONEY
tells you how much was needed. Both ids are null only for INVALID_REQUEST, NOT_LOADED
and NOT_A_GENERATOR. On a dry run charged is always 0, and SUCCESS means the upgrade
would succeed right now. It is not a reservation.
UpgradeStatus reports why a request succeeded or was refused:
| Status | Meaning |
|---|---|
SUCCESS | The upgrade applied, or on a dry run would apply |
INVALID_REQUEST | Null actor or location, world not loaded, or a level count below one |
NOT_LOADED | The chunk is not loaded, so SnGens cannot tell what stands there |
NOT_A_GENERATOR | The chunk is loaded and no generator stands at that location |
CORRUPTED | The generator is corrupted. Repair it first |
NO_ACCESS | The actor is neither the owner nor an island mate of the owner |
BUSY | A bulk upgrade flush owns this owner's scope, or the generator changed tier, got corrupted or was locked while the per-hop events ran. Retry later |
MAX_TIER | The generator has no next tier |
INVALID_TARGET | The target type is unknown, or it is not ahead of the current tier |
REQUIREMENTS_FAILED | An upgrade-requirements guard failed on the current or an intermediate tier |
NOT_ENOUGH_MONEY | The actor's balance is below the total cost, or the economy refused the withdrawal after every check passed. Nothing was changed |
CANCELLED | A listener cancelled one of the GeneratorUpgradeEvent steps |
failedRequirements holds the configured failure messages, raw and with their colour codes.
It is empty unless the status is REQUIREMENTS_FAILED.
Generator catalogue
Use the catalogue to price generators, list every tier, or hand one out.
for (GeneratorTypeView type : api.getGeneratorTypes()) {
menu.addIcon(type.item(), type.tier(), type.shopPrice());
}
api.getGeneratorId(player.getInventory().getItemInMainHand())
.flatMap(api::getGeneratorType)
.ifPresent(type -> player.sendMessage("Tier " + type.tier() + ", worth " + type.shopPrice()));
api.createGeneratorItem("diamond_generator", 1)
.ifPresent(item -> player.getInventory().addItem(item));tier() is the 1-based position in the upgrade chain. The root type is tier 1.
A type the chain does not reach has tier 0 and a shop price of 0.
shopPrice() is what one generator of that type is worth. It is the shop base cost plus
every upgrade cost from the chain root to that type, the number /gens shop charges.
upgradeCost() is the price of leaving the type, as in UpgradeStepView.
item() returns one placeable generator item, cloned on every call.
The views are snapshots. Read them again after a /gens reload instead of keeping them.
Call these four methods on the main thread.
Extension points
| Interface | What it influences | Neutral return |
|---|---|---|
GensSellMultiplier | Adds to the additive part of a player's sell multiplier | 0 |
MultiplicativeGensSellMultiplier | Multiplies on top of the additive total, like equipment | 0 |
GensBonusProvider | Adds speed, tier, drop and lucky bonuses to a player's generators | null or GensBonus.EMPTY |
Register through the facade, from your own onEnable:
// Additive: VIPs get +0.5x
api.registerSellMultiplier(this, ctx ->
ctx.player().hasPermission("myrank.vip") ? 0.5 : 0.0);
// Multiplicative: +10% on top of whatever the player already has
api.registerSellMultiplier(this,
(MultiplicativeGensSellMultiplier) ctx -> 0.10);The context passed to a provider is a GensSellContext, with player() and
sellwandMultiplier(). The second is only present for sellwand sales.
Providers run inside the payout path of every sale, so keep them fast. The server's
player-multiplier-limit clamp still applies on top of whatever your provider contributes.
Registrations last until SnGens disables. They survive /sngens reload, so register once.
Generator bonuses
A GensBonusProvider boosts a player's generators the same way SnGens armor does. Your
answer is added to the player's own armor and off-hand bonuses on every generator run.
// Filled on the main thread whenever your item, pet or armor state changes
Map<UUID, GensBonus> bonuses = new ConcurrentHashMap<>();
api.registerBonusProvider(this, bonuses::get); // null means no bonus
bonuses.put(player.getUniqueId(), GensBonus.builder()
.speed(10) // percent of the interval removed, 50 means 2x output
.tier(1) // whole tiers each drop climbs
.dropMultiplier(15) // percent more drops per fire
.luckyChance(5) // percent chance to double a fire
.build());GensBonus is immutable, and its builder rejects NaN and infinite values. It has no sell
component. Use MultiplicativeGensSellMultiplier to match the equipment sell bonus.
The generator run calls getBonus(UUID) off the main thread, once per online owner per run.
Return a cached value from a concurrent map. Never touch worlds, entities or inventories there.
- Only online owners are asked. Offline owners get no plugin bonus, like SnGens equipment.
- Negative and non-finite components count as
0. - A provider that throws adds nothing. Its first failure is logged with your plugin name.
- The sum of all providers is capped per player by
api-bonusesinconfig.yml. SnGens equipment is never capped. registerBonusProviderreturnsfalsefor a disabled owner or an instance already registered.- Providers survive
/sngens reloadand are removed when your plugin disables. unregisterBonusProviders(plugin)removes yours at runtime. Register again after SnGens itself re-enables.- A changed answer applies on the next generator run.
%sngens_bonus_*%placeholders show the total.%sngens_eq_*%stays equipment only.
The per drop generation path deliberately has no event. It is the hottest loop in the plugin,
and firing an event per drop would cost more than the feature is worth. Use
getPlacedCount or getIslandGeneratorStats for production totals instead.
Global bonuses
You can also switch a server wide generator bonus on and off with a plain call, without a provider. This suits a config driven plugin, such as a weekend event.
api.setGlobalBonus("weekend", 0, 0, 100, 0); // source, speed, tier, dropMultiplier, luckyChance
api.removeGlobalBonus("weekend"); // true when that source was activeThe arguments are plain numbers and a string. A plugin can also call the methods by reflection, matching them by name and argument count.
- The bonus applies to every online generator owner. The source id is its key.
- Calling
setGlobalBonusagain with the same id replaces that source. Different ids add up. - It is summed with every provider, then capped by
api-bonusesinconfig.yml. SnGens equipment is never capped. api-bonuses.enabled: falseignores it. The bonus is kept and applies again when you turn the setting back on.- Negative and non-finite components count as
0. A call with every component0clears that source. - Nothing is saved. A restart clears it, so apply it again when your plugin starts.
/sngens reloadkeeps it. - It is not tied to your plugin. Disabling your plugin does not remove it, so call
removeGlobalBonusyourself. - Both methods are safe from any thread. A change applies on the next generator run.
getGeneratorBonusesand the%sngens_bonus_*%placeholders include it.
Versioning
Call getApiVersion() for the API contract version. It is independent of the plugin version.
Additions bump the minor component. Existing members are never removed or changed; deprecated
members keep working.
The current contract version is 1.13.0. It added broken generators inside stacks in SnGens
2.75.0:
GeneratorView#brokenAmount()is how many generators of the block are broken.corrupted()is true when at least one is.GeneratorCorruptEvent#getBrokenAmount()is how many broke in that wave.GeneratorRepairEvent#getRepairedAmount()is how many the repair fixes.getFixCost()is the tier's fix cost times that number./gens repairnow firesGeneratorRepairEventonce per block, before the charge. Cancel one to leave that block out. The free admin repair fires nothing.
To count repaired generators instead of repair clicks, add getRepairedAmount().
Version 1.12.0 added generator stacking in SnGens 2.73.0:
GeneratorView#stackAmount(), GeneratorStackChangeEvent and getMaxStackSize().
Since that version every count is per generator, not per block. getPlacedCount, island
stats, leaderboards and upgrade events count each generator of a stack. Upgrade costs and
charged cover the whole stack: the unit cost times the stack size.
Version 1.11.0 added the drops sold notification in SnGens 2.72.0:
GeneratorDropsSoldEvent.
Version 1.10.0 added the generator catalogue in SnGens 2.71.0:
getGeneratorTypes, getGeneratorType, getGeneratorId, createGeneratorItem and
GeneratorTypeView.
Version 1.9.0 added global generator bonuses in SnGens 2.70.0:
setGlobalBonus and removeGlobalBonus.
Version 1.8.0 added committed-upgrade notifications in SnGens 2.67.0.
Version 1.7.0 added generator bonus providers in SnGens 2.66.0:
registerBonusProvider, unregisterBonusProviders, getGeneratorBonuses, GensBonus and
GensBonusProvider.
Version 1.6.0 added player to player transfers in SnGens 2.63.0:
transferSlots, transferSellMultiplier, getSlotBreakdown, getSellMultiplierBreakdown,
SlotTransferEvent and SellMultiplierTransferEvent.
Version 1.5.0 added collector levels in SnGens 2.59.0:
CollectorUpgradeEvent, CollectorView#level(), #effectiveLevel(), #areaSide() and
StorageRefundIssuedEvent#getCollectorLevels().
Version 1.4.0 added the upgrade path, the quotes, the dry runs and the four upgrade methods in
SnGens 2.57.0.
Committed generator upgrades (API 1.8.0)
GeneratorUpgradedEvent is a non-cancellable notification after a successful
upgrade has changed the in-memory tier and accepted its charge. It exposes
getPlayer(), getFromGeneratorId(), getToGeneratorId(), getAmount() and
getCost(). The amount is committed tier transitions; cost is the total paid
cost represented by the notification. It covers hand, GUI, radius/free wand
and multi-level API upgrades. Physical block writes and ordered persistence
may still be queued. A free upgrade reports zero cost.
Failed charges, cancelled operations and API dry runs do not emit this event.
A multi-level API climb emits one notification per committed hop, preserving
each hop's cost, including zero-cost hops. Paid-work missions should filter
getCost() > 0 and count getAmount(). PRE events remain unchanged and must
not be used as evidence that an upgrade succeeded.