### Initialize and Connect dddice SDK Source: https://docs.dddice.com/sdk/js/latest/index Initializes the dddice SDK, establishing a connection to the dddice API and a specific room. Requires a canvas element for rendering and an API key. The start() method initiates the dddice instance, and connect() joins a designated room. ```javascript // import ThreeDDice class if using npm import { ThreeDDice } from 'dddice-js'; // initalize dddice with a element and API key const dddice = new ThreeDDice(document.getElementById("dddice"), ""); // start dddice and connect to a room to receive rolls dddice.start(); dddice.connect(""); // make sure you're in this room! ``` -------------------------------- ### Install dddice-js SDK via npm Source: https://docs.dddice.com/sdk/js/latest/index Installs the dddice JavaScript SDK using npm. This is the primary method for integrating the SDK into projects managed with npm. ```bash npm i dddice-js ``` -------------------------------- ### Get Theme by Slug - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Retrieves a specific theme using its unique slug. This function is part of the API's theme management capabilities. ```javascript theme: { get: ((id) => Promise>) } ``` -------------------------------- ### Get Authorized User - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Fetches details about the currently authenticated user. This is a core function for user-specific operations within the SDK. ```javascript user: { get: (() => Promise>) } ``` -------------------------------- ### Connect to Live Server - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Establishes a connection to the live D_Dice server to receive real-time room events. Requires the user to be a participant in the specified room. ```javascript connect(roomSlug, roomPasscode?, userUuid?): ThreeDDiceAPI; ``` -------------------------------- ### Handle Connection Establishment - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Defines a callback function that executes automatically once a connection to the D_Dice server has been successfully established. ```javascript onConnect(callback): ThreeDDiceAPI; ``` -------------------------------- ### ThreeDDice Canvas and Configuration Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDice Methods for resizing the canvas and setting global configuration options. ```APIDIDOCDOC ## Canvas and Configuration Methods ### resize #### Description Resizes the ThreeDDice canvas to the specified dimensions. #### Method `resize(width, height)` #### Parameters - **width** (number) - The new width of the canvas in pixels. - **height** (number) - The new height of the canvas in pixels. #### Returns ThreeDDice - The ThreeDDice instance for chaining. ### setConfig #### Description Sets global configuration options for the ThreeDDice engine. #### Method `setConfig(config)` #### Parameters - **config** (Partial) - An object containing partial engine configuration settings. #### Returns void ``` -------------------------------- ### Execute Callback on Participant Connect (JavaScript) Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI The `onParticipantConnect` method allows you to register a callback function that will be executed whenever a new participant connects to the room. This excludes your own connection. It requires the room connection to be established first. ```javascript api.onParticipantConnect((connection) => { console.log('Participant connected:', connection); }); ``` -------------------------------- ### Create Guest User Account - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Generates a temporary guest user account, providing a basic string identifier. Useful for unauthenticated access or temporary sessions. ```javascript user: { guest: (() => Promise>) } ``` -------------------------------- ### ThreeDDiceAPI Constructor Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Initializes the ThreeDDiceAPI class to communicate with the dddice API. It can be initialized with an optional API key and application name. ```APIDOC ## Constructor ThreeDDiceAPI ### Description The constructor of the `ThreeDDiceAPI` class. ### Method `new ThreeDDiceAPI(apiKey?, appName?): ThreeDDiceAPI` ### Parameters #### Path Parameters * **apiKey** (string) - Optional - The API key used to communicate with the server * **appName** (string) - Optional - Optional string to identify the application which is communicating with the API ### Returns `ThreeDDiceAPI` ``` -------------------------------- ### ThreeDDice Theme and Rendering Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDice Methods for loading theme resources and controlling the rendering process. ```APIDOC ## Theme and Rendering Methods ### loadThemeResources #### Description Loads all necessary assets (meshes, textures, sounds) for a specified dice theme. This method is debounced to process the loading queue efficiently. #### Method `loadThemeResources(id, processQueue?)` #### Parameters - **id** (string) - The unique identifier of the theme. - **processQueue** (boolean) - Optional. Defaults to `true`. Determines if the loading queue should be processed. #### Returns string[] - A list of items that have been queued for loading. ### start #### Description Initializes and starts the ThreeDDice renderer. #### Method `start()` #### Returns ThreeDDice - The ThreeDDice instance for chaining. ### stop #### Description Stops the ThreeDDice renderer. #### Method `stop()` #### Returns ThreeDDice - The ThreeDDice instance for chaining. ``` -------------------------------- ### Activate User Account - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Initiates the process for activating a user account, returning activation details like expiration time and a code. It also provides a promise for an API key upon successful activation. ```javascript user: { activate: (() => Promise<{ expiresAt: string; code: string; apiKey: Promise; }>) } ``` -------------------------------- ### User API Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Actions for managing user accounts, including retrieving user information, creating guest accounts, and activating user codes. ```APIDOC ## GET /user ### Description Get information about the currently authorized user. ### Method GET ### Endpoint /user ### Response #### Success Response (200) - **user** (IUser) - The currently authorized user object. #### Response Example { "user": { "uuid": "user-uuid-123", "username": "testuser" } } ``` ```APIDOC ## POST /user/guest ### Description Creates a new guest user account. ### Method POST ### Endpoint /user/guest ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the guest user was created. #### Response Example { "message": "Guest user created successfully." } ``` ```APIDOC ## POST /user/activate ### Description Initiates the code activation flow for a user. ### Method POST ### Endpoint /user/activate ### Response #### Success Response (200) - **expiresAt** (string) - The expiration date of the activation code. - **code** (string) - The activation code. - **apiKey** (string | undefined) - The API key, if available. #### Response Example { "expiresAt": "2024-12-31T23:59:59Z", "code": "activation-code-abc", "apiKey": "user-api-key-xyz" } ``` -------------------------------- ### Room Management API Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI APIs for joining, leaving, and updating room details. ```APIDOC ## POST /room/join ### Description Joins a room using its slug and an optional passcode if the room is private. ### Method POST ### Endpoint `/room/join` ### Parameters #### Query Parameters - **slug** (string) - Required - Room slug - **passcode** (string) - Optional - Passcode for access if the room is private ### Request Example ```json { "slug": "example-room-slug", "passcode": "optional-private-passcode" } ``` ### Response #### Success Response (200) - **room** (IRoom) - Information about the joined room #### Response Example ```json { "room": { "id": "room-id", "name": "Example Room", "is_public": false, "slug": "example-room-slug" } } ``` ``` ```APIDOC ## POST /room/leave ### Description Leaves a room using its slug and an optional participant ID. ### Method POST ### Endpoint `/room/leave` ### Parameters #### Query Parameters - **slug** (string) - Required - Room slug - **participantId** (string) - Optional - The ID of the participant to remove ### Request Example ```json { "slug": "example-room-slug", "participantId": "optional-participant-id" } ``` ### Response #### Success Response (200) - **room** (IRoom) - Information about the room after the participant has left #### Response Example ```json { "room": { "id": "room-id", "name": "Example Room", "is_public": true, "slug": "example-room-slug" } } ``` ``` ```APIDOC ## PUT /room/update ### Description Updates room details such as name, public status, or passcode. ### Method PUT ### Endpoint `/room/update` ### Parameters #### Query Parameters - **slug** (string) - Required - Room slug #### Request Body - **room** (object) - Required - Object containing room data to patch - **name** (string) - Optional - Room name to change to - **is_public** (boolean) - Optional - Set to true to make room public, false to make private - **passcode** (string) - Optional - Passcode to use for a private room (when is_public is false) ### Request Example ```json { "slug": "example-room-slug", "room": { "name": "Updated Room Name", "is_public": false, "passcode": "new-secret-passcode" } } ``` ### Response #### Success Response (200) - **room** (IRoom) - Updated room information #### Response Example ```json { "room": { "id": "room-id", "name": "Updated Room Name", "is_public": false, "slug": "example-room-slug" } } ``` ``` ```APIDOC ## POST /room/updateBackground ### Description Updates the room's background by uploading a new file. ### Method POST ### Endpoint `/room/updateBackground` ### Parameters #### Query Parameters - **slug** (string) - Required - Room slug #### Request Body - **file** (File) - Required - File object (as created by a file input) containing the file to upload ### Request Example ```json { "slug": "example-room-slug", "file": "" } ``` ### Response #### Success Response (200) - **room** (IRoom) - Updated room information #### Response Example ```json { "room": { "id": "room-id", "name": "Example Room", "slug": "example-room-slug" } } ``` ``` -------------------------------- ### Listen for Local Events (JavaScript) Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI The `listenLocal` method allows you to register a callback function to listen for specific local events. It requires the event name (string) and the callback function to be executed when the event occurs. This method returns the API instance for chaining. ```javascript api.listenLocal('myCustomEvent', (data) => { console.log('Received local event:', data); }); ``` -------------------------------- ### Connection Methods API Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Methods for managing real-time connections to the Dddice server. ```APIDOC ## connect ### Description Connect to the live server and begin listening to room events. The user must be a participant in a room to listen for events. ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters - **roomSlug** (string) - Required - The slug of the room to connect to. - **roomPasscode** (string) - Optional - The private passcode for accessing the room. - **userUuid** (string) - Optional - The personal user UUID to listen for whispers. ### Response #### Success Response (ThreeDDiceAPI) Returns the `ThreeDDiceAPI` instance for chaining. #### Response Example // Assuming 'api' is an instance of ThreeDDiceAPI api.connect('room-slug', 'room-password', 'user-uuid'); ``` ```APIDOC ## disconnect ### Description Disconnect from the live server and stop listening to room events. ### Method Instance Method ### Endpoint N/A ### Response #### Success Response (ThreeDDiceAPI) Returns the `ThreeDDiceAPI` instance for chaining. #### Response Example // Assuming 'api' is an instance of ThreeDDiceAPI api.disconnect(); ``` ```APIDOC ## listen ### Description Listen for specific events and execute a callback function when the event is fired. ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters - **event** (RoomUpdated | ThreeDDiceRollEvent | ThreeDDiceDiceBoxEvent) - Required - The event to listen for. - **callback** (RoomEventCallback | RollEventCallback | DiceBoxEventCallback) - Required - The function to execute when the event is fired. ### Throws APIRoomConnectError - If the room connection has not been established. ### Response #### Success Response (ThreeDDiceAPI) Returns the `ThreeDDiceAPI` instance for chaining. #### Response Example // Example for listening to room updates api.listen(RoomUpdated, (data) => { console.log('Room updated:', data); }); // Example for listening to roll events api.listen(ThreeDDiceRollEvent, (data) => { console.log('Dice rolled:', data); }); // Example for listening to dice box events api.listen(ThreeDDiceDiceBoxEvent, (data) => { console.log('Dice box event:', data); }); ``` ```APIDOC ## stopListening ### Description Stop listening for a specific event. ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters - **event** (RoomUpdated | ThreeDDiceRollEvent | ThreeDDiceDiceBoxEvent) - Required - The event to stop listening for. - **callback** (RoomEventCallback | RollEventCallback | DiceBoxEventCallback) - Required - The callback function that was previously registered. ### Throws APIRoomConnectError - If the room connection has not been established. ### Response #### Success Response (ThreeDDiceAPI) Returns the `ThreeDDiceAPI` instance for chaining. #### Response Example // Assuming 'myRoomCallback' was previously registered with api.listen(RoomUpdated, myRoomCallback) api.stopListening(RoomUpdated, myRoomCallback); ``` ```APIDOC ## onConnectionStateChange ### Description Execute a callback function when the connection state changes. ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters - **callback** ((state: string) => any) - Required - The function to execute when the connection state changes. ### Response #### Success Response (ThreeDDiceAPI) Returns the `ThreeDDiceAPI` instance for chaining. #### Response Example api.onConnectionStateChange((state) => { console.log('Connection state:', state); }); ``` ```APIDOC ## onConnectionError ### Description Execute a callback function when the connection throws an error. ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters - **callback** (ConnectionErrorCallback) - Required - The function to execute when a connection error occurs. ### Response #### Success Response (ThreeDDiceAPI) Returns the `ThreeDDiceAPI` instance for chaining. #### Response Example api.onConnectionError((error) => { console.error('Connection error:', error); }); ``` ```APIDOC ## onConnect ### Description Execute a callback function when a connection is established. ### Method Instance Method ### Endpoint N/A ### Parameters #### Path Parameters - **callback** (ConnectionCreatedCallback) - Required - The function to execute when a connection is established. ### Response #### Success Response (ThreeDDiceAPI) Returns the `ThreeDDiceAPI` instance for chaining. #### Response Example api.onConnect(() => { console.log('Successfully connected!'); }); ``` -------------------------------- ### Define Room Lighting Settings with ILightingSettings Interface (TypeScript) Source: https://docs.dddice.com/sdk/js/latest/interfaces/ILightingSettings This snippet defines the ILightingSettings interface, used to configure ambient and spotlight lighting properties such as color and intensity. It specifies that each property is of type 'number'. ```typescript interface ILightingSettings { ambientColor: number; ambientIntensity: number; spotlightColor: number; spotlightIntensity: number; } ``` -------------------------------- ### ThreeDDiceAPI Methods Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Provides methods for connecting and disconnecting from the dddice server, managing event listeners, and handling connection state changes. ```APIDOC ## Methods ### connect * **Description**: Connects to the dddice API and live server. * **Signature**: `connect(): Promise` ### disconnect * **Description**: Disconnects from the dddice API and live server. * **Signature**: `disconnect(): Promise` ### listen * **Description**: Starts listening for events from the dddice server. * **Signature**: `listen(): Promise` ### stopListening * **Description**: Stops listening for events from the dddice server. * **Signature**: `stopListening(): Promise` ### onConnectionStateChange * **Description**: Registers a callback function to be executed when the connection state changes. * **Signature**: `onConnectionStateChange(callback: (state: ConnectionState) => void): void` ### onConnectionError * **Description**: Registers a callback function to be executed when a connection error occurs. * **Signature**: `onConnectionError(callback: (error: any) => void): void` ### onConnect * **Description**: Registers a callback function to be executed when the connection is successfully established. * **Signature**: `onConnect(callback: () => void): void` ### onParticipantConnect * **Description**: Registers a callback function to be executed when a participant connects to the room. * **Signature**: `onParticipantConnect(callback: (participant: IParticipant) => void): void` ### onParticipantDisconnect * **Description**: Registers a callback function to be executed when a participant disconnects from the room. * **Signature**: `onParticipantDisconnect(callback: (participant: IParticipant) => void): void` ### sendLocal * **Description**: Sends a local event to the dddice server. * **Signature**: `sendLocal(event: string, payload: any): void` ### listenLocal * **Description**: Registers a callback function to listen for local events from the dddice server. * **Signature**: `listenLocal(event: string, callback: (payload: any) => void): void` ``` -------------------------------- ### Execute Callback on Participant Disconnect (JavaScript) Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI The `onParticipantDisconnect` method enables you to set up a callback function that runs when a participant disconnects or loses their connection. This callback is triggered for each participant, excluding yourself. The room connection must be active. ```javascript api.onParticipantDisconnect((connection) => { console.log('Participant disconnected:', connection); }); ``` -------------------------------- ### IRoom Interface Documentation Source: https://docs.dddice.com/sdk/js/latest/interfaces/IRoom Detailed documentation for the IRoom interface, outlining its properties and their types as used in the dddice JavaScript SDK. ```APIDOC ## Interface IRoom Represents a room within the dddice platform, containing information about its settings, participants, and metadata. ### Properties - **bg_file_path** (string) - Optional - The file path for the room's background. - **created_at** (string) - The timestamp when the room was created. - **custom_slug** (string) - Optional - A custom slug for the room, if set. - **id** (number) - The unique identifier for the room. - **is_public** (boolean) - Indicates whether the room is public or private. - **name** (string) - The name of the room. - **participants** (IRoomParticipant[]) - An array of participants in the room. - **passcode** (string) - The passcode for accessing the room (if applicable). - **slug** (string) - The unique slug for the room. - **updated_at** (string) - The timestamp when the room was last updated. - **user** (IUser) - The user who created or owns the room. - **settings** (IRoomSettings) - The settings associated with the room. ### Example Usage (Conceptual) ```javascript // Assuming you have a room object conforming to the IRoom interface: const myRoom = { id: 123, name: "My Awesome Room", is_public: true, created_at: "2023-10-27T10:00:00Z", updated_at: "2023-10-27T10:30:00Z", participants: [], passcode: "", slug: "my-awesome-room", user: { /* IUser object */ }, settings: { /* IRoomSettings object */ } }; console.log(myRoom.name); // Output: My Awesome Room ``` ``` -------------------------------- ### Listen for Connection State Changes - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Registers a callback function to be executed whenever the connection state to the D_Dice server changes. An APIConnectError may be thrown if the live connection isn't established. ```javascript onConnectionStateChange(callback): ThreeDDiceAPI; ``` -------------------------------- ### Set App Name - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Sets the name of the application using the SDK. This might be used for analytics or identification purposes. ```javascript set appName(appName): void; ``` -------------------------------- ### IParticipantSettings Interface Source: https://docs.dddice.com/sdk/js/latest/interfaces/IParticipantSettings Defines the settings that can be configured for a participant within a DDDice room. This includes options like whether the default dice tray should be shown to the Game Master. ```APIDOC ## Interface IParticipantSettings ### Description Room Participant Settings ### Properties #### defaultDiceTrayToGM - **defaultDiceTrayToGM** (boolean) - Optional - Determines if the default dice tray is shown to the Game Master. ``` -------------------------------- ### ThreeDDice Event Handling Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDice Methods for managing event listeners and callbacks for various ThreeDDice events. ```APIDOC ## Event Handling Methods ### off #### Description Removes a callback function from a specified event listener. #### Method `off(event)` #### Parameters - **event** (RoomUpdated | ThreeDDiceRollEvent) - The event to stop listening to. #### Returns ThreeDDice - The ThreeDDice instance for chaining. ### on #### Description Adds a callback function to a specified event listener. #### Method `on(event, callback)` #### Parameters - **event** (DiceEvent) - The event to listen on. - **callback** (DiceEventCallback) - The function to execute when the event is fired. #### Overloads - `on(event: RoomUpdated, callback: RoomEventCallback): ThreeDDice` - `on(event: ThreeDDiceRollEvent, callback: RollEventCallback): ThreeDDice` #### Returns ThreeDDice - The ThreeDDice instance for chaining. ``` -------------------------------- ### Interface ILight Source: https://docs.dddice.com/sdk/js/latest/interfaces/ILight The ILight interface defines the structure for lighting configurations within the dddice JavaScript SDK. ```APIDOC ## Interface ILight ### Description The ILight interface defines the properties for configuring lighting in the dddice environment. It includes settings for ambient and directional light, as well as shadow casting. ### Properties #### ambientColor - **Type**: `string | number` - **Description**: The color of the ambient light. #### ambientIntensity - **Type**: `number` - **Description**: The intensity of the ambient light. #### castShadows - **Type**: `boolean` - **Description**: Determines if shadows should be cast by the light source. #### direction - **Type**: `object` - **Description**: Defines the direction of the light source. - **x** (`number`) - The x-component of the direction vector. - **y** (`number`) - The y-component of the direction vector. - **z** (`number`) - The z-component of the direction vector. #### directionalColor - **Type**: `string | number` - **Description**: The color of the directional light. #### directionalIntensity - **Type**: `number` - **Description**: The intensity of the directional light. ### Example Usage (Conceptual) ```javascript const lightConfig: ILight = { ambientColor: '#ffffff', ambientIntensity: 0.5, castShadows: true, direction: { x: 0, y: -1, z: 0 }, directionalColor: '#0000ff', directionalIntensity: 1.0 }; ``` ``` -------------------------------- ### ThreeDDiceAPI Properties Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Exposes properties for accessing room and user information, as well as methods for interacting with dicebox, roll, and room functionalities. ```APIDOC ## Properties ### `Optional` roomSlug * **Type**: string * **Description**: Room Slug ### `Optional` userUuid * **Type**: string * **Description**: UUID of the connected user ### diceBox * **Type**: object * **Description**: API DiceBox Actions * **list**: `(filter?) => Promise>` - List the themes in a user's dicebox. Accepts an optional filter string. * **next**: `() => Promise>` - Retrieves the next set of themes. ### roll * **Type**: object * **Description**: API Roll Actions * **create**: `(dice: IDiceRoll[], options?: Partial) => Promise>` - Create a new roll. Requires an array of dice and accepts optional roll options. * **get**: `(id: string) => Promise>` - Get a roll by ID. Requires the roll's ID. * **update**: `(id: string, payload: { dice: Partial[]; room?: string; }) => Promise>` - Update an existing roll. Requires the roll's ID and a payload containing partial dice information and an optional room ID. * **updateBulk**: `(rolls: { uuid: string; dice: Partial[]; room?: string; }[]) => Promise>` - Bulk update multiple rolls. Requires an array of roll objects, each with a UUID, partial dice information, and an optional room ID. ### room * **Type**: object * **Description**: API Room Actions * **list**: `() => Promise>` - List all created or joined rooms. * **create**: `() => Promise>` - Create a new room. * **get**: `(slug: string, passcode?: string) => Promise>` - Get a room by its slug. Accepts an optional passcode. * **join**: `(slug: string, passcode?: string) => Promise>` - Join a room using its slug. Accepts an optional passcode. * **leave**: `(slug: string, participantId?: string) => Promise>` - Leave a room using its slug. Accepts an optional participant ID. * **updateParticipant**: `(slug: string, participantId: string, data: any) => Promise>` - Update a participant's information in a room. * **updateRolls**: `(slug: string, dice: any, participant?: string) => Promise` - Update rolls within a specific room. * **update**: `(slug: string, room: any) => Promise` - Update room details. * **deleteRolls**: `(slug: string) => Promise` - Delete all rolls in a room. * **updateBackground**: `(slug: string, file: File) => Promise` - Update the background of a room with a file. ``` -------------------------------- ### Handle Connection Errors - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Sets up a callback function to be invoked when the D_Dice server connection encounters an error. An APIRoomConnectError may be thrown if the room connection isn't established. ```javascript onConnectionError(callback): ThreeDDiceAPI; ``` -------------------------------- ### Theme API Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Actions related to retrieving and managing themes within the Dddice platform. ```APIDOC ## GET /theme/{id} ### Description Get a theme by its unique slug. ### Method GET ### Endpoint /theme/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique slug of the theme to retrieve. ### Response #### Success Response (200) - **theme** (ITheme) - The retrieved theme object. #### Response Example { "theme": { "id": "dark", "name": "Dark Theme", "colors": { "primary": "#000", "secondary": "#333" } } } ``` -------------------------------- ### Listen for Room Events - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Subscribes to specific room events and triggers a provided callback function when the event occurs. Supports multiple event types like RoomUpdated, Roll, and DiceBox events. ```javascript listen(event, callback): ThreeDDiceAPI; // Example for Roll events: listen(event: ThreeDDiceRollEvent, callback: RollEventCallback): ThreeDDiceAPI; // Example for DiceBox events: listen(event: ThreeDDiceDiceBoxEvent, callback: DiceBoxEventCallback): ThreeDDiceAPI; ``` -------------------------------- ### Accessors API Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI APIs for managing the API key and application name. ```APIDOC ## Accessor: apiKey ### Description Manages the API key for authentication. ### Method GET, SET ### Endpoint N/A (Instance property) ### Parameters #### Setter Parameters - **apiKey** (string | undefined) - Required - The API key to set. ### Response #### Success Response (void) No response body for setter. #### Response Example (GET) "user-api-key-xyz" ``` ```APIDOC ## Accessor: appName ### Description Sets the application name for the SDK. ### Method SET ### Endpoint N/A (Instance property) ### Parameters #### Setter Parameters - **appName** (string | undefined) - Required - The name of the application. ### Response #### Success Response (void) No response body. ``` -------------------------------- ### IBindableTextureSrc Interface Documentation Source: https://docs.dddice.com/sdk/js/latest/interfaces/IBindableTextureSrc Details the properties and usage of the IBindableTextureSrc interface. ```APIDOC ## Interface IBindableTextureSrc Config texture parameter with shader binding info. Can be single texture or per-dice-type. Note: only one of "src" or "dice" keys should be present. ### Properties - **binding** (string) - Required - Binding type. For example: "umap", "u_numberMap", etc. - **src** (DieDefinition) - Required - URI to texture(s) used by die types. - **encoding** (string) - Optional - The texture encoding, 'sRGB' or 'linear'. If left blank the render will assume diffuse maps are in sRGB and all others are in linear. ``` -------------------------------- ### Define Room Physics Settings with IPhysicsSettings (TypeScript) Source: https://docs.dddice.com/sdk/js/latest/interfaces/IPhysicsSettings The IPhysicsSettings interface defines the parameters for room physics in the dddice SDK. It includes gravity and throw speed. ```typescript interface IPhysicsSettings { gravity: number; throwSpeed: number; } ``` -------------------------------- ### ThreeDDice Screenshot Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDice Method for capturing a screenshot of the ThreeDDice canvas. ```APIDOC ## Screenshot Method ### screenshot #### Description Captures a screenshot of the current canvas content. #### Method `screenshot(mimeType)` #### Parameters - **mimeType** (string) - The MIME type of the image format for the screenshot (e.g., 'image/png', 'image/jpeg'). #### Returns undefined | string - The screenshot as a Data URI string, or undefined if an error occurs. ``` -------------------------------- ### ThreeDDice Class Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDice The main class for interacting with the dddice service. It allows for initialization, connection to rooms, managing dice, and handling events. ```APIDOC ## Class ThreeDDice ThreeDDice Class ### Constructors #### constructor * `new ThreeDDice(canvas?, apiKey?, config?): ThreeDDice` * Construct and initialize the object ##### Parameters * `Optional` **canvas**: HTMLCanvasElement - Canvas element * `Optional` **apiKey**: string - Required if connecting to the dddice API * `Optional` **config**: Partial - Optional configuration to change the look and feel of the renderer #### Returns ThreeDDice ### Properties #### `Static` DefaultConfig * **DefaultConfig**: IEngineConfig = ... * Default Config #### `Optional` api * **api?**: ThreeDDiceAPI * API Connection * Available after calling connect #### `Optional` apiKey * **apiKey?**: string * API Key #### `Optional` canvas * **canvas?**: HTMLCanvasElement * Canvas ### Accessors #### controlsEnabled * `get controlsEnabled(): boolean` - Get mouse/pointer controls enabled * `set controlsEnabled(enabled): void` - Set mouse/pointer controls enabled * ##### Parameters: * **enabled**: boolean #### height * `get height(): number` - Canvas Height #### isDiceThrowing * `get isDiceThrowing(): boolean` - Get if a roll is currently animating #### diceCount * `get diceCount(): number` - Get the number of dice currently being rendered #### version * `get version(): string` - Get the current version of dddice #### width * `get width(): number` - Canvas width ### Methods #### `Static` isWebGLAvailable * `isWebGLAvailable(): boolean` - Check if WebGL is available #### addCallback * `addCallback(eventName, callback): void` - Add document/canvas event callback ##### Parameters: * **eventName**: string * **callback**: ((...params) => void) * `(...params): void` * #### Parameters: * `Rest` **...params**: any[] #### clear * `clear(): void` - Clear all dice from canvas #### connect * `connect(roomSlug, roomPasscode?, userUuid?): ThreeDDice` - Connect to the live server and begin listening to room events. * **Note**: Your user must be a participant in a room in order to listen to events, otherwise an error is thrown. ##### Parameters: * **roomSlug**: string - Room slug to listen on * `Optional` **roomPasscode**: string - Private passcode to access room * `Optional` **userUuid**: string - Personal User UUID to listen to whispers #### disconnect * `disconnect(): ThreeDDice` - Connect to the live server and begin listening to room events. * **Note**: Your user must be a participant in a room in order to listen to events, otherwise an error is thrown. #### dispatch * `dispatch(event, ...params): ThreeDDice` - Manually trigger an event ##### Parameters: * **event**: DiceEvent | RoomUpdated | ThreeDDiceRollEvent | AddDie - The event to dispatch * `Rest` **...params**: any[] #### getTheme * `getTheme(themeId): ITheme` - Return a loaded theme ##### Parameters: * **themeId**: string #### getThemes * `getThemes(): ITheme[]` - Return all loaded themes #### initialize * `initialize(canvas?, apiKey?, config?, appName?): ThreeDDice` - Initialize object if the default constructor had been called ##### Parameters: * `Optional` **canvas**: HTMLCanvasElement - Canvas element * `Optional` **apiKey**: string - Required if connecting to the dddice API * `Optional` **config**: Partial - Optional configuration to change the look and feel of the renderer * `Optional` **appName**: string - Optional name to identify which application is connecting to dddice #### filter * `filter(participantIds): ThreeDDice` - Limit which participant events are executed This is useful for filtering dice rolls to a select group of players per instance (i.e. creating dice trays) ##### Parameters: * **participantIds**: number[] - The participant IDs of the room #### loadTheme * `loadTheme(theme, overwriteTheme?, fetchPreviews?): ThreeDDice` - Load a theme, including shaders, into the engine ##### Parameters: * **theme**: ITheme * **overwriteTheme**: boolean = false * **fetchPreviews**: boolean = true ``` -------------------------------- ### ThreeDDice Camera Controls Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDice Methods for controlling and resetting the camera view within the ThreeDDice environment. ```APIDOC ## Camera Control Methods ### pause #### Description Pauses camera controls, preventing user interaction with the camera. #### Method `pause()` #### Returns void ### resetCamera #### Description Resets the camera frame to a default top-down view. Useful after disabling camera controls. #### Method `resetCamera()` #### Returns void ### resume #### Description Resumes camera controls, allowing user interaction with the camera. #### Method `resume()` #### Returns void ``` -------------------------------- ### IRoomSettings Interface Source: https://docs.dddice.com/sdk/js/latest/interfaces/IRoomSettings The IRoomSettings interface defines the structure for configuring various room settings, including participant, chat, lighting, physics, and roll. ```APIDOC ## Interface IRoomSettings Room Settings This interface defines the configuration options for a room within the dddice SDK. ### Properties - **participant** (IParticipantSettings) - Settings related to participants in the room. - **chat** (IChatSettings) - Settings related to the chat functionality within the room. - **lighting** (ILightingSettings) - Settings related to lighting effects in the room. - **physics** (IPhysicsSettings) - Settings related to the physics engine of the room. - **roll** (IRollSettings) - Settings related to dice rolling mechanics in the room. ### Property Details #### participant - **Type**: IParticipantSettings - **Description**: Configuration for participant-specific settings. #### chat - **Type**: IChatSettings - **Description**: Configuration for chat-related features. #### lighting - **Type**: ILightingSettings - **Description**: Configuration for visual lighting effects. #### physics - **Type**: IPhysicsSettings - **Description**: Configuration for the room's physics simulation. #### roll - **Type**: IRollSettings - **Description**: Configuration for dice rolling behavior. ``` -------------------------------- ### Disconnect from Live Server - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Terminates the connection to the live D_Dice server, ceasing the reception of room events. ```javascript disconnect(): ThreeDDiceAPI; ``` -------------------------------- ### ThemeSyntaxError Class Source: https://docs.dddice.com/sdk/js/latest/classes/ThemeSyntaxError Details about the ThemeSyntaxError class, including its hierarchy, constructor, and methods. ```APIDOC ## Class ThemeSyntaxError ### Hierarchy * Error * ThemeSyntaxError ### Constructors #### constructor(message: string, expected: any, received: any) Creates a new ThemeSyntaxError instance. **Parameters** * **message** (string) - Required - The error message. * **expected** (any) - Required - The expected value. * **received** (any) - Required - The received value. **Returns** * ThemeSyntaxError - The created ThemeSyntaxError instance. ### Methods #### toString(): string Returns a string representation of the error. **Returns** * string - A string representation of the error. ``` -------------------------------- ### Include dddice-js SDK via CDN Source: https://docs.dddice.com/sdk/js/latest/index Includes the dddice JavaScript SDK directly from a CDN using a script tag. This method is suitable for projects that do not use a package manager or for quick integration. ```html ``` -------------------------------- ### Define Room Participant Settings with IParticipantSettings (TypeScript) Source: https://docs.dddice.com/sdk/js/latest/interfaces/IParticipantSettings The IParticipantSettings interface defines configuration options for participants within a dddice room. Currently, it includes a single boolean property, defaultDiceTrayToGM, to control whether the dice tray is shown to the Game Master by default. This interface is written in TypeScript. ```typescript interface IParticipantSettings { defaultDiceTrayToGM: boolean; } ``` -------------------------------- ### Interface IChatSettings Source: https://docs.dddice.com/sdk/js/latest/interfaces/IChatSettings Defines the structure for chat room settings in the DDDice JavaScript SDK. Allows customization of chat appearance and behavior. ```APIDOC ## Interface IChatSettings ### Description Represents the configuration settings for a chat room within the DDDice SDK. ### Properties - **backgroundColor** (number) - The background color of the chat window. - **deleteAfter** (number) - The time in milliseconds after which messages are automatically deleted. - **fadeAfter** (number) - The time in milliseconds after which messages start to fade. - **isDiceExpanded** (boolean) - Whether the dice display is expanded by default. - **isDiceSorted** (boolean) - Whether the dice are sorted by default. - **isUsernameVisible** (boolean) - Whether usernames are visible in the chat. - **isVisible** (boolean) - Whether the chat window is visible by default. - **textColor** (number) - The text color used in the chat window. - **textSize** (TextSize) - The size of the text in the chat window. (Type: TextSize) ``` -------------------------------- ### Set API Key - JavaScript Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI Configures the API key for authentication. This is essential for making authenticated requests to the D_Dice API. ```javascript set apiKey(apiKey): void; ``` -------------------------------- ### Define IRoomSettings Interface (TypeScript) Source: https://docs.dddice.com/sdk/js/latest/interfaces/IRoomSettings This TypeScript interface defines the structure for room settings in the dddice SDK. It includes properties for participant, chat, lighting, physics, and roll configurations. This interface is essential for setting up and managing dddice rooms. ```typescript interface IRoomSettings { participant: IParticipantSettings; chat: IChatSettings; lighting: ILightingSettings; physics: IPhysicsSettings; roll: IRollSettings; } ``` -------------------------------- ### Participant Management API Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI APIs for updating participant information. ```APIDOC ## PUT /room/{slug}/participant/{participantId} ### Description Updates a participant's information within a room. ### Method PUT ### Endpoint `/room/{slug}/participant/{participantId}` ### Parameters #### Path Parameters - **slug** (string) - Required - Room slug - **participantId** (number) - Required - Participant ID #### Request Body - **data** (Partial) - Required - Participant information to update - **username** (string) - Optional - New username for the participant - **color** (string) - Optional - New color for the participant (e.g., "#FF0000") ### Request Example ```json { "slug": "example-room-slug", "participantId": 123, "data": { "username": "NewUsername", "color": "#00FF00" } } ``` ### Response #### Success Response (200) - **room** (IRoom) - Updated room information #### Response Example ```json { "room": { "id": "room-id", "name": "Example Room", "slug": "example-room-slug" } } ``` ``` -------------------------------- ### IAvailableDie Type Alias Source: https://docs.dddice.com/sdk/js/latest/types/IAvailableDie Defines the structure for an available die, including its ID, type, and an optional notation. ```APIDOC ## Type Alias IAvailableDie ### Description Represents a die definition available in the dddice system. It includes a unique identifier, its type, and an optional user-friendly notation. ### Properties - **id** (string) - Required - The internal reference ID of the die (e.g., 'd6', 'power'). - **type** (IDieType) - Required - The die type, referencing the `IDieType` enum. - **notation** (string) - Optional - An abbreviated notation for displaying the die in roll equations (e.g., "d6", "d%"). ### Example ```json { "id": "d6", "type": "d", "notation": "d6" } ``` ### Response Example (Success) ```json { "id": "d6", "type": "d", "notation": "d6" } ``` ``` -------------------------------- ### Send Local Event Data (JavaScript) Source: https://docs.dddice.com/sdk/js/latest/classes/ThreeDDiceAPI The `sendLocal` method is used to send custom event data locally within the application. It takes an event name (string) and an object containing arbitrary data as parameters. This method does not return any value. ```javascript api.sendLocal('myCustomEvent', { message: 'Hello from SDK!' }); ``` -------------------------------- ### Interface IEngineConfig Definition (TypeScript) Source: https://docs.dddice.com/sdk/js/latest/interfaces/IEngineConfig Defines the configuration object for the dddice engine, specifying properties for audio, background color and opacity, camera settings, dice configurations, optional debug drawing options, lighting, physics, and roll persistence. This interface is crucial for customizing the dddice experience. ```typescript interface IEngineConfig { audio: boolean; autoClear: null | number; bgColor: string | number; bgOpacity: number; camera: ICamera; dice: Partial; drawDebug?: { infoPane: boolean; clearColor: boolean; collisionMeshes: boolean; }; light: ILight; physics: IPhysics; persistRolls?: boolean; } ``` -------------------------------- ### ILight Interface Definition (TypeScript) Source: https://docs.dddice.com/sdk/js/latest/interfaces/ILight Defines the structure for lighting configuration within the dddice SDK. It specifies properties for ambient and directional light sources, including their colors, intensities, and whether they cast shadows. The direction property is a vector defining the orientation of the directional light. ```typescript interface ILight { ambientColor: string | number; ambientIntensity: number; castShadows: boolean; direction: { x: number; y: number; z: number; }; directionalColor: string | number; directionalIntensity: number; } ``` -------------------------------- ### Define IParticleSystem Interface (TypeScript) Source: https://docs.dddice.com/sdk/js/latest/interfaces/IParticleSystem Defines the IParticleSystem interface for configuring particle systems in the dddice JavaScript SDK. It specifies the type for the 'system', 'on', and 'rotate_with_die' properties. ```typescript interface IParticleSystem { system: any; on: string; rotate_with_die: boolean; } ```