From 82f0334f5dc49bb5b980169aa594780b5ab96231 Mon Sep 17 00:00:00 2001 From: Sylvain Calinon <sylvain.calinon@idiap.ch> Date: Thu, 6 Jul 2017 18:53:51 +0200 Subject: [PATCH] New release from sandbox --- CMakeLists.txt | 346 +- Makefile | 28 - README.md | 63 +- data/data_txyz.txt | 0 include/draw_utils.h | 297 + include/gfx.h | 178 + include/gfx3.h | 475 + include/gfx_ui.h | 142 + include/gfx_ui_config.h | 17 + include/gl2ps.h | 207 + include/imconfig.h | 58 + include/imgui.h | 1399 ++ include/imgui_impl_glfw.h | 29 + include/imgui_impl_glfw_gl3.h | 25 + include/imgui_internal.h | 760 ++ include/linmath.h | 571 + include/misc_utils.h | 71 + include/mpc_utils.h | 18 + {src => include}/stb_rect_pack.h | 46 +- {src => include}/stb_textedit.h | 144 +- {src => include}/stb_truetype.h | 947 +- src/demo_LQR_infHor.cpp | 358 + src/demo_MPC_batch_01.cpp | 344 + src/demo_MPC_iterative_01.cpp | 322 + src/demo_MPC_semitied_01.cpp | 402 + src/demo_MPC_velocity_01.cpp | 379 + src/demo_Riemannian_cov_interp02.cpp | 341 + src/demo_Riemannian_quat_infHorLQR.cpp | 518 + src/demo_Riemannian_sphere_infHorLQR.cpp | 823 ++ src/demo_dptpgmm.cpp | 566 + src/demo_glsl.cpp | 172 + src/demo_glsl_gfx.cpp | 165 + src/{pbdlib_gui.cpp => demo_online_gmm.cpp} | 17 +- src/demo_online_hsmm.cpp | 386 + src/demo_proMP01.cpp | 468 + src/demo_teleop.cpp | 568 + src/demo_tp_multiLqr.cpp | 1278 ++ src/demo_tp_trajMpc.cpp | 828 ++ src/gfx.cpp | 909 ++ src/gfx3.cpp | 1368 ++ src/gfx_ui.cpp | 1565 +++ src/gl2ps.c | 6181 +++++++++ src/imconfig.h | 55 - src/imgui.cpp | 12087 ++++++++---------- src/imgui.h | 1033 -- src/imgui_demo.cpp | 2617 ++++ src/imgui_draw.cpp | 2390 ++++ src/imgui_impl_glfw.cpp | 103 +- src/imgui_impl_glfw.h | 20 - src/imgui_impl_glfw_gl3.cpp | 400 + src/mpc_utils.cpp | 241 + 51 files changed, 34514 insertions(+), 8211 deletions(-) delete mode 100644 Makefile mode change 100644 => 100755 data/data_txyz.txt create mode 100644 include/draw_utils.h create mode 100644 include/gfx.h create mode 100644 include/gfx3.h create mode 100644 include/gfx_ui.h create mode 100644 include/gfx_ui_config.h create mode 100644 include/gl2ps.h create mode 100644 include/imconfig.h create mode 100644 include/imgui.h create mode 100644 include/imgui_impl_glfw.h create mode 100644 include/imgui_impl_glfw_gl3.h create mode 100644 include/imgui_internal.h create mode 100644 include/linmath.h create mode 100644 include/misc_utils.h create mode 100644 include/mpc_utils.h rename {src => include}/stb_rect_pack.h (91%) rename {src => include}/stb_textedit.h (89%) rename {src => include}/stb_truetype.h (76%) create mode 100644 src/demo_LQR_infHor.cpp create mode 100644 src/demo_MPC_batch_01.cpp create mode 100644 src/demo_MPC_iterative_01.cpp create mode 100644 src/demo_MPC_semitied_01.cpp create mode 100644 src/demo_MPC_velocity_01.cpp create mode 100644 src/demo_Riemannian_cov_interp02.cpp create mode 100644 src/demo_Riemannian_quat_infHorLQR.cpp create mode 100644 src/demo_Riemannian_sphere_infHorLQR.cpp create mode 100644 src/demo_dptpgmm.cpp create mode 100644 src/demo_glsl.cpp create mode 100644 src/demo_glsl_gfx.cpp rename src/{pbdlib_gui.cpp => demo_online_gmm.cpp} (96%) create mode 100644 src/demo_online_hsmm.cpp create mode 100644 src/demo_proMP01.cpp create mode 100644 src/demo_teleop.cpp create mode 100644 src/demo_tp_multiLqr.cpp create mode 100644 src/demo_tp_trajMpc.cpp create mode 100644 src/gfx.cpp create mode 100644 src/gfx3.cpp create mode 100644 src/gfx_ui.cpp create mode 100644 src/gl2ps.c delete mode 100644 src/imconfig.h delete mode 100644 src/imgui.h create mode 100644 src/imgui_demo.cpp create mode 100644 src/imgui_draw.cpp delete mode 100644 src/imgui_impl_glfw.h create mode 100644 src/imgui_impl_glfw_gl3.cpp create mode 100644 src/mpc_utils.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 2772a64..f305553 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,51 +1,345 @@ cmake_minimum_required(VERSION 2.8) + project(pbdlib_gui) -INCLUDE(CheckCXXCompilerFlag) -check_cxx_compiler_flag("-std=c++11" COMPILER_SUPPORTS_CXX11) -check_cxx_compiler_flag("-std=c++0x" COMPILER_SUPPORTS_CXX0X) -IF(COMPILER_SUPPORTS_CXX11) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -g") -ELSEIF(COMPILER_SUPPORTS_CXX0X) - SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") -ELSE() - MESSAGE(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.") -ENDIF() +set(CMAKE_MAJOR_VERSION 1) +set(CMAKE_MINOR_VERSION 0) +set(CMAKE_PATCH_VERSION 0) + +# Dependencies find_package(OpenGL REQUIRED) +find_package(Armadillo 5.4 REQUIRED) +find_library(EPOXY_LIB epoxy) +find_package(GLEW REQUIRED) + +set(PBDLIB_SEARCH_PATH /usr/local/lib/) +find_library(PBD_LIB pbd PATHS ${PBDLIB_SEARCH_PATH} + DOC "Path to the pbdlib library file" +) -FIND_PACKAGE(Armadillo 5.4 REQUIRED) -SET(CMAKE_MAJOR_VERSION 1) -SET(CMAKE_MINOR_VERSION 0) -SET(CMAKE_PATCH_VERSION 0) +set(PBD_LIB_INCLUDE_DIR "" CACHE STRING + "Path to the directory containing the 'pbdlib' one with the header files (only needed if PBD_LIB is manually specified)" +) -set(GLFWLIB_SEARCH_PATH /usr/lib/x86_64-linux-gnu/) -find_library(GLFW_LIB glfw ${GLFWLIB_SEARCH_PATH}) -#find_library(GLFW_LIB glfw3) +if(APPLE) + set(ARMADILLO_LIBRARIES + ${ARMADILLO_LIBRARIES} + lapack + blas) -set(PBDLIB_SEARCH_PATH /usr/local/lib/) -find_library(PBD_LIB pbd ${PBDLIB_SEARCH_PATH}) + include_directories( + /usr/local/include + ) + + link_directories( + /usr/local/Frameworks + /usr/local/lib + ) -INCLUDE_DIRECTORIES(include) -INCLUDE_DIRECTORIES(${ARMADILLO_INCLUDE_DIRS}) + set(GLFWLIB_SEARCH_PATH /usr/local/lib) + find_library(GLFW_LIB NAMES glfw3 glfw PATHS ${GLFWLIB_SEARCH_PATH}) + # Hack to include Mac frameworks + set(GLFW_LIB + ${GLFW_LIB} + "-framework CoreFoundation" + "-framework OpenGL" + "-framework Cocoa" + "-framework AppKit" + "-framework CoreVideo" + "-framework QTKit" + "-framework IOKit" + "-framework AGL" + "-framework GLUT" + ) + +elseif(UNIX) + + set(GLFWLIB_SEARCH_PATH /usr/lib/x86_64-linux-gnu/) + find_library(GLFW_LIB glfw PATHS ${GLFWLIB_SEARCH_PATH}) + +endif() + + +# Check compiler compatibility +include(CheckCXXCompilerFlag) +check_cxx_compiler_flag("-std=c++11" COMPILER_SUPPORTS_CXX11) +check_cxx_compiler_flag("-std=c++0x" COMPILER_SUPPORTS_CXX0X) +if(COMPILER_SUPPORTS_CXX11) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") +elseif(COMPILER_SUPPORTS_CXX0X) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") +else() + message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.") +endif() + + +# Setup the include directories include_directories( - include - ${PROJECT_SOURCE_DIR}/src/ + ${PROJECT_SOURCE_DIR}/include/ + ${PROJECT_SOURCE_DIR}/include/arpack-arma/include ${ARMADILLO_INCLUDE_DIRS} + ${PBD_LIB_INCLUDE_DIR} +) + + +# Executables +add_executable(demo_online_hsmm + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_online_hsmm.cpp +) +target_link_libraries(demo_online_hsmm + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} +) + +add_executable(demo_online_gmm + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_online_gmm.cpp +) +target_link_libraries(demo_online_gmm + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} +) + +add_executable(demo_tp_trajMpc + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_tp_trajMpc.cpp +) +target_link_libraries(demo_tp_trajMpc + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} +) + +add_executable(demo_tp_multiLqr + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_tp_multiLqr.cpp +) +target_link_libraries(demo_tp_multiLqr + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} +) + +add_executable(demo_dptpgmm + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_dptpgmm.cpp +) +target_link_libraries(demo_dptpgmm + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} +) + +add_executable(demo_LQR_infHor + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw_gl3.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/gfx3.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_LQR_infHor.cpp +) +target_link_libraries(demo_LQR_infHor + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${GLEW_LIBRARIES} + ${PBD_LIB} +) + +add_executable(demo_proMP01 + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw_gl3.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/gfx3.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_proMP01.cpp +) +target_link_libraries(demo_proMP01 + ${OPENGL_LIBRARIES} + ${GLEW_LIBRARIES} + ${GLFW_LIB} + ${ARMADILLO_LIBRARIES} + ${PBD_LIB} +) + +add_executable(demo_Riemannian_cov_interp02 + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/gfx.cpp + ${PROJECT_SOURCE_DIR}/src/demo_Riemannian_cov_interp02.cpp +) +target_link_libraries(demo_Riemannian_cov_interp02 + ${OPENGL_LIBRARIES} + ${GLEW_LIBRARIES} + ${GLFW_LIB} + ${ARMADILLO_LIBRARIES} + ${PBD_LIB} +) + +add_executable(demo_Riemannian_sphere_infHorLQR + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw_gl3.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/gfx3.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_Riemannian_sphere_infHorLQR.cpp +) +target_link_libraries(demo_Riemannian_sphere_infHorLQR + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLEW_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} +) + +add_executable(demo_Riemannian_quat_infHorLQR + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_Riemannian_quat_infHorLQR.cpp +) +target_link_libraries(demo_Riemannian_quat_infHorLQR + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} +) + +add_executable(demo_glsl + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/demo_glsl.cpp +) +target_link_libraries(demo_glsl + ${OPENGL_LIBRARIES} + ${EPOXY_LIB} + ${GLFW_LIB} + ${ARMADILLO_LIBRARIES} + ${PBD_LIB} +) + +add_executable(demo_glsl_gfx + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/gfx.cpp + ${PROJECT_SOURCE_DIR}/src/demo_glsl_gfx.cpp +) +target_link_libraries(demo_glsl_gfx + ${OPENGL_LIBRARIES} + ${GLEW_LIBRARIES} + ${GLFW_LIB} + ${ARMADILLO_LIBRARIES} + ${PBD_LIB} +) + +add_executable(demo_MPC_batch_01 + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_MPC_batch_01.cpp + ${PROJECT_SOURCE_DIR}/src/mpc_utils.cpp + ${PROJECT_SOURCE_DIR}/src/gl2ps.c +) + +target_link_libraries(demo_MPC_batch_01 + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} +) + +add_executable(demo_MPC_iterative_01 + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_MPC_iterative_01.cpp + ${PROJECT_SOURCE_DIR}/src/mpc_utils.cpp +) + +target_link_libraries(demo_MPC_iterative_01 + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} ) -add_executable(pbdlib_gui +add_executable(demo_MPC_velocity_01 ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp ${PROJECT_SOURCE_DIR}/src/imgui.cpp - ${PROJECT_SOURCE_DIR}/src/pbdlib_gui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_MPC_velocity_01.cpp + ${PROJECT_SOURCE_DIR}/src/mpc_utils.cpp + ${PROJECT_SOURCE_DIR}/src/gl2ps.c ) -target_link_libraries(pbdlib_gui +target_link_libraries(demo_MPC_velocity_01 ${OPENGL_LIBRARIES} ${ARMADILLO_LIBRARIES} ${GLFW_LIB} ${PBD_LIB} ) +add_executable(demo_MPC_semitied_01 + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/demo_MPC_semitied_01.cpp + ${PROJECT_SOURCE_DIR}/src/mpc_utils.cpp + ${PROJECT_SOURCE_DIR}/src/gl2ps.c +) +target_link_libraries(demo_MPC_semitied_01 + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} +) +add_executable(demo_teleop + ${PROJECT_SOURCE_DIR}/src/demo_teleop.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_impl_glfw.cpp + ${PROJECT_SOURCE_DIR}/src/imgui.cpp + ${PROJECT_SOURCE_DIR}/src/imgui_draw.cpp + ${PROJECT_SOURCE_DIR}/src/gfx_ui.cpp +) +target_link_libraries(demo_teleop + ${OPENGL_LIBRARIES} + ${ARMADILLO_LIBRARIES} + ${GLFW_LIB} + ${PBD_LIB} +) \ No newline at end of file diff --git a/Makefile b/Makefile deleted file mode 100644 index d18bd6e..0000000 --- a/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -#CXX = g++ - -OBJS = src/imgui_impl_glfw.o -OBJS += src/imgui.o -OBJS += src/pbdlib_gui.o - -LIBS = `pkg-config --static --libs glfw3` -LIBS += -L/usr/local/lib/ -lpbd -LIBS += -larmadillo - -CXXFLAGS = -Isrc/ `pkg-config --cflags glfw3` -CXXFLAGS += -I/usr/local/include -CXXFLAGS += -Wall -CFLAGS = $(CXXFLAGS) - -.cpp.o: - $(CXX) $(CXXFLAGS) -c -o $@ $< - -all:pbdlib_gui - @echo Build complete - -pbdlib_gui:$(OBJS) - $(CXX) -o pbdlib_gui $(OBJS) $(CXXFLAGS) $(LIBS) - -clean: - rm $(OBJS) - - diff --git a/README.md b/README.md index 2e69302..f21b24b 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,19 @@ -# Pbdlib minimalist GUI based on ImGui +# Pbdlib-sandbox minimalist GUI based on ImGui -This GUI is intended to be used with the pbdlib library available at https://gitlab.idiap.ch/rli/pbdlib +This GUI is intended to be used with the pbdlib-sandbox library available at +https://gitlab.idiap.ch/rli/pbdlib-sandbox -### Contact +### Contributors -Pbdlib_gui is currently maintained by Sylvain Calinon, Idiap Research Institute, http://idiap.ch/~scalinon/. It is based on ImGui, a Bloat-free Immediate Mode Graphical User interface for C++ with minimal dependencies, https://github.com/ocornut/imgui. ImGui is licensed under the MIT License, see LICENSE for more information. +Sylvain Calinon, Ioannis Havoutis, Ajay Tanwani, Emmanuel Pignat, Fabien Crepon, +Daniel Berio, Philip Abbet ### Prerequisite -The program can be compiled either with the available Makefile or with CMake. +The program requires glfw3 (modern lightweight and portable library for managing +OpenGL contexts, windows and inputs, similar to glut but better!). -It requires to be linked with the glfw3 library (modern lightweight and portable library for managing OpenGL contexts, windows and inputs, similar to glut but better!). +It also requires epoxy (OpenGL function pointer management library). ### Compilation @@ -22,13 +25,20 @@ cmake .. make ``` +### epoxy package install + +``` +sudo apt-get install libepoxy-dev +``` + ### glfw3 deb package install ``` -sudo apt-get install libglfw3-dev +sudo apt-get install libglfw3-dev ``` If libglfw3-dev is not available on your system, you can install it manually with: + ``` git clone https://github.com/glfw/glfw.git cd glfw @@ -36,14 +46,41 @@ mkdir build cd build cmake -DBUILD_SHARED_LIBS=ON ../ make -sudo make install ``` -**Note:** The `-DBUILD_SHARED_LIBS` is necessary otherwise cmake will create a static library. +**Note:** The `-DBUILD_SHARED_LIBS` is necessary otherwise cmake will create a +static library. ### Execution -The GUI can be run with -``` -./pbdlib_gui -``` +This project will build a number of executables, as listed below: + +- *demo_dptpgmm*: online tp-gmm learning and lqr-based trajectory generation. + +- *demo_glsl*: Minimalist example with glsl display + +- *demo_LQR_infHor*: Minimalist example of discrete infinite horizon linear + quadratic regulation. + +- *demo_online_gmm*: online gmm learning and lqr-based trajectory generation. + +- *demo_online_hsmm*: online hsmm learning and sampling with lqr-based trajectory + generation. + +- *demo_proMP01*: Conditioning on trajectory distributions with ProMP + +- *demo_Riemannian_cov_interp02*: Covariance interpolation on Riemannian manifold + from a GMM with augmented covariances. + +- *demo_Riemannian_sphere_infHorLQR*: Linear quadratic regulation on a sphere by + relying on Riemannian manifold and + infinite-horizon LQR. + +- *demo_teleop*: Example of online learning of tp-hsmm model and teleoperator-like + usage example. + +- *demo_tp_multiLqr*: online tp-hsmm and tp-gmm with lqr-based trajectory generation + and multiframe-lqr trajectory generation. + +- *demo_tp_trajMpc*: online tp-hsmm learning and trajMPC-based trajectory generation + when communication is cut. diff --git a/data/data_txyz.txt b/data/data_txyz.txt old mode 100644 new mode 100755 diff --git a/include/draw_utils.h b/include/draw_utils.h new file mode 100644 index 0000000..23b2c12 --- /dev/null +++ b/include/draw_utils.h @@ -0,0 +1,297 @@ +/* + * draw_utils.h + * + * Created on: 8 Mar 2016 + * Author: ihavoutis + */ + +#ifndef RLI_PBDLIB_GUI_SANDBOX_SRC_DRAW_UTILS_H_ +#define RLI_PBDLIB_GUI_SANDBOX_SRC_DRAW_UTILS_H_ + +#include <stdio.h> + +#include "armadillo" +#include <pbdlib/gmm.h> +#include <pbdlib/tpdpgmm.h> + +#include <GLFW/glfw3.h> +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include <pbdlib/gmr.h> +//#include <pbdlib/lqr.h> +#include <pbdlib/taskparameters.h> +//#include "pbdlib/trajMPC.h" + +#include "misc_utils.h" +#include <deque> + +using namespace std; +using namespace pbdlib; +using namespace arma; + +//plotting color +mat colorM = {{0.f,0.6211f,0.8164f}, + {0.9883f,0.4531f,0.f}, // orange + {0.7422f,0.8555f,0.2227f}, + {0.1211f,0.5391f,0.4375f}, + {0.9961f,0.8789f,0.1016f}}; +vec3 colBlack = {0.0, 0.0, 0.0}; +vec3 colRed = {1.0, 0.0, 0.0}; +vec3 colGreen = {0.0, 1.0, 0.0}; +vec3 colBRGreen = {0.0, 0.26, 0.14}; +vec3 colBlue = {0.0, 0.0, 1.0}; +vec3 colGray = {0.3f, 0.3f, 0.3f}; +vec3 colLightGray = {0.6f, 0.6f, 0.6f}; +vec3 colLightBlue = {0.53, 0.8, 0.98}; +vec3 colLightGreen = {0.56, 0.93, 0.56}; + +vector<vec3> colorCode; + +void drawStrip(mat points, vec3 color, float linewidth){ + glLineWidth(linewidth); + glColor3f(color[0], color[1], color[2]); + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)points.n_cols; t++){ + glVertex2f(points(0,t), points(1,t)); + } + glEnd(); +} + +void drawStrip(vector<mat> points, vec3 color, float linewidth){ + for (int n=0; n<(int)points.size(); n++){ + drawStrip(points[n],color,linewidth); + } +} + +void drawStrip(ImVector<ImVec2> &points, vec3 color, float linewidth){ + glLineWidth(linewidth); + glColor3f(color[0], color[1], color[2]); + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)points.size(); t++){ + glVertex2f(points[t].x, points[t].y); + } + glEnd(); +} + +void drawStrip(deque<vec> &points, int query_pt, vec offset, vec3 color, float linewidth){ + glLineWidth(linewidth); + glColor3f(color[0], color[1], color[2]); + glBegin(GL_LINE_STRIP); + for (int t=query_pt-1; t<(int)points.size(); t++){ + glVertex2f(points[t](0) + offset(0), points[t](1) + offset(1)); + } + glEnd(); +} + +void drawStrip(deque<vec> &points, int query_pt, vec3 color, float linewidth){ + glLineWidth(linewidth); + glColor3f(color[0], color[1], color[2]); + glBegin(GL_LINE_STRIP); + for (int t=query_pt-1; t<(int)points.size(); t++){ + glVertex2f(points[t](0), points[t](1)); + } + glEnd(); +} +void drawStrip(vector<vec> &points, vec3 color, float linewidth){ + glLineWidth(linewidth); + glColor3f(color[0], color[1], color[2]); + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)points.size(); t++){ + glVertex2f(points[t](0), points[t](1)); + } + glEnd(); +} + +void drawProdGaussians(TPDPGMM &tpgmm, vec color){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glColor3f(color(0), color(1), color(2)); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++){ + eig_sym(d, V, tpgmm.getProdGMM()->getSIGMA(i).rows(0,1).cols(0,1)); + R = V * sqrt(diagmat(d)); + pts = R * pts0; + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f((pts(0,t)+tpgmm.getProdGMM()->getMU(i)(0)), + (pts(1,t)+tpgmm.getProdGMM()->getMU(i)(1))); + } + glEnd(); + glBegin(GL_POINTS); + glVertex2f(tpgmm.getProdGMM()->getMU(i)(0), + tpgmm.getProdGMM()->getMU(i)(1)); + glEnd(); + } +} + +void drawGaussians(TPDPGMM &tpgmm, Ref refFrame[], mat colorM){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glLineWidth(2.0f); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++) { + for (int k = 0; k < (int) tpgmm.getNumFRAMES(); k++) { + + eig_sym(d, V, tpgmm.getGMMS(k).getSIGMA(i).rows(0,1).cols(0,1)); + R = refFrame[k].A*(V * sqrt(diagmat(d))); + pts = R * pts0; + + glColor3f(colorM(k+1,0), colorM(k+1,1), colorM(k+1,2)); + glBegin(GL_LINE_STRIP); + + vec refMU = refFrame[k].b + refFrame[k].A*tpgmm.getGMMS(k).getMU(i).rows(0,1); + + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f((pts(0, t) + refMU(0)), (pts(1, t) +refMU(1))); + } + glEnd(); + glBegin(GL_POINTS); + glVertex2f(refMU(0),refMU(1)); + glEnd(); + } + } +} + +void drawGaussians(TPDPGMM &tpgmm, Ref refFrame[], vector<vec3> colorM){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glLineWidth(2.0f); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++) { + for (int k = 0; k < (int) tpgmm.getNumFRAMES(); k++) { + + eig_sym(d, V, tpgmm.getGMMS(k).getSIGMA(i).rows(0,1).cols(0,1)); + R = refFrame[k].A*(V * sqrt(diagmat(d))); + pts = R * pts0; + + glColor3f(colorM[k](0), colorM[k](1), colorM[k](2)); + glBegin(GL_LINE_STRIP); + + vec refMU = refFrame[k].b + refFrame[k].A*tpgmm.getGMMS(k).getMU(i).rows(0,1); + + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f((pts(0, t) + refMU(0)), (pts(1, t) +refMU(1))); + } + glEnd(); + glBegin(GL_POINTS); + glVertex2f(refMU(0),refMU(1)); + glEnd(); + } + } +} + +void drawGaussians(TPGMM &tpgmm, Ref refFrame[], mat colorM){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glLineWidth(2.0f); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++) { + for (int k = 0; k < (int) tpgmm.getNumFRAMES(); k++) { + + eig_sym(d, V, tpgmm.getGMMS(k).getSIGMA(i).rows(0,1).cols(0,1)); + R = refFrame[k].A*(V * sqrt(diagmat(d))); + pts = R * pts0; + +// glColor3f(colorM(0), colorM(1), colorM(2)); + if (k==0){glColor3f(1.0, 0.0, 0.0);} + if (k==1){glColor3f(0.0, 0.0, 1.0);} + glBegin(GL_LINE_STRIP); + + vec refMU = refFrame[k].b + refFrame[k].A*tpgmm.getGMMS(k).getMU(i).rows(0,1); + + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f((pts(0, t) + refMU(0)), (pts(1, t) +refMU(1))); + } + glEnd(); + + glBegin(GL_POINTS); + glVertex2f(refMU(0),refMU(1)); + glEnd(); + } + } +} + + +void drawGaussians(vector<GaussianDistribution> &vGD, vec color){ + glLineWidth(1.0f); + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glColor3f(color(0), color(1), color(2)); + for (int i=0; i<(int)vGD.size(); i++){ + eig_sym(d, V, vGD[i].getSIGMA().rows(0,1).cols(0,1)); + R = V * sqrt(diagmat(d)); + pts = R * pts0; + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f((pts(0,t)+vGD[i].getMU()(0)), + (pts(1,t)+vGD[i].getMU()(1))); + } + glEnd(); + glBegin(GL_POINTS); + glVertex2f(vGD[i].getMU()(0), + vGD[i].getMU()(1)); + glEnd(); + } +} + +void drawGaussian(GaussianDistribution &vGD, vec color){ + glLineWidth(1.0f); + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glColor3f(color(0), color(1), color(2)); + eig_sym(d, V, vGD.getSIGMA().rows(0,1).cols(0,1)); + R = V * sqrt(diagmat(d)); + pts = R * pts0; + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f((pts(0,t)+vGD.getMU()(0)), + (pts(1,t)+vGD.getMU()(1))); + } + glEnd(); + glBegin(GL_POINTS); + glVertex2f(vGD.getMU()(0), + vGD.getMU()(1)); + glEnd(); +} + +//void drawSquare(int pos_x, int pos_y, int square_edge, float lineWidth = 5.0, +// vec col = vec({0.8f, 0.2f, 0.2f})){ +// glLineWidth(lineWidth); +// glBegin( GL_QUADS ); +//// glColor3f( 0.8f, 0.2f, 0.2f ); +// glColor3f(col(0), col(1), col(2)); +// int dot_w = square_edge/2; +// glVertex2f( pos_x - dot_w, pos_y - dot_w); +// glVertex2f( pos_x - dot_w, pos_y + dot_w); +// glVertex2f( pos_x + dot_w, pos_y + dot_w); +// glVertex2f( pos_x + dot_w, pos_y - dot_w); +// glEnd(); +//} + +void drawSquare(int pos_x, int pos_y, int square_edge, float lineWidth = 5.0, + vec col = vec({0.8f, 0.2f, 0.2f}), int filled = 1){ + glLineWidth(lineWidth); + if (filled) + glBegin( GL_QUADS ); + else + glBegin(GL_LINE_STRIP); +// glColor3f( 0.8f, 0.2f, 0.2f ); + glColor3f(col(0), col(1), col(2)); + int dot_w = square_edge/2; + glVertex2f( pos_x - dot_w, pos_y - dot_w); + glVertex2f( pos_x - dot_w, pos_y + dot_w); + glVertex2f( pos_x + dot_w, pos_y + dot_w); + glVertex2f( pos_x + dot_w, pos_y - dot_w); + glVertex2f( pos_x - dot_w, pos_y - dot_w); + glEnd(); +} + +#endif /* RLI_PBDLIB_GUI_SANDBOX_SRC_DRAW_UTILS_H_ */ diff --git a/include/gfx.h b/include/gfx.h new file mode 100644 index 0000000..fa52295 --- /dev/null +++ b/include/gfx.h @@ -0,0 +1,178 @@ +// Minimalist OpenGL utilities +// adapted from https://github.com/colormotor/colormotor + +#pragma once + +#include <stdio.h> +#include <stdarg.h> +#include <math.h> +#include <time.h> +#include <stdlib.h> +#include <string.h> +#include <assert.h> + +#include <iostream> +#include <vector> +#include <map> +#include <string> +#include <sstream> //for ostringsream +#include <iomanip> //for setprecision +#include <errno.h> +#include <functional> +#include <fstream> +#include <thread> +#include <complex> + +#include "armadillo" + +// Detect platform +#ifdef _WIN32 + #define GFX_WINDOWS + #include <windows.h> +#elif __APPLE__ + #define GFX_OSX +#elif __linux__ + #define GFX_LINUX +#elif __unix__ + #define GFX_LINUX +#elif defined(_POSIX_VERSION) + #define GFX_LINUX +#else + #error "Unknown platform" +#endif + +// GL includes +#ifdef GFX_WINDOWS + // NOT TESTED HERE + #include <windows.h> + #include <GL/glu.h> + #ifndef GL_CLAMP_TO_EDGE + #define GL_CLAMP_TO_EDGE 0x812F + #endif +#elif defined GFX_LINUX + #ifndef __glew_h__ + #define GL_GLEXT_PROTOTYPES + #include <GL/glew.h> + #include <GL/glu.h> + #include <GL/gl.h> + #include <GL/glx.h> + #endif +#elif defined GFX_OSX + #ifndef __glew_h__ + #define GL_GLEXT_PROTOTYPES + #include <GL/glew.h> + #endif + #include <OpenGL/glu.h> + #include <OpenGL/OpenGL.h> + #include <OpenGL/gl.h> + #include <OpenGL/glext.h> +#endif + +namespace gfx +{ + +void init(); + +int checkGlExtension(char const *name); + +////////////////////////////////////////////////// +/// Projections/view/transformations +//@{ +/// Returns a perspective projection matrix +arma::fmat perspective(float fovy, float aspect, float zNear, float zFar); +/// Sets perspective projection (as in MESA standard) +void setPerspectiveProjection(float fovy, float aspect, float zNear, float zFar); +/// Set orthographic projection with origin at (0,0) top-left +void setOrtho( float w, float h ); +/// Wrapper around glMultMatrix with armadillo matrices +/// handles 2d and 3d affine matrices (3x3 and 4x4) +void multMatrix( const arma::mat& mat ); +/// Returns a view (or camera) matrix +arma::fmat lookAt(const arma::fvec& position, const arma::fvec& target, const arma::fvec& up); +/// Returns a rotation matrix for the provided axis and angle +arma::fmat rotate(const arma::fvec& axis, float angle); +//@} + +////////////////////////////////////////////////// +/// Drawing +//@{ +/// Draw a 2d quad providing texture coordinates (u,v) +void drawUVQuad( float x , float y , float w , float h, float maxU=0.0f, float maxV=1.0f, bool flip=true ); +/// Draw a 2d quad +void drawQuad( float x, float y, float w, float h ); +/// Draw a line between a and b +void drawLine( const arma::vec& a, const arma::vec& b ); +/// draw a set of points (columns of the matrix) with a given GL primitive defined with @prim, +/// e.g. GL_LINE_STRIP, GL_LINE_LOOP, GL_POINTS +void draw( const arma::mat & P, int prim=GL_LINE_STRIP ); +/// Draw 3d axes defined by a 4x4 matrix (have to test here) +void drawAxis( const arma::mat& mat, float scale ); +//@} + +////////////////////////////////////// +/// Shader interface (needs further testing) +//@{ +/// Convert to string (handy to create a shader, but messes up line numbers, which makes it tricky with errors) +#define STRINGIFY( expr ) #expr + +void removeShader( int id ); +void deleteShaderProgram( int id ); +void deleteAllShaders(); + +void setShaderVersion( const std::string& version ); + +int loadShader( const std::string& vs, const std::string& ps ); +int reloadShader( int id, const std::string& vs, const std::string& ps ); +std::string shaderString( const std::string& path ); +bool setTexture( const std::string& handle, int sampler ); +void bindShader( int id ); +void unbindShader(); + +bool setInt( const std::string& handle, int v ); +bool setBool( const std::string& handle, bool v ); +bool setVector( const std::string& handle, const arma::vec& v ); +bool setMatrix( const std::string& handle, const arma::mat& v ); +//@} + +////////////////////////////////////// +/// Texture interface +/// Example combinations of parameters: +/// { GL_RGB8, GL_BGR, GL_UNSIGNED_BYTE,3 }, //R8G8B8, +/// { GL_RGBA8, GL_BGRA, GL_UNSIGNED_BYTE,4 }, //A8R8G8B8 +/// { GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE,1 }, //L8, +//@{ +int createTexture(int w, int h, int glFormat=GL_RGB8, int dataFormat=GL_BGRA, int dataType=GL_UNSIGNED_BYTE ); +int createTexture(void* data, int w, int h, int glFormat=GL_RGB8, int dataFormat=GL_BGRA, int dataType=GL_UNSIGNED_BYTE ); +void bindTexture( int id, int sampler=0 ); +void unbindTexture( int sampler=0 ); +void grabFrameBuffer( int texId, int w, int h ); +//@} + +} // end gfx + + +////////////////////////////////////// +// OpenGL transformation matrix utils + +/// 3d transformations, when @affine is set to true a 4x4 matrix is created to handle homogeneous coords +//@{ +arma::mat rotX3d( double theta, bool affine=true ); +arma::mat rotY3d( double theta, bool affine=true ); +arma::mat rotZ3d( double theta, bool affine=true ); +arma::mat trans3d( const arma::vec& xyz ); +arma::mat trans3d( double x, double y, double z ); +arma::mat scaling3d( const arma::vec& xyz, bool affine=true ); +arma::mat scaling3d( double s, bool affine=true ); +arma::mat scaling3d( double x, double y, double z, bool affine=true ); +//@} + +////////////////////////////////////// +/// 2d transformations, when @affine is set to true a 3x3 matrix is created to handle homogeneous coords +//@{ +arma::mat rot2d( double theta, bool affine=true ); +arma::mat trans2d( const arma::vec& xy, bool affine=true ); +arma::mat trans2d( double x, double y, bool affine=true ); +arma::mat scaling2d( const arma::vec& xy, bool affine=true ); +arma::mat scaling2d( double s, bool affine=true ); +arma::mat scaling2d( double x, double y, bool affine=true ); +//@} diff --git a/include/gfx3.h b/include/gfx3.h new file mode 100644 index 0000000..f37d304 --- /dev/null +++ b/include/gfx3.h @@ -0,0 +1,475 @@ +/* + * gfx3.h + * + * Rendering utility structures and functions based on OpenGL 3.3+ + * + * Authors: Philip Abbet + */ + +#pragma once + +#define ARMA_DONT_PRINT_ERRORS +#include <armadillo> +#include <map> + +// Detect the platform +#ifdef _WIN32 + #define GFX_WINDOWS + #include <windows.h> +#elif __APPLE__ + #define GFX_OSX +#elif __linux__ || __unix__ || defined(_POSIX_VERSION) + #define GFX_LINUX +#else + #error "Unknown platform" +#endif + +// OpenGL includes +#ifdef GFX_WINDOWS + // NOT TESTED HERE + #include <windows.h> + #include <GL/glu.h> + #ifndef GL_CLAMP_TO_EDGE + #define GL_CLAMP_TO_EDGE 0x812F + #endif +#elif defined GFX_LINUX + #ifndef __glew_h__ + #define GL_GLEXT_PROTOTYPES + #include <GL/glew.h> + #include <GL/glu.h> + #include <GL/gl.h> + #include <GL/glx.h> + #endif +#elif defined GFX_OSX + #ifndef __glew_h__ + #define GL_GLEXT_PROTOTYPES + #include <GL/glew.h> + #endif + #include <OpenGL/glu.h> + #include <OpenGL/OpenGL.h> + #include <OpenGL/gl.h> + #include <OpenGL/glext.h> +#endif + + + +namespace gfx3 +{ + /**************************** UTILITY FUNCTIONS **************************/ + + //------------------------------------------------------------------------- + // Initialisations + //------------------------------------------------------------------------- + void init(); + + //------------------------------------------------------------------------- + // Convert radian to degrees + //------------------------------------------------------------------------- + double deg2rad(double deg); + + //------------------------------------------------------------------------- + // Returns the sinus of an angle in degrees + //------------------------------------------------------------------------- + double sin_deg(double deg); + + //------------------------------------------------------------------------- + // Returns the cosinus of an angle in degrees + //------------------------------------------------------------------------- + double cos_deg(double deg); + + //------------------------------------------------------------------------- + // Indicates if two values are close enough + //------------------------------------------------------------------------- + bool is_close(float a, float b, float epsilon = 1e-6f); + + //------------------------------------------------------------------------- + // Converts some coordinates from UI-space to OpenGL-space + // + // UI coordinates range from (0, 0) to (win_width, win_height) + // OpenGL coordinates range from (-fb_width / 2, fb_height / 2) to + // (fb_width / 2, -fb_height / 2) + //------------------------------------------------------------------------- + arma::vec ui2fb(const arma::vec& coords, int win_width, int win_height, + int fb_width, int fb_height); + + //------------------------------------------------------------------------- + // Converts some coordinates from OpenGL-space to UI-space + // + // OpenGL coordinates range from (-fb_width / 2, fb_height / 2) to + // (fb_width / 2, -fb_height / 2) + // UI coordinates range from (0, 0) to (win_width, win_height) + //------------------------------------------------------------------------- + arma::vec fb2ui(const arma::vec& coords, int win_width, int win_height, + int fb_width, int fb_height); + + //------------------------------------------------------------------------- + // Converts some coordinates from UI-space to shader-space + // + // UI coordinates range from (0, 0) to (win_width, win_height) + // Shader coordinates range from (sh_left, sh_top) to (sh_right, sh_bottom) + // by default: (-1, 1) to (1, -1) + //------------------------------------------------------------------------- + arma::vec ui2shader(const arma::vec& coords, int win_width, int win_height, + int fb_width, int fb_height, float sh_left = -1.0f, + float sh_top = 1.0f, float sh_right = 1.0f, + float sh_bottom = -1.0f); + + + /*********************** PROJECTION & VIEW MATRICES **********************/ + + //------------------------------------------------------------------------- + // Returns a perspective projection matrix + //------------------------------------------------------------------------- + arma::fmat perspective(float fovy, float aspect, float zNear, float zFar); + + //------------------------------------------------------------------------- + // Returns a orthographic projection matrix + //------------------------------------------------------------------------- + arma::fmat orthographic(float width, float height, float zNear, float zFar); + + //------------------------------------------------------------------------- + // Returns a view matrix + //------------------------------------------------------------------------- + arma::fmat lookAt(const arma::fvec& position, const arma::fvec& target, + const arma::fvec& up); + + + /**************************** TRANSFORMATIONS ****************************/ + + //------------------------------------------------------------------------- + // Holds all the transformations needed for a 3D entity + // + // Can be organised in a hierarchy, where the parent transforms affect the + // children ones + //------------------------------------------------------------------------- + struct transforms_t { + + // Constructor + transforms_t() : parent(0) {} + + transforms_t* parent; + + arma::fvec position; + arma::fmat rotation; + }; + + //------------------------------------------------------------------------- + // Returns a rotation matrix given an axis and an angle (in radian) + //------------------------------------------------------------------------- + arma::fmat rotate(const arma::fvec& axis, float angle); + + //------------------------------------------------------------------------- + // Returns the rotation matrix to go from one direction to another one + //------------------------------------------------------------------------- + arma::fmat rotation(const arma::fvec& from, const arma::fvec& to); + + //------------------------------------------------------------------------- + // Compute the translation and rotation to apply to a list of 3D points A to + // obtain the list of 3D points B. + // + // Points are organised in columns: + // [ x0 x1 x2 ... + // y0 y1 y2 + // z0 z1 z2 ] + //------------------------------------------------------------------------- + void rigid_transform_3D(const arma::fmat& A, const arma::fmat& B, + arma::fmat &rotation, arma::fvec &translation); + + //------------------------------------------------------------------------- + // Returns the full world transformation matrix corresponding to the given + // transforms structure, taking all its parent hierarchy into account + //------------------------------------------------------------------------- + arma::fmat worldTransforms(const transforms_t* transforms); + + //------------------------------------------------------------------------- + // Returns the full world position corresponding to the given transforms + // structure, taking all its parent hierarchy into account + //------------------------------------------------------------------------- + arma::fvec worldPosition(const transforms_t* transforms); + + //------------------------------------------------------------------------- + // Returns the full world rotation matrix corresponding to the given + // transforms structure, taking all its parent hierarchy into account + //------------------------------------------------------------------------- + arma::fmat worldRotation(const transforms_t* transforms); + + + /******************************** SHADERS ********************************/ + + struct shader_fmat_uniform_t { + GLint handle; + arma::fmat value; + }; + + + struct shader_fvec_uniform_t { + GLint handle; + arma::fvec value; + }; + + + struct shader_float_uniform_t { + GLint handle; + float value; + }; + + + struct shader_bool_uniform_t { + GLint handle; + bool value; + }; + + + //------------------------------------------------------------------------- + // Holds all the needed informations about a GLSL program + //------------------------------------------------------------------------- + struct shader_t { + GLuint id; + + bool use_lightning; + + // Matrices + GLint model_matrix_handle; + GLint view_matrix_handle; + GLint projection_matrix_handle; + + // Material + GLint ambiant_color_handle; // valid if lightning is used + GLint diffuse_color_handle; + GLint specular_color_handle; // valid if lightning is used + GLint specular_power_handle; // valid if lightning is used + + // Textures + GLint diffuse_texture_handle; // valid if textures are used + + // Light + GLint light_position_handle; // valid if lightning is used + GLint light_color_handle; // valid if lightning is used + GLint light_power_handle; // valid if lightning is used + + // RTT-specific + GLint backbuffer_handle; + + // Application-dependant uniforms + std::map<std::string, shader_fmat_uniform_t> fmat_uniforms; + std::map<std::string, shader_fvec_uniform_t> fvec_uniforms; + std::map<std::string, shader_float_uniform_t> float_uniforms; + std::map<std::string, shader_bool_uniform_t> bool_uniforms; + + void setUniform(const std::string& name, const arma::fmat& value); + void setUniform(const std::string& name, const arma::mat& value); + void setUniform(const std::string& name, const arma::fvec& value); + void setUniform(const std::string& name, const arma::vec& value); + void setUniform(const std::string& name, float value); + void setUniform(const std::string& name, bool value); + }; + + + //------------------------------------------------------------------------- + // Convert to string (handy to create a shader, but messes up line numbers, + // which makes it tricky with errors) + //------------------------------------------------------------------------- + #define STRINGIFY( expr ) #expr + + //------------------------------------------------------------------------- + // Load and compile a vertex and a fragment shaders into a GLSL program + //------------------------------------------------------------------------- + shader_t loadShader(const std::string& vertex_shader, + const std::string& fragment_shader, + const std::string& version = "330 core"); + + //------------------------------------------------------------------------- + // Vertex and fragment shaders for a mesh with normals and one point light + // source + //------------------------------------------------------------------------- + extern const char* VERTEX_SHADER_ONE_LIGHT; + extern const char* FRAGMENT_SHADER_ONE_LIGHT; + + //------------------------------------------------------------------------- + // Vertex and fragment shaders without any lightning + //------------------------------------------------------------------------- + extern const char* VERTEX_SHADER_COLORED; + extern const char* FRAGMENT_SHADER_COLORED; + + //------------------------------------------------------------------------- + // Vertex and fragment shaders with a texture, without any lightning + //------------------------------------------------------------------------- + extern const char* VERTEX_SHADER_TEXTURED; + extern const char* FRAGMENT_SHADER_ONE_TEXTURE; + + //------------------------------------------------------------------------- + // Vertex and fragment shaders to do render-to-texture + //------------------------------------------------------------------------- + extern const char* RTT_VERTEX_SHADER; + extern const char* RTT_FRAGMENT_SHADER_GAUSSIAN; + extern const char* RTT_FRAGMENT_SHADER_LIC; + + + /******************************* LIGHTNING *******************************/ + + //------------------------------------------------------------------------- + // Holds all the needed informations about a point light + //------------------------------------------------------------------------- + struct point_light_t { + transforms_t transforms; + arma::fvec color; + float power; + }; + + //------------------------------------------------------------------------- + // A list of lights + //------------------------------------------------------------------------- + typedef std::vector<point_light_t> light_list_t; + + + /*************************** RENDER-TO-TEXTURE ***************************/ + + struct render_to_texture_buffer_t { + GLuint framebuffer; + GLuint texture; + }; + + struct render_to_texture_t { + + // Textures + render_to_texture_buffer_t buffers[2]; + unsigned int nb_buffers; + unsigned int current_buffer; + unsigned int width; + unsigned int height; + + // Rectangular mesh + GLuint nb_vertices; + GLuint vertex_buffer; + + // Shader + shader_t const* shader; + + inline GLuint texture() const { + return buffers[current_buffer].texture; + }; + + inline GLuint previous_texture() const { + unsigned int previous_buffer = current_buffer + 1; + if (previous_buffer >= nb_buffers) + previous_buffer = 0; + + return buffers[previous_buffer].texture; + }; + }; + + //------------------------------------------------------------------------- + // Create a render-to-texture object + //------------------------------------------------------------------------- + render_to_texture_t createRTT(const shader_t& shader, unsigned int width, + unsigned int height, const arma::fvec& color); + + //------------------------------------------------------------------------- + // Render a render-to-texture object + //------------------------------------------------------------------------- + bool draw(render_to_texture_t &rtt); + + + /********************************* MESHES ********************************/ + + //------------------------------------------------------------------------- + // Holds all the needed informations about a mesh + //------------------------------------------------------------------------- + struct model_t { + GLenum mode; + + // Vertex data + GLuint nb_vertices; + GLuint vertex_buffer; + GLuint normal_buffer; + GLuint uv_buffer; + + // Transforms + transforms_t transforms; + + // Shader + shader_t const* shader; + + // Material + arma::fvec ambiant_color; + arma::fvec diffuse_color; + arma::fvec specular_color; + float specular_power; + + // Textures + GLuint diffuse_texture; + }; + + //------------------------------------------------------------------------- + // Render a mesh + //------------------------------------------------------------------------- + bool draw(const model_t& model, const arma::fmat& view, + const arma::fmat& projection, + const light_list_t& lights); + + //------------------------------------------------------------------------- + // Render a mesh (shortcut when lights aren't used by the shaders) + //------------------------------------------------------------------------- + inline bool draw(const model_t& model, const arma::fmat& view, + const arma::fmat& projection) + { + light_list_t lights; + return draw(model, view, projection, lights); + } + + //------------------------------------------------------------------------- + // Create a rectangular mesh, colored (no lightning) + //------------------------------------------------------------------------- + model_t create_rectangle(const shader_t& shader, const arma::fvec& color, + float width, float height); + + //------------------------------------------------------------------------- + // Create a square mesh, colored (no lightning) + //------------------------------------------------------------------------- + model_t create_square(const shader_t& shader, const arma::fvec& color, + float size); + + //------------------------------------------------------------------------- + // Create a sphere mesh, either colored or that can be lighted (it depends + // on the shader) + //------------------------------------------------------------------------- + model_t create_sphere(const shader_t& shader, float radius = 1.0f); + + //------------------------------------------------------------------------- + // Create a line mesh, colored (no lightning), from a matrix containing the + // point coordinates + //------------------------------------------------------------------------- + model_t create_line(const shader_t& shader, const arma::fvec& color, + const arma::mat& points); + + //------------------------------------------------------------------------- + // Create a line mesh, colored (no lightning), from an array containing the + // point coordinates + //------------------------------------------------------------------------- + model_t create_line(const shader_t& shader, const arma::fvec& color, + const std::vector<arma::vec>& points); + + //------------------------------------------------------------------------- + // Release the OpenGL resources used by the model + //------------------------------------------------------------------------- + void destroy(const model_t& model); + + + /****************************** RAY CASTING ******************************/ + + //------------------------------------------------------------------------- + // Represents a 3D ray (in world coordinates) + //------------------------------------------------------------------------- + struct ray_t { + arma::fvec origin; + arma::fvec direction; + }; + + ray_t create_ray(const arma::fvec& origin, int mouse_x, int mouse_y, + const arma::fmat& view, const arma::fmat& projection, + int window_width, int window_height); + + bool intersects(const ray_t& ray, const arma::fvec& center, float radius, + arma::fvec &result); + +}; diff --git a/include/gfx_ui.h b/include/gfx_ui.h new file mode 100644 index 0000000..470b0a5 --- /dev/null +++ b/include/gfx_ui.h @@ -0,0 +1,142 @@ +/******************************************************************** + -------------------------------------------------------------------- + -- _,(_)._ + -- ___,(_______). ____ + -- ,'__. \ /\___\-. + -- /,' / \ / / \ + -- | | | |,' / \ + -- \`.| / ___|________ + -- `. : : / gfx_ui + -- `. :.,' A immediate mode 2d graphics manipulation UI + -- `-.________,-' Built on top of IMGUI + -- © Daniel Berio + -- http://www.enist.org + -- drand48@gmail.com + -- + -------------------------------------------------------------------- + ********************************************************************/ + + +#pragma once +#include "imgui.h" +#include "gfx_ui_config.h" +#include <stdlib.h> +#include <vector> +#include <string> +#include <sstream> + +namespace ui +{ + enum + { + DRAGGER_CIRCLE = 0, + DRAGGER_SQUARE = 1 + }; + + + struct Trans2d + { + Trans2d() {} + Trans2d( const ImVec2& x, const ImVec2& y, const ImVec2& pos) + : x(x), y(y), pos(pos) {} + +#ifdef UI_TRANS2D_CLASS_EXTRA + UI_TRANS2D_CLASS_EXTRA +#endif + + ImVec2 x; + ImVec2 y; + ImVec2 pos; + }; + + struct Rect + { + Rect() {} + Rect( const ImVec2& min, const ImVec2& max ) + : min(min), max(max) {} + +#ifdef UI_RECT_CLASS_EXTRA + UI_RECT_CLASS_EXTRA +#endif + + bool contains( const ImVec2& p ) const { return ( p.x >= min.x && p.y >= min.y + && p.x <= max.x && p.y <= max.y ); } + + ImVec2 min; + ImVec2 max; + }; + + struct Config + { + Config() + { + rounding = 2.0; + draggerSize = 4.0; + lineColor = 0xff666666; + hoverColor = 0xff0000ff; + selectedColor = 0xff0044ff; + color=0xff666666; + } + + float rounding; + float draggerSize; + ImU32 lineColor; + ImU32 hoverColor; + ImU32 selectedColor; + ImU32 color; + }; + + extern Config config; + + /// Returns true if the IMGUI/gfx_ui have focus + /// Since gfx_ui creates a "full screen" window to handle interactions through IMGUI, + /// you should use this rather than ImGui::GetIO().WantCaptureMouse to check weather + /// your application should handle mouse events + bool hasFocus(); + + /// Initialization, starts up the font + /// This function should be called BEFORE the IMGUI texture atlas is created + /// And AFTER the default IMGUI texture has been loaded. + /// Should find a less restrictive way to handle this. + void init( float iconSize=20.0, const std::string& iconFontPath=""); + + /// The UI should be called withing these begin end blocks + void begin( const std::string& name="gfx_ui" ); + void end(); + + void textColor( ImVec4 clr ); + void text( ImVec2 pos, const std::string& str ); + void textf( ImVec2 pos, const char * format, ... ); + + /// Will return true if the previous widget call has caught an interaction + bool modified(); + + /// Dragger widget + ImVec2 dragger( int index, ImVec2 pos, bool selected=false, float size=-1. ); + + /// Highlights a dragger + void highlightDragger( const ImVec2& pos, float size=-1. ); + + /// Draw a line from a to b + void line( const ImVec2& a, const ImVec2& b ); + + /// Angle and length handle widget + ImVec2 lengthHandle( int index, ImVec2 thetaLen, float startTheta, const ImVec2& pos, const ImVec2& minThetaLen, const ImVec2& maxThetaLen, bool selected=false ); + + /// Angle handle widget + float handle( int index, float ang, const ImVec2& pos, float length, float startTheta=0.0f, float minTheta=0.0f, float maxTheta=0.0f, bool selected=false ); + + /// Simple affine transform widget (two axes, centered) + Trans2d affineSimple( int index, Trans2d m, bool selected=false ); + + /// Creates a draggable rect for selection, see demo() for example usage + Rect selector(); + + /// Returns current mouse delta + ImVec2 dragDelta(); + + /// Creates a font-icon toolbar (not necessary to call between begin and end) + int toolbar( const std::string& title, const std::string& items, int selectedItem, bool horizontal=false, bool showAscii=false ); + + void demo(); +} diff --git a/include/gfx_ui_config.h b/include/gfx_ui_config.h new file mode 100644 index 0000000..672232c --- /dev/null +++ b/include/gfx_ui_config.h @@ -0,0 +1,17 @@ +#pragma once + +// conversion to and from armadillo +#include "armadillo" +#define UI_TRANS2D_CLASS_EXTRA \ +Trans2d(const arma::vec& p, const arma::mat& rot) { x=ImVec2(rot(0,0),rot(1,0)); x=ImVec2(rot(0,1),rot(1,1)); \ + pos.x=p[0]; pos.y=p[1]; } \ + operator arma::mat() const { arma::mat f; \ + f.col(0) = arma::vec({x.x, x.y, 0.0}); \ + f.col(1) = arma::vec({y.x, y.y, 0.0}); \ + f.col(2) = arma::vec({pos.x, pos.y, 1.}); return f; } \ + Trans2d(const arma::mat& f) \ + { \ + x.x=f(0,0); x.y=f(1,0); \ + y.x=f(0,1); y.y=f(1,1); \ + pos.x=f(0,2); pos.y=f(1,2); \ + } diff --git a/include/gl2ps.h b/include/gl2ps.h new file mode 100644 index 0000000..d3e7c0c --- /dev/null +++ b/include/gl2ps.h @@ -0,0 +1,207 @@ +/* + * GL2PS, an OpenGL to PostScript Printing Library + * Copyright (C) 1999-2015 C. Geuzaine + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of either: + * + * a) the GNU Library General Public License as published by the Free + * Software Foundation, either version 2 of the License, or (at your + * option) any later version; or + * + * b) the GL2PS License as published by Christophe Geuzaine, either + * version 2 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either + * the GNU Library General Public License or the GL2PS License for + * more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library in the file named "COPYING.LGPL"; + * if not, write to the Free Software Foundation, Inc., 51 Franklin + * Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * You should have received a copy of the GL2PS License with this + * library in the file named "COPYING.GL2PS"; if not, I will be glad + * to provide one. + * + * For the latest info about gl2ps and a full list of contributors, + * see http://www.geuz.org/gl2ps/. + * + * Please report all bugs and problems to <gl2ps@geuz.org>. + */ + +#ifndef __GL2PS_H__ +#define __GL2PS_H__ + +#include <stdio.h> +#include <stdlib.h> + +/* Define GL2PSDLL at compile time to build a Windows DLL */ + +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) +# if defined(_MSC_VER) +# pragma warning(disable:4115) +# pragma warning(disable:4996) +# endif +# include <windows.h> +# if defined(GL2PSDLL) +# if defined(GL2PSDLL_EXPORTS) +# define GL2PSDLL_API __declspec(dllexport) +# else +# define GL2PSDLL_API __declspec(dllimport) +# endif +# else +# define GL2PSDLL_API +# endif +#else +# define GL2PSDLL_API +#endif + +#if defined(__APPLE__) || defined(HAVE_OPENGL_GL_H) +# include <OpenGL/gl.h> +#else +# include <GL/gl.h> +#endif + +/* Support for compressed PostScript/PDF/SVG and for embedded PNG + images in SVG */ + +#if defined(HAVE_ZLIB) || defined(HAVE_LIBZ) +# define GL2PS_HAVE_ZLIB +# if defined(HAVE_LIBPNG) || defined(HAVE_PNG) +# define GL2PS_HAVE_LIBPNG +# endif +#endif + +#if defined(HAVE_NO_VSNPRINTF) +# define GL2PS_HAVE_NO_VSNPRINTF +#endif + +/* Version number */ + +#define GL2PS_MAJOR_VERSION 1 +#define GL2PS_MINOR_VERSION 3 +#define GL2PS_PATCH_VERSION 9 +#define GL2PS_EXTRA_VERSION "" + +#define GL2PS_VERSION (GL2PS_MAJOR_VERSION + \ + 0.01 * GL2PS_MINOR_VERSION + \ + 0.0001 * GL2PS_PATCH_VERSION) + +#define GL2PS_COPYRIGHT "(C) 1999-2015 C. Geuzaine" + +/* Output file formats (the values and the ordering are important!) */ + +#define GL2PS_PS 0 +#define GL2PS_EPS 1 +#define GL2PS_TEX 2 +#define GL2PS_PDF 3 +#define GL2PS_SVG 4 +#define GL2PS_PGF 5 + +/* Sorting algorithms */ + +#define GL2PS_NO_SORT 1 +#define GL2PS_SIMPLE_SORT 2 +#define GL2PS_BSP_SORT 3 + +/* Message levels and error codes */ + +#define GL2PS_SUCCESS 0 +#define GL2PS_INFO 1 +#define GL2PS_WARNING 2 +#define GL2PS_ERROR 3 +#define GL2PS_NO_FEEDBACK 4 +#define GL2PS_OVERFLOW 5 +#define GL2PS_UNINITIALIZED 6 + +/* Options for gl2psBeginPage */ + +#define GL2PS_NONE 0 +#define GL2PS_DRAW_BACKGROUND (1<<0) +#define GL2PS_SIMPLE_LINE_OFFSET (1<<1) +#define GL2PS_SILENT (1<<2) +#define GL2PS_BEST_ROOT (1<<3) +#define GL2PS_OCCLUSION_CULL (1<<4) +#define GL2PS_NO_TEXT (1<<5) +#define GL2PS_LANDSCAPE (1<<6) +#define GL2PS_NO_PS3_SHADING (1<<7) +#define GL2PS_NO_PIXMAP (1<<8) +#define GL2PS_USE_CURRENT_VIEWPORT (1<<9) +#define GL2PS_COMPRESS (1<<10) +#define GL2PS_NO_BLENDING (1<<11) +#define GL2PS_TIGHT_BOUNDING_BOX (1<<12) + +/* Arguments for gl2psEnable/gl2psDisable */ + +#define GL2PS_POLYGON_OFFSET_FILL 1 +#define GL2PS_POLYGON_BOUNDARY 2 +#define GL2PS_LINE_STIPPLE 3 +#define GL2PS_BLEND 4 + +/* Text alignment (o=raster position; default mode is BL): + +---+ +---+ +---+ +---+ +---+ +---+ +-o-+ o---+ +---o + | o | o | | o | | | | | | | | | | | | + +---+ +---+ +---+ +-o-+ o---+ +---o +---+ +---+ +---+ + C CL CR B BL BR T TL TR */ + +#define GL2PS_TEXT_C 1 +#define GL2PS_TEXT_CL 2 +#define GL2PS_TEXT_CR 3 +#define GL2PS_TEXT_B 4 +#define GL2PS_TEXT_BL 5 +#define GL2PS_TEXT_BR 6 +#define GL2PS_TEXT_T 7 +#define GL2PS_TEXT_TL 8 +#define GL2PS_TEXT_TR 9 + +typedef GLfloat GL2PSrgba[4]; + +#if defined(__cplusplus) +extern "C" { +#endif + +GL2PSDLL_API GLint gl2psBeginPage(const char *title, const char *producer, + GLint viewport[4], GLint format, GLint sort, + GLint options, GLint colormode, + GLint colorsize, GL2PSrgba *colormap, + GLint nr, GLint ng, GLint nb, GLint buffersize, + FILE *stream, const char *filename); +GL2PSDLL_API GLint gl2psEndPage(void); +GL2PSDLL_API GLint gl2psSetOptions(GLint options); +GL2PSDLL_API GLint gl2psGetOptions(GLint *options); +GL2PSDLL_API GLint gl2psBeginViewport(GLint viewport[4]); +GL2PSDLL_API GLint gl2psEndViewport(void); +GL2PSDLL_API GLint gl2psText(const char *str, const char *fontname, + GLshort fontsize); +GL2PSDLL_API GLint gl2psTextOpt(const char *str, const char *fontname, + GLshort fontsize, GLint align, GLfloat angle); +GL2PSDLL_API GLint gl2psTextOptColor(const char *str, const char *fontname, + GLshort fontsize, GLint align, GLfloat angle, + GL2PSrgba color); +GL2PSDLL_API GLint gl2psSpecial(GLint format, const char *str); +GL2PSDLL_API GLint gl2psDrawPixels(GLsizei width, GLsizei height, + GLint xorig, GLint yorig, + GLenum format, GLenum type, const void *pixels); +GL2PSDLL_API GLint gl2psEnable(GLint mode); +GL2PSDLL_API GLint gl2psDisable(GLint mode); +GL2PSDLL_API GLint gl2psPointSize(GLfloat value); +GL2PSDLL_API GLint gl2psLineWidth(GLfloat value); +GL2PSDLL_API GLint gl2psBlendFunc(GLenum sfactor, GLenum dfactor); + +/* undocumented */ +GL2PSDLL_API GLint gl2psDrawImageMap(GLsizei width, GLsizei height, + const GLfloat position[3], + const unsigned char *imagemap); +GL2PSDLL_API const char *gl2psGetFileExtension(GLint format); +GL2PSDLL_API const char *gl2psGetFormatDescription(GLint format); +GL2PSDLL_API GLint gl2psGetFileFormat(); + +#if defined(__cplusplus) +} +#endif + +#endif /* __GL2PS_H__ */ diff --git a/include/imconfig.h b/include/imconfig.h new file mode 100644 index 0000000..9ef94f7 --- /dev/null +++ b/include/imconfig.h @@ -0,0 +1,58 @@ +//----------------------------------------------------------------------------- +// USER IMPLEMENTATION +// This file contains compile-time options for ImGui. +// Other options (memory allocation overrides, callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO(). +//----------------------------------------------------------------------------- + +#pragma once +#include "armadillo" + +//---- Define assertion handler. Defaults to calling assert(). +//#define IM_ASSERT(_EXPR) MyAssert(_EXPR) + +//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows. +//#define IMGUI_API __declspec( dllexport ) +//#define IMGUI_API __declspec( dllimport ) + +//---- Include imgui_user.h at the end of imgui.h +//#define IMGUI_INCLUDE_IMGUI_USER_H + +//---- Don't implement default handlers for Windows (so as not to link with OpenClipboard() and others Win32 functions) +//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS +//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS + +//---- Don't implement help and test window functionality (ShowUserGuide()/ShowStyleEditor()/ShowTestWindow() methods will be empty) +//#define IMGUI_DISABLE_TEST_WINDOWS + +//---- Don't define obsolete functions names +//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS + +//---- Pack colors to BGRA instead of RGBA (remove need to post process vertex buffer in back ends) +//#define IMGUI_USE_BGRA_PACKED_COLOR + +//---- Implement STB libraries in a namespace to avoid conflicts +//#define IMGUI_STB_NAMESPACE ImGuiStb + +//---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4. +// Does not work with columns yet... +#define IM_VEC2_CLASS_EXTRA \ + ImVec2(const arma::vec& f) { x = f[0]; y = f[1]; } \ + ImVec2(const arma::subview_col<double>& f) { x = f[0]; y = f[1]; }\ + operator arma::vec() const { return arma::vec({x,y}); } \ + ImVec2& operator = (const arma::vec& v) {x = v.at(0); y = v.at(1); return *this; } + +#define IM_VEC4_CLASS_EXTRA \ + ImVec4(const arma::vec& f) { x = f[0]; y = f[1]; z = f[2]; w = f[3]; } \ + ImVec4(const arma::subview_col<double>& f) { x = f[0]; y = f[1]; z = f[2]; w = f[3]; } \ + operator arma::vec() const { return arma::vec({x,y,z,w}); } \ + ImVec4& operator = (const arma::vec& v) { x = v.at(0); y = v.at(1); z = v.at(2); w = v.at(3); return *this; } + +//---- Tip: You can add extra functions within the ImGui:: namespace, here or in your own headers files. +//---- e.g. create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers. +/* +namespace ImGui +{ + void Value(const char* prefix, const MyMatrix44& v, const char* float_format = NULL); +} +*/ + diff --git a/include/imgui.h b/include/imgui.h new file mode 100644 index 0000000..7ef8bd2 --- /dev/null +++ b/include/imgui.h @@ -0,0 +1,1399 @@ +// dear imgui, v1.50 WIP +// (headers) + +// See imgui.cpp file for documentation. +// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. +// Read 'Programmer guide' in imgui.cpp for notes on how to setup ImGui in your codebase. +// Get latest version at https://github.com/ocornut/imgui + +#pragma once + +#if !defined(IMGUI_DISABLE_INCLUDE_IMCONFIG_H) || defined(IMGUI_INCLUDE_IMCONFIG_H) +#include "imconfig.h" // User-editable configuration file +#endif +#include <float.h> // FLT_MAX +#include <stdarg.h> // va_list +#include <stddef.h> // ptrdiff_t, NULL +#include <string.h> // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp + +#define IMGUI_VERSION "1.50 WIP" + +// Define attributes of all API symbols declarations, e.g. for DLL under Windows. +#ifndef IMGUI_API +#define IMGUI_API +#endif + +// Define assertion handler. +#ifndef IM_ASSERT +#include <assert.h> +#define IM_ASSERT(_EXPR) assert(_EXPR) +#endif + +// Some compilers support applying printf-style warnings to user functions. +#if defined(__clang__) || defined(__GNUC__) +#define IM_PRINTFARGS(FMT) __attribute__((format(printf, FMT, (FMT+1)))) +#else +#define IM_PRINTFARGS(FMT) +#endif + +#if defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" +#endif + +// Forward declarations +struct ImDrawChannel; // Temporary storage for outputting drawing commands out of order, used by ImDrawList::ChannelsSplit() +struct ImDrawCmd; // A single draw command within a parent ImDrawList (generally maps to 1 GPU draw call) +struct ImDrawData; // All draw command lists required to render the frame +struct ImDrawList; // A single draw command list (generally one per window) +struct ImDrawVert; // A single vertex (20 bytes by default, override layout with IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT) +struct ImFont; // Runtime data for a single font within a parent ImFontAtlas +struct ImFontAtlas; // Runtime data for multiple fonts, bake multiple fonts into a single texture, TTF font loader +struct ImFontConfig; // Configuration data when adding a font or merging fonts +struct ImColor; // Helper functions to create a color that can be converted to either u32 or float4 +struct ImGuiIO; // Main configuration and I/O between your application and ImGui +struct ImGuiOnceUponAFrame; // Simple helper for running a block of code not more than once a frame, used by IMGUI_ONCE_UPON_A_FRAME macro +struct ImGuiStorage; // Simple custom key value storage +struct ImGuiStyle; // Runtime data for styling/colors +struct ImGuiTextFilter; // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextBuffer; // Text buffer for logging/accumulating text +struct ImGuiTextEditCallbackData; // Shared state of ImGui::InputText() when using custom ImGuiTextEditCallback (rare/advanced use) +struct ImGuiSizeConstraintCallbackData;// Structure used to constraint window size in custom ways when using custom ImGuiSizeConstraintCallback (rare/advanced use) +struct ImGuiListClipper; // Helper to manually clip large list of items +struct ImGuiContext; // ImGui context (opaque) + +// Typedefs and Enumerations (declared as int for compatibility and to not pollute the top of this file) +typedef unsigned int ImU32; // 32-bit unsigned integer (typically used to store packed colors) +typedef unsigned int ImGuiID; // unique ID used by widgets (typically hashed from a stack of string) +typedef unsigned short ImWchar; // character for keyboard input/display +typedef void* ImTextureID; // user data to identify a texture (this is whatever to you want it to be! read the FAQ about ImTextureID in imgui.cpp) +typedef int ImGuiCol; // a color identifier for styling // enum ImGuiCol_ +typedef int ImGuiStyleVar; // a variable identifier for styling // enum ImGuiStyleVar_ +typedef int ImGuiKey; // a key identifier (ImGui-side enum) // enum ImGuiKey_ +typedef int ImGuiColorEditMode; // color edit mode for ColorEdit*() // enum ImGuiColorEditMode_ +typedef int ImGuiMouseCursor; // a mouse cursor identifier // enum ImGuiMouseCursor_ +typedef int ImGuiWindowFlags; // window flags for Begin*() // enum ImGuiWindowFlags_ +typedef int ImGuiSetCond; // condition flags for Set*() // enum ImGuiSetCond_ +typedef int ImGuiInputTextFlags; // flags for InputText*() // enum ImGuiInputTextFlags_ +typedef int ImGuiSelectableFlags; // flags for Selectable() // enum ImGuiSelectableFlags_ +typedef int ImGuiTreeNodeFlags; // flags for TreeNode*(), Collapsing*() // enum ImGuiTreeNodeFlags_ +typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data); +typedef void (*ImGuiSizeConstraintCallback)(ImGuiSizeConstraintCallbackData* data); + +// Others helpers at bottom of the file: +// class ImVector<> // Lightweight std::vector like class. +// IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times) + +struct ImVec2 +{ + float x, y; + ImVec2() { x = y = 0.0f; } + ImVec2(float _x, float _y) { x = _x; y = _y; } +#ifdef IM_VEC2_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec2. + IM_VEC2_CLASS_EXTRA +#endif +}; + +struct ImVec4 +{ + float x, y, z, w; + ImVec4() { x = y = z = w = 0.0f; } + ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } +#ifdef IM_VEC4_CLASS_EXTRA // Define constructor and implicit cast operators in imconfig.h to convert back<>forth from your math types and ImVec4. + IM_VEC4_CLASS_EXTRA +#endif +}; + +// ImGui end-user API +// In a namespace so that user can add extra functions in a separate file (e.g. Value() helpers for your vector or common types) +namespace ImGui +{ + // Main + IMGUI_API ImGuiIO& GetIO(); + IMGUI_API ImGuiStyle& GetStyle(); + IMGUI_API ImDrawData* GetDrawData(); // same value as passed to your io.RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() + IMGUI_API void NewFrame(); // start a new ImGui frame, you can submit any command from this point until NewFrame()/Render(). + IMGUI_API void Render(); // ends the ImGui frame, finalize rendering data, then call your io.RenderDrawListsFn() function if set. + IMGUI_API void Shutdown(); + IMGUI_API void ShowUserGuide(); // help block + IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block. you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style) + IMGUI_API void ShowTestWindow(bool* p_open = NULL); // test window demonstrating ImGui features + IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // metrics window for debugging ImGui + + // Window + IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // push window to the stack and start appending to it. see .cpp for details. return false when window is collapsed, so you can early out in your code. 'bool* p_open' creates a widget on the upper-right to close the window (which sets your bool to false). + IMGUI_API bool Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // OBSOLETE. this is the older/longer API. the extra parameters aren't very relevant. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! might obsolete this API eventually. + IMGUI_API void End(); // finish appending to current window, pop it off the window stack. + IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // begin a scrolling region. size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). size>0.0f: fixed size. each axis can use a different mode, e.g. ImVec2(0,400). + IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // " + IMGUI_API void EndChild(); + IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates + IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos() + IMGUI_API float GetContentRegionAvailWidth(); // + IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates + IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates + IMGUI_API float GetWindowContentRegionWidth(); // + IMGUI_API ImDrawList* GetWindowDrawList(); // get rendering command-list if you want to append your own draw primitives + IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList api) + IMGUI_API ImVec2 GetWindowSize(); // get current window size + IMGUI_API float GetWindowWidth(); + IMGUI_API float GetWindowHeight(); + IMGUI_API bool IsWindowCollapsed(); + IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows + + IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set next window position. call before Begin() + IMGUI_API void SetNextWindowPosCenter(ImGuiSetCond cond = 0); // set next window position to be centered on screen. call before Begin() + IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin() + IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Use callback to apply non-trivial programmatic constraints. + IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (enforce the range of scrollbars). set axis to 0.0f to leave it automatic. call before Begin() + IMGUI_API void SetNextWindowContentWidth(float width); // set next window content width (enforce the range of horizontal scrollbar). call before Begin() + IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set next window collapsed state. call before Begin() + IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most. call before Begin() + IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects. + IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0,0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects. + IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed(). + IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / front-most. prefer using SetNextWindowFocus(). + IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond = 0); // set named window position. + IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis. + IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond = 0); // set named window collapsed state + IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. + + IMGUI_API float GetScrollX(); // get scrolling amount [0..GetScrollMaxX()] + IMGUI_API float GetScrollY(); // get scrolling amount [0..GetScrollMaxY()] + IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.X - WindowSize.X + IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.Y - WindowSize.Y + IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0..GetScrollMaxX()] + IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0..GetScrollMaxY()] + IMGUI_API void SetScrollHere(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. + IMGUI_API void SetScrollFromPosY(float pos_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position valid. use GetCursorPos() or GetCursorStartPos()+offset to get valid positions. + IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use negative 'offset' to access previous widgets. + IMGUI_API void SetStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it) + IMGUI_API ImGuiStorage* GetStateStorage(); + + // Parameters stacks (shared) + IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font + IMGUI_API void PopFont(); + IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); + IMGUI_API void PopStyleColor(int count = 1); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); + IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); + IMGUI_API void PopStyleVar(int count = 1); + IMGUI_API ImFont* GetFont(); // get current font + IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied + IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API + IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier + IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied + + // Parameters stacks (current window) + IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side) + IMGUI_API void PopItemWidth(); + IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position + IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space + IMGUI_API void PopTextWrapPos(); + IMGUI_API void PushAllowKeyboardFocus(bool v); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets + IMGUI_API void PopAllowKeyboardFocus(); + IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (uses io.KeyRepeatDelay/io.KeyRepeatRate for now). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame. + IMGUI_API void PopButtonRepeat(); + + // Cursor / Layout + IMGUI_API void Separator(); // horizontal line + IMGUI_API void SameLine(float pos_x = 0.0f, float spacing_w = -1.0f); // call between widgets or groups to layout them horizontally + IMGUI_API void NewLine(); // undo a SameLine() + IMGUI_API void Spacing(); // add vertical spacing + IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size + IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by style.IndentSpacing or indent_w if >0 + IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by style.IndentSpacing or indent_w if >0 + IMGUI_API void BeginGroup(); // lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) + IMGUI_API void EndGroup(); + IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position + IMGUI_API float GetCursorPosX(); // " + IMGUI_API float GetCursorPosY(); // " + IMGUI_API void SetCursorPos(const ImVec2& local_pos); // " + IMGUI_API void SetCursorPosX(float x); // " + IMGUI_API void SetCursorPosY(float y); // " + IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position + IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API) + IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize] + IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets + IMGUI_API float GetTextLineHeight(); // height of font == GetWindowFontSize() + IMGUI_API float GetTextLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of text == GetWindowFontSize() + GetStyle().ItemSpacing.y + IMGUI_API float GetItemsLineHeightWithSpacing(); // distance (in pixels) between 2 consecutive lines of standard height widgets == GetWindowFontSize() + GetStyle().FramePadding.y*2 + GetStyle().ItemSpacing.y + + // Columns + // You can also use SameLine(pos_x) for simplified columning. The columns API is still work-in-progress and rather lacking. + IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true); // setup number of columns. use an identifier to distinguish multiple column sets. close with Columns(1). + IMGUI_API void NextColumn(); // next column + IMGUI_API int GetColumnIndex(); // get current column index + IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetcolumnsCount() inclusive. column 0 is usually 0.0f and not resizable unless you call this + IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column + IMGUI_API float GetColumnWidth(int column_index = -1); // column width (== GetColumnOffset(GetColumnIndex()+1) - GetColumnOffset(GetColumnOffset()) + IMGUI_API int GetColumnsCount(); // number of columns (what was passed to Columns()) + + // ID scopes + // If you are creating widgets in a loop you most likely want to push a unique identifier so ImGui can differentiate them. + // You can also use the "##foobar" syntax within widget label to distinguish them from each others. Read "A primer on the use of labels/IDs" in the FAQ for more details. + IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the *entire* stack! + IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); + IMGUI_API void PushID(const void* ptr_id); + IMGUI_API void PushID(int int_id); + IMGUI_API void PopID(); + IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). useful if you want to query into ImGuiStorage yourself. otherwise rarely needed + IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end); + IMGUI_API ImGuiID GetID(const void* ptr_id); + + // Widgets + IMGUI_API void Text(const char* fmt, ...) IM_PRINTFARGS(1); + IMGUI_API void TextV(const char* fmt, va_list args); + IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_PRINTFARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args); + IMGUI_API void TextDisabled(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor(); + IMGUI_API void TextDisabledV(const char* fmt, va_list args); + IMGUI_API void TextWrapped(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize(). + IMGUI_API void TextWrappedV(const char* fmt, va_list args); + IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done to any bounded stack buffer, recommended for long chunks of text + IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_PRINTFARGS(2); // display text+label aligned the same way as value+label widgets + IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args); + IMGUI_API void Bullet(); // draw a small circle and keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses + IMGUI_API void BulletText(const char* fmt, ...) IM_PRINTFARGS(1); // shortcut for Bullet()+Text() + IMGUI_API void BulletTextV(const char* fmt, va_list args); + IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0)); // button + IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) + IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); + IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); + IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding + IMGUI_API bool Checkbox(const char* label, bool* v); + IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); + IMGUI_API bool RadioButton(const char* label, bool active); + IMGUI_API bool RadioButton(const char* label, int* v, int v_button); + IMGUI_API bool Combo(const char* label, int* current_item, const char** items, int items_count, int height_in_items = -1); + IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items = -1); // separate items with \0, end item-list with \0\0 + IMGUI_API bool Combo(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); + IMGUI_API bool ColorButton(const ImVec4& col, bool small_height = false, bool outline_border = true); + IMGUI_API bool ColorEdit3(const char* label, float col[3]); // Hint: 'float col[3]' function argument is same as 'float* col'. You can pass address of first element out of a contiguous set, e.g. &myvector.x + IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); // " + IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); // FIXME-OBSOLETE: This is inconsistent with most of the API and will be obsoleted/replaced. + IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); + IMGUI_API void PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); + IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), int stride = sizeof(float)); + IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); + IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-1,0), const char* overlay = NULL); + + // Widgets: Drags (tip: ctrl+click on a drag box to input with keyboard. manually input values aren't clamped, can go off-bounds) + // For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, remember than a 'float v[3]' function argument is the same as 'float* v'. You can pass address of your first element out of a contiguous set, e.g. &myvector.x + IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); // If v_min >= v_max we have no bound + IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f", const char* display_format_max = NULL, float power = 1.0f); + IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); // If v_min >= v_max we have no bound + IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); + IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); + IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f"); + IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* display_format = "%.0f", const char* display_format_max = NULL); + + // Widgets: Input with Keyboard + IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0,0), ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags = 0); + IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags = 0); + + // Widgets: Sliders (tip: ctrl+click on a slider to input with keyboard. manually input values aren't clamped, can go off-bounds) + IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix. Use power!=1.0 for logarithmic sliders + IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f); + IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format = "%.0f"); + IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format = "%.0f"); + IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format = "%.0f"); + IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format = "%.0f"); + IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); + IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format = "%.0f"); + + // Widgets: Trees + IMGUI_API bool TreeNode(const char* label); // if returning 'true' the node is open and the tree id is pushed into the id stack. user is responsible for calling TreePop(). + IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_PRINTFARGS(2); // read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet(). + IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_PRINTFARGS(2); // " + IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args); // " + IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args); // " + IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0); + IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3); + IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_PRINTFARGS(3); + IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); + IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args); + IMGUI_API void TreePush(const char* str_id = NULL); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call Push/Pop yourself for layout purpose + IMGUI_API void TreePush(const void* ptr_id = NULL); // " + IMGUI_API void TreePop(); // ~ Unindent()+PopId() + IMGUI_API void TreeAdvanceToLabelPos(); // advance cursor x position by GetTreeNodeToLabelSpacing() + IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode + IMGUI_API void SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond = 0); // set next TreeNode/CollapsingHeader open state. + IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop(). + IMGUI_API bool CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags = 0); // when 'p_open' isn't NULL, display an additional small close button on upper right of the header + + // Widgets: Selectable / Lists + IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); // size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height + IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0,0)); + IMGUI_API bool ListBox(const char* label, int* current_item, const char** items, int items_count, int height_in_items = -1); + IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); + IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. make sure to call ListBoxFooter() afterwards. + IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " + IMGUI_API void ListBoxFooter(); // terminate the scrolling region + + // Widgets: Value() Helpers. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace) + IMGUI_API void Value(const char* prefix, bool b); + IMGUI_API void Value(const char* prefix, int v); + IMGUI_API void Value(const char* prefix, unsigned int v); + IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); + IMGUI_API void ValueColor(const char* prefix, const ImVec4& v); + IMGUI_API void ValueColor(const char* prefix, ImU32 v); + + // Tooltips + IMGUI_API void SetTooltip(const char* fmt, ...) IM_PRINTFARGS(1); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). last call wins + IMGUI_API void SetTooltipV(const char* fmt, va_list args); + IMGUI_API void BeginTooltip(); // use to create full-featured tooltip windows that aren't just text + IMGUI_API void EndTooltip(); + + // Menus + IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar. only call EndMainMenuBar() if this returns true! + IMGUI_API void EndMainMenuBar(); + IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set). only call EndMenuBar() if this returns true! + IMGUI_API void EndMenuBar(); + IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true! + IMGUI_API void EndMenu(); + IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment + IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL + + // Popups + IMGUI_API void OpenPopup(const char* str_id); // mark popup as open. popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). + IMGUI_API bool BeginPopup(const char* str_id); // return true if the popup is open, and you can start outputting to it. only call EndPopup() if BeginPopup() returned true! + IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags extra_flags = 0); // modal dialog (can't close them by clicking outside) + IMGUI_API bool BeginPopupContextItem(const char* str_id, int mouse_button = 1); // helper to open and begin popup when clicked on last item. read comments in .cpp! + IMGUI_API bool BeginPopupContextWindow(bool also_over_items = true, const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked on current window. + IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, int mouse_button = 1); // helper to open and begin popup when clicked in void (no window). + IMGUI_API void EndPopup(); + IMGUI_API void CloseCurrentPopup(); // close the popup we have begin-ed into. clicking on a MenuItem or Selectable automatically close the current popup. + + // Logging: all text output from interface is redirected to tty/file/clipboard. By default, tree nodes are automatically opened during logging. + IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty + IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file + IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard + IMGUI_API void LogFinish(); // stop logging (close file, etc.) + IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard + IMGUI_API void LogText(const char* fmt, ...) IM_PRINTFARGS(1); // pass text data straight to log (without being displayed) + + // Clipping + IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect); + IMGUI_API void PopClipRect(); + + // Utilities + IMGUI_API bool IsItemHovered(); // was the last item hovered by mouse? + IMGUI_API bool IsItemHoveredRect(); // was the last item hovered by mouse? even if another item is active or window is blocked by popup while we are hovering this + IMGUI_API bool IsItemActive(); // was the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false) + IMGUI_API bool IsItemClicked(int mouse_button = 0); // was the last item clicked? (e.g. button/node just clicked on) + IMGUI_API bool IsItemVisible(); // was the last item visible? (aka not out of sight due to clipping/scrolling.) + IMGUI_API bool IsAnyItemHovered(); + IMGUI_API bool IsAnyItemActive(); + IMGUI_API ImVec2 GetItemRectMin(); // get bounding rect of last item in screen space + IMGUI_API ImVec2 GetItemRectMax(); // " + IMGUI_API ImVec2 GetItemRectSize(); // " + IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area. + IMGUI_API bool IsWindowHovered(); // is current window hovered and hoverable (not blocked by a popup) (differentiate child windows from each others) + IMGUI_API bool IsWindowFocused(); // is current window focused + IMGUI_API bool IsRootWindowFocused(); // is current root window focused (root = top-most parent of a child, otherwise self) + IMGUI_API bool IsRootWindowOrAnyChildFocused(); // is current root window or any of its child (including current window) focused + IMGUI_API bool IsRootWindowOrAnyChildHovered(); // is current root window or any of its child (including current window) hovered and hoverable (not blocked by a popup) + IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped. + IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side. + IMGUI_API bool IsPosHoveringAnyWindow(const ImVec2& pos); // is given position hovering any active imgui window + IMGUI_API float GetTime(); + IMGUI_API int GetFrameCount(); + IMGUI_API const char* GetStyleColName(ImGuiCol idx); + IMGUI_API ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = +0.0f); // utility to find the closest point the last item bounding rectangle edge. useful to visually link items + IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); + IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can. + + IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame + IMGUI_API void EndChildFrame(); + + IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in); + IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); + IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); + IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); + + // Inputs + IMGUI_API int GetKeyIndex(ImGuiKey key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key] + IMGUI_API bool IsKeyDown(int key_index); // key_index into the keys_down[] array, imgui doesn't know the semantic of each entry, uses your own indices! + IMGUI_API bool IsKeyPressed(int key_index, bool repeat = true); // uses user's key indices as stored in the keys_down[] array. if repeat=true. uses io.KeyRepeatDelay / KeyRepeatRate + IMGUI_API bool IsKeyReleased(int key_index); // " + IMGUI_API bool IsMouseDown(int button); // is mouse button held + IMGUI_API bool IsMouseClicked(int button, bool repeat = false); // did mouse button clicked (went from !Down to Down) + IMGUI_API bool IsMouseDoubleClicked(int button); // did mouse button double-clicked. a double-click returns false in IsMouseClicked(). uses io.MouseDoubleClickTime. + IMGUI_API bool IsMouseReleased(int button); // did mouse button released (went from Down to !Down) + IMGUI_API bool IsMouseHoveringWindow(); // is mouse hovering current window ("window" in API names always refer to current window). disregarding of any consideration of being blocked by a popup. (unlike IsWindowHovered() this will return true even if the window is blocked because of a popup) + IMGUI_API bool IsMouseHoveringAnyWindow(); // is mouse hovering any visible window + IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true); // is mouse hovering given bounding rect (in screen space). clipped by current clipping settings. disregarding of consideration of focus/window ordering/blocked by a popup. + IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold + IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls + IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve backup of mouse positioning at the time of opening popup we have BeginPopup() into + IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // dragging amount since clicking. if lock_threshold < -1.0f uses io.MouseDraggingThreshold + IMGUI_API void ResetMouseDragDelta(int button = 0); // + IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you + IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type + IMGUI_API void CaptureKeyboardFromApp(bool capture = true); // manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application handle). e.g. force capture keyboard when your widget is being hovered. + IMGUI_API void CaptureMouseFromApp(bool capture = true); // manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application handle). + + // Helpers functions to access functions pointers in ImGui::GetIO() + IMGUI_API void* MemAlloc(size_t sz); + IMGUI_API void MemFree(void* ptr); + IMGUI_API const char* GetClipboardText(); + IMGUI_API void SetClipboardText(const char* text); + + // Internal context access - if you want to use multiple context, share context between modules (e.g. DLL). There is a default context created and active by default. + // All contexts share a same ImFontAtlas by default. If you want different font atlas, you can new() them and overwrite the GetIO().Fonts variable of an ImGui context. + IMGUI_API const char* GetVersion(); + IMGUI_API ImGuiContext* CreateContext(void* (*malloc_fn)(size_t) = NULL, void (*free_fn)(void*) = NULL); + IMGUI_API void DestroyContext(ImGuiContext* ctx); + IMGUI_API ImGuiContext* GetCurrentContext(); + IMGUI_API void SetCurrentContext(ImGuiContext* ctx); + + // Obsolete (will be removed) +#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS + static inline bool CollapsingHeader(const char* label, const char* str_id, bool framed = true, bool default_open = false) { (void)str_id; (void)framed; ImGuiTreeNodeFlags default_open_flags = 1<<5; return CollapsingHeader(label, (default_open ? default_open_flags : 0)); } // OBSOLETE 1.49+ + static inline ImFont* GetWindowFont() { return GetFont(); } // OBSOLETE 1.48+ + static inline float GetWindowFontSize() { return GetFontSize(); } // OBSOLETE 1.48+ + static inline void SetScrollPosHere() { SetScrollHere(); } // OBSOLETE 1.42+ + static inline bool GetWindowCollapsed() { return ImGui::IsWindowCollapsed(); } // OBSOLETE 1.39+ + static inline bool IsRectClipped(const ImVec2& size) { return !IsRectVisible(size); } // OBSOLETE 1.39+ +#endif + +} // namespace ImGui + +// Flags for ImGui::Begin() +enum ImGuiWindowFlags_ +{ + // Default: 0 + ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar + ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip + ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window + ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically) + ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel + ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it + ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame + ImGuiWindowFlags_ShowBorders = 1 << 7, // Show borders around windows and items + ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file + ImGuiWindowFlags_NoInputs = 1 << 9, // Disable catching mouse or keyboard inputs + ImGuiWindowFlags_MenuBar = 1 << 10, // Has a menu-bar + ImGuiWindowFlags_HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section. + ImGuiWindowFlags_NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state + ImGuiWindowFlags_NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus) + ImGuiWindowFlags_AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y) + ImGuiWindowFlags_AlwaysHorizontalScrollbar=1<< 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x) + ImGuiWindowFlags_AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient) + // [Internal] + ImGuiWindowFlags_ChildWindow = 1 << 20, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 21, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_ChildWindowAutoFitY = 1 << 22, // Don't use! For internal use by BeginChild() + ImGuiWindowFlags_ComboBox = 1 << 23, // Don't use! For internal use by ComboBox() + ImGuiWindowFlags_Tooltip = 1 << 24, // Don't use! For internal use by BeginTooltip() + ImGuiWindowFlags_Popup = 1 << 25, // Don't use! For internal use by BeginPopup() + ImGuiWindowFlags_Modal = 1 << 26, // Don't use! For internal use by BeginPopupModal() + ImGuiWindowFlags_ChildMenu = 1 << 27 // Don't use! For internal use by BeginMenu() +}; + +// Flags for ImGui::InputText() +enum ImGuiInputTextFlags_ +{ + // Default: 0 + ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ + ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef + ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z + ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs + ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus + ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) + ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Call user function on pressing TAB (for completion handling) + ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Call user function on pressing Up/Down arrows (for history handling) + ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time. User code may query cursor position, modify text buffer. + ImGuiInputTextFlags_CallbackCharFilter = 1 << 9, // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character. + ImGuiInputTextFlags_AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field + ImGuiInputTextFlags_CtrlEnterForNewLine = 1 << 11, // In multi-line mode, allow exiting edition by pressing Enter. Ctrl+Enter to add new line (by default adds new lines with Enter). + ImGuiInputTextFlags_NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally + ImGuiInputTextFlags_AlwaysInsertMode = 1 << 13, // Insert mode + ImGuiInputTextFlags_ReadOnly = 1 << 14, // Read-only mode + ImGuiInputTextFlags_Password = 1 << 15, // Password mode, display all characters as '*' + // [Internal] + ImGuiInputTextFlags_Multiline = 1 << 20 // For internal use by InputTextMultiline() +}; + +// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*() +enum ImGuiTreeNodeFlags_ +{ + ImGuiTreeNodeFlags_Selected = 1 << 0, // Draw as selected + ImGuiTreeNodeFlags_Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader) + ImGuiTreeNodeFlags_AllowOverlapMode = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one + ImGuiTreeNodeFlags_NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack + ImGuiTreeNodeFlags_NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes) + ImGuiTreeNodeFlags_DefaultOpen = 1 << 5, // Default node to be open + ImGuiTreeNodeFlags_OpenOnDoubleClick = 1 << 6, // Need double-click to open node + ImGuiTreeNodeFlags_OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If ImGuiTreeNodeFlags_OpenOnDoubleClick is also set, single-click arrow or double-click all box to open. + ImGuiTreeNodeFlags_Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes). + ImGuiTreeNodeFlags_Bullet = 1 << 9, // Display a bullet instead of arrow + //ImGuITreeNodeFlags_SpanAllAvailWidth = 1 << 10, // FIXME: TODO: Extend hit box horizontally even if not framed + //ImGuiTreeNodeFlags_NoScrollOnOpen = 1 << 11, // FIXME: TODO: Disable automatic scroll on TreePop() if node got just open and contents is not visible + ImGuiTreeNodeFlags_CollapsingHeader = ImGuiTreeNodeFlags_Framed | ImGuiTreeNodeFlags_NoAutoOpenOnLog +}; + +// Flags for ImGui::Selectable() +enum ImGuiSelectableFlags_ +{ + // Default: 0 + ImGuiSelectableFlags_DontClosePopups = 1 << 0, // Clicking this don't close parent popup window + ImGuiSelectableFlags_SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column) + ImGuiSelectableFlags_AllowDoubleClick = 1 << 2 // Generate press events on double clicks too +}; + +// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array +enum ImGuiKey_ +{ + ImGuiKey_Tab, // for tabbing through fields + ImGuiKey_LeftArrow, // for text edit + ImGuiKey_RightArrow,// for text edit + ImGuiKey_UpArrow, // for text edit + ImGuiKey_DownArrow, // for text edit + ImGuiKey_PageUp, + ImGuiKey_PageDown, + ImGuiKey_Home, // for text edit + ImGuiKey_End, // for text edit + ImGuiKey_Delete, // for text edit + ImGuiKey_Backspace, // for text edit + ImGuiKey_Enter, // for text edit + ImGuiKey_Escape, // for text edit + ImGuiKey_A, // for text edit CTRL+A: select all + ImGuiKey_C, // for text edit CTRL+C: copy + ImGuiKey_V, // for text edit CTRL+V: paste + ImGuiKey_X, // for text edit CTRL+X: cut + ImGuiKey_Y, // for text edit CTRL+Y: redo + ImGuiKey_Z, // for text edit CTRL+Z: undo + ImGuiKey_COUNT +}; + +// Enumeration for PushStyleColor() / PopStyleColor() +enum ImGuiCol_ +{ + ImGuiCol_Text, + ImGuiCol_TextDisabled, + ImGuiCol_WindowBg, // Background of normal windows + ImGuiCol_ChildWindowBg, // Background of child windows + ImGuiCol_PopupBg, // Background of popups, menus, tooltips windows + ImGuiCol_Border, + ImGuiCol_BorderShadow, + ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input + ImGuiCol_FrameBgHovered, + ImGuiCol_FrameBgActive, + ImGuiCol_TitleBg, + ImGuiCol_TitleBgCollapsed, + ImGuiCol_TitleBgActive, + ImGuiCol_MenuBarBg, + ImGuiCol_ScrollbarBg, + ImGuiCol_ScrollbarGrab, + ImGuiCol_ScrollbarGrabHovered, + ImGuiCol_ScrollbarGrabActive, + ImGuiCol_ComboBg, + ImGuiCol_CheckMark, + ImGuiCol_SliderGrab, + ImGuiCol_SliderGrabActive, + ImGuiCol_Button, + ImGuiCol_ButtonHovered, + ImGuiCol_ButtonActive, + ImGuiCol_Header, + ImGuiCol_HeaderHovered, + ImGuiCol_HeaderActive, + ImGuiCol_Column, + ImGuiCol_ColumnHovered, + ImGuiCol_ColumnActive, + ImGuiCol_ResizeGrip, + ImGuiCol_ResizeGripHovered, + ImGuiCol_ResizeGripActive, + ImGuiCol_CloseButton, + ImGuiCol_CloseButtonHovered, + ImGuiCol_CloseButtonActive, + ImGuiCol_PlotLines, + ImGuiCol_PlotLinesHovered, + ImGuiCol_PlotHistogram, + ImGuiCol_PlotHistogramHovered, + ImGuiCol_TextSelectedBg, + ImGuiCol_ModalWindowDarkening, // darken entire screen when a modal window is active + ImGuiCol_COUNT +}; + +// Enumeration for PushStyleVar() / PopStyleVar() +// NB: the enum only refers to fields of ImGuiStyle() which makes sense to be pushed/poped in UI code. Feel free to add others. +enum ImGuiStyleVar_ +{ + ImGuiStyleVar_Alpha, // float + ImGuiStyleVar_WindowPadding, // ImVec2 + ImGuiStyleVar_WindowRounding, // float + ImGuiStyleVar_WindowMinSize, // ImVec2 + ImGuiStyleVar_ChildWindowRounding, // float + ImGuiStyleVar_FramePadding, // ImVec2 + ImGuiStyleVar_FrameRounding, // float + ImGuiStyleVar_ItemSpacing, // ImVec2 + ImGuiStyleVar_ItemInnerSpacing, // ImVec2 + ImGuiStyleVar_IndentSpacing, // float + ImGuiStyleVar_GrabMinSize, // float + ImGuiStyleVar_ButtonTextAlign, // flags ImGuiAlign_* + ImGuiStyleVar_Count_ +}; + +// Enumeration for ColorEditMode() +// FIXME-OBSOLETE: Will be replaced by future color/picker api +enum ImGuiColorEditMode_ +{ + ImGuiColorEditMode_UserSelect = -2, + ImGuiColorEditMode_UserSelectShowButton = -1, + ImGuiColorEditMode_RGB = 0, + ImGuiColorEditMode_HSV = 1, + ImGuiColorEditMode_HEX = 2 +}; + +// Enumeration for GetMouseCursor() +enum ImGuiMouseCursor_ +{ + ImGuiMouseCursor_Arrow = 0, + ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. + ImGuiMouseCursor_Move, // Unused + ImGuiMouseCursor_ResizeNS, // Unused + ImGuiMouseCursor_ResizeEW, // When hovering over a column + ImGuiMouseCursor_ResizeNESW, // Unused + ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window + ImGuiMouseCursor_Count_ +}; + +// Condition flags for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions +// All those functions treat 0 as a shortcut to ImGuiSetCond_Always +enum ImGuiSetCond_ +{ + ImGuiSetCond_Always = 1 << 0, // Set the variable + ImGuiSetCond_Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed) + ImGuiSetCond_FirstUseEver = 1 << 2, // Set the variable if the window has no saved data (if doesn't exist in the .ini file) + ImGuiSetCond_Appearing = 1 << 3 // Set the variable if the window is appearing after being hidden/inactive (or the first time) +}; + +struct ImGuiStyle +{ + float Alpha; // Global alpha applies to everything in ImGui + ImVec2 WindowPadding; // Padding within a window + ImVec2 WindowMinSize; // Minimum window size + float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows + ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered. + float ChildWindowRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows + ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets) + float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). + ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines + ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) + ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! + float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). + float ColumnsMinSpacing; // Minimum horizontal spacing between two columns + float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar + float ScrollbarRounding; // Radius of grab corners for scrollbar + float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar. + float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f,0.5f) for horizontally+vertically centered. + ImVec2 DisplayWindowPadding; // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. + ImVec2 DisplaySafeAreaPadding; // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. + bool AntiAliasedLines; // Enable anti-aliasing on lines/borders. Disable if you are really tight on CPU/GPU. + bool AntiAliasedShapes; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + float CurveTessellationTol; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. + ImVec4 Colors[ImGuiCol_COUNT]; + + IMGUI_API ImGuiStyle(); +}; + +// This is where your app communicate with ImGui. Access via ImGui::GetIO(). +// Read 'Programmer guide' section in .cpp file for general usage. +struct ImGuiIO +{ + //------------------------------------------------------------------ + // Settings (fill once) // Default value: + //------------------------------------------------------------------ + + ImVec2 DisplaySize; // <unset> // Display size, in pixels. For clamping windows positions. + float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. + float IniSavingRate; // = 5.0f // Maximum time between saving positions/sizes to .ini file, in seconds. + const char* IniFilename; // = "imgui.ini" // Path to .ini file. NULL to disable .ini saving. + const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified). + float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. + float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. + float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging + int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array + float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.). + float KeyRepeatRate; // = 0.020f // When holding a key/button, rate at which it repeats, in seconds. + void* UserData; // = NULL // Store your own data for retrieval by callbacks. + + ImFontAtlas* Fonts; // <auto> // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array. + float FontGlobalScale; // = 1.0f // Global scale all fonts + bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. + ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui. + ImVec2 DisplayVisibleMin; // <unset> (0.0f,0.0f) // If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. + ImVec2 DisplayVisibleMax; // <unset> (0.0f,0.0f) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize + + // Advanced/subtle behaviors + bool OSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl + + //------------------------------------------------------------------ + // User Functions + //------------------------------------------------------------------ + + // Rendering function, will be called in Render(). + // Alternatively you can keep this to NULL and call GetDrawData() after Render() to get the same pointer. + // See example applications if you are unsure of how to implement this. + void (*RenderDrawListsFn)(ImDrawData* data); + + // Optional: access OS clipboard + // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) + const char* (*GetClipboardTextFn)(); + void (*SetClipboardTextFn)(const char* text); + + // Optional: override memory allocations. MemFreeFn() may be called with a NULL pointer. + // (default to posix malloc/free) + void* (*MemAllocFn)(size_t sz); + void (*MemFreeFn)(void* ptr); + + // Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME in Windows) + // (default to use native imm32 api on Windows) + void (*ImeSetInputScreenPosFn)(int x, int y); + void* ImeWindowHandle; // (Windows) Set this to your HWND to get automatic IME cursor positioning. + + //------------------------------------------------------------------ + // Input - Fill before calling NewFrame() + //------------------------------------------------------------------ + + ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) + bool MouseDown[5]; // Mouse buttons: left, right, middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API. + float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text. + bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). + bool KeyCtrl; // Keyboard modifier pressed: Control + bool KeyShift; // Keyboard modifier pressed: Shift + bool KeyAlt; // Keyboard modifier pressed: Alt + bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows + bool KeysDown[512]; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data) + ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. + + // Functions + IMGUI_API void AddInputCharacter(ImWchar c); // Helper to add a new character into InputCharacters[] + IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Helper to add new characters into InputCharacters[] from an UTF-8 string + inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Helper to clear the text input buffer + + //------------------------------------------------------------------ + // Output - Retrieve after calling NewFrame(), you can use them to discard inputs or hide them from the rest of your application + //------------------------------------------------------------------ + + bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input) + bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input) + bool WantTextInput; // Some text input widget is active, which will read input characters from the InputCharacters array. + float Framerate; // Framerate estimation, in frame per second. Rolling average estimation based on IO.DeltaTime over 120 frames + int MetricsAllocs; // Number of active memory allocations + int MetricsRenderVertices; // Vertices output during last call to Render() + int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3 + int MetricsActiveWindows; // Number of visible windows (exclude child windows) + + //------------------------------------------------------------------ + // [Internal] ImGui will maintain those fields for you + //------------------------------------------------------------------ + + ImVec2 MousePosPrev; // Previous mouse position + ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are negative to allow mouse enabling/disabling. + bool MouseClicked[5]; // Mouse button went from !Down to Down + ImVec2 MouseClickedPos[5]; // Position at time of clicking + float MouseClickedTime[5]; // Time of last click (used to figure out double-click) + bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? + bool MouseReleased[5]; // Mouse button went from Down to !Down + bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds. + float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked) + float MouseDownDurationPrev[5]; // Previous time the mouse button has been down + float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the click point + float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed) + float KeysDownDurationPrev[512]; // Previous duration the key has been down + + IMGUI_API ImGuiIO(); +}; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +// Lightweight std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug). +// Our implementation does NOT call c++ constructors because we don't use them in ImGui. Don't use this class as a straight std::vector replacement in your code! +template<typename T> +class ImVector +{ +public: + int Size; + int Capacity; + T* Data; + + typedef T value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + + ImVector() { Size = Capacity = 0; Data = NULL; } + ~ImVector() { if (Data) ImGui::MemFree(Data); } + + inline bool empty() const { return Size == 0; } + inline int size() const { return Size; } + inline int capacity() const { return Capacity; } + + inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; } + inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; } + + inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } + inline iterator begin() { return Data; } + inline const_iterator begin() const { return Data; } + inline iterator end() { return Data + Size; } + inline const_iterator end() const { return Data + Size; } + inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; } + inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; } + inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size-1]; } + inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size-1]; } + inline void swap(ImVector<T>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } + + inline int _grow_capacity(int new_size) { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > new_size ? new_capacity : new_size; } + + inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; } + inline void reserve(int new_capacity) + { + if (new_capacity <= Capacity) return; + T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(value_type)); + if (Data) + memcpy(new_data, Data, (size_t)Size * sizeof(value_type)); + ImGui::MemFree(Data); + Data = new_data; + Capacity = new_capacity; + } + + inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size+1)); Data[Size++] = v; } + inline void pop_back() { IM_ASSERT(Size > 0); Size--; } + + inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } + inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; } +}; + +// Helper: execute a block of code at maximum once a frame +// Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. +// Usage: +// IMGUI_ONCE_UPON_A_FRAME +// { +// // code block will be executed one per frame +// } +// Attention! the macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces. +#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf##__LINE__; if (imgui_oaf##__LINE__) +struct ImGuiOnceUponAFrame +{ + ImGuiOnceUponAFrame() { RefFrame = -1; } + mutable int RefFrame; + operator bool() const { int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } +}; + +// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" +struct ImGuiTextFilter +{ + struct TextRange + { + const char* b; + const char* e; + + TextRange() { b = e = NULL; } + TextRange(const char* _b, const char* _e) { b = _b; e = _e; } + const char* begin() const { return b; } + const char* end() const { return e; } + bool empty() const { return b == e; } + char front() const { return *b; } + static bool is_blank(char c) { return c == ' ' || c == '\t'; } + void trim_blanks() { while (b < e && is_blank(*b)) b++; while (e > b && is_blank(*(e-1))) e--; } + IMGUI_API void split(char separator, ImVector<TextRange>& out); + }; + + char InputBuf[256]; + ImVector<TextRange> Filters; + int CountGrep; + + ImGuiTextFilter(const char* default_filter = ""); + ~ImGuiTextFilter() {} + void Clear() { InputBuf[0] = 0; Build(); } + bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build + bool PassFilter(const char* text, const char* text_end = NULL) const; + bool IsActive() const { return !Filters.empty(); } + IMGUI_API void Build(); +}; + +// Helper: Text buffer for logging/accumulating text +struct ImGuiTextBuffer +{ + ImVector<char> Buf; + + ImGuiTextBuffer() { Buf.push_back(0); } + inline char operator[](int i) { return Buf.Data[i]; } + const char* begin() const { return &Buf.front(); } + const char* end() const { return &Buf.back(); } // Buf is zero-terminated, so end() will point on the zero-terminator + int size() const { return Buf.Size - 1; } + bool empty() { return Buf.Size <= 1; } + void clear() { Buf.clear(); Buf.push_back(0); } + const char* c_str() const { return Buf.Data; } + IMGUI_API void append(const char* fmt, ...) IM_PRINTFARGS(2); + IMGUI_API void appendv(const char* fmt, va_list args); +}; + +// Helper: Simple Key->value storage +// - Store collapse state for a tree (Int 0/1) +// - Store color edit options (Int using values in ImGuiColorEditMode enum). +// - Custom user storage for temporary values. +// Typically you don't have to worry about this since a storage is held within each Window. +// Declare your own storage if: +// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). +// - You want to store custom debug data easily without adding or editing structures in your code. +// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types. +struct ImGuiStorage +{ + struct Pair + { + ImGuiID key; + union { int val_i; float val_f; void* val_p; }; + Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } + Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } + Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } + }; + ImVector<Pair> Data; + + // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) + // - Set***() functions find pair, insertion on demand if missing. + // - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair. + IMGUI_API void Clear(); + IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; + IMGUI_API void SetInt(ImGuiID key, int val); + IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const; + IMGUI_API void SetBool(ImGuiID key, bool val); + IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; + IMGUI_API void SetFloat(ImGuiID key, float val); + IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL + IMGUI_API void SetVoidPtr(ImGuiID key, void* val); + + // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. + // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. + // - A typical use case where this is convenient: + // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; + // - You can also use this to quickly create temporary editable values during a session of using Edit&Continue, without restarting your application. + IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); + IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false); + IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f); + IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL); + + // Use on your own storage if you know only integer are being stored (open/close all tree nodes) + IMGUI_API void SetAllInt(int val); +}; + +// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the corresponding callback is triggered. +struct ImGuiTextEditCallbackData +{ + ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only + ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only + void* UserData; // What user passed to InputText() // Read-only + bool ReadOnly; // Read-only mode // Read-only + + // CharFilter event: + ImWchar EventChar; // Character input // Read-write (replace character or set to zero) + + // Completion,History,Always events: + // If you modify the buffer contents make sure you update 'BufTextLen' and set 'BufDirty' to true. + ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only + char* Buf; // Current text buffer // Read-write (pointed data only, can't replace the actual pointer) + int BufTextLen; // Current text length in bytes // Read-write + int BufSize; // Maximum text length in bytes // Read-only + bool BufDirty; // Set if you modify Buf/BufTextLen!! // Write + int CursorPos; // // Read-write + int SelectionStart; // // Read-write (== to SelectionEnd when no selection) + int SelectionEnd; // // Read-write + + // NB: Helper functions for text manipulation. Calling those function loses selection. + void DeleteChars(int pos, int bytes_count); + void InsertChars(int pos, const char* text, const char* text_end = NULL); + bool HasSelection() const { return SelectionStart != SelectionEnd; } +}; + +// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin(). +// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough. +struct ImGuiSizeConstraintCallbackData +{ + void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints() + ImVec2 Pos; // Read-only. Window position, for reference. + ImVec2 CurrentSize; // Read-only. Current window size. + ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing. +}; + +// Helpers macros to generate 32-bits encoded colors +#ifdef IMGUI_USE_BGRA_PACKED_COLOR +#define IM_COL32_R_SHIFT 16 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 0 +#define IM_COL32_A_SHIFT 24 +#else +#define IM_COL32_R_SHIFT 0 +#define IM_COL32_G_SHIFT 8 +#define IM_COL32_B_SHIFT 16 +#define IM_COL32_A_SHIFT 24 +#endif +#define IM_COL32(R,G,B,A) (((ImU32)(A)<<IM_COL32_A_SHIFT) | ((ImU32)(B)<<IM_COL32_B_SHIFT) | ((ImU32)(G)<<IM_COL32_G_SHIFT) | ((ImU32)(R)<<IM_COL32_R_SHIFT)) +#define IM_COL32_WHITE IM_COL32(255,255,255,255) // Opaque white +#define IM_COL32_BLACK IM_COL32(0,0,0,255) // Opaque black +#define IM_COL32_BLACK_TRANS IM_COL32(0,0,0,0) // Transparent black + +// ImColor() helper to implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) +// Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API. +// Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. +// None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. +struct ImColor +{ + ImVec4 Value; + + ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; } + ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; } + ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; } + ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } + ImColor(const ImVec4& col) { Value = col; } + inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } + inline operator ImVec4() const { return Value; } + + inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; } + + static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } +}; + +// Helper: Manually clip large list of items. +// If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse clipping based on visibility to save yourself from processing those items at all. +// The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we have skipped. +// ImGui already clip items based on their bounds but it needs to measure text size to do so. Coarse clipping before submission makes this cost and your own data fetching/submission cost null. +// Usage: +// ImGuiListClipper clipper(1000); // we have 1000 elements, evenly spaced. +// while (clipper.Step()) +// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) +// ImGui::Text("line number %d", i); +// - Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height (step skipped if we passed a known height as second arg to constructor). +// - Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. +// - (Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user call Step(). Does nothing and switch to Step 3.) +// - Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. +struct ImGuiListClipper +{ + float StartPosY; + float ItemsHeight; + int ItemsCount, StepNo, DisplayStart, DisplayEnd; + + // items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step). + // items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetItemsLineHeightWithSpacing(). + // If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step(). + ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want). + ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false. + + IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items. + IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. + IMGUI_API void End(); // Automatically called on the last call of Step() that returns false. +}; + +//----------------------------------------------------------------------------- +// Draw List +// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList. +//----------------------------------------------------------------------------- + +// Draw callbacks for advanced uses. +// NB- You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering (you can poke into the draw list for that) +// Draw callback may be useful for example, A) Change your GPU render state, B) render a complex 3D scene inside a UI element (without an intermediate texture/render target), etc. +// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) cmd.UserCallback(parent_list, cmd); else RenderTriangles()' +typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); + +// Typically, 1 command = 1 gpu draw call (unless command is a callback) +struct ImDrawCmd +{ + unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[]. + ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2) + ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. + ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally. + void* UserCallbackData; // The draw callback code can access this. + + ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = -8192.0f; ClipRect.z = ClipRect.w = +8192.0f; TextureId = NULL; UserCallback = NULL; UserCallbackData = NULL; } +}; + +// Vertex index (override with '#define ImDrawIdx unsigned int' inside in imconfig.h) +#ifndef ImDrawIdx +typedef unsigned short ImDrawIdx; +#endif + +// Vertex layout +#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT +struct ImDrawVert +{ + ImVec2 pos; + ImVec2 uv; + ImU32 col; +}; +#else +// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h +// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. +// The type has to be described within the macro (you can either declare the struct or use a typedef) +IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; +#endif + +// Draw channels are used by the Columns API to "split" the render list into different channels while building, so items of each column can be batched together. +// You can also use them to simulate drawing layers and submit primitives in a different order than how they will be rendered. +struct ImDrawChannel +{ + ImVector<ImDrawCmd> CmdBuffer; + ImVector<ImDrawIdx> IdxBuffer; +}; + +// Draw command list +// This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. +// At the moment, each ImGui window contains its own ImDrawList but they could potentially be merged in the future. +// If you want to add custom rendering within a window, you can use ImGui::GetWindowDrawList() to access the current draw list and add your own primitives. +// You can interleave normal ImGui:: calls and adding primitives to the current draw list. +// All positions are in screen coordinates (0,0=top-left, 1 pixel per unit). Primitives are always added to the list and not culled (culling is done at render time and at a higher-level by ImGui:: functions). +struct ImDrawList +{ + // This is what you have to render + ImVector<ImDrawCmd> CmdBuffer; // Commands. Typically 1 command = 1 gpu draw call. + ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those + ImVector<ImDrawVert> VtxBuffer; // Vertex buffer. + + // [Internal, used while building lists] + const char* _OwnerName; // Pointer to owner window's name (if any) for debugging + unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size + ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much) + ImVector<ImVec4> _ClipRectStack; // [Internal] + ImVector<ImTextureID> _TextureIdStack; // [Internal] + ImVector<ImVec2> _Path; // [Internal] current path building + int _ChannelsCurrent; // [Internal] current channel number (0) + int _ChannelsCount; // [Internal] number of active channels (1+) + ImVector<ImDrawChannel> _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size) + + ImDrawList() { _OwnerName = NULL; Clear(); } + ~ImDrawList() { ClearFreeMemory(); } + IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) + IMGUI_API void PushClipRectFullScreen(); + IMGUI_API void PopClipRect(); + IMGUI_API void PushTextureID(const ImTextureID& texture_id); + IMGUI_API void PopTextureID(); + + // Primitives + IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F, float thickness = 1.0f); // a: upper-left, b: lower-right + IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners = 0x0F); // a: upper-left, b: lower-right + IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left); + IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col); + IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f); + IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); + IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f); + IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); + IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL); + IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL); + IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), ImU32 col = 0xFFFFFFFF); + IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness, bool anti_aliased); + IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col, bool anti_aliased); + IMGUI_API void AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0); + + // Stateful path API, add points then finish with PathFill() or PathStroke() + inline void PathClear() { _Path.resize(0); } + inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); } + inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); } + inline void PathFill(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col, true); PathClear(); } + inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness, true); PathClear(); } + IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10); + IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle + IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0); + IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners = 0x0F); + + // Channels + // - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives) + // - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end) + IMGUI_API void ChannelsSplit(int channels_count); + IMGUI_API void ChannelsMerge(); + IMGUI_API void ChannelsSetCurrent(int channel_index); + + // Advanced + IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles. + IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible + + // Internal helpers + // NB: all primitives needs to be reserved via PrimReserve() beforehand! + IMGUI_API void Clear(); + IMGUI_API void ClearFreeMemory(); + IMGUI_API void PrimReserve(int idx_count, int vtx_count); + IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles) + IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col); + IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col); + inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; } + inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; } + inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); } + IMGUI_API void UpdateClipRect(); + IMGUI_API void UpdateTextureID(); +}; + +// All draw data to render an ImGui frame +struct ImDrawData +{ + bool Valid; // Only valid after Render() is called and before the next NewFrame() is called. + ImDrawList** CmdLists; + int CmdListsCount; + int TotalVtxCount; // For convenience, sum of all cmd_lists vtx_buffer.Size + int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size + + // Functions + ImDrawData() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; } + IMGUI_API void DeIndexAllBuffers(); // For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! + IMGUI_API void ScaleClipRects(const ImVec2& sc); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +}; + +struct ImFontConfig +{ + void* FontData; // // TTF data + int FontDataSize; // // TTF data size + bool FontDataOwnedByAtlas; // true // TTF data ownership taken by the container ImFontAtlas (will delete memory itself). Set to true + int FontNo; // 0 // Index of font within TTF file + float SizePixels; // // Size in pixels for rasterizer + int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis. + bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1. + ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs + const ImWchar* GlyphRanges; // // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE. + bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). + bool MergeGlyphCenterV; // false // When merging (multiple ImFontInput for one ImFont), vertically center new glyphs instead of aligning their baseline + + // [Internal] + char Name[32]; // Name (strictly for debugging) + ImFont* DstFont; + + IMGUI_API ImFontConfig(); +}; + +// Load and rasterize multiple TTF fonts into a same texture. +// Sharing a texture for multiple fonts allows us to reduce the number of draw calls during rendering. +// We also add custom graphic data into the texture that serves for ImGui. +// 1. (Optional) Call AddFont*** functions. If you don't call any, the default font will be loaded for you. +// 2. Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. +// 3. Upload the pixels data into a texture within your graphics system. +// 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture. +// 5. Call ClearTexData() to free textures memory on the heap. +// NB: If you use a 'glyph_ranges' array you need to make sure that your array persist up until the ImFont is cleared. We only copy the pointer, not the data. +struct ImFontAtlas +{ + IMGUI_API ImFontAtlas(); + IMGUI_API ~ImFontAtlas(); + IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg); + IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL); + IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); + IMGUI_API ImFont* AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Transfer ownership of 'ttf_data' to ImFontAtlas, will be deleted after Build() + IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data' still owned by caller. Compress with binary_to_compressed_c.cpp + IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_ttf_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 paramaeter + IMGUI_API void ClearTexData(); // Clear the CPU-side texture data. Saves RAM once the texture has been copied to graphics memory. + IMGUI_API void ClearInputData(); // Clear the input TTF data (inc sizes, glyph ranges) + IMGUI_API void ClearFonts(); // Clear the ImGui-side font data (glyphs storage, UV coordinates) + IMGUI_API void Clear(); // Clear all + + // Retrieve texture data + // User is in charge of copying the pixels into graphics memory, then call SetTextureUserID() + // After loading the texture into your graphic system, store your texture handle in 'TexID' (ignore if you aren't using multiple fonts nor images) + // RGBA32 format is provided for convenience and high compatibility, but note that all RGB pixels are white, so 75% of the memory is wasted. + // Pitch = Width * BytesPerPixels + IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel + IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel + void SetTexID(void* id) { TexID = id; } + + // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) + // NB: Make sure that your string are UTF-8 and NOT in your local code page. See FAQ for details. + IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin + IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters + IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs + IMGUI_API const ImWchar* GetGlyphRangesChinese(); // Japanese + full set of about 21000 CJK Unified Ideographs + IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters + IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters + + // Members + // (Access texture data via GetTexData*() calls which will setup a default font for you.) + void* TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It ia passed back to you during rendering. + unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight + unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 + int TexWidth; // Texture width calculated during Build(). + int TexHeight; // Texture height calculated during Build(). + int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height. + ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel + ImVector<ImFont*> Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font. + + // Private + ImVector<ImFontConfig> ConfigData; // Internal data + IMGUI_API bool Build(); // Build pixels data. This is automatically for you by the GetTexData*** functions. + IMGUI_API void RenderCustomTexData(int pass, void* rects); +}; + +// Font runtime data and rendering +// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). +struct ImFont +{ + struct Glyph + { + ImWchar Codepoint; + float XAdvance; + float X0, Y0, X1, Y1; + float U0, V0, U1, V1; // Texture coordinates + }; + + // Members: Hot ~62/78 bytes + float FontSize; // <user set> // Height of characters, set during loading (don't change after loading) + float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() + ImVec2 DisplayOffset; // = (0.f,1.f) // Offset font rendering by xx pixels + ImVector<Glyph> Glyphs; // // All glyphs. + ImVector<float> IndexXAdvance; // // Sparse. Glyphs->XAdvance in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI). + ImVector<unsigned short> IndexLookup; // // Sparse. Index glyphs by Unicode code-point. + const Glyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) + float FallbackXAdvance; // == FallbackGlyph->XAdvance + ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() + + // Members: Cold ~18/26 bytes + short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont. + ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData + ImFontAtlas* ContainerAtlas; // // What we has been loaded into + float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize] + + // Methods + IMGUI_API ImFont(); + IMGUI_API ~ImFont(); + IMGUI_API void Clear(); + IMGUI_API void BuildLookupTable(); + IMGUI_API const Glyph* FindGlyph(ImWchar c) const; + IMGUI_API void SetFallbackChar(ImWchar c); + float GetCharAdvance(ImWchar c) const { return ((int)c < IndexXAdvance.Size) ? IndexXAdvance[(int)c] : FallbackXAdvance; } + bool IsLoaded() const { return ContainerAtlas != NULL; } + + // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. + // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. + IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 + IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; + IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const; + IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const; + + // Private + IMGUI_API void GrowIndex(int new_size); + IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built. +}; + +#if defined(__clang__) +#pragma clang diagnostic pop +#endif + +//---- Include imgui_user.h at the end of imgui.h +//---- So you can include code that extends ImGui using any of the types declared above. +//---- (also convenient for user to only explicitly include vanilla imgui.h) +#ifdef IMGUI_INCLUDE_IMGUI_USER_H +#include "imgui_user.h" +#endif diff --git a/include/imgui_impl_glfw.h b/include/imgui_impl_glfw.h new file mode 100644 index 0000000..07dd96f --- /dev/null +++ b/include/imgui_impl_glfw.h @@ -0,0 +1,29 @@ +// ImGui GLFW binding with OpenGL +// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. + +// If your context is GL3/GL3 then prefer using the code in opengl3_example. +// You *might* use this code with a GL3/GL4 context but make sure you disable the programmable pipeline by calling "glUseProgram(0)" before ImGui::Render(). +// We cannot do that from GL2 code because the function doesn't exist. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). +// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. +// https://github.com/ocornut/imgui + +struct GLFWwindow; + +IMGUI_API bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks); +IMGUI_API void ImGui_ImplGlfw_Shutdown(); +IMGUI_API void ImGui_ImplGlfw_NewFrame(); + +// Use if you want to reset your rendering device without losing ImGui state. +IMGUI_API void ImGui_ImplGlfw_InvalidateDeviceObjects(); +IMGUI_API bool ImGui_ImplGlfw_CreateDeviceObjects(); + +// GLFW callbacks (installed by default if you enable 'install_callbacks' during initialization) +// Provided here if you want to chain callbacks. +// You can also handle inputs yourself and use those as a reference. +IMGUI_API void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); +IMGUI_API void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset); +IMGUI_API void ImGui_ImplGlFw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); +IMGUI_API void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c); diff --git a/include/imgui_impl_glfw_gl3.h b/include/imgui_impl_glfw_gl3.h new file mode 100644 index 0000000..83c69aa --- /dev/null +++ b/include/imgui_impl_glfw_gl3.h @@ -0,0 +1,25 @@ +// ImGui GLFW binding with OpenGL3 + shaders +// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). +// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. +// https://github.com/ocornut/imgui + +struct GLFWwindow; + +IMGUI_API bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks); +IMGUI_API void ImGui_ImplGlfwGL3_Shutdown(); +IMGUI_API void ImGui_ImplGlfwGL3_NewFrame(); + +// Use if you want to reset your rendering device without losing ImGui state. +IMGUI_API void ImGui_ImplGlfwGL3_InvalidateDeviceObjects(); +IMGUI_API bool ImGui_ImplGlfwGL3_CreateDeviceObjects(); + +// GLFW callbacks (installed by default if you enable 'install_callbacks' during initialization) +// Provided here if you want to chain callbacks. +// You can also handle inputs yourself and use those as a reference. +IMGUI_API void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); +IMGUI_API void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset); +IMGUI_API void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); +IMGUI_API void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow* window, unsigned int c); diff --git a/include/imgui_internal.h b/include/imgui_internal.h new file mode 100644 index 0000000..4bfec9d --- /dev/null +++ b/include/imgui_internal.h @@ -0,0 +1,760 @@ +// dear imgui, v1.50 WIP +// (internals) + +// You may use this file to debug, understand or extend ImGui features but we don't provide any guarantee of forward compatibility! +// Implement maths operators for ImVec2 (disabled by default to not collide with using IM_VEC2_CLASS_EXTRA along with your own math types+operators) +// #define IMGUI_DEFINE_MATH_OPERATORS + +#pragma once + +#ifndef IMGUI_VERSION +#error Must include imgui.h before imgui_internal.h +#endif + +#include <stdio.h> // FILE* +#include <math.h> // sqrtf, fabsf, fmodf, powf, floorf, ceilf, cosf, sinf + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4251) // class 'xxx' needs to have dll-interface to be used by clients of struct 'xxx' // when IMGUI_API is set to__declspec(dllexport) +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-function" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wmissing-prototypes" // for stb_textedit.h +#pragma clang diagnostic ignored "-Wold-style-cast" +#endif + +//----------------------------------------------------------------------------- +// Forward Declarations +//----------------------------------------------------------------------------- + +struct ImRect; +struct ImGuiColMod; +struct ImGuiStyleMod; +struct ImGuiGroupData; +struct ImGuiSimpleColumns; +struct ImGuiDrawContext; +struct ImGuiTextEditState; +struct ImGuiIniData; +struct ImGuiMouseCursorData; +struct ImGuiPopupRef; +struct ImGuiWindow; + +typedef int ImGuiLayoutType; // enum ImGuiLayoutType_ +typedef int ImGuiButtonFlags; // enum ImGuiButtonFlags_ +typedef int ImGuiTreeNodeFlags; // enum ImGuiTreeNodeFlags_ +typedef int ImGuiSliderFlags; // enum ImGuiSliderFlags_ + +//------------------------------------------------------------------------- +// STB libraries +//------------------------------------------------------------------------- + +namespace ImGuiStb +{ + +#undef STB_TEXTEDIT_STRING +#undef STB_TEXTEDIT_CHARTYPE +#define STB_TEXTEDIT_STRING ImGuiTextEditState +#define STB_TEXTEDIT_CHARTYPE ImWchar +#define STB_TEXTEDIT_GETWIDTH_NEWLINE -1.0f +#include "stb_textedit.h" + +} // namespace ImGuiStb + +//----------------------------------------------------------------------------- +// Context +//----------------------------------------------------------------------------- + +extern IMGUI_API ImGuiContext* GImGui; // current implicit ImGui context pointer + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) +#define IM_PI 3.14159265358979323846f +#define IM_OFFSETOF(_TYPE,_ELM) ((size_t)&(((_TYPE*)0)->_ELM)) + +// Helpers: UTF-8 <> wchar +IMGUI_API int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count +IMGUI_API int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count +IMGUI_API int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count +IMGUI_API int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) +IMGUI_API int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points + +// Helpers: Misc +IMGUI_API ImU32 ImHash(const void* data, int data_size, ImU32 seed = 0); // Pass data_size==0 for zero-terminated strings +IMGUI_API void* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size = NULL, int padding_bytes = 0); +IMGUI_API bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c); +static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; } +static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } + +// Helpers: String +IMGUI_API int ImStricmp(const char* str1, const char* str2); +IMGUI_API int ImStrnicmp(const char* str1, const char* str2, int count); +IMGUI_API char* ImStrdup(const char* str); +IMGUI_API int ImStrlenW(const ImWchar* str); +IMGUI_API const ImWchar*ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin); // Find beginning-of-line +IMGUI_API const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end); +IMGUI_API int ImFormatString(char* buf, int buf_size, const char* fmt, ...) IM_PRINTFARGS(3); +IMGUI_API int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args); + +// Helpers: Math +// We are keeping those not leaking to the user by default, in the case the user has implicit cast operators between ImVec2 and its own types (when IM_VEC2_CLASS_EXTRA is defined) +#ifdef IMGUI_DEFINE_MATH_OPERATORS +static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); } +static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); } +static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); } +static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); } +static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); } +static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); } +static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } +static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } +static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } +static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } +static inline ImVec4 operator-(const ImVec4& lhs, const ImVec4& rhs) { return ImVec4(lhs.x-rhs.x, lhs.y-rhs.y, lhs.z-rhs.z, lhs.w-rhs.w); } +#endif + +static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } +static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } +static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } +static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } +static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); } +static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); } +static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } +static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); } +static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } +static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; } +static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } +static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } +static inline float ImLengthSqr(const ImVec4& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z + lhs.w*lhs.w; } +static inline float ImInvLength(const ImVec2& lhs, float fail_value) { float d = lhs.x*lhs.x + lhs.y*lhs.y; if (d > 0.0f) return 1.0f / sqrtf(d); return fail_value; } +static inline float ImFloor(float f) { return (float)(int)f; } +static inline ImVec2 ImFloor(ImVec2 v) { return ImVec2((float)(int)v.x, (float)(int)v.y); } + +// We call C++ constructor on own allocated memory via the placement "new(ptr) Type()" syntax. +// Defining a custom placement new() with a dummy parameter allows us to bypass including <new> which on some platforms complains when user has disabled exceptions. +#ifdef IMGUI_DEFINE_PLACEMENT_NEW +struct ImPlacementNewDummy {}; +inline void* operator new(size_t, ImPlacementNewDummy, void* ptr) { return ptr; } +inline void operator delete(void*, ImPlacementNewDummy, void*) {} +#define IM_PLACEMENT_NEW(_PTR) new(ImPlacementNewDummy(), _PTR) +#endif + +//----------------------------------------------------------------------------- +// Types +//----------------------------------------------------------------------------- + +enum ImGuiButtonFlags_ +{ + ImGuiButtonFlags_Repeat = 1 << 0, // hold to repeat + ImGuiButtonFlags_PressedOnClickRelease = 1 << 1, // (default) return pressed on click+release on same item (default if no PressedOn** flag is set) + ImGuiButtonFlags_PressedOnClick = 1 << 2, // return pressed on click (default requires click+release) + ImGuiButtonFlags_PressedOnRelease = 1 << 3, // return pressed on release (default requires click+release) + ImGuiButtonFlags_PressedOnDoubleClick = 1 << 4, // return pressed on double-click (default requires click+release) + ImGuiButtonFlags_FlattenChilds = 1 << 5, // allow interaction even if a child window is overlapping + ImGuiButtonFlags_DontClosePopups = 1 << 6, // disable automatically closing parent popup on press + ImGuiButtonFlags_Disabled = 1 << 7, // disable interaction + ImGuiButtonFlags_AlignTextBaseLine = 1 << 8, // vertically align button to match text baseline - ButtonEx() only + ImGuiButtonFlags_NoKeyModifiers = 1 << 9, // disable interaction if a key modifier is held + ImGuiButtonFlags_AllowOverlapMode = 1 << 10 // require previous frame HoveredId to either match id or be null before being usable +}; + +enum ImGuiSliderFlags_ +{ + ImGuiSliderFlags_Vertical = 1 << 0 +}; + +enum ImGuiSelectableFlagsPrivate_ +{ + // NB: need to be in sync with last value of ImGuiSelectableFlags_ + ImGuiSelectableFlags_Menu = 1 << 3, + ImGuiSelectableFlags_MenuItem = 1 << 4, + ImGuiSelectableFlags_Disabled = 1 << 5, + ImGuiSelectableFlags_DrawFillAvailWidth = 1 << 6 +}; + +// FIXME: this is in development, not exposed/functional as a generic feature yet. +enum ImGuiLayoutType_ +{ + ImGuiLayoutType_Vertical, + ImGuiLayoutType_Horizontal +}; + +enum ImGuiPlotType +{ + ImGuiPlotType_Lines, + ImGuiPlotType_Histogram +}; + +enum ImGuiDataType +{ + ImGuiDataType_Int, + ImGuiDataType_Float, + ImGuiDataType_Float2, +}; + +// 2D axis aligned bounding-box +// NB: we can't rely on ImVec2 math operators being available here +struct IMGUI_API ImRect +{ + ImVec2 Min; // Upper-left + ImVec2 Max; // Lower-right + + ImRect() : Min(FLT_MAX,FLT_MAX), Max(-FLT_MAX,-FLT_MAX) {} + ImRect(const ImVec2& min, const ImVec2& max) : Min(min), Max(max) {} + ImRect(const ImVec4& v) : Min(v.x, v.y), Max(v.z, v.w) {} + ImRect(float x1, float y1, float x2, float y2) : Min(x1, y1), Max(x2, y2) {} + + ImVec2 GetCenter() const { return ImVec2((Min.x+Max.x)*0.5f, (Min.y+Max.y)*0.5f); } + ImVec2 GetSize() const { return ImVec2(Max.x-Min.x, Max.y-Min.y); } + float GetWidth() const { return Max.x-Min.x; } + float GetHeight() const { return Max.y-Min.y; } + ImVec2 GetTL() const { return Min; } // Top-left + ImVec2 GetTR() const { return ImVec2(Max.x, Min.y); } // Top-right + ImVec2 GetBL() const { return ImVec2(Min.x, Max.y); } // Bottom-left + ImVec2 GetBR() const { return Max; } // Bottom-right + bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } + bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; } + bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } + void Add(const ImVec2& rhs) { if (Min.x > rhs.x) Min.x = rhs.x; if (Min.y > rhs.y) Min.y = rhs.y; if (Max.x < rhs.x) Max.x = rhs.x; if (Max.y < rhs.y) Max.y = rhs.y; } + void Add(const ImRect& rhs) { if (Min.x > rhs.Min.x) Min.x = rhs.Min.x; if (Min.y > rhs.Min.y) Min.y = rhs.Min.y; if (Max.x < rhs.Max.x) Max.x = rhs.Max.x; if (Max.y < rhs.Max.y) Max.y = rhs.Max.y; } + void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } + void Expand(const ImVec2& amount) { Min.x -= amount.x; Min.y -= amount.y; Max.x += amount.x; Max.y += amount.y; } + void Reduce(const ImVec2& amount) { Min.x += amount.x; Min.y += amount.y; Max.x -= amount.x; Max.y -= amount.y; } + void Clip(const ImRect& clip) { if (Min.x < clip.Min.x) Min.x = clip.Min.x; if (Min.y < clip.Min.y) Min.y = clip.Min.y; if (Max.x > clip.Max.x) Max.x = clip.Max.x; if (Max.y > clip.Max.y) Max.y = clip.Max.y; } + void Floor() { Min.x = (float)(int)Min.x; Min.y = (float)(int)Min.y; Max.x = (float)(int)Max.x; Max.y = (float)(int)Max.y; } + ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const + { + if (!on_edge && Contains(p)) + return p; + if (p.x > Max.x) p.x = Max.x; + else if (p.x < Min.x) p.x = Min.x; + if (p.y > Max.y) p.y = Max.y; + else if (p.y < Min.y) p.y = Min.y; + return p; + } +}; + +// Stacked color modifier, backup of modified data so we can restore it +struct ImGuiColMod +{ + ImGuiCol Col; + ImVec4 BackupValue; +}; + +// Stacked style modifier, backup of modified data so we can restore it. Data type inferred from the variable. +struct ImGuiStyleMod +{ + ImGuiStyleVar VarIdx; + union { int BackupInt[2]; float BackupFloat[2]; }; + ImGuiStyleMod(ImGuiStyleVar idx, int v) { VarIdx = idx; BackupInt[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, float v) { VarIdx = idx; BackupFloat[0] = v; } + ImGuiStyleMod(ImGuiStyleVar idx, ImVec2 v) { VarIdx = idx; BackupFloat[0] = v.x; BackupFloat[1] = v.y; } +}; + +// Stacked data for BeginGroup()/EndGroup() +struct ImGuiGroupData +{ + ImVec2 BackupCursorPos; + ImVec2 BackupCursorMaxPos; + float BackupIndentX; + float BackupGroupOffsetX; + float BackupCurrentLineHeight; + float BackupCurrentLineTextBaseOffset; + float BackupLogLinePosY; + bool BackupActiveIdIsAlive; + bool AdvanceCursor; +}; + +// Per column data for Columns() +struct ImGuiColumnData +{ + float OffsetNorm; // Column start offset, normalized 0.0 (far left) -> 1.0 (far right) + //float IndentX; +}; + +// Simple column measurement currently used for MenuItem() only. This is very short-sighted/throw-away code and NOT a generic helper. +struct IMGUI_API ImGuiSimpleColumns +{ + int Count; + float Spacing; + float Width, NextWidth; + float Pos[8], NextWidths[8]; + + ImGuiSimpleColumns(); + void Update(int count, float spacing, bool clear); + float DeclColumns(float w0, float w1, float w2); + float CalcExtraSpace(float avail_w); +}; + +// Internal state of the currently focused/edited text input box +struct IMGUI_API ImGuiTextEditState +{ + ImGuiID Id; // widget id owning the text state + ImVector<ImWchar> Text; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. + ImVector<char> InitialText; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) + ImVector<char> TempTextBuffer; + int CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. + int BufSizeA; // end-user buffer size + float ScrollX; + ImGuiStb::STB_TexteditState StbState; + float CursorAnim; + bool CursorFollow; + bool SelectedAllMouseLock; + + ImGuiTextEditState() { memset(this, 0, sizeof(*this)); } + void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking + void CursorClamp() { StbState.cursor = ImMin(StbState.cursor, CurLenW); StbState.select_start = ImMin(StbState.select_start, CurLenW); StbState.select_end = ImMin(StbState.select_end, CurLenW); } + bool HasSelection() const { return StbState.select_start != StbState.select_end; } + void ClearSelection() { StbState.select_start = StbState.select_end = StbState.cursor; } + void SelectAll() { StbState.select_start = 0; StbState.select_end = CurLenW; StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } + void OnKeyPressed(int key); +}; + +// Data saved in imgui.ini file +struct ImGuiIniData +{ + char* Name; + ImGuiID Id; + ImVec2 Pos; + ImVec2 Size; + bool Collapsed; +}; + +// Mouse cursor data (used when io.MouseDrawCursor is set) +struct ImGuiMouseCursorData +{ + ImGuiMouseCursor Type; + ImVec2 HotOffset; + ImVec2 Size; + ImVec2 TexUvMin[2]; + ImVec2 TexUvMax[2]; +}; + +// Storage for current popup stack +struct ImGuiPopupRef +{ + ImGuiID PopupId; // Set on OpenPopup() + ImGuiWindow* Window; // Resolved on BeginPopup() - may stay unresolved if user never calls OpenPopup() + ImGuiWindow* ParentWindow; // Set on OpenPopup() + ImGuiID ParentMenuSet; // Set on OpenPopup() + ImVec2 MousePosOnOpen; // Copy of mouse position at the time of opening popup + + ImGuiPopupRef(ImGuiID id, ImGuiWindow* parent_window, ImGuiID parent_menu_set, const ImVec2& mouse_pos) { PopupId = id; Window = NULL; ParentWindow = parent_window; ParentMenuSet = parent_menu_set; MousePosOnOpen = mouse_pos; } +}; + +// Main state for ImGui +struct ImGuiContext +{ + bool Initialized; + ImGuiIO IO; + ImGuiStyle Style; + ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() + float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize() + float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters. + ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvWhitePixel + + float Time; + int FrameCount; + int FrameCountEnded; + int FrameCountRendered; + ImVector<ImGuiWindow*> Windows; + ImVector<ImGuiWindow*> WindowsSortBuffer; + ImGuiWindow* CurrentWindow; // Being drawn into + ImVector<ImGuiWindow*> CurrentWindowStack; + ImGuiWindow* FocusedWindow; // Will catch keyboard inputs + ImGuiWindow* HoveredWindow; // Will catch mouse inputs + ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) + ImGuiID HoveredId; // Hovered widget + bool HoveredIdAllowOverlap; + ImGuiID HoveredIdPreviousFrame; + ImGuiID ActiveId; // Active widget + ImGuiID ActiveIdPreviousFrame; + bool ActiveIdIsAlive; + bool ActiveIdIsJustActivated; // Set at the time of activation for one frame + bool ActiveIdAllowOverlap; // Set only by active widget + ImVec2 ActiveIdClickOffset; // Clicked offset from upper-left corner, if applicable (currently only set by ButtonBehavior) + ImGuiWindow* ActiveIdWindow; + ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window. + ImGuiID MovedWindowMoveId; // == MovedWindow->RootWindow->MoveId + ImVector<ImGuiIniData> Settings; // .ini Settings + float SettingsDirtyTimer; // Save .ini Settings on disk when time reaches zero + ImVector<ImGuiColMod> ColorModifiers; // Stack for PushStyleColor()/PopStyleColor() + ImVector<ImGuiStyleMod> StyleModifiers; // Stack for PushStyleVar()/PopStyleVar() + ImVector<ImFont*> FontStack; // Stack for PushFont()/PopFont() + ImVector<ImGuiPopupRef> OpenPopupStack; // Which popups are open (persistent) + ImVector<ImGuiPopupRef> CurrentPopupStack; // Which level of BeginPopup() we are in (reset every frame) + + // Storage for SetNexWindow** and SetNextTreeNode*** functions + ImVec2 SetNextWindowPosVal; + ImVec2 SetNextWindowSizeVal; + ImVec2 SetNextWindowContentSizeVal; + bool SetNextWindowCollapsedVal; + ImGuiSetCond SetNextWindowPosCond; + ImGuiSetCond SetNextWindowSizeCond; + ImGuiSetCond SetNextWindowContentSizeCond; + ImGuiSetCond SetNextWindowCollapsedCond; + ImRect SetNextWindowSizeConstraintRect; // Valid if 'SetNextWindowSizeConstraint' is true + ImGuiSizeConstraintCallback SetNextWindowSizeConstraintCallback; + void* SetNextWindowSizeConstraintCallbackUserData; + bool SetNextWindowSizeConstraint; + bool SetNextWindowFocus; + bool SetNextTreeNodeOpenVal; + ImGuiSetCond SetNextTreeNodeOpenCond; + + // Render + ImDrawData RenderDrawData; // Main ImDrawData instance to pass render information to the user + ImVector<ImDrawList*> RenderDrawLists[3]; + float ModalWindowDarkeningRatio; + ImDrawList OverlayDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set + a few debug overlays + ImGuiMouseCursor MouseCursor; + ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_]; + + // Widget state + ImGuiTextEditState InputTextState; + ImFont InputTextPasswordFont; + ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. + ImGuiStorage ColorEditModeStorage; // Store user selection of color edit mode + float DragCurrentValue; // Currently dragged value, always float, not rounded by end-user precision settings + ImVec2 DragLastMouseDelta; + float DragSpeedDefaultRatio; // If speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio + float DragSpeedScaleSlow; + float DragSpeedScaleFast; + ImVec2 ScrollbarClickDeltaToGrabCenter; // Distance between mouse and center of grab box, normalized in parent space. Use storage? + char Tooltip[1024]; + char* PrivateClipboard; // If no custom clipboard handler is defined + ImVec2 OsImePosRequest, OsImePosSet; // Cursor position request & last passed to the OS Input Method Editor + + // Logging + bool LogEnabled; + FILE* LogFile; // If != NULL log to stdout/ file + ImGuiTextBuffer* LogClipboard; // Else log to clipboard. This is pointer so our GImGui static constructor doesn't call heap allocators. + int LogStartDepth; + int LogAutoExpandMaxDepth; + + // Misc + float FramerateSecPerFrame[120]; // calculate estimate of framerate for user + int FramerateSecPerFrameIdx; + float FramerateSecPerFrameAccum; + int CaptureMouseNextFrame; // explicit capture via CaptureInputs() sets those flags + int CaptureKeyboardNextFrame; + char TempBuffer[1024*3+1]; // temporary text buffer + + ImGuiContext() + { + Initialized = false; + Font = NULL; + FontSize = FontBaseSize = 0.0f; + FontTexUvWhitePixel = ImVec2(0.0f, 0.0f); + + Time = 0.0f; + FrameCount = 0; + FrameCountEnded = FrameCountRendered = -1; + CurrentWindow = NULL; + FocusedWindow = NULL; + HoveredWindow = NULL; + HoveredRootWindow = NULL; + HoveredId = 0; + HoveredIdAllowOverlap = false; + HoveredIdPreviousFrame = 0; + ActiveId = 0; + ActiveIdPreviousFrame = 0; + ActiveIdIsAlive = false; + ActiveIdIsJustActivated = false; + ActiveIdAllowOverlap = false; + ActiveIdClickOffset = ImVec2(-1,-1); + ActiveIdWindow = NULL; + MovedWindow = NULL; + MovedWindowMoveId = 0; + SettingsDirtyTimer = 0.0f; + + SetNextWindowPosVal = ImVec2(0.0f, 0.0f); + SetNextWindowSizeVal = ImVec2(0.0f, 0.0f); + SetNextWindowCollapsedVal = false; + SetNextWindowPosCond = 0; + SetNextWindowSizeCond = 0; + SetNextWindowContentSizeCond = 0; + SetNextWindowCollapsedCond = 0; + SetNextWindowFocus = false; + SetNextWindowSizeConstraintCallback = NULL; + SetNextWindowSizeConstraintCallbackUserData = NULL; + SetNextTreeNodeOpenVal = false; + SetNextTreeNodeOpenCond = 0; + + ScalarAsInputTextId = 0; + DragCurrentValue = 0.0f; + DragLastMouseDelta = ImVec2(0.0f, 0.0f); + DragSpeedDefaultRatio = 1.0f / 100.0f; + DragSpeedScaleSlow = 0.01f; + DragSpeedScaleFast = 10.0f; + ScrollbarClickDeltaToGrabCenter = ImVec2(0.0f, 0.0f); + memset(Tooltip, 0, sizeof(Tooltip)); + PrivateClipboard = NULL; + OsImePosRequest = OsImePosSet = ImVec2(-1.0f, -1.0f); + + ModalWindowDarkeningRatio = 0.0f; + OverlayDrawList._OwnerName = "##Overlay"; // Give it a name for debugging + MouseCursor = ImGuiMouseCursor_Arrow; + memset(MouseCursorData, 0, sizeof(MouseCursorData)); + + LogEnabled = false; + LogFile = NULL; + LogClipboard = NULL; + LogStartDepth = 0; + LogAutoExpandMaxDepth = 2; + + memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); + FramerateSecPerFrameIdx = 0; + FramerateSecPerFrameAccum = 0.0f; + CaptureMouseNextFrame = CaptureKeyboardNextFrame = -1; + memset(TempBuffer, 0, sizeof(TempBuffer)); + } +}; + +// Transient per-window data, reset at the beginning of the frame +// FIXME: That's theory, in practice the delimitation between ImGuiWindow and ImGuiDrawContext is quite tenuous and could be reconsidered. +struct IMGUI_API ImGuiDrawContext +{ + ImVec2 CursorPos; + ImVec2 CursorPosPrevLine; + ImVec2 CursorStartPos; + ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame + float CurrentLineHeight; + float CurrentLineTextBaseOffset; + float PrevLineHeight; + float PrevLineTextBaseOffset; + float LogLinePosY; + int TreeDepth; + ImGuiID LastItemId; + ImRect LastItemRect; + bool LastItemHoveredAndUsable; // Item rectangle is hovered, and its window is currently interactable with (not blocked by a popup preventing access to the window) + bool LastItemHoveredRect; // Item rectangle is hovered, but its window may or not be currently interactable with (might be blocked by a popup preventing access to the window) + bool MenuBarAppending; + float MenuBarOffsetX; + ImVector<ImGuiWindow*> ChildWindows; + ImGuiStorage* StateStorage; + ImGuiLayoutType LayoutType; + + // We store the current settings outside of the vectors to increase memory locality (reduce cache misses). The vectors are rarely modified. Also it allows us to not heap allocate for short-lived windows which are not using those settings. + float ItemWidth; // == ItemWidthStack.back(). 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window + float TextWrapPos; // == TextWrapPosStack.back() [empty == -1.0f] + bool AllowKeyboardFocus; // == AllowKeyboardFocusStack.back() [empty == true] + bool ButtonRepeat; // == ButtonRepeatStack.back() [empty == false] + ImVector<float> ItemWidthStack; + ImVector<float> TextWrapPosStack; + ImVector<bool> AllowKeyboardFocusStack; + ImVector<bool> ButtonRepeatStack; + ImVector<ImGuiGroupData>GroupStack; + ImGuiColorEditMode ColorEditMode; + int StackSizesBackup[6]; // Store size of various stacks for asserting + + float IndentX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) + float GroupOffsetX; + float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. + int ColumnsCurrent; + int ColumnsCount; + float ColumnsMinX; + float ColumnsMaxX; + float ColumnsStartPosY; + float ColumnsCellMinY; + float ColumnsCellMaxY; + bool ColumnsShowBorders; + ImGuiID ColumnsSetId; + ImVector<ImGuiColumnData> ColumnsData; + + ImGuiDrawContext() + { + CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); + CurrentLineHeight = PrevLineHeight = 0.0f; + CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; + LogLinePosY = -1.0f; + TreeDepth = 0; + LastItemId = 0; + LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f); + LastItemHoveredAndUsable = LastItemHoveredRect = false; + MenuBarAppending = false; + MenuBarOffsetX = 0.0f; + StateStorage = NULL; + LayoutType = ImGuiLayoutType_Vertical; + ItemWidth = 0.0f; + ButtonRepeat = false; + AllowKeyboardFocus = true; + TextWrapPos = -1.0f; + ColorEditMode = ImGuiColorEditMode_RGB; + memset(StackSizesBackup, 0, sizeof(StackSizesBackup)); + + IndentX = 0.0f; + ColumnsOffsetX = 0.0f; + ColumnsCurrent = 0; + ColumnsCount = 1; + ColumnsMinX = ColumnsMaxX = 0.0f; + ColumnsStartPosY = 0.0f; + ColumnsCellMinY = ColumnsCellMaxY = 0.0f; + ColumnsShowBorders = true; + ColumnsSetId = 0; + } +}; + +// Windows data +struct IMGUI_API ImGuiWindow +{ + char* Name; + ImGuiID ID; // == ImHash(Name) + ImGuiWindowFlags Flags; // See enum ImGuiWindowFlags_ + int IndexWithinParent; // Order within immediate parent window, if we are a child window. Otherwise 0. + ImVec2 PosFloat; + ImVec2 Pos; // Position rounded-up to nearest pixel + ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) + ImVec2 SizeFull; // Size when non collapsed + ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame + ImVec2 SizeContentsExplicit; // Size of contents explicitly set by the user via SetNextWindowContentSize() + ImRect ContentsRegionRect; // Maximum visible content position in window coordinates. ~~ (SizeContentsExplicit ? SizeContentsExplicit : Size - ScrollbarSizes) - CursorStartPos, per axis + ImVec2 WindowPadding; // Window padding at the time of begin. We need to lock it, in particular manipulation of the ShowBorder would have an effect + ImGuiID MoveId; // == window->GetID("#MOVE") + ImVec2 Scroll; + ImVec2 ScrollTarget; // target scroll position. stored as cursor position with scrolling canceled out, so the highest point is always 0.0f. (FLT_MAX for no change) + ImVec2 ScrollTargetCenterRatio; // 0.0f = scroll so that target position is at top, 0.5f = scroll so that target position is centered + bool ScrollbarX, ScrollbarY; + ImVec2 ScrollbarSizes; + float BorderSize; + bool Active; // Set to true on Begin() + bool WasActive; + bool Accessed; // Set to true when any widget access the current window + bool Collapsed; // Set when collapsing window to become only title-bar + bool SkipItems; // == Visible && !Collapsed + int BeginCount; // Number of Begin() during the current frame (generally 0 or 1, 1+ if appending via multiple Begin/End pairs) + ImGuiID PopupId; // ID in the popup stack when this window is used as a popup/menu (because we use generic Name/ID for recycling) + int AutoFitFramesX, AutoFitFramesY; + bool AutoFitOnlyGrows; + int AutoPosLastDirection; + int HiddenFrames; + int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag. + int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag. + int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag. + bool SetWindowPosCenterWanted; + + ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame + ImVector<ImGuiID> IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack + ImRect ClipRect; // = DrawList->clip_rect_stack.back(). Scissoring / clipping rectangle. x1, y1, x2, y2. + ImRect WindowRectClipped; // = WindowRect just after setup in Begin(). == window->Rect() for root window. + int LastFrameActive; + float ItemWidthDefault; + ImGuiSimpleColumns MenuColumns; // Simplified columns storage for menu items + ImGuiStorage StateStorage; + float FontWindowScale; // Scale multiplier per-window + ImDrawList* DrawList; + ImGuiWindow* RootWindow; // If we are a child window, this is pointing to the first non-child parent window. Else point to ourself. + ImGuiWindow* RootNonPopupWindow; // If we are a child window, this is pointing to the first non-child non-popup parent window. Else point to ourself. + ImGuiWindow* ParentWindow; // If we are a child window, this is pointing to our parent window. Else point to NULL. + + // Navigation / Focus + int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() + int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) + int FocusIdxAllRequestCurrent; // Item being requested for focus + int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus + int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame) + int FocusIdxTabRequestNext; // " + +public: + ImGuiWindow(const char* name); + ~ImGuiWindow(); + + ImGuiID GetID(const char* str, const char* str_end = NULL); + ImGuiID GetID(const void* ptr); + ImGuiID GetIDNoKeepAlive(const char* str, const char* str_end = NULL); + + ImRect Rect() const { return ImRect(Pos.x, Pos.y, Pos.x+Size.x, Pos.y+Size.y); } + float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; } + float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0.0f : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; } + ImRect TitleBarRect() const { return ImRect(Pos, ImVec2(Pos.x + SizeFull.x, Pos.y + TitleBarHeight())); } + float MenuBarHeight() const { return (Flags & ImGuiWindowFlags_MenuBar) ? CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f : 0.0f; } + ImRect MenuBarRect() const { float y1 = Pos.y + TitleBarHeight(); return ImRect(Pos.x, y1, Pos.x + SizeFull.x, y1 + MenuBarHeight()); } +}; + +//----------------------------------------------------------------------------- +// Internal API +// No guarantee of forward compatibility here. +//----------------------------------------------------------------------------- + +namespace ImGui +{ + // We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) + // If this ever crash because g.CurrentWindow is NULL it means that either + // - ImGui::NewFrame() has never been called, which is illegal. + // - You are calling ImGui functions after ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal. + inline ImGuiWindow* GetCurrentWindowRead() { ImGuiContext& g = *GImGui; return g.CurrentWindow; } + inline ImGuiWindow* GetCurrentWindow() { ImGuiContext& g = *GImGui; g.CurrentWindow->Accessed = true; return g.CurrentWindow; } + IMGUI_API ImGuiWindow* GetParentWindow(); + IMGUI_API ImGuiWindow* FindWindowByName(const char* name); + IMGUI_API void FocusWindow(ImGuiWindow* window); + + IMGUI_API void EndFrame(); // Ends the ImGui frame. Automatically called by Render()! you most likely don't need to ever call that yourself directly. If you don't need to render you can call EndFrame() but you'll have wasted CPU already. If you don't need to render, don't create any windows instead! + + IMGUI_API void SetActiveID(ImGuiID id, ImGuiWindow* window); + IMGUI_API void SetHoveredID(ImGuiID id); + IMGUI_API void KeepAliveID(ImGuiID id); + + IMGUI_API void ItemSize(const ImVec2& size, float text_offset_y = 0.0f); + IMGUI_API void ItemSize(const ImRect& bb, float text_offset_y = 0.0f); + IMGUI_API bool ItemAdd(const ImRect& bb, const ImGuiID* id); + IMGUI_API bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged); + IMGUI_API bool IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs = false); + IMGUI_API bool FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop = true); // Return true if focus is requested + IMGUI_API void FocusableItemUnregister(ImGuiWindow* window); + IMGUI_API ImVec2 CalcItemSize(ImVec2 size, float default_x, float default_y); + IMGUI_API float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x); + + IMGUI_API void OpenPopupEx(const char* str_id, bool reopen_existing); + + // NB: All position are in absolute pixels coordinates (not window coordinates) + // FIXME: All those functions are a mess and needs to be refactored into something decent. AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. + // We need: a sort of symbol library, preferably baked into font atlas when possible + decent text rendering helpers. + IMGUI_API void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); + IMGUI_API void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); + IMGUI_API void RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align = ImVec2(0,0), const ImRect* clip_rect = NULL); + IMGUI_API void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); + IMGUI_API void RenderCollapseTriangle(ImVec2 pos, bool is_open, float scale = 1.0f, bool shadow = false); + IMGUI_API void RenderBullet(ImVec2 pos); + IMGUI_API void RenderCheckMark(ImVec2 pos, ImU32 col); + IMGUI_API const char* FindRenderedTextEnd(const char* text, const char* text_end = NULL); // Find the optional ## from which we stop displaying text. + + IMGUI_API bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags = 0); + IMGUI_API bool ButtonEx(const char* label, const ImVec2& size_arg = ImVec2(0,0), ImGuiButtonFlags flags = 0); + IMGUI_API bool CloseButton(ImGuiID id, const ImVec2& pos, float radius); + + IMGUI_API bool SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags = 0); + IMGUI_API bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power); + IMGUI_API bool SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format); + + IMGUI_API bool DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power); + IMGUI_API bool DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power); + IMGUI_API bool DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format); + + IMGUI_API bool InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); + IMGUI_API bool InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags); + IMGUI_API bool InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags); + IMGUI_API bool InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags); + IMGUI_API bool InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision); + + IMGUI_API bool TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end = NULL); + IMGUI_API bool TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags = 0); // Consume previous SetNextTreeNodeOpened() data, if any. May return true when logging + IMGUI_API void TreePushRawID(ImGuiID id); + + IMGUI_API void PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size); + + IMGUI_API int ParseFormatPrecision(const char* fmt, int default_value); + IMGUI_API float RoundScalar(float value, int decimal_precision); + +} // namespace ImGui + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif diff --git a/include/linmath.h b/include/linmath.h new file mode 100644 index 0000000..985e9f9 --- /dev/null +++ b/include/linmath.h @@ -0,0 +1,571 @@ +#ifndef LINMATH_H +#define LINMATH_H + +#include <math.h> + +#ifdef _MSC_VER +#define inline __inline +#endif + +#define LINMATH_H_DEFINE_VEC(n) \ +typedef float vec##n[n]; \ +static inline void vec##n##_add(vec##n r, vec##n const a, vec##n const b) \ +{ \ + int i; \ + for(i=0; i<n; ++i) \ + r[i] = a[i] + b[i]; \ +} \ +static inline void vec##n##_sub(vec##n r, vec##n const a, vec##n const b) \ +{ \ + int i; \ + for(i=0; i<n; ++i) \ + r[i] = a[i] - b[i]; \ +} \ +static inline void vec##n##_scale(vec##n r, vec##n const v, float const s) \ +{ \ + int i; \ + for(i=0; i<n; ++i) \ + r[i] = v[i] * s; \ +} \ +static inline float vec##n##_mul_inner(vec##n const a, vec##n const b) \ +{ \ + float p = 0.; \ + int i; \ + for(i=0; i<n; ++i) \ + p += b[i]*a[i]; \ + return p; \ +} \ +static inline float vec##n##_len(vec##n const v) \ +{ \ + return (float) sqrt(vec##n##_mul_inner(v,v)); \ +} \ +static inline void vec##n##_norm(vec##n r, vec##n const v) \ +{ \ + float k = 1.f / vec##n##_len(v); \ + vec##n##_scale(r, v, k); \ +} + +LINMATH_H_DEFINE_VEC(2) +LINMATH_H_DEFINE_VEC(3) +LINMATH_H_DEFINE_VEC(4) + +static inline void vec3_mul_cross(vec3 r, vec3 const a, vec3 const b) +{ + r[0] = a[1]*b[2] - a[2]*b[1]; + r[1] = a[2]*b[0] - a[0]*b[2]; + r[2] = a[0]*b[1] - a[1]*b[0]; +} + +static inline void vec3_reflect(vec3 r, vec3 const v, vec3 const n) +{ + float p = 2.f*vec3_mul_inner(v, n); + int i; + for(i=0;i<3;++i) + r[i] = v[i] - p*n[i]; +} + +static inline void vec4_mul_cross(vec4 r, vec4 a, vec4 b) +{ + r[0] = a[1]*b[2] - a[2]*b[1]; + r[1] = a[2]*b[0] - a[0]*b[2]; + r[2] = a[0]*b[1] - a[1]*b[0]; + r[3] = 1.f; +} + +static inline void vec4_reflect(vec4 r, vec4 v, vec4 n) +{ + float p = 2.f*vec4_mul_inner(v, n); + int i; + for(i=0;i<4;++i) + r[i] = v[i] - p*n[i]; +} + +typedef vec4 mat4x4[4]; +static inline void mat4x4_identity(mat4x4 M) +{ + int i, j; + for(i=0; i<4; ++i) + for(j=0; j<4; ++j) + M[i][j] = i==j ? 1.f : 0.f; +} +static inline void mat4x4_dup(mat4x4 M, mat4x4 N) +{ + int i, j; + for(i=0; i<4; ++i) + for(j=0; j<4; ++j) + M[i][j] = N[i][j]; +} +static inline void mat4x4_row(vec4 r, mat4x4 M, int i) +{ + int k; + for(k=0; k<4; ++k) + r[k] = M[k][i]; +} +static inline void mat4x4_col(vec4 r, mat4x4 M, int i) +{ + int k; + for(k=0; k<4; ++k) + r[k] = M[i][k]; +} +static inline void mat4x4_transpose(mat4x4 M, mat4x4 N) +{ + int i, j; + for(j=0; j<4; ++j) + for(i=0; i<4; ++i) + M[i][j] = N[j][i]; +} +static inline void mat4x4_add(mat4x4 M, mat4x4 a, mat4x4 b) +{ + int i; + for(i=0; i<4; ++i) + vec4_add(M[i], a[i], b[i]); +} +static inline void mat4x4_sub(mat4x4 M, mat4x4 a, mat4x4 b) +{ + int i; + for(i=0; i<4; ++i) + vec4_sub(M[i], a[i], b[i]); +} +static inline void mat4x4_scale(mat4x4 M, mat4x4 a, float k) +{ + int i; + for(i=0; i<4; ++i) + vec4_scale(M[i], a[i], k); +} +static inline void mat4x4_scale_aniso(mat4x4 M, mat4x4 a, float x, float y, float z) +{ + int i; + vec4_scale(M[0], a[0], x); + vec4_scale(M[1], a[1], y); + vec4_scale(M[2], a[2], z); + for(i = 0; i < 4; ++i) { + M[3][i] = a[3][i]; + } +} +static inline void mat4x4_mul(mat4x4 M, mat4x4 a, mat4x4 b) +{ + mat4x4 temp; + int k, r, c; + for(c=0; c<4; ++c) for(r=0; r<4; ++r) { + temp[c][r] = 0.f; + for(k=0; k<4; ++k) + temp[c][r] += a[k][r] * b[c][k]; + } + mat4x4_dup(M, temp); +} +static inline void mat4x4_mul_vec4(vec4 r, mat4x4 M, vec4 v) +{ + int i, j; + for(j=0; j<4; ++j) { + r[j] = 0.f; + for(i=0; i<4; ++i) + r[j] += M[i][j] * v[i]; + } +} +static inline void mat4x4_translate(mat4x4 T, float x, float y, float z) +{ + mat4x4_identity(T); + T[3][0] = x; + T[3][1] = y; + T[3][2] = z; +} +static inline void mat4x4_translate_in_place(mat4x4 M, float x, float y, float z) +{ + vec4 t = {x, y, z, 0}; + vec4 r; + int i; + for (i = 0; i < 4; ++i) { + mat4x4_row(r, M, i); + M[3][i] += vec4_mul_inner(r, t); + } +} +static inline void mat4x4_from_vec3_mul_outer(mat4x4 M, vec3 a, vec3 b) +{ + int i, j; + for(i=0; i<4; ++i) for(j=0; j<4; ++j) + M[i][j] = i<3 && j<3 ? a[i] * b[j] : 0.f; +} +static inline void mat4x4_rotate(mat4x4 R, mat4x4 M, float x, float y, float z, float angle) +{ + float s = sinf(angle); + float c = cosf(angle); + vec3 u = {x, y, z}; + + if(vec3_len(u) > 1e-4) { + vec3_norm(u, u); + mat4x4 T; + mat4x4_from_vec3_mul_outer(T, u, u); + + mat4x4 S = { + { 0, u[2], -u[1], 0}, + {-u[2], 0, u[0], 0}, + { u[1], -u[0], 0, 0}, + { 0, 0, 0, 0} + }; + mat4x4_scale(S, S, s); + + mat4x4 C; + mat4x4_identity(C); + mat4x4_sub(C, C, T); + + mat4x4_scale(C, C, c); + + mat4x4_add(T, T, C); + mat4x4_add(T, T, S); + + T[3][3] = 1.; + mat4x4_mul(R, M, T); + } else { + mat4x4_dup(R, M); + } +} +static inline void mat4x4_rotate_X(mat4x4 Q, mat4x4 M, float angle) +{ + float s = sinf(angle); + float c = cosf(angle); + mat4x4 R = { + {1.f, 0.f, 0.f, 0.f}, + {0.f, c, s, 0.f}, + {0.f, -s, c, 0.f}, + {0.f, 0.f, 0.f, 1.f} + }; + mat4x4_mul(Q, M, R); +} +static inline void mat4x4_rotate_Y(mat4x4 Q, mat4x4 M, float angle) +{ + float s = sinf(angle); + float c = cosf(angle); + mat4x4 R = { + { c, 0.f, s, 0.f}, + { 0.f, 1.f, 0.f, 0.f}, + { -s, 0.f, c, 0.f}, + { 0.f, 0.f, 0.f, 1.f} + }; + mat4x4_mul(Q, M, R); +} +static inline void mat4x4_rotate_Z(mat4x4 Q, mat4x4 M, float angle) +{ + float s = sinf(angle); + float c = cosf(angle); + mat4x4 R = { + { c, s, 0.f, 0.f}, + { -s, c, 0.f, 0.f}, + { 0.f, 0.f, 1.f, 0.f}, + { 0.f, 0.f, 0.f, 1.f} + }; + mat4x4_mul(Q, M, R); +} +static inline void mat4x4_invert(mat4x4 T, mat4x4 M) +{ + float s[6]; + float c[6]; + s[0] = M[0][0]*M[1][1] - M[1][0]*M[0][1]; + s[1] = M[0][0]*M[1][2] - M[1][0]*M[0][2]; + s[2] = M[0][0]*M[1][3] - M[1][0]*M[0][3]; + s[3] = M[0][1]*M[1][2] - M[1][1]*M[0][2]; + s[4] = M[0][1]*M[1][3] - M[1][1]*M[0][3]; + s[5] = M[0][2]*M[1][3] - M[1][2]*M[0][3]; + + c[0] = M[2][0]*M[3][1] - M[3][0]*M[2][1]; + c[1] = M[2][0]*M[3][2] - M[3][0]*M[2][2]; + c[2] = M[2][0]*M[3][3] - M[3][0]*M[2][3]; + c[3] = M[2][1]*M[3][2] - M[3][1]*M[2][2]; + c[4] = M[2][1]*M[3][3] - M[3][1]*M[2][3]; + c[5] = M[2][2]*M[3][3] - M[3][2]*M[2][3]; + + /* Assumes it is invertible */ + float idet = 1.0f/( s[0]*c[5]-s[1]*c[4]+s[2]*c[3]+s[3]*c[2]-s[4]*c[1]+s[5]*c[0] ); + + T[0][0] = ( M[1][1] * c[5] - M[1][2] * c[4] + M[1][3] * c[3]) * idet; + T[0][1] = (-M[0][1] * c[5] + M[0][2] * c[4] - M[0][3] * c[3]) * idet; + T[0][2] = ( M[3][1] * s[5] - M[3][2] * s[4] + M[3][3] * s[3]) * idet; + T[0][3] = (-M[2][1] * s[5] + M[2][2] * s[4] - M[2][3] * s[3]) * idet; + + T[1][0] = (-M[1][0] * c[5] + M[1][2] * c[2] - M[1][3] * c[1]) * idet; + T[1][1] = ( M[0][0] * c[5] - M[0][2] * c[2] + M[0][3] * c[1]) * idet; + T[1][2] = (-M[3][0] * s[5] + M[3][2] * s[2] - M[3][3] * s[1]) * idet; + T[1][3] = ( M[2][0] * s[5] - M[2][2] * s[2] + M[2][3] * s[1]) * idet; + + T[2][0] = ( M[1][0] * c[4] - M[1][1] * c[2] + M[1][3] * c[0]) * idet; + T[2][1] = (-M[0][0] * c[4] + M[0][1] * c[2] - M[0][3] * c[0]) * idet; + T[2][2] = ( M[3][0] * s[4] - M[3][1] * s[2] + M[3][3] * s[0]) * idet; + T[2][3] = (-M[2][0] * s[4] + M[2][1] * s[2] - M[2][3] * s[0]) * idet; + + T[3][0] = (-M[1][0] * c[3] + M[1][1] * c[1] - M[1][2] * c[0]) * idet; + T[3][1] = ( M[0][0] * c[3] - M[0][1] * c[1] + M[0][2] * c[0]) * idet; + T[3][2] = (-M[3][0] * s[3] + M[3][1] * s[1] - M[3][2] * s[0]) * idet; + T[3][3] = ( M[2][0] * s[3] - M[2][1] * s[1] + M[2][2] * s[0]) * idet; +} +static inline void mat4x4_orthonormalize(mat4x4 R, mat4x4 M) +{ + mat4x4_dup(R, M); + float s = 1.; + vec3 h; + + vec3_norm(R[2], R[2]); + + s = vec3_mul_inner(R[1], R[2]); + vec3_scale(h, R[2], s); + vec3_sub(R[1], R[1], h); + vec3_norm(R[2], R[2]); + + s = vec3_mul_inner(R[1], R[2]); + vec3_scale(h, R[2], s); + vec3_sub(R[1], R[1], h); + vec3_norm(R[1], R[1]); + + s = vec3_mul_inner(R[0], R[1]); + vec3_scale(h, R[1], s); + vec3_sub(R[0], R[0], h); + vec3_norm(R[0], R[0]); +} + +static inline void mat4x4_frustum(mat4x4 M, float l, float r, float b, float t, float n, float f) +{ + M[0][0] = 2.f*n/(r-l); + M[0][1] = M[0][2] = M[0][3] = 0.f; + + M[1][1] = 2.f*n/(t-b); + M[1][0] = M[1][2] = M[1][3] = 0.f; + + M[2][0] = (r+l)/(r-l); + M[2][1] = (t+b)/(t-b); + M[2][2] = -(f+n)/(f-n); + M[2][3] = -1.f; + + M[3][2] = -2.f*(f*n)/(f-n); + M[3][0] = M[3][1] = M[3][3] = 0.f; +} +static inline void mat4x4_ortho(mat4x4 M, float l, float r, float b, float t, float n, float f) +{ + M[0][0] = 2.f/(r-l); + M[0][1] = M[0][2] = M[0][3] = 0.f; + + M[1][1] = 2.f/(t-b); + M[1][0] = M[1][2] = M[1][3] = 0.f; + + M[2][2] = -2.f/(f-n); + M[2][0] = M[2][1] = M[2][3] = 0.f; + + M[3][0] = -(r+l)/(r-l); + M[3][1] = -(t+b)/(t-b); + M[3][2] = -(f+n)/(f-n); + M[3][3] = 1.f; +} +static inline void mat4x4_perspective(mat4x4 m, float y_fov, float aspect, float n, float f) +{ + /* NOTE: Degrees are an unhandy unit to work with. + * linmath.h uses radians for everything! */ + float const a = 1.f / (float) tan(y_fov / 2.f); + + m[0][0] = a / aspect; + m[0][1] = 0.f; + m[0][2] = 0.f; + m[0][3] = 0.f; + + m[1][0] = 0.f; + m[1][1] = a; + m[1][2] = 0.f; + m[1][3] = 0.f; + + m[2][0] = 0.f; + m[2][1] = 0.f; + m[2][2] = -((f + n) / (f - n)); + m[2][3] = -1.f; + + m[3][0] = 0.f; + m[3][1] = 0.f; + m[3][2] = -((2.f * f * n) / (f - n)); + m[3][3] = 0.f; +} +static inline void mat4x4_look_at(mat4x4 m, vec3 eye, vec3 center, vec3 up) +{ + /* Adapted from Android's OpenGL Matrix.java. */ + /* See the OpenGL GLUT documentation for gluLookAt for a description */ + /* of the algorithm. We implement it in a straightforward way: */ + + /* TODO: The negation of of can be spared by swapping the order of + * operands in the following cross products in the right way. */ + vec3 f; + vec3_sub(f, center, eye); + vec3_norm(f, f); + + vec3 s; + vec3_mul_cross(s, f, up); + vec3_norm(s, s); + + vec3 t; + vec3_mul_cross(t, s, f); + + m[0][0] = s[0]; + m[0][1] = t[0]; + m[0][2] = -f[0]; + m[0][3] = 0.f; + + m[1][0] = s[1]; + m[1][1] = t[1]; + m[1][2] = -f[1]; + m[1][3] = 0.f; + + m[2][0] = s[2]; + m[2][1] = t[2]; + m[2][2] = -f[2]; + m[2][3] = 0.f; + + m[3][0] = 0.f; + m[3][1] = 0.f; + m[3][2] = 0.f; + m[3][3] = 1.f; + + mat4x4_translate_in_place(m, -eye[0], -eye[1], -eye[2]); +} + +typedef float quat[4]; +static inline void quat_identity(quat q) +{ + q[0] = q[1] = q[2] = 0.f; + q[3] = 1.f; +} +static inline void quat_add(quat r, quat a, quat b) +{ + int i; + for(i=0; i<4; ++i) + r[i] = a[i] + b[i]; +} +static inline void quat_sub(quat r, quat a, quat b) +{ + int i; + for(i=0; i<4; ++i) + r[i] = a[i] - b[i]; +} +static inline void quat_mul(quat r, quat p, quat q) +{ + vec3 w; + vec3_mul_cross(r, p, q); + vec3_scale(w, p, q[3]); + vec3_add(r, r, w); + vec3_scale(w, q, p[3]); + vec3_add(r, r, w); + r[3] = p[3]*q[3] - vec3_mul_inner(p, q); +} +static inline void quat_scale(quat r, quat v, float s) +{ + int i; + for(i=0; i<4; ++i) + r[i] = v[i] * s; +} +static inline float quat_inner_product(quat a, quat b) +{ + float p = 0.f; + int i; + for(i=0; i<4; ++i) + p += b[i]*a[i]; + return p; +} +static inline void quat_conj(quat r, quat q) +{ + int i; + for(i=0; i<3; ++i) + r[i] = -q[i]; + r[3] = q[3]; +} +static inline void quat_rotate(quat r, float angle, vec3 axis) { + vec3 v; + vec3_scale(v, axis, sinf(angle / 2)); + int i; + for(i=0; i<3; ++i) + r[i] = v[i]; + r[3] = cosf(angle / 2); +} +#define quat_norm vec4_norm +static inline void quat_mul_vec3(vec3 r, quat q, vec3 v) +{ +/* + * Method by Fabian 'ryg' Giessen (of Farbrausch) +t = 2 * cross(q.xyz, v) +v' = v + q.w * t + cross(q.xyz, t) + */ + vec3 t = {q[0], q[1], q[2]}; + vec3 u = {q[0], q[1], q[2]}; + + vec3_mul_cross(t, t, v); + vec3_scale(t, t, 2); + + vec3_mul_cross(u, u, t); + vec3_scale(t, t, q[3]); + + vec3_add(r, v, t); + vec3_add(r, r, u); +} +static inline void mat4x4_from_quat(mat4x4 M, quat q) +{ + float a = q[3]; + float b = q[0]; + float c = q[1]; + float d = q[2]; + float a2 = a*a; + float b2 = b*b; + float c2 = c*c; + float d2 = d*d; + + M[0][0] = a2 + b2 - c2 - d2; + M[0][1] = 2.f*(b*c + a*d); + M[0][2] = 2.f*(b*d - a*c); + M[0][3] = 0.f; + + M[1][0] = 2*(b*c - a*d); + M[1][1] = a2 - b2 + c2 - d2; + M[1][2] = 2.f*(c*d + a*b); + M[1][3] = 0.f; + + M[2][0] = 2.f*(b*d + a*c); + M[2][1] = 2.f*(c*d - a*b); + M[2][2] = a2 - b2 - c2 + d2; + M[2][3] = 0.f; + + M[3][0] = M[3][1] = M[3][2] = 0.f; + M[3][3] = 1.f; +} + +static inline void mat4x4o_mul_quat(mat4x4 R, mat4x4 M, quat q) +{ +/* XXX: The way this is written only works for othogonal matrices. */ +/* TODO: Take care of non-orthogonal case. */ + quat_mul_vec3(R[0], q, M[0]); + quat_mul_vec3(R[1], q, M[1]); + quat_mul_vec3(R[2], q, M[2]); + + R[3][0] = R[3][1] = R[3][2] = 0.f; + R[3][3] = 1.f; +} +static inline void quat_from_mat4x4(quat q, mat4x4 M) +{ + float r=0.f; + int i; + + int perm[] = { 0, 1, 2, 0, 1 }; + int *p = perm; + + for(i = 0; i<3; i++) { + float m = M[i][i]; + if( m < r ) + continue; + m = r; + p = &perm[i]; + } + + r = (float) sqrt(1.f + M[p[0]][p[0]] - M[p[1]][p[1]] - M[p[2]][p[2]] ); + + if(r < 1e-6) { + q[0] = 1.f; + q[1] = q[2] = q[3] = 0.f; + return; + } + + q[0] = r/2.f; + q[1] = (M[p[0]][p[1]] - M[p[1]][p[0]])/(2.f*r); + q[2] = (M[p[2]][p[0]] - M[p[0]][p[2]])/(2.f*r); + q[3] = (M[p[2]][p[1]] - M[p[1]][p[2]])/(2.f*r); +} + +#endif diff --git a/include/misc_utils.h b/include/misc_utils.h new file mode 100644 index 0000000..243e838 --- /dev/null +++ b/include/misc_utils.h @@ -0,0 +1,71 @@ +/* + * draw_utils.h + * + * Created on: 8 Mar 2016 + * Author: ihavoutis + */ + +#ifndef RLI_PBDLIB_GUI_SANDBOX_SRC_MISC_UTILS_H_ +#define RLI_PBDLIB_GUI_SANDBOX_SRC_MISC_UTILS_H_ + +#include "armadillo" + +using namespace std; +using namespace arma; + +class Ref { +public: + vec p1; + vec p2; + + mat A; + vec b; + double theta; + + vec delta; + + void updateRef() { + b = p1; +// A = mat(2,2); +// vec delta = p2-p1; + delta = p2-p1; + delta = delta/arma::norm(delta); + A(0,0) = delta(0); + A(1,0) = delta(1); + A(0,1) = -delta(1); + A(1,1) = delta(0); + } + + Ref(){ + p1 = zeros(2); + p2 = zeros(2); + A = zeros(2,2); + delta = zeros(2); + theta = 0.0; + } +}; + + +class Remap { +public: + Remap(float input_min, float input_max, + float output_min, float output_max) +:_input_min(input_min), _input_max(input_max), + _output_min(output_min), _output_max(output_max){}; + +private: + float _input_min, _input_max, _output_min, _output_max; + +public: + float map( float input ) { + return _output_min + (input - _input_min) * + ((_output_max - _output_min) / (_input_max - _input_min)); + } + + float mapInv( float input ) { + return _input_min + (input - _output_min) * + ((_input_max - _input_min) / (_output_max - _output_min)); + } +}; + +#endif /* RLI_PBDLIB_GUI_SANDBOX_SRC_MISC_UTILS_H_ */ diff --git a/include/mpc_utils.h b/include/mpc_utils.h new file mode 100644 index 0000000..981de95 --- /dev/null +++ b/include/mpc_utils.h @@ -0,0 +1,18 @@ +// Interactive MPC helper functions + +#pragma once + +#include "armadillo" + +/// Create (continous) chain of @order integrators +void makeIntegratorChain(arma::mat* A, arma::mat* B, int order); +/// Discretise system matrices A, B +void discretizeSystem(arma::mat* _A, arma::mat* _B, arma::mat A, arma::mat B, double dt, bool zoh=true ); +/// Creates random (bivariate) covariances for a sequence of means @Mu +void randomCovariances(arma::cube* Sigma, const arma::mat& Mu, const arma::vec& covscale, bool semiTied, double theta, double minRnd=0.8 ); +/// Computes r factor based on a maximum displacement d for an oscillatory movement with period @period +double SHM_r(double d, double period, int order); +/// Creates stepwise reference matrices given a sequence of Gaussians +void stepwiseReference( arma::mat* MuQ, arma::mat* Q, const arma::mat& Mu, const arma::cube& Sigma, int n, int order, int dim, double endWeight=1e-10 ); +/// Creates via point reference matrices given a sequence of Gaussians +void viaPointReference( arma::mat* MuQ, arma::mat* Q, const arma::mat& Mu, const arma::cube& Sigma, int n, int order, int dim, double endWeight=1e-10 ); diff --git a/src/stb_rect_pack.h b/include/stb_rect_pack.h similarity index 91% rename from src/stb_rect_pack.h rename to include/stb_rect_pack.h index eb0ef2f..fafd889 100644 --- a/src/stb_rect_pack.h +++ b/include/stb_rect_pack.h @@ -1,4 +1,4 @@ -// stb_rect_pack.h - v0.05 - public domain - rectangle packing +// stb_rect_pack.h - v0.08 - public domain - rectangle packing // Sean Barrett 2014 // // Useful for e.g. packing rectangular textures into an atlas. @@ -13,6 +13,7 @@ // More docs to come. // // No memory allocations; uses qsort() and assert() from stdlib. +// Can override those by defining STBRP_SORT and STBRP_ASSERT. // // This library currently uses the Skyline Bottom-Left algorithm. // @@ -20,11 +21,29 @@ // implement them to the same API, but with a different init // function. // +// Credits +// +// Library +// Sean Barrett +// Minor features +// Martins Mozeiko +// Bugfixes / warning fixes +// Jeremy Jaussaud +// // Version history: // +// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0) +// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0) +// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort // 0.05: added STBRP_ASSERT to allow replacing assert // 0.04: fixed minor bug in STBRP_LARGE_RECTS support // 0.01: initial release +// +// LICENSE +// +// This software is in the public domain. Where that dedication is not +// recognized, you are granted a perpetual, irrevocable license to copy, +// distribute, and modify this file as you see fit. ////////////////////////////////////////////////////////////////////////////// // @@ -169,7 +188,10 @@ struct stbrp_context // #ifdef STB_RECT_PACK_IMPLEMENTATION +#ifndef STBRP_SORT #include <stdlib.h> +#define STBRP_SORT qsort +#endif #ifndef STBRP_ASSERT #include <assert.h> @@ -246,9 +268,9 @@ STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, } // find minimum y position if it starts at x1 -static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste) +static int stbrp__skyline_find_min_y(stbrp_context *, stbrp_node *first, int x0, int width, int *pwaste) { - (void)c; + //(void)c; stbrp_node *node = first; int x1 = x0 + width; int min_y, visited_width, waste_area; @@ -525,20 +547,24 @@ STBRP_DEF void stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int n } // sort according to heuristic - qsort(rects, num_rects, sizeof(rects[0]), rect_height_compare); + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare); for (i=0; i < num_rects; ++i) { - stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); - if (fr.prev_link) { - rects[i].x = (stbrp_coord) fr.x; - rects[i].y = (stbrp_coord) fr.y; + if (rects[i].w == 0 || rects[i].h == 0) { + rects[i].x = rects[i].y = 0; // empty rect needs no space } else { - rects[i].x = rects[i].y = STBRP__MAXVAL; + stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h); + if (fr.prev_link) { + rects[i].x = (stbrp_coord) fr.x; + rects[i].y = (stbrp_coord) fr.y; + } else { + rects[i].x = rects[i].y = STBRP__MAXVAL; + } } } // unsort - qsort(rects, num_rects, sizeof(rects[0]), rect_original_order); + STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order); // set was_packed flags for (i=0; i < num_rects; ++i) diff --git a/src/stb_textedit.h b/include/stb_textedit.h similarity index 89% rename from src/stb_textedit.h rename to include/stb_textedit.h index 5aa79f0..2dddefe 100644 --- a/src/stb_textedit.h +++ b/include/stb_textedit.h @@ -1,4 +1,10 @@ -// stb_textedit.h - v1.4 - public domain - Sean Barrett +// [ImGui] this is a slightly modified version of stb_truetype.h 1.8 +// [ImGui] - fixed a state corruption/crash bug in stb_text_redo and stb_textedit_discard_redo (#715) +// [ImGui] - fixed a crash bug in stb_textedit_discard_redo (#681) +// [ImGui] - fixed some minor warnings +// [ImGui] - added STB_TEXTEDIT_MOVEWORDLEFT/STB_TEXTEDIT_MOVEWORDRIGHT custom handler (#473) + +// stb_textedit.h - v1.8 - public domain - Sean Barrett // Development of this library was sponsored by RAD Game Tools // // This C header file implements the guts of a multi-line text-editing @@ -17,19 +23,24 @@ // // LICENSE // -// This software has been placed in the public domain by its author. -// Where that dedication is not recognized, you are granted a perpetual, -// irrevocable license to copy and modify this file as you see fit. +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. // // // DEPENDENCIES // -// Uses the C runtime function 'memmove'. Uses no other functions. -// Performs no runtime allocations. +// Uses the C runtime function 'memmove', which you can override +// by defining STB_TEXTEDIT_memmove before the implementation. +// Uses no other functions. Performs no runtime allocations. // // // VERSION HISTORY // +// 1.8 (2016-04-02) better keyboard handling when mouse button is down +// 1.7 (2015-09-13) change y range handling in case baseline is non-0 +// 1.6 (2015-04-15) allow STB_TEXTEDIT_memmove +// 1.5 (2014-09-10) add support for secondary keys for OS X // 1.4 (2014-08-17) fix signed/unsigned warnings // 1.3 (2014-06-19) fix mouse clicking to round to nearest char boundary // 1.2 (2014-05-27) fix some RAD types that had crept into the new code @@ -42,7 +53,13 @@ // ADDITIONAL CONTRIBUTORS // // Ulf Winklemann: move-by-word in 1.1 -// Scott Graham: mouse selection bugfix in 1.3 +// Fabian Giesen: secondary key inputs in 1.5 +// Martins Mozeiko: STB_TEXTEDIT_memmove +// +// Bugfixes: +// Scott Graham +// Daniel Keller +// Omar Cornut // // USAGE // @@ -137,11 +154,17 @@ // STB_TEXTEDIT_K_REDO keyboard input to perform redo // // Optional: -// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode -// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), -// required for WORDLEFT/WORDRIGHT -// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT -// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// STB_TEXTEDIT_K_INSERT keyboard input to toggle insert mode +// STB_TEXTEDIT_IS_SPACE(ch) true if character is whitespace (e.g. 'isspace'), +// required for default WORDLEFT/WORDRIGHT handlers +// STB_TEXTEDIT_MOVEWORDLEFT(obj,i) custom handler for WORDLEFT, returns index to move cursor to +// STB_TEXTEDIT_MOVEWORDRIGHT(obj,i) custom handler for WORDRIGHT, returns index to move cursor to +// STB_TEXTEDIT_K_WORDLEFT keyboard input to move cursor left one word // e.g. ctrl-LEFT +// STB_TEXTEDIT_K_WORDRIGHT keyboard input to move cursor right one word // e.g. ctrl-RIGHT +// STB_TEXTEDIT_K_LINESTART2 secondary keyboard input to move cursor to start of line +// STB_TEXTEDIT_K_LINEEND2 secondary keyboard input to move cursor to end of line +// STB_TEXTEDIT_K_TEXTSTART2 secondary keyboard input to move cursor to start of text +// STB_TEXTEDIT_K_TEXTEND2 secondary keyboard input to move cursor to end of text // // Todo: // STB_TEXTEDIT_K_PGUP keyboard input to move cursor up a page @@ -352,7 +375,10 @@ typedef struct // included just the "header" portion #ifdef STB_TEXTEDIT_IMPLEMENTATION -#include <string.h> // memmove +#ifndef STB_TEXTEDIT_memmove +#include <string.h> +#define STB_TEXTEDIT_memmove memmove +#endif ///////////////////////////////////////////////////////////////////////////// @@ -368,9 +394,6 @@ static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) float base_y = 0, prev_x; int i=0, k; - if (y < 0) - return 0; - r.x0 = r.x1 = 0; r.ymin = r.ymax = 0; r.num_chars = 0; @@ -381,6 +404,9 @@ static int stb_text_locate_coord(STB_TEXTEDIT_STRING *str, float x, float y) if (r.num_chars <= 0) return n; + if (i==0 && y < base_y + r.ymin) + return 0; + if (y < base_y + r.ymax) break; @@ -434,6 +460,8 @@ static void stb_textedit_click(STB_TEXTEDIT_STRING *str, STB_TexteditState *stat static void stb_textedit_drag(STB_TEXTEDIT_STRING *str, STB_TexteditState *state, float x, float y) { int p = stb_text_locate_coord(str, x, y); + if (state->select_start == state->select_end) + state->select_start = state->cursor; state->cursor = state->select_end = p; } @@ -595,9 +623,9 @@ static int is_word_boundary( STB_TEXTEDIT_STRING *_str, int _idx ) return _idx > 0 ? (STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(_str,_idx-1) ) && !STB_TEXTEDIT_IS_SPACE( STB_TEXTEDIT_GETCHAR(_str, _idx) ) ) : 1; } -static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *_str, STB_TexteditState *_state ) +#ifndef STB_TEXTEDIT_MOVEWORDLEFT +static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *_str, int c ) { - int c = _state->cursor - 1; while( c >= 0 && !is_word_boundary( _str, c ) ) --c; @@ -606,11 +634,13 @@ static int stb_textedit_move_to_word_previous( STB_TEXTEDIT_STRING *_str, STB_Te return c; } +#define STB_TEXTEDIT_MOVEWORDLEFT stb_textedit_move_to_word_previous +#endif -static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *_str, STB_TexteditState *_state ) +#ifndef STB_TEXTEDIT_MOVEWORDRIGHT +static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *_str, int c ) { const int len = STB_TEXTEDIT_STRINGLEN(_str); - int c = _state->cursor+1; while( c < len && !is_word_boundary( _str, c ) ) ++c; @@ -619,6 +649,9 @@ static int stb_textedit_move_to_word_next( STB_TEXTEDIT_STRING *_str, STB_Texted return c; } +#define STB_TEXTEDIT_MOVEWORDRIGHT stb_textedit_move_to_word_next +#endif + #endif // update selection and cursor to match each other @@ -740,21 +773,12 @@ retry: state->has_preferred_x = 0; break; -#ifdef STB_TEXTEDIT_IS_SPACE +#ifdef STB_TEXTEDIT_MOVEWORDLEFT case STB_TEXTEDIT_K_WORDLEFT: if (STB_TEXT_HAS_SELECTION(state)) stb_textedit_move_to_first(state); else { - state->cursor = stb_textedit_move_to_word_previous(str, state); - stb_textedit_clamp( str, state ); - } - break; - - case STB_TEXTEDIT_K_WORDRIGHT: - if (STB_TEXT_HAS_SELECTION(state)) - stb_textedit_move_to_last(str, state); - else { - state->cursor = stb_textedit_move_to_word_next(str, state); + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor-1); stb_textedit_clamp( str, state ); } break; @@ -763,17 +787,28 @@ retry: if( !STB_TEXT_HAS_SELECTION( state ) ) stb_textedit_prep_selection_at_cursor(state); - state->cursor = stb_textedit_move_to_word_previous(str, state); + state->cursor = STB_TEXTEDIT_MOVEWORDLEFT(str, state->cursor-1); state->select_end = state->cursor; stb_textedit_clamp( str, state ); break; +#endif + +#ifdef STB_TEXTEDIT_MOVEWORDRIGHT + case STB_TEXTEDIT_K_WORDRIGHT: + if (STB_TEXT_HAS_SELECTION(state)) + stb_textedit_move_to_last(str, state); + else { + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor+1); + stb_textedit_clamp( str, state ); + } + break; case STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT: if( !STB_TEXT_HAS_SELECTION( state ) ) stb_textedit_prep_selection_at_cursor(state); - state->cursor = stb_textedit_move_to_word_next(str, state); + state->cursor = STB_TEXTEDIT_MOVEWORDRIGHT(str, state->cursor+1); state->select_end = state->cursor; stb_textedit_clamp( str, state ); @@ -917,23 +952,35 @@ retry: state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2: +#endif case STB_TEXTEDIT_K_TEXTSTART: state->cursor = state->select_start = state->select_end = 0; state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2: +#endif case STB_TEXTEDIT_K_TEXTEND: state->cursor = STB_TEXTEDIT_STRINGLEN(str); state->select_start = state->select_end = 0; state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTSTART2 + case STB_TEXTEDIT_K_TEXTSTART2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_TEXTSTART | STB_TEXTEDIT_K_SHIFT: stb_textedit_prep_selection_at_cursor(state); state->cursor = state->select_end = 0; state->has_preferred_x = 0; break; +#ifdef STB_TEXTEDIT_K_TEXTEND2 + case STB_TEXTEDIT_K_TEXTEND2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_TEXTEND | STB_TEXTEDIT_K_SHIFT: stb_textedit_prep_selection_at_cursor(state); state->cursor = state->select_end = STB_TEXTEDIT_STRINGLEN(str); @@ -941,6 +988,9 @@ retry: break; +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2: +#endif case STB_TEXTEDIT_K_LINESTART: { StbFindState find; stb_textedit_clamp(str, state); @@ -951,16 +1001,25 @@ retry: break; } +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2: +#endif case STB_TEXTEDIT_K_LINEEND: { StbFindState find; stb_textedit_clamp(str, state); stb_textedit_move_to_first(state); stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - state->cursor = find.first_char + find.length; + state->has_preferred_x = 0; + state->cursor = find.first_char + find.length; + if (find.length > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) == STB_TEXTEDIT_NEWLINE) + --state->cursor; break; } +#ifdef STB_TEXTEDIT_K_LINESTART2 + case STB_TEXTEDIT_K_LINESTART2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_LINESTART | STB_TEXTEDIT_K_SHIFT: { StbFindState find; stb_textedit_clamp(str, state); @@ -971,13 +1030,19 @@ retry: break; } +#ifdef STB_TEXTEDIT_K_LINEEND2 + case STB_TEXTEDIT_K_LINEEND2 | STB_TEXTEDIT_K_SHIFT: +#endif case STB_TEXTEDIT_K_LINEEND | STB_TEXTEDIT_K_SHIFT: { StbFindState find; stb_textedit_clamp(str, state); stb_textedit_prep_selection_at_cursor(state); stb_textedit_find_charpos(&find, str, state->cursor, state->single_line); - state->cursor = state->select_end = find.first_char + find.length; state->has_preferred_x = 0; + state->cursor = find.first_char + find.length; + if (find.length > 0 && STB_TEXTEDIT_GETCHAR(str, state->cursor-1) == STB_TEXTEDIT_NEWLINE) + --state->cursor; + state->select_end = state->cursor; break; } @@ -1008,13 +1073,13 @@ static void stb_textedit_discard_undo(StbUndoState *state) int n = state->undo_rec[0].insert_length, i; // delete n characters from all other records state->undo_char_point = state->undo_char_point - (short) n; // vsnet05 - memmove(state->undo_char, state->undo_char + n, (size_t) ((size_t)state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); + STB_TEXTEDIT_memmove(state->undo_char, state->undo_char + n, (size_t) ((size_t)state->undo_char_point*sizeof(STB_TEXTEDIT_CHARTYPE))); for (i=0; i < state->undo_point; ++i) if (state->undo_rec[i].char_storage >= 0) state->undo_rec[i].char_storage = state->undo_rec[i].char_storage - (short) n; // vsnet05 // @OPTIMIZE: get rid of char_storage and infer it } --state->undo_point; - memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0]))); + STB_TEXTEDIT_memmove(state->undo_rec, state->undo_rec+1, (size_t) ((size_t)state->undo_point*sizeof(state->undo_rec[0]))); } } @@ -1032,13 +1097,13 @@ static void stb_textedit_discard_redo(StbUndoState *state) int n = state->undo_rec[k].insert_length, i; // delete n characters from all other records state->redo_char_point = state->redo_char_point + (short) n; // vsnet05 - memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); + STB_TEXTEDIT_memmove(state->undo_char + state->redo_char_point, state->undo_char + state->redo_char_point-n, (size_t) ((size_t)(STB_TEXTEDIT_UNDOCHARCOUNT - state->redo_char_point)*sizeof(STB_TEXTEDIT_CHARTYPE))); for (i=state->redo_point; i < k; ++i) if (state->undo_rec[i].char_storage >= 0) state->undo_rec[i].char_storage = state->undo_rec[i].char_storage + (short) n; // vsnet05 } + STB_TEXTEDIT_memmove(state->undo_rec + state->redo_point, state->undo_rec + state->redo_point-1, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); ++state->redo_point; - memmove(state->undo_rec + state->redo_point-1, state->undo_rec + state->redo_point, (size_t) ((size_t)(STB_TEXTEDIT_UNDOSTATECOUNT - state->redo_point)*sizeof(state->undo_rec[0]))); } } @@ -1196,6 +1261,7 @@ static void stb_text_redo(STB_TEXTEDIT_STRING *str, STB_TexteditState *state) if (r.insert_length) { // easy case: need to insert n characters STB_TEXTEDIT_INSERTCHARS(str, r.where, &s->undo_char[r.char_storage], r.insert_length); + s->redo_char_point += r.insert_length; } state->cursor = r.where + r.insert_length; diff --git a/src/stb_truetype.h b/include/stb_truetype.h similarity index 76% rename from src/stb_truetype.h rename to include/stb_truetype.h index 3c5d6f3..e6dae97 100644 --- a/src/stb_truetype.h +++ b/include/stb_truetype.h @@ -1,8 +1,5 @@ -// [ImGui] this is a slightly modified version of stb_truetype.h 1.02 -// [ImGui] we added stbtt_PackFontRangesGatherRects() and stbtt_PackFontRangesRenderIntoRects() and modified stbtt_PackBegin() - -// stb_truetype.h - v1.02 - public domain -// authored from 2009-2014 by Sean Barrett / RAD Game Tools +// stb_truetype.h - v1.10 - public domain +// authored from 2009-2015 by Sean Barrett / RAD Game Tools // // This library processes TrueType files: // parse files @@ -24,6 +21,10 @@ // Mikko Mononen: compound shape support, more cmap formats // Tor Andersson: kerning, subpixel rendering // +// Misc other: +// Ryan Gordon +// Simon Glass +// // Bug/warning reports/fixes: // "Zer" on mollyrocket (with fix) // Cass Everitt @@ -37,46 +38,41 @@ // Johan Duparc // Hou Qiming // Fabian "ryg" Giesen -// -// Misc other: -// Ryan Gordon +// Martins Mozeiko +// Cap Petschulat +// Omar Cornut +// github:aloucks +// Peter LaValle +// Sergey Popov +// Giumo X. Clanjor +// Higor Euripedes +// Thomas Fields +// Derek Vinyard // // VERSION HISTORY // -// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ -// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match -// non-oversampled; STBTT_POINT_SIZE for packed case only -// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling -// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) -// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID -// 0.8b (2014-07-07) fix a warning -// 0.8 (2014-05-25) fix a few more warnings -// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back -// 0.6c (2012-07-24) improve documentation -// 0.6b (2012-07-20) fix a few more warnings -// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, -// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty -// 0.5 (2011-12-09) bugfixes: -// subpixel glyph renderer computed wrong bounding box -// first vertex of shape can be off-curve (FreeSans) -// 0.4b (2011-12-03) fixed an error in the font baking example -// 0.4 (2011-12-01) kerning, subpixel rendering (tor) -// bugfixes for: -// codepoint-to-glyph conversion using table fmt=12 -// codepoint-to-glyph conversion using table fmt=4 -// stbtt_GetBakedQuad with non-square texture (Zer) -// updated Hello World! sample to use kerning and subpixel -// fixed some warnings -// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) -// userdata, malloc-from-userdata, non-zero fill (stb) -// 0.2 (2009-03-11) Fix unsigned/signed char warnings -// 0.1 (2009-03-09) First public release +// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// variant PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// +// Full history can be found at the end of this file. // // LICENSE // -// This software is in the public domain. Where that dedication is not -// recognized, you are granted a perpetual, irrevokable license to copy -// and modify this file as you see fit. +// This software is dual-licensed to the public domain and under the following +// license: you are granted a perpetual, irrevocable license to copy, modify, +// publish, and distribute this file as you see fit. // // USAGE // @@ -86,6 +82,9 @@ // before the #include of this file. This expands out the actual // implementation into that C/C++ file. // +// To make the implementation private to the file that generates the implementation, +// #define STBTT_STATIC +// // Simple 3D API (don't ship this, but it's fine for tools and quick start) // stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture // stbtt_GetBakedQuad() -- compute quad to draw for a given char @@ -112,6 +111,15 @@ // stbtt_GetFontVMetrics() // stbtt_GetCodepointKernAdvance() // +// Starting with version 1.06, the rasterizer was replaced with a new, +// faster and generally-more-precise rasterizer. The new rasterizer more +// accurately measures pixel coverage for anti-aliasing, except in the case +// where multiple shapes overlap, in which case it overestimates the AA pixel +// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If +// this turns out to be a problem, you can re-enable the old rasterizer with +// #define STBTT_RASTERIZER_VERSION 1 +// which will incur about a 15% speed hit. +// // ADDITIONAL DOCUMENTATION // // Immediately after this block comment are a series of sample programs. @@ -211,7 +219,15 @@ // Baked bitmap interface 70 LOC / // Font name matching & access 150 LOC ---- 150 // C runtime library abstraction 60 LOC ---- 60 - +// +// +// PERFORMANCE MEASUREMENTS FOR 1.06: +// +// 32-bit 64-bit +// Previous release: 8.83 s 7.68 s +// Pool allocations: 7.72 s 6.34 s +// Inline sort : 6.54 s 5.65 s +// New rasterizer : 5.63 s 5.00 s ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// @@ -225,16 +241,16 @@ #define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation #include "stb_truetype.h" -char ttf_buffer[1<<20]; +unsigned char ttf_buffer[1<<20]; unsigned char temp_bitmap[512*512]; stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs -GLstbtt_uint ftex; +GLuint ftex; void my_stbtt_initfont(void) { fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb")); - stbtt_BakeFontBitmap(data,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! + stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits! // can free ttf_buffer at this point glGenTextures(1, &ftex); glBindTexture(GL_TEXTURE_2D, ftex); @@ -246,6 +262,7 @@ void my_stbtt_initfont(void) void my_stbtt_print(float x, float y, char *text) { // assume orthographic projection with units = screen pixels, origin at top left + glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, ftex); glBegin(GL_QUADS); while (*text) { @@ -321,7 +338,7 @@ int main(int arg, char **argv) stbtt_fontinfo font; int i,j,ascent,baseline,ch=0; float scale, xpos=2; // leave a little padding in case the character extends left - char *text = "Heljo World!"; + char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); stbtt_InitFont(&font, buffer, 0); @@ -379,18 +396,6 @@ int main(int arg, char **argv) typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; - #ifdef STBTT_STATIC - #define STBTT_DEF static - #else - #define STBTT_DEF extern - #endif - - // #define your own STBTT_sort() to override this to avoid qsort - #ifndef STBTT_sort - #include <stdlib.h> - #define STBTT_sort(data,num_items,item_size,compare_func) qsort(data,num_items,item_size,compare_func) - #endif - // #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h #ifndef STBTT_ifloor #include <math.h> @@ -403,6 +408,11 @@ int main(int arg, char **argv) #define STBTT_sqrt(x) sqrt(x) #endif + #ifndef STBTT_fabs + #include <math.h> + #define STBTT_fabs(x) fabs(x) + #endif + // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h #ifndef STBTT_malloc #include <stdlib.h> @@ -437,6 +447,12 @@ int main(int arg, char **argv) #ifndef __STB_INCLUDE_STB_TRUETYPE_H__ #define __STB_INCLUDE_STB_TRUETYPE_H__ +#ifdef STBTT_STATIC +#define STBTT_DEF static +#else +#define STBTT_DEF extern +#endif + #ifdef __cplusplus extern "C" { #endif @@ -512,7 +528,7 @@ STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, i // Future calls using this context will pack characters into the bitmap passed // in here: a 1-channel bitmap that is weight x height. stride_in_bytes is // the distance from one row to the next (or 0 to mean they are packed tightly -// together). "padding" is // the amount of padding to leave between each +// together). "padding" is the amount of padding to leave between each // character (normally you want '1' for bitmaps you'll use as textures with // bilinear filtering). // @@ -541,34 +557,34 @@ STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontd typedef struct { float font_size; - int first_unicode_char_in_range; - int num_chars_in_range; + int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint + int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int num_chars; stbtt_packedchar *chardata_for_range; // output + unsigned char h_oversample, v_oversample; // don't set these, they're used internally } stbtt_pack_range; STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); // Creates character bitmaps from multiple ranges of characters stored in // ranges. This will usually create a better-packed bitmap than multiple -// calls to stbtt_PackFontRange. - -STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); -STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); -// Those functions are called by stbtt_PackFontRanges(). If you want to -// pack multiple fonts or custom data into a same texture, you may copy -// the contents of stbtt_PackFontRanges() and create a custom version -// using those functions. +// calls to stbtt_PackFontRange. Note that you can call this multiple +// times within a single PackBegin/PackEnd. STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); // Oversampling a font increases the quality by allowing higher-quality subpixel // positioning, and is especially valuable at smaller text sizes. // // This function sets the amount of oversampling for all following calls to -// stbtt_PackFontRange(s). The default (no oversampling) is achieved by -// h_oversample=1, v_oversample=1. The total number of pixels required is +// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given +// pack context. The default (no oversampling) is achieved by h_oversample=1 +// and v_oversample=1. The total number of pixels required is // h_oversample*v_oversample larger than the default; for example, 2x2 // oversampling requires 4x the storage of 1x1. For best results, render // oversampled textures with bilinear filtering. Look at the readme in // stb/tests/oversample for information about oversampled fonts +// +// To use with PackFontRangesGather etc., you must set it before calls +// call to PackFontRangesGatherRects. STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, // same data as above int char_index, // character to display @@ -576,6 +592,19 @@ STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, stbtt_aligned_quad *q, // output: quad to draw int align_to_integer); +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +// Calling these functions in sequence is roughly equivalent to calling +// stbtt_PackFontRanges(). If you more control over the packing of multiple +// fonts, or if you want to pack custom data into a font texture, take a look +// at the source to of stbtt_PackFontRanges() and create a custom version +// using these functions, e.g. call GatherRects multiple times, +// building up a single array of rects, then call PackRects once, +// then call RenderIntoRects repeatedly. This may result in a +// better packing than calling PackFontRanges multiple times +// (or it may not). + // this is an opaque structure that you shouldn't mess with which holds // all the context needed from PackBegin to PackEnd. struct stbtt_pack_context { @@ -607,7 +636,7 @@ STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); // The following structure is defined publically so you can declare one on // the stack or as a global or etc, but you should treat it as opaque. -typedef struct stbtt_fontinfo +struct stbtt_fontinfo { void * userdata; unsigned char * data; // pointer to .ttf file @@ -618,7 +647,7 @@ typedef struct stbtt_fontinfo int loca,head,glyf,hhea,hmtx,kern; // table locations as offset from start of .ttf int index_map; // a cmap mapping for our chosen character encoding int indexToLocFormat; // format needed to map from glyph index to glyph -} stbtt_fontinfo; +}; STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); // Given an offset into the file that defines a font, this function builds @@ -786,7 +815,16 @@ typedef struct unsigned char *pixels; } stbtt__bitmap; -STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata); +// rasterize a shape with quadratic beziers into a bitmap +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into + float flatness_in_pixels, // allowable error of curve in pixels + stbtt_vertex *vertices, // array of vertices defining shape + int num_verts, // number of vertices in above array + float scale_x, float scale_y, // scale applied to input vertices + float shift_x, float shift_y, // translation applied to input vertices + int x_off, int y_off, // another translation applied to input + int invert, // if non-zero, vertically flip shape + void *userdata); // context for to STBTT_MALLOC ////////////////////////////////////////////////////////////////////////////// // @@ -901,8 +939,16 @@ enum { // languageID for STBTT_PLATFORM_ID_MAC #define STBTT_MAX_OVERSAMPLE 8 #endif +#if STBTT_MAX_OVERSAMPLE > 255 +#error "STBTT_MAX_OVERSAMPLE cannot be > 255" +#endif + typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; +#ifndef STBTT_RASTERIZER_VERSION +#define STBTT_RASTERIZER_VERSION 2 +#endif + ////////////////////////////////////////////////////////////////////////// // // accessors to parse data from file @@ -971,7 +1017,7 @@ STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *font_collection, stbtt_int32 n = ttLONG(font_collection+8); if (index >= n) return -1; - return ttULONG(font_collection+12+index*14); + return ttULONG(font_collection+12+index*4); } } return -1; @@ -1059,7 +1105,6 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep stbtt_uint16 searchRange = ttUSHORT(data+index_map+8) >> 1; stbtt_uint16 entrySelector = ttUSHORT(data+index_map+10); stbtt_uint16 rangeShift = ttUSHORT(data+index_map+12) >> 1; - stbtt_uint16 item, offset, start, end; // do a binary search of the segments stbtt_uint32 endCount = index_map + 14; @@ -1076,8 +1121,8 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep // now decrement to bias correctly to find smallest search -= 2; while (entrySelector) { + stbtt_uint16 end; searchRange >>= 1; - start = ttUSHORT(data + search + searchRange*2 + segcount*2 + 2); end = ttUSHORT(data + search + searchRange*2); if (unicode_codepoint > end) search += searchRange*2; @@ -1085,19 +1130,21 @@ STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codep } search += 2; - item = (stbtt_uint16) ((search - endCount) >> 1); + { + stbtt_uint16 offset, start; + stbtt_uint16 item = (stbtt_uint16) ((search - endCount) >> 1); - STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); - start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); - end = ttUSHORT(data + index_map + 14 + 2 + 2*item); - if (unicode_codepoint < start) - return 0; + STBTT_assert(unicode_codepoint <= ttUSHORT(data + endCount + 2*item)); + start = ttUSHORT(data + index_map + 14 + segcount*2 + 2 + 2*item); + if (unicode_codepoint < start) + return 0; - offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); - if (offset == 0) - return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); + offset = ttUSHORT(data + index_map + 14 + segcount*6 + 2 + 2*item); + if (offset == 0) + return (stbtt_uint16) (unicode_codepoint + ttSHORT(data + index_map + 14 + segcount*4 + 2 + 2*item)); - return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + return ttUSHORT(data + offset + (unicode_codepoint-start)*2 + index_map + 14 + segcount*6 + 2 + 2*item); + } } else if (format == 12 || format == 13) { stbtt_uint32 ngroups = ttULONG(data+index_map+12); stbtt_int32 low,high; @@ -1519,7 +1566,7 @@ STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) { - int x0,y0,x1,y1; + int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { // e.g. space character if (ix0) *ix0 = 0; @@ -1550,42 +1597,131 @@ STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codep stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); } +////////////////////////////////////////////////////////////////////////////// +// +// Rasterizer + +typedef struct stbtt__hheap_chunk +{ + struct stbtt__hheap_chunk *next; +} stbtt__hheap_chunk; + +typedef struct stbtt__hheap +{ + struct stbtt__hheap_chunk *head; + void *first_free; + int num_remaining_in_head_chunk; +} stbtt__hheap; + +static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) +{ + if (hh->first_free) { + void *p = hh->first_free; + hh->first_free = * (void **) p; + return p; + } else { + if (hh->num_remaining_in_head_chunk == 0) { + int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); + stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); + if (c == NULL) + return NULL; + c->next = hh->head; + hh->head = c; + hh->num_remaining_in_head_chunk = count; + } + --hh->num_remaining_in_head_chunk; + return (char *) (hh->head) + size * hh->num_remaining_in_head_chunk; + } +} + +static void stbtt__hheap_free(stbtt__hheap *hh, void *p) +{ + *(void **) p = hh->first_free; + hh->first_free = p; +} + +static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) +{ + stbtt__hheap_chunk *c = hh->head; + while (c) { + stbtt__hheap_chunk *n = c->next; + STBTT_free(c, userdata); + c = n; + } +} + typedef struct stbtt__edge { float x0,y0, x1,y1; int invert; } stbtt__edge; + typedef struct stbtt__active_edge { + struct stbtt__active_edge *next; + #if STBTT_RASTERIZER_VERSION==1 int x,dx; float ey; - struct stbtt__active_edge *next; - int valid; + int direction; + #elif STBTT_RASTERIZER_VERSION==2 + float fx,fdx,fdy; + float direction; + float sy; + float ey; + #else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" + #endif } stbtt__active_edge; -#define FIXSHIFT 10 -#define FIX (1 << FIXSHIFT) -#define FIXMASK (FIX-1) +#if STBTT_RASTERIZER_VERSION == 1 +#define STBTT_FIXSHIFT 10 +#define STBTT_FIX (1 << STBTT_FIXSHIFT) +#define STBTT_FIXMASK (STBTT_FIX-1) -static stbtt__active_edge *new_active(stbtt__edge *e, int off_x, float start_point, void *userdata) +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) { - stbtt__active_edge *z = (stbtt__active_edge *) STBTT_malloc(sizeof(*z), userdata); // @TODO: make a pool of these!!! + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); - STBTT_assert(e->y0 <= start_point); + STBTT_assert(z != NULL); if (!z) return z; - // round dx down to avoid going too far + + // round dx down to avoid overshooting if (dxdy < 0) - z->dx = -STBTT_ifloor(FIX * -dxdy); + z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); else - z->dx = STBTT_ifloor(FIX * dxdy); - z->x = STBTT_ifloor(FIX * (e->x0 + dxdy * (start_point - e->y0))); - z->x -= off_x * FIX; + z->dx = STBTT_ifloor(STBTT_FIX * dxdy); + + z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount + z->x -= off_x * STBTT_FIX; + z->ey = e->y1; z->next = 0; - z->valid = e->invert ? 1 : -1; + z->direction = e->invert ? 1 : -1; return z; } +#elif STBTT_RASTERIZER_VERSION == 2 +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + STBTT_assert(z != NULL); + //STBTT_assert(e->y0 <= start_point); + if (!z) return z; + z->fdx = dxdy; + z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; + z->fx = e->x0 + dxdy * (start_point - e->y0); + z->fx -= off_x; + z->direction = e->invert ? 1.0f : -1.0f; + z->sy = e->y0; + z->ey = e->y1; + z->next = 0; + return z; +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif +#if STBTT_RASTERIZER_VERSION == 1 // note: this routine clips fills that extend off the edges... ideally this // wouldn't happen, but it could happen if the truetype glyph bounding boxes // are wrong, or if the user supplies a too-small bitmap @@ -1597,26 +1733,26 @@ static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__ac while (e) { if (w == 0) { // if we're currently at zero, we need to record the edge start point - x0 = e->x; w += e->valid; + x0 = e->x; w += e->direction; } else { - int x1 = e->x; w += e->valid; + int x1 = e->x; w += e->direction; // if we went to zero, we need to draw if (w == 0) { - int i = x0 >> FIXSHIFT; - int j = x1 >> FIXSHIFT; + int i = x0 >> STBTT_FIXSHIFT; + int j = x1 >> STBTT_FIXSHIFT; if (i < len && j >= 0) { if (i == j) { // x0,x1 are the same pixel, so compute combined coverage - scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> FIXSHIFT); + scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); } else { if (i >= 0) // add antialiasing for x0 - scanline[i] = scanline[i] + (stbtt_uint8) (((FIX - (x0 & FIXMASK)) * max_weight) >> FIXSHIFT); + scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); else i = -1; // clip if (j < len) // add antialiasing for x1 - scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & FIXMASK) * max_weight) >> FIXSHIFT); + scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); else j = len; // clip @@ -1633,6 +1769,7 @@ static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__ac static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) { + stbtt__hheap hh = { 0, 0, 0 }; stbtt__active_edge *active = NULL; int y,j=0; int max_weight = (255 / vsubsample); // weight per vertical scanline @@ -1660,9 +1797,9 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, stbtt__active_edge * z = *step; if (z->ey <= scan_y) { *step = z->next; // delete from list - STBTT_assert(z->valid); - z->valid = 0; - STBTT_free(z, userdata); + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); } else { z->x += z->dx; // advance to position for current scanline step = &((*step)->next); // advance through list @@ -1691,22 +1828,24 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline while (e->y0 <= scan_y) { if (e->y1 > scan_y) { - stbtt__active_edge *z = new_active(e, off_x, scan_y, userdata); - // find insertion point - if (active == NULL) - active = z; - else if (z->x < active->x) { - // insert at front - z->next = active; - active = z; - } else { - // find thing to insert AFTER - stbtt__active_edge *p = active; - while (p->next && p->next->x < z->x) - p = p->next; - // at this point, p->next->x is NOT < z->x - z->next = p->next; - p->next = z; + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); + if (z != NULL) { + // find insertion point + if (active == NULL) + active = z; + else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + stbtt__active_edge *p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } } } ++e; @@ -1722,24 +1861,395 @@ static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, ++j; } - while (active) { - stbtt__active_edge *z = active; - active = active->next; - STBTT_free(z, userdata); + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} + +#elif STBTT_RASTERIZER_VERSION == 2 + +// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +// (i.e. it has already been clipped to those) +static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) +{ + if (y0 == y1) return; + STBTT_assert(y0 < y1); + STBTT_assert(e->sy <= e->ey); + if (y0 > e->ey) return; + if (y1 < e->sy) return; + if (y0 < e->sy) { + x0 += (x1-x0) * (e->sy - y0) / (y1-y0); + y0 = e->sy; + } + if (y1 > e->ey) { + x1 += (x1-x0) * (e->ey - y1) / (y1-y0); + y1 = e->ey; + } + + if (x0 == x) + STBTT_assert(x1 <= x+1); + else if (x0 == x+1) + STBTT_assert(x1 >= x); + else if (x0 <= x) + STBTT_assert(x1 <= x); + else if (x0 >= x+1) + STBTT_assert(x1 >= x+1); + else + STBTT_assert(x1 >= x && x1 <= x+1); + + if (x0 <= x && x1 <= x) + scanline[x] += e->direction * (y1-y0); + else if (x0 >= x+1 && x1 >= x+1) + ; + else { + STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); + scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position + } +} + +static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) +{ + float y_bottom = y_top+1; + + while (e) { + // brute force every pixel + + // compute intersection points with top & bottom + STBTT_assert(e->ey >= y_top); + + if (e->fdx == 0) { + float x0 = e->fx; + if (x0 < len) { + if (x0 >= 0) { + stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); + stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); + } else { + stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); + } + } + } else { + float x0 = e->fx; + float dx = e->fdx; + float xb = x0 + dx; + float x_top, x_bottom; + float sy0,sy1; + float dy = e->fdy; + STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); + + // compute endpoints of line segment clipped to this scanline (if the + // line segment starts on this scanline. x0 is the intersection of the + // line with y_top, but that may be off the line segment. + if (e->sy > y_top) { + x_top = x0 + dx * (e->sy - y_top); + sy0 = e->sy; + } else { + x_top = x0; + sy0 = y_top; + } + if (e->ey < y_bottom) { + x_bottom = x0 + dx * (e->ey - y_top); + sy1 = e->ey; + } else { + x_bottom = xb; + sy1 = y_bottom; + } + + if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { + // from here on, we don't have to range check x values + + if ((int) x_top == (int) x_bottom) { + float height; + // simple case, only spans one pixel + int x = (int) x_top; + height = sy1 - sy0; + STBTT_assert(x >= 0 && x < len); + scanline[x] += e->direction * (1-((x_top - x) + (x_bottom-x))/2) * height; + scanline_fill[x] += e->direction * height; // everything right of this pixel is filled + } else { + int x,x1,x2; + float y_crossing, step, sign, area; + // covers 2+ pixels + if (x_top > x_bottom) { + // flip scanline vertically; signed area is the same + float t; + sy0 = y_bottom - (sy0 - y_top); + sy1 = y_bottom - (sy1 - y_top); + t = sy0, sy0 = sy1, sy1 = t; + t = x_bottom, x_bottom = x_top, x_top = t; + dx = -dx; + dy = -dy; + t = x0, x0 = xb, xb = t; + } + + x1 = (int) x_top; + x2 = (int) x_bottom; + // compute intersection with y axis at x1+1 + y_crossing = (x1+1 - x0) * dy + y_top; + + sign = e->direction; + // area of the rectangle covered from y0..y_crossing + area = sign * (y_crossing-sy0); + // area of the triangle (x_top,y0), (x+1,y0), (x+1,y_crossing) + scanline[x1] += area * (1-((x_top - x1)+(x1+1-x1))/2); + + step = sign * dy; + for (x = x1+1; x < x2; ++x) { + scanline[x] += area + step/2; + area += step; + } + y_crossing += dy * (x2 - (x1+1)); + + STBTT_assert(STBTT_fabs(area) <= 1.01f); + + scanline[x2] += area + sign * (1-((x2-x2)+(x_bottom-x2))/2) * (sy1-y_crossing); + + scanline_fill[x2] += sign * (sy1-sy0); + } + } else { + // if edge goes outside of box we're drawing, we require + // clipping logic. since this does not match the intended use + // of this library, we use a different, very slow brute + // force implementation + int x; + for (x=0; x < len; ++x) { + // cases: + // + // there can be up to two intersections with the pixel. any intersection + // with left or right edges can be handled by splitting into two (or three) + // regions. intersections with top & bottom do not necessitate case-wise logic. + // + // the old way of doing this found the intersections with the left & right edges, + // then used some simple logic to produce up to three segments in sorted order + // from top-to-bottom. however, this had a problem: if an x edge was epsilon + // across the x border, then the corresponding y position might not be distinct + // from the other y segment, and it might ignored as an empty segment. to avoid + // that, we need to explicitly produce segments based on x positions. + + // rename variables to clear pairs + float y0 = y_top; + float x1 = (float) (x); + float x2 = (float) (x+1); + float x3 = xb; + float y3 = y_bottom; + float y1,y2; + + // x = e->x + e->dx * (y-y_top) + // (y-y_top) = (x - e->x) / e->dx + // y = (x - e->x) / e->dx + y_top + y1 = (x - x0) / dx + y_top; + y2 = (x+1 - x0) / dx + y_top; + + if (x0 < x1 && x3 > x2) { // three segments descending down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x1 && x0 > x2) { // three segments descending down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x1 && x3 > x1) { // two segments across x, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x3 < x1 && x0 > x1) { // two segments across x, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1,y1, x3,y3); + } else if (x0 < x2 && x3 > x2) { // two segments across x+1, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else if (x3 < x2 && x0 > x2) { // two segments across x+1, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2,y2, x3,y3); + } else { // one segment + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); + } + } + } + } + e = e->next; + } +} + +// directly AA rasterize edges w/o supersampling +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + (void)vsubsample; + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0, i; + float scanline_data[129], *scanline, *scanline2; + + if (result->w > 64) + scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); + else + scanline = scanline_data; + + scanline2 = scanline + result->w; + + y = off_y; + e[n].y0 = (float) (off_y + result->h) + 1; + + while (j < result->h) { + // find center of pixel for this scanline + float scan_y_top = y + 0.0f; + float scan_y_bottom = y + 1.0f; + stbtt__active_edge **step = &active; + + STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); + STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); + + // update all active edges; + // remove all active edges that terminate before the top of this scanline + while (*step) { + stbtt__active_edge * z = *step; + if (z->ey <= scan_y_top) { + *step = z->next; // delete from list + STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + step = &((*step)->next); // advance through list + } + } + + // insert all edges that start before the bottom of this scanline + while (e->y0 <= scan_y_bottom) { + if (e->y0 != e->y1) { + stbtt__active_edge *z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); + if (z != NULL) { + STBTT_assert(z->ey >= scan_y_top); + // insert at front + z->next = active; + active = z; + } + } + ++e; + } + + // now process all active edges + if (active) + stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); + + { + float sum = 0; + for (i=0; i < result->w; ++i) { + float k; + int m; + sum += scanline2[i]; + k = scanline[i] + sum; + k = (float) STBTT_fabs(k)*255 + 0.5f; + m = (int) k; + if (m > 255) m = 255; + result->pixels[j*result->stride + i] = (unsigned char) m; + } + } + // advance all the edges + step = &active; + while (*step) { + stbtt__active_edge *z = *step; + z->fx += z->fdx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + + ++y; + ++j; } + stbtt__hheap_cleanup(&hh, userdata); + if (scanline != scanline_data) STBTT_free(scanline, userdata); } +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif -static int stbtt__edge_compare(const void *p, const void *q) +#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) + +static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) { - stbtt__edge *a = (stbtt__edge *) p; - stbtt__edge *b = (stbtt__edge *) q; + int i,j; + for (i=1; i < n; ++i) { + stbtt__edge t = p[i], *a = &t; + j = i; + while (j > 0) { + stbtt__edge *b = &p[j-1]; + int c = STBTT__COMPARE(a,b); + if (!c) break; + p[j] = p[j-1]; + --j; + } + if (i != j) + p[j] = t; + } +} - if (a->y0 < b->y0) return -1; - if (a->y0 > b->y0) return 1; - return 0; +static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) +{ + /* threshhold for transitioning to insertion sort */ + while (n > 12) { + stbtt__edge t; + int c01,c12,c,m,i,j; + + /* compute median of three */ + m = n >> 1; + c01 = STBTT__COMPARE(&p[0],&p[m]); + c12 = STBTT__COMPARE(&p[m],&p[n-1]); + /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ + if (c01 != c12) { + /* otherwise, we'll need to swap something else to middle */ + int z; + c = STBTT__COMPARE(&p[0],&p[n-1]); + /* 0>mid && mid<n: 0>n => n; 0<n => 0 */ + /* 0<mid && mid>n: 0>n => 0; 0<n => n */ + z = (c == c12) ? 0 : n-1; + t = p[z]; + p[z] = p[m]; + p[m] = t; + } + /* now p[m] is the median-of-three */ + /* swap it to the beginning so it won't move around */ + t = p[0]; + p[0] = p[m]; + p[m] = t; + + /* partition loop */ + i=1; + j=n-1; + for(;;) { + /* handling of equality is crucial here */ + /* for sentinels & efficiency with duplicates */ + for (;;++i) { + if (!STBTT__COMPARE(&p[i], &p[0])) break; + } + for (;;--j) { + if (!STBTT__COMPARE(&p[0], &p[j])) break; + } + /* make sure we haven't crossed */ + if (i >= j) break; + t = p[i]; + p[i] = p[j]; + p[j] = t; + + ++i; + --j; + } + /* recurse on smaller side, iterate on larger */ + if (j < (n-i)) { + stbtt__sort_edges_quicksort(p,j); + p = p+i; + n = n-i; + } else { + stbtt__sort_edges_quicksort(p+i, n-i); + n = j; + } + } +} + +static void stbtt__sort_edges(stbtt__edge *p, int n) +{ + stbtt__sort_edges_quicksort(p, n); + stbtt__sort_edges_ins_sort(p, n); } typedef struct @@ -1752,7 +2262,13 @@ static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcou float y_scale_inv = invert ? -scale_y : scale_y; stbtt__edge *e; int n,i,j,k,m; +#if STBTT_RASTERIZER_VERSION == 1 int vsubsample = result->h < 8 ? 15 : 5; +#elif STBTT_RASTERIZER_VERSION == 2 + int vsubsample = 1; +#else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif // vsubsample should divide 255 evenly; otherwise we won't reach full opacity // now we have to blow out the windings into explicit edge lists @@ -1789,7 +2305,8 @@ static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcou } // now sort the edges by their highest point (should snap to integer, and then by x) - STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + stbtt__sort_edges(e, n); // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); @@ -1921,7 +2438,10 @@ STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info if (scale_x == 0) scale_x = scale_y; if (scale_y == 0) { - if (scale_x == 0) return NULL; + if (scale_x == 0) { + STBTT_free(vertices, info->userdata); + return NULL; + } scale_y = scale_x; } @@ -2013,6 +2533,7 @@ STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // fo float scale; int x,y,bottom_y, i; stbtt_fontinfo f; + f.userdata = NULL; if (!stbtt_InitFont(&f, data, offset)) return -1; STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels @@ -2054,8 +2575,8 @@ STBTT_DEF void stbtt_GetBakedQuad(stbtt_bakedchar *chardata, int pw, int ph, int float d3d_bias = opengl_fillrule ? 0 : -0.5f; float ipw = 1.0f / pw, iph = 1.0f / ph; stbtt_bakedchar *b = chardata + char_index; - int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5); - int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5); + int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); + int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = round_x + d3d_bias; q->y0 = round_y + d3d_bias; @@ -2206,10 +2727,11 @@ static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_i unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_w = w - kernel_width; int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < h; ++j) { int i; unsigned int total; - memset(buffer, 0, kernel_width); + STBTT_memset(buffer, 0, kernel_width); total = 0; @@ -2236,6 +2758,13 @@ static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_i pixels[i] = (unsigned char) (total / 4); } break; + case 5: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 5); + } + break; default: for (i=0; i <= safe_w; ++i) { total += pixels[i] - buffer[i & STBTT__OVER_MASK]; @@ -2260,10 +2789,11 @@ static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_i unsigned char buffer[STBTT_MAX_OVERSAMPLE]; int safe_h = h - kernel_width; int j; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze for (j=0; j < w; ++j) { int i; unsigned int total; - memset(buffer, 0, kernel_width); + STBTT_memset(buffer, 0, kernel_width); total = 0; @@ -2290,6 +2820,13 @@ static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_i pixels[i*stride_in_bytes] = (unsigned char) (total / 4); } break; + case 5: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 5); + } + break; default: for (i=0; i <= safe_h; ++i) { total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; @@ -2330,21 +2867,20 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fon for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); - for (j=0; j < ranges[i].num_chars_in_range; ++j) { + ranges[i].h_oversample = (unsigned char) spc->h_oversample; + ranges[i].v_oversample = (unsigned char) spc->v_oversample; + for (j=0; j < ranges[i].num_chars; ++j) { int x0,y0,x1,y1; - int glyph = stbtt_FindGlyphIndex(info,ranges[i].first_unicode_char_in_range + j); - if (glyph) { - stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, - scale * spc->h_oversample, - scale * spc->v_oversample, - 0,0, - &x0,&y0,&x1,&y1); - rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); - rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); - } else { - rects[k].w = rects[k].h = 1; - } - ++k; + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); + stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + &x0,&y0,&x1,&y1); + rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); + rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + ++k; } } @@ -2354,22 +2890,30 @@ STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, stbtt_fon // rects array must be big enough to accommodate all characters in the given ranges STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) { - float recip_h = 1.0f / spc->h_oversample; - float recip_v = 1.0f / spc->v_oversample; - float sub_x = stbtt__oversample_shift(spc->h_oversample); - float sub_y = stbtt__oversample_shift(spc->v_oversample); int i,j,k, return_value = 1; + // save current values + int old_h_over = spc->h_oversample; + int old_v_over = spc->v_oversample; + k = 0; for (i=0; i < num_ranges; ++i) { float fh = ranges[i].font_size; float scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); - for (j=0; j < ranges[i].num_chars_in_range; ++j) { + float recip_h,recip_v,sub_x,sub_y; + spc->h_oversample = ranges[i].h_oversample; + spc->v_oversample = ranges[i].v_oversample; + recip_h = 1.0f / spc->h_oversample; + recip_v = 1.0f / spc->v_oversample; + sub_x = stbtt__oversample_shift(spc->h_oversample); + sub_y = stbtt__oversample_shift(spc->v_oversample); + for (j=0; j < ranges[i].num_chars; ++j) { stbrp_rect *r = &rects[k]; if (r->was_packed) { stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; int advance, lsb, x0,y0,x1,y1; - int glyph = stbtt_FindGlyphIndex(info, ranges[i].first_unicode_char_in_range + j); + int codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + int glyph = stbtt_FindGlyphIndex(info, codepoint); stbrp_coord pad = (stbrp_coord) spc->padding; // pad on left and top @@ -2419,19 +2963,28 @@ STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, stbtt } } + // restore original values + spc->h_oversample = old_h_over; + spc->v_oversample = old_v_over; + return return_value; } +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) +{ + stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); +} + STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) { stbtt_fontinfo info; int i,j,n, return_value = 1; - stbrp_context *context = (stbrp_context *) spc->pack_info; + //stbrp_context *context = (stbrp_context *) spc->pack_info; stbrp_rect *rects; // flag all characters as NOT packed for (i=0; i < num_ranges; ++i) - for (j=0; j < ranges[i].num_chars_in_range; ++j) + for (j=0; j < ranges[i].num_chars; ++j) ranges[i].chardata_for_range[j].x0 = ranges[i].chardata_for_range[j].y0 = ranges[i].chardata_for_range[j].x1 = @@ -2439,29 +2992,32 @@ STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, unsigned char *fontd n = 0; for (i=0; i < num_ranges; ++i) - n += ranges[i].num_chars_in_range; + n += ranges[i].num_chars; rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); if (rects == NULL) return 0; + info.userdata = spc->user_allocator_context; stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); - stbrp_pack_rects(context, rects, n); + stbtt_PackFontRangesPackRects(spc, rects, n); return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); + STBTT_free(rects, spc->user_allocator_context); return return_value; } STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, unsigned char *fontdata, int font_index, float font_size, - int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) + int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) { stbtt_pack_range range; - range.first_unicode_char_in_range = first_unicode_char_in_range; - range.num_chars_in_range = num_chars_in_range; + range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; + range.array_of_unicode_codepoints = NULL; + range.num_chars = num_chars_in_range; range.chardata_for_range = chardata_for_range; range.font_size = font_size; return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); @@ -2473,8 +3029,8 @@ STBTT_DEF void stbtt_GetPackedQuad(stbtt_packedchar *chardata, int pw, int ph, i stbtt_packedchar *b = chardata + char_index; if (align_to_integer) { - float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5); - float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5); + float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); + float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); q->x0 = x; q->y0 = y; q->x1 = x + b->xoff2 - b->xoff; @@ -2656,3 +3212,52 @@ STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *font_collection, const } #endif // STB_TRUETYPE_IMPLEMENTATION + + +// FULL VERSION HISTORY +// +// 1.10 (2016-04-02) allow user-defined fabs() replacement +// fix memory leak if fontsize=0.0 +// fix warning from duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// allow PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ +// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match +// non-oversampled; STBTT_POINT_SIZE for packed case only +// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling +// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) +// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID +// 0.8b (2014-07-07) fix a warning +// 0.8 (2014-05-25) fix a few more warnings +// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back +// 0.6c (2012-07-24) improve documentation +// 0.6b (2012-07-20) fix a few more warnings +// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, +// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty +// 0.5 (2011-12-09) bugfixes: +// subpixel glyph renderer computed wrong bounding box +// first vertex of shape can be off-curve (FreeSans) +// 0.4b (2011-12-03) fixed an error in the font baking example +// 0.4 (2011-12-01) kerning, subpixel rendering (tor) +// bugfixes for: +// codepoint-to-glyph conversion using table fmt=12 +// codepoint-to-glyph conversion using table fmt=4 +// stbtt_GetBakedQuad with non-square texture (Zer) +// updated Hello World! sample to use kerning and subpixel +// fixed some warnings +// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) +// userdata, malloc-from-userdata, non-zero fill (stb) +// 0.2 (2009-03-11) Fix unsigned/signed char warnings +// 0.1 (2009-03-09) First public release +// diff --git a/src/demo_LQR_infHor.cpp b/src/demo_LQR_infHor.cpp new file mode 100644 index 0000000..ac523ba --- /dev/null +++ b/src/demo_LQR_infHor.cpp @@ -0,0 +1,358 @@ +/* + * demo_LQR_infHor.cpp + * + * Discrete infinite horizon linear quadratic regulation + * + * Fabien Crépon, Philip Abbet, Sylvain Calinon, 2017 + */ + +#include <stdio.h> +#include <imgui.h> +#include <imgui_impl_glfw_gl3.h> +#include <gfx3.h> +#include <gfx_ui.h> +#include <GLFW/glfw3.h> + +#include <armadillo> +#include <pbdlib/gmm.h> +#include <pbdlib/lqr.h> + + + +/****************************** HELPER FUNCTIONS *****************************/ + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +//----------------------------------------------- + +int factorial(int n) { + return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; +} + +//----------------------------------------------------------------------------- +// Computes RG (in OpenGL-space) from gaussian transformations (in UI-space) +// +// UI coordinates range from (0, 0) to (win_width, win_height) +// OpenGL coordinates range from (-fb_width / 2, fb_height / 2) to +// (fb_width / 2, -fb_height / 2) +//----------------------------------------------------------------------------- +arma::mat trans2RG(const ui::Trans2d& trans, int win_width, int win_height, + int fb_width, int fb_height) { + float scale_x = (float) fb_width / (float) win_width; + float scale_y = (float) fb_height / (float) win_height; + + arma::mat RG = { + { trans.x.x * scale_x, trans.y.x * scale_x }, + { -trans.x.y * scale_y, -trans.y.y * scale_y } + }; + + return RG; +} + + +/******************************* MAIN FUNCTION *******************************/ + +int main(int argc, char **argv){ + arma_rng::set_seed_random(); + + //--------------- Setup parameters --------------- + + int nbData = 100; //Number of datapoints + int nbRepros = 10; //Number of reproductions + int nbVarPos = 2; //Dimension of position data (here: x1,x2) + int nbDeriv = 2; //Number of static & dynamic features (D=2 for [x,dx]) + int nbVar = nbVarPos * nbDeriv; //Dimension of state vector in the tangent space + double dt = 1E-2; //Time step duration + double rfactor = 1E-8; //Control cost in LQR + + // Control cost + arma::mat R = eye(nbVarPos,nbVarPos) * rfactor; + + // Target + arma::vec Utar = {100.0, 300.0, 0, 0}; + + // Initial positions + arma:mat U0(nbVarPos, 0); + arma::mat pts0(2, 35), pts(3, 35, fill::zeros); + pts0 = join_cols(cos(linspace<rowvec>(0, 2 * PI, 35)), sin(linspace<rowvec>(0, 2 * PI, 35))); + arma::mat RG(2, 2, fill::eye); + + + //--------------- Discrete dynamical system settings --------------- + + arma::mat A, B; + arma::mat A1d(zeros(nbDeriv, nbDeriv)); + for (int i = 0; i <= nbDeriv - 1 ; i++) { + A1d = A1d + diagmat(ones(nbDeriv - i, 1), i) * pow(dt, i) * 1. / factorial(i); + } + arma::mat B1d(zeros(nbDeriv, 1)); + for (int i = 1; i <= nbDeriv ; i++) { + B1d(nbDeriv - i, 0) = pow(dt, i) * 1. / factorial(i); + } + A = kron(A1d, eye(nbVarPos, nbVarPos)); + B = kron(B1d, eye(nbVarPos, nbVarPos)); + + // Initialize discrete LQR with infinite horizon + pbdlib::LQR lqr(A, B, dt); + + + //--------------- Setup of the rendering --------------- + + // Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + return -1; + + glfwWindowHint(GLFW_SAMPLES, 4); + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + + GLFWwindow* window = glfwCreateWindow(600, 600, "Demo LQR", NULL, NULL); + glfwMakeContextCurrent(window); + + // Take 4k screens into account (framebuffer size != window size) + int win_width = ImGui::GetIO().DisplaySize.x; + int win_height = ImGui::GetIO().DisplaySize.y; + + int fb_width, fb_height; + glfwGetFramebufferSize(window, &fb_width, &fb_height); + + // Setup GLSL + gfx3::init(); + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_LINE_SMOOTH); + glDepthFunc(GL_LESS); + + // Creation of the Vertex Array Object (VAO) + GLuint vertexArrayID; + glGenVertexArrays(1, &vertexArrayID); + glBindVertexArray(vertexArrayID); + + // Setup ImGui + ImGui_ImplGlfwGL3_Init(window, true); + ImVec4 clear_color = ImColor(0, 0, 40); + + + //--------------- Rendering matrices, shaders, models --------------- + + // Gaussian UI widget + ui::Trans2d trans(ImVec2(80.0f, 0.0f), ImVec2(0.0f, 100.0f), + ImVec2((float) Utar(0),(float) Utar(1))); + + + // Projection matrix + arma::fmat projection = gfx3::orthographic( + (float) fb_width, (float) fb_height, 0.1f, 10.0f); + + // Camera matrix + arma::fmat view = gfx3::lookAt( + arma::fvec({0, 0, 3}), // Position of the camera + arma::fvec({0, 0, 0}), // Look at the origin + arma::fvec({0, 1, 0}) // Head is up + ); + + gfx3::light_list_t lights; // Not used, but required by gfx3 + + + // Loading of the shaders + gfx3::shader_t rtt_shader = gfx3::loadShader(gfx3::RTT_VERTEX_SHADER, + gfx3::RTT_FRAGMENT_SHADER_LIC); + + rtt_shader.setUniform("Time", 0.0f); + rtt_shader.setUniform("Sigma", arma::fmat(nbVarPos, nbVarPos)); + rtt_shader.setUniform("Resolution", arma::fvec({512, 512})); + rtt_shader.setUniform("Target", arma::vec(gfx3::ui2shader({trans.pos.x, trans.pos.y}, + win_width, win_height, + fb_width, fb_height))); + + gfx3::shader_t background_shader = gfx3::loadShader(gfx3::VERTEX_SHADER_TEXTURED, + gfx3::FRAGMENT_SHADER_ONE_TEXTURE); + + gfx3::shader_t colored_shader = gfx3::loadShader(gfx3::VERTEX_SHADER_COLORED, + gfx3::FRAGMENT_SHADER_COLORED); + + // Creation of the RTTs + gfx3::render_to_texture_t background_rtt = gfx3::createRTT(rtt_shader, 512, 512, + arma::fvec({ 0.5f, 0.5f, 0.5f })); + + // Creation of the background model + gfx3::model_t background = gfx3::create_rectangle(background_shader, + arma::fvec({ 0.5f, 0.0f, 0.0f }), + (float) fb_width, (float) fb_height); + background.diffuse_texture = background_rtt.texture(); + + + //--------------- Main loop --------------- + + while (!glfwWindowShouldClose(window)) { + glfwPollEvents(); + + // Detect when the window was resized + if ((ImGui::GetIO().DisplaySize.x != win_width) || (ImGui::GetIO().DisplaySize.y != win_height)) { + int previous_win_width = win_width; + int previous_win_height = win_height; + int previous_fb_width = fb_width; + int previous_fb_height = fb_height; + + // Retrieve the new window size + win_width = ImGui::GetIO().DisplaySize.x; + win_height = ImGui::GetIO().DisplaySize.y; + + // Retrieve the new framebuffer size + glfwGetFramebufferSize(window, &fb_width, &fb_height); + + // Update the projection matrix + projection = gfx3::orthographic((float) fb_width, (float) fb_height, 0.1f, 10.0f); + + // Recreate the background model + gfx3::destroy(background); + + background = gfx3::create_rectangle(background_shader, arma::fvec({ 0.5f, 0.0f, 0.0f }), + (float) fb_width, (float) fb_height); + background.diffuse_texture = background_rtt.texture(); + + // Move and rescale the various objects so they stay in the window + if (previous_win_width > 0) { + float scale = std::min((float) fb_width / previous_fb_width, (float) fb_height / previous_fb_height); + + U0 *= scale; + + arma::vec target = gfx3::fb2ui(gfx3::ui2fb({trans.pos.x, trans.pos.y}, + previous_win_width, previous_win_height, + previous_fb_width, previous_fb_height) * scale, + win_width, win_height, fb_width, fb_height); + trans.pos.x = target(0); + trans.pos.y = target(1); + + trans.x.x *= scale; + trans.x.y *= scale; + trans.y.x *= scale; + trans.y.y *= scale; + } + } + + // Detect if the number of reproductions has changed + if (nbRepros > U0.n_cols) { + unsigned int nb = U0.n_cols; + U0.reshape(nbVarPos, nbRepros); + + for (int i = nb; i < nbRepros; ++i) { + U0.col(i) = arma::vec({(randu() - 0.5) * fb_width, (randu() - 0.5) * fb_height}); + } + } + else if (nbRepros < U0.n_cols) { + U0.reshape(nbVarPos, nbRepros); + } + + // Start of rendering + ImGui_ImplGlfwGL3_NewFrame(); + glViewport(0, 0, fb_width, fb_height); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, fb_width, fb_height, 0, -1., 1.); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glPushMatrix(); + + // Gaussian UI widget + ui::begin("Gaussian"); + trans = ui::affineSimple(0, trans); + Utar = gfx3::ui2fb({trans.pos.x, trans.pos.y, 0, 0}, win_width, win_height, + fb_width, fb_height); + RG = trans2RG(trans, win_width, win_height, fb_width, fb_height); + ui::end(); + + // Recompute LQR + arma::mat Q = inv(RG * RG.t()); + Q.resize(nbVar, nbVar); + arma::mat P = lqr.solveAlgebraicRiccati_Discrete(A, B, Q, R); + arma::mat L = inv(B.t() * P * B + R) * B.t() * P * A; + arma::vec U(nbVar, fill::zeros); + arma::vec ddu(nbVarPos); + std::vector<arma::mat> reproductions; + + for (int n = 0; n < nbRepros; n++) { + arma::mat reproduction(nbVar, nbData); + U = { U0(0, n), U0(1, n), 0, 0 }; + + for (int t = 0; t < nbData; t++) { + reproduction.col(t) = U; + ddu = L * (Utar - U); + U = A * U + B * ddu; + } + + reproduction.rows(nbVarPos, nbVar-1).zeros(); + + reproductions.push_back(reproduction); + } + + // RTT rendering + rtt_shader.setUniform("Time", (float) glfwGetTime()); + rtt_shader.setUniform("Sigma", conv_to<fmat>::from(inv(RG * RG.t()))); + rtt_shader.setUniform("Target", arma::vec(gfx3::ui2shader({trans.pos.x, trans.pos.y}, + win_width, win_height, + fb_width, fb_height))); + + gfx3::draw(background_rtt); + + background.diffuse_texture = background_rtt.texture(); + + // Draw repros + for (size_t i = 0; i < reproductions.size(); ++i) { + gfx3::model_t line = gfx3::create_line( + colored_shader, arma::fvec({0.33f, 0.97f, 0.33f}), reproductions[i]); + + gfx3::draw(line, view, projection, lights); + + gfx3::destroy(line); + } + + // Draw the gaussian + pts.rows(0, 1) = arma::mat(RG * pts0).each_col() + Utar.subvec(0, 1); + + gfx3::model_t line = gfx3::create_line( + colored_shader, arma::fvec({1.0f, 0.33f, 0.33f}), pts); + + gfx3::draw(line, view, projection, lights); + + gfx3::destroy(line); + + // Draw the background + gfx3::draw(background, view, projection, lights); + + // Parameter window + ImGui::SetNextWindowSize(ImVec2(400, 50)); + ImGui::Begin("Parameters", NULL, + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoMove + ); + ImGui::SliderInt("Nb reproductions", &nbRepros, 1, 10); + ImGui::End(); + + // UI rendering + ImGui::Render(); + + // End of rendering + glPopMatrix(); + glfwSwapBuffers(window); + + // Keyboard input + if (ImGui::IsKeyPressed(GLFW_KEY_ESCAPE)) + break; + } + + // Cleanup + ImGui_ImplGlfwGL3_Shutdown(); + glfwTerminate(); + + return 0; +} diff --git a/src/demo_MPC_batch_01.cpp b/src/demo_MPC_batch_01.cpp new file mode 100644 index 0000000..7c110b8 --- /dev/null +++ b/src/demo_MPC_batch_01.cpp @@ -0,0 +1,344 @@ +/* + * demo_MPC_batch_01.cpp + * + * Interactive MPC demo, with batch LQT and repulsive field test + * + * Fabien Crépon, Sylvain Calinon, 2017 + */ + +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include "gfx_ui.h" +#include <stdio.h> +#include <GLFW/glfw3.h> +#include "mpc_utils.h" + +#include "armadillo" +#include <pbdlib/gmm.h> +#include <pbdlib/gmr.h> +#include <pbdlib/lqr.h> + +#include "gl2ps.h" + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +int factorial(int n){ + return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; +} + +void setOrtho( float w, float h ) +{ + glMatrixMode( GL_PROJECTION ); + glLoadIdentity(); + glOrtho( 0, 0+w, 0+h, 0, -1., 1.); + glMatrixMode( GL_MODELVIEW ); + glLoadIdentity(); +} + +void trans2d_to_gauss(arma::vec* mu, arma::mat* Sigma, const ui::Trans2d& t2d) +{ + arma::mat basis = arma::mat{{t2d.x.x, t2d.y.x}, {t2d.x.y, t2d.y.y}}; + *Sigma = basis * basis.t(); + *mu = arma::vec({t2d.pos.x, t2d.pos.y}); +} + +void gauss_to_trans2d(ui::Trans2d *t2d, const arma::vec& mu, const arma::mat& Sigma) +{ + t2d->pos.x = mu(0); + t2d->pos.y = mu(1); + arma::mat V; + arma::vec d; + arma::eig_sym(d, V, Sigma); + arma::mat VD = V*diagmat(sqrt(d)); + t2d->x.x = VD.col(0)(0); + t2d->x.y = VD.col(0)(1); + t2d->y.x = VD.col(1)(0); + t2d->y.y = VD.col(1)(1); +} + +void draw(const arma::mat& pts, int primitive=GL_LINE_STRIP) +{ + glBegin(primitive); + for (uint t=0; t<pts.n_cols; t++){ + glVertex2f(pts(0,t), pts(1,t)); + } + glEnd(); +} + +arma::mat gradient_2d( arma::mat X, int order=1 ) +{ + mat df = diff(X, 1, 1); + mat db = fliplr( -diff(fliplr(X), 1, 1) ); + mat d = (df+db)/2; + d = join_horiz(zeros(2,1), d); + d.col(0) = df.col(0); + d.col(d.n_cols-1) = db.col(db.n_cols-1); + if(order>1) + return gradient_2d(d, order-1); + return d; +} + +void plot( float x, float y, float w, float h, const vec& v ) +{ + float v_min = v.min(); + float v_max = v.max(); + float inc = w / v.n_rows; + glBegin(GL_LINE_STRIP); + for (int i=0; i < v.n_rows; i++) + { + glVertex2f(x + inc*i, y - h * ((v[i] - v_min) / (v_max - v_min))); + } + glEnd(); +} + +void drawGauss( ui::Trans2d& t2d ) +{ + static arma::mat circ(2,35); + static bool circ_init = true; + if(circ_init) + { + circ = join_cols(cos(linspace<rowvec>(0,2*PI,35)), sin(linspace<rowvec>(0,2*PI,35))); + circ_init = false; + } + arma::mat basis = arma::mat{{t2d.x.x, t2d.y.x}, {t2d.x.y, t2d.y.y}}; + arma::mat pts = basis*circ + arma::repmat(vec({t2d.pos.x, t2d.pos.y}), 1, 35); + + glBegin(GL_TRIANGLE_FAN); + glVertex2f(t2d.pos.x, t2d.pos.y); + for (uint t=0; t<pts.n_cols; t++){ + glVertex2f(pts(0,t), pts(1,t)); + } + glEnd(); +} + +int main(int argc, char **argv){ + + arma_rng::set_seed_random(); + + //---------------------------------------Setup parameters---------------------------------------------------- + //----------------------------------------------------------------------------------------------------------- + int w = 800; + int h = 600; + + double dt = 0.01; + int order = 4; + + int m = 5; // Number of targets + double globScale = 0.0001; // global scale, avoids numerical issues in batch method + double endWeight = 1.; //1e-10; // forces movement to a stop (see stepwiseReference function) + + float d=10.1; // maximum displacement, used to compute R diagonal + float stroke_duration=0.3; // duration of a stroke + + // Gui settings + int plot_deriv = 1; + + // targets + arma::mat V = arma::randu(2, m); + V.row(0) *= w; + V.row(1) *= h; + + // Covariances + mat Mu = V; + cube Sigma; + randomCovariances(&Sigma, Mu, arma::vec({50.,50.}), false, 0.0, 0.8); + + // Gaussians + std::vector<ui::Trans2d> t2ds(m, ui::Trans2d()); + for( int i = 0; i < m; i++ ) + gauss_to_trans2d(&t2ds[i], Mu.col(i), Sigma.slice(i)); + + //------------------------------------------------Plots----------------------------------------------------- + //---------------------------------------------------------------------------------------------------------- + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(w, h, "Demo Batch MPC", NULL, NULL); + glfwMakeContextCurrent(window); + + //Setup ImGui + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(255, 255, 255); + + FILE * eps_file = NULL; + bool saving_eps = false; + + while (!glfwWindowShouldClose(window)) { + w = ImGui::GetIO().DisplaySize.x; + h = ImGui::GetIO().DisplaySize.y; + + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + + if(saving_eps) + { + eps_file = fopen("out.eps", "wb"); + gl2psBeginPage("grab", "gl2psTestSimple", NULL, GL2PS_EPS, GL2PS_SIMPLE_SORT, + GL2PS_DRAW_BACKGROUND | GL2PS_USE_CURRENT_VIEWPORT, + GL_RGBA, 0, NULL, 0, 0, 0, 0, eps_file, "out.eps"); + } + + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + + setOrtho(ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y); + + //Model rendering + glPushMatrix(); + + // Gauss UI + ui::begin("Gaussian"); + arma::vec mu; + arma::mat Sigm; + + for( int i = 0; i < m; i++ ) + { + t2ds[i] = ui::affineSimple(i, t2ds[i]); + trans2d_to_gauss(&mu, &Sigm, t2ds[i]); + Mu.col(i) = mu; + Sigma.slice(i) = Sigm; + } + ui::end(); + + // Slider window + int winw = 250; + ImGui::SetNextWindowPos(ImVec2(w-winw,2)); + ImGui::Begin("Params", NULL, ImVec2(winw,300), 0.5f, + ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize| + ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings); + if(ImGui::Button("Save EPS")) + { + saving_eps = true; + } + ImGui::SliderInt("Order", &order, 2, 7); + ImGui::SliderFloat("Max Displacement", &d, 0.1, 100.); + ImGui::SliderInt("Plot deriv", &plot_deriv, 1, 3); + ImGui::End(); + + // Recompute LQR + int dim = 2; + double duration = stroke_duration * m; + int n = (int)(duration/dt); + int cDim = dim * order; + + // system matrices + mat A, B; + makeIntegratorChain(&A, &B, order); + discretizeSystem(&A, &B, A, B, dt); + // make bi-variate + A = kron(A, eye(dim, dim)); + B = kron( B, eye(dim, dim) ); + + // reference + mat Q, MuQ; + stepwiseReference( &MuQ, &Q, Mu, Sigma, n, order, dim, endWeight ); + MuQ *= globScale; + Q /= globScale*globScale; + + // r based on oscillatory movement displacement + double r = SHM_r(d*globScale, stroke_duration, order); + mat R = kron( eye(n-1, n-1), + eye(dim, dim) * r ); + + //////////////////////////////////// + // Batch LQR + + // Sx and Su matrices for batch LQR + mat Su = zeros(cDim*n, dim*(n-1)); + mat Sx = kron( ones(n,1), + eye(dim*order, dim*order)); + mat M = B; + for( int i = 1; i < n; i++ ) + { + Sx.rows( i*cDim, n*cDim-1 ) = + Sx.rows( i*cDim, n*cDim-1 ) * A; + Su.submat( i*cDim, 0, + (i+1)*cDim-1, i*dim-1 ) = M; + M = join_horiz( A*M.cols(0, dim-1), M ); + } + + arma::vec x0 = MuQ.col(0); + + // Flatten Mu's + mat Xi_hat = reshape(MuQ, cDim*n, 1); + + mat SuInvSigmaQ = Su.t()*Q; + + mat Rq, rq; + + Rq = SuInvSigmaQ*Su + R; + rq = SuInvSigmaQ*(Xi_hat - Sx*x0); + + // least squares solution + vec u = solve(Rq,rq); + mat Y = reshape( Sx*x0 + Su*u, cDim, n ); + mat Xi = Y.submat(0,0, dim-1, n-1) / globScale; + + ////////////////////////////////////// + + glEnable( GL_BLEND ); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // draw gaussians + glColor4f(0.0, 0.5f, 1.0f, 0.2f); + for( int i = 0; i < m; i++ ) + { + drawGauss(t2ds[i]); + } + + // draw motor plan + glColor3f(0.5,0.5,0.5); + draw(Mu); + + // draw trajectory + glColor3f(0, 0, 0); + draw(Xi); + + // plot derivatives magnitude + glColor3f(1,0,0); + mat dx = gradient_2d(Xi, plot_deriv); //, 1, 1); + vec speed = sqrt(sum(dx%dx, 0)).t(); + plot(10, h, 200, 100, speed); + + ui::begin("Text"); + const char* sderiv[] = + { + "velocity", + "acceleration", + "jerk" + }; + ui::textf(ImVec2(200+10, h-20), "%s magnitude", sderiv[plot_deriv-1]); //sderiv[plot_deriv-1]); + ui::end(); + + glPopMatrix(); + + // Render UI + ImGui::Render(); + + // save eps + if(eps_file) + { + glFlush(); + gl2psEndPage(); + fclose(eps_file); + eps_file=NULL; + saving_eps=false; + } + + glfwSwapBuffers(window); + + //Keyboard input + if (ImGui::IsKeyPressed(GLFW_KEY_ESCAPE)) + break; + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + return 0; +} diff --git a/src/demo_MPC_iterative_01.cpp b/src/demo_MPC_iterative_01.cpp new file mode 100644 index 0000000..277d004 --- /dev/null +++ b/src/demo_MPC_iterative_01.cpp @@ -0,0 +1,322 @@ +/* + * demo_MPC_iterative_01.cpp + * + * Interactive MPC demo, with iterative LQT + * + * Fabien Crépon, Sylvain Calinon, 2017 + */ + +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include "gfx_ui.h" +#include <stdio.h> +#include <GLFW/glfw3.h> +#include "mpc_utils.h" + +#include "armadillo" +#include <pbdlib/gmm.h> +#include <pbdlib/gmr.h> +#include <pbdlib/lqr.h> + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +int factorial(int n){ + return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; +} + +void setOrtho( float w, float h ) +{ + glMatrixMode( GL_PROJECTION ); + glLoadIdentity(); + glOrtho( 0, 0+w, 0+h, 0, -1., 1.); + glMatrixMode( GL_MODELVIEW ); + glLoadIdentity(); +} + +void trans2d_to_gauss(arma::vec* mu, arma::mat* Sigma, const ui::Trans2d& t2d) +{ + arma::mat basis = arma::mat{{t2d.x.x, t2d.y.x}, {t2d.x.y, t2d.y.y}}; + *Sigma = basis * basis.t(); + *mu = arma::vec({t2d.pos.x, t2d.pos.y}); +} + +void gauss_to_trans2d(ui::Trans2d *t2d, const arma::vec& mu, const arma::mat& Sigma) +{ + t2d->pos.x = mu(0); + t2d->pos.y = mu(1); + arma::mat V; + arma::vec d; + arma::eig_sym(d, V, Sigma); + arma::mat VD = V*diagmat(sqrt(d)); + t2d->x.x = VD.col(0)(0); + t2d->x.y = VD.col(0)(1); + t2d->y.x = VD.col(1)(0); + t2d->y.y = VD.col(1)(1); +} + +void draw(const arma::mat& pts, int primitive=GL_LINE_STRIP) +{ + glBegin(primitive); + for (uint t=0; t<pts.n_cols; t++){ + glVertex2f(pts(0,t), pts(1,t)); + } + glEnd(); +} + +arma::mat gradient_2d( arma::mat X, int order=1 ) +{ + mat df = diff(X, 1, 1); + mat db = fliplr( -diff(fliplr(X), 1, 1) ); + mat d = (df+db)/2; + d = join_horiz(zeros(2,1), d); + d.col(0) = df.col(0); + d.col(d.n_cols-1) = db.col(db.n_cols-1); + if(order>1) + return gradient_2d(d, order-1); + return d; +} + +void plot( float x, float y, float w, float h, const vec& v ) +{ + float v_min = v.min(); + float v_max = v.max(); + float inc = w / v.n_rows; + glBegin(GL_LINE_STRIP); + for (int i=0; i < v.n_rows; i++) + { + glVertex2f(x + inc*i, y - h * ((v[i] - v_min) / (v_max - v_min))); + } + glEnd(); +} + +void drawGauss( ui::Trans2d& t2d ) +{ + static arma::mat circ(2,35); + static bool circ_init = true; + if(circ_init) + { + circ = join_cols(cos(linspace<rowvec>(0,2*PI,35)), sin(linspace<rowvec>(0,2*PI,35))); + circ_init = false; + } + arma::mat basis = arma::mat{{t2d.x.x, t2d.y.x}, {t2d.x.y, t2d.y.y}}; + arma::mat pts = basis*circ + arma::repmat(vec({t2d.pos.x, t2d.pos.y}), 1, 35); + + glBegin(GL_TRIANGLE_FAN); + glVertex2f(t2d.pos.x, t2d.pos.y); + for (uint t=0; t<pts.n_cols; t++){ + glVertex2f(pts(0,t), pts(1,t)); + } + glEnd(); +} + +int main(int argc, char **argv){ + + arma_rng::set_seed_random(); + + //---------------------------------------Setup parameters---------------------------------------------------- + //----------------------------------------------------------------------------------------------------------- + int w = 800; + int h = 600; + + double dt = 0.01; + int order = 5; + + int m = 3; // Number of targets + double globScale = 0.001; // global scale, avoids numerical issues in batch method + double endWeight = 1.; //1e-10; // forces movement to a stop (see stepwiseReference function) + + float d=0.1; // maximum displacement, used to compute R diagonal + float stroke_duration=0.3; // duration of a stroke + + // Gui settings + int plot_deriv = 1; + + // targets + arma::mat V = arma::randu(2, m); + V.row(0) *= w; + V.row(1) *= h; + + // Covariances + mat Mu = V; + cube Sigma; + randomCovariances(&Sigma, Mu, arma::vec({120.,50.}), false, 0.0, 0.8); + + // Gaussians + std::vector<ui::Trans2d> t2ds(m, ui::Trans2d()); + for( int i = 0; i < m; i++ ) + gauss_to_trans2d(&t2ds[i], Mu.col(i), Sigma.slice(i)); + + //------------------------------------------------Plots----------------------------------------------------- + //---------------------------------------------------------------------------------------------------------- + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(w, h, "Demo Iterative MPC", NULL, NULL); + glfwMakeContextCurrent(window); + + //Setup ImGui + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(255, 255, 255); + + while (!glfwWindowShouldClose(window)) { + w = ImGui::GetIO().DisplaySize.x; + h = ImGui::GetIO().DisplaySize.y; + + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + + setOrtho(ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y); + + //Model rendering + glPushMatrix(); + + // Gauss UI + ui::begin("Gaussian"); + arma::vec mu; + arma::mat Sigm; + + for( int i = 0; i < m; i++ ) + { + t2ds[i] = ui::affineSimple(i, t2ds[i]); + trans2d_to_gauss(&mu, &Sigm, t2ds[i]); + Mu.col(i) = mu; + Sigma.slice(i) = Sigm; + } + + ui::end(); + + // Slider window + int winw = 250; + ImGui::SetNextWindowPos(ImVec2(w-winw,2)); + ImGui::Begin("Params", NULL, ImVec2(winw,300), 0.5f, + ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize| + ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings); + ImGui::SliderInt("Order", &order, 2, 7); + ImGui::SliderFloat("Max Displacement", &d, 0.05, 5.); + ImGui::SliderInt("Plot deriv", &plot_deriv, 1, 3); + ImGui::End(); + + // Recompute LQR + int dim = 2; + double duration = stroke_duration * m; + int n = (int)(duration/dt); + int cDim = dim * order; + + // system matrices + mat A, B; + makeIntegratorChain(&A, &B, order); + discretizeSystem(&A, &B, A, B, dt); + // make bi-variate + A = kron(A, eye(dim, dim)); + B = kron( B, eye(dim, dim) ); + + // reference + mat Q, MuQ, Q0, MuQ0; + stepwiseReference( &MuQ, &Q, Mu, Sigma, n, order, dim, endWeight ); + MuQ *= globScale; + Q /= globScale*globScale; + + // r based on oscillatory movement displacement + double r = SHM_r(d, stroke_duration, order); + + //////////////////////////////////// + // Iterative LQR + mat R = eye(dim, dim) * r; + + cube P = zeros(cDim, cDim, n); + int i = n-1; + P.slice(i) = Q.submat(span(i*cDim,i*cDim+cDim-1),span(i*cDim,i*cDim+cDim-1)); + + mat D = zeros(cDim, n); + // Riccati recursion + for( int i = n-2; i >=0; i-- ) + { + mat Qi = Q.submat(span(i*cDim,i*cDim+cDim-1),span(i*cDim,i*cDim+cDim-1)); + mat P2 = P.slice(i+1); + P.slice(i) = Qi - (A.t() * (P2 * B * inv(B.t() * P2 * B + R) * B.t() * P2 - P2 ) * A); + D.col(i) = (A.t() - A.t() * P2 * B * inv(B.t() * P2 * B + R) * B.t()) + * (P2 * (A * MuQ.col(i) - MuQ.col(i+1)) + D.col(i+1)); + } + + // compute trajectory + arma::vec x0 = MuQ.col(0); + mat Y = zeros(cDim, n); + vec x = x0; + + for( int i = 0; i < n; i++ ) + { + Y.col(i) = x; + mat p = P.slice(i); + vec mu = MuQ.col(i); + + mat G = inv( B.t() * p * B + R ) * B.t(); + + // feedback gain + mat K = G * p * A; + // Feedforward term + mat M = -G * (p * (A * mu - mu) + D.col(i)); + // Control command (highest order derivative of system) + vec u = K * (mu - x) + M; + // New state + x = A*x + B*u; + } + + mat Xi = Y.submat(0,0, dim-1, n-1) / globScale; + + ////////////////////////////////////// + + glEnable( GL_BLEND ); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // draw gaussians + glColor4f(0.0, 0.5f, 1.0f, 0.2f); + for( int i = 0; i < m; i++ ) + { + drawGauss(t2ds[i]); + } + + // draw trajectory + glColor3f(0, 0, 0); + draw(Xi); + + // plot derivatives magnitude + glColor3f(1,0,0); + mat dx = gradient_2d(Xi, plot_deriv); //, 1, 1); + vec speed = sqrt(sum(dx%dx, 0)).t(); + plot(10, h, 200, 100, speed); + + ui::begin("Text"); + const char* sderiv[] = + { + "velocity", + "acceleration", + "jerk" + }; + ui::textf(ImVec2(200+10, h-20), "%s magnitude", sderiv[plot_deriv-1]); //sderiv[plot_deriv-1]); + ui::end(); + + glPopMatrix(); + + // Render UI + ImGui::Render(); + + glfwSwapBuffers(window); + + //Keyboard input + if (ImGui::IsKeyPressed(GLFW_KEY_ESCAPE)) + break; + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + return 0; +} diff --git a/src/demo_MPC_semitied_01.cpp b/src/demo_MPC_semitied_01.cpp new file mode 100644 index 0000000..0625825 --- /dev/null +++ b/src/demo_MPC_semitied_01.cpp @@ -0,0 +1,402 @@ +/* + * demo_MPC_batch_01.cpp + * + * Interactive MPC demo, demonstrates a GUI to edit semi-tied covariances (2d) + * + * Fabien Crépon, Sylvain Calinon, 2017 + */ + +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include "gfx_ui.h" +#include <stdio.h> +#include <GLFW/glfw3.h> +#include "mpc_utils.h" + +#include "armadillo" +#include <pbdlib/gmm.h> +#include <pbdlib/gmr.h> +#include <pbdlib/lqr.h> + +#include "gl2ps.h" + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +int factorial(int n){ + return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; +} + +void setOrtho( float w, float h ) +{ + glMatrixMode( GL_PROJECTION ); + glLoadIdentity(); + glOrtho( 0, 0+w, 0+h, 0, -1., 1.); + glMatrixMode( GL_MODELVIEW ); + glLoadIdentity(); +} + +void trans2d_to_gauss(arma::vec* mu, arma::mat* Sigma, const ui::Trans2d& t2d) +{ + arma::mat basis = arma::mat{{t2d.x.x, t2d.y.x}, {t2d.x.y, t2d.y.y}}; + *Sigma = basis * basis.t(); + *mu = arma::vec({t2d.pos.x, t2d.pos.y}); +} + +void gauss_to_trans2d(ui::Trans2d *t2d, const arma::vec& mu, const arma::mat& Sigma) +{ + t2d->pos.x = mu(0); + t2d->pos.y = mu(1); + arma::mat V; + arma::vec d; + arma::eig_sym(d, V, Sigma); + arma::mat VD = V*diagmat(sqrt(d)); + t2d->x.x = VD.col(0)(0); + t2d->x.y = VD.col(0)(1); + t2d->y.x = VD.col(1)(0); + t2d->y.y = VD.col(1)(1); +} + +void draw(const arma::mat& pts, int primitive=GL_LINE_STRIP) +{ + glBegin(primitive); + for (uint t=0; t<pts.n_cols; t++){ + glVertex2f(pts(0,t), pts(1,t)); + } + glEnd(); +} + +arma::mat gradient_2d( arma::mat X, int order=1 ) +{ + mat df = diff(X, 1, 1); + mat db = fliplr( -diff(fliplr(X), 1, 1) ); + mat d = (df+db)/2; + d = join_horiz(zeros(2,1), d); + d.col(0) = df.col(0); + d.col(d.n_cols-1) = db.col(db.n_cols-1); + if(order>1) + return gradient_2d(d, order-1); + return d; +} + +void plot( float x, float y, float w, float h, const vec& v ) +{ + float v_min = v.min(); + float v_max = v.max(); + float inc = w / v.n_rows; + glBegin(GL_LINE_STRIP); + for (int i=0; i < v.n_rows; i++) + { + glVertex2f(x + inc*i, y - h * ((v[i] - v_min) / (v_max - v_min))); + } + glEnd(); +} + +void drawGauss( ui::Trans2d& t2d ) +{ + static arma::mat circ(2,35); + static bool circ_init = true; + if(circ_init) + { + circ = join_cols(cos(linspace<rowvec>(0,2*PI,35)), sin(linspace<rowvec>(0,2*PI,35))); + circ_init = false; + } + arma::mat basis = arma::mat{{t2d.x.x, t2d.y.x}, {t2d.x.y, t2d.y.y}}; + arma::mat pts = basis*circ + arma::repmat(vec({t2d.pos.x, t2d.pos.y}), 1, 35); + + glBegin(GL_TRIANGLE_FAN); + glVertex2f(t2d.pos.x, t2d.pos.y); + for (uint t=0; t<pts.n_cols; t++){ + glVertex2f(pts(0,t), pts(1,t)); + } + glEnd(); +} + +arma::mat semitiedBasis( const arma::vec& params ) +{ + float t1 = params[0]; + float t2 = params[1]; + return {{cos(t1), cos(t2)}, {sin(t1), sin(t2)}}; +} + +arma::mat semitiedSigma( const arma::vec& params ) +{ + float h = params[2]; + arma::mat H = semitiedBasis(params); + return H*H.t()*h*h; +} + +arma::cube semitiedCovariances( const arma::mat& Mu, const arma::vec& params ) +{ + int m = Mu.n_cols; + arma::cube Sigma = arma::zeros(2,2,m); + arma::mat sigm = semitiedSigma(params); + for( int i = 0; i < m; i++ ) + { + Sigma.slice(i) = sigm; + } + return Sigma; +} + +arma::vec semitiedWidget(int id, arma::vec params, const arma::vec& pos, float minLength=2.0, float maxLength=500.0) +{ + float h = params[2]; + arma::vec theta = params.subvec(0,1); + for( int i = 0; i < 2; i++ ) + { + ImVec2 theta_length = ui::lengthHandle(id+i, ImVec2(theta[i], h), 0.0, pos, ImVec2(-1000.0, minLength), ImVec2(1000.0, maxLength)); + params[i] = theta_length.x; + h = theta_length.y; + } + params[2] = h; + + // draw ellipse + static arma::mat circ(2,35); + static bool circ_init = true; + if(circ_init) + { + circ = join_cols(cos(linspace<rowvec>(0,2*PI,35)), sin(linspace<rowvec>(0,2*PI,35))); + circ_init = false; + } + arma::mat basis = semitiedBasis(params); + arma::mat pts = basis*circ*h + arma::repmat(pos, 1, 35); + glColor4f(1.0,0.0,0.0,1.0); + draw(pts); + return params; +} + + + +int main(int argc, char **argv){ + + arma_rng::set_seed_random(); + + //---------------------------------------Setup parameters---------------------------------------------------- + //----------------------------------------------------------------------------------------------------------- + int w = 800; + int h = 600; + + double dt = 0.01; + int order = 4; + + int m = 4; // Number of targets + double globScale = 0.001; // global scale, avoids numerical issues in batch method + double endWeight = 1.; //1e-10; // forces movement to a stop (see stepwiseReference function) + + float d=0.05; // maximum displacement, used to compute R diagonal + float stroke_duration=0.3; // duration of a stroke + float covscale = 1.0; // hack, field covariance scaling factor + int fieldDeriv=1; // derivative used for additional field + // Gui settings + int plot_deriv = 1; + bool useField = true; + + // targets + arma::mat Mu = arma::randu(2, m); + Mu.row(0) *= w; + Mu.row(1) *= h; + // semi tied parameters (theta1, theta2, h) + arma::vec semitied_params = {0.0, PI/2, 100.0}; + + //------------------------------------------------Plots----------------------------------------------------- + //---------------------------------------------------------------------------------------------------------- + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(w, h, "Demo Batch MPC", NULL, NULL); + glfwMakeContextCurrent(window); + + //Setup ImGui + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(255, 255, 255); + + float theta = 0.0; + float vv = 1.0; + + FILE * eps_file = NULL; + bool saving_eps = false; + + while (!glfwWindowShouldClose(window)) { + w = ImGui::GetIO().DisplaySize.x; + h = ImGui::GetIO().DisplaySize.y; + + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + + if(saving_eps) + { + eps_file = fopen("out.eps", "wb"); + gl2psBeginPage("grab", "gl2psTestSimple", NULL, GL2PS_EPS, GL2PS_SIMPLE_SORT, + GL2PS_DRAW_BACKGROUND | GL2PS_USE_CURRENT_VIEWPORT, + GL_RGBA, 0, NULL, 0, 0, 0, 0, eps_file, "out.eps"); + } + + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + + setOrtho(ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y); + + //Model rendering + glPushMatrix(); + + // Gauss UI + ui::begin("Gaussian"); + arma::vec mu; + arma::mat Sigm; + + // Drag only target means + for( int i = 0; i < m; i++ ) + { + Mu.col(i) = (arma::vec)ui::dragger(i, Mu.col(i)); + } + + // manipulate semitied covariance + semitied_params = semitiedWidget(m, semitied_params, {200, 300}); + // Setup cov states + cube Sigma = semitiedCovariances(Mu, semitied_params); + + std::vector<ui::Trans2d> t2ds(m, ui::Trans2d()); + for( int i = 0; i < m; i++ ) + gauss_to_trans2d(&t2ds[i], Mu.col(i), Sigma.slice(i)); + + ui::end(); + + + + // Slider window + int winw = 250; + ImGui::SetNextWindowPos(ImVec2(w-winw,2)); + ImGui::Begin("Params", NULL, ImVec2(winw,300), 0.5f, + ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize| + ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings); + if(ImGui::Button("Save EPS")) + { + saving_eps = true; + } + + ImGui::SliderInt("Order", &order, 2, 7); + ImGui::SliderFloat("Max Displacement", &d, 0.01, 5.); + ImGui::SliderFloat("Theta", &theta, -PI, PI); + ImGui::SliderInt("Plot deriv", &plot_deriv, 1, 3); + ImGui::End(); + + // Recompute LQR + int dim = 2; + double duration = stroke_duration * m; + int n = (int)(duration/dt); + int cDim = dim * order; + + // system matrices + mat A, B; + makeIntegratorChain(&A, &B, order); + discretizeSystem(&A, &B, A, B, dt); + // make bi-variate + A = kron(A, eye(dim, dim)); + B = kron( B, eye(dim, dim) ); + + // reference + mat Q, MuQ; + stepwiseReference( &MuQ, &Q, Mu, Sigma, n, order, dim, endWeight ); + MuQ *= globScale; + Q /= globScale*globScale; + + // r based on oscillatory movement displacement + double r = SHM_r(d, stroke_duration, order); + mat R = kron( eye(n-1, n-1), + eye(dim, dim) * r ); + + //////////////////////////////////// + // Batch LQR + + // Sx and Su matrices for batch LQR + mat Su = zeros(cDim*n, dim*(n-1)); + mat Sx = kron( ones(n,1), + eye(dim*order, dim*order)); + mat M = B; + for( int i = 1; i < n; i++ ) + { + Sx.rows( i*cDim, n*cDim-1 ) = + Sx.rows( i*cDim, n*cDim-1 ) * A; + Su.submat( i*cDim, 0, + (i+1)*cDim-1, i*dim-1 ) = M; + M = join_horiz( A*M.cols(0, dim-1), M ); + } + + arma::vec x0 = MuQ.col(0); + + // Flatten Mu's + mat Xi_hat = reshape(MuQ, cDim*n, 1); + mat SuInvSigmaQ = Su.t()*Q; + + mat Rq, rq; + + Rq = SuInvSigmaQ*Su + R; + rq = SuInvSigmaQ*(Xi_hat - Sx*x0); + + // least squares solution + vec u = solve(Rq,rq); + mat Y = reshape( Sx*x0 + Su*u, cDim, n ); + mat Xi = Y.submat(0,0, dim-1, n-1) / globScale; + + ////////////////////////////////////// + + glEnable( GL_BLEND ); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // draw gaussians + glColor4f(0.0, 0.5f, 1.0f, 0.2f); + for( int i = 0; i < m; i++ ) + { + drawGauss(t2ds[i]); + } + + // draw trajectory + glColor3f(0, 0, 0); + draw(Xi); + + // plot derivatives magnitude + glColor3f(1,0,0); + mat dx = gradient_2d(Xi, plot_deriv); //, 1, 1); + vec speed = sqrt(sum(dx%dx, 0)).t(); + plot(10, h, 200, 100, speed); + + ui::begin("Text"); + const char* sderiv[] = + { + "velocity", + "acceleration", + "jerk" + }; + ui::textf(ImVec2(200+10, h-20), "%s magnitude", sderiv[plot_deriv-1]); //sderiv[plot_deriv-1]); + ui::end(); + + glPopMatrix(); + + // Render UI + ImGui::Render(); + + if(eps_file) + { + glFlush(); + gl2psEndPage(); + fclose(eps_file); + eps_file=NULL; + saving_eps=false; + } + + glfwSwapBuffers(window); + + //Keyboard input + if (ImGui::IsKeyPressed(GLFW_KEY_ESCAPE)) + break; + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + return 0; +} diff --git a/src/demo_MPC_velocity_01.cpp b/src/demo_MPC_velocity_01.cpp new file mode 100644 index 0000000..5885d47 --- /dev/null +++ b/src/demo_MPC_velocity_01.cpp @@ -0,0 +1,379 @@ +/* + * demo_MPC_batch_01.cpp + * + * Interactive MPC demo, with batch LQT and repulsive field test + * + * Fabien Crépon, Sylvain Calinon, 2017 + */ + +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include "gfx_ui.h" +#include <stdio.h> +#include <GLFW/glfw3.h> +#include "mpc_utils.h" + +#include "armadillo" +#include <pbdlib/gmm.h> +#include <pbdlib/gmr.h> +#include <pbdlib/lqr.h> + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +int factorial(int n){ + return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; +} + +void setOrtho( float w, float h ) +{ + glMatrixMode( GL_PROJECTION ); + glLoadIdentity(); + glOrtho( 0, 0+w, 0+h, 0, -1., 1.); + glMatrixMode( GL_MODELVIEW ); + glLoadIdentity(); +} + +void trans2d_to_gauss(arma::vec* mu, arma::mat* Sigma, const ui::Trans2d& t2d) +{ + arma::mat basis = arma::mat{{t2d.x.x, t2d.y.x}, {t2d.x.y, t2d.y.y}}; + *Sigma = basis * basis.t(); + *mu = arma::vec({t2d.pos.x, t2d.pos.y}); +} + +void gauss_to_trans2d(ui::Trans2d *t2d, const arma::vec& mu, const arma::mat& Sigma) +{ + t2d->pos.x = mu(0); + t2d->pos.y = mu(1); + arma::mat V; + arma::vec d; + arma::eig_sym(d, V, Sigma); + arma::mat VD = V*diagmat(sqrt(d)); + t2d->x.x = VD.col(0)(0); + t2d->x.y = VD.col(0)(1); + t2d->y.x = VD.col(1)(0); + t2d->y.y = VD.col(1)(1); +} + +void draw(const arma::mat& pts, int primitive=GL_LINE_STRIP) +{ + glBegin(primitive); + for (uint t=0; t<pts.n_cols; t++){ + glVertex2f(pts(0,t), pts(1,t)); + } + glEnd(); +} + +arma::mat gradient_2d( arma::mat X, int order=1 ) +{ + mat df = diff(X, 1, 1); + mat db = fliplr( -diff(fliplr(X), 1, 1) ); + mat d = (df+db)/2; + d = join_horiz(zeros(2,1), d); + d.col(0) = df.col(0); + d.col(d.n_cols-1) = db.col(db.n_cols-1); + if(order>1) + return gradient_2d(d, order-1); + return d; +} + +void plot( float x, float y, float w, float h, const vec& v ) +{ + float v_min = v.min(); + float v_max = v.max(); + float inc = w / v.n_rows; + glBegin(GL_LINE_STRIP); + for (int i=0; i < v.n_rows; i++) + { + glVertex2f(x + inc*i, y - h * ((v[i] - v_min) / (v_max - v_min))); + } + glEnd(); +} + +void drawGauss( ui::Trans2d& t2d ) +{ + static arma::mat circ(2,35); + static bool circ_init = true; + if(circ_init) + { + circ = join_cols(cos(linspace<rowvec>(0,2*PI,35)), sin(linspace<rowvec>(0,2*PI,35))); + circ_init = false; + } + arma::mat basis = arma::mat{{t2d.x.x, t2d.y.x}, {t2d.x.y, t2d.y.y}}; + arma::mat pts = basis*circ + arma::repmat(vec({t2d.pos.x, t2d.pos.y}), 1, 35); + + glBegin(GL_TRIANGLE_FAN); + glVertex2f(t2d.pos.x, t2d.pos.y); + for (uint t=0; t<pts.n_cols; t++){ + glVertex2f(pts(0,t), pts(1,t)); + } + glEnd(); +} + +int main(int argc, char **argv){ + + arma_rng::set_seed_random(); + + //---------------------------------------Setup parameters---------------------------------------------------- + //----------------------------------------------------------------------------------------------------------- + int w = 800; + int h = 600; + + double dt = 0.01; + int order = 3; + + int m = 4; // Number of targets + double globScale = 0.001; // global scale, avoids numerical issues in batch method + double endWeight = 1.; //1e-10; // forces movement to a stop (see stepwiseReference function) + + float d=0.1; // maximum displacement, used to compute R diagonal + float stroke_duration=0.3; // duration of a stroke + float covscale = 1.0; // hack, field covariance scaling factor + int fieldDeriv=1; // derivative used for additional field + // Gui settings + int plot_deriv = 1; + bool useField = true; + bool stepwise = false; + + // targets + arma::mat V = arma::randu(2, m); + V.row(0) *= w; + V.row(1) *= h; + + // Covariances + mat Mu = V; + cube Sigma; + randomCovariances(&Sigma, Mu, arma::vec({50.,50.}), false, 0.0, 0.8); + + mat Mu0 = arma::randu(2,1); + Mu0.row(0) *= w; + Mu0.row(1) *= h; + cube Sigma0; + randomCovariances(&Sigma0, Mu0, arma::vec({120.,120.}), false, 0.0, 0.8); + + // Gaussians + std::vector<ui::Trans2d> t2ds(m, ui::Trans2d()); + for( int i = 0; i < m; i++ ) + gauss_to_trans2d(&t2ds[i], Mu.col(i), Sigma.slice(i)); + + std::vector<ui::Trans2d> t2ds0(m, ui::Trans2d()); + for( int i = 0; i < 1; i++ ) + gauss_to_trans2d(&t2ds0[i], Mu0.col(i), Sigma0.slice(i)); + + //------------------------------------------------Plots----------------------------------------------------- + //---------------------------------------------------------------------------------------------------------- + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(w, h, "Demo Batch MPC", NULL, NULL); + glfwMakeContextCurrent(window); + + //Setup ImGui + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(255, 255, 255); + + while (!glfwWindowShouldClose(window)) { + w = ImGui::GetIO().DisplaySize.x; + h = ImGui::GetIO().DisplaySize.y; + + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + + setOrtho(ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y); + + //Model rendering + glPushMatrix(); + + // Gauss UI + ui::begin("Gaussian"); + arma::vec mu; + arma::mat Sigm; + + for( int i = 0; i < m; i++ ) + { + t2ds[i] = ui::affineSimple(i, t2ds[i]); + trans2d_to_gauss(&mu, &Sigm, t2ds[i]); + Mu.col(i) = mu; + Sigma.slice(i) = Sigm; + } + + + // Velocity field Gaussians (actually one) + for( int i = 0; i < 1; i++ ) + { + t2ds0[i] = ui::affineSimple(i+m, t2ds0[i]); + trans2d_to_gauss(&mu, &Sigm, t2ds0[i]); + //Mu0.col(i) = mu; + Sigma0.slice(i) = Sigm; + } + + + ui::end(); + + + // Slider window + int winw = 250; + ImGui::SetNextWindowPos(ImVec2(w-winw,2)); + ImGui::Begin("Params", NULL, ImVec2(winw,300), 0.5f, + ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize| + ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings); + ImGui::SliderInt("Order", &order, 2, 7); + ImGui::SliderInt("Field deriv", &fieldDeriv, 0, 4); + ImGui::SliderFloat("covscale", &covscale, 0.1, 1.0); + ImGui::SliderFloat("Max Displacement", &d, 0.01, 2.); + ImGui::Checkbox("Use Field", &useField); + ImGui::Checkbox("Stepwise", &stepwise); + ImGui::SliderInt("Plot deriv", &plot_deriv, 1, 3); + ImGui::End(); + + // Recompute LQR + int dim = 2; + double duration = stroke_duration * m; + int n = (int)(duration/dt); + int cDim = dim * order; + + // system matrices + mat A, B; + makeIntegratorChain(&A, &B, order); + discretizeSystem(&A, &B, A, B, dt); + // make bi-variate + A = kron(A, eye(dim, dim)); + B = kron( B, eye(dim, dim) ); + + // reference + mat Q, MuQ, Q0, MuQ0; + if(stepwise) + stepwiseReference( &MuQ, &Q, Mu, Sigma, n, order, dim, endWeight ); + else + viaPointReference( &MuQ, &Q, Mu, Sigma, n, order, dim, endWeight ); + MuQ *= globScale; + Q /= globScale*globScale; + + // velocity field + int deriv=std::min(fieldDeriv, order-2); + Mu0 = zeros(cDim,1); + MuQ0 = repmat(Mu0.col(0), 1, n);// * globScale; + mat invSigma0 = zeros(cDim, cDim); + invSigma0(span(dim*deriv, dim*deriv+1), span(dim*deriv, dim*deriv+1)) = inv(Sigma0.slice(0)*covscale*covscale); + Q0 = kron(eye(n,n), invSigma0);// / (globScale*globScale); + + /* + Q0 = zeros(cDim, cDim); + Q0(span(0, dim-1), span(0, dim-1)) = inv(Sigma0.slice(0)); + Q0 = kron(eye(n,n), Q0) / (globScale*globScale); + Q0 = (kron(ones(nbData,1), eye(model.nbVar)) * reshape(model0.invSigma(:,:,qList0), model.nbVar, model.nbVar*nbData)) .* kron(eye(nbData), ones(model.nbVar)); + */ + // Q0 = (kron(ones(n,1), eye(cDim, cDim)) * kron(ones(1,n), invSigma0)) % kron(eye(n,n), ones(cDim,cDim)); + + + // r based on oscillatory movement displacement + double r = SHM_r(d, stroke_duration, order); + mat R = kron( eye(n-1, n-1), + eye(dim, dim) * r ); + + //////////////////////////////////// + // Batch LQR + + // Sx and Su matrices for batch LQR + mat Su = zeros(cDim*n, dim*(n-1)); + mat Sx = kron( ones(n,1), + eye(dim*order, dim*order)); + mat M = B; + for( int i = 1; i < n; i++ ) + { + Sx.rows( i*cDim, n*cDim-1 ) = + Sx.rows( i*cDim, n*cDim-1 ) * A; + Su.submat( i*cDim, 0, + (i+1)*cDim-1, i*dim-1 ) = M; + M = join_horiz( A*M.cols(0, dim-1), M ); + } + + arma::vec x0 = MuQ.col(0); + + // Flatten Mu's + mat Xi_hat = reshape(MuQ, cDim*n, 1); + mat Xi_hat0 = reshape(MuQ0, cDim*n, 1); + + mat SuInvSigmaQ = Su.t()*Q; + mat SuInvSigmaQ0 = Su.t()*Q0; + + mat Rq, rq; + + if(useField) + { + Rq = SuInvSigmaQ*Su + SuInvSigmaQ0*Su + R; + rq = SuInvSigmaQ*(Xi_hat - Sx*x0) + SuInvSigmaQ0*(Xi_hat0 - Sx*x0); + } + else + { + Rq = SuInvSigmaQ*Su + R; + rq = SuInvSigmaQ*(Xi_hat - Sx*x0); + } + + // least squares solution + vec u = solve(Rq,rq); + mat Y = reshape( Sx*x0 + Su*u, cDim, n ); + mat Xi = Y.submat(0,0, dim-1, n-1) / globScale; + + ////////////////////////////////////// + + glEnable( GL_BLEND ); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // draw gaussians + glColor4f(0.0, 0.5f, 1.0f, 0.2f); + for( int i = 0; i < m; i++ ) + { + drawGauss(t2ds[i]); + } + // repulsive gaussians + glColor4f(1.0, 0.5f, 0.0f, 0.2f); + for( int i = 0; i < 1; i++ ) + { + drawGauss(t2ds0[i]); + } + + // draw trajectory + glColor3f(0, 0, 0); + draw(Xi); + + // plot derivatives magnitude + glColor3f(1,0,0); + mat dx = gradient_2d(Xi, plot_deriv); //, 1, 1); + vec speed = sqrt(sum(dx%dx, 0)).t(); + plot(10, h, 200, 100, speed); + + ui::begin("Text"); + const char* sderiv[] = + { + "velocity", + "acceleration", + "jerk" + }; + ui::textf(ImVec2(200+10, h-20), "%s magnitude", sderiv[plot_deriv-1]); //sderiv[plot_deriv-1]); + ui::end(); + + glPopMatrix(); + + // Render UI + ImGui::Render(); + + glfwSwapBuffers(window); + + //Keyboard input + if (ImGui::IsKeyPressed(GLFW_KEY_ESCAPE)) + break; + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + return 0; +} diff --git a/src/demo_Riemannian_cov_interp02.cpp b/src/demo_Riemannian_cov_interp02.cpp new file mode 100644 index 0000000..2e7b682 --- /dev/null +++ b/src/demo_Riemannian_cov_interp02.cpp @@ -0,0 +1,341 @@ +/* + * demo_Riemannian_cov_interp02.cpp + * + * Covariance interpolation on Riemannian manifold from a GMM with augmented + * covariances (Implementation based on Pennec, Fillard and Ayache (2006) + * "A Riemannian Framework For Tensor Computing") + * + * Authors: Sylvain Calinon, Philip Abbet + */ + + +#include <stdio.h> +#include <armadillo> + +#include <imgui.h> +#include <imgui_impl_glfw.h> +#include <gfx.h> +#include <gfx_ui.h> +#include <GLFW/glfw3.h> + +#include <pbdlib/gmm.h> + + +/********************************** SHADERS **********************************/ + +static char const *vert_shader_str = STRINGIFY( + void main(){ + gl_TexCoord[0] = gl_MultiTexCoord0; + gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex; + } +); + + +static char const *frag_shader_str = STRINGIFY( + uniform vec2 Mu; + uniform mat2 Sigma; + uniform vec4 Color; + void main(){ + vec2 e = gl_FragCoord.xy - Mu; + float p = clamp(exp(-(Sigma[0][0] * e.x * e.x - 2 * Sigma[0][1] * e.x * e.y + + Sigma[1][1] * e.y * e.y)), 0, 0.5f); + gl_FragColor = vec4(Color.x, Color.y, Color.z, clamp(Color.a * 2 * p, 0.0, 1.0)); + } +); + + +/********************************* RENDERING *********************************/ + +//----------------------------------------------------------------------------- +// Render a 2d gaussian from its parameters (mu and sigma) +//----------------------------------------------------------------------------- +void render_gaussian(const arma::vec& mu, const arma::mat& sigma, int shader, + const arma::vec& color, float devicePixelRatio) { + + // Compute the gaussian parameters in the fragment shader system coordinates + // (y is 0 at bottom) + arma::vec mu_shad = { + mu(0), + ImGui::GetIO().DisplaySize.y * devicePixelRatio - mu(1) + }; + + // Rendering of the Gaussian "background" with GLSL + gfx::bindShader(shader); + gfx::setVector("Mu", mu_shad); + gfx::setMatrix("Sigma", inv(sigma)); + gfx::setVector("Color", color); + gfx::drawUVQuad(0, 0, ImGui::GetIO().DisplaySize.x * devicePixelRatio, + ImGui::GetIO().DisplaySize.y * devicePixelRatio); + gfx::unbindShader(); + + // Rendering of the Gaussian "border" with standard GL + arma::mat V; + arma::vec d; + arma::eig_sym(d, V, sigma); + arma::mat R = V * diagmat(sqrt(d)); + + arma::mat pts = R * join_cols(cos(linspace<rowvec>(-PI, PI, 60)), + sin(linspace<rowvec>(-PI, PI, 60))); + + glColor3f(0.5 * color(0), 0.5 * color(1), 0.5 * color(2)); + glLineWidth(2.0f); + + glBegin(GL_LINE_STRIP); + for (uint t = 0; t < pts.n_cols; t++) + glVertex2f(mu(0) + pts(0, t), mu(1) + pts(1, t)); + glEnd(); + + // Rendering of the Gaussian position with standard GL + glPointSize(4.); + + glBegin(GL_POINTS); + glVertex2f(mu(0), mu(1)); + glEnd(); +} + + +//----------------------------------------------------------------------------- +// Render a 2d gaussian defined by a transform widget +//----------------------------------------------------------------------------- +void render_gaussian(const ui::Trans2d& gaussian_transforms, int shader, + const arma::vec& color, float devicePixelRatio) { + + // Compute the gaussian parameters + arma::vec mu = { + gaussian_transforms.pos.x, + gaussian_transforms.pos.y + }; + + arma::mat RG = { + { gaussian_transforms.x.x, gaussian_transforms.y.x }, + { gaussian_transforms.x.y, gaussian_transforms.y.y } + }; + + mu *= devicePixelRatio; + RG *= devicePixelRatio; + + render_gaussian(mu, RG * RG.t(), shader, color, devicePixelRatio); +} + + +//----------------------------------------------------------------------------- +// Render a line passing through the provided points +//----------------------------------------------------------------------------- +void render_line(const std::vector<arma::vec>& points, const arma::vec& color) { + + glColor3f(color(0), color(1), color(2)); + glLineWidth(2.0f); + + glBegin(GL_LINE_STRIP); + for (size_t i = 0; i < points.size(); ++i) + glVertex2f(points[i](0), points[i](1)); + glEnd(); +} + + +/****************************** HELPER FUNCTIONS *****************************/ + +static void error_callback(int error, const char* description) { + fprintf(stderr, "Error %d: %s\n", error, description); +} + + +arma::mat expmap(const arma::mat& U, const arma::mat& S) { + return real(sqrtmat(S) * expmat(inv(sqrtmat(S)) * U * inv(sqrtmat(S))) * sqrtmat(S)); +} + + +arma::mat logmap(const arma::mat& X, const arma::mat& S) { + return real(sqrtmat(S) * logmat(inv(sqrtmat(S)) * X * inv(sqrtmat(S))) * sqrtmat(S)); +} + + +/********************************* FUNCTIONS *********************************/ + +void interpolate(const std::vector<ui::Trans2d>& gaussian_transforms, + int nb_data, + std::vector<arma::vec> &interpolated_mu, + std::vector<arma::mat> &interpolated_sigma, + float devicePixelRatio) { + + const int nb_var = 2; // Number of variables (fixed, since we use a + // ui::Trans2d to define a gaussian) + const int nb_var2 = nb_var + 1; + + // Transformation to Gaussians with augmented covariances centered on zero + std::vector<arma::mat> augmented_sigma; + + for (size_t i = 0; i < gaussian_transforms.size(); ++i) { + arma::vec current_mu = { + gaussian_transforms[i].pos.x, + gaussian_transforms[i].pos.y + }; + + arma::mat RG = { + { gaussian_transforms[i].x.x, gaussian_transforms[i].y.x }, + { gaussian_transforms[i].x.y, gaussian_transforms[i].y.y } + }; + + current_mu *= devicePixelRatio; + RG *= devicePixelRatio; + + arma::mat current_sigma(nb_var2, nb_var2); + + current_sigma(0, 0, arma::size(nb_var, nb_var)) = RG * RG.t() + current_mu * current_mu.t(); + current_sigma(0, nb_var, arma::size(nb_var, 1)) = current_mu; + current_sigma(nb_var, 0, arma::size(1, nb_var)) = current_mu.t(); + current_sigma(nb_var, nb_var) = 1; + + augmented_sigma.push_back(current_sigma); + } + + // Geodesic interpolation + arma::vec w = arma::linspace(0, 1, nb_data); + + for (size_t i = 1; i < augmented_sigma.size(); ++i) { + for (size_t t = 0; t < nb_data; ++t) { + // Interpolation between two covariances can be computed in closed form + arma::mat sigma = expmap(w(t) * logmap(augmented_sigma[i], augmented_sigma[i-1]), + augmented_sigma[i-1]); + + double beta = sigma(sigma.n_elem - 1); + arma::vec mu = sigma(sigma.n_rows - 1, 0, arma::size(1, sigma.n_cols-1)).t() / beta; + + interpolated_mu.push_back(mu); + interpolated_sigma.push_back(sigma(0, 0, arma::size(sigma.n_rows-1, sigma.n_cols-1)) - beta * mu * mu.t()); + } + } +} + + +int main(int argc, char **argv) { + arma_rng::set_seed_random(); + + // Parameters + int nb_states = 2; // Number of states in the GMM + int nb_data = 20; // Length of each trajectory + + // Generate random transform widgets to represent some Gaussians + std::vector<ui::Trans2d> gaussian_transforms; + for (int i = 0; i < nb_states; ++i) { + arma::ivec mu = arma::randi(2, arma::distr_param(100, 500)); + arma::ivec xy = arma::randi(2, arma::distr_param(20, 100)); + gaussian_transforms.push_back(ui::Trans2d(ImVec2(xy(0), 0), ImVec2(0, xy(1)), + ImVec2(mu(0), mu(1)))); + } + + // Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(600, 600, "Covariance interpolation", NULL, NULL); + glfwMakeContextCurrent(window); + + // Setup GLSL + gfx::init(); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + int shader = gfx::loadShader(vert_shader_str, frag_shader_str); + + // Setup ImGui + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(255, 255, 255); + + // Take 4k screens into account (framebuffer size != window size) + int win_width = ImGui::GetIO().DisplaySize.x; + int win_height = ImGui::GetIO().DisplaySize.y; + + int fb_width, fb_height; + glfwGetFramebufferSize(window, &fb_width, &fb_height); + + float devicePixelRatio = float(fb_width) / win_width; + + // Main loop + while (!glfwWindowShouldClose(window)) { + glfwPollEvents(); + + // Detect when the window was resized + if ((ImGui::GetIO().DisplaySize.x != win_width) || (ImGui::GetIO().DisplaySize.y != win_height)) { + win_width = ImGui::GetIO().DisplaySize.x; + win_height = ImGui::GetIO().DisplaySize.y; + + glfwGetFramebufferSize(window, &fb_width, &fb_height); + + devicePixelRatio = float(fb_width) / win_width; + } + + // Start of rendering + ImGui_ImplGlfw_NewFrame(); + glViewport(0, 0, fb_width, fb_height); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + + gfx::setOrtho(fb_width, fb_height); + + glPushMatrix(); + + // Ensure that the number of desired states hasn't changed + if (nb_states > gaussian_transforms.size()) { + for (int i = gaussian_transforms.size(); i < nb_states; ++i) { + arma::ivec mu = arma::randi(2, arma::distr_param(100, 500)); + arma::ivec xy = arma::randi(2, arma::distr_param(20, 100)); + gaussian_transforms.push_back(ui::Trans2d(ImVec2(xy(0), 0), + ImVec2(0, xy(1)), + ImVec2(mu(0), mu(1)))); + } + } + else if (nb_states < gaussian_transforms.size()) { + gaussian_transforms.resize(nb_states); + } + + // Interpolation between the gaussians + std::vector<arma::vec> interpolated_mu; + std::vector<arma::mat> interpolated_sigma; + + interpolate(gaussian_transforms, nb_data, interpolated_mu, interpolated_sigma, + devicePixelRatio); + + // Rendering of the gaussians + for (size_t i = 0; i < gaussian_transforms.size(); ++i) { + render_gaussian(gaussian_transforms[i], shader, + arma::vec({ 0.5, 0.5, 0.5, 0.5 }), devicePixelRatio); + } + + for (size_t i = 0; i < interpolated_sigma.size(); ++i) { + render_gaussian(interpolated_mu[i], interpolated_sigma[i], shader, + arma::vec({ 0.8, 0.0, 0.0, 0.02 }), devicePixelRatio); + } + + render_line(interpolated_mu, arma::vec({ 0.8, 0.0, 0.0 })); + + // Gaussian UI widgets + ui::begin("Gaussians"); + for (size_t i = 0; i < gaussian_transforms.size(); ++i) + gaussian_transforms[i] = ui::affineSimple(i, gaussian_transforms[i]); + ui::end(); + + // Parameter window + ImGui::Begin("Parameters", NULL, ImVec2(250, 80), 0.5f, + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings); + ImGui::SliderInt("Nb states", &nb_states, 2, 5); + ImGui::SliderInt("Nb data", &nb_data, 5, 30); + ImGui::End(); + + // GUI rendering + ImGui::Render(); + + // End of rendering + glPopMatrix(); + glfwSwapBuffers(window); + + // Keyboard input + if (ImGui::IsKeyPressed(GLFW_KEY_ESCAPE)) + break; + } + + // Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + + return 0; +} diff --git a/src/demo_Riemannian_quat_infHorLQR.cpp b/src/demo_Riemannian_quat_infHorLQR.cpp new file mode 100644 index 0000000..200d64d --- /dev/null +++ b/src/demo_Riemannian_quat_infHorLQR.cpp @@ -0,0 +1,518 @@ +/* + * demo_Riemannian_quat_infHorLQR.cpp + * + * Linear quadratic regulation of unit quaternions by relying on Riemannian manifold and infinite-horizon LQR + * Change display by setting REFERENTIALS to 1 (referentials in sphere) or 0 (LQR for quaternions) + * + * Inspired by boing.c in the glfw library (available on git) + * Fabien Crépon + */ + + +#include <stdio.h> +#include <stdlib.h> +#include <math.h> + +#include <GLFW/glfw3.h> + +namespace linmath{ +#include <linmath.h> +} + +#include "armadillo" +#include <pbdlib/gmm.h> +#include <pbdlib/gmr.h> +#include <pbdlib/lqr.h> + +#define REFERENTIALS 0 //Change REFERENTIALS to 1 (referentials in sphere) or 0 (LQR for quaternions) + +#define RADIUS 1.f +#define STEP_LONGITUDE 10.5f +#define STEP_LATITUDE 10.5f + +#define DIST_BALL (RADIUS * 2.f + RADIUS * 0.1f) +#define VIEW_SCENE_DIST (DIST_BALL * 3.f + 200.f) + +/* Draw ball */ +typedef enum { DRAW_BALL } DRAW_BALL_ENUM; +/* Vertex type */ +typedef struct {float x; float y; float z;} vertex_t; + +void DrawSphereBand( GLfloat long_lo, GLfloat long_hi ); +void DrawSphere( void ); + +static void error_callback(int error, const char* description) +{ + fprintf(stderr, "Error %d: %s\n", error, description); +} +int factorial(int n) +{ + return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; +} +double deg2rad( double deg ) +{ + return deg / 360 * (2 * M_PI); +} +double sin_deg( double deg ) +{ + return sin( deg2rad( deg ) ); +} +double cos_deg( double deg ) +{ + return cos(deg2rad ( deg ) ); +} +void CrossProduct( vertex_t a, vertex_t b, vertex_t c, vertex_t *n ) +{ + GLfloat u1, u2, u3; + GLfloat v1, v2, v3; + + u1 = b.x - a.x; + u2 = b.y - a.y; + u3 = b.y - a.z; + + v1 = c.x - a.x; + v2 = c.y - a.y; + v3 = c.z - a.z; + + n->x = u2 * v3 - v2 * v3; + n->y = u3 * v1 - v3 * u1; + n->z = u1 * v2 - v1 * u2; +} +arma::mat QuatMatrix(arma::mat q) +{ + arma::mat Q; + Q = {{q(0),-q(1),-q(2),-q(3)}, + {q(1), q(0),-q(3), q(2)}, + {q(2), q(3), q(0),-q(1)}, + {q(3),-q(2), q(1), q(0)}}; + + return Q; +} +arma::mat acoslog(arma::mat x) +{ + arma::mat acosx(1,x.size()); + + for (int n=0; n <= x.size()-1; n++) + { + if (x(0,n) >= 1.0) + x(0,n) = 1.0; + if (x(0,n) <= -1.0) + x(0,n) = -1.0; + if (x(0,n) < 0) + { + acosx(0,n) = acos(x(0,n))-M_PI; + } + else + acosx(0,n) = acos(x(0,n)); + } + + return acosx; +} +arma::mat expfct(arma::mat u) +{ + arma::mat normv = sqrt(pow(u.row(0),2)+pow(u.row(1),2)+pow(u.row(2),2)); + arma::mat Exp(4,1); + + Exp.row(0) = cos(normv); + Exp.row(1) = u.row(0)%sin(normv)/normv; + Exp.row(2) = u.row(1)%sin(normv)/normv; + Exp.row(3) = u.row(2)%sin(normv)/normv; + + return Exp; +} +arma::mat logfct(arma::mat x) +{ + arma::mat fullone; + fullone.ones(size(x.row(0))); + arma::mat scale(1,x.size()/4); + scale = acoslog(x.row(0))/sqrt(fullone-pow(x.row(0),2)); + + arma::mat Log(3,x.size()/4); + Log.row(0) = x.row(1) % scale; + Log.row(1) = x.row(2) % scale; + Log.row(2) = x.row(3) % scale; + + return Log; +} +arma::mat expmap(arma::mat u, arma::vec mu) +{ + arma::mat x = QuatMatrix(mu)*expfct(u); + return x; +} +arma::mat logmap(arma::mat x, arma::vec mu) +{ + arma::mat pole; + arma::mat Q(4,4,fill::ones); + + pole = {1,0,0,0}; + + if(norm(mu-trans(pole))< 1E-6) + Q = {{1,0,0,0}, + {0,1,0,0}, + {0,0,1,0}, + {0,0,0,1}}; + else + Q = QuatMatrix(mu); + + arma::mat u; + u = logfct(trans(Q)*x); + + return u; +} +void DrawTarget(int nbData) +{ + glColor3f(0.98, 0.349, 0.329); + glLineWidth(1.5); + glBegin(GL_LINE_STRIP); + for (int t = 0; t < nbData; t++) { + glVertex2f(t, 1); + } + glEnd(); + glBegin(GL_LINE_STRIP); + for (int t = 0; t < nbData; t++) { + glVertex2f(nbData + 0.05 + t, 0); + } + glEnd(); + glBegin(GL_LINE_STRIP); + for (int t = 0; t < nbData; t++) { + glVertex2f(t, -2.10); + } + glEnd(); + glBegin(GL_LINE_STRIP); + for (int t = 0; t < nbData; t++) { + glVertex2f(nbData + 0.05 + t, -2.10); + } + glEnd(); +} +void DrawResults(int nbData, int nbRepros, arma::mat x_y) +{ + glColor3f(0.f, 0.f, 0.f); + glLineWidth(1.3); + for (int n = 0; n < nbRepros; n++) { + + for (int t = 0; t < nbData; t++) { + glBegin(GL_LINE_STRIP); + glVertex2f(t, x_y(0, n * nbData + t)); + } + glEnd(); + } + + for (int n = 0; n < nbRepros; n++) { + + for (int t = 0; t < nbData; t++) { + glBegin(GL_LINE_STRIP); + glVertex2f(nbData + 0.05 + t, x_y(1, n * nbData + t)); + } + glEnd(); + } + for (int n = 0; n < nbRepros; n++) { + + for (int t = 0; t < nbData; t++) { + glBegin(GL_LINE_STRIP); + glVertex2f(t, x_y(2, n * nbData + t) - 2.10); + } + glEnd(); + } + for (int n = 0; n < nbRepros; n++) { + + for (int t = 0; t < nbData; t++) { + glBegin(GL_LINE_STRIP); + glVertex2f(nbData + 0.05 + t, x_y(3, n * nbData + t) - 2.10); + } + glEnd(); + } + +} +void printQuat(arma::mat q,int black) +{ + arma::mat referential = {{1,0,0},{0,1,0},{0,0,1}}; + arma::mat rotation; + rotation << 2*(pow(q(0),2)+pow(q(1),2))-1 << 2*(q(1)*q(2)-q(0)*q(3)) << 2*(q(1)*q(3)+q(0)*q(2)) << endr + << 2*(q(1)*q(2)+q(0)*q(3)) << 2*(pow(q(0),2)+pow(q(2),2))-1 << 2*(q(2)*q(3)-q(0)*q(1)) << endr + << 2*(q(1)*q(3)-q(0)*q(2)) << 2*(q(2)*q(3)+q(0)*q(1)) << 2*(pow(q(0),2)+pow(q(3),2))-1 << endr; + arma::mat orientation; + orientation = referential*rotation; + + + if(black) + glColor3f(0.,0.,0.); + else + glColor3f(1.,0.,0.); + glLineWidth(1.4); + glBegin(GL_LINE_STRIP); + glVertex3f(0,0,0); + glVertex3f(orientation(0,0),orientation(0,1),orientation(0,2)); + glEnd(); + + if(black) + glColor3f(0.,0.,0.); + else + glColor3f(0.,1.,0.); + glLineWidth(1.4); + glBegin(GL_LINE_STRIP); + glVertex3f(0,0,0); + glVertex3f(orientation(1,0),orientation(1,1),orientation(1,2)); + glEnd(); + + if(black) + glColor3f(0.,0.,0.); + else + glColor3f(0.,0.,1.); + glLineWidth(1.4); + glBegin(GL_LINE_STRIP); + glVertex3f(0,0,0); + glVertex3f(orientation(2,0),orientation(2,1),orientation(2,2)); + glEnd(); + + return; +} +void reshape( GLFWwindow* window, int w, int h ) +{ + linmath::mat4x4 projection, view; + glViewport( 0, 0, (GLsizei)w, (GLsizei)h ); + + glMatrixMode( GL_PROJECTION ); + linmath::mat4x4_perspective( projection, + 2.f * (float) atan2( RADIUS, 200.f ), + (float)w / (float)h, + 1.f, VIEW_SCENE_DIST ); + glLoadMatrixf((const GLfloat*) projection); + glMatrixMode( GL_MODELVIEW ); + { + linmath::vec3 eye = { 0.f, 0.f, VIEW_SCENE_DIST }; + linmath::vec3 center = { 0.f, 0.f, 0.f }; + linmath::vec3 up = { 0.f, -1.f, 0.f }; + linmath::mat4x4_look_at( view, eye, center, up ); + } + glLoadMatrixf((const GLfloat*) view); +} +int main(int argc, char **argv){ + + arma_rng::set_seed_random(); + + //---------------------------------------Setup parameters---------------------------------------------------- + //----------------------------------------------------------------------------------------------------------- + + int nbData = 100; //Number of datapoints + int nbRepros = 5; //Number of reproductions + + int nbVarPos = 3; //Dimension of position data (here: x1,x2) + int nbDeriv = 2; //Number of static & dynamic features (D=2 for [x,dx]) + int nbVar = nbVarPos * nbDeriv; //Dimension of state vector in the tangent space + int nbVarMan = nbVarPos + 1; //Dimension of the manifold + double dt = 1E-3; //Time step duration + float rfactor = 1E-6; //Control cost in LQR + + //Control Cost matrix + arma::mat R = eye(nbVarPos,nbVarPos) * rfactor; + + //Target and desired covariance + arma::vec xTar; + xTar << 1 << endr << 0 << endr << 0 << endr << 0 << endr; + + arma::vec vecCov(3); + vecCov << 1 << endr << 1E-3 << endr << 1E-3 << endr; + arma::mat uCov = diagmat(vecCov); + + + //--------------------------Discrete dynamical system settings (in tangent space)---------------------------- + //----------------------------------------------------------------------------------------------------------- + + arma::mat A, B; + + arma::mat A1d(zeros(nbDeriv,nbDeriv)); + for (int i = 0; i <= nbDeriv -1 ; i++) { + A1d = A1d + diagmat(ones(nbDeriv-i),i) * pow(dt,i) * 1/factorial(i); + } + arma::mat B1d(zeros(nbDeriv,1)); + for (int i = 1; i <= nbDeriv ; i++) { + B1d(nbDeriv-i,0) = pow(dt,i) * 1./factorial(i); + } + + A = kron(A1d, eye(nbVarPos,nbVarPos)); + B = kron(B1d, eye(nbVarPos,nbVarPos)); + + //------------------------------Iterative discrete LQR with infinite horizon--------------------------------- + //----------------------------------------------------------------------------------------------------------- + + pbdlib::LQR lqr(A,B,dt); + arma:: mat duTar = zeros(nbVarPos*(nbDeriv-1),1); + + arma::mat Q = inv(uCov); + Q.resize(6,6); + arma::mat P = lqr.solveAlgebraicRiccati_Discrete(A,B,Q,R); + arma::mat L = (trans(B)*P*B + R).i() * trans(B)*P*A; + + arma::mat x(nbVarMan,1); + arma::mat U; + arma::mat x_y(zeros(4,nbRepros*nbData)); + arma::mat ddu(3,1); + + for (int n = 0; n < nbRepros ; n++) { + x(0,0) = -1 + randn()*9E-1; + x(1,0) = -1 + randn()*9E-1; + x(2,0) = 1 + randn()*9E-1; + x(3,0) = randn()*9E-1; + + x = x/norm(x); + U = -logmap(x,xTar); + U.resize(6,1); + + for (int t = 0; t <nbData ; t++) { + x_y.col(n*nbData+t) = x; + + ddu.rows(0,2) = logmap(x,xTar); + ddu.resize(6,1); + ddu.rows(3,5) = duTar-U.rows(3,5); + ddu = L * ddu; + + U = A*U + B*ddu; + x = expmap(-1*U.rows(0,nbVarPos-1),xTar); + } + } + + //------------------------------------------------Plots----------------------------------------------------- + //---------------------------------------------------------------------------------------------------------- + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + + GLFWwindow* window = glfwCreateWindow(500, 500, "Quaternions", NULL, NULL); + glfwMakeContextCurrent(window); + + if(!REFERENTIALS) + glOrtho(0,2*nbData+0.1,-3.15,1.05,0,1); + + while (!glfwWindowShouldClose(window)) { + + glfwPollEvents(); + + glClearColor(1.f, 1.f, 1.f, 1.f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glPushMatrix(); + + //------------Draw referentials in sphere--------------- + if (REFERENTIALS) + { + printQuat(x_y.col(1), 0); + printQuat(x_y.col(nbData - 1), 1); + + DrawSphere(); + } + + //------------ Draw Q1,Q2,Q3,Q4-------------------------- + else + { + DrawTarget(nbData); + DrawResults(nbData, nbRepros, x_y); + } + + glPopMatrix(); + glfwSwapBuffers(window); + + + } + + //Cleanup + glfwTerminate(); + return 0; +} +void DrawSphere( void ) +{ + GLfloat lon_deg; //degree of longitude + double dt_total, dt2; + + glPushMatrix(); + glMatrixMode( GL_MODELVIEW ); + + glCullFace( GL_FRONT ); + glEnable( GL_CULL_FACE ); + glEnable( GL_NORMALIZE ); + + + //Build a faceted latitude slice of the sphere, + //stepping same-sized vertical bands of the sphere. + + for ( lon_deg = 0; + lon_deg < 180; + lon_deg += STEP_LONGITUDE ) + { + + //Draw a latitude circle at this longitude. + + DrawSphereBand( lon_deg, + lon_deg + STEP_LONGITUDE ); + } + + glPopMatrix(); + + return; +} +void DrawSphereBand( GLfloat long_lo, GLfloat long_hi ) { + vertex_t vert_ne; //"ne" means south-east, so on + vertex_t vert_nw; + vertex_t vert_sw; + vertex_t vert_se; + vertex_t vert_norm; + GLfloat lat_deg; + + // Iterate thru the points of a latitude circle. + // A latitude circle is a 2D set of X,Z points. + + for (lat_deg = 0; + lat_deg <= (360 - STEP_LATITUDE); + lat_deg += STEP_LATITUDE) { + +#if 0 + +#endif + glColor3f(0.55f, 0.55f, 0.55f); + //Assign each Y. + + vert_ne.y = vert_nw.y = (float) cos_deg(long_hi) * RADIUS; + vert_sw.y = vert_se.y = (float) cos_deg(long_lo) * RADIUS; + + + // Assign each X,Z with sin,cos values scaled by latitude radius indexed by longitude. + //Eg, long=0 and long=180 are at the poles, so zero scale is sin(longitude), + //while long=90 (sin(90)=1) is at equator. + + vert_ne.x = (float) cos_deg(lat_deg) * (RADIUS * (float) sin_deg(long_lo + STEP_LONGITUDE)); + vert_se.x = (float) cos_deg(lat_deg) * (RADIUS * (float) sin_deg(long_lo)); + vert_nw.x = (float) cos_deg(lat_deg + STEP_LATITUDE) * (RADIUS * (float) sin_deg(long_lo + STEP_LONGITUDE)); + vert_sw.x = (float) cos_deg(lat_deg + STEP_LATITUDE) * (RADIUS * (float) sin_deg(long_lo)); + + vert_ne.z = (float) sin_deg(lat_deg) * (RADIUS * (float) sin_deg(long_lo + STEP_LONGITUDE)); + vert_se.z = (float) sin_deg(lat_deg) * (RADIUS * (float) sin_deg(long_lo)); + vert_nw.z = (float) sin_deg(lat_deg + STEP_LATITUDE) * (RADIUS * (float) sin_deg(long_lo + STEP_LONGITUDE)); + vert_sw.z = (float) sin_deg(lat_deg + STEP_LATITUDE) * (RADIUS * (float) sin_deg(long_lo)); + + + //Draw the facet. + glBegin(GL_LINE_STRIP); + + CrossProduct(vert_ne, vert_nw, vert_sw, &vert_norm); + glNormal3f(vert_norm.x, vert_norm.y, vert_norm.z); + + glVertex3f(vert_ne.x, vert_ne.y, vert_ne.z); + glVertex3f(vert_nw.x, vert_nw.y, vert_nw.z); + glVertex3f(vert_sw.x, vert_sw.y, vert_sw.z); + glVertex3f(vert_se.x, vert_se.y, vert_se.z); + + glEnd(); + +#if SPHERE_DEBUG + printf( "----------------------------------------------------------- \n" ); + printf( "lat = %f long_lo = %f long_hi = %f \n", lat_deg, long_lo, long_hi ); + printf( "vert_ne x = %.8f y = %.8f z = %.8f \n", vert_ne.x, vert_ne.y, vert_ne.z ); + printf( "vert_nw x = %.8f y = %.8f z = %.8f \n", vert_nw.x, vert_nw.y, vert_nw.z ); + printf( "vert_se x = %.8f y = %.8f z = %.8f \n", vert_se.x, vert_se.y, vert_se.z ); + printf( "vert_sw x = %.8f y = %.8f z = %.8f \n", vert_sw.x, vert_sw.y, vert_sw.z ); +#endif + + } + + return; +} diff --git a/src/demo_Riemannian_sphere_infHorLQR.cpp b/src/demo_Riemannian_sphere_infHorLQR.cpp new file mode 100644 index 0000000..a2fccf7 --- /dev/null +++ b/src/demo_Riemannian_sphere_infHorLQR.cpp @@ -0,0 +1,823 @@ +/* + * demo_sphere.cpp + * + * Linear quadratic regulation on a sphere by relying on Riemannian manifold and + * infinite-horizon LQR + * + * Authors: Sylvain Calinon, Fabien Crépon, Philip Abbet + */ + +#include <stdio.h> +#include <armadillo> +#include <pbdlib/lqr.h> + +#include <gfx3.h> +#include <gfx_ui.h> +#include <GLFW/glfw3.h> +#include <imgui.h> +#include <imgui_impl_glfw_gl3.h> + +using namespace arma; + + +/********************************* SHADERS *********************************/ + +const char* VERTEX_SHADER_SPHERE = STRINGIFY( + // Input vertex data + layout(location = 0) in vec3 vertex_position; + layout(location = 1) in vec3 normal; + + // Values that stay constant for the whole mesh + uniform mat4 ModelMatrix; + uniform mat4 ViewMatrix; + uniform mat4 ProjectionMatrix; + uniform vec3 LightPosition; + + // Output data ; will be interpolated for each fragment + out vec3 position_modelspace; + out vec3 position_worldspace; + out vec3 eye_direction_cameraspace; + out vec3 light_direction_cameraspace; + out vec3 normal_cameraspace; + + void main() { + position_modelspace = vertex_position; + + // Position of the vertex, in clip space + gl_Position = ProjectionMatrix * ViewMatrix * ModelMatrix * vec4(vertex_position, 1); + + // Position of the vertex, in worldspace + position_worldspace = (ModelMatrix * vec4(vertex_position, 1)).xyz; + + // Vector that goes from the vertex to the camera, in camera space. + // In camera space, the camera is at the origin (0,0,0). + vec3 vertex_position_cameraspace = (ViewMatrix * vec4(position_worldspace, 1)).xyz; + eye_direction_cameraspace = vec3(0,0,0) - vertex_position_cameraspace; + + // Vector that goes from the vertex to the light, in camera space + vec3 light_position_cameraspace = (ViewMatrix * vec4(LightPosition, 1)).xyz; + light_direction_cameraspace = light_position_cameraspace + eye_direction_cameraspace; + + // Normal of the the vertex, in camera space (Only correct if ModelMatrix does + // not scale the model) + normal_cameraspace = (ViewMatrix * ModelMatrix * vec4(normal, 0)).xyz; + } +); + +//----------------------------------------------- + +const char* FRAGMENT_SHADER_SPHERE = STRINGIFY( + // Values that stay constant for the whole mesh + uniform vec3 AmbiantColor; + uniform vec3 DiffuseColor; + uniform vec3 SpecularColor; + uniform float SpecularPower; + uniform vec3 LightPosition; + uniform vec3 LightColor; + uniform float LightPower; + uniform bool Attenuation; + uniform sampler2D DiffuseTexture; + + // Interpolated values from the vertex shaders + in vec3 position_modelspace; + in vec3 position_worldspace; + in vec3 eye_direction_cameraspace; + in vec3 light_direction_cameraspace; + in vec3 normal_cameraspace; + + // Output data + out vec3 color; + + void main() { + // Normal of the computed fragment, in camera space + vec3 n = normalize(normal_cameraspace); + + // Direction of the light (from the fragment to the light) + vec3 l = normalize(light_direction_cameraspace); + + // Eye vector (towards the camera) + vec3 E = normalize(eye_direction_cameraspace); + + // Direction in which the triangle reflects the light + vec3 R = reflect(-l, n); + + // Cosine of the angle between the normal and the light direction, + // clamped above 0 + // - light is at the vertical of the triangle -> 1 + // - light is perpendicular to the triangle -> 0 + // - light is behind the triangle -> 0 + float cos_theta = clamp(dot(n, l), 0, 1); + + // Cosine of the angle between the Eye vector and the Reflect vector, + // clamped to 0 + // - Looking into the reflection -> 1 + // - Looking elsewhere -> < 1 + float cos_alpha = clamp(dot(E, R), 0, 1); + + // Distance to the light + float distance = length(LightPosition - position_worldspace); + + // Apply the gaussian texture around the target point + vec3 pos = position_modelspace; + + vec2 longitudeLatitude = vec2((atan(pos.z, pos.x) / 3.1415926 + 1.0) * 0.5, + (asin(-pos.y) / 3.1415926 + 1.0) * 0.5); + + vec3 diffuse_color = texture(DiffuseTexture, longitudeLatitude).rgb; + + if (Attenuation) { + float d = clamp(2.0 * length(2.0 * (longitudeLatitude - vec2(0.5, 0.5))), 0.0, 1.0); + diffuse_color = d * DiffuseColor + (1.0 - d) * diffuse_color; + } + + // Computation of the color of the fragment + color = AmbiantColor + + diffuse_color * LightColor * LightPower * cos_theta / (distance * distance) + + SpecularColor * LightColor * LightPower * pow(cos_alpha, SpecularPower) / (distance * distance); + } +); + + +/****************************** HELPER FUNCTIONS *****************************/ + +static void error_callback(int error, const char* description) { + fprintf(stderr, "Error %d: %s\n", error, description); +} + +//----------------------------------------------- + +int factorial(int n) { + return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; +} + +//----------------------------------------------- + +arma::mat trans2cov(const ui::Trans2d& trans) { + arma::mat RG = { + { trans.x.x / 200.0, trans.y.x / 200.0 }, + { -trans.x.y / 200.0, -trans.y.y / 200.0 } + }; + + return RG * RG.t(); +} + +//----------------------------------------------- + +arma::mat rotM(arma::vec v) { + arma::vec st = v / norm(v); + float acangle = st(2); + float cosa = acangle; + float sina = sqrt(1 - pow(acangle, 2)); + + + if ((1 - acangle) > 1E-16) { + v << st(1) << endr << -st(0) << endr << 0 << endr; + v = v / sina; + } + else { + v = zeros(3); + } + + float vera = 1 - cosa; + float x = v(0); + float y = v(1); + float z = v(2); + + arma::mat rot; + rot = {{cosa + pow(x, 2) * vera, x * y * vera - z * sina, x * z * vera + y * sina}, + {x * y * vera + z * sina, cosa + pow(y, 2) * vera, y * z * vera - x * sina}, + {x * z * vera - y * sina, y * z * vera + x * sina, cosa + pow(z, 2) * vera}}; + + return rot; +} + +//----------------------------------------------- + +arma::mat expfct(arma::mat u) { + arma::mat normv = sqrt(pow(u.row(0), 2) + pow(u.row(1), 2)); + arma::mat Exp(3, u.n_cols); + + Exp.row(0) = u.row(0) % sin(normv) / normv; + Exp.row(1) = u.row(1) % sin(normv) / normv; + Exp.row(2) = cos(normv); + + return Exp; +} + +//----------------------------------------------- + +arma::mat logfct(arma::mat x) { + arma::mat fullone; + fullone.ones(size(x.row(2))); + arma::mat scale(1, x.n_cols); + scale = acos(x.row(2)) / sqrt(fullone - pow(x.row(2), 2)); + + arma::mat Log(2, x.n_cols); + Log.row(0) = x.row(0) % scale; + Log.row(1) = x.row(1) % scale; + + return Log; +} + +//----------------------------------------------- + +arma::mat expmap(arma::mat u, arma::vec mu) { + arma::mat x = trans(rotM(mu)) * expfct(u); + return x; +} + +//----------------------------------------------- + +arma::mat logmap(arma::mat x, arma::vec mu) { + arma::mat pole; + pole = {0, 0, 1}; + arma::mat R(3, 3, fill::ones); + + if (norm(mu - trans(pole)) < 1E-6) { + R = {{1, 0, 0}, + {0, -1, 0}, + {0, 0, -1}}; + } + else { + R = rotM(mu); + } + + arma::mat u; + u = logfct(R * x); + + return u; +} + +//----------------------------------------------- + +arma::mat sample_gaussian_points(const ui::Trans2d& gaussian, const arma::vec& target) { + + arma::mat uCov = trans2cov(gaussian); + + arma::mat V; + arma::vec d; + arma::eig_sym(d, V, uCov); + + arma::mat sample_points({ + { 0.0f, 0.0f }, + { 1.0f, 0.0f }, + { 0.0f, 1.0f }, + { -1.0f, 0.0f }, + { 0.0f, -1.0f }, + }); + + arma::mat points = expmap(V * diagmat(sqrt(d)) * sample_points.t(), target); + + points.col(0) = target; + + return points; +} + + +/********************************* RENDERING *********************************/ + +//----------------------------------------------------------------------------- +// Create a gaussian mesh, colored (no lightning) +//----------------------------------------------------------------------------- +gfx3::model_t create_gaussian(const gfx3::shader_t& shader, const arma::fvec& color, + const ui::Trans2d& gaussian, const arma::vec& target) { + + arma::mat uCov = trans2cov(gaussian); + + arma::rowvec tl = arma::linspace<arma::rowvec>(-arma::datum::pi, arma::datum::pi, 100); + + arma::mat V; + arma::vec d; + arma::eig_sym(d, V, uCov); + + arma::mat points = expmap(V * diagmat(sqrt(d)) * join_cols(cos(tl), sin(tl)), target); + + return gfx3::create_line(shader, color, points); +} + + +/********************************* FUNCTIONS *********************************/ + +void compute(const ui::Trans2d& gaussian, const arma::vec& target, + const std::vector<arma::vec>& start_points, + std::vector<arma::mat> &reproductions) { + + //_____ Setup __________ + + // Parameters + const int nbData = 200; // Number of datapoints + const int nbVarPos = 2; // Dimension of position data (here: x1,x2) + const int nbDeriv = 2; // Number of static & dynamic features (D=2 for [x,dx]) + const int nbVar = nbVarPos * nbDeriv; // Dimension of state vector in the tangent space + const int nbVarMan = nbVarPos + 1; // Dimension of the manifold + const double dt = 1E-3; // Time step duration + const float rfactor = 1E-8; // Control cost in LQR + + // Control Cost matrix + arma::mat R = eye(nbVarPos, nbVarPos) * rfactor; + + // Desired covariance + arma::mat uCov = trans2cov(gaussian); + + + //_____ Discrete dynamical system settings (in tangent space) __________ + + arma::mat A, B; + + arma::mat A1d(zeros(nbDeriv, nbDeriv)); + for (int i = 0; i <= nbDeriv - 1; i++) { + A1d = A1d + diagmat(ones(nbDeriv - i), i) * pow(dt, i) * 1.0 / factorial(i); + } + + arma::mat B1d(zeros(nbDeriv, 1)); + for (int i = 1; i <= nbDeriv; i++) { + B1d(nbDeriv - i, 0) = pow(dt, i) * 1.0 / factorial(i); + } + + A = kron(A1d, eye(nbVarPos, nbVarPos)); + B = kron(B1d, eye(nbVarPos, nbVarPos)); + + + //_____ Iterative discrete LQR with infinite horizon __________ + + pbdlib::LQR lqr(A, B, dt); + arma::vec duTar = zeros(nbVarPos * (nbDeriv - 1)); + + arma::mat Q = inv(uCov); + Q.resize(nbVar, nbVar); + arma::mat P = lqr.solveAlgebraicRiccati_Discrete(A, B, Q, R); + arma::mat L = (trans(B) * P * B + R).i() * trans(B) * P * A; + + arma::vec x(nbVarMan); + arma::mat U; + arma::mat x_y(zeros(3, nbData)); + arma::vec ddu(nbVarPos); + + for (int n = 0; n < start_points.size(); n++) { + x = start_points[n]; + + U = -logmap(x, target); + U.resize(4, U.n_cols); + + for (int t = 0; t < nbData; t++) { + x_y.col(t) = x.col(0); + + ddu.rows(0, 1) = logmap(x, target); + ddu.resize(4); + ddu.rows(2, 3) = duTar - U.rows(2, 3); + + ddu = L * ddu; + U = A * U + B * ddu; + x = expmap(-U.rows(0, nbVarPos - 1), target); + } + + reproductions.push_back(x_y); + } +} + +//----------------------------------------------- + +int main(int argc, char **argv) { + arma_rng::set_seed_random(); + + // Parameters + int nb_repros = 5; // Initial number of reproductions + + // Initial LQR computation + std::vector<arma::vec> start_points; + std::vector<arma::mat> reproductions; + + arma::vec target({ 0.0, 0.2, 0.6 }); + target = target / norm(target); + + ui::Trans2d gaussian(ImVec2(50, 0), ImVec2(0, 100), ImVec2(50, 680)); + + for (int i = 0; i < nb_repros; ++i) { + arma::vec x(3); + x(0) = -1.0 + randn() * 0.9; + x(1) = -1.0 + randn() * 0.9; + x(2) = randn() * 0.9; + start_points.push_back(x / norm(x)); + } + + compute(gaussian, target, start_points, reproductions); + + + // Initialise GLFW + glfwSetErrorCallback(error_callback); + + if (!glfwInit()) + return -1; + + glfwWindowHint(GLFW_SAMPLES, 4); + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + + // Open a window and create its OpenGL context + GLFWwindow* window = glfwCreateWindow(800, 800, "Demo Riemannian sphere", NULL, NULL); + + glfwMakeContextCurrent(window); + + // Take 4k screens into account (framebuffer size != window size) + int win_width = ImGui::GetIO().DisplaySize.x; + int win_height = ImGui::GetIO().DisplaySize.y; + + int fb_width, fb_height; + glfwGetFramebufferSize(window, &fb_width, &fb_height); + + // Setup GLSL + gfx3::init(); + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_LINE_SMOOTH); + glDepthFunc(GL_LESS); + + // Setup ImGui + ImGui_ImplGlfwGL3_Init(window, true); + + ui::config.color = 0x770000ff; + ui::config.lineColor = 0x770000ff; + + // Creation of the Vertex Array Object (VAO) + GLuint vertexArrayID; + glGenVertexArrays(1, &vertexArrayID); + glBindVertexArray(vertexArrayID); + + + // Projection matrix + arma::fmat projection = gfx3::perspective( + gfx3::deg2rad(45.0f), (float) fb_width / (float) fb_height, 0.1f, 10.0f); + + // Camera matrix + arma::fmat view = gfx3::lookAt( + arma::fvec({0, 0, 3}), // Position of the camera + arma::fvec({0, 0, 0}), // Look at the origin + arma::fvec({0, 1, 0}) // Head is up + ); + + + // Loading of the shaders + gfx3::shader_t gaussian_rtt_shader = gfx3::loadShader(gfx3::RTT_VERTEX_SHADER, + gfx3::RTT_FRAGMENT_SHADER_GAUSSIAN); + + gaussian_rtt_shader.setUniform("Scale", conv_to<fvec>::from(arma::vec({arma::datum::pi, arma::datum::pi}))); + gaussian_rtt_shader.setUniform("Mu", conv_to<fvec>::from(target)); + gaussian_rtt_shader.setUniform("Sigma", conv_to<fmat>::from(inv(trans2cov(gaussian)))); + gaussian_rtt_shader.setUniform("GaussianColor", arma::fvec({0.8f, 0.0f, 0.0f})); + gaussian_rtt_shader.setUniform("BackgroundColor", arma::fvec({0.5f, 0.5f, 0.5f})); + + gfx3::shader_t lic_rtt_shader = gfx3::loadShader(gfx3::RTT_VERTEX_SHADER, + gfx3::RTT_FRAGMENT_SHADER_LIC); + + lic_rtt_shader.setUniform("Time", 0.0f); + lic_rtt_shader.setUniform("Sigma", conv_to<fmat>::from(inv(trans2cov(gaussian)))); + lic_rtt_shader.setUniform("Resolution", arma::fvec({1024, 1024})); + lic_rtt_shader.setUniform("Target", arma::vec({0.0, 0.0})); + + gfx3::shader_t lighted_shader = gfx3::loadShader(VERTEX_SHADER_SPHERE, + FRAGMENT_SHADER_SPHERE); + + gfx3::shader_t colored_shader = gfx3::loadShader(gfx3::VERTEX_SHADER_COLORED, + gfx3::FRAGMENT_SHADER_COLORED); + + lighted_shader.setUniform("AmbiantColor", arma::fvec({0.2f, 0.2f, 0.2f})); + lighted_shader.setUniform("DiffuseColor", arma::fvec({0.5f, 0.5f, 0.5f})); + lighted_shader.setUniform("SpecularColor", arma::fvec({0.0f, 0.0f, 0.0f})); + lighted_shader.setUniform("Attenuation", false); + + // Creation of the RTTs + gfx3::render_to_texture_t gaussian_rtt = gfx3::createRTT(gaussian_rtt_shader, 512, 512, + arma::fvec({ 0.0f, 0.0f, 0.0f })); + + gfx3::render_to_texture_t lic_rtt = gfx3::createRTT(lic_rtt_shader, 1024, 1024, + arma::fvec({ 0.5f, 0.5f, 0.5f })); + + // Creation of the models + // + // The following hierarchy is used: + // - transforms node ("node") + // |__ sphere ("sphere") + // |__ reproduction lines ("reproductions_models") + // |__ gaussian ("gaussian_model") + // |__ transforms node ("target_model_node") + // |__ target point ("target_model") + // + // This allows to rotate everything by just changing the rotation of the + // root transforms node. The "target_model_node" transforms is necessary + // correctly place the target point, always tangent to the sphere. + + //-- The root transforms node + gfx3::transforms_t node; + node.position.zeros(3); + node.rotation.eye(4, 4); + + //-- The sphere + gfx3::model_t sphere = gfx3::create_sphere(lighted_shader, 0.99f); + sphere.transforms.parent = &node; + sphere.diffuse_texture = gaussian_rtt.texture(); + + arma::mat points1 = sample_gaussian_points(gaussian, arma::vec({1.0f, 0.0f, 0.0f})); + arma::mat points2 = sample_gaussian_points(gaussian, target); + + arma::fmat rotation; + arma::fvec translation; + gfx3::rigid_transform_3D(conv_to<fmat>::from(points1), + conv_to<fmat>::from(points2), + rotation, translation); + + sphere.transforms.rotation.submat(0, 0, 2, 2) = rotation; + + //-- The reproduction lines + std::vector<gfx3::model_t> reproductions_models; + for (size_t i = 0; i < reproductions.size(); ++i) { + gfx3::model_t line = gfx3::create_line( + colored_shader, arma::fvec({0.0f, 0.5f, 0.0f}), reproductions[i]); + + line.transforms.parent = &node; + + reproductions_models.push_back(line); + } + + //-- The gaussian + gfx3::model_t gaussian_model = create_gaussian( + colored_shader, arma::fvec({0.8f, 0.0f, 0.0f}), gaussian, target); + + gaussian_model.transforms.parent = &node; + + //-- The intermediate transforms node of the target + gfx3::transforms_t target_model_node; + target_model_node.position.zeros(3); + target_model_node.rotation = gfx3::rotation(arma::fvec({1.0f, 0.0f, 0.0f}), + conv_to<fvec>::from(target)); + target_model_node.parent = &node; + + //-- The target point + gfx3::model_t target_model = gfx3::create_square( + colored_shader, arma::fvec({0.8f, 0.0f, 0.0f}), 0.01f); + + target_model.transforms.position = arma::fvec({1.0f, 0.0f, 0.0f}); + target_model.transforms.rotation = gfx3::rotate(arma::fvec({0.0f, 1.0f, 0.0f}), + gfx3::deg2rad(90.0f)); + target_model.transforms.parent = &target_model_node; + + + // Creation of the light + gfx3::point_light_t light; + light.transforms.position = arma::fvec({-3.0f, 3.0f, 5.0f}); + light.color = arma::fvec({1.0f, 1.0f, 1.0f}); + light.power = 30.0f; + + gfx3::light_list_t lights; + lights.push_back(light); + + + // Mouse control + double mouse_x, mouse_y, previous_mouse_x, previous_mouse_y; + bool rotating = false; + GLFWcursor* crosshair_cursor = glfwCreateStandardCursor(GLFW_HAND_CURSOR); + GLFWcursor* arrow_cursor = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); + + glfwGetCursorPos(window, &previous_mouse_x, &previous_mouse_y); + + + // RTT initial rendering + gfx3::draw(gaussian_rtt); + + + // Main loop + ui::Trans2d previous_gaussian = gaussian; + bool must_recompute = false; + int display_mode = 0; + + while (!glfwWindowShouldClose(window)) { + glfwPollEvents(); + + // Detect when the window was resized + if ((ImGui::GetIO().DisplaySize.x != win_width) || (ImGui::GetIO().DisplaySize.y != win_height)) { + win_width = ImGui::GetIO().DisplaySize.x; + win_height = ImGui::GetIO().DisplaySize.y; + + glfwGetFramebufferSize(window, &fb_width, &fb_height); + + // Update the projection matrix + projection = gfx3::perspective( + gfx3::deg2rad(45.0f), (float) fb_width / (float) fb_height, 0.1f, 10.0f); + + // Ensure that the gaussian widgets are still visible + gaussian.pos.x = 50; + gaussian.pos.y = win_height - 120; + } + + + // Ensure that the number of desired reproductions hasn't changed + // -> trigger a recomputation or the recreation of the meshes + bool must_recreate_lines = false; + + if (nb_repros > reproductions.size()) { + for (int i = reproductions.size(); i < nb_repros; ++i) { + arma::vec x(3); + x(0) = -1.0 + randn() * 0.9; + x(1) = -1.0 + randn() * 0.9; + x(2) = randn() * 0.9; + start_points.push_back(x / norm(x)); + } + + must_recompute = true; + } + else if (nb_repros < reproductions.size()) { + start_points.resize(nb_repros); + reproductions.resize(nb_repros); + + must_recreate_lines = true; + } + + + // Ensure that the gaussian parameters have not changed + // -> trigger a recomputation + if (!gfx3::is_close(previous_gaussian.x.x, gaussian.x.x) || + !gfx3::is_close(previous_gaussian.x.y, gaussian.x.y) || + !gfx3::is_close(previous_gaussian.y.x, gaussian.y.x) || + !gfx3::is_close(previous_gaussian.y.y, gaussian.y.y)) { + + gaussian_rtt_shader.setUniform("Sigma", conv_to<fmat>::from(inv(trans2cov(gaussian)))); + gfx3::draw(gaussian_rtt); + + lic_rtt_shader.setUniform("Sigma", conv_to<fmat>::from(inv(trans2cov(gaussian)))); + + must_recompute = true; + previous_gaussian = gaussian; + } + + + // If needed, recompute the LQR + if (must_recompute) { + reproductions.clear(); + compute(gaussian, target, start_points, reproductions); + + must_recreate_lines = true; + must_recompute = false; + } + + + // If needed, recreate the models + if (must_recreate_lines) { + for (size_t i = 0; i < reproductions_models.size(); ++i) { + gfx3::destroy(reproductions_models[i]); + } + + reproductions_models.clear(); + + for (size_t i = 0; i < reproductions.size(); ++i) { + gfx3::model_t line = gfx3::create_line(colored_shader, + arma::fvec({0.0f, 0.5f, 0.0f}), + reproductions[i]); + + line.transforms.parent = &node; + + reproductions_models.push_back(line); + } + + gfx3::destroy(gaussian_model); + + gaussian_model = create_gaussian( + colored_shader, arma::fvec({0.8f, 0.0f, 0.0f}), gaussian, target); + + gaussian_model.transforms.parent = &node; + } + + + // RTT rendering + lic_rtt_shader.setUniform("Time", (float) glfwGetTime()); + gfx3::draw(lic_rtt); + + if (display_mode == 1) { + sphere.diffuse_texture = lic_rtt.texture(); + lighted_shader.setUniform("Attenuation", true); + } + else { + sphere.diffuse_texture = gaussian_rtt.texture(); + lighted_shader.setUniform("Attenuation", false); + } + + // Start the rendering + ImGui_ImplGlfwGL3_NewFrame(); + glViewport(0, 0, fb_width, fb_height); + glClearColor(0.6f, 0.6f, 0.6f, 0.0f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + + // Drawing + gfx3::draw(sphere, view, projection, lights); + + for (size_t i = 0; i < reproductions_models.size(); ++i) + gfx3::draw(reproductions_models[i], view, projection, lights); + + gfx3::draw(gaussian_model, view, projection, lights); + gfx3::draw(target_model, view, projection, lights); + + + // Gaussian UI widget + ui::begin("Gaussian"); + gaussian = ui::affineSimple(0, gaussian); + ui::end(); + + + // Parameter window + ImGui::SetNextWindowSize(ImVec2(400, 110)); + ImGui::Begin("Parameters", NULL, + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoMove + ); + ImGui::SliderInt("Nb reproductions", &nb_repros, 1, 10); + ImGui::Combo("Display", &display_mode, "Gaussian\0Line integral convolution\0\0"); + ImGui::Text("Hold the right mouse button to rotate the sphere"); + ImGui::Text("Left-click on the sphere to change the target point"); + ImGui::End(); + + + // GUI rendering + ImGui::Render(); + + // Swap buffers + glfwSwapBuffers(window); + + // Keyboard input + if (ImGui::IsKeyPressed(GLFW_KEY_ESCAPE)) + break; + + + // Mouse input + glfwGetCursorPos(window, &mouse_x, &mouse_y); + + //-- Left click + if (ImGui::IsMouseClicked(GLFW_MOUSE_BUTTON_1)) { + + // Determine if the click was on the sphere, and where exactly + gfx3::ray_t ray = gfx3::create_ray( + arma::fvec({0, 0, 3}), (int) mouse_x, (int) mouse_y, + view, projection, win_width, win_height + ); + + arma::fvec intersection; + if (gfx3::intersects(ray, node.position, 1.0f, intersection)) { + // Change the target position + arma::fvec p(4); + p.rows(0, 2) = intersection; + p(3) = 1.0f; + + p = arma::inv(gfx3::worldRotation(&node)) * p; + + target = arma::conv_to<arma::vec>::from(p.rows(0, 2)); + + target_model_node.rotation = gfx3::rotation(arma::fvec({1.0f, 0.0f, 0.0f}), + conv_to<fvec>::from(target)); + + arma::mat points1 = sample_gaussian_points(gaussian, arma::vec({1.0f, 0.0f, 0.0f})); + arma::mat points2 = sample_gaussian_points(gaussian, target); + + arma::fmat rotation; + arma::fvec translation; + gfx3::rigid_transform_3D(conv_to<fmat>::from(points1), + conv_to<fmat>::from(points2), + rotation, translation); + + sphere.transforms.rotation.submat(0, 0, 2, 2) = rotation; + + must_recompute = true; + } + } + + //-- Right mouse button: rotation of the meshes while held down + if (ImGui::IsMouseDown(GLFW_MOUSE_BUTTON_2)) { + if (!rotating) { + rotating = true; + glfwSetCursor(window, crosshair_cursor); + } + + arma::fmat rotation = + gfx3::rotate(arma::fvec({ 0.0f, 1.0f, 0.0f }), 0.2f * gfx3::deg2rad(mouse_x - previous_mouse_x)) * + gfx3::rotate(arma::fvec({ 1.0f, 0.0f, 0.0f }), 0.2f * gfx3::deg2rad(mouse_y - previous_mouse_y)); + + node.rotation = rotation * node.rotation; + } + else if (rotating) { + rotating = false; + glfwSetCursor(window, arrow_cursor); + } + + previous_mouse_x = mouse_x; + previous_mouse_y = mouse_y; + } + + + // Cleanup + glfwDestroyCursor(crosshair_cursor); + glfwDestroyCursor(arrow_cursor); + + ImGui_ImplGlfwGL3_Shutdown(); + glfwTerminate(); + + return 0; +} diff --git a/src/demo_dptpgmm.cpp b/src/demo_dptpgmm.cpp new file mode 100644 index 0000000..de0710f --- /dev/null +++ b/src/demo_dptpgmm.cpp @@ -0,0 +1,566 @@ +/* + * demo_dptpgmm.cpp + * + * Online tp-gmm learning and lqr-based trajectory generation. + * + * Authors: Sylvain Calinon, Emmanuel Pignat + */ + +#define N_TPS 3 +#define N_TPTRS 4 +#define N_REC_POINTS 200 + + +#include <stdio.h> + + +#include "armadillo" +#include <pbdlib/gmm.h> +#include <pbdlib/tpdpgmm.h> + +#include <GLFW/glfw3.h> +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include <pbdlib/gmr.h> +#include <pbdlib/lqr.h> +#include <pbdlib/taskparameters.h> + + +using namespace std; +using namespace pbdlib; +using namespace arma; + + + +class Ref +{ +public: + vec p1; + vec p2; + + mat A; + vec b; + + void updateRef() + { + + b = p1; + A = mat(2,2); + + vec delta = p2-p1; + delta = delta/arma::norm(delta); + A(0,0) = delta(0); + A(1,0) = delta(1); + A(0,1) = -delta(1); + A(1,1) = delta(0); + } + void updateRef_rel() + { + + b = p1; + A = mat(2,2); + + vec delta = (p2-p1)/500.0; + + A(0,0) = delta(0); + A(1,0) = delta(1); + A(0,1) = -delta(1); + A(1,1) = delta(0); + } +}; + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +mat solveReconstruction(TPDPGMM& tpgmm,vec startPoint,int iFactor,int nSUB) +{ + mat A(4,4), B(4,2); + float dt = 0.01f*sqrt((double)nSUB); + + + mat R = eye(2,2) * pow(10.0f,iFactor); + + mat A1d; A1d << 0 << 1 << endr << 0 << 0 << endr; + mat B1d; B1d << 0 << endr << 1 << endr; + A = kron(A1d, eye(2,2)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + B = kron(B1d, eye(2,2)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + LQR lqr(A,B,dt); + + std::vector<mat> Q; + + mat pred; + pred = tpgmm.predictForwardVariable(N_REC_POINTS,0); + + //cout << "Alpha Predictions" << endl << pred.t() << endl; + + uword imax[N_REC_POINTS/ nSUB]; + + for (int t=0; t<N_REC_POINTS/ nSUB; t++){ + vec vTmp = pred.col(t* nSUB); + vTmp.max(imax[t]); + //cout<<imax[t]<<"-"; + } + //cout<<endl<<endl; + + //LQR + vec vTmp(4,fill::zeros); + mat QTmp(4,4,fill::zeros); + mat Target(4,N_REC_POINTS/ nSUB,fill::zeros); + for (int t=0; t<N_REC_POINTS/ nSUB; t++){ + QTmp.submat(0,0,1,1) = inv(tpgmm.getProdGMM()->getSIGMA(imax[t])); + Q.push_back(QTmp); + vTmp.subvec(0,1) = tpgmm.getProdGMM()->getMU(imax[t]); + Target.col(t) = vTmp; + } + lqr.setProblem(R,Q,Target); + mat S(4,4,fill::zeros); + vec d(4,fill::zeros); + //lqr.evaluate_gains_finiteHorizon(S,d); + lqr.evaluate_gains_infiniteHorizon(); + + //Retrieve data + + mat rData(2,N_REC_POINTS/ nSUB); + //vec x = demo.getDatapoints().getData().col(0); + //vec dx(2,fill::zeros), ddx(2); + //for (int t=0; t<points.size(); t++){ + //rData.col(t) = x; + //ddx = 100.0f * (Target.submat(0,t,1,t)-x) - sqrtf(2*100.0f) * dx; + //ddx = lqr.getGains().at(t).cols(0,1) * (Target.submat(0,t,1,t)-x) - lqr.getGains().at(t).cols(2,3) * dx; + //ddx += lqr.getFF().at(t); + //dx += ddx * dt; + //x += dx * dt; + //} + + vec u(2); + vec X = join_cols(startPoint, zeros<vec>(2)); + for (int t=0; t<N_REC_POINTS/ nSUB; t++){ + rData.col(t) = X.rows(0,1); + u = lqr.getGains().at(t) * (Target.col(t)-X); + X += (A*X+B*u) * dt; + } + + //Clean up + + Q.clear(); + return rData; +} + +int main(int argc, char **argv){ + + //reference drawings + + mat refShape = {{1, 1, -1, -1, -0.5, -0.5, 0.5, 0.5,1}, + {1.5, -0.5, -0.5, 1.5, 1.5, 0, 0, 1.5, 1.5}}; + refShape = 50*refShape; + //Setup TPDPGMM + + GMM_Model gmm(1,2); + float minSigma = 20.0f; + float lambda = 70.0f; + TPDPGMM tpgmm(2,1,N_TPS,N_TPTRS,lambda); + + TaskParameters tp(2,N_TPS); + + + + mat minSIGMA = eye(2,2) * minSigma; + vector<GaussianDistribution> comps; + vector<Demonstration> demos; + vector<mat> repros; + + //Setup LQR + int iFactor = -6; + + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(1280, 820, "PbdLib GUI", NULL, NULL); + glfwMakeContextCurrent(window); + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // Setup ImGui binding + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(154, 154, 154); + + ImVector<ImVec2> points; + bool adding_line = false; + bool modelExist = false; + bool dispRef = true; + bool dispDemo = false; + bool dispGMM = true; + bool useFramePRIORS = true; + bool movingRef = false; + bool hoveringRef = false; + int nbPts = 0; + bool init = true; + bool startFlag = false; + bool endFlag = false; + float alphaHandles = 0.2f; + Ref refFrame[3]; + refFrame[0].p1 = zeros(2); + refFrame[0].p2 = zeros(2); + refFrame[1].p1 = vec(2); + refFrame[1].p2 = vec(2); + refFrame[2].p1 = vec(2); + refFrame[2].p2 = vec(2); + + //plotting color + float color[5][3] = {{0.f,0.6211f,0.8164f}, + {0.9883f,0.4531f,0.f}, + {0.7422f,0.8555f,0.2227f}, + {0.1211f,0.5391f,0.4375f}, + {0.9961f,0.8789f,0.1016f}}; + + while (!glfwWindowShouldClose(window)){ + + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + hoveringRef = false; + //Control panel GUI + if(init)ImGui::SetNextWindowPos(ImVec2(500,200)); + + ImGui::Begin("r1p1",NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + vec tmpPos = refFrame[0].p1; + refFrame[0].p1(0)=ImGui::GetWindowPos().x+15; + refFrame[0].p1(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + tmpPos-=refFrame[0].p1; + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + if(init)ImGui::SetNextWindowPos(ImVec2(500,300)); + ImGui::Begin("r1p2", NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + if(!init)ImGui::SetWindowPos(ImVec2(ImGui::GetWindowPos().x-tmpPos(0),ImGui::GetWindowPos().y+tmpPos(1))); + refFrame[0].p2(0)=ImGui::GetWindowPos().x+15; + refFrame[0].p2(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + if(init)ImGui::SetNextWindowPos(ImVec2(1000,200)); + ImGui::Begin("r2p1",NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + tmpPos = refFrame[1].p1; + refFrame[1].p1(0)=ImGui::GetWindowPos().x+15; + refFrame[1].p1(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + tmpPos-=refFrame[1].p1; + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + if(init)ImGui::SetNextWindowPos(ImVec2(1000,100)); + ImGui::Begin("r2p2", NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + if(!init)ImGui::SetWindowPos(ImVec2(ImGui::GetWindowPos().x-tmpPos(0),ImGui::GetWindowPos().y+tmpPos(1))); + refFrame[1].p2(0)=ImGui::GetWindowPos().x+15; + refFrame[1].p2(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + refFrame[0].updateRef(); + refFrame[1].updateRef(); + refFrame[2].p1 = refFrame[0].p1; + refFrame[2].p2 = refFrame[1].p1; + refFrame[2].updateRef_rel(); + + + //cout<< refFrame[0].A<<endl; + init = false; + + ImGui::SetNextWindowPos(ImVec2(2,2)); + + //ImGui::Begin("Control Panel"); + + ImGui::Begin("Control Panel", NULL, ImVec2(350,250), 1.0f, + ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize| + ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings); + + + + //cout<<ImGui::IsItemHovered()<<endl; + + if (ImGui::Button("Clear")){ + demos.clear(); + repros.clear(); + gmm.clear(); + tpgmm = TPDPGMM(2,1,N_TPS,N_TPTRS,lambda); + modelExist = false; + //cout<<gmm.getNumSTATES()<<endl; + } + //ImGui::SameLine(); + //if (ImGui::Button("Train")) { + // cout << "\n Number of EM iterations: " << gmm.EM_learn(); + // dispGMM = true; + //} + ImGui::Text("Left-click to collect demonstrations"); + ImGui::Text("nbDemos: %i, nbPoints: %i, nbStates: %i", (int)demos.size(), (int)points.size(), (int)gmm.getNumSTATES()); + ImGui::SliderFloat("minSigma", &minSigma, 1E1, 2E2); + ImGui::SliderFloat("lambda", &lambda, 10.0f, 100.0f); + ImGui::Checkbox("Display Demo",&dispDemo); + ImGui::Checkbox("Plot Gaussian",&dispGMM); + ImGui::Checkbox("Use Frame Priors",&useFramePRIORS); + ImGui::SliderInt("rFactor", &iFactor, -9, -5); + + tpgmm.useFramePRIORS(useFramePRIORS); + + //Get data + ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x, + ImGui::GetIO().DisplaySize.y - ImGui::GetIO().MousePos.y); + //ImGui::GetCursorScreenPos() + + //ImGuiWindow* hw = FindHoveredWindow(ImGui::GetIO().MousePos, false); + + if(hoveringRef&&ImGui::GetIO().MouseClicked[0]) + movingRef = true; + if(movingRef&&!ImGui::GetIO().MouseDown[0]) + movingRef = false; + + if(movingRef&&modelExist&& !ImGui::GetIO().MouseClicked[0]) + { + TaskParameter tpTmp; + + for(int i=0;i<N_TPS;i++) + { + tpTmp.A = refFrame[i].A; + tpTmp.b = refFrame[i].b; + tp.setTaskParameters(i,tpTmp); + } + tpgmm.getTransformedGMM(tp,INVERTIBLE); + + colvec trParam = ones(N_TPTRS); + trParam.rows(0,1) = refFrame[1].b-refFrame[0].b; + mat test = (refFrame[1].A*refFrame[0].A); + trParam.rows(2,3) = lambda*test.col(0); + cout << trParam<<endl; + tpgmm.updateTransition(trParam); + + repros.clear(); + // variable resolution for fast preview when moving references + int nSub; + if (!ImGui::GetIO().MouseDown[0]) nSub= 1; + else nSub = 4; + + mat rData = solveReconstruction(tpgmm,tpgmm.getProdGMM()->getMU(0),iFactor,nSub); + repros.push_back(rData); + } + + + if ((ImGui::GetIO().MousePos.x<352 && ImGui::GetIO().MousePos.y<252)==0&&!movingRef){ //Is outside gui? + if (!adding_line && ImGui::GetIO().MouseClicked[0]){ //Button pushed + adding_line = true; + startFlag = true; + endFlag = false; + if (!modelExist){ + colvec p(2); + p(0) = mouse_pos_in_canvas.x; + p(1) = mouse_pos_in_canvas.y; + cout<<p<<endl; + GaussianDistribution componentTmp(p,minSIGMA); + comps.push_back(componentTmp); + gmm.setCOMPONENTS(comps); + comps.clear(); + } + } + if (!ImGui::GetIO().MouseDown[0]) endFlag = true; + + if (adding_line){ //Trajectory recording + usleep(1e4); + points.push_back(mouse_pos_in_canvas); + nbPts++; + vec p(2); + p(0) = mouse_pos_in_canvas.x; + p(1) = mouse_pos_in_canvas.y; + mat p_frame(2,N_TPS+1); + + TaskParameter tpTmp; + + + for(int i=0;i<N_TPS;i++) + { + p_frame.col(i) = refFrame[i].A.t()/det(refFrame[i].A)*(p-refFrame[i].b); + tpTmp.A = refFrame[i].A; + tpTmp.b = refFrame[i].b; + tp.setTaskParameters(i,tpTmp); + } + // also add the position in absolute space + p_frame.col(N_TPS) = p; + + colvec trParam = ones(N_TPTRS); + trParam.rows(0,1) = refFrame[1].b-refFrame[0].b; + mat test = (refFrame[1].A*refFrame[0].A); + trParam.rows(2,3) = lambda*test.col(0); + + tpgmm.addDatapoints(p_frame,trParam,startFlag,endFlag,lambda,minSigma); + tpgmm.getTransformedGMM(tp,INVERTIBLE); + + startFlag = false; + modelExist = true; + //gmm.onlineEMDP(nbPts, p, lambda, minSigma); + + if (!ImGui::GetIO().MouseDown[0]) + { //Button released + adding_line = false; + + bool merged = true; + while (merged) + { + merged = tpgmm.reduceStates(); + tpgmm.getTransformedGMM(tp, INVERTIBLE); + tpgmm.updateTransition(trParam); + } + //Add demonstration + Demonstration demo = Demonstration(2,points.size()); + for (int t=0; t<(int)points.size(); t++){ + demo.getDatapoints().getData()(0,t) = points[t].x; + demo.getDatapoints().getData()(1,t) = points[t].y; + } + demos.push_back(demo); + + + //Reconstruction + repros.clear(); + + mat rData = solveReconstruction(tpgmm,demo.getDatapoints().getData().col(0),iFactor,1); + repros.push_back(rData); + + points.clear(); + + } + + } + } + ImGui::End(); + + + //GUI rendering + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + ImGui::Render(); + + //PbDlib rendering + glPushMatrix(); + glTranslatef(-1.0f,-1.0f,0); + glScalef(2.0f/(float)ImGui::GetIO().DisplaySize.x, 2.0f/(float)ImGui::GetIO().DisplaySize.y, 1.0f); + glLineWidth(2.0f); + + //Draw current demo + glColor3f(0.0f, 0.0f, 0.0f); + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)points.size(); t++){ + glVertex2f(points[t].x, points[t].y); + } + glEnd(); + + //Draw demos + glColor3f(0.3f, 0.3f, 0.3f); + if(dispDemo) + { + for (int n=0; n<(int)demos.size(); n++){ + glBegin(GL_LINE_STRIP); + + for (int t=0; t<(int)demos[n].getDatapoints().getNumPOINTS(); t++){ + glVertex2f(demos[n].getDatapoints().getData()(0,t), demos[n].getDatapoints().getData()(1,t)); + } + glEnd(); + } + } + + + //Draw references + if(dispRef) + { + glLineWidth(4.0f); + for (int k = 0; k < (int) tpgmm.getNumFRAMES()-1; k++) { + + glColor3f(color[0][0], color[0][1], color[0][2]); + glBegin(GL_LINE_STRIP); + for (int t = 0; t < (int) size(refShape,1); t++) { + vec point = refFrame[k].b + refFrame[k].A * refShape.col(t); + glVertex2f(point(0),point(1)); + } + glEnd(); + } + glLineWidth(2.0f); + } + + //Draw Gaussians + if (modelExist&&dispGMM){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glLineWidth(2.0f); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++) { + for (int k = 0; k < (int) tpgmm.getNumFRAMES(); k++) { + + eig_sym(d, V, tpgmm.getGMMS(k).getSIGMA(i)); + R = refFrame[k].A*(V * sqrt(diagmat(d))); + pts = R * pts0; + + glColor3f(color[k+1][0], color[k+1][1], color[k+1][2]); + glBegin(GL_LINE_STRIP); + + vec refMU = refFrame[k].b + refFrame[k].A*tpgmm.getGMMS(k).getMU(i); + + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f((pts(0, t) + refMU(0)), (pts(1, t) +refMU(1))); + } + glEnd(); + glBegin(GL_POINTS); + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f(tpgmm.getGMMS(k).getMU(i)(0), tpgmm.getGMMS(k).getMU(i)(1)); + } + glEnd(); + } + } + } + if (modelExist){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glColor3f(0.8f, 0.0f, 0.0f); + glColor3f(color[4][0], color[4][1], color[4][2]); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++){ + eig_sym(d, V, tpgmm.getProdGMM()->getSIGMA(i)); + R = V * sqrt(diagmat(d)); + pts = R * pts0; + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f((pts(0,t)+tpgmm.getProdGMM()->getMU(i)(0)), + (pts(1,t)+tpgmm.getProdGMM()->getMU(i)(1))); + } + glEnd(); + glBegin(GL_POINTS); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f(tpgmm.getProdGMM()->getMU(i)(0), + tpgmm.getProdGMM()->getMU(i)(1)); + } + glEnd(); + } + } + glLineWidth(5.0f); + //Draw repros + glColor3f(color[3][0], color[3][1], color[3][2]); + for (int n=0; n<(int)repros.size(); n++){ + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)repros[n].n_cols; t++){ + glVertex2f(repros[n](0,t), repros[n](1,t)); + } + glEnd(); + } + glLineWidth(2.0f); + glPopMatrix(); + glfwSwapBuffers(window); + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + + return 0; +} + diff --git a/src/demo_glsl.cpp b/src/demo_glsl.cpp new file mode 100644 index 0000000..8a68455 --- /dev/null +++ b/src/demo_glsl.cpp @@ -0,0 +1,172 @@ +//Sylvain Calinon, 2017 + +#include <stdio.h> +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include "gfx_ui.h" +#include <epoxy/gl.h> +#include <GLFW/glfw3.h> +#include "armadillo" +#include <pbdlib/gmm.h> + +static char const *vert_shader_str = + "#version 120\n" + "void main(){\n" + "\tgl_TexCoord[0] = gl_MultiTexCoord0;\n" + "\tgl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;\n" + "}\n"; + +static char const *frag_shader_str = + "#version 120\n" + "uniform vec2 Mu;\n" + "uniform mat2 Gamma;\n" + "void main(){\n" + "\tvec2 e = gl_FragCoord.xy - Mu;\n" + //"\tfloat p = exp(-0.5f * dot(e,Gamma*e));\n" + "\tfloat p = clamp(exp(-0.5f * dot(e,Gamma*e)), 0, 0.5f);\n" + "\tgl_FragColor = vec4(p, p, p, p);\n" + "}\n"; + +GLint prog, vert_shader, frag_shader, Mu_loc, Gamma_loc; + +void shader_status(int shader_id){ + int status; + glGetShaderiv(shader_id, GL_COMPILE_STATUS, &status); + if (!status){ + int infologLength, charsWritten; + GLchar *infoLog; + glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &infologLength); + infoLog = (GLchar *)malloc(sizeof(GLchar) * infologLength); + glGetShaderInfoLog(shader_id, infologLength, &charsWritten, infoLog); + std::cout << infoLog << std::endl; + free(infoLog); + } +} + +int check_gl_extension(char const *name){ + const char *glExtensions = (const char *)glGetString(GL_EXTENSIONS); + return (strstr(glExtensions, name) != NULL); +} + +void glsl_init(void){ + if(!check_gl_extension("GL_ARB_fragment_shader")) + fprintf(stderr, "Warning: GL_ARB_fragment_shader extension not present\n"); + else if(!check_gl_extension("GL_ARB_vertex_shader")) + fprintf(stderr, "Warning: GL_ARB_vertex_shader extension not present\n"); + else{ + vert_shader = glCreateShader(GL_VERTEX_SHADER); + frag_shader = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(vert_shader, 1, &vert_shader_str, NULL); + glShaderSource(frag_shader, 1, &frag_shader_str, NULL); + glCompileShader(vert_shader); + glCompileShader(frag_shader); + prog = glCreateProgram(); + glAttachShader(prog, vert_shader); + glAttachShader(prog, frag_shader); + glLinkProgram(prog); + glValidateProgram(prog); + shader_status(vert_shader); + shader_status(frag_shader); + glUseProgram(prog); + Mu_loc = glGetUniformLocation(prog, "Mu"); + Gamma_loc = glGetUniformLocation(prog, "Gamma"); + } + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); +} + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +int main(int argc, char **argv){ + arma_rng::set_seed_random(); + + //Gaussian + arma::vec Utar = {500.0, 500.0}; + arma::mat RG(2,2,fill::eye); + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(600, 600, "Demo GLSL", NULL, NULL); + glfwMakeContextCurrent(window); + + //Setup GLSL + glsl_init(); + + //Setup ImGui + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(0, 0, 40); + + //Setup ui + //ui::init(20.); + ui::Trans2d trans(ImVec2(200,0), ImVec2(0,100), ImVec2(Utar(0),Utar(1))); + + while (!glfwWindowShouldClose(window)) { + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + glPushMatrix(); + glTranslatef(-1.0f, -1.0f, 0); + glScalef(2.0f / (float) ImGui::GetIO().DisplaySize.x, 2.0f / (float) ImGui::GetIO().DisplaySize.y, 1.0f); + + //GUI rendering + ui::begin("Gaussian"); + trans = ui::affineSimple(0, trans); + Utar = {trans.pos.x, ImGui::GetIO().DisplaySize.y - trans.pos.y, 0, 0}; + RG = {{trans.x.x, trans.y.x}, {-trans.x.y, -trans.y.y}}; + ui::end(); + ImGui::Render(); + + + //Gaussian rendering with GLSL + glUseProgram(prog); + + glUniform2f(Mu_loc, Utar(0), Utar(1)); + + fmat S = conv_to<fmat>::from(inv(RG * RG.t())); + glUniformMatrix2fv(Gamma_loc, 1, GL_FALSE, (GLfloat*)S.memptr()); + + glBegin(GL_QUADS); + glTexCoord2f(0.0, 1.0); glVertex2f(0, 0); + glTexCoord2f(0.0, 0.0); glVertex2f(ImGui::GetIO().DisplaySize.x, 0); + glTexCoord2f(1.0, 0.0); glVertex2f(ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y); + glTexCoord2f(1.0, 1.0); glVertex2f(0, ImGui::GetIO().DisplaySize.y); + glEnd(); + + glUseProgram(0); + + + //Gaussian rendering with standard GL + arma::mat pts0(2,35), pts(2,35); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,35)), sin(linspace<rowvec>(0,2*PI,35))); + pts = RG * pts0; + glColor3f(0.79f, 0.33f, 0.33f); + glBegin(GL_LINE_STRIP); + for (uint t=0; t<pts.n_cols; t++){ + glVertex2f(Utar(0)+pts(0,t), Utar(1)+pts(1,t)); + } + glEnd(); + glPointSize(2.); + glBegin(GL_POINTS); + glVertex2f(Utar(0), Utar(1)); + glEnd(); + + + glPopMatrix(); + glfwSwapBuffers(window); + + //Keyboard input + if (ImGui::IsKeyPressed(GLFW_KEY_ESCAPE)) + break; + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + return 0; +} diff --git a/src/demo_glsl_gfx.cpp b/src/demo_glsl_gfx.cpp new file mode 100644 index 0000000..746bc43 --- /dev/null +++ b/src/demo_glsl_gfx.cpp @@ -0,0 +1,165 @@ +//Sylvain Calinon, 2017 + +#include <stdio.h> +#include <imgui.h> +#include "gfx.h" +#include "imgui_impl_glfw.h" +#include "gfx_ui.h" +#include <GLFW/glfw3.h> + +#include "armadillo" +#include <pbdlib/gmm.h> + + +static char const *vert_shader_str = STRINGIFY( + void main(){ + gl_TexCoord[0] = gl_MultiTexCoord0; + gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex; + } +); + +static char const *frag_shader_str = STRINGIFY( + uniform vec2 Mu; + uniform mat2 Gamma; + void main(){ + vec2 e = gl_FragCoord.xy - Mu; + //float p = exp(-0.5f * dot(e,Gamma*e)); + float p = clamp(exp(-0.5f * dot(e,Gamma*e)), 0, 0.5f); + gl_FragColor = vec4(p, p, p, p); + } +); + +/* +static char const *vert_shader_str = + "#version 130\n" + "void main(){\n" + "\tgl_TexCoord[0] = gl_MultiTexCoord0;\n" + "\tgl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;\n" + "}\n"; + +static char const *frag_shader_str = + "#version 130\n" + "uniform vec2 Mu;\n" + "uniform mat2 Gamma;\n" + "void main(){\n" + "\tvec2 e = gl_FragCoord.xy - Mu;\n" + //"\tfloat p = exp(-0.5f * dot(e,Gamma*e));\n" + "\tfloat p = clamp(exp(-0.5f * dot(e,Gamma*e)), 0, 0.5f);\n" + "\tgl_FragColor = vec4(p, p, p, p);\n" + "}\n"; + */ +GLint prog, vert_shader, frag_shader, Mu_loc, Gamma_loc; + +void shader_status(int shader_id){ + int status; + glGetShaderiv(shader_id, GL_COMPILE_STATUS, &status); + if (!status){ + int infologLength, charsWritten; + GLchar *infoLog; + glGetShaderiv(shader_id, GL_INFO_LOG_LENGTH, &infologLength); + infoLog = (GLchar *)malloc(sizeof(GLchar) * infologLength); + glGetShaderInfoLog(shader_id, infologLength, &charsWritten, infoLog); + std::cout << infoLog << std::endl; + free(infoLog); + } +} + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +int main(int argc, char **argv){ + arma_rng::set_seed_random(); + + //Gaussian + arma::vec Utar = {500.0, 500.0}; + arma::mat RG(2,2,fill::eye); + arma::vec Utar_shad = {500.0, 500.0}; + arma::mat RG_shad(2,2,fill::eye); + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(600, 600, "Demo GLSL", NULL, NULL); + glfwMakeContextCurrent(window); + + //Setup GLSL + gfx::init(); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + int shader = gfx::loadShader(vert_shader_str, frag_shader_str); + + //Setup ImGui + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(0, 0, 40); + + //Setup ui + //ui::init(20.); + ui::Trans2d trans(ImVec2(200,0), ImVec2(0,100), ImVec2(Utar(0),Utar(1))); + + while (!glfwWindowShouldClose(window)) { + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + + gfx::setOrtho(ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y); + + //GUI rendering + ui::begin("Gaussian"); + trans = ui::affineSimple(0, trans); + Utar = {trans.pos.x, trans.pos.y, 0, 0}; + RG = {{trans.x.x, trans.y.x}, {trans.x.y, trans.y.y}}; + // Need to find a better solution to this, since frag y coords have zero at bottom... + Utar_shad = {trans.pos.x, ImGui::GetIO().DisplaySize.y - trans.pos.y, 0, 0}; + RG_shad = {{trans.x.x, trans.y.x}, {-trans.x.y, -trans.y.y}}; + ui::end(); + ImGui::Render(); + + //Gaussian rendering with GLSL + gfx::bindShader(shader); + gfx::setVector("Mu", arma::vec({Utar_shad[0], Utar_shad[1]})); + gfx::setMatrix("Gamma", inv(RG_shad * RG_shad.t())); + + gfx::drawUVQuad(0, 0, ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y); + // glBegin(GL_QUADS); + // glTexCoord2f(0.0, 1.0); glVertex2f(0, 0); + // glTexCoord2f(0.0, 0.0); glVertex2f(ImGui::GetIO().DisplaySize.x, 0); + // glTexCoord2f(1.0, 0.0); glVertex2f(ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y); + // glTexCoord2f(1.0, 1.0); glVertex2f(0, ImGui::GetIO().DisplaySize.y); + // glEnd(); + + gfx::unbindShader(); + + + //Gaussian rendering with standard GL + arma::mat pts0(2,35), pts(2,35); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,35)), sin(linspace<rowvec>(0,2*PI,35))); + pts = RG * pts0; + glColor3f(0.79f, 0.33f, 0.33f); + glBegin(GL_LINE_STRIP); + for (uint t=0; t<pts.n_cols; t++){ + glVertex2f(Utar(0)+pts(0,t), Utar(1)+pts(1,t)); + } + glEnd(); + glPointSize(2.); + glBegin(GL_POINTS); + glVertex2f(Utar(0), Utar(1)); + glEnd(); + + + glPopMatrix(); + glfwSwapBuffers(window); + + //Keyboard input + if (ImGui::IsKeyPressed(GLFW_KEY_ESCAPE)) + break; + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + return 0; +} diff --git a/src/pbdlib_gui.cpp b/src/demo_online_gmm.cpp similarity index 96% rename from src/pbdlib_gui.cpp rename to src/demo_online_gmm.cpp index 300c9b3..0776922 100644 --- a/src/pbdlib_gui.cpp +++ b/src/demo_online_gmm.cpp @@ -1,8 +1,9 @@ /* - * pbdlib_gui.cpp + * demo_online_gmm.cpp * - * Created on: Jun 27, 2015 - * Author: Sylvain Calinon + * Online gmm learning and lqr-based trajectory generation. + * + * Author: Sylvain Calinon */ #include <imgui.h> @@ -47,6 +48,8 @@ int main(int argc, char **argv){ B = kron(B1d, eye(2,2)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf LQR lqr(A,B,dt); + + //Setup GUI glfwSetErrorCallback(error_callback); if (!glfwInit()) @@ -57,7 +60,7 @@ int main(int argc, char **argv){ // Setup ImGui binding ImGui_ImplGlfw_Init(window, true); ImVec4 clear_color = ImColor(114, 144, 154); - + ImVector<ImVec2> points; bool adding_line = false; bool dispGMM = false; @@ -92,7 +95,7 @@ int main(int argc, char **argv){ // dispGMM = true; //} ImGui::Text("Left-click to collect demonstrations"); - ImGui::Text("nbDemos: %i, nbPoints: %i, nbStates: %i", demos.size(), points.size(), gmm.getNumSTATES()); + ImGui::Text("nbDemos: %d, nbPoints: %d, nbStates: %d", (int)demos.size(), (int)points.size(), (int)gmm.getNumSTATES()); ImGui::SliderFloat("minSigma", &minSigma, 1E1, 2E2); ImGui::SliderFloat("lambda", &lambda, 10.0f, 100.0f); if (ImGui::SliderInt("rFactor", &iFactor, -9, -6)){ @@ -270,7 +273,3 @@ int main(int argc, char **argv){ glfwTerminate(); return 0; } - - - - diff --git a/src/demo_online_hsmm.cpp b/src/demo_online_hsmm.cpp new file mode 100644 index 0000000..223dd75 --- /dev/null +++ b/src/demo_online_hsmm.cpp @@ -0,0 +1,386 @@ +/* + * demo_online_hsmm.cpp + * + * Online hsmm learning and sampling with lqr-based trajectory generation. + * + * Authors: Sylvain Calinon, Ioannis Havoutis + */ + +#define prt(x) std::cout << #x " = '" << x << "'" << std::endl; + +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include <stdio.h> +#include <GLFW/glfw3.h> + +#include "armadillo" +#include <pbdlib/gmm.h> +#include <pbdlib/gmr.h> +#include <pbdlib/lqr.h> +#include "pbdlib/hsmm.h" + +using namespace std; +using namespace pbdlib; +using namespace arma; + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +mat run_lqr(mat A, mat B, float dt, + mat R, + int traj_length, colvec start_state, uword state_seq[], + GMM_Model model); + +void get_state_seq(uword state_seq[], mat pred); + +int main(int argc, char **argv){ + + //int nVars = 4; + int nVars = 2; //position only + HSMM hsmm(1,nVars); + float minSigma = 2E2; + float lambda = 50.0f; + mat minSIGMA = eye(nVars,nVars) * minSigma; + vector<GaussianDistribution> comps; + vector<Demonstration> demos; + vector<mat> repros; + vector<mat> repros_hsmm; + vector<mat> repros_sampling; + + //Setup hsmm + int init_nStates = 1; // we need to initialize the states to something + + //Setup LQR + mat A(4,4), B(4,2); + float dt = 0.01f; + + float iFactor = -8; + mat R = eye(2,2) * pow(10.0f,iFactor); + mat A1d; A1d << 0 << 1 << endr << 0 << 0 << endr; + mat B1d; B1d << 0 << endr << 1 << endr; + A = kron(A1d, eye(2,2)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + B = kron(B1d, eye(2,2)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(1280, 520, "PbdLib GUI", NULL, NULL); + glfwMakeContextCurrent(window); + + // Setup ImGui binding + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(255, 255, 255); + + ImVector<ImVec2> points; + ImVector<ImVec2> pointsVel; + bool adding_line = false; + bool dispGMM = false; + int nbPts = 0; + + ImVec2 mouse_pos_in_canvas; + + running_stat<float> xi; + float counter = 2; + while (!glfwWindowShouldClose(window)){ + + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + + //Control panel GUI + ImGui::SetNextWindowPos(ImVec2(2,2)); + //ImGui::SetNextWindowSize(ImVec2(250,200)); + + ImGui::Begin("Control Panel", NULL, ImVec2(350,300), 1.0f, + ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize| + ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings); + + if (ImGui::Button("Clear")){ + demos.clear(); + repros.clear(); + repros_sampling.clear(); + repros_hsmm.clear(); + hsmm.clear(); + dispGMM = false; + } + + ImGui::Text("Left-click to collect demonstrations"); + ImGui::Text("nbDemos: %i, nbPoints: %i, nbStates: %i", (int)demos.size(), (int)points.size(), (int)hsmm.getNumSTATES()); + ImGui::SliderFloat("minSigma", &minSigma, 1E1, 2E3); + ImGui::SliderFloat("lambda", &lambda, 10.0f, 500.0f); + if (ImGui::SliderFloat("rFactor", &iFactor, -9.0f, -1.0f, "%.1f" )){ + R = eye(2,2) * pow(10.0f,iFactor); + } + + static bool hsmm_stochastic_sampling = true; + ImGui::Checkbox("Stochastic sampling", &hsmm_stochastic_sampling); + + static bool hsmm_sampling = false; + static int hsmm_sampling_start_state = 0; + static int hsmm_sampling_traj_length = 10; + ImGui::Checkbox("Run hsmm sampling", &hsmm_sampling); + + if (hsmm_sampling) { + ImGui::SliderInt("Start state", &hsmm_sampling_start_state, 0, hsmm.getNumSTATES() - 1); + ImGui::SliderInt("Trajectory length", &hsmm_sampling_traj_length, 2, 1000); + if (ImGui::Button("Sample") && (hsmm.getNumSTATES()!=1)) { + mat pred(hsmm.getNumSTATES(), hsmm_sampling_traj_length, fill::zeros); + if (!hsmm_stochastic_sampling) { + hsmm.predictForwardVariableDeterministic(pred, hsmm_sampling_start_state); + }else{ + hsmm.predictForwardVariableStochastic(pred); + } + uword state_seq[pred.n_cols]; + get_state_seq(state_seq, pred); + mat hsmm_rData = run_lqr(A, B, dt, + R, hsmm_sampling_traj_length, hsmm.getMU(state_seq[0]), state_seq, + hsmm); + repros_sampling.push_back(hsmm_rData); + } + ImGui::SameLine(); + if (ImGui::Button("Clear Samples")) { + repros_sampling.clear(); + } + } + + //Get data + ImVec2 mouse_pos_in_canvas_curr = ImVec2(ImGui::GetIO().MousePos.x, + ImGui::GetIO().DisplaySize.y - ImGui::GetIO().MousePos.y); + + double alpha = 0.2; + mouse_pos_in_canvas.x = mouse_pos_in_canvas.x + + alpha*(mouse_pos_in_canvas_curr.x - mouse_pos_in_canvas.x); + mouse_pos_in_canvas.y = mouse_pos_in_canvas.y + + alpha*(mouse_pos_in_canvas_curr.y - mouse_pos_in_canvas.y); + + if ((ImGui::GetIO().MousePos.x<352 && ImGui::GetIO().MousePos.y<300)==0){ //Is outside gui? + if (!adding_line && ImGui::GetIO().MouseClicked[0]){ //Button pushed + adding_line = true; + if (!dispGMM){ + colvec p(2); + p(0) = mouse_pos_in_canvas.x; + p(1) = mouse_pos_in_canvas.y; +// p(2) = 0.0; +// p(3) = 0.0; +// colvec pd(2); +// pd(0) = 0.0; // initial velocity is always set to 0 +// pd(1) = 0.0; + GaussianDistribution componentTmp(p,minSIGMA); + comps.push_back(componentTmp); + hsmm.setCOMPONENTS(comps); + comps.clear(); + dispGMM = true; + } + } + if (adding_line){ //Trajectory recording + points.push_back(mouse_pos_in_canvas); +// if (points.size()>2){ +// ImVec2 currVel ( ((float)points.back().x - (float)points[points.size()-2].x ) / (float) dt, +// ((float)points.back().y - (float)points[points.size()-2].y ) / (float) dt ); +// pointsVel.push_back(currVel); +// }else{ +// ImVec2 zero(0.0,0.0); // always start with zeros +// pointsVel.push_back(zero); +// } + + nbPts++; + vec p(2); + p(0) = mouse_pos_in_canvas.x; + p(1) = mouse_pos_in_canvas.y; +// p(2) = pointsVel.back().x; +// p(3) = pointsVel.back().y; + + hsmm.onlineEMDP(nbPts, p, lambda, minSigma); + + if (!ImGui::GetIO().MouseDown[0]){ //Button released + adding_line = false; + //Add demonstration + Demonstration demo = Demonstration(nVars,points.size()); + for (int t=0; t<(int)points.size(); t++){ + demo.getDatapoints().getData()(0,t) = points[t].x; + demo.getDatapoints().getData()(1,t) = points[t].y; +// demo.getDatapoints().getData()(2,t) = pointsVel[t].x; +// demo.getDatapoints().getData()(3,t) = pointsVel[t].y; + } + demos.push_back(demo); + + //Compute sequence of states + mat h(hsmm.getNumSTATES(), points.size()); + for (int i=0; i<(int)hsmm.getNumSTATES(); i++){ + h.row(i) = trans(hsmm.getCOMPONENTS(i).getPDFValue(demo.getDatapoints().getData())); + } + uword imax[points.size()]; + get_state_seq(imax, h); + + //LQR + mat rData = run_lqr(A, B, dt, + R, /*Q,*/ points.size(), demo.getDatapoints().getData().col(0), imax, + hsmm); + repros.push_back(rData); + + //.HSMM testing part + hsmm.integrateDemonstration(demo); + mat pred(hsmm.getNumSTATES(), points.size(), fill::zeros); + + hsmm.predictForwardVariableDeterministic(pred, imax[0]); + + uword state_seq[pred.n_cols]; + get_state_seq(state_seq, pred); + + //LQR + mat hsmm_rData = run_lqr(A, B, dt, + R, /*Q,*/ points.size(), hsmm.getMU(state_seq[0]), state_seq, + hsmm); + repros_hsmm.push_back(hsmm_rData); + //.End of HSMM section// + + //Clean up + points.clear(); + pointsVel.clear(); + } + } + } + ImGui::End(); + + //GUI rendering + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + ImGui::Render(); + + //PbDlib rendering + glPushMatrix(); + glTranslatef(-1.0f,-1.0f,0); + glScalef(2.0f/(float)ImGui::GetIO().DisplaySize.x, 2.0f/(float)ImGui::GetIO().DisplaySize.y, 1.0f); + glLineWidth(2.0f); + + //Draw current demo + glColor3f(0.0f, 0.0f, 0.0f); + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)points.size(); t++){ + glVertex2f(points[t].x, points[t].y); + } + glEnd(); + + //Draw demos + glColor3f(0.3f, 0.3f, 0.3f); + for (int n=0; n<(int)demos.size(); n++){ + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)demos[n].getDatapoints().getNumPOINTS(); t++){ + glVertex2f(demos[n].getDatapoints().getData()(0,t), demos[n].getDatapoints().getData()(1,t)); + } + glEnd(); + } + +// //Draw repros +// glColor3f(0.0f, 0.8f, 0.0f); +// for (int n=0; n<(int)repros.size(); n++){ +// glBegin(GL_LINE_STRIP); +// for (int t=0; t<(int)repros[n].n_cols; t++){ +// glVertex2f(repros[n](0,t), repros[n](1,t)); +// } +// glEnd(); +// } + +// //Draw repros hsmm +// glColor3f(0.0f, 0.0f, 0.8f); +// for (int n=0; n<(int)repros_hsmm.size(); n++){ +// glBegin(GL_LINE_STRIP); +// for (int t=0; t<(int)repros_hsmm[n].n_cols; t++){ +// glVertex2f(repros_hsmm[n](0,t), repros_hsmm[n](1,t)); +// } +// glEnd(); +// } + + //Draw repros sampling + glLineWidth(3.0f); + glColor3f(0.0f, 0.0f, 0.9f); + for (int n=0; n<(int)repros_sampling.size(); n++){ + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)repros_sampling[n].n_cols; t++){ + glVertex2f(repros_sampling[n](0,t), repros_sampling[n](1,t)); + } + glEnd(); + } + glLineWidth(2.0f); + + //Draw Gaussians + if (dispGMM){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glColor3f(0.8f, 0.0f, 0.0f); + for (int i=0; i<(int)hsmm.getNumSTATES(); i++){ +// eig_sym(d, V, gmm.getSIGMA(i)); + eig_sym(d, V, hsmm.getSIGMA(i).submat(0,0,1,1)); + R = V * sqrt(diagmat(d)); + pts = R * pts0; + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f((pts(0,t)+hsmm.getMU(i)(0)), (pts(1,t)+hsmm.getMU(i)(1))); + } + glEnd(); + glBegin(GL_POINTS); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f(hsmm.getMU(i)(0), hsmm.getMU(i)(1)); + } + glEnd(); + } + } + + glPopMatrix(); + glfwSwapBuffers(window); + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + return 0; +} + +mat run_lqr(mat A, mat B, float dt, + mat R, //std::vector<mat> Q, + int traj_length, colvec start_state, uword state_seq[], + GMM_Model model){ + + LQR lqr(A, B, dt); + + std::vector<mat> Q; + vec vTmp(4, fill::zeros); + mat QTmp(4, 4, fill::zeros); + mat Target(4, traj_length, fill::zeros); + for (int t=0; t<traj_length; t++){ + QTmp.submat(0, 0, 1, 1) = inv(model.getSIGMA(state_seq[t])); + // QTmp = inv(model.getSIGMA(state_seq[t])); // for vel + Q.push_back(QTmp); + vTmp.subvec(0, 1) = model.getMU(state_seq[t]); + // vTmp = model.getMU(state_seq[t]); // for vel + Target.col(t) = vTmp; + } + lqr.setProblem(R, Q, Target); + + lqr.evaluate_gains_infiniteHorizon(); + + //Retrieve data + mat rData(2, traj_length); + vec u(2); + vec X = join_cols(start_state, zeros<vec>(2)); // second part sets the velocities to zero + // vec X = start_state; // for vel + for (int t=0; t<traj_length; t++){ + rData.col(t) = X.rows(0, 1); + u = lqr.getGains().at(t) * (Target.col(t)-X); + X += (A*X+B*u) * dt; + } + return rData; +} + +void get_state_seq(uword state_seq[], mat pred){ + for (int t=0; t<pred.n_cols; t++){ + vec vTmp = pred.col(t); + vTmp.max(state_seq[t]); + } +} + + diff --git a/src/demo_proMP01.cpp b/src/demo_proMP01.cpp new file mode 100644 index 0000000..55c57a3 --- /dev/null +++ b/src/demo_proMP01.cpp @@ -0,0 +1,468 @@ +/* + * demo_proMP01.cpp + * + * Conditioning on trajectory distributions with ProMP + * + * @incollection{Paraschos13, + * title = {Probabilistic Movement Primitives}, + * author = {Paraschos, A. and Daniel, C. and Peters, J. and Neumann, G.}, + * booktitle = NIPS, + * pages = {2616--2624}, + * year = {2013}, + * publisher = {Curran Associates, Inc.} + * } + * @inproceedings{Rueckert15, + * author = "Rueckert, E. and Mundo, J. and Paraschos, A. and Peters, J. and Neumann, G.", + * title = "Extracting Low-Dimensional Control Variables for Movement Primitives", + * booktitle = ICRA, + * year = "2015", + * pages = "1511--1518", + * address = "Seattle, WA, USA" + * } + * + * Authors: Sylvain Calinon, Philip Abbet + */ + + +#include <stdio.h> +#include <armadillo> +#include <pbdlib/demonstration.h> +#include <pbdlib/mvn.h> + +#include <gfx3.h> +#include <gfx_ui.h> +#include <GLFW/glfw3.h> +#include <imgui.h> +#include <imgui_impl_glfw_gl3.h> + + +using namespace pbdlib; + + +/*********************************** TYPES ***********************************/ + +struct parameters_t { + int nb_states; // Number of components in the GMM + int nb_var; // Dimension of position data (here: x1, x2) + int nb_data; // Number of datapoints in a trajectory + float dt; // Time step (without rescaling, large values such + // as 1 has the advantage of creating clusers based + // on position information) +}; + + +/******************************** CONSTANTS **********************************/ + +const arma::mat COLORS({ + { 0.00000, 0.00000, 1.00000}, + { 0.00000, 0.50000, 0.00000}, + { 1.00000, 0.00000, 0.00000}, + { 0.00000, 0.75000, 0.75000}, + { 0.75000, 0.00000, 0.75000}, + { 0.75000, 0.75000, 0.00000}, + { 0.25000, 0.25000, 0.25000}, + { 0.00000, 0.00000, 1.00000}, + { 0.00000, 0.50000, 0.00000}, + { 1.00000, 0.00000, 0.00000}, +}); + + +/****************************** HELPER FUNCTIONS *****************************/ + +static void error_callback(int error, const char* description) { + fprintf(stderr, "Error %d: %s\n", error, description); +} + +//----------------------------------------------- + +// Create a demonstration (with a length of 'nb_samples') from a trajectory +// (of any length) +Demonstration sample_trajectory(const std::vector<arma::vec>& trajectory, int nb_samples) { + + // Resampling of the trajectory + arma::vec x(trajectory.size()); + arma::vec y(trajectory.size()); + arma::vec x2(trajectory.size()); + arma::vec y2(trajectory.size()); + + for (size_t i = 0; i < trajectory.size(); ++i) { + x(i) = trajectory[i](0); + y(i) = trajectory[i](1); + } + + arma::vec from_indices = arma::linspace<arma::vec>(0, trajectory.size() - 1, trajectory.size()); + arma::vec to_indices = arma::linspace<arma::vec>(0, trajectory.size() - 1, nb_samples); + + interp1(from_indices, x, to_indices, x2, "*linear"); + interp1(from_indices, y, to_indices, y2, "*linear"); + + // Create the demonstration + Demonstration demo = Demonstration(2, nb_samples); + mat& datapoints = demo.getDatapoints().getData(); + for (int i = 0; i < nb_samples; ++i) { + datapoints(0, i) = x2[i]; + datapoints(1, i) = y2[i]; + } + + return demo; +} + + +/********************************* FUNCTIONS *********************************/ + +// The actual computation +// +// Inputs: demos, parameters +// Outputs: mu_mat, mu2_mat, H +void process(std::vector<Demonstration>& demos, const parameters_t& parameters, + arma::mat &mu_mat, arma::mat &mu2_mat, arma::mat &H) { + + // Create basis functions (GMM with components equally split in time) + arma::vec timesteps = arma::linspace<arma::vec>( + 0, parameters.nb_data - 1, parameters.nb_data + ) * parameters.dt; + + arma::vec mu = arma::linspace<arma::vec>( + timesteps(0), timesteps(timesteps.n_rows - 1), parameters.nb_states + ); + + arma::vec sigma = arma::ones<arma::vec>(parameters.nb_states) * 0.01; + + // Compute basis functions activation + H = arma::mat(parameters.nb_states, parameters.nb_data); + + for (unsigned int i = 0; i < parameters.nb_states; ++i) { + arma::colvec mu_({ mu(i) }); + arma::mat sigma_({ sigma(i) }); + + GaussianDistribution gauss(mu_, sigma_); + + H.row(i) = gauss.getPDFValue(timesteps.t()).t(); + } + + H = H / repmat(sum(H, 0), parameters.nb_states, 1); + + + //_____ ProMP __________ + + arma::mat psi(parameters.nb_var * parameters.nb_data, + parameters.nb_var * parameters.nb_states); + + for (unsigned int i = 0; i < parameters.nb_data; ++i) { + psi.rows(i * parameters.nb_var, (i + 1) * parameters.nb_var - 1) = + arma::kron(H.col(i).t(), arma::eye(parameters.nb_var, parameters.nb_var)); + } + + arma::mat w(parameters.nb_var * parameters.nb_states, demos.size()); + for (size_t i = 0; i < demos.size(); ++i) { + w.col(i) = pinv(psi) * (arma::mat) arma::vectorise(demos[i].getDatapoints().getData()); + } + + // Distribution in parameter space + arma::mat mu_w = arma::mean(w, 1); + + //-- First regularization term + arma::mat sigma_w = arma::eye(parameters.nb_var * parameters.nb_states, + parameters.nb_var * parameters.nb_states); + + if (w.n_cols == 1) { + sigma_w += arma::rowvec(arma::cov(w.t()))[0]; + } + else { + sigma_w += arma::cov(w.t()); + } + + // Trajectory distribution + mu = psi * mu_w; + + arma::mat sigma2 = psi * sigma_w * psi.t() + // Second regularization term + 0.01 * arma::eye(parameters.nb_var * parameters.nb_data, + parameters.nb_var * parameters.nb_data); + + + //_____ Conditioning on trajectory distribution __________ + // (reconstruction from partial data) + + arma::uvec in_out = arma::linspace<arma::uvec>( + 0, parameters.nb_data * parameters.nb_var - 1, parameters.nb_data * parameters.nb_var + ); + + arma::uvec in(2 * parameters.nb_var); + + in.head(parameters.nb_var) = in_out.head(parameters.nb_var); + in.tail(parameters.nb_var) = in_out.tail(parameters.nb_var); + + arma::uvec out = in_out.subvec(parameters.nb_var, in_out.n_elem - parameters.nb_var - 1); + + // Input data + arma::vec mu_in = arma::reshape( + demos[0].getDatapoints().getData().cols(arma::uvec({0, (unsigned) parameters.nb_data - 1})) + + arma::repmat((arma::randu(parameters.nb_var, 1) - 0.5) * 10.0, 1, 2), + parameters.nb_var * 2, 1 + ); + + // Gaussian conditioning with trajectory distribution + arma::vec mu2(in_out.n_elem, fill::zeros); + + mu2.rows(in) = mu_in; + + arma::mat A = sigma_w * psi.rows(in).t(); // Used to simplify the + arma::mat B = psi.rows(in) * sigma_w * psi.rows(in).t(); // following operation + + arma::mat mu_w_tmp = mu_w + + (arma::inv(B.t()) * A.t()).t() * // == A / B (not + (mu2.rows(in) - psi.rows(in) * mu_w); // supported by armadillo) + + mu2.rows(out) = psi.rows(out) * mu_w_tmp; + + + //_____ Results __________ + + mu_mat = arma::conv_to<arma::mat>::from(mu); + mu_mat.reshape(parameters.nb_var, parameters.nb_data); + + mu2_mat = arma::conv_to<arma::mat>::from(mu2); + mu2_mat.reshape(parameters.nb_var, parameters.nb_data); +} + +//----------------------------------------------- + +int main(int argc, char **argv) { + arma::arma_rng::set_seed_random(); + + // Parameters + parameters_t parameters; + parameters.nb_states = 6; + parameters.nb_var = 2; + parameters.dt = 0.01; + parameters.nb_data = 100; + + + // Initialise GLFW + glfwSetErrorCallback(error_callback); + + if (!glfwInit()) + return -1; + + glfwWindowHint(GLFW_SAMPLES, 4); + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + + // Open a window and create its OpenGL context + GLFWwindow* window = glfwCreateWindow( + 800, 800, "Demo Conditioning on trajectory distributions", NULL, NULL + ); + + glfwMakeContextCurrent(window); + + // Take 4k screens into account (framebuffer size != window size) + int win_width = ImGui::GetIO().DisplaySize.x; + int win_height = ImGui::GetIO().DisplaySize.y; + + int fb_width, fb_height; + glfwGetFramebufferSize(window, &fb_width, &fb_height); + + // Setup GLSL + gfx3::init(); + glEnable(GL_DEPTH_TEST); + glEnable(GL_CULL_FACE); + glEnable(GL_LINE_SMOOTH); + glDepthFunc(GL_LESS); + + // Setup ImGui + ImGui_ImplGlfwGL3_Init(window, true); + + // Creation of the Vertex Array Object (VAO) + GLuint vertexArrayID; + glGenVertexArrays(1, &vertexArrayID); + glBindVertexArray(vertexArrayID); + + + // Projection matrix + arma::fmat projection = gfx3::orthographic( + (float) fb_width, (float) fb_height, 0.1f, 10.0f); + + // Camera matrix + arma::fmat view = gfx3::lookAt( + arma::fvec({0, 0, 3}), // Position of the camera + arma::fvec({0, 0, 0}), // Look at the origin + arma::fvec({0, 1, 0}) // Head is up + ); + + + // Loading of the shaders + gfx3::shader_t colored_shader = gfx3::loadShader(gfx3::VERTEX_SHADER_COLORED, + gfx3::FRAGMENT_SHADER_COLORED); + + + // Main loop + bool adding_line = false; + std::vector<arma::vec> current_trajectory; + std::vector< std::vector<arma::vec> > original_trajectories; + std::vector<Demonstration> demos; + arma::mat mu; + arma::mat mu2; + arma::mat H; + int current_nb_data = parameters.nb_data; + int current_nb_states = parameters.nb_states; + + while (!glfwWindowShouldClose(window)) { + glfwPollEvents(); + + // Detect when the window was resized + if ((ImGui::GetIO().DisplaySize.x != win_width) || + (ImGui::GetIO().DisplaySize.y != win_height)) { + + win_width = ImGui::GetIO().DisplaySize.x; + win_height = ImGui::GetIO().DisplaySize.y; + + glfwGetFramebufferSize(window, &fb_width, &fb_height); + + // Update the projection matrix + projection = gfx3::orthographic( + (float) fb_width, (float) fb_height, 0.1f, 10.0f); + } + + + // If the parameters changed, recompute + if ((parameters.nb_data != current_nb_data) || + (parameters.nb_states != current_nb_states)) { + + demos.clear(); + + for (size_t i = 0; i < original_trajectories.size(); ++i) + demos.push_back(sample_trajectory(original_trajectories[i], parameters.nb_data)); + + process(demos, parameters, mu, mu2, H); + + current_nb_data = parameters.nb_data; + current_nb_states = parameters.nb_states; + } + + + // Start the rendering + ImGui_ImplGlfwGL3_NewFrame(); + glViewport(0, 0, fb_width, fb_height); + glClearColor(0.6f, 0.6f, 0.6f, 0.0f); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + + // Draw the currently created demonstration (if any) + if (current_trajectory.size() > 1) { + gfx3::model_t line = gfx3::create_line( + colored_shader, arma::fvec({0.33f, 0.97f, 0.33f}), current_trajectory); + + gfx3::draw(line, view, projection); + + gfx3::destroy(line); + } + + + // Draw the demonstrations (if any) + for (auto iter = demos.begin(); iter != demos.end(); ++iter) { + Datapoints& datapoints = iter->getDatapoints(); + + for (uint i = 0; i < datapoints.getNumPOINTS(); ++i) { + arma::fvec color = arma::conv_to<arma::fvec>::from(H.col(i).t() * COLORS.rows(0, parameters.nb_states - 1)); + + gfx3::model_t point = gfx3::create_square(colored_shader, color, 10.0f); + + point.transforms.position = arma::conv_to<arma::fvec>::from(datapoints.getData(i)); + point.transforms.position.reshape(3, point.transforms.position.n_cols); + + gfx3::draw(point, view, projection); + + gfx3::destroy(point); + } + } + + + // Draw the computed trajectories + if (mu.n_elem > 0) { + gfx3::model_t line = gfx3::create_line( + colored_shader, arma::fvec({0.0f, 0.0f, 0.0f}), mu); + + gfx3::draw(line, view, projection); + + gfx3::destroy(line); + + line = gfx3::create_line( + colored_shader, arma::fvec({0.8f, 0.0f, 0.0f}), mu2); + + gfx3::draw(line, view, projection); + + gfx3::destroy(line); + } + + + // Parameter window + ImGui::SetNextWindowSize(ImVec2(400, 110)); + ImGui::Begin("Parameters", NULL, + ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | + ImGuiWindowFlags_NoMove + ); + + ImGui::SliderInt("Nb states", ¶meters.nb_states, 2, 10); + ImGui::SliderInt("Nb data", ¶meters.nb_data, 20, 300); + + if (ImGui::Button("Clear")){ + demos.clear(); + original_trajectories.clear(); + mu = arma::mat(); + mu2 = arma::mat(); + H = arma::mat(); + } + + ImGui::Text("Draw several similar trajectories"); + ImGui::End(); + + + // GUI rendering + ImGui::Render(); + + // Swap buffers + glfwSwapBuffers(window); + + // Keyboard input + if (ImGui::IsKeyPressed(GLFW_KEY_ESCAPE)) + break; + + + // Left click: start a new demonstration + if (!adding_line && ImGui::IsMouseClicked(GLFW_MOUSE_BUTTON_1)) { + // Only if not on the UI + if (!ImGui::GetIO().WantCaptureMouse) + adding_line = true; + } + + if (adding_line) { + double mouse_x, mouse_y; + glfwGetCursorPos(window, &mouse_x, &mouse_y); + + current_trajectory.push_back(gfx3::ui2fb({ mouse_x, mouse_y }, + win_width, win_height, + fb_width, fb_height)); + } + + // Left mouse button release: end the demonstration creation + if (adding_line && !ImGui::IsMouseDown(GLFW_MOUSE_BUTTON_1)) { + adding_line = false; + + demos.push_back(sample_trajectory(current_trajectory, parameters.nb_data)); + + original_trajectories.push_back(current_trajectory); + current_trajectory.clear(); + + process(demos, parameters, mu, mu2, H); + } + } + + + // Cleanup + ImGui_ImplGlfwGL3_Shutdown(); + glfwTerminate(); + + return 0; +} diff --git a/src/demo_teleop.cpp b/src/demo_teleop.cpp new file mode 100644 index 0000000..417942a --- /dev/null +++ b/src/demo_teleop.cpp @@ -0,0 +1,568 @@ +/* + * demo_teleop.cpp + * + * Online learning of tphsmm model and teleoperator-like usage scenario. + * + * Authors: Ioannis Havoutis, Sylvain Calinon. + */ + +#define prt(x) std::cout << #x " = '" << x << "'" << std::endl; +#define prt_msize(x) std::cout << #x ", rows: " << x.n_rows << ", cols: " << x.n_cols << std::endl; + +#include <stdio.h> +#include "armadillo" + +#include <GLFW/glfw3.h> +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include "gfx_ui.h" + +#include <pbdlib/gmm.h> +#include <pbdlib/gmr.h> +#include <pbdlib/lqr.h> +#include <pbdlib/taskparameters.h> +#include <pbdlib/tpdemonstration.h> +#include <pbdlib/tpdpgmm.h> +#include "pbdlib/trajMPC.h" +#include "pbdlib/tptrajMPC.h" + +#include "misc_utils.h" +#include "draw_utils.h" + +#include <vector> +#include <fstream> +#include <iomanip> + +using namespace std; +using namespace pbdlib; +using namespace arma; + +typedef std::vector<float> stdfvec; +typedef std::vector<double> stddvec; + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +mat solveReconstruction(TPDPGMM& tpgmm, vec startPoint, float iFactor, int nRecPoints) { + static mat A(4,4), B(4,2); + static float dt = 0.01f; + mat R = eye(2,2) * pow(10.0f, iFactor); + + static mat A1d; A1d << 0 << 1 << endr << 0 << 0 << endr; + static mat B1d; B1d << 0 << endr << 1 << endr; + A = kron(A1d, eye(2,2)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + B = kron(B1d, eye(2,2)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + LQR lqr(A,B,dt); + + static std::vector<mat> Q; + + //Get most probable state + colvec p(startPoint); + mat h_i(tpgmm.getProdGMM()->getNumSTATES(), 1); + for (int i=0; i<(int)tpgmm.getProdGMM()->getNumSTATES(); i++){ + h_i.row(i) = trans(tpgmm.getProdGMM()->getCOMPONENTS(i).getPDFValue(p)); + } + uword start_state; + h_i.max(start_state); // prt(start_state); + + mat pred; + pred = tpgmm.predictForwardVariable(nRecPoints,start_state); // prt(pred.t()); + uword imax[nRecPoints]; + for (int t=0; t<nRecPoints; t++){ + vec vTmp = pred.col(t); + vTmp.max(imax[t]); // cout<<imax[t]<<"-"; + } // cout<<endl<<endl; + + //LQR + static vec vTmp(4,fill::zeros); + static mat QTmp(4,4,fill::zeros); + mat Target(4,nRecPoints,fill::zeros); + for (int t=0; t<nRecPoints; t++){ + QTmp.submat(0,0, + tpgmm.getNumVARS()-1 , tpgmm.getNumVARS()-1) = + inv(tpgmm.getProdGMM()->getSIGMA(imax[t]).submat(0,0, tpgmm.getNumVARS()-1, tpgmm.getNumVARS()-1)); + Q.push_back(QTmp); + vTmp.subvec(0,tpgmm.getNumVARS()-1) = tpgmm.getProdGMM()->getMU(imax[t]).subvec(0,tpgmm.getNumVARS()-1); + Target.col(t) = vTmp; + } + lqr.setProblem(R,Q,Target); + static mat S(4,4,fill::zeros); + static vec d(4,fill::zeros); + lqr.evaluate_gains_infiniteHorizon(); + + //Retrieve data + mat rData(2,nRecPoints); + static vec u(2); + static vec X(4,fill::zeros); + X.subvec(0,tpgmm.getNumVARS()-1) = startPoint.rows(0, tpgmm.getNumVARS()-1 ); + for (int t=0; t<nRecPoints; t++){ + rData.col(t) = X.rows(0,1); + u = lqr.getGains().at(t) * (Target.col(t)-X); + X += (A*X+B*u) * dt; + } + + Q.clear(); + return rData; +} + +int main(int argc, char **argv){ + mat refShape = { //reference drawing + {-0.3, -0.3, 0.3, 0.3 }, + {1.0, 0.0 , 0.0, 1.0}}; + float refScale = 50.0; + refShape = refShape + 10.0 / refScale; + refShape = refScale * refShape; + + //Setup TPDPGMM + float minSigma = 200.0f; //1E2; + float lambda = 100.0f; + mat minSIGMA = eye(2,2) * minSigma; + + int nVars = 2; + const int nTps = 1; + + TPDPGMM tpdpgmm(nVars,1,nTps,2,lambda); + TaskParameters tp(nVars,nTps); + vector<TPDemonstration> tpdemos; + vector<mat> repros; + + //Setup LQR + float iFactor = -6.0f; + int nRecPoints = 300; + + float filterAlphaPos = 0.1; + bool stateMerging = false; + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + + GLFWwindow* window = glfwCreateWindow(520, 540, "Teleoperation model", NULL, NULL); + glfwMakeContextCurrent(window); + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // Setup ImGui binding + ImGui_ImplGlfw_Init(window, true); + + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->AddFontDefault(); + ui::init(20.); + ui::Trans2d trans(ImVec2(50,0), // X axis + ImVec2(0,30), // Y axis (expected orthogonal) + ImVec2(60,400)); // position + ImVec4 clear_color = ImColor(240, 240, 240); // white background + ImVector<ImVec2> points, velocities; + vector<vec> pointsV, velocitiesV; + bool adding_line = false; + bool modelExist = false; + bool model_changed = false; + bool dispRef = true; + bool dispDemo = true; + bool dispGMM = true; + bool useFramePRIORS = false; + bool movingRef = false; + bool hoveringRef = false; + int nbPts = 0; + bool init = true; + bool startFlag = false; + bool endFlag = false; + float alphaHandles = 0.2f; + + Ref teleopFrames[nTps]; + + vec tele_g_pos;// robo_g_pos; + tele_g_pos = zeros(2); + + vec framesTmpPos = zeros(2); + vec trParam = ones(2); + TaskParameter tpTmp; + colvec p(nVars, fill::zeros); + mat p_frame(nVars, nTps+1); + mat pred; + mat rData; + + colorCode.push_back(colRed); + colorCode.push_back(colBRGreen); + + bool sample_model_cmd = false; + bool stop_mpc_cmd = false; + + //trajMPC parameters====================== + // Model Settings: + uint nVarsPos = 2; // Number of position variables + uint nDeriv = 2; // Number of derivatives considered + + // TrajMPC Settings: + int mpc_start_state = -1; + int Np = -1; // Number of predictions + int Nc = 30; // Number of control predictions + float mpc_dt = 1.0; // time step considered + float alpha = 10.0; // control cost variable + + colvec Xinit; + HSMM* myHSMM; + HSMM* someHSMM; + GMM_Model* tmpGMM; + GMM_Model* tmpGMM_ex; + TrajMPC* myTrajMPC; + + mat Ad, Bd; + mat TestData; + colvec U; + colvec curPos = {0.0,0.0}; + bool trajMPCrunning = false; + vector<mat> trajMPCruns; + //================================ + + while (!glfwWindowShouldClose(window)){ + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + hoveringRef = false; + + ui::begin(); + trans = ui::affineSimple(0, trans); + hoveringRef = ui::hasFocus()||hoveringRef; + ui::end(); + + teleopFrames[0].p1(0)=trans.pos.x; + teleopFrames[0].p1(1)=ImGui::GetIO().DisplaySize.y - trans.pos.y; + + teleopFrames[0].p2(0)=trans.x.x + trans.pos.x; + teleopFrames[0].p2(1)=ImGui::GetIO().DisplaySize.y - (trans.x.y + trans.pos.y); + + for (int i = 0; i < nTps; ++i) { + teleopFrames[i].updateRef(); + } + + int control_panel_height = 300; + int control_panel_width = 500; + + if (init){ // Init the control panel + ImGui::SetNextWindowPos(ImVec2(2,2)); + ImGui::SetNextWindowCollapsed(true);//true); + } + + init = false; + ImGui::Begin("Control Panel", NULL, + ImVec2(control_panel_width,control_panel_height), 1.0f, ImGuiWindowFlags_NoSavedSettings); + + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + + ImGui::Text("Left-click to collect demonstrations."); + ImGui::Text("'S' to sample, 'D' to delete model."); + ImGui::Text("'R' to start MPC, 'T' to stop MPC execution."); + ImGui::Text("nbDemos: %i, nbPoints: %i, nbStates: %i", + (int)tpdemos.size(), (int)nbPts, (int)tpdpgmm.getNumSTATES()); + + ImGui::Separator(); + ImGui::Text("Model learning parameters"); + ImGui::SliderFloat("Min. Sigma", &minSigma, 1E1, 20E2); + ImGui::SliderFloat("lambda", &lambda, 10.0f, 200.0f); + + ImGui::Checkbox("Display Demos",&dispDemo);ImGui::SameLine(); + ImGui::Checkbox("Plot Gaussians",&dispGMM);ImGui::SameLine(); + + ImGui::Checkbox("State Merging",&stateMerging); + ImGui::SliderFloat("Position Filter a", &filterAlphaPos, 0, 1, "%.2f"); + + ImGui::Separator(); + ImGui::Text("LQR motion generation parameters"); + ImGui::SliderFloat("Control cost", &iFactor, -10, -0.001, "%.4f"); + ImGui::SliderInt("Motion length", &nRecPoints, 10, 1000); + + ImGui::Separator(); + if (ImGui::Button("Clear")){ + tpdemos.clear(); + repros.clear(); + tpdpgmm = TPDPGMM(nVars,1,nTps,2,lambda); + modelExist = false; + nbPts = 0; + + TestData.clear(); //trajMPC params + curPos.clear(); + trajMPCrunning = false; + trajMPCruns.clear(); + } + ImGui::SameLine(); + if (ImGui::Button("Clear MPC")){ + TestData.clear(); //trajMPC params + curPos.clear(); + trajMPCrunning = false; + trajMPCruns.clear(); + } + ImGui::Separator(); + + ImGui::SliderInt("MPC start state", &mpc_start_state, -1, 10); + ImGui::SliderInt("MPC n control pred.", &Nc, 1, 100); + ImGui::SliderFloat("MPC time step", &mpc_dt, 0.001, 10.0, "%.3f"); + ImGui::SliderFloat("MPC control cost", &alpha, 0, 1000.0, "%.4f"); + + tpdpgmm.useFramePRIORS(useFramePRIORS); + + if (sample_model_cmd && modelExist){ + if (!trajMPCrunning){ + /*Initialize trajMPC*/ + if (TestData.size()){ + trajMPCruns.push_back(TestData); + } + int nSTATES = tpdpgmm.getHSMM()->getNumSTATES(); + int nVARS = 4; + someHSMM = new HSMM(nSTATES,nVARS); + myHSMM = someHSMM; + myHSMM->setTRANSITION(tpdpgmm.getHSMM()->getTRANSITION()); + myHSMM->setDurationCOMPONENTS(tpdpgmm.getHSMM()->getDurationCOMPONENTS()); + myHSMM->setPRIORS(tpdpgmm.getPRIORS()); + + tmpGMM = tpdpgmm.getTransformedGMM(tp); + tmpGMM_ex = new GMM_Model(nSTATES,nVARS); + + for (int i = 0; i < nSTATES; i++){ // state durations are univariate + tmpGMM_ex->setMU(i, join_vert(tmpGMM->getMU(i),zeros(2,1)) ); + mat sigma = eye(4,4); + sigma.submat(0,0,1,1) = tmpGMM->getSIGMA(i); + tmpGMM_ex->setSIGMA(i, sigma ); + } + myHSMM->setCOMPONENTS(tmpGMM_ex->getCOMPONENTS()); + myHSMM->initializeFwdCalculation(); + + double av_state_duration = 0.0; + for (int i = 0; i < tpdpgmm.getHSMM()->getNumSTATES(); ++i) { + av_state_duration += tpdpgmm.getHSMM()->getDurMU(i)(0); + } + Np = ceil(1.5*(2.0/tpdpgmm.getHSMM()->getNumSTATES()) * av_state_duration); + + if (Nc>=Np){Nc = Np;} + myTrajMPC = new TrajMPC(myHSMM,mpc_dt,nVarsPos,nDeriv,Np,Nc,alpha); + + // Make sure that the TrajMPC model is correctly initialised by resetting it before starting + myTrajMPC->reset(); + + Ad = myTrajMPC->getSystemDynamics(); + Bd = myTrajMPC->getInputDynamics(); + if (mpc_start_state == -1){ + TestData = join_vert(tele_g_pos,zeros(4,1)); + curPos = vec4({tele_g_pos(0), tele_g_pos(1), 0.0, 0.0}); + }else{ + curPos = myHSMM->getMU(mpc_start_state); + } + trajMPCrunning = true; + }else{ + tmpGMM = tpdpgmm.getTransformedGMM(tp); + for (int i = 0; i < tpdpgmm.getHSMM()->getNumSTATES(); ++i) { + myTrajMPC->setMu(i, join_vert(tmpGMM->getMU(i),zeros(2,1))); + mat sigma = eye(4,4); + sigma.submat(0,0,1,1) = tmpGMM->getSIGMA(i); + myTrajMPC->setSigma(i,sigma); + } + U = myTrajMPC->computeControlCommand(curPos); + // Simulate movement of attractor: + curPos = Ad*curPos + Bd*U; + colvec temp = join_cols(curPos, U); + TestData = join_rows(TestData, temp); + if (stop_mpc_cmd){ + if (TestData.size()){ + //trajMPCruns.push_back(TestData); + } + TestData.clear(); //trajMPC params + curPos.clear(); + trajMPCrunning = false; + sample_model_cmd = false; + stop_mpc_cmd = false; + repros.clear(); + } + } + // } + } + + //Get data + ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x, + ImGui::GetIO().DisplaySize.y - ImGui::GetIO().MousePos.y); + + tele_g_pos = tele_g_pos + filterAlphaPos * + ( vec({mouse_pos_in_canvas.x, mouse_pos_in_canvas.y}) - tele_g_pos); + + if(hoveringRef&&ImGui::GetIO().MouseClicked[0]){ + movingRef = true; + repros.clear(); + } + if(movingRef&&!ImGui::GetIO().MouseDown[0]) + movingRef = false; + + if (movingRef&&modelExist && !ImGui::GetIO().MouseClicked[0]) { + for(int i=0;i<nTps;i++) { + tpTmp.A = teleopFrames[i].A; + tpTmp.b = teleopFrames[i].b; + tp.setTaskParameters(i,tpTmp); + } + tpdpgmm.getTransformedGMM(tp,INVERTIBLE); + + // trParam = refFrame[1].b-refFrame[0].b; + tpdpgmm.updateTransition(trParam); + } + + if (!movingRef && (ImGui::GetIO().MousePos.x < ImGui::GetIO().DisplaySize.x)) { //Is outside gui? + if (!adding_line && ImGui::GetIO().MouseClicked[0]){ //Button pushed + adding_line = true; + startFlag = true; + endFlag = false; + } + if (!ImGui::GetIO().MouseDown[0]) endFlag = true; + + if (adding_line){ //Trajectory recording + nbPts++; + p = tele_g_pos; + pointsV.push_back(tele_g_pos); + + for(int i=0;i<nTps;i++) { + p_frame.col(i) = teleopFrames[i].A.t()*(p-teleopFrames[i].b); + tpTmp.A = teleopFrames[i].A; + tpTmp.b = teleopFrames[i].b; + tp.setTaskParameters(i,tpTmp); + } + // also add the position in absolute space + trParam = ones(2); + p_frame.col(nTps) = p; + + tpdpgmm.addDatapoints(p_frame,trParam,startFlag,endFlag,lambda,minSigma); + tpdpgmm.getTransformedGMM(tp,INVERTIBLE); + + startFlag = false; + modelExist = true; + + if (!ImGui::GetIO().MouseDown[0]){ //Button released + adding_line = false; + model_changed = true; + + if (stateMerging){ + bool merged = true; + while (merged) + { + merged = tpdpgmm.reduceStates(); + tpdpgmm.getTransformedGMM(tp, INVERTIBLE); + tpdpgmm.updateTransition(trParam); + } + }else{ + tpdpgmm.updateTransition(trParam); + } + + Demonstration demo = Demonstration(nVars,pointsV.size()); + for (int t=0; t<(int)pointsV.size(); t++){ + demo.getDatapoints().getData()(0,t) = pointsV[t](0); + demo.getDatapoints().getData()(1,t) = pointsV[t](1); + } + + TPDemonstration tmptpdemo( demo.getDatapoints().getData(), tp); + tpdemos.push_back(tmptpdemo); + + pointsV.clear(); + } + } + } + + if (ImGui::GetIO().KeysDown[GLFW_KEY_D] ){ + cout << "D pressed - Cleaning up." << endl; + tpdemos.clear(); + repros.clear(); + tpdpgmm = TPDPGMM(nVars,1,nTps,2,lambda); + modelExist = false; + nbPts = 0; + } + + if (ImGui::GetIO().KeysDown[GLFW_KEY_S] && modelExist){ + cout << "S pressed - Sampling model." << endl; + repros.clear(); + rData = solveReconstruction(tpdpgmm, tele_g_pos, iFactor, nRecPoints); + repros.push_back(rData); + } + + if (ImGui::GetIO().KeysDown[GLFW_KEY_R] && modelExist){ + cout << "R pressed - Asking remote to sample model." << endl; + sample_model_cmd = true; + } + + if (ImGui::GetIO().KeysDown[GLFW_KEY_T] && modelExist){ + cout << "T pressed - Asking remote to stop MPC." << endl; + stop_mpc_cmd = true; + } + + ImGui::End(); + + //GUI rendering ======================================================================= + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + ImGui::Render(); + + //PbDlib rendering + glPushMatrix(); + glTranslatef(-1.0f,-1.0f,0); + glScalef(2.0f/(float)ImGui::GetIO().DisplaySize.x, 2.0f/(float)ImGui::GetIO().DisplaySize.y, 1.0f); + glLineWidth(2.0f); + + //Draw current demo + drawStrip(pointsV, colBlack, 2.0); + + //Draw all demos + if (dispDemo) { + for (int i=0; i<(int)tpdemos.size(); i++){ + mat tmpStrip = tpdemos[i].getDataInTaskParameters(); + for (int j=0; j<tmpStrip.n_cols; j++) { + tmpStrip.col(j) = tp.getTaskParameters(0).A*tmpStrip.col(j); + } + tmpStrip.each_col() += tp.getTaskParameters(0).b; + drawStrip(tmpStrip, colLightGray, 2.0); + } + } + + //Draw references + if(dispRef) { + glLineWidth(4.0f); + for (int k = 0; k < (int) tpdpgmm.getNumFRAMES(); k++) { + glColor3f(38.0/255.0, 57.0/255.0, 76.0/255.0); + glBegin(GL_LINE_STRIP); + for (int t = 0; t < (int) size(refShape,1); t++) { + vec point = teleopFrames[k].b + teleopFrames[k].A * refShape.col(t); + glVertex2f(point(0),point(1)); + } + glEnd(); + } + glLineWidth(2.0f); + } + + //Draw Gaussians + if (modelExist&&dispGMM){ + drawGaussians(tpdpgmm, teleopFrames, colorCode); + } + + //Draw repros + drawStrip(repros,colBlue,3.0); + + //draw position + drawSquare(tele_g_pos(0), tele_g_pos(1), 10, 2.0, colRed); + + //draw sandbox + drawSquare(260,260,500,1.0,vec3({.7,.7,.7}),0); + + //Draw MPC + drawStrip(trajMPCruns,vec3({0.8,0.8,0.8}),2); + if (TestData.size()){ + drawStrip(TestData,vec3({0,0,0.9}),3.0); + } + if (curPos.size()){ // MPC state + drawSquare(curPos(0),curPos(1),10,1.0,vec3({0,0,1})); + } + + glPopMatrix(); + glfwSwapBuffers(window); + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + + return 0; +} diff --git a/src/demo_tp_multiLqr.cpp b/src/demo_tp_multiLqr.cpp new file mode 100644 index 0000000..a276006 --- /dev/null +++ b/src/demo_tp_multiLqr.cpp @@ -0,0 +1,1278 @@ +/* + * demo_tp_multiLQR.cpp + * + * Online tp-hsmm and tp-gmm with lqr-based trajectory generation + * and multiframe-lqr trajectory generation. + * + * Authors: Sylvain Calinon, Ioannis Havoutis + */ + +#define prt(x) std::cout << #x " = '" << x << "'" << std::endl; +#define prt_msize(x) std::cout << #x ", rows: " << x.n_rows << ", cols: " << x.n_cols << std::endl; + +#include <stdio.h> + +#include "armadillo" +#include <pbdlib/gmm.h> +#include <pbdlib/tpdpgmm.h> + +#include <GLFW/glfw3.h> +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include <pbdlib/gmr.h> +#include <pbdlib/lqr.h> +#include <pbdlib/taskparameters.h> +#include "pbdlib/trajMPC.h" + +using namespace std; +using namespace pbdlib; +using namespace arma; + +class Remap { +public: + Remap(float input_min, float input_max, + float output_min, float output_max) +:_input_min(input_min), _input_max(input_max), + _output_min(output_min), _output_max(output_max){}; + +private: + float _input_min, _input_max, _output_min, _output_max; + +public: + float map( float input ) { + return _output_min + (input - _input_min) * + ((_output_max - _output_min) / (_input_max - _input_min)); + } + + float mapInv( float input ) { + return _input_min + (input - _output_min) * + ((_input_max - _input_min) / (_output_max - _output_min)); + } +}; + +class Ref { +public: + vec p1; + vec p2; + + mat A; + vec b; + + void updateRef() { + b = p1; + A = mat(2,2); + vec delta = p2-p1; + delta = delta/arma::norm(delta); + A(0,0) = delta(0); + A(1,0) = delta(1); + A(0,1) = -delta(1); + A(1,1) = delta(0); + } +}; + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +void drawStrip(mat points, vec3 color, float linewidth); +void drawStrip(vector<mat> points, vec3 color, float linewidth); +void drawStrip(ImVector<ImVec2> &points, vec3 color, float linewidth); +void drawGaussians(TPDPGMM &tpgmm, Ref refFrame[], mat colorM); +void drawGaussians(TPGMM &tpgmm, Ref refFrame[], mat colorM); + +void drawProdGaussians(TPDPGMM &tpgmm, vec color); +void drawSquare(int pos_x, int pos_y, int square_edge, float lineWidth = 5.0); + +mat solveReconstructionMFtpgmm(TPGMM& tpgmm, TaskParameters& tp, + vec startPoint, int iFactor, int nRecPoints) +//Batch solution of a lqr acting in multiple frames, vanilla tpgmm version +{ + int nbVarPos = 2; + int nbData = nRecPoints; + prt(nRecPoints); + int nbVar = tpgmm.getNumVARS(); +// prt(nbVar); + + mat A(4,4), B(4,2); + float dt = 0.01f; + + //Dynamical System settings (discrete version), see Eq. (33) + mat A1d; A1d << 1 << dt << endr << 0 << 1 << endr; + mat B1d; B1d << 0 << endr << dt << endr; + A = kron(A1d, eye(nbVarPos,nbVarPos)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + B = kron(B1d, eye(nbVarPos,nbVarPos)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + + //Control cost matrix + mat R = eye(nbVarPos,nbVarPos) * pow(10.0,iFactor); + R = kron(eye(nbData-1,nbData-1),R); + + //Construct Su and Sx matrices, see Eq. (35) + mat Su = zeros(nbVar*nbData, nbVarPos*(nbData-1)); + mat Sx = kron(ones(nbData,1), eye(nbVar,nbVar)); + mat M = B; + + for (uint n=2; n<nbData+1; n++) { + // Build Sx matrix + Sx.rows((n-1)*nbVar, nbData*nbVar - 1) + = Sx.rows((n-1)*nbVar, nbData*nbVar - 1) * A; + // Build Su matrix + Su(span((n-1)*nbVar, (n*nbVar) - 1), span(0, ((n-1)*nbVarPos) - 1)) = M; + M = join_horiz( A * M.cols(0,nbVarPos-1), M); + } + + uint nbFrames = tp.getNumTASKPARAMETERS(); + uint nbStates = tpgmm.getNumSTATES(); +// prt(nbFrames); +// prt(nbStates); + + //GMM projection, see Eq. (5) + vector<GMM_Model> p_gmm; + for (uint i = 0; i < nbFrames; ++i){ + p_gmm.push_back(GMM_Model(nbStates,nbVar)); + } + + for (uint i = 0; i < nbStates; ++i) { + for (uint m = 0; m < nbFrames; ++m){ + p_gmm[m].setMU(i, tp.getTaskParameters(m).A * tpgmm.getGMMS(m).getMU(i) + + tp.getTaskParameters(m).b); + p_gmm[m].setSIGMA(i, tp.getTaskParameters(m).A * tpgmm.getGMMS(m).getSIGMA(i) * tp.getTaskParameters(m).A.t()); + } + } + + +// get state path from first demo + mat h = tpgmm.getGAMMA2(); +prt_msize(h); + + mat pred = h; + uword imax[nRecPoints]; + + for (int t=0; t<nRecPoints; t++){ + vec vTmp = pred.col(t); + vTmp.max(imax[t]); + cout<<imax[t]<<"-"; + } + cout<<endl<<endl; + + vector<mat> MuQ, SigmaQ; + //Build a reference trajectory for each frame, see Eq. (27) + mat invSigmaQ = zeros(nbVar*nbData, nbVar*nbData); + for (uint m=0; m<nbFrames; m++){ + mat mtemp(nbData*nbVar,1); + for (int j = 0; j < nRecPoints; ++j) { +// mtemp = join_vert(mtemp, p_gmm[m].getMU( imax[j] )); + mtemp.submat(j*nbVar, 0, ((j+1)*nbVar)-1, 0) = p_gmm[m].getMU( imax[j] ); + } +// prt_msize(mtemp); + MuQ.push_back(mtemp); + mat ctemp (nbVar, nbData*nbVar); + for (int j = 0; j < nRecPoints; ++j) { +// ctemp = join_horiz(ctemp, p_gmm[m].getSIGMA( imax[j] )); + ctemp.submat(0, j*nbVar, nbVar-1, ( (j+1)*nbVar)-1 ) = p_gmm[m].getSIGMA( imax[j] ); + } +// prt_msize(ctemp); + mat tA,tB,tC; + tA = kron(ones(nbData,1), eye(nbVar,nbVar)); + tB = ctemp; + tC = kron(eye(nbData,nbData), ones(nbVar,nbVar)); + SigmaQ.push_back( (tA * tB) % tC ); + invSigmaQ = invSigmaQ + inv(SigmaQ.back()); + } + + //%Batch LQR (unconstrained linear MPC), see Eq. (37) + mat SuInvSigmaQ = Su.t() * invSigmaQ; + mat Rq = SuInvSigmaQ * Su + R; + colvec X(startPoint); + mat rq = zeros(nbVar*nbData,1); + for (uint m = 0; m<nbFrames; m++) { + rq = rq + solve(SigmaQ[m], MuQ[m] - Sx*X); + } + rq = Su.t() * rq; + mat u = solve(Rq, rq); + + mat Data = reshape(Sx*X+Su*u, nbVar, nbData); + +// prt_msize(Data); + + return Data.rows(0,1); +} + +mat solveReconstructionMF(TPDPGMM& tpgmm, TaskParameters& tp, + vec startPoint,float iFactor, int nRecPoints) +//Batch solution of a lqr acting in multiple frames, +{ + int nbVarPos = 2; + int nbData = nRecPoints; + int nbVar = tpgmm.getNumVARS(); +// prt(nbVar); + + mat A(4,4), B(4,2); + float dt = 0.01f; + + //Dynamical System settings (discrete version), see Eq. (33) + mat A1d; A1d << 1 << dt << endr << 0 << 1 << endr; + mat B1d; B1d << 0 << endr << dt << endr; + A = kron(A1d, eye(nbVarPos,nbVarPos)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + B = kron(B1d, eye(nbVarPos,nbVarPos)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + + //Control cost matrix + mat R = eye(nbVarPos,nbVarPos) * pow(10.0f,iFactor); + R = kron(eye(nbData-1,nbData-1),R); + + //Construct Su and Sx matrices, see Eq. (35) + mat Su = zeros(nbVar*nbData, nbVarPos*(nbData-1)); + mat Sx = kron(ones(nbData,1), eye(nbVar,nbVar)); + mat M = B; + + for (uint n=2; n<nbData+1; n++) { + // Build Sx matrix + Sx.rows((n-1)*nbVar, nbData*nbVar - 1) + = Sx.rows((n-1)*nbVar, nbData*nbVar - 1) * A; + // Build Su matrix + Su(span((n-1)*nbVar, (n*nbVar) - 1), span(0, ((n-1)*nbVarPos) - 1)) = M; + M = join_horiz( A * M.cols(0,nbVarPos-1), M); + } + + uint nbFrames = tp.getNumTASKPARAMETERS(); + uint nbStates = tpgmm.getNumSTATES(); +// prt(nbFrames); +// prt(nbStates); + + //GMM projection, see Eq. (5) + vector<GMM_Model> p_gmm; + for (uint i = 0; i < nbFrames; ++i){ + p_gmm.push_back(GMM_Model(nbStates,nbVar)); + } + + for (uint i = 0; i < nbStates; ++i) { + for (uint m = 0; m < nbFrames; ++m){ + p_gmm[m].setMU(i, tp.getTaskParameters(m).A * tpgmm.getGMMS(m).getMU(i) + + tp.getTaskParameters(m).b); + p_gmm[m].setSIGMA(i, tp.getTaskParameters(m).A * tpgmm.getGMMS(m).getSIGMA(i) * tp.getTaskParameters(m).A.t()); + } + } + + // +// std::vector<mat> Q; +// + //get most probable state + colvec p(startPoint); + mat h_i(tpgmm.getProdGMM()->getNumSTATES(), 1); + for (int i=0; i<(int)tpgmm.getProdGMM()->getNumSTATES(); i++){ + h_i.row(i) = trans(tpgmm.getProdGMM()->getCOMPONENTS(i).getPDFValue(p)); + } + uword start_state; + h_i.max(start_state); + // cout << "ss :" << start_state << endl; + + mat pred; + pred = tpgmm.predictForwardVariable(nRecPoints,start_state); + + // cout << "Alpha Predictions" << endl << pred.t() << endl; + + uword imax[nRecPoints]; + + for (int t=0; t<nRecPoints; t++){ + vec vTmp = pred.col(t); + vTmp.max(imax[t]); +// cout<<imax[t]<<"-"; + } +// cout<<endl<<endl; + + vector<mat> MuQ, SigmaQ; + //Build a reference trajectory for each frame, see Eq. (27) + mat invSigmaQ = zeros(nbVar*nbData, nbVar*nbData); + for (uint m=0; m<nbFrames; m++){ + mat mtemp(nbData*nbVar,1); + for (int j = 0; j < nRecPoints; ++j) { +// mtemp = join_vert(mtemp, p_gmm[m].getMU( imax[j] )); + mtemp.submat(j*nbVar, 0, ((j+1)*nbVar)-1, 0) = p_gmm[m].getMU( imax[j] ); + } +// prt_msize(mtemp); + MuQ.push_back(mtemp); + mat ctemp (nbVar, nbData*nbVar); + for (int j = 0; j < nRecPoints; ++j) { +// ctemp = join_horiz(ctemp, p_gmm[m].getSIGMA( imax[j] )); + ctemp.submat(0, j*nbVar, nbVar-1, ( (j+1)*nbVar)-1 ) = p_gmm[m].getSIGMA( imax[j] ); + } +// prt_msize(ctemp); + mat tA,tB,tC; + tA = kron(ones(nbData,1), eye(nbVar,nbVar)); + tB = ctemp; + tC = kron(eye(nbData,nbData), ones(nbVar,nbVar)); + SigmaQ.push_back( (tA * tB) % tC ); + invSigmaQ = invSigmaQ + inv(SigmaQ.back()); + } + + //%Batch LQR (unconstrained linear MPC), see Eq. (37) + mat SuInvSigmaQ = Su.t() * invSigmaQ; + mat Rq = SuInvSigmaQ * Su + R; + colvec X(startPoint); + mat rq = zeros(nbVar*nbData,1); + for (uint m = 0; m<nbFrames; m++) { + rq = rq + solve(SigmaQ[m], MuQ[m] - Sx*X); + } + rq = Su.t() * rq; + mat u = solve(Rq, rq); + + mat Data = reshape(Sx*X+Su*u, nbVar, nbData); + +// prt_msize(Data); + + return Data.rows(0,1); +} + +mat solveReconstruction(TPDPGMM& tpgmm,vec startPoint,float iFactor, int nRecPoints) +{ + if (startPoint.size() != tpgmm.getNumVARS()) + { + prt("Start point size not equal to number of variables"); + prt(startPoint.size()); + prt(tpgmm.getNumVARS()); + startPoint = join_cols(startPoint, zeros<vec>(2)); + } + + mat A(4,4), B(4,2); + float dt = 0.01f; + + mat R = eye(2,2) * pow(10.0f,iFactor); + + mat A1d; A1d << 0 << 1 << endr << 0 << 0 << endr; + mat B1d; B1d << 0 << endr << 1 << endr; + A = kron(A1d, eye(2,2)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + B = kron(B1d, eye(2,2)); //See Eq. (5.1.1) in doc/TechnicalReport.pdf + LQR lqr(A,B,dt); + + std::vector<mat> Q; + + //get most probable state + colvec p(startPoint); + mat h_i(tpgmm.getProdGMM()->getNumSTATES(), 1); + for (int i=0; i<(int)tpgmm.getProdGMM()->getNumSTATES(); i++){ + h_i.row(i) = trans(tpgmm.getProdGMM()->getCOMPONENTS(i).getPDFValue(p)); + } + uword start_state; + h_i.max(start_state); + // cout << "ss :" << start_state << endl; + + mat pred; + pred = tpgmm.predictForwardVariable(nRecPoints,start_state); + + // cout << "Alpha Predictions" << endl << pred.t() << endl; + + uword imax[nRecPoints]; + + prt("solveRec"); + for (int t=0; t<nRecPoints; t++){ + vec vTmp = pred.col(t); + vTmp.max(imax[t]); + cout<<imax[t]<<"-"; + } + cout<<endl<<endl; + + //LQR + vec vTmp(4,fill::zeros); + mat QTmp(4,4,fill::zeros); + mat Target(4,nRecPoints,fill::zeros); + for (int t=0; t<nRecPoints; t++){ + QTmp.submat(0,0, + tpgmm.getNumVARS()-1 , tpgmm.getNumVARS()-1) = + inv(tpgmm.getProdGMM()->getSIGMA(imax[t]).submat(0,0, tpgmm.getNumVARS()-1, tpgmm.getNumVARS()-1)); + Q.push_back(QTmp); + vTmp.subvec(0,tpgmm.getNumVARS()-1) = tpgmm.getProdGMM()->getMU(imax[t]).subvec(0,tpgmm.getNumVARS()-1); + Target.col(t) = vTmp; + } + lqr.setProblem(R,Q,Target); + mat S(4,4,fill::zeros); + vec d(4,fill::zeros); + //lqr.evaluate_gains_finiteHorizon(S,d); + lqr.evaluate_gains_infiniteHorizon(); + + //Retrieve data + + mat rData(2,nRecPoints); + //vec x = demo.getDatapoints().getData().col(0); + //vec dx(2,fill::zeros), ddx(2); + //for (int t=0; t<points.size(); t++){ + //rData.col(t) = x; + //ddx = 100.0f * (Target.submat(0,t,1,t)-x) - sqrtf(2*100.0f) * dx; + //ddx = lqr.getGains().at(t).cols(0,1) * (Target.submat(0,t,1,t)-x) - lqr.getGains().at(t).cols(2,3) * dx; + //ddx += lqr.getFF().at(t); + //dx += ddx * dt; + //x += dx * dt; + //} + + vec u(2); + vec X(4,fill::zeros); + X.subvec(0,tpgmm.getNumVARS()-1) = startPoint.rows(0, tpgmm.getNumVARS()-1 ); + for (int t=0; t<nRecPoints; t++){ + rData.col(t) = X.rows(0,1); + u = lqr.getGains().at(t) * (Target.col(t)-X); + X += (A*X+B*u) * dt; + } + + //Clean up + + Q.clear(); + return rData; +} + +int main(int argc, char **argv){ + + //trajMPC params====================== + // Model Settings: + uint nVarsPos = 2; // Number of position variables + uint nDeriv = 2; // Number of derivatives considered + + // TrajMPC Settings: + int mpc_start_state = 0; + int Np = 70; // Number of predictions + int Nc = 30; // Number of control predictions + int N = 600; // Number of iterations of simulation + float mpc_dt = 0.01; // time step considered + float alpha = 0.001; // control cost variable + + colvec Xinit; + HSMM* myHSMM; + TrajMPC* myTrajMPC; + + mat Ad, Bd; + mat TestData; + colvec U; + colvec curPos = {0.0,0.0}; + bool trajMPCrunning = false; + //================================ + + //reference drawings + mat refShape = { +// {-0.5, 1.5, 0.0, 0.0, 0.0, 0.0}, +// { 0.0, 0.0, 0.0,-0.5, 0.0, 1.0} + {-0.3, -0.3, 0.3, 0.3 }, + {2.0, 0.0 , 0.0, 2.0} + }; + float refScale = 50.0; + refShape = refShape + 10.0 / refScale; + refShape = refScale * refShape; + + //Setup TPDPGMM + float minSigma = 20; //1E2; + float lambda = 100.0f; +// int nRecPoints = 300; + + int nVars = 4;//2; + int N_TPS = 2; + + TPDPGMM tpdpgmm(nVars,1,N_TPS,2,lambda); + + TaskParameters tp(4,N_TPS); + + mat minSIGMA = eye(2,2) * minSigma; + vector<GaussianDistribution> comps; + vector<Demonstration> demos; + vector<mat> repros, MFrepros, vanilla_tpgmm_repros, trajMPCrepros, trajMPCruns; + + //TPgmm + TPGMM* tpgmm_vanilla; + std::vector<TPDemonstration> TPdemos; // Vector to hold demonstrations + int tpgmm_vannila_nStates = 3; + int tpgmm_vannila_rfactor = -5; + + //Setup LQR + float iFactor = -5; + int nRecPoints = 300; +// float dt = 0.01f; //0.033 + +// float filterAlpha = 1.0; + float filterAlphaPos = 0.05; + + bool stateMerging = false; + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(1280, 820, "PbdLib GUI", NULL, NULL); + glfwMakeContextCurrent(window); + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // Setup ImGui binding + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(154, 154, 154); + + ImVector<ImVec2> points, velocities; + bool adding_line = false; + bool modelExist = false; + bool dispRef = true; + bool dispDemo = false; + bool dispGMM = true; + bool useFramePRIORS = false; + bool movingRef = false; + bool hoveringRef = false; + int nbPts = 0; + bool init = true; + bool startFlag = false; + bool endFlag = false; + float alphaHandles = 0.2f; + Ref refFrame[2]; + refFrame[0].p1 = zeros(2); + refFrame[0].p2 = zeros(2); + refFrame[1].p1 = vec(2); + refFrame[1].p2 = vec(2); + + //plotting color + mat colorM = {{0.f,0.6211f,0.8164f}, + {0.9883f,0.4531f,0.f}, + {0.7422f,0.8555f,0.2227f}, + {0.1211f,0.5391f,0.4375f}, + {0.9961f,0.8789f,0.1016f}}; + vec3 colBlack = {0.0, 0.0, 0.0}; + vec3 colRed = {1.0, 0.0, 0.0}; + vec3 colGreen = {0.0, 1.0, 0.0}; + vec3 colBlue = {0.0, 0.0, 1.0}; + vec3 colGray = {0.3f, 0.3f, 0.3f}; + + float currTime, prevTime; + + ImVec2 teleop_pointer_position; + bool communication_live = true; + + while (!glfwWindowShouldClose(window)){ + + // cout << "Time: " << ImGui::GetTime() << endl; + prevTime = currTime; + currTime = ImGui::GetTime(); + + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + hoveringRef = false; + //Control panel GUI + if(init)ImGui::SetNextWindowPos(ImVec2(300,700)); + + ImGui::Begin("r1p1",NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + ImGui::TextColored(ImVec4(1.0,1.0,0.0,1.0), "p1"); + vec tmpPos = refFrame[0].p1; + refFrame[0].p1(0)=ImGui::GetWindowPos().x+15; + refFrame[0].p1(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + tmpPos-=refFrame[0].p1; + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + if(init)ImGui::SetNextWindowPos(ImVec2(400,700)); + ImGui::Begin("r1p2", NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + ImGui::TextColored(ImVec4(1.0,1.0,0.0,1.0), "r1"); + if(!init)ImGui::SetWindowPos(ImVec2(ImGui::GetWindowPos().x-tmpPos(0),ImGui::GetWindowPos().y+tmpPos(1))); + refFrame[0].p2(0)=ImGui::GetWindowPos().x+15; + refFrame[0].p2(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + if(init)ImGui::SetNextWindowPos(ImVec2(400,100)); + ImGui::Begin("r2p1",NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + ImGui::TextColored(ImVec4(1.0,1.0,0.0,1.0), "p2"); + tmpPos = refFrame[1].p1; + refFrame[1].p1(0)=ImGui::GetWindowPos().x+15; + refFrame[1].p1(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + tmpPos-=refFrame[1].p1; + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + if(init)ImGui::SetNextWindowPos(ImVec2(300,100)); + ImGui::Begin("r2p2", NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + ImGui::TextColored(ImVec4(1.0,1.0,0.0,1.0), "r2"); + if(!init)ImGui::SetWindowPos(ImVec2(ImGui::GetWindowPos().x-tmpPos(0),ImGui::GetWindowPos().y+tmpPos(1))); + refFrame[1].p2(0)=ImGui::GetWindowPos().x+15; + refFrame[1].p2(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + refFrame[0].updateRef(); + refFrame[1].updateRef(); + + + int control_panel_height = 300; + int control_panel_width = 400; + + if (init){ + ImGui::SetNextWindowPos(ImVec2( + (ImGui::GetIO().DisplaySize.x - control_panel_width)/2, 2) ); + ImGui::SetNextWindowCollapsed(true); + teleop_pointer_position = ImVec2(ImGui::GetIO().MousePos.x, + ImGui::GetIO().DisplaySize.y - ImGui::GetIO().MousePos.y); + } + + init = false; + + ImGui::Begin("Control Panel", NULL, + ImVec2(control_panel_width,control_panel_height), 1.0f, +// ImGuiWindowFlags_NoTitleBar| +// ImGuiWindowFlags_NoResize| +// ImGuiWindowFlags_NoMove| + ImGuiWindowFlags_NoSavedSettings); + + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + + if (ImGui::Button("Clear")){ + demos.clear(); + repros.clear(); + MFrepros.clear(); + trajMPCrepros.clear(); + tpdpgmm = TPDPGMM(nVars,1,N_TPS,2,lambda); + modelExist = false; + nbPts = 0; + + TestData.clear(); //trajMPC params + curPos.clear(); + trajMPCrunning = false; + trajMPCruns.clear(); + + TPdemos.clear(); + tpgmm_vanilla = NULL; + vanilla_tpgmm_repros.clear(); + } + ImGui::SameLine(); + if (ImGui::Button("re_MF")){ + MFrepros.clear(); + mat MFrData = solveReconstructionMF(tpdpgmm, tp, + tpdpgmm.getProdGMM()->getMU(0), iFactor, nRecPoints); + MFrepros.push_back(MFrData); + } + ImGui::Text("Left-click to collect demonstrations"); + ImGui::Text("Press space-bar to cut communication."); + ImGui::Text("nbDemos: %i, nbPoints: %i, nbStates: %i", (int)demos.size(), + // points.size(), + nbPts, (int)tpdpgmm.getNumSTATES()); + ImGui::SliderFloat("minSigma", &minSigma, 1E1, 20E2); + ImGui::SliderFloat("lambda", &lambda, 10.0f, 200.0f); + + ImGui::Checkbox("Display Demo",&dispDemo);ImGui::SameLine(); + ImGui::Checkbox("Plot Gaussian",&dispGMM);ImGui::SameLine(); + + ImGui::Checkbox("State Merging",&stateMerging); +// ImGui::SliderFloat("Fil. a pos", &filterAlphaPos, 0, 1, "%.2f"); + + ImGui::Separator(); + ImGui::SliderInt("MPC start state", &mpc_start_state, -1, tpdpgmm.getProdGMM()->getNumSTATES()); + ImGui::SliderInt("MPC n pred.", &Np, 1, 100); + ImGui::SliderInt("MPC n control pred.", &Nc, 1, 100); + //ImGui::SliderInt("MPC n sim. itter.", &N, 1, 1000); + ImGui::SliderFloat("MPC time step", &mpc_dt, 0.001, 0.1, "%.3f"); + ImGui::SliderFloat("MPC control cost", &alpha, 0.0001, 0.1, "%.4f"); + + ImGui::Separator(); + ImGui::SliderFloat("rFactor", &iFactor, -10, -0.001, "%.4f"); + ImGui::SliderInt("nRecPoints", &nRecPoints, 10, 1000); + + tpdpgmm.useFramePRIORS(useFramePRIORS); + + //Get data + ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x, + ImGui::GetIO().DisplaySize.y - ImGui::GetIO().MousePos.y); + + ImVec2 mouse_vel_in_canvas; + + if(hoveringRef&&ImGui::GetIO().MouseClicked[0]) + movingRef = true; + if(movingRef&&!ImGui::GetIO().MouseDown[0]) + movingRef = false; + + if(movingRef&&modelExist&& !ImGui::GetIO().MouseClicked[0]) + { + TaskParameter tpTmp; + + for(int i=0;i<N_TPS;i++) + { +// if (nVars == 2) { +// tpTmp.A = refFrame[i].A; +// tpTmp.b = refFrame[i].b; +// }else if (nVars == 4) { + mat a; a << 1 << 0 << endr << 0 << 1 << endr; + tpTmp.A = kron(a, refFrame[i].A); + tpTmp.b = join_cols(refFrame[i].b, zeros(2,1)); + //tpTmp.b = join_cols(refFrame[i].b, refFrame[i].b); + // cout << "Ai" << refFrame[i].A << endl; + // cout << "A" << tpTmp.A << endl; + // cout << "b" << tpTmp.b << endl; +// } + + tp.setTaskParameters(i,tpTmp); + } + + tpdpgmm.getTransformedGMM(tp,INVERTIBLE); + + vec trParam = ones(2); +// trParam = refFrame[1].b-refFrame[0].b; + tpdpgmm.updateTransition(trParam); + + repros.clear(); + + mat rData = solveReconstruction(tpdpgmm,tpdpgmm.getProdGMM()->getMU(0),iFactor,nRecPoints); + repros.push_back(rData); + +// MFrepros.clear(); +// mat MFrData = solveReconstructionMF(tpgmm, tp, +// tpgmm.getProdGMM()->getMU(0), iFactor, nRecPoints); +// MFrepros.push_back(MFrData); + + } + + + if ( +// (ImGui::GetIO().MousePos.x< control_panel_width +2 && +// ImGui::GetIO().MousePos.y< control_panel_height +2)==0 && + !movingRef + && (ImGui::GetIO().MousePos.x < ImGui::GetIO().DisplaySize.x/2.0)){ //Is outside gui? + if (!adding_line && ImGui::GetIO().MouseClicked[0]){ //Button pushed + adding_line = true; +// trajMPCrunning = false; + startFlag = true; + endFlag = false; + if (!modelExist){ + colvec p(nVars, fill::zeros); + p(0) = mouse_pos_in_canvas.x; + p(1) = mouse_pos_in_canvas.y; + GaussianDistribution componentTmp(p,minSIGMA); + comps.push_back(componentTmp); + comps.clear(); + } + } + if (!ImGui::GetIO().MouseDown[0]) endFlag = true; + + if (adding_line){ //Trajectory recording + nbPts++; + vec p(2); + vec v(2); + if ((int)points.size() < 2) { + p(0) = mouse_pos_in_canvas.x; + p(1) = mouse_pos_in_canvas.y; + }else{ + p(0) = points.back().x + filterAlphaPos * + ( mouse_pos_in_canvas.x - points.back().x); + p(1) = points.back().y + filterAlphaPos * + ( mouse_pos_in_canvas.y - points.back().y); + } + + mouse_pos_in_canvas.x = p(0); + mouse_pos_in_canvas.y = p(1); + points.push_back(mouse_pos_in_canvas); + + if ((int)points.size() < 2){ + v(0) = v(1) = 0.0; + } else { +// float timeDt = 0.01;//currTime - prevTime; + float timeDt = currTime - prevTime; +// float timeDt = mpc_dt; + +// if (timeDt == 0.0) +// { +// throw std::invalid_argument("Error: dt = 0."); +// } +// v(0) = velocities.back().x + filterAlpha * +// ( ((p(0) - points[(int)points.size() - 2].x)/timeDt) - +// velocities.back().x); +// v(1) = velocities.back().y + filterAlpha * +// ( ((p(1) - points[(int)points.size() - 2].y)/timeDt) - +// velocities.back().y); + v(0) = (points.back().x - points[(int)points.size() - 2].x)/timeDt; + v(1) = (points.back().y - points[(int)points.size() - 2].y)/timeDt; + } + + mouse_vel_in_canvas.x = v(0); + mouse_vel_in_canvas.y = v(1); + velocities.push_back(mouse_vel_in_canvas); + + mat p_frame(nVars, N_TPS+1); + + TaskParameter tpTmp; + + for(int i=0;i<N_TPS;i++) + { +// if (nVars == 2) { +// p_frame.col(i) = refFrame[i].A.t()*(p-refFrame[i].b); +// tpTmp.A = refFrame[i].A; +// tpTmp.b = refFrame[i].b; +// }else if (nVars == 4) { + p_frame.col(i) = join_cols( refFrame[i].A.t()*(p-refFrame[i].b), + refFrame[i].A.t()*(v) ); +// refFrame[i].A.t()*(v-refFrame[i].b) ); + mat a; a << 1 << 0 << endr << 0 << 1 << endr; + tpTmp.A = kron(a, refFrame[i].A); + tpTmp.b = join_cols(refFrame[i].b, zeros(2,1)); +// tpTmp.b = join_cols(refFrame[i].b, refFrame[i].b); + // cout << "Ai" << refFrame[i].A << endl; + // cout << "A" << tpTmp.A << endl; + // cout << "b" << tpTmp.b << endl; +// } + + tp.setTaskParameters(i,tpTmp); + } + // also add the position in absolute space + + vec trParam; + trParam = ones(2); +// trParam = refFrame[1].b-refFrame[0].b; +// if (nVars == 2) { +// p_frame.col(N_TPS) = p; +// }else if (nVars == 4) { + p_frame.col(N_TPS) = join_cols( p, v); +// } + + tpdpgmm.addDatapoints(p_frame,trParam,startFlag,endFlag,lambda,minSigma); + tpdpgmm.getTransformedGMM(tp,INVERTIBLE); + + startFlag = false; + modelExist = true; + + if (!ImGui::GetIO().MouseDown[0]){ //Button released + adding_line = false; + + if (stateMerging){ + bool merged = true; + while (merged) + { + merged = tpdpgmm.reduceStates(); + tpdpgmm.getTransformedGMM(tp, INVERTIBLE); + tpdpgmm.updateTransition(trParam); + } + }else{ + tpdpgmm.updateTransition(trParam); + } + + //Add demonstration + Demonstration demo = Demonstration(nVars,points.size()); + for (int t=0; t<(int)points.size(); t++){ + demo.getDatapoints().getData()(0,t) = points[t].x; + demo.getDatapoints().getData()(1,t) = points[t].y; +// if (nVars==4){ + demo.getDatapoints().getData()(2,t) = velocities[t].x; + demo.getDatapoints().getData()(3,t) = velocities[t].y; +// } + } + demo.saveInFile("demoMotion.txt"); + demos.push_back(demo); + + // tpgmm vannila data + TPDemonstration tmpTpDemo(demo.getDatapoints().getData(),tp); // Temp variable to push individual demonstrations + TPdemos.push_back(tmpTpDemo); + + //Reconstruction + repros.clear(); + + mat pred = tpdpgmm.predictForwardVariable(1,0); // make sure that vars are set up + + mat rData = solveReconstruction(tpdpgmm,tpdpgmm.getProdGMM()->getMU(0),iFactor,nRecPoints); + repros.push_back(rData); + + MFrepros.clear(); + mat MFrData = solveReconstructionMF(tpdpgmm, tp, + tpdpgmm.getProdGMM()->getMU(0), iFactor, nRecPoints); + MFrepros.push_back(MFrData); + + points.clear(); + velocities.clear(); + } + + } + } + + if (ImGui::GetIO().KeysDown[GLFW_KEY_SPACE] ){ + ImGui::SetNextWindowPos(ImVec2( (ImGui::GetIO().DisplaySize.x / 2) - (164 / 2),400)); + ImGui::Begin("Info", NULL, ImVec2(164,40), 1.0f, + ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize| + ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings); + ImGui::TextColored(ImVec4(1.0,0.0,0.0,1.0), "Communication down!"); + ImGui::End(); + if (communication_live&&modelExist){ + if (TestData.size()){ + trajMPCruns.push_back(TestData); + } +// Xinit = tpgmm.getProdGMM()->getMU(mpc_start_state); + Xinit = vec4({mouse_pos_in_canvas.x, mouse_pos_in_canvas.y, + mouse_vel_in_canvas.x, mouse_vel_in_canvas.y}); +// prt(Xinit); + myHSMM = tpdpgmm.getHSMM(); + double av_state_duration = 0.0; + for (int i = 0; i < myHSMM->getNumSTATES(); ++i) { + av_state_duration += myHSMM->getDurMU(i)(0); +// prt(myHSMM->getDurMU(i)(0)); + } +// prt(av_state_duration); +// prt( (2.0/myHSMM->getNumSTATES()) * av_state_duration); + Np = ceil(1.5*(2.0/myHSMM->getNumSTATES()) * av_state_duration); + myHSMM->setCOMPONENTS(tpdpgmm.getProdGMM()->getCOMPONENTS()); + if (Nc>=Np){Nc = Np;} + myTrajMPC = new TrajMPC(myHSMM,mpc_dt,nVarsPos,nDeriv,Np,Nc,alpha); +// myTrajMPC = new TpTrajMPC(&tpgmm, &tp, +// myHSMM,mpc_dt,nVarsPos,nDeriv,Np,Nc,alpha); + + // Make sure that the TrajMPC model is correclty initialized by resetting it before starting + myTrajMPC->reset(); + curPos = Xinit; + Ad = myTrajMPC->getSystemDynamics(); + Bd = myTrajMPC->getInputDynamics(); + if (mpc_start_state == -1){ + TestData = curPos;}else{ + curPos = myHSMM->getMU(mpc_start_state); + } + trajMPCrunning = true; + prt(endl << tpdpgmm.getHSMM()->getTRANSITION()); + }else{ + // do trajMPC step + if (trajMPCrunning){ + // Make step: + U = myTrajMPC->computeControlCommand(curPos); + // Simulate movement of attractor: + curPos = Ad*curPos + Bd*U; + TestData = join_rows(TestData, curPos); +// prt(myTrajMPC->getq()); + } + } + communication_live = false; + }else{ + communication_live = true; + trajMPCrunning = false; + TestData.clear(); + } + + if (communication_live){ + float kp = 0.50; + teleop_pointer_position.x += + kp*(mouse_pos_in_canvas.x - teleop_pointer_position.x); + teleop_pointer_position.y += + kp*(mouse_pos_in_canvas.y - teleop_pointer_position.y); + }else{ + teleop_pointer_position.x = curPos(0); + teleop_pointer_position.y = curPos(1); + } + + + //=================================================================== +// if (ImGui::Button("trajMPC")){ +// if (TestData.size()){ +// trajMPCruns.push_back(TestData); +// } +// Xinit = tpgmm.getProdGMM()->getMU(mpc_start_state); +// myHSMM = tpgmm.getHSMM(); +// myHSMM->setCOMPONENTS(tpgmm.getProdGMM()->getCOMPONENTS()); +// myTrajMPC = new TrajMPC(myHSMM,mpc_dt,nVarsPos,nDeriv,Np,Nc,alpha); +// // Make sure that the TrajMPC model is correclty initialized by resetting it before starting +// myTrajMPC->reset(); +// curPos = Xinit; +// Ad = myTrajMPC->getSystemDynamics(); +// Bd = myTrajMPC->getInputDynamics(); +// TestData = curPos; +// trajMPCrunning = true; +// } + // do trajMPC step +// if (trajMPCrunning){ +// // Make step: +// U = myTrajMPC->computeControlCommand(curPos); +// // Simulate movement of attractor: +// curPos = Ad*curPos + Bd*U; +// TestData = join_rows(TestData, curPos); +// } + + ImGui::Separator(); +// ImGui::TextColored(ImVec4({0,1,0,1}),"Vanilla TPGMM"); + ImGui::SliderInt("set_nStates", &tpgmm_vannila_nStates, 1, 20); + ImGui::SliderInt("set_Cost", &tpgmm_vannila_rfactor, -10, 0); + + if (ImGui::Button("EM.tpgmm")){ + prt(TPdemos.size()); + if (TPdemos.size()) { + cout << "Tp demos exist ! training ..." << endl; + tpgmm_vanilla = new TPGMM(TPdemos,tpgmm_vannila_nStates); + tpgmm_vanilla->estimateTensorGMM(); + } + }ImGui::SameLine(); + + if (ImGui::Button("tpgmm_sample")){ + if (tpgmm_vanilla == nullptr) { + cout << "No model trained yet!" << endl; + }else{ + cout << "Here we sample the vanilla tpgmm" << endl; + + vanilla_tpgmm_repros.clear(); + mat van_tpgmm_rData = solveReconstructionMFtpgmm(*tpgmm_vanilla, tp, + TPdemos[0].getDataInGlobalSpace().getData().col(0), tpgmm_vannila_rfactor, + TPdemos[0].getDataInGlobalSpace().getData().n_cols ); + vanilla_tpgmm_repros.push_back(van_tpgmm_rData); + } + }ImGui::SameLine(); + + ImGui::End(); + + //Rendering the reproduction side (right)=========================== + glViewport((int)ImGui::GetIO().DisplaySize.x / 2, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + //Scaling to match the imgui rendering + glPushMatrix(); + glTranslatef(-1.0f,-1.0f,0); + glScalef(2.0f/(float)ImGui::GetIO().DisplaySize.x, 2.0f/(float)ImGui::GetIO().DisplaySize.y, 1.0f); + + //Draw the Separating line + glColor3f(0.1f, 0.1f, 0.1f); + glBegin(GL_LINE_STRIP); + glVertex2f(0, 0); + glVertex2f(0, (int)ImGui::GetIO().DisplaySize.y); + glEnd(); + + //Draw current demo + drawStrip(points, colBlack, 2.0); + + //Draw all demos + if (dispDemo) { + for (int n=0; n<(int)demos.size(); n++) { + drawStrip(demos[n].getDatapoints().getData(),colGray,2.0); + } + } + + //Draw references + if(dispRef) { + glLineWidth(4.0f); + for (int k = 0; k < (int) tpdpgmm.getNumFRAMES(); k++) { + glColor3f(colorM(0,0), colorM(0,1), colorM(0,2)); + glBegin(GL_LINE_STRIP); + for (int t = 0; t < (int) size(refShape,1); t++) { + vec point; + point = refFrame[k].b + refFrame[k].A * refShape.col(t); + glVertex2f(point(0),point(1)); + } + glEnd(); + } + glLineWidth(2.0f); + } + + //Draw Gaussians +// if (modelExist&&dispGMM){ +// drawGaussians(tpgmm, refFrame, colorM); +// } + if (modelExist){ + drawProdGaussians(tpdpgmm, colorM.row(4).t()); + } + + if (tpgmm_vanilla != nullptr ) + { + drawGaussians(*tpgmm_vanilla, refFrame, colGreen ); + } + + //Draw MPC + if (TestData.size()){ + drawStrip(TestData,vec3({1,1,1}),3.0); + } +// if (curPos.size()){ +// drawSquare(curPos(0),curPos(1),10); +// } + drawStrip(trajMPCruns,vec3({0.8,0.8,0.8}),2); + + //draw teleop dot + drawSquare(teleop_pointer_position.x,teleop_pointer_position.y,10); + + glPopMatrix(); + + + //GUI rendering ===================================== + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + // glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + // glClear(GL_COLOR_BUFFER_BIT); + ImGui::Render(); + + //PbDlib rendering + glPushMatrix(); + glTranslatef(-1.0f,-1.0f,0); + glScalef(2.0f/(float)ImGui::GetIO().DisplaySize.x, 2.0f/(float)ImGui::GetIO().DisplaySize.y, 1.0f); + glLineWidth(2.0f); + + //Draw current demo + drawStrip(points,colBlack,2.0); + + //Draw all demos + if (dispDemo) { + for (int n=0; n<(int)demos.size(); n++){ + drawStrip(demos[n].getDatapoints().getData(),colGray,2.0); + } + } + + //Draw references + if(dispRef) { + glLineWidth(4.0f); + for (int k = 0; k < (int) tpdpgmm.getNumFRAMES(); k++) { + + glColor3f(colorM(0,0), colorM(0,1), colorM(0,2)); + glBegin(GL_LINE_STRIP); + for (int t = 0; t < (int) size(refShape,1); t++) { + vec point = refFrame[k].b + refFrame[k].A * refShape.col(t); + glVertex2f(point(0),point(1)); + } + glEnd(); + } + glLineWidth(2.0f); + } + + //Draw Gaussians + if (modelExist&&dispGMM){ + drawGaussians(tpdpgmm, refFrame, colorM); + } + // if (modelExist){ + // drawProdGaussians(tpgmm, colorM.row(4).t()); + // } + + //Draw repros + drawStrip(repros,colorM.row(3).t(),5.0); + + drawStrip(MFrepros,colBlue,5.0); + + drawStrip(vanilla_tpgmm_repros, colGreen, 5.0); + //Draw MPC +// if (TestData.size()){ +// drawStrip(TestData,vec3({1,1,1}),3.0); +// } +// if (curPos.size()){ +// drawSquare(curPos(0),curPos(1),10); +// } + + glPopMatrix(); + glfwSwapBuffers(window); + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + + return 0; +} + + +void drawStrip(mat points, vec3 color, float linewidth){ + glLineWidth(linewidth); + glColor3f(color[0], color[1], color[2]); + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)points.n_cols; t++){ + glVertex2f(points(0,t), points(1,t)); + } + glEnd(); +} + +void drawStrip(vector<mat> points, vec3 color, float linewidth){ + for (int n=0; n<(int)points.size(); n++){ + drawStrip(points[n],color,linewidth); + } +} + +void drawStrip(ImVector<ImVec2> &points, vec3 color, float linewidth){ + glLineWidth(linewidth); + glColor3f(color[0], color[1], color[2]); + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)points.size(); t++){ + glVertex2f(points[t].x, points[t].y); + } + glEnd(); +} + +void drawGaussians(TPDPGMM &tpgmm, Ref refFrame[], mat colorM){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glLineWidth(2.0f); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++) { + for (int k = 0; k < (int) tpgmm.getNumFRAMES(); k++) { + + eig_sym(d, V, tpgmm.getGMMS(k).getSIGMA(i).rows(0,1).cols(0,1)); + R = refFrame[k].A*(V * sqrt(diagmat(d))); + pts = R * pts0; + + glColor3f(colorM(k+1,0), colorM(k+1,1), colorM(k+1,2)); + glBegin(GL_LINE_STRIP); + + vec refMU = refFrame[k].b + refFrame[k].A*tpgmm.getGMMS(k).getMU(i).rows(0,1); + + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f((pts(0, t) + refMU(0)), (pts(1, t) +refMU(1))); + } + glEnd(); + glBegin(GL_POINTS); + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f(tpgmm.getGMMS(k).getMU(i)(0), + tpgmm.getGMMS(k).getMU(i)(1)); + } + glEnd(); + } + } +} + +void drawGaussians(TPGMM &tpgmm, Ref refFrame[], mat colorM){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glLineWidth(2.0f); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++) { + for (int k = 0; k < (int) tpgmm.getNumFRAMES(); k++) { + + eig_sym(d, V, tpgmm.getGMMS(k).getSIGMA(i).rows(0,1).cols(0,1)); + R = refFrame[k].A*(V * sqrt(diagmat(d))); + pts = R * pts0; + +// glColor3f(colorM(0), colorM(1), colorM(2)); + if (k==0){glColor3f(1.0, 0.0, 0.0);} + if (k==1){glColor3f(0.0, 0.0, 1.0);} + glBegin(GL_LINE_STRIP); + + vec refMU = refFrame[k].b + refFrame[k].A*tpgmm.getGMMS(k).getMU(i).rows(0,1); + + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f((pts(0, t) + refMU(0)), (pts(1, t) +refMU(1))); + } + glEnd(); + glBegin(GL_POINTS); + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f(tpgmm.getGMMS(k).getMU(i)(0), + tpgmm.getGMMS(k).getMU(i)(1)); + } + glEnd(); + } + } +} + +void drawProdGaussians(TPDPGMM &tpgmm, vec color){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glColor3f(color(0), color(1), color(2)); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++){ + eig_sym(d, V, tpgmm.getProdGMM()->getSIGMA(i).rows(0,1).cols(0,1)); + R = V * sqrt(diagmat(d)); + pts = R * pts0; + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f((pts(0,t)+tpgmm.getProdGMM()->getMU(i)(0)), + (pts(1,t)+tpgmm.getProdGMM()->getMU(i)(1))); + } + glEnd(); + glBegin(GL_POINTS); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f(tpgmm.getProdGMM()->getMU(i)(0), + tpgmm.getProdGMM()->getMU(i)(1)); + } + glEnd(); + } +} + + void drawSquare(int pos_x, int pos_y, int square_edge, float lineWidth){ + glLineWidth(lineWidth); + glBegin( GL_QUADS ); + glColor3f( 0.8f, 0.2f, 0.2f ); + int dot_w = square_edge/2; + glVertex2f( pos_x - dot_w, pos_y - dot_w); + glVertex2f( pos_x - dot_w, pos_y + dot_w); + glVertex2f( pos_x + dot_w, pos_y + dot_w); + glVertex2f( pos_x + dot_w, pos_y - dot_w); + glEnd(); + } + + diff --git a/src/demo_tp_trajMpc.cpp b/src/demo_tp_trajMpc.cpp new file mode 100644 index 0000000..03fe4e0 --- /dev/null +++ b/src/demo_tp_trajMpc.cpp @@ -0,0 +1,828 @@ +/* + * demo_tp_trajMPC.cpp + * + * Online tp-hsmm learning and trajMPC-based trajectory generation when + * communication is cut. + * + * Authors: Sylvain Calinon, Ioannis Havoutis + */ + +#define prt(x) std::cout << #x " = '" << x << "'" << std::endl; + +#include <stdio.h> + +#include "armadillo" +#include <pbdlib/gmm.h> +#include <pbdlib/tpdpgmm.h> + +#include <GLFW/glfw3.h> +#include <imgui.h> +#include "imgui_impl_glfw.h" +#include <pbdlib/gmr.h> +#include <pbdlib/lqr.h> +#include <pbdlib/taskparameters.h> +#include "pbdlib/trajMPC.h" +#include "pbdlib/tptrajMPC.h" + +using namespace std; +using namespace pbdlib; +using namespace arma; + +class Remap { +public: + Remap(float input_min, float input_max, + float output_min, float output_max) +:_input_min(input_min), _input_max(input_max), + _output_min(output_min), _output_max(output_max){}; + +private: + float _input_min, _input_max, _output_min, _output_max; + +public: + float map( float input ) { + return _output_min + (input - _input_min) * + ((_output_max - _output_min) / (_input_max - _input_min)); + } + + float mapInv( float input ) { + return _input_min + (input - _output_min) * + ((_input_max - _input_min) / (_output_max - _output_min)); + } +}; + +class Ref { +public: + vec p1; + vec p2; + + mat A; + vec b; + + void updateRef() { + b = p1; + A = mat(2,2); + vec delta = p2-p1; + delta = delta/arma::norm(delta); + A(0,0) = delta(0); + A(1,0) = delta(1); + A(0,1) = -delta(1); + A(1,1) = delta(0); + } +}; + +static void error_callback(int error, const char* description){ + fprintf(stderr, "Error %d: %s\n", error, description); +} + +void drawStrip(mat points, vec3 color, float linewidth); +void drawStrip(vector<mat> points, vec3 color, float linewidth); +void drawStrip(ImVector<ImVec2> &points, vec3 color, float linewidth); +void drawGaussians(TPDPGMM &tpgmm, Ref refFrame[], mat colorM); +void drawProdGaussians(TPDPGMM &tpgmm, vec color); +void drawSquare(int pos_x, int pos_y, int square_edge, float lineWidth = 5.0); + + +int main(int argc, char **argv){ + + //trajMPC params====================== + // Model Settings: + uint nVarsPos = 2; // Number of position variables + uint nDeriv = 2; // Number of derivatives considered + + // TrajMPC Settings: + int mpc_start_state = 0; + int Np = 70; // Number of predictions + int Nc = 30; // Number of control predictions + int N = 600; // Number of iterations of simulation + float mpc_dt = 0.01; // time step considered + float alpha = 0.001; // control cost variable + + colvec Xinit; + HSMM* myHSMM; + TrajMPC* myTrajMPC; +// TpTrajMPC* myTrajMPC; + + mat Ad, Bd; + mat TestData; + colvec U; + colvec curPos = {0.0,0.0}; + bool trajMPCrunning = false; + //================================ + + //reference drawings + mat refShape = { +// {-0.5, 1.5, 0.0, 0.0, 0.0, 0.0}, +// { 0.0, 0.0, 0.0,-0.5, 0.0, 1.0} + {-0.3, -0.3, 0.3, 0.3 }, + {2.0, 0.0 , 0.0, 2.0} + }; + float refScale = 50.0; + refShape = refShape + 10.0 / refScale; + refShape = refScale * refShape; + + //Setup TPDPGMM + float minSigma = 20; //1E2; + float lambda = 100.0f; +// int nRecPoints = 300; + + int nVars = 4;//2; + int N_TPS = 2; + + TPDPGMM tpgmm(nVars,1,N_TPS,2,lambda); + + TaskParameters tp(2,N_TPS); + + mat minSIGMA = eye(2,2) * minSigma; + vector<GaussianDistribution> comps; + vector<Demonstration> demos; + vector<mat> repros, trajMPCrepros, trajMPCruns; + + //Setup LQR +// float dt = 0.01f; //0.033 + + float filterAlpha = 1.0; + float filterAlphaPos = 0.1; + + bool stateMerging = false; + + //Setup GUI + glfwSetErrorCallback(error_callback); + if (!glfwInit()) + exit(1); + GLFWwindow* window = glfwCreateWindow(1280, 820, "PbdLib GUI", NULL, NULL); + glfwMakeContextCurrent(window); + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // Setup ImGui binding + ImGui_ImplGlfw_Init(window, true); + ImVec4 clear_color = ImColor(154, 154, 154); + + ImVector<ImVec2> points, velocities; + bool adding_line = false; + bool modelExist = false; + bool dispRef = true; + bool dispDemo = false; + bool dispGMM = true; + bool useFramePRIORS = false; + bool movingRef = false; + bool hoveringRef = false; + int nbPts = 0; + bool init = true; + bool startFlag = false; + bool endFlag = false; + float alphaHandles = 0.2f; + Ref refFrame[2]; + refFrame[0].p1 = zeros(2); + refFrame[0].p2 = zeros(2); + refFrame[1].p1 = vec(2); + refFrame[1].p2 = vec(2); + + //plotting color + mat colorM = {{0.f,0.6211f,0.8164f}, + {0.9883f,0.4531f,0.f}, + {0.7422f,0.8555f,0.2227f}, + {0.1211f,0.5391f,0.4375f}, + {0.9961f,0.8789f,0.1016f}}; + vec3 colBlack = {0.0, 0.0, 0.0}; + vec3 colRed = {1.0, 0.0, 0.0}; + vec3 colGreen = {0.0, 1.0, 0.0}; + vec3 colBlue = {0.0, 0.0, 1.0}; + vec3 colGray = {0.3f, 0.3f, 0.3f}; + + float currTime, prevTime; + + Remap mapper(ImGui::GetIO().DisplaySize.x, ImGui::GetIO().DisplaySize.y, + -1, 1); // map to (-1,1) + + ImVec2 teleop_pointer_position; + bool communication_live = true; + + while (!glfwWindowShouldClose(window)){ + + // cout << "Time: " << ImGui::GetTime() << endl; + prevTime = currTime; + currTime = ImGui::GetTime(); + + glfwPollEvents(); + ImGui_ImplGlfw_NewFrame(); + hoveringRef = false; + //Control panel GUI + if(init)ImGui::SetNextWindowPos(ImVec2(300,700)); + + ImGui::Begin("r1p1",NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + ImGui::TextColored(ImVec4(1.0,1.0,0.0,1.0), "p1"); + vec tmpPos = refFrame[0].p1; + refFrame[0].p1(0)=ImGui::GetWindowPos().x+15; + refFrame[0].p1(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + tmpPos-=refFrame[0].p1; + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + if(init)ImGui::SetNextWindowPos(ImVec2(400,700)); + ImGui::Begin("r1p2", NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + ImGui::TextColored(ImVec4(1.0,1.0,0.0,1.0), "r1"); + if(!init)ImGui::SetWindowPos(ImVec2(ImGui::GetWindowPos().x-tmpPos(0),ImGui::GetWindowPos().y+tmpPos(1))); + refFrame[0].p2(0)=ImGui::GetWindowPos().x+15; + refFrame[0].p2(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + if(init)ImGui::SetNextWindowPos(ImVec2(400,100)); + ImGui::Begin("r2p1",NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + ImGui::TextColored(ImVec4(1.0,1.0,0.0,1.0), "p2"); + tmpPos = refFrame[1].p1; + refFrame[1].p1(0)=ImGui::GetWindowPos().x+15; + refFrame[1].p1(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + tmpPos-=refFrame[1].p1; + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + if(init)ImGui::SetNextWindowPos(ImVec2(300,100)); + ImGui::Begin("r2p2", NULL, ImVec2(5,5), alphaHandles,ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize); + ImGui::TextColored(ImVec4(1.0,1.0,0.0,1.0), "r2"); + if(!init)ImGui::SetWindowPos(ImVec2(ImGui::GetWindowPos().x-tmpPos(0),ImGui::GetWindowPos().y+tmpPos(1))); + refFrame[1].p2(0)=ImGui::GetWindowPos().x+15; + refFrame[1].p2(1)=ImGui::GetIO().DisplaySize.y -ImGui::GetWindowPos().y-15; + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + ImGui::End(); + + refFrame[0].updateRef(); + refFrame[1].updateRef(); + + + int control_panel_height = 300; + int control_panel_width = 400; + + if (init){ + ImGui::SetNextWindowPos(ImVec2( + (ImGui::GetIO().DisplaySize.x - control_panel_width)/2, 2) ); + ImGui::SetNextWindowCollapsed(true); + teleop_pointer_position = ImVec2(ImGui::GetIO().MousePos.x, + ImGui::GetIO().DisplaySize.y - ImGui::GetIO().MousePos.y); + } + + init = false; + + ImGui::Begin("Control Panel", NULL, + ImVec2(control_panel_width,control_panel_height), 1.0f, +// ImGuiWindowFlags_NoTitleBar| +// ImGuiWindowFlags_NoResize| +// ImGuiWindowFlags_NoMove| + ImGuiWindowFlags_NoSavedSettings); + + hoveringRef = ImGui::IsMouseHoveringWindow()||hoveringRef ; + + if (ImGui::Button("Clear")){ + demos.clear(); + repros.clear(); + trajMPCrepros.clear(); + tpgmm = TPDPGMM(nVars,1,N_TPS,2,lambda); + modelExist = false; + nbPts = 0; + + TestData.clear(); //trajMPC params + curPos.clear(); + trajMPCrunning = false; + trajMPCruns.clear(); + } + ImGui::Text("Left-click to collect demonstrations"); + ImGui::Text("Press space-bar to cut communication."); + ImGui::Text("nbDemos: %i, nbPoints: %i, nbStates: %i", (int)demos.size(), + // points.size(), + nbPts, (int)tpgmm.getNumSTATES()); + ImGui::SliderFloat("minSigma", &minSigma, 1E1, 20E2); + ImGui::SliderFloat("lambda", &lambda, 10.0f, 200.0f); + + ImGui::Checkbox("Display Demo",&dispDemo);ImGui::SameLine(); + ImGui::Checkbox("Plot Gaussian",&dispGMM);ImGui::SameLine(); + + ImGui::Checkbox("State Merging",&stateMerging); +// ImGui::SliderFloat("Fil. a pos", &filterAlphaPos, 0, 1, "%.2f"); + + ImGui::Separator(); + ImGui::SliderInt("MPC start state", &mpc_start_state, -1, tpgmm.getProdGMM()->getNumSTATES()); + ImGui::SliderInt("MPC n pred.", &Np, 1, 100); + ImGui::SliderInt("MPC n control pred.", &Nc, 1, 100); + //ImGui::SliderInt("MPC n sim. itter.", &N, 1, 1000); + ImGui::SliderFloat("MPC time step", &mpc_dt, 0.001, 0.1, "%.3f"); + ImGui::SliderFloat("MPC control cost", &alpha, 0.0001, 0.1, "%.4f"); + + tpgmm.useFramePRIORS(useFramePRIORS); + + //Get data + ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x, + ImGui::GetIO().DisplaySize.y - ImGui::GetIO().MousePos.y); + + ImVec2 mouse_vel_in_canvas; + + if(hoveringRef&&ImGui::GetIO().MouseClicked[0]) + movingRef = true; + if(movingRef&&!ImGui::GetIO().MouseDown[0]) + movingRef = false; + + if(movingRef&&modelExist&& !ImGui::GetIO().MouseClicked[0]) + { + TaskParameter tpTmp; + + for(int i=0;i<N_TPS;i++) + { + if (nVars == 2) { + tpTmp.A = refFrame[i].A; + tpTmp.b = refFrame[i].b; + }else if (nVars == 4) { + mat a; a << 1 << 0 << endr << 0 << 1 << endr; + tpTmp.A = kron(a, refFrame[i].A); + tpTmp.b = join_cols(refFrame[i].b, zeros(2,1)); + //tpTmp.b = join_cols(refFrame[i].b, refFrame[i].b); + // cout << "Ai" << refFrame[i].A << endl; + // cout << "A" << tpTmp.A << endl; + // cout << "b" << tpTmp.b << endl; + } + + tp.setTaskParameters(i,tpTmp); + } + + tpgmm.getTransformedGMM(tp,INVERTIBLE); + + vec trParam = ones(2); +// trParam = refFrame[1].b-refFrame[0].b; + tpgmm.updateTransition(trParam); + + repros.clear(); + + } + + + if ( +// (ImGui::GetIO().MousePos.x< control_panel_width +2 && +// ImGui::GetIO().MousePos.y< control_panel_height +2)==0 && + !movingRef + && (ImGui::GetIO().MousePos.x < ImGui::GetIO().DisplaySize.x/2.0)){ //Is outside gui? + if (!adding_line && ImGui::GetIO().MouseClicked[0]){ //Button pushed + adding_line = true; +// trajMPCrunning = false; + startFlag = true; + endFlag = false; + if (!modelExist){ + colvec p(nVars, fill::zeros); + p(0) = mouse_pos_in_canvas.x; + p(1) = mouse_pos_in_canvas.y; + GaussianDistribution componentTmp(p,minSIGMA); + comps.push_back(componentTmp); + comps.clear(); + } + } + if (!ImGui::GetIO().MouseDown[0]) endFlag = true; + + if (adding_line){ //Trajectory recording + nbPts++; + vec p(2); + vec v(2); + if ((int)points.size() < 2) { + p(0) = mouse_pos_in_canvas.x; + p(1) = mouse_pos_in_canvas.y; + }else{ + p(0) = points.back().x + filterAlphaPos * + ( mouse_pos_in_canvas.x - points.back().x); + p(1) = points.back().y + filterAlphaPos * + ( mouse_pos_in_canvas.y - points.back().y); + } + + mouse_pos_in_canvas.x = p(0); + mouse_pos_in_canvas.y = p(1); + points.push_back(mouse_pos_in_canvas); + + if ((int)points.size() < 2){ + v(0) = v(1) = 0.0; + } else { + float timeDt = currTime - prevTime; +// float timeDt = mpc_dt; + + if (timeDt == 0.0) + { + throw std::invalid_argument("Error: dt = 0."); + } + v(0) = velocities.back().x + filterAlpha * + ( ((p(0) - points[(int)points.size() - 2].x)/timeDt) - + velocities.back().x); + v(1) = velocities.back().y + filterAlpha * + ( ((p(1) - points[(int)points.size() - 2].y)/timeDt) - + velocities.back().y); + } + + mouse_vel_in_canvas.x = v(0); + mouse_vel_in_canvas.y = v(1); + velocities.push_back(mouse_vel_in_canvas); + + mat p_frame(nVars, N_TPS+1); + + TaskParameter tpTmp; + + for(int i=0;i<N_TPS;i++) + { + if (nVars == 2) { + p_frame.col(i) = refFrame[i].A.t()*(p-refFrame[i].b); + tpTmp.A = refFrame[i].A; + tpTmp.b = refFrame[i].b; + }else if (nVars == 4) { + p_frame.col(i) = join_cols( refFrame[i].A.t()*(p-refFrame[i].b), + refFrame[i].A.t()*(v) ); +// refFrame[i].A.t()*(v-refFrame[i].b) ); + mat a; a << 1 << 0 << endr << 0 << 1 << endr; + tpTmp.A = kron(a, refFrame[i].A); + tpTmp.b = join_cols(refFrame[i].b, zeros(2,1)); +// tpTmp.b = join_cols(refFrame[i].b, refFrame[i].b); + // cout << "Ai" << refFrame[i].A << endl; + // cout << "A" << tpTmp.A << endl; + // cout << "b" << tpTmp.b << endl; + } + + tp.setTaskParameters(i,tpTmp); + } + // also add the position in absolute space + + vec trParam; + trParam = ones(2); +// trParam = refFrame[1].b-refFrame[0].b; + if (nVars == 2) { + p_frame.col(N_TPS) = p; + }else if (nVars == 4) { + p_frame.col(N_TPS) = join_cols( p, v); + } + + tpgmm.addDatapoints(p_frame,trParam,startFlag,endFlag,lambda,minSigma); + tpgmm.getTransformedGMM(tp,INVERTIBLE); + + startFlag = false; + modelExist = true; + + if (!ImGui::GetIO().MouseDown[0]){ //Button released + adding_line = false; + + if (stateMerging){ + bool merged = true; + while (merged) + { + merged = tpgmm.reduceStates(); + tpgmm.getTransformedGMM(tp, INVERTIBLE); + tpgmm.updateTransition(trParam); + } + }else{ + tpgmm.updateTransition(trParam); + } + + //Add demonstration + Demonstration demo = Demonstration(nVars,points.size()); + for (int t=0; t<(int)points.size(); t++){ + demo.getDatapoints().getData()(0,t) = points[t].x; + demo.getDatapoints().getData()(1,t) = points[t].y; + if (nVars==4){ + demo.getDatapoints().getData()(2,t) = velocities[t].x; + demo.getDatapoints().getData()(3,t) = velocities[t].y; + } + } + // demo.saveInFile("demoMotion.txt"); + demos.push_back(demo); + + //Reconstruction + repros.clear(); + + mat pred = tpgmm.predictForwardVariable(1,0); // make sure that vars are set up + + points.clear(); + velocities.clear(); + } + + } + } + + if (ImGui::GetIO().KeysDown[GLFW_KEY_SPACE] ){ + ImGui::SetNextWindowPos(ImVec2( (ImGui::GetIO().DisplaySize.x / 2) - (164 / 2),400)); + ImGui::Begin("Info", NULL, ImVec2(164,40), 1.0f, + ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize| + ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings); + ImGui::TextColored(ImVec4(1.0,0.0,0.0,1.0), "Communication down!"); + ImGui::End(); + if (communication_live&&modelExist){ + if (TestData.size()){ + trajMPCruns.push_back(TestData); + } +// Xinit = tpgmm.getProdGMM()->getMU(mpc_start_state); + Xinit = vec4({mouse_pos_in_canvas.x, mouse_pos_in_canvas.y, + mouse_vel_in_canvas.x, mouse_vel_in_canvas.y}); +// prt(Xinit); + myHSMM = tpgmm.getHSMM(); + double av_state_duration = 0.0; + for (int i = 0; i < myHSMM->getNumSTATES(); ++i) { + av_state_duration += myHSMM->getDurMU(i)(0); +// prt(myHSMM->getDurMU(i)(0)); + } +// prt(av_state_duration); +// prt( (2.0/myHSMM->getNumSTATES()) * av_state_duration); + Np = ceil(1.5*(2.0/myHSMM->getNumSTATES()) * av_state_duration); + myHSMM->setCOMPONENTS(tpgmm.getProdGMM()->getCOMPONENTS()); + if (Nc>=Np){Nc = Np;} + myTrajMPC = new TrajMPC(myHSMM,mpc_dt,nVarsPos,nDeriv,Np,Nc,alpha); +// myTrajMPC = new TpTrajMPC(&tpgmm, &tp, +// myHSMM,mpc_dt,nVarsPos,nDeriv,Np,Nc,alpha); + + // Make sure that the TrajMPC model is correclty initialized by resetting it before starting + myTrajMPC->reset(); + curPos = Xinit; + Ad = myTrajMPC->getSystemDynamics(); + Bd = myTrajMPC->getInputDynamics(); + if (mpc_start_state == -1){ + TestData = curPos;}else{ + curPos = myHSMM->getMU(mpc_start_state); + } + trajMPCrunning = true; + prt(endl << tpgmm.getHSMM()->getTRANSITION()); + }else{ + // do trajMPC step + if (trajMPCrunning){ + // Make step: + U = myTrajMPC->computeControlCommand(curPos); + // Simulate movement of attractor: + curPos = Ad*curPos + Bd*U; + TestData = join_rows(TestData, curPos); +// prt(myTrajMPC->getq()); + } + } + communication_live = false; + }else{ + communication_live = true; + trajMPCrunning = false; + TestData.clear(); + } + + if (communication_live){ + float kp = 0.50; + teleop_pointer_position.x += + kp*(mouse_pos_in_canvas.x - teleop_pointer_position.x); + teleop_pointer_position.y += + kp*(mouse_pos_in_canvas.y - teleop_pointer_position.y); + }else{ + teleop_pointer_position.x = curPos(0); + teleop_pointer_position.y = curPos(1); + } + + + //=================================================================== +// if (ImGui::Button("trajMPC")){ +// if (TestData.size()){ +// trajMPCruns.push_back(TestData); +// } +// Xinit = tpgmm.getProdGMM()->getMU(mpc_start_state); +// myHSMM = tpgmm.getHSMM(); +// myHSMM->setCOMPONENTS(tpgmm.getProdGMM()->getCOMPONENTS()); +// myTrajMPC = new TrajMPC(myHSMM,mpc_dt,nVarsPos,nDeriv,Np,Nc,alpha); +// // Make sure that the TrajMPC model is correclty initialized by resetting it before starting +// myTrajMPC->reset(); +// curPos = Xinit; +// Ad = myTrajMPC->getSystemDynamics(); +// Bd = myTrajMPC->getInputDynamics(); +// TestData = curPos; +// trajMPCrunning = true; +// } + // do trajMPC step +// if (trajMPCrunning){ +// // Make step: +// U = myTrajMPC->computeControlCommand(curPos); +// // Simulate movement of attractor: +// curPos = Ad*curPos + Bd*U; +// TestData = join_rows(TestData, curPos); +// } + + ImGui::End(); + + //Rendering the reproduction side (right)=========================== + glViewport((int)ImGui::GetIO().DisplaySize.x / 2, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + glClear(GL_COLOR_BUFFER_BIT); + //Scaling to match the imgui rendering + glPushMatrix(); + glTranslatef(-1.0f,-1.0f,0); + glScalef(2.0f/(float)ImGui::GetIO().DisplaySize.x, 2.0f/(float)ImGui::GetIO().DisplaySize.y, 1.0f); + + //Draw the Separating line + glColor3f(0.1f, 0.1f, 0.1f); + glBegin(GL_LINE_STRIP); + glVertex2f(0, 0); + glVertex2f(0, (int)ImGui::GetIO().DisplaySize.y); + glEnd(); + + //Draw current demo + drawStrip(points, colBlack, 2.0); + + //Draw all demos + if (dispDemo) { + for (int n=0; n<(int)demos.size(); n++) { + drawStrip(demos[n].getDatapoints().getData(),colGray,2.0); + } + } + + //Draw references + if(dispRef) { + glLineWidth(4.0f); + for (int k = 0; k < (int) tpgmm.getNumFRAMES(); k++) { + glColor3f(colorM(0,0), colorM(0,1), colorM(0,2)); + glBegin(GL_LINE_STRIP); + for (int t = 0; t < (int) size(refShape,1); t++) { + vec point; + point = refFrame[k].b + refFrame[k].A * refShape.col(t); + glVertex2f(point(0),point(1)); + } + glEnd(); + } + glLineWidth(2.0f); + } + + //Draw Gaussians +// if (modelExist&&dispGMM){ +// drawGaussians(tpgmm, refFrame, colorM); +// } + if (modelExist){ + drawProdGaussians(tpgmm, colorM.row(4).t()); + } + + //Draw MPC + if (TestData.size()){ + drawStrip(TestData,vec3({1,1,1}),3.0); + } +// if (curPos.size()){ +// drawSquare(curPos(0),curPos(1),10); +// } + drawStrip(trajMPCruns,vec3({0.8,0.8,0.8}),2); + + //draw teleop dot + drawSquare(teleop_pointer_position.x,teleop_pointer_position.y,10); + + glPopMatrix(); + + + //GUI rendering ===================================== + glViewport(0, 0, (int)ImGui::GetIO().DisplaySize.x, (int)ImGui::GetIO().DisplaySize.y); + // glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w); + // glClear(GL_COLOR_BUFFER_BIT); + ImGui::Render(); + + //PbDlib rendering + glPushMatrix(); + glTranslatef(-1.0f,-1.0f,0); + glScalef(2.0f/(float)ImGui::GetIO().DisplaySize.x, 2.0f/(float)ImGui::GetIO().DisplaySize.y, 1.0f); + glLineWidth(2.0f); + + //Draw current demo + drawStrip(points,colBlack,2.0); + + //Draw all demos + if (dispDemo) { + for (int n=0; n<(int)demos.size(); n++){ + drawStrip(demos[n].getDatapoints().getData(),colGray,2.0); + } + } + + //Draw references + if(dispRef) { + glLineWidth(4.0f); + for (int k = 0; k < (int) tpgmm.getNumFRAMES(); k++) { + + glColor3f(colorM(0,0), colorM(0,1), colorM(0,2)); + glBegin(GL_LINE_STRIP); + for (int t = 0; t < (int) size(refShape,1); t++) { + vec point = refFrame[k].b + refFrame[k].A * refShape.col(t); + glVertex2f(point(0),point(1)); + } + glEnd(); + } + glLineWidth(2.0f); + } + + //Draw Gaussians + if (modelExist&&dispGMM){ + drawGaussians(tpgmm, refFrame, colorM); + } + // if (modelExist){ + // drawProdGaussians(tpgmm, colorM.row(4).t()); + // } + + //Draw repros + drawStrip(repros,colorM.row(3).t(),5.0); + + //Draw MPC +// if (TestData.size()){ +// drawStrip(TestData,vec3({1,1,1}),3.0); +// } +// if (curPos.size()){ +// drawSquare(curPos(0),curPos(1),10); +// } + + glPopMatrix(); + glfwSwapBuffers(window); + } + + //Cleanup + ImGui_ImplGlfw_Shutdown(); + glfwTerminate(); + + return 0; +} + + +void drawStrip(mat points, vec3 color, float linewidth){ + glLineWidth(linewidth); + glColor3f(color[0], color[1], color[2]); + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)points.n_cols; t++){ + glVertex2f(points(0,t), points(1,t)); + } + glEnd(); +} + +void drawStrip(vector<mat> points, vec3 color, float linewidth){ + for (int n=0; n<(int)points.size(); n++){ + drawStrip(points[n],color,linewidth); + } +} + +void drawStrip(ImVector<ImVec2> &points, vec3 color, float linewidth){ + glLineWidth(linewidth); + glColor3f(color[0], color[1], color[2]); + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)points.size(); t++){ + glVertex2f(points[t].x, points[t].y); + } + glEnd(); +} + +void drawGaussians(TPDPGMM &tpgmm, Ref refFrame[], mat colorM){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glLineWidth(2.0f); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++) { + for (int k = 0; k < (int) tpgmm.getNumFRAMES(); k++) { + + eig_sym(d, V, tpgmm.getGMMS(k).getSIGMA(i).rows(0,1).cols(0,1)); + R = refFrame[k].A*(V * sqrt(diagmat(d))); + pts = R * pts0; + + glColor3f(colorM(k+1,0), colorM(k+1,1), colorM(k+1,2)); + glBegin(GL_LINE_STRIP); + + vec refMU = refFrame[k].b + refFrame[k].A*tpgmm.getGMMS(k).getMU(i).rows(0,1); + + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f((pts(0, t) + refMU(0)), (pts(1, t) +refMU(1))); + } + glEnd(); + glBegin(GL_POINTS); + for (int t = 0; t < (int) pts.n_cols; t++) { + glVertex2f(tpgmm.getGMMS(k).getMU(i)(0), + tpgmm.getGMMS(k).getMU(i)(1)); + } + glEnd(); + } + } +} + +void drawProdGaussians(TPDPGMM &tpgmm, vec color){ + vec d(2); + mat V(2,2), R(2,2), pts(2,30); + mat pts0(2,30); + pts0 = join_cols(cos(linspace<rowvec>(0,2*PI,30)), sin(linspace<rowvec>(0,2*PI,30))); + glColor3f(color(0), color(1), color(2)); + for (int i=0; i<(int)tpgmm.getNumSTATES(); i++){ + eig_sym(d, V, tpgmm.getProdGMM()->getSIGMA(i).rows(0,1).cols(0,1)); + R = V * sqrt(diagmat(d)); + pts = R * pts0; + glBegin(GL_LINE_STRIP); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f((pts(0,t)+tpgmm.getProdGMM()->getMU(i)(0)), + (pts(1,t)+tpgmm.getProdGMM()->getMU(i)(1))); + } + glEnd(); + glBegin(GL_POINTS); + for (int t=0; t<(int)pts.n_cols; t++){ + glVertex2f(tpgmm.getProdGMM()->getMU(i)(0), + tpgmm.getProdGMM()->getMU(i)(1)); + } + glEnd(); + } +} + + void drawSquare(int pos_x, int pos_y, int square_edge, float lineWidth){ + glLineWidth(lineWidth); + glBegin( GL_QUADS ); + glColor3f( 0.8f, 0.2f, 0.2f ); + int dot_w = square_edge/2; + glVertex2f( pos_x - dot_w, pos_y - dot_w); + glVertex2f( pos_x - dot_w, pos_y + dot_w); + glVertex2f( pos_x + dot_w, pos_y + dot_w); + glVertex2f( pos_x + dot_w, pos_y - dot_w); + glEnd(); + } diff --git a/src/gfx.cpp b/src/gfx.cpp new file mode 100644 index 0000000..23e20d3 --- /dev/null +++ b/src/gfx.cpp @@ -0,0 +1,909 @@ +#include "gfx.h" + +using namespace arma; +#define PI 3.14159265358979323846 + +namespace gfx +{ + +void init() +{ + glewInit(); +} + +int checkGlExtension(char const *name) +{ + const char *glExtensions = (const char *)glGetString(GL_EXTENSIONS); + return (strstr(glExtensions, name) != NULL); +} + +bool getGLError() +{ + GLenum err = glGetError(); + //glClearError(); + if( err != GL_NO_ERROR ) + { + #if !defined(CM_GLES) && !defined(GFX_OSX) + printf("GL ERROR %d %s",(int)err,gluErrorString(err)); + #endif + return true; + } + + return false; +} + + +arma::fmat perspective(float fovy, float aspect, float zNear, float zFar) +{ + const float top = zNear * tan(fovy / 2.0f); + const float bottom = -top; + const float right = top * aspect; + const float left = -right; + + arma::fmat projection = arma::zeros<fmat>(4,4); + + projection(0, 0) = 2.0f * zNear / (right - left); + projection(0, 2) = (right + left) / (right - left); + projection(1, 1) = 2.0f * zNear / (top - bottom); + projection(1, 2) = (top + bottom) / (top - bottom); + projection(2, 2) = -(zFar + zNear) / (zFar - zNear); + projection(2, 3) = -(2.0f * zFar * zNear) / (zFar - zNear); + projection(3, 2) = -1.0f; + + return projection; +} + + +void setPerspectiveProjection(float fovy, float aspect, float zNear, float zFar) +{ + glMatrixMode( GL_PROJECTION ); + glLoadIdentity(); + + arma::fmat projection = perspective(fovy, aspect, zNear, zFar); + + // Add to current matrix + glMultMatrixf(projection.memptr()); + + glMatrixMode( GL_MODELVIEW ); +} + +void setOrtho( float w, float h ) +{ + glMatrixMode( GL_PROJECTION ); + glLoadIdentity(); + glOrtho( 0, 0+w, 0+h, 0, -1., 1.); + glMatrixMode( GL_MODELVIEW ); + glLoadIdentity(); +} + +void multMatrix( const arma::mat& m_ ) +{ + arma::mat m = m_; + if(m.n_rows==3) + { + m.insert_cols(2, 1); + m.insert_rows(2, 1); + } + glMultMatrixd(m.memptr()); +} + +arma::fmat lookAt(const arma::fvec& position, const arma::fvec& target, const arma::fvec& up) +{ + const arma::fvec f(arma::normalise(target - position)); + const arma::fvec s(arma::normalise(arma::cross(f, up))); + const arma::fvec u(arma::cross(s, f)); + + arma::fmat result = arma::zeros<fmat>(4,4); + result(0, 0) = s(0); + result(0, 1) = s(1); + result(0, 2) = s(2); + result(1, 0) = u(0); + result(1, 1) = u(1); + result(1, 2) = u(2); + result(2, 0) =-f(0); + result(2, 1) =-f(1); + result(2, 2) =-f(2); + result(0, 3) =-arma::dot(s, position); + result(1, 3) =-arma::dot(u, position); + result(2, 3) = arma::dot(f, position); + result(3, 3) = 1.0f; + + return result; +} + +arma::fmat rotate(const arma::fvec& axis, float angle) +{ + float rcos = cos(angle); + float rsin = sin(angle); + + arma::fmat matrix = arma::zeros<arma::fmat>(4, 4); + + matrix(0, 0) = rcos + axis(0) * axis(0) * (1.0f - rcos); + matrix(1, 0) = axis(2) * rsin + axis(1) * axis(0) * (1.0f - rcos); + matrix(2, 0) = -axis(1) * rsin + axis(2) * axis(0) * (1.0f - rcos); + matrix(0, 1) = -axis(2) * rsin + axis(0) * axis(1) * (1.0f - rcos); + matrix(1, 1) = rcos + axis(1) * axis(1) * (1.0f - rcos); + matrix(2, 1) = axis(0) * rsin + axis(2) * axis(1) * (1.0f - rcos); + matrix(0, 2) = axis(1) * rsin + axis(0) * axis(2) * (1.0f - rcos); + matrix(1, 2) = -axis(0) * rsin + axis(1) * axis(2) * (1.0f - rcos); + matrix(2, 2) = rcos + axis(2) * axis(2) * (1.0f - rcos); + matrix(3, 3) = 1.0f; + + return matrix; +} + + +/////////////////////////////////////////////////////////////// + +void drawUVQuad( float x , float y , float w , float h, float maxU, float maxV, bool flip ) +{ + GLfloat tex_coords[8]; + + if(flip) + { + tex_coords[0] = 0.0f; tex_coords[1] = maxV; + tex_coords[2] = 0.0f; tex_coords[3] = 0.0f; + tex_coords[4] = maxU; tex_coords[5] = 0.0f; + tex_coords[6] = maxU; tex_coords[7] = maxV; + } + else + { + tex_coords[0] = 0.0f; tex_coords[1] = 0.0f; + tex_coords[2] = 0.0f; tex_coords[3] = maxV; + tex_coords[4] = maxU; tex_coords[5] = maxV; + tex_coords[6] = maxU; tex_coords[7] = 0.0f; + } + + GLfloat verts[] = { + x,y, + x,y+h, + x+w,y+h, + x+w,y + }; + + glEnableClientState( GL_TEXTURE_COORD_ARRAY ); + glTexCoordPointer(2, GL_FLOAT, 0, tex_coords ); + + glEnableClientState(GL_VERTEX_ARRAY); + glVertexPointer(2, GL_FLOAT, 0, verts ); + glDrawArrays( GL_TRIANGLE_FAN, 0, 4 ); + glDisableClientState( GL_TEXTURE_COORD_ARRAY ); +} + +void drawQuad( float x , float y , float w , float h ) +{ + GLfloat verts[] = { + x+w,y, + x+w,y+h, + x,y+h, + x,y + }; + + glBegin(GL_TRIANGLE_FAN); + for( int i = 0; i < 8; i+=2 ) + { + glVertex2f(verts[i],verts[i+1]); + } + glEnd(); +} + + +void enableAntiAliasing( bool aa ) +{ + + if ( aa ) + { + glHint( GL_POINT_SMOOTH_HINT, GL_NICEST ); + glHint( GL_LINE_SMOOTH_HINT, GL_NICEST ); + glHint( GL_POLYGON_SMOOTH_HINT, GL_NICEST ); + glEnable( GL_POINT_SMOOTH ); + glEnable( GL_LINE_SMOOTH ); + glEnable( GL_POLYGON_SMOOTH ); + glLineWidth( 0.5 ); + } else { + glHint( GL_POINT_SMOOTH_HINT, GL_FASTEST ); + glHint( GL_LINE_SMOOTH_HINT, GL_FASTEST ); + glHint( GL_POLYGON_SMOOTH_HINT, GL_FASTEST ); + glDisable( GL_POINT_SMOOTH ); + glDisable( GL_LINE_SMOOTH ); + glDisable( GL_POLYGON_SMOOTH ); + } +} + +void vertex( const arma::vec& v ) +{ + switch(v.size()) + { + case 2: + glVertex2f(v[0], v[1]); + break; + case 4: + glVertex4f(v[0], v[1], v[2], v[3]); + break; + default: + glVertex3f(v[0], v[1], v[2]); + break; + } +} + +void draw( const arma::mat& P, int prim ) +{ + if(!P.size()) + return; + + glBegin(prim); + switch(P.n_rows) + { + case 2: + { + for( int i = 0; i < P.n_cols; i++ ) + { + glVertex2f(P.at(0,i), P.at(1,i)); // )P[i][0], P[i][1] ); + } + break; + } + default: + { + for( int i = 0; i < P.n_cols; i++ ) + { + glVertex3f(P.at(0, i), P.at(1, i), P.at(2, i));//P[i][0], P[i][1], P[i][2] ); + } + break; + } + } + glEnd(); +} + +void drawLine( const arma::vec& a, const arma::vec& b ) +{ + glBegin(GL_LINES); + vertex(a); + vertex(b); + glEnd(); +} + + +void drawAxis( const arma::vec& m, float scale ) +{ + arma::vec pos = m.submat(0, 3, 2, 3); + arma::vec x = pos + m.submat(0, 0, 2, 0)*scale; + arma::vec y = pos + m.submat(0, 1, 2, 1)*scale; + arma::vec z = pos + m.submat(0, 2, 2, 2)*scale; + + glBegin(GL_LINE_STRIP); + glColor4f(1,0,0,1); + vertex(pos); + vertex(x); + glColor4f(0,1,0,1); + vertex(pos); + vertex(y); + glColor4f(0,0,1,1); + vertex(pos); + vertex(z); + glColor4f(1,1,1,1); + glEnd(); +} + +/////////////////////////////////////////////////////////////// + +// Handle release +struct GLObj +{ + enum TYPE + { + TEXTURE = 0, + SHADER = 1, + PROGRAM, + VB, + IB + }; + + GLObj( GLuint glId, TYPE type ) + : + glId(glId), + type(type) + { + } + + GLObj() + { + } + + GLuint glId; + TYPE type; +}; + +static void releaseGLObject( GLObj o ) +{ + switch(o.type) + { + case GLObj::TEXTURE: + glDeleteTextures(1,&o.glId); + break; + + case GLObj::SHADER: + glDeleteShader(o.glId); + break; + + case GLObj::PROGRAM: + glDeleteProgram(o.glId); + break; + + case GLObj::VB: + glDeleteBuffers(1,&o.glId); + break; + + case GLObj::IB: + glDeleteBuffers(1,&o.glId); + break; + } +} + +struct Shader : public GLObj +{ + Shader( int id=-1 ) + : + GLObj(id, GLObj::SHADER) + { + + } + + int refcount=0; + + GLuint glId; +}; + +struct ShaderProgram : public GLObj +{ + ShaderProgram( int id=-1, int vs=-1, int ps=-1 ) + : + GLObj(id, GLObj::PROGRAM ), + ps(ps), + vs(vs) + { + + } + + int ps=-1; + int vs=-1; +}; + +typedef std::map<int, Shader> ShaderMap; +typedef std::map<int, ShaderProgram> ShaderProgramMap; + +static ShaderProgramMap shaderProgramMap; +static ShaderMap shaderMap; + +static int curProgram=-1; + +static std::string shaderVersion="120"; + +static void incShaderRefCount(int id) +{ + auto it = shaderMap.find(id); + if(it != shaderMap.end()) + it->second.refcount++; +} + + +void removeShader( int id ) +{ + auto it = shaderMap.find(id); + if(it == shaderMap.end()) + return; + it->second.refcount--; + if( it->second.refcount <= 0 ) + { + releaseGLObject(it->second); + shaderMap.erase(it); + } +} + +void deleteShaderProgram( int id ) +{ + auto it = shaderProgramMap.find(id); + if(it == shaderProgramMap.end()) + return; + releaseGLObject(it->second); + removeShader(it->second.vs); + removeShader(it->second.ps); + shaderProgramMap.erase(it); +} + +void deleteAllShaders() +{ + { + auto it = shaderMap.begin(); + while( it != shaderMap.end() ) + { + releaseGLObject(it->second); + it++; + } + } + + { + auto it = shaderProgramMap.begin(); + while( it != shaderProgramMap.end() ) + { + releaseGLObject(it->second); + it++; + } + } +} + +static bool compileShader( GLuint id, const char* shaderStr ) +{ + char errors[1024]; + + glShaderSource(id, 1, (const GLchar**)&shaderStr,NULL); + + GLsizei len; + GLint compiled; + + glCompileShader(id); + glGetShaderiv(id, GL_COMPILE_STATUS, &compiled); + + if (!compiled) + { + glGetShaderInfoLog( id, 1024, &len, errors ); + printf("shader errors: %s\n",errors); + return false; + } + + return true; +} + +void setShaderVersion( const std::string& version ) +{ + shaderVersion = version; +} + +static std::string addVersion( const std::string& str ) +{ + return std::string("\n#version ") + shaderVersion + "\n\n" + str; +} + +int loadVertexShader( const std::string& vs_ ) +{ + int id = glCreateShader(GL_VERTEX_SHADER); + std::string vs = addVersion(vs_); + if(!compileShader(id, vs.c_str())) + { + return -1; + } + + shaderMap[id] = Shader(id); + + return id; +} + +int loadPixelShader( const std::string& ps_ ) +{ + int id = glCreateShader(GL_FRAGMENT_SHADER); + std::string ps = addVersion(ps_); + if(!compileShader(id, ps.c_str())) + { + return -1; + } + + shaderMap[id] = Shader(id); + + return id; +} + +int linkShader( int vs, int ps ) +{ + int id = glCreateProgram(); + + glAttachShader(id, vs ); + glAttachShader(id, ps ); + + + // bind attributes + /* + for( u32 i = 0; i < _vertexAttributes.size() ; i++ ) + { + VertexAttribute * a = _vertexAttributes[i]; + + glBindAttribLocation(this->_glId, GENERIC_ATTRIB(a->index), a->name.str); + + if(getGLGfx()->getGLError()) + { + debugPrint("In GLShaderProgram::link"); + return false; + } + + delete _vertexAttributes[i]; + } + + _vertexAttributes.clear(); + */ + + glLinkProgram(id); + + GLint linked; + char errors[1024]; + GLsizei len; + + glGetProgramiv(id, GL_LINK_STATUS, &linked); + if (!linked) + { + glGetProgramInfoLog(id, 1024, &len, errors ); + printf("GLSL Shader linker error:%s\n",errors); + assert(0); + return -1; + } + + shaderProgramMap[id] = ShaderProgram(id, vs, ps); + incShaderRefCount(vs); + incShaderRefCount(ps); + + return id; +} + +int loadShader( const std::string& vs, const std::string& ps ) +{ + int vsid = loadVertexShader(vs); + if(vsid < 0) + return -1; + + int psid = loadPixelShader(ps); + if(psid < 0) + return -1; + + return linkShader( vsid, psid ); +} + +int reloadShader( int id, const std::string& vs, const std::string& ps ) +{ + int newid = loadShader(vs, ps); + if(newid==-1) + return id; + + deleteShaderProgram(id); + return newid; +} + +static int getUniformLocation( const std::string& handle ) +{ + int loc = glGetUniformLocation( curProgram, handle.c_str() ); + if(loc==-1) + { + printf("shader error: Could not get uniform %s\n", handle.c_str()); + } + return loc; +} + +bool setTexture( const std::string& handle, int sampler ) +{ + int id = getUniformLocation(handle); + if(id == -1) + return false; + + glUniform1i(id, sampler); + return true; +} + +void bindShader( int id ) +{ + glUseProgram(id); + curProgram = id; +} + +void unbindShader() +{ + glUseProgram(0); + curProgram = -1; +} + +bool setInt( const std::string& handle, int v ) +{ + int id = getUniformLocation(handle); + if(id == -1) + return false; + + glUniform1i(id, v); + return true; +} + +bool setFloat( const std::string& handle, float v ) +{ + int id = getUniformLocation(handle); + if(id == -1) + return false; + glUniform1f(id, v); + + return true; +} + +bool setVector( const std::string& handle, const arma::vec& v ) +{ + int id = getUniformLocation(handle); + if(id == -1) + return false; + fmat fv = conv_to<fvec>::from(v); + switch(fv.n_rows) + { + case 2: + //glUniform2fv(id, 1, (GLfloat*)fv.memptr()); + glUniform2f(id, fv[0], fv[1]);//(GLfloat*)fv.memptr()); + break; + case 3: + glUniform3fv(id, 1, (GLfloat*)fv.memptr()); + break; + case 4: + glUniform4fv(id, 1, (GLfloat*)fv.memptr()); + break; + } + + return true; +} + +bool setMatrix( const std::string& handle, const mat& v ) +{ + int id = getUniformLocation(handle); + if(id == -1) + return false; + + fmat fm = conv_to<fmat>::from(v); + + switch(v.n_rows) + { + case 2: + glUniformMatrix2fv(id, 1, GL_FALSE, (GLfloat*)fm.memptr()); + break; + case 3: + glUniformMatrix3fv(id, 1, GL_FALSE, (GLfloat*)fm.memptr()); + break; + case 4: + glUniformMatrix4fv(id, 1, GL_FALSE, (GLfloat*)fm.memptr()); + break; + default: + return false; + } + + return true; +} + +/* +// Hack, limited number of texture samplers, using a larger number will creash +static int textureSamplers[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + +int createTexture(int w, int h, int glFormat, int dataFormat, int dataType ) +{ + unsigned char * data = new unsigned char[w*h*4*4]; + int id = createTexture(data, w, h, glFormat, dataFormat, dataType); + delete [] data; + return id; +} + +int createTexture(void* data, int w, int h, int glFormat, int dataFormat, int dataType ) +{ + glDisable( GL_TEXTURE_RECTANGLE ); + glEnable( GL_TEXTURE_2D ); + + GLint prevAlignment; + glGetIntegerv(GL_UNPACK_ALIGNMENT, &prevAlignment); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + + int id; + glGenTextures(1, (GLint*)&id); // Create 1 Texture + glBindTexture(GL_TEXTURE_2D, id); // Bind The Texture + + // Does not handle mip maps at the moment + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + int hwWidth=width; + int hwHeight=height; + + // Check if non power of two + if(!checkGlExtension("GL_ARB_texture_non_power_of_two")) + { + hwWidth = NPOT(width); + hwHeight = NPOT(height); + + if(hwWidth != width) + { + // realign data + int hww = info.hwWidth; + int hwh = info.hwHeight; + + int sz = glFormatDescs[fmt].bytesPerPixel; + + unsigned char * src = (unsigned char*)data; + unsigned char * dst = new unsigned char[ hww*hwh*sz ]; + data = dst; + + memset( dst, 0, hww*hwh*sz ); + for( int y = 0; y < h; y++ ) + { + memcpy(&dst[y*hww*sz],&src[y*w*sz],w*sz); + } + } + } + + glTexImage2D( GL_TEXTURE_2D, + 0, + info.glFormat, + info.hwWidth, + info.hwHeight, + 0, + info.glDataFormat, + info.glDataType, + data ); + + glPixelStorei(GL_UNPACK_ALIGNMENT, prevAlignment); + glDisable(GL_TEXTURE_2D); + + if(hwWidth != width) + { + delete [] (unsigned char*)data; + } + + return id; +} + +void bindTexture( int id, int sampler ) +{ + glActiveTexture( GL_TEXTURE0+sampler ); + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, id); + + textureSamplers[sampler] = id; +} + +void unbindTexture( int sampler ) +{ + if(textureSamplers[sampler] > 0) + { + glActiveTexture( GL_TEXTURE0+sampler); + glDisable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, 0); + textureSamplers[sampler] = 0; + } +} + +void grabFrameBuffer( int texId, int w, int h ) +{ + bindTexture(id); + glCopyTexSubImage2D(GL_TEXTURE_2D, //target + 0, //level + 0, //xoffset + 0, //yoffset + 0, //x + 0, //y + w, //width + h //height + ); + unbindTexture(); +} +*/ +} + +arma::mat rot2d( double theta, bool affine ) +{ + int d = affine?3:2; + arma::mat m = arma::eye(d,d); + + double ct = cos(theta); + double st = sin(theta); + + m(0,0) = ct; m(0,1) = -st; + m(1,0) = st; m(1,1) = ct; + + return m; +} + +arma::mat trans2d( const arma::vec& xy, bool affine ) +{ + arma::mat m = arma::eye(3,3); + m(0,2) = xy[0]; + m(1,2) = xy[1]; + return m; +} + +arma::mat trans2d( double x, double y, bool affine ) +{ + return trans2d( arma::vec({x, y}) ); +} + +arma::mat scaling2d( const arma::vec& xy, bool affine ) +{ + int d = affine?3:2; + arma::mat m = arma::eye(d,d); + + m(0,0) = xy[0]; + m(1,1) = xy[1]; + return m; +} + +arma::mat scaling2d( double s, bool affine ) +{ + return scaling2d( arma::vec({s, s}), affine ); +} + +arma::mat scaling2d( double x, double y, bool affine ) +{ + return scaling2d( arma::vec({x, y}), affine ); +} + + +arma::mat rotX3d( double theta, bool affine ) +{ + int d = affine?4:3; + arma::mat m = arma::eye(d,d); + + double ct = cos(theta); + double st = sin(theta); + + m(1,1) = ct; m(1,2) = -st; + m(2,1) = st; m(2,2) = ct; + + return m; +} + +arma::mat rotY3d( double theta, bool affine ) +{ + int d = affine?4:3; + arma::mat m = arma::eye(d,d); + + double ct = cos(theta); + double st = sin(theta); + + m(0,0) = ct; m(0,2) = st; + m(2,0) = -st; m(2,2) = ct; + + return m; +} + +arma::mat rotZ3d( double theta, bool affine ) +{ + int d = affine?4:3; + arma::mat m = arma::eye(d,d); + + double ct = cos(theta); + double st = sin(theta); + + m(0,0) = ct; m(0,1) = -st; + m(1,0) = st; m(1,1) = ct; + + return m; +} + +arma::mat trans3d( const arma::vec& xyz ) +{ + arma::mat m = arma::eye(4,4); + m(0,3) = xyz[0]; + m(1,3) = xyz[1]; + m(2,3) = xyz[2]; + return m; +} + +arma::mat trans3d( double x, double y, double z ) +{ + return trans3d( arma::vec({x, y, z}) ); +} + +arma::mat scaling3d( const arma::vec& xyz, bool affine ) +{ + int d = affine?4:3; + arma::mat m = arma::eye(d,d); + + m(0,0) = xyz[0]; + m(1,1) = xyz[1]; + m(2,2) = xyz[2]; + return m; +} + +arma::mat scaling3d( double s, bool affine ) +{ + return scaling3d( arma::vec({s, s, s}), affine ); +} + +arma::mat scaling3d( double x, double y, double z, bool affine ) +{ + return scaling3d( arma::vec({x, y, z}), affine ); +} + + + diff --git a/src/gfx3.cpp b/src/gfx3.cpp new file mode 100644 index 0000000..0ed6c42 --- /dev/null +++ b/src/gfx3.cpp @@ -0,0 +1,1368 @@ +/* + * gfx3.cpp + * + * Rendering utility structures and functions based on OpenGL 3.3+ + * + * Authors: Philip Abbet + */ + +#include <gfx3.h> + +namespace gfx3 { + + +/****************************** UTILITY FUNCTIONS ****************************/ + +void init() +{ + glewExperimental = GL_TRUE; + glewInit(); +} + +//----------------------------------------------- + +double deg2rad(double deg) +{ + return deg / 360.0 * (2.0 * M_PI); +} + +//----------------------------------------------- + +double sin_deg(double deg) +{ + return sin(deg2rad(deg)); +} + +//----------------------------------------------- + +double cos_deg(double deg) +{ + return cos(deg2rad(deg)); +} + +//----------------------------------------------- + +bool is_close(float a, float b, float epsilon) +{ + return fabs(a - b) < epsilon; +} + +//----------------------------------------------- + +arma::vec ui2fb(const arma::vec& coords, int win_width, int win_height, + int fb_width, int fb_height) { + arma::vec result = coords; + + result(0) = (coords(0) - (float) win_width * 0.5f) * (float) fb_width / (float) win_width; + result(1) = ((float) win_height * 0.5f - coords(1)) * (float) fb_height / (float) win_height; + + return result; +} + +//----------------------------------------------- + +arma::vec fb2ui(const arma::vec& coords, int win_width, int win_height, + int fb_width, int fb_height) { + arma::vec result = coords; + + result(0) = coords(0) * (float) win_width / (float) fb_width + (float) win_width * 0.5f; + result(1) = -(coords(1) * (float) win_height / (float) fb_height - (float) win_height * 0.5f); + + return result; +} + +//----------------------------------------------- + +arma::vec ui2shader(const arma::vec& coords, int win_width, int win_height, + int fb_width, int fb_height, float sh_left, float sh_top, + float sh_right, float sh_bottom) { + arma::vec result = ui2fb(coords, win_width, win_height, fb_width, fb_height); + + result(0) = result(0) * (sh_right - sh_left) / (float) fb_width + (1.0f + sh_left); + result(1) = result(1) * (sh_top - sh_bottom) / (float) fb_height + (1.0f + sh_bottom); + + return result; +} + + +/************************* PROJECTION & VIEW MATRICES ************************/ + +arma::fmat perspective(float fovy, float aspect, float zNear, float zFar) +{ + const float top = zNear * tan(fovy / 2.0f); + const float bottom = -top; + const float right = top * aspect; + const float left = -right; + + arma::fmat projection = arma::zeros<arma::fmat>(4,4); + + projection(0, 0) = 2.0f * zNear / (right - left); + projection(0, 2) = (right + left) / (right - left); + projection(1, 1) = 2.0f * zNear / (top - bottom); + projection(1, 2) = (top + bottom) / (top - bottom); + projection(2, 2) = -(zFar + zNear) / (zFar - zNear); + projection(2, 3) = -(2.0f * zFar * zNear) / (zFar - zNear); + projection(3, 2) = -1.0f; + + return projection; +} + +//----------------------------------------------- + +arma::fmat orthographic(float width, float height, float zNear, float zFar) +{ + const float top = height / 2.0f; + const float bottom = -top; + const float right = width / 2.0f; + const float left = -right; + + arma::fmat projection = arma::zeros<arma::fmat>(4,4); + + projection(0, 0) = 2.0f / (right - left); + projection(0, 3) = -(right + left) / (right - left); + projection(1, 1) = 2.0f / (top - bottom); + projection(1, 3) = -(top + bottom) / (top - bottom); + projection(2, 2) = -2.0f / (zFar - zNear); + projection(2, 3) = -(zFar + zNear) / (zFar - zNear); + projection(3, 3) = 1.0f; + + return projection; +} + +//----------------------------------------------- + +arma::fmat lookAt(const arma::fvec& position, const arma::fvec& target, + const arma::fvec& up) +{ + const arma::fvec f(arma::normalise(target - position)); + const arma::fvec s(arma::normalise(arma::cross(f, up))); + const arma::fvec u(arma::cross(s, f)); + + arma::fmat result = arma::zeros<arma::fmat>(4,4); + + result(0, 0) = s(0); + result(0, 1) = s(1); + result(0, 2) = s(2); + result(1, 0) = u(0); + result(1, 1) = u(1); + result(1, 2) = u(2); + result(2, 0) =-f(0); + result(2, 1) =-f(1); + result(2, 2) =-f(2); + result(0, 3) =-arma::dot(s, position); + result(1, 3) =-arma::dot(u, position); + result(2, 3) = arma::dot(f, position); + result(3, 3) = 1.0f; + + return result; +} + + +/****************************** TRANSFORMATIONS ******************************/ + +arma::fmat rotate(const arma::fvec& axis, float angle) +{ + float rcos = cos(angle); + float rsin = sin(angle); + + arma::fmat matrix = arma::zeros<arma::fmat>(4, 4); + + matrix(0, 0) = rcos + axis(0) * axis(0) * (1.0f - rcos); + matrix(1, 0) = axis(2) * rsin + axis(1) * axis(0) * (1.0f - rcos); + matrix(2, 0) = -axis(1) * rsin + axis(2) * axis(0) * (1.0f - rcos); + matrix(0, 1) = -axis(2) * rsin + axis(0) * axis(1) * (1.0f - rcos); + matrix(1, 1) = rcos + axis(1) * axis(1) * (1.0f - rcos); + matrix(2, 1) = axis(0) * rsin + axis(2) * axis(1) * (1.0f - rcos); + matrix(0, 2) = axis(1) * rsin + axis(0) * axis(2) * (1.0f - rcos); + matrix(1, 2) = -axis(0) * rsin + axis(1) * axis(2) * (1.0f - rcos); + matrix(2, 2) = rcos + axis(2) * axis(2) * (1.0f - rcos); + matrix(3, 3) = 1.0f; + + return matrix; +} + +//----------------------------------------------- + +arma::fmat rotation(const arma::fvec& from, const arma::fvec& to) +{ + const float dot = arma::dot(from, to); + const arma::fvec cross = arma::cross(from, to); + const float norm = arma::norm(cross); + + arma::fmat g({ + { dot, -norm, 0.0f }, + { norm, dot, 0.0f }, + { 0.0f, 0.0f, 1.0f }, + }); + + arma::fmat fi(3, 3); + fi.rows(0, 0) = from.t(); + fi.rows(1, 1) = arma::normalise(to - dot * from).t(); + fi.rows(2, 2) = arma::cross(to, from).t(); + + arma::fmat result = arma::eye<arma::fmat>(4, 4); + + arma::fmat u; + if (arma::inv(u, fi)) + { + u = u * g * fi; + result.submat(0, 0, 2, 2) = u; + } + + return result; +} + +//----------------------------------------------- + +void rigid_transform_3D(const arma::fmat& A, const arma::fmat& B, + arma::fmat &rotation, arma::fvec &translation) { + + arma::fvec centroidsA = arma::mean(A, 1); + arma::fvec centroidsB = arma::mean(B, 1); + + int n = A.n_cols; + + arma::fmat H = (A - repmat(centroidsA, 1, n)) * (B - repmat(centroidsB, 1, n)).t(); + + arma::fmat U, V; + arma::fvec s; + arma::svd(U, s, V, H); + + rotation = V * U.t(); + + if (arma::det(rotation) < 0.0f) + rotation.col(2) *= -1.0f; + + translation = -rotation * centroidsA + centroidsB; +} + +//----------------------------------------------- + +arma::fmat worldTransforms(const transforms_t* transforms) +{ + arma::fmat result = arma::eye<arma::fmat>(4, 4); + result(0, 3, arma::size(3, 1)) = worldPosition(transforms); + + result = result * worldRotation(transforms); + + return result; +} + + +//----------------------------------------------- + +arma::fvec worldPosition(const transforms_t* transforms) +{ + if (transforms->parent) + { + arma::fvec position(4); + position.rows(0, 2) = transforms->position; + position(3) = 1.0f; + + position = worldRotation(transforms->parent) * position; + + return worldPosition(transforms->parent) + position.rows(0, 2); + } + + return transforms->position; +} + + +//----------------------------------------------- + +arma::fmat worldRotation(const transforms_t* transforms) +{ + if (transforms->parent) + { + arma::fmat result = worldRotation(transforms->parent) * transforms->rotation; + return arma::normalise(result); + } + + return transforms->rotation; +} + + +/********************************** SHADERS **********************************/ + +void shader_t::setUniform(const std::string& name, const arma::fmat& value) +{ + auto iter = fmat_uniforms.find(name); + + if (iter == fmat_uniforms.end()) + { + shader_fmat_uniform_t entry; + entry.handle = glGetUniformLocation(this->id, name.c_str()); + entry.value = value; + fmat_uniforms[name] = entry; + } + else + { + iter->second.value = value; + } +} + +//----------------------------------------------- + +void shader_t::setUniform(const std::string& name, const arma::mat& value) +{ + auto iter = fmat_uniforms.find(name); + + if (iter == fmat_uniforms.end()) + { + shader_fmat_uniform_t entry; + entry.handle = glGetUniformLocation(this->id, name.c_str()); + entry.value = arma::conv_to<arma::fmat>::from(value); + fmat_uniforms[name] = entry; + } + else + { + iter->second.value = arma::conv_to<arma::fmat>::from(value); + } +} + +//----------------------------------------------- + +void shader_t::setUniform(const std::string& name, const arma::fvec& value) +{ + auto iter = fvec_uniforms.find(name); + + if (iter == fvec_uniforms.end()) + { + shader_fvec_uniform_t entry; + entry.handle = glGetUniformLocation(this->id, name.c_str()); + entry.value = value; + fvec_uniforms[name] = entry; + } + else + { + iter->second.value = value; + } +} + +//----------------------------------------------- + +void shader_t::setUniform(const std::string& name, const arma::vec& value) +{ + auto iter = fvec_uniforms.find(name); + + if (iter == fvec_uniforms.end()) + { + shader_fvec_uniform_t entry; + entry.handle = glGetUniformLocation(this->id, name.c_str()); + entry.value = arma::conv_to<arma::fvec>::from(value); + fvec_uniforms[name] = entry; + } + else + { + iter->second.value = arma::conv_to<arma::fvec>::from(value); + } +} + +//----------------------------------------------- + +void shader_t::setUniform(const std::string& name, float value) +{ + auto iter = float_uniforms.find(name); + + if (iter == float_uniforms.end()) + { + shader_float_uniform_t entry; + entry.handle = glGetUniformLocation(this->id, name.c_str()); + entry.value = value; + float_uniforms[name] = entry; + } + else + { + iter->second.value = value; + } +} + +//----------------------------------------------- + +void shader_t::setUniform(const std::string& name, bool value) +{ + auto iter = bool_uniforms.find(name); + + if (iter == bool_uniforms.end()) + { + shader_bool_uniform_t entry; + entry.handle = glGetUniformLocation(this->id, name.c_str()); + entry.value = value; + bool_uniforms[name] = entry; + } + else + { + iter->second.value = value; + } +} + +//----------------------------------------------- + +GLuint compileShader(GLenum shader_type, const char* shader_source) +{ + GLuint id = glCreateShader(shader_type); + GLint compiled; + + glShaderSource(id, 1, (const GLchar**) &shader_source, NULL); + glCompileShader(id); + glGetShaderiv(id, GL_COMPILE_STATUS, &compiled); + + if (!compiled) + { + char errors[1024]; + GLsizei len; + + glGetShaderInfoLog(id, 1024, &len, errors); + printf("shader errors: %s\n", errors); + return 0; + } + + return id; +} + +//----------------------------------------------- + +GLuint linkShader(GLuint vertex_shader, GLuint fragment_shader) +{ + GLuint id = glCreateProgram(); + + glAttachShader(id, vertex_shader); + glAttachShader(id, fragment_shader); + glLinkProgram(id); + + GLint linked; + + glGetProgramiv(id, GL_LINK_STATUS, &linked); + if (!linked) + { + char errors[1024]; + GLsizei len; + + glGetProgramInfoLog(id, 1024, &len, errors); + printf("GLSL Shader linker error:%s\n",errors); + return 0; + } + + return id; +} + +//----------------------------------------------- + +shader_t loadShader(const std::string& vertex_shader, + const std::string& fragment_shader, + const std::string& version) +{ + shader_t shader = { 0 }; + shader.id = 0; + + // Compile the vertex shader + GLuint vs_id = compileShader( + GL_VERTEX_SHADER, (std::string("#version ") + version + "\n\n" + vertex_shader).c_str()); + + if (vs_id == 0) + return shader; + + // Compile the fragment shader + GLuint fg_id = compileShader( + GL_FRAGMENT_SHADER, (std::string("#version ") + version + "\n\n" + fragment_shader).c_str()); + + if (fg_id == 0) + return shader; + + // Link the shaders into a GLSL program + shader.id = linkShader(vs_id, fg_id); + + // Transformation matrices-related uniforms + shader.model_matrix_handle = glGetUniformLocation(shader.id, "ModelMatrix"); + shader.view_matrix_handle = glGetUniformLocation(shader.id, "ViewMatrix"); + shader.projection_matrix_handle = glGetUniformLocation(shader.id, "ProjectionMatrix"); + + // Material-related uniforms + shader.ambiant_color_handle = glGetUniformLocation(shader.id, "AmbiantColor"); + shader.diffuse_color_handle = glGetUniformLocation(shader.id, "DiffuseColor"); + shader.specular_color_handle = glGetUniformLocation(shader.id, "SpecularColor"); + shader.specular_power_handle = glGetUniformLocation(shader.id, "SpecularPower"); + + // Texture-related uniforms + shader.diffuse_texture_handle = glGetUniformLocation(shader.id, "DiffuseTexture"); + + // Light-related uniforms + shader.light_position_handle = glGetUniformLocation(shader.id, "LightPosition"); + shader.light_color_handle = glGetUniformLocation(shader.id, "LightColor"); + shader.light_power_handle = glGetUniformLocation(shader.id, "LightPower"); + + // Determine if lightning is used by the shaders + shader.use_lightning = (shader.light_position_handle != -1); + + // Backbuffer + shader.backbuffer_handle = glGetUniformLocation(shader.id, "BackBuffer"); + + return shader; +} + +//----------------------------------------------- + +void sendApplicationUniforms(const shader_t* shader) +{ + // Send the application-specific uniforms to the shader + for (auto iter = shader->fmat_uniforms.begin(), iterEnd = shader->fmat_uniforms.end(); + iter != iterEnd; ++iter) + { + if (iter->second.value.n_rows == 4) + glUniformMatrix4fv(iter->second.handle, 1, GL_FALSE, iter->second.value.memptr()); + else if (iter->second.value.n_rows == 2) + glUniformMatrix2fv(iter->second.handle, 1, GL_FALSE, iter->second.value.memptr()); + } + + for (auto iter = shader->fvec_uniforms.begin(), iterEnd = shader->fvec_uniforms.end(); + iter != iterEnd; ++iter) + { + if (iter->second.value.n_rows == 3) + glUniform3fv(iter->second.handle, 1, iter->second.value.memptr()); + else if (iter->second.value.n_rows == 2) + glUniform2fv(iter->second.handle, 1, iter->second.value.memptr()); + } + + for (auto iter = shader->float_uniforms.begin(), iterEnd = shader->float_uniforms.end(); + iter != iterEnd; ++iter) + { + glUniform1f(iter->second.handle, iter->second.value); + } + + for (auto iter = shader->bool_uniforms.begin(), iterEnd = shader->bool_uniforms.end(); + iter != iterEnd; ++iter) + { + glUniform1i(iter->second.handle, iter->second.value); + } +} + +//----------------------------------------------- + +const char* VERTEX_SHADER_ONE_LIGHT = STRINGIFY( + // Input vertex data + layout(location = 0) in vec3 vertex_position; + layout(location = 1) in vec3 normal; + + // Values that stay constant for the whole mesh + uniform mat4 ModelMatrix; + uniform mat4 ViewMatrix; + uniform mat4 ProjectionMatrix; + uniform vec3 LightPosition; + + // Output data ; will be interpolated for each fragment + out vec3 position_worldspace; + out vec3 eye_direction_cameraspace; + out vec3 light_direction_cameraspace; + out vec3 normal_cameraspace; + + void main() { + // Position of the vertex, in clip space + gl_Position = ProjectionMatrix * ViewMatrix * ModelMatrix * vec4(vertex_position, 1); + + // Position of the vertex, in worldspace + position_worldspace = (ModelMatrix * vec4(vertex_position, 1)).xyz; + + // Vector that goes from the vertex to the camera, in camera space. + // In camera space, the camera is at the origin (0,0,0). + vec3 vertex_position_cameraspace = (ViewMatrix * vec4(position_worldspace, 1)).xyz; + eye_direction_cameraspace = vec3(0,0,0) - vertex_position_cameraspace; + + // Vector that goes from the vertex to the light, in camera space + vec3 light_position_cameraspace = (ViewMatrix * vec4(LightPosition, 1)).xyz; + light_direction_cameraspace = light_position_cameraspace + eye_direction_cameraspace; + + // Normal of the the vertex, in camera space (Only correct if ModelMatrix does + // not scale the model) + normal_cameraspace = (ViewMatrix * ModelMatrix * vec4(normal, 0)).xyz; + } +); + +//----------------------------------------------- + +const char* FRAGMENT_SHADER_ONE_LIGHT = STRINGIFY( + // Values that stay constant for the whole mesh + uniform vec3 AmbiantColor; + uniform vec3 DiffuseColor; + uniform vec3 SpecularColor; + uniform float SpecularPower; + uniform vec3 LightPosition; + uniform vec3 LightColor; + uniform float LightPower; + + // Interpolated values from the vertex shaders + in vec3 position_worldspace; + in vec3 eye_direction_cameraspace; + in vec3 light_direction_cameraspace; + in vec3 normal_cameraspace; + + // Output data + out vec3 color; + + void main() { + // Normal of the computed fragment, in camera space + vec3 n = normalize(normal_cameraspace); + + // Direction of the light (from the fragment to the light) + vec3 l = normalize(light_direction_cameraspace); + + // Eye vector (towards the camera) + vec3 E = normalize(eye_direction_cameraspace); + + // Direction in which the triangle reflects the light + vec3 R = reflect(-l, n); + + // Cosine of the angle between the normal and the light direction, + // clamped above 0 + // - light is at the vertical of the triangle -> 1 + // - light is perpendicular to the triangle -> 0 + // - light is behind the triangle -> 0 + float cos_theta = clamp(dot(n, l), 0, 1); + + // Cosine of the angle between the Eye vector and the Reflect vector, + // clamped to 0 + // - Looking into the reflection -> 1 + // - Looking elsewhere -> < 1 + float cos_alpha = clamp(dot(E, R), 0, 1); + + // Distance to the light + float distance = length(LightPosition - position_worldspace); + + // Computation of the color of the fragment + color = AmbiantColor + + DiffuseColor * LightColor * LightPower * cos_theta / (distance * distance) + + SpecularColor * LightColor * LightPower * pow(cos_alpha, SpecularPower) / (distance * distance); + } +); + +//----------------------------------------------- + +const char* VERTEX_SHADER_COLORED = STRINGIFY( + // Input vertex data + layout(location = 0) in vec3 vertex_position; + + // Values that stay constant for the whole mesh + uniform mat4 ModelMatrix; + uniform mat4 ViewMatrix; + uniform mat4 ProjectionMatrix; + + void main() { + // Position of the vertex, in clip space + gl_Position = ProjectionMatrix * ViewMatrix * ModelMatrix * vec4(vertex_position, 1); + } +); + +//----------------------------------------------- + +const char* FRAGMENT_SHADER_COLORED = STRINGIFY( + // Values that stay constant for the whole mesh + uniform vec3 DiffuseColor; + + // Output data + out vec3 color; + + void main() { + color = DiffuseColor; + } +); + + +//----------------------------------------------- + +const char* VERTEX_SHADER_TEXTURED = STRINGIFY( + // Input vertex data + layout(location = 0) in vec3 vertex_position; + layout(location = 2) in vec2 vertex_UV; + + // Values that stay constant for the whole mesh + uniform mat4 ModelMatrix; + uniform mat4 ViewMatrix; + uniform mat4 ProjectionMatrix; + + // Output data ; will be interpolated for each fragment + out vec2 UV; + + void main() { + // Position of the vertex, in clip space + gl_Position = ProjectionMatrix * ViewMatrix * ModelMatrix * vec4(vertex_position, 1); + + UV = vertex_UV; + } +); + + +//----------------------------------------------- + +const char* FRAGMENT_SHADER_ONE_TEXTURE = STRINGIFY( + // Values that stay constant for the whole mesh + uniform sampler2D DiffuseTexture; + + // Input data + in vec2 UV; + + // Output data + out vec3 color; + + void main() { + color = texture(DiffuseTexture, UV).rgb; + } +); + +//----------------------------------------------- + +const char* RTT_VERTEX_SHADER = STRINGIFY( + // Input vertex data + layout(location = 0) in vec3 vertex_position; + + // Output data ; will be interpolated for each fragment + out vec2 coords; + + void main() { + gl_Position = vec4(vertex_position, 1); + coords = vertex_position.xy; + } +); + +//----------------------------------------------- + +char const* RTT_FRAGMENT_SHADER_GAUSSIAN = STRINGIFY( + // Values that stay constant for the whole mesh + uniform vec2 Scale; + uniform vec2 Mu; + uniform mat2 Sigma; + uniform vec3 GaussianColor; + uniform vec3 BackgroundColor; + + // Input data + in vec2 coords; + + // Output data + layout(location = 0) out vec3 color; + + void main() { + vec2 e = coords * Scale - Mu; + float a = clamp(exp(-(Sigma[0][0] * e.x * e.x + 2 * Sigma[0][1] * e.x * e.y + + Sigma[1][1] * e.y * e.y)), 0, 1.0f); + + color = GaussianColor * a + (1.0f - a) * BackgroundColor; + } +); + +//----------------------------------------------- + +const char* RTT_FRAGMENT_SHADER_LIC = STRINGIFY( + // Values that stay constant for the whole mesh + uniform vec2 Resolution; + uniform float Time; + uniform vec2 Target; + uniform mat2 Sigma; + uniform sampler2D BackBuffer; + + // Input data + in vec2 coords; + + // Output data + layout(location = 0) out vec3 color; + + // Constants + const int Length = 3; + const int nbPass = 5; + + void main() { + vec2 uvUnit = 1.0 / Resolution.xy; + vec2 uv = (coords.xy + 1.0) * 0.5; + + // Approximate the UV coordinates, so the random noise is less sharp + vec2 approximated_uv = round(uv * 200.0) / 200.0; + + vec2 dTarget = -Sigma * (coords - Target); + dTarget = dTarget / length(dTarget); + + color = vec3(0); + + // Random noise + color += vec3(fract(sin(dot(approximated_uv.xy, vec2(12.9898, 78.233) * sin(Time))) * 43758.5453)); + + for (int n = 0; n < nbPass; n++) { + for (int i = 0; i < Length; i++) { + color += texture(BackBuffer, uv - dTarget * uvUnit * float(i + 4)).rgb; + } + } + color /= 1.0 * float(Length) * float(nbPass) + 1.0; + } +); + + +/***************************** RENDER-TO-TEXTURE *****************************/ + +render_to_texture_t createRTT(const shader_t& shader, unsigned int width, + unsigned int height, const arma::fvec& color) +{ + render_to_texture_t rtt = { 0 }; + rtt.width = width; + rtt.height = height; + + rtt.shader = &shader; + + rtt.current_buffer = 0; + rtt.nb_buffers = (shader.backbuffer_handle >= 0 ? 2 : 1); + + // Preparation of the default color buffer + unsigned char* pixels = new unsigned char[width * height * 3]; + unsigned char* pDst = pixels; + for (unsigned int y = 0; y < height; ++y) + { + for (unsigned int x = 0; x < width; ++x) + { + pDst[0] = (unsigned char) (color(0) * 255); + pDst[1] = (unsigned char) (color(1) * 255); + pDst[2] = (unsigned char) (color(2) * 255); + + pDst += 3; + } + } + + for (unsigned int i = 0; i < rtt.nb_buffers; ++i) { + // Creates the framebuffer + glGenFramebuffers(1, &rtt.buffers[i].framebuffer); + glBindFramebuffer(GL_FRAMEBUFFER, rtt.buffers[i].framebuffer); + + // Creates the texture we're going to render to + glActiveTexture(GL_TEXTURE0); + glGenTextures(1, &rtt.buffers[i].texture); + glBindTexture(GL_TEXTURE_2D, rtt.buffers[i].texture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, pixels); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + + // Link the two + glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, rtt.buffers[i].texture, 0); + } + + delete[] pixels; + + // The rectangular mesh on which the shader is applied + rtt.nb_vertices = 6; + + const GLfloat vertex_buffer_data[] = { + -1.0f, -1.0f, 0.0f, + 1.0f, -1.0f, 0.0f, + -1.0f, 1.0f, 0.0f, + -1.0f, 1.0f, 0.0f, + 1.0f, -1.0f, 0.0f, + 1.0f, 1.0f, 0.0f, + }; + + // Vertex buffer + glGenBuffers(1, &rtt.vertex_buffer); + glBindBuffer(GL_ARRAY_BUFFER, rtt.vertex_buffer); + + glBufferData(GL_ARRAY_BUFFER, rtt.nb_vertices * 3 * sizeof(GLfloat), + vertex_buffer_data, GL_STATIC_DRAW); + + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + return rtt; +} + +//----------------------------------------------- + +bool draw(render_to_texture_t &rtt) +{ + // Various checks + if (rtt.shader->id == 0) + return false; + + // Retrieve the current viewport + GLint previous_viewport[4]; + glGetIntegerv(GL_VIEWPORT, previous_viewport); + + // Activate the GLSL program + glUseProgram(rtt.shader->id); + + // Backbuffer management + if (rtt.shader->backbuffer_handle >= 0) { + unsigned int previous_buffer = rtt.current_buffer; + + rtt.current_buffer++; + if (rtt.current_buffer >= rtt.nb_buffers) + rtt.current_buffer = 0; + + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, rtt.buffers[previous_buffer].texture); + glUniform1i(rtt.shader->backbuffer_handle, 0); + } + + glBindFramebuffer(GL_FRAMEBUFFER, rtt.buffers[rtt.current_buffer].framebuffer); + + glViewport(0, 0, rtt.width, rtt.height); + + // Send the application-specific uniforms to the shader + sendApplicationUniforms(rtt.shader); + + // Specify the vertices for the shader + glEnableVertexAttribArray(0); + glBindBuffer(GL_ARRAY_BUFFER, rtt.vertex_buffer); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*) 0); + + // Set the list of draw buffers. + GLenum draw_buffers[1] = { GL_COLOR_ATTACHMENT0 }; + glDrawBuffers(1, draw_buffers); + + // Draw the mesh + glDrawArrays(GL_TRIANGLES, 0, rtt.nb_vertices); + + // Cleanup + glDisableVertexAttribArray(0); + glBindFramebuffer(GL_FRAMEBUFFER, 0); + + // Restore the previous viewport + glViewport(previous_viewport[0], previous_viewport[1], previous_viewport[2], + previous_viewport[3]); + + return true; +} + + +/*********************************** MESHES **********************************/ + +bool draw(const model_t& model, const arma::fmat& view, + const arma::fmat& projection, const light_list_t& lights) +{ + // Various checks + if (model.shader->id == 0) + return false; + + if (model.shader->use_lightning && lights.empty()) + return false; + + // Activate the GLSL program + glUseProgram(model.shader->id); + + // Send the model, view and projection matrices to the shader + arma::fmat model_matrix = worldTransforms(&model.transforms); + + glUniformMatrix4fv(model.shader->model_matrix_handle, 1, GL_FALSE, model_matrix.memptr()); + glUniformMatrix4fv(model.shader->view_matrix_handle, 1, GL_FALSE, view.memptr()); + glUniformMatrix4fv(model.shader->projection_matrix_handle, 1, GL_FALSE, projection.memptr()); + + // Send the material parameters to the shader + glUniform3fv(model.shader->diffuse_color_handle, 1, model.diffuse_color.memptr()); + + if (model.shader->use_lightning) { + glUniform3fv(model.shader->ambiant_color_handle, 1, model.ambiant_color.memptr()); + glUniform3fv(model.shader->specular_color_handle, 1, model.specular_color.memptr()); + glUniform1f(model.shader->specular_power_handle, model.specular_power); + } + + // Send the texture parameters to the shader + if (model.shader->diffuse_texture_handle > -1) { + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, model.diffuse_texture); + glUniform1i(model.shader->diffuse_texture_handle, 0); + } + + // Send the light parameters to the shader + if (model.shader->use_lightning) { + glUniform3fv(model.shader->light_position_handle, 1, lights[0].transforms.position.memptr()); + glUniform3fv(model.shader->light_color_handle, 1, lights[0].color.memptr()); + glUniform1f(model.shader->light_power_handle, lights[0].power); + } + + // Send the application-specific uniforms to the shader + sendApplicationUniforms(model.shader); + + // Specify the vertices for the shader + glEnableVertexAttribArray(0); + glBindBuffer(GL_ARRAY_BUFFER, model.vertex_buffer); + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*) 0); + + // Specify the normals for the shader + if (model.shader->use_lightning) { + glEnableVertexAttribArray(1); + glBindBuffer(GL_ARRAY_BUFFER, model.normal_buffer); + glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (void*) 0); + } + + // Specify the UVs for the shader + if (model.uv_buffer) { + glEnableVertexAttribArray(2); + glBindBuffer(GL_ARRAY_BUFFER, model.uv_buffer); + glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0); + } + + // Draw the mesh + glDrawArrays(model.mode, 0, model.nb_vertices); + + glDisableVertexAttribArray(0); + + if (model.shader->use_lightning) + glDisableVertexAttribArray(1); + + if (model.uv_buffer) + glDisableVertexAttribArray(2); + + return true; +} + +//----------------------------------------------- + +model_t create_rectangle(const shader_t& shader, const arma::fvec& color, + float width, float height) +{ + model_t model = { 0 }; + + if (shader.use_lightning) + return model; + + model.mode = GL_TRIANGLES; + model.shader = &shader; + + // Position & rotation + model.transforms.position.zeros(3); + model.transforms.rotation.eye(4, 4); + + // Material + model.diffuse_color = color; + + // Create the mesh + model.nb_vertices = 6; + + //-- Vertex buffer + float half_width = 0.5f * width; + float half_height = 0.5f * height; + + const GLfloat vertex_buffer_data[] = { + half_width, half_height, 0.0f, + -half_width, half_height, 0.0f, + -half_width, -half_height, 0.0f, + -half_width, -half_height, 0.0f, + half_width, -half_height, 0.0f, + half_width, half_height, 0.0f, + }; + + glGenBuffers(1, &model.vertex_buffer); + glBindBuffer(GL_ARRAY_BUFFER, model.vertex_buffer); + + glBufferData(GL_ARRAY_BUFFER, model.nb_vertices * 3 * sizeof(GLfloat), + vertex_buffer_data, GL_STATIC_DRAW); + + //-- UVs buffer + const GLfloat uv_buffer_data[] = { + 1.0f, 1.0f, + 0.0f, 1.0f, + 0.0f, 0.0f, + 0.0f, 0.0f, + 1.0f, 0.0f, + 1.0f, 1.0f, + }; + + glGenBuffers(1, &model.uv_buffer); + glBindBuffer(GL_ARRAY_BUFFER, model.uv_buffer); + + glBufferData(GL_ARRAY_BUFFER, model.nb_vertices * 2 * sizeof(GLfloat), + uv_buffer_data, GL_STATIC_DRAW); + + return model; +} + +//----------------------------------------------- + +model_t create_square(const shader_t& shader, const arma::fvec& color, float size) +{ + model_t model = { 0 }; + + if (shader.use_lightning) + return model; + + model.mode = GL_TRIANGLES; + model.shader = &shader; + + // Position & rotation + model.transforms.position.zeros(3); + model.transforms.rotation.eye(4, 4); + + // Material + model.diffuse_color = color; + + // Create the mesh + model.nb_vertices = 6; + + float half_size = 0.5f * size; + + const GLfloat vertex_buffer_data[] = { + half_size, half_size, 0.0f, + -half_size, half_size, 0.0f, + -half_size, -half_size, 0.0f, + -half_size, -half_size, 0.0f, + half_size, -half_size, 0.0f, + half_size, half_size, 0.0f, + }; + + // Vertex buffer + glGenBuffers(1, &model.vertex_buffer); + glBindBuffer(GL_ARRAY_BUFFER, model.vertex_buffer); + + glBufferData(GL_ARRAY_BUFFER, model.nb_vertices * 3 * sizeof(GLfloat), + vertex_buffer_data, GL_STATIC_DRAW); + + return model; +} + +//----------------------------------------------- + +model_t create_sphere(const shader_t& shader, float radius) +{ + model_t model = { 0 }; + + model.mode = GL_TRIANGLES; + model.shader = &shader; + + // Position & rotation + model.transforms.position.zeros(3); + model.transforms.rotation.eye(4, 4); + + // Material + model.ambiant_color = arma::fvec({0.2f, 0.2f, 0.2f}); + model.diffuse_color = arma::fvec({0.8f, 0.8f, 0.8f}); + model.specular_color = arma::fvec({0.0f, 0.0f, 0.0f}); + model.specular_power = 5; + + // Create the mesh + const int NB_STEPS = 72; + const float STEP_SIZE = 360.0f / NB_STEPS; + + model.nb_vertices = NB_STEPS / 2 * NB_STEPS * 6; + + GLfloat* vertex_buffer_data = new GLfloat[model.nb_vertices * 3]; + + GLfloat* normal_buffer_data = (shader.use_lightning ? + new GLfloat[model.nb_vertices * 3] : 0); + + GLfloat* dst_vertex = vertex_buffer_data; + GLfloat* dst_normal = normal_buffer_data; + + for (int i = 0; i < NB_STEPS / 2; ++i) + { + GLfloat latitude_lo = (float) i * STEP_SIZE; + GLfloat latitude_hi = latitude_lo + STEP_SIZE; + + for (int j = 0; j < NB_STEPS; ++j) + { + GLfloat longitude_lo = (float) j * STEP_SIZE; + GLfloat longitude_hi = longitude_lo + STEP_SIZE; + + arma::fvec vert_ne(3); + arma::fvec vert_nw(3); + arma::fvec vert_sw(3); + arma::fvec vert_se(3); + + // Assign each X,Z with sin,cos values scaled by latitude radius indexed by longitude. + vert_ne(1) = vert_nw(1) = (float) -cos_deg(latitude_hi) * radius; + vert_sw(1) = vert_se(1) = (float) -cos_deg(latitude_lo) * radius; + + vert_nw(0) = (float) cos_deg(longitude_lo) * (radius * (float) sin_deg(latitude_hi)); + vert_sw(0) = (float) cos_deg(longitude_lo) * (radius * (float) sin_deg(latitude_lo)); + vert_ne(0) = (float) cos_deg(longitude_hi) * (radius * (float) sin_deg(latitude_hi)); + vert_se(0) = (float) cos_deg(longitude_hi) * (radius * (float) sin_deg(latitude_lo)); + + vert_nw(2) = (float) -sin_deg(longitude_lo) * (radius * (float) sin_deg(latitude_hi)); + vert_sw(2) = (float) -sin_deg(longitude_lo) * (radius * (float) sin_deg(latitude_lo)); + vert_ne(2) = (float) -sin_deg(longitude_hi) * (radius * (float) sin_deg(latitude_hi)); + vert_se(2) = (float) -sin_deg(longitude_hi) * (radius * (float) sin_deg(latitude_lo)); + + dst_vertex[0] = vert_ne(0); dst_vertex[1] = vert_ne(1); dst_vertex[2] = vert_ne(2); dst_vertex += 3; + dst_vertex[0] = vert_nw(0); dst_vertex[1] = vert_nw(1); dst_vertex[2] = vert_nw(2); dst_vertex += 3; + dst_vertex[0] = vert_sw(0); dst_vertex[1] = vert_sw(1); dst_vertex[2] = vert_sw(2); dst_vertex += 3; + + dst_vertex[0] = vert_sw(0); dst_vertex[1] = vert_sw(1); dst_vertex[2] = vert_sw(2); dst_vertex += 3; + dst_vertex[0] = vert_se(0); dst_vertex[1] = vert_se(1); dst_vertex[2] = vert_se(2); dst_vertex += 3; + dst_vertex[0] = vert_ne(0); dst_vertex[1] = vert_ne(1); dst_vertex[2] = vert_ne(2); dst_vertex += 3; + + if (shader.use_lightning) + { + arma::fvec normal_ne = arma::normalise(vert_ne); + arma::fvec normal_nw = arma::normalise(vert_nw); + arma::fvec normal_sw = arma::normalise(vert_sw); + arma::fvec normal_se = arma::normalise(vert_se); + + dst_normal[0] = normal_ne(0); dst_normal[1] = normal_ne(1); dst_normal[2] = normal_ne(2); dst_normal += 3; + dst_normal[0] = normal_nw(0); dst_normal[1] = normal_nw(1); dst_normal[2] = normal_nw(2); dst_normal += 3; + dst_normal[0] = normal_sw(0); dst_normal[1] = normal_sw(1); dst_normal[2] = normal_sw(2); dst_normal += 3; + + dst_normal[0] = normal_sw(0); dst_normal[1] = normal_sw(1); dst_normal[2] = normal_sw(2); dst_normal += 3; + dst_normal[0] = normal_se(0); dst_normal[1] = normal_se(1); dst_normal[2] = normal_se(2); dst_normal += 3; + dst_normal[0] = normal_ne(0); dst_normal[1] = normal_ne(1); dst_normal[2] = normal_ne(2); dst_normal += 3; + } + } + } + + // Vertex buffer + glGenBuffers(1, &model.vertex_buffer); + glBindBuffer(GL_ARRAY_BUFFER, model.vertex_buffer); + + glBufferData(GL_ARRAY_BUFFER, model.nb_vertices * 3 * sizeof(GLfloat), + vertex_buffer_data, GL_STATIC_DRAW); + + // Normal buffer + if (shader.use_lightning) + { + glGenBuffers(1, &model.normal_buffer); + glBindBuffer(GL_ARRAY_BUFFER, model.normal_buffer); + + glBufferData(GL_ARRAY_BUFFER, model.nb_vertices * 3 * sizeof(GLfloat), + normal_buffer_data, GL_STATIC_DRAW); + } + + // Cleanup + delete[] vertex_buffer_data; + + if (shader.use_lightning) + delete[] normal_buffer_data; + + return model; +} + +//----------------------------------------------- + +model_t create_line(const shader_t& shader, const arma::fvec& color, + const arma::mat& points) +{ + model_t model = { 0 }; + + if (shader.use_lightning) + return model; + + model.mode = GL_LINE_STRIP; + model.shader = &shader; + + // Position & rotation + model.transforms.position.zeros(3); + model.transforms.rotation.eye(4, 4); + + // Material + model.diffuse_color = color; + + // Create the mesh + model.nb_vertices = points.n_cols; + + GLfloat* vertex_buffer_data = new GLfloat[model.nb_vertices * 3]; + + GLfloat* dst = vertex_buffer_data; + + for (int i = 0; i < points.n_cols; ++i) { + dst[0] = (float) points(0, i); + dst[1] = (float) points(1, i); + + if (points.n_rows == 3) + dst[2] = (float) points(2, i); + else + dst[2] = 0.0f; + + dst += 3; + } + + // Vertex buffer + glGenBuffers(1, &model.vertex_buffer); + glBindBuffer(GL_ARRAY_BUFFER, model.vertex_buffer); + + glBufferData(GL_ARRAY_BUFFER, model.nb_vertices * 3 * sizeof(GLfloat), + vertex_buffer_data, GL_STATIC_DRAW); + + // Cleanup + delete[] vertex_buffer_data; + + return model; +} + +//----------------------------------------------- + +model_t create_line(const shader_t& shader, const arma::fvec& color, + const std::vector<arma::vec>& points) +{ + // arma::mat points_mat(size(points[0]), points.size()); + arma::mat points_mat(points[0].n_rows, points.size()); + + for (size_t i = 0; i < points.size(); ++i) + points_mat.col(i) = points[i]; + + return create_line(shader, color, points_mat); +} + +//----------------------------------------------- + +void destroy(const model_t& model) +{ + if (model.vertex_buffer) + glDeleteBuffers(1, &model.vertex_buffer); + + if (model.normal_buffer) + glDeleteBuffers(1, &model.normal_buffer); + + if (model.uv_buffer) + glDeleteBuffers(1, &model.uv_buffer); +} + + +/******************************** RAY CASTING ********************************/ + +ray_t create_ray(const arma::fvec& origin, int mouse_x, int mouse_y, + const arma::fmat& view, const arma::fmat& projection, + int window_width, int window_height) +{ + ray_t ray; + + ray.origin = origin; + + // Compute the ray in homogeneous clip coordinates (range [-1:1, -1:1, -1:1, -1:1]) + arma::fvec ray_clip(4); + ray_clip(0) = (2.0f * mouse_x) / window_width - 1.0f; + ray_clip(1) = 1.0f - (2.0f * mouse_y) / window_height; + ray_clip(2) = -1.0f; + ray_clip(3) = 1.0f; + + // Compute the ray in camera coordinates + arma::fvec ray_eye = arma::inv(projection) * ray_clip; + ray_eye(2) = -1.0f; + ray_eye(3) = 0.0f; + + // Compute the ray in world coordinates + arma::fvec ray_world = arma::inv(view) * ray_eye; + ray.direction = arma::fvec(arma::normalise(ray_world)).rows(0, 2); + + return ray; +} + +//----------------------------------------------- + +bool intersects(const ray_t& ray, const arma::fvec& center, float radius, + arma::fvec &result) +{ + arma::fvec O_C = ray.origin - center; + float b = arma::dot(ray.direction, O_C); + float c = arma::dot(O_C, O_C) - radius * radius; + + float det = b * b - c; + + if (det < 0.0f) + return false; + + float t; + + if (det > 0.0f) + { + float t1 = -b + sqrtf(det); + float t2 = -b - sqrtf(det); + + t = (t1 < t2 ? t1 : t2); + } + else + { + t = -b + sqrtf(det); + } + + result = ray.origin + ray.direction * t; + + return true; +} + +} diff --git a/src/gfx_ui.cpp b/src/gfx_ui.cpp new file mode 100644 index 0000000..482fbd9 --- /dev/null +++ b/src/gfx_ui.cpp @@ -0,0 +1,1565 @@ +/******************************************************************** + -------------------------------------------------------------------- + -- _,(_)._ + -- ___,(_______). ____ + -- ,'__. \ /\___\-. + -- /,' / \ / / \ + -- | | | |,' / \ + -- \`.| / ___|________ + -- `. : : / gfx_ui + -- `. :.,' A immediate mode graphics manipulation UI + -- `-.________,-' Built on top of IMGUI + -- © Daniel Berio + -- http://www.enist.org + -- drand48@gmail.com + -- + -------------------------------------------------------------------- + ********************************************************************/ + + +#include "imgui.h" +#include "imgui_internal.h" +#include "gfx_ui.h" + +// IM dragger interface + +namespace ui +{ + Config config; + + static ImGuiWindow* uiWindow=NULL; + static std::string groupId = ""; + static bool mod=false; + static ImFont* iconFont; + static float iconSize=20.; + + void init( float iconSize_, const std::string& iconFontPath) + { + iconSize = iconSize_; + ImGuiIO& io = ImGui::GetIO(); + if(iconFontPath!="") + { + iconFont = io.Fonts->AddFontFromFileTTF(iconFontPath.c_str(), iconSize); + }else{ + extern size_t gfx_font_size; + extern unsigned char gfx_font[]; + unsigned char * mem = new unsigned char[gfx_font_size]; + memcpy(mem, gfx_font, gfx_font_size); + iconFont = io.Fonts->AddFontFromMemoryTTF(mem, gfx_font_size, iconSize); + } + + //config.colors.push_back(config.color); + } + + bool hasFocus() + { + ImGuiContext& g = *GImGui; + + // maintains cross compatibility with ImGui + if(!g.IO.WantCaptureMouse) + return false; + + if( g.HoveredWindow == uiWindow && g.HoveredIdPreviousFrame == 0 && g.HoveredId==0 && g.ActiveId==0 ) + { + return false; + } + + return true; + } + + void begin( const std::string& name ) + { + static bool show=true; + ImGui::SetNextWindowPos(ImVec2(0,0)); + ImGui::Begin(name.c_str(),&show, ImGui::GetIO().DisplaySize, 0.0f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoBringToFrontOnFocus); + ImGui::SetWindowSize(ImGui::GetIO().DisplaySize); + uiWindow = ImGui::GetCurrentWindow(); + } + + void end() + { + ImGui::End(); + } + + static ImVec4 txtColor = ImVec4(0.5,0.5,0.5,1.0); + void textColor( ImVec4 clr ) + { + txtColor = clr; + } + + void text( ImVec2 pos, const std::string& str ) + { + ImGui::PushStyleColor(ImGuiCol_Text, txtColor); + ImGui::SetCursorPos(pos); + ImGui::Text("%s", str.c_str()); + ImGui::PopStyleColor(); + } + + void textf( ImVec2 pos, const char * format, ... ) + { + char txt[1024]; + va_list parameter; + va_start(parameter,format); + vsnprintf(txt, 1024, format, parameter); + va_end(parameter); + text(pos, txt); + } + + static ImRect rectFromCircle( const ImVec2& p, float r ) + { + float rd = sqrt(2)*r; + return ImRect( ImVec2(p.x-rd, p.y-rd), ImVec2(p.x+rd, p.y+rd)); + } + + bool modified() { return mod; } + + static ImU32 getColor( bool hovered, bool selected ) + { + if(hovered) + return config.hoverColor; + if(selected) + return config.selectedColor; + return config.color; + } + + static void drawDragger( ImGuiWindow*win, const ImRect& r, ImU32 clr ) + { + win->DrawList->AddRectFilled(r.Min, r.Max, (clr&0x00FFFFFF) | 0x77000000, config.rounding); + win->DrawList->AddRect(r.Min, r.Max, clr, config.rounding, 0x0F, 2.0); + } + + ImVec2 dragger( int index, ImVec2 pos, bool selected, float size ) + { + if(size < 0.) + size = config.draggerSize; + + mod = false; + + std::stringstream idstr; + idstr << groupId << "drag" << index; + + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return pos; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(idstr.str().c_str()); + const float w = ImGui::CalcItemWidth(); + + bool res = false; + if(g.ActiveId == id) + { + if (g.IO.MouseDown[0]) + { + pos.x = ImGui::GetMousePos().x; + pos.y = ImGui::GetMousePos().y; + res=mod=true; + } + else + { + ImGui::SetActiveID(0, window); + } + } + + // Specify object + ImRect rect = rectFromCircle(pos, size); + + ImGui::ItemSize(rect); + if(!ImGui::ItemAdd(rect, &id)) + return pos; + + // Check hovered + const bool hovered = ImGui::IsHovered(rect, id); + if (hovered) + { + ImGui::SetHoveredID(id); + if(g.IO.MouseClicked[0]) + { + ImGui::SetActiveID(id, window); + ImGui::FocusWindow(window); + } + } + + // Draw + ImU32 clr = getColor(hovered, selected); + drawDragger(window, rect, clr); + + return pos; + } + + void highlightDragger( const ImVec2& pos, float size ) + { + if(size < 0.) + size = config.draggerSize; + + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return; + + ImRect rect = rectFromCircle(pos, config.draggerSize); + drawDragger(window, rect, config.selectedColor); + //window->DrawList->AddRectFilled(rect.Min, rect.Max, config.selectedColor, config.rounding); //, rounding); + } + + void line( const ImVec2& a, const ImVec2& b ) + { + ImGui::GetCurrentWindow()->DrawList->AddLine(a, b, config.lineColor); + } + + static ImVec2 handlePos( const ImVec2& pos, float theta, float length ) + { + return ImVec2(pos.x + cos(theta)*length, pos.y + sin(theta)*length); + } + + + static float norm( const ImVec2& v ) + { + return ::sqrt( v.x*v.x + v.y*v.y ); + } + + static float length( const ImVec2& a, const ImVec2& b ) + { + return ::sqrt( (b.x-a.x)*(b.x-a.x) + (b.y-a.y)*(b.y-a.y) ); + } + + static float angleBetween( const ImVec2& a, const ImVec2& b ) + { + return ::atan2( a.x*b.y - a.y*b.x, a.x*b.x + a.y*b.y ); + } + + + ImVec2 lengthHandle( int index, ImVec2 thetaLen, float startTheta, const ImVec2& pos, const ImVec2& minThetaLen, const ImVec2& maxThetaLen, bool selected ) + { + using namespace ui; + mod = false; + + std::stringstream idstr; + idstr << groupId << "handle" << index; + + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return thetaLen; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(idstr.str().c_str()); + const float w = ImGui::CalcItemWidth(); + + ImVec2 vbase = ImVec2(::cos(startTheta), ::sin(startTheta)); + + bool res = false; + if(g.ActiveId == id) + { + if (g.IO.MouseDown[0]) + { + ImVec2 vmouse = ImVec2(ImGui::GetMousePos().x - pos.x, ImGui::GetMousePos().y - pos.y); + thetaLen.x = (float)angleBetween(vbase, vmouse); //::atan2( ImGui::GetMousePos().y - pos.y, ImGui::GetMousePos().x - pos.x ); + + if(maxThetaLen.x != 0) + thetaLen.x = std::max( std::min(thetaLen.x, maxThetaLen.x), minThetaLen.x); + + thetaLen.y = std::max( std::min( length(ImGui::GetMousePos(), pos), maxThetaLen.y ), minThetaLen.y ); + res=mod=true; + } + else + { + ImGui::SetActiveID(0, window); + } + } + + // Specify object + ImVec2 hp = handlePos(pos, thetaLen.x+startTheta, thetaLen.y); + ImRect rect = rectFromCircle(hp, config.draggerSize); + + ImGui::ItemSize(rect); + if(!ImGui::ItemAdd(rect, &id)) + return thetaLen; + + // Check hovered + const bool hovered = ImGui::IsHovered(rect, id); + if (hovered) + { + ImGui::SetHoveredID(id); + if(g.IO.MouseClicked[0]) + { + ImGui::SetActiveID(id, window); + ImGui::FocusWindow(window); + } + } + + // Draw + ImU32 clr = getColor(hovered, selected); //ImU32 clr = (g.ActiveId==id)?config.hoverColor:config.color; // ImGui::GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab); + window->DrawList->AddLine(pos, hp, config.lineColor); + drawDragger(window, rect, clr); + //window->DrawList->AddRectFilled(rect.Min, rect.Max, clr, config.rounding); //, rounding); + + return thetaLen; + } + + float handle( int index, float ang, const ImVec2& pos, float length, float startTheta, float minTheta, float maxTheta, bool selected ) + { + ImVec2 thetaLen=ImVec2(ang, length); + thetaLen = lengthHandle(index, thetaLen, startTheta, pos, ImVec2(minTheta, length), ImVec2(maxTheta, length), selected); + return thetaLen.x; + } + + static ImVec2 operator *( float s, const ImVec2 &v ) { return ImVec2( v.x * s, v.y * s ); } + static ImVec2 operator *( const ImVec2 &v, float s ) { return ImVec2( v.x * s, v.y * s ); } + static ImVec2 operator /( const ImVec2 &v, float s ) { return ImVec2( v.x / s, v.y / s ); } + + static ImVec2 operator +( const ImVec2 &a, const ImVec2 &b ) { return ImVec2( a.x + b.x, a.y + b.y ); } + static ImVec2 operator -( const ImVec2 &a, const ImVec2 &b ) { return ImVec2( a.x - b.x, a.y - b.y ); } + + ImVec2 forceOrtho( ImVec2 v, ImVec2 to, bool sameScale ) + { + // Todo store old norm for when alt is released + float nv = sqrt(v.x*v.x + v.y*v.y); + float nto = sqrt(to.x*to.x + to.y*to.y); + + v = v/nv; + to = to/nto; + ImVec2 p = ImVec2(-to.y, to.x); + v = (p.x*v.x + p.y*v.y) * p; + v = v / sqrt(v.x*v.x + v.y*v.y); + + if(sameScale) + v = v*nto; + else + v = v*nv; + return v; + } + + /// Affine transform widget + ui::Trans2d affineSimple( int index, ui::Trans2d t, bool selected ) + { + mod = false; + + std::stringstream idstr; + idstr << groupId << "affine" << index; + + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return t; + + bool pmod=false, xmod=false, ymod=false; + ImVec2 px, py; + + ImGui::PushID(idstr.str().c_str()); + + // position + t.pos = dragger(0, t.pos, selected, config.draggerSize ); pmod = modified(); + + bool shift = ImGui::GetIO().KeyShift; + bool alt = ImGui::GetIO().KeyAlt; + + // x axis + px = t.pos + t.x; + px = dragger(1, px, false, config.draggerSize*0.7 ); xmod = modified(); + + ImVec2 tx = px - t.pos; + float rx = norm(tx) / norm(t.x); + + if(xmod) + { + t.x = px - t.pos; + t.y = forceOrtho(t.y, t.x, ImGui::GetIO().KeyAlt); + if(shift) + t.y = t.y * rx; + if(alt) + t.y = (t.y / norm(t.y))*norm(tx); + } + + // y axis + py = t.pos + t.y; + py = dragger(2, py, false, config.draggerSize*0.7 ); ymod = modified(); + + ImVec2 ty = py - t.pos; + float ry = norm(ty) / norm(t.y); + + if(ymod) + { + t.y = py - t.pos; + t.x = forceOrtho(t.x, t.y, ImGui::GetIO().KeyAlt); + + if(shift) + t.x = t.x * ry; + if(alt) + t.x = (t.x / norm(t.x))*norm(t.y); + } + + window->DrawList->AddLine(t.pos, px, config.lineColor); + window->DrawList->AddLine(t.pos, py, config.lineColor); + + ImGui::PopID(); + + mod = pmod | xmod | ymod; + + return t; + } + + static Rect makeFlipRect( const ImVec2& a, const ImVec2& b ) + { + return Rect( ImVec2(std::min(a.x, b.x), std::min(a.y, b.y)), + ImVec2(std::max(a.x, b.x), std::max(a.y, b.y)) ); + } + + Rect selector() + { + mod = false; + static Rect none = Rect(ImVec2(-100,-100),ImVec2(-100,-100)); + + static ImVec2 clickp; + static bool dragging=false; + if(ImGui::IsMouseClicked(0) && !hasFocus()) + { + clickp = ImGui::GetMousePos(); + dragging = true; + mod = true; + } + + if(ImGui::IsMouseDragging() && dragging) + { + mod = true; + return makeFlipRect(clickp, ImGui::GetMousePos()); + } + + if(ImGui::IsMouseReleased(0)) + dragging = false; + + return none; + } + + ImVec2 dragDelta() + { + return ImGui::GetIO().MouseDelta; + } + + int toolbar( const std::string& title, const std::string& items, int selectedItem, bool horizontal, bool showAscii ) + { + ImVec2 size; + if(horizontal) + size = ImVec2(iconSize*items.length(), iconSize); + else + size = ImVec2(iconSize,iconSize*items.length()); + + int flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse; + ImGui::PushID(title.c_str()); + if(horizontal) + ImGui::Begin(title.c_str(), NULL, size, -1.0f, flags); + else + ImGui::Begin(" ", NULL, size, -1.0f, flags); + + ImGui::PushFont(iconFont); + + int sel = selectedItem; + for( int i = 0; i < items.length(); i++ ) + { + std::stringstream ss; + ss << items[i]; + ImVec2 size(0,0); + if(horizontal) + size.x = iconSize; + if( ImGui::Selectable(ss.str().c_str(),i==selectedItem, 0, size) ) + { + sel = i; + } + if( showAscii && ImGui::IsItemHovered() ) + ImGui::SetTooltip("%c",items[i]); + + if( horizontal && i < items.length()-1 ) + ImGui::SameLine(); + } + + ImGui::PopFont(); + ImGui::End(); + ImGui::PopID(); + + return sel; + } + + static float frand() { return (float)rand() / RAND_MAX; } + static float frand( float lo, float hi ) { return lo + frand()*(hi-lo); } + + void demo() + { + static int state = 0; + static bool first = true; + static std::vector<ImVec2> pts; + static std::vector<int> selected; + static float angle=IM_PI/2; + static ImVec2 arcPos=ImVec2(600,400); + static ui::Trans2d trans(ImVec2(200,0), // X axis + ImVec2(0,100), // Y axis (expected orthogonal) + ImVec2(200,500)); // position + + static ImVec2 p1(300,300), p2(500,300), c1(350,200), c2(450,200); + + if(first) + { + for( int i = 0; i < 7; i++ ) + { + pts.push_back(ImVec2(frand(50,500), frand(50,500))); + } + + first = false; + } + ui::begin("demo"); + ImGuiWindow *win= ImGui::GetCurrentWindow(); + + // Edit bezier curve + p1 = ui::dragger( -100, p1); + p2 = ui::dragger( -101, p2); + c1 = ui::dragger( -102, c1); + c2 = ui::dragger( -103, c2); + ui::line(p1,c1); + ui::line(p2,c2); + win->DrawList->AddBezierCurve(p1, c1, c2, p2, 0xffff0000, 2.); + + // Edit an angle (arc test) + arcPos = ui::dragger(pts.size(), /*numeric id starts at pts.size so we don't conflict with next ones*/ + arcPos, false, 10.); + + angle = ui::handle(0, angle, arcPos, 100.0 /*handle len*/); + + win->DrawList->PathClear(); + win->DrawList->PathArcTo(arcPos, 100.0, 0.0, angle, 100); + win->DrawList->PathLineTo(arcPos); + //win->DrawList->PathLineTo(ui::handlePos(arcPos, angle, 100.)); + + win->DrawList->PathFill(0x66ff0000); + + // Affine transform test + trans = ui::affineSimple(0, trans); + + win->DrawList->PathClear(); + win->DrawList->PathLineTo(trans.pos); + win->DrawList->PathLineTo(trans.pos+trans.x); + win->DrawList->PathLineTo(trans.pos+trans.x+trans.y); + win->DrawList->PathLineTo(trans.pos+trans.y); + win->DrawList->PathFill(0x66ff0000); + + // Edit polyline + bool dragging = false; + for( int i = 0; i < pts.size(); i++ ) + { + pts[i] = ui::dragger(i, pts[i]); + if(ui::modified()) + dragging = true; + } + + // do selection + if( state == 0 ) + { + ui::Rect r = ui::selector(); + bool selecting = ui::modified(); + if(selecting) + { + win->DrawList->AddRectFilled(r.min, r.max, 0x44555555); + + selected.clear(); + for( int i = 0; i < pts.size(); i++ ) + { + if( r.contains(pts[i])) + selected.push_back(i); + } + } + + // highlight selected + for( int i = 0; i < selected.size(); i++ ) + { + ui::highlightDragger(pts[selected[i]]); + } + + // move selected if dragging + if(dragging && selected.size() && !selecting) + { + for( int i = 0; i < selected.size(); i++ ) + { + ImVec2 d = ui::dragDelta(); + pts[selected[i]] = pts[selected[i]] + d; + } + } + } + else if(state==1) + { + if(ImGui::IsMouseClicked(0) && !ui::hasFocus()) + { + pts.push_back(ImGui::GetMousePos()); + } + } + + // Draw + for( int i = 0; i < pts.size()-1; i++ ) + { + win->DrawList->AddLine(pts[i], pts[i+1], 0xff555555); + } + + // A toolbar can be used to switch states, + // the letters in the second parameter correspond with the ascii codes + // for symbols in the loaded font (iconFont), which is set when calling ui::init + state = ui::toolbar("state","ab",state); + + // This shows characters corresponding to each icon in the font + static int foo = 0; + foo = ui::toolbar("Default icons, hover to view the corresponding character","abcdefg123456789",foo, true, true); + + ui::end(); + + + } + + size_t gfx_font_size=9464; + unsigned char gfx_font[] = + {0x00, 0x01, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x80, 0x00, 0x03, + 0x00, 0x70, 0x47, 0x53, 0x55, 0x42, 0xB0, 0xFE, 0xB3, 0xED, + 0x00, 0x00, 0x00, 0xFC, 0x00, 0x00, 0x00, 0x42, 0x4F, 0x53, + 0x2F, 0x32, 0x56, 0x50, 0x61, 0x68, 0x00, 0x00, 0x01, 0x40, + 0x00, 0x00, 0x00, 0x56, 0x63, 0x6D, 0x61, 0x70, 0x2D, 0xF2, + 0x1F, 0x15, 0x00, 0x00, 0x01, 0x98, 0x00, 0x00, 0x02, 0x4A, + 0x63, 0x76, 0x74, 0x20, 0x0C, 0x58, 0x05, 0x4A, 0x00, 0x00, + 0x18, 0xD0, 0x00, 0x00, 0x00, 0x30, 0x66, 0x70, 0x67, 0x6D, + 0x8A, 0x91, 0x90, 0x59, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, + 0x0B, 0x70, 0x67, 0x61, 0x73, 0x70, 0x00, 0x00, 0x00, 0x10, + 0x00, 0x00, 0x18, 0xC8, 0x00, 0x00, 0x00, 0x08, 0x67, 0x6C, + 0x79, 0x66, 0xDA, 0x7B, 0x80, 0x51, 0x00, 0x00, 0x03, 0xE4, + 0x00, 0x00, 0x10, 0x6A, 0x68, 0x65, 0x61, 0x64, 0x0A, 0x54, + 0x0E, 0x6B, 0x00, 0x00, 0x14, 0x50, 0x00, 0x00, 0x00, 0x36, + 0x68, 0x68, 0x65, 0x61, 0x07, 0x81, 0x03, 0xA9, 0x00, 0x00, + 0x14, 0x88, 0x00, 0x00, 0x00, 0x24, 0x68, 0x6D, 0x74, 0x78, + 0x3A, 0x96, 0xFF, 0xFA, 0x00, 0x00, 0x14, 0xAC, 0x00, 0x00, + 0x00, 0x44, 0x6C, 0x6F, 0x63, 0x61, 0x16, 0xF2, 0x1B, 0x99, + 0x00, 0x00, 0x14, 0xF0, 0x00, 0x00, 0x00, 0x24, 0x6D, 0x61, + 0x78, 0x70, 0x01, 0x55, 0x0C, 0x94, 0x00, 0x00, 0x15, 0x14, + 0x00, 0x00, 0x00, 0x20, 0x6E, 0x61, 0x6D, 0x65, 0x17, 0xED, + 0x88, 0x3D, 0x00, 0x00, 0x15, 0x34, 0x00, 0x00, 0x02, 0xB5, + 0x70, 0x6F, 0x73, 0x74, 0x5E, 0x21, 0x67, 0xDD, 0x00, 0x00, + 0x17, 0xEC, 0x00, 0x00, 0x00, 0xDC, 0x70, 0x72, 0x65, 0x70, + 0xE9, 0x45, 0x42, 0xC0, 0x00, 0x00, 0x24, 0x70, 0x00, 0x00, + 0x00, 0x86, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x1E, + 0x00, 0x2C, 0x00, 0x01, 0x44, 0x46, 0x4C, 0x54, 0x00, 0x08, + 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x01, 0x6C, 0x69, 0x67, 0x61, 0x00, 0x08, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, + 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x01, + 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x01, 0x03, 0x72, 0x01, 0x90, 0x00, 0x05, 0x00, 0x00, + 0x02, 0x7A, 0x02, 0xBC, 0x00, 0x00, 0x00, 0x8C, 0x02, 0x7A, + 0x02, 0xBC, 0x00, 0x00, 0x01, 0xE0, 0x00, 0x31, 0x01, 0x02, + 0x00, 0x00, 0x02, 0x00, 0x05, 0x03, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x66, + 0x45, 0x64, 0x00, 0x40, 0x00, 0x31, 0x00, 0x67, 0x03, 0x52, + 0xFF, 0x6A, 0x00, 0x5A, 0x03, 0x52, 0x00, 0x96, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x05, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x2C, + 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x01, 0x7A, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x00, 0x03, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x2C, 0x00, 0x03, 0x00, 0x0A, 0x00, 0x00, + 0x01, 0x7A, 0x00, 0x04, 0x00, 0x48, 0x00, 0x00, 0x00, 0x06, + 0x00, 0x04, 0x00, 0x01, 0x00, 0x02, 0x00, 0x39, 0x00, 0x67, + 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x31, 0x00, 0x61, 0xFF, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x04, + 0x00, 0x05, 0x00, 0x06, 0x00, 0x07, 0x00, 0x08, 0x00, 0x09, + 0x00, 0x0A, 0x00, 0x0B, 0x00, 0x0C, 0x00, 0x0D, 0x00, 0x0E, + 0x00, 0x0F, 0x00, 0x10, 0x00, 0x00, 0x01, 0x06, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x0B, 0x0C, + 0x0D, 0x0E, 0x0F, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, + 0x00, 0x00, 0x00, 0xD0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x10, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x31, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, + 0x00, 0x32, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x33, + 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, + 0x00, 0x34, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x04, + 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, + 0x00, 0x05, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x36, + 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, + 0x00, 0x37, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x38, + 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, + 0x00, 0x39, 0x00, 0x00, 0x00, 0x39, 0x00, 0x00, 0x00, 0x09, + 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, + 0x00, 0x0A, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00, 0x62, + 0x00, 0x00, 0x00, 0x0B, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, + 0x00, 0x63, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x64, + 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x00, + 0x00, 0x65, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x0E, + 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, + 0x00, 0x0F, 0x00, 0x00, 0x00, 0x67, 0x00, 0x00, 0x00, 0x67, + 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0xFF, 0xAA, 0x03, 0x11, 0x03, 0x13, 0x00, 0x0B, 0x00, 0x06, + 0xB3, 0x07, 0x02, 0x01, 0x2D, 0x2B, 0x09, 0x01, 0x06, 0x26, + 0x35, 0x11, 0x34, 0x36, 0x17, 0x01, 0x16, 0x14, 0x03, 0x04, + 0xFD, 0x1B, 0x0D, 0x12, 0x12, 0x0D, 0x02, 0xE5, 0x0D, 0x01, + 0x4D, 0xFE, 0x64, 0x07, 0x0A, 0x0F, 0x03, 0x36, 0x0E, 0x0C, + 0x08, 0xFE, 0x64, 0x07, 0x14, 0x00, 0x00, 0x01, 0x00, 0x00, + 0xFF, 0xB1, 0x03, 0x5A, 0x03, 0x0B, 0x00, 0x0F, 0x00, 0x42, + 0xB6, 0x08, 0x00, 0x02, 0x00, 0x01, 0x01, 0x47, 0x4B, 0xB0, + 0x0A, 0x50, 0x58, 0x40, 0x0B, 0x00, 0x01, 0x01, 0x0C, 0x48, + 0x00, 0x00, 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x4B, 0xB0, 0x0D, + 0x50, 0x58, 0x40, 0x0B, 0x00, 0x01, 0x01, 0x0D, 0x48, 0x00, + 0x00, 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x40, 0x09, 0x00, 0x01, + 0x00, 0x01, 0x6F, 0x00, 0x00, 0x00, 0x66, 0x59, 0x59, 0xB4, + 0x35, 0x33, 0x02, 0x05, 0x16, 0x2B, 0x01, 0x11, 0x14, 0x06, + 0x23, 0x21, 0x22, 0x26, 0x27, 0x11, 0x34, 0x36, 0x33, 0x21, + 0x32, 0x16, 0x03, 0x59, 0x14, 0x10, 0xFC, 0xEF, 0x0F, 0x14, + 0x01, 0x16, 0x0E, 0x03, 0x11, 0x0F, 0x16, 0x02, 0xE7, 0xFC, + 0xEE, 0x0E, 0x16, 0x16, 0x0E, 0x03, 0x12, 0x0E, 0x16, 0x16, + 0x00, 0x02, 0x00, 0x00, 0xFF, 0xB1, 0x03, 0x5A, 0x03, 0x0B, + 0x00, 0x0F, 0x00, 0x1F, 0x00, 0x4D, 0x40, 0x09, 0x18, 0x10, + 0x08, 0x00, 0x04, 0x00, 0x01, 0x01, 0x47, 0x4B, 0xB0, 0x0A, + 0x50, 0x58, 0x40, 0x0D, 0x03, 0x01, 0x01, 0x01, 0x0C, 0x48, + 0x02, 0x01, 0x00, 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x4B, 0xB0, + 0x0D, 0x50, 0x58, 0x40, 0x0D, 0x03, 0x01, 0x01, 0x01, 0x0D, + 0x48, 0x02, 0x01, 0x00, 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x40, + 0x0B, 0x03, 0x01, 0x01, 0x00, 0x01, 0x6F, 0x02, 0x01, 0x00, + 0x00, 0x66, 0x59, 0x59, 0xB6, 0x35, 0x35, 0x35, 0x33, 0x04, + 0x05, 0x18, 0x2B, 0x01, 0x11, 0x14, 0x06, 0x23, 0x21, 0x22, + 0x26, 0x27, 0x11, 0x34, 0x36, 0x33, 0x21, 0x32, 0x16, 0x05, + 0x11, 0x14, 0x06, 0x23, 0x21, 0x22, 0x26, 0x27, 0x11, 0x34, + 0x36, 0x33, 0x21, 0x32, 0x16, 0x03, 0x59, 0x14, 0x10, 0xFE, + 0xE3, 0x0F, 0x14, 0x01, 0x16, 0x0E, 0x01, 0x1D, 0x0F, 0x16, + 0xFE, 0x0B, 0x14, 0x10, 0xFE, 0xE3, 0x0F, 0x14, 0x01, 0x16, + 0x0E, 0x01, 0x1D, 0x0F, 0x16, 0x02, 0xE7, 0xFC, 0xEE, 0x0E, + 0x16, 0x16, 0x0E, 0x03, 0x12, 0x0E, 0x16, 0x16, 0x0E, 0xFC, + 0xEE, 0x0E, 0x16, 0x16, 0x0E, 0x03, 0x12, 0x0E, 0x16, 0x16, + 0x00, 0x01, 0xFF, 0xFF, 0xFF, 0xAE, 0x02, 0x3C, 0x03, 0x0F, + 0x00, 0x1D, 0x00, 0x45, 0x40, 0x09, 0x1B, 0x1A, 0x12, 0x0A, + 0x04, 0x01, 0x00, 0x01, 0x47, 0x4B, 0xB0, 0x0A, 0x50, 0x58, + 0x40, 0x0B, 0x00, 0x00, 0x00, 0x0C, 0x48, 0x00, 0x01, 0x01, + 0x0E, 0x01, 0x49, 0x1B, 0x4B, 0xB0, 0x0D, 0x50, 0x58, 0x40, + 0x0B, 0x00, 0x00, 0x00, 0x0D, 0x48, 0x00, 0x01, 0x01, 0x0E, + 0x01, 0x49, 0x1B, 0x40, 0x09, 0x00, 0x00, 0x01, 0x00, 0x6F, + 0x00, 0x01, 0x01, 0x66, 0x59, 0x59, 0xB4, 0x35, 0x3D, 0x02, + 0x05, 0x16, 0x2B, 0x17, 0x06, 0x26, 0x37, 0x11, 0x34, 0x36, + 0x17, 0x01, 0x16, 0x17, 0x11, 0x34, 0x36, 0x3B, 0x01, 0x32, + 0x16, 0x07, 0x11, 0x14, 0x06, 0x2B, 0x01, 0x22, 0x26, 0x37, + 0x11, 0x06, 0x07, 0x19, 0x0A, 0x10, 0x01, 0x0E, 0x0B, 0x01, + 0x8C, 0x05, 0x03, 0x14, 0x0F, 0x48, 0x0E, 0x16, 0x01, 0x14, + 0x0F, 0x48, 0x0E, 0x16, 0x01, 0x03, 0x05, 0x47, 0x0B, 0x06, + 0x0F, 0x03, 0x36, 0x0E, 0x08, 0x0C, 0xFE, 0x74, 0x04, 0x06, + 0x01, 0x7A, 0x0E, 0x16, 0x16, 0x0E, 0xFC, 0xEE, 0x0E, 0x16, + 0x16, 0x0E, 0x01, 0x7B, 0x06, 0x05, 0x00, 0x00, 0x00, 0x01, + 0xFF, 0xFF, 0xFF, 0xAE, 0x03, 0xE8, 0x03, 0x0F, 0x00, 0x2B, + 0x00, 0x49, 0x40, 0x0B, 0x29, 0x22, 0x21, 0x19, 0x11, 0x0A, + 0x06, 0x01, 0x00, 0x01, 0x47, 0x4B, 0xB0, 0x0A, 0x50, 0x58, + 0x40, 0x0B, 0x00, 0x00, 0x00, 0x0C, 0x48, 0x00, 0x01, 0x01, + 0x0E, 0x01, 0x49, 0x1B, 0x4B, 0xB0, 0x0D, 0x50, 0x58, 0x40, + 0x0B, 0x00, 0x00, 0x00, 0x0D, 0x48, 0x00, 0x01, 0x01, 0x0E, + 0x01, 0x49, 0x1B, 0x40, 0x09, 0x00, 0x00, 0x01, 0x00, 0x6F, + 0x00, 0x01, 0x01, 0x66, 0x59, 0x59, 0xB6, 0x1F, 0x1C, 0x17, + 0x14, 0x02, 0x05, 0x14, 0x2B, 0x17, 0x06, 0x26, 0x37, 0x11, + 0x34, 0x36, 0x17, 0x01, 0x16, 0x17, 0x11, 0x34, 0x36, 0x17, + 0x01, 0x16, 0x17, 0x11, 0x34, 0x36, 0x3B, 0x01, 0x32, 0x16, + 0x17, 0x11, 0x14, 0x06, 0x2B, 0x01, 0x22, 0x26, 0x27, 0x11, + 0x06, 0x07, 0x01, 0x06, 0x26, 0x35, 0x11, 0x06, 0x07, 0x19, + 0x0A, 0x10, 0x01, 0x0E, 0x0B, 0x01, 0x8C, 0x05, 0x03, 0x0E, + 0x0B, 0x01, 0x8C, 0x04, 0x03, 0x16, 0x0E, 0x47, 0x0F, 0x14, + 0x01, 0x16, 0x0E, 0x47, 0x0F, 0x14, 0x01, 0x03, 0x04, 0xFE, + 0x74, 0x0B, 0x0E, 0x03, 0x05, 0x47, 0x0B, 0x06, 0x0F, 0x03, + 0x36, 0x0E, 0x08, 0x0C, 0xFE, 0x74, 0x04, 0x06, 0x01, 0x8C, + 0x0E, 0x08, 0x0C, 0xFE, 0x74, 0x04, 0x06, 0x01, 0x7A, 0x0E, + 0x16, 0x16, 0x0E, 0xFC, 0xEE, 0x0E, 0x16, 0x16, 0x0E, 0x01, + 0x7B, 0x06, 0x05, 0xFE, 0x74, 0x0B, 0x06, 0x0F, 0x01, 0x8D, + 0x06, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xFF, 0xAD, + 0x02, 0x3B, 0x03, 0x0E, 0x00, 0x1D, 0x00, 0x43, 0xB7, 0x1B, + 0x1A, 0x12, 0x03, 0x00, 0x01, 0x01, 0x47, 0x4B, 0xB0, 0x0A, + 0x50, 0x58, 0x40, 0x0B, 0x00, 0x01, 0x01, 0x0C, 0x48, 0x00, + 0x00, 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x4B, 0xB0, 0x0D, 0x50, + 0x58, 0x40, 0x0B, 0x00, 0x01, 0x01, 0x0D, 0x48, 0x00, 0x00, + 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x40, 0x09, 0x00, 0x01, 0x00, + 0x01, 0x6F, 0x00, 0x00, 0x00, 0x66, 0x59, 0x59, 0xB4, 0x35, + 0x3D, 0x02, 0x05, 0x16, 0x2B, 0x01, 0x36, 0x16, 0x15, 0x11, + 0x14, 0x06, 0x27, 0x01, 0x26, 0x27, 0x11, 0x14, 0x06, 0x2B, + 0x01, 0x22, 0x26, 0x27, 0x11, 0x34, 0x36, 0x3B, 0x01, 0x32, + 0x16, 0x17, 0x11, 0x36, 0x37, 0x02, 0x22, 0x0B, 0x0E, 0x0E, + 0x0B, 0xFE, 0x74, 0x05, 0x02, 0x16, 0x0E, 0x47, 0x0F, 0x14, + 0x01, 0x16, 0x0E, 0x47, 0x0F, 0x14, 0x01, 0x02, 0x05, 0x03, + 0x03, 0x0B, 0x06, 0x0F, 0xFC, 0xCA, 0x0E, 0x08, 0x0C, 0x01, + 0x8C, 0x05, 0x06, 0xFE, 0x85, 0x0E, 0x16, 0x16, 0x0E, 0x03, + 0x12, 0x0E, 0x16, 0x16, 0x0E, 0xFE, 0x86, 0x06, 0x04, 0x00, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xFF, 0xAD, 0x03, 0xE9, + 0x03, 0x0E, 0x00, 0x2B, 0x00, 0x48, 0x40, 0x0A, 0x29, 0x22, + 0x21, 0x19, 0x0A, 0x05, 0x00, 0x01, 0x01, 0x47, 0x4B, 0xB0, + 0x0A, 0x50, 0x58, 0x40, 0x0B, 0x00, 0x01, 0x01, 0x0C, 0x48, + 0x00, 0x00, 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x4B, 0xB0, 0x0D, + 0x50, 0x58, 0x40, 0x0B, 0x00, 0x01, 0x01, 0x0D, 0x48, 0x00, + 0x00, 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x40, 0x09, 0x00, 0x01, + 0x00, 0x01, 0x6F, 0x00, 0x00, 0x00, 0x66, 0x59, 0x59, 0xB6, + 0x1F, 0x1C, 0x17, 0x14, 0x02, 0x05, 0x14, 0x2B, 0x01, 0x36, + 0x16, 0x07, 0x11, 0x14, 0x06, 0x27, 0x01, 0x26, 0x27, 0x11, + 0x14, 0x06, 0x27, 0x01, 0x26, 0x27, 0x11, 0x14, 0x06, 0x2B, + 0x01, 0x22, 0x26, 0x27, 0x11, 0x34, 0x36, 0x3B, 0x01, 0x32, + 0x16, 0x17, 0x11, 0x36, 0x37, 0x01, 0x36, 0x16, 0x15, 0x11, + 0x36, 0x37, 0x03, 0xCF, 0x0A, 0x10, 0x01, 0x0E, 0x0B, 0xFE, + 0x74, 0x05, 0x03, 0x0E, 0x0B, 0xFE, 0x74, 0x05, 0x02, 0x16, + 0x0E, 0x47, 0x0F, 0x14, 0x01, 0x16, 0x0E, 0x47, 0x0F, 0x14, + 0x01, 0x02, 0x05, 0x01, 0x8C, 0x0B, 0x0E, 0x03, 0x05, 0x03, + 0x03, 0x0B, 0x06, 0x0F, 0xFC, 0xCA, 0x0E, 0x08, 0x0C, 0x01, + 0x8C, 0x05, 0x06, 0xFE, 0x73, 0x0E, 0x08, 0x0C, 0x01, 0x8C, + 0x05, 0x06, 0xFE, 0x85, 0x0E, 0x16, 0x16, 0x0E, 0x03, 0x12, + 0x0E, 0x16, 0x16, 0x0E, 0xFE, 0x86, 0x06, 0x04, 0x01, 0x8C, + 0x0B, 0x06, 0x0F, 0xFE, 0x74, 0x06, 0x04, 0x00, 0x00, 0x01, + 0xFF, 0xFF, 0xFF, 0xAE, 0x03, 0x5C, 0x03, 0x0F, 0x00, 0x19, + 0x00, 0x06, 0xB3, 0x06, 0x01, 0x01, 0x2D, 0x2B, 0x17, 0x06, + 0x26, 0x37, 0x11, 0x34, 0x36, 0x17, 0x01, 0x16, 0x17, 0x11, + 0x34, 0x36, 0x17, 0x01, 0x16, 0x14, 0x07, 0x01, 0x06, 0x26, + 0x35, 0x11, 0x06, 0x07, 0x19, 0x0A, 0x10, 0x01, 0x0E, 0x0B, + 0x01, 0x8C, 0x05, 0x03, 0x0E, 0x0B, 0x01, 0x8C, 0x0A, 0x0A, + 0xFE, 0x74, 0x0B, 0x0E, 0x03, 0x05, 0x47, 0x0B, 0x06, 0x0F, + 0x03, 0x36, 0x0E, 0x08, 0x0C, 0xFE, 0x74, 0x04, 0x06, 0x01, + 0x8C, 0x0E, 0x08, 0x0C, 0xFE, 0x74, 0x0A, 0x1E, 0x0A, 0xFE, + 0x74, 0x0B, 0x06, 0x0F, 0x01, 0x8D, 0x06, 0x05, 0x00, 0x01, + 0x00, 0x00, 0xFF, 0xAD, 0x03, 0xA1, 0x03, 0x0E, 0x00, 0x19, + 0x00, 0x06, 0xB3, 0x06, 0x01, 0x01, 0x2D, 0x2B, 0x01, 0x36, + 0x16, 0x17, 0x11, 0x14, 0x06, 0x27, 0x01, 0x26, 0x27, 0x11, + 0x14, 0x06, 0x27, 0x01, 0x26, 0x34, 0x37, 0x01, 0x36, 0x16, + 0x15, 0x11, 0x36, 0x37, 0x03, 0x87, 0x0B, 0x0E, 0x01, 0x10, + 0x0A, 0xFE, 0x74, 0x04, 0x03, 0x0E, 0x0B, 0xFE, 0x74, 0x0B, + 0x0B, 0x01, 0x8C, 0x0B, 0x0E, 0x03, 0x04, 0x03, 0x03, 0x0B, + 0x06, 0x0F, 0xFC, 0xCA, 0x0E, 0x08, 0x0C, 0x01, 0x8C, 0x05, + 0x06, 0xFE, 0x73, 0x0E, 0x08, 0x0C, 0x01, 0x8C, 0x0B, 0x1C, + 0x0B, 0x01, 0x8C, 0x0B, 0x06, 0x0F, 0xFE, 0x74, 0x06, 0x04, + 0x00, 0x00, 0x00, 0x01, 0xFF, 0xFD, 0xFF, 0xB1, 0x03, 0x13, + 0x02, 0xC3, 0x00, 0x16, 0x00, 0x38, 0xB5, 0x08, 0x01, 0x00, + 0x01, 0x01, 0x47, 0x4B, 0xB0, 0x0D, 0x50, 0x58, 0x40, 0x10, + 0x00, 0x02, 0x01, 0x02, 0x6F, 0x00, 0x01, 0x00, 0x01, 0x6F, + 0x00, 0x00, 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x40, 0x0E, 0x00, + 0x02, 0x01, 0x02, 0x6F, 0x00, 0x01, 0x00, 0x01, 0x6F, 0x00, + 0x00, 0x00, 0x66, 0x59, 0xB5, 0x26, 0x26, 0x12, 0x03, 0x05, + 0x17, 0x2B, 0x09, 0x01, 0x06, 0x23, 0x22, 0x27, 0x2E, 0x01, + 0x27, 0x11, 0x21, 0x22, 0x2E, 0x01, 0x36, 0x37, 0x01, 0x36, + 0x33, 0x32, 0x17, 0x1E, 0x01, 0x03, 0x0E, 0xFE, 0x9B, 0x0A, + 0x16, 0x03, 0x05, 0x0D, 0x0E, 0x01, 0xFE, 0xBF, 0x0D, 0x12, + 0x08, 0x0C, 0x0B, 0x02, 0xCA, 0x07, 0x09, 0x0F, 0x0A, 0x08, + 0x04, 0x02, 0x8F, 0xFD, 0x36, 0x14, 0x01, 0x03, 0x14, 0x0C, + 0x01, 0x42, 0x0E, 0x1A, 0x14, 0x07, 0x01, 0x65, 0x04, 0x0A, + 0x08, 0x18, 0x00, 0x04, 0x00, 0x00, 0xFF, 0xB1, 0x03, 0x4D, + 0x02, 0xFF, 0x00, 0x06, 0x00, 0x14, 0x00, 0x19, 0x00, 0x24, + 0x00, 0xE4, 0x40, 0x17, 0x1E, 0x01, 0x02, 0x05, 0x1D, 0x16, + 0x0E, 0x07, 0x04, 0x03, 0x02, 0x19, 0x03, 0x02, 0x03, 0x00, + 0x03, 0x01, 0x01, 0x01, 0x00, 0x04, 0x47, 0x4B, 0xB0, 0x0A, + 0x50, 0x58, 0x40, 0x26, 0x00, 0x02, 0x05, 0x03, 0x05, 0x02, + 0x03, 0x6D, 0x00, 0x03, 0x00, 0x05, 0x03, 0x00, 0x6B, 0x00, + 0x00, 0x01, 0x01, 0x00, 0x63, 0x00, 0x05, 0x05, 0x0C, 0x48, + 0x06, 0x01, 0x01, 0x01, 0x04, 0x57, 0x00, 0x04, 0x04, 0x0E, + 0x04, 0x49, 0x1B, 0x4B, 0xB0, 0x0D, 0x50, 0x58, 0x40, 0x26, + 0x00, 0x02, 0x05, 0x03, 0x05, 0x02, 0x03, 0x6D, 0x00, 0x03, + 0x00, 0x05, 0x03, 0x00, 0x6B, 0x00, 0x00, 0x01, 0x01, 0x00, + 0x63, 0x00, 0x05, 0x05, 0x0D, 0x48, 0x06, 0x01, 0x01, 0x01, + 0x04, 0x57, 0x00, 0x04, 0x04, 0x0E, 0x04, 0x49, 0x1B, 0x4B, + 0xB0, 0x12, 0x50, 0x58, 0x40, 0x27, 0x00, 0x05, 0x02, 0x05, + 0x6F, 0x00, 0x02, 0x03, 0x02, 0x6F, 0x00, 0x03, 0x00, 0x03, + 0x6F, 0x00, 0x00, 0x01, 0x01, 0x00, 0x63, 0x06, 0x01, 0x01, + 0x04, 0x04, 0x01, 0x52, 0x06, 0x01, 0x01, 0x01, 0x04, 0x57, + 0x00, 0x04, 0x01, 0x04, 0x4B, 0x1B, 0x40, 0x26, 0x00, 0x05, + 0x02, 0x05, 0x6F, 0x00, 0x02, 0x03, 0x02, 0x6F, 0x00, 0x03, + 0x00, 0x03, 0x6F, 0x00, 0x00, 0x01, 0x00, 0x6F, 0x06, 0x01, + 0x01, 0x04, 0x04, 0x01, 0x52, 0x06, 0x01, 0x01, 0x01, 0x04, + 0x57, 0x00, 0x04, 0x01, 0x04, 0x4B, 0x59, 0x59, 0x59, 0x40, + 0x12, 0x00, 0x00, 0x21, 0x20, 0x18, 0x17, 0x10, 0x0F, 0x09, + 0x08, 0x00, 0x06, 0x00, 0x06, 0x14, 0x07, 0x05, 0x15, 0x2B, + 0x17, 0x37, 0x27, 0x07, 0x15, 0x33, 0x15, 0x01, 0x34, 0x23, + 0x22, 0x07, 0x01, 0x06, 0x15, 0x14, 0x33, 0x32, 0x37, 0x01, + 0x36, 0x27, 0x17, 0x01, 0x23, 0x35, 0x01, 0x14, 0x0F, 0x01, + 0x27, 0x37, 0x36, 0x32, 0x1F, 0x01, 0x16, 0xCB, 0x32, 0x83, + 0x33, 0x48, 0x01, 0x5F, 0x0C, 0x05, 0x04, 0xFE, 0xD1, 0x04, + 0x0D, 0x05, 0x04, 0x01, 0x2F, 0x03, 0x1E, 0xE8, 0xFE, 0x30, + 0xE8, 0x03, 0x4D, 0x14, 0x5D, 0xE8, 0x5D, 0x14, 0x3B, 0x16, + 0x83, 0x14, 0x07, 0x33, 0x83, 0x33, 0x3C, 0x47, 0x02, 0x06, + 0x0C, 0x04, 0xFE, 0xD2, 0x04, 0x06, 0x0C, 0x04, 0x01, 0x2E, + 0x04, 0x71, 0xE8, 0xFE, 0x2F, 0xE9, 0x01, 0x9A, 0x1D, 0x15, + 0x5D, 0xE9, 0x5C, 0x15, 0x15, 0x83, 0x16, 0x00, 0x00, 0x01, + 0x00, 0x00, 0xFF, 0xB1, 0x03, 0x5A, 0x03, 0x0B, 0x00, 0x43, + 0x00, 0x74, 0x40, 0x15, 0x3C, 0x34, 0x32, 0x22, 0x04, 0x02, + 0x03, 0x33, 0x21, 0x20, 0x1B, 0x12, 0x11, 0x10, 0x02, 0x01, + 0x09, 0x00, 0x02, 0x02, 0x47, 0x4B, 0xB0, 0x0A, 0x50, 0x58, + 0x40, 0x16, 0x05, 0x01, 0x02, 0x03, 0x00, 0x03, 0x02, 0x00, + 0x6D, 0x04, 0x01, 0x03, 0x03, 0x0C, 0x48, 0x01, 0x01, 0x00, + 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x4B, 0xB0, 0x0D, 0x50, 0x58, + 0x40, 0x16, 0x05, 0x01, 0x02, 0x03, 0x00, 0x03, 0x02, 0x00, + 0x6D, 0x04, 0x01, 0x03, 0x03, 0x0D, 0x48, 0x01, 0x01, 0x00, + 0x00, 0x0E, 0x00, 0x49, 0x1B, 0x40, 0x11, 0x04, 0x01, 0x03, + 0x02, 0x03, 0x6F, 0x05, 0x01, 0x02, 0x00, 0x02, 0x6F, 0x01, + 0x01, 0x00, 0x00, 0x66, 0x59, 0x59, 0x40, 0x09, 0x26, 0x38, + 0x37, 0x1B, 0x3A, 0x39, 0x06, 0x05, 0x1A, 0x2B, 0x01, 0x07, + 0x17, 0x37, 0x36, 0x16, 0x1D, 0x01, 0x14, 0x06, 0x2B, 0x01, + 0x22, 0x27, 0x26, 0x3F, 0x01, 0x27, 0x07, 0x17, 0x16, 0x07, + 0x06, 0x2B, 0x01, 0x22, 0x26, 0x27, 0x35, 0x34, 0x36, 0x1F, + 0x01, 0x37, 0x27, 0x07, 0x06, 0x23, 0x22, 0x27, 0x26, 0x3D, + 0x01, 0x34, 0x36, 0x3B, 0x01, 0x32, 0x16, 0x0F, 0x01, 0x17, + 0x37, 0x27, 0x26, 0x36, 0x3B, 0x01, 0x32, 0x16, 0x07, 0x15, + 0x14, 0x07, 0x06, 0x23, 0x22, 0x27, 0x02, 0xCC, 0xC6, 0xC6, + 0x50, 0x10, 0x2D, 0x14, 0x10, 0xFA, 0x17, 0x09, 0x0A, 0x11, + 0x51, 0xC6, 0xC6, 0x50, 0x11, 0x09, 0x0A, 0x17, 0xFA, 0x0F, + 0x14, 0x01, 0x2C, 0x11, 0x50, 0xC6, 0xC6, 0x50, 0x0B, 0x0E, + 0x07, 0x07, 0x16, 0x16, 0x0E, 0xFA, 0x17, 0x13, 0x11, 0x50, + 0xC6, 0xC6, 0x51, 0x11, 0x13, 0x17, 0xFA, 0x0F, 0x16, 0x01, + 0x16, 0x07, 0x07, 0x0E, 0x0B, 0x02, 0x24, 0xC6, 0xC6, 0x50, + 0x12, 0x13, 0x18, 0xFA, 0x0E, 0x16, 0x17, 0x15, 0x11, 0x51, + 0xC6, 0xC6, 0x51, 0x11, 0x15, 0x17, 0x16, 0x0E, 0xFA, 0x18, + 0x13, 0x12, 0x50, 0xC6, 0xC6, 0x50, 0x0B, 0x03, 0x09, 0x18, + 0xFA, 0x0E, 0x16, 0x2D, 0x10, 0x51, 0xC6, 0xC6, 0x51, 0x10, + 0x2D, 0x16, 0x0E, 0xFA, 0x18, 0x09, 0x03, 0x0B, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x00, 0xFF, 0x6A, 0x03, 0xE8, 0x03, 0x52, + 0x00, 0x24, 0x00, 0x29, 0x00, 0x9C, 0x40, 0x19, 0x27, 0x26, + 0x21, 0x18, 0x0D, 0x04, 0x06, 0x00, 0x02, 0x28, 0x01, 0x04, + 0x00, 0x02, 0x47, 0x14, 0x01, 0x04, 0x01, 0x46, 0x13, 0x12, + 0x02, 0x01, 0x44, 0x4B, 0xB0, 0x0A, 0x50, 0x58, 0x40, 0x20, + 0x00, 0x02, 0x03, 0x00, 0x03, 0x02, 0x00, 0x6D, 0x00, 0x00, + 0x04, 0x03, 0x00, 0x04, 0x6B, 0x00, 0x03, 0x03, 0x12, 0x48, + 0x05, 0x01, 0x04, 0x04, 0x01, 0x58, 0x00, 0x01, 0x01, 0x0E, + 0x01, 0x49, 0x1B, 0x4B, 0xB0, 0x0D, 0x50, 0x58, 0x40, 0x20, + 0x00, 0x02, 0x03, 0x00, 0x03, 0x02, 0x00, 0x6D, 0x00, 0x00, + 0x04, 0x03, 0x00, 0x04, 0x6B, 0x00, 0x03, 0x03, 0x10, 0x48, + 0x05, 0x01, 0x04, 0x04, 0x01, 0x58, 0x00, 0x01, 0x01, 0x0E, + 0x01, 0x49, 0x1B, 0x40, 0x1D, 0x00, 0x02, 0x03, 0x00, 0x03, + 0x02, 0x00, 0x6D, 0x00, 0x00, 0x04, 0x03, 0x00, 0x04, 0x6B, + 0x05, 0x01, 0x04, 0x00, 0x01, 0x04, 0x01, 0x5C, 0x00, 0x03, + 0x03, 0x10, 0x03, 0x49, 0x59, 0x59, 0x40, 0x0D, 0x25, 0x25, + 0x25, 0x29, 0x25, 0x29, 0x14, 0x1D, 0x24, 0x1A, 0x06, 0x05, + 0x18, 0x2B, 0x01, 0x16, 0x14, 0x0F, 0x01, 0x17, 0x16, 0x14, + 0x0F, 0x01, 0x06, 0x22, 0x2F, 0x01, 0x01, 0x06, 0x2B, 0x01, + 0x07, 0x27, 0x37, 0x35, 0x34, 0x37, 0x01, 0x27, 0x26, 0x34, + 0x3F, 0x01, 0x36, 0x32, 0x1F, 0x01, 0x37, 0x36, 0x32, 0x09, + 0x01, 0x27, 0x01, 0x15, 0x03, 0xB4, 0x34, 0x34, 0x7E, 0x3A, + 0x06, 0x06, 0x75, 0x06, 0x0E, 0x06, 0x3A, 0xFE, 0xAF, 0x15, + 0x1D, 0x71, 0x8F, 0x24, 0x47, 0x15, 0x01, 0x51, 0x3B, 0x06, + 0x06, 0x75, 0x06, 0x0E, 0x06, 0x3A, 0x7C, 0x34, 0x94, 0xFD, + 0x9F, 0x01, 0x41, 0x6B, 0xFE, 0xBF, 0x03, 0x1E, 0x35, 0x94, + 0x34, 0x7C, 0x3A, 0x06, 0x0E, 0x06, 0x75, 0x06, 0x06, 0x3B, + 0xFE, 0xAF, 0x15, 0x47, 0x24, 0x8F, 0x71, 0x1D, 0x15, 0x01, + 0x51, 0x3A, 0x06, 0x0E, 0x06, 0x75, 0x06, 0x06, 0x3A, 0x7E, + 0x34, 0xFC, 0xCB, 0x01, 0x41, 0x6B, 0xFE, 0xBF, 0x6B, 0x00, + 0x00, 0x06, 0x00, 0x00, 0xFF, 0x72, 0x04, 0x2F, 0x03, 0x49, + 0x00, 0x08, 0x00, 0x12, 0x00, 0x1B, 0x00, 0x7B, 0x00, 0xB7, + 0x00, 0xF3, 0x01, 0x38, 0x40, 0x37, 0xF0, 0xDA, 0x02, 0x04, + 0x0E, 0x6B, 0x5E, 0x02, 0x05, 0x08, 0xD1, 0xBD, 0x71, 0x03, + 0x00, 0x05, 0xBF, 0xAD, 0xA1, 0x76, 0x53, 0x4D, 0x46, 0x23, + 0x1D, 0x09, 0x01, 0x00, 0xB4, 0x9F, 0x41, 0x03, 0x02, 0x01, + 0x3B, 0x2E, 0x02, 0x06, 0x02, 0x96, 0x81, 0x02, 0x0B, 0x03, + 0x07, 0x47, 0xE9, 0xDC, 0x02, 0x0E, 0x45, 0x83, 0x01, 0x0B, + 0x44, 0x4B, 0xB0, 0x0A, 0x50, 0x58, 0x40, 0x46, 0x0A, 0x01, + 0x08, 0x09, 0x05, 0x09, 0x08, 0x05, 0x6D, 0x00, 0x06, 0x02, + 0x07, 0x02, 0x06, 0x07, 0x6D, 0x00, 0x09, 0x08, 0x00, 0x09, + 0x54, 0x00, 0x05, 0x0D, 0x01, 0x00, 0x01, 0x05, 0x00, 0x60, + 0x00, 0x02, 0x06, 0x01, 0x02, 0x54, 0x00, 0x04, 0x04, 0x0E, + 0x58, 0x00, 0x0E, 0x0E, 0x0C, 0x48, 0x0C, 0x01, 0x01, 0x01, + 0x07, 0x58, 0x00, 0x07, 0x07, 0x0F, 0x48, 0x00, 0x03, 0x03, + 0x0B, 0x58, 0x00, 0x0B, 0x0B, 0x0E, 0x0B, 0x49, 0x1B, 0x4B, + 0xB0, 0x0D, 0x50, 0x58, 0x40, 0x46, 0x0A, 0x01, 0x08, 0x09, + 0x05, 0x09, 0x08, 0x05, 0x6D, 0x00, 0x06, 0x02, 0x07, 0x02, + 0x06, 0x07, 0x6D, 0x00, 0x09, 0x08, 0x00, 0x09, 0x54, 0x00, + 0x05, 0x0D, 0x01, 0x00, 0x01, 0x05, 0x00, 0x60, 0x00, 0x02, + 0x06, 0x01, 0x02, 0x54, 0x00, 0x04, 0x04, 0x0E, 0x58, 0x00, + 0x0E, 0x0E, 0x0D, 0x48, 0x0C, 0x01, 0x01, 0x01, 0x07, 0x58, + 0x00, 0x07, 0x07, 0x0F, 0x48, 0x00, 0x03, 0x03, 0x0B, 0x58, + 0x00, 0x0B, 0x0B, 0x0E, 0x0B, 0x49, 0x1B, 0x40, 0x41, 0x0A, + 0x01, 0x08, 0x09, 0x05, 0x09, 0x08, 0x05, 0x6D, 0x00, 0x06, + 0x02, 0x07, 0x02, 0x06, 0x07, 0x6D, 0x00, 0x0E, 0x00, 0x04, + 0x09, 0x0E, 0x04, 0x60, 0x00, 0x09, 0x08, 0x00, 0x09, 0x54, + 0x00, 0x05, 0x0D, 0x01, 0x00, 0x01, 0x05, 0x00, 0x60, 0x00, + 0x02, 0x06, 0x01, 0x02, 0x54, 0x00, 0x03, 0x00, 0x0B, 0x03, + 0x0B, 0x5C, 0x0C, 0x01, 0x01, 0x01, 0x07, 0x58, 0x00, 0x07, + 0x07, 0x0F, 0x07, 0x49, 0x59, 0x59, 0x40, 0x1B, 0xE6, 0xE5, + 0xC8, 0xC7, 0xAB, 0xA9, 0x8C, 0x8B, 0x6E, 0x6D, 0x65, 0x63, + 0x5B, 0x5A, 0x35, 0x33, 0x2B, 0x2A, 0x13, 0x14, 0x14, 0x14, + 0x13, 0x12, 0x0F, 0x05, 0x1A, 0x2B, 0x01, 0x34, 0x26, 0x22, + 0x06, 0x14, 0x16, 0x32, 0x36, 0x05, 0x34, 0x26, 0x0E, 0x01, + 0x17, 0x14, 0x16, 0x32, 0x36, 0x03, 0x34, 0x26, 0x22, 0x06, + 0x1E, 0x01, 0x32, 0x36, 0x07, 0x15, 0x14, 0x06, 0x0F, 0x01, + 0x06, 0x07, 0x16, 0x17, 0x16, 0x14, 0x07, 0x0E, 0x01, 0x23, + 0x22, 0x2F, 0x01, 0x06, 0x07, 0x06, 0x07, 0x06, 0x2B, 0x01, + 0x22, 0x26, 0x35, 0x27, 0x26, 0x27, 0x07, 0x06, 0x22, 0x27, + 0x26, 0x35, 0x34, 0x37, 0x3E, 0x01, 0x37, 0x26, 0x2F, 0x01, + 0x2E, 0x01, 0x3D, 0x01, 0x34, 0x36, 0x3F, 0x01, 0x36, 0x37, + 0x26, 0x27, 0x26, 0x34, 0x37, 0x3E, 0x01, 0x33, 0x32, 0x1F, + 0x01, 0x36, 0x37, 0x36, 0x37, 0x36, 0x3B, 0x01, 0x32, 0x16, + 0x1F, 0x01, 0x16, 0x17, 0x37, 0x36, 0x32, 0x17, 0x16, 0x15, + 0x14, 0x0F, 0x01, 0x06, 0x07, 0x16, 0x1F, 0x01, 0x1E, 0x01, + 0x01, 0x15, 0x14, 0x07, 0x06, 0x07, 0x16, 0x15, 0x14, 0x07, + 0x06, 0x23, 0x22, 0x2F, 0x01, 0x06, 0x22, 0x27, 0x0E, 0x01, + 0x07, 0x22, 0x27, 0x26, 0x35, 0x34, 0x37, 0x26, 0x27, 0x26, + 0x3D, 0x01, 0x34, 0x37, 0x36, 0x37, 0x26, 0x35, 0x34, 0x3F, + 0x01, 0x36, 0x33, 0x32, 0x16, 0x17, 0x37, 0x17, 0x36, 0x3F, + 0x01, 0x32, 0x17, 0x16, 0x15, 0x14, 0x07, 0x16, 0x17, 0x16, + 0x11, 0x15, 0x14, 0x07, 0x06, 0x07, 0x16, 0x15, 0x14, 0x07, + 0x06, 0x23, 0x22, 0x26, 0x27, 0x06, 0x22, 0x27, 0x0E, 0x01, + 0x22, 0x27, 0x26, 0x35, 0x34, 0x37, 0x26, 0x27, 0x26, 0x3D, + 0x01, 0x34, 0x37, 0x36, 0x37, 0x26, 0x35, 0x34, 0x3F, 0x01, + 0x36, 0x33, 0x32, 0x16, 0x17, 0x36, 0x32, 0x17, 0x36, 0x3F, + 0x01, 0x32, 0x17, 0x16, 0x15, 0x14, 0x07, 0x16, 0x17, 0x16, + 0x01, 0xF4, 0x54, 0x76, 0x54, 0x54, 0x76, 0x54, 0x01, 0xAD, + 0x2C, 0x38, 0x2C, 0x01, 0x2A, 0x3A, 0x2C, 0x01, 0x2C, 0x38, + 0x2C, 0x01, 0x2A, 0x3A, 0x2C, 0xD8, 0x08, 0x05, 0x56, 0x06, + 0x0C, 0x13, 0x1F, 0x04, 0x04, 0x0D, 0x42, 0x0B, 0x06, 0x05, + 0x40, 0x15, 0x16, 0x06, 0x07, 0x04, 0x0D, 0x68, 0x06, 0x0A, + 0x0D, 0x13, 0x17, 0x42, 0x04, 0x0D, 0x06, 0x50, 0x04, 0x05, + 0x24, 0x08, 0x0D, 0x07, 0x55, 0x05, 0x08, 0x08, 0x05, 0x56, + 0x07, 0x0B, 0x13, 0x1F, 0x04, 0x04, 0x0C, 0x44, 0x0A, 0x06, + 0x06, 0x40, 0x13, 0x18, 0x06, 0x07, 0x03, 0x0D, 0x68, 0x06, + 0x0A, 0x01, 0x0D, 0x13, 0x16, 0x42, 0x05, 0x0D, 0x05, 0x51, + 0x04, 0x18, 0x11, 0x08, 0x0D, 0x06, 0x55, 0x05, 0x08, 0x01, + 0x65, 0x53, 0x06, 0x0A, 0x1C, 0x02, 0x44, 0x01, 0x05, 0x15, + 0x1D, 0x0B, 0x0C, 0x0B, 0x07, 0x2C, 0x03, 0x01, 0x44, 0x03, + 0x1D, 0x0A, 0x07, 0x53, 0x53, 0x07, 0x0A, 0x1D, 0x03, 0x34, + 0x10, 0x01, 0x04, 0x2A, 0x08, 0x11, 0x11, 0x1C, 0x17, 0x04, + 0x02, 0x43, 0x02, 0x1C, 0x09, 0x07, 0x53, 0x53, 0x06, 0x0A, + 0x1C, 0x02, 0x44, 0x01, 0x05, 0x2A, 0x08, 0x0B, 0x0C, 0x0B, + 0x07, 0x2C, 0x04, 0x44, 0x03, 0x1D, 0x0A, 0x07, 0x53, 0x53, + 0x07, 0x0A, 0x1D, 0x03, 0x34, 0x10, 0x01, 0x04, 0x2A, 0x08, + 0x0C, 0x0A, 0x0C, 0x1C, 0x17, 0x04, 0x02, 0x43, 0x02, 0x1C, + 0x09, 0x07, 0x53, 0x01, 0x5E, 0x3B, 0x54, 0x54, 0x76, 0x54, + 0x54, 0xE3, 0x1D, 0x2C, 0x02, 0x28, 0x1F, 0x1D, 0x2A, 0x2A, + 0x02, 0x59, 0x1D, 0x2A, 0x2A, 0x3B, 0x2A, 0x2A, 0xCD, 0x67, + 0x06, 0x0A, 0x01, 0x0E, 0x13, 0x17, 0x1B, 0x25, 0x06, 0x0C, + 0x04, 0x11, 0x42, 0x04, 0x32, 0x0B, 0x06, 0x3C, 0x1B, 0x0D, + 0x08, 0x06, 0x55, 0x06, 0x0C, 0x32, 0x04, 0x04, 0x4B, 0x0F, + 0x05, 0x05, 0x08, 0x2C, 0x0C, 0x18, 0x16, 0x0D, 0x01, 0x08, + 0x07, 0x67, 0x06, 0x0A, 0x01, 0x0E, 0x13, 0x17, 0x1B, 0x25, + 0x06, 0x0C, 0x04, 0x11, 0x42, 0x04, 0x32, 0x0A, 0x08, 0x3C, + 0x1A, 0x0D, 0x08, 0x06, 0x55, 0x06, 0x0B, 0x31, 0x04, 0x04, + 0x4B, 0x0F, 0x05, 0x05, 0x1E, 0x15, 0x0D, 0x1B, 0x13, 0x0C, + 0x02, 0x08, 0xFE, 0xCF, 0x4E, 0x09, 0x08, 0x0F, 0x0E, 0x3F, + 0x0E, 0x02, 0x02, 0x28, 0x1B, 0x25, 0x01, 0x01, 0x0B, 0x34, + 0x01, 0x28, 0x02, 0x02, 0x0E, 0x3F, 0x0E, 0x0F, 0x08, 0x09, + 0x4E, 0x09, 0x09, 0x10, 0x0D, 0x3F, 0x0E, 0x02, 0x02, 0x1E, + 0x09, 0x34, 0x0C, 0x01, 0x01, 0x28, 0x17, 0x01, 0x27, 0x02, + 0x02, 0x0E, 0x3F, 0x0D, 0x10, 0x09, 0x02, 0x33, 0x4E, 0x09, + 0x09, 0x0F, 0x0E, 0x3F, 0x0E, 0x02, 0x02, 0x27, 0x34, 0x0C, + 0x01, 0x01, 0x0C, 0x34, 0x27, 0x02, 0x02, 0x0E, 0x3F, 0x0E, + 0x0F, 0x09, 0x09, 0x4E, 0x09, 0x08, 0x10, 0x0D, 0x3F, 0x0E, + 0x02, 0x02, 0x1E, 0x09, 0x34, 0x0C, 0x02, 0x02, 0x28, 0x17, + 0x01, 0x27, 0x02, 0x02, 0x0E, 0x3F, 0x0D, 0x10, 0x08, 0x00, + 0x00, 0x04, 0x00, 0x00, 0xFF, 0xB1, 0x03, 0x59, 0x03, 0x0B, + 0x00, 0x03, 0x00, 0x21, 0x00, 0x31, 0x00, 0x45, 0x00, 0xB7, + 0x40, 0x11, 0x2B, 0x2A, 0x23, 0x22, 0x04, 0x08, 0x04, 0x01, + 0x47, 0x0D, 0x01, 0x04, 0x06, 0x01, 0x08, 0x02, 0x46, 0x4B, + 0xB0, 0x0A, 0x50, 0x58, 0x40, 0x28, 0x00, 0x08, 0x00, 0x03, + 0x06, 0x08, 0x03, 0x60, 0x00, 0x06, 0x00, 0x01, 0x00, 0x06, + 0x01, 0x5E, 0x07, 0x01, 0x04, 0x04, 0x0A, 0x58, 0x00, 0x0A, + 0x0A, 0x0C, 0x48, 0x05, 0x02, 0x02, 0x00, 0x00, 0x09, 0x58, + 0x00, 0x09, 0x09, 0x0E, 0x09, 0x49, 0x1B, 0x4B, 0xB0, 0x0D, + 0x50, 0x58, 0x40, 0x28, 0x00, 0x08, 0x00, 0x03, 0x06, 0x08, + 0x03, 0x60, 0x00, 0x06, 0x00, 0x01, 0x00, 0x06, 0x01, 0x5E, + 0x07, 0x01, 0x04, 0x04, 0x0A, 0x58, 0x00, 0x0A, 0x0A, 0x0D, + 0x48, 0x05, 0x02, 0x02, 0x00, 0x00, 0x09, 0x58, 0x00, 0x09, + 0x09, 0x0E, 0x09, 0x49, 0x1B, 0x40, 0x2D, 0x00, 0x0A, 0x07, + 0x01, 0x04, 0x08, 0x0A, 0x04, 0x60, 0x00, 0x08, 0x00, 0x03, + 0x06, 0x08, 0x03, 0x60, 0x00, 0x06, 0x00, 0x01, 0x00, 0x06, + 0x01, 0x5E, 0x05, 0x02, 0x02, 0x00, 0x09, 0x09, 0x00, 0x52, + 0x05, 0x02, 0x02, 0x00, 0x00, 0x09, 0x58, 0x00, 0x09, 0x00, + 0x09, 0x4C, 0x59, 0x59, 0x40, 0x10, 0x40, 0x3D, 0x38, 0x35, + 0x26, 0x26, 0x33, 0x11, 0x13, 0x3B, 0x11, 0x11, 0x10, 0x0B, + 0x05, 0x1D, 0x2B, 0x17, 0x21, 0x35, 0x21, 0x05, 0x33, 0x11, + 0x34, 0x26, 0x2F, 0x01, 0x2E, 0x01, 0x07, 0x15, 0x14, 0x06, + 0x23, 0x21, 0x22, 0x26, 0x27, 0x35, 0x23, 0x11, 0x33, 0x35, + 0x34, 0x36, 0x33, 0x21, 0x32, 0x16, 0x07, 0x03, 0x35, 0x34, + 0x26, 0x2B, 0x01, 0x22, 0x06, 0x17, 0x15, 0x14, 0x16, 0x3B, + 0x01, 0x32, 0x36, 0x05, 0x11, 0x14, 0x06, 0x23, 0x21, 0x22, + 0x26, 0x27, 0x11, 0x34, 0x36, 0x33, 0x21, 0x32, 0x16, 0x1F, + 0x01, 0x1E, 0x01, 0xD6, 0x01, 0xAD, 0xFE, 0x53, 0x01, 0xF4, + 0x48, 0x0C, 0x05, 0x9D, 0x05, 0x1C, 0x08, 0x1E, 0x17, 0xFE, + 0xBE, 0x16, 0x1E, 0x01, 0x48, 0x48, 0x20, 0x15, 0x01, 0xD1, + 0x16, 0x20, 0x01, 0xD6, 0x0A, 0x08, 0x6B, 0x07, 0x0C, 0x01, + 0x0A, 0x08, 0x6B, 0x07, 0x0C, 0x01, 0x64, 0x1E, 0x17, 0xFD, + 0x12, 0x17, 0x1E, 0x01, 0x20, 0x16, 0x02, 0x05, 0x17, 0x36, + 0x0F, 0x9C, 0x10, 0x16, 0x07, 0xD6, 0xD6, 0x01, 0xF4, 0x08, + 0x1A, 0x07, 0x9C, 0x06, 0x0C, 0x01, 0xE8, 0x16, 0x20, 0x20, + 0x16, 0xE8, 0xFD, 0x36, 0xE8, 0x16, 0x20, 0x20, 0x16, 0x01, + 0x1E, 0xB2, 0x08, 0x0A, 0x0A, 0x08, 0xB2, 0x08, 0x0A, 0x0A, + 0x0A, 0xFD, 0xFA, 0x16, 0x20, 0x20, 0x16, 0x02, 0xEE, 0x16, + 0x20, 0x18, 0x0E, 0x9D, 0x0F, 0x36, 0x00, 0x00, 0x00, 0x03, + 0x00, 0x00, 0xFF, 0xF9, 0x04, 0x29, 0x03, 0x0B, 0x00, 0x11, + 0x00, 0x27, 0x00, 0x45, 0x00, 0xA8, 0xB5, 0x24, 0x01, 0x01, + 0x00, 0x01, 0x47, 0x4B, 0xB0, 0x0A, 0x50, 0x58, 0x40, 0x27, + 0x00, 0x07, 0x00, 0x03, 0x02, 0x07, 0x03, 0x60, 0x08, 0x09, + 0x02, 0x02, 0x00, 0x00, 0x01, 0x02, 0x00, 0x60, 0x00, 0x04, + 0x04, 0x06, 0x58, 0x00, 0x06, 0x06, 0x0C, 0x48, 0x00, 0x01, + 0x01, 0x05, 0x58, 0x00, 0x05, 0x05, 0x0F, 0x05, 0x49, 0x1B, + 0x4B, 0xB0, 0x0D, 0x50, 0x58, 0x40, 0x27, 0x00, 0x07, 0x00, + 0x03, 0x02, 0x07, 0x03, 0x60, 0x08, 0x09, 0x02, 0x02, 0x00, + 0x00, 0x01, 0x02, 0x00, 0x60, 0x00, 0x04, 0x04, 0x06, 0x58, + 0x00, 0x06, 0x06, 0x0D, 0x48, 0x00, 0x01, 0x01, 0x05, 0x58, + 0x00, 0x05, 0x05, 0x0F, 0x05, 0x49, 0x1B, 0x40, 0x25, 0x00, + 0x06, 0x00, 0x04, 0x07, 0x06, 0x04, 0x60, 0x00, 0x07, 0x00, + 0x03, 0x02, 0x07, 0x03, 0x60, 0x08, 0x09, 0x02, 0x02, 0x00, + 0x00, 0x01, 0x02, 0x00, 0x60, 0x00, 0x01, 0x01, 0x05, 0x58, + 0x00, 0x05, 0x05, 0x0F, 0x05, 0x49, 0x59, 0x59, 0x40, 0x17, + 0x13, 0x12, 0x42, 0x40, 0x3D, 0x3B, 0x38, 0x35, 0x30, 0x2D, + 0x21, 0x1E, 0x19, 0x16, 0x12, 0x27, 0x13, 0x27, 0x36, 0x31, + 0x0A, 0x05, 0x16, 0x2B, 0x01, 0x34, 0x23, 0x21, 0x22, 0x06, + 0x0F, 0x01, 0x06, 0x15, 0x14, 0x33, 0x21, 0x32, 0x36, 0x3F, + 0x01, 0x36, 0x25, 0x21, 0x35, 0x34, 0x26, 0x07, 0x21, 0x22, + 0x26, 0x27, 0x35, 0x34, 0x26, 0x07, 0x23, 0x22, 0x06, 0x15, + 0x11, 0x37, 0x3E, 0x01, 0x05, 0x14, 0x0F, 0x01, 0x0E, 0x01, + 0x23, 0x21, 0x22, 0x26, 0x35, 0x11, 0x34, 0x36, 0x3B, 0x01, + 0x32, 0x16, 0x1D, 0x01, 0x21, 0x32, 0x16, 0x1D, 0x01, 0x33, + 0x32, 0x16, 0x17, 0x16, 0x03, 0xE2, 0x1E, 0xFD, 0xA1, 0x16, + 0x34, 0x0D, 0xA4, 0x0B, 0x1E, 0x02, 0x5F, 0x16, 0x34, 0x0E, + 0xA4, 0x0A, 0xFD, 0x83, 0x01, 0xAD, 0x20, 0x16, 0xFE, 0xBF, + 0x17, 0x1E, 0x01, 0x1E, 0x17, 0xB3, 0x16, 0x20, 0x8F, 0x19, + 0x50, 0x02, 0xEA, 0x19, 0xA5, 0x18, 0x52, 0x25, 0xFD, 0xA1, + 0x33, 0x4A, 0x4A, 0x33, 0xB3, 0x33, 0x4A, 0x01, 0x2F, 0x33, + 0x4A, 0x6B, 0x1E, 0x34, 0x0B, 0x08, 0x01, 0x4A, 0x14, 0x18, + 0x11, 0xCB, 0x0D, 0x09, 0x14, 0x1A, 0x10, 0xCB, 0x0C, 0x64, + 0x5A, 0x16, 0x20, 0x01, 0x20, 0x16, 0x24, 0x16, 0x20, 0x01, + 0x1E, 0x17, 0xFE, 0x24, 0xAF, 0x1E, 0x26, 0x5B, 0x22, 0x20, + 0xCB, 0x1E, 0x26, 0x4A, 0x33, 0x02, 0x18, 0x33, 0x4A, 0x4A, + 0x33, 0x12, 0x4A, 0x33, 0x5A, 0x1A, 0x1B, 0x11, 0x00, 0x00, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xE7, 0x29, + 0x04, 0xD1, 0x5F, 0x0F, 0x3C, 0xF5, 0x00, 0x0B, 0x03, 0xE8, + 0x00, 0x00, 0x00, 0x00, 0xD3, 0x84, 0x65, 0x65, 0x00, 0x00, + 0x00, 0x00, 0xD3, 0x84, 0x65, 0x65, 0xFF, 0xFD, 0xFF, 0x6A, + 0x04, 0x2F, 0x03, 0x52, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x03, 0x52, 0xFF, 0x6A, 0x00, 0x00, 0x04, 0x2F, 0xFF, 0xFD, + 0xFF, 0xFE, 0x04, 0x2F, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x11, 0x03, 0xE8, 0x00, 0x00, 0x03, 0x11, 0x00, 0x00, + 0x03, 0x59, 0x00, 0x00, 0x03, 0x59, 0x00, 0x00, 0x02, 0x3B, + 0xFF, 0xFF, 0x03, 0xE8, 0xFF, 0xFF, 0x02, 0x3B, 0x00, 0x00, + 0x03, 0xE8, 0x00, 0x00, 0x03, 0xA0, 0xFF, 0xFF, 0x03, 0xA0, + 0x00, 0x00, 0x03, 0x11, 0xFF, 0xFD, 0x03, 0x59, 0x00, 0x00, + 0x03, 0x59, 0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x04, 0x2F, + 0x00, 0x00, 0x03, 0x59, 0x00, 0x00, 0x04, 0x2F, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x5C, 0x00, 0xB6, + 0x01, 0x0A, 0x01, 0x76, 0x01, 0xCA, 0x02, 0x36, 0x02, 0x68, + 0x02, 0x9C, 0x02, 0xE2, 0x03, 0x94, 0x04, 0x30, 0x04, 0xC6, + 0x06, 0xBA, 0x07, 0x7C, 0x08, 0x35, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x11, 0x00, 0xF4, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x02, 0x00, 0x1E, 0x00, 0x2E, 0x00, 0x73, 0x00, 0x00, + 0x00, 0xAC, 0x0B, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x12, 0x00, 0xDE, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x01, 0x00, 0x06, 0x00, 0x35, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x07, 0x00, 0x3B, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x06, + 0x00, 0x42, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, + 0x00, 0x06, 0x00, 0x48, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x05, 0x00, 0x0B, 0x00, 0x4E, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x59, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x2B, 0x00, 0x5F, + 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x00, 0x13, + 0x00, 0x8A, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x00, + 0x00, 0x6A, 0x00, 0x9D, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, + 0x00, 0x01, 0x00, 0x0C, 0x01, 0x07, 0x00, 0x03, 0x00, 0x01, + 0x04, 0x09, 0x00, 0x02, 0x00, 0x0E, 0x01, 0x13, 0x00, 0x03, + 0x00, 0x01, 0x04, 0x09, 0x00, 0x03, 0x00, 0x0C, 0x01, 0x21, + 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x04, 0x00, 0x0C, + 0x01, 0x2D, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x05, + 0x00, 0x16, 0x01, 0x39, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, + 0x00, 0x06, 0x00, 0x0C, 0x01, 0x4F, 0x00, 0x03, 0x00, 0x01, + 0x04, 0x09, 0x00, 0x0A, 0x00, 0x56, 0x01, 0x5B, 0x00, 0x03, + 0x00, 0x01, 0x04, 0x09, 0x00, 0x0B, 0x00, 0x26, 0x01, 0xB1, + 0x43, 0x6F, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, + 0x28, 0x43, 0x29, 0x20, 0x32, 0x30, 0x31, 0x36, 0x20, 0x62, + 0x79, 0x20, 0x6F, 0x72, 0x69, 0x67, 0x69, 0x6E, 0x61, 0x6C, + 0x20, 0x61, 0x75, 0x74, 0x68, 0x6F, 0x72, 0x73, 0x20, 0x40, + 0x20, 0x66, 0x6F, 0x6E, 0x74, 0x65, 0x6C, 0x6C, 0x6F, 0x2E, + 0x63, 0x6F, 0x6D, 0x67, 0x66, 0x78, 0x5F, 0x75, 0x69, 0x52, + 0x65, 0x67, 0x75, 0x6C, 0x61, 0x72, 0x67, 0x66, 0x78, 0x5F, + 0x75, 0x69, 0x67, 0x66, 0x78, 0x5F, 0x75, 0x69, 0x56, 0x65, + 0x72, 0x73, 0x69, 0x6F, 0x6E, 0x20, 0x31, 0x2E, 0x30, 0x67, + 0x66, 0x78, 0x5F, 0x75, 0x69, 0x47, 0x65, 0x6E, 0x65, 0x72, + 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x73, 0x76, + 0x67, 0x32, 0x74, 0x74, 0x66, 0x20, 0x66, 0x72, 0x6F, 0x6D, + 0x20, 0x46, 0x6F, 0x6E, 0x74, 0x65, 0x6C, 0x6C, 0x6F, 0x20, + 0x70, 0x72, 0x6F, 0x6A, 0x65, 0x63, 0x74, 0x2E, 0x68, 0x74, + 0x74, 0x70, 0x3A, 0x2F, 0x2F, 0x66, 0x6F, 0x6E, 0x74, 0x65, + 0x6C, 0x6C, 0x6F, 0x2E, 0x63, 0x6F, 0x6D, 0x00, 0x43, 0x00, + 0x6F, 0x00, 0x70, 0x00, 0x79, 0x00, 0x72, 0x00, 0x69, 0x00, + 0x67, 0x00, 0x68, 0x00, 0x74, 0x00, 0x20, 0x00, 0x28, 0x00, + 0x43, 0x00, 0x29, 0x00, 0x20, 0x00, 0x32, 0x00, 0x30, 0x00, + 0x31, 0x00, 0x36, 0x00, 0x20, 0x00, 0x62, 0x00, 0x79, 0x00, + 0x20, 0x00, 0x6F, 0x00, 0x72, 0x00, 0x69, 0x00, 0x67, 0x00, + 0x69, 0x00, 0x6E, 0x00, 0x61, 0x00, 0x6C, 0x00, 0x20, 0x00, + 0x61, 0x00, 0x75, 0x00, 0x74, 0x00, 0x68, 0x00, 0x6F, 0x00, + 0x72, 0x00, 0x73, 0x00, 0x20, 0x00, 0x40, 0x00, 0x20, 0x00, + 0x66, 0x00, 0x6F, 0x00, 0x6E, 0x00, 0x74, 0x00, 0x65, 0x00, + 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x2E, 0x00, 0x63, 0x00, + 0x6F, 0x00, 0x6D, 0x00, 0x67, 0x00, 0x66, 0x00, 0x78, 0x00, + 0x5F, 0x00, 0x75, 0x00, 0x69, 0x00, 0x52, 0x00, 0x65, 0x00, + 0x67, 0x00, 0x75, 0x00, 0x6C, 0x00, 0x61, 0x00, 0x72, 0x00, + 0x67, 0x00, 0x66, 0x00, 0x78, 0x00, 0x5F, 0x00, 0x75, 0x00, + 0x69, 0x00, 0x67, 0x00, 0x66, 0x00, 0x78, 0x00, 0x5F, 0x00, + 0x75, 0x00, 0x69, 0x00, 0x56, 0x00, 0x65, 0x00, 0x72, 0x00, + 0x73, 0x00, 0x69, 0x00, 0x6F, 0x00, 0x6E, 0x00, 0x20, 0x00, + 0x31, 0x00, 0x2E, 0x00, 0x30, 0x00, 0x67, 0x00, 0x66, 0x00, + 0x78, 0x00, 0x5F, 0x00, 0x75, 0x00, 0x69, 0x00, 0x47, 0x00, + 0x65, 0x00, 0x6E, 0x00, 0x65, 0x00, 0x72, 0x00, 0x61, 0x00, + 0x74, 0x00, 0x65, 0x00, 0x64, 0x00, 0x20, 0x00, 0x62, 0x00, + 0x79, 0x00, 0x20, 0x00, 0x73, 0x00, 0x76, 0x00, 0x67, 0x00, + 0x32, 0x00, 0x74, 0x00, 0x74, 0x00, 0x66, 0x00, 0x20, 0x00, + 0x66, 0x00, 0x72, 0x00, 0x6F, 0x00, 0x6D, 0x00, 0x20, 0x00, + 0x46, 0x00, 0x6F, 0x00, 0x6E, 0x00, 0x74, 0x00, 0x65, 0x00, + 0x6C, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x20, 0x00, 0x70, 0x00, + 0x72, 0x00, 0x6F, 0x00, 0x6A, 0x00, 0x65, 0x00, 0x63, 0x00, + 0x74, 0x00, 0x2E, 0x00, 0x68, 0x00, 0x74, 0x00, 0x74, 0x00, + 0x70, 0x00, 0x3A, 0x00, 0x2F, 0x00, 0x2F, 0x00, 0x66, 0x00, + 0x6F, 0x00, 0x6E, 0x00, 0x74, 0x00, 0x65, 0x00, 0x6C, 0x00, + 0x6C, 0x00, 0x6F, 0x00, 0x2E, 0x00, 0x63, 0x00, 0x6F, 0x00, + 0x6D, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x01, 0x02, + 0x01, 0x03, 0x01, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01, 0x07, + 0x01, 0x08, 0x01, 0x09, 0x01, 0x0A, 0x01, 0x0B, 0x01, 0x0C, + 0x01, 0x0D, 0x01, 0x0E, 0x01, 0x0F, 0x01, 0x10, 0x01, 0x11, + 0x01, 0x12, 0x00, 0x04, 0x70, 0x6C, 0x61, 0x79, 0x04, 0x73, + 0x74, 0x6F, 0x70, 0x05, 0x70, 0x61, 0x75, 0x73, 0x65, 0x06, + 0x74, 0x6F, 0x2D, 0x65, 0x6E, 0x64, 0x0A, 0x74, 0x6F, 0x2D, + 0x65, 0x6E, 0x64, 0x2D, 0x61, 0x6C, 0x74, 0x08, 0x74, 0x6F, + 0x2D, 0x73, 0x74, 0x61, 0x72, 0x74, 0x0C, 0x74, 0x6F, 0x2D, + 0x73, 0x74, 0x61, 0x72, 0x74, 0x2D, 0x61, 0x6C, 0x74, 0x07, + 0x66, 0x61, 0x73, 0x74, 0x2D, 0x66, 0x77, 0x07, 0x66, 0x61, + 0x73, 0x74, 0x2D, 0x62, 0x77, 0x09, 0x64, 0x69, 0x72, 0x65, + 0x63, 0x74, 0x69, 0x6F, 0x6E, 0x06, 0x70, 0x65, 0x6E, 0x63, + 0x69, 0x6C, 0x0F, 0x72, 0x65, 0x73, 0x69, 0x7A, 0x65, 0x2D, + 0x66, 0x75, 0x6C, 0x6C, 0x2D, 0x61, 0x6C, 0x74, 0x0A, 0x65, + 0x79, 0x65, 0x64, 0x72, 0x6F, 0x70, 0x70, 0x65, 0x72, 0x07, + 0x63, 0x6F, 0x67, 0x2D, 0x61, 0x6C, 0x74, 0x06, 0x66, 0x6C, + 0x6F, 0x70, 0x70, 0x79, 0x11, 0x66, 0x6F, 0x6C, 0x64, 0x65, + 0x72, 0x2D, 0x6F, 0x70, 0x65, 0x6E, 0x2D, 0x65, 0x6D, 0x70, + 0x74, 0x79, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0xFF, 0xFF, + 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, + 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x03, 0x0B, 0x03, 0x0B, + 0xFF, 0xB1, 0xFF, 0xF9, 0x03, 0x52, 0xFF, 0x6A, 0x03, 0x52, + 0x03, 0x49, 0xFF, 0x72, 0xFF, 0xF9, 0x03, 0x52, 0xFF, 0x6A, + 0xB0, 0x00, 0x2C, 0x20, 0xB0, 0x00, 0x55, 0x58, 0x45, 0x59, + 0x20, 0x20, 0x4B, 0xB8, 0x00, 0x0E, 0x51, 0x4B, 0xB0, 0x06, + 0x53, 0x5A, 0x58, 0xB0, 0x34, 0x1B, 0xB0, 0x28, 0x59, 0x60, + 0x66, 0x20, 0x8A, 0x55, 0x58, 0xB0, 0x02, 0x25, 0x61, 0xB9, + 0x08, 0x00, 0x08, 0x00, 0x63, 0x63, 0x23, 0x62, 0x1B, 0x21, + 0x21, 0xB0, 0x00, 0x59, 0xB0, 0x00, 0x43, 0x23, 0x44, 0xB2, + 0x00, 0x01, 0x00, 0x43, 0x60, 0x42, 0x2D, 0xB0, 0x01, 0x2C, + 0xB0, 0x20, 0x60, 0x66, 0x2D, 0xB0, 0x02, 0x2C, 0x20, 0x64, + 0x20, 0xB0, 0xC0, 0x50, 0xB0, 0x04, 0x26, 0x5A, 0xB2, 0x28, + 0x01, 0x0A, 0x43, 0x45, 0x63, 0x45, 0x52, 0x5B, 0x58, 0x21, + 0x23, 0x21, 0x1B, 0x8A, 0x58, 0x20, 0xB0, 0x50, 0x50, 0x58, + 0x21, 0xB0, 0x40, 0x59, 0x1B, 0x20, 0xB0, 0x38, 0x50, 0x58, + 0x21, 0xB0, 0x38, 0x59, 0x59, 0x20, 0xB1, 0x01, 0x0A, 0x43, + 0x45, 0x63, 0x45, 0x61, 0x64, 0xB0, 0x28, 0x50, 0x58, 0x21, + 0xB1, 0x01, 0x0A, 0x43, 0x45, 0x63, 0x45, 0x20, 0xB0, 0x30, + 0x50, 0x58, 0x21, 0xB0, 0x30, 0x59, 0x1B, 0x20, 0xB0, 0xC0, + 0x50, 0x58, 0x20, 0x66, 0x20, 0x8A, 0x8A, 0x61, 0x20, 0xB0, + 0x0A, 0x50, 0x58, 0x60, 0x1B, 0x20, 0xB0, 0x20, 0x50, 0x58, + 0x21, 0xB0, 0x0A, 0x60, 0x1B, 0x20, 0xB0, 0x36, 0x50, 0x58, + 0x21, 0xB0, 0x36, 0x60, 0x1B, 0x60, 0x59, 0x59, 0x59, 0x1B, + 0xB0, 0x01, 0x2B, 0x59, 0x59, 0x23, 0xB0, 0x00, 0x50, 0x58, + 0x65, 0x59, 0x59, 0x2D, 0xB0, 0x03, 0x2C, 0x20, 0x45, 0x20, + 0xB0, 0x04, 0x25, 0x61, 0x64, 0x20, 0xB0, 0x05, 0x43, 0x50, + 0x58, 0xB0, 0x05, 0x23, 0x42, 0xB0, 0x06, 0x23, 0x42, 0x1B, + 0x21, 0x21, 0x59, 0xB0, 0x01, 0x60, 0x2D, 0xB0, 0x04, 0x2C, + 0x23, 0x21, 0x23, 0x21, 0x20, 0x64, 0xB1, 0x05, 0x62, 0x42, + 0x20, 0xB0, 0x06, 0x23, 0x42, 0xB1, 0x01, 0x0A, 0x43, 0x45, + 0x63, 0xB1, 0x01, 0x0A, 0x43, 0xB0, 0x01, 0x60, 0x45, 0x63, + 0xB0, 0x03, 0x2A, 0x21, 0x20, 0xB0, 0x06, 0x43, 0x20, 0x8A, + 0x20, 0x8A, 0xB0, 0x01, 0x2B, 0xB1, 0x30, 0x05, 0x25, 0xB0, + 0x04, 0x26, 0x51, 0x58, 0x60, 0x50, 0x1B, 0x61, 0x52, 0x59, + 0x58, 0x23, 0x59, 0x21, 0x20, 0xB0, 0x40, 0x53, 0x58, 0xB0, + 0x01, 0x2B, 0x1B, 0x21, 0xB0, 0x40, 0x59, 0x23, 0xB0, 0x00, + 0x50, 0x58, 0x65, 0x59, 0x2D, 0xB0, 0x05, 0x2C, 0xB0, 0x07, + 0x43, 0x2B, 0xB2, 0x00, 0x02, 0x00, 0x43, 0x60, 0x42, 0x2D, + 0xB0, 0x06, 0x2C, 0xB0, 0x07, 0x23, 0x42, 0x23, 0x20, 0xB0, + 0x00, 0x23, 0x42, 0x61, 0xB0, 0x02, 0x62, 0x66, 0xB0, 0x01, + 0x63, 0xB0, 0x01, 0x60, 0xB0, 0x05, 0x2A, 0x2D, 0xB0, 0x07, + 0x2C, 0x20, 0x20, 0x45, 0x20, 0xB0, 0x0B, 0x43, 0x63, 0xB8, + 0x04, 0x00, 0x62, 0x20, 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, + 0x60, 0x59, 0x66, 0xB0, 0x01, 0x63, 0x60, 0x44, 0xB0, 0x01, + 0x60, 0x2D, 0xB0, 0x08, 0x2C, 0xB2, 0x07, 0x0B, 0x00, 0x43, + 0x45, 0x42, 0x2A, 0x21, 0xB2, 0x00, 0x01, 0x00, 0x43, 0x60, + 0x42, 0x2D, 0xB0, 0x09, 0x2C, 0xB0, 0x00, 0x43, 0x23, 0x44, + 0xB2, 0x00, 0x01, 0x00, 0x43, 0x60, 0x42, 0x2D, 0xB0, 0x0A, + 0x2C, 0x20, 0x20, 0x45, 0x20, 0xB0, 0x01, 0x2B, 0x23, 0xB0, + 0x00, 0x43, 0xB0, 0x04, 0x25, 0x60, 0x20, 0x45, 0x8A, 0x23, + 0x61, 0x20, 0x64, 0x20, 0xB0, 0x20, 0x50, 0x58, 0x21, 0xB0, + 0x00, 0x1B, 0xB0, 0x30, 0x50, 0x58, 0xB0, 0x20, 0x1B, 0xB0, + 0x40, 0x59, 0x59, 0x23, 0xB0, 0x00, 0x50, 0x58, 0x65, 0x59, + 0xB0, 0x03, 0x25, 0x23, 0x61, 0x44, 0x44, 0xB0, 0x01, 0x60, + 0x2D, 0xB0, 0x0B, 0x2C, 0x20, 0x20, 0x45, 0x20, 0xB0, 0x01, + 0x2B, 0x23, 0xB0, 0x00, 0x43, 0xB0, 0x04, 0x25, 0x60, 0x20, + 0x45, 0x8A, 0x23, 0x61, 0x20, 0x64, 0xB0, 0x24, 0x50, 0x58, + 0xB0, 0x00, 0x1B, 0xB0, 0x40, 0x59, 0x23, 0xB0, 0x00, 0x50, + 0x58, 0x65, 0x59, 0xB0, 0x03, 0x25, 0x23, 0x61, 0x44, 0x44, + 0xB0, 0x01, 0x60, 0x2D, 0xB0, 0x0C, 0x2C, 0x20, 0xB0, 0x00, + 0x23, 0x42, 0xB2, 0x0B, 0x0A, 0x03, 0x45, 0x58, 0x21, 0x1B, + 0x23, 0x21, 0x59, 0x2A, 0x21, 0x2D, 0xB0, 0x0D, 0x2C, 0xB1, + 0x02, 0x02, 0x45, 0xB0, 0x64, 0x61, 0x44, 0x2D, 0xB0, 0x0E, + 0x2C, 0xB0, 0x01, 0x60, 0x20, 0x20, 0xB0, 0x0C, 0x43, 0x4A, + 0xB0, 0x00, 0x50, 0x58, 0x20, 0xB0, 0x0C, 0x23, 0x42, 0x59, + 0xB0, 0x0D, 0x43, 0x4A, 0xB0, 0x00, 0x52, 0x58, 0x20, 0xB0, + 0x0D, 0x23, 0x42, 0x59, 0x2D, 0xB0, 0x0F, 0x2C, 0x20, 0xB0, + 0x10, 0x62, 0x66, 0xB0, 0x01, 0x63, 0x20, 0xB8, 0x04, 0x00, + 0x63, 0x8A, 0x23, 0x61, 0xB0, 0x0E, 0x43, 0x60, 0x20, 0x8A, + 0x60, 0x20, 0xB0, 0x0E, 0x23, 0x42, 0x23, 0x2D, 0xB0, 0x10, + 0x2C, 0x4B, 0x54, 0x58, 0xB1, 0x04, 0x64, 0x44, 0x59, 0x24, + 0xB0, 0x0D, 0x65, 0x23, 0x78, 0x2D, 0xB0, 0x11, 0x2C, 0x4B, + 0x51, 0x58, 0x4B, 0x53, 0x58, 0xB1, 0x04, 0x64, 0x44, 0x59, + 0x1B, 0x21, 0x59, 0x24, 0xB0, 0x13, 0x65, 0x23, 0x78, 0x2D, + 0xB0, 0x12, 0x2C, 0xB1, 0x00, 0x0F, 0x43, 0x55, 0x58, 0xB1, + 0x0F, 0x0F, 0x43, 0xB0, 0x01, 0x61, 0x42, 0xB0, 0x0F, 0x2B, + 0x59, 0xB0, 0x00, 0x43, 0xB0, 0x02, 0x25, 0x42, 0xB1, 0x0C, + 0x02, 0x25, 0x42, 0xB1, 0x0D, 0x02, 0x25, 0x42, 0xB0, 0x01, + 0x16, 0x23, 0x20, 0xB0, 0x03, 0x25, 0x50, 0x58, 0xB1, 0x01, + 0x00, 0x43, 0x60, 0xB0, 0x04, 0x25, 0x42, 0x8A, 0x8A, 0x20, + 0x8A, 0x23, 0x61, 0xB0, 0x0E, 0x2A, 0x21, 0x23, 0xB0, 0x01, + 0x61, 0x20, 0x8A, 0x23, 0x61, 0xB0, 0x0E, 0x2A, 0x21, 0x1B, + 0xB1, 0x01, 0x00, 0x43, 0x60, 0xB0, 0x02, 0x25, 0x42, 0xB0, + 0x02, 0x25, 0x61, 0xB0, 0x0E, 0x2A, 0x21, 0x59, 0xB0, 0x0C, + 0x43, 0x47, 0xB0, 0x0D, 0x43, 0x47, 0x60, 0xB0, 0x02, 0x62, + 0x20, 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, 0x60, 0x59, 0x66, + 0xB0, 0x01, 0x63, 0x20, 0xB0, 0x0B, 0x43, 0x63, 0xB8, 0x04, + 0x00, 0x62, 0x20, 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, 0x60, + 0x59, 0x66, 0xB0, 0x01, 0x63, 0x60, 0xB1, 0x00, 0x00, 0x13, + 0x23, 0x44, 0xB0, 0x01, 0x43, 0xB0, 0x00, 0x3E, 0xB2, 0x01, + 0x01, 0x01, 0x43, 0x60, 0x42, 0x2D, 0xB0, 0x13, 0x2C, 0x00, + 0xB1, 0x00, 0x02, 0x45, 0x54, 0x58, 0xB0, 0x0F, 0x23, 0x42, + 0x20, 0x45, 0xB0, 0x0B, 0x23, 0x42, 0xB0, 0x0A, 0x23, 0xB0, + 0x01, 0x60, 0x42, 0x20, 0x60, 0xB0, 0x01, 0x61, 0xB5, 0x10, + 0x10, 0x01, 0x00, 0x0E, 0x00, 0x42, 0x42, 0x8A, 0x60, 0xB1, + 0x12, 0x06, 0x2B, 0xB0, 0x72, 0x2B, 0x1B, 0x22, 0x59, 0x2D, + 0xB0, 0x14, 0x2C, 0xB1, 0x00, 0x13, 0x2B, 0x2D, 0xB0, 0x15, + 0x2C, 0xB1, 0x01, 0x13, 0x2B, 0x2D, 0xB0, 0x16, 0x2C, 0xB1, + 0x02, 0x13, 0x2B, 0x2D, 0xB0, 0x17, 0x2C, 0xB1, 0x03, 0x13, + 0x2B, 0x2D, 0xB0, 0x18, 0x2C, 0xB1, 0x04, 0x13, 0x2B, 0x2D, + 0xB0, 0x19, 0x2C, 0xB1, 0x05, 0x13, 0x2B, 0x2D, 0xB0, 0x1A, + 0x2C, 0xB1, 0x06, 0x13, 0x2B, 0x2D, 0xB0, 0x1B, 0x2C, 0xB1, + 0x07, 0x13, 0x2B, 0x2D, 0xB0, 0x1C, 0x2C, 0xB1, 0x08, 0x13, + 0x2B, 0x2D, 0xB0, 0x1D, 0x2C, 0xB1, 0x09, 0x13, 0x2B, 0x2D, + 0xB0, 0x1E, 0x2C, 0x00, 0xB0, 0x0D, 0x2B, 0xB1, 0x00, 0x02, + 0x45, 0x54, 0x58, 0xB0, 0x0F, 0x23, 0x42, 0x20, 0x45, 0xB0, + 0x0B, 0x23, 0x42, 0xB0, 0x0A, 0x23, 0xB0, 0x01, 0x60, 0x42, + 0x20, 0x60, 0xB0, 0x01, 0x61, 0xB5, 0x10, 0x10, 0x01, 0x00, + 0x0E, 0x00, 0x42, 0x42, 0x8A, 0x60, 0xB1, 0x12, 0x06, 0x2B, + 0xB0, 0x72, 0x2B, 0x1B, 0x22, 0x59, 0x2D, 0xB0, 0x1F, 0x2C, + 0xB1, 0x00, 0x1E, 0x2B, 0x2D, 0xB0, 0x20, 0x2C, 0xB1, 0x01, + 0x1E, 0x2B, 0x2D, 0xB0, 0x21, 0x2C, 0xB1, 0x02, 0x1E, 0x2B, + 0x2D, 0xB0, 0x22, 0x2C, 0xB1, 0x03, 0x1E, 0x2B, 0x2D, 0xB0, + 0x23, 0x2C, 0xB1, 0x04, 0x1E, 0x2B, 0x2D, 0xB0, 0x24, 0x2C, + 0xB1, 0x05, 0x1E, 0x2B, 0x2D, 0xB0, 0x25, 0x2C, 0xB1, 0x06, + 0x1E, 0x2B, 0x2D, 0xB0, 0x26, 0x2C, 0xB1, 0x07, 0x1E, 0x2B, + 0x2D, 0xB0, 0x27, 0x2C, 0xB1, 0x08, 0x1E, 0x2B, 0x2D, 0xB0, + 0x28, 0x2C, 0xB1, 0x09, 0x1E, 0x2B, 0x2D, 0xB0, 0x29, 0x2C, + 0x20, 0x3C, 0xB0, 0x01, 0x60, 0x2D, 0xB0, 0x2A, 0x2C, 0x20, + 0x60, 0xB0, 0x10, 0x60, 0x20, 0x43, 0x23, 0xB0, 0x01, 0x60, + 0x43, 0xB0, 0x02, 0x25, 0x61, 0xB0, 0x01, 0x60, 0xB0, 0x29, + 0x2A, 0x21, 0x2D, 0xB0, 0x2B, 0x2C, 0xB0, 0x2A, 0x2B, 0xB0, + 0x2A, 0x2A, 0x2D, 0xB0, 0x2C, 0x2C, 0x20, 0x20, 0x47, 0x20, + 0x20, 0xB0, 0x0B, 0x43, 0x63, 0xB8, 0x04, 0x00, 0x62, 0x20, + 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, 0x60, 0x59, 0x66, 0xB0, + 0x01, 0x63, 0x60, 0x23, 0x61, 0x38, 0x23, 0x20, 0x8A, 0x55, + 0x58, 0x20, 0x47, 0x20, 0x20, 0xB0, 0x0B, 0x43, 0x63, 0xB8, + 0x04, 0x00, 0x62, 0x20, 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, + 0x60, 0x59, 0x66, 0xB0, 0x01, 0x63, 0x60, 0x23, 0x61, 0x38, + 0x1B, 0x21, 0x59, 0x2D, 0xB0, 0x2D, 0x2C, 0x00, 0xB1, 0x00, + 0x02, 0x45, 0x54, 0x58, 0xB0, 0x01, 0x16, 0xB0, 0x2C, 0x2A, + 0xB0, 0x01, 0x15, 0x30, 0x1B, 0x22, 0x59, 0x2D, 0xB0, 0x2E, + 0x2C, 0x00, 0xB0, 0x0D, 0x2B, 0xB1, 0x00, 0x02, 0x45, 0x54, + 0x58, 0xB0, 0x01, 0x16, 0xB0, 0x2C, 0x2A, 0xB0, 0x01, 0x15, + 0x30, 0x1B, 0x22, 0x59, 0x2D, 0xB0, 0x2F, 0x2C, 0x20, 0x35, + 0xB0, 0x01, 0x60, 0x2D, 0xB0, 0x30, 0x2C, 0x00, 0xB0, 0x01, + 0x45, 0x63, 0xB8, 0x04, 0x00, 0x62, 0x20, 0xB0, 0x00, 0x50, + 0x58, 0xB0, 0x40, 0x60, 0x59, 0x66, 0xB0, 0x01, 0x63, 0xB0, + 0x01, 0x2B, 0xB0, 0x0B, 0x43, 0x63, 0xB8, 0x04, 0x00, 0x62, + 0x20, 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, 0x60, 0x59, 0x66, + 0xB0, 0x01, 0x63, 0xB0, 0x01, 0x2B, 0xB0, 0x00, 0x16, 0xB4, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0x3E, 0x23, 0x38, 0xB1, + 0x2F, 0x01, 0x15, 0x2A, 0x2D, 0xB0, 0x31, 0x2C, 0x20, 0x3C, + 0x20, 0x47, 0x20, 0xB0, 0x0B, 0x43, 0x63, 0xB8, 0x04, 0x00, + 0x62, 0x20, 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, 0x60, 0x59, + 0x66, 0xB0, 0x01, 0x63, 0x60, 0xB0, 0x00, 0x43, 0x61, 0x38, + 0x2D, 0xB0, 0x32, 0x2C, 0x2E, 0x17, 0x3C, 0x2D, 0xB0, 0x33, + 0x2C, 0x20, 0x3C, 0x20, 0x47, 0x20, 0xB0, 0x0B, 0x43, 0x63, + 0xB8, 0x04, 0x00, 0x62, 0x20, 0xB0, 0x00, 0x50, 0x58, 0xB0, + 0x40, 0x60, 0x59, 0x66, 0xB0, 0x01, 0x63, 0x60, 0xB0, 0x00, + 0x43, 0x61, 0xB0, 0x01, 0x43, 0x63, 0x38, 0x2D, 0xB0, 0x34, + 0x2C, 0xB1, 0x02, 0x00, 0x16, 0x25, 0x20, 0x2E, 0x20, 0x47, + 0xB0, 0x00, 0x23, 0x42, 0xB0, 0x02, 0x25, 0x49, 0x8A, 0x8A, + 0x47, 0x23, 0x47, 0x23, 0x61, 0x20, 0x58, 0x62, 0x1B, 0x21, + 0x59, 0xB0, 0x01, 0x23, 0x42, 0xB2, 0x33, 0x01, 0x01, 0x15, + 0x14, 0x2A, 0x2D, 0xB0, 0x35, 0x2C, 0xB0, 0x00, 0x16, 0xB0, + 0x04, 0x25, 0xB0, 0x04, 0x25, 0x47, 0x23, 0x47, 0x23, 0x61, + 0xB0, 0x09, 0x43, 0x2B, 0x65, 0x8A, 0x2E, 0x23, 0x20, 0x20, + 0x3C, 0x8A, 0x38, 0x2D, 0xB0, 0x36, 0x2C, 0xB0, 0x00, 0x16, + 0xB0, 0x04, 0x25, 0xB0, 0x04, 0x25, 0x20, 0x2E, 0x47, 0x23, + 0x47, 0x23, 0x61, 0x20, 0xB0, 0x04, 0x23, 0x42, 0xB0, 0x09, + 0x43, 0x2B, 0x20, 0xB0, 0x60, 0x50, 0x58, 0x20, 0xB0, 0x40, + 0x51, 0x58, 0xB3, 0x02, 0x20, 0x03, 0x20, 0x1B, 0xB3, 0x02, + 0x26, 0x03, 0x1A, 0x59, 0x42, 0x42, 0x23, 0x20, 0xB0, 0x08, + 0x43, 0x20, 0x8A, 0x23, 0x47, 0x23, 0x47, 0x23, 0x61, 0x23, + 0x46, 0x60, 0xB0, 0x04, 0x43, 0xB0, 0x02, 0x62, 0x20, 0xB0, + 0x00, 0x50, 0x58, 0xB0, 0x40, 0x60, 0x59, 0x66, 0xB0, 0x01, + 0x63, 0x60, 0x20, 0xB0, 0x01, 0x2B, 0x20, 0x8A, 0x8A, 0x61, + 0x20, 0xB0, 0x02, 0x43, 0x60, 0x64, 0x23, 0xB0, 0x03, 0x43, + 0x61, 0x64, 0x50, 0x58, 0xB0, 0x02, 0x43, 0x61, 0x1B, 0xB0, + 0x03, 0x43, 0x60, 0x59, 0xB0, 0x03, 0x25, 0xB0, 0x02, 0x62, + 0x20, 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, 0x60, 0x59, 0x66, + 0xB0, 0x01, 0x63, 0x61, 0x23, 0x20, 0x20, 0xB0, 0x04, 0x26, + 0x23, 0x46, 0x61, 0x38, 0x1B, 0x23, 0xB0, 0x08, 0x43, 0x46, + 0xB0, 0x02, 0x25, 0xB0, 0x08, 0x43, 0x47, 0x23, 0x47, 0x23, + 0x61, 0x60, 0x20, 0xB0, 0x04, 0x43, 0xB0, 0x02, 0x62, 0x20, + 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, 0x60, 0x59, 0x66, 0xB0, + 0x01, 0x63, 0x60, 0x23, 0x20, 0xB0, 0x01, 0x2B, 0x23, 0xB0, + 0x04, 0x43, 0x60, 0xB0, 0x01, 0x2B, 0xB0, 0x05, 0x25, 0x61, + 0xB0, 0x05, 0x25, 0xB0, 0x02, 0x62, 0x20, 0xB0, 0x00, 0x50, + 0x58, 0xB0, 0x40, 0x60, 0x59, 0x66, 0xB0, 0x01, 0x63, 0xB0, + 0x04, 0x26, 0x61, 0x20, 0xB0, 0x04, 0x25, 0x60, 0x64, 0x23, + 0xB0, 0x03, 0x25, 0x60, 0x64, 0x50, 0x58, 0x21, 0x1B, 0x23, + 0x21, 0x59, 0x23, 0x20, 0x20, 0xB0, 0x04, 0x26, 0x23, 0x46, + 0x61, 0x38, 0x59, 0x2D, 0xB0, 0x37, 0x2C, 0xB0, 0x00, 0x16, + 0x20, 0x20, 0x20, 0xB0, 0x05, 0x26, 0x20, 0x2E, 0x47, 0x23, + 0x47, 0x23, 0x61, 0x23, 0x3C, 0x38, 0x2D, 0xB0, 0x38, 0x2C, + 0xB0, 0x00, 0x16, 0x20, 0xB0, 0x08, 0x23, 0x42, 0x20, 0x20, + 0x20, 0x46, 0x23, 0x47, 0xB0, 0x01, 0x2B, 0x23, 0x61, 0x38, + 0x2D, 0xB0, 0x39, 0x2C, 0xB0, 0x00, 0x16, 0xB0, 0x03, 0x25, + 0xB0, 0x02, 0x25, 0x47, 0x23, 0x47, 0x23, 0x61, 0xB0, 0x00, + 0x54, 0x58, 0x2E, 0x20, 0x3C, 0x23, 0x21, 0x1B, 0xB0, 0x02, + 0x25, 0xB0, 0x02, 0x25, 0x47, 0x23, 0x47, 0x23, 0x61, 0x20, + 0xB0, 0x05, 0x25, 0xB0, 0x04, 0x25, 0x47, 0x23, 0x47, 0x23, + 0x61, 0xB0, 0x06, 0x25, 0xB0, 0x05, 0x25, 0x49, 0xB0, 0x02, + 0x25, 0x61, 0xB9, 0x08, 0x00, 0x08, 0x00, 0x63, 0x63, 0x23, + 0x20, 0x58, 0x62, 0x1B, 0x21, 0x59, 0x63, 0xB8, 0x04, 0x00, + 0x62, 0x20, 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, 0x60, 0x59, + 0x66, 0xB0, 0x01, 0x63, 0x60, 0x23, 0x2E, 0x23, 0x20, 0x20, + 0x3C, 0x8A, 0x38, 0x23, 0x21, 0x59, 0x2D, 0xB0, 0x3A, 0x2C, + 0xB0, 0x00, 0x16, 0x20, 0xB0, 0x08, 0x43, 0x20, 0x2E, 0x47, + 0x23, 0x47, 0x23, 0x61, 0x20, 0x60, 0xB0, 0x20, 0x60, 0x66, + 0xB0, 0x02, 0x62, 0x20, 0xB0, 0x00, 0x50, 0x58, 0xB0, 0x40, + 0x60, 0x59, 0x66, 0xB0, 0x01, 0x63, 0x23, 0x20, 0x20, 0x3C, + 0x8A, 0x38, 0x2D, 0xB0, 0x3B, 0x2C, 0x23, 0x20, 0x2E, 0x46, + 0xB0, 0x02, 0x25, 0x46, 0x52, 0x58, 0x20, 0x3C, 0x59, 0x2E, + 0xB1, 0x2B, 0x01, 0x14, 0x2B, 0x2D, 0xB0, 0x3C, 0x2C, 0x23, + 0x20, 0x2E, 0x46, 0xB0, 0x02, 0x25, 0x46, 0x50, 0x58, 0x20, + 0x3C, 0x59, 0x2E, 0xB1, 0x2B, 0x01, 0x14, 0x2B, 0x2D, 0xB0, + 0x3D, 0x2C, 0x23, 0x20, 0x2E, 0x46, 0xB0, 0x02, 0x25, 0x46, + 0x52, 0x58, 0x20, 0x3C, 0x59, 0x23, 0x20, 0x2E, 0x46, 0xB0, + 0x02, 0x25, 0x46, 0x50, 0x58, 0x20, 0x3C, 0x59, 0x2E, 0xB1, + 0x2B, 0x01, 0x14, 0x2B, 0x2D, 0xB0, 0x3E, 0x2C, 0xB0, 0x35, + 0x2B, 0x23, 0x20, 0x2E, 0x46, 0xB0, 0x02, 0x25, 0x46, 0x52, + 0x58, 0x20, 0x3C, 0x59, 0x2E, 0xB1, 0x2B, 0x01, 0x14, 0x2B, + 0x2D, 0xB0, 0x3F, 0x2C, 0xB0, 0x36, 0x2B, 0x8A, 0x20, 0x20, + 0x3C, 0xB0, 0x04, 0x23, 0x42, 0x8A, 0x38, 0x23, 0x20, 0x2E, + 0x46, 0xB0, 0x02, 0x25, 0x46, 0x52, 0x58, 0x20, 0x3C, 0x59, + 0x2E, 0xB1, 0x2B, 0x01, 0x14, 0x2B, 0xB0, 0x04, 0x43, 0x2E, + 0xB0, 0x2B, 0x2B, 0x2D, 0xB0, 0x40, 0x2C, 0xB0, 0x00, 0x16, + 0xB0, 0x04, 0x25, 0xB0, 0x04, 0x26, 0x20, 0x2E, 0x47, 0x23, + 0x47, 0x23, 0x61, 0xB0, 0x09, 0x43, 0x2B, 0x23, 0x20, 0x3C, + 0x20, 0x2E, 0x23, 0x38, 0xB1, 0x2B, 0x01, 0x14, 0x2B, 0x2D, + 0xB0, 0x41, 0x2C, 0xB1, 0x08, 0x04, 0x25, 0x42, 0xB0, 0x00, + 0x16, 0xB0, 0x04, 0x25, 0xB0, 0x04, 0x25, 0x20, 0x2E, 0x47, + 0x23, 0x47, 0x23, 0x61, 0x20, 0xB0, 0x04, 0x23, 0x42, 0xB0, + 0x09, 0x43, 0x2B, 0x20, 0xB0, 0x60, 0x50, 0x58, 0x20, 0xB0, + 0x40, 0x51, 0x58, 0xB3, 0x02, 0x20, 0x03, 0x20, 0x1B, 0xB3, + 0x02, 0x26, 0x03, 0x1A, 0x59, 0x42, 0x42, 0x23, 0x20, 0x47, + 0xB0, 0x04, 0x43, 0xB0, 0x02, 0x62, 0x20, 0xB0, 0x00, 0x50, + 0x58, 0xB0, 0x40, 0x60, 0x59, 0x66, 0xB0, 0x01, 0x63, 0x60, + 0x20, 0xB0, 0x01, 0x2B, 0x20, 0x8A, 0x8A, 0x61, 0x20, 0xB0, + 0x02, 0x43, 0x60, 0x64, 0x23, 0xB0, 0x03, 0x43, 0x61, 0x64, + 0x50, 0x58, 0xB0, 0x02, 0x43, 0x61, 0x1B, 0xB0, 0x03, 0x43, + 0x60, 0x59, 0xB0, 0x03, 0x25, 0xB0, 0x02, 0x62, 0x20, 0xB0, + 0x00, 0x50, 0x58, 0xB0, 0x40, 0x60, 0x59, 0x66, 0xB0, 0x01, + 0x63, 0x61, 0xB0, 0x02, 0x25, 0x46, 0x61, 0x38, 0x23, 0x20, + 0x3C, 0x23, 0x38, 0x1B, 0x21, 0x20, 0x20, 0x46, 0x23, 0x47, + 0xB0, 0x01, 0x2B, 0x23, 0x61, 0x38, 0x21, 0x59, 0xB1, 0x2B, + 0x01, 0x14, 0x2B, 0x2D, 0xB0, 0x42, 0x2C, 0xB0, 0x35, 0x2B, + 0x2E, 0xB1, 0x2B, 0x01, 0x14, 0x2B, 0x2D, 0xB0, 0x43, 0x2C, + 0xB0, 0x36, 0x2B, 0x21, 0x23, 0x20, 0x20, 0x3C, 0xB0, 0x04, + 0x23, 0x42, 0x23, 0x38, 0xB1, 0x2B, 0x01, 0x14, 0x2B, 0xB0, + 0x04, 0x43, 0x2E, 0xB0, 0x2B, 0x2B, 0x2D, 0xB0, 0x44, 0x2C, + 0xB0, 0x00, 0x15, 0x20, 0x47, 0xB0, 0x00, 0x23, 0x42, 0xB2, + 0x00, 0x01, 0x01, 0x15, 0x14, 0x13, 0x2E, 0xB0, 0x31, 0x2A, + 0x2D, 0xB0, 0x45, 0x2C, 0xB0, 0x00, 0x15, 0x20, 0x47, 0xB0, + 0x00, 0x23, 0x42, 0xB2, 0x00, 0x01, 0x01, 0x15, 0x14, 0x13, + 0x2E, 0xB0, 0x31, 0x2A, 0x2D, 0xB0, 0x46, 0x2C, 0xB1, 0x00, + 0x01, 0x14, 0x13, 0xB0, 0x32, 0x2A, 0x2D, 0xB0, 0x47, 0x2C, + 0xB0, 0x34, 0x2A, 0x2D, 0xB0, 0x48, 0x2C, 0xB0, 0x00, 0x16, + 0x45, 0x23, 0x20, 0x2E, 0x20, 0x46, 0x8A, 0x23, 0x61, 0x38, + 0xB1, 0x2B, 0x01, 0x14, 0x2B, 0x2D, 0xB0, 0x49, 0x2C, 0xB0, + 0x08, 0x23, 0x42, 0xB0, 0x48, 0x2B, 0x2D, 0xB0, 0x4A, 0x2C, + 0xB2, 0x00, 0x00, 0x41, 0x2B, 0x2D, 0xB0, 0x4B, 0x2C, 0xB2, + 0x00, 0x01, 0x41, 0x2B, 0x2D, 0xB0, 0x4C, 0x2C, 0xB2, 0x01, + 0x00, 0x41, 0x2B, 0x2D, 0xB0, 0x4D, 0x2C, 0xB2, 0x01, 0x01, + 0x41, 0x2B, 0x2D, 0xB0, 0x4E, 0x2C, 0xB2, 0x00, 0x00, 0x42, + 0x2B, 0x2D, 0xB0, 0x4F, 0x2C, 0xB2, 0x00, 0x01, 0x42, 0x2B, + 0x2D, 0xB0, 0x50, 0x2C, 0xB2, 0x01, 0x00, 0x42, 0x2B, 0x2D, + 0xB0, 0x51, 0x2C, 0xB2, 0x01, 0x01, 0x42, 0x2B, 0x2D, 0xB0, + 0x52, 0x2C, 0xB2, 0x00, 0x00, 0x3E, 0x2B, 0x2D, 0xB0, 0x53, + 0x2C, 0xB2, 0x00, 0x01, 0x3E, 0x2B, 0x2D, 0xB0, 0x54, 0x2C, + 0xB2, 0x01, 0x00, 0x3E, 0x2B, 0x2D, 0xB0, 0x55, 0x2C, 0xB2, + 0x01, 0x01, 0x3E, 0x2B, 0x2D, 0xB0, 0x56, 0x2C, 0xB2, 0x00, + 0x00, 0x40, 0x2B, 0x2D, 0xB0, 0x57, 0x2C, 0xB2, 0x00, 0x01, + 0x40, 0x2B, 0x2D, 0xB0, 0x58, 0x2C, 0xB2, 0x01, 0x00, 0x40, + 0x2B, 0x2D, 0xB0, 0x59, 0x2C, 0xB2, 0x01, 0x01, 0x40, 0x2B, + 0x2D, 0xB0, 0x5A, 0x2C, 0xB2, 0x00, 0x00, 0x43, 0x2B, 0x2D, + 0xB0, 0x5B, 0x2C, 0xB2, 0x00, 0x01, 0x43, 0x2B, 0x2D, 0xB0, + 0x5C, 0x2C, 0xB2, 0x01, 0x00, 0x43, 0x2B, 0x2D, 0xB0, 0x5D, + 0x2C, 0xB2, 0x01, 0x01, 0x43, 0x2B, 0x2D, 0xB0, 0x5E, 0x2C, + 0xB2, 0x00, 0x00, 0x3F, 0x2B, 0x2D, 0xB0, 0x5F, 0x2C, 0xB2, + 0x00, 0x01, 0x3F, 0x2B, 0x2D, 0xB0, 0x60, 0x2C, 0xB2, 0x01, + 0x00, 0x3F, 0x2B, 0x2D, 0xB0, 0x61, 0x2C, 0xB2, 0x01, 0x01, + 0x3F, 0x2B, 0x2D, 0xB0, 0x62, 0x2C, 0xB0, 0x37, 0x2B, 0x2E, + 0xB1, 0x2B, 0x01, 0x14, 0x2B, 0x2D, 0xB0, 0x63, 0x2C, 0xB0, + 0x37, 0x2B, 0xB0, 0x3B, 0x2B, 0x2D, 0xB0, 0x64, 0x2C, 0xB0, + 0x37, 0x2B, 0xB0, 0x3C, 0x2B, 0x2D, 0xB0, 0x65, 0x2C, 0xB0, + 0x00, 0x16, 0xB0, 0x37, 0x2B, 0xB0, 0x3D, 0x2B, 0x2D, 0xB0, + 0x66, 0x2C, 0xB0, 0x38, 0x2B, 0x2E, 0xB1, 0x2B, 0x01, 0x14, + 0x2B, 0x2D, 0xB0, 0x67, 0x2C, 0xB0, 0x38, 0x2B, 0xB0, 0x3B, + 0x2B, 0x2D, 0xB0, 0x68, 0x2C, 0xB0, 0x38, 0x2B, 0xB0, 0x3C, + 0x2B, 0x2D, 0xB0, 0x69, 0x2C, 0xB0, 0x38, 0x2B, 0xB0, 0x3D, + 0x2B, 0x2D, 0xB0, 0x6A, 0x2C, 0xB0, 0x39, 0x2B, 0x2E, 0xB1, + 0x2B, 0x01, 0x14, 0x2B, 0x2D, 0xB0, 0x6B, 0x2C, 0xB0, 0x39, + 0x2B, 0xB0, 0x3B, 0x2B, 0x2D, 0xB0, 0x6C, 0x2C, 0xB0, 0x39, + 0x2B, 0xB0, 0x3C, 0x2B, 0x2D, 0xB0, 0x6D, 0x2C, 0xB0, 0x39, + 0x2B, 0xB0, 0x3D, 0x2B, 0x2D, 0xB0, 0x6E, 0x2C, 0xB0, 0x3A, + 0x2B, 0x2E, 0xB1, 0x2B, 0x01, 0x14, 0x2B, 0x2D, 0xB0, 0x6F, + 0x2C, 0xB0, 0x3A, 0x2B, 0xB0, 0x3B, 0x2B, 0x2D, 0xB0, 0x70, + 0x2C, 0xB0, 0x3A, 0x2B, 0xB0, 0x3C, 0x2B, 0x2D, 0xB0, 0x71, + 0x2C, 0xB0, 0x3A, 0x2B, 0xB0, 0x3D, 0x2B, 0x2D, 0xB0, 0x72, + 0x2C, 0xB3, 0x09, 0x04, 0x02, 0x03, 0x45, 0x58, 0x21, 0x1B, + 0x23, 0x21, 0x59, 0x42, 0x2B, 0xB0, 0x08, 0x65, 0xB0, 0x03, + 0x24, 0x50, 0x78, 0xB0, 0x01, 0x15, 0x30, 0x2D, 0x00, 0x4B, + 0xB8, 0x00, 0xC8, 0x52, 0x58, 0xB1, 0x01, 0x01, 0x8E, 0x59, + 0xB0, 0x01, 0xB9, 0x08, 0x00, 0x08, 0x00, 0x63, 0x70, 0xB1, + 0x00, 0x05, 0x42, 0xB2, 0x13, 0x01, 0x00, 0x2A, 0xB1, 0x00, + 0x05, 0x42, 0xB3, 0x0A, 0x06, 0x01, 0x08, 0x2A, 0xB1, 0x00, + 0x05, 0x42, 0xB3, 0x12, 0x04, 0x01, 0x08, 0x2A, 0xB1, 0x00, + 0x06, 0x42, 0xBA, 0x02, 0xC0, 0x00, 0x01, 0x00, 0x09, 0x2A, + 0xB1, 0x00, 0x07, 0x42, 0xBA, 0x00, 0x40, 0x00, 0x01, 0x00, + 0x09, 0x2A, 0xB1, 0x03, 0x00, 0x44, 0xB1, 0x24, 0x01, 0x88, + 0x51, 0x58, 0xB0, 0x40, 0x88, 0x58, 0xB1, 0x03, 0x64, 0x44, + 0xB1, 0x26, 0x01, 0x88, 0x51, 0x58, 0xBA, 0x08, 0x80, 0x00, + 0x01, 0x04, 0x40, 0x88, 0x63, 0x54, 0x58, 0xB1, 0x03, 0x00, + 0x44, 0x59, 0x59, 0x59, 0x59, 0xB3, 0x0C, 0x06, 0x01, 0x0C, + 0x2A, 0xB8, 0x01, 0xFF, 0x85, 0xB0, 0x04, 0x8D, 0xB1, 0x02, + 0x00, 0x44, 0x00, 0x00 + }; + + + +} diff --git a/src/gl2ps.c b/src/gl2ps.c new file mode 100644 index 0000000..c6c6d41 --- /dev/null +++ b/src/gl2ps.c @@ -0,0 +1,6181 @@ +/* + * GL2PS, an OpenGL to PostScript Printing Library + * Copyright (C) 1999-2015 C. Geuzaine + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of either: + * + * a) the GNU Library General Public License as published by the Free + * Software Foundation, either version 2 of the License, or (at your + * option) any later version; or + * + * b) the GL2PS License as published by Christophe Geuzaine, either + * version 2 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either + * the GNU Library General Public License or the GL2PS License for + * more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library in the file named "COPYING.LGPL"; + * if not, write to the Free Software Foundation, Inc., 51 Franklin + * Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * You should have received a copy of the GL2PS License with this + * library in the file named "COPYING.GL2PS"; if not, I will be glad + * to provide one. + * + * For the latest info about gl2ps and a full list of contributors, + * see http://www.geuz.org/gl2ps/. + * + * Please report all bugs and problems to <gl2ps@geuz.org>. + */ + +#include "gl2ps.h" + +#include <math.h> +#include <string.h> +#include <sys/types.h> +#include <stdarg.h> +#include <time.h> +#include <float.h> + +#if defined(GL2PS_HAVE_ZLIB) +#include <zlib.h> +#endif + +#if defined(GL2PS_HAVE_LIBPNG) +#include <png.h> +#endif + +/********************************************************************* + * + * Private definitions, data structures and prototypes + * + *********************************************************************/ + +/* Magic numbers (assuming that the order of magnitude of window + coordinates is 10^3) */ + +#define GL2PS_EPSILON 5.0e-3F +#define GL2PS_ZSCALE 1000.0F +#define GL2PS_ZOFFSET 5.0e-2F +#define GL2PS_ZOFFSET_LARGE 20.0F +#define GL2PS_ZERO(arg) (fabs(arg) < 1.e-20) + +/* Primitive types */ + +#define GL2PS_NO_TYPE -1 +#define GL2PS_TEXT 1 +#define GL2PS_POINT 2 +#define GL2PS_LINE 3 +#define GL2PS_QUADRANGLE 4 +#define GL2PS_TRIANGLE 5 +#define GL2PS_PIXMAP 6 +#define GL2PS_IMAGEMAP 7 +#define GL2PS_IMAGEMAP_WRITTEN 8 +#define GL2PS_IMAGEMAP_VISIBLE 9 +#define GL2PS_SPECIAL 10 + +/* BSP tree primitive comparison */ + +#define GL2PS_COINCIDENT 1 +#define GL2PS_IN_FRONT_OF 2 +#define GL2PS_IN_BACK_OF 3 +#define GL2PS_SPANNING 4 + +/* 2D BSP tree primitive comparison */ + +#define GL2PS_POINT_COINCIDENT 0 +#define GL2PS_POINT_INFRONT 1 +#define GL2PS_POINT_BACK 2 + +/* Internal feedback buffer pass-through tokens */ + +#define GL2PS_BEGIN_OFFSET_TOKEN 1 +#define GL2PS_END_OFFSET_TOKEN 2 +#define GL2PS_BEGIN_BOUNDARY_TOKEN 3 +#define GL2PS_END_BOUNDARY_TOKEN 4 +#define GL2PS_BEGIN_STIPPLE_TOKEN 5 +#define GL2PS_END_STIPPLE_TOKEN 6 +#define GL2PS_POINT_SIZE_TOKEN 7 +#define GL2PS_LINE_WIDTH_TOKEN 8 +#define GL2PS_BEGIN_BLEND_TOKEN 9 +#define GL2PS_END_BLEND_TOKEN 10 +#define GL2PS_SRC_BLEND_TOKEN 11 +#define GL2PS_DST_BLEND_TOKEN 12 +#define GL2PS_IMAGEMAP_TOKEN 13 +#define GL2PS_DRAW_PIXELS_TOKEN 14 +#define GL2PS_TEXT_TOKEN 15 + +typedef enum { + T_UNDEFINED = -1, + T_CONST_COLOR = 1, + T_VAR_COLOR = 1<<1, + T_ALPHA_1 = 1<<2, + T_ALPHA_LESS_1 = 1<<3, + T_VAR_ALPHA = 1<<4 +} GL2PS_TRIANGLE_PROPERTY; + +typedef GLfloat GL2PSxyz[3]; +typedef GLfloat GL2PSplane[4]; + +typedef struct _GL2PSbsptree2d GL2PSbsptree2d; + +struct _GL2PSbsptree2d { + GL2PSplane plane; + GL2PSbsptree2d *front, *back; +}; + +typedef struct { + GLint nmax, size, incr, n; + char *array; +} GL2PSlist; + +typedef struct _GL2PSbsptree GL2PSbsptree; + +struct _GL2PSbsptree { + GL2PSplane plane; + GL2PSlist *primitives; + GL2PSbsptree *front, *back; +}; + +typedef struct { + GL2PSxyz xyz; + GL2PSrgba rgba; +} GL2PSvertex; + +typedef struct { + GL2PSvertex vertex[3]; + int prop; +} GL2PStriangle; + +typedef struct { + GLshort fontsize; + char *str, *fontname; + /* Note: for a 'special' string, 'alignment' holds the format + (PostScript, PDF, etc.) of the special string */ + GLint alignment; + GLfloat angle; +} GL2PSstring; + +typedef struct { + GLsizei width, height; + /* Note: for an imagemap, 'type' indicates if it has already been + written to the file or not, and 'format' indicates if it is + visible or not */ + GLenum format, type; + GLfloat zoom_x, zoom_y; + GLfloat *pixels; +} GL2PSimage; + +typedef struct _GL2PSimagemap GL2PSimagemap; + +struct _GL2PSimagemap { + GL2PSimage *image; + GL2PSimagemap *next; +}; + +typedef struct { + GLshort type, numverts; + GLushort pattern; + char boundary, offset, culled; + GLint factor; + GLfloat width, ofactor, ounits; + GL2PSvertex *verts; + union { + GL2PSstring *text; + GL2PSimage *image; + } data; +} GL2PSprimitive; + +typedef struct { +#if defined(GL2PS_HAVE_ZLIB) + Bytef *dest, *src, *start; + uLongf destLen, srcLen; +#else + int dummy; +#endif +} GL2PScompress; + +typedef struct{ + GL2PSlist* ptrlist; + int gsno, fontno, imno, shno, maskshno, trgroupno; + int gsobjno, fontobjno, imobjno, shobjno, maskshobjno, trgroupobjno; +} GL2PSpdfgroup; + +typedef struct { + /* General */ + GLint format, sort, options, colorsize, colormode, buffersize; + char *title, *producer, *filename; + GLboolean boundary, blending; + GLfloat *feedback, lastlinewidth; + GLint viewport[4], blendfunc[2], lastfactor; + GL2PSrgba *colormap, lastrgba, threshold, bgcolor; + GLushort lastpattern; + GL2PSvertex lastvertex; + GL2PSlist *primitives, *auxprimitives; + FILE *stream; + GL2PScompress *compress; + GLboolean header; + + /* BSP-specific */ + GLint maxbestroot; + + /* Occlusion culling-specific */ + GLboolean zerosurfacearea; + GL2PSbsptree2d *imagetree; + GL2PSprimitive *primitivetoadd; + + /* PDF-specific */ + int streamlength; + GL2PSlist *pdfprimlist, *pdfgrouplist; + int *xreflist; + int objects_stack; /* available objects */ + int extgs_stack; /* graphics state object number */ + int font_stack; /* font object number */ + int im_stack; /* image object number */ + int trgroupobjects_stack; /* xobject numbers */ + int shader_stack; /* shader object numbers */ + int mshader_stack; /* mask shader object numbers */ + + /* for image map list */ + GL2PSimagemap *imagemap_head; + GL2PSimagemap *imagemap_tail; +} GL2PScontext; + +typedef struct { + void (*printHeader)(void); + void (*printFooter)(void); + void (*beginViewport)(GLint viewport[4]); + GLint (*endViewport)(void); + void (*printPrimitive)(void *data); + void (*printFinalPrimitive)(void); + const char *file_extension; + const char *description; +} GL2PSbackend; + +/* The gl2ps context. gl2ps is not thread safe (we should create a + local GL2PScontext during gl2psBeginPage) */ + +static GL2PScontext *gl2ps = NULL; + +/* Need to forward-declare this one */ + +static GLint gl2psPrintPrimitives(void); + +/********************************************************************* + * + * Utility routines + * + *********************************************************************/ + +static void gl2psMsg(GLint level, const char *fmt, ...) +{ + va_list args; + + if(!(gl2ps->options & GL2PS_SILENT)){ + switch(level){ + case GL2PS_INFO : fprintf(stderr, "GL2PS info: "); break; + case GL2PS_WARNING : fprintf(stderr, "GL2PS warning: "); break; + case GL2PS_ERROR : fprintf(stderr, "GL2PS error: "); break; + } + va_start(args, fmt); + vfprintf(stderr, fmt, args); + va_end(args); + fprintf(stderr, "\n"); + } + /* if(level == GL2PS_ERROR) exit(1); */ +} + +static void *gl2psMalloc(size_t size) +{ + void *ptr; + + if(!size) return NULL; + ptr = malloc(size); + if(!ptr){ + gl2psMsg(GL2PS_ERROR, "Couldn't allocate requested memory"); + return NULL; + } + return ptr; +} + +static void *gl2psRealloc(void *ptr, size_t size) +{ + void *orig = ptr; + if(!size) return NULL; + ptr = realloc(orig, size); + if(!ptr){ + gl2psMsg(GL2PS_ERROR, "Couldn't reallocate requested memory"); + free(orig); + return NULL; + } + return ptr; +} + +static void gl2psFree(void *ptr) +{ + if(!ptr) return; + free(ptr); +} + +static int gl2psWriteBigEndian(unsigned long data, int bytes) +{ + int i; + int size = sizeof(unsigned long); + for(i = 1; i <= bytes; ++i){ + fputc(0xff & (data >> (size - i) * 8), gl2ps->stream); + } + return bytes; +} + +/* zlib compression helper routines */ + +#if defined(GL2PS_HAVE_ZLIB) + +static void gl2psSetupCompress(void) +{ + gl2ps->compress = (GL2PScompress*)gl2psMalloc(sizeof(GL2PScompress)); + gl2ps->compress->src = NULL; + gl2ps->compress->start = NULL; + gl2ps->compress->dest = NULL; + gl2ps->compress->srcLen = 0; + gl2ps->compress->destLen = 0; +} + +static void gl2psFreeCompress(void) +{ + if(!gl2ps->compress) + return; + gl2psFree(gl2ps->compress->start); + gl2psFree(gl2ps->compress->dest); + gl2ps->compress->src = NULL; + gl2ps->compress->start = NULL; + gl2ps->compress->dest = NULL; + gl2ps->compress->srcLen = 0; + gl2ps->compress->destLen = 0; +} + +static int gl2psAllocCompress(unsigned int srcsize) +{ + gl2psFreeCompress(); + + if(!gl2ps->compress || !srcsize) + return GL2PS_ERROR; + + gl2ps->compress->srcLen = srcsize; + gl2ps->compress->destLen = (int)ceil(1.001 * gl2ps->compress->srcLen + 12); + gl2ps->compress->src = (Bytef*)gl2psMalloc(gl2ps->compress->srcLen); + gl2ps->compress->start = gl2ps->compress->src; + gl2ps->compress->dest = (Bytef*)gl2psMalloc(gl2ps->compress->destLen); + + return GL2PS_SUCCESS; +} + +static void *gl2psReallocCompress(unsigned int srcsize) +{ + if(!gl2ps->compress || !srcsize) + return NULL; + + if(srcsize < gl2ps->compress->srcLen) + return gl2ps->compress->start; + + gl2ps->compress->srcLen = srcsize; + gl2ps->compress->destLen = (int)ceil(1.001 * gl2ps->compress->srcLen + 12); + gl2ps->compress->src = (Bytef*)gl2psRealloc(gl2ps->compress->src, + gl2ps->compress->srcLen); + gl2ps->compress->start = gl2ps->compress->src; + gl2ps->compress->dest = (Bytef*)gl2psRealloc(gl2ps->compress->dest, + gl2ps->compress->destLen); + + return gl2ps->compress->start; +} + +static int gl2psWriteBigEndianCompress(unsigned long data, int bytes) +{ + int i; + int size = sizeof(unsigned long); + for(i = 1; i <= bytes; ++i){ + *gl2ps->compress->src = (Bytef)(0xff & (data >> (size-i) * 8)); + ++gl2ps->compress->src; + } + return bytes; +} + +static int gl2psDeflate(void) +{ + /* For compatibility with older zlib versions, we use compress(...) + instead of compress2(..., Z_BEST_COMPRESSION) */ + return compress(gl2ps->compress->dest, &gl2ps->compress->destLen, + gl2ps->compress->start, gl2ps->compress->srcLen); +} + +#endif + +static int gl2psPrintf(const char* fmt, ...) +{ + int ret; + va_list args; + +#if defined(GL2PS_HAVE_ZLIB) + static char buf[1024]; + char *bufptr = buf; + GLboolean freebuf = GL_FALSE; + unsigned int oldsize = 0; +#if !defined(GL2PS_HAVE_NO_VSNPRINTF) + /* Try writing the string to a 1024 byte buffer. If it is too small to fit, + keep trying larger sizes until it does. */ + int bufsize = sizeof(buf); +#endif + if(gl2ps->options & GL2PS_COMPRESS){ + va_start(args, fmt); +#if defined(GL2PS_HAVE_NO_VSNPRINTF) + ret = vsprintf(buf, fmt, args); +#else + ret = vsnprintf(bufptr, bufsize, fmt, args); +#endif + va_end(args); +#if !defined(GL2PS_HAVE_NO_VSNPRINTF) + while(ret >= (bufsize - 1) || ret < 0){ + /* Too big. Allocate a new buffer. */ + bufsize *= 2; + if(freebuf == GL_TRUE) gl2psFree(bufptr); + bufptr = (char *)gl2psMalloc(bufsize); + freebuf = GL_TRUE; + va_start(args, fmt); + ret = vsnprintf(bufptr, bufsize, fmt, args); + va_end(args); + } +#endif + oldsize = gl2ps->compress->srcLen; + gl2ps->compress->start = (Bytef*)gl2psReallocCompress(oldsize + ret); + memcpy(gl2ps->compress->start + oldsize, bufptr, ret); + if(freebuf == GL_TRUE) gl2psFree(bufptr); + ret = 0; + } + else{ +#endif + va_start(args, fmt); + ret = vfprintf(gl2ps->stream, fmt, args); + va_end(args); +#if defined(GL2PS_HAVE_ZLIB) + } +#endif + return ret; +} + +static void gl2psPrintGzipHeader(void) +{ +#if defined(GL2PS_HAVE_ZLIB) + char tmp[10] = {'\x1f', '\x8b', /* magic numbers: 0x1f, 0x8b */ + 8, /* compression method: Z_DEFLATED */ + 0, /* flags */ + 0, 0, 0, 0, /* time */ + 2, /* extra flags: max compression */ + '\x03'}; /* OS code: 0x03 (Unix) */ + + if(gl2ps->options & GL2PS_COMPRESS){ + gl2psSetupCompress(); + /* add the gzip file header */ + fwrite(tmp, 10, 1, gl2ps->stream); + } +#endif +} + +static void gl2psPrintGzipFooter(void) +{ +#if defined(GL2PS_HAVE_ZLIB) + int n; + uLong crc, len; + char tmp[8]; + + if(gl2ps->options & GL2PS_COMPRESS){ + if(Z_OK != gl2psDeflate()){ + gl2psMsg(GL2PS_ERROR, "Zlib deflate error"); + } + else{ + /* determine the length of the header in the zlib stream */ + n = 2; /* CMF+FLG */ + if(gl2ps->compress->dest[1] & (1<<5)){ + n += 4; /* DICTID */ + } + /* write the data, without the zlib header and footer */ + fwrite(gl2ps->compress->dest+n, gl2ps->compress->destLen-(n+4), + 1, gl2ps->stream); + /* add the gzip file footer */ + crc = crc32(0L, gl2ps->compress->start, gl2ps->compress->srcLen); + for(n = 0; n < 4; ++n){ + tmp[n] = (char)(crc & 0xff); + crc >>= 8; + } + len = gl2ps->compress->srcLen; + for(n = 4; n < 8; ++n){ + tmp[n] = (char)(len & 0xff); + len >>= 8; + } + fwrite(tmp, 8, 1, gl2ps->stream); + } + gl2psFreeCompress(); + gl2psFree(gl2ps->compress); + gl2ps->compress = NULL; + } +#endif +} + +/* The list handling routines */ + +static void gl2psListRealloc(GL2PSlist *list, GLint n) +{ + if(!list){ + gl2psMsg(GL2PS_ERROR, "Cannot reallocate NULL list"); + return; + } + if(n <= 0) return; + if(!list->array){ + list->nmax = n; + list->array = (char*)gl2psMalloc(list->nmax * list->size); + } + else{ + if(n > list->nmax){ + list->nmax = ((n - 1) / list->incr + 1) * list->incr; + list->array = (char*)gl2psRealloc(list->array, + list->nmax * list->size); + } + } +} + +static GL2PSlist *gl2psListCreate(GLint n, GLint incr, GLint size) +{ + GL2PSlist *list; + + if(n < 0) n = 0; + if(incr <= 0) incr = 1; + list = (GL2PSlist*)gl2psMalloc(sizeof(GL2PSlist)); + list->nmax = 0; + list->incr = incr; + list->size = size; + list->n = 0; + list->array = NULL; + gl2psListRealloc(list, n); + return list; +} + +static void gl2psListReset(GL2PSlist *list) +{ + if(!list) return; + list->n = 0; +} + +static void gl2psListDelete(GL2PSlist *list) +{ + if(!list) return; + gl2psFree(list->array); + gl2psFree(list); +} + +static void gl2psListAdd(GL2PSlist *list, void *data) +{ + if(!list){ + gl2psMsg(GL2PS_ERROR, "Cannot add into unallocated list"); + return; + } + list->n++; + gl2psListRealloc(list, list->n); + memcpy(&list->array[(list->n - 1) * list->size], data, list->size); +} + +static int gl2psListNbr(GL2PSlist *list) +{ + if(!list) + return 0; + return list->n; +} + +static void *gl2psListPointer(GL2PSlist *list, GLint idx) +{ + if(!list){ + gl2psMsg(GL2PS_ERROR, "Cannot point into unallocated list"); + return NULL; + } + if((idx < 0) || (idx >= list->n)){ + gl2psMsg(GL2PS_ERROR, "Wrong list index in gl2psListPointer"); + return NULL; + } + return &list->array[idx * list->size]; +} + +static void gl2psListSort(GL2PSlist *list, + int (*fcmp)(const void *a, const void *b)) +{ + if(!list) + return; + qsort(list->array, list->n, list->size, fcmp); +} + +static void gl2psListAction(GL2PSlist *list, void (*action)(void *data)) +{ + GLint i; + + for(i = 0; i < gl2psListNbr(list); i++){ + (*action)(gl2psListPointer(list, i)); + } +} + +static void gl2psListActionInverse(GL2PSlist *list, void (*action)(void *data)) +{ + GLint i; + + for(i = gl2psListNbr(list); i > 0; i--){ + (*action)(gl2psListPointer(list, i-1)); + } +} + +#if defined(GL2PS_HAVE_LIBPNG) + +static void gl2psListRead(GL2PSlist *list, int index, void *data) +{ + if((index < 0) || (index >= list->n)) + gl2psMsg(GL2PS_ERROR, "Wrong list index in gl2psListRead"); + memcpy(data, &list->array[index * list->size], list->size); +} + +static void gl2psEncodeBase64Block(unsigned char in[3], unsigned char out[4], int len) +{ + static const char cb64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + out[0] = cb64[ in[0] >> 2 ]; + out[1] = cb64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ]; + out[2] = (len > 1) ? cb64[ ((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6) ] : '='; + out[3] = (len > 2) ? cb64[ in[2] & 0x3f ] : '='; +} + +static void gl2psListEncodeBase64(GL2PSlist *list) +{ + unsigned char *buffer, in[3], out[4]; + int i, n, index, len; + + n = list->n * list->size; + buffer = (unsigned char*)gl2psMalloc(n * sizeof(unsigned char)); + memcpy(buffer, list->array, n * sizeof(unsigned char)); + gl2psListReset(list); + + index = 0; + while(index < n) { + len = 0; + for(i = 0; i < 3; i++) { + if(index < n){ + in[i] = buffer[index]; + len++; + } + else{ + in[i] = 0; + } + index++; + } + if(len) { + gl2psEncodeBase64Block(in, out, len); + for(i = 0; i < 4; i++) + gl2psListAdd(list, &out[i]); + } + } + gl2psFree(buffer); +} + +#endif + +/* Helpers for rgba colors */ + +static GLboolean gl2psSameColor(GL2PSrgba rgba1, GL2PSrgba rgba2) +{ + if(!GL2PS_ZERO(rgba1[0] - rgba2[0]) || + !GL2PS_ZERO(rgba1[1] - rgba2[1]) || + !GL2PS_ZERO(rgba1[2] - rgba2[2])) + return GL_FALSE; + return GL_TRUE; +} + +static GLboolean gl2psVertsSameColor(const GL2PSprimitive *prim) +{ + int i; + + for(i = 1; i < prim->numverts; i++){ + if(!gl2psSameColor(prim->verts[0].rgba, prim->verts[i].rgba)){ + return GL_FALSE; + } + } + return GL_TRUE; +} + +static GLboolean gl2psSameColorThreshold(int n, GL2PSrgba rgba[], + GL2PSrgba threshold) +{ + int i; + + if(n < 2) return GL_TRUE; + + for(i = 1; i < n; i++){ + if(fabs(rgba[0][0] - rgba[i][0]) > threshold[0] || + fabs(rgba[0][1] - rgba[i][1]) > threshold[1] || + fabs(rgba[0][2] - rgba[i][2]) > threshold[2]) + return GL_FALSE; + } + + return GL_TRUE; +} + +static void gl2psSetLastColor(GL2PSrgba rgba) +{ + int i; + for(i = 0; i < 3; ++i){ + gl2ps->lastrgba[i] = rgba[i]; + } +} + +static GLfloat gl2psGetRGB(GL2PSimage *im, GLuint x, GLuint y, + GLfloat *red, GLfloat *green, GLfloat *blue) +{ + + GLsizei width = im->width; + GLsizei height = im->height; + GLfloat *pixels = im->pixels; + GLfloat *pimag; + + /* OpenGL image is from down to up, PS image is up to down */ + switch(im->format){ + case GL_RGBA: + pimag = pixels + 4 * (width * (height - 1 - y) + x); + break; + case GL_RGB: + default: + pimag = pixels + 3 * (width * (height - 1 - y) + x); + break; + } + *red = *pimag; pimag++; + *green = *pimag; pimag++; + *blue = *pimag; pimag++; + + return (im->format == GL_RGBA) ? *pimag : 1.0F; +} + +/* Helper routines for pixmaps */ + +static GL2PSimage *gl2psCopyPixmap(GL2PSimage *im) +{ + int size; + GL2PSimage *image = (GL2PSimage*)gl2psMalloc(sizeof(GL2PSimage)); + + image->width = im->width; + image->height = im->height; + image->format = im->format; + image->type = im->type; + image->zoom_x = im->zoom_x; + image->zoom_y = im->zoom_y; + + switch(image->format){ + case GL_RGBA: + size = image->height * image->width * 4 * sizeof(GLfloat); + break; + case GL_RGB: + default: + size = image->height * image->width * 3 * sizeof(GLfloat); + break; + } + + image->pixels = (GLfloat*)gl2psMalloc(size); + memcpy(image->pixels, im->pixels, size); + + return image; +} + +static void gl2psFreePixmap(GL2PSimage *im) +{ + if(!im) + return; + gl2psFree(im->pixels); + gl2psFree(im); +} + +#if defined(GL2PS_HAVE_LIBPNG) + +#if !defined(png_jmpbuf) +# define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf) +#endif + +static void gl2psUserWritePNG(png_structp png_ptr, png_bytep data, png_size_t length) +{ + unsigned int i; + GL2PSlist *png = (GL2PSlist*)png_get_io_ptr(png_ptr); + for(i = 0; i < length; i++) + gl2psListAdd(png, &data[i]); +} + +static void gl2psUserFlushPNG(png_structp png_ptr) +{ + (void) png_ptr; /* not used */ +} + +static void gl2psConvertPixmapToPNG(GL2PSimage *pixmap, GL2PSlist *png) +{ + png_structp png_ptr; + png_infop info_ptr; + unsigned char *row_data; + GLfloat dr, dg, db; + int row, col; + + if(!(png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL))) + return; + + if(!(info_ptr = png_create_info_struct(png_ptr))){ + png_destroy_write_struct(&png_ptr, NULL); + return; + } + + if(setjmp(png_jmpbuf(png_ptr))) { + png_destroy_write_struct(&png_ptr, &info_ptr); + return; + } + + png_set_write_fn(png_ptr, (void *)png, gl2psUserWritePNG, gl2psUserFlushPNG); + png_set_compression_level(png_ptr, Z_DEFAULT_COMPRESSION); + png_set_IHDR(png_ptr, info_ptr, pixmap->width, pixmap->height, 8, + PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, + PNG_FILTER_TYPE_BASE); + png_write_info(png_ptr, info_ptr); + + row_data = (unsigned char*)gl2psMalloc(3 * pixmap->width * sizeof(unsigned char)); + for(row = 0; row < pixmap->height; row++){ + for(col = 0; col < pixmap->width; col++){ + gl2psGetRGB(pixmap, col, row, &dr, &dg, &db); + row_data[3*col] = (unsigned char)(255. * dr); + row_data[3*col+1] = (unsigned char)(255. * dg); + row_data[3*col+2] = (unsigned char)(255. * db); + } + png_write_row(png_ptr, (png_bytep)row_data); + } + gl2psFree(row_data); + + png_write_end(png_ptr, info_ptr); + png_destroy_write_struct(&png_ptr, &info_ptr); +} + +#endif + +/* Helper routines for text strings */ + +static GLint gl2psAddText(GLint type, const char *str, const char *fontname, + GLshort fontsize, GLint alignment, GLfloat angle, + GL2PSrgba color) +{ + GLfloat pos[4]; + GL2PSprimitive *prim; + GLboolean valid; + + if(!gl2ps || !str || !fontname) return GL2PS_UNINITIALIZED; + + if(gl2ps->options & GL2PS_NO_TEXT) return GL2PS_SUCCESS; + + glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID, &valid); + if(GL_FALSE == valid) return GL2PS_SUCCESS; /* the primitive is culled */ + + glGetFloatv(GL_CURRENT_RASTER_POSITION, pos); + + prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); + prim->type = type; + prim->boundary = 0; + prim->numverts = 1; + prim->verts = (GL2PSvertex*)gl2psMalloc(sizeof(GL2PSvertex)); + prim->verts[0].xyz[0] = pos[0]; + prim->verts[0].xyz[1] = pos[1]; + prim->verts[0].xyz[2] = pos[2]; + prim->culled = 0; + prim->offset = 0; + prim->ofactor = 0.0; + prim->ounits = 0.0; + prim->pattern = 0; + prim->factor = 0; + prim->width = 1; + if (color) + memcpy(prim->verts[0].rgba, color, 4 * sizeof(float)); + else + glGetFloatv(GL_CURRENT_RASTER_COLOR, prim->verts[0].rgba); + prim->data.text = (GL2PSstring*)gl2psMalloc(sizeof(GL2PSstring)); + prim->data.text->str = (char*)gl2psMalloc((strlen(str)+1)*sizeof(char)); + strcpy(prim->data.text->str, str); + prim->data.text->fontname = (char*)gl2psMalloc((strlen(fontname)+1)*sizeof(char)); + strcpy(prim->data.text->fontname, fontname); + prim->data.text->fontsize = fontsize; + prim->data.text->alignment = alignment; + prim->data.text->angle = angle; + + gl2psListAdd(gl2ps->auxprimitives, &prim); + glPassThrough(GL2PS_TEXT_TOKEN); + + return GL2PS_SUCCESS; +} + +static GL2PSstring *gl2psCopyText(GL2PSstring *t) +{ + GL2PSstring *text = (GL2PSstring*)gl2psMalloc(sizeof(GL2PSstring)); + text->str = (char*)gl2psMalloc((strlen(t->str)+1)*sizeof(char)); + strcpy(text->str, t->str); + text->fontname = (char*)gl2psMalloc((strlen(t->fontname)+1)*sizeof(char)); + strcpy(text->fontname, t->fontname); + text->fontsize = t->fontsize; + text->alignment = t->alignment; + text->angle = t->angle; + + return text; +} + +static void gl2psFreeText(GL2PSstring *text) +{ + if(!text) + return; + gl2psFree(text->str); + gl2psFree(text->fontname); + gl2psFree(text); +} + +/* Helpers for blending modes */ + +static GLboolean gl2psSupportedBlendMode(GLenum sfactor, GLenum dfactor) +{ + /* returns TRUE if gl2ps supports the argument combination: only two + blending modes have been implemented so far */ + + if( (sfactor == GL_SRC_ALPHA && dfactor == GL_ONE_MINUS_SRC_ALPHA) || + (sfactor == GL_ONE && dfactor == GL_ZERO) ) + return GL_TRUE; + return GL_FALSE; +} + +static void gl2psAdaptVertexForBlending(GL2PSvertex *v) +{ + /* Transforms vertex depending on the actual blending function - + currently the vertex v is considered as source vertex and his + alpha value is changed to 1.0 if source blending GL_ONE is + active. This might be extended in the future */ + + if(!v || !gl2ps) + return; + + if(gl2ps->options & GL2PS_NO_BLENDING || !gl2ps->blending){ + v->rgba[3] = 1.0F; + return; + } + + switch(gl2ps->blendfunc[0]){ + case GL_ONE: + v->rgba[3] = 1.0F; + break; + default: + break; + } +} + +static void gl2psAssignTriangleProperties(GL2PStriangle *t) +{ + /* int i; */ + + t->prop = T_VAR_COLOR; + + /* Uncommenting the following lines activates an even more fine + grained distinction between triangle types - please don't delete, + a remarkable amount of PDF handling code inside this file depends + on it if activated */ + /* + t->prop = T_CONST_COLOR; + for(i = 0; i < 3; ++i){ + if(!GL2PS_ZERO(t->vertex[0].rgba[i] - t->vertex[1].rgba[i]) || + !GL2PS_ZERO(t->vertex[1].rgba[i] - t->vertex[2].rgba[i])){ + t->prop = T_VAR_COLOR; + break; + } + } + */ + + if(!GL2PS_ZERO(t->vertex[0].rgba[3] - t->vertex[1].rgba[3]) || + !GL2PS_ZERO(t->vertex[1].rgba[3] - t->vertex[2].rgba[3])){ + t->prop |= T_VAR_ALPHA; + } + else{ + if(t->vertex[0].rgba[3] < 1) + t->prop |= T_ALPHA_LESS_1; + else + t->prop |= T_ALPHA_1; + } +} + +static void gl2psFillTriangleFromPrimitive(GL2PStriangle *t, GL2PSprimitive *p, + GLboolean assignprops) +{ + t->vertex[0] = p->verts[0]; + t->vertex[1] = p->verts[1]; + t->vertex[2] = p->verts[2]; + if(GL_TRUE == assignprops) + gl2psAssignTriangleProperties(t); +} + +static void gl2psInitTriangle(GL2PStriangle *t) +{ + int i; + GL2PSvertex vertex = { {-1.0F, -1.0F, -1.0F}, {-1.0F, -1.0F, -1.0F, -1.0F} }; + for(i = 0; i < 3; i++) + t->vertex[i] = vertex; + t->prop = T_UNDEFINED; +} + +/* Miscellaneous helper routines */ + +static GL2PSprimitive *gl2psCopyPrimitive(GL2PSprimitive *p) +{ + GL2PSprimitive *prim; + + if(!p){ + gl2psMsg(GL2PS_ERROR, "Trying to copy an empty primitive"); + return NULL; + } + + prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); + + prim->type = p->type; + prim->numverts = p->numverts; + prim->boundary = p->boundary; + prim->offset = p->offset; + prim->ofactor = p->ofactor; + prim->ounits = p->ounits; + prim->pattern = p->pattern; + prim->factor = p->factor; + prim->culled = p->culled; + prim->width = p->width; + prim->verts = (GL2PSvertex*)gl2psMalloc(p->numverts*sizeof(GL2PSvertex)); + memcpy(prim->verts, p->verts, p->numverts * sizeof(GL2PSvertex)); + + switch(prim->type){ + case GL2PS_PIXMAP : + prim->data.image = gl2psCopyPixmap(p->data.image); + break; + case GL2PS_TEXT : + case GL2PS_SPECIAL : + prim->data.text = gl2psCopyText(p->data.text); + break; + default: + break; + } + + return prim; +} + +static GLboolean gl2psSamePosition(GL2PSxyz p1, GL2PSxyz p2) +{ + if(!GL2PS_ZERO(p1[0] - p2[0]) || + !GL2PS_ZERO(p1[1] - p2[1]) || + !GL2PS_ZERO(p1[2] - p2[2])) + return GL_FALSE; + return GL_TRUE; +} + +/********************************************************************* + * + * 3D sorting routines + * + *********************************************************************/ + +static GLfloat gl2psComparePointPlane(GL2PSxyz point, GL2PSplane plane) +{ + return (plane[0] * point[0] + + plane[1] * point[1] + + plane[2] * point[2] + + plane[3]); +} + +static GLfloat gl2psPsca(GLfloat *a, GLfloat *b) +{ + return (a[0]*b[0] + a[1]*b[1] + a[2]*b[2]); +} + +static void gl2psPvec(GLfloat *a, GLfloat *b, GLfloat *c) +{ + c[0] = a[1]*b[2] - a[2]*b[1]; + c[1] = a[2]*b[0] - a[0]*b[2]; + c[2] = a[0]*b[1] - a[1]*b[0]; +} + +static GLfloat gl2psNorm(GLfloat *a) +{ + return (GLfloat)sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2]); +} + +static void gl2psGetNormal(GLfloat *a, GLfloat *b, GLfloat *c) +{ + GLfloat norm; + + gl2psPvec(a, b, c); + if(!GL2PS_ZERO(norm = gl2psNorm(c))){ + c[0] = c[0] / norm; + c[1] = c[1] / norm; + c[2] = c[2] / norm; + } + else{ + /* The plane is still wrong despite our tests in gl2psGetPlane. + Let's return a dummy value for now (this is a hack: we should + do more intelligent tests in GetPlane) */ + c[0] = c[1] = 0.0F; + c[2] = 1.0F; + } +} + +static void gl2psGetPlane(GL2PSprimitive *prim, GL2PSplane plane) +{ + GL2PSxyz v = {0.0F, 0.0F, 0.0F}, w = {0.0F, 0.0F, 0.0F}; + + switch(prim->type){ + case GL2PS_TRIANGLE : + case GL2PS_QUADRANGLE : + v[0] = prim->verts[1].xyz[0] - prim->verts[0].xyz[0]; + v[1] = prim->verts[1].xyz[1] - prim->verts[0].xyz[1]; + v[2] = prim->verts[1].xyz[2] - prim->verts[0].xyz[2]; + w[0] = prim->verts[2].xyz[0] - prim->verts[0].xyz[0]; + w[1] = prim->verts[2].xyz[1] - prim->verts[0].xyz[1]; + w[2] = prim->verts[2].xyz[2] - prim->verts[0].xyz[2]; + if((GL2PS_ZERO(v[0]) && GL2PS_ZERO(v[1]) && GL2PS_ZERO(v[2])) || + (GL2PS_ZERO(w[0]) && GL2PS_ZERO(w[1]) && GL2PS_ZERO(w[2]))){ + plane[0] = plane[1] = 0.0F; + plane[2] = 1.0F; + plane[3] = -prim->verts[0].xyz[2]; + } + else{ + gl2psGetNormal(v, w, plane); + plane[3] = + - plane[0] * prim->verts[0].xyz[0] + - plane[1] * prim->verts[0].xyz[1] + - plane[2] * prim->verts[0].xyz[2]; + } + break; + case GL2PS_LINE : + v[0] = prim->verts[1].xyz[0] - prim->verts[0].xyz[0]; + v[1] = prim->verts[1].xyz[1] - prim->verts[0].xyz[1]; + v[2] = prim->verts[1].xyz[2] - prim->verts[0].xyz[2]; + if(GL2PS_ZERO(v[0]) && GL2PS_ZERO(v[1]) && GL2PS_ZERO(v[2])){ + plane[0] = plane[1] = 0.0F; + plane[2] = 1.0F; + plane[3] = -prim->verts[0].xyz[2]; + } + else{ + if(GL2PS_ZERO(v[0])) w[0] = 1.0F; + else if(GL2PS_ZERO(v[1])) w[1] = 1.0F; + else w[2] = 1.0F; + gl2psGetNormal(v, w, plane); + plane[3] = + - plane[0] * prim->verts[0].xyz[0] + - plane[1] * prim->verts[0].xyz[1] + - plane[2] * prim->verts[0].xyz[2]; + } + break; + case GL2PS_POINT : + case GL2PS_PIXMAP : + case GL2PS_TEXT : + case GL2PS_SPECIAL : + case GL2PS_IMAGEMAP: + plane[0] = plane[1] = 0.0F; + plane[2] = 1.0F; + plane[3] = -prim->verts[0].xyz[2]; + break; + default : + gl2psMsg(GL2PS_ERROR, "Unknown primitive type in BSP tree"); + plane[0] = plane[1] = plane[3] = 0.0F; + plane[2] = 1.0F; + break; + } +} + +static void gl2psCutEdge(GL2PSvertex *a, GL2PSvertex *b, GL2PSplane plane, + GL2PSvertex *c) +{ + GL2PSxyz v; + GLfloat sect, psca; + + v[0] = b->xyz[0] - a->xyz[0]; + v[1] = b->xyz[1] - a->xyz[1]; + v[2] = b->xyz[2] - a->xyz[2]; + + if(!GL2PS_ZERO(psca = gl2psPsca(plane, v))) + sect = -gl2psComparePointPlane(a->xyz, plane) / psca; + else + sect = 0.0F; + + c->xyz[0] = a->xyz[0] + v[0] * sect; + c->xyz[1] = a->xyz[1] + v[1] * sect; + c->xyz[2] = a->xyz[2] + v[2] * sect; + + c->rgba[0] = (1 - sect) * a->rgba[0] + sect * b->rgba[0]; + c->rgba[1] = (1 - sect) * a->rgba[1] + sect * b->rgba[1]; + c->rgba[2] = (1 - sect) * a->rgba[2] + sect * b->rgba[2]; + c->rgba[3] = (1 - sect) * a->rgba[3] + sect * b->rgba[3]; +} + +static void gl2psCreateSplitPrimitive(GL2PSprimitive *parent, GL2PSplane plane, + GL2PSprimitive *child, GLshort numverts, + GLshort *index0, GLshort *index1) +{ + GLshort i; + + if(parent->type == GL2PS_IMAGEMAP){ + child->type = GL2PS_IMAGEMAP; + child->data.image = parent->data.image; + } + else{ + if(numverts > 4){ + gl2psMsg(GL2PS_WARNING, "%d vertices in polygon", numverts); + numverts = 4; + } + switch(numverts){ + case 1 : child->type = GL2PS_POINT; break; + case 2 : child->type = GL2PS_LINE; break; + case 3 : child->type = GL2PS_TRIANGLE; break; + case 4 : child->type = GL2PS_QUADRANGLE; break; + default: child->type = GL2PS_NO_TYPE; break; + } + } + + child->boundary = 0; /* FIXME: not done! */ + child->culled = parent->culled; + child->offset = parent->offset; + child->ofactor = parent->ofactor; + child->ounits = parent->ounits; + child->pattern = parent->pattern; + child->factor = parent->factor; + child->width = parent->width; + child->numverts = numverts; + child->verts = (GL2PSvertex*)gl2psMalloc(numverts * sizeof(GL2PSvertex)); + + for(i = 0; i < numverts; i++){ + if(index1[i] < 0){ + child->verts[i] = parent->verts[index0[i]]; + } + else{ + gl2psCutEdge(&parent->verts[index0[i]], &parent->verts[index1[i]], + plane, &child->verts[i]); + } + } +} + +static void gl2psAddIndex(GLshort *index0, GLshort *index1, GLshort *nb, + GLshort i, GLshort j) +{ + GLint k; + + for(k = 0; k < *nb; k++){ + if((index0[k] == i && index1[k] == j) || + (index1[k] == i && index0[k] == j)) return; + } + index0[*nb] = i; + index1[*nb] = j; + (*nb)++; +} + +static GLshort gl2psGetIndex(GLshort i, GLshort num) +{ + return (i < num - 1) ? i + 1 : 0; +} + +static GLint gl2psTestSplitPrimitive(GL2PSprimitive *prim, GL2PSplane plane) +{ + GLint type = GL2PS_COINCIDENT; + GLshort i, j; + GLfloat d[5]; + + for(i = 0; i < prim->numverts; i++){ + d[i] = gl2psComparePointPlane(prim->verts[i].xyz, plane); + } + + if(prim->numverts < 2){ + return 0; + } + else{ + for(i = 0; i < prim->numverts; i++){ + j = gl2psGetIndex(i, prim->numverts); + if(d[j] > GL2PS_EPSILON){ + if(type == GL2PS_COINCIDENT) type = GL2PS_IN_BACK_OF; + else if(type != GL2PS_IN_BACK_OF) return 1; + if(d[i] < -GL2PS_EPSILON) return 1; + } + else if(d[j] < -GL2PS_EPSILON){ + if(type == GL2PS_COINCIDENT) type = GL2PS_IN_FRONT_OF; + else if(type != GL2PS_IN_FRONT_OF) return 1; + if(d[i] > GL2PS_EPSILON) return 1; + } + } + } + return 0; +} + +static GLint gl2psSplitPrimitive(GL2PSprimitive *prim, GL2PSplane plane, + GL2PSprimitive **front, GL2PSprimitive **back) +{ + GLshort i, j, in = 0, out = 0, in0[5], in1[5], out0[5], out1[5]; + GLint type; + GLfloat d[5]; + + type = GL2PS_COINCIDENT; + + for(i = 0; i < prim->numverts; i++){ + d[i] = gl2psComparePointPlane(prim->verts[i].xyz, plane); + } + + switch(prim->type){ + case GL2PS_POINT : + if(d[0] > GL2PS_EPSILON) type = GL2PS_IN_BACK_OF; + else if(d[0] < -GL2PS_EPSILON) type = GL2PS_IN_FRONT_OF; + else type = GL2PS_COINCIDENT; + break; + default : + for(i = 0; i < prim->numverts; i++){ + j = gl2psGetIndex(i, prim->numverts); + if(d[j] > GL2PS_EPSILON){ + if(type == GL2PS_COINCIDENT) type = GL2PS_IN_BACK_OF; + else if(type != GL2PS_IN_BACK_OF) type = GL2PS_SPANNING; + if(d[i] < -GL2PS_EPSILON){ + gl2psAddIndex(in0, in1, &in, i, j); + gl2psAddIndex(out0, out1, &out, i, j); + type = GL2PS_SPANNING; + } + gl2psAddIndex(out0, out1, &out, j, -1); + } + else if(d[j] < -GL2PS_EPSILON){ + if(type == GL2PS_COINCIDENT) type = GL2PS_IN_FRONT_OF; + else if(type != GL2PS_IN_FRONT_OF) type = GL2PS_SPANNING; + if(d[i] > GL2PS_EPSILON){ + gl2psAddIndex(in0, in1, &in, i, j); + gl2psAddIndex(out0, out1, &out, i, j); + type = GL2PS_SPANNING; + } + gl2psAddIndex(in0, in1, &in, j, -1); + } + else{ + gl2psAddIndex(in0, in1, &in, j, -1); + gl2psAddIndex(out0, out1, &out, j, -1); + } + } + break; + } + + if(type == GL2PS_SPANNING){ + *back = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); + *front = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); + gl2psCreateSplitPrimitive(prim, plane, *back, out, out0, out1); + gl2psCreateSplitPrimitive(prim, plane, *front, in, in0, in1); + } + + return type; +} + +static void gl2psDivideQuad(GL2PSprimitive *quad, + GL2PSprimitive **t1, GL2PSprimitive **t2) +{ + *t1 = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); + *t2 = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); + (*t1)->type = (*t2)->type = GL2PS_TRIANGLE; + (*t1)->numverts = (*t2)->numverts = 3; + (*t1)->culled = (*t2)->culled = quad->culled; + (*t1)->offset = (*t2)->offset = quad->offset; + (*t1)->ofactor = (*t2)->ofactor = quad->ofactor; + (*t1)->ounits = (*t2)->ounits = quad->ounits; + (*t1)->pattern = (*t2)->pattern = quad->pattern; + (*t1)->factor = (*t2)->factor = quad->factor; + (*t1)->width = (*t2)->width = quad->width; + (*t1)->verts = (GL2PSvertex*)gl2psMalloc(3 * sizeof(GL2PSvertex)); + (*t2)->verts = (GL2PSvertex*)gl2psMalloc(3 * sizeof(GL2PSvertex)); + (*t1)->verts[0] = quad->verts[0]; + (*t1)->verts[1] = quad->verts[1]; + (*t1)->verts[2] = quad->verts[2]; + (*t1)->boundary = ((quad->boundary & 1) ? 1 : 0) | ((quad->boundary & 2) ? 2 : 0); + (*t2)->verts[0] = quad->verts[0]; + (*t2)->verts[1] = quad->verts[2]; + (*t2)->verts[2] = quad->verts[3]; + (*t2)->boundary = ((quad->boundary & 4) ? 2 : 0) | ((quad->boundary & 8) ? 4 : 0); +} + +static int gl2psCompareDepth(const void *a, const void *b) +{ + const GL2PSprimitive *q, *w; + GLfloat dq = 0.0F, dw = 0.0F, diff; + int i; + + q = *(const GL2PSprimitive* const*)a; + w = *(const GL2PSprimitive* const*)b; + + for(i = 0; i < q->numverts; i++){ + dq += q->verts[i].xyz[2]; + } + dq /= (GLfloat)q->numverts; + + for(i = 0; i < w->numverts; i++){ + dw += w->verts[i].xyz[2]; + } + dw /= (GLfloat)w->numverts; + + diff = dq - dw; + if(diff > 0.){ + return -1; + } + else if(diff < 0.){ + return 1; + } + else{ + return 0; + } +} + +static int gl2psTrianglesFirst(const void *a, const void *b) +{ + const GL2PSprimitive *q, *w; + + q = *(const GL2PSprimitive* const*)a; + w = *(const GL2PSprimitive* const*)b; + return (q->type < w->type ? 1 : -1); +} + +static GLint gl2psFindRoot(GL2PSlist *primitives, GL2PSprimitive **root) +{ + GLint i, j, count, best = 1000000, idx = 0; + GL2PSprimitive *prim1, *prim2; + GL2PSplane plane; + GLint maxp; + + if(!gl2psListNbr(primitives)){ + gl2psMsg(GL2PS_ERROR, "Cannot fint root in empty primitive list"); + return 0; + } + + *root = *(GL2PSprimitive**)gl2psListPointer(primitives, 0); + + if(gl2ps->options & GL2PS_BEST_ROOT){ + maxp = gl2psListNbr(primitives); + if(maxp > gl2ps->maxbestroot){ + maxp = gl2ps->maxbestroot; + } + for(i = 0; i < maxp; i++){ + prim1 = *(GL2PSprimitive**)gl2psListPointer(primitives, i); + gl2psGetPlane(prim1, plane); + count = 0; + for(j = 0; j < gl2psListNbr(primitives); j++){ + if(j != i){ + prim2 = *(GL2PSprimitive**)gl2psListPointer(primitives, j); + count += gl2psTestSplitPrimitive(prim2, plane); + } + if(count > best) break; + } + if(count < best){ + best = count; + idx = i; + *root = prim1; + if(!count) return idx; + } + } + /* if(index) gl2psMsg(GL2PS_INFO, "GL2PS_BEST_ROOT was worth it: %d", index); */ + return idx; + } + else{ + return 0; + } +} + +static void gl2psFreeImagemap(GL2PSimagemap *list) +{ + GL2PSimagemap *next; + while(list != NULL){ + next = list->next; + gl2psFree(list->image->pixels); + gl2psFree(list->image); + gl2psFree(list); + list = next; + } +} + +static void gl2psFreePrimitive(void *data) +{ + GL2PSprimitive *q; + + q = *(GL2PSprimitive**)data; + gl2psFree(q->verts); + if(q->type == GL2PS_TEXT || q->type == GL2PS_SPECIAL){ + gl2psFreeText(q->data.text); + } + else if(q->type == GL2PS_PIXMAP){ + gl2psFreePixmap(q->data.image); + } + gl2psFree(q); +} + +static void gl2psAddPrimitiveInList(GL2PSprimitive *prim, GL2PSlist *list) +{ + GL2PSprimitive *t1, *t2; + + if(prim->type != GL2PS_QUADRANGLE){ + gl2psListAdd(list, &prim); + } + else{ + gl2psDivideQuad(prim, &t1, &t2); + gl2psListAdd(list, &t1); + gl2psListAdd(list, &t2); + gl2psFreePrimitive(&prim); + } + +} + +static void gl2psFreeBspTree(GL2PSbsptree **tree) +{ + if(*tree){ + if((*tree)->back) gl2psFreeBspTree(&(*tree)->back); + if((*tree)->primitives){ + gl2psListAction((*tree)->primitives, gl2psFreePrimitive); + gl2psListDelete((*tree)->primitives); + } + if((*tree)->front) gl2psFreeBspTree(&(*tree)->front); + gl2psFree(*tree); + *tree = NULL; + } +} + +static GLboolean gl2psGreater(GLfloat f1, GLfloat f2) +{ + if(f1 > f2) return GL_TRUE; + else return GL_FALSE; +} + +static GLboolean gl2psLess(GLfloat f1, GLfloat f2) +{ + if(f1 < f2) return GL_TRUE; + else return GL_FALSE; +} + +static void gl2psBuildBspTree(GL2PSbsptree *tree, GL2PSlist *primitives) +{ + GL2PSprimitive *prim, *frontprim = NULL, *backprim = NULL; + GL2PSlist *frontlist, *backlist; + GLint i, idx; + + tree->front = NULL; + tree->back = NULL; + tree->primitives = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); + idx = gl2psFindRoot(primitives, &prim); + gl2psGetPlane(prim, tree->plane); + gl2psAddPrimitiveInList(prim, tree->primitives); + + frontlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); + backlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); + + for(i = 0; i < gl2psListNbr(primitives); i++){ + if(i != idx){ + prim = *(GL2PSprimitive**)gl2psListPointer(primitives,i); + switch(gl2psSplitPrimitive(prim, tree->plane, &frontprim, &backprim)){ + case GL2PS_COINCIDENT: + gl2psAddPrimitiveInList(prim, tree->primitives); + break; + case GL2PS_IN_BACK_OF: + gl2psAddPrimitiveInList(prim, backlist); + break; + case GL2PS_IN_FRONT_OF: + gl2psAddPrimitiveInList(prim, frontlist); + break; + case GL2PS_SPANNING: + gl2psAddPrimitiveInList(backprim, backlist); + gl2psAddPrimitiveInList(frontprim, frontlist); + gl2psFreePrimitive(&prim); + break; + } + } + } + + if(gl2psListNbr(tree->primitives)){ + gl2psListSort(tree->primitives, gl2psTrianglesFirst); + } + + if(gl2psListNbr(frontlist)){ + gl2psListSort(frontlist, gl2psTrianglesFirst); + tree->front = (GL2PSbsptree*)gl2psMalloc(sizeof(GL2PSbsptree)); + gl2psBuildBspTree(tree->front, frontlist); + } + else{ + gl2psListDelete(frontlist); + } + + if(gl2psListNbr(backlist)){ + gl2psListSort(backlist, gl2psTrianglesFirst); + tree->back = (GL2PSbsptree*)gl2psMalloc(sizeof(GL2PSbsptree)); + gl2psBuildBspTree(tree->back, backlist); + } + else{ + gl2psListDelete(backlist); + } + + gl2psListDelete(primitives); +} + +static void gl2psTraverseBspTree(GL2PSbsptree *tree, GL2PSxyz eye, GLfloat epsilon, + GLboolean (*compare)(GLfloat f1, GLfloat f2), + void (*action)(void *data), int inverse) +{ + GLfloat result; + + if(!tree) return; + + result = gl2psComparePointPlane(eye, tree->plane); + + if(GL_TRUE == compare(result, epsilon)){ + gl2psTraverseBspTree(tree->back, eye, epsilon, compare, action, inverse); + if(inverse){ + gl2psListActionInverse(tree->primitives, action); + } + else{ + gl2psListAction(tree->primitives, action); + } + gl2psTraverseBspTree(tree->front, eye, epsilon, compare, action, inverse); + } + else if(GL_TRUE == compare(-epsilon, result)){ + gl2psTraverseBspTree(tree->front, eye, epsilon, compare, action, inverse); + if(inverse){ + gl2psListActionInverse(tree->primitives, action); + } + else{ + gl2psListAction(tree->primitives, action); + } + gl2psTraverseBspTree(tree->back, eye, epsilon, compare, action, inverse); + } + else{ + gl2psTraverseBspTree(tree->front, eye, epsilon, compare, action, inverse); + gl2psTraverseBspTree(tree->back, eye, epsilon, compare, action, inverse); + } +} + +static void gl2psRescaleAndOffset(void) +{ + GL2PSprimitive *prim; + GLfloat minZ, maxZ, rangeZ, scaleZ; + GLfloat factor, units, area, dZ, dZdX, dZdY, maxdZ; + int i, j; + + if(!gl2psListNbr(gl2ps->primitives)) + return; + + /* get z-buffer range */ + prim = *(GL2PSprimitive**)gl2psListPointer(gl2ps->primitives, 0); + minZ = maxZ = prim->verts[0].xyz[2]; + for(i = 1; i < prim->numverts; i++){ + if(prim->verts[i].xyz[2] < minZ) minZ = prim->verts[i].xyz[2]; + if(prim->verts[i].xyz[2] > maxZ) maxZ = prim->verts[i].xyz[2]; + } + for(i = 1; i < gl2psListNbr(gl2ps->primitives); i++){ + prim = *(GL2PSprimitive**)gl2psListPointer(gl2ps->primitives, i); + for(j = 0; j < prim->numverts; j++){ + if(prim->verts[j].xyz[2] < minZ) minZ = prim->verts[j].xyz[2]; + if(prim->verts[j].xyz[2] > maxZ) maxZ = prim->verts[j].xyz[2]; + } + } + rangeZ = (maxZ - minZ); + + /* rescale z-buffer coordinate in [0,GL2PS_ZSCALE], to make it of + the same order of magnitude as the x and y coordinates */ + scaleZ = GL2PS_ZERO(rangeZ) ? GL2PS_ZSCALE : (GL2PS_ZSCALE / rangeZ); + /* avoid precision loss (we use floats!) */ + if(scaleZ > 100000.F) scaleZ = 100000.F; + + /* apply offsets */ + for(i = 0; i < gl2psListNbr(gl2ps->primitives); i++){ + prim = *(GL2PSprimitive**)gl2psListPointer(gl2ps->primitives, i); + for(j = 0; j < prim->numverts; j++){ + prim->verts[j].xyz[2] = (prim->verts[j].xyz[2] - minZ) * scaleZ; + } + if((gl2ps->options & GL2PS_SIMPLE_LINE_OFFSET) && + (prim->type == GL2PS_LINE)){ + if(gl2ps->sort == GL2PS_SIMPLE_SORT){ + prim->verts[0].xyz[2] -= GL2PS_ZOFFSET_LARGE; + prim->verts[1].xyz[2] -= GL2PS_ZOFFSET_LARGE; + } + else{ + prim->verts[0].xyz[2] -= GL2PS_ZOFFSET; + prim->verts[1].xyz[2] -= GL2PS_ZOFFSET; + } + } + else if(prim->offset && (prim->type == GL2PS_TRIANGLE)){ + factor = prim->ofactor; + units = prim->ounits; + area = + (prim->verts[1].xyz[0] - prim->verts[0].xyz[0]) * + (prim->verts[2].xyz[1] - prim->verts[1].xyz[1]) - + (prim->verts[2].xyz[0] - prim->verts[1].xyz[0]) * + (prim->verts[1].xyz[1] - prim->verts[0].xyz[1]); + if(!GL2PS_ZERO(area)){ + dZdX = + ((prim->verts[2].xyz[1] - prim->verts[1].xyz[1]) * + (prim->verts[1].xyz[2] - prim->verts[0].xyz[2]) - + (prim->verts[1].xyz[1] - prim->verts[0].xyz[1]) * + (prim->verts[2].xyz[2] - prim->verts[1].xyz[2])) / area; + dZdY = + ((prim->verts[1].xyz[0] - prim->verts[0].xyz[0]) * + (prim->verts[2].xyz[2] - prim->verts[1].xyz[2]) - + (prim->verts[2].xyz[0] - prim->verts[1].xyz[0]) * + (prim->verts[1].xyz[2] - prim->verts[0].xyz[2])) / area; + maxdZ = (GLfloat)sqrt(dZdX * dZdX + dZdY * dZdY); + } + else{ + maxdZ = 0.0F; + } + dZ = factor * maxdZ + units; + prim->verts[0].xyz[2] += dZ; + prim->verts[1].xyz[2] += dZ; + prim->verts[2].xyz[2] += dZ; + } + } +} + +/********************************************************************* + * + * 2D sorting routines (for occlusion culling) + * + *********************************************************************/ + +static GLint gl2psGetPlaneFromPoints(GL2PSxyz a, GL2PSxyz b, GL2PSplane plane) +{ + GLfloat n; + + plane[0] = b[1] - a[1]; + plane[1] = a[0] - b[0]; + n = (GLfloat)sqrt(plane[0]*plane[0] + plane[1]*plane[1]); + plane[2] = 0.0F; + if(!GL2PS_ZERO(n)){ + plane[0] /= n; + plane[1] /= n; + plane[3] = -plane[0]*a[0]-plane[1]*a[1]; + return 1; + } + else{ + plane[0] = -1.0F; + plane[1] = 0.0F; + plane[3] = a[0]; + return 0; + } +} + +static void gl2psFreeBspImageTree(GL2PSbsptree2d **tree) +{ + if(*tree){ + if((*tree)->back) gl2psFreeBspImageTree(&(*tree)->back); + if((*tree)->front) gl2psFreeBspImageTree(&(*tree)->front); + gl2psFree(*tree); + *tree = NULL; + } +} + +static GLint gl2psCheckPoint(GL2PSxyz point, GL2PSplane plane) +{ + GLfloat pt_dis; + + pt_dis = gl2psComparePointPlane(point, plane); + if(pt_dis > GL2PS_EPSILON) return GL2PS_POINT_INFRONT; + else if(pt_dis < -GL2PS_EPSILON) return GL2PS_POINT_BACK; + else return GL2PS_POINT_COINCIDENT; +} + +static void gl2psAddPlanesInBspTreeImage(GL2PSprimitive *prim, + GL2PSbsptree2d **tree) +{ + GLint ret = 0; + GLint i; + GLint offset = 0; + GL2PSbsptree2d *head = NULL, *cur = NULL; + + if((*tree == NULL) && (prim->numverts > 2)){ + /* don't cull if transparent + for(i = 0; i < prim->numverts - 1; i++) + if(prim->verts[i].rgba[3] < 1.0F) return; + */ + head = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d)); + for(i = 0; i < prim->numverts-1; i++){ + if(!gl2psGetPlaneFromPoints(prim->verts[i].xyz, + prim->verts[i+1].xyz, + head->plane)){ + if(prim->numverts-i > 3){ + offset++; + } + else{ + gl2psFree(head); + return; + } + } + else{ + break; + } + } + head->back = NULL; + head->front = NULL; + for(i = 2+offset; i < prim->numverts; i++){ + ret = gl2psCheckPoint(prim->verts[i].xyz, head->plane); + if(ret != GL2PS_POINT_COINCIDENT) break; + } + switch(ret){ + case GL2PS_POINT_INFRONT : + cur = head; + for(i = 1+offset; i < prim->numverts-1; i++){ + if(cur->front == NULL){ + cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d)); + } + if(gl2psGetPlaneFromPoints(prim->verts[i].xyz, + prim->verts[i+1].xyz, + cur->front->plane)){ + cur = cur->front; + cur->front = NULL; + cur->back = NULL; + } + } + if(cur->front == NULL){ + cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d)); + } + if(gl2psGetPlaneFromPoints(prim->verts[i].xyz, + prim->verts[offset].xyz, + cur->front->plane)){ + cur->front->front = NULL; + cur->front->back = NULL; + } + else{ + gl2psFree(cur->front); + cur->front = NULL; + } + break; + case GL2PS_POINT_BACK : + for(i = 0; i < 4; i++){ + head->plane[i] = -head->plane[i]; + } + cur = head; + for(i = 1+offset; i < prim->numverts-1; i++){ + if(cur->front == NULL){ + cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d)); + } + if(gl2psGetPlaneFromPoints(prim->verts[i+1].xyz, + prim->verts[i].xyz, + cur->front->plane)){ + cur = cur->front; + cur->front = NULL; + cur->back = NULL; + } + } + if(cur->front == NULL){ + cur->front = (GL2PSbsptree2d*)gl2psMalloc(sizeof(GL2PSbsptree2d)); + } + if(gl2psGetPlaneFromPoints(prim->verts[offset].xyz, + prim->verts[i].xyz, + cur->front->plane)){ + cur->front->front = NULL; + cur->front->back = NULL; + } + else{ + gl2psFree(cur->front); + cur->front = NULL; + } + break; + default: + gl2psFree(head); + return; + } + (*tree) = head; + } +} + +static GLint gl2psCheckPrimitive(GL2PSprimitive *prim, GL2PSplane plane) +{ + GLint i; + GLint pos; + + pos = gl2psCheckPoint(prim->verts[0].xyz, plane); + for(i = 1; i < prim->numverts; i++){ + pos |= gl2psCheckPoint(prim->verts[i].xyz, plane); + if(pos == (GL2PS_POINT_INFRONT | GL2PS_POINT_BACK)) return GL2PS_SPANNING; + } + if(pos & GL2PS_POINT_INFRONT) return GL2PS_IN_FRONT_OF; + else if(pos & GL2PS_POINT_BACK) return GL2PS_IN_BACK_OF; + else return GL2PS_COINCIDENT; +} + +static GL2PSprimitive *gl2psCreateSplitPrimitive2D(GL2PSprimitive *parent, + GLshort numverts, + GL2PSvertex *vertx) +{ + GLint i; + GL2PSprimitive *child = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); + + if(parent->type == GL2PS_IMAGEMAP){ + child->type = GL2PS_IMAGEMAP; + child->data.image = parent->data.image; + } + else { + switch(numverts){ + case 1 : child->type = GL2PS_POINT; break; + case 2 : child->type = GL2PS_LINE; break; + case 3 : child->type = GL2PS_TRIANGLE; break; + case 4 : child->type = GL2PS_QUADRANGLE; break; + default: child->type = GL2PS_NO_TYPE; break; /* FIXME */ + } + } + child->boundary = 0; /* FIXME: not done! */ + child->culled = parent->culled; + child->offset = parent->offset; + child->ofactor = parent->ofactor; + child->ounits = parent->ounits; + child->pattern = parent->pattern; + child->factor = parent->factor; + child->width = parent->width; + child->numverts = numverts; + child->verts = (GL2PSvertex*)gl2psMalloc(numverts * sizeof(GL2PSvertex)); + for(i = 0; i < numverts; i++){ + child->verts[i] = vertx[i]; + } + return child; +} + +static void gl2psSplitPrimitive2D(GL2PSprimitive *prim, + GL2PSplane plane, + GL2PSprimitive **front, + GL2PSprimitive **back) +{ + /* cur will hold the position of the current vertex + prev will hold the position of the previous vertex + prev0 will hold the position of the vertex number 0 + v1 and v2 represent the current and previous vertices, respectively + flag is set if the current vertex should be checked against the plane */ + GLint cur = -1, prev = -1, i, v1 = 0, v2 = 0, flag = 1, prev0 = -1; + + /* list of vertices that will go in front and back primitive */ + GL2PSvertex *front_list = NULL, *back_list = NULL; + + /* number of vertices in front and back list */ + GLshort front_count = 0, back_count = 0; + + for(i = 0; i <= prim->numverts; i++){ + v1 = i; + if(v1 == prim->numverts){ + if(prim->numverts < 3) break; + v1 = 0; + v2 = prim->numverts - 1; + cur = prev0; + } + else if(flag){ + cur = gl2psCheckPoint(prim->verts[v1].xyz, plane); + if(i == 0){ + prev0 = cur; + } + } + if(((prev == -1) || (prev == cur) || (prev == 0) || (cur == 0)) && + (i < prim->numverts)){ + if(cur == GL2PS_POINT_INFRONT){ + front_count++; + front_list = (GL2PSvertex*)gl2psRealloc(front_list, + sizeof(GL2PSvertex)*front_count); + front_list[front_count-1] = prim->verts[v1]; + } + else if(cur == GL2PS_POINT_BACK){ + back_count++; + back_list = (GL2PSvertex*)gl2psRealloc(back_list, + sizeof(GL2PSvertex)*back_count); + back_list[back_count-1] = prim->verts[v1]; + } + else{ + front_count++; + front_list = (GL2PSvertex*)gl2psRealloc(front_list, + sizeof(GL2PSvertex)*front_count); + front_list[front_count-1] = prim->verts[v1]; + back_count++; + back_list = (GL2PSvertex*)gl2psRealloc(back_list, + sizeof(GL2PSvertex)*back_count); + back_list[back_count-1] = prim->verts[v1]; + } + flag = 1; + } + else if((prev != cur) && (cur != 0) && (prev != 0)){ + if(v1 != 0){ + v2 = v1-1; + i--; + } + front_count++; + front_list = (GL2PSvertex*)gl2psRealloc(front_list, + sizeof(GL2PSvertex)*front_count); + gl2psCutEdge(&prim->verts[v2], &prim->verts[v1], + plane, &front_list[front_count-1]); + back_count++; + back_list = (GL2PSvertex*)gl2psRealloc(back_list, + sizeof(GL2PSvertex)*back_count); + back_list[back_count-1] = front_list[front_count-1]; + flag = 0; + } + prev = cur; + } + *front = gl2psCreateSplitPrimitive2D(prim, front_count, front_list); + *back = gl2psCreateSplitPrimitive2D(prim, back_count, back_list); + gl2psFree(front_list); + gl2psFree(back_list); +} + +static GLint gl2psAddInBspImageTree(GL2PSprimitive *prim, GL2PSbsptree2d **tree) +{ + GLint ret = 0; + GL2PSprimitive *frontprim = NULL, *backprim = NULL; + + /* FIXME: until we consider the actual extent of text strings and + pixmaps, never cull them. Otherwise the whole string/pixmap gets + culled as soon as the reference point is hidden */ + if(prim->type == GL2PS_PIXMAP || + prim->type == GL2PS_TEXT || + prim->type == GL2PS_SPECIAL){ + return 1; + } + + if(*tree == NULL){ + if((prim->type != GL2PS_IMAGEMAP) && (GL_FALSE == gl2ps->zerosurfacearea)){ + gl2psAddPlanesInBspTreeImage(gl2ps->primitivetoadd, tree); + } + return 1; + } + else{ + switch(gl2psCheckPrimitive(prim, (*tree)->plane)){ + case GL2PS_IN_BACK_OF: return gl2psAddInBspImageTree(prim, &(*tree)->back); + case GL2PS_IN_FRONT_OF: + if((*tree)->front != NULL) return gl2psAddInBspImageTree(prim, &(*tree)->front); + else return 0; + case GL2PS_SPANNING: + gl2psSplitPrimitive2D(prim, (*tree)->plane, &frontprim, &backprim); + ret = gl2psAddInBspImageTree(backprim, &(*tree)->back); + if((*tree)->front != NULL){ + if(gl2psAddInBspImageTree(frontprim, &(*tree)->front)){ + ret = 1; + } + } + gl2psFree(frontprim->verts); + gl2psFree(frontprim); + gl2psFree(backprim->verts); + gl2psFree(backprim); + return ret; + case GL2PS_COINCIDENT: + if((*tree)->back != NULL){ + gl2ps->zerosurfacearea = GL_TRUE; + ret = gl2psAddInBspImageTree(prim, &(*tree)->back); + gl2ps->zerosurfacearea = GL_FALSE; + if(ret) return ret; + } + if((*tree)->front != NULL){ + gl2ps->zerosurfacearea = GL_TRUE; + ret = gl2psAddInBspImageTree(prim, &(*tree)->front); + gl2ps->zerosurfacearea = GL_FALSE; + if(ret) return ret; + } + if(prim->type == GL2PS_LINE) return 1; + else return 0; + } + } + return 0; +} + +static void gl2psAddInImageTree(void *data) +{ + GL2PSprimitive *prim = *(GL2PSprimitive **)data; + gl2ps->primitivetoadd = prim; + if(prim->type == GL2PS_IMAGEMAP && prim->data.image->format == GL2PS_IMAGEMAP_VISIBLE){ + prim->culled = 1; + } + else if(!gl2psAddInBspImageTree(prim, &gl2ps->imagetree)){ + prim->culled = 1; + } + else if(prim->type == GL2PS_IMAGEMAP){ + prim->data.image->format = GL2PS_IMAGEMAP_VISIBLE; + } +} + +/* Boundary construction */ + +static void gl2psAddBoundaryInList(GL2PSprimitive *prim, GL2PSlist *list) +{ + GL2PSprimitive *b; + GLshort i; + GL2PSxyz c; + + c[0] = c[1] = c[2] = 0.0F; + for(i = 0; i < prim->numverts; i++){ + c[0] += prim->verts[i].xyz[0]; + c[1] += prim->verts[i].xyz[1]; + } + c[0] /= prim->numverts; + c[1] /= prim->numverts; + + for(i = 0; i < prim->numverts; i++){ + if(prim->boundary & (GLint)pow(2., i)){ + b = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); + b->type = GL2PS_LINE; + b->offset = prim->offset; + b->ofactor = prim->ofactor; + b->ounits = prim->ounits; + b->pattern = prim->pattern; + b->factor = prim->factor; + b->culled = prim->culled; + b->width = prim->width; + b->boundary = 0; + b->numverts = 2; + b->verts = (GL2PSvertex*)gl2psMalloc(2 * sizeof(GL2PSvertex)); + +#if 0 /* FIXME: need to work on boundary offset... */ + v[0] = c[0] - prim->verts[i].xyz[0]; + v[1] = c[1] - prim->verts[i].xyz[1]; + v[2] = 0.0F; + norm = gl2psNorm(v); + v[0] /= norm; + v[1] /= norm; + b->verts[0].xyz[0] = prim->verts[i].xyz[0] +0.1*v[0]; + b->verts[0].xyz[1] = prim->verts[i].xyz[1] +0.1*v[1]; + b->verts[0].xyz[2] = prim->verts[i].xyz[2]; + v[0] = c[0] - prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[0]; + v[1] = c[1] - prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[1]; + norm = gl2psNorm(v); + v[0] /= norm; + v[1] /= norm; + b->verts[1].xyz[0] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[0] +0.1*v[0]; + b->verts[1].xyz[1] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[1] +0.1*v[1]; + b->verts[1].xyz[2] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[2]; +#else + b->verts[0].xyz[0] = prim->verts[i].xyz[0]; + b->verts[0].xyz[1] = prim->verts[i].xyz[1]; + b->verts[0].xyz[2] = prim->verts[i].xyz[2]; + b->verts[1].xyz[0] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[0]; + b->verts[1].xyz[1] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[1]; + b->verts[1].xyz[2] = prim->verts[gl2psGetIndex(i, prim->numverts)].xyz[2]; +#endif + + b->verts[0].rgba[0] = 0.0F; + b->verts[0].rgba[1] = 0.0F; + b->verts[0].rgba[2] = 0.0F; + b->verts[0].rgba[3] = 0.0F; + b->verts[1].rgba[0] = 0.0F; + b->verts[1].rgba[1] = 0.0F; + b->verts[1].rgba[2] = 0.0F; + b->verts[1].rgba[3] = 0.0F; + gl2psListAdd(list, &b); + } + } + +} + +static void gl2psBuildPolygonBoundary(GL2PSbsptree *tree) +{ + GLint i; + GL2PSprimitive *prim; + + if(!tree) return; + gl2psBuildPolygonBoundary(tree->back); + for(i = 0; i < gl2psListNbr(tree->primitives); i++){ + prim = *(GL2PSprimitive**)gl2psListPointer(tree->primitives, i); + if(prim->boundary) gl2psAddBoundaryInList(prim, tree->primitives); + } + gl2psBuildPolygonBoundary(tree->front); +} + +/********************************************************************* + * + * Feedback buffer parser + * + *********************************************************************/ + +static void gl2psAddPolyPrimitive(GLshort type, GLshort numverts, + GL2PSvertex *verts, GLint offset, + GLfloat ofactor, GLfloat ounits, + GLushort pattern, GLint factor, + GLfloat width, char boundary) +{ + GL2PSprimitive *prim; + + prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); + prim->type = type; + prim->numverts = numverts; + prim->verts = (GL2PSvertex*)gl2psMalloc(numverts * sizeof(GL2PSvertex)); + memcpy(prim->verts, verts, numverts * sizeof(GL2PSvertex)); + prim->boundary = boundary; + prim->offset = offset; + prim->ofactor = ofactor; + prim->ounits = ounits; + prim->pattern = pattern; + prim->factor = factor; + prim->width = width; + prim->culled = 0; + + /* FIXME: here we should have an option to split stretched + tris/quads to enhance SIMPLE_SORT */ + + gl2psListAdd(gl2ps->primitives, &prim); +} + +static GLint gl2psGetVertex(GL2PSvertex *v, GLfloat *p) +{ + GLint i; + + v->xyz[0] = p[0]; + v->xyz[1] = p[1]; + v->xyz[2] = p[2]; + + if(gl2ps->colormode == GL_COLOR_INDEX && gl2ps->colorsize > 0){ + i = (GLint)(p[3] + 0.5); + v->rgba[0] = gl2ps->colormap[i][0]; + v->rgba[1] = gl2ps->colormap[i][1]; + v->rgba[2] = gl2ps->colormap[i][2]; + v->rgba[3] = gl2ps->colormap[i][3]; + return 4; + } + else{ + v->rgba[0] = p[3]; + v->rgba[1] = p[4]; + v->rgba[2] = p[5]; + v->rgba[3] = p[6]; + return 7; + } +} + +static void gl2psParseFeedbackBuffer(GLint used) +{ + char flag; + GLushort pattern = 0; + GLboolean boundary; + GLint i, sizeoffloat, count, v, vtot, offset = 0, factor = 0, auxindex = 0; + GLfloat lwidth = 1.0F, psize = 1.0F, ofactor, ounits; + GLfloat *current; + GL2PSvertex vertices[3]; + GL2PSprimitive *prim; + GL2PSimagemap *node; + + current = gl2ps->feedback; + boundary = gl2ps->boundary = GL_FALSE; + + while(used > 0){ + + if(GL_TRUE == boundary) gl2ps->boundary = GL_TRUE; + + switch((GLint)*current){ + case GL_POINT_TOKEN : + current ++; + used --; + i = gl2psGetVertex(&vertices[0], current); + current += i; + used -= i; + gl2psAddPolyPrimitive(GL2PS_POINT, 1, vertices, 0, 0.0, 0.0, + pattern, factor, psize, 0); + break; + case GL_LINE_TOKEN : + case GL_LINE_RESET_TOKEN : + current ++; + used --; + i = gl2psGetVertex(&vertices[0], current); + current += i; + used -= i; + i = gl2psGetVertex(&vertices[1], current); + current += i; + used -= i; + gl2psAddPolyPrimitive(GL2PS_LINE, 2, vertices, 0, 0.0, 0.0, + pattern, factor, lwidth, 0); + break; + case GL_POLYGON_TOKEN : + count = (GLint)current[1]; + current += 2; + used -= 2; + v = vtot = 0; + while(count > 0 && used > 0){ + i = gl2psGetVertex(&vertices[v], current); + gl2psAdaptVertexForBlending(&vertices[v]); + current += i; + used -= i; + count --; + vtot++; + if(v == 2){ + if(GL_TRUE == boundary){ + if(!count && vtot == 2) flag = 1|2|4; + else if(!count) flag = 2|4; + else if(vtot == 2) flag = 1|2; + else flag = 2; + } + else + flag = 0; + gl2psAddPolyPrimitive(GL2PS_TRIANGLE, 3, vertices, offset, ofactor, + ounits, pattern, factor, 1, flag); + vertices[1] = vertices[2]; + } + else + v ++; + } + break; + case GL_BITMAP_TOKEN : + case GL_DRAW_PIXEL_TOKEN : + case GL_COPY_PIXEL_TOKEN : + current ++; + used --; + i = gl2psGetVertex(&vertices[0], current); + current += i; + used -= i; + break; + case GL_PASS_THROUGH_TOKEN : + switch((GLint)current[1]){ + case GL2PS_BEGIN_OFFSET_TOKEN : + offset = 1; + current += 2; + used -= 2; + ofactor = current[1]; + current += 2; + used -= 2; + ounits = current[1]; + break; + case GL2PS_END_OFFSET_TOKEN : + offset = 0; + ofactor = 0.0; + ounits = 0.0; + break; + case GL2PS_BEGIN_BOUNDARY_TOKEN : boundary = GL_TRUE; break; + case GL2PS_END_BOUNDARY_TOKEN : boundary = GL_FALSE; break; + case GL2PS_END_STIPPLE_TOKEN : pattern = factor = 0; break; + case GL2PS_BEGIN_BLEND_TOKEN : gl2ps->blending = GL_TRUE; break; + case GL2PS_END_BLEND_TOKEN : gl2ps->blending = GL_FALSE; break; + case GL2PS_BEGIN_STIPPLE_TOKEN : + current += 2; + used -= 2; + pattern = (GLushort)current[1]; + current += 2; + used -= 2; + factor = (GLint)current[1]; + break; + case GL2PS_SRC_BLEND_TOKEN : + current += 2; + used -= 2; + gl2ps->blendfunc[0] = (GLint)current[1]; + break; + case GL2PS_DST_BLEND_TOKEN : + current += 2; + used -= 2; + gl2ps->blendfunc[1] = (GLint)current[1]; + break; + case GL2PS_POINT_SIZE_TOKEN : + current += 2; + used -= 2; + psize = current[1]; + break; + case GL2PS_LINE_WIDTH_TOKEN : + current += 2; + used -= 2; + lwidth = current[1]; + break; + case GL2PS_IMAGEMAP_TOKEN : + prim = (GL2PSprimitive *)gl2psMalloc(sizeof(GL2PSprimitive)); + prim->type = GL2PS_IMAGEMAP; + prim->boundary = 0; + prim->numverts = 4; + prim->verts = (GL2PSvertex *)gl2psMalloc(4 * sizeof(GL2PSvertex)); + prim->culled = 0; + prim->offset = 0; + prim->ofactor = 0.0; + prim->ounits = 0.0; + prim->pattern = 0; + prim->factor = 0; + prim->width = 1; + + node = (GL2PSimagemap*)gl2psMalloc(sizeof(GL2PSimagemap)); + node->image = (GL2PSimage*)gl2psMalloc(sizeof(GL2PSimage)); + node->image->type = 0; + node->image->format = 0; + node->image->zoom_x = 1.0F; + node->image->zoom_y = 1.0F; + node->next = NULL; + + if(gl2ps->imagemap_head == NULL) + gl2ps->imagemap_head = node; + else + gl2ps->imagemap_tail->next = node; + gl2ps->imagemap_tail = node; + prim->data.image = node->image; + + current += 2; used -= 2; + i = gl2psGetVertex(&prim->verts[0], ¤t[1]); + current += i; used -= i; + + node->image->width = (GLint)current[2]; + current += 2; used -= 2; + node->image->height = (GLint)current[2]; + prim->verts[0].xyz[0] = prim->verts[0].xyz[0] - (int)(node->image->width / 2) + 0.5F; + prim->verts[0].xyz[1] = prim->verts[0].xyz[1] - (int)(node->image->height / 2) + 0.5F; + for(i = 1; i < 4; i++){ + for(v = 0; v < 3; v++){ + prim->verts[i].xyz[v] = prim->verts[0].xyz[v]; + prim->verts[i].rgba[v] = prim->verts[0].rgba[v]; + } + prim->verts[i].rgba[v] = prim->verts[0].rgba[v]; + } + prim->verts[1].xyz[0] = prim->verts[1].xyz[0] + node->image->width; + prim->verts[2].xyz[0] = prim->verts[1].xyz[0]; + prim->verts[2].xyz[1] = prim->verts[2].xyz[1] + node->image->height; + prim->verts[3].xyz[1] = prim->verts[2].xyz[1]; + + sizeoffloat = sizeof(GLfloat); + v = 2 * sizeoffloat; + vtot = node->image->height + node->image->height * + ((node->image->width - 1) / 8); + node->image->pixels = (GLfloat*)gl2psMalloc(v + vtot); + node->image->pixels[0] = prim->verts[0].xyz[0]; + node->image->pixels[1] = prim->verts[0].xyz[1]; + + for(i = 0; i < vtot; i += sizeoffloat){ + current += 2; used -= 2; + if((vtot - i) >= 4) + memcpy(&(((char*)(node->image->pixels))[i + v]), &(current[2]), sizeoffloat); + else + memcpy(&(((char*)(node->image->pixels))[i + v]), &(current[2]), vtot - i); + } + current++; used--; + gl2psListAdd(gl2ps->primitives, &prim); + break; + case GL2PS_DRAW_PIXELS_TOKEN : + case GL2PS_TEXT_TOKEN : + if(auxindex < gl2psListNbr(gl2ps->auxprimitives)) + gl2psListAdd(gl2ps->primitives, + gl2psListPointer(gl2ps->auxprimitives, auxindex++)); + else + gl2psMsg(GL2PS_ERROR, "Wrong number of auxiliary tokens in buffer"); + break; + } + current += 2; + used -= 2; + break; + default : + gl2psMsg(GL2PS_WARNING, "Unknown token in buffer"); + current ++; + used --; + break; + } + } + + gl2psListReset(gl2ps->auxprimitives); +} + +/********************************************************************* + * + * PostScript routines + * + *********************************************************************/ + +static void gl2psWriteByte(unsigned char byte) +{ + unsigned char h = byte / 16; + unsigned char l = byte % 16; + gl2psPrintf("%x%x", h, l); +} + +static void gl2psPrintPostScriptPixmap(GLfloat x, GLfloat y, GL2PSimage *im) +{ + GLuint nbhex, nbyte, nrgb, nbits; + GLuint row, col, ibyte, icase; + GLfloat dr, dg, db, fgrey; + unsigned char red = 0, green = 0, blue = 0, b, grey; + GLuint width = (GLuint)im->width; + GLuint height = (GLuint)im->height; + + /* FIXME: should we define an option for these? Or just keep the + 8-bit per component case? */ + int greyscale = 0; /* set to 1 to output greyscale image */ + int nbit = 8; /* number of bits per color compoment (2, 4 or 8) */ + + if((width <= 0) || (height <= 0)) return; + + gl2psPrintf("gsave\n"); + gl2psPrintf("%.2f %.2f translate\n", x, y); + gl2psPrintf("%.2f %.2f scale\n", width * im->zoom_x, height * im->zoom_y); + + if(greyscale){ /* greyscale */ + gl2psPrintf("/picstr %d string def\n", width); + gl2psPrintf("%d %d %d\n", width, height, 8); + gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height); + gl2psPrintf("{ currentfile picstr readhexstring pop }\n"); + gl2psPrintf("image\n"); + for(row = 0; row < height; row++){ + for(col = 0; col < width; col++){ + gl2psGetRGB(im, col, row, &dr, &dg, &db); + fgrey = (0.30F * dr + 0.59F * dg + 0.11F * db); + grey = (unsigned char)(255. * fgrey); + gl2psWriteByte(grey); + } + gl2psPrintf("\n"); + } + nbhex = width * height * 2; + gl2psPrintf("%%%% nbhex digit :%d\n", nbhex); + } + else if(nbit == 2){ /* color, 2 bits for r and g and b; rgbs following each other */ + nrgb = width * 3; + nbits = nrgb * nbit; + nbyte = nbits / 8; + if((nbyte * 8) != nbits) nbyte++; + gl2psPrintf("/rgbstr %d string def\n", nbyte); + gl2psPrintf("%d %d %d\n", width, height, nbit); + gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height); + gl2psPrintf("{ currentfile rgbstr readhexstring pop }\n"); + gl2psPrintf("false 3\n"); + gl2psPrintf("colorimage\n"); + for(row = 0; row < height; row++){ + icase = 1; + col = 0; + b = 0; + for(ibyte = 0; ibyte < nbyte; ibyte++){ + if(icase == 1) { + if(col < width) { + gl2psGetRGB(im, col, row, &dr, &dg, &db); + } + else { + dr = dg = db = 0; + } + col++; + red = (unsigned char)(3. * dr); + green = (unsigned char)(3. * dg); + blue = (unsigned char)(3. * db); + b = red; + b = (b<<2) + green; + b = (b<<2) + blue; + if(col < width) { + gl2psGetRGB(im, col, row, &dr, &dg, &db); + } + else { + dr = dg = db = 0; + } + col++; + red = (unsigned char)(3. * dr); + green = (unsigned char)(3. * dg); + blue = (unsigned char)(3. * db); + b = (b<<2) + red; + gl2psWriteByte(b); + b = 0; + icase++; + } + else if(icase == 2) { + b = green; + b = (b<<2) + blue; + if(col < width) { + gl2psGetRGB(im, col, row, &dr, &dg, &db); + } + else { + dr = dg = db = 0; + } + col++; + red = (unsigned char)(3. * dr); + green = (unsigned char)(3. * dg); + blue = (unsigned char)(3. * db); + b = (b<<2) + red; + b = (b<<2) + green; + gl2psWriteByte(b); + b = 0; + icase++; + } + else if(icase == 3) { + b = blue; + if(col < width) { + gl2psGetRGB(im, col, row, &dr, &dg, &db); + } + else { + dr = dg = db = 0; + } + col++; + red = (unsigned char)(3. * dr); + green = (unsigned char)(3. * dg); + blue = (unsigned char)(3. * db); + b = (b<<2) + red; + b = (b<<2) + green; + b = (b<<2) + blue; + gl2psWriteByte(b); + b = 0; + icase = 1; + } + } + gl2psPrintf("\n"); + } + } + else if(nbit == 4){ /* color, 4 bits for r and g and b; rgbs following each other */ + nrgb = width * 3; + nbits = nrgb * nbit; + nbyte = nbits / 8; + if((nbyte * 8) != nbits) nbyte++; + gl2psPrintf("/rgbstr %d string def\n", nbyte); + gl2psPrintf("%d %d %d\n", width, height, nbit); + gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height); + gl2psPrintf("{ currentfile rgbstr readhexstring pop }\n"); + gl2psPrintf("false 3\n"); + gl2psPrintf("colorimage\n"); + for(row = 0; row < height; row++){ + col = 0; + icase = 1; + for(ibyte = 0; ibyte < nbyte; ibyte++){ + if(icase == 1) { + if(col < width) { + gl2psGetRGB(im, col, row, &dr, &dg, &db); + } + else { + dr = dg = db = 0; + } + col++; + red = (unsigned char)(15. * dr); + green = (unsigned char)(15. * dg); + gl2psPrintf("%x%x", red, green); + icase++; + } + else if(icase == 2) { + blue = (unsigned char)(15. * db); + if(col < width) { + gl2psGetRGB(im, col, row, &dr, &dg, &db); + } + else { + dr = dg = db = 0; + } + col++; + red = (unsigned char)(15. * dr); + gl2psPrintf("%x%x", blue, red); + icase++; + } + else if(icase == 3) { + green = (unsigned char)(15. * dg); + blue = (unsigned char)(15. * db); + gl2psPrintf("%x%x", green, blue); + icase = 1; + } + } + gl2psPrintf("\n"); + } + } + else{ /* 8 bit for r and g and b */ + nbyte = width * 3; + gl2psPrintf("/rgbstr %d string def\n", nbyte); + gl2psPrintf("%d %d %d\n", width, height, 8); + gl2psPrintf("[ %d 0 0 -%d 0 %d ]\n", width, height, height); + gl2psPrintf("{ currentfile rgbstr readhexstring pop }\n"); + gl2psPrintf("false 3\n"); + gl2psPrintf("colorimage\n"); + for(row = 0; row < height; row++){ + for(col = 0; col < width; col++){ + gl2psGetRGB(im, col, row, &dr, &dg, &db); + red = (unsigned char)(255. * dr); + gl2psWriteByte(red); + green = (unsigned char)(255. * dg); + gl2psWriteByte(green); + blue = (unsigned char)(255. * db); + gl2psWriteByte(blue); + } + gl2psPrintf("\n"); + } + } + + gl2psPrintf("grestore\n"); +} + +static void gl2psPrintPostScriptImagemap(GLfloat x, GLfloat y, + GLsizei width, GLsizei height, + const unsigned char *imagemap){ + int i, size; + + if((width <= 0) || (height <= 0)) return; + + size = height + height * (width - 1) / 8; + + gl2psPrintf("gsave\n"); + gl2psPrintf("%.2f %.2f translate\n", x, y); + gl2psPrintf("%d %d scale\n%d %d\ntrue\n", width, height,width, height); + gl2psPrintf("[ %d 0 0 -%d 0 %d ] {<", width, height); + for(i = 0; i < size; i++){ + gl2psWriteByte(*imagemap); + imagemap++; + } + gl2psPrintf(">} imagemask\ngrestore\n"); +} + +static void gl2psPrintPostScriptHeader(void) +{ + time_t now; + + /* Since compression is not part of the PostScript standard, + compressed PostScript files are just gzipped PostScript files + ("ps.gz" or "eps.gz") */ + gl2psPrintGzipHeader(); + + time(&now); + + if(gl2ps->format == GL2PS_PS){ + gl2psPrintf("%%!PS-Adobe-3.0\n"); + } + else{ + gl2psPrintf("%%!PS-Adobe-3.0 EPSF-3.0\n"); + } + + gl2psPrintf("%%%%Title: %s\n" + "%%%%Creator: GL2PS %d.%d.%d%s, %s\n" + "%%%%For: %s\n" + "%%%%CreationDate: %s" + "%%%%LanguageLevel: 3\n" + "%%%%DocumentData: Clean7Bit\n" + "%%%%Pages: 1\n", + gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, + GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, + gl2ps->producer, ctime(&now)); + + if(gl2ps->format == GL2PS_PS){ + gl2psPrintf("%%%%Orientation: %s\n" + "%%%%DocumentMedia: Default %d %d 0 () ()\n", + (gl2ps->options & GL2PS_LANDSCAPE) ? "Landscape" : "Portrait", + (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[3] : + (int)gl2ps->viewport[2], + (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[2] : + (int)gl2ps->viewport[3]); + } + + gl2psPrintf("%%%%BoundingBox: %d %d %d %d\n" + "%%%%EndComments\n", + (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[1] : + (int)gl2ps->viewport[0], + (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[0] : + (int)gl2ps->viewport[1], + (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[3] : + (int)gl2ps->viewport[2], + (gl2ps->options & GL2PS_LANDSCAPE) ? (int)gl2ps->viewport[2] : + (int)gl2ps->viewport[3]); + + /* RGB color: r g b C (replace C by G in output to change from rgb to gray) + Grayscale: r g b G + Font choose: size fontname FC + Text string: (string) x y size fontname S?? + Rotated text string: (string) angle x y size fontname S??R + Point primitive: x y size P + Line width: width W + Line start: x y LS + Line joining last point: x y L + Line end: x y LE + Flat-shaded triangle: x3 y3 x2 y2 x1 y1 T + Smooth-shaded triangle: x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 ST */ + + gl2psPrintf("%%%%BeginProlog\n" + "/gl2psdict 64 dict def gl2psdict begin\n" + "0 setlinecap 0 setlinejoin\n" + "/tryPS3shading %s def %% set to false to force subdivision\n" + "/rThreshold %g def %% red component subdivision threshold\n" + "/gThreshold %g def %% green component subdivision threshold\n" + "/bThreshold %g def %% blue component subdivision threshold\n", + (gl2ps->options & GL2PS_NO_PS3_SHADING) ? "false" : "true", + gl2ps->threshold[0], gl2ps->threshold[1], gl2ps->threshold[2]); + + gl2psPrintf("/BD { bind def } bind def\n" + "/C { setrgbcolor } BD\n" + "/G { 0.082 mul exch 0.6094 mul add exch 0.3086 mul add neg 1.0 add setgray } BD\n" + "/W { setlinewidth } BD\n"); + + gl2psPrintf("/FC { findfont exch /SH exch def SH scalefont setfont } BD\n" + "/SW { dup stringwidth pop } BD\n" + "/S { FC moveto show } BD\n" + "/SBC{ FC moveto SW -2 div 0 rmoveto show } BD\n" + "/SBR{ FC moveto SW neg 0 rmoveto show } BD\n" + "/SCL{ FC moveto 0 SH -2 div rmoveto show } BD\n" + "/SCC{ FC moveto SW -2 div SH -2 div rmoveto show } BD\n" + "/SCR{ FC moveto SW neg SH -2 div rmoveto show } BD\n" + "/STL{ FC moveto 0 SH neg rmoveto show } BD\n" + "/STC{ FC moveto SW -2 div SH neg rmoveto show } BD\n" + "/STR{ FC moveto SW neg SH neg rmoveto show } BD\n"); + + /* rotated text routines: same nameanem with R appended */ + + gl2psPrintf("/FCT { FC translate 0 0 } BD\n" + "/SR { gsave FCT moveto rotate show grestore } BD\n" + "/SBCR{ gsave FCT moveto rotate SW -2 div 0 rmoveto show grestore } BD\n" + "/SBRR{ gsave FCT moveto rotate SW neg 0 rmoveto show grestore } BD\n" + "/SCLR{ gsave FCT moveto rotate 0 SH -2 div rmoveto show grestore} BD\n"); + gl2psPrintf("/SCCR{ gsave FCT moveto rotate SW -2 div SH -2 div rmoveto show grestore} BD\n" + "/SCRR{ gsave FCT moveto rotate SW neg SH -2 div rmoveto show grestore} BD\n" + "/STLR{ gsave FCT moveto rotate 0 SH neg rmoveto show grestore } BD\n" + "/STCR{ gsave FCT moveto rotate SW -2 div SH neg rmoveto show grestore } BD\n" + "/STRR{ gsave FCT moveto rotate SW neg SH neg rmoveto show grestore } BD\n"); + + gl2psPrintf("/P { newpath 0.0 360.0 arc closepath fill } BD\n" + "/LS { newpath moveto } BD\n" + "/L { lineto } BD\n" + "/LE { lineto stroke } BD\n" + "/T { newpath moveto lineto lineto closepath fill } BD\n"); + + /* Smooth-shaded triangle with PostScript level 3 shfill operator: + x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 STshfill */ + + gl2psPrintf("/STshfill {\n" + " /b1 exch def /g1 exch def /r1 exch def /y1 exch def /x1 exch def\n" + " /b2 exch def /g2 exch def /r2 exch def /y2 exch def /x2 exch def\n" + " /b3 exch def /g3 exch def /r3 exch def /y3 exch def /x3 exch def\n" + " gsave << /ShadingType 4 /ColorSpace [/DeviceRGB]\n" + " /DataSource [ 0 x1 y1 r1 g1 b1 0 x2 y2 r2 g2 b2 0 x3 y3 r3 g3 b3 ] >>\n" + " shfill grestore } BD\n"); + + /* Flat-shaded triangle with middle color: + x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 Tm */ + + gl2psPrintf(/* stack : x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 */ + "/Tm { 3 -1 roll 8 -1 roll 13 -1 roll add add 3 div\n" /* r = (r1+r2+r3)/3 */ + /* stack : x3 y3 g3 b3 x2 y2 g2 b2 x1 y1 g1 b1 r */ + " 3 -1 roll 7 -1 roll 11 -1 roll add add 3 div\n" /* g = (g1+g2+g3)/3 */ + /* stack : x3 y3 b3 x2 y2 b2 x1 y1 b1 r g b */ + " 3 -1 roll 6 -1 roll 9 -1 roll add add 3 div" /* b = (b1+b2+b3)/3 */ + /* stack : x3 y3 x2 y2 x1 y1 r g b */ + " C T } BD\n"); + + /* Split triangle in four sub-triangles (at sides middle points) and call the + STnoshfill procedure on each, interpolating the colors in RGB space: + x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 STsplit + (in procedure comments key: (Vi) = xi yi ri gi bi) */ + + gl2psPrintf("/STsplit {\n" + " 4 index 15 index add 0.5 mul\n" /* x13 = (x1+x3)/2 */ + " 4 index 15 index add 0.5 mul\n" /* y13 = (y1+y3)/2 */ + " 4 index 15 index add 0.5 mul\n" /* r13 = (r1+r3)/2 */ + " 4 index 15 index add 0.5 mul\n" /* g13 = (g1+g3)/2 */ + " 4 index 15 index add 0.5 mul\n" /* b13 = (b1+b3)/2 */ + " 5 copy 5 copy 25 15 roll\n"); + + /* at his point, stack = (V3) (V13) (V13) (V13) (V2) (V1) */ + + gl2psPrintf(" 9 index 30 index add 0.5 mul\n" /* x23 = (x2+x3)/2 */ + " 9 index 30 index add 0.5 mul\n" /* y23 = (y2+y3)/2 */ + " 9 index 30 index add 0.5 mul\n" /* r23 = (r2+r3)/2 */ + " 9 index 30 index add 0.5 mul\n" /* g23 = (g2+g3)/2 */ + " 9 index 30 index add 0.5 mul\n" /* b23 = (b2+b3)/2 */ + " 5 copy 5 copy 35 5 roll 25 5 roll 15 5 roll\n"); + + /* stack = (V3) (V13) (V23) (V13) (V23) (V13) (V23) (V2) (V1) */ + + gl2psPrintf(" 4 index 10 index add 0.5 mul\n" /* x12 = (x1+x2)/2 */ + " 4 index 10 index add 0.5 mul\n" /* y12 = (y1+y2)/2 */ + " 4 index 10 index add 0.5 mul\n" /* r12 = (r1+r2)/2 */ + " 4 index 10 index add 0.5 mul\n" /* g12 = (g1+g2)/2 */ + " 4 index 10 index add 0.5 mul\n" /* b12 = (b1+b2)/2 */ + " 5 copy 5 copy 40 5 roll 25 5 roll 15 5 roll 25 5 roll\n"); + + /* stack = (V3) (V13) (V23) (V13) (V12) (V23) (V13) (V1) (V12) (V23) (V12) (V2) */ + + gl2psPrintf(" STnoshfill STnoshfill STnoshfill STnoshfill } BD\n"); + + /* Gouraud shaded triangle using recursive subdivision until the difference + between corner colors does not exceed the thresholds: + x3 y3 r3 g3 b3 x2 y2 r2 g2 b2 x1 y1 r1 g1 b1 STnoshfill */ + + gl2psPrintf("/STnoshfill {\n" + " 2 index 8 index sub abs rThreshold gt\n" /* |r1-r2|>rth */ + " { STsplit }\n" + " { 1 index 7 index sub abs gThreshold gt\n" /* |g1-g2|>gth */ + " { STsplit }\n" + " { dup 6 index sub abs bThreshold gt\n" /* |b1-b2|>bth */ + " { STsplit }\n" + " { 2 index 13 index sub abs rThreshold gt\n" /* |r1-r3|>rht */ + " { STsplit }\n" + " { 1 index 12 index sub abs gThreshold gt\n" /* |g1-g3|>gth */ + " { STsplit }\n" + " { dup 11 index sub abs bThreshold gt\n" /* |b1-b3|>bth */ + " { STsplit }\n" + " { 7 index 13 index sub abs rThreshold gt\n"); /* |r2-r3|>rht */ + gl2psPrintf(" { STsplit }\n" + " { 6 index 12 index sub abs gThreshold gt\n" /* |g2-g3|>gth */ + " { STsplit }\n" + " { 5 index 11 index sub abs bThreshold gt\n" /* |b2-b3|>bth */ + " { STsplit }\n" + " { Tm }\n" /* all colors sufficiently similar */ + " ifelse }\n" + " ifelse }\n" + " ifelse }\n" + " ifelse }\n" + " ifelse }\n" + " ifelse }\n" + " ifelse }\n" + " ifelse }\n" + " ifelse } BD\n"); + + gl2psPrintf("tryPS3shading\n" + "{ /shfill where\n" + " { /ST { STshfill } BD }\n" + " { /ST { STnoshfill } BD }\n" + " ifelse }\n" + "{ /ST { STnoshfill } BD }\n" + "ifelse\n"); + + gl2psPrintf("end\n" + "%%%%EndProlog\n" + "%%%%BeginSetup\n" + "/DeviceRGB setcolorspace\n" + "gl2psdict begin\n" + "%%%%EndSetup\n" + "%%%%Page: 1 1\n" + "%%%%BeginPageSetup\n"); + + if(gl2ps->options & GL2PS_LANDSCAPE){ + gl2psPrintf("%d 0 translate 90 rotate\n", + (int)gl2ps->viewport[3]); + } + + gl2psPrintf("%%%%EndPageSetup\n" + "mark\n" + "gsave\n" + "1.0 1.0 scale\n"); + + if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ + gl2psPrintf("%g %g %g C\n" + "newpath %d %d moveto %d %d lineto %d %d lineto %d %d lineto\n" + "closepath fill\n", + gl2ps->bgcolor[0], gl2ps->bgcolor[1], gl2ps->bgcolor[2], + (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], + (int)gl2ps->viewport[1], (int)gl2ps->viewport[2], (int)gl2ps->viewport[3], + (int)gl2ps->viewport[0], (int)gl2ps->viewport[3]); + } +} + +static void gl2psPrintPostScriptColor(GL2PSrgba rgba) +{ + if(!gl2psSameColor(gl2ps->lastrgba, rgba)){ + gl2psSetLastColor(rgba); + gl2psPrintf("%g %g %g C\n", rgba[0], rgba[1], rgba[2]); + } +} + +static void gl2psResetPostScriptColor(void) +{ + gl2ps->lastrgba[0] = gl2ps->lastrgba[1] = gl2ps->lastrgba[2] = -1.; +} + +static void gl2psEndPostScriptLine(void) +{ + int i; + if(gl2ps->lastvertex.rgba[0] >= 0.){ + gl2psPrintf("%g %g LE\n", gl2ps->lastvertex.xyz[0], gl2ps->lastvertex.xyz[1]); + for(i = 0; i < 3; i++) + gl2ps->lastvertex.xyz[i] = -1.; + for(i = 0; i < 4; i++) + gl2ps->lastvertex.rgba[i] = -1.; + } +} + +static void gl2psParseStipplePattern(GLushort pattern, GLint factor, + int *nb, int array[10]) +{ + int i, n; + int on[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + int off[8] = {0, 0, 0, 0, 0, 0, 0, 0}; + char tmp[16]; + + /* extract the 16 bits from the OpenGL stipple pattern */ + for(n = 15; n >= 0; n--){ + tmp[n] = (char)(pattern & 0x01); + pattern >>= 1; + } + /* compute the on/off pixel sequence */ + n = 0; + for(i = 0; i < 8; i++){ + while(n < 16 && !tmp[n]){ off[i]++; n++; } + while(n < 16 && tmp[n]){ on[i]++; n++; } + if(n >= 15){ i++; break; } + } + + /* store the on/off array from right to left, starting with off + pixels. The PostScript specification allows for at most 11 + elements in the on/off array, so we limit ourselves to 5 on/off + couples (our longest possible array is thus [on4 off4 on3 off3 + on2 off2 on1 off1 on0 off0]) */ + *nb = 0; + for(n = i - 1; n >= 0; n--){ + array[(*nb)++] = factor * on[n]; + array[(*nb)++] = factor * off[n]; + if(*nb == 10) break; + } +} + +static int gl2psPrintPostScriptDash(GLushort pattern, GLint factor, const char *str) +{ + int len = 0, i, n, array[10]; + + if(pattern == gl2ps->lastpattern && factor == gl2ps->lastfactor) + return 0; + + gl2ps->lastpattern = pattern; + gl2ps->lastfactor = factor; + + if(!pattern || !factor){ + /* solid line */ + len += gl2psPrintf("[] 0 %s\n", str); + } + else{ + gl2psParseStipplePattern(pattern, factor, &n, array); + len += gl2psPrintf("["); + for(i = 0; i < n; i++){ + if(i) len += gl2psPrintf(" "); + len += gl2psPrintf("%d", array[i]); + } + len += gl2psPrintf("] 0 %s\n", str); + } + + return len; +} + +static void gl2psPrintPostScriptPrimitive(void *data) +{ + int newline; + GL2PSprimitive *prim; + + prim = *(GL2PSprimitive**)data; + + if((gl2ps->options & GL2PS_OCCLUSION_CULL) && prim->culled) return; + + /* Every effort is made to draw lines as connected segments (i.e., + using a single PostScript path): this is the only way to get nice + line joins and to not restart the stippling for every line + segment. So if the primitive to print is not a line we must first + finish the current line (if any): */ + if(prim->type != GL2PS_LINE) gl2psEndPostScriptLine(); + + switch(prim->type){ + case GL2PS_POINT : + gl2psPrintPostScriptColor(prim->verts[0].rgba); + gl2psPrintf("%g %g %g P\n", + prim->verts[0].xyz[0], prim->verts[0].xyz[1], 0.5 * prim->width); + break; + case GL2PS_LINE : + if(!gl2psSamePosition(gl2ps->lastvertex.xyz, prim->verts[0].xyz) || + !gl2psSameColor(gl2ps->lastrgba, prim->verts[0].rgba) || + gl2ps->lastlinewidth != prim->width || + gl2ps->lastpattern != prim->pattern || + gl2ps->lastfactor != prim->factor){ + /* End the current line if the new segment does not start where + the last one ended, or if the color, the width or the + stippling have changed (multi-stroking lines with changing + colors is necessary until we use /shfill for lines; + unfortunately this means that at the moment we can screw up + line stippling for smooth-shaded lines) */ + gl2psEndPostScriptLine(); + newline = 1; + } + else{ + newline = 0; + } + if(gl2ps->lastlinewidth != prim->width){ + gl2ps->lastlinewidth = prim->width; + gl2psPrintf("%g W\n", gl2ps->lastlinewidth); + } + gl2psPrintPostScriptDash(prim->pattern, prim->factor, "setdash"); + gl2psPrintPostScriptColor(prim->verts[0].rgba); + gl2psPrintf("%g %g %s\n", prim->verts[0].xyz[0], prim->verts[0].xyz[1], + newline ? "LS" : "L"); + gl2ps->lastvertex = prim->verts[1]; + break; + case GL2PS_TRIANGLE : + if(!gl2psVertsSameColor(prim)){ + gl2psResetPostScriptColor(); + gl2psPrintf("%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g ST\n", + prim->verts[2].xyz[0], prim->verts[2].xyz[1], + prim->verts[2].rgba[0], prim->verts[2].rgba[1], + prim->verts[2].rgba[2], prim->verts[1].xyz[0], + prim->verts[1].xyz[1], prim->verts[1].rgba[0], + prim->verts[1].rgba[1], prim->verts[1].rgba[2], + prim->verts[0].xyz[0], prim->verts[0].xyz[1], + prim->verts[0].rgba[0], prim->verts[0].rgba[1], + prim->verts[0].rgba[2]); + } + else{ + gl2psPrintPostScriptColor(prim->verts[0].rgba); + gl2psPrintf("%g %g %g %g %g %g T\n", + prim->verts[2].xyz[0], prim->verts[2].xyz[1], + prim->verts[1].xyz[0], prim->verts[1].xyz[1], + prim->verts[0].xyz[0], prim->verts[0].xyz[1]); + } + break; + case GL2PS_QUADRANGLE : + gl2psMsg(GL2PS_WARNING, "There should not be any quad left to print"); + break; + case GL2PS_PIXMAP : + gl2psPrintPostScriptPixmap(prim->verts[0].xyz[0], prim->verts[0].xyz[1], + prim->data.image); + break; + case GL2PS_IMAGEMAP : + if(prim->data.image->type != GL2PS_IMAGEMAP_WRITTEN){ + gl2psPrintPostScriptColor(prim->verts[0].rgba); + gl2psPrintPostScriptImagemap(prim->data.image->pixels[0], + prim->data.image->pixels[1], + prim->data.image->width, prim->data.image->height, + (const unsigned char*)(&(prim->data.image->pixels[2]))); + prim->data.image->type = GL2PS_IMAGEMAP_WRITTEN; + } + break; + case GL2PS_TEXT : + gl2psPrintPostScriptColor(prim->verts[0].rgba); + gl2psPrintf("(%s) ", prim->data.text->str); + if(prim->data.text->angle) + gl2psPrintf("%g ", prim->data.text->angle); + gl2psPrintf("%g %g %d /%s ", + prim->verts[0].xyz[0], prim->verts[0].xyz[1], + prim->data.text->fontsize, prim->data.text->fontname); + switch(prim->data.text->alignment){ + case GL2PS_TEXT_C: + gl2psPrintf(prim->data.text->angle ? "SCCR\n" : "SCC\n"); + break; + case GL2PS_TEXT_CL: + gl2psPrintf(prim->data.text->angle ? "SCLR\n" : "SCL\n"); + break; + case GL2PS_TEXT_CR: + gl2psPrintf(prim->data.text->angle ? "SCRR\n" : "SCR\n"); + break; + case GL2PS_TEXT_B: + gl2psPrintf(prim->data.text->angle ? "SBCR\n" : "SBC\n"); + break; + case GL2PS_TEXT_BR: + gl2psPrintf(prim->data.text->angle ? "SBRR\n" : "SBR\n"); + break; + case GL2PS_TEXT_T: + gl2psPrintf(prim->data.text->angle ? "STCR\n" : "STC\n"); + break; + case GL2PS_TEXT_TL: + gl2psPrintf(prim->data.text->angle ? "STLR\n" : "STL\n"); + break; + case GL2PS_TEXT_TR: + gl2psPrintf(prim->data.text->angle ? "STRR\n" : "STR\n"); + break; + case GL2PS_TEXT_BL: + default: + gl2psPrintf(prim->data.text->angle ? "SR\n" : "S\n"); + break; + } + break; + case GL2PS_SPECIAL : + /* alignment contains the format for which the special output text + is intended */ + if(prim->data.text->alignment == GL2PS_PS || + prim->data.text->alignment == GL2PS_EPS) + gl2psPrintf("%s\n", prim->data.text->str); + break; + default : + break; + } +} + +static void gl2psPrintPostScriptFooter(void) +{ + gl2psPrintf("grestore\n" + "showpage\n" + "cleartomark\n" + "%%%%PageTrailer\n" + "%%%%Trailer\n" + "end\n" + "%%%%EOF\n"); + + gl2psPrintGzipFooter(); +} + +static void gl2psPrintPostScriptBeginViewport(GLint viewport[4]) +{ + GLint idx; + GLfloat rgba[4]; + int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3]; + + glRenderMode(GL_FEEDBACK); + + if(gl2ps->header){ + gl2psPrintPostScriptHeader(); + gl2ps->header = GL_FALSE; + } + + gl2psPrintf("gsave\n" + "1.0 1.0 scale\n"); + + if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ + if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){ + glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba); + } + else{ + glGetIntegerv(GL_INDEX_CLEAR_VALUE, &idx); + rgba[0] = gl2ps->colormap[idx][0]; + rgba[1] = gl2ps->colormap[idx][1]; + rgba[2] = gl2ps->colormap[idx][2]; + rgba[3] = 1.0F; + } + gl2psPrintf("%g %g %g C\n" + "newpath %d %d moveto %d %d lineto %d %d lineto %d %d lineto\n" + "closepath fill\n", + rgba[0], rgba[1], rgba[2], + x, y, x+w, y, x+w, y+h, x, y+h); + } + + gl2psPrintf("newpath %d %d moveto %d %d lineto %d %d lineto %d %d lineto\n" + "closepath clip\n", + x, y, x+w, y, x+w, y+h, x, y+h); + +} + +static GLint gl2psPrintPostScriptEndViewport(void) +{ + GLint res; + + res = gl2psPrintPrimitives(); + gl2psPrintf("grestore\n"); + return res; +} + +static void gl2psPrintPostScriptFinalPrimitive(void) +{ + /* End any remaining line, if any */ + gl2psEndPostScriptLine(); +} + +/* definition of the PostScript and Encapsulated PostScript backends */ + +static GL2PSbackend gl2psPS = { + gl2psPrintPostScriptHeader, + gl2psPrintPostScriptFooter, + gl2psPrintPostScriptBeginViewport, + gl2psPrintPostScriptEndViewport, + gl2psPrintPostScriptPrimitive, + gl2psPrintPostScriptFinalPrimitive, + "ps", + "Postscript" +}; + +static GL2PSbackend gl2psEPS = { + gl2psPrintPostScriptHeader, + gl2psPrintPostScriptFooter, + gl2psPrintPostScriptBeginViewport, + gl2psPrintPostScriptEndViewport, + gl2psPrintPostScriptPrimitive, + gl2psPrintPostScriptFinalPrimitive, + "eps", + "Encapsulated Postscript" +}; + +/********************************************************************* + * + * LaTeX routines + * + *********************************************************************/ + +static void gl2psPrintTeXHeader(void) +{ + char name[256]; + time_t now; + int i; + + if(gl2ps->filename && strlen(gl2ps->filename) < 256){ + for(i = (int)strlen(gl2ps->filename) - 1; i >= 0; i--){ + if(gl2ps->filename[i] == '.'){ + strncpy(name, gl2ps->filename, i); + name[i] = '\0'; + break; + } + } + if(i <= 0) strcpy(name, gl2ps->filename); + } + else{ + strcpy(name, "untitled"); + } + + time(&now); + + fprintf(gl2ps->stream, + "%% Title: %s\n" + "%% Creator: GL2PS %d.%d.%d%s, %s\n" + "%% For: %s\n" + "%% CreationDate: %s", + gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, + GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, + gl2ps->producer, ctime(&now)); + + fprintf(gl2ps->stream, + "\\setlength{\\unitlength}{1pt}\n" + "\\begin{picture}(0,0)\n" + "\\includegraphics{%s}\n" + "\\end{picture}%%\n" + "%s\\begin{picture}(%d,%d)(0,0)\n", + name, (gl2ps->options & GL2PS_LANDSCAPE) ? "\\rotatebox{90}{" : "", + (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]); +} + +static void gl2psPrintTeXPrimitive(void *data) +{ + GL2PSprimitive *prim; + + prim = *(GL2PSprimitive**)data; + + switch(prim->type){ + case GL2PS_TEXT : + fprintf(gl2ps->stream, "\\fontsize{%d}{0}\n\\selectfont", + prim->data.text->fontsize); + fprintf(gl2ps->stream, "\\put(%g,%g)", + prim->verts[0].xyz[0], prim->verts[0].xyz[1]); + if(prim->data.text->angle) + fprintf(gl2ps->stream, "{\\rotatebox{%g}", prim->data.text->angle); + fprintf(gl2ps->stream, "{\\makebox(0,0)"); + switch(prim->data.text->alignment){ + case GL2PS_TEXT_C: + fprintf(gl2ps->stream, "{"); + break; + case GL2PS_TEXT_CL: + fprintf(gl2ps->stream, "[l]{"); + break; + case GL2PS_TEXT_CR: + fprintf(gl2ps->stream, "[r]{"); + break; + case GL2PS_TEXT_B: + fprintf(gl2ps->stream, "[b]{"); + break; + case GL2PS_TEXT_BR: + fprintf(gl2ps->stream, "[br]{"); + break; + case GL2PS_TEXT_T: + fprintf(gl2ps->stream, "[t]{"); + break; + case GL2PS_TEXT_TL: + fprintf(gl2ps->stream, "[tl]{"); + break; + case GL2PS_TEXT_TR: + fprintf(gl2ps->stream, "[tr]{"); + break; + case GL2PS_TEXT_BL: + default: + fprintf(gl2ps->stream, "[bl]{"); + break; + } + fprintf(gl2ps->stream, "\\textcolor[rgb]{%g,%g,%g}{{%s}}", + prim->verts[0].rgba[0], prim->verts[0].rgba[1], prim->verts[0].rgba[2], + prim->data.text->str); + if(prim->data.text->angle) + fprintf(gl2ps->stream, "}"); + fprintf(gl2ps->stream, "}}\n"); + break; + case GL2PS_SPECIAL : + /* alignment contains the format for which the special output text + is intended */ + if (prim->data.text->alignment == GL2PS_TEX) + fprintf(gl2ps->stream, "%s\n", prim->data.text->str); + break; + default : + break; + } +} + +static void gl2psPrintTeXFooter(void) +{ + fprintf(gl2ps->stream, "\\end{picture}%s\n", + (gl2ps->options & GL2PS_LANDSCAPE) ? "}" : ""); +} + +static void gl2psPrintTeXBeginViewport(GLint viewport[4]) +{ + (void) viewport; /* not used */ + glRenderMode(GL_FEEDBACK); + + if(gl2ps->header){ + gl2psPrintTeXHeader(); + gl2ps->header = GL_FALSE; + } +} + +static GLint gl2psPrintTeXEndViewport(void) +{ + return gl2psPrintPrimitives(); +} + +static void gl2psPrintTeXFinalPrimitive(void) +{ +} + +/* definition of the LaTeX backend */ + +static GL2PSbackend gl2psTEX = { + gl2psPrintTeXHeader, + gl2psPrintTeXFooter, + gl2psPrintTeXBeginViewport, + gl2psPrintTeXEndViewport, + gl2psPrintTeXPrimitive, + gl2psPrintTeXFinalPrimitive, + "tex", + "LaTeX text" +}; + +/********************************************************************* + * + * PDF routines + * + *********************************************************************/ + +static int gl2psPrintPDFCompressorType(void) +{ +#if defined(GL2PS_HAVE_ZLIB) + if(gl2ps->options & GL2PS_COMPRESS){ + return fprintf(gl2ps->stream, "/Filter [/FlateDecode]\n"); + } +#endif + return 0; +} + +static int gl2psPrintPDFStrokeColor(GL2PSrgba rgba) +{ + int i, offs = 0; + + gl2psSetLastColor(rgba); + for(i = 0; i < 3; ++i){ + if(GL2PS_ZERO(rgba[i])) + offs += gl2psPrintf("%.0f ", 0.); + else if(rgba[i] < 1e-4 || rgba[i] > 1e6) /* avoid %e formatting */ + offs += gl2psPrintf("%f ", rgba[i]); + else + offs += gl2psPrintf("%g ", rgba[i]); + } + offs += gl2psPrintf("RG\n"); + return offs; +} + +static int gl2psPrintPDFFillColor(GL2PSrgba rgba) +{ + int i, offs = 0; + + for(i = 0; i < 3; ++i){ + if(GL2PS_ZERO(rgba[i])) + offs += gl2psPrintf("%.0f ", 0.); + else if(rgba[i] < 1e-4 || rgba[i] > 1e6) /* avoid %e formatting */ + offs += gl2psPrintf("%f ", rgba[i]); + else + offs += gl2psPrintf("%g ", rgba[i]); + } + offs += gl2psPrintf("rg\n"); + return offs; +} + +static int gl2psPrintPDFLineWidth(GLfloat lw) +{ + if(GL2PS_ZERO(lw)) + return gl2psPrintf("%.0f w\n", 0.); + else if(lw < 1e-4 || lw > 1e6) /* avoid %e formatting */ + return gl2psPrintf("%f w\n", lw); + else + return gl2psPrintf("%g w\n", lw); +} + +static void gl2psPutPDFText(GL2PSstring *text, int cnt, GLfloat x, GLfloat y) +{ + GLfloat rad, crad, srad; + + if(text->angle == 0.0F){ + gl2ps->streamlength += gl2psPrintf + ("BT\n" + "/F%d %d Tf\n" + "%f %f Td\n" + "(%s) Tj\n" + "ET\n", + cnt, text->fontsize, x, y, text->str); + } + else{ + rad = (GLfloat)(3.141593F * text->angle / 180.0F); + srad = (GLfloat)sin(rad); + crad = (GLfloat)cos(rad); + gl2ps->streamlength += gl2psPrintf + ("BT\n" + "/F%d %d Tf\n" + "%f %f %f %f %f %f Tm\n" + "(%s) Tj\n" + "ET\n", + cnt, text->fontsize, crad, srad, -srad, crad, x, y, text->str); + } +} + +static void gl2psPutPDFSpecial(GL2PSstring *text) +{ + gl2ps->streamlength += gl2psPrintf("%s\n", text->str); +} + +static void gl2psPutPDFImage(GL2PSimage *image, int cnt, GLfloat x, GLfloat y) +{ + gl2ps->streamlength += gl2psPrintf + ("q\n" + "%d 0 0 %d %f %f cm\n" + "/Im%d Do\n" + "Q\n", + (int)image->width, (int)image->height, x, y, cnt); +} + +static void gl2psPDFstacksInit(void) +{ + gl2ps->objects_stack = 7 /* FIXED_XREF_ENTRIES */ + 1; + gl2ps->extgs_stack = 0; + gl2ps->font_stack = 0; + gl2ps->im_stack = 0; + gl2ps->trgroupobjects_stack = 0; + gl2ps->shader_stack = 0; + gl2ps->mshader_stack = 0; +} + +static void gl2psPDFgroupObjectInit(GL2PSpdfgroup *gro) +{ + if(!gro) + return; + + gro->ptrlist = NULL; + gro->fontno = gro->gsno = gro->imno = gro->maskshno = gro->shno + = gro->trgroupno = gro->fontobjno = gro->imobjno = gro->shobjno + = gro->maskshobjno = gro->gsobjno = gro->trgroupobjno = -1; +} + +/* Build up group objects and assign name and object numbers */ + +static void gl2psPDFgroupListInit(void) +{ + int i; + GL2PSprimitive *p = NULL; + GL2PSpdfgroup gro; + int lasttype = GL2PS_NO_TYPE; + GL2PSrgba lastrgba = {-1.0F, -1.0F, -1.0F, -1.0F}; + GLushort lastpattern = 0; + GLint lastfactor = 0; + GLfloat lastwidth = 1; + GL2PStriangle lastt, tmpt; + int lastTriangleWasNotSimpleWithSameColor = 0; + + if(!gl2ps->pdfprimlist) + return; + + gl2ps->pdfgrouplist = gl2psListCreate(500, 500, sizeof(GL2PSpdfgroup)); + gl2psInitTriangle(&lastt); + + for(i = 0; i < gl2psListNbr(gl2ps->pdfprimlist); ++i){ + p = *(GL2PSprimitive**)gl2psListPointer(gl2ps->pdfprimlist, i); + switch(p->type){ + case GL2PS_PIXMAP: + gl2psPDFgroupObjectInit(&gro); + gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); + gro.imno = gl2ps->im_stack++; + gl2psListAdd(gro.ptrlist, &p); + gl2psListAdd(gl2ps->pdfgrouplist, &gro); + break; + case GL2PS_TEXT: + gl2psPDFgroupObjectInit(&gro); + gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); + gro.fontno = gl2ps->font_stack++; + gl2psListAdd(gro.ptrlist, &p); + gl2psListAdd(gl2ps->pdfgrouplist, &gro); + break; + case GL2PS_LINE: + if(lasttype != p->type || lastwidth != p->width || + lastpattern != p->pattern || lastfactor != p->factor || + !gl2psSameColor(p->verts[0].rgba, lastrgba)){ + gl2psPDFgroupObjectInit(&gro); + gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); + gl2psListAdd(gro.ptrlist, &p); + gl2psListAdd(gl2ps->pdfgrouplist, &gro); + } + else{ + gl2psListAdd(gro.ptrlist, &p); + } + lastpattern = p->pattern; + lastfactor = p->factor; + lastwidth = p->width; + lastrgba[0] = p->verts[0].rgba[0]; + lastrgba[1] = p->verts[0].rgba[1]; + lastrgba[2] = p->verts[0].rgba[2]; + break; + case GL2PS_POINT: + if(lasttype != p->type || lastwidth != p->width || + !gl2psSameColor(p->verts[0].rgba, lastrgba)){ + gl2psPDFgroupObjectInit(&gro); + gro.ptrlist = gl2psListCreate(1,2,sizeof(GL2PSprimitive*)); + gl2psListAdd(gro.ptrlist, &p); + gl2psListAdd(gl2ps->pdfgrouplist, &gro); + } + else{ + gl2psListAdd(gro.ptrlist, &p); + } + lastwidth = p->width; + lastrgba[0] = p->verts[0].rgba[0]; + lastrgba[1] = p->verts[0].rgba[1]; + lastrgba[2] = p->verts[0].rgba[2]; + break; + case GL2PS_TRIANGLE: + gl2psFillTriangleFromPrimitive(&tmpt, p, GL_TRUE); + lastTriangleWasNotSimpleWithSameColor = + !(tmpt.prop & T_CONST_COLOR && tmpt.prop & T_ALPHA_1) || + !gl2psSameColor(tmpt.vertex[0].rgba, lastt.vertex[0].rgba); + if(lasttype == p->type && tmpt.prop == lastt.prop && + lastTriangleWasNotSimpleWithSameColor){ + /* TODO Check here for last alpha */ + gl2psListAdd(gro.ptrlist, &p); + } + else{ + gl2psPDFgroupObjectInit(&gro); + gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); + gl2psListAdd(gro.ptrlist, &p); + gl2psListAdd(gl2ps->pdfgrouplist, &gro); + } + lastt = tmpt; + break; + case GL2PS_SPECIAL: + gl2psPDFgroupObjectInit(&gro); + gro.ptrlist = gl2psListCreate(1, 2, sizeof(GL2PSprimitive*)); + gl2psListAdd(gro.ptrlist, &p); + gl2psListAdd(gl2ps->pdfgrouplist, &gro); + break; + default: + break; + } + lasttype = p->type; + } +} + +static void gl2psSortOutTrianglePDFgroup(GL2PSpdfgroup *gro) +{ + GL2PStriangle t; + GL2PSprimitive *prim = NULL; + + if(!gro) + return; + + if(!gl2psListNbr(gro->ptrlist)) + return; + + prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0); + + if(prim->type != GL2PS_TRIANGLE) + return; + + gl2psFillTriangleFromPrimitive(&t, prim, GL_TRUE); + + if(t.prop & T_CONST_COLOR && t.prop & T_ALPHA_LESS_1){ + gro->gsno = gl2ps->extgs_stack++; + gro->gsobjno = gl2ps->objects_stack ++; + } + else if(t.prop & T_CONST_COLOR && t.prop & T_VAR_ALPHA){ + gro->gsno = gl2ps->extgs_stack++; + gro->gsobjno = gl2ps->objects_stack++; + gro->trgroupno = gl2ps->trgroupobjects_stack++; + gro->trgroupobjno = gl2ps->objects_stack++; + gro->maskshno = gl2ps->mshader_stack++; + gro->maskshobjno = gl2ps->objects_stack++; + } + else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_1){ + gro->shno = gl2ps->shader_stack++; + gro->shobjno = gl2ps->objects_stack++; + } + else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_LESS_1){ + gro->gsno = gl2ps->extgs_stack++; + gro->gsobjno = gl2ps->objects_stack++; + gro->shno = gl2ps->shader_stack++; + gro->shobjno = gl2ps->objects_stack++; + } + else if(t.prop & T_VAR_COLOR && t.prop & T_VAR_ALPHA){ + gro->gsno = gl2ps->extgs_stack++; + gro->gsobjno = gl2ps->objects_stack++; + gro->shno = gl2ps->shader_stack++; + gro->shobjno = gl2ps->objects_stack++; + gro->trgroupno = gl2ps->trgroupobjects_stack++; + gro->trgroupobjno = gl2ps->objects_stack++; + gro->maskshno = gl2ps->mshader_stack++; + gro->maskshobjno = gl2ps->objects_stack++; + } +} + +/* Main stream data */ + +static void gl2psPDFgroupListWriteMainStream(void) +{ + int i, j, lastel; + GL2PSprimitive *prim = NULL, *prev = NULL; + GL2PSpdfgroup *gro; + GL2PStriangle t; + + if(!gl2ps->pdfgrouplist) + return; + + for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ + gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); + + lastel = gl2psListNbr(gro->ptrlist) - 1; + if(lastel < 0) + continue; + + prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0); + + switch(prim->type){ + case GL2PS_POINT: + gl2ps->streamlength += gl2psPrintf("1 J\n"); + gl2ps->streamlength += gl2psPrintPDFLineWidth(prim->width); + gl2ps->streamlength += gl2psPrintPDFStrokeColor(prim->verts[0].rgba); + for(j = 0; j <= lastel; ++j){ + prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); + gl2ps->streamlength += + gl2psPrintf("%f %f m %f %f l\n", + prim->verts[0].xyz[0], prim->verts[0].xyz[1], + prim->verts[0].xyz[0], prim->verts[0].xyz[1]); + } + gl2ps->streamlength += gl2psPrintf("S\n"); + gl2ps->streamlength += gl2psPrintf("0 J\n"); + break; + case GL2PS_LINE: + /* We try to use as few paths as possible to draw lines, in + order to get nice stippling even when the individual segments + are smaller than the stipple */ + gl2ps->streamlength += gl2psPrintPDFLineWidth(prim->width); + gl2ps->streamlength += gl2psPrintPDFStrokeColor(prim->verts[0].rgba); + gl2ps->streamlength += gl2psPrintPostScriptDash(prim->pattern, prim->factor, "d"); + /* start new path */ + gl2ps->streamlength += + gl2psPrintf("%f %f m\n", + prim->verts[0].xyz[0], prim->verts[0].xyz[1]); + + for(j = 1; j <= lastel; ++j){ + prev = prim; + prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); + if(!gl2psSamePosition(prim->verts[0].xyz, prev->verts[1].xyz)){ + /* the starting point of the new segment does not match the + end point of the previous line, so we end the current + path and start a new one */ + gl2ps->streamlength += + gl2psPrintf("%f %f l\n", + prev->verts[1].xyz[0], prev->verts[1].xyz[1]); + gl2ps->streamlength += + gl2psPrintf("%f %f m\n", + prim->verts[0].xyz[0], prim->verts[0].xyz[1]); + } + else{ + /* the two segements are connected, so we just append to the + current path */ + gl2ps->streamlength += + gl2psPrintf("%f %f l\n", + prim->verts[0].xyz[0], prim->verts[0].xyz[1]); + } + } + /* end last path */ + gl2ps->streamlength += + gl2psPrintf("%f %f l\n", + prim->verts[1].xyz[0], prim->verts[1].xyz[1]); + gl2ps->streamlength += gl2psPrintf("S\n"); + break; + case GL2PS_TRIANGLE: + gl2psFillTriangleFromPrimitive(&t, prim, GL_TRUE); + gl2psSortOutTrianglePDFgroup(gro); + + /* No alpha and const color: Simple PDF draw orders */ + if(t.prop & T_CONST_COLOR && t.prop & T_ALPHA_1){ + gl2ps->streamlength += gl2psPrintPDFFillColor(t.vertex[0].rgba); + for(j = 0; j <= lastel; ++j){ + prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); + gl2psFillTriangleFromPrimitive(&t, prim, GL_FALSE); + gl2ps->streamlength + += gl2psPrintf("%f %f m\n" + "%f %f l\n" + "%f %f l\n" + "h f\n", + t.vertex[0].xyz[0], t.vertex[0].xyz[1], + t.vertex[1].xyz[0], t.vertex[1].xyz[1], + t.vertex[2].xyz[0], t.vertex[2].xyz[1]); + } + } + /* Const alpha < 1 and const color: Simple PDF draw orders + and an extra extended Graphics State for the alpha const */ + else if(t.prop & T_CONST_COLOR && t.prop & T_ALPHA_LESS_1){ + gl2ps->streamlength += gl2psPrintf("q\n" + "/GS%d gs\n", + gro->gsno); + gl2ps->streamlength += gl2psPrintPDFFillColor(prim->verts[0].rgba); + for(j = 0; j <= lastel; ++j){ + prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); + gl2psFillTriangleFromPrimitive(&t, prim, GL_FALSE); + gl2ps->streamlength + += gl2psPrintf("%f %f m\n" + "%f %f l\n" + "%f %f l\n" + "h f\n", + t.vertex[0].xyz[0], t.vertex[0].xyz[1], + t.vertex[1].xyz[0], t.vertex[1].xyz[1], + t.vertex[2].xyz[0], t.vertex[2].xyz[1]); + } + gl2ps->streamlength += gl2psPrintf("Q\n"); + } + /* Variable alpha and const color: Simple PDF draw orders + and an extra extended Graphics State + Xobject + Shader + object for the alpha mask */ + else if(t.prop & T_CONST_COLOR && t.prop & T_VAR_ALPHA){ + gl2ps->streamlength += gl2psPrintf("q\n" + "/GS%d gs\n" + "/TrG%d Do\n", + gro->gsno, gro->trgroupno); + gl2ps->streamlength += gl2psPrintPDFFillColor(prim->verts[0].rgba); + for(j = 0; j <= lastel; ++j){ + prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); + gl2psFillTriangleFromPrimitive(&t, prim, GL_FALSE); + gl2ps->streamlength + += gl2psPrintf("%f %f m\n" + "%f %f l\n" + "%f %f l\n" + "h f\n", + t.vertex[0].xyz[0], t.vertex[0].xyz[1], + t.vertex[1].xyz[0], t.vertex[1].xyz[1], + t.vertex[2].xyz[0], t.vertex[2].xyz[1]); + } + gl2ps->streamlength += gl2psPrintf("Q\n"); + } + /* Variable color and no alpha: Shader Object for the colored + triangle(s) */ + else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_1){ + gl2ps->streamlength += gl2psPrintf("/Sh%d sh\n", gro->shno); + } + /* Variable color and const alpha < 1: Shader Object for the + colored triangle(s) and an extra extended Graphics State + for the alpha const */ + else if(t.prop & T_VAR_COLOR && t.prop & T_ALPHA_LESS_1){ + gl2ps->streamlength += gl2psPrintf("q\n" + "/GS%d gs\n" + "/Sh%d sh\n" + "Q\n", + gro->gsno, gro->shno); + } + /* Variable alpha and color: Shader Object for the colored + triangle(s) and an extra extended Graphics State + + Xobject + Shader object for the alpha mask */ + else if(t.prop & T_VAR_COLOR && t.prop & T_VAR_ALPHA){ + gl2ps->streamlength += gl2psPrintf("q\n" + "/GS%d gs\n" + "/TrG%d Do\n" + "/Sh%d sh\n" + "Q\n", + gro->gsno, gro->trgroupno, gro->shno); + } + break; + case GL2PS_PIXMAP: + for(j = 0; j <= lastel; ++j){ + prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); + gl2psPutPDFImage(prim->data.image, gro->imno, prim->verts[0].xyz[0], + prim->verts[0].xyz[1]); + } + break; + case GL2PS_TEXT: + for(j = 0; j <= lastel; ++j){ + prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); + gl2ps->streamlength += gl2psPrintPDFFillColor(prim->verts[0].rgba); + gl2psPutPDFText(prim->data.text, gro->fontno, prim->verts[0].xyz[0], + prim->verts[0].xyz[1]); + } + break; + case GL2PS_SPECIAL: + for(j = 0; j <= lastel; ++j){ + prim = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); + gl2psPutPDFSpecial(prim->data.text); + } + default: + break; + } + } +} + +/* Graphics State names */ + +static int gl2psPDFgroupListWriteGStateResources(void) +{ + GL2PSpdfgroup *gro; + int offs = 0; + int i; + + offs += fprintf(gl2ps->stream, + "/ExtGState\n" + "<<\n" + "/GSa 7 0 R\n"); + for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ + gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); + if(gro->gsno >= 0) + offs += fprintf(gl2ps->stream, "/GS%d %d 0 R\n", gro->gsno, gro->gsobjno); + } + offs += fprintf(gl2ps->stream, ">>\n"); + return offs; +} + +/* Main Shader names */ + +static int gl2psPDFgroupListWriteShaderResources(void) +{ + GL2PSpdfgroup *gro; + int offs = 0; + int i; + + offs += fprintf(gl2ps->stream, + "/Shading\n" + "<<\n"); + for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ + gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); + if(gro->shno >= 0) + offs += fprintf(gl2ps->stream, "/Sh%d %d 0 R\n", gro->shno, gro->shobjno); + if(gro->maskshno >= 0) + offs += fprintf(gl2ps->stream, "/TrSh%d %d 0 R\n", gro->maskshno, gro->maskshobjno); + } + offs += fprintf(gl2ps->stream,">>\n"); + return offs; +} + +/* Images & Mask Shader XObject names */ + +static int gl2psPDFgroupListWriteXObjectResources(void) +{ + int i; + GL2PSprimitive *p = NULL; + GL2PSpdfgroup *gro; + int offs = 0; + + offs += fprintf(gl2ps->stream, + "/XObject\n" + "<<\n"); + + for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ + gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); + if(!gl2psListNbr(gro->ptrlist)) + continue; + p = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0); + switch(p->type){ + case GL2PS_PIXMAP: + gro->imobjno = gl2ps->objects_stack++; + if(GL_RGBA == p->data.image->format) /* reserve one object for image mask */ + gl2ps->objects_stack++; + offs += fprintf(gl2ps->stream, "/Im%d %d 0 R\n", gro->imno, gro->imobjno); + case GL2PS_TRIANGLE: + if(gro->trgroupno >=0) + offs += fprintf(gl2ps->stream, "/TrG%d %d 0 R\n", gro->trgroupno, gro->trgroupobjno); + break; + default: + break; + } + } + offs += fprintf(gl2ps->stream,">>\n"); + return offs; +} + +/* Font names */ + +static int gl2psPDFgroupListWriteFontResources(void) +{ + int i; + GL2PSpdfgroup *gro; + int offs = 0; + + offs += fprintf(gl2ps->stream, "/Font\n<<\n"); + + for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ + gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); + if(gro->fontno < 0) + continue; + gro->fontobjno = gl2ps->objects_stack++; + offs += fprintf(gl2ps->stream, "/F%d %d 0 R\n", gro->fontno, gro->fontobjno); + } + offs += fprintf(gl2ps->stream, ">>\n"); + + return offs; +} + +static void gl2psPDFgroupListDelete(void) +{ + int i; + GL2PSpdfgroup *gro = NULL; + + if(!gl2ps->pdfgrouplist) + return; + + for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ + gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist,i); + gl2psListDelete(gro->ptrlist); + } + + gl2psListDelete(gl2ps->pdfgrouplist); + gl2ps->pdfgrouplist = NULL; +} + +/* Print 1st PDF object - file info */ + +static int gl2psPrintPDFInfo(void) +{ + int offs; + time_t now; + struct tm *newtime; + + time(&now); + newtime = gmtime(&now); + + offs = fprintf(gl2ps->stream, + "1 0 obj\n" + "<<\n" + "/Title (%s)\n" + "/Creator (GL2PS %d.%d.%d%s, %s)\n" + "/Producer (%s)\n", + gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, + GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, + gl2ps->producer); + + if(!newtime){ + offs += fprintf(gl2ps->stream, + ">>\n" + "endobj\n"); + return offs; + } + + offs += fprintf(gl2ps->stream, + "/CreationDate (D:%d%02d%02d%02d%02d%02d)\n" + ">>\n" + "endobj\n", + newtime->tm_year+1900, + newtime->tm_mon+1, + newtime->tm_mday, + newtime->tm_hour, + newtime->tm_min, + newtime->tm_sec); + return offs; +} + +/* Create catalog and page structure - 2nd and 3th PDF object */ + +static int gl2psPrintPDFCatalog(void) +{ + return fprintf(gl2ps->stream, + "2 0 obj\n" + "<<\n" + "/Type /Catalog\n" + "/Pages 3 0 R\n" + ">>\n" + "endobj\n"); +} + +static int gl2psPrintPDFPages(void) +{ + return fprintf(gl2ps->stream, + "3 0 obj\n" + "<<\n" + "/Type /Pages\n" + "/Kids [6 0 R]\n" + "/Count 1\n" + ">>\n" + "endobj\n"); +} + +/* Open stream for data - graphical objects, fonts etc. PDF object 4 */ + +static int gl2psOpenPDFDataStream(void) +{ + int offs = 0; + + offs += fprintf(gl2ps->stream, + "4 0 obj\n" + "<<\n" + "/Length 5 0 R\n" ); + offs += gl2psPrintPDFCompressorType(); + offs += fprintf(gl2ps->stream, + ">>\n" + "stream\n"); + return offs; +} + +/* Stream setup - Graphics state, fill background if allowed */ + +static int gl2psOpenPDFDataStreamWritePreface(void) +{ + int offs; + + offs = gl2psPrintf("/GSa gs\n"); + + if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ + offs += gl2psPrintPDFFillColor(gl2ps->bgcolor); + offs += gl2psPrintf("%d %d %d %d re\n", + (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], + (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]); + offs += gl2psPrintf("f\n"); + } + return offs; +} + +/* Use the functions above to create the first part of the PDF*/ + +static void gl2psPrintPDFHeader(void) +{ + int offs = 0; + gl2ps->pdfprimlist = gl2psListCreate(500, 500, sizeof(GL2PSprimitive*)); + gl2psPDFstacksInit(); + + gl2ps->xreflist = (int*)gl2psMalloc(sizeof(int) * gl2ps->objects_stack); + +#if defined(GL2PS_HAVE_ZLIB) + if(gl2ps->options & GL2PS_COMPRESS){ + gl2psSetupCompress(); + } +#endif + gl2ps->xreflist[0] = 0; + offs += fprintf(gl2ps->stream, "%%PDF-1.4\n"); + gl2ps->xreflist[1] = offs; + + offs += gl2psPrintPDFInfo(); + gl2ps->xreflist[2] = offs; + + offs += gl2psPrintPDFCatalog(); + gl2ps->xreflist[3] = offs; + + offs += gl2psPrintPDFPages(); + gl2ps->xreflist[4] = offs; + + offs += gl2psOpenPDFDataStream(); + gl2ps->xreflist[5] = offs; /* finished in gl2psPrintPDFFooter */ + gl2ps->streamlength = gl2psOpenPDFDataStreamWritePreface(); +} + +/* The central primitive drawing */ + +static void gl2psPrintPDFPrimitive(void *data) +{ + GL2PSprimitive *prim = *(GL2PSprimitive**)data; + + if((gl2ps->options & GL2PS_OCCLUSION_CULL) && prim->culled) + return; + + prim = gl2psCopyPrimitive(prim); /* deep copy */ + gl2psListAdd(gl2ps->pdfprimlist, &prim); +} + +/* close stream and ... */ + +static int gl2psClosePDFDataStream(void) +{ + int offs = 0; + +#if defined(GL2PS_HAVE_ZLIB) + if(gl2ps->options & GL2PS_COMPRESS){ + if(Z_OK != gl2psDeflate()) + gl2psMsg(GL2PS_ERROR, "Zlib deflate error"); + else + fwrite(gl2ps->compress->dest, gl2ps->compress->destLen, 1, gl2ps->stream); + gl2ps->streamlength += gl2ps->compress->destLen; + + offs += gl2ps->streamlength; + gl2psFreeCompress(); + } +#endif + + offs += fprintf(gl2ps->stream, + "endstream\n" + "endobj\n"); + return offs; +} + +/* ... write the now known length object */ + +static int gl2psPrintPDFDataStreamLength(int val) +{ + return fprintf(gl2ps->stream, + "5 0 obj\n" + "%d\n" + "endobj\n", val); +} + +/* Put the info created before in PDF objects */ + +static int gl2psPrintPDFOpenPage(void) +{ + int offs; + + /* Write fixed part */ + + offs = fprintf(gl2ps->stream, + "6 0 obj\n" + "<<\n" + "/Type /Page\n" + "/Parent 3 0 R\n" + "/MediaBox [%d %d %d %d]\n", + (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], + (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]); + + if(gl2ps->options & GL2PS_LANDSCAPE) + offs += fprintf(gl2ps->stream, "/Rotate -90\n"); + + offs += fprintf(gl2ps->stream, + "/Contents 4 0 R\n" + "/Resources\n" + "<<\n" + "/ProcSet [/PDF /Text /ImageB /ImageC] %%/ImageI\n"); + + return offs; + + /* End fixed part, proceeds in gl2psPDFgroupListWriteVariableResources() */ +} + +static int gl2psPDFgroupListWriteVariableResources(void) +{ + int offs = 0; + + /* a) Graphics States for shader alpha masks*/ + offs += gl2psPDFgroupListWriteGStateResources(); + + /* b) Shader and shader masks */ + offs += gl2psPDFgroupListWriteShaderResources(); + + /* c) XObjects (Images & Shader Masks) */ + offs += gl2psPDFgroupListWriteXObjectResources(); + + /* d) Fonts */ + offs += gl2psPDFgroupListWriteFontResources(); + + /* End resources and page */ + offs += fprintf(gl2ps->stream, + ">>\n" + ">>\n" + "endobj\n"); + return offs; +} + +/* Standard Graphics State */ + +static int gl2psPrintPDFGSObject(void) +{ + return fprintf(gl2ps->stream, + "7 0 obj\n" + "<<\n" + "/Type /ExtGState\n" + "/SA false\n" + "/SM 0.02\n" + "/OP false\n" + "/op false\n" + "/OPM 0\n" + "/BG2 /Default\n" + "/UCR2 /Default\n" + "/TR2 /Default\n" + ">>\n" + "endobj\n"); +} + +/* Put vertex' edge flag (8bit) and coordinates (32bit) in shader stream */ + +static int gl2psPrintPDFShaderStreamDataCoord(GL2PSvertex *vertex, + int (*action)(unsigned long data, int size), + GLfloat dx, GLfloat dy, + GLfloat xmin, GLfloat ymin) +{ + int offs = 0; + unsigned long imap; + GLfloat diff; + double dmax = ~1UL; + char edgeflag = 0; + + /* FIXME: temp bux fix for 64 bit archs: */ + if(sizeof(unsigned long) == 8) dmax = dmax - 2048.; + + offs += (*action)(edgeflag, 1); + + /* The Shader stream in PDF requires to be in a 'big-endian' + order */ + + if(GL2PS_ZERO(dx * dy)){ + offs += (*action)(0, 4); + offs += (*action)(0, 4); + } + else{ + diff = (vertex->xyz[0] - xmin) / dx; + if(diff > 1) + diff = 1.0F; + else if(diff < 0) + diff = 0.0F; + imap = (unsigned long)(diff * dmax); + offs += (*action)(imap, 4); + + diff = (vertex->xyz[1] - ymin) / dy; + if(diff > 1) + diff = 1.0F; + else if(diff < 0) + diff = 0.0F; + imap = (unsigned long)(diff * dmax); + offs += (*action)(imap, 4); + } + + return offs; +} + +/* Put vertex' rgb value (8bit for every component) in shader stream */ + +static int gl2psPrintPDFShaderStreamDataRGB(GL2PSvertex *vertex, + int (*action)(unsigned long data, int size)) +{ + int offs = 0; + unsigned long imap; + double dmax = ~1UL; + + /* FIXME: temp bux fix for 64 bit archs: */ + if(sizeof(unsigned long) == 8) dmax = dmax - 2048.; + + imap = (unsigned long)((vertex->rgba[0]) * dmax); + offs += (*action)(imap, 1); + + imap = (unsigned long)((vertex->rgba[1]) * dmax); + offs += (*action)(imap, 1); + + imap = (unsigned long)((vertex->rgba[2]) * dmax); + offs += (*action)(imap, 1); + + return offs; +} + +/* Put vertex' alpha (8/16bit) in shader stream */ + +static int gl2psPrintPDFShaderStreamDataAlpha(GL2PSvertex *vertex, + int (*action)(unsigned long data, int size), + int sigbyte) +{ + int offs = 0; + unsigned long imap; + double dmax = ~1UL; + + /* FIXME: temp bux fix for 64 bit archs: */ + if(sizeof(unsigned long) == 8) dmax = dmax - 2048.; + + if(sigbyte != 8 && sigbyte != 16) + sigbyte = 8; + + sigbyte /= 8; + + imap = (unsigned long)((vertex->rgba[3]) * dmax); + + offs += (*action)(imap, sigbyte); + + return offs; +} + +/* Put a triangles raw data in shader stream */ + +static int gl2psPrintPDFShaderStreamData(GL2PStriangle *triangle, + GLfloat dx, GLfloat dy, + GLfloat xmin, GLfloat ymin, + int (*action)(unsigned long data, int size), + int gray) +{ + int i, offs = 0; + GL2PSvertex v; + + if(gray && gray != 8 && gray != 16) + gray = 8; + + for(i = 0; i < 3; ++i){ + offs += gl2psPrintPDFShaderStreamDataCoord(&triangle->vertex[i], action, + dx, dy, xmin, ymin); + if(gray){ + v = triangle->vertex[i]; + offs += gl2psPrintPDFShaderStreamDataAlpha(&v, action, gray); + } + else{ + offs += gl2psPrintPDFShaderStreamDataRGB(&triangle->vertex[i], action); + } + } + + return offs; +} + +static void gl2psPDFRectHull(GLfloat *xmin, GLfloat *xmax, + GLfloat *ymin, GLfloat *ymax, + GL2PStriangle *triangles, int cnt) +{ + int i, j; + + *xmin = triangles[0].vertex[0].xyz[0]; + *xmax = triangles[0].vertex[0].xyz[0]; + *ymin = triangles[0].vertex[0].xyz[1]; + *ymax = triangles[0].vertex[0].xyz[1]; + + for(i = 0; i < cnt; ++i){ + for(j = 0; j < 3; ++j){ + if(*xmin > triangles[i].vertex[j].xyz[0]) + *xmin = triangles[i].vertex[j].xyz[0]; + if(*xmax < triangles[i].vertex[j].xyz[0]) + *xmax = triangles[i].vertex[j].xyz[0]; + if(*ymin > triangles[i].vertex[j].xyz[1]) + *ymin = triangles[i].vertex[j].xyz[1]; + if(*ymax < triangles[i].vertex[j].xyz[1]) + *ymax = triangles[i].vertex[j].xyz[1]; + } + } +} + +/* Writes shaded triangle + gray == 0 means write RGB triangles + gray == 8 8bit-grayscale (for alpha masks) + gray == 16 16bit-grayscale (for alpha masks) */ + +static int gl2psPrintPDFShader(int obj, GL2PStriangle *triangles, + int size, int gray) +{ + int i, offs = 0, vertexbytes, done = 0; + GLfloat xmin, xmax, ymin, ymax; + + switch(gray){ + case 0: + vertexbytes = 1+4+4+1+1+1; + break; + case 8: + vertexbytes = 1+4+4+1; + break; + case 16: + vertexbytes = 1+4+4+2; + break; + default: + gray = 8; + vertexbytes = 1+4+4+1; + break; + } + + gl2psPDFRectHull(&xmin, &xmax, &ymin, &ymax, triangles, size); + + offs += fprintf(gl2ps->stream, + "%d 0 obj\n" + "<< " + "/ShadingType 4 " + "/ColorSpace %s " + "/BitsPerCoordinate 32 " + "/BitsPerComponent %d " + "/BitsPerFlag 8 " + "/Decode [%f %f %f %f 0 1 %s] ", + obj, + (gray) ? "/DeviceGray" : "/DeviceRGB", + (gray) ? gray : 8, + xmin, xmax, ymin, ymax, + (gray) ? "" : "0 1 0 1"); + +#if defined(GL2PS_HAVE_ZLIB) + if(gl2ps->options & GL2PS_COMPRESS){ + gl2psAllocCompress(vertexbytes * size * 3); + + for(i = 0; i < size; ++i) + gl2psPrintPDFShaderStreamData(&triangles[i], + xmax-xmin, ymax-ymin, xmin, ymin, + gl2psWriteBigEndianCompress, gray); + + if(Z_OK == gl2psDeflate() && 23 + gl2ps->compress->destLen < gl2ps->compress->srcLen){ + offs += gl2psPrintPDFCompressorType(); + offs += fprintf(gl2ps->stream, + "/Length %d " + ">>\n" + "stream\n", + (int)gl2ps->compress->destLen); + offs += gl2ps->compress->destLen * fwrite(gl2ps->compress->dest, + gl2ps->compress->destLen, + 1, gl2ps->stream); + done = 1; + } + gl2psFreeCompress(); + } +#endif + + if(!done){ + /* no compression, or too long after compression, or compress error + -> write non-compressed entry */ + offs += fprintf(gl2ps->stream, + "/Length %d " + ">>\n" + "stream\n", + vertexbytes * 3 * size); + for(i = 0; i < size; ++i) + offs += gl2psPrintPDFShaderStreamData(&triangles[i], + xmax-xmin, ymax-ymin, xmin, ymin, + gl2psWriteBigEndian, gray); + } + + offs += fprintf(gl2ps->stream, + "\nendstream\n" + "endobj\n"); + + return offs; +} + +/* Writes a XObject for a shaded triangle mask */ + +static int gl2psPrintPDFShaderMask(int obj, int childobj) +{ + int offs = 0, len; + + offs += fprintf(gl2ps->stream, + "%d 0 obj\n" + "<<\n" + "/Type /XObject\n" + "/Subtype /Form\n" + "/BBox [ %d %d %d %d ]\n" + "/Group \n<<\n/S /Transparency /CS /DeviceRGB\n" + ">>\n", + obj, + (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], + (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]); + + len = (childobj>0) + ? strlen("/TrSh sh\n") + (int)log10((double)childobj)+1 + : strlen("/TrSh0 sh\n"); + + offs += fprintf(gl2ps->stream, + "/Length %d\n" + ">>\n" + "stream\n", + len); + offs += fprintf(gl2ps->stream, + "/TrSh%d sh\n", + childobj); + offs += fprintf(gl2ps->stream, + "endstream\n" + "endobj\n"); + + return offs; +} + +/* Writes a Extended graphics state for a shaded triangle mask if + simplealpha ist true the childobj argument is ignored and a /ca + statement will be written instead */ + +static int gl2psPrintPDFShaderExtGS(int obj, int childobj) +{ + int offs = 0; + + offs += fprintf(gl2ps->stream, + "%d 0 obj\n" + "<<\n", + obj); + + offs += fprintf(gl2ps->stream, + "/SMask << /S /Alpha /G %d 0 R >> ", + childobj); + + offs += fprintf(gl2ps->stream, + ">>\n" + "endobj\n"); + return offs; +} + +/* a simple graphics state */ + +static int gl2psPrintPDFShaderSimpleExtGS(int obj, GLfloat alpha) +{ + int offs = 0; + + offs += fprintf(gl2ps->stream, + "%d 0 obj\n" + "<<\n" + "/ca %g" + ">>\n" + "endobj\n", + obj, alpha); + return offs; +} + +/* Similar groups of functions for pixmaps and text */ + +static int gl2psPrintPDFPixmapStreamData(GL2PSimage *im, + int (*action)(unsigned long data, int size), + int gray) +{ + int x, y, shift; + GLfloat r, g, b, a; + + if(im->format != GL_RGBA && gray) + return 0; + + if(gray && gray != 8 && gray != 16) + gray = 8; + + gray /= 8; + + shift = (sizeof(unsigned long) - 1) * 8; + + for(y = 0; y < im->height; ++y){ + for(x = 0; x < im->width; ++x){ + a = gl2psGetRGB(im, x, y, &r, &g, &b); + if(im->format == GL_RGBA && gray){ + (*action)((unsigned long)(a * 255) << shift, gray); + } + else{ + (*action)((unsigned long)(r * 255) << shift, 1); + (*action)((unsigned long)(g * 255) << shift, 1); + (*action)((unsigned long)(b * 255) << shift, 1); + } + } + } + + switch(gray){ + case 0: return 3 * im->width * im->height; + case 1: return im->width * im->height; + case 2: return 2 * im->width * im->height; + default: return 3 * im->width * im->height; + } +} + +static int gl2psPrintPDFPixmap(int obj, int childobj, GL2PSimage *im, int gray) +{ + int offs = 0, done = 0, sigbytes = 3; + + if(gray && gray !=8 && gray != 16) + gray = 8; + + if(gray) + sigbytes = gray / 8; + + offs += fprintf(gl2ps->stream, + "%d 0 obj\n" + "<<\n" + "/Type /XObject\n" + "/Subtype /Image\n" + "/Width %d\n" + "/Height %d\n" + "/ColorSpace %s \n" + "/BitsPerComponent 8\n", + obj, + (int)im->width, (int)im->height, + (gray) ? "/DeviceGray" : "/DeviceRGB" ); + if(GL_RGBA == im->format && gray == 0){ + offs += fprintf(gl2ps->stream, + "/SMask %d 0 R\n", + childobj); + } + +#if defined(GL2PS_HAVE_ZLIB) + if(gl2ps->options & GL2PS_COMPRESS){ + gl2psAllocCompress((int)(im->width * im->height * sigbytes)); + + gl2psPrintPDFPixmapStreamData(im, gl2psWriteBigEndianCompress, gray); + + if(Z_OK == gl2psDeflate() && 23 + gl2ps->compress->destLen < gl2ps->compress->srcLen){ + offs += gl2psPrintPDFCompressorType(); + offs += fprintf(gl2ps->stream, + "/Length %d " + ">>\n" + "stream\n", + (int)gl2ps->compress->destLen); + offs += gl2ps->compress->destLen * fwrite(gl2ps->compress->dest, gl2ps->compress->destLen, + 1, gl2ps->stream); + done = 1; + } + gl2psFreeCompress(); + } +#endif + + if(!done){ + /* no compression, or too long after compression, or compress error + -> write non-compressed entry */ + offs += fprintf(gl2ps->stream, + "/Length %d " + ">>\n" + "stream\n", + (int)(im->width * im->height * sigbytes)); + offs += gl2psPrintPDFPixmapStreamData(im, gl2psWriteBigEndian, gray); + } + + offs += fprintf(gl2ps->stream, + "\nendstream\n" + "endobj\n"); + + return offs; +} + +static int gl2psPrintPDFText(int obj, GL2PSstring *s, int fontnumber) +{ + int offs = 0; + + offs += fprintf(gl2ps->stream, + "%d 0 obj\n" + "<<\n" + "/Type /Font\n" + "/Subtype /Type1\n" + "/Name /F%d\n" + "/BaseFont /%s\n" + "/Encoding /MacRomanEncoding\n" + ">>\n" + "endobj\n", + obj, fontnumber, s->fontname); + return offs; +} + +/* Write the physical objects */ + +static int gl2psPDFgroupListWriteObjects(int entryoffs) +{ + int i,j; + GL2PSprimitive *p = NULL; + GL2PSpdfgroup *gro; + int offs = entryoffs; + GL2PStriangle *triangles; + int size = 0; + + if(!gl2ps->pdfgrouplist) + return offs; + + for(i = 0; i < gl2psListNbr(gl2ps->pdfgrouplist); ++i){ + gro = (GL2PSpdfgroup*)gl2psListPointer(gl2ps->pdfgrouplist, i); + if(!gl2psListNbr(gro->ptrlist)) + continue; + p = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, 0); + switch(p->type){ + case GL2PS_POINT: + break; + case GL2PS_LINE: + break; + case GL2PS_TRIANGLE: + size = gl2psListNbr(gro->ptrlist); + triangles = (GL2PStriangle*)gl2psMalloc(sizeof(GL2PStriangle) * size); + for(j = 0; j < size; ++j){ + p = *(GL2PSprimitive**)gl2psListPointer(gro->ptrlist, j); + gl2psFillTriangleFromPrimitive(&triangles[j], p, GL_TRUE); + } + if(triangles[0].prop & T_VAR_COLOR){ + gl2ps->xreflist[gro->shobjno] = offs; + offs += gl2psPrintPDFShader(gro->shobjno, triangles, size, 0); + } + if(triangles[0].prop & T_ALPHA_LESS_1){ + gl2ps->xreflist[gro->gsobjno] = offs; + offs += gl2psPrintPDFShaderSimpleExtGS(gro->gsobjno, triangles[0].vertex[0].rgba[3]); + } + if(triangles[0].prop & T_VAR_ALPHA){ + gl2ps->xreflist[gro->gsobjno] = offs; + offs += gl2psPrintPDFShaderExtGS(gro->gsobjno, gro->trgroupobjno); + gl2ps->xreflist[gro->trgroupobjno] = offs; + offs += gl2psPrintPDFShaderMask(gro->trgroupobjno, gro->maskshno); + gl2ps->xreflist[gro->maskshobjno] = offs; + offs += gl2psPrintPDFShader(gro->maskshobjno, triangles, size, 8); + } + gl2psFree(triangles); + break; + case GL2PS_PIXMAP: + gl2ps->xreflist[gro->imobjno] = offs; + offs += gl2psPrintPDFPixmap(gro->imobjno, gro->imobjno+1, p->data.image, 0); + if(p->data.image->format == GL_RGBA){ + gl2ps->xreflist[gro->imobjno+1] = offs; + offs += gl2psPrintPDFPixmap(gro->imobjno+1, -1, p->data.image, 8); + } + break; + case GL2PS_TEXT: + gl2ps->xreflist[gro->fontobjno] = offs; + offs += gl2psPrintPDFText(gro->fontobjno,p->data.text,gro->fontno); + break; + case GL2PS_SPECIAL : + /* alignment contains the format for which the special output text + is intended */ + if(p->data.text->alignment == GL2PS_PDF) + offs += fprintf(gl2ps->stream, "%s\n", p->data.text->str); + break; + default: + break; + } + } + return offs; +} + +/* All variable data has been written at this point and all required + functioninality has been gathered, so we can write now file footer + with cross reference table and trailer */ + +static void gl2psPrintPDFFooter(void) +{ + int i, offs; + + gl2psPDFgroupListInit(); + gl2psPDFgroupListWriteMainStream(); + + offs = gl2ps->xreflist[5] + gl2ps->streamlength; + offs += gl2psClosePDFDataStream(); + gl2ps->xreflist[5] = offs; + + offs += gl2psPrintPDFDataStreamLength(gl2ps->streamlength); + gl2ps->xreflist[6] = offs; + gl2ps->streamlength = 0; + + offs += gl2psPrintPDFOpenPage(); + offs += gl2psPDFgroupListWriteVariableResources(); + gl2ps->xreflist = (int*)gl2psRealloc(gl2ps->xreflist, + sizeof(int) * (gl2ps->objects_stack + 1)); + gl2ps->xreflist[7] = offs; + + offs += gl2psPrintPDFGSObject(); + gl2ps->xreflist[8] = offs; + + gl2ps->xreflist[gl2ps->objects_stack] = + gl2psPDFgroupListWriteObjects(gl2ps->xreflist[8]); + + /* Start cross reference table. The file has to been opened in + binary mode to preserve the 20 digit string length! */ + fprintf(gl2ps->stream, + "xref\n" + "0 %d\n" + "%010d 65535 f \n", gl2ps->objects_stack, 0); + + for(i = 1; i < gl2ps->objects_stack; ++i) + fprintf(gl2ps->stream, "%010d 00000 n \n", gl2ps->xreflist[i]); + + fprintf(gl2ps->stream, + "trailer\n" + "<<\n" + "/Size %d\n" + "/Info 1 0 R\n" + "/Root 2 0 R\n" + ">>\n" + "startxref\n%d\n" + "%%%%EOF\n", + gl2ps->objects_stack, gl2ps->xreflist[gl2ps->objects_stack]); + + /* Free auxiliary lists and arrays */ + gl2psFree(gl2ps->xreflist); + gl2psListAction(gl2ps->pdfprimlist, gl2psFreePrimitive); + gl2psListDelete(gl2ps->pdfprimlist); + gl2psPDFgroupListDelete(); + +#if defined(GL2PS_HAVE_ZLIB) + if(gl2ps->options & GL2PS_COMPRESS){ + gl2psFreeCompress(); + gl2psFree(gl2ps->compress); + gl2ps->compress = NULL; + } +#endif +} + +/* PDF begin viewport */ + +static void gl2psPrintPDFBeginViewport(GLint viewport[4]) +{ + int offs = 0; + GLint idx; + GLfloat rgba[4]; + int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3]; + + glRenderMode(GL_FEEDBACK); + + if(gl2ps->header){ + gl2psPrintPDFHeader(); + gl2ps->header = GL_FALSE; + } + + offs += gl2psPrintf("q\n"); + + if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ + if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){ + glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba); + } + else{ + glGetIntegerv(GL_INDEX_CLEAR_VALUE, &idx); + rgba[0] = gl2ps->colormap[idx][0]; + rgba[1] = gl2ps->colormap[idx][1]; + rgba[2] = gl2ps->colormap[idx][2]; + rgba[3] = 1.0F; + } + offs += gl2psPrintPDFFillColor(rgba); + offs += gl2psPrintf("%d %d %d %d re\n" + "W\n" + "f\n", + x, y, w, h); + } + else{ + offs += gl2psPrintf("%d %d %d %d re\n" + "W\n" + "n\n", + x, y, w, h); + } + + gl2ps->streamlength += offs; +} + +static GLint gl2psPrintPDFEndViewport(void) +{ + GLint res; + + res = gl2psPrintPrimitives(); + gl2ps->streamlength += gl2psPrintf("Q\n"); + return res; +} + +static void gl2psPrintPDFFinalPrimitive(void) +{ +} + +/* definition of the PDF backend */ + +static GL2PSbackend gl2psPDF = { + gl2psPrintPDFHeader, + gl2psPrintPDFFooter, + gl2psPrintPDFBeginViewport, + gl2psPrintPDFEndViewport, + gl2psPrintPDFPrimitive, + gl2psPrintPDFFinalPrimitive, + "pdf", + "Portable Document Format" +}; + +/********************************************************************* + * + * SVG routines + * + *********************************************************************/ + +static void gl2psSVGGetCoordsAndColors(int n, GL2PSvertex *verts, + GL2PSxyz *xyz, GL2PSrgba *rgba) +{ + int i, j; + + for(i = 0; i < n; i++){ + xyz[i][0] = verts[i].xyz[0]; + xyz[i][1] = gl2ps->viewport[3] - verts[i].xyz[1]; + xyz[i][2] = 0.0F; + for(j = 0; j < 4; j++) + rgba[i][j] = verts[i].rgba[j]; + } +} + +static void gl2psSVGGetColorString(GL2PSrgba rgba, char str[32]) +{ + int r = (int)(255. * rgba[0]); + int g = (int)(255. * rgba[1]); + int b = (int)(255. * rgba[2]); + int rc = (r < 0) ? 0 : (r > 255) ? 255 : r; + int gc = (g < 0) ? 0 : (g > 255) ? 255 : g; + int bc = (b < 0) ? 0 : (b > 255) ? 255 : b; + sprintf(str, "#%2.2x%2.2x%2.2x", rc, gc, bc); +} + +static void gl2psPrintSVGHeader(void) +{ + int x, y, width, height; + char col[32]; + time_t now; + + time(&now); + + if (gl2ps->options & GL2PS_LANDSCAPE){ + x = (int)gl2ps->viewport[1]; + y = (int)gl2ps->viewport[0]; + width = (int)gl2ps->viewport[3]; + height = (int)gl2ps->viewport[2]; + } + else{ + x = (int)gl2ps->viewport[0]; + y = (int)gl2ps->viewport[1]; + width = (int)gl2ps->viewport[2]; + height = (int)gl2ps->viewport[3]; + } + + /* Compressed SVG files (.svgz) are simply gzipped SVG files */ + gl2psPrintGzipHeader(); + + gl2psPrintf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"); + gl2psPrintf("<svg xmlns=\"http://www.w3.org/2000/svg\"\n"); + gl2psPrintf(" xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n" + " width=\"%dpx\" height=\"%dpx\" viewBox=\"%d %d %d %d\">\n", + width, height, x, y, width, height); + gl2psPrintf("<title>%s</title>\n", gl2ps->title); + gl2psPrintf("<desc>\n"); + gl2psPrintf("Creator: GL2PS %d.%d.%d%s, %s\n" + "For: %s\n" + "CreationDate: %s", + GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, GL2PS_PATCH_VERSION, + GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, gl2ps->producer, ctime(&now)); + gl2psPrintf("</desc>\n"); + gl2psPrintf("<defs>\n"); + gl2psPrintf("</defs>\n"); + + if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ + gl2psSVGGetColorString(gl2ps->bgcolor, col); + gl2psPrintf("<polygon fill=\"%s\" points=\"%d,%d %d,%d %d,%d %d,%d\"/>\n", col, + (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], + (int)gl2ps->viewport[2], (int)gl2ps->viewport[1], + (int)gl2ps->viewport[2], (int)gl2ps->viewport[3], + (int)gl2ps->viewport[0], (int)gl2ps->viewport[3]); + } + + /* group all the primitives and disable antialiasing */ + gl2psPrintf("<g shape-rendering=\"crispEdges\">\n"); +} + +static void gl2psPrintSVGSmoothTriangle(GL2PSxyz xyz[3], GL2PSrgba rgba[3]) +{ + int i; + GL2PSxyz xyz2[3]; + GL2PSrgba rgba2[3]; + char col[32]; + + /* Apparently there is no easy way to do Gouraud shading in SVG + without explicitly pre-defining gradients, so for now we just do + recursive subdivision */ + + if(gl2psSameColorThreshold(3, rgba, gl2ps->threshold)){ + gl2psSVGGetColorString(rgba[0], col); + gl2psPrintf("<polygon fill=\"%s\" ", col); + if(rgba[0][3] < 1.0F) gl2psPrintf("fill-opacity=\"%g\" ", rgba[0][3]); + gl2psPrintf("points=\"%g,%g %g,%g %g,%g\"/>\n", xyz[0][0], xyz[0][1], + xyz[1][0], xyz[1][1], xyz[2][0], xyz[2][1]); + } + else{ + /* subdivide into 4 subtriangles */ + for(i = 0; i < 3; i++){ + xyz2[0][i] = xyz[0][i]; + xyz2[1][i] = 0.5F * (xyz[0][i] + xyz[1][i]); + xyz2[2][i] = 0.5F * (xyz[0][i] + xyz[2][i]); + } + for(i = 0; i < 4; i++){ + rgba2[0][i] = rgba[0][i]; + rgba2[1][i] = 0.5F * (rgba[0][i] + rgba[1][i]); + rgba2[2][i] = 0.5F * (rgba[0][i] + rgba[2][i]); + } + gl2psPrintSVGSmoothTriangle(xyz2, rgba2); + for(i = 0; i < 3; i++){ + xyz2[0][i] = 0.5F * (xyz[0][i] + xyz[1][i]); + xyz2[1][i] = xyz[1][i]; + xyz2[2][i] = 0.5F * (xyz[1][i] + xyz[2][i]); + } + for(i = 0; i < 4; i++){ + rgba2[0][i] = 0.5F * (rgba[0][i] + rgba[1][i]); + rgba2[1][i] = rgba[1][i]; + rgba2[2][i] = 0.5F * (rgba[1][i] + rgba[2][i]); + } + gl2psPrintSVGSmoothTriangle(xyz2, rgba2); + for(i = 0; i < 3; i++){ + xyz2[0][i] = 0.5F * (xyz[0][i] + xyz[2][i]); + xyz2[1][i] = xyz[2][i]; + xyz2[2][i] = 0.5F * (xyz[1][i] + xyz[2][i]); + } + for(i = 0; i < 4; i++){ + rgba2[0][i] = 0.5F * (rgba[0][i] + rgba[2][i]); + rgba2[1][i] = rgba[2][i]; + rgba2[2][i] = 0.5F * (rgba[1][i] + rgba[2][i]); + } + gl2psPrintSVGSmoothTriangle(xyz2, rgba2); + for(i = 0; i < 3; i++){ + xyz2[0][i] = 0.5F * (xyz[0][i] + xyz[1][i]); + xyz2[1][i] = 0.5F * (xyz[1][i] + xyz[2][i]); + xyz2[2][i] = 0.5F * (xyz[0][i] + xyz[2][i]); + } + for(i = 0; i < 4; i++){ + rgba2[0][i] = 0.5F * (rgba[0][i] + rgba[1][i]); + rgba2[1][i] = 0.5F * (rgba[1][i] + rgba[2][i]); + rgba2[2][i] = 0.5F * (rgba[0][i] + rgba[2][i]); + } + gl2psPrintSVGSmoothTriangle(xyz2, rgba2); + } +} + +static void gl2psPrintSVGDash(GLushort pattern, GLint factor) +{ + int i, n, array[10]; + + if(!pattern || !factor) return; /* solid line */ + + gl2psParseStipplePattern(pattern, factor, &n, array); + gl2psPrintf("stroke-dasharray=\""); + for(i = 0; i < n; i++){ + if(i) gl2psPrintf(","); + gl2psPrintf("%d", array[i]); + } + gl2psPrintf("\" "); +} + +static void gl2psEndSVGLine(void) +{ + int i; + if(gl2ps->lastvertex.rgba[0] >= 0.){ + gl2psPrintf("%g,%g\"/>\n", gl2ps->lastvertex.xyz[0], + gl2ps->viewport[3] - gl2ps->lastvertex.xyz[1]); + for(i = 0; i < 3; i++) + gl2ps->lastvertex.xyz[i] = -1.; + for(i = 0; i < 4; i++) + gl2ps->lastvertex.rgba[i] = -1.; + } +} + +static void gl2psPrintSVGPixmap(GLfloat x, GLfloat y, GL2PSimage *pixmap) +{ +#if defined(GL2PS_HAVE_LIBPNG) + GL2PSlist *png; + unsigned char c; + int i; + + /* The only image types supported by the SVG standard are JPEG, PNG + and SVG. Here we choose PNG, and since we want to embed the image + directly in the SVG stream (and not link to an external image + file), we need to encode the pixmap into PNG in memory, then + encode it into base64. */ + + png = gl2psListCreate(pixmap->width * pixmap->height * 3, 1000, + sizeof(unsigned char)); + gl2psConvertPixmapToPNG(pixmap, png); + gl2psListEncodeBase64(png); + + /* Use "transform" attribute to scale and translate the image from + the coordinates origin (0,0) */ + y -= pixmap->zoom_y * (GLfloat)pixmap->height; + gl2psPrintf("<image x=\"%g\" y=\"%g\" width=\"%d\" height=\"%d\"\n", + 0., 0., pixmap->width, pixmap->height); + gl2psPrintf("transform=\"matrix(%g,0,0,%g,%g,%g)\"\n", + pixmap->zoom_x, pixmap->zoom_y, x, y); + gl2psPrintf("xlink:href=\"data:image/png;base64,"); + for(i = 0; i < gl2psListNbr(png); i++){ + gl2psListRead(png, i, &c); + gl2psPrintf("%c", c); + } + gl2psPrintf("\"/>\n"); + gl2psListDelete(png); +#else + (void) x; (void) y; (void) pixmap; /* not used */ + gl2psMsg(GL2PS_WARNING, "GL2PS must be compiled with PNG support in " + "order to embed images in SVG streams"); +#endif +} + +static void gl2psPrintSVGPrimitive(void *data) +{ + GL2PSprimitive *prim; + GL2PSxyz xyz[4]; + GL2PSrgba rgba[4]; + char col[32]; + int newline; + + prim = *(GL2PSprimitive**)data; + + if((gl2ps->options & GL2PS_OCCLUSION_CULL) && prim->culled) return; + + /* We try to draw connected lines as a single path to get nice line + joins and correct stippling. So if the primitive to print is not + a line we must first finish the current line (if any): */ + if(prim->type != GL2PS_LINE) gl2psEndSVGLine(); + + gl2psSVGGetCoordsAndColors(prim->numverts, prim->verts, xyz, rgba); + + switch(prim->type){ + case GL2PS_POINT : + gl2psSVGGetColorString(rgba[0], col); + gl2psPrintf("<circle fill=\"%s\" ", col); + if(rgba[0][3] < 1.0F) gl2psPrintf("fill-opacity=\"%g\" ", rgba[0][3]); + gl2psPrintf("cx=\"%g\" cy=\"%g\" r=\"%g\"/>\n", + xyz[0][0], xyz[0][1], 0.5 * prim->width); + break; + case GL2PS_LINE : + if(!gl2psSamePosition(gl2ps->lastvertex.xyz, prim->verts[0].xyz) || + !gl2psSameColor(gl2ps->lastrgba, prim->verts[0].rgba) || + gl2ps->lastlinewidth != prim->width || + gl2ps->lastpattern != prim->pattern || + gl2ps->lastfactor != prim->factor){ + /* End the current line if the new segment does not start where + the last one ended, or if the color, the width or the + stippling have changed (we will need to use multi-point + gradients for smooth-shaded lines) */ + gl2psEndSVGLine(); + newline = 1; + } + else{ + newline = 0; + } + gl2ps->lastvertex = prim->verts[1]; + gl2psSetLastColor(prim->verts[0].rgba); + gl2ps->lastlinewidth = prim->width; + gl2ps->lastpattern = prim->pattern; + gl2ps->lastfactor = prim->factor; + if(newline){ + gl2psSVGGetColorString(rgba[0], col); + gl2psPrintf("<polyline fill=\"none\" stroke=\"%s\" stroke-width=\"%g\" ", + col, prim->width); + if(rgba[0][3] < 1.0F) gl2psPrintf("stroke-opacity=\"%g\" ", rgba[0][3]); + gl2psPrintSVGDash(prim->pattern, prim->factor); + gl2psPrintf("points=\"%g,%g ", xyz[0][0], xyz[0][1]); + } + else{ + gl2psPrintf("%g,%g ", xyz[0][0], xyz[0][1]); + } + break; + case GL2PS_TRIANGLE : + gl2psPrintSVGSmoothTriangle(xyz, rgba); + break; + case GL2PS_QUADRANGLE : + gl2psMsg(GL2PS_WARNING, "There should not be any quad left to print"); + break; + case GL2PS_PIXMAP : + gl2psPrintSVGPixmap(xyz[0][0], xyz[0][1], prim->data.image); + break; + case GL2PS_TEXT : + gl2psSVGGetColorString(prim->verts[0].rgba, col); + gl2psPrintf("<text fill=\"%s\" x=\"%g\" y=\"%g\" font-size=\"%d\" ", + col, xyz[0][0], xyz[0][1], prim->data.text->fontsize); + if(prim->data.text->angle) + gl2psPrintf("transform=\"rotate(%g, %g, %g)\" ", + -prim->data.text->angle, xyz[0][0], xyz[0][1]); + switch(prim->data.text->alignment){ + case GL2PS_TEXT_C: + gl2psPrintf("text-anchor=\"middle\" baseline-shift=\"%d\" ", + -prim->data.text->fontsize / 2); + break; + case GL2PS_TEXT_CL: + gl2psPrintf("text-anchor=\"start\" baseline-shift=\"%d\" ", + -prim->data.text->fontsize / 2); + break; + case GL2PS_TEXT_CR: + gl2psPrintf("text-anchor=\"end\" baseline-shift=\"%d\" ", + -prim->data.text->fontsize / 2); + break; + case GL2PS_TEXT_B: + gl2psPrintf("text-anchor=\"middle\" baseline-shift=\"0\" "); + break; + case GL2PS_TEXT_BR: + gl2psPrintf("text-anchor=\"end\" baseline-shift=\"0\" "); + break; + case GL2PS_TEXT_T: + gl2psPrintf("text-anchor=\"middle\" baseline-shift=\"%d\" ", + -prim->data.text->fontsize); + break; + case GL2PS_TEXT_TL: + gl2psPrintf("text-anchor=\"start\" baseline-shift=\"%d\" ", + -prim->data.text->fontsize); + break; + case GL2PS_TEXT_TR: + gl2psPrintf("text-anchor=\"end\" baseline-shift=\"%d\" ", + -prim->data.text->fontsize); + break; + case GL2PS_TEXT_BL: + default: /* same as GL2PS_TEXT_BL */ + gl2psPrintf("text-anchor=\"start\" baseline-shift=\"0\" "); + break; + } + if(!strcmp(prim->data.text->fontname, "Times-Roman")) + gl2psPrintf("font-family=\"Times\">"); + else if(!strcmp(prim->data.text->fontname, "Times-Bold")) + gl2psPrintf("font-family=\"Times\" font-weight=\"bold\">"); + else if(!strcmp(prim->data.text->fontname, "Times-Italic")) + gl2psPrintf("font-family=\"Times\" font-style=\"italic\">"); + else if(!strcmp(prim->data.text->fontname, "Times-BoldItalic")) + gl2psPrintf("font-family=\"Times\" font-style=\"italic\" font-weight=\"bold\">"); + else if(!strcmp(prim->data.text->fontname, "Helvetica-Bold")) + gl2psPrintf("font-family=\"Helvetica\" font-weight=\"bold\">"); + else if(!strcmp(prim->data.text->fontname, "Helvetica-Oblique")) + gl2psPrintf("font-family=\"Helvetica\" font-style=\"oblique\">"); + else if(!strcmp(prim->data.text->fontname, "Helvetica-BoldOblique")) + gl2psPrintf("font-family=\"Helvetica\" font-style=\"oblique\" font-weight=\"bold\">"); + else if(!strcmp(prim->data.text->fontname, "Courier-Bold")) + gl2psPrintf("font-family=\"Courier\" font-weight=\"bold\">"); + else if(!strcmp(prim->data.text->fontname, "Courier-Oblique")) + gl2psPrintf("font-family=\"Courier\" font-style=\"oblique\">"); + else if(!strcmp(prim->data.text->fontname, "Courier-BoldOblique")) + gl2psPrintf("font-family=\"Courier\" font-style=\"oblique\" font-weight=\"bold\">"); + else + gl2psPrintf("font-family=\"%s\">", prim->data.text->fontname); + gl2psPrintf("%s</text>\n", prim->data.text->str); + break; + case GL2PS_SPECIAL : + /* alignment contains the format for which the special output text + is intended */ + if(prim->data.text->alignment == GL2PS_SVG) + gl2psPrintf("%s\n", prim->data.text->str); + break; + default : + break; + } +} + +static void gl2psPrintSVGFooter(void) +{ + gl2psPrintf("</g>\n"); + gl2psPrintf("</svg>\n"); + + gl2psPrintGzipFooter(); +} + +static void gl2psPrintSVGBeginViewport(GLint viewport[4]) +{ + GLint idx; + char col[32]; + GLfloat rgba[4]; + int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3]; + + glRenderMode(GL_FEEDBACK); + + if(gl2ps->header){ + gl2psPrintSVGHeader(); + gl2ps->header = GL_FALSE; + } + + if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ + if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){ + glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba); + } + else{ + glGetIntegerv(GL_INDEX_CLEAR_VALUE, &idx); + rgba[0] = gl2ps->colormap[idx][0]; + rgba[1] = gl2ps->colormap[idx][1]; + rgba[2] = gl2ps->colormap[idx][2]; + rgba[3] = 1.0F; + } + gl2psSVGGetColorString(rgba, col); + gl2psPrintf("<polygon fill=\"%s\" points=\"%d,%d %d,%d %d,%d %d,%d\"/>\n", col, + x, gl2ps->viewport[3] - y, + x + w, gl2ps->viewport[3] - y, + x + w, gl2ps->viewport[3] - (y + h), + x, gl2ps->viewport[3] - (y + h)); + } + + gl2psPrintf("<clipPath id=\"cp%d%d%d%d\">\n", x, y, w, h); + gl2psPrintf(" <polygon points=\"%d,%d %d,%d %d,%d %d,%d\"/>\n", + x, gl2ps->viewport[3] - y, + x + w, gl2ps->viewport[3] - y, + x + w, gl2ps->viewport[3] - (y + h), + x, gl2ps->viewport[3] - (y + h)); + gl2psPrintf("</clipPath>\n"); + gl2psPrintf("<g clip-path=\"url(#cp%d%d%d%d)\">\n", x, y, w, h); +} + +static GLint gl2psPrintSVGEndViewport(void) +{ + GLint res; + + res = gl2psPrintPrimitives(); + gl2psPrintf("</g>\n"); + return res; +} + +static void gl2psPrintSVGFinalPrimitive(void) +{ + /* End any remaining line, if any */ + gl2psEndSVGLine(); +} + +/* definition of the SVG backend */ + +static GL2PSbackend gl2psSVG = { + gl2psPrintSVGHeader, + gl2psPrintSVGFooter, + gl2psPrintSVGBeginViewport, + gl2psPrintSVGEndViewport, + gl2psPrintSVGPrimitive, + gl2psPrintSVGFinalPrimitive, + "svg", + "Scalable Vector Graphics" +}; + +/********************************************************************* + * + * PGF routines + * + *********************************************************************/ + +static void gl2psPrintPGFColor(GL2PSrgba rgba) +{ + if(!gl2psSameColor(gl2ps->lastrgba, rgba)){ + gl2psSetLastColor(rgba); + fprintf(gl2ps->stream, "\\color[rgb]{%f,%f,%f}\n", rgba[0], rgba[1], rgba[2]); + } +} + +static void gl2psPrintPGFHeader(void) +{ + time_t now; + + time(&now); + + fprintf(gl2ps->stream, + "%% Title: %s\n" + "%% Creator: GL2PS %d.%d.%d%s, %s\n" + "%% For: %s\n" + "%% CreationDate: %s", + gl2ps->title, GL2PS_MAJOR_VERSION, GL2PS_MINOR_VERSION, + GL2PS_PATCH_VERSION, GL2PS_EXTRA_VERSION, GL2PS_COPYRIGHT, + gl2ps->producer, ctime(&now)); + + fprintf(gl2ps->stream, "\\begin{pgfpicture}\n"); + if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ + gl2psPrintPGFColor(gl2ps->bgcolor); + fprintf(gl2ps->stream, + "\\pgfpathrectanglecorners{" + "\\pgfpoint{%dpt}{%dpt}}{\\pgfpoint{%dpt}{%dpt}}\n" + "\\pgfusepath{fill}\n", + (int)gl2ps->viewport[0], (int)gl2ps->viewport[1], + (int)gl2ps->viewport[2], (int)gl2ps->viewport[3]); + } +} + +static void gl2psPrintPGFDash(GLushort pattern, GLint factor) +{ + int i, n, array[10]; + + if(pattern == gl2ps->lastpattern && factor == gl2ps->lastfactor) + return; + + gl2ps->lastpattern = pattern; + gl2ps->lastfactor = factor; + + if(!pattern || !factor){ + /* solid line */ + fprintf(gl2ps->stream, "\\pgfsetdash{}{0pt}\n"); + } + else{ + gl2psParseStipplePattern(pattern, factor, &n, array); + fprintf(gl2ps->stream, "\\pgfsetdash{"); + for(i = 0; i < n; i++) fprintf(gl2ps->stream, "{%dpt}", array[i]); + fprintf(gl2ps->stream, "}{0pt}\n"); + } +} + +static const char *gl2psPGFTextAlignment(int align) +{ + switch(align){ + case GL2PS_TEXT_C : return "center"; + case GL2PS_TEXT_CL : return "west"; + case GL2PS_TEXT_CR : return "east"; + case GL2PS_TEXT_B : return "south"; + case GL2PS_TEXT_BR : return "south east"; + case GL2PS_TEXT_T : return "north"; + case GL2PS_TEXT_TL : return "north west"; + case GL2PS_TEXT_TR : return "north east"; + case GL2PS_TEXT_BL : + default : return "south west"; + } +} + +static void gl2psPrintPGFPrimitive(void *data) +{ + GL2PSprimitive *prim; + + prim = *(GL2PSprimitive**)data; + + switch(prim->type){ + case GL2PS_POINT : + /* Points in openGL are rectangular */ + gl2psPrintPGFColor(prim->verts[0].rgba); + fprintf(gl2ps->stream, + "\\pgfpathrectangle{\\pgfpoint{%fpt}{%fpt}}" + "{\\pgfpoint{%fpt}{%fpt}}\n\\pgfusepath{fill}\n", + prim->verts[0].xyz[0]-0.5*prim->width, + prim->verts[0].xyz[1]-0.5*prim->width, + prim->width,prim->width); + break; + case GL2PS_LINE : + gl2psPrintPGFColor(prim->verts[0].rgba); + if(gl2ps->lastlinewidth != prim->width){ + gl2ps->lastlinewidth = prim->width; + fprintf(gl2ps->stream, "\\pgfsetlinewidth{%fpt}\n", gl2ps->lastlinewidth); + } + gl2psPrintPGFDash(prim->pattern, prim->factor); + fprintf(gl2ps->stream, + "\\pgfpathmoveto{\\pgfpoint{%fpt}{%fpt}}\n" + "\\pgflineto{\\pgfpoint{%fpt}{%fpt}}\n" + "\\pgfusepath{stroke}\n", + prim->verts[1].xyz[0], prim->verts[1].xyz[1], + prim->verts[0].xyz[0], prim->verts[0].xyz[1]); + break; + case GL2PS_TRIANGLE : + if(gl2ps->lastlinewidth != 0){ + gl2ps->lastlinewidth = 0; + fprintf(gl2ps->stream, "\\pgfsetlinewidth{0.01pt}\n"); + } + gl2psPrintPGFColor(prim->verts[0].rgba); + fprintf(gl2ps->stream, + "\\pgfpathmoveto{\\pgfpoint{%fpt}{%fpt}}\n" + "\\pgflineto{\\pgfpoint{%fpt}{%fpt}}\n" + "\\pgflineto{\\pgfpoint{%fpt}{%fpt}}\n" + "\\pgfpathclose\n" + "\\pgfusepath{fill,stroke}\n", + prim->verts[2].xyz[0], prim->verts[2].xyz[1], + prim->verts[1].xyz[0], prim->verts[1].xyz[1], + prim->verts[0].xyz[0], prim->verts[0].xyz[1]); + break; + case GL2PS_TEXT : + fprintf(gl2ps->stream, "{\n\\pgftransformshift{\\pgfpoint{%fpt}{%fpt}}\n", + prim->verts[0].xyz[0], prim->verts[0].xyz[1]); + + if(prim->data.text->angle) + fprintf(gl2ps->stream, "\\pgftransformrotate{%f}{", prim->data.text->angle); + + fprintf(gl2ps->stream, "\\pgfnode{rectangle}{%s}{\\fontsize{%d}{0}\\selectfont", + gl2psPGFTextAlignment(prim->data.text->alignment), + prim->data.text->fontsize); + + fprintf(gl2ps->stream, "\\textcolor[rgb]{%g,%g,%g}{{%s}}", + prim->verts[0].rgba[0], prim->verts[0].rgba[1], + prim->verts[0].rgba[2], prim->data.text->str); + + fprintf(gl2ps->stream, "}{}{\\pgfusepath{discard}}}"); + + if(prim->data.text->angle) + fprintf(gl2ps->stream, "}"); + + fprintf(gl2ps->stream, "\n"); + break; + case GL2PS_SPECIAL : + /* alignment contains the format for which the special output text + is intended */ + if (prim->data.text->alignment == GL2PS_PGF) + fprintf(gl2ps->stream, "%s\n", prim->data.text->str); + break; + default : + break; + } +} + +static void gl2psPrintPGFFooter(void) +{ + fprintf(gl2ps->stream, "\\end{pgfpicture}\n"); +} + +static void gl2psPrintPGFBeginViewport(GLint viewport[4]) +{ + GLint idx; + GLfloat rgba[4]; + int x = viewport[0], y = viewport[1], w = viewport[2], h = viewport[3]; + + glRenderMode(GL_FEEDBACK); + + if(gl2ps->header){ + gl2psPrintPGFHeader(); + gl2ps->header = GL_FALSE; + } + + fprintf(gl2ps->stream, "\\begin{pgfscope}\n"); + if(gl2ps->options & GL2PS_DRAW_BACKGROUND){ + if(gl2ps->colormode == GL_RGBA || gl2ps->colorsize == 0){ + glGetFloatv(GL_COLOR_CLEAR_VALUE, rgba); + } + else{ + glGetIntegerv(GL_INDEX_CLEAR_VALUE, &idx); + rgba[0] = gl2ps->colormap[idx][0]; + rgba[1] = gl2ps->colormap[idx][1]; + rgba[2] = gl2ps->colormap[idx][2]; + rgba[3] = 1.0F; + } + gl2psPrintPGFColor(rgba); + fprintf(gl2ps->stream, + "\\pgfpathrectangle{\\pgfpoint{%dpt}{%dpt}}" + "{\\pgfpoint{%dpt}{%dpt}}\n" + "\\pgfusepath{fill}\n", + x, y, w, h); + } + + fprintf(gl2ps->stream, + "\\pgfpathrectangle{\\pgfpoint{%dpt}{%dpt}}" + "{\\pgfpoint{%dpt}{%dpt}}\n" + "\\pgfusepath{clip}\n", + x, y, w, h); +} + +static GLint gl2psPrintPGFEndViewport(void) +{ + GLint res; + res = gl2psPrintPrimitives(); + fprintf(gl2ps->stream, "\\end{pgfscope}\n"); + return res; +} + +static void gl2psPrintPGFFinalPrimitive(void) +{ +} + +/* definition of the PGF backend */ + +static GL2PSbackend gl2psPGF = { + gl2psPrintPGFHeader, + gl2psPrintPGFFooter, + gl2psPrintPGFBeginViewport, + gl2psPrintPGFEndViewport, + gl2psPrintPGFPrimitive, + gl2psPrintPGFFinalPrimitive, + "tex", + "PGF Latex Graphics" +}; + +/********************************************************************* + * + * General primitive printing routine + * + *********************************************************************/ + +/* Warning: the ordering of the backends must match the format + #defines in gl2ps.h */ + +static GL2PSbackend *gl2psbackends[] = { + &gl2psPS, /* 0 */ + &gl2psEPS, /* 1 */ + &gl2psTEX, /* 2 */ + &gl2psPDF, /* 3 */ + &gl2psSVG, /* 4 */ + &gl2psPGF /* 5 */ +}; + +static void gl2psComputeTightBoundingBox(void *data) +{ + GL2PSprimitive *prim; + int i; + + prim = *(GL2PSprimitive**)data; + + for(i = 0; i < prim->numverts; i++){ + if(prim->verts[i].xyz[0] < gl2ps->viewport[0]) + gl2ps->viewport[0] = (GLint)prim->verts[i].xyz[0]; + if(prim->verts[i].xyz[0] > gl2ps->viewport[2]) + gl2ps->viewport[2] = (GLint)(prim->verts[i].xyz[0] + 0.5F); + if(prim->verts[i].xyz[1] < gl2ps->viewport[1]) + gl2ps->viewport[1] = (GLint)prim->verts[i].xyz[1]; + if(prim->verts[i].xyz[1] > gl2ps->viewport[3]) + gl2ps->viewport[3] = (GLint)(prim->verts[i].xyz[1] + 0.5F); + } +} + +static GLint gl2psPrintPrimitives(void) +{ + GL2PSbsptree *root; + GL2PSxyz eye = {0.0F, 0.0F, 100.0F * GL2PS_ZSCALE}; + GLint used; + + used = glRenderMode(GL_RENDER); + + if(used < 0){ + gl2psMsg(GL2PS_INFO, "OpenGL feedback buffer overflow"); + return GL2PS_OVERFLOW; + } + + if(used > 0) + gl2psParseFeedbackBuffer(used); + + gl2psRescaleAndOffset(); + + if(gl2ps->header){ + if(gl2psListNbr(gl2ps->primitives) && + (gl2ps->options & GL2PS_TIGHT_BOUNDING_BOX)){ + gl2ps->viewport[0] = gl2ps->viewport[1] = 100000; + gl2ps->viewport[2] = gl2ps->viewport[3] = -100000; + gl2psListAction(gl2ps->primitives, gl2psComputeTightBoundingBox); + } + (gl2psbackends[gl2ps->format]->printHeader)(); + gl2ps->header = GL_FALSE; + } + + if(!gl2psListNbr(gl2ps->primitives)){ + /* empty feedback buffer and/or nothing else to print */ + return GL2PS_NO_FEEDBACK; + } + + switch(gl2ps->sort){ + case GL2PS_NO_SORT : + gl2psListAction(gl2ps->primitives, gl2psbackends[gl2ps->format]->printPrimitive); + gl2psListAction(gl2ps->primitives, gl2psFreePrimitive); + /* reset the primitive list, waiting for the next viewport */ + gl2psListReset(gl2ps->primitives); + break; + case GL2PS_SIMPLE_SORT : + gl2psListSort(gl2ps->primitives, gl2psCompareDepth); + if(gl2ps->options & GL2PS_OCCLUSION_CULL){ + gl2psListActionInverse(gl2ps->primitives, gl2psAddInImageTree); + gl2psFreeBspImageTree(&gl2ps->imagetree); + } + gl2psListAction(gl2ps->primitives, gl2psbackends[gl2ps->format]->printPrimitive); + gl2psListAction(gl2ps->primitives, gl2psFreePrimitive); + /* reset the primitive list, waiting for the next viewport */ + gl2psListReset(gl2ps->primitives); + break; + case GL2PS_BSP_SORT : + root = (GL2PSbsptree*)gl2psMalloc(sizeof(GL2PSbsptree)); + gl2psBuildBspTree(root, gl2ps->primitives); + if(GL_TRUE == gl2ps->boundary) gl2psBuildPolygonBoundary(root); + if(gl2ps->options & GL2PS_OCCLUSION_CULL){ + gl2psTraverseBspTree(root, eye, -GL2PS_EPSILON, gl2psLess, + gl2psAddInImageTree, 1); + gl2psFreeBspImageTree(&gl2ps->imagetree); + } + gl2psTraverseBspTree(root, eye, GL2PS_EPSILON, gl2psGreater, + gl2psbackends[gl2ps->format]->printPrimitive, 0); + gl2psFreeBspTree(&root); + /* reallocate the primitive list (it's been deleted by + gl2psBuildBspTree) in case there is another viewport */ + gl2ps->primitives = gl2psListCreate(500, 500, sizeof(GL2PSprimitive*)); + break; + } + gl2psbackends[gl2ps->format]->printFinalPrimitive(); + + return GL2PS_SUCCESS; +} + +/********************************************************************* + * + * Public routines + * + *********************************************************************/ + +GL2PSDLL_API GLint gl2psBeginPage(const char *title, const char *producer, + GLint viewport[4], GLint format, GLint sort, + GLint options, GLint colormode, + GLint colorsize, GL2PSrgba *colormap, + GLint nr, GLint ng, GLint nb, GLint buffersize, + FILE *stream, const char *filename) +{ + GLint idx; + int i; + + if(gl2ps){ + gl2psMsg(GL2PS_ERROR, "gl2psBeginPage called in wrong program state"); + return GL2PS_ERROR; + } + + gl2ps = (GL2PScontext*)gl2psMalloc(sizeof(GL2PScontext)); + + if(format >= 0 && format < (GLint)(sizeof(gl2psbackends) / sizeof(gl2psbackends[0]))){ + gl2ps->format = format; + } + else { + gl2psMsg(GL2PS_ERROR, "Unknown output format: %d", format); + gl2psFree(gl2ps); + gl2ps = NULL; + return GL2PS_ERROR; + } + + switch(sort){ + case GL2PS_NO_SORT : + case GL2PS_SIMPLE_SORT : + case GL2PS_BSP_SORT : + gl2ps->sort = sort; + break; + default : + gl2psMsg(GL2PS_ERROR, "Unknown sorting algorithm: %d", sort); + gl2psFree(gl2ps); + gl2ps = NULL; + return GL2PS_ERROR; + } + + if(stream){ + gl2ps->stream = stream; + } + else{ + gl2psMsg(GL2PS_ERROR, "Bad file pointer"); + gl2psFree(gl2ps); + gl2ps = NULL; + return GL2PS_ERROR; + } + + gl2ps->header = GL_TRUE; + gl2ps->maxbestroot = 10; + gl2ps->options = options; + gl2ps->compress = NULL; + gl2ps->imagemap_head = NULL; + gl2ps->imagemap_tail = NULL; + + if(gl2ps->options & GL2PS_USE_CURRENT_VIEWPORT){ + glGetIntegerv(GL_VIEWPORT, gl2ps->viewport); + } + else{ + for(i = 0; i < 4; i++){ + gl2ps->viewport[i] = viewport[i]; + } + } + + if(!gl2ps->viewport[2] || !gl2ps->viewport[3]){ + gl2psMsg(GL2PS_ERROR, "Incorrect viewport (x=%d, y=%d, width=%d, height=%d)", + gl2ps->viewport[0], gl2ps->viewport[1], + gl2ps->viewport[2], gl2ps->viewport[3]); + gl2psFree(gl2ps); + gl2ps = NULL; + return GL2PS_ERROR; + } + + gl2ps->threshold[0] = nr ? 1.0F / (GLfloat)nr : 0.064F; + gl2ps->threshold[1] = ng ? 1.0F / (GLfloat)ng : 0.034F; + gl2ps->threshold[2] = nb ? 1.0F / (GLfloat)nb : 0.100F; + gl2ps->colormode = colormode; + gl2ps->buffersize = buffersize > 0 ? buffersize : 2048 * 2048; + for(i = 0; i < 3; i++){ + gl2ps->lastvertex.xyz[i] = -1.0F; + } + for(i = 0; i < 4; i++){ + gl2ps->lastvertex.rgba[i] = -1.0F; + gl2ps->lastrgba[i] = -1.0F; + } + gl2ps->lastlinewidth = -1.0F; + gl2ps->lastpattern = 0; + gl2ps->lastfactor = 0; + gl2ps->imagetree = NULL; + gl2ps->primitivetoadd = NULL; + gl2ps->zerosurfacearea = GL_FALSE; + gl2ps->pdfprimlist = NULL; + gl2ps->pdfgrouplist = NULL; + gl2ps->xreflist = NULL; + + /* get default blending mode from current OpenGL state (enabled by + default for SVG) */ + gl2ps->blending = (gl2ps->format == GL2PS_SVG) ? GL_TRUE : glIsEnabled(GL_BLEND); + glGetIntegerv(GL_BLEND_SRC, &gl2ps->blendfunc[0]); + glGetIntegerv(GL_BLEND_DST, &gl2ps->blendfunc[1]); + + if(gl2ps->colormode == GL_RGBA){ + gl2ps->colorsize = 0; + gl2ps->colormap = NULL; + glGetFloatv(GL_COLOR_CLEAR_VALUE, gl2ps->bgcolor); + } + else if(gl2ps->colormode == GL_COLOR_INDEX){ + if(!colorsize || !colormap){ + gl2psMsg(GL2PS_ERROR, "Missing colormap for GL_COLOR_INDEX rendering"); + gl2psFree(gl2ps); + gl2ps = NULL; + return GL2PS_ERROR; + } + gl2ps->colorsize = colorsize; + gl2ps->colormap = (GL2PSrgba*)gl2psMalloc(gl2ps->colorsize * sizeof(GL2PSrgba)); + memcpy(gl2ps->colormap, colormap, gl2ps->colorsize * sizeof(GL2PSrgba)); + glGetIntegerv(GL_INDEX_CLEAR_VALUE, &idx); + gl2ps->bgcolor[0] = gl2ps->colormap[idx][0]; + gl2ps->bgcolor[1] = gl2ps->colormap[idx][1]; + gl2ps->bgcolor[2] = gl2ps->colormap[idx][2]; + gl2ps->bgcolor[3] = 1.0F; + } + else{ + gl2psMsg(GL2PS_ERROR, "Unknown color mode in gl2psBeginPage"); + gl2psFree(gl2ps); + gl2ps = NULL; + return GL2PS_ERROR; + } + + if(!title){ + gl2ps->title = (char*)gl2psMalloc(sizeof(char)); + gl2ps->title[0] = '\0'; + } + else{ + gl2ps->title = (char*)gl2psMalloc((strlen(title)+1)*sizeof(char)); + strcpy(gl2ps->title, title); + } + + if(!producer){ + gl2ps->producer = (char*)gl2psMalloc(sizeof(char)); + gl2ps->producer[0] = '\0'; + } + else{ + gl2ps->producer = (char*)gl2psMalloc((strlen(producer)+1)*sizeof(char)); + strcpy(gl2ps->producer, producer); + } + + if(!filename){ + gl2ps->filename = (char*)gl2psMalloc(sizeof(char)); + gl2ps->filename[0] = '\0'; + } + else{ + gl2ps->filename = (char*)gl2psMalloc((strlen(filename)+1)*sizeof(char)); + strcpy(gl2ps->filename, filename); + } + + gl2ps->primitives = gl2psListCreate(500, 500, sizeof(GL2PSprimitive*)); + gl2ps->auxprimitives = gl2psListCreate(100, 100, sizeof(GL2PSprimitive*)); + gl2ps->feedback = (GLfloat*)gl2psMalloc(gl2ps->buffersize * sizeof(GLfloat)); + glFeedbackBuffer(gl2ps->buffersize, GL_3D_COLOR, gl2ps->feedback); + glRenderMode(GL_FEEDBACK); + + return GL2PS_SUCCESS; +} + +GL2PSDLL_API GLint gl2psEndPage(void) +{ + GLint res; + + if(!gl2ps) return GL2PS_UNINITIALIZED; + + res = gl2psPrintPrimitives(); + + if(res != GL2PS_OVERFLOW) + (gl2psbackends[gl2ps->format]->printFooter)(); + + fflush(gl2ps->stream); + + gl2psListDelete(gl2ps->primitives); + gl2psListDelete(gl2ps->auxprimitives); + gl2psFreeImagemap(gl2ps->imagemap_head); + gl2psFree(gl2ps->colormap); + gl2psFree(gl2ps->title); + gl2psFree(gl2ps->producer); + gl2psFree(gl2ps->filename); + gl2psFree(gl2ps->feedback); + gl2psFree(gl2ps); + gl2ps = NULL; + + return res; +} + +GL2PSDLL_API GLint gl2psBeginViewport(GLint viewport[4]) +{ + if(!gl2ps) return GL2PS_UNINITIALIZED; + + (gl2psbackends[gl2ps->format]->beginViewport)(viewport); + + return GL2PS_SUCCESS; +} + +GL2PSDLL_API GLint gl2psEndViewport(void) +{ + GLint res; + + if(!gl2ps) return GL2PS_UNINITIALIZED; + + res = (gl2psbackends[gl2ps->format]->endViewport)(); + + /* reset last used colors, line widths */ + gl2ps->lastlinewidth = -1.0F; + + return res; +} + +GL2PSDLL_API GLint gl2psTextOptColor(const char *str, const char *fontname, + GLshort fontsize, GLint alignment, GLfloat angle, + GL2PSrgba color) +{ + return gl2psAddText(GL2PS_TEXT, str, fontname, fontsize, alignment, angle, + color); +} + +GL2PSDLL_API GLint gl2psTextOpt(const char *str, const char *fontname, + GLshort fontsize, GLint alignment, GLfloat angle) +{ + return gl2psAddText(GL2PS_TEXT, str, fontname, fontsize, alignment, angle, NULL); +} + +GL2PSDLL_API GLint gl2psText(const char *str, const char *fontname, GLshort fontsize) +{ + return gl2psAddText(GL2PS_TEXT, str, fontname, fontsize, GL2PS_TEXT_BL, 0.0F, + NULL); +} + +GL2PSDLL_API GLint gl2psSpecial(GLint format, const char *str) +{ + return gl2psAddText(GL2PS_SPECIAL, str, "", 0, format, 0.0F, NULL); +} + +GL2PSDLL_API GLint gl2psDrawPixels(GLsizei width, GLsizei height, + GLint xorig, GLint yorig, + GLenum format, GLenum type, + const void *pixels) +{ + int size, i; + const GLfloat *piv; + GLfloat pos[4], zoom_x, zoom_y; + GL2PSprimitive *prim; + GLboolean valid; + + if(!gl2ps || !pixels) return GL2PS_UNINITIALIZED; + + if((width <= 0) || (height <= 0)) return GL2PS_ERROR; + + if(gl2ps->options & GL2PS_NO_PIXMAP) return GL2PS_SUCCESS; + + if((format != GL_RGB && format != GL_RGBA) || type != GL_FLOAT){ + gl2psMsg(GL2PS_ERROR, "gl2psDrawPixels only implemented for " + "GL_RGB/GL_RGBA, GL_FLOAT pixels"); + return GL2PS_ERROR; + } + + glGetBooleanv(GL_CURRENT_RASTER_POSITION_VALID, &valid); + if(GL_FALSE == valid) return GL2PS_SUCCESS; /* the primitive is culled */ + + glGetFloatv(GL_CURRENT_RASTER_POSITION, pos); + glGetFloatv(GL_ZOOM_X, &zoom_x); + glGetFloatv(GL_ZOOM_Y, &zoom_y); + + prim = (GL2PSprimitive*)gl2psMalloc(sizeof(GL2PSprimitive)); + prim->type = GL2PS_PIXMAP; + prim->boundary = 0; + prim->numverts = 1; + prim->verts = (GL2PSvertex*)gl2psMalloc(sizeof(GL2PSvertex)); + prim->verts[0].xyz[0] = pos[0] + xorig; + prim->verts[0].xyz[1] = pos[1] + yorig; + prim->verts[0].xyz[2] = pos[2]; + prim->culled = 0; + prim->offset = 0; + prim->ofactor = 0.0; + prim->ounits = 0.0; + prim->pattern = 0; + prim->factor = 0; + prim->width = 1; + glGetFloatv(GL_CURRENT_RASTER_COLOR, prim->verts[0].rgba); + prim->data.image = (GL2PSimage*)gl2psMalloc(sizeof(GL2PSimage)); + prim->data.image->width = width; + prim->data.image->height = height; + prim->data.image->zoom_x = zoom_x; + prim->data.image->zoom_y = zoom_y; + prim->data.image->format = format; + prim->data.image->type = type; + + switch(format){ + case GL_RGBA: + if(gl2ps->options & GL2PS_NO_BLENDING || !gl2ps->blending){ + /* special case: blending turned off */ + prim->data.image->format = GL_RGB; + size = height * width * 3; + prim->data.image->pixels = (GLfloat*)gl2psMalloc(size * sizeof(GLfloat)); + piv = (const GLfloat*)pixels; + for(i = 0; i < size; ++i, ++piv){ + prim->data.image->pixels[i] = *piv; + if(!((i + 1) % 3)) + ++piv; + } + } + else{ + size = height * width * 4; + prim->data.image->pixels = (GLfloat*)gl2psMalloc(size * sizeof(GLfloat)); + memcpy(prim->data.image->pixels, pixels, size * sizeof(GLfloat)); + } + break; + case GL_RGB: + default: + size = height * width * 3; + prim->data.image->pixels = (GLfloat*)gl2psMalloc(size * sizeof(GLfloat)); + memcpy(prim->data.image->pixels, pixels, size * sizeof(GLfloat)); + break; + } + + gl2psListAdd(gl2ps->auxprimitives, &prim); + glPassThrough(GL2PS_DRAW_PIXELS_TOKEN); + + return GL2PS_SUCCESS; +} + +GL2PSDLL_API GLint gl2psDrawImageMap(GLsizei width, GLsizei height, + const GLfloat position[3], + const unsigned char *imagemap){ + int size, i; + int sizeoffloat = sizeof(GLfloat); + + if(!gl2ps || !imagemap) return GL2PS_UNINITIALIZED; + + if((width <= 0) || (height <= 0)) return GL2PS_ERROR; + + size = height + height * ((width - 1) / 8); + glPassThrough(GL2PS_IMAGEMAP_TOKEN); + glBegin(GL_POINTS); + glVertex3f(position[0], position[1],position[2]); + glEnd(); + glPassThrough((GLfloat)width); + glPassThrough((GLfloat)height); + for(i = 0; i < size; i += sizeoffloat){ + const float *value = (const float*)imagemap; + glPassThrough(*value); + imagemap += sizeoffloat; + } + return GL2PS_SUCCESS; +} + +GL2PSDLL_API GLint gl2psEnable(GLint mode) +{ + GLint tmp; + GLfloat tmp2; + + if(!gl2ps) return GL2PS_UNINITIALIZED; + + switch(mode){ + case GL2PS_POLYGON_OFFSET_FILL : + glPassThrough(GL2PS_BEGIN_OFFSET_TOKEN); + glGetFloatv(GL_POLYGON_OFFSET_FACTOR, &tmp2); + glPassThrough(tmp2); + glGetFloatv(GL_POLYGON_OFFSET_UNITS, &tmp2); + glPassThrough(tmp2); + break; + case GL2PS_POLYGON_BOUNDARY : + glPassThrough(GL2PS_BEGIN_BOUNDARY_TOKEN); + break; + case GL2PS_LINE_STIPPLE : + glPassThrough(GL2PS_BEGIN_STIPPLE_TOKEN); + glGetIntegerv(GL_LINE_STIPPLE_PATTERN, &tmp); + glPassThrough((GLfloat)tmp); + glGetIntegerv(GL_LINE_STIPPLE_REPEAT, &tmp); + glPassThrough((GLfloat)tmp); + break; + case GL2PS_BLEND : + glPassThrough(GL2PS_BEGIN_BLEND_TOKEN); + break; + default : + gl2psMsg(GL2PS_WARNING, "Unknown mode in gl2psEnable: %d", mode); + return GL2PS_WARNING; + } + + return GL2PS_SUCCESS; +} + +GL2PSDLL_API GLint gl2psDisable(GLint mode) +{ + if(!gl2ps) return GL2PS_UNINITIALIZED; + + switch(mode){ + case GL2PS_POLYGON_OFFSET_FILL : + glPassThrough(GL2PS_END_OFFSET_TOKEN); + break; + case GL2PS_POLYGON_BOUNDARY : + glPassThrough(GL2PS_END_BOUNDARY_TOKEN); + break; + case GL2PS_LINE_STIPPLE : + glPassThrough(GL2PS_END_STIPPLE_TOKEN); + break; + case GL2PS_BLEND : + glPassThrough(GL2PS_END_BLEND_TOKEN); + break; + default : + gl2psMsg(GL2PS_WARNING, "Unknown mode in gl2psDisable: %d", mode); + return GL2PS_WARNING; + } + + return GL2PS_SUCCESS; +} + +GL2PSDLL_API GLint gl2psPointSize(GLfloat value) +{ + if(!gl2ps) return GL2PS_UNINITIALIZED; + + glPassThrough(GL2PS_POINT_SIZE_TOKEN); + glPassThrough(value); + + return GL2PS_SUCCESS; +} + +GL2PSDLL_API GLint gl2psLineWidth(GLfloat value) +{ + if(!gl2ps) return GL2PS_UNINITIALIZED; + + glPassThrough(GL2PS_LINE_WIDTH_TOKEN); + glPassThrough(value); + + return GL2PS_SUCCESS; +} + +GL2PSDLL_API GLint gl2psBlendFunc(GLenum sfactor, GLenum dfactor) +{ + if(!gl2ps) return GL2PS_UNINITIALIZED; + + if(GL_FALSE == gl2psSupportedBlendMode(sfactor, dfactor)) + return GL2PS_WARNING; + + glPassThrough(GL2PS_SRC_BLEND_TOKEN); + glPassThrough((GLfloat)sfactor); + glPassThrough(GL2PS_DST_BLEND_TOKEN); + glPassThrough((GLfloat)dfactor); + + return GL2PS_SUCCESS; +} + +GL2PSDLL_API GLint gl2psSetOptions(GLint options) +{ + if(!gl2ps) return GL2PS_UNINITIALIZED; + + gl2ps->options = options; + + return GL2PS_SUCCESS; +} + +GL2PSDLL_API GLint gl2psGetOptions(GLint *options) +{ + if(!gl2ps) { + *options = 0; + return GL2PS_UNINITIALIZED; + } + + *options = gl2ps->options; + + return GL2PS_SUCCESS; +} + +GL2PSDLL_API const char *gl2psGetFileExtension(GLint format) +{ + if(format >= 0 && format < (GLint)(sizeof(gl2psbackends) / sizeof(gl2psbackends[0]))) + return gl2psbackends[format]->file_extension; + else + return "Unknown format"; +} + +GL2PSDLL_API const char *gl2psGetFormatDescription(GLint format) +{ + if(format >= 0 && format < (GLint)(sizeof(gl2psbackends) / sizeof(gl2psbackends[0]))) + return gl2psbackends[format]->description; + else + return "Unknown format"; +} + +GL2PSDLL_API GLint gl2psGetFileFormat() +{ + return gl2ps->format; +} diff --git a/src/imconfig.h b/src/imconfig.h deleted file mode 100644 index 625a894..0000000 --- a/src/imconfig.h +++ /dev/null @@ -1,55 +0,0 @@ -//----------------------------------------------------------------------------- -// USER IMPLEMENTATION -// This file contains compile-time options for ImGui. -// Other options (memory allocation overrides, callbacks, etc.) can be set at runtime via the ImGuiIO structure - ImGui::GetIO(). -//----------------------------------------------------------------------------- - -#pragma once - -//---- Define your own ImVector<> type if you don't want to use the provided implementation defined in imgui.h -//#include <vector> -//#define ImVector std::vector -//#define ImVector MyVector - -//---- Define assertion handler. Defaults to calling assert(). -//#define IM_ASSERT(_EXPR) MyAssert(_EXPR) - -//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows. -//#define IMGUI_API __declspec( dllexport ) -//#define IMGUI_API __declspec( dllimport ) - -//---- Don't implement default handlers for Windows (so as not to link with OpenClipboard() and others Win32 functions) -//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS -//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS - -//---- Don't implement help and test window functionality (ShowUserGuide()/ShowStyleEditor()/ShowTestWindow() methods will be empty) -//#define IMGUI_DISABLE_TEST_WINDOWS - -//---- Include imgui_user.inl at the end of imgui.cpp so you can include code that extends ImGui using its private data/functions. -//#define IMGUI_INCLUDE_IMGUI_USER_INL - -//---- Include imgui_user.h at the end of imgui.h -//#define IMGUI_INCLUDE_IMGUI_USER_H - -//---- Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2/ImVec4. -/* -#define IM_VEC2_CLASS_EXTRA \ - ImVec2(const MyVec2& f) { x = f.x; y = f.y; } \ - operator MyVec2() const { return MyVec2(x,y); } - -#define IM_VEC4_CLASS_EXTRA \ - ImVec4(const MyVec4& f) { x = f.x; y = f.y; z = f.z; w = f.w; } \ - operator MyVec4() const { return MyVec4(x,y,z,w); } -*/ - -//---- Freely implement extra functions within the ImGui:: namespace. -//---- Declare helpers or widgets implemented in imgui_user.inl or elsewhere, so end-user doesn't need to include multiple files. -//---- e.g. you can create variants of the ImGui::Value() helper for your low-level math types, or your own widgets/helpers. -/* -namespace ImGui -{ - void Value(const char* prefix, const MyVec2& v, const char* float_format = NULL); - void Value(const char* prefix, const MyVec4& v, const char* float_format = NULL); -} -*/ - diff --git a/src/imgui.cpp b/src/imgui.cpp index 6a7048c..5157a2c 100644 --- a/src/imgui.cpp +++ b/src/imgui.cpp @@ -1,8 +1,13 @@ -// ImGui library v1.38 WIP -// See ImGui::ShowTestWindow() for sample code. -// Read 'Programmer guide' below for notes on how to setup ImGui in your codebase. +// dear imgui, v1.50 WIP +// (main code and documentation) + +// See ImGui::ShowTestWindow() in imgui_demo.cpp for demo code. +// Newcomers, read 'Programmer guide' below for notes on how to setup ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui -// Developed by Omar Cornut and contributors. +// Releases change-log at https://github.com/ocornut/imgui/releases +// Developed by Omar Cornut and every direct or indirect contributors to the GitHub. +// This library is free but I need your support to sustain development and maintenance. +// If you work for a company, please consider financial support, e.g: https://www.patreon.com/imgui /* @@ -12,17 +17,21 @@ - PROGRAMMER GUIDE (read me!) - API BREAKING CHANGES (read me when you update!) - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS - - Can I have multiple widgets with the same label? (Yes) - - Why is my text output blurry? - - How can I load a different font than the default? + - How can I help? + - How do I update to a newer version of ImGui? + - What is ImTextureID and how do I display an image? + - I integrated ImGui in my engine and the text or lines are blurry.. + - I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. + - How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on the purpose of labels/IDs. + - How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? + - How can I load a different font than the default? - How can I load multiple fonts? - - How can I display and input Chinese, Japanese, Korean characters? + - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? + - How can I use the drawing facilities without an ImGui window? (using ImDrawList API) - ISSUES & TODO-LIST - CODE - - SAMPLE CODE - - FONT DATA - + MISSION STATEMENT ================= @@ -46,14 +55,14 @@ ============== - double-click title bar to collapse window - - click upper right corner to close a window, available when 'bool* p_opened' is passed to ImGui::Begin() + - click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin() - click and drag on lower right corner to resize window - click and drag on any empty space to move window - double-click/double-tap on lower right corner grip to auto-fit to content - TAB/SHIFT+TAB to cycle through keyboard editable fields - use mouse wheel to scroll - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true) - - CTRL+Click on a slider to input value as text + - CTRL+Click on a slider or drag box to input value as text - text editor: - Hold SHIFT or use mouse to select text. - CTRL+Left/Right to word jump @@ -70,19 +79,23 @@ - read the FAQ below this section! - your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs. - - call and read ImGui::ShowTestWindow() for sample code demonstrating most features. - - see examples/ folder for standalone sample applications. e.g. examples/opengl_example/ + - call and read ImGui::ShowTestWindow() for demo code demonstrating most features. + - see examples/ folder for standalone sample applications. Prefer reading examples/opengl2_example/ first as it is the simplest. + you may be able to grab and copy a ready made imgui_impl_*** file from the examples/. - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme). - getting started: - - initialisation: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the 'Settings' data. - - every frame: - 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the 'Input' data, then call ImGui::NewFrame(). - 2/ use any ImGui function you want between NewFrame() and Render() - 3/ ImGui::Render() to render all the accumulated command-lists. it will call your RenderDrawListFn handler that you set in the IO structure. - - all rendering information are stored into command-lists until ImGui::Render() is called. - - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you must provide. - - effectively it means you can create widgets at any time in your code, regardless of "update" vs "render" considerations. + - init: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the fields marked 'Settings'. + - init: call io.Fonts->GetTexDataAsRGBA32(...) and load the font texture pixels into graphics memory. + - every frame: + 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the fields marked 'Input' + 2/ call ImGui::NewFrame() as early as you can! + 3/ use any ImGui function you want between NewFrame() and Render() + 4/ call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your RenderDrawListFn handler that you set in the IO structure. + (if you don't need to render, you still need to call Render() and ignore the callback, or call EndFrame() instead. if you call neither some aspects of windows focusing/moving will appear broken.) + - all rendering information are stored into command-lists until ImGui::Render() is called. + - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide. + - effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application. - refer to the examples applications in the examples/ folder for instruction on how to setup your code. - a typical application skeleton may be: @@ -90,58 +103,122 @@ ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = 1920.0f; io.DisplaySize.y = 1280.0f; - io.DeltaTime = 1.0f/60.0f; io.IniFilename = "imgui.ini"; + io.RenderDrawListsFn = my_render_function; // Setup a render function, or set to NULL and call GetDrawData() after Render() to access the render data. // TODO: Fill others settings of the io structure - // Load texture + // Load texture atlas + // There is a default font so you don't need to care about choosing a font yet unsigned char* pixels; - int width, height, bytes_per_pixels; - io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height, &bytes_per_pixels); - // TODO: copy texture to graphics memory. - // TODO: store your texture pointer/identifier in 'io.Fonts->TexID' + int width, height; + io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height); + // TODO: At this points you've got a texture pointed to by 'pixels' and you need to upload that your your graphic system + // TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID' // Application main loop while (true) { - // 1) get low-level input - // e.g. on Win32, GetKeyboardState(), or poll your events, etc. - - // 2) TODO: fill all fields of IO structure and call NewFrame + // 1) get low-level inputs (e.g. on Win32, GetKeyboardState(), or poll your events, etc.) + // TODO: fill all fields of IO structure and call NewFrame ImGuiIO& io = ImGui::GetIO(); + io.DeltaTime = 1.0f/60.0f; io.MousePos = mouse_pos; io.MouseDown[0] = mouse_button_0; + io.MouseDown[1] = mouse_button_1; io.KeysDown[i] = ... + + // 2) call NewFrame(), after this point you can use ImGui::* functions anytime ImGui::NewFrame(); - // 3) most of your application code here - you can use any of ImGui::* functions at any point in the frame - ImGui::Begin("My window"); - ImGui::Text("Hello, world."); - ImGui::End(); - GameUpdate(); - GameRender(); + // 3) most of your application code here + MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); + MyGameRender(); // may use any ImGui functions // 4) render & swap video buffers ImGui::Render(); - // swap video buffer, etc. + SwapBuffers(); } - - after calling ImGui::NewFrame() you can read back 'io.WantCaptureMouse' and 'io.WantCaptureKeyboard' to tell if ImGui - wants to use your inputs. if it does you can discard/hide the inputs from the rest of your application. + - You can read back 'io.WantCaptureMouse', 'io.WantCaptureKeybord' etc. flags from the IO structure to tell how ImGui intends to use your + inputs and to know if you should share them or hide them from the rest of your application. Read the FAQ below for more information. + API BREAKING CHANGES ==================== Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix. Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code. - + Also read releases logs https://github.com/ocornut/imgui/releases for more details. + + - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc. + - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal. + - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. + If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you. + However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. + This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color. + ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) + { + float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; + return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); + } + If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. + - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). + - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. + - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). + - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. + - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337). + - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) + - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). + - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. + - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. + - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. + - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. + - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. + GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. + GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! + - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize + - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. + - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason + - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. + you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. + - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. + this necessary change will break your rendering function! the fix should be very easy. sorry for that :( + - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. + - the signature of the io.RenderDrawListsFn handler has changed! + ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) + became: + ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). + argument 'cmd_lists' -> 'draw_data->CmdLists' + argument 'cmd_lists_count' -> 'draw_data->CmdListsCount' + ImDrawList 'commands' -> 'CmdBuffer' + ImDrawList 'vtx_buffer' -> 'VtxBuffer' + ImDrawList n/a -> 'IdxBuffer' (new) + ImDrawCmd 'vtx_count' -> 'ElemCount' + ImDrawCmd 'clip_rect' -> 'ClipRect' + ImDrawCmd 'user_callback' -> 'UserCallback' + ImDrawCmd 'texture_id' -> 'TextureId' + - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer. + - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! + - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade! + - 2015/07/10 (1.43) - changed SameLine() parameters from int to float. + - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete). + - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount. + - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence + - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry! + - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). + - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). + - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. + - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. + - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). + - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50. + - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. - - 2015/03/17 (1.36) - renamed GetItemRectMin()/GetItemRectMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function (will obsolete). + - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing - - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function (will obsolete). - - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth - - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function (will obsolete). + - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50. + - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) + - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior @@ -162,7 +239,7 @@ // <Copy to GPU> io.Fonts->TexID = (your_texture_identifier); you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. - it is now recommended your sample the font texture with bilinear interpolation. + it is now recommended that you sample the font texture with bilinear interpolation. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets @@ -182,42 +259,88 @@ FREQUENTLY ASKED QUESTIONS (FAQ), TIPS ====================================== - Q: Can I have multiple widgets with the same label? + Q: How can I help? + A: - If you are experienced enough with ImGui and with C/C++, look at the todo list and see how you want/can help! + - Become a Patron/donate. Convince your company to become a Patron or provide serious funding for development time. + + Q: How do I update to a newer version of ImGui? + A: Overwrite the following files: + imgui.cpp + imgui.h + imgui_demo.cpp + imgui_draw.cpp + imgui_internal.h + stb_rect_pack.h + stb_textedit.h + stb_truetype.h + Don't overwrite imconfig.h if you have made modification to your copy. + Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. If you have a problem with a function, search for its name + in the code, there will likely be a comment about it. Please report any issue to the GitHub page! + + + Q: What is ImTextureID and how do I display an image? + A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function. + ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry! + It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc. + At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render. + Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing. + (c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!) + To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions. + ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use. + It is your responsibility to get textures uploaded to your GPU. + + Q: I integrated ImGui in my engine and the text or lines are blurry.. + A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). + Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. + + Q: I integrated ImGui in my engine and some elements are clipping or disappearing when I move windows around.. + A: Most likely you are mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1,y1,x2,y2) and NOT as (x1,y1,width,height). + + Q: Can I have multiple widgets with the same label? Can I have widget without a label? (Yes) A: Yes. A primer on the use of labels/IDs in ImGui.. - + + - Elements that are not clickable, such as Text() items don't need an ID. + - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget). - to do so they need an unique ID. unique ID are typically derived from a string label, an integer index or a pointer. - + to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer. + Button("OK"); // Label = "OK", ID = hash of "OK" Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel" - - Elements that are not clickable, such as Text() items don't need an ID. - - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK" in two different windows or in two different locations of a tree. - - if you have a same ID twice in the same location, you'll have a conflict: + - If you have a same ID twice in the same location, you'll have a conflict: Button("OK"); - Button("OK"); // ID collision! Both buttons will be treated as the same. + Button("OK"); // ID collision! Both buttons will be treated as the same. Fear not! this is easy to solve and there are many ways to solve it! - - when passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases. + - When passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases. use "##" to pass a complement to the ID that won't be visible to the end-user: - Button("Play##0"); // Label = "Play", ID = hash of "Play##0" - Button("Play##1"); // Label = "Play", ID = hash of "Play##1" (different from above) + Button("Play"); // Label = "Play", ID = hash of "Play" + Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above) + Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above) + + - If you want to completely hide the label, but still need an ID: - - occasionally (rarely) you might want change a label while preserving a constant ID. This allows you to animate labels. - use "###" to pass a label that isn't part of ID: + Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!) - Button("Hello###ID"; // Label = "Hello", ID = hash of "ID" - Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above) + - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels. + For example you may want to include varying information in a window title bar (and windows are uniquely identified by their ID.. obviously) + Use "###" to pass a label that isn't part of ID: - - use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window. - this is the most convenient way of distinguish ID if you are iterating and creating many UI elements. - you can push a pointer, a string or an integer value. remember that ID are formed from the addition of everything in the ID stack! + Button("Hello###ID"; // Label = "Hello", ID = hash of "ID" + Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above) + + sprintf(buf, "My game (%f FPS)###MyGame"); + Begin(buf); // Variable label, ID = hash of "MyGame" + + - Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window. + This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements. + You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of everything in the ID stack! for (int i = 0; i < 100; i++) { @@ -242,7 +365,7 @@ PopID(); } - - more example showing that you can stack multiple prefixes into the ID stack: + - More example showing that you can stack multiple prefixes into the ID stack: Button("Click"); // Label = "Click", ID = hash of "Click" PushID("node"); @@ -252,7 +375,7 @@ PopID(); PopID(); - - tree nodes implicitly creates a scope for you by calling PushID(). + - Tree nodes implicitly creates a scope for you by calling PushID(). Button("Click"); // Label = "Click", ID = hash of "Click" if (TreeNode("node")) @@ -261,102 +384,194 @@ TreePop(); } - - when working with trees, ID are used to preserve the opened/closed state of each tree node. - depending on your use cases you may want to use strings, indices or pointers as ID. + - When working with trees, ID are used to preserve the open/close state of each tree node. + Depending on your use cases you may want to use strings, indices or pointers as ID. e.g. when displaying a single object that may change over time (1-1 relationship), using a static string as ID will preserve your node open/closed state when the targeted object change. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. experiment and see what makes more sense! - Q: Why is my text output blurry? - A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) + Q: How can I tell when ImGui wants my mouse/keyboard inputs and when I can pass them to my application? + A: You can read the 'io.WantCaptureXXX' flags in the ImGuiIO structure. Preferably read them after calling ImGui::NewFrame() to avoid those flags lagging by one frame, but either should be fine. + When 'io.WantCaptureMouse' or 'io.WantCaptureKeyboard' flags are set you may want to discard/hide the inputs from the rest of your application. + When 'io.WantInputsCharacters' is set to may want to notify your OS to popup an on-screen keyboard, if available. + ImGui is tracking dragging and widget activity that may occur outside the boundary of a window, so 'io.WantCaptureMouse' is a more accurate and complete than testing for ImGui::IsMouseHoveringAnyWindow(). + (Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically have 'io.WantcaptureKeyboard=false'. + Depending on your application logic it may or not be inconvenient. You might want to track which key-downs were for ImGui (e.g. with an array of bool) and filter out the corresponding key-ups.) Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13) A: Use the font atlas to load the TTF file you want: - io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); - io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + ImGuiIO& io = ImGui::GetIO(); + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() Q: How can I load multiple fonts? A: Use the font atlas to pack them into a single texture: - - ImFont* font0 = io.Fonts->AddFontDefault(); - ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); - ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); - io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() - // the first loaded font gets used by default - // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime - - Q: How can I render and input Chinese, Japanese, Korean characters? - A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. ImGui will support UTF-8 encoding across the board. - Character input depends on you passing the right character code to io.AddInputCharacter(). The example applications do that. - - io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters - io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() - io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application + (Read extra_fonts/README.txt and the code in ImFontAtlas for more details.) + + ImGuiIO& io = ImGui::GetIO(); + ImFont* font0 = io.Fonts->AddFontDefault(); + ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); + ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + // the first loaded font gets used by default + // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime + + // Options + ImFontConfig config; + config.OversampleH = 3; + config.OversampleV = 1; + config.GlyphExtraSpacing.x = 1.0f; + io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config); + + // Combine multiple fonts into one + ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; + ImFontConfig config; + config.MergeMode = true; + io.Fonts->AddFontDefault(); + io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); + io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); + + Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? + A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. + All your strings needs to use UTF-8 encoding. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will not work. + In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. + You can also try to remap your local codepage characters to their Unicode codepoint using font->AddRemapChar(), but international users may have problems reading/editing your source code. + + io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters + io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() + io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application + + As for text input, depends on you passing the right character code to io.AddInputCharacter(). The example applications do that. + + Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API) + A: The easiest way is to create a dummy window. Call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flag, zero background alpha, + then retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug" - - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. + - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings) - tip: you can call Render() multiple times (e.g for VR renders). - - tip: call and read the ShowTestWindow() code for more example of how to use ImGui! + - tip: call and read the ShowTestWindow() code in imgui_demo.cpp for more example of how to use ImGui! ISSUES & TODO-LIST ================== + Issue numbers (#) refer to github issues listed at https://github.com/ocornut/imgui/issues + The list below consist mostly of notes of things to do before they are requested/discussed by users (at that point it usually happens on the github) - - misc: merge or clarify ImVec4 vs ImRect? - - window: add horizontal scroll - - window: fix resize grip rendering scaling along with Rounding style setting - - window: autofit feedback loop when user relies on any dynamic layout (window width multiplier, column). maybe just clearly drop manual autofit? - - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. + - doc: add a proper documentation+regression testing system (#435) + - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. perhaps a lightweight explicit cleanup pass. + - window: calling SetNextWindowSize() every frame with <= 0 doesn't do anything, may be useful to allow (particularly when used for a single axis) (#690) + - window: auto-fit feedback loop when user relies on any dynamic layout (window width multiplier, column) appears weird to end-user. clarify. - window: allow resizing of child windows (possibly given min/max for each axis?) - window: background options for child windows, border option (disable rounding) + - window: add a way to clear an existing window instead of appending (e.g. for tooltip override using a consistent api rather than the deferred tooltip) - window: resizing from any sides? + mouse cursor directives for app. +!- window: begin with *p_open == false should return false. + - window: get size/pos helpers given names (see discussion in #249) + - window: a collapsed window can be stuck behind the main menu bar? + - window: when window is small, prioritize resize button over close button. + - window: detect extra End() call that pop the "Debug" window out and assert at call site instead of later. + - window/tooltip: allow to set the width of a tooltip to allow TextWrapped() etc. while keeping the height automatic. + - window: increase minimum size of a window with menus or fix the menu rendering so that it doesn't look odd. + - draw-list: maintaining bounding box per command would allow to merge draw command when clipping isn't relied on (typical non-scrolling window or non-overflowing column would merge with previous command). +!- scrolling: allow immediately effective change of scroll if we haven't appended items yet + - splitter/separator: formalize the splitter idiom into an official api (we want to handle n-way split) (#319) - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc. - widgets: clean up widgets internal toward exposing everything. - - main: considering adding EndFrame()/Init(). some constructs are awkward in the implementation because of the lack of them. + - widgets: add disabled and read-only modes (#211) + - main: considering adding an Init() function? some constructs are awkward in the implementation because of the lack of them. +!- main: make it so that a frame with no window registered won't refocus every window on subsequent frames (~bump LastFrameActive of all windows). - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? -!- input number: large int not reliably supported because of int<>float conversions. + - input text: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now and super fragile. + - input text: reorganize event handling, allow CharFilter to modify buffers, allow multiple events? (#541) + - input text: expose CursorPos in char filter event (#816) + - input text: flag to disable live update of the user buffer (also applies to float/int text input) + - input text: resize behavior - field could stretch when being edited? hover tooltip shows more text? + - input text: add ImGuiInputTextFlags_EnterToApply? (off #218) + - input text: add discard flag (e.g. ImGuiInputTextFlags_DiscardActiveBuffer) or make it easier to clear active focus for text replacement during edition (#725) + - input text multi-line: don't directly call AddText() which does an unnecessary vertex reserve for character count prior to clipping. and/or more line-based clipping to AddText(). and/or reorganize TextUnformatted/RenderText for more efficiency for large text (e.g TextUnformatted could clip and log separately, etc). + - input text multi-line: way to dynamically grow the buffer without forcing the user to initially allocate for worse case (follow up on #200) + - input text multi-line: line numbers? status bar? (follow up on #200) + - input text multi-line: behave better when user changes input buffer while editing is active (even though it is illegal behavior). namely, the change of buffer can create a scrollbar glitch (#725) + - input text: allow centering/positioning text so that ctrl+clicking Drag or Slider keeps the textual value at the same pixel position. - input number: optional range min/max for Input*() functions - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled) - input number: use mouse wheel to step up/down - - input number: non-decimal input. + - input number: applying arithmetics ops (+,-,*,/) messes up with text edit undo stack. + - button: provide a button that looks framed. - text: proper alignment options - - layout: horizontal layout helper (github issue #97) + - image/image button: misalignment on padded/bordered button? + - image/image button: parameters are confusing, image() has tint_col,border_col whereas imagebutton() has bg_col/tint_col. Even thou they are different parameters ordering could be more consistent. can we fix that? + - layout: horizontal layout helper (#97) + - layout: horizontal flow until no space left (#404) - layout: more generic alignment state (left/right/centered) for single items? - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding. - - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) - - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) - - columns: columns header to act as button (~sort op) and allow resize/reorder - - columns: user specify columns size - - columns: tree node example, removing the last NextColumn() makes a padding difference (it should not) - - combo: turn child handling code into pop up helper + - layout: BeginGroup() needs a border option. + - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (#513, #125) + - columns: add a conditional parameter to SetColumnOffset() (#513, #125) + - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (#125) + - columns: columns header to act as button (~sort op) and allow resize/reorder (#513, #125) + - columns: user specify columns size (#513, #125) + - columns: flag to add horizontal separator above/below? + - columns/layout: setup minimum line height (equivalent of automatically calling AlignFirstTextHeightToWidgets) + - combo: sparse combo boxes (via function call?) / iterators - combo: contents should extends to fit label if combo widget is small + - combo/listbox: keyboard control. need InputText-like non-active focus + key handling. considering keyboard for custom listbox (pr #203) - listbox: multiple selection - listbox: user may want to initial scroll to focus on the one selected value? - ! menubar, menus - - tabs - - gauge: various forms of gauge/loading bars widgets - - color: better color editor. + - listbox: keyboard navigation. + - listbox: scrolling should track modified selection. +!- popups/menus: clarify usage of popups id, how MenuItem/Selectable closing parent popups affects the ID, etc. this is quite fishy needs improvement! (#331, #402) + - popups: add variant using global identifier similar to Begin/End (#402) + - popups: border options. richer api like BeginChild() perhaps? (#197) + - tooltip: tooltip that doesn't fit in entire screen seems to lose their "last preferred button" and may teleport when moving mouse + - menus: local shortcuts, global shortcuts (#456, #126) + - menus: icons + - menus: menubars: some sort of priority / effect of main menu-bar on desktop size? + - menus: calling BeginMenu() twice with a same name doesn't seem to append nicely + - statusbar: add a per-window status bar helper similar to what menubar does. + - tabs (#261, #351) + - separator: separator on the initial position of a window is not visible (cursorpos.y <= clippos.y) +!- color: the color helpers/typing is a mess and needs sorting out. + - color: add a better color picker (#346) + - node/graph editor (#306) + - pie menus patterns (#434) + - drag'n drop, dragging helpers (carry dragging info, visualize drag source before clicking, drop target, etc.) (#143, #479) + - plot: PlotLines() should use the polygon-stroke facilities (currently issues with averaging normals) - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots) - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value) - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID) - - file selection widget -> build the tool in our codebase to improve model-dialog idioms - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. - - text edit: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now. - - text edit: centered text for slider as input text so it matches typical positioning. - - text edit: flag to disable live update of the user buffer. - - text edit: field resize behavior - field could stretch when being edited? hover tooltip shows more text? - - text edit: add multi-line text edit - - tree: add treenode/treepush int variants? because (void*) cast from int warns on some platforms/settings + - slider: tint background based on value (e.g. v_min -> v_max, or use 0.0f either side of the sign) + - slider & drag: int data passing through a float + - drag float: up/down axis + - drag float: added leeway on edge (e.g. a few invisible steps past the clamp limits) + - tree node / optimization: avoid formatting when clipped. + - tree node: tree-node/header right-most side doesn't take account of horizontal scrolling. + - tree node: add treenode/treepush int variants? not there because (void*) cast from int warns on some platforms/settings? + - tree node: try to apply scrolling at time of TreePop() if node was just opened and end of node is past scrolling limits? + - tree node / selectable render mismatch which is visible if you use them both next to each other (e.g. cf. property viewer) + - tree node: tweak color scheme to distinguish headers from selected tree node (#581) + - textwrapped: figure out better way to use TextWrapped() in an always auto-resize context (tooltip, etc.) (#249) - settings: write more decent code to allow saving/loading new fields - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file - ! style: store rounded corners in texture to use 1 quad per corner (filled and wireframe). so rounding have minor cost. - - style: checkbox: padding for "active" color should be a multiplier of the - - style: colorbox not always square? + - style: add window shadows. + - style/optimization: store rounded corners in texture to use 1 quad per corner (filled and wireframe) to lower the cost of rounding. + - style: color-box not always square? + - style: a concept of "compact style" that the end-user can easily rely on (e.g. PushStyleCompact()?) that maps to other settings? avoid implementing duplicate helpers such as SmallCheckbox(), etc. + - style: try to make PushStyleVar() more robust to incorrect parameters (to be more friendly to edit & continues situation). + - style: global scale setting. + - style: WindowPadding needs to be EVEN needs the 0.5 multiplier probably have a subtle effect on clip rectangle - text: simple markup language for color change? + - font: dynamic font atlas to avoid baking huge ranges into bitmap and make scaling easier. + - font: small opt: for monospace font (like the defalt one) we can trim IndexXAdvance as long as trailing value is == FallbackXAdvance + - font: add support for kerning, probably optional. perhaps default to (32..128)^2 matrix ~ 36KB then hash fallback. + - font: add a simpler CalcTextSizeA() api? current one ok but not welcome if user needs to call it directly (without going through ImGui::CalcTextSize) + - font: fix AddRemapChar() to work before font has been built. - log: LogButtons() options for specifying depth and/or hiding depth slider - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard) @@ -364,18 +579,25 @@ - filters: set a current filter that tree node can automatically query to hide themselves - filters: handle wildcards (with implicit leading/trailing *), regexps - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus) - ! keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing - - keyboard: full keyboard navigation and focus. - - input: rework IO to be able to pass actual events to fix temporal aliasing issues. +!- keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing + - keyboard: full keyboard navigation and focus. (#323) + - focus: preserve ActiveId/focus stack state, e.g. when opening a menu and close it, previously selected InputText() focus gets restored (#622) + - focus: SetKeyboardFocusHere() on with >= 0 offset could be done on same frame (else latch and modulate on beginning of next frame) + - input: rework IO system to be able to pass actual ordered/timestamped events. (~#335, #71) + - input: allow to decide and pass explicit double-clicks (e.g. for windows by the CS_DBLCLKS style). - input: support track pad style scrolling & slider edit. - - tooltip: move to fit within screen (e.g. when mouse cursor is right of the screen). - - portability: big-endian test/support (github issue #81) - - misc: mark printf compiler attributes on relevant functions - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL) - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon? - - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? + - misc: provide HoveredTime and ActivatedTime to ease the creation of animations. + - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? (#438) - style editor: color child window height expressed in multiple of line height. - - optimization/render: use indexed rendering to reduce vertex data cost (e.g. for remote/networked imgui) + - remote: make a system like RemoteImGui first-class citizen/project (#75) + - drawlist: move Font, FontSize, FontTexUvWhitePixel inside ImDrawList and make it self-contained (apart from drawing settings?) + - drawlist: end-user probably can't call Clear() directly because we expect a texture to be pushed in the stack. + - examples: directx9: save/restore device state more thoroughly. + - examples: window minimize, maximize (#583) + - optimization: add a flag to disable most of rendering, for the case where the user expect to skip it (#335) + - optimization: use another hash function than crc32, e.g. FNV1a - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)? - optimization: turn some the various stack vectors into statically-sized arrays - optimization: better clipping for multi-component widgets @@ -386,13 +608,22 @@ #endif #include "imgui.h" +#define IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_PLACEMENT_NEW +#include "imgui_internal.h" + #include <ctype.h> // toupper, isprint -#include <math.h> // sqrtf, fabsf, fmodf, powf, cosf, sinf, floorf, ceilf +#include <stdlib.h> // NULL, malloc, free, qsort, atoi +#include <stdio.h> // vsnprintf, sscanf, printf +#include <limits.h> // INT_MIN, INT_MAX +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include <stddef.h> // intptr_t +#else #include <stdint.h> // intptr_t -#include <stdio.h> // vsnprintf, sscanf -#include <new> // new (ptr) +#endif #ifdef _MSC_VER +#pragma warning (disable: 4127) // condition expression is constant #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif @@ -404,132 +635,90 @@ #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. -#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // -#pragma clang diagnostic ignored "-Wmissing-noreturn" // warning : function xx could be declared with attribute 'noreturn' warning // GetDefaultFontData() asserts which some implementation makes it never return. -#endif -#ifdef __GNUC__ +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' // +#elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used -#endif - -//------------------------------------------------------------------------- -// STB libraries implementation -//------------------------------------------------------------------------- - -struct ImGuiTextEditState; - -//#define IMGUI_STB_NAMESPACE ImStb -//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION -//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION - -#ifdef IMGUI_STB_NAMESPACE -namespace IMGUI_STB_NAMESPACE -{ -#endif - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-function" -#pragma clang diagnostic ignored "-Wmissing-prototypes" -#endif - -#define STBRP_ASSERT(x) IM_ASSERT(x) -#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION -#define STBRP_STATIC -#define STB_RECT_PACK_IMPLEMENTATION -#endif -#include "stb_rect_pack.h" - -#define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) -#define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) -#define STBTT_assert(x) IM_ASSERT(x) -#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION -#define STBTT_STATIC -#define STB_TRUETYPE_IMPLEMENTATION -#endif -#include "stb_truetype.h" - -#undef STB_TEXTEDIT_STRING -#undef STB_TEXTEDIT_CHARTYPE -#define STB_TEXTEDIT_STRING ImGuiTextEditState -#define STB_TEXTEDIT_CHARTYPE ImWchar -#include "stb_textedit.h" - -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#ifdef IMGUI_STB_NAMESPACE -} // namespace ImStb -using namespace IMGUI_STB_NAMESPACE; +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #endif //------------------------------------------------------------------------- // Forward Declarations //------------------------------------------------------------------------- -struct ImRect; -struct ImGuiColMod; -struct ImGuiStyleMod; -struct ImGuiDrawContext; -struct ImGuiTextEditState; -struct ImGuiIniData; -struct ImGuiState; -struct ImGuiWindow; - -static bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, bool allow_key_modifiers, bool repeat = false, bool pressed_on_click = false); -static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); - -static void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); -static void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); -static void RenderTextClipped(ImVec2 pos, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& clip_max); -static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); -static void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale = 1.0f, bool shadow = false); - -static void SetFont(ImFont* font); -static bool ItemAdd(const ImRect& bb, const ImGuiID* id); -static void ItemSize(ImVec2 size, float text_offset_y = 0.0f); -static void ItemSize(const ImRect& bb, float text_offset_y = 0.0f); -static void PushColumnClipRect(int column_index = -1); -static bool IsClipped(const ImRect& bb); - -static bool IsMouseHoveringRect(const ImRect& bb); -static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); - -static void Scrollbar(ImGuiWindow* window); -static bool CloseWindowButton(bool* p_opened = NULL); -static void FocusWindow(ImGuiWindow* window); -static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); - -// Helpers: String -static int ImStricmp(const char* str1, const char* str2); -static int ImStrnicmp(const char* str1, const char* str2, int count); -static char* ImStrdup(const char *str); -static size_t ImStrlenW(const ImWchar* str); -static const char* ImStristr(const char* haystack, const char* needle, const char* needle_end); -static size_t ImFormatString(char* buf, size_t buf_size, const char* fmt, ...); -static size_t ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args); - -// Helpers: Misc -static ImU32 ImHash(const void* data, size_t data_size, ImU32 seed); -static bool ImLoadFileToMemory(const char* filename, const char* file_open_mode, void** out_file_data, size_t* out_file_size, size_t padding_bytes = 0); -static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } -static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; } - -// Helpers: UTF-8 <> wchar -static int ImTextCharToUtf8(char* buf, size_t buf_size, unsigned int in_char); // return output UTF-8 bytes count -static ptrdiff_t ImTextStrToUtf8(char* buf, size_t buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count -static int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count -static ptrdiff_t ImTextStrFromUtf8(ImWchar* buf, size_t buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count -static int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) -static int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points +static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); + +static void PushMultiItemsWidths(int components, float w_full = 0.0f); +static float GetDraggedColumnOffset(int column_index); + +static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); + +static void SetCurrentFont(ImFont* font); +static void SetCurrentWindow(ImGuiWindow* window); +static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y); +static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond); +static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond); +static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond); +static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); +static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); +static inline bool IsWindowContentHoverable(ImGuiWindow* window); +static void ClearSetNextWindowData(); +static void CheckStacksSize(ImGuiWindow* window, bool write); +static void Scrollbar(ImGuiWindow* window, bool horizontal); + +static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list); +static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window); +static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window); + +static ImGuiIniData* FindWindowSettings(const char* name); +static ImGuiIniData* AddWindowSettings(const char* name); +static void LoadSettings(); +static void SaveSettings(); +static void MarkSettingsDirty(); + +static void PushColumnClipRect(int column_index = -1); +static ImRect GetVisibleRect(); + +static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags); +static void CloseInactivePopups(); +static void ClosePopupToLevel(int remaining); +static void ClosePopup(ImGuiID id); +static bool IsPopupOpen(ImGuiID id); +static ImGuiWindow* GetFrontMostModalRootWindow(); +static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& rect_to_avoid); + +static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data); +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size); +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size); +static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2); +static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format); //----------------------------------------------------------------------------- // Platform dependent default implementations //----------------------------------------------------------------------------- -static const char* GetClipboardTextFn_DefaultImpl(); -static void SetClipboardTextFn_DefaultImpl(const char* text); -static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); +static const char* GetClipboardTextFn_DefaultImpl(); +static void SetClipboardTextFn_DefaultImpl(const char* text); +static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); + +//----------------------------------------------------------------------------- +// Context +//----------------------------------------------------------------------------- + +// Default context, default font atlas. +// New contexts always point by default to this font atlas. It can be changed by reassigning the GetIO().Fonts variable. +static ImGuiContext GImDefaultContext; +static ImFontAtlas GImDefaultFontAtlas; + +// Current context pointer. Implicitely used by all ImGui functions. Always assumed to be != NULL. Change to a different context by calling ImGui::SetCurrentContext() +// ImGui is currently not thread-safe because of this variable. If you want thread-safety to allow N threads to access N different contexts, you might work around it by (A) having two instances of the ImGui code under different namespaces or (B) change this variable to be TLS. Further development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 +ImGuiContext* GImGui = &GImDefaultContext; //----------------------------------------------------------------------------- // User facing structures @@ -541,31 +730,41 @@ ImGuiStyle::ImGuiStyle() WindowPadding = ImVec2(8,8); // Padding within a window WindowMinSize = ImVec2(32,32); // Minimum window size WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows - ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows + WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text + ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! - AutoFitPadding = ImVec2(8,8); // Extra space after auto-fit (double-clicking on resize grip) - WindowFillAlphaDefault = 0.70f; // Default alpha of window background, if not specified in ImGui::Begin() - IndentSpacing = 22.0f; // Horizontal spacing when e.g. entering a tree node + IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns - ScrollbarWidth = 16.0f; // Width of the vertical scrollbar - GrabMinSize = 10.0f; // Minimum width/height of a slider or scrollbar grab - DisplaySafeAreaPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area. If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding + ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar + ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar + GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar + GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. + ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. + DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows. + DisplaySafeAreaPadding = ImVec2(4,4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. + AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. + AntiAliasedShapes = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) + CurveTessellationTol = 1.25f; // Tessellation tolerance. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); - Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); + Colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f); + Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.70f); Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); - Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); - Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.60f); + Colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); + Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 0.65f); + Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f); Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f); - Colors[ImGuiCol_TitleBg] = ImVec4(0.50f, 0.50f, 1.00f, 0.45f); + Colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f); Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); - Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.40f, 0.40f, 0.80f, 0.15f); + Colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f); + Colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f); + Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f); Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f); @@ -593,13 +792,9 @@ ImGuiStyle::ImGuiStyle() Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); - Colors[ImGuiCol_TooltipBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); + Colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f); } -// Statically allocated font atlas. This is merely a maneuver to keep ImFontAtlas definition at the bottom of the .h file (otherwise it'd be inside ImGuiIO) -// Also we wouldn't be able to new() one at this point, before users may define IO.MemAllocFn. -static ImFontAtlas GDefaultFontAtlas; - ImGuiIO::ImGuiIO() { // Most fields are initialized with zero @@ -610,13 +805,22 @@ ImGuiIO::ImGuiIO() IniSavingRate = 5.0f; IniFilename = "imgui.ini"; LogFilename = "imgui_log.txt"; - Fonts = &GDefaultFontAtlas; + Fonts = &GImDefaultFontAtlas; FontGlobalScale = 1.0f; + DisplayFramebufferScale = ImVec2(1.0f, 1.0f); MousePos = ImVec2(-1,-1); MousePosPrev = ImVec2(-1,-1); MouseDoubleClickTime = 0.30f; MouseDoubleClickMaxDist = 6.0f; MouseDragThreshold = 6.0f; + for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) + MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; + for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) + KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f; + for (int i = 0; i < ImGuiKey_COUNT; i++) + KeyMap[i] = -1; + KeyRepeatDelay = 0.250f; + KeyRepeatRate = 0.050f; UserData = NULL; // User functions @@ -626,6 +830,11 @@ ImGuiIO::ImGuiIO() GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; + + // Set OS X style defaults based on __APPLE__ compile time flag +#ifdef __APPLE__ + OSXBehaviors = true; +#endif } // Pass in translated ASCII characters for text input. @@ -633,101 +842,95 @@ ImGuiIO::ImGuiIO() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message void ImGuiIO::AddInputCharacter(ImWchar c) { - const size_t n = ImStrlenW(InputCharacters); - if (n + 1 < sizeof(InputCharacters) / sizeof(InputCharacters[0])) + const int n = ImStrlenW(InputCharacters); + if (n + 1 < IM_ARRAYSIZE(InputCharacters)) { InputCharacters[n] = c; - InputCharacters[n+1] = 0; + InputCharacters[n+1] = '\0'; } } +void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) +{ + // We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more + const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar); + ImWchar wchars[wchars_buf_len]; + ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL); + for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++) + AddInputCharacter(wchars[i]); +} + //----------------------------------------------------------------------------- -// Helpers +// HELPERS //----------------------------------------------------------------------------- -#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) - -#undef PI -const float PI = 3.14159265358979323846f; - -#ifdef INT_MAX -#define IM_INT_MIN INT_MIN -#define IM_INT_MAX INT_MAX -#else -#define IM_INT_MIN (-2147483647-1) -#define IM_INT_MAX (2147483647) -#endif +#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose +#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255 // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. -#ifdef _MSC_VER -#define STR_NEWLINE "\r\n" +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" #else -#define STR_NEWLINE "\n" +#define IM_NEWLINE "\n" #endif -// Math bits -// We are keeping those static in the .cpp file so as not to leak them outside, in the case the user has implicit cast operators between ImVec2 and its own types. -static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); } -//static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); } -static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); } -static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); } -static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); } -static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); } -static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } -static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } -static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } -//static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } - -static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } -static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } -static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } -static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } -static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); } -static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); } -static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } -static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } -static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); } -static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } -static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; } -static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } -static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } - -static int ImStricmp(const char* str1, const char* str2) +bool ImIsPointInTriangle(const ImVec2& p, const ImVec2& a, const ImVec2& b, const ImVec2& c) +{ + bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; + bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; + bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; + return ((b1 == b2) && (b2 == b3)); +} + +int ImStricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } -static int ImStrnicmp(const char* str1, const char* str2, int count) +int ImStrnicmp(const char* str1, const char* str2, int count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } -static char* ImStrdup(const char *str) +void ImStrncpy(char* dst, const char* src, int count) +{ + if (count < 1) return; + strncpy(dst, src, (size_t)count); + dst[count-1] = 0; +} + +char* ImStrdup(const char *str) { - char *buff = (char*)ImGui::MemAlloc(strlen(str) + 1); - IM_ASSERT(buff); - strcpy(buff, str); - return buff; + size_t len = strlen(str) + 1; + void* buff = ImGui::MemAlloc(len); + return (char*)memcpy(buff, (const void*)str, len); } -static size_t ImStrlenW(const ImWchar* str) +int ImStrlenW(const ImWchar* str) { - size_t n = 0; + int n = 0; while (*str++) n++; return n; } -static const char* ImStristr(const char* haystack, const char* needle, const char* needle_end) +const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line +{ + while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') + buf_mid_line--; + return buf_mid_line; +} + +const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) { if (!needle_end) needle_end = needle + strlen(needle); const char un0 = (char)toupper(*needle); - while (*haystack) + while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) { if (toupper(*haystack) == un0) { @@ -743,32 +946,58 @@ static const char* ImStristr(const char* haystack, const char* needle, const cha return NULL; } -// Pass data_size==0 for zero-terminated string -// Try to replace with FNV1a hash? -static ImU32 ImHash(const void* data, size_t data_size, ImU32 seed = 0) -{ + +// MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size). +// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm. +int ImFormatString(char* buf, int buf_size, const char* fmt, ...) +{ + IM_ASSERT(buf_size > 0); + va_list args; + va_start(args, fmt); + int w = vsnprintf(buf, buf_size, fmt, args); + va_end(args); + if (w == -1 || w >= buf_size) + w = buf_size - 1; + buf[w] = 0; + return w; +} + +int ImFormatStringV(char* buf, int buf_size, const char* fmt, va_list args) +{ + IM_ASSERT(buf_size > 0); + int w = vsnprintf(buf, buf_size, fmt, args); + if (w == -1 || w >= buf_size) + w = buf_size - 1; + buf[w] = 0; + return w; +} + +// Pass data_size==0 for zero-terminated strings +// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. +ImU32 ImHash(const void* data, int data_size, ImU32 seed) +{ static ImU32 crc32_lut[256] = { 0 }; if (!crc32_lut[1]) { const ImU32 polynomial = 0xEDB88320; - for (ImU32 i = 0; i < 256; i++) - { - ImU32 crc = i; - for (ImU32 j = 0; j < 8; j++) - crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); - crc32_lut[i] = crc; + for (ImU32 i = 0; i < 256; i++) + { + ImU32 crc = i; + for (ImU32 j = 0; j < 8; j++) + crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); + crc32_lut[i] = crc; } } seed = ~seed; - ImU32 crc = seed; + ImU32 crc = seed; const unsigned char* current = (const unsigned char*)data; if (data_size > 0) { // Known size - while (data_size--) - crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; + while (data_size--) + crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; } else { @@ -777,43 +1006,226 @@ static ImU32 ImHash(const void* data, size_t data_size, ImU32 seed = 0) { // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. // Because this syntax is rarely used we are optimizing for the common case. - // - If we reach ### in the string we discard the hash so far and reset to the seed. + // - If we reach ### in the string we discard the hash so far and reset to the seed. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller. if (c == '#' && current[0] == '#' && current[1] == '#') crc = seed; - crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } } - return ~crc; -} + return ~crc; +} + +//----------------------------------------------------------------------------- +// ImText* helpers +//----------------------------------------------------------------------------- -static size_t ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) +// Convert UTF-8 to 32-bits character, process single character input. +// Based on stb_from_utf8() from github.com/nothings/stb/ +// We handle UTF-8 decoding error by skipping forward. +int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { - va_list args; - va_start(args, fmt); - int w = vsnprintf(buf, buf_size, fmt, args); - va_end(args); - buf[buf_size-1] = 0; - return (w == -1) ? buf_size : (size_t)w; + unsigned int c = (unsigned int)-1; + const unsigned char* str = (const unsigned char*)in_text; + if (!(*str & 0x80)) + { + c = (unsigned int)(*str++); + *out_char = c; + return 1; + } + if ((*str & 0xe0) == 0xc0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 2) return 1; + if (*str < 0xc2) return 2; + c = (unsigned int)((*str++ & 0x1f) << 6); + if ((*str & 0xc0) != 0x80) return 2; + c += (*str++ & 0x3f); + *out_char = c; + return 2; + } + if ((*str & 0xf0) == 0xe0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 3) return 1; + if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; + if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x0f) << 12); + if ((*str & 0xc0) != 0x80) return 3; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 3; + c += (*str++ & 0x3f); + *out_char = c; + return 3; + } + if ((*str & 0xf8) == 0xf0) + { + *out_char = 0xFFFD; // will be invalid but not end of string + if (in_text_end && in_text_end - (const char*)str < 4) return 1; + if (*str > 0xf4) return 4; + if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; + if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below + c = (unsigned int)((*str++ & 0x07) << 18); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 12); + if ((*str & 0xc0) != 0x80) return 4; + c += (unsigned int)((*str++ & 0x3f) << 6); + if ((*str & 0xc0) != 0x80) return 4; + c += (*str++ & 0x3f); + // utf-8 encodings of values used in surrogate pairs are invalid + if ((c & 0xFFFFF800) == 0xD800) return 4; + *out_char = c; + return 4; + } + *out_char = 0; + return 0; } -static size_t ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) +int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) { - int w = vsnprintf(buf, buf_size, fmt, args); - buf[buf_size-1] = 0; - return (w == -1) ? buf_size : (size_t)w; + ImWchar* buf_out = buf; + ImWchar* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes + *buf_out++ = (ImWchar)c; + } + *buf_out = 0; + if (in_text_remaining) + *in_text_remaining = in_text; + return (int)(buf_out - buf); +} + +int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) +{ + int char_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c; + in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); + if (c == 0) + break; + if (c < 0x10000) + char_count++; + } + return char_count; +} + +// Based on stb_to_utf8() from github.com/nothings/stb/ +static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) +{ + if (c < 0x80) + { + buf[0] = (char)c; + return 1; + } + if (c < 0x800) + { + if (buf_size < 2) return 0; + buf[0] = (char)(0xc0 + (c >> 6)); + buf[1] = (char)(0x80 + (c & 0x3f)); + return 2; + } + if (c >= 0xdc00 && c < 0xe000) + { + return 0; + } + if (c >= 0xd800 && c < 0xdc00) + { + if (buf_size < 4) return 0; + buf[0] = (char)(0xf0 + (c >> 18)); + buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); + buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); + buf[3] = (char)(0x80 + ((c ) & 0x3f)); + return 4; + } + //else if (c < 0x10000) + { + if (buf_size < 3) return 0; + buf[0] = (char)(0xe0 + (c >> 12)); + buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); + buf[2] = (char)(0x80 + ((c ) & 0x3f)); + return 3; + } +} + +static inline int ImTextCountUtf8BytesFromChar(unsigned int c) +{ + if (c < 0x80) return 1; + if (c < 0x800) return 2; + if (c >= 0xdc00 && c < 0xe000) return 0; + if (c >= 0xd800 && c < 0xdc00) return 4; + return 3; +} + +int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) +{ + char* buf_out = buf; + const char* buf_end = buf + buf_size; + while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + *buf_out++ = (char)c; + else + buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); + } + *buf_out = 0; + return (int)(buf_out - buf); +} + +int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) +{ + int bytes_count = 0; + while ((!in_text_end || in_text < in_text_end) && *in_text) + { + unsigned int c = (unsigned int)(*in_text++); + if (c < 0x80) + bytes_count++; + else + bytes_count += ImTextCountUtf8BytesFromChar(c); + } + return bytes_count; +} + +ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) +{ + float s = 1.0f/255.0f; + return ImVec4( + ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_B_SHIFT) & 0xFF) * s, + ((in >> IM_COL32_A_SHIFT) & 0xFF) * s); } ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) { - ImU32 out = ((ImU32)(ImSaturate(in.x)*255.f)); - out |= ((ImU32)(ImSaturate(in.y)*255.f) << 8); - out |= ((ImU32)(ImSaturate(in.z)*255.f) << 16); - out |= ((ImU32)(ImSaturate(in.w)*255.f) << 24); + ImU32 out; + out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT; + out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT; return out; } +ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) +{ + ImVec4 c = GImGui->Style.Colors[idx]; + c.w *= GImGui->Style.Alpha * alpha_mul; + return ColorConvertFloat4ToU32(c); +} + +ImU32 ImGui::GetColorU32(const ImVec4& col) +{ + ImVec4 c = col; + c.w *= GImGui->Style.Alpha; + return ColorConvertFloat4ToU32(c); +} + // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) @@ -839,7 +1251,7 @@ void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 // also http://en.wikipedia.org/wiki/HSL_and_HSV void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) -{ +{ if (s == 0.0f) { // gray @@ -867,501 +1279,93 @@ void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& // Load file content into memory // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() -static bool ImLoadFileToMemory(const char* filename, const char* file_open_mode, void** out_file_data, size_t* out_file_size, size_t padding_bytes) +void* ImLoadFileToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes) { - IM_ASSERT(filename && file_open_mode && out_file_data && out_file_size); - *out_file_data = NULL; - *out_file_size = 0; + IM_ASSERT(filename && file_open_mode); + if (out_file_size) + *out_file_size = 0; FILE* f; if ((f = fopen(filename, file_open_mode)) == NULL) - return false; + return NULL; long file_size_signed; if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); - return false; + return NULL; } - size_t file_size = (size_t)file_size_signed; + int file_size = (int)file_size_signed; void* file_data = ImGui::MemAlloc(file_size + padding_bytes); if (file_data == NULL) { fclose(f); - return false; + return NULL; } - if (fread(file_data, 1, file_size, f) != file_size) + if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size) { fclose(f); ImGui::MemFree(file_data); - return false; + return NULL; } if (padding_bytes > 0) memset((void *)(((char*)file_data) + file_size), 0, padding_bytes); fclose(f); - *out_file_data = file_data; - *out_file_size = file_size; + if (out_file_size) + *out_file_size = file_size; - return true; + return file_data; } +//----------------------------------------------------------------------------- +// ImGuiStorage //----------------------------------------------------------------------------- -struct ImGuiColMod // Color modifier, backup of modified data so we can restore it +// Helper: Key->value storage +void ImGuiStorage::Clear() { - ImGuiCol Col; - ImVec4 PreviousValue; -}; + Data.clear(); +} -struct ImGuiStyleMod // Style modifier, backup of modified data so we can restore it +// std::lower_bound but without the bullshit +static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key) { - ImGuiStyleVar Var; - ImVec2 PreviousValue; -}; - -struct ImRect // 2D axis aligned bounding-box -{ - ImVec2 Min; - ImVec2 Max; - - ImRect() { Min = ImVec2(FLT_MAX,FLT_MAX); Max = ImVec2(-FLT_MAX,-FLT_MAX); } - ImRect(const ImVec2& min, const ImVec2& max) { Min = min; Max = max; } - ImRect(const ImVec4& v) { Min.x = v.x; Min.y = v.y; Max.x = v.z; Max.y = v.w; } - ImRect(float x1, float y1, float x2, float y2) { Min.x = x1; Min.y = y1; Max.x = x2; Max.y = y2; } - - ImVec2 GetCenter() const { return Min + (Max-Min)*0.5f; } - ImVec2 GetSize() const { return Max-Min; } - float GetWidth() const { return (Max-Min).x; } - float GetHeight() const { return (Max-Min).y; } - ImVec2 GetTL() const { return Min; } - ImVec2 GetTR() const { return ImVec2(Max.x,Min.y); } - ImVec2 GetBL() const { return ImVec2(Min.x,Max.y); } - ImVec2 GetBR() const { return Max; } - bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } - bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; } - bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } - void Add(const ImVec2& rhs) { Min.x = ImMin(Min.x, rhs.x); Min.y = ImMin(Min.y, rhs.y); Max.x = ImMax(Max.x, rhs.x); Max.y = ImMax(Max.x, rhs.x); } - void Add(const ImRect& rhs) { Min.x = ImMin(Min.x, rhs.Min.x); Min.y = ImMin(Min.y, rhs.Min.y); Max.x = ImMax(Max.x, rhs.Max.x); Max.y = ImMax(Max.y, rhs.Max.y); } - void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } - void Expand(const ImVec2& amount) { Min -= amount; Max += amount; } - void Clip(const ImRect& clip) { Min.x = ImMax(Min.x, clip.Min.x); Min.y = ImMax(Min.y, clip.Min.y); Max.x = ImMin(Max.x, clip.Max.x); Max.y = ImMin(Max.y, clip.Max.y); } - ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const - { - if (!on_edge && Contains(p)) - return p; - if (p.x > Max.x) p.x = Max.x; - else if (p.x < Min.x) p.x = Min.x; - if (p.y > Max.y) p.y = Max.y; - else if (p.y < Min.y) p.y = Min.y; - return p; + ImVector<ImGuiStorage::Pair>::iterator first = data.begin(); + ImVector<ImGuiStorage::Pair>::iterator last = data.end(); + int count = (int)(last - first); + while (count > 0) + { + int count2 = count / 2; + ImVector<ImGuiStorage::Pair>::iterator mid = first + count2; + if (mid->key < key) + { + first = ++mid; + count -= count2 + 1; + } + else + { + count = count2; + } } -}; -typedef ImRect ImGuiAabb; // FIXME-OBSOLETE + return first; +} -struct ImGuiGroupData +int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { - ImVec2 BackupCursorPos; - ImVec2 BackupCursorMaxPos; - float BackupColumnsStartX; - float BackupCurrentLineHeight; - float BackupCurrentLineTextBaseOffset; - float BackupLogLinePosY; -}; - -// Temporary per-window data, reset at the beginning of the frame -struct ImGuiDrawContext -{ - ImVec2 CursorPos; - ImVec2 CursorPosPrevLine; - ImVec2 CursorStartPos; - ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame - float CurrentLineHeight; - float CurrentLineTextBaseOffset; - float PrevLineHeight; - float PrevLineTextBaseOffset; - float LogLinePosY; - int TreeDepth; - ImGuiID LastItemID; - ImRect LastItemRect; - bool LastItemHoveredAndUsable; - bool LastItemHoveredRect; - ImVector<ImGuiWindow*> ChildWindows; - ImVector<bool> AllowKeyboardFocus; - ImVector<float> ItemWidth; // 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window - ImVector<float> TextWrapPos; - ImVector<ImGuiGroupData> GroupStack; - ImGuiColorEditMode ColorEditMode; - ImGuiStorage* StateStorage; - - float ColumnsStartX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) - float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. - int ColumnsCurrent; - int ColumnsCount; - ImVec2 ColumnsStartPos; - float ColumnsCellMinY; - float ColumnsCellMaxY; - bool ColumnsShowBorders; - ImGuiID ColumnsSetID; - ImVector<float> ColumnsOffsetsT; // Columns offset normalized 0.0 (far left) -> 1.0 (far right) - - ImGuiDrawContext() - { - CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); - CurrentLineHeight = PrevLineHeight = 0.0f; - CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; - LogLinePosY = -1.0f; - TreeDepth = 0; - LastItemID = 0; - LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f); - LastItemHoveredAndUsable = LastItemHoveredRect = false; - ColorEditMode = ImGuiColorEditMode_RGB; - StateStorage = NULL; - - ColumnsStartX = 0.0f; - ColumnsOffsetX = 0.0f; - ColumnsCurrent = 0; - ColumnsCount = 1; - ColumnsStartPos = ImVec2(0.0f, 0.0f); - ColumnsCellMinY = ColumnsCellMaxY = 0.0f; - ColumnsShowBorders = true; - ColumnsSetID = 0; - } -}; + ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); + if (it == Data.end() || it->key != key) + return default_val; + return it->val_i; +} -// Internal state of the currently focused/edited text input box -struct ImGuiTextEditState -{ - ImGuiID Id; // widget id owning the text state - ImWchar Text[1024]; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. - char InitialText[1024*3+1]; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) - size_t CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. - size_t BufSizeA; // end-user buffer size, <= 1024 (or increase above) - float Width; // widget width - float ScrollX; - STB_TexteditState StbState; - float CursorAnim; - ImVec2 InputCursorScreenPos; // Cursor position in screen space to be used by IME callback. - bool SelectedAllMouseLock; - ImFont* Font; - float FontSize; - - ImGuiTextEditState() { memset(this, 0, sizeof(*this)); } - - void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking - bool CursorIsVisible() const { return CursorAnim <= 0.0f || fmodf(CursorAnim, 1.20f) <= 0.80f; } // Blinking - bool HasSelection() const { return StbState.select_start != StbState.select_end; } - void SelectAll() { StbState.select_start = 0; StbState.select_end = (int)ImStrlenW(Text); StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } - - void OnKeyPressed(int key); - void UpdateScrollOffset(); - ImVec2 CalcDisplayOffsetFromCharIdx(int i) const; - - // Static functions because they are used to render non-focused instances of a text input box - static const char* GetTextPointerClippedA(ImFont* font, float font_size, const char* text, float width, ImVec2* out_text_size = NULL); - static const ImWchar* GetTextPointerClippedW(ImFont* font, float font_size, const ImWchar* text, float width, ImVec2* out_text_size = NULL); - static void RenderTextScrolledClipped(ImFont* font, float font_size, const char* text, ImVec2 pos_base, float width, float scroll_x); -}; - -// Data saved in imgui.ini file -struct ImGuiIniData -{ - char* Name; - ImGuiID ID; - ImVec2 Pos; - ImVec2 Size; - bool Collapsed; - - ImGuiIniData() { memset(this, 0, sizeof(*this)); } - ~ImGuiIniData() { if (Name) { ImGui::MemFree(Name); Name = NULL; } } -}; - -struct ImGuiMouseCursorData -{ - ImGuiMouseCursor Type; - ImVec2 Offset; - ImVec2 Size; - ImVec2 TexUvMin[2]; - ImVec2 TexUvMax[2]; -}; - -// Main state for ImGui -struct ImGuiState -{ - bool Initialized; - ImGuiIO IO; - ImGuiStyle Style; - ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() - float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize() - float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters. - ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvForWhite - - float Time; - int FrameCount; - int FrameCountRendered; - ImVector<ImGuiWindow*> Windows; - ImVector<ImGuiWindow*> WindowsSortBuffer; - ImGuiWindow* CurrentWindow; // Being drawn into - ImVector<ImGuiWindow*> CurrentWindowStack; - ImGuiWindow* FocusedWindow; // Will catch keyboard inputs - ImGuiWindow* HoveredWindow; // Will catch mouse inputs - ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) - ImGuiID HoveredId; - ImGuiID ActiveId; - ImGuiID ActiveIdPreviousFrame; - bool ActiveIdIsAlive; - bool ActiveIdIsFocusedOnly; // Set only by active widget. Denote focus but no active interaction. - ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window. Only valid if ActiveID is the "#MOVE" identifier of a window. - float SettingsDirtyTimer; - ImVector<ImGuiIniData*> Settings; - int DisableHideTextAfterDoubleHash; - ImVector<ImGuiColMod> ColorModifiers; - ImVector<ImGuiStyleMod> StyleModifiers; - ImVector<ImFont*> FontStack; - - ImVec2 SetNextWindowPosVal; - ImGuiSetCond SetNextWindowPosCond; - ImVec2 SetNextWindowSizeVal; - ImGuiSetCond SetNextWindowSizeCond; - bool SetNextWindowCollapsedVal; - ImGuiSetCond SetNextWindowCollapsedCond; - bool SetNextWindowFocus; - bool SetNextTreeNodeOpenedVal; - ImGuiSetCond SetNextTreeNodeOpenedCond; - - // Render - ImVector<ImDrawList*> RenderDrawLists[3]; - - // Mouse cursor - ImGuiMouseCursor MouseCursor; - ImDrawList MouseCursorDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set - ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_]; - - // Widget state - ImGuiTextEditState InputTextState; - ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. - ImGuiStorage ColorEditModeStorage; // for user selection - ImGuiID ActiveComboID; - ImVec2 DragLastMouseDelta; - float DragSpeedScaleSlow; - float DragSpeedScaleFast; - float ScrollbarClickDeltaToGrabCenter; // distance between mouse and center of grab box, normalized in parent space - char Tooltip[1024]; - char* PrivateClipboard; // if no custom clipboard handler is defined - - // Logging - bool LogEnabled; - FILE* LogFile; - ImGuiTextBuffer* LogClipboard; // pointer so our GImGui static constructor doesn't call heap allocators. - int LogStartDepth; - int LogAutoExpandMaxDepth; - - // Misc - float FramerateSecPerFrame[120]; // calculate estimate of framerate for user - int FramerateSecPerFrameIdx; - float FramerateSecPerFrameAccum; - char TempBuffer[1024*3+1]; // temporary text buffer - - ImGuiState() - { - Initialized = false; - Font = NULL; - FontBaseSize = FontSize = 0.0f; - FontTexUvWhitePixel = ImVec2(0.0f, 0.0f); - - Time = 0.0f; - FrameCount = 0; - FrameCountRendered = -1; - CurrentWindow = NULL; - FocusedWindow = NULL; - HoveredWindow = NULL; - HoveredRootWindow = NULL; - HoveredId = 0; - ActiveId = 0; - ActiveIdPreviousFrame = 0; - ActiveIdIsAlive = false; - ActiveIdIsFocusedOnly = false; - MovedWindow = NULL; - SettingsDirtyTimer = 0.0f; - DisableHideTextAfterDoubleHash = 0; - - SetNextWindowPosVal = ImVec2(0.0f, 0.0f); - SetNextWindowPosCond = 0; - SetNextWindowSizeVal = ImVec2(0.0f, 0.0f); - SetNextWindowSizeCond = 0; - SetNextWindowCollapsedVal = false; - SetNextWindowCollapsedCond = 0; - SetNextWindowFocus = false; - SetNextTreeNodeOpenedVal = false; - SetNextTreeNodeOpenedCond = 0; - - ScalarAsInputTextId = 0; - ActiveComboID = 0; - DragLastMouseDelta = ImVec2(0.0f, 0.0f); - DragSpeedScaleSlow = 0.01f; - DragSpeedScaleFast = 10.0f; - ScrollbarClickDeltaToGrabCenter = 0.0f; - memset(Tooltip, 0, sizeof(Tooltip)); - PrivateClipboard = NULL; - - MouseCursor = ImGuiMouseCursor_Arrow; - - LogEnabled = false; - LogFile = NULL; - LogClipboard = NULL; - LogStartDepth = 0; - LogAutoExpandMaxDepth = 2; - - memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); - FramerateSecPerFrameIdx = 0; - FramerateSecPerFrameAccum = 0.0f; - } -}; - -static ImGuiState GImDefaultState; // Internal state storage -static ImGuiState* GImGui = &GImDefaultState; // We access everything through this pointer. NB: this pointer is always assumed to be != NULL - -struct ImGuiWindow -{ - char* Name; - ImGuiID ID; - ImGuiWindowFlags Flags; - ImVec2 PosFloat; - ImVec2 Pos; // Position rounded-up to nearest pixel - ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) - ImVec2 SizeFull; // Size when non collapsed - ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame - ImGuiID MoveID; // == window->GetID("#MOVE") - float ScrollY; - float NextScrollY; - bool ScrollbarY; - bool Visible; // Set to true on Begin() - bool WasVisible; - bool Accessed; // Set to true when any widget access the current window - bool Collapsed; // Set when collapsing window to become only title-bar - bool SkipItems; // == Visible && !Collapsed - int AutoFitFrames; - bool AutoFitOnlyGrows; - int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag. - int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag. - int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag. - - ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame - ImVector<ImGuiID> IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack - ImVector<ImVec4> ClipRectStack; // Scissoring / clipping rectangle. x1, y1, x2, y2. - ImRect ClippedRect; // = ClipRectStack.front() after setup in Begin() - int LastFrameDrawn; - float ItemWidthDefault; - ImGuiStorage StateStorage; - float FontWindowScale; // Scale multiplier per-window - ImDrawList* DrawList; - ImGuiWindow* RootWindow; - - // Focus - int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() - int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) - int FocusIdxAllRequestCurrent; // Item being requested for focus - int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus - int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame) - int FocusIdxTabRequestNext; // " - -public: - ImGuiWindow(const char* name); - ~ImGuiWindow(); - - ImGuiID GetID(const char* str); - ImGuiID GetID(const void* ptr); - - bool FocusItemRegister(bool is_active, bool tab_stop = true); // Return true if focus is requested - void FocusItemUnregister(); - - ImRect Rect() const { return ImRect(Pos, Pos+Size); } - float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; } - float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0 : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; } - ImRect TitleBarRect() const { return ImRect(Pos, Pos + ImVec2(SizeFull.x, TitleBarHeight())); } - ImVec2 WindowPadding() const { return ((Flags & ImGuiWindowFlags_ChildWindow) && !(Flags & ImGuiWindowFlags_ShowBorders) && !(Flags & ImGuiWindowFlags_ComboBox)) ? ImVec2(0,0) : GImGui->Style.WindowPadding; } - ImU32 Color(ImGuiCol idx, float a=1.f) const { ImVec4 c = GImGui->Style.Colors[idx]; c.w *= GImGui->Style.Alpha * a; return ImGui::ColorConvertFloat4ToU32(c); } - ImU32 Color(const ImVec4& col) const { ImVec4 c = col; c.w *= GImGui->Style.Alpha; return ImGui::ColorConvertFloat4ToU32(c); } -}; - -static inline ImGuiWindow* GetCurrentWindow() -{ - // If this ever crash it probably means that ImGui::NewFrame() hasn't been called. We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) - ImGuiState& g = *GImGui; - g.CurrentWindow->Accessed = true; - return g.CurrentWindow; -} - -static inline void SetCurrentWindow(ImGuiWindow* window) -{ - ImGuiState& g = *GImGui; - g.CurrentWindow = window; - if (window) - g.FontSize = window->CalcFontSize(); -} - -static inline ImGuiWindow* GetParentWindow() -{ - ImGuiState& g = *GImGui; - IM_ASSERT(g.CurrentWindowStack.size() >= 2); - return g.CurrentWindowStack[g.CurrentWindowStack.size() - 2]; -} - -static void SetActiveId(ImGuiID id) -{ - ImGuiState& g = *GImGui; - g.ActiveId = id; - g.ActiveIdIsFocusedOnly = false; -} - -static void RegisterAliveId(ImGuiID id) -{ - ImGuiState& g = *GImGui; - if (g.ActiveId == id) - g.ActiveIdIsAlive = true; -} - -//----------------------------------------------------------------------------- - -// Helper: Key->value storage -void ImGuiStorage::Clear() -{ - Data.clear(); -} - -// std::lower_bound but without the bullshit -static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImU32 key) -{ - ImVector<ImGuiStorage::Pair>::iterator first = data.begin(); - ImVector<ImGuiStorage::Pair>::iterator last = data.end(); - int count = (int)(last - first); - while (count > 0) - { - int count2 = count / 2; - ImVector<ImGuiStorage::Pair>::iterator mid = first + count2; - if (mid->key < key) - { - first = ++mid; - count -= count2 + 1; - } - else - { - count = count2; - } - } - return first; -} - -int ImGuiStorage::GetInt(ImU32 key, int default_val) const +bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const { - ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); - if (it == Data.end() || it->key != key) - return default_val; - return it->val_i; + return GetInt(key, default_val ? 1 : 0) != 0; } -float ImGuiStorage::GetFloat(ImU32 key, float default_val) const +float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) @@ -1386,6 +1390,11 @@ int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) return &it->val_i; } +bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) +{ + return (bool*)GetIntRef(key, default_val ? 1 : 0); +} + float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { ImVector<Pair>::iterator it = LowerBound(Data, key); @@ -1394,9 +1403,16 @@ float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) return &it->val_f; } -// FIXME-OPT: Wasting CPU because all SetInt() are preceeded by GetInt() calls so we should have the result from lower_bound already in place. -// However we only use SetInt() on explicit user action (so that's maximum once a frame) so the optimisation isn't much needed. -void ImGuiStorage::SetInt(ImU32 key, int val) +void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) +{ + ImVector<Pair>::iterator it = LowerBound(Data, key); + if (it == Data.end() || it->key != key) + it = Data.insert(it, Pair(key, default_val)); + return &it->val_p; +} + +// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) +void ImGuiStorage::SetInt(ImGuiID key, int val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) @@ -1407,7 +1423,12 @@ void ImGuiStorage::SetInt(ImU32 key, int val) it->val_i = val; } -void ImGuiStorage::SetFloat(ImU32 key, float val) +void ImGuiStorage::SetBool(ImGuiID key, bool val) +{ + SetInt(key, val ? 1 : 0); +} + +void ImGuiStorage::SetFloat(ImGuiID key, float val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) @@ -1418,7 +1439,7 @@ void ImGuiStorage::SetFloat(ImU32 key, float val) it->val_f = val; } -void ImGuiStorage::SetVoidPtr(ImU32 key, void* val) +void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) @@ -1431,10 +1452,12 @@ void ImGuiStorage::SetVoidPtr(ImU32 key, void* val) void ImGuiStorage::SetAllInt(int v) { - for (size_t i = 0; i < Data.size(); i++) + for (int i = 0; i < Data.Size; i++) Data[i].val_i = v; } +//----------------------------------------------------------------------------- +// ImGuiTextFilter //----------------------------------------------------------------------------- // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" @@ -1442,7 +1465,7 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) { if (default_filter) { - ImFormatString(InputBuf, IM_ARRAYSIZE(InputBuf), "%s", default_filter); + ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); Build(); } else @@ -1452,14 +1475,16 @@ ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) } } -void ImGuiTextFilter::Draw(const char* label, float width) +bool ImGuiTextFilter::Draw(const char* label, float width) { - if (width > 0.0f) + if (width != 0.0f) ImGui::PushItemWidth(width); - ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); - if (width > 0.0f) + bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); + if (width != 0.0f) ImGui::PopItemWidth(); - Build(); + if (value_changed) + Build(); + return value_changed; } void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out) @@ -1487,7 +1512,7 @@ void ImGuiTextFilter::Build() input_range.split(',', Filters); CountGrep = 0; - for (size_t i = 0; i != Filters.size(); i++) + for (int i = 0; i != Filters.Size; i++) { Filters[i].trim_blanks(); if (Filters[i].empty()) @@ -1497,15 +1522,15 @@ void ImGuiTextFilter::Build() } } -bool ImGuiTextFilter::PassFilter(const char* val) const +bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { if (Filters.empty()) return true; - if (val == NULL) - val = ""; + if (text == NULL) + text = ""; - for (size_t i = 0; i != Filters.size(); i++) + for (int i = 0; i != Filters.Size; i++) { const TextRange& f = Filters[i]; if (f.empty()) @@ -1513,13 +1538,13 @@ bool ImGuiTextFilter::PassFilter(const char* val) const if (f.front() == '-') { // Subtract - if (ImStristr(val, f.begin()+1, f.end()) != NULL) + if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) return false; } else { // Grep - if (ImStristr(val, f.begin(), f.end()) != NULL) + if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) return true; } } @@ -1531,9 +1556,11 @@ bool ImGuiTextFilter::PassFilter(const char* val) const return false; } +//----------------------------------------------------------------------------- +// ImGuiTextBuffer //----------------------------------------------------------------------------- -// On some platform vsnprintf() takes va_list by reference and modifies it. +// On some platform vsnprintf() takes va_list by reference and modifies it. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. #ifndef va_copy #define va_copy(dest, src) (dest = src) @@ -1549,16 +1576,16 @@ void ImGuiTextBuffer::appendv(const char* fmt, va_list args) if (len <= 0) return; - const size_t write_off = Buf.size(); - const size_t needed_sz = write_off + (size_t)len; - if (write_off + (size_t)len >= Buf.capacity()) + const int write_off = Buf.Size; + const int needed_sz = write_off + len; + if (write_off + len >= Buf.Capacity) { - const size_t double_capacity = Buf.capacity() * 2; + int double_capacity = Buf.Capacity * 2; Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity); } Buf.resize(needed_sz); - ImFormatStringV(&Buf[write_off] - 1, (size_t)len+1, fmt, args_copy); + ImFormatStringV(&Buf[write_off] - 1, len+1, fmt, args_copy); } void ImGuiTextBuffer::append(const char* fmt, ...) @@ -1569,41 +1596,184 @@ void ImGuiTextBuffer::append(const char* fmt, ...) va_end(args); } +//----------------------------------------------------------------------------- +// ImGuiSimpleColumns +//----------------------------------------------------------------------------- + +ImGuiSimpleColumns::ImGuiSimpleColumns() +{ + Count = 0; + Spacing = Width = NextWidth = 0.0f; + memset(Pos, 0, sizeof(Pos)); + memset(NextWidths, 0, sizeof(NextWidths)); +} + +void ImGuiSimpleColumns::Update(int count, float spacing, bool clear) +{ + IM_ASSERT(Count <= IM_ARRAYSIZE(Pos)); + Count = count; + Width = NextWidth = 0.0f; + Spacing = spacing; + if (clear) memset(NextWidths, 0, sizeof(NextWidths)); + for (int i = 0; i < Count; i++) + { + if (i > 0 && NextWidths[i] > 0.0f) + Width += Spacing; + Pos[i] = (float)(int)Width; + Width += NextWidths[i]; + NextWidths[i] = 0.0f; + } +} + +float ImGuiSimpleColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double +{ + NextWidth = 0.0f; + NextWidths[0] = ImMax(NextWidths[0], w0); + NextWidths[1] = ImMax(NextWidths[1], w1); + NextWidths[2] = ImMax(NextWidths[2], w2); + for (int i = 0; i < 3; i++) + NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f); + return ImMax(Width, NextWidth); +} + +float ImGuiSimpleColumns::CalcExtraSpace(float avail_w) +{ + return ImMax(0.0f, avail_w - Width); +} + +//----------------------------------------------------------------------------- +// ImGuiListClipper +//----------------------------------------------------------------------------- + +static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) +{ + // Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor. + // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. Consider moving within SetCursorXXX functions? + ImGui::SetCursorPosY(pos_y); + ImGuiWindow* window = ImGui::GetCurrentWindow(); + window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage. + window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. + if (window->DC.ColumnsCount > 1) + window->DC.ColumnsCellMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly +} + +// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 +// Use case B: Begin() called from constructor with items_height>0 +// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. +void ImGuiListClipper::Begin(int count, float items_height) +{ + StartPosY = ImGui::GetCursorPosY(); + ItemsHeight = items_height; + ItemsCount = count; + StepNo = 0; + DisplayEnd = DisplayStart = -1; + if (ItemsHeight > 0.0f) + { + ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display + if (DisplayStart > 0) + SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor + StepNo = 2; + } +} + +void ImGuiListClipper::End() +{ + if (ItemsCount < 0) + return; + // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. + if (ItemsCount < INT_MAX) + SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor + ItemsCount = -1; + StepNo = 3; +} + +bool ImGuiListClipper::Step() +{ + if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems) + { + ItemsCount = -1; + return false; + } + if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height. + { + DisplayStart = 0; + DisplayEnd = 1; + StartPosY = ImGui::GetCursorPosY(); + StepNo = 1; + return true; + } + if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. + { + if (ItemsCount == 1) { ItemsCount = -1; return false; } + float items_height = ImGui::GetCursorPosY() - StartPosY; + IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically + Begin(ItemsCount-1, items_height); + DisplayStart++; + DisplayEnd++; + StepNo = 3; + return true; + } + if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. + { + IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); + StepNo = 3; + return true; + } + if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. + End(); + return false; +} + +//----------------------------------------------------------------------------- +// ImGuiWindow //----------------------------------------------------------------------------- ImGuiWindow::ImGuiWindow(const char* name) { Name = ImStrdup(name); - ID = ImHash(name, 0); + ID = ImHash(name, 0); IDStack.push_back(ID); - MoveID = GetID("#MOVE"); + MoveId = GetID("#MOVE"); Flags = 0; + IndexWithinParent = 0; PosFloat = Pos = ImVec2(0.0f, 0.0f); Size = SizeFull = ImVec2(0.0f, 0.0f); - SizeContents = ImVec2(0.0f, 0.0f); - ScrollY = 0.0f; - NextScrollY = 0.0f; - ScrollbarY = false; - Visible = WasVisible = false; + SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f); + WindowPadding = ImVec2(0.0f, 0.0f); + Scroll = ImVec2(0.0f, 0.0f); + ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); + ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); + ScrollbarX = ScrollbarY = false; + ScrollbarSizes = ImVec2(0.0f, 0.0f); + BorderSize = 0.0f; + Active = WasActive = false; Accessed = false; Collapsed = false; SkipItems = false; - AutoFitFrames = -1; + BeginCount = 0; + PopupId = 0; + AutoFitFramesX = AutoFitFramesY = -1; AutoFitOnlyGrows = false; - SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver; + AutoPosLastDirection = -1; + HiddenFrames = 0; + SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing; + SetWindowPosCenterWanted = false; - LastFrameDrawn = -1; + LastFrameActive = -1; ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList)); - new(DrawList) ImDrawList(); + IM_PLACEMENT_NEW(DrawList) ImDrawList(); + DrawList->_OwnerName = Name; RootWindow = NULL; + RootNonPopupWindow = NULL; + ParentWindow = NULL; FocusIdxAllCounter = FocusIdxTabCounter = -1; - FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = IM_INT_MAX; - FocusIdxAllRequestNext = FocusIdxTabRequestNext = IM_INT_MAX; + FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX; + FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX; } ImGuiWindow::~ImGuiWindow() @@ -1615,276 +1785,337 @@ ImGuiWindow::~ImGuiWindow() Name = NULL; } -ImGuiID ImGuiWindow::GetID(const char* str) +ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); - const ImGuiID id = ImHash(str, 0, seed); - RegisterAliveId(id); + ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed); + ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetID(const void* ptr) { ImGuiID seed = IDStack.back(); - const ImGuiID id = ImHash(&ptr, sizeof(void*), seed); - RegisterAliveId(id); + ImGuiID id = ImHash(&ptr, sizeof(void*), seed); + ImGui::KeepAliveID(id); return id; } -bool ImGuiWindow::FocusItemRegister(bool is_active, bool tab_stop) +ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) +{ + ImGuiID seed = IDStack.back(); + return ImHash(str, str_end ? (int)(str_end - str) : 0, seed); +} + +//----------------------------------------------------------------------------- +// Internal API exposed in imgui_internal.h +//----------------------------------------------------------------------------- + +static void SetCurrentWindow(ImGuiWindow* window) +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow = window; + if (window) + g.FontSize = window->CalcFontSize(); +} + +ImGuiWindow* ImGui::GetParentWindow() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.CurrentWindowStack.Size >= 2); + return g.CurrentWindowStack[(unsigned int)g.CurrentWindowStack.Size - 2]; +} + +void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window = NULL) +{ + ImGuiContext& g = *GImGui; + g.ActiveId = id; + g.ActiveIdAllowOverlap = false; + g.ActiveIdIsJustActivated = true; + if (id) + g.ActiveIdIsAlive = true; + g.ActiveIdWindow = window; +} + +void ImGui::SetHoveredID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + g.HoveredId = id; + g.HoveredIdAllowOverlap = false; +} + +void ImGui::KeepAliveID(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + if (g.ActiveId == id) + g.ActiveIdIsAlive = true; +} + +// Advance cursor given item size for layout. +void ImGui::ItemSize(const ImVec2& size, float text_offset_y) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + // Always align ourselves on pixel boundaries + ImGuiContext& g = *GImGui; + const float line_height = ImMax(window->DC.CurrentLineHeight, size.y); + const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); + window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); + window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); + window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); + window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); + + //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // Debug + + window->DC.PrevLineHeight = line_height; + window->DC.PrevLineTextBaseOffset = text_base_offset; + window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f; +} + +void ImGui::ItemSize(const ImRect& bb, float text_offset_y) +{ + ItemSize(bb.GetSize(), text_offset_y); +} + +// Declare item bounding box for clipping and interaction. +// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface +// declares their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd(). +bool ImGui::ItemAdd(const ImRect& bb, const ImGuiID* id) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); + window->DC.LastItemId = id ? *id : 0; + window->DC.LastItemRect = bb; + window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; + if (IsClippedEx(bb, id, false)) + return false; + + // This is a sensible default, but widgets are free to override it after calling ItemAdd() + ImGuiContext& g = *GImGui; + if (IsMouseHoveringRect(bb.Min, bb.Max)) + { + // Matching the behavior of IsHovered() but allow if ActiveId==window->MoveID (we clicked on the window background) + // So that clicking on items with no active id such as Text() still returns true with IsItemHovered() + window->DC.LastItemHoveredRect = true; + if (g.HoveredRootWindow == window->RootWindow) + if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdAllowOverlap || (g.ActiveId == window->MoveId)) + if (IsWindowContentHoverable(window)) + window->DC.LastItemHoveredAndUsable = true; + } + + return true; +} + +bool ImGui::IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); + + if (!bb.Overlaps(window->ClipRect)) + if (!id || *id != GImGui->ActiveId) + if (clip_even_when_logged || !g.LogEnabled) + return true; + return false; +} + +// NB: This is an internal helper. The user-facing IsItemHovered() is using data emitted from ItemAdd(), with a slightly different logic. +bool ImGui::IsHovered(const ImRect& bb, ImGuiID id, bool flatten_childs) +{ + ImGuiContext& g = *GImGui; + if (g.HoveredId == 0 || g.HoveredId == id || g.HoveredIdAllowOverlap) + { + ImGuiWindow* window = GetCurrentWindowRead(); + if (g.HoveredWindow == window || (flatten_childs && g.HoveredRootWindow == window->RootWindow)) + if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdAllowOverlap) && IsMouseHoveringRect(bb.Min, bb.Max)) + if (IsWindowContentHoverable(g.HoveredRootWindow)) + return true; + } + return false; +} + +bool ImGui::FocusableItemRegister(ImGuiWindow* window, bool is_active, bool tab_stop) +{ + ImGuiContext& g = *GImGui; - const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus.back(); - FocusIdxAllCounter++; + const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus; + window->FocusIdxAllCounter++; if (allow_keyboard_focus) - FocusIdxTabCounter++; + window->FocusIdxTabCounter++; // Process keyboard input at this point: TAB, Shift-TAB switch focus // We can always TAB out of a widget that doesn't allow tabbing in. - if (tab_stop && FocusIdxAllRequestNext == IM_INT_MAX && FocusIdxTabRequestNext == IM_INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) + if (tab_stop && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) { // Modulo on index will be applied at the end of frame once we've got the total counter of items. - FocusIdxTabRequestNext = FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); + window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); } - if (FocusIdxAllCounter == FocusIdxAllRequestCurrent) + if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent) return true; if (allow_keyboard_focus) - if (FocusIdxTabCounter == FocusIdxTabRequestCurrent) + if (window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent) return true; return false; } -void ImGuiWindow::FocusItemUnregister() +void ImGui::FocusableItemUnregister(ImGuiWindow* window) { - FocusIdxAllCounter--; - FocusIdxTabCounter--; + window->FocusIdxAllCounter--; + window->FocusIdxTabCounter--; } -static inline void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list) +ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y) { - if (!draw_list->commands.empty() && !draw_list->vtx_buffer.empty()) - { - if (draw_list->commands.back().vtx_count == 0) - draw_list->commands.pop_back(); - out_render_list.push_back(draw_list); - GImGui->IO.MetricsVertices += (int)draw_list->vtx_buffer.size(); - } + ImGuiContext& g = *GImGui; + ImVec2 content_max; + if (size.x < 0.0f || size.y < 0.0f) + content_max = g.CurrentWindow->Pos + GetContentRegionMax(); + if (size.x <= 0.0f) + size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x; + if (size.y <= 0.0f) + size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y; + return size; } -static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window) +float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { - AddDrawListToRenderList(out_render_list, window->DrawList); - for (size_t i = 0; i < window->DC.ChildWindows.size(); i++) - { - ImGuiWindow* child = window->DC.ChildWindows[i]; - if (child->Visible) // clipped children may have been marked not Visible - AddWindowToRenderList(out_render_list, child); - } + if (wrap_pos_x < 0.0f) + return 0.0f; + + ImGuiWindow* window = GetCurrentWindowRead(); + if (wrap_pos_x == 0.0f) + wrap_pos_x = GetContentRegionMax().x + window->Pos.x; + else if (wrap_pos_x > 0.0f) + wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space + + return ImMax(wrap_pos_x - pos.x, 1.0f); } //----------------------------------------------------------------------------- void* ImGui::MemAlloc(size_t sz) { + GImGui->IO.MetricsAllocs++; return GImGui->IO.MemAllocFn(sz); } void ImGui::MemFree(void* ptr) { + if (ptr) GImGui->IO.MetricsAllocs--; return GImGui->IO.MemFreeFn(ptr); } - -static ImGuiIniData* FindWindowSettings(const char* name) + +const char* ImGui::GetClipboardText() { - ImGuiState& g = *GImGui; - ImGuiID id = ImHash(name, 0); - for (size_t i = 0; i != g.Settings.size(); i++) - { - ImGuiIniData* ini = g.Settings[i]; - if (ini->ID == id) - return ini; - } - return NULL; + return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn() : ""; } -static ImGuiIniData* AddWindowSettings(const char* name) +void ImGui::SetClipboardText(const char* text) { - ImGuiIniData* ini = (ImGuiIniData*)ImGui::MemAlloc(sizeof(ImGuiIniData)); - new(ini) ImGuiIniData(); - ini->Name = ImStrdup(name); - ini->ID = ImHash(name, 0); - ini->Collapsed = false; - ini->Pos = ImVec2(FLT_MAX,FLT_MAX); - ini->Size = ImVec2(0,0); - GImGui->Settings.push_back(ini); - return ini; + if (GImGui->IO.SetClipboardTextFn) + GImGui->IO.SetClipboardTextFn(text); } -// Zero-tolerance, poor-man .ini parsing -// FIXME: Write something less rubbish -static void LoadSettings() +const char* ImGui::GetVersion() { - ImGuiState& g = *GImGui; - const char* filename = g.IO.IniFilename; - if (!filename) - return; - - char* file_data; - size_t file_size; - if (!ImLoadFileToMemory(filename, "rb", (void**)&file_data, &file_size, 1)) - return; + return IMGUI_VERSION; +} - ImGuiIniData* settings = NULL; - const char* buf_end = file_data + file_size; - for (const char* line_start = file_data; line_start < buf_end; ) - { - const char* line_end = line_start; - while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') - line_end++; - - if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') - { - char name[64]; - ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", line_end-line_start-2, line_start+1); - settings = FindWindowSettings(name); - if (!settings) - settings = AddWindowSettings(name); - } - else if (settings) - { - float x, y; - int i; - if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) - settings->Pos = ImVec2(x, y); - else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) - settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); - else if (sscanf(line_start, "Collapsed=%d", &i) == 1) - settings->Collapsed = (i != 0); - } - - line_start = line_end+1; - } - - ImGui::MemFree(file_data); +// Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself +// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module +ImGuiContext* ImGui::GetCurrentContext() +{ + return GImGui; } -static void SaveSettings() +void ImGui::SetCurrentContext(ImGuiContext* ctx) { - ImGuiState& g = *GImGui; - const char* filename = g.IO.IniFilename; - if (!filename) - return; - - // Gather data from windows that were active during this session - for (size_t i = 0; i != g.Windows.size(); i++) - { - ImGuiWindow* window = g.Windows[i]; - if (window->Flags & ImGuiWindowFlags_NoSavedSettings) - continue; - ImGuiIniData* settings = FindWindowSettings(window->Name); - settings->Pos = window->Pos; - settings->Size = window->SizeFull; - settings->Collapsed = window->Collapsed; - } - - // Write .ini file - // If a window wasn't opened in this session we preserve its settings - FILE* f = fopen(filename, "wt"); - if (!f) - return; - for (size_t i = 0; i != g.Settings.size(); i++) - { - const ImGuiIniData* settings = g.Settings[i]; - if (settings->Pos.x == FLT_MAX) - continue; - const char* name = settings->Name; - if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() - name = p; - fprintf(f, "[%s]\n", name); - fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); - fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); - fprintf(f, "Collapsed=%d\n", settings->Collapsed); - fprintf(f, "\n"); - } - - fclose(f); + GImGui = ctx; } -static void MarkSettingsDirty() +ImGuiContext* ImGui::CreateContext(void* (*malloc_fn)(size_t), void (*free_fn)(void*)) { - ImGuiState& g = *GImGui; - - if (g.SettingsDirtyTimer <= 0.0f) - g.SettingsDirtyTimer = g.IO.IniSavingRate; + if (!malloc_fn) malloc_fn = malloc; + ImGuiContext* ctx = (ImGuiContext*)malloc_fn(sizeof(ImGuiContext)); + IM_PLACEMENT_NEW(ctx) ImGuiContext(); + ctx->IO.MemAllocFn = malloc_fn; + ctx->IO.MemFreeFn = free_fn ? free_fn : free; + return ctx; } -const char* ImGui::GetVersion() +void ImGui::DestroyContext(ImGuiContext* ctx) { - return IMGUI_VERSION; + void (*free_fn)(void*) = ctx->IO.MemFreeFn; + ctx->~ImGuiContext(); + free_fn(ctx); + if (GImGui == ctx) + GImGui = NULL; } -// Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself -// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module -void* ImGui::GetInternalState() +ImGuiIO& ImGui::GetIO() { - return GImGui; + return GImGui->IO; } -size_t ImGui::GetInternalStateSize() +ImGuiStyle& ImGui::GetStyle() { - return sizeof(ImGuiState); + return GImGui->Style; } -void ImGui::SetInternalState(void* state, bool construct) +// Same value as passed to your RenderDrawListsFn() function. valid after Render() and until the next call to NewFrame() +ImDrawData* ImGui::GetDrawData() { - if (construct) - new (state) ImGuiState(); - - GImGui = (ImGuiState*)state; + return GImGui->RenderDrawData.Valid ? &GImGui->RenderDrawData : NULL; } -ImGuiIO& ImGui::GetIO() +float ImGui::GetTime() { - return GImGui->IO; + return GImGui->Time; } -ImGuiStyle& ImGui::GetStyle() +int ImGui::GetFrameCount() { - return GImGui->Style; + return GImGui->FrameCount; } void ImGui::NewFrame() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; // Check user data - IM_ASSERT(g.IO.DeltaTime > 0.0f); + IM_ASSERT(g.IO.DeltaTime >= 0.0f); // Need a positive DeltaTime (zero is tolerated but will cause some timing issues) IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f); - IM_ASSERT(g.IO.RenderDrawListsFn != NULL); // Must be implemented - IM_ASSERT(g.IO.Fonts->Fonts.size() > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(g.IO.Fonts->Fonts.Size > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? + IM_ASSERT(g.Style.CurveTessellationTol > 0.0f); // Invalid style setting if (!g.Initialized) { // Initialize on first frame g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer)); - new(g.LogClipboard) ImGuiTextBuffer(); + IM_PLACEMENT_NEW(g.LogClipboard) ImGuiTextBuffer(); IM_ASSERT(g.Settings.empty()); LoadSettings(); g.Initialized = true; } - SetFont(g.IO.Fonts->Fonts[0]); + SetCurrentFont(g.IO.Fonts->Fonts[0]); g.Time += g.IO.DeltaTime; g.FrameCount += 1; g.Tooltip[0] = '\0'; + g.OverlayDrawList.Clear(); + g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID); + g.OverlayDrawList.PushClipRectFullScreen(); + + // Mark rendering data as invalid to prevent user who may have a handle on it to use it + g.RenderDrawData.Valid = false; + g.RenderDrawData.CmdLists = NULL; + g.RenderDrawData.CmdListsCount = g.RenderDrawData.TotalVtxCount = g.RenderDrawData.TotalIdxCount = 0; // Update inputs state if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) @@ -1894,10 +2125,12 @@ void ImGui::NewFrame() else g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; g.IO.MousePosPrev = g.IO.MousePos; - for (size_t i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) + for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { - g.IO.MouseDownTime[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownTime[i] < 0.0f ? 0.0f : g.IO.MouseDownTime[i] + g.IO.DeltaTime) : -1.0f; - g.IO.MouseClicked[i] = (g.IO.MouseDownTime[i] == 0.0f); + g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f; + g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f; + g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i]; + g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f; g.IO.MouseDoubleClicked[i] = false; if (g.IO.MouseClicked[i]) { @@ -1919,8 +2152,9 @@ void ImGui::NewFrame() g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i])); } } - for (size_t i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) - g.IO.KeysDownTime[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownTime[i] < 0.0f ? 0.0f : g.IO.KeysDownTime[i] + g.IO.DeltaTime) : -1.0f; + memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration)); + for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) + g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f; // Calculate frame-rate for the user, as a purely luxurious feature g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; @@ -1929,13 +2163,43 @@ void ImGui::NewFrame() g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame)); // Clear reference to active widget if the widget isn't alive anymore + g.HoveredIdPreviousFrame = g.HoveredId; g.HoveredId = 0; + g.HoveredIdAllowOverlap = false; if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) - SetActiveId(0); + SetActiveID(0); g.ActiveIdPreviousFrame = g.ActiveId; g.ActiveIdIsAlive = false; - if (!g.ActiveId) + g.ActiveIdIsJustActivated = false; + + // Handle user moving window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows. + if (g.MovedWindowMoveId && g.MovedWindowMoveId == g.ActiveId) + { + KeepAliveID(g.MovedWindowMoveId); + IM_ASSERT(g.MovedWindow && g.MovedWindow->RootWindow); + IM_ASSERT(g.MovedWindow->RootWindow->MoveId == g.MovedWindowMoveId); + if (g.IO.MouseDown[0]) + { + if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoMove)) + { + g.MovedWindow->PosFloat += g.IO.MouseDelta; + if (!(g.MovedWindow->Flags & ImGuiWindowFlags_NoSavedSettings)) + MarkSettingsDirty(); + } + FocusWindow(g.MovedWindow); + } + else + { + SetActiveID(0); + g.MovedWindow = NULL; + g.MovedWindowMoveId = 0; + } + } + else + { g.MovedWindow = NULL; + g.MovedWindowMoveId = 0; + } // Delay saving settings so we don't spam disk too much if (g.SettingsDirtyTimer > 0.0f) @@ -1946,34 +2210,56 @@ void ImGui::NewFrame() } // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow - g.HoveredWindow = FindHoveredWindow(g.IO.MousePos, false); + g.HoveredWindow = g.MovedWindow ? g.MovedWindow : FindHoveredWindow(g.IO.MousePos, false); if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow)) g.HoveredRootWindow = g.HoveredWindow->RootWindow; else - g.HoveredRootWindow = FindHoveredWindow(g.IO.MousePos, true); + g.HoveredRootWindow = g.MovedWindow ? g.MovedWindow->RootWindow : FindHoveredWindow(g.IO.MousePos, true); + + if (ImGuiWindow* modal_window = GetFrontMostModalRootWindow()) + { + g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f); + ImGuiWindow* window = g.HoveredRootWindow; + while (window && window != modal_window) + window = window->ParentWindow; + if (!window) + g.HoveredRootWindow = g.HoveredWindow = NULL; + } + else + { + g.ModalWindowDarkeningRatio = 0.0f; + } // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application. - // When clicking outside of a window we assume the click is owned by the application and won't request capture. + // When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership. int mouse_earliest_button_down = -1; + bool mouse_any_down = false; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { if (g.IO.MouseClicked[i]) - g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL); + g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty()); + mouse_any_down |= g.IO.MouseDown[i]; if (g.IO.MouseDown[i]) if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i]) mouse_earliest_button_down = i; } - bool mouse_owned_by_application = mouse_earliest_button_down != -1 && !g.IO.MouseDownOwned[mouse_earliest_button_down]; - g.IO.WantCaptureMouse = (!mouse_owned_by_application && g.HoveredWindow != NULL) || (g.ActiveId != 0); - g.IO.WantCaptureKeyboard = (g.ActiveId != 0); + bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down]; + if (g.CaptureMouseNextFrame != -1) + g.IO.WantCaptureMouse = (g.CaptureMouseNextFrame != 0); + else + g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (g.ActiveId != 0) || (!g.OpenPopupStack.empty()); + g.IO.WantCaptureKeyboard = (g.CaptureKeyboardNextFrame != -1) ? (g.CaptureKeyboardNextFrame != 0) : (g.ActiveId != 0); + g.IO.WantTextInput = (g.ActiveId != 0 && g.InputTextState.Id == g.ActiveId); g.MouseCursor = ImGuiMouseCursor_Arrow; + g.CaptureMouseNextFrame = g.CaptureKeyboardNextFrame = -1; + g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. - if (mouse_owned_by_application) + if (!mouse_avail_to_imgui) g.HoveredWindow = g.HoveredRootWindow = NULL; // Scale & Scrolling - if (g.HoveredWindow && g.IO.MouseWheel != 0.0f) + if (g.HoveredWindow && g.IO.MouseWheel != 0.0f && !g.HoveredWindow->Collapsed) { ImGuiWindow* window = g.HoveredWindow; if (g.IO.KeyCtrl) @@ -1992,36 +2278,42 @@ void ImGui::NewFrame() window->SizeFull *= scale; } } - else + else if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse)) { // Scroll - if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse)) - { - const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5; - window->NextScrollY -= g.IO.MouseWheel * window->CalcFontSize() * scroll_lines; - } + const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5; + SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * window->CalcFontSize() * scroll_lines); } } // Pressing TAB activate widget focus // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus. - if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Visible && IsKeyPressedMap(ImGuiKey_Tab, false)) - { + if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Active && IsKeyPressedMap(ImGuiKey_Tab, false)) g.FocusedWindow->FocusIdxTabRequestNext = 0; - } // Mark all windows as not visible - for (size_t i = 0; i != g.Windows.size(); i++) + for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; - window->WasVisible = window->Visible; - window->Visible = false; + window->WasActive = window->Active; + window->Active = false; window->Accessed = false; } + // Closing the focused window restore focus to the first active root window in descending z-order + if (g.FocusedWindow && !g.FocusedWindow->WasActive) + for (int i = g.Windows.Size-1; i >= 0; i--) + if (g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow)) + { + FocusWindow(g.Windows[i]); + break; + } + // No window should be open at the beginning of the frame. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack.resize(0); + g.CurrentPopupStack.resize(0); + CloseInactivePopups(); // Create implicit window - we will only render it if the user has added something to it. ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver); @@ -2031,41 +2323,54 @@ void ImGui::NewFrame() // NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations. void ImGui::Shutdown() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; + + // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) + if (g.IO.Fonts) // Testing for NULL to allow user to NULLify in case of running Shutdown() on multiple contexts. Bit hacky. + g.IO.Fonts->Clear(); + + // Cleanup of other data are conditional on actually having used ImGui. if (!g.Initialized) return; SaveSettings(); - for (size_t i = 0; i < g.Windows.size(); i++) + for (int i = 0; i < g.Windows.Size; i++) { g.Windows[i]->~ImGuiWindow(); ImGui::MemFree(g.Windows[i]); } g.Windows.clear(); g.WindowsSortBuffer.clear(); + g.CurrentWindow = NULL; g.CurrentWindowStack.clear(); g.FocusedWindow = NULL; g.HoveredWindow = NULL; g.HoveredRootWindow = NULL; - for (size_t i = 0; i < g.Settings.size(); i++) - { - g.Settings[i]->~ImGuiIniData(); - ImGui::MemFree(g.Settings[i]); - } + g.ActiveIdWindow = NULL; + g.MovedWindow = NULL; + for (int i = 0; i < g.Settings.Size; i++) + ImGui::MemFree(g.Settings[i].Name); g.Settings.clear(); g.ColorModifiers.clear(); g.StyleModifiers.clear(); g.FontStack.clear(); - for (size_t i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + g.OpenPopupStack.clear(); + g.CurrentPopupStack.clear(); + g.SetNextWindowSizeConstraintCallback = NULL; + g.SetNextWindowSizeConstraintCallbackUserData = NULL; + for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) g.RenderDrawLists[i].clear(); - g.MouseCursorDrawList.ClearFreeMemory(); + g.OverlayDrawList.ClearFreeMemory(); g.ColorEditModeStorage.Clear(); if (g.PrivateClipboard) { ImGui::MemFree(g.PrivateClipboard); g.PrivateClipboard = NULL; } + g.InputTextState.Text.clear(); + g.InputTextState.InitialText.clear(); + g.InputTextState.TempTextBuffer.clear(); if (g.LogFile && g.LogFile != stdout) { @@ -2078,11 +2383,131 @@ void ImGui::Shutdown() ImGui::MemFree(g.LogClipboard); } - g.IO.Fonts->Clear(); - g.Initialized = false; } +static ImGuiIniData* FindWindowSettings(const char* name) +{ + ImGuiContext& g = *GImGui; + ImGuiID id = ImHash(name, 0); + for (int i = 0; i != g.Settings.Size; i++) + { + ImGuiIniData* ini = &g.Settings[i]; + if (ini->Id == id) + return ini; + } + return NULL; +} + +static ImGuiIniData* AddWindowSettings(const char* name) +{ + GImGui->Settings.resize(GImGui->Settings.Size + 1); + ImGuiIniData* ini = &GImGui->Settings.back(); + ini->Name = ImStrdup(name); + ini->Id = ImHash(name, 0); + ini->Collapsed = false; + ini->Pos = ImVec2(FLT_MAX,FLT_MAX); + ini->Size = ImVec2(0,0); + return ini; +} + +// Zero-tolerance, poor-man .ini parsing +// FIXME: Write something less rubbish +static void LoadSettings() +{ + ImGuiContext& g = *GImGui; + const char* filename = g.IO.IniFilename; + if (!filename) + return; + + int file_size; + char* file_data = (char*)ImLoadFileToMemory(filename, "rb", &file_size, 1); + if (!file_data) + return; + + ImGuiIniData* settings = NULL; + const char* buf_end = file_data + file_size; + for (const char* line_start = file_data; line_start < buf_end; ) + { + const char* line_end = line_start; + while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') + line_end++; + + if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') + { + char name[64]; + ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", (int)(line_end-line_start-2), line_start+1); + settings = FindWindowSettings(name); + if (!settings) + settings = AddWindowSettings(name); + } + else if (settings) + { + float x, y; + int i; + if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) + settings->Pos = ImVec2(x, y); + else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) + settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); + else if (sscanf(line_start, "Collapsed=%d", &i) == 1) + settings->Collapsed = (i != 0); + } + + line_start = line_end+1; + } + + ImGui::MemFree(file_data); +} + +static void SaveSettings() +{ + ImGuiContext& g = *GImGui; + const char* filename = g.IO.IniFilename; + if (!filename) + return; + + // Gather data from windows that were active during this session + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Flags & ImGuiWindowFlags_NoSavedSettings) + continue; + ImGuiIniData* settings = FindWindowSettings(window->Name); + settings->Pos = window->Pos; + settings->Size = window->SizeFull; + settings->Collapsed = window->Collapsed; + } + + // Write .ini file + // If a window wasn't opened in this session we preserve its settings + FILE* f = fopen(filename, "wt"); + if (!f) + return; + for (int i = 0; i != g.Settings.Size; i++) + { + const ImGuiIniData* settings = &g.Settings[i]; + if (settings->Pos.x == FLT_MAX) + continue; + const char* name = settings->Name; + if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() + name = p; + fprintf(f, "[%s]\n", name); + fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); + fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); + fprintf(f, "Collapsed=%d\n", settings->Collapsed); + fprintf(f, "\n"); + } + + fclose(f); +} + +static void MarkSettingsDirty() +{ + ImGuiContext& g = *GImGui; + if (g.SettingsDirtyTimer <= 0.0f) + g.SettingsDirtyTimer = g.IO.IniSavingRate; +} + // FIXME: Add a more explicit sort order in the window structure. static int ChildWindowComparer(const void* lhs, const void* rhs) { @@ -2094,127 +2519,179 @@ static int ChildWindowComparer(const void* lhs, const void* rhs) return d; if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox)) return d; - return 0; + return (a->IndexWithinParent - b->IndexWithinParent); } static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window) { out_sorted_windows.push_back(window); - if (window->Visible) + if (window->Active) { - const size_t count = window->DC.ChildWindows.size(); + int count = window->DC.ChildWindows.Size; if (count > 1) - qsort(window->DC.ChildWindows.begin(), count, sizeof(ImGuiWindow*), ChildWindowComparer); - for (size_t i = 0; i < count; i++) + qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); + for (int i = 0; i < count; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; - if (child->Visible) + if (child->Active) AddWindowToSortedBuffer(out_sorted_windows, child); } } } -static void PushClipRect(const ImVec4& clip_rect, bool clipped = true) +static void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list) { - ImGuiWindow* window = GetCurrentWindow(); + if (draw_list->CmdBuffer.empty()) + return; + + // Remove trailing command if unused + ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); + if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) + { + draw_list->CmdBuffer.pop_back(); + if (draw_list->CmdBuffer.empty()) + return; + } - ImVec4 cr = clip_rect; - if (clipped && !window->ClipRectStack.empty()) + // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. + IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); + IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); + IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); + + // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = 2 bytes = 64K vertices) + // If this assert triggers because you are drawing lots of stuff manually, A) workaround by calling BeginChild()/EndChild() to put your draw commands in multiple draw lists, B) #define ImDrawIdx to a 'unsigned int' in imconfig.h and render accordingly. + IM_ASSERT((int64_t)draw_list->_VtxCurrentIdx <= ((int64_t)1L << (sizeof(ImDrawIdx)*8))); // Too many vertices in same ImDrawList. See comment above. + + out_render_list.push_back(draw_list); + GImGui->IO.MetricsRenderVertices += draw_list->VtxBuffer.Size; + GImGui->IO.MetricsRenderIndices += draw_list->IdxBuffer.Size; +} + +static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window) +{ + AddDrawListToRenderList(out_render_list, window->DrawList); + for (int i = 0; i < window->DC.ChildWindows.Size; i++) { - // Clip with existing clip rect - const ImVec4 cur_cr = window->ClipRectStack.back(); - cr = ImVec4(ImMax(cr.x, cur_cr.x), ImMax(cr.y, cur_cr.y), ImMin(cr.z, cur_cr.z), ImMin(cr.w, cur_cr.w)); + ImGuiWindow* child = window->DC.ChildWindows[i]; + if (!child->Active) // clipped children may have been marked not active + continue; + if ((child->Flags & ImGuiWindowFlags_Popup) && child->HiddenFrames > 0) + continue; + AddWindowToRenderList(out_render_list, child); } - cr.z = ImMax(cr.x, cr.z); - cr.w = ImMax(cr.y, cr.w); +} - IM_ASSERT(cr.x <= cr.z && cr.y <= cr.w); - window->ClipRectStack.push_back(cr); - window->DrawList->PushClipRect(cr); +// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. +void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); + window->ClipRect = window->DrawList->_ClipRectStack.back(); } -static void PopClipRect() +void ImGui::PopClipRect() { ImGuiWindow* window = GetCurrentWindow(); - window->ClipRectStack.pop_back(); window->DrawList->PopClipRect(); + window->ClipRect = window->DrawList->_ClipRectStack.back(); } -void ImGui::Render() +// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. +void ImGui::EndFrame() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // ImGui::EndFrame() called multiple times, or forgot to call ImGui::NewFrame() again - const bool first_render_of_the_frame = (g.FrameCountRendered != g.FrameCount); - g.FrameCountRendered = g.FrameCount; - - if (first_render_of_the_frame) + // Render tooltip + if (g.Tooltip[0]) { - // Hide implicit window if it hasn't been used - IM_ASSERT(g.CurrentWindowStack.size() == 1); // Mismatched Begin/End - if (g.CurrentWindow && !g.CurrentWindow->Accessed) - g.CurrentWindow->Visible = false; - ImGui::End(); + ImGui::BeginTooltip(); + ImGui::TextUnformatted(g.Tooltip); + ImGui::EndTooltip(); + } + + // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) + if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f) + { + g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y); + g.OsImePosSet = g.OsImePosRequest; + } + + // Hide implicit "Debug" window if it hasn't been used + IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls + if (g.CurrentWindow && !g.CurrentWindow->Accessed) + g.CurrentWindow->Active = false; + ImGui::End(); - if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0]) + // Click to focus window and start moving (after we're done with all our widgets) + if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0]) + { + if (!(g.FocusedWindow && !g.FocusedWindow->WasActive && g.FocusedWindow->Active)) // Unless we just made a popup appear { if (g.HoveredRootWindow != NULL) { - // Select window for move/focus when we're done with all our widgets (we use the root window ID here) - IM_ASSERT(g.MovedWindow == NULL); - g.MovedWindow = g.HoveredWindow; - SetActiveId(g.HoveredRootWindow->MoveID); + FocusWindow(g.HoveredWindow); + if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove)) + { + g.MovedWindow = g.HoveredWindow; + g.MovedWindowMoveId = g.HoveredRootWindow->MoveId; + SetActiveID(g.MovedWindowMoveId, g.HoveredRootWindow); + } } - else if (g.FocusedWindow != NULL) + else if (g.FocusedWindow != NULL && GetFrontMostModalRootWindow() == NULL) { // Clicking on void disable focus FocusWindow(NULL); } } + } - // Sort the window list so that all child windows are after their parent - // We cannot do that on FocusWindow() because childs may not exist yet - g.WindowsSortBuffer.resize(0); - g.WindowsSortBuffer.reserve(g.Windows.size()); - for (size_t i = 0; i != g.Windows.size(); i++) - { - ImGuiWindow* window = g.Windows[i]; - if (window->Flags & ImGuiWindowFlags_ChildWindow) // if a child is visible its parent will add it - if (window->Visible) - continue; - AddWindowToSortedBuffer(g.WindowsSortBuffer, window); - } - IM_ASSERT(g.Windows.size() == g.WindowsSortBuffer.size()); // we done something wrong - g.Windows.swap(g.WindowsSortBuffer); - - // Clear data for next frame - g.IO.MouseWheel = 0.0f; - memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); + // Sort the window list so that all child windows are after their parent + // We cannot do that on FocusWindow() because childs may not exist yet + g.WindowsSortBuffer.resize(0); + g.WindowsSortBuffer.reserve(g.Windows.Size); + for (int i = 0; i != g.Windows.Size; i++) + { + ImGuiWindow* window = g.Windows[i]; + if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it + continue; + AddWindowToSortedBuffer(g.WindowsSortBuffer, window); } + IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong + g.Windows.swap(g.WindowsSortBuffer); + + // Clear Input data for next frame + g.IO.MouseWheel = 0.0f; + memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); + + g.FrameCountEnded = g.FrameCount; +} + +void ImGui::Render() +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() + + if (g.FrameCountEnded != g.FrameCount) + ImGui::EndFrame(); + g.FrameCountRendered = g.FrameCount; // Skip render altogether if alpha is 0.0 - // Note that vertex buffers have been created, so it is best practice that you don't call Begin/End in the first place. + // Note that vertex buffers have been created and are wasted, so it is best practice that you don't create windows in the first place, or consistently respond to Begin() returning false. if (g.Style.Alpha > 0.0f) { - // Render tooltip - if (g.Tooltip[0]) - { - // Use a dummy window to render the tooltip - ImGui::BeginTooltip(); - ImGui::TextUnformatted(g.Tooltip); - ImGui::EndTooltip(); - } - // Gather windows to render - g.IO.MetricsVertices = 0; - for (size_t i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0; + for (int i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) g.RenderDrawLists[i].resize(0); - for (size_t i = 0; i != g.Windows.size(); i++) + for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; - if (window->Visible && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0) + if (window->Active && window->HiddenFrames <= 0 && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0) { - // FIXME: Generalize this with a proper layering system so we can stack. + // FIXME: Generalize this with a proper layering system so e.g. user can draw in specific layers, below text, .. + g.IO.MetricsActiveWindows++; if (window->Flags & ImGuiWindowFlags_Popup) AddWindowToRenderList(g.RenderDrawLists[1], window); else if (window->Flags & ImGuiWindowFlags_Tooltip) @@ -2225,68 +2702,65 @@ void ImGui::Render() } // Flatten layers - size_t n = g.RenderDrawLists[0].size(); - size_t flattened_size = n; - for (size_t i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) - flattened_size += g.RenderDrawLists[i].size(); + int n = g.RenderDrawLists[0].Size; + int flattened_size = n; + for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + flattened_size += g.RenderDrawLists[i].Size; g.RenderDrawLists[0].resize(flattened_size); - for (size_t i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) + for (int i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) { ImVector<ImDrawList*>& layer = g.RenderDrawLists[i]; - if (!layer.empty()) - { - memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.size() * sizeof(ImDrawList*)); - n += layer.size(); - } + if (layer.empty()) + continue; + memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.Size * sizeof(ImDrawList*)); + n += layer.Size; } + // Draw software mouse cursor if requested if (g.IO.MouseDrawCursor) { const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor]; - const ImVec2 pos = g.IO.MousePos - cursor_data.Offset; + const ImVec2 pos = g.IO.MousePos - cursor_data.HotOffset; const ImVec2 size = cursor_data.Size; const ImTextureID tex_id = g.IO.Fonts->TexID; - g.MouseCursorDrawList.Clear(); - g.MouseCursorDrawList.PushTextureID(tex_id); - g.MouseCursorDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow - g.MouseCursorDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow - g.MouseCursorDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0xFF000000); // Black border - g.MouseCursorDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], 0xFFFFFFFF); // White fill - g.MouseCursorDrawList.PopTextureID(); - AddDrawListToRenderList(g.RenderDrawLists[0], &g.MouseCursorDrawList); + g.OverlayDrawList.PushTextureID(tex_id); + g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow + g.OverlayDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,48)); // Shadow + g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], IM_COL32(0,0,0,255)); // Black border + g.OverlayDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], IM_COL32(255,255,255,255)); // White fill + g.OverlayDrawList.PopTextureID(); } + if (!g.OverlayDrawList.VtxBuffer.empty()) + AddDrawListToRenderList(g.RenderDrawLists[0], &g.OverlayDrawList); - // Render - if (!g.RenderDrawLists[0].empty()) - g.IO.RenderDrawListsFn(&g.RenderDrawLists[0][0], (int)g.RenderDrawLists[0].size()); + // Setup draw data + g.RenderDrawData.Valid = true; + g.RenderDrawData.CmdLists = (g.RenderDrawLists[0].Size > 0) ? &g.RenderDrawLists[0][0] : NULL; + g.RenderDrawData.CmdListsCount = g.RenderDrawLists[0].Size; + g.RenderDrawData.TotalVtxCount = g.IO.MetricsRenderVertices; + g.RenderDrawData.TotalIdxCount = g.IO.MetricsRenderIndices; + + // Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData() + if (g.RenderDrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) + g.IO.RenderDrawListsFn(&g.RenderDrawData); } } -// Find the optional ## from which we stop displaying text. -static const char* FindTextDisplayEnd(const char* text, const char* text_end = NULL) +const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) { const char* text_display_end = text; if (!text_end) text_end = (const char*)-1; - ImGuiState& g = *GImGui; - if (g.DisableHideTextAfterDoubleHash > 0) - { - while (text_display_end < text_end && *text_display_end != '\0') - text_display_end++; - } - else - { - while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) - text_display_end++; - } + while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) + text_display_end++; return text_display_end; } // Pass text data straight to log (without being displayed) void ImGui::LogText(const char* fmt, ...) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; @@ -2305,13 +2779,13 @@ void ImGui::LogText(const char* fmt, ...) // Internal version that takes a position to decide on newline placement and pad items according to their depth. // We split text into individual lines to add current tree level padding -static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end) +static void LogRenderedText(const ImVec2& ref_pos, const char* text, const char* text_end) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = ImGui::GetCurrentWindowRead(); if (!text_end) - text_end = FindTextDisplayEnd(text, text_end); + text_end = ImGui::FindRenderedTextEnd(text, text_end); const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1; window->DC.LogLinePosY = ref_pos.y; @@ -2343,7 +2817,7 @@ static void LogText(const ImVec2& ref_pos, const char* text, const char* text_en { const int char_count = (int)(line_end - text_remaining); if (log_new_line || !is_first_line) - ImGui::LogText(STR_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining); + ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining); else ImGui::LogText(" %.*s", char_count, text_remaining); } @@ -2354,33 +2828,18 @@ static void LogText(const ImVec2& ref_pos, const char* text, const char* text_en } } -static float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) -{ - if (wrap_pos_x < 0.0f) - return 0.0f; - - ImGuiWindow* window = GetCurrentWindow(); - if (wrap_pos_x == 0.0f) - wrap_pos_x = ImGui::GetContentRegionMax().x; - if (wrap_pos_x > 0.0f) - wrap_pos_x += window->Pos.x; // wrap_pos_x is provided is window local space - - const float wrap_width = wrap_pos_x > 0.0f ? ImMax(wrap_pos_x - pos.x, 0.00001f) : 0.0f; - return wrap_width; -} - // Internal ImGui functions to render text // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() -static void RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) +void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Hide anything after a '##' string const char* text_display_end; if (hide_text_after_hash) { - text_display_end = FindTextDisplayEnd(text, text_end); + text_display_end = FindRenderedTextEnd(text, text_end); } else { @@ -2392,18 +2851,15 @@ static void RenderText(ImVec2 pos, const char* text, const char* text_end, bool const int text_len = (int)(text_display_end - text); if (text_len > 0) { - // Render - window->DrawList->AddText(g.Font, g.FontSize, pos, window->Color(ImGuiCol_Text), text, text_display_end); - - // Log as text + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); if (g.LogEnabled) - LogText(pos, text, text_display_end); + LogRenderedText(pos, text, text_display_end); } } -static void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) +void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (!text_end) @@ -2412,57 +2868,70 @@ static void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end const int text_len = (int)(text_end - text); if (text_len > 0) { - // Render - window->DrawList->AddText(g.Font, g.FontSize, pos, window->Color(ImGuiCol_Text), text, text_end, wrap_width); - - // Log as text + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); if (g.LogEnabled) - LogText(pos, text, text_end); + LogRenderedText(pos, text, text_end); } } -static void RenderTextClipped(ImVec2 pos, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& clip_max) +// Default clip_rect uses (pos_min,pos_max) +// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) +void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - // Hide anything after a '##' string - const char* text_display_end = FindTextDisplayEnd(text, text_end); + const char* text_display_end = FindRenderedTextEnd(text, text_end); const int text_len = (int)(text_display_end - text); - if (text_len > 0) - { - const ImVec2 text_size = text_size_if_known ? *text_size_if_known : ImGui::CalcTextSize(text, text_display_end, false, 0.0f); + if (text_len == 0) + return; + + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); - // Perform CPU side clipping for single clipped element to avoid using scissor state - const bool need_clipping = (pos.x + text_size.x >= clip_max.x) || (pos.y + text_size.y >= clip_max.y); + // Perform CPU side clipping for single clipped element to avoid using scissor state + ImVec2 pos = pos_min; + const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); - // Render - window->DrawList->AddText(g.Font, g.FontSize, pos, window->Color(ImGuiCol_Text), text, text_display_end, 0.0f, need_clipping ? &clip_max : NULL); + const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; + const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; + bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); + if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min + need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); - // Log as text - if (g.LogEnabled) - LogText(pos, text, text_display_end); + // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. + if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); + if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); + + // Render + if (need_clipping) + { + ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); + } + else + { + window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); } + if (g.LogEnabled) + LogRenderedText(pos, text, text_display_end); } // Render a rectangle shaped with optional rounding and borders -static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) +void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); if (border && (window->Flags & ImGuiWindowFlags_ShowBorders)) { - // FIXME: This is the best I've found that works on multiple renderer/back ends. Bit dodgy. - window->DrawList->AddRect(p_min+ImVec2(1.5f,1.5f), p_max+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), rounding); - window->DrawList->AddRect(p_min+ImVec2(0.5f,0.5f), p_max+ImVec2(0,0), window->Color(ImGuiCol_Border), rounding); + window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding); + window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding); } } // Render a triangle to denote expanded/collapsed state -static void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale, bool shadow) +void ImGui::RenderCollapseTriangle(ImVec2 p_min, bool is_open, float scale, bool shadow) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const float h = g.FontSize * 1.00f; @@ -2470,7 +2939,7 @@ static void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale, bool ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale); ImVec2 a, b, c; - if (opened) + if (is_open) { center.y -= r*0.25f; a = center + ImVec2(0,1)*r; @@ -2483,53 +2952,74 @@ static void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale, bool b = center + ImVec2(-0.500f,0.866f)*r; c = center + ImVec2(-0.500f,-0.866f)*r; } - + if (shadow && (window->Flags & ImGuiWindowFlags_ShowBorders) != 0) - window->DrawList->AddTriangleFilled(a+ImVec2(2,2), b+ImVec2(2,2), c+ImVec2(2,2), window->Color(ImGuiCol_BorderShadow)); - window->DrawList->AddTriangleFilled(a, b, c, window->Color(ImGuiCol_Text)); + window->DrawList->AddTriangleFilled(a+ImVec2(2,2), b+ImVec2(2,2), c+ImVec2(2,2), GetColorU32(ImGuiCol_BorderShadow)); + window->DrawList->AddTriangleFilled(a, b, c, GetColorU32(ImGuiCol_Text)); +} + +void ImGui::RenderBullet(ImVec2 pos) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8); +} + +void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + ImVec2 a, b, c; + float start_x = (float)(int)(g.FontSize * 0.307f + 0.5f); + float rem_third = (float)(int)((g.FontSize - start_x) / 3.0f); + a.x = pos.x + 0.5f + start_x; + b.x = a.x + rem_third; + c.x = a.x + rem_third * 3.0f; + b.y = pos.y - 1.0f + (float)(int)(g.Font->Ascent * (g.FontSize / g.Font->FontSize) + 0.5f) + (float)(int)(g.Font->DisplayOffset.y); + a.y = b.y - rem_third; + c.y = b.y - rem_third * 2.0f; + + window->DrawList->PathLineTo(a); + window->DrawList->PathLineTo(b); + window->DrawList->PathLineTo(c); + window->DrawList->PathStroke(col, false); } // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; const char* text_display_end; if (hide_text_after_double_hash) - text_display_end = FindTextDisplayEnd(text, text_end); // Hide anything after a '##' string + text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string else text_display_end = text_end; ImFont* font = g.Font; const float font_size = g.FontSize; + if (text == text_display_end) + return ImVec2(0.0f, font_size); ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field) - const float font_scale = font_size / font->FontSize; + const float font_scale = font_size / font->FontSize; const float character_spacing_x = 1.0f * font_scale; if (text_size.x > 0.0f) text_size.x -= character_spacing_x; + text_size.x = (float)(int)(text_size.x + 0.95f); return text_size; } -// Helper to calculate coarse clipping of large list of evenly sized items. -// If you are displaying thousands of items and you have a random access to the list, you can perform clipping yourself to save on CPU. -// { -// float item_height = ImGui::GetTextLineHeightWithSpacing(); -// int display_start, display_end; -// ImGui::CalcListClipping(count, item_height, &display_start, &display_end); // calculate how many to clip/display -// ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (display_start) * item_height); // advance cursor -// for (int i = display_start; i < display_end; i++) // display only visible items -// // TODO: display visible item -// ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (count - display_end) * item_height); // advance cursor -// } +// Helper to calculate coarse clipping of large list of evenly sized items. +// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. +// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); if (g.LogEnabled) { // If logging is active, do not perform any clipping @@ -2537,35 +3027,38 @@ void ImGui::CalcListClipping(int items_count, float items_height, int* out_items *out_items_display_end = items_count; return; } + if (window->SkipItems) + { + *out_items_display_start = *out_items_display_end = 0; + return; + } const ImVec2 pos = window->DC.CursorPos; - const ImVec4 clip_rect = window->ClipRectStack.back(); - const float clip_y1 = clip_rect.y; - const float clip_y2 = clip_rect.w; - - int start = (int)((clip_y1 - pos.y) / items_height); - int end = (int)((clip_y2 - pos.y) / items_height); + int start = (int)((window->ClipRect.Min.y - pos.y) / items_height); + int end = (int)((window->ClipRect.Max.y - pos.y) / items_height); start = ImClamp(start, 0, items_count); end = ImClamp(end + 1, start, items_count); - *out_items_display_start = start; *out_items_display_end = end; } // Find window given position, search front-to-back +// FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected. static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) { - ImGuiState& g = *GImGui; - for (int i = (int)g.Windows.size()-1; i >= 0; i--) + ImGuiContext& g = *GImGui; + for (int i = g.Windows.Size-1; i >= 0; i--) { - ImGuiWindow* window = g.Windows[(size_t)i]; - if (!window->Visible) + ImGuiWindow* window = g.Windows[i]; + if (!window->Active) + continue; + if (window->Flags & ImGuiWindowFlags_NoInputs) continue; if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0) continue; // Using the clipped AABB so a child window will typically be clipped by its parent. - ImRect bb(window->ClippedRect.Min - g.Style.TouchExtraPadding, window->ClippedRect.Max + g.Style.TouchExtraPadding); + ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding); if (bb.Contains(pos)) return window; } @@ -2575,39 +3068,30 @@ static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) // Test if mouse cursor is hovering given rectangle // NB- Rectangle is clipped by our current clip setting // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) -static bool IsMouseHoveringRect(const ImRect& rect) +bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); // Clip - ImRect rect_clipped = rect; - if (!window->ClipRectStack.empty()) - { - const ImVec4 clip_rect = window->ClipRectStack.back(); - rect_clipped.Clip(ImRect(ImVec2(clip_rect.x, clip_rect.y), ImVec2(clip_rect.z, clip_rect.w))); - } + ImRect rect_clipped(r_min, r_max); + if (clip) + rect_clipped.Clip(window->ClipRect); // Expand for touch input const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); return rect_for_touch.Contains(g.IO.MousePos); } -bool ImGui::IsMouseHoveringRect(const ImVec2& rect_min, const ImVec2& rect_max) -{ - return IsMouseHoveringRect(ImRect(rect_min, rect_max)); -} - bool ImGui::IsMouseHoveringWindow() { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - return g.HoveredWindow == window; + ImGuiContext& g = *GImGui; + return g.HoveredWindow == g.CurrentWindow; } bool ImGui::IsMouseHoveringAnyWindow() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; return g.HoveredWindow != NULL; } @@ -2618,58 +3102,96 @@ bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos) static bool IsKeyPressedMap(ImGuiKey key, bool repeat) { - ImGuiState& g = *GImGui; - const int key_index = g.IO.KeyMap[key]; + const int key_index = GImGui->IO.KeyMap[key]; return ImGui::IsKeyPressed(key_index, repeat); } +int ImGui::GetKeyIndex(ImGuiKey key) +{ + IM_ASSERT(key >= 0 && key < ImGuiKey_COUNT); + return GImGui->IO.KeyMap[key]; +} + +bool ImGui::IsKeyDown(int key_index) +{ + if (key_index < 0) return false; + IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); + return GImGui->IO.KeysDown[key_index]; +} + bool ImGui::IsKeyPressed(int key_index, bool repeat) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; + if (key_index < 0) return false; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); - const float t = g.IO.KeysDownTime[key_index]; + const float t = g.IO.KeysDownDuration[key_index]; if (t == 0.0f) return true; - // FIXME: Repeat rate should be provided elsewhere? - const float KEY_REPEAT_DELAY = 0.250f; - const float KEY_REPEAT_RATE = 0.020f; - if (repeat && t > KEY_REPEAT_DELAY) - if ((fmodf(t - KEY_REPEAT_DELAY, KEY_REPEAT_RATE) > KEY_REPEAT_RATE*0.5f) != (fmodf(t - KEY_REPEAT_DELAY - g.IO.DeltaTime, KEY_REPEAT_RATE) > KEY_REPEAT_RATE*0.5f)) + if (repeat && t > g.IO.KeyRepeatDelay) + { + float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; + if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) return true; + } + return false; +} +bool ImGui::IsKeyReleased(int key_index) +{ + ImGuiContext& g = *GImGui; + if (key_index < 0) return false; + IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); + if (g.IO.KeysDownDurationPrev[key_index] >= 0.0f && !g.IO.KeysDown[key_index]) + return true; return false; } +bool ImGui::IsMouseDown(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseDown[button]; +} + bool ImGui::IsMouseClicked(int button, bool repeat) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); - const float t = g.IO.MouseDownTime[button]; + const float t = g.IO.MouseDownDuration[button]; if (t == 0.0f) return true; - // FIXME: Repeat rate should be provided elsewhere? - const float MOUSE_REPEAT_DELAY = 0.250f; - const float MOUSE_REPEAT_RATE = 0.020f; - if (repeat && t > MOUSE_REPEAT_DELAY) - if ((fmodf(t - MOUSE_REPEAT_DELAY, MOUSE_REPEAT_RATE) > MOUSE_REPEAT_RATE*0.5f) != (fmodf(t - MOUSE_REPEAT_DELAY - g.IO.DeltaTime, MOUSE_REPEAT_RATE) > MOUSE_REPEAT_RATE*0.5f)) + if (repeat && t > g.IO.KeyRepeatDelay) + { + float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate; + if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f)) return true; + } return false; } +bool ImGui::IsMouseReleased(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + return g.IO.MouseReleased[button]; +} + bool ImGui::IsMouseDoubleClicked(int button) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDoubleClicked[button]; } bool ImGui::IsMouseDragging(int button, float lock_threshold) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + if (!g.IO.MouseDown[button]) + return false; if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; @@ -2680,9 +3202,18 @@ ImVec2 ImGui::GetMousePos() return GImGui->IO.MousePos; } +// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! +ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() +{ + ImGuiContext& g = *GImGui; + if (g.CurrentPopupStack.Size > 0) + return g.OpenPopupStack[g.CurrentPopupStack.Size-1].MousePosOnOpen; + return g.IO.MousePos; +} + ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; @@ -2692,6 +3223,14 @@ ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) return ImVec2(0.0f, 0.0f); } +void ImGui::ResetMouseDragDelta(int button) +{ + ImGuiContext& g = *GImGui; + IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); + // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr + g.IO.MouseClickedPos[button] = g.IO.MousePos; +} + ImGuiMouseCursor ImGui::GetMouseCursor() { return GImGui->MouseCursor; @@ -2702,56 +3241,92 @@ void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) GImGui->MouseCursor = cursor_type; } +void ImGui::CaptureKeyboardFromApp(bool capture) +{ + GImGui->CaptureKeyboardNextFrame = capture ? 1 : 0; +} + +void ImGui::CaptureMouseFromApp(bool capture) +{ + GImGui->CaptureMouseNextFrame = capture ? 1 : 0; +} + bool ImGui::IsItemHovered() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemHoveredAndUsable; } bool ImGui::IsItemHoveredRect() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemHoveredRect; } bool ImGui::IsItemActive() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (g.ActiveId) { - ImGuiWindow* window = GetCurrentWindow(); - return g.ActiveId == window->DC.LastItemID; + ImGuiWindow* window = GetCurrentWindowRead(); + return g.ActiveId == window->DC.LastItemId; } return false; } +bool ImGui::IsItemClicked(int mouse_button) +{ + return IsMouseClicked(mouse_button) && IsItemHovered(); +} + +bool ImGui::IsAnyItemHovered() +{ + return GImGui->HoveredId != 0 || GImGui->HoveredIdPreviousFrame != 0; +} + bool ImGui::IsAnyItemActive() { - ImGuiState& g = *GImGui; - return g.ActiveId != 0; + return GImGui->ActiveId != 0; +} + +bool ImGui::IsItemVisible() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + ImRect r(window->ClipRect); + return r.Overlaps(window->DC.LastItemRect); +} + +// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. +void ImGui::SetItemAllowOverlap() +{ + ImGuiContext& g = *GImGui; + if (g.HoveredId == g.CurrentWindow->DC.LastItemId) + g.HoveredIdAllowOverlap = true; + if (g.ActiveId == g.CurrentWindow->DC.LastItemId) + g.ActiveIdAllowOverlap = true; } ImVec2 ImGui::GetItemRectMin() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Min; } ImVec2 ImGui::GetItemRectMax() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Max; } ImVec2 ImGui::GetItemRectSize() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.GetSize(); } ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); ImRect rect = window->DC.LastItemRect; rect.Expand(outward); return rect.GetClosestPoint(pos, on_edge); @@ -2760,7 +3335,7 @@ ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float ou // Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value. void ImGui::SetTooltipV(const char* fmt, va_list args) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args); } @@ -2772,66 +3347,258 @@ void ImGui::SetTooltip(const char* fmt, ...) va_end(args); } -float ImGui::GetTime() -{ - return GImGui->Time; -} - -int ImGui::GetFrameCount() +static ImRect GetVisibleRect() { - return GImGui->FrameCount; + ImGuiContext& g = *GImGui; + if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) + return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax); + return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); } void ImGui::BeginTooltip() { - ImGuiState& g = *GImGui; ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; - ImGui::Begin("##Tooltip", NULL, ImVec2(0,0), g.Style.Colors[ImGuiCol_TooltipBg].w, flags); + ImGui::Begin("##Tooltip", NULL, flags); } void ImGui::EndTooltip() { - IM_ASSERT(GetCurrentWindow()->Flags & ImGuiWindowFlags_Tooltip); + IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls ImGui::End(); } -void ImGui::BeginPopup(bool* p_opened) +static bool IsPopupOpen(ImGuiID id) +{ + ImGuiContext& g = *GImGui; + return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id; +} + +// Mark popup as open (toggle toward open state). +// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. +// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). +// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) +void ImGui::OpenPopupEx(const char* str_id, bool reopen_existing) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + ImGuiID id = window->GetID(str_id); + int current_stack_size = g.CurrentPopupStack.Size; + ImGuiPopupRef popup_ref = ImGuiPopupRef(id, window, window->GetID("##menus"), g.IO.MousePos); // Tagged as new ref because constructor sets Window to NULL (we are passing the ParentWindow info here) + if (g.OpenPopupStack.Size < current_stack_size + 1) + g.OpenPopupStack.push_back(popup_ref); + else if (reopen_existing || g.OpenPopupStack[current_stack_size].PopupId != id) + { + g.OpenPopupStack.resize(current_stack_size+1); + g.OpenPopupStack[current_stack_size] = popup_ref; + } +} + +void ImGui::OpenPopup(const char* str_id) +{ + ImGui::OpenPopupEx(str_id, false); +} + +static void CloseInactivePopups() +{ + ImGuiContext& g = *GImGui; + if (g.OpenPopupStack.empty()) + return; + + // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. + // Don't close our own child popup windows + int n = 0; + if (g.FocusedWindow) + { + for (n = 0; n < g.OpenPopupStack.Size; n++) + { + ImGuiPopupRef& popup = g.OpenPopupStack[n]; + if (!popup.Window) + continue; + IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); + if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) + continue; + + bool has_focus = false; + for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++) + has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == g.FocusedWindow->RootWindow); + if (!has_focus) + break; + } + } + if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a useful breakpoint on the line below + g.OpenPopupStack.resize(n); +} + +static ImGuiWindow* GetFrontMostModalRootWindow() +{ + ImGuiContext& g = *GImGui; + for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) + if (ImGuiWindow* front_most_popup = g.OpenPopupStack.Data[n].Window) + if (front_most_popup->Flags & ImGuiWindowFlags_Modal) + return front_most_popup; + return NULL; +} + +static void ClosePopupToLevel(int remaining) +{ + ImGuiContext& g = *GImGui; + if (remaining > 0) + ImGui::FocusWindow(g.OpenPopupStack[remaining-1].Window); + else + ImGui::FocusWindow(g.OpenPopupStack[0].ParentWindow); + g.OpenPopupStack.resize(remaining); +} + +static void ClosePopup(ImGuiID id) +{ + if (!IsPopupOpen(id)) + return; + ImGuiContext& g = *GImGui; + ClosePopupToLevel(g.OpenPopupStack.Size - 1); +} + +// Close the popup we have begin-ed into. +void ImGui::CloseCurrentPopup() +{ + ImGuiContext& g = *GImGui; + int popup_idx = g.CurrentPopupStack.Size - 1; + if (popup_idx < 0 || popup_idx > g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId) + return; + while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu)) + popup_idx--; + ClosePopupToLevel(popup_idx); +} + +static inline void ClearSetNextWindowData() +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = 0; + g.SetNextWindowSizeConstraint = g.SetNextWindowFocus = false; +} + +static bool BeginPopupEx(const char* str_id, ImGuiWindowFlags extra_flags) { - IM_ASSERT(p_opened != NULL); // Must provide a bool at the moment + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = window->GetID(str_id); + if (!IsPopupOpen(id)) + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); - ImGuiWindowFlags flags = ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; - ImGui::Begin("##Popup", p_opened, flags); + ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; + + char name[32]; + if (flags & ImGuiWindowFlags_ChildMenu) + ImFormatString(name, 20, "##menu_%d", g.CurrentPopupStack.Size); // Recycle windows based on depth + else + ImFormatString(name, 20, "##popup_%08x", id); // Not recycling, so we can close/open during the same frame + + bool is_open = ImGui::Begin(name, NULL, flags); + if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) + g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders; + if (!is_open) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + ImGui::EndPopup(); + + return is_open; +} + +bool ImGui::BeginPopup(const char* str_id) +{ + if (GImGui->OpenPopupStack.Size <= GImGui->CurrentPopupStack.Size) // Early out for performance + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } + return BeginPopupEx(str_id, ImGuiWindowFlags_ShowBorders); +} + +bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags extra_flags) +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + const ImGuiID id = window->GetID(name); + if (!IsPopupOpen(id)) + { + ClearSetNextWindowData(); // We behave like Begin() and need to consume those values + return false; + } + + ImGuiWindowFlags flags = extra_flags|ImGuiWindowFlags_Popup|ImGuiWindowFlags_Modal|ImGuiWindowFlags_NoCollapse|ImGuiWindowFlags_NoSavedSettings; + bool is_open = ImGui::Begin(name, p_open, flags); + if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + { + ImGui::EndPopup(); + if (is_open) + ClosePopup(id); + return false; + } + + return is_open; } void ImGui::EndPopup() { - IM_ASSERT(GetCurrentWindow()->Flags & ImGuiWindowFlags_Popup); + ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls + IM_ASSERT(GImGui->CurrentPopupStack.Size > 0); ImGui::End(); - ImGui::PopStyleVar(); + if (!(window->Flags & ImGuiWindowFlags_Modal)) + ImGui::PopStyleVar(); +} + +// This is a helper to handle the most simple case of associating one named popup to one given widget. +// 1. If you have many possible popups (for different "instances" of a same widget, or for wholly different widgets), you may be better off handling +// this yourself so you can store data relative to the widget that opened the popup instead of choosing different popup identifiers. +// 2. If you want right-clicking on the same item to reopen the popup at new location, use the same code replacing IsItemHovered() with IsItemHoveredRect() +// and passing true to the OpenPopupEx(). +// Because: hovering an item in a window below the popup won't normally trigger is hovering behavior/coloring. The pattern of ignoring the fact that +// the item isn't interactable (because it is blocked by the active popup) may useful in some situation when e.g. large canvas as one item, content of menu +// driven by click position. +bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) +{ + if (IsItemHovered() && IsMouseClicked(mouse_button)) + OpenPopupEx(str_id, false); + return BeginPopup(str_id); +} + +bool ImGui::BeginPopupContextWindow(bool also_over_items, const char* str_id, int mouse_button) +{ + if (!str_id) str_id = "window_context_menu"; + if (IsMouseHoveringWindow() && IsMouseClicked(mouse_button)) + if (also_over_items || !IsAnyItemHovered()) + OpenPopupEx(str_id, true); + return BeginPopup(str_id); +} + +bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) +{ + if (!str_id) str_id = "void_context_menu"; + if (!IsMouseHoveringAnyWindow() && IsMouseClicked(mouse_button)) + OpenPopupEx(str_id, true); + return BeginPopup(str_id); } bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; - ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; - - const ImVec2 content_max = window->Pos + ImGui::GetContentRegionMax(); - const ImVec2 cursor_pos = window->Pos + ImGui::GetCursorPos(); - ImVec2 size = size_arg; + const ImVec2 content_avail = GetContentRegionAvail(); + ImVec2 size = ImFloor(size_arg); if (size.x <= 0.0f) { if (size.x == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitX; - size.x = ImMax(content_max.x - cursor_pos.x, g.Style.WindowMinSize.x) - fabsf(size.x); + size.x = ImMax(content_avail.x, 4.0f) - fabsf(size.x); // Arbitrary minimum zero-ish child size of 4.0f (0.0f causing too much issues) } if (size.y <= 0.0f) { if (size.y == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitY; - size.y = ImMax(content_max.y - cursor_pos.y, g.Style.WindowMinSize.y) - fabsf(size.y); + size.y = ImMax(content_avail.y, 4.0f) - fabsf(size.y); } if (border) flags |= ImGuiWindowFlags_ShowBorders; @@ -2840,11 +3607,10 @@ bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, char title[256]; ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s", window->Name, str_id); - const float alpha = 1.0f; - bool ret = ImGui::Begin(title, NULL, size, alpha, flags); + bool ret = ImGui::Begin(title, NULL, size, -1.0f, flags); if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) - g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders; + GetCurrentWindow()->Flags &= ~ImGuiWindowFlags_ShowBorders; return ret; } @@ -2852,7 +3618,7 @@ bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, bool ImGui::BeginChild(ImGuiID id, const ImVec2& size, bool border, ImGuiWindowFlags extra_flags) { char str_id[32]; - ImFormatString(str_id, IM_ARRAYSIZE(str_id), "child_%x", id); + ImFormatString(str_id, IM_ARRAYSIZE(str_id), "child_%08x", id); bool ret = ImGui::BeginChild(str_id, size, border, extra_flags); return ret; } @@ -2861,21 +3627,20 @@ void ImGui::EndChild() { ImGuiWindow* window = GetCurrentWindow(); - IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); - if (window->Flags & ImGuiWindowFlags_ComboBox) + IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss + if ((window->Flags & ImGuiWindowFlags_ComboBox) || window->BeginCount > 1) { ImGui::End(); } else { // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting. - ImGuiState& g = *GImGui; - ImVec2 sz = ImGui::GetWindowSize(); - if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) - sz.x = ImMax(g.Style.WindowMinSize.x, sz.x - g.Style.AutoFitPadding.x); + ImVec2 sz = GetWindowSize(); + if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f + sz.x = ImMax(4.0f, sz.x); if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY) - sz.y = ImMax(g.Style.WindowMinSize.y, sz.y - g.Style.AutoFitPadding.y); - + sz.y = ImMax(4.0f, sz.y); + ImGui::End(); window = GetCurrentWindow(); @@ -2886,46 +3651,90 @@ void ImGui::EndChild() } // Helper to create a child window / scrolling region that looks like a normal widget frame. -void ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size) +bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]); ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding); - ImGui::BeginChild(id, size); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); + return ImGui::BeginChild(id, size, (g.CurrentWindow->Flags & ImGuiWindowFlags_ShowBorders) ? true : false, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); } void ImGui::EndChildFrame() { ImGui::EndChild(); - ImGui::PopStyleVar(); + ImGui::PopStyleVar(2); ImGui::PopStyleColor(); } -static ImGuiWindow* FindWindowByName(const char* name) +// Save and compare stack sizes on Begin()/End() to detect usage errors +static void CheckStacksSize(ImGuiWindow* window, bool write) { - // FIXME-OPT: Store sorted hashes -> pointers. - ImGuiState& g = *GImGui; - ImGuiID id = ImHash(name, 0); - for (size_t i = 0; i < g.Windows.size(); i++) - if (g.Windows[i]->ID == id) - return g.Windows[i]; - return NULL; + // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) + ImGuiContext& g = *GImGui; + int* p_backup = &window->DC.StackSizesBackup[0]; + { int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID Mismatch!"); p_backup++; } // User forgot PopID() + { int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // User forgot EndGroup() + { int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++; }// User forgot EndPopup()/EndMenu() + { int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // User forgot PopStyleColor() + { int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // User forgot PopStyleVar() + { int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // User forgot PopFont() + IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); } -static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) +static ImVec2 FindBestPopupWindowPos(const ImVec2& base_pos, const ImVec2& size, int* last_dir, const ImRect& r_inner) { - ImGuiState& g = *GImGui; + const ImGuiStyle& style = GImGui->Style; - // Create window the first time - ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); - new(window) ImGuiWindow(name); - window->Flags = flags; + // Clamp into visible area while not overlapping the cursor. Safety padding is optional if our popup size won't fit without it. + ImVec2 safe_padding = style.DisplaySafeAreaPadding; + ImRect r_outer(GetVisibleRect()); + r_outer.Reduce(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? safe_padding.y : 0.0f)); + ImVec2 base_pos_clamped = ImClamp(base_pos, r_outer.Min, r_outer.Max - size); - if (flags & ImGuiWindowFlags_NoSavedSettings) + for (int n = (*last_dir != -1) ? -1 : 0; n < 4; n++) // Last, Right, down, up, left. (Favor last used direction). { - // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. - window->Size = window->SizeFull = size; + const int dir = (n == -1) ? *last_dir : n; + ImRect rect(dir == 0 ? r_inner.Max.x : r_outer.Min.x, dir == 1 ? r_inner.Max.y : r_outer.Min.y, dir == 3 ? r_inner.Min.x : r_outer.Max.x, dir == 2 ? r_inner.Min.y : r_outer.Max.y); + if (rect.GetWidth() < size.x || rect.GetHeight() < size.y) + continue; + *last_dir = dir; + return ImVec2(dir == 0 ? r_inner.Max.x : dir == 3 ? r_inner.Min.x - size.x : base_pos_clamped.x, dir == 1 ? r_inner.Max.y : dir == 2 ? r_inner.Min.y - size.y : base_pos_clamped.y); + } + + // Fallback, try to keep within display + *last_dir = -1; + ImVec2 pos = base_pos; + pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); + pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); + return pos; +} + +ImGuiWindow* ImGui::FindWindowByName(const char* name) +{ + // FIXME-OPT: Store sorted hashes -> pointers so we can do a bissection in a contiguous block + ImGuiContext& g = *GImGui; + ImGuiID id = ImHash(name, 0); + for (int i = 0; i < g.Windows.Size; i++) + if (g.Windows[i]->ID == id) + return g.Windows[i]; + return NULL; +} + +static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) +{ + ImGuiContext& g = *GImGui; + + // Create window the first time + ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); + IM_PLACEMENT_NEW(window) ImGuiWindow(name); + window->Flags = flags; + + if (flags & ImGuiWindowFlags_NoSavedSettings) + { + // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. + window->Size = window->SizeFull = size; } else { @@ -2960,39 +3769,74 @@ static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFl if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { - window->AutoFitFrames = 2; + window->AutoFitFramesX = window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } - else if (ImLengthSqr(window->Size) < 0.00001f) + else { - window->AutoFitFrames = 2; - window->AutoFitOnlyGrows = true; + if (window->Size.x <= 0.0f) + window->AutoFitFramesX = 2; + if (window->Size.y <= 0.0f) + window->AutoFitFramesY = 2; + window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); } - g.Windows.push_back(window); + if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) + g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once + else + g.Windows.push_back(window); return window; } -// Push a new ImGui window to add widgets to. -// - 'size' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation. +static void ApplySizeFullWithConstraint(ImGuiWindow* window, ImVec2 new_size) +{ + ImGuiContext& g = *GImGui; + if (g.SetNextWindowSizeConstraint) + { + // Using -1,-1 on either X/Y axis to preserve the current size. + ImRect cr = g.SetNextWindowSizeConstraintRect; + new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; + new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; + if (g.SetNextWindowSizeConstraintCallback) + { + ImGuiSizeConstraintCallbackData data; + data.UserData = g.SetNextWindowSizeConstraintCallbackUserData; + data.Pos = window->Pos; + data.CurrentSize = window->SizeFull; + data.DesiredSize = new_size; + g.SetNextWindowSizeConstraintCallback(&data); + new_size = data.DesiredSize; + } + } + if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) + new_size = ImMax(new_size, g.Style.WindowMinSize); + window->SizeFull = new_size; +} + +// Push a new ImGui window to add widgets to. // - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. // - Begin/End can be called multiple times during the frame with the same window name to append content. -// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). +// - 'size_on_first_use' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation. +// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). // You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. // - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. -// - Passing 'bool* p_opened' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. +// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. // - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin(). -bool ImGui::Begin(const char* name, bool* p_opened, ImGuiWindowFlags flags) +bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { - return ImGui::Begin(name, p_opened, ImVec2(0.f, 0.f), -1.0f, flags); + return ImGui::Begin(name, p_open, ImVec2(0.f, 0.f), -1.0f, flags); } -bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags) +bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; + IM_ASSERT(name != NULL); // Window name required IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() - IM_ASSERT(name != NULL); // Must pass a name + IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet + + if (flags & ImGuiWindowFlags_NoInputs) + flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; // Find or create bool window_is_new = false; @@ -3002,30 +3846,73 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ window = CreateNewWindow(name, size_on_first_use, flags); window_is_new = true; } - window->Flags = (ImGuiWindowFlags)flags; + + const int current_frame = ImGui::GetFrameCount(); + const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); + if (first_begin_of_the_frame) + window->Flags = (ImGuiWindowFlags)flags; + else + flags = window->Flags; // Add to stack + ImGuiWindow* parent_window = !g.CurrentWindowStack.empty() ? g.CurrentWindowStack.back() : NULL; g.CurrentWindowStack.push_back(window); SetCurrentWindow(window); + CheckStacksSize(window, true); + IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); + + bool window_was_active = (window->LastFrameActive == current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on + if (flags & ImGuiWindowFlags_Popup) + { + ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size]; + window_was_active &= (window->PopupId == popup_ref.PopupId); + window_was_active &= (window == popup_ref.Window); + popup_ref.Window = window; + g.CurrentPopupStack.push_back(popup_ref); + window->PopupId = popup_ref.PopupId; + } + + const bool window_appearing_after_being_hidden = (window->HiddenFrames == 1); // Process SetNextWindow***() calls - bool window_pos_set_by_api = false; + bool window_pos_set_by_api = false, window_size_set_by_api = false; if (g.SetNextWindowPosCond) { - const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this anymore :( need to look into that. - ImGui::SetWindowPos(g.SetNextWindowPosVal, g.SetNextWindowPosCond); + const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this saving/restore anymore :( need to look into that. + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowPosAllowFlags |= ImGuiSetCond_Appearing; + window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.SetNextWindowPosCond) != 0; + if (window_pos_set_by_api && ImLengthSqr(g.SetNextWindowPosVal - ImVec2(-FLT_MAX,-FLT_MAX)) < 0.001f) + { + window->SetWindowPosCenterWanted = true; // May be processed on the next frame if this is our first frame and we are measuring size + window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + } + else + { + SetWindowPos(window, g.SetNextWindowPosVal, g.SetNextWindowPosCond); + } window->DC.CursorPos = backup_cursor_pos; - window_pos_set_by_api = true; g.SetNextWindowPosCond = 0; } if (g.SetNextWindowSizeCond) { - ImGui::SetWindowSize(g.SetNextWindowSizeVal, g.SetNextWindowSizeCond); + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowSizeAllowFlags |= ImGuiSetCond_Appearing; + window_size_set_by_api = (window->SetWindowSizeAllowFlags & g.SetNextWindowSizeCond) != 0; + SetWindowSize(window, g.SetNextWindowSizeVal, g.SetNextWindowSizeCond); g.SetNextWindowSizeCond = 0; } + if (g.SetNextWindowContentSizeCond) + { + window->SizeContentsExplicit = g.SetNextWindowContentSizeVal; + g.SetNextWindowContentSizeCond = 0; + } + else if (first_begin_of_the_frame) + { + window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); + } if (g.SetNextWindowCollapsedCond) { - ImGui::SetWindowCollapsed(g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond); + if (!window_was_active || window_appearing_after_being_hidden) window->SetWindowCollapsedAllowFlags |= ImGuiSetCond_Appearing; + SetWindowCollapsed(window, g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond); g.SetNextWindowCollapsedCond = 0; } if (g.SetNextWindowFocus) @@ -3034,369 +3921,415 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ g.SetNextWindowFocus = false; } - // Find parent - ImGuiWindow* parent_window = (flags & ImGuiWindowFlags_ChildWindow) != 0 ? g.CurrentWindowStack[g.CurrentWindowStack.size()-2] : NULL; - // Update known root window (if we are a child window, otherwise window == window->RootWindow) - size_t root_idx = g.CurrentWindowStack.size() - 1; - while (root_idx > 0) - { - if ((g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow) == 0) + int root_idx, root_non_popup_idx; + for (root_idx = g.CurrentWindowStack.Size - 1; root_idx > 0; root_idx--) + if (!(g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow)) break; - root_idx--; - } + for (root_non_popup_idx = root_idx; root_non_popup_idx > 0; root_non_popup_idx--) + if (!(g.CurrentWindowStack[root_non_popup_idx]->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) + break; + window->ParentWindow = parent_window; window->RootWindow = g.CurrentWindowStack[root_idx]; - - // Default alpha - if (bg_alpha < 0.0f) - bg_alpha = style.WindowFillAlphaDefault; + window->RootNonPopupWindow = g.CurrentWindowStack[root_non_popup_idx]; // This is merely for displaying the TitleBgActive color. // When reusing window again multiple times a frame, just append content (don't need to setup again) - const int current_frame = ImGui::GetFrameCount(); - const bool first_begin_of_the_frame = (window->LastFrameDrawn != current_frame); if (first_begin_of_the_frame) { + window->Active = true; + window->IndexWithinParent = 0; + window->BeginCount = 0; + window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); + window->LastFrameActive = current_frame; + window->IDStack.resize(1); + + // Clear draw list, setup texture, outer clipping rectangle window->DrawList->Clear(); - window->Visible = true; + window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); + ImRect fullscreen_rect(GetVisibleRect()); + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_ComboBox|ImGuiWindowFlags_Popup))) + PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true); + else + PushClipRect(fullscreen_rect.Min, fullscreen_rect.Max, true); - // New windows appears in front - if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) + if (!window_was_active) + { + // Popup first latch mouse position, will position itself when it appears next frame + window->AutoPosLastDirection = -1; + if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) + window->PosFloat = g.IO.MousePos; + } + + // Collapse window by double-clicking on title bar + // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing + if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) { - if (window->LastFrameDrawn < current_frame - 1) + ImRect title_bar_rect = window->TitleBarRect(); + if (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]) { + window->Collapsed = !window->Collapsed; + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkSettingsDirty(); FocusWindow(window); - - // Popup position themselves when they first appear - if (flags & ImGuiWindowFlags_Popup) - { - if (!window_pos_set_by_api) - window->PosFloat = g.IO.MousePos; - } } } + else + { + window->Collapsed = false; + } - window->LastFrameDrawn = current_frame; - window->ClipRectStack.resize(0); + // SIZE - // Reset contents size for auto-fitting - window->SizeContents = window_is_new ? ImVec2(0.0f, 0.0f) : window->DC.CursorMaxPos - window->Pos; - window->SizeContents.y += window->ScrollY; + // Save contents size from last frame for auto-fitting (unless explicitly specified) + window->SizeContents.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.x - window->Pos.x) + window->Scroll.x)); + window->SizeContents.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : ((window_is_new ? 0.0f : window->DC.CursorMaxPos.y - window->Pos.y) + window->Scroll.y)); - if (flags & ImGuiWindowFlags_ChildWindow) + // Hide popup/tooltip window when first appearing while we measure size (because we recycle them) + if (window->HiddenFrames > 0) + window->HiddenFrames--; + if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && !window_was_active) { - parent_window->DC.ChildWindows.push_back(window); - window->Pos = window->PosFloat = parent_window->DC.CursorPos; - window->SizeFull = size_on_first_use; + window->HiddenFrames = 1; + if (flags & ImGuiWindowFlags_AlwaysAutoResize) + { + if (!window_size_set_by_api) + window->Size = window->SizeFull = ImVec2(0.f, 0.f); + window->SizeContents = ImVec2(0.f, 0.f); + } } - } - // Setup texture - window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); + // Lock window padding so that altering the ShowBorders flag for children doesn't have side-effects. + window->WindowPadding = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_ComboBox | ImGuiWindowFlags_Popup))) ? ImVec2(0,0) : style.WindowPadding; - // Setup outer clipping rectangle - if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ComboBox)) - PushClipRect(parent_window->ClipRectStack.back()); - else if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) - PushClipRect(ImVec4(g.IO.DisplayVisibleMin.x, g.IO.DisplayVisibleMin.y, g.IO.DisplayVisibleMax.x, g.IO.DisplayVisibleMax.y)); - else - PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); + // Calculate auto-fit size + ImVec2 size_auto_fit; + if ((flags & ImGuiWindowFlags_Tooltip) != 0) + { + // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose. + size_auto_fit = window->SizeContents + window->WindowPadding - ImVec2(0.0f, style.ItemSpacing.y); + } + else + { + size_auto_fit = ImClamp(window->SizeContents + window->WindowPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding)); - // Setup and draw window - if (first_begin_of_the_frame) - { - // Reset ID stack - window->IDStack.resize(1); + // Handling case of auto fit window not fitting in screen on one axis, we are growing auto fit size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding. + if (size_auto_fit.x < window->SizeContents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)) + size_auto_fit.y += style.ScrollbarSize; + if (size_auto_fit.y < window->SizeContents.y && !(flags & ImGuiWindowFlags_NoScrollbar)) + size_auto_fit.x += style.ScrollbarSize; + size_auto_fit.y = ImMax(size_auto_fit.y - style.ItemSpacing.y, 0.0f); + } - // Move window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows. - RegisterAliveId(window->MoveID); - if (g.ActiveId == window->MoveID) + // Handle automatic resize + if (window->Collapsed) + { + // We still process initial auto-fit on collapsed windows to get a window width, + // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. + if (window->AutoFitFramesX > 0) + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + if (window->AutoFitFramesY > 0) + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + } + else { - if (g.IO.MouseDown[0]) + if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window_size_set_by_api) { - if (!(window->Flags & ImGuiWindowFlags_NoMove)) - { - window->PosFloat += g.IO.MouseDelta; - if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) - MarkSettingsDirty(); - } - IM_ASSERT(g.MovedWindow != NULL); - FocusWindow(g.MovedWindow); + window->SizeFull = size_auto_fit; } - else + else if ((window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) && !window_size_set_by_api) { - SetActiveId(0); - g.MovedWindow = NULL; // Not strictly necessary but doing it for sanity. + // Auto-fit only grows during the first few frames + if (window->AutoFitFramesX > 0) + window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; + if (window->AutoFitFramesY > 0) + window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkSettingsDirty(); } } - // Tooltips always follows mouse - if (!window_pos_set_by_api && (window->Flags & ImGuiWindowFlags_Tooltip) != 0) + // Apply minimum/maximum window size constraints and final size + ApplySizeFullWithConstraint(window, window->SizeFull); + window->Size = window->Collapsed ? window->TitleBarRect().GetSize() : window->SizeFull; + + // POSITION + + // Position child window + if (flags & ImGuiWindowFlags_ChildWindow) + { + window->IndexWithinParent = parent_window->DC.ChildWindows.Size; + parent_window->DC.ChildWindows.push_back(window); + } + if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup)) + { + window->Pos = window->PosFloat = parent_window->DC.CursorPos; + window->Size = window->SizeFull = size_on_first_use; // NB: argument name 'size_on_first_use' misleading here, it's really just 'size' as provided by user passed via BeginChild()->Begin(). + } + + bool window_pos_center = false; + window_pos_center |= (window->SetWindowPosCenterWanted && window->HiddenFrames == 0); + window_pos_center |= ((flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api && window_appearing_after_being_hidden); + if (window_pos_center) { - window->PosFloat = g.IO.MousePos + ImVec2(32,16) - style.FramePadding*2; + // Center (any sort of window) + SetWindowPos(ImMax(style.DisplaySafeAreaPadding, fullscreen_rect.GetCenter() - window->SizeFull * 0.5f)); + } + else if (flags & ImGuiWindowFlags_ChildMenu) + { + IM_ASSERT(window_pos_set_by_api); + ImRect rect_to_avoid; + if (parent_window->DC.MenuBarAppending) + rect_to_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); + else + rect_to_avoid = ImRect(parent_window->Pos.x + style.ItemSpacing.x, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - style.ItemSpacing.x - parent_window->ScrollbarSizes.x, FLT_MAX); // We want some overlap to convey the relative depth of each popup (here hard-coded to 4) + window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + } + else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_appearing_after_being_hidden) + { + ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1); + window->PosFloat = FindBestPopupWindowPos(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + } + + // Position tooltip (always follows mouse) + if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api) + { + ImRect rect_to_avoid(g.IO.MousePos.x - 16, g.IO.MousePos.y - 8, g.IO.MousePos.x + 24, g.IO.MousePos.y + 24); // FIXME: Completely hard-coded. Perhaps center on cursor hit-point instead? + window->PosFloat = FindBestPopupWindowPos(g.IO.MousePos, window->Size, &window->AutoPosLastDirection, rect_to_avoid); + if (window->AutoPosLastDirection == -1) + window->PosFloat = g.IO.MousePos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. } - // Clamp into view - if (!(window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Tooltip)) + // Clamp position so it stays visible + if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) { - if (window->AutoFitFrames <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. + if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. { - ImVec2 clip_min = style.DisplaySafeAreaPadding; - ImVec2 clip_max = g.IO.DisplaySize - style.DisplaySafeAreaPadding; - window->PosFloat = ImMax(window->PosFloat + window->Size, clip_min) - window->Size; - window->PosFloat = ImMin(window->PosFloat, clip_max); + ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); + window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size; + window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding); } - window->SizeFull = ImMax(window->SizeFull, style.WindowMinSize); } window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); // Default item width. Make it proportional to window size if window manually resizes - if (window->Size.x > 0.0f && !(window->Flags & ImGuiWindowFlags_Tooltip) && !(window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) + if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); else - window->ItemWidthDefault = 200.0f; + window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); // Prepare for focus requests - if (window->FocusIdxAllRequestNext == IM_INT_MAX || window->FocusIdxAllCounter == -1) - window->FocusIdxAllRequestCurrent = IM_INT_MAX; - else - window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); - if (window->FocusIdxTabRequestNext == IM_INT_MAX || window->FocusIdxTabCounter == -1) - window->FocusIdxTabRequestCurrent = IM_INT_MAX; - else - window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); + window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); + window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; - window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = IM_INT_MAX; - - ImRect title_bar_rect = window->TitleBarRect(); - - // Apply and ImClamp scrolling - window->ScrollY = window->NextScrollY; - window->ScrollY = ImMax(window->ScrollY, 0.0f); - if (!window->Collapsed && !window->SkipItems) - window->ScrollY = ImMin(window->ScrollY, ImMax(0.0f, window->SizeContents.y - window->SizeFull.y)); - window->NextScrollY = window->ScrollY; + window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX; - // At this point we don't have a clipping rectangle setup yet, so we can test and draw in title bar - // Collapse window by double-clicking on title bar - if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) + // Apply scrolling + if (window->ScrollTarget.x < FLT_MAX) { - if (!(window->Flags & ImGuiWindowFlags_NoCollapse) && g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect) && g.IO.MouseDoubleClicked[0]) - { - window->Collapsed = !window->Collapsed; - if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) - MarkSettingsDirty(); - FocusWindow(window); - } + window->Scroll.x = window->ScrollTarget.x; + window->ScrollTarget.x = FLT_MAX; } - else + if (window->ScrollTarget.y < FLT_MAX) { - window->Collapsed = false; + float center_ratio = window->ScrollTargetCenterRatio.y; + window->Scroll.y = window->ScrollTarget.y - ((1.0f - center_ratio) * (window->TitleBarHeight() + window->MenuBarHeight())) - (center_ratio * window->SizeFull.y); + window->ScrollTarget.y = FLT_MAX; } + window->Scroll = ImMax(window->Scroll, ImVec2(0.0f, 0.0f)); + if (!window->Collapsed && !window->SkipItems) + window->Scroll = ImMin(window->Scroll, ImMax(ImVec2(0.0f, 0.0f), window->SizeContents - window->SizeFull + window->ScrollbarSizes)); - // Calculate auto-fit size - ImVec2 size_auto_fit; - if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) - { - // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose. - size_auto_fit = window->SizeContents + style.WindowPadding - ImVec2(0.0f, style.ItemSpacing.y); - } - else - { - size_auto_fit = ImClamp(window->SizeContents + style.AutoFitPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - style.AutoFitPadding)); - if (size_auto_fit.y < window->SizeContents.y + style.AutoFitPadding.y) - size_auto_fit.x += style.ScrollbarWidth; - } + // Modal window darkens what is behind them + if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow()) + window->DrawList->AddRectFilled(fullscreen_rect.Min, fullscreen_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio)); - const float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; + // Draw window + handle manual resize + ImRect title_bar_rect = window->TitleBarRect(); + const float window_rounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; if (window->Collapsed) { - // We still process initial auto-fit on collapsed windows to get a window width - // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. - if (window->AutoFitFrames > 0) - { - window->SizeFull = window->AutoFitOnlyGrows ? ImMax(window->SizeFull, size_auto_fit) : size_auto_fit; - title_bar_rect = window->TitleBarRect(); - } - // Draw title bar only - window->Size = title_bar_rect.GetSize(); - window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_TitleBgCollapsed), window_rounding); - if (window->Flags & ImGuiWindowFlags_ShowBorders) - { - window->DrawList->AddRect(title_bar_rect.GetTL()+ImVec2(1,1), title_bar_rect.GetBR()+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), window_rounding); - window->DrawList->AddRect(title_bar_rect.GetTL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_Border), window_rounding); - } + RenderFrame(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32(ImGuiCol_TitleBgCollapsed), true, window_rounding); } else { ImU32 resize_col = 0; - if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) + const float resize_corner_size = ImMax(g.FontSize * 1.35f, window_rounding + 1.0f + g.FontSize * 0.2f); + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && !(flags & ImGuiWindowFlags_NoResize)) { - window->Size = window->SizeFull = size_auto_fit; - } - else - { - if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) - { - // Don't continuously mark settings as dirty, the size of the window doesn't need to be stored. - window->SizeFull = size_auto_fit; - } - else if (window->AutoFitFrames > 0) + // Manual resize + const ImVec2 br = window->Rect().GetBR(); + const ImRect resize_rect(br - ImVec2(resize_corner_size * 0.75f, resize_corner_size * 0.75f), br); + const ImGuiID resize_id = window->GetID("#RESIZE"); + bool hovered, held; + ButtonBehavior(resize_rect, resize_id, &hovered, &held, ImGuiButtonFlags_FlattenChilds); + resize_col = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); + + if (hovered || held) + g.MouseCursor = ImGuiMouseCursor_ResizeNWSE; + + if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0]) { - // Auto-fit only grows during the first few frames - window->SizeFull = window->AutoFitOnlyGrows ? ImMax(window->SizeFull, size_auto_fit) : size_auto_fit; - if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) + // Manual auto-fit when double-clicking + ApplySizeFullWithConstraint(window, size_auto_fit); + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) MarkSettingsDirty(); + SetActiveID(0); } - else if (!(window->Flags & ImGuiWindowFlags_NoResize)) + else if (held) { - // Manual resize grip - const ImRect resize_rect(window->Rect().GetBR()-ImVec2(14,14), window->Rect().GetBR()); - const ImGuiID resize_id = window->GetID("#RESIZE"); - bool hovered, held; - ButtonBehavior(resize_rect, resize_id, &hovered, &held, true); - resize_col = window->Color(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); - - if (hovered || held) - g.MouseCursor = ImGuiMouseCursor_ResizeNWSE; - - if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0]) - { - // Manual auto-fit when double-clicking - window->SizeFull = size_auto_fit; - if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) - MarkSettingsDirty(); - SetActiveId(0); - } - else if (held) - { - // Resize - window->SizeFull = ImMax(window->SizeFull + g.IO.MouseDelta, style.WindowMinSize); - if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) - MarkSettingsDirty(); - } + // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position + ApplySizeFullWithConstraint(window, (g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize()) - window->Pos); + if (!(flags & ImGuiWindowFlags_NoSavedSettings)) + MarkSettingsDirty(); } - // Update rectangle immediately so that rendering right below us isn't one frame late window->Size = window->SizeFull; title_bar_rect = window->TitleBarRect(); } - // Scrollbar - window->ScrollbarY = (window->SizeContents.y > window->Size.y) && !(window->Flags & ImGuiWindowFlags_NoScrollbar); + // Scrollbars + window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > window->Size.y + style.ItemSpacing.y) && !(flags & ImGuiWindowFlags_NoScrollbar)); + window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > window->Size.x - (window->ScrollbarY ? style.ScrollbarSize : 0.0f) - window->WindowPadding.x) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); + window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); + window->BorderSize = (flags & ImGuiWindowFlags_ShowBorders) ? 1.0f : 0.0f; // Window background - if (bg_alpha > 0.0f) - { - if ((window->Flags & ImGuiWindowFlags_ComboBox) != 0) - window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_ComboBg, bg_alpha), window_rounding); - else if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) - window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_TooltipBg, bg_alpha), window_rounding); - else if ((window->Flags & ImGuiWindowFlags_ChildWindow) != 0) - window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size-ImVec2(window->ScrollbarY?style.ScrollbarWidth:0.0f,0.0f), window->Color(ImGuiCol_ChildWindowBg, bg_alpha), window_rounding, window->ScrollbarY ? (1|8) : (0xF)); - else - window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_WindowBg, bg_alpha), window_rounding); - } + // Default alpha + ImGuiCol bg_color_idx = ImGuiCol_WindowBg; + if ((flags & ImGuiWindowFlags_ComboBox) != 0) + bg_color_idx = ImGuiCol_ComboBg; + else if ((flags & ImGuiWindowFlags_Tooltip) != 0 || (flags & ImGuiWindowFlags_Popup) != 0) + bg_color_idx = ImGuiCol_PopupBg; + else if ((flags & ImGuiWindowFlags_ChildWindow) != 0) + bg_color_idx = ImGuiCol_ChildWindowBg; + ImVec4 bg_color = style.Colors[bg_color_idx]; + if (bg_alpha >= 0.0f) + bg_color.w = bg_alpha; + bg_color.w *= style.Alpha; + if (bg_color.w > 0.0f) + window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, ColorConvertFloat4ToU32(bg_color), window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 15 : 4|8); // Title bar - if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) - window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_TitleBg), window_rounding, 1|2); + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), GetColorU32((g.FocusedWindow && window->RootNonPopupWindow == g.FocusedWindow->RootNonPopupWindow) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg), window_rounding, 1|2); - // Borders - if (window->Flags & ImGuiWindowFlags_ShowBorders) + // Menu bar + if (flags & ImGuiWindowFlags_MenuBar) { - window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), window_rounding); - window->DrawList->AddRect(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_Border), window_rounding); - if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) - window->DrawList->AddLine(title_bar_rect.GetBL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_Border)); + ImRect menu_bar_rect = window->MenuBarRect(); + window->DrawList->AddRectFilled(menu_bar_rect.GetTL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, 1|2); + if (flags & ImGuiWindowFlags_ShowBorders) + window->DrawList->AddLine(menu_bar_rect.GetBL()-ImVec2(0,0), menu_bar_rect.GetBR()-ImVec2(0,0), GetColorU32(ImGuiCol_Border)); } - // Scrollbar + // Scrollbars + if (window->ScrollbarX) + Scrollbar(window, true); if (window->ScrollbarY) - Scrollbar(window); + Scrollbar(window, false); // Render resize grip // (after the input handling so we don't have a frame of latency) - if (!(window->Flags & ImGuiWindowFlags_NoResize)) + if (!(flags & ImGuiWindowFlags_NoResize)) { - const float r = window_rounding; const ImVec2 br = window->Rect().GetBR(); - if (r == 0.0f) - { - window->DrawList->AddTriangleFilled(br, br-ImVec2(0,14), br-ImVec2(14,0), resize_col); - } - else - { - // FIXME: We should draw 4 triangles and decide on a size that's not dependent on the rounding size (previously used 18) - window->DrawList->AddArc(br - ImVec2(r,r), r, resize_col, 6, 9, true); - window->DrawList->AddTriangleFilled(br+ImVec2(0,-2*r),br+ImVec2(0,-r),br+ImVec2(-r,-r), resize_col); - window->DrawList->AddTriangleFilled(br+ImVec2(-r,-r), br+ImVec2(-r,0),br+ImVec2(-2*r,0), resize_col); - } + window->DrawList->PathLineTo(br + ImVec2(-resize_corner_size, -window->BorderSize)); + window->DrawList->PathLineTo(br + ImVec2(-window->BorderSize, -resize_corner_size)); + window->DrawList->PathArcToFast(ImVec2(br.x - window_rounding - window->BorderSize, br.y - window_rounding - window->BorderSize), window_rounding, 0, 3); + window->DrawList->PathFill(resize_col); + } + + // Borders + if (flags & ImGuiWindowFlags_ShowBorders) + { + window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), window_rounding); + window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding); + if (!(flags & ImGuiWindowFlags_NoTitleBar)) + window->DrawList->AddLine(title_bar_rect.GetBL()+ImVec2(1,0), title_bar_rect.GetBR()-ImVec2(1,0), GetColorU32(ImGuiCol_Border)); } } + // Update ContentsRegionMax. All the variable it depends on are set above in this function. + window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x; + window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); + window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x)); + window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y)); + // Setup drawing context - window->DC.ColumnsStartX = window->WindowPadding().x; + window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x; + window->DC.GroupOffsetX = 0.0f; window->DC.ColumnsOffsetX = 0.0f; - window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.ColumnsStartX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->WindowPadding().y) - ImVec2(0.0f, window->ScrollY); + window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y); window->DC.CursorPos = window->DC.CursorStartPos; window->DC.CursorPosPrevLine = window->DC.CursorPos; window->DC.CursorMaxPos = window->DC.CursorStartPos; window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; + window->DC.MenuBarAppending = false; + window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x); window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; window->DC.ChildWindows.resize(0); - window->DC.ItemWidth.resize(0); - window->DC.ItemWidth.push_back(window->ItemWidthDefault); - window->DC.AllowKeyboardFocus.resize(0); - window->DC.AllowKeyboardFocus.push_back(true); - window->DC.TextWrapPos.resize(0); - window->DC.TextWrapPos.push_back(-1.0f); // disabled - window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect; + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.ItemWidth = window->ItemWidthDefault; + window->DC.TextWrapPos = -1.0f; // disabled + window->DC.AllowKeyboardFocus = true; + window->DC.ButtonRepeat = false; + window->DC.ItemWidthStack.resize(0); + window->DC.AllowKeyboardFocusStack.resize(0); + window->DC.ButtonRepeatStack.resize(0); + window->DC.TextWrapPosStack.resize(0); window->DC.ColumnsCurrent = 0; window->DC.ColumnsCount = 1; - window->DC.ColumnsStartPos = window->DC.CursorPos; - window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPos.y; + window->DC.ColumnsStartPosY = window->DC.CursorPos.y; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPosY; window->DC.TreeDepth = 0; window->DC.StateStorage = &window->StateStorage; window->DC.GroupStack.resize(0); + window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect; + window->MenuColumns.Update(3, style.ItemSpacing.x, !window_was_active); + + if (window->AutoFitFramesX > 0) + window->AutoFitFramesX--; + if (window->AutoFitFramesY > 0) + window->AutoFitFramesY--; - if (window->AutoFitFrames > 0) - window->AutoFitFrames--; + // New windows appears in front (we need to do that AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) + if (!window_was_active && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) + if (!(flags & (ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup)) + FocusWindow(window); // Title bar - if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) + if (!(flags & ImGuiWindowFlags_NoTitleBar)) { - if (p_opened != NULL) - CloseWindowButton(p_opened); - - ImVec2 text_min = window->Pos + style.FramePadding; - if (!(window->Flags & ImGuiWindowFlags_NoCollapse)) + if (p_open != NULL) { - RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f, true); - text_min.x += g.FontSize + style.ItemInnerSpacing.x; + const float pad = 2.0f; + const float rad = (window->TitleBarHeight() - pad*2.0f) * 0.5f; + if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad)) + *p_open = false; } const ImVec2 text_size = CalcTextSize(name, NULL, true); - const ImVec2 text_max = window->Pos + ImVec2(window->Size.x - (p_opened ? (title_bar_rect.GetHeight()-3) : style.FramePadding.x), style.FramePadding.y*2 + text_size.y); - RenderTextClipped(text_min, name, NULL, &text_size, text_max); - } - if (window->Flags & ImGuiWindowFlags_Popup) - { - if (p_opened) - { - if (g.IO.MouseClicked[0] && (!g.HoveredWindow || g.HoveredWindow->RootWindow != window)) - *p_opened = false; - else if (!g.FocusedWindow) - *p_opened = false; - else if (g.FocusedWindow->RootWindow != window)// && !(g.FocusedWindow->RootWindow->Flags & ImGuiWindowFlags_Tooltip)) - *p_opened = false; - } + if (!(flags & ImGuiWindowFlags_NoCollapse)) + RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f, true); + + ImVec2 text_min = window->Pos; + ImVec2 text_max = window->Pos + ImVec2(window->Size.x, style.FramePadding.y*2 + text_size.y); + ImRect clip_rect; + clip_rect.Max = ImVec2(window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x), text_max.y); // Match the size of CloseWindowButton() + float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : 0.0f; + float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : 0.0f; + if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); + text_min.x += pad_left; + text_max.x -= pad_right; + clip_rect.Min = ImVec2(text_min.x, window->Pos.y); + RenderTextClipped(text_min, text_max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); } // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() - window->ClippedRect = window->Rect(); - window->ClippedRect.Clip(window->ClipRectStack.front()); + window->WindowRectClipped = window->Rect(); + window->WindowRectClipped.Clip(window->ClipRect); // Pressing CTRL+C while holding on a window copy its content to the clipboard // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. @@ -3412,14 +4345,19 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior. const ImRect title_bar_rect = window->TitleBarRect(); - ImVec4 clip_rect(title_bar_rect.Min.x+0.5f+window->WindowPadding().x*0.5f, title_bar_rect.Max.y+0.5f, window->Rect().Max.x+0.5f-window->WindowPadding().x*0.5f, window->Rect().Max.y-1.5f); - if (window->ScrollbarY) - clip_rect.z -= style.ScrollbarWidth; - PushClipRect(clip_rect); + const float border_size = window->BorderSize; + ImRect clip_rect; // Force round to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. + clip_rect.Min.x = ImFloor(0.5f + title_bar_rect.Min.x + ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); + clip_rect.Min.y = ImFloor(0.5f + title_bar_rect.Max.y + window->MenuBarHeight() + border_size); + clip_rect.Max.x = ImFloor(0.5f + window->Pos.x + window->Size.x - window->ScrollbarSizes.x - ImMax(border_size, ImFloor(window->WindowPadding.x*0.5f))); + clip_rect.Max.y = ImFloor(0.5f + window->Pos.y + window->Size.y - window->ScrollbarSizes.y - border_size); + PushClipRect(clip_rect.Min, clip_rect.Max, true); // Clear 'accessed' flag last thing if (first_begin_of_the_frame) window->Accessed = false; + window->BeginCount++; + g.SetNextWindowSizeConstraint = false; // Child window can be out of sight and have "negative" clip windows. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar). @@ -3428,115 +4366,149 @@ bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_ IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); window->Collapsed = parent_window && parent_window->Collapsed; - const ImVec4 clip_rect_t = window->ClipRectStack.back(); - window->Collapsed |= (clip_rect_t.x >= clip_rect_t.z || clip_rect_t.y >= clip_rect_t.w); + if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) + window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y); // We also hide the window from rendering because we've already added its border to the command list. // (we could perform the check earlier in the function but it is simpler at this point) if (window->Collapsed) - window->Visible = false; + window->Active = false; } if (style.Alpha <= 0.0f) - window->Visible = false; + window->Active = false; // Return false if we don't intend to display anything to allow user to perform an early out optimization - window->SkipItems = (window->Collapsed || !window->Visible) && window->AutoFitFrames <= 0; + window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0; return !window->SkipItems; } void ImGui::End() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; - ImGui::Columns(1, "#CloseColumns"); + Columns(1, "#CloseColumns"); PopClipRect(); // inner window clip rectangle - PopClipRect(); // outer window clip rectangle - window->DrawList->PopTextureID(); // Stop logging if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging - ImGui::LogFinish(); + LogFinish(); // Pop // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin(). g.CurrentWindowStack.pop_back(); + if (window->Flags & ImGuiWindowFlags_Popup) + g.CurrentPopupStack.pop_back(); + CheckStacksSize(window, false); SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); } // Vertical scrollbar // The entire piece of code below is rather confusing because: // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) -// - We store values as ratio and in a form that allows the window content to change while we are holding on a scrollbar -static void Scrollbar(ImGuiWindow* window) +// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar +// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. +static void Scrollbar(ImGuiWindow* window, bool horizontal) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const ImGuiID id = window->GetID("#SCROLLY"); + const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY"); // Render background - ImRect bb(window->Rect().Max.x - style.ScrollbarWidth, window->Pos.y + window->TitleBarHeight()+1, window->Rect().Max.x, window->Rect().Max.y-1); - window->DrawList->AddRectFilled(bb.Min, bb.Max, window->Color(ImGuiCol_ScrollbarBg)); - bb.Expand(-3.0f); - const float scrollbar_height = bb.GetHeight(); + bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); + float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; + const ImRect window_rect = window->Rect(); + const float border_size = window->BorderSize; + ImRect bb = horizontal + ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size) + : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size); + if (!horizontal) + bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); + + float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; + int window_rounding_corners; + if (horizontal) + window_rounding_corners = 8 | (other_scrollbar ? 0 : 4); + else + window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? 2 : 0) | (other_scrollbar ? 0 : 4); + window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_ScrollbarBg), window_rounding, window_rounding_corners); + bb.Reduce(ImVec2(ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f))); + + // V denote the main axis of the scrollbar + float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); + float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y; + float win_size_avail_v = (horizontal ? window->Size.x : window->Size.y) - other_scrollbar_size_w; + float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y; // The grabable box size generally represent the amount visible (vs the total scrollable amount) // But we maintain a minimum size in pixel to allow for the user to still aim inside. - const float grab_h_pixels = ImMin(ImMax(scrollbar_height * ImSaturate(window->Size.y / ImMax(window->SizeContents.y, window->Size.y)), style.GrabMinSize), scrollbar_height); - const float grab_h_norm = grab_h_pixels / scrollbar_height; + const float grab_h_pixels = ImMin(ImMax(scrollbar_size_v * ImSaturate(win_size_avail_v / ImMax(win_size_contents_v, win_size_avail_v)), style.GrabMinSize), scrollbar_size_v); + const float grab_h_norm = grab_h_pixels / scrollbar_size_v; // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). bool held = false; bool hovered = false; const bool previously_held = (g.ActiveId == id); - ButtonBehavior(bb, id, &hovered, &held, true); + ImGui::ButtonBehavior(bb, id, &hovered, &held); - const float scroll_max = ImMax(1.0f, window->SizeContents.y - window->Size.y); - float scroll_ratio = ImSaturate(window->ScrollY / scroll_max); - float grab_y_norm = scroll_ratio * (scrollbar_height - grab_h_pixels) / scrollbar_height; - if (held) + float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v); + float scroll_ratio = ImSaturate(scroll_v / scroll_max); + float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; + if (held && grab_h_norm < 1.0f) { - const float clicked_y_norm = ImSaturate((g.IO.MousePos.y - bb.Min.y) / scrollbar_height); // Click position in scrollbar space (0.0f->1.0f) - g.HoveredId = id; + float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; + float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; + float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y; + + // Click position in scrollbar normalized space (0.0f->1.0f) + const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); + ImGui::SetHoveredID(id); bool seek_absolute = false; if (!previously_held) { // On initial click calculate the distance between mouse and the center of the grab - if (clicked_y_norm >= grab_y_norm && clicked_y_norm <= grab_y_norm + grab_h_norm) + if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm) { - g.ScrollbarClickDeltaToGrabCenter = clicked_y_norm - grab_y_norm - grab_h_norm*0.5f; + *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } else { seek_absolute = true; - g.ScrollbarClickDeltaToGrabCenter = 0; + *click_delta_to_grab_center_v = 0.0f; } } // Apply scroll - const float scroll_y_norm = ImSaturate((clicked_y_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); - window->ScrollY = (float)(int)(0.5f + scroll_y_norm * (window->SizeContents.y - window->Size.y)); - window->NextScrollY = window->ScrollY; + // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position + const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); + scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); + if (horizontal) + window->Scroll.x = scroll_v; + else + window->Scroll.y = scroll_v; // Update values for rendering - scroll_ratio = ImSaturate(window->ScrollY / scroll_max); - grab_y_norm = scroll_ratio * (scrollbar_height - grab_h_pixels) / scrollbar_height; + scroll_ratio = ImSaturate(scroll_v / scroll_max); + grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Update distance to grab now that we have seeked and saturated if (seek_absolute) - g.ScrollbarClickDeltaToGrabCenter = clicked_y_norm - grab_y_norm - grab_h_norm*0.5f; + *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } // Render - const ImU32 grab_col = window->Color(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); - window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_y_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_y_norm) + grab_h_pixels), grab_col); + const ImU32 grab_col = ImGui::GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); + if (horizontal) + window->DrawList->AddRectFilled(ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y), ImVec2(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, bb.Max.y), grab_col, style.ScrollbarRounding); + else + window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels), grab_col, style.ScrollbarRounding); } // Moving window to front of display (which happens to be back of our sorted list) -static void FocusWindow(ImGuiWindow* window) +void ImGui::FocusWindow(ImGuiWindow* window) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing. g.FocusedWindow = window; @@ -3545,14 +4517,19 @@ static void FocusWindow(ImGuiWindow* window) if (!window) return; - // And move its root window to the top of the pile + // And move its root window to the top of the pile if (window->RootWindow) window = window->RootWindow; - if (g.Windows.back() == window) - return; + // Steal focus on active widgets + if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it.. + if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window) + SetActiveID(0); - for (size_t i = 0; i < g.Windows.size(); i++) + // Bring to front + if ((window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) || g.Windows.back() == window) + return; + for (int i = 0; i < g.Windows.Size; i++) if (g.Windows[i] == window) { g.Windows.erase(g.Windows.begin() + i); @@ -3564,36 +4541,49 @@ static void FocusWindow(ImGuiWindow* window) void ImGui::PushItemWidth(float item_width) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.ItemWidth.push_back(item_width == 0.0f ? window->ItemWidthDefault : item_width); + window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); + window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); +} + +static void PushMultiItemsWidths(int components, float w_full) +{ + ImGuiWindow* window = ImGui::GetCurrentWindow(); + const ImGuiStyle& style = GImGui->Style; + if (w_full <= 0.0f) + w_full = ImGui::CalcItemWidth(); + const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); + window->DC.ItemWidthStack.push_back(w_item_last); + for (int i = 0; i < components-1; i++) + window->DC.ItemWidthStack.push_back(w_item_one); + window->DC.ItemWidth = window->DC.ItemWidthStack.back(); } void ImGui::PopItemWidth() { ImGuiWindow* window = GetCurrentWindow(); - window->DC.ItemWidth.pop_back(); + window->DC.ItemWidthStack.pop_back(); + window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); } float ImGui::CalcItemWidth() { - ImGuiWindow* window = GetCurrentWindow(); - float w = window->DC.ItemWidth.back(); + ImGuiWindow* window = GetCurrentWindowRead(); + float w = window->DC.ItemWidth; if (w < 0.0f) { // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well. - ImGuiState& g = *GImGui; - w = -w; - float width_to_right_edge = window->Pos.x + ImGui::GetContentRegionMax().x - window->DC.CursorPos.x; - w = ImMax(1.0f, width_to_right_edge - w - g.Style.FramePadding.x * 2.0f); + float width_to_right_edge = GetContentRegionAvail().x; + w = ImMax(1.0f, width_to_right_edge + w); } w = (float)(int)w; return w; } -static void SetFont(ImFont* font) +static void SetCurrentFont(ImFont* font) { - ImGuiState& g = *GImGui; - - IM_ASSERT(font && font->IsLoaded()); + ImGuiContext& g = *GImGui; + IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(font->Scale > 0.0f); g.Font = font; g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale; @@ -3603,139 +4593,151 @@ static void SetFont(ImFont* font) void ImGui::PushFont(ImFont* font) { - ImGuiState& g = *GImGui; - + ImGuiContext& g = *GImGui; if (!font) font = g.IO.Fonts->Fonts[0]; - - SetFont(font); + SetCurrentFont(font); g.FontStack.push_back(font); g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() { - ImGuiState& g = *GImGui; - + ImGuiContext& g = *GImGui; g.CurrentWindow->DrawList->PopTextureID(); g.FontStack.pop_back(); - SetFont(g.FontStack.empty() ? g.IO.Fonts->Fonts[0] : g.FontStack.back()); + SetCurrentFont(g.FontStack.empty() ? g.IO.Fonts->Fonts[0] : g.FontStack.back()); } void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.AllowKeyboardFocus.push_back(allow_keyboard_focus); + window->DC.AllowKeyboardFocus = allow_keyboard_focus; + window->DC.AllowKeyboardFocusStack.push_back(allow_keyboard_focus); } void ImGui::PopAllowKeyboardFocus() { ImGuiWindow* window = GetCurrentWindow(); - window->DC.AllowKeyboardFocus.pop_back(); + window->DC.AllowKeyboardFocusStack.pop_back(); + window->DC.AllowKeyboardFocus = window->DC.AllowKeyboardFocusStack.empty() ? true : window->DC.AllowKeyboardFocusStack.back(); +} + +void ImGui::PushButtonRepeat(bool repeat) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.ButtonRepeat = repeat; + window->DC.ButtonRepeatStack.push_back(repeat); } -void ImGui::PushTextWrapPos(float wrap_x) +void ImGui::PopButtonRepeat() { ImGuiWindow* window = GetCurrentWindow(); - window->DC.TextWrapPos.push_back(wrap_x); + window->DC.ButtonRepeatStack.pop_back(); + window->DC.ButtonRepeat = window->DC.ButtonRepeatStack.empty() ? false : window->DC.ButtonRepeatStack.back(); +} + +void ImGui::PushTextWrapPos(float wrap_pos_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->DC.TextWrapPos = wrap_pos_x; + window->DC.TextWrapPosStack.push_back(wrap_pos_x); } void ImGui::PopTextWrapPos() { ImGuiWindow* window = GetCurrentWindow(); - window->DC.TextWrapPos.pop_back(); + window->DC.TextWrapPosStack.pop_back(); + window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); } void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) { - ImGuiState& g = *GImGui; - + ImGuiContext& g = *GImGui; ImGuiColMod backup; backup.Col = idx; - backup.PreviousValue = g.Style.Colors[idx]; + backup.BackupValue = g.Style.Colors[idx]; g.ColorModifiers.push_back(backup); g.Style.Colors[idx] = col; } void ImGui::PopStyleColor(int count) { - ImGuiState& g = *GImGui; - + ImGuiContext& g = *GImGui; while (count > 0) { ImGuiColMod& backup = g.ColorModifiers.back(); - g.Style.Colors[backup.Col] = backup.PreviousValue; + g.Style.Colors[backup.Col] = backup.BackupValue; g.ColorModifiers.pop_back(); count--; } } -static float* GetStyleVarFloatAddr(ImGuiStyleVar idx) +struct ImGuiStyleVarInfo { - ImGuiState& g = *GImGui; - switch (idx) - { - case ImGuiStyleVar_Alpha: return &g.Style.Alpha; - case ImGuiStyleVar_WindowRounding: return &g.Style.WindowRounding; - case ImGuiStyleVar_ChildWindowRounding: return &g.Style.ChildWindowRounding; - case ImGuiStyleVar_FrameRounding: return &g.Style.FrameRounding; - case ImGuiStyleVar_IndentSpacing: return &g.Style.IndentSpacing; - case ImGuiStyleVar_GrabMinSize: return &g.Style.GrabMinSize; - } - return NULL; -} + ImGuiDataType Type; + ImU32 Offset; + void* GetVarPtr() const { return (void*)((unsigned char*)&GImGui->Style + Offset); } +}; -static ImVec2* GetStyleVarVec2Addr(ImGuiStyleVar idx) +static const ImGuiStyleVarInfo GStyleVarInfo[ImGuiStyleVar_Count_] = +{ + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildWindowRounding) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, + { ImGuiDataType_Float, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, + { ImGuiDataType_Float2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, +}; + +static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx) { - ImGuiState& g = *GImGui; - switch (idx) - { - case ImGuiStyleVar_WindowPadding: return &g.Style.WindowPadding; - case ImGuiStyleVar_FramePadding: return &g.Style.FramePadding; - case ImGuiStyleVar_ItemSpacing: return &g.Style.ItemSpacing; - case ImGuiStyleVar_ItemInnerSpacing: return &g.Style.ItemInnerSpacing; - } - return NULL; + IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_Count_); + return &GStyleVarInfo[idx]; } void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { - ImGuiState& g = *GImGui; - - float* pvar = GetStyleVarFloatAddr(idx); - IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a float. - ImGuiStyleMod backup; - backup.Var = idx; - backup.PreviousValue = ImVec2(*pvar, 0.0f); - g.StyleModifiers.push_back(backup); - *pvar = val; + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float) + { + float* pvar = (float*)var_info->GetVarPtr(); + GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0); // Called function with wrong-type? Variable is not a float. } - void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { - ImGuiState& g = *GImGui; - - ImVec2* pvar = GetStyleVarVec2Addr(idx); - IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a ImVec2. - ImGuiStyleMod backup; - backup.Var = idx; - backup.PreviousValue = *pvar; - g.StyleModifiers.push_back(backup); - *pvar = val; + const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); + if (var_info->Type == ImGuiDataType_Float2) + { + ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(); + GImGui->StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); + *pvar = val; + return; + } + IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2. } void ImGui::PopStyleVar(int count) { - ImGuiState& g = *GImGui; - + ImGuiContext& g = *GImGui; while (count > 0) { ImGuiStyleMod& backup = g.StyleModifiers.back(); - if (float* pvar_f = GetStyleVarFloatAddr(backup.Var)) - *pvar_f = backup.PreviousValue.x; - else if (ImVec2* pvar_v = GetStyleVarVec2Addr(backup.Var)) - *pvar_v = backup.PreviousValue; + const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); + if (info->Type == ImGuiDataType_Float) (*(float*)info->GetVarPtr()) = backup.BackupFloat[0]; + else if (info->Type == ImGuiDataType_Float2) (*(ImVec2*)info->GetVarPtr()) = ImVec2(backup.BackupFloat[0], backup.BackupFloat[1]); + else if (info->Type == ImGuiDataType_Int) (*(int*)info->GetVarPtr()) = backup.BackupInt[0]; g.StyleModifiers.pop_back(); count--; } @@ -3747,8 +4749,10 @@ const char* ImGui::GetStyleColName(ImGuiCol idx) switch (idx) { case ImGuiCol_Text: return "Text"; + case ImGuiCol_TextDisabled: return "TextDisabled"; case ImGuiCol_WindowBg: return "WindowBg"; case ImGuiCol_ChildWindowBg: return "ChildWindowBg"; + case ImGuiCol_PopupBg: return "PopupBg"; case ImGuiCol_Border: return "Border"; case ImGuiCol_BorderShadow: return "BorderShadow"; case ImGuiCol_FrameBg: return "FrameBg"; @@ -3756,6 +4760,8 @@ const char* ImGui::GetStyleColName(ImGuiCol idx) case ImGuiCol_FrameBgActive: return "FrameBgActive"; case ImGuiCol_TitleBg: return "TitleBg"; case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; + case ImGuiCol_TitleBgActive: return "TitleBgActive"; + case ImGuiCol_MenuBarBg: return "MenuBarBg"; case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; @@ -3784,51 +4790,75 @@ const char* ImGui::GetStyleColName(ImGuiCol idx) case ImGuiCol_PlotHistogram: return "PlotHistogram"; case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; - case ImGuiCol_TooltipBg: return "TooltipBg"; + case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening"; } IM_ASSERT(0); return "Unknown"; } +bool ImGui::IsWindowHovered() +{ + ImGuiContext& g = *GImGui; + return g.HoveredWindow == g.CurrentWindow && IsWindowContentHoverable(g.HoveredRootWindow); +} + bool ImGui::IsWindowFocused() { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - return g.FocusedWindow == window; + ImGuiContext& g = *GImGui; + return g.FocusedWindow == g.CurrentWindow; } bool ImGui::IsRootWindowFocused() { - ImGuiState& g = *GImGui; - ImGuiWindow* root_window = GetCurrentWindow()->RootWindow; - return g.FocusedWindow == root_window; + ImGuiContext& g = *GImGui; + return g.FocusedWindow == g.CurrentWindow->RootWindow; } bool ImGui::IsRootWindowOrAnyChildFocused() { - ImGuiState& g = *GImGui; - ImGuiWindow* root_window = GetCurrentWindow()->RootWindow; - return g.FocusedWindow && g.FocusedWindow->RootWindow == root_window; + ImGuiContext& g = *GImGui; + return g.FocusedWindow && g.FocusedWindow->RootWindow == g.CurrentWindow->RootWindow; +} + +bool ImGui::IsRootWindowOrAnyChildHovered() +{ + ImGuiContext& g = *GImGui; + return g.HoveredRootWindow && (g.HoveredRootWindow == g.CurrentWindow->RootWindow) && IsWindowContentHoverable(g.HoveredRootWindow); } float ImGui::GetWindowWidth() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.x; } -ImVec2 ImGui::GetWindowPos() +float ImGui::GetWindowHeight() { - ImGuiWindow* window = GetCurrentWindow(); - return window->Pos; + ImGuiWindow* window = GImGui->CurrentWindow; + return window->Size.y; } -static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond) +ImVec2 ImGui::GetWindowPos() +{ + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; + return window->Pos; +} + +static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) +{ + window->DC.CursorMaxPos.y += window->Scroll.y; + window->Scroll.y = new_scroll_y; + window->DC.CursorMaxPos.y -= window->Scroll.y; +} + +static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowPosAllowFlags & cond) == 0) return; - window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver); + window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); + window->SetWindowPosCenterWanted = false; // Set const ImVec2 old_pos = window->Pos; @@ -3853,7 +4883,7 @@ void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond) ImVec2 ImGui::GetWindowSize() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->Size; } @@ -3862,26 +4892,34 @@ static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) return; - window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver); + window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); // Set - if (ImLengthSqr(size) > 0.00001f) + if (size.x > 0.0f) + { + window->AutoFitFramesX = 0; + window->SizeFull.x = size.x; + } + else + { + window->AutoFitFramesX = 2; + window->AutoFitOnlyGrows = false; + } + if (size.y > 0.0f) { - window->SizeFull = size; - window->AutoFitFrames = 0; + window->AutoFitFramesY = 0; + window->SizeFull.y = size.y; } else { - // Autofit - window->AutoFitFrames = 2; + window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } } void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond) { - ImGuiWindow* window = GetCurrentWindow(); - SetWindowSize(window, size, cond); + SetWindowSize(GImGui->CurrentWindow, size, cond); } void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond) @@ -3896,7 +4934,7 @@ static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) return; - window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver); + window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver | ImGuiSetCond_Appearing); // Set window->Collapsed = collapsed; @@ -3904,14 +4942,12 @@ static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond) { - ImGuiWindow* window = GetCurrentWindow(); - SetWindowCollapsed(window, collapsed, cond); + SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); } -bool ImGui::GetWindowCollapsed() +bool ImGui::IsWindowCollapsed() { - ImGuiWindow* window = GetCurrentWindow(); - return window->Collapsed; + return GImGui->CurrentWindow->Collapsed; } void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond) @@ -3923,16 +4959,14 @@ void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond co void ImGui::SetWindowFocus() { - ImGuiWindow* window = GetCurrentWindow(); - FocusWindow(window); + FocusWindow(GImGui->CurrentWindow); } void ImGui::SetWindowFocus(const char* name) { if (name) { - ImGuiWindow* window = FindWindowByName(name); - if (window) + if (ImGuiWindow* window = FindWindowByName(name)) FocusWindow(window); } else @@ -3943,144 +4977,198 @@ void ImGui::SetWindowFocus(const char* name) void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; g.SetNextWindowPosVal = pos; g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; } +void ImGui::SetNextWindowPosCenter(ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowPosVal = ImVec2(-FLT_MAX, -FLT_MAX); + g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; +} + void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; g.SetNextWindowSizeVal = size; g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always; } +void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeConstraintCallback custom_callback, void* custom_callback_user_data) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowSizeConstraint = true; + g.SetNextWindowSizeConstraintRect = ImRect(size_min, size_max); + g.SetNextWindowSizeConstraintCallback = custom_callback; + g.SetNextWindowSizeConstraintCallbackUserData = custom_callback_user_data; +} + +void ImGui::SetNextWindowContentSize(const ImVec2& size) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowContentSizeVal = size; + g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; +} + +void ImGui::SetNextWindowContentWidth(float width) +{ + ImGuiContext& g = *GImGui; + g.SetNextWindowContentSizeVal = ImVec2(width, g.SetNextWindowContentSizeCond ? g.SetNextWindowContentSizeVal.y : 0.0f); + g.SetNextWindowContentSizeCond = ImGuiSetCond_Always; +} + void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; g.SetNextWindowCollapsedVal = collapsed; g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowFocus() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; g.SetNextWindowFocus = true; } +// In window space (not screen space!) ImVec2 ImGui::GetContentRegionMax() { - ImGuiWindow* window = GetCurrentWindow(); - ImVec2 window_padding = window->WindowPadding(); - ImVec2 mx = window->Size - window_padding; + ImGuiWindow* window = GetCurrentWindowRead(); + ImVec2 mx = window->ContentsRegionRect.Max; if (window->DC.ColumnsCount != 1) - { - mx.x = ImGui::GetColumnOffset(window->DC.ColumnsCurrent + 1); - mx.x -= window_padding.x; - } - else - { - if (window->ScrollbarY) - mx.x -= GImGui->Style.ScrollbarWidth; - } + mx.x = GetColumnOffset(window->DC.ColumnsCurrent + 1) - window->WindowPadding.x; return mx; } +ImVec2 ImGui::GetContentRegionAvail() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return GetContentRegionMax() - (window->DC.CursorPos - window->Pos); +} + +float ImGui::GetContentRegionAvailWidth() +{ + return GetContentRegionAvail().x; +} + +// In window space (not screen space!) ImVec2 ImGui::GetWindowContentRegionMin() { - ImGuiWindow* window = GetCurrentWindow(); - return ImVec2(0, window->TitleBarHeight()) + window->WindowPadding(); + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Min; } ImVec2 ImGui::GetWindowContentRegionMax() { - ImGuiWindow* window = GetCurrentWindow(); - ImVec2 m = window->Size - window->WindowPadding(); - if (window->ScrollbarY) - m.x -= GImGui->Style.ScrollbarWidth; - return m; + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Max; +} + +float ImGui::GetWindowContentRegionWidth() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x; } float ImGui::GetTextLineHeight() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; return g.FontSize; } float ImGui::GetTextLineHeightWithSpacing() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; return g.FontSize + g.Style.ItemSpacing.y; } +float ImGui::GetItemsLineHeightWithSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; +} + ImDrawList* ImGui::GetWindowDrawList() { ImGuiWindow* window = GetCurrentWindow(); return window->DrawList; } -ImFont* ImGui::GetWindowFont() +ImFont* ImGui::GetFont() { - ImGuiState& g = *GImGui; - return g.Font; + return GImGui->Font; } -float ImGui::GetWindowFontSize() +float ImGui::GetFontSize() { - ImGuiState& g = *GImGui; - return g.FontSize; + return GImGui->FontSize; +} + +ImVec2 ImGui::GetFontTexUvWhitePixel() +{ + return GImGui->FontTexUvWhitePixel; } void ImGui::SetWindowFontScale(float scale) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = window->CalcFontSize(); } -// NB: internally we store CursorPos in absolute screen coordinates because it is more convenient. -// Conversion happens as we pass the value to user, but it makes our naming convention dodgy. May want to rename 'DC.CursorPos'. +// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. +// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. ImVec2 ImGui::GetCursorPos() { - ImGuiWindow* window = GetCurrentWindow(); - return window->DC.CursorPos - window->Pos; + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos - window->Pos + window->Scroll; } float ImGui::GetCursorPosX() { - return ImGui::GetCursorPos().x; + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; } float ImGui::GetCursorPosY() { - return ImGui::GetCursorPos().y; + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; } -void ImGui::SetCursorPos(const ImVec2& pos) +void ImGui::SetCursorPos(const ImVec2& local_pos) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.CursorPos = window->Pos + pos; + window->DC.CursorPos = window->Pos - window->Scroll + local_pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } void ImGui::SetCursorPosX(float x) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.CursorPos.x = window->Pos.x + x; + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); } void ImGui::SetCursorPosY(float y) { ImGuiWindow* window = GetCurrentWindow(); - window->DC.CursorPos.y = window->Pos.y + y; + window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); } +ImVec2 ImGui::GetCursorStartPos() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->DC.CursorStartPos - window->Pos; +} + ImVec2 ImGui::GetCursorScreenPos() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos; } @@ -4088,31 +5176,69 @@ void ImGui::SetCursorScreenPos(const ImVec2& screen_pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = screen_pos; + window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } -float ImGui::GetScrollPosY() +float ImGui::GetScrollX() { - ImGuiWindow* window = GetCurrentWindow(); - return window->ScrollY; + return GImGui->CurrentWindow->Scroll.x; +} + +float ImGui::GetScrollY() +{ + return GImGui->CurrentWindow->Scroll.y; +} + +float ImGui::GetScrollMaxX() +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->SizeContents.x - window->SizeFull.x - window->ScrollbarSizes.x; } float ImGui::GetScrollMaxY() { + ImGuiWindow* window = GetCurrentWindowRead(); + return window->SizeContents.y - window->SizeFull.y - window->ScrollbarSizes.y; +} + +void ImGui::SetScrollX(float scroll_x) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.x = scroll_x; + window->ScrollTargetCenterRatio.x = 0.0f; +} + +void ImGui::SetScrollY(float scroll_y) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY + window->ScrollTargetCenterRatio.y = 0.0f; +} + +void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio) +{ + // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size ImGuiWindow* window = GetCurrentWindow(); - return window->SizeContents.y - window->SizeFull.y; + IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); + window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y); + if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y) // Minor hack to make "scroll to top" take account of WindowPadding, else it would scroll to (WindowPadding.y - ItemSpacing.y) + window->ScrollTarget.y = 0.0f; + window->ScrollTargetCenterRatio.y = center_y_ratio; } -void ImGui::SetScrollPosHere() +// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. +void ImGui::SetScrollHere(float center_y_ratio) { ImGuiWindow* window = GetCurrentWindow(); - window->NextScrollY = (window->DC.CursorPos.y + window->ScrollY) - (window->Pos.y + window->SizeFull.y * 0.5f) - (window->TitleBarHeight() + window->WindowPadding().y); + float target_y = window->DC.CursorPosPrevLine.y + (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. + SetScrollFromPosY(target_y - window->Pos.y, center_y_ratio); } void ImGui::SetKeyboardFocusHere(int offset) { ImGuiWindow* window = GetCurrentWindow(); window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; - window->FocusIdxTabRequestNext = IM_INT_MAX; + window->FocusIdxTabRequestNext = INT_MAX; } void ImGui::SetStateStorage(ImGuiStorage* tree) @@ -4123,17 +5249,17 @@ void ImGui::SetStateStorage(ImGuiStorage* tree) ImGuiStorage* ImGui::GetStateStorage() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.StateStorage; } void ImGui::TextV(const char* fmt, va_list args) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + ImGuiContext& g = *GImGui; const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); TextUnformatted(g.TempBuffer, text_end); } @@ -4148,9 +5274,9 @@ void ImGui::Text(const char* fmt, ...) void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) { - ImGui::PushStyleColor(ImGuiCol_Text, col); + PushStyleColor(ImGuiCol_Text, col); TextV(fmt, args); - ImGui::PopStyleColor(); + PopStyleColor(); } void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) @@ -4161,11 +5287,27 @@ void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) va_end(args); } +void ImGui::TextDisabledV(const char* fmt, va_list args) +{ + PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]); + TextV(fmt, args); + PopStyleColor(); +} + +void ImGui::TextDisabled(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + TextDisabledV(fmt, args); + va_end(args); +} + void ImGui::TextWrappedV(const char* fmt, va_list args) { - ImGui::PushTextWrapPos(0.0f); + bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set + if (need_wrap) PushTextWrapPos(0.0f); TextV(fmt, args); - ImGui::PopTextWrapPos(); + if (need_wrap) PopTextWrapPos(); } void ImGui::TextWrapped(const char* fmt, ...) @@ -4178,44 +5320,46 @@ void ImGui::TextWrapped(const char* fmt, ...) void ImGui::TextUnformatted(const char* text, const char* text_end) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + ImGuiContext& g = *GImGui; IM_ASSERT(text != NULL); const char* text_begin = text; if (text_end == NULL) text_end = text + strlen(text); // FIXME-OPT - const float wrap_pos_x = window->DC.TextWrapPos.back(); + const float wrap_pos_x = window->DC.TextWrapPos; const bool wrap_enabled = wrap_pos_x >= 0.0f; if (text_end - text > 2000 && !wrap_enabled) { // Long text! // Perform manual coarse clipping to optimize for long multi-line text - // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. + // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. // We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. const char* line = text; - const float line_height = ImGui::GetTextLineHeight(); + const float line_height = GetTextLineHeight(); const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset); - const ImVec4 clip_rect = window->ClipRectStack.back(); + const ImRect clip_rect = window->ClipRect; ImVec2 text_size(0,0); - if (text_pos.y <= clip_rect.w) + if (text_pos.y <= clip_rect.Max.y) { ImVec2 pos = text_pos; // Lines to skip (can't skip when logging text) if (!g.LogEnabled) { - int lines_skippable = (int)((clip_rect.y - text_pos.y) / line_height) - 1; + int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height); if (lines_skippable > 0) { int lines_skipped = 0; - while (line < text_end && lines_skipped <= lines_skippable) + while (line < text_end && lines_skipped < lines_skippable) { const char* line_end = strchr(line, '\n'); + if (!line_end) + line_end = text_end; line = line_end + 1; lines_skipped++; } @@ -4226,11 +5370,11 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) // Lines to render if (line < text_end) { - ImRect line_rect(pos, pos + ImVec2(ImGui::GetWindowWidth(), line_height)); + ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); while (line < text_end) { const char* line_end = strchr(line, '\n'); - if (IsClipped(line_rect)) + if (IsClippedEx(line_rect, NULL, false)) break; const ImVec2 line_size = CalcTextSize(line, line_end, false); @@ -4270,11 +5414,9 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); // Account of baseline offset - ImVec2 text_pos = window->DC.CursorPos; - text_pos.y += window->DC.CurrentLineTextBaseOffset; - + ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset); ImRect bb(text_pos, text_pos + text_size); - ItemSize(bb.GetSize()); + ItemSize(text_size); if (!ItemAdd(bb, NULL)) return; @@ -4285,40 +5427,40 @@ void ImGui::TextUnformatted(const char* text, const char* text_end) void ImGui::AlignFirstTextHeightToWidgets() { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height. + ImGuiContext& g = *GImGui; ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y); - ImGui::SameLine(0, 0); + SameLine(0, 0); } // Add a label+text combo aligned to other label+value widgets void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const float w = ImGui::CalcItemWidth(); - - const char* value_text_begin = &g.TempBuffer[0]; - const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + style.FramePadding.x*2, label_size.y + style.FramePadding.y*2)); - const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + style.FramePadding.x*2 + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); + const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); + const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, NULL)) return; // Render - RenderTextClipped(ImVec2(value_bb.Min.x, value_bb.Min.y + style.FramePadding.y), value_text_begin, value_text_end, NULL, value_bb.Max); - RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); + const char* value_text_begin = &g.TempBuffer[0]; + const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f)); + if (label_size.x > 0.0f) + RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); } void ImGui::LabelText(const char* label, const char* fmt, ...) @@ -4331,58 +5473,67 @@ void ImGui::LabelText(const char* label, const char* fmt, ...) static inline bool IsWindowContentHoverable(ImGuiWindow* window) { - ImGuiState& g = *GImGui; - - ImGuiWindow* focused_window = g.FocusedWindow; - if (focused_window && (focused_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_window->WasVisible && focused_window != window) - return false; + // An active popup disable hovering on other windows (apart from its own children) + ImGuiContext& g = *GImGui; + if (ImGuiWindow* focused_window = g.FocusedWindow) + if (ImGuiWindow* focused_root_window = focused_window->RootWindow) + if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasActive && focused_root_window != window->RootWindow) + return false; return true; } -static bool IsHovered(const ImRect& bb, ImGuiID id) +bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) { - ImGuiState& g = *GImGui; - if (g.HoveredId == 0) + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindow(); + + if (flags & ImGuiButtonFlags_Disabled) { - ImGuiWindow* window = GetCurrentWindow(); - if (g.HoveredRootWindow == window->RootWindow) - if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdIsFocusedOnly) && IsMouseHoveringRect(bb)) - if (IsWindowContentHoverable(g.HoveredRootWindow)) - return true; + if (out_hovered) *out_hovered = false; + if (out_held) *out_held = false; + if (g.ActiveId == id) SetActiveID(0); + return false; } - return false; -} -static bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, bool allow_key_modifiers, bool repeat, bool pressed_on_click) -{ - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0) + flags |= ImGuiButtonFlags_PressedOnClickRelease; - const bool hovered = IsHovered(bb, id); bool pressed = false; + bool hovered = IsHovered(bb, id, (flags & ImGuiButtonFlags_FlattenChilds) != 0); if (hovered) { - g.HoveredId = id; - if (allow_key_modifiers || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) + SetHoveredID(id); + if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) { - if (g.IO.MouseClicked[0]) + // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat + // PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds + // PressedOnClick | <on click> | <on click> <on repeat> <on repeat> .. + // PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release) + // PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> .. + if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) { - if (pressed_on_click) - { - pressed = true; - SetActiveId(0); - } - else - { - SetActiveId(id); - } + SetActiveID(id, window); // Hold on ID FocusWindow(window); + g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; } - else if (repeat && g.ActiveId && ImGui::IsMouseClicked(0, true)) + if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0])) { pressed = true; + SetActiveID(0); + FocusWindow(window); + } + if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0]) + { + if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release> + pressed = true; + SetActiveID(0); } + + // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). + // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. + if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true)) + pressed = true; } } @@ -4395,125 +5546,119 @@ static bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool } else { - if (hovered) - pressed = true; - SetActiveId(0); + if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease)) + if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release> + pressed = true; + SetActiveID(0); } } + // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one. + if (hovered && (flags & ImGuiButtonFlags_AllowOverlapMode) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0)) + hovered = pressed = held = false; + if (out_hovered) *out_hovered = hovered; if (out_held) *out_held = held; return pressed; } -bool ImGui::Button(const char* label, const ImVec2& size_arg, bool repeat_when_held) +bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImVec2 size(size_arg.x != 0.0f ? size_arg.x : (label_size.x + style.FramePadding.x*2), size_arg.y != 0.0f ? size_arg.y : (label_size.y + style.FramePadding.y*2)); - const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ImVec2 pos = window->DC.CursorPos; + if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) + pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y; + ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); + + const ImRect bb(pos, pos + size); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; + if (window->DC.ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true, repeat_when_held); + bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render - const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); + RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); - const ImVec2 off = ImVec2(ImMax(0.0f, size.x - label_size.x) * 0.5f, ImMax(0.0f, size.y - label_size.y) * 0.5f); // Center (only applies if we explicitly gave a size bigger than the text size, which isn't the common path) - RenderTextClipped(bb.Min + off, label, NULL, &label_size, bb.Max); // Render clip (only applies if we explicitly gave a size smaller than the text size, which isn't the commmon path) + // Automatically close popups + //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + // CloseCurrentPopup(); return pressed; } -// Small buttons fits within text without additional spacing. -bool ImGui::SmallButton(const char* label) +bool ImGui::Button(const char* label, const ImVec2& size_arg) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return false; - - const ImGuiStyle& style = g.Style; - const ImGuiID id = window->GetID(label); - const ImVec2 label_size = CalcTextSize(label, NULL, true); - - ImVec2 text_pos = window->DC.CursorPos; - text_pos.y += window->DC.CurrentLineTextBaseOffset; - ImRect bb(text_pos, text_pos + label_size + ImVec2(style.FramePadding.x*2,0)); - ItemSize(bb); - if (!ItemAdd(bb, &id)) - return false; - - bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); - - // Render - const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); - RenderFrame(bb.Min, bb.Max, col); - RenderText(bb.Min + ImVec2(style.FramePadding.x,0), label); + return ButtonEx(label, size_arg, 0); +} +// Small buttons fits within text without additional vertical spacing. +bool ImGui::SmallButton(const char* label) +{ + ImGuiContext& g = *GImGui; + float backup_padding_y = g.Style.FramePadding.y; + g.Style.FramePadding.y = 0.0f; + bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine); + g.Style.FramePadding.y = backup_padding_y; return pressed; } // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) -bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size) +bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiID id = window->GetID(str_id); + ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); + bool pressed = ButtonBehavior(bb, id, &hovered, &held); return pressed; } // Upper-right button to close a window. -static bool CloseWindowButton(bool* p_opened) +bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) { ImGuiWindow* window = GetCurrentWindow(); - const ImGuiID id = window->GetID("#CLOSE"); - const float size = window->TitleBarHeight() - 4.0f; - const ImRect bb(window->Rect().GetTR() + ImVec2(-3.0f-size,2.0f), window->Rect().GetTR() + ImVec2(-3.0f,2.0f+size)); + const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius)); bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); + bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render - const ImU32 col = window->Color((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); const ImVec2 center = bb.GetCenter(); - window->DrawList->AddCircleFilled(center, ImMax(2.0f,size*0.5f), col, 16); + window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), col, 12); - const float cross_extent = (size * 0.5f * 0.7071f) - 1.0f; + const float cross_extent = (radius * 0.7071f) - 1.0f; if (hovered) { - window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), window->Color(ImGuiCol_Text)); - window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), window->Color(ImGuiCol_Text)); + window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), GetColorU32(ImGuiCol_Text)); + window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), GetColorU32(ImGuiCol_Text)); } - if (p_opened != NULL && pressed) - *p_opened = !*p_opened; - return pressed; } @@ -4532,12 +5677,12 @@ void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& if (border_col.w > 0.0f) { - window->DrawList->AddRect(bb.Min, bb.Max, window->Color(border_col), 0.0f); - window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, window->Color(tint_col)); + window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f); + window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col)); } else { - window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, window->Color(tint_col)); + window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col)); } } @@ -4547,36 +5692,35 @@ void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& // The color used are the button colors. bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; // Default to using texture ID as ID. User can still push string/integer prefixes. - // We could hash the size/uv to create a unique ID but that would prevent the user from animating buttons. - ImGui::PushID((void *)user_texture_id); + // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV. + PushID((void *)user_texture_id); const ImGuiID id = window->GetID("#image"); - ImGui::PopID(); + PopID(); const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2); - const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); + const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); + bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render - const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); - if (padding.x > 0.0f || padding.y > 0.0f) - RenderFrame(bb.Min, bb.Max, col); + const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); + RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding)); if (bg_col.w > 0.0f) - window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, window->Color(bg_col)); - window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, window->Color(tint_col)); + window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col)); + window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); return pressed; } @@ -4584,10 +5728,10 @@ bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const I // Start logging ImGui output to TTY void ImGui::LogToTTY(int max_depth) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; if (g.LogEnabled) return; + ImGuiWindow* window = GetCurrentWindowRead(); g.LogEnabled = true; g.LogFile = stdout; @@ -4599,10 +5743,11 @@ void ImGui::LogToTTY(int max_depth) // Start logging ImGui output to given file void ImGui::LogToFile(int max_depth, const char* filename) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; if (g.LogEnabled) return; + ImGuiWindow* window = GetCurrentWindowRead(); + if (!filename) { filename = g.IO.LogFilename; @@ -4625,10 +5770,10 @@ void ImGui::LogToFile(int max_depth, const char* filename) // Start logging ImGui output to clipboard void ImGui::LogToClipboard(int max_depth) { - ImGuiWindow* window = GetCurrentWindow(); - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (g.LogEnabled) return; + ImGuiWindow* window = GetCurrentWindowRead(); g.LogEnabled = true; g.LogFile = NULL; @@ -4639,11 +5784,11 @@ void ImGui::LogToClipboard(int max_depth) void ImGui::LogFinish() { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; - ImGui::LogText(STR_NEWLINE); + LogText(IM_NEWLINE); g.LogEnabled = false; if (g.LogFile != NULL) { @@ -4664,22 +5809,18 @@ void ImGui::LogFinish() // Helper to display logging buttons void ImGui::LogButtons() { - ImGuiState& g = *GImGui; - - ImGui::PushID("LogButtons"); - const bool log_to_tty = ImGui::Button("Log To TTY"); - ImGui::SameLine(); - const bool log_to_file = ImGui::Button("Log To File"); - ImGui::SameLine(); - const bool log_to_clipboard = ImGui::Button("Log To Clipboard"); - ImGui::SameLine(); - - ImGui::PushItemWidth(80.0f); - ImGui::PushAllowKeyboardFocus(false); - ImGui::SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); - ImGui::PopAllowKeyboardFocus(); - ImGui::PopItemWidth(); - ImGui::PopID(); + ImGuiContext& g = *GImGui; + + PushID("LogButtons"); + const bool log_to_tty = Button("Log To TTY"); SameLine(); + const bool log_to_file = Button("Log To File"); SameLine(); + const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); + PushItemWidth(80.0f); + PushAllowKeyboardFocus(false); + SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); + PopAllowKeyboardFocus(); + PopItemWidth(); + PopID(); // Start logging at the end of the function so that the buttons don't appear in the log if (log_to_tty) @@ -4690,31 +5831,23 @@ void ImGui::LogButtons() LogToClipboard(g.LogAutoExpandMaxDepth); } -bool ImGui::CollapsingHeader(const char* label, const char* str_id, bool display_frame, bool default_open) +bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return false; - - const ImGuiStyle& style = g.Style; - - IM_ASSERT(str_id != NULL || label != NULL); - if (str_id == NULL) - str_id = label; - if (label == NULL) - label = str_id; - const ImGuiID id = window->GetID(str_id); + if (flags & ImGuiTreeNodeFlags_Leaf) + return true; // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions) + ImGuiContext& g = *GImGui; + ImGuiWindow* window = g.CurrentWindow; ImGuiStorage* storage = window->DC.StateStorage; - bool opened; - if (g.SetNextTreeNodeOpenedCond != 0) + + bool is_open; + if (g.SetNextTreeNodeOpenCond != 0) { - if (g.SetNextTreeNodeOpenedCond & ImGuiSetCond_Always) + if (g.SetNextTreeNodeOpenCond & ImGuiSetCond_Always) { - opened = g.SetNextTreeNodeOpenedVal; - storage->SetInt(id, opened); + is_open = g.SetNextTreeNodeOpenVal; + storage->SetInt(id, is_open); } else { @@ -4722,218 +5855,275 @@ bool ImGui::CollapsingHeader(const char* label, const char* str_id, bool display const int stored_value = storage->GetInt(id, -1); if (stored_value == -1) { - opened = g.SetNextTreeNodeOpenedVal; - storage->SetInt(id, opened); + is_open = g.SetNextTreeNodeOpenVal; + storage->SetInt(id, is_open); } else { - opened = stored_value != 0; + is_open = stored_value != 0; } } - g.SetNextTreeNodeOpenedCond = 0; + g.SetNextTreeNodeOpenCond = 0; } else { - opened = storage->GetInt(id, default_open) != 0; + is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; } - // Framed header expand a little outside the default padding - const ImVec2 window_padding = window->WindowPadding(); - const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImVec2 pos_min = window->DC.CursorPos; - const ImVec2 pos_max = window->Pos + GetContentRegionMax(); - ImRect bb = ImRect(pos_min, ImVec2(pos_max.x, pos_min.y + label_size.y)); + // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). + // NB- If we are above max depth we still allow manually opened nodes to be logged. + if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) + is_open = true; + + return is_open; +} + +bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; + const ImVec2 padding = display_frame ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f); + + if (!label_end) + label_end = FindRenderedTextEnd(label); + const ImVec2 label_size = CalcTextSize(label, label_end, false); + + // We vertically grow up to current line height up the typical widget height. + const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset - padding.y); // Latch before ItemSize changes it + const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); + ImRect bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height)); if (display_frame) { - bb.Min.x -= window_padding.x*0.5f - 1; - bb.Max.x += window_padding.x*0.5f - 1; - bb.Max.y += style.FramePadding.y * 2; + // Framed header expand a little outside the default padding + bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1; + bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1; } - // FIXME: we don't provide our width so that it doesn't get feed back into AutoFit. Should manage that better so we can still hover without extending ContentsSize - const ImRect text_bb(bb.Min, bb.Min + ImVec2(g.FontSize + style.FramePadding.x*2*2,0) + label_size); - ItemSize(ImVec2(text_bb.GetSize().x, bb.GetSize().y), display_frame ? style.FramePadding.y : 0.0f); - - // When logging is enabled, if automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). - // NB- If we are above max depth we still allow manually opened nodes to be logged. - if (g.LogEnabled && !display_frame && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) - opened = true; + const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing + const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser + ItemSize(ImVec2(text_width, frame_height), text_base_offset_y); - if (!ItemAdd(bb, &id)) - return opened; + // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing + // (Ideally we'd want to add a flag for the user to specify we want want the hit test to be done up to the right side of the content or not) + const ImRect interact_bb = display_frame ? bb : ImRect(bb.Min.x, bb.Min.y, bb.Min.x + text_width + style.ItemSpacing.x*2, bb.Max.y); + bool is_open = TreeNodeBehaviorIsOpen(id, flags); + if (!ItemAdd(interact_bb, &id)) + { + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushRawID(id); + return is_open; + } - bool hovered, held; - bool pressed = ButtonBehavior(display_frame ? bb : text_bb, id, &hovered, &held, false); - if (pressed) + // Flags that affects opening behavior: + // - 0(default) ..................... single-click anywhere to open + // - OpenOnDoubleClick .............. double-click anywhere to open + // - OpenOnArrow .................... single-click on arrow to open + // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open + ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowOverlapMode) ? ImGuiButtonFlags_AllowOverlapMode : 0); + if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0); + bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); + if (pressed && !(flags & ImGuiTreeNodeFlags_Leaf)) { - opened = !opened; - storage->SetInt(id, opened); + bool toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)); + if (flags & ImGuiTreeNodeFlags_OpenOnArrow) + toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)); + if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) + toggled |= g.IO.MouseDoubleClicked[0]; + if (toggled) + { + is_open = !is_open; + window->DC.StateStorage->SetInt(id, is_open); + } } + if (flags & ImGuiTreeNodeFlags_AllowOverlapMode) + SetItemAllowOverlap(); // Render - const ImU32 col = window->Color((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + const ImVec2 text_pos = bb.Min + ImVec2(text_offset_x, padding.y + text_base_offset_y); if (display_frame) { // Framed type RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); - RenderCollapseTriangle(bb.Min + style.FramePadding, opened, 1.0f, true); + RenderCollapseTriangle(bb.Min + padding + ImVec2(0.0f, text_base_offset_y), is_open, 1.0f, true); if (g.LogEnabled) { // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. const char log_prefix[] = "\n##"; - LogText(bb.Min + style.FramePadding, log_prefix, log_prefix+3); + const char log_suffix[] = "##"; + LogRenderedText(text_pos, log_prefix, log_prefix+3); + RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); + LogRenderedText(text_pos, log_suffix+1, log_suffix+3); } - RenderText(bb.Min + style.FramePadding + ImVec2(g.FontSize + style.FramePadding.x*2,0), label); - if (g.LogEnabled) + else { - const char log_suffix[] = "##"; - LogText(bb.Min + style.FramePadding, log_suffix, log_suffix+2); + RenderTextClipped(text_pos, bb.Max, label, label_end, &label_size); } } else { // Unframed typed for tree nodes - if ((held && hovered) || hovered) + if (hovered || (flags & ImGuiTreeNodeFlags_Selected)) RenderFrame(bb.Min, bb.Max, col, false); - RenderCollapseTriangle(bb.Min + ImVec2(style.FramePadding.x, g.FontSize*0.15f), opened, 0.70f, false); + + if (flags & ImGuiTreeNodeFlags_Bullet) + RenderBullet(bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y)); + else if (!(flags & ImGuiTreeNodeFlags_Leaf)) + RenderCollapseTriangle(bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open, 0.70f, false); if (g.LogEnabled) - LogText(bb.Min, ">"); - RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x*2,0), label); + LogRenderedText(text_pos, ">"); + RenderText(text_pos, label, label_end, false); } - return opened; + if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) + TreePushRawID(id); + return is_open; } -void ImGui::Bullet() +// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). +// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). +bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) - return; - - const ImGuiStyle& style = g.Style; - const float line_height = g.FontSize; - const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(line_height, line_height)); - ItemSize(bb); - if (!ItemAdd(bb, NULL)) - return; - - // Render - const float bullet_size = line_height*0.15f; - window->DrawList->AddCircleFilled(bb.Min + ImVec2(style.FramePadding.x + line_height*0.5f, line_height*0.5f), bullet_size, window->Color(ImGuiCol_Text)); + return false; - // Stay on same line - ImGui::SameLine(0, -1); + return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label); } -// Text with a little bullet aligned to the typical tree node. -void ImGui::BulletTextV(const char* fmt, va_list args) +bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) - return; - - const char* text_begin = g.TempBuffer; - const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return false; - const ImGuiStyle& style = g.Style; - const float line_height = g.FontSize; - const ImVec2 label_size = CalcTextSize(text_begin, text_end, true); - const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(line_height + (label_size.x > 0.0f ? (style.FramePadding.x*2) : 0.0f),0) + label_size); // Empty text doesn't add padding - ItemSize(bb); - if (!ItemAdd(bb, NULL)) - return; + if (p_open && !*p_open) + return false; - // Render - const float bullet_size = line_height*0.15f; - window->DrawList->AddCircleFilled(bb.Min + ImVec2(style.FramePadding.x + line_height*0.5f, line_height*0.5f), bullet_size, window->Color(ImGuiCol_Text)); - RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2,0), text_begin, text_end); -} + ImGuiID id = window->GetID(label); + bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowOverlapMode : 0), label); + if (p_open) + { + // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. + ImGuiContext& g = *GImGui; + float button_sz = g.FontSize * 0.5f; + if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz)) + *p_open = false; + } -void ImGui::BulletText(const char* fmt, ...) -{ - va_list args; - va_start(args, fmt); - BulletTextV(fmt, args); - va_end(args); + return is_open; } -// If returning 'true' the node is open and the user is responsible for calling TreePop -bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) +bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); - - if (!str_id || !str_id[0]) - str_id = fmt; - - ImGui::PushID(str_id); - const bool opened = ImGui::CollapsingHeader(g.TempBuffer, "", false); - ImGui::PopID(); - - if (opened) - ImGui::TreePush(str_id); - - return opened; + return TreeNodeBehavior(window->GetID(label), flags, label, NULL); } -bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) +bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { - va_list args; - va_start(args, fmt); - bool s = TreeNodeV(str_id, fmt, args); - va_end(args); - return s; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end); } -// If returning 'true' the node is open and the user is responsible for calling TreePop -bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) +bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); - - if (!ptr_id) - ptr_id = fmt; - - ImGui::PushID(ptr_id); - const bool opened = ImGui::CollapsingHeader(g.TempBuffer, "", false); - ImGui::PopID(); + ImGuiContext& g = *GImGui; + const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end); +} - if (opened) - ImGui::TreePush(ptr_id); +bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) +{ + return TreeNodeExV(str_id, 0, fmt, args); +} - return opened; +bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) +{ + return TreeNodeExV(ptr_id, 0, fmt, args); } -bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) +bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); - bool s = TreeNodeV(ptr_id, fmt, args); + bool is_open = TreeNodeExV(str_id, flags, fmt, args); va_end(args); - return s; + return is_open; } -bool ImGui::TreeNode(const char* str_label_id) +bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { - return TreeNode(str_label_id, "%s", str_label_id); + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); + va_end(args); + return is_open; } -void ImGui::SetNextTreeNodeOpened(bool opened, ImGuiSetCond cond) +bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) { - ImGuiState& g = *GImGui; - g.SetNextTreeNodeOpenedVal = opened; - g.SetNextTreeNodeOpenedCond = cond ? cond : ImGuiSetCond_Always; -} + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(str_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); + va_end(args); + return is_open; +} + +bool ImGui::TreeNode(const char* label) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + return TreeNodeBehavior(window->GetID(label), 0, label, NULL); +} + +void ImGui::TreeAdvanceToLabelPos() +{ + ImGuiContext& g = *GImGui; + g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing(); +} + +// Horizontal distance preceding label when using TreeNode() or Bullet() +float ImGui::GetTreeNodeToLabelSpacing() +{ + ImGuiContext& g = *GImGui; + return g.FontSize + (g.Style.FramePadding.x * 2.0f); +} + +void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiSetCond cond) +{ + ImGuiContext& g = *GImGui; + g.SetNextTreeNodeOpenVal = is_open; + g.SetNextTreeNodeOpenCond = cond ? cond : ImGuiSetCond_Always; +} void ImGui::PushID(const char* str_id) { @@ -4941,13 +6131,19 @@ void ImGui::PushID(const char* str_id) window->IDStack.push_back(window->GetID(str_id)); } +void ImGui::PushID(const char* str_id_begin, const char* str_id_end) +{ + ImGuiWindow* window = GetCurrentWindow(); + window->IDStack.push_back(window->GetID(str_id_begin, str_id_end)); +} + void ImGui::PushID(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(ptr_id)); } -void ImGui::PushID(const int int_id) +void ImGui::PushID(int int_id) { const void* ptr_id = (void*)(intptr_t)int_id; ImGuiWindow* window = GetCurrentWindow(); @@ -4962,19 +6158,120 @@ void ImGui::PopID() ImGuiID ImGui::GetID(const char* str_id) { - ImGuiWindow* window = GetCurrentWindow(); - return window->GetID(str_id); + return GImGui->CurrentWindow->GetID(str_id); +} + +ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) +{ + return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end); } ImGuiID ImGui::GetID(const void* ptr_id) +{ + return GImGui->CurrentWindow->GetID(ptr_id); +} + +void ImGui::Bullet() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); + ItemSize(bb); + if (!ItemAdd(bb, NULL)) + { + SameLine(0, style.FramePadding.x*2); + return; + } + + // Render and stay on same line + RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + SameLine(0, style.FramePadding.x*2); +} + +// Text with a little bullet aligned to the typical tree node. +void ImGui::BulletTextV(const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); - return window->GetID(ptr_id); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + const char* text_begin = g.TempBuffer; + const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); + const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); + const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it + const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding + ItemSize(bb); + if (!ItemAdd(bb, NULL)) + return; + + // Render + RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); + RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false); +} + +void ImGui::BulletText(const char* fmt, ...) +{ + va_list args; + va_start(args, fmt); + BulletTextV(fmt, args); + va_end(args); +} + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size) +{ + if (data_type == ImGuiDataType_Int) + ImFormatString(buf, buf_size, display_format, *(int*)data_ptr); + else if (data_type == ImGuiDataType_Float) + ImFormatString(buf, buf_size, display_format, *(float*)data_ptr); +} + +static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size) +{ + if (data_type == ImGuiDataType_Int) + { + if (decimal_precision < 0) + ImFormatString(buf, buf_size, "%d", *(int*)data_ptr); + else + ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr); + } + else if (data_type == ImGuiDataType_Float) + { + if (decimal_precision < 0) + ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? + else + ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr); + } +} + +static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* value1, const void* value2)// Store into value1 +{ + if (data_type == ImGuiDataType_Int) + { + if (op == '+') + *(int*)value1 = *(int*)value1 + *(const int*)value2; + else if (op == '-') + *(int*)value1 = *(int*)value1 - *(const int*)value2; + } + else if (data_type == ImGuiDataType_Float) + { + if (op == '+') + *(float*)value1 = *(float*)value1 + *(const float*)value2; + else if (op == '-') + *(float*)value1 = *(float*)value1 - *(const float*)value2; + } } // User can input math operators (e.g. +100) to edit a numerical values. -// NB: only call right after InputText because we are using its InitialValue storage -static void ApplyNumericalTextInput(const char* buf, float *v) +static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format) { while (ImCharIsSpace(*buf)) buf++; @@ -4993,69 +6290,84 @@ static void ApplyNumericalTextInput(const char* buf, float *v) op = 0; } if (!buf[0]) - return; + return false; - float ref_v = *v; - if (op) - if (sscanf(GImGui->InputTextState.InitialText, "%f", &ref_v) < 1) - return; + if (data_type == ImGuiDataType_Int) + { + if (!scalar_format) + scalar_format = "%d"; + int* v = (int*)data_ptr; + const int old_v = *v; + int arg0 = *v; + if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) + return false; - float op_v = 0.0f; - if (sscanf(buf, "%f", &op_v) < 1) - return; + // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision + float arg1 = 0.0f; + if (op == '+') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 + arg1); } // Add (use "+-" to subtract) + else if (op == '*') { if (sscanf(buf, "%f", &arg1) == 1) *v = (int)(arg0 * arg1); } // Multiply + else if (op == '/') { if (sscanf(buf, "%f", &arg1) == 1 && arg1 != 0.0f) *v = (int)(arg0 / arg1); }// Divide + else { if (sscanf(buf, scalar_format, &arg0) == 1) *v = arg0; } // Assign constant + return (old_v != *v); + } + else if (data_type == ImGuiDataType_Float) + { + // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in + scalar_format = "%f"; + float* v = (float*)data_ptr; + const float old_v = *v; + float arg0 = *v; + if (op && sscanf(initial_value_buf, scalar_format, &arg0) < 1) + return false; - if (op == '+') - *v = ref_v + op_v; - else if (op == '*') - *v = ref_v * op_v; - else if (op == '/') - { - if (op_v == 0.0f) - return; - *v = ref_v / op_v; + float arg1 = 0.0f; + if (sscanf(buf, scalar_format, &arg1) < 1) + return false; + if (op == '+') { *v = arg0 + arg1; } // Add (use "+-" to subtract) + else if (op == '*') { *v = arg0 * arg1; } // Multiply + else if (op == '/') { if (arg1 != 0.0f) *v = arg0 / arg1; } // Divide + else { *v = arg1; } // Assign constant + return (old_v != *v); } - else - *v = op_v; + + return false; } // Create text input in place of a slider (when CTRL+Clicking on slider) -static bool SliderFloatAsInputText(const char* label, float* v, ImGuiID id, int decimal_precision) +bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - char text_buf[64]; - ImFormatString(text_buf, IM_ARRAYSIZE(text_buf), "%.*f", decimal_precision, *v); - - SetActiveId(g.ScalarAsInputTextId); - g.HoveredId = 0; - // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen) - window->FocusItemUnregister(); + SetActiveID(g.ScalarAsInputTextId, window); + SetHoveredID(0); + FocusableItemUnregister(window); - bool value_changed = ImGui::InputText(label, text_buf, IM_ARRAYSIZE(text_buf), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll); + char buf[32]; + DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf)); + bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll); if (g.ScalarAsInputTextId == 0) { // First frame IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible) g.ScalarAsInputTextId = g.ActiveId; - g.HoveredId = id; + SetHoveredID(id); } else if (g.ActiveId != g.ScalarAsInputTextId) { // Release g.ScalarAsInputTextId = 0; } - if (value_changed) - { - ApplyNumericalTextInput(text_buf, v); - } - return value_changed; + if (text_value_changed) + return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL); + return false; } // Parse display precision back from the display format string -static void ParseFormat(const char* fmt, int& decimal_precision) +int ImGui::ParseFormatPrecision(const char* fmt, int default_precision) { + int precision = default_precision; while ((fmt = strchr(fmt, '%')) != NULL) { fmt++; @@ -5064,36 +6376,54 @@ static void ParseFormat(const char* fmt, int& decimal_precision) fmt++; if (*fmt == '.') { - decimal_precision = atoi(fmt + 1); - if (decimal_precision < 0 || decimal_precision > 10) - decimal_precision = 3; + precision = atoi(fmt + 1); + if (precision < 0 || precision > 10) + precision = default_precision; } break; } + return precision; +} + +float ImGui::RoundScalar(float value, int decimal_precision) +{ + // Round past decimal precision + // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0 + // FIXME: Investigate better rounding methods + static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; + float min_step = (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision); + bool negative = value < 0.0f; + value = fabsf(value); + float remainder = fmodf(value, min_step); + if (remainder <= min_step*0.5f) + value -= remainder; + else + value += (min_step - remainder); + return negative ? -value : value; } -static bool SliderBehavior(const ImRect& frame_bb, const ImRect& slider_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, bool horizontal) +bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = g.Style; // Draw frame - RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); const bool is_non_linear = fabsf(power - 1.0f) > 0.0001f; + const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0; - const float slider_sz = horizontal ? slider_bb.GetWidth() : slider_bb.GetHeight(); + const float grab_padding = 2.0f; + const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f); float grab_sz; if (decimal_precision > 0) grab_sz = ImMin(style.GrabMinSize, slider_sz); else grab_sz = ImMin(ImMax(1.0f * (slider_sz / (v_max-v_min+1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit const float slider_usable_sz = slider_sz - grab_sz; - const float slider_usable_pos_min = (horizontal ? slider_bb.Min.x : slider_bb.Min.y) + grab_sz*0.5f; - const float slider_usable_pos_max = (horizontal ? slider_bb.Max.x : slider_bb.Max.y) - grab_sz*0.5f; - - bool value_changed = false; + const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f; + const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f; // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f float linear_zero_pos = 0.0f; // 0.0->1.0f @@ -5111,13 +6441,14 @@ static bool SliderBehavior(const ImRect& frame_bb, const ImRect& slider_bb, ImGu } // Process clicking on the slider + bool value_changed = false; if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { - const float mouse_abs_pos = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; + const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; float normalized_pos = ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f); - if (!horizontal) + if (!is_horizontal) normalized_pos = 1.0f - normalized_pos; float new_value; @@ -5129,13 +6460,13 @@ static bool SliderBehavior(const ImRect& frame_bb, const ImRect& slider_bb, ImGu // Negative: rescale to the negative range before powering float a = 1.0f - (normalized_pos / linear_zero_pos); a = powf(a, power); - new_value = ImLerp(ImMin(v_max,0.f), v_min, a); + new_value = ImLerp(ImMin(v_max,0.0f), v_min, a); } else { // Positive: rescale to the positive range before powering float a; - if (fabsf(linear_zero_pos - 1.0f) > 1.e-6) + if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f) a = (normalized_pos - linear_zero_pos) / (1.0f - linear_zero_pos); else a = normalized_pos; @@ -5150,15 +6481,7 @@ static bool SliderBehavior(const ImRect& frame_bb, const ImRect& slider_bb, ImGu } // Round past decimal precision - // 0->1, 1->0.1, 2->0.01, etc. - // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0 - const float min_step = 1.0f / powf(10.0f, (float)decimal_precision); - const float remainder = fmodf(new_value, min_step); - if (remainder <= min_step*0.5f) - new_value -= remainder; - else - new_value += (min_step - remainder); - + new_value = RoundScalar(new_value, decimal_precision); if (*v != new_value) { *v = new_value; @@ -5167,7 +6490,7 @@ static bool SliderBehavior(const ImRect& frame_bb, const ImRect& slider_bb, ImGu } else { - SetActiveId(0); + SetActiveID(0); } } @@ -5194,15 +6517,15 @@ static bool SliderBehavior(const ImRect& frame_bb, const ImRect& slider_bb, ImGu } // Draw - if (!horizontal) + if (!is_horizontal) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); ImRect grab_bb; - if (horizontal) - grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + 2.0f), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - 2.0f)); + if (is_horizontal) + grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding)); else - grab_bb = ImRect(ImVec2(frame_bb.Min.x + 2.0f, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - 2.0f, grab_pos + grab_sz*0.5f)); - window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, window->Color(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab)); + grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f)); + window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); return value_changed; } @@ -5214,18 +6537,17 @@ static bool SliderBehavior(const ImRect& frame_bb, const ImRect& slider_bb, ImGu // "Gold: %.0f" Gold: 1 bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = ImGui::CalcItemWidth(); + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); - const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); // NB- we don't call ItemSize() yet because we may turn into a text edit box below @@ -5237,61 +6559,57 @@ bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, c const bool hovered = IsHovered(frame_bb, id); if (hovered) - g.HoveredId = id; + SetHoveredID(id); if (!display_format) display_format = "%.3f"; - int decimal_precision = 3; - ParseFormat(display_format, decimal_precision); + int decimal_precision = ParseFormatPrecision(display_format, 3); // Tabbing or CTRL-clicking on Slider turns it into an input box bool start_text_input = false; - const bool tab_focus_requested = window->FocusItemRegister(g.ActiveId == id); + const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); if (tab_focus_requested || (hovered && g.IO.MouseClicked[0])) { - SetActiveId(id); + SetActiveID(id, window); FocusWindow(window); - const bool is_ctrl_down = g.IO.KeyCtrl; - if (tab_focus_requested || is_ctrl_down) + if (tab_focus_requested || g.IO.KeyCtrl) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) - return SliderFloatAsInputText(label, v, id, decimal_precision); + return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); ItemSize(total_bb, style.FramePadding.y); // Actual slider behavior + render grab - const bool value_changed = SliderBehavior(frame_bb, inner_bb, id, v, v_min, v_max, power, decimal_precision, true); + const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); - const ImVec2 value_text_size = CalcTextSize(value_buf, value_buf_end, true); - RenderTextClipped(ImVec2(ImMax(frame_bb.Min.x + style.FramePadding.x, inner_bb.GetCenter().x - value_text_size.x*0.5f), frame_bb.Min.y + style.FramePadding.y), value_buf, value_buf_end, &value_text_size, frame_bb.Max); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); if (label_size.x > 0.0f) - RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); - const ImRect slider_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(bb, style.FramePadding.y); @@ -5300,40 +6618,37 @@ bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float const bool hovered = IsHovered(frame_bb, id); if (hovered) - g.HoveredId = id; + SetHoveredID(id); if (!display_format) display_format = "%.3f"; - int decimal_precision = 3; - ParseFormat(display_format, decimal_precision); + int decimal_precision = ParseFormatPrecision(display_format, 3); if (hovered && g.IO.MouseClicked[0]) { - SetActiveId(id); + SetActiveID(id, window); FocusWindow(window); } // Actual slider behavior + render grab - bool value_changed = SliderBehavior(frame_bb, slider_bb, id, v, v_min, v_max, power, decimal_precision, false); + bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. // For the vertical slider we allow centered text to overlap the frame padding char value_buf[64]; char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); - const ImVec2 value_text_size = CalcTextSize(value_buf, value_buf_end, true); - RenderTextClipped(ImVec2(ImMax(frame_bb.Min.x, slider_bb.GetCenter().x - value_text_size.x*0.5f), frame_bb.Min.y + style.FramePadding.y), value_buf, value_buf_end, &value_text_size, frame_bb.Max); - + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f)); if (label_size.x > 0.0f) - RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, slider_bb.Min.y), label); + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max) { - float v_deg = (*v_rad) * 360.0f / (2*PI); - bool value_changed = ImGui::SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f); - *v_rad = v_deg * (2*PI) / 360.0f; + float v_deg = (*v_rad) * 360.0f / (2*IM_PI); + bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f); + *v_rad = v_deg * (2*IM_PI) / 360.0f; return value_changed; } @@ -5342,7 +6657,7 @@ bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const cha if (!display_format) display_format = "%.0f"; float v_f = (float)*v; - bool value_changed = ImGui::SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); + bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } @@ -5352,45 +6667,35 @@ bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, if (!display_format) display_format = "%.0f"; float v_f = (float)*v; - bool value_changed = ImGui::VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); + bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } // Add multiple sliders on 1 line for compact edition of multiple components -static bool SliderFloatN(const char* label, float v[3], int components, float v_min, float v_max, const char* display_format, float power) +bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - const ImGuiStyle& style = g.Style; - const float w_full = ImGui::CalcItemWidth(); - const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1))); - + ImGuiContext& g = *GImGui; bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); - ImGui::PushItemWidth(w_item_one); + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { - ImGui::PushID(i); - if (i + 1 == components) - { - ImGui::PopItemWidth(); - ImGui::PushItemWidth(w_item_last); - } - value_changed |= ImGui::SliderFloat("##v", &v[i], v_min, v_max, display_format, power); - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); - ImGui::PopID(); + PushID(i); + value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); } - ImGui::PopItemWidth(); - ImGui::PopID(); + PopID(); - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - ImGui::EndGroup(); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); return value_changed; } @@ -5410,39 +6715,29 @@ bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max return SliderFloatN(label, v, 4, v_min, v_max, display_format, power); } -static bool SliderIntN(const char* label, int v[3], int components, int v_min, int v_max, const char* display_format) +bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - const ImGuiStyle& style = g.Style; - const float w_full = ImGui::CalcItemWidth(); - const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1))); - + ImGuiContext& g = *GImGui; bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); - ImGui::PushItemWidth(w_item_one); + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { - ImGui::PushID(i); - if (i + 1 == components) - { - ImGui::PopItemWidth(); - ImGui::PushItemWidth(w_item_last); - } - value_changed |= ImGui::SliderInt("##v", &v[i], v_min, v_max, display_format); - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); - ImGui::PopID(); + PushID(i); + value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); } - ImGui::PopItemWidth(); - ImGui::PopID(); + PopID(); - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - ImGui::EndGroup(); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); return value_changed; } @@ -5462,65 +6757,94 @@ bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const return SliderIntN(label, v, 4, v_min, v_max, display_format); } -// FIXME-WIP: Work in progress. May change API / behavior. -static bool DragScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_step, float v_min, float v_max) +bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; // Draw frame - const ImU32 frame_col = window->Color(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); + const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); bool value_changed = false; - // Process clicking on the slider + // Process clicking on the drag if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { - const ImVec2 mouse_drag_delta = ImGui::GetMouseDragDelta(0); + if (g.ActiveIdIsJustActivated) + { + // Lock current value on click + g.DragCurrentValue = *v; + g.DragLastMouseDelta = ImVec2(0.f, 0.f); + } + float v_cur = g.DragCurrentValue; + const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f); if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f) { - float step = v_step; + float speed = v_speed; + if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX) + speed = (v_max - v_min) * g.DragSpeedDefaultRatio; if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f) - step = v_step * g.DragSpeedScaleFast; + speed = speed * g.DragSpeedScaleFast; if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f) - step = v_step * g.DragSpeedScaleSlow; + speed = speed * g.DragSpeedScaleSlow; - *v += (mouse_drag_delta.x - g.DragLastMouseDelta.x) * step; + float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed; + if (fabsf(power - 1.0f) > 0.001f) + { + // Logarithmic curve on both side of 0.0 + float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur; + float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f; + float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign); + float v1_abs = v1 >= 0.0f ? v1 : -v1; + float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line + v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign + } + else + { + v_cur += delta; + } + g.DragLastMouseDelta.x = mouse_drag_delta.x; + // Clamp if (v_min < v_max) - *v = ImClamp(*v, v_min, v_max); + v_cur = ImClamp(v_cur, v_min, v_max); + g.DragCurrentValue = v_cur; + } - g.DragLastMouseDelta.x = mouse_drag_delta.x; + // Round to user desired precision, then apply + v_cur = RoundScalar(v_cur, decimal_precision); + if (*v != v_cur) + { + *v = v_cur; value_changed = true; } } else { - SetActiveId(0); + SetActiveID(0); } } return value_changed; } -bool ImGui::DragFloat(const char* label, float *v, float v_step, float v_min, float v_max, const char* display_format) +bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = ImGui::CalcItemWidth(); + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); @@ -5533,21 +6857,19 @@ bool ImGui::DragFloat(const char* label, float *v, float v_step, float v_min, fl const bool hovered = IsHovered(frame_bb, id); if (hovered) - g.HoveredId = id; + SetHoveredID(id); if (!display_format) display_format = "%.3f"; - int decimal_precision = 3; - ParseFormat(display_format, decimal_precision); + int decimal_precision = ParseFormatPrecision(display_format, 3); // Tabbing or CTRL-clicking on Drag turns it into an input box bool start_text_input = false; - const bool tab_focus_requested = window->FocusItemRegister(g.ActiveId == id); + const bool tab_focus_requested = FocusableItemRegister(window, g.ActiveId == id); if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0]))) { - SetActiveId(id); + SetActiveID(id, window); FocusWindow(window); - g.DragLastMouseDelta = ImVec2(0.f, 0.f); if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0]) { @@ -5556,18 +6878,16 @@ bool ImGui::DragFloat(const char* label, float *v, float v_step, float v_min, fl } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) - return SliderFloatAsInputText(label, v, id, decimal_precision); - - ItemSize(total_bb, style.FramePadding.y); + return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision); // Actual drag behavior - const bool value_changed = DragScalarBehavior(frame_bb, id, v, v_step, v_min, v_max); + ItemSize(total_bb, style.FramePadding.y); + const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); - const ImVec2 value_text_size = CalcTextSize(value_buf, value_buf_end, true); - RenderTextClipped(ImVec2(ImMax(frame_bb.Min.x + style.FramePadding.x, inner_bb.GetCenter().x - value_text_size.x*0.5f), frame_bb.Min.y + style.FramePadding.y), value_buf, value_buf_end, &value_text_size, frame_bb.Max); + RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); @@ -5575,34 +6895,163 @@ bool ImGui::DragFloat(const char* label, float *v, float v_step, float v_min, fl return value_changed; } -bool ImGui::DragInt(const char* label, int* v, int v_step, int v_min, int v_max, const char* display_format) +bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power); +} + +bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power); +} + +bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power) +{ + return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power); +} + +bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2); + + bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format, power); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, display_format_max ? display_format_max : display_format, power); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); + + return value_changed; +} + +// NB: v_speed is float to allow adjusting the drag speed with more precision +bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; - bool value_changed = ImGui::DragFloat(label, &v_f, (float)v_step, (float)v_min, (float)v_max, display_format); + bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format); *v = (int)v_f; return value_changed; } -enum ImGuiPlotType +bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format) { - ImGuiPlotType_Lines, - ImGuiPlotType_Histogram -}; + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + + return value_changed; +} + +bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format) +{ + return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format); +} + +bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format) +{ + return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format); +} + +bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format) +{ + return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format); +} + +bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + PushID(label); + BeginGroup(); + PushMultiItemsWidths(2); + + bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, display_format_max ? display_format_max : display_format); + PopItemWidth(); + SameLine(0, g.Style.ItemInnerSpacing.x); + + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); + PopID(); -static void Plot(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) + return value_changed; +} + +void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); + const ImVec2 label_size = CalcTextSize(label, NULL, true); if (graph_size.x == 0.0f) - graph_size.x = ImGui::CalcItemWidth() + (style.FramePadding.x * 2); + graph_size.x = CalcItemWidth(); if (graph_size.y == 0.0f) graph_size.y = label_size.y + (style.FramePadding.y * 2); @@ -5630,26 +7079,25 @@ static void Plot(ImGuiPlotType plot_type, const char* label, float (*values_gett scale_max = v_max; } - RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); - int res_w = ImMin((int)graph_size.x, values_count); - if (plot_type == ImGuiPlotType_Lines) - res_w -= 1; + int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); + int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); // Tooltip on hover int v_hovered = -1; - if (IsMouseHoveringRect(inner_bb)) + if (IsHovered(inner_bb, 0)) { const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); - const int v_idx = (int)(t * (values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0))); + const int v_idx = (int)(t * item_count); IM_ASSERT(v_idx >= 0 && v_idx < values_count); - + const float v0 = values_getter(data, (v_idx + values_offset) % values_count); const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); if (plot_type == ImGuiPlotType_Lines) - ImGui::SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); + SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); else if (plot_type == ImGuiPlotType_Histogram) - ImGui::SetTooltip("%d: %8.4g", v_idx, v0); + SetTooltip("%d: %8.4g", v_idx, v0); v_hovered = v_idx; } @@ -5657,42 +7105,51 @@ static void Plot(ImGuiPlotType plot_type, const char* label, float (*values_gett float v0 = values_getter(data, (0 + values_offset) % values_count); float t0 = 0.0f; - ImVec2 p0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); + ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); // Point in the normalized space of our target rectangle - const ImU32 col_base = window->Color((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); - const ImU32 col_hovered = window->Color((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); + const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); + const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); for (int n = 0; n < res_w; n++) { const float t1 = t0 + t_step; - const int v_idx = (int)(t0 * values_count); - IM_ASSERT(v_idx >= 0 && v_idx < values_count); - const float v1 = values_getter(data, (v_idx + values_offset + 1) % values_count); - const ImVec2 p1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) ); - - // NB- Draw calls are merged together by the DrawList system. + const int v1_idx = (int)(t0 * item_count + 0.5f); + IM_ASSERT(v1_idx >= 0 && v1_idx < values_count); + const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); + const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) ); + + // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. + ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); + ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, 1.0f)); if (plot_type == ImGuiPlotType_Lines) - window->DrawList->AddLine(ImLerp(inner_bb.Min, inner_bb.Max, p0), ImLerp(inner_bb.Min, inner_bb.Max, p1), v_hovered == v_idx ? col_hovered : col_base); + { + window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); + } else if (plot_type == ImGuiPlotType_Histogram) - window->DrawList->AddRectFilled(ImLerp(inner_bb.Min, inner_bb.Max, p0), ImLerp(inner_bb.Min, inner_bb.Max, ImVec2(p1.x, 1.0f))+ImVec2(-1,0), v_hovered == v_idx ? col_hovered : col_base); + { + if (pos1.x >= pos0.x + 2.0f) + pos1.x -= 1.0f; + window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); + } t0 = t1; - p0 = p1; + tp0 = tp1; } // Text overlay if (overlay_text) - RenderText(ImVec2(inner_bb.GetCenter().x - ImGui::CalcTextSize(overlay_text, NULL, true).x*0.5f, frame_bb.Min.y + style.FramePadding.y), overlay_text); + RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f)); - RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); + if (label_size.x > 0.0f) + RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); } struct ImGuiPlotArrayGetterData { const float* Values; - size_t Stride; + int Stride; - ImGuiPlotArrayGetterData(const float* values, size_t stride) { Values = values; Stride = stride; } + ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } }; static float Plot_ArrayGetter(void* data, int idx) @@ -5702,35 +7159,71 @@ static float Plot_ArrayGetter(void* data, int idx) return v; } -void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, size_t stride) +void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); - Plot(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); + PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { - Plot(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); + PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } -void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, size_t stride) +void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); - Plot(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); + PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { - Plot(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); + PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); +} + +// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size +void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + + ImVec2 pos = window->DC.CursorPos; + ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f)); + ItemSize(bb, style.FramePadding.y); + if (!ItemAdd(bb, NULL)) + return; + + // Render + fraction = ImSaturate(fraction); + RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + bb.Reduce(ImVec2(window->BorderSize, window->BorderSize)); + const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y); + RenderFrame(bb.Min, fill_br, GetColorU32(ImGuiCol_PlotHistogram), false, style.FrameRounding); + + // Default displaying the fraction as percentage string, but user can override it + char overlay_buf[32]; + if (!overlay) + { + ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f); + overlay = overlay_buf; + } + + ImVec2 overlay_size = CalcTextSize(overlay, NULL); + if (overlay_size.x > 0.0f) + RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb); } bool ImGui::Checkbox(const char* label, bool* v) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -5740,7 +7233,7 @@ bool ImGui::Checkbox(const char* label, bool* v) ImRect total_bb = check_bb; if (label_size.x > 0) - SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, style.ItemInnerSpacing.x); const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size); if (label_size.x > 0) { @@ -5752,43 +7245,48 @@ bool ImGui::Checkbox(const char* label, bool* v) return false; bool hovered, held; - bool pressed = ButtonBehavior(total_bb, id, &hovered, &held, true); + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) *v = !(*v); - RenderFrame(check_bb.Min, check_bb.Max, window->Color((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); + RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); if (*v) { const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); - const float pad = check_sz < 8.0f ? 1.0f : check_sz < 13.0f ? 2.0f : 3.0f; - window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), window->Color(ImGuiCol_CheckMark), style.FrameRounding); + const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); + window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), style.FrameRounding); } if (g.LogEnabled) - LogText(text_bb.GetTL(), *v ? "[x]" : "[ ]"); - RenderText(text_bb.GetTL(), label); + LogRenderedText(text_bb.GetTL(), *v ? "[x]" : "[ ]"); + if (label_size.x > 0.0f) + RenderText(text_bb.GetTL(), label); return pressed; } bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) { - bool v = (*flags & flags_value) ? true : false; - bool pressed = ImGui::Checkbox(label, &v); - if (v) - *flags |= flags_value; - else - *flags &= ~flags_value; + bool v = ((*flags & flags_value) == flags_value); + bool pressed = Checkbox(label, &v); + if (pressed) + { + if (v) + *flags |= flags_value; + else + *flags &= ~flags_value; + } + return pressed; } bool ImGui::RadioButton(const char* label, bool active) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); @@ -5798,7 +7296,7 @@ bool ImGui::RadioButton(const char* label, bool active) ImRect total_bb = check_bb; if (label_size.x > 0) - SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, style.ItemInnerSpacing.x); const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size); if (label_size.x > 0) { @@ -5815,32 +7313,33 @@ bool ImGui::RadioButton(const char* label, bool active) const float radius = check_bb.GetHeight() * 0.5f; bool hovered, held; - bool pressed = ButtonBehavior(total_bb, id, &hovered, &held, true); + bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); - window->DrawList->AddCircleFilled(center, radius, window->Color((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); + window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); if (active) { const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); - const float pad = check_sz < 8.0f ? 1.0f : check_sz < 13.0f ? 2.0f : 3.0f; - window->DrawList->AddCircleFilled(center, radius-pad, window->Color(ImGuiCol_CheckMark), 16); + const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f)); + window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16); } if (window->Flags & ImGuiWindowFlags_ShowBorders) { - window->DrawList->AddCircle(center+ImVec2(1,1), radius, window->Color(ImGuiCol_BorderShadow), 16); - window->DrawList->AddCircle(center, radius, window->Color(ImGuiCol_Border), 16); + window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16); + window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16); } if (g.LogEnabled) - LogText(text_bb.GetTL(), active ? "(x)" : "( )"); - RenderText(text_bb.GetTL(), label); + LogRenderedText(text_bb.GetTL(), active ? "(x)" : "( )"); + if (label_size.x > 0.0f) + RenderText(text_bb.GetTL(), label); return pressed; } bool ImGui::RadioButton(const char* label, int* v, int v_button) { - const bool pressed = ImGui::RadioButton(label, *v == v_button); + const bool pressed = RadioButton(label, *v == v_button); if (pressed) { *v = v_button; @@ -5848,54 +7347,128 @@ bool ImGui::RadioButton(const char* label, int* v, int v_button) return pressed; } +static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) +{ + int line_count = 0; + const char* s = text_begin; + while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding + if (c == '\n') + line_count++; + s--; + if (s[0] != '\n' && s[0] != '\r') + line_count++; + *out_text_end = s; + return line_count; +} + +static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) +{ + ImFont* font = GImGui->Font; + const float line_height = GImGui->FontSize; + const float scale = line_height / font->FontSize; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const ImWchar* s = text_begin; + while (s < text_end) + { + unsigned int c = (unsigned int)(*s++); + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + if (stop_on_new_line) + break; + continue; + } + if (c == '\r') + continue; + + const float char_width = font->GetCharAdvance((unsigned short)c) * scale; + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (out_offset) + *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n + + if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) -static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return (int)ImStrlenW(obj->Text); } +namespace ImGuiStb +{ + +static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; } -static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { (void)line_start_idx; return obj->Font->CalcTextSizeW(obj->FontSize, FLT_MAX, &obj->Text[char_idx], &obj->Text[char_idx]+1, NULL).x; } +static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); } static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) { + const ImWchar* text = obj->Text.Data; const ImWchar* text_remaining = NULL; - const ImVec2 size = obj->Font->CalcTextSizeW(obj->FontSize, FLT_MAX, obj->Text + line_start_idx, NULL, &text_remaining); + const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true); r->x0 = 0.0f; r->x1 = size.x; r->baseline_y_delta = size.y; r->ymin = 0.0f; r->ymax = size.y; - r->num_chars = (int)(text_remaining - (obj->Text + line_start_idx)); + r->num_chars = (int)(text_remaining - (text + line_start_idx)); } -static bool is_separator(unsigned int c) { return c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } -#define STB_TEXTEDIT_IS_SPACE(CH) ( ImCharIsSpace((unsigned int)CH) || is_separator((unsigned int)CH) ) +static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } +static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; } +static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } +#ifdef __APPLE__ // FIXME: Move setting to IO structure +static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; } +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } +#else +static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } +#endif +#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h +#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL + static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) { - ImWchar* dst = obj->Text + pos; + ImWchar* dst = obj->Text.Data + pos; // We maintain our buffer length in both UTF-8 and wchar formats obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); obj->CurLenW -= n; // Offset remaining text - const ImWchar* src = obj->Text + pos + n; + const ImWchar* src = obj->Text.Data + pos + n; while (ImWchar c = *src++) - *dst++ = c; + *dst++ = c; *dst = '\0'; } static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) { - const size_t text_len = obj->CurLenW; - if ((size_t)new_text_len + text_len + 1 > IM_ARRAYSIZE(obj->Text)) + const int text_len = obj->CurLenW; + IM_ASSERT(pos <= text_len); + if (new_text_len + text_len + 1 > obj->Text.Size) return false; const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len); - if ((size_t)new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA) + if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA) return false; - if (pos != (int)text_len) - memmove(obj->Text + (size_t)pos + new_text_len, obj->Text + (size_t)pos, (text_len - (size_t)pos) * sizeof(ImWchar)); - memcpy(obj->Text + (size_t)pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); + ImWchar* text = obj->Text.Data; + if (pos != text_len) + memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); + memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); obj->CurLenW += new_text_len; obj->CurLenA += new_text_len_utf8; @@ -5921,209 +7494,55 @@ static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const Im #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word #define STB_TEXTEDIT_K_SHIFT 0x20000 -#ifdef IMGUI_STB_NAMESPACE -namespace IMGUI_STB_NAMESPACE -{ -#endif #define STB_TEXTEDIT_IMPLEMENTATION #include "stb_textedit.h" -#ifdef IMGUI_STB_NAMESPACE -} -#endif - -void ImGuiTextEditState::OnKeyPressed(int key) -{ - stb_textedit_key(this, &StbState, key); - CursorAnimReset(); -} - -void ImGuiTextEditState::UpdateScrollOffset() -{ - // Scroll in chunks of quarter width - const float scroll_x_increment = Width * 0.25f; - const float cursor_offset_x = Font->CalcTextSizeW(FontSize, FLT_MAX, Text, Text+StbState.cursor, NULL).x; - - // If widget became bigger than text (because of a resize), reset horizontal scrolling - if (ScrollX > 0.0f) - { - const float text_width = cursor_offset_x + Font->CalcTextSizeW(FontSize, FLT_MAX, Text+StbState.cursor, NULL, NULL).x; - if (text_width < Width) - { - ScrollX = 0.0f; - return; - } - } - - if (cursor_offset_x < ScrollX) - ScrollX = ImMax(0.0f, cursor_offset_x - scroll_x_increment); - else if (cursor_offset_x - Width >= ScrollX) - ScrollX = cursor_offset_x - Width + scroll_x_increment; -} - -ImVec2 ImGuiTextEditState::CalcDisplayOffsetFromCharIdx(int i) const -{ - const ImWchar* text_start = GetTextPointerClippedW(Font, FontSize, Text, ScrollX, NULL); - const ImWchar* text_end = (Text+i >= text_start) ? Text+i : text_start; // Clip if requested character is outside of display - IM_ASSERT(text_end >= text_start); - - const ImVec2 offset = Font->CalcTextSizeW(FontSize, Width+1, text_start, text_end, NULL); - return offset; -} - -// [Static] -const char* ImGuiTextEditState::GetTextPointerClippedA(ImFont* font, float font_size, const char* text, float width, ImVec2* out_text_size) -{ - if (width <= 0.0f) - return text; - - const char* text_clipped_end = NULL; - const ImVec2 text_size = font->CalcTextSizeA(font_size, width, 0.0f, text, NULL, &text_clipped_end); - if (out_text_size) - *out_text_size = text_size; - return text_clipped_end; -} - -// [Static] -const ImWchar* ImGuiTextEditState::GetTextPointerClippedW(ImFont* font, float font_size, const ImWchar* text, float width, ImVec2* out_text_size) -{ - if (width <= 0.0f) - return text; - - const ImWchar* text_clipped_end = NULL; - const ImVec2 text_size = font->CalcTextSizeW(font_size, width, text, NULL, &text_clipped_end); - if (out_text_size) - *out_text_size = text_size; - return text_clipped_end; -} - -// [Static] -void ImGuiTextEditState::RenderTextScrolledClipped(ImFont* font, float font_size, const char* buf, ImVec2 pos, float width, float scroll_x) -{ - ImGuiWindow* window = GetCurrentWindow(); - const ImU32 font_color = window->Color(ImGuiCol_Text); - //window->DrawList->AddLine(pos, pos+ImVec2(width,0), 0xFF00FFFF); - - // Determine start and end of visible string - // FIXME-OPT: This is pretty slow for what it does. - const char* text_start = scroll_x <= 0.0f ? buf : GetTextPointerClippedA(font, font_size, buf, scroll_x, NULL); - const char* text_end = GetTextPointerClippedA(font, font_size, text_start, width + 1, NULL); // +1 to allow character spacing to fit outside the allowed width - window->DrawList->AddText(font, font_size, pos, font_color, text_start, text_end); - - // Log as text - if (GImGui->LogEnabled) - LogText(pos, buf, NULL); -} - -bool ImGui::InputFloat(const char* label, float *v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) -{ - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); - if (window->SkipItems) - return false; - - const ImGuiStyle& style = g.Style; - const float w = ImGui::CalcItemWidth(); - const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); - - ImGui::BeginGroup(); - ImGui::PushID(label); - const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding * 2; - if (step > 0.0f) - ImGui::PushItemWidth(ImMax(1.0f, w - (button_sz.x + style.ItemInnerSpacing.x)*2)); - char buf[64]; - if (decimal_precision < 0) - ImFormatString(buf, IM_ARRAYSIZE(buf), "%f", *v); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? - else - ImFormatString(buf, IM_ARRAYSIZE(buf), "%.*f", decimal_precision, *v); - bool value_changed = false; - const ImGuiInputTextFlags flags = extra_flags | (ImGuiInputTextFlags_CharsDecimal|ImGuiInputTextFlags_AutoSelectAll); - if (ImGui::InputText("", buf, IM_ARRAYSIZE(buf), flags)) - { - ApplyNumericalTextInput(buf, v); - value_changed = true; - } - - // Step buttons - if (step > 0.0f) - { - ImGui::PopItemWidth(); - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); - if (ImGui::Button("-", button_sz, true)) - { - *v -= g.IO.KeyCtrl && step_fast > 0.0f ? step_fast : step; - value_changed = true; - } - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); - if (ImGui::Button("+", button_sz, true)) - { - *v += g.IO.KeyCtrl && step_fast > 0.0f ? step_fast : step; - value_changed = true; - } - } - - ImGui::PopID(); - - if (label_size.x > 0) - { - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); - RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label); - ItemSize(label_size, style.FramePadding.y); - } - - ImGui::EndGroup(); - - return value_changed; } -bool ImGui::InputInt(const char* label, int *v, int step, int step_fast, ImGuiInputTextFlags extra_flags) +void ImGuiTextEditState::OnKeyPressed(int key) { - float f = (float)*v; - const bool value_changed = ImGui::InputFloat(label, &f, (float)step, (float)step_fast, 0, extra_flags); - if (value_changed) - *v = (int)f; - return value_changed; + stb_textedit_key(this, &StbState, key); + CursorFollow = true; + CursorAnimReset(); } // Public API to manipulate UTF-8 text // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) +// FIXME: The existence of this rarely exercised code path is a bit of a nuisance. void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count) { + IM_ASSERT(pos + bytes_count <= BufTextLen); char* dst = Buf + pos; const char* src = Buf + pos + bytes_count; while (char c = *src++) *dst++ = c; *dst = '\0'; - BufDirty = true; if (CursorPos + bytes_count >= pos) CursorPos -= bytes_count; else if (CursorPos >= pos) CursorPos = pos; SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen -= bytes_count; } void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) { - const size_t text_len = strlen(Buf); - if (!new_text_end) - new_text_end = new_text + strlen(new_text); - const size_t new_text_len = (size_t)(new_text_end - new_text); - - if (new_text_len + text_len + 1 >= BufSize) + const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); + if (new_text_len + BufTextLen + 1 >= BufSize) return; - size_t upos = (size_t)pos; - if (text_len != upos) - memmove(Buf + upos + new_text_len, Buf + upos, text_len - upos); - memcpy(Buf + upos, new_text, new_text_len * sizeof(char)); - Buf[text_len + new_text_len] = '\0'; + if (BufTextLen != pos) + memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); + memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); + Buf[BufTextLen + new_text_len] = '\0'; - BufDirty = true; if (CursorPos >= pos) - CursorPos += (int)new_text_len; + CursorPos += new_text_len; SelectionStart = SelectionEnd = CursorPos; + BufDirty = true; + BufTextLen += new_text_len; } // Return false to discard a character. @@ -6132,7 +7551,13 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f unsigned int c = *p_char; if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) - return false; + { + bool pass = false; + pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline)); + pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput)); + if (!pass) + return false; + } if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys. return false; @@ -6160,7 +7585,7 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f { ImGuiTextEditCallbackData callback_data; memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); - callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; + callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; callback_data.EventChar = (ImWchar)c; callback_data.Flags = flags; callback_data.UserData = user_data; @@ -6175,228 +7600,324 @@ static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags f } // Edit a string of text -bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +// NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect. +// FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188 +bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) + IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) + + ImGuiContext& g = *GImGui; const ImGuiIO& io = g.IO; const ImGuiStyle& style = g.Style; - const ImGuiID id = window->GetID(label); - const float w = ImGui::CalcItemWidth(); + const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; + const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0; + const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; + if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn + BeginGroup(); + const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); - ItemSize(total_bb, style.FramePadding.y); - if (!ItemAdd(total_bb, &id)) - return false; + + ImGuiWindow* draw_window = window; + if (is_multiline) + { + if (!BeginChildFrame(id, frame_bb.GetSize())) + { + EndChildFrame(); + EndGroup(); + return false; + } + draw_window = GetCurrentWindow(); + size.x -= draw_window->ScrollbarSizes.x; + } + else + { + ItemSize(total_bb, style.FramePadding.y); + if (!ItemAdd(total_bb, &id)) + return false; + } + + // Password pushes a temporary font with only a fallback glyph + if (is_password) + { + const ImFont::Glyph* glyph = g.Font->FindGlyph('*'); + ImFont* password_font = &g.InputTextPasswordFont; + password_font->FontSize = g.Font->FontSize; + password_font->Scale = g.Font->Scale; + password_font->DisplayOffset = g.Font->DisplayOffset; + password_font->Ascent = g.Font->Ascent; + password_font->Descent = g.Font->Descent; + password_font->ContainerAtlas = g.Font->ContainerAtlas; + password_font->FallbackGlyph = glyph; + password_font->FallbackXAdvance = glyph->XAdvance; + IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexXAdvance.empty() && password_font->IndexLookup.empty()); + PushFont(password_font); + } // NB: we are only allowed to access 'edit_state' if we are the active widget. ImGuiTextEditState& edit_state = g.InputTextState; - const bool is_ctrl_down = io.KeyCtrl; - const bool is_shift_down = io.KeyShift; - const bool focus_requested = window->FocusItemRegister(g.ActiveId == id, (flags & ImGuiInputTextFlags_CallbackCompletion) == 0); // Using completion callback disable keyboard tabbing + const bool focus_requested = FocusableItemRegister(window, g.ActiveId == id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; const bool hovered = IsHovered(frame_bb, id); if (hovered) { - g.HoveredId = id; + SetHoveredID(id); g.MouseCursor = ImGuiMouseCursor_TextInput; } const bool user_clicked = hovered && io.MouseClicked[0]; + const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY"); bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0; - if (focus_requested || user_clicked) + if (focus_requested || user_clicked || user_scrolled) { if (g.ActiveId != id) { // Start edition // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) - // From the moment we focused we are ignoring the content of 'buf' - ImFormatString(edit_state.InitialText, IM_ARRAYSIZE(edit_state.InitialText), "%s", buf); + // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) + const int prev_len_w = edit_state.CurLenW; + edit_state.Text.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + edit_state.InitialText.resize(buf_size+1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash. + ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size); const char* buf_end = NULL; - edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text, IM_ARRAYSIZE(edit_state.Text), buf, NULL, &buf_end); - edit_state.CurLenA = buf_end - buf; // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. - edit_state.Width = w + style.FramePadding.x; - edit_state.InputCursorScreenPos = ImVec2(-1.f,-1.f); + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); + edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. edit_state.CursorAnimReset(); - if (edit_state.Id != id) + // Preserve cursor position and undo/redo stack if we come back to same widget + // FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar). + const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW); + if (recycle_state) { - edit_state.Id = id; - edit_state.ScrollX = 0.0f; - stb_textedit_initialize_state(&edit_state.StbState, true); - if (focus_requested_by_code) - select_all = true; + // Recycle existing cursor/selection/undo stack but clamp position + // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. + edit_state.CursorClamp(); } else { - // Recycle existing cursor/selection/undo stack but clamp position - // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. - edit_state.StbState.cursor = ImMin(edit_state.StbState.cursor, (int)edit_state.CurLenW); - edit_state.StbState.select_start = ImMin(edit_state.StbState.select_start, (int)edit_state.CurLenW); - edit_state.StbState.select_end = ImMin(edit_state.StbState.select_end, (int)edit_state.CurLenW); + edit_state.Id = id; + edit_state.ScrollX = 0.0f; + stb_textedit_initialize_state(&edit_state.StbState, !is_multiline); + if (!is_multiline && focus_requested_by_code) + select_all = true; } - if (focus_requested_by_tab || (user_clicked && is_ctrl_down)) + if (flags & ImGuiInputTextFlags_AlwaysInsertMode) + edit_state.StbState.insert_mode = true; + if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) select_all = true; } - SetActiveId(id); + SetActiveID(id, window); FocusWindow(window); } else if (io.MouseClicked[0]) { // Release focus when we click outside if (g.ActiveId == id) - { - SetActiveId(0); - } + SetActiveID(0); } - // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. - // Down the line we should have a cleaner concept of focused vs active in the library. - if (g.ActiveId == id) - g.ActiveIdIsFocusedOnly = !io.MouseDown[0]; - bool value_changed = false; - bool cancel_edit = false; bool enter_pressed = false; + if (g.ActiveId == id) - //if (edit_state.Id == id) // Works, but double-click to select-all sets cursors to end which in turn tends to scroll toward the right when shrinking widget. { - // Update some data if we are active or last active - edit_state.Width = w + style.FramePadding.x; + if (!is_editable && !g.ActiveIdIsJustActivated) + { + // When read-only we always use the live data passed to the function + edit_state.Text.resize(buf_size+1); + const char* buf_end = NULL; + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end); + edit_state.CurLenA = (int)(buf_end - buf); + edit_state.CursorClamp(); + } + edit_state.BufSizeA = buf_size; - edit_state.Font = g.Font; - edit_state.FontSize = g.FontSize; - edit_state.UpdateScrollOffset(); - } - if (g.ActiveId == id) - { + + // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. + // Down the line we should have a cleaner library-wide concept of Selected vs Active. + g.ActiveIdAllowOverlap = !io.MouseDown[0]; + // Edit in progress - const float mx = g.IO.MousePos.x - frame_bb.Min.x - style.FramePadding.x; - const float my = g.FontSize*0.5f; // Flatten mouse because we are doing a single-line edit + const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX; + const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f)); - if (select_all || (hovered && io.MouseDoubleClicked[0])) + const bool osx_double_click_selects_words = io.OSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text + if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0])) { edit_state.SelectAll(); edit_state.SelectedAllMouseLock = true; } + else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0]) + { + // Select a word only, OS X style (by simulating keystrokes) + edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); + edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); + } else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock) { - stb_textedit_click(&edit_state, &edit_state.StbState, mx + edit_state.ScrollX, my); + stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y); edit_state.CursorAnimReset(); } - else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock) + else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) { - stb_textedit_drag(&edit_state, &edit_state.StbState, mx + edit_state.ScrollX, my); + stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y); edit_state.CursorAnimReset(); + edit_state.CursorFollow = true; } if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) edit_state.SelectedAllMouseLock = false; - if (g.IO.InputCharacters[0]) + if (io.InputCharacters[0]) { // Process text input (before we check for Return because using some IME will effectively send a Return?) - for (int n = 0; n < IM_ARRAYSIZE(g.IO.InputCharacters) && g.IO.InputCharacters[n]; n++) + // We ignore CTRL inputs, but need to allow CTRL+ALT as some keyboards (e.g. German) use AltGR - which is Alt+Ctrl - to input certain characters. + if (!(io.KeyCtrl && !io.KeyAlt) && is_editable) { - unsigned int c = (unsigned int)g.IO.InputCharacters[n]; - if (c) - { - // Insert character if they pass filtering - if (!InputTextFilterCharacter(&c, flags, callback, user_data)) - continue; - edit_state.OnKeyPressed((int)c); - } + for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++) + if (unsigned int c = (unsigned int)io.InputCharacters[n]) + { + // Insert character if they pass filtering + if (!InputTextFilterCharacter(&c, flags, callback, user_data)) + continue; + edit_state.OnKeyPressed((int)c); + } } // Consume characters memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); } - const int k_mask = (is_shift_down ? STB_TEXTEDIT_K_SHIFT : 0); - if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_WORDLEFT | k_mask : STB_TEXTEDIT_K_LEFT | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_WORDRIGHT | k_mask : STB_TEXTEDIT_K_RIGHT | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Delete)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Backspace)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } - else if (IsKeyPressedMap(ImGuiKey_Enter)) { SetActiveId(0); enter_pressed = true; } - else if (IsKeyPressedMap(ImGuiKey_Escape)) { SetActiveId(0); cancel_edit = true; } - else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_Z)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); } - else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_Y)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); } - else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); } - else if (is_ctrl_down && (IsKeyPressedMap(ImGuiKey_X) || IsKeyPressedMap(ImGuiKey_C))) + // Handle various key-presses + bool cancel_edit = false; + const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); + const bool is_shortcut_key_only = (io.OSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl + const bool is_wordmove_key_down = io.OSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl + const bool is_startend_key_down = io.OSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End + + if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } + else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable) + { + if (!edit_state.HasSelection()) + { + if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); + else if (io.OSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); + } + edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); + } + else if (IsKeyPressedMap(ImGuiKey_Enter)) + { + bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; + if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) + { + SetActiveID(0); + enter_pressed = true; + } + else if (is_editable) + { + unsigned int c = '\n'; // Insert new line + if (InputTextFilterCharacter(&c, flags, callback, user_data)) + edit_state.OnKeyPressed((int)c); + } + } + else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable) + { + unsigned int c = '\t'; // Insert TAB + if (InputTextFilterCharacter(&c, flags, callback, user_data)) + edit_state.OnKeyPressed((int)c); + } + else if (IsKeyPressedMap(ImGuiKey_Escape)) { SetActiveID(0); cancel_edit = true; } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); } + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; } + else if (is_shortcut_key_only && !is_password && ((IsKeyPressedMap(ImGuiKey_X) && is_editable) || IsKeyPressedMap(ImGuiKey_C)) && (!is_multiline || edit_state.HasSelection())) { // Cut, Copy const bool cut = IsKeyPressedMap(ImGuiKey_X); if (cut && !edit_state.HasSelection()) edit_state.SelectAll(); - if (g.IO.SetClipboardTextFn) + if (io.SetClipboardTextFn) { const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0; - const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : (int)edit_state.CurLenW; - ImTextStrToUtf8(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), edit_state.Text+ib, edit_state.Text+ie); - g.IO.SetClipboardTextFn(g.TempBuffer); + const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW; + edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1); + ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie); + io.SetClipboardTextFn(edit_state.TempTextBuffer.Data); } if (cut) + { + edit_state.CursorFollow = true; stb_textedit_cut(&edit_state, &edit_state.StbState); + } } - else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_V)) + else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V) && is_editable) { // Paste - if (g.IO.GetClipboardTextFn) + if (const char* clipboard = io.GetClipboardTextFn ? io.GetClipboardTextFn() : NULL) { - if (const char* clipboard = g.IO.GetClipboardTextFn()) + // Filter pasted buffer + const int clipboard_len = (int)strlen(clipboard); + ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar)); + int clipboard_filtered_len = 0; + for (const char* s = clipboard; *s; ) { - // Remove new-line from pasted buffer - const size_t clipboard_len = strlen(clipboard); - ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar)); - int clipboard_filtered_len = 0; - for (const char* s = clipboard; *s; ) - { - unsigned int c; - s += ImTextCharFromUtf8(&c, s, NULL); - if (c == 0) - break; - if (c >= 0x10000) - continue; - if (!InputTextFilterCharacter(&c, flags, callback, user_data)) - continue; - clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; - } - clipboard_filtered[clipboard_filtered_len] = 0; - if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation - stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); - ImGui::MemFree(clipboard_filtered); + unsigned int c; + s += ImTextCharFromUtf8(&c, s, NULL); + if (c == 0) + break; + if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data)) + continue; + clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; + } + clipboard_filtered[clipboard_filtered_len] = 0; + if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation + { + stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); + edit_state.CursorFollow = true; } + ImGui::MemFree(clipboard_filtered); } } - edit_state.CursorAnim += g.IO.DeltaTime; - edit_state.UpdateScrollOffset(); - if (cancel_edit) { // Restore initial value - ImFormatString(buf, buf_size, "%s", edit_state.InitialText); - value_changed = true; + if (is_editable) + { + ImStrncpy(buf, edit_state.InitialText.Data, buf_size); + value_changed = true; + } } else { // Apply new value immediately - copy modified buffer back - // Note that as soon as we can focus into the input box, the in-widget value gets priority over any underlying modification of the input buffer - // FIXME: We actually always render 'buf' in RenderTextScrolledClipped - // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks - ImTextStrToUtf8(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), edit_state.Text, NULL); + // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer + // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. + // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. + if (is_editable) + { + edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4); + ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL); + } // User callback if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) @@ -6421,28 +7942,35 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_DownArrow; } + else if (flags & ImGuiInputTextFlags_CallbackAlways) + event_flag = ImGuiInputTextFlags_CallbackAlways; - if (event_key != ImGuiKey_COUNT || (flags & ImGuiInputTextFlags_CallbackAlways) != 0) + if (event_flag) { ImGuiTextEditCallbackData callback_data; - callback_data.EventFlag = event_flag; + memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); + callback_data.EventFlag = event_flag; + callback_data.Flags = flags; + callback_data.UserData = user_data; + callback_data.ReadOnly = !is_editable; + callback_data.EventKey = event_key; - callback_data.Buf = g.TempBuffer; + callback_data.Buf = edit_state.TempTextBuffer.Data; + callback_data.BufTextLen = edit_state.CurLenA; callback_data.BufSize = edit_state.BufSizeA; callback_data.BufDirty = false; - callback_data.Flags = flags; - callback_data.UserData = user_data; - // We have to convert from position from wchar to UTF-8 positions - const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(edit_state.Text, edit_state.Text + edit_state.StbState.cursor); - const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(edit_state.Text, edit_state.Text + edit_state.StbState.select_start); - const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(edit_state.Text, edit_state.Text + edit_state.StbState.select_end); + // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) + ImWchar* text = edit_state.Text.Data; + const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor); + const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start); + const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end); // Call user code callback(&callback_data); // Read back what user may have modified - IM_ASSERT(callback_data.Buf == g.TempBuffer); // Invalid to modify those fields + IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA); IM_ASSERT(callback_data.Flags == flags); if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); @@ -6450,57 +7978,193 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); if (callback_data.BufDirty) { - ImTextStrFromUtf8(edit_state.Text, IM_ARRAYSIZE(edit_state.Text), g.TempBuffer, NULL); + IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! + edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL); + edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() edit_state.CursorAnimReset(); } } } - if (strcmp(g.TempBuffer, buf) != 0) + // Copy back to user buffer + if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0) { - ImFormatString(buf, buf_size, "%s", g.TempBuffer); + ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size); value_changed = true; } } } - - RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); - const ImVec2 font_off_up = ImVec2(0.0f, g.FontSize+1.0f); // FIXME: those offsets are part of the style or font API - const ImVec2 font_off_dn = ImVec2(0.0f, 2.0f); + // Render + // Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on. + const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL; + + if (!is_multiline) + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + + const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size + ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; + ImVec2 text_size(0.f, 0.f); + const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY")); + if (g.ActiveId == id || is_currently_scrolling) + { + edit_state.CursorAnim += io.DeltaTime; + + // This is going to be messy. We need to: + // - Display the text (this alone can be more easily clipped) + // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) + // - Measure text height (for scrollbar) + // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) + // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. + const ImWchar* text_begin = edit_state.Text.Data; + ImVec2 cursor_offset, select_start_offset; + + { + // Count lines + find lines numbers straddling 'cursor' and 'select_start' position. + const ImWchar* searches_input_ptr[2]; + searches_input_ptr[0] = text_begin + edit_state.StbState.cursor; + searches_input_ptr[1] = NULL; + int searches_remaining = 1; + int searches_result_line_number[2] = { -1, -999 }; + if (edit_state.StbState.select_start != edit_state.StbState.select_end) + { + searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + searches_result_line_number[1] = -1; + searches_remaining++; + } - if (g.ActiveId == id) - { - // Draw selection - const int select_begin_idx = edit_state.StbState.select_start; - const int select_end_idx = edit_state.StbState.select_end; - if (select_begin_idx != select_end_idx) - { - const ImVec2 select_begin_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(ImMin(select_begin_idx,select_end_idx)); - const ImVec2 select_end_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(ImMax(select_begin_idx,select_end_idx)); - window->DrawList->AddRectFilled(select_begin_pos - font_off_up, select_end_pos + font_off_dn, window->Color(ImGuiCol_TextSelectedBg)); + // Iterate all lines to find our line numbers + // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter. + searches_remaining += is_multiline ? 1 : 0; + int line_count = 0; + for (const ImWchar* s = text_begin; *s != 0; s++) + if (*s == '\n') + { + line_count++; + if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; } + if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; } + } + line_count++; + if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count; + if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count; + + // Calculate 2d position by finding the beginning of the line and measuring distance + cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x; + cursor_offset.y = searches_result_line_number[0] * g.FontSize; + if (searches_result_line_number[1] >= 0) + { + select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x; + select_start_offset.y = searches_result_line_number[1] * g.FontSize; + } + + // Calculate text height + if (is_multiline) + text_size = ImVec2(size.x, line_count * g.FontSize); } - } - //const float render_scroll_x = (g.ActiveId == id) ? edit_state.ScrollX : 0.0f; - const float render_scroll_x = (edit_state.Id == id) ? edit_state.ScrollX : 0.0f; - ImGuiTextEditState::RenderTextScrolledClipped(g.Font, g.FontSize, buf, frame_bb.Min + style.FramePadding, w + style.FramePadding.x, render_scroll_x); + // Scroll + if (edit_state.CursorFollow) + { + // Horizontal scroll in chunks of quarter width + if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) + { + const float scroll_increment_x = size.x * 0.25f; + if (cursor_offset.x < edit_state.ScrollX) + edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x); + else if (cursor_offset.x - size.x >= edit_state.ScrollX) + edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x); + } + else + { + edit_state.ScrollX = 0.0f; + } - if (g.ActiveId == id) - { - const ImVec2 cursor_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(edit_state.StbState.cursor); + // Vertical scroll + if (is_multiline) + { + float scroll_y = draw_window->Scroll.y; + if (cursor_offset.y - g.FontSize < scroll_y) + scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); + else if (cursor_offset.y - size.y >= scroll_y) + scroll_y = cursor_offset.y - size.y; + draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag + draw_window->Scroll.y = scroll_y; + render_pos.y = draw_window->DC.CursorPos.y; + } + } + edit_state.CursorFollow = false; + const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f); - // Draw blinking cursor - if (g.InputTextState.CursorIsVisible()) - window->DrawList->AddRect(cursor_pos - font_off_up + ImVec2(0,2), cursor_pos + font_off_dn - ImVec2(0,3), window->Color(ImGuiCol_Text)); - - // Notify OS of text input position for advanced IME - if (io.ImeSetInputScreenPosFn && ImLengthSqr(edit_state.InputCursorScreenPos - cursor_pos) > 0.0001f) - io.ImeSetInputScreenPosFn((int)cursor_pos.x - 1, (int)(cursor_pos.y - g.FontSize)); // -1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety. + // Draw selection + if (edit_state.StbState.select_start != edit_state.StbState.select_end) + { + const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end); + const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end); + + float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. + float bg_offy_dn = is_multiline ? 0.0f : 2.0f; + ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg); + ImVec2 rect_pos = render_pos + select_start_offset - render_scroll; + for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) + { + if (rect_pos.y > clip_rect.w + g.FontSize) + break; + if (rect_pos.y < clip_rect.y) + { + while (p < text_selected_end) + if (*p++ == '\n') + break; + } + else + { + ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); + if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines + ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn)); + rect.Clip(clip_rect); + if (rect.Overlaps(clip_rect)) + draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); + } + rect_pos.x = render_pos.x - render_scroll.x; + rect_pos.y += g.FontSize; + } + } + + draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect); + + // Draw blinking cursor + bool cursor_is_visible = (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f; + ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll; + ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f); + if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) + draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); + + // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) + if (is_editable) + g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize); + } + else + { + // Render text only + const char* buf_end = NULL; + if (is_multiline) + text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width + draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect); + } - edit_state.InputCursorScreenPos = cursor_pos; + if (is_multiline) + { + Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line + EndChildFrame(); + EndGroup(); } + if (is_password) + PopFont(); + + // Log as text + if (g.LogEnabled && !is_password) + LogRenderedText(render_pos, buf_display, NULL); + if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); @@ -6510,110 +8174,175 @@ bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputT return value_changed; } -static bool InputFloatN(const char* label, float* v, int components, int decimal_precision) +bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() + return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); +} + +bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) +{ + return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); +} + +// NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument) +bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const float w_full = ImGui::CalcItemWidth(); - const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1))); + const ImVec2 label_size = CalcTextSize(label, NULL, true); + + BeginGroup(); + PushID(label); + const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding*2.0f; + if (step_ptr) + PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2)); + + char buf[64]; + DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf)); bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); - ImGui::PushItemWidth(w_item_one); - for (int i = 0; i < components; i++) + if (!(extra_flags & ImGuiInputTextFlags_CharsHexadecimal)) + extra_flags |= ImGuiInputTextFlags_CharsDecimal; + extra_flags |= ImGuiInputTextFlags_AutoSelectAll; + if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view + value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format); + + // Step buttons + if (step_ptr) { - ImGui::PushID(i); - if (i + 1 == components) + PopItemWidth(); + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) { - ImGui::PopItemWidth(); - ImGui::PushItemWidth(w_item_last); + DataTypeApplyOp(data_type, '-', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); + value_changed = true; + } + SameLine(0, style.ItemInnerSpacing.x); + if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups)) + { + DataTypeApplyOp(data_type, '+', data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr); + value_changed = true; } - value_changed |= ImGui::InputFloat("##v", &v[i], 0, 0, decimal_precision); - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); - ImGui::PopID(); } - ImGui::PopItemWidth(); - ImGui::PopID(); + PopID(); + + if (label_size.x > 0) + { + SameLine(0, style.ItemInnerSpacing.x); + RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label); + ItemSize(label_size, style.FramePadding.y); + } + EndGroup(); + + return value_changed; +} + +bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + char display_format[16]; + if (decimal_precision < 0) + strcpy(display_format, "%f"); // Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1 + else + ImFormatString(display_format, 16, "%%.%df", decimal_precision); + return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags); +} + +bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags) +{ + // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. + const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; + return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), scalar_format, extra_flags); +} + +bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + bool value_changed = false; + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); + for (int i = 0; i < components; i++) + { + PushID(i); + value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); + } + PopID(); - window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, style.FramePadding.y); - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - ImGui::EndGroup(); + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); return value_changed; } -bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision) +bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags) { - return InputFloatN(label, v, 2, decimal_precision); + return InputFloatN(label, v, 2, decimal_precision, extra_flags); } -bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision) +bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags) { - return InputFloatN(label, v, 3, decimal_precision); + return InputFloatN(label, v, 3, decimal_precision, extra_flags); } -bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision) +bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags) { - return InputFloatN(label, v, 4, decimal_precision); + return InputFloatN(label, v, 4, decimal_precision, extra_flags); } -static bool InputIntN(const char* label, int* v, int components) +bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; - const ImGuiStyle& style = g.Style; - const float w_full = ImGui::CalcItemWidth(); - const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1))); - + ImGuiContext& g = *GImGui; bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); - ImGui::PushItemWidth(w_item_one); + BeginGroup(); + PushID(label); + PushMultiItemsWidths(components); for (int i = 0; i < components; i++) { - ImGui::PushID(i); - if (i + 1 == components) - { - ImGui::PopItemWidth(); - ImGui::PushItemWidth(w_item_last); - } - value_changed |= ImGui::InputInt("##v", &v[i], 0, 0); - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); - ImGui::PopID(); + PushID(i); + value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags); + SameLine(0, g.Style.ItemInnerSpacing.x); + PopID(); + PopItemWidth(); } - ImGui::PopItemWidth(); - ImGui::PopID(); + PopID(); - window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, style.FramePadding.y); - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - ImGui::EndGroup(); + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); + TextUnformatted(label, FindRenderedTextEnd(label)); + EndGroup(); return value_changed; } -bool ImGui::InputInt2(const char* label, int v[2]) +bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags) { - return InputIntN(label, v, 2); + return InputIntN(label, v, 2, extra_flags); } -bool ImGui::InputInt3(const char* label, int v[3]) +bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags) { - return InputIntN(label, v, 3); + return InputIntN(label, v, 3, extra_flags); } -bool ImGui::InputInt4(const char* label, int v[4]) +bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags) { - return InputIntN(label, v, 4); + return InputIntN(label, v, 4, extra_flags); } static bool Items_ArrayGetter(void* data, int idx, const char** out_text) @@ -6655,7 +8384,7 @@ bool ImGui::Combo(const char* label, int* current_item, const char** items, int bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) { int items_count = 0; - const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this + const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open while (*p) { p += strlen(p) + 1; @@ -6668,159 +8397,194 @@ bool ImGui::Combo(const char* label, int* current_item, const char* items_separa // Combo box function. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w = ImGui::CalcItemWidth(); + const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); - const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(style.ItemInnerSpacing.x + label_size.x,0)); + const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); + const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, &id)) return false; const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f); const bool hovered = IsHovered(frame_bb, id); + bool popup_open = IsPopupOpen(id); + bool popup_opened_now = false; - bool value_changed = false; const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); - RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); - RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, window->Color(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING + RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); + RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32(popup_open || hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true); if (*current_item >= 0 && *current_item < items_count) { const char* item_text; if (items_getter(data, *current_item, &item_text)) - RenderTextClipped(frame_bb.Min + style.FramePadding, item_text, NULL, NULL, value_bb.Max); + RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, item_text, NULL, NULL, ImVec2(0.0f,0.0f)); } if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); - - ImGui::PushID((int)id); - bool menu_toggled = false; + if (hovered) { - g.HoveredId = id; + SetHoveredID(id); if (g.IO.MouseClicked[0]) { - menu_toggled = true; - g.ActiveComboID = (g.ActiveComboID == id) ? 0 : id; - if (g.ActiveComboID) + SetActiveID(0); + if (IsPopupOpen(id)) + { + ClosePopup(id); + } + else + { FocusWindow(window); + OpenPopup(label); + popup_open = popup_opened_now = true; + } } } - - if (g.ActiveComboID == id) + + bool value_changed = false; + if (IsPopupOpen(id)) { // Size default to hold ~7 items if (height_in_items < 0) height_in_items = 7; - const ImVec2 backup_pos = ImGui::GetCursorPos(); - const float popup_off_x = 0.0f;//style.ItemInnerSpacing.x; - const float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3); - const ImRect popup_rect(ImVec2(frame_bb.Min.x+popup_off_x, frame_bb.Max.y), ImVec2(frame_bb.Max.x+popup_off_x, frame_bb.Max.y + popup_height)); - ImGui::SetCursorPos(popup_rect.Min - window->Pos); + float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3); + float popup_y1 = frame_bb.Max.y; + float popup_y2 = ImClamp(popup_y1 + popup_height, popup_y1, g.IO.DisplaySize.y - style.DisplaySafeAreaPadding.y); + if ((popup_y2 - popup_y1) < ImMin(popup_height, frame_bb.Min.y - style.DisplaySafeAreaPadding.y)) + { + // Position our combo ABOVE because there's more space to fit! (FIXME: Handle in Begin() or use a shared helper. We have similar code in Begin() for popup placement) + popup_y1 = ImClamp(frame_bb.Min.y - popup_height, style.DisplaySafeAreaPadding.y, frame_bb.Min.y); + popup_y2 = frame_bb.Min.y; + } + ImRect popup_rect(ImVec2(frame_bb.Min.x, popup_y1), ImVec2(frame_bb.Max.x, popup_y2)); + SetNextWindowPos(popup_rect.Min); + SetNextWindowSize(popup_rect.GetSize()); + PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0); - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); - ImGui::BeginChild("#ComboBox", popup_rect.GetSize(), false, flags); - ImGui::Spacing(); - - bool combo_item_active = false; - combo_item_active |= (g.ActiveId == GetCurrentWindow()->GetID("#SCROLLY")); - - // Display items - for (int i = 0; i < items_count; i++) + if (BeginPopupEx(label, flags)) { - ImGui::PushID((void*)(intptr_t)i); - const bool item_selected = (i == *current_item); - const char* item_text; - if (!items_getter(data, i, &item_text)) - item_text = "*Unknown item*"; - if (ImGui::Selectable(item_text, item_selected)) + // Display items + Spacing(); + for (int i = 0; i < items_count; i++) { - SetActiveId(0); - g.ActiveComboID = 0; - value_changed = true; - *current_item = i; + PushID((void*)(intptr_t)i); + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + if (Selectable(item_text, item_selected)) + { + SetActiveID(0); + value_changed = true; + *current_item = i; + } + if (item_selected && popup_opened_now) + SetScrollHere(); + PopID(); } - if (item_selected && menu_toggled) - ImGui::SetScrollPosHere(); - combo_item_active |= ImGui::IsItemActive(); - ImGui::PopID(); + EndPopup(); } - ImGui::EndChild(); - ImGui::PopStyleVar(); - ImGui::SetCursorPos(backup_pos); - - if (!combo_item_active && g.ActiveId != 0) - g.ActiveComboID = 0; + PopStyleVar(); } - - ImGui::PopID(); - return value_changed; } // Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID. -bool ImGui::Selectable(const char* label, bool selected, const ImVec2& size_arg) +bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; - const ImGuiID id = window->GetID(label); - const ImVec2 label_size = CalcTextSize(label, NULL, true); - - const float w = ImMax(label_size.x, window->Pos.x + ImGui::GetContentRegionMax().x - style.AutoFitPadding.x - window->DC.CursorPos.x); - const ImVec2 size(size_arg.x != 0.0f ? size_arg.x : w, size_arg.y != 0.0f ? size_arg.y : label_size.y); - ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + PopClipRect(); + + ImGuiID id = window->GetID(label); + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); + ImVec2 pos = window->DC.CursorPos; + pos.y += window->DC.CurrentLineTextBaseOffset; + ImRect bb(pos, pos + size); ItemSize(bb); - bb.Max.x += style.AutoFitPadding.x; - - // Selectables are meant to be tightly packed together. So for both rendering and collision we extend to compensate for spacing. - ImRect bb_with_spacing = bb; - const float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); - const float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); - const float spacing_R = style.ItemSpacing.x - spacing_L; - const float spacing_D = style.ItemSpacing.y - spacing_U; + + // Fill horizontal space. + ImVec2 window_padding = window->WindowPadding; + float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; + float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x); + ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); + ImRect bb_with_spacing(pos, pos + size_draw); + if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) + bb_with_spacing.Max.x += window_padding.x; + + // Selectables are tightly packed together, we extend the box to cover spacing between selectable. + float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); + float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); + float spacing_R = style.ItemSpacing.x - spacing_L; + float spacing_D = style.ItemSpacing.y - spacing_U; bb_with_spacing.Min.x -= spacing_L; bb_with_spacing.Min.y -= spacing_U; bb_with_spacing.Max.x += spacing_R; bb_with_spacing.Max.y += spacing_D; if (!ItemAdd(bb_with_spacing, &id)) + { + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + PushColumnClipRect(); return false; + } + ImGuiButtonFlags button_flags = 0; + if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick; + if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnClick|ImGuiButtonFlags_PressedOnRelease; + if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled; + if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; bool hovered, held; - bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, true, false, false); + bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags); + if (flags & ImGuiSelectableFlags_Disabled) + selected = false; // Render if (hovered || selected) { - const ImU32 col = window->Color((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); - RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, style.FrameRounding); + const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); + RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f); + } + + if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsCount > 1) + { + PushColumnClipRect(); + bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x); } - //const ImVec2 off = ImVec2(ImMax(0.0f, size.x - text_size.x) * 0.5f, ImMax(0.0f, size.y - text_size.y) * 0.5f); - RenderTextClipped(bb.Min, label, NULL, &label_size, bb_with_spacing.Max); + if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f)); + if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); + // Automatically close popups + if (pressed && !(flags & ImGuiSelectableFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) + CloseCurrentPopup(); return pressed; } -bool ImGui::Selectable(const char* label, bool* p_selected, const ImVec2& size_arg) +bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { - if (ImGui::Selectable(label, *p_selected, size_arg)) + if (Selectable(label, *p_selected, flags, size_arg)) { *p_selected = !*p_selected; return true; @@ -6833,25 +8597,25 @@ bool ImGui::Selectable(const char* label, bool* p_selected, const ImVec2& size_a bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; - const ImGuiStyle& style = ImGui::GetStyle(); - const ImGuiID id = ImGui::GetID(label); - const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); + const ImGuiStyle& style = GetStyle(); + const ImGuiID id = GetID(label); + const ImVec2 label_size = CalcTextSize(label, NULL, true); // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. - ImVec2 size; - size.x = (size_arg.x != 0.0f) ? (size_arg.x) : ImGui::CalcItemWidth() + style.FramePadding.x * 2.0f; - size.y = (size_arg.y != 0.0f) ? (size_arg.y) : ImGui::GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y; - const ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); - const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); - const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); + ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); + ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); + ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); + ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); window->DC.LastItemRect = bb; - ImGui::BeginGroup(); + BeginGroup(); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); - ImGui::BeginChildFrame(id, frame_bb.GetSize()); + BeginChildFrame(id, frame_bb.GetSize()); return true; } @@ -6867,24 +8631,24 @@ bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_item // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). ImVec2 size; size.x = 0.0f; - size.y = ImGui::GetTextLineHeightWithSpacing() * height_in_items_f + ImGui::GetStyle().ItemSpacing.y; - return ImGui::ListBoxHeader(label, size); + size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y; + return ListBoxHeader(label, size); } void ImGui::ListBoxFooter() { ImGuiWindow* parent_window = GetParentWindow(); const ImRect bb = parent_window->DC.LastItemRect; - const ImGuiStyle& style = ImGui::GetStyle(); - - ImGui::EndChildFrame(); + const ImGuiStyle& style = GetStyle(); + + EndChildFrame(); // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect) // We call SameLine() to restore DC.CurrentLine* data - ImGui::SameLine(); + SameLine(); parent_window->DC.CursorPos = bb.Min; ItemSize(bb, style.FramePadding.y); - ImGui::EndGroup(); + EndGroup(); } bool ImGui::ListBox(const char* label, int* current_item, const char** items, int items_count, int height_items) @@ -6894,63 +8658,265 @@ bool ImGui::ListBox(const char* label, int* current_item, const char** items, in } bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) +{ + if (!ListBoxHeader(label, items_count, height_in_items)) + return false; + + // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. + bool value_changed = false; + ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + { + const bool item_selected = (i == *current_item); + const char* item_text; + if (!items_getter(data, i, &item_text)) + item_text = "*Unknown item*"; + + PushID(i); + if (Selectable(item_text, item_selected)) + { + *current_item = i; + value_changed = true; + } + PopID(); + } + ListBoxFooter(); + return value_changed; +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext& g = *GImGui; + ImVec2 pos = window->DC.CursorPos; + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f); + float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + + bool pressed = Selectable(label, false, ImGuiSelectableFlags_MenuItem | ImGuiSelectableFlags_DrawFillAvailWidth | (enabled ? 0 : ImGuiSelectableFlags_Disabled), ImVec2(w, 0.0f)); + if (shortcut_size.x > 0.0f) + { + PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false); + PopStyleColor(); + } + + if (selected) + RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled)); + + return pressed; +} + +bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) +{ + if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled)) + { + if (p_selected) + *p_selected = !*p_selected; + return true; + } + return false; +} + +bool ImGui::BeginMainMenuBar() +{ + ImGuiContext& g = *GImGui; + SetNextWindowPos(ImVec2(0.0f, 0.0f)); + SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f)); + PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); + PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0)); + if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar) + || !BeginMenuBar()) + { + End(); + PopStyleVar(2); + return false; + } + g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x; + return true; +} + +void ImGui::EndMainMenuBar() +{ + EndMenuBar(); + End(); + PopStyleVar(2); +} + +bool ImGui::BeginMenuBar() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + if (!(window->Flags & ImGuiWindowFlags_MenuBar)) + return false; + + IM_ASSERT(!window->DC.MenuBarAppending); + BeginGroup(); // Save position + PushID("##menubar"); + ImRect rect = window->MenuBarRect(); + PushClipRect(ImVec2(ImFloor(rect.Min.x+0.5f), ImFloor(rect.Min.y + window->BorderSize + 0.5f)), ImVec2(ImFloor(rect.Max.x+0.5f), ImFloor(rect.Max.y+0.5f)), false); + window->DC.CursorPos = ImVec2(rect.Min.x + window->DC.MenuBarOffsetX, rect.Min.y);// + g.Style.FramePadding.y); + window->DC.LayoutType = ImGuiLayoutType_Horizontal; + window->DC.MenuBarAppending = true; + AlignFirstTextHeightToWidgets(); + return true; +} + +void ImGui::EndMenuBar() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) + return; + + IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); + IM_ASSERT(window->DC.MenuBarAppending); + PopClipRect(); + PopID(); + window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x; + window->DC.GroupStack.back().AdvanceCursor = false; + EndGroup(); + window->DC.LayoutType = ImGuiLayoutType_Vertical; + window->DC.MenuBarAppending = false; +} - if (!ImGui::ListBoxHeader(label, items_count, height_in_items)) +bool ImGui::BeginMenu(const char* label, bool enabled) +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems) return false; - bool value_changed = false; - for (int i = 0; i < items_count; i++) + ImGuiContext& g = *GImGui; + const ImGuiStyle& style = g.Style; + const ImGuiID id = window->GetID(label); + + ImVec2 label_size = CalcTextSize(label, NULL, true); + ImGuiWindow* backed_focused_window = g.FocusedWindow; + + bool pressed; + bool menu_is_open = IsPopupOpen(id); + bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentMenuSet == window->GetID("##menus")); + if (menuset_is_open) + g.FocusedWindow = window; + + ImVec2 popup_pos, pos = window->DC.CursorPos; + if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { - const bool item_selected = (i == *current_item); - const char* item_text; - if (!items_getter(data, i, &item_text)) - item_text = "*Unknown item*"; + popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight()); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); + PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); + float w = label_size.x; + pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); + PopStyleVar(); + SameLine(); + window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); + } + else + { + popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); + float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame + float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); + pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); + if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); + RenderCollapseTriangle(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.20f, 0.0f), false); + if (!enabled) PopStyleColor(); + } - ImGui::PushID(i); - if (ImGui::Selectable(item_text, item_selected)) + bool hovered = enabled && IsHovered(window->DC.LastItemRect, id); + if (menuset_is_open) + g.FocusedWindow = backed_focused_window; + + bool want_open = false, want_close = false; + if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) + { + // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. + bool moving_within_opened_triangle = false; + if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window) { - *current_item = i; - value_changed = true; + if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window) + { + ImRect next_window_rect = next_window->Rect(); + ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; + ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); + ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); + float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. + ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues + tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? + tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); + moving_within_opened_triangle = ImIsPointInTriangle(g.IO.MousePos, ta, tb, tc); + //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug + } } - ImGui::PopID(); + + want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle); + want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed); } + else if (menu_is_open && pressed && menuset_is_open) // menu-bar: click open menu to close + { + want_close = true; + want_open = menu_is_open = false; + } + else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // menu-bar: first click to open, then hover to open others + want_open = true; + if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' + want_close = true; + if (want_close && IsPopupOpen(id)) + ClosePopupToLevel(GImGui->CurrentPopupStack.Size); - ImGui::ListBoxFooter(); - return value_changed; + if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size) + { + // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame. + OpenPopup(label); + return false; + } + + menu_is_open |= want_open; + if (want_open) + OpenPopup(label); + + if (menu_is_open) + { + SetNextWindowPos(popup_pos, ImGuiSetCond_Always); + ImGuiWindowFlags flags = ImGuiWindowFlags_ShowBorders | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu); + menu_is_open = BeginPopupEx(label, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) + } + + return menu_is_open; +} + +void ImGui::EndMenu() +{ + EndPopup(); } // A little colored square. Return true when clicked. +// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID("#colorbutton"); const float square_size = g.FontSize; - const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.x*2, square_size + (small_height ? 0 : style.FramePadding.y*2))); + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.y*2, square_size + (small_height ? 0 : style.FramePadding.y*2))); ItemSize(bb, small_height ? 0.0f : style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; bool hovered, held; - bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); - RenderFrame(bb.Min, bb.Max, window->Color(col), outline_border, style.FrameRounding); + bool pressed = ButtonBehavior(bb, id, &hovered, &held); + RenderFrame(bb.Min, bb.Max, GetColorU32(col), outline_border, style.FrameRounding); if (hovered) - { - int ix = (int)(col.x * 255.0f + 0.5f); - int iy = (int)(col.y * 255.0f + 0.5f); - int iz = (int)(col.z * 255.0f + 0.5f); - int iw = (int)(col.w * 255.0f + 0.5f); - ImGui::SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, ix, iy, iz, iw); - } + SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, IM_F32_TO_INT8_SAT(col.x), IM_F32_TO_INT8_SAT(col.y), IM_F32_TO_INT8_SAT(col.z), IM_F32_TO_INT8_SAT(col.z)); return pressed; } @@ -6962,7 +8928,7 @@ bool ImGui::ColorEdit3(const char* label, float col[3]) col4[1] = col[1]; col4[2] = col[2]; col4[3] = 1.0f; - const bool value_changed = ImGui::ColorEdit4(label, col4, false); + const bool value_changed = ColorEdit4(label, col4, false); col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2]; @@ -6973,32 +8939,31 @@ bool ImGui::ColorEdit3(const char* label, float col[3]) // Use CTRL-Click to input value and TAB to go to next item. bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; + ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); - const float w_full = ImGui::CalcItemWidth(); - const float square_sz = (g.FontSize + style.FramePadding.x * 2.0f); + const float w_full = CalcItemWidth(); + const float square_sz = (g.FontSize + style.FramePadding.y * 2.0f); ImGuiColorEditMode edit_mode = window->DC.ColorEditMode; if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton) edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3; float f[4] = { col[0], col[1], col[2], col[3] }; - if (edit_mode == ImGuiColorEditMode_HSV) - ImGui::ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); + ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); - int i[4] = { (int)(f[0] * 255.0f + 0.5f), (int)(f[1] * 255.0f + 0.5f), (int)(f[2] * 255.0f + 0.5f), (int)(f[3] * 255.0f + 0.5f) }; + int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; int components = alpha ? 4 : 3; bool value_changed = false; - ImGui::BeginGroup(); - ImGui::PushID(label); + BeginGroup(); + PushID(label); const bool hsv = (edit_mode == 1); switch (edit_mode) @@ -7008,30 +8973,30 @@ bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) { // RGB/HSV 0..255 Sliders const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x); - const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1)) / (float)components)); - const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1))); + const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); + const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x); const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; - const char* fmt_table[3][4] = + const char* fmt_table[3][4] = { - { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, + { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, - { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } + { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } }; - const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1]; + const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1]; - ImGui::PushItemWidth(w_item_one); + PushItemWidth(w_item_one); for (int n = 0; n < components; n++) { if (n > 0) - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, style.ItemInnerSpacing.x); if (n + 1 == components) - ImGui::PushItemWidth(w_item_last); - value_changed |= ImGui::DragInt(ids[n], &i[n], 1, 0, 255, fmt[n]); + PushItemWidth(w_item_last); + value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]); } - ImGui::PopItemWidth(); - ImGui::PopItemWidth(); + PopItemWidth(); + PopItemWidth(); } break; case ImGuiColorEditMode_HEX: @@ -7043,49 +9008,54 @@ bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]); else ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]); - ImGui::PushItemWidth(w_slider_all - style.ItemInnerSpacing.x); - value_changed |= ImGui::InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); - ImGui::PopItemWidth(); - char* p = buf; - while (*p == '#' || ImCharIsSpace(*p)) - p++; - - // Treat at unsigned (%X is unsigned) - i[0] = i[1] = i[2] = i[3] = 0; - if (alpha) - sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); - else - sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); + PushItemWidth(w_slider_all - style.ItemInnerSpacing.x); + if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) + { + value_changed |= true; + char* p = buf; + while (*p == '#' || ImCharIsSpace(*p)) + p++; + i[0] = i[1] = i[2] = i[3] = 0; + if (alpha) + sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned) + else + sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); + } + PopItemWidth(); } break; } - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, style.ItemInnerSpacing.x); const ImVec4 col_display(col[0], col[1], col[2], 1.0f); - if (ImGui::ColorButton(col_display)) + if (ColorButton(col_display)) g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! + // Recreate our own tooltip over's ColorButton() one because we want to display correct alpha here + if (IsItemHovered()) + SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col[0], col[1], col[2], col[3], IM_F32_TO_INT8_SAT(col[0]), IM_F32_TO_INT8_SAT(col[1]), IM_F32_TO_INT8_SAT(col[2]), IM_F32_TO_INT8_SAT(col[3])); + if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) { - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, style.ItemInnerSpacing.x); const char* button_titles[3] = { "RGB", "HSV", "HEX" }; - if (ImGui::Button(button_titles[edit_mode])) + if (ButtonEx(button_titles[edit_mode], ImVec2(0,0), ImGuiButtonFlags_DontClosePopups)) g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! - ImGui::SameLine(); } - else + + const char* label_display_end = FindRenderedTextEnd(label); + if (label != label_display_end) { - ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); + SameLine(0, (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) ? -1.0f : style.ItemInnerSpacing.x); + TextUnformatted(label, label_display_end); } - ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); - // Convert back for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; if (edit_mode == 1) - ImGui::ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); + ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); if (value_changed) { @@ -7096,8 +9066,8 @@ bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) col[3] = f[3]; } - ImGui::PopID(); - ImGui::EndGroup(); + PopID(); + EndGroup(); return value_changed; } @@ -7118,8 +9088,13 @@ void ImGui::Separator() if (window->DC.ColumnsCount > 1) PopClipRect(); - const ImRect bb(ImVec2(window->Pos.x, window->DC.CursorPos.y), ImVec2(window->Pos.x + window->Size.x, window->DC.CursorPos.y)); - ItemSize(ImVec2(0.0f, bb.GetSize().y)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit + float x1 = window->Pos.x; + float x2 = window->Pos.x + window->Size.x; + if (!window->DC.GroupStack.empty()) + x1 += window->DC.IndentX; + + const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y)); + ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit // FIXME: Height should be 1.0f not 0.0f ? if (!ItemAdd(bb, NULL)) { if (window->DC.ColumnsCount > 1) @@ -7127,11 +9102,11 @@ void ImGui::Separator() return; } - window->DrawList->AddLine(bb.Min, bb.Max, window->Color(ImGuiCol_Border)); + window->DrawList->AddLine(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border)); - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; if (g.LogEnabled) - ImGui::LogText(STR_NEWLINE "--------------------------------"); + LogText(IM_NEWLINE "--------------------------------"); if (window->DC.ColumnsCount > 1) { @@ -7140,106 +9115,56 @@ void ImGui::Separator() } } -// A little vertical spacing. void ImGui::Spacing() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - ItemSize(ImVec2(0,0)); } -// Advance cursor given item size. -static void ItemSize(ImVec2 size, float text_offset_y) +void ImGui::Dummy(const ImVec2& size) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - // Always align ourselves on pixel boundaries - const float line_height = ImMax(window->DC.CurrentLineHeight, size.y); - const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); - window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); - window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); - window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); - window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); - - //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, 0xFF0000FF, 4); // Debug + const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); + ItemSize(bb); + ItemAdd(bb, NULL); +} - window->DC.PrevLineHeight = line_height; - window->DC.PrevLineTextBaseOffset = text_base_offset; - window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f; +bool ImGui::IsRectVisible(const ImVec2& size) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); } -static inline void ItemSize(const ImRect& bb, float text_offset_y) -{ - ItemSize(bb.GetSize(), text_offset_y); +bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) +{ + ImGuiWindow* window = GetCurrentWindowRead(); + return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); } -static bool IsClipped(const ImRect& bb) +// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) +void ImGui::BeginGroup() { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - if (!bb.Overlaps(ImRect(window->ClipRectStack.back())) && !g.LogEnabled) - return true; - return false; -} - -bool ImGui::IsClipped(const ImVec2& item_size) -{ - ImGuiWindow* window = GetCurrentWindow(); - return IsClipped(ImRect(window->DC.CursorPos, window->DC.CursorPos + item_size)); -} - -static bool ItemAdd(const ImRect& bb, const ImGuiID* id) -{ - ImGuiWindow* window = GetCurrentWindow(); - window->DC.LastItemID = id ? *id : 0; - window->DC.LastItemRect = bb; - if (IsClipped(bb)) - { - window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; - return false; - } - - // This is a sensible default, but widgets are free to override it after calling ItemAdd() - ImGuiState& g = *GImGui; - if (IsMouseHoveringRect(bb)) - { - // Matching the behavior of IsHovered() but ignore if ActiveId==window->MoveID (we clicked on the window background) - // So that clicking on items with no active id such as Text() still returns true with IsItemHovered() - window->DC.LastItemHoveredRect = true; - window->DC.LastItemHoveredAndUsable = false; - if (g.HoveredRootWindow == window->RootWindow) - if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdIsFocusedOnly || (g.ActiveId == window->MoveID)) - if (IsWindowContentHoverable(window)) - window->DC.LastItemHoveredAndUsable = true; - } - else - { - window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; - } - - return true; -} - -void ImGui::BeginGroup() -{ - ImGuiWindow* window = GetCurrentWindow(); - - window->DC.GroupStack.resize(window->DC.GroupStack.size() + 1); + window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); ImGuiGroupData& group_data = window->DC.GroupStack.back(); group_data.BackupCursorPos = window->DC.CursorPos; group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; - group_data.BackupColumnsStartX = window->DC.ColumnsStartX; + group_data.BackupIndentX = window->DC.IndentX; + group_data.BackupGroupOffsetX = window->DC.GroupOffsetX; group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight; group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; group_data.BackupLogLinePosY = window->DC.LogLinePosY; + group_data.BackupActiveIdIsAlive = GImGui->ActiveIdIsAlive; + group_data.AdvanceCursor = true; - window->DC.ColumnsStartX = window->DC.CursorPos.x - window->Pos.x; + window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX; + window->DC.IndentX = window->DC.GroupOffsetX; window->DC.CursorMaxPos = window->DC.CursorPos; window->DC.CurrentLineHeight = 0.0f; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; @@ -7247,173 +9172,212 @@ void ImGui::BeginGroup() void ImGui::EndGroup() { + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - ImGuiStyle& style = ImGui::GetStyle(); - IM_ASSERT(!window->DC.GroupStack.empty()); + IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls ImGuiGroupData& group_data = window->DC.GroupStack.back(); ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos); - group_bb.Max.y -= style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves. + group_bb.Max.y -= g.Style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves. group_bb.Max = ImMax(group_bb.Min, group_bb.Max); window->DC.CursorPos = group_data.BackupCursorPos; window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight; - window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; // FIXME: Ideally we'll grab the base offset from the first line of the group. - window->DC.ColumnsStartX = group_data.BackupColumnsStartX; + window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; + window->DC.IndentX = group_data.BackupIndentX; + window->DC.GroupOffsetX = group_data.BackupGroupOffsetX; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; - ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); - ItemAdd(group_bb, NULL); + if (group_data.AdvanceCursor) + { + window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. + ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); + ItemAdd(group_bb, NULL); + } + + // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will function on the entire group. + // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but if you search for LastItemId you'll notice it is only used in that context. + const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow); + if (active_id_within_group) + window->DC.LastItemId = g.ActiveId; + if (active_id_within_group && g.HoveredId == g.ActiveId) + window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = true; window->DC.GroupStack.pop_back(); - //window->DrawList->AddRect(group_bb.Min, group_bb.Max, 0xFFFF00FF); // Debug + //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // Debug } // Gets back to previous line and continue with horizontal layout -// column_x == 0 : follow on previous item -// columm_x != 0 : align to specified column -// spacing_w < 0 : use default spacing if column_x==0, no spacing if column_x!=0 -// spacing_w >= 0 : enforce spacing -void ImGui::SameLine(int column_x, int spacing_w) +// pos_x == 0 : follow right after previous item +// pos_x != 0 : align to specified x position (relative to window/group left) +// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 +// spacing_w >= 0 : enforce spacing amount +void ImGui::SameLine(float pos_x, float spacing_w) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; - - float x, y; - if (column_x != 0) + + ImGuiContext& g = *GImGui; + if (pos_x != 0.0f) { - if (spacing_w < 0) spacing_w = 0; - x = window->Pos.x + (float)column_x + (float)spacing_w; - y = window->DC.CursorPosPrevLine.y; + if (spacing_w < 0.0f) spacing_w = 0.0f; + window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } else { - if (spacing_w < 0) spacing_w = (int)g.Style.ItemSpacing.x; - x = window->DC.CursorPosPrevLine.x + (float)spacing_w; - y = window->DC.CursorPosPrevLine.y; + if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x; + window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; + window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } window->DC.CurrentLineHeight = window->DC.PrevLineHeight; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; - window->DC.CursorPos = ImVec2(x, y); } -void ImGui::NextColumn() +void ImGui::NewLine() { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; + if (window->DC.CurrentLineHeight > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. + ItemSize(ImVec2(0,0)); + else + ItemSize(ImVec2(0.0f, GImGui->FontSize)); +} - if (window->DC.ColumnsCount > 1) - { - ImGui::PopItemWidth(); - PopClipRect(); +void ImGui::NextColumn() +{ + ImGuiWindow* window = GetCurrentWindow(); + if (window->SkipItems || window->DC.ColumnsCount <= 1) + return; - window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); - if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount) - { - window->DC.ColumnsOffsetX = ImGui::GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.ColumnsStartX + g.Style.ItemSpacing.x; - } - else - { - window->DC.ColumnsCurrent = 0; - window->DC.ColumnsOffsetX = 0.0f; - window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY; - } - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX); - window->DC.CursorPos.y = window->DC.ColumnsCellMinY; - window->DC.CurrentLineHeight = 0.0f; - window->DC.CurrentLineTextBaseOffset = 0.0f; + ImGuiContext& g = *GImGui; + PopItemWidth(); + PopClipRect(); - PushColumnClipRect(); - ImGui::PushItemWidth(ImGui::GetColumnWidth() * 0.65f); + window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); + if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount) + { + // Columns 1+ cancel out IndentX + window->DC.ColumnsOffsetX = GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.IndentX + g.Style.ItemSpacing.x; + window->DrawList->ChannelsSetCurrent(window->DC.ColumnsCurrent); } + else + { + window->DC.ColumnsCurrent = 0; + window->DC.ColumnsOffsetX = 0.0f; + window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY; + window->DrawList->ChannelsSetCurrent(0); + } + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); + window->DC.CursorPos.y = window->DC.ColumnsCellMinY; + window->DC.CurrentLineHeight = 0.0f; + window->DC.CurrentLineTextBaseOffset = 0.0f; + + PushColumnClipRect(); + PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup } int ImGui::GetColumnIndex() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.ColumnsCurrent; } int ImGui::GetColumnsCount() { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.ColumnsCount; } +static float GetDraggedColumnOffset(int column_index) +{ + // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing + // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. + ImGuiContext& g = *GImGui; + ImGuiWindow* window = ImGui::GetCurrentWindowRead(); + IM_ASSERT(column_index > 0); // We cannot drag column 0. If you get this assert you may have a conflict between the ID of your columns and another widgets. + IM_ASSERT(g.ActiveId == window->DC.ColumnsSetId + ImGuiID(column_index)); + + float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x - window->Pos.x; + x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing); + + return (float)(int)x; +} + float ImGui::GetColumnOffset(int column_index) { - ImGuiState& g = *GImGui; - ImGuiWindow* window = GetCurrentWindow(); + ImGuiContext& g = *GImGui; + ImGuiWindow* window = GetCurrentWindowRead(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; - // Read from cache - IM_ASSERT(column_index < (int)window->DC.ColumnsOffsetsT.size()); - const float t = window->DC.ColumnsOffsetsT[column_index]; + if (g.ActiveId) + { + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); + if (g.ActiveId == column_id) + return GetDraggedColumnOffset(column_index); + } - const float min_x = window->DC.ColumnsStartX; - const float max_x = window->Size.x - (g.Style.ScrollbarWidth);// - window->WindowPadding().x; - const float offset = min_x + t * (max_x - min_x); - return offset; + IM_ASSERT(column_index < window->DC.ColumnsData.Size); + const float t = window->DC.ColumnsData[column_index].OffsetNorm; + const float x_offset = window->DC.ColumnsMinX + t * (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); + return (float)(int)x_offset; } void ImGui::SetColumnOffset(int column_index, float offset) { - ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; - IM_ASSERT(column_index < (int)window->DC.ColumnsOffsetsT.size()); - const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index); + IM_ASSERT(column_index < window->DC.ColumnsData.Size); + const float t = (offset - window->DC.ColumnsMinX) / (window->DC.ColumnsMaxX - window->DC.ColumnsMinX); + window->DC.ColumnsData[column_index].OffsetNorm = t; - const float min_x = window->DC.ColumnsStartX; - const float max_x = window->Size.x - (g.Style.ScrollbarWidth);// - window->WindowPadding().x; - const float t = (offset - min_x) / (max_x - min_x); + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); window->DC.StateStorage->SetFloat(column_id, t); - window->DC.ColumnsOffsetsT[column_index] = t; } float ImGui::GetColumnWidth(int column_index) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = GetCurrentWindowRead(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; - const float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index); + float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index); return w; } static void PushColumnClipRect(int column_index) { - ImGuiWindow* window = GetCurrentWindow(); + ImGuiWindow* window = ImGui::GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; - const float x1 = window->Pos.x + ImGui::GetColumnOffset(column_index) - 1; - const float x2 = window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1; - PushClipRect(ImVec4(x1,-FLT_MAX,x2,+FLT_MAX)); + float x1 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index) - 1.0f); + float x2 = ImFloor(0.5f + window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1.0f); + ImGui::PushClipRect(ImVec2(x1,-FLT_MAX), ImVec2(x2,+FLT_MAX), true); } void ImGui::Columns(int columns_count, const char* id, bool border) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); + IM_ASSERT(columns_count >= 1); if (window->DC.ColumnsCount != 1) { if (window->DC.ColumnsCurrent != 0) ItemSize(ImVec2(0,0)); // Advance to column 0 - ImGui::PopItemWidth(); + PopItemWidth(); PopClipRect(); + window->DrawList->ChannelsMerge(); window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = window->DC.ColumnsCellMaxY; @@ -7422,93 +9386,97 @@ void ImGui::Columns(int columns_count, const char* id, bool border) // Draw columns borders and handle resize at the time of "closing" a columns set if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems) { - const float y1 = window->DC.ColumnsStartPos.y; + const float y1 = window->DC.ColumnsStartPosY; const float y2 = window->DC.CursorPos.y; for (int i = 1; i < window->DC.ColumnsCount; i++) { float x = window->Pos.x + GetColumnOffset(i); - - const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(i); + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(i); const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2)); - - if (IsClipped(column_rect)) + if (IsClippedEx(column_rect, &column_id, false)) continue; bool hovered, held; - ButtonBehavior(column_rect, column_id, &hovered, &held, true); + ButtonBehavior(column_rect, column_id, &hovered, &held); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeEW; // Draw before resize so our items positioning are in sync with the line being drawn - const ImU32 col = window->Color(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); + const ImU32 col = GetColorU32(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); const float xi = (float)(int)x; - window->DrawList->AddLine(ImVec2(xi, y1), ImVec2(xi, y2), col); + window->DrawList->AddLine(ImVec2(xi, y1+1.0f), ImVec2(xi, y2), col); if (held) { - x -= window->Pos.x; - x = ImClamp(x + g.IO.MouseDelta.x, ImGui::GetColumnOffset(i-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(i+1)-g.Style.ColumnsMinSpacing); + if (g.ActiveIdIsJustActivated) + g.ActiveIdClickOffset.x -= 4; // Store from center of column line (we used a 8 wide rect for columns clicking) + x = GetDraggedColumnOffset(i); SetColumnOffset(i, x); - x += window->Pos.x; } } } + // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. + // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. + PushID(0x11223347 + (id ? 0 : columns_count)); + window->DC.ColumnsSetId = window->GetID(id ? id : "columns"); + PopID(); + // Set state for first column - window->DC.ColumnsSetID = window->GetID(id ? id : ""); window->DC.ColumnsCurrent = 0; window->DC.ColumnsCount = columns_count; window->DC.ColumnsShowBorders = border; - window->DC.ColumnsStartPos = window->DC.CursorPos; + + const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : window->Size.x; + window->DC.ColumnsMinX = window->DC.IndentX; // Lock our horizontal range + window->DC.ColumnsMaxX = content_region_width - window->Scroll.x - ((window->Flags & ImGuiWindowFlags_NoScrollbar) ? 0 : g.Style.ScrollbarSize);// - window->WindowPadding().x; + window->DC.ColumnsStartPosY = window->DC.CursorPos.y; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffsetX = 0.0f; - window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX); + window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX); if (window->DC.ColumnsCount != 1) { // Cache column offsets - window->DC.ColumnsOffsetsT.resize((size_t)columns_count + 1); + window->DC.ColumnsData.resize(columns_count + 1); for (int column_index = 0; column_index < columns_count + 1; column_index++) { - const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index); - RegisterAliveId(column_id); + const ImGuiID column_id = window->DC.ColumnsSetId + ImGuiID(column_index); + KeepAliveID(column_id); const float default_t = column_index / (float)window->DC.ColumnsCount; - const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store an union into the map?) - window->DC.ColumnsOffsetsT[column_index] = t; + const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store a union into the map?) + window->DC.ColumnsData[column_index].OffsetNorm = t; } - + window->DrawList->ChannelsSplit(window->DC.ColumnsCount); PushColumnClipRect(); - ImGui::PushItemWidth(ImGui::GetColumnWidth() * 0.65f); + PushItemWidth(GetColumnWidth() * 0.65f); } else { - window->DC.ColumnsOffsetsT.resize(2); - window->DC.ColumnsOffsetsT[0] = 0.0f; - window->DC.ColumnsOffsetsT[1] = 1.0f; + window->DC.ColumnsData.resize(0); } } - -inline void ImGui::Indent() +void ImGui::Indent(float indent_w) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - window->DC.ColumnsStartX += g.Style.IndentSpacing; - window->DC.CursorPos.x = window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX; + window->DC.IndentX += (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; } -inline void ImGui::Unindent() +void ImGui::Unindent(float indent_w) { - ImGuiState& g = *GImGui; + ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); - window->DC.ColumnsStartX -= g.Style.IndentSpacing; - window->DC.CursorPos.x = window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX; + window->DC.IndentX -= (indent_w > 0.0f) ? indent_w : g.Style.IndentSpacing; + window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX; } void ImGui::TreePush(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); - ImGui::Indent(); + Indent(); window->DC.TreeDepth++; PushID(str_id ? str_id : "#TreePush"); } @@ -7516,32 +9484,40 @@ void ImGui::TreePush(const char* str_id) void ImGui::TreePush(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); - ImGui::Indent(); + Indent(); window->DC.TreeDepth++; PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); } +void ImGui::TreePushRawID(ImGuiID id) +{ + ImGuiWindow* window = GetCurrentWindow(); + Indent(); + window->DC.TreeDepth++; + window->IDStack.push_back(id); +} + void ImGui::TreePop() { ImGuiWindow* window = GetCurrentWindow(); - ImGui::Unindent(); + Unindent(); window->DC.TreeDepth--; PopID(); } void ImGui::Value(const char* prefix, bool b) { - ImGui::Text("%s: %s", prefix, (b ? "true" : "false")); + Text("%s: %s", prefix, (b ? "true" : "false")); } void ImGui::Value(const char* prefix, int v) { - ImGui::Text("%s: %d", prefix, v); + Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, unsigned int v) { - ImGui::Text("%s: %d", prefix, v); + Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, float v, const char* float_format) @@ -7550,3692 +9526,269 @@ void ImGui::Value(const char* prefix, float v, const char* float_format) { char fmt[64]; ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); - ImGui::Text(fmt, prefix, v); + Text(fmt, prefix, v); } else { - ImGui::Text("%s: %.3f", prefix, v); + Text("%s: %.3f", prefix, v); } } -void ImGui::Color(const char* prefix, const ImVec4& v) +// FIXME: May want to remove those helpers? +void ImGui::ValueColor(const char* prefix, const ImVec4& v) { - ImGui::Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w); - ImGui::SameLine(); - ImGui::ColorButton(v, true); + Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w); + SameLine(); + ColorButton(v, true); } -void ImGui::Color(const char* prefix, unsigned int v) +void ImGui::ValueColor(const char* prefix, ImU32 v) { - ImGui::Text("%s: %08X", prefix, v); - ImGui::SameLine(); - - ImVec4 col; - col.x = (float)((v >> 0) & 0xFF) / 255.0f; - col.y = (float)((v >> 8) & 0xFF) / 255.0f; - col.z = (float)((v >> 16) & 0xFF) / 255.0f; - col.w = (float)((v >> 24) & 0xFF) / 255.0f; - ImGui::ColorButton(col, true); + Text("%s: %08X", prefix, v); + SameLine(); + ColorButton(ColorConvertU32ToFloat4(v), true); } //----------------------------------------------------------------------------- -// ImDrawList +// PLATFORM DEPENDENT HELPERS //----------------------------------------------------------------------------- -static ImVec4 GNullClipRect(-9999.0f,-9999.0f, +9999.0f, +9999.0f); - -void ImDrawList::Clear() -{ - commands.resize(0); - vtx_buffer.resize(0); - vtx_write = NULL; - clip_rect_stack.resize(0); - texture_id_stack.resize(0); -} - -void ImDrawList::ClearFreeMemory() -{ - commands.clear(); - vtx_buffer.clear(); - vtx_write = NULL; - clip_rect_stack.clear(); - texture_id_stack.clear(); -} - -void ImDrawList::AddDrawCmd() -{ - ImDrawCmd draw_cmd; - draw_cmd.vtx_count = 0; - draw_cmd.clip_rect = clip_rect_stack.empty() ? GNullClipRect : clip_rect_stack.back(); - draw_cmd.texture_id = texture_id_stack.empty() ? NULL : texture_id_stack.back(); - draw_cmd.user_callback = NULL; - draw_cmd.user_callback_data = NULL; - - IM_ASSERT(draw_cmd.clip_rect.x <= draw_cmd.clip_rect.z && draw_cmd.clip_rect.y <= draw_cmd.clip_rect.w); - commands.push_back(draw_cmd); -} +#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS)) +#undef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#include <windows.h> +#endif -void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) -{ - ImDrawCmd* current_cmd = commands.empty() ? NULL : &commands.back(); - if (!current_cmd || current_cmd->vtx_count != 0 || current_cmd->user_callback != NULL) - { - AddDrawCmd(); - current_cmd = &commands.back(); - } - current_cmd->user_callback = callback; - current_cmd->user_callback_data = callback_data; +// Win32 API clipboard implementation +#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) - // Force a new command after us - // We function this way so that the most common calls (AddLine, AddRect..) always have a command to add to without doing any check. - AddDrawCmd(); -} +#ifdef _MSC_VER +#pragma comment(lib, "user32") +#endif -void ImDrawList::UpdateClipRect() +static const char* GetClipboardTextFn_DefaultImpl() { - ImDrawCmd* current_cmd = commands.empty() ? NULL : &commands.back(); - if (!current_cmd || (current_cmd->vtx_count != 0) || current_cmd->user_callback != NULL) - { - AddDrawCmd(); - } - else + static ImVector<char> buf_local; + buf_local.clear(); + if (!OpenClipboard(NULL)) + return NULL; + HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT); + if (wbuf_handle == NULL) + return NULL; + if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle)) { - current_cmd->clip_rect = clip_rect_stack.empty() ? GNullClipRect : clip_rect_stack.back(); + int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; + buf_local.resize(buf_len); + ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL); } + GlobalUnlock(wbuf_handle); + CloseClipboard(); + return buf_local.Data; } -// Scissoring. The values in clip_rect are x1, y1, x2, y2. -void ImDrawList::PushClipRect(const ImVec4& clip_rect) +static void SetClipboardTextFn_DefaultImpl(const char* text) { - clip_rect_stack.push_back(clip_rect); - UpdateClipRect(); + if (!OpenClipboard(NULL)) + return; + const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; + HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); + if (wbuf_handle == NULL) + return; + ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle); + ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); + GlobalUnlock(wbuf_handle); + EmptyClipboard(); + SetClipboardData(CF_UNICODETEXT, wbuf_handle); + CloseClipboard(); } -void ImDrawList::PushClipRectFullScreen() -{ - PushClipRect(GNullClipRect); - - // This would be more correct but we're not supposed to access ImGuiState from here? - //ImGuiState& g = *GImGui; - //if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) - // PushClipRect(ImVec4(g.IO.DisplayVisibleMin.x, g.IO.DisplayVisibleMin.y, g.IO.DisplayVisibleMax.x, g.IO.DisplayVisibleMax.y)); - //else - // PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); -} +#else -void ImDrawList::PopClipRect() +// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +static const char* GetClipboardTextFn_DefaultImpl() { - IM_ASSERT(clip_rect_stack.size() > 0); - clip_rect_stack.pop_back(); - UpdateClipRect(); + return GImGui->PrivateClipboard; } -void ImDrawList::UpdateTextureID() +// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers +static void SetClipboardTextFn_DefaultImpl(const char* text) { - ImDrawCmd* current_cmd = commands.empty() ? NULL : &commands.back(); - const ImTextureID texture_id = texture_id_stack.empty() ? NULL : texture_id_stack.back(); - if (!current_cmd || (current_cmd->vtx_count != 0 && current_cmd->texture_id != texture_id) || current_cmd->user_callback != NULL) - { - AddDrawCmd(); - } - else + ImGuiContext& g = *GImGui; + if (g.PrivateClipboard) { - current_cmd->texture_id = texture_id; + ImGui::MemFree(g.PrivateClipboard); + g.PrivateClipboard = NULL; } + const char* text_end = text + strlen(text); + g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1); + memcpy(g.PrivateClipboard, text, (size_t)(text_end - text)); + g.PrivateClipboard[(int)(text_end - text)] = 0; } -void ImDrawList::PushTextureID(const ImTextureID& texture_id) -{ - texture_id_stack.push_back(texture_id); - UpdateTextureID(); -} +#endif -void ImDrawList::PopTextureID() -{ - IM_ASSERT(texture_id_stack.size() > 0); - texture_id_stack.pop_back(); - UpdateTextureID(); -} +// Win32 API IME support (for Asian languages, etc.) +#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS) -void ImDrawList::ReserveVertices(unsigned int vtx_count) -{ - if (vtx_count > 0) - { - ImDrawCmd& draw_cmd = commands.back(); - draw_cmd.vtx_count += vtx_count; - vtx_buffer.resize(vtx_buffer.size() + vtx_count); - vtx_write = &vtx_buffer[vtx_buffer.size() - vtx_count]; - } -} +#include <imm.h> +#ifdef _MSC_VER +#pragma comment(lib, "imm32") +#endif -void ImDrawList::AddVtx(const ImVec2& pos, ImU32 col) +static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) { - vtx_write->pos = pos; - vtx_write->col = col; - vtx_write->uv = GImGui->FontTexUvWhitePixel; - vtx_write++; + // Notify OS Input Method Editor of text input position + if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) + if (HIMC himc = ImmGetContext(hwnd)) + { + COMPOSITIONFORM cf; + cf.ptCurrentPos.x = x; + cf.ptCurrentPos.y = y; + cf.dwStyle = CFS_FORCE_POSITION; + ImmSetCompositionWindow(himc, &cf); + } } -void ImDrawList::AddVtxUV(const ImVec2& pos, ImU32 col, const ImVec2& uv) -{ - vtx_write->pos = pos; - vtx_write->col = col; - vtx_write->uv = uv; - vtx_write++; -} +#else -// NB: memory should be reserved for 6 vertices by the caller. -void ImDrawList::AddVtxLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) -{ - const float inv_length = 1.0f / sqrtf(ImLengthSqr(b - a)); - const ImVec2 hn = (b - a) * (thickness * 0.5f * inv_length);// half normal - const ImVec2 hp0 = ImVec2(+hn.y, -hn.x); // half perpendiculars + user offset - const ImVec2 hp1 = ImVec2(-hn.y, +hn.x); +static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} - // Two triangles makes up one line. Using triangles allows us to reduce amount of draw calls. - AddVtx(a + hp0, col); - AddVtx(b + hp0, col); - AddVtx(a + hp1, col); - AddVtx(b + hp0, col); - AddVtx(b + hp1, col); - AddVtx(a + hp1, col); -} +#endif + +//----------------------------------------------------------------------------- +// HELP +//----------------------------------------------------------------------------- -void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) +void ImGui::ShowMetricsWindow(bool* p_open) { - if ((col >> 24) == 0) - return; + if (ImGui::Begin("ImGui Metrics", p_open)) + { + ImGui::Text("ImGui %s", ImGui::GetVersion()); + ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); + ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3); + ImGui::Text("%d allocations", ImGui::GetIO().MetricsAllocs); + static bool show_clip_rects = true; + ImGui::Checkbox("Show clipping rectangles when hovering a ImDrawCmd", &show_clip_rects); + ImGui::Separator(); - ReserveVertices(6); - AddVtxLine(a, b, col, thickness); -} + struct Funcs + { + static void NodeDrawList(ImDrawList* draw_list, const char* label) + { + bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); + if (draw_list == ImGui::GetWindowDrawList()) + { + ImGui::SameLine(); + ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) + if (node_open) ImGui::TreePop(); + return; + } + if (!node_open) + return; -void ImDrawList::AddArc(const ImVec2& center, float rad, ImU32 col, int a_min, int a_max, bool tris, const ImVec2& third_point_offset) -{ - if ((col >> 24) == 0) - return; + ImDrawList* overlay_draw_list = &GImGui->OverlayDrawList; // Render additional visuals into the top-most draw list + overlay_draw_list->PushClipRectFullScreen(); + int elem_offset = 0; + for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) + { + if (pcmd->UserCallback) + { + ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); + continue; + } + ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; + bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %-4d %s vtx, tex = %p, clip_rect = (%.0f,%.0f)..(%.0f,%.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); + if (show_clip_rects && ImGui::IsItemHovered()) + { + ImRect clip_rect = pcmd->ClipRect; + ImRect vtxs_rect; + for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) + vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); + clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); + vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); + } + if (!pcmd_node_open) + continue; + ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. + while (clipper.Step()) + for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) + { + char buf[300], *buf_p = buf; + ImVec2 triangles_pos[3]; + for (int n = 0; n < 3; n++, vtx_i++) + { + ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i]; + triangles_pos[n] = v.pos; + buf_p += sprintf(buf_p, "%s %04d { pos = (%8.2f,%8.2f), uv = (%.6f,%.6f), col = %08X }\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); + } + ImGui::Selectable(buf, false); + if (ImGui::IsItemHovered()) + overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f, false); // Add triangle without AA, more readable for large-thin triangle + } + ImGui::TreePop(); + } + overlay_draw_list->PopClipRect(); + ImGui::TreePop(); + } - static ImVec2 circle_vtx[12]; - static bool circle_vtx_builds = false; - if (!circle_vtx_builds) - { - for (int i = 0; i < IM_ARRAYSIZE(circle_vtx); i++) + static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label) + { + if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) + return; + for (int i = 0; i < windows.Size; i++) + Funcs::NodeWindow(windows[i], "Window"); + ImGui::TreePop(); + } + + static void NodeWindow(ImGuiWindow* window, const char* label) + { + if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) + return; + NodeDrawList(window->DrawList, "DrawList"); + ImGui::BulletText("Pos: (%.1f,%.1f)", window->Pos.x, window->Pos.y); + ImGui::BulletText("Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y); + ImGui::BulletText("Scroll: (%.2f,%.2f)", window->Scroll.x, window->Scroll.y); + if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); + if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); + ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair)); + ImGui::TreePop(); + } + }; + + ImGuiContext& g = *GImGui; // Access private state + Funcs::NodeWindows(g.Windows, "Windows"); + if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.RenderDrawLists[0].Size)) { - const float a = ((float)i / (float)IM_ARRAYSIZE(circle_vtx)) * 2*PI; - circle_vtx[i].x = cosf(a + PI); - circle_vtx[i].y = sinf(a + PI); + for (int i = 0; i < g.RenderDrawLists[0].Size; i++) + Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList"); + ImGui::TreePop(); } - circle_vtx_builds = true; - } - - if (tris) - { - ReserveVertices((unsigned int)(a_max-a_min) * 3); - for (int a = a_min; a < a_max; a++) + if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size)) + { + for (int i = 0; i < g.OpenPopupStack.Size; i++) + { + ImGuiWindow* window = g.OpenPopupStack[i].Window; + ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); + } + ImGui::TreePop(); + } + if (ImGui::TreeNode("Basic state")) { - AddVtx(center + circle_vtx[a % IM_ARRAYSIZE(circle_vtx)] * rad, col); - AddVtx(center + circle_vtx[(a+1) % IM_ARRAYSIZE(circle_vtx)] * rad, col); - AddVtx(center + third_point_offset, col); + ImGui::Text("FocusedWindow: '%s'", g.FocusedWindow ? g.FocusedWindow->Name : "NULL"); + ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); + ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); + ImGui::Text("HoveredID: 0x%08X/0x%08X", g.HoveredId, g.HoveredIdPreviousFrame); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not + ImGui::Text("ActiveID: 0x%08X/0x%08X", g.ActiveId, g.ActiveIdPreviousFrame); + ImGui::TreePop(); } } - else - { - ReserveVertices((unsigned int)(a_max-a_min) * 6); - for (int a = a_min; a < a_max; a++) - AddVtxLine(center + circle_vtx[a % IM_ARRAYSIZE(circle_vtx)] * rad, center + circle_vtx[(a+1) % IM_ARRAYSIZE(circle_vtx)] * rad, col); - } -} - -void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) -{ - if ((col >> 24) == 0) - return; - - float r = rounding; - r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f )); - r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f )); - - if (r == 0.0f || rounding_corners == 0) - { - ReserveVertices(4*6); - AddVtxLine(ImVec2(a.x,a.y), ImVec2(b.x,a.y), col); - AddVtxLine(ImVec2(b.x,a.y), ImVec2(b.x,b.y), col); - AddVtxLine(ImVec2(b.x,b.y), ImVec2(a.x,b.y), col); - AddVtxLine(ImVec2(a.x,b.y), ImVec2(a.x,a.y), col); - } - else - { - ReserveVertices(4*6); - AddVtxLine(ImVec2(a.x + ((rounding_corners & 1)?r:0), a.y), ImVec2(b.x - ((rounding_corners & 2)?r:0), a.y), col); - AddVtxLine(ImVec2(b.x, a.y + ((rounding_corners & 2)?r:0)), ImVec2(b.x, b.y - ((rounding_corners & 4)?r:0)), col); - AddVtxLine(ImVec2(b.x - ((rounding_corners & 4)?r:0), b.y), ImVec2(a.x + ((rounding_corners & 8)?r:0), b.y), col); - AddVtxLine(ImVec2(a.x, b.y - ((rounding_corners & 8)?r:0)), ImVec2(a.x, a.y + ((rounding_corners & 1)?r:0)), col); - - if (rounding_corners & 1) AddArc(ImVec2(a.x+r,a.y+r), r, col, 0, 3); - if (rounding_corners & 2) AddArc(ImVec2(b.x-r,a.y+r), r, col, 3, 6); - if (rounding_corners & 4) AddArc(ImVec2(b.x-r,b.y-r), r, col, 6, 9); - if (rounding_corners & 8) AddArc(ImVec2(a.x+r,b.y-r), r, col, 9, 12); - } -} - -void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) -{ - if ((col >> 24) == 0) - return; - - float r = rounding; - r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f )); - r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f )); - - if (r == 0.0f || rounding_corners == 0) - { - // Use triangle so we can merge more draw calls together (at the cost of extra vertices) - ReserveVertices(6); - AddVtx(ImVec2(a.x,a.y), col); - AddVtx(ImVec2(b.x,a.y), col); - AddVtx(ImVec2(b.x,b.y), col); - AddVtx(ImVec2(a.x,a.y), col); - AddVtx(ImVec2(b.x,b.y), col); - AddVtx(ImVec2(a.x,b.y), col); - } - else - { - ReserveVertices(6+6*2); - AddVtx(ImVec2(a.x+r,a.y), col); - AddVtx(ImVec2(b.x-r,a.y), col); - AddVtx(ImVec2(b.x-r,b.y), col); - AddVtx(ImVec2(a.x+r,a.y), col); - AddVtx(ImVec2(b.x-r,b.y), col); - AddVtx(ImVec2(a.x+r,b.y), col); - - float top_y = (rounding_corners & 1) ? a.y+r : a.y; - float bot_y = (rounding_corners & 8) ? b.y-r : b.y; - AddVtx(ImVec2(a.x,top_y), col); - AddVtx(ImVec2(a.x+r,top_y), col); - AddVtx(ImVec2(a.x+r,bot_y), col); - AddVtx(ImVec2(a.x,top_y), col); - AddVtx(ImVec2(a.x+r,bot_y), col); - AddVtx(ImVec2(a.x,bot_y), col); - - top_y = (rounding_corners & 2) ? a.y+r : a.y; - bot_y = (rounding_corners & 4) ? b.y-r : b.y; - AddVtx(ImVec2(b.x-r,top_y), col); - AddVtx(ImVec2(b.x,top_y), col); - AddVtx(ImVec2(b.x,bot_y), col); - AddVtx(ImVec2(b.x-r,top_y), col); - AddVtx(ImVec2(b.x,bot_y), col); - AddVtx(ImVec2(b.x-r,bot_y), col); - - if (rounding_corners & 1) AddArc(ImVec2(a.x+r,a.y+r), r, col, 0, 3, true); - if (rounding_corners & 2) AddArc(ImVec2(b.x-r,a.y+r), r, col, 3, 6, true); - if (rounding_corners & 4) AddArc(ImVec2(b.x-r,b.y-r), r, col, 6, 9, true); - if (rounding_corners & 8) AddArc(ImVec2(a.x+r,b.y-r), r, col, 9, 12,true); - } -} - -void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) -{ - if ((col >> 24) == 0) - return; - - ReserveVertices(3); - AddVtx(a, col); - AddVtx(b, col); - AddVtx(c, col); -} - -void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments) -{ - if ((col >> 24) == 0) - return; - - ReserveVertices((unsigned int)num_segments*6); - const float a_step = 2*PI/(float)num_segments; - float a0 = 0.0f; - for (int i = 0; i < num_segments; i++) - { - const float a1 = (i + 1) == num_segments ? 0.0f : a0 + a_step; - AddVtxLine(centre + ImVec2(cosf(a0), sinf(a0))*radius, centre + ImVec2(cosf(a1), sinf(a1))*radius, col); - a0 = a1; - } -} - -void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) -{ - if ((col >> 24) == 0) - return; - - ReserveVertices((unsigned int)num_segments*3); - const float a_step = 2*PI/(float)num_segments; - float a0 = 0.0f; - for (int i = 0; i < num_segments; i++) - { - const float a1 = (i + 1) == num_segments ? 0.0f : a0 + a_step; - AddVtx(centre + ImVec2(cosf(a0), sinf(a0))*radius, col); - AddVtx(centre + ImVec2(cosf(a1), sinf(a1))*radius, col); - AddVtx(centre, col); - a0 = a1; - } -} - -void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec2* cpu_clip_max) -{ - if ((col >> 24) == 0) - return; - - if (text_end == NULL) - text_end = text_begin + strlen(text_begin); - - IM_ASSERT(font->ContainerAtlas->TexID == texture_id_stack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. - - // reserve vertices for worse case - const unsigned int char_count = (unsigned int)(text_end - text_begin); - const unsigned int vtx_count_max = char_count * 6; - const size_t vtx_begin = vtx_buffer.size(); - ReserveVertices(vtx_count_max); - - font->RenderText(font_size, pos, col, clip_rect_stack.back(), text_begin, text_end, vtx_write, wrap_width, cpu_clip_max); - - // give back unused vertices - vtx_buffer.resize((size_t)(vtx_write - &vtx_buffer.front())); - const size_t vtx_count = vtx_buffer.size() - vtx_begin; - commands.back().vtx_count -= (unsigned int)(vtx_count_max - vtx_count); - vtx_write -= (vtx_count_max - vtx_count); -} - -void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0, const ImVec2& uv1, ImU32 col) -{ - if ((col >> 24) == 0) - return; - - // FIXME-OPT: This is wasting draw calls. - const bool push_texture_id = texture_id_stack.empty() || user_texture_id != texture_id_stack.back(); - if (push_texture_id) - PushTextureID(user_texture_id); - - ReserveVertices(6); - AddVtxUV(ImVec2(a.x,a.y), col, uv0); - AddVtxUV(ImVec2(b.x,a.y), col, ImVec2(uv1.x,uv0.y)); - AddVtxUV(ImVec2(b.x,b.y), col, uv1); - AddVtxUV(ImVec2(a.x,a.y), col, ImVec2(uv0.x,uv0.y)); - AddVtxUV(ImVec2(b.x,b.y), col, uv1); - AddVtxUV(ImVec2(a.x,b.y), col, ImVec2(uv0.x,uv1.y)); - - if (push_texture_id) - PopTextureID(); -} - -//----------------------------------------------------------------------------- -// ImFontAtlias -//----------------------------------------------------------------------------- - -struct ImFontAtlas::ImFontAtlasData -{ - // Input - ImFont* OutFont; // Load into this font - void* TTFData; // TTF data, we own the memory - size_t TTFDataSize; // TTF data size, in bytes - float SizePixels; // Desired output size, in pixels - const ImWchar* GlyphRanges; // List of Unicode range (2 value per range, values are inclusive, zero-terminated list) - int FontNo; // Index of font within .TTF file (0) - - // Temporary Build Data - stbtt_fontinfo FontInfo; - stbrp_rect* Rects; - stbtt_pack_range* Ranges; - int RangesCount; -}; - -ImFontAtlas::ImFontAtlas() -{ - TexID = NULL; - TexPixelsAlpha8 = NULL; - TexPixelsRGBA32 = NULL; - TexWidth = TexHeight = 0; - TexUvWhitePixel = ImVec2(0, 0); -} - -ImFontAtlas::~ImFontAtlas() -{ - Clear(); -} - -void ImFontAtlas::ClearInputData() -{ - for (size_t i = 0; i < InputData.size(); i++) - { - if (InputData[i]->TTFData) - ImGui::MemFree(InputData[i]->TTFData); - ImGui::MemFree(InputData[i]); - } - InputData.clear(); -} - -void ImFontAtlas::ClearTexData() -{ - if (TexPixelsAlpha8) - ImGui::MemFree(TexPixelsAlpha8); - if (TexPixelsRGBA32) - ImGui::MemFree(TexPixelsRGBA32); - TexPixelsAlpha8 = NULL; - TexPixelsRGBA32 = NULL; -} - -void ImFontAtlas::Clear() -{ - ClearInputData(); - ClearTexData(); - for (size_t i = 0; i < Fonts.size(); i++) - { - Fonts[i]->~ImFont(); - ImGui::MemFree(Fonts[i]); - } - Fonts.clear(); -} - -void ImGui::GetDefaultFontData(const void** fnt_data, unsigned int* fnt_size, const void** png_data, unsigned int* png_size) -{ - printf("GetDefaultFontData() is obsoleted in ImGui 1.30.\n"); - printf("Please use ImGui::GetIO().Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() functions to retrieve uncompressed texture data.\n"); - if (fnt_data) *fnt_data = NULL; - if (fnt_size) *fnt_size = 0; - if (png_data) *png_data = NULL; - if (png_size) *png_size = 0; - IM_ASSERT(false); -} - -void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) -{ - // Lazily build - if (TexPixelsAlpha8 == NULL) - { - if (InputData.empty()) - AddFontDefault(); - Build(); - } - - *out_pixels = TexPixelsAlpha8; - if (out_width) *out_width = TexWidth; - if (out_height) *out_height = TexHeight; - if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; -} - -void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) -{ - // Lazily convert to RGBA32 format - // Although it is likely to be the most commonly used format, our font rendering is 8 bpp - if (!TexPixelsRGBA32) - { - unsigned char* pixels; - GetTexDataAsAlpha8(&pixels, NULL, NULL); - TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4)); - const unsigned char* src = pixels; - unsigned int* dst = TexPixelsRGBA32; - for (int n = TexWidth * TexHeight; n > 0; n--) - *dst++ = ((unsigned int)(*src++) << 24) | 0x00FFFFFF; - } - - *out_pixels = (unsigned char*)TexPixelsRGBA32; - if (out_width) *out_width = TexWidth; - if (out_height) *out_height = TexHeight; - if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; -} - -static void GetDefaultCompressedFontDataTTF(const void** ttf_compressed_data, unsigned int* ttf_compressed_size); -static unsigned int stb_decompress_length(unsigned char *input); -static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length); - -// Load embedded ProggyClean.ttf at size 13 -ImFont* ImFontAtlas::AddFontDefault() -{ - // Get compressed data - unsigned int ttf_compressed_size; - const void* ttf_compressed; - GetDefaultCompressedFontDataTTF(&ttf_compressed, &ttf_compressed_size); - - // Decompress - const size_t buf_decompressed_size = stb_decompress_length((unsigned char*)ttf_compressed); - unsigned char* buf_decompressed = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); - stb_decompress(buf_decompressed, (unsigned char*)ttf_compressed, ttf_compressed_size); - - // Add - ImFont* font = AddFontFromMemoryTTF(buf_decompressed, buf_decompressed_size, 13.0f, GetGlyphRangesDefault(), 0); - font->DisplayOffset.y += 1; - return font; -} - -ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImWchar* glyph_ranges, int font_no) -{ - void* data = NULL; - size_t data_size = 0; - if (!ImLoadFileToMemory(filename, "rb", (void**)&data, &data_size)) - { - IM_ASSERT(0); // Could not load file. - return NULL; - } - - // Add - ImFont* font = AddFontFromMemoryTTF(data, data_size, size_pixels, glyph_ranges, font_no); - return font; -} - -// NB: ownership of 'data' is given to ImFontAtlas which will clear it. -ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* in_ttf_data, size_t in_ttf_data_size, float size_pixels, const ImWchar* glyph_ranges, int font_no) -{ - // Create new font - ImFont* font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont)); - new (font) ImFont(); - Fonts.push_back(font); - - // Add to build list - ImFontAtlasData* data = (ImFontAtlasData*)ImGui::MemAlloc(sizeof(ImFontAtlasData)); - memset(data, 0, sizeof(ImFontAtlasData)); - data->OutFont = font; - data->TTFData = in_ttf_data; - data->TTFDataSize = in_ttf_data_size; - data->SizePixels = size_pixels; - data->GlyphRanges = glyph_ranges; - data->FontNo = font_no; - InputData.push_back(data); - - // Invalidate texture - ClearTexData(); - - return font; -} - -bool ImFontAtlas::Build() -{ - IM_ASSERT(InputData.size() > 0); - - TexID = NULL; - TexWidth = TexHeight = 0; - TexUvWhitePixel = ImVec2(0, 0); - ClearTexData(); - - // Initialize font information early (so we can error without any cleanup) + count glyphs - int total_glyph_count = 0; - int total_glyph_range_count = 0; - for (size_t input_i = 0; input_i < InputData.size(); input_i++) - { - ImFontAtlasData& data = *InputData[input_i]; - IM_ASSERT(data.OutFont && !data.OutFont->IsLoaded()); - const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)data.TTFData, data.FontNo); - IM_ASSERT(font_offset >= 0); - if (!stbtt_InitFont(&data.FontInfo, (unsigned char*)data.TTFData, font_offset)) - return false; - - if (!data.GlyphRanges) - data.GlyphRanges = GetGlyphRangesDefault(); - for (const ImWchar* in_range = data.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) - { - total_glyph_count += (in_range[1] - in_range[0]) + 1; - total_glyph_range_count++; - } - } - - // Start packing - TexWidth = (total_glyph_count > 1000) ? 1024 : 512; // Width doesn't actually matters. - TexHeight = 0; - const int max_tex_height = 1024*32; - stbtt_pack_context spc; - int ret = stbtt_PackBegin(&spc, NULL, TexWidth, max_tex_height, 0, 1, NULL); - IM_ASSERT(ret); - stbtt_PackSetOversampling(&spc, 1, 1); - - // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). - ImVector<stbrp_rect> extra_rects; - RenderCustomTexData(0, &extra_rects); - stbrp_pack_rects((stbrp_context*)spc.pack_info, &extra_rects[0], (int)extra_rects.size()); - for (size_t i = 0; i < extra_rects.size(); i++) - if (extra_rects[i].was_packed) - TexHeight = ImMax(TexHeight, extra_rects[i].y + extra_rects[i].h); - - // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) - int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0; - stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyph_count * sizeof(stbtt_packedchar)); - stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyph_count * sizeof(stbrp_rect)); - stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_glyph_range_count * sizeof(stbtt_pack_range)); - memset(buf_packedchars, 0, total_glyph_count * sizeof(stbtt_packedchar)); - memset(buf_rects, 0, total_glyph_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity. - memset(buf_ranges, 0, total_glyph_range_count * sizeof(stbtt_pack_range)); - - // First font pass: pack all glyphs (no rendering at this point, we are working with glyph sizes only) - for (size_t input_i = 0; input_i < InputData.size(); input_i++) - { - ImFontAtlasData& data = *InputData[input_i]; - - // Setup ranges - int glyph_count = 0; - int glyph_ranges_count = 0; - for (const ImWchar* in_range = data.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) - { - glyph_count += (in_range[1] - in_range[0]) + 1; - glyph_ranges_count++; - } - data.Ranges = buf_ranges + buf_ranges_n; - data.RangesCount = glyph_ranges_count; - buf_ranges_n += glyph_ranges_count; - for (int i = 0; i < glyph_ranges_count; i++) - { - const ImWchar* in_range = &data.GlyphRanges[i * 2]; - stbtt_pack_range& range = data.Ranges[i]; - range.font_size = data.SizePixels; - range.first_unicode_char_in_range = in_range[0]; - range.num_chars_in_range = (in_range[1] - in_range[0]) + 1; - range.chardata_for_range = buf_packedchars + buf_packedchars_n; - buf_packedchars_n += range.num_chars_in_range; - } - - // Pack - data.Rects = buf_rects + buf_rects_n; - buf_rects_n += glyph_count; - const int n = stbtt_PackFontRangesGatherRects(&spc, &data.FontInfo, data.Ranges, data.RangesCount, data.Rects); - stbrp_pack_rects((stbrp_context*)spc.pack_info, data.Rects, n); - - // Extend texture height - for (int i = 0; i < n; i++) - if (data.Rects[i].was_packed) - TexHeight = ImMax(TexHeight, data.Rects[i].y + data.Rects[i].h); - } - IM_ASSERT(buf_rects_n == total_glyph_count); - IM_ASSERT(buf_packedchars_n == total_glyph_count); - IM_ASSERT(buf_ranges_n == total_glyph_range_count); - - // Create texture - TexHeight = ImUpperPowerOfTwo(TexHeight); - TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(TexWidth * TexHeight); - memset(TexPixelsAlpha8, 0, TexWidth * TexHeight); - spc.pixels = TexPixelsAlpha8; - spc.height = TexHeight; - - // Second pass: render characters - for (size_t input_i = 0; input_i < InputData.size(); input_i++) - { - ImFontAtlasData& data = *InputData[input_i]; - ret = stbtt_PackFontRangesRenderIntoRects(&spc, &data.FontInfo, data.Ranges, data.RangesCount, data.Rects); - data.Rects = NULL; - } - - // End packing - stbtt_PackEnd(&spc); - ImGui::MemFree(buf_rects); - buf_rects = NULL; - - // Third pass: setup ImFont and glyphs for runtime - for (size_t input_i = 0; input_i < InputData.size(); input_i++) - { - ImFontAtlasData& data = *InputData[input_i]; - data.OutFont->ContainerAtlas = this; - data.OutFont->FontSize = data.SizePixels; - - const float font_scale = stbtt_ScaleForPixelHeight(&data.FontInfo, data.SizePixels); - int font_ascent, font_descent, font_line_gap; - stbtt_GetFontVMetrics(&data.FontInfo, &font_ascent, &font_descent, &font_line_gap); - - const float uv_scale_x = 1.0f / TexWidth; - const float uv_scale_y = 1.0f / TexHeight; - const int character_spacing_x = 1; - for (int i = 0; i < data.RangesCount; i++) - { - stbtt_pack_range& range = data.Ranges[i]; - for (int char_idx = 0; char_idx < range.num_chars_in_range; char_idx += 1) - { - const int codepoint = range.first_unicode_char_in_range + char_idx; - const stbtt_packedchar& pc = range.chardata_for_range[char_idx]; - if (!pc.x0 && !pc.x1 && !pc.y0 && !pc.y1) - continue; - - data.OutFont->Glyphs.resize(data.OutFont->Glyphs.size() + 1); - ImFont::Glyph& glyph = data.OutFont->Glyphs.back(); - glyph.Codepoint = (ImWchar)codepoint; - glyph.Width = (signed short)pc.x1 - pc.x0 + 1; - glyph.Height = (signed short)pc.y1 - pc.y0 + 1; - glyph.XOffset = (signed short)(pc.xoff); - glyph.YOffset = (signed short)(pc.yoff + (int)(font_ascent * font_scale)); - glyph.XAdvance = (signed short)(pc.xadvance + character_spacing_x); // Bake spacing into XAdvance - glyph.U0 = ((float)pc.x0 - 0.5f) * uv_scale_x; - glyph.V0 = ((float)pc.y0 - 0.5f) * uv_scale_y; - glyph.U1 = ((float)pc.x0 - 0.5f + glyph.Width) * uv_scale_x; - glyph.V1 = ((float)pc.y0 - 0.5f + glyph.Height) * uv_scale_y; - } - } - - data.OutFont->BuildLookupTable(); - } - - // Cleanup temporaries - ImGui::MemFree(buf_packedchars); - ImGui::MemFree(buf_ranges); - buf_packedchars = NULL; - buf_ranges = NULL; - ClearInputData(); - - // Render into our custom data block - RenderCustomTexData(1, &extra_rects); - - return true; -} - -void ImFontAtlas::RenderCustomTexData(int pass, void* p_rects) -{ - // . = white layer, X = black layer, others are blank - const int TEX_DATA_W = 90; - const int TEX_DATA_H = 27; - const char texture_data[TEX_DATA_W*TEX_DATA_H+1] = - { - "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX" - "..- -X.....X- X.X - X.X -X.....X - X.....X" - "--- -XXX.XXX- X...X - X...X -X....X - X....X" - "X - X.X - X.....X - X.....X -X...X - X...X" - "XX - X.X -X.......X- X.......X -X..X.X - X.X..X" - "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X" - "X..X - X.X - X.X - X.X -XX X.X - X.X XX" - "X...X - X.X - X.X - XX X.X XX - X.X - X.X " - "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X " - "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X " - "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X " - "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X " - "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X " - "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X " - "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X " - "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X " - "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX " - "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------" - "X.X X..X - -X.......X- X.......X - XX XX - " - "XX X..X - - X.....X - X.....X - X.X X.X - " - " X..X - X...X - X...X - X..X X..X - " - " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - " - "------------ - X - X -X.....................X- " - " ----------------------------------- X...XXXXXXXXXXXXX...X - " - " - X..X X..X - " - " - X.X X.X - " - " - XX XX - " - }; - - ImVector<stbrp_rect>& rects = *(ImVector<stbrp_rect>*)p_rects; - if (pass == 0) - { - stbrp_rect r = { 0 }; - r.w = (TEX_DATA_W*2)+1; - r.h = TEX_DATA_H+1; - rects.push_back(r); - } - else if (pass == 1) - { - // Copy pixels - const stbrp_rect& r = rects[0]; - for (int y = 0, n = 0; y < TEX_DATA_H; y++) - for (int x = 0; x < TEX_DATA_W; x++, n++) - { - const int offset0 = (int)(r.x + x) + (int)(r.y + y) * TexWidth; - const int offset1 = offset0 + 1 + TEX_DATA_W; - TexPixelsAlpha8[offset0] = texture_data[n] == '.' ? 0xFF : 0x00; - TexPixelsAlpha8[offset1] = texture_data[n] == 'X' ? 0xFF : 0x00; - } - const ImVec2 tex_uv_scale(1.0f / TexWidth, 1.0f / TexHeight); - TexUvWhitePixel = ImVec2(r.x + 0.5f, r.y + 0.5f) * tex_uv_scale; - - const ImVec2 cursor_datas[ImGuiMouseCursor_Count_][3] = - { - // Pos ........ Size ......... Offset ...... - { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow - { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput - { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move - { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS - { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW - { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW - { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE - }; - - for (int type = 0; type < ImGuiMouseCursor_Count_; type++) - { - ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type]; - ImVec2 pos = cursor_datas[type][0] + ImVec2((float)r.x, (float)r.y); - const ImVec2 size = cursor_datas[type][1]; - cursor_data.Type = type; - cursor_data.Size = size; - cursor_data.Offset = cursor_datas[type][2]; - cursor_data.TexUvMin[0] = (pos) * tex_uv_scale; - cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale; - pos.x += TEX_DATA_W+1; - cursor_data.TexUvMin[1] = (pos) * tex_uv_scale; - cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale; - } - } -} - -//----------------------------------------------------------------------------- -// ImFont -//----------------------------------------------------------------------------- - -ImFont::ImFont() -{ - Scale = 1.0f; - FallbackChar = (ImWchar)'?'; - Clear(); -} - -ImFont::~ImFont() -{ - // Invalidate active font so that the user gets a clear crash instead of a dangling pointer. - // If you want to delete fonts you need to do it between Render() and NewFrame(). - ImGuiState& g = *GImGui; - if (g.Font == this) - g.Font = NULL; - Clear(); -} - -void ImFont::Clear() -{ - FontSize = 0.0f; - DisplayOffset = ImVec2(-0.5f, 0.5f); - ContainerAtlas = NULL; - Glyphs.clear(); - FallbackGlyph = NULL; - FallbackXAdvance = 0.0f; - IndexXAdvance.clear(); - IndexLookup.clear(); -} - -// Retrieve list of range (2 int per range, values are inclusive) -const ImWchar* ImFontAtlas::GetGlyphRangesDefault() -{ - static const ImWchar ranges[] = - { - 0x0020, 0x00FF, // Basic Latin + Latin Supplement - 0, - }; - return &ranges[0]; -} - -const ImWchar* ImFontAtlas::GetGlyphRangesChinese() -{ - static const ImWchar ranges[] = - { - 0x0020, 0x00FF, // Basic Latin + Latin Supplement - 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana - 0x31F0, 0x31FF, // Katakana Phonetic Extensions - 0xFF00, 0xFFEF, // Half-width characters - 0x4e00, 0x9FAF, // CJK Ideograms - 0, - }; - return &ranges[0]; -} - -const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() -{ - // Store the 1946 ideograms code points as successive offsets from the initial unicode codepoint 0x4E00. Each offset has an implicit +1. - // This encoding helps us reduce the source code size. - static const short offsets_from_0x4E00[] = - { - -1,0,1,3,0,0,0,0,1,0,5,1,1,0,7,4,6,10,0,1,9,9,7,1,3,19,1,10,7,1,0,1,0,5,1,0,6,4,2,6,0,0,12,6,8,0,3,5,0,1,0,9,0,0,8,1,1,3,4,5,13,0,0,8,2,17, - 4,3,1,1,9,6,0,0,0,2,1,3,2,22,1,9,11,1,13,1,3,12,0,5,9,2,0,6,12,5,3,12,4,1,2,16,1,1,4,6,5,3,0,6,13,15,5,12,8,14,0,0,6,15,3,6,0,18,8,1,6,14,1, - 5,4,12,24,3,13,12,10,24,0,0,0,1,0,1,1,2,9,10,2,2,0,0,3,3,1,0,3,8,0,3,2,4,4,1,6,11,10,14,6,15,3,4,15,1,0,0,5,2,2,0,0,1,6,5,5,6,0,3,6,5,0,0,1,0, - 11,2,2,8,4,7,0,10,0,1,2,17,19,3,0,2,5,0,6,2,4,4,6,1,1,11,2,0,3,1,2,1,2,10,7,6,3,16,0,8,24,0,0,3,1,1,3,0,1,6,0,0,0,2,0,1,5,15,0,1,0,0,2,11,19, - 1,4,19,7,6,5,1,0,0,0,0,5,1,0,1,9,0,0,5,0,2,0,1,0,3,0,11,3,0,2,0,0,0,0,0,9,3,6,4,12,0,14,0,0,29,10,8,0,14,37,13,0,31,16,19,0,8,30,1,20,8,3,48, - 21,1,0,12,0,10,44,34,42,54,11,18,82,0,2,1,2,12,1,0,6,2,17,2,12,7,0,7,17,4,2,6,24,23,8,23,39,2,16,23,1,0,5,1,2,15,14,5,6,2,11,0,8,6,2,2,2,14, - 20,4,15,3,4,11,10,10,2,5,2,1,30,2,1,0,0,22,5,5,0,3,1,5,4,1,0,0,2,2,21,1,5,1,2,16,2,1,3,4,0,8,4,0,0,5,14,11,2,16,1,13,1,7,0,22,15,3,1,22,7,14, - 22,19,11,24,18,46,10,20,64,45,3,2,0,4,5,0,1,4,25,1,0,0,2,10,0,0,0,1,0,1,2,0,0,9,1,2,0,0,0,2,5,2,1,1,5,5,8,1,1,1,5,1,4,9,1,3,0,1,0,1,1,2,0,0, - 2,0,1,8,22,8,1,0,0,0,0,4,2,1,0,9,8,5,0,9,1,30,24,2,6,4,39,0,14,5,16,6,26,179,0,2,1,1,0,0,0,5,2,9,6,0,2,5,16,7,5,1,1,0,2,4,4,7,15,13,14,0,0, - 3,0,1,0,0,0,2,1,6,4,5,1,4,9,0,3,1,8,0,0,10,5,0,43,0,2,6,8,4,0,2,0,0,9,6,0,9,3,1,6,20,14,6,1,4,0,7,2,3,0,2,0,5,0,3,1,0,3,9,7,0,3,4,0,4,9,1,6,0, - 9,0,0,2,3,10,9,28,3,6,2,4,1,2,32,4,1,18,2,0,3,1,5,30,10,0,2,2,2,0,7,9,8,11,10,11,7,2,13,7,5,10,0,3,40,2,0,1,6,12,0,4,5,1,5,11,11,21,4,8,3,7, - 8,8,33,5,23,0,0,19,8,8,2,3,0,6,1,1,1,5,1,27,4,2,5,0,3,5,6,3,1,0,3,1,12,5,3,3,2,0,7,7,2,1,0,4,0,1,1,2,0,10,10,6,2,5,9,7,5,15,15,21,6,11,5,20, - 4,3,5,5,2,5,0,2,1,0,1,7,28,0,9,0,5,12,5,5,18,30,0,12,3,3,21,16,25,32,9,3,14,11,24,5,66,9,1,2,0,5,9,1,5,1,8,0,8,3,3,0,1,15,1,4,8,1,2,7,0,7,2, - 8,3,7,5,3,7,10,2,1,0,0,2,25,0,6,4,0,10,0,4,2,4,1,12,5,38,4,0,4,1,10,5,9,4,0,14,4,2,5,18,20,21,1,3,0,5,0,7,0,3,7,1,3,1,1,8,1,0,0,0,3,2,5,2,11, - 6,0,13,1,3,9,1,12,0,16,6,2,1,0,2,1,12,6,13,11,2,0,28,1,7,8,14,13,8,13,0,2,0,5,4,8,10,2,37,42,19,6,6,7,4,14,11,18,14,80,7,6,0,4,72,12,36,27, - 7,7,0,14,17,19,164,27,0,5,10,7,3,13,6,14,0,2,2,5,3,0,6,13,0,0,10,29,0,4,0,3,13,0,3,1,6,51,1,5,28,2,0,8,0,20,2,4,0,25,2,10,13,10,0,16,4,0,1,0, - 2,1,7,0,1,8,11,0,0,1,2,7,2,23,11,6,6,4,16,2,2,2,0,22,9,3,3,5,2,0,15,16,21,2,9,20,15,15,5,3,9,1,0,0,1,7,7,5,4,2,2,2,38,24,14,0,0,15,5,6,24,14, - 5,5,11,0,21,12,0,3,8,4,11,1,8,0,11,27,7,2,4,9,21,59,0,1,39,3,60,62,3,0,12,11,0,3,30,11,0,13,88,4,15,5,28,13,1,4,48,17,17,4,28,32,46,0,16,0, - 18,11,1,8,6,38,11,2,6,11,38,2,0,45,3,11,2,7,8,4,30,14,17,2,1,1,65,18,12,16,4,2,45,123,12,56,33,1,4,3,4,7,0,0,0,3,2,0,16,4,2,4,2,0,7,4,5,2,26, - 2,25,6,11,6,1,16,2,6,17,77,15,3,35,0,1,0,5,1,0,38,16,6,3,12,3,3,3,0,9,3,1,3,5,2,9,0,18,0,25,1,3,32,1,72,46,6,2,7,1,3,14,17,0,28,1,40,13,0,20, - 15,40,6,38,24,12,43,1,1,9,0,12,6,0,6,2,4,19,3,7,1,48,0,9,5,0,5,6,9,6,10,15,2,11,19,3,9,2,0,1,10,1,27,8,1,3,6,1,14,0,26,0,27,16,3,4,9,6,2,23, - 9,10,5,25,2,1,6,1,1,48,15,9,15,14,3,4,26,60,29,13,37,21,1,6,4,0,2,11,22,23,16,16,2,2,1,3,0,5,1,6,4,0,0,4,0,0,8,3,0,2,5,0,7,1,7,3,13,2,4,10, - 3,0,2,31,0,18,3,0,12,10,4,1,0,7,5,7,0,5,4,12,2,22,10,4,2,15,2,8,9,0,23,2,197,51,3,1,1,4,13,4,3,21,4,19,3,10,5,40,0,4,1,1,10,4,1,27,34,7,21, - 2,17,2,9,6,4,2,3,0,4,2,7,8,2,5,1,15,21,3,4,4,2,2,17,22,1,5,22,4,26,7,0,32,1,11,42,15,4,1,2,5,0,19,3,1,8,6,0,10,1,9,2,13,30,8,2,24,17,19,1,4, - 4,25,13,0,10,16,11,39,18,8,5,30,82,1,6,8,18,77,11,13,20,75,11,112,78,33,3,0,0,60,17,84,9,1,1,12,30,10,49,5,32,158,178,5,5,6,3,3,1,3,1,4,7,6, - 19,31,21,0,2,9,5,6,27,4,9,8,1,76,18,12,1,4,0,3,3,6,3,12,2,8,30,16,2,25,1,5,5,4,3,0,6,10,2,3,1,0,5,1,19,3,0,8,1,5,2,6,0,0,0,19,1,2,0,5,1,2,5, - 1,3,7,0,4,12,7,3,10,22,0,9,5,1,0,2,20,1,1,3,23,30,3,9,9,1,4,191,14,3,15,6,8,50,0,1,0,0,4,0,0,1,0,2,4,2,0,2,3,0,2,0,2,2,8,7,0,1,1,1,3,3,17,11, - 91,1,9,3,2,13,4,24,15,41,3,13,3,1,20,4,125,29,30,1,0,4,12,2,21,4,5,5,19,11,0,13,11,86,2,18,0,7,1,8,8,2,2,22,1,2,6,5,2,0,1,2,8,0,2,0,5,2,1,0, - 2,10,2,0,5,9,2,1,2,0,1,0,4,0,0,10,2,5,3,0,6,1,0,1,4,4,33,3,13,17,3,18,6,4,7,1,5,78,0,4,1,13,7,1,8,1,0,35,27,15,3,0,0,0,1,11,5,41,38,15,22,6, - 14,14,2,1,11,6,20,63,5,8,27,7,11,2,2,40,58,23,50,54,56,293,8,8,1,5,1,14,0,1,12,37,89,8,8,8,2,10,6,0,0,0,4,5,2,1,0,1,1,2,7,0,3,3,0,4,6,0,3,2, - 19,3,8,0,0,0,4,4,16,0,4,1,5,1,3,0,3,4,6,2,17,10,10,31,6,4,3,6,10,126,7,3,2,2,0,9,0,0,5,20,13,0,15,0,6,0,2,5,8,64,50,3,2,12,2,9,0,0,11,8,20, - 109,2,18,23,0,0,9,61,3,0,28,41,77,27,19,17,81,5,2,14,5,83,57,252,14,154,263,14,20,8,13,6,57,39,38, - }; - static int ranges_unpacked = false; - static ImWchar ranges[8 + IM_ARRAYSIZE(offsets_from_0x4E00)*2 + 1] = - { - 0x0020, 0x00FF, // Basic Latin + Latin Supplement - 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana - 0x31F0, 0x31FF, // Katakana Phonetic Extensions - 0xFF00, 0xFFEF, // Half-width characters - }; - if (!ranges_unpacked) - { - // Unpack - int codepoint = 0x4e00; - ImWchar* dst = &ranges[8]; - for (int n = 0; n < IM_ARRAYSIZE(offsets_from_0x4E00); n++, dst += 2) - dst[0] = dst[1] = (ImWchar)(codepoint += (offsets_from_0x4E00[n] + 1)); - dst[0] = 0; - ranges_unpacked = true; - } - return &ranges[0]; -} - -void ImFont::BuildLookupTable() -{ - int max_codepoint = 0; - for (size_t i = 0; i != Glyphs.size(); i++) - max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); - - IndexXAdvance.clear(); - IndexXAdvance.resize((size_t)max_codepoint + 1); - IndexLookup.clear(); - IndexLookup.resize((size_t)max_codepoint + 1); - for (size_t i = 0; i < (size_t)max_codepoint + 1; i++) - { - IndexXAdvance[i] = -1.0f; - IndexLookup[i] = -1; - } - for (size_t i = 0; i < Glyphs.size(); i++) - { - const size_t codepoint = (int)Glyphs[i].Codepoint; - IndexXAdvance[codepoint] = Glyphs[i].XAdvance; - IndexLookup[codepoint] = (int)i; - } - - // Create a glyph to handle TAB - // FIXME: Needs proper TAB handling but it needs to be contextualized (can arbitrary say that each string starts at "column 0" - if (FindGlyph((unsigned short)' ')) - { - if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times - Glyphs.resize(Glyphs.size() + 1); - ImFont::Glyph& tab_glyph = Glyphs.back(); - tab_glyph = *FindGlyph((unsigned short)' '); - tab_glyph.Codepoint = '\t'; - tab_glyph.XAdvance *= 4; - IndexXAdvance[(size_t)tab_glyph.Codepoint] = (float)tab_glyph.XAdvance; - IndexLookup[(size_t)tab_glyph.Codepoint] = (int)(Glyphs.size()-1); - } - - FallbackGlyph = NULL; - FallbackGlyph = FindGlyph(FallbackChar); - FallbackXAdvance = FallbackGlyph ? FallbackGlyph->XAdvance : 0.0f; - for (size_t i = 0; i < (size_t)max_codepoint + 1; i++) - if (IndexXAdvance[i] < 0.0f) - IndexXAdvance[i] = FallbackXAdvance; -} - -void ImFont::SetFallbackChar(ImWchar c) -{ - FallbackChar = c; - BuildLookupTable(); -} - -const ImFont::Glyph* ImFont::FindGlyph(unsigned short c) const -{ - if (c < (int)IndexLookup.size()) - { - const int i = IndexLookup[c]; - if (i != -1) - return &Glyphs[i]; - } - return FallbackGlyph; -} - -// Convert UTF-8 to 32-bits character, process single character input. -// Based on stb_from_utf8() from github.com/nothings/stb/ -// We handle UTF-8 decoding error by skipping forward. -static int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) -{ - unsigned int c = (unsigned int)-1; - const unsigned char* str = (const unsigned char*)in_text; - if (!(*str & 0x80)) - { - c = (unsigned int)(*str++); - *out_char = c; - return 1; - } - if ((*str & 0xe0) == 0xc0) - { - *out_char = 0; - if (in_text_end && in_text_end - (const char*)str < 2) return 0; - if (*str < 0xc2) return 0; - c = (unsigned int)((*str++ & 0x1f) << 6); - if ((*str & 0xc0) != 0x80) return 0; - c += (*str++ & 0x3f); - *out_char = c; - return 2; - } - if ((*str & 0xf0) == 0xe0) - { - *out_char = 0; - if (in_text_end && in_text_end - (const char*)str < 3) return 0; - if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 0; - if (*str == 0xed && str[1] > 0x9f) return 0; // str[1] < 0x80 is checked below - c = (unsigned int)((*str++ & 0x0f) << 12); - if ((*str & 0xc0) != 0x80) return 0; - c += (unsigned int)((*str++ & 0x3f) << 6); - if ((*str & 0xc0) != 0x80) return 0; - c += (*str++ & 0x3f); - *out_char = c; - return 3; - } - if ((*str & 0xf8) == 0xf0) - { - *out_char = 0; - if (in_text_end && in_text_end - (const char*)str < 4) return 0; - if (*str > 0xf4) return 0; - if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 0; - if (*str == 0xf4 && str[1] > 0x8f) return 0; // str[1] < 0x80 is checked below - c = (unsigned int)((*str++ & 0x07) << 18); - if ((*str & 0xc0) != 0x80) return 0; - c += (unsigned int)((*str++ & 0x3f) << 12); - if ((*str & 0xc0) != 0x80) return 0; - c += (unsigned int)((*str++ & 0x3f) << 6); - if ((*str & 0xc0) != 0x80) return 0; - c += (*str++ & 0x3f); - // utf-8 encodings of values used in surrogate pairs are invalid - if ((c & 0xFFFFF800) == 0xD800) return 0; - *out_char = c; - return 4; - } - *out_char = 0; - return 0; -} - -static ptrdiff_t ImTextStrFromUtf8(ImWchar* buf, size_t buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) -{ - ImWchar* buf_out = buf; - ImWchar* buf_end = buf + buf_size; - while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) - { - unsigned int c; - in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); - if (c == 0) - break; - if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes - *buf_out++ = (ImWchar)c; - } - *buf_out = 0; - if (in_text_remaining) - *in_text_remaining = in_text; - return buf_out - buf; -} - -static int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) -{ - int char_count = 0; - while ((!in_text_end || in_text < in_text_end) && *in_text) - { - unsigned int c; - in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); - if (c == 0) - break; - if (c < 0x10000) - char_count++; - } - return char_count; -} - -// Based on stb_to_utf8() from github.com/nothings/stb/ -static int ImTextCharToUtf8(char* buf, size_t buf_size, unsigned int c) -{ - if (c) - { - size_t i = 0; - size_t n = buf_size; - if (c < 0x80) - { - if (i+1 > n) return 0; - buf[i++] = (char)c; - return 1; - } - else if (c < 0x800) - { - if (i+2 > n) return 0; - buf[i++] = (char)(0xc0 + (c >> 6)); - buf[i++] = (char)(0x80 + (c & 0x3f)); - return 2; - } - else if (c >= 0xdc00 && c < 0xe000) - { - return 0; - } - else if (c >= 0xd800 && c < 0xdc00) - { - if (i+4 > n) return 0; - buf[i++] = (char)(0xf0 + (c >> 18)); - buf[i++] = (char)(0x80 + ((c >> 12) & 0x3f)); - buf[i++] = (char)(0x80 + ((c >> 6) & 0x3f)); - buf[i++] = (char)(0x80 + ((c ) & 0x3f)); - return 4; - } - //else if (c < 0x10000) - { - if (i+3 > n) return 0; - buf[i++] = (char)(0xe0 + (c >> 12)); - buf[i++] = (char)(0x80 + ((c>> 6) & 0x3f)); - buf[i++] = (char)(0x80 + ((c ) & 0x3f)); - return 3; - } - } - return 0; -} - -static ptrdiff_t ImTextStrToUtf8(char* buf, size_t buf_size, const ImWchar* in_text, const ImWchar* in_text_end) -{ - char* buf_out = buf; - const char* buf_end = buf + buf_size; - while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) - { - buf_out += ImTextCharToUtf8(buf_out, (uintptr_t)(buf_end-buf_out-1), (unsigned int)*in_text); - in_text++; - } - *buf_out = 0; - return buf_out - buf; -} - -static int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) -{ - int bytes_count = 0; - while ((!in_text_end || in_text < in_text_end) && *in_text) - { - char dummy[5]; // FIXME-OPT - bytes_count += ImTextCharToUtf8(dummy, 5, (unsigned int)*in_text); - in_text++; - } - return bytes_count; -} - -const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const -{ - // Simple word-wrapping for English, not full-featured. Please submit failing cases! - // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) - - // For references, possible wrap point marked with ^ - // "aaa bbb, ccc,ddd. eee fff. ggg!" - // ^ ^ ^ ^ ^__ ^ ^ - - // List of hardcoded separators: .,;!?'" - - // Skip extra blanks after a line returns (that includes not counting them in width computation) - // e.g. "Hello world" --> "Hello" "World" - - // Cut words that cannot possibly fit within one line. - // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" - - float line_width = 0.0f; - float word_width = 0.0f; - float blank_width = 0.0f; - - const char* word_end = text; - const char* prev_word_end = NULL; - bool inside_word = true; - - const char* s = text; - while (s < text_end) - { - unsigned int c = (unsigned int)*s; - const char* next_s; - if (c < 0x80) - next_s = s + 1; - else - next_s = s + ImTextCharFromUtf8(&c, s, text_end); - if (c == 0) - break; - - if (c == '\n') - { - line_width = word_width = blank_width = 0.0f; - inside_word = true; - s = next_s; - continue; - } - - const float char_width = ((size_t)c < IndexXAdvance.size()) ? IndexXAdvance[(size_t)c] * scale : FallbackXAdvance; - if (ImCharIsSpace(c)) - { - if (inside_word) - { - line_width += blank_width; - blank_width = 0.0f; - } - blank_width += char_width; - inside_word = false; - } - else - { - word_width += char_width; - if (inside_word) - { - word_end = next_s; - } - else - { - prev_word_end = word_end; - line_width += word_width + blank_width; - word_width = blank_width = 0.0f; - } - - // Allow wrapping after punctuation. - inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); - } - - // We ignore blank width at the end of the line (they can be skipped) - if (line_width + word_width >= wrap_width) - { - // Words that cannot possibly fit within an entire line will be cut anywhere. - if (word_width < wrap_width) - s = prev_word_end ? prev_word_end : word_end; - break; - } - - s = next_s; - } - - return s; -} - -ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const -{ - if (!text_end) - text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. - - const float scale = size / FontSize; - const float line_height = FontSize * scale; - - ImVec2 text_size = ImVec2(0,0); - float line_width = 0.0f; - - const bool word_wrap_enabled = (wrap_width > 0.0f); - const char* word_wrap_eol = NULL; - - const char* s = text_begin; - while (s < text_end) - { - if (word_wrap_enabled) - { - // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. - if (!word_wrap_eol) - { - word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); - if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. - word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below - } - - if (s >= word_wrap_eol) - { - if (text_size.x < line_width) - text_size.x = line_width; - text_size.y += line_height; - line_width = 0.0f; - word_wrap_eol = NULL; - - // Wrapping skips upcoming blanks - while (s < text_end) - { - const char c = *s; - if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } - } - continue; - } - } - - // Decode and advance source (handle unlikely UTF-8 decoding failure by skipping to the next byte) - const char* prev_s = s; - unsigned int c = (unsigned int)*s; - if (c < 0x80) - { - s += 1; - } - else - { - s += ImTextCharFromUtf8(&c, s, text_end); - if (c == 0) - break; - } - - if (c == '\n') - { - text_size.x = ImMax(text_size.x, line_width); - text_size.y += line_height; - line_width = 0.0f; - continue; - } - - const float char_width = ((size_t)c < IndexXAdvance.size()) ? IndexXAdvance[(size_t)c] * scale : FallbackXAdvance; - if (line_width + char_width >= max_width) - { - s = prev_s; - break; - } - - line_width += char_width; - } - - if (line_width > 0 || text_size.y == 0.0f) - { - if (text_size.x < line_width) - text_size.x = line_width; - text_size.y += line_height; - } - - if (remaining) - *remaining = s; - - return text_size; -} - -ImVec2 ImFont::CalcTextSizeW(float size, float max_width, const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining) const -{ - if (!text_end) - text_end = text_begin + ImStrlenW(text_begin); - - const float scale = size / FontSize; - const float line_height = FontSize * scale; - - ImVec2 text_size = ImVec2(0,0); - float line_width = 0.0f; - - const ImWchar* s = text_begin; - while (s < text_end) - { - const unsigned int c = (unsigned int)(*s++); - - if (c == '\n') - { - text_size.x = ImMax(text_size.x, line_width); - text_size.y += line_height; - line_width = 0.0f; - continue; - } - - const float char_width = ((size_t)c < IndexXAdvance.size()) ? IndexXAdvance[(size_t)c] * scale : FallbackXAdvance; - if (line_width + char_width >= max_width) - { - s--; - break; - } - - line_width += char_width; - } - - if (line_width > 0 || text_size.y == 0.0f) - { - if (text_size.x < line_width) - text_size.x = line_width; - text_size.y += line_height; - } - - if (remaining) - *remaining = s; - - return text_size; -} - -void ImFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect_ref, const char* text_begin, const char* text_end, ImDrawVert*& out_vertices, float wrap_width, const ImVec2* cpu_clip_max) const -{ - if (!text_end) - text_end = text_begin + strlen(text_begin); - - const float scale = size / FontSize; - const float line_height = FontSize * scale; - - // Align to be pixel perfect - pos.x = (float)(int)pos.x + DisplayOffset.x; - pos.y = (float)(int)pos.y + DisplayOffset.y; - - const bool word_wrap_enabled = (wrap_width > 0.0f); - const char* word_wrap_eol = NULL; - - ImVec4 clip_rect = clip_rect_ref; - if (cpu_clip_max) - { - clip_rect.z = ImMin(clip_rect.z, cpu_clip_max->x); - clip_rect.w = ImMin(clip_rect.w, cpu_clip_max->y); - } - float x = pos.x; - float y = pos.y; - - const char* s = text_begin; - while (s < text_end) - { - if (word_wrap_enabled) - { - // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. - if (!word_wrap_eol) - { - word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); - if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. - word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below - } - - if (s >= word_wrap_eol) - { - x = pos.x; - y += line_height; - word_wrap_eol = NULL; - - // Wrapping skips upcoming blanks - while (s < text_end) - { - const char c = *s; - if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } - } - continue; - } - } - - // Decode and advance source (handle unlikely UTF-8 decoding failure by skipping to the next byte) - unsigned int c = (unsigned int)*s; - if (c < 0x80) - { - s += 1; - } - else - { - s += ImTextCharFromUtf8(&c, s, text_end); - if (c == 0) - break; - } - - if (c == '\n') - { - x = pos.x; - y += line_height; - continue; - } - - float char_width = 0.0f; - if (const Glyph* glyph = FindGlyph((unsigned short)c)) - { - char_width = glyph->XAdvance * scale; - if (c != ' ' && c != '\t') - { - // Clipping on Y is more likely - float y1 = (float)(y + glyph->YOffset * scale); - float y2 = (float)(y1 + glyph->Height * scale); - if (y1 <= clip_rect.w && y2 >= clip_rect.y) - { - float x1 = (float)(x + glyph->XOffset * scale); - float x2 = (float)(x1 + glyph->Width * scale); - if (x1 <= clip_rect.z && x2 >= clip_rect.x) - { - // Render a character - float u1 = glyph->U0; - float v1 = glyph->V0; - float u2 = glyph->U1; - float v2 = glyph->V1; - - // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quad and in the "max" direction (bottom-right) - if (cpu_clip_max) - { - if (x2 > cpu_clip_max->x) - { - const float clip_tx = (cpu_clip_max->x - x1) / (x2 - x1); - x2 = cpu_clip_max->x; - u2 = u1 + clip_tx * (u2 - u1); - } - if (y2 > cpu_clip_max->y) - { - const float clip_ty = (cpu_clip_max->y - y1) / (y2 - y1); - y2 = cpu_clip_max->y; - v2 = v1 + clip_ty * (v2 - v1); - } - } - - out_vertices[0].pos = ImVec2(x1, y1); - out_vertices[0].uv = ImVec2(u1, v1); - out_vertices[0].col = col; - - out_vertices[1].pos = ImVec2(x2, y1); - out_vertices[1].uv = ImVec2(u2, v1); - out_vertices[1].col = col; - - out_vertices[2].pos = ImVec2(x2, y2); - out_vertices[2].uv = ImVec2(u2, v2); - out_vertices[2].col = col; - - out_vertices[3] = out_vertices[0]; - out_vertices[4] = out_vertices[2]; - - out_vertices[5].pos = ImVec2(x1, y2); - out_vertices[5].uv = ImVec2(u1, v2); - out_vertices[5].col = col; - - out_vertices += 6; - } - } - } - } - - x += char_width; - } -} - -//----------------------------------------------------------------------------- -// PLATFORM DEPENDANT HELPERS -//----------------------------------------------------------------------------- - -#if defined(_MSC_VER) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) - -#ifndef _WINDOWS_ -#define WIN32_LEAN_AND_MEAN -#include <windows.h> -#endif - -// Win32 API clipboard implementation -static const char* GetClipboardTextFn_DefaultImpl() -{ - static char* buf_local = NULL; - if (buf_local) - { - ImGui::MemFree(buf_local); - buf_local = NULL; - } - if (!OpenClipboard(NULL)) - return NULL; - HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT); - if (wbuf_handle == NULL) - return NULL; - if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle)) - { - int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; - buf_local = (char*)ImGui::MemAlloc(buf_len * sizeof(char)); - ImTextStrToUtf8(buf_local, buf_len, wbuf_global, NULL); - } - GlobalUnlock(wbuf_handle); - CloseClipboard(); - return buf_local; -} - -// Win32 API clipboard implementation -static void SetClipboardTextFn_DefaultImpl(const char* text) -{ - if (!OpenClipboard(NULL)) - return; - - const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; - HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); - if (wbuf_handle == NULL) - return; - ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle); - ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); - GlobalUnlock(wbuf_handle); - EmptyClipboard(); - SetClipboardData(CF_UNICODETEXT, wbuf_handle); - CloseClipboard(); -} - -#else - -// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers -static const char* GetClipboardTextFn_DefaultImpl() -{ - return GImGui->PrivateClipboard; -} - -// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers -static void SetClipboardTextFn_DefaultImpl(const char* text) -{ - ImGuiState& g = *GImGui; - if (g.PrivateClipboard) - { - ImGui::MemFree(g.PrivateClipboard); - g.PrivateClipboard = NULL; - } - const char* text_end = text + strlen(text); - g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1); - memcpy(g.PrivateClipboard, text, (size_t)(text_end - text)); - g.PrivateClipboard[(size_t)(text_end - text)] = 0; -} - -#endif - -#if defined(_MSC_VER) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS) - -#ifndef _WINDOWS_ -#define WIN32_LEAN_AND_MEAN -#include <windows.h> -#endif -#include <Imm.h> -#pragma comment(lib, "imm32") - -static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) -{ - // Notify OS Input Method Editor of text input position - if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) - if (HIMC himc = ImmGetContext(hwnd)) - { - COMPOSITIONFORM cf; - cf.ptCurrentPos.x = x; - cf.ptCurrentPos.y = y; - cf.dwStyle = CFS_FORCE_POSITION; - ImmSetCompositionWindow(himc, &cf); - } -} - -#else - -static void ImeSetInputScreenPosFn_DefaultImpl(int, int) -{ -} - -#endif - -#ifdef IMGUI_DISABLE_TEST_WINDOWS - -void ImGui::ShowUserGuide() {} -void ImGui::ShowStyleEditor(ImGuiStyle*) {} -void ImGui::ShowTestWindow(bool*) {} -void ImGui::ShowMetricsWindow(bool*) {} - -#else - -//----------------------------------------------------------------------------- -// HELP -//----------------------------------------------------------------------------- - -void ImGui::ShowUserGuide() -{ - ImGuiState& g = *GImGui; - - ImGui::BulletText("Double-click on title bar to collapse window."); - ImGui::BulletText("Click and drag on lower right corner to resize window."); - ImGui::BulletText("Click and drag on any empty space to move window."); - ImGui::BulletText("Mouse Wheel to scroll."); - if (g.IO.FontAllowUserScaling) - ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); - ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); - ImGui::BulletText("CTRL+Click on a slider to input text."); - ImGui::BulletText( - "While editing text:\n" - "- Hold SHIFT or use mouse to select text\n" - "- CTRL+Left/Right to word jump\n" - "- CTRL+A select all\n" - "- CTRL+X,CTRL+C,CTRL+V clipboard\n" - "- CTRL+Z,CTRL+Y undo/redo\n" - "- ESCAPE to revert\n" - "- You can apply arithmetic operators +,*,/ on numerical values.\n" - " Use +- to subtract.\n"); -} - -void ImGui::ShowStyleEditor(ImGuiStyle* ref) -{ - ImGuiState& g = *GImGui; - ImGuiStyle& style = g.Style; - - const ImGuiStyle def; // Default style - - if (ImGui::Button("Revert Style")) - g.Style = ref ? *ref : def; - if (ref) - { - ImGui::SameLine(); - if (ImGui::Button("Save Style")) - *ref = g.Style; - } - - ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.55f); - - if (ImGui::TreeNode("Sizes")) - { - ImGui::SliderFloat("Alpha", &style.Alpha, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI. But application code could have a toggle to switch between zero and non-zero. - ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 16.0f, "%.0f"); - ImGui::SliderFloat("ChildWindowRounding", &style.ChildWindowRounding, 0.0f, 16.0f, "%.0f"); - ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 16.0f, "%.0f"); - ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); - ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("ScrollBarWidth", &style.ScrollbarWidth, 1.0f, 20.0f, "%.0f"); - ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Colors")) - { - static int output_dest = 0; - static bool output_only_modified = false; - if (ImGui::Button("Output Colors")) - { - if (output_dest == 0) - ImGui::LogToClipboard(); - else - ImGui::LogToTTY(); - ImGui::LogText("ImGuiStyle& style = ImGui::GetStyle();" STR_NEWLINE); - for (int i = 0; i < ImGuiCol_COUNT; i++) - { - const ImVec4& col = style.Colors[i]; - const char* name = ImGui::GetStyleColName(i); - if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &def.Colors[i]), sizeof(ImVec4)) != 0) - ImGui::LogText("style.Colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" STR_NEWLINE, name, 22 - strlen(name), "", col.x, col.y, col.z, col.w); - } - ImGui::LogFinish(); - } - ImGui::SameLine(); ImGui::PushItemWidth(150); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY"); ImGui::PopItemWidth(); - ImGui::SameLine(); ImGui::Checkbox("Only Modified Fields", &output_only_modified); - - static ImGuiColorEditMode edit_mode = ImGuiColorEditMode_RGB; - ImGui::RadioButton("RGB", &edit_mode, ImGuiColorEditMode_RGB); - ImGui::SameLine(); - ImGui::RadioButton("HSV", &edit_mode, ImGuiColorEditMode_HSV); - ImGui::SameLine(); - ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX); - //ImGui::Text("Tip: Click on colored square to change edit mode."); - - static ImGuiTextFilter filter; - filter.Draw("Filter colors", 200); - - ImGui::BeginChild("#colors", ImVec2(0, 300), true); - - ImGui::ColorEditMode(edit_mode); - for (int i = 0; i < ImGuiCol_COUNT; i++) - { - const char* name = ImGui::GetStyleColName(i); - if (!filter.PassFilter(name)) - continue; - ImGui::PushID(i); - ImGui::ColorEdit4(name, (float*)&style.Colors[i], true); - if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &def.Colors[i]), sizeof(ImVec4)) != 0) - { - ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : def.Colors[i]; - if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; } - } - ImGui::PopID(); - } - ImGui::EndChild(); - - ImGui::TreePop(); - } - - ImGui::PopItemWidth(); -} - -//----------------------------------------------------------------------------- -// SAMPLE CODE -//----------------------------------------------------------------------------- - -static void ShowExampleAppConsole(bool* opened); -static void ShowExampleAppLongText(bool* opened); -static void ShowExampleAppAutoResize(bool* opened); -static void ShowExampleAppFixedOverlay(bool* opened); -static void ShowExampleAppManipulatingWindowTitle(bool* opened); -static void ShowExampleAppCustomRendering(bool* opened); - -// Demonstrate ImGui features (unfortunately this makes this function a little bloated!) -void ImGui::ShowTestWindow(bool* opened) -{ - // Examples apps - static bool show_app_metrics = false; - static bool show_app_console = false; - static bool show_app_long_text = false; - static bool show_app_auto_resize = false; - static bool show_app_fixed_overlay = false; - static bool show_app_custom_rendering = false; - static bool show_app_manipulating_window_title = false; - if (show_app_metrics) - ImGui::ShowMetricsWindow(&show_app_metrics); - if (show_app_console) - ShowExampleAppConsole(&show_app_console); - if (show_app_long_text) - ShowExampleAppLongText(&show_app_long_text); - if (show_app_auto_resize) - ShowExampleAppAutoResize(&show_app_auto_resize); - if (show_app_fixed_overlay) - ShowExampleAppFixedOverlay(&show_app_fixed_overlay); - if (show_app_manipulating_window_title) - ShowExampleAppManipulatingWindowTitle(&show_app_manipulating_window_title); - if (show_app_custom_rendering) - ShowExampleAppCustomRendering(&show_app_custom_rendering); - - static bool no_titlebar = false; - static bool no_border = true; - static bool no_resize = false; - static bool no_move = false; - static bool no_scrollbar = false; - static bool no_collapse = false; - static float bg_alpha = 0.65f; - - // Demonstrate the various window flags. Typically you would just use the default. - ImGuiWindowFlags window_flags = 0; - if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar; - if (!no_border) window_flags |= ImGuiWindowFlags_ShowBorders; - if (no_resize) window_flags |= ImGuiWindowFlags_NoResize; - if (no_move) window_flags |= ImGuiWindowFlags_NoMove; - if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar; - if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse; - if (!ImGui::Begin("ImGui Test", opened, ImVec2(550,680), bg_alpha, window_flags)) - { - // Early out if the window is collapsed, as an optimization. - ImGui::End(); - return; - } - - //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // 2/3 of the space for widget and 1/3 for labels - ImGui::PushItemWidth(-140); // Right align, keep 140 pixels for labels - - ImGui::Text("ImGui says hello."); - //ImGui::Text("MousePos (%g, %g)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); - //ImGui::Text("MouseWheel %d", ImGui::GetIO().MouseWheel); - //ImGui::Text("KeyMods %s%s%s", ImGui::GetIO().KeyCtrl ? "CTRL" : "", ImGui::GetIO().KeyShift ? "SHIFT" : "", ImGui::GetIO().KeyAlt? "ALT" : ""); - //ImGui::Text("WantCaptureMouse: %d", ImGui::GetIO().WantCaptureMouse); - //ImGui::Text("WantCaptureKeyboard: %d", ImGui::GetIO().WantCaptureKeyboard); - - ImGui::Spacing(); - if (ImGui::CollapsingHeader("Help")) - { - ImGui::TextWrapped("This window is being created by the ShowTestWindow() function. Please refer to the code for programming reference.\n\nUser Guide:"); - ImGui::ShowUserGuide(); - } - - if (ImGui::CollapsingHeader("Window options")) - { - ImGui::Checkbox("no titlebar", &no_titlebar); ImGui::SameLine(150); - ImGui::Checkbox("no border", &no_border); ImGui::SameLine(300); - ImGui::Checkbox("no resize", &no_resize); - ImGui::Checkbox("no move", &no_move); ImGui::SameLine(150); - ImGui::Checkbox("no scrollbar", &no_scrollbar); ImGui::SameLine(300); - ImGui::Checkbox("no collapse", &no_collapse); - ImGui::SliderFloat("bg alpha", &bg_alpha, 0.0f, 1.0f); - - if (ImGui::TreeNode("Style")) - { - ImGui::ShowStyleEditor(); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Fonts")) - { - ImGui::TextWrapped("Tip: Load fonts with GetIO().Fonts->AddFontFromFileTTF()."); - for (size_t i = 0; i < ImGui::GetIO().Fonts->Fonts.size(); i++) - { - ImFont* font = ImGui::GetIO().Fonts->Fonts[i]; - ImGui::BulletText("Font %d: %.2f pixels, %d glyphs", i, font->FontSize, font->Glyphs.size()); - ImGui::TreePush((void*)i); - ImGui::PushFont(font); - ImGui::Text("The quick brown fox jumps over the lazy dog"); - ImGui::PopFont(); - if (i > 0 && ImGui::Button("Set as default")) - { - ImGui::GetIO().Fonts->Fonts[i] = ImGui::GetIO().Fonts->Fonts[0]; - ImGui::GetIO().Fonts->Fonts[0] = font; - } - ImGui::SliderFloat("font scale", &font->Scale, 0.3f, 2.0f, "%.1f"); // scale only this font - ImGui::TreePop(); - } - static float window_scale = 1.0f; - ImGui::SliderFloat("this window scale", &window_scale, 0.3f, 2.0f, "%.1f"); // scale only this window - ImGui::SliderFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.3f, 2.0f, "%.1f"); // scale everything - ImGui::SetWindowFontScale(window_scale); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Logging")) - { - ImGui::LogButtons(); - ImGui::TreePop(); - } - } - - if (ImGui::CollapsingHeader("Widgets")) - { - static bool a=false; - if (ImGui::Button("Button")) { printf("Clicked\n"); a ^= 1; } - if (a) - { - ImGui::SameLine(); - ImGui::Text("Thanks for clicking me!"); - } - - if (ImGui::TreeNode("Tree")) - { - for (size_t i = 0; i < 5; i++) - { - if (ImGui::TreeNode((void*)i, "Child %d", i)) - { - ImGui::Text("blah blah"); - ImGui::SameLine(); - if (ImGui::SmallButton("print")) - printf("Child %d pressed", (int)i); - ImGui::TreePop(); - } - } - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Bullets")) - { - ImGui::BulletText("Bullet point 1"); - ImGui::BulletText("Bullet point 2\nOn multiple lines"); - ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); - ImGui::Bullet(); ImGui::SmallButton("Button 1"); - ImGui::Bullet(); ImGui::SmallButton("Button 2"); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Colored Text")) - { - // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. - ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink"); - ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow"); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Word Wrapping")) - { - // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. - ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules that works for English and possibly other languages."); - ImGui::Spacing(); - - static float wrap_width = 200.0f; - ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); - - ImGui::Text("Test paragraph 1:"); - ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorScreenPos() + ImVec2(wrap_width, 0.0f), ImGui::GetCursorScreenPos() + ImVec2(wrap_width+10, ImGui::GetTextLineHeight()), 0xFFFF00FF); - ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); - ImGui::Text("lazy dog. This paragraph is made to fit within %.0f pixels. The quick brown fox jumps over the lazy dog.", wrap_width); - ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xFF00FFFF); - ImGui::PopTextWrapPos(); - - ImGui::Text("Test paragraph 2:"); - ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorScreenPos() + ImVec2(wrap_width, 0.0f), ImGui::GetCursorScreenPos() + ImVec2(wrap_width+10, ImGui::GetTextLineHeight()), 0xFFFF00FF); - ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); - ImGui::Text("aaaaaaaa bbbbbbbb, cccccccc,dddddddd. eeeeeeee ffffffff. gggggggg!hhhhhhhh"); - ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xFF00FFFF); - ImGui::PopTextWrapPos(); - - ImGui::TreePop(); - } - - if (ImGui::TreeNode("UTF-8 Text")) - { - // UTF-8 test with Japanese characters - // (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html) - // Most compiler appears to support UTF-8 in source code (with Visual Studio you need to save your file as 'UTF-8 without signature') - // However for the sake for maximum portability here we are *not* including raw UTF-8 character in this source file, instead we encode the string with hexadecimal constants. - // In your own application be reasonable and use UTF-8 in source or retrieve the data from file system! - // Note that characters values are preserved even if the font cannot be displayed, so you can safely copy & paste garbled characters into another application. - ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->LoadFromFileTTF() manually to load extra character ranges."); - ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); - ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); - static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; - ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Clipping")) - { - static ImVec2 size(80, 20); - ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text if it won't fit in its frame."); - ImGui::SliderFloat2("size", (float*)&size, 5.0f, 200.0f); - ImGui::Button("Line 1 hello\nLine 2 clip me!", size); - ImGui::TextWrapped("Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and rendering cost."); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Images")) - { - ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!"); - ImVec2 tex_screen_pos = ImGui::GetCursorScreenPos(); - float tex_w = (float)ImGui::GetIO().Fonts->TexWidth; - float tex_h = (float)ImGui::GetIO().Fonts->TexHeight; - ImTextureID tex_id = ImGui::GetIO().Fonts->TexID; - ImGui::Image(tex_id, ImVec2(tex_w, tex_h), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); - if (ImGui::IsItemHovered()) - { - ImGui::BeginTooltip(); - float focus_sz = 32.0f; - float focus_x = ImClamp(ImGui::GetMousePos().x - tex_screen_pos.x - focus_sz * 0.5f, 0.0f, tex_w - focus_sz); - float focus_y = ImClamp(ImGui::GetMousePos().y - tex_screen_pos.y - focus_sz * 0.5f, 0.0f, tex_h - focus_sz); - ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y); - ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz); - ImVec2 uv0 = ImVec2((focus_x) / tex_w, (focus_y) / tex_h); - ImVec2 uv1 = ImVec2((focus_x + focus_sz) / tex_w, (focus_y + focus_sz) / tex_h); - ImGui::Image(tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128)); - ImGui::EndTooltip(); - } - ImGui::TextWrapped("And now some textured buttons.."); - static int pressed_count = 0; - for (int i = 0; i < 8; i++) - { - if (i > 0) - ImGui::SameLine(); - ImGui::PushID(i); - int frame_padding = -1 + i; // -1 padding uses default padding - if (ImGui::ImageButton(tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/tex_w,32/tex_h), frame_padding)) - pressed_count += 1; - ImGui::PopID(); - } - ImGui::Text("Pressed %d times.", pressed_count); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Selectables")) - { - if (ImGui::TreeNode("Basic")) - { - static bool selected[3] = { false, true, false }; - ImGui::Selectable("1. I am selectable", &selected[0]); - ImGui::Selectable("2. I am selectable", &selected[1]); - ImGui::Text("3. I am not selectable"); - ImGui::Selectable("4. I am selectable", &selected[2]); - ImGui::TreePop(); - } - if (ImGui::TreeNode("Rendering more text into the same block")) - { - static bool selected[3] = { false, false, false }; - ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); - ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes"); - ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); - ImGui::TreePop(); - } - if (ImGui::TreeNode("Grid")) - { - static bool selected[16] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true }; - for (int i = 0; i < 16; i++) - { - ImGui::PushID(i); - if (ImGui::Selectable("Me", &selected[i], ImVec2(50,50))) - { - int x = i % 4, y = i / 4; - if (x > 0) selected[i - 1] ^= 1; - if (x < 3) selected[i + 1] ^= 1; - if (y > 0) selected[i - 4] ^= 1; - if (y < 3) selected[i + 4] ^= 1; - } - if ((i % 4) < 3) ImGui::SameLine(); - ImGui::PopID(); - } - ImGui::TreePop(); - } - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Popup")) - { - static bool popup_open = false; - static int selected_fish = -1; - const char* fishes[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; - if (ImGui::Button("Select..")) - popup_open = true; - ImGui::SameLine(); - ImGui::Text(selected_fish == -1 ? "<None>" : fishes[selected_fish]); - if (popup_open) - { - ImGui::BeginPopup(&popup_open); - ImGui::Text("Aquarium"); - ImGui::Separator(); - for (int i = 0; i < IM_ARRAYSIZE(fishes); i++) - { - if (ImGui::Selectable(fishes[i], false)) - { - selected_fish = i; - popup_open = false; - } - } - ImGui::EndPopup(); - } - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Filtered Text Input")) - { - static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); - static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); - static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); - static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); - static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); - struct TextFilters { static int FilterImGuiLetters(ImGuiTextEditCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } }; - static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); - ImGui::TreePop(); - } - - static bool check = true; - ImGui::Checkbox("checkbox", &check); - - static int e = 0; - ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); - ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); - ImGui::RadioButton("radio c", &e, 2); - - // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. - for (int i = 0; i < 7; i++) - { - if (i > 0) ImGui::SameLine(); - ImGui::PushID(i); - ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(i/7.0f, 0.6f, 0.6f)); - ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(i/7.0f, 0.7f, 0.7f)); - ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(i/7.0f, 0.8f, 0.8f)); - ImGui::Button("Click"); - ImGui::PopStyleColor(3); - ImGui::PopID(); - } - - ImGui::Text("Hover over me"); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("I am a tooltip"); - - ImGui::SameLine(); - ImGui::Text("- or me"); - if (ImGui::IsItemHovered()) - { - ImGui::BeginTooltip(); - ImGui::Text("I am a fancy tooltip"); - static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; - ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); - ImGui::EndTooltip(); - } - - // Testing IMGUI_ONCE_UPON_A_FRAME macro - //for (int i = 0; i < 5; i++) - //{ - // IMGUI_ONCE_UPON_A_FRAME - // { - // ImGui::Text("This will be displayed only once."); - // } - //} - - ImGui::Separator(); - - ImGui::LabelText("label", "Value"); - - static int item = 1; - ImGui::Combo("combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); - - const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" }; - static int item2 = -1; - ImGui::Combo("combo scroll", &item2, items, IM_ARRAYSIZE(items)); - - { - static char str0[128] = "Hello, world!"; - static int i0=123; - static float f0=0.001f; - ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); - ImGui::InputInt("input int", &i0); - ImGui::InputFloat("input float", &f0, 0.01f, 1.0f); - - static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; - ImGui::InputFloat3("input float3", vec4a); - } - - /* - { - static int i1=50; - static int i2=42; - ImGui::DragInt("drag int", &i1, 1); - ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100); - - static float f1=1.00f; - static float f2=0.0067f; - ImGui::DragFloat("drag float", &f1, 1.0f); - ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f"); - } - */ - - { - static int i1=0; - static int i2=42; - ImGui::SliderInt("slider int 0..3", &i1, 0, 3); - ImGui::SliderInt("slider int -100..100", &i2, -100, 100); - - static float f1=1.123f; - static float f2=0; - static float f3=123456789.0f; - ImGui::SliderFloat("slider float", &f1, 0.0f, 2.0f); - ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f); - static float angle = 0.0f; - ImGui::SliderAngle("slider angle", &angle); - } - - static float col1[3] = { 1.0f,0.0f,0.2f }; - static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; - ImGui::ColorEdit3("color 1", col1); - ImGui::ColorEdit4("color 2", col2); - - const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; - static int listbox_item_current = 1; - ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4); - - //static int listbox_item_current2 = 2; - //ImGui::PushItemWidth(-1); - //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4); - //ImGui::PopItemWidth(); - - if (ImGui::TreeNode("Multi-component Widgets")) - { - ImGui::Unindent(); - - static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; - static int vec4i[4] = { 1, 5, 100, 255 }; - - ImGui::InputFloat2("input float2", vec4f); - ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); - ImGui::InputInt2("input int2", vec4i); - ImGui::SliderInt2("slider int2", vec4i, 0, 255); - - ImGui::InputFloat3("input float3", vec4f); - ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); - ImGui::InputInt3("input int3", vec4i); - ImGui::SliderInt3("slider int3", vec4i, 0, 255); - - ImGui::InputFloat4("input float4", vec4f); - ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); - ImGui::InputInt4("input int4", vec4i); - ImGui::SliderInt4("slider int4", vec4i, 0, 255); - - ImGui::Indent(); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Vertical Sliders")) - { - ImGui::Unindent(); - const float spacing = 4; - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); - - static int int_value = 0; - ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5); - ImGui::SameLine(); - - static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; - ImGui::PushID("set1"); - for (int i = 0; i < 7; i++) - { - if (i > 0) ImGui::SameLine(); - ImGui::PushID(i); - ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor::HSV(i/7.0f, 0.5f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImColor::HSV(i/7.0f, 0.6f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImColor::HSV(i/7.0f, 0.7f, 0.5f)); - ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor::HSV(i/7.0f, 0.9f, 0.9f)); - ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, ""); - if (ImGui::IsItemActive() || ImGui::IsItemHovered()) - ImGui::SetTooltip("%.3f", values[i]); - ImGui::PopStyleColor(4); - ImGui::PopID(); - } - ImGui::PopID(); - - ImGui::SameLine(); - ImGui::PushID("set2"); - static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; - const int rows = 3; - const ImVec2 small_slider_size(18, (160.0f-(rows-1)*spacing)/rows); - for (int nx = 0; nx < 4; nx++) - { - if (nx > 0) ImGui::SameLine(); - ImGui::BeginGroup(); - for (int ny = 0; ny < rows; ny++) - { - ImGui::PushID(nx*rows+ny); - ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); - if (ImGui::IsItemActive() || ImGui::IsItemHovered()) - ImGui::SetTooltip("%.3f", values2[nx]); - ImGui::PopID(); - } - ImGui::EndGroup(); - } - ImGui::PopID(); - - ImGui::SameLine(); - ImGui::PushID("set3"); - for (int i = 0; i < 4; i++) - { - if (i > 0) ImGui::SameLine(); - ImGui::PushID(i); - ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); - ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f"); - ImGui::PopStyleVar(); - ImGui::PopID(); - } - ImGui::PopID(); - - ImGui::Indent(); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Dragging")) - { - // You can use ImGui::GetItemActiveDragDelta() to query for the dragged amount on any widget. - static ImVec2 value_raw(0.0f, 0.0f); - static ImVec2 value_with_lock_threshold(0.0f, 0.0f); - ImGui::Button("Drag Me"); - if (ImGui::IsItemActive()) - { - value_raw = ImGui::GetMouseDragDelta(0, 0.0f); - value_with_lock_threshold = ImGui::GetMouseDragDelta(0); - //ImGui::SetTooltip("Delta: %.1f, %.1f", value.x, value.y); - - // Draw a line between the button and the mouse cursor - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - draw_list->PushClipRectFullScreen(); - draw_list->AddLine(ImGui::CalcItemRectClosestPoint(ImGui::GetIO().MousePos, true, -2.0f), ImGui::GetIO().MousePos, ImColor(ImGui::GetStyle().Colors[ImGuiCol_Button]), 4.0f); - draw_list->PopClipRect(); - } - ImGui::SameLine(); ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y); - ImGui::TreePop(); - } - } - - if (ImGui::CollapsingHeader("Graphs widgets")) - { - static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; - ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); - - static bool pause; - static ImVector<float> values; if (values.empty()) { values.resize(90); memset(&values.front(), 0, values.size()*sizeof(float)); } - static size_t values_offset = 0; - if (!pause) - { - // create dummy data at fixed 60 hz rate - static float refresh_time = -1.0f; - if (ImGui::GetTime() > refresh_time + 1.0f/60.0f) - { - refresh_time = ImGui::GetTime(); - static float phase = 0.0f; - values[values_offset] = cosf(phase); - values_offset = (values_offset+1)%values.size(); - phase += 0.10f*values_offset; - } - } - ImGui::PlotLines("##Graph", &values.front(), (int)values.size(), (int)values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80)); - ImGui::SameLine(0, (int)ImGui::GetStyle().ItemInnerSpacing.x); - ImGui::BeginGroup(); - ImGui::Text("Graph"); - ImGui::Checkbox("pause", &pause); - ImGui::EndGroup(); - ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80)); - } - - if (ImGui::CollapsingHeader("Layout")) - { - if (ImGui::TreeNode("Widgets Alignment")) - { - static float f = 0.0f; - ImGui::Text("Fixed: 100 pixels"); - ImGui::PushItemWidth(100); - ImGui::InputFloat("float##1", &f); - ImGui::PopItemWidth(); - - ImGui::Text("Proportional: 50%% of window width"); - ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); - ImGui::InputFloat("float##2", &f); - ImGui::PopItemWidth(); - - ImGui::Text("Right-aligned: Leave 100 pixels for label"); - ImGui::PushItemWidth(-100); - ImGui::InputFloat("float##3", &f); - ImGui::PopItemWidth(); - - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Basic Horizontal Layout")) - { - ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceeding item)"); - - // Text - ImGui::Text("Two items: Hello"); - ImGui::SameLine(); - ImGui::TextColored(ImVec4(1,1,0,1), "World"); - - // Adjust spacing - ImGui::Text("More spacing: Hello"); - ImGui::SameLine(0, 20); - ImGui::TextColored(ImVec4(1,1,0,1), "World"); - - // Button - ImGui::AlignFirstTextHeightToWidgets(); - ImGui::Text("Normal buttons"); ImGui::SameLine(); - ImGui::Button("Banana"); ImGui::SameLine(); - ImGui::Button("Apple"); ImGui::SameLine(); - ImGui::Button("Corniflower"); - - // Button - ImGui::Text("Small buttons"); ImGui::SameLine(); - ImGui::SmallButton("Like this one"); ImGui::SameLine(); - ImGui::Text("can fit within a text block."); - - // Aligned to arbitrary position. Easy/cheap column. - ImGui::Text("Aligned"); - ImGui::SameLine(150); ImGui::Text("x=150"); - ImGui::SameLine(300); ImGui::Text("x=300"); - ImGui::Text("Aligned"); - ImGui::SameLine(150); ImGui::SmallButton("x=150"); - ImGui::SameLine(300); ImGui::SmallButton("x=300"); - - // Checkbox - static bool c1=false,c2=false,c3=false,c4=false; - ImGui::Checkbox("My", &c1); ImGui::SameLine(); - ImGui::Checkbox("Tailor", &c2); ImGui::SameLine(); - ImGui::Checkbox("Is", &c3); ImGui::SameLine(); - ImGui::Checkbox("Rich", &c4); - - // Various - static float f0=1.0f, f1=2.0f, f2=3.0f; - ImGui::PushItemWidth(80); - const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; - static int item = -1; - ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); - ImGui::SliderFloat("X", &f0, 0.0f,5.0f); ImGui::SameLine(); - ImGui::SliderFloat("Y", &f1, 0.0f,5.0f); ImGui::SameLine(); - ImGui::SliderFloat("Z", &f2, 0.0f,5.0f); - ImGui::PopItemWidth(); - - ImGui::PushItemWidth(80); - ImGui::Text("Lists:"); - static int selection[4] = { 0, 1, 2, 3 }; - for (int i = 0; i < 4; i++) - { - if (i > 0) ImGui::SameLine(); - ImGui::PushID(i); - ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items)); - ImGui::PopID(); - //if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i); - } - ImGui::PopItemWidth(); - - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Groups")) - { - ImGui::TextWrapped("(Using ImGui::BeginGroup()/EndGroup() to layout items)"); - - ImVec2 size; - ImGui::BeginGroup(); - { - ImGui::BeginGroup(); - ImGui::Button("AAA"); - ImGui::SameLine(); - ImGui::Button("BBB"); - ImGui::SameLine(); - ImGui::BeginGroup(); - ImGui::Button("CCC"); - ImGui::Button("DDD"); - ImGui::EndGroup(); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip("Group hovered"); - ImGui::SameLine(); - ImGui::Button("EEE"); - ImGui::EndGroup(); - - // Capture the group size and create widgets using the same size - size = ImGui::GetItemRectSize(); - const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; - ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); - } - ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); - ImGui::SameLine(); - ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); - ImGui::EndGroup(); - ImGui::SameLine(); - - ImGui::Button("LEVERAGE\nBUZZWORD", size); - ImGui::SameLine(); - - ImGui::ListBoxHeader("List", size); - ImGui::Selectable("Selected", true); - ImGui::Selectable("Not Selected", false); - ImGui::ListBoxFooter(); - - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Text Baseline Alignment")) - { - ImGui::TextWrapped("(This is testing the vertical alignment that occurs on text to keep it at the same baseline as widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets)"); - - ImGui::Text("One\nTwo\nThree"); ImGui::SameLine(); - ImGui::Text("Hello\nWorld"); ImGui::SameLine(); - ImGui::Text("Banana"); - - ImGui::Text("Banana"); ImGui::SameLine(); - ImGui::Text("Hello\nWorld"); ImGui::SameLine(); - ImGui::Text("One\nTwo\nThree"); - - ImGui::Button("HOP"); ImGui::SameLine(); - ImGui::Text("Banana"); ImGui::SameLine(); - ImGui::Text("Hello\nWorld"); ImGui::SameLine(); - ImGui::Text("Banana"); - - ImGui::Button("HOP"); ImGui::SameLine(); - ImGui::Text("Hello\nWorld"); ImGui::SameLine(); - ImGui::Text("Banana"); - - ImGui::Button("TEST"); ImGui::SameLine(); - ImGui::Text("TEST"); ImGui::SameLine(); - ImGui::SmallButton("TEST"); - - ImGui::AlignFirstTextHeightToWidgets(); // If your line starts with text, call this to align it to upcoming widgets. - ImGui::Text("Text aligned to Widget"); ImGui::SameLine(); - ImGui::Button("Widget"); ImGui::SameLine(); - ImGui::Text("Widget"); ImGui::SameLine(); - ImGui::SmallButton("Widget"); - - ImGui::TreePop(); - } - } - - if (ImGui::CollapsingHeader("Child regions")) - { - ImGui::Text("Without border"); - static int line = 50; - bool goto_line = ImGui::Button("Goto"); - ImGui::SameLine(); - ImGui::PushItemWidth(100); - goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); - ImGui::PopItemWidth(); - ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowWidth() * 0.5f,300)); - for (int i = 0; i < 100; i++) - { - ImGui::Text("%04d: scrollable region", i); - if (goto_line && line == i) - ImGui::SetScrollPosHere(); - } - if (goto_line && line >= 100) - ImGui::SetScrollPosHere(); - ImGui::EndChild(); - - ImGui::SameLine(); - - ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 5.0f); - ImGui::BeginChild("Sub2", ImVec2(0,300), true); - ImGui::Text("With border"); - ImGui::Columns(2); - for (int i = 0; i < 100; i++) - { - if (i == 50) - ImGui::NextColumn(); - char buf[32]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "%08x", i*5731); - ImGui::Button(buf); - } - ImGui::EndChild(); - ImGui::PopStyleVar(); - } - - if (ImGui::CollapsingHeader("Columns")) - { - // Basic columns - ImGui::Text("Basic:"); - ImGui::Columns(4, "mycolumns"); - ImGui::Separator(); - ImGui::Text("ID"); ImGui::NextColumn(); - ImGui::Text("Name"); ImGui::NextColumn(); - ImGui::Text("Path"); ImGui::NextColumn(); - ImGui::Text("Flags"); ImGui::NextColumn(); - ImGui::Separator(); - const char* names[3] = { "Robert", "Stephanie", "C64" }; - const char* paths[3] = { "/path/robert", "/path/stephanie", "/path/computer" }; - for (int i = 0; i < 3; i++) - { - ImGui::Text("%04d", i); ImGui::NextColumn(); - ImGui::Text(names[i]); ImGui::NextColumn(); - ImGui::Text(paths[i]); ImGui::NextColumn(); - ImGui::Text("...."); ImGui::NextColumn(); - } - ImGui::Columns(1); - - ImGui::Separator(); - ImGui::Spacing(); - - // Scrolling columns - /* - ImGui::Text("Scrolling:"); - ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y)); - ImGui::Columns(3); - ImGui::Text("ID"); ImGui::NextColumn(); - ImGui::Text("Name"); ImGui::NextColumn(); - ImGui::Text("Path"); ImGui::NextColumn(); - ImGui::Columns(1); - ImGui::Separator(); - ImGui::EndChild(); - ImGui::BeginChild("##scrollingregion", ImVec2(0, 60)); - ImGui::Columns(3); - for (int i = 0; i < 10; i++) - { - ImGui::Text("%04d", i); ImGui::NextColumn(); - ImGui::Text("Foobar"); ImGui::NextColumn(); - ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn(); - } - ImGui::Columns(1); - ImGui::EndChild(); - - ImGui::Separator(); - ImGui::Spacing(); - */ - - // Create multiple items in a same cell before switching to next column - ImGui::Text("Mixed items:"); - ImGui::Columns(3, "mixed"); - ImGui::Separator(); - - static int e = 0; - ImGui::Text("Hello"); - ImGui::Button("Banana"); - ImGui::RadioButton("radio a", &e, 0); - ImGui::NextColumn(); - - ImGui::Text("ImGui"); - ImGui::Button("Apple"); - ImGui::RadioButton("radio b", &e, 1); - static float foo = 1.0f; - ImGui::InputFloat("red", &foo, 0.05f, 0, 3); - ImGui::Text("An extra line here."); - ImGui::NextColumn(); - - ImGui::Text("World!"); - ImGui::Button("Corniflower"); - ImGui::RadioButton("radio c", &e, 2); - static float bar = 1.0f; - ImGui::InputFloat("blue", &bar, 0.05f, 0, 3); - ImGui::NextColumn(); - - if (ImGui::CollapsingHeader("Category A")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); - if (ImGui::CollapsingHeader("Category B")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); - if (ImGui::CollapsingHeader("Category C")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); - ImGui::Columns(1); - - ImGui::Separator(); - ImGui::Spacing(); - - // Tree items - ImGui::Text("Tree items:"); - ImGui::Columns(2, "tree items"); - ImGui::Separator(); - if (ImGui::TreeNode("Hello")) { ImGui::BulletText("World"); ImGui::TreePop(); } ImGui::NextColumn(); - if (ImGui::TreeNode("Bonjour")) { ImGui::BulletText("Monde"); ImGui::TreePop(); } ImGui::NextColumn(); - ImGui::Columns(1); - - ImGui::Separator(); - ImGui::Spacing(); - - // Word-wrapping - ImGui::Text("Word-wrapping:"); - ImGui::Columns(2, "word-wrapping"); - ImGui::Separator(); - ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); - ImGui::Text("Hello Left"); - ImGui::NextColumn(); - ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); - ImGui::Text("Hello Right"); - ImGui::Columns(1); - - ImGui::Separator(); - ImGui::Spacing(); - - if (ImGui::TreeNode("Inside a tree..")) - { - if (ImGui::TreeNode("node 1 (with borders)")) - { - ImGui::Columns(4); - for (int i = 0; i < 8; i++) - { - ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); - ImGui::NextColumn(); - } - ImGui::Columns(1); - ImGui::TreePop(); - } - if (ImGui::TreeNode("node 2 (without borders)")) - { - ImGui::Columns(4, NULL, false); - for (int i = 0; i < 8; i++) - { - ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); - ImGui::NextColumn(); - } - ImGui::Columns(1); - ImGui::TreePop(); - } - ImGui::TreePop(); - } - } - - if (ImGui::CollapsingHeader("Filtering")) - { - static ImGuiTextFilter filter; - ImGui::Text("Filter usage:\n" - " \"\" display all lines\n" - " \"xxx\" display lines containing \"xxx\"\n" - " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" - " \"-xxx\" hide lines containing \"xxx\""); - filter.Draw(); - const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; - for (size_t i = 0; i < IM_ARRAYSIZE(lines); i++) - if (filter.PassFilter(lines[i])) - ImGui::BulletText("%s", lines[i]); - } - - if (ImGui::CollapsingHeader("Keyboard, Mouse & Focus")) - { - if (ImGui::TreeNode("Tabbing")) - { - ImGui::Text("Use TAB/SHIFT+TAB to cycle thru keyboard editable fields."); - static char buf[32] = "dummy"; - ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); - ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); - ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); - ImGui::PushAllowKeyboardFocus(false); - ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); - //ImGui::SameLine(); ImGui::Text("(?)"); if (ImGui::IsHovered()) ImGui::SetTooltip("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); - ImGui::PopAllowKeyboardFocus(); - ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Focus from code")) - { - bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); - bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); - bool focus_3 = ImGui::Button("Focus on 3"); - int has_focus = 0; - static char buf[128] = "click on a button to set focus"; - - if (focus_1) ImGui::SetKeyboardFocusHere(); - ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); - if (ImGui::IsItemActive()) has_focus = 1; - - if (focus_2) ImGui::SetKeyboardFocusHere(); - ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); - if (ImGui::IsItemActive()) has_focus = 2; - - ImGui::PushAllowKeyboardFocus(false); - if (focus_3) ImGui::SetKeyboardFocusHere(); - ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); - if (ImGui::IsItemActive()) has_focus = 3; - ImGui::PopAllowKeyboardFocus(); - if (has_focus) - ImGui::Text("Item with focus: %d", has_focus); - else - ImGui::Text("Item with focus: <none>"); - ImGui::TextWrapped("Cursor & selection are preserved when refocusing last used item in code."); - ImGui::TreePop(); - } - - if (ImGui::TreeNode("Mouse cursors")) - { - ImGui::TextWrapped("(Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. You can also set io.MouseDrawCursor to ask ImGui to render the cursor for you in software)"); - ImGui::Checkbox("io.MouseDrawCursor", &ImGui::GetIO().MouseDrawCursor); - ImGui::Text("Hover to see mouse cursors:"); - for (int i = 0; i < ImGuiMouseCursor_Count_; i++) - { - char label[32]; - sprintf(label, "Mouse cursor %d", i); - ImGui::Bullet(); ImGui::Selectable(label, false); - if (ImGui::IsItemHovered()) - ImGui::SetMouseCursor(i); - } - ImGui::TreePop(); - } - } - - if (ImGui::CollapsingHeader("App Examples")) - { - ImGui::Checkbox("Metrics", &show_app_metrics); - ImGui::Checkbox("Console", &show_app_console); - ImGui::Checkbox("Long text display", &show_app_long_text); - ImGui::Checkbox("Auto-resizing window", &show_app_auto_resize); - ImGui::Checkbox("Simple overlay", &show_app_fixed_overlay); - ImGui::Checkbox("Manipulating window title", &show_app_manipulating_window_title); - ImGui::Checkbox("Custom rendering", &show_app_custom_rendering); - } - - ImGui::End(); -} - -void ImGui::ShowMetricsWindow(bool* opened) -{ - if (ImGui::Begin("ImGui Metrics", opened)) - { - ImGui::Text("ImGui %s", ImGui::GetVersion()); - ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); - ImGui::Text("%d vertices", ImGui::GetIO().MetricsVertices); - ImGui::Separator(); - - struct Funcs - { - static void NodeDrawList(ImDrawList* draw_list, const char* label) - { - bool opened = ImGui::TreeNode(draw_list, "%s: %d vtx, %d cmds", label, draw_list->vtx_buffer.size(), draw_list->commands.size()); - if (draw_list == ImGui::GetWindowDrawList()) - { - ImGui::SameLine(); - ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) - } - if (!opened) - return; - for (const ImDrawCmd* pcmd = draw_list->commands.begin(); pcmd < draw_list->commands.end(); pcmd++) - if (pcmd->user_callback) - ImGui::BulletText("Callback %p, user_data %p", pcmd->user_callback, pcmd->user_callback_data); - else - ImGui::BulletText("Draw %d vtx, tex = %p", pcmd->vtx_count, pcmd->texture_id); - ImGui::TreePop(); - } - - static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label) - { - if (!ImGui::TreeNode(label, "%s (%d)", label, (int)windows.size())) - return; - for (int i = 0; i < (int)windows.size(); i++) - Funcs::NodeWindow(windows[i], "Window"); - ImGui::TreePop(); - } - - static void NodeWindow(ImGuiWindow* window, const char* label) - { - if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Visible, window)) - return; - NodeDrawList(window->DrawList, "DrawList"); - if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); - if (window->DC.ChildWindows.size() > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); - ImGui::TreePop(); - } - }; - - ImGuiState& g = *GImGui; // Access private state - g.DisableHideTextAfterDoubleHash++; // Not exposed (yet). Disable processing that hides text after '##' markers. - Funcs::NodeWindows(g.Windows, "Windows"); - if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", (int)g.RenderDrawLists[0].size())) - { - for (int i = 0; i < (int)g.RenderDrawLists[0].size(); i++) - Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList"); - ImGui::TreePop(); - } - g.DisableHideTextAfterDoubleHash--; - } - ImGui::End(); -} - -static void ShowExampleAppAutoResize(bool* opened) -{ - if (!ImGui::Begin("Example: Auto-Resizing Window", opened, ImGuiWindowFlags_AlwaysAutoResize)) - { - ImGui::End(); - return; - } - - static int lines = 10; - ImGui::TextWrapped("Window will resize every-frame to the size of its content. Note that you don't want to query the window size to output your content because that would create a feedback loop."); - ImGui::SliderInt("Number of lines", &lines, 1, 20); - for (int i = 0; i < lines; i++) - ImGui::Text("%*sThis is line %d", i*4, "", i); // Pad with space to extend size horizontally - - ImGui::End(); -} - -static void ShowExampleAppFixedOverlay(bool* opened) -{ - ImGui::SetNextWindowPos(ImVec2(10,10)); - if (!ImGui::Begin("Example: Fixed Overlay", opened, ImVec2(0,0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings)) - { - ImGui::End(); - return; - } - - ImGui::Text("Simple overlay\non the top-left side of the screen."); - ImGui::Separator(); - ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); - - ImGui::End(); -} - -static void ShowExampleAppManipulatingWindowTitle(bool* opened) -{ - (void)opened; - - // By default, Windows are uniquely identified by their title. - // You can use the "##" and "###" markers to manipulate the display/ID. Read FAQ at the top of this file! - - // Using "##" to display same title but have unique identifier. - ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiSetCond_FirstUseEver); - ImGui::Begin("Same title as another window##1"); - ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique."); - ImGui::End(); - - ImGui::SetNextWindowPos(ImVec2(100,200), ImGuiSetCond_FirstUseEver); - ImGui::Begin("Same title as another window##2"); - ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique."); - ImGui::End(); - - // Using "###" to display a changing title but keep a static identifier "AnimatedTitle" - char buf[128]; - ImFormatString(buf, IM_ARRAYSIZE(buf), "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], rand()); - ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiSetCond_FirstUseEver); - ImGui::Begin(buf); - ImGui::Text("This window has a changing title."); - ImGui::End(); -} - -static void ShowExampleAppCustomRendering(bool* opened) -{ - ImGui::SetNextWindowSize(ImVec2(300,350), ImGuiSetCond_FirstUseEver); - if (!ImGui::Begin("Example: Custom Rendering", opened)) - { - ImGui::End(); - return; - } - - // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc. - // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4. - // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types) - // In this example we aren't using the operators. - - static ImVector<ImVec2> points; - static bool adding_line = false; - if (ImGui::Button("Clear")) points.clear(); - if (points.size() >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } - ImGui::Text("Left-click and drag to add lines"); - ImGui::Text("Right-click to undo"); - - ImDrawList* draw_list = ImGui::GetWindowDrawList(); - - // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() - // However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). - // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). - ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! - ImVec2 canvas_size = ImVec2(ImMax(50.0f,ImGui::GetWindowContentRegionMax().x-ImGui::GetCursorPos().x), ImMax(50.0f,ImGui::GetWindowContentRegionMax().y-ImGui::GetCursorPos().y)); // Resize canvas what's available - draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), 0xFFFFFFFF); - bool adding_preview = false; - ImGui::InvisibleButton("canvas", canvas_size); - if (ImGui::IsItemHovered()) - { - ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); - if (!adding_line && ImGui::GetIO().MouseClicked[0]) - { - points.push_back(mouse_pos_in_canvas); - adding_line = true; - } - if (adding_line) - { - adding_preview = true; - points.push_back(mouse_pos_in_canvas); - if (!ImGui::GetIO().MouseDown[0]) - adding_line = adding_preview = false; - } - if (ImGui::GetIO().MouseClicked[1] && !points.empty()) - { - adding_line = false; - points.pop_back(); - points.pop_back(); - } - } - draw_list->PushClipRect(ImVec4(canvas_pos.x, canvas_pos.y, canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.) - for (int i = 0; i < (int)points.size() - 1; i += 2) - draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i+1].x, canvas_pos.y + points[i+1].y), 0xFF00FFFF); - draw_list->PopClipRect(); - if (adding_preview) - points.pop_back(); - ImGui::End(); -} - -struct ExampleAppConsole -{ - char InputBuf[256]; - ImVector<char*> Items; - bool ScrollToBottom; - ImVector<char*> History; - int HistoryPos; // -1: new line, 0..History.size()-1 browsing history. - ImVector<const char*> Commands; - - ExampleAppConsole() - { - ClearLog(); - HistoryPos = -1; - Commands.push_back("HELP"); - Commands.push_back("HISTORY"); - Commands.push_back("CLEAR"); - Commands.push_back("CLASSIFY"); // "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches. - } - ~ExampleAppConsole() - { - ClearLog(); - for (size_t i = 0; i < Items.size(); i++) - ImGui::MemFree(History[i]); - } - - void ClearLog() - { - for (size_t i = 0; i < Items.size(); i++) - ImGui::MemFree(Items[i]); - Items.clear(); - ScrollToBottom = true; - } - - void AddLog(const char* fmt, ...) - { - char buf[1024]; - va_list args; - va_start(args, fmt); - ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); - va_end(args); - Items.push_back(ImStrdup(buf)); - ScrollToBottom = true; - } - - void Run(const char* title, bool* opened) - { - ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); - if (!ImGui::Begin(title, opened)) - { - ImGui::End(); - return; - } - - ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc."); - ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); - - // TODO: display from bottom - // TODO: clip manually - - if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.size()); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); - if (ImGui::SmallButton("Add Dummy Error")) AddLog("[error] something went wrong"); ImGui::SameLine(); - if (ImGui::SmallButton("Clear")) ClearLog(); - //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } - - ImGui::Separator(); - - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); - static ImGuiTextFilter filter; - filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); - //if (ImGui::IsItemHovered()) ImGui::SetKeyboardFocusHere(-1); // Auto focus on hover - ImGui::PopStyleVar(); - ImGui::Separator(); - - // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); - // NB- if you have thousands of entries this approach may be too inefficient. You can seek and display only the lines that are visible - CalcListClipping() is a helper to compute this information. - // If your items are of variable size you may want to implement code similar to what CalcListClipping() does. Or split your data into fixed height items to allow random-seeking into your list. - ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetTextLineHeightWithSpacing()*2)); - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing - for (size_t i = 0; i < Items.size(); i++) - { - const char* item = Items[i]; - if (!filter.PassFilter(item)) - continue; - ImVec4 col(1,1,1,1); // A better implement may store a type per-item. For the sample let's just parse the text. - if (strstr(item, "[error]")) col = ImVec4(1.0f,0.4f,0.4f,1.0f); - else if (strncmp(item, "# ", 2) == 0) col = ImVec4(1.0f,0.8f,0.6f,1.0f); - ImGui::PushStyleColor(ImGuiCol_Text, col); - ImGui::TextUnformatted(item); - ImGui::PopStyleColor(); - } - if (ScrollToBottom) - ImGui::SetScrollPosHere(); - ScrollToBottom = false; - ImGui::PopStyleVar(); - ImGui::EndChild(); - ImGui::Separator(); - - // Command-line - if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this)) - { - char* input_end = InputBuf+strlen(InputBuf); - while (input_end > InputBuf && input_end[-1] == ' ') input_end--; *input_end = 0; - if (InputBuf[0]) - ExecCommand(InputBuf); - strcpy(InputBuf, ""); - } - - // Demonstrate keeping auto focus on the input box - if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) - ImGui::SetKeyboardFocusHere(-1); // Auto focus - - ImGui::End(); - } - - void ExecCommand(const char* command_line) - { - AddLog("# %s\n", command_line); - - // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. - HistoryPos = -1; - for (int i = (int)History.size()-1; i >= 0; i--) - if (ImStricmp(History[i], command_line) == 0) - { - ImGui::MemFree(History[i]); - History.erase(History.begin() + i); - break; - } - History.push_back(ImStrdup(command_line)); - - // Process command - if (ImStricmp(command_line, "CLEAR") == 0) - { - ClearLog(); - } - else if (ImStricmp(command_line, "HELP") == 0) - { - AddLog("Commands:"); - for (size_t i = 0; i < Commands.size(); i++) - AddLog("- %s", Commands[i]); - } - else if (ImStricmp(command_line, "HISTORY") == 0) - { - for (size_t i = History.size() >= 10 ? History.size() - 10 : 0; i < History.size(); i++) - AddLog("%3d: %s\n", i, History[i]); - } - else - { - AddLog("Unknown command: '%s'\n", command_line); - } - } - - static int TextEditCallbackStub(ImGuiTextEditCallbackData* data) - { - ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; - return console->TextEditCallback(data); - } - - int TextEditCallback(ImGuiTextEditCallbackData* data) - { - //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); - switch (data->EventFlag) - { - case ImGuiInputTextFlags_CallbackCompletion: - { - // Example of TEXT COMPLETION - - // Locate beginning of current word - const char* word_end = data->Buf + data->CursorPos; - const char* word_start = word_end; - while (word_start > data->Buf) - { - const char c = word_start[-1]; - if (ImCharIsSpace(c) || c == ',' || c == ';') - break; - word_start--; - } - - // Build a list of candidates - ImVector<const char*> candidates; - for (size_t i = 0; i < Commands.size(); i++) - if (ImStrnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) - candidates.push_back(Commands[i]); - - if (candidates.size() == 0) - { - // No match - AddLog("No match for \"%.*s\"!\n", word_end-word_start, word_start); - } - else if (candidates.size() == 1) - { - // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing - data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); - data->InsertChars(data->CursorPos, candidates[0]); - data->InsertChars(data->CursorPos, " "); - } - else - { - // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" - int match_len = (int)(word_end - word_start); - for (;;) - { - int c = 0; - bool all_candidates_matches = true; - for (size_t i = 0; i < candidates.size() && all_candidates_matches; i++) - if (i == 0) - c = toupper(candidates[i][match_len]); - else if (c != toupper(candidates[i][match_len])) - all_candidates_matches = false; - if (!all_candidates_matches) - break; - match_len++; - } - - if (match_len > 0) - { - data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); - data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); - } - - // List matches - AddLog("Possible matches:\n"); - for (size_t i = 0; i < candidates.size(); i++) - AddLog("- %s\n", candidates[i]); - } - - break; - } - case ImGuiInputTextFlags_CallbackHistory: - { - // Example of HISTORY - const int prev_history_pos = HistoryPos; - if (data->EventKey == ImGuiKey_UpArrow) - { - if (HistoryPos == -1) - HistoryPos = (int)(History.size() - 1); - else if (HistoryPos > 0) - HistoryPos--; - } - else if (data->EventKey == ImGuiKey_DownArrow) - { - if (HistoryPos != -1) - if (++HistoryPos >= (int)History.size()) - HistoryPos = -1; - } - - // A better implementation would preserve the data on the current input line along with cursor position. - if (prev_history_pos != HistoryPos) - { - ImFormatString(data->Buf, data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : ""); - data->BufDirty = true; - data->CursorPos = data->SelectionStart = data->SelectionEnd = (int)strlen(data->Buf); - } - } - } - return 0; - } -}; - -static void ShowExampleAppConsole(bool* opened) -{ - static ExampleAppConsole console; - console.Run("Example: Console", opened); -} - -static void ShowExampleAppLongText(bool* opened) -{ - ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); - if (!ImGui::Begin("Example: Long text display", opened)) - { - ImGui::End(); - return; - } - - static int test_type = 0; - static ImGuiTextBuffer log; - static int lines = 0; - ImGui::Text("Printing unusually long amount of text."); - ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped"); - ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); - if (ImGui::Button("Clear")) { log.clear(); lines = 0; } - ImGui::SameLine(); - if (ImGui::Button("Add 1000 lines")) - { - for (int i = 0; i < 1000; i++) - log.append("%i The quick brown fox jumps over the lazy dog\n", lines+i); - lines += 1000; - } - ImGui::BeginChild("Log"); - switch (test_type) - { - case 0: - // Single call to TextUnformatted() with a big buffer - ImGui::TextUnformatted(log.begin(), log.end()); - break; - case 1: - // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the CalcListClipping() helper. - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); - int display_start, display_end; - ImGui::CalcListClipping(lines, ImGui::GetTextLineHeight(), &display_start, &display_end); - ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (display_start) * ImGui::GetTextLineHeight()); - for (int i = display_start; i < display_end; i++) - ImGui::Text("%i The quick brown fox jumps over the lazy dog\n", i); - ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (lines - display_end) * ImGui::GetTextLineHeight()); - ImGui::PopStyleVar(); - break; - case 2: - // Multiple calls to Text(), not clipped - ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); - for (int i = 0; i < lines; i++) - ImGui::Text("%i The quick brown fox jumps over the lazy dog\n", i); - ImGui::PopStyleVar(); - break; - } - ImGui::EndChild(); ImGui::End(); } -// End of Sample code -#endif - -//----------------------------------------------------------------------------- -// FONT DATA -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// ProggyClean.ttf -// Copyright (c) 2004, 2005 Tristan Grimmer -// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) -// Download and more information at http://upperbounds.net -//----------------------------------------------------------------------------- -// Compressed with stb_compress() then converted to a C array. -// Decompressor from stb.h (public domain) by Sean Barrett -// https://github.com/nothings/stb/blob/master/stb.h -//----------------------------------------------------------------------------- - -static unsigned int stb_decompress_length(unsigned char *input) -{ - return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; -} - -static unsigned char *stb__barrier, *stb__barrier2, *stb__barrier3, *stb__barrier4; - -static unsigned char *stb__dout; -static void stb__match(unsigned char *data, unsigned int length) -{ - // INVERSE of memmove... write each byte before copying the next... - IM_ASSERT (stb__dout + length <= stb__barrier); - if (stb__dout + length > stb__barrier) { stb__dout += length; return; } - if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; } - while (length--) *stb__dout++ = *data++; -} - -static void stb__lit(unsigned char *data, unsigned int length) -{ - IM_ASSERT (stb__dout + length <= stb__barrier); - if (stb__dout + length > stb__barrier) { stb__dout += length; return; } - if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; } - memcpy(stb__dout, data, length); - stb__dout += length; -} - -#define stb__in2(x) ((i[x] << 8) + i[(x)+1]) -#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) -#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) - -static unsigned char *stb_decompress_token(unsigned char *i) -{ - if (*i >= 0x20) { // use fewer if's for cases that expand small - if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; - else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; - else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); - } else { // more ifs for cases that expand large, since overhead is amortized - if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; - else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; - else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); - else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); - else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; - else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; - } - return i; -} - -static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) -{ - const unsigned long ADLER_MOD = 65521; - unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; - unsigned long blocklen, i; - - blocklen = buflen % 5552; - while (buflen) { - for (i=0; i + 7 < blocklen; i += 8) { - s1 += buffer[0], s2 += s1; - s1 += buffer[1], s2 += s1; - s1 += buffer[2], s2 += s1; - s1 += buffer[3], s2 += s1; - s1 += buffer[4], s2 += s1; - s1 += buffer[5], s2 += s1; - s1 += buffer[6], s2 += s1; - s1 += buffer[7], s2 += s1; - - buffer += 8; - } - - for (; i < blocklen; ++i) - s1 += *buffer++, s2 += s1; - - s1 %= ADLER_MOD, s2 %= ADLER_MOD; - buflen -= blocklen; - blocklen = 5552; - } - return (unsigned int)(s2 << 16) + (unsigned int)s1; -} - -static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length) -{ - unsigned int olen; - if (stb__in4(0) != 0x57bC0000) return 0; - if (stb__in4(4) != 0) return 0; // error! stream is > 4GB - olen = stb_decompress_length(i); - stb__barrier2 = i; - stb__barrier3 = i+length; - stb__barrier = output + olen; - stb__barrier4 = output; - i += 16; - - stb__dout = output; - for (;;) { - unsigned char *old_i = i; - i = stb_decompress_token(i); - if (i == old_i) { - if (*i == 0x05 && i[1] == 0xfa) { - IM_ASSERT(stb__dout == output + olen); - if (stb__dout != output + olen) return 0; - if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) - return 0; - return olen; - } else { - IM_ASSERT(0); /* NOTREACHED */ - return 0; - } - } - IM_ASSERT(stb__dout <= output + olen); - if (stb__dout > output + olen) - return 0; - } -} - -static const unsigned int proggy_clean_ttf_compressed_size = 9583; -static const unsigned int proggy_clean_ttf_compressed_data[9584/4] = -{ - 0x0000bc57, 0x00000000, 0xf8a00000, 0x00000400, 0x00010037, 0x000c0000, 0x00030080, 0x2f534f40, 0x74eb8832, 0x01000090, 0x2c158248, 0x616d634e, - 0x23120270, 0x03000075, 0x241382a0, 0x74766352, 0x82178220, 0xfc042102, 0x02380482, 0x66796c67, 0x5689af12, 0x04070000, 0x80920000, 0x64616568, - 0xd36691d7, 0xcc201b82, 0x36210382, 0x27108268, 0xc3014208, 0x04010000, 0x243b0f82, 0x78746d68, 0x807e008a, 0x98010000, 0x06020000, 0x61636f6c, - 0xd8b0738c, 0x82050000, 0x0402291e, 0x7078616d, 0xda00ae01, 0x28201f82, 0x202c1082, 0x656d616e, 0x96bb5925, 0x84990000, 0x9e2c1382, 0x74736f70, - 0xef83aca6, 0x249b0000, 0xd22c3382, 0x70657270, 0x12010269, 0xf4040000, 0x08202f82, 0x012ecb84, 0x553c0000, 0x0f5fd5e9, 0x0300f53c, 0x00830008, - 0x7767b722, 0x002b3f82, 0xa692bd00, 0xfe0000d7, 0x83800380, 0x21f1826f, 0x00850002, 0x41820120, 0x40fec026, 0x80030000, 0x05821083, 0x07830120, - 0x0221038a, 0x24118200, 0x90000101, 0x82798200, 0x00022617, 0x00400008, 0x2009820a, 0x82098276, 0x82002006, 0x9001213b, 0x0223c883, 0x828a02bc, - 0x858f2010, 0xc5012507, 0x00023200, 0x04210083, 0x91058309, 0x6c412b03, 0x40007374, 0xac200000, 0x00830008, 0x01000523, 0x834d8380, 0x80032103, - 0x012101bf, 0x23b88280, 0x00800000, 0x0b830382, 0x07820120, 0x83800021, 0x88012001, 0x84002009, 0x2005870f, 0x870d8301, 0x2023901b, 0x83199501, - 0x82002015, 0x84802000, 0x84238267, 0x88002027, 0x8561882d, 0x21058211, 0x13880000, 0x01800022, 0x05850d85, 0x0f828020, 0x03208384, 0x03200582, - 0x47901b84, 0x1b850020, 0x1f821d82, 0x3f831d88, 0x3f410383, 0x84058405, 0x210982cd, 0x09830000, 0x03207789, 0xf38a1384, 0x01203782, 0x13872384, - 0x0b88c983, 0x0d898f84, 0x00202982, 0x23900383, 0x87008021, 0x83df8301, 0x86118d03, 0x863f880d, 0x8f35880f, 0x2160820f, 0x04830300, 0x1c220382, - 0x05820100, 0x4c000022, 0x09831182, 0x04001c24, 0x11823000, 0x0800082e, 0x00000200, 0xff007f00, 0xffffac20, 0x00220982, 0x09848100, 0xdf216682, - 0x843586d5, 0x06012116, 0x04400684, 0xa58120d7, 0x00b127d8, 0x01b88d01, 0x2d8685ff, 0xc100c621, 0xf4be0801, 0x9e011c01, 0x88021402, 0x1403fc02, - 0x9c035803, 0x1404de03, 0x50043204, 0xa2046204, 0x66051605, 0x1206bc05, 0xd6067406, 0x7e073807, 0x4e08ec07, 0x96086c08, 0x1009d008, 0x88094a09, - 0x800a160a, 0x560b040b, 0x2e0cc80b, 0xea0c820c, 0xa40d5e0d, 0x500eea0d, 0x280f960e, 0x1210b00f, 0xe0107410, 0xb6115211, 0x6e120412, 0x4c13c412, - 0xf613ac13, 0xae145814, 0x4015ea14, 0xa6158015, 0x1216b815, 0xc6167e16, 0x8e173417, 0x5618e017, 0xee18ba18, 0x96193619, 0x481ad419, 0xf01a9c1a, - 0xc81b5c1b, 0x4c1c041c, 0xea1c961c, 0x921d2a1d, 0x401ed21d, 0xe01e8e1e, 0x761f241f, 0xa61fa61f, 0x01821020, 0x8a202e34, 0xc820b220, 0x74211421, - 0xee219821, 0x86226222, 0x01820c23, 0x83238021, 0x23983c01, 0x24d823b0, 0x244a2400, 0x24902468, 0x250625ae, 0x25822560, 0x26f825f8, 0x82aa2658, - 0xd8be0801, 0x9a274027, 0x68280a28, 0x0e29a828, 0xb8292029, 0x362af829, 0x602a602a, 0x2a2b022b, 0xac2b5e2b, 0x202ce62b, 0x9a2c342c, 0x5c2d282d, - 0xaa2d782d, 0x262ee82d, 0x262fa62e, 0xf42fb62f, 0xc8305e30, 0xb4313e31, 0x9e321e32, 0x82331e33, 0x5c34ee33, 0x3a35ce34, 0xd4358635, 0x72362636, - 0x7637e636, 0x3a38d837, 0x1239a638, 0xae397439, 0x9a3a2e3a, 0x7c3b063b, 0x3a3ce83b, 0x223d963c, 0xec3d863d, 0xc63e563e, 0x9a3f2a3f, 0x6a401240, - 0x3641d040, 0x0842a241, 0x7a424042, 0xf042b842, 0xcc436243, 0x8a442a44, 0x5845ee44, 0xe245b645, 0xb4465446, 0x7a471447, 0x5448da47, 0x4049c648, - 0x15462400, 0x034d0808, 0x0b000700, 0x13000f00, 0x1b001700, 0x23001f00, 0x2b002700, 0x33002f00, 0x3b003700, 0x43003f00, 0x4b004700, 0x53004f00, - 0x5b005700, 0x63005f00, 0x6b006700, 0x73006f00, 0x7b007700, 0x83007f00, 0x8b008700, 0x00008f00, 0x15333511, 0x20039631, 0x20178205, 0xd3038221, - 0x20739707, 0x25008580, 0x028080fc, 0x05be8080, 0x04204a85, 0x05ce0685, 0x0107002a, 0x02000080, 0x00000400, 0x250d8b41, 0x33350100, 0x03920715, - 0x13820320, 0x858d0120, 0x0e8d0320, 0xff260d83, 0x00808000, 0x54820106, 0x04800223, 0x845b8c80, 0x41332059, 0x078b068f, 0x82000121, 0x82fe2039, - 0x84802003, 0x83042004, 0x23598a0e, 0x00180000, 0x03210082, 0x42ab9080, 0x73942137, 0x2013bb41, 0x8f978205, 0x2027a39b, 0x20b68801, 0x84b286fd, - 0x91c88407, 0x41032011, 0x11a51130, 0x15000027, 0x80ff8000, 0x11af4103, 0x841b0341, 0x8bd983fd, 0x9be99bc9, 0x8343831b, 0x21f1821f, 0xb58300ff, - 0x0f84e889, 0xf78a0484, 0x8000ff22, 0x0020eeb3, 0x14200082, 0x2130ef41, 0xeb431300, 0x4133200a, 0xd7410ecb, 0x9a07200b, 0x2027871b, 0x21238221, - 0xe7828080, 0xe784fd20, 0xe8848020, 0xfe808022, 0x08880d85, 0xba41fd20, 0x82248205, 0x85eab02a, 0x008022e7, 0x2cd74200, 0x44010021, 0xd34406eb, - 0x44312013, 0xcf8b0eef, 0x0d422f8b, 0x82332007, 0x0001212f, 0x8023cf82, 0x83000180, 0x820583de, 0x830682d4, 0x820020d4, 0x82dc850a, 0x20e282e9, - 0xb2ff85fe, 0x010327e9, 0x02000380, 0x0f440400, 0x0c634407, 0x68825982, 0x85048021, 0x260a825d, 0x010b0000, 0x4400ff00, 0x2746103f, 0x08d74209, - 0x4d440720, 0x0eaf4406, 0xc3441d20, 0x23078406, 0xff800002, 0x04845b83, 0x8d05b241, 0x1781436f, 0x6b8c87a5, 0x1521878e, 0x06474505, 0x01210783, - 0x84688c00, 0x8904828e, 0x441e8cf7, 0x0b270cff, 0x80008000, 0x45030003, 0xfb430fab, 0x080f4107, 0x410bf942, 0xd34307e5, 0x070d4207, 0x80800123, - 0x205d85fe, 0x849183fe, 0x20128404, 0x82809702, 0x00002217, 0x41839a09, 0x6b4408cf, 0x0733440f, 0x3b460720, 0x82798707, 0x97802052, 0x0000296f, - 0xff800004, 0x01800100, 0x0021ef89, 0x0a914625, 0x410a4d41, 0x00250ed4, 0x00050000, 0x056d4280, 0x210a7b46, 0x21481300, 0x46ed8512, 0x00210bd1, - 0x89718202, 0x21738877, 0x2b850001, 0x00220582, 0x87450a00, 0x0ddb4606, 0x41079b42, 0x9d420c09, 0x0b09420b, 0x8d820720, 0x9742fc84, 0x42098909, - 0x00241e0f, 0x00800014, 0x0b47da82, 0x0833442a, 0x49078d41, 0x2f450f13, 0x42278f17, 0x01200751, 0x22063742, 0x44808001, 0x20450519, 0x88068906, - 0x83fe2019, 0x4203202a, 0x1a941a58, 0x00820020, 0xe7a40e20, 0x420ce146, 0x854307e9, 0x0fcb4713, 0xff20a182, 0xfe209b82, 0x0c867f8b, 0x0021aea4, - 0x219fa40f, 0x7d41003b, 0x07194214, 0xbf440520, 0x071d4206, 0x6941a590, 0x80802309, 0x028900ff, 0xa9a4b685, 0xc5808021, 0x449b82ab, 0x152007eb, - 0x42134d46, 0x61440a15, 0x051e4208, 0x222b0442, 0x47001100, 0xfd412913, 0x17194714, 0x410f5b41, 0x02220773, 0x09428080, 0x21a98208, 0xd4420001, - 0x481c840d, 0x00232bc9, 0x42120000, 0xe74c261b, 0x149d4405, 0x07209d87, 0x410db944, 0x14421c81, 0x42fd2005, 0x80410bd2, 0x203d8531, 0x06874100, - 0x48256f4a, 0xcb420c95, 0x13934113, 0x44075d44, 0x044c0855, 0x00ff2105, 0xfe228185, 0x45448000, 0x22c5b508, 0x410c0000, 0x7b412087, 0x1bb74514, - 0x32429c85, 0x0a574805, 0x21208943, 0x8ba01300, 0x440dfb4e, 0x77431437, 0x245b4113, 0x200fb145, 0x41108ffe, 0x80203562, 0x00200082, 0x46362b42, - 0x1742178d, 0x4527830f, 0x0f830b2f, 0x4a138146, 0x802409a1, 0xfe8000ff, 0x94419982, 0x09294320, 0x04000022, 0x49050f4f, 0xcb470a63, 0x48032008, - 0x2b48067b, 0x85022008, 0x82638338, 0x00002209, 0x05af4806, 0x900e9f49, 0x84c5873f, 0x214285bd, 0x064900ff, 0x0c894607, 0x00000023, 0x4903820a, - 0x714319f3, 0x0749410c, 0x8a07a145, 0x02152507, 0xfe808000, 0x74490386, 0x8080211b, 0x0c276f82, 0x00018000, 0x48028003, 0x2b2315db, 0x43002f00, - 0x6f82142f, 0x44011521, 0x93510da7, 0x20e68508, 0x06494d80, 0x8e838020, 0x06821286, 0x124bff20, 0x25f3830c, 0x03800080, 0xe74a0380, 0x207b8715, - 0x876b861d, 0x4a152007, 0x07870775, 0xf6876086, 0x8417674a, 0x0a0021f2, 0x431c9743, 0x8d421485, 0x200b830b, 0x06474d03, 0x71828020, 0x04510120, - 0x42da8606, 0x1f831882, 0x001a0022, 0xff4d0082, 0x0b0f532c, 0x0d449b94, 0x4e312007, 0x074f12e7, 0x0bf3490b, 0xbb412120, 0x413f820a, 0xef490857, - 0x80002313, 0xe2830001, 0x6441fc20, 0x8b802006, 0x00012108, 0xfd201582, 0x492c9b48, 0x802014ff, 0x51084347, 0x0f4327f3, 0x17bf4a14, 0x201b7944, - 0x06964201, 0x134ffe20, 0x20d6830b, 0x25d78280, 0xfd800002, 0x05888000, 0x9318dc41, 0x21d282d4, 0xdb481800, 0x0dff542a, 0x45107743, 0xe14813f5, - 0x0f034113, 0x83135d45, 0x47b28437, 0xe4510e73, 0x21f58e06, 0x2b8400fd, 0x1041fcac, 0x08db4b0b, 0x421fdb41, 0xdf4b18df, 0x011d210a, 0x420af350, - 0x6e8308af, 0xac85cb86, 0x1e461082, 0x82b7a407, 0x411420a3, 0xa34130ab, 0x178f4124, 0x41139741, 0x86410d93, 0x82118511, 0x057243d8, 0x8941d9a4, - 0x3093480c, 0x4a13474f, 0xfb5016a9, 0x07ad4108, 0x4a0f9d42, 0xfe200fad, 0x4708aa41, 0x83482dba, 0x288f4d06, 0xb398c3bb, 0x44267b41, 0xb34439d7, - 0x0755410f, 0x200ebb45, 0x0f5f4215, 0x20191343, 0x06df5301, 0xf04c0220, 0x2ba64d07, 0x82050841, 0x430020ce, 0xa78f3627, 0x5213ff42, 0x2f970bc1, - 0x4305ab55, 0xa084111b, 0x450bac45, 0x5f4238b8, 0x010c2106, 0x0220ed82, 0x441bb344, 0x875010af, 0x0737480f, 0x490c5747, 0x0c840c03, 0x4c204b42, - 0x8ba905d7, 0x8b948793, 0x510c0c51, 0xfb4b24b9, 0x1b174107, 0x5709d74c, 0xd1410ca5, 0x079d480f, 0x201ff541, 0x06804780, 0x7d520120, 0x80002205, - 0x20a983fe, 0x47bb83fe, 0x1b8409b4, 0x81580220, 0x4e00202c, 0x4f41282f, 0x0eab4f17, 0x57471520, 0x0e0f4808, 0x8221e041, 0x3e1b4a8b, 0x4407175d, - 0x1b4b071f, 0x4a0f8b07, 0x174a0703, 0x0ba5411b, 0x430fb141, 0x0120057b, 0xfc20dd82, 0x4a056047, 0xf4850c0c, 0x01221982, 0x02828000, 0x1a5d088b, - 0x20094108, 0x8c0e3941, 0x4900200e, 0x7744434f, 0x200b870b, 0x0e4b5a33, 0x2b41f78b, 0x8b138307, 0x0b9f450b, 0x2406f741, 0xfd808001, 0x09475a00, - 0x84000121, 0x5980200e, 0x85450e5d, 0x832c8206, 0x4106831e, 0x00213814, 0x28b34810, 0x410c2f4b, 0x5f4a13d7, 0x0b2b4113, 0x6e43a883, 0x11174b05, - 0x4b066a45, 0xcc470541, 0x5000202b, 0xcb472f4b, 0x44b59f0f, 0xc5430b5b, 0x0d654907, 0x21065544, 0xd6828080, 0xfe201982, 0x8230ec4a, 0x120025c2, - 0x80ff8000, 0x4128d74d, 0x3320408b, 0x410a9f50, 0xdb822793, 0x822bd454, 0x61134b2e, 0x410b214a, 0xad4117c9, 0x0001211f, 0x4206854f, 0x4b430596, - 0x06bb5530, 0x2025cf46, 0x0ddd5747, 0x500ea349, 0x0f840fa7, 0x5213c153, 0x634e08d1, 0x0bbe4809, 0x59316e4d, 0x5b50053f, 0x203f6323, 0x5117eb46, - 0x94450a63, 0x246e410a, 0x63410020, 0x0bdb5f2f, 0x4233ab44, 0x39480757, 0x112d4a07, 0x7241118f, 0x000e2132, 0x9f286f41, 0x0f8762c3, 0x33350723, - 0x094e6415, 0x2010925f, 0x067252fe, 0xd0438020, 0x63a68225, 0x11203a4f, 0x480e6360, 0x5748131f, 0x079b521f, 0x200e2f43, 0x864b8315, 0x113348e7, - 0x85084e48, 0x06855008, 0x5880fd21, 0x7c420925, 0x0c414824, 0x37470c86, 0x1b8b422b, 0x5b0a8755, 0x23410c21, 0x0b83420b, 0x5a082047, 0xf482067f, - 0xa80b4c47, 0x0c0021cf, 0x20207b42, 0x0fb74100, 0x420b8744, 0xeb43076f, 0x0f6f420b, 0x4261fe20, 0x439aa00c, 0x215034e3, 0x0ff9570f, 0x4b1f2d5d, - 0x2d5d0c6f, 0x09634d0b, 0x1f51b8a0, 0x620f200c, 0xaf681e87, 0x24f94d07, 0x4e0f4945, 0xfe200c05, 0x22139742, 0x57048080, 0x23950c20, 0x97601585, - 0x4813201f, 0xad620523, 0x200f8f0f, 0x9e638f15, 0x00002181, 0x41342341, 0x0f930f0b, 0x210b4b62, 0x978f0001, 0xfe200f84, 0x8425c863, 0x2704822b, - 0x80000a00, 0x00038001, 0x610e9768, 0x834514bb, 0x0bc3430f, 0x2107e357, 0x80848080, 0x4400fe21, 0x2e410983, 0x00002a1a, 0x00000700, 0x800380ff, - 0x0fdf5800, 0x59150021, 0xd142163d, 0x0c02410c, 0x01020025, 0x65800300, 0x00240853, 0x1d333501, 0x15220382, 0x35420001, 0x44002008, 0x376406d7, - 0x096f6b19, 0x480bc142, 0x8f4908a7, 0x211f8b1f, 0x9e830001, 0x0584fe20, 0x4180fd21, 0x11850910, 0x8d198259, 0x000021d4, 0x5a08275d, 0x275d1983, - 0x06d9420e, 0x9f08b36a, 0x0f7d47b5, 0x8d8a2f8b, 0x4c0e0b57, 0xe7410e17, 0x42d18c1a, 0xb351087a, 0x1ac36505, 0x4b4a2f20, 0x0b9f450d, 0x430beb53, - 0xa7881015, 0xa5826a83, 0x80200f82, 0x86185a65, 0x4100208e, 0x176c3367, 0x0fe7650b, 0x4a17ad4b, 0x0f4217ed, 0x112e4206, 0x41113a42, 0xf7423169, - 0x0cb34737, 0x560f8b46, 0xa75407e5, 0x5f01200f, 0x31590c48, 0x80802106, 0x42268841, 0x0020091e, 0x4207ef64, 0x69461df7, 0x138d4114, 0x820f5145, - 0x53802090, 0xff200529, 0xb944b183, 0x417e8505, 0x00202561, 0x15210082, 0x42378200, 0x9b431cc3, 0x004f220d, 0x0dd54253, 0x4213f149, 0x7d41133b, - 0x42c9870b, 0x802010f9, 0x420b2c42, 0x8f441138, 0x267c4408, 0x600cb743, 0x8f4109d3, 0x05ab701d, 0x83440020, 0x3521223f, 0x0b794733, 0xfb62fe20, - 0x4afd2010, 0xaf410ae7, 0x25ce8525, 0x01080000, 0x7b6b0000, 0x0973710b, 0x82010021, 0x49038375, 0x33420767, 0x052c4212, 0x58464b85, 0x41fe2005, - 0x50440c27, 0x000c2209, 0x1cb36b80, 0x9b06df44, 0x0f93566f, 0x52830220, 0xfe216e8d, 0x200f8200, 0x0fb86704, 0xb057238d, 0x050b5305, 0x7217eb47, - 0xbd410b6b, 0x0f214610, 0x871f9956, 0x1e91567e, 0x2029b741, 0x20008200, 0x18b7410a, 0x27002322, 0x41095543, 0x0f8f0fb3, 0x41000121, 0x889d111c, - 0x14207b82, 0x00200382, 0x73188761, 0x475013a7, 0x6e33200c, 0x234e0ea3, 0x9b138313, 0x08e54d17, 0x9711094e, 0x2ee74311, 0x4908875e, 0xd75d1f1f, - 0x19ab5238, 0xa2084d48, 0x63a7a9b3, 0x55450b83, 0x0fd74213, 0x440d814c, 0x4f481673, 0x05714323, 0x13000022, 0x412e1f46, 0xdf493459, 0x21c7550f, - 0x8408215f, 0x201d49cb, 0xb1103043, 0x0f0d65d7, 0x452b8d41, 0x594b0f8d, 0x0b004605, 0xb215eb46, 0x000a24d7, 0x47000080, 0x002118cf, 0x06436413, - 0x420bd750, 0x2b500743, 0x076a470c, 0x4105c050, 0xd942053f, 0x0d00211a, 0x5f44779c, 0x0ce94805, 0x51558186, 0x14a54c0b, 0x49082b41, 0x0a4b0888, - 0x8080261f, 0x0d000000, 0x20048201, 0x1deb6a03, 0x420cb372, 0x07201783, 0x4306854d, 0x8b830c59, 0x59093c74, 0x0020250f, 0x67070f4a, 0x2341160b, - 0x00372105, 0x431c515d, 0x554e17ef, 0x0e5d6b05, 0x41115442, 0xb74a1ac1, 0x2243420a, 0x5b4f878f, 0x7507200f, 0x384b086f, 0x09d45409, 0x0020869a, - 0x12200082, 0xab460382, 0x10075329, 0x54138346, 0xaf540fbf, 0x1ea75413, 0x9a0c9e54, 0x0f6b44c1, 0x41000021, 0x47412a4f, 0x07374907, 0x5310bf76, - 0xff2009b4, 0x9a09a64c, 0x8200208d, 0x34c34500, 0x970fe141, 0x1fd74b0f, 0x440a3850, 0x206411f0, 0x27934609, 0x470c5d41, 0x555c2947, 0x1787540f, - 0x6e0f234e, 0x7d540a1b, 0x1d736b08, 0x0026a088, 0x80000e00, 0x9b5200ff, 0x08ef4318, 0x450bff77, 0x1d4d0b83, 0x081f7006, 0xcb691b86, 0x4b022008, - 0xc34b0b33, 0x1d0d4a0c, 0x8025a188, 0x0b000000, 0x52a38201, 0xbf7d0873, 0x0c234511, 0x8f0f894a, 0x4101200f, 0x0c880c9d, 0x2b418ea1, 0x06c74128, - 0x66181341, 0x7b4c0bb9, 0x0c06630b, 0xfe200c87, 0x9ba10882, 0x27091765, 0x01000008, 0x02800380, 0x48113f4e, 0x29430cf5, 0x09a75a0b, 0x31618020, - 0x6d802009, 0x61840e33, 0x8208bf51, 0x0c637d61, 0x7f092379, 0x4f470f4b, 0x1797510c, 0x46076157, 0xf5500fdf, 0x0f616910, 0x1171fe20, 0x82802006, - 0x08696908, 0x41127a4c, 0x3f4a15f3, 0x01042607, 0x0200ff00, 0x1cf77700, 0xff204185, 0x00235b8d, 0x43100000, 0x3b22243f, 0x3b4d3f00, 0x0b937709, - 0xad42f18f, 0x0b1f420f, 0x51084b43, 0x8020104a, 0xb557ff83, 0x052b7f2a, 0x0280ff22, 0x250beb78, 0x00170013, 0xbf6d2500, 0x07db760e, 0x410e2b7f, - 0x00230e4f, 0x49030000, 0x0582055b, 0x07000326, 0x00000b00, 0x580bcd46, 0x00200cdd, 0x57078749, 0x8749160f, 0x0f994f0a, 0x41134761, 0x01200b31, - 0xeb796883, 0x0b41500b, 0x0e90b38e, 0x202e7b51, 0x05d95801, 0x41080570, 0x1d530fc9, 0x0b937a0f, 0xaf8eb387, 0xf743b98f, 0x07c74227, 0x80000523, - 0x0fcb4503, 0x430ca37b, 0x7782077f, 0x8d0a9947, 0x08af4666, 0xeb798020, 0x6459881e, 0xc3740bbf, 0x0feb6f0b, 0x20072748, 0x052b6102, 0x435e0584, - 0x7d088308, 0x03200afd, 0x92109e41, 0x28aa8210, 0x80001500, 0x80030000, 0x0fdb5805, 0x209f4018, 0xa7418d87, 0x0aa3440f, 0x20314961, 0x073a52ff, - 0x6108505d, 0x43181051, 0x00223457, 0xe7820500, 0x50028021, 0x81410d33, 0x063d7108, 0xdb41af84, 0x4d888205, 0x00201198, 0x463d835f, 0x152106d7, - 0x0a355a33, 0x6917614e, 0x75411f4d, 0x184b8b07, 0x1809c344, 0x21091640, 0x0b828000, 0x42808021, 0x26790519, 0x86058605, 0x2428422d, 0x22123b42, - 0x42000080, 0xf587513b, 0x7813677b, 0xaf4d139f, 0x00ff210c, 0x5e0a1d57, 0x3b421546, 0x01032736, 0x02000380, 0x41180480, 0x2f420f07, 0x0c624807, - 0x00000025, 0x18000103, 0x83153741, 0x430120c3, 0x042106b2, 0x088d4d00, 0x2f830620, 0x1810434a, 0x18140345, 0x8507fb41, 0x5ee582ea, 0x0023116c, - 0x8d000600, 0x053b56af, 0xa6554fa2, 0x0d704608, 0x40180d20, 0x47181a43, 0xd37b07ff, 0x0b79500c, 0x420fd745, 0x47450bd9, 0x8471830a, 0x095a777e, - 0x84137542, 0x82002013, 0x2f401800, 0x0007213b, 0x4405e349, 0x0d550ff3, 0x16254c0c, 0x820ffe4a, 0x0400218a, 0x89066f41, 0x106b414f, 0xc84d0120, - 0x80802206, 0x0c9a4b03, 0x00100025, 0x68000200, 0x9d8c2473, 0x44134344, 0xf36a0f33, 0x4678860f, 0x1b440a25, 0x41988c0a, 0x80201879, 0x43079b5e, - 0x4a18080b, 0x0341190b, 0x1259530c, 0x43251552, 0x908205c8, 0x0cac4018, 0x86000421, 0x0e504aa2, 0x0020b891, 0xfb450082, 0x51132014, 0x8f5205f3, - 0x35052108, 0x8505cb59, 0x0f6d4f70, 0x82150021, 0x29af5047, 0x4f004b24, 0x75795300, 0x1b595709, 0x460b6742, 0xbf4b0f0d, 0x5743870b, 0xcb6d1461, - 0x08f64505, 0x4e05ab6c, 0x334126c3, 0x0bcb6b0d, 0x1811034d, 0x4111ef4b, 0x814f1ce5, 0x20af8227, 0x07fd7b80, 0x41188e84, 0xef410f33, 0x80802429, - 0x410d0000, 0xa34205ab, 0x76b7881c, 0xff500b89, 0x0741430f, 0x20086f4a, 0x209d8200, 0x234c18fd, 0x05d4670a, 0x4509af51, 0x9642078d, 0x189e831d, - 0x7c1cc74b, 0xcd4c07b9, 0x0e7c440f, 0x8b7b0320, 0x21108210, 0xc76c8080, 0x03002106, 0x6b23bf41, 0xc549060b, 0x7946180b, 0x0ff7530f, 0x17ad4618, - 0x200ecd45, 0x208c83fd, 0x5e0488fe, 0x032009c6, 0x420d044e, 0x0d8f0d7f, 0x00820020, 0x18001021, 0x6d273b45, 0xfd4c0c93, 0xcf451813, 0x0fe5450f, - 0x5a47c382, 0x820a8b0a, 0x282b4998, 0x410a8b5b, 0x4b232583, 0x54004f00, 0x978f0ce3, 0x500f1944, 0xa95f1709, 0x0280220b, 0x05ba7080, 0xa1530682, - 0x06324c13, 0x91412582, 0x05536e2c, 0x63431020, 0x0f434706, 0x8c11374c, 0x176143d7, 0x4d0f454c, 0xd3680bed, 0x0bee4d17, 0x212b9a41, 0x0f530a00, - 0x140d531c, 0x43139143, 0x95610e8d, 0x0f094415, 0x4205fb56, 0x1b4205cf, 0x17015225, 0x5e0c477f, 0xaf6e0aeb, 0x0ff36218, 0x04849a84, 0x0a454218, - 0x9c430420, 0x23c6822b, 0x04000102, 0x45091b4b, 0xf05f0955, 0x82802007, 0x421c2023, 0x5218282b, 0x7b53173f, 0x0fe7480c, 0x74173b7f, 0x47751317, - 0x634d1807, 0x0f6f430f, 0x24086547, 0xfc808002, 0x0b3c7f80, 0x10840120, 0x188d1282, 0x20096b43, 0x0fc24403, 0x00260faf, 0x0180000b, 0x3f500280, - 0x18002019, 0x450b4941, 0xf3530fb9, 0x18002010, 0x8208a551, 0x06234d56, 0xcb58a39b, 0xc3421805, 0x1313461e, 0x0f855018, 0xd34b0120, 0x6cfe2008, - 0x574f0885, 0x09204114, 0x07000029, 0x00008000, 0x44028002, 0x01420f57, 0x10c95c10, 0x11184c18, 0x80221185, 0x7f421e00, 0x00732240, 0x09cd4977, - 0x6d0b2b42, 0x4f180f8f, 0x8f5a0bcb, 0x9b0f830f, 0x0fb9411f, 0x230b5756, 0x00fd8080, 0x82060745, 0x000121d5, 0x8e0fb277, 0x4a8d4211, 0x24061c53, - 0x04000007, 0x12275280, 0x430c954c, 0x80201545, 0x200f764f, 0x20008200, 0x20ce8308, 0x09534f02, 0x660edf64, 0x73731771, 0xe7411807, 0x20a2820c, - 0x13b64404, 0x8f5d6682, 0x1d6b4508, 0x0cff4d18, 0x3348c58f, 0x0fc34c07, 0x31558b84, 0x8398820f, 0x17514712, 0x240b0e46, 0x80000a00, 0x093b4502, - 0x420f9759, 0xa54c0bf1, 0x0f2b470c, 0x410d314b, 0x2584170c, 0x73b30020, 0xb55fe782, 0x204d8410, 0x08e043fe, 0x4f147e41, 0x022008ab, 0x4b055159, - 0x2950068f, 0x00022208, 0x48511880, 0x82002009, 0x00112300, 0x634dff00, 0x24415f27, 0x180f6d43, 0x4d0b5d45, 0x4d5f05ef, 0x01802317, 0x56188000, - 0xa7840807, 0xc6450220, 0x21ca8229, 0x4b781a00, 0x3359182c, 0x0cf3470f, 0x180bef46, 0x420b0354, 0xff470b07, 0x4515200a, 0x9758239b, 0x4a80200c, - 0xd2410a26, 0x05fb4a08, 0x4b05e241, 0x03200dc9, 0x92290941, 0x00002829, 0x00010900, 0x5b020001, 0x23201363, 0x460d776a, 0xef530fdb, 0x209a890c, - 0x13fc4302, 0x00008024, 0xc4820104, 0x08820220, 0x20086b5b, 0x18518700, 0x8408d349, 0x0da449a1, 0x00080024, 0x7b690280, 0x4c438b1a, 0x01220f63, - 0x4c878000, 0x5c149c53, 0xfb430868, 0x2f56181e, 0x0ccf7b1b, 0x0f075618, 0x2008e347, 0x14144104, 0x00207f83, 0x00207b82, 0x201adf47, 0x16c35a13, - 0x540fdf47, 0x802006c8, 0x5418f185, 0x29430995, 0x00002419, 0x58001600, 0x5720316f, 0x4d051542, 0x4b7b1b03, 0x138f4707, 0xb747b787, 0x4aab8213, - 0x058305fc, 0x20115759, 0x82128401, 0x0a0b44e8, 0x46800121, 0xe64210d0, 0x82129312, 0x4bffdffe, 0x3b41171b, 0x9b27870f, 0x808022ff, 0x085c68fe, - 0x41800021, 0x01410b20, 0x001a213a, 0x47480082, 0x11374e12, 0x56130b4c, 0xdf4b0c65, 0x0b0f590b, 0x0f574c18, 0x830feb4b, 0x075f480f, 0x480b4755, - 0x40490b73, 0x80012206, 0x09d74280, 0x80fe8022, 0x80210e86, 0x056643ff, 0x10820020, 0x420b2646, 0x0b58391a, 0xd74c1808, 0x078b4e22, 0x2007f55f, - 0x4b491807, 0x83802017, 0x65aa82a7, 0x3152099e, 0x068b7616, 0x9b431220, 0x09bb742c, 0x500e376c, 0x8342179b, 0x0a4d5d0f, 0x8020a883, 0x180cd349, - 0x2016bb4b, 0x14476004, 0x84136c43, 0x08cf7813, 0x4f4c0520, 0x156f420f, 0x20085f42, 0x6fd3be03, 0xd4d30803, 0xa7411420, 0x004b222c, 0x0d3b614f, - 0x3f702120, 0x1393410a, 0x8f132745, 0x47421827, 0x41e08209, 0xb05e2bb9, 0x18b7410c, 0x18082647, 0x4107a748, 0xeb8826bf, 0x0ca76018, 0x733ecb41, - 0xd0410d83, 0x43ebaf2a, 0x0420067f, 0x721dab4c, 0x472005bb, 0x4105d341, 0x334844cb, 0x20dba408, 0x47d6ac00, 0x034e3aef, 0x0f8f421b, 0x930f134d, - 0x3521231f, 0xb7421533, 0x42f5ad0a, 0x1e961eaa, 0x17000022, 0x4c367b50, 0x7d491001, 0x0bf5520f, 0x4c18fda7, 0xb8460c55, 0x83fe2005, 0x00fe25b9, - 0x80000180, 0x9e751085, 0x261b5c12, 0x82110341, 0x001123fb, 0x4518fe80, 0xf38c2753, 0x6d134979, 0x295107a7, 0xaf5f180f, 0x0fe3660c, 0x180b6079, - 0x2007bd5f, 0x9aab9103, 0x2f4d1811, 0x05002109, 0x44254746, 0x1d200787, 0x450bab75, 0x4f180f57, 0x4f181361, 0x3b831795, 0xeb4b0120, 0x0b734805, - 0x84078f48, 0x2e1b47bc, 0x00203383, 0xaf065f45, 0x831520d7, 0x130f51a7, 0x1797bf97, 0x2b47d783, 0x18fe2005, 0x4a18a44f, 0xa64d086d, 0x1ab0410d, - 0x6205a258, 0xdbab069f, 0x4f06f778, 0xa963081d, 0x133b670a, 0x8323d141, 0x13195b23, 0x530f5e70, 0xe5ad0824, 0x58001421, 0x1f472b4b, 0x47bf410c, - 0x82000121, 0x83fe20cb, 0x07424404, 0x68068243, 0xd7ad0d3d, 0x00010d26, 0x80020000, 0x4a1c6f43, 0x23681081, 0x10a14f13, 0x8a070e57, 0x430a848f, - 0x7372243e, 0x4397a205, 0xb56c1021, 0x43978f0f, 0x64180505, 0x99aa0ff2, 0x0e000022, 0x20223341, 0x094b4f37, 0x074a3320, 0x2639410a, 0xfe208e84, - 0x8b0e0048, 0x508020a3, 0x9e4308fe, 0x073f4115, 0xe3480420, 0x0c9b5f1b, 0x7c137743, 0x9a95185b, 0x6122b148, 0x979b08df, 0x0fe36c18, 0x48109358, - 0x23441375, 0x0ffd5c0b, 0x180fc746, 0x2011d157, 0x07e95702, 0x58180120, 0x18770ac3, 0x51032008, 0x7d4118e3, 0x80802315, 0x3b4c1900, 0xbb5a1830, - 0x0ceb6109, 0x5b0b3d42, 0x4f181369, 0x4f180b8d, 0x4f180f75, 0x355a1b81, 0x200d820d, 0x18e483fd, 0x4528854f, 0x89420846, 0x1321411f, 0x44086b60, - 0x07421d77, 0x107d4405, 0x4113fd41, 0x5a181bf1, 0x4f180db3, 0x8021128f, 0x20f68280, 0x44a882fe, 0x334d249a, 0x052f6109, 0x1520c3a7, 0xef4eb783, - 0x4ec39b1b, 0xc4c90ee7, 0x20060b4d, 0x256f4905, 0x4d0cf761, 0xcf9b1f13, 0xa213d74e, 0x0e1145d4, 0x50135b42, 0xcb4e398f, 0x20d79f27, 0x08865d80, - 0x186d5018, 0xa90f7142, 0x067342d7, 0x3f450420, 0x65002021, 0xe3560771, 0x24d38f23, 0x15333531, 0x0eb94d01, 0x451c9f41, 0x384322fb, 0x00092108, - 0x19af6b18, 0x6e0c6f5a, 0xbd770bfb, 0x22bb7718, 0x20090f57, 0x25e74204, 0x4207275a, 0xdb5408ef, 0x1769450f, 0x1b1b5518, 0x210b1f57, 0x5e4c8001, - 0x55012006, 0x802107f1, 0x0a306a80, 0x45808021, 0x0d850b88, 0x31744f18, 0x1808ec54, 0x2009575b, 0x45ffa505, 0x1b420c73, 0x180f9f0f, 0x4a0cf748, - 0x501805b2, 0x00210f40, 0x4d118f80, 0xd6823359, 0x072b5118, 0x314ad7aa, 0x8fc79f08, 0x45d78b1f, 0xfe20058f, 0x23325118, 0x7b54d9b5, 0x9fc38f46, - 0x10bb410f, 0x41077b42, 0xc1410faf, 0x27cf441d, 0x46051b4f, 0x04200683, 0x2121d344, 0x8f530043, 0x8fcf9f0e, 0x21df8c1f, 0x50188000, 0x5d180e52, - 0xfd201710, 0x4405c341, 0xd68528e3, 0x20071f6b, 0x1b734305, 0x6b080957, 0x7d422b1f, 0x67002006, 0x7f8317b1, 0x2024cb48, 0x08676e00, 0x8749a39b, - 0x18132006, 0x410a6370, 0x8f490b47, 0x7e1f8f13, 0x551805c3, 0x4c180915, 0xfe200e2f, 0x244d5d18, 0x270bcf44, 0xff000019, 0x04800380, 0x5f253342, - 0xff520df7, 0x13274c18, 0x5542dd93, 0x0776181b, 0xf94a1808, 0x084a4c0c, 0x4308ea5b, 0xde831150, 0x7900fd21, 0x00492c1e, 0x060f4510, 0x17410020, - 0x0ce74526, 0x6206b341, 0x1f561083, 0x9d6c181b, 0x08a0500e, 0x112e4118, 0x60000421, 0xbf901202, 0x4408e241, 0xc7ab0513, 0xb40f0950, 0x055943c7, - 0x4f18ff20, 0xc9ae1cad, 0x32b34f18, 0x7a180120, 0x3d520a05, 0x53d1b40a, 0x80200813, 0x1b815018, 0x832bf86f, 0x67731847, 0x297f4308, 0x6418d54e, - 0x734213f7, 0x056b4b27, 0xdba5fe20, 0x1828aa4e, 0x2031a370, 0x06cb6101, 0x2040ad41, 0x07365300, 0x2558d985, 0x83fe200c, 0x0380211c, 0x542c4743, - 0x052006b7, 0x6021df45, 0x897b0707, 0x18d3c010, 0x20090e70, 0x1d5843ff, 0x540a0e44, 0x002126c5, 0x322f7416, 0x636a5720, 0x0f317409, 0x610fe159, - 0x294617e7, 0x08555213, 0x2006a75d, 0x6cec84fd, 0xfb5907be, 0x3a317405, 0x83808021, 0x180f20ea, 0x4626434a, 0x531818e3, 0xdb59172d, 0x0cbb460c, - 0x2013d859, 0x18b94502, 0x8f46188d, 0x77521842, 0x0a184e38, 0x9585fd20, 0x6a180684, 0xc64507e9, 0x51cbb230, 0xd3440cf3, 0x17ff6a0f, 0x450f5b42, - 0x276407c1, 0x4853180a, 0x21ccb010, 0xcf580013, 0x0c15442d, 0x410a1144, 0x1144359d, 0x5cfe2006, 0xa1410a43, 0x2bb64519, 0x2f5b7618, 0xb512b745, - 0x0cfd6fd1, 0x42089f59, 0xb8450c70, 0x0000232d, 0x50180900, 0xb9491ae3, 0x0fc37610, 0x01210f83, 0x0f3b4100, 0xa01b2742, 0x0ccd426f, 0x6e8f6f94, - 0x9c808021, 0xc7511870, 0x17c74b08, 0x9b147542, 0x44fe2079, 0xd5480c7e, 0x95ef861d, 0x101b597b, 0xf5417594, 0x9f471808, 0x86868d0e, 0x3733491c, - 0x690f4d6d, 0x43440b83, 0x1ba94c0b, 0x660cd16b, 0x802008ae, 0x74126448, 0xcb4f38a3, 0x2cb74b0b, 0x47137755, 0xe3971777, 0x1b5d0120, 0x057a4108, - 0x6e08664d, 0x17421478, 0x11af4208, 0x850c3f42, 0x08234f0c, 0x4321eb4a, 0xf3451095, 0x0f394e0f, 0x4310eb45, 0xc09707b1, 0x54431782, 0xaec08d1d, - 0x0f434dbb, 0x9f0c0b45, 0x0a3b4dbb, 0x4618bdc7, 0x536032eb, 0x17354213, 0x4d134169, 0xc7a30c2f, 0x4e254342, 0x174332cf, 0x43cdae17, 0x6b4706e4, - 0x0e16430d, 0x530b5542, 0x2f7c26bb, 0x13075f31, 0x43175342, 0x60181317, 0x6550114e, 0x28624710, 0x58070021, 0x59181683, 0x2d540cf5, 0x05d5660c, - 0x20090c7b, 0x0e157e02, 0x8000ff2b, 0x14000080, 0x80ff8000, 0x27137e03, 0x336a4b20, 0x0f817107, 0x13876e18, 0x730f2f7e, 0x2f450b75, 0x6d02200b, - 0x6d66094c, 0x4b802009, 0x15820a02, 0x2f45fe20, 0x5e032006, 0x00202fd9, 0x450af741, 0xeb412e0f, 0x0ff3411f, 0x420a8b65, 0xf7410eae, 0x1c664810, - 0x540e1145, 0xbfa509f3, 0x42302f58, 0x80200c35, 0xcb066c47, 0x4b1120c1, 0x41492abb, 0x34854110, 0xa7097b72, 0x251545c7, 0x4b2c7f56, 0xc5b40bab, - 0x940cd54e, 0x2e6151c8, 0x09f35f18, 0x4b420420, 0x09677121, 0x8f24f357, 0x1b5418e1, 0x08915a1f, 0x3143d894, 0x22541805, 0x1b9b4b0e, 0x8c0d3443, - 0x1400240d, 0x18ff8000, 0x582e6387, 0xf99b2b3b, 0x8807a550, 0x17a14790, 0x2184fd20, 0x5758fe20, 0x2354882c, 0x15000080, 0x5e056751, 0x334c2c2f, - 0x97c58f0c, 0x1fd7410f, 0x0d4d4018, 0x4114dc41, 0x04470ed6, 0x0dd54128, 0x00820020, 0x02011523, 0x22008700, 0x86480024, 0x0001240a, 0x8682001a, - 0x0002240b, 0x866c000e, 0x8a03200b, 0x8a042017, 0x0005220b, 0x22218614, 0x84060000, 0x86012017, 0x8212200f, 0x250b8519, 0x000d0001, 0x0b850031, - 0x07000224, 0x0b862600, 0x11000324, 0x0b862d00, 0x238a0420, 0x0a000524, 0x17863e00, 0x17840620, 0x01000324, 0x57820904, 0x0b85a783, 0x0b85a785, - 0x0b85a785, 0x22000325, 0x85007a00, 0x85a7850b, 0x85a7850b, 0x22a7850b, 0x82300032, 0x00342201, 0x0805862f, 0x35003131, 0x54207962, 0x74736972, - 0x47206e61, 0x6d6d6972, 0x65527265, 0x616c7567, 0x58545472, 0x6f725020, 0x43796767, 0x6e61656c, 0x30325454, 0x822f3430, 0x35313502, 0x79006200, - 0x54002000, 0x69007200, 0x74007300, 0x6e006100, 0x47200f82, 0x6d240f84, 0x65006d00, 0x52200982, 0x67240582, 0x6c007500, 0x72201d82, 0x54222b82, - 0x23825800, 0x19825020, 0x67006f22, 0x79220182, 0x1b824300, 0x3b846520, 0x1f825420, 0x41000021, 0x1422099b, 0x0b410000, 0x87088206, 0x01012102, - 0x78080982, 0x01020101, 0x01040103, 0x01060105, 0x01080107, 0x010a0109, 0x010c010b, 0x010e010d, 0x0110010f, 0x01120111, 0x01140113, 0x01160115, - 0x01180117, 0x011a0119, 0x011c011b, 0x011e011d, 0x0020011f, 0x00040003, 0x00060005, 0x00080007, 0x000a0009, 0x000c000b, 0x000e000d, 0x0010000f, - 0x00120011, 0x00140013, 0x00160015, 0x00180017, 0x001a0019, 0x001c001b, 0x001e001d, 0x08bb821f, 0x22002142, 0x24002300, 0x26002500, 0x28002700, - 0x2a002900, 0x2c002b00, 0x2e002d00, 0x30002f00, 0x32003100, 0x34003300, 0x36003500, 0x38003700, 0x3a003900, 0x3c003b00, 0x3e003d00, 0x40003f00, - 0x42004100, 0x4b09f382, 0x00450044, 0x00470046, 0x00490048, 0x004b004a, 0x004d004c, 0x004f004e, 0x00510050, 0x00530052, 0x00550054, 0x00570056, - 0x00590058, 0x005b005a, 0x005d005c, 0x005f005e, 0x01610060, 0x01220121, 0x01240123, 0x01260125, 0x01280127, 0x012a0129, 0x012c012b, 0x012e012d, - 0x0130012f, 0x01320131, 0x01340133, 0x01360135, 0x01380137, 0x013a0139, 0x013c013b, 0x013e013d, 0x0140013f, 0x00ac0041, 0x008400a3, 0x00bd0085, - 0x00e80096, 0x008e0086, 0x009d008b, 0x00a400a9, 0x008a00ef, 0x008300da, 0x00f20093, 0x008d00f3, 0x00880097, 0x00de00c3, 0x009e00f1, 0x00f500aa, - 0x00f600f4, 0x00ad00a2, 0x00c700c9, 0x006200ae, 0x00900063, 0x00cb0064, 0x00c80065, 0x00cf00ca, 0x00cd00cc, 0x00e900ce, 0x00d30066, 0x00d100d0, - 0x006700af, 0x009100f0, 0x00d400d6, 0x006800d5, 0x00ed00eb, 0x006a0089, 0x006b0069, 0x006c006d, 0x00a0006e, 0x0071006f, 0x00720070, 0x00750073, - 0x00760074, 0x00ea0077, 0x007a0078, 0x007b0079, 0x007c007d, 0x00a100b8, 0x007e007f, 0x00810080, 0x00ee00ec, 0x6e750eba, 0x646f6369, 0x78302365, - 0x31303030, 0x32200e8d, 0x33200e8d, 0x34200e8d, 0x35200e8d, 0x36200e8d, 0x37200e8d, 0x38200e8d, 0x39200e8d, 0x61200e8d, 0x62200e8d, 0x63200e8d, - 0x64200e8d, 0x65200e8d, 0x66200e8d, 0x31210e8c, 0x8d0e8d30, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, - 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x66312def, 0x6c656406, 0x04657465, 0x6f727545, 0x3820ec8c, 0x3820ec8d, - 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, - 0x3820ec8d, 0x200ddc41, 0x0ddc4139, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, - 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0x00663923, 0x48fa0500, 0x00f762f9, -}; - -static void GetDefaultCompressedFontDataTTF(const void** ttf_compressed_data, unsigned int* ttf_compressed_size) -{ - *ttf_compressed_data = proggy_clean_ttf_compressed_data; - *ttf_compressed_size = proggy_clean_ttf_compressed_size; -} - //----------------------------------------------------------------------------- -//---- Include imgui_user.inl at the end of imgui.cpp -//---- So you can include code that extends ImGui using its private data/functions. +// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. +// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL #include "imgui_user.inl" #endif diff --git a/src/imgui.h b/src/imgui.h deleted file mode 100644 index d9be420..0000000 --- a/src/imgui.h +++ /dev/null @@ -1,1033 +0,0 @@ -// ImGui library v1.38 WIP -// See .cpp file for documentation. -// See ImGui::ShowTestWindow() for sample code. -// Read 'Programmer guide' in .cpp for notes on how to setup ImGui in your codebase. -// Get latest version at https://github.com/ocornut/imgui - -#pragma once - -#include "imconfig.h" // User-editable configuration file -#include <float.h> // FLT_MAX -#include <stdarg.h> // va_list -#include <stddef.h> // ptrdiff_t, NULL -#include <stdlib.h> // NULL, malloc, free, qsort, atoi -#include <string.h> // memset, memmove, memcpy, strlen, strchr, strcpy, strcmp - -#define IMGUI_VERSION "1.38 WIP" - -// Define assertion handler. -#ifndef IM_ASSERT -#include <assert.h> -#define IM_ASSERT(_EXPR) assert(_EXPR) -#endif - -// Define attributes of all API symbols declarations, e.g. for DLL under Windows. -#ifndef IMGUI_API -#define IMGUI_API -#endif - -// Forward declarations -struct ImDrawCmd; -struct ImDrawList; -struct ImFont; -struct ImFontAtlas; -struct ImGuiIO; -struct ImGuiStorage; -struct ImGuiStyle; - -typedef unsigned int ImU32; -typedef unsigned short ImWchar; // character for display -typedef void* ImTextureID; // user data to refer to a texture (e.g. store your texture handle/id) -typedef ImU32 ImGuiID; // unique ID used by widgets (typically hashed from a stack of string) -typedef int ImGuiCol; // enum ImGuiCol_ -typedef int ImGuiStyleVar; // enum ImGuiStyleVar_ -typedef int ImGuiKey; // enum ImGuiKey_ -typedef int ImGuiColorEditMode; // enum ImGuiColorEditMode_ -typedef int ImGuiMouseCursor; // enum ImGuiMouseCursor_ -typedef int ImGuiWindowFlags; // enum ImGuiWindowFlags_ -typedef int ImGuiSetCond; // enum ImGuiSetCond_ -typedef int ImGuiInputTextFlags; // enum ImGuiInputTextFlags_ -struct ImGuiTextEditCallbackData; // for advanced uses of InputText() -typedef int (*ImGuiTextEditCallback)(ImGuiTextEditCallbackData *data); - -struct ImVec2 -{ - float x, y; - ImVec2() { x = y = 0.0f; } - ImVec2(float _x, float _y) { x = _x; y = _y; } - -#ifdef IM_VEC2_CLASS_EXTRA // Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec2. - IM_VEC2_CLASS_EXTRA -#endif -}; - -struct ImVec4 -{ - float x, y, z, w; - ImVec4() { x = y = z = w = 0.0f; } - ImVec4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; } - -#ifdef IM_VEC4_CLASS_EXTRA // Define constructor and implicit cast operators to convert back<>forth from your math types and ImVec4. - IM_VEC4_CLASS_EXTRA -#endif -}; - -namespace ImGui -{ - // Proxy functions to access the MemAllocFn/MemFreeFn pointers in ImGui::GetIO(). The only reason they exist here is to allow ImVector<> to compile inline. - IMGUI_API void* MemAlloc(size_t sz); - IMGUI_API void MemFree(void* ptr); -} - -// std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug). -// Use '#define ImVector std::vector' if you want to use the STL type or your own type. -// Our implementation does NOT call c++ constructors! because the data types we use don't need them (but that could be added as well). Only provide the minimum functionalities we need. -#ifndef ImVector -template<typename T> -class ImVector -{ -protected: - size_t Size; - size_t Capacity; - T* Data; - -public: - typedef T value_type; - typedef value_type* iterator; - typedef const value_type* const_iterator; - - ImVector() { Size = Capacity = 0; Data = NULL; } - ~ImVector() { if (Data) ImGui::MemFree(Data); } - - inline bool empty() const { return Size == 0; } - inline size_t size() const { return Size; } - inline size_t capacity() const { return Capacity; } - - inline value_type& at(size_t i) { IM_ASSERT(i < Size); return Data[i]; } - inline const value_type& at(size_t i) const { IM_ASSERT(i < Size); return Data[i]; } - inline value_type& operator[](size_t i) { IM_ASSERT(i < Size); return Data[i]; } - inline const value_type& operator[](size_t i) const { IM_ASSERT(i < Size); return Data[i]; } - - inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } } - inline iterator begin() { return Data; } - inline const_iterator begin() const { return Data; } - inline iterator end() { return Data + Size; } - inline const_iterator end() const { return Data + Size; } - inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; } - inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; } - inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size-1]; } - inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size-1]; } - inline void swap(ImVector<T>& rhs) { const size_t rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; const size_t rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; } - - inline void resize(size_t new_size) { if (new_size > Capacity) reserve(new_size); Size = new_size; } - inline void reserve(size_t new_capacity) - { - if (new_capacity <= Capacity) return; - T* new_data = (value_type*)ImGui::MemAlloc(new_capacity * sizeof(value_type)); - memcpy(new_data, Data, Size * sizeof(value_type)); - ImGui::MemFree(Data); - Data = new_data; - Capacity = new_capacity; - } - - inline void push_back(const value_type& v) { if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); Data[Size++] = v; } - inline void pop_back() { IM_ASSERT(Size > 0); Size--; } - - inline iterator erase(const_iterator it) { IM_ASSERT(it >= begin() && it < end()); const ptrdiff_t off = it - begin(); memmove(Data + off, Data + off + 1, (Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; } - inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= begin() && it <= end()); const ptrdiff_t off = it - begin(); if (Size == Capacity) reserve(Capacity ? Capacity * 2 : 4); if (off < (int)Size) memmove(Data + off + 1, Data + off, (Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; } -}; -#endif // #ifndef ImVector - -// Helpers at bottom of the file: -// - IMGUI_ONCE_UPON_A_FRAME // Execute a block of code once per frame only (convenient for creating UI within deep-nested code that runs multiple times) -// - struct ImGuiTextFilter // Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" -// - struct ImGuiTextBuffer // Text buffer for logging/accumulating text -// - struct ImGuiStorage // Custom key value storage (if you need to alter open/close states manually) -// - struct ImDrawList // Draw command list -// - struct ImFont // TTF font loader, bake glyphs into bitmap - -// ImGui end-user API -// In a namespace so that user can add extra functions in a separate file (e.g. Value() helpers for your vector or common types) -namespace ImGui -{ - // Main - IMGUI_API ImGuiIO& GetIO(); - IMGUI_API ImGuiStyle& GetStyle(); - IMGUI_API void NewFrame(); - IMGUI_API void Render(); - IMGUI_API void Shutdown(); - IMGUI_API void ShowUserGuide(); // help block - IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // style editor block - IMGUI_API void ShowTestWindow(bool* opened = NULL); // test window, demonstrate ImGui features - IMGUI_API void ShowMetricsWindow(bool* opened = NULL); // metrics window - - // Window - // See implementation in .cpp for details - IMGUI_API bool Begin(const char* name = "Debug", bool* p_opened = NULL, ImGuiWindowFlags flags = 0); // return false when window is collapsed, so you can early out in your code. 'bool* p_opened' creates a widget on the upper-right to close the window (which sets your bool to false). - IMGUI_API bool Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_use, float bg_alpha = -1.0f, ImGuiWindowFlags flags = 0); // this is the older/longer API. call SetNextWindowSize() instead if you want to set a window size. For regular windows, 'size_on_first_use' only applies to the first time EVER the window is created and probably not what you want! maybe obsolete this API eventually. - IMGUI_API void End(); - IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // size==0.0f: use remaining window size, size<0.0f: use remaining window size minus abs(size). on each axis. - IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0,0), bool border = false, ImGuiWindowFlags extra_flags = 0); // " - IMGUI_API void EndChild(); - IMGUI_API ImVec2 GetContentRegionMax(); // window or current column boundaries, in windows coordinates - IMGUI_API ImVec2 GetWindowContentRegionMin(); // window boundaries, in windows coordinates - IMGUI_API ImVec2 GetWindowContentRegionMax(); - IMGUI_API ImDrawList* GetWindowDrawList(); // get rendering command-list if you want to append your own draw primitives - IMGUI_API ImFont* GetWindowFont(); - IMGUI_API float GetWindowFontSize(); // size (also height in pixels) of current font with current scale applied - IMGUI_API void SetWindowFontScale(float scale); // per-window font scale. Adjust IO.FontGlobalScale if you want to scale all windows - IMGUI_API ImVec2 GetWindowPos(); // you should rarely need/care about the window position, but it can be useful if you want to do your own drawing - IMGUI_API ImVec2 GetWindowSize(); // get current window position - IMGUI_API float GetWindowWidth(); - IMGUI_API bool GetWindowCollapsed(); - - IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set next window position - call before Begin() - IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // set next window size. set to ImVec2(0,0) to force an auto-fit - IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set next window collapsed state - IMGUI_API void SetNextWindowFocus(); // set next window to be focused / front-most - IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiSetCond cond = 0); // set current window position - call within Begin()/End(). may incur tearing - IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiSetCond cond = 0); // set current window size. set to ImVec2(0,0) to force an auto-fit. may incur tearing - IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiSetCond cond = 0); // set current window collapsed state - IMGUI_API void SetWindowFocus(); // set current window to be focused / front-most - IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond = 0); // set named window position - call within Begin()/End(). may incur tearing - IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond = 0); // set named window size. set to ImVec2(0,0) to force an auto-fit. may incur tearing - IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond = 0); // set named window collapsed state - IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / front-most. use NULL to remove focus. - - IMGUI_API float GetScrollPosY(); // get scrolling position [0..GetScrollMaxY()] - IMGUI_API float GetScrollMaxY(); // get maximum scrolling position == ContentSize.Y - WindowSize.Y - IMGUI_API void SetScrollPosHere(); // adjust scrolling position to center into the current cursor position - IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget - IMGUI_API void SetStateStorage(ImGuiStorage* tree); // replace tree state storage with our own (if you want to manipulate it yourself, typically clear subsection of it) - IMGUI_API ImGuiStorage* GetStateStorage(); - - // Parameters stacks (shared) - IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font - IMGUI_API void PopFont(); - IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col); - IMGUI_API void PopStyleColor(int count = 1); - IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); - IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); - IMGUI_API void PopStyleVar(int count = 1); - - // Parameters stacks (current window) - IMGUI_API void PushItemWidth(float item_width); // width of items for the common item+label case, pixels. 0.0f = default to ~2/3 of windows width, >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -0.01f always align width to the right side) - IMGUI_API void PopItemWidth(); - IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position - IMGUI_API void PushAllowKeyboardFocus(bool v); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets - IMGUI_API void PopAllowKeyboardFocus(); - IMGUI_API void PushTextWrapPos(float wrap_pos_x = 0.0f); // word-wrapping for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space - IMGUI_API void PopTextWrapPos(); - - // Tooltip - IMGUI_API void SetTooltip(const char* fmt, ...); // set tooltip under mouse-cursor, typically use with ImGui::IsHovered(). last call wins - IMGUI_API void SetTooltipV(const char* fmt, va_list args); - IMGUI_API void BeginTooltip(); // use to create full-featured tooltip windows that aren't just text - IMGUI_API void EndTooltip(); - - // Popup - IMGUI_API void BeginPopup(bool* p_opened); - IMGUI_API void EndPopup(); - - // Layout - IMGUI_API void BeginGroup(); - IMGUI_API void EndGroup(); - IMGUI_API void Separator(); // horizontal line - IMGUI_API void SameLine(int column_x = 0, int spacing_w = -1); // call between widgets or groups to layout them horizontally - IMGUI_API void Spacing(); // add vertical spacing - IMGUI_API void Indent(); // move content position toward the right by style.IndentSpacing pixels - IMGUI_API void Unindent(); // move content position back to the left (cancel Indent) - IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border=true); // setup number of columns - IMGUI_API void NextColumn(); // next column - IMGUI_API int GetColumnIndex(); // get current column index - IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetcolumnsCount() inclusive. column 0 is usually 0.0f and not resizable unless you call this - IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column - IMGUI_API float GetColumnWidth(int column_index = -1); // column width (== GetColumnOffset(GetColumnIndex()+1) - GetColumnOffset(GetColumnOffset()) - IMGUI_API int GetColumnsCount(); // number of columns (what was passed to Columns()) - IMGUI_API ImVec2 GetCursorPos(); // cursor position is relative to window position - IMGUI_API float GetCursorPosX(); // " - IMGUI_API float GetCursorPosY(); // " - IMGUI_API void SetCursorPos(const ImVec2& pos); // " - IMGUI_API void SetCursorPosX(float x); // " - IMGUI_API void SetCursorPosY(float y); // " - IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] - IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize] - IMGUI_API void AlignFirstTextHeightToWidgets(); // call once if the first item on the line is a Text() item and you want to vertically lower it to match subsequent (bigger) widgets - IMGUI_API float GetTextLineHeight(); // height of font == GetWindowFontSize() - IMGUI_API float GetTextLineHeightWithSpacing(); // spacing (in pixels) between 2 consecutive lines of text == GetWindowFontSize() + GetStyle().ItemSpacing.y - - // ID scopes - // If you are creating widgets in a loop you most likely want to push a unique identifier so ImGui can differentiate them - // You can also use "##extra" within your widget name to distinguish them from each others (see 'Programmer Guide') - IMGUI_API void PushID(const char* str_id); // push identifier into the ID stack. IDs are hash of the *entire* stack! - IMGUI_API void PushID(const void* ptr_id); - IMGUI_API void PushID(const int int_id); - IMGUI_API void PopID(); - IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). useful if you want to query into ImGuiStorage yourself. otherwise rarely needed - IMGUI_API ImGuiID GetID(const void* ptr_id); - - // Widgets - IMGUI_API void Text(const char* fmt, ...); - IMGUI_API void TextV(const char* fmt, va_list args); - IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor(); - IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args); - IMGUI_API void TextWrapped(const char* fmt, ...); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos(); - IMGUI_API void TextWrappedV(const char* fmt, va_list args); - IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // doesn't require null terminated string if 'text_end' is specified. no copy done to any bounded stack buffer, recommended for long chunks of text - IMGUI_API void LabelText(const char* label, const char* fmt, ...); // display text+label aligned the same way as value+label widgets - IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args); - IMGUI_API void Bullet(); - IMGUI_API void BulletText(const char* fmt, ...); - IMGUI_API void BulletTextV(const char* fmt, va_list args); - IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0,0), bool repeat_when_held = false); - IMGUI_API bool SmallButton(const char* label); - IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size); - IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0)); - IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0,0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,1), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding - IMGUI_API bool CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false); - IMGUI_API bool Checkbox(const char* label, bool* v); - IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value); - IMGUI_API bool RadioButton(const char* label, bool active); - IMGUI_API bool RadioButton(const char* label, int* v, int v_button); - IMGUI_API bool Combo(const char* label, int* current_item, const char** items, int items_count, int height_in_items = -1); - IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items = -1); // separate items with \0, end item-list with \0\0 - IMGUI_API bool Combo(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); - IMGUI_API bool ColorButton(const ImVec4& col, bool small_height = false, bool outline_border = true); - IMGUI_API bool ColorEdit3(const char* label, float col[3]); - IMGUI_API bool ColorEdit4(const char* label, float col[4], bool show_alpha = true); - IMGUI_API void ColorEditMode(ImGuiColorEditMode mode); - IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), size_t stride = sizeof(float)); - IMGUI_API void PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); - IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0), size_t stride = sizeof(float)); - IMGUI_API void PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0,0)); - - // Widgets: Sliders (tip: ctrl+click on a slider to input text) - IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); // adjust display_format to decorate the value with a prefix or a suffix. Use power!=1.0 for logarithmic sliders - IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); - IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); - IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); - IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f); - IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format = "%.0f"); - IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format = "%.0f"); - IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format = "%.0f"); - IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format = "%.0f"); - IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format = "%.3f", float power = 1.0f); - IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format = "%.0f"); - - // Widgets: Drags (tip: ctrl+click on a drag box to input text) - // ImGui 1.38+ work-in-progress, may change name or API. - IMGUI_API bool DragFloat(const char* label, float* v, float v_step = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* display_format = "%.3f"); // If v_max >= v_max we have no bound - IMGUI_API bool DragInt(const char* label, int* v, int v_step = 1, int v_min = 0.0f, int v_max = 0.0f, const char* display_format = "%.0f"); // If v_max >= v_max we have no bound - - // Widgets: Input - IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiTextEditCallback callback = NULL, void* user_data = NULL); - IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, int decimal_precision = -1, ImGuiInputTextFlags extra_flags = 0); - IMGUI_API bool InputFloat2(const char* label, float v[2], int decimal_precision = -1); - IMGUI_API bool InputFloat3(const char* label, float v[3], int decimal_precision = -1); - IMGUI_API bool InputFloat4(const char* label, float v[4], int decimal_precision = -1); - IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags extra_flags = 0); - IMGUI_API bool InputInt2(const char* label, int v[2]); - IMGUI_API bool InputInt3(const char* label, int v[3]); - IMGUI_API bool InputInt4(const char* label, int v[4]); - - // Widgets: Trees - IMGUI_API bool TreeNode(const char* str_label_id); // if returning 'true' the node is open and the user is responsible for calling TreePop - IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...); // " - IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...); // " - IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args); // " - IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args); // " - IMGUI_API void TreePush(const char* str_id = NULL); // already called by TreeNode(), but you can call Push/Pop yourself for layouting purpose - IMGUI_API void TreePush(const void* ptr_id = NULL); // " - IMGUI_API void TreePop(); - IMGUI_API void SetNextTreeNodeOpened(bool opened, ImGuiSetCond cond = 0); // set next tree node to be opened. - - // Widgets: Selectable / Lists - IMGUI_API bool Selectable(const char* label, bool selected = false, const ImVec2& size = ImVec2(0,0)); - IMGUI_API bool Selectable(const char* label, bool* p_selected, const ImVec2& size = ImVec2(0,0)); - IMGUI_API bool ListBox(const char* label, int* current_item, const char** items, int items_count, int height_in_items = -1); - IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1); - IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0,0)); // use if you want to reimplement ListBox() will custom data or interactions. make sure to call ListBoxFooter() afterwards. - IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // " - IMGUI_API void ListBoxFooter(); // terminate the scrolling region - - // Widgets: Value() Helpers. Output single value in "name: value" format (tip: freely declare your own within the ImGui namespace!) - IMGUI_API void Value(const char* prefix, bool b); - IMGUI_API void Value(const char* prefix, int v); - IMGUI_API void Value(const char* prefix, unsigned int v); - IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL); - IMGUI_API void Color(const char* prefix, const ImVec4& v); - IMGUI_API void Color(const char* prefix, unsigned int v); - - // Logging: all text output from interface is redirected to tty/file/clipboard. Tree nodes are automatically opened. - IMGUI_API void LogToTTY(int max_depth = -1); // start logging to tty - IMGUI_API void LogToFile(int max_depth = -1, const char* filename = NULL); // start logging to file - IMGUI_API void LogToClipboard(int max_depth = -1); // start logging to OS clipboard - IMGUI_API void LogFinish(); // stop logging (close file, etc.) - IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard - IMGUI_API void LogText(const char* fmt, ...); // pass text data straight to log (without being displayed) - - // Utilities - IMGUI_API bool IsItemHovered(); // was the last item hovered by mouse? - IMGUI_API bool IsItemHoveredRect(); // was the last item hovered by mouse? even if another item is active while we are hovering this - IMGUI_API bool IsItemActive(); // was the last item active? (e.g. button being held, text field being edited- items that don't interact will always return false) - IMGUI_API bool IsAnyItemActive(); // - IMGUI_API ImVec2 GetItemRectMin(); // get bounding rect of last item - IMGUI_API ImVec2 GetItemRectMax(); // " - IMGUI_API ImVec2 GetItemRectSize(); // " - IMGUI_API bool IsWindowFocused(); // is current window focused (differentiate child windows from each others) - IMGUI_API bool IsRootWindowFocused(); // is current root window focused - IMGUI_API bool IsRootWindowOrAnyChildFocused(); // is current root window or any of its child (including current window) focused - IMGUI_API bool IsClipped(const ImVec2& item_size); // to perform coarse clipping on user's side (as an optimization) - IMGUI_API bool IsKeyPressed(int key_index, bool repeat = true); // key_index into the keys_down[512] array, imgui doesn't know the semantic of each entry - IMGUI_API bool IsMouseClicked(int button, bool repeat = false); - IMGUI_API bool IsMouseDoubleClicked(int button); - IMGUI_API bool IsMouseHoveringWindow(); // is mouse hovering current window ("window" in API names always refer to current window) - IMGUI_API bool IsMouseHoveringAnyWindow(); // is mouse hovering any active imgui window - IMGUI_API bool IsMouseHoveringRect(const ImVec2& rect_min, const ImVec2& rect_max);// is mouse hovering given bounding rect - IMGUI_API bool IsMouseDragging(int button = 0, float lock_threshold = -1.0f); // is mouse dragging. if lock_threshold < -1.0f uses io.MouseDraggingThreshold - IMGUI_API bool IsPosHoveringAnyWindow(const ImVec2& pos); // is given position hovering any active imgui window - IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls - IMGUI_API ImVec2 GetMouseDragDelta(int button = 0, float lock_threshold = -1.0f); // dragging amount since clicking, also see: GetItemActiveDragDelta(). if lock_threshold < -1.0f uses io.MouseDraggingThreshold - IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you - IMGUI_API void SetMouseCursor(ImGuiMouseCursor type); // set desired cursor type - IMGUI_API float GetTime(); - IMGUI_API int GetFrameCount(); - IMGUI_API const char* GetStyleColName(ImGuiCol idx); - IMGUI_API ImVec2 CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge = false, float outward = +0.0f); // utility to find the closest point the last item bounding rectangle edge. useful to visually link items - IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f); - IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // helper to manually clip large list of items. see comments in implementation - - IMGUI_API void BeginChildFrame(ImGuiID id, const ImVec2& size); // helper to create a child window / scrolling region that looks like a normal widget frame - IMGUI_API void EndChildFrame(); - - IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in); - IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v); - IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b); - - // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself - IMGUI_API const char* GetVersion(); - IMGUI_API void* GetInternalState(); - IMGUI_API size_t GetInternalStateSize(); - IMGUI_API void SetInternalState(void* state, bool construct = false); - - // Obsolete (will be removed) - IMGUI_API void GetDefaultFontData(const void** fnt_data, unsigned int* fnt_size, const void** png_data, unsigned int* png_size); // OBSOLETE - static inline void OpenNextNode(bool open) { ImGui::SetNextTreeNodeOpened(open, 0); } // OBSOLETE - static inline bool GetWindowIsFocused() { return ImGui::IsWindowFocused(); } // OBSOLETE - static inline ImVec2 GetItemBoxMin() { return GetItemRectMin(); } // OBSOLETE - static inline ImVec2 GetItemBoxMax() { return GetItemRectMax(); } // OBSOLETE - static inline bool IsMouseHoveringBox(const ImVec2& rect_min, const ImVec2& rect_max) { return IsMouseHoveringRect(rect_min, rect_max); } // OBSOLETE - -} // namespace ImGui - -// Flags for ImGui::Begin() -enum ImGuiWindowFlags_ -{ - // Default: 0 - ImGuiWindowFlags_NoTitleBar = 1 << 0, // Disable title-bar - ImGuiWindowFlags_NoResize = 1 << 1, // Disable user resizing with the lower-right grip - ImGuiWindowFlags_NoMove = 1 << 2, // Disable user moving the window - ImGuiWindowFlags_NoScrollbar = 1 << 3, // Disable scrollbar (window can still scroll with mouse or programatically) - ImGuiWindowFlags_NoScrollWithMouse = 1 << 4, // Disable user scrolling with mouse wheel - ImGuiWindowFlags_NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it - ImGuiWindowFlags_AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame - ImGuiWindowFlags_ShowBorders = 1 << 7, // Show borders around windows and items - ImGuiWindowFlags_NoSavedSettings = 1 << 8, // Never load/save settings in .ini file - // [Internal] - ImGuiWindowFlags_ChildWindow = 1 << 9, // For internal use by BeginChild() - ImGuiWindowFlags_ChildWindowAutoFitX = 1 << 10, // For internal use by BeginChild() - ImGuiWindowFlags_ChildWindowAutoFitY = 1 << 11, // For internal use by BeginChild() - ImGuiWindowFlags_ComboBox = 1 << 12, // For internal use by ComboBox() - ImGuiWindowFlags_Tooltip = 1 << 13, // For internal use by BeginTooltip() - ImGuiWindowFlags_Popup = 1 << 14 // For internal use by BeginPopup() -}; - -// Flags for ImGui::InputText() -enum ImGuiInputTextFlags_ -{ - // Default: 0 - ImGuiInputTextFlags_CharsDecimal = 1 << 0, // Allow 0123456789.+-*/ - ImGuiInputTextFlags_CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef - ImGuiInputTextFlags_CharsUppercase = 1 << 2, // Turn a..z into A..Z - ImGuiInputTextFlags_CharsNoBlank = 1 << 3, // Filter out spaces, tabs - ImGuiInputTextFlags_AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus - ImGuiInputTextFlags_EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified) - ImGuiInputTextFlags_CallbackCompletion = 1 << 6, // Call user function on pressing TAB (for completion handling) - ImGuiInputTextFlags_CallbackHistory = 1 << 7, // Call user function on pressing Up/Down arrows (for history handling) - ImGuiInputTextFlags_CallbackAlways = 1 << 8, // Call user function every time - ImGuiInputTextFlags_CallbackCharFilter = 1 << 9 // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character. -}; - -// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array -enum ImGuiKey_ -{ - ImGuiKey_Tab, - ImGuiKey_LeftArrow, - ImGuiKey_RightArrow, - ImGuiKey_UpArrow, - ImGuiKey_DownArrow, - ImGuiKey_Home, - ImGuiKey_End, - ImGuiKey_Delete, - ImGuiKey_Backspace, - ImGuiKey_Enter, - ImGuiKey_Escape, - ImGuiKey_A, // for CTRL+A: select all - ImGuiKey_C, // for CTRL+C: copy - ImGuiKey_V, // for CTRL+V: paste - ImGuiKey_X, // for CTRL+X: cut - ImGuiKey_Y, // for CTRL+Y: redo - ImGuiKey_Z, // for CTRL+Z: undo - ImGuiKey_COUNT -}; - -// Enumeration for PushStyleColor() / PopStyleColor() -enum ImGuiCol_ -{ - ImGuiCol_Text, - ImGuiCol_WindowBg, - ImGuiCol_ChildWindowBg, - ImGuiCol_Border, - ImGuiCol_BorderShadow, - ImGuiCol_FrameBg, // Background of checkbox, radio button, plot, slider, text input - ImGuiCol_FrameBgHovered, - ImGuiCol_FrameBgActive, - ImGuiCol_TitleBg, - ImGuiCol_TitleBgCollapsed, - ImGuiCol_ScrollbarBg, - ImGuiCol_ScrollbarGrab, - ImGuiCol_ScrollbarGrabHovered, - ImGuiCol_ScrollbarGrabActive, - ImGuiCol_ComboBg, - ImGuiCol_CheckMark, - ImGuiCol_SliderGrab, - ImGuiCol_SliderGrabActive, - ImGuiCol_Button, - ImGuiCol_ButtonHovered, - ImGuiCol_ButtonActive, - ImGuiCol_Header, - ImGuiCol_HeaderHovered, - ImGuiCol_HeaderActive, - ImGuiCol_Column, - ImGuiCol_ColumnHovered, - ImGuiCol_ColumnActive, - ImGuiCol_ResizeGrip, - ImGuiCol_ResizeGripHovered, - ImGuiCol_ResizeGripActive, - ImGuiCol_CloseButton, - ImGuiCol_CloseButtonHovered, - ImGuiCol_CloseButtonActive, - ImGuiCol_PlotLines, - ImGuiCol_PlotLinesHovered, - ImGuiCol_PlotHistogram, - ImGuiCol_PlotHistogramHovered, - ImGuiCol_TextSelectedBg, - ImGuiCol_TooltipBg, - ImGuiCol_COUNT -}; - -// Enumeration for PushStyleVar() / PopStyleVar() -// NB: the enum only refers to fields of ImGuiStyle() which makes sense to be pushed/poped in UI code. Feel free to add others. -enum ImGuiStyleVar_ -{ - ImGuiStyleVar_Alpha, // float - ImGuiStyleVar_WindowPadding, // ImVec2 - ImGuiStyleVar_WindowRounding, // float - ImGuiStyleVar_ChildWindowRounding, // float - ImGuiStyleVar_FramePadding, // ImVec2 - ImGuiStyleVar_FrameRounding, // float - ImGuiStyleVar_ItemSpacing, // ImVec2 - ImGuiStyleVar_ItemInnerSpacing, // ImVec2 - ImGuiStyleVar_IndentSpacing, // float - ImGuiStyleVar_GrabMinSize // float -}; - -// Enumeration for ColorEditMode() -enum ImGuiColorEditMode_ -{ - ImGuiColorEditMode_UserSelect = -2, - ImGuiColorEditMode_UserSelectShowButton = -1, - ImGuiColorEditMode_RGB = 0, - ImGuiColorEditMode_HSV = 1, - ImGuiColorEditMode_HEX = 2 -}; - -// Enumeration for GetMouseCursor() -enum ImGuiMouseCursor_ -{ - ImGuiMouseCursor_Arrow = 0, - ImGuiMouseCursor_TextInput, // When hovering over InputText, etc. - ImGuiMouseCursor_Move, // Unused - ImGuiMouseCursor_ResizeNS, // Unused - ImGuiMouseCursor_ResizeEW, // When hovering over a column - ImGuiMouseCursor_ResizeNESW, // Unused - ImGuiMouseCursor_ResizeNWSE, // When hovering over the bottom-right corner of a window - ImGuiMouseCursor_Count_ -}; - -// Condition flags for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions -// All those functions treat 0 as a shortcut to ImGuiSetCond_Always -enum ImGuiSetCond_ -{ - ImGuiSetCond_Always = 1 << 0, // Set the variable - ImGuiSetCond_Once = 1 << 1, // Only set the variable on the first call per runtime session - ImGuiSetCond_FirstUseEver = 1 << 2 // Only set the variable if the window doesn't exist in the .ini file -}; - -struct ImGuiStyle -{ - float Alpha; // Global alpha applies to everything in ImGui - ImVec2 WindowPadding; // Padding within a window - ImVec2 WindowMinSize; // Minimum window size - float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows - float ChildWindowRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows - ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets) - float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets). - ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines - ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) - ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! - ImVec2 AutoFitPadding; // Extra space after auto-fit (double-clicking on resize grip) - float WindowFillAlphaDefault; // Default alpha of window background, if not specified in ImGui::Begin() - float IndentSpacing; // Horizontal indentation when e.g. entering a tree node - float ColumnsMinSpacing; // Minimum horizontal spacing between two columns - float ScrollbarWidth; // Width of the vertical scrollbar - float GrabMinSize; // Minimum width/height of a slider or scrollbar grab - ImVec2 DisplaySafeAreaPadding; // Window positions are clamped to be visible within the display area. If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. - ImVec4 Colors[ImGuiCol_COUNT]; - - IMGUI_API ImGuiStyle(); -}; - -// This is where your app communicate with ImGui. Call ImGui::GetIO() to access. -// Read 'Programmer guide' section in .cpp file for general usage. -struct ImGuiIO -{ - //------------------------------------------------------------------ - // Settings (fill once) // Default value: - //------------------------------------------------------------------ - - ImVec2 DisplaySize; // <unset> // Display size, in pixels. For clamping windows positions. - float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds. - float IniSavingRate; // = 5.0f // Maximum time between saving positions/sizes to .ini file, in seconds. - const char* IniFilename; // = "imgui.ini" // Path to .ini file. NULL to disable .ini saving. - const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified). - float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds. - float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels. - float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging - int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array - void* UserData; // = NULL // Store your own data for retrieval by callbacks. - - ImFontAtlas* Fonts; // <auto> // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array. - float FontGlobalScale; // = 1.0f // Global scale all fonts - bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel. - ImVec2 DisplayVisibleMin; // <unset> (0.0f,0.0f) // If you use DisplaySize as a virtual space larger than your screen, set DisplayVisibleMin/Max to the visible area. - ImVec2 DisplayVisibleMax; // <unset> (0.0f,0.0f) // If the values are the same, we defaults to Min=(0.0f) and Max=DisplaySize - - //------------------------------------------------------------------ - // User Functions - //------------------------------------------------------------------ - - // REQUIRED: rendering function. - // See example code if you are unsure of how to implement this. - void (*RenderDrawListsFn)(ImDrawList** const draw_lists, int count); - - // Optional: access OS clipboard - // (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures) - const char* (*GetClipboardTextFn)(); - void (*SetClipboardTextFn)(const char* text); - - // Optional: override memory allocations. MemFreeFn() may be called with a NULL pointer. - // (default to posix malloc/free) - void* (*MemAllocFn)(size_t sz); - void (*MemFreeFn)(void* ptr); - - // Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME in Windows) - // (default to use native imm32 api on Windows) - void (*ImeSetInputScreenPosFn)(int x, int y); - void* ImeWindowHandle; // (Windows) Set this to your HWND to get automatic IME cursor positioning. - - //------------------------------------------------------------------ - // Input - Fill before calling NewFrame() - //------------------------------------------------------------------ - - ImVec2 MousePos; // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) - bool MouseDown[5]; // Mouse buttons. ImGui itself only uses button 0 (left button). Others buttons allows to track if mouse is being used by your application + available to user as a convenience via IsMouse** API. - float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text. - bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor). - bool KeyCtrl; // Keyboard modifier pressed: Control - bool KeyShift; // Keyboard modifier pressed: Shift - bool KeyAlt; // Keyboard modifier pressed: Alt - bool KeysDown[512]; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data) - ImWchar InputCharacters[16+1]; // List of characters input (translated by user from keypress+keyboard state). Fill using AddInputCharacter() helper. - - // Function - IMGUI_API void AddInputCharacter(ImWchar c); // Helper to add a new character into InputCharacters[] - - //------------------------------------------------------------------ - // Output - Retrieve after calling NewFrame(), you can use them to discard inputs or hide them from the rest of your application - //------------------------------------------------------------------ - - bool WantCaptureMouse; // Mouse is hovering a window or widget is active (= ImGui will use your mouse input) - bool WantCaptureKeyboard; // Widget is active (= ImGui will use your keyboard input) - float Framerate; // Framerate estimation, in frame per second. Rolling average estimation based on IO.DeltaTime over 120 frames - int MetricsVertices; // Vertices processed during last call to Render() - - //------------------------------------------------------------------ - // [Internal] ImGui will maintain those fields for you - //------------------------------------------------------------------ - - ImVec2 MousePosPrev; // Previous mouse position - ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are negative to allow mouse enabling/disabling. - bool MouseClicked[5]; // Mouse button went from !Down to Down - ImVec2 MouseClickedPos[5]; // Position at time of clicking - float MouseClickedTime[5]; // Time of last click (used to figure out double-click) - bool MouseDoubleClicked[5]; // Has mouse button been double-clicked? - bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds. - float MouseDownTime[5]; // Time the mouse button has been down - float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the click point - float KeysDownTime[512]; // Time the keyboard key has been down - - IMGUI_API ImGuiIO(); -}; - -//----------------------------------------------------------------------------- -// Helpers -//----------------------------------------------------------------------------- - -// Helper: execute a block of code once a frame only -// Convenient if you want to quickly create an UI within deep-nested code that runs multiple times every frame. -// Usage: -// IMGUI_ONCE_UPON_A_FRAME -// { -// // code block will be executed one per frame -// } -// Attention! the macro expands into 2 statement so make sure you don't use it within e.g. an if() statement without curly braces. -#define IMGUI_ONCE_UPON_A_FRAME static ImGuiOnceUponAFrame imgui_oaf##__LINE__; if (imgui_oaf##__LINE__) -struct ImGuiOnceUponAFrame -{ - ImGuiOnceUponAFrame() { RefFrame = -1; } - mutable int RefFrame; - operator bool() const { const int current_frame = ImGui::GetFrameCount(); if (RefFrame == current_frame) return false; RefFrame = current_frame; return true; } -}; - -// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" -struct ImGuiTextFilter -{ - struct TextRange - { - const char* b; - const char* e; - - TextRange() { b = e = NULL; } - TextRange(const char* _b, const char* _e) { b = _b; e = _e; } - const char* begin() const { return b; } - const char* end() const { return e; } - bool empty() const { return b == e; } - char front() const { return *b; } - static bool isblank(char c) { return c == ' ' || c == '\t'; } - void trim_blanks() { while (b < e && isblank(*b)) b++; while (e > b && isblank(*(e-1))) e--; } - IMGUI_API void split(char separator, ImVector<TextRange>& out); - }; - - char InputBuf[256]; - ImVector<TextRange> Filters; - int CountGrep; - - ImGuiTextFilter(const char* default_filter = ""); - void Clear() { InputBuf[0] = 0; Build(); } - void Draw(const char* label = "Filter (inc,-exc)", float width = -1.0f); // Helper calling InputText+Build - bool PassFilter(const char* val) const; - bool IsActive() const { return !Filters.empty(); } - IMGUI_API void Build(); -}; - -// Helper: Text buffer for logging/accumulating text -struct ImGuiTextBuffer -{ - ImVector<char> Buf; - - ImGuiTextBuffer() { Buf.push_back(0); } - const char* begin() const { return &Buf.front(); } - const char* end() const { return &Buf.back(); } // Buf is zero-terminated, so end() will point on the zero-terminator - size_t size() const { return Buf.size()-1; } - bool empty() { return size() >= 1; } - void clear() { Buf.clear(); Buf.push_back(0); } - IMGUI_API void append(const char* fmt, ...); - IMGUI_API void appendv(const char* fmt, va_list args); -}; - -// Helper: Key->value storage -// - Store collapse state for a tree (Int 0/1) -// - Store color edit options (Int using values in ImGuiColorEditMode enum). -// - Custom user storage for temporary values. -// Typically you don't have to worry about this since a storage is held within each Window. -// Declare your own storage if: -// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state). -// - You want to store custom debug data easily without adding or editing structures in your code. -struct ImGuiStorage -{ - struct Pair - { - ImGuiID key; - union { int val_i; float val_f; void* val_p; }; - Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; } - Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; } - Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; } - }; - ImVector<Pair> Data; - - // - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N) - // - Set***() functions find pair, insertion on demand if missing. - // - Sorted insertion is costly but should amortize. A typical frame shouldn't need to insert any new pair. - IMGUI_API void Clear(); - IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const; - IMGUI_API void SetInt(ImGuiID key, int val); - IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const; - IMGUI_API void SetFloat(ImGuiID key, float val); - IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL - IMGUI_API void SetVoidPtr(ImGuiID key, void* val); - - // - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set. - // - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. - // - A typical use case where this is convenient: - // float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar; - // - You can also use this to quickly create temporary editable values during a session of using Edit&Continue, without restarting your application. - IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0); - IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0); - - // Use on your own storage if you know only integer are being stored (open/close all tree nodes) - IMGUI_API void SetAllInt(int val); -}; - -// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used. -struct ImGuiTextEditCallbackData -{ - ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only - ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only - void* UserData; // What user passed to InputText() // Read-only - - // CharFilter event: - ImWchar EventChar; // Character input // Read-write (replace character or set to zero) - - // Completion,History,Always events: - ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only - char* Buf; // Current text // Read-write (pointed data only) - size_t BufSize; // // Read-only - bool BufDirty; // Set if you modify Buf directly // Write - int CursorPos; // // Read-write - int SelectionStart; // // Read-write (== to SelectionEnd when no selection) - int SelectionEnd; // // Read-write - - // NB: calling those function loses selection. - void DeleteChars(int pos, int bytes_count); - void InsertChars(int pos, const char* text, const char* text_end = NULL); -}; - -// ImColor() is just a helper that implicity converts to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float) -// None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either formats. -struct ImColor -{ - ImVec4 Value; - - ImColor(int r, int g, int b, int a = 255) { Value.x = (float)r / 255.0f; Value.y = (float)g / 255.0f; Value.z = (float)b / 255.0f; Value.w = (float)a / 255.0f; } - ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; } - ImColor(const ImVec4& col) { Value = col; } - operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); } - operator ImVec4() const { return Value; } - - static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); } -}; - -//----------------------------------------------------------------------------- -// Draw List -// Hold a series of drawing commands. The user provides a renderer for ImDrawList. -//----------------------------------------------------------------------------- - -// Draw callbacks for advanced uses. -// NB- You most likely DO NOT need to care about draw callbacks just to create your own widget or customized UI rendering (you can poke into the draw list for that) -// Draw callback are useful for example if you want to render a complex 3D scene inside a UI element. -// The expected behavior from your rendering loop is: -// if (cmd.user_callback != NULL) -// cmd.user_callback(parent_list, cmd); -// else -// RenderTriangles() -// It is up to you to decide if your rendering loop or the callback should be responsible for backup/restoring rendering state. -typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd); - -// Typically, 1 command = 1 gpu draw call (unless command is a callback) -struct ImDrawCmd -{ - unsigned int vtx_count; // Number of vertices (multiple of 3) to be drawn as triangles. The vertices are stored in the callee ImDrawList's vtx_buffer[] array. - ImVec4 clip_rect; // Clipping rectangle (x1, y1, x2, y2) - ImTextureID texture_id; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas. - ImDrawCallback user_callback; // If != NULL, call the function instead of rendering the vertices. vtx_count will be 0. clip_rect and texture_id will be set normally. - void* user_callback_data; // The draw callback code can access this. -}; - -// Vertex layout -#ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT -struct ImDrawVert -{ - ImVec2 pos; - ImVec2 uv; - ImU32 col; -}; -#else -// You can change the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h -// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine. -// The type has to be described by the #define (you can either declare the struct or use a typedef) -IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT; -#endif - -// Draw command list -// This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering. -// At the moment, each ImGui window contains its own ImDrawList but they could potentially be merged in the future. -// If you want to add custom rendering within a window, you can use ImGui::GetWindowDrawList() to access the current draw list and add your own primitives. -// You can interleave normal ImGui:: calls and adding primitives to the current draw list. -// All positions are in screen coordinates (0,0=top-left, 1 pixel per unit). Primitives are always added to the list and not culled (culling is done at render time and at a higher-level by ImGui:: functions). -// Note that this only gives you access to rendering polygons. If your intent is to create custom widgets and the publicly exposed functions/data aren't sufficient, you can add code in imgui_user.inl -struct ImDrawList -{ - // This is what you have to render - ImVector<ImDrawCmd> commands; // Commands. Typically 1 command = 1 gpu draw call. - ImVector<ImDrawVert> vtx_buffer; // Vertex buffer. Each command consume ImDrawCmd::vtx_count of those - - // [Internal to ImGui] - ImVector<ImVec4> clip_rect_stack; // [Internal] - ImVector<ImTextureID> texture_id_stack; // [Internal] - ImDrawVert* vtx_write; // [Internal] point within vtx_buffer after each add command (to avoid using the ImVector<> operators too much) - - ImDrawList() { Clear(); } - IMGUI_API void Clear(); - IMGUI_API void ClearFreeMemory(); - IMGUI_API void PushClipRect(const ImVec4& clip_rect); // Scissoring. The values are x1, y1, x2, y2. - IMGUI_API void PushClipRectFullScreen(); - IMGUI_API void PopClipRect(); - IMGUI_API void PushTextureID(const ImTextureID& texture_id); - IMGUI_API void PopTextureID(); - - // Primitives - IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); - IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners=0x0F); - IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners=0x0F); - IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col); - IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); - IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12); - IMGUI_API void AddArc(const ImVec2& center, float rad, ImU32 col, int a_min, int a_max, bool tris = false, const ImVec2& third_point_offset = ImVec2(0,0)); - IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec2* cpu_clip_max = NULL); - IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0, const ImVec2& uv1, ImU32 col = 0xFFFFFFFF); - - // Advanced - IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'user_callback' in ImDrawCmd and call the function instead of rendering triangles. - IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible - - // Internal helpers - IMGUI_API void ReserveVertices(unsigned int vtx_count); - IMGUI_API void AddVtx(const ImVec2& pos, ImU32 col); - IMGUI_API void AddVtxUV(const ImVec2& pos, ImU32 col, const ImVec2& uv); - IMGUI_API void AddVtxLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f); - IMGUI_API void UpdateClipRect(); - IMGUI_API void UpdateTextureID(); -}; - -// Load and rasterize multiple TTF fonts into a same texture. -// Sharing a texture for multiple fonts allows us to reduce the number of draw calls during rendering. -// We also add custom graphic data into the texture that serves for ImGui. -// 1. (Optional) Call AddFont*** functions. If you don't call any, the default font will be loaded for you. -// 2. Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data. -// 3. Upload the pixels data into a texture within your graphics system. -// 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture. -// 5. Call ClearPixelsData() to free textures memory on the heap. -struct ImFontAtlas -{ - IMGUI_API ImFontAtlas(); - IMGUI_API ~ImFontAtlas(); - IMGUI_API ImFont* AddFontDefault(); - IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImWchar* glyph_ranges = NULL, int font_no = 0); - IMGUI_API ImFont* AddFontFromMemoryTTF(void* in_ttf_data, size_t in_ttf_data_size, float size_pixels, const ImWchar* glyph_ranges = NULL, int font_no = 0); // Pass ownership of 'in_ttf_data' memory. - IMGUI_API void ClearTexData(); // Saves RAM once the texture has been copied to graphics memory. - IMGUI_API void Clear(); - - // Retrieve texture data - // User is in charge of copying the pixels into graphics memory, then call SetTextureUserID() - // After loading the texture into your graphic system, store your texture handle in 'TexID' (ignore if you aren't using multiple fonts nor images) - // RGBA32 format is provided for convenience and high compatibility, but note that all RGB pixels are white, so 75% of the memory is wasted. - // Pitch = Width * BytesPerPixels - IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel - IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel - IMGUI_API void SetTexID(void* id) { TexID = id; } - - // Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list) - // (Those functions could be static but aren't so most users don't have to refer to the ImFontAtlas:: name ever if in their code; just using io.Fonts->) - IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin - IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs - IMGUI_API const ImWchar* GetGlyphRangesChinese(); // Japanese + full set of about 21000 CJK Unified Ideographs - - // Members - // (Access texture data via GetTexData*() calls which will setup a default font for you.) - void* TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It ia passed back to you during rendering. - unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight - unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4 - int TexWidth; - int TexHeight; - ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel (part of the TexExtraData block) - ImVector<ImFont*> Fonts; - - // Private - struct ImFontAtlasData; - ImVector<ImFontAtlasData*> InputData; // Internal data - IMGUI_API bool Build(); // Build pixels data. This is automatically for you by the GetTexData*** functions. - IMGUI_API void ClearInputData(); // Clear the input TTF data. - IMGUI_API void RenderCustomTexData(int pass, void* rects); -}; - -// TTF font loading and rendering -// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32(). -// Kerning isn't supported. At the moment some ImGui code does per-character CalcTextSize calls, need something more state-ful. -struct ImFont -{ - // Members: Settings - float FontSize; // <user set> // Height of characters, set during loading (don't change after loading) - float Scale; // = 1.0f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale() - ImVec2 DisplayOffset; // = (0.0f,0.0f) // Offset font rendering by xx pixels - ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar() - - // Members: Runtime data - struct Glyph - { - ImWchar Codepoint; - signed short XAdvance; - signed short Width, Height; - signed short XOffset, YOffset; - float U0, V0, U1, V1; // Texture coordinates - }; - ImFontAtlas* ContainerAtlas; // What we has been loaded into - ImVector<Glyph> Glyphs; - const Glyph* FallbackGlyph; // == FindGlyph(FontFallbackChar) - float FallbackXAdvance; // - ImVector<float> IndexXAdvance; // Glyphs->XAdvance directly indexable (for CalcTextSize functions which are often bottleneck in large UI) - ImVector<int> IndexLookup; // Index glyphs by Unicode code-point - - // Methods - IMGUI_API ImFont(); - IMGUI_API ~ImFont(); - IMGUI_API void Clear(); - IMGUI_API void BuildLookupTable(); - IMGUI_API const Glyph* FindGlyph(unsigned short c) const; - IMGUI_API void SetFallbackChar(ImWchar c); - IMGUI_API bool IsLoaded() const { return ContainerAtlas != NULL; } - - // 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable. - // 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable. - IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8 - IMGUI_API ImVec2 CalcTextSizeW(float size, float max_width, const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL) const; // wchar - IMGUI_API void RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, ImDrawVert*& out_vertices, float wrap_width = 0.0f, const ImVec2* cpu_clip_max = NULL) const; - IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const; -}; - -//---- Include imgui_user.h at the end of imgui.h -//---- So you can include code that extends ImGui using any of the types declared above. -//---- (also convenient for user to only explicitly include vanilla imgui.h) -#ifdef IMGUI_INCLUDE_IMGUI_USER_H -#include "imgui_user.h" -#endif diff --git a/src/imgui_demo.cpp b/src/imgui_demo.cpp new file mode 100644 index 0000000..506b0f2 --- /dev/null +++ b/src/imgui_demo.cpp @@ -0,0 +1,2617 @@ +// dear imgui, v1.50 WIP +// (demo code) + +// Don't remove this file from your project! It is useful reference code that you can execute. +// You can call ImGui::ShowTestWindow() in your code to learn about various features of ImGui. +// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowTestWindow(). + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#include <ctype.h> // toupper, isprint +#include <math.h> // sqrtf, powf, cosf, sinf, floorf, ceilf +#include <stdio.h> // vsnprintf, sscanf, printf +#include <stdlib.h> // NULL, malloc, free, qsort, atoi +#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier +#include <stddef.h> // intptr_t +#else +#include <stdint.h> // intptr_t +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#define snprintf _snprintf +#endif +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning : 'xx' is deprecated: The POSIX name for this item.. // for strdup used in demo code (so user can copy & paste the code) +#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' +#pragma clang diagnostic ignored "-Wformat-security" // warning : warning: format string is not a string literal +#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size +#pragma GCC diagnostic ignored "-Wformat-security" // warning : format string is not a string literal (potentially insecure) +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#endif + +// Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. +#ifdef _WIN32 +#define IM_NEWLINE "\r\n" +#else +#define IM_NEWLINE "\n" +#endif + +#define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) +#define IM_MAX(_A,_B) (((_A) >= (_B)) ? (_A) : (_B)) + +//----------------------------------------------------------------------------- +// DEMO CODE +//----------------------------------------------------------------------------- + +#ifndef IMGUI_DISABLE_TEST_WINDOWS + +static void ShowExampleAppConsole(bool* p_open); +static void ShowExampleAppLog(bool* p_open); +static void ShowExampleAppLayout(bool* p_open); +static void ShowExampleAppPropertyEditor(bool* p_open); +static void ShowExampleAppLongText(bool* p_open); +static void ShowExampleAppAutoResize(bool* p_open); +static void ShowExampleAppConstrainedResize(bool* p_open); +static void ShowExampleAppFixedOverlay(bool* p_open); +static void ShowExampleAppManipulatingWindowTitle(bool* p_open); +static void ShowExampleAppCustomRendering(bool* p_open); +static void ShowExampleAppMainMenuBar(); +static void ShowExampleMenuFile(); + +static void ShowHelpMarker(const char* desc) +{ + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(450.0f); + ImGui::TextUnformatted(desc); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } +} + +void ImGui::ShowUserGuide() +{ + ImGui::BulletText("Double-click on title bar to collapse window."); + ImGui::BulletText("Click and drag on lower right corner to resize window."); + ImGui::BulletText("Click and drag on any empty space to move window."); + ImGui::BulletText("Mouse Wheel to scroll."); + if (ImGui::GetIO().FontAllowUserScaling) + ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); + ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); + ImGui::BulletText("CTRL+Click on a slider or drag box to input text."); + ImGui::BulletText( + "While editing text:\n" + "- Hold SHIFT or use mouse to select text\n" + "- CTRL+Left/Right to word jump\n" + "- CTRL+A or double-click to select all\n" + "- CTRL+X,CTRL+C,CTRL+V clipboard\n" + "- CTRL+Z,CTRL+Y undo/redo\n" + "- ESCAPE to revert\n" + "- You can apply arithmetic operators +,*,/ on numerical values.\n" + " Use +- to subtract.\n"); +} + +// Demonstrate most ImGui features (big function!) +void ImGui::ShowTestWindow(bool* p_open) +{ + // Examples apps + static bool show_app_main_menu_bar = false; + static bool show_app_console = false; + static bool show_app_log = false; + static bool show_app_layout = false; + static bool show_app_property_editor = false; + static bool show_app_long_text = false; + static bool show_app_auto_resize = false; + static bool show_app_constrained_resize = false; + static bool show_app_fixed_overlay = false; + static bool show_app_manipulating_window_title = false; + static bool show_app_custom_rendering = false; + static bool show_app_style_editor = false; + + static bool show_app_metrics = false; + static bool show_app_about = false; + + if (show_app_main_menu_bar) ShowExampleAppMainMenuBar(); + if (show_app_console) ShowExampleAppConsole(&show_app_console); + if (show_app_log) ShowExampleAppLog(&show_app_log); + if (show_app_layout) ShowExampleAppLayout(&show_app_layout); + if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor); + if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text); + if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize); + if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize); + if (show_app_fixed_overlay) ShowExampleAppFixedOverlay(&show_app_fixed_overlay); + if (show_app_manipulating_window_title) ShowExampleAppManipulatingWindowTitle(&show_app_manipulating_window_title); + if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering); + + if (show_app_metrics) ImGui::ShowMetricsWindow(&show_app_metrics); + if (show_app_style_editor) { ImGui::Begin("Style Editor", &show_app_style_editor); ImGui::ShowStyleEditor(); ImGui::End(); } + if (show_app_about) + { + ImGui::Begin("About ImGui", &show_app_about, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::Text("dear imgui, %s", ImGui::GetVersion()); + ImGui::Separator(); + ImGui::Text("By Omar Cornut and all github contributors."); + ImGui::Text("ImGui is licensed under the MIT License, see LICENSE for more information."); + ImGui::End(); + } + + static bool no_titlebar = false; + static bool no_border = true; + static bool no_resize = false; + static bool no_move = false; + static bool no_scrollbar = false; + static bool no_collapse = false; + static bool no_menu = false; + + // Demonstrate the various window flags. Typically you would just use the default. + ImGuiWindowFlags window_flags = 0; + if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar; + if (!no_border) window_flags |= ImGuiWindowFlags_ShowBorders; + if (no_resize) window_flags |= ImGuiWindowFlags_NoResize; + if (no_move) window_flags |= ImGuiWindowFlags_NoMove; + if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar; + if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse; + if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar; + ImGui::SetNextWindowSize(ImVec2(550,680), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("ImGui Demo", p_open, window_flags)) + { + // Early out if the window is collapsed, as an optimization. + ImGui::End(); + return; + } + + //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // 2/3 of the space for widget and 1/3 for labels + ImGui::PushItemWidth(-140); // Right align, keep 140 pixels for labels + + ImGui::Text("Dear ImGui says hello."); + + // Menu + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("Menu")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Examples")) + { + ImGui::MenuItem("Main menu bar", NULL, &show_app_main_menu_bar); + ImGui::MenuItem("Console", NULL, &show_app_console); + ImGui::MenuItem("Log", NULL, &show_app_log); + ImGui::MenuItem("Simple layout", NULL, &show_app_layout); + ImGui::MenuItem("Property editor", NULL, &show_app_property_editor); + ImGui::MenuItem("Long text display", NULL, &show_app_long_text); + ImGui::MenuItem("Auto-resizing window", NULL, &show_app_auto_resize); + ImGui::MenuItem("Constrained-resizing window", NULL, &show_app_constrained_resize); + ImGui::MenuItem("Simple overlay", NULL, &show_app_fixed_overlay); + ImGui::MenuItem("Manipulating window title", NULL, &show_app_manipulating_window_title); + ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Help")) + { + ImGui::MenuItem("Metrics", NULL, &show_app_metrics); + ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor); + ImGui::MenuItem("About ImGui", NULL, &show_app_about); + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + ImGui::Spacing(); + if (ImGui::CollapsingHeader("Help")) + { + ImGui::TextWrapped("This window is being created by the ShowTestWindow() function. Please refer to the code for programming reference.\n\nUser Guide:"); + ImGui::ShowUserGuide(); + } + + if (ImGui::CollapsingHeader("Window options")) + { + ImGui::Checkbox("No titlebar", &no_titlebar); ImGui::SameLine(150); + ImGui::Checkbox("No border", &no_border); ImGui::SameLine(300); + ImGui::Checkbox("No resize", &no_resize); + ImGui::Checkbox("No move", &no_move); ImGui::SameLine(150); + ImGui::Checkbox("No scrollbar", &no_scrollbar); ImGui::SameLine(300); + ImGui::Checkbox("No collapse", &no_collapse); + ImGui::Checkbox("No menu", &no_menu); + + if (ImGui::TreeNode("Style")) + { + ImGui::ShowStyleEditor(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Logging")) + { + ImGui::TextWrapped("The logging API redirects all text output so you can easily capture the content of a window or a block. Tree nodes can be automatically expanded. You can also call ImGui::LogText() to output directly to the log without a visual output."); + ImGui::LogButtons(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Widgets")) + { + if (ImGui::TreeNode("Trees")) + { + if (ImGui::TreeNode("Basic trees")) + { + for (int i = 0; i < 5; i++) + if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i)) + { + ImGui::Text("blah blah"); + ImGui::SameLine(); + if (ImGui::SmallButton("print")) printf("Child %d pressed", i); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Advanced, with Selectable nodes")) + { + ShowHelpMarker("This is a more standard looking tree with selectable nodes.\nClick to select, CTRL+Click to toggle, click on arrows or double-click to open."); + static bool align_label_with_current_x_position = false; + ImGui::Checkbox("Align label with current X position)", &align_label_with_current_x_position); + ImGui::Text("Hello!"); + if (align_label_with_current_x_position) + ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing()); + + static int selection_mask = (1 << 2); // Dumb representation of what may be user-side selection state. You may carry selection state inside or outside your objects in whatever format you see fit. + int node_clicked = -1; // Temporary storage of what node we have clicked to process selection at the end of the loop. May be a pointer to your own node type, etc. + ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize()*3); // Increase spacing to differentiate leaves from expanded contents. + for (int i = 0; i < 6; i++) + { + // Disable the default open on single-click behavior and pass in Selected flag according to our selection state. + ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ((selection_mask & (1 << i)) ? ImGuiTreeNodeFlags_Selected : 0); + if (i < 3) + { + // Node + bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i); + if (ImGui::IsItemClicked()) + node_clicked = i; + if (node_open) + { + ImGui::Text("Blah blah\nBlah Blah"); + ImGui::TreePop(); + } + } + else + { + // Leaf: The only reason we have a TreeNode at all is to allow selection of the leaf. Otherwise we can use BulletText() or TreeAdvanceToLabelPos()+Text(). + ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags | ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen, "Selectable Leaf %d", i); + if (ImGui::IsItemClicked()) + node_clicked = i; + } + } + if (node_clicked != -1) + { + // Update selection state. Process outside of tree loop to avoid visual inconsistencies during the clicking-frame. + if (ImGui::GetIO().KeyCtrl) + selection_mask ^= (1 << node_clicked); // CTRL+click to toggle + else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, this commented bit preserve selection when clicking on item that is part of the selection + selection_mask = (1 << node_clicked); // Click to single-select + } + ImGui::PopStyleVar(); + if (align_label_with_current_x_position) + ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing()); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Collapsing Headers")) + { + static bool closable_group = true; + if (ImGui::CollapsingHeader("Header")) + { + ImGui::Checkbox("Enable extra group", &closable_group); + for (int i = 0; i < 5; i++) + ImGui::Text("Some content %d", i); + } + if (ImGui::CollapsingHeader("Header with a close button", &closable_group)) + { + for (int i = 0; i < 5; i++) + ImGui::Text("More content %d", i); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Bullets")) + { + ImGui::BulletText("Bullet point 1"); + ImGui::BulletText("Bullet point 2\nOn multiple lines"); + ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); + ImGui::Bullet(); ImGui::SmallButton("Button"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colored Text")) + { + // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. + ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink"); + ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow"); + ImGui::TextDisabled("Disabled"); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Word Wrapping")) + { + // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. + ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules suitable for English and possibly other languages."); + ImGui::Spacing(); + + static float wrap_width = 200.0f; + ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); + + ImGui::Text("Test paragraph 1:"); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255)); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + ImGui::Text("lazy dog. This paragraph is made to fit within %.0f pixels. The quick brown fox jumps over the lazy dog.", wrap_width); + ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255)); + ImGui::PopTextWrapPos(); + + ImGui::Text("Test paragraph 2:"); + pos = ImGui::GetCursorScreenPos(); + ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(pos.x + wrap_width, pos.y), ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight()), IM_COL32(255,0,255,255)); + ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); + ImGui::Text("aaaaaaaa bbbbbbbb, cccccccc,dddddddd. eeeeeeee ffffffff. gggggggg!hhhhhhhh"); + ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255,255,0,255)); + ImGui::PopTextWrapPos(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("UTF-8 Text")) + { + // UTF-8 test with Japanese characters + // (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html) + // Most compiler appears to support UTF-8 in source code (with Visual Studio you need to save your file as 'UTF-8 without signature') + // However for the sake for maximum portability here we are *not* including raw UTF-8 character in this source file, instead we encode the string with hexadecimal constants. + // In your own application be reasonable and use UTF-8 in source or retrieve the data from file system! + // Note that characters values are preserved even if the font cannot be displayed, so you can safely copy & paste garbled characters into another application. + ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->LoadFromFileTTF() manually to load extra character ranges."); + ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); + ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); + static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; + ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Images")) + { + ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!"); + ImVec2 tex_screen_pos = ImGui::GetCursorScreenPos(); + float tex_w = (float)ImGui::GetIO().Fonts->TexWidth; + float tex_h = (float)ImGui::GetIO().Fonts->TexHeight; + ImTextureID tex_id = ImGui::GetIO().Fonts->TexID; + ImGui::Text("%.0fx%.0f", tex_w, tex_h); + ImGui::Image(tex_id, ImVec2(tex_w, tex_h), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + float focus_sz = 32.0f; + float focus_x = ImGui::GetMousePos().x - tex_screen_pos.x - focus_sz * 0.5f; if (focus_x < 0.0f) focus_x = 0.0f; else if (focus_x > tex_w - focus_sz) focus_x = tex_w - focus_sz; + float focus_y = ImGui::GetMousePos().y - tex_screen_pos.y - focus_sz * 0.5f; if (focus_y < 0.0f) focus_y = 0.0f; else if (focus_y > tex_h - focus_sz) focus_y = tex_h - focus_sz; + ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y); + ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz); + ImVec2 uv0 = ImVec2((focus_x) / tex_w, (focus_y) / tex_h); + ImVec2 uv1 = ImVec2((focus_x + focus_sz) / tex_w, (focus_y + focus_sz) / tex_h); + ImGui::Image(tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128)); + ImGui::EndTooltip(); + } + ImGui::TextWrapped("And now some textured buttons.."); + static int pressed_count = 0; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); + int frame_padding = -1 + i; // -1 = uses default padding + if (ImGui::ImageButton(tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/tex_w,32/tex_h), frame_padding, ImColor(0,0,0,255))) + pressed_count += 1; + ImGui::PopID(); + ImGui::SameLine(); + } + ImGui::NewLine(); + ImGui::Text("Pressed %d times.", pressed_count); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Selectables")) + { + if (ImGui::TreeNode("Basic")) + { + static bool selected[4] = { false, true, false, false }; + ImGui::Selectable("1. I am selectable", &selected[0]); + ImGui::Selectable("2. I am selectable", &selected[1]); + ImGui::Text("3. I am not selectable"); + ImGui::Selectable("4. I am selectable", &selected[2]); + if (ImGui::Selectable("5. I am double clickable", selected[3], ImGuiSelectableFlags_AllowDoubleClick)) + if (ImGui::IsMouseDoubleClicked(0)) + selected[3] = !selected[3]; + ImGui::TreePop(); + } + if (ImGui::TreeNode("Rendering more text into the same block")) + { + static bool selected[3] = { false, false, false }; + ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); + ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes"); + ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); + ImGui::TreePop(); + } + if (ImGui::TreeNode("In columns")) + { + ImGui::Columns(3, NULL, false); + static bool selected[16] = { 0 }; + for (int i = 0; i < 16; i++) + { + char label[32]; sprintf(label, "Item %d", i); + if (ImGui::Selectable(label, &selected[i])) {} + ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::TreePop(); + } + if (ImGui::TreeNode("Grid")) + { + static bool selected[16] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true }; + for (int i = 0; i < 16; i++) + { + ImGui::PushID(i); + if (ImGui::Selectable("Sailor", &selected[i], 0, ImVec2(50,50))) + { + int x = i % 4, y = i / 4; + if (x > 0) selected[i - 1] ^= 1; + if (x < 3) selected[i + 1] ^= 1; + if (y > 0) selected[i - 4] ^= 1; + if (y < 3) selected[i + 4] ^= 1; + } + if ((i % 4) < 3) ImGui::SameLine(); + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Filtered Text Input")) + { + static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); + static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); + static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); + static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); + static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); + struct TextFilters { static int FilterImGuiLetters(ImGuiTextEditCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } }; + static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); + + ImGui::Text("Password input"); + static char bufpass[64] = "password123"; + ImGui::InputText("password", bufpass, 64, ImGuiInputTextFlags_Password | ImGuiInputTextFlags_CharsNoBlank); + ImGui::SameLine(); ShowHelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n"); + ImGui::InputText("password (clear)", bufpass, 64, ImGuiInputTextFlags_CharsNoBlank); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Multi-line Text Input")) + { + static bool read_only = false; + static char text[1024*16] = + "/*\n" + " The Pentium F00F bug, shorthand for F0 0F C7 C8,\n" + " the hexadecimal encoding of one offending instruction,\n" + " more formally, the invalid operand with locked CMPXCHG8B\n" + " instruction bug, is a design flaw in the majority of\n" + " Intel Pentium, Pentium MMX, and Pentium OverDrive\n" + " processors (all in the P5 microarchitecture).\n" + "*/\n\n" + "label:\n" + "\tlock cmpxchg8b eax\n"; + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + ImGui::Checkbox("Read-only", &read_only); + ImGui::PopStyleVar(); + ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 16), ImGuiInputTextFlags_AllowTabInput | (read_only ? ImGuiInputTextFlags_ReadOnly : 0)); + ImGui::TreePop(); + } + + static bool a=false; + if (ImGui::Button("Button")) { printf("Clicked\n"); a ^= 1; } + if (a) + { + ImGui::SameLine(); + ImGui::Text("Thanks for clicking me!"); + } + + static bool check = true; + ImGui::Checkbox("checkbox", &check); + + static int e = 0; + ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); + ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); + ImGui::RadioButton("radio c", &e, 2); + + // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(i/7.0f, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(i/7.0f, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(i/7.0f, 0.8f, 0.8f)); + ImGui::Button("Click"); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + + ImGui::Text("Hover over me"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip"); + + ImGui::SameLine(); + ImGui::Text("- or me"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::Text("I am a fancy tooltip"); + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); + ImGui::EndTooltip(); + } + + // Testing IMGUI_ONCE_UPON_A_FRAME macro + //for (int i = 0; i < 5; i++) + //{ + // IMGUI_ONCE_UPON_A_FRAME + // { + // ImGui::Text("This will be displayed only once."); + // } + //} + + ImGui::Separator(); + + ImGui::LabelText("label", "Value"); + + static int item = 1; + ImGui::Combo("combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); // Combo using values packed in a single constant string (for really quick combo) + + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" }; + static int item2 = -1; + ImGui::Combo("combo scroll", &item2, items, IM_ARRAYSIZE(items)); // Combo using proper array. You can also pass a callback to retrieve array value, no need to create/copy an array just for that. + + { + static char str0[128] = "Hello, world!"; + static int i0=123; + static float f0=0.001f; + ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); + ImGui::SameLine(); ShowHelpMarker("Hold SHIFT or use mouse to select text.\n" "CTRL+Left/Right to word jump.\n" "CTRL+A or double-click to select all.\n" "CTRL+X,CTRL+C,CTRL+V clipboard.\n" "CTRL+Z,CTRL+Y undo/redo.\n" "ESCAPE to revert.\n"); + + ImGui::InputInt("input int", &i0); + ImGui::SameLine(); ShowHelpMarker("You can apply arithmetic operators +,*,/ on numerical values.\n e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\nUse +- to subtract.\n"); + + ImGui::InputFloat("input float", &f0, 0.01f, 1.0f); + + static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + ImGui::InputFloat3("input float3", vec4a); + } + + { + static int i1=50, i2=42; + ImGui::DragInt("drag int", &i1, 1); + ImGui::SameLine(); ShowHelpMarker("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input value."); + + ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%.0f%%"); + + static float f1=1.00f, f2=0.0067f; + ImGui::DragFloat("drag float", &f1, 0.005f); + ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); + } + + { + static int i1=0; + ImGui::SliderInt("slider int", &i1, -1, 3); + ImGui::SameLine(); ShowHelpMarker("CTRL+click to input value."); + + static float f1=0.123f, f2=0.0f; + ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); + ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f); + static float angle = 0.0f; + ImGui::SliderAngle("slider angle", &angle); + } + + static float col1[3] = { 1.0f,0.0f,0.2f }; + static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; + ImGui::ColorEdit3("color 1", col1); + ImGui::SameLine(); ShowHelpMarker("Click on the colored square to change edit mode.\nCTRL+click on individual component to input value.\n"); + + ImGui::ColorEdit4("color 2", col2); + + const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; + static int listbox_item_current = 1; + ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4); + + //static int listbox_item_current2 = 2; + //ImGui::PushItemWidth(-1); + //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4); + //ImGui::PopItemWidth(); + + if (ImGui::TreeNode("Range Widgets")) + { + ImGui::Unindent(); + + static float begin = 10, end = 90; + static int begin_i = 100, end_i = 1000; + ImGui::DragFloatRange2("range", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%"); + ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %.0f units", "Max: %.0f units"); + + ImGui::Indent(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Multi-component Widgets")) + { + ImGui::Unindent(); + + static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; + static int vec4i[4] = { 1, 5, 100, 255 }; + + ImGui::InputFloat2("input float2", vec4f); + ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); + ImGui::DragInt2("drag int2", vec4i, 1, 0, 255); + ImGui::InputInt2("input int2", vec4i); + ImGui::SliderInt2("slider int2", vec4i, 0, 255); + ImGui::Spacing(); + + ImGui::InputFloat3("input float3", vec4f); + ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); + ImGui::DragInt3("drag int3", vec4i, 1, 0, 255); + ImGui::InputInt3("input int3", vec4i); + ImGui::SliderInt3("slider int3", vec4i, 0, 255); + ImGui::Spacing(); + + ImGui::InputFloat4("input float4", vec4f); + ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f); + ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); + ImGui::InputInt4("input int4", vec4i); + ImGui::DragInt4("drag int4", vec4i, 1, 0, 255); + ImGui::SliderInt4("slider int4", vec4i, 0, 255); + + ImGui::Indent(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Vertical Sliders")) + { + ImGui::Unindent(); + const float spacing = 4; + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); + + static int int_value = 0; + ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5); + ImGui::SameLine(); + + static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; + ImGui::PushID("set1"); + for (int i = 0; i < 7; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor::HSV(i/7.0f, 0.5f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImColor::HSV(i/7.0f, 0.6f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImColor::HSV(i/7.0f, 0.7f, 0.5f)); + ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor::HSV(i/7.0f, 0.9f, 0.9f)); + ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values[i]); + ImGui::PopStyleColor(4); + ImGui::PopID(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set2"); + static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; + const int rows = 3; + const ImVec2 small_slider_size(18, (160.0f-(rows-1)*spacing)/rows); + for (int nx = 0; nx < 4; nx++) + { + if (nx > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + for (int ny = 0; ny < rows; ny++) + { + ImGui::PushID(nx*rows+ny); + ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); + if (ImGui::IsItemActive() || ImGui::IsItemHovered()) + ImGui::SetTooltip("%.3f", values2[nx]); + ImGui::PopID(); + } + ImGui::EndGroup(); + } + ImGui::PopID(); + + ImGui::SameLine(); + ImGui::PushID("set3"); + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); + ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f\nsec"); + ImGui::PopStyleVar(); + ImGui::PopID(); + } + ImGui::PopID(); + ImGui::PopStyleVar(); + + ImGui::Indent(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Graphs widgets")) + { + static bool animate = true; + ImGui::Checkbox("Animate", &animate); + + static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; + ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); + + // Create a dummy array of contiguous float values to plot + // Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float and the sizeof() of your structure in the Stride parameter. + static float values[90] = { 0 }; + static int values_offset = 0; + if (animate) + { + static float refresh_time = ImGui::GetTime(); // Create dummy data at fixed 60 hz rate for the demo + for (; ImGui::GetTime() > refresh_time + 1.0f/60.0f; refresh_time += 1.0f/60.0f) + { + static float phase = 0.0f; + values[values_offset] = cosf(phase); + values_offset = (values_offset+1) % IM_ARRAYSIZE(values); + phase += 0.10f*values_offset; + } + } + ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80)); + + // Use functions to generate output + // FIXME: This is rather awkward because current plot API only pass in indices. We probably want an API passing floats and user provide sample rate/count. + struct Funcs + { + static float Sin(void*, int i) { return sinf(i * 0.1f); } + static float Saw(void*, int i) { return (i & 1) ? 1.0f : 0.0f; } + }; + static int func_type = 0, display_count = 70; + ImGui::Separator(); + ImGui::PushItemWidth(100); ImGui::Combo("func", &func_type, "Sin\0Saw\0"); ImGui::PopItemWidth(); + ImGui::SameLine(); + ImGui::SliderInt("Sample count", &display_count, 1, 400); + float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw; + ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0,80)); + ImGui::Separator(); + + // Animate a simple progress bar + static float progress = 0.0f, progress_dir = 1.0f; + if (animate) + { + progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime; + if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; } + if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; } + } + + // Typically we would use ImVec2(-1.0f,0.0f) to use all available width, or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth. + ImGui::ProgressBar(progress, ImVec2(0.0f,0.0f)); + ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x); + ImGui::Text("Progress Bar"); + + float progress_saturated = (progress < 0.0f) ? 0.0f : (progress > 1.0f) ? 1.0f : progress; + char buf[32]; + sprintf(buf, "%d/%d", (int)(progress_saturated*1753), 1753); + ImGui::ProgressBar(progress, ImVec2(0.f,0.f), buf); + } + + if (ImGui::CollapsingHeader("Layout")) + { + if (ImGui::TreeNode("Child regions")) + { + ImGui::Text("Without border"); + static int line = 50; + bool goto_line = ImGui::Button("Goto"); + ImGui::SameLine(); + ImGui::PushItemWidth(100); + goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); + ImGui::PopItemWidth(); + ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f,300), false, ImGuiWindowFlags_HorizontalScrollbar); + for (int i = 0; i < 100; i++) + { + ImGui::Text("%04d: scrollable region", i); + if (goto_line && line == i) + ImGui::SetScrollHere(); + } + if (goto_line && line >= 100) + ImGui::SetScrollHere(); + ImGui::EndChild(); + + ImGui::SameLine(); + + ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 5.0f); + ImGui::BeginChild("Sub2", ImVec2(0,300), true); + ImGui::Text("With border"); + ImGui::Columns(2); + for (int i = 0; i < 100; i++) + { + if (i == 50) + ImGui::NextColumn(); + char buf[32]; + sprintf(buf, "%08x", i*5731); + ImGui::Button(buf, ImVec2(-1.0f, 0.0f)); + } + ImGui::EndChild(); + ImGui::PopStyleVar(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Widgets Width")) + { + static float f = 0.0f; + ImGui::Text("PushItemWidth(100)"); + ImGui::SameLine(); ShowHelpMarker("Fixed width."); + ImGui::PushItemWidth(100); + ImGui::DragFloat("float##1", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(GetWindowWidth() * 0.5f)"); + ImGui::SameLine(); ShowHelpMarker("Half of window width."); + ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); + ImGui::DragFloat("float##2", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(GetContentRegionAvailWidth() * 0.5f)"); + ImGui::SameLine(); ShowHelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)"); + ImGui::PushItemWidth(ImGui::GetContentRegionAvailWidth() * 0.5f); + ImGui::DragFloat("float##3", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(-100)"); + ImGui::SameLine(); ShowHelpMarker("Align to right edge minus 100"); + ImGui::PushItemWidth(-100); + ImGui::DragFloat("float##4", &f); + ImGui::PopItemWidth(); + + ImGui::Text("PushItemWidth(-1)"); + ImGui::SameLine(); ShowHelpMarker("Align to right edge"); + ImGui::PushItemWidth(-1); + ImGui::DragFloat("float##5", &f); + ImGui::PopItemWidth(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Basic Horizontal Layout")) + { + ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceding item)"); + + // Text + ImGui::Text("Two items: Hello"); ImGui::SameLine(); + ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); + + // Adjust spacing + ImGui::Text("More spacing: Hello"); ImGui::SameLine(0, 20); + ImGui::TextColored(ImVec4(1,1,0,1), "Sailor"); + + // Button + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::Text("Normal buttons"); ImGui::SameLine(); + ImGui::Button("Banana"); ImGui::SameLine(); + ImGui::Button("Apple"); ImGui::SameLine(); + ImGui::Button("Corniflower"); + + // Button + ImGui::Text("Small buttons"); ImGui::SameLine(); + ImGui::SmallButton("Like this one"); ImGui::SameLine(); + ImGui::Text("can fit within a text block."); + + // Aligned to arbitrary position. Easy/cheap column. + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::Text("x=150"); + ImGui::SameLine(300); ImGui::Text("x=300"); + ImGui::Text("Aligned"); + ImGui::SameLine(150); ImGui::SmallButton("x=150"); + ImGui::SameLine(300); ImGui::SmallButton("x=300"); + + // Checkbox + static bool c1=false,c2=false,c3=false,c4=false; + ImGui::Checkbox("My", &c1); ImGui::SameLine(); + ImGui::Checkbox("Tailor", &c2); ImGui::SameLine(); + ImGui::Checkbox("Is", &c3); ImGui::SameLine(); + ImGui::Checkbox("Rich", &c4); + + // Various + static float f0=1.0f, f1=2.0f, f2=3.0f; + ImGui::PushItemWidth(80); + const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; + static int item = -1; + ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); + ImGui::SliderFloat("X", &f0, 0.0f,5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Y", &f1, 0.0f,5.0f); ImGui::SameLine(); + ImGui::SliderFloat("Z", &f2, 0.0f,5.0f); + ImGui::PopItemWidth(); + + ImGui::PushItemWidth(80); + ImGui::Text("Lists:"); + static int selection[4] = { 0, 1, 2, 3 }; + for (int i = 0; i < 4; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::PushID(i); + ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items)); + ImGui::PopID(); + //if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i); + } + ImGui::PopItemWidth(); + + // Dummy + ImVec2 sz(30,30); + ImGui::Button("A", sz); ImGui::SameLine(); + ImGui::Dummy(sz); ImGui::SameLine(); + ImGui::Button("B", sz); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Groups")) + { + ImGui::TextWrapped("(Using ImGui::BeginGroup()/EndGroup() to layout items. BeginGroup() basically locks the horizontal position. EndGroup() bundles the whole group so that you can use functions such as IsItemHovered() on it.)"); + ImGui::BeginGroup(); + { + ImGui::BeginGroup(); + ImGui::Button("AAA"); + ImGui::SameLine(); + ImGui::Button("BBB"); + ImGui::SameLine(); + ImGui::BeginGroup(); + ImGui::Button("CCC"); + ImGui::Button("DDD"); + ImGui::EndGroup(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("Group hovered"); + ImGui::SameLine(); + ImGui::Button("EEE"); + ImGui::EndGroup(); + } + // Capture the group size and create widgets using the same size + ImVec2 size = ImGui::GetItemRectSize(); + const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; + ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); + + ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); + ImGui::SameLine(); + ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); + ImGui::EndGroup(); + ImGui::SameLine(); + + ImGui::Button("LEVERAGE\nBUZZWORD", size); + ImGui::SameLine(); + + ImGui::ListBoxHeader("List", size); + ImGui::Selectable("Selected", true); + ImGui::Selectable("Not Selected", false); + ImGui::ListBoxFooter(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Text Baseline Alignment")) + { + ImGui::TextWrapped("(This is testing the vertical alignment that occurs on text to keep it at the same baseline as widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets)"); + + ImGui::Text("One\nTwo\nThree"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("One\nTwo\nThree"); + + ImGui::Button("HOP##1"); ImGui::SameLine(); + ImGui::Text("Banana"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Button("HOP##2"); ImGui::SameLine(); + ImGui::Text("Hello\nWorld"); ImGui::SameLine(); + ImGui::Text("Banana"); + + ImGui::Button("TEST##1"); ImGui::SameLine(); + ImGui::Text("TEST"); ImGui::SameLine(); + ImGui::SmallButton("TEST##2"); + + ImGui::AlignFirstTextHeightToWidgets(); // If your line starts with text, call this to align it to upcoming widgets. + ImGui::Text("Text aligned to Widget"); ImGui::SameLine(); + ImGui::Button("Widget##1"); ImGui::SameLine(); + ImGui::Text("Widget"); ImGui::SameLine(); + ImGui::SmallButton("Widget##2"); + + // Tree + const float spacing = ImGui::GetStyle().ItemInnerSpacing.x; + ImGui::Button("Button##1"); + ImGui::SameLine(0.0f, spacing); + if (ImGui::TreeNode("Node##1")) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + + ImGui::AlignFirstTextHeightToWidgets(); // Vertically align text node a bit lower so it'll be vertically centered with upcoming widget. Otherwise you can use SmallButton (smaller fit). + bool node_open = ImGui::TreeNode("Node##2"); // Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add child content. + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2"); + if (node_open) { for (int i = 0; i < 6; i++) ImGui::BulletText("Item %d..", i); ImGui::TreePop(); } // Dummy tree data + + // Bullet + ImGui::Button("Button##3"); + ImGui::SameLine(0.0f, spacing); + ImGui::BulletText("Bullet text"); + + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::BulletText("Node"); + ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##4"); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Scrolling")) + { + ImGui::TextWrapped("(Use SetScrollHere() or SetScrollFromPosY() to scroll to a given position.)"); + static bool track = true; + static int track_line = 50, scroll_to_px = 200; + ImGui::Checkbox("Track", &track); + ImGui::PushItemWidth(100); + ImGui::SameLine(130); track |= ImGui::DragInt("##line", &track_line, 0.25f, 0, 99, "Line %.0f"); + bool scroll_to = ImGui::Button("Scroll To"); + ImGui::SameLine(130); scroll_to |= ImGui::DragInt("##pos_y", &scroll_to_px, 1.00f, 0, 9999, "y = %.0f px"); + ImGui::PopItemWidth(); + if (scroll_to) track = false; + + for (int i = 0; i < 5; i++) + { + if (i > 0) ImGui::SameLine(); + ImGui::BeginGroup(); + ImGui::Text("%s", i == 0 ? "Top" : i == 1 ? "25%" : i == 2 ? "Center" : i == 3 ? "75%" : "Bottom"); + ImGui::BeginChild(ImGui::GetID((void*)(intptr_t)i), ImVec2(ImGui::GetWindowWidth() * 0.17f, 200.0f), true); + if (scroll_to) + ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_px, i * 0.25f); + for (int line = 0; line < 100; line++) + { + if (track && line == track_line) + { + ImGui::TextColored(ImColor(255,255,0), "Line %d", line); + ImGui::SetScrollHere(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom + } + else + { + ImGui::Text("Line %d", line); + } + } + ImGui::EndChild(); + ImGui::EndGroup(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Horizontal Scrolling")) + { + ImGui::Bullet(); ImGui::TextWrapped("Horizontal scrolling for a window has to be enabled explicitly via the ImGuiWindowFlags_HorizontalScrollbar flag."); + ImGui::Bullet(); ImGui::TextWrapped("You may want to explicitly specify content width by calling SetNextWindowContentWidth() before Begin()."); + static int lines = 7; + ImGui::SliderInt("Lines", &lines, 1, 15); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f)); + ImGui::BeginChild("scrolling", ImVec2(0, ImGui::GetItemsLineHeightWithSpacing()*7 + 30), true, ImGuiWindowFlags_HorizontalScrollbar); + for (int line = 0; line < lines; line++) + { + // Display random stuff + int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3); + for (int n = 0; n < num_buttons; n++) + { + if (n > 0) ImGui::SameLine(); + ImGui::PushID(n + line * 1000); + char num_buf[16]; + const char* label = (!(n%15)) ? "FizzBuzz" : (!(n%3)) ? "Fizz" : (!(n%5)) ? "Buzz" : (sprintf(num_buf, "%d", n), num_buf); + float hue = n*0.05f; + ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(hue, 0.6f, 0.6f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(hue, 0.7f, 0.7f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(hue, 0.8f, 0.8f)); + ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f)); + ImGui::PopStyleColor(3); + ImGui::PopID(); + } + } + ImGui::EndChild(); + ImGui::PopStyleVar(2); + float scroll_x_delta = 0.0f; + ImGui::SmallButton("<<"); if (ImGui::IsItemActive()) scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f; + ImGui::SameLine(); ImGui::Text("Scroll from code"); ImGui::SameLine(); + ImGui::SmallButton(">>"); if (ImGui::IsItemActive()) scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f; + if (scroll_x_delta != 0.0f) + { + ImGui::BeginChild("scrolling"); // Demonstrate a trick: you can use Begin to set yourself in the context of another window (here we are already out of your child window) + ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta); + ImGui::End(); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Clipping")) + { + static ImVec2 size(100, 100), offset(50, 20); + ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text CPU-side if it won't fit in its frame. Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and CPU/GPU rendering cost."); + ImGui::DragFloat2("size", (float*)&size, 0.5f, 0.0f, 200.0f, "%.0f"); + ImGui::TextWrapped("(Click and drag)"); + ImVec2 pos = ImGui::GetCursorScreenPos(); + ImVec4 clip_rect(pos.x, pos.y, pos.x+size.x, pos.y+size.y); + ImGui::InvisibleButton("##dummy", size); + if (ImGui::IsItemActive() && ImGui::IsMouseDragging()) { offset.x += ImGui::GetIO().MouseDelta.x; offset.y += ImGui::GetIO().MouseDelta.y; } + ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x+size.x,pos.y+size.y), ImColor(90,90,120,255)); + ImGui::GetWindowDrawList()->AddText(ImGui::GetFont(), ImGui::GetFontSize()*2.0f, ImVec2(pos.x+offset.x,pos.y+offset.y), ImColor(255,255,255,255), "Line 1 hello\nLine 2 clip me!", NULL, 0.0f, &clip_rect); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Popups & Modal windows")) + { + if (ImGui::TreeNode("Popups")) + { + ImGui::TextWrapped("When a popup is active, it inhibits interacting with windows that are behind the popup. Clicking outside the popup closes it."); + + static int selected_fish = -1; + const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; + static bool toggles[] = { true, false, false, false, false }; + + if (ImGui::Button("Select..")) + ImGui::OpenPopup("select"); + ImGui::SameLine(); + ImGui::Text(selected_fish == -1 ? "<None>" : names[selected_fish]); + if (ImGui::BeginPopup("select")) + { + ImGui::Text("Aquarium"); + ImGui::Separator(); + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + if (ImGui::Selectable(names[i])) + selected_fish = i; + ImGui::EndPopup(); + } + + if (ImGui::Button("Toggle..")) + ImGui::OpenPopup("toggle"); + if (ImGui::BeginPopup("toggle")) + { + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + ImGui::EndMenu(); + } + + ImGui::Separator(); + ImGui::Text("Tooltip here"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("I am a tooltip over a popup"); + + if (ImGui::Button("Stacked Popup")) + ImGui::OpenPopup("another popup"); + if (ImGui::BeginPopup("another popup")) + { + for (int i = 0; i < IM_ARRAYSIZE(names); i++) + ImGui::MenuItem(names[i], "", &toggles[i]); + if (ImGui::BeginMenu("Sub-menu")) + { + ImGui::MenuItem("Click me"); + ImGui::EndMenu(); + } + ImGui::EndPopup(); + } + ImGui::EndPopup(); + } + + if (ImGui::Button("Popup Menu..")) + ImGui::OpenPopup("popup from button"); + if (ImGui::BeginPopup("popup from button")) + { + ShowExampleMenuFile(); + ImGui::EndPopup(); + } + + ImGui::Spacing(); + ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!"); + ImGui::Separator(); + // NB: As a quirk in this very specific example, we want to differentiate the parent of this menu from the parent of the various popup menus above. + // To do so we are encloding the items in a PushID()/PopID() block to make them two different menusets. If we don't, opening any popup above and hovering our menu here + // would open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it, which is the desired behavior for regular menus. + ImGui::PushID("foo"); + ImGui::MenuItem("Menu item", "CTRL+M"); + if (ImGui::BeginMenu("Menu inside a regular window")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::PopID(); + ImGui::Separator(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Context menus")) + { + static float value = 0.5f; + ImGui::Text("Value = %.3f (<-- right-click here)", value); + if (ImGui::BeginPopupContextItem("item context menu")) + { + if (ImGui::Selectable("Set to zero")) value = 0.0f; + if (ImGui::Selectable("Set to PI")) value = 3.1415f; + ImGui::EndPopup(); + } + + static ImVec4 color = ImColor(0.8f, 0.5f, 1.0f, 1.0f); + ImGui::ColorButton(color); + if (ImGui::BeginPopupContextItem("color context menu")) + { + ImGui::Text("Edit color"); + ImGui::ColorEdit3("##edit", (float*)&color); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::SameLine(); ImGui::Text("(<-- right-click here)"); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Modals")) + { + ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside the window."); + + if (ImGui::Button("Delete..")) + ImGui::OpenPopup("Delete?"); + if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n"); + ImGui::Separator(); + + //static int dummy_i = 0; + //ImGui::Combo("Combo", &dummy_i, "Delete\0Delete harder\0"); + + static bool dont_ask_me_next_time = false; + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time); + ImGui::PopStyleVar(); + + if (ImGui::Button("OK", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); } + ImGui::SameLine(); + if (ImGui::Button("Cancel", ImVec2(120,0))) { ImGui::CloseCurrentPopup(); } + ImGui::EndPopup(); + } + + if (ImGui::Button("Stacked modals..")) + ImGui::OpenPopup("Stacked 1"); + if (ImGui::BeginPopupModal("Stacked 1")) + { + ImGui::Text("Hello from Stacked The First"); + + if (ImGui::Button("Another one..")) + ImGui::OpenPopup("Stacked 2"); + if (ImGui::BeginPopupModal("Stacked 2")) + { + ImGui::Text("Hello from Stacked The Second"); + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + if (ImGui::Button("Close")) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Columns")) + { + // Basic columns + if (ImGui::TreeNode("Basic")) + { + ImGui::Text("Without border:"); + ImGui::Columns(3, "mycolumns3", false); // 3-ways, no border + ImGui::Separator(); + for (int n = 0; n < 14; n++) + { + char label[32]; + sprintf(label, "Item %d", n); + if (ImGui::Selectable(label)) {} + //if (ImGui::Button(label, ImVec2(-1,0))) {} + ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + + ImGui::Text("With border:"); + ImGui::Columns(4, "mycolumns"); // 4-ways, with border + ImGui::Separator(); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Text("Flags"); ImGui::NextColumn(); + ImGui::Separator(); + const char* names[3] = { "One", "Two", "Three" }; + const char* paths[3] = { "/path/one", "/path/two", "/path/three" }; + static int selected = -1; + for (int i = 0; i < 3; i++) + { + char label[32]; + sprintf(label, "%04d", i); + if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns)) + selected = i; + ImGui::NextColumn(); + ImGui::Text(names[i]); ImGui::NextColumn(); + ImGui::Text(paths[i]); ImGui::NextColumn(); + ImGui::Text("...."); ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + // Scrolling columns + /* + if (ImGui::TreeNode("Scrolling")) + { + ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y)); + ImGui::Columns(3); + ImGui::Text("ID"); ImGui::NextColumn(); + ImGui::Text("Name"); ImGui::NextColumn(); + ImGui::Text("Path"); ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::EndChild(); + ImGui::BeginChild("##scrollingregion", ImVec2(0, 60)); + ImGui::Columns(3); + for (int i = 0; i < 10; i++) + { + ImGui::Text("%04d", i); ImGui::NextColumn(); + ImGui::Text("Foobar"); ImGui::NextColumn(); + ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::EndChild(); + ImGui::TreePop(); + } + */ + + // Create multiple items in a same cell before switching to next column + if (ImGui::TreeNode("Mixed items")) + { + ImGui::Columns(3, "mixed"); + ImGui::Separator(); + + ImGui::Text("Hello"); + ImGui::Button("Banana"); + ImGui::NextColumn(); + + ImGui::Text("ImGui"); + ImGui::Button("Apple"); + static float foo = 1.0f; + ImGui::InputFloat("red", &foo, 0.05f, 0, 3); + ImGui::Text("An extra line here."); + ImGui::NextColumn(); + + ImGui::Text("Sailor"); + ImGui::Button("Corniflower"); + static float bar = 1.0f; + ImGui::InputFloat("blue", &bar, 0.05f, 0, 3); + ImGui::NextColumn(); + + if (ImGui::CollapsingHeader("Category A")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category B")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + if (ImGui::CollapsingHeader("Category C")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + // Word wrapping + if (ImGui::TreeNode("Word-wrapping")) + { + ImGui::Columns(2, "word-wrapping"); + ImGui::Separator(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Left"); + ImGui::NextColumn(); + ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); + ImGui::TextWrapped("Hello Right"); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Borders")) + { + static bool h_borders = true; + static bool v_borders = true; + ImGui::Checkbox("horizontal", &h_borders); + ImGui::SameLine(); + ImGui::Checkbox("vertical", &v_borders); + ImGui::Columns(4, NULL, v_borders); + if (h_borders) ImGui::Separator(); + for (int i = 0; i < 8; i++) + { + ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); + ImGui::NextColumn(); + } + ImGui::Columns(1); + if (h_borders) ImGui::Separator(); + ImGui::TreePop(); + } + + bool node_open = ImGui::TreeNode("Tree within single cell"); + ImGui::SameLine(); ShowHelpMarker("NB: Tree node must be poped before ending the cell.\nThere's no storage of state per-cell."); + if (node_open) + { + ImGui::Columns(2, "tree items"); + ImGui::Separator(); + if (ImGui::TreeNode("Hello")) { ImGui::BulletText("Sailor"); ImGui::TreePop(); } ImGui::NextColumn(); + if (ImGui::TreeNode("Bonjour")) { ImGui::BulletText("Marin"); ImGui::TreePop(); } ImGui::NextColumn(); + ImGui::Columns(1); + ImGui::Separator(); + ImGui::TreePop(); + } + } + + if (ImGui::CollapsingHeader("Filtering")) + { + static ImGuiTextFilter filter; + ImGui::Text("Filter usage:\n" + " \"\" display all lines\n" + " \"xxx\" display lines containing \"xxx\"\n" + " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" + " \"-xxx\" hide lines containing \"xxx\""); + filter.Draw(); + const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; + for (int i = 0; i < IM_ARRAYSIZE(lines); i++) + if (filter.PassFilter(lines[i])) + ImGui::BulletText("%s", lines[i]); + } + + if (ImGui::CollapsingHeader("Keyboard, Mouse & Focus")) + { + if (ImGui::TreeNode("Tabbing")) + { + ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields."); + static char buf[32] = "dummy"; + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); + ImGui::PushAllowKeyboardFocus(false); + ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); + //ImGui::SameLine(); ShowHelperMarker("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); + ImGui::PopAllowKeyboardFocus(); + ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Focus from code")) + { + bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); + bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); + bool focus_3 = ImGui::Button("Focus on 3"); + int has_focus = 0; + static char buf[128] = "click on a button to set focus"; + + if (focus_1) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 1; + + if (focus_2) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 2; + + ImGui::PushAllowKeyboardFocus(false); + if (focus_3) ImGui::SetKeyboardFocusHere(); + ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); + if (ImGui::IsItemActive()) has_focus = 3; + ImGui::PopAllowKeyboardFocus(); + if (has_focus) + ImGui::Text("Item with focus: %d", has_focus); + else + ImGui::Text("Item with focus: <none>"); + ImGui::TextWrapped("Cursor & selection are preserved when refocusing last used item in code."); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Dragging")) + { + ImGui::TextWrapped("You can use ImGui::GetItemActiveDragDelta() to query for the dragged amount on any widget."); + ImGui::Button("Drag Me"); + if (ImGui::IsItemActive()) + { + // Draw a line between the button and the mouse cursor + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + draw_list->PushClipRectFullScreen(); + draw_list->AddLine(ImGui::CalcItemRectClosestPoint(ImGui::GetIO().MousePos, true, -2.0f), ImGui::GetIO().MousePos, ImColor(ImGui::GetStyle().Colors[ImGuiCol_Button]), 4.0f); + draw_list->PopClipRect(); + ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f); + ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0); + ImVec2 mouse_delta = ImGui::GetIO().MouseDelta; + ImGui::SameLine(); ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f), MouseDelta (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y, mouse_delta.x, mouse_delta.y); + } + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Keyboard & Mouse State")) + { + ImGuiIO& io = ImGui::GetIO(); + + ImGui::Text("MousePos: (%g, %g)", io.MousePos.x, io.MousePos.y); + ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); } + ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse dbl-clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); } + ImGui::Text("MouseWheel: %.1f", io.MouseWheel); + + ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (%.02f secs)", i, io.KeysDownDuration[i]); } + ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d", i); } + ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d", i); } + ImGui::Text("KeyMods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : ""); + + ImGui::Text("WantCaptureMouse: %s", io.WantCaptureMouse ? "true" : "false"); + ImGui::Text("WantCaptureKeyboard: %s", io.WantCaptureKeyboard ? "true" : "false"); + ImGui::Text("WantTextInput: %s", io.WantTextInput ? "true" : "false"); + + ImGui::Button("Hovering me sets the\nkeyboard capture flag"); + if (ImGui::IsItemHovered()) + ImGui::CaptureKeyboardFromApp(true); + ImGui::SameLine(); + ImGui::Button("Holding me clears the\nthe keyboard capture flag"); + if (ImGui::IsItemActive()) + ImGui::CaptureKeyboardFromApp(false); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Mouse cursors")) + { + ImGui::TextWrapped("Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. You can also set io.MouseDrawCursor to ask ImGui to render the cursor for you in software."); + ImGui::Checkbox("io.MouseDrawCursor", &ImGui::GetIO().MouseDrawCursor); + ImGui::Text("Hover to see mouse cursors:"); + for (int i = 0; i < ImGuiMouseCursor_Count_; i++) + { + char label[32]; + sprintf(label, "Mouse cursor %d", i); + ImGui::Bullet(); ImGui::Selectable(label, false); + if (ImGui::IsItemHovered()) + ImGui::SetMouseCursor(i); + } + ImGui::TreePop(); + } + } + + ImGui::End(); +} + +void ImGui::ShowStyleEditor(ImGuiStyle* ref) +{ + ImGuiStyle& style = ImGui::GetStyle(); + + // You can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it compares to the default style) + const ImGuiStyle default_style; // Default style + if (ImGui::Button("Revert Style")) + style = ref ? *ref : default_style; + + if (ref) + { + ImGui::SameLine(); + if (ImGui::Button("Save Style")) + *ref = style; + } + + ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.55f); + + if (ImGui::TreeNode("Rendering")) + { + ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines); + ImGui::Checkbox("Anti-aliased shapes", &style.AntiAliasedShapes); + ImGui::PushItemWidth(100); + ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, FLT_MAX, NULL, 2.0f); + if (style.CurveTessellationTol < 0.0f) style.CurveTessellationTol = 0.10f; + ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero. + ImGui::PopItemWidth(); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Settings")) + { + ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat("ChildWindowRounding", &style.ChildWindowRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); + ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); + ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f"); + ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 16.0f, "%.0f"); + ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); + ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 16.0f, "%.0f"); + ImGui::Text("Alignment"); + ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f"); + ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f"); ImGui::SameLine(); ShowHelpMarker("Alignment applies when a button is larger than its text content."); + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Colors")) + { + static int output_dest = 0; + static bool output_only_modified = false; + if (ImGui::Button("Copy Colors")) + { + if (output_dest == 0) + ImGui::LogToClipboard(); + else + ImGui::LogToTTY(); + ImGui::LogText("ImGuiStyle& style = ImGui::GetStyle();" IM_NEWLINE); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const ImVec4& col = style.Colors[i]; + const char* name = ImGui::GetStyleColName(i); + if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0) + ImGui::LogText("style.Colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE, name, 22 - (int)strlen(name), "", col.x, col.y, col.z, col.w); + } + ImGui::LogFinish(); + } + ImGui::SameLine(); ImGui::PushItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0"); ImGui::PopItemWidth(); + ImGui::SameLine(); ImGui::Checkbox("Only Modified Fields", &output_only_modified); + + static ImGuiColorEditMode edit_mode = ImGuiColorEditMode_RGB; + ImGui::RadioButton("RGB", &edit_mode, ImGuiColorEditMode_RGB); + ImGui::SameLine(); + ImGui::RadioButton("HSV", &edit_mode, ImGuiColorEditMode_HSV); + ImGui::SameLine(); + ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX); + //ImGui::Text("Tip: Click on colored square to change edit mode."); + + static ImGuiTextFilter filter; + filter.Draw("Filter colors", 200); + + ImGui::BeginChild("#colors", ImVec2(0, 300), true, ImGuiWindowFlags_AlwaysVerticalScrollbar); + ImGui::PushItemWidth(-160); + ImGui::ColorEditMode(edit_mode); + for (int i = 0; i < ImGuiCol_COUNT; i++) + { + const char* name = ImGui::GetStyleColName(i); + if (!filter.PassFilter(name)) + continue; + ImGui::PushID(i); + ImGui::ColorEdit4(name, (float*)&style.Colors[i], true); + if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &default_style.Colors[i]), sizeof(ImVec4)) != 0) + { + ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : default_style.Colors[i]; + if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; } + } + ImGui::PopID(); + } + ImGui::PopItemWidth(); + ImGui::EndChild(); + + ImGui::TreePop(); + } + + if (ImGui::TreeNode("Fonts", "Fonts (%d)", ImGui::GetIO().Fonts->Fonts.Size)) + { + ImGui::SameLine(); ShowHelpMarker("Tip: Load fonts with io.Fonts->AddFontFromFileTTF()\nbefore calling io.Fonts->GetTex* functions."); + ImFontAtlas* atlas = ImGui::GetIO().Fonts; + if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight)) + { + ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); + ImGui::TreePop(); + } + ImGui::PushItemWidth(100); + for (int i = 0; i < atlas->Fonts.Size; i++) + { + ImFont* font = atlas->Fonts[i]; + ImGui::BulletText("Font %d: \'%s\', %.2f px, %d glyphs", i, font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size); + ImGui::TreePush((void*)(intptr_t)i); + if (i > 0) { ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { atlas->Fonts[i] = atlas->Fonts[0]; atlas->Fonts[0] = font; } } + ImGui::PushFont(font); + ImGui::Text("The quick brown fox jumps over the lazy dog"); + ImGui::PopFont(); + if (ImGui::TreeNode("Details")) + { + ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font + ImGui::SameLine(); ShowHelpMarker("Note than the default embedded font is NOT meant to be scaled.\n\nFont are currently rendered into bitmaps at a given size at the time of building the atlas. You may oversample them to get some flexibility with scaling. You can also render at multiple sizes and select which one to use at runtime.\n\n(Glimmer of hope: the atlas system should hopefully be rewritten in the future to make scaling more natural and automatic.)"); + ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent); + ImGui::Text("Fallback character: '%c' (%d)", font->FallbackChar, font->FallbackChar); + for (int config_i = 0; config_i < font->ConfigDataCount; config_i++) + { + ImFontConfig* cfg = &font->ConfigData[config_i]; + ImGui::BulletText("Input %d: \'%s\'\nOversample: (%d,%d), PixelSnapH: %d", config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH); + } + if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size)) + { + // Display all glyphs of the fonts in separate pages of 256 characters + const ImFont::Glyph* glyph_fallback = font->FallbackGlyph; // Forcefully/dodgily make FindGlyph() return NULL on fallback, which isn't the default behavior. + font->FallbackGlyph = NULL; + for (int base = 0; base < 0x10000; base += 256) + { + int count = 0; + for (int n = 0; n < 256; n++) + count += font->FindGlyph((ImWchar)(base + n)) ? 1 : 0; + if (count > 0 && ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base+255, count, count > 1 ? "glyphs" : "glyph")) + { + float cell_spacing = style.ItemSpacing.y; + ImVec2 cell_size(font->FontSize * 1, font->FontSize * 1); + ImVec2 base_pos = ImGui::GetCursorScreenPos(); + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + for (int n = 0; n < 256; n++) + { + ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size.x + cell_spacing), base_pos.y + (n / 16) * (cell_size.y + cell_spacing)); + ImVec2 cell_p2(cell_p1.x + cell_size.x, cell_p1.y + cell_size.y); + const ImFont::Glyph* glyph = font->FindGlyph((ImWchar)(base+n));; + draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255,255,255,100) : IM_COL32(255,255,255,50)); + font->RenderChar(draw_list, cell_size.x, cell_p1, ImGui::GetColorU32(ImGuiCol_Text), (ImWchar)(base+n)); // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions available to generate a string. + if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2)) + { + ImGui::BeginTooltip(); + ImGui::Text("Codepoint: U+%04X", base+n); + ImGui::Separator(); + ImGui::Text("XAdvance+1: %.1f", glyph->XAdvance); + ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1); + ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1); + ImGui::EndTooltip(); + } + } + ImGui::Dummy(ImVec2((cell_size.x + cell_spacing) * 16, (cell_size.y + cell_spacing) * 16)); + ImGui::TreePop(); + } + } + font->FallbackGlyph = glyph_fallback; + ImGui::TreePop(); + } + ImGui::TreePop(); + } + ImGui::TreePop(); + } + static float window_scale = 1.0f; + ImGui::DragFloat("this window scale", &window_scale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale only this window + ImGui::DragFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.005f, 0.3f, 2.0f, "%.1f"); // scale everything + ImGui::PopItemWidth(); + ImGui::SetWindowFontScale(window_scale); + ImGui::TreePop(); + } + + ImGui::PopItemWidth(); +} + +static void ShowExampleAppMainMenuBar() +{ + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Edit")) + { + if (ImGui::MenuItem("Undo", "CTRL+Z")) {} + if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item + ImGui::Separator(); + if (ImGui::MenuItem("Cut", "CTRL+X")) {} + if (ImGui::MenuItem("Copy", "CTRL+C")) {} + if (ImGui::MenuItem("Paste", "CTRL+V")) {} + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } +} + +static void ShowExampleMenuFile() +{ + ImGui::MenuItem("(dummy menu)", NULL, false, false); + if (ImGui::MenuItem("New")) {} + if (ImGui::MenuItem("Open", "Ctrl+O")) {} + if (ImGui::BeginMenu("Open Recent")) + { + ImGui::MenuItem("fish_hat.c"); + ImGui::MenuItem("fish_hat.inl"); + ImGui::MenuItem("fish_hat.h"); + if (ImGui::BeginMenu("More..")) + { + ImGui::MenuItem("Hello"); + ImGui::MenuItem("Sailor"); + if (ImGui::BeginMenu("Recurse..")) + { + ShowExampleMenuFile(); + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + ImGui::EndMenu(); + } + if (ImGui::MenuItem("Save", "Ctrl+S")) {} + if (ImGui::MenuItem("Save As..")) {} + ImGui::Separator(); + if (ImGui::BeginMenu("Options")) + { + static bool enabled = true; + ImGui::MenuItem("Enabled", "", &enabled); + ImGui::BeginChild("child", ImVec2(0, 60), true); + for (int i = 0; i < 10; i++) + ImGui::Text("Scrolling Text %d", i); + ImGui::EndChild(); + static float f = 0.5f; + static int n = 0; + ImGui::SliderFloat("Value", &f, 0.0f, 1.0f); + ImGui::InputFloat("Input", &f, 0.1f); + ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0"); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Colors")) + { + for (int i = 0; i < ImGuiCol_COUNT; i++) + ImGui::MenuItem(ImGui::GetStyleColName((ImGuiCol)i)); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu("Disabled", false)) // Disabled + { + IM_ASSERT(0); + } + if (ImGui::MenuItem("Checked", NULL, true)) {} + if (ImGui::MenuItem("Quit", "Alt+F4")) {} +} + +static void ShowExampleAppAutoResize(bool* p_open) +{ + if (!ImGui::Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::End(); + return; + } + + static int lines = 10; + ImGui::Text("Window will resize every-frame to the size of its content.\nNote that you probably don't want to query the window size to\noutput your content because that would create a feedback loop."); + ImGui::SliderInt("Number of lines", &lines, 1, 20); + for (int i = 0; i < lines; i++) + ImGui::Text("%*sThis is line %d", i*4, "", i); // Pad with space to extend size horizontally + ImGui::End(); +} + +static void ShowExampleAppConstrainedResize(bool* p_open) +{ + struct CustomConstraints // Helper functions to demonstrate programmatic constraints + { + static void Square(ImGuiSizeConstraintCallbackData* data) { data->DesiredSize = ImVec2(IM_MAX(data->DesiredSize.x, data->DesiredSize.y), IM_MAX(data->DesiredSize.x, data->DesiredSize.y)); } + static void Step(ImGuiSizeConstraintCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); } + }; + + static int type = 0; + if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Vertical only + if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Horizontal only + if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100 + if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(300, 0), ImVec2(400, FLT_MAX)); // Width 300-400 + if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square + if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)100);// Fixed Step + + if (ImGui::Begin("Example: Constrained Resize", p_open)) + { + const char* desc[] = + { + "Resize vertical only", + "Resize horizontal only", + "Width > 100, Height > 100", + "Width 300-400", + "Custom: Always Square", + "Custom: Fixed Steps (100)", + }; + ImGui::Combo("Constraint", &type, desc, IM_ARRAYSIZE(desc)); + if (ImGui::Button("200x200")) ImGui::SetWindowSize(ImVec2(200,200)); ImGui::SameLine(); + if (ImGui::Button("500x500")) ImGui::SetWindowSize(ImVec2(500,500)); ImGui::SameLine(); + if (ImGui::Button("800x200")) ImGui::SetWindowSize(ImVec2(800,200)); + for (int i = 0; i < 10; i++) + ImGui::Text("Hello, sailor! Making this line long enough for the example."); + } + ImGui::End(); +} + +static void ShowExampleAppFixedOverlay(bool* p_open) +{ + ImGui::SetNextWindowPos(ImVec2(10,10)); + if (!ImGui::Begin("Example: Fixed Overlay", p_open, ImVec2(0,0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings)) + { + ImGui::End(); + return; + } + ImGui::Text("Simple overlay\non the top-left side of the screen."); + ImGui::Separator(); + ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); + ImGui::End(); +} + +static void ShowExampleAppManipulatingWindowTitle(bool*) +{ + // By default, Windows are uniquely identified by their title. + // You can use the "##" and "###" markers to manipulate the display/ID. Read FAQ at the top of this file! + + // Using "##" to display same title but have unique identifier. + ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiSetCond_FirstUseEver); + ImGui::Begin("Same title as another window##1"); + ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique."); + ImGui::End(); + + ImGui::SetNextWindowPos(ImVec2(100,200), ImGuiSetCond_FirstUseEver); + ImGui::Begin("Same title as another window##2"); + ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique."); + ImGui::End(); + + // Using "###" to display a changing title but keep a static identifier "AnimatedTitle" + char buf[128]; + sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], rand()); + ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiSetCond_FirstUseEver); + ImGui::Begin(buf); + ImGui::Text("This window has a changing title."); + ImGui::End(); +} + +static void ShowExampleAppCustomRendering(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(350,560), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Custom rendering", p_open)) + { + ImGui::End(); + return; + } + + // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc. + // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4. + // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types) + // In this example we are not using the maths operators! + ImDrawList* draw_list = ImGui::GetWindowDrawList(); + + // Primitives + ImGui::Text("Primitives"); + static float sz = 36.0f; + static ImVec4 col = ImVec4(1.0f,1.0f,0.4f,1.0f); + ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f"); + ImGui::ColorEdit3("Color", &col.x); + { + const ImVec2 p = ImGui::GetCursorScreenPos(); + const ImU32 col32 = ImColor(col); + float x = p.x + 4.0f, y = p.y + 4.0f, spacing = 8.0f; + for (int n = 0; n < 2; n++) + { + float thickness = (n == 0) ? 1.0f : 4.0f; + draw_list->AddCircle(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 20, thickness); x += sz+spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 0.0f, ~0, thickness); x += sz+spacing; + draw_list->AddRect(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f, ~0, thickness); x += sz+spacing; + draw_list->AddTriangle(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y ), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, thickness); x += sz+spacing; + draw_list->AddLine(ImVec2(x, y), ImVec2(x, y+sz), col32, thickness); x += spacing; + draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x+sz*1.3f,y+sz*0.3f), ImVec2(x+sz-sz*1.3f,y+sz-sz*0.3f), ImVec2(x+sz, y+sz), col32, thickness); + x = p.x + 4; + y += sz+spacing; + } + draw_list->AddCircleFilled(ImVec2(x+sz*0.5f, y+sz*0.5f), sz*0.5f, col32, 32); x += sz+spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32); x += sz+spacing; + draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x+sz, y+sz), col32, 10.0f); x += sz+spacing; + draw_list->AddTriangleFilled(ImVec2(x+sz*0.5f, y), ImVec2(x+sz,y+sz-0.5f), ImVec2(x,y+sz-0.5f), col32); x += sz+spacing; + draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x+sz, y+sz), ImColor(0,0,0), ImColor(255,0,0), ImColor(255,255,0), ImColor(0,255,0)); + ImGui::Dummy(ImVec2((sz+spacing)*8, (sz+spacing)*3)); + } + ImGui::Separator(); + { + static ImVector<ImVec2> points; + static bool adding_line = false; + ImGui::Text("Canvas example"); + if (ImGui::Button("Clear")) points.clear(); + if (points.Size >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } + ImGui::Text("Left-click and drag to add lines,\nRight-click to undo"); + + // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() + // However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). + // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). + ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! + ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available + if (canvas_size.x < 50.0f) canvas_size.x = 50.0f; + if (canvas_size.y < 50.0f) canvas_size.y = 50.0f; + draw_list->AddRectFilledMultiColor(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(50,50,50), ImColor(50,50,60), ImColor(60,60,70), ImColor(50,50,60)); + draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), ImColor(255,255,255)); + + bool adding_preview = false; + ImGui::InvisibleButton("canvas", canvas_size); + if (ImGui::IsItemHovered()) + { + ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); + if (!adding_line && ImGui::IsMouseClicked(0)) + { + points.push_back(mouse_pos_in_canvas); + adding_line = true; + } + if (adding_line) + { + adding_preview = true; + points.push_back(mouse_pos_in_canvas); + if (!ImGui::GetIO().MouseDown[0]) + adding_line = adding_preview = false; + } + if (ImGui::IsMouseClicked(1) && !points.empty()) + { + adding_line = adding_preview = false; + points.pop_back(); + points.pop_back(); + } + } + draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.) + for (int i = 0; i < points.Size - 1; i += 2) + draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i+1].x, canvas_pos.y + points[i+1].y), IM_COL32(255,255,0,255), 2.0f); + draw_list->PopClipRect(); + if (adding_preview) + points.pop_back(); + } + ImGui::End(); +} + +// For the console example, here we are using a more C++ like approach of declaring a class to hold the data and the functions. +struct ExampleAppConsole +{ + char InputBuf[256]; + ImVector<char*> Items; + bool ScrollToBottom; + ImVector<char*> History; + int HistoryPos; // -1: new line, 0..History.Size-1 browsing history. + ImVector<const char*> Commands; + + ExampleAppConsole() + { + ClearLog(); + memset(InputBuf, 0, sizeof(InputBuf)); + HistoryPos = -1; + Commands.push_back("HELP"); + Commands.push_back("HISTORY"); + Commands.push_back("CLEAR"); + Commands.push_back("CLASSIFY"); // "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches. + AddLog("Welcome to ImGui!"); + } + ~ExampleAppConsole() + { + ClearLog(); + for (int i = 0; i < History.Size; i++) + free(History[i]); + } + + // Portable helpers + static int Stricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } + static int Strnicmp(const char* str1, const char* str2, int n) { int d = 0; while (n > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; n--; } return d; } + static char* Strdup(const char *str) { size_t len = strlen(str) + 1; void* buff = malloc(len); return (char*)memcpy(buff, (const void*)str, len); } + + void ClearLog() + { + for (int i = 0; i < Items.Size; i++) + free(Items[i]); + Items.clear(); + ScrollToBottom = true; + } + + void AddLog(const char* fmt, ...) IM_PRINTFARGS(2) + { + char buf[1024]; + va_list args; + va_start(args, fmt); + vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args); + buf[IM_ARRAYSIZE(buf)-1] = 0; + va_end(args); + Items.push_back(Strdup(buf)); + ScrollToBottom = true; + } + + void Draw(const char* title, bool* p_open) + { + ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin(title, p_open)) + { + ImGui::End(); + return; + } + + ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc."); + ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); + + // TODO: display items starting from the bottom + + if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); + if (ImGui::SmallButton("Add Dummy Error")) AddLog("[error] something went wrong"); ImGui::SameLine(); + if (ImGui::SmallButton("Clear")) ClearLog(); ImGui::SameLine(); + if (ImGui::SmallButton("Scroll to bottom")) ScrollToBottom = true; + //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } + + ImGui::Separator(); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); + static ImGuiTextFilter filter; + filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); + ImGui::PopStyleVar(); + ImGui::Separator(); + + ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetItemsLineHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar); + if (ImGui::BeginPopupContextWindow()) + { + if (ImGui::Selectable("Clear")) ClearLog(); + ImGui::EndPopup(); + } + + // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); + // NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping to only process visible items. + // You can seek and display only the lines that are visible using the ImGuiListClipper helper, if your elements are evenly spaced and you have cheap random access to the elements. + // To use the clipper we could replace the 'for (int i = 0; i < Items.Size; i++)' loop with: + // ImGuiListClipper clipper(Items.Size); + // while (clipper.Step()) + // for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + // However take note that you can not use this code as is if a filter is active because it breaks the 'cheap random-access' property. We would need random-access on the post-filtered list. + // A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices that passed the filtering test, recomputing this array when user changes the filter, + // and appending newly elements as they are inserted. This is left as a task to the user until we can manage to improve this example code! + // If your items are of variable size you may want to implement code similar to what ImGuiListClipper does. Or split your data into fixed height items to allow random-seeking into your list. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing + for (int i = 0; i < Items.Size; i++) + { + const char* item = Items[i]; + if (!filter.PassFilter(item)) + continue; + ImVec4 col = ImVec4(1.0f,1.0f,1.0f,1.0f); // A better implementation may store a type per-item. For the sample let's just parse the text. + if (strstr(item, "[error]")) col = ImColor(1.0f,0.4f,0.4f,1.0f); + else if (strncmp(item, "# ", 2) == 0) col = ImColor(1.0f,0.78f,0.58f,1.0f); + ImGui::PushStyleColor(ImGuiCol_Text, col); + ImGui::TextUnformatted(item); + ImGui::PopStyleColor(); + } + if (ScrollToBottom) + ImGui::SetScrollHere(); + ScrollToBottom = false; + ImGui::PopStyleVar(); + ImGui::EndChild(); + ImGui::Separator(); + + // Command-line + if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this)) + { + char* input_end = InputBuf+strlen(InputBuf); + while (input_end > InputBuf && input_end[-1] == ' ') input_end--; *input_end = 0; + if (InputBuf[0]) + ExecCommand(InputBuf); + strcpy(InputBuf, ""); + } + + // Demonstrate keeping auto focus on the input box + if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) + ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget + + ImGui::End(); + } + + void ExecCommand(const char* command_line) + { + AddLog("# %s\n", command_line); + + // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. + HistoryPos = -1; + for (int i = History.Size-1; i >= 0; i--) + if (Stricmp(History[i], command_line) == 0) + { + free(History[i]); + History.erase(History.begin() + i); + break; + } + History.push_back(Strdup(command_line)); + + // Process command + if (Stricmp(command_line, "CLEAR") == 0) + { + ClearLog(); + } + else if (Stricmp(command_line, "HELP") == 0) + { + AddLog("Commands:"); + for (int i = 0; i < Commands.Size; i++) + AddLog("- %s", Commands[i]); + } + else if (Stricmp(command_line, "HISTORY") == 0) + { + for (int i = History.Size >= 10 ? History.Size - 10 : 0; i < History.Size; i++) + AddLog("%3d: %s\n", i, History[i]); + } + else + { + AddLog("Unknown command: '%s'\n", command_line); + } + } + + static int TextEditCallbackStub(ImGuiTextEditCallbackData* data) // In C++11 you are better off using lambdas for this sort of forwarding callbacks + { + ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; + return console->TextEditCallback(data); + } + + int TextEditCallback(ImGuiTextEditCallbackData* data) + { + //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); + switch (data->EventFlag) + { + case ImGuiInputTextFlags_CallbackCompletion: + { + // Example of TEXT COMPLETION + + // Locate beginning of current word + const char* word_end = data->Buf + data->CursorPos; + const char* word_start = word_end; + while (word_start > data->Buf) + { + const char c = word_start[-1]; + if (c == ' ' || c == '\t' || c == ',' || c == ';') + break; + word_start--; + } + + // Build a list of candidates + ImVector<const char*> candidates; + for (int i = 0; i < Commands.Size; i++) + if (Strnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) + candidates.push_back(Commands[i]); + + if (candidates.Size == 0) + { + // No match + AddLog("No match for \"%.*s\"!\n", (int)(word_end-word_start), word_start); + } + else if (candidates.Size == 1) + { + // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing + data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); + data->InsertChars(data->CursorPos, candidates[0]); + data->InsertChars(data->CursorPos, " "); + } + else + { + // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" + int match_len = (int)(word_end - word_start); + for (;;) + { + int c = 0; + bool all_candidates_matches = true; + for (int i = 0; i < candidates.Size && all_candidates_matches; i++) + if (i == 0) + c = toupper(candidates[i][match_len]); + else if (c != toupper(candidates[i][match_len])) + all_candidates_matches = false; + if (!all_candidates_matches) + break; + match_len++; + } + + if (match_len > 0) + { + data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); + data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); + } + + // List matches + AddLog("Possible matches:\n"); + for (int i = 0; i < candidates.Size; i++) + AddLog("- %s\n", candidates[i]); + } + + break; + } + case ImGuiInputTextFlags_CallbackHistory: + { + // Example of HISTORY + const int prev_history_pos = HistoryPos; + if (data->EventKey == ImGuiKey_UpArrow) + { + if (HistoryPos == -1) + HistoryPos = History.Size - 1; + else if (HistoryPos > 0) + HistoryPos--; + } + else if (data->EventKey == ImGuiKey_DownArrow) + { + if (HistoryPos != -1) + if (++HistoryPos >= History.Size) + HistoryPos = -1; + } + + // A better implementation would preserve the data on the current input line along with cursor position. + if (prev_history_pos != HistoryPos) + { + data->CursorPos = data->SelectionStart = data->SelectionEnd = data->BufTextLen = (int)snprintf(data->Buf, (size_t)data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : ""); + data->BufDirty = true; + } + } + } + return 0; + } +}; + +static void ShowExampleAppConsole(bool* p_open) +{ + static ExampleAppConsole console; + console.Draw("Example: Console", p_open); +} + +// Usage: +// static ExampleAppLog my_log; +// my_log.AddLog("Hello %d world\n", 123); +// my_log.Draw("title"); +struct ExampleAppLog +{ + ImGuiTextBuffer Buf; + ImGuiTextFilter Filter; + ImVector<int> LineOffsets; // Index to lines offset + bool ScrollToBottom; + + void Clear() { Buf.clear(); LineOffsets.clear(); } + + void AddLog(const char* fmt, ...) IM_PRINTFARGS(2) + { + int old_size = Buf.size(); + va_list args; + va_start(args, fmt); + Buf.appendv(fmt, args); + va_end(args); + for (int new_size = Buf.size(); old_size < new_size; old_size++) + if (Buf[old_size] == '\n') + LineOffsets.push_back(old_size); + ScrollToBottom = true; + } + + void Draw(const char* title, bool* p_open = NULL) + { + ImGui::SetNextWindowSize(ImVec2(500,400), ImGuiSetCond_FirstUseEver); + ImGui::Begin(title, p_open); + if (ImGui::Button("Clear")) Clear(); + ImGui::SameLine(); + bool copy = ImGui::Button("Copy"); + ImGui::SameLine(); + Filter.Draw("Filter", -100.0f); + ImGui::Separator(); + ImGui::BeginChild("scrolling", ImVec2(0,0), false, ImGuiWindowFlags_HorizontalScrollbar); + if (copy) ImGui::LogToClipboard(); + + if (Filter.IsActive()) + { + const char* buf_begin = Buf.begin(); + const char* line = buf_begin; + for (int line_no = 0; line != NULL; line_no++) + { + const char* line_end = (line_no < LineOffsets.Size) ? buf_begin + LineOffsets[line_no] : NULL; + if (Filter.PassFilter(line, line_end)) + ImGui::TextUnformatted(line, line_end); + line = line_end && line_end[1] ? line_end + 1 : NULL; + } + } + else + { + ImGui::TextUnformatted(Buf.begin()); + } + + if (ScrollToBottom) + ImGui::SetScrollHere(1.0f); + ScrollToBottom = false; + ImGui::EndChild(); + ImGui::End(); + } +}; + +static void ShowExampleAppLog(bool* p_open) +{ + static ExampleAppLog log; + + // Demo fill + static float last_time = -1.0f; + float time = ImGui::GetTime(); + if (time - last_time >= 0.3f) + { + const char* random_words[] = { "system", "info", "warning", "error", "fatal", "notice", "log" }; + log.AddLog("[%s] Hello, time is %.1f, rand() %d\n", random_words[rand() % IM_ARRAYSIZE(random_words)], time, (int)rand()); + last_time = time; + } + + log.Draw("Example: Log", p_open); +} + +static void ShowExampleAppLayout(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiSetCond_FirstUseEver); + if (ImGui::Begin("Example: Layout", p_open, ImGuiWindowFlags_MenuBar)) + { + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + if (ImGui::MenuItem("Close")) *p_open = false; + ImGui::EndMenu(); + } + ImGui::EndMenuBar(); + } + + // left + static int selected = 0; + ImGui::BeginChild("left pane", ImVec2(150, 0), true); + for (int i = 0; i < 100; i++) + { + char label[128]; + sprintf(label, "MyObject %d", i); + if (ImGui::Selectable(label, selected == i)) + selected = i; + } + ImGui::EndChild(); + ImGui::SameLine(); + + // right + ImGui::BeginGroup(); + ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing())); // Leave room for 1 line below us + ImGui::Text("MyObject: %d", selected); + ImGui::Separator(); + ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "); + ImGui::EndChild(); + ImGui::BeginChild("buttons"); + if (ImGui::Button("Revert")) {} + ImGui::SameLine(); + if (ImGui::Button("Save")) {} + ImGui::EndChild(); + ImGui::EndGroup(); + } + ImGui::End(); +} + +static void ShowExampleAppPropertyEditor(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(430,450), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Property editor", p_open)) + { + ImGui::End(); + return; + } + + ShowHelpMarker("This example shows how you may implement a property editor using two columns.\nAll objects/fields data are dummies here.\nRemember that in many simple cases, you can use ImGui::SameLine(xxx) to position\nyour cursor horizontally instead of using the Columns() API."); + + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2,2)); + ImGui::Columns(2); + ImGui::Separator(); + + struct funcs + { + static void ShowDummyObject(const char* prefix, int uid) + { + ImGui::PushID(uid); // Use object uid as identifier. Most commonly you could also use the object pointer as a base ID. + ImGui::AlignFirstTextHeightToWidgets(); // Text and Tree nodes are less high than regular widgets, here we add vertical spacing to make the tree lines equal high. + bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid); + ImGui::NextColumn(); + ImGui::AlignFirstTextHeightToWidgets(); + ImGui::Text("my sailor is rich"); + ImGui::NextColumn(); + if (node_open) + { + static float dummy_members[8] = { 0.0f,0.0f,1.0f,3.1416f,100.0f,999.0f }; + for (int i = 0; i < 8; i++) + { + ImGui::PushID(i); // Use field index as identifier. + if (i < 2) + { + ShowDummyObject("Child", 424242); + } + else + { + ImGui::AlignFirstTextHeightToWidgets(); + // Here we use a Selectable (instead of Text) to highlight on hover + //ImGui::Text("Field_%d", i); + char label[32]; + sprintf(label, "Field_%d", i); + ImGui::Bullet(); + ImGui::Selectable(label); + ImGui::NextColumn(); + ImGui::PushItemWidth(-1); + if (i >= 5) + ImGui::InputFloat("##value", &dummy_members[i], 1.0f); + else + ImGui::DragFloat("##value", &dummy_members[i], 0.01f); + ImGui::PopItemWidth(); + ImGui::NextColumn(); + } + ImGui::PopID(); + } + ImGui::TreePop(); + } + ImGui::PopID(); + } + }; + + // Iterate dummy objects with dummy members (all the same data) + for (int obj_i = 0; obj_i < 3; obj_i++) + funcs::ShowDummyObject("Object", obj_i); + + ImGui::Columns(1); + ImGui::Separator(); + ImGui::PopStyleVar(); + ImGui::End(); +} + +static void ShowExampleAppLongText(bool* p_open) +{ + ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); + if (!ImGui::Begin("Example: Long text display", p_open)) + { + ImGui::End(); + return; + } + + static int test_type = 0; + static ImGuiTextBuffer log; + static int lines = 0; + ImGui::Text("Printing unusually long amount of text."); + ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped\0"); + ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); + if (ImGui::Button("Clear")) { log.clear(); lines = 0; } + ImGui::SameLine(); + if (ImGui::Button("Add 1000 lines")) + { + for (int i = 0; i < 1000; i++) + log.append("%i The quick brown fox jumps over the lazy dog\n", lines+i); + lines += 1000; + } + ImGui::BeginChild("Log"); + switch (test_type) + { + case 0: + // Single call to TextUnformatted() with a big buffer + ImGui::TextUnformatted(log.begin(), log.end()); + break; + case 1: + { + // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + ImGuiListClipper clipper(lines); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + case 2: + // Multiple calls to Text(), not clipped (slow) + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); + for (int i = 0; i < lines; i++) + ImGui::Text("%i The quick brown fox jumps over the lazy dog", i); + ImGui::PopStyleVar(); + break; + } + ImGui::EndChild(); + ImGui::End(); +} + +// End of Demo code +#else + +void ImGui::ShowTestWindow(bool*) {} +void ImGui::ShowUserGuide() {} +void ImGui::ShowStyleEditor(ImGuiStyle*) {} + +#endif diff --git a/src/imgui_draw.cpp b/src/imgui_draw.cpp new file mode 100644 index 0000000..0db105f --- /dev/null +++ b/src/imgui_draw.cpp @@ -0,0 +1,2390 @@ +// dear imgui, v1.50 WIP +// (drawing and font code) + +// Contains implementation for +// - ImDrawList +// - ImDrawData +// - ImFontAtlas +// - ImFont +// - Default font data + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include "imgui.h" +#define IMGUI_DEFINE_MATH_OPERATORS +#define IMGUI_DEFINE_PLACEMENT_NEW +#include "imgui_internal.h" + +#include <stdio.h> // vsnprintf, sscanf, printf +#if !defined(alloca) +#ifdef _WIN32 +#include <malloc.h> // alloca +#elif (defined(__FreeBSD__) || defined(FreeBSD_kernel) || defined(__DragonFly__)) && !defined(__GLIBC__) +#include <stdlib.h> // alloca. FreeBSD uses stdlib.h unless GLIBC +#else +#include <alloca.h> // alloca +#endif +#endif + +#ifdef _MSC_VER +#pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) +#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen +#define snprintf _snprintf +#endif + +#ifdef __clang__ +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. +#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. +#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // +#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning : macro name is a reserved identifier // +#elif defined(__GNUC__) +#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used +#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function +#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value +#endif + +//------------------------------------------------------------------------- +// STB libraries implementation +//------------------------------------------------------------------------- + +//#define IMGUI_STB_NAMESPACE ImGuiStb +//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION + +#ifdef IMGUI_STB_NAMESPACE +namespace IMGUI_STB_NAMESPACE +{ +#endif + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration +#endif + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. +#pragma clang diagnostic ignored "-Wunused-function" +#pragma clang diagnostic ignored "-Wmissing-prototypes" +#endif + +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits] +#endif + +#define STBRP_ASSERT(x) IM_ASSERT(x) +#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION +#define STBRP_STATIC +#define STB_RECT_PACK_IMPLEMENTATION +#endif +#include "stb_rect_pack.h" + +#define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) +#define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) +#define STBTT_assert(x) IM_ASSERT(x) +#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION +#define STBTT_STATIC +#define STB_TRUETYPE_IMPLEMENTATION +#else +#define STBTT_DEF extern +#endif +#include "stb_truetype.h" + +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +#ifdef IMGUI_STB_NAMESPACE +} // namespace ImGuiStb +using namespace IMGUI_STB_NAMESPACE; +#endif + +//----------------------------------------------------------------------------- +// ImDrawList +//----------------------------------------------------------------------------- + +static const ImVec4 GNullClipRect(-8192.0f, -8192.0f, +8192.0f, +8192.0f); // Large values that are easy to encode in a few bits+shift + +void ImDrawList::Clear() +{ + CmdBuffer.resize(0); + IdxBuffer.resize(0); + VtxBuffer.resize(0); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.resize(0); + _TextureIdStack.resize(0); + _Path.resize(0); + _ChannelsCurrent = 0; + _ChannelsCount = 1; + // NB: Do not clear channels so our allocations are re-used after the first frame. +} + +void ImDrawList::ClearFreeMemory() +{ + CmdBuffer.clear(); + IdxBuffer.clear(); + VtxBuffer.clear(); + _VtxCurrentIdx = 0; + _VtxWritePtr = NULL; + _IdxWritePtr = NULL; + _ClipRectStack.clear(); + _TextureIdStack.clear(); + _Path.clear(); + _ChannelsCurrent = 0; + _ChannelsCount = 1; + for (int i = 0; i < _Channels.Size; i++) + { + if (i == 0) memset(&_Channels[0], 0, sizeof(_Channels[0])); // channel 0 is a copy of CmdBuffer/IdxBuffer, don't destruct again + _Channels[i].CmdBuffer.clear(); + _Channels[i].IdxBuffer.clear(); + } + _Channels.clear(); +} + +// Use macros because C++ is a terrible language, we want guaranteed inline, no code in header, and no overhead in Debug mode +#define GetCurrentClipRect() (_ClipRectStack.Size ? _ClipRectStack.Data[_ClipRectStack.Size-1] : GNullClipRect) +#define GetCurrentTextureId() (_TextureIdStack.Size ? _TextureIdStack.Data[_TextureIdStack.Size-1] : NULL) + +void ImDrawList::AddDrawCmd() +{ + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = GetCurrentClipRect(); + draw_cmd.TextureId = GetCurrentTextureId(); + + IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w); + CmdBuffer.push_back(draw_cmd); +} + +void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) +{ + ImDrawCmd* current_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + if (!current_cmd || current_cmd->ElemCount != 0 || current_cmd->UserCallback != NULL) + { + AddDrawCmd(); + current_cmd = &CmdBuffer.back(); + } + current_cmd->UserCallback = callback; + current_cmd->UserCallbackData = callback_data; + + AddDrawCmd(); // Force a new command after us (see comment below) +} + +// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack. +// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only. +void ImDrawList::UpdateClipRect() +{ + // If current command is used with different settings we need to add a new command + const ImVec4 curr_clip_rect = GetCurrentClipRect(); + ImDrawCmd* curr_cmd = CmdBuffer.Size > 0 ? &CmdBuffer.Data[CmdBuffer.Size-1] : NULL; + if (!curr_cmd || (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) != 0) || curr_cmd->UserCallback != NULL) + { + AddDrawCmd(); + return; + } + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + if (curr_cmd->ElemCount == 0 && prev_cmd && memcmp(&prev_cmd->ClipRect, &curr_clip_rect, sizeof(ImVec4)) == 0 && prev_cmd->TextureId == GetCurrentTextureId() && prev_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); + else + curr_cmd->ClipRect = curr_clip_rect; +} + +void ImDrawList::UpdateTextureID() +{ + // If current command is used with different settings we need to add a new command + const ImTextureID curr_texture_id = GetCurrentTextureId(); + ImDrawCmd* curr_cmd = CmdBuffer.Size ? &CmdBuffer.back() : NULL; + if (!curr_cmd || (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != curr_texture_id) || curr_cmd->UserCallback != NULL) + { + AddDrawCmd(); + return; + } + + // Try to merge with previous command if it matches, else use current command + ImDrawCmd* prev_cmd = CmdBuffer.Size > 1 ? curr_cmd - 1 : NULL; + if (prev_cmd && prev_cmd->TextureId == curr_texture_id && memcmp(&prev_cmd->ClipRect, &GetCurrentClipRect(), sizeof(ImVec4)) == 0 && prev_cmd->UserCallback == NULL) + CmdBuffer.pop_back(); + else + curr_cmd->TextureId = curr_texture_id; +} + +#undef GetCurrentClipRect +#undef GetCurrentTextureId + +// Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling) +void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect) +{ + ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y); + if (intersect_with_current_clip_rect && _ClipRectStack.Size) + { + ImVec4 current = _ClipRectStack.Data[_ClipRectStack.Size-1]; + if (cr.x < current.x) cr.x = current.x; + if (cr.y < current.y) cr.y = current.y; + if (cr.z > current.z) cr.z = current.z; + if (cr.w > current.w) cr.w = current.w; + } + cr.z = ImMax(cr.x, cr.z); + cr.w = ImMax(cr.y, cr.w); + + _ClipRectStack.push_back(cr); + UpdateClipRect(); +} + +void ImDrawList::PushClipRectFullScreen() +{ + PushClipRect(ImVec2(GNullClipRect.x, GNullClipRect.y), ImVec2(GNullClipRect.z, GNullClipRect.w)); + //PushClipRect(GetVisibleRect()); // FIXME-OPT: This would be more correct but we're not supposed to access ImGuiContext from here? +} + +void ImDrawList::PopClipRect() +{ + IM_ASSERT(_ClipRectStack.Size > 0); + _ClipRectStack.pop_back(); + UpdateClipRect(); +} + +void ImDrawList::PushTextureID(const ImTextureID& texture_id) +{ + _TextureIdStack.push_back(texture_id); + UpdateTextureID(); +} + +void ImDrawList::PopTextureID() +{ + IM_ASSERT(_TextureIdStack.Size > 0); + _TextureIdStack.pop_back(); + UpdateTextureID(); +} + +void ImDrawList::ChannelsSplit(int channels_count) +{ + IM_ASSERT(_ChannelsCurrent == 0 && _ChannelsCount == 1); + int old_channels_count = _Channels.Size; + if (old_channels_count < channels_count) + _Channels.resize(channels_count); + _ChannelsCount = channels_count; + + // _Channels[] (24 bytes each) hold storage that we'll swap with this->_CmdBuffer/_IdxBuffer + // The content of _Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to. + // When we switch to the next channel, we'll copy _CmdBuffer/_IdxBuffer into _Channels[0] and then _Channels[1] into _CmdBuffer/_IdxBuffer + memset(&_Channels[0], 0, sizeof(ImDrawChannel)); + for (int i = 1; i < channels_count; i++) + { + if (i >= old_channels_count) + { + IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel(); + } + else + { + _Channels[i].CmdBuffer.resize(0); + _Channels[i].IdxBuffer.resize(0); + } + if (_Channels[i].CmdBuffer.Size == 0) + { + ImDrawCmd draw_cmd; + draw_cmd.ClipRect = _ClipRectStack.back(); + draw_cmd.TextureId = _TextureIdStack.back(); + _Channels[i].CmdBuffer.push_back(draw_cmd); + } + } +} + +void ImDrawList::ChannelsMerge() +{ + // Note that we never use or rely on channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use. + if (_ChannelsCount <= 1) + return; + + ChannelsSetCurrent(0); + if (CmdBuffer.Size && CmdBuffer.back().ElemCount == 0) + CmdBuffer.pop_back(); + + int new_cmd_buffer_count = 0, new_idx_buffer_count = 0; + for (int i = 1; i < _ChannelsCount; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (ch.CmdBuffer.Size && ch.CmdBuffer.back().ElemCount == 0) + ch.CmdBuffer.pop_back(); + new_cmd_buffer_count += ch.CmdBuffer.Size; + new_idx_buffer_count += ch.IdxBuffer.Size; + } + CmdBuffer.resize(CmdBuffer.Size + new_cmd_buffer_count); + IdxBuffer.resize(IdxBuffer.Size + new_idx_buffer_count); + + ImDrawCmd* cmd_write = CmdBuffer.Data + CmdBuffer.Size - new_cmd_buffer_count; + _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size - new_idx_buffer_count; + for (int i = 1; i < _ChannelsCount; i++) + { + ImDrawChannel& ch = _Channels[i]; + if (int sz = ch.CmdBuffer.Size) { memcpy(cmd_write, ch.CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; } + if (int sz = ch.IdxBuffer.Size) { memcpy(_IdxWritePtr, ch.IdxBuffer.Data, sz * sizeof(ImDrawIdx)); _IdxWritePtr += sz; } + } + AddDrawCmd(); + _ChannelsCount = 1; +} + +void ImDrawList::ChannelsSetCurrent(int idx) +{ + IM_ASSERT(idx < _ChannelsCount); + if (_ChannelsCurrent == idx) return; + memcpy(&_Channels.Data[_ChannelsCurrent].CmdBuffer, &CmdBuffer, sizeof(CmdBuffer)); // copy 12 bytes, four times + memcpy(&_Channels.Data[_ChannelsCurrent].IdxBuffer, &IdxBuffer, sizeof(IdxBuffer)); + _ChannelsCurrent = idx; + memcpy(&CmdBuffer, &_Channels.Data[_ChannelsCurrent].CmdBuffer, sizeof(CmdBuffer)); + memcpy(&IdxBuffer, &_Channels.Data[_ChannelsCurrent].IdxBuffer, sizeof(IdxBuffer)); + _IdxWritePtr = IdxBuffer.Data + IdxBuffer.Size; +} + +// NB: this can be called with negative count for removing primitives (as long as the result does not underflow) +void ImDrawList::PrimReserve(int idx_count, int vtx_count) +{ + ImDrawCmd& draw_cmd = CmdBuffer.Data[CmdBuffer.Size-1]; + draw_cmd.ElemCount += idx_count; + + int vtx_buffer_size = VtxBuffer.Size; + VtxBuffer.resize(vtx_buffer_size + vtx_count); + _VtxWritePtr = VtxBuffer.Data + vtx_buffer_size; + + int idx_buffer_size = IdxBuffer.Size; + IdxBuffer.resize(idx_buffer_size + idx_count); + _IdxWritePtr = IdxBuffer.Data + idx_buffer_size; +} + +// Fully unrolled with inline call to keep our debug builds decently fast. +void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv(GImGui->FontTexUvWhitePixel); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) +{ + ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y); + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col) +{ + ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx; + _IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2); + _IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3); + _VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + _VtxCurrentIdx += 4; + _IdxWritePtr += 6; +} + +// TODO: Thickness anti-aliased lines cap are missing their AA fringe. +void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, bool closed, float thickness, bool anti_aliased) +{ + if (points_count < 2) + return; + + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + anti_aliased &= GImGui->Style.AntiAliasedLines; + //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug + + int count = points_count; + if (!closed) + count = points_count-1; + + const bool thick_line = thickness > 1.0f; + if (anti_aliased) + { + // Anti-aliased stroke + const float AA_SIZE = 1.0f; + const ImU32 col_trans = col & IM_COL32(255,255,255,0); + + const int idx_count = thick_line ? count*18 : count*12; + const int vtx_count = thick_line ? points_count*4 : points_count*3; + PrimReserve(idx_count, vtx_count); + + // Temporary buffer + ImVec2* temp_normals = (ImVec2*)alloca(points_count * (thick_line ? 5 : 3) * sizeof(ImVec2)); + ImVec2* temp_points = temp_normals + points_count; + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + ImVec2 diff = points[i2] - points[i1]; + diff *= ImInvLength(diff, 1.0f); + temp_normals[i1].x = diff.y; + temp_normals[i1].y = -diff.x; + } + if (!closed) + temp_normals[points_count-1] = temp_normals[points_count-2]; + + if (!thick_line) + { + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * AA_SIZE; + temp_points[1] = points[0] - temp_normals[0] * AA_SIZE; + temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * AA_SIZE; + temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * AA_SIZE; + } + + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+3; + + // Average normals + ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + dm *= AA_SIZE; + temp_points[i2*2+0] = points[i2] + dm; + temp_points[i2*2+1] = points[i2] - dm; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2+0); _IdxWritePtr[1] = (ImDrawIdx)(idx1+0); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+0); + _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10]= (ImDrawIdx)(idx2+0); _IdxWritePtr[11]= (ImDrawIdx)(idx2+1); + _IdxWritePtr += 12; + + idx1 = idx2; + } + + // Add vertexes + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos = temp_points[i*2+0]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; + _VtxWritePtr[2].pos = temp_points[i*2+1]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col_trans; + _VtxWritePtr += 3; + } + } + else + { + const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f; + if (!closed) + { + temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness); + temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness); + temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE); + temp_points[(points_count-1)*4+0] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + temp_points[(points_count-1)*4+1] = points[points_count-1] + temp_normals[points_count-1] * (half_inner_thickness); + temp_points[(points_count-1)*4+2] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness); + temp_points[(points_count-1)*4+3] = points[points_count-1] - temp_normals[points_count-1] * (half_inner_thickness + AA_SIZE); + } + + // FIXME-OPT: Merge the different loops, possibly remove the temporary buffer. + unsigned int idx1 = _VtxCurrentIdx; + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + unsigned int idx2 = (i1+1) == points_count ? _VtxCurrentIdx : idx1+4; + + // Average normals + ImVec2 dm = (temp_normals[i1] + temp_normals[i2]) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + ImVec2 dm_out = dm * (half_inner_thickness + AA_SIZE); + ImVec2 dm_in = dm * half_inner_thickness; + temp_points[i2*4+0] = points[i2] + dm_out; + temp_points[i2*4+1] = points[i2] + dm_in; + temp_points[i2*4+2] = points[i2] - dm_in; + temp_points[i2*4+3] = points[i2] - dm_out; + + // Add indexes + _IdxWritePtr[0] = (ImDrawIdx)(idx2+1); _IdxWritePtr[1] = (ImDrawIdx)(idx1+1); _IdxWritePtr[2] = (ImDrawIdx)(idx1+2); + _IdxWritePtr[3] = (ImDrawIdx)(idx1+2); _IdxWritePtr[4] = (ImDrawIdx)(idx2+2); _IdxWritePtr[5] = (ImDrawIdx)(idx2+1); + _IdxWritePtr[6] = (ImDrawIdx)(idx2+1); _IdxWritePtr[7] = (ImDrawIdx)(idx1+1); _IdxWritePtr[8] = (ImDrawIdx)(idx1+0); + _IdxWritePtr[9] = (ImDrawIdx)(idx1+0); _IdxWritePtr[10] = (ImDrawIdx)(idx2+0); _IdxWritePtr[11] = (ImDrawIdx)(idx2+1); + _IdxWritePtr[12] = (ImDrawIdx)(idx2+2); _IdxWritePtr[13] = (ImDrawIdx)(idx1+2); _IdxWritePtr[14] = (ImDrawIdx)(idx1+3); + _IdxWritePtr[15] = (ImDrawIdx)(idx1+3); _IdxWritePtr[16] = (ImDrawIdx)(idx2+3); _IdxWritePtr[17] = (ImDrawIdx)(idx2+2); + _IdxWritePtr += 18; + + idx1 = idx2; + } + + // Add vertexes + for (int i = 0; i < points_count; i++) + { + _VtxWritePtr[0].pos = temp_points[i*4+0]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col_trans; + _VtxWritePtr[1].pos = temp_points[i*4+1]; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos = temp_points[i*4+2]; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos = temp_points[i*4+3]; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col_trans; + _VtxWritePtr += 4; + } + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Stroke + const int idx_count = count*6; + const int vtx_count = count*4; // FIXME-OPT: Not sharing edges + PrimReserve(idx_count, vtx_count); + + for (int i1 = 0; i1 < count; i1++) + { + const int i2 = (i1+1) == points_count ? 0 : i1+1; + const ImVec2& p1 = points[i1]; + const ImVec2& p2 = points[i2]; + ImVec2 diff = p2 - p1; + diff *= ImInvLength(diff, 1.0f); + + const float dx = diff.x * (thickness * 0.5f); + const float dy = diff.y * (thickness * 0.5f); + _VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col; + _VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col; + _VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col; + _VtxWritePtr += 4; + + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+2); + _IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx+2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx+3); + _IdxWritePtr += 6; + _VtxCurrentIdx += 4; + } + } +} + +void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col, bool anti_aliased) +{ + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + anti_aliased &= GImGui->Style.AntiAliasedShapes; + //if (ImGui::GetIO().KeyCtrl) anti_aliased = false; // Debug + + if (anti_aliased) + { + // Anti-aliased Fill + const float AA_SIZE = 1.0f; + const ImU32 col_trans = col & IM_COL32(255,255,255,0); + const int idx_count = (points_count-2)*3 + points_count*6; + const int vtx_count = (points_count*2); + PrimReserve(idx_count, vtx_count); + + // Add indexes for fill + unsigned int vtx_inner_idx = _VtxCurrentIdx; + unsigned int vtx_outer_idx = _VtxCurrentIdx+1; + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+((i-1)<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx+(i<<1)); + _IdxWritePtr += 3; + } + + // Compute normals + ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); + for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + { + const ImVec2& p0 = points[i0]; + const ImVec2& p1 = points[i1]; + ImVec2 diff = p1 - p0; + diff *= ImInvLength(diff, 1.0f); + temp_normals[i0].x = diff.y; + temp_normals[i0].y = -diff.x; + } + + for (int i0 = points_count-1, i1 = 0; i1 < points_count; i0 = i1++) + { + // Average normals + const ImVec2& n0 = temp_normals[i0]; + const ImVec2& n1 = temp_normals[i1]; + ImVec2 dm = (n0 + n1) * 0.5f; + float dmr2 = dm.x*dm.x + dm.y*dm.y; + if (dmr2 > 0.000001f) + { + float scale = 1.0f / dmr2; + if (scale > 100.0f) scale = 100.0f; + dm *= scale; + } + dm *= AA_SIZE * 0.5f; + + // Add vertices + _VtxWritePtr[0].pos = (points[i1] - dm); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner + _VtxWritePtr[1].pos = (points[i1] + dm); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer + _VtxWritePtr += 2; + + // Add indexes for fringes + _IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx+(i0<<1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); + _IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx+(i0<<1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx+(i1<<1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx+(i1<<1)); + _IdxWritePtr += 6; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } + else + { + // Non Anti-aliased Fill + const int idx_count = (points_count-2)*3; + const int vtx_count = points_count; + PrimReserve(idx_count, vtx_count); + for (int i = 0; i < vtx_count; i++) + { + _VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; + _VtxWritePtr++; + } + for (int i = 2; i < points_count; i++) + { + _IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx+i-1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx+i); + _IdxWritePtr += 3; + } + _VtxCurrentIdx += (ImDrawIdx)vtx_count; + } +} + +void ImDrawList::PathArcToFast(const ImVec2& centre, float radius, int amin, int amax) +{ + static ImVec2 circle_vtx[12]; + static bool circle_vtx_builds = false; + const int circle_vtx_count = IM_ARRAYSIZE(circle_vtx); + if (!circle_vtx_builds) + { + for (int i = 0; i < circle_vtx_count; i++) + { + const float a = ((float)i / (float)circle_vtx_count) * 2*IM_PI; + circle_vtx[i].x = cosf(a); + circle_vtx[i].y = sinf(a); + } + circle_vtx_builds = true; + } + + if (amin > amax) return; + if (radius == 0.0f) + { + _Path.push_back(centre); + } + else + { + _Path.reserve(_Path.Size + (amax - amin + 1)); + for (int a = amin; a <= amax; a++) + { + const ImVec2& c = circle_vtx[a % circle_vtx_count]; + _Path.push_back(ImVec2(centre.x + c.x * radius, centre.y + c.y * radius)); + } + } +} + +void ImDrawList::PathArcTo(const ImVec2& centre, float radius, float amin, float amax, int num_segments) +{ + if (radius == 0.0f) + _Path.push_back(centre); + _Path.reserve(_Path.Size + (num_segments + 1)); + for (int i = 0; i <= num_segments; i++) + { + const float a = amin + ((float)i / (float)num_segments) * (amax - amin); + _Path.push_back(ImVec2(centre.x + cosf(a) * radius, centre.y + sinf(a) * radius)); + } +} + +static void PathBezierToCasteljau(ImVector<ImVec2>* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level) +{ + float dx = x4 - x1; + float dy = y4 - y1; + float d2 = ((x2 - x4) * dy - (y2 - y4) * dx); + float d3 = ((x3 - x4) * dy - (y3 - y4) * dx); + d2 = (d2 >= 0) ? d2 : -d2; + d3 = (d3 >= 0) ? d3 : -d3; + if ((d2+d3) * (d2+d3) < tess_tol * (dx*dx + dy*dy)) + { + path->push_back(ImVec2(x4, y4)); + } + else if (level < 10) + { + float x12 = (x1+x2)*0.5f, y12 = (y1+y2)*0.5f; + float x23 = (x2+x3)*0.5f, y23 = (y2+y3)*0.5f; + float x34 = (x3+x4)*0.5f, y34 = (y3+y4)*0.5f; + float x123 = (x12+x23)*0.5f, y123 = (y12+y23)*0.5f; + float x234 = (x23+x34)*0.5f, y234 = (y23+y34)*0.5f; + float x1234 = (x123+x234)*0.5f, y1234 = (y123+y234)*0.5f; + + PathBezierToCasteljau(path, x1,y1, x12,y12, x123,y123, x1234,y1234, tess_tol, level+1); + PathBezierToCasteljau(path, x1234,y1234, x234,y234, x34,y34, x4,y4, tess_tol, level+1); + } +} + +void ImDrawList::PathBezierCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments) +{ + ImVec2 p1 = _Path.back(); + if (num_segments == 0) + { + // Auto-tessellated + PathBezierToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, GImGui->Style.CurveTessellationTol, 0); + } + else + { + float t_step = 1.0f / (float)num_segments; + for (int i_step = 1; i_step <= num_segments; i_step++) + { + float t = t_step * i_step; + float u = 1.0f - t; + float w1 = u*u*u; + float w2 = 3*u*u*t; + float w3 = 3*u*t*t; + float w4 = t*t*t; + _Path.push_back(ImVec2(w1*p1.x + w2*p2.x + w3*p3.x + w4*p4.x, w1*p1.y + w2*p2.y + w3*p3.y + w4*p4.y)); + } + } +} + +void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, int rounding_corners) +{ + float r = rounding; + r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f ) - 1.0f); + r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f ) - 1.0f); + + if (r <= 0.0f || rounding_corners == 0) + { + PathLineTo(a); + PathLineTo(ImVec2(b.x,a.y)); + PathLineTo(b); + PathLineTo(ImVec2(a.x,b.y)); + } + else + { + const float r0 = (rounding_corners & 1) ? r : 0.0f; + const float r1 = (rounding_corners & 2) ? r : 0.0f; + const float r2 = (rounding_corners & 4) ? r : 0.0f; + const float r3 = (rounding_corners & 8) ? r : 0.0f; + PathArcToFast(ImVec2(a.x+r0,a.y+r0), r0, 6, 9); + PathArcToFast(ImVec2(b.x-r1,a.y+r1), r1, 9, 12); + PathArcToFast(ImVec2(b.x-r2,b.y-r2), r2, 0, 3); + PathArcToFast(ImVec2(a.x+r3,b.y-r3), r3, 3, 6); + } +} + +void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) +{ + if ((col >> 24) == 0) + return; + PathLineTo(a + ImVec2(0.5f,0.5f)); + PathLineTo(b + ImVec2(0.5f,0.5f)); + PathStroke(col, false, thickness); +} + +// a: upper-left, b: lower-right. we don't render 1 px sized rectangles properly. +void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners, float thickness) +{ + if ((col >> 24) == 0) + return; + PathRect(a + ImVec2(0.5f,0.5f), b - ImVec2(0.5f,0.5f), rounding, rounding_corners); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) +{ + if ((col >> 24) == 0) + return; + if (rounding > 0.0f) + { + PathRect(a, b, rounding, rounding_corners); + PathFill(col); + } + else + { + PrimReserve(6, 4); + PrimRect(a, b, col); + } +} + +void ImDrawList::AddRectFilledMultiColor(const ImVec2& a, const ImVec2& c, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left) +{ + if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) >> 24) == 0) + return; + + const ImVec2 uv = GImGui->FontTexUvWhitePixel; + PrimReserve(6, 4); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); + PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx+3)); + PrimWriteVtx(a, uv, col_upr_left); + PrimWriteVtx(ImVec2(c.x, a.y), uv, col_upr_right); + PrimWriteVtx(c, uv, col_bot_right); + PrimWriteVtx(ImVec2(a.x, c.y), uv, col_bot_left); +} + +void ImDrawList::AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness) +{ + if ((col >> 24) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathLineTo(d); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col) +{ + if ((col >> 24) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathLineTo(d); + PathFill(col); +} + +void ImDrawList::AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness) +{ + if ((col >> 24) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) +{ + if ((col >> 24) == 0) + return; + + PathLineTo(a); + PathLineTo(b); + PathLineTo(c); + PathFill(col); +} + +void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments, float thickness) +{ + if ((col >> 24) == 0) + return; + + const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(centre, radius-0.5f, 0.0f, a_max, num_segments); + PathStroke(col, true, thickness); +} + +void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) +{ + if ((col >> 24) == 0) + return; + + const float a_max = IM_PI*2.0f * ((float)num_segments - 1.0f) / (float)num_segments; + PathArcTo(centre, radius, 0.0f, a_max, num_segments); + PathFill(col); +} + +void ImDrawList::AddBezierCurve(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments) +{ + if ((col >> 24) == 0) + return; + + PathLineTo(pos0); + PathBezierCurveTo(cp0, cp1, pos1, num_segments); + PathStroke(col, false, thickness); +} + +void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec4* cpu_fine_clip_rect) +{ + if ((col >> 24) == 0) + return; + + if (text_end == NULL) + text_end = text_begin + strlen(text_begin); + if (text_begin == text_end) + return; + + // Note: This is one of the few instance of breaking the encapsulation of ImDrawList, as we pull this from ImGui state, but it is just SO useful. + // Might just move Font/FontSize to ImDrawList? + if (font == NULL) + font = GImGui->Font; + if (font_size == 0.0f) + font_size = GImGui->FontSize; + + IM_ASSERT(font->ContainerAtlas->TexID == _TextureIdStack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. + + ImVec4 clip_rect = _ClipRectStack.back(); + if (cpu_fine_clip_rect) + { + clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x); + clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y); + clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z); + clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w); + } + font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL); +} + +void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end) +{ + AddText(GImGui->Font, GImGui->FontSize, pos, col, text_begin, text_end); +} + +void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0, const ImVec2& uv1, ImU32 col) +{ + if ((col >> 24) == 0) + return; + + // FIXME-OPT: This is wasting draw calls. + const bool push_texture_id = _TextureIdStack.empty() || user_texture_id != _TextureIdStack.back(); + if (push_texture_id) + PushTextureID(user_texture_id); + + PrimReserve(6, 4); + PrimRectUV(a, b, uv0, uv1, col); + + if (push_texture_id) + PopTextureID(); +} + +//----------------------------------------------------------------------------- +// ImDrawData +//----------------------------------------------------------------------------- + +// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering! +void ImDrawData::DeIndexAllBuffers() +{ + ImVector<ImDrawVert> new_vtx_buffer; + TotalVtxCount = TotalIdxCount = 0; + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList* cmd_list = CmdLists[i]; + if (cmd_list->IdxBuffer.empty()) + continue; + new_vtx_buffer.resize(cmd_list->IdxBuffer.Size); + for (int j = 0; j < cmd_list->IdxBuffer.Size; j++) + new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]]; + cmd_list->VtxBuffer.swap(new_vtx_buffer); + cmd_list->IdxBuffer.resize(0); + TotalVtxCount += cmd_list->VtxBuffer.Size; + } +} + +// Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution. +void ImDrawData::ScaleClipRects(const ImVec2& scale) +{ + for (int i = 0; i < CmdListsCount; i++) + { + ImDrawList* cmd_list = CmdLists[i]; + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i]; + cmd->ClipRect = ImVec4(cmd->ClipRect.x * scale.x, cmd->ClipRect.y * scale.y, cmd->ClipRect.z * scale.x, cmd->ClipRect.w * scale.y); + } + } +} + +//----------------------------------------------------------------------------- +// ImFontAtlas +//----------------------------------------------------------------------------- + +ImFontConfig::ImFontConfig() +{ + FontData = NULL; + FontDataSize = 0; + FontDataOwnedByAtlas = true; + FontNo = 0; + SizePixels = 0.0f; + OversampleH = 3; + OversampleV = 1; + PixelSnapH = false; + GlyphExtraSpacing = ImVec2(0.0f, 0.0f); + GlyphRanges = NULL; + MergeMode = false; + MergeGlyphCenterV = false; + DstFont = NULL; + memset(Name, 0, sizeof(Name)); +} + +ImFontAtlas::ImFontAtlas() +{ + TexID = NULL; + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; + TexWidth = TexHeight = TexDesiredWidth = 0; + TexUvWhitePixel = ImVec2(0, 0); +} + +ImFontAtlas::~ImFontAtlas() +{ + Clear(); +} + +void ImFontAtlas::ClearInputData() +{ + for (int i = 0; i < ConfigData.Size; i++) + if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas) + { + ImGui::MemFree(ConfigData[i].FontData); + ConfigData[i].FontData = NULL; + } + + // When clearing this we lose access to the font name and other information used to build the font. + for (int i = 0; i < Fonts.Size; i++) + if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size) + { + Fonts[i]->ConfigData = NULL; + Fonts[i]->ConfigDataCount = 0; + } + ConfigData.clear(); +} + +void ImFontAtlas::ClearTexData() +{ + if (TexPixelsAlpha8) + ImGui::MemFree(TexPixelsAlpha8); + if (TexPixelsRGBA32) + ImGui::MemFree(TexPixelsRGBA32); + TexPixelsAlpha8 = NULL; + TexPixelsRGBA32 = NULL; +} + +void ImFontAtlas::ClearFonts() +{ + for (int i = 0; i < Fonts.Size; i++) + { + Fonts[i]->~ImFont(); + ImGui::MemFree(Fonts[i]); + } + Fonts.clear(); +} + +void ImFontAtlas::Clear() +{ + ClearInputData(); + ClearTexData(); + ClearFonts(); +} + +void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + // Build atlas on demand + if (TexPixelsAlpha8 == NULL) + { + if (ConfigData.empty()) + AddFontDefault(); + Build(); + } + + *out_pixels = TexPixelsAlpha8; + if (out_width) *out_width = TexWidth; + if (out_height) *out_height = TexHeight; + if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; +} + +void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) +{ + // Convert to RGBA32 format on demand + // Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp + if (!TexPixelsRGBA32) + { + unsigned char* pixels; + GetTexDataAsAlpha8(&pixels, NULL, NULL); + TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4)); + const unsigned char* src = pixels; + unsigned int* dst = TexPixelsRGBA32; + for (int n = TexWidth * TexHeight; n > 0; n--) + *dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++)); + } + + *out_pixels = (unsigned char*)TexPixelsRGBA32; + if (out_width) *out_width = TexWidth; + if (out_height) *out_height = TexHeight; + if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; +} + +ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg) +{ + IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0); + IM_ASSERT(font_cfg->SizePixels > 0.0f); + + // Create new font + if (!font_cfg->MergeMode) + { + ImFont* font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont)); + IM_PLACEMENT_NEW(font) ImFont(); + Fonts.push_back(font); + } + + ConfigData.push_back(*font_cfg); + ImFontConfig& new_font_cfg = ConfigData.back(); + if (!new_font_cfg.DstFont) + new_font_cfg.DstFont = Fonts.back(); + if (!new_font_cfg.FontDataOwnedByAtlas) + { + new_font_cfg.FontData = ImGui::MemAlloc(new_font_cfg.FontDataSize); + new_font_cfg.FontDataOwnedByAtlas = true; + memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize); + } + + // Invalidate texture + ClearTexData(); + return new_font_cfg.DstFont; +} + +// Default font TTF is compressed with stb_compress then base85 encoded (see extra_fonts/binary_to_compressed_c.cpp for encoder) +static unsigned int stb_decompress_length(unsigned char *input); +static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length); +static const char* GetDefaultCompressedFontDataTTFBase85(); +static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; } +static void Decode85(const unsigned char* src, unsigned char* dst) +{ + while (*src) + { + unsigned int tmp = Decode85Byte(src[0]) + 85*(Decode85Byte(src[1]) + 85*(Decode85Byte(src[2]) + 85*(Decode85Byte(src[3]) + 85*Decode85Byte(src[4])))); + dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianess. + src += 5; + dst += 4; + } +} + +// Load embedded ProggyClean.ttf at size 13, disable oversampling +ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template) +{ + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (!font_cfg_template) + { + font_cfg.OversampleH = font_cfg.OversampleV = 1; + font_cfg.PixelSnapH = true; + } + if (font_cfg.Name[0] == '\0') strcpy(font_cfg.Name, "<default>"); + + const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85(); + ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, 13.0f, &font_cfg, GetGlyphRangesDefault()); + return font; +} + +ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + int data_size = 0; + void* data = ImLoadFileToMemory(filename, "rb", &data_size, 0); + if (!data) + { + IM_ASSERT(0); // Could not load file. + return NULL; + } + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + if (font_cfg.Name[0] == '\0') + { + // Store a short copy of filename into into the font name for convenience + const char* p; + for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {} + snprintf(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s", p); + } + return AddFontFromMemoryTTF(data, data_size, size_pixels, &font_cfg, glyph_ranges); +} + +// NBM Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build(). +ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontData = ttf_data; + font_cfg.FontDataSize = ttf_size; + font_cfg.SizePixels = size_pixels; + if (glyph_ranges) + font_cfg.GlyphRanges = glyph_ranges; + return AddFont(&font_cfg); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges) +{ + const unsigned int buf_decompressed_size = stb_decompress_length((unsigned char*)compressed_ttf_data); + unsigned char* buf_decompressed_data = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); + stb_decompress(buf_decompressed_data, (unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size); + + ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig(); + IM_ASSERT(font_cfg.FontData == NULL); + font_cfg.FontDataOwnedByAtlas = true; + return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges); +} + +ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges) +{ + int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4; + void* compressed_ttf = ImGui::MemAlloc((size_t)compressed_ttf_size); + Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf); + ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges); + ImGui::MemFree(compressed_ttf); + return font; +} + +bool ImFontAtlas::Build() +{ + IM_ASSERT(ConfigData.Size > 0); + + TexID = NULL; + TexWidth = TexHeight = 0; + TexUvWhitePixel = ImVec2(0, 0); + ClearTexData(); + + struct ImFontTempBuildData + { + stbtt_fontinfo FontInfo; + stbrp_rect* Rects; + stbtt_pack_range* Ranges; + int RangesCount; + }; + ImFontTempBuildData* tmp_array = (ImFontTempBuildData*)ImGui::MemAlloc((size_t)ConfigData.Size * sizeof(ImFontTempBuildData)); + + // Initialize font information early (so we can error without any cleanup) + count glyphs + int total_glyph_count = 0; + int total_glyph_range_count = 0; + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + + IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == this)); + const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo); + IM_ASSERT(font_offset >= 0); + if (!stbtt_InitFont(&tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset)) + return false; + + // Count glyphs + if (!cfg.GlyphRanges) + cfg.GlyphRanges = GetGlyphRangesDefault(); + for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) + { + total_glyph_count += (in_range[1] - in_range[0]) + 1; + total_glyph_range_count++; + } + } + + // Start packing. We need a known width for the skyline algorithm. Using a cheap heuristic here to decide of width. User can override TexDesiredWidth if they wish. + // After packing is done, width shouldn't matter much, but some API/GPU have texture size limitations and increasing width can decrease height. + TexWidth = (TexDesiredWidth > 0) ? TexDesiredWidth : (total_glyph_count > 4000) ? 4096 : (total_glyph_count > 2000) ? 2048 : (total_glyph_count > 1000) ? 1024 : 512; + TexHeight = 0; + const int max_tex_height = 1024*32; + stbtt_pack_context spc; + stbtt_PackBegin(&spc, NULL, TexWidth, max_tex_height, 0, 1, NULL); + + // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). + ImVector<stbrp_rect> extra_rects; + RenderCustomTexData(0, &extra_rects); + stbtt_PackSetOversampling(&spc, 1, 1); + stbrp_pack_rects((stbrp_context*)spc.pack_info, &extra_rects[0], extra_rects.Size); + for (int i = 0; i < extra_rects.Size; i++) + if (extra_rects[i].was_packed) + TexHeight = ImMax(TexHeight, extra_rects[i].y + extra_rects[i].h); + + // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) + int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0; + stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyph_count * sizeof(stbtt_packedchar)); + stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyph_count * sizeof(stbrp_rect)); + stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_glyph_range_count * sizeof(stbtt_pack_range)); + memset(buf_packedchars, 0, total_glyph_count * sizeof(stbtt_packedchar)); + memset(buf_rects, 0, total_glyph_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity. + memset(buf_ranges, 0, total_glyph_range_count * sizeof(stbtt_pack_range)); + + // First font pass: pack all glyphs (no rendering at this point, we are working with rectangles in an infinitely tall texture at this point) + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + + // Setup ranges + int glyph_count = 0; + int glyph_ranges_count = 0; + for (const ImWchar* in_range = cfg.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) + { + glyph_count += (in_range[1] - in_range[0]) + 1; + glyph_ranges_count++; + } + tmp.Ranges = buf_ranges + buf_ranges_n; + tmp.RangesCount = glyph_ranges_count; + buf_ranges_n += glyph_ranges_count; + for (int i = 0; i < glyph_ranges_count; i++) + { + const ImWchar* in_range = &cfg.GlyphRanges[i * 2]; + stbtt_pack_range& range = tmp.Ranges[i]; + range.font_size = cfg.SizePixels; + range.first_unicode_codepoint_in_range = in_range[0]; + range.num_chars = (in_range[1] - in_range[0]) + 1; + range.chardata_for_range = buf_packedchars + buf_packedchars_n; + buf_packedchars_n += range.num_chars; + } + + // Pack + tmp.Rects = buf_rects + buf_rects_n; + buf_rects_n += glyph_count; + stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); + int n = stbtt_PackFontRangesGatherRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); + stbrp_pack_rects((stbrp_context*)spc.pack_info, tmp.Rects, n); + + // Extend texture height + for (int i = 0; i < n; i++) + if (tmp.Rects[i].was_packed) + TexHeight = ImMax(TexHeight, tmp.Rects[i].y + tmp.Rects[i].h); + } + IM_ASSERT(buf_rects_n == total_glyph_count); + IM_ASSERT(buf_packedchars_n == total_glyph_count); + IM_ASSERT(buf_ranges_n == total_glyph_range_count); + + // Create texture + TexHeight = ImUpperPowerOfTwo(TexHeight); + TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(TexWidth * TexHeight); + memset(TexPixelsAlpha8, 0, TexWidth * TexHeight); + spc.pixels = TexPixelsAlpha8; + spc.height = TexHeight; + + // Second pass: render characters + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + stbtt_PackSetOversampling(&spc, cfg.OversampleH, cfg.OversampleV); + stbtt_PackFontRangesRenderIntoRects(&spc, &tmp.FontInfo, tmp.Ranges, tmp.RangesCount, tmp.Rects); + tmp.Rects = NULL; + } + + // End packing + stbtt_PackEnd(&spc); + ImGui::MemFree(buf_rects); + buf_rects = NULL; + + // Third pass: setup ImFont and glyphs for runtime + for (int input_i = 0; input_i < ConfigData.Size; input_i++) + { + ImFontConfig& cfg = ConfigData[input_i]; + ImFontTempBuildData& tmp = tmp_array[input_i]; + ImFont* dst_font = cfg.DstFont; + + float font_scale = stbtt_ScaleForPixelHeight(&tmp.FontInfo, cfg.SizePixels); + int unscaled_ascent, unscaled_descent, unscaled_line_gap; + stbtt_GetFontVMetrics(&tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap); + + float ascent = unscaled_ascent * font_scale; + float descent = unscaled_descent * font_scale; + if (!cfg.MergeMode) + { + dst_font->ContainerAtlas = this; + dst_font->ConfigData = &cfg; + dst_font->ConfigDataCount = 0; + dst_font->FontSize = cfg.SizePixels; + dst_font->Ascent = ascent; + dst_font->Descent = descent; + dst_font->Glyphs.resize(0); + } + dst_font->ConfigDataCount++; + float off_y = (cfg.MergeMode && cfg.MergeGlyphCenterV) ? (ascent - dst_font->Ascent) * 0.5f : 0.0f; + + dst_font->FallbackGlyph = NULL; // Always clear fallback so FindGlyph can return NULL. It will be set again in BuildLookupTable() + for (int i = 0; i < tmp.RangesCount; i++) + { + stbtt_pack_range& range = tmp.Ranges[i]; + for (int char_idx = 0; char_idx < range.num_chars; char_idx += 1) + { + const stbtt_packedchar& pc = range.chardata_for_range[char_idx]; + if (!pc.x0 && !pc.x1 && !pc.y0 && !pc.y1) + continue; + + const int codepoint = range.first_unicode_codepoint_in_range + char_idx; + if (cfg.MergeMode && dst_font->FindGlyph((unsigned short)codepoint)) + continue; + + stbtt_aligned_quad q; + float dummy_x = 0.0f, dummy_y = 0.0f; + stbtt_GetPackedQuad(range.chardata_for_range, TexWidth, TexHeight, char_idx, &dummy_x, &dummy_y, &q, 0); + + dst_font->Glyphs.resize(dst_font->Glyphs.Size + 1); + ImFont::Glyph& glyph = dst_font->Glyphs.back(); + glyph.Codepoint = (ImWchar)codepoint; + glyph.X0 = q.x0; glyph.Y0 = q.y0; glyph.X1 = q.x1; glyph.Y1 = q.y1; + glyph.U0 = q.s0; glyph.V0 = q.t0; glyph.U1 = q.s1; glyph.V1 = q.t1; + glyph.Y0 += (float)(int)(dst_font->Ascent + off_y + 0.5f); + glyph.Y1 += (float)(int)(dst_font->Ascent + off_y + 0.5f); + glyph.XAdvance = (pc.xadvance + cfg.GlyphExtraSpacing.x); // Bake spacing into XAdvance + if (cfg.PixelSnapH) + glyph.XAdvance = (float)(int)(glyph.XAdvance + 0.5f); + } + } + cfg.DstFont->BuildLookupTable(); + } + + // Cleanup temporaries + ImGui::MemFree(buf_packedchars); + ImGui::MemFree(buf_ranges); + ImGui::MemFree(tmp_array); + + // Render into our custom data block + RenderCustomTexData(1, &extra_rects); + + return true; +} + +void ImFontAtlas::RenderCustomTexData(int pass, void* p_rects) +{ + // A work of art lies ahead! (. = white layer, X = black layer, others are blank) + // The white texels on the top left are the ones we'll use everywhere in ImGui to render filled shapes. + const int TEX_DATA_W = 90; + const int TEX_DATA_H = 27; + const char texture_data[TEX_DATA_W*TEX_DATA_H+1] = + { + "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX" + "..- -X.....X- X.X - X.X -X.....X - X.....X" + "--- -XXX.XXX- X...X - X...X -X....X - X....X" + "X - X.X - X.....X - X.....X -X...X - X...X" + "XX - X.X -X.......X- X.......X -X..X.X - X.X..X" + "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X" + "X..X - X.X - X.X - X.X -XX X.X - X.X XX" + "X...X - X.X - X.X - XX X.X XX - X.X - X.X " + "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X " + "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X " + "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X " + "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X " + "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X " + "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X " + "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X " + "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X " + "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX " + "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------" + "X.X X..X - -X.......X- X.......X - XX XX - " + "XX X..X - - X.....X - X.....X - X.X X.X - " + " X..X - X...X - X...X - X..X X..X - " + " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - " + "------------ - X - X -X.....................X- " + " ----------------------------------- X...XXXXXXXXXXXXX...X - " + " - X..X X..X - " + " - X.X X.X - " + " - XX XX - " + }; + + ImVector<stbrp_rect>& rects = *(ImVector<stbrp_rect>*)p_rects; + if (pass == 0) + { + // Request rectangles + stbrp_rect r; + memset(&r, 0, sizeof(r)); + r.w = (TEX_DATA_W*2)+1; + r.h = TEX_DATA_H+1; + rects.push_back(r); + } + else if (pass == 1) + { + // Render/copy pixels + const stbrp_rect& r = rects[0]; + for (int y = 0, n = 0; y < TEX_DATA_H; y++) + for (int x = 0; x < TEX_DATA_W; x++, n++) + { + const int offset0 = (int)(r.x + x) + (int)(r.y + y) * TexWidth; + const int offset1 = offset0 + 1 + TEX_DATA_W; + TexPixelsAlpha8[offset0] = texture_data[n] == '.' ? 0xFF : 0x00; + TexPixelsAlpha8[offset1] = texture_data[n] == 'X' ? 0xFF : 0x00; + } + const ImVec2 tex_uv_scale(1.0f / TexWidth, 1.0f / TexHeight); + TexUvWhitePixel = ImVec2((r.x + 0.5f) * tex_uv_scale.x, (r.y + 0.5f) * tex_uv_scale.y); + + // Setup mouse cursors + const ImVec2 cursor_datas[ImGuiMouseCursor_Count_][3] = + { + // Pos ........ Size ......... Offset ...... + { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow + { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput + { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move + { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS + { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW + { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW + { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE + }; + + for (int type = 0; type < ImGuiMouseCursor_Count_; type++) + { + ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type]; + ImVec2 pos = cursor_datas[type][0] + ImVec2((float)r.x, (float)r.y); + const ImVec2 size = cursor_datas[type][1]; + cursor_data.Type = type; + cursor_data.Size = size; + cursor_data.HotOffset = cursor_datas[type][2]; + cursor_data.TexUvMin[0] = (pos) * tex_uv_scale; + cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale; + pos.x += TEX_DATA_W+1; + cursor_data.TexUvMin[1] = (pos) * tex_uv_scale; + cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale; + } + } +} + +// Retrieve list of range (2 int per range, values are inclusive) +const ImWchar* ImFontAtlas::GetGlyphRangesDefault() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesKorean() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3131, 0x3163, // Korean alphabets + 0xAC00, 0xD79D, // Korean characters + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesChinese() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + 0x4e00, 0x9FAF, // CJK Ideograms + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() +{ + // Store the 1946 ideograms code points as successive offsets from the initial unicode codepoint 0x4E00. Each offset has an implicit +1. + // This encoding helps us reduce the source code size. + static const short offsets_from_0x4E00[] = + { + -1,0,1,3,0,0,0,0,1,0,5,1,1,0,7,4,6,10,0,1,9,9,7,1,3,19,1,10,7,1,0,1,0,5,1,0,6,4,2,6,0,0,12,6,8,0,3,5,0,1,0,9,0,0,8,1,1,3,4,5,13,0,0,8,2,17, + 4,3,1,1,9,6,0,0,0,2,1,3,2,22,1,9,11,1,13,1,3,12,0,5,9,2,0,6,12,5,3,12,4,1,2,16,1,1,4,6,5,3,0,6,13,15,5,12,8,14,0,0,6,15,3,6,0,18,8,1,6,14,1, + 5,4,12,24,3,13,12,10,24,0,0,0,1,0,1,1,2,9,10,2,2,0,0,3,3,1,0,3,8,0,3,2,4,4,1,6,11,10,14,6,15,3,4,15,1,0,0,5,2,2,0,0,1,6,5,5,6,0,3,6,5,0,0,1,0, + 11,2,2,8,4,7,0,10,0,1,2,17,19,3,0,2,5,0,6,2,4,4,6,1,1,11,2,0,3,1,2,1,2,10,7,6,3,16,0,8,24,0,0,3,1,1,3,0,1,6,0,0,0,2,0,1,5,15,0,1,0,0,2,11,19, + 1,4,19,7,6,5,1,0,0,0,0,5,1,0,1,9,0,0,5,0,2,0,1,0,3,0,11,3,0,2,0,0,0,0,0,9,3,6,4,12,0,14,0,0,29,10,8,0,14,37,13,0,31,16,19,0,8,30,1,20,8,3,48, + 21,1,0,12,0,10,44,34,42,54,11,18,82,0,2,1,2,12,1,0,6,2,17,2,12,7,0,7,17,4,2,6,24,23,8,23,39,2,16,23,1,0,5,1,2,15,14,5,6,2,11,0,8,6,2,2,2,14, + 20,4,15,3,4,11,10,10,2,5,2,1,30,2,1,0,0,22,5,5,0,3,1,5,4,1,0,0,2,2,21,1,5,1,2,16,2,1,3,4,0,8,4,0,0,5,14,11,2,16,1,13,1,7,0,22,15,3,1,22,7,14, + 22,19,11,24,18,46,10,20,64,45,3,2,0,4,5,0,1,4,25,1,0,0,2,10,0,0,0,1,0,1,2,0,0,9,1,2,0,0,0,2,5,2,1,1,5,5,8,1,1,1,5,1,4,9,1,3,0,1,0,1,1,2,0,0, + 2,0,1,8,22,8,1,0,0,0,0,4,2,1,0,9,8,5,0,9,1,30,24,2,6,4,39,0,14,5,16,6,26,179,0,2,1,1,0,0,0,5,2,9,6,0,2,5,16,7,5,1,1,0,2,4,4,7,15,13,14,0,0, + 3,0,1,0,0,0,2,1,6,4,5,1,4,9,0,3,1,8,0,0,10,5,0,43,0,2,6,8,4,0,2,0,0,9,6,0,9,3,1,6,20,14,6,1,4,0,7,2,3,0,2,0,5,0,3,1,0,3,9,7,0,3,4,0,4,9,1,6,0, + 9,0,0,2,3,10,9,28,3,6,2,4,1,2,32,4,1,18,2,0,3,1,5,30,10,0,2,2,2,0,7,9,8,11,10,11,7,2,13,7,5,10,0,3,40,2,0,1,6,12,0,4,5,1,5,11,11,21,4,8,3,7, + 8,8,33,5,23,0,0,19,8,8,2,3,0,6,1,1,1,5,1,27,4,2,5,0,3,5,6,3,1,0,3,1,12,5,3,3,2,0,7,7,2,1,0,4,0,1,1,2,0,10,10,6,2,5,9,7,5,15,15,21,6,11,5,20, + 4,3,5,5,2,5,0,2,1,0,1,7,28,0,9,0,5,12,5,5,18,30,0,12,3,3,21,16,25,32,9,3,14,11,24,5,66,9,1,2,0,5,9,1,5,1,8,0,8,3,3,0,1,15,1,4,8,1,2,7,0,7,2, + 8,3,7,5,3,7,10,2,1,0,0,2,25,0,6,4,0,10,0,4,2,4,1,12,5,38,4,0,4,1,10,5,9,4,0,14,4,2,5,18,20,21,1,3,0,5,0,7,0,3,7,1,3,1,1,8,1,0,0,0,3,2,5,2,11, + 6,0,13,1,3,9,1,12,0,16,6,2,1,0,2,1,12,6,13,11,2,0,28,1,7,8,14,13,8,13,0,2,0,5,4,8,10,2,37,42,19,6,6,7,4,14,11,18,14,80,7,6,0,4,72,12,36,27, + 7,7,0,14,17,19,164,27,0,5,10,7,3,13,6,14,0,2,2,5,3,0,6,13,0,0,10,29,0,4,0,3,13,0,3,1,6,51,1,5,28,2,0,8,0,20,2,4,0,25,2,10,13,10,0,16,4,0,1,0, + 2,1,7,0,1,8,11,0,0,1,2,7,2,23,11,6,6,4,16,2,2,2,0,22,9,3,3,5,2,0,15,16,21,2,9,20,15,15,5,3,9,1,0,0,1,7,7,5,4,2,2,2,38,24,14,0,0,15,5,6,24,14, + 5,5,11,0,21,12,0,3,8,4,11,1,8,0,11,27,7,2,4,9,21,59,0,1,39,3,60,62,3,0,12,11,0,3,30,11,0,13,88,4,15,5,28,13,1,4,48,17,17,4,28,32,46,0,16,0, + 18,11,1,8,6,38,11,2,6,11,38,2,0,45,3,11,2,7,8,4,30,14,17,2,1,1,65,18,12,16,4,2,45,123,12,56,33,1,4,3,4,7,0,0,0,3,2,0,16,4,2,4,2,0,7,4,5,2,26, + 2,25,6,11,6,1,16,2,6,17,77,15,3,35,0,1,0,5,1,0,38,16,6,3,12,3,3,3,0,9,3,1,3,5,2,9,0,18,0,25,1,3,32,1,72,46,6,2,7,1,3,14,17,0,28,1,40,13,0,20, + 15,40,6,38,24,12,43,1,1,9,0,12,6,0,6,2,4,19,3,7,1,48,0,9,5,0,5,6,9,6,10,15,2,11,19,3,9,2,0,1,10,1,27,8,1,3,6,1,14,0,26,0,27,16,3,4,9,6,2,23, + 9,10,5,25,2,1,6,1,1,48,15,9,15,14,3,4,26,60,29,13,37,21,1,6,4,0,2,11,22,23,16,16,2,2,1,3,0,5,1,6,4,0,0,4,0,0,8,3,0,2,5,0,7,1,7,3,13,2,4,10, + 3,0,2,31,0,18,3,0,12,10,4,1,0,7,5,7,0,5,4,12,2,22,10,4,2,15,2,8,9,0,23,2,197,51,3,1,1,4,13,4,3,21,4,19,3,10,5,40,0,4,1,1,10,4,1,27,34,7,21, + 2,17,2,9,6,4,2,3,0,4,2,7,8,2,5,1,15,21,3,4,4,2,2,17,22,1,5,22,4,26,7,0,32,1,11,42,15,4,1,2,5,0,19,3,1,8,6,0,10,1,9,2,13,30,8,2,24,17,19,1,4, + 4,25,13,0,10,16,11,39,18,8,5,30,82,1,6,8,18,77,11,13,20,75,11,112,78,33,3,0,0,60,17,84,9,1,1,12,30,10,49,5,32,158,178,5,5,6,3,3,1,3,1,4,7,6, + 19,31,21,0,2,9,5,6,27,4,9,8,1,76,18,12,1,4,0,3,3,6,3,12,2,8,30,16,2,25,1,5,5,4,3,0,6,10,2,3,1,0,5,1,19,3,0,8,1,5,2,6,0,0,0,19,1,2,0,5,1,2,5, + 1,3,7,0,4,12,7,3,10,22,0,9,5,1,0,2,20,1,1,3,23,30,3,9,9,1,4,191,14,3,15,6,8,50,0,1,0,0,4,0,0,1,0,2,4,2,0,2,3,0,2,0,2,2,8,7,0,1,1,1,3,3,17,11, + 91,1,9,3,2,13,4,24,15,41,3,13,3,1,20,4,125,29,30,1,0,4,12,2,21,4,5,5,19,11,0,13,11,86,2,18,0,7,1,8,8,2,2,22,1,2,6,5,2,0,1,2,8,0,2,0,5,2,1,0, + 2,10,2,0,5,9,2,1,2,0,1,0,4,0,0,10,2,5,3,0,6,1,0,1,4,4,33,3,13,17,3,18,6,4,7,1,5,78,0,4,1,13,7,1,8,1,0,35,27,15,3,0,0,0,1,11,5,41,38,15,22,6, + 14,14,2,1,11,6,20,63,5,8,27,7,11,2,2,40,58,23,50,54,56,293,8,8,1,5,1,14,0,1,12,37,89,8,8,8,2,10,6,0,0,0,4,5,2,1,0,1,1,2,7,0,3,3,0,4,6,0,3,2, + 19,3,8,0,0,0,4,4,16,0,4,1,5,1,3,0,3,4,6,2,17,10,10,31,6,4,3,6,10,126,7,3,2,2,0,9,0,0,5,20,13,0,15,0,6,0,2,5,8,64,50,3,2,12,2,9,0,0,11,8,20, + 109,2,18,23,0,0,9,61,3,0,28,41,77,27,19,17,81,5,2,14,5,83,57,252,14,154,263,14,20,8,13,6,57,39,38, + }; + static ImWchar base_ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana + 0x31F0, 0x31FF, // Katakana Phonetic Extensions + 0xFF00, 0xFFEF, // Half-width characters + }; + static bool full_ranges_unpacked = false; + static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(offsets_from_0x4E00)*2 + 1]; + if (!full_ranges_unpacked) + { + // Unpack + int codepoint = 0x4e00; + memcpy(full_ranges, base_ranges, sizeof(base_ranges)); + ImWchar* dst = full_ranges + IM_ARRAYSIZE(base_ranges);; + for (int n = 0; n < IM_ARRAYSIZE(offsets_from_0x4E00); n++, dst += 2) + dst[0] = dst[1] = (ImWchar)(codepoint += (offsets_from_0x4E00[n] + 1)); + dst[0] = 0; + full_ranges_unpacked = true; + } + return &full_ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesCyrillic() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + Latin Supplement + 0x0400, 0x052F, // Cyrillic + Cyrillic Supplement + 0x2DE0, 0x2DFF, // Cyrillic Extended-A + 0xA640, 0xA69F, // Cyrillic Extended-B + 0, + }; + return &ranges[0]; +} + +const ImWchar* ImFontAtlas::GetGlyphRangesThai() +{ + static const ImWchar ranges[] = + { + 0x0020, 0x00FF, // Basic Latin + 0x0E00, 0x0E7F, // Thai + 0, + }; + return &ranges[0]; +} + +//----------------------------------------------------------------------------- +// ImFont +//----------------------------------------------------------------------------- + +ImFont::ImFont() +{ + Scale = 1.0f; + FallbackChar = (ImWchar)'?'; + Clear(); +} + +ImFont::~ImFont() +{ + // Invalidate active font so that the user gets a clear crash instead of a dangling pointer. + // If you want to delete fonts you need to do it between Render() and NewFrame(). + // FIXME-CLEANUP + /* + ImGuiContext& g = *GImGui; + if (g.Font == this) + g.Font = NULL; + */ + Clear(); +} + +void ImFont::Clear() +{ + FontSize = 0.0f; + DisplayOffset = ImVec2(0.0f, 1.0f); + ConfigData = NULL; + ConfigDataCount = 0; + Ascent = Descent = 0.0f; + ContainerAtlas = NULL; + Glyphs.clear(); + FallbackGlyph = NULL; + FallbackXAdvance = 0.0f; + IndexXAdvance.clear(); + IndexLookup.clear(); +} + +void ImFont::BuildLookupTable() +{ + int max_codepoint = 0; + for (int i = 0; i != Glyphs.Size; i++) + max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); + + IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved + IndexXAdvance.clear(); + IndexLookup.clear(); + GrowIndex(max_codepoint + 1); + for (int i = 0; i < Glyphs.Size; i++) + { + int codepoint = (int)Glyphs[i].Codepoint; + IndexXAdvance[codepoint] = Glyphs[i].XAdvance; + IndexLookup[codepoint] = (unsigned short)i; + } + + // Create a glyph to handle TAB + // FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?) + if (FindGlyph((unsigned short)' ')) + { + if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times + Glyphs.resize(Glyphs.Size + 1); + ImFont::Glyph& tab_glyph = Glyphs.back(); + tab_glyph = *FindGlyph((unsigned short)' '); + tab_glyph.Codepoint = '\t'; + tab_glyph.XAdvance *= 4; + IndexXAdvance[(int)tab_glyph.Codepoint] = (float)tab_glyph.XAdvance; + IndexLookup[(int)tab_glyph.Codepoint] = (unsigned short)(Glyphs.Size-1); + } + + FallbackGlyph = NULL; + FallbackGlyph = FindGlyph(FallbackChar); + FallbackXAdvance = FallbackGlyph ? FallbackGlyph->XAdvance : 0.0f; + for (int i = 0; i < max_codepoint + 1; i++) + if (IndexXAdvance[i] < 0.0f) + IndexXAdvance[i] = FallbackXAdvance; +} + +void ImFont::SetFallbackChar(ImWchar c) +{ + FallbackChar = c; + BuildLookupTable(); +} + +void ImFont::GrowIndex(int new_size) +{ + IM_ASSERT(IndexXAdvance.Size == IndexLookup.Size); + int old_size = IndexLookup.Size; + if (new_size <= old_size) + return; + IndexXAdvance.resize(new_size); + IndexLookup.resize(new_size); + for (int i = old_size; i < new_size; i++) + { + IndexXAdvance[i] = -1.0f; + IndexLookup[i] = (unsigned short)-1; + } +} + +void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst) +{ + IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function. + int index_size = IndexLookup.Size; + + if (dst < index_size && IndexLookup.Data[dst] == (unsigned short)-1 && !overwrite_dst) // 'dst' already exists + return; + if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op + return; + + GrowIndex(dst + 1); + IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (unsigned short)-1; + IndexXAdvance[dst] = (src < index_size) ? IndexXAdvance.Data[src] : 1.0f; +} + +const ImFont::Glyph* ImFont::FindGlyph(unsigned short c) const +{ + if (c < IndexLookup.Size) + { + const unsigned short i = IndexLookup[c]; + if (i != (unsigned short)-1) + return &Glyphs.Data[i]; + } + return FallbackGlyph; +} + +const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const +{ + // Simple word-wrapping for English, not full-featured. Please submit failing cases! + // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) + + // For references, possible wrap point marked with ^ + // "aaa bbb, ccc,ddd. eee fff. ggg!" + // ^ ^ ^ ^ ^__ ^ ^ + + // List of hardcoded separators: .,;!?'" + + // Skip extra blanks after a line returns (that includes not counting them in width computation) + // e.g. "Hello world" --> "Hello" "World" + + // Cut words that cannot possibly fit within one line. + // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" + + float line_width = 0.0f; + float word_width = 0.0f; + float blank_width = 0.0f; + + const char* word_end = text; + const char* prev_word_end = NULL; + bool inside_word = true; + + const char* s = text; + while (s < text_end) + { + unsigned int c = (unsigned int)*s; + const char* next_s; + if (c < 0x80) + next_s = s + 1; + else + next_s = s + ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) + break; + + if (c < 32) + { + if (c == '\n') + { + line_width = word_width = blank_width = 0.0f; + inside_word = true; + s = next_s; + continue; + } + if (c == '\r') + { + s = next_s; + continue; + } + } + + const float char_width = ((int)c < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * scale; + if (ImCharIsSpace(c)) + { + if (inside_word) + { + line_width += blank_width; + blank_width = 0.0f; + } + blank_width += char_width; + inside_word = false; + } + else + { + word_width += char_width; + if (inside_word) + { + word_end = next_s; + } + else + { + prev_word_end = word_end; + line_width += word_width + blank_width; + word_width = blank_width = 0.0f; + } + + // Allow wrapping after punctuation. + inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); + } + + // We ignore blank width at the end of the line (they can be skipped) + if (line_width + word_width >= wrap_width) + { + // Words that cannot possibly fit within an entire line will be cut anywhere. + if (word_width < wrap_width) + s = prev_word_end ? prev_word_end : word_end; + break; + } + + s = next_s; + } + + return s; +} + +ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. + + const float line_height = size; + const float scale = size / FontSize; + + ImVec2 text_size = ImVec2(0,0); + float line_width = 0.0f; + + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + const char* s = text_begin; + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + if (text_size.x < line_width) + text_size.x = line_width; + text_size.y += line_height; + line_width = 0.0f; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source + const char* prev_s = s; + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) + break; + } + + if (c < 32) + { + if (c == '\n') + { + text_size.x = ImMax(text_size.x, line_width); + text_size.y += line_height; + line_width = 0.0f; + continue; + } + if (c == '\r') + continue; + } + + const float char_width = ((int)c < IndexXAdvance.Size ? IndexXAdvance[(int)c] : FallbackXAdvance) * scale; + if (line_width + char_width >= max_width) + { + s = prev_s; + break; + } + + line_width += char_width; + } + + if (text_size.x < line_width) + text_size.x = line_width; + + if (line_width > 0 || text_size.y == 0.0f) + text_size.y += line_height; + + if (remaining) + *remaining = s; + + return text_size; +} + +void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const +{ + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') // Match behavior of RenderText(), those 4 codepoints are hard-coded. + return; + if (const Glyph* glyph = FindGlyph(c)) + { + float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f; + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + ImVec2 pos_tl(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale); + ImVec2 pos_br(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale); + draw_list->PrimReserve(6, 4); + draw_list->PrimRectUV(pos_tl, pos_br, ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col); + } +} + +void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const +{ + if (!text_end) + text_end = text_begin + strlen(text_begin); + + // Align to be pixel perfect + pos.x = (float)(int)pos.x + DisplayOffset.x; + pos.y = (float)(int)pos.y + DisplayOffset.y; + float x = pos.x; + float y = pos.y; + if (y > clip_rect.w) + return; + + const float scale = size / FontSize; + const float line_height = FontSize * scale; + const bool word_wrap_enabled = (wrap_width > 0.0f); + const char* word_wrap_eol = NULL; + + // Skip non-visible lines + const char* s = text_begin; + if (!word_wrap_enabled && y + line_height < clip_rect.y) + while (s < text_end && *s != '\n') // Fast-forward to next line + s++; + + // Reserve vertices for remaining worse case (over-reserving is useful and easily amortized) + const int vtx_count_max = (int)(text_end - s) * 4; + const int idx_count_max = (int)(text_end - s) * 6; + const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max; + draw_list->PrimReserve(idx_count_max, vtx_count_max); + + ImDrawVert* vtx_write = draw_list->_VtxWritePtr; + ImDrawIdx* idx_write = draw_list->_IdxWritePtr; + unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx; + + while (s < text_end) + { + if (word_wrap_enabled) + { + // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. + if (!word_wrap_eol) + { + word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); + if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. + word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below + } + + if (s >= word_wrap_eol) + { + x = pos.x; + y += line_height; + word_wrap_eol = NULL; + + // Wrapping skips upcoming blanks + while (s < text_end) + { + const char c = *s; + if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } + } + continue; + } + } + + // Decode and advance source + unsigned int c = (unsigned int)*s; + if (c < 0x80) + { + s += 1; + } + else + { + s += ImTextCharFromUtf8(&c, s, text_end); + if (c == 0) + break; + } + + if (c < 32) + { + if (c == '\n') + { + x = pos.x; + y += line_height; + + if (y > clip_rect.w) + break; + if (!word_wrap_enabled && y + line_height < clip_rect.y) + while (s < text_end && *s != '\n') // Fast-forward to next line + s++; + continue; + } + if (c == '\r') + continue; + } + + float char_width = 0.0f; + if (const Glyph* glyph = FindGlyph((unsigned short)c)) + { + char_width = glyph->XAdvance * scale; + + // Arbitrarily assume that both space and tabs are empty glyphs as an optimization + if (c != ' ' && c != '\t') + { + // We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w + float x1 = x + glyph->X0 * scale; + float x2 = x + glyph->X1 * scale; + float y1 = y + glyph->Y0 * scale; + float y2 = y + glyph->Y1 * scale; + if (x1 <= clip_rect.z && x2 >= clip_rect.x) + { + // Render a character + float u1 = glyph->U0; + float v1 = glyph->V0; + float u2 = glyph->U1; + float v2 = glyph->V1; + + // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quads. + if (cpu_fine_clip) + { + if (x1 < clip_rect.x) + { + u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1); + x1 = clip_rect.x; + } + if (y1 < clip_rect.y) + { + v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1); + y1 = clip_rect.y; + } + if (x2 > clip_rect.z) + { + u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1); + x2 = clip_rect.z; + } + if (y2 > clip_rect.w) + { + v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1); + y2 = clip_rect.w; + } + if (y1 >= y2) + { + x += char_width; + continue; + } + } + + // We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug build. + // Inlined here: + { + idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2); + idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3); + vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1; + vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1; + vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2; + vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2; + vtx_write += 4; + vtx_current_idx += 4; + idx_write += 6; + } + } + } + } + + x += char_width; + } + + // Give back unused vertices + draw_list->VtxBuffer.resize((int)(vtx_write - draw_list->VtxBuffer.Data)); + draw_list->IdxBuffer.resize((int)(idx_write - draw_list->IdxBuffer.Data)); + draw_list->CmdBuffer[draw_list->CmdBuffer.Size-1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size); + draw_list->_VtxWritePtr = vtx_write; + draw_list->_IdxWritePtr = idx_write; + draw_list->_VtxCurrentIdx = (unsigned int)draw_list->VtxBuffer.Size; +} + +//----------------------------------------------------------------------------- +// DEFAULT FONT DATA +//----------------------------------------------------------------------------- +// Compressed with stb_compress() then converted to a C array. +// Use the program in extra_fonts/binary_to_compressed_c.cpp to create the array from a TTF file. +// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h +//----------------------------------------------------------------------------- + +static unsigned int stb_decompress_length(unsigned char *input) +{ + return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; +} + +static unsigned char *stb__barrier, *stb__barrier2, *stb__barrier3, *stb__barrier4; +static unsigned char *stb__dout; +static void stb__match(unsigned char *data, unsigned int length) +{ + // INVERSE of memmove... write each byte before copying the next... + IM_ASSERT (stb__dout + length <= stb__barrier); + if (stb__dout + length > stb__barrier) { stb__dout += length; return; } + if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; } + while (length--) *stb__dout++ = *data++; +} + +static void stb__lit(unsigned char *data, unsigned int length) +{ + IM_ASSERT (stb__dout + length <= stb__barrier); + if (stb__dout + length > stb__barrier) { stb__dout += length; return; } + if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; } + memcpy(stb__dout, data, length); + stb__dout += length; +} + +#define stb__in2(x) ((i[x] << 8) + i[(x)+1]) +#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) +#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) + +static unsigned char *stb_decompress_token(unsigned char *i) +{ + if (*i >= 0x20) { // use fewer if's for cases that expand small + if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; + else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; + else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); + } else { // more ifs for cases that expand large, since overhead is amortized + if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; + else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; + else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); + else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); + else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; + else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; + } + return i; +} + +static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) +{ + const unsigned long ADLER_MOD = 65521; + unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; + unsigned long blocklen, i; + + blocklen = buflen % 5552; + while (buflen) { + for (i=0; i + 7 < blocklen; i += 8) { + s1 += buffer[0], s2 += s1; + s1 += buffer[1], s2 += s1; + s1 += buffer[2], s2 += s1; + s1 += buffer[3], s2 += s1; + s1 += buffer[4], s2 += s1; + s1 += buffer[5], s2 += s1; + s1 += buffer[6], s2 += s1; + s1 += buffer[7], s2 += s1; + + buffer += 8; + } + + for (; i < blocklen; ++i) + s1 += *buffer++, s2 += s1; + + s1 %= ADLER_MOD, s2 %= ADLER_MOD; + buflen -= blocklen; + blocklen = 5552; + } + return (unsigned int)(s2 << 16) + (unsigned int)s1; +} + +static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length) +{ + unsigned int olen; + if (stb__in4(0) != 0x57bC0000) return 0; + if (stb__in4(4) != 0) return 0; // error! stream is > 4GB + olen = stb_decompress_length(i); + stb__barrier2 = i; + stb__barrier3 = i+length; + stb__barrier = output + olen; + stb__barrier4 = output; + i += 16; + + stb__dout = output; + for (;;) { + unsigned char *old_i = i; + i = stb_decompress_token(i); + if (i == old_i) { + if (*i == 0x05 && i[1] == 0xfa) { + IM_ASSERT(stb__dout == output + olen); + if (stb__dout != output + olen) return 0; + if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) + return 0; + return olen; + } else { + IM_ASSERT(0); /* NOTREACHED */ + return 0; + } + } + IM_ASSERT(stb__dout <= output + olen); + if (stb__dout > output + olen) + return 0; + } +} + +//----------------------------------------------------------------------------- +// ProggyClean.ttf +// Copyright (c) 2004, 2005 Tristan Grimmer +// MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) +// Download and more information at http://upperbounds.net +//----------------------------------------------------------------------------- +// File: 'ProggyClean.ttf' (41208 bytes) +// Exported using binary_to_compressed_c.cpp +//----------------------------------------------------------------------------- +static const char proggy_clean_ttf_compressed_data_base85[11980+1] = + "7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/" + "2*>]b(MC;$jPfY.;h^`IWM9<Lh2TlS+f-s$o6Q<BWH`YiU.xfLq$N;$0iR/GX:U(jcW2p/W*q?-qmnUCI;jHSAiFWM.R*kU@C=GH?a9wp8f$e.-4^Qg1)Q-GL(lf(r/7GrRgwV%MS=C#" + "`8ND>Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1<q-UE31#^-V'8IRUo7Qf./L>=Ke$$'5F%)]0^#0X@U.a<r:QLtFsLcL6##lOj)#.Y5<-R&KgLwqJfLgN&;Q?gI^#DY2uL" + "i@^rMl9t=cWq6##weg>$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;-<nLENhvx>-VsM.M0rJfLH2eTM`*oJMHRC`N" + "kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`�j@'DbG&#^$PG.Ll+DNa<XCMKEV*N)LN/N" + "*b=%Q6pia-Xg8I$<MR&,VdJe$<(7G;Ckl'&hF;;$<_=X(b.RS%%)###MPBuuE1V:v&cXm#(&cV]`k9OhLMbn%s$G2,B$BfD3X*sp5#l,$R#]x_X1xKX%b5U*[r5iMfUo9U`N99hG)" + "tm+/Us9pG)XPu`<0s-)WTt(gCRxIg(%6sfh=ktMKn3j)<6<b5Sk_/0(^]AaN#(p/L>&VZ>1i%h1S9u5o@YaaW$e+b<TWFn/Z:Oh(Cx2$lNEoN^e)#CFY@@I;BOQ*sRwZtZxRcU7uW6CX" + "ow0i(?$Q[cjOd[P4d)]>ROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc." + "x]Ip.PH^'/aqUO/$1WxLoW0[iLA<QT;5HKD+@qQ'NQ(3_PLhE48R.qAPSwQ0/WK?Z,[x?-J;jQTWA0X@KJ(_Y8N-:/M74:/-ZpKrUss?d#dZq]DAbkU*JqkL+nwX@@47`5>w=4h(9.`G" + "CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?G<Nald$qs]@]L<J7bR*>gv:[7MI2k).'2($5FNP&EQ(,)" + "U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#" + "'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM" + "_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0<q-]L_?^)1vw'.,MRsqVr.L;aN&#/EgJ)PBc[-f>+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu" + "Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/" + "/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[K<L" + "%a2E-grWVM3@2=-k22tL]4$##6We'8UJCKE[d_=%wI;'6X-GsLX4j^SgJ$##R*w,vP3wK#iiW&#*h^D&R?jp7+/u&#(AP##XU8c$fSYW-J95_-Dp[g9wcO&#M-h1OcJlc-*vpw0xUX&#" + "OQFKNX@QI'IoPp7nb,QU//MQ&ZDkKP)X<WSVL(68uVl&#c'[0#(s1X&xm$Y%B7*K:eDA323j998GXbA#pwMs-jgD$9QISB-A_(aN4xoFM^@C58D0+Q+q3n0#3U1InDjF682-SjMXJK)(" + "h$hxua_K]ul92%'BOU&#BRRh-slg8KDlr:%L71Ka:.A;%YULjDPmL<LYs8i#XwJOYaKPKc1h:'9Ke,g)b),78=I39B;xiY$bgGw-&.Zi9InXDuYa%G*f2Bq7mn9^#p1vv%#(Wi-;/Z5h" + "o;#2:;%d	v68C5g?ntX0X)pT`;%pB3q7mgGN)3%(P8nTd5L7GeA-GL@+%J3u2:(Yf>et`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO" + "j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J<j$UpK<Q4a1]MupW^-" + "sj_$%[HK%'F####QRZJ::Y3EGl4'@%FkiAOg#p[##O`gukTfBHagL<LHw%q&OV0##F=6/:chIm0@eCP8X]:kFI%hl8hgO@RcBhS-@Qb$%+m=hPDLg*%K8ln(wcf3/'DW-$.lR?n[nCH-" + "eXOONTJlh:.RYF%3'p6sq:UIMA945&^HFS87@$EP2iG<-lCO$%c`uKGD3rC$x0BL8aFn--`ke%#HMP'vh1/R&O_J9'um,.<tx[@%wsJk&bUT2`0uMv7gg#qp/ij.L56'hl;.s5CUrxjO" + "M7-##.l+Au'A&O:-T72L]P`&=;ctp'XScX*rU.>-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%" + "LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$M<Jnq79VsJW/mWS*PUiq76;]/NM_>hLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]" + "%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et" + "Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$<M-SGZ':+Q_k+uvOSLiEo(<aD/K<CCc`'Lx>'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:" + "a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VB<HFF*qL(" + "$/V,;(kXZejWO`<[5?\?ewY(*9=%wDc;,u<'9t3W-(H1th3+G]ucQ]kLs7df($/*JL]@*t7Bu_G3_7mp7<iaQjO@.kLg;x3B0lqp7Hf,^Ze7-##@/c58Mo(3;knp0%)A7?-W+eI'o8)b<" + "nKnw'Ho8C=Y>pqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<<aG/1N$#FX$0V5Y6x'aErI3I$7x%E`v<-BY,)%-?Psf*l?%C3.mM(=/M0:JxG'?" + "7WhH%o'a<-80g0NBxoO(GH<dM]n.+%q@jH?f.UsJ2Ggs&4<-e47&Kl+f//9@`b+?.TeN_&B8Ss?v;^Trk;f#YvJkl&w$]>-+k?'(<S:68tq*WoDfZu';mM?8X[ma8W%*`-=;D.(nc7/;" + ")g:T1=^J$&BRV(-lTmNB6xqB[@0*o.erM*<SWF]u2=st-*(6v>^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M" + "D?@f&1'BW-)Ju<L25gl8uhVm1hL$##*8###'A3/LkKW+(^rWX?5W_8g)a(m&K8P>#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX(" + "P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs" + "bIu)'Z,*[>br5fX^:FPAWr-m2KgL<LUN098kTF&#lvo58=/vjDo;.;)Ka*hLR#/k=rKbxuV`>Q_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q" + "h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aeg<Z'<$#4H)6,>e0jT6'N#(q%.O=?2S]u*(m<-" + "V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i" + "sZ88+dKQ)W6>J%CL<KE>`.d*(B`-n8D9oK<Up]c$X$(,)M8Zt7/[rdkqTgl-0cuGMv'?>-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P	r+$%CE=68>K8r0=dSC%%(@p7" + ".m7jilQ02'0-VWAg<a/''3u.=4L$Y)6k/K:_[3=&jvL<L0C/2'v:^;-DIBW,B4E68:kZ;%?8(Q8BH=kO65BW?xSG&#@uU,DS*,?.+(o(#1vCS8#CHF>TlGW'b)Tq7VT9q^*^$$.:&N@@" + "$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*" + "hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u" + "@-W$U%VEQ/,,>>#)D<h#`)h0:<Q6909ua+&VU%n2:cG3FJ-%@Bj-DgLr`Hw&HAKjKjseK</xKT*)B,N9X3]krc12t'pgTV(Lv-tL[xg_%=M_q7a^x?7Ubd>#%8cY#YZ?=,`Wdxu/ae&#" + "w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$s<Eh#c&)q.MXI%#v9ROa5FZO%sF7q7Nwb&#ptUJ:aqJe$Sl68%.D###EC><?-aF&#RNQv>o8lKN%5/$(vdfq7+ebA#" + "u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(<c`Q8N)jEIF*+?P2a8g%)$q]o2aH8C&<SibC/q,(e:v;-b#6[$NtDZ84Je2KNvB#$P5?tQ3nt(0" + "d=j.LQf./Ll33+(;q3L-w=8dX$#WF&uIJ@-bfI>%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8" + "6e%B/:=>)N4xeW.*wft-;$'58-ESqr<b?UI(_%@[P46>#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#" + "b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjL<Lni;''X.`$#8+1GD" + ":k$YUWsbn8ogh6rxZ2Z9]%nd+>V#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#<NEdtg(n'=S1A(Q1/I&4([%dM`,Iu'1:_hL>SfD07&6D<fp8dHM7/g+" + "tlPN9J*rKaPct&?'uBCem^jn%9_K)<,C5K3s=5g&GmJb*[SYq7K;TRLGCsM-$$;S%:Y@r7AK0pprpL<Lrh,q7e/%KWK:50I^+m'vi`3?%Zp+<-d+$L-Sv:@.o19n$s0&39;kn;S%BSq*" + "$3WoJSCLweV[aZ'MQIjO<7;X-X;&+dMLvu#^UsGEC9WEc[X(wI7#2.(F0jV*eZf<-Qv3J-c+J5AlrB#$p(H68LvEA'q3n0#m,[`*8Ft)FcYgEud]CWfm68,(aLA$@EFTgLXoBq/UPlp7" + ":d[/;r_ix=:TF`S5H-b<LI&HY(K=h#)]Lk$K14lVfm:x$H<3^Ql<M`$OhapBnkup'D#L$Pb_`N*g]2e;X/Dtg,bsj&K#2[-:iYr'_wgH)NUIR8a1n#S?Yej'h8^58UbZd+^FKD*T@;6A" + "7aQC[K8d-(v6GI$x:T<&'Gp5Uf>@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-<aN((^7('#Z0wK#5GX@7" + "u][`*S^43933A4rl][`*O4CgLEl]v$1Q3AeF37dbXk,.)vj#x'd`;qgbQR%FW,2(?LO=s%Sc68%NP'##Aotl8x=BE#j1UD([3$M(]UI2LX3RpKN@;/#f'f/&_mt&F)XdF<9t4)Qa.*kT" + "LwQ'(TTB9.xH'>#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5<N?)NBS)QN*_I,?&)2'IM%L3I)X((e/dl2&8'<M" + ":^#M*Q+[T.Xri.LYS3v%fF`68h;b-X[/En'CR.q7E)p'/kle2HM,u;^%OKC-N+Ll%F9CF<Nf'^#t2L,;27W:0O@6##U6W7:$rJfLWHj$#)woqBefIZ.PK<b*t7ed;p*_m;4ExK#h@&]>" + "_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%" + "hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;" + "^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmL<LD)F^%[tC'8;+9E#C$g%#5Y>q9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:" + "+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3<n-&%H%b<FDj2M<hH=&Eh<2Len$b*aTX=-8QxN)k11IM1c^j%" + "9s<L<NFSo)B?+<-(GxsF,^-Eh@$4dXhN$+#rxK8'je'D7k`e;)2pYwPA'_p9&@^18ml1^[@g4t*[JOa*[=Qp7(qJ_oOL^('7fB&Hq-:sf,sNj8xq^>$U4O]GKx'm9)b@p7YsvK3w^YR-" + "CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*" + "hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdF<TddF<9Ah-6&9tWoDlh]&1SpGMq>Ti1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IX<N+T+0MlMBPQ*Vj>SsD<U4JHY" + "8kD2)2fU/M#$e.)T4,_=8hLim[&);?UkK'-x?'(:siIfL<$pFM`i<?%W(mGDHM%>iWP,##P`%/L<eXi:@Z9C.7o=@(pXdAO/NLQ8lPl+HPOQa8wD8=^GlPa8TKI1CjhsCTSLJM'/Wl>-" + "S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n<bhPmUkMw>%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL<LoNs'6,'85`" + "0?t/'_U59@]ddF<#LdF<eWdF<OuN/45rY<-L@&#+fm>69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdF<gR@2L=FNU-<b[(9c/ML3m;Z[$oF3g)GAWqpARc=<ROu7cL5l;-[A]%/" + "+fsd;l#SafT/f*W]0=O'$(Tb<[)*@e775R-:Yob%g*>l*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj" + "M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#<IGe;__.thjZl<%w(Wk2xmp4Q@I#I9,DF]u7-P=.-_:YJ]aS@V" + "?6*C()dOp7:WL,b&3Rg/.cmM9&r^>$(>.Z-I&J(Q0Hd5Q%7Co-b`-c<N(6r@ip+AurK<m86QIth*#v;-OBqi+L7wDE-Ir8K['m+DDSLwK&/.?-V%U_%3:qKNu$_b*B-kp7NaD'QdWQPK" + "Yq[@>P)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8<FfNkgg^oIbah*#8/Qt$F&:K*-(N/'+1vMB,u()-a.VUU*#[e%gAAO(S>WlA2);Sa" + ">gXm8YB`1d@K#n]76-a$U,mF<fX]idqd)<3,]J7JmW4`6]uks=4-72L(jEk+:bJ0M^q-8Dm_Z?0olP1C9Sa&H[d&c$ooQUj]Exd*3ZM@-WGW2%s',B-_M%>%Ul:#/'xoFM9QX-$.QN'>" + "[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B</R90;eZ]%Ncq;-Tl]#F>2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I" + "wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1<Vc52=u`3^o-n1'g4v58Hj&6_t7$##?M)c<$bgQ_'SY((-xkA#" + "Y(,p'H9rIVY-b,'%bCPF7.J<Up^,(dU1VY*5#WkTU>h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-u<Hp,3@e^9UB1J+ak9-TN/mhKPg+AJYd$" + "MlvAF_jCK*.O-^(63adMT->W%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)" + "i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo" + "1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P" + "iDDG)g,r%+?,$@?uou5tSe2aN_AQU*<h`e-GI7)?OK2A.d7_c)?wQ5AS@DL3r#7fSkgl6-++D:'A,uq7SvlB$pcpH'q3n0#_%dY#xCpr-l<F0NR@-##FEV6NTF6##$l84N1w?AO>'IAO" + "URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#" + ";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T<XoIB&hx=T1PcDaB&;HH+-AFr?(m9HZV)FKS8JCw;SD=6[^/DZUL`EUDf]GGlG&>" + "w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#<xU?#@.i?#D:%@#HF7@#LRI@#P_[@#Tkn@#Xw*A#]-=A#a9OA#" + "d<F&#*;G##.GY##2Sl##6`($#:l:$#>xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4" + "A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#" + "/QHC#3^ZC#7jmC#;v)D#?,<D#C8ND#GDaD#KPsD#O]/E#g1A5#KA*1#gC17#MGd;#8(02#L-d3#rWM4#Hga1#,<w0#T.j<#O#'2#CYN1#qa^:#_4m3#o@/=#eG8=#t8J5#`+78#4uI-#" + "m3B2#SB[8#Q0@8#i[*9#iOn8#1Nm;#^sN9#qh<9#:=x-#P;K2#$%X9#bC+.#Rg;<#mN=.#MTF.#RZO.#2?)4#Y#(/#[)1/#b;L/#dAU/#0Sv;#lY$0#n`-0#sf60#(F24#wrH0#%/e0#" + "TmD<#%JSMFove:CTBEXI:<eh2g)B,3h2^G3i;#d3jD>)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP" + "GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp" + "O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#"; + +static const char* GetDefaultCompressedFontDataTTFBase85() +{ + return proggy_clean_ttf_compressed_data_base85; +} diff --git a/src/imgui_impl_glfw.cpp b/src/imgui_impl_glfw.cpp index 0243d51..837125b 100644 --- a/src/imgui_impl_glfw.cpp +++ b/src/imgui_impl_glfw.cpp @@ -1,4 +1,13 @@ // ImGui GLFW binding with OpenGL +// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. + +// If your context is GL3/GL3 then prefer using the code in opengl3_example. +// You *might* use this code with a GL3/GL4 context but make sure you disable the programmable pipeline by calling "glUseProgram(0)" before ImGui::Render(). +// We cannot do that from GL2 code because the function doesn't exist. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). +// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui #include <imgui.h> @@ -6,7 +15,7 @@ // GLFW #include <GLFW/glfw3.h> -#ifdef _MSC_VER +#ifdef _WIN32 #undef APIENTRY #define GLFW_EXPOSE_NATIVE_WIN32 #define GLFW_EXPOSE_NATIVE_WGL @@ -23,14 +32,20 @@ static GLuint g_FontTexture = 0; // This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) // If text or lines are blurry when integrating ImGui in your engine: // - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) -static void ImGui_ImplGlfw_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) +void ImGui_ImplGlfw_RenderDrawLists(ImDrawData* draw_data) { - if (cmd_lists_count == 0) + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + ImGuiIO& io = ImGui::GetIO(); + int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); + int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); + if (fb_width == 0 || fb_height == 0) return; + draw_data->ScaleClipRects(io.DisplayFramebufferScale); // We are using the OpenGL fixed pipeline to make the example code simpler to read! - // A probable faster way to render would be to collate all vertices from all cmd_lists into a single vertex buffer. // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, vertex/texcoord/color pointers. + GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); @@ -43,42 +58,41 @@ static void ImGui_ImplGlfw_RenderDrawLists(ImDrawList** const cmd_lists, int cmd glEnable(GL_TEXTURE_2D); //glUseProgram(0); // You may want this if using this code in an OpenGL 3+ context - // Setup orthographic projection matrix - const float width = ImGui::GetIO().DisplaySize.x; - const float height = ImGui::GetIO().DisplaySize.y; + // Setup viewport, orthographic projection matrix + glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); - glOrtho(0.0f, width, height, 0.0f, -1.0f, +1.0f); + glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // Render command lists #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) - for (int n = 0; n < cmd_lists_count; n++) + for (int n = 0; n < draw_data->CmdListsCount; n++) { - const ImDrawList* cmd_list = cmd_lists[n]; - const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->vtx_buffer.front(); + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front(); + const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front(); glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, pos))); glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, uv))); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + OFFSETOF(ImDrawVert, col))); - int vtx_offset = 0; - for (size_t cmd_i = 0; cmd_i < cmd_list->commands.size(); cmd_i++) + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); cmd_i++) { - const ImDrawCmd* pcmd = &cmd_list->commands[cmd_i]; - if (pcmd->user_callback) + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) { - pcmd->user_callback(cmd_list, pcmd); + pcmd->UserCallback(cmd_list, pcmd); } else { - glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->texture_id); - glScissor((int)pcmd->clip_rect.x, (int)(height - pcmd->clip_rect.w), (int)(pcmd->clip_rect.z - pcmd->clip_rect.x), (int)(pcmd->clip_rect.w - pcmd->clip_rect.y)); - glDrawArrays(GL_TRIANGLES, vtx_offset, pcmd->vtx_count); + glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); + glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); + glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer); } - vtx_offset += pcmd->vtx_count; + idx_buffer += pcmd->ElemCount; } } #undef OFFSETOF @@ -87,12 +101,13 @@ static void ImGui_ImplGlfw_RenderDrawLists(ImDrawList** const cmd_lists, int cmd glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); - glBindTexture(GL_TEXTURE_2D, 0); + glBindTexture(GL_TEXTURE_2D, (GLuint)last_texture); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glPopAttrib(); + glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); } static const char* ImGui_ImplGlfw_GetClipboardText() @@ -123,9 +138,12 @@ void ImGui_ImplGlFw_KeyCallback(GLFWwindow*, int key, int, int action, int mods) io.KeysDown[key] = true; if (action == GLFW_RELEASE) io.KeysDown[key] = false; - io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0; - io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0; - io.KeyAlt = (mods & GLFW_MOD_ALT) != 0; + + (void)mods; // Modifiers are not reliable across systems + io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL]; + io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT]; + io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT]; + io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER]; } void ImGui_ImplGlfw_CharCallback(GLFWwindow*, unsigned int c) @@ -137,14 +155,15 @@ void ImGui_ImplGlfw_CharCallback(GLFWwindow*, unsigned int c) bool ImGui_ImplGlfw_CreateDeviceObjects() { + // Build texture atlas ImGuiIO& io = ImGui::GetIO(); - - // Build texture unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsAlpha8(&pixels, &width, &height); - - // Create texture + + // Upload texture to graphics system + GLint last_texture; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); glGenTextures(1, &g_FontTexture); glBindTexture(GL_TEXTURE_2D, g_FontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); @@ -154,6 +173,9 @@ bool ImGui_ImplGlfw_CreateDeviceObjects() // Store our identifier io.Fonts->TexID = (void *)(intptr_t)g_FontTexture; + // Restore state + glBindTexture(GL_TEXTURE_2D, last_texture); + return true; } @@ -172,11 +194,13 @@ bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks) g_Window = window; ImGuiIO& io = ImGui::GetIO(); - io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. + io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; + io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; + io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; @@ -190,10 +214,10 @@ bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks) io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; - io.RenderDrawListsFn = ImGui_ImplGlfw_RenderDrawLists; + io.RenderDrawListsFn = ImGui_ImplGlfw_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer. io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText; io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText; -#ifdef _MSC_VER +#ifdef _WIN32 io.ImeWindowHandle = glfwGetWin32Window(g_Window); #endif @@ -226,7 +250,8 @@ void ImGui_ImplGlfw_NewFrame() int display_w, display_h; glfwGetWindowSize(g_Window, &w, &h); glfwGetFramebufferSize(g_Window, &display_w, &display_h); - io.DisplaySize = ImVec2((float)display_w, (float)display_h); + io.DisplaySize = ImVec2((float)w, (float)h); + io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); // Setup time step double current_time = glfwGetTime(); @@ -237,17 +262,15 @@ void ImGui_ImplGlfw_NewFrame() // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents()) if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED)) { - double mouse_x, mouse_y; - glfwGetCursorPos(g_Window, &mouse_x, &mouse_y); - mouse_x *= (float)display_w / w; // Convert mouse coordinates to pixels - mouse_y *= (float)display_h / h; - io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position, in pixels (set to -1,-1 if no mouse / on another screen, etc.) + double mouse_x, mouse_y; + glfwGetCursorPos(g_Window, &mouse_x, &mouse_y); + io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.) } else { - io.MousePos = ImVec2(-1,-1); + io.MousePos = ImVec2(-1,-1); } - + for (int i = 0; i < 3; i++) { io.MouseDown[i] = g_MousePressed[i] || glfwGetMouseButton(g_Window, i) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. @@ -257,7 +280,7 @@ void ImGui_ImplGlfw_NewFrame() io.MouseWheel = g_MouseWheel; g_MouseWheel = 0.0f; - // Hide/show hardware mouse cursor + // Hide OS mouse cursor if ImGui is drawing it glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL); // Start the frame diff --git a/src/imgui_impl_glfw.h b/src/imgui_impl_glfw.h deleted file mode 100644 index 502d837..0000000 --- a/src/imgui_impl_glfw.h +++ /dev/null @@ -1,20 +0,0 @@ -// ImGui GLFW binding with OpenGL -// https://github.com/ocornut/imgui - -struct GLFWwindow; - -bool ImGui_ImplGlfw_Init(GLFWwindow* window, bool install_callbacks); -void ImGui_ImplGlfw_Shutdown(); -void ImGui_ImplGlfw_NewFrame(); - -// Use if you want to reset your rendering device without losing ImGui state. -void ImGui_ImplGlfw_InvalidateDeviceObjects(); -bool ImGui_ImplGlfw_CreateDeviceObjects(); - -// GLFW callbacks (installed by default if you enable 'install_callbacks' during initialization) -// Provided here if you want to chain callbacks. -// You can also handle inputs yourself and use those as a reference. -void ImGui_ImplGlfw_MouseButtonCallback(GLFWwindow* window, int button, int action, int mods); -void ImGui_ImplGlfw_ScrollCallback(GLFWwindow* window, double xoffset, double yoffset); -void ImGui_ImplGlFw_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); -void ImGui_ImplGlfw_CharCallback(GLFWwindow* window, unsigned int c); diff --git a/src/imgui_impl_glfw_gl3.cpp b/src/imgui_impl_glfw_gl3.cpp new file mode 100644 index 0000000..868cf98 --- /dev/null +++ b/src/imgui_impl_glfw_gl3.cpp @@ -0,0 +1,400 @@ +// ImGui GLFW binding with OpenGL3 + shaders +// In this binding, ImTextureID is used to store an OpenGL 'GLuint' texture identifier. Read the FAQ about ImTextureID in imgui.cpp. + +// You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. +// If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). +// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. +// https://github.com/ocornut/imgui + +#include <imgui.h> +#include "imgui_impl_glfw_gl3.h" + +// GL3W/GLFW +#include <GL/glew.h> +#include <GLFW/glfw3.h> +#ifdef _WIN32 +#undef APIENTRY +#define GLFW_EXPOSE_NATIVE_WIN32 +#define GLFW_EXPOSE_NATIVE_WGL +#include <GLFW/glfw3native.h> +#endif + +// Data +static GLFWwindow* g_Window = NULL; +static double g_Time = 0.0f; +static bool g_MousePressed[3] = { false, false, false }; +static float g_MouseWheel = 0.0f; +static GLuint g_FontTexture = 0; +static int g_ShaderHandle = 0, g_VertHandle = 0, g_FragHandle = 0; +static int g_AttribLocationTex = 0, g_AttribLocationProjMtx = 0; +static int g_AttribLocationPosition = 0, g_AttribLocationUV = 0, g_AttribLocationColor = 0; +static unsigned int g_VboHandle = 0, g_VaoHandle = 0, g_ElementsHandle = 0; + +// This is the main rendering function that you have to implement and provide to ImGui (via setting up 'RenderDrawListsFn' in the ImGuiIO structure) +// If text or lines are blurry when integrating ImGui in your engine: +// - in your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) +void ImGui_ImplGlfwGL3_RenderDrawLists(ImDrawData* draw_data) +{ + // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) + ImGuiIO& io = ImGui::GetIO(); + int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x); + int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y); + if (fb_width == 0 || fb_height == 0) + return; + draw_data->ScaleClipRects(io.DisplayFramebufferScale); + + // Backup GL state + GLint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, &last_program); + GLint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + GLint last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, &last_active_texture); + GLint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); + GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer); + GLint last_vertex_array; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); + GLint last_blend_src; glGetIntegerv(GL_BLEND_SRC, &last_blend_src); + GLint last_blend_dst; glGetIntegerv(GL_BLEND_DST, &last_blend_dst); + GLint last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, &last_blend_equation_rgb); + GLint last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, &last_blend_equation_alpha); + GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport); + GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box); + GLboolean last_enable_blend = glIsEnabled(GL_BLEND); + GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE); + GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST); + GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST); + + // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled + glEnable(GL_BLEND); + glBlendEquation(GL_FUNC_ADD); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + glEnable(GL_SCISSOR_TEST); + glActiveTexture(GL_TEXTURE0); + + // Setup viewport, orthographic projection matrix + glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height); + const float ortho_projection[4][4] = + { + { 2.0f/io.DisplaySize.x, 0.0f, 0.0f, 0.0f }, + { 0.0f, 2.0f/-io.DisplaySize.y, 0.0f, 0.0f }, + { 0.0f, 0.0f, -1.0f, 0.0f }, + {-1.0f, 1.0f, 0.0f, 1.0f }, + }; + glUseProgram(g_ShaderHandle); + glUniform1i(g_AttribLocationTex, 0); + glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); + glBindVertexArray(g_VaoHandle); + + for (int n = 0; n < draw_data->CmdListsCount; n++) + { + const ImDrawList* cmd_list = draw_data->CmdLists[n]; + const ImDrawIdx* idx_buffer_offset = 0; + + glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); + glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)cmd_list->VtxBuffer.Size * sizeof(ImDrawVert), (GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx), (GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW); + + for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) + { + const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; + if (pcmd->UserCallback) + { + pcmd->UserCallback(cmd_list, pcmd); + } + else + { + glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->TextureId); + glScissor((int)pcmd->ClipRect.x, (int)(fb_height - pcmd->ClipRect.w), (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y)); + glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); + } + idx_buffer_offset += pcmd->ElemCount; + } + } + + // Restore modified GL state + glUseProgram(last_program); + glActiveTexture(last_active_texture); + glBindTexture(GL_TEXTURE_2D, last_texture); + glBindVertexArray(last_vertex_array); + glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer); + glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha); + glBlendFunc(last_blend_src, last_blend_dst); + if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND); + if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE); + if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST); + if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST); + glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]); + glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]); +} + +static const char* ImGui_ImplGlfwGL3_GetClipboardText() +{ + return glfwGetClipboardString(g_Window); +} + +static void ImGui_ImplGlfwGL3_SetClipboardText(const char* text) +{ + glfwSetClipboardString(g_Window, text); +} + +void ImGui_ImplGlfwGL3_MouseButtonCallback(GLFWwindow*, int button, int action, int /*mods*/) +{ + if (action == GLFW_PRESS && button >= 0 && button < 3) + g_MousePressed[button] = true; +} + +void ImGui_ImplGlfwGL3_ScrollCallback(GLFWwindow*, double /*xoffset*/, double yoffset) +{ + g_MouseWheel += (float)yoffset; // Use fractional mouse wheel, 1.0 unit 5 lines. +} + +void ImGui_ImplGlfwGL3_KeyCallback(GLFWwindow*, int key, int, int action, int mods) +{ + ImGuiIO& io = ImGui::GetIO(); + if (action == GLFW_PRESS) + io.KeysDown[key] = true; + if (action == GLFW_RELEASE) + io.KeysDown[key] = false; + + (void)mods; // Modifiers are not reliable across systems + io.KeyCtrl = io.KeysDown[GLFW_KEY_LEFT_CONTROL] || io.KeysDown[GLFW_KEY_RIGHT_CONTROL]; + io.KeyShift = io.KeysDown[GLFW_KEY_LEFT_SHIFT] || io.KeysDown[GLFW_KEY_RIGHT_SHIFT]; + io.KeyAlt = io.KeysDown[GLFW_KEY_LEFT_ALT] || io.KeysDown[GLFW_KEY_RIGHT_ALT]; + io.KeySuper = io.KeysDown[GLFW_KEY_LEFT_SUPER] || io.KeysDown[GLFW_KEY_RIGHT_SUPER]; +} + +void ImGui_ImplGlfwGL3_CharCallback(GLFWwindow*, unsigned int c) +{ + ImGuiIO& io = ImGui::GetIO(); + if (c > 0 && c < 0x10000) + io.AddInputCharacter((unsigned short)c); +} + +bool ImGui_ImplGlfwGL3_CreateFontsTexture() +{ + // Build texture atlas + ImGuiIO& io = ImGui::GetIO(); + unsigned char* pixels; + int width, height; + io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bits (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. + + // Upload texture to graphics system + GLint last_texture; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + glGenTextures(1, &g_FontTexture); + glBindTexture(GL_TEXTURE_2D, g_FontTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + + // Store our identifier + io.Fonts->TexID = (void *)(intptr_t)g_FontTexture; + + // Restore state + glBindTexture(GL_TEXTURE_2D, last_texture); + + return true; +} + +bool ImGui_ImplGlfwGL3_CreateDeviceObjects() +{ + // Backup GL state + GLint last_texture, last_array_buffer, last_vertex_array; + glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture); + glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer); + glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array); + + const GLchar *vertex_shader = + "#version 330\n" + "uniform mat4 ProjMtx;\n" + "in vec2 Position;\n" + "in vec2 UV;\n" + "in vec4 Color;\n" + "out vec2 Frag_UV;\n" + "out vec4 Frag_Color;\n" + "void main()\n" + "{\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" + "}\n"; + + const GLchar* fragment_shader = + "#version 330\n" + "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\n" + "in vec4 Frag_Color;\n" + "out vec4 Out_Color;\n" + "void main()\n" + "{\n" + " Out_Color = Frag_Color * texture( Texture, Frag_UV.st);\n" + "}\n"; + + g_ShaderHandle = glCreateProgram(); + g_VertHandle = glCreateShader(GL_VERTEX_SHADER); + g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(g_VertHandle, 1, &vertex_shader, 0); + glShaderSource(g_FragHandle, 1, &fragment_shader, 0); + glCompileShader(g_VertHandle); + glCompileShader(g_FragHandle); + glAttachShader(g_ShaderHandle, g_VertHandle); + glAttachShader(g_ShaderHandle, g_FragHandle); + glLinkProgram(g_ShaderHandle); + + g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); + g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); + g_AttribLocationPosition = glGetAttribLocation(g_ShaderHandle, "Position"); + g_AttribLocationUV = glGetAttribLocation(g_ShaderHandle, "UV"); + g_AttribLocationColor = glGetAttribLocation(g_ShaderHandle, "Color"); + + glGenBuffers(1, &g_VboHandle); + glGenBuffers(1, &g_ElementsHandle); + + glGenVertexArrays(1, &g_VaoHandle); + glBindVertexArray(g_VaoHandle); + glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); + glEnableVertexAttribArray(g_AttribLocationPosition); + glEnableVertexAttribArray(g_AttribLocationUV); + glEnableVertexAttribArray(g_AttribLocationColor); + +#define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT)) + glVertexAttribPointer(g_AttribLocationPosition, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos)); + glVertexAttribPointer(g_AttribLocationUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv)); + glVertexAttribPointer(g_AttribLocationColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col)); +#undef OFFSETOF + + ImGui_ImplGlfwGL3_CreateFontsTexture(); + + // Restore modified GL state + glBindTexture(GL_TEXTURE_2D, last_texture); + glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer); + glBindVertexArray(last_vertex_array); + + return true; +} + +void ImGui_ImplGlfwGL3_InvalidateDeviceObjects() +{ + if (g_VaoHandle) glDeleteVertexArrays(1, &g_VaoHandle); + if (g_VboHandle) glDeleteBuffers(1, &g_VboHandle); + if (g_ElementsHandle) glDeleteBuffers(1, &g_ElementsHandle); + g_VaoHandle = g_VboHandle = g_ElementsHandle = 0; + + if (g_ShaderHandle && g_VertHandle) glDetachShader(g_ShaderHandle, g_VertHandle); + if (g_VertHandle) glDeleteShader(g_VertHandle); + g_VertHandle = 0; + + if (g_ShaderHandle && g_FragHandle) glDetachShader(g_ShaderHandle, g_FragHandle); + if (g_FragHandle) glDeleteShader(g_FragHandle); + g_FragHandle = 0; + + if (g_ShaderHandle) glDeleteProgram(g_ShaderHandle); + g_ShaderHandle = 0; + + if (g_FontTexture) + { + glDeleteTextures(1, &g_FontTexture); + ImGui::GetIO().Fonts->TexID = 0; + g_FontTexture = 0; + } +} + +bool ImGui_ImplGlfwGL3_Init(GLFWwindow* window, bool install_callbacks) +{ + g_Window = window; + + ImGuiIO& io = ImGui::GetIO(); + io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array. + io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; + io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; + io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; + io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; + io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; + io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; + io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; + io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; + io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; + io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; + io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; + io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; + io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; + io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; + io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; + io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; + io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; + io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; + + io.RenderDrawListsFn = ImGui_ImplGlfwGL3_RenderDrawLists; // Alternatively you can set this to NULL and call ImGui::GetDrawData() after ImGui::Render() to get the same ImDrawData pointer. + io.SetClipboardTextFn = ImGui_ImplGlfwGL3_SetClipboardText; + io.GetClipboardTextFn = ImGui_ImplGlfwGL3_GetClipboardText; +#ifdef _WIN32 + io.ImeWindowHandle = glfwGetWin32Window(g_Window); +#endif + + if (install_callbacks) + { + glfwSetMouseButtonCallback(window, ImGui_ImplGlfwGL3_MouseButtonCallback); + glfwSetScrollCallback(window, ImGui_ImplGlfwGL3_ScrollCallback); + glfwSetKeyCallback(window, ImGui_ImplGlfwGL3_KeyCallback); + glfwSetCharCallback(window, ImGui_ImplGlfwGL3_CharCallback); + } + + return true; +} + +void ImGui_ImplGlfwGL3_Shutdown() +{ + ImGui_ImplGlfwGL3_InvalidateDeviceObjects(); + ImGui::Shutdown(); +} + +void ImGui_ImplGlfwGL3_NewFrame() +{ + if (!g_FontTexture) + ImGui_ImplGlfwGL3_CreateDeviceObjects(); + + ImGuiIO& io = ImGui::GetIO(); + + // Setup display size (every frame to accommodate for window resizing) + int w, h; + int display_w, display_h; + glfwGetWindowSize(g_Window, &w, &h); + glfwGetFramebufferSize(g_Window, &display_w, &display_h); + io.DisplaySize = ImVec2((float)w, (float)h); + io.DisplayFramebufferScale = ImVec2(w > 0 ? ((float)display_w / w) : 0, h > 0 ? ((float)display_h / h) : 0); + + // Setup time step + double current_time = glfwGetTime(); + io.DeltaTime = g_Time > 0.0 ? (float)(current_time - g_Time) : (float)(1.0f/60.0f); + g_Time = current_time; + + // Setup inputs + // (we already got mouse wheel, keyboard keys & characters from glfw callbacks polled in glfwPollEvents()) + if (glfwGetWindowAttrib(g_Window, GLFW_FOCUSED)) + { + double mouse_x, mouse_y; + glfwGetCursorPos(g_Window, &mouse_x, &mouse_y); + io.MousePos = ImVec2((float)mouse_x, (float)mouse_y); // Mouse position in screen coordinates (set to -1,-1 if no mouse / on another screen, etc.) + } + else + { + io.MousePos = ImVec2(-1,-1); + } + + for (int i = 0; i < 3; i++) + { + io.MouseDown[i] = g_MousePressed[i] || glfwGetMouseButton(g_Window, i) != 0; // If a mouse press event came, always pass it as "mouse held this frame", so we don't miss click-release events that are shorter than 1 frame. + g_MousePressed[i] = false; + } + + io.MouseWheel = g_MouseWheel; + g_MouseWheel = 0.0f; + + // Hide OS mouse cursor if ImGui is drawing it + glfwSetInputMode(g_Window, GLFW_CURSOR, io.MouseDrawCursor ? GLFW_CURSOR_HIDDEN : GLFW_CURSOR_NORMAL); + + // Start the frame + ImGui::NewFrame(); +} diff --git a/src/mpc_utils.cpp b/src/mpc_utils.cpp new file mode 100644 index 0000000..8f11fbf --- /dev/null +++ b/src/mpc_utils.cpp @@ -0,0 +1,241 @@ +// Interactive MPC helper functions + +#include "mpc_utils.h" +//#include <LinAlg/LapackWrapperExtra.h> +//#include <SymEigsSolver.h> + +#define PI 3.14159265359 +// We are going to calculate the eigenvalues of M + +using namespace arma; +/* +void symEigs( arma::vec* Dv, arma::mat* V, arma::mat A, int numEigs, int convFactor) +{ + // Construct matrix operation object using the wrapper class DenseGenMatProd + DenseGenMatProd<double> op(A); + // Construct eigen solver object, requesting the largest three eigenvalues + SymEigsSolver< double, LARGEST_ALGE, DenseGenMatProd<double> > eigs(&op, numEigs, convFactor); + + eigs.init(); + int nconv = eigs.compute(); + + if(nconv > 0) + { + *Dv = eigs.eigenvalues(); + *V = eigs.eigenvectors(nconv); + } + else + { + *Dv = arma::zeros(2); + *V = arma::eye(2,2); + } +} +*/ + +double factorials[15] = +{ + 1, + 1, + 2, + 6, + 24, + 120, + 720, + 5040, + 40320, + 362880, + 3628800, + 39916800, + 479001600, + 6227020800, + 87178291200 +}; + + +static mat transformSigma( const mat& m, const mat& Sigma) +{ + mat V; + vec d; + eig_sym(d, V, Sigma); + mat D = diagmat(d); + V = m*V; + return V*D*inv(V); +} + +arma::mat rot2d( double theta, bool affine ) +{ + int d = affine?3:2; + arma::mat m = arma::eye(d,d); + + double ct = cos(theta); + double st = sin(theta); + + m(0,0) = ct; m(0,1) = -st; + m(1,0) = st; m(1,1) = ct; + + return m; +} + +static mat makeSigma( float rot, vec scale ) +{ + mat Q = rot2d(rot, false); + mat Lambda = diagmat(scale%scale); + return Q * Lambda * inv(Q); +} + +/// Inits the system matrices with a chain of integrators +void makeIntegratorChain(arma::mat* A, arma::mat* B, int order) +{ + *A = zeros(order, order); + A->submat(0, 1, order-2, order-1) + = eye(order-1, order-1); + *B = join_vert(zeros(order-1,1), + ones(1,1)); +} + +void discretizeSystem(arma::mat* _A, arma::mat* _B, arma::mat A, arma::mat B, double dt, bool zoh ) +{ + if(zoh) + { + // matrix eponential trick + // From Linear Systems: A State Variable Approach with Numerical Implementation pg 215 + // adapted from scipy impl + + mat EM = join_horiz(A, B); + mat zero = join_horiz(zeros(B.n_cols, B.n_rows), + zeros(B.n_cols, B.n_cols)); + EM = join_vert(EM, zero); + mat M = expmat(EM * dt); + *_A = M.submat(span(0, A.n_rows-1), span(0, A.n_cols-1)); + *_B = M.submat(span(0, B.n_rows-1), span(A.n_cols, M.n_cols-1)); + } + else // euler + { + *_A = eye(A.n_rows, A.n_cols) + A*dt; + *_B = B * dt; + } +} + +/// Creates random gaussians as targets for LQR constraints +void randomCovariances(arma::cube* Sigma, const arma::mat& Mu, const arma::vec& covscale, bool semiTied, double theta, double minRnd ) +{ + int m = Mu.n_cols; + + *Sigma = zeros(2,2,m); + vec s; + + for( int i = 0; i < m; i++ ) + { + vec s = (minRnd+(randu(2)*(1.-minRnd))) % covscale; + if(!semiTied) + theta = -PI + arma::randu()*2.*PI; + mat sigm = makeSigma(theta, s); + Sigma->slice(i) = makeSigma(theta, s); + } +} + +double SHM_r(double d, double period, int order) +{ + double omega = (2. * PI) / period; + return 1. / pow(d * pow(omega,order), 2); +} + +arma::ivec stepwiseIndices(int m, int n) +{ + return arma::conv_to<arma::ivec>::from( + arma::linspace(0, (float)m-0.1, n) ); +} + +arma::ivec viaPointIndices(int m, int n) +{ + float a = 0.; + float b = n-1; + + ivec inds = zeros<ivec>(m); + for( int i = 0; i < m; i++ ) + inds(i) = (int)(a + i*(b-a)/(m-1)); + return inds; +} + +void stepwiseReference( arma::mat* MuQ, arma::mat* Q, const mat& Mu, const cube& Sigma, int n, int order, int dim, double endWeight ) +{ + int m = Mu.n_cols; + int cDim = order*dim; + int muDim = Mu.n_rows; + + // equally distributed optimal states + // Could try something along the lines of Fitts here based on covariance. + arma::ivec qList = stepwiseIndices(m, n); + + // precision matrices + mat Lambda = zeros(muDim, m*muDim); + for( int i = 0; i < m; i++ ) + Lambda.cols(i*muDim, muDim*(i+1)-1) = inv(Sigma.slice(i)); + + *Q = zeros(cDim*n, cDim*n); // Precision matrix + *MuQ = zeros(cDim, n); // Mean vector + + for( int i = 0; i < qList.n_rows; i++ ) + { + // Precision matrix based on state sequence + Q->submat(i*cDim, + i*cDim, + i*cDim+muDim-1, + i*cDim+muDim-1) = + Lambda.cols(qList[i]*muDim, (qList[i]+1)*muDim-1); + + // Mean vector + MuQ->submat(span(0,muDim-1), span(i,i)) = Mu.col(qList[i]); + } + + if(endWeight > 0.0) + { + // Set last value for Q to enforce 0 end condition + int ind = qList.n_rows-1; + for( int i = 2; i < cDim; i++ ) + Q->operator()(ind*cDim+i, ind*cDim+i) = endWeight; + } +} + +void viaPointReference( arma::mat* MuQ, arma::mat* Q, const mat& Mu, const cube& Sigma, int n, int order, int dim, double endWeight ) +{ + int m = Mu.n_cols; + int cDim = order*dim; + int muDim = Mu.n_rows; + + // equally distributed optimal states + // Could try something along the lines of Fitts here based on covariance. + arma::ivec qList = stepwiseIndices(m, n); + + // precision matrices + mat Lambda = zeros(muDim, m*muDim); + for( int i = 0; i < m; i++ ) + Lambda.cols(i*muDim, muDim*(i+1)-1) = inv(Sigma.slice(i)); + + *Q = zeros(cDim*n, cDim*n); // Precision matrix + *MuQ = zeros(cDim, n); // Mean vector + + ivec vI = viaPointIndices(m, n); + for( int i = 0; i < vI.n_rows; i++ ) + { + int t = vI[i]; + Q->submat(t*cDim, + t*cDim, + t*cDim+muDim-1, + t*cDim+muDim-1) + = + Lambda.cols(i*muDim, (i+1)*muDim-1); + + MuQ->submat(span(0,muDim-1), span(t,t)) = Mu.col(i); + } + + + if(endWeight > 0.0) + { + // Set last value for Q to enforce 0 end condition + int ind = n-1; + for( int i = 2; i < cDim; i++ ) + Q->operator()(ind*cDim+i, ind*cDim+i) = endWeight; + + } +} -- GitLab