### SoundEmitterExample.cs Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/sound-emitter.md This C# example demonstrates various operations with the sound emitter, including checking sound validity, getting duration, modifying parameters, emitting, and stopping sounds. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace SoundEmitterExample { public class SoundEmitterExample : Game { private GraphicsDeviceManager _graphics; private SpriteBatch _spriteBatch; private SoundEffect _soundEffect; private SoundEffectInstance _soundEffectInstance; private SpriteFont _font; public SoundEmitterExample() { _graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; IsMouseVisible = true; } protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } protected override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); _font = Content.Load("Arial"); // Load sound effect from content pipeline _soundEffect = Content.Load("sound"); _soundEffectInstance = _soundEffect.CreateInstance(); } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); // TODO: Add your update logic here base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); _spriteBatch.Begin(); // Check if sound is valid if (_soundEffect != null) { // Get sound duration TimeSpan duration = TimeSpan.FromSeconds(_soundEffect.Duration.TotalSeconds); _spriteBatch.DrawString(_font, $"Sound Duration: {duration.TotalSeconds:F2}s", new Vector2(10, 10), Color.White); // Modify parameters in sound events _soundEffectInstance.Volume = 0.5f; // Set volume to 50% _soundEffectInstance.Pitch = 0.2f; // Set pitch slightly higher _soundEffectInstance.Pan = 0.0f; // Set pan to center // Emit sounds if (Keyboard.GetState().IsKeyDown(Keys.Space)) { // Play sound if not already playing if (_soundEffectInstance.State != SoundState.Playing) { _soundEffectInstance.Play(); } } else { // Stop sounds if (_soundEffectInstance.State == SoundState.Playing) { _soundEffectInstance.Stop(); } } } else { _spriteBatch.DrawString(_font, "Sound not loaded.", new Vector2(10, 10), Color.Red); } _spriteBatch.End(); base.Draw(gameTime); } } } ``` -------------------------------- ### Full Admin Example Source Code Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/admin-example.md This is the complete source code for the admin example, demonstrating the integration and usage of the Admin module. ```csharp // This is a placeholder for the actual full source code from the link. // The actual code would be inserted here if it were directly available in the provided text. ``` -------------------------------- ### Client Listener Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/client-listener.md A C# example demonstrating the Client Listener functionality. This code should be placed in a file named ClientListenerExample.cs. ```csharp using System; using System.Threading.Tasks; using Microsoft.Azure.Devices.Edge.Util.Concurrency; namespace Microsoft.Azure.Devices.Edge.Samples.ClientListener { public class ClientListenerExample { public static async Task Main(string[] args) { Console.WriteLine("Starting client listener example..."); // Simulate a client listener scenario var listener = new AsyncManualResetEvent(false); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; listener.Set(); }; Console.WriteLine("Client listener is running. Press Ctrl+C to stop."); await listener.WaitAsync(); Console.WriteLine("Client listener stopped."); } } } ``` -------------------------------- ### SharpExtensionsExample.cs Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/sharp-extensions.md Example demonstrating the use of Sharp Extensions. ```csharp using System; namespace ModSharp.Examples { public class SharpExtensionsExample { public static void Main(string[] args) { // Example usage of a hypothetical extension method string message = "Hello, ModSharp!"; Console.WriteLine(message.ToUpperCase()); // Assuming ToUpperCase is an extension method } } } // Hypothetical extension method definition (usually in a separate static class) public static class StringExtensions { public static string ToUpperCase(this string str) { return str.ToUpper(); } } ``` -------------------------------- ### NetMessage Send Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/net-message-send.md Example demonstrating how to send a Net Message. ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; public class NetMessageSendExample { public static void SendMessage(string ipAddress, int port, string message) { try { using (var client = new UdpClient()) { IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port); byte[] messageBytes = Encoding.UTF8.GetBytes(message); client.SendAsync(messageBytes, messageBytes.Length, ipEndPoint); Console.WriteLine($"Message sent to {ipEndPoint}"); } } catch (Exception ex) { Console.WriteLine($"Error sending message: {ex.Message}"); } } public static void Main(string[] args) { // Example usage: // SendMessage("127.0.0.1", 11000, "Hello, Server!"); } } ``` -------------------------------- ### Example MySQL Connection String Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/configurations/admin-commands-sqlstorage.md Provides an example of a connection string for MySQL in a JSON configuration. ```json "ConnectionStrings": { "AdminCommands.SQLStorage": "mysql://Server=localhost;Port=3306;Database=modsharp;User ID=modsharp;Password=secret;" } ``` -------------------------------- ### Dependency Injection Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/dependency-injection.md Demonstrates the basic usage of Dependency Injection. ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; var builder = Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { // Add services to the container. services.AddTransient(); services.AddScoped(); services.AddSingleton(); services.AddSingleton(); // Register the configuration object services.Configure(hostContext.Configuration.GetSection("MyOptions")); }); var app = builder.Build(); // Resolve and use services using (var scope = app.Services.CreateScope()) { var transientService = scope.ServiceProvider.GetRequiredService(); transientService.Describe("App Starts"); var scopedService1 = scope.ServiceProvider.GetRequiredService(); scopedService1.Describe("App Starts"); var singletonService = scope.ServiceProvider.GetRequiredService(); singletonService.Describe("App Starts"); var singletonInstanceService = scope.ServiceProvider.GetRequiredService(); singletonInstanceService.Describe("App Starts"); } app.Run(async (context) => { var transientService = context.RequestServices.GetRequiredService(); transientService.Describe("Incoming Request"); var scopedService2 = context.RequestServices.GetRequiredService(); scopedService2.Describe("Incoming Request"); var singletonService = context.RequestServices.GetRequiredService(); singletonService.Describe("Incoming Request"); var singletonInstanceService = context.RequestServices.GetRequiredService(); singletonInstanceService.Describe("Incoming Request"); await context.Response.WriteAsync("Hello World!"); }); public interface IOperation { Guid OperationId { get; } void Describe(string description); } public class Operation : IOperation { private static int _transientCounter = 0; private static int _scopedCounter = 0; private static int _singletonCounter = 0; private static int _singletonInstanceCounter = 0; private readonly Guid _id; private readonly ILogger _logger; private readonly IOptionsMonitor _options; // For transient and scoped public Operation(ILogger logger, IOptionsMonitor options) { _id = Guid.NewGuid(); _logger = logger; _options = options; Interlocked.Increment(ref _transientCounter); _logger.LogInformation("Operation created. ID: {OperationId}", _id); // Example using options _logger.LogInformation("{SectionName}: {Message}", nameof(MyOptions), _options.CurrentValue.Message); } // For singleton public Operation(string id, ILogger logger) { _id = Guid.Parse(id); _logger = logger; _singletonCounter++; _logger.LogInformation("Singleton Operation created. ID: {OperationId}", _id); } // For singleton instance public Operation(ILogger logger) { _id = Guid.NewGuid(); _logger = logger; _singletonInstanceCounter++; _logger.LogInformation("Singleton Instance Operation created. ID: {OperationId}", _id); } public Guid OperationId => _id; public void Describe(string description) { var counter = "N/A"; if (_transientCounter > 0) counter = _transientCounter.ToString(); if (_scopedCounter > 0) counter = _scopedCounter.ToString(); if (_singletonCounter > 0) counter = _singletonCounter.ToString(); if (_singletonInstanceCounter > 0) counter = _singletonInstanceCounter.ToString(); _logger.LogInformation("{Description} - Operation ID: {OperationId}, Instance Count: {Counter}", description, _id, counter); } } public interface IOperationTransient : IOperation { } public interface IOperationScoped : IOperation { } public interface IOperationSingleton : IOperation { } public interface IOperationSingletonInstance : IOperation { } public class MyOptions { public string Message { get; set; } } ``` -------------------------------- ### C# Event Listener Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/event-listener.md A basic example of setting up and using an EventListener in C#. ```csharp using System; public class EventListenerExample { public static void Main(string[] args) { // Create an event source (e.g., a custom event) var eventSource = new EventSource(); // Subscribe to an event eventSource.MyEvent += (sender, e) => { Console.WriteLine($"Event received: {e.Message}"); }; // Trigger the event eventSource.TriggerEvent("Hello from EventListener!"); } } public class EventSource { public event EventHandler MyEvent; public void TriggerEvent(string message) { OnMyEvent(new MyEventArgs { Message = message }); } protected virtual void OnMyEvent(MyEventArgs e) { MyEvent?.Invoke(this, e); } } public class MyEventArgs : EventArgs { public string Message { get; set; } } ``` -------------------------------- ### Basic Command Implementation Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/command.md Demonstrates the fundamental structure for creating a command. This example shows how to define a command that can be executed. ```csharp using System; namespace Mod.Commands { public class CommandExample { [Command("hello")] public void HelloCommand(CommandContext context) { context.Reply("Hello, World!"); } [Command("echo")] public void EchoCommand(CommandContext context, [RemainingText] string message) { context.Reply(message); } [Command("serveronly")] [ServerOnly] public void ServerOnlyCommand(CommandContext context) { context.Reply("This command can only be run on the server."); } [Command("clientonly")] [ClientOnly] public void ClientOnlyCommand(CommandContext context) { context.Reply("This command can only be run on the client."); } } } ``` -------------------------------- ### SteamListener Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/steam-listener.md A C# example demonstrating the functionality of the SteamListener. ```csharp using Steamworks; namespace SteamListenerExample { internal class SteamListenerExample { public static void Main(string[] args) { Steamworks.SteamClient.Init(480, true); // Create a listener that will be called when a message is received var listener = new Steamworks.Callback(OnFriendMessage); // Send a message to a friend (replace with a valid friend ID) // Steamworks.SteamClient.GetSteamUser().SendMessage(123456789, "Hello from SteamListener!"); // Keep the application running to receive messages System.Console.WriteLine("SteamListener started. Press any key to exit."); System.Console.ReadKey(); Steamworks.SteamClient.Shutdown(); } private static void OnFriendMessage(Steamworks.User.FriendMsgCallback callback) { System.Console.WriteLine($"Received message from {callback.FriendId}: {callback.Message}"); } } } ``` -------------------------------- ### GameListener Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/game-listener.md A C# example demonstrating the usage of the GameListener class. ```csharp using System; public class GameListenerExample { public static void Main(string[] args) { // Assuming GameListener is a class that can be instantiated and used // This is a placeholder for actual GameListener implementation and usage Console.WriteLine("GameListener example placeholder."); // Example: // var listener = new GameListener(); // listener.OnGameStart += (gameInfo) => Console.WriteLine($"Game started: {gameInfo}"); // listener.OnGameOver += (result) => Console.WriteLine($"Game over: {result}"); // listener.StartListening(); } } ``` -------------------------------- ### Client Preferences Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/client-preferences.md Demonstrates how to read and save player settings using ClientPreferences. ```csharp using System; using System.Threading.Tasks; public class ClientPreferencesExample { public static async Task Example() { // Load preferences from disk var preferences = await ClientPreferences.LoadAsync("MyGame"); // Read a preference value var playerName = preferences.GetString("PlayerName", "Guest"); Console.WriteLine($"Player Name: {playerName}"); // Set a preference value preferences.Set("PlayerName", "Alice"); // Save preferences to disk await preferences.SaveAsync(); } } ``` -------------------------------- ### C# Native Call Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/native-call.md This C# code snippet demonstrates how to perform a native call using ModSharp. Ensure the Sharp.Generator.Sdk is installed and the game data configuration is prepared. ```csharp using ModSharp.Core.Native; namespace ModSharp.Examples.NativeCall { public class NativeCall { public static void Main(string[] args) { // Example of calling a native function // Ensure the native-call.games.jsonc file is in the correct directory // and the Sharp.Generator.Sdk is installed. // This is a placeholder for actual native call logic. // Replace with your specific native function calls. // Example: GetWeaponByName might be called like this (hypothetical): // var player = CSPlayer.GetLocalPlayer(); // var weapon = player.CallNativeMethod("GetWeaponByName"); Console.WriteLine("Native call example executed."); } } } ``` -------------------------------- ### Install and Remove Game Listener Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/features/listeners.md This snippet shows how to install a game listener in the PostInit method and remove it in the Shutdown method. Ensure listeners are removed to avoid unexpected errors. ```csharp public void PostInit() => _modSharp.InstallGameListener(this); public void Shutdown() => _modSharp.RemoveGameListener(this); ``` -------------------------------- ### Example ModSharp Directory Structure Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/guides/getting-started.md Illustrates the expected file structure after placing the ModSharp package in the server's game directory. ```text . ├── bin ├── core ├── cs2.sh ├── csgo ├── csgo_community_addons ├── csgo_core ├── csgo_imported ├── csgo_lv ├── sharp │ ├── bin │ ├── configs │ ├── core │ ├── gamedata │ ├── modules │ └── shared └── thirdpartylegalnotices.txt ``` -------------------------------- ### HTTP Client Preferences Connection String Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/configurations/client-preferences.md This example demonstrates the connection string format for the HTTP schema, including host and authorization details. It's useful for configuring client preferences to be stored via a RESTful API. ```text http://Host=https://clientprefs.modsharp.net;Authorization=abc114514 ``` -------------------------------- ### Complete Example Configuration (admins.jsonc) Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/configurations/admin.md This JSON configuration defines permission collections, roles with immunity and permissions, and specific admin assignments including role inheritance and explicit denials. ```json { "PermissionCollection": { "admin": [ "admin:kick", "admin:ban", "admin:mute", "admin:slay", "admin:freeze", "admin:tp", "admin:map", "admin:noclip", "admin:rcon", "admin:cvar" ] }, "Roles": [ { "Name": "root", "Immunity": 255, "Permissions": ["*"] }, { "Name": "senior_admin", "Immunity": 80, "Permissions": ["@admin", "admin:rcon", "admin:cvar"] }, { "Name": "admin", "Immunity": 60, "Permissions": ["@moderator", "admin:map", "admin:slay", "admin:noclip"] }, { "Name": "moderator", "Immunity": 40, "Permissions": ["@helper", "admin:ban", "admin:freeze", "admin:tp"] }, { "Name": "helper", "Immunity": 20, "Permissions": ["admin:kick", "admin:mute"] } ], "Admins": [ { "Identity": 76561198000000001, "Permissions": ["@root"] }, { // Admin who cannot ban "Identity": 76561198000000002, "Permissions": ["@admin", "!admin:ban"] } ] } ``` -------------------------------- ### Command Manager Extension Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/command-manager.md This example shows how to register commands using the CommandManager extension. It is suitable for monorepo projects where all features are in a single module. ```csharp using Microsoft.Extensions.DependencyInjection; using Sharp.Extensions.CommandManager; namespace CommandManagerExample { public class CommandManagerExample { public static void ConfigureServices(IServiceCollection services) { // Register the CommandManager extension services.AddCommandManager(); } } } ``` -------------------------------- ### Trace Wrapper Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/trace-wrapper.md This C# snippet shows a basic example of performing a trace operation using the PhysicsQueryManager Wrapper. It requires the 'TraceWrapperExample.cs' file. ```csharp using System; using System.Numerics; using System.Runtime.InteropServices; using Anvil.Services; using Anvil.Native; using Anvil.Physics; public static class TraceWrapperExample { public static void Example() { // Get the PhysicsQueryManager service. var physicsQueryManager = Service.Get(); // Define the trace parameters. var ray = new Ray(new Vector3(0, 100, 0), new Vector3(0, -1, 0)); var maxDistance = 1000.0f; var collisionFilter = new CollisionFilter(1 << 0); // Perform the trace operation. var result = physicsQueryManager.Trace(ray, maxDistance, collisionFilter); // Process the result. if (result.HasHit) { Console.WriteLine($"Hit at distance: {result.Distance}"); Console.WriteLine($"Hit entity: {result.Entity}"); } else { Console.WriteLine("No hit."); } } } ``` -------------------------------- ### Simple Admin Configuration Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/configurations/admin.md Assign existing roles to players using their SteamID64. This format is a simple key-value pair for quick role assignment. ```json { // Owner / Root "76561198000000001": "root", // General Admins "76561198000000002": "admin", "76561198000000003": "admin", // Multiple roles: admin + vip "76561198000000004": ["admin", "vip"] } ``` -------------------------------- ### GameEventManager Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/game-event-manager.md This C# code snippet shows a basic example of how to use the GameEventManager. Ensure the GameEventManager extension is properly set up before using this code. ```csharp using System; public class GameEventManagerExample { public static void Main(string[] args) { // Example usage of GameEventManager // Assuming GameEventManager is initialized and available // GameEventManager.Instance.RegisterEvent(OnPlayerScoreUpdated); // GameEventManager.Instance.TriggerEvent(new PlayerScoreUpdatedEvent { PlayerId = 1, Score = 100 }); Console.WriteLine("GameEventManager example executed."); } // Example event handler // private static void OnPlayerScoreUpdated(PlayerScoreUpdatedEvent eventData) // { // Console.WriteLine($"Player {eventData.PlayerId} score updated to {eventData.Score}."); // } } // Example event class (should be defined elsewhere) // public class PlayerScoreUpdatedEvent // { // public int PlayerId { get; set; } // public int Score { get; set; } // } ``` -------------------------------- ### i18n Configuration Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/localizer-manager.md This JSON defines localization strings for different keys and languages. It includes examples of simple strings and strings with placeholders for parameters. ```json { "Generic.HelloWorld": { "en-us": "Test case A", "zh-cn": "测试用例A" }, "Hello": { "en-us": "Param A", "zh-cn": "参数A" }, "World": { "en-us": "Phrase, Param A={0}", "zh-cn": "语句, 参数A={0}" }, "Time": { "en-us": "Time = {0:F2}", "zh-cn": "时间 = {0:F6}" }, "Date": { "en-us": "Date is {0:d}", "zh-cn": "日期: {0:yyyy/MM/dd HH:mm}" } } ``` -------------------------------- ### Connection String Examples Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/configurations/core.md Provides connection strings for various ModSharp modules, such as client preferences and SQL storage. ```json "ConnectionStrings": { "ClientPreferences": "litedb://Filename={sharp::data}/client-preferences.db;Mode=Exclusive;Flush=true", "AdminCommands.SQLStorage": "mysql://Server=localhost;Port=3306;Database=modsharp;User ID=modsharp;Password=secret;" } ``` -------------------------------- ### MultiListenerExample.cs Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/multi-listeners.md This example shows how to define and implement multiple listeners within a single module. Explicitly implementing listener interfaces is used to distinguish the priority and version of each listener. ```csharp using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using ModuleSharp.Hosting; using ModuleSharp.Hosting.Abstractions; namespace MultiListenerExample { public class MultiListenerModule : ModuleBase { public override void ConfigureServices(ServiceConfigurationContext context) { context.Services.AddSingleton(); context.Services.AddSingleton(); } } public interface IMyListener : IListener { void HandleMessage(string message); } public class MyListenerOne : IMyListener { private readonly ILogger _logger; public MyListenerOne(ILogger logger) { _logger = logger; } public void HandleMessage(string message) { _logger.LogInformation("Listener One received: {Message}", message); } } public class MyListenerTwo : IMyListener { private readonly ILogger _logger; public MyListenerTwo(ILogger logger) { _logger = logger; } public void HandleMessage(string message) { _logger.LogInformation("Listener Two received: {Message}", message); } } } ``` -------------------------------- ### EntityListenerExample.cs Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/entity-listener.md A basic C# example demonstrating the usage of an Entity Listener. This snippet shows the core implementation without additional configurations. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ModSharp.Examples.EntityListeners { public class EntityListenerExample { // This is a placeholder for the actual Entity Listener implementation. // In a real scenario, this would involve specific framework or library calls // to register and define the behavior of an entity listener. public void DemonstrateEntityListener() { Console.WriteLine("Entity Listener example executed."); // Example of interacting with entities (conceptual) // var entity = new MyEntity(); // entity.SomeProperty = "Updated Value"; // EntityFramework.SaveChanges(); // Or similar persistence operation } } // Placeholder for a hypothetical entity class // public class MyEntity // { // public string SomeProperty { get; set; } // } } ``` -------------------------------- ### SteamCMD Installation for Steam RT3 Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/guides/getting-started.md Commands to install Steam RT3 using SteamCMD. This is a prerequisite for running ModSharp on Linux. ```bash force_install_dir ~/steamrt login anonymous app_update 1628350 validate ``` -------------------------------- ### EntityHookManager Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/entity-hook-manager.md Demonstrates the basic usage of the EntityHookManager for custom entity event handling. ```csharp using Mod.Framework.Entity; namespace Mod.Framework.Example { public class EntityHookManagerExample { public void Example() { var hookManager = new EntityHookManager(); // Register a hook for 'EntityCreated' event hookManager.RegisterHook(@event => { // Your custom logic here Console.WriteLine($"Entity created: {@event.Entity.Id}"); }); // Register a hook for 'EntityUpdated' event hookManager.RegisterHook(@event => { // Your custom logic here Console.WriteLine($"Entity updated: {@event.Entity.Id}"); }); // Simulate an entity creation event var entity = new Entity { Id = 1, Name = "Test Entity" }; hookManager.TriggerEvent(new EntityCreatedEvent(entity)); // Simulate an entity update event entity.Name = "Updated Entity"; hookManager.TriggerEvent(new EntityUpdatedEvent(entity)); } } // Dummy classes for demonstration purposes public class Entity { public int Id { get; set; } public string Name { get; set; } } public class EntityCreatedEvent { public Entity Entity { get; } public EntityCreatedEvent(Entity entity) { Entity = entity; } } public class EntityUpdatedEvent { public Entity Entity { get; } public EntityUpdatedEvent(Entity entity) { Entity = entity; } } } ``` -------------------------------- ### Create a ConVar Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/convar.md Example demonstrating the creation of a ConVar. This code defines a new console variable and its associated behavior. ```csharp using System; namespace ModSharp.Examples { public class ConVarExample { public static void Main(string[] args) { // Create a new ConVar named "my_convar" with a default value of "hello world" ConVar.Create("my_convar", "hello world"); // You can also create a ConVar with a description ConVar.Create("another_convar", "default", "This is another convar."); // Get the value of a ConVar string value = ConVar.Get("my_convar"); Console.WriteLine($"The value of my_convar is: {value}"); // Set the value of a ConVar ConVar.Set("my_convar", "new value"); value = ConVar.Get("my_convar"); Console.WriteLine($"The new value of my_convar is: {value}"); } } } ``` -------------------------------- ### Spawn Entity with SpawnEntitySync Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/features/game-entities.md Create and spawn entities using SpawnEntitySync for better performance and code clarity. This example spawns a prop_dynamic with specified keyvalues. ```csharp var kv = new Dictionary { {"origin", pawn.GetAbsOrigin().ToString()}, {"angles", "0 90 0"}, {"model", "models/foo/bar.vmdl"}, {"spawnflags", 3}, {"disabled", true} }; if (_entityManager.SpawnEntitySync("prop_dynamic", kv) is { } entity) { entity.AcceptInput("Blabla"); } ``` -------------------------------- ### TraceNativeExample.cs Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/trace-native.md Example demonstrating native physics trace operations using PhysicsQueryManager. This native version offers engine-native exports and APIs but is more complex to use than the wrapper version. ```csharp using System; using Unity.Entities; using Unity.Physics; using Unity.Physics.Extensions; using Unity.Mathematics; public class TraceNativeExample : SystemBase { protected override void OnUpdate() { // Ensure we only run this once if (HasSingleton()) return; // Create a singleton to mark that we've run EntityManager.AddComponentData(SystemHandle, new TraceNativeExampleData()); // Get the PhysicsWorld from the World var physicsWorld = World.DefaultGameObjectInjectionWorld.GetExistingSystem().PhysicsWorld; // Define the ray var ray = new Ray { Origin = new float3(0, 5, 0), Direction = new float3(0, -1, 0) }; // Define the query var query = new Query { MaxDistance = 10.0f, Filter = CollisionFilter.Default }; // Perform the trace var hit = physicsWorld.Sphere .CastRay(ray, query); // Log the result if (hit.HasValue) { Console.WriteLine($"Hit at distance: {hit.Value.Fraction}"); } else { Console.WriteLine("No hit."); } // Example of a sphere cast var sphereCast = new Sphere { Center = new float3(0, 5, 0), Radius = 1.0f }; // Perform the sphere cast var sphereHit = physicsWorld.Sphere .Cast(sphereCast, ray, query); // Log the result if (sphereHit.HasValue) { Console.WriteLine($"Sphere hit at distance: {sphereHit.Value.Fraction}"); } else { Console.WriteLine("No sphere hit."); } // Example of a box cast var boxCast = new Box { Center = new float3(0, 5, 0), Orientation = quaternion.identity, Size = new float3(1, 1, 1) }; // Perform the box cast var boxHit = physicsWorld.Box .Cast(boxCast, ray, query); // Log the result if (boxHit.HasValue) { Console.WriteLine($"Box hit at distance: {boxHit.Value.Fraction}"); } else { Console.WriteLine("No box hit."); } // Example of a capsule cast var capsuleCast = new Capsule { AxisLocal = new float3(0, 1, 0), Center = new float3(0, 5, 0), Radius = 1.0f, Length = 1.0f }; // Perform the capsule cast var capsuleHit = physicsWorld.Capsule .Cast(capsuleCast, ray, query); // Log the result if (capsuleHit.HasValue) { Console.WriteLine($"Capsule hit at distance: {capsuleHit.Value.Fraction}"); } else { Console.WriteLine("No capsule hit."); } // Example of a mesh cast // Note: Mesh casting requires a Mesh component to be present on an entity. // This example assumes a mesh exists and is properly configured. // var meshCast = new Mesh // { // // ... mesh properties ... // }; // var meshHit = physicsWorld.Mesh.Cast(meshCast, ray, query); // if (meshHit.HasValue) // { // Console.WriteLine($"Mesh hit at distance: {meshHit.Value.Fraction}"); // } // else // { // Console.WriteLine("No mesh hit."); // } } } // Component to ensure the system runs only once public struct TraceNativeExampleData : IComponentData { } ``` -------------------------------- ### NetMessage Hook Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/net-message-hook.md Demonstrates how to set up and use a NetMessage hook in C# to intercept and potentially modify network messages. ```csharp using HarmonyLib; using System; using System.Reflection; namespace ModSharp.Examples { public class NetMessageHookExample { private static Harmony harmony; public static void Init() { harmony = new Harmony("com.example.netmessagehook"); harmony.PatchAll(Assembly.GetExecutingAssembly()); } public static void Shutdown() { harmony?.UnpatchSelf(); harmony = null; } } [HarmonyPatch] public static class NetMessagePatch { [HarmonyPrefix] [HarmonyPatch(typeof(NetMessage), nameof(NetMessage.Send))] // Example: Patching NetMessage.Send public static void Prefix_NetMessageSend(NetMessage __instance, ref bool __runOriginal) { // __runOriginal = false; // Uncomment to prevent the original method from running Console.WriteLine($"NetMessage.Send called. Message Type: {__instance.GetType().Name}"); // You can inspect or modify __instance here before it's sent } [HarmonyPostfix] [HarmonyPatch(typeof(NetMessage), nameof(NetMessage.Send))] // Example: Patching NetMessage.Send public static void Postfix_NetMessageSend(NetMessage __instance) { Console.WriteLine($"NetMessage.Send finished. Message Type: {__instance.GetType().Name}"); // You can inspect __instance after it has been sent } // Add more patches for other NetMessage methods or types as needed // For example, to patch a specific NetMessage subclass: /* [HarmonyPrefix] [HarmonyPatch(typeof(MyCustomNetMessage), nameof(MyCustomNetMessage.Deserialize))] public static void Prefix_MyCustomNetMessageDeserialize(MyCustomNetMessage __instance, BinaryReader reader) { Console.WriteLine("Deserializing MyCustomNetMessage..."); // Modify reader or __instance if needed } */ } } ``` -------------------------------- ### TransmitManager Example Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/transmit.md This C# snippet shows how to use TransmitManager. Ensure the TransmitManager class is accessible. ```csharp public class TransmitExample { public void BlockTeammateTransmit(string teammateId) { TransmitManager.Instance.BlockTransmit(teammateId); } } ``` -------------------------------- ### Localizer Example C# Code Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/localizer-manager.md This C# code snippet demonstrates how to use the localizer to retrieve localized strings. Ensure the locale-example.json file is correctly placed and configured. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Game.Sharp.Core.Localization; namespace Example.Sharp.Core.Localization { public class LocalizerExample { public static void Main(string[] args) { // Example usage of the Localizer // Assumes 'locale-example.json' is loaded and configured. // Simple string retrieval Console.WriteLine(Localizer.Instance.GetString("Generic.HelloWorld")); // Output: Test case A (if en-us is default) // String with parameter Console.WriteLine(Localizer.Instance.GetString("World", "ModSharp")); // Output: Phrase, Param A=ModSharp // String with formatted parameter (Time) Console.WriteLine(Localizer.Instance.GetString("Time", 123.456)); // Output: Time = 123.46 // String with formatted parameter (Date) Console.WriteLine(Localizer.Instance.GetString("Date", DateTime.Now)); // Output: Date is 10/26/2023 (or similar based on current date and default culture) // Example of retrieving a string that might not exist (returns key if not found) Console.WriteLine(Localizer.Instance.GetString("NonExistentKey", "DefaultValue")); } } } ``` -------------------------------- ### Configure gameinfo.gi for ModSharp Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/guides/getting-started.md Modify the gameinfo.gi file to include ModSharp in the search paths. This is similar to Metamod installation but uses a different path. ```diff // ...Ignore FileSystem { SearchPaths { Game_LowViolence csgo_lv // Perfect World content override + Game sharp Game csgo Game csgo_imported Game csgo_core Game core Mod csgo Mod csgo_imported Mod csgo_core AddonRoot csgo_addons OfficialAddonRoot csgo_community_addons LayeredGameRoot "../game_otherplatforms/etc" [$MOBILE || $ETC_TEXTURES] //Some platforms do not support DXT compression. ETC is a well-supported alternative. LayeredGameRoot "../game_otherplatforms/low_bitrate" [$MOBILE] } "UserSettingsPathID" "USRLOCAL" "UserSettingsFileEx" "cs2_" } // ...Ignore ``` -------------------------------- ### Native Hook Example with Marshalling Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/native-hook.md This C# code snippet demonstrates a native hook method signature that requires specific marshalling attributes for parameters and return values when RuntimeMarshalling is disabled. Ensure parameter types and the number of parameters match the target function. ```csharp [return: MarshalAs(UnmanagedType.I1)] private static unsafe bool Method([MarshalAs(UnmanagedType.I1)] bool argBool, byte* argPointer, int argInt32, long argInt64) { } ``` -------------------------------- ### Project Configuration (HelloWorld.xml) Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/hello-world.md This XML file configures the project's assembly name and references necessary shared components. Ensure 'AssemblyName' matches your project name. ```xml Example Example net6.0 enable enable ``` -------------------------------- ### Init and Shutdown Methods Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/guides/writing-a-module.md Implement `Init()` for module initialization and `Shutdown()` for cleanup when the module is unloaded. `Init()` must return a boolean, and can be simplified to `=> true;` if no specific logic is needed. `Shutdown()` can be an empty function. ```csharp public bool Init() => true; public void Shutdown() { } ``` -------------------------------- ### Get Module Assembly Name Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/configurations/admin.md Use this to define a stable module identity for programmatic integration. Ensure the assembly name is consistent. ```csharp private static readonly string ModuleIdentity = typeof(MyModule).Assembly.GetName().Name ?? "MyModule"; ``` -------------------------------- ### Basic .NET Project Configuration Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/guides/writing-a-module.md This is the default content of a .NET Class Library project's .csproj file. Ensure your TargetFramework is compatible with ModSharp. ```xml net10.0 disable enable ``` -------------------------------- ### Module Implementation (HelloWorld.cs) Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/hello-world.md This C# code defines the basic structure of a ModSharp plugin module, implementing the 'IMod' interface. It serves as the entry point for the plugin's logic. ```csharp using ModSharp.Sharp.Shared; namespace Example; public class HelloWorld : IMod { public void Start(IModHost host) { host.Log("Hello World!"); } } ``` -------------------------------- ### Configure Dependency Injection for Sharp Extension Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/writing-sharp-extensions.md Sets up Dependency Injection for the SharpExtension. This registers the extension with the DI container, making it available for use. ```csharp using Microsoft.Extensions.DependencyInjection; using ModSharp.Example.Extension.Api; using ModSharp.Example.Extension; namespace ModSharp.Example.Extension.Di { public static class SharpExtensionDi { public static IServiceCollection AddSharpExtension(this IServiceCollection services) { services.AddSingleton(); return services; } } } ``` -------------------------------- ### Add Root Admin Configuration Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/configurations/admin.md This JSON snippet shows how to configure a root administrator by replacing the placeholder with your SteamID64 in the `admins_simple.jsonc` file. ```json { "YOUR_STEAMID64_HERE": "root" } ``` -------------------------------- ### Use Entities as Dictionary Keys Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/features/game-entities.md Entities in ModSharp can be safely used as keys in collections like Dictionary and HashSet. This example shows adding an entity to a dictionary and retrieving it by handle. ```csharp var map = new Dictionary(); map.Add(entity, 1); var handle = entity.Handle; if (_entityManager.FindEntityByHandle(handle) is { } find) { if (map.TryGetValue(find, out var value)) { find.Health = value; } } ``` -------------------------------- ### Basic Module Structure Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/guides/writing-a-module.md This is the main entry point for a ModSharp module. It must inherit from `IModSharpModule`. Ensure only one class in a module inherits this interface to avoid unexpected behavior. ```csharp using Microsoft.Extensions.Configuration; using Sharp.Shared; namespace Example; public sealed class Example : IModSharpModule { public Example(ISharedSystem sharedSystem, string dllPath, string sharpPath, Version version, IConfiguration configuration, bool hotReload) { } public bool Init() { Console.WriteLine("Hello, World!"); return true; } public void Shutdown() { Console.WriteLine("Byebye, World!"); } public string DisplayName => "Example"; public string DisplayAuthor => "YourName"; } ``` -------------------------------- ### Module Constructor Parameters Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/guides/writing-a-module.md The module constructor must accept these specific parameters for successful initialization. Failure to do so will prevent the module from initializing. ```csharp public Example(ISharedSystem sharedSystem, string dllPath, string sharpPath, Version version, IConfiguration configuration, bool hotReload) { } ``` -------------------------------- ### Bootstrap cmkr and Regenerate CMakeLists.txt Source: https://github.com/kxnrl/modsharp-public/blob/master/Loader/CMakeLists.txt Includes the cmkr.cmake script if available and calls the cmkr() function to bootstrap the build system and regenerate CMakeLists.txt. This is typically done at the root of the project. ```cmake set(CMKR_ROOT_PROJECT OFF) if(CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set(CMKR_ROOT_PROJECT ON) # Bootstrap cmkr and automatically regenerate CMakeLists.txt include(cmkr.cmake OPTIONAL RESULT_VARIABLE CMKR_INCLUDE_RESULT) if(CMKR_INCLUDE_RESULT) cmkr() endif() # Enable folder support set_property(GLOBAL PROPERTY USE_FOLDERS ON) # Create a configure-time dependency on cmake.toml to improve IDE support configure_file(cmake.toml cmake.toml COPYONLY) endif() ``` -------------------------------- ### Build Admin Manifest with External Data Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/admin-example.md This snippet shows how to build an AdminTableManifest by fetching permissions, roles, and admins from external sources using a request manager. Leave permissions and roles empty if they are defined elsewhere. ```csharp private AdminTableManifest BuildAdminManifest() { // 1. Permissions & Roles: // OR leave these empty if you are using roles/permissions defined elsewhere. Dictionary> myPermissions = _requestManager.GetPermissions(); List myRoles = _requestManager.GetRoles(); // 2. Admins: // Fetch admins from your database List myAdmins = _requestManager.GetAdmins(); return new AdminTableManifest(myPermissions, myRoles, myAdmins); } ``` -------------------------------- ### Default Logging Templates Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/configurations/core.md Specifies the formatting for logs output to the console and log files. Uses Serilog formatting placeholders. ```json "Template": { "File": "[{Timestamp:yyyy/MM/dd HH:mm:ss.fff}] | {Level} | {SourceContext}{Scope} {MapName} {NewLine}{Message:lj}{NewLine}{Exception}{NewLine}", "Console": "[{Timestamp:MM/dd HH:mm:ss}] | {Level} | {SourceContext}{Scope} {MapName} {NewLine}{Message:lj}{NewLine}{Exception}{NewLine}" } ``` -------------------------------- ### Implement the Sharp Extension Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/examples/writing-sharp-extensions.md Provides a basic implementation of the ISharpExtension interface. This class contains the core logic for your extension. ```csharp using ModSharp.Example.Extension.Api; namespace ModSharp.Example.Extension { public class SharpExtension : ISharpExtension { public string Name => "Example Extension"; public string Version => "1.0.0"; public void Initialize() { // Extension initialization logic here Console.WriteLine($"{Name} v{Version} initialized."); } } } ``` -------------------------------- ### Create and Broadcast Game Event Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/features/game-events.md Creates a game event, sets player and weapon properties, and broadcasts it to all clients. Use this for general event broadcasting. ```csharp if (_eventManager.CreateEvent("weapon_fire", false) is { } e) { e.SetPlayer("userid", pawn); e.SetString("weapon", "hh,nm"); e.Fire(); // Fire event and broadcast to all clients } ``` -------------------------------- ### Default Client Preferences Connection String Source: https://github.com/kxnrl/modsharp-public/blob/master/docfx/docs/en-us/configurations/client-preferences.md This snippet shows the default configuration for client preferences, utilizing the 'litedb' schema with a local file path. It's suitable for local development or single-server instances. ```json "ConnectionStrings": { // ... others "ClientPreferences": "litedb://Filename={sharp::data}/client-preferences.db;Mode=Exclusive;Flush=true" } ```