diff --git a/wiki/concepts/block/Block/en.yml b/wiki/concepts/block/Block/en.yml new file mode 100644 index 00000000..613014b0 --- /dev/null +++ b/wiki/concepts/block/Block/en.yml @@ -0,0 +1,4 @@ +title: "Block" +description: "The base representation of a Minecraft block" + +optional: "#[[#c3c7cb;border:1px solid #51565d;font-size:0.8rem;padding:0.2em 0.3em; border-radius: 1em|Optional]]" \ No newline at end of file diff --git a/wiki/concepts/block/Block/page.kubedoc b/wiki/concepts/block/Block/page.kubedoc new file mode 100644 index 00000000..0c916aca --- /dev/null +++ b/wiki/concepts/block/Block/page.kubedoc @@ -0,0 +1,10 @@ +# Creating Blocks + +In places where `Block`s are expected, KubeJS will convert strings representing the blocks' ID into `Block` instances. + +For example: `[js]'minecraft:stone'`. + +# Useful Block methods + +In the following examples, `[js]block` will refer to the instance of `Block`. + diff --git a/wiki/concepts/block/BlockState/en.yml b/wiki/concepts/block/BlockState/en.yml new file mode 100644 index 00000000..7c0ffbec --- /dev/null +++ b/wiki/concepts/block/BlockState/en.yml @@ -0,0 +1,4 @@ +title: "BlockState" +description: "Block with states!" + +optional: "#[[#c3c7cb;border:1px solid #51565d;font-size:0.8rem;padding:0.2em 0.3em; border-radius: 1em|Optional]]" \ No newline at end of file diff --git a/wiki/concepts/block/BlockState/page.kubedoc b/wiki/concepts/block/BlockState/page.kubedoc new file mode 100644 index 00000000..7d4f7579 --- /dev/null +++ b/wiki/concepts/block/BlockState/page.kubedoc @@ -0,0 +1,6 @@ +# Creating BlockStates + +In places where `BlockState`s are expected, KubeJS will try to implicitly convert other objects into them. +Most `BlockState`s can be written as string literals, with block property syntax being the same as one used in [`/setblock` or `/fill`](https://minecraft.wiki/w/Argument_types#minecraft:block_state). + +# Useful BlockState methods \ No newline at end of file diff --git a/wiki/concepts/block/LevelBlock/en.yml b/wiki/concepts/block/LevelBlock/en.yml new file mode 100644 index 00000000..01760a48 --- /dev/null +++ b/wiki/concepts/block/LevelBlock/en.yml @@ -0,0 +1,4 @@ +title: "LevelBlock" +description: "A representation of a block in world" + +optional: "#[[#c3c7cb;border:1px solid #51565d;font-size:0.8rem;padding:0.2em 0.3em; border-radius: 1em|Optional]]" \ No newline at end of file diff --git a/wiki/concepts/block/LevelBlock/page.kubedoc b/wiki/concepts/block/LevelBlock/page.kubedoc new file mode 100644 index 00000000..2653ab8e --- /dev/null +++ b/wiki/concepts/block/LevelBlock/page.kubedoc @@ -0,0 +1,203 @@ +**LevelBlock** is a KubeJS interface defining the script-friendly abstraction of a block in world. LevelBlocks can be easily manipulated to your heart's content. + +# How to get LevelBlocks + +`LevelBlock`s are usually obtained via block-getting methods on `Level` (object representing the Minecraft world), such as `[js]level.getBlock(x, y, z)`. + +# Useful LevelBlock methods + +In the following examples, `[js]block` will refer to the instance of `LevelBlock`. + +## Position + +| Getter | Read-only bean | Description | +| `[js]block.getPos()` | `[js]block.pos` | Gets the position of the block, as BlockPos. | +| `[js]block.getX()` | `[js]block.x` | Gets the x coordinate of the block. | +| `[js]block.getY()` | `[js]block.y` | Gets the y coordinate of the block. | +| `[js]block.getZ()` | `[js]block.z` | Gets the z coordinate of the block. | +| `[js]block.getCenterX()` | `[js]block.centerX` | Gets the x coordinate of the center of the block. | +| `[js]block.getCenterY()` | `[js]block.centerY` | Gets the y coordinate of the center of the block. | +| `[js]block.getCenterZ()` | `[js]block.centerZ` | Gets the z coordinate of the center of the block. | + +**Example** +Position related beans on `LevelBlock` make for a useful application of a [destructuring pattern](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring) to quickly get all the block's coordinates to variables. + +```js +const { x, y, z } = block +// Now x, y and z constants are respectively the block's x, y and z coordinate. +``` + +--- + +## Relative + +>>> #get-north +Gets the block to the north of the `block`. +<<< +>>> #get-south +Gets the block to the south of the `block`. +<<< +>>> #get-east +Gets the block to the east of the `block`. +<<< +>>> #get-west +Gets the block to the west of the `block`. +<<< +>>> #get-up +Gets the block above the `block`. +<<< +>>> #get-down +Gets the block below the `block`. +<<< + +These getters allow you to get blocks around the currently referenced block, as `LevelBlock`s. + +| Getter | Read-only bean | Description | +| `[js]block.getNorth()` | `[js]block.north` | <#get-north> | +| `[js]block.getSouth()` | `[js]block.south` | <#get-south> | +| `[js]block.getEast()` | `[js]block.east` | <#get-east> | +| `[js]block.getWest()` | `[js]block.west` | <#get-west> | +| `[js]block.getUp()` | `[js]block.up` | <#get-up> | +| `[js]block.getDown()` | `[js]block.down` | <#get-down> | +--- + +## Other + +### Accessors + +>>> #entity-data +Gets or sets the block entity data (as `CompoundTag`) of the block. The data get or set may be `null`. +<<< +>>> #block-state-note +Gets or sets the BlockState of the block. +**Note**: `setBlockState` also has an overload that allows for setting block update flags, see "Setters". +<<< + +| Getter | Setter | Bean | Description | +| `[js]block.getEntityData()` | `[js]block.setEntityData(entityData)` | `[js]block.entityData` | <#entity-data> | +| `[js]block.getBlockState()` | `[js]block.setBlockState(state)` | `[js]block.blockState` | <#block-state-note> | + +### Setters + +- `[js]block.set(block, properties, updateFlags)` + - `[js]block`: The Block to set the `block` to. It may be a string representing a block, for example `[js]'minecraft:oak_log'` + - `[js]properties` {optional}: Block properties to set on that block. It can be an object representing the block properties, for example `[js]\{ axis: 'x' \}` + - `[js]updateFlags` {optional}: Block update flags. They are a bit map of update properties. + +- `[js]block.setBlockState(blockState, updateFlags)` + - `[js]blockState`: The BlockState to set the `block` to. It may be a string representing a block state, for example `[js]'minecraft:oak_log\[axis=x\]'` + - `[js]updateFlags` {optional}: Block update flags. They are a bit map of update properties. + +### Getters + +>>> #players-in-radius-note +Gets a list of all player entities in an 8-block radius, excluding fake players. +**Note**: `getPlayersInRadius` also has an overload with customizable radius, see below this table. +<<< +>>> #inventory-note +Gets the block's inventory (as `InventoryKJS`) accessible from the top of the block. +Will get `[js]null` if the block does not have an inventory. +**Note**: `getInventory` also has an overload with customizable access side, see below this table. +<<< +>>> #can-see-sky +Gets `true` if block can see sky, `false` if it can't. +<<< +>>> #drops-note +Gets the block's drops that are independent of entity and item held (as a list of [[/concepts/item-stack|ItemStacks]]). +Will get an empty list if the block is not on a server-side world. +**Note**: `getDrops` also has an overload with customizable entity and item, see below this table. +<<< + +**Parameterless (with beans)** + +| Getter | Read-only bean | Description | +| `[js]block.getBiomeId()` | `[js]block.biomeId` | Gets the biome ID as ResourceLocation. | +| `[js]block.getBlock()` | `[js]block.block` | Gets the Block of the block. | +| `[js]block.getBlockLight()` | `[js]block.blockLight` | Gets the block's block light level. | +| `[js]block.getCanSeeSky()` | `[js]block.canSeeSky` | <#can-see-sky> | +| `[js]block.getDimension()` | `[js]block.dimension` | Gets the dimension of the block. | +| `[js]block.getDimensionKey()` | `[js]block.dimensionKey` | Gets the dimension key of the block. | +| `[js]block.getDrops()` | `[js]block.drops` | <#drops-note> | +| `[js]block.getEntity()` | `[js]block.entity` | Gets the block entity of the block. | +| `[js]block.getEntityId()` | `[js]block.entityId` | Gets the block entity ID (as ResourceLocation) of the block. | +| `[js]block.getId()` | `[js]block.id` | Gets the block's ID as string. | +| `[js]block.getIdLocation()` | `[js]block.idLocation` | Gets the block's ID as ResourceLocation. | +| `[js]block.getInventory()` | `[js]block.inventory` | <#inventory-note> | +| `[js]block.getItem()` | `[js]block.item` | Gets the ItemStack corresponding to this block. | +| `[js]block.getKey()` | `[js]block.key` | Gets the block's ResourceKey. | +| `[js]block.getLevel()` | `[js]block.level` | Gets the world the block is in. | +| `[js]block.getLight()` | `[js]block.light` | Gets the block's light level. | +| `[js]block.getMod()` | `[js]block.mod` | Gets the block's mod ID as string. | +| `[js]block.getPlayersInRadius()` | `[js]block.playersInRadius` | <#players-in-radius-note> | +| `[js]block.getProperties()` | `[js]block.properties` | Gets the block's properties. | +| `[js]block.getRegistry()` | `[js]block.registry` | Gets the block registry. | +| `[js]block.getRegistryId()` | `[js]block.registryId` | Gets the block's ResourceKey from the block registry. | +| `[js]block.getSkyLight()` | `[js]block.skyLight` | Gets the block's sky light level. | +| `[js]block.getTagKeys()` | `[js]block.tagKeys` | Gets the list of block's TagKeys. | +| `[js]block.getTags()` | `[js]block.tags` | Gets the list of block's tags as ResourceLocations. | +| `[js]block.getTypeData()` | `[js]block.typeData` | ??? | + +**With parameters** + +- `[js]block.getInventory()` +- `[js]block.getInventory(direction)` + - `[js]direction` {optional}: A `Direction`. In can be a string representing a direction, for example `[js]'north'`. Defaults to `[js]'up'` if not provided. + - **Returns**: The block's inventory (as `InventoryKJS`) accessible from the specified side. Will get `[js]null` if the block does not have an inventory. + +- `[js]block.getDrops()` +- `[js]block.getDrops(entity, heldItem)` + - `[js]entity`: The [[/concepts/entity|`Entity`]] that would break the block. Defaults to `[js]null` if not provided. There's no overload without `heldItem`, so it must be provided too, regardless whether you want to use an item or not. + - `[js]heldItem`: The held item (as [[/concepts/item-stack|ItemStack]]) that would break the block. Defaults to air if not provided. + - **Returns**: The block's drops as a list of [[/concepts/item-stack|ItemStacks]], if the block is on a server-side world, an empty list otherwise. + - This method doesn't break the block, it just simulates the drops for that block. + +- `[js]block.getPlayersInRadius()` +- `[js]block.getPlayersInRadius(radius)` + - `[js]radius` {optional}: The radius around the `block` to search players for. Defaults to `8` if not provided. + - **Returns**: All players found (as a list of [[/concepts/entity|Entities]]), excluding fake players. + - ==Guarantee==: Entities in this list are guaranteed to be [[/concepts/player|Players]], so documentation for [[/concepts/player|Player]] applies to those entities as well. + +### Other methods + +- `[js]block.offset(direction)` +- `[js]block.offset(direction, amount)` + - `[js]direction`: A `Direction`. In can be a string representing a direction, for example `[js]'north'` + - `[js]amount` {optional}: Amount of blocks to move away from the `block`. Defaults to `1` if not provided. +- `[js]block.offset(x, y, z)` + - `[js]x`, `[js]y`, `[js]z`: Amount of blocks to move from the `block` in x, y and z directions respectively. + - **Returns**: A `LevelBlock` representing a block at a specified offset. + +- `[js]block.mergeEntityData(entityData)` + - `[js]entityData`: The block entity data (as `CompoundTag`) to merge with existing entity data. + +- `[js]block.explode(explosionProperties)` + - `[js]explosionProperties`: The [[/ref/records/ExplosionProperties|explosion properties]] to use. + - **Returns**: An `Explosion` object. Also creates an explosion at the location of the block. + +- `[js]block.createEntity(entityType)` + - `[js]entityType`: The type of entity to create. It may be a string representing an entity, for example `[js]'minecraft:creeper'` + - **Returns**: An new [[/concepts/entity|`Entity`]] object with its position set to the position of the `block` (not its center!). Of course, you still need to spawn the entity, so don't discard the return type! + +- `[js]block.spawnLightning()` +- `[js]block.spawnLightning(isEffectOnly)` +- `[js]block.spawnLightning(isEffectOnly, player)` + - `[js]isEffectOnly` {optional}: Whether the lightning is purely visual (that is, harmless). Defaults to `[js]false` if not provided. + - `[js]player` {optional}: A player who caused the lightning. + - Results in a Lightning Bolt spawned at the center of the `block`, optionally with above properties set. + +- `[js]block.spawnFireworks(fireworksProperties, flightTime)` + - `[js]fireworksProperties`: The [[/ref/records/Fireworks|firework properties]] to use. + - `[js]flightTime`: Flight time of the firework, in ticks. + - Results in a firework launched from the center of the `block`, with above properties set. + +- `[js]block.popItem(item)` + - `[js]item`: The item to pop from the block (as [[/concepts/item-stack|ItemStack]]). + - Results in the specified `[js]item` being popped as an item entity from the location of the block. + +- `[js]block.popItemFromFace(item, direction)` + - `[js]item`: The item to pop from the block (as [[/concepts/item-stack|ItemStack]]). + - `[js]direction`: A `Direction`. It can be a string representing a direction, for example `[js]'north'` + - Results in the specified `[js]item` being popped as an item entity from the specified side from the location of the block. + +- `[js]block.toBlockStateString()` + - **Returns**: The block's state as a string, with syntax being the same as one used in [`/setblock` or `/fill`](https://minecraft.wiki/w/Argument_types#minecraft:block_state). diff --git a/wiki/concepts/block/en.yml b/wiki/concepts/block/en.yml new file mode 100644 index 00000000..e099215b --- /dev/null +++ b/wiki/concepts/block/en.yml @@ -0,0 +1,4 @@ +title: "Block" +description: "It wouldn't be Minecraft if not for blocks!" + +optional: "#[[#c3c7cb;border:1px solid #51565d;font-size:0.8rem;padding:0.2em 0.3em; border-radius: 1em|Optional]]" \ No newline at end of file diff --git a/wiki/concepts/block/page.kubedoc b/wiki/concepts/block/page.kubedoc new file mode 100644 index 00000000..b391b0fb --- /dev/null +++ b/wiki/concepts/block/page.kubedoc @@ -0,0 +1,13 @@ +**Blocks** are the very foundation of a Minecraft block. + +In the game, their role is split into the following Java objects: +- [[/concepts/block/Block|`Block`]] - which are the singleton objects defining block behavior. These aren't generally used in in-world interactions. + +- [[/concepts/block/BlockState|`BlockState`]] - which define additional properties attacked to a block (like axis, being waterlogged, orientation, etc.). These are actual objects stored in world, and can be manipulated. + +- [[/concepts/block/LevelBlock|`LevelBlock`]] - a special interface added by KubeJS which abstracts away common cases of manipulating blocks in world. + +# See also + + + diff --git a/wiki/concepts/data-components/page.kubedoc b/wiki/concepts/data-components/page.kubedoc index a6548659..e0fe1e08 100644 --- a/wiki/concepts/data-components/page.kubedoc +++ b/wiki/concepts/data-components/page.kubedoc @@ -1,6 +1,44 @@ WIP! +**Data components** are structured data consisting of key-value pairs, that define various properties of items and block entities, such as their name, lore, enchantments, inventory, etc. Data components can be attached to Items (and thus [[/concepts/item-stack|ItemStacks]]), and block entities. + +This article will discuss how you can create data component types and manipulate them. + +# Creating DataComponentMaps + +In places where DataComponentMap is expected (such as the second argument of `[js]Item.of(item, components)`), you can write: +- String literals with the same string format as you would use in [`/give`](https://minecraft.wiki/w/Argument_types#item_stack). +`minecraft` namespace may be omitted for Minecraft's own data components. + +Example: `[js]Item.of('minecraft:diamond_sword', '\[damage=2,lore=[{text:"This item is cool."}]\]')` + +- JS objects, representing the key-value pairs. Values will be converted into appropriate NBT objects. +`minecraft` namespace may be omitted for Minecraft's own data components. + +Example: `[js]Item.of('minecraft:diamond_sword', { damage: 2, lore: [{ text: "This item is cool." }] })` + +# Using DataComponentMaps + +In the following examples, `components` will refer to the DataComponentMap. + +- `[js]components.get(type)` + - `type` - A component type. It can be a string representing a type, for example `[js]'minecraft:lore'`. + - **Returns**: Value associated with the component type. +- `[js]components.has(type)` + - `type` - A component type. It can be a string representing a type, for example `[js]'minecraft:lore'`. + - **Returns**: `true` is the component has data associated with a type, `false` otherwise. +- `[js]components.isEmpty()` + - **Returns**: `true` is the component contains no data, `false` otherwise. +>>>info +Also available as a **read-only** bean: `components.empty`. +<<< +- `[js]components.keySet()` + - **Returns**: A set of all types (as implementations of `DataComponentType` interface) in the component map. +- `[js]components.size()` + - **Returns**: The amount of keys in the component map. + +Just like other read-only maps, `components` also contain `filter` and `forEach` methods. # Further Reading - [Minecraft Wiki: Data Component format](https://minecraft.wiki/w/Data_component_format) -- [Data Components | NeoForged docs](https://docs.neoforged.net/docs/1.21.1/items/datacomponents) +- [Data Components | NeoForge docs](https://docs.neoforged.net/docs/1.21.1/items/datacomponents) - [NBT Data](/concepts/nbt-data) \ No newline at end of file diff --git a/wiki/concepts/ingredient/page.kubedoc b/wiki/concepts/ingredient/page.kubedoc index b6e694b5..183fc702 100644 --- a/wiki/concepts/ingredient/page.kubedoc +++ b/wiki/concepts/ingredient/page.kubedoc @@ -4,63 +4,120 @@ This page was created with KubeJS 7.2 (for 1.21.1) in mind. Most of the informat We are working on creating alternate versions of this page for other versions of Minecraft. <<< -An `Ingredient` is a filter over items that is used to determine which item stacks are valid inputs for a given recipe. In their most basic form, they can either match a single item, a item tag, or any combination of the previous two (as a list). Additionally, more complex ingredients exist that allow filtering by creative tab or mod name, or let you subtract one ingredient from another, as elaborated on below. +An `Ingredient` is a filter over items that is used to determine which item stacks are valid inputs for a given recipe. In their most basic form, they can either match a single item, an item tag, or any combination of the previous two (as a list). Additionally, more complex ingredients exist that allow filtering by creative tab or mod name, or let you subtract one ingredient from another, as elaborated on below. >>> info -Ingredients are **unstacked** by default, though NeoForge provides a `SizedIngredient` to fill that gap. SizedIngredients use the same syntax as ingredients, though additionally support a stack size (see [[/concepts/item-stack|`ItemStack`]] as well) during parsing. +Ingredients are **unstacked** by default, though NeoForge provides a `SizedIngredient` to fill that gap. SizedIngredients use the same syntax as ingredients, though additionally support a stack size (see [[/concepts/item-stack|`ItemStack`]] as well) during parsing. <<< # Creating Ingredients KubeJS will automatically try to *wrap* any input to an ingredient in places where it is expected, but you can also use the `Ingredient` wrapper ([source](https://github.com/KubeJS-Mods/KubeJS/blob/main/src/main/java/dev/latvian/mods/kubejs/plugin/builtin/wrapper/IngredientWrapper.java)) to explicitly create them yourself, specifically using the method `[js]Ingredient.of(input)`: ## Simple Ingredients -Most simple ingredient types may simply be written as a string, for example: -- `'-'` will return an ingredient that matches nothing, while `'*'` returns one that matches anything -- any item ID (such as `'minecraft:apple'`) will create an Ingredient that matches that specific item (ignoring data) -- any ID beginning with a `#` will match the tag with the given name, for example `'#c:ingots/iron'` will match all iron ingots -- an item ID followed by a **component filter** (using the same syntax as [`/give`](https://minecraft.wiki/w/Argument_types#item_stack)) creates an ingredient that matches that item with the given data +Most simple ingredient types may simply be written as string literals. +- `''` (empty string), `'-'`, `air` and `minecraft:air` will return an ingredient that matches nothing, while `'*'` returns one that matches anything. +- Any item ID will create an Ingredient that matches that specific item (ignoring data). + - Example: `[js]Ingredient.of('minecraft:apple')` +- Any ID beginning with a `#` will match the tag with the given name, for example `'#c:ingots/iron'` will match all iron ingots. + - Example: `[js]Ingredient.of('#c:ingots/copper')` + +>>> warn +Tag ingredients are not available in startup scripts! +<<< + +- An item ID followed by a **component filter** (using the same syntax as [`/give`](https://minecraft.wiki/w/Argument_types#item_stack)) creates an ingredient that matches that item with the given components + - Example: `[js]Ingredient.of('minecraft:diamond_sword[damage=2]')` - `'@modid'` will match all items added by the mod with the given mod ID + - Example: `[js]Ingredient.of('@create')` - `%` followed by an ID will match any items contained in the creative tab with that ID -- A regular expression (either using the JavaScript regex syntax or as a string) will match all items where the ID matches that regex, e.g. `[js]/minecraft:(gold|iron)_ingot/` will match bold Gold and Iron Ingots. + - Example: `[js]Ingredient.of('%minecraft:building_blocks')` +- A regular expression (either using the JavaScript regex syntax or as a string) will match all items where the ID matches that regex. + - Examples: + - `[js]Ingredient.of(/minecraft:(gold|iron)_ingot/)` + - `[js]Ingredient.of('/minecraft:(gold|iron)_ingot/')` + - Both of these will match both Gold and Iron Ingots. >>> quote Use [[/tutorials/hand|`/kubejs hand`]] to get some useful string representations of the item in your hand! <<< +## Sized ingredients +You can create sized ingredients from regular ones by either: +- in string syntax - prepending the ingredient with an integer number and a letter `x`. + - Example: `[js]Ingredient.of('2x minecraft:apple')` +- using `[js]Ingredient.of(ingredient, count)` + - Example: `[js]Ingredient.of('minecraft:apple', 2)` +- or by using the `withSize` method on ingredients. + - Example: `[js]Ingredient.of('minecraft:apple').withSize(2)` + ## Compound Ingredients As mentioned above, Ingredients may also be *nested* by using lists, which means that for example, ```js [ - "minecraft:apple", // either an apple - "#c:ingots/copper", // OR any copper ingot - "@create", // OR any item added by Create - "-" // OR nothing, which does... nothing + 'minecraft:apple', // either an apple + '#c:ingots/copper', // OR any copper ingot + '@create', // OR any item added by Create + '-' // OR nothing, which does... nothing ] ``` -is valid syntax and will match any item that fulfills ANY of these conditions. - -Additionally, if you want to create an `[js]Ingredient` that needs to match **multiple** conditions, you can use the method `[js]ingredient.and(other)` on an existing ingredient to create a so-called `IntersectionIngredient`: `[js]Ingredient.of('#c:ingots').and('@create')` for example will match any ingots that have been added by Create. +and: +```js +Ingredient.of('[minecraft:apple, #c:ingots/copper, @create, -]') +``` +are valid syntaxes and will match any item that fulfills ANY of these conditions. -Similarly, `[js]ingredient.except(other)` can be used on an ingredient to create a `SubtractionIngredient`, i.e. an ingredient that matches all items from the first ingredient that are NOT contained in the second ingredient. In the above example, replacing `and` with `except` would thus match any ingot NOT added by Create. +Additionally, if you want to create an `[js]Ingredient` that needs to match **multiple** conditions, you can use the method `[js]ingredient.and(other)` on an existing ingredient to create a so-called `IntersectionIngredient`: `[js]Ingredient.of('#c:ingots').and('@create')` for example will match any ingots that have been added by Create. -Finally, you can create a SizedIngredient directly by using `[js]Ingredient.of(ingredient, amount)`. +Similarly, `[js]ingredient.except(other)` can be used on an ingredient to create a `SubtractionIngredient`, i.e. an ingredient that matches all items from the first ingredient that are NOT contained in the second ingredient. In the above example, replacing `and` with `except` would thus match any ingot NOT added by Create. # Using Ingredients >>> danger -Ingredients are **lazily resolved** and will cache their results once tested. For this reason, we do __not__ allow using Ingredient in contexts where ItemStack is expected! +Ingredients are **lazily resolved** and will cache their results once tested. +For this reason, we do __not__ allow using Ingredient in contexts where ItemStack is expected! +<<< + +## Useful Methods + +- `[js]ingredient.and(other)`: + - `other` - Another ingredient. + - **Returns**: An ingredient accepting items that match both this ingredient and `other`. +- `[js]ingredient.or(other)`: + - `other` - Another ingredient. + - **Returns**: An ingredient accepting items that match this ingredient or `other`. +- `[js]ingredient.except(other)`: + - `other` - Another ingredient. + - **Returns**: An ingredient accepting items that match this ingredient, but not `other`. +- `[js]ingredient.withCount(count)` + - `count` - An integer specifying count of the ingredient. + - **Returns**: a `SizedIngredient` of this ingredient with the given count +- `[js]ingredient.asStack()` + - **Returns**: a `SizedIngredient` of size 1, equivalent to `[js]ingredient.withCount(1)` +- `[js]ingredient.test(item)`: + - `item`: The `ItemStack` to test whether it is a part of the ingredient. + - **Returns**: `true` if the provided item stack matches this ingredient, `false` otherwise. **This resolves the ingredient!** +- `[js]ingredient.getItems()` +- `[js]ingredient.getStackArray()` + - **Returns**: An array of all ItemStacks that match the ingredient. **This resolves the ingredient!** + +>>> info +Also available as **read-only** beans: `[js]ingredient.items`, `[js]ingredient.stackArray`. +<<< + +- `[js]ingredient.getStacks()` +- `[js]ingredient.getDisplayStacks()` + - **Returns**: An ItemStackSet of all ItemStacks that match the ingredient. **This resolves the ingredient!** + +>>> info +Also available as **read-only** beans: `[js]ingredient.stacks`, `[js]ingredient.displayStacks`. <<< -## Useful Methods and Properties -- `[js]ingredient.and(other)`: create an ingredient accepting items that match both this ingredient and `other` -- `[js]ingredient.or(other)`: create an ingredient accepting items that match this ingredient or `other` -- `[js]ingredient.except(other)`: create an ingredient accepting items that match this ingredient, but not `other` -- `[js]ingredient.withCount(count)`: Returns a `SizedIngredient` of this ingredient with the given count - - `[js]ingredient.asStack()` = `[js]ingredient.withCount(1)` -- `[js]ingredient.test(item)`: tests if the provided item stack matches this ingredient. **This resolves the ingredient!** -- `[js]ingredient.items`: **resolves** the ingredient and returns a list of all matching item stacks - - (`[js]ingredient.stacks`, `[js]ingredient.stackArray`, `[js]ingredient.displayStacks` are variants of this) -- `[js]ingredient.first`: **resolves** the ingredient and returns the first stack that matches it +- `[js]ingredient.getFirst()`: +- **Returns**: The first stack that matches the ingredient. **This resolves the ingredient!** + +>>> info +Also available as a **read-only** bean: `[js]ingredient.first`. +<<< # Further Reading - [Ingredients | NeoForged docs](https://docs.neoforged.net/docs/1.21.1/resources/server/recipes/ingredients/) \ No newline at end of file diff --git a/wiki/concepts/item-stack/en.yml b/wiki/concepts/item-stack/en.yml index 1ba6d222..60a31a46 100644 --- a/wiki/concepts/item-stack/en.yml +++ b/wiki/concepts/item-stack/en.yml @@ -1,2 +1,4 @@ title: "ItemStack" -description: "Item stacks, stacked items, items in a stack (sometimes with data, too)" \ No newline at end of file +description: "Item stacks, stacked items, items in a stack (sometimes with data, too)" + +optional: "#[[#c3c7cb;border:1px solid #51565d;font-size:0.8rem;padding:0.2em 0.3em; border-radius: 1em|Optional]]" \ No newline at end of file diff --git a/wiki/concepts/item-stack/page.kubedoc b/wiki/concepts/item-stack/page.kubedoc index 89332a2d..1151f062 100644 --- a/wiki/concepts/item-stack/page.kubedoc +++ b/wiki/concepts/item-stack/page.kubedoc @@ -4,64 +4,137 @@ This page was created with KubeJS 7.2 (for 1.21.1) in mind. Most of the informat We are working on creating alternate versions of this page for other versions of Minecraft. <<< -An `ItemStack` is an item associated with an amount and optionally some data attached to it. Or to put it slightly differently, it is... well, _a single stack_ of items that all share the same data. It is also the representation of an "item" that is most familiar to players, since item stacks are what you hold in your inventory, pick up from the ground, etc. +An `ItemStack` is an item associated with an amount and optionally some data attached to it. +Or to put it slightly differently, it is... well, *a single stack* of items that all share the same data. It is also the representation of an "item" that is most familiar to players, since item stacks are what you hold in your inventory, pick up from the ground, etc. -You may consider the `Item` contained in an `ItemStack` to basically just be the raw "definition" of what that item is; for example, all diamond axes share the same item ID `minecraft:diamond_axe`, they all use the same item, but two diamond axes with different amounts of damage in your inventory, like `diamond_axe[damage=123]` and `diamond_axe[damage=456]` would be part of different **item stacks** since their data doesn't overlap. Similarly, two sticks with custom lore `stick[lore=[{text:"This Stick is very sticky."}]]` would work as part of the same item stack. +You may consider the `Item` contained in an `ItemStack` to basically just be the raw "definition" of what that item is. +For example, all Diamond Axes share the same item ID `minecraft:diamond_axe`, they all use the same item, but two Diamond Axes with different amounts of damage in your inventory, like `minecraft:diamond_axe[damage=123]` and `minecraft:diamond_axe[damage=456]` would be part of different **item stacks** since their data doesn't overlap. +Similarly, two sticks with custom lore `minecraft:stick[lore=[{text:"This Stick is very sticky."}]]` would work as part of the same item stack. >>> quote -Since 1.20.4, data on items has changed *significantly* with the transition from NBT to data components. A neat side effect of this is that you can now change and override things that used to be hardcoded into the item definition itself, like the item's max stack size, enchantibility, repair ingredients, etc. +Since 1.20.4, data on items has changed *significantly* with the transition from NBT to data components. A neat side effect of this is that you can now change and override things that used to be hardcoded into the item definition itself, like the item's max stack size, enchantability, repair ingredients, etc. <<< # Creating ItemStacks -KubeJS will automatically try to *wrap* any input to an item stack in places where it is expected, but you can also use the `Item` wrapper ([source](https://github.com/KubeJS-Mods/KubeJS/blob/main/src/main/java/dev/latvian/mods/kubejs/plugin/builtin/wrapper/ItemWrapper.java)) to explicitly create them yourself, specifically using `[js]Item.of(input)` and `[js]Item.of(input, count)`: +KubeJS will automatically try to *wrap* any input to an item stack in places where it is expected, but you can also use the `Item` wrapper ([[/ref/wrappers/ItemWrapper|reference]]) to explicitly create them yourself, specifically using `[js]Item.of(input)` and `[js]Item.of(input, count)`: -In this case, the most simple way to write an item (and the one we recommend here) is by specifying its string ID, which you can most easily find by either enabling *advanced tooltips* in your game (press F3+H) and hovering over the item in your inventory, or by using the ever-useful [[/tutorials/hand|`/kubejs hand`]]! +Most ItemStacks can be simply written as string literals. -Here are some example string inputs that will parse to item stacks: +- `''` (empty string), `'-'`, `'air'` and `'minecraft:air'` will return an empty ItemStack. It doesn't seem particularly useful, but hey, it's there! +- Any item ID will create an ItemStack of that specific item. You can find item IDs easily by either enabling *advanced tooltips* in your game (press F3+H) and hovering over the item in your inventory, or by using the ever-useful [[/tutorials/hand|`/kubejs hand`]]! + - Example: `[js]Item.of('minecraft:apple')` +- Prepending the item ID with an integer number and a letter `x` will create an item stack, with the stack size equal to the specified integer number. + - Example: `[js]Item.of('2x minecraft:apple')` +- An item ID followed by a component (using the same syntax as [`/give`](https://minecraft.wiki/w/Argument_types#item_stack)) creates an item stack of the given item with the given components. + - Example: `[js]Item.of('minecraft:diamond_sword[damage=2]')` -- `[js]'minecraft:air'` is the empty item, which... doesn't seem particularly useful, but hey, maybe good to know still! -- `[js]'minecraft:apple'` is a single apple. (Note: If you're using vanilla items, the `minecraft:` may be omitted as well!) -- `[js]'2x minecraft:apple'` represents a stack of two apples together. -- `[js]'3x stick[lore=[{text:"This Stick is very sticky."}]]'` represents a stack of three very sticky sticks (with custom data components!) -Also note that while possible in some older versions of KubeJS, [[/concepts/ingredient|`Ingredient`]]s are **unsupported** and WILL now error if you try to convert them to an ItemStack implicitly, just use `ingredient.first`! +You can of course, combine these syntaxes: +- `[js]Item.of('3x minecraft:stick[lore=[{text:"This Stick is very sticky."}]])'` will result a stack of three very sticky sticks (with custom data components!) + +Also note that while possible in some older versions of KubeJS, [[/concepts/ingredient|`Ingredient`]]s are **unsupported** and WILL now error if you try to convert them to an ItemStack implicitly. If you want to explicitly convert an `Ingredient` into an `ItemStack`, use `ingredient.first`! # Using ItemStacks ## Useful Methods and Properties -- `[js]item.block`: If this item is a `BlockItem`, returns the associated block, else `null` -- `[js]item.count` (**writable**): The count of this item stack - - related: `[js]item.grow(amount)` and `[js]item.shrink(amount)` in- or decrease the current stack's count by `amount` - - related: `[js]item.withCount(count)`: Copies this stack with the specified `count` -- `[js]item.areItemsEqual(other)`: Returns `true` if `item` and `other` have the same item type -- `[js]item.areComponentsEqual(other)`: Returns `true` if `item` and `other` have the same item and data +- `[js]item.getBlock()`: + - **Returns**: The associated `Block` is the item corresponds to a block (that is - is an instance of `BlockItem`), otherwise `null`. +>>>info +Also available as a **read-only** bean: `item.block`. +<<< +- `[js]item.count` - Accessor for the stack size of the item. +>>>info +Also available as a getter `[js]item.setCount(count)` and setter `[js]item.getCount()`. +<<< +- `[js]item.grow(amount)` + - `amount` - Specifies, by how much should the stack size be increased. + - Returns nothing (`undefined`). + +- `[js]item.shrink(amount)` + - `amount` - Specifies, by how much should the stack size be decreased. + - Returns nothing (`undefined`). + +- `[js]item.withCount(count)` + - `count` - The stack size of the new item stack. + - **Returns** - A copy of the `item` with stack size of `count`. + +- `[js]item.areItemsEqual(other)`: + - `other`: An `ItemStack` to compare to. + - **Returns** `true` if `item` and `other` relate to the same item type, `false` otherwise. + +- `[js]item.areComponentsEqual(other)`: + - `other`: An `ItemStack` to compare to. + - **Returns** `true` if `item` and `other` relate to the same item and have **identical components**, `false` otherwise. ## Registry Object Functions -(these functions are all present on `Item` as well) -- `[js]item.id`: Returns the item's ID in the item registry (as a string) - - related: `[js]item.idLocation` (as `ResourceLocation`), `[js]item.key` (as `ResourceKey`) - - related: `[js]item.mod` returns *namespace* the item was registered for -- `[js]item.holder`: Wraps this item as a Holder (internal registry object) -- `[js]item.registry`: Returns the item registry - - related: `[js]item.registryId`: Returns the *key* of the item registry -- `[js]item.tags`: Returns a list of all tags for this item - - related: `[js]item.tagKeys`: Returns a list of `TagKey` instead of `ResourceLocation` - - related: `[js]item.hasTag(tag)`: Checks if this item has a certain tag +These functions are all inherited from `Item`. +Described here will be **read-only** beans, but be aware that for the `x` bean, `getX()` getter exists. + +- `[js]item.id`: Gets the item's ID in the item registry (as a string) +- `[js]item.idLocation`: Gets the item's ID in the item registry (as a `ResourceLocation`) +- `[js]item.key`: Gets the item's ID in the item registry (as a `ResourceKey`) +- `[js]item.mod`: Gets the **namespace** of an item. + - For example, for `item` being `minecraft:stone`, `item.mod` will be `minecraft`. + +- `[js]item.holder`: Gets the item wrapped into a Holder (internal registry object). +- `[js]item.registry`: Gets the item registry. +- `[js]item.registryId`: Gets the *key* of the item registry +- `[js]item.tags`: Gets a list of all tags for this item, as `ResourceLocation` objects. +- `[js]item.tagKeys`: Gets a list of all tags for this item, as `TagKey` objects. + +- `[js]item.hasTag(tag)`: Checks if this item has a certain tag. + - `tag` - A `ResourceLocation` or a string corresponding to a tag (for example `minecraft:logs`). + - **Returns**: `true` if the item has `tag` as a tag, `false` otherwise. ## Component Functions WIP! (TODO: make a page on Components and KubeJS' ComponentFunctions interface) -- `[js]componentString`: Returns the item's data components as a string representation -- `[js]withCustomName(name)`: Copies this item stack with the specified name -- `[js]enchantments`: Retrieves the item's enchantments -- `[js]hasEnchantment(enchantment, level)`: Checks if the item has a specific enchantment at or above a given level -- `[js]enchant(enchantment, level)`: Adds an enchantment to the ItemStack (TODO: enchantments page?) -- `[js]enchant(enchantments)`: Adds enchantments to the ItemStack (TODO: enchantments page?) -- `[js]getHarvestSpeed(block?)`: Gets the item's harvest speed for a given block (or default) -- `[js]typeData`: ??? (is this just a custom map for scripters to use to attach data to item definitions?) -- `[js]toItemString()`: Converts the ItemStack to its KubeJS string representation -- `[js]asIngredient()`: Converts the ItemStack to an `Ingredient` -- `[js]withLore(lore)`: Copies this item stack with the specified lore text +- `[js]item.components`: Gets a `DataComponentMap` (a map of item's components) of the item. +- `[js]item.componentString`: Gets a stringified representation of the item's components. + +- `[js]item.enchantments`: Retrieves the item's enchantments, as an `ItemEnchantments` object. +- `[js]item.hasEnchantment(enchantment, level)`: + - `enchantment`: The enchantment to check for. It may be a string representing an enchantment (like `minecraft:efficiency`). + - `level`: The level to compare to. + - **Returns**: `true` if the item has the given enchantment at a given level or higher, `false` otherwise. +- `[js]item.enchant(enchantment, level)`: + - `enchantment`: The enchantment to check for. It may be a string representing an enchantment (like `minecraft:efficiency`). + - `level`: The level of the enchantment + - **Returns**: A copy of `item` with the enchantment applied. Only enchantments that were not present on the `item` already or that were below the level applied will be changed. +- `[js]item.enchant(enchantments)`: + - `enchantments`: The enchantments to apply. It may be an object with keys being strings representing enchantments and values being the levels of enchantments. + - **Returns**: A copy of `item` with the enchantments applied. Only enchantments that were not present on the `item` already or that were below the level applied will be changed. + +Example: +```js +const enchItem = item.enchant({ + "minecraft:efficiency": 5, + "minecraft:unbreaking": 3, + "minecraft:mending": 1 +}) +// Will result in a copy of an item with the following enchantments applied: +// Efficiency V, Unbreaking III, Mending +``` + +- `[js]item.getHarvestSpeed()`: +- `[js]item.getHarvestSpeed(block)`: + - `block` {optional}: The `Block` to check the harvest speed against. + - **Returns**: The harvest speed of the item against a given block, or its default harvest speed if `block` isn't provided. +- `[js]item.toItemString()`: + - **Returns**: A KubeJS string representation of an ItemStack. + Essentially does the reverse of an item wrapper, for example: + For an `item` being a stack of 64 Sand, `[js]item.toItemString()` returns `[js]'64x minecraft:sand'`. +- `[js]item.asIngredient()` + - **Returns**: An `Ingredient` which matches the `item`. + +- `[js]item.withCustomName(name)`: + - `name` - A text `Component` to apply as custom name. It may be a plain string, for example: `[js]'My custom item!'` + - **Returns**: A copy of `item` with `minecraft:custom_name` data component applied. +- `[js]item.withLore(lore)`: Copies this item stack with the specified lore text + - `lore` - An **array** of text `Component`s to apply as lore. Components in the array may be plain strings. + - For example: `[js]\['Some cool lore!', 'KubeJS rocks!'\]` + - **Returns**: A copy of `item` with `minecraft:lore` data component applied. +- `[js]item.typeData`: ??? (is this just a custom map for scripters to use to attach data to item definitions?) # Further Reading - [Data Components](/concepts/data-components) diff --git a/wiki/concepts/item/en.yml b/wiki/concepts/item/en.yml new file mode 100644 index 00000000..6997ce0b --- /dev/null +++ b/wiki/concepts/item/en.yml @@ -0,0 +1,6 @@ +title: "Item" +description: "Things you can pick up to your inventory, store in chests, etc." + +item: "#[[orange|`<`#[[yellow|`item`]]`>`]]" +components: "#[[blue|`\\[​`#[[orange|`<`#[[yellow|`components`]]`>`]]`​\\]`]]" +custom-data: "#[[blue|`\\{​`#[[orange|`<`#[[yellow|`custom-data`]]`>`]]`​\\}`]]" diff --git a/wiki/ref/BlockBuilder/en.yml b/wiki/concepts/item/meta.yml similarity index 100% rename from wiki/ref/BlockBuilder/en.yml rename to wiki/concepts/item/meta.yml diff --git a/wiki/concepts/item/page.kubedoc b/wiki/concepts/item/page.kubedoc new file mode 100644 index 00000000..63af9aad --- /dev/null +++ b/wiki/concepts/item/page.kubedoc @@ -0,0 +1,35 @@ +`Item`s are objects representing Minecraft items. +They are usually used in places where the item's components are needed. + +TODO: Reword this article! + +# Type wrappers +Various data types can wrap into `Item`s when an `Item` is expected. + +## String literals + +### {item} + - {item} - A string corresponding to item ID. + Special case: `''` (empty string), `'-'`, `air` and `minecraft:air` all result in the air item. + - Example: `minecraft:diamond_sword` + - Results in a Diamond Sword. + +### {item}{components} + - {item} - A string corresponding to item ID. + - {components} - A list of components formatted as follows: `\[key1=value1,key2=value2\]`. + - Example: `minecraft:diamond_sword[damage=2]` + - Results in a Diamond Sword with 2 durability damage. + +### {item}{custom-data} + - {item} - A string corresponding to item ID. + - {custom-data} - A NBT compound tag to be stored into the `minecraft:custom_data` component, formatted as a stringified NBT: `\{key1:value1, key2:value2\}`. + - Example: `minecraft:diamond_sword{souls:2l}` + - Results in a Diamond Sword with `minecraft:custom_data` component set to `{souls:2l}`. + +# Methods + +This page contains only a small subset of possible methods. The following methods can be useful in scripts. +In code snippets below, `item` will refer to the instance of `Item`. + +- `[js]item.getId()` | Getter bean: `[js]item.id` + - Returns: The item's namespaced ID as a string. \ No newline at end of file diff --git a/wiki/global-scope/page.kubedoc b/wiki/global-scope/page.kubedoc index 4170c0ef..a96d722a 100644 --- a/wiki/global-scope/page.kubedoc +++ b/wiki/global-scope/page.kubedoc @@ -13,8 +13,55 @@ | `HOUR` | number | 3600000 (`60 * MINUTE`) | # Classes - -|> 1.20.1 +|> 1.21.1 +- [[/ref/wrappers/BlockWrapper|`Block`]] +- `BlockPos` +- `BlockProperties` +- `BlockStatePredicate` +- `Blocks` +- `Client` +- `Color` +- `Component` +- `DamageSource` +- `DataMap` +- `Direction` +- `Duration` +- `EntitySelector` +- `Facing` +- `Fluid` +- `FluidAmounts` +- `Ingredient` +- [[/ref/wrappers/ItemWrapper|`Item`]] +- `Items` +- `Java` +- `JavaMath` +- `JsonIO` +- `JsonUtils` +- `Matrix3f` +- `Matrix4f` +- `MobEffectUtil` +- `NBT` +- `NBTIO` +- `Notification` +- `ParticleOptions` +- `Platform` +- `Quaternionf` +- `Registry` +- `RotationAxis` +- `SizedIngredient` +- `SoundType` +- `Stats` +- `StringUtils` +- `Text` +- `TextIcons` +- `Types` +- `UUID` +- `Utils` +- `Vec3d` +- `Vec3f` +- `Vec3i` +- `Vec4f` +<||> 1.20.1 - WIP <||>+ 1.19.2 - `Platform` diff --git a/wiki/ref/Boolean/page.kubedoc b/wiki/ref/Boolean/page.kubedoc deleted file mode 100644 index 2d9c6756..00000000 --- a/wiki/ref/Boolean/page.kubedoc +++ /dev/null @@ -1,10 +0,0 @@ -Type representing any true of false values - ---- -# Properties ---- -None ---- -# Methods ---- -None \ No newline at end of file diff --git a/wiki/ref/Consumer/page.kubedoc b/wiki/ref/Consumer/page.kubedoc deleted file mode 100644 index f8313427..00000000 --- a/wiki/ref/Consumer/page.kubedoc +++ /dev/null @@ -1,13 +0,0 @@ -Consumer is a generic class that usually means that method has a callback function. - -If your method looks something like: - -`object`$$.example(callback: Consumer) - -Then the script for this will be: -```js -object.example(obj => { - console.log(obj) // obj is a string -}) -``` -Of course, the argument name in callback doesn't matter. \ No newline at end of file diff --git a/wiki/ref/ID/page.kubedoc b/wiki/ref/ID/page.kubedoc deleted file mode 100644 index d896533f..00000000 --- a/wiki/ref/ID/page.kubedoc +++ /dev/null @@ -1,17 +0,0 @@ -ID is basically a [[$String]] with namespace and path. - -Examples: -- `'minecraft:stone'` -- `'minecraft:textures/blocks/stone'` -- `'kubejs:custom_item'` - -This class is called `ResourceLocation` in mojang mappings and `Identifier` in Yarn. - ---- -# Properties ---- -## $$.namespace: String -Namespace - of `'example:thing'` namespace would be `'example'` ---- -## $$.path: String -Path - of `'example:thing'` path would be `'thing'` \ No newline at end of file diff --git a/wiki/ref/Number/page.kubedoc b/wiki/ref/Number/page.kubedoc deleted file mode 100644 index 06cbdeac..00000000 --- a/wiki/ref/Number/page.kubedoc +++ /dev/null @@ -1,10 +0,0 @@ -Type representing any number (both whole and floating point) - ---- -# Properties ---- -None ---- -# Methods ---- -None \ No newline at end of file diff --git a/wiki/ref/Void/page.kubedoc b/wiki/ref/Void/page.kubedoc deleted file mode 100644 index 7c4eca37..00000000 --- a/wiki/ref/Void/page.kubedoc +++ /dev/null @@ -1,10 +0,0 @@ -Nothing. Void... is nothing. - ---- -# Properties ---- -None ---- -# Methods ---- -None \ No newline at end of file diff --git a/wiki/ref/BlockProperty/en.yml b/wiki/ref/builders/BlockBuilder/en.yml similarity index 100% rename from wiki/ref/BlockProperty/en.yml rename to wiki/ref/builders/BlockBuilder/en.yml diff --git a/wiki/ref/BlockBuilder/meta.yml b/wiki/ref/builders/BlockBuilder/meta.yml similarity index 100% rename from wiki/ref/BlockBuilder/meta.yml rename to wiki/ref/builders/BlockBuilder/meta.yml diff --git a/wiki/ref/BlockBuilder/page.kubedoc b/wiki/ref/builders/BlockBuilder/page.kubedoc similarity index 100% rename from wiki/ref/BlockBuilder/page.kubedoc rename to wiki/ref/builders/BlockBuilder/page.kubedoc diff --git a/wiki/ref/Consumer/en.yml b/wiki/ref/builders/FoodBuilder/en.yml similarity index 100% rename from wiki/ref/Consumer/en.yml rename to wiki/ref/builders/FoodBuilder/en.yml diff --git a/wiki/ref/FoodBuilder/page.kubedoc b/wiki/ref/builders/FoodBuilder/page.kubedoc similarity index 100% rename from wiki/ref/FoodBuilder/page.kubedoc rename to wiki/ref/builders/FoodBuilder/page.kubedoc diff --git a/wiki/ref/builders/en.yml b/wiki/ref/builders/en.yml new file mode 100644 index 00000000..d1a64c14 --- /dev/null +++ b/wiki/ref/builders/en.yml @@ -0,0 +1,2 @@ +title: "Builders" +description: "Classes that use builder pattern to create things" \ No newline at end of file diff --git a/wiki/ref/Direction/en.yml b/wiki/ref/enums/BlockProperty/en.yml similarity index 100% rename from wiki/ref/Direction/en.yml rename to wiki/ref/enums/BlockProperty/en.yml diff --git a/wiki/ref/BlockProperty/page.kubedoc b/wiki/ref/enums/BlockProperty/page.kubedoc similarity index 100% rename from wiki/ref/BlockProperty/page.kubedoc rename to wiki/ref/enums/BlockProperty/page.kubedoc diff --git a/wiki/ref/FoodBuilder/en.yml b/wiki/ref/enums/Direction/en.yml similarity index 100% rename from wiki/ref/FoodBuilder/en.yml rename to wiki/ref/enums/Direction/en.yml diff --git a/wiki/ref/Direction/page.kubedoc b/wiki/ref/enums/Direction/page.kubedoc similarity index 100% rename from wiki/ref/Direction/page.kubedoc rename to wiki/ref/enums/Direction/page.kubedoc diff --git a/wiki/ref/FluidAmounts/en.yml b/wiki/ref/enums/FluidAmounts/en.yml similarity index 100% rename from wiki/ref/FluidAmounts/en.yml rename to wiki/ref/enums/FluidAmounts/en.yml diff --git a/wiki/ref/FluidAmounts/page.kubedoc b/wiki/ref/enums/FluidAmounts/page.kubedoc similarity index 100% rename from wiki/ref/FluidAmounts/page.kubedoc rename to wiki/ref/enums/FluidAmounts/page.kubedoc diff --git a/wiki/ref/ID/en.yml b/wiki/ref/enums/MapColor/en.yml similarity index 100% rename from wiki/ref/ID/en.yml rename to wiki/ref/enums/MapColor/en.yml diff --git a/wiki/ref/MapColor/meta.yml b/wiki/ref/enums/MapColor/meta.yml similarity index 100% rename from wiki/ref/MapColor/meta.yml rename to wiki/ref/enums/MapColor/meta.yml diff --git a/wiki/ref/MapColor/page.kubedoc b/wiki/ref/enums/MapColor/page.kubedoc similarity index 100% rename from wiki/ref/MapColor/page.kubedoc rename to wiki/ref/enums/MapColor/page.kubedoc diff --git a/wiki/ref/MapColor/en.yml b/wiki/ref/enums/RenderType/en.yml similarity index 100% rename from wiki/ref/MapColor/en.yml rename to wiki/ref/enums/RenderType/en.yml diff --git a/wiki/ref/RenderType/page.kubedoc b/wiki/ref/enums/RenderType/page.kubedoc similarity index 100% rename from wiki/ref/RenderType/page.kubedoc rename to wiki/ref/enums/RenderType/page.kubedoc diff --git a/wiki/ref/MutableBlock/en.yml b/wiki/ref/enums/SoundType/en.yml similarity index 100% rename from wiki/ref/MutableBlock/en.yml rename to wiki/ref/enums/SoundType/en.yml diff --git a/wiki/ref/SoundType/meta.yml b/wiki/ref/enums/SoundType/meta.yml similarity index 100% rename from wiki/ref/SoundType/meta.yml rename to wiki/ref/enums/SoundType/meta.yml diff --git a/wiki/ref/SoundType/page.kubedoc b/wiki/ref/enums/SoundType/page.kubedoc similarity index 100% rename from wiki/ref/SoundType/page.kubedoc rename to wiki/ref/enums/SoundType/page.kubedoc diff --git a/wiki/ref/enums/en.yml b/wiki/ref/enums/en.yml new file mode 100644 index 00000000..fc8d033c --- /dev/null +++ b/wiki/ref/enums/en.yml @@ -0,0 +1,2 @@ +title: "Enums and alikes" +description: "Enumeration classes and other value-heavy classes/interfaces used throughout Minecraft and KubeJS" \ No newline at end of file diff --git a/wiki/ref/java/class/en.yml b/wiki/ref/java/class/en.yml new file mode 100644 index 00000000..c266bb97 --- /dev/null +++ b/wiki/ref/java/class/en.yml @@ -0,0 +1,2 @@ +title: "Classes" +description: "From where all Java objects come from" \ No newline at end of file diff --git a/wiki/ref/MutableItem/en.yml b/wiki/ref/java/class/page.kubedoc similarity index 100% rename from wiki/ref/MutableItem/en.yml rename to wiki/ref/java/class/page.kubedoc diff --git a/wiki/ref/java/en.yml b/wiki/ref/java/en.yml new file mode 100644 index 00000000..f947827e --- /dev/null +++ b/wiki/ref/java/en.yml @@ -0,0 +1,2 @@ +title: "Java" +description: "Reference for Java built-in types that can be described by JavaScript" \ No newline at end of file diff --git a/wiki/ref/java/functional-interface/Consumer/en.yml b/wiki/ref/java/functional-interface/Consumer/en.yml new file mode 100644 index 00000000..fdc90f34 --- /dev/null +++ b/wiki/ref/java/functional-interface/Consumer/en.yml @@ -0,0 +1,2 @@ +title: "Consumer" +description: "A function that takes one parameter and returns nothing" \ No newline at end of file diff --git a/wiki/ref/java/functional-interface/Consumer/page.kubedoc b/wiki/ref/java/functional-interface/Consumer/page.kubedoc new file mode 100644 index 00000000..718dc8e4 --- /dev/null +++ b/wiki/ref/java/functional-interface/Consumer/page.kubedoc @@ -0,0 +1,24 @@ +**Consumer** functional interfaces represent functions, that take a value of a type (specified in type argument) and return nothing. + +They are commonly used in KubeJS events - the event is passed as a parameter to event handler function. + +Examples: +```js +// A function that takes `event` and returns nothing +const handler = event => { + // When passed into `ServerEvents.recipes` event handler, + // `event` will be of type RecipesKubeEvent + event.shaped('minecraft:brick_slab', ['BBB'], { B: 'minecraft:brick' }) +} + +// handler's expected type is Consumer +ServerEvents.recipes(handler) +``` + +```js +// Or more commonly, put the function directly inside of the parameter +ServerEvents.recipes(event => { + // `event` will be of type RecipesKubeEvent + event.shaped('minecraft:brick_slab', ['BBB'], { B: 'minecraft:brick' }) +}) +``` \ No newline at end of file diff --git a/wiki/ref/java/functional-interface/Function/en.yml b/wiki/ref/java/functional-interface/Function/en.yml new file mode 100644 index 00000000..5ba9b2b4 --- /dev/null +++ b/wiki/ref/java/functional-interface/Function/en.yml @@ -0,0 +1,2 @@ +title: "Function" +description: "A function that takes a parameter and returns a value" \ No newline at end of file diff --git a/wiki/ref/java/functional-interface/Function/page.kubedoc b/wiki/ref/java/functional-interface/Function/page.kubedoc new file mode 100644 index 00000000..0b0bfe56 --- /dev/null +++ b/wiki/ref/java/functional-interface/Function/page.kubedoc @@ -0,0 +1,13 @@ +**Supplier** functional interfaces represent functions, that take a parameter (specified in type argument) and return a value of a type (specified in another type argument). + +They are usually used in customized callbacks. + +Examples: +```js +const $ItemProperties = Java.loadClass('net.minecraft.world.item.Item$Properties') +const $ShieldItem = Java.loadClass('net.minecraft.world.item.ShieldItem') + +// An inpractical example of a function that takes a number and outputs a ShieldItem +// If could be assigned to places where Function is expected. +const intToShieldFunction = (durability) => new $ShieldItem(new $ItemProperties().durability(durability).stacksTo(1)) +``` diff --git a/wiki/ref/java/functional-interface/Predicate/en.yml b/wiki/ref/java/functional-interface/Predicate/en.yml new file mode 100644 index 00000000..1d46d44f --- /dev/null +++ b/wiki/ref/java/functional-interface/Predicate/en.yml @@ -0,0 +1,2 @@ +title: "Predicate" +description: "A function that takes one parameter and returns a boolean" \ No newline at end of file diff --git a/wiki/ref/java/functional-interface/Predicate/page.kubedoc b/wiki/ref/java/functional-interface/Predicate/page.kubedoc new file mode 100644 index 00000000..3208b51e --- /dev/null +++ b/wiki/ref/java/functional-interface/Predicate/page.kubedoc @@ -0,0 +1,26 @@ +**Predicate** functional interfaces represent functions, that take a value of a type (specified in type argument) and return a boolean value. + +They are commonly used in callbacks used to filter lists and other collections. + +Examples: +```js +// When passed into the `rayTraceEntity` predicate parameter, `entity` will be of type Entity +const cowPredicate = entity => entity.type == 'minecraft:cow' + +PlayerEvents.tick(event => { + if (event.server.tickCount % 10 != 0) return + // The expected type of `rayTraceEntity`'s first parameter is Predicate + const rayTracedCow = event.player.rayTraceEntity(cowPredicate) +}) +``` + +```js +// Or more commonly, put the function directly inside of the parameter +PlayerEvents.tick(event => { + if (event.server.tickCount % 10 != 0) return; + const rayTracedCow = event.player.rayTraceEntity(entity => { + // `entity` will be of type Entity + return entity.type == 'minecraft:cow' + }) +}) +``` \ No newline at end of file diff --git a/wiki/ref/java/functional-interface/Supplier/en.yml b/wiki/ref/java/functional-interface/Supplier/en.yml new file mode 100644 index 00000000..87c1dfd6 --- /dev/null +++ b/wiki/ref/java/functional-interface/Supplier/en.yml @@ -0,0 +1,2 @@ +title: "Supplier" +description: "A function that takes nothing and returns a value" \ No newline at end of file diff --git a/wiki/ref/java/functional-interface/Supplier/page.kubedoc b/wiki/ref/java/functional-interface/Supplier/page.kubedoc new file mode 100644 index 00000000..d56a7643 --- /dev/null +++ b/wiki/ref/java/functional-interface/Supplier/page.kubedoc @@ -0,0 +1,34 @@ +**Supplier** functional interfaces represent functions, that take nothing and return a value of a type (specified in type argument). + +They are usually used in places, where: +- The value needs to be fetched lazily, that means that the method that uses such callback can choose when to execute the function to fetch the value, +- The value can be dependent on external sources, and may change over time. + +Examples: +```js +const $ItemProperties = Java.loadClass('net.minecraft.world.item.Item$Properties') +const $ShieldItem = Java.loadClass('net.minecraft.world.item.ShieldItem') + +// A function that takes nothing and outputs a ShieldItem +const shieldSupplier = () => new $ShieldItem(new $ItemProperties().durability(128).stacksTo(1)) + +StartupEvents.registry('item', event => { + event.createCustom( + 'kubejs:copper_shield', + shieldSupplier + ) +}) +``` + +```js +// Or more commonly, put the function directly inside of the parameter +const $ItemProperties = Java.loadClass('net.minecraft.world.item.Item$Properties') +const $ShieldItem = Java.loadClass('net.minecraft.world.item.ShieldItem') + +StartupEvents.registry('item', event => { + event.createCustom( + 'kubejs:copper_shield', + () => new $ShieldItem(new $ItemProperties().durability(128).stacksTo(1)) + ) +}) +``` \ No newline at end of file diff --git a/wiki/ref/java/functional-interface/en.yml b/wiki/ref/java/functional-interface/en.yml new file mode 100644 index 00000000..4af76ee9 --- /dev/null +++ b/wiki/ref/java/functional-interface/en.yml @@ -0,0 +1,2 @@ +title: "Functional interfaces" +description: "No first-class functions? No problem!" \ No newline at end of file diff --git a/wiki/ref/java/functional-interface/page.kubedoc b/wiki/ref/java/functional-interface/page.kubedoc new file mode 100644 index 00000000..187f7858 --- /dev/null +++ b/wiki/ref/java/functional-interface/page.kubedoc @@ -0,0 +1,19 @@ +Java does not feature [first-class functions](https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function) like JavaScript does. +That doesn't mean that Java can't represent callbacks (functions passed into functions as an argument)! + +To represent them, Java uses **functional interfaces**. + +Functional interfaces are interfaces, that feature only one abstract method. That method will be the target for lambda expressions in Java. + +In JavaScript scripts, they can be represented by passing in a function that roughly matches the signature (parameters and return type) of the single abstract method. + +# Common functional interfaces + +[[[/ref/java/functional-interface/Consumer]]] +[[[/ref/java/functional-interface/Supplier]]] +[[[/ref/java/functional-interface/Predicate]]] +[[[/ref/java/functional-interface/Function]]] + +# Reference + +[JavaDocs for `java.util.function` package](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/function/package-summary.html) \ No newline at end of file diff --git a/wiki/ref/String/page.kubedoc b/wiki/ref/js/String/page.kubedoc similarity index 100% rename from wiki/ref/String/page.kubedoc rename to wiki/ref/js/String/page.kubedoc diff --git a/wiki/ref/js/en.yml b/wiki/ref/js/en.yml new file mode 100644 index 00000000..693f9899 --- /dev/null +++ b/wiki/ref/js/en.yml @@ -0,0 +1,2 @@ +title: "JavaScript enhancements" +description: "Existing JavaScript objects enhanced by KubeJS" \ No newline at end of file diff --git a/wiki/ref/MutableToolTier/en.yml b/wiki/ref/mutables/MutableBlock/en.yml similarity index 100% rename from wiki/ref/MutableToolTier/en.yml rename to wiki/ref/mutables/MutableBlock/en.yml diff --git a/wiki/ref/MutableBlock/page.kubedoc b/wiki/ref/mutables/MutableBlock/page.kubedoc similarity index 100% rename from wiki/ref/MutableBlock/page.kubedoc rename to wiki/ref/mutables/MutableBlock/page.kubedoc diff --git a/wiki/ref/RenderType/en.yml b/wiki/ref/mutables/MutableItem/en.yml similarity index 100% rename from wiki/ref/RenderType/en.yml rename to wiki/ref/mutables/MutableItem/en.yml diff --git a/wiki/ref/MutableItem/page.kubedoc b/wiki/ref/mutables/MutableItem/page.kubedoc similarity index 100% rename from wiki/ref/MutableItem/page.kubedoc rename to wiki/ref/mutables/MutableItem/page.kubedoc diff --git a/wiki/ref/SoundType/en.yml b/wiki/ref/mutables/MutableToolTier/en.yml similarity index 100% rename from wiki/ref/SoundType/en.yml rename to wiki/ref/mutables/MutableToolTier/en.yml diff --git a/wiki/ref/MutableToolTier/page.kubedoc b/wiki/ref/mutables/MutableToolTier/page.kubedoc similarity index 100% rename from wiki/ref/MutableToolTier/page.kubedoc rename to wiki/ref/mutables/MutableToolTier/page.kubedoc diff --git a/wiki/ref/mutables/en.yml b/wiki/ref/mutables/en.yml new file mode 100644 index 00000000..791f2dad --- /dev/null +++ b/wiki/ref/mutables/en.yml @@ -0,0 +1,2 @@ +title: "Mutables" +description: "Mutable versions of immutable classes" \ No newline at end of file diff --git a/wiki/ref/records/ExplosionProperties/en.yml b/wiki/ref/records/ExplosionProperties/en.yml new file mode 100644 index 00000000..21ea9b02 --- /dev/null +++ b/wiki/ref/records/ExplosionProperties/en.yml @@ -0,0 +1,4 @@ +title: "ExplosionProperties" +description: "KABOOM!!!" + +record: "" diff --git a/wiki/ref/records/ExplosionProperties/page.kubedoc b/wiki/ref/records/ExplosionProperties/page.kubedoc new file mode 100644 index 00000000..0b59e4dd --- /dev/null +++ b/wiki/ref/records/ExplosionProperties/page.kubedoc @@ -0,0 +1,92 @@ +>>> info +This class is a [[/ref/records|record]]. If you want to learn, how to use them in KubeJS scripts, [[/ref/records|go here]]. +<<< + +**ExplosionProperties** define explosion properties. Nothing to write home about here. + +>>> #source-type +[[/concepts/entity|`Entity`]] +<<< +>>> #source-description +Specifies the source of the explosion's damage (for example, the player who lit the TNT). +<<< +>>> #damage-source-type +`DamageSource` +<<< +>>> #damage-source-description +Specifies the damage source for the explosion. +<<< +>>> #explosion-damage-calculator-type +`ExplosionDamageCalculator` +<<< +>>> #explosion-damage-calculator-description +Explosion damage calculator. +<<< +>>> #strength-type +`number` (float) +<<< +>>> #strength-description +Specifies the strength of the explosion. +Defaults to `[js]3` if not provided. +<<< +>>> #causes-fire-type +`boolean` +<<< +>>> #causes-fire-description +Specifies, whether explosion causes fire, like Ghast fireball explosions or bed explosions in the Nether. +Defaults to `[js]false` if not provided. +<<< +>>> #mode-type +`Level.ExplosionInteraction` +<<< +>>> #mode-description +The explosion mode. +May be also a string representing a mode: +`[js]'none'`, `[js]'block'`, `[js]'mob'`, `[js]'tnt'`, `[js]'trigger'` +Defaults to `[js]'none'` if not provided. +<<< +>>> #particles-type +`boolean` +<<< +>>> #particles-description +Whether the explosion emits particles or not. +Defaults to `[js]true` if not provided. +<<< +>>> #small-particles-type +`ParticleOptions` +<<< +>>> #small-particles-description +Specifies the small particles used in the explosion. +May be also a string representing the particle to use, for example `[js]'minecraft:angry_villager'`. +Defaults to `[js]'minecraft:explosion'` if not provided. +<<< +>>> #large-particles-type +`ParticleOptions` +<<< +>>> #large-particles-description +Specifies the large particles used in the explosion. +May be also a string representing the particle to use, for example `[js]'minecraft:angry_villager'`. +Defaults to `[js]'minecraft:explosion_emitter'` if not provided. +<<< +>>> #explosion-sound-type +`Holder` +<<< +>>> #explosion-sound-description +Specifies the sound of the explosion. +May be also a string representing a sound, for example `[js]'minecraft:block.amethyst_block.chime'`. +Defaults to `[js]'minecraft:entity.generic.explode'` if not provided. +<<< + +# Properties + +| Property | Type | Description | +| `source` | <#source-type> | <#source-description> | +| `damageSource` | <#damage-source-type> | <#damage-source-description> | +| `damageCalculator` | <#explosion-damage-calculator-type> | <#explosion-damage-calculator-description> | +| `strength` | <#strength-type> | <#strength-description> | +| `causesFire` | <#causes-fire-type> | <#causes-fire-description> | +| `mode` | <#mode-type> | <#mode-description> | +| `particles` | <#particles-type> | <#particles-description> | +| `smallParticles` | <#small-particles-type> | <#small-particles-description> | +| `largeParticles` | <#large-particles-type> | <#large-particles-description> | +| `explosionSound` | <#explosion-sound-type> | <#explosion-sound-description> | \ No newline at end of file diff --git a/wiki/ref/records/FireworkExplosion/en.yml b/wiki/ref/records/FireworkExplosion/en.yml new file mode 100644 index 00000000..7c9d79b5 --- /dev/null +++ b/wiki/ref/records/FireworkExplosion/en.yml @@ -0,0 +1,2 @@ +title: "FireworkExplosion" +description: "The actual cool lights" diff --git a/wiki/ref/records/FireworkExplosion/page.kubedoc b/wiki/ref/records/FireworkExplosion/page.kubedoc new file mode 100644 index 00000000..e97e20e3 --- /dev/null +++ b/wiki/ref/records/FireworkExplosion/page.kubedoc @@ -0,0 +1,55 @@ +>>> info +This class is a [[/ref/records|record]]. If you want to learn, how to use them in KubeJS scripts, [[/ref/records|go here]]. +<<< + +**FireworkExplosion** record defines how fireworks explode. This record is used as a part of the `minecraft:firework_explosion` data component. + +>>> #shape-type +`Shape` +<<< +>>> #shape-description +Defines the shape of the explosion. +May be also a string representing a shape: +`[js]'small_ball'`, `[js]'large_ball'`, `[js]'star'`, `[js]'creeper'`, `[js]'burst'`. +<<< +>>> #colors-type +`IntList` +<<< +>>> #colors-description +The RGB colors of the initial particles of the explosion. +Can be described in JS as an array of numbers: +```js +[0x00ff00, 0xff0000, 0x0000ff] +``` +<<< +>>> #fade-colors-type +`IntList` +<<< +>>> #fade-colors-description +The RGB colors of the fading particles of the explosion. +Can be described in JS as an array of numbers: +```js +[0x00ff00, 0xff0000, 0x0000ff] +``` +<<< +>>> #has-trail-type +`boolean` +<<< +>>> #has-trail-description +Whether the firework has a trail effect. +<<< +>>> #has-twinkle-type +`boolean` +<<< +>>> #has-twinkle-description +Whether the firework has a twinkle effect. +<<< + +# Properties + +| Property | Type | Description | +| `shape` | <#shape-type> | <#shape-description> | +| `colors` | <#colors-type> | <#colors-description> | +| `fadeColors` | <#fade-colors-type> | <#fade-colors-description> | +| `hasTrail` | <#has-trail-type> | <#has-trail-description> | +| `hasTwinkle` | <#has-twinkle-type> | <#has-twinkle-description> | \ No newline at end of file diff --git a/wiki/ref/records/Fireworks/en.yml b/wiki/ref/records/Fireworks/en.yml new file mode 100644 index 00000000..2e364fa2 --- /dev/null +++ b/wiki/ref/records/Fireworks/en.yml @@ -0,0 +1,2 @@ +title: "Fireworks" +description: "Let's celebrate!" diff --git a/wiki/ref/records/Fireworks/page.kubedoc b/wiki/ref/records/Fireworks/page.kubedoc new file mode 100644 index 00000000..dc0c63ef --- /dev/null +++ b/wiki/ref/records/Fireworks/page.kubedoc @@ -0,0 +1,25 @@ +>>> info +This class is a [[/ref/records|record]]. If you want to learn, how to use them in KubeJS scripts, [[/ref/records|go here]]. +<<< + +**Fireworks** record defines firework properties. This record is used as a part of the `minecraft:firework` data component. + +>>> #flight-duration-type +`number` +(integer) +<<< +>>> #flight-duration-description +Specifies the flight duration of the rocket, that is - with how much gunpowder the rocket was crafted. Used to specify, for how long should the firework boost Elytra flight and how far should firework fly, with certain random variation. +<<< +>>> #explosions-type +`List<`[[/ref/records/FireworkExplosion|`FireworkExplosion`]]`>` +<<< +>>> #explosions-description +A list of up to 256 [[/ref/records/FireworkExplosion|firework explosions]]. +<<< + +# Properties + +| Property | Type | Description | +| `flightDuration` | <#flight-duration-type> | <#flight-duration-description> | +| `explosions` | <#explosions-type> | <#explosions-description> | diff --git a/wiki/ref/records/en.yml b/wiki/ref/records/en.yml new file mode 100644 index 00000000..1abc4365 --- /dev/null +++ b/wiki/ref/records/en.yml @@ -0,0 +1,2 @@ +title: "Records" +description: "Classes usually representing properties of something" \ No newline at end of file diff --git a/wiki/ref/records/page.kubedoc b/wiki/ref/records/page.kubedoc new file mode 100644 index 00000000..b3a69f7f --- /dev/null +++ b/wiki/ref/records/page.kubedoc @@ -0,0 +1,63 @@ +**Records** in Java are usually immutable, non-extensible classes which role is to hold data. +Their role can be described as similar to a JavaScript object. + +Records in Minecraft are mainly used to provide data for [[/concepts/data-components|data components]]. +KubeJS also uses them to provide script-friendly interfaces for defining properties of things. + +# Usage + +In KubeJS scripts, records can be described in two ways: JavaScript objects and JavaScript arrays. + +>>> info +The following examples will use [[/ref/wrappers/ItemWrapper|`Item.fireworks`]] method which takes in a parameter of [[/ref/records/Fireworks|`Fireworks`]]. +<<< + +## JavaScript objects + +In this style, the object must have keys named exactly like the record's accessors. +All properties of the object are considered optional, and are considered `[js]null` if they aren't provided in the object. + +**Example** + +```js +Item.fireworks({ + explosions: [ + { + hasTwinkle: true, + hasTrail: false, + shape: 'creeper', + colors: [0xaa11ff], + fadeColors: [0xee33ff], + }, + ], + flightDuration: 2 +}) +``` + +## JavaScript arrays + +In this style, the array must be provided **exactly** in order of the argument appearances in the record's constuctor. +All array fields are considered optional, and are considered `[js]null` if they aren't provided in the array. + +>>> info +For convenience, record properties in record documentations here are described exactly in order as they appear in the constructor. +<<< + +```js +// Comments are added to show what value corresponds to what property. + +Item.fireworks([ + 2, // flightDuration + [ // explosions + [ + 'creeper', // shape + [0xaa11ff], // colors + [0xee33ff], // fadeColors + false, // hasTrail + true // hasTwinkle + ] + ] +]) +``` + +# Common records \ No newline at end of file diff --git a/wiki/ref/TextComponent/en.yml b/wiki/ref/utils/TextComponent/en.yml similarity index 100% rename from wiki/ref/TextComponent/en.yml rename to wiki/ref/utils/TextComponent/en.yml diff --git a/wiki/ref/Unit/en.yml b/wiki/ref/utils/Unit/en.yml similarity index 100% rename from wiki/ref/Unit/en.yml rename to wiki/ref/utils/Unit/en.yml diff --git a/wiki/ref/Unit/meta.yml b/wiki/ref/utils/Unit/meta.yml similarity index 100% rename from wiki/ref/Unit/meta.yml rename to wiki/ref/utils/Unit/meta.yml diff --git a/wiki/ref/Unit/page.kubedoc b/wiki/ref/utils/Unit/page.kubedoc similarity index 100% rename from wiki/ref/Unit/page.kubedoc rename to wiki/ref/utils/Unit/page.kubedoc diff --git a/wiki/ref/utils/en.yml b/wiki/ref/utils/en.yml new file mode 100644 index 00000000..a599c482 --- /dev/null +++ b/wiki/ref/utils/en.yml @@ -0,0 +1,2 @@ +title: "Utilities" +description: "Various classes/interfaces that provide useful values/methods" \ No newline at end of file diff --git a/wiki/ref/wrappers/BlockWrapper/en.yml b/wiki/ref/wrappers/BlockWrapper/en.yml new file mode 100644 index 00000000..9f6a282a --- /dev/null +++ b/wiki/ref/wrappers/BlockWrapper/en.yml @@ -0,0 +1,2 @@ +title: "BlockWrapper" +description: "Getting blocks from string" \ No newline at end of file diff --git a/wiki/ref/wrappers/BlockWrapper/meta.yml b/wiki/ref/wrappers/BlockWrapper/meta.yml new file mode 100644 index 00000000..e69de29b diff --git a/wiki/ref/wrappers/BlockWrapper/page.kubedoc b/wiki/ref/wrappers/BlockWrapper/page.kubedoc new file mode 100644 index 00000000..109d5942 --- /dev/null +++ b/wiki/ref/wrappers/BlockWrapper/page.kubedoc @@ -0,0 +1,153 @@ +`BlockWrapper` is an interface containing many useful static methods for getting blocks from string. +It's exposed to [[/global-scope|global scope]] as `Block`. + +# Static methods + +## ID related + +### `getBlock` + +```js +Block.of(id) +``` +**Parameters** +- `[js]id`: A ResourceLocation instance corresponding to a block ID. It can be a string representing a resource location, for example: `[js]'minecraft:stone'`. +**Returns** +A new {block} corresponding to the provided `id`. + +--- + +### `getId` + +```js +Block.getId(block) +``` +**Parameters** +- `[js]block`: A {block} instance. It can be a string representing a resource location of a block, for example: `[js]'minecraft:stone'`, but in this case that conversion isn't useful. +**Returns** +A ResourceLocation corresponding to the provided `block`. + +--- + +## Predicates + +### `id` + +```js +Block.id(id) +``` + +**Parameters** +- `[js]id`: A ResourceLocation instance corresponding to a block ID. It can be a string representing a resource location, for example: `[js]'minecraft:stone'`. +**Returns** +A new `BlockIDPredicate` matching the block with the given `id`. + +--- + +### `entity` + +```js +Block.entity(id) +``` + +**Parameters** +- `[js]id`: A ResourceLocation instance corresponding to a block entity ID. It can be a string representing a resource location, for example: `[js]'minecraft:chest'`. +**Returns** +A new `BlockEntityPredicate` matching the block entity with the given `id`. + +--- + +### `custom` + +```js +Block.custom(blockPredicate) +``` + +**Parameters** +- `[js]blockPredicate`: A BlockPredicate instance. It can be a function, which takes a `LevelBlock` (KubeJS' interface for script-friendly block access) and returns a boolean. +**Returns** +If `blockPredicate` was already a BlockPredicate, it returns the same `blockPredicate`. +If `blockPredicate` was a function, it returns the function wrapped into a `BlockPredicate`. +**Example** +```js +// Returns a BlockPredicate that matches all blocks whose block light is greater than 7 +Block.custom(block => block.blockLight > 7) +``` + +--- + +## Collections + +### `getTypeList` + +```js +Block.getTypeList() +Block.typeList // read-only bean +``` + +**Returns** +A list of class names of all blocks registered in the game. + +--- + +### `getTaggedIds` + +```js +Block.getTaggedIds(tag) +``` + +**Parameters** +- `[js]tag`: A `ResourceLocation` instance corresponding to a block tag. It can be a string representing a resource location, for example: `[js]'minecraft:logs'`. + +**Returns** +A list of `ResourceLocation`s of all blocks in a block tag. + +--- + +### `getAllBlockStates` + +```js +Block.getAllBlockStates() +Block.allBlockStates // read-only bean +``` + +**Returns** +A set of all `BlockState`s registered in the game. + + +--- + +### `getFacing` + +```js +Block.getFacing() +Block.facing // read-only bean +``` + +**Returns** +A map of all directions (as strings) to `Direction` enumerations. +It can be used as a usual JavaScript object: +```js +Block.facing.south // Direction.SOUTH +``` + +--- + +## Other + +### `withProperties` + +```js +Block.withProperties(blockState, properties) +``` +**Parameters** +- `[js]blockState`: A `BlockState` instance. It can be a string representing a block state, for example: `[js]'minecraft:oak_log\[axis=x\]'`, but in this case that conversion isn't useful, since this method is more useful for modification of existing `BlockState`. +- `[js]properties`: A map of block state property keys to their values. It can be an object, for example `[js]{axis: 'x'}`. If the property isn't present on the block, the newly created block state won't have that property set. +**Returns** +A new `BlockState` with all the properties on the `properties` map/object set. + +--- + +# Source + +([BlockWrapper.java](https://github.com/KubeJS-Mods/KubeJS/blob/main/src/main/java/dev/latvian/mods/kubejs/plugin/builtin/wrapper/BlockWrapper.java)) \ No newline at end of file diff --git a/wiki/ref/wrappers/HolderWrapper/en.yml b/wiki/ref/wrappers/HolderWrapper/en.yml new file mode 100644 index 00000000..98c9f456 --- /dev/null +++ b/wiki/ref/wrappers/HolderWrapper/en.yml @@ -0,0 +1,2 @@ +title: "HolderWrapper" +description: "Getting registry objects (or sets of these) from strings and objects" \ No newline at end of file diff --git a/wiki/ref/wrappers/HolderWrapper/page.kubedoc b/wiki/ref/wrappers/HolderWrapper/page.kubedoc new file mode 100644 index 00000000..4baca8a5 --- /dev/null +++ b/wiki/ref/wrappers/HolderWrapper/page.kubedoc @@ -0,0 +1,41 @@ +`HolderWrapper` is an interface used internally by KubeJS to convert strings and other JS objects into `Holder` and `HolderSet` instances. +It is not exposed to global scope, so only the type wrapper will be discussed here. + +`Holder` instances hold references to registry objects of a given type. These are obtained from Minecraft registry lookups. +For example, `Holder` holds references to `Item` registry objects. + +`HolderSet` instances are sets of `Holder` instances that hold references to registry objects of a given type. +For example, `HolderSet` is a set of `Holder` instances that hold references to `Item` registry objects. + +# Wrapping to `Holder` + +The following: +- strings and other Java character sequences, +- `ResourceLocation` instances, +- `ResourceKey` instances +all perform a registry lookup for the ID stored in them, and the result is a Holder of a target type that holds a reference to a registry object. + +**Example** + +When `[js]'minecraft:iron_pickaxe'` is passed into a method argument that expects a `Holder`, that function will receive a `Holder` that holds a reference to an `Item` which represents the Iron Pickaxe item. + +# Wrapping to `HolderSet` + +These objects can be converted to `HolderSet` directly by doing the following: +- `HolderSet`: kept as is, +- `Holder`: creates a one-element `HolderSet` with the `Holder` inside, +- `ResourceLocation` and strings representing resource locations, like `[js]'minecraft:iron_pickaxe'`: creates a flattened `HolderSet` with the `Holder` instances holding references to registry objects with the given resource location as its ID, +- [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp), [`Pattern`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html) and strings containing regex patterns (like `[js]'/minecraft:.*_wool/'`): Returns a `HolderSet` of all `Holders` of registry objects whose ID match the given regex, +- `TagKey` and strings representing tags (like `[js]'#minecraft:logs'`): Returns a `HolderSet` of all `Holders` of registry objects who are a part of a given tag, +- Strings representing mod IDs (like `[js]'@minecraft'`): Returns a `HolderSet` of all `Holders` of registry objects that match the namespace part of their ID, +- In all other cases, `[js]null` is returned. + +If the object passed in is an JS array or any other Java iterable object, it is recursively flattened to produce the final `HolderSet`. + +**Example** + +When `[js]\['minecraft:iron_pickaxe', 'minecraft:diamond_pickaxe'\]` is passed into a method argument that expects a `HolderSet`, that function will receive a `HolderSet` that holds references to `Item` instances which represent respectively: the Iron Pickaxe and the Diamond Pickaxe. + +# Source + +([HolderWrapper.java](https://github.com/KubeJS-Mods/KubeJS/blob/main/src/main/java/dev/latvian/mods/kubejs/holder/HolderWrapper.java)) \ No newline at end of file diff --git a/wiki/ref/wrappers/IngredientWrapper/en.yml b/wiki/ref/wrappers/IngredientWrapper/en.yml new file mode 100644 index 00000000..a6f3ff15 --- /dev/null +++ b/wiki/ref/wrappers/IngredientWrapper/en.yml @@ -0,0 +1,4 @@ +title: "IngredientWrapper" +description: "Getting ingredients from string" + +optional: "#[[#c3c7cb;border:1px solid #51565d;font-size:0.8rem;padding:0.2em 0.3em; border-radius: 1em|Optional]]" \ No newline at end of file diff --git a/wiki/ref/wrappers/IngredientWrapper/meta.yml b/wiki/ref/wrappers/IngredientWrapper/meta.yml new file mode 100644 index 00000000..e69de29b diff --git a/wiki/ref/wrappers/IngredientWrapper/page.kubedoc b/wiki/ref/wrappers/IngredientWrapper/page.kubedoc new file mode 100644 index 00000000..adca94c6 --- /dev/null +++ b/wiki/ref/wrappers/IngredientWrapper/page.kubedoc @@ -0,0 +1,220 @@ +`IngredientWrapper` is an interface containing many useful static methods for getting ingredients from string and objects. +It's exposed to [[/global-scope|global scope]] as `Ingredient`. + +# Static methods + +## Ingredient getters + +### `of` +```js +Ingredient.of(ingredient) +``` +**Parameters** +- `[js]ingredient`: An [[/concepts/ingredient|`Ingredient`]]. Like with any other place that expects an `Ingredient`, the argument will be converted to `Ingredient` if possible. +**Returns** +A new [[/concepts/ingredient|`Ingredient`]]. + +--- + +```js +Ingredient.of(ingredient, count) +``` +**Parameters** +- `[js]ingredient`: An [[/concepts/ingredient|Ingredient]]. Like with any other place that expects an `Ingredient`, the argument will be converted to `Ingredient` if possible. +- `[js]count`: An integer, representing the size of the ingredient. +**Returns** +A new [[/concepts/ingredient|SizedIngredient]] with the specified `count` set. + +--- + +### `withData` + +```js +Ingredient.withData(itemSet, componentFilter) +Ingredient.withData(itemSet, componentFilter, strict) +``` +**Parameters** +- `[js]itemSet`: a [[/ref/wrappers/HolderWrapper|HolderSet]] of items. See [[/ref/wrappers/HolderWrapper|here]] for a list of possible conversions. +- `[js]componentFilter`: A [[/concepts/data-components|DataComponentMap]] which acts as a component filter. May be also a string or a JS object: See [[/concepts/data-components|here]] for details. +- `[js]strict` {optional}: Whether the component filter is strict. Defaults to `[js]false` if not provided. +**Returns** +A new [[/concepts/ingredient|Ingredient]] that accepts the given set of items under the given component filter. + +--- + +### `first` + +```js +Ingredient.first(ingredient) +``` + +Gets the first item stack that matches the ingredient. Equivalent to `[js]ingredient.first` or `[js]Ingredient.of(ingredient).first`, but unlike the `[js]ingredient.first` case, `ingredient` doesn't have to be an `Ingredient`, it can be any type that can convert to `Ingredient`. + +**Parameters** +- `[js]ingredient`: An [[/concepts/ingredient|Ingredient]]. Like with any other place that expects an `Ingredient`, the argument will be converted to `Ingredient` if possible. + +**Returns** +The first [[/concepts/item-stack|`ItemStack`]] matching the ingredient. + +--- + +## Instance checks + +>>> info +Note that the fact that the object isn't an instance of `Ingredient` doesn't mean, that the object can't be used in place of an `Ingredient`. +This is due to KubeJS using type wrappers, which attempt to implicitly convert other objects into the necessary type when needed. + +So, `[js]'minecraft:stone'` string won't be an instance of `Ingredient`, but can still be passed into places that expect one. +<<< + +### `isIngredient` + +```js +Ingredient.isIngredient(object) +``` + +**Parameters** +- `[js]object`: Any object. + +**Returns** +`[js]true` if `object` is instance of the `Ingredient` class, `[js]false` otherwise. + +--- + +### `isIngredientLike` + +```js +Ingredient.isIngredientLike(object) +``` + +**Parameters** +- `[js]object`: Any object. + +**Returns** +`[js]true` if `object` is instance of either `Ingredient`, `SizedIngredient` or `ItemStack` class, `[js]false` otherwise. + +--- + +## Tags + +### `tagKeyOf` + +```js +Ingredient.tagKeyOf(ingredient) +``` + +**Parameters** +- `[js]ingredient`: An [[/concepts/ingredient|`Ingredient`]]. Like with any other place that expects an `Ingredient`, the argument will be converted to `Ingredient` if possible. + +**Returns** +If the ingredient: +- isn't a custom ingredient (that is - it represents items or lists of items), +- contains only one value, +- and that value is a tag value, +this returns that tag value as a `TagKey`. +Otherwise, returns `[js]null`. + +--- + +### `containsAnyTag` + +```js +Ingredient.containsAnyTag(ingredient) +``` + +**Parameters** +- `[js]ingredient`: An [[/concepts/ingredient|`Ingredient`]]. Like with any other place that expects an `Ingredient`, the argument will be converted to `Ingredient` if possible. + +**Returns** +`[js]true` if the ingredient is not custom (that is - it represents items or lists of items) and contains a tag value, `[js]false` otherwise. + +--- + +## Parsers + +>>> info +These are mainly used internally in KubeJS in the type wrapping process, but they are not hidden from JS, so you can use them if you wish to create a framework that needs to parse ingredients. +<<< + +### `parseJson` + +```js +Ingredient.parseJson(json) +``` + +Parses a JSON object into a potential Ingredient, according to Minecraft's own codec. + +**Parameters** +- `[js]json`: A `JsonElement`. Can be also a JS object or array (?). + +**Returns** +A `DataResult` that potentially contains an `Ingredient`. +This is one of the ways an `Ingredient` can be obtained from the data result: + +```js +const ingredient = Ingredient.parseJson(['minecraft:stone', 'minecraft:cobblestone']) // DataResult + .result() // Optional + .orElse(null) // Ingredient +``` + +--- + +### `parseString` + +```js +Ingredient.parseString(string) +``` + +Parses a string into a potential Ingredient, according to KubeJS' string type wrapping rules. + +**Parameters** +- `[js]string`: A string to parse. + +**Returns** +A `DataResult` that potentially contains an `Ingredient`. +This is one of the ways an `Ingredient` can be obtained from the data result: + +```js +const ingredient = Ingredient.parseString('#minecraft:logs') // DataResult + .result() // Optional + .orElse(null) // Ingredient +``` + +--- + +# Static fields + +## `TYPE_INFO` + +```js +Ingredient.TYPE_INFO +``` + +**Value** +The `TypeInfo` corresponding to the [[/concepts/ingredient|`Ingredient`]] class. + +--- + +## `none` + +```js +Ingredient.none +``` + +**Value** +An empty [[/concepts/ingredient|`Ingredient`]] that matches nothing. + +--- + +## `all` + +```js +Ingredient.all +``` + +**Value** +An [[/concepts/ingredient|`Ingredient`]] that matches every item in the game. + +# Source + +([IngredientWrapper.java](https://github.com/KubeJS-Mods/KubeJS/blob/main/src/main/java/dev/latvian/mods/kubejs/plugin/builtin/wrapper/IngredientWrapper.java)) \ No newline at end of file diff --git a/wiki/ref/wrappers/ItemWrapper/en.yml b/wiki/ref/wrappers/ItemWrapper/en.yml new file mode 100644 index 00000000..b1b57e08 --- /dev/null +++ b/wiki/ref/wrappers/ItemWrapper/en.yml @@ -0,0 +1,2 @@ +title: "ItemWrapper" +description: "Getting items from string" \ No newline at end of file diff --git a/wiki/ref/wrappers/ItemWrapper/meta.yml b/wiki/ref/wrappers/ItemWrapper/meta.yml new file mode 100644 index 00000000..e69de29b diff --git a/wiki/ref/wrappers/ItemWrapper/page.kubedoc b/wiki/ref/wrappers/ItemWrapper/page.kubedoc new file mode 100644 index 00000000..eaefab1e --- /dev/null +++ b/wiki/ref/wrappers/ItemWrapper/page.kubedoc @@ -0,0 +1,223 @@ +`ItemWrapper` is an interface containing many useful static methods for getting items from string. +It's exposed to [[/global-scope|global scope]] as `Item`. + +# Static methods + +## `of` +```js +Item.of(itemStack) +Item.of(itemStack, components) +Item.of(itemStack, count) +Item.of(itemStack, count, components) +``` +**Parameters** +- `[js]itemStack` - an [[/concepts/item-stack|ItemStack]]. Like with any other place that expects an `ItemStack`, the argument will be converted to `ItemStack` if possible. +**Optional parameters**: +- `[js]components` - A map of components. Can be a string representing key-value pairs: `damage=2, item_name={text:"Hello world"}`. +- `[js]count` - An integer, representing the size of the item stack. +**Returns** +A new [[/concepts/item-stack|ItemStack]]. + +--- + +## `getList` + +```js +Item.getList() +Item.list // Bean +``` + +**Returns** +A list of most items (as [[/concepts/item-stack|ItemStack]]s) in the game. Items, that are not in a creative tab are ignored. + +--- + +## `getTypeList` + +```js +Item.getTypeList() +Item.typeList // Bean +``` + +**Returns** +A list of all the namespaced item IDs in the game as strings. + +--- + +## `getTypeToStackMap` + +```js +Item.getTypeToStackMap() +Item.typeToStackMap // Bean +``` + +**Returns** +A map between ResourceLocations and collections of variants of [[/concepts/item-stack|ItemStack]]. + +--- + +## `getVariants` + +```js +Item.getVariants(itemStack) +``` +**Parameters** +- `[js]itemStack` - an [[/concepts/item-stack|ItemStack]]. +**Returns** +A collection of variants of the given [[/concepts/item-stack|ItemStack]]. + +--- + +## `getEmpty` + +```js +Item.getEmpty() +Item.empty // Read-only bean +``` + +**Returns** +- An [[/concepts/item-stack|ItemStack]] that represents an empty slot or air. + +--- + +## `fireworks` + +```js +Item.fireworks(fireworkProperties) +``` + +**Parameters** +- `[js]fireworkProperties` - The [[/ref/records/Fireworks|firework properties]] to use. + +**Returns** +If `fireworkProperties` was already an instance of [[/ref/records/Fireworks|`Fireworks`]], it returns the same [[/ref/records/Fireworks|`Fireworks`]]. +If `fireworkProperties` was an object or an array, it returns the [[/ref/records/Fireworks|`Fireworks`]] instance created from the object/array. + +**Example** +```js +Item.fireworks({ + explosions: [ + { + hasTwinkle: true, + hasTrail: false, + shape: 'creeper', + colors: [0xaa11ff], + fadeColors: [0xee33ff], + }, + ], + flightDuration: 2 +}) +``` + +--- + +## `getItem` + +```js +Item.getItem(id) +``` + +**Parameters** +- `[js]id` - a ResourceLocation instance or a string representing a resource location, like `'minecraft:diamond_sword'`. +**Returns** +An [[/concepts/item|Item]] instance. + +--- + +## `getID` + +```js +Item.getID(item) +``` + +**Parameters** +- `[js]item` - an [[/concepts/item|Item]]. +**Returns** +An ResourceLocation of the item. + +--- + +## `exists` + +```js +Item.exists(id) +``` + +**Parameters** +- `[js]id` - a ResourceLocation instance or a string representing a resource location, like `'minecraft:diamond_sword'`. + +**Returns** +`true` if the item corresponding to the ID exists, `false` otherwise. + +--- + +## `isItem` + +```js +Item.isItem(object) +``` + +**Parameters** +- `[js]object` - Any object. + +**Returns** +`true` if the object is an instance of [[/concepts/item-stack|ItemStack]], `false` otherwise. + +--- + +## `playerHead` + +```js +Item.playerHead(nickname) +``` + +**Parameters** +- `[js]nickname` - A nickname of a player to get their head. + +**Returns** +A player head with the `minecraft:profile` data component applied. + +--- + +## `playerHeadfromBase64` + +```js +Item.playerHeadfromBase64(uuid, textureBase64) +``` + +**Parameters** +- `[js]uuid` - A non-null UUID. +- `[js]textureBase64` - Texture data JSON to apply to the head, encoded in Base64. + +**Returns** +A player head with the `minecraft:profile` data component applied. + +--- + +## `playerHeadFromUrl` + +```js +Item.playerHeadFromUrl(url) +``` + +**Parameters** +- `[js]url` - A URL leading to the texture data JSON to apply to the head. +**Returns** +A player head with the `minecraft:profile` data component applied. + +--- + +## `playerHeadfromStringHash` + +```js +Item.playerHeadfromStringHash(stringHash) +``` + +**Parameters** +- `[js]stringHash` - A string hash of the player to get the texture data JSON from. +**Returns** +A player head with the `minecraft:profile` data component applied. + +# Source + +([ItemWrapper.java](https://github.com/KubeJS-Mods/KubeJS/blob/main/src/main/java/dev/latvian/mods/kubejs/plugin/builtin/wrapper/ItemWrapper.java)) \ No newline at end of file diff --git a/wiki/ref/wrappers/JavaWrapper/en.yml b/wiki/ref/wrappers/JavaWrapper/en.yml new file mode 100644 index 00000000..a193c68a --- /dev/null +++ b/wiki/ref/wrappers/JavaWrapper/en.yml @@ -0,0 +1,2 @@ +title: "JavaWrapper" +description: "Lets you script Java" \ No newline at end of file diff --git a/wiki/ref/wrappers/JavaWrapper/meta.yml b/wiki/ref/wrappers/JavaWrapper/meta.yml new file mode 100644 index 00000000..e69de29b diff --git a/wiki/ref/wrappers/JavaWrapper/page.kubedoc b/wiki/ref/wrappers/JavaWrapper/page.kubedoc new file mode 100644 index 00000000..759b3ba6 --- /dev/null +++ b/wiki/ref/wrappers/JavaWrapper/page.kubedoc @@ -0,0 +1,127 @@ +`JavaWrapper` is an interface containing many useful static methods for accessing Java classes from KubeJS scripts. +It's exposed to [[/global-scope|global scope]] as `Java`. + +# Static methods + +## `loadClass` + +```js +Java.loadClass(className) +``` + +**Parameters** +- `[js]className`: A string representing a fully qualified class name - that is, a name of a class prefixed with a name of a package the class is in. + +**Returns** +A reference to a Java class. +To learn, how to use such reference, see [[/ref/java/class|here]]. + +===Throws=== +If the provided class name is not allowed by the class filter or not found, this method throws an error. + +--- + +## `tryLoadClass` + +```js +Java.tryloadClass(className) +``` + +**Parameters** +- `[js]className`: A string representing a fully qualified class name - that is, a name of a class prefixed with a name of a package the class is in. + +**Returns** +A reference to a Java class, or `[js]null` if the provided class name is not allowed by the class filter or not found. +To learn, how to use such reference, see [[/ref/java/class|here]]. + +--- + +## `cast` + +```js +Java.cast(theClass, object) +``` + +Casts `[js]object` to the target type of `[js]theClass`. Use this in situations, where Rhino can't determine the correct type, for example if the object is provided indirectly. + +**Parameters** +- `[js]theClass`: A reference to a Java class to cast the object to. +- `[js]object`: Any Java object. + +**Returns** +- The `[js]object` cast to `theClass`. + +--- + +## `createConsole` + +```js +Java.createConsole(name) +``` + +Creates a custom `ConsoleJS` instance that allows for logging under a custom name. + +**Parameters** +- `[js]name`: A name of the console. + +**Returns** +- The new `ConsoleJS` instance. +This instance can be used just like `console` in global scope, but logs created by that console will bear the custom name. + +**Example** + +```js +const myConsole = Java.createConsole("My cool console") +console.log("Standard KubeJS log.") +myConsole.log("That's an awesome log!") + +/* Should log something similar to: +[15:38:22] [Server thread/INFO] [KubeJS Server/]: server_scripts:test.js#2: Standard KubeJS log. +[15:38:22] [Server thread/INFO] [My cool console/]: That's an awesome log! +*/ + +``` + +--- + +## `makeFunctionProxy` + +>>> warn +There is a way easier way to acquire implementations of interfaces. See [[/ref/java/class|here]]. +<<< + +```js +Java.makeFunctionProxy(targetClassTypeInfo, theFunction) +``` + +**Parameters** +- `[js]targetClassTypeInfo`: A `TypeInfo` implementation that implements `asClass()` abstract method which returns the target interface class. +- `[js]theFunction`: The JS function. + +**Returns** +The function wrapped into an implementation of a functional interface. + +--- + +## `mergeRecord` + +>>> warn +This method is presumably unfinished, as it currently does not do anything to the record. +<<< + +```js +Java.mergeRecord(originalRecord, mergeMap) +``` + +**Parameters** +- `[js]originalRecord`: A `Record` that serves as a base. +- `[js]mergeMap`: A Java `Map` with string keys and any values to merge with `originalRecord`. It may be a JS object. + +**Returns** +The `[js]originalRecord`. + +--- + +# Source + +([JavaWrapper.java](https://github.com/KubeJS-Mods/KubeJS/blob/main/src/main/java/dev/latvian/mods/kubejs/plugin/builtin/wrapper/JavaWrapper.java)) \ No newline at end of file diff --git a/wiki/ref/wrappers/StringUtilsWrapper/en.yml b/wiki/ref/wrappers/StringUtilsWrapper/en.yml new file mode 100644 index 00000000..d4d3b465 --- /dev/null +++ b/wiki/ref/wrappers/StringUtilsWrapper/en.yml @@ -0,0 +1,4 @@ +title: "StringUtilsWrapper" +description: "Parsing numbers from string and various string utilities" + +optional: "#[[#c3c7cb;border:1px solid #51565d;font-size:0.8rem;padding:0.2em 0.3em; border-radius: 1em|Optional]]" \ No newline at end of file diff --git a/wiki/ref/wrappers/StringUtilsWrapper/meta.yml b/wiki/ref/wrappers/StringUtilsWrapper/meta.yml new file mode 100644 index 00000000..e69de29b diff --git a/wiki/ref/wrappers/StringUtilsWrapper/page.kubedoc b/wiki/ref/wrappers/StringUtilsWrapper/page.kubedoc new file mode 100644 index 00000000..fdfbba23 --- /dev/null +++ b/wiki/ref/wrappers/StringUtilsWrapper/page.kubedoc @@ -0,0 +1,235 @@ +`StringUtilsWrapper` is an interface containing many useful methods for interacting with Java classes. +It's exposed to [[/global-scope|global scope]] as `StringUtils`. + +# Static methods + +## Typed number parsing + +### `parseInt` + +```js +StringUtils.parseInt(object, fallback) +``` + +Parses a 32-bit integer (`int`) from a given object. + + +**Parameters** +- `[js]object` - Any object. If it isn't a number, it will be converted to string. +- `[js]fallback` - The number that will be returned if parsing fails. +**Returns** +The parsed `int` if the object can be converted to string that represents a 32-bit integer. +If the object is `[js]null`, gets converted into an empty string or parsing fails, returns the `[js]fallback` number as a 32-bit integer. + +--- + +### `parseLong` + +```js +StringUtils.parseLong(object, fallback) +``` + +Parses a 64-bit integer (`long`) from a given object. + +**Parameters** +- `[js]object` - Any object. If it isn't a number, it will be converted to string. +- `[js]fallback` - The number that will be returned if parsing fails. +**Returns** +The parsed `long` if the object can be converted to string that represents a 64-bit integer. +If the object is `[js]null`, gets converted into an empty string or parsing fails, returns the `[js]fallback` number as a 64-bit integer. + +>>>info +`[js]StringUtils.parseLong` is very useful for representing long values exactly in scripts, because: +- JavaScript only has one type of number: [`number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number), which is a 64-bit floating point number (also known as `double` in languages such as Java), +- `bigint` doesn't exist in Rhino. +Unless a JS arithmetic operation is performed on a Java number, it will stay as a Java number. +<<< + +--- + +### `parseDouble` + +```js +StringUtils.parseDouble(object, fallback) +``` + +Parses a 64-bit floating point number (`double`) from a given object. + +**Parameters** +- `[js]object` - Any object. If it isn't a number, it will be converted to string. +- `[js]fallback` - The number that will be returned if parsing fails. +**Returns** +The parsed `double` if the object can be converted to string that represents a 64-bit floating point number. +If the object is `[js]null`, gets converted into an empty string or parsing fails, returns the `[js]fallback` number as a 64-bit floating point number. + +--- + +## String processing + +### `snakeCaseToCamelCase` + +```js +StringUtils.snakeCaseToCamelCase(string) +``` + +Converts casing of the provided string from [`snake_case`](https://en.wikipedia.org/wiki/Snake_case) into [`camelCase`](https://en.wikipedia.org/wiki/Camel_case). +Used internally by KubeJS as a way to give names for recipe handlers from `[js]event.recipes` exposed in `[js]event`. +For example, `[js]event.recipes.create.mechanical_crafting` gets exposed as `[js]event.createMechanicalCrafting`. + +**Parameters** +- `[js]string` - The string in [`snake_case`](https://en.wikipedia.org/wiki/Snake_case) to process + +**Returns** +The string in [`camelCase`](https://en.wikipedia.org/wiki/Camel_case). + +**Example** +```js +const string = 'my_cool_identifier' +console.log(StringUtils.snakeCaseToCamelCase(string)) // "myCoolIdentifier" +``` + +--- + +### `snakeCaseToTitleCase` + +```js +StringUtils.snakeCaseToTitleCase(string) +``` + +Converts casing of the provided string from [`snake_case`](https://en.wikipedia.org/wiki/Snake_case) into [Title Case](https://en.wikipedia.org/wiki/Title_case). +First word will always be capitalized, other words will be capitalized unless the word is an article or preposition. +Used internally by KubeJS as a part of generating implicit display names from ID for custom items that had no explicit display name provided. +For example, `kubejs:my_item` will get "My Item" as an implicit display name. + +**Parameters** +- `[js]string` - The string in [`snake_case`](https://en.wikipedia.org/wiki/Snake_case) to process + +**Returns** +The string in [Title Case](https://en.wikipedia.org/wiki/Title_case). + +**Example** +```js +const string = 'the_quick_brown_fox_jumps_over_the_lazy_dog' +console.log(StringUtils.snakeCaseToCamelCase(string)) // "The Quick Brown Fox Jumps Over the Lazy Dog" +``` + +--- + +### `toTitleCase` + +```js +StringUtils.toTitleCase(string) +StringUtils.toTitleCase(string, ignoreSpecial) +``` + +Converts the first letter of the provided `string` to upper case. +Articles and prepositions like "a", "an", "the", "of", "on", "in", "and", "or", "but", "for" won't be capitalized, unless `ignoreSpecial` is set to `[js]true` + +**Parameters** +- `[js]string` - The string in [`snake_case`](https://en.wikipedia.org/wiki/Snake_case) to process +- `[js]ignoreSpecial` {optional} - Whether to ignore special cases involving articles and prepositions. Defaults to `[js]false` if not provided. + +**Returns** +The processed string. + +**Example** +```js +console.log(StringUtils.toTitleCase('the')) // "the" +console.log(StringUtils.toTitleCase('the', true)) // "The" +console.log(StringUtils.toTitleCase('fox')) // "Fox" +``` + +--- + +### `stripEventName` + +```js +StringUtils.stripEventName(string) +``` + +Converts all `/` and `:` characters into `.`, and all `-` characters into `_`. + +**Parameters** +- `[js]string` - The string to process + +**Returns** +The processed string. + +--- + +### `stripIdForEvent` + +```js +StringUtils.stripIdForEvent(id) +``` + +Converts the provided ID (as ResourceLocation) to string and in that string, converts all `/` and `:` characters into `.`, and all `-` characters into `_`. + +**Parameters** +- `[js]id` - A `ResourceLocation`. It may be a string representing a resource location, like `minecraft:iron_pickaxe`. + +**Returns** +The processed string. + +--- + +### `getUniqueId` + +```js +StringUtils.getUniqueId(json) +``` + +Used internally by KubeJS to generate random, unique IDs for recipes that don't have explicit recipe ID set. + +**Parameters** +- `[js]json` - A `JsonElement`. It may be a JS object or array (?). + +**Returns** +The hash of JSON as string. + +--- + +```js +StringUtils.getUniqueId(object, toJsonFunction) +``` + +**Parameters** +- `[js]object` - Object of any type. +- `[js]toJsonFunction` - A function that takes the `[js]object` and returns a `[js]JsonElement`. It may be a JS function, but be aware that it must return a Java `[js]JsonElement`, not a JS object! + +**Returns** +The hash of JSON created as a result of conversion of `[js]object` to JsonObject as string. + +# Static fields + +## `SNAKE_CASE_SPLIT` + +```js +StringUtils.SNAKE_CASE_SPLIT +``` + +**Value** +A [`Pattern`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html) corresponding to the following regex: `[js]/[:_/]/`. + +## `ALWAYS_LOWER_CASE` + +```js +StringUtils.ALWAYS_LOWER_CASE +``` + +**Value** +A `Set` containing words that won't be normally converted to uppercase in process of converting the string to [Title Case](https://en.wikipedia.org/wiki/Title_case): +"a", "an", "the", "of", "on", "in", "and", "or", "but", "for". + +## `EMPTY_STRING_ARRAY` + +```js +StringUtils.EMPTY_STRING_ARRAY +``` + +**Value** +An empty string Java array. + +# Source + +([StringUtilsWrapper.java](https://github.com/KubeJS-Mods/KubeJS/blob/main/src/main/java/dev/latvian/mods/kubejs/plugin/builtin/wrapper/StringUtilsWrapper.java)) \ No newline at end of file diff --git a/wiki/ref/wrappers/UtilsWrapper/en.yml b/wiki/ref/wrappers/UtilsWrapper/en.yml new file mode 100644 index 00000000..cf366d4b --- /dev/null +++ b/wiki/ref/wrappers/UtilsWrapper/en.yml @@ -0,0 +1,6 @@ +title: "UtilsWrapper" +description: "Various Java utilities" + +random-link: "https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Random.html" +pattern-link: "https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html" +future-link: "https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/CompletableFuture.html" \ No newline at end of file diff --git a/wiki/ref/wrappers/UtilsWrapper/meta.yml b/wiki/ref/wrappers/UtilsWrapper/meta.yml new file mode 100644 index 00000000..e69de29b diff --git a/wiki/ref/wrappers/UtilsWrapper/page.kubedoc b/wiki/ref/wrappers/UtilsWrapper/page.kubedoc new file mode 100644 index 00000000..659413bb --- /dev/null +++ b/wiki/ref/wrappers/UtilsWrapper/page.kubedoc @@ -0,0 +1,298 @@ +`UtilsWrapper` is an interface containing many useful methods for interacting with Java classes. +It's exposed to [[/global-scope|global scope]] as `Utils`. + +# Static methods + +## RNG + +### `getRandom` + +```js +Utils.getRandom() +Utils.random // read-only bean +``` + +**Returns** +The shared instance of `RandomSource` to generate random numbers from. +This method will always return the same `RandomSource` instance. + +--- + +### `newRandom` + +```js +Utils.newRandom() +``` + +**Returns** +A **new** instance of `RandomSource` to generate random numbers from. + +--- + +### `randomOf` + +```js +Utils.randomOf(random, collection) +``` + +>>> #random +`[js]random`: An instance of [`Random`]({random-link}). +Note that unlike `RandomSource` obtained via `[js]Utils.getRandom()` or `[js]Utils.randomOf(random, collection)`, this [`Random`]({random-link}) comes from a built-in Java package ([`java.util.Random`]({random-link})) and not from Minecraft (`net.minecraft.util.RandomSource`), and are not assignable to each other, since they have not in a common ancestor tree. +<<< + +**Parameters** +- <#random> +- `[js]collection` - Any Java collection. This includes all sorts of lists, but not maps. It may be also a JS array, like `[js]\['one', 'two', 'three'\]`. + +**Returns** +A random element from the collection. + +--- + +## Collections + +### `emptyList` + +```js +Utils.emptyList() +``` +**Returns** +A new empty, immutable (read-only) `ArrayList`. + +--- + +### `emptyMap` + +```js +Utils.emptyMap() +``` +**Returns** +A new empty, immutable (read-only) `Map`. + +--- + +### `newList` + +```js +Utils.newList() +``` +**Returns** +A new empty, mutable `ArrayList`. + +--- + +### `newMap` + +```js +Utils.newMap() +``` +**Returns** +A new empty, mutable `LinkedHashMap`. + +--- + +### `newCountingMap` + +```js +Utils.newCountingMap() +``` +**Returns** +A new empty, mutable `CountingMap`. + +--- + +## Java Regex + +### `regex` + +```js +Utils.regex(regexLike) +``` + +**Parameters** +- `[js]regexLike`: Any value, but preferably one of the following: + - A JavaScript [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp), + - A JavaScript string (which will be used to create a regular expression object) + - A Java character sequence (that includes Java strings) + - A Java [`Pattern`]({pattern-link}). + +**Returns** +If the `[js]regexLike` was: +- a [`Pattern`]({pattern-link}) - returns the same Pattern +- a [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) - returns a `Pattern` corresponding to the RegExp, +- a string or a character sequence - If the string is formed similarly to a JavaScript regex literal, returns a `Pattern` corresponding to the string. + +If `[js]regexLike` was of a different type, this returns `[js]null`. + +===Throws=== +If the given string doesn't start with a `/`, this throws an exception. +Other malformations are silently ignored, until the string is passed into the [`Pattern.compile`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#compile(java.lang.String) method, which may throw an exception on an improper pattern. + +```js +Utils.regex(regexString, flags) +``` +- `[js]regexString`: A string that represents the regular expression pattern. +- `[js]flags`: A bit mask of regular expression flags to use. See the field summary of the [`Pattern`]({pattern-link}) class to learn more. + +**Returns** + +A new [`Pattern`]({pattern-link}) with the given pattern and flags. + +===Throws=== +If the given string doesn't start with a `/`, this throws an exception. +Other malformations are silently ignored, until the string is passed into the [`Pattern.compile`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/regex/Pattern.html#compile(java.lang.String) method, which may throw an exception on an improper pattern. + +--- + +## Registry lookup + +### `getStat` + +```js +Utils.getStat(id) +``` + +**Parameters** +- `[js]id`: The stat's `ResourceLocation`. + +>>> danger +Do NOT pass strings in place of the `ResourceLocation` here! +Stats are referred to by **reference**, not by resource location's string value. + +Unless you are making your own stat and have a reference to `ResourceLocation` on hand, do not use this method. +<<< + +**Returns** +A `Stat` coming from the `CUSTOM` field corresponding to the provided `id`. + +--- + +### `getSound` + +```js +Utils.getSound(id) +``` + +**Parameters** +- `[js]id`: The sound's resource location. It may be a string. + +**Returns** +A `SoundEvent` corresponding to the given `id`, or `[js]null` if the sound event doesn't exist under the provided ID. + +--- + +### `findCreativeTab` + +```js +Utils.findCreativeTab(id) +``` + +**Parameters** +- `[js]id`: The creative tab's resource location. It may be a string representing the creative mode tab, for example `[js]'minecraft:building_blocks'`. + +**Returns** +A `CreativeModeTab` corresponding to the given `id`, or `[js]null` if the creative mode tab doesn't exist under the provided ID. + +--- + +## Lazy and asynchronous Java + +### `lazy` + +```js +Utils.lazy(supplier) +``` + +Creates a lazy supplier. After the first `get` call to the resulting supplier, its return value is [memoized](https://en.wikipedia.org/wiki/Memoization) and never forgotten, unless done explicitly with its `forget` method. + +**Parameters** +- `[js]supplier`: A [[/ref/java/functional-interface/Supplier|`Supplier`]]. It may be a JS function that takes no parameters and returns a value, for example `[js]() => { return 42 }`. + +**Returns** +A [[/ref/java/utils/Lazy|`Lazy`]] supplier corresponding to the given `[js]supplier`. + +--- + +### `expiringLazy` + +```js +Utils.expiringLazy(supplier, duration) +``` + +Creates an expiring lazy supplier. Its [memoized](https://en.wikipedia.org/wiki/Memoization) value expires after the specified duration. + +**Parameters** +- `[js]supplier`: A [[/ref/java/functional-interface/Supplier|`Supplier`]]. It may be a JS function that takes no arguments and returns a value, for example `[js]() => { return 42 }`. +- `[js]duration`: A [`Duration`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/Duration.html). It may be also: + - a number representing milliseconds, for example `[js]2000`, + - or a string representing a duration, with format being the one used in [`Duration#parse`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/Duration.html#parse(java.lang.CharSequence)) static method. For example, `[js]'PT2S'` represents a duration of 2 seconds. + +**Returns** +A [[/ref/java/utils/Lazy|`Lazy`]] supplier corresponding to the given `[js]supplier`, which forgets about its [memoized](https://en.wikipedia.org/wiki/Memoization) value after the specified `[js]duration`. + +--- + +### `runAsync` + +```js +Utils.runAsync(runnable) +``` + +Runs the provided runnable function in KubeJS' background thread. + +**Parameters** +- `[js]runnable`: Any Java class that implements the [`Runnable`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Runnable.html) interface. It may be also a JS function that takes no arguments and doesn't return anything, for example `[js]() => { console.log('Ran asynchronously!') }` + +**Returns** +A [`CompletableFuture`]({future-link}) representing the eventual completion or failure of the asynchronous call. +The return type of this asynchronous call is `void` (does not return anything). +(`CompletableFuture` in Java fulfills similar role to [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) found in JavaScript) + +--- + +### `supplyAsync` + +```js +Utils.supplyAsync(supplier) +``` + +Runs the provided supplier function in KubeJS' background thread. + +**Parameters** +- `[js]supplier`: A [[/ref/java/functional-interface/Supplier|`Supplier`]]. It may be also a JS function that takes no arguments and returns a value, for example `[js]() => { return 'Asynchronously supplied!' }` + +**Returns** +A [`CompletableFuture`]({future-link}) representing the eventual completion or failure of the asynchronous call. +The return type of this asynchronous call is `Object` (represents anything that the provided `supplier` can supply). +(`CompletableFuture` in Java fulfills similar role to [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) found in JavaScript) + +--- +# Other + +### `getSystemTime` + +```js +Utils.getSystemTime() +Utils.systemTime // read-only bean +``` + +**Returns** +The difference between current time and midnight, January 1, 1970, UTC, in milliseconds. +Also known as [Unix time](https://en.wikipedia.org/wiki/Unix_time). + +--- + +### `isWrapped` + +```js +Utils.isWrapped(object) +``` + +**Returns** +`[js]true` if object's class implements the [`WrappedJS`](https://github.com/KubeJS-Mods/KubeJS/blob/main/src/main/java/dev/latvian/mods/kubejs/util/WrappedJS.java) marker interface, `[js]false` if it does not. + +--- + +# Source + +([UtilsWrapper.java](https://github.com/KubeJS-Mods/KubeJS/blob/main/src/main/java/dev/latvian/mods/kubejs/plugin/builtin/wrapper/UtilsWrapper.java)) \ No newline at end of file diff --git a/wiki/ref/wrappers/en.yml b/wiki/ref/wrappers/en.yml new file mode 100644 index 00000000..663f8450 --- /dev/null +++ b/wiki/ref/wrappers/en.yml @@ -0,0 +1,2 @@ +title: "Wrappers" +description: "Classes that turn strings and other JS objects into Java objects" \ No newline at end of file diff --git a/wiki/test/page.kubedoc b/wiki/test/page.kubedoc index 59282fd1..54f5a82d 100644 --- a/wiki/test/page.kubedoc +++ b/wiki/test/page.kubedoc @@ -59,7 +59,7 @@ Inline `code` and `code II` and `code *III*` Inline image ![[emoji:test.png|Test]] test [[@000001]] [[[/tutorials/block-registry]]] -[[[/ref/BlockBuilder]]] +[[[/ref/builders/BlockBuilder]]] [[[/fake-page]]] ---