Exemplo n.º 1
0
 public static T1 Load <T1, T2>(T2 baseApi)
     where T1 : NativeExtension <T2> where T2 : NativeAPI
 {
     return(baseApi.IsExtensionPresent(GetExtensionAttribute(typeof(T1)).Name)
         ? LibraryActivator.CreateInstance <T1>(baseApi.Library)
         : null);
 }
Exemplo n.º 2
0
        static unsafe void Main(string[] args)
        {
            Span <byte> s;

            //var x = File.OpenWrite("b.dll");
            //AheadOfTimeActivator.WriteImplementation<TestClass>(x);
            //var y = File.OpenWrite("a.dll");
            //AheadOfTimeActivator.WriteImplementation<TestClass2>(y);
            //x.Flush();
            //y.Flush();
            //var user32 = LibraryActivator.CreateInstance<TestClass>("user32.dll");
            //user32.MessageBox(IntPtr.Zero, "SuperInvoke".ToCharArray(), "Hello from SuperInvoke!".ToCharArray(), 0);
            if (AotTest)
            {
                var libBuilder = new LibraryBuilder();
                var opts       = BuilderOptions.GetDefault(typeof(TestClass2));
                libBuilder.Add(opts);
#if NET47
                var bytes = libBuilder.BuildBytes();
                File.WriteAllBytes("c.dll", bytes);
#else
                libBuilder.Build();
#endif
            }

            var lib = LibraryActivator.CreateInstance <TestClass2>("user32");

            var a = Marshal.StringToHGlobalAnsi("Test 1");
            var b = Marshal.StringToHGlobalAnsi("Hello from SuperInvoke!");
            lib.MessageBox(default, (char *)a, (char *)b, 0);
Exemplo n.º 3
0
    private static unsafe void Main(string[] args)
    {
        var parsedOpts = Parser.Default.ParseArguments <Options>(args);

        parsedOpts.WithParsed(opts => {
            if (opts.Context != null)
            {
                _useEgl = opts.Context.Contains("egl");
            }

            if (opts.GlApi != null)
            {
                _automaticFallback = false;
                _useOpenGl         = !opts.GlApi.Contains("es");
                _useOpenGl         = true;
            }

            if (opts.GlMajorVersion != null)
            {
                _automaticFallback = false;
                _glMaj             = opts.GlMajorVersion.Value;
            }

            if (opts.GlMinorVersion != null)
            {
                _automaticFallback = false;
                _glMin             = opts.GlMinorVersion.Value;
            }
        });

        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            Console.OutputEncoding = Encoding.UTF8;
            Ansi.WindowsConsole.TryEnableVirtualTerminalProcessing();
        }

        AppDomain.CurrentDomain.UnhandledException   += OnUnhandledException;
        AppDomain.CurrentDomain.FirstChanceException += OnFirstChanceException;

        //InjectNsight();

        //InjectRenderDoc();

        var options = WindowOptions.Default;

        var size = new Size(1024, 576);

        var title = "UltralightSharp - Silk.NET";

        options.Size  = size;
        options.Title = title;
        options.VSync = VSyncMode.On;
        options.TransparentFramebuffer   = false;
        options.PreferredDepthBufferBits = null;
        //options.VSync = true;

        /*
         * if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
         * var asmDir = Path.GetDirectoryName(new Uri(typeof(Program).Assembly.CodeBase!).LocalPath)!;
         * var glfwPath = Path.Combine(asmDir, "libglfw.so.3");
         * const string sysGlfwPath = "/lib/libglfw.so.3";
         * if (File.Exists(sysGlfwPath)) {
         *  var sb = new StringBuilder(1024);
         *  var sbSize = (UIntPtr)sb.Capacity;
         *  var used = (long)Libc.readlink(glfwPath, sb, sbSize);
         *  if (used >= 0) {
         *    var link = sb.ToString(0, (int)(used - 1));
         *    if (link != sysGlfwPath) {
         *      File.Delete(glfwPath);
         *      Libc.symlink(sysGlfwPath, glfwPath);
         *    }
         *  }
         *  else {
         *    // not a link
         *    File.Delete(glfwPath);
         *    Libc.symlink(sysGlfwPath, glfwPath);
         *    Cleanup += () => {
         *      File.Delete(glfwPath);
         *    };
         *  }
         * }
         * }
         */

        _glfw = Glfw.GetApi();
        Console.WriteLine($"GLFW v{_glfw.GetVersionString()}");

        if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            _glfw.InitHint(InitHint.CocoaMenubar, false);
            _glfw.InitHint(InitHint.CocoaChdirResources, false);
        }

        _glfw = GlfwProvider.GLFW.Value;

        {
            // setup logging
            Ultralight.SetLogger(new Logger {
                LogMessage = LoggerCallback
            });

            var tempDir = Path.GetTempPath();
            // find a place to stash instance storage
            do
            {
                _storagePath = Path.Combine(tempDir, Guid.NewGuid().ToString());
            }while (Directory.Exists(_storagePath) || File.Exists(_storagePath));

            AppCore.EnablePlatformFontLoader();

            AppCore.EnablePlatformFileSystem(AssetsDir);
        }

        /* afaik GLFW already does this, this was just to check
         * if (_useEgl || _automaticFallback) {
         * Console.WriteLine("Binding to LibEGL...");
         * var eglLib = new UnmanagedLibrary(
         *  new CustomEglLibNameContainer().GetLibraryName(),
         *  LibraryLoader.GetPlatformDefaultLoader()
         * );
         * var q = eglLib.LoadFunction("eglQueryAPI");
         * IL.Push(q);
         * IL.Emit.Calli(StandAloneMethodSig.UnmanagedMethod(CallingConvention.Cdecl, typeof(EGLEnum)));
         * IL.Pop(out EGLEnum api);
         * Console.WriteLine($"EGL API Target: {api}");
         * var b = eglLib.LoadFunction("eglBindAPI");
         * if (_useOpenGL && api != EGLEnum.OpenglApi) {
         *  IL.Push(EGLEnum.OpenglApi);
         *  IL.Push(b);
         *  IL.Emit.Calli(StandAloneMethodSig.UnmanagedMethod(CallingConvention.Cdecl, typeof(bool),
         *    typeof(EGLEnum)));
         *  IL.Pop(out bool success);
         *  Console.Error.WriteLine(!success
         *    ? "Couldn't bind EGL to OpenGL"
         *    : "EGL now bound to OpenGL");
         * }
         * else if (!_useOpenGL && api != EGLEnum.OpenglESApi){
         *  IL.Push(EGLEnum.OpenglESApi);
         *  IL.Push(b);
         *  IL.Emit.Calli(StandAloneMethodSig.UnmanagedMethod(CallingConvention.Cdecl, typeof(bool),
         *    typeof(EGLEnum)));
         *  IL.Pop(out bool success);
         *  Console.Error.WriteLine(!success
         *    ? "Couldn't bind EGL to OpenGL ES"
         *    : "EGL now bound to OpenGL ES");
         * }
         * }
         */

        if (_automaticFallback)
        {
            Console.WriteLine("Checking for supported context...");

            for (;;)
            {
                SetGlfwWindowHints();

                Console.WriteLine(
                    _useOpenGl
            ? "Attempting OpenGL v3.2 (Core)"
            : $"Attempting OpenGL ES v{_majOES}.0");
                var wh = _glfw.CreateWindow(1024, 576, title, null, null);
                if (wh != null)
                {
                    Console.WriteLine(
                        _useOpenGl
              ? "Created Window with OpenGL v3.2 (Core)"
              : $"Created Window with OpenGL ES v{_majOES}.0");
                    _glfw.DestroyWindow(wh);
                    break;
                }

                var code = _glfw.GetError(out char *pDesc);
                if (code == ErrorCode.NoError || pDesc == null)
                {
                    throw new PlatformNotSupportedException("Can't create a window via GLFW. Unknown error.");
                }

                var strLen = new ReadOnlySpan <byte>((byte *)pDesc, 32768).IndexOf <byte>(0);
                if (strLen == -1)
                {
                    strLen = 0;
                }
                var str    = new string((sbyte *)pDesc, 0, strLen, Encoding.UTF8);
                var errMsg = $"{code}: {str}";
                Console.Error.WriteLine(errMsg);
                if (code != ErrorCode.VersionUnavailable)
                {
                    throw new GlfwException(errMsg);
                }

                // attempt sequence: OpenGL ES 3.0, OpenGL 3.2, OpenGL ES 2.0
                if (!_useOpenGl && _majOES == 3)
                {
                    _useOpenGl = true;
                }
                else if (_majOES == 3 && _useOpenGl)
                {
                    _useOpenGl = false;
                    _majOES    = 2;
                }
                else
                {
                    throw new GlfwException(errMsg);
                }
            }
        }

        SetGlfwWindowHints();

        if (_useOpenGl)
        {
            options.API = new GraphicsAPI(
                ContextAPI.OpenGL,
                ContextProfile.Core,
                ContextFlags.ForwardCompatible,
                new APIVersion(_automaticFallback ? 3 : _glMaj, _automaticFallback ? 2 : _glMin)
                );
        }
        else
        {
            options.API = new GraphicsAPI(
                ContextAPI.OpenGLES,
                ContextProfile.Core,
                ContextFlags.ForwardCompatible,
                new APIVersion(_automaticFallback ? _majOES : _glMaj, _automaticFallback ? 0 : _glMin)
                );
        }
        options.IsVisible    = true;
        options.WindowBorder = WindowBorder.Resizable;
        options.WindowState  = WindowState.Normal;

        Console.WriteLine("Creating window...");

        _snView = Window.Create(options);

        _snView.Load    += OnLoad;
        _snView.Render  += OnRender;
        _snView.Update  += OnUpdate;
        _snView.Closing += OnClose;
        _snView.Resize  += OnResize;

        var glCtx = _snView.GLContext;

        if (!_useOpenGl)
        {
            Console.WriteLine("Binding to LibGLES...");
            _gl = LibraryActivator.CreateInstance <GL>
                  (
                new CustomGlEsLibNameContainer().GetLibraryName(),
                TemporarySuperInvokeClass.GetLoader(glCtx)
                  );
        }

        Console.WriteLine("Initializing window...");

        _snView.Initialize();

        if (_snView.Handle == IntPtr.Zero)
        {
            var code = _glfw.GetError(out char *pDesc);
            if (code == ErrorCode.NoError || pDesc == null)
            {
                throw new PlatformNotSupportedException("Can't create a window via GLFW. Unknown error.");
            }

            var strLen = new ReadOnlySpan <byte>((byte *)pDesc, 32768).IndexOf <byte>(0);
            if (strLen == -1)
            {
                strLen = 0;
            }
            var str = new string((sbyte *)pDesc, 0, strLen, Encoding.UTF8);
            throw new GlfwException($"{code}: {str}");
        }

        Console.WriteLine("Starting main loop...");
        _snView.Run();
    }
Exemplo n.º 4
0
    private static unsafe void OnLoad()
    {
        Console.WriteLine($"Loading...");
        //Getting the opengl api for drawing to the screen.
        _gl = LibraryActivator.CreateInstance <GL>(
            new CustomGlEsLibNameContainer().GetLibraryName(),
            TemporarySuperInvokeClass.GetLoader(_snView.GLContext)
            );

        var glVersionInfo  = _gl.GetString(StringName.Version);
        var glVersionMajor = _gl.GetInteger(GetPName.MajorVersion);

        if (glVersionMajor == 0)
        {
            Console.WriteLine("Unable to retrieve API major version.");
            glVersionMajor = !_automaticFallback ? _glMaj : _useOpenGl ? 3 : _majOES; // bug?
        }
        var glVersionMinor = _gl.GetInteger(GetPName.MinorVersion);

        Console.WriteLine($"{(_useOpenGl?"OpenGL":"OpenGL ES")} v{glVersionMajor}.{glVersionMinor} ({glVersionInfo})");

        var glVendor = _gl.GetString(StringName.Vendor);
        var glDevice = _gl.GetString(StringName.Renderer);

        Console.WriteLine($"{glVendor} {glDevice}");

        var glShaderVersionInfo = _gl.GetString(StringName.ShadingLanguageVersion);

        Console.WriteLine($"Shader Language: {glShaderVersionInfo}");

        _gpuDriverSite = new OpenGlEsGpuDriverSite(_gl, _dbg);

        var gpuDriver = _gpuDriverSite.CreateGpuDriver();

        Ultralight.SetGpuDriver(gpuDriver);

        using var cfg = new Config();

        var cachePath = Path.Combine(_storagePath, "Cache");

        cfg.SetCachePath(cachePath);

        var resourcePath = Path.Combine(AsmDir, "resources");

        cfg.SetResourcePath(resourcePath);

        cfg.SetUseGpuRenderer(true);
        cfg.SetEnableImages(true);
        cfg.SetEnableJavaScript(false);

        //cfg.SetForceRepaint(true);

        _ulRenderer = new Renderer(cfg);
        _ulSession  = new Session(_ulRenderer, false, "Demo");
        var wndSize   = _snView.Size;
        var wndWidth  = (uint)wndSize.Width;
        var wndHeight = (uint)wndSize.Height;
        var width     = (uint)(_scaleX * wndWidth);
        var height    = (uint)(_scaleY * wndHeight);

        _ulView = new View(_ulRenderer, width, height, false, _ulSession);
        _ulView.SetAddConsoleMessageCallback(ConsoleMessageCallback, default);

        if (_snView is IWindow wnd)
        {
            wnd.Title = _useOpenGl
        ? $"UltralightSharp - OpenGL v{glVersionMajor}.{glVersionMinor} (Silk.NET)"
        : $"UltralightSharp - OpenGL ES v{glVersionMajor}.{glVersionMinor} (Silk.NET)";
        }

        if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            var monitors         = _glfw.GetMonitors(out var monitorCount);
            var monitorInterface = ((IWindow)_snView).Monitor;
            var monitor          = monitors[monitorInterface.Index];
            _glfw.GetMonitorContentScale(monitor, out var xScale, out var yScale);
            _scaleX = xScale;
            _scaleY = yScale;
        }

        EnableDebugExtension();

        _gl.Disable(EnableCap.Dither);
        CheckGl();
        //_gl.Disable(EnableCap.PointSmooth);
        //CheckGl();
        //_gl.Disable(EnableCap.LineSmooth);
        //CheckGl();
        //_gl.Disable(EnableCap.PolygonSmooth);
        //CheckGl();
        //_gl.Hint(HintTarget.PointSmoothHint, HintMode.DontCare);
        //CheckGl();
        //_gl.Hint(HintTarget.LineSmoothHint, HintMode.DontCare);
        //CheckGl();
        //_gl.Hint(HintTarget.PolygonSmoothHint, HintMode.DontCare);
        //CheckGl();
        //_gl.Disable(EnableCap.Multisample);
        CheckGl();

        //Vertex data, uploaded to the VBO.
        var quadVertsLen = (uint)(_quadVerts.Length * sizeof(float));

        //Index data, uploaded to the EBO.
        var indicesSize = (uint)(_quadIndices.Length * sizeof(uint));

        //Creating a vertex array.
        _qva = _gl.GenVertexArray();
        _gl.BindVertexArray(_qva);
        LabelObject(ObjectIdentifier.VertexArray, _qva, "Quad VAO");

        //Initializing a vertex buffer that holds the vertex data.
        _qvb = _gl.GenBuffer();                                                                                             //Creating the buffer.
        _gl.BindBuffer(BufferTargetARB.ArrayBuffer, _qvb);                                                                  //Binding the buffer.
        LabelObject(ObjectIdentifier.Buffer, _qvb, "Quad VBO");
        _gl.BufferData(BufferTargetARB.ArrayBuffer, quadVertsLen, new Span <float>(_quadVerts), BufferUsageARB.StaticDraw); //Setting buffer data.

        //Initializing a element buffer that holds the index data.
        _qeb = _gl.GenBuffer();                                                                                                    //Creating the buffer.
        _gl.BindBuffer(BufferTargetARB.ElementArrayBuffer, _qeb);                                                                  //Binding the buffer.
        LabelObject(ObjectIdentifier.Buffer, _qeb, "Quad EBO");
        _gl.BufferData(BufferTargetARB.ElementArrayBuffer, indicesSize, new Span <uint>(_quadIndices), BufferUsageARB.StaticDraw); //Setting buffer data.

        //Creating a vertex shader.
        var qvs = _gl.CreateShader(ShaderType.VertexShader);

        LabelObject(ObjectIdentifier.Shader, qvs, "Quad VS");
        _gl.ShaderSource(qvs, Utilities.LoadEmbeddedUtf8String("embedded.basic.vert.glsl"));
        _gl.CompileShader(qvs);
        CheckGl();
        _gl.GetShader(qvs, ShaderParameterName.CompileStatus, out var qvsCompileStatus);

        //Checking the shader for compilation errors.
        var qvsLog            = _gl.GetShaderInfoLog(qvs);
        var qvsLogEmpty       = string.IsNullOrWhiteSpace(qvsLog);
        var qvsCompileSuccess = qvsCompileStatus == (int)GLEnum.True;

        if (!qvsCompileSuccess || !qvsLogEmpty)
        {
            (qvsCompileSuccess ? Console.Out : Console.Error).WriteLine($"{(qvsCompileSuccess ? "Messages" : "Errors")} compiling quad vertex shader\n{qvsLog}");
            if (!qvsCompileSuccess)
            {
                Console.Error.Flush();
                //Debugger.Break();
            }
        }

        CheckGl();

        //Creating a fragment shader.
        var qfs = _gl.CreateShader(ShaderType.FragmentShader);

        LabelObject(ObjectIdentifier.Shader, qfs, "Quad FS");
        _gl.ShaderSource(qfs, Utilities.LoadEmbeddedUtf8String("embedded.basic.frag.glsl"));
        _gl.CompileShader(qfs);
        CheckGl();
        _gl.GetShader(qfs, ShaderParameterName.CompileStatus, out var qfsCompileStatus);

        //Checking the shader for compilation errors.
        var qfsLog            = _gl.GetShaderInfoLog(qfs);
        var qfsLogEmpty       = string.IsNullOrWhiteSpace(qfsLog);
        var qfsCompileSuccess = qfsCompileStatus == (int)GLEnum.True;

        if (!qfsCompileSuccess || !qfsLogEmpty)
        {
            (qfsCompileSuccess ? Console.Out : Console.Error).WriteLine($"{(qfsCompileSuccess ? "Messages" : "Errors")} compiling quad fragment shader\n{qfsLog}");
            if (!qfsCompileSuccess)
            {
                Console.Error.Flush();
                //Debugger.Break();
            }
        }

        CheckGl();

        //Combining the shaders under one shader program.
        _qpg = _gl.CreateProgram();
        LabelObject(ObjectIdentifier.Program, _qpg, "Quad Program");
        _gl.AttachShader(_qpg, qvs);
        _gl.AttachShader(_qpg, qfs);
        _gl.BindAttribLocation(_qpg, 0, "vPos");
        CheckGl();
        _gl.EnableVertexAttribArray(0);
        CheckGl();
        _gl.LinkProgram(_qpg);
        CheckGl();
        _gl.GetProgram(_qpg, ProgramPropertyARB.LinkStatus, out var qpgLinkStatus);

        //Checking the linking for errors.
        var qpgLog         = _gl.GetProgramInfoLog(_qpg);
        var qpgLogEmpty    = string.IsNullOrWhiteSpace(qpgLog);
        var qpgLinkSuccess = qpgLinkStatus == (int)GLEnum.True;

        if (!qpgLinkSuccess || !qpgLogEmpty)
        {
            Console.WriteLine($"{(qpgLinkSuccess ? "Messages" : "Errors")} linking quad shader program:\n{qpgLog}");
        }
        CheckGl();
        _gl.ValidateProgram(_qpg);
        CheckGl();

        _gl.UseProgram(_qpg);
        var vPos = (uint)_gl.GetAttribLocation(_qpg, "vPos");

        CheckGl();
        _gl.VertexAttribPointer(vPos,
                                3, VertexAttribPointerType.Float, false, 0, (void *)0);
        CheckGl();

        //Delete the no longer useful individual shaders;
        _gl.DetachShader(_qpg, qvs);
        _gl.DetachShader(_qpg, qfs);
        _gl.DeleteShader(qvs);
        _gl.DeleteShader(qfs);

        _gpuDriverSite.InitializeShaders();

        var input = _snView.CreateInput();

        foreach (var kb in input.Keyboards)
        {
            kb.KeyDown += KeyDown;
        }

        Console.WriteLine("Loading index.html");
        _ulView.LoadUrl("file:///index.html");
    }
Exemplo n.º 5
0
 public static T1 Load <T1>
     (SearchPathContainer nameContainer, Ultz.SuperInvoke.Loader.LibraryLoader loader) where T1 : NativeAPI =>
 LibraryActivator.CreateInstance <T1>(nameContainer.GetLibraryName(), loader);
Exemplo n.º 6
0
 public static T1 Load <T1>
     (SearchPathContainer nameContainer) where T1 : NativeAPI => LibraryActivator.CreateInstance <T1>
     (nameContainer.GetLibraryName());