Jazz2::LevelHandler class

Level handler of a local game session.

Concrete state handler that runs a single-player or local-multiplayer level: it loads the level descriptor, owns the tile map, event map and collision broad-phase, spawns and updates actors and players, drives rendering, lighting and audio, and serializes resumable state.

Base classes

class ILevelHandler
Base interface of a level handler.
class IStateHandler
Base interface of a state handler, only one handler runs at a time.
class IResumable
Base interface of a resumable object.
class ITileMapOwner
Interface used to notify tile map owner of various events.

Derived classes

class EditorLevelHandler
Shows a level being edited.
class PlayTestLevelHandler
Plays a level being edited.
class MpLevelHandler
Level handler of a multiplayer game session (online or local splitscreen).

Constructors, destructors, conversion operators

LevelHandler(IRootController* root)
Creates a new instance.
~LevelHandler() override

Public functions

auto Initialize(const LevelInitialization& levelInit) -> bool override
Initializes the level handler from LevelInitialization.
auto Initialize(Stream& src, std::uint16_t version) -> bool override
Initializes the level handler from resumable state.
auto EventSpawner() -> Events::EventSpawner* override
Returns event spawner for the level.
auto EventMap() -> Events::EventMap* override
Returns event map for the level.
auto TileMap() -> Tiles::TileMap* override
Returns tile map for the level.
auto GetDifficulty() const -> GameDifficulty override
Return current difficulty.
auto IsLocalSession() const -> bool override
Returns true if the level handler is on a local session.
auto IsServer() const -> bool override
Returns true if the level handler is on a server or a local session.
auto IsPausable() const -> bool override
Returns true if the level handler is pausable.
auto IsReforged() const -> bool override
Returns true if Reforged Gameplay is enabled.
auto IsLedgeClimbEnabled(const Actors::Player* player) const -> bool override
Returns true if a player may climb ledges, see PreferencesCache::EnableLedgeClimb.
auto CanActivateSugarRush() const -> bool override
Returns true if sugar rush can be activated.
auto CanEventDisappear(EventType eventType) const -> bool override
Returns true if event can be safely despawned.
auto CanFreezeActor(Actors::ActorBase* actor, Actors::ActorBase* shooter) -> bool override
Returns true if a shot of shooter (may be nullptr) can freeze actor.
auto CanPlayersCollide() const -> bool override
Returns true if players can collide with each other.
auto GetLevelBounds() const -> Recti override
Returns level bounds including camera limits.
auto GetElapsedFrames() const -> float override
Returns number of elapsed frames.
auto GetGravity() const -> float override
Returns current gravity force.
auto GetWaterLevel() const -> float override
Returns current water level.
auto GetPlayerWaterLevel() const -> float override
Returns the water level the players swim by.
auto GetHurtInvulnerableTime() const -> float override
Returns default invulnerable time when a player is hurt.
auto GetActiveBossHealth(std::int32_t& health, std::int32_t& maxHealth) const -> bool override
Returns true if a boss health bar should be shown, together with the boss' health.
auto GetActors() const -> ArrayView<const std::shared_ptr<Actors::ActorBase>> override
Returns list of actors (objects).
auto GetPlayers() const -> ArrayView<Actors::Player* const> override
Returns list of players.
auto FindPlayerToStandOn(Actors::Player* player, float timeMult) -> Actors::ActorBase* override
Returns the player actor player is standing/landing on (one-way platform check), or nullptr.
auto GetPlayerFurColor(const Actors::Player* player, std::uint32_t furColor) const -> std::uint32_t override
Returns the fur color a player should actually be recolored with.
auto IsPlayerColorForced(const Actors::Player* player) const -> bool override
Returns whether the level handler forces a fur color on the player, overriding local color preferences.
auto GetCharacterProfile(PlayerType type) const -> CharacterProfile override
Returns the abilities of a character.
auto WarpsTransmuteCoins() const -> bool override
Returns true if a bonus warp turns the coins lying in the level into gems.
auto AreCoinsTransmuted() const -> bool override
Returns true if the coins lying in the level have turned into gems.
void TransmuteCoins() override
Turns the coins lying in the level into gems, as a bonus warp that costs coins does.
auto GetWaterInteraction() const -> WaterInteraction override
Returns how players move under water.
auto GetLevelName() const -> StringView
Returns the internal name (path) of the current level.
auto GetLevelDisplayName() const -> StringView
Returns the display (title) name of the current level.
void SetLevelDisplayName(StringView value)
Overrides the display (title) name of the current level.
auto GetDefaultAmbientLight() const -> float override
Returns default ambient light intensity.
auto GetAmbientLight(Actors::Player* player) const -> float override
Returns current ambient light intensity.
void SetAmbientLight(Actors::Player* player, float value) override
Sets current ambient light intensity.
auto GetViewSize() const -> Vector2i override
Returns viewport size of the handler.
void OnBeginFrame() override
Called at the beginning of each frame.
void OnEndFrame() override
Called at the end of each frame.
void OnReplacing() override
Called when another handler is about to be made in its place, before it loads what it needs.
void OnInitializeViewport(std::int32_t width, std::int32_t height) override
Called when the viewport needs to be initialized (e.g., when the resolution is changed).
auto OnConsoleCommand(StringView line) -> bool virtual
Called when a console command is entered.
void OnKeyPressed(const KeyboardEvent& event) override
Called when a key is pressed.
void OnKeyReleased(const KeyboardEvent& event) override
Called when a key is released.
void OnTextInput(const TextInputEvent& event) override
Called when a text input is detected.
void OnTouchEvent(const TouchEvent& event) override
Called when a touch event is triggered.
void AddActor(std::shared_ptr<Actors::ActorBase> actor) override
Adds an actor (object) to the level.
auto PlaySfx(Actors::ActorBase* self, StringView identifier, AudioBuffer* buffer, const Vector3f& pos, bool sourceRelative, float gain, float pitch, SfxFlags flags) -> std::shared_ptr<AudioBufferPlayer> override
Plays a sound effect for a given actor (object).
void StopSfx(Actors::ActorBase* self, StringView identifier, AudioBufferPlayer* player) override
Stops a sound effect of a given actor (object) started with SfxFlags::Exclusive.
auto PlayCommonSfx(StringView identifier, const Vector3f& pos, float gain = 1.0f, float pitch = 1.0f) -> std::shared_ptr<AudioBufferPlayer> override
Plays a common sound effect.
void SetSfxEcho(float strength)
Sets how strongly the sounds the level plays echo, from 0 (no echo) to 1.
auto GetSfxEcho() const -> float
Returns how strongly the sounds the level plays echo, see SetSfxEcho().
void WarpCameraToTarget(Actors::ActorBase* actor, bool fast = false) override
Warps a camera to its assigned target.
auto IsPositionEmpty(Actors::ActorBase* self, const AABBf& aabb, Tiles::TileCollisionParams& params, Actors::ActorBase** collider) -> bool override
Returns true if a specified AABB is empty.
void FindCollisionActorsByAABB(const Actors::ActorBase* self, const AABBf& aabb, Function<bool(Actors::ActorBase*)>&& callback) override
Calls the callback function for all colliding objects with specified AABB.
void FindCollisionActorsByRadius(float x, float y, float radius, Function<bool(Actors::ActorBase*)>&& callback) override
Calls the callback function for all colliding objects with specified circle.
void GetCollidingPlayers(const AABBf& aabb, Function<bool(Actors::ActorBase*)>&& callback) override
Calls the callback function for all colliding players with specified AABB.
void BroadcastTriggeredEvent(Actors::ActorBase* initiator, EventType eventType, std::uint8_t* eventParams) override
Broadcasts specified event to all other actors.
void BeginLevelChange(Actors::ActorBase* initiator, ExitType exitType, StringView nextLevel = {}) override
Starts transition to change current level.
auto CanTakeLevelExit(ExitType exitType, StringView nextLevel) const -> bool override
Returns true if a level exit of the specified type leading to the specified level can be taken.
void SendPacket(const Actors::ActorBase* self, ArrayView<const std::uint8_t> data) override
Sends a packet to the other side of a non-local session.
void HandleBossActivated(Actors::Bosses::BossBase* boss, Actors::ActorBase* initiator = nullptr) override
Called when a boss is activated.
void HandleLevelChange(LevelInitialization&& levelInit) override
Called when the level is changed.
void HandleGameOver(Actors::Player* player) override
Called when the game is over.
auto HandlePlayerDied(Actors::Player* player) -> bool override
Called when a player dies.
void HandlePlayerWarped(Actors::Player* player, Vector2f prevPos, WarpFlags flags) override
Called when a player warps.
void HandlePlayerPushed(Actors::Player* player) override
Called after a server-side force/knockback is applied to a player.
void HandlePlayerCoins(Actors::Player* player, std::int32_t prevCount, std::int32_t newCount) override
Called when a player collects or losts coins.
void HandlePlayerGems(Actors::Player* player, std::uint8_t gemType, std::int32_t prevCount, std::int32_t newCount) override
Called when a player collects or losts gems.
auto HandlePlayerFire(Actors::Player* player, WeaponType weaponType) -> bool override
Called when a player fires a weapon, returns true if its shots were fired by something else (a level script).
auto GetWeaponDefinition(WeaponType weaponType) const -> const WeaponDefinition& override
Returns what the level makes of a weapon (see Formats::WeaponsChunk).
auto GetWritableWeaponDefinition(WeaponType weaponType) -> WeaponDefinition*
Returns what the level makes of a weapon, which a script may change, nullptr for no weapon.
auto GetWeapons() const -> const WeaponsDescription& override
Returns the weapons of the level with the images they use.
void SetCheckpoint(Actors::Player* player, Vector2f pos) override
Sets checkpoint for a given player.
void RollbackToCheckpoint(Actors::Player* player) override
Rolls back to the last checkpoint for a given player.
void HandleActivateSugarRush(Actors::Player* player) override
Called when a player activates sugar rush.
void HandleCreateParticleDebrisOnPerish(const Actors::ActorBase* self, Actors::ParticleDebrisEffect effect, Vector2f speed) override
Called when an object creates a particle debris on perish.
void HandleCreateSpriteDebris(const Actors::ActorBase* self, AnimState state, std::int32_t count, float elasticity) override
Called when an object creates a sprite debris.
void ShowLevelText(StringView text, Actors::ActorBase* initiator = nullptr) override
Shows a text notification.
auto GetLevelText(std::uint32_t textId, std::int32_t index = -1, std::uint32_t delimiter = 0) -> StringView override
Returns a level text.
void OverrideLevelText(std::uint32_t textId, StringView value) override
Override specified level text.
auto GetScriptText(std::uint32_t textId) -> StringView
Returns a level text as the original game had it, for scripts, the level text if the level has none (see Formats::ScriptDataChunk).
void OverrideScriptText(std::uint32_t textId, StringView value)
Sets a level text as the original game has it, which scripts read back, the text shown has to be set too.
auto GetCameraPos(Actors::Player* player) const -> Vector2f override
Returns camera position of a given player.
void LimitCameraView(Actors::Player* player, Vector2f playerPos, std::int32_t left, std::int32_t width) override
Limits camera viewport for a given player.
void OverrideCameraView(Actors::Player* player, CameraOverride modeX, float x, CameraOverride modeY, float y, bool centered = false, bool instant = true) override
Fixes the camera of a given player at a position of the level, or lets it follow the player again, on each axis.
void ShakeCameraView(Actors::Player* player, float duration) override
Shake camera for a given player.
void ShakeCameraViewNear(Vector2f pos, float duration) override
Shake camera for all players near a given position.
auto GetTrigger(std::uint8_t triggerId) -> bool override
Returns state of a given trigger in the tile map.
void SetTrigger(std::uint8_t triggerId, bool newState) override
Sets state of a given trigger in the tile map.
void SetWeather(WeatherType type, std::uint8_t intensity) override
Sets current level weather.
auto BeginPlayMusic(StringView path, bool setDefault = false, bool forceReload = false) -> bool override
Plays specified music.
auto PlayerActionPressed(Actors::Player* player, PlayerAction action, bool includeGamepads = true) -> bool override
Returns true if player action is pressed.
auto PlayerActionPressed(Actors::Player* player, PlayerAction action, bool includeGamepads, bool& isGamepad) -> bool override
auto PlayerActionHit(Actors::Player* player, PlayerAction action, bool includeGamepads = true) -> bool override
Returns true if player action is hit (newly pressed).
auto PlayerActionHit(Actors::Player* player, PlayerAction action, bool includeGamepads, bool& isGamepad) -> bool override
auto PlayerHorizontalMovement(Actors::Player* player) -> float override
Returns value of desired horizontal player movement.
auto PlayerVerticalMovement(Actors::Player* player) -> float override
Returns value of desired vertical player movement.
void PlayerExecuteRumble(Actors::Player* player, StringView rumbleEffect) override
Executes a rumble effect.
auto SerializeResumableToStream(Stream& dest) -> bool override
Serializes object state to a stream.
auto GetLevelTimeMult() const -> float
Returns how far the time of the level goes in this frame, in frames at 60 FPS.
void ResetPressedKeys(bool fromKeyboard)
Takes which keys are held from the keyboard again, or lets all of them go.
void SuspendRendering()
Takes the level off the screen, until its viewports are initialized again.
auto IsEditorPlayTest() const -> bool virtual
Returns true if the level is played from the level editor, it returns there when it's left.
void ExitEditor() virtual
Leaves the level editor the level is played from.
auto GetPlayTestDebug() const -> Editor::PlayTestDebug*
Returns the debug tools of a level played from the level editor, or nullptr in a game.
auto IsSandbox() const -> bool virtual
Returns true if the level is loaded only to run its script, by the level editor.
auto GetCameraView(Actors::Player* player) const -> Rectf
Returns the part of the level the view of a given player shows, from its top left corner, the whole view without one.
void OnAdvanceDestructibleTileAnimation(std::int32_t tx, std::int32_t ty, std::int32_t amount) override
Called when a destructible tile animation is advanced.
void OnTileFrozen(std::int32_t x, std::int32_t y) override
Called when a tile is frozen.

Protected types

struct PlayerInput
Describes current input state of a player.
struct ViewportSetup
How the viewports of the level are rendered, see GetViewportSetup().

Protected static functions

static auto IsReturnLevel(StringView levelName) -> bool
Returns true if the specified level is a special level.
static auto IsSecretExit(ExitType exitType) -> bool
Returns true if the exit type is a secret exit.

Protected functions

void InvokeAsync(Function<void()>&& callback)
Invokes the specified callback asynchronously, usually at the end of current frame.
auto GetViewportSetup(std::int32_t width, std::int32_t height) -> ViewportSetup virtual
Returns how the viewports of the level are rendered for a given size of the window.
auto LoadLevel(LevelDescriptor& descriptor) -> bool virtual
Loads the level of the handler into a level descriptor.
auto GetLevelLoadOptions() const -> LevelLoadOptions virtual
Returns the options the level is loaded with, which decide what events are present.
void AttachComponents(LevelDescriptor&& descriptor) virtual
Attaches all required level components to the handler.
void LoadLevelScripts(StringView fullPath) virtual
Loads the scripts of the level, if there are any and they are allowed.
void LoadLevelScripts(StringView fullPath, StringView scriptText)
Loads the scripts of the level, with scriptText read in place of the .j2as file if it's not empty.
void ApplyLevelSettings(const Formats::LevelSettingsChunk::Settings& settings)
Applies the settings of the level that its properties have no room for, the water and the rules.
void SetWaterLayer(std::int32_t layerIndex)
Sets the layer the water is drawn in front of.
auto GetWaterDepth() const -> std::uint16_t
Returns the depth the water is drawn at in the middle of the scene.
auto MayDrawWaterInScene() const -> bool
Returns true if the water may be drawn in the middle of the scene, which needs passes of its own.
auto CreateHUD() -> std::unique_ptr<UI::HUD> virtual
Creates HUD.
void SpawnPlayers(const LevelInitialization& levelInit) virtual
Spawns all players.
auto FindClearSpawnPosition(Vector2f spawnPosition, Vector2f offset) -> Vector2f
Returns where a co-op player can actually be placed, given the offset that would separate them.
auto CreateResumablePlayer(std::int32_t index) -> std::shared_ptr<Actors::Player> virtual
Creates a player instance while restoring a resumable state from a stream (one per serialized player).
auto IsCheatingAllowed(Actors::Player* player) -> bool virtual
Returns true if cheats are enabled for the specified player, nullptr refers to the local console.
void OnInitialized() virtual
Called after the level is loaded and all players were spawned.
void BeforeActorDestroyed(Actors::ActorBase* actor) virtual
Called before an actor (object) is destroyed.
void ProcessEvents(float timeMult) virtual
Processes events.
void ProcessQueuedNextLevel() virtual
Processes transition to the next level if queued.
void PrepareNextLevelInitialization(LevelInitialization& levelInit) virtual
Prepares LevelInitialization for transition to the next level.
auto CanUseLevelStateSnapshots() const -> bool virtual
Returns true if actors can be stored in level state snapshots.
auto ResolveNextLevelName(ExitType exitType, StringView nextLevel) const -> String
Returns full name of the level that follows after the level is exited with the specified exit type.
auto ReturnsFromSecretLevel(ExitType exitType) const -> bool
Returns true if the current level was entered through a secret exit and the exit type returns back from it.
auto GetPlayerViewportBounds(std::int32_t w, std::int32_t h, std::int32_t index) -> Recti
Returns player viewport bounds.
void ProcessWeather(float timeMult)
Processes weather.
void ResolveCollisions(float timeMult)
Resolves collisions.
void AssignViewport(Actors::Player* player)
Assigns viewport.
void UnassignViewport(Actors::Player* player)
Unassigns viewport.
void CommitViewports()
Commits changes in assigned viewports.
auto GetActiveOverlayPass() -> Rendering::UpscaleRenderPassWithClipping&
Returns the upscale pass that hosts the HUD and in-game menu (the native-resolution overlay pass when the scene is supersampled, otherwise the scene pass).
auto GetHudParentNode() -> SceneNode*
Returns the scene node that the HUD and other overlay UI should attach to.
void InitializeCamera(Rendering::PlayerViewport& viewport)
Initializes camera for specified viewport.
void UpdatePressedActions()
Updates pressed actions.
void UpdateRichPresence()
Updates rich presence.
void InitializeRumbleEffects()
Initializes common rumble effects.
auto RegisterRumbleEffect(StringView name) -> RumbleDescription*
Registers a rumple effect.
void PauseGame() virtual
Pauses the game.
void ResumeGame() virtual
Resumes the paused game.
void PauseAllSfx()
Pauses all sound effects that are playing, see ResumeAllSfx().
void ResumeAllSfx()
Plays all paused sound effects again.
void ShowConsole() virtual
Shows the in-game console.
void HideConsole() virtual
Hides the in-game console.
void ReleaseScripts()
Releases the level script and the actors while the rest of the level is still there.
auto ApplyCheat(StringView line, ArrayView<Actors::Player* const> targets) -> bool
Applies the cheat matching the specified command to the specified players.

Constants

static std::int32_t DefaultWidth constexpr
Default width of viewport (see Rendering::UpscaleRenderPass::DefaultViewWidth).
static std::int32_t DefaultHeight constexpr
Default height of viewport.
static std::int32_t ActivateTileRange constexpr
Range of tile activation, in tiles either side of a player.
static Vector3f DefaultWaterColor constexpr
Color of the water unless a script gives it its own, see Rendering::CombineRenderer.
static float WaterLevelSpeed constexpr
Speed the water level moves to a new level at, in px per frame (1 px per tick of the original).

Function documentation

Jazz2::LevelHandler::LevelHandler(IRootController* root)

Creates a new instance.

Parameters
root Root controller that owns the handler

float Jazz2::LevelHandler::GetPlayerWaterLevel() const override

Returns the water level the players swim by.

The same as GetWaterLevel(), unless a level script changes the water in its ticks - the water as the script left it for the players then, before its objects (see LevelHandler::GetPlayerWaterLevel()).

bool Jazz2::LevelHandler::GetActiveBossHealth(std::int32_t& health, std::int32_t& maxHealth) const override

Returns true if a boss health bar should be shown, together with the boss' health.

Online clients never own the boss actor (boss activation is server-side only), so multiplayer reports the health synchronized from the server instead of reading the local boss actor.

Actors::ActorBase* Jazz2::LevelHandler::FindPlayerToStandOn(Actors::Player* player, float timeMult) override

Returns the player actor player is standing/landing on (one-way platform check), or nullptr.

Shared by local splitscreen co-op and online sessions to let players stand on top of each other. Local sessions search the player list; online sessions also search remote players on clients.

std::uint32_t Jazz2::LevelHandler::GetPlayerFurColor(const Actors::Player* player, std::uint32_t furColor) const override

Returns the fur color a player should actually be recolored with.

Lets the level handler override a player's configured color; multiplayer team modes use this to force the team color.

bool Jazz2::LevelHandler::IsPlayerColorForced(const Actors::Player* player) const override

Returns whether the level handler forces a fur color on the player, overriding local color preferences.

Multiplayer team modes force the team color on every player so teams stay distinguishable; such a forced color applies regardless of the cosmetic "Apply Colors" preference.

void Jazz2::LevelHandler::OnReplacing() override

Called when another handler is about to be made in its place, before it loads what it needs.

The handler can still be alive while the next one loads, and the resources are shared, so what it changed of them goes back now. It isn't updated or drawn any more afterwards.

void Jazz2::LevelHandler::StopSfx(Actors::ActorBase* self, StringView identifier, AudioBufferPlayer* player) override

Stops a sound effect of a given actor (object) started with SfxFlags::Exclusive.

Stops player, the instance playing here (may be nullptr), and the instance the remote peers play for the same actor and identifier, which the actor has no handle to.

void Jazz2::LevelHandler::SetSfxEcho(float strength)

Sets how strongly the sounds the level plays echo, from 0 (no echo) to 1.

Each sound that isn't looping is repeated twice, a fifth of a second apart and quieter every time.

bool Jazz2::LevelHandler::CanTakeLevelExit(ExitType exitType, StringView nextLevel) const override

Returns true if a level exit of the specified type leading to the specified level can be taken.

A special level returns back to the level it was entered from once it's completed, and it cannot be entered from there again (see LevelInitialization::ReturnLevelState).

void Jazz2::LevelHandler::HandlePlayerPushed(Actors::Player* player) override

Called after a server-side force/knockback is applied to a player.

Allows the change to be synchronized to the owning client in a non-local session.

void Jazz2::LevelHandler::OverrideCameraView(Actors::Player* player, CameraOverride modeX, float x, CameraOverride modeY, float y, bool centered = false, bool instant = true) override

Fixes the camera of a given player at a position of the level, or lets it follow the player again, on each axis.

The position is where the top left corner of the view is, or its center if centered is true. Unless instant is true, the camera takes half a second to get there, as jjPLAYER::cameraFreeze() of JJ2+.

bool Jazz2::LevelHandler::PlayerActionPressed(Actors::Player* player, PlayerAction action, bool includeGamepads, bool& isGamepad) override

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

bool Jazz2::LevelHandler::PlayerActionHit(Actors::Player* player, PlayerAction action, bool includeGamepads, bool& isGamepad) override

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

float Jazz2::LevelHandler::GetLevelTimeMult() const

Returns how far the time of the level goes in this frame, in frames at 60 FPS.

The time of the application, unless a play-test of the level editor slows the level down or stops it, see GetPlayTestDebug().

void Jazz2::LevelHandler::ResetPressedKeys(bool fromKeyboard)

Takes which keys are held from the keyboard again, or lets all of them go.

For a level that didn't get the keyboard for a while, as one played from the level editor, the keys pressed and released meanwhile went elsewhere. With fromKeyboard the keys held now are held in the level too, otherwise none is.

bool Jazz2::LevelHandler::IsSandbox() const virtual

Returns true if the level is loaded only to run its script, by the level editor.

Nothing of it is shown or heard, and its script writes no files.

static bool Jazz2::LevelHandler::IsReturnLevel(StringView levelName) protected

Returns true if the specified level is a special level.

A special level specifies itself as its next level, it has no successor of its own and returns back to the level it was entered from once completed (e.g., "Gargoyle's Lair" from "Medieval Kineval").

static bool Jazz2::LevelHandler::IsSecretExit(ExitType exitType) protected

Returns true if the exit type is a secret exit.

The level a secret exit leads to always returns back to the level it was entered from, whatever its next level is, see ReturnsFromSecretLevel().

ViewportSetup Jazz2::LevelHandler::GetViewportSetup(std::int32_t width, std::int32_t height) virtual protected

Returns how the viewports of the level are rendered for a given size of the window.

The game renders the scene at a smaller size, see DefaultWidth and DefaultHeight, and upscales it. The level editor renders it at the size of the window.

bool Jazz2::LevelHandler::LoadLevel(LevelDescriptor& descriptor) virtual protected

Loads the level of the handler into a level descriptor.

The level is looked up by its name, and in the unknown episode if it isn't found there.

void Jazz2::LevelHandler::LoadLevelScripts(StringView fullPath) virtual protected

Loads the scripts of the level, if there are any and they are allowed.

The script is a .j2as file next to the level file. The level editor doesn't run scripts while a level is being edited.

void Jazz2::LevelHandler::SetWaterLayer(std::int32_t layerIndex) protected

Sets the layer the water is drawn in front of.

Parameters
layerIndex Index of the layer, Formats::LevelSettingsChunk::WaterInFront or Formats::LevelSettingsChunk::WaterHidden

std::uint16_t Jazz2::LevelHandler::GetWaterDepth() const protected

Returns the depth the water is drawn at in the middle of the scene.

The depth of the nearest visible layer in front of the layer the water is in front of, everything below it is under the water and the rest is drawn over it. 0 if the water is drawn in front of everything by the combine pass, or not at all.

Vector2f Jazz2::LevelHandler::FindClearSpawnPosition(Vector2f spawnPosition, Vector2f offset) protected

Returns where a co-op player can actually be placed, given the offset that would separate them.

Parameters
spawnPosition Where the level says the player starts
offset What to add to separate this player from the others; zero returns the start
Returns The first of the offset, half the offset and no offset that the player fits in

The offset exists only so players do not start standing inside one another, and applying it blind puts the second one inside the tileset wherever the level starts in a tight space — reported on rescue/colon2, where the start is barely taller than the player and the lift buried them from the first frame. Tried at full strength, then at half, then not at all.

Shared with Multiplayer::MpLevelHandler, which spawns local splitscreen players through its own override and had the same defect with its own copy of the arithmetic — an unchecked 30 px lift. That is the reason this is a function rather than a few lines at each site: the two paths look alike, are reached by different routes (the menu's co-op goes through the multiplayer handler, a /level start does not), and a fix applied to one of them silently leaves the other broken.

bool Jazz2::LevelHandler::CanUseLevelStateSnapshots() const virtual protected

Returns true if actors can be stored in level state snapshots.

Snapshots make it possible to roll back all actors to the last checkpoint, to resume them from a saved state and to return from a special level to the exact state the previous level was left in.

void Jazz2::LevelHandler::ReleaseScripts() protected

Releases the level script and the actors while the rest of the level is still there.

Destructors of script objects may call back into the level (JJ2+ behaviors write to the console). Called by the destructor, and earlier by a derived handler whose overrides they should still see.

bool Jazz2::LevelHandler::ApplyCheat(StringView line, ArrayView<Actors::Player* const> targets) protected

Applies the cheat matching the specified command to the specified players.

Parameters
line Command to look up
targets Players the cheat is applied to, pass an empty view to only check whether line is a cheat
Returns true if line is a known cheat command

The command is not validated against IsCheatingAllowed, the caller is responsible for it.

Variable documentation

static std::int32_t Jazz2::LevelHandler::ActivateTileRange constexpr

Range of tile activation, in tiles either side of a player.

Everything inside this square around a player is spawned from the event map, and everything whose origin tile leaves it by a further 4 tiles is destroyed again. Nothing culls an actor's update, only its drawing, so every actor in here - enemies, platforms, and the gems, ammo and crates that are just as much actors - runs a full movement and tile-collision step every frame. The range is therefore a direct lever on how much the level costs to simulate, quadratically: 26 is a 52x52 tile box, 18 is 36x36, or 48% of the area.

The consoles below take the smaller value because their screens are small enough that it is still entirely off-screen. What has to stay off-screen is the margin between the box and the edge of the view, which at 32 pixels to the tile is 8 tiles (256 px) on the widest of them (the 640-wide Dreamcast, GameCube and PlayStation 2, whose visible half-width is 10 tiles) and 13 tiles on the Nintendo 64. Even the tightest of those is about half a second of travel at Player::MaxDashingSpeed, and lowering PreferencesCache::RenderingResolutionPercent only ever shows less of the world, so it cannot eat into the margin. The Wii is deliberately not in the list - it is the fastest machine here and renders the same 640 columns - but it would be safe if it ever needs the room.