diff --git a/docs/crafttweaker.md b/docs/crafttweaker.md
index 9082c383..4dd99fe7 100644
--- a/docs/crafttweaker.md
+++ b/docs/crafttweaker.md
@@ -1005,7 +1005,7 @@ block using it is created.
## Creative tabs
Scripts can make creative tabs, and change the tabs that `mmdlib/creative_tab/`
-JSON files declare (see [creative tabs](creative-tabs.md) for the file format).
+XML or JSON files declare (see [creative tabs](creative-tabs.md) for the file formats).
```zenscript
#loader mmdlib
@@ -1026,14 +1026,13 @@ workshop.build();
```
`new CreativeTabBuilder("tools")` starts the tab `mmdlib:tools`; other namespaces
-are rejected, as for materials. A name a JSON file already declares is rejected
+are rejected, as for materials. A name a file already declares is rejected
too: change that tab with `edit` instead.
-`CreativeTabBuilder.edit(id)` starts from the tab a JSON file declares, in any
+`CreativeTabBuilder.edit(id)` starts from the tab a file declares, in any
namespace, with all its settings and contents. Building it replaces the file's
-version, so the changed tab is the one registered. A tab in another mod's namespace
-is registered by that mod; the change applies when it registers its tabs from
-`MMDLib.creativeTabs()`, as [creative tabs](creative-tabs.md) describes.
+version, so the changed tab is the one automatically registered by MMDLib,
+including tabs in another mod's namespace.
`CreativeTabBuilder.exists(id)` tells whether a file declares a tab, and
`CreativeTabBuilder.declared()` lists every file tab's ID.
@@ -1044,6 +1043,10 @@ is registered by that mod; the change applies when it registers its tabs from
| `titleFallback` | string | `""`: none |
| `icon` | item ID | `""`: the first item or material entry |
| `searchBar` | bool | `false` |
+| `defaultForMod` | bool | `false`; sends the owning mod's generated content to this tab (one default per mod) |
+| `includeModItems` | bool | `false`; includes all registered items in the owning namespace |
+| `exclude` | item IDs, string[] | empty; exclusions override explicit and automatic entries |
+| `excludeTags` | item tag IDs, string[] | empty; bare IDs (no `#`), resolved when tabs rebuild |
| `before`, `after` | tab IDs, string[] | empty |
| `contents` | string[], read-only | empty |
diff --git a/docs/creative-tabs.md b/docs/creative-tabs.md
index f248fae9..72a93d27 100644
--- a/docs/creative-tabs.md
+++ b/docs/creative-tabs.md
@@ -1,19 +1,66 @@
# Creative tabs
-A mod using MMDLib can describe its creative tabs in JSON, next to its material and
+A mod using MMDLib can describe its creative tabs in XML or JSON, next to its material and
other definitions. Each file in `mmdlib/creative_tab/` becomes one tab:
```text
src/main/resources/mmdlib/
material/copper.json
- creative_tab/tools.json -> tab example:tools
+ creative_tab/main.xml -> tab example:main
creative_tab/blocks/deco.json -> tab example:blocks/deco
```
The tab's ID is the mod's ID and the file's path below `creative_tab/`, without
-`.json`, as for every other [definition file](definition-loading.md).
+`.xml` or `.json`. Defining the same ID in both formats is an error.
+
+## XML
+
+```xml
+
+
+
+
+```
+
+The namespace and `version="1"` are required. Root attributes are `title`,
+`title-fallback`, `icon`, `search-bar`, `default-for-mod` and `include-mod-items`;
+boolean attributes default to `false`. Children are `item`, `tag`, `material`,
+`before`, `after` and `exclude`. Entries use `id`; `exclude` requires exactly one
+of `id` (an item) or `tag` (an item tag). Unknown attributes/elements are errors. DTDs and
+external entities are not allowed. XML and JSON use the same validation and
+runtime behavior.
+
+`include-mod-items="true"` includes every registered item whose namespace matches
+the tab's owning mod, including native Java items and generated block/material
+items. No item list is needed. New items appear automatically after restarting.
+Items are sorted by registry ID. Optional `item`, `tag` and `material` entries
+come first, allowing favorites at the top without duplicates.
+
+`exclude` accepts exact item IDs or item tags and wins over all inclusion sources, including
+explicit entries and `default-for-mod` generated content. It affects this tab's
+display and contribution to creative search; another tab may still list the item.
+Unknown exclusions are harmless, allowing optional or retired internal items.
+Supply an `icon` when there are no explicit item/material entries.
+
+For ``, put the members in
+`data/example/tags/item/internal_items.json`:
+
+```json
+{
+ "replace": false,
+ "values": ["example:internal_part", "example:legacy_alias"]
+}
+```
+
+Use the bare tag ID in XML (no `#`). Tag files can include nested tags using
+`"#example:other_internal_items"`. Exclusion tags are resolved whenever the tab
+is rebuilt, using the current datapack tags; missing or empty tags exclude nothing.
+Both shipped mod tabs use their own `internal_items` tag.
-## The file
+## JSON
```json
{
@@ -29,7 +76,11 @@ The tab's ID is the mod's ID and the file's path below `creative_tab/`, without
}
```
-Only `contents` is required.
+`contents` may be omitted or empty only when `include_mod_items` or
+`default_for_mod` is true. Otherwise an empty definition is rejected, including
+one that accidentally uses `content` instead of `contents`. Without an explicit
+item/material entry, an `icon` is required. The same rules apply to XML and Java
+builders.
| Field | Meaning |
|---|---|
@@ -39,6 +90,10 @@ Only `contents` is required.
| `icon` | The item shown on the tab. Defaults to the first item or material entry in `contents`; a tab whose contents are all tags needs one. |
| `before`, `after` | Tab IDs this tab is placed before or after, such as `"minecraft:combat"`. |
| `search_bar` | `true` gives the tab a search bar. |
+| `default_for_mod` | `true` sends generated machines and registrar items in this tab's namespace here. At most one default per mod. XML spells this `default-for-mod`. |
+| `include_mod_items` | `true` appends every enabled item registered in the owning namespace, sorted by ID. Defaults to `false`. XML spells this `include-mod-items`. |
+| `exclude` | Item IDs to omit from all inclusion sources, e.g. `["example:internal_part"]`. Defaults to `[]`. XML uses ``. |
+| `exclude_tags` | Item tag IDs to omit, e.g. `["example:internal_items"]` (no `#`). Defaults to `[]`. XML uses ``. |
An item appears once, where it is first listed: a tag or material that includes an
item already shown does not repeat it. Items whose feature flags are disabled are
@@ -57,19 +112,29 @@ Tags are filled in when the game builds the tab, so tags from datapacks work.
## Registering the tabs
-MMDLib registers the tabs in its own namespace. As with materials, your mod
-registers its own, through its `RuntimeContentRegistrar`. `MMDLib.creativeTabs()`
-lists every tab file; queue yours once loading is done:
-
-```java
-MMDLib.creativeTabs().forEach((id, tab) -> {
- if (id.getNamespace().equals("example"))
- registrar.queueTab(id, tab);
-});
-```
-
-`queueTab` returns the tab's `DeferredHolder`. It only takes IDs in the
-registrar's namespace, and not `:materials`, which is the registrar's own tab.
+MMDLib automatically registers file-defined tabs for every owning mod. No Java
+tab registration is needed. `MMDLib.creativeTabs()` lists the loaded definitions.
+Existing consumers that queue file tabs through a `RuntimeContentRegistrar`
+remain supported; a queued tab is not registered a second time.
+
+Generated machines and material/standalone items join their owner's default tab,
+after its explicit contents, without duplicates. Without an explicit default,
+MMDLib selects a same-namespace Java or file tab: `main`, then `machines`, then
+other names alphabetically, then `materials`, then `mmdlib_content`. A namespace
+with generated items gets a fallback only
+if it has no authored, queued or registered Java tab after its own tab registration
+handlers run. Registrar namespaces retain `:materials` and the existing
+`itemGroup..materials` translation key; other namespaces get
+`:mmdlib_content`. Both use the mod display name when their title is untranslated.
+No unused placeholder tab is registered. Routing is selected once after registration;
+Tag exclusions and feature flags are still evaluated on each contents rebuild.
+There is no shared data-defined machines tab. MMDLib's Range, Gearbox and Capacitor Upgrades live in `mmdlib:main`.
+
+Use `include-mod-items` to discover manually registered Java items too, and
+exclude internal parts and compatibility aliases. Without that option, list
+Java items explicitly or use the Java tab's display callback.
+
+When replacing a Java tab with XML, remove the old registration for that ID.
## Building a tab in code
@@ -86,9 +151,16 @@ registrar.queueTab(ResourceLocation.parse("example:tools"),
.tag(ResourceLocation.parse("c:gears"))
.after(ResourceLocation.parse("minecraft:tools_and_utilities"))
.searchBar()
+ .defaultForMod()
+ .includeModItems()
+ .exclude(ResourceLocation.parse("example:internal_part"))
+ .excludeTag(ResourceLocation.parse("example:internal_items"))
.build());
```
+`queueTab` returns the tab's `DeferredHolder`. It only takes IDs in the
+registrar's namespace, and not `:materials`, which is reserved for its fallback.
+
## From CraftTweaker scripts
`#loader mmdlib` scripts can make tabs with `mods.mmdlib.CreativeTabBuilder`, and
@@ -100,6 +172,6 @@ ID replaces it.
## The materials tab
-Every registrar also has its automatic `:materials` tab, holding every item it
-registers; its title is the translation key `itemGroup..materials`. It is
-unchanged by tab files, so an item listed in your own tab also appears there.
+Every registrar retains `:materials` as a fallback, using translation key
+`itemGroup.` and the mod's display name. It receives generated content only
+when the mod has no preferred tab; otherwise it stays empty and hidden.
diff --git a/docs/definition-loading.md b/docs/definition-loading.md
index 957fd03d..29d99830 100644
--- a/docs/definition-loading.md
+++ b/docs/definition-loading.md
@@ -15,11 +15,12 @@ src/main/resources/mmdlib/
sound/machine/hum.json
sound_type/steel_plate.json
creative_tab/tools.json
+ creative_tab/main.xml
machine/simple_crusher.xml
```
IDs use the owning mod's namespace and the relative path below the section,
-without `.json`. For mod ID `example`, the gear above is `example:components/gear`
+without `.json` or `.xml`. For mod ID `example`, the gear above is `example:components/gear`
and the material is `example:copper`. For a file declaring several mods, the
root-level directory belongs to the first mod declared in its metadata. Extension
files also have file IDs, but their callable handler IDs come from the explicit
@@ -174,7 +175,7 @@ in datapacks, and code playing it through its registry holder.
## Creative tabs
-`mmdlib/creative_tab/.json` describes one creative tab: its title, icon,
+`mmdlib/creative_tab/.xml` (or `.json`) describes one creative tab: its title, icon,
placement and contents (items, item tags and whole materials). See
[creative tabs](creative-tabs.md).
diff --git a/docs/machine-companion.md b/docs/machine-companion.md
index 6cf96176..1f29aa9d 100644
--- a/docs/machine-companion.md
+++ b/docs/machine-companion.md
@@ -38,7 +38,7 @@ those mods' login payloads; real client smoke runs include them.
| `dual_crusher` | Two independently pausable processors share the same input and output slots |
| `logistics` | Seven independent resource groups for testing automation, filters and side configuration; no recipe processing |
| `creative_power` | Refills its buffer and supplies up to 1,000 FE per enabled adjacent face per tick |
-| `simple_crusher` | XML-only definition with inherited power, generated screen contents, and tag-generated ore-to-ingot recipes; in the **Data-defined Machines** tab |
+| `simple_crusher` | XML-only definition with inherited power, generated screen contents, and tag-generated ore-to-ingot recipes; in the companion mod's own tab |
| `multiblock_demo` | One item places a controller and two linked parts; the far part exposes item/fluid/energy ports; breaking a member dismantles the machine |
The **Multiblock Test Bench** is in the Machines tab. It occupies the controller position and two
diff --git a/docs/xml-machines.md b/docs/xml-machines.md
index c5df619a..e146ce25 100644
--- a/docs/xml-machines.md
+++ b/docs/xml-machines.md
@@ -59,7 +59,7 @@ The example reuses vanilla textures; your own textures can use names such as
blockstates, block/item models, English labels, mining tags and a self-drop loot
table in a low-priority resource pack. Authored resources can override these
defaults. Crafting recipes remain ordinary files under `data//recipe/`.
-The companion's SimpleCrusher is in the **Data-defined Machines** creative tab.
+The companion's SimpleCrusher is in the companion mod's own creative tab.
## Ghost inventory inputs
diff --git a/scripts/gui-smoke.init.gradle b/scripts/gui-smoke.init.gradle
index e27143ed..5fa06408 100644
--- a/scripts/gui-smoke.init.gradle
+++ b/scripts/gui-smoke.init.gradle
@@ -9,7 +9,15 @@ allprojects {
// The GUI smoke doesn't test CraftTweaker (the game tests do); keep it out of this client.
configurations.named('craftTweakerDevRuntime') { dependencies.clear() }
sourceSets.main.java.srcDir(file('src/runtimeTest/java'))
- sourceSets.main.resources.srcDir(file('src/runtimeTest/resources'))
+ // Test resources overlay production resources, as they do in the runtime-test pack.
+ def runtimeResources = file('src/runtimeTest/resources')
+ sourceSets.main.resources.srcDir(runtimeResources)
+ tasks.named('processResources') {
+ eachFile { entry ->
+ def overlay = new File(runtimeResources, entry.path)
+ if (overlay.isFile() && entry.file != overlay) entry.exclude()
+ }
+ }
def ghostOnly = providers.gradleProperty('ghostSmokeOnly').isPresent()
def transferOnly = providers.gradleProperty('transferSmokeOnly').isPresent()
if (ghostOnly && transferOnly) throw new GradleException('Choose one focused GUI runner')
diff --git a/src/companionTest/java/zone/moddev/mc/companion/test/CompanionGameTests.java b/src/companionTest/java/zone/moddev/mc/companion/test/CompanionGameTests.java
index ce8a9594..7437ff1d 100644
--- a/src/companionTest/java/zone/moddev/mc/companion/test/CompanionGameTests.java
+++ b/src/companionTest/java/zone/moddev/mc/companion/test/CompanionGameTests.java
@@ -42,6 +42,37 @@
public final class CompanionGameTests {
private static final BlockPos CENTER = new BlockPos(2, 2, 2);
+ @GameTest(template = "empty")
+ public static void nativeCreativeTabSuppressesGeneratedFallback(
+ GameTestHelper helper) {
+ var tabs = BuiltInRegistries.CREATIVE_MODE_TAB;
+ var namespace = CompanionMod.ID;
+ require(
+ tabs.containsKey(net.minecraft.resources.ResourceLocation
+ .fromNamespaceAndPath(namespace, "machines")),
+ "Consumer's Java machines tab is registered");
+ require(
+ !tabs.containsKey(net.minecraft.resources.ResourceLocation
+ .fromNamespaceAndPath(namespace, "materials"))
+ && !tabs.containsKey(net.minecraft.resources.ResourceLocation
+ .fromNamespaceAndPath(namespace, "mmdlib_content")),
+ "Consumer registration after MMDLib does not leave empty fallback tabs");
+ var tab = tabs.get(net.minecraft.resources.ResourceLocation
+ .fromNamespaceAndPath(namespace, "machines"));
+ var level = helper.getLevel();
+ tab.buildContents(
+ new net.minecraft.world.item.CreativeModeTab.ItemDisplayParameters(
+ level.enabledFeatures(), false, level.registryAccess()));
+ var simple = zone.moddev.mc.lib.machine.neoforge.MachineContent
+ .item(net.minecraft.resources.ResourceLocation
+ .fromNamespaceAndPath(namespace, "simple_crusher"));
+ require(
+ tab.getDisplayItems().stream().filter(stack -> stack.is(simple))
+ .count() == 1,
+ "Generated XML machine is routed into the consumer's Java tab exactly once");
+ helper.succeed();
+ }
+
@GameTest(template = "empty")
public static void poweredBasePreservesSavesAndSeparatesFeatureUpdates(
GameTestHelper helper) {
diff --git a/src/main/java/zone/moddev/mc/lib/MMDLib.java b/src/main/java/zone/moddev/mc/lib/MMDLib.java
index b9fa0cf8..e669a21c 100644
--- a/src/main/java/zone/moddev/mc/lib/MMDLib.java
+++ b/src/main/java/zone/moddev/mc/lib/MMDLib.java
@@ -167,6 +167,7 @@ public MMDLib(IEventBus modBus, ModContainer container) {
MMDLibConfig.SERVER_SPEC);
zone.moddev.mc.lib.gui.runtime.ScreenRuntime.register(modBus);
zone.moddev.mc.lib.machine.neoforge.MachineContent.register(modBus);
+ zone.moddev.mc.lib.common.runtime.ModCreativeTabs.register(modBus);
BLOCKS.register(modBus);
ITEMS.register(modBus);
machineTypes.register(modBus);
diff --git a/src/main/java/zone/moddev/mc/lib/common/loading/CreativeTabXml.java b/src/main/java/zone/moddev/mc/lib/common/loading/CreativeTabXml.java
new file mode 100644
index 00000000..d4aa0f0b
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/common/loading/CreativeTabXml.java
@@ -0,0 +1,147 @@
+package zone.moddev.mc.lib.common.loading;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import java.util.ArrayList;
+import java.util.Optional;
+import java.util.Set;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import net.minecraft.resources.ResourceLocation;
+
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+import zone.moddev.mc.lib.common.types.CreativeTabDefinition;
+
+/**
+ * Strict XML front end for the same definition used by JSON and Java builders.
+ */
+public final class CreativeTabXml {
+ public static final String NAMESPACE = "https://moddev.zone/mmdlib/creative-tab";
+ private CreativeTabXml() {
+ }
+
+ public static CreativeTabDefinition read(Path path) {
+ try (var input = Files.newInputStream(path)) {
+ var factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ factory.setFeature(
+ "http://apache.org/xml/features/disallow-doctype-decl", true);
+ factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
+ factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
+ factory.setXIncludeAware(false);
+ factory.setExpandEntityReferences(false);
+ var root = factory.newDocumentBuilder().parse(input)
+ .getDocumentElement();
+ if (!"creative-tab".equals(root.getLocalName())
+ || !NAMESPACE.equals(root.getNamespaceURI()))
+ throw new IllegalArgumentException(
+ "Expected creative-tab in " + NAMESPACE);
+ attributes(root, Set.of("version", "title", "title-fallback",
+ "icon", "search-bar", "default-for-mod", "include-mod-items"));
+ if (!"1".equals(root.getAttribute("version")))
+ throw new IllegalArgumentException("Expected version=1");
+ var contents = new ArrayList();
+ var before = new ArrayList();
+ var after = new ArrayList();
+ var exclusions = new ArrayList();
+ var excludedTags = new ArrayList();
+ for (var node = root.getFirstChild(); node != null; node = node
+ .getNextSibling()) {
+ if (node instanceof Element child) {
+ if (!NAMESPACE.equals(child.getNamespaceURI()))
+ throw new IllegalArgumentException(
+ "Unexpected child namespace");
+ boolean exclusion = "exclude".equals(child.getLocalName());
+ attributes(child,
+ exclusion ? Set.of("id", "tag") : Set.of("id"));
+ for (var nested = child
+ .getFirstChild(); nested != null; nested = nested
+ .getNextSibling())
+ if (nested instanceof Element || !ignorable(nested))
+ throw new IllegalArgumentException(
+ "Entries must be empty elements");
+ if (exclusion) {
+ if (child.hasAttribute("id") == child
+ .hasAttribute("tag"))
+ throw new IllegalArgumentException(
+ "Exclude requires exactly one of id or tag");
+ if (child.hasAttribute("tag")) {
+ excludedTags.add(ResourceLocation
+ .parse(optional(child, "tag").orElseThrow()));
+ continue;
+ }
+ }
+ var id = ResourceLocation.parse(optional(child, "id")
+ .orElseThrow(() -> new IllegalArgumentException(
+ "Entry requires id")));
+ switch (child.getLocalName()) {
+ case "item" -> contents
+ .add(new CreativeTabDefinition.ItemEntry(id));
+ case "tag" -> contents
+ .add(new CreativeTabDefinition.TagEntry(id));
+ case "material" -> contents
+ .add(new CreativeTabDefinition.MaterialEntry(id));
+ case "before" -> before.add(id);
+ case "after" -> after.add(id);
+ case "exclude" -> exclusions.add(id);
+ default -> throw new IllegalArgumentException(
+ "Unknown entry: " + child.getLocalName());
+ }
+ } else if (!ignorable(node))
+ throw new IllegalArgumentException(
+ "Unexpected creative-tab text");
+ }
+ return new CreativeTabDefinition(optional(root, "title"),
+ optional(root, "title-fallback"),
+ optional(root, "icon").map(ResourceLocation::parse), contents,
+ before, after, bool(root, "search-bar"),
+ bool(root, "default-for-mod"), bool(root, "include-mod-items"),
+ exclusions, excludedTags);
+ } catch (Exception error) {
+ throw new IllegalArgumentException(path + ": " + error.getMessage(),
+ error);
+ }
+ }
+
+ private static boolean ignorable(Node node) {
+ return node.getNodeType() == Node.COMMENT_NODE
+ || node.getNodeType() == Node.TEXT_NODE
+ && node.getTextContent().isBlank();
+ }
+
+ private static void attributes(Element element, Set allowed) {
+ var attrs = element.getAttributes();
+ for (int i = 0; i < attrs.getLength(); i++) {
+ var attr = attrs.item(i);
+ if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI
+ .equals(attr.getNamespaceURI()))
+ continue;
+ if (attr.getNamespaceURI() != null
+ || !allowed.contains(attr.getNodeName()))
+ throw new IllegalArgumentException(
+ "Unknown attribute: " + attr.getNodeName());
+ }
+ }
+
+ private static Optional optional(Element element, String name) {
+ if (!element.hasAttribute(name))
+ return Optional.empty();
+ var text = element.getAttribute(name).trim();
+ if (text.isEmpty())
+ throw new IllegalArgumentException("Empty attribute: " + name);
+ return Optional.of(text);
+ }
+
+ private static boolean bool(Element element, String name) {
+ var value = optional(element, name).orElse("false");
+ if (!value.equals("true") && !value.equals("false"))
+ throw new IllegalArgumentException("Expected boolean: " + name);
+ return Boolean.parseBoolean(value);
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/common/loading/DefinitionLoader.java b/src/main/java/zone/moddev/mc/lib/common/loading/DefinitionLoader.java
index 00b4f2da..ebc4a3ab 100644
--- a/src/main/java/zone/moddev/mc/lib/common/loading/DefinitionLoader.java
+++ b/src/main/java/zone/moddev/mc/lib/common/loading/DefinitionLoader.java
@@ -421,8 +421,10 @@ private static Batch discover(SourceRoot source, List sections) {
continue;
try (var files = Files.walk(folder)) {
for (var file : files.filter(Files::isRegularFile)
- .filter(path -> path.toString().endsWith(".json")).sorted()
- .toList()) {
+ .filter(path -> path.toString().endsWith(".json")
+ || section.equals(CREATIVE_TABS)
+ && path.toString().endsWith(".xml"))
+ .sorted().toList()) {
var id = resourceId(source.namespace(), folder, file);
var loader = source.classLoader();
switch (section) {
@@ -455,7 +457,9 @@ private static Batch discover(SourceRoot source, List sections) {
decode(file, SoundDefinition.CODEC), loader));
case CREATIVE_TABS -> add(batch.creativeTabs, id,
new Located<>(file,
- decode(file, CreativeTabDefinition.CODEC),
+ file.toString().endsWith(".xml")
+ ? CreativeTabXml.read(file)
+ : decode(file, CreativeTabDefinition.CODEC),
loader));
case SOUND_TYPES -> add(batch.soundTypes, id,
new Located<>(file,
@@ -478,7 +482,7 @@ private static ResourceLocation resourceId(String namespace, Path folder,
var relative = folder.relativize(file).toString().replace('\\', '/');
try {
return ResourceLocation.fromNamespaceAndPath(namespace,
- relative.substring(0, relative.length() - 5));
+ relative.substring(0, relative.lastIndexOf('.')));
} catch (RuntimeException ex) {
throw new IllegalArgumentException(
file + ": Invalid definition resource ID", ex);
diff --git a/src/main/java/zone/moddev/mc/lib/common/runtime/CreativeTabs.java b/src/main/java/zone/moddev/mc/lib/common/runtime/CreativeTabs.java
index a0a21ddf..798a0194 100644
--- a/src/main/java/zone/moddev/mc/lib/common/runtime/CreativeTabs.java
+++ b/src/main/java/zone/moddev/mc/lib/common/runtime/CreativeTabs.java
@@ -1,8 +1,10 @@
package zone.moddev.mc.lib.common.runtime;
+import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
import com.mojang.logging.LogUtils;
@@ -43,7 +45,7 @@ static CreativeModeTab build(ResourceLocation id,
var builder = CreativeModeTab.builder().title(title)
.icon(() -> new ItemStack(icon(id, definition)))
.displayItems((parameters,
- output) -> items(definition, parameters.enabledFeatures())
+ output) -> items(id, definition, parameters.enabledFeatures())
.forEach(item -> output.accept(new ItemStack(item))));
if (!definition.before().isEmpty())
builder.withTabsBefore(keys(definition.before()));
@@ -58,8 +60,8 @@ static CreativeModeTab build(ResourceLocation id,
* The tab's items in order: each once, where it first appears, and only
* those enabled.
*/
- static List- items(CreativeTabDefinition definition,
- FeatureFlagSet enabled) {
+ static List
- items(ResourceLocation tabId,
+ CreativeTabDefinition definition, FeatureFlagSet enabled) {
var items = new LinkedHashSet
- ();
for (var entry : definition.contents())
switch (entry) {
@@ -71,7 +73,26 @@ static List
- items(CreativeTabDefinition definition,
case MaterialEntry material ->
items.addAll(materialItems(material.material()));
}
- return items.stream().filter(item -> item.isEnabled(enabled)).toList();
+ if (definition.includeModItems())
+ BuiltInRegistries.ITEM.keySet().stream()
+ .filter(id -> id.getNamespace().equals(tabId.getNamespace()))
+ .sorted().map(BuiltInRegistries.ITEM::get).forEach(items::add);
+ var excluded = excludedItems(definition);
+ return items.stream().filter(item -> item.isEnabled(enabled))
+ .filter(item -> !excluded.contains(item)).toList();
+ }
+
+ /** Resolve tags on every rebuild, after datapack tags have been loaded. */
+ static Set
- excludedItems(CreativeTabDefinition definition) {
+ var result = new HashSet
- ();
+ definition.exclusions().stream()
+ .filter(BuiltInRegistries.ITEM::containsKey)
+ .map(BuiltInRegistries.ITEM::get).forEach(result::add);
+ definition.excludedTags()
+ .forEach(tag -> BuiltInRegistries.ITEM
+ .getTagOrEmpty(TagKey.create(Registries.ITEM, tag))
+ .forEach(holder -> result.add(holder.value())));
+ return result;
}
/**
diff --git a/src/main/java/zone/moddev/mc/lib/common/runtime/ModCreativeTabs.java b/src/main/java/zone/moddev/mc/lib/common/runtime/ModCreativeTabs.java
new file mode 100644
index 00000000..5178ef73
--- /dev/null
+++ b/src/main/java/zone/moddev/mc/lib/common/runtime/ModCreativeTabs.java
@@ -0,0 +1,227 @@
+package zone.moddev.mc.lib.common.runtime;
+
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.TreeMap;
+
+import net.minecraft.core.registries.BuiltInRegistries;
+import net.minecraft.core.registries.Registries;
+import net.minecraft.network.chat.Component;
+import net.minecraft.resources.ResourceLocation;
+import net.minecraft.world.item.CreativeModeTab;
+import net.minecraft.world.item.Item;
+import net.minecraft.world.item.ItemStack;
+
+import net.neoforged.bus.api.EventPriority;
+import net.neoforged.bus.api.IEventBus;
+import net.neoforged.fml.ModList;
+import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
+import net.neoforged.fml.event.lifecycle.FMLConstructModEvent;
+import net.neoforged.neoforge.event.BuildCreativeModeTabContentsEvent;
+import net.neoforged.neoforge.registries.RegisterEvent;
+
+import zone.moddev.mc.lib.MMDLib;
+import zone.moddev.mc.lib.common.types.CreativeTabDefinition;
+import zone.moddev.mc.lib.machine.neoforge.MachineContent;
+
+/**
+ * Routes generated content to its owner's main tab, independent of how items
+ * were declared.
+ */
+public final class ModCreativeTabs {
+ private static Map declared = Map
+ .of();
+ private static Map> generated = Map
+ .of();
+ private static Set registrarNamespaces = Set.of();
+ private static Map destinations = Map.of();
+
+ private ModCreativeTabs() {
+ }
+
+ public static void register(IEventBus bus) {
+ bus.addListener(ModCreativeTabs::registerTabs);
+ bus.addListener(ModCreativeTabs::contents);
+ // Install after mod construction, behind native tab registrations.
+ // Each owner's bus may receive RegisterEvent after MMDLib's bus.
+ bus.addListener((FMLConstructModEvent event) -> event
+ .enqueueWork(ModCreativeTabs::installFallbackListeners));
+ bus.addListener((FMLCommonSetupEvent event) -> event.enqueueWork(() -> {
+ MMDLib.creativeTabs().forEach(CreativeTabs::verify);
+ var selected = new TreeMap();
+ generated.keySet()
+ .forEach(namespace -> choose(namespace, declared,
+ BuiltInRegistries.CREATIVE_MODE_TAB.keySet())
+ .ifPresent(id -> selected.put(namespace, id)));
+ destinations = Map.copyOf(selected);
+ }));
+ }
+
+ private static void registerTabs(RegisterEvent event) {
+ event.register(Registries.CREATIVE_MODE_TAB, helper -> {
+ var declarations = definitions();
+ declared = Map.copyOf(declarations);
+ var byNamespace = new TreeMap>();
+ generatedItems().forEach((id, item) -> byNamespace
+ .computeIfAbsent(id.getNamespace(), ignored -> new TreeMap<>())
+ .put(id, item));
+ byNamespace.replaceAll((namespace, items) -> java.util.Collections
+ .unmodifiableMap(items));
+ generated = java.util.Collections.unmodifiableMap(byNamespace);
+ registrarNamespaces = RuntimeContentRegistrar.instances().stream()
+ .map(RuntimeContentRegistrar::namespace)
+ .collect(java.util.stream.Collectors.toUnmodifiableSet());
+ var defaults = new java.util.HashSet();
+ declarations.forEach((id, definition) -> {
+ if (definition.defaultForMod()
+ && !defaults.add(id.getNamespace()))
+ throw new IllegalArgumentException(
+ "Multiple default creative tabs for "
+ + id.getNamespace());
+ boolean queued = RuntimeContentRegistrar.instances().stream()
+ .anyMatch(
+ registrar -> registrar.creativeTabs().containsKey(id));
+ if (!queued)
+ helper.register(id, CreativeTabs.build(id, definition));
+ });
+ });
+ }
+
+ private static void installFallbackListeners() {
+ var buses = new java.util.LinkedHashMap();
+ ModList.get().getMods().forEach(info -> ModList.get()
+ .getModContainerById(info.getModId()).ifPresent(container -> {
+ if (container.getEventBus() != null)
+ buses.put(info.getModId(), container.getEventBus());
+ }));
+ var owners = Set.copyOf(buses.keySet());
+ buses.forEach((owner, bus) -> bus.addListener(EventPriority.LOWEST,
+ (RegisterEvent event) -> registerFallbacks(event, owner, owners)));
+ }
+
+ private static void registerFallbacks(RegisterEvent event, String owner,
+ Set owners) {
+ event.register(Registries.CREATIVE_MODE_TAB,
+ helper -> generated.forEach((namespace, items) -> {
+ // Synthetic namespaces (for example tests) have no mod bus of
+ // their own.
+ if (!namespace.equals(owner) && !(owner.equals(MMDLib.MODID)
+ && !owners.contains(namespace)))
+ return;
+ if (!needsFallback(namespace, declared.keySet(),
+ BuiltInRegistries.CREATIVE_MODE_TAB.keySet()))
+ return;
+ boolean materials = registrarNamespaces.contains(namespace);
+ var id = ResourceLocation.fromNamespaceAndPath(namespace,
+ materials ? "materials" : "mmdlib_content");
+ var icon = items.values().iterator().next();
+ helper.register(id, CreativeModeTab.builder()
+ .title(
+ fallbackTitle(namespace, modName(namespace), materials))
+ .icon(() -> new ItemStack(icon))
+ .displayItems((parameters, output) -> {
+ }).build());
+ }));
+ }
+
+ static boolean needsFallback(String namespace,
+ Collection declarations,
+ Collection registered) {
+ return declarations.stream()
+ .noneMatch(id -> id.getNamespace().equals(namespace))
+ && registered.stream()
+ .noneMatch(id -> id.getNamespace().equals(namespace));
+ }
+
+ static Component fallbackTitle(String namespace, String displayName,
+ boolean materials) {
+ return Component.translatableWithFallback(
+ "itemGroup." + namespace + (materials ? ".materials" : ""),
+ displayName);
+ }
+
+ private static String modName(String namespace) {
+ return ModList.get().getModContainerById(namespace)
+ .map(container -> container.getModInfo().getDisplayName())
+ .orElse(namespace);
+ }
+
+ public static Component modTitle(String namespace) {
+ return fallbackTitle(namespace, modName(namespace), false);
+ }
+
+ private static Map definitions() {
+ var result = new TreeMap<>(MMDLib.creativeTabs());
+ RuntimeContentRegistrar.instances().forEach(
+ registrar -> result.putAll(registrar.creativeTabDefinitions()));
+ return result;
+ }
+
+ /**
+ * Deterministic fallback for Java tabs; explicit default-for-mod
+ * declarations take precedence.
+ */
+ public static Optional choose(String namespace,
+ Map definitions,
+ Collection registered) {
+ var defaults = definitions.entrySet().stream()
+ .filter(entry -> entry.getKey().getNamespace().equals(namespace)
+ && entry.getValue().defaultForMod())
+ .map(Map.Entry::getKey).toList();
+ if (defaults.size() > 1)
+ throw new IllegalArgumentException(
+ "Multiple default creative tabs for " + namespace);
+ if (!defaults.isEmpty())
+ return registered.contains(defaults.getFirst())
+ ? Optional.of(defaults.getFirst())
+ : Optional.empty();
+ return registered.stream()
+ .filter(id -> id.getNamespace().equals(namespace)).sorted(Comparator
+ .comparingInt(id -> switch (id.getPath()) {
+ case "main" -> 0;
+ case "machines" -> 1;
+ case "materials" -> 3;
+ case "mmdlib_content" -> 4;
+ default -> 2;
+ }).thenComparing(ResourceLocation::toString))
+ .findFirst();
+ }
+
+ private static Map generatedItems() {
+ var result = new TreeMap();
+ MachineContent.definitions().keySet()
+ .forEach(id -> result.put(id, MachineContent.item(id)));
+ RuntimeContentRegistrar.instances().forEach(registrar -> registrar
+ .items().forEach((id, item) -> result.put(id, item.get())));
+ return result;
+ }
+
+ private static void contents(BuildCreativeModeTabContentsEvent event) {
+ var id = event.getTabKey().location();
+ // Unrelated/secondary tabs do no copying, registry sorting or item
+ // scans.
+ if (!id.equals(destinations.get(id.getNamespace())))
+ return;
+ var definition = declared.get(id);
+ var excluded = definition == null
+ ? java.util.Set.
- of()
+ : CreativeTabs.excludedItems(definition);
+ generated.get(id.getNamespace()).forEach((itemId, item) -> {
+ if (!item.isEnabled(event.getFlags()) || excluded.contains(item))
+ return;
+ var stack = new ItemStack(item);
+ boolean parent = event.getParentEntries().contains(stack);
+ boolean search = event.getSearchEntries().contains(stack);
+ if (!parent || !search)
+ event.accept(stack,
+ !parent && !search
+ ? CreativeModeTab.TabVisibility.PARENT_AND_SEARCH_TABS
+ : !parent
+ ? CreativeModeTab.TabVisibility.PARENT_TAB_ONLY
+ : CreativeModeTab.TabVisibility.SEARCH_TAB_ONLY);
+ });
+ }
+}
diff --git a/src/main/java/zone/moddev/mc/lib/common/runtime/RuntimeContentRegistrar.java b/src/main/java/zone/moddev/mc/lib/common/runtime/RuntimeContentRegistrar.java
index a5ede2b3..edd3b3c4 100644
--- a/src/main/java/zone/moddev/mc/lib/common/runtime/RuntimeContentRegistrar.java
+++ b/src/main/java/zone/moddev/mc/lib/common/runtime/RuntimeContentRegistrar.java
@@ -116,18 +116,13 @@ public RuntimeContentRegistrar(String namespace,
tabs.register(bus);
sounds.register(bus);
- tabs.register("materials", () -> CreativeModeTab.builder()
- .title(
- Component.translatable("itemGroup." + namespace + ".materials"))
- .icon(() -> itemEntries.isEmpty()
- ? new ItemStack(Items.IRON_INGOT)
- : new ItemStack(itemEntries.values().iterator().next().get()))
- .displayItems((parameters, output) -> itemEntries.values()
- .forEach(item -> output.accept(item.get())))
- .build());
INSTANCES.add(this);
}
+ String namespace() {
+ return namespace;
+ }
+
/** Every registrar created so far. */
public static List instances() {
return List.copyOf(INSTANCES);
@@ -143,6 +138,10 @@ public Map> c
return Collections.unmodifiableMap(tabEntries);
}
+ Map creativeTabDefinitions() {
+ return Collections.unmodifiableMap(tabDefinitions);
+ }
+
/**
* Queues the creative tab {@code id}, described by {@code definition}, for
* registration. Its items, materials and placement are checked during
diff --git a/src/main/java/zone/moddev/mc/lib/common/types/CreativeTabDefinition.java b/src/main/java/zone/moddev/mc/lib/common/types/CreativeTabDefinition.java
index d42c1767..82d4867a 100644
--- a/src/main/java/zone/moddev/mc/lib/common/types/CreativeTabDefinition.java
+++ b/src/main/java/zone/moddev/mc/lib/common/types/CreativeTabDefinition.java
@@ -1,6 +1,9 @@
package zone.moddev.mc.lib.common.types;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec;
@@ -10,8 +13,8 @@
import net.minecraft.resources.ResourceLocation;
/**
- * A creative tab declared in {@code mmdlib/creative_tab/.json}, or built
- * with {@link #builder()}: its title, icon, contents and placement.
+ * A creative tab declared in {@code mmdlib/creative_tab/} as XML or JSON, or
+ * built with {@link #builder()}: its title, icon, contents and placement.
*
* @param title the title's translation key; empty for
* {@code itemGroup..}, with {@code /} as {@code .}
@@ -22,11 +25,26 @@
* @param before tabs this one is placed before
* @param after tabs this one is placed after
* @param searchBar whether the tab has a search bar
+ * @param defaultForMod whether generated content in this namespace joins this
+ * tab
+ * @param includeModItems whether to append all registered items in this tab's
+ * namespace
+ * @param exclusions item IDs omitted from explicit and automatic contents
+ * @param excludedTags item tags omitted from explicit and automatic contents
*/
public record CreativeTabDefinition(Optional title,
Optional titleFallback, Optional icon,
List contents, List before,
- List after, boolean searchBar) {
+ List after, boolean searchBar, boolean defaultForMod,
+ boolean includeModItems, List exclusions,
+ List excludedTags) {
+ public CreativeTabDefinition(Optional title,
+ Optional titleFallback, Optional icon,
+ List contents, List before,
+ List after, boolean searchBar) {
+ this(title, titleFallback, icon, contents, before, after, searchBar,
+ false, false, List.of(), List.of());
+ }
/** One line of a tab's {@code contents}. */
public sealed interface Entry {
}
@@ -77,21 +95,32 @@ public record MaterialEntry(ResourceLocation material) implements Entry {
.forGetter(CreativeTabDefinition::titleFallback),
ResourceLocation.CODEC.optionalFieldOf("icon")
.forGetter(CreativeTabDefinition::icon),
- ENTRY.listOf().fieldOf("contents")
+ ENTRY.listOf().optionalFieldOf("contents", List.of())
.forGetter(CreativeTabDefinition::contents),
ResourceLocation.CODEC.listOf().optionalFieldOf("before", List.of())
.forGetter(CreativeTabDefinition::before),
ResourceLocation.CODEC.listOf().optionalFieldOf("after", List.of())
.forGetter(CreativeTabDefinition::after),
Codec.BOOL.optionalFieldOf("search_bar", false)
- .forGetter(CreativeTabDefinition::searchBar))
+ .forGetter(CreativeTabDefinition::searchBar),
+ Codec.BOOL.optionalFieldOf("default_for_mod", false)
+ .forGetter(CreativeTabDefinition::defaultForMod),
+ Codec.BOOL.optionalFieldOf("include_mod_items", false)
+ .forGetter(CreativeTabDefinition::includeModItems),
+ ResourceLocation.CODEC.listOf()
+ .optionalFieldOf("exclude", List.of())
+ .forGetter(CreativeTabDefinition::exclusions),
+ ResourceLocation.CODEC.listOf()
+ .optionalFieldOf("exclude_tags", List.of())
+ .forGetter(CreativeTabDefinition::excludedTags))
.apply(i, CreativeTabDefinition::new));
/**
* Copies the lists.
*
- * @throws IllegalArgumentException if there is no {@code icon} and no item
- * or material entry to take it from
+ * @throws IllegalArgumentException if contents are empty without automatic
+ * contents, or there is no {@code icon} and no item or material
+ * entry to take it from
*/
public CreativeTabDefinition {
Objects.requireNonNull(title);
@@ -100,6 +129,11 @@ public record MaterialEntry(ResourceLocation material) implements Entry {
contents = List.copyOf(contents);
before = List.copyOf(before);
after = List.copyOf(after);
+ exclusions = List.copyOf(exclusions);
+ excludedTags = List.copyOf(excludedTags);
+ if (contents.isEmpty() && !defaultForMod && !includeModItems)
+ throw new IllegalArgumentException(
+ "A creative tab needs contents, include_mod_items or default_for_mod");
check(icon, contents).getOrThrow(IllegalArgumentException::new);
}
@@ -134,6 +168,10 @@ public static final class Builder {
private final List before = new ArrayList<>(),
after = new ArrayList<>();
private boolean searchBar;
+ private boolean defaultForMod;
+ private boolean includeModItems;
+ private final List exclusions = new ArrayList<>();
+ private final List excludedTags = new ArrayList<>();
private Builder() {
}
@@ -192,6 +230,32 @@ public Builder searchBar() {
return this;
}
+ /** Receives this mod's generated machine and material items. */
+ public Builder defaultForMod() {
+ defaultForMod = true;
+ return this;
+ }
+
+ /** Appends all items registered in the tab's owning namespace. */
+ public Builder includeModItems() {
+ includeModItems = true;
+ return this;
+ }
+
+ /** Omits an item from both explicit and automatic contents. */
+ public Builder exclude(ResourceLocation item) {
+ exclusions.add(Objects.requireNonNull(item));
+ return this;
+ }
+
+ /**
+ * Omits all members of an item tag, resolved when the tab is rebuilt.
+ */
+ public Builder excludeTag(ResourceLocation tag) {
+ excludedTags.add(Objects.requireNonNull(tag));
+ return this;
+ }
+
/**
* The definition.
*
@@ -201,7 +265,8 @@ public Builder searchBar() {
public CreativeTabDefinition build() {
return new CreativeTabDefinition(Optional.ofNullable(title),
Optional.ofNullable(titleFallback), Optional.ofNullable(icon),
- contents, before, after, searchBar);
+ contents, before, after, searchBar, defaultForMod,
+ includeModItems, exclusions, excludedTags);
}
}
}
diff --git a/src/main/java/zone/moddev/mc/lib/compat/CraftTweaker/ScriptCreativeTabBuilder.java b/src/main/java/zone/moddev/mc/lib/compat/CraftTweaker/ScriptCreativeTabBuilder.java
index 0e86ff87..9aef3db5 100644
--- a/src/main/java/zone/moddev/mc/lib/compat/CraftTweaker/ScriptCreativeTabBuilder.java
+++ b/src/main/java/zone/moddev/mc/lib/compat/CraftTweaker/ScriptCreativeTabBuilder.java
@@ -36,6 +36,10 @@ public final class ScriptCreativeTabBuilder {
private final List contents = new ArrayList<>();
private List before = List.of(), after = List.of();
private boolean searchBar;
+ private boolean defaultForMod;
+ private boolean includeModItems;
+ private List exclusions = List.of();
+ private List excludedTags = List.of();
/**
* Starts a new tab named {@code name}, a path such as {@code "tools"}. It
@@ -64,6 +68,10 @@ private ScriptCreativeTabBuilder(ResourceLocation id,
before = from.before();
after = from.after();
searchBar = from.searchBar();
+ defaultForMod = from.defaultForMod();
+ includeModItems = from.includeModItems();
+ exclusions = from.exclusions();
+ excludedTags = from.excludedTags();
}
/**
@@ -204,6 +212,54 @@ public void setSearchBar(boolean value) {
searchBar = value;
}
+ /** Whether generated content belonging to this mod joins this tab. */
+ @ZenCodeType.Getter("defaultForMod")
+ public boolean getDefaultForMod() {
+ return defaultForMod;
+ }
+
+ /** Selects this tab as the mod's destination for generated content. */
+ @ZenCodeType.Setter("defaultForMod")
+ public void setDefaultForMod(boolean value) {
+ defaultForMod = value;
+ }
+
+ /** Whether all items in the owning mod's namespace join this tab. */
+ @ZenCodeType.Getter("includeModItems")
+ public boolean getIncludeModItems() {
+ return includeModItems;
+ }
+
+ /** Includes all items in the owning mod's namespace. */
+ @ZenCodeType.Setter("includeModItems")
+ public void setIncludeModItems(boolean value) {
+ includeModItems = value;
+ }
+
+ /** Item IDs omitted from explicit and automatic contents. */
+ @ZenCodeType.Getter("exclude")
+ public String[] getExclusions() {
+ return strings(exclusions);
+ }
+
+ /** Sets item IDs omitted from explicit and automatic contents. */
+ @ZenCodeType.Setter("exclude")
+ public void setExclusions(String[] values) {
+ exclusions = ids(values);
+ }
+
+ /** Item tags omitted from explicit and automatic contents. */
+ @ZenCodeType.Getter("excludeTags")
+ public String[] getExcludedTags() {
+ return strings(excludedTags);
+ }
+
+ /** Sets item tags omitted from explicit and automatic contents. */
+ @ZenCodeType.Setter("excludeTags")
+ public void setExcludedTags(String[] values) {
+ excludedTags = ids(values);
+ }
+
/**
* Tabs this one is placed before.
*
@@ -373,7 +429,8 @@ public void build() {
ScriptDefinitions.add(id,
new CreativeTabDefinition(Optional.ofNullable(title),
Optional.ofNullable(titleFallback), Optional.ofNullable(icon),
- contents, before, after, searchBar));
+ contents, before, after, searchBar, defaultForMod,
+ includeModItems, exclusions, excludedTags));
}
private static ResourceLocation tag(String text) {
diff --git a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java
index a6c5f3a9..58f669ca 100644
--- a/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java
+++ b/src/main/java/zone/moddev/mc/lib/machine/neoforge/MachineContent.java
@@ -7,11 +7,8 @@
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
-import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
-import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
-import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraft.world.level.block.state.BlockBehaviour;
import net.minecraft.world.level.material.Fluids;
@@ -232,18 +229,6 @@ private static void registries(RegisterEvent event) {
helper.register(id, type);
entities.put(id, type);
}));
- event.register(Registries.CREATIVE_MODE_TAB, helper -> {
- if (!definitions.isEmpty())
- helper.register(ResourceLocation.parse("mmdlib:data_machines"),
- CreativeModeTab.builder()
- .title(Component.literal("Data-defined Machines"))
- .icon(() -> new ItemStack(
- blocks.values().iterator().next()))
- .displayItems((parameters, output) -> {
- blocks.values().forEach(output::accept);
- output.accept(recoveryItem());
- }).build());
- });
}
private static void capabilities(RegisterCapabilitiesEvent event) {
diff --git a/src/main/resources/assets/mmdlib/lang/en_us.json b/src/main/resources/assets/mmdlib/lang/en_us.json
index b9afe963..699a8337 100644
--- a/src/main/resources/assets/mmdlib/lang/en_us.json
+++ b/src/main/resources/assets/mmdlib/lang/en_us.json
@@ -1,4 +1,5 @@
{
+ "itemGroup.mmdlib.main": "MMDLib",
"screen.mmdlib.face.unavailable": "Unavailable on this machine",
"screen.mmdlib.tank.name": "Tank %s",
"screen.mmdlib.tank.empty": "Empty",
diff --git a/src/main/resources/data/mmdlib/tags/item/internal_items.json b/src/main/resources/data/mmdlib/tags/item/internal_items.json
new file mode 100644
index 00000000..2a19ef12
--- /dev/null
+++ b/src/main/resources/data/mmdlib/tags/item/internal_items.json
@@ -0,0 +1,4 @@
+{
+ "replace": false,
+ "values": ["mmdlib:machine_recovery_capsule"]
+}
diff --git a/src/main/resources/mmdlib/creative_tab/main.xml b/src/main/resources/mmdlib/creative_tab/main.xml
new file mode 100644
index 00000000..93a64ae2
--- /dev/null
+++ b/src/main/resources/mmdlib/creative_tab/main.xml
@@ -0,0 +1,6 @@
+
+
+
+
diff --git a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CreativeTabSmoke.java b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CreativeTabSmoke.java
index d0da915e..c880d4c0 100644
--- a/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CreativeTabSmoke.java
+++ b/src/runtimeTest/java/zone/moddev/mc/lib/smoke/CreativeTabSmoke.java
@@ -57,6 +57,86 @@ static void workshop(ServerLevel level) {
&& "MMDLib Test Workshop".equals(title.getFallback()),
"the default title key, with the fallback");
require(MMDLib.creativeTabs().containsKey(id), "the tab is listed");
+ automaticItems(level);
+ fallbackRegistration(level);
+ }
+
+ private static void fallbackRegistration(ServerLevel level) {
+ var tabs = BuiltInRegistries.CREATIVE_MODE_TAB;
+ require(
+ !tabs.containsKey(ResourceLocation.parse("mmdlib:materials"))
+ && !tabs.containsKey(
+ ResourceLocation.parse("mmdlib:mmdlib_content")),
+ "authored main tab prevents both generated placeholder tabs");
+ var fallback = tabs
+ .get(ResourceLocation.parse("mmdlib_smoke:materials"));
+ require(
+ fallback != null && !tabs.containsKey(
+ ResourceLocation.parse("mmdlib_smoke:mmdlib_content")),
+ "a registrar without its own tab receives exactly one materials fallback");
+ require(
+ fallback.getDisplayName()
+ .getContents() instanceof TranslatableContents title
+ && title.getKey().equals("itemGroup.mmdlib_smoke.materials"),
+ "registrar fallback retains the legacy materials translation key");
+ fallback.buildContents(new CreativeModeTab.ItemDisplayParameters(
+ level.enabledFeatures(), false, level.registryAccess()));
+ var expected = RuntimeContentRegistrar.instances().stream()
+ .flatMap(registrar -> registrar.items().keySet().stream())
+ .filter(item -> item.getNamespace().equals("mmdlib_smoke"))
+ .collect(java.util.stream.Collectors.toSet());
+ var shown = fallback.getDisplayItems().stream()
+ .map(stack -> BuiltInRegistries.ITEM.getKey(stack.getItem()))
+ .toList();
+ require(
+ !expected.isEmpty()
+ && new java.util.HashSet<>(shown).equals(expected)
+ && shown.size() == expected.size(),
+ "cached routing fills the fallback with each generated item exactly once");
+ }
+
+ private static void automaticItems(ServerLevel level) {
+ var id = ResourceLocation.parse("mmdlib:test/automatic");
+ var excluded = java.util.Set.of(
+ ResourceLocation.parse("mmdlib:iron_gear"),
+ ResourceLocation.parse("mmdlib:machine_recovery_capsule"));
+ var tab = BuiltInRegistries.CREATIVE_MODE_TAB.get(id);
+ require(tab != null, "automatic XML tab registered");
+ for (int rebuild = 0; rebuild < 2; rebuild++) {
+ tab.buildContents(new CreativeModeTab.ItemDisplayParameters(
+ level.enabledFeatures(), false, level.registryAccess()));
+ var shown = tab.getDisplayItems().stream()
+ .map(stack -> BuiltInRegistries.ITEM.getKey(stack.getItem()))
+ .toList();
+ var expected = BuiltInRegistries.ITEM.keySet().stream()
+ .filter(item -> item.getNamespace().equals("mmdlib")
+ && !excluded.contains(item))
+ .filter(item -> BuiltInRegistries.ITEM.get(item)
+ .isEnabled(level.enabledFeatures()))
+ .collect(java.util.stream.Collectors.toSet());
+ require(
+ new java.util.HashSet<>(shown).equals(expected)
+ && shown.size() == expected.size(),
+ "all enabled own-mod items appear once, and exclusions override item, tag, material and automatic entries");
+ require(
+ shown.getFirst().equals(
+ ResourceLocation.parse("mmdlib:iron_molten_bucket")),
+ "explicit favorite stays first even when also automatically included");
+ require(
+ tab.getSearchTabDisplayItems().stream()
+ .noneMatch(stack -> excluded.contains(
+ BuiltInRegistries.ITEM.getKey(stack.getItem()))),
+ "excluded items are not contributed to search");
+ var main = BuiltInRegistries.CREATIVE_MODE_TAB
+ .get(ResourceLocation.parse("mmdlib:main"));
+ main.buildContents(new CreativeModeTab.ItemDisplayParameters(
+ level.enabledFeatures(), false, level.registryAccess()));
+ require(
+ main.getDisplayItems().stream()
+ .noneMatch(stack -> excluded.contains(
+ BuiltInRegistries.ITEM.getKey(stack.getItem()))),
+ "nested tag exclusions also prevent default routing from restoring generated items");
+ }
}
/** The script's tab: an apple, then the gold material, and no stick. */
diff --git a/src/runtimeTest/resources/data/mmdlib/tags/item/internal_items.json b/src/runtimeTest/resources/data/mmdlib/tags/item/internal_items.json
new file mode 100644
index 00000000..580d9dba
--- /dev/null
+++ b/src/runtimeTest/resources/data/mmdlib/tags/item/internal_items.json
@@ -0,0 +1,4 @@
+{
+ "replace": false,
+ "values": ["#mmdlib:test/internal_items", "mmdlib:machine_recovery_capsule"]
+}
diff --git a/src/runtimeTest/resources/data/mmdlib/tags/item/test/internal_items.json b/src/runtimeTest/resources/data/mmdlib/tags/item/test/internal_items.json
new file mode 100644
index 00000000..adda96fd
--- /dev/null
+++ b/src/runtimeTest/resources/data/mmdlib/tags/item/test/internal_items.json
@@ -0,0 +1,4 @@
+{
+ "replace": false,
+ "values": ["#mmdlib:test/workshop_gear"]
+}
diff --git a/src/runtimeTest/resources/mmdlib/creative_tab/test/automatic.xml b/src/runtimeTest/resources/mmdlib/creative_tab/test/automatic.xml
new file mode 100644
index 00000000..7126e089
--- /dev/null
+++ b/src/runtimeTest/resources/mmdlib/creative_tab/test/automatic.xml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
diff --git a/src/test/java/zone/moddev/mc/lib/common/builders/DefinitionLoaderTest.java b/src/test/java/zone/moddev/mc/lib/common/builders/DefinitionLoaderTest.java
index 4e363cc4..07a35e98 100644
--- a/src/test/java/zone/moddev/mc/lib/common/builders/DefinitionLoaderTest.java
+++ b/src/test/java/zone/moddev/mc/lib/common/builders/DefinitionLoaderTest.java
@@ -300,7 +300,23 @@ void loadsCreativeTabs() throws Exception {
"icon": "alpha:hammer",
"contents": ["alpha:hammer", "#c:ingots", {"material": "alpha:copper"}],
"before": ["minecraft:combat"], "after": ["minecraft:tools_and_utilities"],
- "search_bar": true}
+ "search_bar": true, "default_for_mod": true,
+ "include_mod_items": true, "exclude": ["alpha:internal"],
+ "exclude_tags": ["alpha:internal_items"]}
+ """);
+ write(root, "creative_tab/nested/xml.xml",
+ """
+
+
+
+
+
+
+
+
+
""");
write(root, "creative_tab/misc/odds.json",
"{\"contents\": [{\"material\": \"alpha:tin\"}]}");
@@ -314,12 +330,37 @@ void loadsCreativeTabs() throws Exception {
.icon(id("alpha:hammer")).item(id("alpha:hammer"))
.tag(id("c:ingots")).material(id("alpha:copper"))
.before(id("minecraft:combat"))
- .after(id("minecraft:tools_and_utilities")).searchBar().build();
+ .after(id("minecraft:tools_and_utilities")).searchBar()
+ .defaultForMod().includeModItems().exclude(id("alpha:internal"))
+ .excludeTag(id("alpha:internal_items")).build();
require(tools.equals(built));
+ require(tabs.get(id("alpha:nested/xml")).equals(built));
var odds = tabs.get(id("alpha:misc/odds"));
require(odds.titleKey(id("alpha:misc/odds"))
.equals("itemGroup.alpha.misc.odds") && odds.icon().isEmpty()
- && !odds.searchBar() && odds.before().isEmpty());
+ && !odds.searchBar() && odds.before().isEmpty()
+ && !odds.includeModItems() && odds.exclusions().isEmpty()
+ && odds.excludedTags().isEmpty());
+
+ var empty = temporary.resolve("empty/mmdlib");
+ for (String fields : List.of("", ", \"contents\": []",
+ ", \"content\": [\"alpha:hammer\"]")) {
+ write(empty, "creative_tab/empty.json",
+ "{\"icon\": \"alpha:hammer\"" + fields + "}");
+ expectFailure(() -> DefinitionLoader.load(
+ List.of(new SourceRoot("empty", empty, loader)), api(),
+ mod -> false), "empty.json", "needs contents");
+ }
+ for (String flag : List.of("default_for_mod",
+ "include_mod_items")) {
+ write(empty, "creative_tab/empty.json",
+ "{\"icon\": \"alpha:hammer\", \"" + flag + "\": true}");
+ require(DefinitionLoader
+ .load(List.of(new SourceRoot("empty", empty, loader)),
+ api(), mod -> false)
+ .creativeTabs().get(id("empty:empty")).contents()
+ .isEmpty());
+ }
var bad = temporary.resolve("bad/mmdlib");
write(bad, "creative_tab/tags.json",
@@ -333,6 +374,14 @@ void loadsCreativeTabs() throws Exception {
expectFailure(() -> DefinitionLoader.load(
List.of(new SourceRoot("worse", worse, loader)), api(),
mod -> false), "broken.json");
+ write(root, "creative_tab/tools.xml",
+ """
+
+ """);
+ expectFailure(() -> DefinitionLoader.load(
+ List.of(new SourceRoot("alpha", root, loader)), api(),
+ mod -> false), "tools.json", "tools.xml");
} finally {
try (var paths = Files.walk(temporary)) {
for (var path : paths
diff --git a/src/test/java/zone/moddev/mc/lib/common/loading/CreativeTabXmlTest.java b/src/test/java/zone/moddev/mc/lib/common/loading/CreativeTabXmlTest.java
new file mode 100644
index 00000000..b96509f2
--- /dev/null
+++ b/src/test/java/zone/moddev/mc/lib/common/loading/CreativeTabXmlTest.java
@@ -0,0 +1,73 @@
+package zone.moddev.mc.lib.common.loading;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import java.util.List;
+
+import net.minecraft.resources.ResourceLocation;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+class CreativeTabXmlTest {
+ @TempDir
+ Path directory;
+
+ @Test
+ void includesOwningModWithoutIndividualItemEntries() throws Exception {
+ var path = directory.resolve("main.xml");
+ Files.writeString(path, xml(
+ "version=\"1\" icon=\"example:item\" include-mod-items=\"true\"",
+ ""));
+ var definition = CreativeTabXml.read(path);
+ assertTrue(definition.includeModItems());
+ assertTrue(definition.contents().isEmpty());
+ assertEquals(List.of(ResourceLocation.parse("example:internal")),
+ definition.exclusions());
+ assertEquals(List.of(ResourceLocation.parse("example:internal_items")),
+ definition.excludedTags());
+ }
+
+ @Test
+ void rejectsInvalidDefinitionsWithFileDiagnostic() throws Exception {
+ var path = directory.resolve("main.xml");
+ for (String invalid : List.of(
+ "",
+ xml("version=\"1\" icon=\"example:item\"", ""),
+ xml("version=\"2\" icon=\"example:item\"", ""),
+ xml("version=\"1\" search-bar=\"yes\" icon=\"example:item\"", ""),
+ xml("version=\"1\" include-mod-items=\"yes\" icon=\"example:item\"",
+ ""),
+ xml("version=\"1\" icon=\"example:item\"", ""),
+ xml("version=\"1\" icon=\"example:item\"",
+ ""),
+ xml("version=\"1\" icon=\"example:item\"", ""),
+ xml("version=\"1\" icon=\"example:item\"",
+ ""),
+ xml("version=\"1\" default-for-mode=\"true\" icon=\"example:item\"",
+ ""),
+ xml("version=\"1\" icon=\"example:item\"",
+ ""),
+ xml("version=\"1\"", " "),
+ xml("version=\"1\"", ""),
+ xml("version=\"1\"",
+ " "),
+ "]>" + xml(
+ "version=\"1\" icon=\"example:item\" title=\"&title;\"", ""))) {
+ Files.writeString(path, invalid);
+ var error = assertThrows(IllegalArgumentException.class,
+ () -> CreativeTabXml.read(path), invalid);
+ assertTrue(error.getMessage().contains(path.toString()));
+ }
+ }
+
+ private static String xml(String attributes, String children) {
+ return "" + children + "";
+ }
+}
diff --git a/src/test/java/zone/moddev/mc/lib/common/runtime/ModCreativeTabsTest.java b/src/test/java/zone/moddev/mc/lib/common/runtime/ModCreativeTabsTest.java
new file mode 100644
index 00000000..0c6eaa6a
--- /dev/null
+++ b/src/test/java/zone/moddev/mc/lib/common/runtime/ModCreativeTabsTest.java
@@ -0,0 +1,96 @@
+package zone.moddev.mc.lib.common.runtime;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.util.List;
+import java.util.Map;
+
+import net.minecraft.resources.ResourceLocation;
+
+import org.junit.jupiter.api.Test;
+
+import zone.moddev.mc.lib.common.types.CreativeTabDefinition;
+
+class ModCreativeTabsTest {
+ @Test
+ void explicitDefaultWinsAndStaysWithinOwnerNamespace() {
+ var definitions = Map.of(id("example:tools"), definition(),
+ id("other:main"), definition());
+ var tabs = List.of(id("example:machines"), id("example:tools"),
+ id("other:main"));
+ assertEquals(id("example:tools"),
+ ModCreativeTabs.choose("example", definitions, tabs).orElseThrow());
+ assertTrue(
+ ModCreativeTabs.choose("absent", definitions, tabs).isEmpty());
+ assertTrue(ModCreativeTabs
+ .choose("example", definitions, List.of(id("example:machines")))
+ .isEmpty());
+ }
+
+ @Test
+ void javaTabsTakePrecedenceOverGeneratedFallbacks() {
+ var tabs = List.of(id("example:mmdlib_content"),
+ id("example:materials"), id("example:tools"),
+ id("example:machines"), id("other:main"));
+ assertEquals(id("example:machines"),
+ ModCreativeTabs.choose("example", Map.of(), tabs).orElseThrow());
+ assertEquals(id("example:materials"), ModCreativeTabs
+ .choose("example", Map.of(), tabs.subList(0, 2)).orElseThrow());
+ assertEquals(id("example:mmdlib_content"), ModCreativeTabs
+ .choose("example", Map.of(), tabs.subList(0, 1)).orElseThrow());
+ }
+
+ @Test
+ void rejectsAmbiguousDefaults() {
+ var definitions = Map.of(id("example:tools"), definition(),
+ id("example:machines"), definition());
+ assertThrows(IllegalArgumentException.class, () -> ModCreativeTabs
+ .choose("example", definitions, definitions.keySet()));
+ }
+
+ @Test
+ void fallbackOnlyExistsWhenTheOwnerHasNoDeclaredOrRegisteredTab() {
+ assertTrue(ModCreativeTabs.needsFallback("example",
+ List.of(id("other:main")), List.of(id("minecraft:combat"))));
+ for (String path : List.of("main", "machines", "tools", "materials",
+ "mmdlib_content")) {
+ var own = List.of(id("example:" + path));
+ assertFalse(
+ ModCreativeTabs.needsFallback("example", own, List.of()));
+ assertFalse(
+ ModCreativeTabs.needsFallback("example", List.of(), own));
+ }
+ }
+
+ @Test
+ void materialsFallbackPreservesItsConsumerTranslationKey() {
+ var title = (net.minecraft.network.chat.contents.TranslatableContents) ModCreativeTabs
+ .fallbackTitle("example", "Example Mod", true).getContents();
+ assertEquals("itemGroup.example.materials", title.getKey());
+ assertEquals("Example Mod", title.getFallback());
+ var general = (net.minecraft.network.chat.contents.TranslatableContents) ModCreativeTabs
+ .fallbackTitle("example", "Example Mod", false).getContents();
+ assertEquals("itemGroup.example", general.getKey());
+ }
+
+ @Test
+ void emptyBuilderRequiresAutomaticContents() {
+ assertThrows(IllegalArgumentException.class, () -> CreativeTabDefinition
+ .builder().icon(id("minecraft:stone")).build());
+ assertTrue(CreativeTabDefinition.builder().icon(id("minecraft:stone"))
+ .includeModItems().build().contents().isEmpty());
+ assertTrue(definition().contents().isEmpty());
+ }
+
+ private static CreativeTabDefinition definition() {
+ return CreativeTabDefinition.builder().icon(id("minecraft:stone"))
+ .defaultForMod().build();
+ }
+
+ private static ResourceLocation id(String value) {
+ return ResourceLocation.parse(value);
+ }
+}