Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions NImpeller.sln
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sandbox.Metal", "samples\Sandbox.Metal\Sandbox.Metal.csproj", "{554505AE-9958-4740-91B1-FA285716F5E5}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NImpeller.Tests", "tests\NImpeller.Tests\NImpeller.Tests.csproj", "{5CDD2905-02B5-4A31-AA07-E45D45A1A5B8}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Sandbox.GLFW", "samples\Sandbox.GLFW\Sandbox.GLFW.csproj", "{E83AA564-7987-44DE-95DD-D9F418141E48}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down Expand Up @@ -140,6 +141,18 @@ Global
{5CDD2905-02B5-4A31-AA07-E45D45A1A5B8}.Release|x64.Build.0 = Release|Any CPU
{5CDD2905-02B5-4A31-AA07-E45D45A1A5B8}.Release|x86.ActiveCfg = Release|Any CPU
{5CDD2905-02B5-4A31-AA07-E45D45A1A5B8}.Release|x86.Build.0 = Release|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Debug|x64.ActiveCfg = Debug|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Debug|x64.Build.0 = Debug|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Debug|x86.ActiveCfg = Debug|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Debug|x86.Build.0 = Debug|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Release|Any CPU.Build.0 = Release|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Release|x64.ActiveCfg = Release|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Release|x64.Build.0 = Release|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Release|x86.ActiveCfg = Release|Any CPU
{E83AA564-7987-44DE-95DD-D9F418141E48}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -152,5 +165,6 @@ Global
{9E990EB5-B048-43E5-B788-1B388D59BF03} = {FE23EB06-C41F-4FE7-9CE2-2C05323A3366}
{0DD46D36-B034-476D-B416-649F7B5BD324} = {FE23EB06-C41F-4FE7-9CE2-2C05323A3366}
{554505AE-9958-4740-91B1-FA285716F5E5} = {FE23EB06-C41F-4FE7-9CE2-2C05323A3366}
{E83AA564-7987-44DE-95DD-D9F418141E48} = {FE23EB06-C41F-4FE7-9CE2-2C05323A3366}
EndGlobalSection
EndGlobal
197 changes: 197 additions & 0 deletions samples/Sandbox.GLFW/GlfwApplication.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using NImpeller;
using Silk.NET.Core.Contexts;
using Silk.NET.Core.Native;
using Silk.NET.GLFW;
using Silk.NET.OpenGL;

namespace Sandbox;

public unsafe class GlfwApplication(GlfwApplication.GraphicsApi apiType = GlfwApplication.GraphicsApi.OpenGL,ILogger<GlfwApplication>? logger = null) : IApplication
{
public enum GraphicsApi
{
OpenGL,
Vulkan
}

public event EventHandler<StatusUpdatedEventArgs>? StatusUpdated;

private readonly ILogger<GlfwApplication> _logger = logger ?? NullLogger<GlfwApplication>.Instance;
private readonly Glfw _glfw = Glfw.GetApi();
private WindowHandle* _window;
private ImpellerContext _impellerContext = null!;
private ImpellerVulkanSwapchain _vulkanSwapchain = null!;
private ImpellerSurface? _surface;
private ImpellerISize _surfaceSize;
private IScene _scene = null!;
private readonly Stopwatch _fpsStopwatch = Stopwatch.StartNew();
private readonly Stopwatch _totalRunTime = Stopwatch.StartNew();
private int _frames;
private long _totalFrames;
private int _fbo;
private int _fps;

public ApplicationStatus GetStatus()
{
return new ApplicationStatus
{
CurrentFps = _fps,
TotalFrames = _totalFrames,
RunTime = _totalRunTime.Elapsed
};
}

public bool Initialize(int width, int height, string title = "NImpeller on GLFW")
{
if (!_glfw.Init())
{
_logger.LogError("GLFW initialization failed.");
return false;
}

if (apiType == GraphicsApi.OpenGL)
{
_glfw.WindowHint(WindowHintInt.ContextVersionMajor, 3);
_glfw.WindowHint(WindowHintInt.ContextVersionMinor, 0);
_glfw.WindowHint(WindowHintClientApi.ClientApi, ClientApi.OpenGLES);
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
_glfw.WindowHint(WindowHintInt.ContextVersionMinor, 3);
_glfw.WindowHint(WindowHintBool.OpenGLForwardCompat, true);
_glfw.WindowHint(WindowHintOpenGlProfile.OpenGlProfile, OpenGlProfile.Core);
}
}

_window = _glfw.CreateWindow(width, height, title, null, null);
if (_window == null)
{
_logger.LogError("Window creation failed.");
_glfw.Terminate();
return false;
}

switch (apiType)
{
case GraphicsApi.OpenGL:
{
_logger.LogInformation("Creating OpenGL ES context...");
_glfw.MakeContextCurrent(_window);
_glfw.SwapInterval(0);
var gl = GL.GetApi(new LamdaNativeContext(s => _glfw.GetProcAddress(s)));

_impellerContext = ImpellerContext.CreateOpenGLESNew(name =>
{
_logger.LogDebug("Loading OpenGL function: {FuncName}", name);
return _glfw.GetProcAddress(name);
})!;

gl.GetInteger(GLEnum.FramebufferBinding, out var data);
_fbo = data;
break;
}
case GraphicsApi.Vulkan:
{
_logger.LogInformation("Creating Vulkan context...");
_impellerContext = ImpellerContext.CreateVulkanNew(
(instance, procNamePtr) => _glfw.GetInstanceProcAddress(new VkHandle(instance), (byte*)procNamePtr),
false)!;

VkNonDispatchableHandle surfaceHandle;
_glfw.CreateWindowSurface(
new VkHandle(_impellerContext.GetVulkanInfo()!.Value.Vk_instance),
_window,
null,
&surfaceHandle
);

_vulkanSwapchain = _impellerContext.VulkanSwapchainCreateNew(
new IntPtr((long)surfaceHandle.Handle))!;
break;
}
}

return true;
}

public void SetScene(IScene scene) => _scene = scene;

public void Run()
{
var running = true;

while (running)
{
_glfw.PollEvents();
if (_glfw.WindowShouldClose(_window))
running = false;

_glfw.GetWindowSize(_window, out var width, out var height);
var windowSize = new ImpellerISize(width, height);

if (apiType == GraphicsApi.OpenGL)
{
if (_surface == null || windowSize != _surfaceSize)
{
_surface?.Dispose();
_surface = _impellerContext.SurfaceCreateWrappedFBONew(
(ulong)_fbo,
ImpellerPixelFormat.kImpellerPixelFormatRGBA8888,
windowSize)!;
_surfaceSize = windowSize;
}
}

ImpellerDisplayList displayList;
using (var builder = ImpellerDisplayListBuilder.New(
new ImpellerRect(100, 100, width, height))!)
{
if (_fpsStopwatch.Elapsed.TotalSeconds >= 1.0)
{
_fps = (int)(_frames / _fpsStopwatch.Elapsed.TotalSeconds);
_frames = 0;
_fpsStopwatch.Restart();

_glfw.SetWindowTitle(_window, $"FPS: {_fps}");
StatusUpdated?.Invoke(this, new StatusUpdatedEventArgs(GetStatus()));
}

_frames++;
_totalFrames++;

_scene.Render(_impellerContext, builder, new SceneParameters
{
Width = width,
Height = height
});

displayList = builder.CreateDisplayListNew()!;
}

using (displayList)
{
switch (apiType)
{
case GraphicsApi.OpenGL:
_surface?.DrawDisplayList(displayList);
_glfw.SwapBuffers(_window);
break;
case GraphicsApi.Vulkan:
{
using (_surface = _vulkanSwapchain.AcquireNextSurfaceNew()!)
{
_surface.DrawDisplayList(displayList);
_surface.Present();
}
break;
}
}
}
}

Process.GetCurrentProcess().Kill();
}
}
23 changes: 23 additions & 0 deletions samples/Sandbox.GLFW/Sandbox.GLFW.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<TargetFramework>net8.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<RootNamespace>Sandbox</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Silk.NET.GLFW" Version="2.22.0"/>
<PackageReference Include="Silk.NET.Vulkan" Version="2.22.0"/>
<PackageReference Include="Silk.NET.OpenGL" Version="2.22.0"/>
<PackageReference Include="Silk.NET.Vulkan.Extensions.KHR" Version="2.22.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Sandbox.Core\Sandbox.Core.csproj"/>
</ItemGroup>

</Project>
63 changes: 55 additions & 8 deletions samples/Sandbox/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ public enum GraphicsApi
Vulkan,
Metal
}

public enum WindowBackend
{
SDL,
GLFW
}

public class Options
{
Expand All @@ -43,6 +49,9 @@ public class Options

[Option('h', "height", Required = false, Default = 600, HelpText = "Window height")]
public int Height { get; set; }

[Option('b', "backend", Required = false, Default = WindowBackend.SDL, HelpText = "Window backend (SDL, GLFW)")]
public WindowBackend Backend { get; set; }
}

static void Main(string[] args)
Expand Down Expand Up @@ -81,10 +90,23 @@ static void Main(string[] args)
.Color(Color.Blue));

AnsiConsole.MarkupLine("[dim]A .NET binding for Flutter's Impeller graphics engine[/]\n");

var selectedBackend = AnsiConsole.Prompt(
new SelectionPrompt<string>()
.Title("[green]Select Window Backend:[/]")
.PageSize(10)
.AddChoices("SDL", "GLFW"));

var backend = selectedBackend switch
{
"SDL" => WindowBackend.SDL,
"GLFW" => WindowBackend.GLFW,
_ => WindowBackend.SDL
};

// Select Graphics API
var availableApis = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? AllApis : NonMetalApis;

var selectedApi = AnsiConsole.Prompt(
new SelectionPrompt<string>()
.Title("[green]Select Graphics API:[/]")
Expand Down Expand Up @@ -131,7 +153,8 @@ static void Main(string[] args)
Api = api,
Scene = selectedScene.Name,
Width = width,
Height = height
Height = height,
Backend = backend
};
}

Expand Down Expand Up @@ -171,15 +194,39 @@ static void RunApplication(Options options)
return;
}

// For OpenGL and Vulkan, use SDL
var sdlApi = options.Api == GraphicsApi.OpenGL ? SdlApplication.GraphicsApi.OpenGL : SdlApplication.GraphicsApi.Vulkan;
var sdlLogger = _loggerFactory!.CreateLogger<SdlApplication>();
var sdlApp = new SdlApplication(sdlApi, sdlLogger);
if (sdlApp.Initialize(options.Width, options.Height))
IApplication app;
if (options.Backend == WindowBackend.GLFW)
{
var glfwApi = options.Api == GraphicsApi.OpenGL
? GlfwApplication.GraphicsApi.OpenGL
: GlfwApplication.GraphicsApi.Vulkan;
var glfwLogger = _loggerFactory!.CreateLogger<GlfwApplication>();
var glfwApp = new GlfwApplication(glfwApi,glfwLogger);
if (!glfwApp.Initialize(options.Width, options.Height))
{
logger.LogError("GLFW initialization failed.");
return;
}
glfwApp.SetScene(scene);
app = glfwApp;
}
else
{
var sdlApi = options.Api == GraphicsApi.OpenGL
? SdlApplication.GraphicsApi.OpenGL
: SdlApplication.GraphicsApi.Vulkan;
var sdlLogger = _loggerFactory!.CreateLogger<SdlApplication>();
var sdlApp = new SdlApplication(sdlApi, sdlLogger);
if (!sdlApp.Initialize(options.Width, options.Height))
{
logger.LogError("SDL initialization failed.");
return;
}
sdlApp.SetScene(scene);
RunWithConsoleDisplay(sdlApp);
app = sdlApp;
}

RunWithConsoleDisplay(app);
}

static void RunWithConsoleDisplay(IApplication app)
Expand Down
1 change: 1 addition & 0 deletions samples/Sandbox/Sandbox.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
<ProjectReference Include="../Sandbox.Metal/Sandbox.Metal.csproj" />
<ProjectReference Include="../Sandbox.SDL/Sandbox.SDL.csproj" />
<ProjectReference Include="..\..\src\NImpeller\NImpeller.csproj" />
<ProjectReference Include="..\Sandbox.GLFW\Sandbox.GLFW.csproj" />
</ItemGroup>

</Project>
Loading