GithubHelp home page GithubHelp logo

foreverzer0 / glfw-net Goto Github PK

View Code? Open in Web Editor NEW
220.0 11.0 53.0 290 KB

Complete, cross-platform, managed wrapper around the GLFW library for creating native windows with an OpenGL context.

License: MIT License

C# 100.00%

glfw-net's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

glfw-net's Issues

A callback was made on a garbage collected delegate of type 'GLFW.NET!GLFW.MouseCallback::Invoke'.

I am writing a very simple application based on the HelloTriangle, available at https://github.com/ForeverZer0/glfw-net on VisualStudio 2019.

When I added some callbacks, I got the following error message:

Process terminated. A callback was made on a garbage collected delegate of type 'GLFW.NET!GLFW.MouseCallback::Invoke'.
at GLFW.Glfw.PollEvents()
at GLFW.Glfw.PollEvents()
at HelloTriangle.Program.Main(System.String[])

I've looked at "#19" and my code is very similar to your "solution 2".

using System;
using System.IO;
using GLFW;
using static OpenGL.Gl;
using GlmNet;

namespace HelloTriangle
{
    class Program
    {
        static void Main(string[] args)
        {
            PrepareContext();
            Window window = CreateWindow(1500, 1500);
            var program = CreateProgram();

            var loc = glGetUniformLocation(program, "projectionMatrix");
            SetCallBacks(window);

            while (!Glfw.WindowShouldClose(window))
            {

                // Swap fore/back framebuffers, and poll for operating system events.
                Glfw.SwapBuffers(window);
                Glfw.PollEvents();

                int w, h;
                Glfw.GetFramebufferSize(window, out w, out h);  //this works properly. 
                glViewport(0, 0, w, h);

                glClear(GL_COLOR_BUFFER_BIT);

                mat4 mat = glm.ortho(0, w, h, 0);
                glUniformMatrix4fv(loc, 1, false, mat.to_array());
            }

            Glfw.Terminate();
        }

        private static void SetCallBacks(Window window)
        {
            Glfw.SetCursorPositionCallback(window, mouseHandler);  //MouseCallback
        }

        private static void mouseHandler(Window win, double x, double y)
        {
            Console.WriteLine("Mouse: " + x + "  " + y);
        }
       ....
}

====================================================

#version 330 core
layout (location = 0) in vec3 pos;
uniform mat4 projectionMatrix;
out vec2 TexCoord;

void main()
{
    TexCoord = uv;
    gl_Position = projectionMatrix * vec4(pos.x, pos.y, pos.z, 1.0);
}

====================================================

The application crashes after a few seconds. If I comment the command

glUniformMatrix4fv(loc, 1, false, mat.to_array());

it runs a bit longer before crashing.

AcessViolation in FileDrop event

 private static void OnWindowFileDrop(object sender, FileDropEventArgs e)
    {
        foreach (var item in e.Filenames)
        {
            Console.WriteLine(item);
        }
    }

Exception:
Fatal error. System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at System.Runtime.InteropServices.Marshal.ReadByte(IntPtr, Int32)
at GLFW.Util.PtrToStringUTF8(IntPtr)
at GLFW.NativeWindow.OnFileDrop(Int32, IntPtr)
at GLFW.NativeWindow.b__115_4(IntPtr, Int32, IntPtr)
at GLFW.Glfw.WaitEvents()
at GLFW.Glfw.WaitEvents()
at Program.Main(System.String[])

library won't find libglfw.so.3.3

On fedora 31 atleast the library won't find the dll. If I manually create a soft link from libglfw.so to libglfw.so.3 the thing works without any issues.
Is this a problem with glfw-net or is there supposed to be a .so link already there?

AOT - Ahead of Time | native code compiling

I tryed it with this libary and it dosnt work

Unhandled Exception: GLFW.Exception: Win32: Failed to convert string from UTF-8: Falscher Parameter.
at GLFW.Glfw.GlfwError(ErrorCode code, IntPtr message) + 0x52
at SimpleGame!+0x120468

or

Unhandled Exception: UGLFW.Exception: PlatformError
at GLFW.Glfw.GlfwError(ErrorCode code, IntPtr message) + 0x64
at SimpleGame!+0x11fac8

after removing the the IntPtr to string method from source.
I tryed already a diferent libary/implementation of glfw in c# with aot and it work. it would be cool if that would be added here to

Glfw.GetKeyName(Keys key, int scanCode) throws internal exception when used with non-printable key

Glfw.GetKeyName(Keys key, int scanCode) throws an internal NullReferenceException when specifying a key that is non-printable (eg. Keys.LeftControl). Description states the method returnes null instead. To fix this, changing

public static string GetKeyName(Keys key, int scanCode)
{
    return Util.PtrToStringUTF8(GetKeyNameInternal(key, scanCode));
}

to

public static string GetKeyName(Keys key, int scanCode)
{
    IntPtr ptr = GetKeyNameInternal(key, scanCode);
    return ptr == IntPtr.Zero? null : Util.PtrToStringUTF8(ptr);
 }

should probably do the trick.

Side note: what are the plans on releasing the current/corrected version to nuget?

Expunge references to "Game"

There are plenty of applications for GLFW that are not games. I suggest that classes that contain the word Game be renamed to something more application agnostic.

Perhaps GameWindow could become AppWindow.

GLFW does not contain the function Glfw.GetTime()

The sample window creation code on README.md says

using (var window = new NativeWindow(800, 600, "MyWindowTitle"))
            {
                // Main application loop
                while (!window.IsClosing)
                {
                    // OpenGL rendering
                    // Implement any timing for flow control, etc (see Glfw.GetTime())
                   
                    // Swap the front/back buffers
                    window.SwapBuffers();

                    // Poll native operating system events (must be called or OS will think application is hanging)
                    Glfw.PollEvents();
                }
            }

But the function Glfw.GetTime() does not appear to exist.

Add Annotations

Add JetBrains.Annotations file (internal file, not NuGet package), and implement proper CanBeNull, NotNull, etc. annotations where applicable.

This will assist users with JetBrains tools (Rider/Resharper) in catching possible usage errors within the IDE.

Default Native Library Name

The library name use with the DllImportAttribute to import the functions at run-time currently uses the Windows default naming convention of glfw3, as opposed to its Unix-like counterpart: glfw.

This causes anyone using the library on Linux/Mac to have to manually edit the library name and recompile, since they have no control over the name of native GLFW library as it gets installed on the system.

Since Windows users need only include the pre-built and portable binaries with their application, refactoring the native library name to glfw is trivial, and will not require editing the code or rebuilding, only the library name which they must provide themselves anyway.

Proposal is to change the constant to the Glfw.LIBRARY constant from glfw3 to glfw, so Unix users need only include the library and run it, and Windows users only need to apply a rename to the binaries while adding them to their project.

This should hopefully reduce hassle for everyone on all platforms, and enforce a standardized name "that just works" without all the extra mumbo-jumbo of resolving dependencies at runtime. Windows users will still need to account for CPU architecture and which binary to target, but that is unavoidable.

Glfw.CreateWindowSurface return a pointer in read or write protected memory

When I call Glfw.CreateWindowSurface the method succeds, everything seems well but when I try to access the value at the pointer location a System.AccessViolationException gets thrown because the pointer points to read and write protected memory.

static VkSurfaceKHR CreateSurface(VkInstance instance, Window window)
        {

            Assert((VkResult)GLFW.Vulkan.CreateWindowSurface(instance.Handle,
            Glfw.GetWindowUserPointer(window), IntPtr.Zero, out var ptr));

            VkSurfaceKHR surface = *(VkSurfaceKHR*)ptr;

            Console.WriteLine(surface);

            return surface;
        }

Why GLFW.NET does't see the Vulkan?

Why GLFW.NET does't see the Vulkan?

VulkanSharp can find Vulkan, but GLFW return Vulkan.IsSupported false, and when try get Vulkan instance extensions throw Vulkan: Loader not found

What can I do to make the GLFW.NET see the Vulkan?

System: MacOS Catalina
Framework: Net Core 3.1

Best Regards, Roman S

Exception is thrown when I create a GameWindow using Monitors static property

Exception: 'Invalid window size 0x0' is thrown when I use Monitors static property in Glfw class to create a new GameWindow.

Code Example:
var monitor = Glfw.Monitors[1];
var videoMode = Glfw.GetVideoMode(monitor);
var window = new GameWindow(videoMode.Width, videoMode.Height, "Test", monitor, Window.None);

Calling .Fullscreen() causes an exception.

Unhandled exception. GLFW.Exception: Invalid window size 0x0
at GLFW.Glfw.GlfwError(ErrorCode code, IntPtr message)
at GLFW.Glfw.SetWindowMonitor(Window window, Monitor monitor, Int32 x, Int32 y, Int32 width, Int32 height, Int32 refreshRate)
at GLFW.NativeWindow.Fullscreen(Monitor monitor)
at GLFW.NativeWindow.Fullscreen()

Window is visible and has not the size 0x0...

MouseEventArgs.cs Where is Type "Point"

Where the type Point Referencing to i looked through GLFW.NET/ file in the repo i cant find the type
says im missing the an assembly reference

Somthing like -:

public Point postition => new Point(Convert.ToInt(x) , Convert.ToInt(y));

sorry if this might be minor issue and i'm missing something..

Application crashes when running on x86

I've downloaded Glfw-net and started developing my application using "Any CPU" configuration on Windows 10, based on the HelloTriangle demo. I've downloaded glfw.dll from https://www.glfw.org/.

Since I have plans to run my application on x86 platforms, I've changed the configuration to "x86" on Visual Studio 19 (Version 16.8.2). I've downloaded the glfw.dll for x86 architecture. In this configuration, the application crashes immediately.

Sometimes, it reports Error 0xc0000005 (Access Violation) and (process 17684) exited with code -1073740791. I also tried different versions of glfw.dll, but with no success.

After hundreds of unsuccessful experiments, I returned to the HelloTriangle demo to compare to it with my application (HelloTrinagle runs smoothly on x86 and x64). I was considering the problem could be related to texture loading, shaders, and so on.

I've started adding code to the HelloTriangle (code used on my application) to try to find the error. I noticed that just adding something like this

  mat4 matOrtho = glm.ortho(0, 500, 500, 0);
  glUniformMatrix4fv(projectionMatrixLoc, 1, false, matOrtho.to_array());

or

      v = new float[100];

to the render loop causes the application to crash. In other words, anything that allocates some memory. The larger the memory block, the faster the failure occurs.

          while (!Glfw.WindowShouldClose(window))
           {
               Glfw.SwapBuffers(window);
               Glfw.PollEvents();

               //mat4 matOrtho = glm.ortho(0, 500, 500, 0);
               //glUniformMatrix4fv(projectionMatrixLoc, 1, false, matOrtho.to_array());
               //v = new float[1000];

               glClear(GL_COLOR_BUFFER_BIT);
               glDrawArrays(GL_TRIANGLES, 0, 3);
           }

Since my application loads several textures, in x86 it crashes even before the render loop is reached.

Illegal `glfwDestroyWindow` in window close handler

On MacOS, the following code will cause a segfault when the user quits the application using command+Q:

using Glfw;

// ...

public static void Main()
{
	using var window = new NativeWindow(1920, 1080, "My App");
	while (!window.IsClosed)
	{
		Glfw.PollEvents();
	}
	Console.WriteLine("Goodbye!");
}

The access violation happens after the NativeWindow.Closed event is finished dispatching, where the window close request callback returns control back to GLFW. Looking into the implementation of the protected NativeWindow.OnClosing handler, this seems to happen because underlying window is destroyed in the middle of the callback (see this line, which is responsible for destroying the window handle). This is illegal, with the GLFW reference documentation for glfwDestroyWindow stating that:

Reentrancy
This function must not be called from a callback.

This is a logical error, not an error in C#'s FFI. Here is the equivalent C code which exhibits the same faulty behavior:

#include <stdio.h>
#include <GLFW/glfw3.h>

static void onClosing(GLFWwindow* window)
{
	printf("Destroying %p\n", window);
	// ...
	glfwDestroyWindow(window);
}

int main(void)
{
	// Setup GLFW
	if (!glfwInit())
		return -1;

	// Setup window
	GLFWwindow* window = glfwCreateWindow(1920, 1080, "My App", NULL, NULL);

	if (!window)
		goto stop;

	glfwSetWindowCloseCallback(window, onClosing);

	// Main loop
	while (!glfwWindowShouldClose(window))
	{
		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	// Cleanup
	puts("Goodbye!");
stop:
	glfwTerminate();
	return 0;
}

There's no easy way to fix this without changing the API. A non-breaking (but potentially confusing) fix could be to invisibly handle window destruction at the end of the Glfw.PollEvents method call by destroying all windows that still have the shouldClose flag, but that breaks the user expectation that the Glfw class is just raw FFI. A better (but breaking) approach would be to introduce a dedicated wrapper around Glfw.PollEvents that "handles higher-level behavior for the GLFW-NET-specific wrapper objects" i.e. implements the behavior of the previous proposal but in a different method.

BadImageFormatException on .NET framework 4.7.2 via NuGet and source

Yesterday and today I tried to get your library to run (first via NuGet, later on also via the source from here).
I first tried to use .NET framework 4.7.2 which always resulted in either a DllNotFoundException (due to wrong naming, wrong location and forgetting to copy the dll to the output) and BadImageFormatException, which I could not resolve - this seems to be a problem with .NET framework (occured both via NuGet and your source, using the same dll file that worked with your example).
When I tried to use .NET Core 3.1 it worked fine with the NuGet version as soon as I had setup the dll correctly.

Also maybe you could improve the usability by

  • making the LIBRARY path changeable (especially for the NuGet version)
  • extending the Getting Started part in the README (state where exactly the dll should be put in and which name it should have, in the best case also mention to not forget setting the copy to source option in the IDE)
  • adding a troubleshooting part to the README containing the more common exceptions

This especially the README would probably resolve most errors

Resizing Problem when using Skia

For some unknown reason, when using the skia example, resizing the window doesn't actually seem to resize the canvas.
Instead, the dimensions stay the same and the canvas is docked in the bottom left corner of the screen

Information

<PackageReference Include="SkiaSharp" Version="2.80.3" />
<PackageReference Include="glfw-net" Version="3.3.1" />

Windows 10

Unable to load shared library 'glfw' or one of its dependencies

First off, this library looks really fantastic. I was really excited to find it. Thanks for making it!

I'm seeing the following exception when trying to run one of the example projects:

Unhandled exception. System.TypeInitializationException: The type initializer for 'GLFW.Glfw' threw an exception.
 ---> System.DllNotFoundException: Unable to load shared library 'glfw' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(libglfw, 1): image not found
   at GLFW.Glfw.Init()
   at GLFW.Glfw..cctor() in /Users/nathanlandis/Code/mivi/src/glfw-net/GLFW.NET/Glfw.cs:line 34
   --- End of inner exception stack trace ---
   at GLFW.Glfw.WindowHint(Hint hint, ClientApi value) in /Users/nathanlandis/Code/mivi/src/glfw-net/GLFW.NET/Glfw.cs:line 1776
   at HelloTriangle.Program.PrepareContext() in /Users/nathanlandis/Code/mivi/src/glfw-net/Examples/HelloTriangle/Program.cs:line 65
   at HelloTriangle.Program.Main(String[] args) in /Users/nathanlandis/Code/mivi/src/glfw-net/Examples/HelloTriangle/Program.cs:line 22

I'm running macOS 10.15.4 and have latest dotnet core sdks. I installed glfw using homebrew, and I've verified that it shows up in /usr/local/include and lib. I've tried a system reboot too.

Any idea of what I need to get the library to load correctly?

Thanks!

NativeWindow.OnFileDrop hardcoded for 32 bit pointers, crashes on 64 bit Windows

So I had a crash in NativeWindow.OnFileDrop callback because of this line:

var ptr = new IntPtr(Marshal.ReadInt32(pointer + offset));

which returned nonsense on my 64 bit windows machine. Issue can be fixed by replacing with

var ptr = Marshal.ReadIntPtr(pointer + offset);

which reads native-sized pointers and should probably be used instead.

GLFW Keeps calling Garbage Collected Fields

Im not sure if this is just me being dumb or not however i keep encountering this error when enough event callbacks are called

Error:

Process terminated. A callback was made on a garbage collected delegate of type 'JStudio!GLFW.MouseCallback::Invoke'.
Repeat 2 times:
--------------------------------
   at GLFW.Glfw.PollEvents()
--------------------------------
   at TheJYT.JStudio.Platform.Windows.WindowsWindow.OnUpdate()
   at TheJYT.JStudio.Application.Run()
   at TheJYT.JStudio.Studio.Main()
   at TheJYT.JStudio.Sandbox.Program.Main(System.String[])

This error only occures when enough event callbacks trigger.

Let me know if you need anything else

Missing Native Functions

There are various functions in the native library related to native contexts that have not been implemented:

  • glfwGetGLXContext
  • glfwGetCocoaMonitor
  • glfwGetNSGLContext
  • glfwGetX11Display
  • glfwGetX11Adapter
  • glfwGetX11Monitor
  • glfwGetX11Window
  • glfwSetX11SelectionString
  • glfwGetX11SelectionString
  • glfwGetGLXWindow
  • glfwGetWaylandDisplay
  • glfwGetWaylandMonitor
  • glfwGetWaylandWindow
  • glfwGetOSMesaColorBuffer
  • glfwGetOSMesaDepthBuffer
  • glfwGetOSMesaContext

Create Examples

Create examples utilizing the library, demonstrating both basic functionality, and lesser-known, more advanced scenarios.

Required Vulkan extensions list contains empty strings

When calling GLFW.Vulkan.GetRequiredInstanceExtensions(), multiple empty strings are included in the array. If you pass that to Vulkan and create an instance, it causes a crash. Using Linq to remove all empty strings makes it work as expected.

Possibility to use as nuget package

Is it possible to make use the nuget package given by using add package glfw-net,
instead of using the source code directly, even as submodule?

Whenever I try, I receive a System.DllNotFoundException even when renaming the dll files from glfw3 to glfw. Neither does changing the location from a lib folder to the root seem to work. Though this method seems greatly more preferable to cloning the source.

Calling MakeCurrent() when no context is created crashes the window.

When creating a gamewindow for vulkan, and one decides to disable contexts using Glfw.WindowHint(Hint.ClientApi, ClientApi.None);, the app crashes with a The specified window has no contex error at MakeCurrent() in the constructor. Currently, the only way to use vulkan is if you use the raw functions to create and manage the window.

KeyCallback handle throws AccessViolation

AccessViolation is throw when dereferencing window handle from callback.

unsafe public void keyCallback(IntPtr window, Keys key, int scanCode, InputState state, ModifierKeys mod) {
    if (state == InputState.Press) {
        switch (key) {
            case Keys.Escape:
                Glfw.SetWindowShouldClose( * (Window * ) window, true);
                //Glfw.SetWindowShouldClose(this.window, true); workaround-ish, does work.
                return;
            default:
                return; // Niets
        }
    }
}

I might be missing something basal here, yet i cannot figure it out. Have been using an instance variable as workaround.

PollEvents throws an Execution Engine Exception

I am currently trying to setup some callbacks for the mouse and keyboard.
I have a very basic loop going: Draw, Swap buffers, Poll events.
Everytime I move my mouse or spin the mouse wheel it prints the information onto the console. But after a certain amount of time the PollEvents function throws this exception and the only way to avoid this is to not use these events. Is this a bug or am I missing something?

How do I get the Example projects to run?

Which glfw dll file do I need to use?
Which folder should I place it in?
Do I need to add anything in a csproj file?
The default right now is netcoreapp3.1

Tried out a bunch of variations, but none of them works. Also tried dumping it in next to the built exe, no luck.

Update Nuget Package

Can you please update the Nuget package to the current state of this repository? I'm trying to use Vulkan.GetRequiredInstanceExtensions but because this commit isn't in the nuget package it crashes with a System.AccessViolationException. This seems like a very major issue so it would be nice to see the patch on nuget.

Thanks :)

Glfw SetWindowPositionCallback Bug

Inside Glfw.cs

public static extern PositionCallback SetWindowPositionCallback(Window window, PositionCallback positionCallback);

the delegate (PositionCallback) fail to return correct values.

Inside Delegates.cs

public delegate void PositionCallback(Window window, double x, double y);

this can be fixed if the signature of the delegate is changed to :

public delegate void PositionCallback(Window window, int x, int y);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.