### Install Doxygen Source: https://github.com/luatrauma/luatrauma.docs/blob/master/README.md Run the installation script for Doxygen. This is a prerequisite for building the CSharp API documentation. ```bash install_doxygen.sh ``` -------------------------------- ### Install MkDocs Material Source: https://github.com/luatrauma/luatrauma.docs/blob/master/README.md Install the MkDocs Material theme for building the manual. This is a prerequisite for the manual build process. ```bash pip install mkdocs-material ``` -------------------------------- ### Lua Configuration Example (Lua) Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-service.md Placeholder for Lua configuration examples. This snippet is intended to be completed with specific Lua code for configuration management. ```lua -- TO BE COMPLETED by @EvilFactory ``` -------------------------------- ### Build and Serve Manual Source: https://github.com/luatrauma/luatrauma.docs/blob/master/README.md Execute the script to build and serve the project's manual. Assumes MkDocs Material is installed. ```bash ./serve_manual.sh ``` -------------------------------- ### Windows Launch Option Install Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/installation.md Use this command in Steam launch options to automatically install and update the mod on Windows. Ensure the game is closed before applying. ```cmd cmd /c "C:\\Windows\\System32\\curl.exe -L -o Luatrauma.AutoUpdater.win-x64.exe https://github.com/Luatrauma/Luatrauma.AutoUpdater/releases/download/latest/Luatrauma.AutoUpdater.win-x64.exe && start /b Luatrauma.AutoUpdater.win-x64.exe %COMMAND%" ``` -------------------------------- ### Install Luatrauma using Steam Launch Option (Windows) Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Use this command in Steam launch options for automatic installation and updates on Windows. It downloads and runs the auto-updater. ```bash # Windows — paste into Steam > Barotrauma > Properties > Launch Options cmd /c "C:\\Windows\\System32\\curl.exe -L -o Luatrauma.AutoUpdater.win-x64.exe https://github.com/Luatrauma/Luatrauma.AutoUpdater/releases/download/latest/Luatrauma.AutoUpdater.win-x64.exe && start /b Luatrauma.AutoUpdater.win-x64.exe %COMMAND%" ``` -------------------------------- ### Build CSharp API Documentation Source: https://github.com/luatrauma/luatrauma.docs/blob/master/README.md Build the CSharp API documentation after Doxygen has been installed. Generated files will be located in build/api/cs/client and build/api/cs/server. ```bash build_api_cs.sh ``` -------------------------------- ### Linux Launch Option Install Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/installation.md Use this command in Steam launch options to automatically install and update the mod on Linux. Ensure the game is closed before applying. ```bash bash -c "wget https://github.com/Luatrauma/Luatrauma.AutoUpdater/releases/download/latest/Luatrauma.AutoUpdater.linux-x64 && chmod +x Luatrauma.AutoUpdater.linux-x64 && ./Luatrauma.AutoUpdater.linux-x64 %command%" ``` -------------------------------- ### Build Lua API Documentation Source: https://github.com/luatrauma/luatrauma.docs/blob/master/README.md Build the Lua API documentation. Ensure Lua 5.2, Lua headers, and Luarocks are installed prior to execution. Generated files will be in build/api/lua/. ```bash build_api_lua.sh ``` -------------------------------- ### Create a First Lua Mod (Hello World) Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Place Lua scripts in the `Lua/Autorun/` directory of your mod. They will execute automatically when the game starts or a round begins. Use `cl_reloadlua` or `reloadlua` in the debug console to reload scripts. ```plaintext LocalMods/ MyMod/ Lua/ Autorun/ test.lua ← executed automatically ``` ```lua -- LocalMods/MyMod/Lua/Autorun/test.lua print("Hello, world!") -- Reload scripts at any time using the debug console (F3): -- cl_reloadlua → reloads client-side Lua -- reloadlua → reloads server-side Lua ``` -------------------------------- ### Install Luatrauma using Steam Launch Option (Linux) Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Use this command in Steam launch options for automatic installation and updates on Linux. It downloads, makes executable, and runs the auto-updater. ```bash # Linux bash -c "wget https://github.com/Luatrauma/Luatrauma.AutoUpdater/releases/download/latest/Luatrauma.AutoUpdater.linux-x64 && chmod +x Luatrauma.AutoUpdater.linux-x64 && ./Luatrauma.AutoUpdater.linux-x64 %command%" ``` -------------------------------- ### Example In-Memory Mod Implementation Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/cs/setup-in-memory-csharp.md This C# code demonstrates the basic structure of an in-memory mod, including necessary assembly attributes and the `IAssemblyPlugin` interface for initialization and lifecycle management. ```csharp using System; using Barotrauma; // This is required so that the .NET runtime doesn't complain about you trying to access internal Types and Members [assembly: IgnoreAccessChecksTo("Barotrauma")] [assembly: IgnoreAccessChecksTo("BarotraumaCore")] [assembly: IgnoreAccessChecksTo("DedicatedServer")] namespace ExampleNamespace { partial class ExampleMod : IAssemblyPlugin { public void Initialize() { // When your plugin is loading, use this instead of the constructor // Put any code here that does not rely on other plugins. LuaCsLogger.Log("ExampleMod loaded!"); } public void OnLoadCompleted() { // After all plugins have loaded // Put code that interacts with other plugins here. } public void PreInitPatching() { // Not yet supported: Called during the Barotrauma startup phase before vanilla content is loaded. } public void Dispose() { // Cleanup your plugin! LuaCsLogger.Log("ExampleMod disposed!"); } } } ``` -------------------------------- ### Install Luatrauma using Steam Launch Option (macOS) Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Use this command in Steam launch options for automatic installation and updates on macOS. It navigates to the correct directory, downloads, makes executable, and runs the auto-updater. ```bash # macOS /bin/zsh -c "cd Barotrauma.app/Contents/MacOS && /usr/bin/curl -LOR https://github.com/Luatrauma/Luatrauma.AutoUpdater/releases/download/latest/Luatrauma.AutoUpdater.osx-x64 && chmod +x Luatrauma.AutoUpdater.osx-x64 && ./Luatrauma.AutoUpdater.osx-x64 %command%/Contents/MacOS/Barotrauma" ``` -------------------------------- ### MacOS Launch Option Install Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/installation.md Use this command in Steam launch options to automatically install and update the mod on MacOS. Ensure the game is closed before applying. ```zsh /bin/zsh -c "cd Barotrauma.app/Contents/MacOS && /usr/bin/curl -LOR https://github.com/Luatrauma/Luatrauma.AutoUpdater/releases/download/latest/Luatrauma.AutoUpdater.osx-x64 && chmod +x Luatrauma.AutoUpdater.osx-x64 && ./Luatrauma.AutoUpdater.osx-x64 %command%/Contents/MacOS/Barotrauma" ``` -------------------------------- ### Define Setting Localizations in XML Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-service.md Example of defining the DisplayName, DisplayCategory, and Tooltip for a setting within the infotexts XML file. ```xml A String of No Time Sample Imagine if ``` -------------------------------- ### Verify Luatrauma Installation Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Check the Barotrauma debug console (F3) to confirm correct installation. Use `cl_reloadluacs` for client-side and `reloadluacs` for server-side verification. ```bash # Verify correct installation in the Barotrauma debug console (F3): # Client-side: cl_reloadluacs # Server-side: reloadluacs ``` -------------------------------- ### Assembly Mod Project Structure Example Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt A typical directory structure for an assembly mod, showing the placement of C# source files, compiled DLLs, configuration files, and Lua scripts. ```text MyMod/ Assets/Content/ ModConfig.xml filelist.xml SharedProject/SharedSource/ Plugin.cs ← entry point ClientProject/ClientSource/ ... ← client-only code ServerProject/ServerSource/ ... ← server-only code Config/ SettingsShared.xml Lua/Server/ autorun.lua ``` -------------------------------- ### Build Scripts for LuaCsForBarotrauma Documentation Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Provides build scripts for installing prerequisites and serving/building the manual and API documentation. Requires Python, Doxygen, and Lua 5.2 with headers and LuaRocks. ```bash # Install prerequisites pip install mkdocs-material # MkDocs (manual) ./install_doxygen.sh # Doxygen (C# API) # Also requires: Lua 5.2, Lua headers, LuaRocks (Lua API) # Build and serve the manual (live reload) ./serve_manual.sh # Output: http://127.0.0.1:8000 # Build all documentation components ./build_manual.sh # → build/manual/ ./build_api_lua.sh # → build/api/lua/ ./build_api_cs.sh # → build/api/cs/client/ and build/api/cs/server/ ``` -------------------------------- ### Basic Lua Print Statement Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/lua/getting-started.md This is a simple Lua script that prints 'Hello, world!' to the debug console. It's the first script to create when starting a new mod. ```lua print("Hello, world!") ``` -------------------------------- ### Define a String Setting in XML Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-service.md Example of defining a string type setting within the Configuration element of your settings XML file. ```xml ``` -------------------------------- ### Call a non-existent function in Lua Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/lua/errors.md This example demonstrates an 'attempt to call a nil value' error, which occurs when trying to execute a function that has not been defined. ```lua somethingThatDoesntExist() ``` -------------------------------- ### Initialize Plugin with ConfigService (C#) Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-service.md Demonstrates how to initialize a plugin by accessing the IConfigService to retrieve and manipulate settings. Ensure the plugin service is available before accessing configurations. ```csharp public partial class Plugin : IAssemblyPlugin { // These are automatically assigned by the plugin service after the Constructor is called public IConfigService ConfigService { get; set; } public IPluginManagementService PluginService { get; set; } public ILoggerService LoggerService { get; set; } private ContentPackage _myPackage; public ISettingBase AStringOfAllTime; public void Initialize() { // When your plugin is loading, use this instead of the constructor for code relying on // the services above. // Put any code here that does not rely on other plugins. // Get your ContentPackage if (!PluginService.TryGetPackageForPlugin(out _myPackage)) { LoggerService.LogError("Failed to find package!"); return; } // Get your setting's instance. if (!ConfigService.TryGetConfig(_myPackage, "AStringOfAllTime", out AStringOfAllTime)) { LoggerService.LogError("Failed to find config!"); return; } // Let's log the value LoggerService.Log($"Value={AStringOfAllTime.Value}"); // Lets write a value AStringOfAllTime.TrySetValue("No!"); // Let's save it to storage ConfigService.SaveConfigValue(AStringOfAllTime); } /* ...other code. */ } ``` -------------------------------- ### C# List Setting Initialization and Usage Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-specifications.md Initializes and uses a string list setting in C#. Demonstrates retrieving options, logging them, and setting a new value. Event handling for value changes is also included. ```csharp /* C# */ // class vars public ILoggerService Logger { get; set; } public IConfigService ConfigService { get; set; } ISettingList myVar; // Initialize() ConfigService.TryGetConfig>(mypackage, "Sample", out myVar); myVar.OnValueChanged += (cfg) => { Logger.Log($"Value Set for {myVar.InternalName} at {myVar.Value}"); }; foreach (string option in myVar.Options) { Logger.Log($"Possible option: {option}"); } myVar.TrySetValue("Option A"); // set in memory ConfigService.SaveConfigValue(myVar); // save to disk ``` -------------------------------- ### Lua Basic Setting Initialization and Usage Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-specifications.md Initializes and uses a basic boolean setting in Lua. Demonstrates retrieving a package and configuration, and adding an event listener for value changes. ```lua -- Lua function onValueChanged(cfg) print("New value set: ", cfg.Value) end local success, myPackage = trygetpackage("SamplePackage") local success2, var = ConfigService.TryGetConfig(SettingBase.Bool, myPackage, "Sample") if success2 then var.OnValueChanged.add(onValueChanged) end ``` -------------------------------- ### Sample Localization for Basic Settings Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-specifications.md Defines display name, category, and tooltip for basic settings like booleans. Use this format for `ISettingBase` and `ISettingRangeBase`. ```xml Sample Display Name Samples This is a sample ``` -------------------------------- ### Sample Localization for List Settings Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-specifications.md Defines display name, category, tooltip, and display names for list options. Use this format for `ISettingList`. ```xml Sample Display Name Samples This is a sample Is A Always B ``` -------------------------------- ### Retrieve Package for New APIs Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/migration-guide.md Many new APIs require your content package as an argument. Retrieve it using `trygetpackage("your package name")`. ```lua trygetpackage("your package name") ``` -------------------------------- ### LuaCsForBarotrauma Migration Guide API Renames Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Lists API references that were renamed in the Spring 2026 LuaCsForBarotrauma refactor. New APIs require the ContentPackage to be passed explicitly. ```lua -- Lua and C# In-Memory: rename these references -- OLD NEW -- GameMain.LuaCs → LuaCsSetup.Instance -- Client.ClientList → ModUtils.Client.ClientList -- Barotrauma.Networking.Client.ClientList → ModUtils.Client.ClientList -- ItemPrefab.GetItemPrefab → ModUtils.ItemPrefab.GetItemPrefab -- New APIs require the ContentPackage to be passed explicitly local ok, pkg = trygetpackage("MyPackageName") local ok2, mySetting = ConfigService.TryGetConfig(SettingBase.Bool, pkg, "MySetting") ``` -------------------------------- ### Access and Manage Settings in C# Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Retrieve, subscribe to changes, and modify settings values at runtime using C#. Ensure settings are correctly retrieved using the ContentPackage and `TryGetConfig`. ```csharp // SharedProject/SharedSource/Plugin.cs public partial class Plugin : IAssemblyPlugin { // Services injected automatically after constructor public IConfigService ConfigService { get; set; } public IPluginManagementService PluginService { get; set; } public ILoggerService LoggerService { get; set; } private ContentPackage _package; public ISettingBase EnableFeature; public ISettingRangeBase Intensity; public ISettingList Mode; public void Initialize() { if (!PluginService.TryGetPackageForPlugin(out _package)) { LoggerService.LogError("Could not find ContentPackage!"); return; } // Retrieve settings ConfigService.TryGetConfig(_package, "EnableFeature", out EnableFeature); ConfigService.TryGetConfig(_package, "Intensity", out Intensity); ConfigService.TryGetConfig(_package, "Mode", out Mode); // Subscribe to changes EnableFeature.OnValueChanged += cfg => LoggerService.Log($"EnableFeature changed to {cfg.Value}"); // Read values LoggerService.Log($"EnableFeature={EnableFeature.Value}"); LoggerService.Log($"Intensity={Intensity.Value} (min={Intensity.MinValue}, max={Intensity.MaxValue})"); LoggerService.Log($"Mode={Mode.Value}, options={string.Join(", ", Mode.Options)}"); // Write and persist EnableFeature.TrySetValue(false); ConfigService.SaveConfigValue(EnableFeature); } public void OnLoadCompleted() { } public void PreInitPatching() { } public void Dispose() { } } ``` -------------------------------- ### XML Configuration Sample Declaration Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-specifications.md This is a sample XML declaration for defining configuration settings. It includes a root Configuration element with a Settings element containing a sample Setting. ```xml ``` -------------------------------- ### C# Basic Setting Initialization and Usage Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-specifications.md Initializes and uses a basic boolean setting in C#. Requires ILoggerService and IConfigService. Event handling for value changes and setting new values are demonstrated. ```csharp /* C# */ // class vars public ILoggerService Logger { get; set; } public IConfigService ConfigService { get; set; } ISettingBase myVar; // Initialize() ConfigService.TryGetConfig>(mypackage, "Sample", out myVar); myVar.OnValueChanged += (cfg) => { Logger.Log($"Value Set for {myVar.InternalName} at {myVar.Value}"); }; myVar.TrySetValue(true); // set in memory ConfigService.SaveConfigValue(myVar); // save to disk ``` -------------------------------- ### Download Reference DLLs Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Command to download fresh reference DLLs for LuaCsForBarotrauma. Place these DLLs in the /Refs/ directory. ```bash # Also download fresh reference DLLs and place in /Refs/ # https://github.com/MapleWheels/LuaCsForBarotrauma/releases/download/latest/luacsforbarotrauma_refs.zip ``` -------------------------------- ### Basic Configuration XML Structure Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-service.md This is the basic structure for your custom settings XML file. Define your settings within the Configuration element. ```xml ``` -------------------------------- ### Schedule Execution with Timer.Wait/Timer.NextFrame Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Use Timer.Wait for delayed execution and Timer.NextFrame for execution on the next game frame. Timings are in milliseconds. Timer.GetTime returns the current game time in seconds. ```lua -- Delayed execution (3 seconds after round start) Hook.Add("roundStart", "delayedAnnounce", function() Timer.Wait(function() if SERVER then Game.SendMessage("3 seconds have passed!", ChatMessageType.Server, nil, nil) end end, 3000) end) -- Next-frame execution (defer expensive work) Hook.Add("character.created", "deferSetup", function(character) Timer.NextFrame(function() -- All other character.created hooks have now run print("Deferred setup for: " .. character.Name) end) end) -- Read the current game time local t = Timer.GetTime() print("Current game time (seconds): " .. tostring(t)) ``` -------------------------------- ### C# Range Setting Initialization and Usage Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-specifications.md Initializes and uses a float range setting in C#. Demonstrates retrieving the setting and logging its value along with min and max values. Saving the configuration is also shown. ```csharp /* C# */ // class vars public ILoggerService Logger { get; set; } public IConfigService ConfigService { get; set; } ISettingRangeBase myVar; // Initialize() ConfigService.TryGetConfig>(mypackage, "Sample", out myVar); myVar.OnValueChanged += (cfg) => { Logger.Log($"Value Set for {myVar.InternalName} at {myVar.Value}"); Logger.Log($"MinValue Set for {myVar.InternalName} at {myVar.MinValue}"); Logger.Log($"MaxValue Set for {myVar.InternalName} at {myVar.MaxValue}"); }; ConfigService.SaveConfigValue(myVar); ``` -------------------------------- ### Add NuGet Package References Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/migration-guide.md Add these NuGet package references to your Build.props file for binary assembly C# mods. ```xml ``` -------------------------------- ### Prefix Patch: Execute Before Original Method Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/lua/patching.md Use this to execute custom logic before a method runs. It allows modification of parameters, prevention of the original method's execution, or early returns. ```lua Hook.Patch( "Barotrauma.Character", "CanInteractWith", { "Barotrauma.Item", -- ref/out parameters are supported "out System.Single", "System.Boolean" }, function(instance, ptable) -- This prevents the original method from executing, so we're -- effectively replacing the method entirely. ptable.PreventExecution = true -- Modify the `out System.Single` parameter ptable["distanceToItem"] = Single(50) -- This changes the return value to "null" return nil end, Hook.HookMethodType.Before) ``` -------------------------------- ### Localize Settings Display Names (XML) Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Provide user-friendly display names and tooltips for settings in different languages using a separate XML file. This ensures settings are understandable in the in-game menu. ```xml Enable Feature My Mod Enables or disables the main feature. Game Mode Easy Normal Hard ``` -------------------------------- ### File.Write / File.Exists / File.Read / File.GetFiles / File.DirSearch Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Provides sandboxed filesystem access for reading and writing data files within the mod directory. Paths are relative to the mod folder. ```APIDOC ## File ### Description Provides sandboxed filesystem access for reading and writing data files within the mod directory. Paths are relative to the mod folder. ### Usage ```lua local dataPath = "%ModDir%/data/scores.json" -- Write data to a file local scores = '{"alice":10,"bob":7}' File.Write(dataPath, scores) -- Read it back if File.Exists(dataPath) then local contents = File.Read(dataPath) print("Loaded scores: " .. contents) end -- List all files in a directory local files = File.GetFiles("%ModDir%/data/") for _, f in ipairs(files) do print("Found file: " .. f) end -- Recursively search a folder local allFiles = File.DirSearch("%ModDir%/") for _, f in ipairs(allFiles) do print(f) end ``` ``` -------------------------------- ### Declare Settings in XML Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Define settings with their types, default values, and constraints in an XML configuration file. This file serves as the source of truth for all configurable options. ```xml ``` -------------------------------- ### Manage Files with File API Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt The File API provides sandboxed filesystem access for reading and writing data files. Paths are relative to the mod folder. Use File.Write, File.Read, File.Exists, File.GetFiles, and File.DirSearch. ```lua local dataPath = "%ModDir%/data/scores.json" -- Write data to a file local scores = '{"alice":10,"bob":7}' File.Write(dataPath, scores) -- Read it back if File.Exists(dataPath) then local contents = File.Read(dataPath) print("Loaded scores: " .. contents) end -- List all files in a directory local files = File.GetFiles("%ModDir%/data/") for _, f in ipairs(files) do print("Found file: " .. f) end -- Recursively search a folder local allFiles = File.DirSearch("%ModDir%/") for _, f in ipairs(allFiles) do print(f) end ``` -------------------------------- ### Build.props for Binary Assembly Mods Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Specifies the NuGet packages required for binary assembly mods after the Spring 2026 refactor. ```xml ``` -------------------------------- ### Use Util API for Item and Client Lookups Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt The Util API offers helpers for finding items by identifier, creating item groups, and mapping characters to clients. Use Util.GetItemsById, Util.RegisterItemGroup, Util.GetItemGroup, and Util.FindClientCharacter. ```lua -- Find all in-world items matching an identifier local medkits = Util.GetItemsById(Identifier("firstaidkit")) for _, item in pairs(medkits) do print("Found medkit at: " .. tostring(item.WorldPosition)) end -- Register a custom item group (items with "weapon" tag) Util.RegisterItemGroup("weapons", function(item) return item.HasTag(Identifier("weapon")) end) -- Retrieve the group later local weapons = Util.GetItemGroup("weapons") print("Total weapons on map: " .. tostring(#weapons)) -- Find the client controlling a character Hook.Add("character.death", "findKilledClient", function(character) local client = Util.FindClientCharacter(character) if client then print("Player " .. client.Name .. " died.") else print("An NPC died.") end end) ``` -------------------------------- ### Send Message from Server to Client Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/lua/networking.md This demonstrates sending a message from the server to a specific client or all clients. The client must have a corresponding receive handler. ```lua if CLIENT then Networking.Receive("foobar", function(message) print(message.ReadString()) end) end if SERVER then -- send from server to client local message = Networking.Start("foobar") message.WriteString("hello") -- The second argument is the client you want to send the message to, if you leave it nil, it will send to all clients Networking.Send(message, Client.ClientList[1].Connection) end ``` -------------------------------- ### Add Text File to filelist.xml Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-service.md Include your localization text file in the main filelist.xml of your content package. ```xml ``` -------------------------------- ### Sync Light Component Color with Serializable Property Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/lua/networking.md Synchronize a light component's color on an item to clients using Serializable Properties. This method avoids the need for manual client-side updates. ```lua local item = ... local light = item.GetComponentString("LightComponent") light.LightColor = Color(0, 0, 255, 255) local property = light.SerializableProperties[Identifier("LightColor")] Networking.CreateEntityEvent(item, Item.ChangePropertyEventData(property, light)) ``` -------------------------------- ### IAssemblyPlugin Interface for In-Memory C# Mods Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Implement the IAssemblyPlugin interface in your C# files placed in the CSharp/Shared, CSharp/Client, or CSharp/Server directories. These methods control the mod's lifecycle. ```csharp // /CSharp/Shared/MyPlugin.cs using System; using Barotrauma; [assembly: IgnoreAccessChecksTo("Barotrauma")] [assembly: IgnoreAccessChecksTo("BarotraumaCore")] [assembly: IgnoreAccessChecksTo("DedicatedServer")] namespace MyMod { partial class MyPlugin : IAssemblyPlugin { public void Initialize() { // Called first; do not depend on other plugins here LuaCsLogger.Log("MyPlugin: Initialize"); } public void OnLoadCompleted() { // Called after ALL plugins have loaded — safe to reference other mods LuaCsLogger.Log("MyPlugin: OnLoadCompleted"); // Example: register a hook from C# GameMain.LuaCs.Hook.Add("roundStart", "myRoundStart", (object[] args) => { LuaCsLogger.Log("Round started!"); return null; }); } public void PreInitPatching() { // Reserved for pre-content-load patching (not yet fully supported) } public void Dispose() { // Clean up resources, unregister hooks, etc. LuaCsLogger.Log("MyPlugin: Disposed"); } } } ``` -------------------------------- ### Include Config File in ModConfig.xml Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-service.md Add this to your ModConfig.xml to specify the path to your custom settings configuration file. ```xml ``` -------------------------------- ### HarmonyX Attribute-Based Method Patching in C# Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Demonstrates attribute-based patching for C# assembly mods using HarmonyX. Use Postfix to run code after the original method, and Prefix to control execution flow by returning false to skip the original method. Ensure Harmony is initialized with PatchAll() and unpatched with UnpatchAll() during plugin initialization and disposal. ```csharp using HarmonyLib; using Barotrauma; namespace MyMod { // Applied automatically if Harmony is initialised with PatchAll() [HarmonyPatch(typeof(CharacterInfo), nameof(CharacterInfo.IncreaseSkillLevel))] public static class SkillLevelPatch { // Postfix: runs after the original method [HarmonyPostfix] public static void Postfix(CharacterInfo __instance, float increase) { LuaCsLogger.Log($"{__instance.Character?.Name} gained {increase} XP"); } } [HarmonyPatch(typeof(Character), nameof(Character.CanInteractWith), new[] { typeof(Item), typeof(float), typeof(bool) })] public static class CanInteractPatch { // Prefix: return false to skip the original method [HarmonyPrefix] public static bool Prefix(Character __instance, Item item, ref float distanceToItem, ref bool __result) { distanceToItem = 50f; __result = false; return false; // skip original } } public partial class Plugin : IAssemblyPlugin { private Harmony _harmony; public void Initialize() { _harmony = new Harmony("com.mymod.harmony"); _harmony.PatchAll(); // applies all [HarmonyPatch] classes in this assembly } public void Dispose() { _harmony.UnpatchAll("com.mymod.harmony"); } } } ``` -------------------------------- ### Game State and Server Controls Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt The `Game` global provides access to round state, server settings, and server-side actions such as sending chat messages, spawning explosions, and managing console commands. ```APIDOC ## Game ### Description Provides access to round state, server settings, and server-side actions like sending chat messages, spawning explosions, and managing console commands. ### Usage ```lua -- Check runtime context print("Is server: " .. tostring(SERVER)) print("Is client: " .. tostring(CLIENT)) print("Round started: " .. tostring(Game.RoundStarted)) print("Is dedicated: " .. tostring(Game.IsDedicated)) -- Send a server-wide chat message (server only) if SERVER then Hook.Add("roundStart", "serverAnnounce", function() Game.SendMessage("Round started! Good luck.", ChatMessageType.Server, nil, nil) end) end -- Spawn an explosion at a world position (shared) Hook.Add("item.use", "grenadePatch", function(item, user, limb) if item.Prefab.Identifier == Identifier("grenade") then Game.Explode(item.WorldPosition, 200, 500, 100, 50, 10, 0, 0) end end) -- Add a custom console command Game.AddCommand("mymod_hello", "Prints a greeting", function(args) print("Hello from mymod! Args: " .. table.concat(args, ", ")) end) -- Execute an existing console command programmatically Game.ExecuteCommand("kick SomeTrollingPlayer") ``` ``` -------------------------------- ### Send HTTP Requests with Networking.HttpGet/HttpPost Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Use Networking.HttpGet and Networking.HttpPost to send asynchronous HTTP requests. The callback function receives the response body, status code, and headers. ```lua -- GET request Networking.HttpGet("https://api.example.com/data", function(response, statusCode, headers) if statusCode == 200 then print("Response: " .. response) else print("Error: HTTP " .. tostring(statusCode)) end end) -- POST request with JSON body Networking.HttpPost( "https://api.example.com/report", function(response, statusCode, headers) print("POST result: " .. tostring(statusCode)) end, '{"event":"roundEnd","players":4}', "application/json" ) ``` -------------------------------- ### Networking.CreateEntityEvent Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Synchronizes serializable properties of game entities from the server to all clients. ```APIDOC ## Networking.CreateEntityEvent ### Description Synchronizes a Barotrauma serializable property (e.g., item colour) from the server to all clients without requiring manual client-side network code. This is useful for updating visual aspects or state that doesn't require complex logic. ### Method Signature `Networking.CreateEntityEvent(entity, eventData)` ### Parameters - **entity** (object) - The entity whose property is being changed (e.g., an `Item` object). - **eventData** (object) - Data describing the property change. Typically created using `Item.ChangePropertyEventData()` or similar methods for components. ### Usage Examples ```lua -- Change an item's sprite colour and sync to all clients if SERVER then Hook.Add("item.use", "colorOnUse", function(item, user, targetLimb) -- Set value server-side item.SpriteColor = Color(0, 128, 255, 255) -- Notify clients via the entity event system local property = item.SerializableProperties[Identifier("SpriteColor")] Networking.CreateEntityEvent(item, Item.ChangePropertyEventData(property, item)) end) end -- Sync an item component property (e.g., LightComponent colour) if SERVER then Hook.Add("roundStart", "initLights", function() for _, item in pairs(Item.ItemList) do local light = item.GetComponentString("LightComponent") if light then light.LightColor = Color(255, 50, 50, 255) local prop = light.SerializableProperties[Identifier("LightColor")] Networking.CreateEntityEvent(item, Item.ChangePropertyEventData(prop, light)) end end end) end ``` ``` -------------------------------- ### Send Message from Client to Server Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/lua/networking.md Use this pattern to send custom messages from the client to the server. Ensure the server is listening for the message with the same identifier. ```lua if CLIENT then -- send from client to server local message = Networking.Start("foobar") message.WriteString("hello") Networking.Send(message) end if SERVER then -- receive in server Networking.Receive("foobar", function(message, client) print(client.Name .. " sent " .. message.ReadString()) end) end ``` -------------------------------- ### Postfix Patch: Execute After Original Method Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/lua/patching.md Use this to run custom code after a method completes. It's useful for logging or reacting to the original method's outcome. ```lua Hook.Patch("Barotrauma.CharacterInfo", "IncreaseSkillLevel", function(instance, ptable) print(string.format("%s gained % xp", instance.Character.Name, ptable["increase"])) end, Hook.HookMethodType.After) ``` -------------------------------- ### Access Settings in Lua Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Access the same settings defined in XML and managed by `IConfigService` from Lua scripts. This allows for cross-language access to configuration values. ```lua -- Lua equivalent — access the same settings local ok, pkg = trygetpackage("MyMod") if not ok then return end local ok2, enableFeature = ConfigService.TryGetConfig(SettingBase.Bool, pkg, "EnableFeature") if ok2 then enableFeature.OnValueChanged.add(function(cfg) print("EnableFeature changed: " .. tostring(cfg.Value)) end) print("Current value: " .. tostring(enableFeature.Value)) end ``` -------------------------------- ### Send Custom Network Messages Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Implement bidirectional messaging between clients and server using `Networking.Start`, `Networking.Send`, and `Networking.Receive`. Handles custom message names and data serialization. ```lua -- ── CLIENT → SERVER ────────────────────────────────────────────────────────── if CLIENT then -- Send a message to the server local msg = Networking.Start("myMod.ping") msg.WriteString("Hello server!") msg.WriteInt32(42) Networking.Send(msg) end if SERVER then -- Receive on server Networking.Receive("myMod.ping", function(message, client) local text = message.ReadString() local value = message.ReadInt32() print(client.Name .. " sent: " .. text .. ", value=" .. tostring(value)) end) end ``` ```lua -- ── SERVER → CLIENT ────────────────────────────────────────────────────────── if SERVER then Networking.Receive("myMod.ping", function(message, client) -- Echo back to the sending client only local reply = Networking.Start("myMod.pong") reply.WriteString("Hello " .. client.Name .. "!") Networking.Send(reply, client.Connection) -- Or broadcast to ALL connected clients (pass nil as connection) -- Networking.Send(reply, nil) end) end if CLIENT then Networking.Receive("myMod.pong", function(message) print("Server replied: " .. message.ReadString()) end) end ``` -------------------------------- ### XML Basic Setting Configuration Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-specifications.md Defines a basic boolean setting in XML format. Ensure Name, Type, and Value attributes are present. ```xml ``` -------------------------------- ### Replace C# Code References Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/migration-guide.md Replace these legacy code references with their new equivalents for immediate compatibility in C# mods. ```csharp "GameMain.LuaCs" is now "LuaCsSetup.Instance" ``` ```csharp "Client.ClientList" is now "ModUtils.Client.ClientList" ``` ```csharp "Barotrauma.Networking.Client.ClientList" is now "ModUtils.Client.ClientList" ``` ```csharp "ItemPrefab.GetItemPrefab" is now "ModUtils.ItemPrefab.GetItemPrefab" ``` -------------------------------- ### XML List Setting Configuration Source: https://github.com/luatrauma/luatrauma.docs/blob/master/manual/docs/common/development/config-specifications.md Defines a string list setting in XML. Requires a 'Values' child element containing individual 'Value' elements. The 'Value' attribute must be present in the options. ```xml ``` -------------------------------- ### Hook.Add - Listen to Game Events Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Registers a callback function to be executed when a specific game event occurs. Multiple listeners can be added for the same event, and they can be removed later using Hook.Remove. ```APIDOC ## Hook.Add — Listen to Game Events Registers a named callback for a game event. The hook name (second argument) is a unique identifier for this particular listener — it allows the same event to have multiple independent listeners and supports later removal via `Hook.Remove`. ```lua -- Listen for chat messages and log them server-side Hook.Add("chatMessage", "myChatLogger", function(message, client) print(client.Name .. " says: " .. message) -- Return true to suppress the message entirely -- return true end) -- React to character death Hook.Add("character.death", "myDeathHandler", function(character) print(character.Name .. " has died.") end) -- React to round start / end Hook.Add("roundStart", "myRoundStart", function() print("A new round has begun!") end) Hook.Add("roundEnd", "myRoundEnd", function() print("Round is over.") end) -- Per-frame update hook (~60 Hz) Hook.Add("think", "myTick", function() -- runs every physics tick; keep this lightweight end) -- Remove a hook when no longer needed Hook.Remove("chatMessage", "myChatLogger") ``` ``` -------------------------------- ### Interact with Game State using Game API Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt The Game global provides access to round state, server settings, and server-side actions. Use Game.SendMessage to send chat messages and Game.Explode to spawn explosions. ```lua -- Check runtime context print("Is server: " .. tostring(SERVER)) print("Is client: " .. tostring(CLIENT)) print("Round started: " .. tostring(Game.RoundStarted)) print("Is dedicated: " .. tostring(Game.IsDedicated)) -- Send a server-wide chat message (server only) if SERVER then Hook.Add("roundStart", "serverAnnounce", function() Game.SendMessage("Round started! Good luck.", ChatMessageType.Server, nil, nil) end) end -- Spawn an explosion at a world position (shared) Hook.Add("item.use", "grenadePatch", function(item, user, limb) if item.Prefab.Identifier == Identifier("grenade") then Game.Explode(item.WorldPosition, 200, 500, 100, 50, 10, 0, 0) end end) -- Add a custom console command Game.AddCommand("mymod_hello", "Prints a greeting", function(args) print("Hello from mymod! Args: " .. table.concat(args, ", ")) end) -- Execute an existing console command programmatically Game.ExecuteCommand("kick SomeTrollingPlayer") ``` -------------------------------- ### Networking.Send / Networking.Receive Source: https://context7.com/luatrauma/luatrauma.docs/llms.txt Enables bidirectional custom messaging between clients and the server for synchronized gameplay features. ```APIDOC ## Networking.Send / Networking.Receive ### Description Provides a system for sending and receiving custom network messages between clients and the server. This allows for custom synchronization of data and events. ### Methods - **Networking.Start(messageName)**: Creates a new, named message object for sending. - **Networking.Send(message, connection)**: Dispatches the created message. If `connection` is nil, the message is broadcast to all clients. - **Networking.Receive(messageName, handlerFunction)**: Registers a handler function to process incoming messages with the specified name. ### Message Object Methods - **WriteString(string)**: Writes a string to the message. - **WriteInt32(integer)**: Writes a 32-bit integer to the message. - **ReadString()**: Reads a string from the message. - **ReadInt32()**: Reads a 32-bit integer from the message. ### Usage Examples ```lua -- ── CLIENT → SERVER ────────────────────────────────────────────────────────── if CLIENT then -- Send a message to the server local msg = Networking.Start("myMod.ping") msg.WriteString("Hello server!") msg.WriteInt32(42) Networking.Send(msg) end if SERVER then -- Receive on server Networking.Receive("myMod.ping", function(message, client) local text = message.ReadString() local value = message.ReadInt32() print(client.Name .. " sent: " .. text .. ", value=" .. tostring(value)) end) end -- ── SERVER → CLIENT ────────────────────────────────────────────────────────── if SERVER then Networking.Receive("myMod.ping", function(message, client) -- Echo back to the sending client only local reply = Networking.Start("myMod.pong") reply.WriteString("Hello " .. client.Name .. "!") Networking.Send(reply, client.Connection) -- Or broadcast to ALL connected clients (pass nil as connection) -- Networking.Send(reply, nil) end) end if CLIENT then Networking.Receive("myMod.pong", function(message) print("Server replied: " .. message.ReadString()) end) end ``` ```