@drincs/pixi-vn
Version:
Pixi'VN is a npm package that provides various features for creating visual novels.
1,158 lines (1,124 loc) • 42.6 kB
TypeScript
import { PlayerOptions, Player, ToneAudioNode, Param, ReverbOptions, FeedbackDelayOptions, FreeverbOptions, DelayOptions, PingPongDelayOptions, GateOptions, AutoFilterOptions, BiquadFilterOptions, OnePoleFilterOptions, FeedbackCombFilterOptions, FilterOptions, ChorusOptions, PhaserOptions, TremoloOptions, VibratoOptions, CompressorOptions, MidSideCompressorOptions, MultibandCompressorOptions, LimiterOptions, GreaterThanOptions, GreaterThanZeroOptions, DistortionOptions, BitCrusherOptions, Panner3DOptions, AutoPannerOptions, StereoWidenerOptions } from 'tone';
import * as canvasUtils from '@drincs/pixi-vn/canvas';
import { StoredChoiceInterface, StorageElementType as StorageElementType$1, OpenedLabel as OpenedLabel$1 } from '@drincs/pixi-vn/canvas';
export * from '@drincs/pixi-vn/canvas';
import * as characterUtils from '@drincs/pixi-vn/characters';
export * from '@drincs/pixi-vn/characters';
import { OnErrorHandler, GameUnifier } from '@drincs/pixi-vn/core';
export * from '@drincs/pixi-vn/core';
import * as historyUtils from '@drincs/pixi-vn/history';
export * from '@drincs/pixi-vn/history';
import * as narrationUtils from '@drincs/pixi-vn/narration';
import { NarrationGameState } from '@drincs/pixi-vn/narration';
export * from '@drincs/pixi-vn/narration';
import { UPDATE_PRIORITY, PointData, Container, ContainerOptions, ApplicationOptions } from '@drincs/pixi-vn/pixi.js';
export { AllFederatedEventMap, ApplicationOptions, AssetSrc, AssetsBundle, AssetsManifest, FederatedEvent, LoadParserName, ResolvedAsset, ResolvedSrc, UnresolvedAsset } from '@drincs/pixi-vn/pixi.js';
import * as soundUtils from '@drincs/pixi-vn/sound';
export * from '@drincs/pixi-vn/sound';
import * as storageUtils from '@drincs/pixi-vn/storage';
export * from '@drincs/pixi-vn/storage';
import { LRUCache } from 'lru-cache';
import { CharacterInterface, GameStepState } from '@drincs/pixi-vn';
import { Difference } from 'microdiff';
import { Devtools } from '@pixi/devtools';
interface MediaInterface extends Pick<Player, "blockTime" | "disposed" | "loaded" | "loop" | "loopEnd" | "loopStart" | "mute" | "now" | "playbackRate" | "reverse" | "restart" | "start" | "stop" | "chain" | "disconnect" | "volume" | "state"> {
/**
* Whether the sound is currently paused.
*/
paused: boolean;
/**
* @deprecated Use {@link mute} instead.
*/
muted: boolean;
/**
* @deprecated Use {@link playbackRate} instead.
*/
speed: number;
}
interface MediaMemory extends Partial<Omit<PlayerOptions, "url" | "volume">> {
/**
* The volume of this sound in the linear range [0, 1], where 0 is silence
* and 1 is full volume. Stored and restored in linear form; converted
* to/from Tone.js decibels internally.
*/
volume?: number;
elapsed: number | undefined;
paused: boolean;
delay?: number;
}
interface SoundOptions extends Pick<Partial<PlayerOptions>, "loop" | "autostart" | "fadeIn" | "fadeOut" | "mute" | "loopEnd" | "loopStart" | "reverse" | "playbackRate"> {
/**
* The volume of this sound in the linear range [0, 1], where 0 is silence
* and 1 is full volume. This is converted to decibels internally before
* being passed to the Tone.js Player.
*/
volume?: number;
/**
* A collection of audio filters/effects to apply to this sound.
*
* Install "tone" for the full list of available filters.
*
* @example
* ```ts
* import * as Tone from "tone";
*
* const filters = [new Tone.FeedbackDelay("8n", 0.5)];
* ```
*/
filters?: ToneAudioNode[];
/**
* @deprecated Use {@link playbackRate} instead.
*/
speed?: number;
/**
* @deprecated Use {@link mute} instead.
*/
muted?: boolean;
}
interface SoundPlayOptions extends SoundOptions {
/**
* The delay in seconds before playback starts. If specified, playback is
* scheduled to begin after the delay has elapsed rather than starting
* immediately in a paused state.
*/
delay?: number;
/**
* The offset in seconds from the start of the sound at which to begin playback.
*/
elapsed?: number;
}
interface SoundPlayOptionsWithChannel extends SoundPlayOptions {
/**
* The alias of the audio channel to play the sound on. If the channel does
* not exist it will be created automatically.
* Defaults to `SoundManagerInterface.defaultChannelAlias` ("general").
*/
channel?: string;
}
interface ChannelOptions extends Pick<SoundPlayOptions, "filters" | "muted" | "volume"> {
/**
* Whether this channel is a background channel.
* Background channels are special: media playing on them is not stopped
* when a scene changes, but continues in the background.
*/
background?: boolean;
/**
* The stereo pan position for this channel in the range [-1, 1].
* -1 is full left, 0 is centre, 1 is full right.
* Defaults to 0.
*/
pan?: number;
}
interface AudioChannelInterface {
/**
* The alias of the audio channel. This is used to reference the channel when playing sounds. The alias must be unique among all channels.
*/
readonly alias: string;
/**
* Plays a sound.
* @param alias The media and sound (asset) alias reference.
* @param options The options
* @return The sound instance,
* this cannot be reused after it is done playing. Returns a Promise if the sound
* has not yet loaded.
*/
play(alias: string, options?: SoundPlayOptions): Promise<MediaInterface>;
/**
* Plays a sound.
* @param mediaAlias The media alias reference.
* @param soundAlias The sound (asset) alias reference.
* @param options The options
* @return The sound instance,
* this cannot be reused after it is done playing. Returns a Promise if the sound
* has not yet loaded.
*/
play(mediaAlias: string, soundAlias: string, options?: SoundPlayOptions): Promise<MediaInterface>;
/**
* The stereo pan position for this channel in the range [-1, 1].
* -1 is full left, 0 is centre, 1 is full right.
*/
pan: number;
/**
* The volume of the audio channel, between 0 and 1. This is multiplied with the volume of each sound played through this channel.
*/
volume: number;
/**
* Whether the audio channel is muted. This is combined with the muted state of each sound played through this channel.
*/
muted: boolean;
/**
* The MediaInstances currently playing through this channel. This is read-only and cannot be modified directly. Use the play method to add new MediaInstances to this channel.
*/
readonly mediaInstances: MediaInterface[];
/**
* Whether this channel is a background channel.
* Background channels are special channels. Unlike normal channels, media connected to a background channel does not stop when a scene changes, but continues to play in the background.
*/
readonly background: boolean;
/**
* Stops all media currently playing through this channel.
* @return Instance for chaining.
*/
stopAll(): this;
/**
* Pauses any playing sounds.
* @return Instance for chaining.
*/
pauseAll(): this;
/**
* Resumes any sounds.
* @return Instance for chaining.
*/
resumeAll(): this;
/**
* Toggle muted property for all sounds.
* @return `true` if all sounds are muted.
*/
toggleMuteAll(): boolean;
/**
* Useful for inserting channel-wide audio effects such as reverb, delay or EQ.
*
* Install "tone" to use this method.
*
* @param nodes One or more Tone.js {@link ToneAudioNode} instances to chain in series.
* @return Instance for chaining.
*
* @example
* ```ts
* import * as Tone from "tone";
*
* const channel = sound.findChannel("music");
*
* // Create a reverb effect and wait for its impulse response to be ready.
* const reverb = new Tone.Reverb({ decay: 2.5 });
*
* // Route the channel through the reverb to the master output.
* channel.chain(reverb);
* ```
*/
chain(...nodes: ToneAudioNode[]): this;
/**
* **Advanced** — the raw `Tone.Param<"decibels">` for this channel's volume.
*
* Unlike the {@link volume} property (which uses a linear 0–1 scale), this
* Param works directly in **decibels** and exposes all Tone.js automation
* methods such as `rampTo`, `linearRampTo`, and `exponentialRampTo`.
*
* Use this when you need to smoothly automate volume over time instead of
* setting it instantly.
*
* @example
* ```ts
* const channel = sound.findChannel("music");
*
* // Fade the volume from its current level to -12 dB over 3 seconds.
* channel.volumeParam.rampTo(-12, 3);
*
* // Fade to silence over 2 seconds.
* channel.volumeParam.rampTo(-Infinity, 2);
* ```
*/
readonly volumeParam: Param<"decibels">;
/**
* **Advanced** — the raw `Tone.Param<"audioRange">` for this channel's
* stereo pan position.
*
* Unlike the {@link pan} property (which sets the value instantly), this
* Param exposes all Tone.js automation methods such as `rampTo`,
* `linearRampTo`, and `exponentialRampTo`.
*
* Use this when you need to smoothly automate panning over time instead of
* setting it instantly. Values range from -1 (full left) to 1 (full right).
*
* @example
* ```ts
* const channel = sound.findChannel("music");
*
* // Gradually pan to the left over 3 seconds.
* channel.panParam.rampTo(-1, 3);
*
* // Return to centre over 2 seconds.
* channel.panParam.rampTo(0, 2);
* ```
*/
readonly panParam: Param<"audioRange">;
}
type SoundFilterMemory = ({
filterType: "ReverbFilter";
} & Omit<Partial<ReverbOptions>, "context">) | ({
filterType: "FeedbackDelayFilter";
} & Omit<Partial<FeedbackDelayOptions>, "context">) | ({
filterType: "FreeverbFilter";
} & Omit<Partial<FreeverbOptions>, "context">) | ({
filterType: "DelayFilter";
} & Omit<Partial<DelayOptions>, "context">) | ({
filterType: "PingPongDelayFilter";
} & Omit<Partial<PingPongDelayOptions>, "context">) | ({
filterType: "GateFilter";
} & Omit<Partial<GateOptions>, "context">) | ({
filterType: "AutoFilterFilter";
} & Omit<Partial<AutoFilterOptions>, "context">) | ({
filterType: "BiquadFilterFilter";
} & Omit<Partial<BiquadFilterOptions>, "context">) | ({
filterType: "OnePoleFilterFilter";
} & Omit<Partial<OnePoleFilterOptions>, "context" | "frequency">) | ({
filterType: "FeedbackCombFilterFilter";
} & Omit<Partial<FeedbackCombFilterOptions>, "context">) | ({
filterType: "CustomFilter";
} & Omit<Partial<FilterOptions>, "context">) | ({
filterType: "ChorusFilter";
} & Omit<Partial<ChorusOptions>, "context">) | ({
filterType: "PhaserFilter";
} & Omit<Partial<PhaserOptions>, "context">) | ({
filterType: "TremoloFilter";
} & Omit<Partial<TremoloOptions>, "context">) | ({
filterType: "VibratoFilter";
} & Omit<Partial<VibratoOptions>, "context">) | ({
filterType: "CompressorFilter";
} & Omit<Partial<CompressorOptions>, "context">) | ({
filterType: "MidSideCompressorFilter";
} & Omit<Partial<MidSideCompressorOptions>, "context">) | ({
filterType: "MultibandCompressorFilter";
} & Omit<Partial<MultibandCompressorOptions>, "context">) | ({
filterType: "LimiterFilter";
} & Omit<Partial<LimiterOptions>, "context">) | ({
filterType: "GreaterThanFilter";
} & Omit<Partial<GreaterThanOptions>, "context">) | ({
filterType: "GreaterThanZeroFilter";
} & Omit<Partial<GreaterThanZeroOptions>, "context">) | ({
filterType: "DistortionFilter";
} & Omit<Partial<DistortionOptions>, "context">) | ({
filterType: "BitCrusherFilter";
} & Omit<Partial<BitCrusherOptions>, "context">) | ({
filterType: "Panner3DFilter";
} & Omit<Partial<Panner3DOptions>, "context">) | ({
filterType: "AutoPannerFilter";
} & Omit<Partial<AutoPannerOptions>, "context">) | ({
filterType: "StereoWidenerFilter";
} & Omit<Partial<StereoWidenerOptions>, "context">);
interface ExportedSound {
options: SoundOptions;
filters?: SoundFilterMemory[];
}
interface SoundPlay {
stepIndex: number;
paused: boolean;
options?: SoundPlayOptions | string;
}
interface ExportedSoundPlay extends SoundPlay {
sound: ExportedSound;
}
/**
* Interface exported sounds
*/
interface SoundGameState {
/**
* @deprecated
*/
soundsPlaying?: {
[key: string]: ExportedSoundPlay;
};
mediaInstances: {
[key: string]: {
channelAlias: string;
soundAlias: string;
stepCounter: number;
options: MediaMemory & {
filters?: SoundFilterMemory[];
delay?: number;
};
/**
* @deprecated Use options.paused instead.
*/
paused?: boolean;
};
};
}
interface SoundManagerInterface {
/** Master volume in the range [0, 1]. */
volumeAll: number;
/**
* @deprecated Global playback speed. This is not a well-supported feature and may be removed in a future release. Use individual sound speed options instead.
*/
speedAll: number;
/**
* The default channel alias used when playing a sound without specifying a
* channel. Defaults to `"general"`.
*/
defaultChannelAlias: string;
/**
* @deprecated Register sound assets directly via `PIXI.Assets` instead.
*/
add(alias: string, options: string): void;
/**
* Plays a sound.
* @param alias The media and sound (asset) alias reference.
* @param options The options.
* @returns The media instance (resolves immediately if already loaded).
*/
play(alias: string, options?: SoundPlayOptionsWithChannel): Promise<MediaInterface>;
play(mediaAlias: string, soundAlias: string, options?: SoundPlayOptionsWithChannel): Promise<MediaInterface>;
/**
* Plays a non-persistent ("transient") sound (e.g. UI / menu sounds).
* Transient playback is not tracked in save/export state.
*/
playTransient(alias: string, options?: Partial<PlayerOptions>): Promise<Player>;
/**
* Find a tracked media instance by alias.
*/
find(alias: string): MediaInterface | undefined;
/**
* Stop a tracked media instance and remove it from the manager.
*/
stop(alias: string): void;
/**
* Pause a tracked media instance.
*/
pause(alias: string): MediaInterface | undefined;
/**
* Resume a paused media instance.
*/
resume(alias: string): MediaInterface | undefined;
/** Duration in seconds of the loaded sound with the given alias. */
duration(alias: string): number;
/** Toggle mute on all sounds. Returns the new muted state. */
toggleMuteAll(): boolean;
/**
* Whether all sounds are currently muted. Note that individual channels or media instances may still be muted or unmuted; this is just the global master mute state.
*/
readonly muted: boolean;
/** Mute all sounds. */
muteAll(): this;
/** Unmute all sounds. */
unmuteAll(): this;
/** Stop all sounds. */
stopAll(): this;
/** Pause all sounds. */
pauseAll(): this;
/** Resume all sounds. */
resumeAll(): this;
/**
* Temporarily pause all currently-playing sounds (or just those in the given
* channel) without persisting the paused state. Useful for overlays / pause
* menus.
*
* Only sounds that are **actively playing** at the time of the call are paused;
* sounds that were already paused beforehand are left untouched so that they
* remain paused when {@link resumeUnsavedAll} is called later.
*
* When called without a channel argument all transient players started with
* {@link playTransient} are also stopped.
*/
pauseUnsavedAll(channel?: string): this;
/**
* Resume all sounds (or just those in the given channel) that were paused by
* the most recent call to {@link pauseUnsavedAll}. Sounds that were already
* paused before `pauseUnsavedAll` was called are **not** resumed.
*/
resumeUnsavedAll(channel?: string): this;
/**
* Stop all transient media instances started with {@link playTransient}.
*/
stopTransientAll(): this;
/** Load one or more sound assets. */
load(...alias: string[]): Promise<void>;
/** Trigger background loading of one or more sound assets. */
backgroundLoad(...alias: string[]): Promise<void>;
/** Trigger background loading of a sound bundle. */
backgroundLoadBundle(alias: string): Promise<void>;
/** Stop all sounds and clear internal state. */
clear(): void;
/**
* Add a new audio channel.
* Returns the created channel, or `undefined` if the alias already exists.
*/
addChannel(alias: string | string[], options?: ChannelOptions): AudioChannelInterface | undefined;
/**
* Find the channel for the given alias, creating it if it does not yet exist.
*/
findChannel(alias: string): AudioChannelInterface;
/** All registered audio channels. */
readonly channels: AudioChannelInterface[];
/**
* Export the current sound state, including currently playing sounds and their options, for saving or debugging purposes. This is not guaranteed to be stable across versions and may contain implementation details; it is not intended for use in general application code.
*/
export(): SoundGameState;
/**
* Restore a sound state exported by {@link export}. This will stop any currently playing sounds and replace them with the sounds specified in the exported state. This is not guaranteed to be stable across versions and may contain implementation details; it is not intended for use in general application code.
*/
restore(data: object): Promise<void>;
}
declare class CachedMap<K extends {}, V extends {}> implements Map<K, V> {
readonly cache: LRUCache<K, V>;
readonly map: Map<K, V>;
constructor(options: {
cacheSize: number;
});
get [Symbol.iterator](): () => MapIterator<[K, V]>;
get [Symbol.toStringTag](): string;
clear(): void;
delete(key: K): boolean;
get forEach(): (callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any) => void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
get size(): number;
entries(): MapIterator<[K, V]>;
keys(): MapIterator<K>;
values(): MapIterator<V>;
}
interface TickerArgs {
}
interface TickerHistory<TArgs extends TickerArgs> {
id: string;
args: TArgs;
/**
* The aliases of the canvas elements that are connected to this ticker
*/
canvasElementAliases: string[];
priority?: UPDATE_PRIORITY;
duration?: number;
paused?: boolean;
}
type PauseType = {
/**
* The type of the value
*/
type: "pause";
/**
* Duration in seconds
*/
duration: number;
};
type RepeatType = "repeat";
interface TickersStep<TArgs extends TickerArgs> {
/**
* Ticker class name
*/
ticker: string;
/**
* Duration in seconds. If is undefined, the step will end only when the animation is finished.
*/
duration?: number;
/**
* Arguments to pass to the ticker
*/
args: TArgs;
/**
* Priority of the ticker
*/
priority?: UPDATE_PRIORITY;
}
/**
* The steps of the tickers
*/
interface TickersSequence {
/**
* The step number
*/
currentStepNumber: number;
/**
* The steps of the tickers
*/
steps: (TickersStep<any> | RepeatType | PauseType)[];
}
/**
* This class is used to create a canvas element to add into a Pixi Application.
* You can use {@link canvas.add()} to add this element into the application.
* This class should be implemented and the memory method should be overridden.
* You must use the {@link canvasComponentDecorator} to register the canvas in the game.
* In Ren'Py is a displayable.
* @example
* ```typescript
* const CANVAS_EXAMPLE_ID = "CanvasExample";
*
* \@canvasComponentDecorator({
* name: CANVAS_EXAMPLE_ID,
* })
* export class CanvasExample extends Container implements CanvasBaseItem<Memory> {
* get memory(): Memory {
* return {
* pixivnId: CANVAS_EXAMPLE_ID,
* // ... other properties
* }
* }
* async setMemory(value: Memory) {
* // ... set other properties
* }
* }
* ```
*/
declare class CanvasBaseItem<T2 extends CanvasBaseItemMemory> {
constructor(..._options: any);
/**
* This method return the memory of the canvas element.
* @throws {PixiError} when the method is not overridden in the subclass.
*/
get memory(): T2;
/**
* This method set the memory of the canvas element.
* @throws {PixiError} when the method is not overridden in the subclass.
*/
setMemory(_value: T2): Promise<void> | void;
/**
* Get the id of the canvas element. This variable is used in the system to get the canvas element by id
*/
pixivnId: string;
}
/**
* Interface for the canvas base memory
*/
interface CanvasBaseItemMemory {
pixivnId: string;
/**
* The index of the container in its parent, if it has one
*/
index?: number;
/**
* The label of the parent container, if it has one
*/
parentLabel?: string;
label?: string;
zIndex?: number;
}
/**
* Interface exported canvas
*/
interface CanvasGameState {
tickers: {
[id: string]: TickerHistory<any>;
};
tickersSteps: {
[alias: string]: {
[tickerId: string]: TickersSequence;
};
};
elements: {
[alias: string]: CanvasBaseItemMemory;
};
stage: Partial<ContainerMemory>;
/**
* @deprecated
*/
elementAliasesOrder: string[];
tickersToCompleteOnStepEnd: {
tikersIds: {
id: string;
}[];
stepAlias: {
id: string;
alias: string;
}[];
};
}
interface AdditionalPositionsExtensionProps {
/**
* is a way to set the position of the element in the canvas. compared to position, align, it is a percentage used to determine the proximity from the edges of the canvas.
* For example:
* - if you set align to 0.5, the element will be in the center of the canvas.
* - if you set align to 0, the left end and a top end of the element will be in the left end and top end of the canvas.
* - if you set align to 1, the right end and a bottom end of the element will be in the right end and bottom end of the canvas.
*
* **Important:** The {@link PixiContainer.pivot} field does not affect the alignment.
*/
align?: Partial<PointData> | number;
/**
* is a way to set the position of the element in the canvas. compared to position, align, it is a percentage used to determine the proximity from the edges of the canvas.
* For example:
* - if you set align to 0.5, the element will be in the center of the canvas.
* - if you set align to 0, the left end and a top end of the element will be in the left end and top end of the canvas.
* - if you set align to 1, the right end and a bottom end of the element will be in the right end and bottom end of the canvas.
*
* **Important:** The {@link PixiContainer.pivot} field does not affect the alignment.
*/
xAlign?: number;
/**
* is a way to set the position of the element in the canvas. compared to position, align, it is a percentage used to determine the proximity from the edges of the canvas.
* For example:
* - if you set align to 0.5, the element will be in the center of the canvas.
* - if you set align to 0, the left end and a top end of the element will be in the left end and top end of the canvas.
* - if you set align to 1, the right end and a bottom end of the element will be in the right end and bottom end of the canvas.
*
* **Important:** The {@link PixiContainer.pivot} field does not affect the alignment.
*/
yAlign?: number;
/**
* is a way to set the position of the element in the canvas calculated in percentage.
* For example, if you set the {@link PixiContainer.pivot} to 0.5, and:
* - if you set percentagePosition to 0.5, the element will be in the center of the canvas.
* - If you set percentagePosition to 0, the center of the element will be in the left end and top end of the canvas.
* - If you set percentagePosition to 1, the center of the element will be in the right end and bottom end of the canvas.
*
* **Important:** The {@link PixiContainer.pivot} field does affect the percentagePosition.
*/
percentagePosition?: Partial<PointData> | number;
/**
* is a way to set the position of the element in the canvas calculated in percentage.
* For example, if you set the {@link PixiContainer.pivot} to 0.5, and:
* - if you set percentagePosition to 0.5, the element will be in the center of the canvas.
* - If you set percentagePosition to 0, the center of the element will be in the left end and top end of the canvas.
* - If you set percentagePosition to 1, the center of the element will be in the right end and bottom end of the canvas.
*
* **Important:** The {@link PixiContainer.pivot} field does affect the percentagePosition.
*/
percentageX?: number;
/**
* is a way to set the position of the element in the canvas calculated in percentage.
* For example, if you set the {@link PixiContainer.pivot} to 0.5, and:
* - if you set percentagePosition to 0.5, the element will be in the center of the canvas.
* - If you set percentagePosition to 0, the center of the element will be in the left end and top end of the canvas.
* - If you set percentagePosition to 1, the center of the element will be in the right end and bottom end of the canvas.
*
* **Important:** The {@link PixiContainer.pivot} field does affect the percentagePosition.
*/
percentageY?: number;
}
type ContainerChild = Container & CanvasBaseItem<any>;
interface ListenerExtensionMemory {
onEvents?: OnEventsHandlers;
}
interface OnEventsHandlers {
[name: string]: string;
}
/**
* Interface for the canvas container memory
*/
interface ContainerMemory<C extends ContainerChild = ContainerChild> extends ContainerOptions<C>, CanvasBaseItemMemory, ListenerExtensionMemory, AdditionalPositionsExtensionProps {
/**
* The elements contained in this container
*/
elements: CanvasBaseItemMemory[];
}
var version = "1.8.1";
/**
* @deprecated
*/
declare const Repeat: RepeatType;
/**
* Pause the tickers for a duration.
* @param duration Duration in seconds
* @returns The pause object
* @deprecated
*/
declare function Pause(duration: number): PauseType;
/**
* Is a special alias to indicate the game layer.
*/
declare const CANVAS_APP_GAME_LAYER_ALIAS = "__game_layer__";
declare const SYSTEM_RESERVED_STORAGE_KEYS: {
/**
* The key of the current dialogue memory
*/
CURRENT_DIALOGUE_MEMORY_KEY: string;
/**
* The key of step counter of the current dialogue memory
*/
LAST_DIALOGUE_ADDED_IN_STEP_MEMORY_KEY: string;
/**
* The key of the current menu options memory
*/
CURRENT_MENU_OPTIONS_MEMORY_KEY: string;
/**
* The key of the last menu options added in the step memory
*/
LAST_MENU_OPTIONS_ADDED_IN_STEP_MEMORY_KEY: string;
/**
* The key of the input memory. This value can be read by pixi-vn json importer
*/
CURRENT_INPUT_VALUE_MEMORY_KEY: string;
/**
* The key of the last input added in the step memory
*/
LAST_INPUT_ADDED_IN_STEP_MEMORY_KEY: string;
/**
* The key of the current input info
*/
CURRENT_INPUT_INFO_MEMORY_KEY: string;
/**
* The key of the characters memory
*/
CHARACTER_CATEGORY_KEY: string;
/**
* This variable is used to add the next dialog text into the current dialog memory.
* This value was added to introduce Ink Glue functionality https://github.com/inkle/ink/blob/master/Documentation/WritingWithInk.md#glue
*/
ADD_NEXT_DIALOG_TEXT_INTO_THE_CURRENT_DIALOG_FLAG_KEY: string;
/**
* The key of a list of all labels that have been opened during the progression of the steps.
*/
OPENED_LABELS_COUNTER_KEY: string;
/**
* The key of a list of all choices that have been made during the progression of the steps.
*/
ALL_CHOICES_MADE_KEY: string;
/**
* The key of the current step times counter.
* This value was added to introduce Ink Sequences, cycles and other alternatives https://github.com/inkle/ink/blob/master/Documentation/WritingWithInk.md#sequences-cycles-and-other-alternatives
*/
CURRENT_STEP_TIMES_COUNTER_KEY: string;
/**
* The key of the last dialogue step glued in the step memory
*/
LAST_STEP_GLUED: string;
};
type StorageElementPrimaryType = string | number | boolean | undefined | null | StorageElementPrimaryType[];
type StorageElementInternalType = StorageElementPrimaryType | Record<string | number | symbol, StorageElementPrimaryType> | StorageElementInternalType[];
type NonFunctionStorage = string | number | boolean | undefined | null | NonFunctionStorage[] | {
[key: string | number | symbol]: NonFunctionStorage;
};
/**
* StorageElementType are all the types that can be stored in the storage
*/
type StorageElementType = StorageElementInternalType | Record<string | number | symbol, StorageElementInternalType> | {
[key: string | number | symbol]: StorageElementType;
} | StorageObjectType[] | (StorageElementPrimaryType | StorageElementInternalType | StorageElementType)[] | {
[key: string | number | symbol]: NonFunctionStorage;
};
/**
* StorageObjectType are all the types that can be stored in the storage
*/
type StorageObjectType = Record<string | number | symbol, StorageElementType>;
interface StorageGameStateItem<T = StorageElementType> {
key: string;
value: T;
}
/**
* Interface exported storage data
*/
type StorageGameState = {
/**
* @deprecated
*/
base?: StorageGameStateItem[];
/**
* @deprecated
*/
temp?: StorageGameStateItem[];
tempDeadlines: StorageGameStateItem<number>[];
/**
* @deprecated
*/
flags?: string[];
main: StorageGameStateItem[];
};
/**
* is a string containing the name of the label.
* It is used to {@link narration.registeredLabels} to get the label class.
*/
type LabelIdType = string;
interface DialogueInterface {
/**
* The text of the dialogue.
*/
text: string | string[];
/**
* The id of the character that is speaking.
*/
character?: CharacterInterface | string;
}
type StoredDialogue = Omit<DialogueInterface, "character"> & {
character: string | undefined;
};
interface HistoryStep {
/**
* The difference between the previous step and the current step.
*/
diff?: Difference[];
/**
* The label id of the current step.
*/
currentLabel?: LabelIdType;
/**
* The sha1 of the step function.
*/
stepSha1: string;
/**
* Equivalent to the narration.stepCounter
*/
index: number;
/**
* The data of the step of the label.
*/
labelStepIndex: number | null;
/**
* Dialogue to be shown in the game
*/
dialogue?: StoredDialogue;
/**
* List of choices asked of the player
*/
choices?: StoredChoiceInterface[];
/**
* List of choices already made by the player
*/
alreadyMadeChoices?: number[];
/**
* The input value of the player
*/
inputValue?: StorageElementType$1;
/**
* The choice made by the player
*/
choiceIndexMade?: number;
/**
* If true, the current dialogue will be glued to the previous one.
*/
isGlued?: boolean;
/**
* Opened Labels in the current step.
*/
openedLabels?: OpenedLabel$1[];
}
interface OpenedLabel {
label: LabelIdType;
currentStepIndex: number;
}
/**
* Interface exported step data
*/
interface HistoryGameState {
stepsHistory: HistoryStep[];
originalStepData: GameStepState | undefined;
}
interface GameState {
pixivn_version: string;
stepData: NarrationGameState;
storageData: StorageGameState;
canvasData: CanvasGameState;
soundData: SoundGameState;
historyData: HistoryGameState;
path: string;
}
/**
* It is a interface that contains the information of a step.
*/
interface GameStepStateData {
/**
* The browser path that occurred during the progression of the steps.
*/
path: string;
/**
* The storage that occurred during the progression of the steps.
*/
storage: StorageGameState;
/**
* The index of the label that occurred during the progression of the steps.
*/
labelIndex: number;
/**
* The canvas that occurred during the progression of the steps.
*/
canvas: CanvasGameState;
/**
* The opened labels that occurred during the progression of the steps.
*/
openedLabels: OpenedLabel[];
/**
* The sound data that occurred during the progression of the steps.
*/
sound: SoundGameState;
}
/**
* This function is used to create a deep copy of the element
* @param element The element to be copied
* @returns The copied element
* @throws {PixiError} when the element is not JSON serializable (e.g. contains functions or class instances).
*/
declare function createExportableElement<T>(element: T): T;
declare namespace Game {
/**
* Initialize the Game and PixiJS Application and the interface div.
* This method should be called before any other method.
* @param element The html element where I will put the canvas. Example: document.body
* @param width The width of the canvas
* @param height The height of the canvas
* @param options The options of PixiJS Application and other options
* @param devtoolsOptions The options of the devtools. You can read more about it in the [PixiJS Devtools documentation](https://pixijs.io/devtools/docs/plugin/)
* @example
* ```typescript
* const body = document.body
* if (!body) {
* throw new Error('body element not found')
* }
* await Game.initialize(body, {
* navigate: (path) => {
* // navigate to the path
* },
* width: 1920,
* height: 1080,
* backgroundColor: "#303030"
* resizeMode: "contain"
* })
* ```
*/
function init(element: HTMLElement, options: Partial<ApplicationOptions> & {
/**
* The id of the canvas element.
* @default "pixi-vn-canvas"
*/
id?: string;
/**
* The route navigate function.
* You can set this function after the initialization using {@link GameUnifier.navigate}
* @param path The path to navigate to.
* @returns
*/
navigate?: (path: string) => void | Promise<void>;
/**
* The resize mode of the canvas.
* @default "contain"
*/
resizeMode?: "contain" | "none";
}, devtoolsOptions?: Devtools): Promise<void>;
/**
* Initialize only the GameUnifier, and not the PixiJS Application and the interface div.
* This method can be used if you want to use only the GameUnifier features, such as save/load game,
* without initializing the canvas.
*/
function init(): Promise<void>;
/**
* Clear all game data. This function is used to reset the game.
*/
function clear(): void;
/**
* Get all the game data. It can be used to save the game.
* @returns The game data
*/
function exportGameState(): GameState;
/**
* Load the save data
* @param data The save data
*/
function restoreGameState(data: GameState): Promise<void>;
/**
* @deprecated Use `restoreGameState(data)` (without the `navigate` argument) and configure navigation via `Game.init({ navigate })` or `Game.onNavigate(...)`.
* @param data The save data
* @param navigate Navigation function to use for this restore call.
*/
function restoreGameState(data: GameState, navigate: (path: string) => void | Promise<void>): Promise<void>;
/**
* Start the game with a label. This function will clear all the game data and start the narration from the specified label.
* @param label The label to start the game with. It can be a string or a LabelAbstract instance. If it is a string, it will be used as the id of the label to start. If it is a LabelAbstract instance, it will be used directly. If the label is not found, an error will be thrown.
* @param props The properties to pass to the label. It will be passed to the {@link StepLabelType} of the label when it is executed.
* @returns The result of the label execution. It can be a {@link StepLabelResultType} or a Promise that resolves to a {@link StepLabelResultType}.
*/
function start<T extends {} = {}>(label: narrationUtils.LabelAbstract<any, T> | string, props: narrationUtils.StepLabelPropsType<T>): Promise<narrationUtils.StepLabelResultType>;
/**
* Convert a JSON string to a save data
* @param json The JSON string
* @returns The save data
*/
function jsonToGameState(json: string): GameState;
/**
* Function to be executed at the end of the game. It should be set in the game initialization.
* @example
* ```typescript
* Game.onEnd(async (props) => {
* props.navigate("/end")
* })
* ```
*/
function onEnd(value: narrationUtils.StepLabelType): void;
/**
* @deprecated Game.onError is deprecated. Use Game.addOnError / Game.removeOnError to register multiple handlers.
*/
function onError(handler: (type: "step", error: any, props: narrationUtils.StepLabelPropsType) => void | Promise<void>): () => void;
/**
* Register an error handler. Multiple handlers can be registered; they
* will be executed in registration order.
* @example
* ```typescript
* // Register a synchronous error handler
* Game.addOnError((error, props) => {
* props.notify("An error occurred")
* // send a notification to GlitchTip, Sentry, etc...
* })
*
* // Register an asynchronous error handler
* Game.addOnError(async (error, props) => {
* await logErrorToServer(error)
* props.notify("An error occurred")
* })
*
* // Register an error handler with step restoration/rollback
* Game.addOnError(async (error, props) => {
* // Restore the game state to the previous step
* await stepHistory.back(props)
* props.notify("An error occurred, returning to previous step")
* })
* ```
*/
function addOnError(value: OnErrorHandler): () => void;
/**
* Remove a previously registered error handler.
*/
function removeOnError(handler: OnErrorHandler): void;
/**
* Is a function that will be executed before any step is executed.
* @param stepId Step id
* @param label Label
* @returns
*/
function onStepStart(value: (stepId: number, label: narrationUtils.LabelAbstract<any>) => void | Promise<void>): void;
/**
* Is a function that will be executed in {@link Game.onStepStart} if the id of the step is 0
* and when the user laods a save file.
* When you load a save file, will be executed all onLoadingLabel functions of the {@link narrationUtils.narration}.openedLabels.
* It is useful for example to make sure all images used have been cached
* @param stepId Step id
* @param label Label
* @returns
* @example
* ```typescript
* Game.onLoadingLabel(async (stepId, label) => {
* await Assets.load('path/to/image1.png')
* await Assets.load('path/to/image2.png')
* })
* ```
*/
function onLoadingLabel(value: (stepId: number, label: narrationUtils.LabelAbstract<any>) => void | Promise<void>): void;
/**
* Is a function that will be executed when the step ends.
* @param stepId Step id
* @param label Label
* @returns
*/
function onStepEnd(value: (stepId: number, label: narrationUtils.LabelAbstract<any>) => void | Promise<void>): void;
/**
* Function to be executed when navigation is requested.
* @example
* ```typescript
* Game.onNavigate(async (path) => {
* // custom navigation logic
* window.history.pushState({}, "title", path)
* })
* ```
*/
function onNavigate(value: (path: string) => void | Promise<void>): void;
/**
* Register a handler to run immediately before a narration "continue" operation.
* Handlers are executed in registration order and may be async. Use
* `{@link addOnPreContinue}` / `{@link removeOnPreContinue}` to manage them programmatically.
*/
function addOnPreContinue(handler: () => Promise<void> | void): void;
function removeOnPreContinue(handler: () => Promise<void> | void): void;
}
declare const _default: {
canvas: canvasUtils.CanvasManagerInterface;
narration: narrationUtils.NarrationManagerInterface;
sound: SoundManagerInterface;
storage: storageUtils.StorageManagerInterface;
history: historyUtils.HistoryManagerInterface;
Game: typeof Game;
GameUnifier: typeof GameUnifier;
createExportableElement: typeof createExportableElement;
characterUtils: typeof characterUtils;
canvasUtils: typeof canvasUtils;
narrationUtils: typeof narrationUtils;
soundUtils: typeof soundUtils;
CANVAS_APP_GAME_LAYER_ALIAS: string;
Pause: typeof Pause;
Repeat: "repeat";
PIXIVN_VERSION: string;
};
export { CANVAS_APP_GAME_LAYER_ALIAS, CachedMap, Game, type GameState, type GameStepStateData, version as PIXIVN_VERSION, Pause, Repeat, SYSTEM_RESERVED_STORAGE_KEYS, createExportableElement, _default as default };