Merge remote-tracking branch 'ImGuiBase/docking' into docking
commit
7c6ae45ee0
@ -0,0 +1 @@
|
||||
custom: ['https://github.com/ocornut/imgui/wiki/Sponsors']
|
@ -0,0 +1,15 @@
|
||||
#
|
||||
# This is a dummy workflow used to trigger scheduled builds. Forked repositories most likely should disable this
|
||||
# workflow to avoid daily builds of inactive repositories.
|
||||
#
|
||||
name: scheduled
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 9 * * *'
|
||||
|
||||
jobs:
|
||||
scheduled:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- run: exit 0
|
@ -0,0 +1,77 @@
|
||||
name: static-analysis
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
# Perform static analysis together with build workflow. Build triggers of "build" workflow do not need to be repeated here.
|
||||
workflows:
|
||||
- build
|
||||
types:
|
||||
- requested
|
||||
|
||||
jobs:
|
||||
PVS-Studio:
|
||||
runs-on: ubuntu-18.04
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Install Dependencies
|
||||
env:
|
||||
# The Secret variable setup in GitHub must be in format: "name_or_email key", on a single line
|
||||
PVS_STUDIO_LICENSE: ${{ secrets.PVS_STUDIO_LICENSE }}
|
||||
run: |
|
||||
if [[ "$PVS_STUDIO_LICENSE" != "" ]];
|
||||
then
|
||||
wget -q https://files.viva64.com/etc/pubkey.txt
|
||||
sudo apt-key add pubkey.txt
|
||||
sudo wget -O /etc/apt/sources.list.d/viva64.list https://files.viva64.com/etc/viva64.list
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y pvs-studio
|
||||
pvs-studio-analyzer credentials -o pvs-studio.lic $PVS_STUDIO_LICENSE
|
||||
fi
|
||||
|
||||
- name: PVS-Studio static analysis
|
||||
run: |
|
||||
if [[ ! -f pvs-studio.lic ]];
|
||||
then
|
||||
echo "PVS Studio license is missing. No analysis will be performed."
|
||||
echo "If you have a PVS Studio license please create a project secret named PVS_STUDIO_LICENSE with your license."
|
||||
echo "You may use a free license. More information at https://www.viva64.com/en/b/0457/"
|
||||
exit 0
|
||||
fi
|
||||
cd examples/example_null
|
||||
pvs-studio-analyzer trace -- make WITH_EXTRA_WARNINGS=1
|
||||
pvs-studio-analyzer analyze -e ../../imstb_rectpack.h -e ../../imstb_textedit.h -e ../../imstb_truetype.h -l ../../pvs-studio.lic -o pvs-studio.log
|
||||
plog-converter -a 'GA:1,2;OP:1' -d V1071 -t errorfile -w pvs-studio.log
|
||||
|
||||
Discord-CI:
|
||||
runs-on: ubuntu-18.04
|
||||
needs: [PVS-Studio]
|
||||
if: always()
|
||||
steps:
|
||||
- uses: dearimgui/github_discord_notifier@latest
|
||||
with:
|
||||
discord-webhook: ${{ secrets.DISCORD_CI_WEBHOOK }}
|
||||
github-token: ${{ github.token }}
|
||||
action-task: discord-jobs
|
||||
discord-filter: "'{{ github.branch }}'.match(/master|docking/g) != null && '{{ run.conclusion }}' != '{{ last_run.conclusion }}'"
|
||||
discord-username: GitHub Actions
|
||||
discord-job-new-failure-message: ''
|
||||
discord-job-fixed-failure-message: ''
|
||||
discord-job-new-failure-embed: |
|
||||
{
|
||||
"title": "`{{ job.name }}` job is failing on `{{ github.branch }}`!",
|
||||
"description": "Commit [{{ github.context.payload.head_commit.title }}]({{ github.context.payload.head_commit.url }}) pushed to [{{ github.branch }}]({{ github.branch_url }}) broke static analysis [{{ job.name }}]({{ job.url }}) job.\nFailing steps: {{ failing_steps }}",
|
||||
"url": "{{ job.url }}",
|
||||
"color": "0xFF0000",
|
||||
"timestamp": "{{ run.updated_at }}"
|
||||
}
|
||||
discord-job-fixed-failure-embed: |
|
||||
{
|
||||
"title": "`{{ github.branch }}` branch is no longer failing!",
|
||||
"description": "Static analysis failures were fixed on [{{ github.branch }}]({{ github.branch_url }}) branch.",
|
||||
"color": "0x00FF00",
|
||||
"url": "{{ github.context.payload.head_commit.url }}",
|
||||
"timestamp": "{{ run.completed_at }}"
|
||||
}
|
@ -0,0 +1,187 @@
|
||||
// dear imgui: Platform Binding for Android native app
|
||||
// This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Keyboard arrays indexed using AKEYCODE_* codes, e.g. ImGui::IsKeyPressed(AKEYCODE_SPACE).
|
||||
// Missing features:
|
||||
// [ ] Platform: Clipboard support.
|
||||
// [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
|
||||
// [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android.
|
||||
// Important:
|
||||
// - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446)
|
||||
// - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446)
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2021-03-04: Initial version.
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_android.h"
|
||||
#include <time.h>
|
||||
#include <map>
|
||||
#include <queue>
|
||||
#include <android/native_window.h>
|
||||
#include <android/input.h>
|
||||
#include <android/keycodes.h>
|
||||
#include <android/log.h>
|
||||
|
||||
// Android data
|
||||
static double g_Time = 0.0;
|
||||
static ANativeWindow* g_Window;
|
||||
static char g_LogTag[] = "ImGuiExample";
|
||||
static std::map<int32_t, std::queue<int32_t>> g_KeyEventQueues; // FIXME: Remove dependency on map and queue once we use upcoming input queue.
|
||||
|
||||
int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
int32_t event_type = AInputEvent_getType(input_event);
|
||||
switch (event_type)
|
||||
{
|
||||
case AINPUT_EVENT_TYPE_KEY:
|
||||
{
|
||||
int32_t event_key_code = AKeyEvent_getKeyCode(input_event);
|
||||
int32_t event_action = AKeyEvent_getAction(input_event);
|
||||
int32_t event_meta_state = AKeyEvent_getMetaState(input_event);
|
||||
|
||||
io.KeyCtrl = ((event_meta_state & AMETA_CTRL_ON) != 0);
|
||||
io.KeyShift = ((event_meta_state & AMETA_SHIFT_ON) != 0);
|
||||
io.KeyAlt = ((event_meta_state & AMETA_ALT_ON) != 0);
|
||||
|
||||
switch (event_action)
|
||||
{
|
||||
// FIXME: AKEY_EVENT_ACTION_DOWN and AKEY_EVENT_ACTION_UP occur at once as soon as a touch pointer
|
||||
// goes up from a key. We use a simple key event queue/ and process one event per key per frame in
|
||||
// ImGui_ImplAndroid_NewFrame()...or consider using IO queue, if suitable: https://github.com/ocornut/imgui/issues/2787
|
||||
case AKEY_EVENT_ACTION_DOWN:
|
||||
case AKEY_EVENT_ACTION_UP:
|
||||
g_KeyEventQueues[event_key_code].push(event_action);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case AINPUT_EVENT_TYPE_MOTION:
|
||||
{
|
||||
int32_t event_action = AMotionEvent_getAction(input_event);
|
||||
int32_t event_pointer_index = (event_action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
|
||||
event_action &= AMOTION_EVENT_ACTION_MASK;
|
||||
switch (event_action)
|
||||
{
|
||||
case AMOTION_EVENT_ACTION_DOWN:
|
||||
case AMOTION_EVENT_ACTION_UP:
|
||||
// Physical mouse buttons (and probably other physical devices) also invoke the actions AMOTION_EVENT_ACTION_DOWN/_UP,
|
||||
// but we have to process them separately to identify the actual button pressed. This is done below via
|
||||
// AMOTION_EVENT_ACTION_BUTTON_PRESS/_RELEASE. Here, we only process "FINGER" input (and "UNKNOWN", as a fallback).
|
||||
if((AMotionEvent_getToolType(input_event, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_FINGER)
|
||||
|| (AMotionEvent_getToolType(input_event, event_pointer_index) == AMOTION_EVENT_TOOL_TYPE_UNKNOWN))
|
||||
{
|
||||
io.MouseDown[0] = (event_action == AMOTION_EVENT_ACTION_DOWN);
|
||||
io.MousePos = ImVec2(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index));
|
||||
}
|
||||
break;
|
||||
case AMOTION_EVENT_ACTION_BUTTON_PRESS:
|
||||
case AMOTION_EVENT_ACTION_BUTTON_RELEASE:
|
||||
{
|
||||
int32_t button_state = AMotionEvent_getButtonState(input_event);
|
||||
io.MouseDown[0] = ((button_state & AMOTION_EVENT_BUTTON_PRIMARY) != 0);
|
||||
io.MouseDown[1] = ((button_state & AMOTION_EVENT_BUTTON_SECONDARY) != 0);
|
||||
io.MouseDown[2] = ((button_state & AMOTION_EVENT_BUTTON_TERTIARY) != 0);
|
||||
}
|
||||
break;
|
||||
case AMOTION_EVENT_ACTION_HOVER_MOVE: // Hovering: Tool moves while NOT pressed (such as a physical mouse)
|
||||
case AMOTION_EVENT_ACTION_MOVE: // Touch pointer moves while DOWN
|
||||
io.MousePos = ImVec2(AMotionEvent_getX(input_event, event_pointer_index), AMotionEvent_getY(input_event, event_pointer_index));
|
||||
break;
|
||||
case AMOTION_EVENT_ACTION_SCROLL:
|
||||
io.MouseWheel = AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_VSCROLL, event_pointer_index);
|
||||
io.MouseWheelH = AMotionEvent_getAxisValue(input_event, AMOTION_EVENT_AXIS_HSCROLL, event_pointer_index);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool ImGui_ImplAndroid_Init(ANativeWindow* window)
|
||||
{
|
||||
g_Window = window;
|
||||
g_Time = 0.0;
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.BackendPlatformName = "imgui_impl_android";
|
||||
|
||||
// Keyboard mapping. Dear ImGui will use those indices to peek into the io.KeysDown[] array.
|
||||
io.KeyMap[ImGuiKey_Tab] = AKEYCODE_TAB;
|
||||
io.KeyMap[ImGuiKey_LeftArrow] = AKEYCODE_DPAD_LEFT; // also covers physical keyboard arrow key
|
||||
io.KeyMap[ImGuiKey_RightArrow] = AKEYCODE_DPAD_RIGHT; // also covers physical keyboard arrow key
|
||||
io.KeyMap[ImGuiKey_UpArrow] = AKEYCODE_DPAD_UP; // also covers physical keyboard arrow key
|
||||
io.KeyMap[ImGuiKey_DownArrow] = AKEYCODE_DPAD_DOWN; // also covers physical keyboard arrow key
|
||||
io.KeyMap[ImGuiKey_PageUp] = AKEYCODE_PAGE_UP;
|
||||
io.KeyMap[ImGuiKey_PageDown] = AKEYCODE_PAGE_DOWN;
|
||||
io.KeyMap[ImGuiKey_Home] = AKEYCODE_MOVE_HOME;
|
||||
io.KeyMap[ImGuiKey_End] = AKEYCODE_MOVE_END;
|
||||
io.KeyMap[ImGuiKey_Insert] = AKEYCODE_INSERT;
|
||||
io.KeyMap[ImGuiKey_Delete] = AKEYCODE_FORWARD_DEL;
|
||||
io.KeyMap[ImGuiKey_Backspace] = AKEYCODE_DEL;
|
||||
io.KeyMap[ImGuiKey_Space] = AKEYCODE_SPACE;
|
||||
io.KeyMap[ImGuiKey_Enter] = AKEYCODE_ENTER;
|
||||
io.KeyMap[ImGuiKey_Escape] = AKEYCODE_ESCAPE;
|
||||
io.KeyMap[ImGuiKey_KeyPadEnter] = AKEYCODE_NUMPAD_ENTER;
|
||||
io.KeyMap[ImGuiKey_A] = AKEYCODE_A;
|
||||
io.KeyMap[ImGuiKey_C] = AKEYCODE_C;
|
||||
io.KeyMap[ImGuiKey_V] = AKEYCODE_V;
|
||||
io.KeyMap[ImGuiKey_X] = AKEYCODE_X;
|
||||
io.KeyMap[ImGuiKey_Y] = AKEYCODE_Y;
|
||||
io.KeyMap[ImGuiKey_Z] = AKEYCODE_Z;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplAndroid_Shutdown()
|
||||
{
|
||||
}
|
||||
|
||||
void ImGui_ImplAndroid_NewFrame()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// Process queued key events
|
||||
// FIXME: This is a workaround for multiple key event actions occurring at once (see above) and can be removed once we use upcoming input queue.
|
||||
for (auto& key_queue : g_KeyEventQueues)
|
||||
{
|
||||
if (key_queue.second.empty())
|
||||
continue;
|
||||
io.KeysDown[key_queue.first] = (key_queue.second.front() == AKEY_EVENT_ACTION_DOWN);
|
||||
key_queue.second.pop();
|
||||
}
|
||||
|
||||
// Setup display size (every frame to accommodate for window resizing)
|
||||
int32_t window_width = ANativeWindow_getWidth(g_Window);
|
||||
int32_t window_height = ANativeWindow_getHeight(g_Window);
|
||||
int display_width = window_width;
|
||||
int display_height = window_height;
|
||||
|
||||
io.DisplaySize = ImVec2((float)window_width, (float)window_height);
|
||||
if (window_width > 0 && window_height > 0)
|
||||
io.DisplayFramebufferScale = ImVec2((float)display_width / window_width, (float)display_height / window_height);
|
||||
|
||||
// Setup time step
|
||||
struct timespec current_timespec;
|
||||
clock_gettime(CLOCK_MONOTONIC, ¤t_timespec);
|
||||
double current_time = (double)(current_timespec.tv_sec) + (current_timespec.tv_nsec / 1000000000.0);
|
||||
io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f / 60.0f);
|
||||
g_Time = current_time;
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
// dear imgui: Platform Binding for Android native app
|
||||
// This needs to be used along with the OpenGL 3 Renderer (imgui_impl_opengl3)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Keyboard arrays indexed using AKEYCODE_* codes, e.g. ImGui::IsKeyPressed(AKEYCODE_SPACE).
|
||||
// Missing features:
|
||||
// [ ] Platform: Clipboard support.
|
||||
// [ ] Platform: Gamepad support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
|
||||
// [ ] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'. FIXME: Check if this is even possible with Android.
|
||||
// Important:
|
||||
// - FIXME: On-screen keyboard currently needs to be enabled by the application (see examples/ and issue #3446)
|
||||
// - FIXME: Unicode character inputs needs to be passed by Dear ImGui by the application (see examples/ and issue #3446)
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
#pragma once
|
||||
|
||||
struct ANativeWindow;
|
||||
struct AInputEvent;
|
||||
|
||||
IMGUI_IMPL_API bool ImGui_ImplAndroid_Init(ANativeWindow* window);
|
||||
IMGUI_IMPL_API int32_t ImGui_ImplAndroid_HandleInputEvent(AInputEvent* input_event);
|
||||
IMGUI_IMPL_API void ImGui_ImplAndroid_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplAndroid_NewFrame();
|
@ -1,14 +1,15 @@
|
||||
// dear imgui: Renderer for DirectX10
|
||||
// This needs to be used along with a Platform Binding (e.g. Win32)
|
||||
// dear imgui: Renderer Backend for DirectX10
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'ID3D10ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
|
||||
// [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
|
||||
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
|
||||
|
||||
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
|
||||
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
|
||||
// https://github.com/ocornut/imgui
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
@ -1,14 +1,15 @@
|
||||
// dear imgui: Renderer for DirectX11
|
||||
// This needs to be used along with a Platform Binding (e.g. Win32)
|
||||
// dear imgui: Renderer Backend for DirectX11
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID!
|
||||
// [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
|
||||
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
|
||||
|
||||
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
|
||||
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
|
||||
// https://github.com/ocornut/imgui
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
@ -0,0 +1,532 @@
|
||||
// dear imgui: Renderer Backend for DirectX9
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID!
|
||||
// [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
|
||||
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2021-XX-XX: Platform: Added support for multiple windows via the ImGuiPlatformIO interface.
|
||||
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
|
||||
// 2021-06-25: DirectX9: Explicitly disable texture state stages after >= 1.
|
||||
// 2021-05-19: DirectX9: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
|
||||
// 2021-04-23: DirectX9: Explicitly setting up more graphics states to increase compatibility with unusual non-default states.
|
||||
// 2021-03-18: DirectX9: Calling IDirect3DStateBlock9::Capture() after CreateStateBlock() as a workaround for state restoring issues (see #3857).
|
||||
// 2021-03-03: DirectX9: Added support for IMGUI_USE_BGRA_PACKED_COLOR in user's imconfig file.
|
||||
// 2021-02-18: DirectX9: Change blending equation to preserve alpha in output buffer.
|
||||
// 2019-05-29: DirectX9: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
|
||||
// 2019-04-30: DirectX9: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
|
||||
// 2019-03-29: Misc: Fixed erroneous assert in ImGui_ImplDX9_InvalidateDeviceObjects().
|
||||
// 2019-01-16: Misc: Disabled fog before drawing UI's. Fixes issue #2288.
|
||||
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
|
||||
// 2018-06-08: Misc: Extracted imgui_impl_dx9.cpp/.h away from the old combined DX9+Win32 example.
|
||||
// 2018-06-08: DirectX9: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
|
||||
// 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud.
|
||||
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself.
|
||||
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_dx9.h"
|
||||
|
||||
// DirectX
|
||||
#include <d3d9.h>
|
||||
|
||||
// DirectX data
|
||||
struct ImGui_ImplDX9_Data
|
||||
{
|
||||
LPDIRECT3DDEVICE9 pd3dDevice;
|
||||
LPDIRECT3DVERTEXBUFFER9 pVB;
|
||||
LPDIRECT3DINDEXBUFFER9 pIB;
|
||||
LPDIRECT3DTEXTURE9 FontTexture;
|
||||
int VertexBufferSize;
|
||||
int IndexBufferSize;
|
||||
|
||||
ImGui_ImplDX9_Data() { memset(this, 0, sizeof(*this)); VertexBufferSize = 5000; IndexBufferSize = 10000; }
|
||||
};
|
||||
|
||||
struct CUSTOMVERTEX
|
||||
{
|
||||
float pos[3];
|
||||
D3DCOLOR col;
|
||||
float uv[2];
|
||||
};
|
||||
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)
|
||||
|
||||
#ifdef IMGUI_USE_BGRA_PACKED_COLOR
|
||||
#define IMGUI_COL_TO_DX9_ARGB(_COL) (_COL)
|
||||
#else
|
||||
#define IMGUI_COL_TO_DX9_ARGB(_COL) (((_COL) & 0xFF00FF00) | (((_COL) & 0xFF0000) >> 16) | (((_COL) & 0xFF) << 16))
|
||||
#endif
|
||||
|
||||
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
|
||||
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
|
||||
static ImGui_ImplDX9_Data* ImGui_ImplDX9_GetBackendData()
|
||||
{
|
||||
return ImGui::GetCurrentContext() ? (ImGui_ImplDX9_Data*)ImGui::GetIO().BackendRendererUserData : NULL;
|
||||
}
|
||||
|
||||
// Forward Declarations
|
||||
static void ImGui_ImplDX9_InitPlatformInterface();
|
||||
static void ImGui_ImplDX9_ShutdownPlatformInterface();
|
||||
static void ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows();
|
||||
static void ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows();
|
||||
|
||||
// Functions
|
||||
static void ImGui_ImplDX9_SetupRenderState(ImDrawData* draw_data)
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
|
||||
// Setup viewport
|
||||
D3DVIEWPORT9 vp;
|
||||
vp.X = vp.Y = 0;
|
||||
vp.Width = (DWORD)draw_data->DisplaySize.x;
|
||||
vp.Height = (DWORD)draw_data->DisplaySize.y;
|
||||
vp.MinZ = 0.0f;
|
||||
vp.MaxZ = 1.0f;
|
||||
bd->pd3dDevice->SetViewport(&vp);
|
||||
|
||||
// Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient)
|
||||
bd->pd3dDevice->SetPixelShader(NULL);
|
||||
bd->pd3dDevice->SetVertexShader(NULL);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_INVSRCALPHA);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_FOGENABLE, FALSE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_RANGEFOGENABLE, FALSE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_SPECULARENABLE, FALSE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_CLIPPING, TRUE);
|
||||
bd->pd3dDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
|
||||
bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
|
||||
bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
|
||||
bd->pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
|
||||
bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);
|
||||
bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
|
||||
bd->pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
|
||||
bd->pd3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);
|
||||
bd->pd3dDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
|
||||
bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
|
||||
bd->pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
|
||||
|
||||
// Setup orthographic projection matrix
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
|
||||
// Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH()
|
||||
{
|
||||
float L = draw_data->DisplayPos.x + 0.5f;
|
||||
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x + 0.5f;
|
||||
float T = draw_data->DisplayPos.y + 0.5f;
|
||||
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y + 0.5f;
|
||||
D3DMATRIX mat_identity = { { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } } };
|
||||
D3DMATRIX mat_projection =
|
||||
{ { {
|
||||
2.0f/(R-L), 0.0f, 0.0f, 0.0f,
|
||||
0.0f, 2.0f/(T-B), 0.0f, 0.0f,
|
||||
0.0f, 0.0f, 0.5f, 0.0f,
|
||||
(L+R)/(L-R), (T+B)/(B-T), 0.5f, 1.0f
|
||||
} } };
|
||||
bd->pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity);
|
||||
bd->pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity);
|
||||
bd->pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection);
|
||||
}
|
||||
}
|
||||
|
||||
// Render function.
|
||||
void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data)
|
||||
{
|
||||
// Avoid rendering when minimized
|
||||
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
|
||||
return;
|
||||
|
||||
// Create and grow buffers if needed
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
if (!bd->pVB || bd->VertexBufferSize < draw_data->TotalVtxCount)
|
||||
{
|
||||
if (bd->pVB) { bd->pVB->Release(); bd->pVB = NULL; }
|
||||
bd->VertexBufferSize = draw_data->TotalVtxCount + 5000;
|
||||
if (bd->pd3dDevice->CreateVertexBuffer(bd->VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &bd->pVB, NULL) < 0)
|
||||
return;
|
||||
}
|
||||
if (!bd->pIB || bd->IndexBufferSize < draw_data->TotalIdxCount)
|
||||
{
|
||||
if (bd->pIB) { bd->pIB->Release(); bd->pIB = NULL; }
|
||||
bd->IndexBufferSize = draw_data->TotalIdxCount + 10000;
|
||||
if (bd->pd3dDevice->CreateIndexBuffer(bd->IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &bd->pIB, NULL) < 0)
|
||||
return;
|
||||
}
|
||||
|
||||
// Backup the DX9 state
|
||||
IDirect3DStateBlock9* d3d9_state_block = NULL;
|
||||
if (bd->pd3dDevice->CreateStateBlock(D3DSBT_ALL, &d3d9_state_block) < 0)
|
||||
return;
|
||||
if (d3d9_state_block->Capture() < 0)
|
||||
{
|
||||
d3d9_state_block->Release();
|
||||
return;
|
||||
}
|
||||
|
||||
// Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to)
|
||||
D3DMATRIX last_world, last_view, last_projection;
|
||||
bd->pd3dDevice->GetTransform(D3DTS_WORLD, &last_world);
|
||||
bd->pd3dDevice->GetTransform(D3DTS_VIEW, &last_view);
|
||||
bd->pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection);
|
||||
|
||||
// Allocate buffers
|
||||
CUSTOMVERTEX* vtx_dst;
|
||||
ImDrawIdx* idx_dst;
|
||||
if (bd->pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0)
|
||||
{
|
||||
d3d9_state_block->Release();
|
||||
return;
|
||||
}
|
||||
if (bd->pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0)
|
||||
{
|
||||
bd->pVB->Unlock();
|
||||
d3d9_state_block->Release();
|
||||
return;
|
||||
}
|
||||
|
||||
// Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format.
|
||||
// FIXME-OPT: This is a minor waste of resource, the ideal is to use imconfig.h and
|
||||
// 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR
|
||||
// 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; }
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* cmd_list = draw_data->CmdLists[n];
|
||||
const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data;
|
||||
for (int i = 0; i < cmd_list->VtxBuffer.Size; i++)
|
||||
{
|
||||
vtx_dst->pos[0] = vtx_src->pos.x;
|
||||
vtx_dst->pos[1] = vtx_src->pos.y;
|
||||
vtx_dst->pos[2] = 0.0f;
|
||||
vtx_dst->col = IMGUI_COL_TO_DX9_ARGB(vtx_src->col);
|
||||
vtx_dst->uv[0] = vtx_src->uv.x;
|
||||
vtx_dst->uv[1] = vtx_src->uv.y;
|
||||
vtx_dst++;
|
||||
vtx_src++;
|
||||
}
|
||||
memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
|
||||
idx_dst += cmd_list->IdxBuffer.Size;
|
||||
}
|
||||
bd->pVB->Unlock();
|
||||
bd->pIB->Unlock();
|
||||
bd->pd3dDevice->SetStreamSource(0, bd->pVB, 0, sizeof(CUSTOMVERTEX));
|
||||
bd->pd3dDevice->SetIndices(bd->pIB);
|
||||
bd->pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);
|
||||
|
||||
// Setup desired DX state
|
||||
ImGui_ImplDX9_SetupRenderState(draw_data);
|
||||
|
||||
// Render command lists
|
||||
// (Because we merged all buffers into a single one, we maintain our own offset into them)
|
||||
int global_vtx_offset = 0;
|
||||
int global_idx_offset = 0;
|
||||
ImVec2 clip_off = draw_data->DisplayPos;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* cmd_list = draw_data->CmdLists[n];
|
||||
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
|
||||
{
|
||||
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
|
||||
if (pcmd->UserCallback != NULL)
|
||||
{
|
||||
// User callback, registered via ImDrawList::AddCallback()
|
||||
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
|
||||
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
|
||||
ImGui_ImplDX9_SetupRenderState(draw_data);
|
||||
else
|
||||
pcmd->UserCallback(cmd_list, pcmd);
|
||||
}
|
||||
else
|
||||
{
|
||||
const RECT r = { (LONG)(pcmd->ClipRect.x - clip_off.x), (LONG)(pcmd->ClipRect.y - clip_off.y), (LONG)(pcmd->ClipRect.z - clip_off.x), (LONG)(pcmd->ClipRect.w - clip_off.y) };
|
||||
const LPDIRECT3DTEXTURE9 texture = (LPDIRECT3DTEXTURE9)pcmd->GetTexID();
|
||||
bd->pd3dDevice->SetTexture(0, texture);
|
||||
bd->pd3dDevice->SetScissorRect(&r);
|
||||
bd->pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, pcmd->VtxOffset + global_vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, pcmd->IdxOffset + global_idx_offset, pcmd->ElemCount / 3);
|
||||
}
|
||||
}
|
||||
global_idx_offset += cmd_list->IdxBuffer.Size;
|
||||
global_vtx_offset += cmd_list->VtxBuffer.Size;
|
||||
}
|
||||
|
||||
// When using multi-viewports, it appears that there's an odd logic in DirectX9 which prevent subsequent windows
|
||||
// from rendering until the first window submits at least one draw call, even once. That's our workaround. (see #2560)
|
||||
if (global_vtx_offset == 0)
|
||||
bd->pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, 0, 0, 0);
|
||||
|
||||
// Restore the DX9 transform
|
||||
bd->pd3dDevice->SetTransform(D3DTS_WORLD, &last_world);
|
||||
bd->pd3dDevice->SetTransform(D3DTS_VIEW, &last_view);
|
||||
bd->pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection);
|
||||
|
||||
// Restore the DX9 state
|
||||
d3d9_state_block->Apply();
|
||||
d3d9_state_block->Release();
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX9_Init(IDirect3DDevice9* device)
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
IM_ASSERT(io.BackendRendererUserData == NULL && "Already initialized a renderer backend!");
|
||||
|
||||
// Setup backend capabilities flags
|
||||
ImGui_ImplDX9_Data* bd = IM_NEW(ImGui_ImplDX9_Data)();
|
||||
io.BackendRendererUserData = (void*)bd;
|
||||
io.BackendRendererName = "imgui_impl_dx9";
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
|
||||
|
||||
bd->pd3dDevice = device;
|
||||
bd->pd3dDevice->AddRef();
|
||||
|
||||
if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
|
||||
ImGui_ImplDX9_InitPlatformInterface();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX9_Shutdown()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
|
||||
ImGui_ImplDX9_ShutdownPlatformInterface();
|
||||
ImGui_ImplDX9_InvalidateDeviceObjects();
|
||||
if (bd->pd3dDevice) { bd->pd3dDevice->Release(); }
|
||||
io.BackendRendererName = NULL;
|
||||
io.BackendRendererUserData = NULL;
|
||||
IM_DELETE(bd);
|
||||
}
|
||||
|
||||
static bool ImGui_ImplDX9_CreateFontsTexture()
|
||||
{
|
||||
// Build texture atlas
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
unsigned char* pixels;
|
||||
int width, height, bytes_per_pixel;
|
||||
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel);
|
||||
|
||||
// Convert RGBA32 to BGRA32 (because RGBA32 is not well supported by DX9 devices)
|
||||
#ifndef IMGUI_USE_BGRA_PACKED_COLOR
|
||||
if (io.Fonts->TexPixelsUseColors)
|
||||
{
|
||||
ImU32* dst_start = (ImU32*)ImGui::MemAlloc((size_t)width * height * bytes_per_pixel);
|
||||
for (ImU32* src = (ImU32*)pixels, *dst = dst_start, *dst_end = dst_start + (size_t)width * height; dst < dst_end; src++, dst++)
|
||||
*dst = IMGUI_COL_TO_DX9_ARGB(*src);
|
||||
pixels = (unsigned char*)dst_start;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Upload texture to graphics system
|
||||
bd->FontTexture = NULL;
|
||||
if (bd->pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &bd->FontTexture, NULL) < 0)
|
||||
return false;
|
||||
D3DLOCKED_RECT tex_locked_rect;
|
||||
if (bd->FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK)
|
||||
return false;
|
||||
for (int y = 0; y < height; y++)
|
||||
memcpy((unsigned char*)tex_locked_rect.pBits + (size_t)tex_locked_rect.Pitch * y, pixels + (size_t)width * bytes_per_pixel * y, (size_t)width * bytes_per_pixel);
|
||||
bd->FontTexture->UnlockRect(0);
|
||||
|
||||
// Store our identifier
|
||||
io.Fonts->SetTexID((ImTextureID)bd->FontTexture);
|
||||
|
||||
#ifndef IMGUI_USE_BGRA_PACKED_COLOR
|
||||
if (io.Fonts->TexPixelsUseColors)
|
||||
ImGui::MemFree(pixels);
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ImGui_ImplDX9_CreateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
if (!bd || !bd->pd3dDevice)
|
||||
return false;
|
||||
if (!ImGui_ImplDX9_CreateFontsTexture())
|
||||
return false;
|
||||
ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows();
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplDX9_InvalidateDeviceObjects()
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
if (!bd || !bd->pd3dDevice)
|
||||
return;
|
||||
if (bd->pVB) { bd->pVB->Release(); bd->pVB = NULL; }
|
||||
if (bd->pIB) { bd->pIB->Release(); bd->pIB = NULL; }
|
||||
if (bd->FontTexture) { bd->FontTexture->Release(); bd->FontTexture = NULL; ImGui::GetIO().Fonts->SetTexID(NULL); } // We copied bd->pFontTextureView to io.Fonts->TexID so let's clear that as well.
|
||||
ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows();
|
||||
}
|
||||
|
||||
void ImGui_ImplDX9_NewFrame()
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
IM_ASSERT(bd != NULL && "Did you call ImGui_ImplDX9_Init()?");
|
||||
|
||||
if (!bd->FontTexture)
|
||||
ImGui_ImplDX9_CreateDeviceObjects();
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
|
||||
// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
|
||||
// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
|
||||
// Helper structure we store in the void* RenderUserData field of each ImGuiViewport to easily retrieve our backend data.
|
||||
struct ImGui_ImplDX9_ViewportData
|
||||
{
|
||||
IDirect3DSwapChain9* SwapChain;
|
||||
D3DPRESENT_PARAMETERS d3dpp;
|
||||
|
||||
ImGui_ImplDX9_ViewportData() { SwapChain = NULL; ZeroMemory(&d3dpp, sizeof(D3DPRESENT_PARAMETERS)); }
|
||||
~ImGui_ImplDX9_ViewportData() { IM_ASSERT(SwapChain == NULL); }
|
||||
};
|
||||
|
||||
static void ImGui_ImplDX9_CreateWindow(ImGuiViewport* viewport)
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
ImGui_ImplDX9_ViewportData* vd = IM_NEW(ImGui_ImplDX9_ViewportData)();
|
||||
viewport->RendererUserData = vd;
|
||||
|
||||
// PlatformHandleRaw should always be a HWND, whereas PlatformHandle might be a higher-level handle (e.g. GLFWWindow*, SDL_Window*).
|
||||
// Some backends will leave PlatformHandleRaw NULL, in which case we assume PlatformHandle will contain the HWND.
|
||||
HWND hwnd = viewport->PlatformHandleRaw ? (HWND)viewport->PlatformHandleRaw : (HWND)viewport->PlatformHandle;
|
||||
IM_ASSERT(hwnd != 0);
|
||||
|
||||
ZeroMemory(&vd->d3dpp, sizeof(D3DPRESENT_PARAMETERS));
|
||||
vd->d3dpp.Windowed = TRUE;
|
||||
vd->d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
|
||||
vd->d3dpp.BackBufferWidth = (UINT)viewport->Size.x;
|
||||
vd->d3dpp.BackBufferHeight = (UINT)viewport->Size.y;
|
||||
vd->d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
|
||||
vd->d3dpp.hDeviceWindow = hwnd;
|
||||
vd->d3dpp.EnableAutoDepthStencil = FALSE;
|
||||
vd->d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
|
||||
vd->d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync
|
||||
|
||||
HRESULT hr = bd->pd3dDevice->CreateAdditionalSwapChain(&vd->d3dpp, &vd->SwapChain); IM_UNUSED(hr);
|
||||
IM_ASSERT(hr == D3D_OK);
|
||||
IM_ASSERT(vd->SwapChain != NULL);
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX9_DestroyWindow(ImGuiViewport* viewport)
|
||||
{
|
||||
// The main viewport (owned by the application) will always have RendererUserData == NULL since we didn't create the data for it.
|
||||
if (ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData)
|
||||
{
|
||||
if (vd->SwapChain)
|
||||
vd->SwapChain->Release();
|
||||
vd->SwapChain = NULL;
|
||||
ZeroMemory(&vd->d3dpp, sizeof(D3DPRESENT_PARAMETERS));
|
||||
IM_DELETE(vd);
|
||||
}
|
||||
viewport->RendererUserData = NULL;
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX9_SetWindowSize(ImGuiViewport* viewport, ImVec2 size)
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
|
||||
if (vd->SwapChain)
|
||||
{
|
||||
vd->SwapChain->Release();
|
||||
vd->SwapChain = NULL;
|
||||
vd->d3dpp.BackBufferWidth = (UINT)size.x;
|
||||
vd->d3dpp.BackBufferHeight = (UINT)size.y;
|
||||
HRESULT hr = bd->pd3dDevice->CreateAdditionalSwapChain(&vd->d3dpp, &vd->SwapChain); IM_UNUSED(hr);
|
||||
IM_ASSERT(hr == D3D_OK);
|
||||
}
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX9_RenderWindow(ImGuiViewport* viewport, void*)
|
||||
{
|
||||
ImGui_ImplDX9_Data* bd = ImGui_ImplDX9_GetBackendData();
|
||||
ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
|
||||
ImVec4 clear_color = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);
|
||||
|
||||
LPDIRECT3DSURFACE9 render_target = NULL;
|
||||
LPDIRECT3DSURFACE9 last_render_target = NULL;
|
||||
LPDIRECT3DSURFACE9 last_depth_stencil = NULL;
|
||||
vd->SwapChain->GetBackBuffer(0, D3DBACKBUFFER_TYPE_MONO, &render_target);
|
||||
bd->pd3dDevice->GetRenderTarget(0, &last_render_target);
|
||||
bd->pd3dDevice->GetDepthStencilSurface(&last_depth_stencil);
|
||||
bd->pd3dDevice->SetRenderTarget(0, render_target);
|
||||
bd->pd3dDevice->SetDepthStencilSurface(NULL);
|
||||
|
||||
if (!(viewport->Flags & ImGuiViewportFlags_NoRendererClear))
|
||||
{
|
||||
D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f));
|
||||
bd->pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, clear_col_dx, 1.0f, 0);
|
||||
}
|
||||
|
||||
ImGui_ImplDX9_RenderDrawData(viewport->DrawData);
|
||||
|
||||
// Restore render target
|
||||
bd->pd3dDevice->SetRenderTarget(0, last_render_target);
|
||||
bd->pd3dDevice->SetDepthStencilSurface(last_depth_stencil);
|
||||
render_target->Release();
|
||||
last_render_target->Release();
|
||||
if (last_depth_stencil) last_depth_stencil->Release();
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX9_SwapBuffers(ImGuiViewport* viewport, void*)
|
||||
{
|
||||
ImGui_ImplDX9_ViewportData* vd = (ImGui_ImplDX9_ViewportData*)viewport->RendererUserData;
|
||||
HRESULT hr = vd->SwapChain->Present(NULL, NULL, vd->d3dpp.hDeviceWindow, NULL, 0);
|
||||
// Let main application handle D3DERR_DEVICELOST by resetting the device.
|
||||
IM_ASSERT(hr == D3D_OK || hr == D3DERR_DEVICELOST);
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX9_InitPlatformInterface()
|
||||
{
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
platform_io.Renderer_CreateWindow = ImGui_ImplDX9_CreateWindow;
|
||||
platform_io.Renderer_DestroyWindow = ImGui_ImplDX9_DestroyWindow;
|
||||
platform_io.Renderer_SetWindowSize = ImGui_ImplDX9_SetWindowSize;
|
||||
platform_io.Renderer_RenderWindow = ImGui_ImplDX9_RenderWindow;
|
||||
platform_io.Renderer_SwapBuffers = ImGui_ImplDX9_SwapBuffers;
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX9_ShutdownPlatformInterface()
|
||||
{
|
||||
ImGui::DestroyPlatformWindows();
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX9_CreateDeviceObjectsForPlatformWindows()
|
||||
{
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
for (int i = 1; i < platform_io.Viewports.Size; i++)
|
||||
if (!platform_io.Viewports[i]->RendererUserData)
|
||||
ImGui_ImplDX9_CreateWindow(platform_io.Viewports[i]);
|
||||
}
|
||||
|
||||
static void ImGui_ImplDX9_InvalidateDeviceObjectsForPlatformWindows()
|
||||
{
|
||||
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
|
||||
for (int i = 1; i < platform_io.Viewports.Size; i++)
|
||||
if (platform_io.Viewports[i]->RendererUserData)
|
||||
ImGui_ImplDX9_DestroyWindow(platform_io.Viewports[i]);
|
||||
}
|
@ -1,14 +1,15 @@
|
||||
// dear imgui: Renderer for DirectX9
|
||||
// This needs to be used along with a Platform Binding (e.g. Win32)
|
||||
// dear imgui: Renderer Backend for DirectX9
|
||||
// This needs to be used along with a Platform Backend (e.g. Win32)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID!
|
||||
// [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
|
||||
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
|
||||
|
||||
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
|
||||
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
|
||||
// https://github.com/ocornut/imgui
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
@ -1,12 +1,13 @@
|
||||
// dear imgui: Renderer + Platform Binding for Marmalade + IwGx
|
||||
// dear imgui: Renderer + Platform Backend for Marmalade + IwGx
|
||||
// Marmalade code: Copyright (C) 2015 by Giovanni Zito (this file is part of Dear ImGui)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'CIwTexture*' as ImTextureID. Read the FAQ about ImTextureID!
|
||||
|
||||
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
|
||||
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
|
||||
// https://github.com/ocornut/imgui
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
@ -1,13 +1,14 @@
|
||||
// dear imgui: Renderer for OpenGL2 (legacy OpenGL, fixed pipeline)
|
||||
// This needs to be used along with a Platform Binding (e.g. GLFW, SDL, Win32, custom..)
|
||||
// dear imgui: Renderer Backend for OpenGL2 (legacy OpenGL, fixed pipeline)
|
||||
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
|
||||
// [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
|
||||
|
||||
// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this.
|
||||
// If you are new to dear imgui, read examples/README.txt and read the documentation at the top of imgui.cpp.
|
||||
// https://github.com/ocornut/imgui
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
|
||||
// **Prefer using the code in imgui_impl_opengl3.cpp**
|
@ -0,0 +1,56 @@
|
||||
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
|
||||
// - Desktop GL: 2.x 3.x 4.x
|
||||
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
|
||||
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
|
||||
// [X] Renderer: Multi-viewport support. Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
|
||||
// [x] Renderer: Desktop GL only: Support for large meshes (64k+ vertices) with 16-bit indices.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
// About GLSL version:
|
||||
// The 'glsl_version' initialization parameter should be NULL (default) or a "#version XXX" string.
|
||||
// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es"
|
||||
// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp.
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
|
||||
// Backend API
|
||||
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = NULL);
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);
|
||||
|
||||
// (Optional) Called by Init/NewFrame/Shutdown
|
||||
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture();
|
||||
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
|
||||
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
|
||||
|
||||
// Specific OpenGL ES versions
|
||||
//#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten
|
||||
//#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android
|
||||
|
||||
// You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
|
||||
#if !defined(IMGUI_IMPL_OPENGL_ES2) \
|
||||
&& !defined(IMGUI_IMPL_OPENGL_ES3)
|
||||
|
||||
// Try to detect GLES on matching platforms
|
||||
#if defined(__APPLE__)
|
||||
#include "TargetConditionals.h"
|
||||
#endif
|
||||
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__))
|
||||
#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es"
|
||||
#elif defined(__EMSCRIPTEN__)
|
||||
#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
|
||||
#else
|
||||
// Otherwise imgui_impl_opengl3_loader.h will be used.
|
||||
#endif
|
||||
|
||||
#endif
|
@ -0,0 +1,730 @@
|
||||
/*
|
||||
* This file was generated with gl3w_gen.py, part of imgl3w
|
||||
* (hosted at https://github.com/dearimgui/gl3w_stripped)
|
||||
*
|
||||
* This is free and unencumbered software released into the public domain.
|
||||
*
|
||||
* Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
* distribute this software, either in source code form or as a compiled
|
||||
* binary, for any purpose, commercial or non-commercial, and by any
|
||||
* means.
|
||||
*
|
||||
* In jurisdictions that recognize copyright laws, the author or authors
|
||||
* of this software dedicate any and all copyright interest in the
|
||||
* software to the public domain. We make this dedication for the benefit
|
||||
* of the public at large and to the detriment of our heirs and
|
||||
* successors. We intend this dedication to be an overt act of
|
||||
* relinquishment in perpetuity of all present and future rights to this
|
||||
* software under copyright law.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
* OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
// We embed our own OpenGL loader to not require user to provide their own or to have to use ours, which proved to be endless problems for users.
|
||||
// Our loader is custom-generated, based on gl3w but automatically filtered to only include enums/functions that we use in this source file.
|
||||
// Regenerate with: python gl3w_gen.py --imgui-dir /path/to/imgui/
|
||||
// see https://github.com/dearimgui/gl3w_stripped for more info.
|
||||
#ifndef __gl3w_h_
|
||||
#define __gl3w_h_
|
||||
|
||||
// Adapted from KHR/khrplatform.h to avoid including entire file.
|
||||
typedef float khronos_float_t;
|
||||
typedef signed char khronos_int8_t;
|
||||
typedef unsigned char khronos_uint8_t;
|
||||
typedef signed short int khronos_int16_t;
|
||||
typedef unsigned short int khronos_uint16_t;
|
||||
#ifdef _WIN64
|
||||
typedef signed long long int khronos_intptr_t;
|
||||
typedef signed long long int khronos_ssize_t;
|
||||
#else
|
||||
typedef signed long int khronos_intptr_t;
|
||||
typedef signed long int khronos_ssize_t;
|
||||
#endif
|
||||
|
||||
#if defined(_MSC_VER) && !defined(__clang__)
|
||||
typedef signed __int64 khronos_int64_t;
|
||||
typedef unsigned __int64 khronos_uint64_t;
|
||||
#elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100)
|
||||
#include <stdint.h>
|
||||
typedef int64_t khronos_int64_t;
|
||||
typedef uint64_t khronos_uint64_t;
|
||||
#else
|
||||
typedef signed long long khronos_int64_t;
|
||||
typedef unsigned long long khronos_uint64_t;
|
||||
#endif
|
||||
|
||||
#ifndef __gl_glcorearb_h_
|
||||
#define __gl_glcorearb_h_ 1
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/*
|
||||
** Copyright 2013-2020 The Khronos Group Inc.
|
||||
** SPDX-License-Identifier: MIT
|
||||
**
|
||||
** This header is generated from the Khronos OpenGL / OpenGL ES XML
|
||||
** API Registry. The current version of the Registry, generator scripts
|
||||
** used to make the header, and the header can be found at
|
||||
** https://github.com/KhronosGroup/OpenGL-Registry
|
||||
*/
|
||||
#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN 1
|
||||
#endif
|
||||
#include <windows.h>
|
||||
#endif
|
||||
#ifndef APIENTRY
|
||||
#define APIENTRY
|
||||
#endif
|
||||
#ifndef APIENTRYP
|
||||
#define APIENTRYP APIENTRY *
|
||||
#endif
|
||||
#ifndef GLAPI
|
||||
#define GLAPI extern
|
||||
#endif
|
||||
/* glcorearb.h is for use with OpenGL core profile implementations.
|
||||
** It should should be placed in the same directory as gl.h and
|
||||
** included as <GL/glcorearb.h>.
|
||||
**
|
||||
** glcorearb.h includes only APIs in the latest OpenGL core profile
|
||||
** implementation together with APIs in newer ARB extensions which
|
||||
** can be supported by the core profile. It does not, and never will
|
||||
** include functionality removed from the core profile, such as
|
||||
** fixed-function vertex and fragment processing.
|
||||
**
|
||||
** Do not #include both <GL/glcorearb.h> and either of <GL/gl.h> or
|
||||
** <GL/glext.h> in the same source file.
|
||||
*/
|
||||
/* Generated C header for:
|
||||
* API: gl
|
||||
* Profile: core
|
||||
* Versions considered: .*
|
||||
* Versions emitted: .*
|
||||
* Default extensions included: glcore
|
||||
* Additional extensions included: _nomatch_^
|
||||
* Extensions removed: _nomatch_^
|
||||
*/
|
||||
#ifndef GL_VERSION_1_0
|
||||
typedef void GLvoid;
|
||||
typedef unsigned int GLenum;
|
||||
|
||||
typedef khronos_float_t GLfloat;
|
||||
typedef int GLint;
|
||||
typedef int GLsizei;
|
||||
typedef unsigned int GLbitfield;
|
||||
typedef double GLdouble;
|
||||
typedef unsigned int GLuint;
|
||||
typedef unsigned char GLboolean;
|
||||
typedef khronos_uint8_t GLubyte;
|
||||
#define GL_COLOR_BUFFER_BIT 0x00004000
|
||||
#define GL_FALSE 0
|
||||
#define GL_TRUE 1
|
||||
#define GL_TRIANGLES 0x0004
|
||||
#define GL_ONE 1
|
||||
#define GL_SRC_ALPHA 0x0302
|
||||
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
|
||||
#define GL_FRONT_AND_BACK 0x0408
|
||||
#define GL_POLYGON_MODE 0x0B40
|
||||
#define GL_CULL_FACE 0x0B44
|
||||
#define GL_DEPTH_TEST 0x0B71
|
||||
#define GL_STENCIL_TEST 0x0B90
|
||||
#define GL_VIEWPORT 0x0BA2
|
||||
#define GL_BLEND 0x0BE2
|
||||
#define GL_SCISSOR_BOX 0x0C10
|
||||
#define GL_SCISSOR_TEST 0x0C11
|
||||
#define GL_UNPACK_ROW_LENGTH 0x0CF2
|
||||
#define GL_PACK_ALIGNMENT 0x0D05
|
||||
#define GL_TEXTURE_2D 0x0DE1
|
||||
#define GL_UNSIGNED_BYTE 0x1401
|
||||
#define GL_UNSIGNED_SHORT 0x1403
|
||||
#define GL_UNSIGNED_INT 0x1405
|
||||
#define GL_FLOAT 0x1406
|
||||
#define GL_RGBA 0x1908
|
||||
#define GL_FILL 0x1B02
|
||||
#define GL_VERSION 0x1F02
|
||||
#define GL_EXTENSIONS 0x1F03
|
||||
#define GL_LINEAR 0x2601
|
||||
#define GL_TEXTURE_MAG_FILTER 0x2800
|
||||
#define GL_TEXTURE_MIN_FILTER 0x2801
|
||||
typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode);
|
||||
typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
|
||||
typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);
|
||||
typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
|
||||
typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask);
|
||||
typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
|
||||
typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap);
|
||||
typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap);
|
||||
typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param);
|
||||
typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
|
||||
typedef void (APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data);
|
||||
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGPROC) (GLenum name);
|
||||
typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap);
|
||||
typedef void (APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode);
|
||||
GLAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
|
||||
GLAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
|
||||
GLAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
|
||||
GLAPI void APIENTRY glClear (GLbitfield mask);
|
||||
GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
|
||||
GLAPI void APIENTRY glDisable (GLenum cap);
|
||||
GLAPI void APIENTRY glEnable (GLenum cap);
|
||||
GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param);
|
||||
GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
|
||||
GLAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *data);
|
||||
GLAPI const GLubyte *APIENTRY glGetString (GLenum name);
|
||||
GLAPI GLboolean APIENTRY glIsEnabled (GLenum cap);
|
||||
GLAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
|
||||
#endif
|
||||
#endif /* GL_VERSION_1_0 */
|
||||
#ifndef GL_VERSION_1_1
|
||||
typedef khronos_float_t GLclampf;
|
||||
typedef double GLclampd;
|
||||
#define GL_TEXTURE_BINDING_2D 0x8069
|
||||
typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices);
|
||||
typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture);
|
||||
typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures);
|
||||
typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices);
|
||||
GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture);
|
||||
GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
|
||||
GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures);
|
||||
#endif
|
||||
#endif /* GL_VERSION_1_1 */
|
||||
#ifndef GL_VERSION_1_3
|
||||
#define GL_TEXTURE0 0x84C0
|
||||
#define GL_ACTIVE_TEXTURE 0x84E0
|
||||
typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glActiveTexture (GLenum texture);
|
||||
#endif
|
||||
#endif /* GL_VERSION_1_3 */
|
||||
#ifndef GL_VERSION_1_4
|
||||
#define GL_BLEND_DST_RGB 0x80C8
|
||||
#define GL_BLEND_SRC_RGB 0x80C9
|
||||
#define GL_BLEND_DST_ALPHA 0x80CA
|
||||
#define GL_BLEND_SRC_ALPHA 0x80CB
|
||||
#define GL_FUNC_ADD 0x8006
|
||||
typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
|
||||
typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
|
||||
GLAPI void APIENTRY glBlendEquation (GLenum mode);
|
||||
#endif
|
||||
#endif /* GL_VERSION_1_4 */
|
||||
#ifndef GL_VERSION_1_5
|
||||
typedef khronos_ssize_t GLsizeiptr;
|
||||
typedef khronos_intptr_t GLintptr;
|
||||
#define GL_ARRAY_BUFFER 0x8892
|
||||
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
|
||||
#define GL_ARRAY_BUFFER_BINDING 0x8894
|
||||
#define GL_STREAM_DRAW 0x88E0
|
||||
typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
|
||||
typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
|
||||
typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
|
||||
typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer);
|
||||
GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);
|
||||
GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);
|
||||
GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
|
||||
#endif
|
||||
#endif /* GL_VERSION_1_5 */
|
||||
#ifndef GL_VERSION_2_0
|
||||
typedef char GLchar;
|
||||
typedef khronos_int16_t GLshort;
|
||||
typedef khronos_int8_t GLbyte;
|
||||
typedef khronos_uint16_t GLushort;
|
||||
#define GL_BLEND_EQUATION_RGB 0x8009
|
||||
#define GL_BLEND_EQUATION_ALPHA 0x883D
|
||||
#define GL_FRAGMENT_SHADER 0x8B30
|
||||
#define GL_VERTEX_SHADER 0x8B31
|
||||
#define GL_COMPILE_STATUS 0x8B81
|
||||
#define GL_LINK_STATUS 0x8B82
|
||||
#define GL_INFO_LOG_LENGTH 0x8B84
|
||||
#define GL_CURRENT_PROGRAM 0x8B8D
|
||||
#define GL_UPPER_LEFT 0x8CA2
|
||||
typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
|
||||
typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
|
||||
typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
|
||||
typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
|
||||
typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
|
||||
typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
|
||||
typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
|
||||
typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
|
||||
typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
|
||||
typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
|
||||
typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
|
||||
typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
|
||||
typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
|
||||
typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
|
||||
typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
|
||||
typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
|
||||
typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
|
||||
typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
|
||||
typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
|
||||
typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
|
||||
typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
|
||||
GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader);
|
||||
GLAPI void APIENTRY glCompileShader (GLuint shader);
|
||||
GLAPI GLuint APIENTRY glCreateProgram (void);
|
||||
GLAPI GLuint APIENTRY glCreateShader (GLenum type);
|
||||
GLAPI void APIENTRY glDeleteProgram (GLuint program);
|
||||
GLAPI void APIENTRY glDeleteShader (GLuint shader);
|
||||
GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader);
|
||||
GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index);
|
||||
GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name);
|
||||
GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params);
|
||||
GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
|
||||
GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params);
|
||||
GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
|
||||
GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name);
|
||||
GLAPI void APIENTRY glLinkProgram (GLuint program);
|
||||
GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
|
||||
GLAPI void APIENTRY glUseProgram (GLuint program);
|
||||
GLAPI void APIENTRY glUniform1i (GLint location, GLint v0);
|
||||
GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
|
||||
GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
|
||||
#endif
|
||||
#endif /* GL_VERSION_2_0 */
|
||||
#ifndef GL_VERSION_3_0
|
||||
typedef khronos_uint16_t GLhalf;
|
||||
#define GL_MAJOR_VERSION 0x821B
|
||||
#define GL_MINOR_VERSION 0x821C
|
||||
#define GL_NUM_EXTENSIONS 0x821D
|
||||
#define GL_FRAMEBUFFER_SRGB 0x8DB9
|
||||
#define GL_VERTEX_ARRAY_BINDING 0x85B5
|
||||
typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data);
|
||||
typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data);
|
||||
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index);
|
||||
typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array);
|
||||
typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays);
|
||||
typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index);
|
||||
GLAPI void APIENTRY glBindVertexArray (GLuint array);
|
||||
GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays);
|
||||
GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays);
|
||||
#endif
|
||||
#endif /* GL_VERSION_3_0 */
|
||||
#ifndef GL_VERSION_3_1
|
||||
#define GL_VERSION_3_1 1
|
||||
#define GL_PRIMITIVE_RESTART 0x8F9D
|
||||
#endif /* GL_VERSION_3_1 */
|
||||
#ifndef GL_VERSION_3_2
|
||||
#define GL_VERSION_3_2 1
|
||||
typedef struct __GLsync *GLsync;
|
||||
typedef khronos_uint64_t GLuint64;
|
||||
typedef khronos_int64_t GLint64;
|
||||
typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
|
||||
typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
|
||||
#endif
|
||||
#endif /* GL_VERSION_3_2 */
|
||||
#ifndef GL_VERSION_3_3
|
||||
#define GL_VERSION_3_3 1
|
||||
#define GL_SAMPLER_BINDING 0x8919
|
||||
typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler);
|
||||
#ifdef GL_GLEXT_PROTOTYPES
|
||||
GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler);
|
||||
#endif
|
||||
#endif /* GL_VERSION_3_3 */
|
||||
#ifndef GL_VERSION_4_1
|
||||
typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data);
|
||||
typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data);
|
||||
#endif /* GL_VERSION_4_1 */
|
||||
#ifndef GL_VERSION_4_3
|
||||
typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
|
||||
#endif /* GL_VERSION_4_3 */
|
||||
#ifndef GL_VERSION_4_5
|
||||
#define GL_CLIP_ORIGIN 0x935C
|
||||
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param);
|
||||
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param);
|
||||
#endif /* GL_VERSION_4_5 */
|
||||
#ifndef GL_ARB_bindless_texture
|
||||
typedef khronos_uint64_t GLuint64EXT;
|
||||
#endif /* GL_ARB_bindless_texture */
|
||||
#ifndef GL_ARB_cl_event
|
||||
struct _cl_context;
|
||||
struct _cl_event;
|
||||
#endif /* GL_ARB_cl_event */
|
||||
#ifndef GL_ARB_clip_control
|
||||
#define GL_ARB_clip_control 1
|
||||
#endif /* GL_ARB_clip_control */
|
||||
#ifndef GL_ARB_debug_output
|
||||
typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
|
||||
#endif /* GL_ARB_debug_output */
|
||||
#ifndef GL_EXT_EGL_image_storage
|
||||
typedef void *GLeglImageOES;
|
||||
#endif /* GL_EXT_EGL_image_storage */
|
||||
#ifndef GL_EXT_direct_state_access
|
||||
typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params);
|
||||
typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params);
|
||||
typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params);
|
||||
typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param);
|
||||
typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param);
|
||||
#endif /* GL_EXT_direct_state_access */
|
||||
#ifndef GL_NV_draw_vulkan_image
|
||||
typedef void (APIENTRY *GLVULKANPROCNV)(void);
|
||||
#endif /* GL_NV_draw_vulkan_image */
|
||||
#ifndef GL_NV_gpu_shader5
|
||||
typedef khronos_int64_t GLint64EXT;
|
||||
#endif /* GL_NV_gpu_shader5 */
|
||||
#ifndef GL_NV_vertex_buffer_unified_memory
|
||||
typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result);
|
||||
#endif /* GL_NV_vertex_buffer_unified_memory */
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef GL3W_API
|
||||
#define GL3W_API
|
||||
#endif
|
||||
|
||||
#ifndef __gl_h_
|
||||
#define __gl_h_
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define GL3W_OK 0
|
||||
#define GL3W_ERROR_INIT -1
|
||||
#define GL3W_ERROR_LIBRARY_OPEN -2
|
||||
#define GL3W_ERROR_OPENGL_VERSION -3
|
||||
|
||||
typedef void (*GL3WglProc)(void);
|
||||
typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc);
|
||||
|
||||
/* gl3w api */
|
||||
GL3W_API int imgl3wInit(void);
|
||||
GL3W_API int imgl3wInit2(GL3WGetProcAddressProc proc);
|
||||
GL3W_API int imgl3wIsSupported(int major, int minor);
|
||||
GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc);
|
||||
|
||||
/* gl3w internal state */
|
||||
union GL3WProcs {
|
||||
GL3WglProc ptr[52];
|
||||
struct {
|
||||
PFNGLACTIVETEXTUREPROC ActiveTexture;
|
||||
PFNGLATTACHSHADERPROC AttachShader;
|
||||
PFNGLBINDBUFFERPROC BindBuffer;
|
||||
PFNGLBINDSAMPLERPROC BindSampler;
|
||||
PFNGLBINDTEXTUREPROC BindTexture;
|
||||
PFNGLBINDVERTEXARRAYPROC BindVertexArray;
|
||||
PFNGLBLENDEQUATIONPROC BlendEquation;
|
||||
PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate;
|
||||
PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate;
|
||||
PFNGLBUFFERDATAPROC BufferData;
|
||||
PFNGLCLEARPROC Clear;
|
||||
PFNGLCLEARCOLORPROC ClearColor;
|
||||
PFNGLCOMPILESHADERPROC CompileShader;
|
||||
PFNGLCREATEPROGRAMPROC CreateProgram;
|
||||
PFNGLCREATESHADERPROC CreateShader;
|
||||
PFNGLDELETEBUFFERSPROC DeleteBuffers;
|
||||
PFNGLDELETEPROGRAMPROC DeleteProgram;
|
||||
PFNGLDELETESHADERPROC DeleteShader;
|
||||
PFNGLDELETETEXTURESPROC DeleteTextures;
|
||||
PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays;
|
||||
PFNGLDETACHSHADERPROC DetachShader;
|
||||
PFNGLDISABLEPROC Disable;
|
||||
PFNGLDRAWELEMENTSPROC DrawElements;
|
||||
PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex;
|
||||
PFNGLENABLEPROC Enable;
|
||||
PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray;
|
||||
PFNGLGENBUFFERSPROC GenBuffers;
|
||||
PFNGLGENTEXTURESPROC GenTextures;
|
||||
PFNGLGENVERTEXARRAYSPROC GenVertexArrays;
|
||||
PFNGLGETATTRIBLOCATIONPROC GetAttribLocation;
|
||||
PFNGLGETINTEGERVPROC GetIntegerv;
|
||||
PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog;
|
||||
PFNGLGETPROGRAMIVPROC GetProgramiv;
|
||||
PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog;
|
||||
PFNGLGETSHADERIVPROC GetShaderiv;
|
||||
PFNGLGETSTRINGPROC GetString;
|
||||
PFNGLGETSTRINGIPROC GetStringi;
|
||||
PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation;
|
||||
PFNGLISENABLEDPROC IsEnabled;
|
||||
PFNGLLINKPROGRAMPROC LinkProgram;
|
||||
PFNGLPIXELSTOREIPROC PixelStorei;
|
||||
PFNGLPOLYGONMODEPROC PolygonMode;
|
||||
PFNGLREADPIXELSPROC ReadPixels;
|
||||
PFNGLSCISSORPROC Scissor;
|
||||
PFNGLSHADERSOURCEPROC ShaderSource;
|
||||
PFNGLTEXIMAGE2DPROC TexImage2D;
|
||||
PFNGLTEXPARAMETERIPROC TexParameteri;
|
||||
PFNGLUNIFORM1IPROC Uniform1i;
|
||||
PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv;
|
||||
PFNGLUSEPROGRAMPROC UseProgram;
|
||||
PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer;
|
||||
PFNGLVIEWPORTPROC Viewport;
|
||||
} gl;
|
||||
};
|
||||
|
||||
GL3W_API extern union GL3WProcs gl3wProcs;
|
||||
|
||||
/* OpenGL functions */
|
||||
#define glActiveTexture gl3wProcs.gl.ActiveTexture
|
||||
#define glAttachShader gl3wProcs.gl.AttachShader
|
||||
#define glBindBuffer gl3wProcs.gl.BindBuffer
|
||||
#define glBindSampler gl3wProcs.gl.BindSampler
|
||||
#define glBindTexture gl3wProcs.gl.BindTexture
|
||||
#define glBindVertexArray gl3wProcs.gl.BindVertexArray
|
||||
#define glBlendEquation gl3wProcs.gl.BlendEquation
|
||||
#define glBlendEquationSeparate gl3wProcs.gl.BlendEquationSeparate
|
||||
#define glBlendFuncSeparate gl3wProcs.gl.BlendFuncSeparate
|
||||
#define glBufferData gl3wProcs.gl.BufferData
|
||||
#define glClear gl3wProcs.gl.Clear
|
||||
#define glClearColor gl3wProcs.gl.ClearColor
|
||||
#define glCompileShader gl3wProcs.gl.CompileShader
|
||||
#define glCreateProgram gl3wProcs.gl.CreateProgram
|
||||
#define glCreateShader gl3wProcs.gl.CreateShader
|
||||
#define glDeleteBuffers gl3wProcs.gl.DeleteBuffers
|
||||
#define glDeleteProgram gl3wProcs.gl.DeleteProgram
|
||||
#define glDeleteShader gl3wProcs.gl.DeleteShader
|
||||
#define glDeleteTextures gl3wProcs.gl.DeleteTextures
|
||||
#define glDeleteVertexArrays gl3wProcs.gl.DeleteVertexArrays
|
||||
#define glDetachShader gl3wProcs.gl.DetachShader
|
||||
#define glDisable gl3wProcs.gl.Disable
|
||||
#define glDrawElements gl3wProcs.gl.DrawElements
|
||||
#define glDrawElementsBaseVertex gl3wProcs.gl.DrawElementsBaseVertex
|
||||
#define glEnable gl3wProcs.gl.Enable
|
||||
#define glEnableVertexAttribArray gl3wProcs.gl.EnableVertexAttribArray
|
||||
#define glGenBuffers gl3wProcs.gl.GenBuffers
|
||||
#define glGenTextures gl3wProcs.gl.GenTextures
|
||||
#define glGenVertexArrays gl3wProcs.gl.GenVertexArrays
|
||||
#define glGetAttribLocation gl3wProcs.gl.GetAttribLocation
|
||||
#define glGetIntegerv gl3wProcs.gl.GetIntegerv
|
||||
#define glGetProgramInfoLog gl3wProcs.gl.GetProgramInfoLog
|
||||
#define glGetProgramiv gl3wProcs.gl.GetProgramiv
|
||||
#define glGetShaderInfoLog gl3wProcs.gl.GetShaderInfoLog
|
||||
#define glGetShaderiv gl3wProcs.gl.GetShaderiv
|
||||
#define glGetString gl3wProcs.gl.GetString
|
||||
#define glGetStringi gl3wProcs.gl.GetStringi
|
||||
#define glGetUniformLocation gl3wProcs.gl.GetUniformLocation
|
||||
#define glIsEnabled gl3wProcs.gl.IsEnabled
|
||||
#define glLinkProgram gl3wProcs.gl.LinkProgram
|
||||
#define glPixelStorei gl3wProcs.gl.PixelStorei
|
||||
#define glPolygonMode gl3wProcs.gl.PolygonMode
|
||||
#define glReadPixels gl3wProcs.gl.ReadPixels
|
||||
#define glScissor gl3wProcs.gl.Scissor
|
||||
#define glShaderSource gl3wProcs.gl.ShaderSource
|
||||
#define glTexImage2D gl3wProcs.gl.TexImage2D
|
||||
#define glTexParameteri gl3wProcs.gl.TexParameteri
|
||||
#define glUniform1i gl3wProcs.gl.Uniform1i
|
||||
#define glUniformMatrix4fv gl3wProcs.gl.UniformMatrix4fv
|
||||
#define glUseProgram gl3wProcs.gl.UseProgram
|
||||
#define glVertexAttribPointer gl3wProcs.gl.VertexAttribPointer
|
||||
#define glViewport gl3wProcs.gl.Viewport
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef IMGL3W_IMPL
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
|
||||
|
||||
#if defined(_WIN32)
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN 1
|
||||
#endif
|
||||
#include <windows.h>
|
||||
|
||||
static HMODULE libgl;
|
||||
typedef PROC(__stdcall* GL3WglGetProcAddr)(LPCSTR);
|
||||
static GL3WglGetProcAddr wgl_get_proc_address;
|
||||
|
||||
static int open_libgl(void)
|
||||
{
|
||||
libgl = LoadLibraryA("opengl32.dll");
|
||||
if (!libgl)
|
||||
return GL3W_ERROR_LIBRARY_OPEN;
|
||||
wgl_get_proc_address = (GL3WglGetProcAddr)GetProcAddress(libgl, "wglGetProcAddress");
|
||||
return GL3W_OK;
|
||||
}
|
||||
|
||||
static void close_libgl(void) { FreeLibrary(libgl); }
|
||||
static GL3WglProc get_proc(const char *proc)
|
||||
{
|
||||
GL3WglProc res;
|
||||
res = (GL3WglProc)wgl_get_proc_address(proc);
|
||||
if (!res)
|
||||
res = (GL3WglProc)GetProcAddress(libgl, proc);
|
||||
return res;
|
||||
}
|
||||
#elif defined(__APPLE__)
|
||||
#include <dlfcn.h>
|
||||
|
||||
static void *libgl;
|
||||
static int open_libgl(void)
|
||||
{
|
||||
libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL);
|
||||
if (!libgl)
|
||||
return GL3W_ERROR_LIBRARY_OPEN;
|
||||
return GL3W_OK;
|
||||
}
|
||||
|
||||
static void close_libgl(void) { dlclose(libgl); }
|
||||
|
||||
static GL3WglProc get_proc(const char *proc)
|
||||
{
|
||||
GL3WglProc res;
|
||||
*(void **)(&res) = dlsym(libgl, proc);
|
||||
return res;
|
||||
}
|
||||
#else
|
||||
#include <dlfcn.h>
|
||||
|
||||
static void *libgl;
|
||||
static GL3WglProc (*glx_get_proc_address)(const GLubyte *);
|
||||
|
||||
static int open_libgl(void)
|
||||
{
|
||||
libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL);
|
||||
if (!libgl)
|
||||
return GL3W_ERROR_LIBRARY_OPEN;
|
||||
*(void **)(&glx_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB");
|
||||
return GL3W_OK;
|
||||
}
|
||||
|
||||
static void close_libgl(void) { dlclose(libgl); }
|
||||
|
||||
static GL3WglProc get_proc(const char *proc)
|
||||
{
|
||||
GL3WglProc res;
|
||||
res = glx_get_proc_address((const GLubyte *)proc);
|
||||
if (!res)
|
||||
*(void **)(&res) = dlsym(libgl, proc);
|
||||
return res;
|
||||
}
|
||||
#endif
|
||||
|
||||
static struct { int major, minor; } version;
|
||||
|
||||
static int parse_version(void)
|
||||
{
|
||||
if (!glGetIntegerv)
|
||||
return GL3W_ERROR_INIT;
|
||||
glGetIntegerv(GL_MAJOR_VERSION, &version.major);
|
||||
glGetIntegerv(GL_MINOR_VERSION, &version.minor);
|
||||
if (version.major < 3)
|
||||
return GL3W_ERROR_OPENGL_VERSION;
|
||||
return GL3W_OK;
|
||||
}
|
||||
|
||||
static void load_procs(GL3WGetProcAddressProc proc);
|
||||
|
||||
int imgl3wInit(void)
|
||||
{
|
||||
int res = open_libgl();
|
||||
if (res)
|
||||
return res;
|
||||
atexit(close_libgl);
|
||||
return imgl3wInit2(get_proc);
|
||||
}
|
||||
|
||||
int imgl3wInit2(GL3WGetProcAddressProc proc)
|
||||
{
|
||||
load_procs(proc);
|
||||
return parse_version();
|
||||
}
|
||||
|
||||
int imgl3wIsSupported(int major, int minor)
|
||||
{
|
||||
if (major < 3)
|
||||
return 0;
|
||||
if (version.major == major)
|
||||
return version.minor >= minor;
|
||||
return version.major >= major;
|
||||
}
|
||||
|
||||
GL3WglProc imgl3wGetProcAddress(const char *proc) { return get_proc(proc); }
|
||||
|
||||
static const char *proc_names[] = {
|
||||
"glActiveTexture",
|
||||
"glAttachShader",
|
||||
"glBindBuffer",
|
||||
"glBindSampler",
|
||||
"glBindTexture",
|
||||
"glBindVertexArray",
|
||||
"glBlendEquation",
|
||||
"glBlendEquationSeparate",
|
||||
"glBlendFuncSeparate",
|
||||
"glBufferData",
|
||||
"glClear",
|
||||
"glClearColor",
|
||||
"glCompileShader",
|
||||
"glCreateProgram",
|
||||
"glCreateShader",
|
||||
"glDeleteBuffers",
|
||||
"glDeleteProgram",
|
||||
"glDeleteShader",
|
||||
"glDeleteTextures",
|
||||
"glDeleteVertexArrays",
|
||||
"glDetachShader",
|
||||
"glDisable",
|
||||
"glDrawElements",
|
||||
"glDrawElementsBaseVertex",
|
||||
"glEnable",
|
||||
"glEnableVertexAttribArray",
|
||||
"glGenBuffers",
|
||||
"glGenTextures",
|
||||
"glGenVertexArrays",
|
||||
"glGetAttribLocation",
|
||||
"glGetIntegerv",
|
||||
"glGetProgramInfoLog",
|
||||
"glGetProgramiv",
|
||||
"glGetShaderInfoLog",
|
||||
"glGetShaderiv",
|
||||
"glGetString",
|
||||
"glGetStringi",
|
||||
"glGetUniformLocation",
|
||||
"glIsEnabled",
|
||||
"glLinkProgram",
|
||||
"glPixelStorei",
|
||||
"glPolygonMode",
|
||||
"glReadPixels",
|
||||
"glScissor",
|
||||
"glShaderSource",
|
||||
"glTexImage2D",
|
||||
"glTexParameteri",
|
||||
"glUniform1i",
|
||||
"glUniformMatrix4fv",
|
||||
"glUseProgram",
|
||||
"glVertexAttribPointer",
|
||||
"glViewport",
|
||||
};
|
||||
|
||||
GL3W_API union GL3WProcs gl3wProcs;
|
||||
|
||||
static void load_procs(GL3WGetProcAddressProc proc)
|
||||
{
|
||||
size_t i;
|
||||
for (i = 0; i < ARRAY_SIZE(proc_names); i++)
|
||||
gl3wProcs.ptr[i] = proc(proc_names[i]);
|
||||
}
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
@ -0,0 +1,25 @@
|
||||
// dear imgui: Platform Backend for OSX / Cocoa
|
||||
// This needs to be used along with a Renderer (e.g. OpenGL2, OpenGL3, Vulkan, Metal..)
|
||||
// [ALPHA] Early backend, not well tested. If you want a portable application, prefer using the GLFW or SDL platform Backends on Mac.
|
||||
|
||||
// Implemented features:
|
||||
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
|
||||
// [X] Platform: OSX clipboard is supported within core Dear ImGui (no specific code in this backend).
|
||||
// Issues:
|
||||
// [ ] Platform: Keys are all generally very broken. Best using [event keycode] and not [event characters]..
|
||||
// [ ] Platform: Multi-viewport / platform windows.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
|
||||
@class NSEvent;
|
||||
@class NSView;
|
||||
|
||||
IMGUI_IMPL_API bool ImGui_ImplOSX_Init();
|
||||
IMGUI_IMPL_API void ImGui_ImplOSX_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplOSX_NewFrame(NSView* _Nullable view);
|
||||
IMGUI_IMPL_API bool ImGui_ImplOSX_HandleEvent(NSEvent* _Nonnull event, NSView* _Nullable view);
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,715 @@
|
||||
// dear imgui: Renderer for WebGPU
|
||||
// This needs to be used along with a Platform Binding (e.g. GLFW)
|
||||
// (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
|
||||
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
// CHANGELOG
|
||||
// (minor and older changes stripped away, please see git history for details)
|
||||
// 2021-05-24: Add support for draw_data->FramebufferScale.
|
||||
// 2021-05-19: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
|
||||
// 2021-05-16: Update to latest WebGPU specs (compatible with Emscripten 2.0.20 and Chrome Canary 92).
|
||||
// 2021-02-18: Change blending equation to preserve alpha in output buffer.
|
||||
// 2021-01-28: Initial version.
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_wgpu.h"
|
||||
#include <limits.h>
|
||||
#include <webgpu/webgpu.h>
|
||||
|
||||
#define HAS_EMSCRIPTEN_VERSION(major, minor, tiny) (__EMSCRIPTEN_major__ > (major) || (__EMSCRIPTEN_major__ == (major) && __EMSCRIPTEN_minor__ > (minor)) || (__EMSCRIPTEN_major__ == (major) && __EMSCRIPTEN_minor__ == (minor) && __EMSCRIPTEN_tiny__ >= (tiny)))
|
||||
|
||||
#if defined(__EMSCRIPTEN__) && !HAS_EMSCRIPTEN_VERSION(2, 0, 20)
|
||||
#error "Requires at least emscripten 2.0.20"
|
||||
#endif
|
||||
|
||||
// Dear ImGui prototypes from imgui_internal.h
|
||||
extern ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed = 0);
|
||||
|
||||
// WebGPU data
|
||||
static WGPUDevice g_wgpuDevice = NULL;
|
||||
static WGPUQueue g_defaultQueue = NULL;
|
||||
static WGPUTextureFormat g_renderTargetFormat = WGPUTextureFormat_Undefined;
|
||||
static WGPURenderPipeline g_pipelineState = NULL;
|
||||
|
||||
struct RenderResources
|
||||
{
|
||||
WGPUTexture FontTexture; // Font texture
|
||||
WGPUTextureView FontTextureView; // Texture view for font texture
|
||||
WGPUSampler Sampler; // Sampler for the font texture
|
||||
WGPUBuffer Uniforms; // Shader uniforms
|
||||
WGPUBindGroup CommonBindGroup; // Resources bind-group to bind the common resources to pipeline
|
||||
ImGuiStorage ImageBindGroups; // Resources bind-group to bind the font/image resources to pipeline (this is a key->value map)
|
||||
WGPUBindGroup ImageBindGroup; // Default font-resource of Dear ImGui
|
||||
WGPUBindGroupLayout ImageBindGroupLayout; // Cache layout used for the image bind group. Avoids allocating unnecessary JS objects when working with WebASM
|
||||
};
|
||||
static RenderResources g_resources;
|
||||
|
||||
struct FrameResources
|
||||
{
|
||||
WGPUBuffer IndexBuffer;
|
||||
WGPUBuffer VertexBuffer;
|
||||
ImDrawIdx* IndexBufferHost;
|
||||
ImDrawVert* VertexBufferHost;
|
||||
int IndexBufferSize;
|
||||
int VertexBufferSize;
|
||||
};
|
||||
static FrameResources* g_pFrameResources = NULL;
|
||||
static unsigned int g_numFramesInFlight = 0;
|
||||
static unsigned int g_frameIndex = UINT_MAX;
|
||||
|
||||
struct Uniforms
|
||||
{
|
||||
float MVP[4][4];
|
||||
};
|
||||
|
||||
//-----------------------------------------------------------------------------
|
||||
// SHADERS
|
||||
//-----------------------------------------------------------------------------
|
||||
|
||||
// glsl_shader.vert, compiled with:
|
||||
// # glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
|
||||
/*
|
||||
#version 450 core
|
||||
layout(location = 0) in vec2 aPos;
|
||||
layout(location = 1) in vec2 aUV;
|
||||
layout(location = 2) in vec4 aColor;
|
||||
layout(set=0, binding = 0) uniform transform { mat4 mvp; };
|
||||
|
||||
out gl_PerVertex { vec4 gl_Position; };
|
||||
layout(location = 0) out struct { vec4 Color; vec2 UV; } Out;
|
||||
|
||||
void main()
|
||||
{
|
||||
Out.Color = aColor;
|
||||
Out.UV = aUV;
|
||||
gl_Position = mvp * vec4(aPos, 0, 1);
|
||||
}
|
||||
*/
|
||||
static uint32_t __glsl_shader_vert_spv[] =
|
||||
{
|
||||
0x07230203,0x00010000,0x00080007,0x0000002c,0x00000000,0x00020011,0x00000001,0x0006000b,
|
||||
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
|
||||
0x000a000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000b,0x0000000f,0x00000015,
|
||||
0x0000001b,0x00000023,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
|
||||
0x00000000,0x00030005,0x00000009,0x00000000,0x00050006,0x00000009,0x00000000,0x6f6c6f43,
|
||||
0x00000072,0x00040006,0x00000009,0x00000001,0x00005655,0x00030005,0x0000000b,0x0074754f,
|
||||
0x00040005,0x0000000f,0x6c6f4361,0x0000726f,0x00030005,0x00000015,0x00565561,0x00060005,
|
||||
0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,0x00000000,
|
||||
0x505f6c67,0x7469736f,0x006e6f69,0x00030005,0x0000001b,0x00000000,0x00050005,0x0000001d,
|
||||
0x6e617274,0x726f6673,0x0000006d,0x00040006,0x0000001d,0x00000000,0x0070766d,0x00030005,
|
||||
0x0000001f,0x00000000,0x00040005,0x00000023,0x736f5061,0x00000000,0x00040047,0x0000000b,
|
||||
0x0000001e,0x00000000,0x00040047,0x0000000f,0x0000001e,0x00000002,0x00040047,0x00000015,
|
||||
0x0000001e,0x00000001,0x00050048,0x00000019,0x00000000,0x0000000b,0x00000000,0x00030047,
|
||||
0x00000019,0x00000002,0x00040048,0x0000001d,0x00000000,0x00000005,0x00050048,0x0000001d,
|
||||
0x00000000,0x00000023,0x00000000,0x00050048,0x0000001d,0x00000000,0x00000007,0x00000010,
|
||||
0x00030047,0x0000001d,0x00000002,0x00040047,0x0000001f,0x00000022,0x00000000,0x00040047,
|
||||
0x0000001f,0x00000021,0x00000000,0x00040047,0x00000023,0x0000001e,0x00000000,0x00020013,
|
||||
0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,
|
||||
0x00000007,0x00000006,0x00000004,0x00040017,0x00000008,0x00000006,0x00000002,0x0004001e,
|
||||
0x00000009,0x00000007,0x00000008,0x00040020,0x0000000a,0x00000003,0x00000009,0x0004003b,
|
||||
0x0000000a,0x0000000b,0x00000003,0x00040015,0x0000000c,0x00000020,0x00000001,0x0004002b,
|
||||
0x0000000c,0x0000000d,0x00000000,0x00040020,0x0000000e,0x00000001,0x00000007,0x0004003b,
|
||||
0x0000000e,0x0000000f,0x00000001,0x00040020,0x00000011,0x00000003,0x00000007,0x0004002b,
|
||||
0x0000000c,0x00000013,0x00000001,0x00040020,0x00000014,0x00000001,0x00000008,0x0004003b,
|
||||
0x00000014,0x00000015,0x00000001,0x00040020,0x00000017,0x00000003,0x00000008,0x0003001e,
|
||||
0x00000019,0x00000007,0x00040020,0x0000001a,0x00000003,0x00000019,0x0004003b,0x0000001a,
|
||||
0x0000001b,0x00000003,0x00040018,0x0000001c,0x00000007,0x00000004,0x0003001e,0x0000001d,
|
||||
0x0000001c,0x00040020,0x0000001e,0x00000002,0x0000001d,0x0004003b,0x0000001e,0x0000001f,
|
||||
0x00000002,0x00040020,0x00000020,0x00000002,0x0000001c,0x0004003b,0x00000014,0x00000023,
|
||||
0x00000001,0x0004002b,0x00000006,0x00000025,0x00000000,0x0004002b,0x00000006,0x00000026,
|
||||
0x3f800000,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,
|
||||
0x0004003d,0x00000007,0x00000010,0x0000000f,0x00050041,0x00000011,0x00000012,0x0000000b,
|
||||
0x0000000d,0x0003003e,0x00000012,0x00000010,0x0004003d,0x00000008,0x00000016,0x00000015,
|
||||
0x00050041,0x00000017,0x00000018,0x0000000b,0x00000013,0x0003003e,0x00000018,0x00000016,
|
||||
0x00050041,0x00000020,0x00000021,0x0000001f,0x0000000d,0x0004003d,0x0000001c,0x00000022,
|
||||
0x00000021,0x0004003d,0x00000008,0x00000024,0x00000023,0x00050051,0x00000006,0x00000027,
|
||||
0x00000024,0x00000000,0x00050051,0x00000006,0x00000028,0x00000024,0x00000001,0x00070050,
|
||||
0x00000007,0x00000029,0x00000027,0x00000028,0x00000025,0x00000026,0x00050091,0x00000007,
|
||||
0x0000002a,0x00000022,0x00000029,0x00050041,0x00000011,0x0000002b,0x0000001b,0x0000000d,
|
||||
0x0003003e,0x0000002b,0x0000002a,0x000100fd,0x00010038
|
||||
};
|
||||
|
||||
// glsl_shader.frag, compiled with:
|
||||
// # glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
|
||||
/*
|
||||
#version 450 core
|
||||
layout(location = 0) out vec4 fColor;
|
||||
layout(set=0, binding=1) uniform sampler s;
|
||||
layout(set=1, binding=0) uniform texture2D t;
|
||||
layout(location = 0) in struct { vec4 Color; vec2 UV; } In;
|
||||
void main()
|
||||
{
|
||||
fColor = In.Color * texture(sampler2D(t, s), In.UV.st);
|
||||
}
|
||||
*/
|
||||
static uint32_t __glsl_shader_frag_spv[] =
|
||||
{
|
||||
0x07230203,0x00010000,0x00080007,0x00000023,0x00000000,0x00020011,0x00000001,0x0006000b,
|
||||
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
|
||||
0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x0000000d,0x00030010,
|
||||
0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
|
||||
0x00000000,0x00040005,0x00000009,0x6c6f4366,0x0000726f,0x00030005,0x0000000b,0x00000000,
|
||||
0x00050006,0x0000000b,0x00000000,0x6f6c6f43,0x00000072,0x00040006,0x0000000b,0x00000001,
|
||||
0x00005655,0x00030005,0x0000000d,0x00006e49,0x00030005,0x00000015,0x00000074,0x00030005,
|
||||
0x00000019,0x00000073,0x00040047,0x00000009,0x0000001e,0x00000000,0x00040047,0x0000000d,
|
||||
0x0000001e,0x00000000,0x00040047,0x00000015,0x00000022,0x00000001,0x00040047,0x00000015,
|
||||
0x00000021,0x00000000,0x00040047,0x00000019,0x00000022,0x00000000,0x00040047,0x00000019,
|
||||
0x00000021,0x00000001,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,
|
||||
0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,0x00000004,0x00040020,0x00000008,
|
||||
0x00000003,0x00000007,0x0004003b,0x00000008,0x00000009,0x00000003,0x00040017,0x0000000a,
|
||||
0x00000006,0x00000002,0x0004001e,0x0000000b,0x00000007,0x0000000a,0x00040020,0x0000000c,
|
||||
0x00000001,0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000001,0x00040015,0x0000000e,
|
||||
0x00000020,0x00000001,0x0004002b,0x0000000e,0x0000000f,0x00000000,0x00040020,0x00000010,
|
||||
0x00000001,0x00000007,0x00090019,0x00000013,0x00000006,0x00000001,0x00000000,0x00000000,
|
||||
0x00000000,0x00000001,0x00000000,0x00040020,0x00000014,0x00000000,0x00000013,0x0004003b,
|
||||
0x00000014,0x00000015,0x00000000,0x0002001a,0x00000017,0x00040020,0x00000018,0x00000000,
|
||||
0x00000017,0x0004003b,0x00000018,0x00000019,0x00000000,0x0003001b,0x0000001b,0x00000013,
|
||||
0x0004002b,0x0000000e,0x0000001d,0x00000001,0x00040020,0x0000001e,0x00000001,0x0000000a,
|
||||
0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x00050041,
|
||||
0x00000010,0x00000011,0x0000000d,0x0000000f,0x0004003d,0x00000007,0x00000012,0x00000011,
|
||||
0x0004003d,0x00000013,0x00000016,0x00000015,0x0004003d,0x00000017,0x0000001a,0x00000019,
|
||||
0x00050056,0x0000001b,0x0000001c,0x00000016,0x0000001a,0x00050041,0x0000001e,0x0000001f,
|
||||
0x0000000d,0x0000001d,0x0004003d,0x0000000a,0x00000020,0x0000001f,0x00050057,0x00000007,
|
||||
0x00000021,0x0000001c,0x00000020,0x00050085,0x00000007,0x00000022,0x00000012,0x00000021,
|
||||
0x0003003e,0x00000009,0x00000022,0x000100fd,0x00010038
|
||||
};
|
||||
|
||||
static void SafeRelease(ImDrawIdx*& res)
|
||||
{
|
||||
if (res)
|
||||
delete[] res;
|
||||
res = NULL;
|
||||
}
|
||||
static void SafeRelease(ImDrawVert*& res)
|
||||
{
|
||||
if (res)
|
||||
delete[] res;
|
||||
res = NULL;
|
||||
}
|
||||
static void SafeRelease(WGPUBindGroupLayout& res)
|
||||
{
|
||||
if (res)
|
||||
wgpuBindGroupLayoutRelease(res);
|
||||
res = NULL;
|
||||
}
|
||||
static void SafeRelease(WGPUBindGroup& res)
|
||||
{
|
||||
if (res)
|
||||
wgpuBindGroupRelease(res);
|
||||
res = NULL;
|
||||
}
|
||||
static void SafeRelease(WGPUBuffer& res)
|
||||
{
|
||||
if (res)
|
||||
wgpuBufferRelease(res);
|
||||
res = NULL;
|
||||
}
|
||||
static void SafeRelease(WGPURenderPipeline& res)
|
||||
{
|
||||
if (res)
|
||||
wgpuRenderPipelineRelease(res);
|
||||
res = NULL;
|
||||
}
|
||||
static void SafeRelease(WGPUSampler& res)
|
||||
{
|
||||
if (res)
|
||||
wgpuSamplerRelease(res);
|
||||
res = NULL;
|
||||
}
|
||||
static void SafeRelease(WGPUShaderModule& res)
|
||||
{
|
||||
if (res)
|
||||
wgpuShaderModuleRelease(res);
|
||||
res = NULL;
|
||||
}
|
||||
static void SafeRelease(WGPUTextureView& res)
|
||||
{
|
||||
if (res)
|
||||
wgpuTextureViewRelease(res);
|
||||
res = NULL;
|
||||
}
|
||||
static void SafeRelease(WGPUTexture& res)
|
||||
{
|
||||
if (res)
|
||||
wgpuTextureRelease(res);
|
||||
res = NULL;
|
||||
}
|
||||
|
||||
static void SafeRelease(RenderResources& res)
|
||||
{
|
||||
SafeRelease(res.FontTexture);
|
||||
SafeRelease(res.FontTextureView);
|
||||
SafeRelease(res.Sampler);
|
||||
SafeRelease(res.Uniforms);
|
||||
SafeRelease(res.CommonBindGroup);
|
||||
SafeRelease(res.ImageBindGroup);
|
||||
SafeRelease(res.ImageBindGroupLayout);
|
||||
};
|
||||
|
||||
static void SafeRelease(FrameResources& res)
|
||||
{
|
||||
SafeRelease(res.IndexBuffer);
|
||||
SafeRelease(res.VertexBuffer);
|
||||
SafeRelease(res.IndexBufferHost);
|
||||
SafeRelease(res.VertexBufferHost);
|
||||
}
|
||||
|
||||
static WGPUProgrammableStageDescriptor ImGui_ImplWGPU_CreateShaderModule(uint32_t* binary_data, uint32_t binary_data_size)
|
||||
{
|
||||
WGPUShaderModuleSPIRVDescriptor spirv_desc = {};
|
||||
spirv_desc.chain.sType = WGPUSType_ShaderModuleSPIRVDescriptor;
|
||||
spirv_desc.codeSize = binary_data_size;
|
||||
spirv_desc.code = binary_data;
|
||||
|
||||
WGPUShaderModuleDescriptor desc;
|
||||
desc.nextInChain = reinterpret_cast<WGPUChainedStruct*>(&spirv_desc);
|
||||
|
||||
WGPUProgrammableStageDescriptor stage_desc = {};
|
||||
stage_desc.module = wgpuDeviceCreateShaderModule(g_wgpuDevice, &desc);
|
||||
stage_desc.entryPoint = "main";
|
||||
return stage_desc;
|
||||
}
|
||||
|
||||
static WGPUBindGroup ImGui_ImplWGPU_CreateImageBindGroup(WGPUBindGroupLayout layout, WGPUTextureView texture)
|
||||
{
|
||||
WGPUBindGroupEntry image_bg_entries[] = { { 0, 0, 0, 0, 0, texture } };
|
||||
|
||||
WGPUBindGroupDescriptor image_bg_descriptor = {};
|
||||
image_bg_descriptor.layout = layout;
|
||||
image_bg_descriptor.entryCount = sizeof(image_bg_entries) / sizeof(WGPUBindGroupEntry);
|
||||
image_bg_descriptor.entries = image_bg_entries;
|
||||
return wgpuDeviceCreateBindGroup(g_wgpuDevice, &image_bg_descriptor);
|
||||
}
|
||||
|
||||
static void ImGui_ImplWGPU_SetupRenderState(ImDrawData* draw_data, WGPURenderPassEncoder ctx, FrameResources* fr)
|
||||
{
|
||||
// Setup orthographic projection matrix into our constant buffer
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
|
||||
{
|
||||
float L = draw_data->DisplayPos.x;
|
||||
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
|
||||
float T = draw_data->DisplayPos.y;
|
||||
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
|
||||
float mvp[4][4] =
|
||||
{
|
||||
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
|
||||
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
|
||||
{ 0.0f, 0.0f, 0.5f, 0.0f },
|
||||
{ (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f },
|
||||
};
|
||||
wgpuQueueWriteBuffer(g_defaultQueue, g_resources.Uniforms, 0, mvp, sizeof(mvp));
|
||||
}
|
||||
|
||||
// Setup viewport
|
||||
wgpuRenderPassEncoderSetViewport(ctx, 0, 0, draw_data->FramebufferScale.x * draw_data->DisplaySize.x, draw_data->FramebufferScale.y * draw_data->DisplaySize.y, 0, 1);
|
||||
|
||||
// Bind shader and vertex buffers
|
||||
wgpuRenderPassEncoderSetVertexBuffer(ctx, 0, fr->VertexBuffer, 0, 0);
|
||||
wgpuRenderPassEncoderSetIndexBuffer(ctx, fr->IndexBuffer, sizeof(ImDrawIdx) == 2 ? WGPUIndexFormat_Uint16 : WGPUIndexFormat_Uint32, 0, 0);
|
||||
wgpuRenderPassEncoderSetPipeline(ctx, g_pipelineState);
|
||||
wgpuRenderPassEncoderSetBindGroup(ctx, 0, g_resources.CommonBindGroup, 0, NULL);
|
||||
|
||||
// Setup blend factor
|
||||
WGPUColor blend_color = { 0.f, 0.f, 0.f, 0.f };
|
||||
wgpuRenderPassEncoderSetBlendConstant(ctx, &blend_color);
|
||||
}
|
||||
|
||||
// Render function
|
||||
// (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop)
|
||||
void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder)
|
||||
{
|
||||
// Avoid rendering when minimized
|
||||
if (draw_data->DisplaySize.x <= 0.0f || draw_data->DisplaySize.y <= 0.0f)
|
||||
return;
|
||||
|
||||
// FIXME: Assuming that this only gets called once per frame!
|
||||
// If not, we can't just re-allocate the IB or VB, we'll have to do a proper allocator.
|
||||
g_frameIndex = g_frameIndex + 1;
|
||||
FrameResources* fr = &g_pFrameResources[g_frameIndex % g_numFramesInFlight];
|
||||
|
||||
// Create and grow vertex/index buffers if needed
|
||||
if (fr->VertexBuffer == NULL || fr->VertexBufferSize < draw_data->TotalVtxCount)
|
||||
{
|
||||
if (fr->VertexBuffer)
|
||||
{
|
||||
wgpuBufferDestroy(fr->VertexBuffer);
|
||||
wgpuBufferRelease(fr->VertexBuffer);
|
||||
}
|
||||
SafeRelease(fr->VertexBufferHost);
|
||||
fr->VertexBufferSize = draw_data->TotalVtxCount + 5000;
|
||||
|
||||
WGPUBufferDescriptor vb_desc =
|
||||
{
|
||||
NULL,
|
||||
"Dear ImGui Vertex buffer",
|
||||
WGPUBufferUsage_CopyDst | WGPUBufferUsage_Vertex,
|
||||
fr->VertexBufferSize * sizeof(ImDrawVert),
|
||||
false
|
||||
};
|
||||
fr->VertexBuffer = wgpuDeviceCreateBuffer(g_wgpuDevice, &vb_desc);
|
||||
if (!fr->VertexBuffer)
|
||||
return;
|
||||
|
||||
fr->VertexBufferHost = new ImDrawVert[fr->VertexBufferSize];
|
||||
}
|
||||
if (fr->IndexBuffer == NULL || fr->IndexBufferSize < draw_data->TotalIdxCount)
|
||||
{
|
||||
if (fr->IndexBuffer)
|
||||
{
|
||||
wgpuBufferDestroy(fr->IndexBuffer);
|
||||
wgpuBufferRelease(fr->IndexBuffer);
|
||||
}
|
||||
SafeRelease(fr->IndexBufferHost);
|
||||
fr->IndexBufferSize = draw_data->TotalIdxCount + 10000;
|
||||
|
||||
WGPUBufferDescriptor ib_desc =
|
||||
{
|
||||
NULL,
|
||||
"Dear ImGui Index buffer",
|
||||
WGPUBufferUsage_CopyDst | WGPUBufferUsage_Index,
|
||||
fr->IndexBufferSize * sizeof(ImDrawIdx),
|
||||
false
|
||||
};
|
||||
fr->IndexBuffer = wgpuDeviceCreateBuffer(g_wgpuDevice, &ib_desc);
|
||||
if (!fr->IndexBuffer)
|
||||
return;
|
||||
|
||||
fr->IndexBufferHost = new ImDrawIdx[fr->IndexBufferSize];
|
||||
}
|
||||
|
||||
// Upload vertex/index data into a single contiguous GPU buffer
|
||||
ImDrawVert* vtx_dst = (ImDrawVert*)fr->VertexBufferHost;
|
||||
ImDrawIdx* idx_dst = (ImDrawIdx*)fr->IndexBufferHost;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* cmd_list = draw_data->CmdLists[n];
|
||||
memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
|
||||
memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
|
||||
vtx_dst += cmd_list->VtxBuffer.Size;
|
||||
idx_dst += cmd_list->IdxBuffer.Size;
|
||||
}
|
||||
int64_t vb_write_size = ((char*)vtx_dst - (char*)fr->VertexBufferHost + 3) & ~3;
|
||||
int64_t ib_write_size = ((char*)idx_dst - (char*)fr->IndexBufferHost + 3) & ~3;
|
||||
wgpuQueueWriteBuffer(g_defaultQueue, fr->VertexBuffer, 0, fr->VertexBufferHost, vb_write_size);
|
||||
wgpuQueueWriteBuffer(g_defaultQueue, fr->IndexBuffer, 0, fr->IndexBufferHost, ib_write_size);
|
||||
|
||||
// Setup desired render state
|
||||
ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
|
||||
|
||||
// Render command lists
|
||||
// (Because we merged all buffers into a single one, we maintain our own offset into them)
|
||||
int global_vtx_offset = 0;
|
||||
int global_idx_offset = 0;
|
||||
ImVec2 clip_scale = draw_data->FramebufferScale;
|
||||
ImVec2 clip_off = draw_data->DisplayPos;
|
||||
for (int n = 0; n < draw_data->CmdListsCount; n++)
|
||||
{
|
||||
const ImDrawList* cmd_list = draw_data->CmdLists[n];
|
||||
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
|
||||
{
|
||||
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
|
||||
if (pcmd->UserCallback != NULL)
|
||||
{
|
||||
// User callback, registered via ImDrawList::AddCallback()
|
||||
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
|
||||
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
|
||||
ImGui_ImplWGPU_SetupRenderState(draw_data, pass_encoder, fr);
|
||||
else
|
||||
pcmd->UserCallback(cmd_list, pcmd);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Bind custom texture
|
||||
ImTextureID tex_id = pcmd->GetTexID();
|
||||
ImGuiID tex_id_hash = ImHashData(&tex_id, sizeof(tex_id));
|
||||
auto bind_group = g_resources.ImageBindGroups.GetVoidPtr(tex_id_hash);
|
||||
if (bind_group)
|
||||
{
|
||||
wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, (WGPUBindGroup)bind_group, 0, NULL);
|
||||
}
|
||||
else
|
||||
{
|
||||
WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(g_resources.ImageBindGroupLayout, (WGPUTextureView)tex_id);
|
||||
g_resources.ImageBindGroups.SetVoidPtr(tex_id_hash, image_bind_group);
|
||||
wgpuRenderPassEncoderSetBindGroup(pass_encoder, 1, image_bind_group, 0, NULL);
|
||||
}
|
||||
|
||||
// Apply Scissor, Bind texture, Draw
|
||||
uint32_t clip_rect[4];
|
||||
clip_rect[0] = (uint32_t)(clip_scale.x * (pcmd->ClipRect.x - clip_off.x));
|
||||
clip_rect[1] = (uint32_t)(clip_scale.y * (pcmd->ClipRect.y - clip_off.y));
|
||||
clip_rect[2] = (uint32_t)(clip_scale.x * (pcmd->ClipRect.z - clip_off.x));
|
||||
clip_rect[3] = (uint32_t)(clip_scale.y * (pcmd->ClipRect.w - clip_off.y));
|
||||
wgpuRenderPassEncoderSetScissorRect(pass_encoder, clip_rect[0], clip_rect[1], clip_rect[2] - clip_rect[0], clip_rect[3] - clip_rect[1]);
|
||||
wgpuRenderPassEncoderDrawIndexed(pass_encoder, pcmd->ElemCount, 1, pcmd->IdxOffset + global_idx_offset, pcmd->VtxOffset + global_vtx_offset, 0);
|
||||
}
|
||||
}
|
||||
global_idx_offset += cmd_list->IdxBuffer.Size;
|
||||
global_vtx_offset += cmd_list->VtxBuffer.Size;
|
||||
}
|
||||
}
|
||||
|
||||
static void ImGui_ImplWGPU_CreateFontsTexture()
|
||||
{
|
||||
// Build texture atlas
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
unsigned char* pixels;
|
||||
int width, height, size_pp;
|
||||
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &size_pp);
|
||||
|
||||
// Upload texture to graphics system
|
||||
{
|
||||
WGPUTextureDescriptor tex_desc = {};
|
||||
tex_desc.label = "Dear ImGui Font Texture";
|
||||
tex_desc.dimension = WGPUTextureDimension_2D;
|
||||
tex_desc.size.width = width;
|
||||
tex_desc.size.height = height;
|
||||
tex_desc.size.depthOrArrayLayers = 1;
|
||||
tex_desc.sampleCount = 1;
|
||||
tex_desc.format = WGPUTextureFormat_RGBA8Unorm;
|
||||
tex_desc.mipLevelCount = 1;
|
||||
tex_desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_Sampled;
|
||||
g_resources.FontTexture = wgpuDeviceCreateTexture(g_wgpuDevice, &tex_desc);
|
||||
|
||||
WGPUTextureViewDescriptor tex_view_desc = {};
|
||||
tex_view_desc.format = WGPUTextureFormat_RGBA8Unorm;
|
||||
tex_view_desc.dimension = WGPUTextureViewDimension_2D;
|
||||
tex_view_desc.baseMipLevel = 0;
|
||||
tex_view_desc.mipLevelCount = 1;
|
||||
tex_view_desc.baseArrayLayer = 0;
|
||||
tex_view_desc.arrayLayerCount = 1;
|
||||
tex_view_desc.aspect = WGPUTextureAspect_All;
|
||||
g_resources.FontTextureView = wgpuTextureCreateView(g_resources.FontTexture, &tex_view_desc);
|
||||
}
|
||||
|
||||
// Upload texture data
|
||||
{
|
||||
WGPUImageCopyTexture dst_view = {};
|
||||
dst_view.texture = g_resources.FontTexture;
|
||||
dst_view.mipLevel = 0;
|
||||
dst_view.origin = { 0, 0, 0 };
|
||||
dst_view.aspect = WGPUTextureAspect_All;
|
||||
WGPUTextureDataLayout layout = {};
|
||||
layout.offset = 0;
|
||||
layout.bytesPerRow = width * size_pp;
|
||||
layout.rowsPerImage = height;
|
||||
WGPUExtent3D size = { (uint32_t)width, (uint32_t)height, 1 };
|
||||
wgpuQueueWriteTexture(g_defaultQueue, &dst_view, pixels, (uint32_t)(width * size_pp * height), &layout, &size);
|
||||
}
|
||||
|
||||
// Create the associated sampler
|
||||
{
|
||||
WGPUSamplerDescriptor sampler_desc = {};
|
||||
sampler_desc.minFilter = WGPUFilterMode_Linear;
|
||||
sampler_desc.magFilter = WGPUFilterMode_Linear;
|
||||
sampler_desc.mipmapFilter = WGPUFilterMode_Linear;
|
||||
sampler_desc.addressModeU = WGPUAddressMode_Repeat;
|
||||
sampler_desc.addressModeV = WGPUAddressMode_Repeat;
|
||||
sampler_desc.addressModeW = WGPUAddressMode_Repeat;
|
||||
sampler_desc.maxAnisotropy = 1;
|
||||
g_resources.Sampler = wgpuDeviceCreateSampler(g_wgpuDevice, &sampler_desc);
|
||||
}
|
||||
|
||||
// Store our identifier
|
||||
static_assert(sizeof(ImTextureID) >= sizeof(g_resources.FontTexture), "Can't pack descriptor handle into TexID, 32-bit not supported yet.");
|
||||
io.Fonts->SetTexID((ImTextureID)g_resources.FontTextureView);
|
||||
}
|
||||
|
||||
static void ImGui_ImplWGPU_CreateUniformBuffer()
|
||||
{
|
||||
WGPUBufferDescriptor ub_desc =
|
||||
{
|
||||
NULL,
|
||||
"Dear ImGui Uniform buffer",
|
||||
WGPUBufferUsage_CopyDst | WGPUBufferUsage_Uniform,
|
||||
sizeof(Uniforms),
|
||||
false
|
||||
};
|
||||
g_resources.Uniforms = wgpuDeviceCreateBuffer(g_wgpuDevice, &ub_desc);
|
||||
}
|
||||
|
||||
bool ImGui_ImplWGPU_CreateDeviceObjects()
|
||||
{
|
||||
if (!g_wgpuDevice)
|
||||
return false;
|
||||
if (g_pipelineState)
|
||||
ImGui_ImplWGPU_InvalidateDeviceObjects();
|
||||
|
||||
// Create render pipeline
|
||||
WGPURenderPipelineDescriptor2 graphics_pipeline_desc = {};
|
||||
graphics_pipeline_desc.primitive.topology = WGPUPrimitiveTopology_TriangleList;
|
||||
graphics_pipeline_desc.primitive.stripIndexFormat = WGPUIndexFormat_Undefined;
|
||||
graphics_pipeline_desc.primitive.frontFace = WGPUFrontFace_CW;
|
||||
graphics_pipeline_desc.primitive.cullMode = WGPUCullMode_None;
|
||||
graphics_pipeline_desc.multisample.count = 1;
|
||||
graphics_pipeline_desc.multisample.mask = UINT_MAX;
|
||||
graphics_pipeline_desc.multisample.alphaToCoverageEnabled = false;
|
||||
graphics_pipeline_desc.layout = nullptr; // Use automatic layout generation
|
||||
|
||||
// Create the vertex shader
|
||||
WGPUProgrammableStageDescriptor vertex_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__glsl_shader_vert_spv, sizeof(__glsl_shader_vert_spv) / sizeof(uint32_t));
|
||||
graphics_pipeline_desc.vertex.module = vertex_shader_desc.module;
|
||||
graphics_pipeline_desc.vertex.entryPoint = vertex_shader_desc.entryPoint;
|
||||
|
||||
// Vertex input configuration
|
||||
WGPUVertexAttribute attribute_desc[] =
|
||||
{
|
||||
{ WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, pos), 0 },
|
||||
{ WGPUVertexFormat_Float32x2, (uint64_t)IM_OFFSETOF(ImDrawVert, uv), 1 },
|
||||
{ WGPUVertexFormat_Unorm8x4, (uint64_t)IM_OFFSETOF(ImDrawVert, col), 2 },
|
||||
};
|
||||
|
||||
WGPUVertexBufferLayout buffer_layouts[1];
|
||||
buffer_layouts[0].arrayStride = sizeof(ImDrawVert);
|
||||
buffer_layouts[0].stepMode = WGPUInputStepMode_Vertex;
|
||||
buffer_layouts[0].attributeCount = 3;
|
||||
buffer_layouts[0].attributes = attribute_desc;
|
||||
|
||||
graphics_pipeline_desc.vertex.bufferCount = 1;
|
||||
graphics_pipeline_desc.vertex.buffers = buffer_layouts;
|
||||
|
||||
// Create the pixel shader
|
||||
WGPUProgrammableStageDescriptor pixel_shader_desc = ImGui_ImplWGPU_CreateShaderModule(__glsl_shader_frag_spv, sizeof(__glsl_shader_frag_spv) / sizeof(uint32_t));
|
||||
|
||||
// Create the blending setup
|
||||
WGPUBlendState blend_state = {};
|
||||
blend_state.alpha.operation = WGPUBlendOperation_Add;
|
||||
blend_state.alpha.srcFactor = WGPUBlendFactor_One;
|
||||
blend_state.alpha.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
|
||||
blend_state.color.operation = WGPUBlendOperation_Add;
|
||||
blend_state.color.srcFactor = WGPUBlendFactor_SrcAlpha;
|
||||
blend_state.color.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha;
|
||||
|
||||
WGPUColorTargetState color_state = {};
|
||||
color_state.format = g_renderTargetFormat;
|
||||
color_state.blend = &blend_state;
|
||||
color_state.writeMask = WGPUColorWriteMask_All;
|
||||
|
||||
WGPUFragmentState fragment_state = {};
|
||||
fragment_state.module = pixel_shader_desc.module;
|
||||
fragment_state.entryPoint = pixel_shader_desc.entryPoint;
|
||||
fragment_state.targetCount = 1;
|
||||
fragment_state.targets = &color_state;
|
||||
|
||||
graphics_pipeline_desc.fragment = &fragment_state;
|
||||
|
||||
// Create depth-stencil State
|
||||
WGPUDepthStencilState depth_stencil_state = {};
|
||||
depth_stencil_state.depthBias = 0;
|
||||
depth_stencil_state.depthBiasClamp = 0;
|
||||
depth_stencil_state.depthBiasSlopeScale = 0;
|
||||
|
||||
// Configure disabled depth-stencil state
|
||||
graphics_pipeline_desc.depthStencil = nullptr;
|
||||
|
||||
g_pipelineState = wgpuDeviceCreateRenderPipeline2(g_wgpuDevice, &graphics_pipeline_desc);
|
||||
|
||||
ImGui_ImplWGPU_CreateFontsTexture();
|
||||
ImGui_ImplWGPU_CreateUniformBuffer();
|
||||
|
||||
// Create resource bind group
|
||||
WGPUBindGroupLayout bg_layouts[2];
|
||||
bg_layouts[0] = wgpuRenderPipelineGetBindGroupLayout(g_pipelineState, 0);
|
||||
bg_layouts[1] = wgpuRenderPipelineGetBindGroupLayout(g_pipelineState, 1);
|
||||
|
||||
WGPUBindGroupEntry common_bg_entries[] =
|
||||
{
|
||||
{ 0, g_resources.Uniforms, 0, sizeof(Uniforms), 0, 0 },
|
||||
{ 1, 0, 0, 0, g_resources.Sampler, 0 },
|
||||
};
|
||||
|
||||
WGPUBindGroupDescriptor common_bg_descriptor = {};
|
||||
common_bg_descriptor.layout = bg_layouts[0];
|
||||
common_bg_descriptor.entryCount = sizeof(common_bg_entries) / sizeof(WGPUBindGroupEntry);
|
||||
common_bg_descriptor.entries = common_bg_entries;
|
||||
g_resources.CommonBindGroup = wgpuDeviceCreateBindGroup(g_wgpuDevice, &common_bg_descriptor);
|
||||
|
||||
WGPUBindGroup image_bind_group = ImGui_ImplWGPU_CreateImageBindGroup(bg_layouts[1], g_resources.FontTextureView);
|
||||
g_resources.ImageBindGroup = image_bind_group;
|
||||
g_resources.ImageBindGroupLayout = bg_layouts[1];
|
||||
g_resources.ImageBindGroups.SetVoidPtr(ImHashData(&g_resources.FontTextureView, sizeof(ImTextureID)), image_bind_group);
|
||||
|
||||
SafeRelease(vertex_shader_desc.module);
|
||||
SafeRelease(pixel_shader_desc.module);
|
||||
SafeRelease(bg_layouts[0]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplWGPU_InvalidateDeviceObjects()
|
||||
{
|
||||
if (!g_wgpuDevice)
|
||||
return;
|
||||
|
||||
SafeRelease(g_pipelineState);
|
||||
SafeRelease(g_resources);
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->SetTexID(NULL); // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well.
|
||||
|
||||
for (unsigned int i = 0; i < g_numFramesInFlight; i++)
|
||||
SafeRelease(g_pFrameResources[i]);
|
||||
}
|
||||
|
||||
bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextureFormat rt_format)
|
||||
{
|
||||
// Setup backend capabilities flags
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.BackendRendererName = "imgui_impl_webgpu";
|
||||
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
|
||||
|
||||
g_wgpuDevice = device;
|
||||
g_defaultQueue = wgpuDeviceGetQueue(g_wgpuDevice);
|
||||
g_renderTargetFormat = rt_format;
|
||||
g_pFrameResources = new FrameResources[num_frames_in_flight];
|
||||
g_numFramesInFlight = num_frames_in_flight;
|
||||
g_frameIndex = UINT_MAX;
|
||||
|
||||
g_resources.FontTexture = NULL;
|
||||
g_resources.FontTextureView = NULL;
|
||||
g_resources.Sampler = NULL;
|
||||
g_resources.Uniforms = NULL;
|
||||
g_resources.CommonBindGroup = NULL;
|
||||
g_resources.ImageBindGroups.Data.reserve(100);
|
||||
g_resources.ImageBindGroup = NULL;
|
||||
g_resources.ImageBindGroupLayout = NULL;
|
||||
|
||||
// Create buffers with a default size (they will later be grown as needed)
|
||||
for (int i = 0; i < num_frames_in_flight; i++)
|
||||
{
|
||||
FrameResources* fr = &g_pFrameResources[i];
|
||||
fr->IndexBuffer = NULL;
|
||||
fr->VertexBuffer = NULL;
|
||||
fr->IndexBufferHost = NULL;
|
||||
fr->VertexBufferHost = NULL;
|
||||
fr->IndexBufferSize = 10000;
|
||||
fr->VertexBufferSize = 5000;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ImGui_ImplWGPU_Shutdown()
|
||||
{
|
||||
ImGui_ImplWGPU_InvalidateDeviceObjects();
|
||||
delete[] g_pFrameResources;
|
||||
g_pFrameResources = NULL;
|
||||
wgpuQueueRelease(g_defaultQueue);
|
||||
g_wgpuDevice = NULL;
|
||||
g_numFramesInFlight = 0;
|
||||
g_frameIndex = UINT_MAX;
|
||||
}
|
||||
|
||||
void ImGui_ImplWGPU_NewFrame()
|
||||
{
|
||||
if (!g_pipelineState)
|
||||
ImGui_ImplWGPU_CreateDeviceObjects();
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
// dear imgui: Renderer for WebGPU
|
||||
// This needs to be used along with a Platform Binding (e.g. GLFW)
|
||||
// (Please note that WebGPU is currently experimental, will not run on non-beta browsers, and may break.)
|
||||
|
||||
// Implemented features:
|
||||
// [X] Renderer: User texture binding. Use 'WGPUTextureView' as ImTextureID. Read the FAQ about ImTextureID!
|
||||
// [X] Renderer: Support for large meshes (64k+ vertices) with 16-bit indices.
|
||||
|
||||
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
|
||||
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
#pragma once
|
||||
#include "imgui.h" // IMGUI_IMPL_API
|
||||
#include <webgpu/webgpu.h>
|
||||
|
||||
IMGUI_IMPL_API bool ImGui_ImplWGPU_Init(WGPUDevice device, int num_frames_in_flight, WGPUTextureFormat rt_format);
|
||||
IMGUI_IMPL_API void ImGui_ImplWGPU_Shutdown();
|
||||
IMGUI_IMPL_API void ImGui_ImplWGPU_NewFrame();
|
||||
IMGUI_IMPL_API void ImGui_ImplWGPU_RenderDrawData(ImDrawData* draw_data, WGPURenderPassEncoder pass_encoder);
|
||||
|
||||
// Use if you want to reset your rendering device without losing Dear ImGui state.
|
||||
IMGUI_IMPL_API void ImGui_ImplWGPU_InvalidateDeviceObjects();
|
||||
IMGUI_IMPL_API bool ImGui_ImplWGPU_CreateDeviceObjects();
|
@ -1,3 +1,6 @@
|
||||
#!/bin/bash
|
||||
## -V: create SPIR-V binary
|
||||
## -x: save binary output as text-based 32-bit hexadecimal numbers
|
||||
## -o: output file
|
||||
glslangValidator -V -x -o glsl_shader.frag.u32 glsl_shader.frag
|
||||
glslangValidator -V -x -o glsl_shader.vert.u32 glsl_shader.vert
|
@ -0,0 +1,141 @@
|
||||
_(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md or view this file with any Markdown viewer)_
|
||||
|
||||
## Dear ImGui: Backends
|
||||
|
||||
**The backends/ folder contains backends for popular platforms/graphics API, which you can use in
|
||||
your application or engine to easily integrate Dear ImGui.** Each backend is typically self-contained in a pair of files: imgui_impl_XXXX.cpp + imgui_impl_XXXX.h.
|
||||
|
||||
- The 'Platform' backends are in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, windowing.<BR>
|
||||
e.g. Windows ([imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp)), GLFW ([imgui_impl_glfw.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_glfw.cpp)), SDL2 ([imgui_impl_sdl.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdl.cpp)), etc.
|
||||
|
||||
- The 'Renderer' backends are in charge of: creating atlas texture, rendering imgui draw data.<BR>
|
||||
e.g. DirectX11 ([imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)), OpenGL/WebGL ([imgui_impl_opengl3.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_opengl3.cpp), Vulkan ([imgui_impl_vulkan.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_vulkan.cpp), etc.
|
||||
|
||||
- For some high-level frameworks, a single backend usually handle both 'Platform' and 'Renderer' parts.<BR>
|
||||
e.g. Allegro 5 ([imgui_impl_allegro5.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_allegro5.cpp)), Marmalade ([imgui_impl_marmalade.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_marmalade.cpp)). If you end up creating a custom backend for your engine, you may want to do the same.
|
||||
|
||||
An application usually combines 1 Platform backend + 1 Renderer backend + main Dear ImGui sources.
|
||||
For example, the [example_win32_directx11](https://github.com/ocornut/imgui/tree/master/examples/example_win32_directx11) application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp. There are 20+ examples in the [examples/](https://github.com/ocornut/imgui/blob/master/examples/) folder. See [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) for details.
|
||||
|
||||
**Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.**
|
||||
|
||||
|
||||
### What are backends
|
||||
|
||||
Dear ImGui is highly portable and only requires a few things to run and render, typically:
|
||||
|
||||
- Required: providing mouse/keyboard inputs (fed into the `ImGuiIO` structure).
|
||||
- Required: uploading the font atlas texture into graphics memory.
|
||||
- Required: rendering indexed textured triangles with a clipping rectangle.
|
||||
|
||||
Extra features are opt-in, our backends try to support as many as possible:
|
||||
|
||||
- Optional: custom texture binding support.
|
||||
- Optional: clipboard support.
|
||||
- Optional: gamepad support.
|
||||
- Optional: mouse cursor shape support.
|
||||
- Optional: IME support.
|
||||
- Optional: multi-viewports support.
|
||||
etc.
|
||||
|
||||
This is essentially what each backends are doing + obligatory portability cruft. Using default backends ensure you can get all those features including the ones that would be harder to implement on your side (e.g. multi-viewports support).
|
||||
|
||||
It is important to understand the difference between the core Dear ImGui library (files in the root folder)
|
||||
and backends which we are describing here (backends/ folder).
|
||||
|
||||
- Some issues may only be backend or platform specific.
|
||||
- You should be able to write backends for pretty much any platform and any 3D graphics API.
|
||||
e.g. you can get creative and use software rendering or render remotely on a different machine.
|
||||
|
||||
|
||||
### Integrating a backend
|
||||
|
||||
See "Getting Started" section of [EXAMPLES.MD](https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md) for more details.
|
||||
|
||||
|
||||
### List of backends
|
||||
|
||||
In the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder:
|
||||
|
||||
List of Platforms Backends:
|
||||
|
||||
imgui_impl_android.cpp ; Android native app API
|
||||
imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/
|
||||
imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl backends)
|
||||
imgui_impl_sdl.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org
|
||||
imgui_impl_win32.cpp ; Win32 native API (Windows)
|
||||
imgui_impl_glut.cpp ; GLUT/FreeGLUT (this is prehistoric software and absolutely not recommended today!)
|
||||
|
||||
List of Renderer Backends:
|
||||
|
||||
imgui_impl_dx9.cpp ; DirectX9
|
||||
imgui_impl_dx10.cpp ; DirectX10
|
||||
imgui_impl_dx11.cpp ; DirectX11
|
||||
imgui_impl_dx12.cpp ; DirectX12
|
||||
imgui_impl_metal.mm ; Metal (with ObjC)
|
||||
imgui_impl_opengl2.cpp ; OpenGL 2 (legacy, fixed pipeline <- don't use with modern OpenGL context)
|
||||
imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline)
|
||||
imgui_impl_vulkan.cpp ; Vulkan
|
||||
imgui_impl_wgpu.cpp ; WebGPU
|
||||
|
||||
List of high-level Frameworks Backends (combining Platform + Renderer):
|
||||
|
||||
imgui_impl_allegro5.cpp
|
||||
imgui_impl_marmalade.cpp
|
||||
|
||||
Emscripten is also supported.
|
||||
The [example_emscripten_opengl3](https://github.com/ocornut/imgui/tree/master/examples/example_emscripten_opengl3) app uses imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp, but other combos are possible.
|
||||
|
||||
### Backends for third-party frameworks, graphics API or other languages
|
||||
|
||||
See https://github.com/ocornut/imgui/wiki/Bindings for the full list.
|
||||
|
||||
### Recommended Backends
|
||||
|
||||
If you are not sure which backend to use, the recommended platform/frameworks for portable applications:
|
||||
|
||||
|Library |Website |Backend |Note |
|
||||
|--------|--------|--------|-----|
|
||||
| GLFW | https://github.com/glfw/glfw | imgui_impl_glfw.cpp | |
|
||||
| SDL2 | https://www.libsdl.org | imgui_impl_sdl.cpp | |
|
||||
| Sokol | https://github.com/floooh/sokol | [util/sokol_imgui.h](https://github.com/floooh/sokol/blob/master/util/sokol_imgui.h) | Lower-level than GLFW/SDL |
|
||||
|
||||
|
||||
### Using a custom engine?
|
||||
|
||||
You will likely be tempted to start by rewrite your own backend using your own custom/high-level facilities...<BR>
|
||||
Think twice!
|
||||
|
||||
If you are new to Dear ImGui, first try using the existing backends as-is.
|
||||
You will save lots of time integrating the library.
|
||||
You can LATER decide to rewrite yourself a custom backend if you really need to.
|
||||
In most situations, custom backends have less features and more bugs than the standard backends we provide.
|
||||
If you want portability, you can use multiple backends and choose between them either at compile time
|
||||
or at runtime.
|
||||
|
||||
**Example A**: your engine is built over Windows + DirectX11 but you have your own high-level rendering
|
||||
system layered over DirectX11.<BR>
|
||||
Suggestion: try using imgui_impl_win32.cpp + imgui_impl_dx11.cpp first.
|
||||
Once it works, if you really need it you can replace the imgui_impl_dx11.cpp code with a
|
||||
custom renderer using your own rendering functions, and keep using the standard Win32 code etc.
|
||||
|
||||
**Example B**: your engine runs on Windows, Mac, Linux and uses DirectX11, Metal, Vulkan respectively.<BR>
|
||||
Suggestion: use multiple generic backends!
|
||||
Once it works, if you really need it you can replace parts of backends with your own abstractions.
|
||||
|
||||
**Example C**: your engine runs on platforms we can't provide public backends for (e.g. PS4/PS5, Switch),
|
||||
and you have high-level systems everywhere.<BR>
|
||||
Suggestion: try using a non-portable backend first (e.g. win32 + underlying graphics API) to get
|
||||
your desktop builds working first. This will get you running faster and get your acquainted with
|
||||
how Dear ImGui works and is setup. You can then rewrite a custom backend using your own engine API.
|
||||
|
||||
Also:
|
||||
The [multi-viewports feature](https://github.com/ocornut/imgui/issues/1542) of the 'docking' branch allows
|
||||
Dear ImGui windows to be seamlessly detached from the main application window. This is achieved using an
|
||||
extra layer to the Platform and Renderer backends, which allows Dear ImGui to communicate platform-specific
|
||||
requests such as: "create an additional OS window", "create a render context", "get the OS position of this
|
||||
window" etc. See 'ImGuiPlatformIO' for details.
|
||||
Supporting the multi-viewports feature correctly using 100% of your own abstractions is more difficult
|
||||
than supporting single-viewport.
|
||||
If you decide to use unmodified imgui_impl_XXXX.cpp files, you can automatically benefit from
|
||||
improvements and fixes related to viewports and platform windows without extra work on your side.
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,240 @@
|
||||
_(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/EXAMPLES.md or view this file with any Markdown viewer)_
|
||||
|
||||
## Dear ImGui: Examples
|
||||
|
||||
**The [examples/](https://github.com/ocornut/imgui/blob/master/examples) folder example applications (standalone, ready-to-build) for variety of
|
||||
platforms and graphics APIs.** They all use standard backends from the [backends/](https://github.com/ocornut/imgui/blob/master/backends) folder (see [BACKENDS.md](https://github.com/ocornut/imgui/blob/master/docs/BACKENDS.md)).
|
||||
|
||||
The purpose of Examples is to showcase integration with backends, let you try Dear ImGui, and guide you toward
|
||||
integrating Dear ImGui in your own application/game/engine.
|
||||
**Once Dear ImGui is setup and running, run and refer to `ImGui::ShowDemoWindow()` in imgui_demo.cpp for usage of the end-user API.**
|
||||
|
||||
You can find Windows binaries for some of those example applications at:
|
||||
http://www.dearimgui.org/binaries
|
||||
|
||||
|
||||
### Getting Started
|
||||
|
||||
Integration in a typical existing application, should take <20 lines when using standard backends.
|
||||
|
||||
At initialization:
|
||||
call ImGui::CreateContext()
|
||||
call ImGui_ImplXXXX_Init() for each backend.
|
||||
|
||||
At the beginning of your frame:
|
||||
call ImGui_ImplXXXX_NewFrame() for each backend.
|
||||
call ImGui::NewFrame()
|
||||
|
||||
At the end of your frame:
|
||||
call ImGui::Render()
|
||||
call ImGui_ImplXXXX_RenderDrawData() for your Renderer backend.
|
||||
|
||||
At shutdown:
|
||||
call ImGui_ImplXXXX_Shutdown() for each backend.
|
||||
call ImGui::DestroyContext()
|
||||
|
||||
Example (using [backends/imgui_impl_win32.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_win32.cpp) + [backends/imgui_impl_dx11.cpp](https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_dx11.cpp)):
|
||||
|
||||
// Create a Dear ImGui context, setup some options
|
||||
ImGui::CreateContext();
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable some options
|
||||
|
||||
// Initialize Platform + Renderer backends (here: using imgui_impl_win32.cpp + imgui_impl_dx11.cpp)
|
||||
ImGui_ImplWin32_Init(my_hwnd);
|
||||
ImGui_ImplDX11_Init(my_d3d_device, my_d3d_device_context);
|
||||
|
||||
// Application main loop
|
||||
while (true)
|
||||
{
|
||||
// Beginning of frame: update Renderer + Platform backend, start Dear ImGui frame
|
||||
ImGui_ImplDX11_NewFrame();
|
||||
ImGui_ImplWin32_NewFrame();
|
||||
ImGui::NewFrame();
|
||||
|
||||
// Any application code here
|
||||
ImGui::Text("Hello, world!");
|
||||
|
||||
// End of frame: render Dear ImGui
|
||||
ImGui::Render();
|
||||
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
|
||||
|
||||
// Swap
|
||||
g_pSwapChain->Present(1, 0);
|
||||
}
|
||||
|
||||
// Shutdown
|
||||
ImGui_ImplDX11_Shutdown();
|
||||
ImGui_ImplWin32_Shutdown();
|
||||
ImGui::DestroyContext();
|
||||
|
||||
Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.
|
||||
Please read the comments and instruction at the top of each file.
|
||||
Please read FAQ at http://www.dearimgui.org/faq
|
||||
|
||||
If you are using of the backend provided here, you can add the backends/imgui_impl_xxxx(.cpp,.h)
|
||||
files to your project and use as-in. Each imgui_impl_xxxx.cpp file comes with its own individual
|
||||
Changelog, so if you want to update them later it will be easier to catch up with what changed.
|
||||
|
||||
|
||||
### Examples Applications
|
||||
|
||||
[example_allegro5/](https://github.com/ocornut/imgui/blob/master/examples/example_allegro5/) <BR>
|
||||
Allegro 5 example. <BR>
|
||||
= main.cpp + imgui_impl_allegro5.cpp
|
||||
|
||||
[example_android_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_android_opengl3/) <BR>
|
||||
Android + OpenGL3 (ES) example. <BR>
|
||||
= main.cpp + imgui_impl_android.cpp + imgui_impl_opengl3.cpp
|
||||
|
||||
[example_apple_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_metal/) <BR>
|
||||
OSX & iOS + Metal example. <BR>
|
||||
= main.m + imgui_impl_osx.mm + imgui_impl_metal.mm <BR>
|
||||
It is based on the "cross-platform" game template provided with Xcode as of Xcode 9.
|
||||
(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends.
|
||||
You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.)
|
||||
|
||||
[example_apple_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_apple_opengl2/) <BR>
|
||||
OSX + OpenGL2 example. <BR>
|
||||
= main.mm + imgui_impl_osx.mm + imgui_impl_opengl2.cpp <BR>
|
||||
(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms backends.
|
||||
You may prefer to use the GLFW Or SDL backends, which will also support Windows and Linux.)
|
||||
|
||||
[example_emscripten_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_emscripten_opengl3/) <BR>
|
||||
Emcripten + SDL2 + OpenGL3+/ES2/ES3 example. <BR>
|
||||
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp <BR>
|
||||
Note that other examples based on SDL or GLFW + OpenGL could easily be modified to work with Emscripten.
|
||||
We provide this to make the Emscripten differences obvious, and have them not pollute all other examples.
|
||||
|
||||
[example_emscripten_wgpu/](https://github.com/ocornut/imgui/blob/master/examples/example_emscripten_wgpu/) <BR>
|
||||
Emcripten + GLFW + WebGPU example. <BR>
|
||||
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_wgpu.cpp
|
||||
|
||||
[example_glfw_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_metal/) <BR>
|
||||
GLFW (Mac) + Metal example. <BR>
|
||||
= main.mm + imgui_impl_glfw.cpp + imgui_impl_metal.mm
|
||||
|
||||
[example_glfw_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl2/) <BR>
|
||||
GLFW + OpenGL2 example (legacy, fixed pipeline). <BR>
|
||||
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp <BR>
|
||||
**DO NOT USE THIS IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** <BR>
|
||||
This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter.
|
||||
If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to
|
||||
make things more complicated, will require your code to reset many OpenGL attributes to their initial
|
||||
state, and might confuse your GPU driver. One star, not recommended.
|
||||
|
||||
[example_glfw_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_opengl3/) <BR>
|
||||
GLFW (Win32, Mac, Linux) + OpenGL3+/ES2/ES3 example (modern, programmable pipeline). <BR>
|
||||
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp <BR>
|
||||
This uses more modern OpenGL calls and custom shaders. <BR>
|
||||
This may actually also work with OpenGL 2.x contexts! <BR>
|
||||
Prefer using that if you are using modern OpenGL in your application (anything with shaders).
|
||||
|
||||
[example_glfw_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_glfw_vulkan/) <BR>
|
||||
GLFW (Win32, Mac, Linux) + Vulkan example. <BR>
|
||||
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_vulkan.cpp <BR>
|
||||
This is quite long and tedious, because: Vulkan.
|
||||
For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp.
|
||||
|
||||
[example_glut_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_glut_opengl2/) <BR>
|
||||
GLUT (e.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2 example. <BR>
|
||||
= main.cpp + imgui_impl_glut.cpp + imgui_impl_opengl2.cpp <BR>
|
||||
Note that GLUT/FreeGLUT is largely obsolete software, prefer using GLFW or SDL.
|
||||
|
||||
[example_marmalade/](https://github.com/ocornut/imgui/blob/master/examples/example_marmalade/) <BR>
|
||||
Marmalade example using IwGx. <BR>
|
||||
= main.cpp + imgui_impl_marmalade.cpp
|
||||
|
||||
[example_null/](https://github.com/ocornut/imgui/blob/master/examples/example_null/) <BR>
|
||||
Null example, compile and link imgui, create context, run headless with no inputs and no graphics output. <BR>
|
||||
= main.cpp <BR>
|
||||
This is used to quickly test compilation of core imgui files in as many setups as possible.
|
||||
Because this application doesn't create a window nor a graphic context, there's no graphics output.
|
||||
|
||||
[example_sdl_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_directx11/) <BR>
|
||||
SDL2 + DirectX11 example, Windows only. <BR>
|
||||
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_dx11.cpp <BR>
|
||||
This to demonstrate usage of DirectX with SDL.
|
||||
|
||||
[example_sdl_metal/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_metal/) <BR>
|
||||
SDL2 (Mac) + Metal example. <BR>
|
||||
= main.mm + imgui_impl_sdl.cpp + imgui_impl_metal.mm
|
||||
|
||||
[example_sdl_opengl2/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_opengl2/) <BR>
|
||||
SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline). <BR>
|
||||
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl2.cpp <BR>
|
||||
**DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)** <BR>
|
||||
This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter.
|
||||
If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to
|
||||
make things more complicated, will require your code to reset many OpenGL attributes to their initial
|
||||
state, and might confuse your GPU driver. One star, not recommended.
|
||||
|
||||
[example_sdl_opengl3/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_opengl3/) <BR>
|
||||
SDL2 (Win32, Mac, Linux, etc.) + OpenGL3+/ES2/ES3 example. <BR>
|
||||
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp <BR>
|
||||
This uses more modern OpenGL calls and custom shaders. <BR>
|
||||
This may actually also work with OpenGL 2.x contexts! <BR>
|
||||
|
||||
[example_sdl_vulkan/](https://github.com/ocornut/imgui/blob/master/examples/example_sdl_vulkan/) <BR>
|
||||
SDL2 (Win32, Mac, Linux, etc.) + Vulkan example. <BR>
|
||||
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_vulkan.cpp <BR>
|
||||
This is quite long and tedious, because: Vulkan. <BR>
|
||||
For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp.
|
||||
|
||||
[example_win32_directx9/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx9/) <BR>
|
||||
DirectX9 example, Windows only. <BR>
|
||||
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx9.cpp
|
||||
|
||||
[example_win32_directx10/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx10/) <BR>
|
||||
DirectX10 example, Windows only. <BR>
|
||||
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx10.cpp
|
||||
|
||||
[example_win32_directx11/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx11/) <BR>
|
||||
DirectX11 example, Windows only. <BR>
|
||||
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx11.cpp
|
||||
|
||||
[example_win32_directx12/](https://github.com/ocornut/imgui/blob/master/examples/example_win32_directx12/) <BR>
|
||||
DirectX12 example, Windows only. <BR>
|
||||
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx12.cpp <BR>
|
||||
This is quite long and tedious, because: DirectX12.
|
||||
|
||||
|
||||
### Miscallaneous
|
||||
|
||||
**Building**
|
||||
|
||||
Unfortunately nowadays it is still tedious to create and maintain portable build files using external
|
||||
libraries (the kind we're using here to create a window and render 3D triangles) without relying on
|
||||
third party software and build systems. For most examples here we choose to provide:
|
||||
- Makefiles for Linux/OSX
|
||||
- Batch files for Visual Studio 2008+
|
||||
- A .sln project file for Visual Studio 2012+
|
||||
- Xcode project files for the Apple examples
|
||||
Please let us know if they don't work with your setup!
|
||||
You can probably just import the imgui_impl_xxx.cpp/.h files into your own codebase or compile those
|
||||
directly with a command-line compiler.
|
||||
|
||||
If you are interested in using Cmake to build and links examples, see:
|
||||
https://github.com/ocornut/imgui/pull/1713 and https://github.com/ocornut/imgui/pull/3027
|
||||
|
||||
**About mouse cursor latency**
|
||||
|
||||
Dear ImGui has no particular extra lag for most behaviors,
|
||||
e.g. the value of 'io.MousePos' provided at the time of NewFrame() will result in windows being moved
|
||||
to the right spot at the time of EndFrame()/Render(). At 60 FPS your experience should be pleasant.
|
||||
|
||||
However, consider that OS mouse cursors are typically drawn through a very specific hardware accelerated
|
||||
path and will feel smoother than the majority of contents rendered via regular graphics API (including,
|
||||
but not limited to Dear ImGui windows). Because UI rendering and interaction happens on the same plane
|
||||
as the mouse, that disconnect may be jarring to particularly sensitive users.
|
||||
You may experiment with enabling the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor
|
||||
using the regular graphics API, to help you visualize the difference between a "hardware" cursor and a
|
||||
regularly rendered software cursor.
|
||||
However, rendering a mouse cursor at 60 FPS will feel sluggish so you likely won't want to enable that at
|
||||
all times. It might be beneficial for the user experience to switch to a software rendered cursor _only_
|
||||
when an interactive drag is in progress.
|
||||
|
||||
Note that some setup or GPU drivers are likely to be causing extra display lag depending on their settings.
|
||||
If you feel that dragging windows feels laggy and you are not sure what the cause is: try to build a simple
|
||||
drawing a flat 2D shape directly under the mouse cursor!
|
||||
|
@ -0,0 +1,397 @@
|
||||
_(You may browse this at https://github.com/ocornut/imgui/blob/master/docs/FONTS.md or view this file with any Markdown viewer)_
|
||||
|
||||
## Dear ImGui: Using Fonts
|
||||
|
||||
The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer),
|
||||
a 13 pixels high, pixel-perfect font used by default. We embed it in the source code so you can use Dear ImGui without any file system access. ProggyClean does not scale smoothly, therefore it is recommended that you load your own file when using Dear ImGui in an application aiming to look nice and wanting to support multiple resolutions.
|
||||
|
||||
You may also load external .TTF/.OTF files.
|
||||
In the [misc/fonts/](https://github.com/ocornut/imgui/tree/master/misc/fonts) folder you can find a few suggested fonts, provided as a convenience.
|
||||
|
||||
**Also read the FAQ:** https://www.dearimgui.org/faq (there is a Fonts section!)
|
||||
|
||||
## Index
|
||||
- [Readme First](#readme-first)
|
||||
- [How should I handle DPI in my application?](#how-should-i-handle-dpi-in-my-application)
|
||||
- [Fonts Loading Instructions](#font-loading-instructions)
|
||||
- [Using Icon Fonts](#using-icon-fonts)
|
||||
- [Using FreeType Rasterizer (imgui_freetype)](#using-freetype-rasterizer-imgui_freetype)
|
||||
- [Using Colorful Glyphs/Emojis](#using-colorful-glyphsemojis)
|
||||
- [Using Custom Glyph Ranges](#using-custom-glyph-ranges)
|
||||
- [Using Custom Colorful Icons](#using-custom-colorful-icons)
|
||||
- [Using Font Data Embedded In Source Code](#using-font-data-embedded-in-source-code)
|
||||
- [About filenames](#about-filenames)
|
||||
- [Credits/Licenses For Fonts Included In Repository](#creditslicenses-for-fonts-included-in-repository)
|
||||
- [Font Links](#font-links)
|
||||
|
||||
---------------------------------------
|
||||
## Readme First
|
||||
|
||||
- All loaded fonts glyphs are rendered into a single texture atlas ahead of time. Calling either of `io.Fonts->GetTexDataAsAlpha8()`, `io.Fonts->GetTexDataAsRGBA32()` or `io.Fonts->Build()` will build the atlas.
|
||||
|
||||
- You can use the style editor `ImGui::ShowStyleEditor()` in the "Fonts" section to browse your fonts and understand what's going on if you have an issue. You can also reach it in `Demo->Tools->Style Editor->Fonts`:
|
||||
|
||||
![imgui_capture_0008](https://user-images.githubusercontent.com/8225057/84162822-1a731f00-aa71-11ea-9b6b-89c2332aa161.png)
|
||||
|
||||
- Make sure your font ranges data are persistent (available during the calls to `GetTexDataAsAlpha8()`/`GetTexDataAsRGBA32()/`Build()`.
|
||||
|
||||
- Use C++11 u8"my text" syntax to encode literal strings as UTF-8. e.g.:
|
||||
```cpp
|
||||
u8"hello"
|
||||
u8"こんにちは" // this will be encoded as UTF-8
|
||||
```
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
## How should I handle DPI in my application?
|
||||
|
||||
See [FAQ entry](https://github.com/ocornut/imgui/blob/master/docs/FAQ.md#q-how-should-i-handle-dpi-in-my-application).
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
|
||||
## Font Loading Instructions
|
||||
|
||||
**Load default font:**
|
||||
```cpp
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->AddFontDefault();
|
||||
```
|
||||
|
||||
|
||||
**Load .TTF/.OTF file with:**
|
||||
```cpp
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
|
||||
```
|
||||
If you get an assert stating "Could not load font file!", your font filename is likely incorrect. Read "[About filenames](#about-filenames)" carefully.
|
||||
|
||||
|
||||
**Load multiple fonts:**
|
||||
```cpp
|
||||
// Init
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
|
||||
ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels);
|
||||
```
|
||||
```cpp
|
||||
// In application loop: select font at runtime
|
||||
ImGui::Text("Hello"); // use the default font (which is the first loaded font)
|
||||
ImGui::PushFont(font2);
|
||||
ImGui::Text("Hello with another font");
|
||||
ImGui::PopFont();
|
||||
```
|
||||
|
||||
|
||||
**For advanced options create a ImFontConfig structure and pass it to the AddFont() function (it will be copied internally):**
|
||||
```cpp
|
||||
ImFontConfig config;
|
||||
config.OversampleH = 2;
|
||||
config.OversampleV = 1;
|
||||
config.GlyphExtraSpacing.x = 1.0f;
|
||||
ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config);
|
||||
```
|
||||
|
||||
|
||||
**Combine multiple fonts into one:**
|
||||
```cpp
|
||||
// Load a first font
|
||||
ImFont* font = io.Fonts->AddFontDefault();
|
||||
|
||||
// Add character ranges and merge into the previous font
|
||||
// The ranges array is not copied by the AddFont* functions and is used lazily
|
||||
// so ensure it is available at the time of building or calling GetTexDataAsRGBA32().
|
||||
static const ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 }; // Will not be copied by AddFont* so keep in scope.
|
||||
ImFontConfig config;
|
||||
config.MergeMode = true;
|
||||
io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge into first font
|
||||
io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges); // Merge into first font
|
||||
io.Fonts->Build();
|
||||
```
|
||||
|
||||
**Add a fourth parameter to bake specific font ranges only:**
|
||||
|
||||
```cpp
|
||||
// Basic Latin, Extended Latin
|
||||
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault());
|
||||
|
||||
// Default + Selection of 2500 Ideographs used by Simplified Chinese
|
||||
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
|
||||
|
||||
// Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
|
||||
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
|
||||
```
|
||||
See [Using Custom Glyph Ranges](#using-custom-glyph-ranges) section to create your own ranges.
|
||||
|
||||
|
||||
**Example loading and using a Japanese font:**
|
||||
|
||||
```cpp
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->AddFontFromFileTTF("NotoSansCJKjp-Medium.otf", 20.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
|
||||
```
|
||||
```cpp
|
||||
ImGui::Text(u8"こんにちは!テスト %d", 123);
|
||||
if (ImGui::Button(u8"ロード"))
|
||||
{
|
||||
// do stuff
|
||||
}
|
||||
ImGui::InputText("string", buf, IM_ARRAYSIZE(buf));
|
||||
ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
|
||||
```
|
||||
|
||||
![sample code output](https://raw.githubusercontent.com/wiki/ocornut/imgui/web/v160/code_sample_02_jp.png)
|
||||
<br>_(settings: Dark style (left), Light style (right) / Font: NotoSansCJKjp-Medium, 20px / Rounding: 5)_
|
||||
|
||||
**Font Atlas too large?**
|
||||
|
||||
- If you have very large number of glyphs or multiple fonts, the texture may become too big for your graphics API. The typical result of failing to upload a texture is if every glyphs appears as white rectangles.
|
||||
- Mind the fact that some graphics drivers have texture size limitation. If you are building a PC application, mind the fact that your users may use hardware with lower limitations than yours.
|
||||
|
||||
Some solutions:
|
||||
|
||||
1. Reduce glyphs ranges by calculating them from source localization data.
|
||||
You can use the `ImFontGlyphRangesBuilder` for this purpose and rebuilding your atlas between frames when new characters are needed. This will be the biggest win!
|
||||
2. You may reduce oversampling, e.g. `font_config.OversampleH = 2`, this will largely reduce your texture size.
|
||||
Note that while OversampleH = 2 looks visibly very close to 3 in most situations, with OversampleH = 1 the quality drop will be noticeable.
|
||||
3. Set `io.Fonts.TexDesiredWidth` to specify a texture width to minimize texture height (see comment in `ImFontAtlas::Build()` function).
|
||||
4. Set `io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight;` to disable rounding the texture height to the next power of two.
|
||||
5. Read about oversampling [here](https://github.com/nothings/stb/blob/master/tests/oversample).
|
||||
6. To support the extended range of unicode beyond 0xFFFF (e.g. emoticons, dingbats, symbols, shapes, ancient languages, etc...) add `#define IMGUI_USE_WCHAR32`in your `imconfig.h`.
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
## Using Icon Fonts
|
||||
|
||||
Using an icon font (such as [FontAwesome](http://fontawesome.io) or [OpenFontIcons](https://github.com/traverseda/OpenFontIcons)) is an easy and practical way to use icons in your Dear ImGui application.
|
||||
A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without having to change fonts back and forth.
|
||||
|
||||
To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut: https://github.com/juliettef/IconFontCppHeaders.
|
||||
|
||||
So you can use `ICON_FA_SEARCH` as a string that will render as a "Search" icon.
|
||||
|
||||
Example Setup:
|
||||
```cpp
|
||||
// Merge icons into default tool font
|
||||
#include "IconsFontAwesome.h"
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->AddFontDefault();
|
||||
|
||||
ImFontConfig config;
|
||||
config.MergeMode = true;
|
||||
config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced
|
||||
static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
|
||||
io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges);
|
||||
```
|
||||
Example Usage:
|
||||
```cpp
|
||||
// Usage, e.g.
|
||||
ImGui::Text("%s among %d items", ICON_FA_SEARCH, count);
|
||||
ImGui::Button(ICON_FA_SEARCH " Search");
|
||||
// C string _literals_ can be concatenated at compilation time, e.g. "hello" " world"
|
||||
// ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB"
|
||||
```
|
||||
See Links below for other icons fonts and related tools.
|
||||
|
||||
Here's an application using icons ("Avoyd", https://www.avoyd.com):
|
||||
![avoyd](https://user-images.githubusercontent.com/8225057/81696852-c15d9e80-9464-11ea-9cab-2a4d4fc84396.jpg)
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
## Using FreeType Rasterizer (imgui_freetype)
|
||||
|
||||
- Dear ImGui uses imstb\_truetype.h to rasterize fonts (with optional oversampling). This technique and its implementation are not ideal for fonts rendered at small sizes, which may appear a little blurry or hard to read.
|
||||
- There is an implementation of the ImFontAtlas builder using FreeType that you can use in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder.
|
||||
- FreeType supports auto-hinting which tends to improve the readability of small fonts.
|
||||
- Read documentation in the [misc/freetype/](https://github.com/ocornut/imgui/tree/master/misc/freetype) folder.
|
||||
- Correct sRGB space blending will have an important effect on your font rendering quality.
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
## Using Colorful Glyphs/Emojis
|
||||
|
||||
- Rendering of colored emojis is only supported by imgui_freetype with FreeType 2.10+.
|
||||
- You will need to load fonts with the `ImGuiFreeTypeBuilderFlags_LoadColor` flag.
|
||||
- Emojis are frequently encoded in upper Unicode layers (character codes >0x10000) and will need dear imgui compiled with `IMGUI_USE_WCHAR32`.
|
||||
- Not all types of color fonts are supported by FreeType at the moment.
|
||||
- Stateful Unicode features such as skin tone modifiers are not supported by the text renderer.
|
||||
|
||||
![colored glyphs](https://user-images.githubusercontent.com/8225057/106171241-9dc4ba80-6191-11eb-8a69-ca1467b206d1.png)
|
||||
|
||||
```cpp
|
||||
io.Fonts->AddFontFromFileTTF("../../../imgui_dev/data/fonts/NotoSans-Regular.ttf", 16.0f);
|
||||
static ImWchar ranges[] = { 0x1, 0x1FFFF, 0 };
|
||||
static ImFontConfig cfg;
|
||||
cfg.OversampleH = cfg.OversampleV = 1;
|
||||
cfg.MergeMode = true;
|
||||
cfg.FontBuilderFlags |= ImGuiFreeTypeBuilderFlags_LoadColor;
|
||||
io.Fonts->AddFontFromFileTTF("C:\\Windows\\Fonts\\seguiemj.ttf", 16.0f, &cfg, ranges);
|
||||
```
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
## Using Custom Glyph Ranges
|
||||
|
||||
You can use the `ImFontGlyphRangesBuilder` helper to create glyph ranges based on text input. For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs.
|
||||
```cpp
|
||||
ImVector<ImWchar> ranges;
|
||||
ImFontGlyphRangesBuilder builder;
|
||||
builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
|
||||
builder.AddChar(0x7262); // Add a specific character
|
||||
builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
|
||||
builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
|
||||
|
||||
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
|
||||
io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted.
|
||||
```
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
## Using Custom Colorful Icons
|
||||
|
||||
As an alternative to rendering colorful glyphs using imgui_freetype with `ImGuiFreeTypeBuilderFlags_LoadColor`, you may allocate your own space in the texture atlas and write yourself into it. **(This is a BETA api, use if you are familiar with dear imgui and with your rendering backend)**
|
||||
|
||||
- You can use the `ImFontAtlas::AddCustomRect()` and `ImFontAtlas::AddCustomRectFontGlyph()` api to register rectangles that will be packed into the font atlas texture. Register them before building the atlas, then call Build()`.
|
||||
- You can then use `ImFontAtlas::GetCustomRectByIndex(int)` to query the position/size of your rectangle within the texture, and blit/copy any graphics data of your choice into those rectangles.
|
||||
- This API is beta because it is likely to change in order to support multi-dpi (multiple viewports on multiple monitors with varying DPI scale).
|
||||
|
||||
#### Pseudo-code:
|
||||
```cpp
|
||||
// Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font
|
||||
ImFont* font = io.Fonts->AddFontDefault();
|
||||
int rect_ids[2];
|
||||
rect_ids[0] = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1);
|
||||
rect_ids[1] = io.Fonts->AddCustomRectFontGlyph(font, 'b', 13, 13, 13+1);
|
||||
|
||||
// Build atlas
|
||||
io.Fonts->Build();
|
||||
|
||||
// Retrieve texture in RGBA format
|
||||
unsigned char* tex_pixels = NULL;
|
||||
int tex_width, tex_height;
|
||||
io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height);
|
||||
|
||||
for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++)
|
||||
{
|
||||
int rect_id = rects_ids[rect_n];
|
||||
if (const ImFontAtlas::CustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id))
|
||||
{
|
||||
// Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!)
|
||||
for (int y = 0; y < rect->Height; y++)
|
||||
{
|
||||
ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X);
|
||||
for (int x = rect->Width; x > 0; x--)
|
||||
*p++ = IM_COL32(255, 0, 0, 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
## Using Font Data Embedded In Source Code
|
||||
|
||||
- Compile and use [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) to create a compressed C style array that you can embed in source code.
|
||||
- See the documentation in [binary_to_compressed_c.cpp](https://github.com/ocornut/imgui/blob/master/misc/fonts/binary_to_compressed_c.cpp) for instruction on how to use the tool.
|
||||
- You may find a precompiled version binary_to_compressed_c.exe for Windows instead of demo binaries package (see [README](https://github.com/ocornut/imgui/blob/master/docs/README.md)).
|
||||
- The tool can optionally output Base85 encoding to reduce the size of _source code_ but the read-only arrays in the actual binary will be about 20% bigger.
|
||||
|
||||
Then load the font with:
|
||||
```cpp
|
||||
ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...);
|
||||
```
|
||||
or
|
||||
```cpp
|
||||
ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...);
|
||||
```
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
## About filenames
|
||||
|
||||
**Please note that many new C/C++ users have issues their files _because the filename they provide is wrong_.**
|
||||
|
||||
Two things to watch for:
|
||||
- Make sure your IDE/debugger settings starts your executable from the right working directory. In Visual Studio you can change your working directory in project `Properties > General > Debugging > Working Directory`. People assume that their execution will start from the root folder of the project, where by default it oftens start from the folder where object or executable files are stored.
|
||||
```cpp
|
||||
// Relative filename depends on your Working Directory when running your program!
|
||||
io.Fonts->AddFontFromFileTTF("MyImage01.jpg", ...);
|
||||
|
||||
// Load from the parent folder of your Working Directory
|
||||
io.Fonts->AddFontFromFileTTF("../MyImage01.jpg", ...);
|
||||
```
|
||||
- In C/C++ and most programming languages if you want to use a backslash `\` within a string literal, you need to write it double backslash `\\`. At it happens, Windows uses backslashes as a path separator, so be mindful.
|
||||
```cpp
|
||||
io.Fonts->AddFontFromFileTTF("MyFiles\MyImage01.jpg", ...); // This is INCORRECT!!
|
||||
io.Fonts->AddFontFromFileTTF("MyFiles\\MyImage01.jpg", ...); // This is CORRECT
|
||||
```
|
||||
In some situations, you may also use `/` path separator under Windows.
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
## Credits/Licenses For Fonts Included In Repository
|
||||
|
||||
Some fonts files are available in the `misc/fonts/` folder:
|
||||
|
||||
**Roboto-Medium.ttf**, by Christian Robetson
|
||||
<br>Apache License 2.0
|
||||
<br>https://fonts.google.com/specimen/Roboto
|
||||
|
||||
**Cousine-Regular.ttf**, by Steve Matteson
|
||||
<br>Digitized data copyright (c) 2010 Google Corporation.
|
||||
<br>Licensed under the SIL Open Font License, Version 1.1
|
||||
<br>https://fonts.google.com/specimen/Cousine
|
||||
|
||||
**DroidSans.ttf**, by Steve Matteson
|
||||
<br>Apache License 2.0
|
||||
<br>https://www.fontsquirrel.com/fonts/droid-sans
|
||||
|
||||
**ProggyClean.ttf**, by Tristan Grimmer
|
||||
<br>MIT License
|
||||
<br>(recommended loading setting: Size = 13.0, GlyphOffset.y = +1)
|
||||
<br>http://www.proggyfonts.net/
|
||||
|
||||
**ProggyTiny.ttf**, by Tristan Grimmer
|
||||
<br>MIT License
|
||||
<br>(recommended loading setting: Size = 10.0, GlyphOffset.y = +1)
|
||||
<br>http://www.proggyfonts.net/
|
||||
|
||||
**Karla-Regular.ttf**, by Jonathan Pinhorn
|
||||
<br>SIL OPEN FONT LICENSE Version 1.1
|
||||
|
||||
##### [Return to Index](#index)
|
||||
|
||||
## Font Links
|
||||
|
||||
#### ICON FONTS
|
||||
|
||||
- C/C++ header for icon fonts (#define with code points to use in source code string literals) https://github.com/juliettef/IconFontCppHeaders
|
||||
- FontAwesome https://fortawesome.github.io/Font-Awesome
|
||||
- OpenFontIcons https://github.com/traverseda/OpenFontIcons
|
||||
- Google Icon Fonts https://design.google.com/icons/
|
||||
- Kenney Icon Font (Game Controller Icons) https://github.com/nicodinh/kenney-icon-font
|
||||
- IcoMoon - Custom Icon font builder https://icomoon.io/app
|
||||
|
||||
#### REGULAR FONTS
|
||||
|
||||
- Google Noto Fonts (worldwide languages) https://www.google.com/get/noto/
|
||||
- Open Sans Fonts https://fonts.google.com/specimen/Open+Sans
|
||||
- (Japanese) M+ fonts by Coji Morishita http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html
|
||||
|
||||
#### MONOSPACE FONTS
|
||||
|
||||
Pixel Perfect:
|
||||
- Proggy Fonts, by Tristan Grimmer http://www.proggyfonts.net or http://upperbounds.net
|
||||
- Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A) https://github.com/kmar/Sweet16Font (also include an .inl file to use directly in dear imgui.)
|
||||
|
||||
Regular:
|
||||
- Google Noto Mono Fonts https://www.google.com/get/noto/
|
||||
- Typefaces for source code beautification https://github.com/chrissimpkins/codeface
|
||||
- Programmation fonts http://s9w.github.io/font_compare/
|
||||
- Inconsolata http://www.levien.com/type/myfonts/inconsolata.html
|
||||
- Adobe Source Code Pro: Monospaced font family for ui & coding environments https://github.com/adobe-fonts/source-code-pro
|
||||
- Monospace/Fixed Width Programmer's Fonts http://www.lowing.org/fonts/
|
||||
|
||||
Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing).
|
||||
|
||||
##### [Return to Index](#index)
|
@ -1,376 +0,0 @@
|
||||
dear imgui
|
||||
FONTS DOCUMENTATION
|
||||
|
||||
Also read https://www.dearimgui.org/faq for more fonts related infos.
|
||||
|
||||
The code in imgui.cpp embeds a copy of 'ProggyClean.ttf' (by Tristan Grimmer),
|
||||
a 13 pixels high, pixel-perfect font used by default.
|
||||
We embed it font in source code so you can use Dear ImGui without any file system access.
|
||||
|
||||
You may also load external .TTF/.OTF files.
|
||||
The files in this folder are suggested fonts, provided as a convenience.
|
||||
|
||||
Please read the FAQ: https://www.dearimgui.org/faq
|
||||
Please use the Discord server: http://discord.dearimgui.org and not the Github issue tracker for basic font loading questions.
|
||||
|
||||
|
||||
---------------------------------------
|
||||
INDEX:
|
||||
---------------------------------------
|
||||
|
||||
- Readme First / FAQ
|
||||
- Fonts Loading Instructions
|
||||
- Using Icons
|
||||
- Using FreeType rasterizer
|
||||
- Building Custom Glyph Ranges
|
||||
- Using custom colorful icons
|
||||
- Embedding Fonts in Source Code
|
||||
- Credits/Licences for fonts included in repository
|
||||
- Fonts Links
|
||||
|
||||
|
||||
---------------------------------------
|
||||
README FIRST / FAQ
|
||||
---------------------------------------
|
||||
|
||||
- You can use the style editor ImGui::ShowStyleEditor() in the "Fonts" section to browse your fonts
|
||||
and understand what's going on if you have an issue.
|
||||
- Fonts are rasterized in a single texture at the time of calling either of io.Fonts->GetTexDataAsAlpha8()/GetTexDataAsRGBA32()/Build().
|
||||
- Make sure your font ranges data are persistent and available at the time the font atlas is being built.
|
||||
- Use C++11 u8"my text" syntax to encode literal strings as UTF-8. e.g.:
|
||||
u8"hello"
|
||||
u8"こんにちは" // this will be encoded as UTF-8
|
||||
- If you want to include a backslash \ character in your string literal, you need to double them e.g. "folder\\filename".
|
||||
Read FAQ for details.
|
||||
|
||||
|
||||
---------------------------------------
|
||||
FONTS LOADING INSTRUCTIONS
|
||||
---------------------------------------
|
||||
|
||||
Load default font:
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->AddFontDefault();
|
||||
|
||||
Load .TTF/.OTF file with:
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
|
||||
|
||||
Load multiple fonts:
|
||||
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
ImFont* font1 = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
|
||||
ImFont* font2 = io.Fonts->AddFontFromFileTTF("anotherfont.otf", size_pixels);
|
||||
|
||||
// Select font at runtime
|
||||
ImGui::Text("Hello"); // use the default font (which is the first loaded font)
|
||||
ImGui::PushFont(font2);
|
||||
ImGui::Text("Hello with another font");
|
||||
ImGui::PopFont();
|
||||
|
||||
For advanced options create a ImFontConfig structure and pass it to the AddFont function (it will be copied internally):
|
||||
|
||||
ImFontConfig config;
|
||||
config.OversampleH = 2;
|
||||
config.OversampleV = 1;
|
||||
config.GlyphExtraSpacing.x = 1.0f;
|
||||
ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, &config);
|
||||
|
||||
Combine two fonts into one:
|
||||
|
||||
// Load a first font
|
||||
ImFont* font = io.Fonts->AddFontDefault();
|
||||
|
||||
// Add character ranges and merge into the previous font
|
||||
// The ranges array is not copied by the AddFont* functions and is used lazily
|
||||
// so ensure it is available at the time of building or calling GetTexDataAsRGBA32().
|
||||
static const ImWchar icons_ranges[] = { 0xf000, 0xf3ff, 0 }; // Will not be copied by AddFont* so keep in scope.
|
||||
ImFontConfig config;
|
||||
config.MergeMode = true;
|
||||
io.Fonts->AddFontFromFileTTF("DroidSans.ttf", 18.0f, &config, io.Fonts->GetGlyphRangesJapanese());
|
||||
io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 18.0f, &config, icons_ranges);
|
||||
io.Fonts->Build();
|
||||
|
||||
Font atlas is too large?
|
||||
|
||||
- If you have very large number of glyphs or multiple fonts, the texture may become too big for your graphics API.
|
||||
- The typical result of failing to upload a texture is if every glyphs appears as white rectangles.
|
||||
- In particular, using a large range such as GetGlyphRangesChineseSimplifiedCommon() is not recommended
|
||||
unless you set OversampleH/OversampleV to 1 and use a small font size.
|
||||
- Mind the fact that some graphics drivers have texture size limitation.
|
||||
- If you are building a PC application, mind the fact that users may run on hardware with lower specs than yours.
|
||||
|
||||
Some solutions:
|
||||
|
||||
- 1) Reduce glyphs ranges by calculating them from source localization data.
|
||||
You can use ImFontGlyphRangesBuilder for this purpose, this will be the biggest win!
|
||||
- 2) You may reduce oversampling, e.g. config.OversampleH = config.OversampleV = 1, this will largely reduce your texture size.
|
||||
- 3) Set io.Fonts.TexDesiredWidth to specify a texture width to minimize texture height (see comment in ImFontAtlas::Build function).
|
||||
- 4) Set io.Fonts.Flags |= ImFontAtlasFlags_NoPowerOfTwoHeight; to disable rounding the texture height to the next power of two.
|
||||
- Read about oversampling here: https://github.com/nothings/stb/blob/master/tests/oversample
|
||||
|
||||
|
||||
Add a fourth parameter to bake specific font ranges only:
|
||||
|
||||
// Basic Latin, Extended Latin
|
||||
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesDefault());
|
||||
|
||||
// Default + Selection of 2500 Ideographs used by Simplified Chinese
|
||||
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesChineseSimplifiedCommon());
|
||||
|
||||
// Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
|
||||
io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
|
||||
|
||||
See "BUILDING CUSTOM GLYPH RANGES" section to create your own ranges.
|
||||
Offset font vertically by altering the io.Font->DisplayOffset value:
|
||||
|
||||
ImFont* font = io.Fonts->AddFontFromFileTTF("font.ttf", size_pixels);
|
||||
font->DisplayOffset.y = 1; // Render 1 pixel down
|
||||
|
||||
|
||||
---------------------------------------
|
||||
USING ICONS
|
||||
---------------------------------------
|
||||
|
||||
Using an icon font (such as FontAwesome: http://fontawesome.io or OpenFontIcons. https://github.com/traverseda/OpenFontIcons)
|
||||
is an easy and practical way to use icons in your Dear ImGui application.
|
||||
A common pattern is to merge the icon font within your main font, so you can embed icons directly from your strings without
|
||||
having to change fonts back and forth.
|
||||
|
||||
To refer to the icon UTF-8 codepoints from your C++ code, you may use those headers files created by Juliette Foucaut:
|
||||
|
||||
https://github.com/juliettef/IconFontCppHeaders
|
||||
|
||||
Those files contains a bunch of named #define which you can use to refer to specific icons of the font, e.g.:
|
||||
|
||||
#define ICON_FA_MUSIC "\xef\x80\x81"
|
||||
#define ICON_FA_SEARCH "\xef\x80\x82"
|
||||
|
||||
Example Setup:
|
||||
|
||||
// Merge icons into default tool font
|
||||
#include "IconsFontAwesome.h"
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.Fonts->AddFontDefault();
|
||||
|
||||
ImFontConfig config;
|
||||
config.MergeMode = true;
|
||||
config.GlyphMinAdvanceX = 13.0f; // Use if you want to make the icon monospaced
|
||||
static const ImWchar icon_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
|
||||
io.Fonts->AddFontFromFileTTF("fonts/fontawesome-webfont.ttf", 13.0f, &config, icon_ranges);
|
||||
|
||||
Example Usage:
|
||||
|
||||
// Usage, e.g.
|
||||
ImGui::Text("%s among %d items", ICON_FA_SEARCH, count);
|
||||
ImGui::Button(ICON_FA_SEARCH " Search");
|
||||
|
||||
Important to understand: C string _literals_ can be concatenated at compilation time, e.g. "hello" " world"
|
||||
ICON_FA_SEARCH is defined as a string literal so this is the same as "A" "B" becoming "AB"
|
||||
|
||||
See Links below for other icons fonts and related tools.
|
||||
|
||||
|
||||
---------------------------------------
|
||||
FREETYPE RASTERIZER, SMALL FONT SIZES
|
||||
---------------------------------------
|
||||
|
||||
Dear ImGui uses imstb_truetype.h to rasterize fonts (with optional oversampling).
|
||||
This technique and its implementation are not ideal for fonts rendered at _small sizes_, which may appear a
|
||||
little blurry or hard to read.
|
||||
|
||||
There is an implementation of the ImFontAtlas builder using FreeType that you can use in the misc/freetype/ folder.
|
||||
|
||||
FreeType supports auto-hinting which tends to improve the readability of small fonts.
|
||||
Note that this code currently creates textures that are unoptimally too large (could be fixed with some work).
|
||||
Also note that correct sRGB space blending will have an important effect on your font rendering quality.
|
||||
|
||||
|
||||
---------------------------------------
|
||||
BUILDING CUSTOM GLYPH RANGES
|
||||
---------------------------------------
|
||||
|
||||
You can use the ImFontGlyphRangesBuilder helper to create glyph ranges based on text input.
|
||||
For example: for a game where your script is known, if you can feed your entire script to it and only build the characters the game needs.
|
||||
|
||||
ImVector<ImWchar> ranges;
|
||||
ImFontGlyphRangesBuilder builder;
|
||||
builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
|
||||
builder.AddChar(0x7262); // Add a specific character
|
||||
builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
|
||||
builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
|
||||
|
||||
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
|
||||
io.Fonts->Build(); // Build the atlas while 'ranges' is still in scope and not deleted.
|
||||
|
||||
|
||||
---------------------------------------
|
||||
USING CUSTOM COLORFUL ICONS
|
||||
---------------------------------------
|
||||
|
||||
(This is a BETA api, use if you are familiar with dear imgui and with your rendering back-end)
|
||||
|
||||
You can use the ImFontAtlas::AddCustomRect() and ImFontAtlas::AddCustomRectFontGlyph() api to register rectangles
|
||||
that will be packed into the font atlas texture. Register them before building the atlas, then call Build().
|
||||
You can then use ImFontAtlas::GetCustomRectByIndex(int) to query the position/size of your rectangle within the
|
||||
texture, and blit/copy any graphics data of your choice into those rectangles.
|
||||
|
||||
Pseudo-code:
|
||||
|
||||
// Add font, then register two custom 13x13 rectangles mapped to glyph 'a' and 'b' of this font
|
||||
ImFont* font = io.Fonts->AddFontDefault();
|
||||
int rect_ids[2];
|
||||
rect_ids[0] = io.Fonts->AddCustomRectFontGlyph(font, 'a', 13, 13, 13+1);
|
||||
rect_ids[1] = io.Fonts->AddCustomRectFontGlyph(font, 'b', 13, 13, 13+1);
|
||||
|
||||
// Build atlas
|
||||
io.Fonts->Build();
|
||||
|
||||
// Retrieve texture in RGBA format
|
||||
unsigned char* tex_pixels = NULL;
|
||||
int tex_width, tex_height;
|
||||
io.Fonts->GetTexDataAsRGBA32(&tex_pixels, &tex_width, &tex_height);
|
||||
|
||||
for (int rect_n = 0; rect_n < IM_ARRAYSIZE(rect_ids); rect_n++)
|
||||
{
|
||||
int rect_id = rects_ids[rect_n];
|
||||
if (const ImFontAtlas::CustomRect* rect = io.Fonts->GetCustomRectByIndex(rect_id))
|
||||
{
|
||||
// Fill the custom rectangle with red pixels (in reality you would draw/copy your bitmap data here!)
|
||||
for (int y = 0; y < rect->Height; y++)
|
||||
{
|
||||
ImU32* p = (ImU32*)tex_pixels + (rect->Y + y) * tex_width + (rect->X);
|
||||
for (int x = rect->Width; x > 0; x--)
|
||||
*p++ = IM_COL32(255, 0, 0, 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
---------------------------------------
|
||||
EMBEDDING FONTS IN SOURCE CODE
|
||||
---------------------------------------
|
||||
|
||||
Compile and use 'binary_to_compressed_c.cpp' to create a compressed C style array that you can embed in source code.
|
||||
See the documentation in binary_to_compressed_c.cpp for instruction on how to use the tool.
|
||||
You may find a precompiled version binary_to_compressed_c.exe for Windows instead of demo binaries package (see README).
|
||||
The tool can optionally output Base85 encoding to reduce the size of _source code_ but the read-only arrays in the
|
||||
actual binary will be about 20% bigger.
|
||||
|
||||
Then load the font with:
|
||||
ImFont* font = io.Fonts->AddFontFromMemoryCompressedTTF(compressed_data, compressed_data_size, size_pixels, ...);
|
||||
or:
|
||||
ImFont* font = io.Fonts->AddFontFromMemoryCompressedBase85TTF(compressed_data_base85, size_pixels, ...);
|
||||
|
||||
|
||||
---------------------------------------
|
||||
CREDITS/LICENSES FOR FONTS INCLUDED IN REPOSITORY
|
||||
---------------------------------------
|
||||
|
||||
Some fonts are available in the misc/fonts/ folder:
|
||||
|
||||
Roboto-Medium.ttf
|
||||
|
||||
Apache License 2.0
|
||||
by Christian Robertson
|
||||
https://fonts.google.com/specimen/Roboto
|
||||
|
||||
Cousine-Regular.ttf
|
||||
|
||||
by Steve Matteson
|
||||
Digitized data copyright (c) 2010 Google Corporation.
|
||||
Licensed under the SIL Open Font License, Version 1.1
|
||||
https://fonts.google.com/specimen/Cousine
|
||||
|
||||
DroidSans.ttf
|
||||
|
||||
Copyright (c) Steve Matteson
|
||||
Apache License, version 2.0
|
||||
https://www.fontsquirrel.com/fonts/droid-sans
|
||||
|
||||
ProggyClean.ttf
|
||||
|
||||
Copyright (c) 2004, 2005 Tristan Grimmer
|
||||
MIT License
|
||||
recommended loading setting: Size = 13.0, DisplayOffset.Y = +1
|
||||
http://www.proggyfonts.net/
|
||||
|
||||
ProggyTiny.ttf
|
||||
Copyright (c) 2004, 2005 Tristan Grimmer
|
||||
MIT License
|
||||
recommended loading setting: Size = 10.0, DisplayOffset.Y = +1
|
||||
http://www.proggyfonts.net/
|
||||
|
||||
Karla-Regular.ttf
|
||||
Copyright (c) 2012, Jonathan Pinhorn
|
||||
SIL OPEN FONT LICENSE Version 1.1
|
||||
|
||||
|
||||
---------------------------------------
|
||||
FONTS LINKS
|
||||
---------------------------------------
|
||||
|
||||
ICON FONTS
|
||||
|
||||
C/C++ header for icon fonts (#define with code points to use in source code string literals)
|
||||
https://github.com/juliettef/IconFontCppHeaders
|
||||
|
||||
FontAwesome
|
||||
https://fortawesome.github.io/Font-Awesome
|
||||
|
||||
OpenFontIcons
|
||||
https://github.com/traverseda/OpenFontIcons
|
||||
|
||||
Google Icon Fonts
|
||||
https://design.google.com/icons/
|
||||
|
||||
Kenney Icon Font (Game Controller Icons)
|
||||
https://github.com/nicodinh/kenney-icon-font
|
||||
|
||||
IcoMoon - Custom Icon font builder
|
||||
https://icomoon.io/app
|
||||
|
||||
REGULAR FONTS
|
||||
|
||||
Google Noto Fonts (worldwide languages)
|
||||
https://www.google.com/get/noto/
|
||||
|
||||
Open Sans Fonts
|
||||
https://fonts.google.com/specimen/Open+Sans
|
||||
|
||||
(Japanese) M+ fonts by Coji Morishita are free
|
||||
http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html
|
||||
|
||||
MONOSPACE FONTS (PIXEL PERFECT)
|
||||
|
||||
Proggy Fonts, by Tristan Grimmer
|
||||
http://www.proggyfonts.net or http://upperbounds.net
|
||||
|
||||
Sweet16, Sweet16 Mono, by Martin Sedlak (Latin + Supplemental + Extended A)
|
||||
https://github.com/kmar/Sweet16Font
|
||||
Also include .inl file to use directly in dear imgui.
|
||||
|
||||
MONOSPACE FONTS (REGULAR)
|
||||
|
||||
Google Noto Mono Fonts
|
||||
https://www.google.com/get/noto/
|
||||
|
||||
Typefaces for source code beautification
|
||||
https://github.com/chrissimpkins/codeface
|
||||
|
||||
Programmation fonts
|
||||
http://s9w.github.io/font_compare/
|
||||
|
||||
Inconsolata
|
||||
http://www.levien.com/type/myfonts/inconsolata.html
|
||||
|
||||
Adobe Source Code Pro: Monospaced font family for user interface and coding environments
|
||||
https://github.com/adobe-fonts/source-code-pro
|
||||
|
||||
Monospace/Fixed Width Programmer's Fonts
|
||||
http://www.lowing.org/fonts/
|
||||
|
||||
|
||||
Or use Arial Unicode or other Unicode fonts provided with Windows for full characters coverage (not sure of their licensing).
|
@ -1,294 +1,9 @@
|
||||
-----------------------------------------------------------------------
|
||||
dear imgui, v1.77 WIP
|
||||
-----------------------------------------------------------------------
|
||||
examples/README.txt
|
||||
(This is the README file for the examples/ folder. See docs/ for more documentation)
|
||||
-----------------------------------------------------------------------
|
||||
See BACKENDS and EXAMPLES files in the docs/ folder, or on the web at: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
Dear ImGui is highly portable and only requires a few things to run and render:
|
||||
Backends = Helper code to facilitate integration with platforms/graphics api (used by Examples + should be used by your app).
|
||||
Examples = Standalone applications showcasing integration with platforms/graphics api.
|
||||
|
||||
- Providing mouse/keyboard inputs
|
||||
- Uploading the font atlas texture into graphics memory
|
||||
- Providing a render function to render indexed textured triangles
|
||||
- Optional: clipboard support, mouse cursor supports, Windows IME support, etc.
|
||||
- Optional (Advanced,Beta): platform window API to use multi-viewport.
|
||||
Some Examples have extra README files in their respective directory, please check them too!
|
||||
|
||||
This is essentially what the example bindings in this folder are providing + obligatory portability cruft.
|
||||
|
||||
It is important to understand the difference between the core Dear ImGui library (files in the root folder)
|
||||
and examples bindings which we are describing here (examples/ folder).
|
||||
You should be able to write bindings for pretty much any platform and any 3D graphics API. With some extra
|
||||
effort you can even perform the rendering remotely, on a different machine than the one running the logic.
|
||||
|
||||
This folder contains two things:
|
||||
|
||||
- Example bindings for popular platforms/graphics API, which you can use as is or adapt for your own use.
|
||||
They are the imgui_impl_XXXX files found in the examples/ folder.
|
||||
|
||||
- Example applications (standalone, ready-to-build) using the aforementioned bindings.
|
||||
They are the in the XXXX_example/ sub-folders.
|
||||
|
||||
You can find binaries of some of those example applications at:
|
||||
http://www.dearimgui.org/binaries
|
||||
|
||||
|
||||
---------------------------------------
|
||||
MISC COMMENTS AND SUGGESTIONS
|
||||
---------------------------------------
|
||||
|
||||
- Read FAQ at http://dearimgui.org/faq
|
||||
|
||||
- Please read 'PROGRAMMER GUIDE' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.
|
||||
Please read the comments and instruction at the top of each file.
|
||||
|
||||
- If you are using of the backend provided here, so you can copy the imgui_impl_xxx.cpp/h files
|
||||
to your project and use them unmodified. Each imgui_impl_xxxx.cpp comes with its own individual
|
||||
ChangeLog at the top of the .cpp files, so if you want to update them later it will be easier to
|
||||
catch up with what changed.
|
||||
|
||||
- Dear ImGui has 0 to 1 frame of lag for most behaviors, at 60 FPS your experience should be pleasant.
|
||||
However, consider that OS mouse cursors are typically drawn through a specific hardware accelerated path
|
||||
and will feel smoother than common GPU rendered contents (including Dear ImGui windows).
|
||||
You may experiment with the io.MouseDrawCursor flag to request Dear ImGui to draw a mouse cursor itself,
|
||||
to visualize the lag between a hardware cursor and a software cursor. However, rendering a mouse cursor
|
||||
at 60 FPS will feel slow. It might be beneficial to the user experience to switch to a software rendered
|
||||
cursor only when an interactive drag is in progress.
|
||||
Note that some setup or GPU drivers are likely to be causing extra lag depending on their settings.
|
||||
If you feel that dragging windows feels laggy and you are not sure who to blame: try to build an
|
||||
application drawing a shape directly under the mouse cursor.
|
||||
|
||||
|
||||
---------------------------------------
|
||||
EXAMPLE BINDINGS
|
||||
---------------------------------------
|
||||
|
||||
Most the example bindings are split in 2 parts:
|
||||
|
||||
- The "Platform" bindings, in charge of: mouse/keyboard/gamepad inputs, cursor shape, timing, windowing.
|
||||
Examples: Windows (imgui_impl_win32.cpp), GLFW (imgui_impl_glfw.cpp), SDL2 (imgui_impl_sdl.cpp), etc.
|
||||
|
||||
- The "Renderer" bindings, in charge of: creating the main font texture, rendering imgui draw data.
|
||||
Examples: DirectX11 (imgui_impl_dx11.cpp), GL3 (imgui_impl_opengl3.cpp), Vulkan (imgui_impl_vulkan.cpp), etc.
|
||||
|
||||
- The example _applications_ usually combine 1 platform + 1 renderer binding to create a working program.
|
||||
Examples: the example_win32_directx11/ application combines imgui_impl_win32.cpp + imgui_impl_dx11.cpp.
|
||||
|
||||
- Some bindings for higher level frameworks carry both "Platform" and "Renderer" parts in one file.
|
||||
This is the case for Allegro 5 (imgui_impl_allegro5.cpp), Marmalade (imgui_impl_marmalade5.cpp).
|
||||
|
||||
- If you use your own engine, you may decide to use some of existing bindings and/or rewrite some using
|
||||
your own API. As a recommendation, if you are new to Dear ImGui, try using the existing binding as-is
|
||||
first, before moving on to rewrite some of the code. Although it is tempting to rewrite both of the
|
||||
imgui_impl_xxxx files to fit under your coding style, consider that it is not necessary!
|
||||
In fact, if you are new to Dear ImGui, rewriting them will almost always be harder.
|
||||
|
||||
Example: your engine is built over Windows + DirectX11 but you have your own high-level rendering
|
||||
system layered over DirectX11.
|
||||
Suggestion: step 1: try using imgui_impl_win32.cpp + imgui_impl_dx11.cpp first.
|
||||
Once this work, _if_ you want you can replace the imgui_impl_dx11.cpp code with a custom renderer
|
||||
using your own functions, etc.
|
||||
Please consider using the bindings to the lower-level platform/graphics API as-is.
|
||||
|
||||
Example: your engine is multi-platform (consoles, phones, etc.), you have high-level systems everywhere.
|
||||
Suggestion: step 1: try using a non-portable binding first (e.g. win32 + underlying graphics API)!
|
||||
This is counter-intuitive, but this will get you running faster! Once you better understand how imgui
|
||||
works and is bound, you can rewrite the code using your own systems.
|
||||
|
||||
- Road-map: Dear ImGui 1.80 (WIP currently in the "docking" branch) will allows imgui windows to be
|
||||
seamlessly detached from the main application window. This is achieved using an extra layer to the
|
||||
platform and renderer bindings, which allows Dear ImGui to communicate platform-specific requests such as
|
||||
"create an additional OS window", "create a render context", "get the OS position of this window" etc.
|
||||
When using this feature, the coupling with your OS/renderer becomes much tighter than a regular imgui
|
||||
integration. It is also much more complicated and require more work to integrate correctly.
|
||||
If you are new to imgui and you are trying to integrate it into your application, first try to ignore
|
||||
everything related to Viewport and Platform Windows. You'll be able to come back to it later!
|
||||
Note that if you decide to use unmodified imgui_impl_xxxx.cpp files, you will automatically benefit
|
||||
from improvements and fixes related to viewports and platform windows without extra work on your side.
|
||||
See 'ImGuiPlatformIO' for details.
|
||||
|
||||
|
||||
List of Platforms Bindings in this repository:
|
||||
|
||||
imgui_impl_glfw.cpp ; GLFW (Windows, macOS, Linux, etc.) http://www.glfw.org/
|
||||
imgui_impl_osx.mm ; macOS native API (not as feature complete as glfw/sdl back-ends)
|
||||
imgui_impl_sdl.cpp ; SDL2 (Windows, macOS, Linux, iOS, Android) https://www.libsdl.org
|
||||
imgui_impl_win32.cpp ; Win32 native API (Windows)
|
||||
imgui_impl_glut.cpp ; GLUT/FreeGLUT (absolutely not recommended in 2020!)
|
||||
|
||||
List of Renderer Bindings in this repository:
|
||||
|
||||
imgui_impl_dx9.cpp ; DirectX9
|
||||
imgui_impl_dx10.cpp ; DirectX10
|
||||
imgui_impl_dx11.cpp ; DirectX11
|
||||
imgui_impl_dx12.cpp ; DirectX12
|
||||
imgui_impl_metal.mm ; Metal (with ObjC)
|
||||
imgui_impl_opengl2.cpp ; OpenGL 2 (legacy, fixed pipeline <- don't use with modern OpenGL context)
|
||||
imgui_impl_opengl3.cpp ; OpenGL 3/4, OpenGL ES 2, OpenGL ES 3 (modern programmable pipeline)
|
||||
imgui_impl_vulkan.cpp ; Vulkan
|
||||
|
||||
List of high-level Frameworks Bindings in this repository: (combine Platform + Renderer)
|
||||
|
||||
imgui_impl_allegro5.cpp
|
||||
imgui_impl_marmalade.cpp
|
||||
|
||||
Note that Dear ImGui works with Emscripten. The examples_emscripten/ app uses imgui_impl_sdl.cpp and
|
||||
imgui_impl_opengl3.cpp, but other combinations are possible.
|
||||
|
||||
Third-party framework, graphics API and languages bindings are listed at:
|
||||
|
||||
https://github.com/ocornut/imgui/wiki/Bindings
|
||||
|
||||
Including backends for:
|
||||
|
||||
AGS/Adventure Game Studio, Amethyst, bsf, Cinder, Cocos2d-x, Diligent Engine, Flexium,
|
||||
GML/Game Maker Studio2, GTK3+OpenGL3, Irrlicht Engine, LÖVE+LUA, Magnum, NanoRT, Nim Game Lib,
|
||||
Ogre, openFrameworks, OSG/OpenSceneGraph, Orx, px_render, Qt/QtDirect3D, SFML, Sokol,
|
||||
Unreal Engine 4, vtk, Win32 GDI, etc.
|
||||
|
||||
Not sure which to use?
|
||||
Recommended platform/frameworks:
|
||||
|
||||
GLFW https://github.com/glfw/glfw Use imgui_impl_glfw.cpp
|
||||
SDL2 https://www.libsdl.org Use imgui_impl_sdl.cpp
|
||||
Sokol https://github.com/floooh/sokol Use util/sokol_imgui.h in Sokol repository.
|
||||
|
||||
Those will allow you to create portable applications and will solve and abstract away many issues.
|
||||
|
||||
|
||||
---------------------------------------
|
||||
EXAMPLE APPLICATIONS
|
||||
---------------------------------------
|
||||
|
||||
Building:
|
||||
Unfortunately in 2020 it is still tedious to create and maintain portable build files using external
|
||||
libraries (the kind we're using here to create a window and render 3D triangles) without relying on
|
||||
third party software. For most examples here I choose to provide:
|
||||
- Makefiles for Linux/OSX
|
||||
- Batch files for Visual Studio 2008+
|
||||
- A .sln project file for Visual Studio 2010+
|
||||
- Xcode project files for the Apple examples
|
||||
Please let me know if they don't work with your setup!
|
||||
You can probably just import the imgui_impl_xxx.cpp/.h files into your own codebase or compile those
|
||||
directly with a command-line compiler.
|
||||
|
||||
If you are interested in using Cmake to build and links examples, see:
|
||||
https://github.com/ocornut/imgui/pull/1713 and https://github.com/ocornut/imgui/pull/3027
|
||||
|
||||
|
||||
example_allegro5/
|
||||
Allegro 5 example.
|
||||
= main.cpp + imgui_impl_allegro5.cpp
|
||||
|
||||
example_apple_metal/
|
||||
OSX & iOS + Metal.
|
||||
= main.m + imgui_impl_osx.mm + imgui_impl_metal.mm
|
||||
It is based on the "cross-platform" game template provided with Xcode as of Xcode 9.
|
||||
(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms back-ends.
|
||||
You may prefer to use the GLFW Or SDL back-ends, which will also support Windows and Linux.)
|
||||
|
||||
example_apple_opengl2/
|
||||
OSX + OpenGL2.
|
||||
= main.mm + imgui_impl_osx.mm + imgui_impl_opengl2.cpp
|
||||
(NB: imgui_impl_osx.mm is currently not as feature complete as other platforms back-ends.
|
||||
You may prefer to use the GLFW Or SDL back-ends, which will also support Windows and Linux.)
|
||||
|
||||
example_empscripten:
|
||||
Emcripten + SDL2 + OpenGL3+/ES2/ES3 example.
|
||||
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp
|
||||
Note that other examples based on SDL or GLFW + OpenGL could easily be modified to work with Emscripten.
|
||||
We provide this to make the Emscripten differences obvious, and have them not pollute all other examples.
|
||||
|
||||
example_glfw_metal/
|
||||
GLFW (Mac) + Metal example.
|
||||
= main.mm + imgui_impl_glfw.cpp + imgui_impl_metal.mm
|
||||
|
||||
example_glfw_opengl2/
|
||||
GLFW + OpenGL2 example (legacy, fixed pipeline).
|
||||
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl2.cpp
|
||||
**DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
|
||||
**Prefer using OPENGL3 code (with gl3w/glew/glad/glbinding, you can replace the OpenGL function loader)**
|
||||
This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter.
|
||||
If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to
|
||||
make things more complicated, will require your code to reset many OpenGL attributes to their initial
|
||||
state, and might confuse your GPU driver. One star, not recommended.
|
||||
|
||||
example_glfw_opengl3/
|
||||
GLFW (Win32, Mac, Linux) + OpenGL3+/ES2/ES3 example (programmable pipeline).
|
||||
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_opengl3.cpp
|
||||
This uses more modern OpenGL calls and custom shaders.
|
||||
Prefer using that if you are using modern OpenGL in your application (anything with shaders).
|
||||
(Please be mindful that accessing OpenGL3+ functions requires a function loader, which are a frequent
|
||||
source for confusion for new users. We use a loader in imgui_impl_opengl3.cpp which may be different
|
||||
from the one your app normally use. Read imgui_impl_opengl3.h for details and how to change it.)
|
||||
|
||||
example_glfw_vulkan/
|
||||
GLFW (Win32, Mac, Linux) + Vulkan example.
|
||||
= main.cpp + imgui_impl_glfw.cpp + imgui_impl_vulkan.cpp
|
||||
This is quite long and tedious, because: Vulkan.
|
||||
For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp.
|
||||
|
||||
example_glut_opengl2/
|
||||
GLUT (e.g., FreeGLUT on Linux/Windows, GLUT framework on OSX) + OpenGL2.
|
||||
= main.cpp + imgui_impl_glut.cpp + imgui_impl_opengl2.cpp
|
||||
Note that GLUT/FreeGLUT is largely obsolete software, prefer using GLFW or SDL.
|
||||
|
||||
example_marmalade/
|
||||
Marmalade example using IwGx.
|
||||
= main.cpp + imgui_impl_marmalade.cpp
|
||||
|
||||
example_null
|
||||
Null example, compile and link imgui, create context, run headless with no inputs and no graphics output.
|
||||
= main.cpp
|
||||
This is used to quickly test compilation of core imgui files in as many setups as possible.
|
||||
Because this application doesn't create a window nor a graphic context, there's no graphics output.
|
||||
|
||||
example_sdl_directx11/
|
||||
SDL2 + DirectX11 example, Windows only.
|
||||
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_dx11.cpp
|
||||
This to demonstrate usage of DirectX with SDL.
|
||||
|
||||
example_sdl_metal/
|
||||
SDL2 (Mac) + Metal example.
|
||||
= main.mm + imgui_impl_sdl.cpp + imgui_impl_metal.mm
|
||||
|
||||
example_sdl_opengl2/
|
||||
SDL2 (Win32, Mac, Linux etc.) + OpenGL example (legacy, fixed pipeline).
|
||||
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl2.cpp
|
||||
**DO NOT USE OPENGL2 CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
|
||||
**Prefer using OPENGL3 code (with gl3w/glew/glad/glbinding, you can replace the OpenGL function loader)**
|
||||
This code is mostly provided as a reference to learn about Dear ImGui integration, because it is shorter.
|
||||
If your code is using GL3+ context or any semi modern OpenGL calls, using this renderer is likely to
|
||||
make things more complicated, will require your code to reset many OpenGL attributes to their initial
|
||||
state, and might confuse your GPU driver. One star, not recommended.
|
||||
|
||||
example_sdl_opengl3/
|
||||
SDL2 (Win32, Mac, Linux, etc.) + OpenGL3+/ES2/ES3 example.
|
||||
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_opengl3.cpp
|
||||
This uses more modern OpenGL calls and custom shaders.
|
||||
Prefer using that if you are using modern OpenGL in your application (anything with shaders).
|
||||
(Please be mindful that accessing OpenGL3+ functions requires a function loader, which are a frequent
|
||||
source for confusion for new users. We use a loader in imgui_impl_opengl3.cpp which may be different
|
||||
from the one your app normally use. Read imgui_impl_opengl3.h for details and how to change it.)
|
||||
|
||||
example_sdl_vulkan/
|
||||
SDL2 (Win32, Mac, Linux, etc.) + Vulkan example.
|
||||
= main.cpp + imgui_impl_sdl.cpp + imgui_impl_vulkan.cpp
|
||||
This is quite long and tedious, because: Vulkan.
|
||||
For this example, the main.cpp file exceptionally use helpers function from imgui_impl_vulkan.h/cpp.
|
||||
|
||||
example_win32_directx9/
|
||||
DirectX9 example, Windows only.
|
||||
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx9.cpp
|
||||
|
||||
example_win32_directx10/
|
||||
DirectX10 example, Windows only.
|
||||
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx10.cpp
|
||||
|
||||
example_win32_directx11/
|
||||
DirectX11 example, Windows only.
|
||||
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx11.cpp
|
||||
|
||||
example_win32_directx12/
|
||||
DirectX12 example, Windows only.
|
||||
= main.cpp + imgui_impl_win32.cpp + imgui_impl_dx12.cpp
|
||||
This is quite long and tedious, because: DirectX12.
|
||||
Once Dear ImGui is running (in either examples or your own application/game/engine),
|
||||
run and refer to ImGui::ShowDemoWindow() in imgui_demo.cpp for the end-user API.
|
||||
|
@ -0,0 +1,40 @@
|
||||
cmake_minimum_required(VERSION 3.6)
|
||||
|
||||
project(ImGuiExample)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 11)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
add_library(${CMAKE_PROJECT_NAME} SHARED
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/main.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../imgui.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../imgui_demo.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../imgui_draw.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../imgui_tables.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../imgui_widgets.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../backends/imgui_impl_android.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../backends/imgui_impl_opengl3.cpp
|
||||
${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c
|
||||
)
|
||||
|
||||
set(CMAKE_SHARED_LINKER_FLAGS
|
||||
"${CMAKE_SHARED_LINKER_FLAGS} -u ANativeActivity_onCreate"
|
||||
)
|
||||
|
||||
target_compile_definitions(${CMAKE_PROJECT_NAME} PRIVATE
|
||||
IMGUI_IMPL_OPENGL_ES3
|
||||
)
|
||||
|
||||
target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../..
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../backends
|
||||
${ANDROID_NDK}/sources/android/native_app_glue
|
||||
)
|
||||
|
||||
target_link_libraries(${CMAKE_PROJECT_NAME} PRIVATE
|
||||
android
|
||||
EGL
|
||||
GLESv3
|
||||
log
|
||||
)
|
@ -0,0 +1,12 @@
|
||||
.cxx
|
||||
.externalNativeBuild
|
||||
build/
|
||||
*.iml
|
||||
|
||||
.idea
|
||||
.gradle
|
||||
local.properties
|
||||
|
||||
# Android Studio puts a Gradle wrapper here, that we don't want:
|
||||
gradle/
|
||||
gradlew*
|
@ -0,0 +1,34 @@
|
||||
apply plugin: 'com.android.application'
|
||||
apply plugin: 'kotlin-android'
|
||||
|
||||
android {
|
||||
compileSdkVersion 29
|
||||
buildToolsVersion "30.0.3"
|
||||
ndkVersion "21.4.7075529"
|
||||
defaultConfig {
|
||||
applicationId "imgui.example.android"
|
||||
minSdkVersion 23
|
||||
targetSdkVersion 29
|
||||
versionCode 1
|
||||
versionName "1.0"
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
minifyEnabled false
|
||||
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt')
|
||||
}
|
||||
}
|
||||
|
||||
externalNativeBuild {
|
||||
cmake {
|
||||
path "../../CMakeLists.txt"
|
||||
}
|
||||
}
|
||||
}
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="imgui.example.android">
|
||||
|
||||
<application
|
||||
android:label="ImGuiExample"
|
||||
android:allowBackup="false"
|
||||
android:fullBackupContent="false"
|
||||
android:hasCode="true">
|
||||
|
||||
<activity
|
||||
android:name="imgui.example.android.MainActivity"
|
||||
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
|
||||
android:configChanges="orientation|keyboardHidden|screenSize">
|
||||
<meta-data android:name="android.app.lib_name"
|
||||
android:value="ImGuiExample" />
|
||||
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
</application>
|
||||
</manifest>
|
@ -0,0 +1,40 @@
|
||||
package imgui.example.android
|
||||
|
||||
import android.app.NativeActivity
|
||||
import android.os.Bundle
|
||||
import android.content.Context
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.view.KeyEvent
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
|
||||
class MainActivity : NativeActivity() {
|
||||
public override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
}
|
||||
|
||||
fun showSoftInput() {
|
||||
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
inputMethodManager.showSoftInput(this.window.decorView, 0)
|
||||
}
|
||||
|
||||
fun hideSoftInput() {
|
||||
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
inputMethodManager.hideSoftInputFromWindow(this.window.decorView.windowToken, 0)
|
||||
}
|
||||
|
||||
// Queue for the Unicode characters to be polled from native code (via pollUnicodeChar())
|
||||
private var unicodeCharacterQueue: LinkedBlockingQueue<Int> = LinkedBlockingQueue()
|
||||
|
||||
// We assume dispatchKeyEvent() of the NativeActivity is actually called for every
|
||||
// KeyEvent and not consumed by any View before it reaches here
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||
unicodeCharacterQueue.offer(event.getUnicodeChar(event.metaState))
|
||||
}
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
|
||||
fun pollUnicodeChar(): Int {
|
||||
return unicodeCharacterQueue.poll() ?: 0
|
||||
}
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
buildscript {
|
||||
ext.kotlin_version = '1.4.31'
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:4.1.0'
|
||||
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
task clean(type: Delete) {
|
||||
delete rootProject.buildDir
|
||||
}
|
@ -0,0 +1 @@
|
||||
include ':app'
|
@ -0,0 +1,369 @@
|
||||
// dear imgui: standalone example application for Android + OpenGL ES 3
|
||||
// If you are new to dear imgui, see examples/README.txt and documentation at the top of imgui.cpp.
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_android.h"
|
||||
#include "imgui_impl_opengl3.h"
|
||||
#include <android/log.h>
|
||||
#include <android_native_app_glue.h>
|
||||
#include <android/asset_manager.h>
|
||||
#include <EGL/egl.h>
|
||||
#include <GLES3/gl3.h>
|
||||
|
||||
// Data
|
||||
static EGLDisplay g_EglDisplay = EGL_NO_DISPLAY;
|
||||
static EGLSurface g_EglSurface = EGL_NO_SURFACE;
|
||||
static EGLContext g_EglContext = EGL_NO_CONTEXT;
|
||||
static struct android_app* g_App = NULL;
|
||||
static bool g_Initialized = false;
|
||||
static char g_LogTag[] = "ImGuiExample";
|
||||
|
||||
// Forward declarations of helper functions
|
||||
static int ShowSoftKeyboardInput();
|
||||
static int PollUnicodeChars();
|
||||
static int GetAssetData(const char* filename, void** out_data);
|
||||
|
||||
void init(struct android_app* app)
|
||||
{
|
||||
if (g_Initialized)
|
||||
return;
|
||||
|
||||
g_App = app;
|
||||
ANativeWindow_acquire(g_App->window);
|
||||
|
||||
// Initialize EGL
|
||||
// This is mostly boilerplate code for EGL...
|
||||
{
|
||||
g_EglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
|
||||
if (g_EglDisplay == EGL_NO_DISPLAY)
|
||||
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglGetDisplay(EGL_DEFAULT_DISPLAY) returned EGL_NO_DISPLAY");
|
||||
|
||||
if (eglInitialize(g_EglDisplay, 0, 0) != EGL_TRUE)
|
||||
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglInitialize() returned with an error");
|
||||
|
||||
const EGLint egl_attributes[] = { EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE };
|
||||
EGLint num_configs = 0;
|
||||
if (eglChooseConfig(g_EglDisplay, egl_attributes, nullptr, 0, &num_configs) != EGL_TRUE)
|
||||
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglChooseConfig() returned with an error");
|
||||
if (num_configs == 0)
|
||||
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglChooseConfig() returned 0 matching config");
|
||||
|
||||
// Get the first matching config
|
||||
EGLConfig egl_config;
|
||||
eglChooseConfig(g_EglDisplay, egl_attributes, &egl_config, 1, &num_configs);
|
||||
EGLint egl_format;
|
||||
eglGetConfigAttrib(g_EglDisplay, egl_config, EGL_NATIVE_VISUAL_ID, &egl_format);
|
||||
ANativeWindow_setBuffersGeometry(g_App->window, 0, 0, egl_format);
|
||||
|
||||
const EGLint egl_context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE };
|
||||
g_EglContext = eglCreateContext(g_EglDisplay, egl_config, EGL_NO_CONTEXT, egl_context_attributes);
|
||||
|
||||
if (g_EglContext == EGL_NO_CONTEXT)
|
||||
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s", "eglCreateContext() returned EGL_NO_CONTEXT");
|
||||
|
||||
g_EglSurface = eglCreateWindowSurface(g_EglDisplay, egl_config, g_App->window, NULL);
|
||||
eglMakeCurrent(g_EglDisplay, g_EglSurface, g_EglSurface, g_EglContext);
|
||||
}
|
||||
|
||||
// Setup Dear ImGui context
|
||||
IMGUI_CHECKVERSION();
|
||||
ImGui::CreateContext();
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
|
||||
// Disable loading/saving of .ini file from disk.
|
||||
// FIXME: Consider using LoadIniSettingsFromMemory() / SaveIniSettingsToMemory() to save in appropriate location for Android.
|
||||
io.IniFilename = NULL;
|
||||
|
||||
// Setup Dear ImGui style
|
||||
ImGui::StyleColorsDark();
|
||||
//ImGui::StyleColorsClassic();
|
||||
|
||||
// Setup Platform/Renderer backends
|
||||
ImGui_ImplAndroid_Init(g_App->window);
|
||||
ImGui_ImplOpenGL3_Init("#version 300 es");
|
||||
|
||||
// Load Fonts
|
||||
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
|
||||
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
|
||||
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
|
||||
// - Read 'docs/FONTS.md' for more instructions and details.
|
||||
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
|
||||
// - Android: The TTF files have to be placed into the assets/ directory (android/app/src/main/assets), we use our GetAssetData() helper to retrieve them.
|
||||
|
||||
// We load the default font with increased size to improve readability on many devices with "high" DPI.
|
||||
// FIXME: Put some effort into DPI awareness.
|
||||
// Important: when calling AddFontFromMemoryTTF(), ownership of font_data is transfered by Dear ImGui by default (deleted is handled by Dear ImGui), unless we set FontDataOwnedByAtlas=false in ImFontConfig
|
||||
ImFontConfig font_cfg;
|
||||
font_cfg.SizePixels = 22.0f;
|
||||
io.Fonts->AddFontDefault(&font_cfg);
|
||||
//void* font_data;
|
||||
//int font_data_size;
|
||||
//ImFont* font;
|
||||
//font_data_size = GetAssetData("Roboto-Medium.ttf", &font_data);
|
||||
//font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f);
|
||||
//IM_ASSERT(font != NULL);
|
||||
//font_data_size = GetAssetData("Cousine-Regular.ttf", &font_data);
|
||||
//font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 15.0f);
|
||||
//IM_ASSERT(font != NULL);
|
||||
//font_data_size = GetAssetData("DroidSans.ttf", &font_data);
|
||||
//font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 16.0f);
|
||||
//IM_ASSERT(font != NULL);
|
||||
//font_data_size = GetAssetData("ProggyTiny.ttf", &font_data);
|
||||
//font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 10.0f);
|
||||
//IM_ASSERT(font != NULL);
|
||||
//font_data_size = GetAssetData("ArialUni.ttf", &font_data);
|
||||
//font = io.Fonts->AddFontFromMemoryTTF(font_data, font_data_size, 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
|
||||
//IM_ASSERT(font != NULL);
|
||||
|
||||
// Arbitrary scale-up
|
||||
// FIXME: Put some effort into DPI awareness
|
||||
ImGui::GetStyle().ScaleAllSizes(3.0f);
|
||||
|
||||
g_Initialized = true;
|
||||
}
|
||||
|
||||
void tick()
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
if (g_EglDisplay == EGL_NO_DISPLAY)
|
||||
return;
|
||||
|
||||
// Our state
|
||||
static bool show_demo_window = true;
|
||||
static bool show_another_window = false;
|
||||
static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
|
||||
|
||||
// Poll Unicode characters via JNI
|
||||
// FIXME: do not call this every frame because of JNI overhead
|
||||
PollUnicodeChars();
|
||||
|
||||
// Open on-screen (soft) input if requested by Dear ImGui
|
||||
static bool WantTextInputLast = false;
|
||||
if (io.WantTextInput && !WantTextInputLast)
|
||||
ShowSoftKeyboardInput();
|
||||
WantTextInputLast = io.WantTextInput;
|
||||
|
||||
// Start the Dear ImGui frame
|
||||
ImGui_ImplOpenGL3_NewFrame();
|
||||
ImGui_ImplAndroid_NewFrame();
|
||||
ImGui::NewFrame();
|
||||
|
||||
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
|
||||
if (show_demo_window)
|
||||
ImGui::ShowDemoWindow(&show_demo_window);
|
||||
|
||||
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
|
||||
{
|
||||
static float f = 0.0f;
|
||||
static int counter = 0;
|
||||
|
||||
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
|
||||
|
||||
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
|
||||
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
|
||||
ImGui::Checkbox("Another Window", &show_another_window);
|
||||
|
||||
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
|
||||
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
|
||||
|
||||
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
|
||||
counter++;
|
||||
ImGui::SameLine();
|
||||
ImGui::Text("counter = %d", counter);
|
||||
|
||||
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
// 3. Show another simple window.
|
||||
if (show_another_window)
|
||||
{
|
||||
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
|
||||
ImGui::Text("Hello from another window!");
|
||||
if (ImGui::Button("Close Me"))
|
||||
show_another_window = false;
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
// Rendering
|
||||
ImGui::Render();
|
||||
glViewport(0, 0, (int)io.DisplaySize.x, (int)io.DisplaySize.y);
|
||||
glClearColor(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
|
||||
glClear(GL_COLOR_BUFFER_BIT);
|
||||
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
|
||||
eglSwapBuffers(g_EglDisplay, g_EglSurface);
|
||||
}
|
||||
|
||||
void shutdown()
|
||||
{
|
||||
if (!g_Initialized)
|
||||
return;
|
||||
|
||||
// Cleanup
|
||||
ImGui_ImplOpenGL3_Shutdown();
|
||||
ImGui_ImplAndroid_Shutdown();
|
||||
ImGui::DestroyContext();
|
||||
|
||||
if (g_EglDisplay != EGL_NO_DISPLAY)
|
||||
{
|
||||
eglMakeCurrent(g_EglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
|
||||
|
||||
if (g_EglContext != EGL_NO_CONTEXT)
|
||||
eglDestroyContext(g_EglDisplay, g_EglContext);
|
||||
|
||||
if (g_EglSurface != EGL_NO_SURFACE)
|
||||
eglDestroySurface(g_EglDisplay, g_EglSurface);
|
||||
|
||||
eglTerminate(g_EglDisplay);
|
||||
}
|
||||
|
||||
g_EglDisplay = EGL_NO_DISPLAY;
|
||||
g_EglContext = EGL_NO_CONTEXT;
|
||||
g_EglSurface = EGL_NO_SURFACE;
|
||||
ANativeWindow_release(g_App->window);
|
||||
|
||||
g_Initialized = false;
|
||||
}
|
||||
|
||||
static void handleAppCmd(struct android_app* app, int32_t appCmd)
|
||||
{
|
||||
switch (appCmd)
|
||||
{
|
||||
case APP_CMD_SAVE_STATE:
|
||||
break;
|
||||
case APP_CMD_INIT_WINDOW:
|
||||
init(app);
|
||||
break;
|
||||
case APP_CMD_TERM_WINDOW:
|
||||
shutdown();
|
||||
break;
|
||||
case APP_CMD_GAINED_FOCUS:
|
||||
break;
|
||||
case APP_CMD_LOST_FOCUS:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static int32_t handleInputEvent(struct android_app* app, AInputEvent* inputEvent)
|
||||
{
|
||||
return ImGui_ImplAndroid_HandleInputEvent(inputEvent);
|
||||
}
|
||||
|
||||
void android_main(struct android_app* app)
|
||||
{
|
||||
app->onAppCmd = handleAppCmd;
|
||||
app->onInputEvent = handleInputEvent;
|
||||
|
||||
while (true)
|
||||
{
|
||||
int out_events;
|
||||
struct android_poll_source* out_data;
|
||||
|
||||
// Poll all events. If the app is not visible, this loop blocks until g_Initialized == true.
|
||||
while (ALooper_pollAll(g_Initialized ? 0 : -1, NULL, &out_events, (void**)&out_data) >= 0)
|
||||
{
|
||||
// Process one event
|
||||
if (out_data != NULL)
|
||||
out_data->process(app, out_data);
|
||||
|
||||
// Exit the app by returning from within the infinite loop
|
||||
if (app->destroyRequested != 0)
|
||||
{
|
||||
// shutdown() should have been called already while processing the
|
||||
// app command APP_CMD_TERM_WINDOW. But we play save here
|
||||
if (!g_Initialized)
|
||||
shutdown();
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Initiate a new frame
|
||||
tick();
|
||||
}
|
||||
}
|
||||
|
||||
// Unfortunately, there is no way to show the on-screen input from native code.
|
||||
// Therefore, we call ShowSoftKeyboardInput() of the main activity implemented in MainActivity.kt via JNI.
|
||||
static int ShowSoftKeyboardInput()
|
||||
{
|
||||
JavaVM* java_vm = g_App->activity->vm;
|
||||
JNIEnv* java_env = NULL;
|
||||
|
||||
jint jni_return = java_vm->GetEnv((void**)&java_env, JNI_VERSION_1_6);
|
||||
if (jni_return == JNI_ERR)
|
||||
return -1;
|
||||
|
||||
jni_return = java_vm->AttachCurrentThread(&java_env, NULL);
|
||||
if (jni_return != JNI_OK)
|
||||
return -2;
|
||||
|
||||
jclass native_activity_clazz = java_env->GetObjectClass(g_App->activity->clazz);
|
||||
if (native_activity_clazz == NULL)
|
||||
return -3;
|
||||
|
||||
jmethodID method_id = java_env->GetMethodID(native_activity_clazz, "showSoftInput", "()V");
|
||||
if (method_id == NULL)
|
||||
return -4;
|
||||
|
||||
java_env->CallVoidMethod(g_App->activity->clazz, method_id);
|
||||
|
||||
jni_return = java_vm->DetachCurrentThread();
|
||||
if (jni_return != JNI_OK)
|
||||
return -5;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Unfortunately, the native KeyEvent implementation has no getUnicodeChar() function.
|
||||
// Therefore, we implement the processing of KeyEvents in MainActivity.kt and poll
|
||||
// the resulting Unicode characters here via JNI and send them to Dear ImGui.
|
||||
static int PollUnicodeChars()
|
||||
{
|
||||
JavaVM* java_vm = g_App->activity->vm;
|
||||
JNIEnv* java_env = NULL;
|
||||
|
||||
jint jni_return = java_vm->GetEnv((void**)&java_env, JNI_VERSION_1_6);
|
||||
if (jni_return == JNI_ERR)
|
||||
return -1;
|
||||
|
||||
jni_return = java_vm->AttachCurrentThread(&java_env, NULL);
|
||||
if (jni_return != JNI_OK)
|
||||
return -2;
|
||||
|
||||
jclass native_activity_clazz = java_env->GetObjectClass(g_App->activity->clazz);
|
||||
if (native_activity_clazz == NULL)
|
||||
return -3;
|
||||
|
||||
jmethodID method_id = java_env->GetMethodID(native_activity_clazz, "pollUnicodeChar", "()I");
|
||||
if (method_id == NULL)
|
||||
return -4;
|
||||
|
||||
// Send the actual characters to Dear ImGui
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
jint unicode_character;
|
||||
while ((unicode_character = java_env->CallIntMethod(g_App->activity->clazz, method_id)) != 0)
|
||||
io.AddInputCharacter(unicode_character);
|
||||
|
||||
jni_return = java_vm->DetachCurrentThread();
|
||||
if (jni_return != JNI_OK)
|
||||
return -5;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Helper to retrieve data placed into the assets/ directory (android/app/src/main/assets)
|
||||
static int GetAssetData(const char* filename, void** outData)
|
||||
{
|
||||
int num_bytes = 0;
|
||||
AAsset* asset_descriptor = AAssetManager_open(g_App->activity->assetManager, filename, AASSET_MODE_BUFFER);
|
||||
if (asset_descriptor)
|
||||
{
|
||||
num_bytes = AAsset_getLength(asset_descriptor);
|
||||
*outData = IM_ALLOC(num_bytes);
|
||||
int64_t num_bytes_read = AAsset_read(asset_descriptor, *outData, num_bytes);
|
||||
AAsset_close(asset_descriptor);
|
||||
IM_ASSERT(num_bytes_read == num_bytes);
|
||||
}
|
||||
return num_bytes;
|
||||
}
|
@ -1,18 +0,0 @@
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface AppDelegate : UIResponder <UIApplicationDelegate>
|
||||
@property (strong, nonatomic) UIWindow *window;
|
||||
@end
|
||||
|
||||
#else
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@interface AppDelegate : NSObject <NSApplicationDelegate>
|
||||
@end
|
||||
|
||||
#endif
|
@ -1,11 +0,0 @@
|
||||
#import "AppDelegate.h"
|
||||
|
||||
@implementation AppDelegate
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender {
|
||||
return YES;
|
||||
}
|
||||
#endif
|
||||
|
||||
@end
|
@ -1,8 +0,0 @@
|
||||
#import <MetalKit/MetalKit.h>
|
||||
|
||||
@interface Renderer : NSObject <MTKViewDelegate>
|
||||
|
||||
-(nonnull instancetype)initWithView:(nonnull MTKView *)view;
|
||||
|
||||
@end
|
||||
|
@ -1,129 +0,0 @@
|
||||
#import "Renderer.h"
|
||||
#import <Metal/Metal.h>
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_metal.h"
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
#include "imgui_impl_osx.h"
|
||||
#endif
|
||||
|
||||
@interface Renderer ()
|
||||
@property (nonatomic, strong) id <MTLDevice> device;
|
||||
@property (nonatomic, strong) id <MTLCommandQueue> commandQueue;
|
||||
@end
|
||||
|
||||
@implementation Renderer
|
||||
|
||||
-(nonnull instancetype)initWithView:(nonnull MTKView *)view;
|
||||
{
|
||||
self = [super init];
|
||||
if(self)
|
||||
{
|
||||
_device = view.device;
|
||||
_commandQueue = [_device newCommandQueue];
|
||||
|
||||
IMGUI_CHECKVERSION();
|
||||
ImGui::CreateContext();
|
||||
ImGui::StyleColorsDark();
|
||||
|
||||
ImGui_ImplMetal_Init(_device);
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)drawInMTKView:(MTKView *)view
|
||||
{
|
||||
ImGuiIO &io = ImGui::GetIO();
|
||||
io.DisplaySize.x = view.bounds.size.width;
|
||||
io.DisplaySize.y = view.bounds.size.height;
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
CGFloat framebufferScale = view.window.screen.backingScaleFactor ?: NSScreen.mainScreen.backingScaleFactor;
|
||||
#else
|
||||
CGFloat framebufferScale = view.window.screen.scale ?: UIScreen.mainScreen.scale;
|
||||
#endif
|
||||
io.DisplayFramebufferScale = ImVec2(framebufferScale, framebufferScale);
|
||||
|
||||
io.DeltaTime = 1 / float(view.preferredFramesPerSecond ?: 60);
|
||||
|
||||
id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
|
||||
|
||||
static bool show_demo_window = true;
|
||||
static bool show_another_window = false;
|
||||
static float clear_color[4] = { 0.28f, 0.36f, 0.5f, 1.0f };
|
||||
|
||||
MTLRenderPassDescriptor *renderPassDescriptor = view.currentRenderPassDescriptor;
|
||||
if (renderPassDescriptor != nil)
|
||||
{
|
||||
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color[0], clear_color[1], clear_color[2], clear_color[3]);
|
||||
|
||||
// Here, you could do additional rendering work, including other passes as necessary.
|
||||
|
||||
id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
|
||||
[renderEncoder pushDebugGroup:@"ImGui demo"];
|
||||
|
||||
// Start the Dear ImGui frame
|
||||
ImGui_ImplMetal_NewFrame(renderPassDescriptor);
|
||||
#if TARGET_OS_OSX
|
||||
ImGui_ImplOSX_NewFrame(view);
|
||||
#endif
|
||||
ImGui::NewFrame();
|
||||
|
||||
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
|
||||
if (show_demo_window)
|
||||
ImGui::ShowDemoWindow(&show_demo_window);
|
||||
|
||||
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
|
||||
{
|
||||
static float f = 0.0f;
|
||||
static int counter = 0;
|
||||
|
||||
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
|
||||
|
||||
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
|
||||
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
|
||||
ImGui::Checkbox("Another Window", &show_another_window);
|
||||
|
||||
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
|
||||
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
|
||||
|
||||
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
|
||||
counter++;
|
||||
ImGui::SameLine();
|
||||
ImGui::Text("counter = %d", counter);
|
||||
|
||||
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
// 3. Show another simple window.
|
||||
if (show_another_window)
|
||||
{
|
||||
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
|
||||
ImGui::Text("Hello from another window!");
|
||||
if (ImGui::Button("Close Me"))
|
||||
show_another_window = false;
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
// Rendering
|
||||
ImGui::Render();
|
||||
ImDrawData *drawData = ImGui::GetDrawData();
|
||||
ImGui_ImplMetal_RenderDrawData(drawData, commandBuffer, renderEncoder);
|
||||
|
||||
[renderEncoder popDebugGroup];
|
||||
[renderEncoder endEncoding];
|
||||
|
||||
[commandBuffer presentDrawable:view.currentDrawable];
|
||||
}
|
||||
|
||||
[commandBuffer commit];
|
||||
}
|
||||
|
||||
- (void)mtkView:(MTKView *)view drawableSizeWillChange:(CGSize)size
|
||||
{
|
||||
}
|
||||
|
||||
@end
|
@ -1,19 +0,0 @@
|
||||
#import <Metal/Metal.h>
|
||||
#import <MetalKit/MetalKit.h>
|
||||
#import "Renderer.h"
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
|
||||
@interface ViewController : UIViewController
|
||||
@end
|
||||
|
||||
#else
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
@interface ViewController : NSViewController
|
||||
@end
|
||||
|
||||
#endif
|
@ -1,129 +0,0 @@
|
||||
#import "ViewController.h"
|
||||
#import "Renderer.h"
|
||||
#include "imgui.h"
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
#include "imgui_impl_osx.h"
|
||||
#endif
|
||||
|
||||
@interface ViewController ()
|
||||
@property (nonatomic, readonly) MTKView *mtkView;
|
||||
@property (nonatomic, strong) Renderer *renderer;
|
||||
@end
|
||||
|
||||
@implementation ViewController
|
||||
|
||||
- (MTKView *)mtkView {
|
||||
return (MTKView *)self.view;
|
||||
}
|
||||
|
||||
- (void)viewDidLoad
|
||||
{
|
||||
[super viewDidLoad];
|
||||
|
||||
self.mtkView.device = MTLCreateSystemDefaultDevice();
|
||||
|
||||
if (!self.mtkView.device) {
|
||||
NSLog(@"Metal is not supported");
|
||||
abort();
|
||||
}
|
||||
|
||||
self.renderer = [[Renderer alloc] initWithView:self.mtkView];
|
||||
|
||||
[self.renderer mtkView:self.mtkView drawableSizeWillChange:self.mtkView.bounds.size];
|
||||
|
||||
self.mtkView.delegate = self.renderer;
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
// Add a tracking area in order to receive mouse events whenever the mouse is within the bounds of our view
|
||||
NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect
|
||||
options:NSTrackingMouseMoved | NSTrackingInVisibleRect | NSTrackingActiveAlways
|
||||
owner:self
|
||||
userInfo:nil];
|
||||
[self.view addTrackingArea:trackingArea];
|
||||
|
||||
// If we want to receive key events, we either need to be in the responder chain of the key view,
|
||||
// or else we can install a local monitor. The consequence of this heavy-handed approach is that
|
||||
// we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our
|
||||
// window, we'd want to be much more careful than just ingesting the complete event stream, though we
|
||||
// do make an effort to be good citizens by passing along events when Dear ImGui doesn't want to capture.
|
||||
NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged | NSEventTypeScrollWheel;
|
||||
[NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event) {
|
||||
BOOL wantsCapture = ImGui_ImplOSX_HandleEvent(event, self.view);
|
||||
if (event.type == NSEventTypeKeyDown && wantsCapture) {
|
||||
return nil;
|
||||
} else {
|
||||
return event;
|
||||
}
|
||||
|
||||
}];
|
||||
|
||||
ImGui_ImplOSX_Init();
|
||||
#endif
|
||||
}
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
|
||||
- (void)mouseMoved:(NSEvent *)event {
|
||||
ImGui_ImplOSX_HandleEvent(event, self.view);
|
||||
}
|
||||
|
||||
- (void)mouseDown:(NSEvent *)event {
|
||||
ImGui_ImplOSX_HandleEvent(event, self.view);
|
||||
}
|
||||
|
||||
- (void)mouseUp:(NSEvent *)event {
|
||||
ImGui_ImplOSX_HandleEvent(event, self.view);
|
||||
}
|
||||
|
||||
- (void)mouseDragged:(NSEvent *)event {
|
||||
ImGui_ImplOSX_HandleEvent(event, self.view);
|
||||
}
|
||||
|
||||
- (void)scrollWheel:(NSEvent *)event {
|
||||
ImGui_ImplOSX_HandleEvent(event, self.view);
|
||||
}
|
||||
|
||||
#elif TARGET_OS_IOS
|
||||
|
||||
// This touch mapping is super cheesy/hacky. We treat any touch on the screen
|
||||
// as if it were a depressed left mouse button, and we don't bother handling
|
||||
// multitouch correctly at all. This causes the "cursor" to behave very erratically
|
||||
// when there are multiple active touches. But for demo purposes, single-touch
|
||||
// interaction actually works surprisingly well.
|
||||
- (void)updateIOWithTouchEvent:(UIEvent *)event {
|
||||
UITouch *anyTouch = event.allTouches.anyObject;
|
||||
CGPoint touchLocation = [anyTouch locationInView:self.view];
|
||||
ImGuiIO &io = ImGui::GetIO();
|
||||
io.MousePos = ImVec2(touchLocation.x, touchLocation.y);
|
||||
|
||||
BOOL hasActiveTouch = NO;
|
||||
for (UITouch *touch in event.allTouches) {
|
||||
if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled) {
|
||||
hasActiveTouch = YES;
|
||||
break;
|
||||
}
|
||||
}
|
||||
io.MouseDown[0] = hasActiveTouch;
|
||||
}
|
||||
|
||||
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
|
||||
[self updateIOWithTouchEvent:event];
|
||||
}
|
||||
|
||||
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
|
||||
[self updateIOWithTouchEvent:event];
|
||||
}
|
||||
|
||||
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
|
||||
[self updateIOWithTouchEvent:event];
|
||||
}
|
||||
|
||||
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
|
||||
[self updateIOWithTouchEvent:event];
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@end
|
||||
|
@ -1,22 +0,0 @@
|
||||
#import <TargetConditionals.h>
|
||||
|
||||
#if TARGET_OS_IPHONE
|
||||
|
||||
#import <UIKit/UIKit.h>
|
||||
#import "AppDelegate.h"
|
||||
|
||||
int main(int argc, char * argv[]) {
|
||||
@autoreleasepool {
|
||||
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
#import <Cocoa/Cocoa.h>
|
||||
|
||||
int main(int argc, const char * argv[]) {
|
||||
return NSApplicationMain(argc, argv);
|
||||
}
|
||||
|
||||
#endif
|
@ -1,28 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="14113" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="BV1-FR-VrT">
|
||||
<device id="retina4_7" orientation="portrait">
|
||||
<adaptation id="fullscreen"/>
|
||||
</device>
|
||||
<dependencies>
|
||||
<deployment identifier="iOS"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="14088"/>
|
||||
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
|
||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
<!--View Controller-->
|
||||
<scene sceneID="tXr-a1-R10">
|
||||
<objects>
|
||||
<viewController id="BV1-FR-VrT" customClass="ViewController" sceneMemberID="viewController">
|
||||
<view key="view" contentMode="scaleToFill" id="3se-qz-xqx" customClass="MTKView">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
<viewLayoutGuide key="safeArea" id="BKg-qs-eN0"/>
|
||||
</view>
|
||||
</viewController>
|
||||
<placeholder placeholderIdentifier="IBFirstResponder" id="SZV-WD-TEh" sceneMemberID="firstResponder"/>
|
||||
</objects>
|
||||
</scene>
|
||||
</scenes>
|
||||
</document>
|
Binary file not shown.
Before Width: | Height: | Size: 1.6 KiB |
@ -0,0 +1,356 @@
|
||||
// Dear ImGui: standalone example application for OSX + Metal.
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
#import <Cocoa/Cocoa.h>
|
||||
#else
|
||||
#import <UIKit/UIKit.h>
|
||||
#endif
|
||||
|
||||
#import <Metal/Metal.h>
|
||||
#import <MetalKit/MetalKit.h>
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_metal.h"
|
||||
#if TARGET_OS_OSX
|
||||
#include "imgui_impl_osx.h"
|
||||
@interface AppViewController : NSViewController
|
||||
@end
|
||||
#else
|
||||
@interface AppViewController : UIViewController
|
||||
@end
|
||||
#endif
|
||||
|
||||
@interface AppViewController () <MTKViewDelegate>
|
||||
@property (nonatomic, readonly) MTKView *mtkView;
|
||||
@property (nonatomic, strong) id <MTLDevice> device;
|
||||
@property (nonatomic, strong) id <MTLCommandQueue> commandQueue;
|
||||
@end
|
||||
|
||||
//-----------------------------------------------------------------------------------
|
||||
// AppViewController
|
||||
//-----------------------------------------------------------------------------------
|
||||
|
||||
@implementation AppViewController
|
||||
|
||||
-(instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil
|
||||
{
|
||||
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
|
||||
|
||||
_device = MTLCreateSystemDefaultDevice();
|
||||
_commandQueue = [_device newCommandQueue];
|
||||
|
||||
if (!self.device)
|
||||
{
|
||||
NSLog(@"Metal is not supported");
|
||||
abort();
|
||||
}
|
||||
|
||||
// Setup Dear ImGui context
|
||||
// FIXME: This example doesn't have proper cleanup...
|
||||
IMGUI_CHECKVERSION();
|
||||
ImGui::CreateContext();
|
||||
ImGuiIO& io = ImGui::GetIO(); (void)io;
|
||||
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
|
||||
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
|
||||
|
||||
// Setup Dear ImGui style
|
||||
ImGui::StyleColorsDark();
|
||||
//ImGui::StyleColorsClassic();
|
||||
|
||||
// Setup Renderer backend
|
||||
ImGui_ImplMetal_Init(_device);
|
||||
|
||||
// Load Fonts
|
||||
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
|
||||
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
|
||||
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
|
||||
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
|
||||
// - Read 'docs/FONTS.txt' for more instructions and details.
|
||||
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
|
||||
//io.Fonts->AddFontDefault();
|
||||
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
|
||||
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
|
||||
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
|
||||
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
|
||||
//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
|
||||
//IM_ASSERT(font != NULL);
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
-(MTKView *)mtkView
|
||||
{
|
||||
return (MTKView *)self.view;
|
||||
}
|
||||
|
||||
-(void)loadView
|
||||
{
|
||||
self.view = [[MTKView alloc] initWithFrame:CGRectMake(0, 0, 1200, 720)];
|
||||
}
|
||||
|
||||
-(void)viewDidLoad
|
||||
{
|
||||
[super viewDidLoad];
|
||||
|
||||
self.mtkView.device = self.device;
|
||||
self.mtkView.delegate = self;
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
// Add a tracking area in order to receive mouse events whenever the mouse is within the bounds of our view
|
||||
NSTrackingArea *trackingArea = [[NSTrackingArea alloc] initWithRect:NSZeroRect
|
||||
options:NSTrackingMouseMoved | NSTrackingInVisibleRect | NSTrackingActiveAlways
|
||||
owner:self
|
||||
userInfo:nil];
|
||||
[self.view addTrackingArea:trackingArea];
|
||||
|
||||
// If we want to receive key events, we either need to be in the responder chain of the key view,
|
||||
// or else we can install a local monitor. The consequence of this heavy-handed approach is that
|
||||
// we receive events for all controls, not just Dear ImGui widgets. If we had native controls in our
|
||||
// window, we'd want to be much more careful than just ingesting the complete event stream.
|
||||
// To match the behavior of other backends, we pass every event down to the OS.
|
||||
NSEventMask eventMask = NSEventMaskKeyDown | NSEventMaskKeyUp | NSEventMaskFlagsChanged;
|
||||
[NSEvent addLocalMonitorForEventsMatchingMask:eventMask handler:^NSEvent * _Nullable(NSEvent *event)
|
||||
{
|
||||
ImGui_ImplOSX_HandleEvent(event, self.view);
|
||||
return event;
|
||||
}];
|
||||
|
||||
ImGui_ImplOSX_Init();
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
-(void)drawInMTKView:(MTKView*)view
|
||||
{
|
||||
ImGuiIO& io = ImGui::GetIO();
|
||||
io.DisplaySize.x = view.bounds.size.width;
|
||||
io.DisplaySize.y = view.bounds.size.height;
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
CGFloat framebufferScale = view.window.screen.backingScaleFactor ?: NSScreen.mainScreen.backingScaleFactor;
|
||||
#else
|
||||
CGFloat framebufferScale = view.window.screen.scale ?: UIScreen.mainScreen.scale;
|
||||
#endif
|
||||
io.DisplayFramebufferScale = ImVec2(framebufferScale, framebufferScale);
|
||||
|
||||
io.DeltaTime = 1 / float(view.preferredFramesPerSecond ?: 60);
|
||||
|
||||
id<MTLCommandBuffer> commandBuffer = [self.commandQueue commandBuffer];
|
||||
|
||||
MTLRenderPassDescriptor* renderPassDescriptor = view.currentRenderPassDescriptor;
|
||||
if (renderPassDescriptor == nil)
|
||||
{
|
||||
[commandBuffer commit];
|
||||
return;
|
||||
}
|
||||
|
||||
// Start the Dear ImGui frame
|
||||
ImGui_ImplMetal_NewFrame(renderPassDescriptor);
|
||||
#if TARGET_OS_OSX
|
||||
ImGui_ImplOSX_NewFrame(view);
|
||||
#endif
|
||||
ImGui::NewFrame();
|
||||
|
||||
// Our state (make them static = more or less global) as a convenience to keep the example terse.
|
||||
static bool show_demo_window = true;
|
||||
static bool show_another_window = false;
|
||||
static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
|
||||
|
||||
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
|
||||
if (show_demo_window)
|
||||
ImGui::ShowDemoWindow(&show_demo_window);
|
||||
|
||||
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
|
||||
{
|
||||
static float f = 0.0f;
|
||||
static int counter = 0;
|
||||
|
||||
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
|
||||
|
||||
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
|
||||
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
|
||||
ImGui::Checkbox("Another Window", &show_another_window);
|
||||
|
||||
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
|
||||
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
|
||||
|
||||
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
|
||||
counter++;
|
||||
ImGui::SameLine();
|
||||
ImGui::Text("counter = %d", counter);
|
||||
|
||||
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
// 3. Show another simple window.
|
||||
if (show_another_window)
|
||||
{
|
||||
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
|
||||
ImGui::Text("Hello from another window!");
|
||||
if (ImGui::Button("Close Me"))
|
||||
show_another_window = false;
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
// Rendering
|
||||
ImGui::Render();
|
||||
ImDrawData* draw_data = ImGui::GetDrawData();
|
||||
|
||||
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w);
|
||||
id <MTLRenderCommandEncoder> renderEncoder = [commandBuffer renderCommandEncoderWithDescriptor:renderPassDescriptor];
|
||||
[renderEncoder pushDebugGroup:@"Dear ImGui rendering"];
|
||||
ImGui_ImplMetal_RenderDrawData(draw_data, commandBuffer, renderEncoder);
|
||||
[renderEncoder popDebugGroup];
|
||||
[renderEncoder endEncoding];
|
||||
|
||||
// Present
|
||||
[commandBuffer presentDrawable:view.currentDrawable];
|
||||
[commandBuffer commit];
|
||||
}
|
||||
|
||||
-(void)mtkView:(MTKView*)view drawableSizeWillChange:(CGSize)size
|
||||
{
|
||||
}
|
||||
|
||||
//-----------------------------------------------------------------------------------
|
||||
// Input processing
|
||||
//-----------------------------------------------------------------------------------
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
|
||||
// Forward Mouse/Keyboard events to Dear ImGui OSX backend.
|
||||
// Other events are registered via addLocalMonitorForEventsMatchingMask()
|
||||
-(void)mouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)rightMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)otherMouseDown:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)mouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)rightMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)otherMouseUp:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)mouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)mouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)rightMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)rightMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)otherMouseMoved:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)otherMouseDragged:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
-(void)scrollWheel:(NSEvent *)event { ImGui_ImplOSX_HandleEvent(event, self.view); }
|
||||
|
||||
#else
|
||||
|
||||
// This touch mapping is super cheesy/hacky. We treat any touch on the screen
|
||||
// as if it were a depressed left mouse button, and we don't bother handling
|
||||
// multitouch correctly at all. This causes the "cursor" to behave very erratically
|
||||
// when there are multiple active touches. But for demo purposes, single-touch
|
||||
// interaction actually works surprisingly well.
|
||||
-(void)updateIOWithTouchEvent:(UIEvent *)event
|
||||
{
|
||||
UITouch *anyTouch = event.allTouches.anyObject;
|
||||
CGPoint touchLocation = [anyTouch locationInView:self.view];
|
||||
ImGuiIO &io = ImGui::GetIO();
|
||||
io.MousePos = ImVec2(touchLocation.x, touchLocation.y);
|
||||
|
||||
BOOL hasActiveTouch = NO;
|
||||
for (UITouch *touch in event.allTouches)
|
||||
{
|
||||
if (touch.phase != UITouchPhaseEnded && touch.phase != UITouchPhaseCancelled)
|
||||
{
|
||||
hasActiveTouch = YES;
|
||||
break;
|
||||
}
|
||||
}
|
||||
io.MouseDown[0] = hasActiveTouch;
|
||||
}
|
||||
|
||||
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
|
||||
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
|
||||
-(void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
|
||||
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self updateIOWithTouchEvent:event]; }
|
||||
|
||||
#endif
|
||||
|
||||
@end
|
||||
|
||||
//-----------------------------------------------------------------------------------
|
||||
// AppDelegate
|
||||
//-----------------------------------------------------------------------------------
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
|
||||
@interface AppDelegate : NSObject <NSApplicationDelegate>
|
||||
@property (nonatomic, strong) NSWindow *window;
|
||||
@end
|
||||
|
||||
@implementation AppDelegate
|
||||
|
||||
-(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
|
||||
{
|
||||
return YES;
|
||||
}
|
||||
|
||||
-(instancetype)init
|
||||
{
|
||||
if (self = [super init])
|
||||
{
|
||||
NSViewController *rootViewController = [[AppViewController alloc] initWithNibName:nil bundle:nil];
|
||||
self.window = [[NSWindow alloc] initWithContentRect:NSZeroRect
|
||||
styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable | NSWindowStyleMaskMiniaturizable
|
||||
backing:NSBackingStoreBuffered
|
||||
defer:NO];
|
||||
self.window.contentViewController = rootViewController;
|
||||
[self.window orderFront:self];
|
||||
[self.window center];
|
||||
[self.window becomeKeyWindow];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#else
|
||||
|
||||
@interface AppDelegate : UIResponder <UIApplicationDelegate>
|
||||
@property (strong, nonatomic) UIWindow *window;
|
||||
@end
|
||||
|
||||
@implementation AppDelegate
|
||||
|
||||
-(BOOL)application:(UIApplication *)application
|
||||
didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey,id> *)launchOptions
|
||||
{
|
||||
UIViewController *rootViewController = [[AppViewController alloc] init];
|
||||
self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
|
||||
self.window.rootViewController = rootViewController;
|
||||
[self.window makeKeyAndVisible];
|
||||
return YES;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
#endif
|
||||
|
||||
//-----------------------------------------------------------------------------------
|
||||
// Application main() function
|
||||
//-----------------------------------------------------------------------------------
|
||||
|
||||
#if TARGET_OS_OSX
|
||||
|
||||
int main(int argc, const char * argv[])
|
||||
{
|
||||
return NSApplicationMain(argc, argv);
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
int main(int argc, char * argv[])
|
||||
{
|
||||
@autoreleasepool
|
||||
{
|
||||
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
@ -1,12 +0,0 @@
|
||||
|
||||
# How to Build
|
||||
|
||||
- You need to install Emscripten from https://emscripten.org/docs/getting_started/downloads.html, and have the environment variables set, as described in https://emscripten.org/docs/getting_started/downloads.html#installation-instructions
|
||||
|
||||
- Depending on your configuration, in Windows you may need to run `emsdk/emsdk_env.bat` in your console to access the Emscripten command-line tools.
|
||||
|
||||
- Then build using `make` while in the `example_emscripten/` directory.
|
||||
|
||||
- Note that Emscripten 1.39.0 (October 2019) obsoleted the `BINARYEN_TRAP_MODE=clamp` compilation flag which was required with version older than 1.39.0 to avoid rendering artefacts. See [#2877](https://github.com/ocornut/imgui/issues/2877) for details. If you use an older version, uncomment this line in the Makefile:
|
||||
|
||||
`#EMS += -s BINARYEN_TRAP_MODE=clamp`
|
@ -0,0 +1,88 @@
|
||||
#
|
||||
# Makefile to use with emscripten
|
||||
# See https://emscripten.org/docs/getting_started/downloads.html
|
||||
# for installation instructions.
|
||||
#
|
||||
# This Makefile assumes you have loaded emscripten's environment.
|
||||
# (On Windows, you may need to execute emsdk_env.bat or encmdprompt.bat ahead)
|
||||
#
|
||||
# Running `make` will produce three files:
|
||||
# - web/index.html (current stored in the repository)
|
||||
# - web/index.js
|
||||
# - web/index.wasm
|
||||
#
|
||||
# All three are needed to run the demo.
|
||||
|
||||
CC = emcc
|
||||
CXX = em++
|
||||
WEB_DIR = web
|
||||
EXE = $(WEB_DIR)/index.js
|
||||
IMGUI_DIR = ../..
|
||||
SOURCES = main.cpp
|
||||
SOURCES += $(IMGUI_DIR)/imgui.cpp $(IMGUI_DIR)/imgui_demo.cpp $(IMGUI_DIR)/imgui_draw.cpp $(IMGUI_DIR)/imgui_tables.cpp $(IMGUI_DIR)/imgui_widgets.cpp
|
||||
SOURCES += $(IMGUI_DIR)/backends/imgui_impl_glfw.cpp $(IMGUI_DIR)/backends/imgui_impl_wgpu.cpp
|
||||
OBJS = $(addsuffix .o, $(basename $(notdir $(SOURCES))))
|
||||
UNAME_S := $(shell uname -s)
|
||||
CPPFLAGS =
|
||||
LDFLAGS =
|
||||
EMS =
|
||||
|
||||
##---------------------------------------------------------------------
|
||||
## EMSCRIPTEN OPTIONS
|
||||
##---------------------------------------------------------------------
|
||||
|
||||
# ("EMS" options gets added to both CPPFLAGS and LDFLAGS, whereas some options are for linker only)
|
||||
EMS += -s DISABLE_EXCEPTION_CATCHING=1
|
||||
LDFLAGS += -s USE_GLFW=3 -s USE_WEBGPU=1
|
||||
LDFLAGS += -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s NO_EXIT_RUNTIME=0 -s ASSERTIONS=1
|
||||
|
||||
# Emscripten allows preloading a file or folder to be accessible at runtime.
|
||||
# The Makefile for this example project suggests embedding the misc/fonts/ folder into our application, it will then be accessible as "/fonts"
|
||||
# See documentation for more details: https://emscripten.org/docs/porting/files/packaging_files.html
|
||||
# (Default value is 0. Set to 1 to enable file-system and include the misc/fonts/ folder as part of the build.)
|
||||
USE_FILE_SYSTEM ?= 0
|
||||
ifeq ($(USE_FILE_SYSTEM), 0)
|
||||
LDFLAGS += -s NO_FILESYSTEM=1
|
||||
CPPFLAGS += -DIMGUI_DISABLE_FILE_FUNCTIONS
|
||||
endif
|
||||
ifeq ($(USE_FILE_SYSTEM), 1)
|
||||
LDFLAGS += --no-heap-copy --preload-file ../../misc/fonts@/fonts
|
||||
endif
|
||||
|
||||
##---------------------------------------------------------------------
|
||||
## FINAL BUILD FLAGS
|
||||
##---------------------------------------------------------------------
|
||||
|
||||
CPPFLAGS += -I$(IMGUI_DIR) -I$(IMGUI_DIR)/backends
|
||||
#CPPFLAGS += -g
|
||||
CPPFLAGS += -Wall -Wformat -Os $(EMS)
|
||||
#LDFLAGS += --shell-file shell_minimal.html
|
||||
LDFLAGS += $(EMS)
|
||||
|
||||
##---------------------------------------------------------------------
|
||||
## BUILD RULES
|
||||
##---------------------------------------------------------------------
|
||||
|
||||
%.o:%.cpp
|
||||
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
|
||||
|
||||
%.o:$(IMGUI_DIR)/%.cpp
|
||||
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
|
||||
|
||||
%.o:$(IMGUI_DIR)/backends/%.cpp
|
||||
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<
|
||||
|
||||
all: $(EXE)
|
||||
@echo Build complete for $(EXE)
|
||||
|
||||
$(WEB_DIR):
|
||||
mkdir $@
|
||||
|
||||
serve: all
|
||||
python3 -m http.server -d $(WEB_DIR)
|
||||
|
||||
$(EXE): $(OBJS) $(WEB_DIR)
|
||||
$(CXX) -o $@ $(OBJS) $(LDFLAGS)
|
||||
|
||||
clean:
|
||||
rm -f $(EXE) $(OBJS) $(WEB_DIR)/*.js $(WEB_DIR)/*.wasm $(WEB_DIR)/*.wasm.pre
|
@ -0,0 +1,10 @@
|
||||
|
||||
# How to Build
|
||||
|
||||
- You need to install Emscripten from https://emscripten.org/docs/getting_started/downloads.html, and have the environment variables set, as described in https://emscripten.org/docs/getting_started/downloads.html#installation-instructions
|
||||
|
||||
- Depending on your configuration, in Windows you may need to run `emsdk/emsdk_env.bat` in your console to access the Emscripten command-line tools.
|
||||
|
||||
- Then build using `make` while in the `example_emscripten_wgpu/` directory.
|
||||
|
||||
- Requires Emscripten 2.0.10 (December 2020) due to GLFW adaptations
|
@ -0,0 +1,245 @@
|
||||
// Dear ImGui: standalone example application for Emscripten, using GLFW + WebGPU
|
||||
// (Emscripten is a C++-to-javascript compiler, used to publish executables for the web. See https://emscripten.org/)
|
||||
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
|
||||
// Read online: https://github.com/ocornut/imgui/tree/master/docs
|
||||
|
||||
#include "imgui.h"
|
||||
#include "imgui_impl_glfw.h"
|
||||
#include "imgui_impl_wgpu.h"
|
||||
#include <stdio.h>
|
||||
#include <emscripten.h>
|
||||
#include <emscripten/html5.h>
|
||||
#include <emscripten/html5_webgpu.h>
|
||||
#include <GLFW/glfw3.h>
|
||||
#include <webgpu/webgpu.h>
|
||||
#include <webgpu/webgpu_cpp.h>
|
||||
|
||||
// Global WebGPU required states
|
||||
static WGPUDevice wgpu_device = NULL;
|
||||
static WGPUSurface wgpu_surface = NULL;
|
||||
static WGPUSwapChain wgpu_swap_chain = NULL;
|
||||
static int wgpu_swap_chain_width = 0;
|
||||
static int wgpu_swap_chain_height = 0;
|
||||
|
||||
// States tracked across render frames
|
||||
static bool show_demo_window = true;
|
||||
static bool show_another_window = false;
|
||||
static ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
|
||||
|
||||
// Forward declarations
|
||||
static bool init_wgpu();
|
||||
static void main_loop(void* window);
|
||||
static void print_glfw_error(int error, const char* description);
|
||||
static void print_wgpu_error(WGPUErrorType error_type, const char* message, void*);
|
||||
|
||||
int main(int, char**)
|
||||
{
|
||||
glfwSetErrorCallback(print_glfw_error);
|
||||
if (!glfwInit())
|
||||
return 1;
|
||||
|
||||
// Make sure GLFW does not initialize any graphics context.
|
||||
// This needs to be done explicitly later
|
||||
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
|
||||
|
||||
GLFWwindow* window = glfwCreateWindow(1280, 720, "Dear ImGui GLFW+WebGPU example", NULL, NULL);
|
||||
if (!window)
|
||||
{
|
||||
glfwTerminate();
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Initialize the WebGPU environment
|
||||
if (!init_wgpu())
|
||||
{
|
||||
if (window)
|
||||
glfwDestroyWindow(window);
|
||||
glfwTerminate();
|
||||
return 1;
|
||||
}
|
||||
glfwShowWindow(window);
|
||||
|
||||
// Setup Dear ImGui context
|
||||
IMGUI_CHECKVERSION();
|
||||
ImGui::CreateContext();
|
||||
ImGuiIO& io = ImGui::GetIO(); (void)io;
|
||||
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
|
||||
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
|
||||
|
||||
// For an Emscripten build we are disabling file-system access, so let's not attempt to do a fopen() of the imgui.ini file.
|
||||
// You may manually call LoadIniSettingsFromMemory() to load settings from your own storage.
|
||||
io.IniFilename = NULL;
|
||||
|
||||
// Setup Dear ImGui style
|
||||
ImGui::StyleColorsDark();
|
||||
//ImGui::StyleColorsClassic();
|
||||
|
||||
// Setup Platform/Renderer backends
|
||||
ImGui_ImplGlfw_InitForOther(window, true);
|
||||
ImGui_ImplWGPU_Init(wgpu_device, 3, WGPUTextureFormat_RGBA8Unorm);
|
||||
|
||||
// Load Fonts
|
||||
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
|
||||
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
|
||||
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
|
||||
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
|
||||
// - Read 'docs/FONTS.md' for more instructions and details.
|
||||
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
|
||||
// - Emscripten allows preloading a file or folder to be accessible at runtime. See Makefile for details.
|
||||
//io.Fonts->AddFontDefault();
|
||||
#ifndef IMGUI_DISABLE_FILE_FUNCTIONS
|
||||
io.Fonts->AddFontFromFileTTF("fonts/Roboto-Medium.ttf", 16.0f);
|
||||
//io.Fonts->AddFontFromFileTTF("fonts/Cousine-Regular.ttf", 15.0f);
|
||||
//io.Fonts->AddFontFromFileTTF("fonts/DroidSans.ttf", 16.0f);
|
||||
//io.Fonts->AddFontFromFileTTF("fonts/ProggyTiny.ttf", 10.0f);
|
||||
//ImFont* font = io.Fonts->AddFontFromFileTTF("fonts/ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
|
||||
//IM_ASSERT(font != NULL);
|
||||
#endif
|
||||
|
||||
// This function will directly return and exit the main function.
|
||||
// Make sure that no required objects get cleaned up.
|
||||
// This way we can use the browsers 'requestAnimationFrame' to control the rendering.
|
||||
emscripten_set_main_loop_arg(main_loop, window, 0, false);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static bool init_wgpu()
|
||||
{
|
||||
wgpu_device = emscripten_webgpu_get_device();
|
||||
if (!wgpu_device)
|
||||
return false;
|
||||
|
||||
wgpuDeviceSetUncapturedErrorCallback(wgpu_device, print_wgpu_error, NULL);
|
||||
|
||||
// Use C++ wrapper due to misbehavior in Emscripten.
|
||||
// Some offset computation for wgpuInstanceCreateSurface in JavaScript
|
||||
// seem to be inline with struct alignments in the C++ structure
|
||||
wgpu::SurfaceDescriptorFromCanvasHTMLSelector html_surface_desc = {};
|
||||
html_surface_desc.selector = "#canvas";
|
||||
|
||||
wgpu::SurfaceDescriptor surface_desc = {};
|
||||
surface_desc.nextInChain = &html_surface_desc;
|
||||
|
||||
// Use 'null' instance
|
||||
wgpu::Instance instance = {};
|
||||
wgpu_surface = instance.CreateSurface(&surface_desc).Release();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static void main_loop(void* window)
|
||||
{
|
||||
glfwPollEvents();
|
||||
|
||||
int width, height;
|
||||
glfwGetFramebufferSize((GLFWwindow*) window, &width, &height);
|
||||
|
||||
// React to changes in screen size
|
||||
if (width != wgpu_swap_chain_width && height != wgpu_swap_chain_height)
|
||||
{
|
||||
ImGui_ImplWGPU_InvalidateDeviceObjects();
|
||||
|
||||
if (wgpu_swap_chain)
|
||||
wgpuSwapChainRelease(wgpu_swap_chain);
|
||||
|
||||
wgpu_swap_chain_width = width;
|
||||
wgpu_swap_chain_height = height;
|
||||
|
||||
WGPUSwapChainDescriptor swap_chain_desc = {};
|
||||
swap_chain_desc.usage = WGPUTextureUsage_RenderAttachment;
|
||||
swap_chain_desc.format = WGPUTextureFormat_RGBA8Unorm;
|
||||
swap_chain_desc.width = width;
|
||||
swap_chain_desc.height = height;
|
||||
swap_chain_desc.presentMode = WGPUPresentMode_Fifo;
|
||||
wgpu_swap_chain = wgpuDeviceCreateSwapChain(wgpu_device, wgpu_surface, &swap_chain_desc);
|
||||
|
||||
ImGui_ImplWGPU_CreateDeviceObjects();
|
||||
}
|
||||
|
||||
// Start the Dear ImGui frame
|
||||
ImGui_ImplWGPU_NewFrame();
|
||||
ImGui_ImplGlfw_NewFrame();
|
||||
ImGui::NewFrame();
|
||||
|
||||
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
|
||||
if (show_demo_window)
|
||||
ImGui::ShowDemoWindow(&show_demo_window);
|
||||
|
||||
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
|
||||
{
|
||||
static float f = 0.0f;
|
||||
static int counter = 0;
|
||||
|
||||
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
|
||||
|
||||
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
|
||||
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
|
||||
ImGui::Checkbox("Another Window", &show_another_window);
|
||||
|
||||
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
|
||||
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
|
||||
|
||||
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
|
||||
counter++;
|
||||
ImGui::SameLine();
|
||||
ImGui::Text("counter = %d", counter);
|
||||
|
||||
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
// 3. Show another simple window.
|
||||
if (show_another_window)
|
||||
{
|
||||
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
|
||||
ImGui::Text("Hello from another window!");
|
||||
if (ImGui::Button("Close Me"))
|
||||
show_another_window = false;
|
||||
ImGui::End();
|
||||
}
|
||||
|
||||
// Rendering
|
||||
ImGui::Render();
|
||||
|
||||
WGPURenderPassColorAttachment color_attachments = {};
|
||||
color_attachments.loadOp = WGPULoadOp_Clear;
|
||||
color_attachments.storeOp = WGPUStoreOp_Store;
|
||||
color_attachments.clearColor = { clear_color.x * clear_color.w, clear_color.y * clear_color.w, clear_color.z * clear_color.w, clear_color.w };
|
||||
color_attachments.view = wgpuSwapChainGetCurrentTextureView(wgpu_swap_chain);
|
||||
WGPURenderPassDescriptor render_pass_desc = {};
|
||||
render_pass_desc.colorAttachmentCount = 1;
|
||||
render_pass_desc.colorAttachments = &color_attachments;
|
||||
render_pass_desc.depthStencilAttachment = NULL;
|
||||
|
||||
WGPUCommandEncoderDescriptor enc_desc = {};
|
||||
WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(wgpu_device, &enc_desc);
|
||||
|
||||
WGPURenderPassEncoder pass = wgpuCommandEncoderBeginRenderPass(encoder, &render_pass_desc);
|
||||
ImGui_ImplWGPU_RenderDrawData(ImGui::GetDrawData(), pass);
|
||||
wgpuRenderPassEncoderEndPass(pass);
|
||||
|
||||
WGPUCommandBufferDescriptor cmd_buffer_desc = {};
|
||||
WGPUCommandBuffer cmd_buffer = wgpuCommandEncoderFinish(encoder, &cmd_buffer_desc);
|
||||
WGPUQueue queue = wgpuDeviceGetQueue(wgpu_device);
|
||||
wgpuQueueSubmit(queue, 1, &cmd_buffer);
|
||||
}
|
||||
|
||||
static void print_glfw_error(int error, const char* description)
|
||||
{
|
||||
printf("Glfw Error %d: %s\n", error, description);
|
||||
}
|
||||
|
||||
static void print_wgpu_error(WGPUErrorType error_type, const char* message, void*)
|
||||
{
|
||||
const char* error_type_lbl = "";
|
||||
switch (error_type)
|
||||
{
|
||||
case WGPUErrorType_Validation: error_type_lbl = "Validation"; break;
|
||||
case WGPUErrorType_OutOfMemory: error_type_lbl = "Out of memory"; break;
|
||||
case WGPUErrorType_Unknown: error_type_lbl = "Unknown"; break;
|
||||
case WGPUErrorType_DeviceLost: error_type_lbl = "Device lost"; break;
|
||||
default: error_type_lbl = "Unknown";
|
||||
}
|
||||
printf("%s error: %s\n", error_type_lbl, message);
|
||||
}
|
@ -0,0 +1,80 @@
|
||||
<!doctype html>
|
||||
<html lang="en-us">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"/>
|
||||
<title>Dear ImGui Emscripten+WebGPU example</title>
|
||||
<style>
|
||||
body { margin: 0; background-color: black }
|
||||
.emscripten {
|
||||
position: absolute;
|
||||
top: 0px;
|
||||
left: 0px;
|
||||
margin: 0px;
|
||||
border: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
display: block;
|
||||
image-rendering: optimizeSpeed;
|
||||
image-rendering: -moz-crisp-edges;
|
||||
image-rendering: -o-crisp-edges;
|
||||
image-rendering: -webkit-optimize-contrast;
|
||||
image-rendering: optimize-contrast;
|
||||
image-rendering: crisp-edges;
|
||||
image-rendering: pixelated;
|
||||
-ms-interpolation-mode: nearest-neighbor;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()"></canvas>
|
||||
<script type='text/javascript'>
|
||||
var Module;
|
||||
(async () => {
|
||||
Module = {
|
||||
preRun: [],
|
||||
postRun: [],
|
||||
print: (function() {
|
||||
return function(text) {
|
||||
text = Array.prototype.slice.call(arguments).join(' ');
|
||||
console.log(text);
|
||||
};
|
||||
})(),
|
||||
printErr: function(text) {
|
||||
text = Array.prototype.slice.call(arguments).join(' ');
|
||||
console.error(text);
|
||||
},
|
||||
canvas: (function() {
|
||||
var canvas = document.getElementById('canvas');
|
||||
//canvas.addEventListener("webglcontextlost", function(e) { alert('FIXME: WebGL context lost, please reload the page'); e.preventDefault(); }, false);
|
||||
return canvas;
|
||||
})(),
|
||||
setStatus: function(text) {
|
||||
console.log("status: " + text);
|
||||
},
|
||||
monitorRunDependencies: function(left) {
|
||||
// no run dependencies to log
|
||||
}
|
||||
};
|
||||
window.onerror = function() {
|
||||
console.log("onerror: " + event);
|
||||
};
|
||||
|
||||
// Initialize the graphics adapter
|
||||
{
|
||||
const adapter = await navigator.gpu.requestAdapter();
|
||||
const device = await adapter.requestDevice();
|
||||
Module.preinitializedWebGPUDevice = device;
|
||||
}
|
||||
|
||||
{
|
||||
const js = document.createElement('script');
|
||||
js.async = true;
|
||||
js.src = "index.js";
|
||||
document.body.appendChild(js);
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
@ -1,3 +1,8 @@
|
||||
@REM Build for Visual Studio compiler. Run your copy of vcvars32.bat or vcvarsall.bat to setup command-line compiler.
|
||||
mkdir Debug
|
||||
cl /nologo /Zi /MD /I .. /I ..\.. /I ..\libs\glfw\include *.cpp ..\imgui_impl_opengl2.cpp ..\imgui_impl_glfw.cpp ..\..\imgui*.cpp /FeDebug/example_glfw_opengl2.exe /FoDebug/ /link /LIBPATH:..\libs\glfw\lib-vc2010-32 glfw3.lib opengl32.lib gdi32.lib shell32.lib
|
||||
@set OUT_DIR=Debug
|
||||
@set OUT_EXE=example_glfw_opengl2
|
||||
@set INCLUDES=/I..\.. /I..\..\backends /I..\libs\glfw\include
|
||||
@set SOURCES=main.cpp ..\..\backends\imgui_impl_opengl2.cpp ..\..\backends\imgui_impl_glfw.cpp ..\..\imgui*.cpp
|
||||
@set LIBS=/LIBPATH:..\libs\glfw\lib-vc2010-32 glfw3.lib opengl32.lib gdi32.lib shell32.lib
|
||||
mkdir %OUT_DIR%
|
||||
cl /nologo /Zi /MD %INCLUDES% %SOURCES% /Fe%OUT_DIR%/%OUT_EXE%.exe /Fo%OUT_DIR%/ /link %LIBS%
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue