GetIO() public static method

public static GetIO ( ) : IO
return IO
Example #1
0
        private static void SetOpenTKKeyMappings()
        {
            IO io = ImGui.GetIO();

            io.KeyMap[GuiKey.Tab]        = (int)Keys.Tab;
            io.KeyMap[GuiKey.LeftArrow]  = (int)Keys.Left;
            io.KeyMap[GuiKey.RightArrow] = (int)Keys.Right;
            io.KeyMap[GuiKey.UpArrow]    = (int)Keys.Up;
            io.KeyMap[GuiKey.DownArrow]  = (int)Keys.Down;
            io.KeyMap[GuiKey.PageUp]     = (int)Keys.PageUp;
            io.KeyMap[GuiKey.PageDown]   = (int)Keys.PageDown;
            io.KeyMap[GuiKey.Home]       = (int)Keys.Home;
            io.KeyMap[GuiKey.End]        = (int)Keys.End;
            io.KeyMap[GuiKey.Delete]     = (int)Keys.Delete;
            io.KeyMap[GuiKey.Backspace]  = (int)Keys.Back;
            io.KeyMap[GuiKey.Enter]      = (int)Keys.Enter;
            io.KeyMap[GuiKey.Escape]     = (int)Keys.Escape;
            io.KeyMap[GuiKey.A]          = (int)Keys.A;
            io.KeyMap[GuiKey.C]          = (int)Keys.C;
            io.KeyMap[GuiKey.V]          = (int)Keys.V;
            io.KeyMap[GuiKey.X]          = (int)Keys.X;
            io.KeyMap[GuiKey.Y]          = (int)Keys.Y;
            io.KeyMap[GuiKey.Z]          = (int)Keys.Z;
        }
Example #2
0
        private static void SetKeyMappings()
        {
            ImGuiIOPtr io = ImGui.GetIO();

            io.KeyMap[(int)ImGuiKey.Tab]        = (int)Key.Tab;
            io.KeyMap[(int)ImGuiKey.LeftArrow]  = (int)Key.Left;
            io.KeyMap[(int)ImGuiKey.RightArrow] = (int)Key.Right;
            io.KeyMap[(int)ImGuiKey.UpArrow]    = (int)Key.Up;
            io.KeyMap[(int)ImGuiKey.DownArrow]  = (int)Key.Down;
            io.KeyMap[(int)ImGuiKey.PageUp]     = (int)Key.PageUp;
            io.KeyMap[(int)ImGuiKey.PageDown]   = (int)Key.PageDown;
            io.KeyMap[(int)ImGuiKey.Home]       = (int)Key.Home;
            io.KeyMap[(int)ImGuiKey.End]        = (int)Key.End;
            io.KeyMap[(int)ImGuiKey.Delete]     = (int)Key.Delete;
            io.KeyMap[(int)ImGuiKey.Backspace]  = (int)Key.BackSpace;
            io.KeyMap[(int)ImGuiKey.Enter]      = (int)Key.Enter;
            io.KeyMap[(int)ImGuiKey.Escape]     = (int)Key.Escape;
            io.KeyMap[(int)ImGuiKey.A]          = (int)Key.A;
            io.KeyMap[(int)ImGuiKey.C]          = (int)Key.C;
            io.KeyMap[(int)ImGuiKey.V]          = (int)Key.V;
            io.KeyMap[(int)ImGuiKey.X]          = (int)Key.X;
            io.KeyMap[(int)ImGuiKey.Y]          = (int)Key.Y;
            io.KeyMap[(int)ImGuiKey.Z]          = (int)Key.Z;
        }
Example #3
0
        private static unsafe void SubmitUI()
        {
            // Demo code adapted from the official Dear ImGui demo program:
            // https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx11/main.cpp#L172

            // 1. Show a simple window.
            // Tip: if we don't call ImGui.BeginWindow()/ImGui.EndWindow() the widgets automatically appears in a window called "Debug".
            {
                ImGui.Text("Hello, world!");                                     // Display some text (you can use a format string too)
                ImGui.SliderFloat("float", ref _f, 0, 1, _f.ToString("0.000"));  // Edit 1 float using a slider from 0.0f to 1.0f
                //ImGui.ColorEdit3("clear color", ref _clearColor);                   // Edit 3 floats representing a color

                ImGui.Text($"Mouse position: {ImGui.GetMousePos()}");

                ImGui.Checkbox("Demo Window", ref _showDemoWindow);                 // Edit bools storing our windows open/close state
                ImGui.Checkbox("Another Window", ref _showAnotherWindow);
                ImGui.Checkbox("Memory Editor", ref _showMemoryEditor);
                if (ImGui.Button("Button"))                                         // Buttons return true when clicked (NB: most widgets return true when edited/activated)
                {
                    _counter++;
                }
                ImGui.SameLine(0, -1);
                ImGui.Text($"counter = {_counter}");

                ImGui.DragInt("Draggable Int", ref _dragInt);

                float framerate = ImGui.GetIO().Framerate;
                ImGui.Text($"Application average {1000.0f / framerate:0.##} ms/frame ({framerate:0.#} FPS)");
            }

            // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name your windows.
            if (_showAnotherWindow)
            {
                ImGui.Begin("Another Window", ref _showAnotherWindow);
                ImGui.Text("Hello from another window!");
                if (ImGui.Button("Close Me"))
                {
                    _showAnotherWindow = false;
                }
                ImGui.End();
            }

            // 3. Show the ImGui demo window. Most of the sample code is in ImGui.ShowDemoWindow(). Read its code to learn more about Dear ImGui!
            if (_showDemoWindow)
            {
                // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway.
                // Here we just want to make the demo initial state a bit more friendly!
                ImGui.SetNextWindowPos(new Vector2(650, 20), ImGuiCond.FirstUseEver);
                ImGui.ShowDemoWindow(ref _showDemoWindow);
            }

            if (ImGui.TreeNode("Tabs"))
            {
                if (ImGui.TreeNode("Basic"))
                {
                    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags.None;
                    if (ImGui.BeginTabBar("MyTabBar", tab_bar_flags))
                    {
                        if (ImGui.BeginTabItem("Avocado"))
                        {
                            ImGui.Text("This is the Avocado tab!\nblah blah blah blah blah");
                            ImGui.EndTabItem();
                        }
                        if (ImGui.BeginTabItem("Broccoli"))
                        {
                            ImGui.Text("This is the Broccoli tab!\nblah blah blah blah blah");
                            ImGui.EndTabItem();
                        }
                        if (ImGui.BeginTabItem("Cucumber"))
                        {
                            ImGui.Text("This is the Cucumber tab!\nblah blah blah blah blah");
                            ImGui.EndTabItem();
                        }
                        ImGui.EndTabBar();
                    }
                    ImGui.Separator();
                    ImGui.TreePop();
                }

                if (ImGui.TreeNode("Advanced & Close Button"))
                {
                    // Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0).
                    ImGui.CheckboxFlags("ImGuiTabBarFlags_Reorderable", ref s_tab_bar_flags, (uint)ImGuiTabBarFlags.Reorderable);
                    ImGui.CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", ref s_tab_bar_flags, (uint)ImGuiTabBarFlags.AutoSelectNewTabs);
                    ImGui.CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", ref s_tab_bar_flags, (uint)ImGuiTabBarFlags.NoCloseWithMiddleMouseButton);
                    if ((s_tab_bar_flags & (uint)ImGuiTabBarFlags.FittingPolicyMask) == 0)
                    {
                        s_tab_bar_flags |= (uint)ImGuiTabBarFlags.FittingPolicyDefault;
                    }
                    if (ImGui.CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", ref s_tab_bar_flags, (uint)ImGuiTabBarFlags.FittingPolicyResizeDown))
                    {
                        s_tab_bar_flags &= ~((uint)ImGuiTabBarFlags.FittingPolicyMask ^ (uint)ImGuiTabBarFlags.FittingPolicyResizeDown);
                    }
                    if (ImGui.CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", ref s_tab_bar_flags, (uint)ImGuiTabBarFlags.FittingPolicyScroll))
                    {
                        s_tab_bar_flags &= ~((uint)ImGuiTabBarFlags.FittingPolicyMask ^ (uint)ImGuiTabBarFlags.FittingPolicyScroll);
                    }

                    // Tab Bar
                    string[] names = { "Artichoke", "Beetroot", "Celery", "Daikon" };

                    for (int n = 0; n < s_opened.Length; n++)
                    {
                        if (n > 0)
                        {
                            ImGui.SameLine();
                        }
                        ImGui.Checkbox(names[n], ref s_opened[n]);
                    }

                    // Passing a bool* to BeginTabItem() is similar to passing one to Begin(): the underlying bool will be set to false when the tab is closed.
                    if (ImGui.BeginTabBar("MyTabBar", (ImGuiTabBarFlags)s_tab_bar_flags))
                    {
                        for (int n = 0; n < s_opened.Length; n++)
                        {
                            if (s_opened[n] && ImGui.BeginTabItem(names[n], ref s_opened[n]))
                            {
                                ImGui.Text($"This is the {names[n]} tab!");
                                if ((n & 1) != 0)
                                {
                                    ImGui.Text("I am an odd tab.");
                                }
                                ImGui.EndTabItem();
                            }
                        }
                        ImGui.EndTabBar();
                    }
                    ImGui.Separator();
                    ImGui.TreePop();
                }
                ImGui.TreePop();
            }

            ImGuiIOPtr io = ImGui.GetIO();

            SetThing(out io.DeltaTime, 2f);

            if (_showMemoryEditor)
            {
                _memoryEditor.Draw("Memory Editor", _memoryEditorData, _memoryEditorData.Length);
            }
        }
Example #4
0
        private void UpdateImGuiInput(InputSnapshot snapshot)
        {
            ImGuiIOPtr io = ImGui.GetIO();

            Vector2 mousePosition = snapshot.MousePosition;

            // Determine if any of the mouse buttons were pressed during this snapshot period, even if they are no longer held.
            bool leftPressed   = false;
            bool middlePressed = false;
            bool rightPressed  = false;

            foreach (MouseEvent me in snapshot.MouseEvents)
            {
                if (me.Down)
                {
                    switch (me.MouseButton)
                    {
                    case MouseButton.Left:
                        leftPressed = true;
                        break;

                    case MouseButton.Middle:
                        middlePressed = true;
                        break;

                    case MouseButton.Right:
                        rightPressed = true;
                        break;
                    }
                }
            }

            io.MouseDown[0] = leftPressed || snapshot.IsMouseDown(MouseButton.Left);
            io.MouseDown[1] = rightPressed || snapshot.IsMouseDown(MouseButton.Right);
            io.MouseDown[2] = middlePressed || snapshot.IsMouseDown(MouseButton.Middle);
            io.MousePos     = mousePosition;
            io.MouseWheel   = snapshot.WheelDelta;

            IReadOnlyList <char> keyCharPresses = snapshot.KeyCharPresses;

            for (int i = 0; i < keyCharPresses.Count; i++)
            {
                char c = keyCharPresses[i];
                io.AddInputCharacter(c);
            }

            IReadOnlyList <KeyEvent> keyEvents = snapshot.KeyEvents;

            for (int i = 0; i < keyEvents.Count; i++)
            {
                KeyEvent keyEvent = keyEvents[i];
                io.KeysDown[(int)keyEvent.Key] = keyEvent.Down;
                if (keyEvent.Key == Key.ControlLeft)
                {
                    _controlDown = keyEvent.Down;
                }
                if (keyEvent.Key == Key.ShiftLeft)
                {
                    _shiftDown = keyEvent.Down;
                }
                if (keyEvent.Key == Key.AltLeft)
                {
                    _altDown = keyEvent.Down;
                }
                if (keyEvent.Key == Key.WinLeft)
                {
                    _winKeyDown = keyEvent.Down;
                }
            }

            io.KeyCtrl  = _controlDown;
            io.KeyAlt   = _altDown;
            io.KeyShift = _shiftDown;
            io.KeySuper = _winKeyDown;
        }
Example #5
0
        private string ChooseFileMainMethod(
            string directory,
            bool _isFolderChooserDialog,
            bool _isSaveFileDialog,
            string _saveFileName,
            string fileFilterExtensionString,
            string windowTitle,
            Vector2?windowSize,
            Vector2?windowPos,
            float windowAlpha
            )
        {
            //-----------------------------------------------------------------------------
            Internal I  = _internal;
            string   rv = I.chosenPath = "";
            //-----------------------------------------------------
            bool isSelectFolderDialog = I.isSelectFolderDialog = _isFolderChooserDialog;
            bool isSaveFileDialog     = I.isSaveFileDialog = _isSaveFileDialog;

            bool allowDirectoryCreation = I.allowDirectoryCreation = I.forbidDirectoryCreation ? false : (isSelectFolderDialog || isSaveFileDialog);
            //----------------------------------------------------------

            //----------------------------------------------------------
            Style   style            = ImGui.GetStyle();
            Vector4 dummyButtonColor = new Vector4(0.0f, 0.0f, 0.0f, 0.5f);     // Only the alpha is twickable from here

            // Fill ColorSet above and fix dummyButtonColor here
            {
                for (int i = 0, sz = (int)Internal.Color.ImGuiCol_Dialog_Directory_Text; i <= sz; i++)
                {
                    Vector4 r = style.GetColor(i < sz ? (ColorTarget.Button + i) : ColorTarget.Text);
                    Internal.ColorCombine(ref ColorSet[i], r, df);
                }
                for (int i = (int)Internal.Color.ImGuiCol_Dialog_File_Background, sz =
                         (int)Internal.Color.ImGuiCol_Dialog_File_Text; i <= sz; i++)
                {
                    Vector4 r = style.GetColor(i < sz ? (ColorTarget.Button - (int)Internal.Color.ImGuiCol_Dialog_File_Background + i)
                        : ColorTarget.Text);
                    Internal.ColorCombine(ref ColorSet[i], r, ff);
                }
                if (dummyButtonColor.W > 0)
                {
                    Vector4 bbc = style.GetColor(ColorTarget.Button);
                    dummyButtonColor.X = bbc.X; dummyButtonColor.Y = bbc.Y; dummyButtonColor.Z = bbc.Z; dummyButtonColor.W *= bbc.W;
                }
            }

            if (I.rescan)
            {
                string validDirectory = ".";
                if (directory != null && directory.Length > 0)
                {
                    if (Directory.Exists(directory))
                    {
                        validDirectory = directory;
                    }
                    else
                    {
                        validDirectory = Path.GetDirectoryName(directory);
                        if (!Directory.Exists(validDirectory))
                        {
                            validDirectory = ".";
                        }
                    }
                }
                I.currentFolder = Path.GetFullPath(validDirectory);

                I.editLocationCheckButtonPressed = false;
                I.history.reset();                   // reset history
                I.history.switchTo(I.currentFolder); // init history
                I.dirs.Clear(); I.files.Clear(); I.dirNames.Clear(); I.fileNames.Clear(); I.currentSplitPath.Clear();
                I.newDirectoryName = "New Folder";
                if (_saveFileName != null)
                {
                    //&I.saveFileName[0] = _saveFileName;
                    I.saveFileName = Path.GetFileName(_saveFileName);    // Better!
                }
                else
                {
                    I.saveFileName = "";
                }
                isSelectFolderDialog   = _isFolderChooserDialog;
                isSaveFileDialog       = _isSaveFileDialog;
                allowDirectoryCreation = I.forbidDirectoryCreation? false : (isSelectFolderDialog || isSaveFileDialog);
                if (isSelectFolderDialog && I.sortingMode > (int)Sorting.SORT_ORDER_LAST_MODIFICATION_INVERSE)
                {
                    I.sortingMode = 0;
                }
                I.forceRescan = true;
                I.open        = true;
                I.filter.Clear();
                if (windowTitle == null || windowTitle.Length == 0)
                {
                    if (isSelectFolderDialog)
                    {
                        I.wndTitle = "Please select a folder";
                    }
                    else if (isSaveFileDialog)
                    {
                        I.wndTitle = "Please choose/create a file for saving";
                    }
                    else
                    {
                        I.wndTitle = "Please choose a file";
                    }
                }
                else
                {
                    I.wndTitle = windowTitle;
                }
                I.wndTitle += "##";
                // char[] tmpWndTitleNumber = new char[12];
                // ImFormatString(tmpWndTitleNumber,11,"%d", I.uniqueNumber);
                string tmpWndTitleNumber = I.uniqueNumber.ToString();
                I.wndTitle += tmpWndTitleNumber;
                I.wndPos    = windowPos ?? new Vector2();
                I.wndSize   = windowSize ?? new Vector2();
                if (I.wndSize.X <= 0)
                {
                    I.wndSize.X = 400;
                }
                if (I.wndSize.Y <= 0)
                {
                    I.wndSize.Y = 400;
                }
                Vector2 mousePos = ImGui.GetMousePos();// ImGui.GetCursorPos();
                if (I.wndPos.X <= 0)
                {
                    I.wndPos.X = mousePos.X - I.wndSize.X * 0.5f;
                }
                if (I.wndPos.Y <= 0)
                {
                    I.wndPos.Y = mousePos.Y - I.wndSize.Y * 0.5f;
                }
                Vector2 screenSize = ImGui.GetIO().DisplaySize;
                if (I.wndPos.X > screenSize.X - I.wndSize.X)
                {
                    I.wndPos.X = screenSize.X - I.wndSize.X;
                }
                if (I.wndPos.Y > screenSize.Y - I.wndSize.Y)
                {
                    I.wndPos.Y = screenSize.Y - I.wndSize.Y;
                }
                if (I.wndPos.X < 0)
                {
                    I.wndPos.X = 0;
                }
                if (I.wndPos.Y < 0)
                {
                    I.wndPos.Y = 0;
                }
                //fprintf(stderr,"screenSize = %f,%f mousePos = %f,%f wndPos = %f,%f wndSize = %f,%f\n",screenSize.X,screenSize.Y,mousePos.X,mousePos.Y,wndPos.X,wndPos.Y,wndSize.X,wndSize.Y);
                if (I.detectKnownDirectoriesAtEveryOpening)
                {
                    pUserKnownDirectories = Directory_GetUserKnownDirectories(ref pUserKnownDirectoryDisplayNames, ref pNumberKnownUserDirectoriesExceptDrives, true);
                }
            }
            if (!I.open)
            {
                return(rv);
            }

            if (I.forceRescan)
            {
                I.forceRescan = false;
                int sortingModeForDirectories = (I.sortingMode <= (int)Sorting.SORT_ORDER_LAST_MODIFICATION_INVERSE) ? I.sortingMode : (I.sortingMode % 2);
                Directory_GetDirectories(I.currentFolder, ref I.dirs, ref I.dirNames, (Sorting)sortingModeForDirectories);  // this is because directories don't return their size or their file extensions (so if needed we sort them alphabetically)
                //I.dirNames.resize(I.dirs.size());for (int i=0,sz=I.dirs.size();i<sz;i++)  Path.GetFileName(I.dirs[i],(char*)I.dirNames[i]);

                if (!isSelectFolderDialog)
                {
                    if (fileFilterExtensionString == null || fileFilterExtensionString.Length == 0)
                    {
                        Directory_GetFiles(I.currentFolder, ref I.files, ref I.fileNames, (Sorting)I.sortingMode);
                    }
                    else
                    {
                        Directory_GetFiles(I.currentFolder, ref I.files, fileFilterExtensionString, ref I.fileNames, (Sorting)I.sortingMode);
                    }
                    //I.fileNames.resize(I.files.size());for (int i=0,sz=I.files.size();i<sz;i++) Path.GetFileName(I.files[i],(char*)I.fileNames[i]);
                }
                else
                {
                    I.files.Clear(); I.fileNames.Clear();
                    I.saveFileName = "";
                    string currentFolderName     = Path.GetFileName(I.currentFolder);
                    int    currentFolderNameSize = currentFolderName.Length;
                    if (currentFolderNameSize == 0 || currentFolderName[currentFolderNameSize - 1] == ':')
                    {
                        currentFolderName += "/";
                    }
                    I.saveFileName += currentFolderName;
                }

                I.history.getCurrentSplitPath(ref I.currentSplitPath);

                const int approxNumEntriesPerColumn = 20;//(int) (20.f / browseSectionFontScale);// tweakable
                I.totalNumBrowsingEntries = (int)(I.dirs.Count + I.files.Count);
                I.numBrowsingColumns      = I.totalNumBrowsingEntries / approxNumEntriesPerColumn;
                if (I.numBrowsingColumns <= 0)
                {
                    I.numBrowsingColumns = 1;
                }
                if (I.totalNumBrowsingEntries % approxNumEntriesPerColumn > (approxNumEntriesPerColumn / 2))
                {
                    ++I.numBrowsingColumns;
                }
                if (I.numBrowsingColumns > 6)
                {
                    I.numBrowsingColumns = 6;
                }
                I.numBrowsingEntriesPerColumn = I.totalNumBrowsingEntries / I.numBrowsingColumns;
                if (I.totalNumBrowsingEntries % I.numBrowsingColumns != 0)
                {
                    ++I.numBrowsingEntriesPerColumn;
                }

                //#       define DEBUG_HISTORY
#if DEBUG_HISTORY
                if (I.history.getInfoSize() > 0)
                {
                    fprintf(stderr, "\nHISTORY: currentFolder:\"%s\" history.canGoBack=%s history.canGoForward=%s currentHistory:\n", I.currentFolder, I.history.canGoBack()?"true":"false", I.history.canGoForward()?"true":"false");
                }
                if (I.history.getCurrentFolderInfo())
                {
                    I.history.getCurrentFolderInfo()->display();
                }
#endif //DEBUG_HISTORY
            }

            if (I.rescan)
            {
                I.rescan = false; // Mandatory

                ImGui.BeginWindow(I.wndTitle, ref I.open, I.wndSize, windowAlpha, WindowFlags.Default);
                ImGuiNative.igSetWindowPos(I.wndPos, Condition.FirstUseEver);
                ImGui.SetWindowSize(I.wndSize);
                //fprintf(stderr,"\"%s\" wndPos={%1.2f,%1.2f}\n",wndTitle.c_str(),wndPos.X,wndPos.Y);
            }
            else
            {
                ImGui.BeginWindow(I.wndTitle, ref I.open, new Vector2(0, 0), windowAlpha, WindowFlags.Default);
            }
            ImGui.Separator();

            //------------------------------------------------------------------------------------
            // History (=buttons: < and >)
            {
                bool historyBackClicked    = false;
                bool historyForwardClicked = false;

                // history -----------------------------------------------
                ImGui.PushID("historyDirectoriesID");

                bool historyCanGoBack    = I.history.canGoBack();
                bool historyCanGoForward = I.history.canGoForward();

                if (!historyCanGoBack)
                {
                    ImGui.PushStyleColor(ColorTarget.Button, dummyButtonColor);
                    ImGui.PushStyleColor(ColorTarget.ButtonHovered, dummyButtonColor);
                    ImGui.PushStyleColor(ColorTarget.ButtonActive, dummyButtonColor);
                }
                historyBackClicked = ImGui.Button("<") & historyCanGoBack;
                ImGui.SameLine();
                if (!historyCanGoBack)
                {
                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                }

                if (!historyCanGoForward)
                {
                    ImGui.PushStyleColor(ColorTarget.Button, dummyButtonColor);
                    ImGui.PushStyleColor(ColorTarget.ButtonHovered, dummyButtonColor);
                    ImGui.PushStyleColor(ColorTarget.ButtonActive, dummyButtonColor);
                }
                historyForwardClicked = ImGui.Button(">") & historyCanGoForward;
                ImGui.SameLine();
                if (!historyCanGoForward)
                {
                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                }

                ImGui.PopID();
                // -------------------------------------------------------

                if (historyBackClicked || historyForwardClicked)
                {
                    ImGui.EndWindow();

                    if (historyBackClicked)
                    {
                        I.history.goBack();
                    }
                    else if (historyForwardClicked)
                    {
                        I.history.goForward();
                    }

                    I.forceRescan = true;

                    I.currentFolder         = I.history.getCurrentFolder();
                    I.editLocationInputText = I.currentFolder;

#if DEBUG_HISTORY
                    if (historyBackClicked)
                    {
                        fprintf(stderr, "\nPressed BACK to\t");
                    }
                    else
                    {
                        fprintf(stderr, "\nPressed FORWARD to\t");
                    }
                    fprintf(stderr, "\"%s\" (%d)\n", I.currentFolder, (int)*I.history.getCurrentSplitPathIndex());
#undef DEBUG_HISTOTY
#endif //DEBUG_HISTORY
                    return(rv);
                }
            }
            //------------------------------------------------------------------------------------
            // Edit Location CheckButton
            bool editLocationInputTextReturnPressed = false;
            {
                bool mustValidateInputPath = false;
                ImGui.PushStyleColor(ColorTarget.Button, I.editLocationCheckButtonPressed? dummyButtonColor :
                                     style.GetColor(ColorTarget.Button));

                if (ImGui.Button("L##EditLocationCheckButton"))
                {
                    I.editLocationCheckButtonPressed = !I.editLocationCheckButtonPressed;
                    if (I.editLocationCheckButtonPressed)
                    {
                        I.editLocationInputText = I.currentFolder;
                        ImGui.SetKeyboardFocusHere();
                    }
                    //if (!I.editLocationCheckButtonPressed) mustValidateInputPath = true;   // or not ? I mean: the user wants to quit or to validate in this case ?
                }

                ImGui.PopStyleColor();

                if (I.editLocationCheckButtonPressed)
                {
                    ImGui.SameLine();
                    Encoding.UTF8.GetBytes(I.editLocationInputText, 0, I.editLocationInputText.Length, tmpPathBytes, 0);
                    editLocationInputTextReturnPressed = ImGui.InputText("##EditLocationInputText", tmpPathBytes, MaxPathBytes,
                                                                         InputTextFlags.AutoSelectAll | InputTextFlags.EnterReturnsTrue, null);
                    I.editLocationInputText = Encoding.UTF8.GetString(tmpPathBytes);
                    if (editLocationInputTextReturnPressed)
                    {
                        mustValidateInputPath = true;
                    }
                    else
                    {
                        ImGui.Separator();
                    }
                }

                if (mustValidateInputPath)
                {
                    // it's better to clean the input path here from trailing slashes:
                    StringBuilder cleanEnteredPathB = new StringBuilder(I.editLocationInputText);
                    int           len = cleanEnteredPathB.Length;
                    while (len > 0 && (cleanEnteredPathB[len - 1] == '/' || cleanEnteredPathB[len - 1] == '\\'))
                    {
                        cleanEnteredPathB.Remove(len - 1, 1); len = cleanEnteredPathB.Length;
                    }
                    string cleanEnteredPath = cleanEnteredPathB.ToString();

                    if (len == 0 || I.currentFolder == cleanEnteredPath)
                    {
                        I.editLocationCheckButtonPressed = false;
                    }
                    else if (Directory.Exists(cleanEnteredPath))
                    {
                        I.editLocationCheckButtonPressed = false; // Optional (return to split-path buttons)
                        //----------------------------------------------------------------------------------
                        I.history.switchTo(cleanEnteredPath);
                        I.currentFolder = cleanEnteredPath;
                        I.forceRescan   = true;
                    }
                    //else fprintf(stderr,"mustValidateInputPath NOOP: \"%s\" \"%s\"\n",I.currentFolder,cleanEnteredPath);
                }
                else
                {
                    ImGui.SameLine();
                }
            }
            //------------------------------------------------------------------------------------
            // Split Path control
            if (!I.editLocationCheckButtonPressed && !editLocationInputTextReturnPressed)
            {
                bool       mustSwitchSplitPath = false;
                FolderInfo fi = I.history.getCurrentFolderInfo();

                Vector2 framePadding          = ImGui.GetStyle().FramePadding;
                float   originalFramePaddingX = framePadding.X;
                framePadding.X = 0;

                // Split Path
                // Tab:
                {
                    //-----------------------------------------------------
                    // TAB LABELS
                    //-----------------------------------------------------
                    {
                        int numTabs        = (int)I.currentSplitPath.Count;
                        int newSelectedTab = fi.splitPathIndex;
                        for (int t = 0; t < numTabs; t++)
                        {
                            if (t > 0)
                            {
                                ImGui.SameLine(0, 0);
                            }
                            if (t == fi.splitPathIndex)
                            {
                                ImGui.PushStyleColor(ColorTarget.Button, dummyButtonColor);
                                ImGui.PushStyleColor(ColorTarget.ButtonHovered, dummyButtonColor);
                                ImGui.PushStyleColor(ColorTarget.ButtonActive, dummyButtonColor);
                            }
                            ImGui.PushID(I.currentSplitPath[t]);
                            bool pressed = ImGui.Button(I.currentSplitPath[t]);
                            ImGui.PopID();
                            if (pressed)
                            {
                                if (fi.splitPathIndex != t && !mustSwitchSplitPath)
                                {
                                    mustSwitchSplitPath = true;
                                }
                                newSelectedTab = t;
                            }
                            if (t == fi.splitPathIndex)
                            {
                                ImGui.PopStyleColor();
                                ImGui.PopStyleColor();
                                ImGui.PopStyleColor();
                            }
                        }
                        if (mustSwitchSplitPath)
                        {
                            FolderInfo mfi = null;
                            fi.getFolderInfoForSplitPathIndex(newSelectedTab, ref mfi);
                            I.history.switchTo(mfi);
                            I.forceRescan           = true;
                            I.currentFolder         = I.history.getCurrentFolder();
                            I.editLocationInputText = I.currentFolder;
                            //fprintf(stderr,"%s\n",I.currentFolder);
                        }
                    }
                }

                framePadding.X = originalFramePaddingX;
            }
            //------------------------------------------------------------------------------------

            // Start collapsable regions----------------------------------------------------------
            // User Known directories-------------------------------------------------------------
            if (I.allowKnownDirectoriesSection && pUserKnownDirectories.Count > 0)
            {
                ImGui.Separator();

                if (ImGui.CollapsingHeader("Known Directories##UserKnownDirectories", TreeNodeFlags.CollapsingHeader))
                {
                    ImGui.PushID(id);

                    ImGui.PushStyleColor(ColorTarget.Text, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Text]);
                    ImGui.PushStyleColor(ColorTarget.Button, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Background]);
                    ImGui.PushStyleColor(ColorTarget.ButtonHovered, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Hover]);
                    ImGui.PushStyleColor(ColorTarget.ButtonActive, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Pressed]);

                    for (int i = 0, sz = (int)pUserKnownDirectories.Count; i < sz; i++)
                    {
                        string userKnownFolder            = pUserKnownDirectories[i];
                        string userKnownFolderDisplayName = pUserKnownDirectoryDisplayNames[i];
                        if (ImGui.SmallButton(userKnownFolderDisplayName) && userKnownFolder != I.currentFolder)
                        {
                            I.currentFolder         = userKnownFolder;
                            I.editLocationInputText = I.currentFolder;
                            I.history.switchTo(I.currentFolder);
                            I.forceRescan = true;
                            //------------------------------------------------------------------------------------------------------------------------------
                        }
                        if (i != sz - 1 && (i >= pNumberKnownUserDirectoriesExceptDrives || i % 7 != 6))
                        {
                            ImGui.SameLine();
                        }
                    }

                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();

                    ImGui.PopID();
                }
            }
            // End User Known directories---------------------------------------------------------
            // Allow directory creation ----------------------------------------------------------
            if (allowDirectoryCreation)
            {
                ImGui.Separator();
                bool mustCreate = false;

                if (ImGui.CollapsingHeader("New Directory##allowDirectoryCreation", TreeNodeFlags.CollapsingHeader))
                {
                    ImGui.PushID(id);

                    Encoding.UTF8.GetBytes(I.newDirectoryName, 0, I.newDirectoryName.Length, tmpPathBytes, 0);
                    ImGui.InputText("##createNewFolderName", tmpPathBytes, MaxFilenameBytes, InputTextFlags.Default, null);
                    I.newDirectoryName = Encoding.UTF8.GetString(tmpPathBytes);
                    ImGui.SameLine();
                    mustCreate = ImGui.Button("CREATE");

                    ImGui.PopID();
                }

                if (mustCreate && I.newDirectoryName.Length > 0)
                {
                    string newDirPath = Path.Combine(I.currentFolder, I.newDirectoryName);
                    if (!Directory.Exists(newDirPath))
                    {
                        //#           define SIMULATING_ONLY
#if SIMULATING_ONLY
                        fprintf(stderr, "creating: \"%s\"\n", newDirPath);
#undef SIMULATING_ONLY
#else //SIMULATING_ONLY
                        Directory.CreateDirectory(newDirPath);
                        if (!Directory.Exists(newDirPath))
                        {
                            Console.Error.WriteLine("Error creating new folder: \"{0}\"\n", newDirPath);
                        }
                        else
                        {
                            I.forceRescan = true;    // Just update
                        }
#endif //SIMULATING_ONLY
                    }
                }
            }
            // End allow directory creation ------------------------------------------------------
            // Filtering entries -----------------------------------------------------------------
            if (I.allowFiltering)
            {
                ImGui.Separator();
                if (ImGui.CollapsingHeader("Filtering##fileNameFiltering", TreeNodeFlags.CollapsingHeader))
                {
                    ImGui.PushID(id);
                    I.filter.Draw();
                    ImGui.PopID();
                }
            }
            // End filtering entries -------------------------------------------------------------
            // End collapsable regions------------------------------------------------------------

            // Selection field -------------------------------------------------------------------
            if (isSaveFileDialog || isSelectFolderDialog)
            {
                ImGui.Separator();
                bool selectionButtonPressed = false;

                ImGui.PushID(id);
                if (isSaveFileDialog)
                {
                    ImGui.Text("File:"); ImGui.SameLine();
                    Encoding.UTF8.GetBytes(I.saveFileName, 0, I.saveFileName.Length, tmpPathBytes, 0);
                    ImGui.InputText("##saveFileName", tmpPathBytes, MaxFilenameBytes, InputTextFlags.Default, null);
                    I.saveFileName = Encoding.UTF8.GetString(tmpPathBytes);
                    ImGui.SameLine();
                }
                else
                {
                    //ImGui.AlignFirstTextHeightToWidgets();
                    ImGui.Text("Folder:"); ImGui.SameLine();

                    Vector4 r = style.GetColor(ColorTarget.Text);
                    Internal.ColorCombine(ref ColorSet[(int)Internal.Color.ImGuiCol_Dialog_SelectedFolder_Text], r, sf);

                    ImGuiNative.igTextColored(ColorSet[(int)Internal.Color.ImGuiCol_Dialog_SelectedFolder_Text], I.saveFileName);
                    ImGui.SameLine();
                }

                if (isSelectFolderDialog)
                {
                    selectionButtonPressed = ImGui.Button("Select");
                }
                else
                {
                    selectionButtonPressed = ImGui.Button("Save");
                }

                ImGui.PopID();

                if (selectionButtonPressed)
                {
                    if (isSelectFolderDialog)
                    {
                        rv     = I.currentFolder;
                        I.open = true;
                    }
                    else if (isSaveFileDialog)
                    {
                        if (I.saveFileName.Length > 0)
                        {
                            bool pathOk = true;
                            if (I.mustFilterSaveFilePathWithFileFilterExtensionString && fileFilterExtensionString != null && fileFilterExtensionString.Length > 0)
                            {
                                pathOk = false;
                                string saveFileNameExtension    = Path.GetExtension(I.saveFileName);
                                bool   saveFileNameHasExtension = saveFileNameExtension.Length > 0;
                                //-------------------------------------------------------------------
                                string[] wExts     = fileFilterExtensionString.Split(';');
                                int      wExtsSize = wExts.Length;
                                if (!saveFileNameHasExtension)
                                {
                                    if (wExtsSize == 0)
                                    {
                                        pathOk = true;                  // Bad situation, better allow this case
                                    }
                                    else
                                    {
                                        I.saveFileName += wExts[0];
                                    }
                                }
                                else
                                {
                                    // saveFileNameHasExtension
                                    for (int i = 0; i < wExtsSize; i++)
                                    {
                                        string ext = wExts[i];
                                        if (ext == saveFileNameExtension)
                                        {
                                            pathOk = true;
                                            break;
                                        }
                                    }
                                    if (!pathOk && wExtsSize > 0)
                                    {
                                        I.saveFileName += wExts[0];
                                    }
                                }
                            }
                            if (pathOk)
                            {
                                string savePath = Path.Combine(I.currentFolder, I.saveFileName);
                                rv     = savePath;
                                I.open = true;
                            }
                        }
                    }
                }

                //ImGui.Spacing();
            }
            // End selection field----------------------------------------------------------------

            ImGui.Separator();
            // sorting --------------------------------------------------------------------
            ImGui.Text("Sorting by: "); ImGui.SameLine();
            {
                int oldSortingMode = I.sortingMode;
                int oldSelectedTab = I.sortingMode / 2;
                //-----------------------------------------------------
                // TAB LABELS
                //-----------------------------------------------------
                {
                    int newSortingMode = oldSortingMode;
                    int numUsedTabs    = isSelectFolderDialog ? 2 : numTabs;
                    for (int t = 0; t < numUsedTabs; t++)
                    {
                        if (t > 0)
                        {
                            ImGui.SameLine();
                        }
                        if (t == oldSelectedTab)
                        {
                            ImGui.PushStyleColor(ColorTarget.Button, dummyButtonColor);
                        }
                        ImGui.PushID(names[t]);
                        bool pressed = ImGui.SmallButton(names[t]);
                        ImGui.PopID();
                        if (pressed)
                        {
                            if (oldSelectedTab == t)
                            {
                                newSortingMode = oldSortingMode;
                                if (newSortingMode % 2 == 0)
                                {
                                    ++newSortingMode;                     // 0,2,4
                                }
                                else
                                {
                                    --newSortingMode;
                                }
                            }
                            else
                            {
                                newSortingMode = t * 2;
                            }
                        }
                        if (t == oldSelectedTab)
                        {
                            ImGui.PopStyleColor();
                        }
                    }

                    if (newSortingMode != oldSortingMode)
                    {
                        I.sortingMode = newSortingMode;
                        //printf("sortingMode = %d\n",sortingMode);
                        I.forceRescan = true;
                    }

                    //-- Browsing per row -----------------------------------
                    if (I.allowDisplayByOption && I.numBrowsingColumns > 1)
                    {
                        ImGui.SameLine();
                        ImGui.Text("   Display by:");
                        ImGui.SameLine();
                        ImGui.PushStyleColor(ColorTarget.Button, dummyButtonColor);
                        if (ImGui.SmallButton(!Internal.BrowsingPerRow? "Column##browsingPerRow" : "Row##browsingPerRow"))
                        {
                            Internal.BrowsingPerRow = !Internal.BrowsingPerRow;
                        }
                        ImGui.PopStyleColor();
                    }
                    //-- End browsing per row -------------------------------
                }
            }
            //-----------------------------------------------------------------------------
            ImGui.Separator();

            //-----------------------------------------------------------------------------
            // MAIN BROWSING FRAME:
            //-----------------------------------------------------------------------------
            {
                ImGui.BeginChild("BrowsingFrame");
                // ImGui.SetScrollPosHere();   // possible future ref: while drawing to place the scroll bar
                ImGui.Columns(I.numBrowsingColumns, null, true);

                ImGui.PushID(id);
                int cntEntries = 0;
                // Directories --------------------------------------------------------------
                if (I.dirs.Count > 0)
                {
                    ImGui.PushStyleColor(ColorTarget.Text, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Text]);
                    ImGui.PushStyleColor(ColorTarget.Button, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Background]);
                    ImGui.PushStyleColor(ColorTarget.ButtonHovered, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Hover]);
                    ImGui.PushStyleColor(ColorTarget.ButtonActive, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_Directory_Pressed]);

                    for (int i = 0, sz = (int)I.dirs.Count; i < sz; i++)
                    {
                        string dirName = I.dirNames[i];
                        if (I.filter.PassFilter(dirName))
                        {
                            if (ImGui.SmallButton(dirName))
                            {
                                I.currentFolder         = I.dirs[i];
                                I.editLocationInputText = I.currentFolder;
                                I.history.switchTo(I.currentFolder);
                                I.forceRescan = true;
                                //------------------------------------------------------------------------------------------------------------------------------
                            }
                            ++cntEntries;
                            if (Internal.BrowsingPerRow)
                            {
                                ImGui.NextColumn();
                            }
                            else if (cntEntries == I.numBrowsingEntriesPerColumn)
                            {
                                cntEntries = 0;
                                ImGui.NextColumn();
                            }
                        }
                    }

                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                }
                // Files ----------------------------------------------------------------------
                if (!isSelectFolderDialog && I.files.Count > 0)
                {
                    ImGui.PushStyleColor(ColorTarget.Text, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_File_Text]);
                    ImGui.PushStyleColor(ColorTarget.Button, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_File_Background]);
                    ImGui.PushStyleColor(ColorTarget.ButtonHovered, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_File_Hover]);
                    ImGui.PushStyleColor(ColorTarget.ButtonActive, ColorSet[(int)Internal.Color.ImGuiCol_Dialog_File_Pressed]);


                    for (int i = 0, sz = (int)I.files.Count; i < sz; i++)
                    {
                        string fileName = I.fileNames[i];
                        if (I.filter.PassFilter(fileName))
                        {
                            if (ImGui.SmallButton(fileName))
                            {
                                if (!isSaveFileDialog)
                                {
                                    rv     = I.files[i];
                                    I.open = true;
                                }
                                else
                                {
                                    I.saveFileName = Path.GetFileName(I.files[i]);
                                }
                            }
                            ++cntEntries;
                            if (Internal.BrowsingPerRow)
                            {
                                ImGui.NextColumn();
                            }
                            else if (cntEntries == I.numBrowsingEntriesPerColumn)
                            {
                                cntEntries = 0;
                                ImGui.NextColumn();
                            }
                        }
                    }

                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                    ImGui.PopStyleColor();
                }
                //-----------------------------------------------------------------------------
                ImGui.PopID();
                ImGui.EndChild();
            }
            //-----------------------------------------------------------------------------

            ImGui.EndWindow();
            return(rv);
        }
Example #6
0
        public static void Init(Window window, Vector2f displaySize, bool loadDefaultFont = true)
        {
            ImGui.CreateContext();
            var io = ImGui.GetIO();

            // tell ImGui which features we support
            io.BackendFlags |= ImGuiBackendFlags.HasGamepad;
            io.BackendFlags |= ImGuiBackendFlags.HasMouseCursors;
            io.BackendFlags |= ImGuiBackendFlags.HasSetMousePos;

            // init keyboard mapping
            io.KeyMap[(int)ImGuiKey.Tab]        = (int)Keyboard.Key.Tab;
            io.KeyMap[(int)ImGuiKey.LeftArrow]  = (int)Keyboard.Key.Left;
            io.KeyMap[(int)ImGuiKey.RightArrow] = (int)Keyboard.Key.Right;
            io.KeyMap[(int)ImGuiKey.UpArrow]    = (int)Keyboard.Key.Up;
            io.KeyMap[(int)ImGuiKey.DownArrow]  = (int)Keyboard.Key.Down;
            io.KeyMap[(int)ImGuiKey.PageUp]     = (int)Keyboard.Key.PageUp;
            io.KeyMap[(int)ImGuiKey.PageDown]   = (int)Keyboard.Key.PageDown;
            io.KeyMap[(int)ImGuiKey.Home]       = (int)Keyboard.Key.Home;
            io.KeyMap[(int)ImGuiKey.End]        = (int)Keyboard.Key.End;
            io.KeyMap[(int)ImGuiKey.Insert]     = (int)Keyboard.Key.Insert;
            io.KeyMap[(int)ImGuiKey.Delete]     = (int)Keyboard.Key.Delete;
            io.KeyMap[(int)ImGuiKey.Backspace]  = (int)Keyboard.Key.Backspace;
            io.KeyMap[(int)ImGuiKey.Space]      = (int)Keyboard.Key.Space;
            io.KeyMap[(int)ImGuiKey.Enter]      = (int)Keyboard.Key.Enter;
            io.KeyMap[(int)ImGuiKey.Escape]     = (int)Keyboard.Key.Escape;
            io.KeyMap[(int)ImGuiKey.A]          = (int)Keyboard.Key.A;
            io.KeyMap[(int)ImGuiKey.C]          = (int)Keyboard.Key.C;
            io.KeyMap[(int)ImGuiKey.V]          = (int)Keyboard.Key.V;
            io.KeyMap[(int)ImGuiKey.X]          = (int)Keyboard.Key.X;
            io.KeyMap[(int)ImGuiKey.Y]          = (int)Keyboard.Key.Y;
            io.KeyMap[(int)ImGuiKey.Z]          = (int)Keyboard.Key.Z;

            JoystickId = GetConnectedJoystickId();

            for (var i = 0u; i < (uint)ImGuiNavInput.COUNT; ++i)
            {
                _joystickMapping[i] = _nullJoystickButton;
            }

            InitDefaultJoystickMapping();

            // init rendering
            io.DisplaySize = new Vector2(displaySize.X, displaySize.Y);

            LoadMouseCursor(ImGuiMouseCursor.Arrow, Cursor.CursorType.Arrow);
            LoadMouseCursor(ImGuiMouseCursor.TextInput, Cursor.CursorType.Text);
            LoadMouseCursor(ImGuiMouseCursor.ResizeAll, Cursor.CursorType.SizeAll);
            LoadMouseCursor(ImGuiMouseCursor.ResizeNS, Cursor.CursorType.SizeVertical);
            LoadMouseCursor(ImGuiMouseCursor.ResizeEW, Cursor.CursorType.SizeHorinzontal);
            LoadMouseCursor(ImGuiMouseCursor.ResizeNESW, Cursor.CursorType.SizeBottomLeftTopRight);
            LoadMouseCursor(ImGuiMouseCursor.ResizeNWSE, Cursor.CursorType.SizeTopLeftBottomRight);
            LoadMouseCursor(ImGuiMouseCursor.Hand, Cursor.CursorType.Hand);

            if (loadDefaultFont)
            {
                // this will load default font automatically
                // No need to call AddDefaultFont
                UpdateFontTexture();
            }

            _windowHasFocus = window.HasFocus();

            window.MouseMoved           += OnMouseMoved;
            window.MouseButtonPressed   += OnMouseButtonPressed;
            window.MouseButtonReleased  += OnMouseButtonReleased;
            window.TouchBegan           += OnTouchBegan;
            window.TouchEnded           += OnTouchEnded;
            window.MouseWheelScrolled   += OnMouseWheelScrolled;
            window.KeyPressed           += OnKeyPressed;
            window.KeyReleased          += OnKeyReleased;
            window.TextEntered          += OnTextEntered;
            window.JoystickConnected    += OnJoystickConnected;
            window.JoystickDisconnected += OnJoystickDisconnected;
            window.GainedFocus          += OnGainedFocus;
            window.LostFocus            += OnLostFocus;
        }
Example #7
0
 public static void Render()
 {
     ImGui.Render();
     RenderDrawLists(ImGui.GetDrawData(), ImGui.GetIO());
 }
Example #8
0
        private unsafe void SubmitImGuiStuff()
        {
            ImGui.GetStyle().WindowRounding = 0;

            ImGui.SetNextWindowSize(new System.Numerics.Vector2(_nativeWindow.Width - 10, _nativeWindow.Height - 20), SetCondition.Always);
            ImGui.SetNextWindowPosCenter(SetCondition.Always);
            ImGui.BeginWindow("ImGUI.NET Sample Program", ref _mainWindowOpened, WindowFlags.NoResize | WindowFlags.NoTitleBar | WindowFlags.NoMove);

            ImGui.BeginMainMenuBar();
            if (ImGui.BeginMenu("Help"))
            {
                if (ImGui.MenuItem("About", "Ctrl-Alt-A", false, true))
                {
                }
                ImGui.EndMenu();
            }
            ImGui.EndMainMenuBar();

            ImGui.Text("Hello,");
            ImGui.Text("World!");
            ImGui.Text("From ImGui.NET. ...Did that work?");
            var  pos         = ImGui.GetIO().MousePosition;
            bool leftPressed = ImGui.GetIO().MouseDown[0];

            ImGui.Text("Current mouse position: " + pos + ". Pressed=" + leftPressed);

            if (ImGui.Button("Increment the counter."))
            {
                _pressCount += 1;
            }

            ImGui.Text($"Button pressed {_pressCount} times.", new System.Numerics.Vector4(0, 1, 1, 1));

            ImGui.InputTextMultiline("Input some text:",
                                     _textInputBuffer, (uint)_textInputBufferLength,
                                     new System.Numerics.Vector2(360, 240),
                                     InputTextFlags.Default,
                                     OnTextEdited);

            ImGui.SliderFloat("SlidableValue", ref _sliderVal, -50f, 100f, $"{_sliderVal.ToString("##0.00")}", 1.0f);
            ImGui.DragVector3("Vector3", ref _positionValue, -100, 100);

            if (ImGui.TreeNode("First Item"))
            {
                ImGui.Text("Word!");
                ImGui.TreePop();
            }
            if (ImGui.TreeNode("Second Item"))
            {
                ImGui.ColorButton(_buttonColor, false, true);
                if (ImGui.Button("Push me to change color", new System.Numerics.Vector2(120, 30)))
                {
                    _buttonColor = new System.Numerics.Vector4(_buttonColor.Y + .25f, _buttonColor.Z, _buttonColor.X, _buttonColor.W);
                    if (_buttonColor.X > 1.0f)
                    {
                        _buttonColor.X -= 1.0f;
                    }
                }

                ImGui.TreePop();
            }

            if (ImGui.Button("Press me!", new System.Numerics.Vector2(100, 30)))
            {
                ImGuiNative.igOpenPopup("SmallButtonPopup");
            }

            if (ImGui.BeginPopup("SmallButtonPopup"))
            {
                ImGui.Text("Here's a popup menu.");
                ImGui.Text("With two lines.");

                ImGui.EndPopup();
            }

            if (ImGui.Button("Open Modal window"))
            {
                ImGui.OpenPopup("ModalPopup");
            }
            if (ImGui.BeginPopupModal("ModalPopup"))
            {
                ImGui.Text("You can't press on anything else right now.");
                ImGui.Text("You are stuck here.");
                if (ImGui.Button("OK", new System.Numerics.Vector2(0, 0)))
                {
                }
                ImGui.SameLine();
                ImGui.Dummy(100f, 0f);
                ImGui.SameLine();
                if (ImGui.Button("Please go away", new System.Numerics.Vector2(0, 0)))
                {
                    ImGui.CloseCurrentPopup();
                }

                ImGui.EndPopup();
            }

            ImGui.Text("I have a context menu.");
            if (ImGui.BeginPopupContextItem("ItemContextMenu"))
            {
                if (ImGui.Selectable("How's this for a great menu?"))
                {
                }
                ImGui.Selectable("Just click somewhere to get rid of me.");
                ImGui.EndPopup();
            }

            ImGui.EndWindow();

            _memoryEditor.Draw("Memory editor", _memoryEditorData, _memoryEditorData.Length);

            if (ImGui.GetIO().AltPressed&& ImGui.GetIO().KeysDown[(int)Key.F4])
            {
                _nativeWindow.Close();
            }
        }
Example #9
0
        private static unsafe void SubmitUI()
        {
            // Demo code adapted from the official Dear ImGui demo program:
            // https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx11/main.cpp#L172

            // 1. Show a simple window.
            // Tip: if we don't call ImGui.BeginWindow()/ImGui.EndWindow() the widgets automatically appears in a window called "Debug".
            {
                ImGui.Text("Hello, world!");                                                        // Display some text (you can use a format string too)
                ImGui.SliderFloat("float", ref _f, 0, 1, _f.ToString("0.000"), 1);                  // Edit 1 float using a slider from 0.0f to 1.0f
                //ImGui.ColorEdit3("clear color", ref _clearColor);                   // Edit 3 floats representing a color

                if (ImGui.InputTextMultiline("TestLabel", ref _testInput, ushort.MaxValue, new Vector2(200, 200)))
                {
                }

                ImGui.Text($"Mouse position: {ImGui.GetMousePos()}");
                ImGui.Text($"Mouse down: {ImGui.GetIO().MouseDown[0]}");

                ImGui.Checkbox("Demo Window", ref _showDemoWindow);                                 // Edit bools storing our windows open/close state
                ImGui.Checkbox("Another Window", ref _showAnotherWindow);
                ImGui.Checkbox("Memory Editor", ref _showMemoryEditor);
                if (ImGui.Button("Button"))                                                         // Buttons return true when clicked (NB: most widgets return true when edited/activated)
                {
                    _counter++;
                }
                ImGui.SameLine(0, -1);
                ImGui.Text($"counter = {_counter}");

                ImGui.DragInt("Draggable Int", ref _dragInt);

                float framerate = ImGui.GetIO().Framerate;
                ImGui.Text($"Application average {1000.0f / framerate:0.##} ms/frame ({framerate:0.#} FPS)");
            }

            // 2. Show another simple window. In most cases you will use an explicit Begin/End pair to name your windows.
            if (_showAnotherWindow)
            {
                ImGui.Begin("Another Window", ref _showAnotherWindow);
                ImGui.Text("Hello from another window!");
                if (ImGui.Button("Close Me"))
                {
                    _showAnotherWindow = false;
                }
                ImGui.End();
            }

            // 3. Show the ImGui demo window. Most of the sample code is in ImGui.ShowDemoWindow(). Read its code to learn more about Dear ImGui!
            if (_showDemoWindow)
            {
                // Normally user code doesn't need/want to call this because positions are saved in .ini file anyway.
                // Here we just want to make the demo initial state a bit more friendly!
                ImGui.SetNextWindowPos(new Vector2(650, 20), ImGuiCond.FirstUseEver);
                ImGui.ShowDemoWindow(ref _showDemoWindow);
            }

            ImGuiIOPtr io = ImGui.GetIO();

            SetThing(out io.DeltaTime, 2f);

            if (_showMemoryEditor)
            {
                _memoryEditor.Draw("Memory Editor", _memoryEditorData, _memoryEditorData.Length);
            }
        }
Example #10
0
 private void OnKeyDown(object sender, KeyboardKeyEventArgs e)
 {
     ImGui.GetIO().KeysDown[(int)e.Key] = true;
     UpdateModifiers(e);
 }
        /// <summary>
        /// Constructs a new ImGuiController.
        /// </summary>
        public ImGuiController(GraphicsDevice gd, Sdl2Window window, OutputDescription outputDescription, int width, int height)
        {
            _gd           = gd;
            _window       = window;
            _windowWidth  = width;
            _windowHeight = height;

            IntPtr context = ImGui.CreateContext();

            ImGui.SetCurrentContext(context);
            ImGuiIOPtr io = ImGui.GetIO();


            io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
            io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;

            ImGuiPlatformIOPtr platformIO   = ImGui.GetPlatformIO();
            ImGuiViewportPtr   mainViewport = platformIO.MainViewport;

            _mainViewportWindow         = new VeldridImGuiWindow(gd, mainViewport, _window);
            mainViewport.PlatformHandle = window.Handle;

            _createWindow       = CreateWindow;
            _destroyWindow      = DestroyWindow;
            _getWindowPos       = GetWindowPos;
            _showWindow         = ShowWindow;
            _setWindowPos       = SetWindowPos;
            _setWindowSize      = SetWindowSize;
            _getWindowSize      = GetWindowSize;
            _setWindowFocus     = SetWindowFocus;
            _getWindowFocus     = GetWindowFocus;
            _getWindowMinimized = GetWindowMinimized;
            _setWindowTitle     = SetWindowTitle;

            platformIO.Platform_CreateWindow       = Marshal.GetFunctionPointerForDelegate(_createWindow);
            platformIO.Platform_DestroyWindow      = Marshal.GetFunctionPointerForDelegate(_destroyWindow);
            platformIO.Platform_ShowWindow         = Marshal.GetFunctionPointerForDelegate(_showWindow);
            platformIO.Platform_SetWindowPos       = Marshal.GetFunctionPointerForDelegate(_setWindowPos);
            platformIO.Platform_SetWindowSize      = Marshal.GetFunctionPointerForDelegate(_setWindowSize);
            platformIO.Platform_SetWindowFocus     = Marshal.GetFunctionPointerForDelegate(_setWindowFocus);
            platformIO.Platform_GetWindowFocus     = Marshal.GetFunctionPointerForDelegate(_getWindowFocus);
            platformIO.Platform_GetWindowMinimized = Marshal.GetFunctionPointerForDelegate(_getWindowMinimized);
            platformIO.Platform_SetWindowTitle     = Marshal.GetFunctionPointerForDelegate(_setWindowTitle);
            platformIO.Platform_GetWindowPos       = Marshal.GetFunctionPointerForDelegate(_getWindowPos);
            platformIO.Platform_GetWindowSize      = Marshal.GetFunctionPointerForDelegate(_getWindowSize);

            unsafe
            {
                io.NativePtr->BackendPlatformName = (byte *)new FixedAsciiString("Veldrid.SDL2 Backend").DataPtr;
            }
            io.BackendFlags |= ImGuiBackendFlags.HasMouseCursors;
            io.BackendFlags |= ImGuiBackendFlags.HasSetMousePos;
            io.BackendFlags |= ImGuiBackendFlags.PlatformHasViewports;
            io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports;

            io.Fonts.AddFontDefault();

            CreateDeviceResources(gd, outputDescription);
            SetKeyMappings();

            SetPerFrameImGuiData(1f / 60f);

            UpdateMonitors();

            ImGui.NewFrame();
            _frameBegun = true;
        }
        private void RenderImDrawData(ImDrawDataPtr draw_data, GraphicsDevice gd, CommandList cl)
        {
            uint vertexOffsetInVertices = 0;
            uint indexOffsetInElements  = 0;

            if (draw_data.CmdListsCount == 0)
            {
                return;
            }

            uint totalVBSize = (uint)(draw_data.TotalVtxCount * Unsafe.SizeOf <ImDrawVert>());

            if (totalVBSize > _vertexBuffer.SizeInBytes)
            {
                gd.DisposeWhenIdle(_vertexBuffer);
                _vertexBuffer = gd.ResourceFactory.CreateBuffer(new BufferDescription((uint)(totalVBSize * 1.5f), BufferUsage.VertexBuffer | BufferUsage.Dynamic));
            }

            uint totalIBSize = (uint)(draw_data.TotalIdxCount * sizeof(ushort));

            if (totalIBSize > _indexBuffer.SizeInBytes)
            {
                gd.DisposeWhenIdle(_indexBuffer);
                _indexBuffer = gd.ResourceFactory.CreateBuffer(new BufferDescription((uint)(totalIBSize * 1.5f), BufferUsage.IndexBuffer | BufferUsage.Dynamic));
            }

            for (int i = 0; i < draw_data.CmdListsCount; i++)
            {
                ImDrawListPtr cmd_list = draw_data.CmdListsRange[i];

                cl.UpdateBuffer(
                    _vertexBuffer,
                    vertexOffsetInVertices * (uint)Unsafe.SizeOf <ImDrawVert>(),
                    cmd_list.VtxBuffer.Data,
                    (uint)(cmd_list.VtxBuffer.Size * Unsafe.SizeOf <ImDrawVert>()));

                cl.UpdateBuffer(
                    _indexBuffer,
                    indexOffsetInElements * sizeof(ushort),
                    cmd_list.IdxBuffer.Data,
                    (uint)(cmd_list.IdxBuffer.Size * sizeof(ushort)));

                vertexOffsetInVertices += (uint)cmd_list.VtxBuffer.Size;
                indexOffsetInElements  += (uint)cmd_list.IdxBuffer.Size;
            }

            // Setup orthographic projection matrix into our constant buffer
            ImGuiIOPtr io  = ImGui.GetIO();
            Matrix4x4  mvp = Matrix4x4.CreateOrthographicOffCenter(
                draw_data.DisplayPos.X,
                draw_data.DisplayPos.X + draw_data.DisplaySize.X,
                draw_data.DisplayPos.Y + draw_data.DisplaySize.Y,
                draw_data.DisplayPos.Y,
                0.0f,
                1.0f);

            cl.SetPipeline(_pipeline);
            cl.SetViewport(0, new Viewport(draw_data.DisplayPos.X, draw_data.DisplayPos.Y, draw_data.DisplaySize.X, draw_data.DisplaySize.Y, 0, 1));
            cl.SetFullViewports();
            cl.SetVertexBuffer(0, _vertexBuffer);
            cl.SetIndexBuffer(_indexBuffer, IndexFormat.UInt16);

            DeviceBuffer projMatrix  = gd.ResourceFactory.CreateBuffer(new BufferDescription(64, BufferUsage.UniformBuffer | BufferUsage.Dynamic));
            ResourceSet  resourceSet = gd.ResourceFactory.CreateResourceSet(new ResourceSetDescription(_layout, projMatrix, gd.PointSampler));

            gd.UpdateBuffer(projMatrix, 0, mvp);
            cl.SetGraphicsResourceSet(0, resourceSet);
            resourceSet.Dispose();
            projMatrix.Dispose();

            draw_data.ScaleClipRects(io.DisplayFramebufferScale);

            // Render command lists
            int vtx_offset = 0;
            int idx_offset = 0;

            for (int n = 0; n < draw_data.CmdListsCount; n++)
            {
                ImDrawListPtr cmd_list = draw_data.CmdListsRange[n];
                for (int cmd_i = 0; cmd_i < cmd_list.CmdBuffer.Size; cmd_i++)
                {
                    ImDrawCmdPtr pcmd = cmd_list.CmdBuffer[cmd_i];
                    if (pcmd.UserCallback != IntPtr.Zero)
                    {
                        throw new NotImplementedException();
                    }
                    else
                    {
                        if (pcmd.TextureId != IntPtr.Zero)
                        {
                            if (pcmd.TextureId == _fontAtlasID)
                            {
                                cl.SetGraphicsResourceSet(1, _fontTextureResourceSet);
                            }
                            else
                            {
                                cl.SetGraphicsResourceSet(1, GetImageResourceSet(pcmd.TextureId));
                            }
                        }

                        Vector2 clipOff   = draw_data.DisplayPos;
                        Vector2 clipScale = draw_data.FramebufferScale;

                        cl.SetScissorRect(
                            0,
                            (uint)((pcmd.ClipRect.X - clipOff.X) * clipScale.X),
                            (uint)((pcmd.ClipRect.Y - clipOff.Y) * clipScale.Y),
                            (uint)((pcmd.ClipRect.Z - clipOff.X) * clipScale.X),
                            (uint)((pcmd.ClipRect.W - clipOff.Y) * clipScale.Y));

                        cl.DrawIndexed(pcmd.ElemCount, 1, (uint)idx_offset, vtx_offset, 0);
                    }

                    idx_offset += (int)pcmd.ElemCount;
                }
                vtx_offset += cmd_list.VtxBuffer.Size;
            }
        }
        private void UpdateImGuiInput(InputSnapshot snapshot)
        {
            ImGuiIOPtr io = ImGui.GetIO();

            // Determine if any of the mouse buttons were pressed during this snapshot period, even if they are no longer held.
            bool leftPressed   = false;
            bool middlePressed = false;
            bool rightPressed  = false;

            foreach (MouseEvent me in snapshot.MouseEvents)
            {
                if (me.Down)
                {
                    switch (me.MouseButton)
                    {
                    case MouseButton.Left:
                        leftPressed = true;
                        break;

                    case MouseButton.Middle:
                        middlePressed = true;
                        break;

                    case MouseButton.Right:
                        rightPressed = true;
                        break;
                    }
                }
            }

            io.MouseDown[0] = leftPressed || snapshot.IsMouseDown(MouseButton.Left);
            io.MouseDown[1] = middlePressed || snapshot.IsMouseDown(MouseButton.Right);
            io.MouseDown[2] = rightPressed || snapshot.IsMouseDown(MouseButton.Middle);

            if (p_sdl_GetGlobalMouseState == null)
            {
                p_sdl_GetGlobalMouseState = Sdl2Native.LoadFunction <SDL_GetGlobalMouseState_t>("SDL_GetGlobalMouseState");
            }

            if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
            {
                int x, y;
                unsafe
                {
                    uint buttons = p_sdl_GetGlobalMouseState(&x, &y);
                    io.MouseDown[0] = (buttons & 0b00001) != 0;
                    io.MouseDown[1] = (buttons & 0b00010) != 0;
                    io.MouseDown[2] = (buttons & 0b00100) != 0;
                    io.MouseDown[3] = (buttons & 0b01000) != 0;
                    io.MouseDown[4] = (buttons & 0b10000) != 0;
                }
                io.MousePos = new Vector2(x, y);
            }
            else
            {
                io.MousePos = snapshot.MousePosition;
            }

            io.MouseWheel = snapshot.WheelDelta;

            IReadOnlyList <char> keyCharPresses = snapshot.KeyCharPresses;

            for (int i = 0; i < keyCharPresses.Count; i++)
            {
                char c = keyCharPresses[i];
                io.AddInputCharacter(c);
            }

            IReadOnlyList <KeyEvent> keyEvents = snapshot.KeyEvents;

            for (int i = 0; i < keyEvents.Count; i++)
            {
                io.KeysDown[(int)keyEvents[i].Key] = keyEvents[i].Down;
            }

            io.KeyCtrl  = io.KeysDown[(int)Key.ControlLeft] || io.KeysDown[(int)Key.ControlRight];
            io.KeyAlt   = io.KeysDown[(int)Key.AltLeft] || io.KeysDown[(int)Key.AltRight];
            io.KeyShift = io.KeysDown[(int)Key.ShiftLeft] || io.KeysDown[(int)Key.ShiftRight];
            io.KeySuper = io.KeysDown[(int)Key.WinLeft] || io.KeysDown[(int)Key.WinRight];

            ImVector <ImGuiViewportPtr> viewports = ImGui.GetPlatformIO().Viewports;

            for (int i = 1; i < viewports.Size; i++)
            {
                ImGuiViewportPtr   v      = viewports[i];
                VeldridImGuiWindow window = ((VeldridImGuiWindow)GCHandle.FromIntPtr(v.PlatformUserData).Target);
                window.Update();
            }
        }
Example #14
0
        private unsafe void RenderImDrawData(DrawData *draw_data, GraphicsDevice gd, CommandList cl)
        {
            uint vertexOffsetInVertices = 0;
            uint indexOffsetInElements  = 0;

            if (draw_data->CmdListsCount == 0)
            {
                return;
            }

            uint totalVBSize = (uint)(draw_data->TotalVtxCount * sizeof(DrawVert));

            if (totalVBSize > _vertexBuffer.SizeInBytes)
            {
                gd.DisposeWhenIdle(_vertexBuffer);
                _vertexBuffer = gd.ResourceFactory.CreateBuffer(new BufferDescription((uint)(totalVBSize * 1.5f), BufferUsage.VertexBuffer | BufferUsage.Dynamic));
            }

            uint totalIBSize = (uint)(draw_data->TotalIdxCount * sizeof(ushort));

            if (totalIBSize > _indexBuffer.SizeInBytes)
            {
                gd.DisposeWhenIdle(_indexBuffer);
                _indexBuffer = gd.ResourceFactory.CreateBuffer(new BufferDescription((uint)(totalIBSize * 1.5f), BufferUsage.IndexBuffer | BufferUsage.Dynamic));
            }

            for (int i = 0; i < draw_data->CmdListsCount; i++)
            {
                NativeDrawList *cmd_list = draw_data->CmdLists[i];

                cl.UpdateBuffer(
                    _vertexBuffer,
                    vertexOffsetInVertices * (uint)sizeof(DrawVert),
                    (IntPtr)cmd_list->VtxBuffer.Data,
                    (uint)(cmd_list->VtxBuffer.Size * sizeof(DrawVert)));

                cl.UpdateBuffer(
                    _indexBuffer,
                    indexOffsetInElements * (uint)sizeof(ushort),
                    (IntPtr)cmd_list->IdxBuffer.Data,
                    (uint)(cmd_list->IdxBuffer.Size * sizeof(ushort)));

                vertexOffsetInVertices += (uint)cmd_list->VtxBuffer.Size;
                indexOffsetInElements  += (uint)cmd_list->IdxBuffer.Size;
            }

            // Setup orthographic projection matrix into our constant buffer
            {
                IO io = ImGui.GetIO();

                Matrix4x4 mvp = Matrix4x4.CreateOrthographicOffCenter(
                    0f,
                    io.DisplaySize.X,
                    io.DisplaySize.Y,
                    0.0f,
                    -1.0f,
                    1.0f);

                _gd.UpdateBuffer(_projMatrixBuffer, 0, ref mvp);
            }

            cl.SetVertexBuffer(0, _vertexBuffer);
            cl.SetIndexBuffer(_indexBuffer, IndexFormat.UInt16);
            cl.SetPipeline(_pipeline);
            cl.SetGraphicsResourceSet(0, _mainResourceSet);

            ImGui.ScaleClipRects(draw_data, ImGui.GetIO().DisplayFramebufferScale);

            // Render command lists
            int vtx_offset = 0;
            int idx_offset = 0;

            for (int n = 0; n < draw_data->CmdListsCount; n++)
            {
                NativeDrawList *cmd_list = draw_data->CmdLists[n];
                for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
                {
                    DrawCmd *pcmd = &(((DrawCmd *)cmd_list->CmdBuffer.Data)[cmd_i]);
                    if (pcmd->UserCallback != IntPtr.Zero)
                    {
                        throw new NotImplementedException();
                    }
                    else
                    {
                        if (pcmd->TextureId != IntPtr.Zero)
                        {
                            if (pcmd->TextureId == _fontAtlasID)
                            {
                                cl.SetGraphicsResourceSet(1, _fontTextureResourceSet);
                            }
                            else
                            {
                                cl.SetGraphicsResourceSet(1, GetImageResourceSet(pcmd->TextureId));
                            }
                        }

                        cl.SetScissorRect(
                            0,
                            (uint)pcmd->ClipRect.X,
                            (uint)pcmd->ClipRect.Y,
                            (uint)(pcmd->ClipRect.Z - pcmd->ClipRect.X),
                            (uint)(pcmd->ClipRect.W - pcmd->ClipRect.Y));

                        cl.DrawIndexed(pcmd->ElemCount, 1, (uint)idx_offset, vtx_offset, 0);
                    }

                    idx_offset += (int)pcmd->ElemCount;
                }
                vtx_offset += cmd_list->VtxBuffer.Size;
            }
        }
Example #15
0
        private static void OnKeyReleased(object sender, KeyEventArgs args)
        {
            var io = ImGui.GetIO();

            io.KeysDown[(int)args.Code] = false;
        }
Example #16
0
 private unsafe void OnKeyUp(object sender, KeyboardKeyEventArgs e)
 {
     ImGui.GetIO().KeysDown[(int)e.Key] = false;
     UpdateModifiers(e);
 }
Example #17
0
 public static void Render(RenderTarget target)
 {
     target.ResetGLStates();
     ImGui.Render();
     RenderDrawLists(ImGui.GetDrawData(), ImGui.GetIO());
 }
Example #18
0
        private unsafe void RenderImDrawData(DrawData *draw_data)
        {
            // Rendering
            int display_w, display_h;

            display_w = _nativeWindow.Width;
            display_h = _nativeWindow.Height;

            Vector4 clear_color = new Vector4(114f / 255f, 144f / 255f, 154f / 255f, 1.0f);

            GL.Viewport(0, 0, display_w, display_h);
            GL.ClearColor(clear_color.X, clear_color.Y, clear_color.Z, clear_color.W);
            GL.Clear(ClearBufferMask.ColorBufferBit);

            // We are using the OpenGL fixed pipeline to make the example code simpler to read!
            // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers.
            int last_texture;

            GL.GetInteger(GetPName.TextureBinding2D, out last_texture);
            GL.PushAttrib(AttribMask.EnableBit | AttribMask.ColorBufferBit | AttribMask.TransformBit);
            GL.Enable(EnableCap.Blend);
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            GL.Disable(EnableCap.CullFace);
            GL.Disable(EnableCap.DepthTest);
            GL.Enable(EnableCap.ScissorTest);
            GL.EnableClientState(ArrayCap.VertexArray);
            GL.EnableClientState(ArrayCap.TextureCoordArray);
            GL.EnableClientState(ArrayCap.ColorArray);
            GL.Enable(EnableCap.Texture2D);

            GL.UseProgram(0);

            // Handle cases of screen coordinates != from framebuffer coordinates (e.g. retina displays)
            IO io = ImGui.GetIO();

            ImGui.ScaleClipRects(draw_data, io.DisplayFramebufferScale);

            // Setup orthographic projection matrix
            GL.MatrixMode(MatrixMode.Projection);
            GL.PushMatrix();
            GL.LoadIdentity();
            GL.Ortho(
                0.0f,
                io.DisplaySize.X / io.DisplayFramebufferScale.X,
                io.DisplaySize.Y / io.DisplayFramebufferScale.Y,
                0.0f,
                -1.0f,
                1.0f);
            GL.MatrixMode(MatrixMode.Modelview);
            GL.PushMatrix();
            GL.LoadIdentity();

            // Render command lists

            for (int n = 0; n < draw_data->CmdListsCount; n++)
            {
                NativeDrawList *cmd_list   = draw_data->CmdLists[n];
                byte *          vtx_buffer = (byte *)cmd_list->VtxBuffer.Data;
                ushort *        idx_buffer = (ushort *)cmd_list->IdxBuffer.Data;

                DrawVert vert0 = *((DrawVert *)vtx_buffer);
                DrawVert vert1 = *(((DrawVert *)vtx_buffer) + 1);
                DrawVert vert2 = *(((DrawVert *)vtx_buffer) + 2);

                GL.VertexPointer(2, VertexPointerType.Float, sizeof(DrawVert), new IntPtr(vtx_buffer + DrawVert.PosOffset));
                GL.TexCoordPointer(2, TexCoordPointerType.Float, sizeof(DrawVert), new IntPtr(vtx_buffer + DrawVert.UVOffset));
                GL.ColorPointer(4, ColorPointerType.UnsignedByte, sizeof(DrawVert), new IntPtr(vtx_buffer + DrawVert.ColOffset));

                for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
                {
                    DrawCmd *pcmd = &(((DrawCmd *)cmd_list->CmdBuffer.Data)[cmd_i]);
                    if (pcmd->UserCallback != IntPtr.Zero)
                    {
                        throw new NotImplementedException();
                    }
                    else
                    {
                        GL.BindTexture(TextureTarget.Texture2D, pcmd->TextureId.ToInt32());
                        GL.Scissor(
                            (int)pcmd->ClipRect.X,
                            (int)(io.DisplaySize.Y - pcmd->ClipRect.W),
                            (int)(pcmd->ClipRect.Z - pcmd->ClipRect.X),
                            (int)(pcmd->ClipRect.W - pcmd->ClipRect.Y));
                        ushort[] indices = new ushort[pcmd->ElemCount];
                        for (int i = 0; i < indices.Length; i++)
                        {
                            indices[i] = idx_buffer[i];
                        }
                        GL.DrawElements(PrimitiveType.Triangles, (int)pcmd->ElemCount, DrawElementsType.UnsignedShort, new IntPtr(idx_buffer));
                    }
                    idx_buffer += pcmd->ElemCount;
                }
            }

            // Restore modified state
            GL.DisableClientState(ArrayCap.ColorArray);
            GL.DisableClientState(ArrayCap.TextureCoordArray);
            GL.DisableClientState(ArrayCap.VertexArray);
            GL.BindTexture(TextureTarget.Texture2D, last_texture);
            GL.MatrixMode(MatrixMode.Modelview);
            GL.PopMatrix();
            GL.MatrixMode(MatrixMode.Projection);
            GL.PopMatrix();
            GL.PopAttrib();

            _graphicsContext.SwapBuffers();
        }
Example #19
0
        private unsafe void CreateDeviceObjects()
        {
            IO io = ImGui.GetIO();

            // Build texture atlas
            FontTextureData texData = io.FontAtlas.GetTexDataAsRGBA32();

            // Create DirectX Texture
            fontTexture = new Texture2D(Device, new Texture2DDescription()
            {
                Width             = texData.Width,
                Height            = texData.Height,
                MipLevels         = 1,
                ArraySize         = 1,
                Format            = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                SampleDescription = new SharpDX.DXGI.SampleDescription(1, 1),
                Usage             = ResourceUsage.Default,
                BindFlags         = BindFlags.ShaderResource,
                CpuAccessFlags    = 0
            }, new SharpDX.DataRectangle(new IntPtr(texData.Pixels), texData.Width));

            fontTextureView = new ShaderResourceView(Device, fontTexture, new ShaderResourceViewDescription()
            {
                Format    = SharpDX.DXGI.Format.R8G8B8A8_UNorm,
                Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D,
                Texture2D = new ShaderResourceViewDescription.Texture2DResource()
                {
                    MipLevels       = 1,
                    MostDetailedMip = 0,
                }
            });

            io.FontAtlas.SetTexID(FontTextureId);

            // Create texture sampler
            fontSampler = new SamplerState(Device, new SamplerStateDescription()
            {
                Filter             = Filter.MinMagMipLinear,
                AddressU           = TextureAddressMode.Wrap,
                AddressV           = TextureAddressMode.Wrap,
                AddressW           = TextureAddressMode.Wrap,
                MipLodBias         = 0.0f,
                ComparisonFunction = Comparison.Always,
                MinimumLod         = 0.0f,
                MaximumLod         = 0.0f
            });

            // Compile Shader
            var vertexShaderByteCode = ShaderBytecode.Compile(vertexShaderCode, "vs_4_0", ShaderFlags.None, EffectFlags.None);
            var vertexShader         = new VertexShader(Device, vertexShaderByteCode);

            var pixelShaderByteCode = ShaderBytecode.Compile(pixelShaderCode, "ps_4_0", ShaderFlags.None, EffectFlags.None);
            var pixelShader         = new PixelShader(Device, pixelShaderByteCode);

            inputLayout = new InputLayout(Device,
                                          ShaderSignature.GetInputSignature(vertexShaderByteCode),
                                          new[]
            {
                new InputElement("POSITION", 0, Format.R32G32_Float, 0),
                new InputElement("TEXCOORD", 0, Format.R32G32_Float, 1),
                new InputElement("COLOR", 0, Format.R8G8B8A8_UNorm, 2)
            });

            vertexConstantBuffer = new Buffer(Device, SharpDX.Utilities.SizeOf <SharpDX.Matrix>(), ResourceUsage.Dynamic, BindFlags.ConstantBuffer, CpuAccessFlags.Write, ResourceOptionFlags.None, 0);

            // Create the blending setup
            var blendStateDesc = new BlendStateDescription();

            blendStateDesc.AlphaToCoverageEnable                 = true;
            blendStateDesc.RenderTarget[0].IsBlendEnabled        = true;
            blendStateDesc.RenderTarget[0].SourceAlphaBlend      = BlendOption.SourceAlpha;
            blendStateDesc.RenderTarget[0].DestinationBlend      = BlendOption.InverseSourceAlpha;
            blendStateDesc.RenderTarget[0].BlendOperation        = BlendOperation.Add;
            blendStateDesc.RenderTarget[0].SourceBlend           = BlendOption.InverseSourceAlpha;
            blendStateDesc.RenderTarget[0].DestinationAlphaBlend = BlendOption.Zero;
            blendStateDesc.RenderTarget[0].AlphaBlendOperation   = BlendOperation.Add;
            blendStateDesc.RenderTarget[0].RenderTargetWriteMask = ColorWriteMaskFlags.All;
            blendState = new BlendState(Device, blendStateDesc);

            // Create the rasterizer state
            rasterizerState = new RasterizerState(Device, new RasterizerStateDescription()
            {
                FillMode           = FillMode.Solid,
                CullMode           = CullMode.None,
                IsScissorEnabled   = true,
                IsDepthClipEnabled = true,
            });

            // Create depth-stencil State
            depthStencilState = new DepthStencilState(Device, new DepthStencilStateDescription()
            {
                IsDepthEnabled   = true,
                DepthWriteMask   = DepthWriteMask.All,
                DepthComparison  = Comparison.Always,
                IsStencilEnabled = false,
                FrontFace        = new DepthStencilOperationDescription()
                {
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation      = StencilOperation.Keep
                },
                BackFace = new DepthStencilOperationDescription()
                {
                    FailOperation      = StencilOperation.Keep,
                    DepthFailOperation = StencilOperation.Keep,
                    PassOperation      = StencilOperation.Keep
                }
            });
        }