### ImGui UI Integration Example Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/examples/imgui-ui.md This C# code snippet shows the main program setup for integrating ImGui with Stride. It includes necessary using directives and the main application entry point. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Stride.Core; using Stride.Core.Mathematics; using Stride.Engine; using Stride.Games; using Hexa.NET.ImGui; namespace Example11_ImGui { class Program { static void Main(string[] args) { using (var game = new Game()) { game.Run(new MyGameSync()); } } } public class MyGameSync : SyncScript { private ImGuiRenderer _imGuiRenderer; public override void Start() { // Initialize ImGui renderer _imGuiRenderer = new ImGuiRenderer(Services.GetService().GraphicsDevice); _imGuiRenderer.Initialize(Window); // Set ImGui style ImGui.StyleColorsDark(); } public override void Update() { // Handle ImGui input and rendering _imGuiRenderer.Window = Window; _imGuiRenderer.BeginLayout(); // Example: Draw a simple ImGui window ImGui.Begin("My First ImGui Window"); ImGui.Text("Hello, ImGui!"); ImGui.End(); _imGuiRenderer.EndLayout(); } } } ``` -------------------------------- ### Running Examples via .NET CLI Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/examples/code-only/README.md Examples can be executed directly from the command line using the 'dotnet run' command, specifying the project path. ```bash dotnet run --project path/to/example/Example.csproj ``` -------------------------------- ### F# Capsule with Rigid Body Setup Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/examples/capsule-with-rigid-body-fs.md Initializes a Stride game, sets up a basic 3D scene with a skybox, adds a capsule primitive, and positions it in the scene. This snippet is the entry point for the F# example. ```fsharp let game = new Game() let Start rootScene = game.SetupBase3DScene() game.AddSkybox() game.AddProfiler() |> ignore let firstBox = game.Create3DPrimitive(PrimitiveModelType.Capsule) firstBox.Transform.Position <- new Vector3(0f, 2.5f, 0f) firstBox.Scene <- rootScene [] let main argv = game.Run(start = Start) 0 ``` -------------------------------- ### Add Example Metadata to Project File Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/contributing/examples/index.md Add these XML elements to your example's *.csproj file to register it with the console application menu. Ensure `` is set to `true` for it to appear. ```xml Basic Example - Capsule with rigid body 100 true 1 - Basic Example ``` -------------------------------- ### Basic ImGui.NET Setup and Usage Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/src/Stride.CommunityToolkit.ImGuiNet/README.md Initializes the ImGui.NET system and demonstrates drawing text at screen and world coordinates. ```csharp using Stride.CommunityToolkit.Engine; using Stride.CommunityToolkit.ImGuiNet; using Stride.Core.Mathematics; using Stride.Engine; using var game = new Game(); ImGuiNetSystem? imguiSystem = null; game.Run(start: Start, update: Update); void Start(Scene scene) { game.SetupBase3DScene(); // Initialize ImGui.NET system imguiSystem = game.AddImGuiNet(); } void Update(Scene scene, GameTime gameTime) { // Draw text at screen coordinates (like Box2D.NET) imguiSystem?.DrawString(10, 10, "Hello, ImGui.NET!"); // Draw text at world coordinates imguiSystem?.DrawString(Vector3.Zero, "World Text"); } ``` -------------------------------- ### Run Examples Launcher Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/tools/Stride.CommunityToolkit.Examples.Launcher/README.md Navigate to the launcher's directory and execute the application using the .NET CLI. This command initiates the launcher interface. ```bash cd src/Stride.CommunityToolkit.Examples.Launcher dotnet run ``` -------------------------------- ### Program.cs - Cube Clicker Example Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/examples/stride-ui-cube-clicker.md This C# code is the main entry point for the Cube Clicker example. It sets up the game, loads data, and initializes the UI. It demonstrates game data management using NexVYaml and Stride UI. ```csharp using NexVYaml; using Stride.Core; using Stride.Core.Mathematics; using Stride.Engine; using Stride.Games; using Stride.UI; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace Example07_CubeClicker { public class Program { public static async Task Main(string[] args) { using (var game = new Game()) { game.Window.Title = "Cube Clicker"; game.Run(async () => { // Load game data var gameData = await LoadGameData(); // Create UI var ui = new UIManager(game.Services, gameData); game.Services.AddService(ui); // Create game logic script var gameLogic = new GameLogic(ui, gameData); game.Add(gameLogic); // Create cube spawner script var cubeSpawner = new CubeSpawner(ui, gameData); game.Add(cubeSpawner); }); } } private static async Task LoadGameData() { var serializer = new YamlSerializer(); var dataPath = "GameData.yml"; if (File.Exists(dataPath)) { using (var stream = File.OpenRead(dataPath)) { return await serializer.DeserializeAsync(stream); } } else { return new GameData(); } } } public class UIManager { private readonly GameData _gameData; private readonly TextBlock _clicksTextBlock; private readonly TextBlock _cubesTextBlock; private readonly Grid _cubeGrid; public UIManager(IServiceRegistry services, GameData gameData) { _gameData = gameData; var uiManager = services.Get(); var uiScene = new Scene("UI Scene"); var rootElement = new Grid() { RootElement = uiScene.Root }; // Create UI elements _clicksTextBlock = new TextBlock() { Text = "Clicks: 0", HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(10) }; rootElement.Children.Add(_clicksTextBlock); _cubesTextBlock = new TextBlock() { Text = "Cubes: 0", HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top, Margin = new Thickness(10, 40) }; rootElement.Children.Add(_cubesTextBlock); _cubeGrid = new Grid() { Width = 400, Height = 400, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Background = Color.Gray }; rootElement.Children.Add(_cubeGrid); uiManager.RootElement = rootElement; } public void UpdateClicks(int clicks) { _clicksTextBlock.Text = $"Clicks: {clicks}"; } public void UpdateCubes(int cubes) { _cubesTextBlock.Text = $"Cubes: {cubes}"; } public void AddCube(Entity cubeEntity) { _cubeGrid.Children.Add(new ImageElement() { Source = cubeEntity.Get()?.Texture, Width = 50, Height = 50 }); } } public class GameData { public int Clicks { get; set; } = 0; public List CubePositions { get; set; } = new List(); } public class GameLogic : SyncScript { private readonly UIManager _uiManager; private readonly GameData _gameData; private readonly YamlSerializer _serializer = new YamlSerializer(); public GameLogic(UIManager uiManager, GameData gameData) { _uiManager = uiManager; _gameData = gameData; } public override void Start() { _uiManager.UpdateClicks(_gameData.Clicks); _uiManager.UpdateCubes(_gameData.CubePositions.Count); } public override void Update() { // Handle mouse clicks if (Input.IsMouseButtonPressed(MouseButton.Left)) { _gameData.Clicks++; _uiManager.UpdateClicks(_gameData.Clicks); } else if (Input.IsMouseButtonPressed(MouseButton.Right)) { // Right click could be used for something else, e.g., removing a cube } } public override Task DisposeAsync() { // Save game data on exit using (var stream = File.OpenWrite("GameData.yml")) { _serializer.Serialize(stream, _gameData); } return Task.CompletedTask; } } public class CubeSpawner : SyncScript { private readonly UIManager _uiManager; private readonly GameData _gameData; private float _spawnTimer = 0f; private const float SpawnInterval = 2.0f; public CubeSpawner(UIManager uiManager, GameData gameData) { _uiManager = uiManager; _gameData = gameData; } public override void Update() { _spawnTimer += (float)Game.UpdateTime.Elapsed.TotalSeconds; if (_spawnTimer >= SpawnInterval) { SpawnCube(); _spawnTimer = 0f; } } private void SpawnCube() { // Create a new cube entity var cubeEntity = new Entity("Cube") { new UIImageComponent() { // Placeholder for actual cube texture Texture = Content.Load("icon") } }; // Assign a random position within the UI grid bounds var random = new Random(); var x = random.Next(0, (int)_uiManager._cubeGrid.Width - 50); var y = random.Next(0, (int)_uiManager._cubeGrid.Height - 50); // Note: Stride UI uses a different coordinate system, this is a simplification. // For actual positioning, you'd need to map UI coordinates. var position = new Vector3(x, y, 0); _gameData.CubePositions.Add(position); _uiManager.AddCube(cubeEntity); _uiManager.UpdateCubes(_gameData.CubePositions.Count); } } } ``` -------------------------------- ### Generate Command Usage Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/tools/Stride.CommunityToolkit.Examples.MetadataGenerator/README.md Shows how to use the 'generate' command to create a JSON manifest file from example metadata. The command requires the root path of the examples. ```bash MetadataGenerator generate "../../examples/code-only" # or dotnet run -- generate "../../examples/code-only" ``` -------------------------------- ### Scan Command Usage Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/tools/Stride.CommunityToolkit.Examples.MetadataGenerator/README.md Demonstrates how to use the 'scan' command to discover metadata in example directories. The command takes the root path of the examples as an argument. ```bash MetadataGenerator scan "../../examples/code-only" # or dotnet run -- scan "../../examples/code-only" ``` -------------------------------- ### Verify .NET SDK Installation Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/getting-started.md Run this command in your terminal to check if the .NET SDK is installed and to view its version information. ```bash dotnet --info ``` -------------------------------- ### Initialize ImGuiSystem Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/src/Stride.CommunityToolkit.ImGui/README.md Start ImGui within your game's BeginRun() method by creating an instance of ImGuiSystem. ```csharp using Stride.CommunityToolkit.ImGuiDebug; protected override void BeginRun() { base.BeginRun(); new ImGuiSystem( Services, GraphicsDeviceManager ); } ``` -------------------------------- ### Install DocFX Globally Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/contributing/documentation/index.md Installs the latest version of DocFX as a global tool using the .NET CLI. This is a prerequisite for building the documentation. ```bash dotnet tool install -g docfx ``` -------------------------------- ### Initialize and Run Game in Visual Basic Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/examples/capsule-with-rigid-body-vb.md Initializes a new Stride game instance and starts the game loop, calling the specified start method. ```vb Private game As New Game() GameExtensions.Run(game, Nothing, AddressOf StartGame) ``` -------------------------------- ### Draggable Window UI Example (C#) Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/examples/stride-ui-draggable-window.md This C# code implements a draggable window system within Stride UI. It includes functionality for creating new windows, generating 3D objects, and managing the UI state. Ensure you have the necessary Stride packages installed. ```csharp using System; using System.Collections.Generic; using System.Linq; using Stride.Core; using Stride.Core.Mathematics; using Stride.Engine; using Stride.Games; using Stride.Graphics; using Stride.Input; using Stride.UI; using Stride.UI.Controls; using Stride.UI.Events; namespace Example10_StrideUI_DragAndDrop { public class Program : AsyncGame { private UIManager uiManager; private PrimitiveGenerator primitiveGenerator; private DragAndDropContainer dragAndDropContainer; public Program() { // Use headless graphics device to avoid the need for a graphics adapter GraphicsDeviceManager.PreferredGraphicsProfile = new GraphicsProfile(new FeatureLevel[] { FeatureLevel.Level_11_0 }); } protected override async Task LoadContent(){ // Load UI package Services.AddService(new UIManager(this)); Services.AddService(new PrimitiveGenerator(this)); Services.AddService(new DragAndDropContainer(this)); uiManager = Services.GetService(); primitiveGenerator = Services.GetService(); dragAndDropContainer = Services.GetService(); // Load UI await uiManager.LoadUI("UI/UIManager"); await dragAndDropContainer.LoadUI("UI/DragAndDropContainer"); return Task.CompletedTask; } protected override void Update(GameTime gameTime) { // Update UI manager uiManager.Update(gameTime); primitiveGenerator.Update(gameTime); dragAndDropContainer.Update(gameTime); // Handle input var input = Services.GetService(); if (input.IsKeyReleased(Keys.Escape)) { Exit(); } } } public class UIManager { private Game _game; private Scene _scene; private TextBlock _objectCountTextBlock; private int _objectCount; public UIManager(Game game) { _game = game; _scene = game.Scene; } public async Task LoadUI(string url) { var uiPackage = await _game.Content.LoadAsync(url); var uiLayout = uiPackage.RootElement; _objectCountTextBlock = uiLayout.FindName("ObjectCountTextBlock") as TextBlock; _game.GraphicsPresenter.RootWindow.UIElement.Children.Add(uiLayout); } public void Update(GameTime gameTime) { if (_objectCountTextBlock != null) { _objectCountTextBlock.Text = "Objects: " + _objectCount; } } public void IncrementObjectCount() { _objectCount++; } public void DecrementObjectCount() { _objectCount--; } } public class DragAndDropContainer { private Game _game; private Scene _scene; private Canvas _dragAndDropCanvas; private int _windowCount; public DragAndDropContainer(Game game) { _game = game; _scene = game.Scene; } public async Task LoadUI(string url) { var uiPackage = await _game.Content.LoadAsync(url); _dragAndDropCanvas = uiPackage.RootElement as Canvas; _game.GraphicsPresenter.RootWindow.UIElement.Children.Add(_dragAndDropCanvas); // Find the main window and attach event handlers var mainWindow = _dragAndDropCanvas.FindName("MainWindow") as DragAndDropCanvas; if (mainWindow != null) { mainWindow.OnCloseClicked += HandleCloseClicked; mainWindow.OnObjectGenerated += HandleObjectGenerated; mainWindow.OnObjectRemoved += HandleObjectRemoved; } } public void Update(GameTime gameTime) { // Update all draggable canvases foreach (var canvas in _dragAndDropCanvas.Children.OfType()) { canvas.Update(gameTime); } } private void HandleCloseClicked(DragAndDropCanvas sender) { _dragAndDropCanvas.Children.Remove(sender); sender.OnCloseClicked -= HandleCloseClicked; sender.OnObjectGenerated -= HandleObjectGenerated; sender.OnObjectRemoved -= HandleObjectRemoved; } private void HandleObjectGenerated(DragAndDropCanvas sender) { var primitiveGenerator = _game.Services.GetService(); primitiveGenerator.GeneratePrimitive(sender.Position + new Vector3(0, 50, 0)); } private void HandleObjectRemoved(DragAndDropCanvas sender) { var uiManager = _game.Services.GetService(); uiManager.DecrementObjectCount(); } public void CreateNewWindow() { _windowCount++; var newWindow = new DragAndDropCanvas($"New Window {_windowCount}"); newWindow.Position = new Vector3(100 + (_windowCount * 20), 100 + (_windowCount * 20), 0); newWindow.OnCloseClicked += HandleCloseClicked; newWindow.OnObjectGenerated += HandleObjectGenerated; newWindow.OnObjectRemoved += HandleObjectRemoved; _dragAndDropCanvas.Children.Add(newWindow); } } public class DragAndDropCanvas : Canvas { public event Action OnCloseClicked; public event Action OnObjectGenerated; public event Action OnObjectRemoved; private const float TitleBarHeight = 30; private const float DividerLineHeight = 1; private const float CloseButtonSize = 20; private Image _closeButton; private TextBlock _titleTextBlock; private Grid _contentGrid; private bool _isDragging; private Vector2 _dragOffset; private float _lastZ; public DragAndDropCanvas(string title) { // Create UI elements _titleTextBlock = new TextBlock { Text = title, VerticalAlignment = Stride.UI.VerticalAlignment.Center, HorizontalAlignment = Stride.UI.HorizontalAlignment.Center }; _closeButton = new Image { Source = new Sprite(null), Width = CloseButtonSize, Height = CloseButtonSize, HorizontalAlignment = Stride.UI.HorizontalAlignment.Right, VerticalAlignment = Stride.UI.VerticalAlignment.Center }; _contentGrid = new Grid { RowDefinitions = { new Grid.RowDefinition(GridLength.Star) }, ColumnDefinitions = { new Grid.ColumnDefinition(GridLength.Star) } }; // Add elements to the canvas Children.Add(_titleTextBlock); Children.Add(_closeButton); Children.Add(_contentGrid); // Set initial properties Width = 300; Height = 200; Background = new Color(50, 50, 50, 200); // Attach event handlers MouseDown += OnMouseDown; MouseMove += OnMouseMove; MouseUp += OnMouseUp; _closeButton.MouseDown += OnCloseButtonMouseDown; // Add a divider line var divider = new Border { Background = Color.Gray, Height = DividerLineHeight }; Children.Add(divider); } public Vector3 Position { get; set; } public void Update(GameTime gameTime) { // Update title bar position _titleTextBlock.Position = new Vector3(Width / 2 - _titleTextBlock.ActualWidth / 2, 0, 0); _closeButton.Position = new Vector3(Width - CloseButtonSize - 5, 0, 0); // Update divider line position var divider = Children.OfType().FirstOrDefault(); if (divider != null) { divider.Width = Width; divider.Position = new Vector3(0, TitleBarHeight, 0); } // Update content grid position _contentGrid.Width = Width; _contentGrid.Height = Height - TitleBarHeight - DividerLineHeight; _contentGrid.Position = new Vector3(0, TitleBarHeight + DividerLineHeight, 0); } private void OnMouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButton.Left) { _isDragging = true; _dragOffset = new Vector2(e.Position.X, e.Position.Y); _lastZ = Z; // Bring window to front BringToFront(); } } private void OnMouseMove(object sender, MouseEventArgs e) { if (_isDragging) { Position = new Vector3(Position.X + e.Position.X - _dragOffset.X, Position.Y + e.Position.Y - _dragOffset.Y, Position.Z); _dragOffset = e.Position; } } private void OnMouseUp(object sender, MouseEventArgs e) { if (_isDragging) { _isDragging = false; } } private void OnCloseButtonMouseDown(object sender, MouseEventArgs e) { OnCloseClicked?.Invoke(this); e.Handled = true; // Prevent drag event } public void BringToFront() { var parent = Parent as Canvas; if (parent != null) { // Find the highest Z index among siblings float maxZ = 0; foreach (var child in parent.Children.OfType()) { if (child != this && child.Z > maxZ) { maxZ = child.Z; } } Z = maxZ + 1; } } // Add a button to generate a primitive public void AddGenerateButton(Action onClick) { var button = new Button { Text = "Generate Primitive" }; button.Click += (sender, e) => onClick(this); _contentGrid.Children.Add(button); } // Add a button to close the window public void AddCloseButton(Action onClick) { var button = new Button { Text = "Close Window" }; button.Click += (sender, e) => onClick(this); _contentGrid.Children.Add(button); } } public class PrimitiveGenerator { private Game _game; private Scene _scene; private List _generatedObjects; public PrimitiveGenerator(Game game) { _game = game; _scene = game.Scene; _generatedObjects = new List(); } public void Update(GameTime gameTime) { // Remove objects that fall below a certain threshold var objectsToRemove = _generatedObjects.Where(obj => obj.Transform.Position.Y < -100).ToList(); foreach (var obj in objectsToRemove) { _scene.Entities.Remove(obj); _generatedObjects.Remove(obj); var uiManager = _game.Services.GetService(); uiManager.DecrementObjectCount(); } } public void GeneratePrimitive(Vector3 position) { var entity = new Entity("GeneratedPrimitive") { Transform = { Position = position }, }; // Add a sphere shape var shape = Stride.Rendering.ShapeGenerator.GenerateSphere(1.0f); entity.Add(new Stride.Rendering.MeshRendererComponent { Model = Stride.Rendering.Model.New(shape.ToMeshDraw()) }); // Add physics component (optional) // entity.Add(new RigidBodyComponent { Mass = 1.0f, LinearDamping = 0.1f, AngularDamping = 0.1f }); _scene.Entities.Add(entity); _generatedObjects.Add(entity); var uiManager = _game.Services.GetService(); uiManager.IncrementObjectCount(); } } } ``` -------------------------------- ### Example Metadata Structure Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/examples/code-only/README.md This YAML structure is used to provide metadata for each example, including title, level, category, complexity, description, concepts, tags, order, and creation date. ```yaml /* ---example-metadata title: en: Example Title cs: Název příkladu level: Beginners category: Physics complexity: 4 description: en: | English description of what the example demonstrates cs: | Czech description of what the example demonstrates concepts: - First concept demonstrated - Second concept demonstrated related: - RelatedExample1 - RelatedExample2 tags: - Tag1 - Tag2 order: 1 enabled: true created: 2025-12-13 --- ``` -------------------------------- ### Setup Basic 3D Scene and Add Elements in Visual Basic Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/examples/capsule-with-rigid-body-vb.md Sets up a basic 3D scene, adds a skybox for background, and includes a profiler for performance monitoring. ```vb game.SetupBase3DScene() game.AddSkybox() game.AddProfiler() ``` -------------------------------- ### Create a new .NET Console App Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/create-project.md Use this command to create a new console application project. Ensure you have the .NET SDK installed. ```bash dotnet new console --framework net10.0 --name YourProjectName ``` -------------------------------- ### Instancing Entity Transform Setup Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/examples/code-only/Example_Bepu_Playground/FINAL_INSTANCING_SOLUTION.md This code snippet shows how to configure the instancing system to track entity-based instances rather than manual matrices. It's crucial for enabling the master-instance pattern. ```csharp masterInstancing.Type = new InstancingEntityTransform(); // Not InstancingUserArray! ``` -------------------------------- ### DI-Integrated Command Handler Setup Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/tools/Stride.CommunityToolkit.Examples.MetadataGenerator/README.md Sets up the DI container and registers a scoped service for command handling. Constructor injection is used for CLI configuration. ```csharp var builder = Host.CreateApplicationBuilder(args); builder.Services.AddScoped(); using var host = builder.Build(); // Constructor injection for CLI configuration var cliConfiguration = new CommandLineConfiguration(host.Services); var rootCommand = cliConfiguration.CreateRootCommand(); var parseResult = rootCommand.Parse(args); return parseResult.Invoke(); ``` -------------------------------- ### Basic Stride Game Initialization Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/create-project.md This C# code demonstrates the basic setup for a Stride game application, including scene creation, entity instantiation, and physics integration. It requires the Stride.CommunityToolkit packages. ```csharp using Stride.CommunityToolkit.Bepu; using Stride.CommunityToolkit.Engine; using Stride.CommunityToolkit.Rendering.ProceduralModels; using Stride.Core.Mathematics; using Stride.Engine; using var game = new Game(); game.Run(start: Start); void Start(Scene rootScene) { game.SetupBase3DScene(); var entity = game.Create3DPrimitive(PrimitiveModelType.Capsule); entity.Transform.Position = new Vector3(0, 8, 0); entity.Scene = rootScene; } ``` -------------------------------- ### Add Stride Community Toolkit Package Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/create-project.md Installs the Windows-specific Stride Community Toolkit package. Use `--prerelease` for the latest pre-release version. ```bash dotnet add package Stride.CommunityToolkit.Windows --prerelease ``` -------------------------------- ### Initialize and Configure Box2D Physics World Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/examples/box2d-physics.md Sets up a reusable 2D physics world and bridges it to Stride entities. Ensure the Box2D.NET NuGet package is installed. ```csharp using System; using System.Numerics; using Stride.Core; using Stride.Core.Mathematics; using Stride.Engine; using Stride.Games; using Box2D.NetStandard.Collision.Shapes; using Box2D.NetStandard.Dynamics.World; using Box2D.NetStandard.Dynamics.Bodies; using Box2D.NetStandard.Dynamics.Contacts; namespace Example18_Box2DPhysics.Scenes { public class PhysicsScene : SyncScript { public override void Start() { // Initialize the physics world var gravity = new Vector2(0.0f, -9.81f); var physicsWorld = new World(gravity); // Create a static ground body var groundBodyDesc = new BodyDesc() { Type = BodyType.Static, Position = new Vector2(0.0f, -10.0f), Rotation = 0.0f, FixedRotation = true, UserData = "Ground" }; var groundBody = physicsWorld.CreateBody(groundBodyDesc); groundBody.CreateFixture(new PolygonShape(20.0f, 1.0f)); // Create a dynamic box body var boxBodyDesc = new BodyDesc() { Type = BodyType.Dynamic, Position = new Vector2(0.0f, 5.0f), Rotation = 0.0f, FixedRotation = false, UserData = "Box" }; var boxBody = physicsWorld.CreateBody(boxBodyDesc); boxBody.CreateFixture(new PolygonShape(1.0f, 1.0f), 1.0f); // Store the physics world for later use (e.g., in other scripts or systems) Entity.Add(new PhysicsWorldComponent { World = physicsWorld }); } public override void Update() { // Fixed time step for physics simulation var physicsWorldComponent = Entity.Get(); if (physicsWorldComponent != null) { var deltaTime = (float)Game.TargetElapsedTime.TotalSeconds; physicsWorldComponent.World.Step(deltaTime, 8, 3); // Synchronize entity transforms from physics bodies foreach (var body in physicsWorldComponent.World.BodyList) { if (body.UserData is string name) { var entity = Scene.Entities.GetChild(name); if (entity != null) { var transform = entity.Transform; var position = body.Position; var rotation = body.Rotation; transform.Position = new Vector3(position.X, position.Y, transform.Position.Z); transform.Rotation = Quaternion.RotationZ(rotation); } } } } } } // Component to hold the physics world public class PhysicsWorldComponent : Component { public World World; } } ``` -------------------------------- ### Implement Custom ImGui Window Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/src/Stride.CommunityToolkit.ImGui/README.md Implement a custom ImGui window by inheriting from BaseWindow and overriding the OnDraw method. This example shows how to create menus, color pickers, plots, and child windows. ```csharp using System.Numerics; using static Hexa.NET.ImGui.ImGui; using static Stride.CommunityToolkit.ImGuiDebug.ImGuiExtension; public class YourInterface : Stride.CommunityToolkit.ImGuiDebug.BaseWindow { bool my_tool_active; Vector4 my_color; float[] my_values = { 0.2f, 0.1f, 1.0f, 0.5f, 0.9f, 2.2f }; public YourInterface( Stride.Core.IServiceRegistry services ) : base( services ) { } protected override void OnDestroy() { } protected override void OnDraw( bool collapsed ) { if( collapsed ) return; if( BeginMenuBar() ) { if( BeginMenu( "File" ) ) { if( MenuItem( "Open..", "Ctrl+O" ) ) { /* Do stuff */ } if( MenuItem( "Save", "Ctrl+S" ) ) { /* Do stuff */ } if( MenuItem( "Close", "Ctrl+W" ) ) { my_tool_active = false; } EndMenu(); } EndMenuBar(); } // Edit a color (stored as ~4 floats) ColorEdit4( "Color", ref my_color ); // Plot some values PlotLines( "Frame Times", ref my_values[ 0 ], my_values.Length ); // Display contents in a scrolling region TextColored( new Vector4( 1, 1, 0, 1 ), "Important Stuff" ); using( Child() ) { for( int n = 0; n < 50; n++ ) Text( $"{n}: Some text" ); } } } ``` -------------------------------- ### Setup Debug Shapes in Stride Scene Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/examples/debug-shapes.md This C# code sets up a basic 3D scene and adds debugging visuals. A special entity with a ShapeUpdater component is added to update and render debug shapes in the scene, making it easier to visualize spatial information during development. Ensure you have the necessary additional packages installed. ```csharp using Stride.Core.Mathematics; using Stride.Engine; using Stride.Games; using Stride.Rendering.Compositing; namespace Example08_DebugShapes.Game { public class DebugShapes : SyncScript { public override void Start() { // Create a new entity var entity = new Entity("Debug Shapes Entity"); // Add a ShapeUpdater component to the entity // This component is responsible for updating and rendering debug shapes entity.Add(new ShapeUpdater()); // Add the entity to the scene entity.Scene = this.Entity.Scene; } } } ``` -------------------------------- ### C# Program Setup for Capsule and UI Window Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/examples/stride-ui-capsule-with-rigid-body.md This is the main entry point for setting up the scene. It orchestrates the creation of the 3D environment, including adding a capsule with a rigid body and a UI window. Ensure all necessary packages are included. ```csharp using Stride.Core.Mathematics; using Stride.Engine; using Stride.Games; using Stride.Graphics; using Stride.UI; using Stride.UI.Controls; namespace Example03_StrideUI_CapsuleAndWindow { public class Program : SyncScript { public override void Start() { // Entry point for the scene setup var scene = new Scene(); // Add a 3D capsule with a rigid body to the scene AddCapsule(scene); // Load the font for the UI window LoadFont(); // Add a UI window to the scene AddWindow(scene); // Assign the scene to the game Game.LoadScene(scene); } private void AddCapsule(Scene scene) { // Create a new entity for the capsule var capsuleEntity = new Entity("Capsule") { // Position the capsule in the scene Transform = { Position = new Vector3(0, 5, 0) } }; // Add a shape component for the capsule var shape = new Stride.Physics.CapsuleShape(1.0f, 1.0f); capsuleEntity.Add(new Stride.Physics.ColliderShape(shape)); // Add a rigid body component to enable physics simulation var rigidBody = new Stride.Physics.RigidBodyComponent { // Set mass and friction properties Mass = 1.0f, Friction = 0.5f }; capsuleEntity.Add(rigidBody); // Add the capsule entity to the scene scene.Entities.Add(capsuleEntity); } private void LoadFont() { // Load the default sprite font for UI text // Ensure 'Resources/Fonts/default.xnb' exists in your project // This path might need adjustment based on your project structure SpriteFont = Content.Load("Fonts/default"); } private void AddWindow(Scene scene) { // Create a UI entity with a canvas var uiEntity = CreateUIEntity(); // Add the UI entity to the root scene scene.Entities.Add(uiEntity); } private Entity CreateUIEntity() { // Create a new entity to hold the UI components var uiEntity = new Entity("UI Entity") { // Position the UI entity Transform = { Position = new Vector3(0, 0, 0) } }; // Create the root canvas for the UI var canvas = CreateCanvas(); uiEntity.Add(canvas); return uiEntity; } private Canvas CreateCanvas() { // Create a new canvas element var canvas = new Canvas() { // Set the canvas size to fill the screen WidthSizePolicy = UILayout.Fill, HeightSizePolicy = UILayout.Fill }; // Create a text block to display a message var textBlock = CreateTextBlock(SpriteFont); canvas.Children.Add(textBlock); return canvas; } private TextBlock CreateTextBlock(SpriteFont font) { // Create a TextBlock element var textBlock = new TextBlock() { // Set the text content Text = "Hello, World", // Set the font to be used Font = font, // Set the text color to white TextColor = Color.White, // Set the horizontal alignment to center HorizontalAlignment = HorizontalAlignment.Center, // Set the vertical alignment to center VerticalAlignment = VerticalAlignment.Center, // Set the font size FontSize = 32 }; return textBlock; } // SpriteFont is a property that needs to be defined or passed in // For simplicity, assuming it's accessible here private SpriteFont SpriteFont; } } ``` -------------------------------- ### Preview Documentation Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/contributing/documentation/index.md Opens the locally built documentation site in a web browser. The default port is 8080. ```bash http://localhost:8080/ ``` -------------------------------- ### Build Documentation Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/contributing/documentation/index.md Executes the 'run.bat' script to build the project's documentation. This command should be run from the 'docs' directory. ```bash run.bat ``` -------------------------------- ### Error MSB3073: Command Exited with Code -532462766 Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/troubleshooting.md This error indicates a missing native library, likely due to not installing the Microsoft Visual C++ Redistributable. Ensure prerequisites are installed. ```msbuild C:\Users\Vacla\.nuget\packages\stride.core.assets.compilerapp\4.1.0.1728\buildTransitive\Stride.Core.Assets.CompilerApp.targets(132,5): error MSB3073: The command ""C:\Users\Vacla\.nuget\packages\stride.core.assets.compilerapp\4.1.0.1728\buildTransitive\..\tools\net6.0-windows7.0\Stride.Core.Assets.CompilerApp.exe" --disable-auto- compile --project-configuration "Debug" --platform=Windows --project-configuration=Debug --compile-property:StrideGraphicsApi=Direct3D11 --output-path="C:\Projects\StrideDemo\bin\Debug\net6.0\data" --build-path="C:\Projects\StrideDemo\obj\stride\assetbuild\data" --package-file="C:\Projects\StrideDemo\StrideDemo.csproj" --msbuild-up todatecheck-filebase="C:\Projects\StrideDemo\obj\Debug\net6.0\stride\assetcompiler-uptodatecheck"" exited with code -532462766. [C:\Projects\StrideDemo\StrideDemo.csproj] ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/create-project.md Change the current directory to your newly created project folder. ```bash cd YourProjectName ``` -------------------------------- ### GetFirstCamera Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/script-extensions/index.md Gets the first camera from the GraphicsCompositor. ```APIDOC ## GetFirstCamera ### Description Gets the first camera from the `GraphicsCompositor`. ### Method `GetFirstCamera(ScriptComponent)` ### Parameters #### Path Parameters - **scriptComponent** (ScriptComponent) - Required - The script component to get the camera from. ### Response #### Success Response (CameraComponent) - Returns the first `CameraComponent` found in the `GraphicsCompositor`. ``` -------------------------------- ### WorldPosition Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/entity-extensions/index.md An easier way to get world position. ```APIDOC ## WorldPosition ### Description An easier way to get world position. ### Method Extension Method ### Endpoint N/A (Extension Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response N/A #### Response Example N/A ``` -------------------------------- ### Myra UI Initialization and Service Retrieval Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/examples/myra-ui-draggable-window-and-services.md Sets up the Myra UI manager and demonstrates retrieving services dynamically. Ensure Myra is correctly configured before use. ```csharp using System; using System.Threading.Tasks; using Myra.Graphics.UI; using Stride.Core.Mathematics; using Stride.Engine; namespace Example04_MyraUI { public class Program : Game { private readonly Activity _activity; public Program() { // Graphics device creation Graphics.PreferredBackBufferWidth = 1920; Graphics.PreferredBackBufferHeight = 1080; // Setup the activity to load the game scene _activity = new Activity(); // Initialize Myra UI Myra.MyraManager.Instance.Initialize(this); } protected override async Task LoadContent() { await _activity.LoadContent(Services); // Example of retrieving a service dynamically var myService = Services.GetService(); if (myService != null) { // Use the service } return base.LoadContent(); } protected override void Update(GameTime gameTime) { // Update Myra input Myra.MyraManager.Instance.Update(gameTime); _activity.Update(gameTime); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsContext.CommandList.ClearRenderTarget(null, Color.CornflowerBlue); // Draw Myra UI Myra.MyraManager.Instance.Draw(gameTime); base.Draw(gameTime); } static void Main(string[] args) { using (var game = new Program()) { game.Run(); } } } // Dummy service for demonstration public class MyService { public void DoSomething() { } } } ``` -------------------------------- ### ModelComponentExtensions Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/extensions.md Extensions for ModelComponent to get mesh dimensions. ```APIDOC ## GetMeshHeight() ### Description Returns the mesh height as a `float`. (Status: Done) ### Method `GetMeshHeight` ## GetMeshHWL() ### Description Returns the mesh height, width, and length as a `Vector3`. (Status: Done) ### Method `GetMeshHWL` ``` -------------------------------- ### Run the Project Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/code-only/create-project.md Executes the project. This command also implicitly builds the project if changes have been made. ```bash dotnet run ``` -------------------------------- ### GetCamera (by name) Source: https://github.com/vaclavelias/stride-community-toolkit/blob/main/docs/manual/script-extensions/index.md Gets the camera from the GraphicsCompositor with the given name. ```APIDOC ## GetCamera (by name) ### Description Gets the camera from the `GraphicsCompositor` with the given name. ### Method `GetCamera(ScriptComponent, string)` ### Parameters #### Path Parameters - **scriptComponent** (ScriptComponent) - Required - The script component to get the camera from. - **cameraName** (string) - Required - The name of the camera to retrieve. ### Response #### Success Response (CameraComponent) - Returns the `CameraComponent` with the specified name. ```