') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); GitHub - MrsFlower/MoonSLG: 使用moonbit开发的SLG视觉小说游戏自动生成框架 · GitHub
Skip to content

Repository files navigation

Moonbit Visual Novel Engine

A minimalist Visual Novel / Interactive Fiction engine built with Moonbit and WebAssembly.

Project Overview

This project implements a Visual Novel engine where:

  • Core logic is written in Moonbit and compiled to WebAssembly (Wasm)
  • UI is built with vanilla HTML/CSS/JavaScript
  • Story data is defined in JSON format following a defined schema

Project Structure

moonslg/
├── moon.mod.json # Moonbit module configuration
├── moon.pkg.json # Moonbit package configuration with Wasm exports
├── main.mbt # Core Moonbit source code (data structures & logic)
├── index.html # Main HTML entry point
├── css/
│ └── style.css # Visual novel UI styles
├── js/
│ ├── wasm-loader.js # WebAssembly module loader
│ └── app.js # Main application logic
├── schema/
│ └── story.schema.json # JSON schema for story data
├── data/
│ └── example-story.json # Example story data file
└── target/ # Build output directory (generated)
└── wasm-gc/
└── vn-engine.wasm # Compiled WebAssembly module

Moonbit Type Definitions

Choice Struct

Represents a player-selectable option in the story.

pubstructChoice {
mut text: String// The display text for this choice
mut target_node_id: Int// The ID of the node this choice leads to
}

Node Struct

Represents a single story node/scene in the visual novel.

pubstructNode {
mut id: Int// Unique identifier for this node
mut background_image_url: String// URL or path to the background image
mut text_content: String// The main text content displayed
mut choices: Array[Choice] // Available choices for the player
}

StoryState Struct

Manages the current state of the visual novel.

pubstructStoryState {
mut nodes: Map[Int, Node] // All story nodes indexed by ID
mut current_node: Option[Node] // Currently active node
mut selected_choice: Int// Currently selected choice index
}

Exported Wasm Functions

The following functions are exported from the Wasm module:

FunctionDescription
get_current_node()Returns the current story node
get_node_id(node)Gets the ID of a node
get_node_background_url(node)Gets the background image URL
get_node_text_content(node)Gets the text content
get_choices_count(node)Returns the number of choices
get_choice_text(node, index)Gets choice text at index
get_choice_target_id(node, index)Gets target node ID for choice
load_story_data(json_string)Loads story from JSON
select_choice(index)Selects a choice and navigates

JSON Schema

Story data follows the JSON schema defined in schema/story.schema.json. The schema maps directly to the Moonbit structs:

{
"metadata": {
"title": "Story Title",
"author": "Author Name",
"version": "1.0.0"
},
"start_node_id": 1,
"nodes": [
{
"id": 1,
"background_image_url": "images/scene1.png",
"text_content": "Your story text here...",
"choices": [
{
"text": "Choice text",
"target_node_id": 2
}
]
}
]
}

Building the Project

Prerequisites

  • Moonbit installed on your system
  • A modern web browser with WebAssembly support

Build Commands

# Build the project for Wasm target
moon build --target wasm-gc
# The output will be at:# target/wasm-gc/vn-engine.wasm

Development Server

To run the project locally, you need a web server (required for Wasm loading):

# Using Python 3
python -m http.server 8080
# Using Node.js (npx)
npx serve .# Using PHP
php -S localhost:8080

Then open http://localhost:8080 in your browser.

Usage

  1. Build the Moonbit project to generate the Wasm module
  2. Start a local web server
  3. Open index.html in a browser
  4. The engine will automatically load and display the demo story

Loading Custom Stories

To load a custom story:

  1. Create a JSON file following the schema in schema/story.schema.json
  2. Place the file in the data/ directory
  3. Modify js/app.js to load your story file instead of the demo

Architecture

┌─────────────────────────────────────────────────────────┐
│ Browser │
├─────────────────────────────────────────────────────────┤
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ index.html │───▶│ app.js │───▶│ wasm-loader │ │
│ └─────────────┘ └──────┬──────┘ └──────┬──────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ style.css │ │ vn-engine │ │
│ └─────────────┘ │ .wasm │ │
│ └─────────────┘ │
└─────────────────────────────────────────────────────────┘

Phase 1 Implementation Notes

This is Phase 1 of the project, which includes:

  • ✅ Moonbit project structure with Wasm target configuration
  • ✅ Core data structures (Node, Choice, StoryState)
  • ✅ HTML/CSS/JS boilerplate for Wasm loading
  • ✅ JSON schema for story data
  • ✅ Example story data
  • ✅ Basic demo story hardcoded in Moonbit

Known Limitations

  • JSON parsing is not yet implemented in Moonbit; story data is hardcoded
  • String handling between Wasm and JS may need adjustment based on Moonbit's actual memory layout
  • No save/load functionality yet

Future Phases

  • Phase 2: JSON parsing and external story loading
  • Phase 3: Save/Load game state
  • Phase 4: Audio support (BGM, sound effects)
  • Phase 5: Character sprites and animations
  • Phase 6: Visual editor for story creation

License

MIT License

Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

About

使用moonbit开发的SLG视觉小说游戏自动生成框架

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages