Skip to content

Commit

Permalink
Add docs
Browse files Browse the repository at this point in the history
  • Loading branch information
stirante committed Dec 5, 2023
1 parent 6064667 commit 89d1a0f
Show file tree
Hide file tree
Showing 6 changed files with 379 additions and 1 deletion.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ import { Vec3 } from "@bedrock-oss/bedrock-boost";
import { world } from "@minecraft/server";

world.beforeEvents.itemUse.subscribe((event) => {

event.source.applyImpulse(Vec3.from(event.source.getViewDirection()).setY(0).normalize().multiply(2));
})

Expand Down Expand Up @@ -79,6 +78,16 @@ Timings.begin("big operation 2");
Timings.end();
```

### ChatColor and ColorJSON classes

```typescript
import { Logger } from "@bedrock-oss/bedrock-boost"

const log = Logger.getLogger("main", "tag1", "tag2");
log.info("Hello, Minecraft World!");
```
```
### Logger
```typescript
Expand Down
15 changes: 15 additions & 0 deletions docs/cache.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Cache

In Minecraft Bedrock Script API, native calls to the game engine are often costly and should be avoided when possible. For example, calling `world.getDimension()` in a loop will cause the script to get the dimension from the game engine for each iteration, which can be very slow. To avoid this, we can cache the dimension object.

Currently, only the `Dimension` objects are cached, but more objects may be added in the future.

## Usage

The following example will get the dimension object for the overworld and cache it. If the dimension object is already cached, it will return the cached object.

```typescript
import { getDimension } from "@bedrock-oss/bedrock-boost";

const dimension = getDimension("overworld");
```
153 changes: 153 additions & 0 deletions docs/colorJson.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
# ColorJSON

## Overview

The `ColorJSON` class is designed to transform various data types into a chat-friendly, colored JSON representation. It offers a range of customization options for the formatting and styling of JSON output. This documentation outlines how to use the `ColorJSON` class, including its properties and methods.

### Key Features:

- Color customization for different JSON elements.
- Inline threshold settings for compact JSON representation.
- Maximum depth control for object traversal.
- Class name inclusion in output.
- Ability to override methods for custom formatting.
- Cycle detection and handling.

## Usage

### Initialization

```javascript
import ColorJSON from '@bedrock-oss/bedrock-boost';
const jsonFormatter = new ColorJSON();// or use default instance `ColorJSON.DEFAULT`
```

### Basic JSON Stringification

To convert a value to a colored JSON string:

```javascript
const result = jsonFormatter.stringify(yourValue);
```

### Customization

#### Tokens

Customize JSON tokens like braces, brackets, comma, etc.:

```javascript
jsonFormatter.OpenObject = '{';
jsonFormatter.CloseObject = '}';
// ...similarly for other tokens
```

#### Inline Threshold

Set the inline threshold to control how short arrays and objects representation must be to be displayed inline:

```javascript
jsonFormatter.InlineThreshold = 60;
```
#### Maximum Depth

Set the maximum depth to control how deep the object traversal must go:

```javascript
jsonFormatter.MaxDepth = 5; // or 0 for unlimited
```


#### Class Names

Toggle inclusion of class names:

```javascript
jsonFormatter.IncludeClassNames = true; // or false
```

#### Colors

Customize colors for various elements:

```javascript
jsonFormatter.OpenCloseObjectColor = ChatColor.YELLOW;
jsonFormatter.StringColor = ChatColor.DARK_GREEN;
// ...similarly for other color properties
```

### Customization through Method Overriding

#### Overridable Methods

The `ColorJSON` class contains several methods intended for overriding to customize the output. These methods handle the stringification of different data types and structural elements in JSON.

- `stringifyString(value: string): string`
- `stringifyNumber(value: number): string`
- `stringifyBoolean(value: boolean): string`
- `stringifyFunction(value: function): string`
- `stringifyNull(): string`
- `stringifyUndefined(): string`
- `stringifyCycle(): string`
- `stringifyArray(value: any[]): string`
- `stringifyObject(value: object, className: string, entries: any[][], indentLevel: number): string`

#### How to Override

To override these methods, extend the `ColorJSON` class and redefine the methods as per your requirements.

```javascript
class CustomColorJSON extends ColorJSON {
// Override methods here
stringifyString(value) {
// Custom implementation
}

// ... other overrides
}
```

#### Example of Overriding

```javascript
class MyColorJSON extends ColorJSON {
stringifyString(value) {
return `${this.StringColor}["${value}"]${ChatColor.RESET}`;
}

stringifyNumber(value) {
return `${this.NumberColor}{${value}}${ChatColor.RESET}`;
}
// ... other method overrides
}
```

#### Using Customized Class

```javascript
const jsonFormatter = new MyColorJSON();
const result = jsonFormatter.stringify(yourValue);
```

### Cycle Detection and Handling

The class automatically detects cycles within objects and arrays to prevent infinite loops.

## Examples

### Basic Example

```javascript
const data = { name: "Alice", age: 30, active: true };
const coloredJson = jsonFormatter.stringify(data);
world.sendMessage(coloredJson);
```

### Customized Example

```javascript
jsonFormatter.StringColor = ChatColor.BLUE;
jsonFormatter.BooleanColor = ChatColor.RED;
const customColoredJson = jsonFormatter.stringify(data);
world.sendMessage(customColoredJson);
```
79 changes: 79 additions & 0 deletions docs/logging.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Logging

## Overview

The logging system is designed to provide a flexible and efficient way to handle log messages in Minecraft Bedrock Script API. It leverages TypeScript to define log levels, color-coding, and message formatting, offering a customizable logging experience.

## The `LogLevel` Class

The `LogLevel` class is at the core of the logging system. It defines several log levels, each with a numerical level, name, and associated `ChatColor`. These levels include:

- **All**: For logging all messages.
- **Trace**: Detailed information, useful for diagnosing problems.
- **Debug**: General debugging information.
- **Info**: General information about the script's operation.
- **Warn**: Warning messages about potential issues.
- **Error**: Error messages indicating problems that need attention.
- **Fatal**: Critical errors causing the script to abort.
- **Off**: Disables logging.

## The `Logger` Class

The `Logger` class is used for creating and managing loggers with specific names and tags. It provides methods for logging messages at different levels and configuring logging behavior.

### Initialization

The `init` method initializes the logging system, setting up commands and default settings. If not called, the system will initialize automatically when the first logger is created.

### Configuration

- **setLevel**: Sets the global logging level. By default, info and higher levels are enabled.
- **setFilter**: Sets a filter to control which loggers are active. By default, all loggers are active.
- **setFormatFunction**: Customizes how log messages are formatted.
- **setJsonFormatter**: Sets a JSON formatter for stringifying objects and arrays. By default, `ColorJSON.DEFAULT` is used.

### Logging Methods

Each log level has a corresponding method (`trace`, `debug`, `info`, `warn`, `error`, `fatal`) for logging messages. These methods internally use `log` and `logRaw` to process and display messages.

## Usage

To use the logging system, create a `Logger` instance with a specific name and tags. Then, use the appropriate logging methods (`info`, `warn`, `error`, etc.) to log messages. The system will handle formatting and display based on the configured settings.

### Example

```typescript
import { Logger } from "@bedrock-oss/bedrock-boost";

const logger = new Logger("myLogger", "myTag", "anotherTag");

logger.info("Hello, world!", { foo: "bar"});
```

## Commands

The logging system includes 2 commands to control the logging system:

```
scriptevent logger:level <level either as string or as a number>
scriptevent logger:filter <comma separated tags>
```

## Build Options

When using esbuild, you can use `dropLabels` option with `LOGGING` label to remove all logging code from the final bundle.

When using [gametests regolith filter](https://github.com/Bedrock-OSS/regolith-filters/tree/master/gametests), you can configure it like this:
```json
{
"filter": "gametests",
"settings": {
"modules": [
// ...
],
"buildOptions": {
"dropLabels": ["LOGGING"]
}
}
}
```
15 changes: 15 additions & 0 deletions docs/profilingDummy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Profiling dummy

Currently, when profiling a script, the profiler will group the time spent on waiting for the next tick into the last native call. This is not very useful, as it might make it seem like the last native call took a long time, when in reality it was just waiting for the next tick.

To avoid this, we can use a dummy function and group the time spent on waiting for the next tick into that function. This will make the profiler more accurate.

## Usage

Make sure to make this call as late as possible in your script. This is in hopes, that the dummy will be called last in the tick, and therefore will group all the time spent on waiting for the next tick.

```typescript
import { addIdleDummy } from "@bedrock-oss/bedrock-boost";

addIdleDummy();
```
Loading

0 comments on commit 89d1a0f

Please sign in to comment.