XSharp

Imported level assets and game sessions

Breakable map definitions may specify breaksTo, an ID in their own tilemap (or -1 to clear the placed cell). Replacements are prepared with the level and are applied locally, so other instances of shared templates remain unchanged. The importer emits the original successor ID for X1 collision3C metatiles; older USA X1 imports recover that rule from their pinned sourceSha1 metadata. An explicit breaksTo overrides migration. Custom maps without that property clear the broken cell. The existing placed-map save extension records the result.

Production hosts load .xlevel assets, not original ROMs. ROMExporter is the standalone .NET 9 import console/API (XSharp.Exporter.LevelWriter). It references MegaEDXCore, shared data/math and the device-free level authoring/package API, without initializing an engine or a renderer/audio host. The engine no longer references MegaEDXCore; the optional XSharp.RomCompatibility assembly retains direct-ROM loading for research tools and old ROM-backed states. Neither production host references that compatibility assembly or copies ROMs. DX9 shader content is supplied by its renderer project, avoiding duplicate publish paths in the engine. Fresh publications of both hosts are checked recursively for ROM files and decoder/compatibility assemblies.

Import and validate

dotnet run --project ROMExporter/ROMExporter.csproj -- --rom 'C:\ROMs\Megaman X (USA).sfc' --stage 8 --output XSharpDemo/Assets/Levels/Penguin.xlevel
dotnet run --project ROMExporter/ROMExporter.csproj -- --rom 'C:\ROMs\Megaman X2 (USA).sfc' --all --output XSharp.LevelSandbox/Assets/Levels
dotnet run --project tools/XSharp.LevelValidation/XSharp.LevelValidation.csproj -- XSharp.LevelSandbox/Assets/Levels

Repeat --all for the local X1/X3 ROMs. Stage numbers are decimal original stage indices, including intro/fortress stages (13 X1, 13 X2, 15 X3 slots). The importer accepts MegaEDX-supported originals/edited ROMs and records the normalized source SHA1; it does not embed the source ROM, native machine code or its path. A headered input’s 512-byte copier header is excluded from that hash. Output is written to a temporary sibling and replaced only after export completes. The public Load / Save API also supports reuse from another C# host such as HunterBaseStudio.

The CPU validator prepares every distinct shared graphics state, both atlases, checkpoint records and supported entity/trigger descriptors. It opens only the imported package and does not initialize an engine, renderer or audio device. This verifies asset/load contracts, not native gameplay/AI parity.

Package contents

The importer also supports editable sources and rebuilding them:

dotnet run --project ROMExporter -- --rom 'C:\ROMs\Megaman X (USA).sfc' --stage 8 --format editable --output Penguin.xproject
dotnet run --project ROMExporter -- --rom 'C:\ROMs\Megaman X (USA).sfc' --stage 8 --format both --output Penguin.xlevel
dotnet run --project ROMExporter -- --package XSharpDemo/Assets/Levels/Penguin.xlevel --output Penguin.xproject
dotnet run --project ROMExporter -- --project Penguin.xproject --output Penguin.xlevel

--format runtime (also binary) preserves the existing .xlevel output; editable (also project) writes a .xproject plus external resource files; both produces both. --all applies the chosen format to each stage. A --package input converts an existing runtime package without a ROM, while --project compiles edited source data. See authoring contracts and the Chill Penguin examples.

An asset is a ZIP containing the original JSON resource hierarchy:

Entry Purpose
level.json Format version 1, logical source ID, original game/stage, spawn/camera, initial selectors, source SHA1 and optional music
palettes/*.json Packed #AABBGGRR colors; alpha preserves transparent colors in each bank
tilesets/*.json Deduplicated 8x8 indexed tiles
tilemaps/*.json Native 16x16 map IDs, tile cells, palette banks, flips, priority and collision
blocks/blocks.json, scenes/scenes.json, layouts/layouts.json Map/block/scene references and foreground/background layout grids
checkpoints/checkpoints.json Ordered checkpoints, world bounds, spawn/camera/background, scroll, resource selectors, raw checkpoint records and X1 teleport collision delay
entities/entities.json Supported items, doors/triggers, ambient_generic, logic_script and original_object events retaining object ID/subtype
scripts/scripts.json, scripts/* Optional manifest aliases/languages and embedded source files for logic_script entities; see engine scripting
events/native.json Ordered source event identities/positions and raw match/flag bytes, including events without an engine implementation
resources/index.json Selector triples mapped to shared snapshots; null means reuse base graphics
resources/snapshots/*.xlevel Deduplicated palette/tileset/tilemap snapshots; geometry/entities remain in the base asset

The importer exports combinations of checkpoint/trigger selectors rather than looking them up during gameplay. Equal graphics share one snapshot, including selectors that alter native object graphics but leave the level graphics intact. Changing resources replaces atlas/palette resources without rebuilding entities or resetting live terrain. An unavailable selector combination fails explicitly. Native map IDs are preserved when map 0 is transparent in a nonzero palette bank. This matters to authored classes that refer to original map IDs. Native tile descriptors are exported in row-major quadrant order. See the quadrant regression and captured repair for the foreground/background transpose fixed after the initial integration. Packages created by that affected exporter require reimport.

Raw checkpoint records retain unknown X2/X3 control bytes. X1 and X3 telDwn are interpreted as teleport collision delays. X3 $04:9216 decrements +64 during descent and $04:B58A bypasses vertical collision while it is nonzero. Hornet’s initial checkpoint at $86:AA4C contains12 hex (18 updates), allowing X to pass the upper structure before landing. X2 remains unreviewed.

New imports mark level.json.checkpointTeleportTimers=true, making explicit checkpoint timer values authoritative. Old packages from the pinned X3 USA ROM can recover an omitted zero timer from byte29 of their retained32-byte native record. This migration opens no ROM and does not alter custom/new authored zero values or other source games. Hornet’s packaged Sandbox level was reimported. The source/collision fixture and reproduction script are XSharp.Tests/Fixtures/Armor/x3-hornet-spawn.json and tools/parity/extract_x3_hornet_spawn.py.

Authored logic can read the immutable source metadata through engine.CurrentLevelPackage; current selectors and stage identity are also exposed for debugging.

Object creation uses original game + object ID + subtype through the optional content registry. It does not hard-code imported actors to the former core compatibility shells. Unknown/unimplemented native events remain in the source event list for future authored logic; preserving them does not implement them. Resource snapshots describe graphics, not replacement layouts/collision logic.

Direct assets and authored levels

engine.LoadLevelPackage("Assets/Levels/X2/02.xlevel", checkpoint: 0);

var level = LevelDefinition.FromFile("Assets/Levels/X3/01.xlevel");
engine.LoadLevel(level);

LevelDefinition can instead open an embedded resource or any supplied stream. A derived class overrides OnLoaded, OnReady, OnPlayerSpawned, OnUnloaded and boss-door callbacks when a host needs C# behavior. The Penguin package carries its music manifest, scripts/Penguin.lua and logic_script event subscription itself; the demo opens it through a plain LevelDefinition. No Penguin-specific class is needed, and the same file works in LevelSandbox. Asset metadata selects the original game’s X physics profile unless the host explicitly configures PlayerPhysics or XSHARP_PHYSICS.

Hosts

dotnet run --project XSharpDemo/XSharpDemo.csproj -- --renderer=dx9
dotnet run --project XSharp.LevelSandbox/XSharp.LevelSandbox.csproj -- --game=X2 --stage=8 --checkpoint=1 --renderer=dx9
dotnet run --project XSharp.LevelSandbox/XSharp.LevelSandbox.csproj -- --level='C:\Levels\custom.xlevel' --checkpoint=0

During play in the sandbox, press F8 or open the window’s system menu with Alt+Space and choose Select level. Choose the game, stage and checkpoint, then select Load. Open package adds an external .xlevel to the choices for the current session. The selector opens with the current level and checkpoint selected. Cancelling returns to the current simulation frame, and loading another stage keeps the existing sandbox session context. Stop demo playback or recording before switching.

To test armor, start LevelSandbox with --armor=none, --armor=all or a comma-separated list of helmet, body, arms and legs. The launch value initializes the session inventory. F8 level changes keep that inventory, and loading a save state restores the inventory in the save. Set XSHARP_PAUSE_MENU=1 to view the equipped parts in the pause menu.

$env:XSHARP_PAUSE_MENU = '1'
dotnet run --project XSharp.LevelSandbox -- --game=X1 --stage=1 --armor=legs,body

The selected armor profile controls the effects of those parts. For example, the existing test asset package provides an armor profile that requires the leg parts for dash and reduces damage taken with the body parts. Use the same command with --armor=none to compare behavior.

dotnet build tests/XSharp.AssetFixture -c Release
dotnet run --project XSharp.LevelSandbox -- --game=X1 --stage=1 --armor=legs,body --asset-package=tests/XSharp.AssetFixture/bin/Release/net9.0/XSharp.AssetFixture.dll --armor-profile-asset=Profiles/Fixture/custom-bundle-armor.json

--armor-profile-asset reads the specified logical resource from the mounted content. It overrides armor rules from --player-profile-asset.

The Direct3D9 selector smoke dispatches the native system-menu command and F8 to the runtime window. It verifies all 41 installed catalog entries, external package metadata, cross-game loading, checkpoint reloads, session preservation and cancellation. An invalid checkpoint or a malformed external package leaves the running level in place and displays an error in the selector.

dotnet run --project tests/XSharp.LevelSmoke -c Release -- XSharp.LevelSandbox/Assets/Levels/X1/00.xlevel 0 --sandbox-level-selector=XSharp.LevelSandbox/Assets/Levels

Both retain --renderer=dx9|dx11|opengl; renderer implementation/runtime limits are independent of this format. The hidden-window DX9 integration runner also checks normal startup and asset/session save-state continuation:

dotnet run --project tests/XSharp.LevelSmoke/XSharp.LevelSmoke.csproj -- --penguin
dotnet run --project tests/XSharp.LevelSmoke/XSharp.LevelSmoke.csproj -- XSharp.LevelSandbox/Assets/Levels/X2/02.xlevel 0

LevelDefinition.OnLoaded runs inside loading. Register extra music, native SPC contexts and data-selected actor types there with PrecacheSoundFromManifest, PrecacheNativeSoundContext and PrecacheEntityAssets<T>/PrecacheEntityAssets(Type). Placed actors and their statically created child dependencies are prepared before OnReady and LevelAssetsPrecached. Runtime first-use asset loading is rejected; see the precache contract and regression smoke.

Game manager ownership

GameManager owns session policy, level resolution, player-death and boss-clear callbacks. CampaignGameManager owns CampaignContext: lives, completed stage IDs, collected heart/sub-tank IDs, tank energy and armor-part flags. Campaign collection is idempotent, survives stage reloads and is captured in state/demo snapshots. Collected hearts/sub-tanks do not respawn as fresh collectibles.

DemoGameManager and LevelTestGameManager use a separate transient SessionContext, without completed-stage or armor inventory requirements. Custom games can derive their own manager/policy. The sandbox overrides death handling to keep testing; the demo keeps a local life counter. Player lives are delegated to the active context, so respawning does not reset campaign lives. After a completed exit teleport and its fade, the engine calls GameManager.OnPlayerTeleportCompleted. The single-stage demo reloads its authored initial level at checkpoint zero, preserving session lives. The base policy retains the current-checkpoint reload; a campaign can override it for stage selection or progression. Ordinary death continues to use checkpoint respawn. Level teardown clears the previous battle/introduction flags. Custom session-context fields are serialized using the context type owned by the registered manager. The state document cannot select an executable type.

CaptureState() / RestoreState() also expose JSON session persistence to an application. Restoration checks manager identity, context kind and schema before replacing context. Armor/tank inventory records do not implement missing armor weapons, campaign menus or tank-consumption UI; those remain game behavior.

Engine states with a manager use xsharp-state:session-v3, capturing manager state and the asset source/selector/checkpoint. File assets restore from their path; embedded assets resolve their logical ID through the same manager registration. Existing combat-v2 states remain readable through the compatibility path; old ROM-backed states require the research assembly and source ROM, not the demo. Rectangular spatial partitions now use consistent column/row addressing while preserving the historical square-grid wire order.

Boss room entry depends on a registered boss, independently of the level source. Both normal and Sigma entry schedule their introduction/spawn for asset-backed hosts. See the room-entry regression and validation.

Validation scope

The checked-in asset catalog covers 41 stage slots (13 X1, 13 X2, 15 X3), with source SHA1, package SHA256, checkpoint/event counts and graphics-state counts. The separate embedded Penguin asset makes 42 packages for CPU validation. Assets/Levels/catalog.json is copied alongside the sandbox assets. All 42 packages / 1,722 logical resource combinations passed the CPU validator on 2026-11-09. Repeated native tile/block/scene lookups materialize JSON arrays once; the complete final validator run took 26.37 seconds on the development machine. This timing is an observation, not a portable performance target.

The focused tests cover asset parsing/resource selection, transparent map zero, typed session persistence, campaign versus demo policies and rectangular spatial state restoration. The DX9 smoke runner checks live startup, resource changes without replacing entities/terrain, authored Penguin doors and session/state restoration. Its --penguin 0 --campaign mode also exercises heart and sub-tank pickups, duplicate suppression, lives and inventory restoration. These checks do not certify every native event, renderer, stage playthrough or movie parity. The focused suite passed 53 cases and the existing enemy/projectile regression passed 226 cases. Live DX9 checks covered Penguin, Sponge checkpoint 1, Buffalo, Mandrill and Kuwanger; the last two retained the expected lower starting floor (player origins Y=911 and Y=6047 respectively).

HunterBaseStudio reuse

Use the importer/data schema without importing production hosts, game actors or the optional direct-ROM runtime adapter. Preserve source game/stage, IDs/subtypes, checkpoint selectors and raw event records. A project/editor may attach a C# level class or game manager separately; the imported asset does not contain executable type names or automatically instantiate arbitrary code. No executable HunterBaseStudio integration is implied by this format documentation.

Runtime placed-map changes now have an isolated path and persist in the terrain-v4 state envelope, including authored Penguin doors and Igloo destruction. Source IDs resolve through prepared atlas offsets. See local terrain/state details for the API, compatibility boundaries and 2026-11-17 validation.