public HolofunkForm(bool isSecondaryForm) { _isSecondaryForm = isSecondaryForm; if (!isSecondaryForm) { _primaryForm = this; } // Hardcode to 1080p size of Kinect color buffer for now Size = new Size(1920, 1080); FormClosing += new FormClosingEventHandler(WindowClosing); InitializeComponent(); if (!_isSecondaryForm) { new Thread(GameThread).Start(); while (!_gameStarted) { Thread.Sleep(10); } } Panel gamePanel = new Panel(); gamePanel.Bounds = System.Drawing.Rectangle.FromLTRB(0, 0, ClientSize.Width, ClientSize.Height); gamePanel.Dock = DockStyle.Fill; Controls.Add(gamePanel); // set window { _holofunkGame.Window.IsBorderlessEXT = true; SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo(); SDL.SDL_GetWindowWMInfo(_holofunkGame.Window.Handle, ref info); IntPtr winHandle = info.info.win.window; SetWindowPos( winHandle, Handle, 0, 0, 0, 0, 0x0401 // NOSIZE | SHOWWINDOW ); SetParent(winHandle, gamePanel.Handle); ShowWindow(winHandle, 1); // SHOWNORMAL } }
public void Load() { _recv = OnPluginRecv; _send = OnPluginSend; _getPacketLength = PacketsTable.GetPacketLength; _getPlayerPosition = GetPlayerPosition; _castSpell = GameActions.CastSpell; _getStaticImage = GetStaticImage; _getUoFilePath = GetUOFilePath; _requestMove = RequestMove; _setTitle = SetWindowTitle; SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo(); SDL.SDL_VERSION(out info.version); SDL.SDL_GetWindowWMInfo(SDL.SDL_GL_GetCurrentWindow(), ref info); IntPtr hwnd = IntPtr.Zero; if (info.subsystem == SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS) { hwnd = info.info.win.window; } PluginHeader header = new PluginHeader { ClientVersion = (int)FileManager.ClientVersion, Recv = Marshal.GetFunctionPointerForDelegate(_recv), Send = Marshal.GetFunctionPointerForDelegate(_send), GetPacketLength = Marshal.GetFunctionPointerForDelegate(_getPacketLength), GetPlayerPosition = Marshal.GetFunctionPointerForDelegate(_getPlayerPosition), CastSpell = Marshal.GetFunctionPointerForDelegate(_castSpell), GetStaticImage = Marshal.GetFunctionPointerForDelegate(_getStaticImage), HWND = hwnd, GetUOFilePath = Marshal.GetFunctionPointerForDelegate(_getUoFilePath), RequestMove = Marshal.GetFunctionPointerForDelegate(_requestMove), SetTitle = Marshal.GetFunctionPointerForDelegate(_setTitle) }; void *func = &header; try { IntPtr assptr = Native.LoadLibrary(_path); Log.Message(LogTypes.Trace, $"assembly: {assptr}"); if (assptr == IntPtr.Zero) { throw new Exception("Invalid Assembly, Attempting managed load."); } Log.Message(LogTypes.Trace, $"Searching for 'Install' entry point - {assptr}"); IntPtr installPtr = Native.GetProcessAddress(assptr, "Install"); Log.Message(LogTypes.Trace, $"Entry point: {installPtr}"); if (installPtr == IntPtr.Zero) { throw new Exception("Invalid Entry Point, Attempting managed load."); } Marshal.GetDelegateForFunctionPointer <OnInstall>(installPtr)(func); Console.WriteLine(">>> ADDRESS {0}", header.OnInitialize); } catch { try { var asm = Assembly.LoadFile(_path); var type = asm.GetType("Assistant.Engine"); if (type == null) { Log.Message(LogTypes.Error, "Unable to find Plugin Type, API requires the public class Engine in namespace Assistant."); return; } var meth = type.GetMethod("Install", BindingFlags.Public | BindingFlags.Static); if (meth == null) { Log.Message(LogTypes.Error, "Engine class missing public static Install method Needs 'public static unsafe void Install(PluginHeader *plugin)' "); return; } meth.Invoke(null, new object[] { (IntPtr)func }); } catch (Exception err) { Log.Message(LogTypes.Error, $"Plugin threw an error during Initialization. {err.Message} {err.StackTrace} {err.InnerException?.Message} {err.InnerException?.StackTrace}"); return; } } if (header.OnRecv != IntPtr.Zero) { _onRecv = Marshal.GetDelegateForFunctionPointer <OnPacketSendRecv>(header.OnRecv); } if (header.OnSend != IntPtr.Zero) { _onSend = Marshal.GetDelegateForFunctionPointer <OnPacketSendRecv>(header.OnSend); } if (header.OnHotkeyPressed != IntPtr.Zero) { _onHotkeyPressed = Marshal.GetDelegateForFunctionPointer <OnHotkey>(header.OnHotkeyPressed); } if (header.OnMouse != IntPtr.Zero) { _onMouse = Marshal.GetDelegateForFunctionPointer <OnMouse>(header.OnMouse); } if (header.OnPlayerPositionChanged != IntPtr.Zero) { _onUpdatePlayerPosition = Marshal.GetDelegateForFunctionPointer <OnUpdatePlayerPosition>(header.OnPlayerPositionChanged); } if (header.OnClientClosing != IntPtr.Zero) { _onClientClose = Marshal.GetDelegateForFunctionPointer <OnClientClose>(header.OnClientClosing); } if (header.OnInitialize != IntPtr.Zero) { _onInitialize = Marshal.GetDelegateForFunctionPointer <OnInitialize>(header.OnInitialize); } if (header.OnConnected != IntPtr.Zero) { _onConnected = Marshal.GetDelegateForFunctionPointer <OnConnected>(header.OnConnected); } if (header.OnDisconnected != IntPtr.Zero) { _onDisconnected = Marshal.GetDelegateForFunctionPointer <OnDisconnected>(header.OnDisconnected); } if (header.OnFocusGained != IntPtr.Zero) { _onFocusGained = Marshal.GetDelegateForFunctionPointer <OnFocusGained>(header.OnFocusGained); } if (header.OnFocusLost != IntPtr.Zero) { _onFocusLost = Marshal.GetDelegateForFunctionPointer <OnFocusLost>(header.OnFocusLost); } if (header.Tick != IntPtr.Zero) { _tick = Marshal.GetDelegateForFunctionPointer <OnTick>(header.Tick); } IsValid = true; _onInitialize?.Invoke(); }
public Renderer(GameWindow sdlWindow, int width, int height, RendererFlags flags = RendererFlags.None, RendererType type = RendererType.Default) { window = sdlWindow; // retrieve platform specific data and pass them to bgfx SDL.SDL_SysWMinfo wmi = window.GetPlatformWindowInfo(); PlatformData platformData = new PlatformData(); switch (wmi.subsystem) { case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS: platformData.WindowHandle = wmi.info.win.window; break; case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_X11: platformData.DisplayType = wmi.info.x11.display; platformData.WindowHandle = wmi.info.x11.window; break; case SDL.SDL_SYSWM_TYPE.SDL_SYSWM_COCOA: platformData.WindowHandle = wmi.info.cocoa.window; break; default: throw new ApplicationException("Failed to initialize renderer, unsupported platform detected"); } if (platformData.WindowHandle == IntPtr.Zero) { throw new ApplicationException("Failed to initialize renderer, invalid platform window handle"); } Bgfx.SetPlatformData(platformData); Bgfx.Init((RendererBackend)type); if (width * height <= 0) { Int2 windowSize = window.ClientSize; width = windowSize.x; height = windowSize.y; } Reset(width, height, flags); shaderPath = Path.Combine(Program.basePath, "Shaders"); switch (rendererType) { case RendererType.Direct3D11: shaderPath = Path.Combine(shaderPath, "dx11"); break; case RendererType.Direct3D9: shaderPath = Path.Combine(shaderPath, "dx9"); break; case RendererType.OpenGL: shaderPath = Path.Combine(shaderPath, "opengl"); break; default: throw new ApplicationException("No shader path defined for renderer " + rendererType.ToString()); } spriteRenderer = new SpriteRenderer(this, width, height); defaultProgram = new ShaderProgram( Path.Combine(shaderPath, "default_vs.bin"), Path.Combine(shaderPath, "default_fs.bin")); textureColor = new Uniform("s_texColor", UniformType.Int1); }
private int OnUOAssistMessage(uint msg, int wParam, int lParam) { switch ((UOAMessage)msg) { case UOAMessage.REGISTER: if (_wndRegs.ContainsKey(wParam)) { _wndRegs.Remove(wParam); return(2); } _wndRegs.Add(wParam, new WndRegEnt(wParam, lParam == 1 ? 1 : 0)); if (lParam == 1 && World.InGame) { foreach (Item item in World.Items.Where(s => s.IsMulti)) { PostMessage((IntPtr)wParam, (uint)UOAMessage.ADD_MULTI, (IntPtr)((item.X & 0xFFFF) | ((item.Y & 0xFFFF) << 16)), (IntPtr)(int)item.Graphic); } } return(1); case UOAMessage.COUNT_RESOURCES: break; case UOAMessage.GET_COORDS: if (World.Player != null) { return((World.Player.X & 0xFFFF) | ((World.Player.Y & 0xFFFF) << 16)); } break; case UOAMessage.GET_SKILL: break; case UOAMessage.GET_STAT: if (World.Player == null || wParam < 0 || wParam > 5) { return(0); } switch (wParam) { case 0: return(World.Player.Strength); case 1: return(World.Player.Intelligence); case 2: return(World.Player.Dexterity); case 3: return(World.Player.Weight); case 4: return(World.Player.HitsMax); case 5: return((int)World.Player.TithingPoints); } return(0); case UOAMessage.SET_MACRO: break; case UOAMessage.PLAY_MACRO: break; case UOAMessage.DISPLAY_TEXT: if (World.Player != null) { ushort hue = (ushort)(wParam & 0xFFFF); StringBuilder sb = new StringBuilder(256); if (GlobalGetAtomName((ushort)lParam, sb, 256) == 0) { return(0); } if ((wParam & 0x00010000) != 0) { Chat.HandleMessage(null, sb.ToString(), "System", hue, MessageType.Regular, 3, true); } else { World.Player.AddMessage(MessageType.Regular, sb.ToString(), 3, hue, true); } return(1); } break; case UOAMessage.REQUEST_MULTIS: return(World.Player != null ? 1 : 0); case UOAMessage.ADD_CMD: { var sb = new StringBuilder(256); if (GlobalGetAtomName((ushort)lParam, sb, 256) == 0) { return(0); } if (wParam == 0) { CommandManager.UnRegister(sb.ToString()); return(0); } new WndCmd(_cmdID, (IntPtr)wParam, sb.ToString()); return((int)_cmdID++); } case UOAMessage.GET_UID: return(World.Player != null ? (int)World.Player.Serial.Value : 0); case UOAMessage.GET_SHARDNAME: break; case UOAMessage.ADD_USER_2_PARTY: break; case UOAMessage.GET_UO_HWND: SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo(); SDL.SDL_VERSION(out info.version); SDL.SDL_GetWindowWMInfo(SDL.SDL_GL_GetCurrentWindow(), ref info); IntPtr hwnd = IntPtr.Zero; if (info.subsystem == SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS) { hwnd = info.info.win.window; } return((int)hwnd); case UOAMessage.GET_POISON: return(World.Player != null && World.Player.IsPoisoned ? 1 : 0); case UOAMessage.SET_SKILL_LOCK: break; case UOAMessage.GET_ACCT_ID: break; case UOAMessage.RES_COUNT_DONE: break; case UOAMessage.CAST_SPELL: break; case UOAMessage.LOGIN: break; case UOAMessage.MAGERY_LEVEL: break; case UOAMessage.INT_STATUS: break; case UOAMessage.SKILL_LEVEL: break; case UOAMessage.MACRO_DONE: break; case UOAMessage.LOGOUT: break; case UOAMessage.STR_STATUS: break; case UOAMessage.DEX_STATUS: break; case UOAMessage.ADD_MULTI: break; case UOAMessage.REM_MULTI: break; case UOAMessage.MAP_INFO: break; case UOAMessage.POWERHOUR: break; } return(0); }
public CustomWindow(string class_name) { SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo(); SDL.SDL_VERSION(out info.version); SDL.SDL_GetWindowWMInfo(SDL.SDL_GL_GetCurrentWindow(), ref info); IntPtr hwnd = IntPtr.Zero; if (info.subsystem == SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS) { hwnd = info.info.win.window; } if (class_name == null) { throw new Exception("class_name is null"); } if (class_name == string.Empty) { throw new Exception("class_name is empty"); } m_wnd_proc_delegate = CustomWndProc; // Create WNDCLASS WNDCLASS wind_class = new WNDCLASS { hInstance = hwnd, lpszClassName = class_name, lpfnWndProc = Marshal.GetFunctionPointerForDelegate(m_wnd_proc_delegate) }; ushort class_atom = RegisterClassW(ref wind_class); int last_error = Marshal.GetLastWin32Error(); if (class_atom == 0 && last_error != ERROR_CLASS_ALREADY_EXISTS) { throw new Exception("Could not register window class"); } // Create window m_hwnd = CreateWindowExW( 0, class_name, class_name, 0, 0, 0, 0, 0, IntPtr.Zero, IntPtr.Zero, hwnd, IntPtr.Zero ); if (m_hwnd != IntPtr.Zero) { ShowWindow(m_hwnd, 0); } }
public Form1() { Size = new Size(800, 600); FormClosing += new FormClosingEventHandler(WindowClosing); InitializeComponent(); // start game { new Thread(GameThread).Start(); while (!_gameStarted) { Thread.Sleep(10); } } Panel gamePanel = new Panel(); gamePanel.Bounds = System.Drawing.Rectangle.FromLTRB(0, 0, ClientSize.Width, ClientSize.Height); gamePanel.Dock = DockStyle.Fill; Controls.Add(gamePanel); // set window { _game.Window.IsBorderlessEXT = true; SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo(); SDL.SDL_GetWindowWMInfo(_game.Window.Handle, ref info); IntPtr winHandle = info.info.win.window; SetWindowPos( winHandle, Handle, 0, 0, 0, 0, 0x0401 // NOSIZE | SHOWWINDOW ); SetParent(winHandle, gamePanel.Handle); ShowWindow(winHandle, 1); // SHOWNORMAL } }
public GameView() { MenuStrip menu = new MenuStrip(); menu.Text = "File Menu"; menu.Name = "MainMenu"; menu.Dock = DockStyle.Top; ToolStripMenuItem item = new ToolStripMenuItem("File"); item.DropDownItems.Add("Load", null, (s, e) => LoadROM()); menu.Items.Add(item); this.MainMenuStrip = menu; Controls.Add(menu); windowSize = new Size(screenWidth + textWidth, screenHeight + menu.Height); gamePanel = new Panel(); gamePanel.Size = windowSize; gamePanel.Location = new Point(0, menu.Height); ClientSize = windowSize; FormClosing += new FormClosingEventHandler(WindowClosing); Controls.Add(gamePanel); SDL.SDL_Init(SDL.SDL_INIT_EVERYTHING); SDL_ttf.TTF_Init(); gameWindow = SDL.SDL_CreateWindow("GBEmu", SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, windowSize.Width, windowSize.Height, SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS | SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL); glRenderer = SDL.SDL_CreateRenderer(gameWindow, -1, SDL.SDL_RendererFlags.SDL_RENDERER_ACCELERATED); glFont = SDL_ttf.TTF_OpenFont("assets/arial.ttf", 12); glTexture = SDL.SDL_CreateTexture(glRenderer, SDL.SDL_PIXELFORMAT_RGB24, (int)SDL.SDL_TextureAccess.SDL_TEXTUREACCESS_STREAMING, gbWidth, gbHeight); // Get the Win32 HWND from the SDL2 window SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo(); SDL.SDL_GetWindowWMInfo(gameWindow, ref info); IntPtr winHandle = info.info.win.window; SetWindowPos( winHandle, Handle, 0, 0, 0, 0, 0x0401 // NOSIZE | SHOWWINDOW ); // Attach the SDL2 window to the panel SetParent(winHandle, gamePanel.Handle); ShowWindow(winHandle, 1); // SHOWNORMAL renderCancellationToken = new CancellationTokenSource(); renderTask = Task.Factory.StartNew(async() => { DateTime now = DateTime.Now; DateTime lastExecution = now; TimeSpan elapsedTime = TimeSpan.FromSeconds(0); SDL.SDL_Event e; try { while (true) { now = DateTime.Now; elapsedTime = now - lastExecution; lastExecution = now; PrintCPU(); while (SDL.SDL_PollEvent(out e) != 0) { switch (e.type) { case SDL.SDL_EventType.SDL_KEYDOWN: switch (e.key.keysym.sym) { case SDL.SDL_Keycode.SDLK_SPACE: if (play) { break; } do { bus.GetCPU().Clock(); } while (bus.GetCPU().Complete); break; case SDL.SDL_Keycode.SDLK_p: play = !play; break; } break; } } if (play) { do { bus.GetCPU().Clock(); } while (bus.GetCPU().Complete); } Render(elapsedTime.TotalMilliseconds); await Task.Delay(30); } } catch (Exception ex) { Log.Error(ex, "Rendering error"); MethodInvoker methodInvokerDelegate = delegate() { this.Close(); }; this.Invoke(methodInvokerDelegate); } }, renderCancellationToken.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
/// <summary> /// Initializes a new instance of the <see cref="Window"/> class with <paramref name="title"/> as the title of the Window. /// </summary> /// <param name="title">Title of the window, see Text property.</param> public Window(string title, int width, int height, bool fullscreen) { var flags = SDL.SDL_WindowFlags.SDL_WINDOW_VULKAN | SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI; // don't try using a resolution too large SDL.SDL_GetDesktopDisplayMode(0, out SDL.SDL_DisplayMode mode); if (mode.w <= width || mode.h <= height) { flags |= SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP; width = mode.w; height = mode.h; } else if (fullscreen) { flags |= SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN; } OriginalSize = new Size2(width, height); try { // Create the SDL window and then extract the native handle. SdlHandle = SDL.SDL_CreateWindow(title, SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, width, height, flags); } catch (Exception e) { GenerateCreationError(e); } if (SdlHandle == IntPtr.Zero) { GenerateCreationError(); } else { SDL.SDL_SysWMinfo info = default(SDL.SDL_SysWMinfo); try { SDL.SDL_VERSION(out info.version); if (SDL.SDL_GetWindowWMInfo(SdlHandle, ref info) == SDL.SDL_bool.SDL_FALSE) { GenerateCreationError(); } } catch (Exception e) { GenerateCreationError(e); } #if XENKO_PLATFORM_WINDOWS_DESKTOP Handle = info.info.win.window; #elif XENKO_PLATFORM_LINUX Handle = info.info.x11.window; Display = info.info.x11.display; #elif XENKO_PLATFORM_MACOS Handle = info.info.cocoa.window; #endif Application.RegisterWindow(this); Application.ProcessEvents(); } }
public SDL2WindowExample() { // This is what we're going to attach the SDL2 window to gamePanel = new Panel(); gamePanel.Size = new Size(640, 480); gamePanel.Location = new Point(80, 10); // Make the WinForms window Size = new Size(800, 600); FormClosing += new FormClosingEventHandler(WindowClosing); Button button = new Button(); button.Text = "Whatever"; button.Location = new Point( (Size.Width / 2) - (button.Size.Width / 2), gamePanel.Location.Y + gamePanel.Size.Height + 10 ); button.Click += new EventHandler(ClickedButton); Controls.Add(button); Controls.Add(gamePanel); // IGNORE MEEEEE random = new Random(); SDL.SDL_Init(SDL.SDL_INIT_VIDEO); gameWindow = SDL.SDL_CreateWindow( String.Empty, 0, 0, gamePanel.Size.Width, gamePanel.Size.Height, SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS | SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL ); glContext = SDL.SDL_GL_CreateContext(gameWindow); glViewport = (Viewport)Marshal.GetDelegateForFunctionPointer( SDL.SDL_GL_GetProcAddress("glViewport"), typeof(Viewport) ); glClearColor = (ClearColor)Marshal.GetDelegateForFunctionPointer( SDL.SDL_GL_GetProcAddress("glClearColor"), typeof(ClearColor) ); glClear = (Clear)Marshal.GetDelegateForFunctionPointer( SDL.SDL_GL_GetProcAddress("glClear"), typeof(Clear) ); glViewport(0, 0, gamePanel.Size.Width, gamePanel.Size.Height); glClearColor(1.0f, 0.0f, 0.0f, 1.0f); glClear(0x4000); SDL.SDL_GL_SwapWindow(gameWindow); // Get the Win32 HWND from the SDL2 window SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo(); SDL.SDL_GetWindowWMInfo(gameWindow, ref info); IntPtr winHandle = info.info.win.window; // Move the SDL2 window to 0, 0 SetWindowPos( winHandle, Handle, 0, 0, 0, 0, 0x0401 // NOSIZE | SHOWWINDOW ); // Attach the SDL2 window to the panel SetParent(winHandle, gamePanel.Handle); ShowWindow(winHandle, 1); // SHOWNORMAL }
public void RunGame(Game game, bool borderless = false, Action a = null) { NativeLibraryLoader.SetNativeLibaryFolder(); SDL.SDL_Init(SDL.SDL_INIT_VIDEO); var imgFlags = SDL_image.IMG_InitFlags.IMG_INIT_PNG | SDL_image.IMG_InitFlags.IMG_INIT_JPG; if ((SDL_image.IMG_Init(imgFlags) > 0 & imgFlags > 0) == false) { Console.WriteLine("SDL_image could not initialize! SDL_image Error: {0}", SDL.SDL_GetError()); return; } var cpus = SDL.SDL_GetCPUCount(); Console.WriteLine("SYSTEM: CPU Count:" + cpus); var ramMb = SDL.SDL_GetSystemRAM(); Console.WriteLine("SYSTEM: RAM MB:" + ramMb); // Init OpenAL var audioDevice = new AudioDevice(); audioDevice.Initalise(); GameInput = new GameInput(); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_PROFILE_MASK, SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_CORE); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DOUBLEBUFFER, 1); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_MULTISAMPLEBUFFERS, 1); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_MULTISAMPLESAMPLES, 8); // TODO Register the Audio device in the dependancy locator var windowStyle = /*SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS |*/ SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE | SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL; if (borderless == true) { windowStyle = windowStyle | SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS; } WindowPtr = SDL.SDL_CreateWindow(m_WindowName, SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, ScreenWidth, ScreenHeight, windowStyle); OpenGLPtr = SDL.SDL_GL_CreateContext(WindowPtr); // Get the Win32 HWND from the SDL2 window SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo(); SDL.SDL_GetWindowWMInfo(WindowPtr, ref info); Win32Ptr = info.info.win.window; OpenGL.GlBindings.InitaliseOpenGLEntryPoints(); var graphicsDevice = new OpenGLGraphicsDevice(OpenGLPtr); SetVSync(VSyncStatus.VSYNC_ENABLE); GraphicsDevice = graphicsDevice; AudioDevice = audioDevice; game.Init(audioDevice, graphicsDevice, this, GameInput); // TODO Rename to OnLoadedWindow if (a != null) { a.Invoke(); } // TODO Embed these as resources QuadBatchShader = ShaderProgram.CreateFromFile("Resources/Shaders/Vertex/v.quadbatch.glsl", "Resources/Shaders/Fragment/f.quadbatch.glsl"); FullScreenShader = ShaderProgram.CreateFromFile("Resources/Shaders/Vertex/v.fullscreenquad.glsl", "Resources/Shaders/Fragment/f.fullscreenquad.glsl"); using (TracedStopwatch.Start("Loading Game Resources")) { game.Load(); } var stopwatch = new Stopwatch(); var isRunning = true; while (isRunning) { // TODO Reset stats counters stopwatch.Restart(); ProcessEvents(); if (this.HasQuit) { break; } game.Update(); game.UpdateCoroutines(); GraphicsDevice.Enable(OpenGL.Enable.GL_DEPTH_TEST); game.RenderScene(); GraphicsDevice.Disable(OpenGL.Enable.GL_DEPTH_TEST); game.Render2D(); // TODO Multimedia Timer or sleep for time... // TODO Stats for frame time and fps // Update window with OpenGL rendering SDL.SDL_GL_SwapWindow(WindowPtr); GameInput.Swap(); stopwatch.Stop(); GameTime.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds; GameTime.ElapsedSeconds = stopwatch.Elapsed.TotalSeconds; GameTime.TotalSeconds += GameTime.ElapsedSeconds; } // Unload Resources SDL.SDL_Quit(); }
public bool GetWMInfo(ref SDL.SDL_SysWMinfo Info) { return(SDL.SDL_GetWindowWMInfo(myPtr, ref Info) != SDL.SDL_bool.SDL_FALSE); }
bool INTERNAL_SDLThread_InitWindow() { Console.Write("INTERNAL_SDLThread_InitWindow()\n"); // Create the SDL window _sdlWindow = SDL.SDL_CreateWindow( _windowTitle, SDL.SDL_WINDOWPOS_UNDEFINED, SDL.SDL_WINDOWPOS_UNDEFINED, _windowSize.Width, _windowSize.Height, SDL.SDL_WindowFlags.SDL_WINDOW_HIDDEN | SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE | (_anchored ? SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS | SDL.SDL_WindowFlags.SDL_WINDOW_SKIP_TASKBAR : (SDL.SDL_WindowFlags) 0) ); if (_sdlWindow == IntPtr.Zero) { return(false); } //throw new Exception( string.Format( "Unable to create SDL_Window!\n\n{0}", SDL.SDL_GetError() ) ); _sdlWindow_PixelFormat = SDL.SDL_GetWindowPixelFormat(_sdlWindow); if (_sdlWindow_PixelFormat == SDL.SDL_PIXELFORMAT_UNKNOWN) { return(false); } //throw new Exception( string.Format( "Unable to obtain SDL_Window pixel format!\n\n{0}", SDL.SDL_GetError() ) ); if (SDL.SDL_PixelFormatEnumToMasks( _sdlWindow_PixelFormat, out _sdlWindow_bpp, out _sdlWindow_Rmask, out _sdlWindow_Gmask, out _sdlWindow_Bmask, out _sdlWindow_Amask) == SDL.SDL_bool.SDL_FALSE) { return(false); } //throw new Exception( string.Format( "Unable to obtain SDL_Window pixel format bitmasks!\n\n{0}", SDL.SDL_GetError() ) ); // Get the Win32 HWND from the SDL window var sysWMinfo = new SDL.SDL_SysWMinfo(); SDL.SDL_GetWindowWMInfo(_sdlWindow, ref sysWMinfo); _sdlWindowHandle = sysWMinfo.info.win.window; if (_anchored) { // Time to anchor the window to the control... // Tell SDL we don't want a border... SDL.SDL_SetWindowBordered(_sdlWindow, SDL.SDL_bool.SDL_FALSE); // ...Aero doesn't always listen to SDL so force it through the Windows API var winStyle = (WinAPI.WindowStyleFlags)WinAPI.GetWindowLongPtr(_sdlWindowHandle, WinAPI.WindowLongIndex.GWL_STYLE); winStyle &= ~WinAPI.WindowStyleFlags.WS_BORDER; winStyle &= ~WinAPI.WindowStyleFlags.WS_SIZEBOX; winStyle &= ~WinAPI.WindowStyleFlags.WS_DLGFRAME; WinAPI.SetWindowLongPtr(_sdlWindowHandle, WinAPI.WindowLongIndex.GWL_STYLE, (uint)winStyle); // Move the SDL window to 0, 0 WinAPI.SetWindowPos( _sdlWindowHandle, _mainFormHandle, 0, 0, 0, 0, WinAPI.WindowSWPFlags.SWP_NOSIZE | WinAPI.WindowSWPFlags.SWP_SHOWWINDOW ); // Anchor the SDL_Window to the control WinAPI.SetParent(_sdlWindowHandle, _targetControlHandle); } else { // Make the SDL_Window look like a tool window var winStyle = (WinAPI.WindowStyleFlags)WinAPI.GetWindowLongPtr(_sdlWindowHandle, WinAPI.WindowLongIndex.GWL_EXSTYLE); winStyle |= WinAPI.WindowStyleFlags.WS_EX_TOOLWINDOW; WinAPI.SetWindowLongPtr(_sdlWindowHandle, WinAPI.WindowLongIndex.GWL_EXSTYLE, (uint)winStyle); // ShowWindow to force all the changes and present the SDL_Window //WinAPI.ShowWindow( _sdlWindowHandle, WinAPI.ShowWindowFlags.SW_SHOWNORMAL ); SDL.SDL_ShowWindow(_sdlWindow); } _windowResetRequired = false; _rendererResetRequired = true; return(true); }
public void Load() { _recv = OnPluginRecv; _send = OnPluginSend; _recv_new = OnPluginRecv_new; _send_new = OnPluginSend_new; _getPacketLength = PacketsTable.GetPacketLength; _getPlayerPosition = GetPlayerPosition; _castSpell = GameActions.CastSpell; _getStaticImage = GetStaticImage; _getUoFilePath = GetUOFilePath; _requestMove = RequestMove; _setTitle = SetWindowTitle; _get_static_data = GetStaticData; _get_tile_data = GetTileData; _get_cliloc = GetCliloc; SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo(); SDL.SDL_VERSION(out info.version); SDL.SDL_GetWindowWMInfo(Client.Game.Window.Handle, ref info); IntPtr hwnd = IntPtr.Zero; if (info.subsystem == SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS) { hwnd = info.info.win.window; } PluginHeader header = new PluginHeader { ClientVersion = (int)Client.Version, Recv = Marshal.GetFunctionPointerForDelegate(_recv), Send = Marshal.GetFunctionPointerForDelegate(_send), GetPacketLength = Marshal.GetFunctionPointerForDelegate(_getPacketLength), GetPlayerPosition = Marshal.GetFunctionPointerForDelegate(_getPlayerPosition), CastSpell = Marshal.GetFunctionPointerForDelegate(_castSpell), GetStaticImage = Marshal.GetFunctionPointerForDelegate(_getStaticImage), HWND = hwnd, GetUOFilePath = Marshal.GetFunctionPointerForDelegate(_getUoFilePath), RequestMove = Marshal.GetFunctionPointerForDelegate(_requestMove), SetTitle = Marshal.GetFunctionPointerForDelegate(_setTitle), Recv_new = Marshal.GetFunctionPointerForDelegate(_recv_new), Send_new = Marshal.GetFunctionPointerForDelegate(_send_new), SDL_Window = Client.Game.Window.Handle, GetStaticData = Marshal.GetFunctionPointerForDelegate(_get_static_data), GetTileData = Marshal.GetFunctionPointerForDelegate(_get_tile_data), GetCliloc = Marshal.GetFunctionPointerForDelegate(_get_cliloc) }; void *func = &header; if (Environment.OSVersion.Platform != PlatformID.Unix && Environment.OSVersion.Platform != PlatformID.MacOSX) { UnblockPath(Path.GetDirectoryName(PluginPath)); } try { IntPtr assptr = Native.LoadLibrary(PluginPath); Log.Trace($"assembly: {assptr}"); if (assptr == IntPtr.Zero) { throw new Exception("Invalid Assembly, Attempting managed load."); } Log.Trace($"Searching for 'Install' entry point - {assptr}"); IntPtr installPtr = Native.GetProcessAddress(assptr, "Install"); Log.Trace($"Entry point: {installPtr}"); if (installPtr == IntPtr.Zero) { throw new Exception("Invalid Entry Point, Attempting managed load."); } Marshal.GetDelegateForFunctionPointer <OnInstall>(installPtr)(func); Console.WriteLine(">>> ADDRESS {0}", header.OnInitialize); } catch { try { Assembly asm = Assembly.LoadFile(PluginPath); Type type = asm.GetType("Assistant.Engine"); if (type == null) { Log.Error("Unable to find Plugin Type, API requires the public class Engine in namespace Assistant."); return; } MethodInfo meth = type.GetMethod("Install", BindingFlags.Public | BindingFlags.Static); if (meth == null) { Log.Error("Engine class missing public static Install method Needs 'public static unsafe void Install(PluginHeader *plugin)' "); return; } meth.Invoke(null, new object[] { (IntPtr)func }); } catch (Exception err) { Log.Error($"Plugin threw an error during Initialization. {err.Message} {err.StackTrace} {err.InnerException?.Message} {err.InnerException?.StackTrace}"); return; } } if (header.OnRecv != IntPtr.Zero) { _onRecv = Marshal.GetDelegateForFunctionPointer <OnPacketSendRecv>(header.OnRecv); } if (header.OnSend != IntPtr.Zero) { _onSend = Marshal.GetDelegateForFunctionPointer <OnPacketSendRecv>(header.OnSend); } if (header.OnHotkeyPressed != IntPtr.Zero) { _onHotkeyPressed = Marshal.GetDelegateForFunctionPointer <OnHotkey>(header.OnHotkeyPressed); } if (header.OnMouse != IntPtr.Zero) { _onMouse = Marshal.GetDelegateForFunctionPointer <OnMouse>(header.OnMouse); } if (header.OnPlayerPositionChanged != IntPtr.Zero) { _onUpdatePlayerPosition = Marshal.GetDelegateForFunctionPointer <OnUpdatePlayerPosition>(header.OnPlayerPositionChanged); } if (header.OnClientClosing != IntPtr.Zero) { _onClientClose = Marshal.GetDelegateForFunctionPointer <OnClientClose>(header.OnClientClosing); } if (header.OnInitialize != IntPtr.Zero) { _onInitialize = Marshal.GetDelegateForFunctionPointer <OnInitialize>(header.OnInitialize); } if (header.OnConnected != IntPtr.Zero) { _onConnected = Marshal.GetDelegateForFunctionPointer <OnConnected>(header.OnConnected); } if (header.OnDisconnected != IntPtr.Zero) { _onDisconnected = Marshal.GetDelegateForFunctionPointer <OnDisconnected>(header.OnDisconnected); } if (header.OnFocusGained != IntPtr.Zero) { _onFocusGained = Marshal.GetDelegateForFunctionPointer <OnFocusGained>(header.OnFocusGained); } if (header.OnFocusLost != IntPtr.Zero) { _onFocusLost = Marshal.GetDelegateForFunctionPointer <OnFocusLost>(header.OnFocusLost); } if (header.Tick != IntPtr.Zero) { _tick = Marshal.GetDelegateForFunctionPointer <OnTick>(header.Tick); } if (header.OnRecv_new != IntPtr.Zero) { _onRecv_new = Marshal.GetDelegateForFunctionPointer <OnPacketSendRecv_new>(header.OnRecv_new); } if (header.OnSend_new != IntPtr.Zero) { _onSend_new = Marshal.GetDelegateForFunctionPointer <OnPacketSendRecv_new>(header.OnSend_new); } if (header.OnDrawCmdList != IntPtr.Zero) { _draw_cmd_list = Marshal.GetDelegateForFunctionPointer <OnDrawCmdList>(header.OnDrawCmdList); } if (header.OnWndProc != IntPtr.Zero) { _on_wnd_proc = Marshal.GetDelegateForFunctionPointer <OnWndProc>(header.OnWndProc); } IsValid = true; if (_onInitialize != null) { _onInitialize(); } }
public void Load() { _recv = OnPluginRecv; _send = OnPluginSend; _getPacketLength = PacketsTable.GetPacketLength; _getPlayerPosition = GetPlayerPosition; _castSpell = GameActions.CastSpell; _getStaticImage = GetStaticImage; _getUoFilePath = GetUOFilePath; IntPtr assptr = SDL2EX.SDL_LoadObject(_path); Log.Message(LogTypes.Trace, $"assembly: {assptr}"); if (assptr == IntPtr.Zero) { Log.Message(LogTypes.Error, "Invalid assemlby."); return; } Log.Message(LogTypes.Trace, $"Searching for 'Install' entry point - {assptr}"); IntPtr installPtr = SDL2EX.SDL_LoadFunction(assptr, "Install"); Log.Message(LogTypes.Trace, $"Entry point: {installPtr}"); if (installPtr == IntPtr.Zero) { Log.Message(LogTypes.Error, "Invalid entry point."); return; } //IntPtr headerPtr = Marshal.AllocHGlobal(4 + 8 * 18); // 256 ? //Marshal.WriteInt32(headerPtr, (int)FileManager.ClientVersion); //Marshal.WriteIntPtr(headerPtr, Marshal.GetFunctionPointerForDelegate(_recv)); //Marshal.WriteIntPtr(headerPtr, Marshal.GetFunctionPointerForDelegate(_send)); //Marshal.WriteIntPtr(headerPtr, Marshal.GetFunctionPointerForDelegate(_getPacketLength)); //Marshal.WriteIntPtr(headerPtr, Marshal.GetFunctionPointerForDelegate(_getPlayerPosition)); //Marshal.WriteIntPtr(headerPtr, Marshal.GetFunctionPointerForDelegate(_castSpell)); //Marshal.WriteIntPtr(headerPtr, Marshal.GetFunctionPointerForDelegate(_getStaticImage)); //Marshal.WriteIntPtr(headerPtr, SDL.SDL_GL_GetCurrentWindow()); //Marshal.WriteIntPtr(headerPtr, Marshal.GetFunctionPointerForDelegate(_getUoFilePath)); SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo(); SDL.SDL_VERSION(out info.version); SDL.SDL_GetWindowWMInfo(SDL.SDL_GL_GetCurrentWindow(), ref info); IntPtr hwnd = IntPtr.Zero; if (info.subsystem == SDL.SDL_SYSWM_TYPE.SDL_SYSWM_WINDOWS) { hwnd = info.info.win.window; } PluginHeader header = new PluginHeader { ClientVersion = (int)FileManager.ClientVersion, Recv = Marshal.GetFunctionPointerForDelegate(_recv), Send = Marshal.GetFunctionPointerForDelegate(_send), GetPacketLength = Marshal.GetFunctionPointerForDelegate(_getPacketLength), GetPlayerPosition = Marshal.GetFunctionPointerForDelegate(_getPlayerPosition), CastSpell = Marshal.GetFunctionPointerForDelegate(_castSpell), GetStaticImage = Marshal.GetFunctionPointerForDelegate(_getStaticImage), HWND = hwnd, GetUOFilePath = Marshal.GetFunctionPointerForDelegate(_getUoFilePath) }; void *func = &header; Marshal.GetDelegateForFunctionPointer <OnInstall>(installPtr)(ref func); if (header.OnRecv != IntPtr.Zero) { _onRecv = Marshal.GetDelegateForFunctionPointer <OnPacketSendRecv>(header.OnRecv); } if (header.OnSend != IntPtr.Zero) { _onSend = Marshal.GetDelegateForFunctionPointer <OnPacketSendRecv>(header.OnSend); } if (header.OnHotkeyPressed != IntPtr.Zero) { _onHotkeyPressed = Marshal.GetDelegateForFunctionPointer <OnHotkey>(header.OnHotkeyPressed); } if (header.OnMouse != IntPtr.Zero) { _onMouse = Marshal.GetDelegateForFunctionPointer <OnMouse>(header.OnMouse); } if (header.OnPlayerPositionChanged != IntPtr.Zero) { _onUpdatePlayerPosition = Marshal.GetDelegateForFunctionPointer <OnUpdatePlayerPosition>(header.OnPlayerPositionChanged); } if (header.OnClientClosing != IntPtr.Zero) { _onClientClose = Marshal.GetDelegateForFunctionPointer <OnClientClose>(header.OnClientClosing); } if (header.OnInitialize != IntPtr.Zero) { _onInitialize = Marshal.GetDelegateForFunctionPointer <OnInitialize>(header.OnInitialize); } if (header.OnConnected != IntPtr.Zero) { _onConnected = Marshal.GetDelegateForFunctionPointer <OnConnected>(header.OnConnected); } if (header.OnDisconnected != IntPtr.Zero) { _onDisconnected = Marshal.GetDelegateForFunctionPointer <OnDisconnected>(header.OnDisconnected); } if (header.OnFocusGained != IntPtr.Zero) { _onFocusGained = Marshal.GetDelegateForFunctionPointer <OnFocusGained>(header.OnFocusGained); } if (header.OnFocusLost != IntPtr.Zero) { _onFocusLost = Marshal.GetDelegateForFunctionPointer <OnFocusLost>(header.OnFocusLost); } IsValid = true; //Marshal.FreeHGlobal(headerPtr); _onInitialize?.Invoke(); }
private static void Main(string[] args) { var platform = "x64"; if (IntPtr.Size == 4) { platform = "x86"; } NativeMethods.LoadLibrary($"{platform}/SDL2.dll"); Bgfx.InitializeLibrary(); ushort resolutionWidth = 800; ushort resolutionHeight = 600; var windowhandle = SDL.SDL_CreateWindow("hello", 10, 10, resolutionWidth, resolutionHeight, SDL.SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI); var wm = new SDL.SDL_SysWMinfo(); SDL.SDL_GetWindowWMInfo(windowhandle, ref wm); Bgfx.SetPlatformData(wm.info.win.window); var init = Bgfx.Initialize(resolutionWidth, resolutionHeight, Bgfx.RendererType.DIRECT_3D11); ImGui.SetCurrentContext(ImGui.CreateContext()); var IO = ImGui.GetIO(); IO.ImeWindowHandle = wm.info.win.window; //IO.BackendFlags |= ImGuiBackendFlags.HasMouseCursors; // We can honor GetMouseCursor() values (optional) //IO.BackendFlags |= ImGuiBackendFlags.HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) //IO.BackendPlatformName = new NullTerminatedString("imgui_impl_win32".ToCharArray()); IO.KeyMap[(int)ImGuiKey.Tab] = (int)SDL.SDL_Scancode.SDL_SCANCODE_TAB; IO.KeyMap[(int)ImGuiKey.LeftArrow] = (int)SDL.SDL_Scancode.SDL_SCANCODE_LEFT; IO.KeyMap[(int)ImGuiKey.RightArrow] = (int)SDL.SDL_Scancode.SDL_SCANCODE_RIGHT; IO.KeyMap[(int)ImGuiKey.UpArrow] = (int)SDL.SDL_Scancode.SDL_SCANCODE_UP; IO.KeyMap[(int)ImGuiKey.DownArrow] = (int)SDL.SDL_Scancode.SDL_SCANCODE_DOWN; IO.KeyMap[(int)ImGuiKey.PageUp] = (int)SDL.SDL_Scancode.SDL_SCANCODE_PAGEUP; IO.KeyMap[(int)ImGuiKey.PageDown] = (int)SDL.SDL_Scancode.SDL_SCANCODE_PAGEDOWN; IO.KeyMap[(int)ImGuiKey.Home] = (int)SDL.SDL_Scancode.SDL_SCANCODE_HOME; IO.KeyMap[(int)ImGuiKey.End] = (int)SDL.SDL_Scancode.SDL_SCANCODE_END; IO.KeyMap[(int)ImGuiKey.Insert] = (int)SDL.SDL_Scancode.SDL_SCANCODE_INSERT; IO.KeyMap[(int)ImGuiKey.Delete] = (int)SDL.SDL_Scancode.SDL_SCANCODE_DELETE; IO.KeyMap[(int)ImGuiKey.Backspace] = (int)SDL.SDL_Scancode.SDL_SCANCODE_BACKSPACE; IO.KeyMap[(int)ImGuiKey.Space] = (int)SDL.SDL_Scancode.SDL_SCANCODE_SPACE; IO.KeyMap[(int)ImGuiKey.Enter] = (int)SDL.SDL_Scancode.SDL_SCANCODE_KP_ENTER; IO.KeyMap[(int)ImGuiKey.Escape] = (int)SDL.SDL_Scancode.SDL_SCANCODE_ESCAPE; IO.KeyMap[(int)ImGuiKey.KeyPadEnter] = (int)SDL.SDL_Scancode.SDL_SCANCODE_RETURN; IO.KeyMap[(int)ImGuiKey.A] = (int)SDL.SDL_Scancode.SDL_SCANCODE_A; IO.KeyMap[(int)ImGuiKey.C] = (int)SDL.SDL_Scancode.SDL_SCANCODE_C; IO.KeyMap[(int)ImGuiKey.V] = (int)SDL.SDL_Scancode.SDL_SCANCODE_V; IO.KeyMap[(int)ImGuiKey.X] = (int)SDL.SDL_Scancode.SDL_SCANCODE_X; IO.KeyMap[(int)ImGuiKey.Y] = (int)SDL.SDL_Scancode.SDL_SCANCODE_Y; IO.KeyMap[(int)ImGuiKey.Z] = (int)SDL.SDL_Scancode.SDL_SCANCODE_Z; IO.Fonts.AddFontDefault(); IO.Fonts.GetTexDataAsRGBA32(out IntPtr pixels, out var fwidth, out var fheight); IO.Fonts.SetTexID(new IntPtr(Bgfx.CreateTexture2D((ushort)fwidth, (ushort)fheight, false, 1, (Bgfx.TextureFormat)Bgfx.TextureFormat.RGBA8, (Bgfx.SamplerFlags.U_CLAMP | Bgfx.SamplerFlags.V_CLAMP | Bgfx.SamplerFlags.MIN_POINT | Bgfx.SamplerFlags.MAG_POINT | Bgfx.SamplerFlags.MIP_POINT), Bgfx.MakeRef(pixels, (uint)(4 * fwidth * fheight))).Idx)); Bgfx.SetViewClear(0, (ushort)(Bgfx.ClearFlags.COLOR | Bgfx.ClearFlags.DEPTH), 0x6495edff, 0, 0); Bgfx.SetViewMode(0, Bgfx.ViewMode.SEQUENTIAL); Bgfx.SetViewMode(255, Bgfx.ViewMode.SEQUENTIAL); Bgfx.SetDebug(Bgfx.DebugFlags.NONE); Bgfx.Reset(resolutionWidth, resolutionHeight, Bgfx.ResetFlags.VSYNC | Bgfx.ResetFlags.MSAA_X4, init.format); var running = true; var bgfxcaps = Bgfx.GetCaps(); mtxOrtho(out var ortho, 0, resolutionWidth, resolutionHeight, 0, 0, 1000.0f, 0, bgfxcaps.Homogenousdepth); var ImguiVertexLayout = new Bgfx.VertexLayout(); ImguiVertexLayout.Begin(Bgfx.RendererType.NOOP); ImguiVertexLayout.Add(Bgfx.Attrib.POSITION, Bgfx.AttribType.FLOAT, 2, false, false); ImguiVertexLayout.Add(Bgfx.Attrib.TEX_COORD0, Bgfx.AttribType.FLOAT, 2, false, false); ImguiVertexLayout.Add(Bgfx.Attrib.COLOR0, Bgfx.AttribType.UINT8, 4, true, false); ImguiVertexLayout.End(); var WhitePixelTexture = Bgfx.CreateTexture2D(1, 1, false, 1, Bgfx.TextureFormat.RGBA8, Bgfx.SamplerFlags.V_CLAMP | Bgfx.SamplerFlags.U_CLAMP | Bgfx.SamplerFlags.MIN_POINT | Bgfx.SamplerFlags.MAG_POINT | Bgfx.SamplerFlags.MIP_POINT, new uint[] { 0x0000ffff }); var TextureUniform = Bgfx.CreateUniform("s_texture", Bgfx.UniformType.SAMPLER, 1); var ImGuiShader = LoadEffect("vs_imgui.bin", "fs_imgui.bin"); while (running) { SDL.SDL_PollEvent(out var Event); if (Event.window.type == SDL.SDL_EventType.SDL_QUIT) { running = false; } var mouseState = SDL.SDL_GetMouseState(out var mouseX, out var mouseY); IO.MouseDown[0] = (mouseState & SDL.SDL_BUTTON(SDL.SDL_BUTTON_LEFT)) != 0; IO.MouseDown[1] = (mouseState & SDL.SDL_BUTTON(SDL.SDL_BUTTON_RIGHT)) != 0; IO.MouseDown[2] = (mouseState & SDL.SDL_BUTTON(SDL.SDL_BUTTON_MIDDLE)) != 0; SDL.SDL_GetWindowPosition(windowhandle, out var wx, out var wy); SDL.SDL_GetGlobalMouseState(out mouseX, out mouseY); mouseX -= wx; mouseY -= wy; IO.MousePosPrev = IO.MousePos; IO.MousePos = new Vector2(mouseX, mouseY); ImGui.NewFrame(); //ImGui.SetNextWindowSize(new Vector2(200); if (ImGui.Begin("test")) { if (ImGui.Button("click OS popup")) { SDL.SDL_ShowSimpleMessageBox(SDL.SDL_MessageBoxFlags.SDL_MESSAGEBOX_INFORMATION, "Cliked Button", "Click Message", windowhandle); } if (ImGui.Button("modal popup")) { ImGui.OpenPopup("modal popup"); } ImGui.Text("Hello"); if (ImGui.BeginPopupModal("modal popup")) { if (ImGui.Button("clicked")) { ImGui.CloseCurrentPopup(); } ImGui.EndPopup(); } } ImGui.End(); ImGui.EndFrame(); ImGui.Render(); Bgfx.SetViewRect(0, 0, 0, resolutionWidth, resolutionHeight); Bgfx.SetViewRect(255, 0, 0, resolutionWidth, resolutionHeight); IO.DisplaySize = new Vector2(resolutionWidth, resolutionHeight); IO.DisplayFramebufferScale = new Vector2(1); Bgfx.Touch(0); { var drawdata = ImGui.GetDrawData(); ushort viewID = 0; Bgfx.SetViewTransform(viewID, null, ortho); { // Render command lists for (int ii = 0, num = drawdata.CmdListsCount; ii < num; ++ii) { var drawList = drawdata.CmdListsRange[ii]; var numVertices = drawList.VtxBuffer.Size; var numIndices = drawList.IdxBuffer.Size; var tib = Bgfx.AllocateTransientIndexBuffer((uint)numIndices); var tvb = Bgfx.AllocateTransientVertexBuffer((uint)numVertices, ImguiVertexLayout); tvb.CopyIntoBuffer(drawList.VtxBuffer.Data, (uint)numVertices * (uint)Unsafe.SizeOf <ImDrawVert>()); tib.CopyIntoBuffer(drawList.IdxBuffer.Data, (uint)numIndices * (uint)Unsafe.SizeOf <ushort>()); uint offset = 0; for (int i = 0; i < drawList.CmdBuffer.Size; i++) { var cmd = drawList.CmdBuffer[i]; if (cmd.UserCallback != IntPtr.Zero) { // cmd->UserCallback(drawList, cmd); } else if (cmd.ElemCount > 0) { var state = Bgfx.StateFlags.WRITE_RGB | Bgfx.StateFlags.WRITE_A | Bgfx.StateFlags.MSAA ; var texHandle = new Bgfx.TextureHandle(); if (cmd.TextureId.ToInt32() != 0) { texHandle.Idx = (ushort)cmd.TextureId.ToInt32(); } else { texHandle.Idx = WhitePixelTexture.Idx; } state |= Bgfx.STATE_BLEND_FUNC(Bgfx.StateFlags.BLEND_SRC_ALPHA, Bgfx.StateFlags.BLEND_INV_SRC_ALPHA); ushort xx = (ushort)((cmd.ClipRect.X > 0.0f ? cmd.ClipRect.X : 0.0f)); ushort yy = (ushort)((cmd.ClipRect.Y > 0.0f ? cmd.ClipRect.Y : 0.0f)); ushort zz = (ushort)((cmd.ClipRect.Z > 65535.0f ? 65535.0f : cmd.ClipRect.Z) - xx); ushort ww = (ushort)((cmd.ClipRect.W > 65535.0f ? 65535.0f : cmd.ClipRect.W) - yy); Bgfx.SetScissor(xx, yy, zz, ww); Bgfx.SetState(state, 0); Bgfx.SetTexture(0, TextureUniform, texHandle); Bgfx.SetTransientVertexBuffer(0, tvb, 0, (uint)numVertices); Bgfx.SetTransientIndexBuffer(tib, offset, cmd.ElemCount); Bgfx.Submit(viewID, ImGuiShader.program, 0, false); } offset += cmd.ElemCount; } } } } Bgfx.Frame(false); } }